diff --git "a/5368.jsonl" "b/5368.jsonl" new file mode 100644--- /dev/null +++ "b/5368.jsonl" @@ -0,0 +1,710 @@ +{"seq_id":"518844106","text":"##########################################################################\n#\n# Copyright (c) 2013, Image Engine Design Inc. All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are\n# met:\n#\n# * Redistributions of source code must retain the above\n# copyright notice, this list of conditions and the following\n# disclaimer.\n#\n# * Redistributions in binary form must reproduce the above\n# copyright notice, this list of conditions and the following\n# disclaimer in the documentation and/or other materials provided with\n# the distribution.\n#\n# * Neither the name of Image Engine Design nor the names of\n# any other contributors to this software may be used to endorse or\n# promote products derived from this software without specific prior\n# written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS\n# IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,\n# THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR\n# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n#\n##########################################################################\n\nimport unittest\n\nimport IECore\nimport Gaffer\nimport GafferImage\nimport os\n\nclass SamplerTest( unittest.TestCase ) :\n\n\tfileName = os.path.expandvars( \"$GAFFER_ROOT/python/GafferImageTest/images/checker.exr\" )\n\n\tdef testConstructors( self ) :\n\n\t\ts = Gaffer.ScriptNode()\n\t\tr = GafferImage.ImageReader()\n\t\ts.addChild( r )\n\n\t\tr[\"fileName\"].setValue( self.fileName )\n\n\t\tbounds = r[\"out\"][\"dataWindow\"].getValue();\n\n\t\t# Check that the default sampler is the same as a sampler with the default filter.\n\t\tdefaultSampler = GafferImage.Sampler( r[\"out\"], \"R\", bounds, GafferImage.Sampler.BoundingMode.Black )\n\n\t\tdefaultFilter = GafferImage.Filter.create( GafferImage.Filter.defaultFilter() )\n\t\tsampler = GafferImage.Sampler( r[\"out\"], \"R\", bounds, defaultFilter, GafferImage.Sampler.BoundingMode.Black )\n\n\t\tc = Gaffer.Context()\n\t\tc[\"image:channelName\"] = 'R'\n\t\tc[\"image:tileOrigin\"] = IECore.V2i( 0 )\n\t\twith c:\n\t\t\tself.assertEqual( sampler.sample( bounds.min.x+.5, bounds.min.y+.5 ), defaultSampler.sample( bounds.min.x+.5, bounds.min.y+.5 ) )\n\n\n\tdef testOutOfBoundsSampleModeBlack( self ) :\n\n\t\ts = Gaffer.ScriptNode()\n\t\tr = GafferImage.ImageReader()\n\t\tr[\"fileName\"].setValue( self.fileName )\n\t\ts.addChild( r )\n\n\t\tc = Gaffer.Context()\n\t\tc[\"image:channelName\"] = 'R'\n\t\tc[\"image:tileOrigin\"] = IECore.V2i( 0 )\n\n\t\tbounds = r[\"out\"][\"dataWindow\"].getValue();\n\n\t\ttestCases = [\n\t\t\t( bounds.min.x-1, bounds.min.y ),\n\t\t\t( bounds.min.x, bounds.min.y-1 ),\n\t\t\t( bounds.max.x-1, bounds.max.y ),\n\t\t\t( bounds.max.x, bounds.max.y-1 ),\n\t\t\t( bounds.min.x-1, bounds.max.y-1 ),\n\t\t\t( bounds.min.x, bounds.max.y ),\n\t\t\t( bounds.max.x, bounds.min.y ),\n\t\t\t( bounds.max.x-1, bounds.min.y-1 )\n\t\t]\n\n\t\tself.assertTrue( \"Box\" in GafferImage.Filter.filters() )\n\t\tf = GafferImage.Filter.create(\"Box\")\n\n\t\twith c :\n\n\t\t\tself.assertTrue( \"R\" in r[\"out\"][\"channelNames\"].getValue() )\n\t\t\ts = GafferImage.Sampler( r[\"out\"], \"R\", bounds, f, GafferImage.Sampler.BoundingMode.Black )\n\n\t\t\t# Check that the bounding pixels are non zero.\n\t\t\tself.assertNotEqual( s.sample( bounds.min.x+.5, bounds.min.y+.5 ), 0. )\n\t\t\tself.assertNotEqual( s.sample( bounds.max.x-.5, bounds.max.y-.5 ), 0. )\n\t\t\tself.assertNotEqual( s.sample( bounds.min.x+.5, bounds.max.y-.5 ), 0. )\n\t\t\tself.assertNotEqual( s.sample( bounds.max.x-.5, bounds.min.y+.5 ), 0. )\n\n\t\t\t# Sample out of bounds and assert that a zero is returned.\n\t\t\tfor x, y in testCases :\n\t\t\t\tself.assertEqual( s.sample( x+.5, y+.5 ), 0. )\n\n\tdef testOutOfBoundsSampleModeClamp( self ) :\n\n\t\ts = Gaffer.ScriptNode()\n\t\tr = GafferImage.ImageReader()\n\t\tr[\"fileName\"].setValue( self.fileName )\n\t\ts.addChild( r )\n\n\t\tc = Gaffer.Context()\n\t\tc[\"image:channelName\"] = 'R'\n\t\tc[\"image:tileOrigin\"] = IECore.V2i( 0 )\n\n\t\tbounds = r[\"out\"][\"dataWindow\"].getValue();\n\t\tf = GafferImage.Filter.create( \"Box\" )\n\n\t\twith c :\n\n\t\t\tself.assertTrue( \"R\" in r[\"out\"][\"channelNames\"].getValue() )\n\t\t\ts = GafferImage.Sampler( r[\"out\"], \"R\", bounds, f, GafferImage.Sampler.BoundingMode.Clamp )\n\n\t\t\t# Get the values of the corner pixels.\n\t\t\tbl = s.sample( bounds.min.x+.5, bounds.min.y+.5 )\n\t\t\tbr = s.sample( bounds.max.x-.5, bounds.min.y+.5 )\n\t\t\ttr = s.sample( bounds.max.x-.5, bounds.max.y-.5 )\n\t\t\ttl = s.sample( bounds.min.x+.5, bounds.max.y-.5 )\n\n\t\t\t# Sample out of bounds and assert that the same value as the nearest pixel is returned.\n\t\t\tself.assertEqual( s.sample( bounds.min.x-1, bounds.min.y ), bl )\n\t\t\tself.assertEqual( s.sample( bounds.min.x, bounds.min.y-1 ), bl )\n\t\t\tself.assertEqual( s.sample( bounds.max.x-1, bounds.max.y ), tr )\n\t\t\tself.assertEqual( s.sample( bounds.max.x, bounds.max.y-1 ), tr )\n\t\t\tself.assertEqual( s.sample( bounds.min.x-1, bounds.max.y-1 ), tl )\n\t\t\tself.assertEqual( s.sample( bounds.min.x, bounds.max.y ), tl )\n\t\t\tself.assertEqual( s.sample( bounds.max.x, bounds.min.y ), br )\n\t\t\tself.assertEqual( s.sample( bounds.max.x-1, bounds.min.y-1 ), br )\n\n\t# Test that the hash() method accumulates all of the hashes of the tiles within the sample area\n\t# for a large number of different sample areas.\n\tdef testSampleHash( self ) :\n\n\t\ts = Gaffer.ScriptNode()\n\t\tr = GafferImage.ImageReader()\n\t\tr[\"fileName\"].setValue( self.fileName )\n\t\ts.addChild( r )\n\n\t\ttileSize = GafferImage.ImagePlug.tileSize()\n\t\t# Test one tile first.\n\n\t\tfor w in range(2, 6) :\n\t\t\tfor x in range(-3, 3) :\n\t\t\t\tfor y in range(-3, 3) :\n\t\t\t\t\tsampleBox = IECore.Box2i( IECore.V2i( x*tileSize, y*tileSize ), IECore.V2i( x*tileSize+w*tileSize/2, y*tileSize+w*tileSize/2 ) )\n\t\t\t\t\tself.__testHashOfBounds( sampleBox, \"R\", r[\"out\"] )\n\n\n\t# A private method that acumulates the hashes of the tiles within\n\t# a box and compares them to the hash returned by the sampler.\n\tdef __testHashOfBounds( self, box, channel, plug ) :\n\n\t\ttileOrigin = GafferImage.ImagePlug.tileOrigin( IECore.V2i( box.min ) )\n\t\tself.assertTrue( channel in plug[\"channelNames\"].getValue() )\n\n\t\tc = Gaffer.Context()\n\t\tc[\"image:channelName\"] = channel\n\t\tc[\"image:tileOrigin\"] = tileOrigin\n\n\t\th = IECore.MurmurHash()\n\t\th2 = h\n\n\t\t# Get the hash from the sampler.\n\t\twith c :\n\t\t\tf = GafferImage.Filter.create( \"Box\" )\n\t\t\ts = GafferImage.Sampler( plug, channel, box, f, GafferImage.Sampler.BoundingMode.Clamp )\n\t\t\ts.hash( h )\n\n\t\t# Get the hash from the tiles within our desired sample area.\n\t\twith c :\n\t\t\ty = box.min.y\n\t\t\twhile y < box.max.y :\n\t\t\t\tx = box.min.x\n\t\t\t\twhile x < box.max.x :\n\t\t\t\t\ttileOrigin = GafferImage.ImagePlug.tileOrigin( IECore.V2i( x, y ) )\n\t\t\t\t\th2.append( plug.channelDataHash( channel, tileOrigin ) )\n\t\t\t\t\tx += GafferImage.ImagePlug.tileSize()\n\t\t\t\ty += GafferImage.ImagePlug.tileSize()\n\n\t\tself.assertEqual( h, h2 )\n\n\tdef test2x2Checker( self ) :\n\n\t\treader = GafferImage.ImageReader()\n\t\treader[\"fileName\"].setValue( os.path.dirname( __file__ ) + \"/images/checker2x2.exr\" )\n\n\t\t# As long as the sample region includes the valid range of our image,\n\t\t# it should have not effect on our sampling. So test with a few such ranges.\n\t\tsampleRegions = [\n\t\t\tIECore.Box2i( IECore.V2i( 0 ), IECore.V2i( GafferImage.ImagePlug.tileSize() ) ),\n\t\t\tIECore.Box2i( -IECore.V2i( GafferImage.ImagePlug.tileSize() ), IECore.V2i( GafferImage.ImagePlug.tileSize() ) ),\n\t\t\tIECore.Box2i( IECore.V2i( 0 ), IECore.V2i( 2 ) ),\n\t\t]\n\n\t\t# List of positions inside and outside of the image, along\n\t\t# with expected values if outside points are clamped inside.\n\t\tsamples = [\n\t\t\t( IECore.V2i( 0, 0 ), 1 ),\n\t\t\t( IECore.V2i( 1, 0 ), 0 ),\n\t\t\t( IECore.V2i( 1, 1 ), 1 ),\n\t\t\t( IECore.V2i( 0, 1 ), 0 ),\n\t\t\t( IECore.V2i( -1, 0 ), 1 ),\n\t\t\t( IECore.V2i( 2, 0 ), 0 ),\n\t\t\t( IECore.V2i( 0, 3 ), 0 ),\n\t\t\t( IECore.V2i( 0, -1 ), 1 ),\n\t\t\t( IECore.V2i( 3, 3 ), 1 ),\n\t\t\t( IECore.V2i( -1, -1 ), 1 ),\n\t\t\t( IECore.V2i( -1, 2 ), 0 ),\n\t\t\t( IECore.V2i( 2, 2 ), 1 ),\n\t\t\t( IECore.V2f( 1, 1 ), 0.5 ),\n\t\t]\n\n\t\t# Assert all is as expected for all combos of region and sample.\n\t\tfor region in sampleRegions :\n\t\t\tsampler = GafferImage.Sampler( reader[\"out\"], \"R\", region, boundingMode = GafferImage.Sampler.BoundingMode.Clamp )\n\t\t\tfor position, value in samples :\n\t\t\t\tself.assertEqual( sampler.sample( position.x, position.y ), value )\n\n\tdef testSampleOutsideDataWindow( self ) :\n\n\t\tconstant = GafferImage.Constant()\n\t\tconstant[\"format\"].setValue( GafferImage.Format( 1000, 1000 ) )\n\t\tconstant[\"color\"].setValue( IECore.Color4f( 1 ) )\n\n\t\tcrop = GafferImage.Crop()\n\t\tcrop[\"in\"].setInput( constant[\"out\"] )\n\t\tcrop[\"areaSource\"].setValue( crop.AreaSource.Custom )\n\t\tcrop[\"area\"].setValue( IECore.Box2i( IECore.V2i( 135 ), IECore.V2i( 214 ) ) )\n\t\tcrop[\"affectDisplayWindow\"].setValue( False )\n\n\t\tsampler = GafferImage.Sampler( crop[\"out\"], \"R\", IECore.Box2i( IECore.V2i( 0 ), IECore.V2i( 50 ) ), boundingMode = GafferImage.Sampler.BoundingMode.Clamp )\n\t\tself.assertEqual( sampler.sample( 0, 0 ), 1 )\n\n\t\tsampler = GafferImage.Sampler( crop[\"out\"], \"R\", IECore.Box2i( IECore.V2i( 0 ), IECore.V2i( 50 ) ), boundingMode = GafferImage.Sampler.BoundingMode.Black )\n\t\tself.assertEqual( sampler.sample( 0, 0 ), 0 )\n\n\tdef testHashIncludesBlackPixels( self ) :\n\n\t\tconstant = GafferImage.Constant()\n\t\tconstant[\"format\"].setValue( GafferImage.Format( 1000, 1000 ) )\n\t\tconstant[\"color\"].setValue( IECore.Color4f( 1 ) )\n\n\t\tcrop = GafferImage.Crop()\n\t\tcrop[\"in\"].setInput( constant[\"out\"] )\n\t\tcrop[\"areaSource\"].setValue( crop.AreaSource.Custom )\n\t\tcrop[\"area\"].setValue( IECore.Box2i( IECore.V2i( 0 ), IECore.V2i( 200 ) ) )\n\t\tcrop[\"affectDisplayWindow\"].setValue( False )\n\t\tcrop[\"affectDataWindow\"].setValue( False )\n\n\t\t# Samples the whole data window\n\t\tsampler1 = GafferImage.Sampler( crop[\"out\"], \"R\", IECore.Box2i( IECore.V2i( 0 ), IECore.V2i( 200 ) ), boundingMode = GafferImage.Sampler.BoundingMode.Black )\n\t\t# Samples the whole data window and then some.\n\t\tsampler2 = GafferImage.Sampler( crop[\"out\"], \"R\", IECore.Box2i( IECore.V2i( 0 ), IECore.V2i( 210 ) ), boundingMode = GafferImage.Sampler.BoundingMode.Black )\n\t\t# Samples the whole data window and then some and then some more.\n\t\tsampler3 = GafferImage.Sampler( crop[\"out\"], \"R\", IECore.Box2i( IECore.V2i( 0 ), IECore.V2i( 220 ) ), boundingMode = GafferImage.Sampler.BoundingMode.Black )\n\n\t\t# The hashes must take account of the additional pixels being sampled.\n\t\tself.assertNotEqual( sampler1.hash(), sampler2.hash() )\n\t\tself.assertNotEqual( sampler2.hash(), sampler3.hash() )\n\t\tself.assertNotEqual( sampler3.hash(), sampler1.hash() )\n\nif __name__ == \"__main__\":\n\tunittest.main()\n","sub_path":"python/GafferImageTest/SamplerTest.py","file_name":"SamplerTest.py","file_ext":"py","file_size_in_byte":11094,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"369325222","text":"# https://codeforces.com/contest/71/problem/A\ndef too_long(T):\n res = ''\n while T > 0:\n res = ''\n string = input()\n n = len(string)\n if n > 10:\n first = string[0]\n last = string[n - 1]\n res += first + str(n - 2) + last\n print(res)\n else:\n print(string)\n T -= 1\n\nT = int(input())\ntoo_long(T)\n","sub_path":"A. Way Too Long Words.py","file_name":"A. Way Too Long Words.py","file_ext":"py","file_size_in_byte":394,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"335387516","text":"from gym import logger\nimport numpy as np\n\nfrom rl_agents.agents.common import safe_deepcopy_env\nfrom rl_agents.agents.tree_search.abstract import Node, AbstractTreeSearchAgent, AbstractPlanner\n\n\nclass OLOPAgent(AbstractTreeSearchAgent):\n \"\"\"\n An agent that uses Open Loop Optimistic Planning to plan a sequence of actions in an MDP.\n \"\"\"\n def make_planner(self):\n return OLOP(self.env, self.config)\n\n\nclass OLOP(AbstractPlanner):\n \"\"\"\n An implementation of Open Loop Optimistic Planning.\n \"\"\"\n def __init__(self, env, config=None):\n self.leaves = None\n super(OLOP, self).__init__(config)\n\n def make_root(self):\n root, self.leaves = self.build_tree()\n return root\n\n @staticmethod\n def horizon(episodes, gamma):\n return int(np.ceil(np.log(episodes) / (2 * np.log(1 / gamma))))\n\n def allocate_budget(self):\n for episodes in range(1, 1000):\n if episodes * OLOP.horizon(episodes, self.config[\"gamma\"]) > self.config[\"budget\"]:\n self.config[\"episodes\"] = episodes - 1\n self.config[\"horizon\"] = OLOP.horizon(self.config[\"episodes\"], self.config[\"gamma\"])\n break\n else:\n raise ValueError(\"Could not split budget {} with gamma {}\".format(self.config[\"budget\"], self.config[\"gamma\"]))\n\n def build_tree(self, branching_factor):\n root = OLOPNode(parent=None, planner=self)\n leaves = [root]\n if \"horizon\" not in self.config:\n self.allocate_budget()\n for _ in range(self.config[\"horizon\"]):\n next_leaves = []\n for leaf in leaves:\n leaf.expand(branching_factor)\n next_leaves += leaf.children.values()\n leaves = next_leaves\n return root, leaves\n\n def run(self, state):\n \"\"\"\n Run an OLOP episode\n\n :param state: the initial environment state\n \"\"\"\n # Compute B-values\n list(Node.breadth_first_search(self.root, operator=self.accumulate_ucb, condition=None))\n sequences = list(map(OLOP.sharpen_ucb, self.leaves))\n\n # Pick best action sequence\n best_sequence = list(self.leaves[np.argmax(sequences)].path())\n\n # Execute sequence and collect rewards\n node = self.root\n terminal = False\n for action in best_sequence:\n observation, reward, done, _ = state.step(action)\n terminal = terminal or done\n node = node.children[action]\n node.update(reward if not terminal else 0)\n\n def accumulate_ucb(self, node, path):\n node_t = node\n node.value = self.config[\"gamma\"] ** (len(path) + 1) / (1 - self.config[\"gamma\"])\n try:\n for t in np.arange(len(path), 0, -1):\n node.value += self.config[\"gamma\"]**t * \\\n (node_t.total_reward / node_t.count\n + np.sqrt(2*np.log(self.config[\"episodes\"])/node_t.count))\n node_t = node_t.parent\n except ZeroDivisionError:\n node.value = np.infty\n return path, node.value\n\n @staticmethod\n def sharpen_ucb(node):\n node_t = node\n min_ucb = node.value\n while node_t.parent:\n min_ucb = min(min_ucb, node_t.value)\n node_t = node_t.parent\n node.value = min_ucb\n return node.value\n\n def plan(self, state, observation):\n for i in range(self.config['episodes']):\n if (i+1) % 10 == 0:\n logger.debug('{} / {}'.format(i+1, self.config['episodes']))\n self.run(safe_deepcopy_env(state))\n\n return self.get_plan()\n\n\nclass OLOPNode(Node):\n def __init__(self, parent, planner):\n super(OLOPNode, self).__init__(parent, planner)\n self.total_reward = 0\n\n def selection_rule(self):\n # Tie best counts by best value\n actions = list(self.children.keys())\n counts = Node.all_argmax([self.children[a].count for a in actions])\n return actions[max(counts, key=(lambda i: self.children[actions[i]].get_value()))]\n\n def update(self, reward):\n if not 0 <= reward <= 1:\n raise ValueError(\"This planner assumes that all rewards are normalized in [0, 1]\")\n self.total_reward += reward\n self.count += 1\n","sub_path":"rl_agents/agents/tree_search/olop.py","file_name":"olop.py","file_ext":"py","file_size_in_byte":4337,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"390191674","text":"# example for a SQLite recipe for JSON support\n# https://bitbucket.org/zzzeek/sqlalchemy/issues/3850/request-sqlite-json1-ext-support\nimport json\n\nfrom sqlalchemy import String, TypeDecorator, func\nfrom sqlalchemy.types import NullType\n\n\nclass SQLiteJson(TypeDecorator):\n impl = String\n\n class Comparator(String.Comparator):\n def __getitem__(self, index):\n if isinstance(index, tuple):\n index = \"$%s\" % (\n \"\".join(\n [\n \"[%s]\" % elem\n if isinstance(elem, int)\n else '.\"%s\"' % elem\n for elem in index\n ]\n )\n )\n elif isinstance(index, int):\n index = \"$[%s]\" % index\n else:\n index = '$.\"%s\"' % index\n\n # json_extract does not appear to return JSON sub-elements\n # which is weird.\n return func.json_extract(self.expr, index, type_=NullType)\n\n comparator_factory = Comparator\n\n def process_bind_param(self, value, dialect):\n if value is not None:\n value = json.dumps(value)\n return value\n\n def process_result_value(self, value, dialect):\n if value is not None:\n value = json.loads(value)\n return value\n","sub_path":"lib/backend/utils/customSQLAlchemy/types.py","file_name":"types.py","file_ext":"py","file_size_in_byte":1386,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"1238829","text":"# -*- coding: utf-8 -*-\n\"\"\"\nAssembly views\n\nThis is the views file. Create all of your view classes in here\n\n## Example\n\nclass Index(Assembly):\n\n # path: /\n # It will match the template at /templates/Index/index.html\n def index(self):\n return \"Hello world\"\n\n # path: /about-us\n # It will match the template at /templates/Index/about_us.html\n def about_us(self):\n return \n\nclass Blog(Assembly):\n\n # path: /blog/\n # It will match the template at /templates/Blog/index.html\n def index(self):\n return \"Hello world\"\n\n # path: /blog/posts\n # It will match the template at /templates/Blog/posts.html\n def posts(self):\n return \n\nclass API(Assembly):\n\n # path: /api/\n # It will return a json\n\n @response.json \n def index(self):\n return {\n \"name\": \"Assembly\",\n \"version\": \"x.y.z\"\n }\n\n # path: /api/items\n # It will return a json\n\n @response.json \n def items(self):\n return {\n \"data\": {\n \"items\": [1, 2, 3]\n }\n }\n\n\"\"\"\n\nfrom assembly import (Assembly,\n asm,\n date,\n models,\n request,\n response,\n HTTPError)\n\n# ------------------------------------------------------------------------------\n\n\nclass Index(Assembly):\n\n def index(self):\n return\n\n @request.cors\n @response.json\n def api(self):\n \"\"\"API Endpoint with CORS and JSON response\n This is using docstrings for specifications.\n ---\n definitions:\n Endpoint:\n type: object\n properties:\n date:\n type: date\n description:\n type: string\n items:\n $ref: '#/definitions/Endpoint'\n responses:\n 200:\n description: API Endpoint with CORS and JSON response\n schema:\n $ref: '#/definitions/Endpoint'\n examples:\n response: {\n \"date\": \"2019-11-29T18:28:07.125075+00:00\",\n \"description\": \"API Endpoint with CORS and JSON response\"\n }\n \"\"\"\n return {\n \"date\": date.utcnow(),\n \"description\": \"API Endpoint with CORS and JSON response\"\n }\n\n @response.json\n @response.cache(timeout=10)\n def cached(self):\n return {\n \"description\": \"This is a cached endpoint\",\n \"date\": date.utcnow(),\n }\n\n\n def error(self):\n \"\"\"\n Accessing /error should trigger the error handlers below\n \"\"\"\n raise HTTPError.NotFound()\n\n# ------------------------------------------------------------------------------\n\n\nclass Error(Assembly):\n \"\"\"\n This View handles errors\n \"\"\"\n\n def _error_handler(self, e):\n \"\"\"\n * special method\n Error handler method to catch all HTTP Error\n It's template must be the same name without the leading _, ie 'error_handler.html'\n \"\"\"\n return {\n \"code\": e.code,\n \"e\": e\n }\n\n def _error_404(self, e):\n \"\"\"\n * special method\n Error handler for 404\n It's template must be the same name without the leading _, ie 'error_404.html'\n \"\"\"\n return {\n \"code\": e.code,\n \"e\": e\n }\n","sub_path":"assembly/scaffold/init/main/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":3358,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"452128992","text":"class Solution:\n # @param A a list of integers\n # @param elem an integer, value need to be removed\n # @return an integer\n def removeElement(self, A, elem):\n if None == A:\n return 0\n idx = 0\n length = len(A)\n while idx < length:\n if A[idx] == elem:\n del A[idx]\n length -=1\n else:\n idx +=1\n\nif __name__ == \"__main__\":\n ins = Solution()\n A = [1,2,3,4,5,6,7,7,8,8,7,7]\n ins.removeElement(A, 7)\n input()","sub_path":"Python/LeetCode/LeetCode/removeElement.py","file_name":"removeElement.py","file_ext":"py","file_size_in_byte":543,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"127568493","text":"import os\nfrom flask import Flask\nfrom flask_sqlalchemy import SQLAlchemy\n\napp = Flask(__name__)\napp.config.from_object(os.environ['APP_SETTINGS'])\napp.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False\ndb = SQLAlchemy(app)\n\n\n@app.route('/')\ndef hello():\n return \"Hello World!\"\n\n\n@app.route('/')\ndef hello_name(name):\n return \"Hello {}!\".format(name)\n\n@app.route('/all-news')\ndef allnews():\n #resolve temporariamente.\n from models import Post\n posts = Post.list_all()\n return posts\n\n\nif __name__ == '__main__':\n app.run()","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":546,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"458666156","text":"from tkinter import Tk\nfrom tkinter import *\nfrom nhentai import Hentai\nfrom downloadNhentai import DownloadHentai\nfrom nhentai import ConnectionErrorNHentai\n\nclass App:\n\n def __init__(self, root):\n self.window = root\n self.window.title(\"NHentai\")\n self.window.geometry(\"500x280\")\n self.window.resizable(False, False)\n \n # Important elements\n self.hentai = None\n self.icon = None\n self.iconFrame = LabelFrame(self.window)\n \n self.searchFrame = LabelFrame(self.window, text = \"Enter the code\")\n self.codeInput = None\n self.searchButtom = None\n self.downloadButtom = None\n \n self.infoWindow = None\n self.infoFrame = None\n self.infoLabel = None\n \n self.iconFrame.grid(row = 0, column = 0, padx = 10, pady = 10)\n self.searchFrame.grid(row = 0, column = 2, pady = 0, sticky=N)\n self.loadIcon()\n self.loadSearch()\n \n \n def loadIcon(self):\n try:\n self.icon = PhotoImage(file=\"resources/nhentai.png\")\n widgetIcon = Label(self.iconFrame, image=self.icon)\n except TclError as e:\n print(e)\n widgetIcon = Label(self.iconFrame, text = \"Error loading resource 'resources/nhentai2.png'\")\n widgetIcon.pack()\n\n def loadSearch(self):\n self.codeInput = Entry(self.searchFrame)\n self.codeInput.focus()\n self.codeInput.grid(row = 1, column = 1)\n \n self.searchButtom = Button(self.searchFrame, text = \"Search\", command=self.search)\n self.searchButtom.grid(row = 3, columnspan=2, sticky=W + E)\n self.downloadButtom = Button(self.searchFrame, text = \"Download\", command=self.download)\n self.downloadButtom.grid(row = 4, columnspan=2, sticky=W + E)\n self.downloadButtom[\"state\"] = DISABLED\n self.message = Label(self.searchFrame, text = \"\", fg='red')\n self.message.grid(row = 2, columnspan=2, sticky=W + E)\n \n def download(self):\n self.hentai.downloadHentai()\n self.downloadButtom.config(text=\"Download\")\n self.downloadButtom[\"state\"] = DISABLED\n \n def search(self):\n if self.validate():\n self.message.config(text='')\n self.hentai = DownloadHentai(self.codeInput.get())\n\n try:\n self.hentai.loadData()\n except ConnectionErrorNHentai as error:\n print(error)\n self.message.config(text=str(error))\n self.codeInput.delete(0, END)\n return\n self.hentai.analyzeData()\n self.showInfo()\n \n \n def validate(self):\n if len(self.codeInput.get()) != 0:\n try:\n int(self.codeInput.get())\n except Exception as e:\n self.message.config(text='That is not a code')\n self.codeInput.delete(0, END)\n return False\n return True\n else:\n self.message.config(text='Enter a code')\n self.codeInput.delete(0, END)\n return False \n \n\n\n def showInfo(self):\n self.infoWindow = Toplevel()\n self.infoWindow.title(str(self.hentai.title))\n \n self.infoFrame = LabelFrame(self.infoWindow)\n self.infoFrame.grid(row = 0, column = 0, columnspan = 3, pady = 10)\n \n self.loadHentai()\n \n self.infoWindow.transient(master=self.window)\n self.infoWindow.grab_set()\n self.window.wait_window(self.infoWindow)\n self.downloadButtom[\"state\"] = NORMAL\n string = \"Download (Code: \" + self.codeInput.get() + \")\"\n self.downloadButtom.config(text=string)\n \n def loadHentai(self):\n data = {}\n if self.hentai.title:\n data[\"Title\"] = self.hentai.title\n if self.hentai.pages:\n data[\"Pages\"] = self.hentai.pages\n \n self.loadAttributes(self.hentai.parodies, \"Parodies\", data)\n self.loadAttributes(self.hentai.characters, \"Characters\", data)\n self.loadAttributes(self.hentai.tags, \"Tags\", data)\n self.loadAttributes(self.hentai.artists, \"Artists\", data)\n self.loadAttributes(self.hentai.groups, \"Groups\", data)\n self.loadAttributes(self.hentai.languages, \"Languages\", data)\n self.loadAttributes(self.hentai.categories, \"Categories\", data)\n \n string = ''\n for key in data.keys():\n strData = str(data[key]).replace(\"'\",\"\").replace(\"[\",\"\").replace(\"]\",\"\")\n string = string + key + \" : \" + strData + \"\\n\"\n \n self.infoLabel = Label(self.infoFrame, text = string)\n self.infoLabel.grid(row = 2, columnspan=2, sticky=W + E)\n\n def loadAttributes(self, atributes, key, data):\n if atributes:\n data[key] = []\n for atribute in atributes:\n data[key].append(atribute)\n\nif __name__ == \"__main__\":\n root = Tk()\n app = App(root)\n root.mainloop()\n","sub_path":"graphics.py","file_name":"graphics.py","file_ext":"py","file_size_in_byte":5062,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"170944122","text":"import logging\n\nfrom utct.common.trainer_template import TrainerTemplate\n\nimport mxnet as mx\nfrom mxnet import gluon, autograd\n\n\nclass Trainer(TrainerTemplate):\n \"\"\"\n Class, which provides training process under Gluon/MXNet framework.\n\n Parameters:\n ----------\n model : object\n instance of Model class with graph of CNN\n optimizer : object\n instance of Optimizer class with CNN optimizer\n data_source : object\n instance of DataSource class with training/validation iterators\n saver : object\n instance of Saver class with information about stored files\n ctx : object\n instance of MXNet context\n \"\"\"\n def __init__(self,\n model,\n optimizer,\n data_source,\n saver,\n ctx):\n super(Trainer, self).__init__(\n model,\n optimizer,\n data_source,\n saver)\n self.ctx = ctx\n\n def _hyper_train_target_sub(self, **kwargs):\n \"\"\"\n Calling single training procedure for specific hyper parameters from hyper optimizer.\n \"\"\"\n\n if self.saver.log_filename:\n fh = logging.FileHandler(self.saver.log_filename)\n self.logger.addHandler(fh)\n\n self.logger.info(\"Training with parameters: {}\".format(kwargs))\n\n train_loader, val_loader = self.data_source()\n\n net = self.model()\n net.initialize(\n mx.init.Xavier(magnitude=2.24),\n ctx=self.ctx)\n\n trainer = self.optimizer(\n params=net.collect_params(),\n **kwargs)\n\n metric = mx.metric.Accuracy()\n loss = gluon.loss.SoftmaxCrossEntropyLoss()\n\n log_interval = 1\n for epoch in range(self.num_epoch):\n metric.reset()\n for i, (data, label) in enumerate(train_loader):\n # Copy data to ctx if necessary\n data = data.as_in_context(self.ctx)\n label = label.as_in_context(self.ctx)\n # Start recording computation graph with record() section.\n # Recorded graphs can then be differentiated with backward.\n with autograd.record():\n output = net(data)\n L = loss(output, label)\n L.backward()\n # take a gradient step with batch_size equal to data.shape[0]\n trainer.step(data.shape[0])\n # update metric at last.\n metric.update([label], [output])\n\n if i % log_interval == 0 and i > 0:\n name, acc = metric.get()\n print('[Epoch %d Batch %d] Training: %s=%f' % (epoch, i, name, acc))\n\n name, acc = metric.get()\n print('[Epoch %d] Training: %s=%f' % (epoch, name, acc))\n\n name, val_acc = self._test(\n model=net,\n val_data=val_loader,\n ctx=self.ctx)\n print('[Epoch %d] Validation: %s=%f' % (epoch, name, val_acc))\n\n if self.saver.log_filename:\n self.logger.removeHandler(fh)\n fh.close()\n\n best_value = 0.0\n\n return best_value\n\n @staticmethod\n def _test(model,\n val_data,\n ctx):\n metric = mx.metric.Accuracy()\n for data, label in val_data:\n data = data.as_in_context(ctx)\n label = label.as_in_context(ctx)\n output = model(data)\n metric.update([label], [output])\n\n return metric.get()\n\n","sub_path":"Gluon/trainer.py","file_name":"trainer.py","file_ext":"py","file_size_in_byte":3553,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"172558359","text":"# python_tutorial_task.py - Batch Python SDK tutorial sample\n#\n# Copyright (c) Microsoft Corporation\n#\n# All rights reserved.\n#\n# MIT License\n#\n# Permission is hereby granted, free of charge, to any person obtaining a\n# copy of this software and associated documentation files (the \"Software\"),\n# to deal in the Software without restriction, including without limitation\n# the rights to use, copy, modify, merge, publish, distribute, sublicense,\n# and/or sell copies of the Software, and to permit persons to whom the\n# Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n# DEALINGS IN THE SOFTWARE.\n\nfrom __future__ import print_function\nimport argparse\nimport os\nfrom subprocess import call\nimport datetime as dt\n\nimport azure.storage.blob as azureblob\n\nif __name__ == '__main__':\n\n parser = argparse.ArgumentParser()\n parser.add_argument('--storageaccount', required=True,\n help='The name the Azure Storage account that owns the'\n 'blob storage container to which to upload'\n 'results.')\n parser.add_argument('--storagecontainer', required=True,\n help='The Azure Blob storage container to which to'\n 'upload results.')\n parser.add_argument('--sastoken', required=True,\n help='The SAS token providing write access to the'\n 'Storage container.')\n args = parser.parse_args()\n\n output_file_path = os.path.realpath('topopt_results.zip')\n dttm = dt.datetime.now().strftime(\"-%y%m%d-%H%M%S\")\n\n output_file = 'topopt_results_{}.zip'.format(dttm)\n\n run_command = \"topopt_run.sh \"\n call(run_command, shell=True)\n\n # Create the blob client using the container's SAS token.\n # This allows us to create a client that provides write\n # access only to the container.\n blob_client = azureblob.BlockBlobService(account_name=args.storageaccount,\n sas_token=args.sastoken)\n\n # upload output file to blob with timestamps\n blob_client.create_blob_from_path(args.storagecontainer,\n output_file,\n output_file_path)\n print('Uploading file {} to container [{}]...'.format(\n output_file_path,\n args.storagecontainer))\n\n # upload stdout and stderr\n stdout_file_path = os.path.realpath('stdout.txt')\n stderr_file_path = os.path.realpath('stderr.txt')\n\n stdout_file = 'stdout_{}.txt'.format(dttm)\n stderr_file = 'stderr_{}.txt'.format(dttm)\n blob_client.create_blob_from_path(args.storagecontainer,\n stdout_file,\n stdout_file_path)\n\n blob_client.create_blob_from_path(args.storagecontainer,\n stderr_file,\n stderr_file_path)\n\n print('Uploading file {} to container [{}]...'.format(\n stdout_file_path,\n args.storagecontainer))\n\n print('Uploading file {} to container [{}]...'.format(\n stderr_file_path,\n args.storagecontainer))\n\n\n\n","sub_path":"topopt_batch/application/task.py","file_name":"task.py","file_ext":"py","file_size_in_byte":3769,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"566060926","text":"\"\"\"\nCreated on Wed Mar 18 12:44:00 2020\n@author: nsourlos\n\"\"\"\n\n#Usage\n#python pix2pix_combine.py --image /home/nsourlos/Desktop/Train/Pictures --sketch /home/nsourlos/Desktop/Train/Sketches --destination /home/nsourlos/Desktop/new\n\n\nimport cv2\nimport os\nimport numpy as np\nimport argparse\n\nap = argparse.ArgumentParser()\nap.add_argument(\"-p\", \"--image\", required=True,\n\thelp=\"path to real images folder\")\nap.add_argument(\"-i\", \"--sketch\", required=True,\n\thelp=\"path to sketch images folder\")\nap.add_argument(\"-d\", \"--destination\", required=True,\n\thelp=\"path to output folder\")\nargs = vars(ap.parse_args())\n\n#We have already both real images and their sketches have the same dimension (see massive_resizer file) and same name in their folders\n#Below are three path examples\n\n#path = '/home/nsourlos/Desktop/train/photos' #Assuming that real images are in this folder\n#path2 = '/home/nsourlos/Desktop/train/sketches' #Assuming sketches are in this folder\n#path3 = '/home/nsourlos/Desktop/train/new' #Combined photos+sketches images will be created here\n\nos.chdir(args[\"image\"]) \n\nfor filename in os.listdir(args[\"image\"]):\n a=filename \n print(a)\n image1 = cv2.imread(a)\n print(image1.shape)\n os.chdir(args[\"sketch\"]) \n image2 = cv2.imread(a)\n print(image2.shape)\n os.chdir(args[\"destination\"]) \n comb = 255 * np.ones((image1.shape[0], image1.shape[1]+image2.shape[1], 3), dtype=np.uint8)\n print(comb.shape)\n comb[:image1.shape[0],image1.shape[1]:,:]=image1\n comb[:image1.shape[0],:image1.shape[1],:]=image2\n #cv2.imshow(\"Output\", comb)\n cv2.imwrite(a[:-4]+\"_AB\"+a[-4:], comb) \n os.chdir(args[\"image\"])\n \n\n \n","sub_path":"scripts/pix2pix_combine.py","file_name":"pix2pix_combine.py","file_ext":"py","file_size_in_byte":1656,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"646204620","text":"from flask_restful import Resource, reqparse\nfrom params import params\nfrom coreApis import coreApis\nfrom utils import tokenValidator,sql\nimport logging\nimport requests\n\nparam=params()\ncoreApi=coreApis()\n\nclass DoModelPredict(Resource):\n def post(self):\n parser = reqparse.RequestParser()\n parser.add_argument('fileID', type=str, required=True)\n parser.add_argument('token',type=str,required=True)\n parser.add_argument('modelIndex', type=str, required=True)\n parser.add_argument('preprocessFileName', type=str, required=True)\n parser.add_argument('predictFileName', type=str, required=True)\n parser.add_argument('preprocess', type=str, required=True)\n parser.add_argument('projectID', type=str, required=True)\n parser.add_argument('userID', type=str, required=True)\n args = parser.parse_args()\n logging.debug(f\"[DoModelPredict] args: {args}\")\n\n fileID = args['fileID']\n modelIndex = args['modelIndex']\n preprocessFileName = args['preprocessFileName']\n predictFileName = args['predictFileName']\n token = args['token']\n preprocess = args['preprocess']\n projectID = args['projectID']\n userID = args['userID']\n\n #check user isLogin\n if tokenValidator(token):\n try:\n db=sql()\n db.cursor.execute(f\"select * from model where `model_index`='{modelIndex}'\")\n result = db.cursor.fetchone()\n if(result[1] != None):\n form = {\n 'modelUid': result[1],\n 'fileUid': fileID,\n 'preprocess': preprocess,\n 'token': token\n } \n resp = requests.post(coreApi.DoModelPredict, data=form)\n response = resp.json()\n try:\n db.cursor.execute(f\"select * from file where `file_id`='{result[4]}'\")\n fileObject = db.cursor.fetchone()\n fileType = fileObject[1][(fileObject[1].rfind(\".\")+1):]\n logging.info(f'{fileType}')\n except Exception as e:\n db.conn.rollback()\n logging.error(str(e))\n if response['status'] == 'success':\n if preprocess == '1':\n try:\n preprocessFileID = response[\"data\"][\"preprocessedFileUid\"]\n if preprocessFileID != 'None':\n predictFileID = response[\"data\"][\"predictedFileUid\"]\n db.cursor.execute(f\"insert into file (`file_id`,`file_name`,`user_id`,`project_id`) values ('{preprocessFileID}','{preprocessFileName}.{fileType}','{userID}','{projectID}');\")\n db.cursor.execute(f\"insert into file (`file_id`,`file_name`,`user_id`,`project_id`) values ('{predictFileID}','{predictFileName}.{fileType}','{userID}','{projectID}');\")\n db.conn.commit()\n return {\"status\":\"success\",\"msg\":\"predict success\",\"data\":{'isPreprocess':'1'}},200\n else:\n predictFileID = response[\"data\"][\"predictedFileUid\"]\n db.cursor.execute(f\"insert into file (`file_id`,`file_name`,`user_id`,`project_id`) values ('{predictFileID}','{predictFileName}.{fileType}','{userID}','{projectID}');\")\n db.conn.commit()\n return {\"status\":\"success\",\"msg\":\"predict success\",\"data\":{'isPreprocess':'0'}},200\n except Exception as e:\n db.conn.rollback()\n logging.error(str(e))\n else:\n try:\n predictFileID = response[\"data\"][\"predictedFileUid\"]\n db.cursor.execute(f\"insert into file (`file_id`,`file_name`,`user_id`,`project_id`) values ('{predictFileID}','{predictFileName}.{fileType}','{userID}','{projectID}');\")\n db.conn.commit()\n return {\"status\":\"success\",\"msg\":\"predict success\",\"data\":{}},200\n except Exception as e:\n db.conn.rollback()\n logging.error(str(e))\n else:\n return response, 400\n else:\n return {\"status\":\"error\",\"msg\":\"model id or file id not found\",\"data\":{}},500\n except Exception as e:\n logging.error(str(e))\n db.conn.rollback()\n finally:\n db.conn.close()\n else:\n return {\"status\":\"error\",\"msg\":\"user did not login\",\"data\":{}},401","sub_path":"src/service/analytic/controller/doModelPredict.py","file_name":"doModelPredict.py","file_ext":"py","file_size_in_byte":5056,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"263449638","text":"from setuptools import setup, find_packages\n\n__version__ = None\nwith open('sgbackend/version.py') as f:\n exec(f.read())\n\nsetup(\n name='sendgrid-django',\n version=str(__version__),\n author='Yamil Asusta',\n author_email='yamil@sendgrid.com',\n url='https://github.com/elbuo8/sendgrid-django',\n packages=find_packages(),\n license='MIT',\n description='SendGrid Backend for Django',\n long_description=open('./README.rst').read(),\n install_requires=[\"sendgrid >= 3.5, < 4\"],\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":503,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"8279497","text":"# -*- coding: utf-8 -*-\n\nfrom typing import Optional\nfrom aiohttp.client import ClientSession\nfrom objects.collections import PlayerList, ChannelList, MatchList\nfrom cmyui import SQLPool\nimport config\n\n__all__ = ('players', 'channels',\n 'matches', 'db', 'cache')\n\nplayers = PlayerList()\nchannels = ChannelList()\nmatches = MatchList()\ndb: Optional[SQLPool] = None\nhttp: Optional[ClientSession] = None\n\n# Gulag's main cache.\n# The idea here is simple - keep a copy of things either from SQL or\n# that take a lot of time to produce in memory for quick and easy access.\n# Ideally, the cache is hidden away in methods so that developers do not\n# need to think about it.\ncache = {\n # Doing bcrypt on a password takes a surplus of 250ms in python\n # (at least on my current [powerful] machine). This is intentional\n # with bcrypt, but to remove some of this performance hit, we only\n # do it on the user's first login.\n 'bcrypt': {},\n # We'll cache results for osu! client update requests since they\n # are relatively frequently and won't change very frequently.\n 'update': { # Default timeout is 1h, set on request.\n 'cuttingedge': {'check': None, 'path': None, 'timeout': 0},\n 'stable40': {'check': None, 'path': None, 'timeout': 0},\n 'beta40': {'check': None, 'path': None, 'timeout': 0},\n 'stable': {'check': None, 'path': None, 'timeout': 0}\n }\n # XXX: I want to do some sort of beatmap cache, I'm just not yet\n # quite sure on how I want it setup..\n}\n","sub_path":"objects/glob.py","file_name":"glob.py","file_ext":"py","file_size_in_byte":1526,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"413333491","text":"import plotly\nimport plotly.graph_objects as pgo\nimport plotly.figure_factory as pff\nimport codecs\n\nimport math\n\n## for relative Imports\nimport sys, os, pathlib\ncurrentPath = pathlib.Path(os.path.dirname(__file__))\nrelativePath = currentPath.parent.parent\nsys.path.append(str(relativePath))\n\n\n## classes and enums from our utilities:\nfrom StateEst_Utils.config import CONFIG, IS_DEBUG_MODE \nfrom StateEst_Utils.ConeType import ConeType\nfrom StateEst_Utils.MessagesClass import messages\n\n# Get proper Enum:\nYELLOW \t\t = ConeType.YELLOW #messages.perception.Yellow\nBLUE \t\t = ConeType.BLUE #messages.perception.Blue\nORANGE_BIG = ConeType.ORANGE_BIG #messages.perception.OrangeBig\nORANGE_SMALL = ConeType.ORANGE_SMALL \nUNKNOWN = ConeType.UNKNOWN\n\n\nis_first_call = True\nIS_Xnorth_Yeast = True\n\n\ndef send_StateEst_DashBoard_with_GroundTruth(msg ,CarTruth): \n data = messages.state_est.FormulaState()\n msg.data.Unpack(data)\n time_in_milisec = msg.header.timestamp.ToMilliseconds()\n \n plotly_state(data , time=time_in_milisec , CarTruth=CarTruth)\n\n\ndef send_StateEst_DashBoard_msg(msg):\n data = messages.state_est.FormulaState()\n msg.data.Unpack(data)\n time_in_milisec = msg.header.timestamp.ToMilliseconds()\n\n plotly_state(data , time=time_in_milisec)\n\n\ndef get_update(path_str):\n with open(path_str) as f:\n data = json.load(f)\n plotly_state(data)\n\n\ndef set_fig_appearance(fig):\n if IS_Xnorth_Yeast:\n fig.update_layout(\n title='State Estimation Dash-Board',\n xaxis_title='yEast [m]',\n yaxis_title='xNorth [m]'\n )\n else:\n fig.update_layout(\n title='State Estimation Dash-Board',\n xaxis_title='xNorth [m]',\n yaxis_title='yEast [m]'\n )\n return fig\n\ndef cones_to_x_y_arrays(cone_array):\n x_array = []\n y_array = []\n for cone in cone_array:\n x_array.append(cone.position.x)\n y_array.append(cone.position.y)\n return x_array , y_array\n\n\ndef plotly_state(data , time=0 , **kargs):\n\n\n if 'CarTruth' in kargs:\n is_with_car_truth = True\n CarTruth = kargs['CarTruth']\n ## Parse GroundTruth\"\n true_x = CarTruth[\"x\"]\n true_y = CarTruth[\"y\"]\n true_theta = CarTruth[\"theta\"]\n else:\n is_with_car_truth = False\n\n\n ## Parse Data:\n right_cones = data.right_bound_cones\n left_cones = data.left_bound_cones\n distance2finish = data.distance_to_finish\n car_x = data.current_state.position.x\n car_y = data.current_state.position.y\n car_theta = data.current_state.theta\n #error in estimation:\n car_pos_deviation_x = data.current_state.position_deviation.x\n car_pos_deviation_y = data.current_state.position_deviation.y\n\n\n x_arr_yellow , y_arr_yellow = cones_to_x_y_arrays(right_cones)\n color_arr_yellow = ['yellow'] * len(x_arr_yellow)\n x_arr_blue , y_arr_blue = cones_to_x_y_arrays(left_cones)\n color_arr_blue = ['blue'] * len(x_arr_blue)\n\n if len(x_arr_yellow)==0:\n print(f\"DashBoard::StateEst::no cones\")\n\n if is_with_car_truth:\n x_arr = x_arr_yellow + x_arr_blue + [car_x] + [true_x]\n y_arr = y_arr_yellow + y_arr_blue + [car_y] + [true_y]\n c_arr = color_arr_yellow + color_arr_blue + ['red'] + ['orange']\n else:\n x_arr = x_arr_yellow + x_arr_blue + [car_x] \n y_arr = y_arr_yellow + y_arr_blue + [car_y] \n c_arr = color_arr_yellow + color_arr_blue + ['red'] \n\n ## Show theta as arrow:\n # fig = pff.create_quiver(car_x, car_y , math.cos(car_theta) , math.sin(car_theta)) \n\n ## Plot:\n if IS_Xnorth_Yeast:\n scatter = pgo.Scatter( x=y_arr , y=x_arr , mode='markers' ,\n marker=dict( color=c_arr , size=20)\n )\n else:\n scatter = pgo.Scatter( x=x_arr , y=y_arr , mode='markers' ,\n marker=dict( color=c_arr , size=20)\n )\n # color='rgb(140,140,0)'\n\n\n\n fig = pgo.Figure(data=scatter)\n fig = set_fig_appearance(fig)\n\n global is_first_call\n if is_first_call:\n fig.write_html('State Estimation Dash-Board.html' , auto_open=True)\n is_first_call = False\n else:\n fig.write_html('State Estimation Dash-Board.html' , auto_open=False)\n\n\ndef plotly_test():\n x = [1 , 3]\n y = [2 , 2]\n scatter = pgo.Scatter(x=x , y=y , mode='markers')\n fig = pgo.Figure(data=scatter)\n fig.write_html('State Estimation Dash-Board.html' , auto_open=True )\n\n x = [2 , 2]\n y = [3 , 5]\n scatter = pgo.Scatter(x=x , y=y , mode='markers')\n fig = pgo.Figure(data=scatter)\n fig.write_html('State Estimation Dash-Board.html' , auto_open=False )\n\n\nif __name__ == \"__main__\":\n plotly_test()\n","sub_path":"Code_RealTime/StateEst_SR/StateEst_Dash.py","file_name":"StateEst_Dash.py","file_ext":"py","file_size_in_byte":4702,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"609180347","text":"'''\ngiven a model (.pkl) and a test observation, \ncalculate the health score\n'''\nfrom sklearn.neighbors import NearestNeighbors\n\n\ndef health_score(neurons, test_points):\n '''\n given bmu's (or neurons), \n calculate the health score,\n by using kNN clustering \n and then the euclidean distance metric\n '''\n print(\"Classifying...\")\n #print(neurons)\n clf = NearestNeighbors(n_neighbors=3)\n clf.fit(neurons)\n distances, indices = clf.kneighbors(test_points)\n return distances.min(1)","sub_path":"src/score.py","file_name":"score.py","file_ext":"py","file_size_in_byte":512,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"102898780","text":"import os\nimport unittest\nfrom Twitter_Utils.KeywordGenerator import KeywordGenerator\n\n\nclass TestKeywordGenerator(unittest.TestCase):\n def test___init__(self):\n assert True\n\n def test_generate_search_terms_should_throw_exception(self):\n keyword_generator = KeywordGenerator()\n keyword_generator.team_data_path = ''\n with self.assertRaises(IOError):\n keyword_generator.generate_search_terms('20901970-53a0-417c-b5b4-832a74148af6', \"notARealSport\")\n assert True\n\n def test_append_word_with_go_to_list(self):\n keyword_generator = KeywordGenerator()\n test_list = ['test', 'ok']\n self.assertEqual(['test', 'ok', 'gotest', 'gook'], keyword_generator.append_word_with_go_to_list(test_list))\n # No words\n test_list = []\n self.assertEqual([], keyword_generator.append_word_with_go_to_list(test_list))\n\n def test_get_team_data_path_for_nhl(self):\n keyword_generator = KeywordGenerator()\n expected = os.getcwd() + '/Twitter_Utils/data/nhl-teams-data.json'\n self.assertEqual(expected, keyword_generator.get_team_data_path(\"nhl\"))\n\n def test_get_team_data_path_for_nba(self):\n keyword_generator = KeywordGenerator()\n expected = os.getcwd() + '/Twitter_Utils/data/nba-teams-data.json'\n self.assertEqual(expected, keyword_generator.get_team_data_path(\"nba\"))\n\n def test_generate_search_terms(self):\n keyword_generator = KeywordGenerator()\n team_id = '84eb19ca-1e66-416f-9e00-90b20fe4bb5e'\n sport = 'nba'\n self.assertGreater(len(keyword_generator.generate_search_terms(team_id, sport)),35)\n\n def test_get_team_data_path_nba(self):\n keyword_generator = KeywordGenerator()\n expected = os.getcwd() + '/Twitter_Utils/data/nba-teams-data.json'\n self.assertEqual(expected, keyword_generator.get_team_data_path(\"nba\"))\n\n def test_get_team_data_path_nhl(self):\n keyword_generator = KeywordGenerator()\n expected = os.getcwd() + '/Twitter_Utils/data/nhl-teams-data.json'\n self.assertEqual(expected, keyword_generator.get_team_data_path(\"nhl\"))\n\n def test_get_team_data_path(self):\n keyword_generator = KeywordGenerator()\n expected_nba = os.getcwd() + '/Twitter_Utils/data/nba-teams-data.json'\n expected_nhl = os.getcwd() + '/Twitter_Utils/data/nhl-teams-data.json'\n self.assertEqual(expected_nba, keyword_generator.get_team_data_path(\"nba\"))\n self.assertEqual(expected_nhl, keyword_generator.get_team_data_path(\"nhl\"))\n\nif __name__ == '__main__': # pragma: no cover\n unittest.main()\n","sub_path":"Twitter_Utils/tests/test_KeywordGenerator.py","file_name":"test_KeywordGenerator.py","file_ext":"py","file_size_in_byte":2624,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"600880324","text":"''' Created on Apr 25, 2012\n\n@author: jasonz\n'''\nfrom spider_base import SpiderBase\nfrom spider_thread import SpiderThread\nimport thread\nimport time\nfrom bs4 import BeautifulSoup\nimport sys\nsys.path.append('../')\n\nfrom sources.douban_movie_spider import DoubanMovieSpider\nfrom sources.mtime_news_spider import MtimeNewsSpider \nfrom sources.sohu_star_spider import SohuStarSpider\nfrom sources.yahoo_news_spider import YahooNewsSpider \nfrom sources.yisou_all_spider import YisouAllSpider\n\ndef create_spider(data_adapter_config_path, source_name, encode):\n if source_name == \"douban_movie\":\n return DoubanMovieSpider(data_adapter_config_path, encode)\n \n if source_name == \"mtime_news\":\n return MtimeNewsSpider(data_adapter_config_path, encode)\n\n if source_name == \"sohu_star\":\n return SohuStarSpider(data_adapter_config_path, encode)\n\n if source_name == \"yahoo_news\":\n return YahooNewsSpider(data_adapter_config_path, encode)\n \n if source_name == \"yisou_all\":\n return YisouAllSpider(data_adapter_config_path, encode)\n\n return None\n\ndef load_spiders(data_sources_file):\n f = open(data_sources_file, 'r')\n config = BeautifulSoup(f.read())\n f.close()\n \n spider_source_encoding = {} \n for source in config.sources.findAll(\"source\"):\n if source.spider.enable.string == \"1\":\n source_name = source.source_name.string\n encoding = source.encoding.string\n spider_source_encoding[source_name] = encoding\n \n return spider_source_encoding \n \ndatabase_config_file = \"../database_config.xml\" \nsource_config_file = \"../source_config.xml\" \nif __name__ == '__main__':\n threads = {}\n while True:\n spider_source_encoding = load_spiders(source_config_file)\n for source_name, encoding in spider_source_encoding.items():\n if not threads.has_key(source_name):\n spider = create_spider(database_config_file, source_name, encoding)\n threads[source_name] = SpiderThread(spider)\n threads[source_name].setDaemon(True)\n threads[source_name].start()\n for source_name in threads.keys():\n if not spider_source_encoding.has_key(source_name):\n if threads[source_name].is_running:\n threads[source_name].available = False \n else:\n del(threads[source_name])\n\n time.sleep(30)\n \n\n","sub_path":"spider/spider_main.py","file_name":"spider_main.py","file_ext":"py","file_size_in_byte":2463,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"154308302","text":"# copypasta.py\n\n# module for bobbit that pulls posts from r/copypasta\n# i don't claim any responsibility for the content of the posts\n# Gavin Inglis\n\nimport os\nimport re\nimport random\n\nimport tornado.gen\nimport tornado.httpclient\nimport json\n\n# Metadata\n\nNAME = 'copypasta'\nENABLE = True\nTYPE = 'command'\nPATTERN = re.compile('^!copypasta$')\nURL \t= 'https://www.reddit.com/r/copypasta/.json'\nMIN_LEN = 0\nMAX_LEN = 480\n\nUSAGE = '''Usage: !copypasta\nDisplays a random post from r/copypasta\n\nWARNING: can be pretty offcolor. Use at your own discretion\n'''\n\n# Command\n\n@tornado.gen.coroutine\ndef command(bot, nick, message, channel, url=URL):\n client = tornado.httpclient.AsyncHTTPClient()\n result = yield tornado.gen.Task(client.fetch, url)\n\n pastas = []\n try:\n for result in json.loads(result.body.decode())['data']['children']:\n data = result['data']\n pasta = data['selftext'].replace('\\n', ' ')\n\n\t # Ignore long posts b/c IRC\n if MIN_LEN < len(pasta) < MAX_LEN:\n pastas.append(pasta)\n\n response = random.choice(pastas)\n\n except (IndexError, KeyError, ValueError) as e:\n bot.logger.warn(e)\n response = 'No results'\n\n bot.send_response(response, nick, channel)\n\n# Register\n\ndef register(bot):\n return (\n (PATTERN, command),\n )\n\n# vim: set sts=4 sw=4 ts=8 expandtab ft=python:\n","sub_path":"modules/copypasta.py","file_name":"copypasta.py","file_ext":"py","file_size_in_byte":1394,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"648986207","text":"import json\nimport datetime\n\nfrom flask import Blueprint, url_for, make_response, g\n\nfrom flask_restful import Resource, Api, reqparse, fields, marshal, marshal_with, abort, inputs\n\nfrom auth import auth\n\nimport models\n\n\ntodo_fields = {\n 'id': fields.Integer,\n 'name': fields.String,\n 'edited': fields.Boolean,\n 'completed': fields.Boolean,\n 'created_at': fields.String,\n 'updated_at': fields.String,\n 'created_by': fields.String,\n}\n\n\ndef todo_or_404(todo_id):\n \"\"\"Return task from DB by ID, or error message if task does not exist.\"\"\"\n try:\n todo = models.Todo.get(models.Todo.id == todo_id)\n except models.Todo.DoesNotExist:\n abort(404, message='Todo {} does not exist'.format(todo_id))\n else:\n return todo\n\n\nclass TodoList(Resource):\n def __init__(self):\n self.reqparse = reqparse.RequestParser()\n self.reqparse.add_argument(\n 'name',\n required=True,\n help='No name provided',\n location=['form', 'json']\n )\n super().__init__()\n\n def get(self):\n \"\"\"\n Return a list of tasks.\n Show all task to anonymous users.\n Show only users own tasks to logged-in users\n \"\"\"\n if g.user.is_anonymous:\n todos = [marshal(todo, todo_fields) for todo in models.Todo.select()]\n return todos\n else:\n todos = [marshal(todo, todo_fields) for todo in models.Todo.select()\n .where(models.Todo.created_by == g.user.id)]\n return todos\n\n @marshal_with(todo_fields)\n @auth.login_required\n def post(self):\n \"\"\"Post a new task and assign it to the current user\"\"\"\n args = self.reqparse.parse_args()\n todo = models.Todo.create(\n created_by=g.user,\n **args\n )\n return todo, 201, {'location': url_for('resources.todos.todo', id=todo.id)}\n\n\nclass Todo(Resource):\n def __init__(self):\n self.reqparse = reqparse.RequestParser()\n self.reqparse.add_argument(\n 'name',\n required=True,\n help='No name provided',\n location=['form', 'json']\n )\n self.reqparse.add_argument(\n 'edited',\n required=True,\n help='No edit state provided',\n location=['form', 'json'],\n type=inputs.boolean\n )\n self.reqparse.add_argument(\n 'completed',\n required=True,\n help='No completed state provided',\n location=['form', 'json'],\n type=inputs.boolean\n )\n self.reqparse.add_argument(\n 'updated_at',\n required=True,\n help='No updated_at time provided',\n location=['form', 'json'],\n )\n super().__init__()\n\n @marshal_with(todo_fields)\n def get(self, id):\n \"\"\"Return details of a single task.\"\"\"\n return todo_or_404(id)\n\n @marshal_with(todo_fields)\n @auth.login_required\n def put(self, id):\n \"\"\"\n Allow task owners to edit existing tasks.\n Prevent other users from editing tasks that do not belong to them.\n \"\"\"\n task_owner = models.Todo.get(models.Todo.id == id).created_by\n if g.user != task_owner:\n abort(400, message='Only the task owner can edit this task')\n else:\n args = self.reqparse.parse_args()\n args.edited = False\n args.updated_at = datetime.datetime.now()\n query = models.Todo.update(**args).where(models.Todo.id == id)\n query.execute()\n todo = todo_or_404(id)\n return todo, 200, {'location': url_for('resources.todos.todo', id=todo.id)}\n\n @auth.login_required\n def delete(self, id):\n \"\"\"\n Allow task owners to delete existing tasks.\n Prevent other users from deleting tasks that do not belong to them.\n \"\"\"\n try:\n task_owner = models.Todo.get(models.Todo.id == id).created_by\n except models.Todo.DoesNotExist:\n return make_response(json.dumps({'error': \"That TODO does not exist\"}), 403)\n if g.user != task_owner:\n abort(400, message='Only the task owner can delete this task')\n else:\n todo = models.Todo.get(models.Todo.id == id)\n todo.delete_instance()\n return '', 204,\n\n\ntodos_api = Blueprint('resources.todos', __name__)\napi = Api(todos_api)\n\napi.add_resource(\n TodoList,\n '/todos',\n endpoint='todos'\n)\n\napi.add_resource(\n Todo,\n '/todos/',\n endpoint='todo'\n)","sub_path":"resources/todos.py","file_name":"todos.py","file_ext":"py","file_size_in_byte":4611,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"203680678","text":"# -*- coding: utf-8 -*-\n\nimport base64\nimport hashlib\nimport MySQLdb.cursors\nimport os\n\n\nclass Backend:\n def __init__(self, host, port, db, user, passwd):\n self.db = MySQLdb.connect(host=host, port=port, db=db, user=user, passwd=passwd,\n cursorclass=MySQLdb.cursors.DictCursor)\n\n def __del__(self):\n if hasattr(self, 'db'):\n self.db.close()\n\n def domain_exists(self, login):\n domain_id = None\n\n cur = self.db.cursor()\n cur.execute(\"SELECT id FROM domains WHERE user_id = %s\" % self.user_get_id(login))\n\n if cur.rowcount > 0:\n domain_id = cur.fetchone()['id']\n\n cur.close()\n\n return domain_id is not None\n\n def domain_get_id(self, name):\n domain_id = None\n\n cur = self.db.cursor()\n cur.execute(\"SELECT id FROM domains WHERE name = '%s'\" % MySQLdb.escape_string(name))\n\n if cur.rowcount > 0:\n domain_id = cur.fetchone()['id']\n\n cur.close()\n\n return domain_id\n\n def domain_get_name(self, username):\n domain_name = None\n\n cur = self.db.cursor()\n cur.execute(\"SELECT domains.name FROM domains, users WHERE domains.user_id = users.id AND users.login = '%s'\" % MySQLdb.escape_string(username))\n\n if cur.rowcount > 0:\n domain_name = cur.fetchone()['name']\n\n cur.close()\n\n return domain_name\n\n def domain_list(self, filter=None):\n cur = self.db.cursor()\n\n cur.execute('''\n SELECT domains.id, users.login, domains.name\n FROM domains, users\n WHERE domains.user_id = users.id\n %s\n ORDER BY id\n ''' % (\"AND name LIKE '%%%s%%'\" % MySQLdb.escape_string(filter) if filter else ''))\n\n result = list(cur.fetchall())\n\n cur.close()\n\n return result\n\n def domain_set(self, **kwargs):\n args = []\n\n if kwargs.get('login') and not 'modify' in kwargs:\n args.append(('user_id', \"%s\" % self.user_get_id(kwargs.get('login'))))\n\n if kwargs.get('name'):\n args.append(('name', \"'%s'\" % MySQLdb.escape_string(kwargs.get('name'))))\n\n cur = self.db.cursor()\n\n if len(args) > 0:\n if 'modify' in kwargs:\n query = \"UPDATE domains SET %s WHERE user_id = %s\" % (', '.join([x + ' = ' + y for x, y in args]),\n self.user_get_id(kwargs.get('login')))\n else:\n query = 'INSERT INTO domains (%s) VALUES (%s)' % tuple([', '.join(x) for x in zip(*args)])\n cur.execute(query)\n self.db.commit()\n\n cur.close()\n\n def domain_unset(self, login):\n user_id = self.user_get_id(login)\n\n if not user_id:\n return False\n\n cur = self.db.cursor()\n cur.execute(\"DELETE FROM domains WHERE user_id = %d\" % user_id)\n cur.close()\n\n self.db.commit()\n\n def user_exists(self, login):\n return self.user_get_id(login) is not None\n\n def user_get_id(self, login):\n user_id = None\n\n cur = self.db.cursor()\n cur.execute(\"SELECT id FROM users WHERE login = '%s'\" % MySQLdb.escape_string(login))\n\n if cur.rowcount > 0:\n user_id = cur.fetchone()['id']\n\n cur.close()\n\n return user_id\n\n def user_list(self, filter=None):\n cur = self.db.cursor()\n\n cur.execute('''\n SELECT users.id, login, accessed, expires, allow_ftp, allow_sftp, issue_ref, clients.name, gid\n FROM users, clients\n WHERE users.client_id = clients.id\n %s\n ORDER BY id\n ''' % (\"AND login LIKE '%%%s%%'\" % MySQLdb.escape_string(filter) if filter else ''))\n\n result = list(cur.fetchall())\n\n cur.close()\n\n return result\n\n def user_set(self, **kwargs):\n args = []\n\n if kwargs.get('login') and not 'modify' in kwargs:\n args.append(('login', \"'%s'\" % MySQLdb.escape_string(kwargs.get('login'))))\n\n if kwargs.get('password'):\n args.append(('password', \"'%s'\" % MySQLdb.escape_string('{sha1}' +\n base64.b64encode(hashlib.sha1(kwargs.get('password')).digest()))))\n\n if kwargs.get('expires'):\n args.append(('expires', \"'%s'\" % MySQLdb.escape_string(kwargs.get('expires'))))\n\n if kwargs.get('protocols'):\n protocols = [x.strip().lower() for x in kwargs.get('protocols').split(',')]\n args.append(('allow_ftp', '%s' % ('TRUE' if 'ftp' in protocols else 'FALSE')))\n args.append(('allow_sftp', '%s' % ('TRUE' if 'sftp' in protocols else 'FALSE')))\n\n if kwargs.get('issue'):\n args.append(('issue_ref', \"'%s'\" % MySQLdb.escape_string(kwargs.get('issue'))))\n\n if kwargs.get('gid'):\n args.append(('gid', \"'%s'\" % MySQLdb.escape_string(kwargs.get('gid'))))\n\n cur = self.db.cursor()\n\n if kwargs.get('client'):\n cur.execute(\"SELECT id FROM clients WHERE name = '%(client)s' OR tag = '%(client)s'\" %\n {'client': MySQLdb.escape_string(kwargs.get('client'))})\n\n args.append(('client_id', MySQLdb.escape_string(str(cur.fetchone()['id']))))\n\n if len(args) > 0:\n\n if 'modify' in kwargs:\n query = \"UPDATE users SET %s WHERE login = '%s'\" % (', '.join([x + ' = ' + y for x, y in args]),\n MySQLdb.escape_string(kwargs.get('login')))\n else:\n query = 'INSERT INTO users (%s) VALUES (%s)' % tuple([', '.join(x) for x in zip(*args)])\n cur.execute(query)\n self.db.commit()\n\n cur.close()\n\n def user_unset(self, login):\n user_id = self.user_get_id(login)\n\n if not user_id:\n return False\n\n cur = self.db.cursor()\n cur.execute(\"DELETE FROM shares WHERE user_id = %d\" % user_id)\n cur.execute(\"DELETE FROM users WHERE id = %d\" % user_id)\n cur.close()\n\n self.db.commit()\n\n def share_contains(self, user_id, path):\n path = os.path.split(path)[0]\n\n while path:\n share_id = self.share_id(user_id, path)\n\n if share_id is not None:\n return share_id\n\n path = os.path.split(path)[0]\n\n return None\n\n def share_delete(self, share_id):\n cur = self.db.cursor()\n cur.execute(\"DELETE FROM shares WHERE id = %s\" % share_id)\n cur.close()\n\n self.db.commit()\n\n def share_exists(self, user_id, path):\n return self.share_id(user_id, path) is not None\n\n def share_get_path(self, share_id):\n result = None\n\n cur = self.db.cursor()\n\n cur.execute('SELECT share_path FROM shares WHERE id = %d' % share_id)\n\n if cur.rowcount > 0:\n result = cur.fetchone()['share_path']\n\n cur.close()\n\n return result\n\n def share_id(self, user_id, path):\n share_id = None\n\n cur = self.db.cursor()\n\n cur.execute(\"SELECT id FROM shares WHERE user_id = %s AND share_path = '%s'\" %\n (user_id, MySQLdb.escape_string(path)))\n\n if cur.rowcount > 0:\n share_id = cur.fetchone()['id']\n\n cur.close()\n\n return share_id\n\n def share_insert(self, user_id, path, writable, acl):\n args = [\n ('user_id', str(user_id)),\n ('share_path', \"'%s'\" % MySQLdb.escape_string(path)),\n ('writable', str(writable)),\n ('acl', str(acl))\n ]\n\n cur = self.db.cursor()\n cur.execute(\"INSERT INTO shares (%s) VALUES (%s)\" % tuple([', '.join(x) for x in zip(*args)]))\n cur.close()\n\n self.db.commit()\n\n def share_is_acl_set(self, share_id):\n is_acl_set = None\n\n cur = self.db.cursor()\n\n cur.execute(\"SELECT acl FROM shares WHERE id = %s\" % (share_id))\n\n if cur.rowcount > 0:\n is_acl_set = cur.fetchone()['acl']\n\n cur.close()\n\n return is_acl_set\n\n def share_intersect(self, user_id, path):\n result = None\n\n cur = self.db.cursor()\n\n query = '''\n SELECT id FROM shares\n WHERE user_id = %s\n AND share_path LIKE '%s/%%'\n ''' % (user_id, MySQLdb.escape_string(path))\n\n cur.execute(query)\n\n if cur.rowcount > 0:\n result = cur.fetchone()['id']\n\n cur.close()\n\n return result\n\n def share_list(self, user_id=None):\n cur = self.db.cursor()\n\n cur.execute('''\n SELECT shares.share_path, users.login, shares.writable, shares.acl\n FROM shares\n INNER JOIN users ON users.id = shares.user_id\n %s\n ORDER BY shares.share_path\n ''' % ('WHERE shares.user_id=%d' % user_id if user_id is not None else ''))\n\n result = list(cur.fetchall())\n\n cur.close()\n\n return result\n\n def share_update(self, share_id, writable):\n args = [\n ('writable', str(writable)),\n ]\n\n cur = self.db.cursor()\n cur.execute(\"UPDATE shares SET %s WHERE id = %s\" % (', '.join([x + ' = ' + y for x, y in args]), share_id))\n cur.close()\n\n self.db.commit()\n","sub_path":"scripts/arch_work_scripts/python/backend.py","file_name":"backend.py","file_ext":"py","file_size_in_byte":9162,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"565129217","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Mon May 24 08:38:41 2021\r\n\r\n@author: kevin\r\n\"\"\"\r\n\r\nimport numpy as np\r\nimport scipy as sp\r\nimport matplotlib.pyplot as plt\r\nimport scipy.signal as signal\r\n\r\nimport seaborn as sns\r\ncolor_names = [\"windows blue\", \"red\", \"amber\", \"faded green\"]\r\ncolors = sns.xkcd_palette(color_names)\r\nsns.set_style(\"white\")\r\nsns.set_context(\"talk\")\r\n\r\nimport matplotlib \r\nmatplotlib.rc('xtick', labelsize=25) \r\nmatplotlib.rc('ytick', labelsize=25) \r\n\r\n# %% low-rank network test\r\nN = 30\r\ndt = 0.1\r\nT = 1000\r\nlt = int(T/dt)\r\nn = np.random.randn(N)\r\nm = np.random.randn(N)\r\ng= .1\r\ntau = 0.1\r\nnoise = 0.\r\nJ = np.outer(n,m)/N + g**2*np.random.randn(N,N)/N\r\nxs = np.zeros((N,lt))\r\nrs = np.zeros((N,lt))\r\nIs = np.ones((N,lt))#np.random.randn(N,lt)\r\nfor tt in range(lt-1):\r\n rs[:,tt] = np.tanh(xs[:,tt])\r\n xs[:,tt+1] = xs[:,tt] + dt*(1/tau)*(-xs[:,tt] + J @ rs[:,tt] + n/N*Is[:,tt] + noise*np.random.randn(N)*np.sqrt(dt))\r\n \r\nplt.figure()\r\nplt.imshow(rs,aspect='auto')\r\n\r\n# %%\r\ndef LowD(Is, J, dt, T, noise=0):\r\n N = J.shape[0]\r\n lt = int(T/dt)\r\n xs = np.zeros((N,lt))\r\n rs = np.zeros((N,lt))\r\n for tt in range(lt-1):\r\n rs[:,tt] = np.tanh(xs[:,tt])\r\n xs[:,tt+1] = xs[:,tt] + dt*(1/tau)*(-xs[:,tt] + J @ rs[:,tt] + Is[:,tt] + noise*np.random.randn(N)*np.sqrt(dt))\r\n return rs, xs\r\n\r\ndef rotmnd(v,theta):\r\n nn = v.shape[0]\r\n M = np.eye(nn)\r\n for c in range(0,nn-2):\r\n for r in range(nn-1,c+1,-1):\r\n t = np.arctan2(v[r,c], v[r-1,c])\r\n R = np.eye(nn)\r\n #R[[r, r-1], [r, r-1]] = np.array([[np.cos(t), -np.sin(t)],[np.sin(t), np.cos(t)]])\r\n R[r,r] = np.cos(t)\r\n R[r,r-1] = -np.sin(t)\r\n R[r-1,r] = np.sin(t)\r\n R[r-1,r-1] = np.cos(t)\r\n v = R @ v\r\n M = R @ M\r\n R = np.eye(nn)\r\n #R[[n-1, n], [n-1, n]] = np.array([[np.cos(theta), -np.sin(theta)],[np.sin(theta), np.cos(theta)]])\r\n R[nn-2,nn-2] = np.cos(theta)\r\n R[nn-2,nn-1] = -np.sin(theta)\r\n R[nn-1,nn-2] = np.sin(theta)\r\n R[nn-1,nn-1] = np.cos(theta)\r\n M = np.linalg.solve(M, R @ M)\r\n return M\r\n#function M = rotmnd(v,theta)\r\n# n = size(v,1);\r\n# M = eye(n);\r\n# for c = 1:(n-2)\r\n# for r = n:-1:(c+1)\r\n# t = atan2(v(r,c),v(r-1,c));\r\n# R = eye(n);\r\n# R([r r-1],[r r-1]) = [cos(t) -sin(t); sin(t) cos(t)];\r\n# v = R*v;\r\n# M = R*M;\r\n# end\r\n# end\r\n# R = eye(n);\r\n# R([n-1 n],[n-1 n]) = [cos(theta) -sin(theta); sin(theta) cos(theta)];\r\n# M = M\\R*M;\r\n \r\ndef unit_vector(vector):\r\n \"\"\" Returns the unit vector of the vector. \"\"\"\r\n return vector / np.linalg.norm(vector)\r\n\r\ndef angle_between(v1, v2):\r\n \"\"\" Returns the angle in radians between vectors 'v1' and 'v2'::\r\n\r\n >>> angle_between((1, 0, 0), (0, 1, 0))\r\n 1.5707963267948966\r\n >>> angle_between((1, 0, 0), (1, 0, 0))\r\n 0.0\r\n >>> angle_between((1, 0, 0), (-1, 0, 0))\r\n 3.141592653589793\r\n \"\"\"\r\n v1_u = unit_vector(v1)\r\n v2_u = unit_vector(v2)\r\n return np.arccos(np.clip(np.abs(np.dot(v1_u, v2_u)), -1.0, 1.0))\r\n\r\ndef xcorr(x,y):\r\n \"\"\"\r\n Perform Cross-Correlation on x and y\r\n x : 1st signal\r\n y : 2nd signal\r\n\r\n returns\r\n lags : lags of correlation\r\n corr : coefficients of correlation\r\n \"\"\"\r\n corr = signal.correlate(x, y, mode=\"full\")\r\n lags = signal.correlation_lags(len(x), len(y), mode=\"full\")\r\n return lags, corr\r\n\r\n# %%\r\nbasis = np.eye(N)\r\nbasis = basis[:,:N-2]\r\nR = rotmnd(basis,np.pi/2)\r\n\r\n# %%\r\n## prep for orthogonal normal vector and rotation matrix\r\nrandM1 = np.random.randn(N,N)\r\nrandM2 = np.random.randn(N,N)\r\nuu,ss,vv = np.linalg.svd(randM1)\r\nqq,rr = np.linalg.qr(randM2)\r\nn = uu[:,0] #np.random.randn(N)\r\nm = uu[:,1] #@ qq#np.random.randn(N,N) #np.random.randn(N)\r\ng= 1.\r\ntau = 0.1\r\nnoise = 0.01\r\nJ = np.outer(n,m)/N + g**2*np.random.randn(N,N)/N + np.outer(uu[:,2], uu[:,3])/N*0\r\npe = 20\r\nIn_ang = np.convolve(np.random.randn(lt),np.ones(pe),'same')/pe*np.pi #target\r\nIn_ang = (In_ang-np.min(In_ang))/(np.max(In_ang)-np.min(In_ang))\r\nIn_ang = np.cos(np.arange(0,T,dt)/pe)\r\nIn_ang = (In_ang + 1)/2\r\nIm_ang = np.convolve(np.random.randn(lt),np.ones(pe),'same')/pe*np.pi #decoding angle\r\nIm_ang = (Im_ang-np.min(Im_ang))/(np.max(Im_ang)-np.min(Im_ang))\r\n#Im_ang = signal.sawtooth(np.arange(0,T,dt)/pe, 0.5)\r\n#Im_ang = np.cos(np.arange(0,T,dt)/pe)#*np.pi\r\n#Im_ang = (Im_ang + 1)/2\r\n\r\n#test = np.sin(np.arange(0,T,dt)/pe)\r\n#ang = np.sin(np.arange(0,T,dt)/pe)*np.pi\r\n#Is = np.zeros((N,lt))\r\n#for ii in range(lt):\r\n# R = rotmnd(basis,ang[ii]) #rotating the angle\r\n# Is[:,ii] = n @ R * I[ii]\r\n#nI = n#n @ rr #np.random.randn(N,N)\r\nIn = np.matmul(n[:,None], (In_ang)[None,:])\r\nIm = np.matmul(m[:,None], (Im_ang)[None,:])\r\nIs = In*(1-Im_ang*1) + Im*1\r\nangs = np.zeros(lt)\r\nfor ii in range(lt):\r\n angs[ii] = angle_between(n,Is[:,ii])\r\nrs, xs = LowD(Is,J,dt,T,noise)\r\n\r\nrec_I = rs.T @ m\r\nerr = np.abs(In_ang-rec_I)**2\r\n#rec_angs = np.zeros(lt)\r\n#for ii in range(lt):\r\n# rec_angs[ii] = angle_between(n,rs[:,ii])\r\n\r\nplt.figure()\r\nplt.imshow(rs,aspect='auto')\r\nplt.figure()\r\nplt.plot(In_ang)\r\nplt.plot(rec_I)\r\nplt.plot(err,'--')\r\nplt.plot(angs,'k--')\r\nplt.figure()\r\nplt.plot(Im_ang,err,'o')\r\n\r\nww = np.abs(np.diff(angs)/dt)\r\nlag = np.abs(rec_I[:-1] - In_ang[:-1])**1\r\nplt.figure()\r\nplt.plot(ww,lag,'o',alpha=0.5)\r\n\r\n\r\n# %%\r\n###############################################################################\r\n###############################################################################\r\n\r\n# %% Low-rank fields\r\nT = 1000\r\ndt = 0.1\r\ntau = 0.1\r\nlt = int(T/dt)\r\nN = 50\r\nspe = 3.5\r\ng = .1\r\ndd = np.arange(0,N)\r\naa, bb = np.sin(dd/spe), np.cos(dd/spe)\r\nJ = 1*np.outer(aa,bb)/N + g**2*np.random.randn(N,N)/N\r\n#plt.imshow(J,aspect='auto')\r\nI = np.zeros((N,lt))#np.random.randn(N,lt)\r\nI[22:28,0:100] = 1\r\nx = np.zeros((N,lt))\r\ndef sigm(x):\r\n return 1/(1+np.exp(x))\r\nfor tt in range(lt-1):\r\n x[:,tt+1] = x[:,tt] + dt*(-x[:,tt]/tau + J @ sigm(x[:,tt]) - 0*x[:,tt]**3 + I[:,tt] + np.random.randn(N)*0.01)\r\n \r\nplt.figure()\r\nplt.imshow(x,aspect='auto')\r\n\r\n","sub_path":"LowRank_test.py","file_name":"LowRank_test.py","file_ext":"py","file_size_in_byte":6176,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"296851211","text":"import dataAccessSQLAlchemy as da\nimport pandas as pd\nimport numpy\nimport random\nimport numpy as np\n\n#n_classes = 14\n#n_days = 5\n#n_slots = 10\n#n_max_lecs_per_slot = 4\n\n\ndef teacher_overlap(timetable, req_all, n_days, n_slots):\n \"Calculates number of teacher overlaps for all days and all slots\"\n\n teacher_cost = 0\n for day in range(n_days):\n for slot in range (n_slots):\n temp_array = timetable[:, day, slot, :]\n teacher_list = []\n #print(temp_array)\n for row in temp_array:\n for cell in row:\n if not np.isnan(cell):\n req = req_all.loc[req_all.index == cell]\n teacher_list.append(req.iloc[0]['teacherId'])\n for teacher_id in teacher_list:\n if teacher_id is not None:\n teacher_cost = teacher_cost + teacher_list.count(teacher_id) - 1\n \n\n return teacher_cost\n\n\n\ndef get_room_allocation_overflow (timetable, req_all, n_days, n_slots, max_theory, max_lab):\n \"Checks for a day and slot, maximum allocations possible for a room\"\n\n room_cost = 0\n for day in range(n_days):\n for slot in range (n_slots):\n temp_array = timetable[:, day, slot, :]\n req_list = []\n for row in temp_array:\n for cell in row:\n if not np.isnan(cell):\n req = req_all.loc[req_all.index == cell]\n #print(req);\n if (req.iloc[0]['category'] == 'T'):\n max_theory -= 1\n else:\n max_lab -= 1\n #print(max_theory);\n #print(max_lab);\n if (max_theory < 0):\n room_cost = room_cost + -(max_theory) \n if (max_lab < 0):\n room_cost = room_cost + -(max_lab) \n \n \n return room_cost\n\n\ndef class_batch_overlap(timetable, req_all):\n \"\"\"Calculates overlaps for theory classes and (non allowed) overlaps for batches and increments cost accordingly\"\"\"\n\n class_cost = 0\n batch_cost = 0\n\n n_classes, n_days, n_slots, n_max_lec_per_slot=timetable.shape\n f_batch_can_overlap = da.initialize('batchcanoverlap');\n\n for cl in range(n_classes):\n for day in range(n_days):\n for slot in range(n_slots):\n class_list = []\n batch_list = []\n slot_array = timetable[cl,day,slot,:]\n # Make 2 lists-class_list having all classes in the sub-slot & batch-list having all batches in sub-slot\n # Classes have category 'T' and Batches have category 'L'\n for sub_slot in slot_array:\n if not np.isnan(sub_slot):\n req = req_all.loc[req_all.index == sub_slot]\n if req.iloc[0]['category'] == 'T': # Class clash can be removed\n class_list.append(req.iloc[0]['classId'])\n elif req.iloc[0]['category'] == 'L':\n batch_list.append(req.iloc[0]['batchId'])\n\n # If the same class is repeated in the class_list for the same sub-slot, increment cost\n if len(class_list) > 1 : # Cost will be incremented only if multiple classes in same sub-slot\n for class_id in class_list: class_cost = class_cost + class_list.count(class_id) - 1\n\n if len(batch_list)>1: # Cost will be incremented only if multiple batches in same sub-slot\n for batch_id in batch_list: # In case same batch is slotted more than once in sub slot\n batch_cost = batch_cost + batch_list.count(batch_id) - 1\n # 1. Consider first batch in batch_list.\n # 2. Get all batches that are allowed to overlap\n # 3. Loop over all batches in batch_list. If any batch does'nt belong to this list, cost incremented\n batch_id = batch_list[0]\n batches_can_overlap = f_batch_can_overlap[f_batch_can_overlap['batchId'] == batch_id]\n batches_all = batches_can_overlap[batches_can_overlap.columns[2:3]] # get batch_can_overlap column batches_all_list = batches_all['batchOverlapId'].tolist()\n batches_all_list.append(batch_id)\n for batch in batch_list:\n if batch not in batches_all_list:\n batch_cost += 1\n\n return class_cost + batch_cost\n\n \n## To be tested\n\ndef getting_lunch_break (timetable, n_days, n_slots, n_classes):\n \"Checks if a class is getting lunch break\"\n\n lunch_break_cost = 0;\n\n # Check for all classes if the lunch break is available\n for classId in range (n_classes):\n for day in range(n_days): #this is wrong\n if (not (np.isnan (timetable[classId, day, 4, :]) or np.isnan (timetable[classId, day, 5, :]) or np.isnan (timetable[classId, day, 6, :]))):\n lunch_break_cost += 1;\n\n return lunch_break_cost;\n\ndef req_missing(timetable, req_all):\n n_classes, n_days, n_slots, n_maxlecsperslot = timetable.shape\n penalty=0\n for c in range(n_classes):\n req_for_c = req_all.loc[req_all['classId'] == c]\n s = np.unique(timetable[c])\n missing = [x for x in req_for_c.index if x not in s]\n penalty=penalty+len(missing)\n if(len(missing)>0):\n print(c, len(missing))\n return penalty\n\n\n## To be tested\n\ndef subject_on_same_day (timetable, req_all, classId, n_days, n_slots):\n \"Finds out if requirements of same subject fall on same day\"\n\n req_classId = req_all.loc[req_all['classId'] == classId]\n subjects = req_classId['subjectId'] \n\n\n\n print(subjects);\n\n\ndef get_cost(tt, req_all, n_classes, n_days, n_slots, max_theory, max_lab):\n \"Calculates all costs for time table\"\n\n # weights\n w_teacher = w_room = w_batch_class = 1;\n w_lunch_break = 1;\n\n # Varoius costs\n c_teacher = teacher_overlap (tt, req_all, n_days, n_slots);\n c_room = get_room_allocation_overflow (tt, req_all, n_days, n_slots, max_theory, max_lab);\n c_batch_class = class_batch_overlap (tt, req_all);\n #c_lunch_break = getting_lunch_break(tt, n_days, n_slots, n_classes);\n \n # Actual cost\n cost = w_teacher * c_teacher + w_room * c_room + w_batch_class * c_batch_class;\n\n # Print costs\n print(\"Teacher cost: \", c_teacher);\n print(\"Room cost: \", c_room);\n print(\"Batch-class overlap cost: \", c_batch_class);\n #print(\"Lunch break cost: \", c_lunch_break);\n\n return cost;\n\n","sub_path":"TimeTable1/costFunctions.py","file_name":"costFunctions.py","file_ext":"py","file_size_in_byte":6680,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"465840242","text":"#! /bin/python\n\nfrom sys import stdin\n\nT = int(stdin.readline())\n\nfor t in range(T):\n [R, C] = [int(x) for x in stdin.readline().split()]\n cake = []\n for _ in range(R):\n cake.append([x for x in stdin.readline().strip()])\n\n firstLine = True\n for r in range(R):\n letterOnLine = '?'\n for c in range(C):\n l = cake[r][c]\n if l == '?':\n cake[r][c] = letterOnLine\n continue\n\n if letterOnLine == '?':\n cake[r][:c] = [l]*c\n cake[r][c] = l\n letterOnLine = l\n\n if letterOnLine == '?' and not firstLine:\n cake[r] = cake[r-1][:]\n elif firstLine and not letterOnLine == '?':\n for k in range(r):\n cake[k] = cake[r][:]\n if not letterOnLine == '?':\n firstLine = False\n\n\n print(\"Case #{}: \".format(t+1))\n for r in range(R):\n print(\"\".join(cake[r]))\n","sub_path":"solutions_python/Problem_203/304.py","file_name":"304.py","file_ext":"py","file_size_in_byte":949,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"233068891","text":"#!/usr/bin/python\n\nfrom getFreq import getFrequency as getFreq\nfrom datetime import datetime as date\nfrom os import makedirs as mkdir\nfrom os.path import exists\nfrom os.path import dirname\nfrom os import rename as move\n\n# Have a Current Test Directory That Always has Current Test...\n# When This Runs, create new Directory for this report and raw data.\n# Generate Report in Current Test Directory\n# Move Report and All Raw Files to New Directory\n\ncwd = \"/home/pi/CurrentTest/\"\narchivesDirectory = \"/home/pi/ArchivedTests/\"\n\ndef readRedValues():\n\tred = []\n\tfilename = cwd + \"RGB.txt\"\n\tf = open(filename, 'r')\n\tfor line in f:\n\t\tdata = line.split(\"\\t\")\n\t\tred.append(data[0])\n\tf.close()\n\tred.pop(0)\n\treturn map(int, red)\n\ndef readGreenValues():\n\tgreen = []\n\tfilename = cwd + \"RGB.txt\"\n\tf = open(filename, 'r')\n\tfor line in f:\n\t\tdata = line.split(\"\\t\")\n\t\tgreen.append(data[1])\n\tf.close()\n\tgreen.pop(0)\n\treturn map(int, green)\n\ndef readBlueValues():\n\tblue = []\n\tfilename = cwd + \"RGB.txt\"\n\tf = open(filename, 'r')\n\tfor line in f:\n\t\tdata = line.split(\"\\t\")\n\t\tblue.append(data[2])\n\tf.close()\n\tblue.pop(0)\n\treturn map(int, blue)\n\ndef readClearValues():\n\tclear = []\n\tfilename = cwd + \"RGB.txt\"\n\tf = open(filename, 'r')\n\tfor line in f:\n\t\tdata = line.split(\"\\t\")\n\t\tclear.append(data[3])\n\tf.close()\n\tclear.pop(0)\n\treturn map(int, clear)\n\ndef readTempValues():\n\ttemp = []\n\tfilename = cwd + \"RGB.txt\"\n\tf = open(filename, 'r')\n\tfor line in f:\n\t\tdata = line.split(\"\\t\")\n\t\ttemp.append(data[4])\n\tf.close()\n\ttemp.pop(0)\n\treturn map(int, temp)\n\ndef readLuxValues():\n\tlux = []\n\tfilename = cwd + \"RGB.txt\"\n\tf = open(filename, 'r')\n\tfor line in f:\n\t\tdata = line.split(\"\\t\")\n\t\tlux.append(data[5])\n\tf.close()\n\tlux.pop(0)\n\treturn map(int, lux)\n\ndef readBlue2Values():\n\tblue2 = []\n\tfilename = cwd + \"Blue.txt\"\n\tf = open(filename, 'r')\n\tfor line in f:\n\t\tdata = line.split(\"\\n\")\n\t\tblue2.append(data[0])\n\tf.close()\n\tblue2.pop(0)\n\treturn map(int, blue2)\t\n\ndef readIRValues():\n\tir = []\n\tfilename = cwd + \"UV+IR.txt\"\n\tf = open(filename, 'r')\n\tfor line in f:\n\t\tdata = line.split(\"\\t\")\n\t\tir.append(data[1])\n\tf.close()\n\tir.pop(0)\n\treturn map(int, ir)\n\t\ndef readUVValues():\n\tuv = []\n\tfilename = cwd + \"UV+IR.txt\"\n\tf = open(filename, 'r')\n\tfor line in f:\n\t\tdata = line.split(\"\\t\")\n\t\tuv.append(data[2])\n\tf.close()\n\tuv.pop(0)\n\treturn map(int, uv)\n\ndef readUVIndexes():\n\tindexes = []\n\tfilename = cwd + \"UV+IR.txt\"\n\tf = open(filename, 'r')\n\tfor line in f:\n\t\tdata = line.split(\"\\t\")\n\t\tindexes.append(data[3])\n\tf.close()\n\tindexes.pop(0)\n\treturn map(int, indexes)\n\t\ndef getAverage(list):\n\ttotal = 0.0\n\tcount = 0.0\n\tfor x in list:\n\t\ttotal += x\n\t\tcount += 1\n\treturn (total/float(count))\n\t\ndef relocate(timestamp):\n\tdateStamp = date.now()\n\tyear = str(dateStamp.year)\n\tmonth = str(dateStamp.month)\n\tday = str(dateStamp.day)\n\t\n\tnewDir = (archivesDirectory + year + \"/\" + month + \"/\" + day + \"/\" + timestamp + \"/\")\n\t\n\tdir = dirname(newDir)\n\t\n\tif not exists(dir):\n\t\tmkdir(dir)\n\t\n\tsrc = cwd + \"*\"\n\tdst = newDir + \"*\"\n\tmove(src, dst)\n\ndef main():\n\tred =int(getAverage(readRedValues()))\n\tgreen = int(getAverage(readGreenValues()))\n\tblue = int(getAverage(readBlueValues()))\n\tblue2 = int(getAverage(readBlue2Values()))\n\ttemp = int(getAverage(readTempValues()))\n\tlux = int(getAverage(readLuxValues()))\n\tuv = int(getAverage(readUVValues()))\n\tir = int(getAverage(readIRValues()))\n\tindex = int(getAverage(readUVIndexes()))\n\tflicker = getFreq()\n\t\n\ttime = date.now()\n\t\n\thour = str(time.hour)\n\tmin = str(time.minute)\n\tsec = str(time.second)\n\t\n\ttimestamp = (hour + \"_\" + min + \"_\" + sec)\n\tfilepath = cwd + timestamp + \".rep\"\n\t\n\tprint (timestamp + \".rep\")\n\n\tf = open(filepath, 'w')\n\t\t\n\tf.write((\"Red = \" + str(red) + \"\\n\"))\n\tf.write((\"Green = \" + str(green) + \"\\n\"))\n\tf.write((\"Blue = \" + str(blue) + \"\\n\"))\n\tf.write((\"480 nm = \" + str(blue2) + \"\\n\"))\n\tf.write((\"UV = \" + str(uv) + \"\\n\"))\n\tf.write((\"IR = \" + str(ir) + \"\\n\"))\n\tf.write((\"Flicker = \" + str(flicker) + \" Hz\\n\"))\n\tf.write((\"Color Temp = \" + str(temp) + \" K \\n\"))\n\tf.write((\"Lux = \" + str(lux) + \" K \\n\"))\n\tf.write((\"UV Index = \" + str(index) + \"\\n\"))\n\t\n\tf.close()\n\t\n\t#relocate(timestamp)\n\t\n\t\n#============ Main Method Referral ============#\nif __name__ == \"__main__\":\n main()\n\n","sub_path":"Portable-Light-Sensor/PythonBackup/Report/makeReport.py","file_name":"makeReport.py","file_ext":"py","file_size_in_byte":4176,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"31713516","text":"__author__ = 'mona esmaeili'\r\n\r\n\r\nfrom collections import defaultdict\r\nimport csv\r\nimport numpy as np\r\nfrom itertools import izip, tee, islice\r\n\r\ndef take(n, iterable):\r\n \"Return first n items of the iterable as a list\"\r\n return list(islice(iterable, n))\r\ndef pairwise(iterable):\r\n #\"s -> (s0,s1), (s1,s2), (s2, s3), ...\"\r\n a, b = tee(iterable)\r\n next(b, None)\r\n return izip(a, b)\r\n\r\ndef read_file(filename):\r\n Domains=defaultdict(list)\r\n Domains_dif=defaultdict(list)\r\n with open(filename, \"rU\") as my_file:\r\n reader = csv.reader(my_file, dialect=csv.excel_tab, delimiter='\\t')\r\n #reader=[my_file.next().strip() for i in xrange(lines_to_read)]\r\n for row in reader:\r\n #domain,_, timestamp = row.partition(\"\\t\")\r\n domain=row[0]\r\n time_stamp=row[1]\r\n if domain != \"\":\r\n Domains[domain].append(time_stamp)\r\n for domain in Domains:\r\n Domains[domain]=sorted(Domains[domain])\r\n Domains_dif[domain]=[(int(y) - int(x)) for x,y in pairwise(Domains[domain])]\r\n return Domains, Domains_dif\r\ndef num_ad_timeinterval(Domain_dif, time_interval):\r\n DomainFreq=defaultdict(list)\r\n ti=time_interval*3600\r\n for user in Domain_dif.keys():\r\n imp_count=0\r\n for time_diff in Domain_dif[user]:\r\n if time_diff <= ti and time_diff >0:\r\n imp_count += 1\r\n else:\r\n DomainFreq[user].append(imp_count)\r\n\r\n return DomainFreq\r\n\r\ndef stats (DomainFreq):\r\n Mean=defaultdict(float)\r\n Deviation=defaultdict(float)\r\n for domain in DomainFreq.keys():\r\n Mean[domain]= np.mean(DomainFreq[domain])\r\n Deviation[domain]=np.std(DomainFreq[domain])\r\n return Mean, Deviation\r\ndef main():\r\n Domain_Frequency =defaultdict(list)\r\n time_interval=24\r\n filename = 'file1.csv'\r\n Domains, Domain_dif= read_file(filename)\r\n Domain_Frequency=num_ad_timeinterval(Domain_dif, time_interval)\r\n Mean, Deviation = stats (Domain_Frequency)\r\n writer = csv.writer(open('file2.csv', 'w'))\r\n for key, value in Domain_Frequency.items():\r\n writer.writerow([key, value])\r\n writer = csv.writer(open('file3.csv', 'w'))\r\n for key, value in Mean.items():\r\n writer.writerow([key, value])\r\n\r\n writer = csv.writer(open('file4.csv', 'w'))\r\n for key, value in Deviation.items():\r\n writer.writerow([key, value])\r\n\r\nif __name__ == '__main__':\r\n main()\r\n","sub_path":"Intrusiondetection.py","file_name":"Intrusiondetection.py","file_ext":"py","file_size_in_byte":2464,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"203124082","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Aug 22 14:58:29 2018\n\n@author: CV_LAB_Howard\n\"\"\"\n\nimport time\nimport argparse\nfrom naoqi import ALProxy\n\ndef main(robotIP, PORT = 9559):\n motionProxy = ALProxy(\"ALMotion\", robotIP, PORT)\n postureProxy = ALProxy(\"ALRobotPosture\", robotIP, PORT)\n\n # Wake up robot\n motionProxy.wakeUp()\n\n # Send robot to Stand Init\n postureProxy.goToPosture(\"StandInit\", 0.5)\n\n # Example showing multiple trajectories\n # Interpolate the head yaw to 1.0 radian and back to zero in 2.0 seconds\n # while interpolating HeadPitch up and down over a longer period.\n names = [\"HeadYaw\",\"HeadPitch\"]\n # Each joint can have lists of different lengths, but the number of\n # angles and the number of times must be the same for each joint.\n # Here, the second joint (\"HeadPitch\") has three angles, and\n # three corresponding times.\n angleLists = [[1.0, 0.0], [-0.5, 0.5, 0.0]]\n timeLists = [[1.0, 2.0], [ 1.0, 2.0, 3.0]]\n isAbsolute = True\n motionProxy.angleInterpolation(names, angleLists, timeLists, isAbsolute)\n\n time.sleep(1.0)\n\n # Example showing a single target for one joint\n names = \"HeadYaw\"\n targetAngles = 1.0\n maxSpeedFraction = 1 # Using 20% of maximum joint speed\n motionProxy.angleInterpolationWithSpeed(names, targetAngles, maxSpeedFraction)\n\n time.sleep(1.0)\n\n # Example showing multiple joints\n # Instead of listing each joint, you can use a chain name, which will\n # be expanded to contain all the joints in the chain. In this case,\n # \"Head\" will be interpreted as [\"HeadYaw\", \"HeadPitch\"]\n names = \"RWristYaw\"\n # We still need to specify the correct number of target angles\n targetAngles = 1\n maxSpeedFraction = 1 # Using 20% of maximum joint speed\n motionProxy.angleInterpolationWithSpeed(names, targetAngles, maxSpeedFraction)\n '''\n # Example showing body zero position\n # Instead of listing each joint, you can use a the name \"Body\"\n names = \"Body\"\n # We still need to specify the correct number of target angles, so\n # we need to find the number of joints that this Nao has.\n # Here we are using the getBodyNames method, which tells us all\n # the names of the joints in the alias \"Body\".\n # We could have used this list for the \"names\" parameter.\n numJoints = len(motionProxy.getBodyNames(\"Body\"))\n # Make a list of the correct length. All angles are zero.\n targetAngles = [0.0]*numJoints\n # Using 10% of maximum joint speed\n maxSpeedFraction = 0.2\n motionProxy.angleInterpolationWithSpeed(names, targetAngles, maxSpeedFraction)\n\n # Go to rest position\n motionProxy.rest()\n '''\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--ip\", type=str, default=\"127.0.0.1\",\n help=\"Robot ip address\")\n parser.add_argument(\"--port\", type=int, default=9559,\n help=\"Robot port number\")\n\n args = parser.parse_args()\n main(args.ip, args.port)","sub_path":"Motion_Part/bezier_test.py","file_name":"bezier_test.py","file_ext":"py","file_size_in_byte":3048,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"398364864","text":"# !/usr/bin/python\n# -*- coding: utf-8 -*-\n\"\"\"Tests for Test event formatter.\"\"\"\n\nimport unittest\n\nfrom plaso.formatters import test\nfrom tests.formatters import test_lib\n\n\nclass TestUsersFormatterTest(test_lib.EventFormatterTestCase):\n \"\"\"Tests the Test users event formatter.\"\"\"\n\n def testInitialization(self):\n \"\"\"Tests the initialization.\"\"\"\n event_formatter = test.TestUsersFormatter()\n self.assertIsNotNone(event_formatter)\n\n def testGetFormatStringAttributeNames(self):\n \"\"\"Tests the GetFormatStringAttributeNames function.\"\"\"\n event_formatter = test.TestUsersFormatter()\n\n expected_attribute_names = [\n u'advertiser_account_type', u'analytics_type', u'bio_entities',\n u'business_profile_state', u'could_be_stale', u'description',\n u'device_following', u'extended_profile_fields', u'favorites_count',\n u'followers_count', u'followers_count_fast', u'followers_count_normal',\n u'following', u'following_count', u'has_collections',\n u'has_extended_profile_fields', u'id', u'is_lifeline_institution',\n u'is_translator', u'location', u'media_count', u'name',\n u'pinned_tweet_id', u'profile_banner_url', u'profile_image_url',\n u'profile_link_color_hex_triplet', u'protected', u'screen_name',\n u'statuses_count', u'structured_location', u'url', u'url_entities',\n u'verified'\n ]\n\n self._TestGetFormatStringAttributeNames(\n event_formatter, expected_attribute_names)\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"tests/end_to_end_test/ExpectedEasyGenerationOwnColumnNameFiles/formatters_test.py","file_name":"formatters_test.py","file_ext":"py","file_size_in_byte":1523,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"176862509","text":"#!/usr/bin/env python3\nimport numpy as np\nimport cv2\nimport time\nimport datetime\n\ncap = cv2.VideoCapture(0)\nstart_time = time.time()\nframes_per_second = 5\nframeIndex = 0\n\nfont = cv2.FONT_HERSHEY_SIMPLEX\n\nwhile(True):\n ret, raw_frame = cap.read()\n frame = cv2.cvtColor(raw_frame, cv2.IMREAD_COLOR)\n height, width = frame.shape[:2] \n \n cv2.imshow('frame',frame)\n \n if cv2.waitKey(1) & 0xFF == ord('c'): \n cv2.putText(frame,'Frame: ' + str(frameIndex) + ': ' + str(datetime.datetime.now()),(10,height-20), font, 1, (200,255,155), 2, cv2.LINE_AA)\n cv2.imwrite('/home/pi/Pictures/recording/frame' + str(frameIndex) + '.jpg', frame)\n frameIndex += 1\n \n if cv2.waitKey(1) & 0xFF == ord('q'): \n break\n\ncap.release()\ncv2.destroyAllWindows()\n\n","sub_path":"video_frame_capture.py","file_name":"video_frame_capture.py","file_ext":"py","file_size_in_byte":799,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"211490891","text":"#!/usr/bin/env python3\n# -*- coding: utf-8-unix -*-\n\nfrom __future__ import print_function\n\nfrom binascii import hexlify\nfrom serial import Serial\nfrom IPython import embed\nfrom ucdev.register import Register\n\nimport wx\nimport sys\nimport os\n\nCMD = Register(\"\"\"\n:8 START_EX:8 START_HI:8 START_LO:8 STEP:8 SAMPLE:8 XPLOT_HI:8 XPLOT_LO:8\n:8 RBW:8 BAND:8 TG:8 ADJUST:8\n:8 SG_EX:8 SG_HI:8 SG_LO:8 SG_BAND:8 DELAY:8 ADCH:8 NV10V:8\n\"\"\", 0)\n\ndef gencmd():\n \"\"\"Control command for GigaSt v4\"\"\"\n cmd = CMD()\n\n # start = N * 20KHz\n cmd.START_EX = 0x00\n cmd.START_HI = 0x01\n cmd.START_LO = 0xF4\n\n # step = N * 20KHz\n cmd.STEP = 250\n\n cmd.SAMPLE = 1\n cmd.XPLOT_HI = 1\n cmd.XPLOT_LO = 244\n\n # 0 = 250KHz, 1 = 50KHz\n cmd.RBW = 0\n\n cmd.BAND = 1\n cmd.TG = 0\n\n # 0 in -127..127 range\n cmd.ADJUST = 127\n\n cmd.SG_EX = 0\n cmd.SG_HI = 0\n cmd.SG_LO = 0\n cmd.SG_BAND = 0\n\n # delay = N * 100us\n cmd.DELAY = 1\n\n cmd.ADCH = 0\n cmd.NV10V = 0\n return cmd\n\ndef connect(port=\"/dev/ttyUSB0\"):\n return Serial(port=port, baudrate=38400)\n\ndef main():\n sp = connect()\n cmd = gencmd()\n sp.write(cmd.value.bytes)\n for i in range(500):\n ret = sp.read(2)\n print(hexlify(ret))\n ret = sp.read(3)\n print(hexlify(ret))\n\nif __name__ == '__main__' and '__file__' in globals():\n main()\n\n","sub_path":"tmp/scan-plot.py","file_name":"scan-plot.py","file_ext":"py","file_size_in_byte":1356,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"83074726","text":"import discord\nfrom discord.utils import escape_markdown\nfrom io import BytesIO\nimport re\n\n\nSMART_QUOTE_REPLACEMENT_DICT = {\n \"\\u2018\": \"'\", # Left single quote\n \"\\u2019\": \"'\", # Right single quote\n \"\\u201C\": '\"', # Left double quote\n \"\\u201D\": '\"', # Right double quote\n}\n\nSMART_QUOTE_REPLACE_RE = re.compile(\"|\".join(SMART_QUOTE_REPLACEMENT_DICT.keys()))\n\n\ndef escape(text: str, *, mass_mentions: bool = False, formatting: bool = False) -> str:\n \"\"\"\n Get text with all mass mentions or markdown escaped.\n\n Parameters\n ----------\n text : str\n The text to be escaped.\n mass_mentions : `bool`, optional\n Set to :code:`True` to escape mass mentions in the text.\n formatting : `bool`, optional\n Set to :code:`True` to escape any markdown formatting in the text.\n\n Returns\n -------\n str\n The escaped text.\n\n \"\"\"\n if mass_mentions:\n text = text.replace(\"@everyone\", \"@\\u200beveryone\")\n text = text.replace(\"@here\", \"@\\u200bhere\")\n if formatting:\n text = escape_markdown(text)\n return text\n\n\ndef bold(text: str, escape_formatting: bool = True) -> str:\n \"\"\"\n Get the given text in bold.\n\n Note: By default, this function will escape ``text`` prior to emboldening.\n\n Parameters\n ----------\n text : str\n The text to be marked up.\n escape_formatting : `bool`, optional\n Set to :code:`False` to not escape markdown formatting in the text.\n\n Returns\n -------\n str\n The marked up text.\n\n \"\"\"\n text = escape(text, formatting=escape_formatting)\n return \"**{}**\".format(text)\n\n\ndef code_block(text: str, lang: str = \"\") -> str:\n \"\"\"\n Get the given text in a code block.\n\n Parameters\n ----------\n text : str\n The text to be marked up.\n lang : `str`, optional\n The syntax highlighting language for the codeblock.\n\n Returns\n -------\n str\n The marked up text.\n\n \"\"\"\n ret = \"```{}\\n{}\\n```\".format(lang, text)\n return ret\n\n\ndef normalize_smartquotes(to_normalize: str) -> str:\n \"\"\"\n Get a string with smart quotes replaced with normal ones\n\n Parameters\n ----------\n to_normalize : str\n The string to normalize.\n\n Returns\n -------\n str\n The normalized string.\n \"\"\"\n\n def replacement_for(obj):\n return SMART_QUOTE_REPLACEMENT_DICT.get(obj.group(0), \"\")\n\n return SMART_QUOTE_REPLACE_RE.sub(replacement_for, to_normalize)\n\n\n# noinspection PyPep8Naming\nclass plural:\n \"\"\"\n Formats a string to singular or plural based on the length objects it refers to.\n\n Examples\n --------\n - 'plural(len(data)):member'\n - 'plural(len(data)):entry|entries'\n \"\"\"\n\n def __init__(self, value):\n self.value = value\n\n def __format__(self, format_spec):\n v = self.value\n singular, sep, plural = format_spec.partition(\"|\")\n plural = plural or f\"{singular}s\"\n if abs(v) != 1:\n return f\"{v} {plural}\"\n return f\"{v} {singular}\"\n","sub_path":"trivia/utils/chat_formatting.py","file_name":"chat_formatting.py","file_ext":"py","file_size_in_byte":3035,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"597784244","text":"\"\"\"Resource cacher and controller.\"\"\"\nimport sys\nimport time\n\nimport logging\nlog = logging.getLogger(__name__)\n\nimport pylons\n\nfrom pylons.templating import render_mako\nfrom pylons.controllers.util import abort\n\nfrom codalib.util import getdotprefixed\nfrom codalib.paste.converters import asdict\nfrom paste.deploy.converters import asbool\n\n\ntry:\n import Crypto\n\nexcept ImportError:\n log.warning('pyCrypto is not available. Using the insecure `codalib.util.randstr` instead of `codalib.crypto.urandstr`')\n from codalib.util import randstr\n\nelse:\n from codalib.crypto import urandstr as randstr\n\n\ndef resource_config(config, prefix = \"resources.\"):\n config_data = getdotprefixed(config, prefix = prefix)\n\n config['%stemplates' % prefix] = asdict(config_data['templates'])\n config['%sassignments' % prefix] = asdict(config_data['assignments'])\n\n return config\n \nimport time\n\n# should this be threaded?? perhaps!\n# But if the page requests the cache before the item is cached, that could be bad.\ndef resource_cache(key, template_uri, expiry = 10, token_length = 6):\n \"\"\"Front end function for caching resources in templates.\"\"\"\n def render():\n return render_mako(template_uri)\n\n token = randstr(token_length)\n cache = pylons.cache.get_cache(key)\n cache.get_value(token, createfunc = render, expiretime = expiry)\n\n log.debug(\"Created cache for %s using key: %s\" % (key, token))\n\n return token\n\n\ndef resourcescontroller(BaseController):\n from pylons import request, response\n from pylons.controllers.util import redirect, abort\n import jsmin\n\n def retrieve_cache(key, token):\n try:\n cache = pylons.cache.get_cache(str(key))\n return cache.get_value(token)\n\n except KeyError:\n log.error(\"Requested resource cache unavailable. key: %s | token: %s\" % (key, token))\n return abort(403)\n\n class ResourcesController(BaseController):\n # dict of resources offered by the controller.\n templates = {'cached.js':lambda k, t: retrieve_cache(k, t)}\n assignments = {}\n\n '''\n # dict of valid resource collections.\n types = { 'root.js':['cached.js'],\n 'root.content.js':['ui.js','player.js','playlist.js','voting.js','tracker.js','comments.js','cached.js'],\n 'join.js':['ui.js', 'cached.js'],\n 'recover_form.js':['ui.js', 'cached.js'],\n 'verify_form.js':['cached.js'],\n 'recover_send.js':['ui.js', 'cached.js'],\n 'invite_form.js':['ui.js', 'cached.js'],\n 'upload.js':['ui.js', 'cached.js'],\n 'video.view.js':['ui.js','player.js','voting.js','tracker.js','comments.js','cached.js'],\n 'video.edit.js':['cached.js'],\n 'hive.view.js':['ui.js','player.js','playlist.js','voting.js','comments.js','cached.js'],\n 'bee.view.js':['ui.js','player.js','playlist.js','voting.js','comments.js','cached.js'],\n 'root.css':['root.css']\n }'''\n\n def index(self, type_key, format):\n t = request.params.get('t')\n\n type_key = \".\".join([type_key, format])\n if t and type_key in self.assignments.keys():\n t1 = time.time()\n out = ''.join([self.templates[r](type_key, t) for r in self.assignments[type_key]])\n log.debug('Resource template rendered in: %s:%f2' % (r, (time.time() - t1)))\n \n else:\n log.error('Something bad happened.')\n abort(403)\n\n if format == 'js':\n response.content_type = 'text/javascript'\n if not asbool(pylons.config['debug']) and asbool(pylons.config.get('resource.jsmin')):\n # This is really slow.\n t1 = time.time()\n out = jsmin.jsmin(out)\n log.debug('Resource minified in: %s:%f2' % (r, (time.time() - t1)))\n\n elif format == 'css':\n response.content_type = 'text/css'\n\n return out\n\n ResourcesController.assignments.update(pylons.config['resources.assignments'])\n \n ResourcesController.templates.update({k:lambda key, token, v = v: render_mako(v) for k, v in pylons.config['resources.templates'].iteritems()})\n\n '''\n templates = {}\n for k, v in pylons.config['resources.templates'].iteritems():\n def render(key, token, template_uri = v):\n return render_mako(template_uri)\n\n templates.update({k:render})\n\n ResourcesController.templates.update(templates)'''\n\n\n return ResourcesController","sub_path":"codalib/pylons/resources.py","file_name":"resources.py","file_ext":"py","file_size_in_byte":4715,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"650769433","text":"test = { 'name': 'q1_4',\n 'points': 1,\n 'suites': [ { 'cases': [ {'code': '>>> assert type(review_columns) != type(...)\\n', 'hidden': False, 'locked': False},\n { 'code': \">>> assert set(review_columns) == set(['App', 'Translated_Review', 'Sentiment', 'Sentiment_Polarity',\\n... 'Sentiment_Subjectivity'])\\n\",\n 'hidden': False,\n 'locked': False}],\n 'scored': True,\n 'setup': '',\n 'teardown': '',\n 'type': 'doctest'}]}\n","sub_path":"tutorial/week1/1.3/tests/q1_4.py","file_name":"q1_4.py","file_ext":"py","file_size_in_byte":634,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"208693854","text":"\"\"\"\nUsing python 3.6.3\n@author: Michael Kirkham\n@version: 12/14/2017\n\nA program to calculate the probability and likelihood, using a Markov Model, that the alpha-helix\nfor the amino acid sequence 'MQTRRSAFIILQGRPEYVMMDLHVHNMQSHTACWDMMAFKEEIWSHTALR'\nstarts at the only Cysteine.\n\"\"\"\n\nimport numpy as np #for use of arrays\nimport math #to calculate log values\n\ndef main():\n np.set_printoptions(suppress=True)#sets the array output to a readable form\n aaSeq = 'MQTRRSAFIILQGRPEYVMMDLHVHNMQSHTACWDMMAFKEEIWSHTALR' #the amino acid sequence\n\n transProbMatrix = np.ndarray([2, 3]) #creates the transition probability matrix\n transProbMatrix = [0.95, 0.05, 0,\n 0, 0.9, 0.1]\n markovModel = np.ndarray([len(aaSeq) - 1, 4]) #creates the markov model matrix\n for i in range(0, len(aaSeq) - 1): #initializes the markov model with 0's.\n for j in range(0, 4):\n markovModel[i][j] = 0\n #dictionary of emmision probabilities in alpha-helical regions\n helixEmission = {'A' : 0.106,\n 'C' : 0.014,\n 'D' : 0.016,\n 'E' : 0.070,\n 'F' : 0.040,\n 'G' : 0.006,\n 'H' : 0.028,\n 'I' : 0.066,\n 'K' : 0.082,\n 'L' : 0.098,\n 'M' : 0.091,\n 'N' : 0.019,\n 'P' : 0.001,\n 'Q' : 0.074,\n 'R' : 0.098,\n 'S' : 0.051,\n 'T' : 0.017,\n 'V' : 0.023,\n 'W' : 0.057,\n 'Y' : 0.043}\n #dictionary of emmision probabilities in non-helical regions\n coilEmission = { 'A' : 0.078,\n 'C' : 0.019,\n 'D' : 0.054,\n 'E' : 0.058,\n 'F' : 0.041,\n 'G' : 0.073,\n 'H' : 0.024,\n 'I' : 0.058,\n 'K' : 0.059,\n 'L' : 0.094,\n 'M' : 0.023,\n 'N' : 0.045,\n 'P' : 0.046,\n 'Q' : 0.038,\n 'R' : 0.053,\n 'S' : 0.060,\n 'T' : 0.062,\n 'V' : 0.069,\n 'W' : 0.013,\n 'Y' : 0.033}\n #fills the first 3 columns of the markov model\n for i in range(0, len(aaSeq) - 1):\n markovModel[i][0] = -math.log10((0.95**(i) * 0.5 * 0.9**(len(aaSeq) - i - 1) * 0.1)) #equation for the probability of state path\n obsSeq = 1\n for j in range(0, len(aaSeq)):\n if j < (i + 1):\n obsSeq *= coilEmission[aaSeq[j]]\n else:\n obsSeq *= helixEmission[aaSeq[j]]\n markovModel[i][1] = -math.log10(obsSeq) #equation for the probability of observed path\n markovModel[i][2] = markovModel[i][0] + markovModel[i][1] #equation for the probability of state path and observed path\n\n totalLikelihood = 0\n for k in range(0, len(aaSeq)-1):\n totalLikelihood += 10**(-markovModel[k][2]) #calculates the total for the probabilities of the state path and observed paths\n\n for i in range(0, len(aaSeq) - 1):\n markovModel[i][3] = (10**(-markovModel[i][2])) / totalLikelihood #calculate likelihood of observed path\n #print statements\n print(\"The transition probability matrix is: \")\n print(transProbMatrix[0:3])\n print(transProbMatrix[3:])\n print(\"The probablity that the alpha-helix starts at the only Cysteine is \" + str(10**(-markovModel[aaSeq.index('C')][2])))\n print(\"The likelihood that the alpha-helix starts at the only Cysteine is \" + str(markovModel[aaSeq.index('C')][3]))\n return 0\n\nmain()","sub_path":"Bioinformatics/Project 2/Kirkham_CS_Markov.py","file_name":"Kirkham_CS_Markov.py","file_ext":"py","file_size_in_byte":3824,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"5646121","text":"def merge_sort(num):\n if (len(num) == 1):\n return num\n lst1 = num[:int(len(num) / 2)]\n lst2 = num[int(len(num) / 2):]\n sl1 = merge_sort(lst1)\n sl2 = merge_sort(lst2)\n r = merge(sl1, sl2)\n return r\n\n\ndef merge(lst1, lst2):\n i = 0\n j = 0\n r = []\n while (i < len(lst1) and j < len(lst2)):\n if (lst1[i] < lst2[j]):\n r.append(lst1[i])\n i = i + 1\n else:\n r.append(lst2[j])\n j = j + 1\n\n if (i >= len(lst1)):\n r.extend(lst2[j:])\n else:\n r.extend(lst1[i:])\n\n return r\n\n\nprint(merge_sort([38, 27, 43, 3, 9, 82, 10]))\n\n\ndef partition(num, low, high):\n pivot = num[low]\n i = low + 1\n j = high\n while (i < j):\n if (num[i] < pivot):\n i = i + 1\n continue\n\n if (num[j] >= pivot):\n j = j - 1\n continue\n\n s = num[i]\n num[i] = num[j]\n num[j] = s\n i=i+1\n j=j-1\n\n\n if(pivot>num[i]):\n swap = i\n else:\n swap = i-1\n num[low] = num[swap]\n num[swap] = pivot\n return swap\n\n\ndef quick_sort(arr, low, high):\n if(low0:\n max_profit=max_profit+p\n\n return max_profit","sub_path":"sort.py","file_name":"sort.py","file_ext":"py","file_size_in_byte":1510,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"591634822","text":"import os\nimport sys\nimport json\nimport shutil\nimport logging\nimport Tkinter as tk\nimport tkFileDialog\nimport subprocess as sp\nfrom collections import OrderedDict\n\n# Project modules\nimport mugen.exceptions as ex\nimport mugen.settings as s\n\n### INPUTS ###\n\ndef get_music_video_name(output_name, is_regenerated):\n music_video_name = None\n if output_name == None:\n count = 0\n while True:\n music_video_name = 'regenerated_' if is_regenerated else \"\"\n music_video_name += s.MUSIC_VIDEO_NAME_DEFAULT + \"_%s\" % count\n if not os.path.exists(get_output_path(music_video_name)):\n break\n else:\n count += 1\n else:\n music_video_name = output_name\n\n print(\"Preparing {}...\".format(music_video_name))\n\n return music_video_name\n\ndef get_file(file_type, source):\n \"\"\"\n Validates a file path from a given source, \n or returns a file path after prompting user via file selection dialog\n \"\"\"\n file = None\n\n # Select via terminal input\n if source:\n source_exists = os.path.exists(source)\n\n # Check that file exists\n if not source_exists:\n print(\"{} source path '{}' does not exist.\".format(file_type, source))\n sys.exit(1)\n\n file = source\n # Select via file selection dialog\n else:\n root = tk.Tk()\n root.withdraw()\n source = tkFileDialog.askopenfilename(message=\"Select {} file\".format(file_type))\n root.update()\n\n if source == \"\":\n print(\"No {} file was selected.\".format(file_type))\n sys.exit(1)\n\n # Properly encode file name\n file = source.encode('utf-8')\n\n logging.debug(\"{}_file {}\".format(file_type, file))\n return file\n\ndef get_files(file_type, *sources):\n \"\"\"\n Returns list of file paths from a given list of sources, \n or after prompting user for a list of sources via file selection dialog\n \"\"\"\n files = []\n\n # Select via terminal input\n if sources:\n for source in sources:\n source_exists = os.path.exists(source)\n source_is_dir = os.path.isdir(source)\n\n # Check that file/directory exists\n if not source_exists:\n print(\"{} source path {} does not exist.\".format(file_type, source))\n sys.exit(1)\n\n # Check if source is file or directory \n if source_is_dir:\n files.extend([file for file in listdir_nohidden(source) if os.path.isfile(file)])\n else:\n files.append(source)\n # Select files via file selection dialog\n else:\n message = \"Select {} files\".format(file_type)\n while True:\n root = tk.Tk()\n root.withdraw()\n source = tkFileDialog.askopenfilename(message=message, multiple=True)\n message = \"Select more {} files, or press cancel if done\".format(file_type)\n root.update()\n \n if not source:\n break\n\n # Properly encode file names\n files.extend([file.encode('utf-8') for file in source])\n\n if len(files) == 0:\n print(\"No {} files were selected.\".format(file_type))\n sys.exit(1)\n\n logging.debug(\"{}_source {}\".format(file_type, sources))\n for file in files:\n logging.debug(\"{}_file: {}\".format(file_type, file))\n return files\n\ndef parse_speed_multiplier(speed_multiplier, speed_multiplier_offset):\n if speed_multiplier == 0 or (speed_multiplier.numerator != 1 and speed_multiplier.denominator != 1):\n print(\"Improper speed multiplier provided.\" + s.HELP)\n sys.exit(1)\n\n if speed_multiplier_offset:\n if speed_multiplier >= 1:\n print(\"Speed multiplier offsets may only be used with slowdown speed multipliers.\" + s.HELP)\n sys.exit(1)\n elif speed_multiplier_offset > speed_multiplier.denominator - 1:\n print(\"Speed multiplier offset may not be greater than x - 1 for a slowdown of 1/x.\" + s.HELP)\n sys.exit(1)\n\n logging.debug('speed_multiplier: {}'.format(speed_multiplier))\n\n return speed_multiplier, speed_multiplier_offset\n\ndef parse_spec_file(spec_file):\n with open(spec_file) as spec_file: \n spec = json.load(spec_file, object_pairs_hook=OrderedDict)\n\n return spec\n\ndef validate_replace_segments(replace_segments, video_segments):\n for segment in replace_segments:\n if segment < 0 or segment > (len(video_segments) - 1):\n print(\"No segment {} exists in spec for music video\".format(segment))\n sys.exit(1)\n\n### FILESYSTEM ###\n\ndef ensure_dir(*directories):\n for directory in directories:\n if not os.path.exists(directory):\n os.makedirs(directory)\n\ndef recreate_dir(*directories):\n for directory in directories:\n if os.path.exists(directory):\n shutil.rmtree(directory)\n os.makedirs(directory)\n\ndef delete_dir(*directories):\n for directory in directories:\n if os.path.exists(directory):\n shutil.rmtree(directory)\n\ndef get_segments_dir(music_video_name):\n return s.SEGMENTS_PATH_BASE + music_video_name + '/'\n\ndef get_output_path(music_video_name):\n return s.OUTPUT_PATH_BASE + music_video_name + s.VIDEO_OUTPUT_EXTENSION\n\ndef get_spec_path(music_video_name):\n return s.OUTPUT_PATH_BASE + music_video_name + '_spec' + s.SPEC_EXTENSION\n\ndef get_audio_preview_path(audio_file):\n return s.OUTPUT_PATH_BASE + filename_from_path(audio_file) + \"_marked_audio_preview\" + s.ESSENTIA_ONSETS_AUDIO_EXTENSION\n\ndef get_temp_output_path(music_video_name):\n return s.TEMP_PATH_BASE + 'temp_' + music_video_name + s.VIDEO_OUTPUT_EXTENSION\n\ndef get_temp_subtitle_path(music_video_name, track_type):\n return s.TEMP_PATH_BASE + music_video_name + '_' + track_type + '_subs' + s.SUBTITLES_EXTENSION\n\ndef get_temp_audio_onsets_path(audio_file):\n return s.TEMP_PATH_BASE + filename_from_path(audio_file) + '_marked_audio' + s.ESSENTIA_ONSETS_AUDIO_EXTENSION\n\ndef get_temp_audio_offset_path(audio_file):\n return s.TEMP_PATH_BASE + filename_from_path(audio_file) + '_offset_audio' + os.path.splitext(audio_file)[1]\n\ndef filename_from_path(path):\n \"\"\"\n Returns a path's file basename without its extension\n \"\"\"\n file = os.path.basename(path)\n filename, extension = os.path.splitext(file)\n\n return filename\n\ndef sanitize_filename(filename):\n keepcharacters = (' ','.','_','-','(',')','[',']')\n return \"\".join(c for c in filename if c.isalnum() or c in keepcharacters).rstrip() if filename else None\n\ndef listdir_nohidden(path):\n # Make sure path has trailing slash\n path = os.path.join(path, '')\n for file in os.listdir(path):\n if not file.startswith('.'):\n yield path + file\n\n### SYSTEM ###\n\ndef get_ffmpeg_binary():\n \"\"\"\n Return appropriate ffmpeg binary for system\n \"\"\"\n # Unix\n if which(\"ffmpeg\"):\n return \"ffmpeg\"\n # Windows\n elif which(\"ffmpeg.exe\"):\n return \"ffmpeg.exe\"\n else:\n raise IOError(\"Could not find ffmpeg binary for system.\")\n\ndef execute_ffmpeg_command(cmd):\n p = sp.Popen(cmd, stdout=sp.PIPE, stderr=sp.PIPE)\n p_out, p_err = p.communicate()\n\n if p.returncode != 0:\n raise ex.FFMPEGError(\"Error executing ffmpeg command.\", p.returncode, p_out, p_err)\n\ndef touch(filename):\n open(filename, 'a').close()\n\ndef which(program):\n \"\"\"\n Mimics behavior of UNIX which command.\n \"\"\"\n envdir_list = [os.curdir] + os.environ[\"PATH\"].split(os.pathsep)\n\n for envdir in envdir_list:\n program_path = os.path.join(envdir, program)\n if os.path.isfile(program_path) and os.access(program_path, os.X_OK):\n return program_path","sub_path":"mugen/utility.py","file_name":"utility.py","file_ext":"py","file_size_in_byte":7767,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"80667935","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom decimal import Decimal\n\nfrom django.test import TestCase\nfrom django.utils import timezone\n\nfrom mixer.backend.django import mixer\n\nfrom tour.models import Transport, Hotel, Excursion, Tour\n\n\nclass TestTour(TestCase):\n def test_tour_model(self):\n \"\"\"\n Check create instance of Tour and str method of model.\n \"\"\"\n obj = mixer.blend(Tour, title='Анталия лайт')\n self.assertIn('Анталия лайт', str(obj))\n\n def test_method_get_price_tour(self):\n \"\"\"\n Check that this method return appropriate value.\n \"\"\"\n hotel = mixer.blend(Hotel, cost=623)\n excurs = mixer.blend(Excursion, cost=Decimal('50.04'))\n trans = mixer.blend(Transport, cost=Decimal('500.23'))\n tour = mixer.blend(\n Tour, cost=100, hotel=hotel, transport=trans, excursion=excurs)\n tour_price = tour.get_price_tour()\n price = tour.cost + hotel.cost + excurs.cost + trans.cost\n self.assertEqual(tour_price, price)\n\n\nclass TestTransport(TestCase):\n def test_transport_model(self):\n \"\"\"\n Check create instance of Transport and str method of model.\n \"\"\"\n title = 'A320'\n date_start = timezone.now()\n departure_point = 'Запорожье'\n destination_point = 'Анталия'\n obj = mixer.blend(\n Transport,\n title=title,\n date_start=date_start,\n departure_point=departure_point,\n destination_point=destination_point)\n text = '%s - %s(%s-%s)' % (\n title, date_start, departure_point, destination_point)\n self.assertEqual(str(obj), text)\n\n\nclass TestHotel(TestCase):\n def test_hotel_model(self):\n \"\"\"\n Check create instance of Hotel and str method of model.\n \"\"\"\n title = 'Леополис'\n loc = 'Львов'\n obj = mixer.blend(Hotel, title=title, location=loc)\n text = '%s (%s)' % (title, loc)\n self.assertEqual(str(obj), text)\n\n\nclass TestExcursion(TestCase):\n def test_excursion_model(self):\n \"\"\"\n Check create instance of Excursion and str method of model.\n \"\"\"\n title = 'Старый Львов'\n loc = 'Львов'\n obj = mixer.blend(Excursion, title=title, location=loc)\n text = '%s (%s)' % (title, loc)\n self.assertEqual(str(obj), text)\n","sub_path":"tour/tests/test_models.py","file_name":"test_models.py","file_ext":"py","file_size_in_byte":2469,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"281366084","text":"\"\"\"Visualization for the Hello World Open 2012 competition.\r\nWritten by Juha Reunanen (juha.reunanen-at-gmail.com).\r\n\"\"\"\r\n\r\nclass PingPongVisu(object):\r\n\tdef __init__(self, visualizationEnabled):\r\n\t\tself._error = \"\"\r\n\t\tif visualizationEnabled:\r\n\t\t\ttry:\r\n\t\t\t\tfrom Tkinter import Tk\r\n\t\t\t\tself._master = Tk()\r\n\t\t\texcept Exception as e:\r\n\t\t\t\tself._master = None\r\n\t\t\t\tself._error = str(e)\r\n\t\telse:\r\n\t\t\tself._master = None\r\n\t\tself._canvas = None\r\n\r\n\tdef set_conf(self, confData):\r\n\t\tif self._master is None:\r\n\t\t\treturn\r\n\r\n\t\tself._maxWidth = confData[\"maxWidth\"]\r\n\t\tself._maxHeight = confData[\"maxHeight\"]\r\n\t\tself._paddleHeight = confData[\"paddleHeight\"]\r\n\t\tself._paddleWidth = confData[\"paddleWidth\"]\r\n\t\tself._ballRadius = confData[\"ballRadius\"]\r\n\t\tself._tickInterval = confData[\"tickInterval\"]\t\t\r\n\r\n\t\tif self._canvas is not None:\r\n\t\t\tself._canvas.destroy()\r\n\r\n\t\ttry:\r\n\t\t\tfrom Tkinter import Canvas\r\n\t\t\tself._canvas = Canvas(self._master, width=self._maxWidth, height=self._maxHeight)\r\n\t\t\tself._canvas.pack()\r\n\t\texcept Exception as e:\r\n\t\t\tself._error = str(e)\r\n\r\n\tdef set_game_data(self, data):\r\n\t\tif self._canvas is None:\r\n\t\t\treturn\r\n\t\t\r\n\t\tself._ballCurrX = data[\"ball\"][\"pos\"][\"x\"]\r\n\t\tself._ballCurrY = data[\"ball\"][\"pos\"][\"y\"]\r\n\t\tself._myCurrY = data[\"left\"][\"y\"]\r\n\t\tself._herCurrY = data[\"right\"][\"y\"]\r\n\t\t\r\n\t\tfrom Tkinter import ALL\r\n\t\tself._canvas.delete(ALL)\r\n\t\tself._canvas.create_rectangle(self._ballCurrX - self._ballRadius, self._ballCurrY - self._ballRadius, self._ballCurrX + self._ballRadius, self._ballCurrY + self._ballRadius)\r\n\t\tself._canvas.create_rectangle(0, self._myCurrY, self._paddleWidth, self._myCurrY + self._paddleHeight)\r\n\t\tself._canvas.create_rectangle(self._maxWidth - self._paddleWidth, self._herCurrY, self._maxWidth, self._herCurrY + self._paddleHeight)\r\n\t\t\r\n\tdef set_missiles(self, missiles, currentServerTime):\r\n\t\tif self._canvas is None:\r\n\t\t\treturn\r\n\r\n\t\tfor missile in missiles:\r\n\t\t\tmissilePosX = missile.get_current_x(currentServerTime)\r\n\t\t\tmissilePosY = missile.get_current_y(currentServerTime)\r\n\t\t\tself._canvas.create_rectangle(missilePosX-3, missilePosY-1, missilePosX+3, missilePosY+1, fill=\"red\")\r\n\t\t\t\r\n\tdef draw_rectangle(self, x1, y1, x2, y2, color):\r\n\t\tif self._canvas is not None:\r\n\t\t\tself._canvas.create_rectangle(x1, y1, x2, y2, fill=color)\r\n\t\t\t\r\n\tdef update(self):\r\n\t\tif self._master is not None:\r\n\t\t\tself._master.update()\r\n\r\n\tdef get_error(self):\r\n\t\treturn self._error\r\n\t\t\r\n\tdef clear_error(self):\r\n\t\tself._error = \"\"\r\n\t\t","sub_path":"pingpongvisu.py","file_name":"pingpongvisu.py","file_ext":"py","file_size_in_byte":2464,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"217244692","text":"from django.urls import path\n\nfrom . import views\n\nurlpatterns=[\n\tpath(\"\",views.index, name=\"index\"),\n\tpath('about', views.about , name=\"about\"),\n\tpath('who', views.who , name=\"who\"),\n\tpath('seller', views.seller , name=\"seller\"),\n\tpath('buyer', views.buyer , name=\"buyer\"),\n\t\n\tpath('register',views.register, name=\"register\"),\n\tpath('login',views.login, name=\"login\"),\n\tpath('cart', views.cart , name=\"cart\"),\n\tpath('contact', views.contact , name=\"contact\"),\n\tpath('logout', views.logout , name=\"logout\"),\n\t#path('purchase', views.purchase , name=\"purchase\"),\n\tpath('search', views.Search , name=\"search\"),\n\tpath('Home_seller', views.Home_seller , name=\"Home_seller\"),\n\tpath('Home_buyer', views.Home_Buyer , name=\"Home_Buyer\"),\n\tpath('add_book', views.bookform , name=\"add_book\"),\n\t#path('delete-book/', views.deleteBook , name=\"delete-book\"),\n\t#path('edit-book', views.editBook , name=\"edit-book\"),\n\tpath('storebook', views.storebook, name=\"storebook\"),\t\n]","sub_path":"firstapp/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":975,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"549513222","text":"def phi(n): \n result = n\n p = 2\n while p * p <= n: \n if n % p == 0: \n while n % p == 0: \n n = n // p \n result = result * (1.0 - (1.0 / float(p))) \n p = p + 1\n if n > 1:\n result = result * (1.0 - (1.0 / float(n))) \n \n return int(result) \n\ndef sumFarey(lim):\n lengths = [0,2]\n for i in range(2,lim+1):\n lengths.append(lengths[i-1] + phi(i))\n return lengths\n","sub_path":"misc_funcs/sumFarey.py","file_name":"sumFarey.py","file_ext":"py","file_size_in_byte":446,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"451975884","text":"from typing import Optional\nfrom collections import deque\n\n\nclass Node:\n def __init__(self, val: int = 0, left: \"Node\" = None, right: \"Node\" = None, next: \"Node\" = None):\n self.val = val\n self.left = left\n self.right = right\n self.next = next\n\n\nclass Solution:\n def connect(self, root: Optional[Node]) -> Optional[Node]:\n if root is None:\n return root\n nodes = deque([root])\n size, previous, current = len(nodes), None, None\n while len(nodes) != 0:\n for _ in range(size):\n previous = current\n current = nodes.popleft()\n if current.right is not None:\n nodes.append(current.right)\n if current.left is not None:\n nodes.append(current.left)\n current.next = previous\n size = len(nodes)\n current = None\n return root\n","sub_path":"Top_Interview_Questions/Medium/116. Populating Next Right Pointers in Each Node/solution2.py","file_name":"solution2.py","file_ext":"py","file_size_in_byte":936,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"500095325","text":"import base64\nimport functools\nimport hashlib\nimport pickle\nimport os\nimport sys\nfrom weakref import WeakValueDictionary\n\nimport PIL\n\n\nIMAGE_CACHE = None\nCOMPUTE_CACHE = None\n\n@functools.lru_cache(128)\ndef _cached_mtime(path):\n return os.path.getmtime(path)\n\nclass CachedImage(object):\n \"\"\"An immutable wrapper around PIL.Image that allows for caching of\n intermediate images.\"\"\"\n def __init__(self, size, desc, inputs):\n self.size = size\n self._desc = (type(self), desc, tuple(i._desc for i in inputs))\n self._raw = None\n\n def _realize(self):\n raise RuntimeError('CachedImage subclass must implement _realize()')\n\n def raw(self):\n img = self._raw\n if img is not None:\n return img\n\n img = IMAGE_CACHE.get(self._desc)\n if img is not None:\n assert img.size == self.size, 'cache contained an image of the wrong size'\n self._raw = img\n return img\n\n img = self._realize()\n assert img is not None, '_realize() must return a PIL.Image, not None'\n assert img.size == self.size, '_realize() returned an image of the wrong size'\n self._raw = img\n if type(img) is not PIL.Image.Image:\n # It's a lazy crop object, or something similar. Force it.\n img = img.copy()\n IMAGE_CACHE.add(self._desc, img)\n return img\n\n def compute(self, f, desc=None):\n code_file = sys.modules[f.__module__].__file__\n code_time = _cached_mtime(code_file)\n if desc is None:\n desc = (f.__module__, f.__qualname__)\n k = ('compute', self._desc, desc, code_file, code_time)\n\n # Avoid .get because a compute result may legitimately be `None`\n if COMPUTE_CACHE.contains(k):\n result = COMPUTE_CACHE.get(k)\n else:\n result = f(self.raw())\n COMPUTE_CACHE.add(k, result)\n\n return result\n\n def desc(self):\n return self._desc\n\n @staticmethod\n def blank(size):\n return BlankImage(size)\n\n @staticmethod\n def open(filename):\n return FileImage(filename)\n\n @staticmethod\n def from_raw(img):\n return ConstImage(img)\n\n def modify(self, f, size=None, desc=None):\n if desc is None:\n desc = '%s.%s' % (f.__module__, f.__qualname__)\n return ModifiedImage(self, f, size or self.size, desc)\n\n def fold(self, imgs, f, size=None, desc=None):\n if desc is None:\n desc = '%s.%s' % (f.__module__, f.__qualname__)\n return FoldedImage(self, imgs, f, size or self.size, desc)\n\n def crop(self, bounds):\n return CroppedImage(self, bounds)\n\n def resize(self, size, resample=0):\n return ResizedImage(self, size, resample)\n\n def stack(self, imgs):\n return StackedImage((self,) + tuple(imgs))\n\n def pad(self, size, offset):\n return PaddedImage(self, size, offset)\n\n @staticmethod\n def sheet(img_offsets, size=None):\n if size is None:\n w, h = 0, 0\n for i, o in img_offsets:\n w = max(w, i.size[0] + o[0])\n h = max(h, i.size[1] + o[1])\n size = (w, h)\n\n return SheetImage(img_offsets, size)\n\n def get_bounds(self):\n # NB: we only consider the alpha channel when finding the bounds. This\n # means pixels with zero alpha but non-zero color will be considered\n # empty.\n b = self.compute(lambda i: i.split()[3].getbbox())\n if b is None:\n return (0, 0, 0, 0)\n else:\n return b\n\nclass BlankImage(CachedImage):\n def __init__(self, size):\n super(BlankImage, self).__init__(size, size, ())\n\n def _realize(self):\n return PIL.Image.new('RGBA', self.size)\n\nclass ConstImage(CachedImage):\n def __init__(self, img):\n h = hashlib.sha1(bytes(x for p in img.getdata() for x in p)).hexdigest()\n super(ConstImage, self).__init__(img.size, (img.size, h), ())\n self._raw = img\n\n def _realize(self):\n assert False, 'ConstImage already sets self._raw, should be no need to call _realize()'\n\nclass FileImage(CachedImage):\n def __init__(self, filename):\n mtime = os.path.getmtime(filename)\n img = PIL.Image.open(filename)\n super(FileImage, self).__init__(img.size, (filename, mtime), ())\n self._raw = img\n\n def _realize(self):\n assert False, 'FileImage already sets self._raw, should be no need to call _realize()'\n\nclass ModifiedImage(CachedImage):\n def __init__(self, img, f, size, desc):\n code_file = sys.modules[f.__module__].__file__\n code_time = _cached_mtime(code_file)\n\n super(ModifiedImage, self).__init__(size, (desc, size, code_time), (img,))\n self.orig = img\n self.f = f\n\n def _realize(self):\n img = self.orig.raw().copy()\n return self.f(img) or img\n\nclass FoldedImage(CachedImage):\n def __init__(self, base_img, imgs, f, size, desc):\n code_file = sys.modules[f.__module__].__file__\n code_time = _cached_mtime(code_file)\n\n imgs = tuple(imgs)\n super(FoldedImage, self).__init__(size, (desc, size, code_time), (base_img,) + imgs)\n self.base_orig = base_img\n self.origs = imgs\n self.f = f\n\n def _realize(self):\n base = self.base_orig.raw().copy()\n imgs = [o.raw().copy() for o in self.origs]\n return self.f(base, *imgs) or base\n\nclass CroppedImage(CachedImage):\n def __init__(self, img, bounds):\n x0, y0, x1, y1 = bounds\n w = x1 - x0\n h = y1 - y0\n\n super(CroppedImage, self).__init__((w, h), bounds, (img,))\n\n self.orig = img\n self.bounds = bounds\n\n def _realize(self):\n return self.orig.raw().crop(self.bounds)\n\nclass ResizedImage(CachedImage):\n def __init__(self, img, size, resample=0):\n super(ResizedImage, self).__init__(size, (size, resample), (img,))\n\n self.orig = img\n # self.size already set\n self.resample = resample\n\n def _realize(self):\n return self.orig.raw().resize(self.size, self.resample)\n\nclass StackedImage(CachedImage):\n def __init__(self, imgs):\n assert all(i.size == imgs[0].size for i in imgs)\n super(StackedImage, self).__init__(imgs[0].size, (), imgs)\n self.imgs = imgs\n\n def _realize(self):\n img = self.imgs[0].raw().copy()\n for i in self.imgs[1:]:\n layer_img = i.raw()\n img.paste(layer_img, (0, 0), layer_img)\n return img\n\nclass PaddedImage(CachedImage):\n def __init__(self, img, size, offset):\n super(PaddedImage, self).__init__(size, (size, offset), (img,))\n self.orig = img\n # self.size already set\n self.offset = offset\n\n def _realize(self):\n orig_img = self.orig.raw()\n img = PIL.Image.new(orig_img.mode, self.size)\n img.paste(orig_img, self.offset)\n return img\n\nclass SheetImage(CachedImage):\n def __init__(self, img_offsets, size):\n imgs = tuple(i for i,o in img_offsets)\n offsets = tuple(o for i,o in img_offsets)\n super(SheetImage, self).__init__(size, (offsets, size), imgs)\n\n self.imgs = imgs\n self.offsets = offsets\n\n def _realize(self):\n acc = PIL.Image.new('RGBA', self.size)\n for i, o in zip(self.imgs, self.offsets):\n acc.paste(i.raw(), o)\n return acc\n\n\nWORKAROUND_0X0 = 'workaround-0x0-bug'\n\ndef _safe_dump(value, f):\n if isinstance(value, PIL.Image.Image) and value.size == (0, 0):\n # Pickling a 0x0 image seems to cause a crash (\"tile cannot extend\n # outside image\"). Store this dummy value instead.\n pickle.dump(WORKAROUND_0X0, f)\n else:\n pickle.dump(value, f)\n\ndef _safe_load(f):\n value = pickle.load(f)\n if value == WORKAROUND_0X0:\n return PIL.Image.new('RGBA', (0, 0))\n else:\n return value\n\nCACHE_PAGE = 4096\n\nclass LargeCache:\n '''File-backed cache for large objects (particularly images). Uses a\n WeakValueDictionary for in-memory storage, and a page-based format for\n on-disk.'''\n def __init__(self, data_file, index_file):\n # Dict storing currently loaded values\n self.cache = WeakValueDictionary()\n\n # Data file, and index mapping key to data offset\n self.data_file = data_file\n self.data_total = os.fstat(data_file.fileno()).st_size\n\n self.index_file = index_file\n self.index = {}\n\n self.used = set()\n\n # Read index data into dict\n self.index_file.seek(0)\n for line in self.index_file.readlines():\n parts = line.strip().split()\n if len(parts) != 2:\n continue\n offset_str, key_str = parts\n offset = int(offset_str)\n key = pickle.loads(base64.decodebytes(key_str.encode('ascii')))\n self.index[key] = offset\n\n # Seek both to EOF\n self.data_file.seek(0, os.SEEK_END)\n self.index_file.seek(0, os.SEEK_END)\n\n def contains(self, key):\n return key in self.cache or key in self.index\n\n def get(self, key):\n # Record the key use here, regardless of the outcome. This assumes the\n # caller runs `add` only on keys for which it first ran `get`.\n self.used.add(key)\n\n # Try to fetch from in-memory cache\n value = self.cache.get(key)\n if value is not None:\n return value\n\n # Try to load from file\n if key in self.index:\n offset = self.index[key]\n self.data_file.seek(offset)\n value = _safe_load(self.data_file)\n self.cache[key] = value\n return value\n\n # No cached copy of this image\n return None\n\n def add(self, key, value):\n # Add to in-memory cache\n self.cache[key] = value\n\n # Write pickled value to next available page\n page = CACHE_PAGE\n offset = (self.data_total + page - 1) & ~(page - 1)\n self.data_file.seek(offset)\n _safe_dump(value, self.data_file)\n self.data_total = self.data_file.tell()\n\n # Write index line\n self.index[key] = offset\n key_str = base64.encodebytes(pickle.dumps(key)).decode('ascii')\n self.index_file.write('%d %s\\n' % (offset, key_str.replace('\\n', '')))\n\n def size(self):\n return len(self.index)\n\n def save(self):\n pass\n\nclass SmallCache:\n '''File-backed cache for small objects. Uses a standard dict for in-memory\n storage and a single pickle file on disk.'''\n def __init__(self, data_file):\n self.data_file = data_file\n\n self.data_file.seek(0)\n try:\n self.dct = pickle.load(self.data_file)\n except:\n self.dct = {}\n\n def contains(self, key):\n return key in self.dct\n\n def get(self, key):\n return self.dct.get(key)\n\n def add(self, key, value):\n self.dct[key] = value\n\n def size(self):\n return len(self.dct)\n\n def save(self):\n self.data_file.seek(0)\n self.data_file.truncate(0)\n pickle.dump(self.dct, self.data_file)\n\n\ndef load_cache(cache_dir):\n global IMAGE_CACHE, COMPUTE_CACHE\n\n def open2(name, binary=False):\n b = 'b' if binary else ''\n try:\n # Open without truncating\n return open(os.path.join(cache_dir, name), 'r+' + b)\n except OSError:\n # Doesn't exist, so create it\n return open(os.path.join(cache_dir, name), 'w+' + b)\n\n IMAGE_CACHE = LargeCache(\n open2('image_cache.dat', binary=True),\n open2('image_cache.idx'))\n COMPUTE_CACHE = SmallCache(\n open2('compute_cache.dat', binary=True))\n\ndef new_cache(cache_dir):\n def rm(name):\n path = os.path.join(cache_dir, name)\n if os.path.exists(path):\n os.unlink(path)\n\n rm('image_cache.dat')\n rm('image_cache.idx')\n rm('compute_cache.dat')\n load_cache(cache_dir)\n\ndef save_cache():\n IMAGE_CACHE.save()\n COMPUTE_CACHE.save()\n\ndef _old_dump_cache(f):\n global NEW_IMAGE_CACHE, NEW_COMPUTE_CACHE\n for k, v in NEW_IMAGE_CACHE.items():\n new_v = v\n if type(new_v) is not PIL.Image.Image:\n # It may be an _ImageCrop or similar.\n new_v = v.copy()\n new_v.load()\n\n if new_v.size == (0, 0):\n # Pickling a 0x0 image seems to cause a crash (\"tile cannot extend\n # outside image\"). Store this dummy value instead.\n new_v = WORKAROUND_0X0\n\n if new_v is not v:\n NEW_IMAGE_CACHE[k] = new_v\n\n blob = (NEW_IMAGE_CACHE, NEW_COMPUTE_CACHE)\n pickle.dump(blob, f, -1)\n","sub_path":"src/gen/data/image_cache.py","file_name":"image_cache.py","file_ext":"py","file_size_in_byte":12690,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"633746241","text":"def MH(modelo, datos, N, params, q0, cov_mod, cov_prop, des=0.24):\n \"\"\"\n datos: X, F(X)\n params: ['p1', 'p2', ..., 'pn']\n cov: matriz de covarianza de datos\n \"\"\"\n # Matrices de datos de la cadena\n #pid = PID(kp=10, ki=10, kd=10, o_min=2, o_max=20)\n T0 = q0\n X = datos[0]\n Y = datos[1]\n chain = [] \n post = [] \n chi_2 = []\n Ratio = []\n mod = []\n acept = 0\n mod0 = modelo(T0, X)\n chi0 = chi2(mod0, Y, cov_mod)[0]\n pos0 = likelihood(mod0, Y, cov_mod) + prior(T0)\n mod.append(mod0)\n chain.append(T0)\n post.append(pos0)\n chi_2.append(chi0)\n Ratio.append(100)\n\n # pasos de cadena\n Ti = time.time()\n for i in range(N):\n # revisa si se paso umbral de burn in\n \"\"\"\t\n if chi_2[i]<=580 and d==0 and o!=0:\n covarianza = COV[o]\n d = 1\n print('actualizada')\n print(covarianza)\n \"\"\"\t\n # selecciona ultimo elemento de la cadena\n T0 = chain[i]\n # itera hasta que encuentra un proposal valido\n while True:\n T1 = np.random.multivariate_normal(mean=T0, cov=cov_prop)\n if revisa1(T1):\n break\n # selecciona ultimo modelo\n mod0 = mod[i]\n # calcula modelo con proposal\n mod1 = modelo(T1, X)\n # selecciona ultima dis. post.\n pos0 = post[i]\n # calcula nueva dist. post.\n pos1 = likelihood(mod1, Y, cov_mod) + prior(T1)\n # decision de aceptacion\n A = acepta(T0, pos0, T1, pos1, mod1, mod1)\n # guarda la variable aceptada (puede ser la anterior o proposal)\n chain.append(A[0])\n post.append(A[1])\n mod.append(A[2])\n chi_2.append(chi2(A[2], Y, cov)[0])\n # ratio de aceptacion\n acept += tasa(chain[i], chain[i + 1]) \n Ratio.append(acept/(i+1)*100)\n if i%100==0:\n print(i)\n print('ratio', Ratio[i])\n\n Tf = time.time()\n print('Tiempo cadena', np.around(Tf - Ti, 0), 's')\n \n ratio = acept/N*100\n print('ratio %', np.rint(ratio))\n\n post = np.array(post)\n chain = np.array(chain)\n chi_2 = np.array(chi_2)\n Ratio = np.array(Ratio)\n \n t1 = chain[:,0]\n t2 = chain[:,1]\n t3 = chain[:,2]\n\n # busca argumento del minimo de chi2\n t1m, t2m, t3m = np.around(argmin2(t1, t2, t3, chi_2),3)\n mins = [t1m, t2m, t3m]\n muestras = {}\n for i in range(len(params)):\n muestras[params[i]] = chain[:, i]\n return muestras, Ratio, chi_2, post, mins\n","sub_path":"p17/metodos.py","file_name":"metodos.py","file_ext":"py","file_size_in_byte":2525,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"633583452","text":"from string import punctuation\nfrom collections import Counter\n\nimport torch\nfrom torch.utils.data import TensorDataset, DataLoader\nimport numpy as np\n\nimport settings\nfrom common.data.text import text_load\nfrom common.models.sentimentrnn import SentimentRNN\nfrom common.managers.losses import define_loss\nfrom common.managers.optimizers import define_optimizer_classifier\nfrom text_classifier.dataset_processing import remove_outlier\nfrom text_classifier.datasets import get_loader\nfrom text_classifier.features import text2words, worddict_generate, text2int_generate, labels_encoded, features_padding, get_batchsize, tokenize\nfrom text_classifier.learn_validation import validate_steps\nfrom text_classifier.learn_inference import infer_single\nfrom text_classifier.learn_test import test_with_multi\n\n\nif __name__ == '__main__':\n reviews = text_load(settings.DATA_SENTIMENT_DIR + 'reviews_mini.txt')\n labels = text_load(settings.DATA_SENTIMENT_DIR + 'labels_mini.txt')\n \n words, text_split = text2words(reviews)\n vocabulary2int = worddict_generate(words)\n text2int = text2int_generate(text_split, vocabulary2int)\n encoded_labels = labels_encoded(labels)\n text2int, encoded_labels = remove_outlier(text2int, encoded_labels)\n\n seq_length = 200\n # text2int = text2int[:10]\n # encoded_labels = encoded_labels[:10]\n train_loader, valid_loader, test_loader = get_loader(text2int, encoded_labels, seq_length)\n batch_size = 10\n dataiter = iter(train_loader)\n sample_x, sample_y = dataiter.next()\n print('Sample input size: ', sample_x.size()) # batch_size, seq_length\n print('Sample input: \\n', sample_x)\n print()\n print('Sample label size: ', sample_y.size()) # batch_size\n print('Sample label: \\n', sample_y)\n\n # Instantiate the model w/ hyperparams\n vocab_size = len(vocabulary2int)+1 # +1 for the 0 padding + our word tokens\n output_size = 1\n embedding_dim = 400\n hidden_dim = 256\n n_layers = 2\n net = SentimentRNN(vocab_size, output_size, embedding_dim, hidden_dim, n_layers)\n print(net)\n\n lr=0.001\n criterion = define_loss(\"BCE\")\n optimizer = define_optimizer_classifier(\"ADAM\", lr, net)\n epochs = 2\n clip=5\n evalloop = 100\n validate_steps(epochs, train_loader, valid_loader, test_loader, net, criterion, optimizer, batch_size, clip, evalloop)\n\n batch_size = 2\n test_losses = test_with_multi(test_loader, net, criterion, batch_size)\n\n # test_review_neg = 'The worst movie I have seen; acting was terrible and I want my money back. This movie had bad acting and the dialogue was slow.'\n test_review_neg = \"The I\"\n test_ints = tokenize(test_review_neg, vocabulary2int)\n print(test_ints)\n features = features_padding(test_ints, seq_length)\n print(features)\n # test conversion to tensor and pass into your model\n feature_tensor = torch.from_numpy(features)\n print(feature_tensor.size())\n batch_size = feature_tensor.size(0) \n infer_single(feature_tensor, net, batch_size, seq_length) \n","sub_path":"mural/text_classifier.py","file_name":"text_classifier.py","file_ext":"py","file_size_in_byte":3023,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"66404677","text":"class Options:\r\n def __init__(self):\r\n # Source and Sink options\r\n self.srctype = 'random' # options are '0' (null), '1' (all 1's), '01' (for unitstep), 'random'\r\n self.numbits = 200 # number of data bits (for the file=None option)\r\n self.fname = None # if set, data is read from the file; should be a string giving filename\r\n self.header = True # True <==> use a 16-bit header specifying the length\r\n\r\n # Phy-layer Transmitter and Receiver options\r\n self.samplerate = 48000\r\n self.chunksize = 256\r\n self.prefill = 60\r\n self.spb = 256 # samples per bit\r\n self.channel = [1000] # channel type: bypass (synthetic) or carrier freq\r\n self.changap = 500 # gap between channel center freqs (Hz)\r\n self.silence = 80\r\n self.carrier_preamble = False # don't change this!\r\n\r\n # Modulation (signaling) and Demodulation options \r\n self.ktype = 'on_off' # keying (signaling): {'on_off', 'bipolar'}\r\n self.demod = 'envelope'\r\n self.one = 1.0 # voltage for bit \"1\"\r\n\r\n # BypassChannel options\r\n self.bypass = False\r\n self.noise = 0.25 # Gaussian noise variance for bypass channel\r\n self.lag = 0 # channel lag (delay) for bypass channel\r\n self.h = \"1\" # unit sample response for bypass channel; given as string with elements seperated by a space each\r\n\r\n # Got graphs?\r\n self.graph = False # True <==> plot some interesting graphs\r\n","sub_path":"6.02/ps04/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":1528,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"621333325","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 ('cms', '0014_auto_20160404_1908'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Contact',\n fields=[\n ('cmsplugin_ptr', models.OneToOneField(to='cms.CMSPlugin', serialize=False, parent_link=True, primary_key=True, auto_created=True)),\n ('form_name', models.CharField(help_text='Used to distinguish multiple contact forms on the same site.', verbose_name='Form name', blank=True, max_length=60)),\n ('site_email', models.EmailField(verbose_name='Email recipient', max_length=254)),\n ('thanks', models.TextField(help_text='Message displayed on successful submit', verbose_name='Thanks message', max_length=200, default='Thank you for your message.')),\n ('submit', models.CharField(verbose_name='Submit button value', max_length=30, default='Submit')),\n ('redirect_url', models.URLField(help_text='If it is set, the form redirect to url when the form is valid', verbose_name='URL Redirection', blank=True)),\n ],\n options={\n 'abstract': False,\n },\n bases=('cms.cmsplugin',),\n ),\n ]\n","sub_path":"contact/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":1355,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"149366569","text":"### 'try', 'except' and 'finally' block of codes\n# They work like the if and else block -\n\n# I would like to declare a method called greeting\n\n# def greetings():\n# pass\n\n# name = \"devops\"\n# year = 2021\n# print(name + year)\n# # Type Error\n#\n# #There is a method called open\n# file =open(\"order.txt\")\n# No such file or directory found\n\n# There are different types of errors that we see in our codes\n# We use try, except and finally to deal with these errors for the user\n\n# try:\n# file = open(\"order.txt\")\n# except FileNotFoundError as errmsg:\n# # raise\n# # there is something called creating aliases which means short form (rather than calling it with the full message, you can shorten it\").\n# print(\"order.txt not found\")\n# finally:\n# print(\"Thank you for vising, hope to see you again\")\n\n\n# Second Iteration\n# def open_using_with_and_print(file):\n#\n# try:\n# with open(\"order.txt\", \"r\") as file:\n# for line in file.readlines():\n# print(line.rstrip('\\n')) # prints it on separate lines\n# # try code block ends\n# except FileNotFoundError as errmsg:\n# print(\"Sorry, file not found :(\")\n#\n# finally:\n# return \"Thank you for visiting, hope to see you again\"\n\n# print(open_using_with_and_print(\"order.txt\"))\n# create a function to called open_with_to_write_to_file write/add/append\n\n# create a new function to call open_with_to_write_to_file write/add/append\n# display the date with the added items - item name - pizza, cakes , avacados, biriyani, pasta\n\ndef open_with_to_write_to_file(file):\n\n try:\n with open(\"order.txt\", \"r+\") as file_object: #read and append = r+\n file_object.write(\"\\nPizza\")\n file_object.write(\"\\nCakes\")\n file_object.write(\"\\nAvacados\")\n file_object.write(\"\\nBiriyani\")\n file_object.write(\"\\nPasta\")\n for line in file_object.readlines():\n print(line.rstrip('\\n'))\n # try code block ends\n except FileNotFoundError as errmsg:\n print(\"Sorry, file not found :(\")\n\n finally:\n return \"Thank you for visiting, hope to see you again\"\n\nprint(open_with_to_write_to_file(\"order.txt\"))\n\n\n\n\n\n\n\n","sub_path":"python/working_with_files_exception_handling/error_exception_handling.py","file_name":"error_exception_handling.py","file_ext":"py","file_size_in_byte":2201,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"436697191","text":"#\r\n# -*- coding: utf-8 -*-\r\n#\r\n\r\nimport wx, re, sqlparse\r\n\r\nSQL_KEY = r'.*Preparing: '\r\nPAR_KEY = r'.*Parameters: '\r\n\r\nclass SqlDropTarget(wx.TextDropTarget):\r\n\r\n\t# 初期化\r\n\t#\teditor\t:\teditorオブジェクト\r\n\tdef __init__(self, editor):\r\n\t\twx.TextDropTarget.__init__(self)\r\n\t\tself.editor = editor\r\n\t\treturn\r\n\r\n\r\n\t# Drop時のイベントハンドラ\r\n\t#\tx\t\t:\tイベントX\r\n\t#\ty\t\t:\tイベントY\r\n\t#\ttext\t:\tDropされた文字列\r\n\tdef OnDropText(self, x, y, data):\r\n\t\tself.editor.SetValue('')\r\n\t\tself.editor.AppendText(data)\r\n\t\treturn False\r\n\r\n\r\n#\r\n# アプリケーションクラス\r\n#\r\nclass MyFrame(wx.Frame):\r\n\r\n\t# 初期化\r\n\t#\tparent\t:\t親インスタンス\r\n\t#\ttitle\t:\t画面タイトル\r\n\tdef __init__(self, parent, title):\r\n\t\tsuper(MyFrame, self).__init__(\r\n\t\t\tparent,\r\n\t\t\ttitle = title,\r\n\t\t\tsize = (640, 460),\r\n\t\t\tstyle = wx.DEFAULT_FRAME_STYLE ^ wx.RESIZE_BORDER ^wx.MINIMIZE_BOX ^ wx.MAXIMIZE_BOX)\r\n\t\tself.InitUI()\r\n\t\tself.Centre()\r\n\t\tself.Show()\r\n\t\treturn\r\n\r\n\r\n\t# UI初期化\r\n\tdef InitUI(self):\r\n\t\tpanel = wx.Panel(self)\r\n\t\tsizer = wx.GridBagSizer(0, 0)\r\n\t\tfont = wx.Font(9, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_BOLD)\r\n\t\tself.labelSrc = wx.StaticText(panel, label = \"変換前 :\")\r\n\t\tself.labelSrc.SetFont(font)\r\n\t\tmyFont = wx.Font(8, wx.MODERN, wx.NORMAL, wx.NORMAL, False, 'Consolas')\r\n\t\tself.txtSrc = wx.TextCtrl(panel, size = (614, 150), style = wx.TE_MULTILINE)\r\n\t\tself.txtSrc.SetToolTip('変換したいSQLとパラメータをドラッグするかコピー&ペーストする')\r\n\t\tself.txtSrc.SetFont(myFont)\r\n\t\tself.labelDst = wx.StaticText(panel, label = \"変換後 :\")\r\n\t\tself.labelDst.SetFont(font)\r\n\t\tself.txtDst = wx.TextCtrl(panel, size = (614, 150), style = wx.TE_MULTILINE)\r\n\t\tself.txtDst.SetToolTip('変換ボタンを押下するとSQとパラメータをマージした結果が表示される')\r\n\t\tself.txtDst.SetFont(myFont)\r\n\t\tself.txtDst.SetEditable(False)\r\n\t\tself.btnConv = wx.Button(panel, label = \"変換\")\r\n\t\tself.btnConv.SetToolTip('マージ変換を行う')\r\n\t\tself.btnCopy = wx.Button(panel, label = \"コピー\")\r\n\t\tself.btnCopy.SetToolTip('変換後のSQLをクリップボードにコピーする')\r\n\t\tself.btnClear = wx.Button(panel, label = \"クリア\")\r\n\t\tself.btnClear.SetToolTip('変換前文字列と変換後文字列ををクリアする')\r\n\t\tself.btnConv.SetBackgroundColour ('#e0ffff')\r\n\t\tself.btnCopy.SetBackgroundColour ('#e0ffff')\r\n\t\tself.btnClear.SetBackgroundColour('#e0ffff')\r\n\r\n\t\tsizer.Add(self.labelSrc, pos = (0, 0), span = (1, 1), flag = wx.ALL, border = 5)\r\n\t\tsizer.Add(self.txtSrc, pos = (1, 0), span = (1, 3), flag = wx.ALL, border = 5)\r\n\t\tsizer.Add(self.labelDst, pos = (2, 0), span = (1, 1), flag = wx.ALL, border = 5)\r\n\t\tsizer.Add(self.txtDst, pos = (3, 0), span = (1, 3), flag = wx.ALL, border = 5)\r\n\t\tsizer.Add(self.btnConv, pos = (4, 0), span = (1, 1), flag = wx.ALL, border = 5)\r\n\t\tsizer.Add(self.btnCopy, pos = (4, 1), span = (1, 1), flag = wx.ALL, border = 5)\r\n\t\tsizer.Add(self.btnClear, pos = (4, 2), span = (1, 1), flag = wx.ALL, border = 5)\r\n\r\n\t\tself.txtSrc.Bind(wx.EVT_TEXT, self.onChageSrc)\r\n\t\tself.SetDropTarget(SqlDropTarget(self.txtSrc))\r\n\t\tself.btnConv.Bind (wx.EVT_BUTTON, self.clickBtnConv)\r\n\t\tself.btnCopy.Bind (wx.EVT_BUTTON, self.clickBtnCopy)\r\n\t\tself.btnClear.Bind(wx.EVT_BUTTON, self.clickBtnClear)\r\n\t\tpanel.SetSizerAndFit(sizer)\r\n\r\n\r\n\t# 変更前SQL&パラメータ変更イベントハンドラ\r\n\t#\tevent\t:\tイベントインスタンス\r\n\tdef onChageSrc(self, event):\r\n\t\tself.txtDst.SetValue('')\r\n\t\treturn\r\n\r\n\r\n\t# 変換ボタン押下ハンドラ\r\n\t#\tevent\t:\tイベントインスタンス\r\n\tdef clickBtnConv(self, event):\r\n\t\tself.txtDst.SetValue(self.marge(self.txtSrc.GetValue()))\r\n\t\treturn\r\n\r\n\r\n\t# コピーボタン押下ハンドラ\r\n\t#\tevent\t:\tイベントインスタンス\r\n\tdef clickBtnCopy(self, event):\r\n\t\tt = self.txtDst.GetValue()\r\n\t\twx.TheClipboard.SetData(wx.TextDataObject(t))\r\n\t\treturn\r\n\r\n\r\n\t# クリアボタン押下ハンドラ\r\n\t#\tevent\t:\tイベントインスタンス\r\n\tdef clickBtnClear(self, event):\r\n\t\tself.txtSrc.SetValue('')\r\n\t\tself.txtDst.SetValue('')\r\n\t\treturn\r\n\r\n\r\n\t# ログ上のパラメータを分解、変換する\r\n\t# instr\t:\tソース文字列\r\n\tdef analize_param(self, instr):\r\n\t\tret_prms = []\r\n\t\tinstr = instr.replace('\\r', '')\r\n\t\tfor prm in instr.split(','):\r\n\t\t\tmy_prm = re.sub(r'^ ', '', prm, count = 1)\r\n\t\t\tif my_prm.find('(String)') > 0:\r\n\t\t\t\tmy_prm = re.sub(r'\\(.*\\)', '', my_prm)\r\n\t\t\t\tret_prms.append(f\"'{my_prm}'\")\r\n\t\t\telse:\r\n\t\t\t\tmy_prm = re.sub(r'\\(.*\\)', '', my_prm)\r\n\t\t\t\tret_prms.append(f\"{my_prm}\")\r\n\t\treturn ret_prms\r\n\r\n\r\n\t# ログ上のSQLとパラメータをマージする\r\n\t# instr\t:\tソース文字列\r\n\tdef marge(self, instr):\r\n\t\tsql = ''\r\n\t\tprm = ''\r\n\t\tfor line in instr.split('\\n'):\r\n\t\t\tif len(line) <= 10:\r\n\t\t\t\tcontinue\r\n\t\t\tmatch_sql = re.search(SQL_KEY, line)\r\n\t\t\tmatch_prm = re.search(PAR_KEY, line)\r\n\t\t\tif match_sql:\r\n\t\t\t\tsql = re.sub(SQL_KEY, '', line)\r\n\t\t\tif match_prm:\r\n\t\t\t\tprm = re.sub(PAR_KEY, '', line)\r\n\t\tfor p in self.analize_param(prm):\r\n\t\t\tsql = re.sub(r'\\?', p, sql, count = 1)\r\n\r\n\t\treturn sqlparse.format(sql, reindent=True, keyword_case='upper')\r\n\r\n\r\n#\r\n# アプリケーション入口\r\n#\r\nif __name__ == '__main__':\r\n\tapp = wx.App()\r\n\tMyFrame(None, title = 'マージSQL')\r\n\tapp.MainLoop()\r\n","sub_path":"MergeSql/src/MergeSql.py","file_name":"MergeSql.py","file_ext":"py","file_size_in_byte":5316,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"417751238","text":"\"\"\"This is a base library for translate MCOCO-dataset into TFRecord\"\"\"\r\nimport tensorflow as tf\r\nimport json\r\nimport os\r\nimport numpy as np\r\nfrom collections import namedtuple\r\nimport random\r\nimport threading\r\nfrom datetime import datetime\r\nimport sys\r\n\r\n__all__ = [\"\"]\r\n\r\n\r\ntf.flags.DEFINE_string(\"train_image_dir\", \"D:/dataset/Images/COCO/train2014/\",\r\n \"Training image directory.\")\r\ntf.flags.DEFINE_string(\"val_image_dir\", \"D:/dataset/Images/COCO/val2014/\",\r\n \"Validation image directory.\")\r\ntf.flags.DEFINE_string(\"category_file\", \"D:/Detection/dataset/COCO/id_to_category.txt\", \"Category file\")\r\ntf.flags.DEFINE_string(\"train_instance_file\", \"D:/Detection/dataset/COCO/instances_train2014.json\",\r\n \"Training boxs JSON file.\")\r\ntf.flags.DEFINE_string(\"val_boxs_file\", \"D:/Detection/dataset/COCO/instances_val2014.json\",\r\n \"Validation boxs JSON file.\")\r\n\r\ntf.flags.DEFINE_string(\"output_dir\", \"D:/Detection/dataset/COCO_tfrecord/\", \"Output data directory.\")\r\n\r\ntf.flags.DEFINE_integer(\"train_shards\", 256,\r\n \"Number of shards in training TFRecord files.\")\r\ntf.flags.DEFINE_integer(\"val_shards\", 4,\r\n \"Number of shards in validation TFRecord files.\")\r\ntf.flags.DEFINE_integer(\"test_shards\", 8,\r\n \"Number of shards in testing TFRecord files.\")\r\n\r\ntf.flags.DEFINE_integer(\"num_threads\", 8,\r\n \"Number of threads to preprocess the images.\")\r\n\r\nFLAGS = tf.flags.FLAGS\r\nImageMetadata = namedtuple(\"ImageMetadata\",\r\n [\"image_id\", \"height\", \"width\", \"path\", \"bboxes\"])\r\n\r\n\r\nclass ImageDecoder(object):\r\n\r\n def __init__(self):\r\n # Create a single TensorFlow Session for all image decoding calls.\r\n self._sess = tf.Session()\r\n # TensorFlow ops for JPEG decoding.\r\n self._encoded_jpeg = tf.placeholder(dtype=tf.string)\r\n self._decode_jpeg = tf.image.decode_jpeg(self._encoded_jpeg, channels=3)\r\n\r\n def decode_jpeg(self, encoded_jpeg):\r\n image = self._sess.run(self._decode_jpeg,\r\n feed_dict={self._encoded_jpeg: encoded_jpeg})\r\n assert len(image.shape) == 3\r\n assert image.shape[2] == 3\r\n return image\r\n\r\n\r\ndef _int64_feature(value):\r\n \"\"\"Wrapper for inserting an int64 Feature into a SequenceExample proto.\"\"\"\r\n return tf.train.Feature(int64_list=tf.train.Int64List(value=[value]))\r\n\r\n\r\ndef _bytes_feature(value):\r\n \"\"\"Wrapper for inserting a bytes Feature into a SequenceExample proto.\"\"\"\r\n return tf.train.Feature(bytes_list=tf.train.BytesList(\r\n value=[value.encode('utf-8') if type(value) == str else value]))\r\n\r\n\r\ndef _float_feature(value):\r\n \"\"\"Wrapper for inserting a float Feature into a SequenceExample proto.\"\"\"\r\n return tf.train.Feature(float_list=tf.train.FloatList(value=[value]))\r\n\r\n\r\ndef _int64_feature_list(values):\r\n \"\"\"Wrapper for inserting an int64 FeatureList into a SequenceExample proto.\"\"\"\r\n return tf.train.FeatureList(feature=[_int64_feature(v) for v in values])\r\n\r\n\r\ndef _bytes_feature_list(values):\r\n \"\"\"Wrapper for inserting a bytes FeatureList into a SequenceExample proto.\"\"\"\r\n return tf.train.FeatureList(feature=[_bytes_feature(v) for v in values])\r\n\r\n\r\ndef _float_feature_list(values):\r\n \"\"\"Wrapper for inserting a float FeatureList into a SequenceExample proto.\"\"\"\r\n return tf.train.FeatureList(feature=[_float_feature(v) for v in values])\r\n\r\n\r\ndef _load_cls_bboxes(annotations, im_infos):\r\n id_to_cls_bboxes = {}\r\n for entity in annotations:\r\n image_id = entity[\"image_id\"]\r\n _, height, width = im_infos[image_id]\r\n cls_id = entity[\"category_id\"]\r\n bbox = _transform_bbox(entity[\"bbox\"], cls_id, height, width)\r\n # [[x_left], [y_bottom], [x_right], [y_top], [category_id]]\r\n id_to_cls_bboxes.setdefault(image_id, [[], [], [], [], []])\r\n for i, item in enumerate(id_to_cls_bboxes[image_id]):\r\n item.append(bbox[i])\r\n return id_to_cls_bboxes\r\n\r\n\r\ndef _transform_bbox(bbox, cls_id, height, width):\r\n \"\"\"\r\n Validate that whether the box is out of the range of image\r\n :param bbox: bounding box [x_left, y_right, width, height]\r\n :param cls_id: bounding box's category id\r\n :return: [x_left, y_bottom, x_right, y_top, category_id]\r\n \"\"\"\r\n x_left = max(0, bbox[0])\r\n y_top = max(0, bbox[1])\r\n x_right = min(width-1, x_left + max(0, bbox[2]-1))\r\n y_bottom = min(height-1, y_top + max(0, bbox[3]-1))\r\n return [x_left, y_bottom, x_right, y_top, cls_id]\r\n\r\n\r\ndef _to_sequence_example(image, decoder):\r\n \"\"\"\r\n Builds a SequenceExample proto for an image-detection pair.\r\n :param image: An ImageMetadata object.\r\n :param decoder: An ImageDecoder object.\r\n :return: a SequenceExample proto for an image-detection pair.\r\n \"\"\"\r\n with tf.gfile.FastGFile(image.path, \"rb\") as f:\r\n encoded_image = f.read()\r\n try:\r\n decoder.decode_jpeg(encoded_image)\r\n except (tf.errors.InvalidArgumentError, AssertionError):\r\n print(\"Skipping file with invalid JPEG data: %s\" % image.path)\r\n bboxes = image.bboxes\r\n context = tf.train.Features(feature={\r\n \"image/image_id\": _int64_feature(image.image_id),\r\n \"image/data\": _bytes_feature(encoded_image)\r\n })\r\n feature_lists = tf.train.FeatureLists(feature_list={\r\n \"bbox/locations/x_l\": _float_feature_list(bboxes[0]),\r\n \"bbox/locations/y_b\": _float_feature_list(bboxes[1]),\r\n \"bbox/locations/x_r\": _float_feature_list(bboxes[2]),\r\n \"bbox/locations/y_t\": _float_feature_list(bboxes[3]),\r\n \"bbox/categories\": _int64_feature_list(bboxes[4]),\r\n \"image/size\": _int64_feature_list([image.height, image.width, 3])\r\n })\r\n sequence_example = tf.train.SequenceExample(\r\n context=context, feature_lists=feature_lists)\r\n return sequence_example\r\n\r\n\r\ndef _process_image_files(thread_index, ranges, name, images,\r\n decoder, num_shards, out_dir):\r\n # Each thread produces N shards where N = num_shards / num_threads. For\r\n # instance, if num_shards = 128, and num_threads = 2, then the first thread\r\n # would produce shards [0, 64).\r\n num_threads = len(ranges)\r\n assert not num_shards % num_threads\r\n num_shards_per_batch = int(num_shards / num_threads)\r\n indices = ranges[thread_index]\r\n shard_ranges = np.linspace(indices[0], indices[1],\r\n num_shards_per_batch + 1).astype(int)\r\n num_images_in_thread = indices[1] - indices[0]\r\n\r\n counter = 0\r\n for s in range(num_shards_per_batch):\r\n # Generate a sharded version of the file name, e.g. 'train-00002-of-00010'\r\n shard = thread_index * num_shards_per_batch + s\r\n output_filename = \"%s-%.5d-of-%.5d\" % (name, shard, num_shards)\r\n output_file = os.path.join(out_dir, output_filename)\r\n writer = tf.python_io.TFRecordWriter(output_file)\r\n\r\n shard_counter = 0\r\n images_in_shard = np.arange(shard_ranges[s], shard_ranges[s + 1], dtype=int)\r\n for i in images_in_shard:\r\n image = images[i]\r\n sequence_example = _to_sequence_example(image, decoder)\r\n if sequence_example is not None:\r\n writer.write(sequence_example.SerializeToString())\r\n shard_counter += 1\r\n counter += 1\r\n\r\n if not counter % 1000:\r\n print(\"%s [thread %d]: Processed %d of %d items in thread batch.\" %\r\n (datetime.now(), thread_index, counter, num_images_in_thread))\r\n sys.stdout.flush()\r\n\r\n writer.close()\r\n print(\"%s [thread %d]: Wrote %d image-box pairs to %s\" %\r\n (datetime.now(), thread_index, shard_counter, output_file))\r\n sys.stdout.flush()\r\n print(\"%s [thread %d]: Wrote %d image-box pairs to %d shards.\" %\r\n (datetime.now(), thread_index, counter, num_shards_per_batch))\r\n sys.stdout.flush()\r\n\r\n\r\ndef process_data(name, images, num_shards):\r\n \"\"\"\r\n Processes a complete data set and saves it as a TFRecord.\r\n :param name: Unique identifier specifying the dataset.\r\n :param images: List of ImageMetadata.\r\n :param num_shards: Integer number of shards for the output files.\r\n :return: TFRecord dataset\r\n \"\"\"\r\n # No need to break up each image into a separate entity for each bbox.\r\n # Cause each bbox in the same image can share computation of convolution\r\n # images = [ImageMetadata(image.image_id, image.height, image.width, image.path, label)\r\n # for image in images for label in image.labels]\r\n count = len(images)\r\n if count < num_shards:\r\n num_shards = count\r\n # Shuffle the ordering of images. Make the randomization repeatable\r\n random.seed(12345)\r\n random.shuffle(images)\r\n out_dir = os.path.join(FLAGS.output_dir, name)\r\n if not tf.gfile.Exists(out_dir):\r\n tf.gfile.MakeDirs(out_dir)\r\n # Break the images into num_threads batches. Batch i is defined as\r\n # images[ranges[i][0]:ranges[i][1]].\r\n num_threads = min(num_shards, FLAGS.num_threads)\r\n spacing = np.linspace(0, len(images), num_threads + 1).astype(np.int)\r\n ranges = []\r\n threads = []\r\n for i in range(len(spacing) - 1):\r\n ranges.append([spacing[i], spacing[i + 1]])\r\n\r\n # Create a mechanism for monitoring when all threads are finished.\r\n coord = tf.train.Coordinator()\r\n # Create a utility for decoding JPEG images to run sanity checks.\r\n decoder = ImageDecoder()\r\n\r\n # Launch a thread for each batch.\r\n print(\"Launch %d threads for spacings: %s\" % (num_threads, ranges))\r\n for thread_index in range(len(ranges)):\r\n args = (thread_index, ranges, name, images, decoder, num_shards, out_dir)\r\n t = threading.Thread(target=_process_image_files, args=args)\r\n t.start()\r\n threads.append(t)\r\n # Wait for all the threads to terminate.\r\n coord.join(threads)\r\n print(\"%s: Finished processing all %d image-box pairs in data set '%s'.\" %\r\n (datetime.now(), len(images), name))\r\n\r\n\r\ndef debug(id_to_img_info, id_to_bboxes):\r\n arg1 = [entity[0] for entity in id_to_img_info]\r\n arg2 = list(id_to_bboxes.keys())\r\n for v in arg2:\r\n arg1.remove(v)\r\n print(arg1)\r\n\r\n\r\ndef load_and_process_metadata(desc_file, img_dir):\r\n with tf.gfile.FastGFile(desc_file, \"r\") as f:\r\n desc_data = json.load(f)\r\n # Extract filename of image\r\n id_to_img_info = {entity[\"id\"]: (entity[\"file_name\"], entity[\"height\"], entity[\"width\"])\r\n for entity in desc_data[\"images\"]}\r\n # Extract the target label, each image_id may associated with multiple labels\r\n annotations = desc_data[\"annotations\"]\r\n id_to_bboxes = _load_cls_bboxes(annotations, id_to_img_info)\r\n # debug(id_to_img_info, id_to_bboxes)\r\n print(\"Loaded detection metadata for %d images from %s\"\r\n % (len(id_to_img_info), desc_file))\r\n # Process the labels and combine the data into a list of ImageMetadata\r\n print(\"Processing bboxes\")\r\n image_metadata = []\r\n num_bbox = 0\r\n skip_num = 0\r\n for image_id, (base_filename, height, width) in id_to_img_info.items():\r\n if image_id not in id_to_bboxes:\r\n skip_num += 1\r\n continue\r\n bboxes = id_to_bboxes[image_id]\r\n path = os.path.join(img_dir, base_filename)\r\n image_metadata.append(ImageMetadata(image_id, height, width, path, bboxes))\r\n num_bbox += len(bboxes)\r\n assert (len(id_to_img_info) - skip_num) == len(id_to_bboxes)\r\n print(\"Finished processing %d boxs for %d images in %s,\"\r\n \" skip %d images which have no box contained\" %\r\n (num_bbox, len(id_to_img_info), desc_file, skip_num))\r\n return image_metadata\r\n","sub_path":"dataset/build_coco_tfrecord.py","file_name":"build_coco_tfrecord.py","file_ext":"py","file_size_in_byte":11863,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"526901311","text":"import socket\nfrom random import randint\n\nclass Player:\n def __init__(self):\n self.position = 0\n self.zVelocity = 0\n self.playerState = 0\n self.connection = socket.socket()\n\n def connectToSever(self,ipAdress,port):\n self.connection.connect((ipAdress,port))\n\n ###################\n ## PUBLIC GETTER ##\n ###################\n def getVelocity(self):\n command = '\"getVelocity\",'\n command = command.encode(\"utf-8\")\n self.connection.send(command)\n result = self.connection.recv(1024)\n result = result.decode(\"utf-8\")\n return result\n\n def getPosition(self):\n command = '\"getPosition\",'\n command = command.encode(\"utf-8\")\n self.connection.send(command)\n result = self.connection.recv(1024)\n result = result.decode(\"utf-8\")\n \n return result\n\n def getPlayerState(self):\n command = '\"getPlayerState\",'\n command = command.encode(\"utf-8\")\n self.connection.send(command)\n result = self.connection.recv(1024)\n result = result.decode(\"utf-8\")\n return result\n\n ###################\n ## PUBLIC SETTER ##\n ###################\n def setFrequency(self,frequency):\n command = '\"setFrequency\",' + str(frequency)\n command = command.encode(\"utf-8\")\n self.connection.send(command)\n \n \n#s = socket.socket()\n#s.connect((\"192.168.1.8\",1995))\n \np = Player()\nhostName = socket.gethostbyname('localhost')\np.connectToSever(hostName,1995)\n\nwhile True:\n## b = randint(1,50)\n b = 10\n p.setFrequency(b)\n p.getVelocity()\n a = float(p.getPosition())\n print(a)\n print(p.getPlayerState())\n \n","sub_path":"source/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":1717,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"533842725","text":"from rest_framework.permissions import BasePermission, SAFE_METHODS\n\nclass OwnerCanManageReadOnly(BasePermission):\n message = ''\n\n def has_object_permission(self, request, view):\n self.message = 'تو باید ادمین باشی تا بتونی ادیتش کنی باهوش '\n if request.method in SAFE_METHODS:\n return True\n elif not request.user.is_anonymous:\n return True\n else:\n return False\n\n def has_object_permission(self, request, view, obj):\n self.message = 'این پست تو نیست که بتونی ادیتش کنی متاسفم'\n return request.user == obj.owner","sub_path":"app1/permissions.py","file_name":"permissions.py","file_ext":"py","file_size_in_byte":663,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"603602404","text":"\n\nfrom xai.brain.wordbase.nouns._proponent import _PROPONENT\n\n#calss header\nclass _PROPONENTS(_PROPONENT, ):\n\tdef __init__(self,): \n\t\t_PROPONENT.__init__(self)\n\t\tself.name = \"PROPONENTS\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"proponent\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_proponents.py","file_name":"_proponents.py","file_ext":"py","file_size_in_byte":259,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"306700306","text":"from setuptools import setup, find_packages\nimport os\n\n\ndef read(fname):\n return open(os.path.join(os.path.dirname(__file__), fname)).read()\n\n\npkg = {}\nexec (read('aapippackage/__pkg__.py'), pkg)\n\nsetup(\n name=pkg['__package_name__'],\n version=pkg['__version__'],\n description=pkg['__description__'],\n url='',\n author=pkg['__author__'],\n author_email=pkg['__email__'],\n license=pkg['__license__'],\n packages=find_packages(),\n include_package_data=True,\n zip_safe=False,\n test_suite='nose.collector',\n tests_require=['nose']\n)","sub_path":"pypi_install_script/aapippackage-0.9.tar/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":564,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"355412593","text":"#!/usr/bin/python3\r\n# -*- coding: utf-8 -*-\r\nimport atexit\r\nimport time\r\nimport json\r\nimport random\r\nfrom client import Client\r\n\r\ndef check_game_status(game_state):\r\n if game_state['finished']:\r\n print(game_state['reason'])\r\n exit(0)\r\n\r\n\r\nwin_dic = {}\r\nmove_dic = {}\r\n\r\ndef find_move(my_reset, opponent_reset, being_reset, stones_left, possible_move):\r\n # if possible_move<3:\r\n # possible_move = 2\r\n if stones_left<=3:\r\n ## 0 for we win\r\n ## 1 for the opponent wins\r\n ## if there are less or equal to 3 stones left, then it is a win regardless\r\n win_dic[(my_reset, opponent_reset, being_reset, stones_left, possible_move)] = 0\r\n move_dic[(my_reset, opponent_reset, being_reset, stones_left, possible_move)] = (stones_left, 0)\r\n # print(stones_left, 0)\r\n return 0\r\n elif stones_left<=possible_move+1 and being_reset==0:\r\n ## if we are not being reset, and we can possible_move+1 is >=the stones left, then we can just \r\n ## make that move\r\n win_dic[(my_reset, opponent_reset, being_reset, stones_left, possible_move)] = 0\r\n move_dic[(my_reset, opponent_reset, being_reset, stones_left, possible_move)] = (stones_left, 0)\r\n # print(stones_left, 0)\r\n return 0\r\n if (my_reset, opponent_reset, being_reset, stones_left, possible_move) in win_dic:\r\n ## if it is already recorded, then just return it\r\n # print(move_dic[(my_reset, opponent_reset, being_reset, stones_left, possible_move)])\r\n return win_dic[(my_reset, opponent_reset, being_reset, stones_left, possible_move)]\r\n else:\r\n if being_reset==0:\r\n ## if we are not being reset\r\n if_won = False\r\n for i in range(1, max(3, possible_move)+1):\r\n ## if we are using less than possible move steps\r\n if find_move(opponent_reset, my_reset, 0, stones_left-i, max(i, possible_move))==1:\r\n ## if removing i stones will make the other player lose\r\n ## here ==1 means at the opponent's turn, their opponent will win, aka us\r\n if_won = True\r\n move_dic[(my_reset, opponent_reset, being_reset, stones_left, possible_move)] = (i, 0)\r\n break\r\n if not if_won and possible_move>=3:\r\n ## if that did not work\r\n ## we move the possible_move+1 stones\r\n if find_move(opponent_reset, my_reset, 0, stones_left-possible_move-1, possible_move+1)==1:\r\n ## if that will make them lose, then we win\r\n if_won = True\r\n move_dic[(my_reset, opponent_reset, being_reset, stones_left, possible_move)]= (possible_move+1, 0)\r\n \r\n if not if_won and my_reset>0:\r\n ## if the regular moves dont work, then we use the reset\r\n for i in range(1, max(3, possible_move)+1):\r\n if find_move(opponent_reset, my_reset-1, 1, stones_left-i, max(i, possible_move))==1:\r\n if_won = True\r\n move_dic[(my_reset, opponent_reset, being_reset, stones_left, possible_move)] = (i, 1)\r\n break\r\n if not if_won and possible_move>=3:\r\n if find_move(opponent_reset, my_reset-1, 1, stones_left-i-1, possible_move+1)==1:\r\n if_won = True\r\n move_dic[(my_reset, opponent_reset, being_reset, stones_left, possible_move)]= (possible_move+1, 1)\r\n if not if_won:\r\n win_dic[(my_reset, opponent_reset, being_reset, stones_left, possible_move)] = 1\r\n move_dic[(my_reset, opponent_reset, being_reset, stones_left, possible_move)] = (-1, -1)\r\n # print(-1, -1)\r\n return 1\r\n else:\r\n win_dic[(my_reset, opponent_reset, being_reset, stones_left, possible_move)] = 0\r\n # print(move_dic[(my_reset, opponent_reset, being_reset, stones_left, possible_move)])\r\n return 0\r\n\r\n else:\r\n ## if we got reset\r\n if_won = False\r\n for i in range(1, 4):\r\n # first we go over 1, 2, 3, and dont reset the opponent\r\n if find_move(opponent_reset, my_reset, 0, stones_left-i, possible_move)==1:\r\n if_won = True\r\n move_dic[(my_reset, opponent_reset, being_reset, stones_left, possible_move)] = (i, 0)\r\n break\r\n if not if_won and my_reset>0:\r\n ## now we try to reset\r\n for i in range(1, 4):\r\n if find_move(opponent_reset, my_reset-1, 1, stones_left-i, possible_move)==1:\r\n if_won = True\r\n move_dic[(my_reset, opponent_reset, being_reset, stones_left, possible_move)] = (i, 1)\r\n break\r\n if not if_won:\r\n win_dic[(my_reset, opponent_reset, being_reset, stones_left, possible_move)] = 1\r\n move_dic[(my_reset, opponent_reset, being_reset, stones_left, possible_move)] = (-1, -1)\r\n # print(-1, -1)\r\n return 1\r\n else:\r\n win_dic[(my_reset, opponent_reset, being_reset, stones_left, possible_move)] = 0\r\n # print(move_dic[(my_reset, opponent_reset, being_reset, stones_left, possible_move)])\r\n return 0\r\n\r\n\r\n\r\nif __name__ == '__main__':\r\n # Read these from stdin to make life easier\r\n goes_first = True\r\n ip = '127.0.0.1'\r\n port = 9000\r\n client = Client('first noob', goes_first, (ip, port))\r\n atexit.register(client.close)\r\n stones = client.init_stones\r\n resets = client.init_resets\r\n my_reset = 4\r\n opponent_reset = 4\r\n current_max = 0\r\n\r\n if goes_first:\r\n print(\"You made your first move\")\r\n print('Current max: %d' % 0)\r\n print('Stones left: %d' % stones)\r\n\r\n find_move(my_reset, opponent_reset, 0, stones, 0)\r\n num_stones, reset = move_dic[(my_reset, opponent_reset, 0, stones, 0)]\r\n if num_stones == -1:\r\n num_stones, reset = random.randint(1, 4), 0\r\n print(\"dead game\\n------------------------------------------------------------------------------\")\r\n\r\n print('You took %d stones%s' % (num_stones,\r\n ' and used reset.' if reset else '.'))\r\n print(\"--------------------------------------------------------------------\")\r\n check_game_status(client.make_move(num_stones, reset))\r\n if reset == 1:\r\n my_reset = my_reset-1\r\n while True:\r\n game_state = client.receive_move()\r\n # print(game_state)\r\n check_game_status(game_state)\r\n stones = game_state['stones_left']\r\n opponent_use_reset = game_state['reset_used']\r\n if opponent_use_reset:\r\n opponent_reset = opponent_reset-1\r\n print(\"Being reset this turn\")\r\n\r\n ## find a move\r\n ## the current max is 2 if being reset, so we gonna look for one, either current max of stones removed\r\n current_max_this_turn = max(game_state['current_max'], game_state['stones_removed'])\r\n\r\n ## if both of them are less then the max we recorded, then do nothing\r\n ## otherwise replace that value since we need to go to the bottom of the recursion\r\n if current_max_this_turn>current_max:\r\n current_max =current_max_this_turn\r\n\r\n \r\n if ((my_reset, opponent_reset, opponent_use_reset, stones, current_max)) in move_dic:\r\n num_stones, reset = move_dic[(my_reset, opponent_reset, opponent_use_reset, stones, current_max)]\r\n else:\r\n find_move(my_reset, opponent_reset, opponent_use_reset, stones, current_max)\r\n num_stones, reset = move_dic[(my_reset, opponent_reset, opponent_use_reset, stones, current_max)]\r\n\r\n ## if we use a reset, -1\r\n if reset==1:\r\n my_reset = my_reset - 1\r\n\r\n\r\n if num_stones == -1:\r\n print(\"dead game\\n------------------------------------------------------------------------------\")\r\n ## if it is a dead game, we jam them by doing random moves\r\n num_stones, reset = (random.randint(1, max(3, current_max+1))) if not opponent_use_reset else (random.randint(1, 3)), 0\r\n\r\n \r\n # Some parsing logic to convert game state to algo_inputs\r\n # num_stones, reset = my_algo(game_state)\r\n print('Current max: %d' % game_state['current_max'])\r\n print('Stones left: %d' % game_state['stones_left'])\r\n\r\n print('You took %d stones%s' % (num_stones,\r\n ' and used reset.' if reset else '.'))\r\n\r\n # print('Player %s has %d resets left' % (game_state['player_0']['name'], game_state['player_0']['resets_left']))\r\n # print('Player %s has %d resets left' % (game_state['player_1']['name'], game_state['player_1']['resets_left']))\r\n print('---------------------------------------')\r\n if game_state['finished']:\r\n print('Game over\\n%s' % game_state['reason'])\r\n exit(0)\r\n\r\n check_game_status(client.make_move(num_stones, reset))\r\n","sub_path":"NIM/anh_xuan_first.py","file_name":"anh_xuan_first.py","file_ext":"py","file_size_in_byte":9315,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"502004631","text":"import csv\nimport io\nimport psycopg2\nfrom psycopg2.extras import Json\nfrom urllib.request import Request\nfrom urllib.request import urlopen\nfrom ckanapi import RemoteCKAN\n\ndata_gov_ckan = RemoteCKAN('https://data.gov.sg/', user_agent='')\nconn = psycopg2.connect(database='', user='', password=\"\",\n host='', port='5432')\ncur = conn.cursor()\n\n# Access the resource and return a CSV reader\ndef access_resource(resource_url):\n hdr = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11',\n 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',\n 'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.3',\n 'Accept-Encoding': 'none',\n 'Accept-Language': 'en-US,en;q=0.8',\n 'Connection': 'keep-alive'}\n req = Request(resource_url, headers=hdr)\n response = urlopen(req).read().decode('utf-8')\n return csv.reader(io.StringIO(response))\n\ndef read_metadata(package_id):\n print('reading ' + package_id)\n return data_gov_ckan.action.package_metadata_show(id=package_id)\n\ndef save_package_metadata(package_metadata):\n cur.execute(\"insert into package (id, metadata) values (%s, %s)\", (package_metadata['name'], Json(package_metadata)))\n\n# main logic\npackages = data_gov_ckan.action.package_list()\nfor package in packages:\n save_package_metadata(read_metadata(package))\n\nconn.commit()\ncur.close()\nconn.close()\nprint('---------------')\nprint('done!')\n\n","sub_path":"crawl_lambda.py","file_name":"crawl_lambda.py","file_ext":"py","file_size_in_byte":1480,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"615146426","text":"#!/usr/bin/python\n\nimport mraa \nimport time\n\n\"\"\"\nThis script demonstrates the usage of mraa library for configuring and\nusing a GPIO as input port\n\nsetup:\nThe LED is connected port D5 and button is connected to port D6\n\nDemo:\nstart the application in the command line by using following command:\npython button.py\nPress the button to toggle the LED from off to on, on to off...\n\nYou can exit this demo by hitting ctrl+c\n\nLink for this tutorial:\nhttps://navinbhaskar.wordpress.com/2015/04/06/python-on-intel-galileoedison-part-2-buttons/\n\n\n\"\"\"\n\nLED_GPIO = 5 # The LED pin\nBUTTON_GPIO = 6 # The button GPIO\nled = mraa.Gpio(LED_GPIO) # Get the LED pin object\nled.dir(mraa.DIR_OUT) # Set the direction as output\nledState = False # LED is off to begin with\nled.write(0)\n\nbtn = mraa.Gpio(BUTTON_GPIO)\nbtn.dir(mraa.DIR_IN)\n\ndef getButtonPress():\n \n while 1:\n \n if (btn.read() != 0):\n continue\n else:\n time.sleep(0.05)\n if (btn.read() == 1):\n return\n else:\n continue\n\nwhile 1:\n \n getButtonPress()\n if ledState == True:\n led.write(1)\n ledState = False\n else:\n led.write(0)\n ledState = True\n\n time.sleep(0.005)\n","sub_path":"part2-button/button.py","file_name":"button.py","file_ext":"py","file_size_in_byte":1305,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"176397506","text":"# -*- coding: utf-8; -*-\nimport json\nimport jsonschema\nimport common.logger as logger\n\n\ndef validate_json_schema(schema_name):\n \"\"\"Validate the JSON schema defined in test.\n\n :param schema_name: string to name the schema, name is coincident with the schema definition file name\n :return: True if validation is successful or on exception print exception report and fail the test\n \"\"\"\n file_name = 'schemas/%s.json' % schema_name\n file_handler = open(file_name)\n schema_to_validate = json.load(file_handler)\n jsonschema.Draft4Validator.check_schema(schema_to_validate)\n validator = jsonschema.Draft4Validator(schema_to_validate)\n return validator\n\n\ndef validate_json_by_schema(json_data, schema_name, abort_on_exception=False, message_on_exception=True):\n \"\"\"Validate json data with schema\n\n :param json_data: json to validate\n :param schema_name: name of schema to validate json on\n :param abort_on_exception: optional, if True then print exception report in case of validation failure and abort .\n :param message_on_exception: optional, if True then message printed on any exception or failure, message is not printed otherwise\n :return: True on success or False otherwise or on exception print exception report and fail the test\n \"\"\"\n # prepare the validator\n validator = validate_json_schema(schema_name)\n filename = 'schemas/%s.json' % schema_name\n with open(filename) as schema_file:\n schema_json = json.load(schema_file)\n # validate json\n try:\n validator.validate(json_data)\n return True\n except jsonschema.exceptions.ValidationError as e:\n if message_on_exception:\n logger.fail(\"Validate JSON with schema '%s'\" % schema_name)\n logger.debug(\"The schema '%s' is:\\n %s\\n\" % (schema_name, schema_json))\n logger.debug(\"Actual JSON:\\n %s\\n\" % json_data)\n logger.debug(\"The following validation errors found:\\n\")\n errors = sorted(validator.iter_errors(json_data), key=lambda k: k.path)\n for error in errors:\n for suberror in sorted(error.context, key=lambda k: k.schema_path):\n logger.debug(\"%s, %s\" % (list(suberror.schema_path), suberror.message))\n logger.debug(\"Exception text: %s\" % e)\n if abort_on_exception:\n assert False, e\n return False\n","sub_path":"che-test/scripts/autotests/common/json_functions.py","file_name":"json_functions.py","file_ext":"py","file_size_in_byte":2380,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"626407210","text":"# vim:foldmethod=marker\n# XXX: Polish reference to paper in docstring\nimport numpy as np\nimport tensorflow as tf\nfrom tensorflow_mcmc.sampling.mcmc_base_classes import MCMCSampler\n\nfrom tensorflow_mcmc.tensor_utils import (vectorize, unvectorize,\n safe_divide, safe_sqrt)\n\n\nclass RelativisticSGHMCSampler(MCMCSampler):\n def __init__(self, params, Cost, seed=None, epsilon=0.01, m=1.0, c=0.6,\n D=1.0, scale_grad=1.0, batch_generator=None,\n dtype=tf.float64, session=tf.get_default_session()):\n\n \"\"\" Relativistic Stochastic Gradient Hamiltonian Monte-Carlo Sampler.\n\n See [1] for more details on Relativistic SGHMC.\n\n [1] X. Lu, V. Perrone, L. Hasenclever, Y. W. Teh, S. J. Vollmer\n Relativistic Monte Carlo\n\n Parameters\n ----------\n params : list of tensorflow.Variable objects\n Target parameters for which we want to sample new values.\n\n Cost : tensorflow.Tensor\n 1-d Cost tensor that depends on `params`.\n Frequently denoted as U(theta) in literature.\n\n seed : int, optional\n Random seed to use.\n Defaults to `None`.\n\n epsilon : float, optional\n Value that is used as learning rate parameter for the sampler,\n also denoted as discretization parameter in literature.\n Defaults to `0.01`.\n\n m : float, optional\n mass constant.\n Defaults to `1.0`.\n\n c : float, optional\n \"Speed of light constant\"\n Defaults to `0.6`.\n\n D : float, optional\n Diffusion constant\n Defaults to `1.0`.\n\n scale_grad : float, optional\n Value that is used to scale the magnitude of the noise used\n during sampling. In a typical batches-of-data setting this usually\n corresponds to the number of examples in the entire dataset.\n Defaults to `1.0` which corresponds to no scaling.\n\n batch_generator : BatchGenerator, optional\n Iterable which returns dictionaries to feed into\n tensorflow.Session.run() calls to evaluate the cost function.\n Defaults to `None` which indicates that no batches shall be fed.\n\n dtype : tensorflow.DType, optional\n Type of elements of `tensorflow.Tensor` objects used in this sampler.\n Defaults to `tensorflow.float64`.\n\n session : tensorflow.Session, optional\n Session object which knows about the external part of the graph\n (which defines `Cost`, and possibly batches).\n Used internally to evaluate (burn-in/sample) the sampler.\n\n \"\"\"\n\n super().__init__(params=params, batch_generator=batch_generator,\n dtype=dtype, session=session, seed=seed)\n\n self.c = tf.constant(c, dtype=dtype)\n self.m = tf.constant(m, dtype=dtype)\n\n self.Cost = Cost\n\n # Epsilon = tf.constant(epsilon, dtype=dtype)\n Epsilon = tf.constant(epsilon / np.sqrt(scale_grad), dtype=dtype)\n\n grads = [vectorize(gradient) for gradient in\n tf.gradients(self.Cost, params)]\n\n # Sampler Variables {{{ #\n\n # Noise estimate of stochastic gradient (B_hat) {{{ #\n\n Tau = [tf.Variable(tf.ones_like(Param, dtype=dtype),\n dtype=dtype, name=\"Tau_{}\".format(i),\n trainable=False)\n for i, Param in enumerate(self.vectorized_params)]\n\n R = [tf.Variable(1. / (Tau[i].initialized_value() + 1),\n name=\"R_{}\".format(i), trainable=False)\n for i, Param in enumerate(self.vectorized_params)]\n\n G = [tf.Variable(tf.ones_like(Param, dtype=dtype),\n dtype=dtype, name=\"G_{}\".format(i),\n trainable=False)\n for i, Param in enumerate(self.vectorized_params)]\n\n V_hat = [tf.Variable(tf.ones_like(Param, dtype=dtype),\n dtype=dtype, name=\"V_hat_{}\".format(i),\n trainable=False)\n for i, Param in enumerate(self.vectorized_params)]\n\n B_hat = [tf.Variable(0.5 * Epsilon * V_hat.initialized_value(),\n name=\"B_hat_{}\".format(i), dtype=dtype)\n for i, V_hat in enumerate(V_hat)]\n\n # }}} Noise estimate of stochastic gradient (B_hat) #\n\n # Diffusion Terms {{{ #\n D = [tf.Variable(tf.ones_like(Param, dtype=dtype),\n name=\"D_{}\".format(i),\n dtype=dtype, trainable=False)\n for i, Param in enumerate(self.vectorized_params)]\n\n # }}} Diffusion Terms #\n\n # Momentum\n P = [tf.Variable(tf.ones_like(Param, dtype=dtype),\n dtype=dtype, name=\"P_{}\".format(i),\n trainable=False)\n for i, Param in enumerate(self.vectorized_params)]\n\n # Mass term\n M_update = [tf.Variable(self._mass_update(P_0.initialized_value()),\n name=\"Mass_update_{}\".format(i),\n dtype=dtype)\n for i, P_0 in enumerate(P)]\n\n # }}} Sampler Parameters #\n\n self.Theta_t = [None] * len(params)\n\n for i, (Param, Grad) in enumerate(zip(params, grads)):\n Vectorized_Param = self.vectorized_params[i]\n\n R_t = tf.assign(R[i], 1. / (Tau[i] + 1), name=\"R_t_{}\".format(i))\n\n # R_t should always use the old value of Tau\n with tf.control_dependencies([R_t]):\n Tau_t = tf.assign_add(\n Tau[i],\n safe_divide(-G[i] * G[i] * Tau[i], V_hat[i]) + 1,\n name=\"Tau_t_{}\".format(i)\n )\n\n # Tau_t should always use the old values of G, V_hat\n with tf.control_dependencies([Tau_t]):\n G_t = tf.assign_add(\n G[i],\n -R_t * G[i] + R_t * Grad,\n name=\"G_t_{}\".format(i)\n )\n\n V_hat_t = tf.assign_add(\n V_hat[i],\n - R_t * V_hat[i] + R_t * Grad ** 2,\n name=\"V_hat_t_{}\".format(i)\n )\n\n with tf.control_dependencies([G_t, V_hat_t]):\n B_hat_t = tf.assign(\n B_hat[i],\n 0.5 * Epsilon * V_hat_t\n )\n\n # Draw random sample {{{ #\n\n Noise_scale = Epsilon * (2 * D[i] - Epsilon * B_hat_t)\n Sigma = safe_sqrt(Noise_scale)\n Sample = self._draw_noise_sample(\n Sigma=Sigma, Shape=Vectorized_Param.shape\n )\n\n # }}} Draw random sample #\n\n # Equation (9) upper part\n P_t = tf.assign_add(\n P[i],\n -Epsilon * Grad - Epsilon * D[i] * M_update[i] +\n Sample,\n name=\"P_t_{}\".format(i)\n )\n\n # Update mass term for Equation (9) lower part\n M_update_t = tf.assign(\n M_update[i],\n self._mass_update(P_t),\n name=\"M_update_t_{}\".format(i)\n )\n\n # Equation (9) lower part\n Vectorized_Theta_t = tf.assign_add(\n Vectorized_Param,\n Epsilon * M_update_t\n )\n\n self.Theta_t[i] = tf.assign(\n Param,\n unvectorize(\n Vectorized_Theta_t,\n original_shape=Param.shape\n ),\n name=\"Theta_t_{}\".format(i)\n )\n\n def _mass_update(self, P):\n # Equation (10) in the paper\n return safe_divide(\n P,\n tf.sqrt(\n tf.divide(\n tf.matmul(P, P, transpose_a=True), tf.square(self.c)\n ) + tf.square(self.m)\n )\n )\n","sub_path":"sgmcmc/tensorflow_mcmc/sampling/relativistic_sghmc.py","file_name":"relativistic_sghmc.py","file_ext":"py","file_size_in_byte":8530,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"155727715","text":"'''\nUtilities for SenatorBeck Basin Deep Learning\n\nby: Joel A. Gongora\ndate: 10/01/2018\n'''\n\nimport h5py\nimport os\nimport numpy as np\nimport pandas as pd\n\nos.chdir('/Users/joel/PhDResearch/SnowEx/SenatorBeck/PythonCode/scripts/')\n\n\ndef loaddata():\n '''\n This function will load two dataframes [df_train, df_test] each containing\n training and test sets for a CNN.\n '''\n train_dataset = h5py.File('../../hdf5files/sbb_train.hdf5', \"r\")\n test_dataset = h5py.File('../../hdf5files/sbb_test.hdf5', \"r\")\n #\n train_set_x_orig = np.array(train_dataset[\"/train_set_x\"][:])\n train_set_y_orig = np.array(train_dataset[\"/train_set_y\"][:])\n train_set_y_orig_mat = np.array(train_dataset[\"/train_set_y_mat\"][:])\n train_set_utme_orig = np.array(train_dataset[\"/train_set_utme\"][:])\n train_set_utmn_orig = np.array(train_dataset[\"/train_set_utmn\"][:])\n #\n test_set_x_orig = np.array(test_dataset[\"/test_set_x\"][:])\n test_set_y_orig = np.array(test_dataset[\"/test_set_y\"][:])\n test_set_y_orig_mat = np.array(test_dataset[\"/test_set_y_mat\"][:])\n test_set_utme_orig = np.array(test_dataset[\"/test_set_utme\"][:])\n test_set_utmn_orig = np.array(test_dataset[\"/test_set_utmn\"][:])\n #\n X_trainset = np.swapaxes(np.swapaxes(train_set_x_orig, 1, 3), 1, 2)\n Y_trainset = train_set_y_orig\n Y_trainset_mat = np.swapaxes(np.swapaxes(train_set_y_orig_mat, 1, 3), 1, 2)\n utme_trainset = np.swapaxes(np.swapaxes(train_set_utme_orig, 1, 3), 1, 2)\n utmn_trainset = np.swapaxes(np.swapaxes(train_set_utmn_orig, 1, 3), 1, 2)\n #\n X_testset = np.swapaxes(np.swapaxes(test_set_x_orig, 1, 3), 1, 2)\n Y_testset = test_set_y_orig\n Y_testset_mat = np.swapaxes(np.swapaxes(test_set_y_orig_mat, 1, 3), 1, 2)\n utme_testset = np.swapaxes(np.swapaxes(test_set_utme_orig, 1, 3), 1, 2)\n utmn_testset = np.swapaxes(np.swapaxes(test_set_utmn_orig, 1, 3), 1, 2)\n #\n colnames_tr = ['X_trainset', 'Y_trainset', 'Y_trainset_mat',\n 'utme_trainset', 'utmn_trainset']\n #\n colnames_te = ['X_testset', 'Y_testset', 'Y_testset_mat',\n 'utme_testset', 'utmn_testset']\n #\n lytr = [Y_trainset[ix]\n for ix in range(np.shape(Y_trainset)[0])]\n lxtr = [X_trainset[ix, :, :, :]\n for ix in range(np.shape(X_trainset)[0])]\n lytr_mat = [Y_trainset_mat[ix]\n for ix in range(np.shape(Y_trainset_mat)[0])]\n letr = [utme_trainset[ix]\n for ix in range(np.shape(utme_trainset)[0])]\n lntr = [utmn_trainset[ix]\n for ix in range(np.shape(utmn_trainset)[0])]\n lxte = [X_testset[ix, :, :, :]\n for ix in range(np.shape(X_testset)[0])]\n lyte = [Y_testset[ix]\n for ix in range(np.shape(Y_testset)[0])]\n lyte_mat = [Y_testset_mat[ix]\n for ix in range(np.shape(Y_testset_mat)[0])]\n lete = [utme_testset[ix]\n for ix in range(np.shape(utme_testset)[0])]\n lnte = [utmn_testset[ix]\n for ix in range(np.shape(utmn_testset)[0])]\n #\n print(np.shape(lxtr))\n listnames_tr = ['lxtr', 'lytr', 'lytr_mat', 'letr', 'lntr']\n listnames_te = ['lxte', 'lyte', 'lyte_mat', 'lete', 'lnte']\n #\n ll_tr = [eval(listnames_tr[ix]) for ix in range(len(listnames_tr))]\n ll_te = [eval(listnames_te[ix]) for ix in range(len(listnames_te))]\n #\n ldict_tr = {colnames_tr[idx]: ll_tr[idx]\n for idx in range(len(colnames_tr))}\n #\n ldict_te = {colnames_te[idx]: ll_te[idx]\n for idx in range(len(colnames_te))}\n #\n df_tr = pd.DataFrame(ldict_tr)\n df_te = pd.DataFrame(ldict_te)\n #\n return df_tr, df_te\n# Convert to DataFrame\n","sub_path":"utils/cnnutils2.py","file_name":"cnnutils2.py","file_ext":"py","file_size_in_byte":3669,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"264780685","text":"# -*- coding: utf-8 -*-\n\"\"\"Parses for MacOS Wifi log (wifi.log) files.\"\"\"\n\nimport re\n\nimport pyparsing\n\nfrom dfdatetime import time_elements as dfdatetime_time_elements\n\nfrom plaso.containers import events\nfrom plaso.containers import time_events\nfrom plaso.lib import errors\nfrom plaso.lib import definitions\nfrom plaso.lib import timelib\nfrom plaso.parsers import logger\nfrom plaso.parsers import manager\nfrom plaso.parsers import text_parser\n\n\nclass MacWifiLogEventData(events.EventData):\n \"\"\"Mac Wifi log event data.\n\n Attributes:\n action (str): known WiFI action, for example connected to an AP,\n configured, etc. If the action is not known, the value is\n the message of the log (text variable).\n agent (str): name and identifier of process that generated the log message.\n function (str): name of function that generated the log message.\n text (str): log message\n \"\"\"\n\n DATA_TYPE = 'mac:wifilog:line'\n\n def __init__(self):\n \"\"\"Initializes event data.\"\"\"\n super(MacWifiLogEventData, self).__init__(data_type=self.DATA_TYPE)\n self.action = None\n self.agent = None\n self.function = None\n self.text = None\n\n\nclass MacWifiLogParser(text_parser.PyparsingSingleLineTextParser):\n \"\"\"Parses MacOS Wifi log (wifi.log) files.\"\"\"\n\n NAME = 'macwifi'\n DATA_FORMAT = 'MacOS Wifi log (wifi.log) file'\n\n _ENCODING = 'utf-8'\n\n THREE_DIGITS = text_parser.PyparsingConstants.THREE_DIGITS\n THREE_LETTERS = text_parser.PyparsingConstants.THREE_LETTERS\n\n # Regular expressions for known actions.\n _CONNECTED_RE = re.compile(r'Already\\sassociated\\sto\\s(.*)\\.\\sBailing')\n _WIFI_PARAMETERS_RE = re.compile(\n r'\\[ssid=(.*?), bssid=(.*?), security=(.*?), rssi=')\n\n _KNOWN_FUNCTIONS = [\n 'airportdProcessDLILEvent',\n '_doAutoJoin',\n '_processSystemPSKAssoc']\n\n _AGENT = (\n pyparsing.Literal('<') +\n pyparsing.Combine(\n pyparsing.Literal('airportd') + pyparsing.CharsNotIn('>'),\n joinString='', adjacent=True).setResultsName('agent') +\n pyparsing.Literal('>'))\n\n _DATE_TIME = pyparsing.Group(\n THREE_LETTERS.setResultsName('day_of_week') +\n THREE_LETTERS.setResultsName('month') +\n text_parser.PyparsingConstants.ONE_OR_TWO_DIGITS.setResultsName('day') +\n text_parser.PyparsingConstants.TIME_ELEMENTS + pyparsing.Suppress('.') +\n THREE_DIGITS.setResultsName('milliseconds'))\n\n # Log line with a known function name.\n _MAC_WIFI_KNOWN_FUNCTION_LINE = (\n _DATE_TIME.setResultsName('date_time') + _AGENT +\n pyparsing.oneOf(_KNOWN_FUNCTIONS).setResultsName('function') +\n pyparsing.Literal(':') +\n pyparsing.SkipTo(pyparsing.lineEnd).setResultsName('text'))\n\n # Log line with an unknown function name.\n _MAC_WIFI_LINE = (\n _DATE_TIME.setResultsName('date_time') + pyparsing.NotAny(\n _AGENT +\n pyparsing.oneOf(_KNOWN_FUNCTIONS) +\n pyparsing.Literal(':')) +\n pyparsing.SkipTo(pyparsing.lineEnd).setResultsName('text'))\n\n _MAC_WIFI_HEADER = (\n _DATE_TIME.setResultsName('date_time') +\n pyparsing.Literal('***Starting Up***').setResultsName('text'))\n\n _DATE_TIME_TURNED_OVER_HEADER = pyparsing.Group(\n text_parser.PyparsingConstants.MONTH.setResultsName('month') +\n text_parser.PyparsingConstants.ONE_OR_TWO_DIGITS.setResultsName('day') +\n text_parser.PyparsingConstants.TIME_ELEMENTS)\n\n _MAC_WIFI_TURNED_OVER_HEADER = (\n _DATE_TIME_TURNED_OVER_HEADER.setResultsName('date_time') +\n pyparsing.Combine(\n pyparsing.Word(pyparsing.printables) +\n pyparsing.Word(pyparsing.printables) +\n pyparsing.Literal('logfile turned over') +\n pyparsing.LineEnd(),\n joinString=' ', adjacent=False).setResultsName('text'))\n\n # Define the available log line structures.\n LINE_STRUCTURES = [\n ('header', _MAC_WIFI_HEADER),\n ('turned_over_header', _MAC_WIFI_TURNED_OVER_HEADER),\n ('known_function_logline', _MAC_WIFI_KNOWN_FUNCTION_LINE),\n ('logline', _MAC_WIFI_LINE)]\n\n _SUPPORTED_KEYS = frozenset([key for key, _ in LINE_STRUCTURES])\n\n def __init__(self):\n \"\"\"Initializes a parser.\"\"\"\n super(MacWifiLogParser, self).__init__()\n self._last_month = 0\n self._year_use = 0\n\n def _GetAction(self, action, text):\n \"\"\"Parse the well known actions for easy reading.\n\n Args:\n action (str): the function or action called by the agent.\n text (str): mac Wifi log text.\n\n Returns:\n str: a formatted string representing the known (or common) action.\n If the action is not known the original log text is returned.\n \"\"\"\n # TODO: replace \"x in y\" checks by startswith if possible.\n if 'airportdProcessDLILEvent' in action:\n interface = text.split()[0]\n return 'Interface {0:s} turn up.'.format(interface)\n\n if 'doAutoJoin' in action:\n match = self._CONNECTED_RE.match(text)\n if match:\n ssid = match.group(1)[1:-1]\n else:\n ssid = 'Unknown'\n return 'Wifi connected to SSID {0:s}'.format(ssid)\n\n if 'processSystemPSKAssoc' in action:\n wifi_parameters = self._WIFI_PARAMETERS_RE.search(text)\n if wifi_parameters:\n ssid = wifi_parameters.group(1)\n bssid = wifi_parameters.group(2)\n security = wifi_parameters.group(3)\n if not ssid:\n ssid = 'Unknown'\n if not bssid:\n bssid = 'Unknown'\n if not security:\n security = 'Unknown'\n\n return (\n 'New wifi configured. BSSID: {0:s}, SSID: {1:s}, '\n 'Security: {2:s}.').format(bssid, ssid, security)\n\n return text\n\n def _GetTimeElementsTuple(self, key, structure):\n \"\"\"Retrieves a time elements tuple from the structure.\n\n Args:\n key (str): name of the parsed structure.\n structure (pyparsing.ParseResults): structure of tokens derived from\n a line of a text file.\n\n Returns:\n tuple: containing:\n year (int): year.\n month (int): month, where 1 represents January.\n day_of_month (int): day of month, where 1 is the first day of the month.\n hours (int): hours.\n minutes (int): minutes.\n seconds (int): seconds.\n milliseconds (int): milliseconds.\n \"\"\"\n time_elements_tuple = self._GetValueFromStructure(structure, 'date_time')\n # TODO: what if time_elements_tuple is None.\n if key == 'turned_over_header':\n month, day, hours, minutes, seconds = time_elements_tuple\n\n milliseconds = 0\n else:\n _, month, day, hours, minutes, seconds, milliseconds = time_elements_tuple\n\n # Note that dfdatetime_time_elements.TimeElements will raise ValueError\n # for an invalid month.\n month = timelib.MONTH_DICT.get(month.lower(), 0)\n\n if month != 0 and month < self._last_month:\n # Gap detected between years.\n self._year_use += 1\n\n return self._year_use, month, day, hours, minutes, seconds, milliseconds\n\n def _ParseLogLine(self, parser_mediator, key, structure):\n \"\"\"Parse a single log line and produce an event object.\n\n Args:\n parser_mediator (ParserMediator): mediates interactions between parsers\n and other components, such as storage and dfvfs.\n key (str): name of the parsed structure.\n structure (pyparsing.ParseResults): structure of tokens derived from\n a line of a text file.\n \"\"\"\n time_elements_tuple = self._GetTimeElementsTuple(key, structure)\n\n try:\n date_time = dfdatetime_time_elements.TimeElementsInMilliseconds(\n time_elements_tuple=time_elements_tuple)\n except ValueError:\n parser_mediator.ProduceExtractionWarning(\n 'invalid date time value: {0!s}'.format(time_elements_tuple))\n return\n\n self._last_month = time_elements_tuple[1]\n\n function = self._GetValueFromStructure(structure, 'function')\n\n text = self._GetValueFromStructure(structure, 'text')\n if text:\n text = text.strip()\n\n event_data = MacWifiLogEventData()\n event_data.agent = self._GetValueFromStructure(structure, 'agent')\n event_data.function = function\n event_data.text = text\n\n if key == 'known_function_logline':\n event_data.action = self._GetAction(\n event_data.function, event_data.text)\n\n event = time_events.DateTimeValuesEvent(\n date_time, definitions.TIME_DESCRIPTION_ADDED)\n parser_mediator.ProduceEventWithEventData(event, event_data)\n\n def ParseRecord(self, parser_mediator, key, structure):\n \"\"\"Parses a log record structure and produces events.\n\n Args:\n parser_mediator (ParserMediator): mediates interactions between parsers\n and other components, such as storage and dfvfs.\n key (str): name of the parsed structure.\n structure (pyparsing.ParseResults): structure of tokens derived from\n a line of a text file.\n\n Raises:\n ParseError: when the structure type is unknown.\n \"\"\"\n if key not in self._SUPPORTED_KEYS:\n raise errors.ParseError(\n 'Unable to parse record, unknown structure: {0:s}'.format(key))\n\n self._ParseLogLine(parser_mediator, key, structure)\n\n def VerifyStructure(self, parser_mediator, line):\n \"\"\"Verify that this file is a Mac Wifi log file.\n\n Args:\n parser_mediator (ParserMediator): mediates interactions between parsers\n and other components, such as storage and dfvfs.\n line (str): line from a text file.\n\n Returns:\n bool: True if the line is in the expected format, False if not.\n \"\"\"\n self._last_month = 0\n self._year_use = parser_mediator.GetEstimatedYear()\n\n key = 'header'\n\n try:\n structure = self._MAC_WIFI_HEADER.parseString(line)\n except pyparsing.ParseException:\n structure = None\n\n if not structure:\n key = 'turned_over_header'\n\n try:\n structure = self._MAC_WIFI_TURNED_OVER_HEADER.parseString(line)\n except pyparsing.ParseException:\n structure = None\n\n if not structure:\n logger.debug('Not a Mac Wifi log file')\n return False\n\n time_elements_tuple = self._GetTimeElementsTuple(key, structure)\n\n try:\n dfdatetime_time_elements.TimeElementsInMilliseconds(\n time_elements_tuple=time_elements_tuple)\n except ValueError:\n logger.debug(\n 'Not a Mac Wifi log file, invalid date and time: {0!s}'.format(\n time_elements_tuple))\n return False\n\n self._last_month = time_elements_tuple[1]\n\n return True\n\n\nmanager.ParsersManager.RegisterParser(MacWifiLogParser)\n","sub_path":"plaso/parsers/mac_wifi.py","file_name":"mac_wifi.py","file_ext":"py","file_size_in_byte":10474,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"87230580","text":"# 2070. Most Beautiful Item for Each Query\n# vbc 65\n# 2021/11/15\n\n# Runtime: 1304 ms, faster than 100.00% of Python3 online submissions for Most Beautiful Item for Each Query.\n# Memory Usage: 77.6 MB, less than 7.69% of Python3 online submissions for Most Beautiful Item for Each Query.\n\n# 排序 + 最大堆问题。做过很多类似的题。\n# 将item和query都按照价格从小到大来排列\n# 从最小的query开始遍历,将价格比该query小的物品全部存入最大堆中即可。\n# 实际上并不需要最大堆,只要track当前的最大值即可。\n\nclass Solution:\n def maximumBeauty(self, items: List[List[int]], queries: List[int]) -> List[int]:\n ans = [0] * len(queries)\n items, start = sorted(items), 0\n queries = [(p, i) for i, p in enumerate(queries)]\n queries.sort()\n max_beauty = []\n for p, i in queries:\n while start < len(items) and items[start][0] <= p:\n heapq.heappush(max_beauty, -items[start][1])\n start += 1\n if max_beauty:\n ans[i] = -max_beauty[0]\n return ans","sub_path":"2070. Most Beautiful Item for Each Query.py","file_name":"2070. Most Beautiful Item for Each Query.py","file_ext":"py","file_size_in_byte":1119,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"430796928","text":"def triangle(row):\n dicts = {'GG':'G', 'BB':'B', 'RR':'R', 'BR':'G', 'BG':'R', 'GB':'R', 'GR':'B', 'RG':'B', 'RB':'G'}\n if len(row) > 2:\n s = ''\n for i in range(len(row) - 1):\n s = s + dicts[row[i:i + 2]]\n row = s\n return triangle(row)\n elif len(row) > 1:\n return dicts[row]\n else:\n return row","sub_path":"CodeWars/7 Kyu/Coloured Triangles.py","file_name":"Coloured Triangles.py","file_ext":"py","file_size_in_byte":358,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"102198375","text":"# Alla metoder ska skrivas under klass. med den indentering som finns nedan\nclass Contact(object):\n def __init__(self, name):\n self.name = name\n self.phone_num = \"\"\n self.append_to_name(\", Efternamn\")\n\n def append_to_name(self, string_to_append):\n self.name += string_to_append\n\n def __str__(self):\n return \"{}, {}\".format(self.name, self.phone_num)\n\nc1 = Contact(\"c1\")\nc1.phone_num = \"0701-111111\"\nc2 = Contact(\"c2\")\nc2.phone_num = \"0702-222222\"\n\n# Nedan skrevs ut enligt övning 3, men när övving 5 skrevs ut skrevs dess ut\n# i onödan, därav lagda som kommentarer istället för att de ska skrivas ut\n# en extra gång\n\n# print(c1.name)\n# print(c2.name)\n\ncontact_list = [c1, c2, Contact(\"c3\")]\n\nfor contact in contact_list:\n print(contact)\n","sub_path":"lab5/lektion_5.py","file_name":"lektion_5.py","file_ext":"py","file_size_in_byte":792,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"378603778","text":"import requests\nimport html.parser\n#import xml.etree.ElementTree as ET\nimport json\nfrom bs4 import BeautifulSoup\nimport os.path\nimport sys\n\nif len(sys.argv) != 3:\n print(\"Usage: getjson.py url CharName\")\n sys.exit()\n\nif os.path.isfile(sys.argv[2] + \".json\"):\n print(\"json file already exists.\")\n sys.exit()\n\nheaders = {\n 'User-Agent': 'My User Agent 1.0',\n}\n\nr = requests.get(sys.argv[1], headers=headers)\n#s = requests.session()\n#response = s.get(sys.argv[1])\n#print(r.text)\nsoup = BeautifulSoup(r.text, 'html.parser')\nprint(soup)\n\nt = soup.find_all('table')\nr = t[0].find_all('tr')\nr.pop(0) #remove the header row\n\nmoves = []\nfor row in r:\n move = {}\n columns = row.find_all('td')\n move['notation'] = columns[0].text\n move['hit_level'] = columns[1].text\n move['damage'] = columns[2].text\n move['speed'] = columns[3].text\n move['on_block'] = columns[4].text\n move['on_hit'] = columns[5].text\n move['on_ch'] = columns[6].text\n move['notes'] = columns[7].text\n moves.append(move)\n\nmeta = {\"ver\": \"0.4\", \"game\": \"t7\", \"character\": sys.argv[2], \"name\": sys.argv[2], \"type\": \"normal\"}\nchar = {\"moves\": moves, \"metadata\":meta}\nf = open(sys.argv[2] + \".json\", \"w\")\nf.write(json.dumps(char, sort_keys=False, indent=4, separators=(',', ': ')))","sub_path":"TekkenData/Movelists/json-Needs fixing/getjson.py","file_name":"getjson.py","file_ext":"py","file_size_in_byte":1283,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"144578348","text":"import numpy as np\r\n\r\ndef central_difference(I):\r\n \"\"\"\r\n Computes the gradient in the u and v direction using\r\n a central difference filter, and returns the resulting\r\n gradient images (Iu, Iv) and the gradient magnitude Im.\r\n \"\"\"\r\n Iu = np.zeros_like(I) # Placeholder\r\n Iv = np.zeros_like(I) # Placeholder\r\n Im = np.zeros_like(I) # Placeholder\r\n rows,cols = I.shape\r\n kernel = np.array([0.5, 0, -0.5])\r\n\r\n for i in range(rows):\r\n Iu[i,:] = np.convolve(I[i,:], kernel, mode='same')\r\n for j in range(cols):\r\n Iv[:,j] = np.convolve(I[:,j], kernel, mode='same')\r\n Im = np.sqrt(Iu**2 + Iv**2)\r\n \r\n return Iu, Iv, Im\r\n\r\n# Task 1b\r\ndef blur(I, sigma):\r\n \"\"\"\r\n Applies a 2-D Gaussian blur with standard deviation sigma to\r\n a grayscale image I.\r\n \"\"\"\r\n w = 2*np.ceil(3*sigma) + 1\r\n kernel = np.linspace(-(w-1)/2, (w-1)/2, w)\r\n rows,cols = I.shape\r\n result = np.zeros_like(I)\r\n for i in range(rows):\r\n result[i,:] = np.convolve(I[i,:], kernel, mode='same')\r\n for j in range(cols):\r\n result[:,j] = np.convolve(I[:,j], kernel, mode='same') \r\n return result\r\n\r\ndef __convolve(kernel, img):\r\n convolved_img = np.array(img)\r\n N = img.shape[0]\r\n for row in range(N):\r\n convolved_img[row,:] = np.convolve(img[row,:], kernel, mode='same')\r\n return convolved_img\r\n\r\ndef __gaussian(blur_sigma):\r\n k = np.arange(5) - 2\r\n gauss_k = (1 / (2*np.pi*blur_sigma**2)) * np.exp(-0.5 * k**2 / (2*blur_sigma**2))\r\n return gauss_k\r\n\r\n# Task 1c\r\ndef extract_edges(Iu, Iv, Im, threshold):\r\n \"\"\"\r\n Returns the u and v coordinates of pixels whose gradient\r\n magnitude is greater than the threshold.\r\n \"\"\"\r\n\r\n # This is an acceptable solution for the task (you don't\r\n # need to do anything here). However, it results in thick\r\n # edges. If you want better results you can try to replace\r\n # this with a thinning algorithm as described in the text.\r\n v,u = np.nonzero(Im > threshold)\r\n theta = np.arctan2(Iv[v,u], Iu[v,u])\r\n return u, v, theta\r\n\r\ndef rgb2gray(I):\r\n \"\"\"\r\n Converts a red-green-blue (RGB) image to grayscale brightness.\r\n \"\"\"\r\n return 0.2989*I[:,:,0] + 0.5870*I[:,:,1] + 0.1140*I[:,:,2]","sub_path":"exercise5/python/common1.py","file_name":"common1.py","file_ext":"py","file_size_in_byte":2248,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"14673379","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sun Mar 8 15:35:24 2020\r\n\r\n@author: raulm\r\n\"\"\"\r\n\r\n# Imports\r\nimport scipy.io\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport sounddevice as sd\r\n\r\n# Import helper functions\r\nfrom helper_functions import awgn, sliding_window, sliding_window_rec, Yule_Walker, kalman_ite\r\n\r\n# KALMAN FILTER TO DENOISE VOICE SIGNAL\r\n\r\nsignal_number = 1\r\n\r\n# Load signals\r\nif (signal_number==1):\r\n signal = scipy.io.loadmat('fcno01fz.mat')\r\n signal = np.array(signal[\"fcno01fz\"])\r\nelse:\r\n signal = scipy.io.loadmat('fcno02fz.mat')\r\n signal = np.array(signal[\"fcno02fz\"])\r\n\r\nFs = 8000 # 8 kHz sample frequency\r\n\r\n# Signal length\r\nN = signal.shape[0]\r\n\r\n# time vector\r\nt = np.arange(0,N/Fs,1/Fs)\r\nt = np.reshape(t,(len(t),1))\r\n\r\n# frequency vector\r\nfreq = np.linspace(-Fs/2,Fs/2,N)\r\nfreq = np.reshape(freq,(len(freq),1))\r\n\r\n# Yules-Walker and AR parameters\r\np = 16 # AR order\r\nite_kalman = 10 # We apply YW-KALMAN a few times to each slice\r\n\r\n# Noise addition\r\nSNR = 10 #dB\r\nnoisy_signal, wg_noise = awgn(signal,SNR)\r\n\r\n# Plot noisy signal and original signal\r\nplt.figure()\r\nplt.grid()\r\nplt.title('Original signal vs Noisy signal')\r\nplt.plot(t,signal)\r\nplt.plot(t,noisy_signal,'r--',linewidth=0.7)\r\nplt.xlabel('Time (s)')\r\nplt.ylabel('Amplitude')\r\nplt.legend(['Original signal','Noisy signal'])\r\n\r\n# Noise variance estimation (using silence )\r\nvarNoise = np.var(noisy_signal[1:4500])\r\n\r\n# Sliced signal\r\nsignal_sliced_windowed, padding = sliding_window(signal,Fs)\r\n\r\n# Save after filtering\r\nsignal_sliced_windowed_filtered = np.zeros((signal_sliced_windowed.shape))\r\n\r\n\r\nfor ite_slice in range(signal_sliced_windowed.shape[1]):\r\n \r\n # Slice n\r\n slice_signal = signal_sliced_windowed[:,ite_slice:ite_slice+1].T\r\n \r\n # On fait YW-KALMAN plusieurs tours pour chaque morceau\r\n for ite in range(ite_kalman):\r\n # YW\r\n a, var_bruit = Yule_Walker( slice_signal,p )\r\n# ar, variance, coeff_reflection = aryule(slice_signal, p)\r\n \r\n # Save\r\n signal_filtered = np.zeros((1,signal_sliced_windowed.shape[0]))\r\n \r\n # Phi et H\r\n Phi = np.concatenate((np.zeros((p-1,1)),np.eye(p-1)),axis=1)\r\n Phi = np.concatenate((Phi,-np.fliplr(a[1:].T)),axis=0)\r\n \r\n H = np.concatenate((np.zeros((p-1,1)), np.ones((1,1))),axis=0).T\r\n \r\n # Q, R and Po\r\n Q = var_bruit*np.eye(p)\r\n R = varNoise\r\n P = 10000*np.eye(p)\r\n\r\n # Initialisation vecteur d'etat\r\n x = np.zeros((p,1))\r\n\r\n for jj in range(signal_sliced_windowed.shape[0]):\r\n y = slice_signal[0][jj] # Observation\r\n [x, P] = kalman_ite(x,P,y,Q,R,Phi,H)\r\n signal_filtered[0][jj] = x[-1]\r\n \r\n slice_signal = signal_filtered\r\n signal_sliced_windowed_filtered[:,ite_slice:ite_slice+1] = signal_filtered.T\r\n\r\n\r\n# Reconstruct signal\r\nsignal_reconstructed = sliding_window_rec(signal_sliced_windowed_filtered,Fs,padding)\r\n\r\n# Plot reconstructed signal and original signal\r\nplt.figure()\r\nplt.grid()\r\nplt.title('Noisy signal vs Reconstructed signal')\r\nplt.plot(t,noisy_signal)\r\nplt.plot(t,signal_reconstructed,'r--',linewidth=0.7)\r\nplt.xlabel('Time (s)')\r\nplt.ylabel('Amplitude')\r\nplt.legend(['Noisy signal','Reconstructed signal'])\r\n\r\n\r\n# Play Sound\r\nsd.play(signal, Fs, blocking=True)\r\nsd.play(wg_noise, Fs, blocking=True)\r\nsd.play(noisy_signal, Fs, blocking=True)\r\nsd.play(signal_reconstructed, Fs, blocking=True)\r\n","sub_path":"DenoiseMain.py","file_name":"DenoiseMain.py","file_ext":"py","file_size_in_byte":3485,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"517245444","text":"import time,random\nimport pytest\nfrom selenium import webdriver\n\n\n\nclass TestSlyder:\n\n '''\n 测试UI库微营销模块_大转盘活动\n '''\n AUTHOR = 'XZ'\n activity_name=u\"【大转盘活动】\" + ''.join(random.sample(['z','y','x','w','v','u','t','s','r','q','p','o','n','m','l','k','j','i','h','g','f','e','d','c','b','a'], 5))\n newname=u\"【修改大转盘活动】\" + ''.join(random.sample(['z','y','x','w','v','u','t','s','r','q','p','o','n','m','l','k','j','i','h','g','f','e','d','c','b','a'], 5))\n\n @pytest.fixture(autouse=True)\n def setup(self, conf):\n self.conf = conf\n self.admin = conf.ui.Admin(conf)\n self.promotion = conf.ui.admin.market.PromotActivity(conf)\n\n self.slyderAPI = conf.api.Market(conf)\n self.slyderparam = conf.param.Market(conf)\n\n self.LC = self.admin.market.LOCATOR\n driver = webdriver.Chrome()\n self.driver = driver\n conf.COMMON.login(conf, driver)\n\n def test_slyder_info(self):\n '''\n 用例:大转盘活动页面检查\n '''\n self.admin.common.top_menu('微营销')\n self.admin.common.market_menu(\"大转盘\")\n slyderResponse = self.slyderAPI.slyder_list()\n slyderList = slyderResponse['errmsg']['data']\n slyderlNum = len(slyderList)\n # 获取页面显示活动数\n pageslyderNum = self.promotion.slyder_get_matching_xpath_count('活动名称栏')\n assert slyderlNum == pageslyderNum\n # 众筹活动页面校验\n self.promotion.check_slyder_info(slyderList)\n #分页操作\n #self.promotion.collect_zan_choose_page(\"页面总条数\")\n self.admin.common.choose_page(\"页面总条数\")\n self.driver.close()\n\n\n def test_slyder_add(self):\n '''\n 用例:添加大转盘活动\n '''\n driver = self.driver\n click = self.promotion.slyder_click\n input = self.promotion.slyder_input\n choose = self.promotion.slyder_choose\n get_text = self.promotion.slyder_get_text\n self.admin.common.top_menu('微营销')\n self.admin.common.market_menu(\"大转盘\")\n click(\"新增活动\")\n time.sleep(2)\n choose(\"选择大转盘模板\")\n #活动名称\n input(\"活动名称\",self.activity_name)\n #选择抽奖对象\n choose(\"抽奖对象\")\n #选择活动时间\n self.admin.common.choose_endtime(\"活动结束时间\")\n self.admin.common.choose_starttime(\"活动开始时间\")\n time.sleep(1)\n #活动类型\n choose(\"活动类型\")\n #填写用户信息规则\n click(\"填写用户信息规则\")\n self.promotion.fill_user_info()\n #是否使用积分抽奖\n self.promotion.point_lottery()\n #次数限制类型\n choose(\"次数限制类型\")\n #限制参与次数\n input(\"限制参与次数\",random.randint(1,3))\n #中奖次数限制\n choose(\"中奖次数限制\")\n #补充活动说明\n input(\"补充活动说明\",u\"补充活动说明。。。。\"+self.conf.Utils.rand_str())\n #滚动滚动条\n self.promotion.slyder_scroll_to(self.driver,\"补充活动说明\")\n #活动奖励设置\n input(\"未中奖说明\",u\"谢谢参与!\")\n #一等奖设置\n self.promotion.first_prize_setting()\n #二等奖设置\n self.promotion.second_prize_setting()\n #三等奖设置\n self.promotion.third_prize_setting()\n #添加奖项\n click(\"添加奖项按钮\")\n #四等奖设置\n self.promotion.fourth_prize_setting()\n #删除奖项\n click(\"添加奖项按钮\")\n click(\"删除奖项按钮\")\n time.sleep(1)\n self.promotion.slyder_scroll_to(self.driver,\"补充活动说明\")\n #兑奖结束时间设置\n self.promotion.exchange_prize_endtime()\n #图文信息设置\n self.promotion.slyder_scroll_to(self.driver,\"图文标题\")\n input(\"图文标题\", u\"图文标题-\" + self.conf.Utils.rand_str())\n input(\"摘要内容\",u\"摘要内容-\"+self.conf.Utils.rand_str())\n click(\"图片\")\n self.promotion.slyder_choose_picture()\n #分享设置\n self.promotion.slyder_scroll_to(self.driver,\"分享标题\")\n input(\"分享标题\",u\"分享标题-\"+self.conf.Utils.rand_str())\n input(\"分享内容\", u\"分享描述-\" + self.conf.Utils.rand_str())\n time.sleep(0.5)\n click(\"分享图标\")\n self.promotion.slyder_choose_picture()\n self.admin.market.common.click(\"保存并关闭\")\n time.sleep(1)\n self.driver.switch_to_alert().accept()\n time.sleep(10)\n #页面校验\n time.sleep(2)\n activity_name1 = get_text('大转盘活动名称')\n print('activity_name1:',activity_name1)\n time.sleep(1)\n assert self.activity_name==activity_name1,u\"添加大转盘活动失败\"\n print(\"添加大转盘活动成功\")\n time.sleep(1)\n self.driver.close()\n\n\n def test_slyder_status(self):\n '''\n 用例:开启和关闭大转盘活动\n '''\n click = self.promotion.slyder_click\n self.admin.common.top_menu('微营销')\n self.admin.common.market_menu(\"大转盘\")\n #随机获取活动名称\n count = self.promotion.slyder_get_matching_xpath_count('活动名称栏')\n activitynameIndex = random.randint(1,count)\n activityName = self.promotion.slyder_get_activity_text('活动名称栏',activitynameIndex)\n click(\"状态\",activityName)\n #切换状态\n #click(\"状态\",self.activity_name)\n time.sleep(0.8)\n self.driver.switch_to_alert().accept()\n time.sleep(0.8)\n #切换状态\n click(\"状态\",activityName)\n time.sleep(0.8)\n self.driver.switch_to_alert().accept()\n self.driver.close()\n\n\n def test_slyder_check_note(self):\n\n '''\n 用例:\n 查看大转盘活动的日志\n '''\n click = self.promotion.slyder_click\n get_text = self.promotion.slyder_get_text\n self.admin.common.top_menu('微营销')\n self.admin.common.market_menu(\"大转盘\")\n #随机获取活动名称\n count = self.promotion.slyder_get_matching_xpath_count('活动名称栏')\n activitynameIndex = random.randint(1,count)\n activityName = self.promotion.slyder_get_activity_text('活动名称栏',activitynameIndex)\n click(\"查看日志按钮\",activityName)\n time.sleep(2)\n note=get_text('操作日志页面')\n assert note==\"操作日志\",\"查看操作日志页面校验失败\"\n print(\"查看操作日志校验成功\")\n time.sleep(0.5)\n #分页操作\n self.admin.common.choose_page(\"页面总条数\")\n self.driver.close()\n\n def test_slyder_check_code(self):\n\n '''\n 用例:\n 查看大转盘活动的二维码\n '''\n click = self.promotion.slyder_click\n get_text = self.promotion.slyder_get_text\n self.admin.common.top_menu('微营销')\n self.admin.common.market_menu(\"大转盘\")\n time.sleep(1)\n now_handle=self.driver.current_window_handle #获取当前窗口的句柄\n time.sleep(1)\n #随机获取活动名称\n count = self.promotion.slyder_get_matching_xpath_count('活动名称栏')\n activitynameIndex = random.randint(1,count)\n activityName = self.promotion.slyder_get_activity_text('活动名称栏',activitynameIndex)\n click(\"查看二维码按钮\",activityName)\n time.sleep(2)\n time.sleep(2)\n all_handles=self.driver.window_handles\n for handle in all_handles:\n if handle != now_handle:\n self.driver.switch_to_window(handle)\n erweimaPage = get_text('二维码页面')\n guishu = get_text('二维码归属')\n assert erweimaPage == \"二维码\",\"二维码页面校验失败\"\n print(\"二维码页面校验成功\")\n assert guishu == \"自动化测试分店\",\"二维码归属栏校验失败\"\n print(\"二维码归属栏校验成功\")\n time.sleep(1)\n click(\"查看二维码\")\n time.sleep(3)\n click(\"关闭二维码\")\n time.sleep(1)\n self.driver.close()\n time.sleep(1)\n self.driver.switch_to_window(now_handle) # 返回主窗口\n time.sleep(1)\n self.driver.close()\n\n\n\n\n def test_slyder_edit(self):\n '''\n 用例:编辑大转盘活动\n '''\n driver = self.driver\n click = self.promotion.slyder_click\n input = self.promotion.slyder_input\n choose = self.promotion.slyder_choose\n get_text = self.promotion.slyder_get_text\n self.admin.common.top_menu('微营销')\n self.admin.common.market_menu(\"大转盘\")\n time.sleep(2)\n click(\"编辑大转盘活动\",self.activity_name)\n time.sleep(2)\n #活动名称\n input(\"活动名称\",self.newname)\n #选择抽奖对象\n choose(\"抽奖对象\")\n #选择活动时间\n self.admin.common.choose_endtime(\"活动结束时间\")\n self.admin.common.choose_starttime(\"活动开始时间\")\n time.sleep(1)\n #活动类型\n choose(\"活动类型\")\n #是否使用积分抽奖\n self.promotion.point_lottery()\n #次数限制类型\n choose(\"次数限制类型\")\n #限制参与次数\n time.sleep(1)\n input(\"限��参与次数\",random.randint(1,3))\n #中奖次数限制\n choose(\"中奖次数限制\")\n #补充活动说明\n input(\"补充活动说明\",u\"补充活动说明。。。。\"+self.conf.Utils.rand_str())\n #滚动滚动条\n self.promotion.slyder_scroll_to(self.driver,\"补充活动说明\")\n #活动奖励设置\n input(\"未中奖说明\",u\"谢谢参与!\")\n #一等奖设置\n self.promotion.first_prize_setting()\n #二等奖设置\n self.promotion.second_prize_setting()\n #兑奖结束时间设置\n self.promotion.exchange_prize_endtime()\n self.promotion.slyder_scroll_to(self.driver,\"图片\")\n #图文信息设置\n self.promotion.slyder_scroll_to(self.driver,\"图文标题\")\n input(\"图文标题\", u\"图文标题-\" + self.conf.Utils.rand_str())\n input(\"摘要内容\",u\"摘要内容-\"+self.conf.Utils.rand_str())\n click(\"图片\")\n self.promotion.slyder_choose_picture()\n #分享设置\n self.promotion.slyder_scroll_to(self.driver,\"分享标题\")\n input(\"分享标题\",u\"分享标题-\"+self.conf.Utils.rand_str())\n input(\"分享内容\", u\"分享描述-\" + self.conf.Utils.rand_str())\n time.sleep(0.5)\n click(\"分享图标\")\n self.promotion.slyder_choose_picture()\n self.admin.market.common.click(\"保存并关闭\")\n time.sleep(1)\n self.driver.switch_to_alert().accept()\n time.sleep(5)\n assert self.driver.title==u\"大转盘活动列表\", u\"页面元素加载失败\"\n time.sleep(1)\n #页面校验\n activity_name1 = get_text('修改后大转盘活动名称',self.newname)\n print('activity_name1:',activity_name1)\n time.sleep(1)\n assert self.newname==activity_name1,u\"编辑大转盘活动失败\"\n print(\"编辑大转盘活动成功\")\n time.sleep(1)\n self.driver.close()\n\n\n\n def test_slyder_del(self):\n '''\n 用例:删除大转盘活动\n '''\n # 执行用例\n click = self.promotion.slyder_click\n self.admin.common.top_menu('微营销')\n self.admin.common.market_menu(\"大转盘\")\n click(\"删除大转盘活动\",self.newname)\n time.sleep(1)\n self.admin.market.common.click(\"删除\")\n self.driver.switch_to_alert().accept()\n time.sleep(2)\n assert self.newname not in \"活动名称栏\",\"删除大转盘活动失败\"\n print(\"删除大转盘活动成功\")\n time.sleep(1)\n self.driver.close()\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"Test/wkd/tests/ui/admin/market/test_slyder.py","file_name":"test_slyder.py","file_ext":"py","file_size_in_byte":12303,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"6701533","text":"# Configuration file for the Sphinx documentation builder.\n#\n# This file only contains a selection of the most common options. For a full\n# list see the documentation:\n# https://www.sphinx-doc.org/en/master/usage/configuration.html\n\n# -- Path setup --------------------------------------------------------------\n\n# If extensions (or modules to document with autodoc) are in another directory,\n# add these directories to sys.path here. If the directory is relative to the\n# documentation root, use os.path.abspath to make it absolute, like shown here.\nimport os\nimport sys\nimport sphinx_rtd_theme\n\n# -- Add module, and scripts paths to the system path --\n# sys.path.insert(0, os.path.join(os.path.abspath(os.path.dirname(__name__)), \"../../\"))\n# sys.path.insert(0, os.path.join(os.path.abspath(os.path.dirname(__name__)), \"..\"))\nsys.path.insert(\n 0,\n os.path.join(os.path.abspath(os.path.dirname(__name__)), \"../panda_openai_sim/src\"),\n)\nsys.path.insert(\n 0,\n os.path.abspath(\n os.path.join(os.path.dirname(__name__), \"../../panda_openai_sim/nodes\")\n ),\n)\nsys.path.insert(\n 0,\n os.path.abspath(\n os.path.join(os.path.dirname(__name__), \"../../panda_training/scripts\")\n ),\n)\nsys.path.insert(\n 0,\n os.path.join(os.path.abspath(os.path.dirname(__name__)), \"../panda_training\"),\n)\n\n# -- Project information -----------------------------------------------------\nproject = \"gazebo-panda-gym\"\ncopyright = \"2020, Rick Staa\"\nauthor = \"Rick Staa\"\n\n# The full version, including alpha/beta/rc tags\nrelease = \"0.0.0\"\n\n\n# -- General configuration ---------------------------------------------------\n\n# Add any Sphinx extension module names here, as strings. They can be\n# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom\n# ones.\n\n# Extensions\nextensions = [\n \"sphinx.ext.napoleon\",\n \"sphinx.ext.autodoc\",\n \"sphinx.ext.autosummary\",\n \"sphinx.ext.intersphinx\",\n \"sphinx.ext.viewcode\",\n \"sphinx.ext.githubpages\",\n \"sphinx.ext.extlinks\",\n]\n\n# Extension settings\nautoclass_content = \"class\"\nautodoc_member_order = \"bysource\"\nautodoc_default_options = {\n \"show-inheritance\": True,\n \"private-members\": True,\n}\nnapoleon_include_special_with_doc = True\nnapoleon_include_init_with_doc = True\nautosummary_generate = True\n\n# Add mappings\nintersphinx_mapping = {\n \"python\": (\"https://docs.python.org/3\", None),\n \"numpy\": (\"https://numpy.org/doc/stable/\", None),\n}\n\n# Add any paths that contain templates here, relative to this directory.\ntemplates_path = [\"_templates\"]\n\n# The suffix(es) of source filenames.\n# You can specify multiple suffix as a list of string:\n# source_suffix = [\".rst\", \".md\"]\nsource_suffix = \".rst\"\n\n# List of patterns, relative to source directory, that match files and\n# directories to ignore when looking for source files.\n# This pattern also affects html_static_path and html_extra_path.\nexclude_patterns = []\n\n# The master toctree document.\nmaster_doc = \"index\"\n\n# The name of the Pygments (syntax highlighting) style to use.\npygments_style = \"sphinx\"\n\n# If true, `todo` and `todoList` produce output, else they produce nothing.\ntodo_include_todos = False\n\n# -- Options for HTML output -------------------------------------------------\n\n# The theme to use for HTML and HTML Help pages. See the documentation for\n# a list of builtin themes.\nhtml_theme = \"sphinx_rtd_theme\"\nhtml_theme_path = [sphinx_rtd_theme.get_html_theme_path()]\n\n\n# Add any paths that contain custom static files (such as style sheets) here,\n# relative to this directory. They are copied after the builtin static files,\n# so a file named \"default.css\" will overwrite the builtin \"default.css\".\nhtml_static_path = [\"_static\"]\nhtml_context = {\n \"css_files\": [\n \"_static/theme_overrides.css\" # overrides for wide tables in RTD theme\n ]\n}\n\n# -- External links dictionary -----------------------------------------------\nextlinks = {\n \"gazebo-panda-gym\": (\"https://github.com/rickstaa/panda_openai_sim/%s\", None),\n \"panda_openai_sim\": (\n \"https://github.com/rickstaa/panda_openai_sim/tree/melodic-devel/panda_openai_sim/%s\",\n None,\n ),\n \"panda_training\": (\n \"https://github.com/rickstaa/panda_openai_sim/tree/melodic-devel/panda_training/%s\",\n None,\n ),\n \"env_config\": (\n (\n \"https://github.com/rickstaa/panda_openai_sim/blob/melodic-devel/\"\n \"panda_openai_sim/cfg/env_config.yaml/%s\"\n ),\n None,\n ),\n \"stable-baselines\": (\"https://stable-baselines.readthedocs.io/en/master/%s\", None),\n \"sphinx\": (\"http://www.sphinx-doc.org/en/master/%s\", None),\n \"ros\": (\"https://wiki.ros.org/%s\", None),\n \"gym\": (\"https://gym.openai.com/%s\", None),\n \"openai_ros\": (\"https://wiki.ros.org/openai_ros/%s\", None),\n \"franka\": (\"https://www.franka.de/%s\", None),\n \"geometry_msgs\": (\"https://docs.ros.org/api/geometry_msgs/%s\", None),\n \"visualization_msgs\": (\"https://docs.ros.org/api/visualization_msgs/%s\", None),\n \"gazebo_msgs\": (\"https://docs.ros.org/api/gazebo_msgs/%s\", None),\n \"control_msgs\": (\n \"https://docs.ros.org/api/control_msgs/%s\",\n None,\n ),\n \"controller_manager_msgs\": (\n \"https://docs.ros.org/api/controller_manager_msgs/%s\",\n None,\n ),\n}\n","sub_path":"docs/source/conf.py","file_name":"conf.py","file_ext":"py","file_size_in_byte":5268,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"190306765","text":"from talon.voice import Context, Key, press\nimport talon.clip as clip\nfrom ..utils import text, parse_words, parse_words_as_integer, insert, word, join_words\n\ndef verifyExtension(app, win):\n return win.doc.endswith(\".js\") or win.doc.endswith(\".ts\") or win.doc.endswith(\".jsx\") or \"freeCodeCamp\" in win.title\n\ncontext = Context(\"javascript\", func=verifyExtension)\n\ndef remove_spaces_around_dashes(m):\n words = parse_words(m)\n s = ' '.join(words)\n s = s.replace(' – ', '-')\n insert(s)\n\ndef CursorText(s):\n left, right = s.split('{.}', 1)\n return [left + right, Key(' '.join(['left'] * len(right)))]\n\n\ncontext.keymap({\n 'const []': ['const ', text],\n 'let []': ['let ', text],\n 'static': 'static ',\n 'args': ['()', Key('left')],\n 'index': ['[]', Key('left')],\n 'block': [' {}', Key('left enter')],\n 'empty array': '[]',\n 'empty object': '{}',\n 'call': '()',\n\n 'state func': 'function ',\n 'state return': 'return ',\n 'state constructor': 'constructor ',\n 'state if': ['if ()', Key('left')],\n 'state else': ' else',\n 'state else if': [' else if ()', Key('left')],\n 'state while': ['while ()', Key('left')],\n 'state for': ['for ()', Key('left')],\n 'state switch': ['switch ()', Key('left')],\n 'state case': ['case \\nbreak;', Key('up')],\n 'state goto': 'goto ',\n 'state important': 'import ',\n 'state class': 'class ',\n 'state extends': 'extends ',\n 'state super': 'super',\n\n 'comment js': '// ',\n 'word no': 'null',\n 'arrow': ' => ',\n 'assign': ' = ',\n 'asink': 'async ',\n 'oh wait': ' await ',\n\n 'op (minus | subtract)': ' - ',\n 'op (plus | add)': ' + ',\n 'op (times | multiply)': ' * ',\n 'op divide': ' / ',\n 'op mod': ' % ',\n '[op] (minus | subtract) equals': ' -= ',\n '[op] (plus | add) equals': ' += ',\n '[op] (times | multiply) equals': ' *= ',\n '[op] divide equals': ' /= ',\n '[op] mod equals': ' %= ',\n\n '(op | is) greater [than]': ' > ',\n '(op | is) less [than]': ' < ',\n '(op | is) equal': ' === ',\n '(op | is) not equal': ' !== ',\n '(op | is) greater [than] or equal': ' >= ',\n '(op | is) less [than] or equal': ' <= ',\n '(op (power | exponent) | to the power [of])': ' ** ',\n 'op and': ' && ',\n 'op or': ' || ',\n})\n","sub_path":"lang/javascript.py","file_name":"javascript.py","file_ext":"py","file_size_in_byte":2319,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"554935336","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Dec 14 11:14:56 2016\n\nNN Training Script\n\n@author: David Roberts\n\"\"\"\n\n# core libraries\nimport numpy as np\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Dropout, Convolution2D, MaxPooling2D, Flatten\nfrom keras.utils import np_utils\n\n# I/O operations\nimport pickle\nimport os\n\n# image manipulation\nimport cv2\n\n# load data from pickel file\nCWD = os.getcwd()\nORIGINAL_SIZE = (150,95)\n\n\ndef load_data(file_name = CWD + \"/data/NN_training_examples/digit_dictionary.pkl\"):\n data_dictionary = pickle.load(open(file_name, mode = \"rb\"))\n return data_dictionary\n\n\ndef rescale_images(flattened_image_matrix, scaling_factor= .50):\n \"\"\"\n given matrix of flattented pixel vectors, resizes \n \"\"\"\n \n new_shape = (int(ORIGINAL_SIZE[0]*scaling_factor), int(ORIGINAL_SIZE[1]*scaling_factor))\n new_size = new_shape[0]*new_shape[1]\n new_matrix = np.empty((0, new_size), dtype = np.uint8)\n \n for i in range(flattened_image_matrix.shape[0]):\n row = flattened_image_matrix[i].astype(np.uint8)\n image = row.reshape(ORIGINAL_SIZE) # note this should be parameterized by a master variable script\n new_image = cv2.resize(image, new_shape[::-1])\n new_flattened_row = new_image.reshape((1, new_size))\n new_matrix = np.append(new_matrix, new_flattened_row, axis = 0)\n \n return new_matrix\n\n\n# defining a simple CNN with only one hidden layer as baseline\ndef baseline_model(num_pixels, num_classes):\n # Construct 3 layer sequential model\n model = Sequential()\n \n # all layers are \"dense\", that is to say, all input values are connected to all subsequent activations\n model.add(Dense(num_pixels, input_dim = num_pixels, init = 'normal', activation = 'relu'))\n model.add(Dense(num_classes, input_dim = num_pixels, init = 'normal', activation = 'softmax'))\n \n # compile the model - train using Adam gradient descent method\n model.compile(optimizer = 'adam', loss = 'categorical_crossentropy', metrics = ['accuracy'])\n return model\n\n\ndef CNN_model_basic(num_classes, image_shape):\n \"\"\"\n Constructs a 6 layer convolutional neural network with the following layers:\n 1. Convolution layer - 32 filters (feature maps) convolve over pixel map, generating similarity \"scores\" for each pixel.\n - Results in a matrix of scores with the same size as the image\n 2. Pooling layer which essentially scales this similiarty scores matrix down to half the size\n 3. Dropout - regularization layer which randomly drops specified proporiton of neurons\n 4. Flatten - flattens arrays out to be processed by standard layers\n 5. Dense - standard, fully connected hidden layer\n 6. Dense - 10 class output layer\n \"\"\"\n \n # create model\n model = Sequential()\n model.add(Convolution2D(32, 5, 5, border_mode='valid', input_shape=(1, image_shape[0], image_shape[1]), activation='relu'))\n model.add(MaxPooling2D(pool_size=(2, 2)))\n model.add(Dropout(0.1))\n model.add(Flatten())\n model.add(Dense(128, activation='relu'))\n model.add(Dense(num_classes, activation='softmax'))\n\t# Compile model\n model.compile(optimizer = 'adam', loss = 'categorical_crossentropy', metrics = ['accuracy'])\n \n return model\n \n# initializing random seed to ensure reproducability\nnp.random.seed(10)\n\n#%%\n# loading data, transforming to desirable format\ndataset = load_data()\ndataset['image'] = rescale_images(dataset['image'], scaling_factor = .3)\nIMAGE_SHAPE = (45, 28)\n\n#%%\ndataset['image'] = dataset['image'] / 255\ndataset['ocr'] = dataset['ocr'].astype(np.int)\ndataset['ocr'] = np_utils.to_categorical(dataset['ocr'])\n\n#%%\nsep = (dataset['ocr'].shape[0] // 5) * 4\nX_train = dataset['image'][0:sep]\nX_val = dataset['image'][sep:]\ny_train = dataset['ocr'][0:sep]\ny_val = dataset['ocr'][sep:]\nnum_pixels = dataset['image'].shape[1]\n\n#%%\n\"\"\"\nTraining a baseline model\n\"\"\"\n\nmodel = baseline_model(num_pixels, 10)\nmodel.fit(X_train, y_train, validation_data = (X_val, y_val), nb_epoch = 5, batch_size = 200, verbose = 2)\n\n# 8:37 start time, 8:41 finish\\\nscores = model.evaluate(X_val, y_val, verbose=0)\nprint(\"Baseline Error: %.2f%%\" % (100-scores[1]*100))\n\"\"\"\nScaled at 50% \nBaseline Error: 72.14% -- fook lol\n\"\"\"\n\n\"\"\"\nScaled at 20%\nBaseline Error: .19%\n\"\"\"\n\n\"\"\"\n at 30% \nBaseline Error: .12%\n\"\"\"\n\n\"\"\"\nLarger image sizes resulted in worse accuracy, this makes sense to some degree.\nSince we're looking simply at pixel values as opposed to hog features or contours, larger sizes just grant more chance that two pixels would not overlap\nThe shrinking process essentially maps surrounding pixels to one value, boiling more complex patterns down to simpler contours. \n\"\"\"\n\n#%%\n\"\"\"\nTraining a basic convolutional model\n\"\"\"\n\nX_train_CNN = X_train.reshape(X_train.shape[0], 1, IMAGE_SHAPE[0], IMAGE_SHAPE[1]).astype('float32')\nX_val_CNN = X_val.reshape(X_val.shape[0], 1, IMAGE_SHAPE[0], IMAGE_SHAPE[1]).astype('float32')\n\nCNN_basic = CNN_model_basic(10, IMAGE_SHAPE)\nCNN_basic.fit(X_train_CNN, y_train, validation_data = (X_val_CNN, y_val), nb_epoch = 5, batch_size = 200, verbose = 2)\n\n#%%\nscores = CNN_basic.evaluate(X_val_CNN, y_val, verbose=0)\nprint(\"Baseline Error: %.2f%%\" % (100-scores[1]*100))\n\n# Baseline Error: 0.19%\n\n\"\"\"\nSeems to me that the error could likely be chalked up to labeling errors on my part\nThe regularization probably caused a decreases in accuracy over the basic model.\n\"\"\"\n#%% Saving the models\nimport os\nCWD = os.getcwd().replace(\"\\\\\", \"/\")\nmodel.save(CWD + \"/models/basic_NN.h5\")\nCNN_basic.save(CWD + \"/models/CNN.h5\")\n","sub_path":"ocr/train_nn.py","file_name":"train_nn.py","file_ext":"py","file_size_in_byte":5627,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"175297618","text":"from __future__ import print_function\nimport os\nimport sys\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' # Nivel de advertencia\nos.environ[\"CUDA_VISIBLE_DEVICES\"] = \"0\" # usa GPU 0\nimport numpy as np\nimport tensorflow as tf\nfrom tensorflow.contrib import rnn\nfrom utilities import *\nfrom sklearn.metrics import confusion_matrix\n\n\ndef runModel(ID):\n\tglobal sess\n\tglobal predY\n\tglobal testAcc\n\t \n\t# Establecemos las configuraciones\n\tconfig = tf.ConfigProto()\n\tconfig.gpu_options.allow_growth = True\n\n\twith tf.Session(config=config) as sess:\n\t\n\t\t# Restauramos los pesos del modelo del modelo previamente guardado\n\t\tmodel_path_ID = model_path + ID + '/'\n\t\tsaver = tf.train.import_meta_graph(model_path_ID+'model.ckpt.meta')\n\t\tsaver.restore(sess,tf.train.latest_checkpoint(model_path_ID))\n\t\tprint(\"Model of %s is restored\" % str(ID+'B_'+str(run)))\n\n\t\t# Restauramos las variables del modelo del modelo previamente guardado\n\t\tgraph = tf.get_default_graph()\n\t\taccuracy = graph.get_tensor_by_name(\"Accuracy:0\")\n\t\tx = graph.get_tensor_by_name(\"x:0\")\n\t\ty = graph.get_tensor_by_name(\"y:0\")\n\t\tpred = graph.get_tensor_by_name(\"pred:0\")\n\n\t\t# Ejecutamos el modelo con datos de prueba\n\t\ttestAcc, predY = sess.run([accuracy, pred], feed_dict={x: testX, y: testYcat})\n\t\t\n\t\t# Guardamos las predicciones\n\t\tdirectory = os.path.dirname(predsPath)\n\t\ttry:\n\t\t\tos.stat(directory)\n\t\texcept:\n\t\t\tos.mkdir(directory)\n\t\tnp.save( predsPath + ID + '_predY.npy', predY)\n\t\n\treturn\n\n\ndef personalResults(): # Esta función calcula la matriz de confusión para cada ID\n\tpredClass = np.argmax(predY,1)\n\tC = confusion_matrix(testY.ravel(), predClass.ravel(), np.arange(n_classes))\n\tnp.set_printoptions(suppress=True)\n\treturn C\n\n\n\ndef loadTestVars(ID):\n\tglobal testX\n\tglobal testY\n\tglobal testYcat\n\tglobal n_input\n\t\n\t# Cargamos las variables de prueba\n\tvars_path_ID = vars_path + ID + '/'\n\ttestX = np.load(vars_path_ID+'testX.npy')\n\tn_input = (testX.shape[2]//n_steps)\n\ttestX = np.reshape(testX,(-1,n_steps,n_input))\n\ttestY = np.load(vars_path_ID+'testY.npy')\n\ttestYcat = np.load(vars_path_ID+'testYcat.npy')\n\t\n\treturn\n\n\t\n\n# --------******** main *********----------\n\n# Hiperparámetros\nn_classes = 7\nn_hidden = 50\nret = 0\nn_steps = 5\n\n# Rutas de datos\nvars_path = '../Data/BB/'\nmodels_path = '../models/'\nres_path = models_path + 'resB.txt'\nos.system('rm ' + res_path)\nIDs = ['100','101','103','105','106','108','109','111','112','113','114','115','116','117','118','119','121','122','123','124','200', '201', '202', '203', '205', '207', '208', '209', '210', '212', '213', '214', '215', '219', '220', '221', '222', '223', '228', '230', '231', '232', '233', '234'] # all records\n#IDs = ['200', '201', '202', '203', '205', '207', '208', '209', '210', '212', '213', '214', '215', '219', '220', '221', '222', '223', '228', '230', '231', '232', '233', '234']\nruns = np.random.permutation(np.arange(int(sys.argv[1]), int(sys.argv[2])))#ret#['_1', '_2', '_3', ..., '_50']\noutArr = np.zeros((1,8)) # array de 8 elementos para la salida\n\n# ***Cargamos los modelos***\nfor run in runs:\n\n\t# Ruta de almacenamiento de modelos y sus resultados\n\tmodel_path = models_path + 'modelsB_' + str(run) + '_' + str(ret) + '/'\n\tpredsPath = '../preds/testB_outs_' + str(run) + '_' + str(ret) + '/'\n\tallCs = {}\n\t\t\n\t# Bucle para todos los pacientes\n\tfor ID in IDs:\n\t\tloadTestVars(ID) #cargamos las variables\n\t\ttf.reset_default_graph() #reset the graph\n\t\trunModel(ID) #Ejecutamos el modelo completo con nuevos datos de prueba\n\t\tC = personalResults() #Vemos los resultados\n\t\tallCs[ID] = C #Almacenamos las matrices de confusión\n\t\n\toutArr += calc_tables(allCs, n_classes)\n\t\noutArr /= np.size(runs)\n","sub_path":"codes/modelB-pred.py","file_name":"modelB-pred.py","file_ext":"py","file_size_in_byte":3625,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"109324429","text":"import hashlib\nimport json\nimport crypto\nimport datetime\nimport constants\nimport jsonpickle\n\nclass Transaction:\n def __init__(self, id, owner, receiver, coins, signature):\n self.owner = owner\n self.receiver = receiver\n self.coins = coins\n self.id = id\n self.signature = signature\n\n def valid_signature(self):\n if self.owner == \"mined\":\n return True\n return crypto.verify(self.comp(), self.owner, self.signature)\n\n def __str__(self):\n return json.dumps({\n 'owner': self.owner,\n 'receiver': self.receiver,\n 'coins': self.coins,\n 'id': self.id,\n 'signature': self.signature\n })\n\n def comp(self):\n return json.dumps({\n 'owner': self.owner,\n 'receiver': self.receiver,\n 'coins': self.coins,\n 'id': self.id\n })\n\n def __repr__(self):\n return str(self)\n\n @staticmethod\n def from_json(jobj):\n return Transaction(\n id = str(jobj['id']),\n owner = str(jobj['owner']),\n receiver = str(jobj['receiver']),\n coins = int(jobj['coins']),\n signature = str(jobj['signature'])\n )\n\nclass Block:\n def __init__(self, timestamp, transactions, previous_hash, nonce=0, height=-1):\n self.height = height\n self.timestamp = timestamp\n self.transactions = transactions\n self.previous_hash = previous_hash\n self.nonce = nonce\n\n self.parent = None\n\n # Transaction lookup\n self.txn_lookup = {}\n for transaction in self.transactions:\n self.txn_lookup[transaction.comp()] = True\n\n def add_transaction(self, transaction):\n self.transactions.append(transaction)\n self.txn_lookup[transaction.comp()] = True\n\n def set_parent(self, parent):\n self.parent = parent\n self.height = parent.height + 1\n \n def hash_block(self):\n sha = hashlib.sha256()\n\n sha.update(str(self.timestamp) + \n str(self.transactions) + \n str(self.previous_hash) + \n str(self.nonce))\n\n return sha.hexdigest()\n\n def __str__(self):\n return json.dumps({\n 'timestamp': str(self.timestamp),\n 'transactions': str(self.transactions),\n 'previous_hash': str(self.previous_hash),\n 'nonce': self.nonce\n })\n\n def is_valid(self):\n return int(self.hash_block(), 16) < constants.DIFFICULTY\n\n def traverse(self, include_head=True):\n \"\"\"Goes recursively through parents.\n \"\"\"\n if include_head:\n yield self\n current = self.parent\n genisis_hash = get_genisis().hash_block()\n while current != None and current.hash_block() != genisis_hash:\n yield current\n current = current.parent\n\n @staticmethod\n def from_json(jobj):\n return Block(\n timestamp = datetime.datetime.strptime(jobj['timestamp'], \"%Y-%m-%d %H:%M:%S.%f\"),\n transactions = [\n Transaction.from_json(tj)\n for tj in json.loads(jobj['transactions'])\n ],\n previous_hash = str(jobj['previous_hash']),\n nonce = int(jobj['nonce'])\n )\n\ndef get_genisis():\n return Block(\n height = 0,\n timestamp = datetime.datetime.min,\n transactions = [],\n previous_hash = None\n )\n\nclass Blockchain:\n def __init__(self, json_str=None):\n if json_str:\n pass\n else:\n blocks = [get_genisis()]\n\n # Lookup\n self.head = blocks[0]\n self.block_lookup = {}\n for b in blocks:\n self.block_lookup[b.hash_block()] = b\n if b.height > self.head.height:\n self.head = b\n\n # Parents\n for b in blocks:\n if not b.previous_hash == None:\n assert b.previous_hash in self.block_lookup\n b.set_parent(self.block_lookup[b.previous_hash])\n\n def get_wallet_amount(self, address):\n total = 0\n\n # Go back through the current longest chain\n # and tally the total.\n for b in self.head.traverse(include_head=True):\n if not b:\n break\n\n for txn in b.transactions:\n if txn.owner == address and txn.receiver != address:\n total -= txn.coins\n elif txn.owner != address and txn.receiver == address:\n total += txn.coins\n\n return total\n\n def add_block(self, block, cheat=False):\n \"\"\"Checks the entire chain for valid transactions\n and checks proof of work. Then adds block.\"\"\"\n\n block_hash = block.hash_block()\n\n # We already know this block.\n if block_hash in self.block_lookup:\n return False, \"Known block.\"\n \n # Parent doesn't exist :(\n if block.previous_hash not in self.block_lookup:\n return False, \"No valid parent.\"\n parent = self.block_lookup[block.previous_hash]\n \n block.set_parent(parent)\n\n # Check proof of work ;o\n if not cheat and not block.is_valid():\n return False, \"Invalid proof of work.\"\n\n # Verify transaction signatures.\n for transaction in block.transactions:\n if transaction.owner != \"mined\" and not transaction.valid_signature():\n return False, \"Transaction has invalid signature.\"\n\n # Have any of these transactions been replays?\n for b in block.traverse(include_head=True):\n for c_txn in block.transactions:\n if c_txn in b.txn_lookup:\n # We found the same transaction in a previous block.\n return False, \"Transaction replay detected.\"\n \n # For every transaction, does the owner own this money?\n reward_counted = False\n for txn in block.transactions:\n if txn.coins < 0:\n return False, \"Amount can't be negative.\"\n \n if txn.owner == \"mined\":\n # This is the miner reward, let's make sure\n # it's correct. Technically, the miner can make\n # this payment to anyone she likes.\n if txn.coins > constants.REWARD:\n return False, \"Incorrect miner reward.\"\n \n # Let's also make sure the reward is only given\n # once and once only.\n if reward_counted:\n return False, \"Miner reward found twice in block.\"\n\n reward_counted = True\n else:\n owner_coins = self.get_wallet_amount(txn.owner)\n if owner_coins < txn.coins:\n # Owner doesn't have enough coins,\n # block is invalid.\n return False, \"Owner doesn't have enough coins.\"\n \n # Looks like everything is set with this block.\n # Let's add this block and compute the longest\n # chain.\n\n self.block_lookup[block_hash] = block\n if block.height > self.head.height:\n self.head = block\n \n return True, \"Block added.\"\n\n def to_json(self):\n return jsonpickle.encode(self)\n\nif __name__ == '__main__':\n # Just a sanity test.\n bc = Blockchain()\n bc.add_block(\n Block(\n timestamp=datetime.datetime.now(),\n transactions=[],\n previous_hash=get_genisis().hash_block(),\n nonce=12834\n ),\n cheat=True\n )\n print(bc.to_json())\n","sub_path":"hackcoin/hackcoin/core/blockchain.py","file_name":"blockchain.py","file_ext":"py","file_size_in_byte":7685,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"419531776","text":"\nimport math\nsuma = 0\ncantidad = 0\nL = []\nM = []\nfor i in range(844,1845):\n if i % 5 == 0:\n ln = math.log(i)\n L.append(ln)\nfor i in range(2450,2844):\n if i % 3 == 2:\n t = i\n M.append(t)\nfor i in range(0,90):\n l = L[i]\n m = M[i]\n suma += (2*l) + m\n cantidad += 1\npromedio = suma / cantidad\ncoseno = math.cos(promedio)\nprint (round(coseno,6))\nprint(cantidad)\nprint(suma)","sub_path":"base_2.py","file_name":"base_2.py","file_ext":"py","file_size_in_byte":386,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"463408956","text":"#!/usr/bin/env python3\n\nimport json\nimport os\nimport glob\nimport time\nimport re\nfrom terminaltables import AsciiTable\nfrom colorclass import Color\n\nfrom tasks import Tasks\nfrom runner import Runner\nfrom tool_parameters import ToolParametersHelper\n\nroot_dir = os.path.dirname(os.path.abspath(__file__))\nsrc_dir = root_dir + '/src'\n\n\ndef get_builds(out_prefix):\n \"\"\"Returns all the paths of all the builds in the build directory.\"\"\"\n build_dir = os.path.join(root_dir, out_prefix)\n builds = []\n for content in os.listdir(build_dir):\n if os.path.isdir(os.path.join(build_dir, content)):\n builds.append(content)\n\n return builds\n\n\ndef print_summary_table(out_prefix, build_type, build_nr=None):\n \"\"\"Prints a summary table of the outcome of each test.\"\"\"\n builds = get_builds(out_prefix)\n table_data = [\n [\n 'Project', 'Toolchain', 'Family', 'Part', 'Board', 'Build Type',\n 'Build N.', 'Options'\n ]\n ]\n passed = failed = 0\n build_count = 0\n for build in sorted(builds):\n # Split directory name into columns\n # Example: oneblink_vpr_xc7_a35tcsg326-1_arty_generic-build_0_options\n pattern = ''\n for i in range(0, len(table_data[0]) - 1):\n pattern += '([^_]*)_'\n pattern += '(.*)'\n\n row = list(re.match(pattern, build).groups())\n\n if build_type != row[5] or (build_nr and int(build_nr) != int(row[6])):\n continue\n\n # Check if metadata was generated\n # It is created for successful builds only\n if os.path.exists(os.path.join(root_dir, out_prefix, build,\n 'meta.json')):\n row.append(Color('{autogreen}passed{/autogreen}'))\n passed += 1\n else:\n row.append(Color('{autored}failed{/autored}'))\n failed += 1\n table_data.append(row)\n build_count += 1\n\n table_data.append(\n [\n Color('{autogreen}Passed:{/autogreen}'), passed,\n Color('{autored}Failed:{/autored}'), failed, '', '', '', '',\n '{}%'.format(int(passed / build_count * 100))\n ]\n )\n table = AsciiTable(table_data)\n table.inner_footing_row_border = True\n print(table.table)\n\n return failed == 0\n\n\ndef main():\n import argparse\n parser = argparse.ArgumentParser(\n description='Exhaustively try project-toolchain combinations'\n )\n parser.add_argument(\n '--project',\n default=None,\n nargs=\"+\",\n help='run given project only (default: all)'\n )\n parser.add_argument(\n '--toolchain',\n default=None,\n nargs=\"+\",\n help='run given toolchain only (default: all)'\n )\n parser.add_argument(\n '--out-prefix',\n default='build',\n help='output directory prefix (default: build)'\n )\n parser.add_argument(\n '--build_type',\n default='generic',\n help=\n 'Type of build that is performed (e.g. regression test, multiple options, etc.)'\n )\n parser.add_argument('--build', default=None, help='Build number')\n parser.add_argument(\n '--parameters', default=None, help='Tool parameters json file'\n )\n parser.add_argument('--fail', action='store_true', help='fail on error')\n parser.add_argument(\n '--verbose', action='store_true', help='verbose output'\n )\n\n args = parser.parse_args()\n\n tasks = Tasks(src_dir)\n\n args_dict = {\"project\": args.project, \"toolchain\": args.toolchain}\n\n task_list = tasks.get_tasks(args_dict)\n\n params_file = args.parameters\n params_strings = [None]\n if params_file:\n params_strings = []\n assert len(\n args.toolchain\n ) == 1, \"A single toolchain can be selected when running multiple params.\"\n\n params_helper = ToolParametersHelper(args.toolchain[0], params_file)\n for params in params_helper.get_all_params_combinations():\n params_strings.append(\" \".join(params))\n\n runner = Runner(\n task_list, args.verbose, args.out_prefix, root_dir, args.build_type,\n args.build, params_strings\n )\n runner.run()\n runner.collect_results()\n\n result = print_summary_table(args.out_prefix, args.build_type, args.build)\n\n if not result and args.fail:\n print(\"ERROR: some tests have failed.\")\n exit(1)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"exhaust.py","file_name":"exhaust.py","file_ext":"py","file_size_in_byte":4414,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"600956044","text":"from numpy import log\nimport numpy as np\n\ndef CrossEntropy(yHat, y):\n if y == 1:\n return -log(yHat)\n else:\n return -log(1 - yHat)\n\ndef bb_intersection_over_union(boxA, boxB):\n # determine the (x, y)-coordinates of the intersection rectangle\n xA = max(boxA[0], boxB[0])\n yA = max(boxA[1], boxB[1])\n xB = min(boxA[2], boxB[2])\n yB = min(boxA[3], boxB[3])\n\n # compute the area of intersection rectangle\n interArea = max(0, xB - xA + 1) * max(0, yB - yA + 1)\n\n # compute the area of both the prediction and ground-truth\n # rectangles\n boxAArea = (boxA[2] - boxA[0] + 1) * (boxA[3] - boxA[1] + 1)\n #print(boxAArea)\n boxBArea = (boxB[2] - boxB[0] + 1) * (boxB[3] - boxB[1] + 1)\n #print(boxBArea)\n\n # compute the intersection over union by taking the intersection\n # area and dividing it by the sum of prediction + ground-truth\n # areas - the interesection area\n iou = interArea / float(boxAArea + boxBArea - interArea)\n\n # return the intersection over union value\n return iou\n\ndef softmax(x):\n return np.exp(x[0]) / np.sum(np.exp(x), axis=0)\n\ndef mean_squared_diff(yHat, y):\n yHat = np.array(yHat)\n y = np.array(y)\n return np.sum(np.square(yHat-y))\n\ndef calc_reggression(bbox, anchor):\n x, y, h, w = (bbox[0] - bbox[2])/2, (bbox[1] - bbox[3])/2, np.abs(bbox[1] - (bbox[1] - bbox[3])/2), np.abs(bbox[0] - (bbox[0] - bbox[2])/2)\n xA, yA, hA, wA = (anchor[0] - anchor[2]) / 2, (anchor[1] - anchor[3]) / 2, np.abs(anchor[1] - (anchor[1] - anchor[3]) / 2), np.abs(anchor[0] - (anchor[0] - anchor[2]) / 2)\n\n tx = (x-xA)/wA\n ty = (y-yA)/hA\n th = np.log(h/hA)\n tw = np.log(w/wA)\n\n return [tx, ty, th, tw]\n","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1697,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"7990424","text":"from common import *\nfrom joblib import Parallel, delayed\nimport yaml, os\n\ndef success(path, out):\n out = [filter_output(l) for l in out]\n out.append(\"Done fetching {}\".format(path))\n return '\\n'.join(out)\n\ndef failure(path):\n print(colored(\"Failed to pull {}\".format(path), 'red'))\n\ndef git_pull(path, index):\n remote = git_remotes(path)\n\n if remote is None:\n pprint((\"Skipping {} for it has no remotes\".format(path)), index)\n return\n\n pprint((\"Pulling {} from {}\".format(path, remote)), index)\n out, err, ret = git('pull', path)\n\n if ret == 0:\n pprint(success(path, out), index)\n else:\n failure(path)\n\ndef recursive_walk(d, depth=0, parent=[]):\n for k, v in sorted(d.items(), key=lambda x: x[0]):\n if isinstance(v, dict):\n recursive_walk(v, depth+1, parent + [k])\n else:\n path = \"/\".join(parent + [k])\n if os.path.exists(path):\n paths.append(path)\n\ndef main():\n with open('_repos.yml', 'r') as f:\n repos = yaml.load(f)\n\n recursive_walk(repos)\n Parallel(n_jobs=get_cpu_count())(delayed(git_pull)(p,i) for i, p in enumerate(paths))\n\npaths = []\nmain()\n","sub_path":"pull.py","file_name":"pull.py","file_ext":"py","file_size_in_byte":1108,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"641592421","text":"import fresh_tomatoes\nimport movie_api\n\n\nclass Movie():\n \"\"\"\n Movie Class gets the movie name, pass the details to OMDB API and\n fetch all the details related to that movie (if available)\n\n Attributes:\n name (str): name of the movie\n trailer (str): youtube link for the movie trailer\n \"\"\"\n def __init__(self, name, trailer):\n \"\"\"Constructor method\"\"\"\n\n # Pass the movie name to OMDB API\n movie = movie_api.MovieApi(name)\n\n # Fetch the details related to the movie\n self.title = movie.get_title()\n self.director = movie.get_director()\n self.production = movie.get_production()\n self.poster_image_url = movie.get_poster_url()\n self.genre = movie.get_genre()\n self.released = movie.get_release_date()\n self.imdb_rating = movie.get_rating()\n self.trailer_youtube_url = trailer\n","sub_path":"media.py","file_name":"media.py","file_ext":"py","file_size_in_byte":889,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"507369062","text":"import run\nimport json\nfrom pts import ranks, points\nimport discord\nimport asyncio\nimport requests\nfrom discord.ext import commands\nimport requests as rq\nimport datetime\nimport os\n\n\ndef get_prefix(bot, msg):\n \"\"\"[This funciton allows you to change the command prefixes or add more prefixes that can be used to tirgger the bot commands\n This can be used to make per server prefixes and or per user prefixes]\n \n Arguments:\n bot {[Class]} -- [The bot]\n msg {[Class]} -- [The messages being sent]\n \n Returns:\n [type] -- [This will return the command prefixes that can be used]\n \"\"\"\n\n user_cm = ['!@', '$', '%', '^'] # another command prefix list\n if msg.author.id == '1934123473892': # this makes is so that this user will have a different prefix from others and can't use the prefixes that it does't have access to\n # this user will onlyb e able to use the command prefies inside the list user_cm\n return commands.when_mentioned_or(*user_cm)(bot, msg)\n\n # the normal prefixes that users can use if they are not in the igs list\n prefixes = ['a.', 's.', '!', '?']\n\n # now any of the command prefixes a. s. ! ? can be used to run bot commands\n return commands.when_mentioned_or(*prefixes)(bot, msg)\n\n\nbot = commands.Bot(command_prefix=get_prefix,\n description='A bot with multiple command prefixes')\nevn = bot.event # a short cut for @bot.event, but now @evn instead\n# now you can just do @cms instead of doing @bot.command(pass_context=True) everytime\ncms = bot.command(pass_context=True)\nups = {'cp': 0}\n\n\"\"\"\nGo to jsonblob.com and create a JSON in this format\n\n{\n \"servers\": {},\n \"users\": {},\n \"daily\": {}\n}\n\nthen click save and put api in the position after .com/ https://jsonblob.com/Put the word api here/55eae264-1470-11e9-8960-672add231a5a\nexample: \nBefore: \"https://jsonblob.com/55eae264-1470-11e9-8960-672add231a5a\"\nAfter: \"https://jsonblob.com/api/55eae264-1470-11e9-8960-672add231a5a\"\n\n\n\nOnce you've done all that replace the urls I that I have in the code with your own url that you made from jsonblob\n\"\"\"\n\n\n# this is your database url\ndb = 'https://jsonblob.com/api/55eae264-1470-11e9-8960-672add231a5a'\nrewards_db = 'https://jsonblob.com/api/76262d92-1f7c-11e9-94d1-a979d19deaff'\n\ndef get_db():\n \"\"\"\n [This function requests the data from the web server(database) jsonblob.com]\n \"\"\"\n while True:\n r = rq.Session().get(db)\n if r.status_code == 200: # if request is successful\n global data # create global variable\n data = r.json() # set the global variale to the json result\n \n re_db=rq.get(rewards_db) #request the rewards database\n if re_db.status_code == 200: #request was successful\n global r_db #define a global variable for it\n r_db = re_db.json() #store it into global variable\n break # break the loop\n\n\nget_db() # run the function called get_db\n\n\nasync def auto_update(user, ual=False):\n \"\"\"\n This function is used to update the database manually or automatically\n The second parameter is used to determine if the command was triggered manualy or automatically\n \"\"\"\n if user.author.id != 'author id':\n while True:\n r = rq.get(db, data=data)\n if r.status_code == 200:\n print(\"Data updated\")\n if ual == True:\n await bot.send_message(user.channel, \"**Data updated**\")\n break\n else:\n await asyncio.sleep(1)\n if user.author.id != 'author id':\n await bot.send_message(user.channel, \"Only bot owner can use this command\")\n\n\n@bot.event\nasync def on_ready():\n \"\"\"[Determine the task to do when the bot is ready\n Task 1: Print bot's name when ready]\"\"\"\n print(bot.user.name)\n\n\n@evn\nasync def on_message(msg):\n \"\"\"\n You will need the file named pts.py and it's values\n \n The on message function is used for the following:\n Add non-existing users: Add users that are not in database yet\n Update existing user's info:Update info such as coins or exp\n Detect changes: Add the ups['cp] value by 1 everytime a chagne is made and if it exceeds a certain limit(250) update the data to the database ]\n \n The current values of coin and exp users get from send messages are all set to default to 1 for now, you can customize the values if you desire.\n The code is not complete yet so once it's complete, the coins and exp values will be determined by the length of the message.\n\n\n\n Arguments:\n msg {[obj]} -- [The context of the user that sent the message]\n \"\"\"\n\n msg_pts = len(msg.content.split())\n\n Exp = points['points']['exp'][str(msg_pts)]\n Coin = points['points']['coin'][str(msg_pts)]\n\n if msg.channel.is_private == False: # check if the message is from DM or server\n if msg.server.id not in data['servers']: # server id not in database\n data['servers'][msg.server.id] = {\n 'coins': 0, 'exp': 0} # add it to database\n ups['cp'] += 1\n\n if msg.server.id in data['servers']: # server in database\n data['servers'][msg.server.id]['coins'] += Coin\n data['servers'][msg.server.id]['exp'] += Exp\n ups['cp'] += 1\n\n if msg.author.id not in data['users']: # user not in database\n data['users'][msg.author.id] = {\n 'coins': 0, 'exp': 0} # Add user to database\n ups['cp'] += 1\n\n if msg.author.id in data['users']: # user in database\n data['users'][msg.author.id]['coins'] += Coin\n data['users'][msg.author.id]['exp'] += Exp\n ups['cp'] += 1\n\n if ups['cp'] > 250:\n bot.loop.create_task(auto_update(msg, False))\n\n # makes it so that commands are not blocked\n await bot.process_commands(msg)\n\n\n@cms\nasync def check(con, user: discord.Member = None):\n \"\"\"[This function checks for the author's points or the tagged person's]\n \n Arguments:\n con {[ojb]} -- [The context from the author(command user)]\n \n Keyword Arguments:\n user {discord.Member} -- [The person that's being tagged] (default: {None})\n \"\"\"\n\n if user == None or user.id == con.message.author.id: # user not tagged or == to author\n if con.message.author.id in data['users']: # use in database\n # sent back the points\n await bot.say(\"{}\\nCoins:{}\\nExp:{}\\nRank:{}\".format(con.message.author.name,round(data['users'][con.message.author.id]['coins'],2), round(data['users'][con.message.author.id]['exp'],1),data['users'][con.message.author.id]['level']))\n else: # no need for if user not in database since the on_message function will do the job\n await bot.say(\"{}\\nCoins:1\\nExp:1\\nRank:slave\".format(con.message.author.name))\n\n if user != None and user.id != con.message.author.id: # user other than the author is tagged\n if user.id in data['users']: # tagged user in database\n # send back results for the request\n await bot.say(\"{}\\nCoins:{}\\nExp:{}\\nRank: {}\".format(user.name, round(data['users'][user.id]['coins'], 2), round(data['users'][user.id]['exp'], 1), data['users'][user.id]['level']))\n else: # user will be added from the on_mesage function\n await bot.say(\"{}\\nCoins:1\\nExp:1\\nRank:slave\".format(user.name))\n\n\n@cms\nasync def gift(con, user: discord.Member, amt: int): \n\n\n\n \"\"\"[This function gifts the person tagged even if user is not in database\n The gift value must not exceed the person gifting's balance else it won't work]\n \n Arguments:\n con {[ojb]} -- [The context of from the author]\n user {discord.Member} -- [The user that is being tagged]\n amt {int} -- [The gift value]\n \"\"\"\n\n if user.id != con.message.author.id:\n if con.message.author.id in data['users']: # author in database\n # gift amount exceeds gifter's value\n if data['users'][con.message.author.id]['coins'] < amt:\n # reply back saying gift value exceeds balance\n await bot.say(\"Your balance exceeds your gift amount by {}\".format(round(amt-data['users'][con.message.author.id]['coins'],2)))\n\n if data['users'][con.message.author.id]['coins'] >= amt: # balance >= gift value\n if user.id in data['users']: # Tagged user in database\n # subtract and from gifter\n data['users'][con.message.author.id]['coins'] -= amt\n data['users'][user.id]['coins'] += amt # add to tagged user\n await bot.say(\"{} gifted to {}\".format(amt,user.name))\n\n\n if user.id not in data['users']: # tagged user not in database\n\n if data['users'][con.message.author.id]['coins'] < amt: # balance >= gift value\n await bot.say(\"Your balance exceeds your gift amount by {}\".format(round(amt-data['users'][con.message.author.id]['coins'],2)))\n\n\n if data['users'][con.message.author.id]['coins'] >= amt: # balance >= gift value\n\n data['users'][user.id]={'coins': amt, 'exp': 0} # add to database\n data['users'][con.message.author.id]['coins'] -= amt\n await bot.say(\"{} gifted to {}\".format(amt,user.name))\n\n\n\n\n if user.id == con.message.author.id:\n await bot.say(\"**You can't gift yourself**\")\n\n@cms\nasync def daily(con):\n \"\"\"\n [The daily command gives users that use it 30 exp and 10 coin. \n This command uses the datetime library and the day value to determine if use has already checked in or not\n\n `datetime.datetime.now().day \n\n To customize the values of the amounts given change the following variables\n \n Exp: The amount of exp to give by default when using the daily command\n Coin: The amount of coin to give by default when this command is used\n \n Exp = 30 Default Value\n Coin = 10 Default Value\n ]\n \"\"\"\n Exp = 30\n Coin = 10\n user = con.message.author\n if user.id in data['users']:\n if user.id in data['daily']:\n \n if data['daily'][user.id]['current'] - data['daily'][user.id]['before'] !=1:\n if data['daily'][user.id]['current'] - data['daily'][user.id]['before'] not in data['daily'][user.id]['monthos']:\n data['daily'][user.id]['streak']=1\n\n\n if datetime.datetime.now().day == data['daily'][user.id]['check']:\n await bot.say(\"You've already checked in for today, please check in for daily rewards tomorrow \")\n \n if datetime.datetime.now().day != data['daily'][user.id]['check']:\n data['users'][user.id]['coins'] += Coin *data['daily'][user.id]['streak'] #multiple the default coin value by the streak, limit is 6\n data['users'][user.id]['exp'] += Exp *data['daily'][user.id]['streak'] #multiple the default coin value by the streak, limit is 6\n await bot.say(\"You've been give {} exp and {} coins\".format(Exp*data['daily'][user.id]['streak'], Coin*data['daily'][user.id]['streak']))\n data['daily'][user.id]['check']=datetime.datetime.now().day\n\n\n if data['daily'][user.id]['streak'] <=6:\n data['daily'][user.id]['streak'] +=1 #add the streak if it's lower than limit\n\n if user.id not in data['daily']:\n data['users'][user.id]['coins'] += Coin *data['daily'][user.id]['streak'] #multiple the default coin value by the streak, limit is 6\n data['users'][user.id]['exp'] += Exp * data['daily'][user.id]['streak'] #multiple the default coin value by the streak, limit is 6\n data['daily'][user.id] = {\"check\": datetime.datetime.now().day,'streak':1,\"before\":22,\"current\":23,\"diff\":1}\n await bot.say(\"You've been give {} exp and {} coins\".format(Exp*data['daily'][user.id]['streak'], Coin*data['daily'][user.id]['streak']))\n\n if user.id not in data['users']:\n if user.id not in data['daily']:\n data['users'][user.id]['coins'] += Coin *data['daily'][user.id]['streak'] #multiple the default coin value by the streak, limit is 6\n data['users'][user.id]['exp'] += Exp *data['daily'][user.id]['streak'] #multiple the default coin value by the streak, limit is 6\n data['daily'][user.id] = {\"check\": datetime.datetime.now().day,'streak':1,\"before\":22,\"current\":23,\"diff\":1}\n await bot.say(\"You've been give {} exp and {} coins\".format(Exp*data['daily'][user.id]['streak'], Coin*data['daily'][user.id]['streak']))\n\n\n@cms\nasync def db_update(con):\n \"\"\"[This function updates the database manually]\n\n Make this command only avaliable to specific users or people since allowing it publically will be a spam to the database.\n \n Arguments:\n con {[obj]} -- [The context from the command user]\"\"\"\n bot.loop.create_task(auto_update(con.message, True))\n\n\n\n@cms\nasync def get(con):\n if con.message.author.id == '188415708902850562':\n data['users'][con.message.author.id]['coins']+=1000\n else:\n pass\n\n\n@cms\nasync def rewards(con):\n \"\"\"\n [\n Users will be given a list of options for the rewards.\n Users can get the rewards by adding a reaction to the option.\n Ex:\n 🇦: Get a role color (1,000 coins) (15 Days)\n 🇧: Get custom prefix (5,000 coins) (31 Days)\n 🇨: Change bot's playing status (1,000) (5 hours) (`status must be appropriate`) (if request already active, it will be queued)\n 🇩: Change bot's listening status (1,000) (5 hours) (`status must be appropriate`) (if request already active, it will be queued)\n 🇪: Change bot's watching status (1,000) (5 hours) (`status must be appropriate`) (if request already active, it will be queued)\n ]\n \n\n\n\n Arguments:\n con {[class]} -- [The attrs from the command user]\n\n \"\"\"\n\n msg=await bot.say(r_db)\n\n\n\n#you can do\n#bot.run(os.environ['bot token']) to run it on heroku or\n#bot.run(os.get.environ['bot token'])\n\nbot.run(run.yakumo)\n","sub_path":"econ.py","file_name":"econ.py","file_ext":"py","file_size_in_byte":14115,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"109285044","text":"from app import GetPinterest, CreatePinterest\n\ntoken = 'YOUR-TOKEN-HERE'\n\ng = GetPinterest(token)\nc = CreatePinterest(token)\n\n# username/boardName\nboardName = 'put in board name'\ng.getPinFromBoard(boardName)\ng.getBoardInfo(boardName)\n\n# pin id is tail of URL\npinId = 'put in pin id'\ng.getPinData(pinId)\n\n# account name\nusername = 'put in username'\ng.getUserData(username)\n\n# only token\ng.getMyAccount()\n\n# with description\nboardName = 'put in board name'\ndescription = 'こんな所に行ってみたい!'\nc.createBoard(boardName, description)","sub_path":"run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":545,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"491746061","text":"''' Ch2, Ch3 Homework\nHelen Sun 1/4/2016\nGiahuy Dang\n'''\n# Exercise 2.5\nsubtotal, gratuity = eval(input(\"Enter the subtotal and a grauity rate: \"))\ngratuity_calc = subtotal * (gratuity / 100)\nsubtotal_calc = subtotal + gratuity_calc\nprint(\"The gratuity is \",gratuity_calc,\"and the total is\",subtotal_calc)\n'''\nResults:\nEnter the subtotal and a grauity rate: 15.69, 15\nThe gratuity is 2.3535 and the total is 18.043499999999998\n'''\n# Exercise 2.13\ninteger = eval(input(\"Enter an integer: \"))\nd1 = integer // 1000\nn2 = integer % 1000\nd2 = n2 // 100\nn3 = integer % 100\nd3 = n3 // 10\nn4 = integer % 10\nd4 = n4\nprint(d1)\nprint(d2)\nprint(d3)\nprint(d4)\n\n'''\nResults:\nEnter an integer: 6542\n6\n5\n4\n2\n'''\n\n# Exercise 2.15\nsides = eval(input(\"Enter the side:\"))\narea = ((3 * 1.732050807568877)/(2)) * sides**2\nprint(\"The area of the hexagon is \", area)\n\n''' Results:\nEnter the side:79\nThe area of the hexagon is 16214.593635056042\n'''\n\n# Exercise 3.9\nname = input(\"Enter employee's name: \")\nhours_worked = eval(input(\"Enter number of hours worked in a week: \"))\nhourly_pay = eval(input(\"Enter hourly pay rate: \"))\ninput_federal_tax_withholding = eval(input(\"Enter federal tax withhoulding rate: \"))\ninput_state_tax_withholding = eval(input(\"Enter state tax withholding rate: \"))\nfederal_tax_withholding = input_federal_tax_withholding * 100\nstate_tax_withholding = input_state_tax_withholding * 100\n\nprint(\"Employee Name: Smith \\nHours worked:\", format(hours_worked, \".1f\"), \"\\nPay Rate: $\",hourly_pay, \"\\nGross Pay: $\",hourly_pay * 10, \\\n \"\\nDeductions: \\n Federal Withholding (\",federal_tax_withholding,\"%): $\",(hourly_pay / 10) * federal_tax_withholding, \\\n \"\\n State Withholding (\",state_tax_withholding,\"%): $\",format((hourly_pay / 10) * state_tax_withholding,\"<.2f\"), \\\n \"\\n Total Deduction: $\",format((hourly_pay / 10) * federal_tax_withholding + (hourly_pay / 10) *state_tax_withholding,\"<.2f\"), \\\n \"\\nNet Pay: $\",format((hourly_pay* 10) - ((hourly_pay / 10) * federal_tax_withholding + (hourly_pay / 10) *state_tax_withholding),\".2f\"))\n\n''' Results:\nEnter employee's name: Smith\nEnter number of hours worked in a week: 10\nEnter hourly pay rate: 9.75\nEnter federal tax withhoulding rate: 0.20\nEnter state tax withholding rate: 0.09\nEmployee Name: Smith \nHours worked: 10.0 \nPay Rate: $ 9.75 \nGross Pay: $ 97.5 \nDeductions: \n Federal Withholding ( 20.0 %): $ 19.5 \n State Withholding ( 9.0 %): $ 8.78 \n Total Deduction: $ 28.27 \nNet Pay: $ 69.22\n'''\n\n# Exercise 3.11\ninteger = eval(input(\"Enter an integer: \"))\nd1 = integer // 1000\nn2 = integer % 1000\nd2 = n2 // 100\nn3 = integer % 100\nd3 = n3 // 10\nn4 = integer % 10\nd4 = n4\nprint(d4, end = '')\nprint(d3, end = '')\nprint(d2, end = '')\nprint(d1, end = '')\n\n''' Results:\nEnter an integer: 6542\n2456\n'''\n","sub_path":"Homework/Ch 2-3 Homework.py","file_name":"Ch 2-3 Homework.py","file_ext":"py","file_size_in_byte":2776,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"346423919","text":"import random\n\n\ndef get_random_word():\n words = [\"pizza\", \"cheese\", \"apple\"]\n word = words[random.randint(0, len(words)-1)]\n return word\n\n\ndef show_word(word):\n for character in word:\n print(character, \" \", end=\"\")\n print(\"\")\n\n\ndef get_guess():\n print(\"enter the letter\")\n return input()\n\n\ndef process_letter(letter, secret_word, blank_word):\n result = False\n for i in range(0, len(secret_word)):\n if secret_word[i] == letter:\n result = True\n blank_word[i] = letter\n return result\n\n\ndef print_strike(no_of_strikes):\n for i in range(0, no_of_strikes):\n print(\"X \", end=\"\")\n print(\"\")\n\n\ndef play_word_game():\n word = get_random_word()\n blank_word = list(\"_\" * len(word))\n strike = 0\n max_strikes = 3\n playing = True\n\n while playing:\n show_word(blank_word)\n\n letter = get_guess()\n found = process_letter(letter, word, blank_word)\n\n if not found:\n strike += 1\n print_strike(strike)\n if strike >= max_strikes:\n playing = False\n if not \"_\" in blank_word:\n playing = False\n\n if strike >= max_strikes:\n print(\"loser\")\n else:\n print(\"winner\")\n\n\nprint(\"get started\")\nplay_word_game()\nprint(\"game over\")\n","sub_path":"PYTHON/programs/Words.py","file_name":"Words.py","file_ext":"py","file_size_in_byte":1300,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"477268229","text":"\nfrom django.urls import include, path\nfrom . import views_ent\n# ../apis/ent+ 接口\nurlpatterns = [\n path('entSubmitUser', views_ent.entSubmitUser),\n path('entLogin', views_ent.entLogin),\n path('getEntBaseInfo', views_ent.getEntBaseInfo),\n path('subEntBaseInfo', views_ent.subEntBaseInfo),\n path('subEntJobInfo', views_ent.subEntJobInfo),\n path('updateEntBaseInfo', views_ent.updateEntBaseInfo),\n path('delEntJobInfo', views_ent.delEntJobInfo),\n]\n","sub_path":"polls/urls_ent.py","file_name":"urls_ent.py","file_ext":"py","file_size_in_byte":470,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"207348317","text":"from crazyradio import Crazyradio\n\n\nif __name__ == \"__main__\":\n radio = Crazyradio()\n radio.set_channel(90)\n radio.set_data_rate(radio.DR_2MPS)\n radio.set_address(b'\\xe7\\xe7\\xe7\\xe7\\xe7')\n radio.set_ack_enable(True)\n\n import time\n while True:\n# resp = radio.send_packet(bytes([0x01, 0x02]))\n res = radio.scan_channels(0, 125, bytes([0x01, ]))\n if res:\n print(res)\n\n\n\n\n\n\"\"\" from machine import SoftSPI, Pin\nfrom known import NRF24L01\nspi = SoftSPI(baudrate=100000, polarity=0, phase=0, sck=Pin(5), mosi=Pin(4), miso=Pin(0))\nNRF24L01(spi, Pin(2), Pin(14))\nce = 2\ncsn = 14\n \"\"\"\n","sub_path":"src/pc-client/tester.py","file_name":"tester.py","file_ext":"py","file_size_in_byte":628,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"169828534","text":"import pygame as pg\nimport socket\nimport pickle\nfrom math import sqrt, atan2\nfrom os import walk\nfrom random import choice, randint\n\nfrom ships import Player, Enemy, Ship, Ghost\nfrom settings import windowHeight, windowWidth, mapSize, fps\nfrom background import Layer, decode_layer\nfrom bullet import Bullet\nfrom quadtree import Quadtree\n\npg.init()\npg.joystick.init()\n\npg.display.set_caption('Space Fighters')\nrunning = True\nclock = pg.time.Clock()\nfont = pg.font.Font('png/kenvector_future.ttf', 50)\nrect_space = pg.Rect(0, 0, mapSize, mapSize)\nkeys_dict = {}\nused_keys = []\ncollision_tree = Quadtree(0, 0, mapSize, mapSize)\n\nmeteor_pngs = []\nfor (dirpath, dirnames, files) in walk('png/Meteors'):\n for file in files:\n meteor_pngs.append(dirpath + '/' + file)\n\n\nclass Camera:\n def __init__(self, f):\n self.rect = pg.Rect(0, 0, windowWidth, windowHeight)\n self.r = 100\n self.follower = f\n\n def move(self):\n dx = self.rect.centerx - self.follower.pos.x\n dy = self.rect.centery - self.follower.pos.y\n d = sqrt(dx * dx + dy * dy)\n if d > self.r:\n dx /= d\n dy /= d\n self.rect.centerx -= dx * (d - self.r)\n self.rect.centery -= dy * (d - self.r)\n\n self.rect = self.rect.clamp(rect_space)\n\n def offset(self, grp):\n for sprt in grp:\n sprt.rect.centerx = sprt.pos.x - self.rect.x\n sprt.rect.centery = sprt.pos.y - self.rect.y\n\n def draw_layers(self, layers, w):\n for l in layers:\n rect = pg.Rect(0, 0, self.rect.w / l.speed, self.rect.h / l.speed)\n rect.center = self.rect.center\n\n for s in l.query(rect):\n if s.rect.colliderect(rect):\n r = s.rect.copy()\n r.centerx = mapping(s.rect.centerx, rect.left, rect.right, 0, self.rect.w)\n r.centery = mapping(s.rect.centery, rect.top, rect.bottom, 0, self.rect.h)\n w.blit(s.image, (r.x, r.y))\n\n def draw(self, obj, w):\n if isinstance(obj, list) or isinstance(obj, pg.sprite.Group):\n for sprite in obj:\n w.blit(sprite.image, (sprite.rect.x - self.rect.x, sprite.rect.y - self.rect.y))\n else:\n w.blit(obj.image, (obj.rect.x - self.rect.x, obj.rect.y - self.rect.y))\n\n\nclass Radar:\n def __init__(self, ship, target_groups):\n self.owner = ship\n self.groups = target_groups\n self.rect = pg.Rect(0, 0, 4000, 4000)\n self.image_size = 200\n self.image = pg.Surface((self.image_size, self.image_size), pg.SRCALPHA)\n\n def update(self):\n self.image.fill(0)\n pg.draw.rect(self.image, (255, 255, 255), (1, 1, self.image_size - 2, self.image_size - 2), 1)\n self.rect.center = self.owner.pos.x, self.owner.pos.y\n\n for targets in self.groups:\n for target in targets:\n x = mapping(target.rect.centerx, self.rect.left, self.rect.right, 0, self.image_size)\n y = mapping(target.rect.centery, self.rect.top, self.rect.bottom, 0, self.image_size)\n pg.draw.rect(self.image, (255, 0, 0), (x, y, 4, 4))\n\n\ndef mapping(value, xmin, xmax, ymin, ymax):\n x_span = xmax - xmin\n y_span = ymax - ymin\n\n scaled_value = float(value - xmin) / float(x_span)\n\n return ymin + (scaled_value * y_span)\n\n\ndef check_collision(group):\n collision_tree.clear()\n for sprite in group:\n collision_tree.insert(sprite)\n\n collision_list = []\n for sprite in group:\n for other in collision_tree.query(sprite.rect):\n if sprite != other:\n if pg.sprite.collide_rect(sprite, other):\n if pg.sprite.collide_mask(sprite, other):\n collision_list.append((sprite, other))\n\n return collision_list\n\n\nclass Game:\n def __init__(self, w):\n self.window = w\n self.running = True\n self.player = Player()\n self.camera = Camera(self.player)\n self.ships = []\n self.ships.append(self.player)\n self.bullets = []\n self.radar = Radar(self.player, [self.ships])\n self.particles = []\n self.explosions = []\n\n self.layers = []\n\n self.last_spawn = 0\n\n if pg.joystick.get_count() != 0:\n self.joystick = pg.joystick.Joystick(0)\n self.joystick.init()\n self.mode_joystick = True\n else:\n self.mode_joystick = False\n\n def create_map(self):\n self.layers.append(Layer(0.1, mapSize, windowWidth / 0.1 - windowWidth, windowHeight / 0.1 - windowHeight))\n self.layers.append(Layer(0.2, mapSize, windowWidth / 0.2 - windowWidth, windowHeight / 0.1 - windowHeight))\n self.layers.append(Layer(0.3, mapSize, windowWidth / 0.3 - windowWidth, windowHeight / 0.1 - windowHeight))\n self.layers.append(Layer(0.4, mapSize, windowWidth / 0.4 - windowWidth, windowHeight / 0.1 - windowHeight))\n self.layers.append(Layer(0.6, mapSize, windowWidth / 0.6 - windowWidth, windowHeight / 0.1 - windowHeight))\n self.layers[0].create_objs(100, 'png/star1.png')\n self.layers[1].create_objs(50, choice(meteor_pngs))\n self.layers[2].create_objs(75, choice(meteor_pngs))\n self.layers[3].create_objs(100, choice(meteor_pngs))\n self.layers[4].create_objs(100, choice(meteor_pngs))\n\n def input(self):\n for event in pg.event.get():\n if event.type == pg.JOYBUTTONDOWN and event.button == 8 or \\\n event.type == pg.KEYDOWN and event.key == pg.K_ESCAPE:\n self.running = False\n\n if self.player.alive:\n if self.mode_joystick:\n if self.joystick.get_button(4):\n shot = self.player.shoot()\n if shot:\n self.add_bullet(self.player, shot)\n if self.joystick.get_button(5):\n self.particles.append(self.player.power())\n\n x = self.joystick.get_axis(0)\n y = self.joystick.get_axis(1)\n\n else:\n buttons = pg.mouse.get_pressed()\n if buttons[0] == 1:\n self.particles.append(self.player.power())\n if buttons[2] == 1:\n shot = self.player.shoot()\n if shot:\n self.add_bullet(self.player, shot)\n\n mouse_pos = pg.mouse.get_pos()\n x = mouse_pos[0] - (self.player.rect.centerx - self.camera.rect.x)\n y = mouse_pos[1] - (self.player.rect.centery - self.camera.rect.y)\n\n self.player.angle = atan2(y, x)\n\n def spawn_enemy(self):\n time = pg.time.get_ticks()\n if self.last_spawn + 5000 < time:\n self.last_spawn = time\n self.ships.append(Enemy([self.player], self.ships))\n\n def add_bullet(self, shooter, vel):\n self.bullets.append(Bullet(shooter.pos, vel, shooter.angle, self.player))\n\n def game_over(self):\n self.ships.remove(self.player)\n\n\nclass GameSingle(Game):\n def __init__(self, w):\n super().__init__(w)\n\n self.create_map()\n\n def loop(self): # TODO divide into smaller functions\n while self.running:\n self.window.fill((40, 50, 50))\n\n self.input()\n\n self.spawn_enemy()\n\n self.collision()\n\n self.kill()\n\n for ship in self.ships:\n ship.update()\n\n for bullet in self.bullets:\n bullet.update()\n\n for exp in self.explosions:\n part = exp.update()\n if part:\n self.particles.append(part)\n\n self.camera.move()\n self.camera.draw_layers(self.layers, self.window)\n self.camera.draw(self.bullets, self.window)\n self.camera.draw(self.ships, self.window)\n self.camera.draw(self.particles, self.window)\n\n self.particles = []\n\n score_surf = font.render(str(self.player.score), True, (255, 255, 255))\n self.window.blit(score_surf, (windowWidth - score_surf.get_width(), 0))\n\n self.radar.update()\n self.window.blit(self.radar.image, (20, 20))\n\n pg.display.update()\n clock.tick(fps)\n\n return self.player.score\n\n def collision(self):\n handled = []\n for collision in check_collision(self.ships + self.bullets):\n if collision[0] not in handled and collision[1] not in handled:\n\n if isinstance(collision[0], Ship) and isinstance(collision[1], Ship):\n self.explosions.append(collision[0].die())\n self.explosions.append(collision[1].die())\n\n elif isinstance(collision[0], Bullet):\n part = collision[0].check_hit(collision[1])\n if part:\n if collision[0].shooter == self.player:\n self.player.score += 50\n self.particles.append(part)\n\n elif isinstance(collision[1], Bullet):\n part = collision[1].check_hit(collision[0])\n if part:\n if collision[1].shooter == self.player:\n self.player.score += 50\n self.particles.append(part)\n\n handled.append(collision[0])\n handled.append(collision[1])\n\n def kill(self):\n for ship in self.ships:\n exp = ship.check_alive()\n if exp:\n if ship == self.player:\n self.game_over()\n try:\n self.ships.remove(ship)\n except ValueError:\n pass\n self.explosions.append(exp)\n\n for bullet in self.bullets:\n if not bullet.alive:\n self.bullets.remove(bullet)\n\n\nclass GameMulti(Game):\n def __init__(self, w):\n super().__init__(w)\n\n self.socket = socket.socket()\n self.send_list = []\n\n self.player = Player(get_key())\n self.send_list.append(AddEvent(self.player.img_path, self.player.rect.size, self.player.key, 'player'))\n\n self.camera = Camera(self.player)\n self.ships = []\n self.ghost_bullets = []\n self.ghost_ships = []\n self.ghost_players = []\n self.ships.append(self.player)\n self.bullets = []\n self.radar = Radar(self.player, [self.ships, self.ghost_ships, self.ghost_players])\n\n def send(self, data):\n encoded_data = pickle.dumps(data)\n try:\n self.socket.send(encoded_data)\n except ConnectionError:\n pass\n\n def receive(self):\n data = None\n try:\n data = pickle.loads(self.socket.recv(2048))\n except EOFError:\n pass\n except ConnectionError:\n pass\n\n if data:\n for event in data:\n if isinstance(event, AddEvent):\n if event.obj == 'ship':\n event.do(self.ghost_ships)\n elif event.obj == 'player':\n event.do(self.ghost_players)\n\n elif isinstance(event, ShootEvent):\n event.do(self.ghost_bullets)\n\n else:\n event.do()\n\n def spawn_enemy(self): # TODO make better\n time = pg.time.get_ticks()\n if self.last_spawn + 5000 < time:\n self.last_spawn = time\n ship = Enemy([self.player] + self.ghost_players, self.ships, key=get_key())\n self.ships.append(ship)\n self.send_list.append(AddEvent(ship.img_path, ship.rect.size, ship.key, 'ship'))\n\n def add_bullet(self, shooter, vel):\n bullet = Bullet(shooter.pos, vel, shooter.angle, shooter, get_key())\n self.bullets.append(bullet)\n self.send_list.append(ShootEvent(bullet.pos, bullet.vel, bullet.angle, bullet.key))\n\n def collision(self):\n handled = []\n for collision in check_collision(self.ships + self.bullets + self.ghost_ships + self.ghost_bullets):\n if collision[0] not in handled and collision[1] not in handled:\n\n if isinstance(collision[0], Ship) and isinstance(collision[1], Ship):\n self.explosions.append(collision[0].die())\n self.explosions.append(collision[1].die())\n\n if not isinstance(collision[0], Ghost):\n self.send_list.append(KillEvent(collision[0].key))\n if not isinstance(collision[1], Ghost):\n self.send_list.append(KillEvent(collision[1].key))\n\n elif isinstance(collision[0], Bullet):\n part = collision[0].check_hit(collision[1])\n if part:\n if collision[0].shooter == self.player:\n self.player.score += 50\n self.particles.append(part)\n\n elif isinstance(collision[1], Bullet):\n part = collision[1].check_hit(collision[0])\n if part:\n if collision[1].shooter == self.player:\n self.player.score += 50\n self.particles.append(part)\n\n handled.append(collision[0])\n handled.append(collision[1])\n\n def kill(self):\n for ship in self.ships:\n exp = ship.check_alive()\n if exp:\n if ship == self.player:\n self.game_over()\n try:\n self.ships.remove(ship)\n except ValueError:\n pass\n self.explosions.append(exp)\n self.send_list.append(KillEvent(ship.key))\n\n for bullet in self.bullets:\n if not bullet.alive:\n self.bullets.remove(bullet)\n self.send_list.append(KillEvent(bullet.key))\n\n for bullet in self.ghost_bullets:\n if not bullet.alive:\n self.ghost_bullets.remove(bullet)\n\n for ship in self.ghost_ships:\n if ship.check_alive():\n self.ghost_ships.remove(ship)\n\n def game_over(self):\n self.ships.remove(self.player)\n self.send_list.append(KillEvent(self.player.key))\n\n\nclass GameServer(GameMulti):\n def __init__(self, w, sock):\n super().__init__(w)\n\n self.socket = sock\n\n self.create_map()\n self.send_map()\n\n def loop(self):\n while self.running:\n self.window.fill((40, 50, 50))\n self.particles = []\n\n self.input()\n\n self.spawn_enemy()\n\n self.collision()\n\n self.kill()\n\n for ship in self.ships:\n ship.update()\n self.send_list.append(MoveEvent(ship.key, ship.pos, ship.angle))\n\n for bullet in self.bullets:\n bullet.update()\n\n for exp in self.explosions:\n part = exp.update()\n if part:\n self.particles.append(part)\n\n self.receive()\n self.send(self.send_list)\n\n for ghost in self.ghost_ships + self.ghost_bullets + self.ghost_players:\n ghost.update()\n\n self.camera.move()\n self.camera.draw_layers(self.layers, self.window)\n all_sprites = self.bullets + self.ghost_bullets + self.ships + self.ghost_ships + self.ghost_players\n self.camera.draw(all_sprites, self.window)\n self.camera.draw(self.particles, self.window)\n\n self.radar.update()\n self.window.blit(self.radar.image, (20, 20))\n\n score_surf = font.render(str(self.player.score), True, (255, 255, 255))\n self.window.blit(score_surf, (windowWidth - score_surf.get_width(), 0))\n\n pg.display.update()\n self.send_list = []\n clock.tick(fps)\n\n self.socket.close()\n return self.player.score\n\n def send_map(self):\n encoded_list = []\n for layer in self.layers:\n encoded_list.append(layer.get_dict())\n data = pickle.dumps(encoded_list)\n\n length = len(data)\n print('byte size: ' + str(length))\n self.socket.sendall(str(length).encode())\n\n self.socket.sendall(data)\n\n\nclass GameClient(GameMulti):\n def __init__(self, w, sock):\n super().__init__(w)\n\n self.socket = sock\n\n self.recv_map()\n\n def loop(self):\n while self.running:\n self.window.fill((40, 50, 50))\n self.particles = []\n\n self.input()\n\n self.collision()\n\n self.kill()\n\n for ship in self.ships:\n ship.update()\n self.send_list.append(MoveEvent(ship.key, ship.pos, ship.angle))\n\n for bullet in self.bullets:\n bullet.update()\n\n for exp in self.explosions:\n part = exp.update()\n if part:\n self.particles.append(part)\n\n self.send(self.send_list)\n self.receive()\n\n for ghost in self.ghost_ships + self.ghost_bullets + self.ghost_players:\n ghost.update()\n\n self.camera.move()\n self.camera.draw_layers(self.layers, self.window)\n self.camera.draw(self.ghost_ships + self.ghost_bullets + self.ghost_players, self.window)\n self.camera.draw(self.bullets + self.ships, self.window)\n self.camera.draw(self.particles, self.window)\n\n self.radar.update()\n self.window.blit(self.radar.image, (20, 20))\n\n score_surf = font.render(str(self.player.score), True, (255, 255, 255))\n self.window.blit(score_surf, (windowWidth - score_surf.get_width(), 0))\n\n pg.display.update()\n self.send_list = []\n clock.tick(fps)\n\n self.socket.close()\n return self.player.score\n\n def recv_map(self):\n length = int(self.socket.recv(1024).decode())\n encoded_data = b''\n while True:\n if len(encoded_data) == length:\n break\n d = self.socket.recv(8192)\n encoded_data += d\n\n layer_list = pickle.loads(encoded_data)\n\n for layer_dct in layer_list:\n self.layers.append(decode_layer(layer_dct))\n\n\nclass AddEvent:\n def __init__(self, img_path, img_size, key, obj):\n self.img_path = img_path\n self.img_size = img_size\n self.key = key\n self.obj = obj\n\n def do(self, group):\n shp = Ghost(self.img_path, self.img_size)\n keys_dict[self.key] = shp\n used_keys.append(self.key)\n group.append(shp)\n\n\nclass MoveEvent:\n def __init__(self, key, pos, angle):\n self.key = key\n self.pos = pos.copy()\n self.angle = angle\n\n def do(self):\n obj = keys_dict[self.key]\n obj.pos = self.pos\n obj.angle = self.angle\n\n\nclass ShootEvent:\n def __init__(self, pos, vel, angle, key):\n self.pos = pos.copy()\n self.vel = vel.copy()\n self.key = key\n self.angle = angle\n\n def do(self, group):\n bullet = Bullet(self.pos, self.vel, self.angle, None, self.key)\n keys_dict[self.key] = bullet\n group.append(bullet)\n\n\nclass ParticleEvent:\n def __init__(self):\n pass\n\n\ndef get_key():\n key = str(randint(0, 255))\n while key in used_keys:\n key = str(randint(0, 255))\n\n used_keys.append(key)\n\n return key\n\n\nclass KillEvent:\n def __init__(self, key):\n self.key = key\n\n def do(self):\n keys_dict[self.key].die()\n\n\n# class Ghost(pg.sprite.Sprite):\n# def __init__(self, img_path, img_size):\n# super().__init__()\n#\n# self.pos = Vector2d(0, 0)\n# self.image = pg.image.load(img_path)\n# if img_size:\n# self.image = pg.transform.scale(self.image, img_size)\n# self.original_img = self.image.copy()\n# self.rect = self.image.get_rect()\n# self.angle = 0\n#\n# def update(self):\n# self.image = pg.transform.rotate(self.original_img, 270 - degrees(self.angle))\n# self.rect.size = self.image.get_size()\n# self.rect.center = self.pos.x, self.pos.y\n#\n# def die(self):\n# self.kill()\n","sub_path":"game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":20431,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"460355986","text":"# -*- coding: utf-8 -*-\n\nimport os\nfrom os.path import expanduser\nimport re\nimport pkg_resources\nimport json\n\n\ndef cotede_dir():\n return expanduser(os.getenv('COTEDE_DIR', '~/.config/cotederc'))\n\n\ndef cotederc(subdir=None):\n \"\"\"Returns the directory with custom config for CoTeDe\n \"\"\"\n path = expanduser(os.getenv('COTEDE_DIR', '~/.config/cotederc'))\n if subdir is not None:\n path = os.path.join(path, subdir)\n return path\n\n# ============================================================================\ndef savePQCCollection_pandas(db, filename):\n \"\"\" Save\n\n To Do:\n - Save the files in a tmp file\n - As it saves, creates a md5 of each file\n - Put everything together in a tar.bz2, including the md5 list\n - Delete the tmp file\n \"\"\"\n import os\n import tempfile\n import tarfile\n import shutil\n import hashlib\n # tar = tarfile.open(\"%s.tar.bz2\" % filename, \"w:bz2\")\n tar = tarfile.open(filename, \"w:bz2\")\n tmpdir = tempfile.mkdtemp()\n\n try:\n # Data\n f = \"%s/data.hdf\" % (tmpdir)\n db.data.to_hdf(f, 'df')\n tar.add(f, arcname='data.hdf')\n # hashlib.md5(open(f, 'rb').read()).digest()\n # hashlib.sha256(open(f, 'rb').read()).digest()\n # Flags\n p = os.path.join(tmpdir, 'flags')\n os.mkdir(p)\n for k in db.flags.keys():\n f = os.path.join(p, \"flags_%s.hdf\" % k)\n db.flags[k].to_hdf(f, 'df')\n tar.add(f, arcname=\"flags/flags_%s.hdf\" % k)\n if hasattr(db, 'auxiliary'):\n p = os.path.join(tmpdir, 'aux')\n os.mkdir(p)\n for k in db.auxiliary.keys():\n f = os.path.join(p, \"aux_%s.hdf\" % k)\n db.auxiliary[k].to_hdf(f, 'df')\n tar.add(f, arcname=\"aux/aux_%s.hdf\" % k)\n tar.close()\n except:\n shutil.rmtree(tmpdir)\n raise\n print(\"Problems saving the data\")\n shutil.rmtree(\"%s.tar.bz2\" % filename)\n finally:\n shutil.rmtree(tmpdir)\n\n\ndef loadPQCCollection_pandas(filename):\n import os\n import tempfile\n import tarfile\n import shutil\n tmpdir = tempfile.mkdtemp()\n tar = tarfile.open(filename, \"r:*\")\n tar.extractall(path=tmpdir)\n shutil.rmtree(tmpdir)\n","sub_path":"cotede/utils/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2298,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"137967888","text":"import pandas as pd\nimport streamlit as st\nimport matplotlib.pyplot as plt\n\ndf = pd.read_csv('University_Rank.csv')\n\ndef line_plot(column):\n x = df[column]\n y = df['Overall_Score']\n\n plt.scatter(x, y)\n plt.xlabel(str(column))\n plt.ylabel('Overall Score')\n title = 'Overall Score vs. ' + str(column)\n plt.title(title)\n\n return plt\n\ndef main():\n df = pd.read_csv('University_Rank.csv')\n factor = ['International_Student_Ratio', 'International_Faculty_Ratio', 'Faculty_Student_Ratio', 'Citations_per_Faculty', 'Academic_Reputation', 'Employer_Reputation']\n st.title(\"QS Top 30 University Analysis\")\n data_load_state = st.text('Loading data...')\n data_load_state.text(\"Finished loading data!\")\n column = st.sidebar.multiselect('Select a factor', factor)\n st.pyplot(line_plot(column))\n\nmain()\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":833,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"26850293","text":"\"\"\"Utilities for working with Shelf components.\"\"\"\n\nimport logging\n\nfrom six import itervalues\n\n# pylint: disable=unused-import\ntry:\n from typing import Any\n from typing import Dict\n from typing import Tuple\nexcept ImportError:\n pass\n\nfrom photon.lib import drive_utils\nfrom photon.lib import hardware_utils\n\nLOGGER = logging.getLogger(__name__)\n\n\ndef _build_drive_enclosure(enclosure_name, enclosure_handle):\n # type: (str, str) -> Enclosure\n \"\"\"Build an Enclosure (shelf/chassis) for the given drive instance.\"\"\"\n if 'SH' in enclosure_name:\n enc_type = Shelf\n elif 'CH' in enclosure_name:\n enc_type = Chassis\n else:\n LOGGER.warning('Unknown enclosure type: {}. Using base Enclosure type.'.format(enclosure_name))\n enc_type = Enclosure\n return enc_type(enclosure_name, **{'handle': enclosure_handle})\n\n\ndef build_enclosures(drives):\n # type: (Dict[str, Any]) -> Dict[str, Enclosure]\n \"\"\"Build Enclosures and add Drive instances to them.\n\n Arguments:\n drives (dict): One or more named drive instances.\n\n Returns:\n enclosures (dict): One or more Enclosure instances built, based upon the drives.\n \"\"\"\n enclosures = {}\n for drive in itervalues(drives):\n enclosure_name = drive.location\n enclosure = _build_drive_enclosure(enclosure_name, drive.parent_id)\n if enclosure_name not in enclosures:\n enclosures[enclosure_name] = enclosure\n\n # Add the drive to the stored enclosure instance.\n enclosures[enclosure_name].add_component(drive)\n return enclosures\n\n\nclass Enclosure(hardware_utils.StorageGroup):\n \"\"\"The base class for enclosures which house drives.\n\n Arguments:\n name (str): The bay name of a drive. i.e. 'SH2'\n kwargs (Keyword Arguments): Additional pass-through arguments.\n \"\"\"\n\n def __init__(self, name, **kwargs):\n # type: (str, **Dict[Any]) -> None\n super(Enclosure, self).__init__(name, **kwargs)\n self.kwargs = kwargs\n self._capacity = None\n self.drives = self.components\n LOGGER.debug('Created an Enclosure ({}).'.format(self.name))\n\n def __str__(self):\n # type: () -> str\n \"\"\"Return the name and capacity of this enclosure.\"\"\"\n return 'Enclosure {} ({} drives; {} B).'.format(self.name, len(self.drives), self.capacity)\n\n @property\n def compatible_components(self):\n # type: () -> Tuple[drive_utils.NVRAM, drive_utils.SSD]\n \"\"\"A listing of all compatible sub-components that can be added to this group.\"\"\"\n return drive_utils.NVRAM, drive_utils.SSD\n\n\nclass Chassis(Enclosure):\n \"\"\"A single chassis containing drives.\n\n Arguments:\n name (str): The name of the Chassis. i.e. 'CH2'\n kwargs (Keyword Arguments): Additional pass-through arguments.\n \"\"\"\n\n\nclass Shelf(Enclosure):\n \"\"\"A single Shelf containing drives.\n\n Arguments:\n name (str): The name of the Shelf. i.e. 'SH2'\n kwargs (Keyword Arguments): Additional pass-through arguments.\n \"\"\"\n","sub_path":"lib/shelf_utils.py","file_name":"shelf_utils.py","file_ext":"py","file_size_in_byte":3065,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"105296092","text":"import subprocess\n\nif __name__ == '__main__':\n\n outfile = '/home/richard/gee_task_list.txt'\n\n with open(outfile, 'w') as f:\n\n command = \"earthengine task list\"\n proc = subprocess.Popen(command.split(\" \"),\n stdout=subprocess.PIPE)\n f.write(proc.stdout.read())\n\n print(proc)\n print('Done!')\n\n","sub_path":"data/get_task_list.py","file_name":"get_task_list.py","file_ext":"py","file_size_in_byte":354,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"562452584","text":"import random\nimport torch\nimport torch.utils.data\n\n\nclass SampleRNNPASELoader(torch.utils.data.DataLoader):\n dataset = None\n batch_size = None\n receptive_field = None\n conds_utterance_size = None\n\n dataset_iterator = None\n buffer = None\n reset_buffer = None\n no_more_samples_in_batch = None\n\n def __init__(self, dataset, batch_size):\n self.dataset = dataset\n self.batch_size = batch_size\n self.receptive_field = self.dataset.frame_size * self.dataset.sequence_length\n if self.dataset.conds_utterance_type == 'acoustic':\n self.conds_utterance_size = 43\n elif self.dataset.conds_utterance_type == 'linguistic':\n self.conds_utterance_size = 55\n else:\n self.conds_utterance_size = 57\n super().__init__(self.dataset, self.batch_size)\n\n def __iter__(self):\n self._reset_parameters()\n while True:\n self._prepare_buffers()\n self._fill_data()\n yield self._yield_iteration()\n\n def _reset_parameters(self):\n self.dataset.shuffle_utterances()\n self.dataset_iterator = iter(self.dataset)\n self.buffer = [None] * self.batch_size\n self.reset_buffer = [None] * self.batch_size\n self.no_more_samples_in_batch = False\n\n def _prepare_buffers(self):\n for buffer_index, buffer_item in enumerate(self.buffer):\n if buffer_item is None:\n continue\n self.reset_buffer[buffer_index] = False\n if buffer_item[1].shape[0] < self.dataset.sequence_length:\n self.buffer[buffer_index] = None\n self.reset_buffer[buffer_index] = None\n\n def _fill_data(self):\n while not all(self.buffer) and not self.no_more_samples_in_batch:\n try:\n none_indexes = [i for i, x in enumerate(self.buffer) if x is None]\n none_index = random.choice(none_indexes)\n self.buffer[none_index] = list(next(self.dataset_iterator))\n self.reset_buffer[none_index] = True\n except StopIteration:\n self.no_more_samples_in_batch = True\n\n def _yield_iteration(self):\n x_len, y_len, utt_conds_len = self._get_iteration_sizes()\n x = []\n y = []\n utt_conds = []\n reset = [2 if reset_item is None else int(reset_item) for i, reset_item in enumerate(self.reset_buffer)]\n info = [buffer_item[2] if buffer_item is not None else None for i, buffer_item in enumerate(self.buffer)]\n for buffer_index, buffer_item in enumerate(self.buffer):\n if buffer_item is None:\n x.append(torch.zeros(x_len))\n y.append(torch.zeros(y_len))\n utt_conds.append(torch.zeros(utt_conds_len, self.conds_utterance_size))\n continue\n else:\n x.append(torch.from_numpy(buffer_item[0][:x_len]))\n y.append(torch.from_numpy(buffer_item[0][self.dataset.frame_size:self.dataset.frame_size + y_len]))\n utt_conds.append(torch.from_numpy(buffer_item[1][:utt_conds_len, :]).type(torch.float32))\n buffer_item[0] = buffer_item[0][y_len:]\n buffer_item[1] = buffer_item[1][utt_conds_len:, :]\n return torch.stack(x), torch.stack(y), torch.stack(utt_conds), torch.tensor(reset), info\n\n def _get_iteration_sizes(self):\n return self.receptive_field + self.dataset.frame_size - 1, self.receptive_field, self.dataset.sequence_length\n","sub_path":"samplernn_pase/loader.py","file_name":"loader.py","file_ext":"py","file_size_in_byte":3523,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"250413766","text":"from model.model import CovidModel\nfrom mesa.batchrunner import BatchRunner\n\nmodelo_normal = CovidModel(\n 1500, 3, insert_variant=False, width=60, height=60, seed=1024\n)\nmodelo_variante = CovidModel(\n 1500, 3, insert_variant=True, width=60, height=60, seed=1024\n)\n\nfor _ in range(2000):\n modelo_normal.step()\n\n\ndata = modelo_normal.datacollector.get_model_vars_dataframe()\n\nprint(f\"Rodando modelo normal por 2000 iterações:\\n{data}\")\n\ndata.to_csv(\"../data/modelo_comum_dados.csv\")\n\nfor _ in range(2000):\n modelo_variante.step()\n\ndata_variante = modelo_variante.datacollector.get_model_vars_dataframe()\nprint(f\"Rodando modelo variante por 2000 iterações:\\n{data_variante}\")\n\ndata_agentes_variante = modelo_variante.datacollector.get_agent_vars_dataframe()\n\ndata_variante.to_csv(\"../data/modelo_variante_dados.csv\")\ndata_agentes_variante.to_csv(\"../data/agentes_variante.csv\")","sub_path":"src/batch_run.py","file_name":"batch_run.py","file_ext":"py","file_size_in_byte":890,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"216602176","text":"import matplotlib.pyplot as plt\nimport imageio\nimport csv\n\nnData = 15000\ndatafiles = []\nfor i in range(0,nData+1):\n if(i%100 == 0):\n print(\"plotting\",i)\n with open(\"data/data\"+str(i)+\".dat\", \"r\") as csvfile:\n plots = csv.reader(csvfile, delimiter='\\t')\n x = []\n y = []\n value = []\n for row in plots:\n x.append(float(row[0]))\n y.append(float(row[1]))\n value.append(float(row[2]))\n\n plt.scatter(x,y,c=value)\n plt.savefig(\"plots/plot\"+str(i)+\".png\")\n plt.cla()\n","sub_path":"src/plot.py","file_name":"plot.py","file_ext":"py","file_size_in_byte":560,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"16397190","text":"split = 'exp'\ndataset = 'folder'\nheight = 320\nwidth = 640\ndisparity_smoothness = 1e-3\nscales = [0, 1, 2, 3, 4]\nmin_depth = 0.1\nmax_depth = 100.0\nframe_ids = [0, -1, 1]\nlearning_rate = 1e-4\ndepth_num_layers = 50\npose_num_layers = 50\ntotal_epochs = 45\ndevice_ids = range(8)\n\ndepth_pretrained_path = '/node01/jobs/io/pretrained/checkpoints/resnet/resnet{}.pth'.format(depth_num_layers)\npose_pretrained_path = '/node01/jobs/io/pretrained/checkpoints/resnet/resnet{}.pth'.format(pose_num_layers)\n\nin_path = '/ssd/avp/soho_garage3/keyframe_underground'\ngt_depth_path = ''\ncheckpoint_path = '/node01_data5/monodepth2-test/model/refine/smallfigure.pth'\n\nimgs_per_gpu = 2\nworkers_per_gpu = 4\n\nvalidate = False\n\npng = False\nscale_invariant = False\nplane_fitting = False\nfinetune = False\nperception = False\nfocus_loss = False\n\nscale_invariant_weight = 0.01\nplane_fitting_weight = 0.0001\nperceptional_weight = 0.001\n\noptimizer = dict(type='Adam', lr=learning_rate, weight_decay=0)\noptimizer_config = dict(grad_clip=dict(max_norm=35, norm_type=2))\n# learning policy\nlr_config = dict(\n policy='step',\n warmup='linear',\n warmup_iters=500,\n warmup_ratio=1.0 / 3,\n step=[15,25,35],\n gamma=0.5,\n )\n\ncheckpoint_config = dict(interval=1)\n# yapf:disable\nlog_config = dict(interval=50,\n hooks=[dict(type='TextLoggerHook'),])\n# yapf:enable\n# runtime settings\ndist_params = dict(backend='nccl')\nlog_level = 'INFO'\nload_from = None\nresume_from = None\nworkflow = [('train', 1)]","sub_path":"config/cfg_folder.py","file_name":"cfg_folder.py","file_ext":"py","file_size_in_byte":1490,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"82139061","text":"# -*- coding: utf-8 -*-\n\"\"\"\n tickets._compat\n ~~~~~~~~~~~~~~~\n\n Compatibility for Python2 and Python3.\n\"\"\"\nimport sys\n\n\n_ver = sys.version_info\n\n#: Py2.*?\nis_py2 = (_ver[0] == 2)\n\n#: Py3.*?\nis_py3 = (_ver[0] == 3)\n\nif is_py2:\n unicode_type = unicode\n bytes_type = str\nelif is_py3:\n unicode_type = str\n bytes_type = bytes\n\n\ndef to_unicode(value, encoding='utf-8'):\n if isinstance(value, unicode_type):\n return value\n\n if isinstance(value, bytes_type):\n return unicode_type(value, encoding=encoding)\n\n if isinstance(value, int):\n return unicode_type(str(value))\n\n return value\n","sub_path":"tickets/_compat.py","file_name":"_compat.py","file_ext":"py","file_size_in_byte":629,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"257105366","text":"import matplotlib.pyplot as plt\nimport numpy as np\nimport time\nimport random\n#import types\n\ndef loadDataset(fileName):\n '''\n 说明:读入数据\n\n Arguments:\n fileName - 数据文件名\n\n Returns:\n dataMat - 数据集和:X\n labelMat - 数据集合:Y\n '''\n dataMat = []\n labelMat = []\n fr = open(fileName)\n for line in fr.readlines():\n lineArr = line.strip().split('\\t')\n dataMat.append([float(lineArr[0]), float(lineArr[1])])\n labelMat.append(float(lineArr[2]))\n return dataMat, labelMat\n\ndef showDataSet(dataMat, labelMat):\n '''\n Declaration:\n 画出正负样本图形\n\n :param dataMat: 样本X\n :param labelMat: 样本Y\n :return: 无\n '''\n data_plus = []\n data_minus = []\n for i in range(len(dataMat)):\n if labelMat[i] > 0:\n data_plus.append(dataMat[i])\n else:\n data_minus.append(dataMat[i])\n data_plus_np = np.array(data_plus)\n data_minus_np = np.array(data_minus)\n plt.scatter(np.transpose(data_plus_np)[0], np.transpose(data_plus_np)[1])\n plt.scatter(np.transpose(data_minus_np)[0], np.transpose(data_minus_np)[1])\n plt.show()\n\ndef showClassifer(dataMat, labelMat, w, b):\n #绘制样本点\n data_plus = [] #正样本\n data_minus = [] #负样本\n for i in range(len(dataMat)):\n if labelMat[i] > 0:\n data_plus.append(dataMat[i])\n else:\n data_minus.append(dataMat[i])\n data_plus_np = np.array(data_plus) #转换为numpy矩阵\n data_minus_np = np.array(data_minus) #转换为numpy矩阵\n plt.scatter(np.transpose(data_plus_np)[0], np.transpose(data_plus_np)[1], s=30, alpha=0.7) #正样本散点图\n plt.scatter(np.transpose(data_minus_np)[0], np.transpose(data_minus_np)[1], s=30, alpha=0.7) #负样本散点图\n #绘制直线\n x1 = max(dataMat)[0]\n x2 = min(dataMat)[0]\n\n b = float(b)\n a1 = float(w[0][0])\n a2 = float(w[0][1])\n y1, y2 = (-b- a1*x1)/a2, (-b - a1*x2)/a2\n plt.plot([x1, x2], [y1, y2])\n #找出支持向量点\n for i, alpha in enumerate(alphas):\n if alpha > 0:\n x, y = dataMat[i]\n plt.scatter([x], [y], s=150, c='none', alpha=0.7, linewidth=1.5, edgecolor='red')\n plt.show()\n\ndef clipAlpha(alpha, H, L):\n '''\n Declaration: 修剪alpha\n :param alpha: 更新后的alpha\n :param H: 上限\n :param L: 下限\n :return: 修剪后的alpha\n '''\n if alpha > H:\n alpha = H\n if alpha < L:\n alpha = L\n return alpha\n\ndef gX(dataMat, labelMat, alphas, index):\n '''\n Declaration:\n 计算g(x)\n f(x) = g(x) + b\n :param dataMat: 样本X\n :param labelMat: 样本Y\n :param alphas: alpha\n :param index: 索引[index]\n :return: g(x[index])\n '''\n ay = alphas*labelMat\n ayx = np.dot(ay.T, dataMat)\n g_index = np.dot(ayx, (dataMat[index]).T)\n return g_index\n\ndef smoSimple(dataMatIn, classLabels, C, maxIter):\n '''\n Declaration:\n 简化版SMO(Sequential Minimal Optimization)\n\n :param dataMatIn: 数据X\n :param classLabels: 数据Y\n :param C: alpha限定值 - alpha<=C\n :param maxIter: 最大迭代次数\n :return: 超平面参数 w,b, 解为 wx + b = 0\n '''\n dataMat = np.array(dataMatIn)\n labelMat = np.array(classLabels)\n\n m, _ = np.shape(dataMat)\n alphas = np.zeros((m, 1))\n\n labelMat = labelMat.reshape(m,1)\n b = 0\n\n iter_num = 0\n while(iter_num < maxIter):\n for i in range(m):\n #随机确定 j\n j = i\n while( j==i):\n j = int(random.uniform(0,m))\n\n xi = dataMat[i]; xj = dataMat[j]\n yi = labelMat[i]; yj = labelMat[j]\n alphai_old = alphas[i]; alphaj_old = alphas[j]\n\n gi = gX(dataMat, labelMat, alphas, i)\n gj = gX(dataMat, labelMat, alphas, j)\n eta = np.dot(xi, xi.T) + np.dot(xj, xj.T) - 2*np.dot(xi, xj.T)\n\n epsilon = 1e-8\n if abs(yi - yj) < epsilon:\n H = min(C, alphai_old + alphaj_old)\n L = max(0, alphai_old + alphaj_old -C)\n else:\n H = min(C, C + alphaj_old - alphai_old)\n L = max(0, alphaj_old - alphai_old)\n\n alphaj_new = alphaj_old + yj*((gi - yi) - (gj - yj))/eta\n alphaj_new = clipAlpha(alphaj_new, H, L)\n\n alphai_new = alphai_old + yi*yj*(alphaj_old - alphaj_new)\n\n alphas[i] = alphai_new\n alphas[j] = alphaj_new\n\n iter_num +=1\n #print('end', iter_num)\n\n w = get_w(alphas, dataMat, labelMat)\n b = get_b(alphas, dataMat, labelMat)\n\n return alphas,w,b\n\ndef get_w(alphas, data, label):\n '''\n Declaration:得到w\n :param alphas: alpha数组\n :param data: 样本X\n :param label: 样本Y\n :return: 超平面方程参数w\n '''\n ay_temp = alphas*label\n w = np.dot(ay_temp.T, data)\n return w\n\ndef get_b(alphas, data, label):\n '''\n 得到 b\n :param alphas: alpha数组\n :param data: 样本X\n :param label: 样本Y\n :return: 超平面参数 b\n '''\n w = get_w(alphas, data, label)\n index = np.where(abs(alphas) < 1e-8)\n sv_num = len(index[0])\n sum_sv = 0.0\n for i in range(sv_num):\n sv_index = index[0][i]\n yi_sv = label[sv_index]\n wxi_sv = np.dot(w, data[sv_index].T)\n sum_temp = yi_sv - wxi_sv\n sum_sv += sum_temp\n b = sum_sv/sv_num\n return b\n\nif __name__ == '__main__':\n time_start = time.time()\n dataMat,labelMat = loadDataset('SVM_InputData.txt')\n alphas, w,b = smoSimple(dataMat, labelMat, 0.6, 400)\n print('w', w)\n print('b', b)\n time_end = time.time()\n print('time:', time_end - time_start, ' s')\n showClassifer(dataMat, labelMat, w, b)\n","sub_path":"SVM/data_visualization_SVM.py","file_name":"data_visualization_SVM.py","file_ext":"py","file_size_in_byte":5869,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"219878143","text":"#!usr/bin/env python3\r\n#-*-coding:utf-8 -*-\r\n#Filename:IO.py\r\n\r\n#The IO things is divided in synchronous and asynchronous to improve the CPU effience\r\n#The file read and open\r\n#f=open('/UsersUsers/liangkan/AppData/Local/Programs/Python/Python36-32/README.txt','r')\r\n\"\"\"\r\ntry:\r\n f=open('/path/to/file','r')\r\n print(f.read())\r\nfinally:\r\n if f:\r\n f.write('Hello world.')\r\n else:\r\n f.close()\r\n\"\"\"\r\nimport os\r\nos.name\r\n\r\n#Json update/improve\r\nimport json\r\nd=dict(name='bob',age=20,score=90)\r\njson.dumps(d) #Change the dict into a string\r\n\r\nclass Student(object):\r\n def __init__(self,name,age,score):\r\n self.name=name\r\n self.age=age\r\n self.score=score\r\n\r\ndef student2dict(std): #Make the Student class be a Dict style\r\n return {\r\n 'name':std.name, #The spot should not missed\r\n 'age':std.age,\r\n 'score':std.score\r\n }\r\ns=Student('Bob',20,90)\r\nprint(json.dumps(s,default=student2dict))\r\n\r\n#Parent and children muti-process : fork()\r\n#And fork() only for Unix/Linux, Windows system has no fork()\r\n'''\r\nimport os\r\npid=os.fork()\r\nif pid==0:\r\n print('I am child process(%s) and my parent is (%s)'%(os.getpid().os.getppid()))\r\nelse:\r\n print('I (%s) just created a child process (%s)'%(os.getpid(),pid))\r\n'''\r\n","sub_path":"IO_File.py","file_name":"IO_File.py","file_ext":"py","file_size_in_byte":1287,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"335134695","text":"import gpio_pin\nimport importlib\nimport logging\nimport RPi.GPIO as gpio\nimport salt.exceptions\n\nfrom messaging import EventDrivenMessageProcessor\nfrom retrying import retry\n\n\nlog = logging.getLogger(__name__)\n\n# Message processor\nedmp = EventDrivenMessageProcessor(\"audio\", default_hooks={\"handler\": \"play\"})\n\ncontext = {\n \"mixer\": {\n \"settings\": None,\n \"initialized\": False\n }\n}\n\n\n@retry(stop_max_attempt_number=5, wait_fixed=1000)\ndef _ensure_mixer():\n ctx = context[\"mixer\"]\n\n if ctx.get(\"initialized\", False):\n return\n\n try:\n settings = ctx[\"settings\"]\n\n globals()[\"pygame\"] = importlib.import_module(\"pygame\")\n\n log.info(\"Initializing mixer using settings: {:}\".format(settings))\n\n pygame.mixer.init(frequency=settings[\"frequency\"],\n size=settings[\"bit_size\"],\n channels=settings[\"channels\"],\n buffer=settings[\"buffer_size\"])\n\n log.debug(\"Successfully initialized mixer\")\n\n ctx[\"initialized\"] = True\n\n except Exception:\n log.exception(\"Failed to initialize mixer\")\n raise\n\n\n@edmp.register_hook()\ndef play_handler(audio_file, force=False, loops=0, volume=None):\n \"\"\"\n Plays a specific audio file. \n\n Arguments:\n - audio_file (str): Local path of audio file to play.\n\n Optional arguments:\n - force (bool): Default is 'False'.\n - loops (int): Default is '0'.\n - volume (int):\n \"\"\"\n\n _ensure_mixer()\n\n if pygame.mixer.music.get_busy():\n if not force:\n return {\n \"success\": False,\n \"error\": \"Already busy playing audio\"\n }\n\n log.info(\"Forcibly fading out ongoing playback\")\n pygame.mixer.music.fadeout(100)\n\n if volume != None:\n log.debug(\"Setting volume to: %d%%\", volume*100)\n pygame.mixer.music.set_volume(volume)\n\n log.debug(\"Loading audio file: %s\", audio_file)\n pygame.mixer.music.load(audio_file)\n\n log.info(\"Playback of audio file: %s\", audio_file)\n pygame.mixer.music.play(loops=loops)\n\n return {\n \"playing\": True\n }\n\n\n@edmp.register_hook()\ndef queue_handler(audio_file):\n \"\"\"\n Queues an audio file.\n\n Arguments:\n - audio_file (str): Local path of audio file to play.\n \"\"\"\n\n _ensure_mixer()\n\n #if not pygame.mixer.music.get_busy():\n # return _play_handler(audio_file)\n\n log.info(\"Queuing audio file: %s\", audio_file)\n # TODO: Apparently not working?\n pygame.mixer.music.queue(audio_file)\n\n return {\n \"queued\": True\n }\n\n\n@edmp.register_hook()\ndef stop_handler():\n \"\"\"\n Stops playback of the current audio.\n \"\"\"\n\n _ensure_mixer()\n\n busy = pygame.mixer.music.get_busy()\n if busy:\n log.info(\"Stopping playback of all audio\")\n pygame.mixer.music.stop()\n\n return {\n \"was_playing\": bool(busy)\n }\n\n\n@edmp.register_hook()\ndef volume_handler(value=None):\n \"\"\"\n Set volumen of the playback.\n\n Optional arguments:\n - value (int):\n \"\"\"\n\n _ensure_mixer()\n\n if value != None:\n log.info(\"Setting volume to: %d%%\", value*100)\n pygame.mixer.music.set_volume(value)\n\n return {\n \"value\": pygame.mixer.music.get_volume()\n }\n\n\n@edmp.register_hook()\ndef speak_handler(text, volume=100, language=\"en-gb\", pitch=50, speed=175, word_gap=10, timeout=10):\n \"\"\"\n Speak given text.\n\n NOTE: Unfortunately 'espeak' command is not always reliable - sometimes it fails for uncertain reasons.\n\n Arguments:\n - text (str): Text to speak out.\n \"\"\"\n\n ret = {}\n\n res = __salt__[\"cmd.run_all\"](\"espeak -a {:d} -v {:s} -p {:d} -s {:d} -g {:d} -X '{:s}'\".format(volume, language, pitch, speed, word_gap, text),\n timeout=timeout) # Timeout added because espeak sometimes hangs\n if res[\"retcode\"] != 0:\n raise salt.exceptions.CommandExecutionError(res[\"stderr\"])\n\n ret[\"result\"] = res[\"stdout\"]\n\n return ret\n\n\ndef start(**settings):\n try:\n if log.isEnabledFor(logging.DEBUG):\n log.debug(\"Starting audio manager with settings: {:}\".format(settings))\n\n context[\"mixer\"][\"settings\"] = settings[\"mixer\"]\n\n gpio.setwarnings(False)\n gpio.setmode(gpio.BOARD)\n gpio.setup(gpio_pin.AMP_ON, gpio.OUT)\n\n # Ensure amplifier is powered on\n gpio.output(gpio_pin.AMP_ON, gpio.HIGH)\n if log.isEnabledFor(logging.DEBUG):\n log.debug(\"Initially powered on amplifier chip by setting GPIO pin #%d high\", gpio_pin.AMP_ON)\n\n # Initialize and run message processor\n edmp.init(__salt__, __opts__)\n edmp.run()\n\n except Exception:\n log.exception(\"Failed to start audio manager\")\n\n raise\n finally:\n log.info(\"Stopping audio manager\")\n\n","sub_path":"src/salt/base/ext/_engines/audio_manager.py","file_name":"audio_manager.py","file_ext":"py","file_size_in_byte":4822,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"629613909","text":"\"\"\"In computer science, an optimal binary search tree, sometimes called a weight-balanced binary tree, is a binary\nsearch tree which provides the smallest possible search time for a given sequence of accesses. \"\"\"\n\"\"\"It is use to determine the tree with minimum height so it provide minimum search time\"\"\"\n\n# To understand the concept please watch this video\n# https://www.youtube.com/watch?v=wAy6nDMPYAE&list=PLDN4rrl48XKpZkf03iYFl-O29szjTrs_O&index=57\n\nnode = [0, 10, 20, 30, 40]\np = [0, 3, 3, 1, 1]\nq = [2, 3, 1, 1, 1]\nn = 5\nweight = [[0 for _ in range(5)] for _ in range(5)]\ncost = [[0 for _ in range(5)] for _ in range(5)]\nK = [[0 for _ in range(5)] for _ in range(5)]\n\nfor d in range(0, n):\n for i in range(0, n - d):\n j = i + d\n if i == j:\n weight[i][j] = q[j]\n cost[i][j] = 0\n K[i][j] = 0\n\n else:\n weight[i][j] = weight[i][j - 1] + p[j] + q[j] # wieght[i][j] = weight[i][j-1]+p[j]+q[j]\n minimum = float('INF')\n for k in range(i + 1, j + 1):\n c = cost[i][k - 1] + cost[k][j] # cost[i][j] = min of {c[i, k-1]+c[k, j] where i str:\n \"\"\"Encodes a tree to a single string.\n \"\"\"\n values = []\n self.preorder(root, values)\n return ','.join(values)\n\n def preorder(self, root, values):\n if root:\n values.append(str(root.val))\n self.preorder(root.left, values)\n self.preorder(root.right, values)\n\n def deserialize(self, data: str) -> TreeNode:\n \"\"\"Decodes your encoded data to tree.\n \"\"\"\n if data:\n values = data.split(',')\n else:\n values = []\n values_queue = deque(values)\n min_value = float('-inf')\n max_value = float('inf')\n return self.build_tree(values_queue, max_value, min_value)\n\n def build_tree(self, values, max_value, min_value):\n if values and max_value > int(values[0]) > min_value:\n value = int(values.popleft())\n root = TreeNode(value)\n root.left = self.build_tree(values, value, min_value)\n root.right = self.build_tree(values, max_value, value)\n return root\n else:\n return None\n\n\n# Your Codec object will be instantiated and called as such:\n# Your Codec object will be instantiated and called as such:\n# ser = Codec()\n# deser = Codec()\n# tree = ser.serialize(root)\n# ans = deser.deserialize(tree)\n# return ans\n","sub_path":"LeetCode31DaysChallenge-202010/Serialize and Deserialize BST.py","file_name":"Serialize and Deserialize BST.py","file_ext":"py","file_size_in_byte":1577,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"405794782","text":"print(\"Rock, Paper, Scissors, Shoot!\")\n\nimport random\n\narr = [\"Rock\",\"Paper\",\"Scissors\"]\n\ndef options (s):\n if s == \"Rock\":\n return arr[0]\n if s == \"rock\":\n return arr[0]\n elif s == \"Paper\":\n return arr[1]\n elif s == \"paper\":\n return arr[1]\n elif s == \"Scissors\":\n return arr[2]\n elif s == \"scissors\":\n return arr[2]\n else:\n return (\"Hmmm...that's not an option. Try entering Rock, Paper, or Scissors\", quit)\n\n\n\nprint(\"--------------------\")\nuser_choice = input(\"Enter Rock, Paper, or Scissors Here: \")\nitem = options(user_choice)\nprint(\"YOU CHOSE:\", item)\n\ncomputer_choice = random.choice(arr)\nprint(f\"COMPUTER CHOSE: '{computer_choice}'\")\n\noutcomes = {\n arr[0]:{\n arr[0]: None,\n arr[1]: arr[1],\n arr[2]: arr[0],\n },\n arr[1]:{\n arr[0]: arr[1],\n arr[1]: None,\n arr[2]: arr[2],\n }, \n arr[2]:{\n arr[0]: arr[0],\n arr[1]: arr[2],\n arr[2]: None,\n }, \n }\n\n\n\nwinning_choice = outcomes[user_choice][computer_choice]\n\nif winning_choice:\n if winning_choice == user_choice:\n print(\"YOU WON\")\n elif winning_choice == computer_choice:\n print(\"YOU LOST\")\nelse:\n print(\"TIE\")\nprint(\"Thanks for playing. Please play again!\")","sub_path":"game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":1292,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"207719558","text":"import main as x\nimport time\nimport graphIOExtra as gio\n\ngraphFiles = ['test/trees11.grl', 'test/trees36.grl', 'test/trees90.grl', 'test/bigtrees1.grl', 'test/bigtrees2.grl',\n 'test/bigtrees3.grl']\n\n\ndef main():\n for graphpath in graphFiles:\n L = gio.loadgraph(graphpath, readlist=True)\n H = gio.loadgraph(graphpath, readlist=True)\n start = time.time()\n Fresults, Ftests = x.findIsomorphisms(L, forcebranching=False)\n mid = time.time()\n Tresults, Ttests = x.findIsomorphisms(H, forcebranching=True)\n end = time.time()\n print('%s | Nodes: %d | Edges: %d' % (graphpath, len(L[0][0]._V), len(L[0][0]._E)))\n print('BFS | Tests: %d, Time: %fs, time/tests: %fs.' % (Ftests, (mid-start), (mid-start)/Ftests))\n print('Branching | Tests: %d, Time: %fs, time/tests: %fs.\\n' % (Ttests, (end-mid), (end-mid)/Ttests))\n\nmain()","sub_path":"experiment.py","file_name":"experiment.py","file_ext":"py","file_size_in_byte":904,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"425502512","text":"import sys\n\nsys.path.add('/home/eweiwi/phd_work/toy_experiments/')\n\nfrom MyCode.utils.FeatureExtractor import FeatureExtractor\nimport numpy as np\n\n\nif __name__ == '__main__':\n param = {'sampling': 'UNIFORM',\n 'im_size': None,\n 'pSize': (24, 24),\n 'sp_pyramid' : 3,\n 'spacing': 4,\n 'max_size' :300,\n 'use_existing_split': False,\n 'use_existing_descriptors': False,\n 'use_existing_simplex': False,\n 'extention': 'avi',\n 'cont': 'videos',\n 'split_ratio': 0.8,\n 'data_structure': 'dataframe',\n 'feature_type': 'hog',\n 'cluster_pak': 'scipy',\n 'train_test_store_path': 'train_test_spm.h5',\n 'descriptors_store_path': 'descriptors_store_spm.h5',\n 'work_path': '/home/eweiwi/phd_work/toy_experiments/',\n 'raw_data_path': '/home/eweiwi/phd_work/datasets/Actions_in_videos/kth_seperate/',\n 'tr_path':'/home/eweiwi/phd_work/datasets/Action_in_still_images/willowactions/train',\n 'tst_path':'/home/eweiwi/phd_work/datasets/Action_in_still_images/willowactions/test',\n 'use_benchmark_split':False\n }\n\n vid_obj = FeatureExtractor()\n ","sub_path":"MyCode/tests/radon3D.py","file_name":"radon3D.py","file_ext":"py","file_size_in_byte":1385,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"407146421","text":"# -*- coding: utf-8 -*-\n\nimport os\nimport sys\nimport copy\nfrom xml.dom import minidom\nfrom robofab.world import CurrentFont\n\ndef splitContour(path):\n\tclass Contour:\n\t\tdef __init__(self, contour, pointList):\n\t\t\tself.pointList = pointList\n\t\t\tself.numLinePoints = 0\n\t\t\tself.numCurvPoints = 0\n\t\t\tself.contour = contour\n\t\t\tself.countPoints()\n\n\t\tdef countPoints(self):\n\t\t\tfor point in self.pointList:\n\t\t\t\tif point.hasAttribute('type') :\n\t\t\t\t\tif point.attributes['type'].value[:] == 'line':\n\t\t\t\t\t\tself.numLinePoints += 1\n\t\t\t\t\telif point.attributes['type'].value[:] == 'curve':\n\t\t\t\t\t\tself.numCurvPoints += 1\n\n\t\tdef getTargetPoint(self):\n\t\t\ttarPointList = []\n\t\t\tfor ind, point in enumerate(self.pointList):\n\t\t\t\tif point.hasAttribute('smooth'):\n\t\t\t\t\tp = self.pointList[ind+1]\n\t\t\t\t\tif p.hasAttribute('type') and p.attributes['type'].value[:] == 'line':\n\t\t\t\t\t\ttarPointList.append(p)\n\n\t\t\t\t\tp = self.pointList[ind-1]\n\t\t\t\t\tif p.hasAttribute('type') and p.attributes['type'].value[:] == 'line':\n\t\t\t\t\t\ttarPointList.append(p)\n\n\t\t\tfor p1 in tarPointList:\n\t\t\t\tfor p2 in tarPointList:\n\t\t\t\t\tif p1 == p2:\n\t\t\t\t\t\tcontinue\n\t\t\t\t\tif p1.attributes['x'].value == p2.attributes['x'].value:\n\t\t\t\t\t\tdel tarPointList[:]\n\t\t\t\t\t\ttarPointList.append(p1)\n\t\t\t\t\t\ttarPointList.append(p2)\n\t\t\t\t\t\tbreak\n\t\t\t\telse:\n\t\t\t\t\tcontinue\n\t\t\t\tbreak\n\t\t\treturn tarPointList\n\n\t\tdef getInnerPointList(self, tarPointList):\n\t\t\tInnerPointList = []\n\t\t\tindexList = []\n\t\t\tindexList.append(self.pointList.index(tarPointList[0]))\n\t\t\tindexList.append(self.pointList.index(tarPointList[1]))\n\t\t\t\n\t\t\tfor index in indexList:\n\t\t\t\tp = self.pointList[index+1]\n\t\t\t\tif not p.hasAttribute('smooth'):\n\t\t\t\t\tInnerPointList.append(p)\n\t\t\t\t\tInnerPointList.append(self.pointList[index+2])\n\t\t\t\telse:\n\t\t\t\t\tInnerPointList.append(self.pointList[index-1])\n\t\t\t\t\tInnerPointList.append(self.pointList[index-2])\n\n\t\t\treturn InnerPointList\n\t\t\n\t\t# def print(self):\n\t\t# \tprint('numLinePoints: ', self.numLinePoints, 'numCurvPoints: ' , self.numCurvPoints)\n\n\tclass Glif:\n\t\tdef __init__(self, dirPath, fileName):\n\t\t\tself.contourList = []\n\t\t\tself.fileName = fileName\n\t\t\tself.parseGlif(dirPath, fileName)\n\n\t\tdef parseGlif(self, dirPath, fileName):\n\t\t\txmldoc = minidom.parse(dirPath + '/' + fileName)\n\t\t\tself.xmldoc = xmldoc\n\t\t\tself.doParse(xmldoc)\n\n\t\tdef doParse(self, xmldoc):\n\t\t\tcontours = xmldoc.getElementsByTagName('contour')\n\t\t\tfor contour in contours:\n\t\t\t\tpointList = contour.getElementsByTagName('point')\n\t\t\t\tc = Contour(contour, pointList)\n\t\t\t\tself.contourList.append(c)\n\n\t\tdef getTargetContour(self):\n\t\t\tfor contour in self.contourList:\n\t\t\t\tif contour.numLinePoints == 14 and contour.numCurvPoints == 2:\n\t\t\t\t\treturn contour\n\n\t\t# def print(self):\n\t\t# \tfor ind, contour in enumerate(self.contourList):\n\t\t# \t\tprint('contour[', ind, ']')\n\t\t# \t\tcontour.print()\n\t\t# \t\tfor point in contour.pointList:\n\t\t# \t\t\tprint(point.toxml('utf-8'))\n\t\t# \t\tprint(' ')\n\t\t\t\n\tdef changeCoordinate(pointList):\n\t\tdistance = abs(int(pointList[0].attributes['y'].value) - int(pointList[1].attributes['y'].value))\n\t\tfor point in pointList:\n\t\t\tx = int(point.getAttribute('x'))\n\t\t\tpoint.setAttribute('x', str(x + distance//2))\n\n\t# have to detect line : 14, curve : 2\n\tglifList = []\n\tdirPath = path + '/glyphs'\n\n\tfor fileName in os.listdir(dirPath):\n\t\tif fileName.endswith('.glif') and fileName.startswith('cid'):\n\t\t\tif fileName in ['cid6335.glif', 'cid6352.glif', 'cid6412.glif', 'cid6519.glif', 'cid6833.glif', 'cid6897.glif', 'cid6918.glif', 'cid7281.glif', 'cid7327.glif']:\n\t\t\t\tg = Glif(dirPath, fileName)\n\t\t\t\tglifList.append(g)\n\n\tfor g in glifList:\n\t\tprint(g.fileName)\n\t\ttarContour = g.getTargetContour()\n\t\tif tarContour is None:\n\t\t\t# print(g.fileName + ' has no target contour')\n\t\t\tcontinue\n\t\ttarPointList = tarContour.getTargetPoint()\n\t\tinnerPointList = tarContour.getInnerPointList(tarPointList)\n\t\touterPointList = [point for point in tarContour.pointList if point not in innerPointList]\n\n\t\toutline = g.xmldoc.getElementsByTagName('outline')[0]\n\t\t\n\t\t# innerContour = copy.deepcopy(tarContour.contour)\n\t\t# outerContour = copy.deepcopy(tarContour.contour)\n\t\tinnerContour = tarContour.contour.cloneNode(True)\n\t\touterContour = tarContour.contour.cloneNode(True)\n\n\t\tfor point1 in outerPointList:\n\t\t\tfor point2 in innerContour.getElementsByTagName('point'):\n\t\t\t\tif point1.toxml() == point2.toxml():\n\t\t\t\t\tinnerContour.removeChild(point2)\n\n\t\tfor point1 in innerContour.getElementsByTagName('point'):\n\t\t\tfor point2 in outerContour.getElementsByTagName('point'):\n\t\t\t\tif point1.toxml() == point2.toxml():\n\t\t\t\t\touterContour.removeChild(point2)\n\n\t\tind = []\n\t\tfor index, point in enumerate(outerContour.getElementsByTagName('point')):\n\t\t\tfor point2 in tarPointList:\n\t\t\t\tif point.toxml() == point2.toxml():\n\t\t\t\t\tind.append(index)\n\t\t\t\n\t\tchangeCoordinate([outerContour.getElementsByTagName('point')[ind[0]], outerContour.getElementsByTagName('point')[ind[1]]])\n\n\t\toutline.removeChild(tarContour.contour)\n\t\toutline.appendChild(innerContour)\n\t\toutline.appendChild(outerContour)\n\n\t\tf = open(dirPath + '/' + g.fileName, 'w')\n\t\txmlcontent = g.xmldoc.toprettyxml()\n\t\txmlcontentList = xmlcontent.split('\\n')\n\n\t\tfor xmlcontent in xmlcontentList:\n\t\t\tif xmlcontent.isspace() == True:\n\t\t\t\tcontinue\n\t\t\telse:\n\t\t\t\tf.write(xmlcontent + '\\n')\n\t\tf.close()\n\n\n","sub_path":"newMetaFontHandler_chinese.roboFontExt/lib/splitContour.py","file_name":"splitContour.py","file_ext":"py","file_size_in_byte":5206,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"201412257","text":"import numpy as np\nfrom numpy import linalg as LA\n\nclass Node(object):\n\tdef __init__(self, Node_arr=None):\n\t\t\n\t\tif Node_arr == None:\n\t\t\tNode_arr = []\n\t\tself.__Node_arr = Node_arr\n\tdef add_vertex(self, nodeid, w=1.0):\n\t\t#if node not in self.__Node_arr:\n\t\tself.__Node_arr.append([nodeid,w])\n\tdef get_nachbarn(self):\n\t\treturn self.__Node_arr\n\t\n\t\n\t\n\t\nclass Graph(object):\n\t\n\tdef __init__(self, n=0, Node_arr=None):\n\t\t\n\t\tif Node_arr == None:\n\t\t\tNode_arr = []\n\t\t\tfor i in range(n):\n\t\t\t\tc1 = Node()\n\t\t\t\tc1.set_name(str(i))\n\t\t\t\tNode_arr.append(c1)\n\t\t\t\n\t\tself.__Node_arr = Node_arr\n\t\tself.__dic = {}\n\t\tself.__n = 0\n\n\t\n\n\tdef add_Node(self, node, name=None):\n\t\t\n\t\tn = self.__n\n\t\tif(name==None):\n\t\t\tname = str(n)\n\t\tself.__dic[name] = n\n\t\tself.__dic[n] = name\n\t\tself.__Node_arr.append(node)\n\t\t\n\t\t#print(self.__dic)\n\t\tself.__n += 1\n\tdef add_edge(self, node1, node2, w=1.0):\n\t\t\n\t\tv1 = None\n\t\tv2 = None\n\t\tif(type(node1)==int):\n\t\t\tv1 = self.__Node_arr[node1]\n\t\telse:#str\n\t\t\tnode1 = self.__dic[node1]\n\t\t\tv1 = self.__Node_arr[node1]\n\t\tif(type(node2)==int):\n\t\t\tv2 = self.__Node_arr[node2]\n\t\telse:\n\t\t\tnode2 = self.__dic[node2]\n\t\t\tv2 = self.__Node_arr[node2]\n\t\t\n\t\tv1.add_vertex(node2,w)\n\t\tv2.add_vertex(node1,w)\n\tdef __str__(self):\n\t\tres = \"\"\n\t\t\n\t\tfor k in enumerate(self.__Node_arr):#Nur nodes\n\t\t\tres += \"Kanten von \"+self.__dic[k[0]] + \" nach\\n\"\n\t\t\t\n\t\t\t\n\t\t\tfor j in k[1].get_nachbarn():#Tuple of nodes and w\n\t\t\t\t\n\t\t\t\tres += self.__dic[j[0]]+\" (\"+str(j[1])+\"), \"\n\t\t\t\t\n\t\t\tres += \"\\n\"\n\t\t\n\t\treturn res\t\n\n\tdef getw(self, i, j):\n\t\tr = 0.\n\t\tv = self.__Node_arr[i]\n\t\tn = v.get_nachbarn()\n\t\tfor x in n:#alle node nachbarn gucken\n\t\t\tif(x[0] == j):\n\t\t\t\tr = x[1]\n\t\t\t\treturn r\n\t\t\n\t\t#print(r)\n\t\treturn r\n\tdef len_n(self):\n\t\treturn len(self.__Node_arr)\n\tdef dic(self):\n\t\treturn self.__dic\n\ndef randplaces(le, mx):\n\tres = np.random.permutation(mx)\n\t#print(res[0: le])\n\treturn res[0: le]\ndef randplaces2(items, a):\n\ttmp = np.zeros(a*a, dtype=np.int32).reshape(a, a)\n\tplaces = []\n\tl = len(items)\n\t'''Random placement'''\n\tfor i in range(l):\n\t\t\n\t\tk = np.random.randint(a*a-i)\n\t\t#print(k)\n\t\tj = 0\n\t\tit = np.nditer(tmp, flags=['multi_index'], op_flags=['writeonly'])\n\t\twhile not it.finished:\n\t\t\t#print \"%d <%s>\" % (it[0], it.multi_index),\n\t\t\t\n\t\t\tif(it[0] == 0):\n\t\t\t\tif(j==k):\n\t\t\t\t\tit[0] = items[i]\n\t\t\t\t\t#print(a[it.multi_index])\n\t\t\t\t\tplaces.append(it.multi_index)\n\t\t\t\tj+=1\n\t\t\tit.iternext()\n\t\n\t\n\treturn places\n\t\ndef swap(t, index, x):#Mit seiten effekt\n\t\n\t#t = np.copy(places)\n\t\n\tj = -1\n\tfor h in enumerate(t):\n\t\t#print(x)\n\t\tif(h[1]==x ):\n\t\t\tj = h[0]\n\t\n\t\n\tif(j==-1):\n\t\tt[index] = x\n\telse:\n\t\t\n\t\tt[j] = t[index]\n\t\tt[index] = x\n\treturn t\n\t\n\t\n\t\ndef insert(alist, x):\n\tindex = 0\n\tl = len(alist)\n\tt = x[0]\n\tfor i in range(l):\n\t\tif(alist[i][0] area_min:\n filtered_regions.append(regions[i])\n\n left_pixels = [np.min(region.coords[:, 1]) for region in filtered_regions]\n left_pixels = np.array(left_pixels)\n left_pixels = left_pixels[left_pixels > 0.05 * binary.shape[1]]\n\n crop_right = int(0.5 * binary.shape[1] + np.min(left_pixels))\n\n return crop_right\n\n\ndef main(image_rgb, top_ruler, ax=None):\n \"\"\"Binarizes and crops properly image_rgb\n\n Arguments\n ---------\n image_rgb : 3D array\n RGB image of the entire picture\n top_ruler: integer\n Y-coordinate of the height of the ruler top edge as\n found by ruler_detection.py\n ax : obj\n If any, the result of the binarization and cropping\n will be plotted on it\n\n Returns\n -------\n bfly_bin : 2D array\n Binarized and cropped version of imge_rgb\n \"\"\"\n\n image_gray = image_rgb[:, :, 0]\n thresh_rgb = threshold_otsu(image_gray, nbins=60)\n binary = image_gray > thresh_rgb\n\n label_edge = find_tags_edge(binary, top_ruler)\n\n bfly_rgb = image_rgb[:top_ruler, :label_edge]\n bfly_hsv = color.rgb2hsv(bfly_rgb)[:, :, 1]\n rescaled = rescale_intensity(bfly_hsv, out_range=(0, 255))\n thresh_hsv = threshold_otsu(rescaled)\n bfly_bin = rescaled > thresh_hsv\n\n if ax:\n ax.set_title('Binary')\n ax.imshow(bfly_bin)\n\n return bfly_bin\n","sub_path":"butterfly/binarization.py","file_name":"binarization.py","file_ext":"py","file_size_in_byte":2551,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"638955074","text":"\"\"\"\nTPFile.py\nhttps://github.com/sam210723/COMS-1\n\nAssembles and parses xRIT Transport Files (TP_File) from multiple CP_PDUs\n\"\"\"\n\nimport os\nfrom tools import get_bits, get_bits_int\n\nclass TPFile:\n\n def __init__(self, data):\n self.data = data\n\n self.parse()\n \n\n def parse(self):\n header = self.data[:10]\n\n # Header fields\n self.COUNTER = get_bits_int(header, 0, 16, 80) # File Counter\n self.LENGTH = get_bits_int(header, 16, 64, 80) # File Length\n \n\n def start(self, data):\n \"\"\"\n Creates full TP_File data block for data to be appended to\n \"\"\"\n\n self.fullTPFile = data\n \n\n def append(self, data):\n \"\"\"\n Appends data to full TP_File data block\n \"\"\"\n\n self.fullTPFile += data\n \n\n def get_data(self):\n \"\"\"\n Returns full S_PDU contained in complete TP_File without leading header bytes\n \"\"\"\n\n return self.fullTPFile[10:]\n \n\n def print_info(self):\n \"\"\"\n Prints information about the current TP_File to the console\n \"\"\"\n\n # Get image band based on file counter\n if 1 <= self.COUNTER <= 10:\n band = \"VIS\"\n num = self.COUNTER\n elif 11 <= self.COUNTER <= 20:\n band = \"SWIR\"\n num = self.COUNTER - 10\n elif 21 <= self.COUNTER <= 30:\n band = \"WV\"\n num = self.COUNTER - 20\n elif 31 <= self.COUNTER <= 40:\n band = \"IR1\"\n num = self.COUNTER - 30\n elif 41 <= self.COUNTER <= 50:\n band = \"IR2\"\n num = self.COUNTER - 40\n else:\n band = \"Other\"\n num = \"?\"\n \n countType = \" ({}, SEGMENT: {})\".format(band, num)\n\n print(\"\\n [TP_File] COUNTER: {}{} LENGTH: {}\".format(self.COUNTER, countType, int(self.LENGTH/8)))\n","sub_path":"demux/CCSDS_TPFile.py","file_name":"CCSDS_TPFile.py","file_ext":"py","file_size_in_byte":1907,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"403036069","text":"def rchch(txt):\r\n Z=0\r\n W=0\r\n X=0\r\n G=0\r\n U=0\r\n O=0\r\n T=0\r\n F=0\r\n S=0\r\n I=0\r\n for k in txt:\r\n if k=='Z':\r\n Z+=1\r\n elif k=='W':\r\n W+=1\r\n elif k=='X':\r\n X+=1\r\n elif k=='G':\r\n G+=1\r\n elif k=='U':\r\n U+=1\r\n elif k=='O':\r\n O+=1\r\n elif k=='T':\r\n T+=1\r\n elif k=='F':\r\n F+=1\r\n elif k=='S':\r\n S+=1\r\n elif k=='I':\r\n I+=1\r\n zero=Z\r\n un=O-W-U-Z\r\n deux=W\r\n trois=T-W-G\r\n quatre=U\r\n cinq=F-U\r\n six=X\r\n sept=S-X\r\n huit=G\r\n neuf=I-huit-six-cinq\r\n return([zero,un,deux,trois,quatre,cinq,six,sept,huit,neuf])\r\n \r\ndef main():\r\n ifn='A-large.in'\r\n ofn='output.txt'\r\n f=open(ifn,'r',encoding='utf-8')\r\n g=open(ofn,'w')\r\n nb_val=int(f.readline().strip())\r\n for k in range(nb_val):\r\n g.write(\"Case #%d: \" %(k+1))\r\n txt=f.readline().strip()\r\n S=rchch(txt)\r\n g.write(\"0\"*S[0])\r\n g.write(\"1\"*S[1])\r\n g.write(\"2\"*S[2])\r\n g.write(\"3\"*S[3])\r\n g.write(\"4\"*S[4])\r\n g.write(\"5\"*S[5])\r\n g.write(\"6\"*S[6])\r\n g.write(\"7\"*S[7])\r\n g.write(\"8\"*S[8])\r\n g.write(\"9\"*S[9])\r\n g.write('\\n')\r\n f.close()\r\n g.close()\r\n return('Fin')\r\n ","sub_path":"codes/CodeJamCrawler/CJ_16_2/16_2_1_hoenaime_Pb1.py","file_name":"16_2_1_hoenaime_Pb1.py","file_ext":"py","file_size_in_byte":1366,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"515959249","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\nimport sys\n\nfrom sqlalchemy.sql import select\n\nfrom qsdatacenter.settings import *\n\nlogger = logging.getLogger(__name__)\n\n\ndef transmit_all(tablename, prefix):\n conn_dest = ENGINE_RDB.connect()\n conn_dest.execute('DELETE FROM %s%s ' % (prefix, tablename))\n logger.info(\n 'All data deleted in Table %s%s in engine %s, .' % (prefix, tablename, str(ENGINE_RDB)))\n\n metadata_src = sa.MetaData(bind=ENGINE_JY)\n metadata_src.reflect(bind=ENGINE_JY, only=[tablename])\n tbl_src = metadata_src.tables.get(tablename)\n tbl_stat = select([tbl_src])\n\n metadata_dest = sa.MetaData(bind=ENGINE_RDB)\n metadata_dest.reflect(bind=ENGINE_RDB, only=[(prefix + tablename).lower()])\n tbl_dest = metadata_dest.tables.get((prefix + tablename).lower())\n\n tbl_dest_ins = tbl_dest.insert()\n\n conn_src = ENGINE_JY.connect()\n result = conn_src.execute(tbl_stat)\n items = result.fetchmany(1000)\n rowcounts = 0\n while len(items) > 0:\n rowcounts += len(items)\n conn_dest.execute(tbl_dest_ins, [item for item in items])\n items = result.fetchmany(1000)\n logger.info(\n '%s rows inserted into Table %s in engine %s, .' % (rowcounts, tablename, str(ENGINE_RDB)))\n\n\nif __name__ == '__main__':\n PREFIX = 'ODS_JY_'\n if len(sys.argv) <= 1:\n logger.info('Usage: python replace_table_mssql2oracle.py tablename')\n exit(1)\n tablenames = sys.argv[1:]\n available_src = ENGINE_JY.table_names(None, connection=ENGINE_JY.connect())\n available_src = [item.lower() for item in available_src]\n available_dest = ENGINE_RDB.table_names(SCHEMA_RDB, connection=ENGINE_RDB.connect())\n available_dest = [item.lower() for item in available_dest]\n\n for t in tablenames:\n prefix = PREFIX\n if len(PREFIX) + len(t) > 30:\n prefix = PREFIX[:30 - len(t)]\n logger.info('Processing ' + t)\n if t.lower() not in available_src or (prefix + t).lower() not in available_dest:\n logger.error('Table %s not found, please check.' % t)\n exit(1)\n transmit_all(t, prefix)\n","sub_path":"qsdatacenter/datamodel/tools/replace_table_mssql2oracle.py","file_name":"replace_table_mssql2oracle.py","file_ext":"py","file_size_in_byte":2126,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"637712369","text":"import base64\nimport platform\nimport sys\nfrom threading import Timer\n\nimport requests\n\ntry: # py3\n import urllib.parse as urlparse\nexcept: # py2\n import urlparse\n\n\nclass RestClient(object):\n def __init__(self, client_id, client_secret, server):\n self.client_id = client_id\n self.client_secret = client_secret\n self.server = server\n self._token = None\n self._timer = None\n self.auto_refresh = False\n self.debug = False\n\n @property\n def token(self):\n return self._token\n\n @token.setter\n def token(self, value):\n self._token = value\n if self._timer:\n self._timer.cancel()\n self._timer = None\n if self.auto_refresh and value:\n self._timer = Timer(value['expires_in'] - 120, self.refresh)\n\n self._timer.start()\n\n def authorize(self,\n username=None,\n extension=None,\n password=None,\n auth_code=None,\n redirect_uri=None):\n if auth_code:\n data = {\n 'grant_type': 'authorization_code',\n 'code': auth_code,\n 'redirect_uri': redirect_uri,\n }\n else:\n data = {\n 'grant_type': 'password',\n 'username': username,\n 'extension': extension,\n 'password': password,\n }\n r = self.post('/restapi/oauth/token', data=data)\n self.token = r.json()\n return r\n\n def refresh(self):\n if self.token is None:\n return\n data = {\n 'grant_type': 'refresh_token',\n 'refresh_token': self.token['refresh_token'],\n }\n self.token = None\n r = self.post('/restapi/oauth/token', data=data)\n self.token = r.json()\n return r\n\n def revoke(self):\n '''\n Revokes access/refresh token.\n Requests to this endpoint must be authenticated with HTTP Basic scheme\n using client ID and client secret as login and password, correspondingly.\n '''\n if self.token is None:\n return None\n data = {'token': self.token['access_token']}\n self.token = None\n return self.post('/restapi/oauth/revoke', data=data)\n\n def authorize_uri(self, redirect_uri, state=''):\n '''\n TODO: why i need this?\n The authorization code is obtained by using an authorization server as an\n intermediary between the client and resource owner.\n Returns link to a login page location.\n Web applications are higly advised to use the Proof Key for\n Code Exchange scheme (PKCE) for security concerns.\n '''\n url = urlparse.urljoin(self.server, '/restapi/oauth/authorize')\n params = {\n 'response_type': 'code',\n 'state': state,\n 'redirect_uri': redirect_uri,\n 'client_id': self.client_id\n }\n req = requests.PreparedRequest()\n req.prepare_url(url, params=params)\n return req.url\n\n def get(self, endpoint, params=None):\n return self._request('GET', endpoint, params)\n\n def post(self, *args, **kwargs):\n return self._request('POST', *args, **kwargs)\n\n def put(self, *args, **kwargs):\n return self._request('PUT', *args, **kwargs)\n\n def patch(self, *args, **kwargs):\n return self._request('PATCH', *args, **kwargs)\n\n def delete(self, endpoint, params=None):\n return self._request('DELETE', endpoint, params)\n\n def _autorization_header(self):\n if self.token:\n return 'Bearer {access_token}'.format(\n access_token=self.token['access_token'])\n return 'Basic {basic_key}'.format(basic_key=self._basic_key())\n\n def _basic_key(self):\n return base64.b64encode('{client_id}:{client_secret}'.format(\n client_id=self.client_id,\n client_secret=self.client_secret).encode('utf-8')).decode('utf-8')\n\n def _request(self,\n method,\n endpoint,\n params=None,\n json=None,\n data=None,\n files=None,\n multipart_mixed=False):\n url = urlparse.urljoin(self.server, endpoint)\n user_agent_header = '{name} Python {major_lang_version}.{minor_lang_version} {platform}'.format(\n name='RCV DevOps RC SDK',\n major_lang_version=sys.version_info[0],\n minor_lang_version=sys.version_info[1],\n platform=platform.platform(),\n )\n headers = {\n 'Authorization': self._autorization_header(),\n 'User-Agent': user_agent_header,\n 'RC-User-Agent': user_agent_header,\n 'X-User-Agent': user_agent_header,\n }\n req = requests.Request(method,\n url,\n params=params,\n data=data,\n json=json,\n files=files,\n headers=headers)\n prepared = req.prepare()\n if multipart_mixed:\n prepared.headers['Content-Type'] = prepared.headers[\n 'Content-Type'].replace('multipart/form-data;',\n 'multipart/mixed;')\n if self.debug:\n pretty_print_POST(prepared)\n s = requests.Session()\n r = s.send(prepared)\n try:\n r.raise_for_status()\n except:\n raise Exception(\n 'HTTP Status: {s} RCRequestId\\n{h} Body: {t}'.format(\n s=r.status_code,\n t=r.text,\n h=r.headers.get('RCRequestId', None)))\n return r\n\n\n# Blow is for debugging:\n\n\ndef pretty_print_POST(req):\n \"\"\"\n At this point it is completely built and ready\n to be fired; it is \"prepared\".\n\n However pay attention at the formatting used in\n this function because it is programmed to be pretty\n printed and may differ from the actual request.\n \"\"\"\n print('{}\\n{}\\n{}\\n\\n{}'.format(\n '-----------START-----------',\n req.method + ' ' + req.url,\n '\\n'.join('{}: {}'.format(k, v) for k, v in req.headers.items()),\n req.body,\n ))\n","sub_path":"rc_python/rest_client.py","file_name":"rest_client.py","file_ext":"py","file_size_in_byte":6385,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"327959413","text":"from .serializers import TaskSeriaizer, ProjectSerializer, TasksReprioritizeSerializer\nfrom rest_framework import status, viewsets\nfrom rest_framework.decorators import action\nfrom rest_framework.response import Response\nfrom .models import Project, Task\nfrom rest_framework.authtoken.models import Token\nfrom rest_framework.permissions import IsAuthenticated\nfrom django_filters.rest_framework import OrderingFilter\n\n\nclass ProjectViewSet(viewsets.ModelViewSet):\n permission_classes = [IsAuthenticated]\n\n serializer_class = ProjectSerializer\n task_serializer_class = TaskSeriaizer\n reprioritaze_serializer_class = TasksReprioritizeSerializer\n\n def get_queryset(self):\n token = self.request.META.get('HTTP_AUTHORIZATION').split(' ')[1]\n\n user = Token.objects.get(key=token).user\n\n queryset = Project.objects.filter(owner=user)\n\n return queryset\n\n def get_serializer_class(self):\n if self.action == 'create_task':\n return self.task_serializer_class\n elif self.action == 'move_task':\n return self.reprioritaze_serializer_class\n else:\n return super(ProjectViewSet, self).get_serializer_class()\n\n @action(detail=True, methods=['post'])\n def create_task(self, request, pk=None):\n serializer = self.get_serializer_class()(data=request.data, context={'request': request})\n\n if not serializer.is_valid():\n return Response(status=status.HTTP_400_BAD_REQUEST)\n\n project = self.get_object()\n\n serializer.save()\n\n task = serializer.instance\n task.priority = len(project.tasks.all())\n\n task.save()\n\n project.tasks.add(task)\n\n data = self.serializer_class(instance=project, context={'request': request}).data\n\n self.sort_tasks(data)\n\n return Response(data=data, status=status.HTTP_200_OK)\n\n def sort_tasks(self, project):\n project['tasks'] = sorted(project['tasks'], key=lambda task: task['priority'])\n\n def sort_projects_tasks(self, projects):\n for project in projects:\n self.sort_tasks(project)\n\n def list(self, request):\n response = super(ProjectViewSet, self).list(request)\n\n if response.status_code != status.HTTP_200_OK:\n return response\n\n data = response.data\n\n self.sort_projects_tasks(data)\n\n response.data = data\n\n return response\n\n def retrieve(self, request, pk=None):\n response = super(ProjectViewSet, self).retrieve(request, pk)\n\n if response.status_code != status.HTTP_200_OK:\n return response\n\n data = response.data\n\n self.sort_tasks(data)\n\n response.data = data\n\n return response\n\n def perform_create(self, serializer):\n token = self.request.META.get('HTTP_AUTHORIZATION').split(' ')[1]\n\n user = Token.objects.get(key=token).user\n\n serializer.save(owner=user)\n\n @action(detail=True, methods=['post'])\n def move_task(self, request, pk=None):\n serializer = self.get_serializer_class()(data=self.request.data)\n\n if not serializer.is_valid():\n return Response(status=status.HTTP_400_BAD_REQUEST)\n\n priority = serializer.data['index']\n up = serializer.data['up']\n\n project = self.get_object()\n tasks = project.tasks.order_by('priority').all()\n\n from_task = tasks[priority]\n to_task = None\n\n if up and priority > 0:\n to_task = tasks[priority - 1]\n elif not up and priority < len(tasks) - 1:\n to_task = tasks[priority + 1]\n\n if to_task != None:\n temp = from_task.priority\n from_task.priority = to_task.priority\n to_task.priority = temp\n\n to_task.save()\n from_task.save()\n\n data = self.serializer_class(instance=project, context={'request': request}).data\n\n self.sort_tasks(data)\n\n return Response(data=data, status=status.HTTP_200_OK)\n\nclass TaskViewSet(viewsets.ModelViewSet):\n permission_classes = [IsAuthenticated]\n\n serializer_class = TaskSeriaizer\n queryset = Task.objects.all()\n\n def destroy(self, request, pk=None):\n task = self.get_object()\n\n project = task.project_set.first()\n\n response = super(TaskViewSet, self).destroy(request, pk)\n\n tasks = project.tasks.order_by('priority').all()\n\n for index in range(len(tasks)):\n tasks[index].priority = index\n tasks[index].save()\n\n return response","sub_path":"list_server/list_todo/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4524,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"302810872","text":"from PySide2 import QtWidgets, QtGui\r\n\r\nCUSTOM_FONT = QtGui.QFont()\r\nCUSTOM_FONT.setPointSize(14)\r\n\r\nclass BoutonCustom(QtWidgets.QPushButton):\r\n\r\n\tdef __init__(self, texte):\r\n\t\tsuper(BoutonCustom, self).__init__(texte)\r\n\r\n\t\tself.setFont(CUSTOM_FONT)\r\n\t\tself.setStyleSheet('QPushButton:hover {color: rgb(100, 200, 130);}')\r\n\r\n","sub_path":"calculatrice/pyside2/custom_ui/boutonCustom.py","file_name":"boutonCustom.py","file_ext":"py","file_size_in_byte":326,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"180752422","text":"from orm.services.image_manager.ims.persistency.wsme import models\nfrom orm.tests.unit.ims import FunctionalTest\n\nimport mock\n\nGROUP_REGIONS = [\n \"DPK\",\n \"SNA1\",\n \"SNA2\"\n]\n\n\nclass TestModels(FunctionalTest):\n\n def setUp(self):\n FunctionalTest.setUp(self)\n models.get_regions_of_group = mock.MagicMock(return_value=GROUP_REGIONS)\n models.set_utils_conf = mock.MagicMock()\n\n def test_handle_group_success(self):\n image = get_image_model()\n image.handle_region_group()\n\n self.assertEqual(len(image.regions), 3)\n\n def test_handle_group_not_found(self):\n models.get_regions_of_group = mock.MagicMock(return_value=None)\n image = get_image_model()\n\n self.assertRaises(models.ErrorStatus, image.handle_region_group,)\n\n\nclass TestWsmeModels(FunctionalTest):\n def test_create_image_visibility(self):\n image_wrapper = models.ImageWrapper()\n image_wrapper.image = models.Image()\n\n image_wrapper.image.name = 'name'\n image_wrapper.image.url = 'http://aic.att.com'\n image_wrapper.image.visibility = 'private'\n image_wrapper.image.disk_format = 'raw'\n image_wrapper.image.container_format = 'bare'\n image_wrapper.image.min_ram = 1024\n image_wrapper.image.customers = ['a1', 'a2']\n\n sql_image = image_wrapper.validate_model()\n\n self.assertEqual(len(image_wrapper.image.customers), 2)\n\n\ndef get_image_model():\n \"\"\"this function create a customer model object for testing\n :return: new customer object\n \"\"\"\n\n image = models.Image(id='a', regions=[models.Region(name='r1', type='group')])\n\n return image\n","sub_path":"orm/tests/unit/ims/test_models.py","file_name":"test_models.py","file_ext":"py","file_size_in_byte":1661,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"30576000","text":"import Task2Functions\r\nimport pprint\r\n\r\nroot_path = \"./Data\"\r\n\r\n########################################################################################################################\r\n# Step 1 - Parse contents of stations.xml\r\n########################################################################################################################\r\n\r\nstep1_path = root_path + '/Stations/stations.xml'\r\n# print(step1_path)\r\n# Get list of stations and assign to a dictionary\r\ndict_stations = Task2Functions.parse_stations_xml(step1_path)\r\n# print(\"Station Dictionary:\\t {}\".format(dict_stations))\r\n\r\n\r\n########################################################################################################################\r\n# Step 2 - Parse contents of JourneyTimes directory\r\n# Step 3 - Process JourneyTimes data into a usable structure\r\n########################################################################################################################\r\n\r\n\r\n# 2.1 - Get list of .xml files in a directory\r\nstep2_path = root_path + \"/JourneyTimes/\"\r\nlist_xml_files = Task2Functions.step2_1_get_list_xml_files(step2_path)\r\n\r\n# 2.2 - Get route details for all tube lines, returned as a single dictionary for later processing\r\n# dict_journeytimes = Task2Functions.parse_journeytimes_into_dict(list_xml_files, path) # !! Function withdrawn !!\r\n# print(\"JourneyTimes Dictionary:\\t {}\".format(dict_journeytimes))\r\n\r\ndict_all_lines = {} # Stores a dictionary of lines in format {from: {to: time}\r\ndict_lines_journey_times = {} # Stores a dictionary of journey times in format {from: {to: time, to: time, ...}}\r\ntemp_list_stations = [] # Stores a list of stations on line in route order\r\n\r\nfor file in list_xml_files:\r\n file_path = step2_path + file # Create full path to a .xml file to pass to process_xml_file()\r\n # print(file_path)\r\n file = file.split('.')[0] # Removes the .xml part of the file by splitting on . and keeping first part of file\r\n file = Task2Functions.format_string(file)\r\n # Run function and assign result to temp_returned_tuple, then assign the returned values to required dictionaries\r\n temp_returned_tuple = Task2Functions.step2_2_process_xml_file(file_path)\r\n dict_all_lines[file] = temp_returned_tuple[0]\r\n temp_list_stations = temp_returned_tuple[1]\r\n # print(dict_all_lines[file])\r\n # print(temp_list_stations)\r\n\r\n # 3.1 - Generate journey times\r\n dict_lines_journey_times[file] = Task2Functions.step3_generate_journey_times(temp_list_stations\r\n , dict_all_lines[file])\r\n # print(dict_lines_journey_times[file])\r\n # break # used for debugging to stop after the first file\r\n# print(dict_lines_journey_times.keys())\r\n# print(dict_lines_journey_times['Bakerloo'])\r\n# print(dict_all_lines)\r\n# pprint.pprint(dict_lines_journey_times)\r\n\r\n\r\n########################################################################################################################\r\n# Step 4 - Parse JSON file\r\n########################################################################################################################\r\n\r\n\r\nstep4_path = root_path + '/JSON/'\r\n# Get JSON data using function and place into a list. Format is data will be [{}, {...}]\r\njson_data = Task2Functions.parse_json(step4_path)\r\n# print(json_data)\r\n# pprint.pprint(json_data)\r\n\r\n\r\n########################################################################################################################\r\n# Step 5 - Enrich data\r\n########################################################################################################################\r\n\r\nprint(\"Length of json data: {}\".format(json_data.__len__()))\r\n\r\nenriched_json_data = Task2Functions.step5_enrich_data(json_data, dict_stations, dict_lines_journey_times)\r\n\r\nprint(\"\\nLength of json data: {}\".format(json_data.__len__()))\r\nprint(\"Length of enriched data: {}\".format(enriched_json_data.__len__()))\r\n\r\n\r\n########################################################################################################################\r\n# Step 6 - Calculate the route of each package\r\n########################################################################################################################\r\n\r\n\r\n########################################################################################################################\r\n# Step 7 - - Generate the output\r\n########################################################################################################################\r\n","sub_path":"Task2Main.py","file_name":"Task2Main.py","file_ext":"py","file_size_in_byte":4567,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"64016600","text":"import numpy as np\nimport numpy\nimport scipy\nfrom skimage import io\nfrom scipy.misc import imread\nimport sys\nfrom PIL import Image\n\nim = io.imread(\"spotdetection_testgel.gif\")\nnew_im=io.imread(\"watershed_init_255.gif\")\n\nthreshold = 200\n\n#threshold = 150\n\n#for i in im:\n# print(i)\n\ndata = numpy.asarray(im)\n#for i in data:\n# print(i)\n\n\nwith Image.open(\"spotdetection_testgel.gif\") as im:\n width, height = im.size\n\nfor i in range(height):\n for j in range(width):\n if data[i][j] > threshold:\n data[i][j] = 255\n\n else:\n continue\n\nio.imsave(\"newimage.gif\", data)\n\nold_im=io.imread(\"newimage.gif\")\nnew_im=io.imread(\"watershed_init_255.gif\")\n\nprint(\"hello\")\n\ndata = numpy.asarray(old_im)\ndata_new = numpy.asarray(new_im)\n#for i in data:\n# print(i)\n\n\nwith Image.open(\"spotdetection_testgel.gif\") as im:\n width, height = im.size\n\nfor i in range(height):\n for j in range(width):\n if data[i][j] == 255:\n data_new[i][j] = 255\n else:\n continue\n\nnr_spots = np.unique(data_new)\nprint(len(nr_spots))\n\t\t\t\nio.imsave(\"newimage_watershed.gif\", data_new)\n\n\nprint(\"hello\")\n","sub_path":"Mini-project---computational-Proteomics/miniproject.py","file_name":"miniproject.py","file_ext":"py","file_size_in_byte":1144,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"353693165","text":"import numpy as np\n\n\n# para (bs) X sentences X words\ndef sentence_classifier_generator(fp, batch_size, max_sentence_len, output_size):\n batch_X = []\n batch_Y = []\n max_paragraph_len = 0\n paragraph_len = 0\n sequence_lengths = np.zeros(batch_size, dtype=np.int32)\n X = []\n Y = []\n count = 0\n for line in fp:\n if line == \"\\n\":\n sequence_lengths[count] = len(X)\n batch_X.append(X)\n batch_Y.append(Y)\n X = []\n Y = []\n count += 1\n max_paragraph_len = max(max_paragraph_len, paragraph_len)\n if count >= batch_size:\n for i in range(count):\n for j in range(max_paragraph_len-sequence_lengths[i]):\n batch_X[i].append([0]*max_sentence_len)\n y = np.zeros((output_size,))\n y[0] = 1\n batch_Y[i].append(y)\n yield np.array(batch_X, dtype=np.int32), np.array(batch_Y, dtype=np.int32), sequence_lengths, max_paragraph_len\n batch_X = []\n batch_Y = []\n max_paragraph_len = 0\n paragraph_len = 0\n sequence_lengths = np.zeros(batch_size, dtype=np.int32)\n X = []\n Y = []\n count = 0\n else:\n row = line.split('\\t')\n X.append([int(i) for i in row[0].split(',')])\n y = np.zeros((output_size,))\n y[int(row[1])] = 1\n Y.append(y)\n paragraph_len += 1\n\n if count < batch_size and count > 0 and sequence_lengths[0] > 0:\n for i in range(count):\n for j in range(max_paragraph_len - sequence_lengths[i]):\n batch_X[i].append([0] * max_sentence_len)\n y = np.zeros((output_size,))\n y[0] = 1\n batch_Y[i].append(y)\n batch_X = np.concatenate((np.array(batch_X, dtype=np.int32), np.zeros((batch_size - count, max_paragraph_len, max_sentence_len))), axis=0)\n y = np.zeros((batch_size - count, max_paragraph_len, output_size))\n y[:,:,0] = 1\n batch_Y = np.concatenate((np.array(batch_Y, dtype=np.int32), y), axis=0)\n yield np.array(batch_X, dtype=np.int32), np.array(batch_Y, dtype=np.int32), sequence_lengths, max_paragraph_len\n","sub_path":"model/generator.py","file_name":"generator.py","file_ext":"py","file_size_in_byte":2354,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"63549281","text":"class Solution:\n def findErrorNums(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: List[int]\n \"\"\"\n S = len(nums)* (len(nums)+1) // 2\n N = sum(nums)\n L = sum(set(nums))\n return [N-L,S-L]\n\n\nprint(Solution().findErrorNums([2, 3, 2]))\n","sub_path":"leet_code/645#set_mismatch.py","file_name":"645#set_mismatch.py","file_ext":"py","file_size_in_byte":292,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"533954185","text":"import firebase_admin\nfrom firebase_admin import credentials, messaging\n\ncred = credentials.Certificate(\"serviceAccountKey.json\")\nfirebase_admin.initialize_app(cred)\n\ndef sendPush (title, msg, registration_token, dataObject=None):\n message=messaging.MulticastMessage(\n notification=messaging.Notification(\n title=title,\n body=msg\n ),\n data=dataObject,\n token=registration_token,\n )\n\n response = messaging.send_multicast(message)\n\n print('successfully sent message:', response)\n","sub_path":"ShopWala/ShopWala/FCMManager.py","file_name":"FCMManager.py","file_ext":"py","file_size_in_byte":539,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"424389425","text":"#!/usr/bin/env python\n# coding:utf-8\nimport paramiko\n\nprivate_key = paramiko.RSAKey.from_private_key_file('/home/sun/.ssh/id_rsa')\n\ntransport = paramiko.Transport(('172.20.22.165', 59488))\ntransport.connect(username='is_develop', pkey=private_key)\n\nsftp = paramiko.SFTPClient.from_transport(transport)\n# 将location.py 上传至服务器 /tmp/test.py\nsftp.put('/tmp/location.py', '/tmp/test2.py')\n# 将remove_path 下载到本地 local_path\nsftp.get('/tmp/sbt223617161030205056.log', '/tmp/sbt2.log')\n\ntransport.close()","sub_path":"day9/sftp_key.py","file_name":"sftp_key.py","file_ext":"py","file_size_in_byte":519,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"354385101","text":"from kivy.clock import Clock\nfrom kivy.uix.label import Label\n\nimport PiAlarmClock.config.config as cfg\n\n\n#status labels for Settings page which update based on state of their corresponding checkbox\nclass SmartSleepStatusLabel(Label):\n def __init__(self, **kwargs):\n super(SmartSleepStatusLabel, self).__init__(**kwargs)\n self.text = \"[color=f44253]Disabled[/color]\"\n self.markup = True\n Clock.schedule_interval(self.update, 0.2)\n\n def update(self, *args):\n if cfg.SMART_SLEEP == 0:\n self.text = \"[color=f44253]Disabled[/color]\"\n else:\n self.text = \"[color=42f445]Enabled[/color]\"\n\n\n","sub_path":"src/PiAlarmClock/components/sleep.py","file_name":"sleep.py","file_ext":"py","file_size_in_byte":653,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"398548271","text":"#1.\n# try:\n# n = input('请输入一个数字:')\n# find = float(n)\n# if('.' not in n):\n# # print(\"少侠,你输入的是个整数: \",int(n),\",对不对?!\")\n# n = int(n)\n# if(n%3==0):\n# print('是3的倍数')\n# else:\n# print('不是3的倍数') \n# else:\n# print(\"少侠,你输入的是个浮点数: \",float(n),\",哈哈,被小甲虫猜中了吧?!\")\n# except ValueError:\n# print('请输入数字')\n\n#2.\n# try:\n# n = input('请输入一个数字:')\n# find = float(n)\n# if('.' not in n):\n# # print(\"少侠,你输入的是个整数: \",int(n),\",对不对?!\")\n# m = int(n)\n# if m>=0 and m<100:\n# c = '6'\n# if c in n:\n# print('包含6')\n# else:\n# print('不包含6')\n# else:\n# print('请输入两位以内的数字')\n# else:\n# print(\"少侠,你输入的是个浮点数: \",float(n),\",哈哈,被小甲虫猜中了吧?!\")\n# except ValueError:\n# print('请输入数字')\n\n#3.\n# try:\n# ly = input('请输入一个年份:')\n# find = float(ly)\n# if('.' not in ly):\n# # print(\"少侠,你输入的是个整数: \",int(n),\",对不对?!\")\n# m = int(ly)\n# if m%100!=0 and(m%4==0 or m%100==0):\n# print('您输入的年份是闰年')\n# else:\n# print('您输入的年份不是闰年')\n# else:\n# print(\"少侠,你输入的是个浮点数: \",float(ly),\",哈哈,被小甲虫猜中了吧?!\")\n# except ValueError:\n# print('请输入数字')\n\n#4.\n# print(1 + 10 * 2 / 2 - 5)\n# #10*2/2+1-5\n# print(3.0 / 5)\n# #3.0/5\n# print(3.0 // 5)\n# #\n# print('a' * 10)\n# #打印10次a\n# print(True + 3)\n# #1+3\n# print(False + 3)\n# #0+3\n# print('1' > 'A')\n# #ASCII码的大小规则:0~9 1)\n# #字符和汉字不能比较\n\n#5.\n# try:\n# n = input('请输入一个数字:')\n# find = float(n)\n# if('.' not in n):\n# # print(\"少侠,你输���的是个整数: \",int(n),\",对不对?!\")\n# m = int(n)\n# if m==0 or (m%2==0 and m>0):\n# print('该数字为偶数')\n# else:\n# print('该数不是偶数')\n# else:\n# print(\"少侠,你输入的是个浮点数: \",float(n),\",哈哈,被小甲虫猜中了吧?!\")\n# except ValueError:\n# print('请输入数字')\n\n#6.\n# try:\n# n = input('请输入一个数字:')\n# find = float(n)\n# if('.' not in n):\n# # print(\"少侠,你输入的是个整数: \",int(n),\",对不对?!\")\n# m = int(n)\n# if m>=18:\n# print('成年')\n# elif m< 18 and m>0:\n# print('未成年')\n# else:\n# print('年龄不能小于0')\n# else:\n# print(\"少侠,你输入的是个浮点数: \",float(n),\",哈哈,被小甲虫猜中了吧?!\")\n# except ValueError:\n# print('请输入数字')\n\n#7.\n# height = 1.75\n# weight = 80\n# BMI = weight/(height**2)\n# if BMI< 18.5:\n# print('过轻')\n# elif 18.5<=BMI<25:\n# print('正常')\n# elif 25<=BMI<28:\n# print('过重')\n# elif 28<=BMI<=32:\n# print('肥胖')\n# elif BMI>32:\n# print('严重肥胖')\n#8.\n# try:\n# n = input('请输入身高:')\n# find = float(n)\n# # print(\"少侠,你输入的是个整数: \",int(n),\",对不对?!\")\n \n# if 0.43)\n# print(1==3)\n\n\n# accept = int(input('请输入你想输入的数字:'))\n# num = 50\n# if accept == num:\n# print('right')\n# elif accept < num:\n# print('small')\n# else:\n# print('more')\n\n# n = 1\n# while n < 10:\n# print(n)\n# n = n + 1\n\nimport pymysql.cursors\nconnection = pymysql.connect(host='192.168.0.27',\n user='root',\n password='123456',\n db='ice',\n charset='utf8mb4',\n cursorclass=pymysql.cursors.DictCursor)\nprint(connection)\nprint(connection,connection.cursor())\ntry:\n with connection.cursor() as cursor:\n # Read a single record\n sql = \"SELECT `balance` FROM `account` WHERE `id`=%s\"\n cursor.execute(sql, (1))\n result = cursor.fetchone()\n balance = result['balance']\n money = int(input('请输入取款金额:'))\n if money%100!=0:\n print('对不起,本机器无法提供输入的面额')\n else:\n if money > balance:\n print('余额不足')\n else:\n balance = balance - money\n print('正在出钞,您的账户余额:{}'.format(balance))\n with connection.cursor() as cursor:\n # Create a new record\n sql = \"update `account` set `balance` = %s where id = 1\"\n cursor.execute(sql, (balance))\n result = cursor.fetchone()\n # connection is not autocommit by default. So you must commit to save\n # your changes..\n connection.commit()\nfinally:\n connection.close()\n\n","sub_path":"test_2019_10_09/a.py","file_name":"a.py","file_ext":"py","file_size_in_byte":6029,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"192838083","text":"# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License.\nimport random, datetime\n\nprint(\"Creating task manager.\")\n\nclass TaskManager:\n def __init__(self):\n self.status_dict = {}\n\n def GetTaskId(self):\n id = str(random.randint(1, 10000))\n while id in self.status_dict:\n id = str(random.randint(1, 10000))\n return id\n\n def AddTask(self, request):\n id = self.GetTaskId() \n self.status_dict[id] = ('created', datetime.datetime.strftime(datetime.datetime.now(), \"%Y-%m-%d %H:%M:%S\"), 'task')\n\n ret = {}\n ret['TaskId'] = id\n ret['Status'] = self.status_dict[id][0]\n ret['Timestamp'] = self.status_dict[id][1]\n ret['Endpoint'] = self.status_dict[id][2]\n return(ret)\n\n def UpdateTaskStatus(self, taskId, status):\n if (taskId in self.status_dict):\n stat = self.status_dict[taskId]\n self.status_dict[taskId] = (status, stat[1], stat[2])\n else:\n self.status_dict[taskId] = (status, stat[1], stat[2])\n\n def AddPipelineTask(self, taskId, organization_moniker, version, api_name, body):\n next_url = organization_moniker + '/' + version + '/' + api_name\n self.UpdateTaskStatus(taskId, \"Pipelining is not supported in a single node deployment, but the next service is: \" + next_url)\n return \"Pipelining is not supported in a single node deployment, but the next service is: \" + next_url\n\n def CompleteTask(self, taskId, status):\n self.UpdateTaskStatus(taskId, status)\n\n def FailTask(self, taskId, status):\n self.UpdateTaskStatus(taskId, status)\n\n def GetTaskStatus(self, taskId):\n try:\n if taskId in self.status_dict:\n return self.status_dict[taskId]\n else:\n return \"not found\"\n except:\n print(sys.exc_info()[0])\n","sub_path":"Containers/base-py/ai4e_api_tools/task_management/api_task.py","file_name":"api_task.py","file_ext":"py","file_size_in_byte":1919,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"371007151","text":"spellItemEnchantment_Name=0xd\ns_curMgr_NextObject=0x3c\nspellDB_spellName=0x75\nspellDB_spellRank=0x7e\ns_currentWorldFrame_AntiAFK_1=0x94\ns_curMgr_FirstObject=0xac\nCGGameObject_C__Name=0x1fc\nCGGameObject_C__Y=0x230\nCGGameObject_C__X=0x234\nCGGameObject_C__Z=0x238\nCGGameObject_C__Facing=0x23c\nCGItem_C__BuffTimes=0x320\nCGPlayer_C__Y=0xa90\nCGPlayer_C__X=0xa94\nCGPlayer_C__Z=0xa98\nCGPlayer_C__Facing=0xa9c\nCGPlayer_C__Speed=0xb04\nCGUnit_C__Name=0xc04\nCGPlayer_C__IsShootingFlag=0xd08\nCGPlayer_C__MeleeTarget=0xd58\nCGPlayer_C__CastingSpellId=0xd9c\nCGPlayer_C__ComboPoints_Ptr2=0xf31\nCGPlayer_C__ComboPoints_Ptr1=0xf78\ns_currentWorldFrame_AntiAFK_2=0x10a0\nAutoStoreAllLootItems=0x4b1f00\nCGBuffBar__m_buffs=0xb4e350\nCGBuffBar__m_durations=0xb4e238\nCGChat__AddChatMessage=0x48deb0\nCGGameUI__ClearTarget=0x487b50\nCGGameUI__LeftClick=0x486900\nCGGameUI__RightClick=0x486b50\nCGGameUI__m_lockedTarget=0xaf74b8\nCGGameUI__m_player=0xaeb5a0\nCGGameUI__s_lastErrorString=0xaf6c20\nCGInputControl__GetActive=0x4ff240\nCGInputControl__SetControlBit=0x4ffeb0\nCGLootInfo__LootSlot=0x4b2700\nCGLootInfo__m_coins=0xafc8d8\nCGLootInfo__m_loot=0xafc6a0\nCGLootInfo__m_object=0xafc880\nCGPartyInfo__m_leader=0xb4f9e8\nCGPartyInfo__m_members=0xb4f358\nCGSpellBook__m_knownSpells=0xafae78\nCGSpellBook__m_petSpells=0xaf9e20\nCGWorldFrame__RenderWorld=0x477fd0\nCGWorldMap__m_currentContinent=0x7f3790\nFrameScript_Execute=0x6e9f30\nFrameScript_RegisterFunction=0x6e9520\nNetClient__ProcessMessage=0x520420\nOsGetAsyncTimeMs=0x422430\nSpell_C_CastSpell=0x6cc7e0\nSpell_C_CastSpellByID=0x6cb980\nWOW_LOCALE_CURRENT_LANGUAGE=0xb953a4\nclientDB=0xb948ec\ng_HardwareEvent=0xc791e0\ng_SpellDB=0xb94b38\ng_SpellDBTotalRows=0xb94b3c\ng_charClasses=0xb95218\ng_charClassesCount=0xb9521c\ng_charRaces=0xb95204\ng_charRacesCount=0xb95208\ng_factionDB=0xb95074\ng_factionGroupDB=0xb95060\ng_gameObjectDisplayInfoDB=0xb9501c\ng_itemDBCache=0xb955c4\ng_nameDBCache=0xb9554c\ng_slotNames=0xb94d9c\ng_slotNamesCount=0xb94da0\ng_spellItemEnchantment=0xb94b80\nluaState=0xc737ac\nlua_gettop=0x6d96a0\nlua_tostring=0x6d9bc0\ns_containerDescriptors=0xaec8d0\ns_corpseDescriptors=0xaec290\ns_corpsePosition=0xaf7464\ns_curMgr=0xaeab94\ns_currentWorldFrame=0xaf4620\ns_dynamicObjectDescriptors=0xaec5a0\ns_gameObjectDescriptors=0xaec6f0\ns_itemDescriptors=0xaf41b0\ns_objDescriptors=0xaf4590\ns_playerDescriptors=0xaed260\ns_unitDescriptors=0xaf3188\n","sub_path":"oldprogs/wowbot-backup/offsets1.9.4.py","file_name":"offsets1.9.4.py","file_ext":"py","file_size_in_byte":2350,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"631839183","text":"# # this implementation has quadratic time complexity\n# def twosum(arr, target):\n# for i in range(len(arr)):\n# for j in range(len(arr)):\n# if (i != j) and (arr[i] + arr[j] == target):\n# return [i, j]\n# this implementation has linear time complexity\n\ndef twosum(arr, target):\n dictionary = {}\n for i in range(len(arr)):\n diff = str(target - arr[i])\n dictionary[diff] = i\n for j in range(len(arr)):\n value = str(arr[j])\n if dictionary.has_key(value) and j != dictionary[value]:\n return [j, dictionary[value]]\nprint(twosum([11, 2, 7, 15], 9))\nprint(twosum([11, 5, 7, 3, 15], 10))","sub_path":"two_sum.py","file_name":"two_sum.py","file_ext":"py","file_size_in_byte":616,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"230376391","text":"class Solution:\n def longestCommonPrefix(self, strs: List[str]) -> str: \n if len(strs) < 1:\n return \"\"\n \n # first word is assumed as the longest prefix until comparisons to the other strings\n lcp = strs[0]\n \n for i in range(1,len(strs)):\n compare = strs[i]\n \n # compare current longest common prefix with each subsequent string\n for j in range(len(lcp)):\n if j >= len(compare) or lcp[j] != compare[j]:\n lcp = lcp[:j]\n break \n return lcp","sub_path":"week-1/string-manipulation/LongestCommonPrefix.py","file_name":"LongestCommonPrefix.py","file_ext":"py","file_size_in_byte":606,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"377315599","text":"import os\n\nimport torch\nfrom torch import nn, optim\nfrom torch.autograd.variable import Variable\nfrom torchvision import transforms, datasets\nimport torch.nn as nn\nfrom experiments.image_generation.utils import Logger\n\n#\tmnist data\n# def mnist_data():\n# , transforms.Normalize((.5, .5, .5), (.5,.5,.5))\ncompose = transforms.Compose([transforms.ToTensor()])\nout_dir = './dataset'\ndata = datasets.CIFAR10(root=out_dir, train=True, transform=compose, download=True)\n\n# Load data\n# data = mnist_data()\n# Create loader with data, so that we can iterate over it\ndata_loader = torch.utils.data.DataLoader(data, batch_size=100, shuffle=True)\n# Num batches\nnum_batches = len(data_loader)\n\n# data_transform = transforms.Compose([\n# \t# transforms.RandomResizedCrop(224),\n# \t# transforms.RandomHorizontalFlip(),\n# \ttransforms.ToTensor(),\n# \t# transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])\n# ])\n# hymenoptera_dataset = datasets.ImageFolder(root='../dataset/extra_data', transform=data_transform)\n# print(len(hymenoptera_dataset))\n# data_loader = torch.utils.data.DataLoader(hymenoptera_dataset, batch_size=128, shuffle=True, num_workers=4)\n# # Num batches\n# num_batches = len(data_loader)\n\n\nn_features = 3 * 64 * 64\nn_channels = 3\nwidth = 64\nheight = 64\nn_out = 1\nn_noise = 100\nclip = 0.01\n\ndevice = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\nD_PATH = 'models/vgan/anime_d.pth'\nG_PATH = 'models/vgan/anime_g.pth'\n\n\n# custom weights initialization called on netG and netD\ndef weights_init(m):\n\tclassname = m.__class__.__name__\n\tif classname.find('Conv') != -1:\n\t\tnn.init.normal_(m.weight.data, 0.0, 0.02)\n\telif classname.find('BatchNorm') != -1:\n\t\tnn.init.normal_(m.weight.data, 1.0, 0.02)\n\t\tnn.init.constant_(m.bias.data, 0)\n\n\nclass DiscriminatorNet(nn.Module):\n\t\"\"\"\n\tA three hidden-layer discriminative neural network\n\t\"\"\"\n\n\tdef __init__(self):\n\t\tsuper(DiscriminatorNet, self).__init__()\n\t\t# n_features = 784\n\t\t# n_out = 1\n\n\t\tself.hidden0 = nn.Sequential(\n\t\t\tnn.Conv2d(3, 64, 3, stride=2, padding=1, ),\n\t\t\tnn.LeakyReLU(0.2),\n\t\t\t# nn.MaxPool2d(2, 2)\n\t\t)\n\n\t\tself.hidden1 = nn.Sequential(\n\t\t\tnn.Conv2d(64, 128, 3, stride=2, padding=1),\n\t\t\tnn.BatchNorm2d(128),\n\t\t\tnn.LeakyReLU(0.2),\n\t\t\t# nn.MaxPool2d(2, 2)\n\t\t)\n\n\t\tself.hidden2 = nn.Sequential(\n\t\t\tnn.Conv2d(128, 256, 3, stride=2, padding=1),\n\t\t\tnn.BatchNorm2d(256),\n\t\t\tnn.LeakyReLU(0.2),\n\t\t\t# nn.MaxPool2d(2, 2, ceil_mode=True)\n\t\t)\n\n\t\t# self.hidden3 = nn.Sequential(\n\t\t# \tnn.Conv2d(256, 512, 3, stride=2, padding=1),\n\t\t# \tnn.BatchNorm2d(512),\n\t\t# \tnn.LeakyReLU(0.2),\n\t\t# \t# nn.MaxPool2d(2, 2, ceil_mode=True)\n\t\t# )\n\n\t\tself.out = nn.Sequential(\n\t\t\t# nn.Conv2d(256, 1, 4, padding=0),\n\t\t\tnn.Linear(256 * 4 * 4 + 10, n_out),\n\t\t\t# nn.Conv2d(512, 1, 5, stride=2, padding=1),\n\t\t\t# nn.BatchNorm1d(n_out),\n\n\t\t\t# in wgan, should not use sigmoid\n\t\t\tnn.Sigmoid()\n\t\t)\n\n\tdef forward(self, x, y):\n\t\t\"\"\"\n\t\tinput 3*64*64\n\t\t:param x:\n\t\t:return:\n\t\t\"\"\"\n\t\tx = self.hidden0(x)\n\t\tx = self.hidden1(x)\n\t\tx = self.hidden2(x)\n\t\t# x = self.hidden3(x)\n\n\t\tx = x.view(-1, 256 * 4 * 4)\n\t\tx = torch.cat((x, y), 1)\n\n\t\tx = self.out(x)\n\t\treturn x\n\n\ndiscriminator = DiscriminatorNet()\n\n# # load model\n# if os.path.isfile(D_PATH):\n# \tdiscriminator.load_state_dict(torch.load(D_PATH))\ndiscriminator.to(device)\ndiscriminator.apply(weights_init)\n\n\ndef images_to_vectors(images):\n\treturn images.view(images.size(0), n_features)\n\n\ndef vectors_to_images(vectors):\n\treturn vectors.view(vectors.size(0), n_channels, width, height)\n\n\nclass GeneratorNet(nn.Module):\n\t\"\"\"\n\tA three hidden-layer generative neural network\n\t\"\"\"\n\n\tdef __init__(self):\n\t\tsuper(GeneratorNet, self).__init__()\n\t\t# n_features = 100\n\t\t# n_out = 784\n\n\t\t# self.hidden0 = nn.Sequential(\n\t\t# \tnn.Linear(n_noise, 4 * 4 * 1024),\n\t\t# \tnn.BatchNorm1d(4 * 4 * 1024),\n\t\t# \tnn.ReLU()\n\t\t# )\n\n\t\tself.hidden0 = nn.Sequential(\n\t\t\tnn.ConvTranspose2d(110, 512, 4, 1, 0),\n\t\t\tnn.BatchNorm2d(512),\n\t\t\tnn.ReLU()\n\t\t)\n\n\t\tself.hidden1 = nn.Sequential(\n\t\t\tnn.ConvTranspose2d(512, 256, 4, 2, 1),\n\t\t\tnn.BatchNorm2d(256),\n\t\t\tnn.ReLU()\n\t\t)\n\n\t\tself.hidden2 = nn.Sequential(\n\t\t\tnn.ConvTranspose2d(256, 128, 4, 2, 1),\n\t\t\tnn.BatchNorm2d(128),\n\t\t\tnn.ReLU()\n\t\t)\n\n\t\tself.out = nn.Sequential(\n\t\t\tnn.ConvTranspose2d(128, 3, 4, 2, 1),\n\t\t\t# nn.BatchNorm2d(64),\n\t\t\tnn.Tanh()\n\t\t)\n\n\t# self.out = nn.Sequential(\n\t# \tnn.ConvTranspose2d(64, 3, 4, 2, 1),\n\t# \tnn.Tanh()\n\t# )\n\n\tdef forward(self, x):\n\t\tx = x.view(-1, 110, 1, 1)\n\t\tx = self.hidden0(x)\n\n\t\tx = self.hidden1(x)\n\t\tx = self.hidden2(x)\n\t\t# x = self.hidden3(x)\n\t\tx = self.out(x)\n\n\t\treturn x\n\n\ngenerator = GeneratorNet()\n#\n# if os.path.isfile(G_PATH):\n# \tgenerator.load_state_dict(torch.load(G_PATH))\n\ngenerator.to(device)\ngenerator.apply(weights_init)\n\n\ndef noise(size):\n\t\"\"\"\n\tGenerates a 1-d vector of gaussian sampled random values\n\t\"\"\"\n\t# n = Variable(torch.randn(size, 100))\n\tn = torch.randn((size, 100), requires_grad=True).to(device)\n\t# n = torch.randn((size, 100, 1, 1), requires_grad=True).to(device)\n\t# n = torch.randn((size, 100), requires_grad=True).to(device)\n\treturn n\n\n\nd_optimizer = optim.RMSprop(discriminator.parameters(), lr=0.0002)\ng_optimizer = optim.RMSprop(generator.parameters(), lr=0.0002)\n\n\ndef train_discriminator(optimizer, real_data, fake_data, y):\n\tN = real_data.size(0)\n\t# Reset gradients\n\toptimizer.zero_grad()\n\n\t# 1.1 Train on Real Data\n\tprediction_real = discriminator(real_data, y)\n\t# Calculate error and backpropagate\n\t# error_real = loss(prediction_real, ones_target(N))\n\t# error_real.backward()\n\n\t# 1.2 Train on Fake Data\n\t# fake_data = fake_data.view(-1, 3, 64, 64)\n\tprediction_fake = discriminator(fake_data, y)\n\t# Calculate error and backpropagate\n\t# error_fake = loss(prediction_fake, zeros_target(N))\n\t# error_fake.backward()\n\n\tD_loss = -(torch.mean(prediction_real) - torch.mean(prediction_fake))\n\tD_loss.backward()\n\n\t# 1.3 Update weights with gradients\n\toptimizer.step()\n\n\t# weight(gradient) clipping\n\t# # torch.clamp_(discriminator.parameters(), min=-clip, max=clip)\n\t# w = discriminator.weight.data\n\t# w = w.clamp(-clip, clip)\n\t# discriminator.weight.data = w\n\n\tfor p in discriminator.parameters():\n\t\tp.data.clamp_(-clip, clip)\n\n\t# Return error and predictions for real and fake inputs\n\t# return error_real + error_fake, prediction_real, prediction_fake\n\treturn D_loss, prediction_real, prediction_fake\n\n\ndef train_generator(optimizer, fake_data, y):\n\tN = fake_data.size(0)\n\n\t# Reset gradients\n\toptimizer.zero_grad()\n\n\t# Sample noise and generate fake data\n\tprediction = discriminator(fake_data, y)\n\n\t# Calculate error and backpropagate\n\t# error = loss(prediction, ones_target(N))\n\tG_loss = -torch.mean(prediction)\n\n\tG_loss.backward()\n\n\t# Update weights with gradients\n\toptimizer.step()\n\n\t# Return error\n\treturn G_loss\n\n\nnum_test_samples = 16\ntest_noise = noise(num_test_samples)\ntest_condition = torch.randint(10, (num_test_samples,)).to(device)\ntest_labels = torch.zeros(num_test_samples, 10).to(device)\ntest_labels[torch.arange(num_test_samples), test_condition] = 1\n\ntest_z_y = torch.cat((test_noise, test_labels), 1).to(device)\n\n# Create logger instance\nlogger = Logger(model_name='cGAN', data_name='cifar')\n\n# Total number of epochs to train\nnum_epochs = 2000\nfor epoch in range(num_epochs):\n\tfor n_batch, samples in enumerate(data_loader):\n\t\t(real_batch, real_labels) = samples\n\t\treal_batch = real_batch.to(device)\n\t\treal_labels = real_labels.to(device)\n\t\tN = real_batch.size(0)\n\n\t\t# 0. change to one-hot encoding\n\t\tone_hot = torch.zeros(N, 10).to(device)\n\t\tone_hot[torch.arange(N).to(device), real_labels] = 1\n\t\t# one_hot.to(device)\n\n\t\t# 1. Train Discriminator\n\t\t# real_data = images_to_vectors(real_batch)\n\n\t\t# Generate fake data and detach (so gradients are not calculated for generator)\n\t\tz = noise(N)\n\t\tz_y = torch.cat((z, one_hot), 1).to(device)\n\t\ty = one_hot\n\t\tfake_data = generator(z_y).detach()\n\n\t\t# Train D\n\t\td_error, d_pred_real, d_pred_fake = train_discriminator(d_optimizer, real_batch, fake_data, y)\n\n\t\t# 2. Train Generator\n\t\t# Generate fake data\n\t\tfake_data = generator(z_y)\n\n\t\t# Train G\n\t\tg_error = train_generator(g_optimizer, fake_data, y)\n\n\t\t# Log batch error\n\t\tlogger.log(d_error, g_error, epoch, n_batch, num_batches)\n\n\t\t# Display Progress every few batches\n\t\tif n_batch % 100 == 0:\n\t\t\t# test_images = vectors_to_images(generator(test_z_y))\n\t\t\ttest_images = generator(test_z_y).data\n\t\t\tlogger.log_images(test_images.cpu(), num_test_samples, epoch, n_batch, num_batches)\n\n\t\t\t# Display status Logs\n\t\t\tlogger.display_status(epoch, num_epochs, n_batch, num_batches, d_error, g_error, d_pred_real, d_pred_fake)\n#\n# # save model every 100 epoch\n# if epoch % 10 == 0:\n# \ttorch.save(discriminator.state_dict(), D_PATH)\n# \ttorch.save(generator.state_dict(), G_PATH)\n","sub_path":"experiments/image_generation/gans/cgan.py","file_name":"cgan.py","file_ext":"py","file_size_in_byte":8649,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"621054449","text":"#!/usr/bin/env python\n\nimport atexit\nimport json\nimport re\nimport sys\nimport time\nimport zmq\nfrom daemon import Daemon\nfrom persistent_dict import PersistentDict\n\n\nclass BrainDaemon(Daemon):\n def init_store(self):\n self.logger.info(\"initializing data store\")\n try:\n self.store = PersistentDict(self.savefile, 'c', format='json')\n self.store['laststart'] = time.time()\n except Exception as e:\n self.logger.error(\"initialization failed: {}\".format(e),\n exc_info=True)\n sys.exit(2)\n\n def init_sock(self):\n self.logger.info(\"initializing command socket\")\n try:\n context = zmq.Context.instance()\n\n self.sock = context.socket(zmq.REP)\n self.sock.bind('tcp://*:9000')\n except Exception as e:\n self.logger.error(\"command socket initialization failed: {}\".format(e),\n exc_info=True)\n sys.exit(3)\n\n def init_parser(self):\n self.parser = re.compile(\"^set (\\S+)\\s*=\\s*(\\S.*)\")\n\n def handle_msg(self, message):\n self.logger.debug(\"msg received: {} eom\".format(message))\n # set default response\n response = \"Unrecognized command: {}\".format(message)\n if message == \"quit\":\n self.sock.send(\"goodbye!\")\n self.shutdown()\n return \"shutting down.\"\n if message == \"save\":\n self.store.sync()\n response = \"saved!\"\n if message.startswith(\"get \"):\n response = json.dumps(self.store[message.split(\" \")[1]])\n if message.startswith(\"set \"):\n m = self.parser.search(message)\n if m:\n (k, v) = m.groups()\n try:\n self.store[k ] = json.loads(v)\n response = \"ok.\"\n except:\n response = \"failed to set {} = {}\".format(k,v)\n return response\n\n def shutdown(self):\n self.store.sync()\n self.stop()\n\n def run(self):\n self.logger.info(\"initializing run routine\")\n self.init_store()\n self.init_sock()\n self.init_parser()\n self.logger.info(\"braindaemon initialized\")\n self.logger.debug(\"sock object: {}\".format(self.sock))\n while True:\n try:\n message = self.sock.recv()\n response = self.handle_msg(message)\n self.sock.send(response)\n except Exception as e:\n self.logger.warning(\"problem in receive loop: {}\".format(e), exc_info=True)\n","sub_path":"mudbrain/braindaemon.py","file_name":"braindaemon.py","file_ext":"py","file_size_in_byte":2607,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"552004530","text":"import itertools\nimport numbertheory\n\ndef contfracE():\n yield 2\n n = 1\n while True:\n yield 1\n yield 2 * n\n yield 1\n n += 1\n\na = str(numbertheory.contfrac2real(list(itertools.islice(contfracE(), 100)))[0])\nprint(sum(list(map(int, (x for x in a)))))\n","sub_path":"p065.py","file_name":"p065.py","file_ext":"py","file_size_in_byte":285,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"557266048","text":"from selenium import webdriver\nimport time\nimport os\nif 'HTTP_PROXY' in os.environ: del os.environ['HTTP_PROXY']\n\n\ndriver = webdriver.Chrome()\nfile_path = 'file:///' + os.path.abspath('status.html')\ndriver.get(file_path)\ndriver.implicitly_wait(10)\n\ntext_field = driver.find_element_by_name('user')\nprint(text_field.is_enabled())\n\n# 直接用enabled方法去判断button的话返回的会是True\n# 这是因为button是用css方法disabled的,并不是真正的disable\n# 这时需要判断class里是否有disabled这个值来判断其是否出disable状态\nprint(driver.find_element_by_name('bnt').is_enabled())\n\n# 隐藏掉text_field\n# 判断其是否显示\ndriver.execute_script('$(arguments[0]).hide()', text_field)\nprint(text_field.is_displayed())\n\n# 使用click方法选择radio\nradio = driver.find_element_by_name('radio')\nradio.click()\nprint(radio.is_selecter())\n\n# 判断元素存在\ntry:\n driver.find_element_by_id('none')\nexcept:\n print(\"element is not exist\")\n\ndriver.quit()","sub_path":"21status.py","file_name":"21status.py","file_ext":"py","file_size_in_byte":993,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"91663043","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n# This script is for collecting data on vision controller CPU performance. Originally used for evaluating performance between 1-controller vs. 2-controller system\n\nimport sys\nimport argparse\nimport time\n\nimport psutil\nimport numpy as np\n\nimport cpuTestUtilities\nfrom cpuTestUtilities import SyncTestWithControllerClient, SyncTestWithControllerServer\n\nimport logging\nlog = logging.getLogger(__name__)\n\n\ndef ConfigureLogging(logLevel=logging.DEBUG, outputStream=sys.stderr):\n handler = logging.StreamHandler(outputStream)\n try:\n import logutils.colorize\n handler = logutils.colorize.ColorizingStreamHandler(outputStream)\n handler.level_map[logging.DEBUG] = (None, 'green', False)\n handler.level_map[logging.INFO] = (None, None, False)\n handler.level_map[logging.WARNING] = (None, 'yellow', False)\n handler.level_map[logging.ERROR] = (None, 'red', False)\n handler.level_map[logging.CRITICAL] = ('white', 'magenta', True)\n except ImportError:\n pass\n handler.setFormatter(logging.Formatter('%(asctime)s %(name)s [%(levelname)s] [%(filename)s:%(lineno)s %(funcName)s] %(message)s'))\n handler.setLevel(logLevel)\n\n root = logging.getLogger()\n root.setLevel(logLevel)\n root.handlers = []\n root.addHandler(handler)\n\n\ndef WriteDataSaveGraphData(**kwargs):\n # Configuration\n num_total_cpu = kwargs['num_total_cpu']\n num_physical_cpu = kwargs['num_physical_cpu']\n min_cpu_freq = kwargs['min_cpu_freq']\n max_cpu_freq = kwargs['max_cpu_freq']\n\n # Collected data\n total_cpu_percent = np.array(kwargs['total_cpu_percent'])\n per_cpu_percent = np.array(kwargs['per_cpu_percent'])\n total_cpu_freq = np.array(kwargs['total_cpu_freq'])\n per_cpu_freq = np.array(kwargs['per_cpu_freq'])\n per_cpu_temp = np.array(kwargs['per_cpu_temp'])\n total_context_switches = kwargs['total_context_switches']\n\n # Process CPU affinities\n detection_cpu_affinity = kwargs['detection_cpu_affinity']\n\n #####################\n # WRITE TO FILE\n #####################\n\n # Write configuration\n file = open('Vision_Controller_Results.txt', 'w')\n\n # Write configuration\n configurations = {'num_total_cpu': num_total_cpu, 'num_physical_cpu': num_physical_cpu, 'min_cpu_freq': min_cpu_freq, 'max_cpu_freq': max_cpu_freq}\n cpuTestUtilities.WriteConfigurations(file, **configurations)\n\n # Write collected data\n cpuTestUtilities.ComputeStatisticsAndWriteToFile(file, 'TOTAL CPU USAGE', '%' , total_cpu_percent)\n cpuTestUtilities.ComputeStatisticsAndWriteToFile(file, 'INDIVIDUAL USAGE CPU', '%', per_cpu_percent)\n cpuTestUtilities.ComputeStatisticsAndWriteToFile(file, 'TOTAL CPU FREQUENCY', 'Mhz', total_cpu_freq)\n cpuTestUtilities.ComputeStatisticsAndWriteToFile(file, 'INDIVIDUAL FREQUENCY CPU', 'MHz', per_cpu_freq)\n cpuTestUtilities.ComputeStatisticsAndWriteToFile(file, 'INDIVIDUAL TEMPERATURE CPU', 'deg (Celsius)', per_cpu_temp)\n cpuTestUtilities.WriteGeneralData(file, 'TOTAL CPU CONTEXT SWITCHING', total_context_switches)\n\n # Write process CPU affinities\n cpuTestUtilities.WriteGeneralData(file, 'DETECTION PROCESS CPU AFFINITY', detection_cpu_affinity)\n\n file.close()\n\n ##########################\n # SAVE ARRAYS FOR PLOTTING\n ##########################\n\n # Plot CPU usage and frequency as function of time and save figures\n np.save('Total_CPU_Usage_Data', total_cpu_percent)\n np.save('Per_CPU_Usage_Data', per_cpu_percent)\n np.save('Total_CPU_Freq_Data', total_cpu_freq)\n np.save('Per_CPU_Freq_Data', per_cpu_freq)\n np.save('Per_CPU_Temp_Data', per_cpu_temp)\n\n\ndef main():\n\n ####################\n # MEASUREMENTS\n ####################\n\n # Number of CPUs\n num_total_cpu = psutil.cpu_count() # Total CPU count (physical and virtual)\n num_physical_cpu = psutil.cpu_count(logical=False) # Physical CPU count\n min_cpu_freq = psutil.cpu_freq().min # Minimum operating frequency\n max_cpu_freq = psutil.cpu_freq().max # Maximum operating frequency\n\n # Overall motion controller CPU percent usage\n \n # Ignore first value. See documentation on usage\n psutil.cpu_percent() \n psutil.cpu_percent(percpu=True)\n\n total_cpu_percent = list() # Total CPU usage \n per_cpu_percent = list() # Per CPU usage\n\n # Real time CPU frequency\n total_cpu_freq = list() # Real time CPU frequency\n per_cpu_freq = list() # Real time per CPU frequency\n\n per_cpu_temp = list() # CPU temperature\n\n total_context_switches = 0 # Total number of context switches\n\n # Resource heavy processes for monitoring\n detection_cpu_affinity = [p.cpu_affinity() for p in psutil.process_iter() if 'mujin_detectors_runvisionmanager' in p.as_dict(attrs=['pid', 'name'])['name']]\n\n ######################\n # INFRASTRUCTURE SETUP\n ######################\n\n parser = argparse.ArgumentParser(description='Script for collecting vision controller data')\n parser.add_argument('-p', '--port', action='store', type=int, dest='serverPort', default=24001, help='Port for vision controller server process')\n parser.add_argument('-s', '--seconds', action='store', type=int, dest='samplingRate', default=5, help='Sample frequency: Number of seconds per sample')\n options = parser.parse_args()\n\n ConfigureLogging()\n\n # Create server to listen for start event\n log.warn('Starting vision server...')\n visionControllerServer = SyncTestWithControllerServer(options.serverPort)\n visionControllerServer.Start() # Spin off thread to listen for start and stop events from motion controller\n log.warn('Created vision server!')\n\n # Wait for start data collection event\n log.warn('Vision server listening for start collection event!')\n while visionControllerServer.ShouldRun() is not True:\n continue\n log.warn('Starting data collection on vision controller!')\n\n\n ####################\n # DATA COLLECTION\n ####################\n\n # Start measuring context switches\n contextSwitchesStart = psutil.cpu_stats().ctx_switches\n\n # Waits for client to set to False (production cycles finished running)\n lastSample = time.time()\n sampleInterval = options.samplingRate\n while visionControllerServer.ShouldRun() is not False:\n if time.time() - lastSample < sampleInterval: \n total_cpu_percent.append(psutil.cpu_percent())\n per_cpu_percent.append(psutil.cpu_percent(percpu=True))\n total_cpu_freq.append(psutil.cpu_freq().current)\n per_cpu_freq.append([cpuFreq.current for cpuFreq in psutil.cpu_freq(percpu=True)])\n per_cpu_temp.append(psutil.sensors_temperatures()['coretemp'][1:(num_total_cpu+1)])\n lastSample = time.time()\n continue\n \n # Stop measuring context switches\n total_context_switches = psutil.cpu_stats().ctx_switches -contextSwitchesStart\n\n log.warn('Stopping data collection on vision controller and stopping vision controller server...')\n visionControllerServer.Stop()\n log.warn('Stopped vision controller server!')\n\n #####################################\n # WRITE DATA TO FILES AND SAVE GRAPHS\n #####################################\n\n log.warn('Writing vision controller data...')\n\n # Data\n kwargs = \\\n { \\\n 'num_total_cpu': num_total_cpu, \\\n 'num_physical_cpu': num_physical_cpu, \\\n 'min_cpu_freq': min_cpu_freq, \\\n 'max_cpu_freq': max_cpu_freq, \\\n 'total_cpu_percent': total_cpu_percent, \\\n 'per_cpu_percent': per_cpu_percent, \\\n 'total_cpu_freq': total_cpu_freq, \\\n 'per_cpu_freq': per_cpu_freq, \\\n 'per_cpu_temp': per_cpu_temp, \\\n 'total_context_switches': total_context_switches, \\\n 'detection_cpu_affinity': detection_cpu_affinity \\\n }\n\n # Write to output file\n WriteDataSaveGraphData(**kwargs)\n\n log.warn('Finished writing vision controller data!')\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"python/visionControllerDataCollection.py","file_name":"visionControllerDataCollection.py","file_ext":"py","file_size_in_byte":8132,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"437972945","text":"#!/usr/bin/env python3\n\nfrom gitsrc import GITSRC, ROOT\nfrom os.path import exists, join, dirname\n\n\ndef main():\n gitmodules = \"gitmodules\"\n if exists(join(ROOT, \".\"+gitmodules)):\n return\n\n li = []\n\n with open(join(ROOT, \".direnv/%s.ini\" % gitmodules)) as f:\n for name in f:\n print(name)\n name = name.strip(\" \\n\")\n if not name:\n continue\n txt = f\"\"\"[submodule \"{name}\"]\npath = {name}\nurl = {GITSRC}/{name}.git\"\"\"\n li.append(txt)\n\n with open(join(ROOT, \".\"+gitmodules), \"w\") as out:\n out.write('\\n'.join(li))\n\n\nmain()\n","sub_path":".direnv/sh/init.py","file_name":"init.py","file_ext":"py","file_size_in_byte":562,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"519198917","text":"__author__ = 'robswift'\n\nclass Molecule:\n \"\"\"\n\tcsv molecule class\n\t\"\"\"\n\n def __init__(self):\n \"\"\"\n\t\tclass attributes\n\t\t\"\"\"\n self.id = None\n self.status = None\n self.bm = None\n self.graph = None\n self.scores = {}\n self.properties = {}\n self.tags = ('id', 'status', 'bm', 'graph')\n\n def SetProp(self, prop, value, score=None):\n \"\"\"\n\t\tset attribute\n\t\t\"\"\"\n if score:\n self.scores[prop] = value\n else:\n if prop == 'id':\n self.id = value\n elif prop == 'status':\n self.status = value\n elif prop == 'bm':\n self.bm = format(value)\n elif prop == 'graph':\n self.graph = format(value)\n else:\n self.properties[prop] = value\n\n def GetProp(self, prop):\n \"\"\"\n\t\tget attribute\n\t\t\"\"\"\n\n if prop == 'scores':\n return [x[1] for x in self.scores.items()]\n elif prop:\n if prop == 'id':\n return self.id\n elif prop == 'status':\n return self.status\n elif prop == 'bm':\n return self.bm\n elif prop == 'graph':\n return self.graph\n elif prop in self.scores.keys():\n return self.scores[prop]\n elif prop in self.properties.keys():\n return self.properties[prop]\n else:\n return None","sub_path":"EB/builder/utilities/molecules.py","file_name":"molecules.py","file_ext":"py","file_size_in_byte":1491,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"484190362","text":"class Solution:\n def missingElement(self, nums: List[int], k: int) -> int:\n l, r=0, len(nums)-1\n while l mean:\n pos = idx\n break\n # Remove emotions at the position, then reverse\n result = emo_score_list[pos + 1:]\n result.reverse()\n\n result = result[:3]\n\n return result\n\ndef process_emos(emos, mean2, token_num):\n STD_THRE = float(sys.argv[1])\n emo_score_list = break_into_list(emos)\n\n # If having only one emotion or std is below threshold,\n # no process is needed\n # Normalize using token_num\n # std = get_standard_deviation(emo_score_list) / token_num\n std = get_standard_deviation(emo_score_list)\n\n if len(emo_score_list) <= 2 or std < STD_THRE:\n return emo_score_list\n # Otherwise, process below is needed\n else:\n return remove_emotions(emo_score_list, mean2)\n\ndef calculation(in_f, mean2):\n result = []\n for line in in_f:\n line = line.strip().split('\\t')\n id_text, emos = line[:2], line[2].split(' ')\n token_num = len(id_text[1].split())\n emos_list = process_emos(emos, mean2, token_num)\n id_text.append(emos_list)\n result.append(id_text)\n return result\n\ndef create_out_file(after_mean_2, out_f):\n for each in after_mean_2:\n out_f.write(each[0] + '\\t' + each[1] + '\\t')\n for emo in each[2]:\n out_f.write(emo[0] + ':' + str(emo[1]) + ' ')\n out_f.write('\\n')\n\ndef get_after_mean_2(mean1, mean2):\n in_file, out_file = get_files(mean1, mean2)\n after_mean_2 = []\n\n with open(in_file, 'r') as in_f:\n after_mean_2 = calculation(in_f, mean2)\n\n with open(out_file, 'w+') as out_f:\n create_out_file(after_mean_2, out_f)\n\n# ATTENTION:\n# argv[1] for std threshold\nif __name__ == '__main__':\n for mean1 in range(1, 71):\n mean1 = str(float(mean1) / 10).replace('.', '_')\n for mean2 in range(1, 71):\n mean2 = str(float(mean2) / 10).replace('.', '_')\n print('Processing', mean1, mean2)\n get_after_mean_2(mean1, mean2)\n","sub_path":"src_evaluation/get_after_mean_2_second.py","file_name":"get_after_mean_2_second.py","file_ext":"py","file_size_in_byte":3640,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"235023507","text":"from tkinter import*\r\n\r\n\r\nroot = Tk() # create window\r\n\r\nroot.title(\"Job 1\") # title for window\r\nroot.geometry('300x300')\r\n\r\n# persons = [['Bill', 2, True], ['Faith', 6, False], ['Jake', 11, True], ['Louise', 15, False]]\r\n\r\nlblTest = Label(root, text=\"Start\")\r\nlblTest.grid(column=1, row=2)\r\n\r\n\r\n# button action listeners\r\ndef clickedpause():\r\n lblTest.configure(text=\"PAUSED\")\r\n\r\n\r\ndef clickedunpause():\r\n lblTest.configure(text=\"UNPAUSED\")\r\n\r\n\r\ndef clickedend():\r\n lblTest.configure(text=\"END\")\r\n\r\n\r\n# button creation\r\nbtnPause = Button(root, text=\"Pause\", fg=\"black\", bg=\"gray\", command=clickedpause, height = 1, width = 10)\r\n\r\nbtnUnPause = Button(root, text=\"Un Pause\", fg=\"black\", bg=\"gray\", command=clickedunpause, height = 1, width = 10)\r\n\r\nbtnEnd = Button(root, text=\"End\", fg=\"black\", bg=\"gray\", command=clickedend, height = 1, width = 10)\r\n\r\n# button placement\r\nbtnPause.grid(column=1, row=1)\r\n\r\nbtnUnPause.grid(column=2, row=1)\r\n\r\nbtnEnd.grid(column=3, row=1)\r\n\r\nroot.mainloop()\r\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1002,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"633735728","text":"# .remove .count 보다는 tmp list 선언 및 할당\nimport sys\ninput = sys.stdin.readline \nR, C, M = map(int,input().split())\nspace = [[[] for j in range(C)] for i in range(R)]\nshark_loc_list = []\nanswer = 0\nfor i in range(M):\n r,c,s,d,z = map(int,input().split())\n space[r-1][c-1].append((s,d,z))\n shark_loc_list.append((r-1,c-1))\ndy = [99,-1,1,0,0]\ndx = [99,0,0,1,-1]\n# shark_loc_list 없는 버전\n\ndef move(y,x):\n global space\n sh_info = space[y][x][0]\n speed = sh_info[0]\n dire = sh_info[1]\n size = sh_info[2]\n # 시간복잡도를 위한 속도 트릭\n if dire == 1 or dire == 2:\n speed = speed % (2*R-2)\n elif dire == 3 or dire == 4:\n speed = speed % (2*C-2)\n space[y][x] = [] \n\n S = 0\n while (S < speed):\n if dire == 1:\n ny = y + dy[1]\n nx = x + dx[1]\n if ny < 0:\n dire = 2\n ny = ny + dy[2]\n nx = nx + dx[2]\n S = S - 1\n elif dire == 2:\n ny = y + dy[2]\n nx = x + dx[2]\n if ny > R - 1:\n dire = 1\n ny = ny + dy[1]\n nx = nx + dx[1]\n S = S - 1\n elif dire == 3:\n ny = y + dy[3]\n nx = x + dx[3]\n if nx > C-1:\n dire = 4\n ny = ny + dy[4]\n nx = nx + dx[4]\n S = S - 1\n elif dire == 4:\n ny = y + dy[4]\n nx = x + dx[4]\n if nx < 0:\n dire = 3\n ny = ny + dy[3]\n nx = nx + dx[3]\n S = S - 1\n y = ny\n x = nx\n S = S + 1\n \n return (y,x,speed,dire,size)\n\nfor peo_loc in range(0,C):\n for capture in range(0,R):\n sh_info = space[capture][peo_loc]\n if sh_info :\n answer = answer + sh_info[0][2]\n space[capture][peo_loc] = []\n break\n \n k = []\n for i in range(R):\n for j in range(C):\n if space[i][j] :\n k.append( move(i,j) )\n \n for (y,x,s,d,z) in k:\n space[y][x].append((s,d,z))\n\n many_shark = []\n for i in range(R):\n for j in range(C):\n if len(space[i][j]) >= 2:\n many_shark.append((i,j,len(space[i][j])))\n\n for (y,x,ls) in many_shark:\n l = space[y][x]\n fight = []\n for J in range(ls):\n fight.append((l[J][2],l[J][1],l[J][0]))\n\n space[y][x] = []\n max_zmrl = max(fight)\n space[y][x].append( ( max_zmrl[2],max_zmrl[1],max_zmrl[0] ) )\n\nprint(answer)","sub_path":"BoJ/BoJ.17143(2).py","file_name":"BoJ.17143(2).py","file_ext":"py","file_size_in_byte":2615,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"537839506","text":"import logging\nimport multiprocessing.dummy as mp\nimport psycopg2 as pg\n\nimport RedditClient as rc\nfrom InterruptableThread import InterruptableThread\n\nlogger = logging.getLogger(__name__)\n\n\nclass CommentStreamProcess(InterruptableThread):\n sql_statement = \"\"\"\n INSERT INTO reddit_replies(id, author, text, subreddit, Ups, CreatedUTC, parent_id)\n SELECT %s, %s, %s, %s, %s, %s, %s\n WHERE NOT EXISTS(\n SELECT * FROM reddit_replies WHERE id = %s\n )\"\"\"\n\n def __init__(self, task: str, cursor, error_queue: mp.Queue, metrics_queue: mp.Queue, stop_event: mp.Event):\n self.task = task\n self._id = task\n self.cursor = cursor\n self._error_queue = error_queue\n self._metrics_queue = metrics_queue\n self._stop_event = stop_event\n super().__init__(target=self.run, args=())\n\n def run(self):\n logger.info(\"streaming and inserting comments from \" + self.task)\n for comment in rc.stream_subreddit_comments(self.task, self._error_queue):\n if self._stop_event.is_set() or comment == 'exception':\n logger.info(f\"{self.task} comment harvesting thread exiting\")\n # if there was an error in stream_subreddit_comments\n return # check if an exception has occurred that caused all threads to stop\n\n values = (comment.id, str(comment.author), comment.body, self.task,\n comment.score, comment.created_utc, comment.parent_id, comment.id)\n try:\n self.cursor.execute(self.sql_statement, values)\n except Exception as e:\n logger.error(\"Error on executing sql: {0}\".format(e))\n self._error_queue.put(e)\n else:\n self._metrics_queue.put('comment')\n logger.info(f\"Inserted [{comment.id}] comment from [{self.task}]\")\n\n\nclass SubmissionStreamProcess(InterruptableThread):\n sql_statement = \"\"\"\n INSERT INTO reddit_posts \n (post_id, author, subreddit, title, ups, num_comments, CreatedUTC, text, permalink) \n SELECT %s, %s, %s, %s, %s, %s, %s, %s, %s\n WHERE NOT EXISTS (\n SELECT * FROM reddit_posts WHERE post_id = %s\n )\"\"\"\n\n def __init__(self, task: str, cursor, error_queue: mp.Queue, metrics_queue: mp.Queue, stop_event: mp.Event):\n self.task = task\n self._id = task\n self.cursor = cursor\n self._error_queue = error_queue\n self._metrics_queue = metrics_queue\n self._stop_event = stop_event\n super().__init__(target=self.run, args=())\n\n def run(self):\n logger.info(\"streaming and inserting submissions from \" + self.task)\n for submission in rc.stream_subreddit_submissions(self.task, self._error_queue):\n if self._stop_event.is_set() or submission == 'exception':\n logger.info(f\"{self.task} submission harvesting thread exiting\")\n # if there was an error in stream_subreddit_comments\n return # check if an exception has occurred that caused all threads to stop\n values = (submission.id, str(submission.author), self.task, submission.title,\n submission.score, submission.num_comments, submission.created_utc, submission.selftext,\n submission.permalink, submission.id)\n try:\n self.cursor.execute(self.sql_statement, values)\n except Exception as e:\n logger.error(\"Error on executing sql: {0}\".format(e))\n self._error_queue.put(e)\n else:\n self._metrics_queue.put('submission')\n logger.info(f\"Inserted [{submission.id}] submission from [{self.task}]\")\n","sub_path":"PyWeaver/StreamProcesses.py","file_name":"StreamProcesses.py","file_ext":"py","file_size_in_byte":3806,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"32263361","text":"import os\nimport re\nimport string\nimport cPickle\nimport numpy as np\nimport pylab as pl\nimport logging as logger\nimport sklearn.metrics as smet\nfrom nltk import SnowballStemmer\nfrom sklearn.metrics import roc_curve, auc\nfrom sklearn.feature_extraction import text\nfrom sklearn.decomposition import TruncatedSVD\nfrom sklearn.datasets import fetch_20newsgroups\nfrom sklearn.preprocessing import label_binarize\nfrom sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer, TfidfTransformer\n\nlogger.basicConfig(level=logger.INFO,format='> %(message)s')\n\n# categories = ['comp.graphics', 'comp.os.ms-windows.misc', 'comp.sys.ibm.pc.hardware', 'comp.sys.mac.hardware',\n# 'rec.autos', 'rec.motorcycles', 'rec.sport.baseball', 'rec.sport.hockey']\n\ncategories = ['Computer Technology', 'Recreational Activity']\n\ndef load_dataset(category_list):\n \"\"\"\n :return: Load the 20_newsgroup dataset depending on category_list.\n If [] provided return everything\n \"\"\"\n\n if category_list == []: # read all categories from news20 dataset\n train = fetch_20newsgroups(subset='train', shuffle=True, random_state=42)\n test = fetch_20newsgroups(subset='test', shuffle=True, random_state=42)\n else: # read only computer technology & recreational activity categories\n train = fetch_20newsgroups(subset='train', shuffle=True, random_state=42, categories=category_list)\n test = fetch_20newsgroups(subset='test', shuffle=True, random_state=42, categories=category_list)\n\n return train, test\n\n\ndef clean_dataset(data, load_data=True, dataset='Train'):\n \"\"\"\n :param data: data required to be pre-processed\n :param load_data: if True check if pickle object saved on drive or not\n :param dataset: dataset being processed\n :return: pre-processed data\n \"\"\"\n\n if os.path.isfile(\"../Dataset/Pre_Processed_{0}.pkl\".format(dataset)): # load pickle file if it exists\n logger.info(\"Pre-processed Dataset located at ../Dataset/Pre_Processed_{0}.pkl. Loading.\".format(dataset))\n data = cPickle.load(open(\"../Dataset/Pre_Processed_{0}.pkl\".format(dataset), \"r\"))\n else:\n for text,pos in zip(data,range(len(data))):\n stemmed_data = preprocess_data(text) # pre-process the docs\n data[pos] = ' '.join(stemmed_data) # combine all stemmed words\n\n logger.info(\"Dumping pickle file at ../Dataset/Pre_Processed_{0}.pkl\".format(dataset))\n cPickle.dump(data,open(\"../Dataset/Pre_Processed_{0}.pkl\".format(dataset), \"wb\"))\n\n return data\n\n\ndef preprocess_data(data):\n \"\"\"\n :param data: data to be pre-processed\n :return: pre-processed data\n \"\"\"\n\n stemmer2 = SnowballStemmer(\"english\") # for removing stem words\n stop_words = text.ENGLISH_STOP_WORDS # omit stop words\n\n temp = data\n temp = re.sub(\"[,.-:/()?{}*$#&]\",\" \",temp) # remove all symbols\n temp = \"\".join([ch for ch in temp if ch not in string.punctuation]) # remove all punctuation\n temp = \"\".join(ch for ch in temp if ord(ch) < 128) # remove all non-ascii characters\n temp = temp.lower() # convert to lowercase\n words = temp.split()\n no_stop_words = [w for w in words if not w in stop_words] # stemming of words\n stemmed_data = [stemmer2.stem(plural) for plural in no_stop_words]\n\n return stemmed_data\n\n\ndef model_text_data(train, test):\n \"\"\"\n :param train: train dataset data\n :param test: test dataset data\n :return: TFxIDF Matrices for both training and testing dataset\n \"\"\"\n logger.info(\"Preprocessing dataset - Training & Testing Dataset\")\n\n train.data = clean_dataset(train.data) # training dataset\n test.data = clean_dataset(test.data,dataset='Test') # testing dataset\n\n logger.info(\"Creating TFxIDF Vector Representations\")\n\n stop_words = text.ENGLISH_STOP_WORDS # omit stop words\n\n '''\n # using TfidfVectorizer\n vectorizer = TfidfVectorizer(min_df=1, stop_words=stop_words)\n train_idf = vectorizer.fit_transform(train.data[:]) # fit pre-processed dataset to vectorizer\n test_idf = vectorizer.transform(test.data[:])\n '''\n\n # using CountVectorizer and TFxIDF Transformer\n count_vect = CountVectorizer(stop_words=stop_words, lowercase=True)\n train_counts = count_vect.fit_transform(train.data)\n test_counts = count_vect.transform(test.data)\n tfidf_transformer = TfidfTransformer(norm='l2', sublinear_tf=True)\n train_idf = tfidf_transformer.fit_transform(train_counts)\n test_idf = tfidf_transformer.transform(test_counts)\n\n\n logger.info(\"TFxIDF Matrices Created\")\n logger.info(\"Number of Terms Extracted : {}\".format(train_idf.shape[1]))\n\n return train_idf.toarray(),test_idf.toarray()\n\n\ndef apply_lsi(train_data, test_data):\n \"\"\"\n :param train_data: train dataset data\n :param test_data: testing dataset data\n :return: apply LSI on TFxIDF matrices and return transformed matrices\n \"\"\"\n\n logger.info(\"Performing LSI on TFxIDF Matrices\")\n\n if os.path.isfile(\"../Dataset/Train_LSI.pkl\") and os.path.isfile(\"../Dataset/Test_LSI.pkl\"): # load pickle file if it exists\n logger.info(\"TFxIDF Matrices located at ../Dataset. Loading.\")\n train_lsi = cPickle.load(open(\"../Dataset/Train_LSI.pkl\", \"r\"))\n test_lsi = cPickle.load(open(\"../Dataset/Test_LSI.pkl\", \"r\"))\n\n else:\n svd = TruncatedSVD(n_components=50) # LSI applied with k=50\n train_lsi = svd.fit_transform(train_data)\n test_lsi = svd.transform(test_data)\n\n logger.info(\"TFxIDF Matrices Transformed\")\n logger.info(\"Dumping TFxLSI Matrices to ../Dataset/\")\n cPickle.dump(train_lsi,open(\"../Dataset/Train_LSI.pkl\", \"wb\"))\n cPickle.dump(test_lsi,open(\"../Dataset/Test_LSI.pkl\", \"wb\"))\n\n logger.info(\"Size of Transformed Training Dataset: {0}\".format(train_lsi.shape))\n logger.info(\"Size of Transformed Testing Dataset: {0}\".format(test_lsi.shape))\n\n return train_lsi, test_lsi\n\ndef calculate_statistics(target, predicted):\n \"\"\"\n :param target: target class\n :param predicted: predicted class\n :return: statistics of classifier\n \"\"\"\n\n accuracy = smet.accuracy_score(target,predicted)\n precision = smet.precision_score(target, predicted, average='macro')\n recall = smet.recall_score(target, predicted, average='macro')\n confusion_matrix = smet.confusion_matrix(target,predicted)\n\n logger.info(\"Statistics for Classifier:\")\n logger.info(\"Accuracy : {0}\".format(accuracy * 100))\n logger.info(\"Precision : {0}\".format(precision * 100))\n logger.info(\"Recall : {0}\".format(recall * 100))\n logger.info(\"Confusion Matrix : \\n{0}\".format(confusion_matrix))\n\n return True\n\n\ndef plot_ROC(test_target, test_predicted, algo):\n \"\"\"\n :param test_target: target class numeric\n :param test_predicted: predicted class\n :param algo: classifier name\n :return: ROC curve for the given classifier and for given names\n \"\"\"\n\n logger.info(\"ROC Curve for Categories: {}\".format(categories))\n # compute ROC curve and ROC area for each class\n fpr = dict()\n tpr = dict()\n roc_auc = dict()\n\n fpr, tpr, _ = roc_curve(test_target, test_predicted)\n roc_auc = auc(fpr, tpr)\n\n # plot curve\n pl.figure(1)\n pl.plot(fpr, tpr, label='ROC curve(area = {0:0.4f})'\n ''.format(roc_auc))\n\n pl.plot([0, 1], [0, 1], 'k--')\n pl.xlim([0.0, 1.0])\n pl.ylim([0.0, 1.05])\n pl.xlabel('False Positive Rate')\n pl.ylabel('True Positive Rate')\n pl.title('ROC Curves for {0} Classifier'.format(algo))\n pl.legend(loc=\"lower right\")\n pl.show()\n\n return True\n","sub_path":"Project 2 - Classification Analysis/Scripts/utility.py","file_name":"utility.py","file_ext":"py","file_size_in_byte":7626,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"398170439","text":"# Copyright (c) 2021 - present / Neuralmagic, Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"\nCode related to managing jobs in the server\n\"\"\"\n\nimport logging\nimport threading\nfrom typing import Union\n\nfrom sparseml.utils import Singleton\nfrom sparsify.models import Job, JobStatus, database\nfrom sparsify.workers.base import JobWorkerRegistryHolder\nfrom sparsify.workers.base_wrapper import JobWorkerWrapper\n\n\n__all__ = [\"JobNotFoundError\", \"JobCancelationFailureError\", \"JobWorkerManager\"]\n\n\n_LOGGER = logging.getLogger(__name__)\n\n\nclass JobNotFoundError(Exception):\n \"\"\"\n Error raised if a job is not found in the database\n \"\"\"\n\n def __init__(self, *args: object) -> None:\n super().__init__(*args)\n\n\nclass JobCancelationFailureError(Exception):\n \"\"\"\n Error raised if a job could not be canceled\n \"\"\"\n\n def __init__(self, *args: object) -> None:\n super().__init__(*args)\n\n\nclass JobWorkerManager(object, metaclass=Singleton):\n \"\"\"\n Manager class for handling running job workers in the background.\n Only one job worker can run at once.\n Once one completes, the next oldest one marked as pending in the db is launched.\n \"\"\"\n\n def __init__(self):\n self._lock = threading.Lock()\n self._current = None # type: Union[None, JobWorkerWrapper]\n\n def app_startup(self):\n \"\"\"\n Handle app startup to clear uncompleted state for jobs and begin running\n \"\"\"\n\n # cancel any jobs that were left in an uncompleted state\n with database.connection_context():\n Job.update(status=JobStatus.canceled).where(Job.status == JobStatus.started)\n\n self.refresh()\n\n def refresh(self):\n \"\"\"\n Refresh the available jobs.\n If a new job is marked as pending and no current job is running,\n will start the new job.\n\n Otherwise will exit out without doing anything and\n subsequent jobs will be launched after the current one completes.\n \"\"\"\n refresh_thread = threading.Thread(target=self._refresh_worker)\n refresh_thread.start()\n\n def cancel_job(self, job_id: str):\n \"\"\"\n Cancel a job with the given job_id so it won't be run.\n Blocks until the job can be canceled.\n\n :param job_id: the job_id to cancel\n :raise JobNotFoundError: if the job could not be found in the database\n :raise JobCancelationFailureError: if the job could not be canceled\n \"\"\"\n _LOGGER.info(\"Canceling job with id {}\".format(job_id))\n\n with self._lock:\n if self._current is not None and self._current.job_id == job_id:\n self._current.cancel()\n\n return\n\n with database.connection_context():\n job = Job.get_or_none(Job.job_id == job_id)\n\n if job is None:\n _LOGGER.error(\"Could not find job with id {}\".format(job_id))\n\n raise JobNotFoundError(\n \"Could not find job with id {}\".format(job_id)\n )\n\n if (\n job.status == JobStatus.error\n or job.status == JobStatus.completed\n or job.status == JobStatus.canceled\n ):\n _LOGGER.error(\n \"Could not cancel job with status {}\".format(job.status)\n )\n\n raise JobCancelationFailureError(\n \"Job with status {} cannot be canceled\".format(job.status)\n )\n\n job.status = JobStatus.canceled\n job.save()\n\n def _refresh_worker(self):\n _LOGGER.info(\"refreshing JobWorkerManager state\")\n\n with self._lock:\n if (\n self._current is not None\n and not self._current.completed\n and not self._current.canceled\n and not self._current.errored\n ):\n return\n\n self._current = JobWorkerManager._load_next_pending()\n\n if self._current is not None:\n _LOGGER.info(\n (\n \"found pending job with job_id {} \"\n \"and project_id {}, starting\"\n ).format(\n self._current.worker.job_id, self._current.worker.project_id\n )\n )\n self._current.start(self.refresh)\n else:\n _LOGGER.info(\"no pending jobs found\")\n\n @staticmethod\n def _load_next_pending() -> Union[None, JobWorkerWrapper]:\n _LOGGER.debug(\"loading next pending job for JobWorkerManager\")\n err_count = 0\n\n while err_count < 5:\n try:\n worker = JobWorkerManager._load_next_pending_helper()\n\n return worker\n except Exception as err:\n _LOGGER.error(\n (\n \"error while loading next pending job \"\n \"for JobWorkerManager {}\"\n ).format(err)\n )\n err_count += 1\n\n @staticmethod\n def _load_next_pending_helper() -> Union[None, JobWorkerWrapper]:\n with database.connection_context():\n next_job = None # type: Union[None, Job]\n query = (\n Job.select()\n .where(Job.status == JobStatus.pending)\n .order_by(Job.created)\n .limit(1)\n )\n\n for job in query:\n next_job = job\n break\n\n if next_job is None:\n return None\n\n try:\n if next_job.type_ not in JobWorkerRegistryHolder.REGISTRY:\n raise ValueError(\n \"Cannot find job of type {}\".format(next_job.type_)\n )\n\n cls = JobWorkerRegistryHolder.REGISTRY[next_job.type_]\n worker = cls(job.job_id, job.project_id, **job.worker_args)\n wrapper = JobWorkerWrapper(worker)\n\n return wrapper\n except Exception as err:\n next_job.error = str(err)\n next_job.status = JobStatus.error\n next_job.save()\n\n raise err\n","sub_path":"src/sparsify/workers/base_manager.py","file_name":"base_manager.py","file_ext":"py","file_size_in_byte":6844,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"177113467","text":"#Jacob Banghart\n#Last Editied: 6/5/2020\nfrom math import floor\ndata = open(\"testdata.txt\", \"r\")\noutput = []\nfor line in data:\n #read data and assign variables\n numbers = line.split()\n numberBaulbs = int(numbers[0])\n time = int(numbers[1])\n baulb = int(numbers[2])\n\n #remove repeated cycles\n newtime = time - (floor(time / numberBaulbs) * numberBaulbs)\n\n #determine on/off\n if newtime == 0:\n output.append(\"Off\")\n elif newtime == 1:\n output.append(\"On\")\n else:\n factors = []\n for i in range(1, baulb + 1):\n if(baulb % i == 0):\n factors.append(i)\n elif(i > newtime):\n break\n if len(factors) % 2 == 0:\n output.append(\"Off\")\n else:\n output.append(\"On\")\n\n#close file and ouput results\ndata.close()\nfor i in range(0, len(output)):\n print(\"Case \"+ str(i) + \": \" + str(output[i]))","sub_path":"light_switches/index.py","file_name":"index.py","file_ext":"py","file_size_in_byte":924,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"610176195","text":"from helper_functions import *\nfrom graph_edm import *\nfrom track_trajectory_functions import *\nfrom scipy.spatial import ConvexHull\nimport networkx as nx\nimport dgl\nfrom pdg_id_dict import *\n\nedge_color_dict ={\n\t1: 'cornflowerblue',\n\t2: 'mediumseagreen',\n\t3: 'gold',\n\t4: 'magenta',\n\t5: 'red',\n\t6: 'orange'\n\n}\n\nnode_color_dict = {\n\t'charged': {np.nan: 'darkgray',0:'midnightblue', 1:'cornflowerblue', 2:'mediumseagreen',3:'gold',4:'magenta',5:'red',6:'orange'},\n\t'neutral': 'olive'\n}\n\n\ndef plot_tree_graph(jet_graph,ax):\n\n\tax.set_axis_off()\n\t\n\tvtxlist,vtxdict,hadron_list, additional_vtx_dict = compute_jet_vtx(jet_graph)\n\t\n\tpt = jet_graph.jet_pt\n\teta = jet_graph.jet_eta\n\tflav = jet_graph.jet_DoubleHadLabel\n\t\n\tax.set_title('Flavour : '+str(flav)+' pt: '+'{0:.2f}'.format(pt/1000.0)+' eta: '+'{0:.2f}'.format(eta) ,\n\t\t\t\t fontsize=20)\n\t\n\tg = dgl.DGLGraph()\n\tn_nodes = len( jet_graph['trk_node_index'] )+len(jet_graph['jf_node_index'])+len(jet_graph['particle_node_index'])\n\tg.add_nodes(n_nodes)\n\t\n\tedge_list = np.dstack([ jet_graph.edge_start , jet_graph.edge_end ])[0]\n\t\n\tlabels = {}\n\t\n\tfor edge in edge_list:\n\t\ts,e = edge\n\t\t\n\t\tg.add_edge(int(s),int(e))\n\t\n\tpv_x,pv_y,pv_z = jet_graph.truth_PVx, jet_graph.truth_PVy, jet_graph.truth_PVz\n\t\n\n\t\n\tg.add_nodes(1)\n\t\n\tparticles_in_primary = []\n\tfor idx, pdgid,x0,y0,z0, x,y,z, stat,injet in zip(jet_graph['particle_node_index'], \n\t\t\t\t\t\t\t\t\t\t jet_graph['particle_node_pdgid'],\n\t\t\t\t\t\t\t\t\t\t jet_graph.particle_node_prod_x, \n\t\t\t\t\t\t\t\t\t\t jet_graph.particle_node_prod_y,\n\t\t\t\t\t\t\t\t\t\t jet_graph.particle_node_prod_z,\n\t\t\t\t\t\t\t\t\t\t jet_graph.particle_node_decay_x, \n\t\t\t\t\t\t\t\t\t\t jet_graph.particle_node_decay_y,\n\t\t\t\t\t\t\t\t\t\t jet_graph.particle_node_decay_z,\n\t\t\t\t\t\t\t\t\t\t jet_graph.particle_node_status,\n\t\t\t\t\t\t\t\t\t\t\t jet_graph.particle_node_inJet):\n\t\tif np.linalg.norm([x0-pv_x,y0-pv_y,z0-pv_z]) < 0.01:\n\t\t\t\n\t\t\tparticles_in_primary.append(idx)\n\t\n\tfor p_in_primary in particles_in_primary:\n\t\thas_parent = False\n\t\t#loop over the other children of the vtx, see if one of them is the parent\n\t\tfor p_in_primary_j in particles_in_primary:\n\t\t\tfor edge in edge_list:\n\t\t\t\ts,e = edge\n\t\t\t\tif p_in_primary_j==s and p_in_primary==e:\n\t\t\t\t\thas_parent=True\n\t\tif not has_parent:\n\t\t\tg.add_edge(n_nodes,int(p_in_primary))\n\t\t\t\t\n\tG = g.to_networkx()\n\t\n\tnode_colors = []\n\tfor idx, pdgid, charge, in zip(jet_graph['particle_node_index'], jet_graph['particle_node_pdgid'],jet_graph.particle_node_charge):\n\t\tif abs(pdgid) in [6,24]:\n\t\t\tnode_colors.append('lightgreen')\n\t\telif charge==0:\n\t\t\tnode_colors.append('khaki')\n\t\telse:\n\t\t\tnode_colors.append('lightsalmon')\n\t\n\t\n\tpos = nx.nx_agraph.graphviz_layout(G,prog='dot')\n\t\n\tmin_max_x = list(pos[0])\n\ty_min = -10\n\t\n\tfor key_i, key in enumerate( jet_graph['particle_node_index'] ):\n\t\tif key_i==0:\n\t\t\tmin_max_x = list(pos[key])\n\t\tx,y = pos[key]\n\t\tif x < min_max_x[0]:\n\t\t\tmin_max_x[0] = x\n\t\tif x > min_max_x[1]:\n\t\t\tmin_max_x[1] = x\n\t\tif y < y_min:\n\t\t\ty_min = y-10\n\tx_range = min_max_x[1]-min_max_x[0]\n\t\n\t\n\tn_tracks = len(jet_graph['trk_node_index'])\n\t\n\ttrack_x_positions = []\n\n\tfor track_i, idx in enumerate( jet_graph['trk_node_index'] ):\n\t\tx_orig, y_orig = pos[idx]\n\t\tif idx not in jet_graph.edge_end:\n\t\t\ttrack_x_positions.append( (min_max_x[0]+track_i*x_range/n_tracks, idx) )\n\t\telse:\n\t\t\ttrack_x_positions.append((x_orig, idx))\n\t\t\n\t\n\ttrack_x_positions = sorted(track_x_positions, key=lambda x: x[0])\n\t\n\t\n\tspacing = 50\n\tfor track_i in range(1,len(track_x_positions)):\n\t\tprevious_pos = track_x_positions[track_i-1][0]\n\t\tcurrent_pos = track_x_positions[track_i][0]\n\t\t\n\t\tif current_pos < previous_pos+spacing:\n\t\t\ttrack_x_positions[track_i] = ( previous_pos+spacing ,track_x_positions[track_i][1] ) \n\t\n\tfor track_x,idx in track_x_positions:\n\t\tpos[idx] = ( track_x ,y_min)\n\t\t\n\tn_jf_vtx = len(jet_graph['jf_node_index'])\n\t\n\tfor idx, vtx_i in zip(jet_graph['jf_node_index'], range(len(jet_graph['jf_node_index']))):\n\t\tpos[idx] = (min_max_x[0]+x_range/2+(vtx_i)*x_range/n_jf_vtx/2.,y_min-80)\n\t\tlabels[idx] = 'JF'+str(vtx_i)\n\t\n\tnx.draw_networkx_nodes(G,pos,node_color='orchid',node_size=1200,ax=ax,nodelist=jet_graph['jf_node_index'])\n\tnx.draw_networkx_nodes(G,pos,node_color='lightskyblue',node_size=300,ax=ax,nodelist=jet_graph['trk_node_index'])\n\tnx.draw_networkx_nodes(G,pos,node_color=node_colors,node_size=800,ax=ax,nodelist=jet_graph['particle_node_index'])\n\tnx.draw_networkx_edges(G,pos,ax=ax)\n\t\n\t\n\t\n\tfor idx, pdgid,x0,y0,z0, x,y,z, stat,injet in zip(jet_graph['particle_node_index'], \n\t\t\t\t\t\t\t\t\t\t jet_graph['particle_node_pdgid'],\n\t\t\t\t\t\t\t\t\t\t jet_graph.particle_node_prod_x, \n\t\t\t\t\t\t\t\t\t\t jet_graph.particle_node_prod_y,\n\t\t\t\t\t\t\t\t\t\t jet_graph.particle_node_prod_z,\n\t\t\t\t\t\t\t\t\t\t jet_graph.particle_node_decay_x, \n\t\t\t\t\t\t\t\t\t\t jet_graph.particle_node_decay_y,\n\t\t\t\t\t\t\t\t\t\t jet_graph.particle_node_decay_z,\n\t\t\t\t\t\t\t\t\t\t jet_graph.particle_node_status,\n\t\t\t\t\t\t\t\t\t\t\t jet_graph.particle_node_inJet):\n\t\t#labels[idx] = str(idx)\n\t\t#labels[idx] = str(stat)+' '+str(injet)\n\t\t#labels[idx] = '{0:.2f}'.format(x0)+'\\n'+ '{0:.2f}'.format(y0)+'\\n'+ '{0:.2f}'.format(z0)\n\t\t#labels[idx] = '{0:.4f}'.format(np.linalg.norm(np.array([pv_x,pv_y,pv_z])-np.array([x0,y0,z0])))\n\t\tif pdgid in pdg_id_dict:\n\t\t\tlabels[idx] = pdg_id_dict[pdgid]\n\t\telse:\n\t\t\tlabels[idx] = str(pdgid)\n\n\tnx.draw_networkx_labels(G,pos,labels,ax=ax)\n\n\ndef plot_locations(graph,ax):\n\n\thad_list = graph.hadron_list\n\tnode_list = graph.nodes\n\n\tvertices = list(set([node.vertex_idx for node in node_list]))\n\n\tif 0 not in vertices:\n\t\tvertices.append(0)\n\tif 1 not in vertices:\n\t\tvertices.append(1)\n\n\tn_vertices = len(vertices)\n\n\n\tlocations_g = dgl.DGLGraph()\n\tlocations_g.add_nodes(n_vertices)\n\tloc_labels = {}\n\tloc_spacing = 500\n\n\tx_range = n_vertices*loc_spacing\n\n\tloc_labels[0] = 'pileup/\\nfakes'\n\tloc_labels[1] = 'primary'\n\n\t\n\tG = locations_g.to_networkx()\n\tpos = {} \n\n\tfor pos_i in range(n_vertices):\n\t\tpos[pos_i] = (loc_spacing*pos_i, 0)\n\t\tif pos_i < 2:\n\t\t\tcontinue\n\t\tfor node in node_list:\n\t\t\tif node.vertex_idx == pos_i:\n\t\t\t\tloc_labels[pos_i] = '{0:.2f}'.format( np.linalg.norm(node.origin) )\n\t\t\t\tbreak\n\t\n\tnx.draw_networkx_nodes(G,pos,node_color='mediumaquamarine',node_size=1800,ax=ax)\n\tnx.draw_networkx_edges(G,pos,ax=ax)\n\tnx.draw_networkx_labels(G,pos,loc_labels,ax=ax)\n\n\n\t#fake/pileup vertex \n\tcenter_point = pos[0]\n\tsub_g = dgl.DGLGraph()\n\tsub_g.add_nodes(1)\n\tsub_g_pos = {0: center_point}\n\tn_children = 0\n\tr_x = loc_spacing/3.5\n\tr_y = 30\n\tfor node in node_list:\n\t\tif node.vertex_idx == 0:\n\t\t\tn_children+=1\n\t\t\tsub_g.add_nodes(1)\n\t\t\tsub_g.add_edge(0,n_children)\n\n\tchild_idx = 0\n\tn_tracks = 0\n\tfor node in node_list:\n\t\tif node.vertex_idx == 0:\n\t\t\tchild_idx+=1\n\t\t\t\t\n\t\t\tsub_g_pos[child_idx] = (center_point[0]+r_x*np.cos( ((child_idx-1)/float(n_children))*2*np.pi ),\n\t\t\t\t\t\t\t center_point[1]+r_y*np.sin( ((child_idx-1)/float(n_children))*2*np.pi ))\n\tG = sub_g.to_networkx()\n\t\t\n\tnx.draw_networkx_nodes(G,sub_g_pos,node_color='skyblue',node_size=800,ax=ax,nodelist=range(1,n_children+1))\n\tnx.draw_networkx_edges(G,sub_g_pos,ax=ax)\n\n\tfor vtx_i in range(1,n_vertices):\n\n\t\tcenter_point = pos[vtx_i]\n\n\n\t\tsub_g = dgl.DGLGraph()\n\t\tsub_g.add_nodes(1)\n\t\tsub_g_labels = {}\n\n\t\tsub_g_pos = {0: center_point}\n\n\n\n\t\tn_children = 0\n\t\tfor node in node_list:\n\t\t\tif node.vertex_idx == vtx_i:\n\t\t\t\tn_children+=1\n\t\t\t\tsub_g.add_nodes(1)\n\t\t\t\tsub_g.add_edge(0,n_children)\n\n\t\t\t\tif node.pdgid in pdg_id_dict:\n\t\t\t\t\tsub_g_labels[n_children] = pdg_id_dict[node.pdgid]\n\t\t\t\telse:\n\t\t\t\t\tsub_g_labels[n_children] = str(node.pdgid)\n\n\n\t\t\t\t\n\n\t\tr_x = loc_spacing/3.5\n\t\tr_y = 30\n\n\t\tchild_idx = 0\n\t\tn_tracks = 0\n\t\tfor node in node_list:\n\t\t\tif node.vertex_idx == vtx_i:\n\t\t\t\tchild_idx+=1\n\t\t\t\t\n\t\t\t\tsub_g_pos[child_idx] = (center_point[0]+r_x*np.cos( ((child_idx-1)/float(n_children))*2*np.pi ),\n\t\t\t\t\t\t\t center_point[1]+r_y*np.sin( ((child_idx-1)/float(n_children))*2*np.pi ))\n\n\t\t\t\tif node.reconstructed:\n\t\t\t\t\tsub_g.add_nodes(1)\n\t\t\t\t\tn_tracks+=1\n\t\t\t\t\tsub_g.add_edge(child_idx,n_children+n_tracks)\n\n\t\t\t\t\tsub_g_pos[n_children+n_tracks] = (center_point[0]+1.5*r_x*np.cos( ((child_idx-1)/float(n_children))*2*np.pi ),\n\t\t\t\t\t\t\t center_point[1]+1.5*r_y*np.sin( ((child_idx-1)/float(n_children))*2*np.pi ))\n\n\n\n\t\tG = sub_g.to_networkx()\n\t\t\n\t\tnx.draw_networkx_nodes(G,sub_g_pos,node_color='darksalmon',node_size=800,ax=ax,nodelist=range(1,n_children+1))\n\t\tnx.draw_networkx_nodes(G,sub_g_pos,node_color='skyblue',node_size=300,ax=ax,nodelist=range(n_children+1,n_children+n_tracks+1))\n\t\tnx.draw_networkx_edges(G,sub_g_pos,ax=ax)\n\t\tnx.draw_networkx_labels(G,sub_g_pos,sub_g_labels,ax=ax,nodelist=range(1,n_children+1))\n\n\ndef create_dgl_for_plot(graph,addJF=False):\n\tg = dgl.DGLGraph()\n\n\tnode_list = graph.nodes\n\n\tn_nodes = len( node_list )\n\n\tg.add_nodes(n_nodes)\n\n\tnode_colors = []\n\tjf_nodes = {}\n\tnode_pdgids = []\n\n\tfor node_i,node in enumerate(node_list):\n\t\tif node.pdgid in pdg_id_dict:\n\t\t\tnode_pdgids.append(pdg_id_dict[node.pdgid])\n\t\telse:\n\t\t\tnode_pdgids.append(str(node.pdgid))\n\t\t\n\n\t\tif abs(node.charge) > 0:\n\t\t\t\n\t\t\tif node.vertex_idx not in node_color_dict['charged']:\n\t\t\t\tnode_colors.append(node_color_dict['charged'][np.nan])\n\t\t\telse:\n\t\t\t\tnode_colors.append(node_color_dict['charged'][node.vertex_idx])\n\t\telse:\n\t\t\tnode_colors.append(node_color_dict['neutral'])\n\t\tif node.jf_vtx_idx > -1:\n\t\t\tif node.jf_vtx_idx not in jf_nodes:\n\t\t\t\tjf_nodes[node.jf_vtx_idx] = []\n\t\t\tjf_nodes[node.jf_vtx_idx].append(node_i)\n\t\t\t\n\t#loop over edges\n\tedge_colors = []\n\tfor node_i,node in enumerate(node_list):\n\t\tfor node_j,node2 in enumerate(node_list):\n\t\t\t\n\t\t\tedge_color = 'gray'\n\t\t\tif node.vertex_idx > 1:\n\t\t\t\tif node.vertex_idx == node2.vertex_idx:\n\t\t\t\t\tif node.vertex_idx in edge_color_dict:\n\t\t\t\t\t\tedge_color = edge_color_dict[node.vertex_idx]\n\t\t\t\t\telse:\n\t\t\t\t\t\tedge_color = 'r'\n\t\t\t\t\tg.add_edge(node_i,node_j)\n\t\t\t\t\tedge_colors.append(edge_color)\n\t\t\t\t#if node.jf_vtx_idx > -1 and node.jf_vtx_idx==node2.jf_vtx_idx and addJF:\n\t\t\t\t\t#g.add_edge(node_i,node_j)\n\t\t\t\t\t#edge_colors.append('gray')\n\t\t\t\t\n\tif not addJF:\n\t\treturn g, node_colors,node_pdgids,edge_colors\n\telse:\n\t\treturn g, node_colors,node_pdgids,edge_colors,jf_nodes\n\ndef create_hadron_G(graph):\n\thad_list = graph.hadron_list\n\tG = nx.Graph()\n\tfor h_i, h in enumerate(had_list):\n\t\t\n\t\tG.add_node(h_i,label = h[1]) \n\n\treturn G\n\ndef draw_hadron_plot(ax,G):\n\n\tpos = nx.circular_layout(G)\n\n\tn_data = G.nodes.data()\n\tn_label = {}\n\tfor key in pos:\n\t\tpos[key] = pos[key]*0.3\n\t\tif n_data[key]['label'] in pdg_id_dict:\n\t\t\tn_label[key] = pdg_id_dict[ n_data[key]['label'] ]\n\t\telse:\n\t\t\tn_label[key] = n_data[key]['label']\n\t\tax.text(pos[key][0],pos[key][1]+0.2,n_label[key],fontsize=20,\n\t\t\thorizontalalignment='center',verticalalignment='center')\n\tnx.draw_networkx(G,pos=pos,with_labels=False, style='-',ax=ax,arrows=False,\n\t\tnode_color='k')\n\treturn pos\n\ndef add_circle(p,radius):\n\tx, y = p\n\tadded_points = []\n\tfor n in range(36):\n\t\tang = (2*np.pi)*(float(n)/36.0)\n\t\tnew_p = [ x+radius*np.cos(ang),y+radius*np.sin(ang) ]\n\t\tadded_points.append(new_p)\n\t\t\n\treturn added_points\n\ndef fill_points(points_list,r=0.18):\n\textended = []\n\tfor p in points_list:\n\t\textended.append(p)\n\t\tadded = add_circle(p,r)\n\t\tfor ad in added:\n\t\t\textended.append(ad)\n\treturn np.array(extended)\n\n\ndef create_graph_plot(graph,ax,draw_JF=True):\n\t\n\tgraph.sort_nodes()\n\n\tg, node_colors,node_pdgids,e_colors, jf_nodes = create_dgl_for_plot(graph,addJF=True)\n\n\thadron_G = create_hadron_G(graph)\n\thadron_positions = draw_hadron_plot(ax,hadron_G)\n\thadron_node_indices = [n.had_idx for n in graph.nodes]\n\t\n\tG = g.to_networkx()\n\n\tpos = nx.circular_layout(G)\n\n\te_widths=[0.2 if e_c=='gray' else 3 for e_c in e_colors]\n\n\tnx.drawing.draw_circular(G,with_labels=False,node_color=node_colors,edge_color=e_colors, style='-',ax=ax\n\t\t\t\t\t\t,width=e_widths,arrows=False)\n\n\tfor n_i, n_idx in enumerate(hadron_node_indices):\n\t\tif np.isnan(n_idx):\n\t\t\tcontinue\n\t\torigin_point = hadron_positions[n_idx]\n\t\tnode_point = pos[n_i]\n\t\tlcolor = node_colors[n_i]\n\t\tax.plot([origin_point[0],node_point[0]],[origin_point[1],node_point[1]],\n\t\t\tc=lcolor,linestyle='-',alpha=0.3)\n\n\tpoints_dict = {}\n\tif draw_JF:\n\t\tfor key in jf_nodes:\n\t\t\tpoints_dict[key] = np.array([pos[x] for x in jf_nodes[key]])\n\t\t\tfill_p = fill_points(points_dict[key])\n\t\t\thull = ConvexHull(fill_p)\n\t\t\tfor simplex in hull.simplices:\n\n\t\t\t\tax.plot(fill_p[simplex, 0], fill_p[simplex, 1], 'k--')\n\ndef plot_graph_jet_image(graph,ax):\n\tg, node_colors,node_pdgids,e_colors = create_dgl_for_plot(graph)\n\t# PVx,PVy,PVz = graph.\n\tj_axis = graph.axis\n\n\trotMatrix = rotationMatrix(j_axis,[1,0,0])\n\n\t\n\tfor node_i, node in enumerate( graph.nodes ):\n\t\tif not type(node.p4) == float:\n\t\t\t_ ,px,py,pz = node.p4\n\t\t\tp = np.array([px,py,pz])\n\t\t\tp = 0.5*(p/np.linalg.norm(p))\n\t\t\tpx,py,pz = 5.0*np.dot(rotMatrix,list(p))\n\t\t\tx,y,z = np.dot(rotMatrix,list(node.origin) )\n\n\t\t\tlcolor = node_colors[node_i] #'purple'\n\t\t\tlstyle = '-'\n\t\t\tlwidth = 6\n\n\t\t\tax.plot([x,x+px],[y,y+py],c=lcolor,linestyle=lstyle,lw=lwidth)\n\n\tylim = list(ax.get_ylim())\n\txlim = list(ax.get_xlim())\n\n\tfor node_i, node in enumerate( graph.nodes ):\n\t\tif not node.reconstructed:\n\t\t\tcontinue\n\t\tpt,d0,d0signed,z0,z0signed,phi,theta,qoverp = node.matched_track\n\t\ttrack = build_track_trajectory( [phi,theta,d0,z0,qoverp] ) \n\n\t\tplot_track(ax,track,rotMatrix,node_colors[node_i])\n\n\t\n\tax.set_xlabel('distance along jet axis [mm]',fontsize=20)\n\tax.set_ylabel('distance transverse to jet axis [mm]',fontsize=20)\n\n\tax.plot([0,1.5*xlim[1]],[0,0],c='k')\n\tax.set_xlim(0,1.5*xlim[1])\n\tax.set_ylim(-1.2*max(abs(ylim[0]),abs(ylim[1])), 1.2*max(abs(ylim[0]),abs(ylim[1])) )\n\n\n","sub_path":"helper_functions/graph_plotting.py","file_name":"graph_plotting.py","file_ext":"py","file_size_in_byte":13377,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"162653724","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.6 (3379)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: /home/hanzz/releases/odcs/server/tests/utils.py\n# Compiled at: 2018-02-20 08:15:54\n# Size of source mod 2**32: 4252 bytes\nimport unittest\nfrom odcs.server import db\nfrom sqlalchemy import event\nfrom odcs.server.events import cache_composes_if_state_changed\nfrom odcs.server.events import start_to_publish_messages\nfrom flask.ext.sqlalchemy import SignallingSession\nfrom mock import patch\n\nclass AnyStringWith(str):\n\n def __eq__(self, other):\n return self in other\n\n\nclass ConfigPatcher(object):\n\n def __init__(self, config_obj):\n self.objects = []\n self.config_obj = config_obj\n\n def patch(self, key, value):\n try:\n obj = patch.object((self.config_obj), key, new=value)\n except Exception:\n self.stop()\n raise\n\n self.objects.append(obj)\n\n def start(self):\n for obj in self.objects:\n obj.start()\n\n def stop(self):\n for obj in self.objects:\n obj.stop()\n\n\nclass ModelsBaseTest(unittest.TestCase):\n __doc__ = 'Base test case for models\\n\\n Database and schemas are initialized on behalf of developers.\\n '\n disable_event_handlers = True\n\n def setUp(self):\n if event.contains(SignallingSession, 'before_commit', cache_composes_if_state_changed):\n event.remove(SignallingSession, 'before_commit', cache_composes_if_state_changed)\n else:\n if event.contains(SignallingSession, 'after_commit', start_to_publish_messages):\n event.remove(SignallingSession, 'after_commit', start_to_publish_messages)\n else:\n db.session.remove()\n db.drop_all()\n db.create_all()\n db.session.commit()\n setup_composes = getattr(self, 'setup_composes', None)\n if setup_composes is not None:\n assert callable(setup_composes)\n setup_composes()\n if hasattr(self, 'setup_composes'):\n getattr(self, 'setup_composes')()\n if not self.disable_event_handlers:\n event.listen(SignallingSession, 'before_commit', cache_composes_if_state_changed)\n event.listen(SignallingSession, 'after_commit', start_to_publish_messages)\n\n def tearDown(self):\n if not self.disable_event_handlers:\n event.remove(SignallingSession, 'before_commit', cache_composes_if_state_changed)\n event.remove(SignallingSession, 'after_commit', start_to_publish_messages)\n db.session.remove()\n db.drop_all()\n db.session.commit()\n event.listen(SignallingSession, 'before_commit', cache_composes_if_state_changed)\n event.listen(SignallingSession, 'after_commit', start_to_publish_messages)","sub_path":"pycfiles/odcs-0.2.46.tar/utils.cpython-36.py","file_name":"utils.cpython-36.py","file_ext":"py","file_size_in_byte":2940,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"390199819","text":"# Program to convert floating point decimal numbers into its equivalent binary.\r\n\r\ndef reverse_str(ThisStr):\r\n rev_str = \"\"\r\n i = len(ThisStr) - 1\r\n while i >= 0:\r\n rev_str += ThisStr[i]\r\n i -= 1\r\n return rev_str\r\n\r\ndef convert_float_binary(float_num):\r\n integer_part = int(float_num)\r\n decimal_part = float_num - integer_part\r\n\r\n if integer_part:\r\n binary = \"\"\r\n while integer_part:\r\n binary = binary + (str(integer_part % 2))\r\n integer_part /= 2\r\n binary = reverse_str(binary)\r\n\r\n if decimal_part:\r\n binary += '.'\r\n while (int(decimal_part)) < 1:\r\n decimal_part *= 2\r\n binary += str(int(decimal_part))\r\n\r\n return binary\r\n\r\n\r\nnum = input(\"Enter integer or float number:\")\r\nprint(\"Binary equivalent of integer/float number {} is: {}\".format(num,convert_float_binary(num))) \r\n","sub_path":"Practice Programs/GeeksforGeeks Archive/float_binary.py","file_name":"float_binary.py","file_ext":"py","file_size_in_byte":826,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"610323212","text":"#!/usr/bin/python\nfrom coffea import util,hist\nimport json\nimport os\nimport subprocess\n\nimport argparse\n\nitoa = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']\n\n#python hadd_coffea.py --prefix hists_sum_bkg_ --samples 0 20 40 60 80 100 --outname hists_sum_bkg --indir Sep21_Trig -n\nparser = argparse.ArgumentParser(description='Process some integers.')\nparser.add_argument('--indir', metavar='indir', default='./', help='indir')\nparser.add_argument('--prefix', metavar='prefix', default='', type=str, help='prefix')\nparser.add_argument('--samples', metavar='samples', help='samples', nargs='+')\nparser.add_argument('--outname', metavar='outname', default='hists_sum', help='outname', type=str)\nparser.add_argument('-s', '--doscale', action='store_true')\nparser.add_argument('--chunk', metavar='chunk', default=5, type=int, help='chunk')\nargs = parser.parse_args()\n\nindir = args.indir\n\nchunk_size = args.chunk\n\nonlyfiles = [\"%s%s\"%(args.prefix,s) for s in args.samples]\n\nchunk_names = []\nfor ii,i in enumerate(range(0,len(onlyfiles),chunk_size)):\n print('Chunk',i)\n flist = []\n if (i+chunk_size m: s, m = m, s\n if m > l: m, l = l, m\n\n if l < s+m: return True\n\n return False\n\n\n def __go_ready_to_dock_position__(self, robot_pos):\n #print('__face_ready_to_dock_position__ started')\n self.__send_robot_speed__(0.0, 0.0)\n self.station.ros_sleep()\n clockwise = True if robot_pos[0] > 0 else False\n \n ready_point = 0.90\n\n a = round(math.sqrt(robot_pos[0]**2 + robot_pos[1]**2),2)\n b = round(math.sqrt(robot_pos[0]**2 + (robot_pos[1]-ready_point)**2),2)\n c = ready_point # (0.0, 0.0) ~ (0.0, ready_point)\n\n if not self.__is_triangle(a,b,c):\n ang = 0.0 if robot_pos[1] >= ready_point else math.pi\n else:\n ang = math.acos((a**2+b**2-c**2)/(2*a*b))\n\n robot_ang = robot_pos[2]\n if clockwise: robot_ang *= -1.0\n relative_angle = abs(ang)# + robot_ang) <========== Add this in real environment \n #print('angle:', ang, ' robot angle:', robot_pos[2], ' relative_angle:', relative_angle) \n\n # Checking if our movement is CW or CCW\n angular_speed = 1.0\n if clockwise: angular_speed = -abs(angular_speed)\n\n # 01.Rotation \n print('01.Rotation ')\n t0 = self.station.ros_time()\n desired_angle = 0\n while(desired_angle < relative_angle):\n z, _ = self.__send_robot_speed__(ang=angular_speed, lin=0.0)\n self.station.ros_sleep()\n #print('desired_angle:', desired_angle, ' angular speed:', z)\n t1 = self.station.ros_time()\n desired_angle = abs(z*(t1-t0))\n self.station.ros_sleep()\n self.__send_robot_speed__(0.0, 0.0)\n \n # 02.Move to (0.0, ready_point)\n print('02.Move to (0.0,'+str(ready_point)+')')\n\n t0 = self.station.ros_time()\n distance_moved = 0\n linear_speed = 0.25 # Ratio\n while(distance_moved < b):\n _ , lin_speed = self.__send_robot_speed__(ang=0.0, lin=linear_speed)\n self.station.ros_sleep()\n t1 = self.station.ros_time()\n distance_moved = abs(lin_speed*(t1-t0))\n self.__send_robot_speed__(0.0, 0.0)\n self.station.ros_sleep()\n\n # 03.Face the docking station\n print('03.Face the docking station') \n\n if not self.__is_triangle(a,b,c):\n ang = 0.0 if robot_pos[1] < ready_point else math.pi\n else:\n ang = math.acos((b**2+c**2-a**2)/(2*b*c))\n relative_angle = math.pi - ang # - robot_ang <============= Add this in real environment \n angular_speed *= -1.0\n\n t0 = self.station.ros_time()\n desired_angle = 0\n while(desired_angle < relative_angle):\n z, _ = self.__send_robot_speed__(ang=angular_speed, lin=0.0)\n self.station.ros_sleep()\n t1 = self.station.ros_time()\n desired_angle = abs(z*(t1-t0))\n self.station.ros_sleep()\n self.__send_robot_speed__(0.0, 0.0)\n\n self.no_image_taken = True\n self.station.place_randomly()\n self.no_image_taken = False\n\n self.labels = []\n self.images = []\n self.data = []\n\n print('### Ready-to-Go Position is set ###')\n\n\n def __predict_pos__(self):\n images = self.images\n labels = self.labels\n\n self.labels = []\n self.images = []\n self.data = []\n \n if len(images) == 0 or len(images) != len(labels): return\n\n image = images[-1]\n label = labels[-1]\n\n data = np.array(image, dtype=np.float32)\n data.shape = (1,) + data.shape\n data /= 255.\n\n predictions = self.model.predict(data)[0]\n prob = np.max(predictions, axis=-1)\n ind = np.argmax(predictions, axis=-1)\n\n label = np.round(label,2)\n if prob > DETECTION_THRESHOLD_ACCURACY:\n \n pred = self.label_dic[ind]\n pred[0], pred[1] = pred[1], pred[0]\n if 0.1 > np.mean(np.sum(np.round(label,1)-pred)): self.correct+=1\n else: self.wrong +=1\n\n pred_string = [str(a) for a in pred]\n label = [str(a) for a in label]\n print('\\nPredicted('+str(round(prob,2)*100)+'%):['+','.join(pred_string)+'] | Label:['+','.join(label)+'] | '\n + str(self.correct) + '/' + str(self.correct+self.wrong))\n\n self.__go_ready_to_dock_position__(pred)\n\n self.no_image_taken = False\n\n\n def run(self):\n ''' Main Loop '''\n settings = termios.tcgetattr(sys.stdin)\n \n while True:\n key = self.__getKey__(settings)\n \n if not self._collision_situation():\n if key == '\\x03': \n print(\"Bye~\")\n return False\n elif key == 'n':\n self.no_image_taken = True\n self.station.align_and_face_robot()\n self.no_image_taken = False\n elif key == 'r':\n self.no_image_taken = True\n self.station.place_randomly()\n self.no_image_taken = False\n\n self.__predict_pos__()\n self.__random_move__(boost_ang=True)\n\n time.sleep(0.005)\n \n self.__send_robot_speed__()\n \n termios.tcsetattr(sys.stdin, termios.TCSADRAIN, settings)\n\n\ndef main():\n ''' \n Main Function working with ROS\n '''\n ModelEvaluation().run()\n\n\ndef evaluate_model_with_validation_dataset():\n '''\n Evaluate the model with validation dataset in data/validation folder \n '''\n\n model = load_model(MODEL_W_PATH)\n\n # Generate dataset from a path\n BATCH_SIZE = 100\n test_datagen = ImageDataGenerator(rescale=1. / 255)\n test_generator = test_datagen.flow_from_directory(\n VAL_DATA_PATH,\n batch_size = BATCH_SIZE,\n target_size=(IMG_HEIGHT, IMG_WIDTH),\n class_mode='categorical'\n )\n\n # Create Label map\n label_map = (test_generator.class_indices)\n label_map = dict((v,k) for k,v in label_map.items()) #flip k,v\n total_accuray = 0\n total_num = 0\n\t\n while True:\n # Take first one of dataset\n data, labels = test_generator.next()\n #if data == None: break\n labels = np.argmax(labels, axis=-1) \n labels = [label_map[k] for k in labels]\n\n # Predict\n predictions = model.predict(data)\n total_num += len(predictions)\n if len(predictions) != BATCH_SIZE : break\n\n # Label predictions\n predictions = np.argmax(predictions, axis=-1) #multiple categories\n predictions = [label_map[k] for k in predictions]\n\n # Visualize results\n cnt = 0\n for p, l in zip(predictions, labels):\n result = True if p == l else False\n if result: \n cnt += 1\n total_accuray += 1\n #print(p, \" : \", l, \" \", result)\n print(\"Accuracy:\",str(cnt) + \"/\" + str(BATCH_SIZE), \" (\"+ str(100.0*cnt/BATCH_SIZE)+\")\")\n\n print(\"Overall Accuracy:\",str(total_accuray) + \"/\" + str(total_num), \" (\"+ str(100.0*total_accuray/total_num)+\")\")\n\n\ndef evaluate_model_with_images():\n '''\n Evaluate model with images in sample_images folder \n '''\n import cv2\n IMAGE_PATH = __PATH__ + '/sample_images/'\n\n model = load_model(MODEL_W_PATH)\n label_dic = load_labels()\n\n def _prediction(model, file, rescale_img_save=False):\n '''\n Iterated Function to predict\n '''\n img = cv2.imread(file)\n img = cv2.resize(img, (100, 100))\n\n img_bgr = img[...,::-1] #RGB 2 BGR\n\n data = np.array(img_bgr, dtype=np.float32)\n data = data.transpose((0, 1, 2))\n data.shape = (1,) + data.shape\n data /= 255.\n\n predictions = model.predict(data)\n prob = np.max(predictions, axis=-1)[0]\n ind = np.argmax(predictions, axis=-1)[0]\n\n pred = label_dic[ind]\n pred[0], pred[1] = pred[1], pred[0] # exchage x and y place in the list \n file = file.split('/') # to get only file name \n print('Prediction => index:'+'{}({}%) - position and yaw: [{},{},{}] - file name:'.format(ind, round(prob,2)*100, *pred)+file[-1])\n\n if rescale_img_save:\n rescale_img_path = IMAGE_PATH + str(pred[1])+'_'+str(pred[0])+'_'+str(pred[2])+'.jpg'\n cv2.imwrite(rescale_img_path,img)\n \n for file in os.listdir(IMAGE_PATH):\n if file.endswith(\".jpg\") or file.endswith(\".jpeg\") or file.endswith(\".png\") or file.endswith(\".JPG\"):\n _prediction(model, IMAGE_PATH+file)\n \n\n \nif __name__==\"__main__\":\n OPS \t= ['main', 'dataset', 'images']\n \n parser = argparse.ArgumentParser( description = 'Input Arguments --run dataset or --run sample' )\n parser.add_argument( '--run' , dest = 'run' , default = OPS[0] )\n args = parser.parse_args()\n\n if args.run == OPS[0]:\n main()\n elif args.run == OPS[1]:\n evaluate_model_with_validation_dataset()\n elif args.run == OPS[2]:\n evaluate_model_with_images()\n else:\n raise Exception(args.run + ' is Not supported')\n\n# end of file","sub_path":"turtlebot3_auto_docking/src/model_eval.py","file_name":"model_eval.py","file_ext":"py","file_size_in_byte":10931,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"23402939","text":"#! /usr/bin/env python\n\n# implement PlantUML extension\n# https://www.mediawiki.org/wiki/Extension:PlantUML\n\nimport os\nimport tempfile\nimport subprocess\nfrom hashlib import md5\n\n_basedir = None\n\nplantuml_paths = [os.path.expanduser('~/plantuml/'), os.path.dirname(os.path.abspath(__file__))]\n\n\ndef _get_global_basedir():\n global _basedir\n if not _basedir:\n _basedir = tempfile.mkdtemp(prefix='uml-')\n import atexit\n import shutil\n atexit.register(shutil.rmtree, _basedir)\n return _basedir\n\n\ndef _get_plantuml_path():\n for path in plantuml_paths:\n jar_path = os.path.join(path, 'plantuml.jar')\n if os.path.exists(jar_path):\n return path\n return None\n\n\ndef drawUml(script, basedir=None):\n if isinstance(script, unicode):\n script = script.encode('utf8')\n\n if basedir is None:\n basedir = _get_global_basedir()\n\n m = md5()\n m.update(script)\n ident = m.hexdigest()\n\n pngfile = os.path.join(basedir, '%s.png' % ident)\n\n if os.path.exists(pngfile):\n return pngfile\n\n scriptfile = os.path.join(basedir, ident + '.txt')\n\n with open(scriptfile, 'w') as scruml:\n scruml.write(script)\n\n plantumljar_path = _get_plantuml_path()\n plantumljar_path_binary = os.path.join(plantumljar_path, 'plantuml.jar')\n\n # Unable to access jarfile plantuml.jar\n # cmd_string = 'java -Djava.awt.headless=true -Dplantuml.include.path=\"%(plantumljar_path)s\" -jar plantuml.jar -o \"%(basedir)s\" %(scriptfile)s' % {\n # 'plantumljar_path': plantumljar_path, 'scriptfile': scriptfile, 'basedir': basedir}\n\n cmd_string = 'java -Djava.awt.headless=true -jar %(plantumljar_path_binary)s -o \"%(basedir)s\" %(scriptfile)s' % {\n 'plantumljar_path_binary': plantumljar_path_binary, 'scriptfile': scriptfile, 'basedir': basedir}\n\n cmd = subprocess.Popen(cmd_string, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=True)\n\n err = cmd.communicate()\n\n if err[0]:\n return None\n\n if os.path.exists(pngfile):\n return pngfile\n\n return None\n","sub_path":"mwlib/uml.py","file_name":"uml.py","file_ext":"py","file_size_in_byte":2072,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"203050983","text":"import Model\nimport os.path as pth\nimport zipfile\n\n#Get abs path about this file\nabsFilePath = pth.abspath(__file__)\n#Get abs directory about this file\nabsFileDirectoryPath = pth.dirname(absFilePath)\n#Join into this directory sub module directory\nmodulesZipPyc = pth.join(absFileDirectoryPath, 'TrainLibraries.zip')\n#Create the basename for writepy method\nlstModules = ('Model', 'ElectronicModel', 'Controller', 'ElectronicComponents', 'TrainIO')\nwith zipfile.PyZipFile(modulesZipPyc, 'w', zipfile.ZIP_DEFLATED) as zfile:\n for tmpModuleName in lstModules:\n pathNameWritePy = pth.join(absFileDirectoryPath, tmpModuleName)\n zfile.writepy(pathNameWritePy)\n zfile.close()\n","sub_path":"src/zipModules.py","file_name":"zipModules.py","file_ext":"py","file_size_in_byte":676,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"13233064","text":"\"\"\"\n 1. 입력문자열을 앞에서부터 차례차례 한 글자씩 스택에 push 합니다.\n 2. 현재 글자가 폭발 문자열의 마지막 글자와 일치하면\n스택의 top부터 폭발문자열의 길이까지 확인하여 폭발문자열이 만들어지는지 확인합니다.\n 3. 폭발문자열이 만들어진다면 만들어지는 폭발문자열을 스택에서 pop합니다.\n 4. 1~3을 반복합니다.\n 5. 문자열 순회를 마치고 스택이 비어있으면, FRULA를 출력, 비어있지 않다면 스택 속 문자열을 차례로 출력합니다.\n\"\"\"\n\n\ndef main():\n string = input() # 전체 문자열\n bomb = input() # 폭발 문자열\n\n lastChar = bomb[-1] # 폭발 문자열의 마지막 글자\n stack = []\n length = len(bomb) # 폭발 문자열의 길이\n\n for char in string:\n stack.append(char)\n if char == lastChar and ''.join(stack[-length:]) == bomb:\n del stack[-length:]\n\n answer = ''.join(stack)\n\n if answer == '':\n print(\"FRULA\")\n else:\n print(answer)\n\n\nif __name__ == '__main__':\n main()\n\n\n# 출처 : https://mytodays.tistory.com/23","sub_path":"DataStructure/9935_ans.py","file_name":"9935_ans.py","file_ext":"py","file_size_in_byte":1160,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"342852158","text":"\"\"\"Support for Zyxel Keenetic NDMS2 based routers.\"\"\"\nimport logging\n\nfrom ndms2_client import Client, ConnectionException, TelnetConnection\nimport voluptuous as vol\n\nfrom homeassistant.components.device_tracker import (\n DOMAIN,\n PLATFORM_SCHEMA,\n DeviceScanner,\n)\nfrom homeassistant.const import CONF_HOST, CONF_PASSWORD, CONF_PORT, CONF_USERNAME\nimport homeassistant.helpers.config_validation as cv\n\n_LOGGER = logging.getLogger(__name__)\n\n# Interface name to track devices for. Most likely one will not need to\n# change it from default 'Home'. This is needed not to track Guest WI-FI-\n# clients and router itself\nCONF_INTERFACE = \"interface\"\n\nDEFAULT_INTERFACE = \"Home\"\nDEFAULT_PORT = 23\n\n\nPLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(\n {\n vol.Required(CONF_HOST): cv.string,\n vol.Required(CONF_USERNAME): cv.string,\n vol.Required(CONF_PORT, default=DEFAULT_PORT): cv.port,\n vol.Required(CONF_PASSWORD): cv.string,\n vol.Required(CONF_INTERFACE, default=DEFAULT_INTERFACE): cv.string,\n }\n)\n\n\ndef get_scanner(_hass, config):\n \"\"\"Validate the configuration and return a Keenetic NDMS2 scanner.\"\"\"\n scanner = KeeneticNDMS2DeviceScanner(config[DOMAIN])\n\n return scanner if scanner.success_init else None\n\n\nclass KeeneticNDMS2DeviceScanner(DeviceScanner):\n \"\"\"This class scans for devices using keenetic NDMS2 web interface.\"\"\"\n\n def __init__(self, config):\n \"\"\"Initialize the scanner.\"\"\"\n\n self.last_results = []\n\n self._interface = config[CONF_INTERFACE]\n\n self._client = Client(\n TelnetConnection(\n config.get(CONF_HOST),\n config.get(CONF_PORT),\n config.get(CONF_USERNAME),\n config.get(CONF_PASSWORD),\n )\n )\n\n self.success_init = self._update_info()\n _LOGGER.info(\"Scanner initialized\")\n\n def scan_devices(self):\n \"\"\"Scan for new devices and return a list with found device IDs.\"\"\"\n self._update_info()\n\n return [device.mac for device in self.last_results]\n\n def get_device_name(self, device):\n \"\"\"Return the name of the given device or None if we don't know.\"\"\"\n name = next(\n (result.name for result in self.last_results if result.mac == device), None\n )\n return name\n\n def get_extra_attributes(self, device):\n \"\"\"Return the IP of the given device.\"\"\"\n attributes = next(\n ({\"ip\": result.ip} for result in self.last_results if result.mac == device),\n {},\n )\n return attributes\n\n def _update_info(self):\n \"\"\"Get ARP from keenetic router.\"\"\"\n _LOGGER.debug(\"Fetching devices from router...\")\n\n try:\n self.last_results = [\n dev\n for dev in self._client.get_devices()\n if dev.interface == self._interface\n ]\n _LOGGER.debug(\"Successfully fetched data from router\")\n return True\n\n except ConnectionException:\n _LOGGER.error(\"Error fetching data from router\")\n return False\n","sub_path":"homeassistant/components/keenetic_ndms2/device_tracker.py","file_name":"device_tracker.py","file_ext":"py","file_size_in_byte":3122,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"371716298","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Feb 4 01:14:20 2019\n\n@author: Ian\n\npolynomial = poly(frequenciesFromGraph, T_uncVal)(freqRange)\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt \nimport scipy.interpolate as sci\nfrom numpy import exp, angle\nimport skrf\nimport math\n\n# The first two lines of the .prn files contain no information we need\nthrowAwayLines = 2\n\ndef frequencies(filename): \n '''Array of frequencies at which measurements were taken. \n Function takes a .prn file'''\n # Read file; remove commas and new-line characters\n with open(filename) as f:\n data = np.loadtxt((x.replace(',', '') for x in f), skiprows = throwAwayLines)\n # Extracting just frequencies\n frequencies = data[:, 0]\n return frequencies\n\ndef psd(filename):\n '''Array of PSD measurements. DOES NOT convert units or smooth.\n Function takes a .prn file'''\n with open(filename) as f:\n data = np.loadtxt((x.replace(',', '') for x in f), skiprows = throwAwayLines)\n PSD = data[:, 1]\n return PSD\n\ndef matS11(filename):\n '''Get the reflection coefficients (S11s) of the calibrator or receiver. \n It takes an .s1p or .s2p file.\n SCIKIT-RF NEEDS TO BE INSTALLED IN ORDER FOR THIS TO WORK!'''\n matrixDat = skrf.Network(filename)\n # We only care about the S11s so we throw away the other measurements\n matrixDat = matrixDat.s[:,0,0]\n return matrixDat\n\ndef matS12(filename):\n matrixDat = skrf.Network(filename)\n matrixDat = matrixDat.s[:,0,1]\n return matrixDat\n\ndef matS21(filename):\n matrixDat = skrf.Network(filename)\n matrixDat = matrixDat.s[:,1,0]\n return matrixDat\n\ndef matS22(filename):\n matrixDat = skrf.Network(filename)\n matrixDat = matrixDat.s[:,1,1]\n return matrixDat\n\ndef poly(xVals, yVals):\n polyft = np.polyfit(xVals, yVals, 3)\n polynomial = np.poly1d(polyft)\n #temps = polynomial(xVals)\n return polynomial\n #return temps\n\ndef inter(xVals, yVals):\n interp = sci.interp1d(xVals, yVals)\n #interpolation = interp(freqRange)\n return interp\n #return interpolation\n\ndef convertUnits(dBmMeasurements):\n dBmMeasurements = 10.00** (dBmMeasurements / 10.0) \n return dBmMeasurements\n\ndef polar2z(r,theta):\n return np.array(r * exp( 1j * theta ))\n\ndef z2polar(z):\n return np.array([abs(z), angle(z)])\n\ndef uncalTemps(antData, loadData, noiseData, T_L, T_NS):\n T_calStar = (((antData - loadData) / (noiseData - loadData)) * T_NS) + T_L\n return T_calStar\n\ndef Abuilder(gammaCal, gammaRec, T_calStar, frequencies, n, T_L):\n F = np.sqrt(1 - abs(gammaRec)**2) / (1 - (gammaCal * gammaRec))\n K2 = (abs(gammaCal)**2 * abs(F)**2) / (1 - abs(gammaRec)**2)\n K3 = ((abs(gammaCal) * abs(F)) / (1 - abs(gammaRec)**2)) * np.real(gammaCal * F) / np.absolute(gammaCal * F)\n K4 = ((abs(gammaCal) * abs(F)) / (1 - abs(gammaRec)**2)) * np.imag(gammaCal * F) / np.absolute(gammaCal * F)\n nu = np.array([frequencies**i for i in range(max(n)+1)], dtype = float)\n A = np.concatenate((-K2*nu[:n[0]+1,:], -K3*nu[:n[1]+1,:], -K4*nu[:n[2]+1,:], (T_calStar - T_L)*nu[:n[3]+1,:], ([-1]* len(frequencies))*nu[:n[4]+1,:]))\n return A\n\ndef thetaBuilder(gammaCal, gammaRec, T_calStar, frequencies, n, T_L, T_cal):\n A = Abuilder(gammaCal, gammaRec, T_calStar, frequencies, n, T_L)\n M = np.matmul(A, np.transpose(A))\n F = np.sqrt(1 - abs(gammaRec)**2) / (1 - (gammaCal * gammaRec))\n K1 = ((1 - abs(gammaCal)**2) * abs(F)**2) / (1 - abs(gammaRec)**2)\n D = (T_cal * K1) - T_L\n b = np.matmul(D, A.transpose())\n theta = np.linalg.solve(M, b)\n return theta\n\ndef calibratedTemps(A, theta, T_L, gammaCal, gammaRec):\n F = np.sqrt(1 - abs(gammaRec)**2) / (1 - (gammaCal * gammaRec))\n K1 = ((1 - abs(gammaCal)**2) * abs(F)**2) / (1 - abs(gammaRec)**2)\n Dv = np.matmul(np.transpose(A), theta)\n calibratedTemps = (Dv + T_L) / K1\n return calibratedTemps\n\ndef sigma(A, b, theta, K1, freq, T_cal, T_L): \n N = len(freq)\n bTM_invb = np.matmul(np.transpose(b), theta)\n \n D = (T_cal * K1) - T_L\n D = D**2\n D = np.sum(D)\n \n SIGMA = np.sqrt((D - bTM_invb) / N)\n return SIGMA\n\ndef PCM(sigma, A):\n M = np.matmul(A, np.transpose(A))\n invertedM = np.linalg.inv(M)\n PCM = (sigma**2) * invertedM\n return PCM\n\ndef pdn(PSDatAnt, PSDatLoad, PSDatNS, internal_T_L, internal_T_NS, gammaCal, gammaRec, n):\n frequencies = ft.frequencies(PSDatAnt)\n frequencies = frequencies / 1e+6\n internal_gamma_L = 0.1\n internal_T_L = 297\n internal_T_NS = 2017.420\n T_cal = 297\n N = len(frequencies)\n \n recS11 = ft.matS11(gammaRec)\n recS12 = ft.matS12(gammaRec)\n recS21 = ft.matS21(gammaRec)\n recS22 = ft.matS22(gammaRec)\n gammaRec = recS11 + (((recS12*recS21)*internal_gamma_L) / (1 - (recS22*internal_gamma_L)))\n \n PSDatAnt = ft.psd(PSDatAnt)\n PSDatLoad = ft.psd(PSDatLoad)\n PSDatNS = ft.psd(PSDatNS)\n PSDatAnt = ft.convertUnits(PSDatAnt)\n PSDatLoad = ft.convertUnits(PSDatLoad)\n PSDatNS = ft.convertUnits(PSDatNS)\n \n PSDatAnt = PSDatAnt - 30\n PSDatLoad = PSDatLoad - 30\n PSDatNS = PSDatNS - 30\n \n T_calStar = ft.uncalTemps(PSDatAnt, PSDatLoad, PSDatNS, internal_T_L, internal_T_NS)\n gammaCal = ft.matS11(gammaCal)\n A = ft.Abuilder(gammaCal, gammaRec, T_calStar, frequencies, n, internal_T_L)\n M = np.matmul(A, np.transpose(A))\n theta = ft.thetaBuilder(gammaCal, gammaRec, T_calStar, frequencies, n, internal_T_L, T_cal)\n \n F = np.sqrt(1 - abs(gammaRec)**2) / (1 - (gammaCal * gammaRec))\n K1 = ((1 - abs(gammaCal)**2) * abs(F)**2) / (1 - abs(gammaRec)**2)\n D = (T_cal * K1) - internal_T_L\n b = np.matmul(D, A.transpose())\n calibratorSig = ft.sigma(A, b, theta, K1, frequencies, T_cal, internal_T_L)\n \n #chi2 = ((D - (np.matmul(A.T, theta)))**2) / (2 * calibratorSig)\n \n theta_Min = -1000\n theta_Max = 1000\n PThetaSig = 1 / (theta_Max - theta_Min)\n \n k = N - np.linalg.matrix_rank(M)\n Y = -1 * np.matmul(b.T, np.matmul(np.linalg.inv(M), b)) + np.sum(D**2)\n \n PDn = np.log(PThetaSig) + (5/2)*np.log(2*np.pi*(calibratorSig**2)) \n - (N/2)*np.log(2*np.pi*(calibratorSig**2)) + .5*np.log(np.linalg.det(np.linalg.inv(M)))\n + ((k - 3)/2)*np.log(2) + ((1 - k)/2)*np.log(Y) + math.lgamma((k - 1) / 2)\n \n return PDn\n\ndef orderOptimization(PSDatAnt, PSDatLoad, PSDatNS, internal_T_L, internal_T_NS, gammaCal, gammaRec):\n n = [0, 0, 0, 0, 0] \n iteration = 1\n stepSize = 1\n printVals = 1\n maxOrder = 7\n minOrder = 0\n while True:\n if iteration > 1000000: break\n if stepSize > 5:\n print ('Sufficient local maximum found: ', n)\n break\n if all(i == maxOrder for i in n): \n print('Maximum value of n = [7, 7, 7, 7, 7] reached ... exiting')\n break\n def comparison(a): \n comp = pdn(PSDatAnt, PSDatLoad, PSDatNS, internal_T_L, internal_T_NS, gammaCal, gammaRec, n) + (pdn(PSDatAnt, PSDatLoad, PSDatNS, internal_T_L, internal_T_NS, gammaCal, gammaRec, a) - pdn(PSDatAnt, PSDatLoad, PSDatNS, internal_T_L, internal_T_NS, gammaCal, gammaRec, n)) \n # cant we just use pdn(a)?\n return comp\n \n increase = []\n if n[0] + stepSize < maxOrder: increase.append([n[0] + stepSize, n[1], n[2], n[3], n[4]])\n else: increase.append([maxOrder, n[1], n[2], n[3], n[4]])\n if n[1] + stepSize < maxOrder: increase.append([n[0], n[1] + stepSize, n[2], n[3], n[4]])\n else: increase.append([n[0], maxOrder, n[2], n[3], n[4]])\n if n[2] + stepSize < maxOrder: increase.append([n[0], n[1], n[2] + stepSize, n[3], n[4]])\n else: increase.append([n[0], n[1], maxOrder, n[3], n[4]])\n if n[3] + stepSize < maxOrder: increase.append([n[0], n[1], n[2], n[3] + stepSize, n[4]])\n else: increase.append([n[0], n[1], n[2], maxOrder, n[4]])\n if n[4] + stepSize < maxOrder: increase.append([n[0], n[1], n[2], n[3], n[4] + stepSize])\n else: increase.append([n[0], n[1], n[2], n[3], maxOrder])\n \n if iteration % printVals == 0: print('Trying: ', increase)\n m = max(increase, key = comparison) \n \n decrease = []\n if n[0] - stepSize > minOrder: decrease.append([n[0] - stepSize, n[1], n[2], n[3], n[4]])\n else: decrease.append([0, n[1], n[2], n[3], n[4]])\n if n[1] - stepSize > minOrder: decrease.append([n[0], n[1] - stepSize, n[2], n[3], n[4]])\n else: decrease.append([n[0], 0, n[2], n[3], n[4]])\n if n[2] - stepSize > minOrder: decrease.append([n[0], n[1], n[2] - stepSize, n[3], n[4]])\n else: decrease.append([n[0], n[1], 0, n[3], n[4]])\n if n[3] - stepSize > minOrder: decrease.append([n[0], n[1], n[2], n[3] - stepSize, n[4]])\n else: decrease.append([n[0], n[1], n[2], 0, n[4]])\n if n[4] - stepSize > minOrder: decrease.append([n[0], n[1], n[2], n[3], n[4] - stepSize])\n else: decrease.append([n[0], n[1], n[2], n[3], 0])\n \n if iteration % printVals == 0: print('Trying: ', decrease)\n j = max(decrease, key = comparison)\n \n if iteration % printVals == 0: print('Comparing: ', n, m, 'and', j)\n r = max([n, m, j], key = comparison)\n if iteration % printVals == 0: print('Taking: ', r)\n print('Iteration: ', iteration, ' Current n: ', r, 'Step Size:', stepSize)\n print()\n if np.array_equal(n, r): stepSize += 1\n else: n = r\n iteration += 1\n return n","sub_path":"February Calibration 2/februarysTest.py","file_name":"februarysTest.py","file_ext":"py","file_size_in_byte":9504,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"598451258","text":"#!/usr/bin/python3.4\n# -*- coding: utf-8 -*-\n# Pavel Ostyakov\n# pavelosta@gmail.com\n\nimport os\n\nfrom django.http import HttpResponse\nfrom django.http import HttpResponseRedirect\nfrom django.shortcuts import render_to_response\nfrom django.template import loader\nfrom django.template.context_processors import csrf\n\nfrom recommend.common import *\nfrom recommend.data import rating_load\nfrom recommend.get_recommend import get_recommend_news\nfrom recommend.news import check_model\nfrom recommend.news_slider import get_latest_news\n\ndatabase = pymongo.MongoClient(\"localhost\").lenta\n\n\ndef show_news_page(request, main_news=None, message=None, page=SITE_PAGE_ANOTHER, query=None):\n login = request.session.get('login')\n rating = rating_load(login)\n\n recommend_news = get_recommend_news((login, rating, login is None))\n\n recommend = []\n for news in recommend_news:\n temp = [news[\"Time\"], news[\"Image\"], news[\"Title\"], news[\"URL\"]]\n recommend.append(temp)\n\n if main_news:\n carousel_news = []\n i = 1\n for news in main_news:\n temp = [news[\"Category\"], news[\"Time\"], news[\"Image\"], news[\"Title\"], i % 3 == 0, news[\"URL\"]]\n carousel_news.append(temp)\n i += 1\n\n cont = {\"recommend\": recommend,\n \"login\": login is not None,\n \"CATEGORIES\": CATEGORIES,\n \"carousel\": True,\n \"carousel_news\": carousel_news,\n \"message\": message,\n \"page\": page,\n \"query\": query}\n else:\n cont = {\"recommend\": recommend,\n \"login\": login is not None,\n \"CATEGORIES\": CATEGORIES,\n \"carousel\": False,\n \"message\": message,\n \"page\": page,\n \"query\": query}\n\n cont = add_constants(cont)\n template = loader.get_template('lenta.html')\n return HttpResponse(template.render(context=cont))\n\n\ndef get_favourite(request, from_time):\n if not from_time:\n from_time = 2147483647\n favourite_news = []\n\n rating = rating_load(request.session.get('login'))\n\n for news in rating.keys():\n if not rating[news]:\n continue\n\n news_information = database.articles.find_one({\"URL\": news, \"Timestamp\": {\"$lt\": from_time}})\n if not news_information:\n continue\n favourite_news.append((news_information[\"Timestamp\"], news_information))\n\n favourite_news.sort(reverse=True, key=lambda x: x[0])\n\n return [favourite_news[i][1] for i in range(min(10, len(favourite_news)))]\n\n\ndef show_favourite(request):\n favourite_news = get_favourite(request, None)\n\n message = None\n if len(favourite_news) == 0:\n message = \"У вас пока что нет понравившихся новостей\"\n\n return show_news_page(request,\n message=message,\n page=SITE_PAGE_FAVOURITE)\n\n\ndef get_category_news(database, category, from_time):\n result = []\n if not from_time:\n from_time = 2147483647\n\n for news in database.articles.find(\n {\"Category\": category, \"Image\": {\"$ne\": None}, \"Timestamp\": {\"$lt\": from_time}}).sort(\"Timestamp\",\n pymongo.DESCENDING):\n result.append(news)\n if len(result) == 10:\n break\n return result\n\n\ndef show_category(request, category):\n import time\n all_time = time.time()\n response = show_news_page(request, page=category)\n print(\"Страница с категорией загружена за \", time.time() - all_time)\n return response\n\n\ndef show_news(request, year, month, day, name):\n login = request.session.get('login')\n rating = rating_load(login)\n\n url = \"/news/\" + str(year) + \"/\" + str(month) + \"/\" + str(day) + \"/\" + str(name) + \"/\"\n news = database.articles.find_one({\"URL\": url})\n\n news[\"Category\"] = news[\"Category\"][news[\"Category\"].rfind(\":\") + 1:]\n temp = [news[\"Category\"], news[\"Time\"], news[\"Image\"], news[\"Title\"], news[\"Text\"].split(\"\\n\\n\"), news[\"URL\"],\n rating.get(news[\"URL\"])]\n\n recommend_news = get_recommend_news((login, rating, login is None))\n\n recommend = []\n for news in recommend_news:\n new_recommend_news = [news[\"Time\"], news[\"Image\"], news[\"Title\"], news[\"URL\"]]\n recommend.append(new_recommend_news)\n\n cont = {\"news\": temp, \"recommend\": recommend, \"login\": login is not None,\n \"CATEGORIES\": CATEGORIES}\n\n template = loader.get_template('news.html')\n\n return HttpResponse(template.render(context=cont))\n\n\ndef show_enter(request):\n if request.session.get('login', None) is not None:\n return account(request)\n c = {}\n c.update(csrf(request))\n if request.session.get('exit'):\n c.update({\"message\": \"Вы вышли из аккаунта.\"})\n request.session['exit'] = None\n\n return render_to_response(\"enter.html\", c)\n\n\nmean = [[], [], []]\nmean_process = []\n\n\ndef recommend(request):\n if request.session.get('login', None) is None:\n return show_enter(request)\n\n import time\n all_time = time.time()\n\n login = request.session.get('login')\n rating = rating_load(login)\n\n model_address = \"models/\" + login + \".pkl\"\n general = not os.path.exists(model_address)\n if general:\n general = not check_model(rating, login)\n\n message = None\n if general:\n message = \"Рекомендаций для вашего аккаунта пока нет\"\n\n response = show_news_page(request, page=SITE_PAGE_RECOMMEND, message=message)\n print(\"Страница с рекомендациями загружена за \", time.time() - all_time)\n return response\n\n\ndef get_search_news(request, query, database, skip):\n if not skip:\n skip = 0\n\n founded = database.articles.aggregate(\n [{\"$match\":\n {\"$text\":\n {\"$search\": query\n }\n }\n },\n {\"$sort\":\n {\"score\":\n {\"$meta\": \"textScore\"\n },\n }\n },\n {\"$skip\": skip},\n {\"$limit\": 10}\n ], allowDiskUse=True\n )\n\n result = []\n\n i = 1\n for news in founded:\n news[\"Category\"] = news[\"Category\"][news[\"Category\"].rfind(\":\") + 1:]\n news[\"Timestamp\"] = skip + i\n i += 1\n result.append(news)\n if len(result) == 10:\n break\n\n return result\n\n\ndef search(request, query):\n database = pymongo.MongoClient(\"localhost\").lenta\n import time\n all_time = time.time()\n\n search_news = get_search_news(request, query, database, 0)\n\n message = None\n if len(search_news) == 0:\n message = \"Поиск не дал результатов\"\n\n response = show_news_page(request, message=message, page=SITE_PAGE_SEARCH, query=query)\n print(\"Страница с поиском загружена за \", time.time() - all_time)\n return response\n\n\ndef index(request):\n params = dict(request.GET)\n if params.get(\"search\"):\n return search(request, params.get(\"search\")[0])\n\n import time\n all_time = time.time()\n\n rating = rating_load(request.session.get('login'))\n\n response = show_news_page(\n request,\n main_news=get_latest_news(database, rating),\n page=SITE_PAGE_INDEX\n\n )\n print(\"Страница с новостями загружена за \", time.time() - all_time)\n return response\n\n\ndef registration(request):\n if request.session.get('login', None) is not None:\n return account(request)\n c = {}\n c.update(csrf(request))\n if request.method == 'POST':\n if request.POST['password'] != request.POST['password2']:\n c.update({'message': \"Пароли не совпадают. Попробуйте ещё раз\"})\n elif len(request.POST['password']) < 5:\n c.update({'message': \"Пароль должен содержать не менее 5 символов\"})\n elif database.users.find_one({\"Login\": request.POST['login']}) is not None:\n c.update({'message': \"Пользователь с таким логином уже зарегистрирован\"})\n else:\n database.users.insert_one({\"Login\": request.POST['login'], \"Name\": request.POST['name'],\n \"Password\": request.POST['password']})\n request.session['login'] = request.POST['login']\n return account(request)\n\n template = loader.get_template('registration.html')\n return HttpResponse(template.render(context=c))\n\n\ndef exit(request):\n request.session['login'] = None\n request.session['exit'] = True\n return HttpResponseRedirect(\"/enter\")\n\n\ndef enter(request):\n if request.method != 'POST':\n return show_enter(request)\n user = database.users.find_one({\"Login\": request.POST['login'], \"Password\": request.POST['password']})\n if user is None:\n c = {}\n c.update(csrf(request))\n c.update({\"message\": \"Неверный логин или пароль\"})\n return render_to_response(\"enter.html\", c)\n\n request.session['login'] = request.POST['login']\n request.session.modified = True\n return HttpResponseRedirect(\"/\")\n\n\ndef account(request):\n return HttpResponseRedirect(\"/\")\n","sub_path":"website/recommend/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":9432,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"551597212","text":"# -*- coding: utf-8 -*-\n# Copyright 2023 Google LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\nfrom __future__ import annotations\n\nfrom typing import MutableMapping, MutableSequence\n\nimport proto # type: ignore\n\n__protobuf__ = proto.module(\n package=\"google.cloud.securitycenter.v1\",\n manifest={\n \"SecurityMarks\",\n },\n)\n\n\nclass SecurityMarks(proto.Message):\n r\"\"\"User specified security marks that are attached to the parent\n Security Command Center resource. Security marks are scoped\n within a Security Command Center organization -- they can be\n modified and viewed by all users who have proper permissions on\n the organization.\n\n Attributes:\n name (str):\n The relative resource name of the SecurityMarks. See:\n https://cloud.google.com/apis/design/resource_names#relative_resource_name\n Examples:\n \"organizations/{organization_id}/assets/{asset_id}/securityMarks\"\n \"organizations/{organization_id}/sources/{source_id}/findings/{finding_id}/securityMarks\".\n marks (MutableMapping[str, str]):\n Mutable user specified security marks belonging to the\n parent resource. Constraints are as follows:\n\n - Keys and values are treated as case insensitive\n - Keys must be between 1 - 256 characters (inclusive)\n - Keys must be letters, numbers, underscores, or dashes\n - Values have leading and trailing whitespace trimmed,\n remaining characters must be between 1 - 4096 characters\n (inclusive)\n canonical_name (str):\n The canonical name of the marks. Examples:\n \"organizations/{organization_id}/assets/{asset_id}/securityMarks\"\n \"folders/{folder_id}/assets/{asset_id}/securityMarks\"\n \"projects/{project_number}/assets/{asset_id}/securityMarks\"\n \"organizations/{organization_id}/sources/{source_id}/findings/{finding_id}/securityMarks\"\n \"folders/{folder_id}/sources/{source_id}/findings/{finding_id}/securityMarks\"\n \"projects/{project_number}/sources/{source_id}/findings/{finding_id}/securityMarks\".\n \"\"\"\n\n name: str = proto.Field(\n proto.STRING,\n number=1,\n )\n marks: MutableMapping[str, str] = proto.MapField(\n proto.STRING,\n proto.STRING,\n number=2,\n )\n canonical_name: str = proto.Field(\n proto.STRING,\n number=3,\n )\n\n\n__all__ = tuple(sorted(__protobuf__.manifest))\n","sub_path":"packages/google-cloud-securitycenter/google/cloud/securitycenter_v1/types/security_marks.py","file_name":"security_marks.py","file_ext":"py","file_size_in_byte":3025,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"147153894","text":"# 变量的作用域\n'''\n变量的作用域:变量可以正常使用的范围。\n变量并不是在当前文件的任意位置均可使用,访问的权限范围取决于该变量定义\n的位置。\n\n在Python中,模块(module)、类(class)、函数(def)会产生新的作用域,在这些代码\n块中定义的变量,在其他位置也不能使用。\n其他的代码块,如if、for、while、try,不会引入新的作用域,在这些代码\n块中定义的变量,在其他位置也可以使用。\n\n变量的作用域分类:\nB(built-in) 内建作用域\nG(Global) 全局作用域\nE(Enclosing) 闭包作用域\nL(Local) 局部作用域\n\n变量的查找规则: L -> E -> G -> B\n先从局部查找,找到直接使用,找不到去闭包中找,找到直接使用,\n找不到去全局中找,找到直接使用,找不到去内建中找,找到直接使用,\n找不到报错。\n'''\n# 验证 if\nif 1:\n a = 10\n print(a)\nprint(a)\n\n# 验证 def\n# 函数内部声明的变量,在函数外部不能使用。\ndef func1():\n b = 200\n print(b)\nfunc1()\n# print(b) # NameError: name 'b' is not defined\nprint(\"********************************************************\")\n# 在.py文件中声明的变量为全局变量\nc = 200\nprint(c)\n\n# 作用域范围从大到小排列: B -> G -> E -> L\n# dir() Builtins python的内建函数:能够使用的范围为内建作用域 内建函数/内建变量\n# 内建变量或函数属于python语言环境范围的变量或函数。\n'''\ndir = 1 # Global 全局作用域 全局变量 在当前文件的任意位置均能使用\ndef outerFunc():\n dir = 2 # Enclosing 闭包作用域 在闭包范围内使用\n def innerFunc():\n dir = 3 # Local 局部作用域 只能在该局部范围内使用\n return innerFunc\n\ndef func():\n dir = 4 # Local 局部作用域 只能在该局部范围内使用\n'''\nprint(\"********************************************************\")\n# 定义一个全局范围的变量num\nnum = 100\nprint(\"1==\", num)\n\ndef func():\n # 定义了一个局部范围的变量num,只是该局部变量与全局变量名字相同。\n # 局部范围的变量与全局范围的变量互不影响。\n # 如果变量没有global修饰,就是一个局部变量,不能修改全局变量。\n num = 200\n print(\"2==\", num)\nfunc()\nprint(\"3==\",num)\n\n\nnum1 = 100\nprint(num1)\n\ndef func2():\n # 在局部范围修改全局变量使用global关键字修饰变量\n # 语法规则: global 变量名\n # 使用global关键字修饰的变量为全局变量,该局部范围直接可以获取及\n # 修改全局变量。\n # 当同时使用多个全局变量时,使用 逗号 (,) 隔开\n # 注:使用global关键字,需要放在函数的最上方,函数的最开始位置。\n global num1,num\n num1 = 200\n print(num1)\n num = 800\n print(num)\n\nfunc2()\nprint(num1)\nprint(num)\n\n\n# nonlocal 非局部\ni = 777 # 全局\ndef outerFunc():\n i = 666 # 局部\n def innerFunc():\n nonlocal i # nonlocal 修饰局部变量\n i = 555 # 局部范围的局部变量\n print(\"inner==\", i)\n innerFunc()\n print(\"outer==\",i)\n\nouterFunc()\nprint(i)\n\nprint(\"******************************\")\ndef a():\n i = 1\n def b():\n nonlocal i\n i = 2\n def c():\n nonlocal i\n i = 3\n print(\"c==\",i)\n c()\n print(\"b==\",i)\n b()\n print(\"a==\",i)\na()\n\n\nname = \"Lily\" # 全局变量\ndef changeFunc():\n global name\n name = \"Lucy\"\n def inner():\n global name\n name = \"张三\"\n print(name)\n inner()\n print(name)\nchangeFunc()\nprint(name)\n\n\n\n\n\n","sub_path":"Day08/2-代码/作用域/2-变量的作用域.py","file_name":"2-变量的作用域.py","file_ext":"py","file_size_in_byte":3694,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"623805494","text":"# -*- coding: utf-8 -*-\n\nfrom django.conf.urls import url\n\nfrom apps.persons.views import *\n\nurlpatterns = [\n url(r'^$', PersonListView.as_view(), name='list'),\n url(r'^stats$', PersonAllStatsView.as_view(), name='allstats'),\n url(r'(?P\\d+)/$', PersonDetailView.as_view(), name='detail')\n]\n","sub_path":"apps/persons/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":303,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"548786511","text":"import json\nimport os\n\n\nclass Modifier:\n \"\"\"An Object containing all relevant information about one skin tone Modifier\"\"\"\n\n def __init__(self, name: str, colors: dict, extension: str, tolerance: int = 16, *args, **kwargs):\n \"\"\"\n Creates a new skin tone modifier\n :param name: The name of this skin tone\n :param colors: All colors in 'name: color hex'-format\n :param extension: All characters to be added to the original emoji sequence (e.g. _200d_1f3b0)\n :param tolerance: The color 'radius' which is matched\n \"\"\"\n self.name = name\n self.colors = colors\n self.extension = extension\n self.tolerance = tolerance\n\n def replace(self, colors, base) -> dict:\n \"\"\"\n Creates a dict containing all color replacements\n :param colors: A dict containing the original color strings and their RGB values\n :param base: The base Modifier\n :return: A dict containing the replacement rules as from: to (they can be applied by using simple string substitution)\n \"\"\"\n # Create a new list\n replace = list()\n # The base colors as a RGBA: hex string dict\n basecolors = Modifier.build_rgb(base)\n\n # Go through all the colors that have been found\n for old_color, value in colors.items():\n # ...And try to find a matching base color\n for base_value, color_name in basecolors.items():\n # Also match some surrounding colors\n if Modifier.eucl_dist(value, base_value) <= self.tolerance:\n # It's a match!\n try:\n # Try to find an appropiate replacement\n new_color = self.colors[color_name]\n replace.append((old_color, new_color))\n except KeyError:\n try:\n # We'll now try to ignore any extensions added with '_'\n # (e.g. \"hand_2\" -> \"hand\", \"skin_boo_ya\" -> \"skin\")\n new_color = self.colors[color_name.split('_')[0]]\n replace.append((old_color, new_color))\n except KeyError:\n # Replacement not found\n print('Didn\\'t find replacement for color {} from {} (Name: \"{}\" or \"{}\") in {}.'.format(value, base.name, color, color.split('_')[0], self.name)) \n return dict(replace)\n\n @staticmethod\n def eucl_dist(a, b):\n \"\"\"\n Returns the euclidean distance between two tuples\n :param a: The first tuple\n :param b: The second tuple\n :return: Their euclidean distance\n \"\"\"\n pairs = zip(a,b)\n dist = map(lambda x: (x[0]-x[1])**2, pairs)\n return sum(dist)**(1/2)\n\n def build_rgb(self) -> dict:\n \"\"\"\n Returns the colors dict with the RGBA values as a tuple instead of a hex string and with the colors as keys\n :return: A dict with RGBA tuple:color name\n \"\"\"\n colors = list()\n for name, value in self.colors.items():\n # Get rid of the #\n value = value.replace('#','').strip()\n value = [value[0:2], value[2:4], value[4:6], value[6:8]]\n # Add an alpha value if necessary\n if not value[3]:\n value[3] = 'ff'\n value = tuple(int(v, 16) for v in value)\n colors.append((value, name))\n return dict(colors)\n\n @staticmethod\n def generate_from_json(file: str):\n \"\"\"\n Creates a new Modifier object out of a JSON file\n :param file: The file path\n :return: A new Modifier parsed from this JSON file\n \"\"\"\n try:\n # Open file\n with open(file) as json_file:\n # Load JSON table\n jdict = json.loads(json_file.read())\n # Do we have a name?\n if 'name' in jdict:\n return Modifier(**jdict)\n else:\n # If not, we'll just use the file name\n return Modifier(name= os.path.splitext(os.path.basename(file))[0], **jdict)\n except FileNotFoundError:\n print(\"File not found ¯\\_(ツ)_/¯\")\n except json.JSONDecodeError:\n print(\"This is not a valid JSON file >:(\")\n\n def __str__(self):\n return '{} (uxxxx_{}): Skin tone modifier with {} different colors'.format(self.name, self.extension, len(self.colors))\n\n def detailed_info(self) -> str:\n \"\"\"\n Returns more detailed information on this Modifier \n :return: A str containing some details\n \"\"\"\n return '{} (uxxxx_{}):\\n {}'.format(self.name, self.extension, '\\n '.join([': '.join(item) for item in list(self.colors.items())]))\n\n\nclass HexString:\n \"\"\"\n This is a simple data type to handle conversions and some basic operations on hexadecimal strings.\n \"\"\"\n\n def __init__(self, string: str, min_: int = 0, max_: int = 0xff, length: int = 2):\n \"\"\"\n Create a new HexString\n :param string: The string representation without the 0x-prefix\n :param min_: The min allowed value\n :param max_: The max allowed value\n :param length: The max zfill length\n \"\"\"\n self.string = string.zfill(length)\n self.value = int(string, 16)\n self.min_ = min_\n self.max_ = max_\n self.length = length\n\n def __add__(self, other):\n \"\"\"\n Add another HexString or int\n :param other: summand\n :return: A new HexString with this operation applied\n \"\"\"\n if type(other) == int:\n # Add\n result = HexString(hex(self.value + other)[2:], self.min_, self.max_)\n # Test for range\n if result.value in range(self.min_, self.max_ + 1):\n return result\n else:\n raise ValueError('Value not in allowed range')\n if type(other) == HexString:\n # Add\n result = HexString(hex(self.value + other.value)[2:], self.min_, self.max_)\n # Test for range\n if result.value in range(self.min_, self.max_ + 1):\n return result\n else:\n raise ValueError('Value not in allowed range')\n\n def __sub__(self, other):\n \"\"\"\n Sub another HexString or int\n :param other: Subtrahend\n :return: A new HexString with this operation applied\n \"\"\"\n if type(other) == int:\n # Sub\n result = HexString(hex(self.value - other)[2:], self.min_, self.max_)\n # Test for range\n if result.value in range(self.min_, self.max_ + 1):\n return result\n else:\n raise ValueError('Value not in allowed range')\n if type(other) == HexString:\n # Sub\n result = HexString(hex(self.value - other.value)[2:], self.min_, self.max_)\n # Test for range\n if result.value in range(self.min_, self.max_ + 1):\n return result\n else:\n raise ValueError('Value not in allowed range')\n\n def __mul__(self, other):\n result = HexString(hex(self.value * other)[2:], self.min_, self.max_)\n # Test for range\n if result.value in range(self.min_, self.max_ + 1):\n return result\n else:\n raise ValueError('Value not in allowed range')\n\n def __len__(self):\n return self.length\n\n def __str__(self):\n return self.string.zfill(self.length)\n","sub_path":"skintone/modifier.py","file_name":"modifier.py","file_ext":"py","file_size_in_byte":7649,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"509662137","text":"# -*- coding:utf-8 -*-\n'''\nclass Solution:\n def __init__(self):\n self.arr = []\n def Permutation(self, ss):\n # write code here\n if(ss == ''):\n return ''\n if(len(ss) == 1):\n return [ss]\n # ss = sorted(ss) # 先对字符串进行排序\n temp = ''\n self.digui(ss, temp)\n return sorted(self.arr)\n \n\n def digui(self, ss, temp):\n if(len(ss) == 0):\n if(temp not in self.arr):\n self.arr.append(a)\n return\n i = 0\n length = len(ss)\n while(i < length):\n temp += ss[i]\n self.digui(ss[0:i]+ss[i+1:], temp)\n temp = temp[0:-1]\n i = i + 1\n'''\nclass Solution:\n def __init__(self):\n self.arr = []\n def Permutation(self, ss):\n # write code here\n if(ss == ''):\n return ''\n ss = sorted(ss)\n self.arr.append(''.join(ss))\n length = len(ss)\n while(True):\n fromIndex = length - 1\n for i in range(length-1, 0, -1):\n if(ss[i-1] < ss[i]):\n break\n fromIndex -= 1\n if(fromIndex == 0):\n break\n changeIndex = fromIndex - 1\n\n for i in range(fromIndex, length):\n if(ss[i] <= ss[fromIndex-1]): # 如果没有等于号,会在字符串中存在相同字符时死循环\n break\n changeIndex += 1\n temp = ss[fromIndex-1]\n ss[fromIndex-1] = ss[changeIndex]\n ss[changeIndex] = temp\n ss = ss[0:fromIndex] + ss[fromIndex:][::-1]\n\n self.arr.append(''.join(ss))\n return self.arr\n\nif __name__ == \"__main__\":\n sol = Solution()\n a = sol.Permutation('1223')\n print(a)","sub_path":"AimAtOffer/Permutation/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1831,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"123444582","text":"from django.contrib.sites.models import Site\n\nfrom allauth.socialaccount.adapter import get_adapter\nfrom allauth.socialaccount.models import SocialApp\n\n\ndef test_list_db_based_apps(db, settings):\n app = SocialApp.objects.create(\n provider=\"saml\", provider_id=\"urn:idp-identity-id\", client_id=\"org-slug\"\n )\n app.sites.add(Site.objects.get_current())\n apps = get_adapter().list_apps(None, provider=\"saml\", client_id=\"org-slug\")\n assert app.pk in [a.pk for a in apps]\n\n\ndef test_list_settings_based_apps(db, settings):\n settings.SOCIALACCOUNT_PROVIDERS = {\n \"saml\": {\n \"APPS\": [\n {\n \"provider_id\": \"urn:idp-entity-id\",\n \"client_id\": \"org-slug\",\n }\n ]\n }\n }\n apps = get_adapter().list_apps(None, provider=\"saml\", client_id=\"org-slug\")\n assert len(apps) == 1\n app = apps[0]\n assert not app.pk\n assert app.client_id == \"org-slug\"\n","sub_path":"allauth/socialaccount/tests/test_adapter.py","file_name":"test_adapter.py","file_ext":"py","file_size_in_byte":971,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"138028903","text":"\"\"\"Python implementation of the Earth Explorer API.\"\"\"\n\nimport json\nfrom urllib.parse import urljoin\nimport string\nimport random\nimport time\n\nimport requests\nfrom shapely.geometry import Point\n\nfrom landsatxplore.errors import USGSAuthenticationError, USGSError, USGSRateLimitError\n\n\nAPI_URL = \"https://m2m.cr.usgs.gov/api/api/json/stable/\"\n\n\ndef _random_string(length=10):\n \"\"\"Generate a random string.\"\"\"\n letters = string.ascii_lowercase\n return \"\".join(random.choice(letters) for i in range(length))\n\n\nclass API(object):\n \"\"\"EarthExplorer API.\"\"\"\n\n def __init__(self, username, password):\n \"\"\"EarthExplorer API.\n\n Parameters\n ----------\n username : str\n USGS EarthExplorer username.\n password : str\n USGS EarthExplorer password.\n \"\"\"\n self.url = API_URL\n self.session = requests.Session()\n self.login(username, password)\n\n @staticmethod\n def raise_api_error(response):\n \"\"\"Parse API response and return the appropriate exception.\n\n Parameters\n ----------\n response : requests response\n Response from USGS API.\n \"\"\"\n data = response.json()\n error_code = data.get(\"errorCode\")\n error_msg = data.get(\"errorMessage\")\n if error_code:\n if error_code in (\"AUTH_INVALID\", \"AUTH_UNAUTHROIZED\", \"AUTH_KEY_INVALID\"):\n raise USGSAuthenticationError(f\"{error_code}: {error_msg}.\")\n elif error_code == \"RATE_LIMIT\":\n raise USGSRateLimitError(f\"{error_code}: {error_msg}.\")\n else:\n raise USGSError(f\"{error_code}: {error_msg}.\")\n\n def request(self, endpoint, params=None):\n \"\"\"Perform a request to the USGS M2M API.\n\n Parameters\n ----------\n endpoint : str\n API endpoint.\n params : dict, optional\n API parameters.\n\n Returns\n -------\n data : dict\n JSON data returned by the USGS API.\n\n Raises\n ------\n USGSAuthenticationError\n If credentials are not valid of if user lacks permission.\n USGSError\n If the USGS API returns a non-null error code.\n \"\"\"\n url = urljoin(self.url, endpoint)\n data = json.dumps(params)\n r = self.session.get(url, data=data)\n try:\n self.raise_api_error(r)\n except USGSRateLimitError:\n time.sleep(3)\n r = self.session.get(url, data=data)\n self.raise_api_error(r)\n return r.json().get(\"data\")\n\n def login(self, username, password):\n \"\"\"Get an API key.\n\n Parameters\n ----------\n username : str\n EarthExplorer username.\n password : str\n EarthExplorer password.\n \"\"\"\n login_url = urljoin(self.url, \"login\")\n payload = {\"username\": username, \"password\": password}\n r = self.session.post(login_url, json.dumps(payload))\n self.raise_api_error(r)\n self.session.headers[\"X-Auth-Token\"] = r.json().get(\"data\")\n\n def logout(self):\n \"\"\"Logout from USGS M2M API.\"\"\"\n self.request(\"logout\")\n self.session = requests.Session()\n\n def get_scene_id(self, product_id, dataset):\n \"\"\"Get scene ID from product ID.\n\n Note\n ----\n As the lookup endpoint has been removed in API v1.5, the function makes\n successive calls to scene-list-add and scene-list-get in order to retrieve\n the scene IDs. A temporary sceneList is created and removed at the end of the\n process.\n\n Parameters\n ----------\n product_id : str or list of str\n Input product ID. Can also be a list of product IDs.\n dataset : str\n Dataset alias.\n\n Returns\n -------\n scene_id : str or list of str\n Output scene ID. Can also be a list of scene IDs depending on input.\n \"\"\"\n # scene-list-add support both entityId and entityIds input parameters\n param = \"entityId\"\n if isinstance(product_id, list):\n param = \"entityIds\"\n\n # a random scene list name is created -- better error handling is needed\n # to ensure that the temporary scene list is removed even if scene-list-get\n # fails.\n list_id = _random_string()\n self.request(\n \"scene-list-add\",\n params={\n \"listId\": list_id,\n \"datasetName\": dataset,\n \"idField\": \"displayId\",\n param: product_id,\n },\n )\n r = self.request(\"scene-list-get\", params={\"listId\": list_id})\n scene_id = [scene[\"entityId\"] for scene in r]\n self.request(\"scene-list-remove\", params={\"listId\": list_id})\n\n if param == \"entityId\":\n return scene_id[0]\n else:\n return scene_id\n\n @staticmethod\n def parse_metadata(response):\n \"\"\"Parse metadata from API response.\n\n Parameters\n ----------\n response : requests response\n As returned by api.request(\"scene-metadata\").\n\n Returns\n -------\n scene_metadata : dict\n Metadata parsed into a dict.\n \"\"\"\n scene_metadata = {}\n for key, value in response.items():\n if key in (\"browse\", \"metadata\"):\n continue\n else:\n scene_metadata[key] = value\n\n for field in response[\"metadata\"]:\n label = field[\"dictionaryLink\"].split(\"#\")[-1].strip()\n if label in (\"coordinate_degrees\", \"coordinate_decimal\"):\n continue\n scene_metadata[label] = field[\"value\"]\n\n return scene_metadata\n\n def metadata(self, scene_id, dataset):\n \"\"\"Get metadata for a given scene.\n\n Parameters\n ----------\n scene_id : str\n Landsat scene identifier.\n dataset : str\n Dataset alias.\n\n Returns\n -------\n meta : dict\n Scene metadata.\n \"\"\"\n r = self.request(\n \"scene-metadata\",\n params={\n \"datasetName\": dataset,\n \"entityId\": scene_id,\n \"metadataType\": \"full\",\n },\n )\n return self.parse_metadata(r)\n\n def get_product_id(self, scene_id, dataset):\n \"\"\"Get product ID from scene ID.\n\n Parameters\n ----------\n scene_id : str\n Landsat scene identifier.\n dataset : str\n Dataset alias.\n\n Returns\n -------\n product_id : str\n Landsat product identifier.\n \"\"\"\n meta = self.metadata(scene_id, dataset)\n return meta[\"displayId\"]\n\n def search(\n self,\n dataset,\n longitude=None,\n latitude=None,\n bbox=None,\n max_cloud_cover=None,\n start_date=None,\n end_date=None,\n months=None,\n max_results=100,\n ):\n \"\"\"Search for scenes.\n\n Parameters\n ----------\n dataset : str\n Case-insensitive dataset alias (e.g. landsat_tm_c1).\n longitude : float, optional\n Longitude of the point of interest.\n latitude : float, optional\n Latitude of the point of interest.\n bbox : tuple, optional\n (xmin, ymin, xmax, ymax) of the bounding box.\n max_cloud_cover : int, optional\n Max. cloud cover in percent (1-100).\n start_date : str, optional\n YYYY-MM-DD\n end_date : str, optional\n YYYY-MM-DD. Equal to start_date if not provided.\n months : list of int, optional\n Limit results to specific months (1-12).\n max_results : int, optional\n Max. number of results. Defaults to 100.\n\n Returns\n -------\n scenes : list of dict\n Matching scenes as a list of dict containing metadata.\n \"\"\"\n spatial_filter = None\n if longitude and latitude:\n spatial_filter = SpatialFilterMbr(*Point(longitude, latitude).bounds)\n elif bbox:\n spatial_filter = SpatialFilterMbr(*bbox)\n\n acquisition_filter = None\n if start_date and end_date:\n acquisition_filter = AcquisitionFilter(start_date, end_date)\n\n cloud_cover_filter = None\n if max_cloud_cover:\n cloud_cover_filter = CloudCoverFilter(\n max=max_cloud_cover, include_unknown=False\n )\n\n scene_filter = SceneFilter(\n acquisition_filter, spatial_filter, cloud_cover_filter, months=months\n )\n\n r = self.request(\n \"scene-search\",\n params={\n \"datasetName\": dataset,\n \"sceneFilter\": scene_filter,\n \"maxResults\": max_results,\n },\n )\n return [self.parse_metadata(scene) for scene in r.get(\"results\")]\n\n\nclass Coordinate(dict):\n \"\"\"A coordinate object as expected by the USGS M2M API.\n\n Parameters\n ----------\n longitude : float\n Decimal longitude.\n latitude : float\n Decimal latitude.\n \"\"\"\n\n def __init__(self, longitude, latitude):\n self[\"longitude\"] = longitude\n self[\"latitude\"] = latitude\n\n\nclass GeoJson(dict):\n \"\"\"A GeoJSON object as expected by the USGS M2M API.\n\n Parameters\n ----------\n shape : dict\n Input geometry as a geojson-like dict.\n \"\"\"\n\n def __init__(self, shape):\n self[\"type\"] = shape[\"type\"]\n self[\"coordinates\"] = self.transform(shape[\"type\"], shape[\"coordinates\"])\n\n @staticmethod\n def transform(type, coordinates):\n \"\"\"Convert geojson-like coordinates as expected by the USGS M2M API.\n\n Essentially converts tuples of coordinates to api.Coordinate objects.\n \"\"\"\n if type == \"MultiPolygon\":\n return [\n [Coordinate(*point) for point in polygon] for polygon in coordinates[0]\n ]\n elif type == \"Polygon\":\n return [Coordinate(*point) for point in coordinates[0]]\n elif type == \"LineString\":\n return [Coordinate(*point) for point in coordinates]\n elif type == \"Point\":\n return Coordinate(*coordinates)\n else:\n raise ValueError(f\"Geometry type `{type}` not supported.\")\n\n\nclass SpatialFilterMbr(dict):\n \"\"\"Bounding box spatial filter.\n\n Parameters\n ----------\n xmin : float\n Min. decimal longitude.\n ymin : float\n Min. decimal latitude.\n xmax : float\n Max. decimal longitude.\n ymax : float\n Max. decimal latitude.\n \"\"\"\n\n def __init__(self, xmin, ymin, xmax, ymax):\n self[\"filterType\"] = \"mbr\"\n self[\"lowerLeft\"] = Coordinate(xmin, ymin)\n self[\"upperRight\"] = Coordinate(xmax, ymax)\n\n\nclass SpatialFilterGeoJSON(dict):\n \"\"\"GeoJSON-based spatial filter.\n\n Parameters\n ----------\n shape : dict\n Input shape as a geojson-like dict.\n \"\"\"\n\n def __init__(self, shape):\n self[\"filterType\"] = \"geoJson\"\n self[\"geoJson\"] = GeoJson(shape)\n\n\nclass AcquisitionFilter(dict):\n \"\"\"Acquisition date filter.\n\n Parameters\n ----------\n start : str\n ISO 8601 start date.\n end : str\n ISO 8601 end date.\n \"\"\"\n\n def __init__(self, start, end):\n self[\"start\"] = start\n self[\"end\"] = end\n\n\nclass CloudCoverFilter(dict):\n \"\"\"Cloud cover filter.\n\n Parameters\n ----------\n min : int, optional\n Min. cloud cover in percents (default=0).\n max : int, optional\n Max. cloud cover in percents (default=100).\n include_unknown : bool, optional\n Include scenes with unknown cloud cover (default=False).\n \"\"\"\n\n def __init__(self, min=0, max=100, include_unknown=False):\n self[\"min\"] = min\n self[\"max\"] = max\n self[\"includeUnknown\"] = include_unknown\n\n\nclass MetadataValue(dict):\n \"\"\"Metadata filter.\n\n Parameters\n ----------\n field_id : str\n ID of the field.\n value : str, float or int\n Value of the field.\n \"\"\"\n\n def __init__(self, field_id, value):\n self[\"filterType\"] = \"value\"\n self[\"filterId\"] = field_id\n self[\"value\"] = value\n if isinstance(value, str):\n self[\"operand\"] = \"like\"\n else:\n self[\"operand\"] = \"=\"\n\n\nclass SceneFilter(dict):\n \"\"\"Scene search filter.\n\n Parameters\n ----------\n acquisition_filter : AcquisitionFilter, optional\n Acquisition date filter.\n spatial_filter : SpatialFilterMbr or SpatialFilterGeoJson, optional\n Spatial filter.\n cloud_cover_filter : CloudCoverFilter, optional\n Cloud cover filter.\n metadata_filter : MetadataValue, optional\n Metadata filter.\n months : list of int, optional\n Seasonal filter (month numbers from 1 to 12).\n \"\"\"\n\n def __init__(\n self,\n acquisition_filter=None,\n spatial_filter=None,\n cloud_cover_filter=None,\n metadata_filter=None,\n months=None,\n ):\n if acquisition_filter:\n self[\"acquisitionFilter\"] = acquisition_filter\n if spatial_filter:\n self[\"spatialFilter\"] = spatial_filter\n if cloud_cover_filter:\n self[\"cloudCoverFilter\"] = cloud_cover_filter\n if metadata_filter:\n self[\"metadataFilter\"] = metadata_filter\n if months:\n self[\"seasonalFilter\"] = months\n","sub_path":"landsatxplore/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":13535,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"13276018","text":"\nfrom gym.spaces import Discrete\nimport numpy as np\n\nfrom admiral.envs import Agent, AgentBasedSimulation\n\nclass Corridor(AgentBasedSimulation):\n \"\"\"\n Simple Corridor Environment used for testing. A single agent start at position\n 0 and can choose to move left, right, or stay still. The agent must learn to \n move to the right until it reaches the end position. If the agent attempts\n to move left from the start position, it will remain in that start position.\n\n The agent can observe its own position.\n \"\"\"\n from enum import IntEnum\n class Actions(IntEnum):\n LEFT = 0\n STAY = 1\n RIGHT = 2\n\n def __init__(self, config): \n self.start = 0\n self.end = config['end']\n self.agents = config['agents']\n \n def reset(self, **kwargs):\n self.pos = self.start\n \n def step(self, actions, **kwargs):\n action = actions['agent0']\n if action == self.Actions.LEFT and self.pos != self.start:\n self.pos -= 1\n elif action == self.Actions.RIGHT:\n self.pos += 1\n # else: Don't move\n # self.pos = self.pos\n\n def render(self, *args, fig=None, **kwargs):\n \"\"\"\n Visualize the state of the environment. If a figure is received, then we\n will draw but not actually plot because we assume the caller will do the\n work (e.g. with an Animation object). If there is no figure received, then\n we will draw and plot the environment.\n \"\"\"\n draw_now = fig is None\n if draw_now:\n from matplotlib import pyplot as plt\n fig = plt.gcf()\n\n fig.clear()\n ax = fig.gca()\n ax.set(xlim=(-0.5, self.end + 0.5), ylim=(-0.5, 0.5))\n ax.set_xticks(np.arange(-0.5, self.end + 0.5, 1.))\n ax.scatter(self.pos, 0, marker='s', s=200, c='g')\n \n if draw_now:\n plt.plot()\n plt.pause(1e-17)\n \n def get_obs(self, agent_id, **kwargs):\n return self.pos\n \n def get_reward(self, agent_id, **kwargs):\n return 10 if self.pos == self.end else -1\n \n def get_done(self, agent_id, **kwargs):\n return self.pos == self.end\n \n def get_all_done(self, **kwargs):\n return self.pos == self.end\n \n def get_info(self, agent_id, **kwargs):\n return {}\n \n @classmethod\n def build(cls, env_config={}):\n config = {\n 'end': 5,\n # agents determined after end is set\n }\n\n config['end'] = env_config.get('end', config['end'])\n config['agents'] = {'agent0': Agent(\n 'agent0',\n Discrete(config['end'] + 1),\n Discrete(3)\n )}\n\n return cls(config)\n","sub_path":"admiral/envs/corridor/corridor.py","file_name":"corridor.py","file_ext":"py","file_size_in_byte":2725,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"206660756","text":"#!/usr/bin/env python\n\"\"\"Test the functionality of Prototypes\"\"\"\n\nimport logging\nlogger = logging.getLogger(__name__)\n\nfrom mock import Mock\nfrom nose.tools import assert_raises, eq_\nfrom prototype import Resource\nfrom tests.test_common import SAMPLES\n\n__author__ = 'Clayton Daley III'\n__copyright__ = \"Copyright 2015, Clayton Daley III\"\n__license__ = \"Apache License 2.0\"\n__version__ = \"2.0.0\"\n__maintainer__ = \"Clayton Daley III\"\n__status__ = \"Development\"\n\n\ndef getattr_attributeerror(object_, attribute):\n assert_raises(AttributeError, getattr, object_, attribute)\n\n\ndef getattr_keyerror(object_, attribute):\n assert_raises(KeyError, getattr, object_, attribute)\n\n\ndef getattr_typeerror(object_, attribute):\n assert_raises(TypeError, getattr, object_, attribute)\n\n\ndef setattr_eq(object_, attribute, value):\n object_.__setattr__(attribute, value)\n eq_(getattr(object_, attribute), value)\n\n\ndef setattr_attributeerror(object_, attribute, value):\n assert_raises(AttributeError, object_.__setattr__, attribute, value)\n\n\ndef setattr_keyerror(object_, attribute, value):\n assert_raises(KeyError, object_.__setattr__, attribute, value)\n\n\ndef setattr_typeerror(object_, attribute, value):\n assert_raises(TypeError, object_.__setattr__, attribute, value)\n\n\nclass PropertiesStub(Resource):\n PROPERTIES = {\n '_readonly': object,\n 'editable': object,\n }\n\n\ndef test_resource_setattr_readonly():\n \"\"\"\n Readonly attributes are indicated by a leading underscore and should throw a KeyError\n \"\"\"\n stub = PropertiesStub()\n mock = Mock()\n yield setattr_keyerror, stub, 'readonly', mock\n\n\ndef test_resource_setattr_editable():\n \"\"\"\n Editable attributes do not have a leading underscore and are stored inside the 'dirty' table\n \"\"\"\n stub = PropertiesStub()\n mock = Mock()\n yield setattr_eq, stub, 'editable', mock\n\n\ndef test_resource_setattr_nonproperty():\n \"\"\"\n If an attribute is not a member of properties, an AttributeError should be generated\n \"\"\"\n stub = PropertiesStub()\n mock = Mock()\n yield setattr_attributeerror, stub, 'nonproperty', mock\n\n\ndef test_generator_setattr_typechecking():\n \"\"\"\n setattr should provide type checking based on PROPERTIES definition\n \"\"\"\n for type in SAMPLES:\n mock = Mock(Resource)\n object.__setattr__(mock, 'PROPERTIES', {'key': type})\n object.__setattr__(mock, '_dirty', dict())\n for t2, samples in SAMPLES.iteritems():\n if not isinstance(t2, type):\n for sample in samples:\n yield setattr_eq, mock, 'key', sample\n else:\n for sample in samples:\n yield setattr_typeerror, mock, 'key', sample\n\n\ndef is_attribute_unchanged_data(value):\n mock = Mock(Resource)\n object.__setattr__(mock, 'PROPERTIES', {'key': object})\n object.__setattr__(mock, '_data', {'key': value})\n object.__setattr__(mock, '_dirty', dict())\n mock.key = value\n assert 'key' not in mock._dirty\n\n\ndef test_generator_is_attribute_unchanged():\n \"\"\"\n If an attribute is unchanged, we should not store it in 'dirty'. This should use the 'is' operator to preserve\n mutability.\n \"\"\"\n for value in [v[0] for k, v in SAMPLES.iteritems()]:\n yield is_attribute_unchanged_data, value\n\n\nEQ_NOT_IS = [\n [1000000, 10 ** 6],\n [[0, 1], [0, 1]],\n [{}, {}],\n [{'key': 'value'}, {'key': 'value'}]\n]\n\n\ndef eq_attribute_changed_data(value, compare):\n # sample values are equal\n assert value == compare\n # sample values are not the same\n assert value is not compare\n mock = Resource()\n object.__setattr__(mock, 'PROPERTIES', {'key': object})\n mock.key = compare\n assert 'key' in mock._dirty\n # Confirm that the key is updated\n assert mock.key is compare\n assert mock.key is not value\n\n\ndef test_generator_equal_attribute_replace():\n \"\"\"\n If an attribute is equal but not \"is\", we need to update it to preserve mutability.\n \"\"\"\n for values in EQ_NOT_IS:\n yield eq_attribute_changed_data, values[0], values[1]","sub_path":"tests/test_prototypes.py","file_name":"test_prototypes.py","file_ext":"py","file_size_in_byte":4112,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"384218542","text":"import sqlite3\nimport helpers\n\nconn = sqlite3.connect(helpers.get_file_path('../databases/flights.db'))\ncur = conn.cursor()\ncur.execute('''\n SELECT country, count(country) as airline_count\n FROM airlines\n GROUP BY country\n HAVING airline_count > 60\n ORDER BY airline_count desc;\n''')\nresults = cur.fetchall()\ncur.close()\nconn.close()\n\nfor row in results:\n print(row)","sub_path":"course-files/lectures/lecture_13/scripts/11_query_group_by_having.py","file_name":"11_query_group_by_having.py","file_ext":"py","file_size_in_byte":383,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"145311848","text":"import csv\nmy_file = open('exmaple.csv')\nfile_reader = csv.reader(my_file)\nmy_data = list(file_reader)\n\n# we use this method to open and read from a csv\n# then we turn what we read in a list\n# each line in the csv will be an element in the list\n\n\n","sub_path":"Desktop/coding_testing/udemy_python/helloworld/classroom11.py","file_name":"classroom11.py","file_ext":"py","file_size_in_byte":247,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"520923548","text":"import socket\nimport select\nimport threading\nimport sys\nimport time\n\n\nhost = 'localhost'\nport = 12802\n\nclass ThreadClient(threading.Thread):\n def __init__(self, co):\n threading.Thread.__init__(self)\n self.life = 17\n self.connexion = co\n self.oponent = None\n self.nom = None\n\n def run(self):\n self.connexion.send(bytes(\"SENDPSEUDO\", 'UTF-8'))\n self.nom = self.connexion.recv(1024).decode()\n print(self.nom)\n if self.oponent is not None:\n self.connexion.send(bytes(\"GO\", 'UTF-8'))\n self.oponent.connexion.send(bytes(\"GO\", 'UTF-8'))\n time.sleep(0.5)\n turn = 1\n ok = True\n while ok:\n if turn == 1:\n self.connexion.send(bytes(\"SENDATK\", 'UTF-8'))\n time.sleep(0.5)\n temp = self.connexion.recv(1024)\n time.sleep(0.5)\n self.oponent.connexion.send(temp)\n time.sleep(0.5)\n msg = self.oponent.connexion.recv(1024).decode()\n if msg == '':\n msg = 0\n id = int(msg)\n print(id)\n if int(id) != 0:\n self.connexion.send(bytes(\"1\", 'UTF-8'))\n time.sleep(0.5)\n if int(id) != 9:\n self.oponent.life -= 1\n if self.oponent.life == 0:\n self.connexion.send(bytes(\"GAGNE\", 'UTF-8'))\n self.oponent.connexion.send(bytes(\"PERDU\", 'UTF-8'))\n ok = False\n else:\n self.connexion.send(bytes(\"0\", 'UTF-8'))\n turn = 2\n else:\n self.oponent.connexion.send(bytes(\"SENDATK\", 'UTF-8'))\n time.sleep(0.5)\n temp = self.oponent.connexion.recv(1024)\n time.sleep(0.5)\n self.connexion.send(temp)\n time.sleep(0.5)\n msg = self.connexion.recv(1024).decode()\n if msg == '':\n msg = 0\n id = int(msg)\n print(id)\n if int(id) != 0:\n self.oponent.connexion.send(bytes(\"1\", 'UTF-8'))\n time.sleep(0.5)\n if int(id) != 9:\n self.life -= 1\n if self.life == 0:\n self.oponent.connexion.send(bytes(\"GAGNE\", 'UTF-8'))\n self.connexion.send(bytes(\"PERDU\", 'UTF-8'))\n ok = False\n else:\n self.oponent.connexion.send(bytes(\"0\", 'UTF-8'))\n turn = 1\n\n self.oponent.connexion.close()\n self.connexion.close() # couper la connexion côté serveur\n\n def addOponent(self, th):\n self.oponent = th\n\n# Initialisation du serveur - Mise en place du socket :\nmySocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\ntry:\n mySocket.bind((host, port))\nexcept socket.error:\n print(\"La liaison du socket à l'adresse choisie a échoué.\")\n sys.exit()\nprint(\"Serveur prêt, en attente de requêtes ...\")\nmySocket.listen(5)\n\n# Attente et prise en charge des connexions demandées par les clients :\nconn_client = {} # dictionnaire des connexions clients\nnumClient = 1\nwhile 1:\n connexion, adresse = mySocket.accept()\n print(\"nouveau client\" + str(numClient))\n # Créer un nouvel objet thread pour gérer la connexion :\n th = ThreadClient(connexion)\n # Mémoriser la connexion dans le dictionnaire :\n conn_client[numClient] = th\n if numClient % 2 == 0:\n conn_client[numClient-1].addOponent(conn_client[numClient])\n conn_client[numClient].start()\n conn_client[numClient-1].start()\n numClient += 1\n","sub_path":"src/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":4093,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"67465948","text":"from kivy.app import App\nfrom kivy.lang import Builder\nfrom kivy.uix.label import Label\n\n\nclass DynamicLabelGeneratorApp(App):\n def __init__(self):\n super().__init__()\n self.names = ['Steve', 'Tony', 'Bucky', 'Sam', 'Rhody', 'Bruce']\n\n def build(self):\n self.title = 'Dynamic Label Generator'\n self.root = Builder.load_file('dynamic_labels.kv')\n self.create_labels()\n return self.root\n\n def create_labels(self):\n for name in self.names:\n temp_label = Label(text=name)\n self.root.ids.main.add_widget(temp_label)\n\n\nDynamicLabelGeneratorApp().run()\n","sub_path":"prac_07/dynamic_labels.py","file_name":"dynamic_labels.py","file_ext":"py","file_size_in_byte":626,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"152130318","text":"import FWCore.ParameterSet.Config as cms\n\nprocess = cms.Process(\"DEMO\")\n\nprocess.load(\"FWCore.MessageService.MessageLogger_cfi\")\n\nprocess.MessageLogger.cerr.FwkReport.reportEvery = 25\n\nprocess.maxEvents = cms.untracked.PSet(\n input = cms.untracked.int32(5)\n)\n\nprocess.source = cms.Source(\"PoolSource\",\n fileNames = cms.untracked.vstring(\n 'file:/tmp/sturdy/CMSSW_5_3_14/src/testOut.root'\n )\n)\n\nprocess.readWeights = cms.EDAnalyzer('LHEWeightsAnalyzer',\n weightMapSrc = cms.InputTag(\"weightsMap\",\"MGWeightMap\"),\n weightSrc = cms.InputTag(\"allWeights\",\"mg-reweight-1\"),\n #weightSrc = cms.InputTag(\"weight30\"),\n #weightLabel = cms.string(\"mg_reweight_13\"),\n)\nprocess.p = cms.Path(process.readWeights)\n","sub_path":"LHEWeightProducer/test/reading_test.py","file_name":"reading_test.py","file_ext":"py","file_size_in_byte":753,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"551467967","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\nfrom django.conf import settings\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n migrations.swappable_dependency(settings.AUTH_USER_MODEL),\n ('android', '0009_auto_20160211_1930'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Person',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('firstname', models.CharField(max_length=20, null=True)),\n ('middlename1', models.CharField(max_length=20, null=True, blank=True)),\n ('middlename2', models.CharField(max_length=20, null=True, blank=True)),\n ('surname', models.CharField(max_length=20, null=True)),\n ('maidenname', models.CharField(max_length=20, null=True, blank=True)),\n ('children', models.ManyToManyField(related_name='c', null=True, verbose_name=b'Children', to='android.Person', blank=True)),\n ('parents', models.ManyToManyField(related_name='p', null=True, verbose_name=b'Parents', to='android.Person', blank=True)),\n ('partner', models.ManyToManyField(related_name='ps', null=True, verbose_name=b'Partner', to='android.Person', blank=True)),\n ('siblings', models.ManyToManyField(related_name='s', null=True, verbose_name=b'Siblings', to='android.Person', blank=True)),\n ('unique_id', models.ForeignKey(to='android.UniqueId')),\n ],\n ),\n migrations.RemoveField(\n model_name='user',\n name='children',\n ),\n migrations.RemoveField(\n model_name='user',\n name='parents',\n ),\n migrations.RemoveField(\n model_name='user',\n name='partner',\n ),\n migrations.RemoveField(\n model_name='user',\n name='siblings',\n ),\n migrations.RemoveField(\n model_name='user',\n name='unique_id',\n ),\n migrations.DeleteModel(\n name='User',\n ),\n migrations.AddField(\n model_name='person',\n name='user',\n field=models.ForeignKey(to=settings.AUTH_USER_MODEL),\n ),\n ]\n","sub_path":"android/migrations/0010_auto_20160211_2100.py","file_name":"0010_auto_20160211_2100.py","file_ext":"py","file_size_in_byte":2368,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"324801218","text":"from target_funcs import *\nfrom collision_problem import Collision_Problem\nfrom argparse import ArgumentParser\n\n\nif __name__=='__main__':\n parser = ArgumentParser()\n parser.add_argument('--n', default=100, help='training points')\n parser.add_argument('--i', default=10000, help='Iterations')\n args = parser.parse_args()\n\n test = Collision_Problem(lambda x:target_func2(x), train_num=int(args.n))\n if test.find_collision(iter_num=int(args.i)):\n print(\"Collision Found!\")\n else:\n test.plot_collision() # plot result at the end if collision not found","sub_path":"latent_problem/find_collision.py","file_name":"find_collision.py","file_ext":"py","file_size_in_byte":582,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"81275502","text":"#!C:\\Users\\Lee\\AppData\\Local\\Programs\\Python\\Python38-32\\python.exe\nimport random\nimport json\n\n#mode = list noting the number of nodes per layer ie: ([9900, 50, 1]) for our case of 9900 input nodes, one hidden layer with 50 nodes, and one output layer\ndef gen_weights(model):\n #for each layer\n weights = []\n for a in range(len(model)):\n layer = []\n #for each node in the layer\n for b in range(model[a]):\n node = []\n #if we are not one the last layer\n if( a < len(model) - 1 ):\n #for node in the next layer\n for x in range(model[a+1]):\n node.append(round(random.uniform(-4,4),2))\n layer.append(node)\n weights.append(layer)\n return weights\n\nif __name__ == '__main__':\n model = [198,50,1]\n weights = gen_weights(model)\n\n with open(\"weights.json\",\"w\") as weight_file:\n weight_file.write(json.dumps(weights))\n weight_file.close()\n \n\n\n\n","sub_path":"gen_weights.py","file_name":"gen_weights.py","file_ext":"py","file_size_in_byte":993,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"604725497","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Jan 6 16:28:37 2021\r\n\r\n@author: ANIL\r\n\"\"\"\r\ndoggy = {\r\n 'type': 'dog',\r\n 'owner': 'sam pitroda',\r\n}\r\n\r\ncatty = {\r\n 'type': 'cat',\r\n 'owner': 'preeti rai',\r\n}\r\n\r\nmilky = {\r\n 'type': 'cow',\r\n 'owner': 'ramesh chandra',\r\n}\r\n\r\npets = [doggy, catty, milky]\r\nfor pet in pets:\r\n print(f\"Type:\\t\\t{pet['type'].title()}\")\r\n print(f\"Owner:\\t\\t{pet['owner'].title()}\\n\")\r\n","sub_path":"Python Crash Course/vAnil/Chapter-6/6-8.py","file_name":"6-8.py","file_ext":"py","file_size_in_byte":430,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"229835997","text":"import time\nimport os, shutil\nimport pymysql, sqlparse\n\ndef Query(sql):\n\tdb = pymysql.connect(\"localhost\",\"root\",\"stroops2020\",\"CIN_Number\",charset='utf8mb4')\n\tdbc = db.cursor(pymysql.cursors.DictCursor)\n\toutput = {}\n\tqcnt = -1\n\tfor statement in sqlparse.split(sql):\n\t\tqcnt = qcnt + 1\n\t\tdbc.execute(statement)\n\t\tdb.commit()\n\t\toutput[qcnt] = dbc.fetchall()\n\tif qcnt == 0:\n\t\toutput = output[0]\n\tdbc.close()\n\tdb.close()\n\treturn output\n\ndirectory_path = '/var/www/seleniumtest/data4'\ndestination = '/var/www/seleniumtest/datacom'\n\nfor filename in os.listdir(directory_path):\n\tprint(filename)\n\tname1= directory_path+'/'+ filename\n\tname2 = destination +'/'+ filename\n\n\t# file_upload(os.path.join(directory_path, filename))\n\twith open(name1, encoding=\"utf8\", errors='ignore') as f:\n\t\tdata = f.read()\n\t\ti = 0\n\t\tfor row in data.split('\\n'):\n\t\t\tif row != '':\n\t\t\t\tif i > 0:\n\t\t\t\t\tcin= row.split(',')[1]\n\t\t\t\t\tprint(cin)\n\t\t\t\t\tww = cin.replace(\"'\",'').replace('\"','')\n\t\t\t\t\tprint(ww)\n\t\t\t\t\t# try:\n\t\t\t\t\t# \tQuery('INSERT INTO CIN_NO(CIN) VALUES(\"'+str(ww)+'\")')\n\t\t\t\t\t# except Exception as e:\n\t\t\t\t\t# \tprint(e)\n\t\t\t\n\t\t\ti +=1\n\t\t# shutil.move(name1, name2)\n","sub_path":"extra.py","file_name":"extra.py","file_ext":"py","file_size_in_byte":1134,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"522762472","text":"#!/usr/bin/env python3\n# _*_ coding: utf-8 _*_\n# @Time : 18-7-7 下午4:47\n# @Author : Abel\n# @Email : zilongcheng@outlook.com\n# @File : test.py\n# @Software: PyCharm\nimport os\nimport time\n\n\ndef show_time(fun):\n def inner(n):\n st = time.time()\n fun(n)\n et = time.time()\n return str(et - st)\n return inner\n\n\n@show_time\ndef deal_sum(n):\n sum = 0\n for i in range(n):\n sum += i\n print('sum = %s' % sum)\n\n\nif __name__ == '__main__':\n # a = deal_sum(1000000)\n # print(a)\n print(os.path.dirname('/usr/bin'))\n\n","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":569,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"389823573","text":"import numpy as np\nimport random\n\n\ndef train_validation_split(train_names, data, CVS=5):\n \"\"\"\n :param train_names:\n\n :param data:\n\n :param CVS: Integer\n Default 5\n Number of cross validation folds to perform\n :return:\n \"\"\"\n\n # TH is the amount of posts we can take for our validation set, putting the rest into the train set\n data = data[data['user_name'].isin(train_names)]\n TH = int(data[data['user_name'].isin(train_names)].shape[0] / CVS)\n\n # Train and validation names to return\n train_names_to_send = []\n valid_names_to_send = []\n\n flag = 1\n for cv in range(CVS):\n # counter to check if we exceeded our TH\n total_names = 0\n\n # Lists to hold our current train & val names\n train_names = []\n val_names = []\n\n # if first iteration\n if flag == 1:\n for name in data.user_name.value_counts().keys():\n # if exceeded append to train, else val\n if total_names > TH:\n train_names.append(name)\n else:\n val_names.append(name)\n total_names += data.user_name.value_counts()[name]\n # concat the lists so we can take the next names as validation next iteration\n cv_names = train_names + val_names\n train_names_to_send.append(train_names)\n valid_names_to_send.append(val_names)\n flag = 0\n else:\n\n for name in cv_names:\n if total_names > TH:\n train_names.append(name)\n else:\n val_names.append(name)\n total_names += data.user_name.value_counts()[name]\n train_names_to_send.append(train_names)\n valid_names_to_send.append(val_names)\n cv_names = train_names + val_names\n\n return train_names_to_send, valid_names_to_send\n\n\ndef shuffle_forward(data):\n\n \"\"\"\n This method is to shuffle the given data while retaining the original indices for each row vector\n\n :param data: Matrix\n The sequences matrix to shuffle\n :return: Matrix, Array\n A new matrix shuffled\n Array containing the original indices of the shuffled matrix\n \"\"\"\n order = np.arange(len(data))\n random.shuffle(order)\n\n data = list(np.array(data)[order])\n\n t = np.zeros((len(list(data)), len(data[0])))\n for arr in range(len(list(data))):\n t[arr] = list(data)[arr]\n\n return t, order\n\n\ndef shuffle_backward(data, order):\n \"\"\"\n This method is to un-shuffle the given data using the indices retained by the shuffle method\n\n :param data: Matrix\n Shuffled sequence matrix\n :param order: Array\n Array of the unshuffled indices\n :return: Matrix\n Return the shuffled matrix in its original order\n \"\"\"\n\n data_out = [0] * len(data)\n for i, j in enumerate(order):\n data_out[j] = data[i]\n\n t = np.zeros((len(list(data_out)), len(data_out[0])))\n for arr in range(len(list(data_out))):\n t[arr] = list(data_out)[arr]\n\n return t\n\n\ndef split_user_train_test(data, ratio):\n \"\"\"\n We calculate how much exactly ids make up for the ratio we want in our train set & test set\n If the num of rows exceeds the ratio threshold, we append the following ids to the test set keeping a close ratio.\n\n :param data:\n :param ratio: Float\n The ratio we wish to maintain with our train and test sets\n :return:\n \"\"\"\n TH = int(data.shape[0] * ratio)\n total_names = 0\n\n train_names = []\n test_names = []\n\n for name in data.user_name.value_counts().keys():\n if total_names > TH:\n test_names.append(name)\n else:\n train_names.append(name)\n total_names += data.user_name.value_counts()[name]\n\n return train_names, test_names\n","sub_path":"keras_models/keras_util_functions.py","file_name":"keras_util_functions.py","file_ext":"py","file_size_in_byte":3835,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"131051578","text":"\"\"\"\nFull Application for Lightpath\n\"\"\"\nfrom functools import partial\nimport logging\nimport threading\nimport os.path\n\nimport numpy as np\nimport pcdsdevices.device_types as dtypes\nfrom pcdsdevices.valve import PPSStopper\nfrom pydm import Display\nfrom qtpy.QtCore import Slot as pyqtSlot, Qt\nfrom qtpy.QtWidgets import QHBoxLayout, QGridLayout, QCheckBox\nimport typhos\nfrom typhos import TyphosDeviceDisplay\n\nfrom lightpath.path import DeviceState\nfrom .widgets import LightRow\n\nlogger = logging.getLogger(__name__)\n\n\nclass LightApp(Display):\n \"\"\"\n Main widget display for the lightpath\n\n Shows tables of devices and the current destination of the beam, as well\n as the status of the MPS system for LCLS\n\n Parameters\n ----------\n controller: LightController\n LightController object\n\n beamline : str, optional\n Beamline to initialize the application with, otherwise the most\n upstream beamline will be selected\n\n dark : bool, optional\n Load the UI with the `qdarkstyle` interface\n\n parent : optional\n \"\"\"\n shown_types = [dtypes.Attenuator, dtypes.GateValve, dtypes.IPM,\n dtypes.LODCM, dtypes.OffsetMirror, dtypes.PIM, PPSStopper,\n dtypes.PulsePicker, dtypes.Slits, dtypes.Stopper,\n dtypes.XFLS]\n\n def __init__(self, controller, beamline=None,\n parent=None, dark=True):\n super().__init__(parent=parent)\n # Store Lightpath information\n self.light = controller\n self.path = None\n self.detail_screen = None\n self.device_buttons = dict()\n self._lock = threading.Lock()\n # Create empty layout\n self.lightLayout = QHBoxLayout()\n self.lightLayout.setSpacing(1)\n self.widget_rows.setLayout(self.lightLayout)\n self.device_types.setLayout(QGridLayout())\n self.overview.setLayout(QHBoxLayout())\n self.overview.layout().setSpacing(2)\n self.overview.layout().setContentsMargins(2, 2, 2, 2)\n # Setup the fancy overview slider\n slide_scroll = self.scroll.horizontalScrollBar()\n self.slide.setRange(slide_scroll.minimum(),\n slide_scroll.maximum())\n self.slide.sliderMoved.connect(slide_scroll.setSliderPosition)\n slide_scroll.rangeChanged.connect(self.slide.setRange)\n slide_scroll.valueChanged.connect(self.slide.setSliderPosition)\n # Add destinations\n for line in self.destinations():\n self.destination_combo.addItem(line)\n\n # Connect signals to slots\n self.destination_combo.currentIndexChanged.connect(\n self.change_path_display)\n self.device_combo.activated[str].connect(self.focus_on_device)\n self.impediment_button.pressed.connect(self.focus_on_device)\n self.remove_check.toggled.connect(self.filter)\n self.upstream_check.toggled.connect(self.filter)\n self.detail_hide.clicked.connect(self.hide_detailed)\n # Store LightRow objects to manage subscriptions\n self.rows = list()\n # Select the beamline to begin with\n beamline = beamline or self.destinations()[0]\n try:\n idx = self.destinations().index(beamline.upper())\n except ValueError:\n logger.error(\"%s is not a valid beamline\", beamline)\n idx = 0\n # Move the ComboBox\n self.destination_combo.setCurrentIndex(idx)\n # Add all of our device type options\n max_columns = 3\n for i, row in enumerate(np.array_split(self.shown_types,\n max_columns)):\n for j, device_type in enumerate(row):\n # Add box to layout\n box = QCheckBox(device_type.__name__)\n box.setChecked(True)\n self.device_types.layout().addWidget(box, j, i)\n # Hook up box to hide function\n self.device_buttons[box] = device_type\n box.toggled.connect(self.filter)\n # Setup the UI\n self.change_path_display()\n self.resizeSlider()\n # Change the stylesheet\n if dark:\n typhos.use_stylesheet(dark=True)\n\n def destinations(self):\n \"\"\"\n All possible beamline destinations sorted by end point\n \"\"\"\n return sorted(list(self.light.beamlines.keys()),\n key=lambda x: self.light.beamlines[x].range[0])\n\n def load_device_row(self, device):\n \"\"\"\n Create LightRow for device\n \"\"\"\n # Create two widgets\n widgets = (LightRow(device),\n LightRow(device))\n # Condense the second\n widgets[1].condense()\n return widgets\n\n def select_devices(self, beamline):\n \"\"\"\n Select a subset of beamline devices to show in the display\n\n Parameters\n ----------\n beamline : str\n Beamline to display\n\n upstream : bool, optional\n Include upstream devices in the display\n \"\"\"\n # Clear any remaining subscriptions\n if self.path:\n self.clear_subs()\n # Find pool of devices and create subscriptions\n self.path = self.light.beamlines[beamline]\n # Defer running updates until UI is created\n self.path.subscribe(self.update_path, run=False)\n logger.debug(\"Selected %s devices ...\", len(self.path.path))\n return self.path.path\n\n def selected_beamline(self):\n \"\"\"\n Current beamline selected by the combo box\n \"\"\"\n return self.destination_combo.currentText()\n\n @property\n def hidden_devices(self):\n \"\"\"Device types set to currently be visible\"\"\"\n return [dtype for button, dtype in self.device_buttons.items()\n if not button.isChecked()]\n\n @pyqtSlot()\n @pyqtSlot(bool)\n def change_path_display(self, value=None):\n \"\"\"\n Change the display devices based on the state of the control buttons\n \"\"\"\n with self._lock:\n logger.debug(\"Resorting beampath display ...\")\n # Remove old detailed screen\n self.hide_detailed()\n # Grab all the light rows\n rows = [self.load_device_row(d)\n for d in self.select_devices(self.selected_beamline())]\n # Clear layout if previously loaded rows exist\n if self.rows:\n # Clear our subscribtions\n for row in self.rows:\n # Remove from layout\n self.lightLayout.removeWidget(row[0])\n self.overview.layout().removeWidget(row[1])\n # Disconnect\n for widget in row:\n widget.clear_sub()\n widget.deleteLater()\n # Clear subscribed row cache\n self.rows.clear()\n self.device_combo.clear()\n # Hide nothing when switching beamlines\n boxes = self.device_types.children()\n boxes.extend([self.upstream_check, self.remove_check])\n for box in boxes:\n if isinstance(box, QCheckBox):\n box.setChecked(True)\n # Add all the widgets to the display\n for i, row in enumerate(rows):\n # Cache row to later clear subscriptions\n self.rows.append(row)\n # Add widget to layout\n self.lightLayout.addWidget(row[0])\n self.overview.layout().addWidget(row[1])\n # Connect condensed widget to focus_on_device\n row[1].device_drawing.clicked.connect(\n partial(self.focus_on_device,\n name=row[1].device.name))\n # Connect large widget to show Typhos screen\n row[0].device_drawing.clicked.connect(\n partial(self.show_detailed, row[0].device))\n # Add device to combo\n self.device_combo.addItem(row[0].device.name)\n # Initialize interface\n for row in self.rows:\n for widget in row:\n widget.update_state()\n # Update the state of the path\n self.update_path()\n\n def ui_filename(self):\n \"\"\"\n Name of designer UI file\n \"\"\"\n return 'lightapp.ui'\n\n def ui_filepath(self):\n \"\"\"\n Full path to :attr:`.ui_filename`\n \"\"\"\n return os.path.join(os.path.dirname(os.path.abspath(__file__)),\n self.ui_filename())\n\n def update_path(self, *args, **kwargs):\n \"\"\"\n Update the PyDMRectangles to show devices as in the beam or not\n \"\"\"\n with self._lock:\n block = self.path.impediment\n # Set the current impediment label\n if block:\n self.current_impediment.setText(block.name)\n self.impediment_button.setEnabled(True)\n else:\n self.current_impediment.setText('None')\n self.impediment_button.setEnabled(False)\n for row in self.rows:\n device = row[0].device\n # If our device is before or at the impediment, it is lit\n if not block or (device.md.z <= block.md.z):\n _in = True\n # Check whether this device is passing beam\n _out = block != device\n # Otherwise, it is off\n else:\n _in, _out = (False, False)\n # Update widget display\n for widget in row:\n widget.update_light(_in, _out)\n\n @pyqtSlot()\n @pyqtSlot(str)\n def focus_on_device(self, name=None):\n \"\"\"Scroll to the desired device\"\"\"\n # If not provided a name, use the impediment\n name = name or self.current_impediment.text()\n # Map of names\n names = [row[0].device.name for row in self.rows]\n # Find index\n try:\n idx = names.index(name)\n except ValueError:\n logger.error(\"Can not set focus on device %r\",\n name)\n return\n # Grab widget\n self.rows[idx][0].setHidden(False)\n self.scroll.ensureWidgetVisible(self.rows[idx][0])\n\n @pyqtSlot(bool)\n def filter(self, *args):\n \"\"\"Hide devices along the beamline for a more succinct view\"\"\"\n for row in self.rows:\n device = row[0].device\n # Hide if a hidden instance of a device type\n hidden_device_type = type(device) in self.hidden_devices\n # Hide if removed\n hidden_removed = (not self.remove_check.isChecked()\n and row[0].last_state == DeviceState.Removed)\n # Hide if upstream\n beamline = self.selected_beamline()\n hidden_upstream = (not self.upstream_check.isChecked()\n and device.md.beamline != beamline)\n # Hide device if any of the criteria are met\n row[0].setHidden(hidden_device_type\n or hidden_removed\n or hidden_upstream)\n # Change the slider size to match changing view\n self.resizeSlider()\n\n def clear_subs(self):\n \"\"\"\n Clear the subscription event\n \"\"\"\n self.path.clear_sub(self.update_path)\n\n @pyqtSlot()\n def show_detailed(self, device):\n \"\"\"Show the Typhos display for a device\"\"\"\n # Hide the last widget\n self.hide_detailed()\n # Create a Typhos display\n try:\n self.detail_screen = TyphosDeviceDisplay.from_device(device)\n except Exception:\n logger.exception(\"Unable to create display for %r\",\n device.name)\n return\n # Add to widget\n self.detail_layout.insertWidget(1, self.detail_screen,\n 0, Qt.AlignHCenter)\n self.device_detail.show()\n\n @pyqtSlot()\n def hide_detailed(self):\n \"\"\"Hide Typhos display for a device\"\"\"\n # Catch the issue when there is no detail_screen already\n self.device_detail.hide()\n if self.detail_screen:\n # Remove from layout\n self.detail_layout.removeWidget(self.detail_screen)\n # Destroy widget\n self.detail_screen.deleteLater()\n self.detail_screen = None\n\n def resizeSlider(self):\n # Visible area of beamline\n visible = self.scroll.width() / self.scroll.widget().width()\n # Take same fraction of bar up in handle width\n slider_size = round(self.slide.width() * visible)\n # Set Stylesheet\n self.slide.setStyleSheet('QSlider::handle'\n '{width: %spx;'\n 'background: rgb(124, 252, 0);}'\n '' % slider_size)\n\n def show(self):\n # Comandeered to assure that slider is initialized properly\n super().show()\n self.resizeSlider()\n\n def resizeEvent(self, evt):\n # Further resize-ing of the widget should affect the fancy slider\n super().resizeEvent(evt)\n self.resizeSlider()\n","sub_path":"lightpath/ui/gui.py","file_name":"gui.py","file_ext":"py","file_size_in_byte":13332,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"641426448","text":"import requests\n\n# Docs for requests module: https://docs.python-requests.org/en/master/\n# https://realpython.com/python-requests/\n\n# ISS Location API: http://open-notify.org/Open-Notify-API/ISS-Location-Now/\nresponse = requests.get(url=\"http://api.open-notify.org/iss-now.json\")\n\nprint(f\"Response Code = {response.status_code}\")\nprint(f\"Response Text = {response.text}\")\n\nresponse_data = response.json() # This is a dict\nlatitude = response_data['iss_position']['latitude']\nlongitude = response_data['iss_position']['longitude']\niss_position = (latitude, longitude)\n\nprint(f\"ISS Position = {iss_position}\")\n\nif response.status_code == 200:\n print('Success!')\nelif response.status_code == 404:\n print('Not Found.')\n\n# If the response was successful, no Exception will be raised\nresponse.raise_for_status()\n","sub_path":"section_05_intermediate/lesson_05_api/01_making_api_calls.py","file_name":"01_making_api_calls.py","file_ext":"py","file_size_in_byte":813,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"80512099","text":"\ns = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n'''\n#First\nlength = len(s) - 1\ns[0], s[length] = s[length], s[0]\nprint(s)\n'''\n'''\n#second\n\nsliceable = s[::2]\nprint(sliceable)\n'''\n'''\n#third\nlength = len(s)\nlength -= 1\ns.pop(length)\ns.pop(0)\n\nslicable = s[::2]\n\nprint(slicable)\n'''\n'''\n#fourth\ns = s[::-1]\nprint(s)\n'''\n\n","sub_path":"students/MichaelGregor/Session 3/classWork.py","file_name":"classWork.py","file_ext":"py","file_size_in_byte":308,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"342052246","text":"from math import sin, cos, sqrt, atan2, radians\ninfo = [\n\t{\n\t'id' : 1,\n\t'range' : 0,\n\t'location' : {\n\t\t\t\"lat1\" : 43.235051,\n\n\t\t\t'lon1' : 76.909720,\n\t\t}\n\t\t},\n\t{\n\t'id' : 2,\n\t'range' : 0,\n\t\"location\" : \n\t\t{\n\t\t\t'lat2' : 43.235210,\n\n\t\t\t'lon2' : 76.908025,\n\t\t\t},\n\t},\n\t\n\t{\n\t'id' : 3,\n\t'range' : 0,\n\t\"location\" : {\n\t\t\n\t\t\t'lat3' : 43.240199,\n\n\t\t\t'lon3' : 76.905399, \n\t\t\t},\n\t\t},\n\t\n\t{\n\t'id' : 4,\n\t'range' : 0,\n\t\"location\" : {\n\t\t\n\t\t\t'lat4' : 43.240670,\n\t\n\t\t\t'lon4' : 76.914141,\n\t\t\t},\n\t\t},\n\t\n\t{\n\t'id' : 5,\n\t'range' : 0,\n\t\"location\" : {\n\t\t \n\t\t\t'lat5' : 43.235823,\n\n\t\t\t'lon5' : 76.883344\n\t\t\n\t\t},\n\t},\n\t{\n\t'id' : 6,\n\t'range' : 0,\n\t\"location\" : {\n\t\t \n\t\t\t'lat5' : 43.235804,\n\n\t\t\t'lon5' : 76.883513\n\t\t\n\t\t},\n\t},\n]\n\n\nR = 6373.0\n\nlatinput = float(input())\nloninput = float(input())\n\ndlon = 0\ndlat = 0\ndistance2 = 9999999999\ndistance = 0\nlatnum = 0\nfor lat in info:\n\tfor x in lat['location']:\n\t\t#print (lat['location'][x])\n\t\tlat['location'][x] = float(lat['location'][x])\n\t\tfor y in x:\n\t\t\tif y == 'o':\n\t\t\t\tdlon = radians(loninput) - radians(lat['location'][x])\n\t\t\t\tdlat = radians(latinput)- radians(latnum)\n\t\t\t\ta = sin(dlat / 2)**2 + cos(latnum) * cos(latinput) * sin(dlon / 2)**2\n\t\t\t\tc = 2 * atan2(sqrt(a), sqrt(1 - a))\t\n\t\t\t\tdistance = R * c\n\t\t\telif y == 'a': \n\t\t\t\tlatnum = lat['location'][x]\n\t\t\t\t\n\t\tif distance == 0:\n\t\t\tpass\n\t\telif distance2 > distance:\n\t\t\tdistance2 = distance\n\n\tlat['range'] = distance\n\tprint (lat['range'])\n\nprint (info)\n\"\"\"\ndef podchet():\n\t\t#задаем переменную для цикла\n\tdlon = 0\n\tdlat = 0\n\tdistance2 = 9999999999\n\tdistance = 0\n\tlatnum = 0\n\tlon[i] = 0\n\t#------\n\tfor lat in info['restoran']:\n\t\t\n\t\tlonnum['location'] = float(lonnum['location'])\n\t\t\n\t\tfor i in lat['location']:\n\t\t\t\n\t\t\tif i == 'o':\n\t\t\t\tdlon = radians(loninput) - radians(lonnum['location'])\n\t\t\t\tdlat = radians(latinput)- radians(latnum['location'])\n\t\t\t\ta = sin(dlat / 2)**2 + cos(latnum['location']) * cos(latinput) * sin(dlon / 2)**2\n\t\t\t\tc = 2 * atan2(sqrt(a), sqrt(1 - a))\t\n\t\t\t\tdistance = R * c\n\t\t\telif i == 'a': \n\t\t\t\tlatnum['location'] = lonnum['location']\n\t\tif distance == 0:\n\t\t\tpass\n\t\telif distance2 > distance:\n\t\t\tdistance2 = distance\n\n\treturn distance2\n\na = podchet()\nprint(\"Result:\", a) \n\nfrom math import sin, cos, sqrt, atan2, radians\n\n# approximate radius of earth in km\nR = 6373.0\n\nlat1 = radians(43.235051)\nlon1 = radians(76.909720)\nlat2 = radians(43.235210)\nlon2 = radians(76.908025)\n\ndlon = lon2 - lon1\ndlat = lat2 - lat1\n\na = sin(dlat / 2)**2 + cos(lat1) * cos(lat2) * sin(dlon / 2)**2\nc = 2 * atan2(sqrt(a), sqrt(1 - a))\n\ndistance = R * c\n\nprint(\"Result:\", distance)\n\"\"\"","sub_path":"git clone/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":2571,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"181147665","text":"import heapq\nfrom collections import deque\nfrom math import floor\n\nfrom src.components.board.monster import Monster\nfrom src.components.board.dijkstra import DijkstraGraph, SimpleDijkstraGraph\nfrom src.helper.dictionaryprinter import DictionaryPrinter\nfrom src.helper import functions\nfrom src.helper.Misc.constants import IMPASSIBLE, UNEXPLORED\nfrom src.helper.Misc.datatables import DataTables\n\n\nclass PathMatrix:\n \"\"\"Holds distance values used for movement and path calculation\n\n Is created by PathMatrixFactory. Makes use of the board to refer to\n terrain types.\n \"\"\"\n\n def __init__(self, board):\n self.board = board\n self.monster = None\n self.start = None\n self.end = None\n self.dist_values = {}\n self.heuristic = {}\n self.accessible_positions = set()\n self.enemies = set()\n self.explored_tiles = set()\n\n def set_heuristic_value_at(self, pos, value):\n self.heuristic[pos] = value\n\n def set_distance_value_at(self, pos, value):\n self.dist_values[pos] = value\n\n def get_distance_value_at(self, pos):\n if pos in self.dist_values:\n return self.dist_values[pos]\n else:\n return UNEXPLORED\n\n def get_heuristic_value_at(self, pos):\n if pos in self.heuristic:\n return self.heuristic[pos]\n else:\n return UNEXPLORED\n\n def is_legal_destination(self, pos):\n if pos in self.accessible_positions:\n return True\n\n def set_monster(self, monster):\n self.monster = monster\n self.start = monster.pos\n\n def get_printable_dist_values(self):\n printer = MatrixPrinter(self)\n return printer.get_printable_dist_values()\n\n def get_printable_heuristic_values(self):\n printer = MatrixPrinter(self)\n return printer.get_printable_heuristic_values()\n\n def get_printable_terrain_cost_values(self):\n printer = MatrixPrinter(self)\n return printer.get_printable_terrain_cost_values()\n\n def __iter__(self):\n return iter(self.dist_values)\n\n def check_validity(self):\n graph = DijkstraGraph(self.board, self.monster)\n dist, prev = graph.dijkstra(self.start)\n self._compare_with_dijkstra(dist, graph)\n\n def check_validity_simple(self):\n graph = SimpleDijkstraGraph(self.board, self.monster)\n dist, prev = graph.dijkstra(self.start)\n self._compare_with_dijkstra(dist, graph)\n\n def _compare_with_dijkstra(self, dist, graph):\n for pos in self.dist_values:\n dist_val = self.get_distance_value_at(pos)\n if dist_val < UNEXPLORED and pos in self.explored_tiles:\n dijk_val = dist[pos]\n assert dist_val == dijk_val, (\n f'Mismatch at {pos}: expected {dijk_val} but was {dist_val}'\n f'\\nmonster: {self.monster}\\n'\n 'Distance values:\\n'\n f'{self.get_printable_dist_values()}\\n'\n 'Dijkstra values:\\n'\n f'{graph.get_printable_values(dist)}\\n'\n 'Node count:\\n'\n f'{len(graph.edges)}')\n\n\nclass MatrixPrinter(DictionaryPrinter):\n PRINT_DIST, PRINT_HEURISTIC, PRINT_TERRAIN_COST = range(3)\n\n def __init__(self, matrix):\n super().__init__(matrix.dist_values)\n self.matrix = matrix\n self.mode = None\n\n def get_printable_dist_values(self):\n self.mode = self.PRINT_DIST\n return self._get_values()\n\n def get_printable_heuristic_values(self):\n self.mode = self.PRINT_HEURISTIC\n return self._get_values()\n\n def get_printable_terrain_cost_values(self):\n self.mode = self.PRINT_TERRAIN_COST\n return self._get_values()\n\n def _get_value_representation_at(self, pos):\n if self.mode == self.PRINT_DIST:\n val = self.matrix.get_distance_value_at(pos)\n elif self.mode == self.PRINT_HEURISTIC:\n val = self.matrix.get_heuristic_value_at(pos)\n else:\n terrain_type = self.matrix.monster.terrain_type\n terrain = self.matrix.board.terrain_at(pos)\n val = DataTables.get_terrain_cost(terrain, terrain_type)\n if val is None:\n return ' '\n else:\n if val == IMPASSIBLE:\n return '. '\n if val == UNEXPLORED:\n return ' '\n if val < 10:\n return ' ' + str(floor(val))\n else:\n return str(floor(val))\n pass\n\n\nclass MatrixProcessor:\n \"\"\"Generates a distance value matrix using a move point limit given\n\n Used by the regular, 'wide' matrix that is shown when trying to move a\n monster. It will be blocked by enemy monsters present.\n \"\"\"\n\n def __init__(self, matrix):\n self.board = matrix.board\n self.tiles_to_explore: [] = None\n self.matrix: PathMatrix = matrix\n self.accessible_positions = None\n self.monster = None\n self.move_points_base_tile = None\n self.move_points_next_tile = None\n self.pos = None\n self.cannot_move_from_pos = None\n self.max_dist_value = None\n\n def _process_tiles(self, start):\n self._setup_processing(start)\n self._explore_tiles()\n\n def _explore_tiles(self):\n n = 0\n while n < 1000:\n if self.matrix_is_finished():\n break\n self._explore_next_tile()\n n += 1\n assert n < 1000, 'Matrix took too long to process'\n\n def _setup_processing(self, start):\n self.monster = self.board.monster_at(start)\n # creating set with tuple doesn't work, add it separately\n self.accessible_positions = set()\n self.accessible_positions.add(start)\n self.matrix.accessible_positions = self.accessible_positions\n self.matrix.set_distance_value_at(start, 0)\n self.tiles_to_explore = [(0, start)]\n\n def matrix_is_finished(self):\n return not self.tiles_to_explore\n\n def _explore_next_tile(self):\n self.pos = heapq.heappop(self.tiles_to_explore)[1]\n assert self.pos[0] >= 0\n assert self.pos[1] >= 0\n self.matrix.explored_tiles.add(self.pos)\n self.cannot_move_from_pos = False\n self._handle_adjacent_enemies()\n if self.cannot_move_from_pos:\n return\n if self._found_tile_to_search_for():\n self.tile_found = True\n self.matrix.end = self.pos\n return\n self.move_points_base_tile = self.matrix.get_distance_value_at(self.pos)\n self._process_adjacent_tiles()\n\n def _found_tile_to_search_for(self):\n return False\n\n def _handle_adjacent_enemies(self):\n adjacent_enemies = self.board.get_enemies_adjacent_to(self.pos)\n # if tile has enemies adjacent, you cannot move from it, unless\n # this is the tile the moving monster starts on\n for enemy in adjacent_enemies:\n self.matrix.enemies.add(enemy)\n if adjacent_enemies and self.monster.pos != self.pos:\n self.cannot_move_from_pos = True\n self._highlight_tiles_with_enemies(adjacent_enemies)\n\n def _highlight_tiles_with_enemies(self, adjacent_enemies):\n for adjacent_enemy in adjacent_enemies:\n self.accessible_positions.add(adjacent_enemy.pos)\n\n def _process_adjacent_tiles(self):\n adjacent_posses = self.board.get_posses_adjacent_to(self.pos)\n for adj_pos in adjacent_posses:\n self._process_adjacent_tile(adj_pos)\n\n def _process_adjacent_tile(self, adj_pos):\n if self._tile_is_not_passable(adj_pos):\n return\n move_cost = self._get_move_cost_for(adj_pos)\n if move_cost == 99:\n if self.matrix.get_distance_value_at(adj_pos) is UNEXPLORED:\n self.matrix.set_distance_value_at(adj_pos, IMPASSIBLE)\n return\n self.move_points_next_tile = self.move_points_base_tile + move_cost\n if self._move_is_valid_and_better(adj_pos):\n self.matrix.set_distance_value_at(\n adj_pos, self.move_points_next_tile)\n self.accessible_positions.add(adj_pos)\n self._push_tile_at(adj_pos)\n\n def _tile_is_not_passable(self, pos):\n tile_monster = self.board.monster_at(pos)\n if (tile_monster\n and tile_monster.is_enemy_of(self.monster.owner)):\n return True\n\n def _get_move_cost_for(self, pos):\n return DataTables.get_terrain_cost(\n self.board.terrain_at(pos),\n self.monster.terrain_type)\n\n def _move_is_valid_and_better(self, pos):\n # Returns true only if this move is within the move point budget and\n # has a lower distance value\n if self.move_points_next_tile > self.max_dist_value:\n return False\n dist_value = self.matrix.get_distance_value_at(pos)\n return dist_value > self.move_points_next_tile\n\n def _push_tile_at(self, pos):\n heapq.heappush(self.tiles_to_explore, (self._get_heuristic(pos), pos))\n\n def _get_heuristic(self, pos):\n heuristic = self.matrix.get_heuristic_value_at(pos)\n if heuristic == UNEXPLORED:\n heuristic = self.move_points_next_tile\n self.matrix.set_heuristic_value_at(pos, heuristic)\n return heuristic\n\n\nclass FullMatrixProcessor(MatrixProcessor):\n def __init__(self, matrix):\n super().__init__(matrix)\n\n def fill_distance_values(self, start, max_dist_value):\n self.max_dist_value = max_dist_value\n self._process_tiles(start)\n\n\nclass SearchMatrixProcessor(MatrixProcessor):\n \"\"\"Abstract class that checks for properties of tiles\n\n It should have its _found_tile_to_search_for overridden by inheritance.\n Have it return true when the tile at pos fulfills the requirements.\n\n What this really does is create two matrices. The regular matrix, which\n is needed to create valid destinations for the first move, and a second\n matrix which has no hard restrictions of movement points to draw a path to\n the final destination of a path. Otherwise the path may not be valid if the\n first move ends at a spot occupied by a monster, but it should ignore\n monsters on the rest of the path, otherwise it may create strange routes\n to circumvent potential blockades from far away.\n \"\"\"\n\n def __init__(self, matrix):\n super().__init__(matrix)\n self.tile_found = False\n\n def _setup_processing(self, start):\n super()._setup_processing(start)\n self.player = self.monster.owner\n\n def matrix_is_finished(self):\n if not self.tiles_to_explore:\n return True\n return self.tile_found\n\n def _move_is_valid_and_better(self, pos):\n \"\"\"Checks to see if the tile at pos should be updated\n\n Returns true only if this move is within the move point budget and\n has a lower distance value\n \"\"\"\n if self.move_points_next_tile > self.max_dist_value:\n return False\n dist_value = self.matrix.get_distance_value_at(pos)\n return dist_value > self.move_points_next_tile\n\n\nclass TowerSearchMatrixProcessor(SearchMatrixProcessor):\n \"\"\"Like regular MatrixProcessor, except it searches a capturable tower\"\"\"\n\n def fill_distance_values(self, start, max_dist_value):\n self.max_dist_value = max_dist_value\n self._process_tiles(start)\n\n def _handle_adjacent_enemies(self):\n \"\"\"This processor ignores blocking enemies\"\"\"\n pass\n\n def _tile_is_not_passable(self, pos):\n \"\"\"Ignore impassible tiles for this processor\"\"\"\n return False\n\n def _found_tile_to_search_for(self):\n # todo move players to board, add method to check friend or foe\n return (self.board.has_tower_at(self.pos)\n and self.board.tower_is_capturable_by(self.pos, self.player))\n\n\nclass AStarMatrixProcessor(MatrixProcessor):\n \"\"\"Processes a matrix using the a star algorithm.\n\n This is faster but will only work when given a specific pos that it should\n search for. It will stop building the matrix once that pos is reached.\n \"\"\"\n\n def __init__(self, matrix):\n super().__init__(matrix)\n self.destination_reached = False\n self.destination = None\n\n def fill_distance_values(self, start, destination):\n self.monster = self.board.monster_at(start)\n self.matrix.monster = self.monster\n assert self.monster\n self.destination = destination\n self._process_tiles(start)\n\n def matrix_is_finished(self):\n if not self.tiles_to_explore:\n return True\n return self.destination_reached\n\n def _handle_adjacent_enemies(self):\n \"\"\"Enemies don't block matrix for this processor\"\"\"\n pass\n\n def _tile_is_not_passable(self, pos):\n \"\"\"Ignore impassible tiles for this processor\"\"\"\n return False\n\n def _explore_next_tile(self):\n self.pos = heapq.heappop(self.tiles_to_explore)[1]\n self.matrix.explored_tiles.add(self.pos)\n if self.pos == self.destination:\n self.destination_reached = True\n self.matrix.end = self.pos\n return\n self.move_points_base_tile = self.matrix.get_distance_value_at(self.pos)\n self._process_adjacent_tiles()\n\n def _move_is_valid_and_better(self, pos):\n # Returns true if this tile hasn't been visited yet or has a lower\n # distance value\n if self.matrix.get_distance_value_at(pos) == UNEXPLORED:\n return True\n dist_value = self.matrix.get_distance_value_at(pos)\n return dist_value > self.move_points_next_tile\n\n def _get_heuristic(self, pos):\n dist_from_destination = \\\n self._get_manhattan_distance_to(pos) * 1.001\n heuristic = self.move_points_next_tile + dist_from_destination\n self.matrix.set_heuristic_value_at(pos, heuristic)\n return heuristic\n\n def _get_manhattan_distance_to(self, pos):\n return functions.get_hexagonal_manhattan_distance(pos, self.destination)\n\n\nclass Path:\n def __init__(self):\n self.posses = deque()\n self.furthest_reachable = None\n\n def add_pos(self, pos):\n self.posses.appendleft(pos)\n\n def get_last_pos(self):\n return self.posses[-1]\n\n def get_posses(self):\n return\n\n def get_furthest_reachable_pos(self):\n return self.furthest_reachable\n\n def __len__(self):\n return len(self.posses)\n\n def __getitem__(self, index):\n return self.posses[index]\n\n def __repr__(self):\n name = []\n for pos in self.posses:\n name.append(str(pos))\n return ','.join(name)\n\n\nclass PathFinder:\n \"\"\" Generates shortest paths for monsters.\n\n Use the board's path matrix to generate the shortest path between monster\n location and a provided destination. Paths are constrained by the game's\n rules. Will return None if no path could be found or reached.\n \"\"\"\n\n def __init__(self, board):\n self.board: board.Board = board\n self.path_matrix: PathMatrix = None\n self.pos_from = None\n self.pos_to = None\n self.path: Path = None\n self.terrain_type = None\n self.adj_found = None\n self.start = None\n self.end = None\n\n def set_path_matrix(self, matrix):\n self.path_matrix = matrix\n\n def get_path_to(self, pos):\n \"\"\"Returns the shortest path to a pos in the path matrix\"\"\"\n assert self.path_matrix, 'No path matrix set'\n self.start = self.path_matrix.start\n self.end = pos\n if self._destination_not_reachable():\n return None\n self._setup_tracing()\n while self._path_not_fully_traced_yet():\n self._search_for_adjacent_tiles()\n assert self.adj_found, \\\n (f'Could not retrace path to {self.start}. '\n f'Stuck at {self.pos_from}. \\n'\n f'{self.path_matrix.get_printable_dist_values()}')\n return self.path\n\n def get_path_on(self, matrix):\n self.path_matrix = matrix\n return self.get_path()\n\n def get_path(self):\n \"\"\"Returns the shortest path to a pos in the path matrix\"\"\"\n assert self.path_matrix, 'No path matrix set'\n assert self.path_matrix.start\n if not self.path_matrix.end:\n return self.path\n self.start = self.path_matrix.start\n self.end = self.path_matrix.end\n if self.end is None:\n return None\n if self._destination_not_reachable():\n return None\n self._setup_tracing()\n while self._path_not_fully_traced_yet():\n self._search_for_adjacent_tiles()\n # check\n for part in self.path:\n assert part in self.path_matrix, (\n f'Path is not fully present in matrix: {self.path}'\n f'{self.path_matrix.get_printable_dist_values()}')\n return self.path\n\n def _destination_not_reachable(self):\n return self._get_distance_value(self.end) is None\n\n def _path_not_fully_traced_yet(self):\n return self.pos_from != self.path_matrix.start\n\n def _setup_tracing(self):\n assert self.start, 'Start position not configured'\n assert self.end, 'End position not configured'\n monster: Monster = self.path_matrix.monster\n assert monster\n self.move_points = monster.stats.move_points\n self.terrain_type = monster.stats.terrain_type\n # append the ending point (starting pos for the algorithm)\n self.path = Path()\n self.pos_to = self.end\n self._add_tile_to_path()\n\n def _search_for_adjacent_tiles(self):\n self.adj_found = False\n adjacent_tiles = self.board.get_posses_adjacent_to(self.pos_from)\n for self.pos_to in adjacent_tiles:\n if self._tile_can_be_moved_to():\n self._add_tile_to_path()\n if self.adj_found:\n break\n assert self.adj_found, \\\n (f'Could not retrace path for {self.board.monster_at(self.start)} '\n f'from {self.start} to {self.end}. Stuck at {self.pos_from}\\n'\n f'Path so far: {self.path}\\n'\n f'{self.path_matrix.get_printable_dist_values()}')\n\n def _get_distance_value(self, pos):\n if pos not in self.path_matrix.explored_tiles:\n return UNEXPLORED\n return self.path_matrix.get_distance_value_at(pos)\n\n def _tile_can_be_moved_to(self):\n return (self._move_cost_difference_is_correct()\n and self._next_tile_is_not_blocked())\n\n def _move_cost_difference_is_correct(self):\n path_cost_difference = (\n self._get_distance_value(self.pos_from) -\n self._get_distance_value(self.pos_to))\n terrain = self.board.terrain_at(self.pos_from)\n move_cost = DataTables.get_terrain_cost(terrain, self.terrain_type)\n return path_cost_difference == move_cost\n\n def _next_tile_is_not_blocked(self):\n \"\"\"Check if monster can move to this tile.\n\n If there are monsters adjacent to this tile, the tile is blocked\n (counts as a final move), unless this is the tile the monster starts on\n \"\"\"\n return (self.pos_to == self.start\n or self._next_tile_has_no_adjacent_enemies())\n\n def _next_tile_has_no_adjacent_enemies(self):\n posses = self.board.get_posses_adjacent_to(self.pos_to)\n for pos in posses:\n if self._pos_has_adjacent_enemy(pos):\n return False\n return True\n\n def _pos_has_adjacent_enemy(self, pos):\n nearby_monster = self.board.monster_at(pos)\n return (nearby_monster\n and nearby_monster.is_enemy_of(self.board.get_current_player()))\n\n def _add_tile_to_path(self):\n pos = self.pos_to\n self.path.add_pos(pos)\n self.pos_from = pos\n self.adj_found = True\n if self._furthest_reachable_can_be_set(pos):\n self.path.furthest_reachable = pos\n\n def _furthest_reachable_can_be_set(self, pos):\n return (not self.path.furthest_reachable\n and self.path_matrix.get_distance_value_at(pos)\n <= self.move_points)\n\n\nclass SimplePathFinder(PathFinder):\n \"\"\"Gives the shorest possible path, ignores monsters blocking the path\"\"\"\n\n def _next_tile_is_not_blocked(self):\n return True\n\n\nclass MatrixFactory:\n def __init__(self, board):\n self.matrix = None\n self.processor: FullMatrixProcessor = None\n self.terrain_cost = DataTables.terrain_cost\n self.board: board.Board = board\n\n def setup_matrix(self, start):\n self.matrix = PathMatrix(self.board)\n monster = self.board.monster_at(start)\n assert monster, f'No monster found at pos {start}'\n self.matrix.set_monster(monster)\n\n\nclass AStarMatrixFactory(MatrixFactory):\n def generate_path_matrix(self, start, destination) -> PathMatrix:\n \"\"\"Generates path matrix up until the destination\"\"\"\n assert destination\n self.setup_matrix(start)\n self.processor = AStarMatrixProcessor(self.matrix)\n self.processor.fill_distance_values(start, destination)\n return self.matrix\n\n\nclass TowerSearchMatrixFactory(MatrixFactory):\n def generate_path_matrix(self, start) -> PathMatrix:\n \"\"\"Generates a path matrix to the nearest capturable tower\"\"\"\n self.setup_matrix(start)\n self.processor = TowerSearchMatrixProcessor(self.matrix)\n move_points = self.board.monster_at(start).stats.move_points\n self.processor.fill_distance_values(start, move_points * 1000)\n return self.matrix\n\n # def _generate_path_matrix_old(self, start, terrain_type) -> PathMatrix:\n # \"\"\"Generates a path matrix to the nearest terrain type\n #\n # Buggy, might be fixed later\n # \"\"\"\n # self.setup_matrix(start)\n # self.processor = TowerSearchMatrixProcessor(self.matrix)\n # move_points = self.board.monster_at(start).stats.move_points\n # # todo something goes wrong here, invalid distance values are\n # # generated\n # # on hold till later\n # # INFO:root:1\n # # INFO:root:\n # # 17 2 4 4\n # # 18 5 1 0 4\n # # 19 2 4 4\n # # 11 12 13 14\n # # the 2's on the left make no sense\n # self.processor.fill_distance_values(start, terrain_type, move_points)\n # # ok, so now we have the matrix for a single turn. if the terrain is\n # # further than that, what we need to do is continue the matrix until\n # # we\n # # find the terrain.\n # # only restriction is that the first turn can't end on another\n # # monster,\n # # so all dist values from the first turn that end on a monster must be\n # # removed. then more dist values should be generated continuing from\n # # the\n # # second turn, so they start with dist values equal to the monster's\n # # move points per turn.\n # # to do this, copy the matrix and replace dist values\n # # with move point values, push them on the queue and fill remaining\n # # dist\n # # values\n # logging.info('1')\n # logging.info(self.matrix.get_dist_values())\n # # now we have a matrix that may need to expand, check if we found\n # # something already\n # if self.matrix.end and self.board.monster_at(self.matrix.end) is None:\n # return self.matrix\n # # if not, we need to expand this\n # # save dist values since these are overwritten\n # old_dist_values = copy.copy(self.matrix.dist_values)\n # # change dist values that have friendly monsters on them since\n # # they can't be used as starting pos for the next turn\n # keys_to_remove = []\n # if self.matrix.end:\n # assert not self.board.monster_at(self.matrix.end)\n # for pos in self.matrix.dist_values:\n # if self.board.monster_at(pos) and pos != start:\n # self.matrix.dist_values[pos] = IMPASSIBLE\n #\n # logging.info('2')\n # logging.info(self.matrix.get_dist_values())\n # self.processor.expand_matrix(\n # self.matrix, move_points, move_points * 11)\n # logging.info('3')\n # logging.info(self.matrix.get_dist_values())\n # # now we got a matrix that doesn't have a full path, so copy the saved\n # # path over the expanded one to reconstruct the full path\n # for pos in old_dist_values:\n # self.matrix.dist_values[pos] = old_dist_values[pos]\n # logging.info('4')\n # logging.info(self.matrix.get_dist_values())\n # return self.matrix\n","sub_path":"src/components/board/pathing_components.py","file_name":"pathing_components.py","file_ext":"py","file_size_in_byte":24844,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"235313564","text":"from django.conf import settings\nfrom django.core.exceptions import ObjectDoesNotExist\nfrom django.db import transaction\nfrom django.shortcuts import redirect\nfrom django.utils.translation.trans_real import to_language\n\nimport jingo\n\nimport amo\nfrom amo.decorators import login_required\nfrom amo.urlresolvers import reverse\nfrom addons.forms import CategoryFormSet, DeviceTypeForm\nfrom addons.models import Addon, AddonUser\nfrom market.models import AddonPaymentData\nfrom mkt.developers import tasks\nfrom mkt.developers.decorators import dev_required\nfrom mkt.developers.forms import (AppFormMedia, PaypalPaymentData,\n PreviewFormSet)\nfrom mkt.submit.forms import (AppDetailsBasicForm, PaypalSetupForm)\nfrom mkt.submit.models import AppSubmissionChecklist\nimport paypal\nfrom files.models import Platform\nfrom users.models import UserProfile\nfrom . import forms\nfrom .decorators import submit_step\n\n\n@login_required\ndef submit(request):\n \"\"\"Determine which step to redirect user to.\"\"\"\n # If dev has already agreed, continue to next step.\n user = UserProfile.objects.get(pk=request.user.id)\n if user.read_dev_agreement:\n return redirect('submit.app.manifest')\n else:\n return redirect('submit.app.terms')\n\n\n@login_required\n@submit_step('terms')\ndef terms(request):\n # If dev has already agreed, continue to next step.\n # TODO: When this code is finalized, use request.amo_user instead.\n user = UserProfile.objects.get(pk=request.user.id)\n if user.read_dev_agreement:\n # TODO: Have decorator redirect to next step.\n return redirect('submit.app.manifest')\n\n agreement_form = forms.DevAgreementForm(\n request.POST or {'read_dev_agreement': True}, instance=user)\n if request.POST and agreement_form.is_valid():\n agreement_form.save()\n return redirect('submit.app.manifest')\n return jingo.render(request, 'submit/terms.html', {\n 'step': 'terms',\n 'agreement_form': agreement_form,\n })\n\n\n@login_required\n@submit_step('manifest')\n@transaction.commit_on_success\ndef manifest(request):\n # TODO: Have decorator handle the redirection.\n user = UserProfile.objects.get(pk=request.user.id)\n if not user.read_dev_agreement:\n # And we start back at one...\n return redirect('submit.app')\n\n form = forms.NewWebappForm(request.POST or None)\n if request.method == 'POST' and form.is_valid():\n data = form.cleaned_data\n\n plats = [Platform.objects.get(id=amo.PLATFORM_ALL.id)]\n addon = Addon.from_upload(data['upload'], plats)\n if addon.has_icon_in_manifest():\n # Fetch the icon, do polling.\n addon.update(icon_type='image/png')\n tasks.fetch_icon.delay(addon)\n else:\n # In this case there is no need to do any polling.\n addon.update(icon_type='')\n\n AddonUser(addon=addon, user=request.amo_user).save()\n # Checking it once. Checking it twice.\n AppSubmissionChecklist.objects.create(addon=addon, terms=True,\n manifest=True)\n\n return redirect('submit.app.details', addon.app_slug)\n\n return jingo.render(request, 'submit/manifest.html', {\n 'step': 'manifest',\n 'form': form,\n })\n\n\n@dev_required\n@submit_step('details')\ndef details(request, addon_id, addon):\n # Name, Slug, Summary, Description, Privacy Policy,\n # Homepage URL, Support URL, Support Email.\n form_basic = AppDetailsBasicForm(request.POST or None, instance=addon,\n request=request)\n form_cats = CategoryFormSet(request.POST or None, addon=addon,\n request=request)\n form_devices = DeviceTypeForm(request.POST or None, addon=addon)\n form_icon = AppFormMedia(request.POST or None, request.FILES or None,\n instance=addon, request=request)\n form_previews = PreviewFormSet(request.POST or None, prefix='files',\n queryset=addon.get_previews())\n\n # For empty webapp-locale (or no-locale) fields that have\n # form-locale values, duplicate them to satisfy the requirement.\n form_locale = request.COOKIES.get(\"current_locale\", \"\")\n app_locale = to_language(addon.default_locale)\n for name, value in request.POST.items():\n if value:\n if name.endswith(form_locale):\n basename = name[:-len(form_locale)]\n else:\n basename = name + '_'\n othername = basename + app_locale\n if not request.POST.get(othername, None):\n request.POST[othername] = value\n forms = {\n 'form_basic': form_basic,\n 'form_devices': form_devices,\n 'form_cats': form_cats,\n 'form_icon': form_icon,\n 'form_previews': form_previews,\n }\n\n if request.POST and all(f.is_valid() for f in forms.itervalues()):\n addon = form_basic.save(addon)\n form_devices.save(addon)\n form_cats.save()\n form_icon.save(addon)\n for preview in form_previews.forms:\n preview.save(addon)\n AppSubmissionChecklist.objects.get(addon=addon).update(details=True)\n return redirect('submit.app.payments', addon.app_slug)\n\n ctx = {\n 'step': 'details',\n 'addon': addon,\n }\n ctx.update(forms)\n return jingo.render(request, 'submit/details.html', ctx)\n\n\n@dev_required\n@submit_step('payments')\ndef payments(request, addon_id, addon):\n form = forms.PremiumTypeForm(request.POST or None)\n if request.POST and form.is_valid():\n addon.update(premium_type=form.cleaned_data['premium_type'])\n\n if addon.premium_type in [amo.ADDON_PREMIUM, amo.ADDON_PREMIUM_INAPP]:\n return redirect('submit.app.payments.upsell', addon.app_slug)\n if addon.premium_type == amo.ADDON_FREE_INAPP:\n return redirect('submit.app.payments.paypal', addon.app_slug)\n\n AppSubmissionChecklist.objects.get(addon=addon).update(payments=True)\n addon.mark_done()\n return redirect('submit.app.done', addon.app_slug)\n return jingo.render(request, 'submit/payments.html', {\n 'step': 'payments',\n 'addon': addon,\n 'form': form\n })\n\n\n@dev_required\n@submit_step('payments')\ndef payments_upsell(request, addon_id, addon):\n form = forms.UpsellForm(request.POST or None, request=request,\n extra={'addon': addon,\n 'amo_user': request.amo_user})\n if request.POST and form.is_valid():\n form.save()\n return redirect('submit.app.payments.paypal', addon.app_slug)\n return jingo.render(request, 'submit/payments-upsell.html', {\n 'step': 'payments',\n 'addon': addon,\n 'form': form\n })\n\n\n@dev_required\n@submit_step('payments')\ndef payments_paypal(request, addon_id, addon):\n form = PaypalSetupForm(request.POST or None)\n if request.POST and form.is_valid():\n existing = form.cleaned_data['business_account']\n if existing == 'later':\n # We'll have a premium or similar account with no PayPal id\n # at this point.\n (AppSubmissionChecklist.objects.get(addon=addon)\n .update(payments=True))\n return redirect('submit.app.done', addon.app_slug)\n if existing != 'yes':\n # Go create an account.\n # TODO: this will either become the API or something some better\n # URL for the future.\n return redirect(settings.PAYPAL_CGI_URL)\n addon.update(paypal_id=form.cleaned_data['email'])\n return redirect('submit.app.payments.bounce', addon.app_slug)\n return jingo.render(request, 'submit/payments-paypal.html', {\n 'step': 'payments',\n 'addon': addon,\n 'form': form\n })\n\n\n@dev_required\n@submit_step('payments')\ndef payments_bounce(request, addon_id, addon):\n paypal_url = paypal.get_permission_url(addon, 'submission',\n ['REFUND',\n 'ACCESS_BASIC_PERSONAL_DATA',\n 'ACCESS_ADVANCED_PERSONAL_DATA'])\n return jingo.render(request, 'submit/payments-bounce.html', {\n 'step': 'payments',\n 'paypal_url': paypal_url,\n 'addon': addon\n })\n\n\n@dev_required\n@submit_step('payments')\ndef payments_confirm(request, addon_id, addon):\n adp, created = AddonPaymentData.objects.safer_get_or_create(addon=addon)\n form = PaypalPaymentData(request.POST or None, instance=adp)\n if request.method == 'POST' and form.is_valid():\n adp.update(**form.cleaned_data)\n AppSubmissionChecklist.objects.get(addon=addon).update(payments=True)\n addon.mark_done()\n return redirect('submit.app.done', addon.app_slug)\n\n return jingo.render(request, 'submit/payments-confirm.html', {\n 'step': 'payments',\n 'addon': addon,\n 'form': form\n })\n\n\n@dev_required\ndef done(request, addon_id, addon):\n # No submit step forced on this page, we don't really care.\n return jingo.render(request, 'submit/done.html', {\n 'step': 'done', 'addon': addon\n })\n\n\n@dev_required\ndef resume(request, addon_id, addon):\n try:\n # If it didn't go through the app submission\n # checklist. Don't die. This will be useful for\n # creating apps with an API later.\n step = addon.appsubmissionchecklist.get_next()\n except ObjectDoesNotExist:\n step = None\n\n # If there is not a Free app and there's no PayPal id, they\n # clicked \"later\" in the submission flow.\n if not step and addon.premium_type != amo.ADDON_FREE:\n return redirect(addon.get_dev_url('paypal_setup'))\n\n return _resume(addon, step)\n\n\ndef _resume(addon, step):\n if step:\n if step in ['terms', 'manifest']:\n return redirect('submit.app.%s' % step)\n return redirect(reverse('submit.app.%s' % step,\n args=[addon.app_slug]))\n\n return redirect(addon.get_dev_url('edit'))\n","sub_path":"mkt/submit/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":10506,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"64557417","text":"from flask import Flask, render_template, request, redirect\nfrom flask_sqlalchemy import SQLAlchemy\nfrom sqlalchemy import func\nfrom datetime import datetime\n\napp = Flask(__name__)\napp.debug = True\napp.config['SQLALCHEMY_DATABASE_URI'] = 'postgres://asiopgjackioyq' \\\n ':77c694ab09e3fcf8c89a8ca55056c19ebc4be7d6ab4e8b27854670c123948bf1@ec2-54-225' \\\n '-242-183.compute-1.amazonaws.com:5432/d6i8f80sqi62dd'\napp.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = 'True'\n\ndb = SQLAlchemy(app)\n\n\nclass Answer(db.Model):\n __table_name__ = 'answers'\n\n id = db.Column(db.Integer, primary_key=True)\n created_at = db.Column(db.DateTime, default=datetime.now)\n\n season = db.Column(db.String(10))\n place = db.Column(db.String(10))\n favourite = db.Column(db.String(50))\n accommodation = db.Column(db.String(20))\n mean = db.Column(db.String(15))\n planning = db.Column(db.String(50))\n partners = db.Column(db.String(50))\n is_active = db.Column(db.String(50))\n activity = db.Column(db.String(50))\n last_holidays = db.Column(db.String(50))\n abroad = db.Column(db.String(50))\n arrangements = db.Column(db.String(100))\n expenses = db.Column(db.String(30))\n\n def __init__(self,\n season,\n place,\n favourite,\n accommodation,\n mean,\n planning,\n partners,\n is_active,\n activity,\n last_holidays,\n abroad,\n arrangements,\n expenses):\n self.season = season\n self.place = place\n self.favourite = favourite\n self.accommodation = accommodation\n self.mean = mean\n self.planning = planning\n self.partners = partners\n self.is_active = is_active\n self.activity = activity\n self.last_holidays = last_holidays\n self.abroad = abroad\n self.arrangements = arrangements\n self.expenses = expenses\n\n\n@app.route(\"/\")\ndef welcome():\n return render_template('welcome_template.html')\n\n\n@app.route(\"/survey/\")\ndef show_form():\n return render_template('survey_template.html')\n\n\n@app.route(\"/save\", methods=['POST'])\ndef save():\n _season = request.form[\"season\"]\n _place = request.form[\"place\"]\n _favourite = request.form[\"favourite\"]\n _favourite_text = request.form[\"favourite_text\"]\n _accommodation = request.form[\"accommodation\"]\n _mean = request.form[\"mean\"]\n _planning = request.form[\"planning\"]\n _partners = request.form[\"partners\"]\n _partners_text = request.form[\"partners_text\"]\n _is_active = request.form[\"is_active\"]\n _activity = request.form[\"activity\"]\n _last_holidays = request.form[\"last_holidays\"]\n _abroad = request.form[\"abroad\"]\n _arrangements = request.form[\"arrangements\"]\n _expenses = request.form[\"expenses\"]\n\n answer = Answer(_season,\n _place,\n get_favourite(_favourite, _favourite_text),\n _accommodation,\n _mean,\n _planning,\n get_partners(_partners, _partners_text),\n _is_active,\n _activity,\n _last_holidays,\n _abroad,\n _arrangements,\n _expenses)\n db.session.add(answer)\n db.session.commit()\n\n return redirect(\"/results/\")\n\n\ndef get_favourite(_favourite, _favourite_text):\n if _favourite == \"Tak\":\n return _favourite_text\n\n else:\n return _favourite\n\n\ndef get_partners(_partners, _partners_text):\n if _partners == \"Inne\":\n return _partners_text\n\n else:\n return _partners\n\n\n@app.route(\"/results/\")\ndef show_results():\n return render_template(\"results_template.html\")\n\n\n@app.route(\"/charts/\", methods=['POST'])\ndef charts():\n type = request.form['type']\n\n if type == 'season':\n parameter = Answer.season\n\n elif type == 'place':\n parameter = Answer.place\n\n elif type == 'hotel':\n parameter = Answer.accommodation\n\n elif type == 'transport':\n parameter = Answer.mean\n\n elif type == 'partner':\n parameter = Answer.partners\n\n elif type == 'activity':\n parameter = Answer.activity\n\n elif type == 'abroad':\n parameter = Answer.abroad\n\n elif type == 'expenses':\n parameter = Answer.expenses\n\n else:\n parameter = Answer.season\n\n total = func.count(Answer.id)\n\n answers = db.session.query(parameter, total).group_by(parameter).all()\n\n return render_template('charts_template.html', data=answers)\n\n\n@app.route(\"/info/\")\ndef info():\n return render_template('info_template.html')\n\n\nif __name__ == \"__main__\":\n app.run(debug=True)\n\n","sub_path":"hello.py","file_name":"hello.py","file_ext":"py","file_size_in_byte":4854,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"50614490","text":"import nltk\nimport os \nimport glob\nimport math\n'''\nget probability of words in documents\n'''\ndef get_prob(frequency,length): \n for key in frequency:\n frequency[key] = frequency[key]/length\n return frequency\n\n\n\n'''\nread files in a list and clean and tokenize the chapters and the query\n'''\ndef process_files(text_list):\n freq = []\n prob = []\n for act in text_list:\n if \"act\" in act:\n with open(act) as file:\n tokens = nltk.word_tokenize(file.read()) \n words = [w.lower() for w in tokens if w.isalpha()] # filter tokens \n freq.append(nltk.FreqDist(words)) # get frequence of words in document\n prob.append(get_prob(nltk.FreqDist(words),len(words))) \n else:\n with open(act) as file:\n query_token = nltk.word_tokenize(file.read())\n query = [w.lower() for w in query_token if w.isalpha()]\n \n return(query,prob,freq)\n\n'''\napply smoothing \n'''\ndef add_smoothing(query,freq):\n prob = []\n for act_freq in freq:\n add_list = []\n add_dic = dict()\n for token in set(query): #findwords whichare not in the act\n if token not in list(act_freq.keys()):\n add_list.append(token)\n \n for word in add_list: # add missing words to dict\n add_dic[word] = 1\n \n for key in act_freq: # add 1 to all other enries in dict act_freq\n act_freq[key] += 1\n \n act_freq.update(add_dic)\n prob.append(get_prob(act_freq, sum(act_freq.values()))) # collect all smoothed dicts in the list prob\n \n return prob\n\n\ndef calculate_prob(dict_prob,query):\n p = 1\n r = 1\n for word in query:\n p= p* math.log(dict_prob[word])\n r= r* dict_prob[word]\n return p\n\n\n\n'''\ncalculate the relevance of query\n'''\ndef relevance_of_query(query,prob,freq):\n \n prob = add_smoothing(query,freq)\n \n #print(sum(prob[1].values()))\n prob_list = []\n for act_prob in prob:\n prob_list.append(calculate_prob(act_prob,query))\n \n return prob_list \n \n \n \n \n\n\n\n'''\nmain funtion\n'''\nif __name__==\"__main__\": \n path = os.getcwd()\n os.chdir(path+'/Text')\n text_list = glob.glob('*.txt')\n \n query,prob,freq = process_files(text_list)\n \n query_prob = relevance_of_query(query,prob,freq)\n \n dictionary = dict(zip(text_list,query_prob,))\n \n ranking = sorted(dictionary,key=dictionary.__getitem__)\n\n print('The printed list shows the ranking of the acts sorted from high relevance to low relevance:')\n print(ranking)\n'''\nübereinstimmung mit query bestimmen\n'''","sub_path":"Exercise_02/exercise2.1.py","file_name":"exercise2.1.py","file_ext":"py","file_size_in_byte":2967,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"9994303","text":"import nmap\n#You can download nmap module from http://xael.org/pages/python-nmap-0.5.0-1.tar.gz\n#How to install module: unpack it and invoke the command 'python setup.py install'\nNets={'10.0.15.0/24', '10.0.145.0/24', '10.0.155.0/24', '10.0.156.0/24', '10.15.160.0/24', '10.15.193.0/24'}\nUbuntus=open('ubuntus.txt','w')\nnm = nmap.PortScanner()\nnm2 = nmap.PortScanner()\nfor hosts in Nets:\n nm.scan(hosts,'22','-n -sV --open')\n for host in nm.all_hosts():\n if nm[host]['tcp'][22]['version'] == '6.9p1 Ubuntu 2':\n nm2.scan(host,'445','-n -sV --open')\n hostname=nm2[host]['tcp'][445]['extrainfo'].replace('workgroup: ','')\n ssh_logo=nm[host]['tcp'][22]['product']\n ssh_version=nm[host]['tcp'][22]['version']\n Ubuntus.write('Host: %s (%s) %s %s\\n' % (hostname, host, ssh_logo, ssh_version))\nUbuntus.close() \n","sub_path":"Where_are_ubuntus.py","file_name":"Where_are_ubuntus.py","file_ext":"py","file_size_in_byte":872,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"535128171","text":"\"\"\"\nModels and managers for generic tagging.\n\"\"\"\n# Python 2.3 compatibility\ntry:\n set\nexcept NameError:\n from sets import Set as set\n\nfrom django.conf import settings\nfrom django.contrib.contenttypes import generic\nfrom django.contrib.contenttypes.models import ContentType\nfrom django.db import connection, models\nfrom django.db.models.query import QuerySet\nfrom django.utils.translation import ugettext_lazy as _\n\nfrom tagging import settings\nfrom tagging.utils import calculate_cloud, get_tag_list, get_queryset_and_model, parse_tag_input\nfrom tagging.utils import LOGARITHMIC, unique_from_iter\n\nif hasattr(settings, 'OWNER_MODEL') and settings.OWNER_MODEL:\n OWNER_MODEL = settings.OWNER_MODEL\nelse:\n from django.contrib.auth.models import User\n OWNER_MODEL = User\n\nqn = connection.ops.quote_name\n\n\n\n\n############\n# Managers #\n############\n\nclass TagManager(models.Manager):\n\n def update_tags(self, obj, tag_names, owner):\n \"\"\"\n Update tags associated with an object.\n \"\"\"\n ctype = ContentType.objects.get_for_model(obj)\n current_tags = list(self.filter(items__content_type__pk=ctype.pk,\n items__owners=owner,\n items__object_id=obj.pk))\n updated_tag_names = parse_tag_input(tag_names)\n if settings.FORCE_LOWERCASE_TAGS:\n updated_tag_names = [t.lower() for t in updated_tag_names]\n\n # Remove tags which no longer apply\n tags_for_removal = [tag for tag in current_tags \\\n if tag.name not in updated_tag_names]\n if len(tags_for_removal):\n items = TaggedItem._default_manager.filter(content_type__pk=ctype.pk,\n object_id=obj.pk,\n tag__in=tags_for_removal)\n for tag in tags_for_removal:\n if TaggedItem._default_manager.filter(owners=owner, content_type=ctype, object_id=tag.pk).count() <= 1:\n tag.owners.remove(owner)\n tag.save()\n\n for item in items:\n # remove the owner from the list\n item.owners.remove(owner)\n # if no one is using this tag anymore, remove it\n if item.owners.all().count():\n item.save()\n else:\n item.delete()\n\n # Add new tags\n current_tag_names = [tag.name for tag in current_tags]\n for tag_name in updated_tag_names:\n if tag_name not in current_tag_names:\n tag, created = self.get_or_create(name=tag_name)\n\n if owner not in tag.owners.all():\n tag.owners.add(owner)\n tag.save()\n\n t_item, created = TaggedItem._default_manager.get_or_create(tag=tag, object_id=obj.pk, content_type=ctype)\n t_item.owners.add(owner)\n t_item.save()\n\n\n def add_tag(self, obj, tag_name, owner):\n \"\"\"\n Associates the given object with a tag.\n \"\"\"\n tag_names = parse_tag_input(tag_name)\n if not len(tag_names):\n raise AttributeError(_('No tags were given: \"%s\".') % tag_name)\n if len(tag_names) > 1:\n raise AttributeError(_('Multiple tags were given: \"%s\".') % tag_name)\n tag_name = tag_names[0]\n if settings.FORCE_LOWERCASE_TAGS:\n tag_name = tag_name.lower()\n tag, created = self.get_or_create(name=tag_name)\n \n if owner not in tag.owners.all():\n tag.owners.add(owner)\n tag.save()\n\n ctype = ContentType.objects.get_for_model(obj)\n t_item, created = TaggedItem._default_manager.get_or_create(tag=tag, content_type=ctype, object_id=obj.pk)\n t_item.owners.add(owner)\n t_item.save()\n\n def get_for_object_owner(self, obj, owner):\n \"\"\"\n Create a queryset matching all tags associated with the given\n object and owner.\n \"\"\"\n return self.get_for_object(obj, owner, items__owners=owner)\n \n def get_for_model(self, model, owner_mark=None, *filter_args, **filter_kwargs):\n \"\"\"\n Create a queryset matching the popular tags associated with the given\n object.\n \"\"\"\n\n ctype = ContentType.objects.get_for_model(model)\n\n extra_select = {'popular': 'tagging_taggeditem.popular'} \n select_params = []\n\n if owner_mark is not None:\n extra_select['is_own'] = '(SELECT COUNT(*) > 0 from tagging_taggeditem_owners WHERE taggeditem_id = tagging_taggeditem.id AND user_id = %s)'\n select_params.append(owner_mark.pk)\n \n filter_kwargs['items__content_type'] = ctype\n\n return self.select_related().filter(*filter_args, \n **filter_kwargs).extra(select=extra_select, select_params=select_params).distinct()\n # distinct is fail-safe hack for prevent wrong result when django creates \n # additional join when you try to make another .filter(items__ ... ) call\n\n def get_for_object(self, obj, owner_mark=None, *filter_args, **filter_kwargs):\n\n filter_kwargs['items__object_id'] = obj.pk\n \n return self.get_for_model(obj, owner_mark, *filter_args, **filter_kwargs)\n\n def get_for_owner(self, owner):\n\n return self.filter(items__owners=owner).distinct('pk')\n\n\n \n\nclass TaggedItemManager(models.Manager):\n \"\"\"\n \"\"\"\n\n def _get_matching_ids(self, model, tags, filter_function=None):\n \n if filter_function is None:\n filter_function = lambda item: True\n \n assert callable(filter_function)\n\n for tag in tags.select_related(depth=1):\n for item in tag.items.all():\n if item.object_id and filter_function(item):\n yield item.object_id\n \n\n def match_any(self, model, tags, user_filter_function=None):\n\n ctype = ContentType.objects.get_for_model(model)\n \n default_filter = lambda item: item.content_type==ctype\n\n if user_filter_function is not None:\n filter_function = lambda item: (user_filter_function(item) and default_filter(item))\n else:\n filter_function = default_filter \n\n ids = self._get_matching_ids(model, tags, filter_function)\n return model._default_manager.filter(pk__in=unique_from_iter(ids))\n\n\n def match_all(self, model, tags, user_filter_function=None):\n\n ctype = ContentType.objects.get_for_model(model)\n\n default_filter = lambda item: item.content_type==ctype\n\n if user_filter_function is not None:\n filter_function = lambda item: (user_filter_function(item) and default_filter(item))\n else:\n filter_function = default_filter\n\n ids = list(self._get_matching_ids(model, tags, filter_function))\n tag_len = isinstance(tags, models.query.QuerySet) and tags.count() or len(tags) \n match_all_ids = [id for id in unique_from_iter(ids) if ids.count(id) == tag_len]\n\n if len(match_all_ids) == 0:\n return model._default_manager.none()\n\n return model._default_manager.filter(pk__in=match_all_ids)\n\n\n##########\n# Models # \n##########\n\nclass Tag(models.Model):\n \"\"\"\n A tag.\n \"\"\"\n name = models.CharField(_('name'), max_length=50, unique=True, db_index=True)\n owners = models.ManyToManyField(OWNER_MODEL)\n objects = TagManager()\n\n class Meta:\n ordering = ('name',)\n verbose_name = _('tag')\n verbose_name_plural = _('tags')\n\n def __unicode__(self):\n return self.name\n\nclass TaggedItem(models.Model):\n \"\"\"\n Holds the relationship between a tag, the item being tagged and the user doing the tagging.\n \"\"\"\n owners = models.ManyToManyField(OWNER_MODEL)\n tag = models.ForeignKey(Tag, verbose_name=_('tag'), related_name='items')\n content_type = models.ForeignKey(ContentType, verbose_name=_('content type'))\n object_id = models.PositiveIntegerField(_('object id'), db_index=True)\n object = generic.GenericForeignKey('content_type', 'object_id')\n popular = models.BooleanField(_('popular'))\n object_id = models.PositiveIntegerField(_('object id'), db_index=True)\n\n objects = TaggedItemManager()\n\n class Meta:\n # Enforce unique tag association per object\n unique_together = (('tag', 'content_type', 'object_id',),)\n verbose_name = _('tagged item')\n verbose_name_plural = _('tagged items')\n\n def __unicode__(self):\n return u'%s [%s]' % (self.object, self.tag)\n\n def save(self, *args, **kwargs):\n\n # cannot work with ManyToMany if model is not created\n \n item = super(TaggedItem, self).save(*args, **kwargs)\n\n TaggedItem.refresh_popular(self.content_type, self.object_id)\n\n return item\n\n @staticmethod\n def refresh_popular(content_type, object_id):\n\n try:\n from .settings import MIN_OWNERS_COUNT_PER_TAG\n except ImportError:\n MIN_OWNERS_COUNT_PER_TAG = 0\n \n queryset = TaggedItem.objects.filter(content_type=content_type, object_id=object_id)\n\n tag_count = queryset.count()\n total_owners_count = queryset.aggregate(models.Count('owners'))['owners__count']\n avg = total_owners_count/tag_count\n \n if avg < MIN_OWNERS_COUNT_PER_TAG:\n avg = MIN_OWNERS_COUNT_PER_TAG\n\n popular_ids = [item['pk'] for item in queryset.annotate(oc=models.Count('owners')).filter(oc__gt=avg).values('pk')]\n\n queryset.exclude(pk__in=popular_ids).update(popular=False)\n queryset.filter(pk__in=popular_ids).update(popular=True)\n \n \n \n \n \n","sub_path":"models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":9843,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"603388500","text":"import io\nimport json\nimport logging\nimport os\nfrom typing import Dict, Iterator, List, Optional\n\nfrom docker.types import Mount\nfrom redis import StrictRedis\n\nfrom plz.controller.containers import ContainerState, Containers\nfrom plz.controller.images import Images\nfrom plz.controller.instances.instance_base import ExecutionInfo, Instance, \\\n KillingInstanceException, Parameters\nfrom plz.controller.api.exceptions import InstanceStillRunningException\nfrom plz.controller.results import ResultsStorage\nfrom plz.controller.results.results_base import CouldNotGetOutputException\nfrom plz.controller.volumes import \\\n VolumeDirectory, VolumeEmptyDirectory, VolumeFile, Volumes\n\nlog = logging.getLogger(__name__)\n\n\nclass DockerInstance(Instance):\n def __init__(self,\n images: Images,\n containers: Containers,\n volumes: Volumes,\n execution_id: str,\n redis: StrictRedis,\n lock_timeout: int):\n super().__init__(redis, lock_timeout)\n self.images = images\n self.containers = containers\n self.volumes = volumes\n self.execution_id = execution_id\n\n def run(self,\n command: List[str],\n snapshot_id: str,\n parameters: Parameters,\n input_stream: Optional[io.RawIOBase],\n docker_run_args: Dict[str, str]) -> None:\n configuration = {\n 'input_directory': Volumes.INPUT_DIRECTORY_PATH,\n 'output_directory': Volumes.OUTPUT_DIRECTORY_PATH,\n 'measures_directory': Volumes.MEASURES_DIRECTORY_PATH,\n 'summary_measures_path': os.path.join(\n Volumes.MEASURES_DIRECTORY_PATH, 'summary'),\n 'parameters': parameters\n }\n environment = {\n 'CONFIGURATION_FILE': Volumes.CONFIGURATION_FILE_PATH\n }\n volume = self.volumes.create(self.volume_name, [\n VolumeDirectory(\n Volumes.INPUT_DIRECTORY,\n contents_tarball=input_stream or io.BytesIO()),\n VolumeEmptyDirectory(Volumes.OUTPUT_DIRECTORY),\n VolumeEmptyDirectory(Volumes.MEASURES_DIRECTORY),\n VolumeFile(Volumes.CONFIGURATION_FILE,\n contents=json.dumps(configuration, indent=2)),\n ])\n self.containers.run(execution_id=self.execution_id,\n repository=self.images.repository,\n tag=snapshot_id,\n command=command,\n environment=environment,\n mounts=[Mount(source=volume.name,\n target=Volumes.VOLUME_MOUNT)],\n docker_run_args=docker_run_args)\n\n def stop_execution(self):\n self.containers.stop(self.execution_id)\n\n def _cleanup(self):\n self.containers.rm(self.execution_id)\n self.volumes.remove(self.volume_name)\n self.execution_id = ''\n\n @property\n def volume_name(self):\n return f'plz-{self.execution_id}'\n\n def get_idle_since_timestamp(\n self, container_state: Optional[ContainerState] = None) -> int:\n # Doesn't make sense for local instances\n return 0\n\n def get_resource_state(self) -> str:\n # Docker is always running\n return 'running'\n\n def delete_resource(self) -> None:\n # No underlying resource to delete\n pass\n\n def get_execution_id(self) -> str:\n return self.execution_id\n\n def get_instance_type(self) -> str:\n return 'local'\n\n def get_max_idle_seconds(self) -> int:\n # Doesn't make sense for local instances\n return 0\n\n def dispose_if_its_time(\n self, execution_info: Optional[ExecutionInfo] = None):\n # It's never time for a local instance\n pass\n\n def kill(self, force_if_not_idle: bool):\n if not force_if_not_idle:\n raise KillingInstanceException(\n 'Attempt to kill a running local container, which is not idle')\n try:\n self.containers.kill(self.get_execution_id())\n except Exception as e:\n raise KillingInstanceException(str(e)) from e\n\n def container_state(self) -> Optional[ContainerState]:\n if self.execution_id == '':\n return None\n return self.containers.get_state(self.execution_id)\n\n def release(self,\n results_storage: ResultsStorage,\n idle_since_timestamp: int,\n release_container: bool = True):\n if not release_container:\n # Everything to release here is about the container\n return\n with self._lock:\n self.stop_execution()\n self._publish_results(results_storage,\n finish_timestamp=idle_since_timestamp,\n path=None)\n # Check that we could collect the logs before destroying the\n # container\n if not results_storage.is_finished(self.execution_id):\n raise CouldNotGetOutputException(\n f'Couldn\\'t read the results for {self.execution_id}')\n self._cleanup()\n\n def get_forensics(self) -> dict:\n return {}\n\n def _publish_results(self, results_storage: ResultsStorage,\n finish_timestamp: int, path: Optional[str]):\n results_storage.publish(\n self.get_execution_id(),\n exit_status=self.get_status().exit_status,\n logs=self.get_logs(since=None),\n output_tarball=self.get_output_files_tarball(path),\n measures_tarball=self.get_measures_files_tarball(),\n finish_timestamp=finish_timestamp)\n\n @property\n def instance_id(self):\n return self.execution_id\n\n def get_logs(self, since: Optional[int] = None, stdout: bool = True,\n stderr: bool = True) -> Iterator[bytes]:\n return self.containers.logs(self.execution_id,\n since,\n stdout=stdout,\n stderr=stderr)\n\n def get_output_files_tarball(self, path: Optional[str]) -> Iterator[bytes]:\n return self.containers.get_files(\n self.execution_id,\n os.path.join(Volumes.OUTPUT_DIRECTORY_PATH,\n path if path is not None else ''))\n\n def get_measures_files_tarball(self) -> Iterator[bytes]:\n return self.containers.get_files(\n self.execution_id, Volumes.MEASURES_DIRECTORY_PATH)\n\n def get_stored_metadata(self) -> dict:\n raise InstanceStillRunningException(self.execution_id)\n","sub_path":"services/controller/src/plz/controller/instances/docker.py","file_name":"docker.py","file_ext":"py","file_size_in_byte":6728,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"184255592","text":"import h5py\nimport pickle\nimport numpy as np\nimport json\nfrom collections import OrderedDict, defaultdict\nimport random as rn\nfrom sklearn.ensemble import GradientBoostingRegressor, BaggingRegressor\nfrom xgboost import XGBRegressor\nfrom sklearn.preprocessing import StandardScaler, MinMaxScaler\nfrom lightgbm import LGBMRegressor\nfrom sklearn import datasets\nfrom sklearn.utils import shuffle\nfrom sklearn.metrics import mean_squared_error\nfrom sklearn.model_selection import GridSearchCV\nnp.random.seed(1)\nrn.seed(1)\n\ndef get_cindex(Y, P):\n summ = 0\n pair = 0\n \n for i in range(1, len(Y)):\n for j in range(0, i):\n if i is not j:\n if(Y[i] > Y[j]):\n pair +=1\n summ += 1* (P[i] > P[j]) + 0.5 * (P[i] == P[j])\n \n \n if pair is not 0:\n return summ/pair\n else:\n return 0\n\ndef read_data(train_Y_file, test_Y_file, feature_file):\n\n test_Y = json.load(open(test_Y_file))\n train_Y = json.load(open(train_Y_file))\n f = h5py.File(feature_file,'r') #打开h5文件 \n train_feature = f['train_feature'][:]\n test_feature = f['test_feature'][:]\n f.close()\n #scaler = MinMaxScaler()\n return train_Y, test_Y, train_feature, test_feature\n\ndef experiment(regressor, regressor_args):\n with open(f'log0918lgbbagging_n800.txt', 'w') as f:\n clf = regressor(**regressor_args)\n print(f'Present regressor is {str(regressor)}', file=f)\n #regr = BaggingRegressor(base_estimator=clf, n_estimators=10, random_state=1, n_jobs=-1, verbose=1)\n regr = BaggingRegressor(base_estimator=clf, n_estimators=800, random_state=1, n_jobs=10, verbose=1)\n regr.fit(train_feature, train_Y) \n\n #best_estim.fit(train_feature, train_Y)\n print(f'params:{regr.get_params}', file=f)\n #pickle.dump(regr, open(f'best_bagging_0611_2.pkl', \"wb\"))\n #clf2 = pickle.load(open(\"best_boston.pkl\", \"rb\"))\n gbdt_pred = regr.predict(test_feature)\n\n mse = mean_squared_error(test_Y, gbdt_pred)\n ci = get_cindex(test_Y, gbdt_pred)\n\n print(f'MSE:{mse},CI:{ci}', file=f)\n\n\n\ntrain_Y, test_Y, train_feature, test_feature = read_data(train_Y_file=\"train_Y.txt\", test_Y_file=\"test_Y.txt\", feature_file='DenseFeature.h5')\nregressor = (LGBMRegressor, )\nregressor_args = defaultdict(dict,{LGBMRegressor: dict(random_state=1, max_depth=120, n_estimators=1200, num_leaves=50, learning_rate=0.01)})\n#grid_args = defaultdict(dict,{LGBMRegressor: dict(max_depth=[160, 180, 200, 220], n_estimators=[1800, 2000, 2200], num_leaves=[80, 100, 120], learning_rate=[0.01,0.001])})\n\"\"\"\nregressor = (LGBMRegressor, XGBRegressor)\nregressor_args = defaultdict(dict,{XGBRegressor: dict(random_state=1, learning_rate=0.001, ), LGBMRegressor: dict(random_state=1, metric='mse', bagging_fraction = 0.8, feature_fraction = 0.8)})\ngrid_args = defaultdict(dict,{XGBRegressor: dict(max_depth=[200],n_estimators=[2000,3000]), LGBMRegressor: dict(max_depth=[200, 250], n_estimators=[2000,3000], num_leaves=[60,100], learning_rate=[0.01,0.001])})\n\"\"\"\nfor reg in regressor:\n args = (reg, regressor_args[reg])\n experiment(*args)","sub_path":"bagging.py","file_name":"bagging.py","file_ext":"py","file_size_in_byte":3191,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"29284688","text":"# -*- coding: utf-8 -*-\n\n\"\"\"\n Contains a set of reusable functions to read, pre-process and prepare data.\n\"\"\"\n\nimport os\nimport sys\nimport string\nimport nltk\nimport math\nimport random\nimport itertools\nimport pandas as pd\nimport nltk.tokenize as tokenize\nimport nltk.stem as stem\nimport nltk.corpus as corpus\nimport src.core.helper as helper\n\n\ndef extract_works_sentence_data(dic_works, n_sentences_per_author):\n dic_data = {}\n __download_text_processing_depedencies()\n sent_tokenizer = __get_sent_tokenizer()\n\n for author, paths_works in dic_works.items():\n for path in paths_works:\n raw_data = __read_data(path)\n sent_tokens = sent_tokenizer.tokenize(raw_data)\n filtered_tokens = __filter_sentence_tokens(sent_tokens)\n dic_data[author] = dic_data[author] + filtered_tokens if author in dic_data else [] + filtered_tokens\n\n if len(dic_data[author]) >= n_sentences_per_author:\n dic_data[author] = dic_data[author][0:n_sentences_per_author]\n break\n\n __export_length_sentences(sum(dic_data.values(), []), 100)\n\n return dic_data\n\n\ndef save_training_sentences_as_csv(dic_data_works, n_sentences_per_author):\n n_authors = len(dic_data_works.keys())\n # csv_filename = \"training-{}-sentences.csv\".format(n_sentences_per_author * n_authors * 2)\n csv_filename = \"training-sentences.csv\"\n id_count = 1\n columns = ['qd1', 'qd2', 'phrase1', 'phrase2', 'label']\n dic_dataframe = {'qd1': [], 'qd2': [], 'phrase1': [], 'phrase2': [], 'label': []}\n\n # Phrases of the same author (similarity = 1)\n for author, sentences in dic_data_works.items():\n length_sentences = len(sentences)\n\n for i in range(0, length_sentences, 2):\n dic_dataframe['qd1'].append(id_count)\n dic_dataframe['qd2'].append(id_count + 1)\n dic_dataframe['phrase1'].append(sentences[i])\n dic_dataframe['phrase2'].append(sentences[i + 1])\n dic_dataframe['label'].append(1)\n id_count += 2\n\n # Phrases of the different author (similarity = 0)\n author_combinations = __get_author_combinations(list(dic_data_works.keys()))\n\n for combination in author_combinations:\n author_a = combination[0]\n author_b = combination[1]\n dic_author_a = dic_data_works[author_a]\n dic_author_b = dic_data_works[author_b]\n # length_sentences = int(n_sentences_per_author / 2)\n length_sentences = n_sentences_per_author\n\n for i in range(0, length_sentences):\n dic_dataframe['qd1'].append(id_count)\n dic_dataframe['qd2'].append(id_count + 1)\n dic_dataframe['phrase1'].append(dic_author_a[i])\n dic_dataframe['phrase2'].append(dic_author_b[i])\n dic_dataframe['label'].append(0)\n id_count += 2\n\n dataframe = pd.DataFrame(dic_dataframe, columns=columns)\n dataframe.to_csv(os.path.join(helper.DATA_FILES_TRAINING_PATH, csv_filename), index=False, header=True)\n\n\ndef save_prediction_sentences_as_csv(dic_data_works, n_sentences):\n n_sentences_prediction = math.ceil(n_sentences)\n csv_filename = \"prediction-{}-sentences.csv\".format(n_sentences_prediction)\n columns = ['phrase1', 'phrase2']\n dic_dataframe = {'phrase1': [], 'phrase2': []}\n\n if not bool(dic_data_works):\n return\n\n # First column - Take n_sentences_prediction randomly from the first author\n first_author = next(iter(dic_data_works))\n random.shuffle(dic_data_works[first_author])\n dic_dataframe['phrase1'] = dic_data_works[first_author][0:n_sentences_prediction]\n\n # Second column - Take n_sentences_prediction randomly from authors inside dic_data_works\n random_works = []\n length_authors = len(dic_data_works.keys())\n n_sentences_per_author = math.ceil(n_sentences_prediction / length_authors)\n\n for author in dic_data_works.keys():\n sentences_per_author = [item for item in dic_data_works[author] if item not in dic_dataframe['phrase1']]\n random.shuffle(sentences_per_author)\n random_works += sentences_per_author[0:n_sentences_per_author]\n\n dic_dataframe['phrase2'] = random_works[0:n_sentences_prediction]\n\n # Export to csv file\n dataframe = pd.DataFrame(dic_dataframe, columns=columns)\n dataframe.to_csv(os.path.join(helper.DATA_FILES_PREDICTION_PATH, csv_filename), index=False, header=True)\n\n\ndef list_dir_authors(directory_name):\n dir_authors = []\n\n for dir in os.listdir(directory_name):\n if os.path.isdir(os.path.join(directory_name, dir)):\n dir_authors.append(os.path.join(directory_name, dir))\n\n return dir_authors\n\n\ndef works_by_author(path_author):\n works = []\n\n for file in os.listdir(path_author):\n if os.path.isfile(os.path.join(path_author, file)):\n works.append(os.path.join(path_author, file))\n\n return works\n\n\ndef dic_works_by_authors(path_authors):\n works = {}\n\n for path in path_authors:\n author = __get_author_by_path(path)\n works[author] = [] + works_by_author(path)\n\n return works\n\n\ndef __read_data(filename):\n try:\n with open(filename, mode='r') as f:\n raw_data = f.read()\n except FileNotFoundError as err:\n print(err)\n sys.exit(1)\n except IOError as err:\n print(err)\n sys.exit(1)\n except Exception as err:\n print(err)\n sys.exit(1)\n else:\n return raw_data\n\n\ndef __get_list_common_abrrev():\n return [\n \"Mr\", \"Mrs\", \"LLC\", \"Pres\", \"approx\", \"min\", \"vs\", \"E.T.A\", \"dept\", \"c/o\", \"B.Y.O.B\", \"apt\", \"appt\", \"A.S.A.P\",\n \"D.I.Y\", \"est\", \"vet\", \"temp\", \"R.S.V.P\"\n ]\n\n\ndef __get_sent_tokenizer():\n punkt_params = tokenize.punkt.PunktParameters()\n punkt_params.abbrev_types = set(__get_list_common_abrrev())\n tokenizer = tokenize.punkt.PunktSentenceTokenizer(punkt_params)\n\n return tokenizer\n\n\ndef __get_wordnet_pos(word):\n wordnet = corpus.wordnet\n\n tag = nltk.pos_tag([word])[0][1][0].upper()\n tag_dict = {\n \"J\": wordnet.ADJ,\n \"N\": wordnet.NOUN,\n \"V\": wordnet.VERB,\n \"R\": wordnet.ADV\n }\n\n return tag_dict.get(tag, wordnet.NOUN)\n\n\ndef __download_text_processing_depedencies():\n nltk.download('wordnet')\n nltk.download('averaged_perceptron_tagger')\n nltk.download('punkt')\n nltk.download('stopwords')\n\n\ndef __filter_sentence_tokens(sent_tokens):\n sent_tokens = __slice_sentence_tokens(sent_tokens, 5)\n filtered_tokens = []\n # stemmer = stem.PorterStemmer() # Stemming\n lemmatizer = stem.WordNetLemmatizer() # Lemmatization\n stopwords = set(corpus.stopwords.words('english'))\n\n for sentence in sent_tokens:\n if not __valid_sentence_token(sentence):\n continue\n\n # Split into words\n tokens = tokenize.word_tokenize(sentence)\n\n # Convert to lower case\n tokens = [w.lower() for w in tokens]\n\n # Stemming of words\n # tokens = [stemmer.stem(w) for w in tokens]\n\n # Lemmatization of words\n tokens = [lemmatizer.lemmatize(w, __get_wordnet_pos(w)) for w in tokens]\n\n # Remove punctuation from each word\n table = str.maketrans('', '', string.punctuation)\n stripped = [w.translate(table) for w in tokens]\n\n # Remove remaining tokens that are not alphabetic\n word_list = [word for word in stripped if word.isalpha()]\n\n # Removing stopwords\n word_list = [word for word in word_list if word not in stopwords]\n\n # Join the words normalized with one common space\n normalized_sentence = ' '.join(word_list)\n\n # Check if the sentence normalized is valid\n if not __valid_sentence_token(normalized_sentence):\n continue\n\n # Add the sentence normalized to list\n filtered_tokens.append(normalized_sentence)\n\n return filtered_tokens\n\n\ndef __valid_sentence_token(sent_token):\n if '\\n' in sent_token:\n return False\n\n if len(sent_token.strip()) <= 0 or len(sent_token.split()) > 150:\n return False\n\n return True\n\n\ndef __slice_sentence_tokens(sent_tokens, percent):\n length_sentences = len(sent_tokens)\n\n if sent_tokens is None or length_sentences <= 0:\n return []\n\n abs_percent = percent / 100\n abs_units = math.ceil(length_sentences * abs_percent)\n\n start_index = abs_units\n end_index = (length_sentences - abs_units) + 1\n result = sent_tokens[start_index:end_index]\n\n return result\n\n\ndef __get_author_by_path(path):\n return path.split('/')[-1]\n\n\ndef __get_author_combinations(authors):\n combinations_object = itertools.combinations(authors, 2)\n combinations = list(combinations_object)\n\n return combinations\n\n\ndef __export_length_sentences(tokens, length_sentences):\n dic_dataframe = {'length': [], 'sentence': []}\n sorted_tokens = sorted(tokens, key=lambda sentence: len(sentence.split()), reverse=True)\n\n for s in sorted_tokens:\n length_current_sentence = len(s.split())\n\n if length_current_sentence >= length_sentences:\n dic_dataframe['length'].append(length_current_sentence)\n dic_dataframe['sentence'].append(s)\n\n csv_filename = \"sentences-greater-{}.csv\".format(length_sentences)\n dataframe = pd.DataFrame(dic_dataframe, columns=['length', 'sentence'])\n dataframe.to_csv(os.path.join(helper.DATA_FILES_RESULTS_PATH, csv_filename), index=False, header=True)\n","sub_path":"src/core/data_structuring.py","file_name":"data_structuring.py","file_ext":"py","file_size_in_byte":9426,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"613109957","text":"import sys\nsys.path.append(\"..\")\n\nimport os, argparse\nfrom tqdm import tqdm, trange\nimport numpy as np\n\nimport torch\nimport torch.utils.data\nimport torch.nn.functional as F\n\nimport config as cfg\nimport global_data\nimport optimizer as optim\nimport data\nimport model as txl_model\n\n\ndef train_epoch(config, epoch, model, loss_fn, optimizer, scheduler, train_iter):\n losses = []\n model.train()\n\n mems = tuple()\n with tqdm(total=len(train_iter), desc=f\"Train {epoch}\") as pbar:\n for i, value in enumerate(train_iter):\n inputs, labels = map(lambda v: v.to(config.device), value)\n optimizer.zero_grad()\n\n logit, mems = model(inputs, *mems)\n\n loss = loss_fn(logit.view(-1, logit.size(2)), labels.view(-1))\n loss_val = loss.item()\n losses.append(loss_val)\n\n loss.backward()\n optimizer.step()\n scheduler.step()\n\n pbar.update(1)\n pbar.set_postfix_str(f\"Loss: {loss_val:.3f} ({np.mean(losses):.3f})\")\n\n\ndef train_model(cuda, vocab_file, data_pkl, save_pretrain_file):\n config = cfg.Config.load(\"config.json\")\n\n vocab = global_data.load_vocab(vocab_file)\n token_ids = data.load_pretrain(data_pkl)\n\n config.device = torch.device(cuda if torch.cuda.is_available() else \"cpu\")\n config.n_vocab = len(vocab)\n config.n_enc_vocab = len(vocab)\n config.n_dec_vocab = len(vocab)\n config.i_pad = global_data.PAD_ID\n config.n_batch = 64\n config.n_epoch = 3\n print(config)\n config.device = torch.device(\"cpu\")\n\n offset = 0\n model = txl_model.TXLPretrain(config)\n if os.path.isfile(save_pretrain_file):\n offset = model.decoder.load(save_pretrain_file) + 1\n print(\">>>> load state dict from: \", save_pretrain_file)\n model.to(config.device)\n\n train_iter = data.TXLIterator(config, token_ids)\n\n loss_fn = torch.nn.CrossEntropyLoss(ignore_index=-1)\n \n t_total = len(train_iter) * config.n_epoch\n no_decay = ['bias', 'LayerNorm.weight']\n optimizer_grouped_parameters = [\n {'params': [p for n, p in model.named_parameters() if not any(nd in n for nd in no_decay)], 'weight_decay': config.weight_decay},\n {'params': [p for n, p in model.named_parameters() if any(nd in n for nd in no_decay)], 'weight_decay': 0.0}\n ]\n optimizer = optim.AdamW(optimizer_grouped_parameters, lr=config.learning_rate, eps=config.adam_epsilon)\n scheduler = optim.WarmupLinearSchedule(optimizer, warmup_steps=config.warmup_steps, t_total=t_total)\n \n for step in trange(config.n_epoch, desc=\"Epoch\"):\n epoch = step + offset\n train_epoch(config, epoch, model, loss_fn, optimizer, scheduler, train_iter)\n model.decoder.save(epoch, save_pretrain_file)\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--cuda\", default=\"cuda\", type=str, required=False,\n help=\"cuda device # cuda / cuda:0 / cuda:1\")\n parser.add_argument(\"--vocab\", default=\"8000\", type=str, required=False,\n help=\"vocab size # 8000 / 1600\")\n args = parser.parse_args()\n\n vocab_file = f\"../data/m_snli_{args.vocab}.model\"\n data_pkl = f\"../data/pretrain_gpt_{args.vocab}_0.pkl\"\n save_pretrain_file = f\"save_pretrain_{args.vocab}.pth\"\n\n train_model(args.cuda, vocab_file, data_pkl, save_pretrain_file)\n","sub_path":"cchyun/txl/pretrain.py","file_name":"pretrain.py","file_ext":"py","file_size_in_byte":3385,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"43377777","text":"from User.models import User\nfrom essential_generators import DocumentGenerator\ngen = DocumentGenerator()\nimport random\nimport string\nnewUsersGen = 8000\ntemplate = {\n 'username' : 'name',\n \"email\" : \"email\"\n }\nN= 4\ngen.set_template(template)\ndocuments = gen.documents(newUsersGen)\nfor doc in documents:\n\n randomContraint = ''.join(random.choices(string.ascii_uppercase + string.digits, k=N))\n try:\n user = User.objects.create_user(username=doc[\"username\"]+randomContraint,\n email=doc[\"email\"],\n password='beefpattiestesting')\n except Exception as e:\n print(e)","sub_path":"Messenger-BackEnd/Test/User/genNewUsers.py","file_name":"genNewUsers.py","file_ext":"py","file_size_in_byte":680,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"122563080","text":"import matplotlib.pyplot as plt\nimport numpy as np\n\n\ndef demo():\n labels = np.array([\"Jan\", \"Feb\", \"Mar\", \"Apr\", \"May\", \"Jun\"])\n x = np.arange(labels.size)\n y1 = np.random.normal(80, 10, x.size)\n y2 = np.random.normal(95, 12, x.size)\n plt.bar(x, y1, color=\"deepskyblue\", alpha=.3, label=\"we\")\n plt.plot(x, y2, color=\"orange\", label=\"industry\", marker=\"o\")\n plt.xticks(x, labels)\n plt.legend()\n plt.title(\"Sales (Jan-Jun 2017)\")\n plt.ylabel(\"Sales ('000)\")\n plt.show()\n\n\nif __name__ == '__main__':\n demo()\n","sub_path":"src/plot_combo.py","file_name":"plot_combo.py","file_ext":"py","file_size_in_byte":541,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"100647411","text":"from payments.signals import status_changed\nfrom django.dispatch import receiver\n\nfrom ..core import analytics\n\n\n@receiver(status_changed)\ndef order_status_change(sender, instance, **kwargs):\n order = instance.order\n if order.is_fully_paid():\n order.change_status('fully-paid')\n instance.send_confirmation_email()\n analytics.report_order(order.tracking_client_id, order)\n","sub_path":"saleor/payment/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":398,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"496654216","text":"import numpy as np\nimport sys\nimport gzip\n\nfrom collections import defaultdict\nbuckets=defaultdict(list)\nwith gzip.open(sys.argv[1],'rt') as f:\n for line in f:\n if line.startswith('[broker]'):\n fields=line.strip().split(\" \")\n arrival_time = float(fields[1])*1000 #sec to ms\n complt_time = float(fields[2]) #ms\n arrival_bucket=(arrival_time + complt_time)//1000 #to seconds\n buckets[arrival_bucket].append(complt_time)\n\nw=[]\nfor i in range(0, len(buckets)):\n w.clear()\n for j in range(i-min(i, 30), i): #30 sec moving windows\n if j in buckets:\n w += buckets[j]\n print(0 if not w else np.percentile(w, 95))\n","sub_path":"scripts/mungetime-gzip.py","file_name":"mungetime-gzip.py","file_ext":"py","file_size_in_byte":697,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"1301564","text":"\nclass Circular_Queue:\n def __init__(self,n):\n self.array = [None] * Q_size\n self.front = 0 % Q_size\n self.back = 0 % Q_size\n\n\n def enQueue(self, num):\n self.array[self.back] = int(num)\n self.back = (self.back + 1) % Q_size\n print(self.array)\n print(self.back)\n \n \n def deQueue(self):\n last_val = self.array[self.front]\n self.array[self.front] = None\n print(self.array)\n self.front = (self.front + 1) % Q_size\n return last_val\n \n def size(self):\n return abs(self.front - self.back)\n \n def empty(self):\n if self.array:\n return 0\n if self.front == self.back:\n return 1\n \n def front_val(self):\n if self.empty == 1:\n return -1\n return self.array[self.front]\n \n def back_val(self):\n if self.empty == 1:\n return -1\n return self.array[self.back-1]\n\n \n\ndef run_cmd_with_queue(Cqueue_obj, command):\n cmd_type = command[0]\n \n if cmd_type == \"enQueue\":\n _, num = command\n Cqueue_obj.enQueue(int(num))\n elif cmd_type == \"deQueue\":\n print(Cqueue_obj.deQueue())\n elif cmd_type == \"size\":\n print(Cqueue_obj.size())\n elif cmd_type == \"empty\":\n print(Cqueue_obj.empty())\n elif cmd_type == \"front\":\n print(Cqueue_obj.front_val())\n elif cmd_type == \"back\":\n print(Cqueue_obj.back_val())\n\nQ_size = 6\n\nn = int(input())\nCqueue_obj = Circular_Queue(n)\n\nfor _ in range(n):\n run_cmd_with_queue(Cqueue_obj, input().split())","sub_path":"알고리즘 수업/엔큐(enqueue)/enque.py","file_name":"enque.py","file_ext":"py","file_size_in_byte":1600,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"252620347","text":"import numpy as np\r\nimport jieba\r\n\r\n# 余弦法求相似度\r\n\r\n\r\ndef cosine_similarity(sentence1: str, sentence2: str) -> float:\r\n seg1 = [word for word in jieba.cut(sentence1)]\r\n seg2 = [word for word in jieba.cut(sentence2)]\r\n word_list = list(set([word for word in seg1 + seg2]))\r\n get_word_vector_1 = []\r\n get_word_vector_2 = []\r\n for word in word_list:\r\n get_word_vector_1.append(seg1.count(word))\r\n get_word_vector_2.append(seg2.count(word))\r\n vec_1 = np.array(get_word_vector_1)\r\n vec_2 = np.array(get_word_vector_2)\r\n try:\r\n norm = \"false\"\r\n assert len(vec_1) == len(vec_2), \"len(x) != len(y)\"\r\n zero_list = [0] * len(vec_1)\r\n\r\n res = np.array([[vec_1[i] * vec_2[i], vec_1[i] * vec_1[i], vec_2[i] * vec_2[i]] for i in range(len(vec_1))])\r\n cos = sum(res[:, 0]) / (np.sqrt(sum(res[:, 1])) * np.sqrt(sum(res[:, 2])))\r\n sim = 0.5 + 0.5 * cos if norm else cos\r\n return sim\r\n\r\n except ZeroDivisionError:\r\n print(\"NULL\")\r\n return 0\r\n\r\n\r\nif __name__ == '__main__':\r\n\r\n path1 = input(\"原本文件:\")\r\n path2 = input(\"对比文件:\")\r\n save_path = \"C:/1/save.txt\"\r\n\r\n try:\r\n f1 = open(path1, 'r', encoding='UTF-8')\r\n f2 = open(path2, 'r', encoding='UTF-8')\r\n str1 = f1.read()\r\n str2 = f2.read()\r\n result = cosine_similarity(str1, str2)\r\n print(\"相似度 :%.4f\" % result)\r\n f = open(save_path, 'w', encoding='utf-8')\r\n f.write(\"文章相似度:%.4f\" % result)\r\n f.close()\r\n\r\n except FileNotFoundError:\r\n print(\"error\")","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1674,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"416834996","text":"#!/usr/bin/env python\nfrom selenium.webdriver.common.keys import Keys\nimport pytest\n\n\n@pytest.mark.userfixtures('browser_setup', '')\nclass TestNewVisitor:\n def check_for_row_in_list_table(self, row_text):\n table = self.browser.find_element_by_id('id_list_table')\n rows = table.find_elements_by_tag_name('tr')\n assert row_text in [row.text for row in rows]\n\n def test_can_start_a_list_and_retrieve_it_later(self, browser_setup):\n self.browser = browser_setup\n self.browser.get('http://localhost:8001')\n\n assert 'To-Do' in self.browser.title\n\n header_text = self.browser.find_element_by_tag_name('h1').text\n assert 'To-Do' in header_text\n\n inputbox = self.browser.find_element_by_id('id_new_item')\n assert inputbox.get_attribute('placeholder') == 'Enter a to-do item'\n\n inputbox.send_keys('Buy peacock feathers')\n inputbox.send_keys(Keys.ENTER)\n\n self.check_for_row_in_list_table('1: Buy peacock feathers')\n self.check_for_row_in_list_table('2: Use peacock feathers to make a '\n 'fly')\n\n pytest.fail('Finish the test!')\n\nif __name__ == '__main__':\n pytest.main()\n","sub_path":"superlists/tests/test_e2e.py","file_name":"test_e2e.py","file_ext":"py","file_size_in_byte":1215,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"342206969","text":"from django.conf.urls import include, url\nfrom . import views\n\nurlpatterns = [\n url(r'^send/$', views.send_message, name='send_message'),\n url(r'^reply/$', views.reply, name='reply'),\n url(r'^delete/$', views.delete, name='delete_message'),\n url(r'^check/$', views.delete, name='check_message'),\n url(r'^send_mail$', views.send_mail, name='send_mail'),\n]\n","sub_path":"chat/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":371,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"512836777","text":"# -*- coding: utf-8 -*-\n#\n# Copyright (c), 2018-2019, SISSA (International School for Advanced Studies).\n# All rights reserved.\n# This file is distributed under the terms of the MIT License.\n# See the file 'LICENSE' in the root directory of the present\n# distribution, or http://opensource.org/licenses/MIT.\n#\n# @author Davide Brunato \n#\nimport datetime\n\nfrom .exceptions import ElementPathTypeError, ElementPathValueError\nfrom .xpath_helpers import AttributeNode, is_etree_element, is_element_node, is_document_node, is_attribute_node\n\n\nclass XPathContext(object):\n \"\"\"\n The XPath dynamic context. The static context is provided by the parser.\n\n Usually the dynamic context instances are created providing only the root element.\n Variables argument is needed if the XPath expression refers to predefined variables.\n The other optional arguments are needed only if a specific position on the context is\n required, but have to be used with the knowledge of what is their meaning.\n\n :param root: the root of the XML document, can be a ElementTree instance or an Element.\n :param item: the context item. A `None` value means that the context is positioned on \\\n the document node.\n :param position: the current position of the node within the input sequence.\n :param size: the number of items in the input sequence.\n :param axis: the active axis. Used to choose when apply the default axis ('child' axis).\n :param variables: dictionary of context variables that maps a QName to a value.\n :param current_dt: current dateTime of the implementation, including explicit timezone.\n :param timezone: implicit timezone to be used when a date, time, or dateTime value does \\\n not have a timezone.\n \"\"\"\n def __init__(self, root, item=None, position=0, size=1, axis=None, variables=None,\n current_dt=None, timezone=None):\n if not is_element_node(root) and not is_document_node(root):\n raise ElementPathTypeError(\"argument 'root' must be an Element: %r\" % root)\n self.root = root\n if item is not None:\n self.item = item\n elif is_element_node(root):\n self.item = root\n else:\n self.item = None\n\n self.position = position\n self.size = size\n self.axis = axis\n self.variables = {} if variables is None else dict(variables)\n self.current_dt = current_dt or datetime.datetime.now()\n self.timezone = timezone\n self._parent_map = None\n\n def __repr__(self):\n return '%s(root=%r, item=%r, position=%r, size=%r, axis=%r)' % (\n self.__class__.__name__, self.root, self.item, self.position, self.size, self.axis\n )\n\n def copy(self, clear_axis=True):\n obj = type(self)(\n root=self.root,\n item=self.item,\n position=self.position,\n size=self.size,\n axis=None if clear_axis else self.axis,\n variables=self.variables.copy(),\n current_dt=self.current_dt,\n timezone=self.timezone,\n )\n obj._parent_map = self._parent_map\n return obj\n\n @property\n def parent_map(self):\n if self._parent_map is None:\n self._parent_map = {child: elem for elem in self.root.iter() for child in elem}\n return self._parent_map\n\n def is_principal_node_kind(self):\n if self.axis == 'attribute':\n return is_attribute_node(self.item)\n else:\n return is_element_node(self.item)\n\n # Context item iterators\n def iter_self(self):\n status = self.item, self.size, self.position, self.axis\n self.axis = 'self'\n yield self.item\n self.item, self.size, self.position, self.axis = status\n\n def iter_attributes(self):\n if not is_element_node(self.item):\n return\n\n status = self.item, self.size, self.position, self.axis\n self.axis = 'attribute'\n\n for item in self.item.attrib.items():\n self.item = AttributeNode(*item)\n yield self.item\n\n self.item, self.size, self.position, self.axis = status\n\n def iter_children_or_self(self, item=None, child_axis=False):\n status = self.item, self.size, self.position, self.axis\n if not child_axis and self.axis is not None:\n yield self.item\n self.item, self.size, self.position, self.axis = status\n return\n\n self.axis = 'child'\n if item is not None:\n self.item = item\n\n if self.item is None:\n self.size, self.position = 1, 0\n self.item = self.root.getroot() if is_document_node(self.root) else self.root\n yield self.item\n elif is_element_node(self.item):\n elem = self.item\n if elem.text is not None:\n self.item = elem.text\n yield self.item\n self.size = len(elem)\n for self.position, self.item in enumerate(elem):\n yield self.item\n\n self.item, self.size, self.position, self.axis = status\n\n def iter_parent(self, axis=None):\n status = self.item, self.size, self.position, self.axis\n self.axis = axis\n try:\n self.item = self.parent_map[self.item]\n except KeyError:\n pass\n else:\n yield self.item\n self.item, self.size, self.position, self.axis = status\n\n def iter_descendants(self, item=None, axis=None):\n status = self.item, self.size, self.position, self.axis\n self.axis = axis\n\n if item is not None:\n self.item = item\n\n if self.item is None:\n self.size, self.position = 1, 0\n yield self.root\n self.item = self.root.getroot() if is_document_node(self.root) else self.root\n elif not is_etree_element(self.item):\n return\n\n for descendant in self._iter_descendants():\n yield descendant\n\n self.item, self.size, self.position, self.axis = status\n\n def _iter_descendants(self):\n elem = self.item\n yield elem\n if elem.text is not None:\n self.item = elem.text\n yield self.item\n if len(elem):\n self.size = len(elem)\n for self.position, self.item in enumerate(elem):\n for item in self._iter_descendants():\n yield item\n\n def iter_ancestors(self, item=None, axis=None):\n status = self.item, self.size, self.position, self.axis\n self.axis = axis\n\n if item is not None:\n self.item = item\n\n if not is_etree_element(self.item):\n return\n elem = self.item\n parent_map = self.parent_map\n while True:\n try:\n parent = parent_map[self.item]\n except KeyError:\n break\n else:\n if parent is elem:\n raise ElementPathValueError(\"not an Element tree, circularity found for %r.\" % elem)\n self.item = parent\n yield self.item\n\n self.item, self.size, self.position, self.axis = status\n\n def iter(self, axis=None):\n status = self.item, self.size, self.position, self.axis\n self.axis = axis\n\n if self.item is None:\n self.size, self.position = 1, 0\n yield self.root\n self.item = self.root.getroot() if is_document_node(self.root) else self.root\n elif not is_etree_element(self.item):\n return\n\n for item in self._iter_context():\n yield item\n\n self.item, self.size, self.position, self.axis = status\n\n def _iter_context(self):\n elem = self.item\n yield elem\n if elem.text is not None:\n self.item = elem.text\n yield self.item\n\n for item in elem.attrib.items():\n self.item = item\n yield item\n\n if len(elem):\n self.size = len(elem)\n for self.position, self.item in enumerate(elem):\n for item in self._iter_context():\n yield item\n\n\nclass XPathSchemaContext(XPathContext):\n \"\"\"Schema context class used during static analysis phase for matching tokens with schema types.\"\"\"\n","sub_path":"elementpath/xpath_context.py","file_name":"xpath_context.py","file_ext":"py","file_size_in_byte":8300,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"335105243","text":"class Solution:\n \"\"\"\n @param chars: The letters array you should sort.\n \"\"\"\n def sortLetters(self, chars):\n # write your code here\n tail = 0\n \n for i in xrange(len(chars)):\n if 'a' <= chars[i] <= 'z':\n chars[i], chars[tail] = chars[tail], chars[i]\n tail += 1","sub_path":"src/main/java/com/practice/python/sort_letters_by_case.py","file_name":"sort_letters_by_case.py","file_ext":"py","file_size_in_byte":339,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"616004546","text":"import os\r\nimport argparse\r\nimport torchvision\r\nimport torch\r\nimport torch.nn as nn\r\nimport torch.nn.functional as F\r\nimport torch.optim as optim\r\nfrom torchvision import datasets, transforms\r\nimport time\r\nimport numpy as np\r\nimport logging\r\nfrom preact_resnet import PreActResNet18\r\nfrom wideresnet import WideResNet\r\nfrom earlystop import earlystop\r\nfrom utils import *\r\n\r\nparser = argparse.ArgumentParser(description='PyTorch Friendly Adversarial Training')\r\nparser.add_argument('--batch-size', type=int, default=128)\r\nparser.add_argument('--epochs', type=int, default=50, metavar='N', help='number of epochs to train')\r\nparser.add_argument('--model', default='pre', type=str, choices=['pre', 'wide'])\r\nparser.add_argument('--wide-factor', default=10, type=int, help='Widen factor')\r\nparser.add_argument('--weight_decay', '--wd', default=5e-4, type=float, metavar='W')\r\nparser.add_argument('--lr', type=float, default=0.05, metavar='LR', help='learning rate')\r\nparser.add_argument('--momentum', type=float, default=0.9, metavar='M', help='SGD momentum')\r\nparser.add_argument('--epsilon', type=float, default=8, help='perturbation bound')\r\nparser.add_argument('--num_steps', type=int, default=5, help='maximum perturbation step K')\r\nparser.add_argument('--step_size', type=float, default=2, help='step size')\r\nparser.add_argument('--normalization', default='std', type=str, choices=['std', '01','+-1'])\r\nparser.add_argument('--seed', type=int, default=0, metavar='S', help='random seed')\r\nparser.add_argument('--tau', type=int, default=3, help='step tau')\r\nparser.add_argument('--rand_init', type=bool, default=True, help=\"whether to initialize adversarial sample with random noise\")\r\nparser.add_argument('--omega', type=float, default=0.001, help=\"random sample parameter for adv data generation\")\r\nparser.add_argument('--dynamictau', type=bool, default=False, help='whether to use dynamic tau')\r\nparser.add_argument('--fname', default='output', type=str)\r\nparser.add_argument('--data-dir', default='/mnt/storage0_8/torch_datasets/cifar-data', type=str)\r\nparser.add_argument('--out-dir', default='fat_out', type=str, help='Output directory')\r\nparser.add_argument('--save-model', action='store_true')\r\nargs = parser.parse_args()\r\n\r\n# training settings\r\ntorch.manual_seed(args.seed)\r\nnp.random.seed(args.seed)\r\ntorch.cuda.manual_seed_all(args.seed)\r\ntorch.backends.cudnn.deterministic = False\r\ntorch.backends.cudnn.benchmark = True\r\ndevice = torch.device(\"cuda\")\r\nepsilon = (args.epsilon / 255.)\r\nstep_size = (args.step_size / 255.)\r\nif args.normalization == 'std':\r\n mu = torch.tensor(cifar10_mean).view(3,1,1).cuda()\r\n std = torch.tensor(cifar10_std).view(3,1,1).cuda()\r\nelif args.normalization == '01':\r\n mu = torch.tensor((0.,0.,0.)).view(3,1,1).cuda()\r\n std = torch.tensor((1.,1.,1.)).view(3,1,1).cuda()\r\nelif args.normalization == '+-1':\r\n mu = torch.tensor((0.5, 0.5, 0.5)).view(3,1,1).cuda()\r\n std = torch.tensor((0.5, 0.5, 0.5)).view(3,1,1).cuda()\r\ndef train(model, train_loader, optimizer, tau):\r\n start_epoch_time = time.time()\r\n train_loss = 0\r\n train_n = 0\r\n bp_count = 0\r\n for batch_idx, (data, target) in enumerate(train_loader):\r\n data, target = data.cuda(), target.cuda()\r\n\r\n # Get friendly adversarial training data via early-stopped PGD\r\n output_adv, output_target, output_natural, count = earlystop(model, data, target, step_size=step_size,\r\n epsilon=epsilon, perturb_steps=args.num_steps, tau=tau,\r\n randominit_type=\"uniform_randominit\", loss_fn='cent', \r\n mu=mu, std=std, rand_init=args.rand_init, omega=args.omega)\r\n bp_count += count\r\n model.train()\r\n optimizer.zero_grad()\r\n output = model(normalize(output_adv,mu,std))\r\n\r\n # calculate standard adversarial training loss\r\n loss = nn.CrossEntropyLoss(reduction='mean')(output, output_target)\r\n loss.backward()\r\n optimizer.step()\r\n train_loss += loss.item() * target.size(0)\r\n train_n += target.size(0)\r\n\r\n end_epoch_time = time.time()\r\n epoch_time = end_epoch_time - start_epoch_time\r\n\r\n return epoch_time, train_loss/train_n, bp_count/train_n\r\n\r\ndef adjust_tau(epoch, dynamictau):\r\n tau = args.tau\r\n if dynamictau:\r\n if epoch <= 50:\r\n tau = 0\r\n elif epoch <= 90:\r\n tau = 1\r\n else:\r\n tau = 2\r\n return tau\r\n\r\n\r\ndef adjust_learning_rate(optimizer, epoch):\r\n \"\"\"decrease the learning rate\"\"\"\r\n lr = args.lr\r\n if epoch >= 25:\r\n lr = args.lr * 0.1\r\n if epoch >= 40:\r\n lr = args.lr * 0.01\r\n\r\n for param_group in optimizer.param_groups:\r\n param_group['lr'] = lr\r\n return lr\r\n\r\n\r\nout_dir = args.out_dir\r\nif not os.path.exists(out_dir):\r\n os.makedirs(out_dir)\r\nlogfile = os.path.join(args.out_dir, args.fname+'.log')\r\nlogger = logging.getLogger(__name__)\r\nlogging.basicConfig(\r\n filename=logfile,\r\n format='[%(asctime)s] - %(message)s',\r\n datefmt='%Y/%m/%d %H:%M:%S',\r\n level=logging.INFO)\r\nlogger.info(args)\r\ntrain_loader, test_loader = get_loaders(args.data_dir, args.batch_size)\r\nif args.model == 'pre':\r\n model = PreActResNet18().cuda()\r\nelif args.model == 'wide':\r\n model = WideResNet(34, 10, widen_factor=args.wide_factor, dropRate=0.0)\r\nmodel = torch.nn.DataParallel(model).cuda()\r\nmodel.train()\r\noptimizer = optim.SGD(model.parameters(), lr=args.lr, momentum=args.momentum, weight_decay=args.weight_decay)\r\n\r\n\r\ntrain_time = 0\r\nhighest_acc = 0\r\nhighest_idx = 0\r\nlogger.info('Epoch \\t Seconds \\t LR \\t \\t Train Loss \\t #BP \\t Val Acc \\t PGD Acc')\r\nfor epoch in range(args.epochs):\r\n cur_lr = adjust_learning_rate(optimizer, epoch + 1)\r\n epoch_time, train_loss, nb_bp = train(model, train_loader, optimizer, adjust_tau(epoch + 1, args.dynamictau))\r\n train_time += epoch_time\r\n\r\n # Evaluation\r\n if args.model == 'pre':\r\n model_test = PreActResNet18().cuda()\r\n elif args.model == 'wide':\r\n model_test = WideResNet(34, 10, widen_factor=args.wide_factor, dropRate=0.0)\r\n model_test = torch.nn.DataParallel(model_test).cuda()\r\n model_test.load_state_dict(model.state_dict())\r\n model_test.float()\r\n model_test.eval()\r\n\r\n val_adv_loss, val_adv_acc = evaluate_pgd(test_loader, model_test, mu, std, 10, 1, val=20, use_CWloss=True)\r\n val_loss, val_acc = evaluate_standard(test_loader, model_test, mu, std, val=20)\r\n logger.info('%d \\t %.1f \\t \\t %.4f \\t %.4f \\t %d \\t %.4f \\t %.4f',\r\n epoch, epoch_time, cur_lr, train_loss,nb_bp+1, val_acc, val_adv_acc)\r\n\r\n if val_adv_acc > highest_acc and args.save_model:\r\n highest_acc = val_adv_acc\r\n highest_idx = epoch\r\n torch.save(model.state_dict(), os.path.join(args.out_dir, f'model_{args.model}.pth'))\r\nlogger.info('Total train time: %.4f minutes', (train_time)/60)\r\nlogger.info(f'Best checkpoint at {highest_idx}, {highest_acc}')\r\n\r\n\r\n","sub_path":"standard training/fat_cifar10.py","file_name":"fat_cifar10.py","file_ext":"py","file_size_in_byte":7089,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"38708202","text":"import socket\nimport time\n\ndef get_ip_address():\n s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n s.connect((\"8.8.8.8\", 80))\n return s.getsockname()[0]\n\nUDP_IP = get_ip_address()\nUDP_PORT = 5005\nMESSAGE = \"Hello, World!\"\n\nprint(\"UDP target IP:\", UDP_IP)\nprint(\"UDP target port:\", UDP_PORT)\nprint(\"message:\", MESSAGE)\n\nsock = socket.socket(socket.AF_INET, # Internet\n socket.SOCK_DGRAM) # UDP\nfor i in range(0,1000):\n\tsock.sendto(MESSAGE.encode(encoding='utf-8'), (UDP_IP, UDP_PORT))\n\ttime.sleep(1)\n","sub_path":"pc-side/clientest.py","file_name":"clientest.py","file_ext":"py","file_size_in_byte":533,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"645199134","text":"from django.urls import path\nfrom django.contrib.auth import views as log_view # views for login/logout provided by django\nfrom . import views\n\nurlpatterns = [\n path('', log_view.LoginView.as_view(template_name='application/login.html')), # Home page of entire site\n path('login/', log_view.LoginView.as_view(template_name='application/login.html'), name='login-view'), # login page at /login\n path('logout/', views.logout_user, name=\"logout-view\"), # Logout page at\n path('create_user/', views.create_user, name='create-new-user'), # Path for new user registration\n path('backend_home/', views.backend_home, name=\"backend-home\"), # Home page for logged in user\n path('documentation/', views.documentation, name=\"documentation\"), # Home page for logged in user\n path('survey/', views.survey, name=\"survey\"),\n path('medications/', views.medications, name=\"medications\"),\n path('patients/', views.patients, name=\"patients\"),\n path('treatment-overview', views.treatment_overview, name=\"treatment-overview\"),\n path('new-patient', views.new_patient, name=\"new-patient\"),\n path('bug_report/', views.bug_report, name=\"bug_report\"),\n path('patient_home/', views.patient_home, name=\"patient-home\"),\n path('phq9_results/', views.phq9_results, name=\"phq9-results\"),\n path('pocket_guide/', views.pocket_guide, name=\"pocket_guide\"),\n]\n","sub_path":"application/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1373,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"598026939","text":"# -*- coding: UTF-8 -*-\nfrom budget_app.loaders import PaymentsLoader\n\nclass TorrelodonesPaymentsLoader(PaymentsLoader):\n\n def parse_item(self, budget, line):\n # We reuse the parent implementation...\n fields = PaymentsLoader.parse_item(self, budget, line)\n\n # ...but we modify the programme field.\n # Programme codes have changed in 2015, due to new laws. Since the application expects a code-programme\n # mapping to be constant over time, we are forced to amend budget data prior to 2015.\n # See https://github.com/civio/presupuestos/wiki/La-clasificaci%C3%B3n-funcional-en-las-Entidades-Locales\n programme_mapping = {\n '1340': '1350', # Protección Civil\n '1550': '1532', # Vías públicas\n '1620': '1621', # Recogida, eliminación y tratamiento de residuos \n '2310': '2210', # Acción social: personal\n '2311': '2310', # Acción social: servicios sociales\n '2320': '3371', # Promoción social: juventud\n '2410': '4331', # Desarrollo local\n '2411': '2410', # Fomento del empleo: garantía social\n '3120': '3110', # Sanidad\n '3130': '3110', # Acciones públicas relativas a la salud\n '3210': '3230', # Educación\n '3211': '3231', # Escuela infantil\n '3300': '3330', # Administración general de cultura\n '3301': '3340', # Administración general de cultura: escuela de música\n '3302': '3261', # Administración general de cultura: escuela de idiomas\n '3320': '3321', # Bibliotecas\n '3400': '3420', # Administración general de deportes\n '4400': '4410', # Administración general del transporte\n '9240': '4910' # Medios de comunicación social\n }\n\n if budget.year < 2015:\n new_programme = programme_mapping.get(fields['fc_code'])\n if new_programme:\n fields['fc_code'] = new_programme\n\n return fields","sub_path":"loaders/torrelodones_payments_loader.py","file_name":"torrelodones_payments_loader.py","file_ext":"py","file_size_in_byte":2096,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"468029408","text":"from flask.ext.script import Manager\nimport kevslist as kl\nimport pymongo\nfrom pprint import pprint\n\nmanager = Manager(kl.app)\n\n\n@manager.command\ndef create_indicies():\n mongo, db = kl.connect_mongo()\n\n print(db.items.create_index([('posted_at', pymongo.DESCENDING), ('feed_ids', pymongo.ASCENDING)]))\n print(db.items.create_index('link', unique=True))\n\n mongo.close()\n\n\n@manager.command\ndef parse_feeds():\n mongo, db = kl.connect_mongo()\n\n pprint(kl.parse_feeds(db), indent=4)\n\n mongo.close()\n\n\nif __name__ == \"__main__\":\n manager.run()\n","sub_path":"manage.py","file_name":"manage.py","file_ext":"py","file_size_in_byte":562,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"114294372","text":"import matplotlib\nmatplotlib.use('TkAgg')\nfrom pylab import *\nimport random\nimport scipy\nimport pylab as plt\n\nn = 100 # size of space: n x n\np = 0.5 # probability of initially panicky individuals\nT = 1\nJ = 6.34369e-21 # Interaction constant for iron [Joule]\nkB = 1.38065e-23 # Boltzmann constant [Joule / Kelvin]\n\n\ndef initialize():\n global config\n config = zeros([n, n])\n for x in range(n):\n for y in range(n):\n if random.random() < p:\n config[x, y] = 1\n else:\n config[x, y] = -1\n\n\ndef observe():\n global config\n cla()\n imshow(config, vmin=0, vmax=1, cmap=cm.binary)\n\n\ndef update():\n global config\n for i in range(1000):\n i = random.randint(0,n-1)\n j = random.randint(0,n-1)\n E = 2*J*(config[i,j]*config[i-1,j] + config[i,j]*config[i,j-1] +\n config[i,j]*config[i,(j+1)%n] + config[i,j]*config[(i+1)%n,j])\n log_p = -E / (T * kB)\n if scipy.log(scipy.random.uniform(0, 1)) < log_p:\n config[i,j] = -config[i,j]\n\n\n\n\nfrom CS166 import pycxsimulator\npycxsimulator.GUI().start(func=[initialize, observe, update])\n\n# list=[]\n# for i in range(100):\n# black=0\n# initialize()\n# update()\n# for l in range(n):\n# for m in range(n):\n# if config[l,m]==-1:\n# black += 1\n# list.append(float(black/(n*n)))\n# print(i)\n#\n# plt.hist(list)\n# plt.show()\n\n","sub_path":"CS166_11.1.py","file_name":"CS166_11.1.py","file_ext":"py","file_size_in_byte":1435,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"251140979","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\nclass Fpnode:\n def __init__(self, item='root'):\n self.item = item\n self.parent = None\n self.child = {}\n self.count = 0\n\n def is_root(self):\n return self.parent is None\n\ndef generateData():\n data_no = 10000\n total_product_no = 100\n threshold = 0.56\n\n possibility1 = np.random.normal(0.47,0.2,total_product_no)\n possibility2 = np.random.normal(0.47,0.2,total_product_no)\n data = []\n for _ in range(data_no):\n itemset = []\n for m in range(0,5):\n possibility_first = np.random.rand()\n possibility_other = np.random.rand(total_product_no)\n if possibility_first > threshold:\n itemset.append(20*m)\n for j in range(20*m+1, 20*(m+1)):\n if possibility_other[j] < possibility1[j]:\n itemset.append(j)\n else:\n for j in range(20*m+1, 20*(m+1)):\n if possibility_other[j] < possibility2[j]:\n itemset.append(j)\n data.append(itemset)\n itemsets = []\n for i in range(len(data)):\n itemset = set(data[i])\n itemsets.append(itemset)\n return itemsets\n\n\ndef printFPTree(root):\n print('%s %d' % (root.item, root.count))\n for subnode in root.child.values():\n printFPTree(subnode)\n\ndef compute_frequency(dataset):\n frequency = {}\n for data in dataset:\n for item in data[0]:\n frequency[item] = frequency.get(item,0) + data[1]\n return frequency\n\ndef sort_data(dataset, frequency):\n result = []\n for i in range(len(dataset)):\n data = dataset[i]\n data[0].sort(key=lambda item : frequency[item], reverse=True)\n result.append(data)\n return result\n\ndef prune(dataset, frequency, minSupport):\n result = []\n for i in range(len(dataset)):\n data = dataset[i]\n listdata = [item for item in data[0] if frequency[item] >= minSupport]\n result.append((listdata,data[1]))\n return result\n\ndef insert_data(data, root, header):\n for item in data[0]:\n if item not in root.child.keys():\n newnode = Fpnode(item)\n newnode.parent = root\n root.child[item] = newnode\n if item not in header.keys():\n header[item] = None\n header[item] = (newnode, header[item])\n root = root.child[item]\n root.count = root.count + data[1]\n\ndef build_fptree(dataset, minSupport, suffix):\n if len(dataset) == 0:\n return [], {}\n\n root = Fpnode()\n header = {}\n frequent_itemset = []\n support = {}\n frequency = compute_frequency(dataset)\n dataset = prune(dataset, frequency, minSupport)\n dataset = sort_data(dataset, frequency)\n for data in dataset:\n insert_data(data, root, header)\n # print(data)\n\n for h in header.keys():\n sup_count = 0\n t = header[h]\n while t is not None:\n sup_count += t[0].count\n t = t[1]\n listitem = [h] + suffix\n frequent_itemset.append(listitem)\n listitem.sort()\n support[tuple(listitem)] = sup_count\n\n for item in sorted(header.items(), key=lambda item: frequency[item[0]]):\n t = item[1]\n newdataset = []\n while t is not None:\n count = t[0].count\n newdata = []\n panode = t[0].parent\n while not panode.is_root():\n newdata.append(panode.item)\n panode = panode.parent\n newdata.reverse()\n newdata = (newdata, count)\n t = t[1]\n if len(newdata[0]) != 0:\n newdataset.append(newdata)\n newsuffix = [item[0]] + suffix\n new_itemset, new_support = build_fptree(newdataset, minSupport, newsuffix)\n frequent_itemset.extend(new_itemset)\n support.update(new_support)\n\n return frequent_itemset, support\n\ndef getAllSubsets(itemset):\n if len(itemset) == 0:\n return []\n result = [[]]\n for item in itemset:\n newSet = [ oldSet + [item] for oldSet in result]\n result.extend(newSet)\n result = result[1:-1]\n for i in range(len(result)):\n result[i].sort()\n return result\n\ndef getAssociaionRules(frequent_itemset, support, minConfidenceRatio):\n rules = []\n for itemset in frequent_itemset:\n subsets = getAllSubsets(itemset)\n for subset in subsets:\n confidence = support[tuple(itemset)] / support[tuple(subset)]\n if confidence >= minConfidenceRatio:\n diffset = set(itemset).difference(set(subset))\n rules.append((tuple(subset),tuple(diffset)))\n return rules\n\n\n\ndef fpgrowth(dataset, minSupportRatio, minConfidenceRatio):\n dataset = [(list(data),1) for data in dataset]\n minSupport = int(minSupportRatio * len(dataset))\n frequent_itemset, support = build_fptree(dataset, minSupport, [])\n rules = getAssociaionRules(frequent_itemset, support, minConfidenceRatio)\n return frequent_itemset,rules\n\nif __name__ == '__main__':\n\n np.random.seed(0)\n dataset = generateData()\n\n x = np.linspace(0.30,0.50,20)\n y = []\n for support_ratio in x:\n _, rules = fpgrowth(dataset, support_ratio, 0.8)\n y.append(len(rules))\n print('In graph 1, if confidence = 0.8, and support = %.2f, then rules remaining = %i' % (support_ratio, len(rules)))\n print(y)\n plt.plot(x,y)\n plt.title('Confidence = 80%')\n plt.xlabel('Support')\n plt.ylabel('Rules')\n plt.savefig('../assets/61')\n plt.show()\n\n x = np.linspace(0.5,0.8,30)\n y = []\n for confidence in x:\n _, rules = fpgrowth(dataset, 0.3, confidence)\n y.append(len(rules))\n print('In graph 2, if support = 0.3, and confidence = %.2f, then rules remaining = %i' % (confidence,len(rules)))\n print(y)\n plt.plot(x,y)\n plt.title('Support = 30%')\n plt.xlabel('Confidence')\n plt.ylabel('Rules')\n plt.savefig('../assets/62')\n plt.show()","sub_path":"demos/test classify/data/fp/FPGrowth12.py","file_name":"FPGrowth12.py","file_ext":"py","file_size_in_byte":6043,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"161278849","text":"#!/usr/bin/env python\n\nfrom __future__ import print_function, division\n\nimport numpy as np\nfrom numpy.linalg import norm\n\nimport tf\nimport rospy\nfrom geometry_msgs.msg import Twist, Vector3\nfrom nav_msgs.msg import Odometry\n\n\nclass Neato:\n def __init__(self):\n rospy.init_node('square')\n \n self.pub = rospy.Publisher('/cmd_vel', Twist, queue_size=10)\n self.distance = rospy.get_param(\"distance\", 0.1)\n self.speed = rospy.get_param(\"speed\", 1)\n \n self.last_keypoint = self.curr_position(rospy.wait_for_message('/odom', Odometry))\n self.curr_pos = self.last_keypoint\n self.to_angle = None\n rospy.Subscriber('/odom', Odometry, self.curr_position)\n \n self.phase = \"Forward\"\n\n self.rate = rospy.Rate(20)\n \n def curr_position(self, msg):\n pos = [getattr(msg.pose.pose.position, coord) for coord in 'xyz']\n angle = [getattr(msg.pose.pose.orientation, coord) for coord in 'xyzw'] #TODO\n self.curr_pos = np.array([pos + [0], angle])\n return self.curr_pos\n \n def logic(self):\n distance, _= abs(self.curr_pos - self.last_keypoint) \n angle = tf.transformations.euler_from_quaternion(self.last_keypoint[1])[2]\n angle = angle + np.pi\n now_angle = tf.transformations.euler_from_quaternion(self.curr_pos[1])[2]\n now_angle = now_angle + np.pi\n print(distance)\n if angle + np.pi/2 > 2*np.pi:\n if self.to_angle is None:\n self.to_angle = np.pi/2 - (2*np.pi - now_angle)\n angle = self.to_angle\n\n if now_angle > np.pi*3/2:\n now_angle = 0\n else:\n angle = angle + np.pi/2\n \n\n\n #pretty simple 2-state within 2-state FSM\n if self.phase == \"Forward\":\n if norm(distance) < self.distance:\n self.pub.publish(self.go_fwd(self.speed))\n rospy.loginfo(\"{} at {}\".format(self.phase, self.speed))\n return\n if norm(distance) >= self.distance:\n self.pub.publish(self.stop())\n rospy.loginfo(\"Reached polygon edge, beginning to Rotate\")\n self.phase = \"Rotate\"\n self.last_keypoint = self.curr_pos\n return\n if self.phase == \"Rotate\":\n print(now_angle, angle)\n if now_angle - angle < 0:\n self.pub.publish(self.turn_right(-0.5))\n return\n else:\n self.pub.publish(self.stop())\n self.to_angle = None\n self.last_keypoint = self.curr_pos\n self.phase = \"Forward\"\n return\n\n def run(self):\n while not rospy.is_shutdown():\n self.logic()\n self.rate.sleep()\n\n @staticmethod\n def stop():\n return Twist(linear=Vector3(0, 0, 0),\n angular=Vector3(0, 0, 0))\n @staticmethod\n def turn_left(v):\n return Twist(linear=Vector3(0, 0, 0),\n angular=Vector3(0, 0, v)) #TODO\n \n @staticmethod \n def turn_right(v):\n return Twist(linear=Vector3(0, 0, 0),\n angular=Vector3(0, 0, -v)) #TODO\n \n @staticmethod \n def go_fwd(v):\n return Twist(linear=Vector3(v, 0, 0), #TODO\n angular=Vector3(0, 0, 0))\n\n\nsquare = Neato()\nsquare.run()\n","sub_path":"warmup_project/scripts/square.py","file_name":"square.py","file_ext":"py","file_size_in_byte":3399,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"209483918","text":"import risar\r\nimport random\r\nimport math\r\nimport time\r\nfrom PyQt5.QtWidgets import QMessageBox\r\n\r\n\r\nclass Kroglica:\r\n def __init__(self):\r\n self.x = random.randint(10, risar.maxX - 10)\r\n self.y = random.randint(10, risar.maxY - 10)\r\n self.r = 10\r\n self.color = risar.nakljucna_barva()\r\n\r\n self.hitrost_X = random.randint(-5, 5)\r\n self.hitrost_Y = math.sqrt(25 - self.hitrost_X ** 2)\r\n\r\n self.object = risar.krog(self.x, self.y, self.r, self.color)\r\n\r\n self.exploded = False\r\n\r\n def shrani(self, sez):\r\n sez.append((self.exploded, self.object, self.hitrost_X, self.hitrost_Y))\r\n\r\n\r\nstopnja = 0\r\nparametri_stopenj = ((1, 5), (3, 5), (5, 10), (8, 10), (10, 15), (13, 15), (16, 20), (18, 20), (20, 25), (22, 25))\r\n\r\nwhile stopnja < 10:\r\n\r\n # Izpis potreb za naslednjo stopnjo\r\n QMessageBox.information(None, \"Rezultat\", \"Eksplodirajte \" + str(parametri_stopenj[stopnja][0]) + \" od \" + str(parametri_stopenj[stopnja][1]) + \" žog.\")\r\n\r\n sez_kroglic = []\r\n nov_sez_kroglic = []\r\n miska_krog = risar.krog(risar.miska[0], risar.miska[1], 30)\r\n\r\n # Definiramo kroglice\r\n for i in range(parametri_stopenj[stopnja][1]):\r\n # Ustvarimo objekt\r\n kroglica = Kroglica()\r\n\r\n # Potrebne podatke shranimo v seznam\r\n kroglica.shrani(sez_kroglic)\r\n\r\n koordinate_eks_kroglic = [()]\r\n nove_koordinate_eks_kroglic = []\r\n konec = False\r\n st_explodiranih = 0\r\n\r\n while True:\r\n\r\n # Posodbaljanje miške do klika\r\n if not risar.klik:\r\n miska_krog.setPos(risar.miska[0], risar.miska[1])\r\n koordinate_eks_kroglic[0] = (miska_krog.x(), miska_krog.y(), time.time(), miska_krog)\r\n\r\n # Preverjanje vseh (neeksplodiranih) žog\r\n for stanje, kroglica, hitrost_X, hitrost_Y in sez_kroglic:\r\n # Če smo kliknii\r\n if risar.klik:\r\n\r\n # Pregledamo vse eksplodirane žoge\r\n for x, y, cas, eks_kroglica in koordinate_eks_kroglic:\r\n\r\n # Če so od ekplozije minile 4 sekunde skrijemo kroglico IN JO NE DODAMO V SEZNAM ZA NASLEDNJI KROG\r\n if time.time() - cas >= 4:\r\n eks_kroglica.hide()\r\n continue\r\n\r\n # Če od ekplozije niso minile 4 sekunde ŽE EKSPLODIRANO KROGLICO DODAMO V SEZNAM ZA NASLEDNJI KROG\r\n else:\r\n nove_koordinate_eks_kroglic.append((x, y, cas, eks_kroglica))\r\n\r\n # Če žoga še ni ekplodirana, pregledamo če se nahaja v območju eksplodirane žoge\r\n if not stanje and (kroglica.x() > x - 40 and kroglica.x() < x + 40) and (kroglica.y() > y - 40 and kroglica.y() < y + 40):\r\n # Če se, povečamo števec za 1\r\n st_explodiranih += 1\r\n\r\n # Žogo ustavimo\r\n hitrost_X = 0\r\n hitrost_Y = 0\r\n\r\n # Nastavimo stanje na eksplodirano\r\n stanje = True\r\n\r\n # Povečamo obseg\r\n kroglica.setRect(-30, -30, 60, 60)\r\n\r\n # Spremenimo polnilo\r\n c = kroglica.pen().color().lighter()\r\n c.setAlpha(192)\r\n kroglica.setBrush(c)\r\n\r\n # Eksplodirano žogico dodamo v seznam za naslednji krog\r\n nove_koordinate_eks_kroglic.append((kroglica.x(), kroglica.y(), time.time(), kroglica))\r\n\r\n # Ko preverimo vse eksplodirane kroglice, pogledamo, če jih je še kaj ostalo\r\n if len(nove_koordinate_eks_kroglic) == 0:\r\n\r\n # Če ne nastavimo pogoj za konec na True\r\n konec = True\r\n\r\n # In zlomimo zanko\r\n break\r\n\r\n # Če so kroglice še ostale\r\n else:\r\n # Shranimo seznam, ki smo ga zgradili (za naslednji krog), v originalni seznam\r\n koordinate_eks_kroglic = nove_koordinate_eks_kroglic[:]\r\n\r\n # Seznam za naslednji krog povozimo s praznim\r\n nove_koordinate_eks_kroglic = []\r\n\r\n # Pogledamo, če nam je kroglica \"ušla\" z okna (x os)\r\n if kroglica.x() + 10 >= risar.maxX or kroglica.x() - 10 <= 0:\r\n hitrost_X *= -1\r\n\r\n # Pogledamo, če nam je kroglica \"ušla\" z okna (y os)\r\n if kroglica.y() + 10 >= risar.maxY or kroglica.y() - 10 <= 0:\r\n hitrost_Y *= -1\r\n\r\n # Kroglici posodobimo položaj\r\n kroglica.setPos(kroglica.x() + hitrost_X, kroglica.y() + hitrost_Y)\r\n\r\n # V seznam kroglic za naslednji krog dodamo kroglico\r\n nov_sez_kroglic.append((stanje, kroglica, hitrost_X, hitrost_Y))\r\n\r\n # Če je pogoj za prekinitev resničen\r\n if konec:\r\n\r\n # Če smo eksplodirali dovolj kroglic\r\n if st_explodiranih >= parametri_stopenj[stopnja][0]:\r\n\r\n # Izpišemo sporočilo\r\n QMessageBox.information(None, \"Rezultat\", \"Eksplodirali ste \" + str(st_explodiranih) + \" od \" + str(\r\n parametri_stopenj[stopnja][1]) + \" žog. Nadaljujete na naslednjo stopnjo.\")\r\n\r\n # Povečamo stopnjo\r\n stopnja += 1\r\n\r\n # Nastavimo klik na false\r\n risar.klik = False\r\n\r\n # Skrijemo kroglice te stopnje\r\n for stanje, kroglica, hitrost_X, hitrost_Y in sez_kroglic:\r\n kroglica.hide()\r\n\r\n # Zlomimo zanko\r\n break\r\n\r\n # Če nismo\r\n else:\r\n # Izpišemo sporočilo\r\n QMessageBox.information(None, \"Rezultat\", \"Eksplodirali ste \" + str(st_explodiranih) + \" od \" + str(\r\n parametri_stopenj[stopnja][1]) + \" žog. Ostajate na trenutni stopnji.\")\r\n\r\n # Klik nastavimo na false\r\n risar.klik = False\r\n\r\n # Skrijemo kroglice te stopnje\r\n for stanje, kroglica, hitrost_X, hitrost_Y in sez_kroglic:\r\n kroglica.hide()\r\n\r\n # Zlomimo zanko\r\n break\r\n\r\n # Shranimo seznam s posodobljanimi koordinatami kroglic v originalni seznam\r\n sez_kroglic = nov_sez_kroglic[:]\r\n\r\n # Seznam s posodobljnimi koordinatami povozimo s praznim\r\n nov_sez_kroglic = []\r\n\r\n # Malo počakamo\r\n risar.cakaj(0.02)\r\n","sub_path":"code/batch-2/vse-naloge-brez-testov/DN14-M-139.py","file_name":"DN14-M-139.py","file_ext":"py","file_size_in_byte":6615,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"214618708","text":"\"\"\"\nOperate Database\n\"\"\"\n\nimport csv\nimport logging\nimport sqlite3\nimport time\n\n\n####################################################################################################\ndef checkRecords(dbName, tbName):\n \"\"\"\n Check the amount of records\n @param dbName(str) Database name\n @param tbName(str) Table name\n @return the amount of records\n \"\"\"\n \n # connect to database\n conn = sqlite3.connect(dbName)\n \n # create cursor\n cur = conn.cursor()\n \n # check the amount of records\n cur.execute(\"SELECT COUNT(*) FROM %s\" % tbName)\n records = cur.fetchone()\n \n # close database\n conn.close()\n \n #logging.debug(\"the amount of records on %s - %s seconds\" % (tbName, records))\n \n return records[0]\n\n####################################################################################################\ndef createObjTb(dbName, tbName):\n \"\"\"\n Create table for storing performance data\n @param dbName(str) Database name\n @param tbName(str) Table name\n \"\"\"\n \n logger = logging.getLogger()\n logger.log(logging.INFO, \"Create database \\\"%s\\\" if not exist.\" % dbName)\n \n # connect to database\n conn = sqlite3.connect(dbName)\n \n # create cursor\n cur = conn.cursor()\n \n # create table if not exist\n for i in tbName:\n logger.log(logging.INFO, \"Create table \\\"%s\\\" on %s if not exist\" % (i, dbName))\n cur.execute(\"CREATE TABLE IF NOT EXISTS %s (time REAL NOT NULL, oid TEXT NOT NULL, value REAL, PRIMARY KEY(time, oid))\" % i)\n \n # close database\n conn.close()\n \n#################################################################################################### \ndef createResultTb(dbName):\n \"\"\"\n Create table for storing result from fault detection\n @param dbName(str) Database name\n \"\"\"\n \n logger = logging.getLogger()\n\n tbName = \"RESULT\"\n logger.log(logging.INFO, \"Create database \\\"%s\\\" if not exist.\" % dbName)\n \n # connect to database\n conn = sqlite3.connect(dbName)\n \n # create cursor\n cur = conn.cursor()\n \n # create table if not exist\n logger.log(logging.INFO, \"Create table \\\"%s\\\" on %s if not exist\" % (tbName, dbName))\n cur.execute(\"CREATE TABLE IF NOT EXISTS %s (time REAL NOT NULL, result INTEGER NOT NULL)\" % tbName)\n \n # close database\n conn.close()\n\n####################################################################################################\ndef insertObj(dbName, tbName, dataList):\n \"\"\"\n Insert performance data into table\n @param dbName(str) Database name\n @param tbName(str) Table name\n @param dataList(dict) Object data list {oid:[time, value], ...}\n \"\"\"\n \n # check time\n t1 = time.time()\n \n # connect to database\n conn = sqlite3.connect(dbName)\n \n # create cursor\n cur = conn.cursor()\n \n # insert data\n for i, j in dataList.items():\n cur.execute(\"INSERT INTO %s VALUES (?, ?, ?)\" % tbName, (float(j[0]), str(i), float(j[1])))\n \n # commit\n conn.commit()\n \n # close database\n conn.close()\n \n # check time\n t2 = time.time()\n \n #logging.debug(\"insertion time on %s - %d seconds\" % (tbName, (t2 - t1)))\n f=open(\"./insertion.csv\", \"a\")\n csvWriter = csv.writer(f)\n listData = [time.time(), (t2-t1), len(dataList)]\n csvWriter.writerow(listData)\n f.close()\n\n####################################################################################################\ndef insertResult(dbName, result):\n \"\"\"\n Insert performance data into table\n @param dbName(str) Database name\n @param tbName(str) Table name\n @param result(list) time, 1: false, 0: normal\n \"\"\"\n \n # connect to database\n conn = sqlite3.connect(dbName)\n \n # create cursor\n cur = conn.cursor()\n \n # insert data\n cur.execute(\"INSERT INTO %s VALUES (?, ?)\" % \"RESULT\", (float(result[0]), float(resut[1])))\n \n # commit\n conn.commit()\n \n # close database\n conn.close()\n \n # check time\n t2 = time.time()\n \n #logging.debug(\"insertion time on %s - %d seconds\" % (tbName, (t2 - t1)))\n f=open(\"./insertion.csv\", \"a\")\n csvWriter = csv.writer(f)\n listData = [time.time(), (t2-t1), len(dataList)]\n csvWriter.writerow(listData)\n f.close()\n\n#################################################################################################### \ndef select(dbName, oidDict, duration, interval):\n \"\"\"\n Select performance data\n @param dbName(str) Database name\n @param oidDict(dict) ObjectID dictionary\n @param duration(int) Duration to collect data from now\n @param interval(int) Time slot interval to correlate data\n \"\"\"\n \n # check time\n t1 = time.time()\n \n # connect to database\n conn = sqlite3.connect(dbName)\n \n # create cursor\n cur = conn.cursor()\n \n sDataDict = {}\n \n for i in range(duration // interval):\n slotTime = t1 - (interval * i)\n \n sDataDict[slotTime] = {}\n \n for cate in oidDict.keys():\n sDataDict[slotTime][cate] = {}\n \n # check time\n records = checkRecords(dbName, cate)\n t2 = time.time()\n \n for oid in oidDict[cate].keys():\n cur.execute(\"SELECT value FROM %s WHERE oid = \\\"%s\\\" AND time <= \\\"%s\\\" ORDER BY time DESC LIMIT 1\" % (str(cate), str(oid), str(slotTime)))\n \n val = cur.fetchone()\n \n if val is not None:\n sDataDict[slotTime][cate][oid] = val[0]\n \n if sDataDict[slotTime][cate] == {}:\n sDataDict[slotTime].pop(cate)\n \n # check time\n t3 = time.time()\n \n #logging.debug(\"select time on %s (%s records) - %d seconds\" % (cate, records, (t3 - t2)))\n f=open(\"./selection.csv\", \"a\")\n csvWriter = csv.writer(f)\n listData = [time.time(), (t3-t2), records]\n csvWriter.writerow(listData)\n f.close()\n \n if sDataDict[slotTime] == {}:\n sDataDict.pop(slotTime)\n \n # close database\n conn.close()\n \n return sDataDict\n\n\n","sub_path":"pytest001/database.py","file_name":"database.py","file_ext":"py","file_size_in_byte":6328,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"621915178","text":"from django import forms\nfrom ninjas.models import Ninja\nimport csv\nfrom csvvalidator import *\n\nclass CSVImportForm(forms.Form):\n\tcsv = forms.FileField(required = True, label = \"CSV file\", help_text = \"A valid CSV file from the CoderDojo @ Curtin ninja signup sheet.\")\n\n\tdef is_valid(self):\n\t\tcsvfile = self.files.get('csv')\n\t\ttry:\n\t\t\tdialect = csv.Sniffer().sniff(csvfile.read(2048))\n\t\texcept csv.Error:\n\t\t\treturn False\n\t\tcsvfile.seek(0)\n\t\treader = csv.reader(csvfile, dialect=dialect)\t\t\n\t\tfields = (\n\t\t\t\"Timestamp\",\n\t\t\t\"Full Name\",\n\t\t\t\"School\",\n\t\t\t\"School Year\",\n\t\t\t\"Email Address\",\n\t\t\t\"Gender\",\n\t\t\t\"Been Before?\",\n\t\t\t\"Black Belt\",\n\t\t\t\"Referral\",\n\t\t\t\"Laptop\",\n\t\t\t\"Aim\",\n\t\t\t\"Coding Knowledge\",\n\t\t\t\"Codecademy Knowledge\",\n\t\t\t\"Scratch Knowledge\",\n\t\t\t\"Programming Languages\",\n\t\t\t\"Parent/Guardian Name\",\n\t\t\t\"Phone Number\",\n\t\t\t\"Postcode\",\n\t\t\t\"Parent/Guardian Email\",\n\t\t\t\"Allergies/Dietary Restrictions\",\n\t\t\t\"Photo Permission\",\n\t\t\t\"Parent's Permission\",\n\t\t\t\"Availability [Saturday 2 August]\",\n\t\t\t\"Availability [Saturday 9 August]\",\n\t\t\t\"Availability [Saturday 16 August]\",\n\t\t\t\"Availability [Saturday 23 August]\",\n\t\t\t\"Availability [Saturday 30 August]\",\n\t\t\t\"Availability [Saturday 6 September]\",\n\t\t\t\"Availability [Saturday 13 September]\",\n\t\t\t\"Availability [Saturday 20 September]\",\n\t\t)\n\n\t\tval = CSVValidator(fields)\n\n\t\tval.add_header_check('EX1', 'bad header')\n\t\tval.add_record_length_check('EX2', 'unexpected record length')\n\t\tstatus = val.validate(reader)\n\t\tcsvfile.seek(0)\n\t\tif len(status) is 0:\n\t\t\treturn True\n\t\telse:\n\t\t\treturn False\n\nclass NinjaSelectionForm(forms.Form):\n\tninja = forms.ModelChoiceField(\n\t\tqueryset = Ninja.objects.all(),\n\t)","sub_path":"ninjas/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":1639,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"153617765","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sun Nov 25 10:30:52 2018\r\n\r\n@author: alin.manolache\r\n\"\"\"\r\n\r\nimport numpy as np\r\nimport pandas as pd\r\nimport os\r\n\r\ndirPath = os.path.dirname(os.path.realpath(__file__))\r\nos.chdir(dirPath)\r\n\r\nimg1 = pd.read_csv('Healthy\\\\topImageGray10_crop.csv')\r\nimg2 = pd.read_csv('Healthy\\\\topImageGray10_blur.csv')\r\nimg3 = pd.read_csv('Healthy\\\\topImageGray15_all.csv')\r\n\r\n# First col - Schizo\r\n# Second col - Healthy\r\nlabel = np.zeros((115+203, 2))\r\ndata = np.zeros((115+203,108,95,1))\r\ncurDataIndex = 0\r\n\r\nfor file in os.listdir('Schizo'):\r\n if (file.endswith('.csv')):\r\n img = pd.read_csv('Schizo\\\\{}'.format(file))\r\n img = img.values;\r\n img=img[0:108,:]\r\n img_r = img.reshape((108,95,1))\r\n data[curDataIndex] = img_r\r\n label[curDataIndex,0] = 1\r\n curDataIndex += 1\r\n \r\nfor file in os.listdir('Healthy'):\r\n if (file.endswith('.csv')):\r\n img = pd.read_csv('Healthy\\\\{}'.format(file))\r\n img = img.values;\r\n img=img[0:108,:]\r\n img_r = img.reshape((108,95,1))\r\n data[curDataIndex] = img_r\r\n label[curDataIndex,1] = 1\r\n curDataIndex += 1\r\n \r\n#for file in os.listdir('Schizo'):\r\n #if (file.endswith('.csv') ):\r\n # img = pd.read_csv('Schizo\\\\{}'.format(file))\r\n#img1=img1.values\r\n#img1=img1[0:108, :]\r\n#img1_r = img1.reshape((1,108,95,1))\r\n\r\n#img1=img1.values\r\n#img1=img1[0:108, :]\r\n#img2=img2.values\r\n#img2=img2[0:108, :]\r\n#img3=img3.values\r\n#img3=img3[0:108, :]\r\n#img2_r = img2.reshape((1,108,95,1))\r\n\r\n#imgRes = np.concatenate((img1_r, img2_r), 0)\r\n\r\n#img222 = data[1][:][:][:].reshape((108,95))\r\n\r\n \r\nimport matplotlib.pyplot as plt\r\n#import random\r\n#from imgaug import augmenters as iaa\r\n#import matplotlib.image as mpimg\r\n#img=mpimg.imread('your_image.png')\r\n#seq3 = iaa.Sequential([\r\n#iaa.Crop(px=(0, 1)), # crop images from each side by 0 to 16px (randomly chosen)\r\n#iaa.Fliplr(0.1), # horizontally flip 50% of the images\r\n#iaa.GaussianBlur(sigma=(0, 1.0)), # blur images with a sigma of 0 to 3.0\r\n#iaa.Affine(translate_px={\"x\":int(random.uniform(-3, 3))}),\r\n#iaa.AdditiveGaussianNoise(loc=0, scale=(0.0, 0.05*255), per_channel=0.5) \r\n#],random_order=True)\r\n#img3 = img3.reshape((108,95,1))\r\n#img_aug3 = seq3.augment_image(img3)\r\n#img3 = img_aug3.reshape((108,95))\r\nimg = data[316].reshape(108,95)\r\nimgplot = plt.imshow(img)\r\n\r\nplt.show()\r\n","sub_path":"getData.py","file_name":"getData.py","file_ext":"py","file_size_in_byte":2401,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"626024678","text":"#! /usr/bin/env python3\n# -*- coding:utf-8 -*-\n# Copyright 2018- \n\"\"\" unpack *.tar.gz *.zip *.tgz *.rar *.tax *.jar files \"\"\"\n\nimport sys\nimport os\nsys.path.append('.')\nimport util\n\n\ndef help_msg():\n print(\"Brief:\")\n print(\" extract compressed [file]\")\n print(\"Usage:\")\n print(\" %s [file]\" % util.get_command_name())\n print(\"Try again\")\n exit(1)\n\n\ndef unpackTarGz(target):\n os.system('tar zxvf \"%s\"' % (target))\n\n\ndef unpackTar(target):\n os.system('tar xvf \"%s\"' % (target))\n\n\ndef unpackTarBz2(target):\n os.system('tar xvf \"%s\"' % (target))\n\n\ndef unpackZip(target):\n os.system('unzip \"%s\"' % (target))\n\n\ndef unpackJar(target):\n os.system('jar xf \"%s\"' % (target))\n\n\nUnpackMapping = {\n 'tar.gz': unpackTarGz,\n 'tgz': unpackTarGz,\n 'tar': unpackTar,\n 'tar.bz2': unpackTarBz2,\n 'zip': unpackZip,\n 'jar': unpackJar,\n}\n\nif __name__ == '__main__':\n util.check_help_message(help_msg)\n if len(sys.argv) != 2:\n help_msg()\n target = util.get_sys_args_one_line()\n if target == \".\" or target == \"..\":\n help_msg()\n foldname = target[:target.index(\".\")]\n util.backup_file(foldname)\n ts = util.get_file_name_all_suffix(target)\n if ts not in UnpackMapping.keys():\n help_msg()\n unpacker = UnpackMapping[ts]\n unpacker(target)\n print(\"[boostscript] extract '%s' to '%s'\" % (target, foldname))\n","sub_path":"command/unpack.py","file_name":"unpack.py","file_ext":"py","file_size_in_byte":1410,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"249498925","text":"from datetime import datetime\n\nfrom pytz import timezone, utc\n\nnew_year = datetime.now().year + 1\nindia_zone = \"Asia/Kolkata\"\n\n\ndef count_down(tz: timezone) -> tuple:\n \"\"\" Function return days and time to next new year \"\"\"\n\n tz = timezone(tz)\n new_year = datetime(datetime.now(tz).year + 1, 1, 1)\n today = datetime.now(tz)\n\n day_diff = new_year.day - today.day\n if day_diff < 0:\n day_diff = 30 + new_year.day - today.day\n month_diff = 12 - today.month\n total_days = int(day_diff + ((month_diff / 2) * 30) + ((month_diff / 2) * 31))\n\n hour_diff = new_year.hour - today.hour\n if hour_diff < 0:\n hour_diff = (new_year.hour - today.hour) + 23\n\n minute_diff = new_year.minute - today.minute\n if minute_diff < 0:\n minute_diff = 59 + new_year.minute - today.minute\n\n sec_diff = new_year.second - today.second\n if sec_diff < 0:\n sec_diff = 59 + (new_year.second - today.second)\n\n return {\n \"day\": str(total_days).zfill(2),\n \"hour\": str(hour_diff).zfill(2),\n \"min\": str(minute_diff).zfill(2),\n \"sec\": str(sec_diff).zfill(2),\n }\n","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1123,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"369367857","text":"# %%\r\nimport nltk\r\n\r\ngrammar = r\"\"\"\r\n NP: {+} # Chunk sequences of DT, JJ, NN\r\n PP: {} # Chunk prepositions followed by NP\r\n VP: {+$} # Chunk verbs and their arguments\r\n CLAUSE: {} # Chunk NP, VP\r\n \"\"\"\r\ncp = nltk.RegexpParser(grammar)\r\nsentence = [(\"Mary\", \"NN\"), (\"saw\", \"VBD\"), (\"the\", \"DT\"), (\"cat\", \"NN\"),\r\n (\"sit\", \"VB\"), (\"on\", \"IN\"), (\"the\", \"DT\"), (\"mat\", \"NN\")]\r\n\r\n# %%\r\ngrammar = r\"\"\"S: {}\r\nNP: {+}\r\nPP: {} \r\nVP: {+$} \"\"\"\r\n\r\n\r\ncp = nltk.RegexpParser(grammar)\r\n\r\nsentence = [(\"Rohit\", \"NN\"), (\"saw\", \"VBD\"), (\"the\", \"DT\"), (\"cat\", \"NN\"), (\"sit\", \"VB\"), (\"on\", \"IN\"), (\"the\", \"DT\"), (\"mat\", \"NN\")]\r\n\r\n# %%\r\nres = cp.parse(sentence)\r\nprint(res)\r\n# %%\r\n","sub_path":"05Natural Language Processing/02Syntactic Processing/03Information Extraction/temp.py","file_name":"temp.py","file_ext":"py","file_size_in_byte":797,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"408059414","text":"import datetime\nimport sqlite3\nfrom sqlite3 import Error\n\nclass DataBase:\n \"\"\" This class opens the connection and creates (if does not exists) a database\"\"\"\n def __init__(self):\n \"\"\"Creating a connection\"\"\"\n self.conn = sqlite3.connect('database.db')\n\n \"\"\"Creating a cursor object\"\"\"\n self.cur = self.conn.cursor()\n\n \"\"\"Performing a query, commit and close\"\"\"\n\n ## checks if the tables already exists\n check_if_exists = self.cur.execute(\n ''' SELECT count(*) FROM sqlite_master WHERE type='table' AND name='users' ''')\n if check_if_exists.fetchone()[0] != 1:\n self.cur.execute(\"CREATE TABLE IF NOT EXISTS users (\"\n \" UserName MESSAGE_TEXT,\"\n \" Password MESSAGE_TEXT,\"\n \" Email MESSAGE_TEXT)\")\n\n\n check_if_exists = self.cur.execute(\n ''' SELECT count(*) FROM sqlite_master WHERE type='table' AND name='dataTable' ''')\n if check_if_exists.fetchone()[0] != 1:\n self.cur.execute(\"CREATE TABLE IF NOT EXISTS dataTable (\"\n \" ItemName MESSAGE_TEXT,\"\n \" Amount INTEGER,\"\n \" Category MESSAGE_TEXT,\"\n \" Location MESSAGE_TEXT,\"\n \" UserName MESSAGE_TEXT,\"\n \"Taken MESSAGE_TEXT)\")\n\n self.conn.commit()\n self.conn.close() # closes the connection\n self.user = None\n\n \"\"\"This function returns the user if exists in the db, otherwise returns -1\"\"\"\n def get_user(self, user):\n if user == self.user[0][0]:\n return self.user[0]\n else:\n return -1\n\n \"\"\" This function adds the user to the db\"\"\"\n def add_user(self, email, password, name):\n self.conn = sqlite3.connect('database.db')\n self.cur = self.conn.cursor()\n self.cur.execute(\"SELECT * FROM users WHERE UserName=?\", (name,)) #check if exist\n result = self.cur.fetchall()\n if len(result) > 0:\n -1\n self.cur.execute(\"INSERT INTO users (UserName, Password, Email) VALUES (?, ?, ?);\",(name, password, email))\n self.conn.commit()\n self.conn.close()\n return 1\n\n \"\"\" This function validates the user's information\"\"\"\n def validate(self, name, password):\n self.conn = sqlite3.connect('database.db')\n self.cur = self.conn.cursor()\n self.cur.execute(\"SELECT * FROM users WHERE UserName=? AND Password=?\", (name, password))\n result = self.cur.fetchall()\n if len(result) == 0:\n return False;\n self.user = result\n return True\n\n\n \"\"\" This function adds a new item to the dataTable\"\"\"\n \"\"\" Returns true if the insertion succeed, otherwise false\"\"\"\n def add_item_to_user(self, name, item_name, amount, location, category):\n self.conn = sqlite3.connect('database.db')\n self.cur = self.conn.cursor()\n self.cur.execute(\"INSERT INTO dataTable (ItemName,Amount,Category,Location,UserName,Taken) VALUES (?, ?, ?,?,?,?);\",\n (item_name,amount, category, location, name, \"FALSE\"))\n self.conn.commit()\n self.cur.execute(\"SELECT * FROM dataTable WHERE UserName=? AND ItemName=?\", (name, item_name))\n result = self.cur.fetchall()\n self.conn.close()\n if len(result) == 0:\n return False\n return True\n\n \"\"\" This function updates an item from not taken to taken\"\"\"\n def update_taken (self, item_name, taken):\n self.conn = sqlite3.connect('database.db')\n self.cur = self.conn.cursor()\n name = str(item_name)\n name = item_name.split(\" \")\n self.cur.execute(\"UPDATE dataTable SET Taken =? WHERE ItemName=?;\", (taken, name[0]))\n self.conn.commit()\n self.cur.execute(\"SELECT Taken FROM dataTable WHERE ItemName=?\", (name[0],))\n result = self.cur.fetchall()\n self.conn.close()\n if len(result) > 0:\n if result[0] == taken:\n return True\n else:\n return False\n\n \"\"\" This function returns all the posts that were published by the given user\"\"\"\n def get_posts_by_user(self, userName):\n self.conn = sqlite3.connect('database.db')\n self.cur = self.conn.cursor()\n self.cur.execute('SELECT * FROM dataTable WHERE UserName=?', (userName,))\n posts = self.cur.fetchall()\n self.conn.close()\n return posts\n\n def save(self):\n with open(self.filename, \"w\") as f:\n for user in self.users:\n f.write(user + \";\" + self.users[user][0] + \";\" + self.users[user][1] + \";\" + self.users[user][2]\n + \";\" + self.users[user][3] + \";\" + self.users[user][4]\n + \"\\n\")\n\n \"\"\" This function searches for all the items that match the information that was given\"\"\"\n def search(self, category, location):\n self.conn = sqlite3.connect('database.db')\n self.cur = self.conn.cursor()\n # no category was picked so search only by location\n if category == \"Show possibilities\":\n self.cur.execute(\"SELECT * FROM dataTable WHERE Location=?\",\n (location,))\n # no location was picked so search only by category\n elif location == \"Show possibilities\":\n self.cur.execute(\"SELECT * FROM dataTable WHERE Category=?\",\n (category,))\n # both category and location was given by the user\n else:\n self.cur.execute(\"SELECT * FROM dataTable WHERE Category=? AND Location=?\",\n (category, location))\n result = self.cur.fetchall()\n\n if len(result) == 0:\n return \"No matching results!\"\n return result\n\n \"\"\" This function updates the item's information\"\"\"\n def update(self, userName, itemName, amount, location):\n try:\n self.conn = sqlite3.connect('database.db')\n self.cur = self.conn.cursor()\n self.cur.execute(\"UPDATE dataTable SET Amount =?, Location=? WHERE UserName=? AND ItemName=? \", (amount, location, userName, itemName))\n self.conn.commit()\n self.conn.close()\n return True\n except:\n return False\n\n \"\"\" This function return the locations with the amount of records for each location\"\"\"\n def get_data_on_location(self):\n self.conn = sqlite3.connect('database.db')\n self.cur = self.conn.cursor()\n self.cur.execute(\"SELECT Location, COUNT(*) FROM dataTable GROUP BY Location\")\n result = self.cur.fetchall()\n\n if len(result) == 0:\n return \"no results\"\n return result\n\n \"\"\" This function return the categories with the amount of records for each category\"\"\"\n def get_data_on_category(self):\n self.conn = sqlite3.connect('database.db')\n self.cur = self.conn.cursor()\n self.cur.execute(\"SELECT Category, COUNT(*) FROM dataTable GROUP BY Category\")\n result = self.cur.fetchall()\n\n if len(result) == 0:\n return \"no results\"\n return result\n\n \"\"\" This function return the amounts with the amount of records for each amount\"\"\"\n def get_data_on_amounts(self):\n self.conn = sqlite3.connect('database.db')\n self.cur = self.conn.cursor()\n self.cur.execute(\"SELECT Amount, COUNT(*) FROM dataTable GROUP BY Amount\")\n result = self.cur.fetchall()\n\n if len(result) == 0:\n return \"no results\"\n return result\n","sub_path":"backend.py","file_name":"backend.py","file_ext":"py","file_size_in_byte":7649,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"172621530","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Mar 30 17:16:21 2017\n\n@author: lracuna\n\"\"\"\nimport camera_calibration\nimport yaml\nimport numpy as np\n\ndef loadCalibrationFile(filename, cname):\n \"\"\" Load calibration data from a file.\n This function returns a `sensor_msgs/CameraInfo`_ message, based\n on the filename parameter. An empty or non-existent file is *not*\n considered an error; a null CameraInfo being provided in that\n case.\n :param filename: location of CameraInfo to read\n :param cname: Camera name.\n :returns: `sensor_msgs/CameraInfo`_ message containing calibration,\n if file readable; null calibration message otherwise.\n :raises: :exc:`IOError` if an existing calibration file is unreadable.\n \"\"\"\n ci = camera_calibration.Camera\n try:\n f = open(filename)\n calib = yaml.load(f)\n if calib is not None:\n if calib['camera_name'] != cname:\n print(\"[\" + cname + \"] does not match name \" +\n calib['camera_name'] + \" in file \" + filename)\n\n # fill in CameraInfo fields\n #ci.width = calib['image_width']\n #ci.height = calib['image_height']\n #ci.distortion_model = calib['distortion_model']\n #ci.D = calib['distortion_coefficients']['data']\n ci.K = calib['camera_matrix']['data']\n ci.R = calib['rectification_matrix']['data']\n ci.P = calib['projection_matrix']['data']\n\n except IOError: # OK if file did not exist\n pass\n\n return ci\n \ncalibs = list()\nfx = list()\nfy = list()\ncx = list()\ncy = list()\nfor i in range(1,18):\n filename = \"logitech_camera_calibration/logitech_cam_dyn\"+str(i)+\".yaml\"\n print (filename)\n ci = loadCalibrationFile(filename, \"logitech_cam\")\n fx.append(ci.K[0])\n fy.append(ci.K[4])\n cx.append(ci.K[2])\n cy.append(ci.K[5])\n\nfx = np.array(fx)\nfy = np.array(fy)\ncx = np.array(cx)\ncy = np.array(cy)\n\n#%%\nfilename = \"logitech_camera_calibration/logitech_cam_ground_truth_2.yaml\"\nprint (filename)\nci = loadCalibrationFile(filename, \"logitech_cam\")\n\nfx_gt = ci.K[0]\nfy_gt = ci.K[4]\ncx_gt = ci.K[2]\ncy_gt = ci.K[5]\n\nprint (\" fx factor: \")\nprint (fx / fx_gt)\nprint (\" fy factor: \")\nprint (fy / fy_gt)\nprint (\" fx factor / fy factor: \")\nprint ((fx / fx_gt) / (fy / fy_gt) )\nprint (\" cx factor: \")\nprint (cx / cx_gt)\nprint (\" cy factor: \")\nprint (cy / cy_gt)\nprint (\" cx factor / cy factor: \")\nprint ((cx / cx_gt) / (cy / cy_gt))\nprint (\" fx factor / cx factor: \")\nprint ((fx / fx_gt) / (cx / cx_gt))\n\n\n\n","sub_path":"python/compare_calibration_files.py","file_name":"compare_calibration_files.py","file_ext":"py","file_size_in_byte":2586,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"409718820","text":"\"\"\"\nSuccess\nDetails \nRuntime: 84 ms, faster than 82.89% of Python3 online submissions for Minimum Height Trees.\nMemory Usage: 17.7 MB, less than 61.05% of Python3 online submissions for Minimum Height Trees.\n\"\"\"\nfrom __future__ import annotations \nimport collections \nimport random \nimport heapq \n\nclass Solution:\n def findMinHeightTrees(self, n: int, edges: List[List[int]]) -> List[int]:\n if n == 1:\n return [0]\n adj = [set() for _ in range(n)]\n for i, j in edges:\n adj[i].add(j)\n adj[j].add(i)\n\n leaves = [i for i in range(n) if len(adj[i]) == 1]\n\n while n > 2:\n n -= len(leaves)\n new_leaves = []\n for l in leaves:\n j = adj[l].pop()\n adj[j].remove(l)\n if len(adj[j]) == 1:\n new_leaves.append(j)\n leaves = new_leaves\n return leaves\n\n\ns = Solution()\n\nn = 4\nedges = [[1, 0], [1, 2], [1, 3]]\nres = s.findMinHeightTrees(n, edges)\nexp = [1]\nprint(res, res == exp)\n\nn = 6\nedges = [[0, 3], [1, 3], [2, 3], [4, 3], [5, 4]]\nres = s.findMinHeightTrees(n, edges)\nexp = [3,4]\nprint(res, res == exp)\n","sub_path":"M_310_findMinHeightTrees.py","file_name":"M_310_findMinHeightTrees.py","file_ext":"py","file_size_in_byte":1175,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"78272995","text":"from __future__ import division\nfrom collections import defaultdict\nimport numpy as np\nimport csv\nfrom sklearn.decomposition import NMF, ProjectedGradientNMF\n\n\n# Predict using Matrix Factorization.\n\ndata_path = '../data/'\nres_path = '../res/'\ntrain_file = data_path + 'train.csv'\ncount_file = data_path + 'user_counts.csv'\ntest_file = data_path + 'test.csv'\nsoln_file = res_path + 'normed_MF_preds.csv'\n\n# Load the training data.\nmax_data = 1e9\n\ntrain_data = defaultdict(dict)\ntrain_artists = set()\nwith open(train_file, 'r') as train_fh:\n train_csv = csv.reader(train_fh, delimiter=',', quotechar='\"')\n next(train_csv, None)\n\n for i, row in enumerate(train_csv):\n # if i == max_data:\n # break\n user = row[0]\n artist = row[1]\n plays = row[2]\n\n train_artists.add(artist)\n train_data[user][artist] = float(plays)\n\n# Load global median, user play counts, and user medians.\nuser_counts = dict()\nuser_medians = dict()\nwith open(count_file, 'r') as count_fh:\n count_csv = csv.reader(count_fh, delimiter=',', quotechar='\"')\n next(count_csv, None)\n\n for i, row in enumerate(count_csv):\n if i == 0:\n global_median = row[0]\n continue\n elif i == 1:\n continue\n\n user = row[0]\n count = row[1]\n median = row[2]\n\n user_counts[user] = int(count)\n user_medians[user] = int(median)\n\nprint('done loading {} data'.format(i))\n\n# Assign users/artists `IDs` for indexing into arrays.\nuser_index = dict()\nindex_user = []\nfor i, user in enumerate(train_data):\n user_index[user] = i\n index_user.append(user)\n\nartist_index = dict()\nindex_artist = []\nfor i, artist in enumerate(train_artists):\n artist_index[artist] = i\n index_artist.append(artist)\n\n# Construct ratings matrix.\nR = np.zeros((len(train_data), len(train_artists)))\nfor user, user_data in train_data.iteritems():\n for artist, plays in user_data.iteritems():\n R[user_index[user], artist_index[artist]] = plays\nprint('done constructing {}x{} ratings matrix'.format(len(train_data), len(train_artists)))\n\nn = []\nfor row in R:\n n.append(np.count_nonzero(row))\nprint('average number of artists per user: {}'.format(\n np.mean(n)))\nprint('median number of artists per user: {}'.format(\n np.median(n)))\n\n# Get matrix factorization.\nn_components = 1\nmax_iter = 1000\n\nH_init = np.ones((n_components, len(train_artists)))\nW_init = np.zeros((len(train_data), n_components))\nfor i in range(len(W_init)):\n W_init[i] = user_medians[index_user[i]]\n\nnmf = NMF(n_components=n_components, init='nndsvda', alpha=1, max_iter=max_iter)\nW_user = nmf.fit_transform(R, W=W_init, H=H_init)\nH_artist = nmf.components_\n\n# mf = MatrixFactorizer()\n# W_user, H_artist = mf.factorize(R, artist_index, user_index)\n# IDEA: should only ALS on the non-zero components of R\n# (where the training data lies) to achieve better results\n\nprint('done factorizing ratings matrix')\n\n# Error on train data.\nerror = 0\nn = 0\nfor user, user_data in train_data.iteritems():\n for artist, plays in user_data.iteritems():\n n += 1\n pred = np.dot(W_user[user_index[user]], H_artist[:, artist_index[artist]])\n # print(pred, plays)\n error += abs(plays - pred)\nerror /= n\nprint('reconstruction error: {}'.format(error))\n\n# Predict plays for test file.\n# with open(test_file, 'r') as test_fh:\n# test_csv = csv.reader(test_fh, delimiter=',', quotechar='\"')\n# next(test_csv, None)\n#\n# with open(soln_file, 'w') as soln_fh:\n# soln_csv = csv.writer(soln_fh,\n# delimiter=',',\n# quotechar='\"',\n# quoting=csv.QUOTE_MINIMAL)\n# soln_csv.writerow(['Id', 'plays'])\n#\n# c = 0\n# r = 0\n# for row in test_csv:\n# r += 1\n#\n# id = row[0]\n# user = row[1]\n# artist = row[2]\n#\n# # previously unseen user\n# if user not in train_data:\n# pred = global_median\n#\n# # previously unseen artist\n# elif artist not in train_artists:\n# pred = user_medians[user]\n#\n# # existing pair in training data\n# elif train_data[user].get(artist, False):\n# pred = user_counts[user] * train_data[user][artist]\n# print('existing pred: {}'.format(pred))\n#\n# # predict plays from matrix factorization\n# else:\n# pred = user_counts[user] * np.dot(W_user[user_index[user]],\n# H_artist[:, artist_index[artist]])\n# if pred > user_medians[user]:\n# c += 1\n# print('MF pred={}, median={}, count={}'.format(\n# pred, user_medians[user], user_counts[user]))\n#\n# soln_csv.writerow([id, pred])\n#\n# print(c, r)\n","sub_path":"p3/code/matrix_factorization.py","file_name":"matrix_factorization.py","file_ext":"py","file_size_in_byte":4946,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"459737252","text":"import tensorflow as tf\r\nfrom inception import pipe\r\nfrom inception.model import inception\r\nfrom utils import metrics\r\n\r\nINF = int(1e9)\r\n\r\n\r\ndef get_learning_rate(learning_rate, hidden_size, learning_rate_warmup_steps):\r\n\r\n with tf.name_scope('learning_rate'):\r\n warmup_steps = tf.to_float(learning_rate_warmup_steps)\r\n step = tf.to_float(tf.train.get_or_create_global_step())\r\n\r\n learning_rate *= (hidden_size ** -0.5)\r\n\r\n learning_rate *= tf.minimum(1.0, step / warmup_steps)\r\n learning_rate *= tf.rsqrt(tf.maximum(step, warmup_steps))\r\n tf.identity(learning_rate, 'learning_rate')\r\n\r\n return learning_rate\r\n\r\n\r\ndef get_train_op_and_metrics(loss, params):\r\n\r\n with tf.variable_scope('get_train_op'):\r\n learning_rate = get_learning_rate(\r\n params['learning_rate'],\r\n params['hidden_size'],\r\n params['learning_rate_warmup_steps']\r\n )\r\n\r\n optimizer = tf.contrib.opt.LazyAdamOptimizer(\r\n learning_rate,\r\n beta1=params['optimizer_adam_beta1'],\r\n beta2=params['optimizer_adam_beta2'],\r\n epsilon=params['optimizer_adam_epsilon']\r\n )\r\n\r\n global_step = tf.train.get_global_step()\r\n tvars = tf.trainable_variables()\r\n gradients = optimizer.compute_gradients(\r\n loss, tvars, colocate_gradients_with_ops=True)\r\n clipped_gradients = tf.clip_by_global_norm([grad[0] for grad in gradients], params['gradient_clipping'])[0]\r\n minimize_op = optimizer.apply_gradients(\r\n [(grad, var[1]) for grad, var in zip(clipped_gradients, gradients)], global_step=global_step, name=\"train\")\r\n update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)\r\n train_op = tf.group(minimize_op, update_ops)\r\n\r\n return train_op\r\n\r\n\r\ndef model_fn(features, labels, mode, params):\r\n code_table = tf.contrib.lookup.index_table_from_file(\r\n params['icd_file'], vocab_size=params['vocab_size'])\r\n\r\n inputs, targets = pipe.input_layers(\r\n features, labels, code_table, pipe.make_columns(params)\r\n )\r\n\r\n initializer = tf.variance_scaling_initializer(\r\n params[\"initializer_gain\"], mode=\"fan_avg\", distribution=\"uniform\")\r\n\r\n model = inception.Model(params, mode == tf.estimator.ModeKeys.TRAIN, initializer)\r\n\r\n logits = model(inputs['codes'], inputs['aux_inputs'])\r\n loss = metrics.cross_entropy_loss(logits, targets, params['label_smoothing'], params['vocab_size'])\r\n\r\n if mode == tf.estimator.ModeKeys.EVAL:\r\n metrics_dict = {\r\n 'accuracy': tf.metrics.accuracy(\r\n targets,\r\n tf.argmax(logits, axis=-1)\r\n )\r\n }\r\n return tf.estimator.EstimatorSpec(\r\n mode=mode, loss=loss, predictions={'predictions': logits},\r\n eval_metric_ops=metrics_dict\r\n )\r\n if mode == tf.estimator.ModeKeys.TRAIN:\r\n train_op, metric_dict = get_train_op_and_metrics(loss, params)\r\n\r\n metric_dict['minibatch_loss'] = loss\r\n\r\n return tf.estimator.EstimatorSpec(mode=mode, loss=loss, train_op=train_op)\r\n\r\n\r\n\"\"\"\r\na = tf.contrib.distribute.MirroredStrategy(\r\n num_gpus=2,\r\n cross_tower_ops=tf.contrib.distribute.AllReduceCrossTowerOps(\r\n all_reduce_alg=\"hierarchical_copy\"\r\n )\r\n)\"\"\"","sub_path":"inception_main.py","file_name":"inception_main.py","file_ext":"py","file_size_in_byte":3328,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"129007570","text":"class fPeragaanItemParameter:\n def __init__(self,parentForm,FormObj):\n self.form = parentForm\n self.app = parentForm.ClientApplication\n self.FormView = None\n\n def Hapus(self,key):\n if self.app.ConfirmDialog('Yakin akan Menghapus Item Parameter Penggajian?'):\n pass\n else:\n return 0\n\n params = self.app.CreateValues(['key',key])\n retval = self.form.CallServerMethod('hapus',params)\n\n status = retval.FirstRecord\n if status.Peringatan != '':\n self.app.ShowMessage(status.Peringatan)\n return 0\n else :\n self.app.ShowMessage('Data Item Parameter Berhasil Dihapus')\n\n def NonAktifkan(self,key):\n params = self.app.CreateValues(['key',key])\n retval = self.form.CallServerMethod('NonAktif',params)\n\n status = retval.FirstRecord\n self.app.ShowMessage(status.Pesan)\n\n def Aktifkan(self,key):\n params = self.app.CreateValues(['key',key])\n retval = self.form.CallServerMethod('Aktif',params)\n\n status = retval.FirstRecord\n self.app.ShowMessage(status.Pesan)\n\n","sub_path":"dialogs/karyawan/fPeragaanItemParameter_intr.py","file_name":"fPeragaanItemParameter_intr.py","file_ext":"py","file_size_in_byte":1031,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"463715106","text":"## long string sorter \r\n\r\nword_arr = []\r\nlock = True\r\nn = 0\r\n\r\n\r\nwhile lock == True:\r\n \r\n n = int(input(\"enter the value of the number of words to be entered\"))\r\n\r\n if n > 100 or n < 0:\r\n print (\" enter a value between 0 and 100\")\r\n\r\n else:\r\n lock = False \r\n\r\n\r\n\r\n\r\nfor i in range (n):\r\n\r\n print (\"enter word\", i+1)\r\n inp = str(input(\"--- \"))\r\n word_arr.append(inp)\r\n\r\n\r\n\r\n\r\ndef shorten():\r\n for i in range (len(word_arr)):\r\n\r\n if len(str(word_arr[i])) > 10: # works only if length of word > 10\r\n\r\n new_str = \"\"\r\n\r\n mid = str(len(str(word_arr[i])) - 2) # the in the middle is just total length - 2\r\n\r\n woop = str(word_arr[i])\r\n \r\n new_str = new_str + (woop[0]) # concatenating first alphabet, length-2, last alphabet\r\n\r\n new_str = new_str + mid # \r\n\r\n new_str = new_str + (woop[len(woop)-1]) # add last alphabet\r\n\r\n word_arr[i] = new_str\r\n\r\n\r\nshorten()\r\nfor i in range (n):\r\n print (word_arr[i])\r\n\r\n\r\n\r\n","sub_path":"final/task 2/codeforces/codeforces 2 long word.py","file_name":"codeforces 2 long word.py","file_ext":"py","file_size_in_byte":1049,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"643813252","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# # Classificador de Assuntos\n# \n# Por Ana Carolina Pereira Rocha\n\nfrom docutils.nodes import header\nfrom sklearn.naive_bayes import MultinomialNB\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.neural_network import MLPClassifier\nfrom sklearn.svm import SVC,LinearSVC\nfrom datetime import timedelta\nimport time\nimport sys\nfrom datetime import datetime\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nimport uuid\nimport os\nfrom sklearn.calibration import CalibratedClassifierCV\nimport argparse\nimport multiprocessing as mp\nimport numpy as np\nimport pandas as pd\n\n# Verificando o ambiente de execução do conda\n\nimport os\nprint(os.environ['CONDA_DEFAULT_ENV'])\n\nimport funcoes as func\nfrom modelo import *\n\nn_cores = mp.cpu_count()\nn_cores_grande = round(n_cores * 0.8)\nn_cores_pequeno = round(n_cores * 0.35)\n\n# #### ATENÇÃO:\n#\n# A célula abaixo deve ser editada para conter o caminho correto para a pasta onde\n# os dados serão buscados, e a pasta onde serão gravadas as saídas do processamento\n# deste código. O caminho de cada pasta deve ser terminado com a '/' no final.\n\npath_fonte_de_dados = '/home//DocumentosClassificadorAssuntos/'\npath_resultados = '/home/DocumentosClassificadorAssuntos/DocsProcessados/'\n\nif not os.path.exists(path_resultados):\n os.makedirs(path_resultados)\n\nfloat_formatter = lambda x: \"%.4f\" % x\nnp.set_printoptions(formatter={'float_kind':float_formatter})\n\ncolumnsResultados=['id_execucao', 'data', 'nome','feature_type','tempo_processamento',\n 'tamanho_conjunto_treinamento', 'accuracy','balanced_accuracy',\n 'micro_precision','micro_recall','micro_fscore','macro_precision',\n 'macro_recall','macro_fscore','best_params_','best_estimator_',\n 'grid_scores_','grid_cv_results','confusion_matrix',\n 'classification_report','num_estimators','max_samples']\ndf_resultados = pd.DataFrame(columns = columnsResultados)\nnome_arquivo_destino = path_resultados + \"Metricas.csv\"\nif not (os.path.isfile(nome_arquivo_destino)):\n with open(nome_arquivo_destino, 'a') as f:\n df_resultados.to_csv(f, header=True)\nnome_classification_reports = path_resultados + 'ClassificationReport'\n\nid_execucao = str(uuid.uuid1())[:7]\ndata = datetime.now().strftime(\"%d/%m/%Y %H:%M:%S\")\n\nmodelos = []\n\nlistaAssuntos=[2546,2086,1855,2594,2458,2704,2656,2140,2435,2029,2583,2554,8808,\n 2117,2021,5280,1904,1844,2055,1907, 1806,55220,2506, 4437,10570,\n 1783,1888,2478,5356,1773,1663,5272,2215,1767,1661,1690]\n\n# Definindo modelos que serão usados\n\nclassificadorNB = MultinomialNB()\nclassificadorRF = RandomForestClassifier(random_state=42)\nclassificadorSVM = CalibratedClassifierCV(LinearSVC(class_weight='balanced',\n max_iter=10000,random_state=42),\n method='sigmoid', cv=5)\nclassificadorMLP = MLPClassifier(early_stopping= True,random_state=42)\n\nnomeAlgoritmoNB='Multinomial Naive Bayes'\nnomeAlgoritmoRF='Random Forest'\nnomeAlgoritmoSVM='SVM'\nnomeAlgoritmoMLP=\"Multi-Layer Perceptron\"\n\n# Pré-processamento dos documentos\n\npath_destino_de_dados = path_fonte_de_dados + 'DocumentosProcessados/'\nif not os.path.exists(path_destino_de_dados):\n os.makedirs(path_destino_de_dados)\n \n#func.processaDocumentos(path_fonte_de_dados,path_destino_de_dados)\nprint(\"Todos os documentos disponíveis foram processados\")\n\n\n# Recuperando textos\n\nqtdElementosPorAssunto=1000000\ndf_amostra = func.recupera_amostras_de_todos_regionais(listaAssuntos,\n qtdElementosPorAssunto, path_destino_de_dados)\n\n\n# Juntando os assuntos 55220 e 1855, ambos Indenização por Dano Moral\n\ndf_amostra.loc[df_amostra['cd_assunto_nivel_3'] == 55220, 'cd_assunto_nivel_3'] = 1855\ndf_amostra.loc[df_amostra['cd_assunto_nivel_2'] == 55218, 'cd_assunto_nivel_3'] = 2567\n\nprint('Total de textos recuperados: ' + str(len(df_amostra)))\ndf_amostra = df_amostra.dropna(subset=['texto_stemizado'])\nprint('Total de textos recuperados com conteúdo: ' + str(len(df_amostra)))\n\n\n# Analisando tamanho dos textos\n\ndf_amostra['quantidade_de_palavras'] = \\\n [len(x.split()) for x in df_amostra['texto_processado'].tolist()]\nsns.boxplot(df_amostra['quantidade_de_palavras'])\nplt.savefig(\"{0}{1}.png\".format(path_resultados, \"Distribuicao_Tamanho_Textos_Original\"))\n\ndf_amostra_f = df_amostra[((df_amostra.quantidade_de_palavras < 400) &\n (df_amostra.quantidade_de_palavras > 0))]\nprint('Quantidade de textos entre 0 e 400 palavras: ' + str(len(df_amostra_f)))\ndf_amostra_f = df_amostra[(df_amostra.quantidade_de_palavras > 10000)]\nprint('Quantidade de textos com mais de 10.000 palavras: ' + str(len(df_amostra_f)))\ndf_amostra.shape\ndf_amostra_f = df_amostra[((df_amostra.quantidade_de_palavras < 10000) &\n (df_amostra.quantidade_de_palavras > 400))]\ndf_amostra_f= df_amostra_f.sort_values(by='quantidade_de_palavras', ascending=True)\ndf_amostra_f.shape\ndf_amostra = df_amostra_f\nplt.clf()\nplt.cla()\nplt.close()\nsns.boxplot(df_amostra['quantidade_de_palavras'])\nplt.savefig(\"{0}{1}.png\".format(path_resultados, \"Distribuicao_Tamanho_Textos Final\"))\n\nprint('Total de textos utilizados: ' + str(len(df_amostra)))\nX_train, X_test, y_train, y_test = func.splitTrainTest(df_amostra)\nprint(\"Amostra de teste de \" + str(X_test.shape[0]) + \" elementos\")\nprint(\"Amostra de treinamento de \" + str(X_train.shape[0]) + \" elementos\")\n\ntitle = \"Balanceamento de assuntos na amostra de \" + str(X_train.shape[0])\nfunc.mostra_balanceamento_assunto(y_train.value_counts(), title,\n \"Quantidade Elementos\", \"Código Assunto\",\n path_resultados, y_train.shape[0])\n\n\n# ## Criando matrizes\n\n# #### TF-IDF\n\nstart_time = time.time()\ntfidf_transformer,x_tfidf_train, x_tfidf_test = \\\n func.extraiFeaturesTFIDF_train_test(df_amostra,\n X_train['texto_stemizado'], X_test['texto_stemizado'], path_resultados)\ntotal_time = time.time() - start_time\nprint(\"Tempo para montar matrizes TF-IDF (features: \"\n + str(x_tfidf_train.shape[1]) + \") :\"\n + str(timedelta(seconds=total_time)))\n\n# #### BM25\n\nbm25_transformer,x_bm25_train, x_bm25_test = func.extraiFeaturesBM25(df_amostra,\n tfidf_transformer, x_tfidf_train, x_tfidf_test, path_resultados)\n\n# #### LSI\n\nlsi100_transformer,x_lsi100_train, x_lsi100_test = func.extraiFeaturesLSI(df_amostra,\n X_train['texto_stemizado'], X_test['texto_stemizado'],\n 100, path_resultados)\nlsi250_transformer,x_lsi250_train, x_lsi250_test = func.extraiFeaturesLSI(df_amostra,\n X_train['texto_stemizado'], X_test['texto_stemizado'],\n 250, path_resultados)\n\n# ## Grid Search\n# #### Com TF-IDF\n# \n# Coloque aqui a quantidade de configurações diferentes a serem testadas\n# no GridSearch para cada modelo.\n\nnumero_de_configuracoes_por_modelo=2\n\n# #### Multinomial Naïve-Bayes (NB)\n\nparam_grid_NB = {\n 'estimator__n_estimators': [3,5],\n 'estimator__max_samples': [0.8,0.5],\n 'estimator__base_estimator__alpha': [0.0001, 0.001, 0.01, 0.1, 0.5, 1]\n}\nmodeloNB = func.chama_treinamento_modelo(x_tfidf_train, y_train, x_tfidf_test,\n y_test, classificadorNB,\n nomeAlgoritmoNB , 'TFIDF',param_grid_NB,\n numero_de_configuracoes_por_modelo,\n n_cores_grande,id_execucao ,data,path_resultados,df_resultados,\n nome_arquivo_destino,X_test)\nmodelos.append([modeloNB.getNome(),modeloNB.getFeatureType(),\n modeloNB.getMicroPrecision(),modeloNB])\n\n# #### SVM\n\nparam_grid_SVM = {\n 'estimator__n_estimators': [3, 5],\n 'estimator__max_samples': [0.8, 0.5],\n 'estimator__base_estimator__base_estimator__C': [0.01, 0.1, 1, 10]\n}\nmodeloSVM = func.chama_treinamento_modelo(x_tfidf_train,y_train, x_tfidf_test,y_test,\n classificadorSVM, nomeAlgoritmoSVM,'TFIDF',\n param_grid_SVM, numero_de_configuracoes_por_modelo,\n n_cores_grande,id_execucao ,data,path_resultados,df_resultados,\n nome_arquivo_destino,X_test)\nmodelos.append([modeloSVM.getNome(), modeloSVM.getFeatureType(),\n modeloSVM.getMicroPrecision(),modeloSVM])\n\n# #### Random Forest (RF)\n\nparam_grid_RF = {\n 'estimator__n_estimators': [3,5],\n 'estimator__max_samples': [0.8,0.5],\n 'estimator__base_estimator__max_depth': [30,50,100],\n 'estimator__base_estimator__n_estimators': [100,200,300],\n 'estimator__base_estimator__min_samples_leaf': [0.05, 0.1, 0.5],\n 'estimator__base_estimator__min_samples_split': [0.05, 0.1, 0.5],\n 'estimator__base_estimator__max_features': [0.3, 0.5, 0.8]\n}\nmodeloRF = func.chama_treinamento_modelo(x_tfidf_train,y_train,\n x_tfidf_test,y_test, classificadorRF,\n nomeAlgoritmoRF,'TFIDF',param_grid_RF,\n numero_de_configuracoes_por_modelo,\n n_cores_grande,id_execucao ,data,path_resultados,df_resultados,\n nome_arquivo_destino,X_test)\nmodelos.append([modeloRF.getNome(),modeloRF.getFeatureType(),\n modeloRF.getMicroPrecision(),modeloRF])\n\n# #### Multi-layer Perceptron\n\nparam_grid_MLP = {\n 'estimator__n_estimators': [3,5],\n 'estimator__max_samples': [0.8,0.5],\n 'estimator__base_estimator__hidden_layer_sizes': [(10,10),(10,5,10)],\n 'estimator__base_estimator__activation': ['identity', 'logistic', 'tanh', 'relu'],\n 'estimator__base_estimator__solver': ['sgd', 'adam','lbfgs'],\n 'estimator__base_estimator__alpha': [0.001, 0.01, 0.05, 0.1],\n 'estimator__base_estimator__learning_rate': ['constant','adaptive','invscaling'],\n 'estimator__base_estimator__max_iter': [200,300,400]\n}\nmodeloMLP = func.chama_treinamento_modelo(x_tfidf_train,y_train, x_tfidf_test,y_test,\n classificadorMLP, nomeAlgoritmoMLP, 'TFIDF',\n param_grid_MLP, numero_de_configuracoes_por_modelo,\n n_cores_pequeno,id_execucao ,data,path_resultados,\n df_resultados, nome_arquivo_destino,X_test)\nmodelos.append([modeloMLP.getNome(),modeloMLP.getFeatureType(),\n modeloMLP.getMicroPrecision(),modeloMLP])\n\n# #### Criando dicionarios com a melhor configuração de cada modelo\n\n#MNB\nparam_grid_melhor_NB = {\n 'estimator__n_estimators':\n [modeloNB.getBestParams().get('estimator__n_estimators')],\n 'estimator__max_samples':\n [modeloNB.getBestParams().get('estimator__max_samples')],\n 'estimator__base_estimator__alpha':\n [modeloNB.getBestParams().get('estimator__base_estimator__alpha')]\n}\n\n# SVM\nparam_grid_melhor_SVM = {\n 'estimator__n_estimators':\n [modeloSVM.getBestParams().get('estimator__n_estimators')],\n 'estimator__max_samples':\n [modeloSVM.getBestParams().get('estimator__max_samples')],\n 'estimator__base_estimator__base_estimator__C':\n [modeloSVM.getBestParams().\n get('estimator__base_estimator__base_estimator__C')]\n}\n\n# RF\nparam_grid_melhor_RF = {\n 'estimator__n_estimators':\n [modeloRF.getBestParams().get('estimator__n_estimators')],\n 'estimator__max_samples':\n [modeloRF.getBestParams().get('estimator__max_samples')],\n 'estimator__base_estimator__max_depth':\n [modeloRF.getBestParams().get('estimator__base_estimator__max_depth')],\n 'estimator__base_estimator__n_estimators':\n [modeloRF.getBestParams().get('estimator__base_estimator__n_estimators')],\n 'estimator__base_estimator__min_samples_leaf':\n [modeloRF.getBestParams().get('estimator__base_estimator__min_samples_leaf')],\n 'estimator__base_estimator__min_samples_split':\n [modeloRF.getBestParams().get('estimator__base_estimator__min_samples_split')],\n 'estimator__base_estimator__max_features':\n [modeloRF.getBestParams().get('estimator__base_estimator__max_features')]\n}\n\n# MLP\nparam_grid_melhor_MLP = {\n 'estimator__n_estimators':\n [modeloMLP.getBestParams().get('estimator__n_estimators')],\n 'estimator__max_samples':\n [modeloMLP.getBestParams().get('estimator__max_samples')],\n 'estimator__base_estimator__hidden_layer_sizes':\n [modeloMLP.getBestParams().get('estimator__base_estimator__hidden_layer_sizes')],\n 'estimator__base_estimator__activation':\n [modeloMLP.getBestParams().get('estimator__base_estimator__activation')],\n 'estimator__base_estimator__solver':\n [modeloMLP.getBestParams().get('estimator__base_estimator__solver')],\n 'estimator__base_estimator__alpha':\n [modeloMLP.getBestParams().get('estimator__base_estimator__alpha')],\n 'estimator__base_estimator__learning_rate':\n [modeloMLP.getBestParams().get('estimator__base_estimator__learning_rate')],\n 'estimator__base_estimator__max_iter':\n [modeloMLP.getBestParams().get('estimator__base_estimator__max_iter')]\n}\n\n# #### BM25\n\nmodeloNB_BM25 = func.chama_treinamento_modelo(x_bm25_train,y_train, x_bm25_test,\n y_test, classificadorNB,\n nomeAlgoritmoNB,'BM25',param_grid_melhor_NB, 1,n_cores_grande,\n id_execucao ,data,path_resultados,df_resultados,nome_arquivo_destino,\n X_test)\nmodelos.append([modeloNB_BM25.getNome(),modeloNB_BM25.getFeatureType(),\n modeloNB_BM25.getMicroPrecision(),modeloNB_BM25])\n\nmodeloSVM_BM25 = func.chama_treinamento_modelo(x_bm25_train,y_train, x_bm25_test,\n y_test, classificadorSVM,\n nomeAlgoritmoSVM,'BM25',param_grid_melhor_SVM, 1,n_cores_grande,\n id_execucao ,data,path_resultados,df_resultados,nome_arquivo_destino,\n X_test)\nmodelos.append([modeloSVM_BM25.getNome(),modeloSVM_BM25.getFeatureType(),\n modeloSVM_BM25.getMicroPrecision(),modeloSVM_BM25])\n\nmodeloRF_BM25 = func.chama_treinamento_modelo(x_bm25_train,y_train, x_bm25_test,\n y_test, classificadorRF,nomeAlgoritmoRF,\n 'BM25',param_grid_melhor_RF, 1,n_cores_grande,id_execucao,\n data,path_resultados,df_resultados,nome_arquivo_destino,X_test)\nmodelos.append([modeloRF_BM25.getNome(),modeloRF_BM25.getFeatureType(),\n modeloRF_BM25.getMicroPrecision(),modeloRF_BM25])\n\nmodeloMLP_BM25 = func.chama_treinamento_modelo(x_bm25_train,y_train, x_bm25_test,\n y_test, classificadorMLP,\n nomeAlgoritmoMLP,'BM25',param_grid_melhor_MLP, 1,n_cores_pequeno,\n id_execucao ,data,path_resultados,df_resultados,nome_arquivo_destino,\n X_test)\nmodelos.append([modeloMLP_BM25.getNome(),modeloMLP_BM25.getFeatureType(),\n modeloMLP_BM25.getMicroPrecision(), modeloMLP_BM25])\n\n# #### LSI 100\n\nmodeloSVM_LSI100 = func.chama_treinamento_modelo(x_lsi100_train,y_train, x_lsi100_test ,\n y_test, classificadorSVM,\n nomeAlgoritmoSVM, 'LSI100',param_grid_melhor_SVM, 1,n_cores_grande,\n id_execucao ,data,path_resultados,df_resultados,nome_arquivo_destino,\n X_test)\nmodelos.append([modeloSVM_LSI100.getNome(),modeloSVM_LSI100.getFeatureType(),\n modeloSVM_LSI100.getMicroPrecision(),\n modeloSVM_LSI100])\n\nmodeloRF_LSI100 = func.chama_treinamento_modelo(x_lsi100_train, y_train,x_lsi100_test ,\n y_test, classificadorRF,\n nomeAlgoritmoRF, 'LSI100',param_grid_melhor_RF, 1,n_cores_grande,\n id_execucao ,data,path_resultados,df_resultados,nome_arquivo_destino,\n X_test)\nmodelos.append([modeloRF_LSI100.getNome(),modeloRF_LSI100.getFeatureType(),\n modeloRF_LSI100.getMicroPrecision(), modeloRF_LSI100])\n\nmodeloMLP_LSI100 = func.chama_treinamento_modelo(x_lsi100_train,y_train, x_lsi100_test ,\n y_test, classificadorMLP,\n nomeAlgoritmoMLP,'LSI100',param_grid_melhor_MLP, 1,n_cores_pequeno,\n id_execucao ,data,path_resultados,df_resultados,nome_arquivo_destino,\n X_test)\nmodelos.append([modeloMLP_LSI100.getNome(),modeloMLP_LSI100.getFeatureType(),\n modeloMLP_LSI100.getMicroPrecision(), modeloMLP_LSI100])\n\n# #### LSI 250\n\nmodeloSVM_LSI250 = func.chama_treinamento_modelo(x_lsi250_train,y_train, x_lsi250_test ,\n y_test, classificadorSVM,\n nomeAlgoritmoSVM, 'LSI250',param_grid_melhor_SVM, 1,n_cores_grande,\n id_execucao ,data,path_resultados,df_resultados,nome_arquivo_destino,\n X_test)\nmodelos.append([modeloSVM_LSI250.getNome(),modeloSVM_LSI250.getFeatureType(),\n modeloSVM_LSI250.getMicroPrecision(), modeloSVM_LSI250])\n\nmodeloRF_LSI250 = func.chama_treinamento_modelo(x_lsi250_train, y_train,x_lsi250_test ,\n y_test, classificadorRF,\n nomeAlgoritmoRF, 'LSI250',param_grid_melhor_RF, 1,n_cores_grande,\n id_execucao ,data,path_resultados,df_resultados,nome_arquivo_destino,\n X_test)\nmodelos.append([modeloRF_LSI250.getNome(),modeloRF_LSI250.getFeatureType(),\n modeloRF_LSI250.getMicroPrecision(), modeloRF_LSI250])\n\nmodeloMLP_LSI250 = func.chama_treinamento_modelo(x_lsi250_train,y_train, x_lsi250_test ,\n y_test, classificadorMLP,\n nomeAlgoritmoMLP,'LSI250',param_grid_melhor_MLP, 1,n_cores_pequeno,\n id_execucao ,data,path_resultados,df_resultados,nome_arquivo_destino,\n X_test)\nmodelos.append([modeloMLP_LSI250.getNome(),modeloMLP_LSI250.getFeatureType(),\n modeloMLP_LSI250.getMicroPrecision(), modeloMLP_LSI250])\n\n# Encontrando o modelo vencedor\n\nmodelos_df = pd.DataFrame(modelos,\n columns=['Nome Modelo','Feature Type','micro_precision','Modelo'])\nmodelos_df= modelos_df.sort_values(by='micro_precision', ascending=False)\nprint(\"O modelo vencedor foi o \" + modelos_df.iloc[0]['Nome Modelo'] + \", com \" +\n (str(\"%.2f\" % modelos_df.iloc[0]['micro_precision'])) + \" de micro precisão\")\n\nmodelo_vencedor = modelos_df.iloc[0]['Modelo']\n\narquivoPickle = open(path_resultados + \"MelhorModelo.p\", 'wb')\npickle.dump(modelo_vencedor.getBestEstimator(), arquivoPickle)\narquivoPickle.close()\n\nif modelo_vencedor.getFeatureType() == 'LSI100':\n feature_vencedora = open(path_resultados + \"MelhorModeloFeature.p\", 'wb')\n pickle.dump(lsi100_transformer, feature_vencedora)\n feature_vencedora.close()\nelif modelo_vencedor.getFeatureType() == 'LSI250':\n feature_vencedora = open(path_resultados + \"MelhorModeloFeature.p\", 'wb')\n pickle.dump(lsi250_transformer, feature_vencedora)\n feature_vencedora.close()\nelif modelo_vencedor.getFeatureType() == 'TFIDF':\n feature_vencedora = open(path_resultados + \"MelhorModeloFeature.p\", 'wb')\n pickle.dump(tfidf_transformer, feature_vencedora)\n feature_vencedora.close()\nelif modelo_vencedor.getFeatureType() == 'BM25':\n feature_vencedora = open(path_resultados + \"MelhorModeloFeature.p\", 'wb')\n pickle.dump(bm25_transformer, feature_vencedora)\n feature_vencedora.close()\n \nprint(\"O modelo para transformação dos textos pré-processados se encontra no arquivo \"\n + path_resultados +\n \"MelhorModeloFeature.p\" + \" e o modelo de classificação no arquivo \"\n + path_resultados + \"MelhorModelo.p\")\n\n","sub_path":"ClassificadorAssuntos.py","file_name":"ClassificadorAssuntos.py","file_ext":"py","file_size_in_byte":19540,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"263599169","text":"from modules import get_conn, truncate_table_name\nimport pandas as pd\n\nengine = get_conn()\n\n\ndef create_table_latest_marquee_prices(table_name,existing_table_1,existing_table_2):\n\t\n\tprint('Creating a Table.')\n\tsql = '''select distinct a.* from raw.\"{0}\" as a \n\tleft join raw.\"{1}\" as b on a.evcode = b.event_code \t\n\twhere b.show_date >= a.file_date - 2 or b.show_date is null'''.format(existing_table_1,existing_table_2) \n\t\n\t\n\tdf = pd.read_sql_query(sql, con=engine)\n\tdf.to_sql(table_name,if_exists = 'replace', con=engine, chunksize=1000, schema='consumption',index=False)\n\tprint('Temp table created')\n\treturn df\n\ndef delete_recent_date_Marq(hist_table_name,recent_table_name):\n\tengine.execute(''' select * from raw.\"{0}\" \n\twhere run_date =(select max(file_date) from raw.\"{1}\")'''.format(hist_table_name,recent_table_name))\n\tprint('it done')\n\n\ndef delete_recent_date_Trans(hist_table_name,recent_table_name):\n\tengine.execute(''' delete from raw.{0} \n\twhere transaction_date =(select max(transaction_date) from raw.{1})'''.format(hist_table_name,recent_table_name))\n\tprint('it done')\n\n\ndef insert_recent_data_into_hist(hist_table_name,recent_table_name):\n\tengine.execute('''insert into raw.{0} select * from raw.{1}'''.format(hist_table_name,recent_table_name))\n\tprint('really done')\n\n\n\n","sub_path":"Sql_Transform.py","file_name":"Sql_Transform.py","file_ext":"py","file_size_in_byte":1288,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"67037946","text":"import csv\nwords = [\"oil\", \"vehicle\", \"university\", \"dalhousie\", \"expensive\", \"good school\",\n \"dalhousie\", \"expensive\", \"good school\", \"good schools\", \"bad school\", \"bad schools\", \"poor school\",\n \"poor schools\", \"population\", \"bus\", \"buses\", \"agriculture\", \"economy\"]\nmyfile = open(\"/home/ubuntu/DataAssignment2/all_data.csv\",\"r\",encoding=\"utf-8\")\nreadCSV = csv.reader(myfile, delimiter=',')\nresult=[]\nfor row in readCSV:\n text = (row[0])\n for w in words:\n if w in text:\n count =text.count(w)\n for i in range(count):\n result.append(w)\n\n","sub_path":"spark.py","file_name":"spark.py","file_ext":"py","file_size_in_byte":602,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"115963148","text":"class Node:\n def __init__(self, value):\n self.value = value\n self.next = None\n\ndef reverse(node):\n head = node\n new_head = node.next\n node.next = None\n while new_head:\n future_head = new_head.next\n new_head.next = head\n head = new_head\n new_head = future_head\n return head\n\n\n\n\n\n\n\n\ndef recursive_reverse(node):\n if node.next is None:\n return node\n node.next = None\n new_head = node.next\n future_head = recursive_reverse(new_head)\n new_head.next = node\n return future_head\n\n# 123\n# 23\n# 3\n# 3\n\n\n# 1 234\n# 2 34\n# 3 4\n# 4-back\n# 43\n# 432\n# 4321\n\na = Node(1)\nb = Node(2)\na.next = b\nc = Node(3)\nb.next = c\nd = Node(4)\nc.next = d\ne = Node(5)\nd.next = e\n\nforward = a\nprint(\"Forward\")\nwhile forward is not None:\n print(forward.value)\n forward = forward.next\n\nprint(\"Reversed\")\nreversed = recursive_reverse(a)\nwhile reversed is not None:\n print(reversed.value)\n reversed = reversed.next\n\nword = \"five\"\ndef rev(word):\n if len(word) == 1:\n return word\n word = rev(word[1:]) + (word[0])\n return word\n\nprint(rev(word))","sub_path":"reverse.py","file_name":"reverse.py","file_ext":"py","file_size_in_byte":1169,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"292772667","text":"class Solution(object):\n def findTargetSumWays(self, nums, S):\n if not nums:\n return 0\n '''\n initiate d for a better use of get after\n '''\n d = {nums[0]: 1, -nums[0]: 1} if nums[0] else {0: 2}\n for num in nums[1:]:\n t = {}\n for k in d:\n t[k + num] = t.get(k + num, 0) + d.get(k, 0)\n t[k - num] = t.get(k - num, 0) + d.get(k, 0)\n d = t\n '''\n using a new dict because we shoudln't change d while it is still iterating\n the key idea is to use DP and record the times every result could come up\n t[k + num] = the older t[k + num] + new way to get [k + num] from d[k]\n '''\n return d.get(S, 0) #retuen a get in case we can not get S in this way\n","sub_path":"400-499/TargetSum_494.py","file_name":"TargetSum_494.py","file_ext":"py","file_size_in_byte":821,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"114450837","text":"#!/usr/bin/env python3\nimport os\nimport locust_plugins.utils\n\nlocust_plugins.utils.gevent_debugger_patch()\nlocust_plugins.utils.print_json_on_decode_fail()\nfrom locust_plugins.listeners import PrintListener, TimescaleListener\nfrom locust_plugins.readers import PostgresReader\nfrom locust import HttpLocust, task, TaskSet\n\nTimescaleListener(\"example\")\n\ncustomer_reader = PostgresReader(f\"env='{os.environ['LOCUST_TEST_ENV']}' AND tb=0 AND lb=1\")\n\n\nclass UserBehavior(TaskSet):\n @task\n def my_task(self):\n customer = customer_reader.get()\n self.client.get(f\"/?ssn={customer['ssn']}\")\n customer_reader.release(customer)\n\n\nclass MyHttpLocust(HttpLocust):\n task_set = UserBehavior\n min_wait = 0\n max_wait = 0\n host = \"http://example.com\"\n if __name__ == \"__main__\":\n _catch_exceptions = False\n\n\n# allow running as executable, mainly to support attaching the debugger\nif __name__ == \"__main__\":\n PrintListener()\n MyHttpLocust().run()\n","sub_path":"examples/pgreader.py","file_name":"pgreader.py","file_ext":"py","file_size_in_byte":983,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"419386206","text":"#\r\n# Licensed to the Apache Software Foundation (ASF) under one\r\n# or more contributor license agreements. See the NOTICE file\r\n# distributed with this work for additional information\r\n# regarding copyright ownership. The ASF licenses this file\r\n# to you under the Apache License, Version 2.0 (the\r\n# \"License\"); you may not use this file except in compliance\r\n# with the License. You may obtain a copy of the License at\r\n#\r\n# http://www.apache.org/licenses/LICENSE-2.0\r\n#\r\n# Unless required by applicable law or agreed to in writing,\r\n# software distributed under the License is distributed on an\r\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\r\n# KIND, either express or implied. See the License for the\r\n# specific language governing permissions and limitations\r\n# under the License.\r\n#\r\n\r\n\"\"\"\r\nDefinition of urls for api resource.\r\n\"\"\"\r\n\r\nfrom django.conf.urls import url\r\nfrom django.urls import path, include\r\nfrom rest_framework import routers\r\nfrom drf_spectacular.views import SpectacularAPIView, SpectacularRedocView, SpectacularSwaggerView\r\n\r\nfrom api.views import AlgorithmViewSet, DatasetViewSet, PredictionRequestViewSet\r\n\r\nrouter = routers.DefaultRouter(trailing_slash=False)\r\nrouter.register(r\"algorithms\", AlgorithmViewSet, basename=\"algorithms\")\r\nrouter.register(r\"datasets\", DatasetViewSet, basename=\"datasets\")\r\nrouter.register(r\"requests\",\r\n PredictionRequestViewSet,\r\n basename=\"prediction_requests\")\r\n\r\nurlpatterns = [\r\n # API docs\r\n path('api-docs/', SpectacularAPIView.as_view(), name='api-docs'),\r\n \r\n # Optional UI:\r\n path('api-docs/swagger-ui',\r\n SpectacularSwaggerView.as_view(url_name='api-docs'),\r\n name='swagger-ui'),\r\n path('api-docs/redoc',\r\n SpectacularRedocView.as_view(url_name='api-docs'),\r\n name='redoc'),\r\n\r\n # API Views\r\n path('api-auth/', include('rest_framework.urls',\r\n namespace='rest_framework')),\r\n path('api/v1/', include(router.urls)),\r\n]\r\n","sub_path":"api/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":2017,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"266576971","text":"import numpy as np\nimport random\nimport math\nfrom scipy.spatial import distance\nfrom tdw.output_data import IsOnNavMesh\nfrom PIL import Image\nimport io\nimport os\nfrom tdw.controller import Controller\nimport tdw.librarian as librarian\n\n\nclass TDWUtils:\n \"\"\"\n Utility functions for controllers.\n\n Usage: `from tdw.tdw_utils import TDWUtils`\n \"\"\"\n\n VECTOR3_ZERO = {\"x\": 0, \"y\": 0, \"z\": 0}\n\n @staticmethod\n def vector3_to_array(vector3):\n \"\"\"\n Convert a Vector3 object to a numpy array.\n\n :param vector3: The Vector3 object.\n\n :return A numpy array.\n \"\"\"\n\n return np.array([vector3[\"x\"], vector3[\"y\"], vector3[\"z\"]])\n\n @staticmethod\n def array_to_vector3(arr):\n \"\"\"\n Convert a numpy array to a Vector3.\n\n :param arr: The numpy array.\n\n :return A Vector3.\n \"\"\"\n\n return {\"x\": arr[0], \"y\": arr[1], \"z\": arr[2]}\n\n @staticmethod\n def get_random_point_in_circle(center, radius):\n \"\"\"\n Get a random point in a circle, defined by a center and radius.\n\n :param center: The center of the circle.\n :param radius: The radius of the circle.\n\n :return A numpy array.\n \"\"\"\n\n alpha = 2 * math.pi * random.random()\n r = radius * math.sqrt(random.random())\n x = r * math.cos(alpha) + center[0]\n z = r * math.sin(alpha) + center[2]\n\n return np.array([x, 0, z])\n\n @staticmethod\n def get_magnitude(vector3):\n \"\"\"\n Get the magnitude of a Vector3.\n\n :param vector3: The Vector3 object.\n\n :return The vector magnitude.\n \"\"\"\n\n return np.linalg.norm(TDWUtils.vector3_to_array(vector3))\n\n @staticmethod\n def extend_line(p0, p1, d, clamp_y=True):\n \"\"\"\n Extend the line defined by p0 to p1 by distance d. Clamps the y value to 0.\n\n :param p0: The origin.\n :param p1: The second point.\n :param d: The distance of which the line is to be extended.\n :param clamp_y: Clamp the y value to 0.\n\n :return: The position at distance d.\n \"\"\"\n\n if clamp_y:\n p0[1] = 0\n p1[1] = 0\n\n # Get the distance between the two points.\n d0 = distance.euclidean(p0, p1)\n # Get the total distance.\n d_total = d0 + d\n\n return p1 + ((p1 - p0) * d_total)\n\n @staticmethod\n def get_distance(vector3_0, vector3_1):\n \"\"\"\n Calculate the distance between two Vector3 objects.\n\n :param vector3_0: The first Vector3.\n :param vector3_1: The second Vector3.\n\n :return The distance.\n \"\"\"\n\n return distance.euclidean(TDWUtils.vector3_to_array(vector3_0), TDWUtils.vector3_to_array(vector3_1))\n\n @staticmethod\n def get_box(width, length):\n \"\"\"\n Create a box GridPoint objects of the given dimensions.\n\n :param width: The width of the box.\n :param length: The length of the box.\n\n :return The box.\n \"\"\"\n\n box = []\n for x in range(width):\n for y in range(length):\n if x == 0 or x == width - 1 or y == 0 or y == length - 1:\n box.append({\"x\": x, \"y\": y})\n return box\n\n @staticmethod\n def get_vector3(x, y, z):\n \"\"\"\n Returns a dictionary: {\"x\": x, \"y\", y, \"z\": z}\n :param x: The x value.\n :param y: The y value.\n :param z: The z value.\n\n :return: A Vector3.\n \"\"\"\n\n return {\"x\": x, \"y\": y, \"z\": z}\n\n @staticmethod\n def create_empty_room(width, length, num_envs=1):\n \"\"\"\n Create an empty room.\n\n :param width: The width of the room.\n :param length: The length of the room.\n :param num_envs: The number of rooms.\n\n :return: The command.\n \"\"\"\n\n return {\"$type\": \"create_exterior_walls\", \"walls\": TDWUtils.get_box(width, length), \"num_envs\": num_envs}\n\n @staticmethod\n def save_images(images, frame, output_directory=\"dist\", filename=None, resize_to=None):\n \"\"\"\n Save each image in the Images object.\n\n :param images: The Images object. Contains each capture pass plus metadata.\n :param frame: The current frame number.\n :param output_directory: The directory to write images to.\n :param filename: The filename of each image.\n :param resize_to: Specify a (width, height) tuple to resize the images to. This is slower than saving as-is.\n \"\"\"\n\n frame = Controller.get_frame(frame)\n\n if not os.path.isdir(output_directory):\n os.makedirs(output_directory)\n\n for i in range(images.get_num_passes()):\n if not filename:\n fi = str(frame) + \"_\" + images.get_avatar_id() + \"_\" + str(images.get_env_id()) +\\\n images.get_pass_mask(i) + \".\" + images.get_extension(i)\n else:\n fi = filename + \".\" + images.get_extension(i)\n\n if resize_to:\n Image.open(io.BytesIO(images.get_image(i))).resize((resize_to[0], resize_to[1]), Image.LANCZOS)\\\n .save(os.path.join(output_directory, fi))\n else:\n with open(os.path.join(output_directory, fi), \"wb\") as f:\n f.write(images.get_image(i))\n\n @staticmethod\n def get_random_position_on_nav_mesh(c, width, length, x_e=0, z_e=0, bake=True, rng=random.uniform):\n \"\"\"\n Returns a random position on a NavMesh.\n\n :param c: The controller.\n :param width: The width of the environment.\n :param length: The length of the environment.\n :param bake: If true, send bake_nav_mesh.\n :param rng: Random number generator.\n :param x_e: The x position of the environment.\n :param z_e: The z position of the environment.\n\n :return The coordinates as a tuple (x, y, z)\n \"\"\"\n\n if bake:\n c.communicate({'$type': 'bake_nav_mesh'})\n\n # Try to find a valid position on the NavMesh.\n is_on = False\n x, y, z = (0, 0, 0)\n while not is_on:\n # Get a random position.\n x = rng(-width / 2, width / 2) + x_e\n z = rng(-length / 2, length / 2) + z_e\n resp = c.communicate(\n {'$type': 'send_is_on_nav_mesh',\n 'position': {'x': x, 'y': 0, 'z': z},\n 'max_distance': 4.0\n })\n answer = IsOnNavMesh(resp[0])\n is_on = answer.get_is_on()\n x, y, z = answer.get_position()\n return x, y, z\n\n @staticmethod\n def set_visual_material(substructure, object_id, material):\n \"\"\"\n Returns a list of commands to set ALL visual materials on an object to a single material.\n\n :param substructure: The metadata substructure of the object.\n :param object_id: The ID of the object in the scene.\n :param material: The name of the new material.\n\n :return The list of commands.\n \"\"\"\n\n commands = []\n for s in substructure:\n for i in range(len(s[\"materials\"])):\n commands.append({\"$type\": \"set_visual_material\",\n \"id\": object_id,\n \"new_material_name\": material,\n \"object_name\": s[\"name\"],\n \"old_material_index\": i})\n return commands\n\n @staticmethod\n def get_depth_values(image, screen_size, far_plane, near_plane):\n \"\"\"\n Get the depth values of each pixel in a _depth image pass.\n\n :param image: The image pass as a numpy array.\n :param screen_size: The screen size\n :param far_plane: The far clipping plane of the camera.\n :param near_plane: The near clipping plane of the camera.\n \"\"\"\n\n # Convert the image to a 2D image array.\n image = np.array(Image.open(io.BytesIO(image)))\n\n depth = (image[:, :, 0] * screen_size * screen_size + image[:, :, 1] * screen_size + image[:, :, 2]) / \\\n (screen_size * screen_size * screen_size) * (far_plane + near_plane)\n return depth\n\n @staticmethod\n def create_avatar(avatar_type=\"A_Img_Caps_Kinematic\", avatar_id=\"a\", position=None, look_at=None):\n \"\"\"\n This is a wrapper for `create_avatar` and, optionally, `teleport_avatar_to` and `look_at_position`.\n Returns a list of commands.\n\n :param avatar_type: The type of avatar.\n :param avatar_id: The avatar ID.\n :param position: The position of the avatar. If this is None, the avatar won't teleport.\n :param look_at: If this isn't None, the avatar will look at this position.\n \"\"\"\n\n # Create the avatar.\n commands = [{\"$type\": \"create_avatar\",\n \"type\": avatar_type,\n \"id\": avatar_id}]\n\n # Teleport the avatar.\n if position:\n commands.append({\"$type\": \"teleport_avatar_to\",\n \"avatar_id\": avatar_id,\n \"position\": position})\n if look_at:\n commands.append({\"$type\": \"look_at_position\",\n \"avatar_id\": avatar_id,\n \"position\": look_at})\n return commands\n","sub_path":"tdw/tdw/tdw_utils.py","file_name":"tdw_utils.py","file_ext":"py","file_size_in_byte":9304,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"222785470","text":"#!/usr/bin/env python\nimport sys\nimport pyglet\nimport touch_handler\nimport window_manager \n\nsys.stdout = open('log.txt', 'w')\npyglet.options['debug_gl'] = False\n\nif len(sys.argv) > 1:\n window = pyglet.window.Window(fullscreen=True)\nelse:\n window = pyglet.window.Window(480, 320)\nwindow.set_mouse_visible(False)\npyglet.font.add_file('data/cat.ttf')\npyglet.font.load('Cat Font')\npyglet.font.load('Helvetica')\n\ntouch = touch_handler.TouchHandler()\nwindowMan = window_manager.WindowManager()\n\n@window.event\ndef on_mouse_press(x, y, button, modifiers):\n x = 480-x\n y = 320-y\n touch.press(x, y)\n\n@window.event\ndef on_mouse_release(x, y, button, modifiers):\n x = 480-x\n y = 320-y\n event = touch.release(x, y)\n windowMan.registerPress(event, x, y)\n\n@window.event\ndef on_draw():\n window.clear()\n windowMan.draw()\n\npyglet.app.run()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":855,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"315602042","text":"import logging\nimport os\nimport re\nfrom datetime import date, datetime\n\nfrom src.utils.ipython import in_ipython\n\nmain_logger_name = \"thermo\"\n\n\ndef get_log_dir(path=\"\", prefix=\"logs\", subdirs=[]):\n \"\"\"Returns a path ending in a time stamp for saving logs\n to for a given combination of model and labels. Creates a\n directory at that path if necessary.\n \n Args:\n model_name (str): Name of the running model.\n labels (str): Name of the labels the model predicts.\n path (str, optional): Path prefix.\n \n Returns:\n str: The full path to which logs will be saved.\n \"\"\"\n stamp = datetime.now().strftime(\"%m-%d@%H:%M:%S\")\n path = re.sub(\"/+\", \"/\", f\"{prefix}/{path}/{stamp}/\")\n os.makedirs(path, exist_ok=True)\n for direc in subdirs:\n os.makedirs(path + direc, exist_ok=True)\n return path\n\n\ndef configure_main_logger(log_file_path, level):\n \"\"\"Configures the main logger to write logs to the console and\n (if not running Python in interactive mode or if the env variable\n `save_to_disk` is set) a file at `path + filename` with default\n logging level INFO.\n \"\"\"\n # Note: If the main logger was renamed to \"src\", all loggers created in\n # submodules via logging.getLogger(\"thermo\") could become child loggers\n # that inherit its config unless it's the main script being executed in\n # which case unfortunately __name__=\"__main__\".\n logger = logging.getLogger(main_logger_name)\n # Do not propagate messages further to the root logger.\n logger.propagate = False\n logger.setLevel(getattr(logging, level))\n\n if not in_ipython() or os.getenv(\"save_to_disk\") == \"True\":\n file_handler = logging.FileHandler(log_file_path)\n file_formatter = logging.Formatter(\"\\n%(asctime)s - %(message)s\", \"%H:%M:%S\")\n file_handler.setFormatter(file_formatter)\n logger.addHandler(file_handler)\n\n print(f\"Logs will be saved to {log_file_path}.\")\n logger.info(f\"These logs were generated on {date.today()}.\")\n\n console = logging.StreamHandler()\n console_formatter = logging.Formatter(\"\\n%(message)s\")\n console.setFormatter(console_formatter)\n logger.addHandler(console)\n\n\ndef get_logger(path=None, log_file=\"run.log\", level=\"INFO\"):\n if not in_ipython():\n assert path, \"Missing path in get_logger call.\"\n assert log_file, \"Missing log file in get_logger call.\"\n\n if not logging.getLogger(main_logger_name).handlers:\n configure_main_logger(path + log_file, level)\n return logging.getLogger(main_logger_name)\n","sub_path":"src/utils/logging.py","file_name":"logging.py","file_ext":"py","file_size_in_byte":2572,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"189395659","text":"# Definition for singly-linked list.\nclass ListNode(object):\n def __init__(self, x):\n self.val = x\n self.next = None\ndef printList(l):\n value = []\n while(l):\n value.append(l.val)\n l = l.next\n print(' -> '.join(map(str, value)))\ndef addTwoNumbers(l1, l2):\n \"\"\"\n :type l1: ListNode\n :type l2: ListNode\n :rtype: ListNode\n \"\"\"\n \n printList(l1)\n printList(l2)\n sum = l1.val + l2.val\n carry = int(sum/10)\n l3 = ListNode(sum%10)\n p1 = l1.next\n p2 = l2.next\n p3 = l3\n if l1.next == None and l2.next ==None:\n if carry > 0:\n l3 = ListNode(sum%10)\n l3.next = ListNode(carry)\n printList(l3)\n else:\n l3 = ListNode(sum)\n printList(l3)\n while p1 != None or p2 !=None:\n sum = carry + (p1.val if p1 else 0) + (p2.val if p2 else 0)\n carry = int(sum/10)\n p3.next = ListNode(sum % 10)\n p3 = p3.next\n p1 = p1.next if p1 else None\n p2 = p2.next if p2 else None\n if carry > 0:\n p3.next = ListNode(carry)\n printList(l3)\n\n\n# l1 = ListNode(2)\n# l1.next = ListNode(4)\n# l1.next.next = ListNode(3)\n\n# l2 = ListNode(5)\n# l2.next = ListNode(6)\n# l2.next.next = ListNode(4)\nl1 = ListNode(0)\nl2 = ListNode(0)\n\naddTwoNumbers(l1, l2)\n","sub_path":"linkedLists/add2Lists.py","file_name":"add2Lists.py","file_ext":"py","file_size_in_byte":1321,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"179968543","text":"#!/usr/bin/python\n# Code written by @gerty\n# 12-7-2016\n# This is the first day using Python 3 in the miniconda environment - then switched to just PyCharm\n\nimport collections\n\n# Input from Day 4, Problem 2 of Advent of Code (yes, I'm behind!)\n# Input files in same directory\n# My input: in file D4input.txt\n\nrawdata = [] # <-- all the lines of data\ncrypt = [] # <-- just the encrypted data\nrooms = [] # <-- only the room numbers\nchecksums = [] # <-- only the checksums\nworksum = collections.Counter()\ncalcsum = '' # <-- calculated checksum for room\ntempsum = []\nsectorIDsum = 0 # <-- sum of real room numbers\n\nf = open('D4input.txt', 'r')\nrawdata = f.readlines()\n\nfor line in range(len(rawdata)):\n crypt.append(rawdata[line].split(\"-\")[:-1]) # <-- Establish crypt with split checksum\n crypt[line] = ''.join(crypt[line]) # <-- (put the string back together)\n\n rooms.append(rawdata[line].split(\"[\")[0].split(\"-\")[-1]) # <-- Establish rooms with the room number\n checksums.append(rawdata[line].split(\"[\")[1][0:5]) # <-- Establish checksums\n\n # Once you have lists of encrypted data for each room, the room number, and the checksum...\n\n worksum = collections.Counter(crypt[line]) # <-- Load up single use of worksum\n\n# print(worksum, rooms[line], checksums[line])\n\n calcsum = ''\n while len(calcsum) < 5: # <-- While we still have less than 5 chars in our calcsum\n x = worksum.most_common(1)[0][1] # <-- Find the max occurring number of chars in worksum collection\n# print(x)\n temp = '' # <-- Get ready to add somethng to calcsum\n for letter, count in worksum.most_common(): # <-- Looking at all of the remaining entries in worksum\n if count == x: # <-- if a letter is one of the top occurring left in the set\n temp += letter # <-- then add the letter to our yet-to-be-sorted string\n for count in range(len(temp)):\n worksum.pop(temp[count]) # Remove largest entries from worksum so they don't reappear\n calcsum += ''.join(sorted(temp)) # Add the sorted list of letters with x frequency to calcsum\n# print(calcsum)\n\n if calcsum[0:5] == checksums[line]:\n sectorIDsum += int(rooms[line])\n answer = ''\n for ch in crypt[line]:\n t1 = int(rooms[line])\n t2 = (ord(ch) - ord('a'))\n letter = chr((t1+t2)%26 + ord('a'))\n answer += letter\n print(answer,rooms[line])\n\nprint(sectorIDsum)\n\n# First attempt returns 6367, and was too low\n# Second attempt yielded 361724, and ... was correct!\n\n# The north pole objects are stored in 482 - output file saved.\n","sub_path":"Day 04 - Security Through Obscurity/AoC_D4-2.py","file_name":"AoC_D4-2.py","file_ext":"py","file_size_in_byte":2762,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"361080996","text":"from django.shortcuts import render, redirect\n\nfrom django.contrib.auth import authenticate, login\nfrom django.http import HttpResponseRedirect, HttpResponse\nfrom django.core.urlresolvers import reverse\nfrom django.contrib.auth import logout\nfrom django.contrib.auth.decorators import login_required\nfrom.forms import UserForm, UserProfileForm, AddArticleForm, DotmForm, AddEventForm, ServiceForm, AddDogForm\nfrom.models import Article, Event, Dotm, User, Service, Dog, UserProfile\n\n\nfrom datetime import datetime\n\ndef home(request):\n context_dict = {'boldmessage': \"Dogs everywhere\"}\n return render(request, 'destination_dog/home.html', context=context_dict)\n\ndef article_list(request):\n context_dict = {}\n\n article = Article.objects.order_by('-date')\n context_dict['article'] = article\n\n return render(request, 'destination_dog/article_list.html', context=context_dict)\n\ndef show_article(request, article_title_slug):\n\n context_dict = {}\n\n try:\n article = Article.objects.get(slug=article_title_slug)\n\n context_dict['article'] = article\n\n except Article.DoesNotExist:\n context_dict['article'] = None\n\n return render(request, 'destination_dog/article.html', context_dict)\n\n@login_required\ndef add_article(request):\n\n user = User.objects.get(username=request.user)\n profile = user.userprofile\n\n form = AddArticleForm()\n\n if request.method == 'POST':\n form = AddArticleForm(request.POST)\n if form.is_valid():\n\n article = form.save(commit=False)\n article.author = profile\n\n if 'image' in request.FILES:\n article.image = request.FILES['image']\n\n article.save()\n return HttpResponseRedirect(reverse('article_list'))\n\n else:\n print(form.errors)\n\n context_dict = {'form': form}\n return render(request, 'destination_dog/add_article.html', context=context_dict)\n\ndef dotm(request):\n\n context_dict = {}\n month = datetime.now().month - 1\n year = datetime.now().year\n\n\n try:\n article = Article.objects.get(is_dotm=True)\n winner = Dotm.objects.get(winner=True, created_at__month=month, created_at__year=year)\n\n context_dict['winner'] = winner\n context_dict['article'] = article\n\n except Article.DoesNotExist:\n context_dict['article'] = None\n\n return render(request, 'destination_dog/dotm.html', context_dict)\n\n@login_required()\ndef dotm_vote(request):\n\n month = datetime.now().month\n year = datetime.now().year\n\n context_dict = {}\n dotm = Dotm.objects.filter(created_at__month=month, created_at__year=year)\n\n context_dict['dotm'] = dotm\n\n return render(request, 'destination_dog/dotm_vote.html', context_dict)\n\n@login_required\ndef vote_dotm(request):\n if request.method == 'GET':\n\n dotm_id = request.GET['dotmid']\n likes = 0\n if dotm_id:\n dotm = Dotm.objects.get(id=int(dotm_id))\n if dotm:\n likes = dotm.likes + 1\n dotm.likes = likes\n dotm.save()\n return HttpResponse(likes)\n\n@login_required()\ndef dotm_enter(request):\n\n user = User.objects.get(username=request.user)\n profile = user.userprofile\n\n form = DotmForm()\n\n if request.method == 'POST':\n form = DotmForm(request.POST)\n if form.is_valid():\n\n dotm = form.save(commit=False)\n dotm.owner = profile\n\n if 'image' in request.FILES:\n dotm.image = request.FILES['image']\n\n dotm.save()\n return HttpResponseRedirect(reverse('dotm_vote'))\n\n else:\n print(form.errors)\n\n context_dict = {'form': form}\n return render(request, 'destination_dog/dotm_enter.html', context=context_dict)\n\ndef dotm_hall_of_fame(request):\n\n context_dict = {}\n this_year = datetime.now().year\n last_year = this_year - 1\n\n\n thisyear = Dotm.objects.filter(winner=True, created_at__year=this_year)\n lastyear = Dotm.objects.filter(winner=True, created_at__year=last_year)\n\n context_dict['thisyear'] = thisyear\n context_dict['lastyear'] = lastyear\n\n return render(request, 'destination_dog/dotm_hall_of_fame.html', context=context_dict)\n\ndef locateServices(request):\n context_dict = {}\n service = Service.objects.order_by('name')\n context_dict['service'] = service\n return render(request, 'destination_dog/locateservice.html', context=context_dict)\n\ndef show_service(request, service_name_slug):\n context_dict = {}\n\n try:\n service = Service.objects.get(slug=service_name_slug)\n\n context_dict['service'] = service\n \n except Service.DoesNotExist:\n context_dict['service'] = None\n \n return render(request, 'destination_dog/service.html', context_dict)\n\n@login_required()\ndef add_service(request):\n user = User.objects.get(username=request.user)\n profile = user.userprofile\n\n form = ServiceForm()\n\n if request.method == 'POST':\n form = ServiceForm(request.POST)\n\n if form.is_valid():\n service = form.save(commit=False)\n service.provider = profile\n \n service.save()\n return locateServices(request)\n else:\n print(form.errors)\n \n context_dict = {'form':form}\n return render(request, 'destination_dog/add_service.html', context=context_dict)\n\ndef events(request):\n events_list = Event.objects.order_by('date')\n context_dict = {'events': events_list}\n return render(request, 'destination_dog/events.html', context=context_dict)\n\n@login_required\ndef add_events(request):\n\n user = User.objects.get(username=request.user)\n profile = user.userprofile\n\n form = AddEventForm()\n\n if request.method == 'POST':\n form = AddEventForm(request.POST)\n\n if form.is_valid():\n\n event = form.save(commit=False)\n event.user = profile\n\n event.save()\n return events(request)\n\n else:\n print(form.errors)\n\n return render(request, 'destination_dog/add_events.html', {'form': form})\n\ndef show_event(request, event_name_slug):\n context_dict = {}\n\n try:\n event = Event.objects.get(slug=event_name_slug)\n\n context_dict['event'] = event\n\n except Event.DoesNotExist:\n context_dict['event'] = None\n\n return render(request, 'destination_dog/event.html', context_dict)\n\ndef forum(request):\n context_dict = {'boldmessage' : \"chat to people\"}\n return render(request, 'destination_dog/forum.html', context=context_dict)\n\ndef about(request):\n context_dict = {'boldmessage' : \"enjoy yourself!\"}\n return render(request, 'destination_dog/about.html', context=context_dict)\n\ndef contactus(request):\n context_dict = {'boldmessage' : \"tell us something interesting\"}\n return render(request, 'destination_dog/contactus.html', context=context_dict)\n\ndef sitemap(request):\n context_dict = {'boldmessage' : \"find your way around\"}\n return render(request, 'destination_dog/sitemap.html', context=context_dict)\n\ndef user_login(request):\n if request.method == 'POST':\n username = request.POST.get('username')\n password = request.POST.get('password')\n\n user = authenticate(username=username, password=password)\n\n if user:\n if user.is_active:\n login(request, user)\n return HttpResponseRedirect(reverse('home'))\n else:\n return HttpResponse(\"Your account is disabled.\")\n else:\n print(\"Invalid login details: {0}, {1}\".format(username, password))\n return HttpResponse(\"Invalid login details supplied.\")\n \n else:\n return render(request, 'destination_dog/login.html', {})\n\ndef user_logout(request):\n logout(request)\n return HttpResponseRedirect(reverse('home'))\n\ndef register(request):\n registered = False\n\n if request.method == 'POST':\n user_form = UserForm(data=request.POST)\n profile_form = UserProfileForm(data=request.POST)\n\n if user_form.is_valid() and profile_form.is_valid():\n user = user_form.save()\n user.set_password(user.password)\n user.save()\n profile = profile_form.save(commit=False)\n profile.user = user\n \n if 'picture' in request.FILES:\n profile.picture = request.FILES['picture']\n profile.save()\n registered = True\n else:\n print(user_form.errors, profile_form.errors)\n else:\n user_form = UserForm()\n profile_form = UserProfileForm()\n return render(request, 'destination_dog/register.html', {'user_form': user_form, 'profile_form': profile_form, 'registered': registered})\n\n\ndef profile(request, username):\n try:\n user = User.objects.get(username=username)\n except User.DoesNotExist:\n return redirect('home')\n\n userprofile = UserProfile.objects.get_or_create(user=user)[0]\n\n form = UserProfileForm({'picture': userprofile.picture})\n\n\n dog_list = Dog.objects.filter(owner=userprofile)\n\n if request.method == 'POST':\n form = UserProfileForm(request.POST, request.FILES, instance=userprofile)\n if form.is_valid():\n form.save(commit=True)\n return redirect('user_profile', user.username)\n else:\n print(form.errors)\n\n return render(request, 'destination_dog/userprofile.html',\n {'userprofile': userprofile, 'user': user, 'form': form, 'dog': dog_list})\n\ndef dogprofile(request, dog):\n \n context_dict = {}\n \n try: \n dogprofile = User.objects.get(dog=dog)\n\n context_dict['dog'] = dogprofile\n \n except Dog.DoesNotExist:\n context_dict['dog'] = None\n \n return render(request, 'destination_dog/dogprofile.html', context_dict)\n\n@login_required\ndef add_dog(request, username):\n\n user = User.objects.get(username=request.user)\n profile = user.userprofile\n\n form = AddDogForm()\n\n if request.method == 'POST':\n form = AddDogForm(request.POST)\n if form.is_valid():\n\n dog = form.save(commit=False)\n dog.owner = profile\n\n if 'picture' in request.FILES:\n dog.picture = request.FILES['picture']\n\n dog.save()\n return home(request)\n else:\n print(form.errors)\n\n context_dict = {'form': form}\n return render(request, 'destination_dog/add_dog.html', context=context_dict)\n\n@ login_required\ndef list_profiles(request):\n userprofile_list = UserProfile.objects.all()\n\n return render(request, 'destination_dog/list_all_user_profiles.html', {'userprofile_list': userprofile_list})\n\n@ login_required\ndef deactivate_profile(request):\n\n user = request.user\n user.is_active= False\n user.save()\n context_dict = 'Profile successfully deactivated'\n\n # messages.success(request, 'Profile successfully deactivated.')\n # return redirect('home')\n\n return render(request, 'destination_dog/deactivate_profile.html', context=context_dict)\n","sub_path":"destination_dog/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":11128,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"5722567","text":"class Solution(object):\n # 在二维矩阵中查找一个数据,返回bool值\n # 矩阵有如下特征:\n # 每一行数据都是排好序的\n # 每一行第一个数据都比前一行最后一个数据大\n\n # def searchMatrix(self, matrix, target):\n # \"\"\"\n # :type matrix: List[List[int]]\n # :type target: int\n # :rtype: bool\n # \"\"\"\n # m = len(matrix)\n # n = len(matrix[0])\n\n # for i in range(m):\n # if matrix[i][0] <= target <= matrix[i][n - 1]:\n # left = 0\n # right = n - 1\n # while left <= right:\n # middle = (left + right) // 2\n # if matrix[i][middle] > target:\n # right = middle - 1\n # elif matrix[i][middle] < target:\n # left = middle + 1\n # else:\n # return True\n # return False\n\n def searchMatrix(self, matrix, target):\n \"\"\"\n :type matrix: List[List[int]]\n :type target: int\n :rtype: bool\n \"\"\"\n i = 0\n j = len(matrix[0]) - 1\n\n while i < len(matrix) and j >= 0:\n if matrix[i][j] == target:\n return True\n elif matrix[i][j] > target:\n j -= 1\n else:\n i += 1\n return False\n \nif __name__ == \"__main__\":\n cl = Solution()\n print(cl.searchMatrix([[1, 3, 5, 7],\n [10, 11, 16, 20],\n [23, 30, 34, 50]], 3))\n","sub_path":"74.Search_a_2D_Matrix/74.Search_a_2D_Matrix.py","file_name":"74.Search_a_2D_Matrix.py","file_ext":"py","file_size_in_byte":1594,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"133975279","text":"from rest_framework import status\nfrom rest_framework.response import Response\nfrom rest_framework.views import APIView\nfrom alipay import AliPay\n\nfrom contents.pay_by_alipay.contents import *\nfrom orders.models import OrderModel\nfrom payment.models import Payment\n\nalipay = AliPay(\n appid=ALIPAY_APP_ID,\n app_notify_url=None,\n app_private_key_path=APP_PRIVATE_KEY_PATH,\n alipay_public_key_path=ALIPAY_PUBLIC_KEY_PATH,\n sign_type='RSA2',\n debug=ALIPAY_DEBUG\n )\n\n\n# noinspection PyUnresolvedReferences\nclass PaymentView(APIView):\n \"\"\"支付宝支付\"\"\"\n # 1. 必须登陆\n # 2. 提供支付宝接口及对应参数\n # 3. 返回响应\n def get(self, request, order_id):\n user = request.user\n try:\n order = OrderModel.objects.get(order_id=order_id,\n user=user,\n status=OrderModel.ORDER_STATUS_ENUM['UNPAID'])\n except OrderModel.DoesNotExist:\n return Response({\"message\": \"订单数据有误!\"})\n\n order_string = alipay.api_alipay_trade_page_pay(\n out_trade_no=order_id,\n total_amount=str(order.total_amount), # 将浮点数转换为字符串\n subject='测试订单',\n return_url='http://www.meiduo.site:8080/pay_success.html',\n )\n alipay_url = ALIPAY_GATEWAY_URL + order_string\n return Response({\"alipay_url\": alipay_url})\n\n\n\nclass PaymentStatusView(APIView):\n \"\"\"支付后的页面回调\"\"\"\n def put(self, request):\n data = request.query_params.dict()\n signature = data.pop(\"sign\")\n if alipay.verify(data, signature):\n order_id = data.get(\"out_trade_no\")\n trade_id = data.get(\"trade_no\")\n Payment.objects.create(\n order_id = order_id,\n trade_id = trade_id\n )\n return Response({\"trade_id\": trade_id})\n return Response({\"message\": \"支付失败!\"}, status=status.HTTP_400_BAD_REQUEST)\n","sub_path":"mall/apps/payment/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2078,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"67079296","text":"'''\nВерсия python 3.8.10\nиспользуемые версии модулей python:\npandas==1.3.4\nnumpy==1.20.2\nmatplotlib==3.4.1\ntensorflow==2.8.0\nkeras==2.8.0\nscikit-learn==0.22.2\ntorch==1.11.0\ntorchbnn==1.2\nscipy==1.4.1\n'''\n\n#импорт необходимых модулей\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport torchbnn as bnn\nimport matplotlib.pyplot as plt\nimport array\nimport tensorflow as tf\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport os\nfrom sklearn.model_selection import train_test_split\nfrom tensorflow.keras.utils import to_categorical\nfrom scipy.special import softmax as sci_softmax\n\n#объявление служебных переменных и констант\ndf_name = '../sign_dump_BNN.csv'\nnumber_of_features_1 = 144\nmax_type = 22\nnumber_of_neurans_1 = 30\nmodel_name = '../BNN_models/BNN_model_'\nid_user='id_user'\nusers = [1,8,9,10,11,14,15,17,18,19,20,22]\n\n#загрузка датасета\ndf = pd.read_csv(df_name)\ndf = df.drop(df.columns[0], axis=1) #удаление служебного безымянного столбца\n\n#получение результата предсказания в softmax encoded виде\ndef get_predict(test_df):\n #перечень распознаваемых пользователей\n softmax = nn.Softmax(dim=1)\n\n result = np.zeros((test_df.shape[0], 23))\n \n #для исключения влияния случайных факторов распознавание повторяется 50 раз\n for repeat in range(50):\n #проверка данных на каждом из пользователе\n for i in users: \n data = test_df\n data_tensor=torch.from_numpy(data).float()\n model = torch.load(model_name+str(i)+'.h5')\n outputs = model(data_tensor)\n prob_array = softmax(outputs).detach().numpy()\n\n #запись результата в итоговый массив\n for itr in range(test_df.shape[0]):\n result[itr][i] += prob_array[itr][1]\n\n #приведение результата в softmax encoded вид\n result = sci_softmax(result, axis=1)\n return result\n\n#вычисление значения потерь и точности предсказания относительно верных ответов\ndef evaluate(prediction, answers): \n cross_entropy_loss = nn.CrossEntropyLoss()\n \n correct = (np.argmax(prediction, axis=1) == np.argmax(answers, axis=1)).sum()\n accuracy = correct / prediction.shape[0]\n \n pred_tensor = torch.from_numpy(prediction).float()\n ans_tensor = torch.from_numpy(answers).float()\n loss = cross_entropy_loss(pred_tensor, ans_tensor)\n loss = loss.item()\n\n return loss, accuracy\n\n#определение модели нейронной сети\nmodel = nn.Sequential(\n bnn.BayesLinear(prior_mu=0, prior_sigma=0.01, in_features=144, out_features=300), \n nn.ReLU(), \n bnn.BayesLinear(prior_mu=0, prior_sigma=0.01, in_features=300, out_features=2))\n\n#подготовка данных для тестирования\ntest_df = df[df['id_user'].isin(users)]\nansw = test_df['id_user'].to_numpy()\nansw = to_categorical(answ, 23)\ntest_df = test_df.drop(columns = 'id_user')\ntest_df = test_df.to_numpy()\n\n#тестирование обученных моделей\nfor i in range (0,31):\n model_name = '../BNN_models/BNN_model_'+str(i)+'/'\n pred = get_predict(test_df)\n print(evaluate(pred, answ))","sub_path":"AdvAttacks/Evaluate_BNNs.py","file_name":"Evaluate_BNNs.py","file_ext":"py","file_size_in_byte":3591,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"567549340","text":"# Forms a pyramid\n# Takes user input as pyramid's height\n\nfrom cs50 import get_int\n\n\ndef main():\n # Prompts user for a positive number\n while True:\n n = get_int('Height: ')\n if n > 0 and n < 9:\n break\n # For spaces and hashes to build the pyramid\n for i in range(n):\n for j in range(1, n+1):\n if i + j < n:\n print(' ', end='')\n else:\n print('#', end='')\n # Prints a space with each iteration\n print(' ', end='')\n # For the other half of the pyramid\n for a in range(i+1):\n print('#', end='')\n print()\n\n\n# Executes main function\nif __name__ == \"__main__\":\n main()\n","sub_path":"sentimental/mariomore.py","file_name":"mariomore.py","file_ext":"py","file_size_in_byte":708,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"518483213","text":"from flask import Flask, request, Response, jsonify\nfrom flask_cors import CORS\nimport requests\nimport cv2\nimport base64\nimport numpy\nimport TapWork, recolour, resize, contours, map_downloader\n\nAPI_KEY = 'AgqByPum4K6T5wlV3oIAhSDvFHVRuoPs6cwipRdvprWtmvqld0poyLI54AP0e6HI'\n\napp = Flask(__name__)\ncors = CORS(app)\n\ndef toBase64(image):\n# image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)\n _, buffer = cv2.imencode('.png', image)\n png_as_text = base64.b64encode(buffer).decode('utf-8')\n return png_as_text\n\ndef process(image,max_size=200,taps=5):\n resized_image = resize.resize(image,max_size)\n height, width, _ = resized_image.shape\n recoloured_image = recolour.find_silver(resized_image)\n houses = contours.get_contour_nodes(recoloured_image)\n tap_locations = TapWork.greedy_brute(houses,taps,(height,width))\n image = TapWork.draw_network(houses,tap_locations,resized_image,display=False) \n image = cv2.imread('figureTaps.png')\n return toBase64(image)\n\n@app.route('/giveLocation', methods=['GET'])\ndef giveLocation():\n lon = request.args.get('long')\n lat = request.args.get('lat')\n max_size = request.args.get('size')\n taps = request.args.get('taps')\n print(lon,lat)\n if lon is None or lat is None:\n response = Response()\n response.status_code = 400\n return response\n response = map_downloader.download_patch((lat,lon),API_KEY)\n image_array = numpy.asarray(bytearray(response.content), dtype=numpy.uint8)\n map_image = cv2.imdecode(image_array, -1)\n if max_size is not None and taps is not None:\n base64_payload = process(map_image,max_size=max_size,taps=taps)\n elif max_size is not None: \n base64_payload = process(map_image,max_size=max_size)\n elif taps is not None:\n base64_payload = process(map_image,taps=taps)\n else:\n base64_payload = process(map_image)\n\n return jsonify(image=base64_payload)\n\nif __name__ == '__main__':\n app.run(port=25565,host='0.0.0.0')\n","sub_path":"api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":1987,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"13754829","text":"#!/bin/py\n# -*-coding:utf-8-*-\n' 说明 '\n_author_ = 'zl'\nimport sys\nfrom tkinter import Button,mainloop\n\nf=(lambda x,y:x if x 0):\n for inp_tokens, inp_length, label, label_output, prev_output_tokens in zip(\n [sampled['net_input']['src_tokens'], sampled['net_target']['src_tokens']],\n [sampled['net_input']['src_lengths'], sampled['net_target']['src_lengths']],\n [0.0,1.0],\n [1.0,0.0],\n [sampled['net_target']['prev_output_tokens'], sampled['net_input']['prev_output_tokens']],\n ):\n if (recon_weight > 0):\n decoder_out, extra, logits = model(inp_tokens,inp_length,prev_output_tokens, tgt_lang = label)\n loss, _ = self.compute_loss(model, (decoder_out, extra), inp_tokens, reduce=reduce)\n tot_recon_loss = tot_recon_loss + forward_weight[int(label)] * loss\n if (cycle_weight > 0):\n decoder_out, extra, logits = model(inp_tokens,inp_length, prev_output_tokens, tgt_lang = label_output)\n src_tokens= torch.argmax(decoder_out, 2)\n src_lengths = torch.ones(src_tokens.size()[0])\n for i in range(0, src_tokens.size()[0]):\n for j in range(src_tokens.size()[1]-1,0,-1):\n if (src_tokens[i][j] != 2):\n src_lengths[i] = j + 1\n break\n decoder_out, extra, _ = model(src_tokens,src_lengths,prev_output_tokens, tgt_lang = label)\n loss, _ = self.compute_loss(model, (decoder_out, extra), inp_tokens, reduce=reduce)\n tot_cycle_loss = tot_cycle_loss + forward_weight[int(label)] * loss\n\n\n\n sample_size = sample['net_target']['src_tokens'].size(0) if self.sentence_avg else sample['ntokens']\n accuracy = accuracy/tot_sz\n tot_loss = 2.0 * (tot_trans_loss + disc_weight*tot_disc_loss + recon_weight*tot_recon_loss + cycle_weight*tot_cycle_loss)\n logging_output = {\n 'loss': tot_loss.data,\n 'trans_loss': tot_trans_loss.data,\n 'cycle_loss': tot_cycle_loss.data,\n 'recon_loss': tot_recon_loss.data,\n 'accuracy': accuracy.data,\n 'disc_loss':tot_disc_loss.data,\n 'nll_loss':tot_nll_loss.data,\n 'ntokens': sample['ntokens'],\n 'nsentences': sample['net_target']['src_tokens'].size(0),\n 'sample_size': sample_size,\n }\n return tot_loss, sample_size, logging_output\n\n def compute_loss(self, model, net_output, sample, reduce=True):\n lprobs = model.get_normalized_probs(net_output, log_probs=True)\n lprobs = lprobs.view(-1, lprobs.size(-1))\n target = model.get_targets(sample, net_output).view(-1, 1)\n loss, nll_loss = label_smoothed_nll_loss(\n lprobs, target, self.eps, ignore_index=self.padding_idx, reduce=reduce,\n )\n return loss, nll_loss\n\n @staticmethod\n def reduce_metrics(logging_outputs) -> None:\n \"\"\"Aggregate logging outputs from data parallel training.\"\"\"\n loss_sum = utils.item(sum(log.get('loss', 0) for log in logging_outputs))\n trans_loss_sum = utils.item(sum(log.get('trans_loss', 0) for log in logging_outputs))\n recon_loss_sum = utils.item(sum(log.get('recon_loss', 0) for log in logging_outputs))\n cycle_loss_sum = utils.item(sum(log.get('cycle_loss', 0) for log in logging_outputs))\n ntokens = utils.item(sum(log.get('ntokens', 0) for log in logging_outputs))\n disc_loss_sum = utils.item(sum(log.get('disc_loss', 0) for log in logging_outputs))\n sample_size = utils.item(sum(log.get('sample_size', 0) for log in logging_outputs))\n accuracy_sum = utils.item(sum(log.get('accuracy', 0) for log in logging_outputs))\n nll_loss_sum = utils.item(sum(log.get('nll_loss', 0) for log in logging_outputs))\n\n metrics.log_scalar('accuracy', accuracy_sum / len(logging_outputs), len(logging_outputs), round=3)\n metrics.log_scalar('loss', loss_sum / sample_size / math.log(2), sample_size, round=3)\n metrics.log_scalar('trans_loss', trans_loss_sum / sample_size / math.log(2), sample_size, round=3)\n metrics.log_scalar('disc_loss', disc_loss_sum / sample_size / math.log(2), sample_size, round=3)\n metrics.log_scalar('cycle_loss', cycle_loss_sum / sample_size / math.log(2), sample_size, round=3)\n metrics.log_scalar('recon_loss', recon_loss_sum / sample_size / math.log(2), sample_size, round=3)\n metrics.log_scalar('nll_loss', nll_loss_sum / ntokens / math.log(2), ntokens, round=3)\n metrics.log_derived('ppl', lambda meters: utils.get_perplexity(meters['nll_loss'].avg))\n\n @staticmethod\n def logging_outputs_can_be_summed() -> bool:\n \"\"\"\n Whether the logging outputs returned by `forward` can be summed\n across workers prior to calling `reduce_metrics`. Setting this\n to True will improves distributed training speed.\n \"\"\"\n return True\n","sub_path":"fairseq/criterions/label_smoothed_cross_entropy.py","file_name":"label_smoothed_cross_entropy.py","file_ext":"py","file_size_in_byte":9659,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"468856176","text":"\"\"\"\nSet of user controllers.\nclassical CRUD operations\n\"\"\"\n\nfrom aiohttp import web\n\nfrom dao.user_dao import get_id, get_all, insert_user, change_user, delete_user\n\nasync def get_user_by_id(request):\n \"\"\"\n user retriever, based on technical id\n :param request: aiohttp request\n :return: json format of the user data retrieved or json description of the error\n \"\"\"\n # get id set by the user into the request\n id = int(request.match_info['id'])\n\n # execute dao statement\n try:\n res = await get_id(id=int(id))\n except Exception as e:\n print(e)\n return web.json_response({'error': str(e)}, status=500)\n\n # nothing has been found\n if not res:\n return web.json_response({'error': \"User {} not found\".format(id)}, status=404)\n\n # success response\n return web.json_response(res)\n\n\nasync def get_all_users(request):\n \"\"\"\n retrieve all users registered\n :param request: aioihttp request\n :return: json format of the list of users retrieved or json description of the error\n \"\"\"\n\n # execute dao statement\n try:\n res = await get_all()\n except Exception as e:\n print(e)\n return web.json_response({'error': str(e)}, status=500)\n\n # success response\n return web.json_response(res)\n\n\nasync def create_user(request):\n \"\"\"\n crate a new user\n :param request: aioihttp request\n :return: json format of the new user id or json description of the error\n \"\"\"\n # data describing of the user to be created\n data = await request.json()\n\n # check of the data, we ensure required data are present, name\n name = data.get('name', '__missing__')\n if name == '__missing__':\n return web.json_response({'error': '\"name\" is a required field'})\n\n # check of the data type, we ensure required data type are correct present, name\n if not isinstance(name, str) or not len(name):\n return web.json_response({'error': '\"name\" must be a string with at least one character'})\n\n # check of the data type, if not age or age is zero we raise an error\n data['age'] = int(data.get('age', 0))\n if not data['age']:\n return web.json_response({'error': '\"age\" must be a present and greater than 0'})\n\n # execute dao statement\n try:\n new_id = await insert_user(data)\n except Exception as e:\n print(e)\n return web.json_response({'error': str(e)}, status=500)\n\n # success response\n return web.json_response({'id': new_id})\n\n\nasync def update_user(request):\n # data describing of the updation to be done, get back the id\n data = await request.json()\n\n # get id from the url\n user_id = int(request.match_info['id'])\n\n # check of the data type, we ensure required data type are correct present, name and age\n if not any([data.get('name', None), data.get('age', None)]):\n return web.json_response({'error': '\"name\" or \"age\" has to be provided.'})\n\n # execute dao statement\n try:\n await change_user(user_id, values={k:data[k] for k in ('name','age') if k in data.keys()})\n except Exception as e:\n print(e)\n return web.json_response({'error': str(e)}, status=500)\n\n # success response\n return web.json_response({'id': user_id})\n\n\nasync def remove_user(request):\n # get id from the url\n user_id = int(request.match_info['id'])\n\n # execute dao statement\n try:\n await delete_user(user_id)\n except Exception as e:\n print(e)\n return web.json_response({'error': str(e)}, status=500)\n\n # success response\n return web.json_response({'id': user_id})","sub_path":"controller/user.py","file_name":"user.py","file_ext":"py","file_size_in_byte":3605,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"271809286","text":"import pandas as pd\nfrom scipy.stats import mannwhitneyu\nimport statsmodels.sandbox.stats.multicomp\nfrom sklearn import metrics\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport plotly\nimport plotly.figure_factory as ff\n\n\ndef calc_raw_pvalues(exp_df, gene_list):\n \"\"\"\n Gets uncorrected p_values for whether a geneset is enriched in a structure.\n\n Parameters\n ----------\n exp_df: dataframe\n expression matrix: rows->genes ; columns->brain_areas\n gene_list: series\n list of gene symbols of interest\n Returns\n -------\n results\n a series of P-values for each brain area\n \"\"\"\n results = []\n for col in exp_df:\n X = exp_df[col][exp_df[col].index.isin(gene_list)]\n y = exp_df[col][~exp_df[col].index.isin(gene_list)]\n # make sure that you are comparing the gene list to all other genes\n # assert(X.shape[0] + y.shape[0] == exp_df.shape[0])\n results.append(mannwhitneyu(X, y, alternative='two-sided')[1])\n return pd.Series(results)\n\n\ndef calc_AUC_for_ranked_genelist(exp_df, gene_list):\n \"\"\"\n Calculates AUROC to determine whether genes of interest are expressed at\n levels greater than chance within the brain area\n\n Parameters\n ----------\n exp_df: dataframe\n expression matrix: rows->genes ; columns->brain_areas\n gene_list: series\n list of gene symbols of interest\n Returns\n -------\n results\n a series of AUC values for each brain area\n \"\"\"\n results = []\n for col in exp_df:\n y_true = exp_df[col].index.isin(gene_list)\n y_score = exp_df[col].values\n results.append(metrics.roc_auc_score(y_true, y_score))\n return pd.Series(results)\n\n\ndef make_ROC_plot(exp_df, brain_area, gene_list):\n \"\"\"\n Creates static ROC plot for genes of interest in specified brain area\n\n Parameters\n ----------\n exp_df: dataframe\n expression matrix: rows->genes ; columns->brain_areas\n brain_area: string\n name of brain area testing within\n gene_list: series\n list of gene symbols of interest\n Returns\n -------\n ax\n axis containing ROC plot\n \"\"\"\n y_true = exp_df[brain_area].index.isin(gene_list)\n y_score = exp_df[brain_area].values\n # sns.distplot(y_score)\n fpr, tpr, thresholds = metrics.roc_curve(y_true, y_score, pos_label=True)\n brainarea_auc = metrics.auc(fpr, tpr)\n\n plt.figure(figsize=(8, 6), dpi=80)\n ax = plt.gca()\n plt.plot(fpr, tpr, color='darkorange',\n label='ROC (area = {:0.6f})'.format(brainarea_auc))\n plt.plot([0, 1], [0, 1], color='navy', linestyle='--')\n plt.xlim([0.0, 1.0])\n plt.ylim([0.0, 1.05])\n plt.xlabel('False Positive Rate')\n plt.ylabel('True Positive Rate')\n plt.title('{} ROC'.format(brain_area))\n plt.legend(loc=\"lower right\")\n\n return ax\n\n\ndef make_dist_plot(exp_matrix, brain_area, gene_list):\n \"\"\"\n Plots the distributions of zscored levels of expression of genes of\n interest compared to the rest of genes\n\n Parameters\n ----------\n exp_df : dataframe\n expression matrix: rows->genes ; columns->brain_areas\n gene_list : series\n list of gene symbols of interest\n Returns\n -------\n\n \"\"\"\n brain_area_exp = exp_matrix.loc[:, brain_area].reset_index()\n brain_area_exp['In gene list'] = brain_area_exp.gene_symbol.isin(gene_list)\n g = sns.FacetGrid(brain_area_exp, row='In gene list', aspect=4)\n g.map(sns.distplot, brain_area, norm_hist=True, hist=True, rug=False)\n g.set_xlabels('Mean expression value')\n\n\ndef raster(gene_list, **kwargs):\n \"\"\"\n Creates a raster plot\n\n Parameters\n ----------\n gene_list: iterable\n a list of genes of interest\n color: string\n color of vlines\n Returns\n -------\n ax\n an axis containing the raster plot\n \"\"\"\n plt.figure(figsize=(8, 1), dpi=80)\n ax = plt.gca()\n\n i = 0\n for position, value in enumerate(gene_list[::-1]):\n # somehow this doesnt plot if == is switched to \"is\" ...?\n if value:\n plt.vlines(position, ymin=0, ymax=1, **kwargs)\n i += 1\n print('Number of genes of interest: {}'.format(i))\n plt.ylim(0, 1)\n plt.xlim(0, len(gene_list))\n ax.set_yticklabels([])\n return ax\n\n\ndef interactive_distplot(exp_df, brain_area, gene_list, disease_label=None, filename='Distplot with Normal Curve'):\n brain_area_exp = exp_df.loc[:, brain_area].reset_index()\n brain_area_exp['hit'] = brain_area_exp.gene_symbol.isin(gene_list)\n\n x1 = brain_area_exp[brain_area_exp['hit'] == True].loc[:, brain_area].values\n x2 = brain_area_exp[brain_area_exp['hit'] == False].loc[:, brain_area].values\n\n hist_data = [x1, x2]\n group_labels = ['{} hits'.format(disease_label), 'Background']\n # colors = ['#94F3E4', '#3A4750']\n\n rug_text_hits = brain_area_exp[brain_area_exp['hit'] == True].loc[:, 'gene_symbol']\n rug_text_background = brain_area_exp[brain_area_exp['hit'] == False].loc[:, 'gene_symbol']\n rug_text = [rug_text_hits, rug_text_background]\n\n fig = ff.create_distplot(hist_data, group_labels, bin_size=.25, curve_type='normal', rug_text=rug_text)#, colors=colors)\n plotly.offline.iplot(fig, filename=filename)\n\n\ndef generate_stats_table(exp_df, gene_list):\n \"\"\"\n Creates a table of summary stats for each brain area\n\n Parameters\n ----------\n exp_df : dataframe\n expression matrix: rows->genes ; columns->brain_areas\n gene_list : series\n list of gene symbols of interest\n Returns\n -------\n table\n dataframe with brain areas as index\n\n \"\"\"\n count = len(gene_list)\n n_genes_in_matrix = gene_list.isin(exp_df.index).sum()\n genes_not_found = gene_list[~gene_list.isin(exp_df.index)].values\n\n print('You submitted a gene list with {} genes.\\n\\\n{} of those genes are present in the HBA dataset.\\n\\\nGenes not found in our reference data: {}'.format(\n count, n_genes_in_matrix, genes_not_found))\n\n raw_pvalues = calc_raw_pvalues(exp_df, gene_list)\n corrected_p_vals = statsmodels.sandbox.stats.multicomp.multipletests(\n raw_pvalues, method=\"fdr_bh\")[1]\n corrected_p_vals = pd.Series(corrected_p_vals)\n auc = calc_AUC_for_ranked_genelist(exp_df, gene_list)\n table = pd.concat([raw_pvalues, corrected_p_vals, auc],\n keys=['raw p_values', 'corrected_p', 'AUC'], axis=1)\n table.set_index(exp_df.columns, inplace=True)\n return table.sort_values('AUC', ascending=False)\n","sub_path":"HBA_analysis.py","file_name":"HBA_analysis.py","file_ext":"py","file_size_in_byte":6520,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"507608156","text":"from django.contrib.gis.db import models\nfrom django.db.models import Q\nfrom django.db.models.query import QuerySet\n\nclass GroupMixin(object):\n \n def get_objects_with_counts(self, user, ordering='name'):\n \n sql = '''select distinct g.id, g.name, g.description, g.last_updated, g.user_id, \n s.processed_maps_count, a.audio_count, p.photo_count, m.marker_count \n from \n account_%s g left join \n account_userauthorityobject pu on g.id = pu.object_id left join \n (select project_id, count(id) as processed_maps_count from uploads_scan \n group by project_id) s \n ON (g.id = s.project_id) \n left join \n (select project_id, count(id) as audio_count from uploads_audio \n group by project_id) a \n ON (g.id = a.project_id) \n left join \n (select project_id, count(id) as photo_count from uploads_photo \n group by project_id) p \n ON (g.id = p.project_id) \n left join \n (select project_id, count(id) as marker_count from overlays_marker \n group by project_id) m \n ON (g.id = m.project_id)\n ''' % str(self.model.__name__).lower()\n if user is not None: #only accessible to superusers\n sql = sql + ' where g.user_id = %s or pu.user_id = %s' \\\n % (user.id, user.id)\n if ordering == 'name':\n sql = sql + ' order by g.name'\n elif ordering == 'id': \n sql = sql + ' order by g.id'\n return list(self.model.objects.raw(sql))\n \n def get_objects(self, user):\n q = self.model.objects.select_related('owner')\n if user is not None: #only accessible to superusers\n filter_expression = Q(owner=user) | Q(users__user=user)\n q = q.filter(filter_expression)\n q = q.distinct()\n return q.order_by('name')\n\n\nclass ProjectMixin(GroupMixin):\n def to_dict_list(self, include_auth_users=False, include_processed_maps=False,\n include_markers=False, include_audio=True, include_photos=False):\n dict_list = []\n \n # similar to p.to_dict(), but queries optimized at the list level \n # rather than at the object level:\n from localground.uploads.models import Scan, Audio, Photo\n from localground.overlays.models import Marker\n scan_set, audio_set, photo_set, marker_set = None, None, None, None\n project_ids = [p.id for p in self]\n if len(project_ids) > 0:\n if include_processed_maps:\n scan_set = Scan.objects.by_projects(project_ids)\n if include_audio:\n audio_set = Audio.objects.by_projects(project_ids)\n if include_photos:\n photo_set = Photo.objects.by_projects(project_ids)\n if include_markers:\n marker_set = Marker.objects.by_projects(project_ids)\n \n def get_list(p, obj_set):\n arr = []\n if obj_set is not None:\n for o in obj_set:\n if o.project.id == p.id:\n arr.append(o.to_dict())\n return arr\n \n \n for p in self:\n e = p.to_dict()\n \n e.update({\n 'processed_maps': get_list(p, scan_set), \n 'photos': get_list(p, photo_set), \n 'audio': get_list(p, audio_set), \n 'markers': get_list(p, marker_set) \n })\n dict_list.append(e)\n \n return dict_list\n \n \nclass ProjectQuerySet(QuerySet, ProjectMixin):\n pass\n\nclass ProjectManager(models.GeoManager, ProjectMixin):\n def get_query_set(self):\n return ProjectQuerySet(self.model, using=self._db)\n \n \nclass ViewMixin(GroupMixin):\n def to_dict_list(self):\n return []\n \nclass ViewQuerySet(QuerySet, ViewMixin):\n pass\n\nclass ViewManager(models.GeoManager, ViewMixin):\n def get_query_set(self):\n return ViewQuerySet(self.model, using=self._db) \n ","sub_path":"account/managers.py","file_name":"managers.py","file_ext":"py","file_size_in_byte":4125,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"612986724","text":"teams = [\"Raptors\",\"Leafs\",\"Jays\",\"TFC\",\"Argos\",\"Rock\"]\nfileHandle = open(\"answers.txt\", \"w+\")\nfileHandle.write(\"Teams I Like:\\n\")\nstopProgram = False\nnumAnswers = 0\nfor team in teams:\n answer = \"\"\n while not((answer == \"yes\") or (answer == \"no\")):\n print(\"Please answer yes or no (or type stop to end the program)\")\n answer = input(\"Do you like the %s? \" %(team))\n if answer == 'stop':\n stopProgram = True\n break\n elif((answer == 'yes') or (answer == 'no')):\n numAnswers += 1\n fileHandle.write(\"Team %s, answer %s\\n\" %(team, answer))\n if stopProgram == True:\n break\nfileHandle.close()\nprint(\"You have answered %d questions!\" % numAnswers)\n","sub_path":"summative/Program Listing A reworked.py","file_name":"Program Listing A reworked.py","file_ext":"py","file_size_in_byte":678,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"210776544","text":"from string import Template\n\n\ndef parse_response(responseLines):\n responseDic = {}\n for line in responseLines:\n words = line.split(': ')\n if len(words) != 2:\n continue\n responseDic[words[0].strip()] = words[1].strip()\n return responseDic\n\n\ndef generate_request(requestDic, method, url):\n request = method + ' ' + url\n for key, value in requestDic.items():\n request += str(key) + ': ' + str(value) + '\\r\\n'\n request += '\\r\\n'\n return request.encode('utf-8')\n","sub_path":"rtsp.py","file_name":"rtsp.py","file_ext":"py","file_size_in_byte":517,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"366517345","text":"class Solution:\r\n def trap(self, height: List[int]) -> int:\r\n l2r = []\r\n left_max = 0\r\n for h in height:\r\n left_max = max(left_max, h)\r\n l2r.append(left_max)\r\n \r\n r2l = []\r\n right_max = 0\r\n for h in reversed(height):\r\n right_max = max(right_max, h)\r\n r2l.insert(0, right_max)\r\n \r\n return sum(min(lh, rh) - h for lh, rh, h in zip(l2r, r2l, height))\r\n\r\nclass Solution:\r\n def trap(self, height: List[int]) -> int:\r\n if not height:\r\n return 0\r\n leftmax, rightmax = height[0], height[-1]\r\n left, right = 0, len(height) - 1\r\n res = 0\r\n while left < right:\r\n if height[left] < height[right]:\r\n leftmax = max(leftmax, height[left])\r\n res += leftmax - height[left]\r\n left += 1\r\n else:\r\n rightmax = max(rightmax, height[right])\r\n res += rightmax - height[right]\r\n right -= 1\r\n return res\r\n","sub_path":"solutions/42-trapping-rain-water/trapping-rain-water.py","file_name":"trapping-rain-water.py","file_ext":"py","file_size_in_byte":1057,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"599232126","text":"import random\n\nclass Dealer_card:\n \"\"\"Dealer_card class is used to 'Throw' a card\n so that the game can start, continue and end the game.\"\"\"\n \"\"\"Attributes:\n card and cards\"\"\"\n\n def __init__(self):\n \"\"\"The class constructor.\n\n Args: \n self (Dealer_card): an instance of Dealer_card.\"\"\"\n\n # self.cards is the list of the 13 possible cards that the dealer can throw.\n self.cards = [1, 2, 3, 4, 5, 6,\n 7, 8, 9, 10, 11, 12, 13]\n # declared player response to get higher or lower inputs\n self.player_response = \"\"\n\n def get_points(self, next_card, current_card):\n \"\"\"The get_points method calculates and returns the total points for the current game. \n It goes from 1 point up until 13 points\n \n Args:\n self (Dealer_card): an instance of Dealer_card.\n next_card: the value of the next card from the throw_card\n current_card: the value of the current card from the throw_card\n Return:\n points: returning the points for getting the result from the comparison\n \"\"\"\n\n points = 0\n\n #evaluating response from the user\n if (self.player_response == \"l\" and next_card < current_card) or (self.player_response == \"h\" and next_card > current_card):\n points = 100\n elif (self.player_response == \"l\" and next_card > current_card) or (self.player_response == \"h\" and next_card < current_card):\n points = -75\n elif next_card == current_card:\n print(\"Current Card and Next Card is equal. No score added.\")\n else:\n print(\"Invalid Response! Please enter 'h' or 'H' for Highest or 'l' or 'L' for Lowest\")\n \n return points\n\n def throw_card(self):\n \"\"\"The throw_card method randomly choose a value from a list called 'cards'. \n\n Args:\n self (Dealer_card): an instance of Dealer_card. \n Return:\n card: return the randomly choosen card and use as playing cards\"\"\"\n \n # Randomly choose a card from the cards list\n card = random.choice(self.cards)\n\n return card","sub_path":"hilo/game/next_card.py","file_name":"next_card.py","file_ext":"py","file_size_in_byte":2203,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"192604406","text":"import re\nimport os\nimport functools\nfrom colour_printing.style import setting\nfrom colour_printing.custom.config import Config\n\n\nclass PrintMeError(Exception):\n def __init__(self, message):\n super().__init__(message)\n\n\ndef level_wrap(func):\n @functools.wraps(func)\n def wrap(self, *args, **kwargs):\n if self.switch is False:\n return\n if func.__name__ in self.filter:\n return\n return func(self, *args, **kwargs)\n\n return wrap\n\n\nclass PrintMe(object):\n def __init__(self, template: str, config_filename: str = None):\n self.term = re.findall(r'(?<=\\{)[^}]*(?=\\})+', template)\n if \"message\" not in self.term:\n raise PrintMeError('\\n [*]Tip:: template muse have {message} ! ')\n self.__term_wrap = {i: \"{%s}{%s}{%s}\" % (i + '0', i, i + '1') for i in self.term}\n self.template = template.format(**self.__term_wrap)\n self.box = {}\n self.default = {}\n # switch\n self.switch = True\n self.filter = []\n # style config\n if not config_filename:\n config_filename = 'colour_printing_config'\n self.config = Config(self, os.getcwd())\n self.config.from_pyfile(config_filename)\n\n def set_config(self):\n for k, v in self.config.items():\n default = self.default[k] = {}\n style = self.box[k] = {}\n for t in self.term:\n default.update({t: v[t].pop(\"DEFAULT\", \"\")})\n sett = setting(**v[t])\n style.update({f'{t}0': sett[0], f'{t}1': sett[1]})\n\n\n def show(self, level, *args, **kwargs):\n style = self.box[level]\n default = self.default[level]\n data = {}\n for i in self.term:\n data[i] = kwargs.pop(i, default[i]())\n data.update(style)\n data['message'] = \" \".join([str(i) for i in args])\n print(self.template.format(**data), sep=kwargs.get('sep', \" \"), end=kwargs.get('end', \"\\n\"),\n file=kwargs.get('file', None))\n\n @level_wrap\n def info(self, *args, **kwargs):\n self.show('INFO', *args, **kwargs)\n\n @level_wrap\n def debug(self, *args, **kwargs):\n self.show('DEBUG', *args, **kwargs)\n\n @level_wrap\n def error(self, *args, **kwargs):\n self.show('ERROR', *args, **kwargs)\n\n @level_wrap\n def warn(self, *args, **kwargs):\n self.show('WARN', *args, **kwargs)\n\n @level_wrap\n def success(self, *args, **kwargs):\n self.show('SUCCESS', *args, **kwargs)\n","sub_path":"colour_printing/custom/printme.py","file_name":"printme.py","file_ext":"py","file_size_in_byte":2523,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"560251123","text":"#按c保存图片,按q退出\nimport cv2\ncap = cv2.VideoCapture(1)\n# cap.set(3,1600) #设置分辨率\n# cap.set(4,1200)\ncap.set(15, -6)\ncap.set(10, -64)\ncap.set(11, 64)\n\n# print(cap.get(15))#-1.0 曝光\n# print(cap.get(14))# 0 增益\n# print(cap.get(13))# 0 图像的色相\n# print(cap.get(12))#64.0 图像的饱和度\n# print(cap.get(11))#32.0 图像的对比度\n# print(cap.get(10))# 0 图像的亮度\n\n\n\n# cap.set(3,1280) #设置分辨率跑一趟hi哦那\n# cap.set(4,960)\ncap.set(3,2592) #设置分辨率\ncap.set(4,1944)\n# cap.set(15, 0.01)\n\n\n\n\n'''\n设置曝光\nhttps://blog.csdn.net/zmdsjtu/article/details/72864828\n\n\nhttps://codeday.me/bug/20171101/90657.html\n> 1CV_CAP_PROP_POS_FRAMES接下来要解码/捕获的帧的基于0的索引。\n> 2CV_CAP_PROP_POS_AVI_RATIO视频文件的相对位置\n> 3CV_CAP_PROP_FRAME_WIDTH视频流中的帧的宽度。\n> 4CV_CAP_PROP_FRAME_HEIGHT视频流中帧的高度。\n> 5CV_CAP_PROP_FPS帧速率。\n> 6CV_CAP_PROP_FOURCC编解码器的4个字符代码。\n> 7CV_CAP_PROP_FRAME_COUNT视频文件中的帧数。\n> 8CV_CAP_PROP_FORMAT retrieve()返回的Mat对象的格式。\n> 9CV_CAP_PROP_MODE指示当前捕获模式的后端特定值。\n> 10CV_CAP_PROP_BRIGHTNESS图像的亮度(仅适用于相机)。\n> 11CV_CAP_PROP_CONTRAST图像的对比度(仅适用于相机)。\n> 12CV_CAP_PROP_SATURATION图像的饱和度(仅适用于相机)。\n> 13CV_CAP_PROP_HUE图像的色相(仅适用于相机)。\n> 14CV_CAP_PROP_GAIN图像的增益(仅适用于相机)。\n> 15CV_CAP_PROP_EXPOSURE曝光(仅适用于相机)。\n> 16CV_CAP_PROP_CONVERT_RGB指示图像是否应转换为RGB的布尔标志。\n> 17CV_CAP_PROP_WHITE_BALANCE目前不支持\n> 18CV_CAP_PROP_RECTIFICATION立体摄像机的校正标志(注意:目前仅支持DC1394 v 2.x后端)\n'''\n\n\n\n\nwin = cv2.namedWindow('capture', flags=0)\n# flags为0表示窗口可以用鼠标来改变大小,此时显示的图像也跟着窗口大小变化,需要注意的是它可能会导致图像的变\n\n# prefix = input('前缀,eg: size1_>>>')\n# afterfix = input('后缀,eg: .bmp>>>')\n\nprefix = 'img'\nafterfix = '.bmp'\n\nwhile(1):\n # get a frame\n ret, frame = cap.read()\n # show a frame\n # cv2.imshow(\"capture\", frame)\n cv2.imshow(\"capture\", frame)\n # if cv2.waitKey(1) & 0xFF == ord('n'):\n # prefix = input('前缀,eg: size1_>>>')\n # afterfix = input('后缀,eg: .bmp>>>')\n if cv2.waitKey(1) & 0xFF == ord('c'):\n name = input(\"Img_name,eg: 1>>>\")\n # name = name + '.png'\n name = prefix + name + afterfix\n cv2.imwrite(name, frame)\n # break\n if cv2.waitKey(1) & 0xFF == ord('q'):\n # cv2.imwrite(\"fangjian2.jpeg\", frame)\n break\ncap.release()\ncv2.destroyAllWindows()\n\n","sub_path":"funpython/ocr/pygetpic.py","file_name":"pygetpic.py","file_ext":"py","file_size_in_byte":2736,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"605807806","text":"# -*- coding: utf-8 -*-\nimport sys\nimport smtplib\nfrom datetime import datetime\nfrom datetime import date\nfrom dateutil import tz\nfrom email.mime.text import MIMEText\nfrom email.header import Header\nfrom email.utils import formataddr\nimport pandas as pd\nimport numpy as np\nfrom data import conf\nimport requests\n\ndef days_between(d1, d2):\n d1 = datetime.strptime(d1, \"%Y-%m-%d\")\n d2 = datetime.strptime(d2, \"%Y-%m-%d\")\n return abs((d2 - d1).days)\n\ndef utc_to_est(utc_timestamp):\n from_zone = tz.gettz('UTC')\n to_zone = tz.gettz('EST')\n utc_time = datetime.fromtimestamp(utc_timestamp)\n utc_time = utc_time.replace(tzinfo=from_zone)\n local_time = utc_time.astimezone(to_zone)\n return local_time.strftime('%Y-%m-%d %H:%M:%S')\n\ndef ord(n):\n return str(n)+(\"th\" if 4 <= n%100 <= 20 else {1:\"st\",2:\"nd\",3:\"rd\"}.get(n%10, \"th\"))\n\ndef summarize_weather(list_weather):\n weather_cnt = dict()\n for value in list_weather:\n cnt = weather_cnt.get(value, 0)\n cnt += 1\n weather_cnt[value] = cnt\n max_cnt = -1\n weather_summary = ''\n for v in weather_cnt:\n if weather_cnt[v] > max_cnt:\n max_cnt = weather_cnt[v]\n weather_summary = v\n return weather_summary\n\nclass FamilyReport(object):\n\n def __init__(self):\n pass\n\n def generate_email(self):\n pass\n\n def get_exchange_rate(self):\n exchange_rate_url = 'https://api.exchangeratesapi.io/latest?'\n payload = {'base': 'CNY'}\n exchange_rate_r = requests.get(exchange_rate_url, params=payload)\n exchange_rate_r.raise_for_status() # If not OK (200), raise exception\n res = exchange_rate_r.json()\n date_calculated = res['date']\n CAD_rate = 1.0 / res['rates']['CAD'] * 100\n USD_rate = 1.0 / res['rates']['USD'] * 100\n\n text = '''\n

Exchange rate

\n

100 CAD = {cad_rate:.2f} CNY

\n

100 USD = {usd_rate:.2f} CNY

\n

The above information is provided by European Central Bank, updated on {date}.

\n '''.format(cad_rate=CAD_rate, usd_rate=USD_rate, date=date_calculated)\n return text\n\n def get_weather(self):\n payload = {'id': conf.city_id,\n 'appid': conf.weather_app_id,\n 'units': 'metric',\n }\n weather_url = 'http://api.openweathermap.org/data/2.5/forecast?'\n weather_response = requests.get(weather_url, params=payload)\n weather_response.raise_for_status() # If not 200, raise exception\n res = weather_response.json()\n weather_of_date = dict()\n for item in res['list']:\n str_time = utc_to_est(item['dt'])\n date_forcasted = str_time.split(\" \")[0]\n temp = round(item['main']['temp'], 1)\n weather = item['weather'][0]['main'] + \" (\" + item['weather'][0]['description'] + \")\"\n if date_forcasted not in weather_of_date:\n weather_of_date[date_forcasted] = {'min_temp': temp,\n 'max_temp': temp,\n 'weather': [weather]}\n else:\n weather_of_date[date_forcasted]['min_temp'] = min(temp,\n weather_of_date[date_forcasted]['min_temp'])\n weather_of_date[date_forcasted]['max_temp'] = max(temp,\n weather_of_date[date_forcasted]['max_temp'])\n weather_of_date[date_forcasted]['weather'].append(weather)\n for k, v in weather_of_date.items():\n v['weather'] = summarize_weather(v['weather'])\n sorted_weather = sorted(weather_of_date.items(), key=lambda x: x[0])\n return sorted_weather\n\n def send_email(self):\n\n # Date information\n date_of_landing='2018-11-12'\n date_of_today = date.today().strftime(\"%Y-%m-%d\")\n day_of_year = date.today().strftime(\"%j\")\n day_of_week = date.today().strftime(\"%A\")\n weekday_of_today = date.today().weekday()\n # week_of_year = date.today().strftime(\"%W\")\n percent = round((float(day_of_year) + 0.0) / 3.65, 1)\n progress_bar = str(percent) + '%
'\n tmp_bar = round(percent) * '\\u25A0' + (100 - int(percent)) * '\\u25A1'\n for idx in range(10):\n progress_bar += '\\u25c0' + tmp_bar[idx*10:idx*10+10] + '\\u25b6
'\n\n # Exchange rate\n exchange_rate_info = self.get_exchange_rate()\n # Weather\n list_weather = self.get_weather()\n str_forecast = ''\n for idx, item in enumerate(list_weather):\n str_forecast += (\"\" if (idx % 2 == 0) else \"\") + \\\n \"\" + item[0] + \\\n \"\" + str(item[1]['min_temp']) + \\\n \"\" + str(item[1]['max_temp']) + \\\n \"\" + item[1]['weather'] + \"\\n\"\n\n style = \"\"\"\n \n \"\"\"\n weather_info = '''\n

Weather information

\n \n \n \n {forecast}\n
Weather forecast of the following 6 days
DateMin Temp.Max Temp.Weather
\n '''.format(forecast=str_forecast)\n # Food expenses\n df = pd.read_csv(conf.data_path + '/' + 'food_expense', sep='\\t')\n cost = round(df['Expense'].sum(), 2)\n days_since_landing = days_between(date_of_landing, date_of_today)\n mail_msg = u\"\"\"\n \n \n \n {style}\n \n \n

Date information

\n

Today is {date}, {week}, the {doy} day in this year.

\n

This year's progress is as follows:

\n

{progress}

\n
\n {exchange_rate_info}\n
\n

Expenses on food

\n

We've landed in Toronto for {dsl} days, and spent ${cost} on food.

\n

Our average daily expense on food is: ${cpd} / d .

\n
\n {weather_info}\n
\n

This is an automatically generated email, however, you can reply if you insist. To unsubscribe, please discuss with your husband in person.

\n --------------\n

Have a nice day!

\n \n \n \"\"\".format(date=date_of_today, week=day_of_week, doy=ord(int(day_of_year)),\n weather_info=weather_info,style=style,exchange_rate_info=exchange_rate_info,\n progress=progress_bar, dsl=days_since_landing, cost=cost, cpd=round(float(cost)/days_since_landing, 2))\n message = MIMEText(mail_msg, 'html', 'utf-8')\n message['From'] = Header(\"Bo Pang\", 'utf-8')\n # message['To'] = Header(\"Ms. Egg\", 'utf-8')\n subject = 'FAMILY REPORT @ {}'.format(date_of_today)\n message['Subject'] = Header(subject, 'utf-8')\n try:\n print(\"connect ...\")\n server = smtplib.SMTP('{host}:{port}'.format(host=conf.mail_host, port=conf.mail_port))\n server.ehlo()\n server.starttls()\n print(\"login ...\")\n server.login(conf.sender, conf.mail_pswd)\n print(\"send ...\")\n receivers_today = conf.receivers\n if weekday_of_today in [1, 3, 5]:\n receivers_today += conf.conditional_receivers\n print(\"Today's receivers are: \" + \", \".join(receivers_today))\n server.sendmail(conf.sender, receivers_today, message.as_string())\n server.quit()\n print(\"Successfully sent email.\")\n except smtplib.SMTPException as e:\n print(e)\n\n def run(self):\n self.send_email()\n\nif __name__ == '__main__':\n # main process\n family_report = FamilyReport()\n family_report.run()\n # family_report.get_exchange_rate()\n","sub_path":"FamilyReport/run_report.py","file_name":"run_report.py","file_ext":"py","file_size_in_byte":8492,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"82833718","text":"import numpy\nfrom kaggle_environments import make\n\n# create the environment. You can also specify configurations for seed and loglevel as shown below. If not specified, a random seed is chosen. \n# loglevel default is 0. \n# 1 is for errors, 2 is for match warnings such as units colliding, invalid commands (recommended)\n# 3 for info level, and 4 for everything (not recommended)\n# set annotations True so annotation commands are drawn on visualizer\n# set debug to True so print statements get shown\nenv = make(\"lux_ai_2021\", configuration={\"seed\": 562124210, \"loglevel\": 2, \"annotations\": True}, debug=True)\n\n# run a match between two simple agents, which are the agents we will walk you through on how to build!\nsteps = env.run([\"simple_agent\", \"simple_agent\"])\n# if you are viewing this outside of the interactive jupyter notebook / kaggle notebooks mode, this may look cutoff\n# render the game, feel free to change width and height to your liking. We recommend keeping them as large as possible for better quality.\n# you may also want to close the output of this render cell or else the notebook might get laggy\nout = env.render(mode=\"html\", width=1200, height=800)\n\n# write the output html file\nwith open('../../runs/output.html', 'w') as f:\n f.write(out)","sub_path":"scripts/py/simple_run.py","file_name":"simple_run.py","file_ext":"py","file_size_in_byte":1262,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"128229635","text":"import pandas as pd\nimport numpy as np\n\ndf = pd.read_csv('https://opendata.arcgis.com/datasets/dd4580c810204019a7b8eb3e0b329dd6_0.csv')\n\nfocus = df.copy().drop(['ObjectId','IdBundesland','Altersgruppe','Geschlecht','AnzahlTodesfall','IdLandkreis','Datenstand','NeuerFall','NeuerTodesfall','Refdatum','NeuGenesen','AnzahlGenesen','IstErkrankungsbeginn','Altersgruppe2'], axis=1)#.set_index(['Meldedatum'])\nconfirm = focus.groupby('Bundesland').sum().T\nconfirm_LK = focus.groupby('Landkreis').sum().T\n#\ncols=['District/County Town','COVID-Free Days','New Cases in Last 14 Days','Last7','Previous7']\nimport datetime as dt\ncollect = []\nfor country in confirm_LK.columns:\n bula = focus[focus['Landkreis']==country]\n bula = bula.sort_values(['Meldedatum'], ascending=[True])\n bula['Total'] = bula.groupby(['Landkreis', 'Meldedatum'])['AnzahlFall'].transform('sum')\n new_bula = bula.drop_duplicates(subset=['Landkreis', 'Meldedatum'])\n\n\n bula2 = new_bula.copy().drop(['Bundesland','AnzahlFall'], axis=1)\n\n\n bula2.set_index('Meldedatum', inplace=True)\n bula2.index = pd.to_datetime(bula2.index)\n idx = pd.date_range('01/26/2020', dt.datetime.today().strftime(\"%m/%d/%Y\"))\n bula2 = bula2.reindex(idx, fill_value=0)\n bula2.drop(bula2.tail(2).index,inplace=True)\n\n ave = bula2['Total']\n las = len(ave)-14\n last_forteen = ave[las:].sum()\n if last_forteen < 0:\n last_forteen = 0\n last7 = ave[len(ave)-7:].sum() #last week\n prev7 = ave[len(ave)-14:len(ave)-7].sum() #prev week\n if last7 < 0:\n last7 = 0\n if last7 > last_forteen:\n last_forteen = last7\n if prev7 < 0:\n prev7 = 0\n if (last7 == 0) & (last_forteen == 0):\n prev7 = 0\n i = len(ave)-1\n c = 0\n while i > 0:\n if ave[i] <= 0:\n c = c + 1\n else:\n i = 0\n i = i - 1\n\n collect.append((country,\n c,\n last_forteen,\n\t\t last7,\n\t prev7))\n\nthr = pd.DataFrame(collect, columns=cols)\nfin = thr.sort_values(['COVID-Free Days'], ascending=[False])\nfin['week'] = fin['COVID-Free Days'].gt(13) \ntab = fin.sort_values(['week'], ascending=[False])\ntab_t = tab[tab['week']==True]\ntab_f = tab[tab['week']==False]\ntab_f = tab_f.sort_values(['New Cases in Last 14 Days','COVID-Free Days'], ascending = [True,False])\ntab_t = tab_t.sort_values(['COVID-Free Days','New Cases in Last 14 Days'], ascending = [False,True])\ntab = tab_t.append(tab_f)\ntab = tab.drop(['week'], axis=1)\n\n#Percent Change\n\ntab['PercentChange'] = 100*(tab['Last7'] - tab['Previous7'])/(tab['Last7']+tab['Previous7'])\ntab['PercentChange'] = tab['PercentChange'].fillna(0.0)\n\ntab = tab.drop(['Previous7'], axis = 1)\ntab.columns = ['District/County Town', 'COVID-Free Days', 'New Cases in Last 14 Days', 'Last 7 Days', 'Pct Change']\n\ndef highlighter(s):\n val_1 = s['COVID-Free Days']\n val_2 = s['New Cases in Last 14 Days']\n \n r=''\n try:\n if val_1>=14: #More than 14 Covid free days\n r = 'background-color: #018001; color: #ffffff;'\n elif 20>=val_2 : # less than 20 in last 2 weeks\n r = 'background-color: #02be02; color: #ffffff;'\n elif 200>=val_2 >=21: #Light green\n r = 'background-color: #ffff01;'\n elif 1000>=val_2 >= 201: #Yellow\n r = 'background-color: #ffa501;'\n elif 20000>=val_2 >= 1001: #Orange\n r = 'background-color: #ff3434;'\n elif val_2 > 20001: # Red\n r = 'background-color: #990033;'\n except Exception as e:\n r = 'background-color: white'\n return [r]*(len(s)-2) + ['']*2\n\ndef hover(hover_color=\"#ffff99\"):\n return dict(selector=\"tbody tr:hover td, tbody tr:hover th\",\n props=[(\"background-color\", \"rgba(66, 165, 245, 0.2) !important\")])\n\ntop = \"\"\"\n\n\n\n\n\n\n\n\n\"\"\"\nbottom = \"\"\"\n\n\n\"\"\"\n\narrow = lambda x : ' ↗' if x>0 else (' →' if x ==0 else ' ↘')\nstyles=[hover(),]\ntab['Rank'] = tab.reset_index().index\ntab['Rank'] = tab['Rank'].add(1)\ntab['Trend'] = tab['Pct Change'].map(arrow)\ntab['Percent Change'] = tab['Pct Change'].map('{:,.2f}%'.format) + tab['Trend']\ntab = tab.drop(['Trend','Pct Change'], axis = 1)\n\ntab = tab[['Rank', 'District/County Town', 'COVID-Free Days', 'New Cases in Last 14 Days','Last 7 Days','Percent Change']] \ns = tab.style.apply(highlighter, axis = 1).set_table_styles(styles).hide_index()\n\ntry: \n with open(f'Germany.html', 'w', encoding=\"utf-8\") as out:\n body = s.render().replace('↗','') # red arrow up\n body = body.replace('↘','') # green arrow down\n content = top + body + bottom\n out.write(content)\nexcept Exception as e:\n print(f'Error:\\n{e}')\n \n\n","sub_path":"Germany/Germany_ranking.py","file_name":"Germany_ranking.py","file_ext":"py","file_size_in_byte":5606,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"623949339","text":"import vampytest\n\nfrom ...action import AutoModerationAction\n\nfrom ..fields import put_actions_into\n\n\ndef test__parse_action():\n \"\"\"\n Tests whether ``put_actions_into`` works as intended.\n \"\"\"\n action_1 = AutoModerationAction(duration = 69)\n action_2 = AutoModerationAction(channel_id = 202211170022)\n \n for input_value, defaults, expected_output in (\n (None, False, {}),\n (None, True, {'actions': []}),\n ((action_1, action_2), True, {'actions': [action_1.to_data(defaults = True), action_2.to_data(defaults = True)]}),\n ):\n output = put_actions_into(input_value, {}, defaults)\n vampytest.assert_eq(output, expected_output)\n","sub_path":"hata/discord/auto_moderation/rule/tests/test__put_actions_into.py","file_name":"test__put_actions_into.py","file_ext":"py","file_size_in_byte":683,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"581252267","text":"#!/usr/bin/env python2.7\nimport rospy\nfrom geometry_msgs.msg import Vector3\nfrom geometry_msgs.msg import Twist\nfrom sensor_msgs.msg import CameraInfo\n\nimport time\n\nfrom control_pid import ControlPid\n\nclass ControlVision:\n control_pid_x = None\n control_pid_yaw = None\n pub_cmd_vel = None\n msg_twist = None\n camera_info = None\n\n def __init__ (self):\n rospy.init_node(\"robot_vision\", anonymous=True)\n self.pub_cmd_vel = rospy.Publisher(\"/cmd_vel\", Twist, queue_size=1)\n self.control_pid_x = ControlPid(5, -5, 0.01, 0, 0)\n self.control_pid_yaw = ControlPid(3, -3, 0.001, 0, 0)\n self.msg_twist = Twist()\n rospy.Subscriber(\"/diff/camera_top/camera_info\", CameraInfo, self.callback_camera_info)\n \n def callback(self, data):\n if data.x != -1:\n self.msg_twist.angular.z = self.control_pid_yaw.pid_calculate(0.5, self.camera_info.width/2, int(data.x))\n self.msg_twist.linear.x = self.control_pid_x.pid_calculate(0.5, 360, int(data.z))\n self.pub_cmd_vel.publish(self.msg_twist)\n\n def callback_camera_info(self, data):\n self.camera_info = data\n\n def run(self):\n self.msg = rospy.Subscriber(\"camera/param\", Vector3, self.callback)\n\nif __name__ == \"__main__\":\n rospy.loginfo(\"Init Control\")\n ctrl_vision = ControlVision()\n ctrl_vision.run()\n while not rospy.is_shutdown():\n rospy.spin() ","sub_path":"src/desafio/scripts/controlvision.py","file_name":"controlvision.py","file_ext":"py","file_size_in_byte":1341,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"598169576","text":"# coding: utf-8\nimport collections\nwith open('enc.txt', 'r') as f:\n enc = f.read()\n\nline = ''\nfor i in range(0, len(enc), 8):\n line += chr(int(enc[i:i+8], 2))\n\nl = []\nfor i in range(0, len(line), 29):\n l.append(line[i:i+29])\n\nflag = ''\nfor i in range(len(l[0])):\n tmp_l = []\n for j in range(len(l)):\n tmp_l.append(l[j][i])\n c = collections.Counter(tmp_l)\n flag += c.most_common()[0][0]\n\nprint(flag)","sub_path":"error_0.py","file_name":"error_0.py","file_ext":"py","file_size_in_byte":426,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"449648170","text":"import re\n\nclass Claim():\n def __init__(self, mid, x, y, w, h):\n self.mid = int(mid)\n self.x = int(x)\n self.y = int(y)\n self.w = int(w)\n self.h = int(h)\n\nboard = [[0 for x in range(1000)] for y in range(1000)]\nclaims = []\nwith open(\"input.txt\") as f:\n for line in f:\n match = re.match(\"#(\\d+) @ (\\d+),(\\d+): (\\d+)x(\\d+)\", line)\n c = Claim(match.group(1), match.group(2), match.group(3), match.group(4), match.group(5))\n claims.append(c)\n# part 1\n for i in range(0, c.w):\n for j in range(0, c.h):\n board[c.x+i][c.y+j] += 1\n\ncount = 0\nfor i in range(0, 1000):\n for j in range(0, 1000):\n if board[i][j] > 1:\n count += 1\nprint(count)\n\n\n# part 2\ndef intersects(c1, c2):\n return ((c1.x < (c2.x+c2.w)) and ((c1.x+c1.w) > c2.x) and\n (c1.y < (c2.y+c2.h)) and ((c1.y+c1.h) > c2.y))\n\nfor c1 in claims:\n alone = True\n for c2 in claims:\n if c1.mid == c2.mid:\n continue\n if intersects(c1, c2):\n alone = False\n break\n if not alone:\n continue\n else:\n print(c1.mid)\n\n","sub_path":"3/3.py","file_name":"3.py","file_ext":"py","file_size_in_byte":1153,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"531096035","text":"import os\nimport sys\n\nsys.path.append('../')\n\nfrom corpus import Corpus\nfrom model import Model\nfrom evaluator.scorer import Scorer\n\n# maximum sequence length\nmax_len = 60\n\n\n#test(self, path_model, path_weigths, classes_file, word_idx_file, max_len_file, test_corpus): \ndef __evaluate_experiment(working_dir, save_dir, test_filename, test_labelsfile, path_weights):\n working_dir = working_dir\n test_file = working_dir + test_filename\n test_labels = working_dir + test_labelsfile\n #intialize corpus\n test_corpus = Corpus(test_file, test_labels)\n # create model object\n model = Model()\n result = model.test(save_dir, path_weights, test_corpus)\n scorer = Scorer(result)\n\n print('Macro Fscore:')\n print(scorer.get_macro())\n\n print('Micro Fscore:')\n print(scorer.get_micro())\n for label in scorer.labels:\n print('Fscore ' + label)\n print(scorer.get_f_score(label))\n\n\ndef __run_experiment(working_dir, save_dir, train_filename, word_embed_filename, embed_file_type, architecture, max_len,\n params=None, train_params=None, dev_filename=None, dev_labelsfile=None):\n # define path to working dir\n dir_path = working_dir\n # define path to dir where files should be saved to\n savedir_path = save_dir\n\n # get ful filenames paths to data files and initialize corpora\n train_file = dir_path + train_filename\n train_corpus = Corpus(train_file)\n if dev_filename and dev_labelsfile:\n dev_file = dir_path + dev_filename\n dev_labels = dir_path + dev_labelsfile\n dev_corpus = Corpus(dev_file, dev_labels)\n else:\n dev_corpus = None\n\n # define filename of embedding file and file type (txt or bin)\n word_embedding_file = dir_path + 'word_embeddings/w2v_embeddings/' + word_embed_filename\n file_type = embed_file_type\n\n # define label to int mapping\n classes = {'joy' : 0, 'anger' : 1, 'fear' : 2, 'surprise' : 3, 'disgust' : 4, 'sad' : 5}\n\n architecture = architecture\n params = params\n\n # parse train parameters\n if 'num_epochs' in train_params:\n num_epochs = train_params['num_epochs']\n else:\n num_epochs = 5\n if 'min_count' in train_params:\n min_count = train_params['min_count']\n else:\n min_count = 1\n\n # create model object\n model = Model()\n # train model TODO: use savedir\n model.train(train_corpus, classes, architecture, params, num_epochs, max_len, word_embedding_file, file_type, min_count, save_dir, dev_corpus)\n # free memory\n del model\n\ndef train_architecture_experiment(working_dir, experiment_dir, word_embeddings, architecture, train_filename, dev_file, dev_labels, test_file, test_labels, params, train_params):\n\n # Experiments\n print('Running Architectures Experiment')\n print('Using full training data')\n\n # create output directory\n directory = os.path.dirname(working_dir + experiment_dir + architecture + '/')\n if not os.path.exists(directory):\n os.makedirs(directory)\n\n print('Experiment Architecture: ' + architecture)\n __run_experiment(working_dir, working_dir + experiment_dir + architecture + '/', train_filename, word_embeddings, 'word2vec', \n architecture, max_len, params, train_params, dev_file, dev_labels)\n\ndef train_word_embedding_experiment(working_dir, experiment_dir, word_embeddings, architecture, train_filename, dev_file, dev_labels, test_file, test_labels, params, train_params):\n\n # Experiments\n print('Running Word Embedding Experiments')\n print('Using full training data')\n\n params = {'dropout' : .5, 'trainable_embeddings' : False}\n train_params = {'num_epochs' : 15, 'min_count' : 1}\n\n # create output directory\n directory = os.path.dirname(working_dir + experiment_dir + word_embeddings + '/')\n if not os.path.exists(directory):\n os.makedirs(directory)\n\n print('Experiment Word embeddings: ' + word_embeddings)\n __run_experiment(working_dir, working_dir + experiment_dir + word_embeddings + '/', train_filename, word_embeddings, 'word2vec', \n architecture, max_len, params, train_params, dev_file, dev_labels)\n\ndef eval_architecture_experiment(working_dir, experiment_dir, architecture, best_weights, test_filename, test_labelsfile):\n\n architecture_path = working_dir + experiment_dir + architecture + '/'\n print(architecture_path)\n print('Architecture Experiment Evaluation')\n\n print('Experiment Architecture: ' + architecture)\n __evaluate_experiment(working_dir, architecture_path, test_filename, test_labelsfile, architecture_path + best_weights)\n\ndef eval_word_embedding_experiment(working_dir, experiment_dir, word_embeddings, best_weights, test_filename, test_labelsfile):\n\n word_embedding_path = working_dir + experiment_dir + word_embeddings + '/'\n \n print('Wordembedding Experiment Evaluation')\n\n print('Experiment Word embeddings: ' + word_embeddings)\n __evaluate_experiment(working_dir, word_embedding_path, test_filename, test_labelsfile, word_embedding_path + best_weights)\n\n\ndef main():\n # absolute path\n working_dir = '/run/media/martin/Elements/Marina/TeamLab/'\n # relative to working_dir\n experiment_dir = 'experiments/architecture_experiment/'\n # directory of train, dev and test data, relative to working dir\n data_dir = 'data/'\n # filename of word_embeddings\n word_embeddings = 'w2v_cbow_hs_300_w5.txt'\n # architecture\n architecture = 'BiLSTM+ATT'\n # filename of best weights\n best_weights = 'weights-improvement-07-0.64.hdf5'\n # parameters\n params = {'dropout' : .5, 'trainable_embeddings' : True}\n # train parameters\n train_params = {'num_epochs' : 15, 'min_count' : 1}\n\n # filenames of the train, dev and test data\n train_filename = 'train-v2.csv'\n dev_file = 'trial-v2.csv'\n dev_labels = 'trial-v2.labels'\n test_file = 'trial.csv'\n test_labels = 'trial.labels'\n\n # combine filenames for internal use\n train_f = data_dir + train_filename\n dev_f = data_dir + dev_file\n dev_l = data_dir + dev_labels\n test_f = data_dir + test_file\n test_l = data_dir + test_labels\n\n # train_word_embedding_experiment(working_dir, experiment_dir, word_embeddings, architecture, train_f, dev_f, dev_l, test_f, test_l, params, train_params)\n train_architecture_experiment(working_dir, experiment_dir, word_embeddings, architecture, train_f, dev_f, dev_l, test_f, test_l, params, train_params)\n # eval_word_embedding_experiment(working_dir, experiment_dir, word_embeddings, best_weights, test_f, test_l)\n # eval_architecture_experiment(working_dir, experiment_dir, architecture, best_weights, test_f, test_l)\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"deepLearning/deeplearning_experiment.py","file_name":"deeplearning_experiment.py","file_ext":"py","file_size_in_byte":6721,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"556340391","text":"import sys\n\nfrom benchmark_paths import get_result_path\nfrom benchmark_tools import run\n\nassert len(sys.argv) == 3, \"Usage: python script.py scene_name scene_depth\"\n\nscene = sys.argv[1]\nscene_depth = int(sys.argv[2])\nreplay_name = \"edits\"\n\npage_sizes = [128, 256, 512];\n\nthreads = \"1\"; #\"0\"; # \"1\"\n\nnum_threads = \"6\";\nbase_defines = [\n (\"SCENE\", \"\\\"{}\\\"\".format(scene)),\n (\"SCENE_DEPTH\", \"{}\".format(scene_depth)),\n (\"REPLAY_NAME\", \"\\\"{}\\\"\".format(replay_name)),\n (\"USE_BLOOM_FILTER\", \"0\"),\n (\"EDITS_COUNTERS\", \"1\"),\n (\"THREADED_EDITS\", threads),\n (\"NUM_THREADS\", num_threads),\n (\"EDITS_ENABLE_COLORS\", \"0\"),\n]\n\n\n# At level 17, we need a bit more space in the buckets.\n# This mainly increases the memory consumption of the page size\nif scene_depth >= 17:\n base_defines += [\n (\"BUCKETS_SIZE_FOR_LOW_LEVELS\", 2048+1024)\n ]\n\npath = get_result_path(\"page_size\")\n\nfor i in range(len(page_sizes)):\n ps = page_sizes[i]\n threaded=base_defines + [\n (\"PAGE_SIZE\", ps),\n ];\n run(threaded, \"scene={}_depth={}_ps{}\".format(scene, scene_depth, ps), path)\npass;\n","sub_path":"python/benchmark_page_size.py","file_name":"benchmark_page_size.py","file_ext":"py","file_size_in_byte":1103,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"633734228","text":"\r\n#爬取汽车之家所有车型数据\r\nfrom bs4 import BeautifulSoup\r\nimport requests\r\n\r\nhtml='https://www.autohome.com.cn/grade/carhtml/'\r\n\r\n\r\ndoc=open('out.txt','w')\r\nfor i in range(97,97+27):\r\n url=html+chr(i)+'.html'\r\n i+=1\r\n r=requests.get(url)\r\n r.encoding='gbk'\r\n soup=BeautifulSoup(r.text,'html.parser')\r\n zzr=soup.find_all('h4')\r\n for a in zzr:\r\n print(a.text,file=doc)\r\ndoc.close\r\n","sub_path":"spiders/car.py","file_name":"car.py","file_ext":"py","file_size_in_byte":420,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"412241996","text":"'''\n63. オブジェクトを値に格納したKVS\nKVSを用い,アーティスト名(name)から\nタグと被タグ数(タグ付けされた回数)のリストを検索するためのデータベースを構築せよ.\nさらに,ここで構築したデータベースを用い,アーティスト名からタグと被タグ数を検索せよ.\n'''\nimport sys\nimport gzip\nimport json\nimport leveldb\n\n\ndef message(text):\n sys.stderr.write(f\"\\33[92m{text}\\33[0m\\n\")\n\n\nfname = 'artist.json.gz'\ndb_name = 'name2tags'\n\ndb = leveldb.LevelDB(db_name)\n\nif sum(1 for _ in db.RangeIter(include_value=False)) == 66137:\n message(\"[*] skip\")\nelse:\n with gzip.open(fname, 'rt') as f:\n for line in f:\n json_data = json.loads(line)\n name = f\"{json_data['name']}\\t{json_data['id']}\"\n try:\n tags = json.dumps(json_data['tags'])\n except KeyError as e:\n continue\n db.Put(name.encode(), tags.encode())\n\nfname_db_size = sum(1 for _ in db.RangeIter(include_value=False))\nmessage(f'[+] {db_name} のサイズ -> {fname_db_size}')\n\n# 以上,knock60 と同様\n# 以下,knock61 と同様\n\nmessage(\"[*] key = Oasis\\t20660 のタ���と被タグ数\")\nfor d in json.loads(db.Get(b'Oasis\\t20660').decode()):\n print(f\"{d['value']}({d['count']})\")\n\n\n'''\n* LevelDB\n - https://github.com/google/leveldb\n cf. plyvel\n* LevelDB入門 (基本編)\n - https://yosuke-furukawa.hatenablog.com/entry/2014/05/05/095207\n* JSON形式の概要は以下の通りである.\nフィールド\t 型\t内容\t例\nid\t ユニーク識別子\t整数\t20660\ngid\t グローバル識別子\t文字列\t\"ecf9f3a3-35e9-4c58-acaa-e707fba45060\"\nname\t アーティスト名\t文字列\t\"Oasis\"\nsort_name\t アーティスト名(辞書順整列用)\t文字列\t\"Oasis\"\narea\t 活動場所\t文字列\t\"United Kingdom\"\naliases\t 別名\t辞書オブジェクトのリスト\naliases[].name\t 別名\t文字列\t\"オアシス\"\naliases[].sort_name\t 別名(整列用)\t文字列\t\"オアシス\"\nbegin\t 活動開始日\t辞書\nbegin.year\t 活動開始年\t整数\t1991\nbegin.month\t 活動開始月\t整数\nbegin.date\t 活動開始日\t整数\nend\t 活動終了日\t辞書\nend.year\t 活動終了年\t整数\t2009\nend.month\t 活動終了月\t整数\t8\nend.date\t 活動終了日\t整数\t28\ntags\t タグ\t辞書オブジェクトのリスト\ntags[].count\t タグ付けされた回数\t整数\t1\ntags[].value タグ内容\t文字列\t\"rock\"\nrating\t レーティング\t辞書オブジェクト\nrating.count\t レーティングの投票数\t整数\t13\nrating.value\t レーティングの値(平均値)\t整数\t86\n'''\n","sub_path":"kiyuna/chapter07/knock63.py","file_name":"knock63.py","file_ext":"py","file_size_in_byte":2874,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"424607301","text":"####\n#\n#\tTitle: Tensorflow tutorial 01\n#\tWritten by DoYoung Lee in 2018-11-06\n#\tReference: \"https://gist.github.com/haje01/202ac276bace4b25dd3f\"\n#\n####\n\nimport tensorflow as tf\n\n# Initialize variables to 0\nstate = tf.Variable(0, name=\"counter\")\n\n# Create operation: add 1 to state\none = tf.constant(1)\nnew_value = tf.add(state, one)\nupdate = tf.assign(state, new_value)\n\n# Initialize operator\ninit_op = tf.initialize_all_variables()\n\n# Execute operations\nwith tf.Session() as sess:\n\tsess.run(init_op)\n\tprint(sess.run(state))\n\tfor _ in range(3):\n\t\tsess.run(update)\n\t\tprint(sess.run(state))","sub_path":"Basic tensorflow/tf_tutorial_01.py","file_name":"tf_tutorial_01.py","file_ext":"py","file_size_in_byte":588,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"496369060","text":"# -*- coding: utf-8 -*-\n\n#\n# Copyright (c) 2012-2019 Virtual Cable S.L.\n# All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without modification,\n# are permitted provided that the following conditions are met:\n#\n# * Redistributions of source code must retain the above copyright notice,\n# this list of conditions and the following disclaimer.\n# * Redistributions in binary form must reproduce the above copyright notice,\n# this list of conditions and the following disclaimer in the documentation\n# and/or other materials provided with the distribution.\n# * Neither the name of Virtual Cable S.L. nor the names of its contributors\n# may be used to endorse or promote products derived from this software\n# without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n\"\"\"\n@author: Adolfo Gómez, dkmaster at dkmon dot com\n\"\"\"\nimport logging\nimport random\nimport operator\nimport typing\n\nfrom django.utils.translation import gettext as _\nfrom django.db.models import Q\nfrom django.db import transaction\nfrom uds.core.services.exceptions import OperationException\nfrom uds.core.util.config import GlobalConfig\nfrom uds.core.util.state import State\nfrom uds.core.util import log\nfrom uds.core.services.exceptions import (\n MaxServicesReachedError,\n ServiceInMaintenanceMode,\n InvalidServiceException,\n ServiceNotReadyError,\n ServiceAccessDeniedByCalendar,\n)\nfrom uds.models import (\n MetaPool,\n ServicePool,\n UserService,\n getSqlDatetime,\n Transport,\n User,\n ServicePoolPublication,\n)\nfrom uds.models.meta_pool import MetaPoolMember\nfrom uds.core import services, transports\nfrom uds.core.util import singleton\nfrom uds.core.util.stats import events\nfrom uds.core.util.os_detector import DetectedOsInfo\n\nfrom .userservice import comms\nfrom .userservice.opchecker import UserServiceOpChecker\n\nif typing.TYPE_CHECKING:\n from uds import models\n\nlogger = logging.getLogger(__name__)\ntraceLogger = logging.getLogger('traceLog')\noperationsLogger = logging.getLogger('operationsLog')\n\nclass UserServiceManager(metaclass=singleton.Singleton):\n def __init__(self):\n pass\n\n @staticmethod\n def manager() -> 'UserServiceManager':\n return (\n UserServiceManager()\n ) # Singleton pattern will return always the same instance\n\n def getCacheStateFilter(self, servicePool: ServicePool, level: int) -> Q:\n return Q(cache_level=level) & self.getStateFilter(servicePool.service)\n\n @staticmethod\n def getStateFilter(service: 'models.Service') -> Q:\n if service.oldMaxAccountingMethod: # If no limits and accounting method is not old one\n # Valid states are: PREPARING, USABLE\n states = [State.PREPARING, State.USABLE] \n else: # New accounting method selected\n states = [State.PREPARING, State.USABLE, State.REMOVING, State.REMOVABLE]\n return Q(state__in=states)\n\n def _checkMaxDeployedReached(self, servicePool: ServicePool) -> None:\n \"\"\"\n Checks if maxDeployed for the service has been reached, and, if so,\n raises an exception that no more services of this kind can be reached\n \"\"\"\n if self.maximumUserServicesDeployed(servicePool.service):\n raise MaxServicesReachedError(\n _('Maximum number of user services reached for this {}').format(\n servicePool\n )\n )\n\n def getExistingUserServices(self, service: 'models.Service') -> int:\n \"\"\"\n Returns the number of running user services for this service\n \"\"\"\n return UserService.objects.filter(\n self.getStateFilter(service) & Q(deployed_service__service=service)\n ).count()\n\n def maximumUserServicesDeployed(self, service: 'models.Service') -> bool:\n \"\"\"\n Checks if the maximum number of user services for this service has been reached\n \"\"\"\n serviceInstance = service.getInstance()\n # Early return, so no database count is needed\n if serviceInstance.maxDeployed == services.Service.UNLIMITED:\n return False\n\n if self.getExistingUserServices(service) >= (serviceInstance.maxDeployed or 1):\n operationsLogger.info('Maximum number of user services reached for service: {}'.format(service.name))\n return True\n\n return False\n\n def _createCacheAtDb(\n self, publication: ServicePoolPublication, cacheLevel: int\n ) -> UserService:\n \"\"\"\n Private method to instatiate a cache element at database with default states\n \"\"\"\n # Checks if maxDeployed has been reached and if so, raises an exception\n self._checkMaxDeployedReached(publication.deployed_service)\n now = getSqlDatetime()\n return publication.userServices.create(\n cache_level=cacheLevel,\n state=State.PREPARING,\n os_state=State.PREPARING,\n state_date=now,\n creation_date=now,\n data='',\n deployed_service=publication.deployed_service,\n user=None,\n in_use=False,\n )\n\n def _createAssignedAtDb(\n self, publication: ServicePoolPublication, user: User\n ) -> UserService:\n \"\"\"\n Private method to instatiate an assigned element at database with default state\n \"\"\"\n self._checkMaxDeployedReached(publication.deployed_service)\n now = getSqlDatetime()\n return publication.userServices.create(\n cache_level=0,\n state=State.PREPARING,\n os_state=State.PREPARING,\n state_date=now,\n creation_date=now,\n data='',\n deployed_service=publication.deployed_service,\n user=user,\n in_use=False,\n )\n\n def _createAssignedAtDbForNoPublication(\n self, servicePool: ServicePool, user: User\n ) -> UserService:\n \"\"\"\n __createCacheAtDb and __createAssignedAtDb uses a publication for create the UserService.\n There is cases where deployed services do not have publications (do not need them), so we need this method to create\n an UserService with no publications, and create them from an ServicePool\n \"\"\"\n self._checkMaxDeployedReached(servicePool)\n now = getSqlDatetime()\n return servicePool.userServices.create(\n cache_level=0,\n state=State.PREPARING,\n os_state=State.PREPARING,\n state_date=now,\n creation_date=now,\n data='',\n publication=None,\n user=user,\n in_use=False,\n )\n\n def createCacheFor(\n self, publication: ServicePoolPublication, cacheLevel: int\n ) -> UserService:\n \"\"\"\n Creates a new cache for the deployed service publication at level indicated\n \"\"\"\n operationsLogger.info(\n 'Creating a new cache element at level %s for publication %s',\n cacheLevel,\n publication,\n )\n cache = self._createCacheAtDb(publication, cacheLevel)\n ci = cache.getInstance()\n state = ci.deployForCache(cacheLevel)\n\n UserServiceOpChecker.checkAndUpdateState(cache, ci, state)\n return cache\n\n def createAssignedFor(self, servicePool: ServicePool, user: User) -> UserService:\n \"\"\"\n Creates a new assigned deployed service for the current publication (if any) of service pool and user indicated\n \"\"\"\n # First, honor maxPreparingServices\n if self.canGrowServicePool(servicePool) is False:\n # Cannot create new\n operationsLogger.info(\n 'Too many preparing services. Creation of assigned service denied by max preparing services parameter. (login storm with insufficient cache?).'\n )\n raise ServiceNotReadyError()\n\n if servicePool.service.getType().publicationType is not None:\n publication = servicePool.activePublication()\n if publication:\n assigned = self._createAssignedAtDb(publication, user)\n operationsLogger.info(\n 'Creating a new assigned element for user %s for publication %s on pool %s',\n user.pretty_name,\n publication.revision,\n servicePool.name,\n )\n else:\n raise Exception(\n 'Invalid publication creating service assignation: {} {}'.format(\n servicePool, user\n )\n )\n else:\n operationsLogger.info('Creating a new assigned element for user %s on pool %s', user.pretty_name, servicePool.name)\n assigned = self._createAssignedAtDbForNoPublication(servicePool, user)\n\n assignedInstance = assigned.getInstance()\n state = assignedInstance.deployForUser(user)\n\n UserServiceOpChecker.makeUnique(assigned, assignedInstance, state)\n\n return assigned\n\n def createFromAssignable(\n self, servicePool: ServicePool, user: User, assignableId: str\n ) -> UserService:\n \"\"\"\n Creates an assigned service from an \"assignable\" id\n \"\"\"\n serviceInstance = servicePool.service.getInstance()\n if not serviceInstance.canAssign():\n raise Exception('This service type cannot assign asignables')\n\n if servicePool.service.getType().publicationType is not None:\n publication = servicePool.activePublication()\n if publication:\n assigned = self._createAssignedAtDb(publication, user)\n operationsLogger.info(\n 'Creating an assigned element from assignable %s for user %s for publication %s on pool %s',\n assignableId,\n user.pretty_name,\n publication.revision,\n servicePool.name,\n )\n else:\n raise Exception(\n 'Invalid publication creating service assignation: {} {}'.format(\n servicePool, user\n )\n )\n else:\n operationsLogger.info(\n 'Creating an assigned element from assignable %s for user %s on pool %s',\n assignableId,\n user.pretty_name,\n servicePool.name,\n )\n assigned = self._createAssignedAtDbForNoPublication(servicePool, user)\n\n # Now, get from serviceInstance the data\n assignedInstance = assigned.getInstance()\n state = serviceInstance.assignFromAssignables(\n assignableId, user, assignedInstance\n )\n # assigned.updateData(assignedInstance)\n\n UserServiceOpChecker.makeUnique(assigned, assignedInstance, state)\n\n return assigned\n\n def moveToLevel(self, cache: UserService, cacheLevel: int) -> None:\n \"\"\"\n Moves a cache element from one level to another\n @return: cache element\n \"\"\"\n cache.refresh_from_db()\n logger.debug('Moving cache %s to level %s', cache, cacheLevel)\n cacheInstance = cache.getInstance()\n state = cacheInstance.moveToCache(cacheLevel)\n cache.cache_level = cacheLevel\n cache.save(update_fields=['cache_level'])\n logger.debug(\n 'Service State: %a %s %s',\n State.toString(state),\n State.toString(cache.state),\n State.toString(cache.os_state),\n )\n if State.isRuning(state) and cache.isUsable():\n cache.setState(State.PREPARING)\n\n # Data will be serialized on makeUnique process\n UserServiceOpChecker.makeUnique(cache, cacheInstance, state)\n\n def cancel(self, userService: UserService) -> UserService:\n \"\"\"\n Cancels an user service creation\n @return: the Uservice canceling\n \"\"\"\n userService.refresh_from_db()\n\n if userService.isPreparing() is False:\n logger.debug(\n 'Cancel requested for a non running operation, performing removal instead'\n )\n return self.remove(userService)\n\n operationsLogger.info('Canceling userService %s', userService.name)\n userServiceInstance = userService.getInstance()\n\n if (\n not userServiceInstance.supportsCancel()\n ): # Does not supports cancel, but destroy, so mark it for \"later\" destroy\n # State is kept, just mark it for destroy after finished preparing\n userService.destroy_after = True\n else:\n userService.setState(State.CANCELING)\n # We simply notify service that it should cancel operation\n state = userServiceInstance.cancel()\n\n # Data will be serialized on makeUnique process\n # If cancel is not supported, base cancel always returns \"FINISHED\", and\n # opchecker will set state to \"removable\"\n UserServiceOpChecker.makeUnique(userService, userServiceInstance, state)\n\n return userService\n\n def remove(self, userService: UserService) -> UserService:\n \"\"\"\n Removes a uService element\n \"\"\"\n with transaction.atomic():\n userService = UserService.objects.select_for_update().get(id=userService.id)\n operationsLogger.info('Removing userService %a', userService.name)\n if (\n userService.isUsable() is False\n and State.isRemovable(userService.state) is False\n ):\n raise OperationException(_('Can\\'t remove a non active element'))\n userService.setState(State.REMOVING)\n logger.debug(\n \"***** The state now is %s *****\", State.toString(userService.state)\n )\n userService.setInUse(\n False\n ) # For accounting, ensure that it is not in use right now\n userService.save()\n\n userServiceInstance = userService.getInstance()\n state = userServiceInstance.destroy()\n\n # Data will be serialized on makeUnique process\n UserServiceOpChecker.makeUnique(userService, userServiceInstance, state)\n\n return userService\n\n def removeOrCancel(self, userService: UserService):\n if userService.isUsable() or State.isRemovable(userService.state):\n return self.remove(userService)\n\n if userService.isPreparing():\n return self.cancel(userService)\n\n raise OperationException(\n _('Can\\'t remove nor cancel {} cause its state don\\'t allow it').format(\n userService.name\n )\n )\n\n def getExistingAssignationForUser(\n self, servicePool: ServicePool, user: User\n ) -> typing.Optional[UserService]:\n existing = servicePool.assignedUserServices().filter(\n user=user, state__in=State.VALID_STATES\n ) # , deployed_service__visible=True\n if existing.exists():\n logger.debug(\n 'Found assigned service from %s to user %s', servicePool, user.name\n )\n return existing.first()\n return None\n\n def getAssignationForUser(\n self, servicePool: ServicePool, user: User\n ) -> typing.Optional[UserService]: # pylint: disable=too-many-branches\n if servicePool.service.getInstance().spawnsNew is False:\n assignedUserService = self.getExistingAssignationForUser(servicePool, user)\n else:\n assignedUserService = None\n\n # If has an assigned user service, returns this without any more work\n if assignedUserService:\n return assignedUserService\n\n if servicePool.isRestrained():\n raise InvalidServiceException(_('The requested service is restrained'))\n\n cache: typing.Optional[UserService] = None\n # Now try to locate 1 from cache already \"ready\" (must be usable and at level 1)\n with transaction.atomic():\n caches = typing.cast(\n typing.List[UserService],\n servicePool.cachedUserServices()\n .select_for_update()\n .filter(\n cache_level=services.UserDeployment.L1_CACHE,\n state=State.USABLE,\n os_state=State.USABLE,\n )[\n :1 # type: ignore # Slicing is not supported by pylance right now\n ],\n )\n if caches:\n cache = caches[0]\n # Ensure element is reserved correctly on DB\n if (\n servicePool.cachedUserServices()\n .select_for_update()\n .filter(user=None, uuid=typing.cast(UserService, cache).uuid)\n .update(user=user, cache_level=0)\n != 1\n ):\n cache = None\n else:\n cache = None\n\n # Out of previous atomic\n if not cache:\n with transaction.atomic():\n caches = typing.cast(\n typing.List[UserService],\n servicePool.cachedUserServices()\n .select_for_update()\n .filter(\n cache_level=services.UserDeployment.L1_CACHE, state=State.USABLE\n )[\n :1 # type: ignore # Slicing is not supported by pylance right now\n ],\n )\n if cache:\n cache = caches[0]\n if (\n servicePool.cachedUserServices()\n .select_for_update()\n .filter(user=None, uuid=typing.cast(UserService, cache).uuid)\n .update(user=user, cache_level=0)\n != 1\n ):\n cache = None\n else:\n cache = None\n\n # Out of atomic transaction\n if cache:\n # Early assign\n cache.assignToUser(user)\n\n logger.debug(\n 'Found a cached-ready service from %s for user %s, item %s',\n servicePool,\n user,\n cache,\n )\n events.addEvent(\n servicePool,\n events.ET_CACHE_HIT,\n fld1=servicePool.cachedUserServices()\n .filter(\n cache_level=services.UserDeployment.L1_CACHE, state=State.USABLE\n )\n .count(),\n )\n return cache\n\n # Cache missed\n\n # Now find if there is a preparing one\n with transaction.atomic():\n caches = (\n servicePool.cachedUserServices()\n .select_for_update()\n .filter(\n cache_level=services.UserDeployment.L1_CACHE, state=State.PREPARING\n )[\n :1 # type: ignore # Slicing is not supported by pylance right now\n ]\n )\n if caches:\n cache = caches[0] # type: ignore # Slicing is not supported by pylance right now\n if (\n servicePool.cachedUserServices()\n .select_for_update()\n .filter(user=None, uuid=typing.cast(UserService, cache).uuid)\n .update(user=user, cache_level=0)\n != 1\n ):\n cache = None\n else:\n cache = None\n\n # Out of atomic transaction\n if cache:\n cache.assignToUser(user)\n\n logger.debug(\n 'Found a cached-preparing service from %s for user %s, item %s',\n servicePool,\n user,\n cache,\n )\n events.addEvent(\n servicePool,\n events.ET_CACHE_MISS,\n fld1=servicePool.cachedUserServices()\n .filter(\n cache_level=services.UserDeployment.L1_CACHE, state=State.PREPARING\n )\n .count(),\n )\n return cache\n\n # Can't assign directly from L2 cache... so we check if we can create e new service in the limits requested\n serviceType = servicePool.service.getType()\n if serviceType.usesCache:\n inAssigned = (\n servicePool.assignedUserServices()\n .filter(self.getStateFilter(servicePool.service))\n .count()\n )\n if (\n inAssigned >= servicePool.max_srvs\n ): # cacheUpdater will drop unnecesary L1 machines, so it's not neccesary to check against inCacheL1\n log.doLog(\n servicePool,\n log.WARN,\n 'Max number of services reached: {}'.format(servicePool.max_srvs),\n log.INTERNAL,\n )\n raise MaxServicesReachedError()\n\n # Can create new service, create it\n events.addEvent(servicePool, events.ET_CACHE_MISS, fld1=0)\n return self.createAssignedFor(servicePool, user)\n\n def getUserServicesInStatesForProvider(\n self, provider: 'models.Provider', states: typing.List[str]\n ) -> int:\n \"\"\"\n Returns the number of services of a service provider in the state indicated\n \"\"\"\n return UserService.objects.filter(\n deployed_service__service__provider=provider, state__in=states\n ).count()\n\n def canRemoveServiceFromDeployedService(self, servicePool: ServicePool) -> bool:\n \"\"\"\n checks if we can do a \"remove\" from a deployed service\n serviceIsntance is just a helper, so if we already have deserialized deployedService\n \"\"\"\n removing = self.getUserServicesInStatesForProvider(\n servicePool.service.provider, [State.REMOVING]\n )\n serviceInstance = servicePool.service.getInstance()\n if (\n serviceInstance.isAvailable() and\n removing >= serviceInstance.parent().getMaxRemovingServices()\n and serviceInstance.parent().getIgnoreLimits() is False\n ):\n return False\n return True\n\n def canGrowServicePool(self, servicePool: ServicePool) -> bool:\n \"\"\"\n Checks if we can start a new service\n \"\"\"\n preparingForProvider = self.getUserServicesInStatesForProvider(\n servicePool.service.provider, [State.PREPARING]\n )\n serviceInstance = servicePool.service.getInstance()\n if self.maximumUserServicesDeployed(servicePool.service) or (\n preparingForProvider >= serviceInstance.parent().getMaxPreparingServices()\n and serviceInstance.parent().getIgnoreLimits() is False\n ):\n return False\n return True\n\n def isReady(self, userService: UserService) -> bool:\n userService.refresh_from_db()\n logger.debug('Checking ready of %s', userService)\n\n if userService.state != State.USABLE or userService.os_state != State.USABLE:\n logger.debug('State is not usable for %s', userService.name)\n return False\n\n logger.debug('Service %s is usable, checking it via setReady', userService)\n userServiceInstance = userService.getInstance()\n try:\n state = userServiceInstance.setReady()\n except Exception as e:\n logger.warn('Could not check readyness of %s: %s', userService, e)\n return False\n\n logger.debug('State: %s', state)\n\n if state == State.FINISHED:\n userService.updateData(userServiceInstance)\n return True\n\n userService.setState(State.PREPARING)\n UserServiceOpChecker.makeUnique(userService, userServiceInstance, state)\n\n return False\n\n def reset(self, userService: UserService) -> None:\n userService.refresh_from_db()\n\n if not userService.deployed_service.service.getType().canReset:\n return\n\n operationsLogger.info('Reseting %s', userService)\n\n userServiceInstance = userService.getInstance()\n try:\n userServiceInstance.reset()\n except Exception:\n logger.exception('Reseting service')\n\n def notifyPreconnect(\n self, userService: UserService, userName: str, protocol: str\n ) -> None:\n comms.notifyPreconnect(userService, userName, protocol)\n\n def checkUuid(self, userService: UserService) -> bool:\n return comms.checkUuid(userService)\n\n def requestScreenshot(self, userService: UserService) -> bytes:\n return comms.requestScreenshot(userService)\n\n def sendScript(\n self, userService: UserService, script: str, forUser: bool = False\n ) -> None:\n comms.sendScript(userService, script, forUser)\n\n def requestLogoff(self, userService: UserService) -> None:\n comms.requestLogoff(userService)\n\n def sendMessage(self, userService: UserService, message: str) -> None:\n comms.sendMessage(userService, message)\n\n def checkForRemoval(self, userService: UserService) -> None:\n \"\"\"\n This method is used by UserService when a request for setInUse(False) is made\n This checks that the service can continue existing or not\n \"\"\"\n osManager = userService.deployed_service.osmanager\n # If os manager says \"machine is persistent\", do not try to delete \"previous version\" assigned machines\n doPublicationCleanup = (\n True if not osManager else not osManager.getInstance().isPersistent()\n )\n\n if doPublicationCleanup:\n remove = False\n with transaction.atomic():\n userService = UserService.objects.select_for_update().get(\n id=userService.id\n )\n activePublication = userService.deployed_service.activePublication()\n if (\n userService.publication\n and activePublication\n and userService.publication.id != activePublication.id\n ):\n logger.debug(\n 'Old revision of user service, marking as removable: %s',\n userService,\n )\n remove = True\n\n if remove:\n userService.remove()\n\n def notifyReadyFromOsManager(\n self, userService: UserService, data: typing.Any\n ) -> None:\n try:\n userServiceInstance = userService.getInstance()\n logger.debug('Notifying user service ready state')\n state = userServiceInstance.notifyReadyFromOsManager(data)\n logger.debug('State: %s', state)\n if state == State.FINISHED:\n userService.updateData(userServiceInstance)\n logger.debug('Service is now ready')\n elif userService.state in (\n State.USABLE,\n State.PREPARING,\n ): # We don't want to get active deleting or deleted machines...\n userService.setState(State.PREPARING)\n UserServiceOpChecker.makeUnique(userService, userServiceInstance, state)\n userService.save(update_fields=['os_state'])\n except Exception as e:\n logger.exception('Unhandled exception on notyfyReady: %s', e)\n userService.setState(State.ERROR)\n return\n\n def locateUserService(\n self, user: User, idService: str, create: bool = False\n ) -> typing.Optional[UserService]:\n kind, uuidService = idService[0], idService[1:]\n\n logger.debug('Kind of service: %s, idService: %s', kind, uuidService)\n userService: typing.Optional[UserService] = None\n\n if kind in 'A': # This is an assigned service\n logger.debug('Getting A service %s', uuidService)\n userService = UserService.objects.get(uuid=uuidService, user=user)\n typing.cast(UserService, userService).deployed_service.validateUser(user)\n else:\n try:\n servicePool: ServicePool = ServicePool.objects.get(uuid=uuidService)\n # We first do a sanity check for this, if the user has access to this service\n # If it fails, will raise an exception\n servicePool.validateUser(user)\n\n # Now we have to locate an instance of the service, so we can assign it to user.\n if (\n create\n ): # getAssignation, if no assignation is found, tries to create one\n userService = self.getAssignationForUser(servicePool, user)\n else: # Sometimes maybe we only need to locate the existint user service\n userService = self.getExistingAssignationForUser(servicePool, user)\n except ServicePool.DoesNotExist:\n logger.debug('Service pool does not exist')\n return None\n\n logger.debug('Found service: %s', userService)\n\n if userService and userService.state == State.ERROR:\n return None\n\n return userService\n\n def getService( # pylint: disable=too-many-locals, too-many-branches, too-many-statements\n self,\n user: User,\n os: DetectedOsInfo,\n srcIp: str,\n idService: str,\n idTransport: typing.Optional[str],\n doTest: bool = True,\n clientHostname: typing.Optional[str] = None,\n ) -> typing.Tuple[\n typing.Optional[str],\n UserService,\n typing.Optional['services.UserDeployment'],\n Transport,\n typing.Optional[transports.Transport],\n ]:\n \"\"\"\n Get service info from user service\n \"\"\"\n if idService[0] == 'M': # Meta pool\n return self.getMeta(user, srcIp, os, idService[1:], idTransport or '')\n\n userService = self.locateUserService(user, idService, create=True)\n\n if not userService:\n raise InvalidServiceException(\n _(\n 'Invalid service. The service is not available at this moment. Please, try later'\n )\n )\n\n # Early log of \"access try\" so we can imagine what is going on\n userService.setConnectionSource(srcIp, clientHostname or srcIp)\n\n if userService.isInMaintenance():\n raise ServiceInMaintenanceMode()\n\n if not userService.deployed_service.isAccessAllowed():\n raise ServiceAccessDeniedByCalendar()\n\n if not idTransport: # Find a suitable transport\n t: Transport\n for t in userService.deployed_service.transports.order_by('priority'):\n typeTrans = t.getType()\n if (\n typeTrans\n and t.validForIp(srcIp)\n and typeTrans.supportsOs(os.os)\n and t.validForOs(os.os)\n ):\n idTransport = t.uuid\n break\n\n try:\n transport: Transport = Transport.objects.get(uuid=idTransport)\n except Exception:\n raise InvalidServiceException()\n\n # Ensures that the transport is allowed for this service\n if userService.deployed_service.transports.filter(id=transport.id).count() == 0:\n raise InvalidServiceException()\n\n # If transport is not available for the request IP...\n if not transport.validForIp(srcIp):\n msg = _('The requested transport {} is not valid for {}').format(\n transport.name, srcIp\n )\n logger.error(msg)\n raise InvalidServiceException(msg)\n\n userName = user.name if user else 'unknown'\n\n if not doTest:\n # traceLogger.info('GOT service \"{}\" for user \"{}\" with transport \"{}\" (NOT TESTED)'.format(userService.name, userName, trans.name))\n return None, userService, None, transport, None\n\n serviceNotReadyCode = 0x0001\n ip = 'unknown'\n # Test if the service is ready\n if userService.isReady():\n serviceNotReadyCode = 0x0002\n log.doLog(\n userService,\n log.INFO,\n \"User {0} from {1} has initiated access\".format(user.name, srcIp),\n log.WEB,\n )\n # If ready, show transport for this service, if also ready ofc\n userServiceInstance = userService.getInstance()\n ip = userServiceInstance.getIp()\n userService.logIP(ip) # Update known ip\n logger.debug('IP: %s', ip)\n\n if (\n self.checkUuid(userService) is False\n ): # The service is not the expected one\n serviceNotReadyCode = 0x0004\n log.doLog(\n userService,\n log.WARN,\n \"User service is not accessible due to invalid UUID (ip {0})\".format(\n ip\n ),\n log.TRANSPORT,\n )\n logger.debug('UUID check failed for user service %s', userService)\n else:\n events.addEvent(\n userService.deployed_service,\n events.ET_ACCESS,\n username=userName,\n srcip=srcIp,\n dstip=ip,\n uniqueid=userService.unique_id,\n )\n if ip:\n serviceNotReadyCode = 0x0003\n transportInstance = transport.getInstance()\n if transportInstance.isAvailableFor(userService, ip):\n # userService.setConnectionSource(srcIp, 'unknown')\n log.doLog(userService, log.INFO, \"User service ready\", log.WEB)\n self.notifyPreconnect(\n userService,\n transportInstance.processedUser(userService, user),\n transportInstance.protocol,\n )\n traceLogger.info(\n 'READY on service \"%s\" for user \"%s\" with transport \"%s\" (ip:%s)',\n userService.name,\n userName,\n transport.name,\n ip,\n )\n return (\n ip,\n userService,\n userServiceInstance,\n transport,\n transportInstance,\n )\n\n message = transportInstance.getCustomAvailableErrorMsg(\n userService, ip\n )\n log.doLog(userService, log.WARN, message, log.TRANSPORT)\n logger.debug(\n 'Transport is not ready for user service %s: %s',\n userService,\n message,\n )\n else:\n logger.debug('Ip not available from user service %s', userService)\n else:\n log.doLog(\n userService,\n log.WARN,\n \"User {} from {} tried to access, but service was not ready\".format(\n user.name, srcIp\n ),\n log.WEB,\n )\n\n traceLogger.error(\n 'ERROR %s on service \"%s\" for user \"%s\" with transport \"%s\" (ip:%s)',\n serviceNotReadyCode,\n userService.name,\n userName,\n transport.name,\n ip,\n )\n raise ServiceNotReadyError(\n code=serviceNotReadyCode, userService=userService, transport=transport\n )\n\n def isMetaService(self, metaId: str) -> bool:\n return metaId[0] == 'M'\n\n def locateMetaService(\n self, user: User, idService: str\n ) -> typing.Optional[UserService]:\n kind, uuidMetapool = idService[0], idService[1:]\n if kind != 'M':\n return None\n\n meta: MetaPool = MetaPool.objects.get(uuid=uuidMetapool)\n # Get pool members. Just pools \"visible\" and \"usable\"\n pools = [\n p.pool\n for p in meta.members.all()\n if p.pool.isVisible() and p.pool.isUsable()\n ]\n # look for an existing user service in the pool\n try:\n return UserService.objects.filter(\n deployed_service__in=pools,\n state__in=State.VALID_STATES,\n user=user,\n cache_level=0,\n ).order_by('deployed_service__name')[0]\n except IndexError:\n return None\n\n def getMeta(\n self,\n user: User,\n srcIp: str,\n os: DetectedOsInfo,\n idMetaPool: str,\n idTransport: str,\n clientHostName: typing.Optional[str] = None,\n ) -> typing.Tuple[\n typing.Optional[str],\n UserService,\n typing.Optional['services.UserDeployment'],\n Transport,\n typing.Optional[transports.Transport],\n ]:\n logger.debug('This is meta')\n # We need to locate the service pool related to this meta, and also the transport\n # First, locate if there is a service in any pool associated with this metapool\n meta: MetaPool = MetaPool.objects.get(uuid=idMetaPool)\n\n # If access is denied by calendar...\n if meta.isAccessAllowed() is False:\n raise ServiceAccessDeniedByCalendar()\n\n # Get pool members. Just pools \"visible\" and \"usable\"\n poolMembers = [\n p for p in meta.members.all() if p.pool.isVisible() and p.pool.isUsable()\n ]\n # Sort pools array. List of tuples with (priority, pool)\n sortPools: typing.List[typing.Tuple[int, ServicePool]]\n # Sort pools based on meta selection\n if meta.policy == MetaPool.PRIORITY_POOL:\n sortPools = [(p.priority, p.pool) for p in poolMembers]\n elif meta.policy == MetaPool.MOST_AVAILABLE_BY_NUMBER:\n sortPools = [(p.pool.usage(), p.pool) for p in poolMembers]\n else:\n sortPools = [\n (random.randint(0, 10000), p.pool) for p in poolMembers # nosec: just a suffle, not a crypto (to get a round robin-like behavior)\n ] # Just shuffle them\n\n # Sort pools related to policy now, and xtract only pools, not sort keys\n # split resuult in two lists, 100% full and not 100% full\n # Remove \"full\" pools (100%) from result and pools in maintenance mode, not ready pools, etc...\n sortedPools = sorted(sortPools, key=operator.itemgetter(0)) # sort by priority (first element)\n pools: typing.List[ServicePool] = [\n p[1] for p in sortedPools if p[1].usage() < 100 and p[1].isUsable()\n ]\n poolsFull: typing.List[ServicePool] = [\n p[1] for p in sortedPools if p[1].usage() == 100 and p[1].isUsable()\n ]\n\n logger.debug('Pools: %s/%s', pools, poolsFull)\n\n usable: typing.Optional[typing.Tuple[ServicePool, Transport]] = None\n # Now, Lets find first if there is one assigned in ANY pool\n\n def ensureTransport(\n pool: ServicePool,\n ) -> typing.Optional[typing.Tuple[ServicePool, Transport]]:\n found = None\n t: Transport\n if idTransport == 'meta': # Autoselected:\n q = pool.transports.all()\n elif idTransport[:6] == 'LABEL:':\n q = pool.transports.filter(label=idTransport[6:])\n else:\n q = pool.transports.filter(uuid=idTransport)\n for t in q.order_by('priority'):\n typeTrans = t.getType()\n if (\n typeTrans\n and t.getType()\n and t.validForIp(srcIp)\n and typeTrans.supportsOs(os.os)\n and t.validForOs(os.os)\n ):\n found = (pool, t)\n break\n return found\n\n try:\n # Already assigned should look for in all usable pools, not only \"non-full\" ones\n alreadyAssigned: UserService = UserService.objects.filter(\n deployed_service__in=pools + poolsFull,\n state__in=State.VALID_STATES,\n user=user,\n cache_level=0,\n ).order_by('deployed_service__name')[\n 0 # type: ignore # Slicing is not supported by pylance right now\n ]\n logger.debug('Already assigned %s', alreadyAssigned)\n # If already assigned, and HA is enabled, check if it is accessible\n if meta.ha_policy == MetaPool.HA_POLICY_ENABLED:\n # Check that servide is accessible\n if not alreadyAssigned.deployed_service.service.getInstance().isAvailable(): # Not available, mark for removal\n alreadyAssigned.release()\n raise Exception() # And process a new access\n\n # Ensure transport is available for the OS, and store it\n usable = ensureTransport(alreadyAssigned.deployed_service)\n # Found already assigned, ensure everythinf is fine\n if usable:\n return self.getService(\n user,\n os,\n srcIp,\n 'F' + usable[0].uuid,\n usable[1].uuid,\n doTest=False,\n clientHostname=clientHostName,\n )\n\n except Exception: # No service already assigned, lets find a suitable one\n for (\n pool\n ) in pools: # Pools are already sorted, and \"full\" pools are filtered out\n if meta.ha_policy == MetaPool.HA_POLICY_ENABLED:\n # If not available, skip it\n if pool.service.getInstance().isAvailable() is False:\n continue\n\n # Ensure transport is available for the OS\n usable = ensureTransport(pool)\n\n # Stop if a pool-transport is found and can be assigned to user\n if usable:\n try:\n usable[0].validateUser(user)\n return self.getService(\n user,\n os,\n srcIp,\n 'F' + usable[0].uuid,\n usable[1].uuid,\n doTest=False,\n clientHostname=clientHostName,\n )\n except Exception as e:\n logger.info(\n 'Meta service %s:%s could not be assigned, trying a new one',\n usable[0].name,\n e,\n )\n usable = None\n\n log.doLog(\n meta,\n log.WARN,\n \"No user service accessible from device (ip {}, os: {})\".format(\n srcIp, os.os.name\n ),\n log.SERVICE,\n )\n raise InvalidServiceException(\n _('The service is not accessible from this device')\n )\n","sub_path":"server/src/uds/core/managers/user_service.py","file_name":"user_service.py","file_ext":"py","file_size_in_byte":44318,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"550002764","text":"l=[]\nwhile True:\n j=input()\n if j =='q' or j=='Q':\n break\n else:\n l.append(j)\nb=l.count('-')\nt=len(l)\ns=len(set(l))\nprint(b)\nprint(t)\nprint(s)\n","sub_path":"programmingInPython/sghres.py","file_name":"sghres.py","file_ext":"py","file_size_in_byte":166,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"16850894","text":"from __future__ import division, print_function, absolute_import\nimport selfsup\nimport tensorflow as tf\nimport os\nfrom .base import Method\nfrom autocolorize.tensorflow.sparse_extractor import sparse_extractor\nfrom autocolorize.extraction import calc_rgb_from_hue_chroma\nimport functools\nfrom collections import OrderedDict\n\n\nclass ColorizeHypercolumn(Method):\n def __init__(self, name, basenet, loader, use_scalers=False, hypercolumn_scales=None, version=1):\n self.name = name\n self._loader = loader\n self.basenet = basenet\n self.locations = 256\n self.edge_buffer = 32\n self.bins = 32\n self._use_scalers = use_scalers\n self._version = version\n self._label_scale = 1.0\n self._hypercolumn_scales = hypercolumn_scales\n\n @property\n def basenet_settings(self):\n return {'convolutional': True}\n\n def batch(self):\n #input_size = self.basenet.canonical_input_size\n x, _ = self._loader.batch()\n\n input_size = x.get_shape().as_list()[1]\n\n self.centroids = tf.to_float(tf.random_uniform(\n shape=[self._loader.batch_size, self.locations, 2],\n minval=self.edge_buffer,\n maxval=input_size - self.edge_buffer,\n name='centroids',\n dtype=tf.int32))\n\n gray_single = tf.reduce_mean(x, 3, keep_dims=True)\n gray = tf.tile(gray_single, [1, 1, 1, 3])\n\n if self._label_scale > 1.0:\n w = input_size // int(self._label_scale)\n x4 = tf.image.resize_bilinear(x, (w, w))\n else:\n x4 = x\n\n hsv = tf.image.rgb_to_hsv(x4)\n\n self.hue = tf.expand_dims(hsv[..., 0], -1)\n self.chr = tf.reduce_max(x4, 3, keep_dims=True) - tf.reduce_min(x4, 3, keep_dims=True)\n\n #self.chr = tf.reduce_mean(x, 3, keep_dims=True)\n\n self.huechr = tf.concat([self.hue, self.chr], 3)\n\n return gray, dict(grayscale=gray_single, hsv=hsv), #, imgshape, imgname\n\n def build_network(self, basenet_info, extra, phase_test, global_step):\n info = selfsup.info.create(scale_summary=True)\n\n hyper = []\n\n dropout = functools.partial(selfsup.ops.dropout, phase_test=phase_test, info=info)\n\n with tf.name_scope('hypercolumn'):\n layers = self.basenet.hypercolumn_layers\n if self._version == 2:\n layers = layers[4:]\n for name, scale in layers:\n sparse_layer = sparse_extractor(self.centroids,\n basenet_info['activations'][name],\n scale, [0.0, 0.0])\n if self._use_scalers:\n sparse_layer = selfsup.ops.scale(sparse_layer, name=name+'/scale',\n value=self._hypercolumn_scales.get(name))\n elif self._hypercolumn_scales is not None:\n if name in self._hypercolumn_scales:\n sparse_layer *= self._hypercolumn_scales[name]\n\n hyper.append(sparse_layer)\n\n flat_x = tf.concat(hyper, 1, name='concat')\n info['activations']['hypercolumn'] = flat_x\n\n flat_h = selfsup.ops.inner(flat_x, 1024, stddev=0.0001, info=info, name='pre_h_fc1')\n flat_h = dropout(flat_h, 0.5, name='h_fc1')\n\n z_hue = selfsup.ops.inner(flat_h, self.bins, activation=None, info=info, name='hue')\n z_chr = selfsup.ops.inner(flat_h, self.bins, activation=None, info=info, name='chroma')\n\n with tf.name_scope('sparse_y'):\n y_huechr = sparse_extractor(self.centroids, self.huechr, self._label_scale, [0.0, 0.0])\n y_hue, y_chr = tf.unstack(tf.to_int32(y_huechr * self.bins * 0.99999), axis=1)\n\n with tf.variable_scope('primary_loss'):\n loss_chr_each = tf.nn.sparse_softmax_cross_entropy_with_logits(labels=y_chr, logits=z_chr)\n loss_hue_each = tf.multiply(5 * y_huechr[..., 1], tf.nn.sparse_softmax_cross_entropy_with_logits(labels=y_hue, logits=z_hue), name='foo')\n hue_loss = tf.reduce_mean(loss_hue_each)\n chr_loss = tf.reduce_mean(loss_chr_each)\n primary_loss = hue_loss + chr_loss\n\n l2_layers = [\n info['weights']['pre_h_fc1:weights'],\n info['weights']['hue:weights'],\n info['weights']['chroma:weights'],\n ]\n with tf.name_scope('weight_decay'):\n wd = 1e-6\n l2_loss = tf.add_n([\n tf.nn.l2_loss(v) for v in l2_layers\n ])\n weight_decay = wd * l2_loss\n\n with tf.name_scope('loss'):\n loss = weight_decay + primary_loss\n\n\n self._losses = OrderedDict([\n ('hue', hue_loss),\n ('chr', chr_loss),\n ('+weight_decay', weight_decay),\n ])\n self._primary_loss = primary_loss\n self._loss = loss\n\n variables = info['vars']\n\n info['activations']['y_hue'] = y_hue\n info['activations']['y_chr'] = y_chr\n info['activations']['z_hue'] = z_hue\n info['activations']['z_chr'] = z_chr\n\n self.feedback_variables = [\n #extra['grayscale'],\n #tf.nn.softmax(z_hue),\n #tf.nn.softmax(z_chr),\n ]\n\n info['activations']['hue'] = self.huechr[..., 0]\n info['activations']['chr'] = self.huechr[..., 1]\n info['activations']['centroids'] = self.centroids\n info['activations']['primary_loss'] = primary_loss\n info['activations']['loss'] = loss\n info['activations']['weight_decay'] = weight_decay\n return info\n\n def feedback(self, variables, iteration):\n \"\"\"\n rgb = calc_rgb_from_hue_chroma(variables[0], variables[1], variables[2])\n\n vzlog.ColorImageGrid([\n rgb[:3]\n ], rows=1, vmin=0, vmax=1).save(self.make_path('hue', 'png'))\n \"\"\"\n\n @property\n def losses(self):\n return self._losses\n\n @property\n def primary_loss(self):\n return self._primary_loss\n\n @property\n def loss(self):\n return self._loss\n\n","sub_path":"selfsup/multi/methods/colorize_hypercolumn.py","file_name":"colorize_hypercolumn.py","file_ext":"py","file_size_in_byte":6125,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"323155097","text":"MAP_SIZE_PIXELS = 500\nMAP_SIZE_METERS = 10\nLIDAR_DEVICE = '/dev/ttyACM0'\n\nfrom breezyslam.algorithms import RMHC_SLAM\nfrom breezyslam.components import URG04LX as LaserModel\nimport serial\nfrom hokuyo.driver import hokuyo\nfrom hokuyo.tools import serial_port\n\nuart_port = '/dev/tty.usbmodem1421'\nuart_speed = 19200\n\n\nfrom cvslamshow import SlamShow\n \nif __name__ == '__main__':\n\n # Connect to Lidar unit\n laser_serial = serial.Serial(port=uart_port, baudrate=uart_speed, timeout=0.5)\n port = serial_port.SerialPort(laser_serial)\n\n lidar = hokuyo.Hokuyo(port)\n\n # Create an RMHC SLAM object with a laser model and optional robot model\n slam = RMHC_SLAM(LaserModel(), MAP_SIZE_PIXELS, MAP_SIZE_METERS)\n\n # Set up a SLAM display\n display = SlamShow(MAP_SIZE_PIXELS, MAP_SIZE_METERS*1000/MAP_SIZE_PIXELS, 'SLAM')\n\n # Initialize an empty trajectory\n trajectory = []\n\n # Initialize empty map\n mapbytes = bytearray(MAP_SIZE_PIXELS * MAP_SIZE_PIXELS)\n\n lidar.reset()\n lidar.laser_on()\n \n while True:\n\n # Update SLAM with current Lidar scan\n slam.update(lidar.getScan())\n\n # Get current robot position\n x, y, theta = slam.getpos()\n\n # Get current map bytes as grayscale\n slam.getmap(mapbytes)\n\n display.displayMap(mapbytes)\n\n display.displayRobot((x, y, theta))\n\n trajectory.append((x,y))\n\n # Display trajectory\n display.displayTrajectory(trajectory)\n\n # Exit on ESCape\n key = display.refresh()\n if key != None and (key&0x1A):\n exit(0)\n \n","sub_path":"Old Code/Dinosaur Code/slam_test.py","file_name":"slam_test.py","file_ext":"py","file_size_in_byte":1622,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"142536555","text":"import codecs\nimport time\nimport re\nfrom web3 import Web3, HTTPProvider\nfrom optparse import OptionParser\n\n\n# python .\\test.py -C \"0xbe865d289C3FFB28DC3e843e41Ba18E922d7093a\"\n\n###\n### OPTIONS DEFINITION\n###\n\nparser = OptionParser()\nparser.add_option(\"-C\", '--contract-address', dest='contract_address', help='REQUIRE Address of contract', )\n# parser.add_option(\"--B\", '--begin', dest='begin')\n# parser.add_option(\"--E\",\"--end\", dest='end')\n\n(options, args) = parser.parse_args()\n\n###\n### CONFIGURATION OF ADDRESS AND TOKEN KEY\n###\n\nweb3 = Web3(HTTPProvider('https://ropsten.infura.io/i3YOB8MSt4RYUoP5ThiG'))\n\nweb3.eth.enable_unaudited_features()\n\n\n# contract_addr = \"0xbe865d289C3FFB28DC3e843e41Ba18E922d7093a\" # token whale challenge instance\ncontract_address = web3.toChecksumAddress(options.contract_address)\nwallet_private_key = 0x21d7f3e28cd3e45aabe68f5bcc4cd9ecbad10750f86375683f2f524f2c4ce401\nwallet_addr = 0xaE0A9bC7fB8Caf0AD1374a21eB35662b5964765C\n\n\n\ndef elementType(typ):\n IntList = ['int', 'int8', 'int16', 'int24', 'int32', 'int40', 'int48', 'int56', 'int64', 'int72'\n , 'int80', 'int88', 'int96', 'int104', 'int112', 'int120', 'int128', 'int136', 'int144'\n , 'int152', 'int160', 'int168', 'int176', 'int184', 'int192', 'int200', 'int208', 'int216'\n , 'int224', 'int232', 'int240', 'int248', 'int256']\n UintList = ['uint', 'uint8', 'uint16', 'uint24', 'uint32'\n , 'uint40', 'uint48', 'uint56', 'uint64', 'uint72', 'uint80', 'uint88', 'uint96', 'uint104'\n , 'uint112', 'uint120', 'uint128', 'uint136', 'uint144', 'uint152', 'uint160', 'uint168'\n , 'uint176', 'uint184', 'uint192', 'uint200', 'uint208', 'uint216', 'uint224', 'uint232'\n , 'uint240', 'uint248', 'uint256']\n ByteList = ['bytes', 'bytes1', 'bytes2', 'bytes3', 'bytes4', 'bytes5', 'bytes6', 'bytes7', 'bytes8'\n , 'bytes9', 'bytes10', 'bytes11', 'bytes12', 'bytes13', 'bytes14', 'bytes15', 'bytes16'\n , 'bytes17', 'bytes18', 'bytes19', 'bytes20', 'bytes21', 'bytes22', 'bytes23', 'bytes24'\n , 'bytes25', 'bytes26', 'bytes27', 'bytes28', 'bytes29', 'bytes30', 'bytes31', 'bytes32']\n if typ in IntList:\n return \"Int\"\n elif typ in UintList:\n return \"Uint\"\n elif typ in ByteList:\n return \"Byte\"\n elif re.match(r'fixed[0-9]+x[0-9]+', typ):\n return \"Fixed\"\n elif re.match(r'ufixed[0-9]+x[0-9]+', typ):\n return \"Ufixed\"\n else:\n return typ\n\n# def userDefinedTyp(typ):\n#\n# def functionTyp(typ):\n\ndef valueOf(index, typ):\n if elementType(typ) == \"string\":\n return str(web3.toHex(web3.eth.getStorageAt(contract_address, index)))\n elif elementType(typ) == \"Uint\" or elementType(typ) == \"Int\":\n return web3.toInt(web3.eth.getStorageAt(contract_address , index))\n elif elementType(typ) == \"bool\":\n return bool(web3.toInt(web3.eth.getStorageAt(contract_address, index)))\n elif elementType(typ) == \"address\":\n return str(web3.toHex(web3.eth.getStorageAt(contract_address, index)))\n elif elementType(typ) == \"byte\":\n return web3.toBytes(web3.eth.getStorageAt(contract_address, index))\n\ndef getStorage(start = 0, stop = 10):\n\n print ('Get storage of contract ' + str(contract_address) + ' from index ' + str(start) + ' to ' + str(stop))\n for index in range (start,stop) :\n tmp = web3.eth.getStorageAt(contract_address, index)\n # tmpstr = str(web3.toHex(tmp))\n print(str(index) + \" : \" + str(web3.toHex(tmp)) )\n\ndef mapping(slot, key):\n print(web3.eth.getBlock(3230012))\n index = Web3.toInt(Web3.soliditySha3('0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001a'))\n # print(str(index))\n tmp = web3.eth.getStorageAt(contract_address, 0xc206ffad34fd371168d5316b8ab2a6f30eac6909fb16834ecb53c364217791d7)\n print(str(web3.toHex(tmp)))\n return web3.toHex(tmp)\n\n\nif __name__ == '__main__':\n # begin = options.begin\n # end = options.end\n getStorage()\n # mapping(24, 0)\n\n# 0xece0dd04f4bbaa1cb58bd45bbcd02f611983da8808cbe2937e8f08de1502a8a1","sub_path":"src/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":4179,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"92096600","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Fri Jan 3 17:14:10 2020\r\n\r\n@author: Miguel\r\n\"\"\"\r\nimport numpy as np\r\nfrom abc import abstractmethod\r\nclass Tree:\r\n \r\n \"\"\"\r\n This classes define the weight distributions and the gravity and forces\r\n acting over a simplified pine. \r\n \r\n Inclination and pulling point are considered to evaluate pulley systems inputs.\r\n \r\n @inclination: maximum vertical inclination, degrees\r\n @height: in meters. An stimation could be given by the diameter.\r\n @diameter: diameter at the ground. in centimeters\r\n @perimeter: (optional) base circumference in cm.\r\n \r\n \"\"\"\r\n def __init__(self, inclination= 0. ,diameter= None\r\n , height= None, perimeter= None):\r\n \r\n self.inclination = inclination\r\n \r\n if not diameter:\r\n if not perimeter:\r\n raise Exception(\"Perimeter or diameter are required\")\r\n self.perimeter = perimeter\r\n self.diameter = perimeter / np.pi \r\n else:\r\n self.diameter = diameter\r\n self.perimeter = np.pi * diameter\r\n \r\n self.height = height\r\n \r\n print (f\"inclination: {self.inclination}º\\ndiameter: {self.diameter} cm\",\r\n f\"\\nperimeter: {self.perimeter} cm\\nheight: {self.height} m\")\r\n \r\n @property\r\n def height(self):\r\n return self.__height\r\n \r\n @height.setter\r\n def height(self, height):\r\n if height:\r\n self.__height = float(height)\r\n else:\r\n self.__height = self.setHeigthProfile()\r\n \r\n @abstractmethod\r\n def setHeigthProfile(self):\r\n raise Exception(\"Heigth profile has to be set in the child classes\")\r\n \r\n @abstractmethod\r\n def setDensityProfile(self):\r\n raise Exception(\"Density profile has to be set in the child classes\")\r\n \r\nclass PineException(Exception):\r\n pass\r\nclass Pine(Tree):\r\n \"\"\"\r\n Class Docs. [Pine] --> [Tree]\r\n \r\n * Description of the pine model arguments:\r\n \r\n vvvvvvvvv---------------------------\r\n vvvvvvvvvvvvv ^ \r\n vvvvvvvvvvvvvvv <-- _topCentroid_z |- top_height \r\n vvvvvvvvvvv________________________v\r\n || ^ >( )< top_diameter \r\n ||\r\n || ·\r\n || |- height\r\n | | ·\r\n | |<----- centroidHeight\r\n | |<----- _trunkCentroid_z \r\n | |\r\n | |\r\n ___| |_______V__ >( )< diameter\r\n \r\n The density profile is the combination of a truncated cone for the trunk \r\n and a point like mass for the upper part, that sumarize the centroid of an\r\n homogeneous bunch of leaves and branches.\r\n \r\n The density considered for the wood could be normal or lower if the pine \r\n is dead and partialy rotten.\r\n \r\n Args:\r\n =========================================================\r\n * :inclination: [deg] Angle between the trunk and the vertical\r\n * :diameter: [cm] Diameter at the base\r\n * :top_diameter: [cm] Diameter of the trunk before the begining of the branches\r\n * :height: [m] Height of the trunk before the begining of the branches\r\n * :top_height: [m] Height of the top part of the pine.\r\n * :pineStatus: [NORMAL or ROTTEN]. Defines the expected density.\r\n \r\n =========================================================\r\n \"\"\"\r\n \r\n class PineStatus:\r\n ROTTEN = 'rotten'\r\n NORMAL = 'normal'\r\n \r\n def __init__(self, inclination= 0. ,diameter= None\r\n , height= None, perimeter= None\r\n , top_height= None, top_diameter=None\r\n , pineStatus=PineStatus.NORMAL):\r\n print(self.__doc__)\r\n print('SETTING UP PINE ...\\n')\r\n #print(\"Height goes from the ground to the begining of the branches\")\r\n super().__init__(inclination, diameter, height, perimeter)\r\n \r\n \"\"\" Definitions of the upper part parameters if they are fixed, \r\n otherwise, they are set by estimations\"\"\"\r\n self.topHeight = top_height\r\n self.topDiameter = top_diameter\r\n self.density = pineStatus\r\n \r\n self.setDensityProfile()\r\n \r\n \r\n \"\"\" TODO: Find the correct regresions for the following properties.\"\"\"\r\n \r\n @property\r\n def density(self):\r\n return self.__density\r\n @density.setter\r\n def density(self, pineStatus):\r\n \"\"\" Density defined in [kg / cm3] in terms of the pine status\"\"\"\r\n if pineStatus is self.PineStatus.NORMAL:\r\n self.__density = 0.0009 \r\n elif pineStatus is self.PineStatus.ROTTEN:\r\n self.__density = 0.0007\r\n else:\r\n raise PineException(\"pineStatus can only be NORMAL or ROTTEN:\", \r\n \"got [{}]\".format(pineStatus))\r\n \r\n @property\r\n def topHeight(self):\r\n return self.__topHeight\r\n @topHeight.setter\r\n def topHeight(self, top_height):\r\n if top_height:\r\n if (top_height > self.height/3) or (top_height < self.height/6):\r\n print(\"WARNING: Very extrange pine definition\",\r\n \"top height is > 0.33 trunk heigt or < trunk height / 6\")\r\n self.__topHeight = top_height\r\n else:\r\n self.__topHeight = self.height / 4\r\n \r\n @property\r\n def topDiameter(self):\r\n return self.__topDiameter\r\n @topDiameter.setter\r\n def topDiameter(self, top_diameter):\r\n if top_diameter:\r\n if top_diameter > self.diameter:\r\n raise PineException(\"A pine cannot be more widder in the top [{} cm]\"\r\n .fotmat(top_diameter), \" than in the base[{} cm].\"\r\n .format(self.diameter))\r\n \r\n elif (top_diameter > 0.9 * self._trunkDiameter()):\r\n print(\"WARNING: Extrange pine definition, too cilindrical profile.\",\r\n \"top diameter is more than 90 % bigger than the base estimation\")\r\n elif (top_diameter < 0.5 * self._trunkDiameter()):\r\n print(\"WARNING: Extrange pine definition, too conical profile\",\r\n \"top diameter is 50 % lower than from the base estimation\")\r\n \r\n self.__topDiameter = top_diameter\r\n else:\r\n self.__topDiameter = self._trunkDiameter(h=self.height)\r\n \r\n \r\n def _trunkDiameter(self, h=7):\r\n # rough approximation:\r\n # (30 cm - 20 cm) / 7m = 10 cm / 7 m = 1.4285 cm / m\r\n return self.diameter - 1.4285 * h\r\n \r\n def _pineSystemMasses(self, trunk_mass, top_mass):\r\n self.trunk_mass = trunk_mass\r\n self.top_mass = top_mass\r\n self.totalMass = trunk_mass + top_mass\r\n \r\n def setDensityProfile(self):\r\n \"\"\" \r\n Definition of the mass distribution from the description.\r\n Inclination will be taken into account after.\r\n \r\n * Trunk is treated as a truncated cone.\r\n * The centroid of the branches will be sum into a point like mass.\r\n \r\n The centroid of the sistem will be the average sum of the two.\r\n + density is in kg/cm3\r\n + height in meters\r\n + diameters in cm\r\n \"\"\"\r\n t_volume = (self.topDiameter**2 + \r\n self.topDiameter*self.diameter +\r\n self.diameter**2) / 4\r\n self._trunkCentroid_z = (.25 * (self.height * 100)* \r\n (3 * (self.topDiameter**2) + \r\n 2 * self.topDiameter * self.diameter + \r\n self.diameter**2)) /(4 * t_volume)\r\n \r\n self._trunkCentroid_z = self._trunkCentroid_z / 100 ## in [m]\r\n trunk_mass = self.density * t_volume * np.pi * (100*self.height) / 3\r\n \r\n # the top part has the density profile of a cone:\r\n self._topCentroid_z = self.topHeight / 4\r\n # this estimation come from comparing the volume of wood from the \r\n # branches compared with the trunks. \r\n # $$pi*topH*(diam/2)**2 / 3 = 2.5'parts' * 1.5*pi*(top_diam/2)**2 $$\r\n top_mass = self.density * (294.52 * self.topDiameter**2)\r\n \r\n self._pineSystemMasses(trunk_mass, top_mass)\r\n \r\n self.centroidHeight = ((trunk_mass * self._trunkCentroid_z + \r\n top_mass * (self._topCentroid_z + self.height))\r\n / self.totalMass)\r\n \r\n self._applyInclination()\r\n \r\n def _applyInclination(self):\r\n _alpha = np.deg2rad(self.inclination)\r\n self.centroidHeight = self.centroidHeight * np.cos(_alpha)\r\n self.centroidLenght = self.centroidHeight * np.sin(_alpha) * 100\r\n \r\n if abs(self.centroidLenght) > (self.diameter / 2):\r\n print(\"\\n*WARNING !!\\n\",\r\n \"Centroid projection outside the tree basis.\\n\", \r\n f\"centroidLenght: [{self.centroidLenght} cm] \\n radius: [{.5*self.diameter} cm]\",\r\n \"\\n---------------------------------\")\r\n self.centroidProjectionInsideBase = False\r\n else:\r\n self.centroidProjectionInsideBase = True\r\n \r\n \r\n \r\n \r\n \r\n \r\nt = Pine(diameter = 30., height=7, top_diameter= 20., top_height= 2., \r\n inclination= 3. )\r\nprint(\"\\n\\nPINE RESULT DESCRIPTION:\\n========================\")\r\nprint('top_diameter\\t=',t.topDiameter)\r\nprint('top_heigth\\t=',t.topHeight)\r\nprint('----------')\r\nprint('top mass\\t=', t.top_mass)\r\nprint('trunk mass\\t=',t.trunk_mass)\r\nprint('total\\t\\t=', t.totalMass)\r\nprint('----------')\r\nprint('centroid_top\\t=',t._topCentroid_z)\r\nprint('centroid_trunk\\t=',t._trunkCentroid_z)\r\nprint()\r\nprint('centroid', t.centroidHeight)\r\n\r\n \r\n","sub_path":"Tree.py","file_name":"Tree.py","file_ext":"py","file_size_in_byte":10018,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"35022623","text":"#!usr/bin/env python\n# -*- coding: utf-8 -*-\nimport zmq\nimport os\n\n\nctx = zmq.Context()\ns = ctx.socket(zmq.REP)\ns.bind(\"tcp://*:5557\")\n\nwhile True:\n nameFile = s.recv_string()\n path = \"Server2/\" + nameFile\n with open(path,\"rb\") as f:\n contents = f.read()\n s.send(contents)\n","sub_path":"MusicServer/server2.py","file_name":"server2.py","file_ext":"py","file_size_in_byte":296,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"327597633","text":"import os\nfrom autoPyTorch.utils.config.config_option import ConfigOption, to_bool\nfrom autoPyTorch.utils.config.config_file_parser import ConfigFileParser\nfrom autoPyTorch.pipeline.base.pipeline_node import PipelineNode\n\nclass SetAutoNetConfig(PipelineNode):\n\n def fit(self, pipeline_config, autonet, autonet_config_file, data_manager, instance):\n parser = autonet.get_autonet_config_file_parser()\n config = parser.read(autonet_config_file)\n\n if ('additional_logs' not in config):\n config['additional_logs'] = ['test_result' if not pipeline_config['enable_ensemble'] else 'test_predictions_for_ensemble']\n\n if (pipeline_config['use_dataset_metric'] and data_manager.metric is not None):\n config['optimize_metric'] = data_manager.metric\n if (pipeline_config['use_dataset_max_runtime'] and data_manager.max_runtime is not None):\n config['max_runtime'] = data_manager.max_runtime\n\n if (pipeline_config['working_dir'] is not None):\n config['working_dir'] = pipeline_config['working_dir']\n if (pipeline_config['network_interface_name'] is not None):\n config['network_interface_name'] = pipeline_config['network_interface_name']\n\n config['log_level'] = pipeline_config['log_level']\n \n if data_manager.categorical_features:\n config['categorical_features'] = data_manager.categorical_features\n\n # Note: PrepareResultFolder will make a small run dependent update of the autonet_config\n autonet.update_autonet_config(**config)\n return dict()\n\n def get_pipeline_config_options(self):\n options = [\n ConfigOption(\"use_dataset_metric\", default=False, type=to_bool),\n ConfigOption(\"use_dataset_max_runtime\", default=False, type=to_bool),\n ConfigOption(\"working_dir\", default=None, type='directory'),\n ConfigOption(\"network_interface_name\", default=None, type=str)\n ]\n return options\n","sub_path":"autoPyTorch/utils/benchmarking/benchmark_pipeline/set_autonet_config.py","file_name":"set_autonet_config.py","file_ext":"py","file_size_in_byte":1997,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"2802409","text":"import cdms2\nimport MV2\n\nf = cdms2.open('/cnrm/moana/user/couvreux/GABLS4_INTERCOMPARISON_LES/POUR_OLIVIER/MESONH/24h/gabls4_instprofile_les_MESONH_stage3_zo3.nc')\npres = f('P')\nf.close()\n\nnt,nlev = pres.shape\n\nps = 65100.\n\nph = MV2.zeros((nlev+1,),typecode=MV2.float)\npf = MV2.zeros(nlev,typecode=MV2.float)\n\npf[:] = pres[0,:]\n\nph[0] = ps\n\nfor i in range(1,nlev-1):\n ph[i] = (pf[i]+pf[i+1])/2. \n\nph[nlev-1] = 59800.\nph[nlev] = 59000.\n\ntmp = [50000.,40000.,30000.,20000.,10000.,1000.,100.,0.]\n\nnlev2 = nlev+1 + len(tmp)\n\nph2 = MV2.zeros(nlev2,typecode=MV2.float)\nph2[0:nlev+1] = ph[:]\nph2[nlev+1:] = tmp[:]\n\n\na = MV2.zeros(nlev2,typecode=MV2.float)\nb = MV2.zeros(nlev2,typecode=MV2.float)\n\nb = ph2/ps\n\ng = open('L{0}.dta'.format(nlev2-1),'w')\n\nfor ilev in range(0,nlev2):\n print >>g, a[nlev2-ilev-1],b[nlev2-ilev-1]\n\ng.close()\n\n","sub_path":"examples/grid/prep_grille_GABLS4_v3.py","file_name":"prep_grille_GABLS4_v3.py","file_ext":"py","file_size_in_byte":835,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"579552278","text":"import re\nimport random\nimport logging\nfrom urlparse import urlparse\nfrom urllib import getproxies, urlopen\n\nfrom scrapy import signals\nfrom scrapy.conf import settings\nfrom scrapy.downloadermiddlewares.httpproxy import HttpProxyMiddleware\nfrom scrapy.exceptions import NotConfigured, IgnoreRequest\nfrom scrapy.http import Request\nfrom scrapy.utils.httpobj import urlparse_cached\n\nfrom brightcorp.lib import robotparser, robotparser_nikkita\n\nimport time\n\ndigit_extractor = re.compile(r'\\d+')\n\nclass ProxyMiddleware(HttpProxyMiddleware):\n \"\"\" Proxy midddleware child class of HttpProxyMiddleware\n See https://github.com/scrapy/scrapy/blob/master/scrapy/contrib/downloadermiddleware/httpproxy.py\n \"\"\"\n def __init__(self):\n self._log = logging.getLogger(self.__class__.__name__)\n # Parent class will disable the middleware when no proxy\n # is configured in the mining node (raises NotConfigured exception)\n # Just copied the constructor code and removed the exception\n self.proxies = {}\n for key, url in getproxies().items():\n self.proxies[key] = self._get_proxy(url, key)\n\n def process_request(self, request, spider):\n # Accepts the following:\n # http://user:pass@192.168.1.1:80\n # http://192.168.1.1:80\n # http://192.168.1.1\n # user:pass@192.168.1.1:80\n # user:pass@192.168.1.1\n # 192.168.1.1:80\n # 192.68.1.1\n if hasattr(spider, 'proxy') and spider.proxy != \"\":\n proxies_dict = {}\n for proxy in spider.proxy.split(','):\n auth, url = self._get_proxy(proxy, None)\n schemes = urlparse(url).scheme\n schemes = [schemes] if schemes else ['http', 'https']\n\n # Proxy urls must have 'http', 'https', 'no' scheme for them to be used by scrapy\n # Default is http and https?\n for scheme in schemes:\n if scheme in proxies_dict:\n proxies_dict[scheme].append(tuple([auth, url]))\n else:\n proxies_dict.update({scheme: [tuple([auth, url])]})\n\n # Pick a random proxy from the ones set in scrapy command\n for scheme, proxies in proxies_dict.items():\n self.proxies.update({scheme: random.choice(proxies)})\n\n if self.proxies:\n # super() handles request.meta['proxy'], needs self.proxies to have values\n super(ProxyMiddleware, self).process_request(request, spider)\n\n self._log.info(\"REQUEST META: %s\" % request.meta)\n\n\nclass RobotsTxtMiddleware(object):\n \"\"\"\n This is a middleware to respect robots.txt policies. To activate it you must\n enable this middleware and enable the ROBOTSTXT_OBEY setting.\n \"\"\"\n DOWNLOAD_PRIORITY = 1000\n\n def __init__(self, crawler):\n self._log = logging.getLogger(self.__class__.__name__)\n if not crawler.settings.getbool('ROBOTSTXT_OBEY'):\n raise NotConfigured\n\n self.crawler = crawler\n self._useragent = crawler.settings.get('USER_AGENT')\n self._parsers = {}\n\n @classmethod\n def from_crawler(cls, crawler):\n return cls(crawler)\n\n def process_request(self, request, spider):\n if request.meta.get('dont_obey_robotstxt'):\n return\n rp = self.robot_parser(request, spider)\n if rp and not rp.can_fetch(self._useragent, request.url):\n self._log.info(\"Forbidden by robots.txt: %s\", request.url)\n self._log.debug(\"Robots.txt is %s\", str(rp))\n raise IgnoreRequest\n\n def robot_parser(self, request, spider):\n url = urlparse_cached(request)\n netloc = url.netloc\n if netloc not in self._parsers:\n self._parsers[netloc] = None\n robotsurl = \"%s://%s/robots.txt\" % (url.scheme, url.netloc)\n if hasattr(spider, 'load_robots_separate') and getattr(spider, 'load_robots_separate'):\n self._parse_robots_txt(robotsurl, urlopen(robotsurl).readlines())\n else:\n robotsreq = Request(\n robotsurl,\n priority=self.DOWNLOAD_PRIORITY,\n meta={'dont_obey_robotstxt': True}\n )\n dfd = self.crawler.engine.download(robotsreq, spider)\n dfd.addCallback(self._parse_robots)\n return self._parsers[netloc]\n\n def _parse_robots(self, response):\n #rp = robotparser.RobotFileParser(response.url)\n rp = robotparser_nikkita.RobotFileParserLookalike(response.url)\n rp.parse(response.body.splitlines())\n self._parsers[urlparse_cached(response).netloc] = rp\n\n def _parse_robots_txt(self, url, txt):\n rp = robotparser.RobotFileParser(url)\n rp.parse(txt)\n self._parsers[urlparse(url).netloc] = rp\n\n\nclass FullLogMiddleware(object):\n def __init__(self, crawler):\n self.crawler = crawler\n # if running in prod we also want ot start a debug level logger\n # we could consider moving this to spider_opened and spider_closed\n # that would give us access to spider.management node to verify we are on prod\n \"\"\"if settings.get('PROD_RUN') and settings['LOG_FILE']:\n sflo = scrapy.log.start(settings['LOG_FILE'].replace('.log', '_full.log'),\n scrapy.log.DEBUG, settings['LOG_STDOUT'], settings['LOG_ENCODING'],\n self.crawler)\n crawler.signals.connect(sflo.stop, signals.engine_stopped)\n \"\"\"\n if settings.get('PROD_RUN') and settings['LOG_FILE']:\n d_log_file = settings['LOG_FILE'].replace('.log', '_full.log')\n logging.info(\"Adding a different debug level logger at %s\" % d_log_file)\n # create file handler which logs debug level to *_full.log\n d_logger = logging.FileHandler(d_log_file)\n d_logger.setLevel(logging.DEBUG)\n # create formatter with existing log setting\n formatter = logging.Formatter(settings['LOG_FORMAT'], settings['LOG_DATEFORMAT'])\n d_logger.setFormatter(formatter)\n # add the handler to the root logger\n logging.getLogger().addHandler(d_logger)\n\n @classmethod\n def from_crawler(cls, crawler):\n return cls(crawler)\n\nclass BrightStats(object):\n \"\"\"aggregate stats about jobs scraped\n\n We could implement this as an extension by creating an ItemPipeline\n since for now we focus on item level pipeline.\n\n This approach enables more flexible logging of stats at the end.\n To cleanup keys into sub heirarchies\n \"\"\"\n\n PATTERNS = {\n 'item': re.compile('(?Pitem)\\|(?P[^|]+)\\|(?P.+)')\n }\n\n ROLLUP_FIELDS = {}\n\n def __init__(self, stats):\n self._log = logging.getLogger(self.__class__.__name__)\n self.stats = stats\n\n @classmethod\n def from_crawler(cls, crawler):\n o = cls(crawler.stats)\n\n # extract command line settings in format -s brightstats=key:count,key:count,key,key\n brightstats_settings = crawler.settings.get('brightstats') or crawler.settings.get('BRIGHT_STATS')\n if brightstats_settings:\n for k, _, v in [f.partition(':') for f in brightstats_settings.split(',')]:\n o.ROLLUP_FIELDS[k]= int(v) if v else -1\n o.ROLLUP_KEYS = o.ROLLUP_FIELDS.keys()\n logging.info('brightstats settings %s' % o.ROLLUP_FIELDS)\n\n # connect to signals\n crawler.signals.connect(o.spider_opened, signal=signals.spider_opened)\n crawler.signals.connect(o.spider_closed, signal=signals.spider_closed)\n crawler.signals.connect(o.item_scraped, signal=signals.item_scraped)\n crawler.signals.connect(o.item_dropped, signal=signals.item_dropped)\n crawler.signals.connect(o.response_received, signal=signals.response_received)\n crawler.signals.connect(o.spider_error, signal=signals.spider_error)\n return o\n\n def spider_opened(self, spider):\n pass\n\n def spider_closed(self, spider, reason):\n # re-aggregate stats\n all_stats = spider.crawler.stats.get_stats()\n # convert all_stats fields like 'item|company|Acme = 10' and 'item|location|CA = 100' to\n # {company: {Acme: 10}, location: {CA: 100}}\n # then we can select top n by field according to ROLLUP_FIELDS dict\n item_stats = {}\n for kv in filter(None, [self.PATTERNS['item'].match(k) for k in all_stats.keys()]):\n f = kv.group('field')\n v = kv.group('value')\n if f in item_stats:\n item_stats[f][v] = all_stats[kv.string]\n else:\n item_stats[f] = {v: all_stats[kv.string]}\n del all_stats[kv.string]\n # get total uniques per tracked field\n fields = item_stats.keys()\n all_stats['item_uniques'] = {field: len(item_stats[field]) for field in fields}\n # limit some fields to just the top n results\n for field in [f for f in fields if self.ROLLUP_FIELDS.get(f, -1) > 0]:\n item_stats[field] = sorted(item_stats[field].items(),\n key=lambda x: x[1],\n reverse=True)[:10]\n all_stats['item_stats'] = item_stats\n if spider.time_limit is not None:\n all_stats['time_limit'] = spider.time_limit\n self._set_expected(all_stats, spider)\n spider.crawler.stats.set_stats(all_stats)\n\n def _set_expected(self, all_stats, spider):\n '''\n Get total job count stats, as reported by site\n !side-effect! modifies all_stats\n '''\n if spider.expected_job_count_set:\n ec = spider.expected_job_count\n if isinstance(ec, unicode):\n all_stats['expected_job_count'] = int(''.join([str(d) for d in digit_extractor.findall(ec)]))\n else:\n all_stats['expected_job_count'] = int(ec if isinstance(ec, int) or str(ec).isdigit()\n else ''.join(digit_extractor.findall(str(ec))) or -1)\n\n def item_scraped(self, item, spider):\n for key in self.ROLLUP_KEYS:\n val = item.get(key)\n if not val:\n val = 'none'\n spider.crawler.stats.inc_value('item|%s|%s' % (key, val))\n missing_fields = self._validate_item_fields(item, spider)\n for field in missing_fields:\n spider.crawler.stats.inc_value('missing_field|%s' % field)\n if missing_fields:\n spider.crawler.stats.inc_value('missing_field_any')\n if spider.subspider_detector:\n # this will check each item and update the valid_spider value\n # so that subspider detector will know if this spider is valid or not\n spider.items_scraped_count += 1\n if spider.items_scraped_count <= spider.max_items_count:\n missing_fields = self._validate_item_fields(item, spider)\n if not missing_fields:\n spider.valid_job_count = spider.valid_job_count + 1\n if spider.valid_job_count == spider.spider_valid_cutoff:\n spider.valid_spider = True\n spider.crawler.engine.close_spider(\n spider, 'closespider_valid_spider'\n )\n elif not spider.valid_spider:\n spider.crawler.engine.close_spider(spider, 'closespider_itemcount')\n\n def response_received(self, spider):\n pass\n\n def item_dropped(self, item, spider, exception):\n pass\n\n def spider_error(self, failure, response, spider):\n pass\n\n def _validate_item_fields(self, item, spider):\n if hasattr(spider, 'validate_item_fields'):\n return spider.validate_item_fields(item)\n else:\n return []\n\n\nclass TimeLimitMiddleware(object):\n def process_request(self, request, spider):\n if hasattr(spider, 'end_time') and spider.end_time and time.time() > spider.end_time:\n logging.info(\"Canceling request due to time limit: %s\", request.url)\n raise IgnoreRequest\n\n\nclass StaleCrawlMiddleware(object):\n \"\"\"Monitors how frequently a crawler produces items and ends crawls that haven't produced jobs in a while.\n \"\"\"\n def __init__(self):\n self._log = logging.getLogger(self.__class__.__name__)\n self.last_seen = 0\n\n @classmethod\n def from_crawler(cls, crawler):\n o = cls()\n # connect to signals\n crawler.signals.connect(o.spider_opened, signal=signals.spider_opened)\n return o\n\n def spider_opened(self, spider):\n if hasattr(spider, 'stale_limit') and spider.stale_limit > 0:\n self._log.info('StaleCrawlMiddleware enabled with limit seconds %d' % spider.stale_limit)\n self.last_seen = time.time()\n spider.crawler.signals.connect(self.item_scraped, signal=signals.item_scraped)\n else:\n self._log.info('StaleCrawlMiddleware disabled')\n\n def process_request(self, request, spider):\n if self.last_seen > 0 and (time.time() - self.last_seen) > spider.stale_limit:\n self._log.info(\"Canceling request due to stale limit: %s\", request.url)\n raise IgnoreRequest\n\n def item_scraped(self, item, response, spider):\n self.last_seen = time.time()\n\n","sub_path":"brightcorp/brightcorp/middlewares.py","file_name":"middlewares.py","file_ext":"py","file_size_in_byte":13496,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"244995505","text":"# Auto assign 'good first issue' issues to user\n# When they comment '!assign' on the issue\n\nimport os\nimport sys\n\nimport requests\nimport time\n\nOWNER = \"codinasion\"\nREPO = \"hello-world\"\n\n# Get arguments from command line\nif len(sys.argv) > 1:\n REPO_TOKEN = sys.argv[1]\n if len(sys.argv) > 2:\n ISSUE_NUMBER = sys.argv[2]\n if len(sys.argv) > 3:\n USERNAME = sys.argv[3]\n else:\n print(\n \"USERNAME is required !!! \\n\\nUsage: python auto_assign_issue.py \"\n )\n else:\n print(\n \"ISSUE_NUMBER is required !!! \\n\\nUsage: python auto_assign_issue.py \"\n )\nelse:\n print(\n \"REPO_TOKEN is required !!! \\n\\nUsage: python auto_assign_issue.py \"\n )\n sys.exit(1)\n\n# Get issue data\nURL = \"https://api.github.com/repos/{}/{}/issues/{}\".format(\n OWNER, REPO, ISSUE_NUMBER)\nissue_data_request = requests.get(\n URL,\n headers={\n \"Authorization\": \"Token \" + REPO_TOKEN,\n \"Content-Type\": \"application/json\",\n },\n)\n\nif issue_data_request.status_code == 200:\n print(\"Issue data fetched successfully\")\nelse:\n print(\"==>> Issue data fetch failed :( !!!\")\n print(issue_data_request.json())\n sys.exit(1)\n\n# Get issue labels\nlabels = [label[\"name\"] for label in issue_data_request.json()[\"labels\"]]\nprint(labels)\n\n# Check if issue contains \"good first issue\" label\nif \"good first issue\" in labels:\n print(\"Issue contains 'good first issue' label\")\n\n # Check if issue is assigned to anyone\n if issue_data_request.json()[\"assignee\"] is None:\n print(\"Issue is not assigned to anyone\")\n\n # Assign issue to user\n URL = \"https://api.github.com/repos/{}/{}/issues/{}/assignees\".format(\n OWNER, REPO, ISSUE_NUMBER\n )\n assign_issue_request = requests.post(\n URL,\n headers={\n \"Authorization\": \"Token \" + REPO_TOKEN,\n \"Content-Type\": \"application/json\",\n },\n json={\"assignees\": [USERNAME]},\n )\n\n if assign_issue_request.status_code == 201:\n print(\"Issue assigned successfully\")\n else:\n print(\"==>> Issue assignment failed :( !!!\")\n print(assign_issue_request.json())\n else:\n # Check if issue is assigned to user\n if issue_data_request.json()[\"assignee\"][\"login\"] == USERNAME:\n print(\"Issue is assigned to user\")\n else:\n print(\"Issue is assigned to someone else\")\n\n # Create comment\n URL = \"https://api.github.com/repos/{}/{}/issues/{}/comments\".format(\n OWNER, REPO, ISSUE_NUMBER\n )\n create_comment_request = requests.post(\n URL,\n headers={\n \"Authorization\": \"Token \" + REPO_TOKEN,\n \"Content-Type\": \"application/json\",\n },\n json={\n \"body\": \"\"\"Hey @{}, this issue is already assigned to someone else.\n\nPlease choose another issue.\n\nThanks for your interest in contributing to this project.\"\"\".format(\n USERNAME\n )\n },\n )\n","sub_path":"script/auto_assign_issue.py","file_name":"auto_assign_issue.py","file_ext":"py","file_size_in_byte":3317,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"484925002","text":"import copy\r\n\r\ndef copy_state(board, s_index, x):\r\n new_state = [0, [], s_index, x]\r\n for i in range(len(board)):\r\n for j in range(len(board[i])):\r\n if board[i][j][1] == 1:\r\n new_state[0] = [i, j]\r\n if board[i][j][1] == 2:\r\n new_state[1].append([i, j])\r\n return new_state\r\n\r\nfile_in = open('zad2_input.txt', 'r').read().splitlines()\r\n\r\n# cell = [x,y]\r\n# x -> rodzaj podlogi pola, 0 -> zwykly tile, 1 -> sciana, 2 -> punkty docelowy\r\n# y -> rodzaj obiektu znajdujacego sie polu, 0 -> brak, 1 -> gracz, 2 -> skrzynia\r\n\r\nbase_board = []\r\nstates = []\r\nstart = [0, [], 0, 0]\r\n\r\nfor i in range(len(file_in)):\r\n\r\n line = []\r\n cell = []\r\n\r\n for j in range(len(file_in[i])):\r\n if file_in[i][j] == 'W':\r\n cell = [1, 0]\r\n if file_in[i][j] == '.':\r\n cell = [0, 0]\r\n if file_in[i][j] == 'K':\r\n cell = [0, 0]\r\n start[0] = [i, j]\r\n if file_in[i][j] == 'B':\r\n cell = [0, 0]\r\n start[1].append([i, j])\r\n if file_in[i][j] == 'G':\r\n cell = [2, 0]\r\n if file_in[i][j] == '*':\r\n cell = [2, 0]\r\n start[1].append([i, j])\r\n if file_in[i][j] == '+':\r\n cell = [2, 0]\r\n start[0] = [i, j]\r\n line.append(cell)\r\n\r\n base_board.append(line)\r\n\r\n# states = [state] -> zapisane dane dla bfs\r\n# state = [pozycja_gracza, pozycje_skrzynek, indeks_poprzedniego_stanu, ostatni_ruch] -> stan gry\r\n# pozycja_gracza = [x,y]\r\n# pozycja_skrzynek = [[x0,y0],[x1,y1],...,[xn,yn]]\r\n\r\ns_index = 0\r\nstates.append(start)\r\n\r\nwork = True\r\nwhile work:\r\n\r\n board = copy.deepcopy(base_board)\r\n state = states[s_index]\r\n\r\n px = state[0][0]\r\n py = state[0][1]\r\n board[px][py][1] = 1\r\n\r\n boxes = state[1]\r\n for box in boxes:\r\n board[box[0]][box[1]][1] = 2\r\n\r\n #print(s_index)\r\n #for line in board:\r\n # print(line)\r\n #print()\r\n\r\n count = 0\r\n for i in range(len(board)):\r\n for j in range(len(board[i])):\r\n if board[i][j] == [2,1] or board[i][j] == [2,0]:\r\n count = count + 1\r\n\r\n if count == 0:\r\n work = False\r\n\r\n #if s_index > 20:\r\n # work = False\r\n\r\n for r in range(-1,2,2): #os Y\r\n if board[px+r][py][0] != 1: #czy nie sciana\r\n\r\n if board[px+r][py][1] == 2 and board[px+r*2][py][0] != 1 and board[px+r*2][py][1] == 0: #przesun skrzynie\r\n board[px][py][1] = 0\r\n board[px+r][py][1] = 1\r\n board[px+r*2][py][1] = 2\r\n states.append(copy_state(board, s_index,r+1))\r\n board[px][py][1] = 1\r\n board[px+r][py][1] = 2\r\n board[px+r*2][py][1] = 0\r\n\r\n if board[px+r][py][1] == 0: #wejdz na wolne pole\r\n board[px][py][1] = 0\r\n board[px+r][py][1] = 1\r\n states.append(copy_state(board, s_index,r+1))\r\n board[px][py][1] = 1\r\n board[px+r][py][1] = 0\r\n\r\n for r in range(-1, 2, 2): #os X\r\n if board[px][py+r][0] != 1: # czy nie sciana\r\n\r\n if board[px][py+r][1] == 2 and board[px][py+r*2][0] != 1 and board[px][py+r*2][1] == 0: # przesun skrzynie\r\n board[px][py][1] = 0\r\n board[px][py+r][1] = 1\r\n board[px][py+r*2][1] = 2\r\n states.append(copy_state(board, s_index,r+2))\r\n board[px][py][1] = 1\r\n board[px][py+r][1] = 2\r\n board[px][py+r*2][1] = 0\r\n\r\n if board[px][py+r][1] == 0: # wejdz na wolne pole\r\n board[px][py][1] = 0\r\n board[px][py+r][1] = 1\r\n states.append(copy_state(board, s_index,r+2))\r\n board[px][py][1] = 1\r\n board[px][py+r][1] = 0\r\n\r\n s_index = s_index + 1\r\n\r\ns_index = s_index - 1\r\nresult = []\r\nwhile s_index > 0:\r\n state = states[s_index]\r\n if state[3] == 0:\r\n result.append('U')\r\n if state[3] == 1:\r\n result.append('L')\r\n if state[3] == 2:\r\n result.append('D')\r\n if state[3] == 3:\r\n result.append('R')\r\n s_index = state[2]\r\nopen('zad2_output.txt', 'w+').write('\\n'.join(reversed(result)))\r\n","sub_path":"L2/Z2A/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4256,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"16285928","text":"import plotly.graph_objects as go\nimport plotly.express as px\n\ndf = px.data.wind() # 三维数据,风向,强度,频率\n\nfig = go.Figure()\n\nfig.add_trace(go.Barpolar(\n\n))\n\n# 频率对应半径,角度对应风向,颜色对应强度\nfig = px.bar_polar(df, r='frequency', theta='direction', color='strength',\n template='plotly_dark', color_discrete_sequence=px.colors.sequential.Plasma_r)\nfig.show()\n","sub_path":"src/plotly_test/barpolar_go2.py","file_name":"barpolar_go2.py","file_ext":"py","file_size_in_byte":425,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"441787566","text":"import datetime\nimport logging\nimport os\nfrom time import time\nfrom urllib.parse import urljoin\n\nfrom django.conf import settings\n\nfrom apns_clerk import Session, APNs, Message\nfrom gcm.gcm import GCM, GCMAuthenticationException\nfrom pyfcm import FCMNotification\nfrom pyfcm.errors import AuthenticationError, InternalPackageError, FCMServerError\n\nfrom .models import APNS_PLATFORM, GCM_PLATFORM, ANDROID_PLATFORM\n\nlogger = logging.getLogger('django')\n\n\nTYPE_CALL = 'call'\nTYPE_MESSAGE = 'message'\n\n\ndef send_call_message(device, unique_key, phonenumber, caller_id, attempt):\n \"\"\"\n Function to send the call push notification.\n\n Args:\n device (Device): A Device object.\n unique_key (string): String with the unique_key.\n phonenumber (string): Phonenumber that is calling.\n caller_id (string): ID of the caller.\n \"\"\"\n data = {\n 'unique_key': unique_key,\n 'phonenumber': phonenumber,\n 'caller_id': caller_id,\n 'attempt': attempt,\n }\n if device.app.platform == APNS_PLATFORM:\n send_apns_message(device, device.app, TYPE_CALL, data)\n elif device.app.platform == GCM_PLATFORM:\n send_gcm_message(device, device.app, TYPE_CALL, data)\n elif device.app.platform == ANDROID_PLATFORM:\n send_fcm_message(device, device.app, TYPE_CALL, data)\n else:\n logger.warning('{0} | Trying to sent \\'call\\' notification to unknown platform:{1} device:{2}'.format(\n unique_key, device.app.platform, device.token))\n\n\ndef send_text_message(device, app, message):\n \"\"\"\n Function to send a push notification with a message.\n\n Args:\n device (Device): A Device object.\n message (string): The message that needs to be send to the device.\n \"\"\"\n if app.platform == APNS_PLATFORM:\n send_apns_message(device, app, TYPE_MESSAGE, {'message': message})\n elif app.platform == GCM_PLATFORM:\n send_gcm_message(device, app, TYPE_MESSAGE, {'message': message})\n elif app.platform == ANDROID_PLATFORM:\n send_fcm_message(device, app, TYPE_MESSAGE, {'message': message})\n else:\n logger.warning('Trying to sent \\'message\\' notification to unknown platform:{0} device:{1}'.format(\n app.platform, device.token))\n\n\ndef get_call_push_payload(unique_key, phonenumber, caller_id):\n \"\"\"\n Function to create a dict used in the call push notification.\n\n Args:\n unique_key (string): The unique_key for the call.\n phonenumber (string): The phonenumber that is calling.\n caller_id (string): ID of the caller.\n\n Returns:\n dict: A dictionary with the following keys:\n type\n unique_key\n phonenumber\n caller_id\n response_api\n message_start_time\n \"\"\"\n response_url = urljoin(settings.APP_API_URL, 'api/call-response/')\n\n payload = {\n 'type': TYPE_CALL,\n 'unique_key': unique_key,\n 'phonenumber': phonenumber,\n 'caller_id': caller_id,\n 'response_api': response_url,\n 'message_start_time': time(),\n }\n return payload\n\n\ndef get_message_push_payload(message):\n \"\"\"\n Function to create a dict used in the message push notification.\n\n Args:\n message (string): The message send in the notification.\n\n Returns:\n dict: A dictionary with the following keys:\n type\n message\n \"\"\"\n payload = {\n 'type': TYPE_MESSAGE,\n 'message': message,\n }\n return payload\n\n\ndef send_apns_message(device, app, message_type, data=None):\n \"\"\"\n Send an Apple Push Notification message.\n \"\"\"\n token_list = [device.token]\n unique_key = device.token\n\n if message_type == TYPE_CALL:\n unique_key = data['unique_key']\n message = Message(token_list, payload=get_call_push_payload(unique_key, data['phonenumber'],\n data['caller_id']))\n elif message_type == TYPE_MESSAGE:\n message = Message(token_list, payload=get_message_push_payload(data['message']))\n else:\n logger.warning('{0} | TRYING TO SENT MESSAGE OF UNKNOWN TYPE: {1}', unique_key, message_type)\n\n session = Session()\n\n push_mode = settings.APNS_PRODUCTION\n if device.sandbox:\n # Sandbox push mode.\n push_mode = settings.APNS_SANDBOX\n\n full_cert_path = os.path.join(settings.CERT_DIR, app.push_key)\n\n con = session.get_connection(push_mode, cert_file=full_cert_path)\n srv = APNs(con)\n\n try:\n logger.info('{0} | Sending APNS \\'{1}\\' message at time:{2} to {3} Data:{4}'.\n format(unique_key, message_type,\n datetime.datetime.fromtimestamp(time()).strftime('%H:%M:%S.%f'), device.token, data))\n res = srv.send(message)\n\n except Exception:\n logger.exception('{0} | Error sending APNS message'.format(unique_key,))\n\n else:\n # Check failures. Check codes in APNs reference docs.\n for token, reason in res.failed.items():\n code, errmsg = reason\n # According to APNs protocol the token reported here\n # is garbage (invalid or empty), stop using and remove it.\n logger.warning('{0} | Sending APNS message failed for device: {1}, reason: {2}'.format(\n unique_key, token, errmsg)\n )\n\n # Check failures not related to devices.\n for code, errmsg in res.errors:\n logger.warning('{0} | Error sending APNS message. \\'{1}\\''.format(unique_key, errmsg))\n\n # Check if there are tokens that can be retried.\n if res.needs_retry():\n logger.info('{0} | Could not sent APNS message, retrying...')\n # Repeat with retry_message or reschedule your task.\n res.retry()\n\n\ndef send_fcm_message(device, app, message_type, data=None):\n \"\"\"\n Function for sending a push message using firebase.\n \"\"\"\n registration_id = device.token\n unique_key = device.token\n if message_type == TYPE_CALL:\n unique_key = data['unique_key']\n message = get_call_push_payload(\n unique_key,\n data['phonenumber'],\n data['caller_id'],\n )\n elif message_type == TYPE_MESSAGE:\n message = get_message_push_payload(data['message'])\n else:\n logger.warning('{0} | Trying to sent message of unknown type: {1}'.format(unique_key, message_type))\n\n push_service = FCMNotification(api_key=app.push_key)\n\n try:\n start_time = time()\n result = push_service.notify_single_device(registration_id=registration_id, data_message=message)\n except AuthenticationError:\n logger.error('{0} | Our Google API key was rejected!!!'.format(unique_key))\n except InternalPackageError:\n logger.error('{0} | Bad api request made by package.'.format(unique_key))\n except FCMServerError:\n logger.error('{0} | FCM Server error.'.format(unique_key))\n else:\n if result.get('success'):\n logger.info('{0} | FCM \\'{1}\\' message sent at time:{2} to {3} Data:{4}'\n .format(unique_key,\n message_type,\n datetime.datetime.fromtimestamp(start_time).strftime('%H:%M:%S.%f'),\n registration_id,\n data,)\n )\n\n if result.get('failure'):\n logger.warning('%s | Should remove %s because %s' % (unique_key, registration_id, result['results']))\n\n if result.get('canonical_ids'):\n logger.warning('%s | Should replace device token %s' % (unique_key, registration_id))\n\n\ndef send_gcm_message(device, app, message_type, data=None):\n \"\"\"\n Send a Google Cloud Messaging message.\n \"\"\"\n token_list = [device.token, ]\n unique_key = device.token\n\n key = \"%d-cycle.key\" % int(time())\n if message_type == TYPE_CALL:\n unique_key = data['unique_key']\n message = get_call_push_payload(\n unique_key,\n data['phonenumber'],\n data['caller_id'],\n )\n elif message_type == TYPE_MESSAGE:\n message = get_message_push_payload(data['message'])\n else:\n logger.warning('{0} | Trying to sent message of unknown type: {1}'.format(unique_key, message_type))\n\n gcm = GCM(app.push_key)\n\n try:\n start_time = time()\n response = gcm.json_request(\n registration_ids=token_list,\n data=message,\n collapse_key=key,\n priority='high',\n )\n\n success = response.get('success')\n canonical = response.get('canonical')\n errors = response.get('errors')\n\n if success:\n for reg_id, msg_id in success.items():\n logger.info('{0} | GCM \\'{1}\\' message sent at time:{2} to {3} Data:{4}'\n .format(unique_key,\n message_type,\n datetime.datetime.fromtimestamp(start_time).strftime('%H:%M:%S.%f'),\n reg_id,\n data,)\n )\n\n if canonical:\n for reg_id, new_reg_id in canonical.items():\n logger.warning('%s | Should replace device token %s with %s in database' % (\n unique_key, reg_id, new_reg_id))\n\n if errors:\n for err_code, reg_id in errors.items():\n logger.warning(\n '%s | Should remove %s because %s' % (unique_key, reg_id, err_code))\n\n except GCMAuthenticationException:\n # Stop and fix your settings.\n logger.error('{0} | Our Google API key was rejected!!!'.format(unique_key))\n except ValueError:\n # Probably your extra options, such as time_to_live,\n # are invalid. Read error message for more info.\n logger.error('{0} | Invalid message/option or invalid GCM response'.format(unique_key))\n except Exception:\n logger.exception('{0} | Error sending GCM message'.format(unique_key))\n","sub_path":"app/push.py","file_name":"push.py","file_ext":"py","file_size_in_byte":10161,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"341862416","text":"#!/usr/bin/env python3\n\nfrom typing import List\nimport subprocess\nimport sys\nimport enum\nimport argparse\nimport os\n\n\n@enum.unique\nclass Color(enum.Enum):\n RED = \"\\033[0;31m\"\n GREEN = \"\\033[0;33m\"\n CYAN = \"\\033[0;36m\"\n\n\nNC = \"\\033[0m\" # No Color\n\n\ndef colorify(\n s: str,\n color: Color,\n no_color: bool = False,\n):\n if no_color:\n return s\n return f\"{color.value}{s}{NC}\"\n\n\ndef rustfmt(fix_inplace: bool = False, no_color: bool = False) -> str:\n cmd = \"rustfmt --edition=2018\"\n if not fix_inplace:\n cmd += \" --check\"\n if no_color:\n cmd += \" --color=never\"\n return cmd\n\n\ndef get_commit_files() -> List[str]:\n files = subprocess.check_output(\n \"git diff --cached --name-only --diff-filter=ACM\".split()\n )\n return files.decode().splitlines()\n\n\ndef check(\n name: str, suffix: str, cmd: str, changed_files: List[str], no_color: bool = False\n):\n print(f\"Checking: {name} \", end=\"\")\n applicable_files = list(\n filter(lambda fname: fname.strip().endswith(suffix), changed_files)\n )\n if not applicable_files:\n print(colorify(\"[NOT APPLICABLE]\", Color.CYAN, no_color))\n return\n\n cmd = f'{cmd} {\" \".join(applicable_files)}'\n res = subprocess.run(cmd.split(), capture_output=True)\n if res.returncode != 0:\n print(colorify(\"[FAILED]\", Color.RED, no_color))\n print(\"Please inspect the output below and run make fmt to fix automatically\\n\")\n print(res.stdout.decode())\n exit(1)\n\n print(colorify(\"[OK]\", Color.GREEN, no_color))\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument(\n \"--fix-inplace\", action=\"store_true\", help=\"apply fixes inplace\"\n )\n parser.add_argument(\n \"--no-color\", action=\"store_true\", help=\"disable colored output\", default=not sys.stdout.isatty()\n )\n args = parser.parse_args()\n\n files = get_commit_files()\n # we use rustfmt here because cargo fmt does not accept list of files\n # it internally gathers project files and feeds them to rustfmt\n # so because we want to check only files included in the commit we use rustfmt directly\n check(\n name=\"rustfmt\",\n suffix=\".rs\",\n cmd=rustfmt(fix_inplace=args.fix_inplace, no_color=args.no_color),\n changed_files=files,\n no_color=args.no_color,\n )\n","sub_path":"pre-commit.py","file_name":"pre-commit.py","file_ext":"py","file_size_in_byte":2364,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"311332747","text":"#!/usr/bin/env python\n# coding:utf-8\n# TODO: 1. sort reply rdata by ip latency\n# 3. reduce socket fd usage\n\n\n__version__ = '1.0'\n\nimport sys\nimport os\nimport glob\n\nsys.path += glob.glob('*.egg')\n\nimport gevent\nimport gevent.server\nimport gevent.timeout\nimport gevent.monkey\ngevent.monkey.patch_all(subprocess=True)\n\nimport time\nimport logging\nimport heapq\nfrom gevent import socket\nimport errno\nimport select\nimport re\nimport dnslib\ntry:\n import pygeoip\nexcept ImportError:\n pygeoip = None\n\nimport win32api, win32gui \nct = win32api.GetConsoleTitle() \nhd = win32gui.FindWindow(0,ct) \nwin32gui.ShowWindow(hd,0) \t\n\t\nCHINA_DOMAINS = {\n 'google-analytics.com'\n 'dytt8.net'\n '07073.com',\n '10010.com',\n '100ye.com',\n '114la.com',\n '115.com',\n '120ask.com',\n '126.com',\n '126.net',\n '1616.net',\n '163.com',\n 'douyu.tv',\n '17173.com',\n '1778.com',\n '178.com',\n '17u.com',\n '19lou.com',\n '1o26.com',\n '1ting.com',\n '21cn.com',\n '2345.com',\n '265.com',\n '265g.com',\n '28.com',\n '28tui.com',\n '2hua.com',\n '2mdn.net',\n '315che.com',\n '3366.com',\n '360buy.com',\n '360buyimg.com',\n '360doc.com',\n '36kr.com',\n '39.net',\n '3dmgame.com',\n '4399.com',\n '4738.com',\n '500wan.com',\n '51.com',\n '51.la',\n '5173.com',\n '51auto.com',\n '51buy.com',\n '51cto.com',\n '51fanli.com',\n '51job.com',\n '52kmh.com',\n '52pk.net',\n '52tlbb.com',\n '53kf.com',\n '55bbs.com',\n '55tuan.com',\n '56.com',\n '58.com',\n '591hx.com',\n '5d6d.net',\n '61.com',\n '70e.com',\n '777wyx.com',\n '778669.com',\n '7c.com',\n '7k7k.com',\n '88db.com',\n '91.com',\n '99bill.com',\n 'a135.net',\n 'abang.com',\n 'abchina.com',\n 'ad1111.com',\n 'admin5.com',\n 'adnxs.com',\n 'adobe.com',\n 'adroll.com',\n 'ads8.com',\n 'adsame.com',\n 'adsonar.com',\n 'adtechus.com',\n 'aibang.com',\n 'aifang.com',\n 'aili.com',\n 'aipai.com',\n 'aizhan.com',\n 'ali213.net',\n 'alibaba.com',\n 'alicdn.com',\n 'aliexpress.com',\n 'alimama.com',\n 'alipay.com',\n 'alipayobjects.com',\n 'alisoft.com',\n 'alivv.com',\n 'aliyun.com',\n 'allyes.com',\n 'amazon.com',\n 'anjuke.com',\n 'anzhi.com',\n 'aol.com',\n 'apple.com',\n 'arpg2.com',\n 'atdmt.com',\n 'b2b168.com',\n 'babytree.com',\n 'baidu.com',\n 'baihe.com',\n 'baixing.com',\n 'bankcomm.com',\n 'baomihua.com',\n 'bdimg.com',\n 'bdstatic.com',\n 'bendibao.com',\n 'betrad.com',\n 'bilibili.tv',\n 'bing.com',\n 'bitauto.com',\n 'blog.163.com',\n 'blogchina.com',\n 'blueidea.com',\n 'bluekai.com',\n 'booksky.org',\n 'caixin.com',\n 'ccb.com',\n 'ccidnet.com',\n 'cctv*.com',\n 'china.com',\n 'chinabyte.com',\n 'chinahr.com',\n 'chinanews.com',\n 'chinaunix.net',\n 'chinaw3.com',\n 'chinaz.com',\n 'chuangelm.com',\n 'ci123.com',\n 'cmbchina.com',\n 'cnbeta.com',\n 'cnblogs.com',\n 'cncn.com',\n 'cnhubei.com',\n 'cnki.net',\n 'cnmo.com',\n 'cnxad.com',\n 'cnzz.com',\n 'cocoren.com',\n 'compete.com',\n 'comsenz.com',\n 'coo8.com',\n 'cqnews.net',\n 'crsky.com',\n 'csdn.net',\n 'ct10000.com',\n 'ctrip.com',\n 'dangdang.com',\n 'daqi.com',\n 'dayoo.com',\n 'dbank.com',\n 'ddmap.com',\n 'dedecms.com',\n 'dh818.com',\n 'diandian.com',\n 'dianping.com',\n 'discuz.net',\n 'doc88.com',\n 'docin.com',\n 'donews.com',\n 'dospy.com',\n 'douban.com',\n 'douban.fm',\n 'doubleclick.com',\n 'doubleclick.net',\n 'duba.net',\n 'duote.com',\n 'duowan.com',\n 'dzwww.com',\n 'eastday.com',\n 'eastmoney.com',\n 'ebay.com',\n 'elong.com',\n 'ename.net',\n 'etao.com',\n 'exam8.com',\n 'eye.rs',\n 'fantong.com',\n 'fastcdn.com',\n 'fblife.com',\n 'fengniao.com',\n 'fenzhi.com',\n 'flickr.com',\n 'fobshanghai.com',\n 'ftuan.com',\n 'funshion.com',\n 'fx120.net',\n 'game3737.com',\n 'gamersky.com',\n 'gamestlbb.com',\n 'gamesville.com',\n 'ganji.com',\n 'gfan.com',\n 'gongchang.com',\n 'google-analytics.com',\n 'gougou.com',\n 'gtimg.com',\n 'hao123.com',\n 'haodf.com',\n 'harrenmedianetwork.com',\n 'hc360.com',\n 'hefei.cc',\n 'hf365.com',\n 'hiapk.com',\n 'hichina.com',\n 'homeinns.com',\n 'hotsales.net',\n 'house365.com',\n 'huaban.com',\n 'huanqiu.com',\n 'hudong.com',\n 'hupu.com',\n 'iask.com',\n 'iciba.com',\n 'icson.com',\n 'ifeng.com',\n 'iloveyouxi.com',\n 'im286.com',\n 'imanhua.com',\n 'img.cctvpic.com',\n 'imrworldwide.com',\n 'invitemedia.com',\n 'ip138.com',\n 'ipinyou.com',\n 'iqilu.com',\n 'iqiyi.com',\n 'irs01.com',\n 'irs01.net',\n 'it168.com',\n 'iteye.com',\n 'iyaya.com',\n 'jb51.net',\n 'jiathis.com',\n 'jiayuan.com',\n 'jing.fm',\n 'jinti.com',\n 'jqw.com',\n 'jumei.com',\n 'jxedt.com',\n 'jysq.net',\n 'kaixin001.com',\n 'kandian.com',\n 'kdnet.net',\n 'kimiss.com',\n 'ku6.com',\n 'ku6cdn.com',\n 'ku6img.com',\n 'kuaidi100.com',\n 'kugou.com',\n 'l99.com',\n 'lady8844.com',\n 'lafaso.com',\n 'lashou.com',\n 'legolas-media.com',\n 'lehecai.com',\n 'leho.com',\n 'letv.com',\n 'liebiao.com',\n 'lietou.com',\n 'linezing.com',\n 'linkedin.com',\n 'live.com',\n 'longhoo.net',\n 'lusongsong.com',\n 'lxdns.com',\n 'lycos.com',\n 'lygo.com',\n 'm18.com',\n 'm1905.com',\n 'made-in-china.com',\n 'makepolo.com',\n 'mangocity.com',\n 'manzuo.com',\n 'mapbar.com',\n 'mathtag.com',\n 'mediaplex.com',\n 'mediav.com',\n 'meilele.com',\n 'meilishuo.com',\n 'meishichina.com',\n 'meituan.com',\n 'meizu.com',\n 'miaozhen.com',\n 'microsoft.com',\n 'miercn.com',\n 'mlt01.com',\n 'mmstat.com',\n 'mnwan.com',\n 'mogujie.com',\n 'mookie1.com',\n 'moonbasa.com',\n 'mop.com',\n 'mosso.com',\n 'mplife.com',\n 'msn.com',\n 'mtime.com',\n 'mumayi.com',\n 'mydrivers.com',\n 'net114.com',\n 'netease.com',\n 'newsmth.net',\n 'nipic.com',\n 'nowec.com',\n 'nuomi.com',\n 'oadz.com',\n 'oeeee.com',\n 'onetad.com',\n 'onlinedown.net',\n 'onlylady.com',\n 'oschina.net',\n 'otwan.com',\n 'paipai.com',\n 'paypal.com',\n 'pchome.net',\n 'pcpop.com',\n 'pengyou.com',\n 'php100.com',\n 'phpwind.net',\n 'pingan.com',\n 'pixlr.com',\n 'pp.cc',\n 'ppstream.com',\n 'pptv.com',\n 'ptlogin2.qq.com',\n 'pubmatic.com',\n 'q150.com',\n 'qianlong.com',\n 'qidian.com',\n 'qingdaonews.com',\n 'qire123.com',\n 'qiushibaike.com',\n 'qiyou.com',\n 'qjy168.com',\n 'qq.com',\n 'qq937.com',\n 'qstatic.com',\n 'quantserve.com',\n 'qunar.com',\n 'rakuten.co.jp',\n 'readnovel.com',\n 'renren.com',\n 'rtbidder.net',\n 'scanscout.com',\n 'scorecardresearch.com',\n 'sdo.com',\n 'seowhy.com',\n 'serving-sys.com',\n 'sf-express.com',\n 'shangdu.com',\n 'si.kz',\n 'sina.com',\n 'sinahk.net',\n 'sinajs.com',\n 'smzdm.com',\n 'snyu.com',\n 'sodu.org',\n 'sogou.com',\n 'sohu.com',\n 'soku.com',\n 'sootoo.com',\n 'soso.com',\n 'soufun.com',\n 'sourceforge.net',\n 'staticsdo.com',\n 'stockstar.com',\n 'sttlbb.com',\n 'suning.com',\n 'szhome.com',\n 'sznews.com',\n 'tangdou.com',\n 'tanx.com',\n 'tao123.com',\n 'taobao.com',\n 'taobaocdn.com',\n 'tdimg.com',\n 'tenpay.com',\n 'tgbus.com',\n 'theplanet.com',\n 'thethirdmedia.com',\n 'tiancity.com',\n 'tianji.com',\n 'tiao8.info',\n 'tiexue.net',\n 'titan24.com',\n 'tmall.com',\n 'tom.com',\n 'toocle.com',\n 'tremormedia.com',\n 'tuan800.com',\n 'tudou.com',\n 'tudouui.com',\n 'tui18.com',\n 'tuniu.com',\n 'twcczhu.com',\n 'u17.com',\n 'ucjoy.com',\n 'ulink.cc',\n 'uniontoufang.com',\n 'up2c.com',\n 'uuu9.com',\n 'uuzu.com',\n 'vancl.com',\n 'verycd.com',\n 'vipshop.com',\n 'vizu.com',\n 'vjia.com',\n 'weibo.com',\n 'weiphone.com',\n 'west263.com',\n 'whlongda.com',\n 'wrating.com',\n 'wumii.com',\n 'xiami.com',\n 'xiaomi.com',\n 'xiazaiba.com',\n 'xici.net',\n 'xinhuanet.com',\n 'xinnet.com',\n 'xitek.com',\n 'xiu.com',\n 'xunlei.com',\n 'xyxy.net',\n 'yaolan.com',\n 'yesky.com',\n 'yieldmanager.com',\n 'yihaodian.com',\n 'yingjiesheng.com',\n 'yinyuetai.com',\n 'yiqifa.com',\n 'ykimg.com',\n 'ynet.com',\n 'yoka.com',\n 'yolk7.com',\n 'youboy.com',\n 'youdao.com',\n 'yougou.com',\n 'youku.com',\n 'youshang.com',\n 'yupoo.com',\n 'yxlady.com',\n 'yyets.com',\n 'zhaodao123.com',\n 'zhaopin.com',\n 'zhenai.com',\n 'zhibo8.cc',\n 'zhihu.com',\n 'zhubajie.com',\n 'zongheng.com',\n 'zoosnet.net',\n 'zqgame.com',\n 'ztgame.com',\n 'zx915.com',\n 'miui.com',\n 'mi-idc.com',\n 'qhimg.com',\n 'wandoujia.com'\n}\n\ndef is_china_domain(domain):\n if domain.endswith('.cn'):\n return True\n if '.'.join(domain.split('.')[-2:]) in CHINA_DOMAINS:\n return True\n return False\n\n\nclass ExpireCache(object):\n \"\"\" A dictionary-like object, supporting expire semantics.\"\"\"\n def __init__(self, max_size=1024):\n self.__maxsize = max_size\n self.__values = {}\n self.__expire_times = {}\n self.__expire_heap = []\n\n def size(self):\n return len(self.__values)\n\n def clear(self):\n self.__values.clear()\n self.__expire_times.clear()\n del self.__expire_heap[:]\n\n def exists(self, key):\n return key in self.__values\n\n def set(self, key, value, expire):\n try:\n et = self.__expire_times[key]\n pos = self.__expire_heap.index((et, key))\n del self.__expire_heap[pos]\n if pos < len(self.__expire_heap):\n heapq._siftup(self.__expire_heap, pos)\n except KeyError:\n pass\n et = int(time.time() + expire)\n self.__expire_times[key] = et\n heapq.heappush(self.__expire_heap, (et, key))\n self.__values[key] = value\n self.cleanup()\n\n def get(self, key):\n et = self.__expire_times[key]\n if et < time.time():\n self.cleanup()\n raise KeyError(key)\n return self.__values[key]\n\n def delete(self, key):\n et = self.__expire_times.pop(key)\n pos = self.__expire_heap.index((et, key))\n del self.__expire_heap[pos]\n if pos < len(self.__expire_heap):\n heapq._siftup(self.__expire_heap, pos)\n del self.__values[key]\n\n def cleanup(self):\n t = int(time.time())\n eh = self.__expire_heap\n ets = self.__expire_times\n v = self.__values\n size = self.__maxsize\n heappop = heapq.heappop\n #Delete expired, ticky\n while eh and eh[0][0] <= t or len(v) > size:\n _, key = heappop(eh)\n del v[key], ets[key]\n\n\nclass DNSServer(gevent.server.DatagramServer):\n \"\"\"DNS Proxy based on gevent/dnslib\"\"\"\n\n def __init__(self, *args, **kwargs):\n dns_servers = kwargs.pop('dns_servers')\n dns_timeout = kwargs.pop('dns_timeout', 2)\n super(self.__class__, self).__init__(*args, **kwargs)\n self.dns_servers = dns_servers\n self.dns_v4_servers = [x for x in self.dns_servers if ':' not in x]\n self.dns_v6_servers = [x for x in self.dns_servers if ':' in x]\n self.dns_timeout = int(dns_timeout)\n self.dns_cache = ExpireCache(max_size=65536)\n\n def do_read(self):\n try:\n return gevent.server.DatagramServer.do_read(self)\n except socket.error as e:\n if e[0] not in (errno.ECONNABORTED, errno.ECONNRESET, errno.EPIPE):\n raise\t\t\n \n def handle(self, data, address):\n logging.debug('receive from %r data=%r', address, data)\n request = dnslib.DNSRecord.parse(data)\n qname = str(request.q.qname)\n qtype = request.q.qtype\n try:\n reply_data = self.dns_cache.get((qname, qtype))\n except KeyError:\n reply_data = ''\n sock_v4 = sock_v6 = None\n socks = []\n is_local_hostname = '.' not in qname\n if 'USERDNSDOMAIN' in os.environ:\n is_local_hostname = qname.lower().endswith('.' + os.environ['USERDNSDOMAIN'].lower())\n if is_local_hostname :\n logging.warning('qname=%r is a plain hostname, need intranet dns server!!!', qname)\n reply = dnslib.DNSRecord(header=dnslib.DNSHeader(id=request.header.id, rcode=3))\n self.sendto(reply.pack(), address)\n return\n dns_v4_servers = self.dns_v4_servers if not is_local_hostname else [x for x in self.dns_intranet_servers if ':' not in x]\n dns_v6_servers = self.dns_v6_servers if not is_local_hostname else [x for x in self.dns_intranet_servers if ':' in x]\n if dns_v4_servers:\n sock_v4 = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n socks.append(sock_v4)\n if dns_v6_servers:\n sock_v6 = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM)\n socks.append(sock_v6)\n for _ in xrange(2):\n if reply_data:\n break\n try:\n #need_reply_servers = set()\n if is_china_domain(qname):\n sock_v4.sendto(data, ('223.6.6.6', 53))\n #need_reply_servers.add('202.116.0.1')\n else:\n for dnsserver in dns_v4_servers:\n sock_v4.sendto(data, (dnsserver, 5353))\n #need_reply_servers.add(dnsserver)\n for dnsserver in dns_v6_servers:\n sock_v6.sendto(data, (dnsserver, 5353))\n #need_reply_servers.add(dnsserver)\n timeout_at = time.time() + self.dns_timeout\n while time.time() < timeout_at:\n if reply_data:\n break\n ins, _, _ = select.select(socks, [], [], 0.1)\n for sock in ins:\n reply_data, (_, _) = sock.recvfrom(512)\n reply = dnslib.DNSRecord.parse(reply_data)\n iplist = [str(x.rdata) for x in reply.rr ]\n \n ttl = max(x.ttl for x in reply.rr) if reply.rr else 600\n #logging.debug('query qname=%r qtype=%r reply_server=%r reply iplist=%s, ttl=%r', qname, qtype, reply_server, iplist, ttl)\n if iplist or qname.endswith('.in-addr.arpa'):\n self.dns_cache.set((qname, qtype), reply_data, ttl*2)\n break\n except socket.error as e:\n logging.warning('handle dns data=%r socket: %r', data, e)\n for sock in socks:\n sock.close()\n if reply_data:\n #print 'data:', data[:2], 'reply:', reply_data[2:]\n return self.sendto(data[:2] + reply_data[2:], address)\n\n\ndef test():\n logging.basicConfig(level=logging.INFO, format='%(levelname)s - %(asctime)s %(message)s', datefmt='[%b %d %H:%M:%S]')\n dns_servers = ['208.67.220.220']\n logging.info('serving at port 53...')\n DNSServer(('localhost', 53), dns_servers=dns_servers).serve_forever()\n\n\nif __name__ == '__main__':\n test()\n","sub_path":"opendns.py","file_name":"opendns.py","file_ext":"py","file_size_in_byte":15423,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"514728918","text":"\"\"\"Solution to the Momentum and Energy equation for a NEWTONIAN VISCOUS Fluid \"\"\"\n\nfrom __future__ import print_function\nfrom decimal import *\nfrom dolfin import *\nfrom mshr import *\nfrom math import pi, sin, cos, sqrt\nimport numpy as np\n\n# Print log messages only from the root process in parallel\nparameters[\"std_out_all_processes\"] = False;\n\n\n# Construct hollow cylinder mesh\nr_a=0.031\nr_b=0.035\n\n# Create geometry 1\nx1=0.0\ny1=0.00\nx2=0.002\ny2=0.0\n\n\nc1=Circle(Point(x1,y1), r_a)\nc2=Circle(Point(x2,y2), r_b)\n\ncyl=c2-c1\n\n# Create mesh\nmesh = generate_mesh(cyl, 35)\n\nprint('Number of Cells:', mesh.num_cells())\nprint('Number of Vertices:', mesh.num_vertices())\nplot(mesh, interactive=True)\n\ntol = 0.005\niter = 0 \nmaxiter = 2\n\n# Refinement Code 1\niter = 0 \nmaxiter = 2\nwhile iter < maxiter:\n iter+=1\n gam = 0.68\n class Omega0(SubDomain):\n def inside(self, x, on_boundary):\n r = sqrt((x[0]-x1)**2+(x[1]-y1)**2)\n return True if r <= gam*r_a + (1-gam)*r_b else False\n omega0= Omega0()\n class Omega1(SubDomain):\n def inside(self, x, on_boundary):\n p = sqrt((x[0]-x2)**2+(x[1]-y2)**2)\n return True if p > (1-gam)*r_a + gam*r_b else False\n omega1= Omega1()\n cell_domains = CellFunction(\"bool\", mesh)\n cell_domains.set_all(False)\n \n #omega1.mark(cell_domains, True)\n omega0.mark(cell_domains, True)\n mesh = refine(mesh, cell_domains, redistribute=True)\n print('Number of Cells:', mesh.num_cells())\n print('Number of Vertices:', mesh.num_vertices())\n\n# Plot cell_domains\nplot(cell_domains, interactive=True)\n\n# Set parameter values\nh = mesh.hmin()\ndt = 0.0005 #0.025*h/1.\nTf = 20.0\nrho = 820.0\ncp = 4000.0\nmu = 1.0*10E-3\nw_j = 5.0\neps = 10E-6\nkappa = 25.0\nheatt= 2.0\n\n\n\n# Define function spaces \nV = VectorFunctionSpace(mesh, \"CG\", 1)\nQ = FunctionSpace(mesh, \"CG\", 2)\nW = TensorFunctionSpace(mesh, \"CG\", 1)\n\n# Define trial and test functions\nu = TrialFunction(V)\np = TrialFunction(Q)\nT = TrialFunction(Q)\nv = TestFunction(V)\nq = TestFunction(Q)\n\n\n#Define inner cylinder velocity \n \nw = Expression(('-w_j*(x[1]-y1)' , 'w_j*(x[0]-x1)' ), w_j=w_j , r_a=r_a, x1=x1, y1=y1 )\n\n\n#Define Boundaries (Method 2) \nclass Omega0(SubDomain):\n def inside(self, x, on_boundary):\n return True if ((x[0]-x1)*(x[0]-x1))+((x[1]-y1)*(x[1]-y1)) < r_a*r_a + DOLFIN_EPS else False\n\nclass Omega1(SubDomain):\n def inside(self, x, on_boundary):\n return True if ((x[0]-x2)*(x[0]-x2))+((x[1]-y2)*(x[1]-y2)) > (1.0-6*10E-3)*r_b*r_b else False\n\nomega0= Omega0()\nomega1= Omega1()\n\n\n\n# Define boundary conditions\nspin = DirichletBC(V, w, omega0) #The inner cylinder will be rotated with constant angular velocity w_j\nnoslip = DirichletBC(V, (0.0, 0.0), omega1) #The outer cylinder remains fixed with zero velocity \ntemp0 = DirichletBC(Q, 100.0, omega0) #Dirichlet Boundary Condition on the inner bearing \n\n\n#Collect Boundary Conditions\nbcu = [noslip, spin]\nbcp = []\nbcT = [temp0]\n\n# Create functions\nu0 = Function(V)\nu1 = Function(V)\np1 = Function(Q)\nT0 = Function(Q)\nT1 = Function(Q)\n\n# Define coefficients \nk = Constant(dt)\nalpha = 1.0/(rho*cp)\necc = (x2-x1)/(r_b-r_a)\n\n#Define Strain Rate and other tensors\nsr = 0.5*(grad(u0) + transpose(grad(u0)))\ngamdot = inner(sr,grad(u0))\n\n#CHORIN'S PROJECTION METHOD\n\n# Tentative velocity step\na1 = inner(u, v)*dx + k*(mu/rho)*inner(grad(u), grad(v))*dx \nL1 = inner(u0,v)*dx - k*inner(grad(u0)*u0, v)*dx \n\n# Pressure update \na2 = k*inner(grad(p), grad(q))*dx #+ eps*inner(p,q)*dx\nL2 = -div(u1)*q*dx\n\n# Velocity update\na3 = inner(u, v)*dx\nL3 = inner(u1, v)*dx - k*inner(grad(p1), v)*dx\n\n\n# Temperature Update\na4 = inner(T,q)*dx + k*kappa*alpha*inner(grad(T),grad(q))*dx + k*inner(inner(u1,grad(T)),q)*dx\nL4 = inner(T0,q)*dx + k*alpha*(heatt*inner(T0,q)*ds(1) + mu*inner(gamdot,q)*dx) #Neumann Condition on the outer bearing is encoded in the weak formulation\n\n# Assemble matrices\nA1 = assemble(a1)\nA2 = assemble(a2)\nA3 = assemble(a3)\nA4 = assemble(a4)\n\n\n#Define Surface Integral for Torque Calculation\n\n# Define unit Normal Vector at inner and outer Boundary (Method 1)\n#n0 = FacetNormal(omega0)\n#n1 = FacetNormal(omega1)\n\n# Define unit Normal Vector at inner and outer Boundary (Method 2)\n\nn0 = Expression(('(x[0]-x1)/r_a' , '(x[1]-y1)/r_a' ), r_a=r_a, x1=x1, y1=y1)\nn1 = Expression(('(x[0]-x2)/r_b' , '(x[1]-y2)/r_b' ), r_b=r_b, x2=x2, y2=y2)\nt0 = Expression(('-(x[1]-y1)/r_a' , '(x[0]-x1)/r_a' ), r_a=r_a, x1=x1, y1=y1)\nt1 = Expression(('-(x[1]-y2)/r_b' , '(x[0]-x2)/r_b' ), r_b=r_b, x2=x2, y2=y2)\n\nn0v = interpolate(n0, V)\n\n\nI = Expression((('1.0','0.0'),\n ('0.0','1.0')), degree=2)\n\n\nboundary_parts = FacetFunction(\"size_t\", mesh)\nomega0.mark(boundary_parts,0)\nomega1.mark(boundary_parts,1)\nds = Measure(\"ds\")[boundary_parts]\n\nsigma0 = (p1*I+2*mu*sr)*t0\nsigma1 = (p1*I+2*mu*sr)*t1\n\nomegaf0 = p1*I*n0 #Nomral component of the stress \nomegaf1 = p1*I*n1\n\n\ninnerforcex = -inner(Constant((1.0, 0.0)), omegaf0)*ds(0)\ninnerforcey = -inner(Constant((0.0, 1.0)), omegaf0)*ds(0)\nouterforcex = -inner(Constant((1.0, 0.0)), omegaf1)*ds(1)\nouterforcey = -inner(Constant((0.0, 1.0)), omegaf1)*ds(1)\ninnertorque = -inner(n0, sigma0)*ds(0)\noutertorque = -inner(n1, sigma1)*ds(1)\n\n\n\n# Use amg preconditioner if available\nprec = \"amg\" if has_krylov_solver_preconditioner(\"amg\") else \"default\"\n\n# Use nonzero guesses - essential for CG with non-symmetric BC\nparameters['krylov_solver']['nonzero_initial_guess'] = True\n\nprint(\"eccentricity ratio\", ecc)\n\n# Time-stepping\niter = 0 # iteration counter\nmaxiter = 1150 \nt = dt\nwhile t < Tf + DOLFIN_EPS and iter < maxiter:\n iter += 1\n\n # Compute tentative velocity step\n begin(\"Computing tentative velocity\")\n b1 = assemble(L1)\n [bc.apply(A1, b1) for bc in bcu]\n solve(A1, u1.vector(), b1, \"bicgstab\", \"default\")\n end()\n\n # Pressure correction\n begin(\"Computing pressure correction\")\n b2 = assemble(L2)\n [bc.apply(A2, b2) for bc in bcp]\n [bc.apply(p1.vector()) for bc in bcp]\n solve(A2, p1.vector(), b2, \"bicgstab\", prec)\n end()\n\n # Velocity correction\n begin(\"Computing velocity correction\")\n b3 = assemble(L3)\n [bc.apply(A3, b3) for bc in bcu]\n solve(A3, u1.vector(), b3, \"bicgstab\", \"default\")\n end()\n\n # Temperature correction\n begin(\"Computing temperature correction\")\n b4 = assemble(L4)\n [bc.apply(A4, b4) for bc in bcT]\n solve(A4, T1.vector(), b4, \"bicgstab\", \"default\")\n end()\n\n # Calcultate Force on the bearing\n print(\"Normal Force on inner bearing: \", (assemble(innerforcex), assemble(innerforcey)))\n print(\"Torque on inner bearing: \", assemble(innertorque))\n \n\n # Plot solution\n plot(p1, title=\"Pressure\", rescale=True)\n plot(u1, title=\"Velocity\", rescale=True, mode = \"auto\")\n plot(T1, title=\"Temperature\", rescale=True)\n\n # Move to next time step\n u0.assign(u1)\n T0.assign(T1)\n t += dt\n print(\"t =\", t)\n\n# Hold plot\nplot(mesh)\ninteractive()\n\n","sub_path":"JBP/Obselete Codes/refinedspinningjournal.py","file_name":"refinedspinningjournal.py","file_ext":"py","file_size_in_byte":7058,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"103205086","text":"import json\n\nimport requests\nfrom aioresponses import aioresponses\nfrom fastapi.testclient import TestClient\nimport pytest\n\nfrom fastAPI_aiohttp.fastAPI import app, SingletonAiohttp\n\nurl = \"test/toto\"\n\n\n@pytest.fixture\ndef client_aio():\n with aioresponses() as m:\n m.post(url=url,\n status=200,\n body=json.dumps({\"result\": 2}))\n yield m\n\n\n@pytest.fixture\ndef client_fastAPI():\n return TestClient(app=app)\n\n\n@pytest.mark.asyncio\nasync def test_query_url(client_aio):\n rst = await SingletonAiohttp.query_url(url)\n assert rst == {\"result\": 2}\n\n\ndef test_endpoint(client_fastAPI):\n result: requests.Response = client_fastAPI.get(url='/endpoint/')\n assert result is not None\n\n result_json = result.json()\n assert result_json == {'succes': 1}\n\n\ndef test_endpoint_multi(client_fastAPI):\n result: requests.Response = client_fastAPI.get(url='/endpoint_multi/')\n assert result is not None\n\n result_json = result.json()\n assert result_json == {'succes': 3}\n","sub_path":"src/tests/test_fastAPI_aiohttp.py","file_name":"test_fastAPI_aiohttp.py","file_ext":"py","file_size_in_byte":1023,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"349157052","text":"# coding=utf-8\n# Copyright 2022 The Google Research Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nr\"\"\"Creates new train/dev/test split for SentEval data based on text length.\n\nFinds a length threshold such that all texts longer than this threshold make up\na test set that is at max `test_set_size` in size. All other examples are\nrandomly assigned to the training/dev sets. Note that the exact test set size\ncannot be guaranteed.\n\nThis script generates the following directory structure under the\n`base_out_dir`. This follows the original SentEval directory structure and thus\nallows running the original scripts with no change.\n\nbase_out_dir/\n probing/TASK_NAME.txt # Data for this task.\n probing/TASK_NAME.txt-settings.json # Some information on the generated data.\n\nTASK_NAME.txt contains all examples with their respective set labels attached.\nThis file follows the original SentEval data format.\n\nExample call:\npython -m \\\n talk_about_random_splits.probing.split_by_length_threshold_main \\\n --senteval_path=\"/tmp/senteval/task_data/probing\" \\\n --base_out_dir=\"YOUR_PATH_HERE\" --alsologtostderr\n\"\"\"\nimport csv\nimport json\nimport os\nimport random\n\nfrom absl import app\nfrom absl import flags\nfrom absl import logging\nimport numpy as np\n\n\nfrom talk_about_random_splits.probing import probing_utils\n\nFLAGS = flags.FLAGS\n\nflags.DEFINE_string('senteval_path', None,\n 'Path to the original SentEval data in tsv format.')\nflags.DEFINE_string(\n 'base_out_dir', None,\n 'Base working dir in which to create subdirs for this script\\'s results.')\nflags.DEFINE_string(\n 'split_name', 'length_split_threshold',\n 'Determines the base name of result sub-directories in `base_out_dir`.')\nflags.DEFINE_integer('dev_set_size', 10000,\n 'Number of requested examples in dev sets.')\nflags.DEFINE_integer('test_set_size', 10000,\n 'Number of requested examples in test sets.')\nflags.DEFINE_list('tasks', [\n 'word_content.txt', 'sentence_length.txt', 'bigram_shift.txt',\n 'tree_depth.txt', 'top_constituents.txt', 'past_present.txt',\n 'subj_number.txt', 'obj_number.txt', 'odd_man_out.txt',\n 'coordination_inversion.txt'\n], 'Tasks for which to generate new data splits.')\n\n\ndef main(argv):\n if len(argv) > 1:\n raise app.UsageError('Too many command-line arguments.')\n\n for task_name in FLAGS.tasks:\n logging.info('Starting task: %s.', task_name)\n df = probing_utils.read_senteval_data(FLAGS.senteval_path, task_name)\n df['text_len'] = df['text'].str.split().apply(len)\n\n # There is only 1 trial. Therefore, in order to stay consistent in directory\n # names we manually add '0' here.\n split_dir = os.path.join(FLAGS.base_out_dir, FLAGS.split_name) + '-0'\n probing_dir = os.path.join(split_dir, 'probing')\n settings_path = os.path.join(probing_dir,\n '{}-settings.json'.format(task_name))\n data_out_path = os.path.join(probing_dir, '{}'.format(task_name))\n\n length_threshold, test_lengths, test_mask = (\n probing_utils.split_by_length_threshold(df, FLAGS.test_set_size))\n train_dev_idxs = np.nonzero(~test_mask)[0]\n assert len(train_dev_idxs) > FLAGS.dev_set_size, 'Dev set size too large.'\n dev_idxs = random.sample(train_dev_idxs.tolist(), FLAGS.dev_set_size)\n train_idxs = list(set(train_dev_idxs) - set(dev_idxs))\n\n logging.info('Writing output to file: %s.', data_out_path)\n\n # Set new labels.\n df.loc[test_mask, 'set'] = 'te'\n df.loc[df.index[train_idxs], 'set'] = 'tr'\n df.loc[df.index[dev_idxs], 'set'] = 'va'\n\n os.make_dirs(probing_dir)\n\n with open(settings_path, 'w') as settings_file:\n settings = {\n 'task_name': task_name,\n 'length_threshold': length_threshold,\n 'all_lengths': sorted(set(df['text_len'])),\n 'test_lengths': sorted(test_lengths),\n 'train/dev_lengths': sorted(set(df['text_len']) - set(test_lengths)),\n 'train_size': len(train_idxs),\n 'dev_size': len(dev_idxs),\n 'test_size': int(test_mask.sum()),\n 'test_mask': test_mask.values.tolist(),\n }\n logging.info('Settings:\\n%r', settings)\n json.dump(settings, settings_file, indent=2)\n\n with open(data_out_path, 'w') as data_file:\n # Don't add quoting to retain the original format unaltered.\n df[['set', 'target', 'text']].to_csv(\n data_file,\n sep='\\t',\n header=False,\n index=False,\n quoting=csv.QUOTE_NONE,\n doublequote=False)\n\n\nif __name__ == '__main__':\n flags.mark_flags_as_required(['senteval_path', 'base_out_dir'])\n app.run(main)\n","sub_path":"talk_about_random_splits/probing/split_by_length_threshold_main.py","file_name":"split_by_length_threshold_main.py","file_ext":"py","file_size_in_byte":5162,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"119128830","text":"#!/usr/bin/env python\nimport os\n\n\nfile = open(\"/home/tong/maxsense2.log\")\nout = open(\"/home/tong/maxsense_gpfpd.log\",'w')\n# print>>out ,\"lat\",',',\"lng\"\nfor line in file:\n if \"GPFPD\" in line:\n # print>>out ,line.split(',')[6],',',line.split(',')[7]\n print>>out,line.replace('\"',''),\n","sub_path":"python/catch_gpfpd_longlat.py","file_name":"catch_gpfpd_longlat.py","file_ext":"py","file_size_in_byte":299,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"138053636","text":"import os\nimport tweepy\n\nimport logging\n\nlogger = logging.getLogger(__name__)\n\ndef twitter_api(public_account=True):\n consumer_key = None\n consumer_secret = None\n access_token = None\n access_token_secret = None\n if public_account: # @PlayPartyPi\n try:\n consumer_key = os.environ.get('TWITTER_KEY_PUBLIC')\n consumer_secret = os.environ.get('TWITTER_SECRET_PUBLIC')\n access_token = os.environ.get('TWITTER_TOKEN_PUBLIC')\n access_token_secret = os.environ.get('TWITTER_TOKEN_SECRET_PUBLIC')\n except Exception as e:\n logger.error(\"No twitter auth found: {e}\")\n auth = tweepy.OAuthHandler(consumer_key, consumer_secret)\n auth.set_access_token(access_token, access_token_secret)\n api = tweepy.API(auth)\n return api\n\n\ndef tweet_message(message, public_account=True):\n api = twitter_api(public_account=public_account)\n try:\n api.update_status(status=message)\n print(\"Tweeted: {}\".format(message))\n except tweepy.TweepError as e:\n logger.error(e.reason)\n\n\ndef tweet_image(filename, message, public_account=True):\n api = twitter_api(public_account=public_account)\n api.update_with_media(filename, status=message)\n print(\"Tweeted: {}\".format(message))\n\n\nif __name__ == '__main__':\n logger.info(\"Testing\")\n logger.error(\"Example error\")\n tweet_message(\"Testing the API!\", True)\n # tweet_image('img_car.jpg', 'testing the API!')\n","sub_path":"partypi/utils/tweeter.py","file_name":"tweeter.py","file_ext":"py","file_size_in_byte":1464,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"333465142","text":"from sklearn.grid_search import GridSearchCV\nfrom sklearn import datasets\nfrom sklearn.metrics import precision_score\nfrom sklearn.svm import SVC\n\nfrom modeldb.sklearn_native.ModelDbSyncer import *\nfrom modeldb.sklearn_native import SyncableMetrics\n\n# This is a sample usage of GridSearch in scikit, adapted from\n# http://scikit-learn.org/stable/auto_examples/model_selection/grid_search_digits.html\nname = \"grid search\"\nauthor = \"srinidhi\"\ndescription = \"digits dataset\"\nsyncer_obj = Syncer(\n NewOrExistingProject(name, author, description),\n DefaultExperiment(),\n NewExperimentRun(\"Abc\"))\n\n# Loading the Digits dataset\ndigits = datasets.load_digits()\n\n# To apply an classifier on this data, we need to flatten the image, to\n# turn the data in a (samples, feature) matrix:\nn_samples = len(digits.images)\nX = digits.images.reshape((n_samples, -1))\ny = digits.target\n\n# Split the dataset in two equal parts\nx_train, x_test, y_train, y_test = cross_validation.train_test_split_sync(\n X, y, test_size=0.5, random_state=0)\n\n# Set the parameters by cross-validation\ntuned_parameters = [{'kernel': ['rbf'], 'gamma': [1e-3, 1e-4],\n 'C': [1, 10, 100, 1000]},\n {'kernel': ['linear'], 'C': [1, 10, 100, 1000]}]\n\nclf = GridSearchCV(SVC(C=1), tuned_parameters, cv=5)\nclf.fit_sync(x_train, y_train)\n\nprint(\"The model is trained on the full development set.\")\nprint(\"The scores are computed on the full evaluation set.\")\ny_pred = clf.predict_sync(x_test)\nmean_error = SyncableMetrics.compute_metrics(\n clf, precision_score, y_test, y_pred, x_test, '', '')\n\nsyncer_obj.sync()\n","sub_path":"client/python/samples/sklearn/GridSearchCrossValidation.py","file_name":"GridSearchCrossValidation.py","file_ext":"py","file_size_in_byte":1615,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"285515811","text":"# -*- coding:UTF-8 -*-\n# Author: bigbugboy\n# Software: VS Code\n# Datatime: 2018.12.19\n\ndef reverse(x):\n x = int(x)\n y = 0\n if(x == 0): y = x\n if(x>0):\n s = str(x)\n y = s[::-1]\n if(x<0):\n s = str(x)\n z = s[1:]\n y = \"-\" + z[::-1]\n y = int(y)\n if(y<-2**31 or y>2**31-1):return 0\n else:return y\n\nif __name__ == '__main__':\n x = input(\"请输入要测试的数字\")\n # print(2**31-1)\n # x = 1534236469\n print(reverse(x))","sub_path":"7. Reverse Integer.py","file_name":"7. Reverse Integer.py","file_ext":"py","file_size_in_byte":486,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"578399399","text":"import tensorflow as tf\nfrom keras.preprocessing.image import ImageDataGenerator, array_to_img, img_to_array, load_img\n\n# Data generator to augment data\ndataGenerator = ImageDataGenerator(rotation_range=40,\n width_shift_range=0.2,\n height_shift_range=0.2,\n rescale=1./255,\n shear_range=0.2,\n zoom_range=0.2,\n horizontal_flip=True,\n fill_mode='nearest')\n\n# Test data augmentation\n#img = load_img('Test/2009-04-17_5623_V0_C04_F01.jpg')\n#x = img_to_array(img)\n#x = x.reshape((1,)+x.shape)\n#i=0\n#for batch in dataGenerator.flow(x, batch_size=1,\n# save_to_dir='preview', save_prefix='leish', save_format='jpeg'):\n# i += 1\n# if i > 20:\n# break \n\n\n\n","sub_path":"PrepareData.py","file_name":"PrepareData.py","file_ext":"py","file_size_in_byte":918,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"370119623","text":"import heapq\nfrom typing import *\nfrom point import Point\nimport numpy as np\n\nT = TypeVar('T')\n\n\nclass PriorityQueue:\n def __init__(self):\n self.elements: List[Tuple[float, T]] = []\n\n def empty(self) -> bool:\n return not self.elements\n\n def put(self, item: T, priority: float):\n heapq.heappush(self.elements, (priority, item))\n\n def get(self) -> T:\n return heapq.heappop(self.elements)[1]\n\n\nclass AStar:\n\n @staticmethod\n def heuristic(a: Point, b: Point) -> float:\n return abs(a.x - b.x) + abs(a.y - b.y)\n\n @staticmethod\n def neighbors(map, current: Point) -> [Point]:\n directions = [Point(1, 0), Point(0, 1), Point(-1, 0), Point(0, -1)]\n neighbors_of_current = [current + direction for direction in directions]\n rows, columns = np.shape(map)\n filtered = filter(lambda neighbor: 0 <= neighbor.x < columns and 0 <= neighbor.y < rows and \\\n map[neighbor.y][neighbor.x] == 0, neighbors_of_current)\n return filtered\n\n @staticmethod\n def search(map, start: Point, goal: Point):\n frontier = PriorityQueue()\n frontier.put(start, 0)\n came_from: Dict[Point, Optional[Point]] = {}\n cost_so_far: Dict[Point, float] = {}\n came_from[start] = None\n cost_so_far[start] = 0\n\n while not frontier.empty():\n current: Point = frontier.get()\n\n if current == goal:\n break\n\n for next_neighbor in AStar.neighbors(map, current):\n parent_of_current = came_from.get(current, None)\n # Favor straight lines\n if parent_of_current:\n if next_neighbor.x == current.x == parent_of_current.x or \\\n next_neighbor.y == current.y == parent_of_current.y:\n new_cost = cost_so_far[current] + 1\n else:\n new_cost = cost_so_far[current] + 5\n else:\n new_cost = cost_so_far[current] + 1\n\n if next_neighbor not in cost_so_far or new_cost < cost_so_far[next_neighbor]:\n cost_so_far[next_neighbor] = new_cost\n priority = new_cost + AStar.heuristic(next_neighbor, goal)\n frontier.put(next_neighbor, priority)\n came_from[next_neighbor] = current\n\n return came_from, cost_so_far\n\n\nif __name__ == '__main__':\n\n maze = np.array([[0, 1, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0],\n [0, 1, 0, 1, 0, 0],\n [0, 1, 0, 0, 1, 0],\n [0, 0, 0, 0, 1, 0]])\n\n new_maze = np.full(np.shape(maze), -1)\n\n start = Point(0, 0) # starting position\n end = Point(5, 4) # ending position\n\n came_from, cost_so_far = AStar.search(maze, start, end)\n for point, cost in cost_so_far.items():\n new_maze[point.y][point.x] = cost\n print(new_maze)\n last_elm = end\n print(last_elm)\n while last_elm is not None:\n last_elm = came_from[last_elm]\n print(last_elm)\n","sub_path":"lab1/a_star_search.py","file_name":"a_star_search.py","file_ext":"py","file_size_in_byte":3122,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"18199905","text":"from flask import Blueprint, render_template, redirect, url_for\nfrom myproject import db\nfrom myproject.models import Animal\nfrom myproject.animals.forms import AddForm, DelForm\n\n\n\nanimals_blueprint = Blueprint('animals', __name__,\n template_folder='templates/animals')\n\n\n@animals_blueprint.route('/add',methods =['GET','POST'])\ndef add():\n form = AddForm()\n\n if form.validate_on_submit():\n animalID = form.animalID.data\n startWeight = form.startWeight.data\n w1 = form.w1.data\n w2 = form.w2.data\n w3 = form.w3.data\n w4 = form.w4.data\n finalWeight = form.finalWeight.data\n motherID = form.motherID.data\n fatherID = form.fatherID.data\n diet = form.diet.data\n ch4_daily_mean = form.ch4_daily_mean.data\n feedEfficiency = form.feedEfficiency.data\n waterEfficieny = form.waterEfficieny.data\n\n\n\n # Add new Animal to database\n new_animal = Animal(animalID,startWeight,w1,w2,w3,w4,finalWeight,\n motherID,fatherID,diet,ch4_daily_mean,feedEfficiency,waterEfficieny)\n db.session.add(new_animal)\n db.session.commit()\n\n return redirect(url_for('animals.list'))\n\n return render_template('add.html',form=form)\n\n\n@animals_blueprint.route('/list')\ndef list():\n # Grab a list of animals from database.\n animals = Animal.query.all()\n return render_template('list.html', animals=animals)\n\n#DELETE ANIMAL FROM DATABASE\n@animals_blueprint.route('/delete',methods =['GET','POST'])\ndef delete():\n\n form = DelForm()\n\n if form.validate_on_submit():\n animalID = form.animalID.data\n animal = Animal.query.get(animalID)\n db.session.delete(animal)\n db.session.commit()\n\n return redirect(url_for('animals.list'))\n return render_template('delete.html',form=form)\n\n\n@animals_blueprint.route('/graph/')\ndef graph(input_data):\n \n\n return render_template('graph.html')\n\n\n \n\n \n\n","sub_path":"myproject/animals/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2006,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"290722724","text":"from ROOT import TCanvas, TFile, TH1D, TTree, TLegend\nfrom ROOT import kRed, kBlue\nfrom CMGTools.TTbarTime.proto.samples.fall17.ttbar import mc_signal\nfrom CMGTools.TTbarTime.proto.samples.fall17.ttbar import mc_background\n\nfile_data = TFile(\"$CMSSW_BASE/src/CMGTools/H2TauTau/data/pudistributions_data_2017.root\")\nhist_data = file_data.Get(\"pileup\")\n\nfile_sig = TFile(\"$CMSSW_BASE/src/CMGTools/TTbarTime/data/pileupSignal.root\")\nfile_bkgd = TFile(\"$CMSSW_BASE/src/CMGTools/TTbarTime/data/pileupBackground.root\")\n\nhist_sig = []\nhist_bkgd = []\n\nc = TCanvas()\n\nhist_data.Scale(1./hist_data.Integral())\nhist_data.SetLineWidth(3)\nhist_data.SetLineColor(kRed)\n\n\n\nfor i in range (2):\n hist_sig.append(file_sig.Get(mc_signal[i].dataset.replace('/','#')))\n hist_sig[i].Scale(1./hist_sig[i].Integral())\n hist_sig[i].SetLineWidth(3)\n hist_sig[i].SetLineColor(kBlue)\n hist_data.SetTitle(\"\")\n hist_data.Draw()\n hist_sig[i].Draw(\"SAME\")\n legend = TLegend(0.5,0.5,0.9,0.7)\n legend.AddEntry(hist_data, \"data\", \"l\")\n legend.AddEntry(hist_sig[i], \"MC \"+mc_signal[i].name, \"l\")\n legend.Draw()\n c.SaveAs(\"pu_comparaison/\"+mc_signal[i].name+\".png\")\n c.Clear()\n \nfor i in range(7):\n hist_bkgd.append(file_bkgd.Get(mc_background[i].dataset.replace('/','#')))\n hist_bkgd[i].Scale(1./hist_bkgd[i].Integral())\n hist_bkgd[i].SetLineWidth(3)\n hist_bkgd[i].SetLineColor(kBlue)\n hist_data.SetTitle(\"\")\n hist_data.Draw()\n hist_bkgd[i].Draw(\"SAME\")\n legend = TLegend(0.5,0.5,0.9,0.7)\n legend.AddEntry(hist_data, \"data\", \"l\")\n legend.AddEntry(hist_bkgd[i], \"MC \"+mc_background[i].name, \"l\")\n legend.Draw()\n c.SaveAs(\"pu_comparaison/\"+mc_background[i].name+\".png\")\n c.Clear()\n\n\n\n\n\n\n","sub_path":"TTbarTime/analyze/PU/pileupComparaison.py","file_name":"pileupComparaison.py","file_ext":"py","file_size_in_byte":1730,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"592306322","text":"import pytest\n\nfrom application.model import Oauth\n\n\n@pytest.fixture(scope='function')\ndef oauth_factory(\n user_factory, uuid, db) -> Oauth:\n user = user_factory()\n\n def factory():\n o = Oauth(\n user_id=user.id,\n type='slack',\n email='slacktest@test.com',\n uid=uuid,\n access_token='access_token' + uuid\n )\n db.session.add(o)\n db.session.commit()\n return o\n\n return factory\n","sub_path":"tests/fixtures/oauth.py","file_name":"oauth.py","file_ext":"py","file_size_in_byte":478,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"13452719","text":"#coding: utf-8\n__author__ = 'Abbey'\n\nimport scrapy\nfrom scrapy.contrib.spiders import CrawlSpider, Rule\nfrom xiaozhao.items import XiaozhaoItem\nfrom scrapy.selector import Selector\nimport re\nimport datetime\nimport time\nfrom scrapy.http import Request\nimport sqlite3\nfrom scrapy import signals\nfrom scrapy.xlib.pydispatch import dispatcher\nimport logging\nfrom scrapy.log import ScrapyFileLogObserver\nimport HTMLParser\n\nclass Yjs(CrawlSpider):\n name = \"yjs\"\n allowed_domains = ['yingjiesheng.com']\n\n start_urls = ['http://www.yingjiesheng.com/beijing-morejob-1.html',\n 'http://www.yingjiesheng.com/shanghai-morejob-1.html',\n 'http://www.yingjiesheng.com/guangzhou-morejob-1.html',\n 'http://www.yingjiesheng.com/tianjin-morejob-1.html',\n 'http://www.yingjiesheng.com/nanjing-morejob-1.html',\n 'http://www.yingjiesheng.com/shenzhen-morejob-1.html',\n 'http://www.yingjiesheng.com/jinanjob/list_1.html',\n 'http://www.yingjiesheng.com/wuhan-morejob-1.html',\n 'http://www.yingjiesheng.com/chengdu-morejob-1.html',\n 'http://www.yingjiesheng.com/dalianjob/list_1.html',\n 'http://www.yingjiesheng.com/hangzhoujob/list_1.html',\n 'http://www.yingjiesheng.com/chongqingjob/list_1.html',\n 'http://www.yingjiesheng.com/qingdaojob/list_1.html',\n 'http://www.yingjiesheng.com/fuzhoujob/list_1.html',\n 'http://www.yingjiesheng.com/xianjob/list_1.html',\n 'http://www.yingjiesheng.com/shandongjob/list_1.html',\n 'http://www.yingjiesheng.com/jiangsujob/list_1.html',\n 'http://www.yingjiesheng.com/guangdongjob/list_1.html',\n 'http://www.yingjiesheng.com/liaoningjob/list_1.html',\n 'http://www.yingjiesheng.com/hubeijob/list_1.html',\n 'http://www.yingjiesheng.com/sichuanjob/list_1.html',\n 'http://www.yingjiesheng.com/hebeijob/list_1.html',\n 'http://www.yingjiesheng.com/zhejiangjob/list_1.html',\n 'http://www.yingjiesheng.com/yunnanjob/list_1.html',\n 'http://www.yingjiesheng.com/jilinjob/list_1.html',\n 'http://www.yingjiesheng.com/fujianjob/list_1.html',\n 'http://www.yingjiesheng.com/guizhoujob/list_1.html',\n 'http://www.yingjiesheng.com/shanxijob/list_1.html',\n 'http://www.yingjiesheng.com/henanjob/list_1.html',\n 'http://www.yingjiesheng.com/guangxijob/list_1.html',\n 'http://www.yingjiesheng.com/shanxijob/list_1.html',\n 'http://www.yingjiesheng.com/hunanjob/list_1.html',\n 'http://www.yingjiesheng.com/hainanjob/list_1.html',\n 'http://www.yingjiesheng.com/heilongjiangjob/list_1.html',\n 'http://www.yingjiesheng.com/neimenggujob/list_1.html',\n 'http://www.yingjiesheng.com/gansuningxiaqinghaijob/list_1.html',\n 'http://www.yingjiesheng.com/xinjiangxizangjob/list_1.html',\n 'http://www.yingjiesheng.com/anhuijob/list_1.html',\n 'http://www.yingjiesheng.com/jiangxijob/list_1.html'\n ]\n # start_urls = [\n # \"http://www.yingjiesheng.com/nanjing-morejob-1.html\"\n # ]\n\n def __init__(self):\n CrawlSpider.__init__(self)\n logFile = open('debug.log', 'w')\n log_observer = ScrapyFileLogObserver(logFile, level=logging.INFO)\n log_observer.start()\n self.cx, self.cu = self.sqlite()\n dispatcher.connect(self.spider_closed, signals.spider_closed)\n\n def sqlite(self):\n cx = sqlite3.connect('./link.db')\n cu = cx.cursor()\n cu.execute('create table if NOT EXISTS links (url text PRIMARY key)')\n return cx, cu\n\n def spider_closed(self, spider):\n self.cx.close()\n\n def parse(self, response):\n sel = Selector(response)\n trs = sel.xpath('//tr[@class=\"tr_list\"] | //tr[@class=\"bg_0\"] | tr[@class=\"bg_1\"]')\n for tr in trs:\n link = tr.xpath('td[@class=\"item1\"]/a/@href').extract()\n if link:\n link_str = link[0]\n if link_str[0] == 'h':\n pass\n else:\n link_str = 'http://www.yingjiesheng.com/' + link_str\n date = tr.xpath('td[@class=\"date center\"]/text() | td[@class=\"date cen\"]/text()').extract()\n if date:\n date_str = date[0]\n date_time = datetime.datetime.strptime(date_str, '%Y-%m-%d')\n time_time = int(time.mktime(date_time.timetuple()))\n date_now = datetime.date.today()\n now_time = int(time.mktime(date_now.timetuple()))\n if now_time - time_time <= 1 * 24 * 60 * 60:\n sql = 'select * from links where url=\"' + link_str + '\"'\n self.cu.execute(sql)\n url = self.cu.fetchone()\n if url:\n pass\n else:\n sql = 'insert into links values (\"' + link_str + '\")'\n self.cu.execute(sql)\n self.cx.commit()\n yield Request(link_str, callback=self.parse_page)\n else:\n continue\n url = response.url\n if url in self.start_urls:\n index = url.index('1')\n pre = url[0: index]\n end = url[index+1:]\n for i in range(2, 6):\n nextPage = pre + str(i) + end\n yield Request(nextPage, callback=self.parse)\n try:\n indexOfLine = url.index('-')\n yield Request('www.yingjiesheng.com/' + url[0: indexOfLine] + '/')\n except ValueError:\n pass\n\n def re_yingjiesheng(self):\n pattern_yingjiesheng = re.compile(r'\\W+[yY]{0,1}\\W*ing\\W*[jJ]{0,1}\\W*i{0,1}e{0,1}\\W*[sS]{0,1}\\W*h{0,1}e{0,1}n{0,1}g{0,1}')\n return pattern_yingjiesheng\n\n def parse_page(self, response):\n sel = Selector(response)\n item = XiaozhaoItem()\n item['link'] = [response.url]\n div = sel.xpath('//div[@class=\"mleft\"] | //div[@class=\"com_mleft\"]')\n # item['title'] = div.xpath('h1/text() | div[@class=\"com\"]/h2/a/text()').extract()\n title_t = div.xpath('h1/text() | div[@class=\"com\"]/h2/a/text()').extract()\n if title_t:\n title = title_t[0]\n if title.find('[') >= 0:\n front = title.index('[')\n try:\n end = title.index(']')\n item['title'] = [title[end+1:]]\n citys = title[front+1:end].split('|')\n except ValueError:\n item['title'] = title_t\n else:\n item['title'] = title_t\n else:\n item['title'] = []\n div_info = div.xpath('div[@class=\"info clearfix\"]')\n lis = div_info.xpath('ol')\n for index, li in enumerate(lis.xpath('li')):\n if index == 0:\n item['releaseTime'] = li.xpath('u/text()').extract()\n elif index == 1:\n item['workPlace'] = li.xpath('u/text()').extract()\n elif index == 2:\n item['positionType'] = li.xpath('u/text()').extract()\n elif index == 3:\n item['source'] = li.xpath('u/text()').extract()\n elif index == 4:\n item['position'] = li.xpath('u/text()').extract()\n professionalLabel = div.xpath('div[@style=\"margin-top:10px; overflow:hidden\"]/a/text()').extract()\n if professionalLabel:\n item['professionalLabel'] = professionalLabel\n else:\n item['professionalLabel'] = []\n info = sel.xpath('//div[@class=\"jobIntro\"] | //div[@class=\"job_list\"]')\n try:\n if not item['position']:\n item['position'] = info.xpath('h1/a/text()').extract()\n except KeyError:\n pass\n for index, li in enumerate(info.xpath('ul/li')):\n if index == 0:\n item['workPlace'] = li.xpath('span/text() | span/a/text()').extract()\n elif index == 1:\n item['validDate'] = li.xpath('span/text()').extract()\n elif index == 2:\n item['hiringNumber'] = li.xpath('span/text()').extract()\n elif index == 3:\n item['positionType'] = li.xpath('text()').extract()\n # description = info.xpath('.//a[not[re:test(@href, \"http://bbs.yingjiesheng.com/\\.+\")]]/text() | .//p/text() | .//div/text() | .//span/text() | .//td/text() | text() | .//br | .//strong/text() | .//li/text() | .//th/text() | .//h2/text() | .//font/text()').extract()\n # item['description'] = description\n description = self.handle_description(info)\n pattern = re.compile(r'\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*')\n pattern_yingjiesheng = self.re_yingjiesheng()\n for i, index in enumerate(description):\n match = pattern.search(index)\n if match:\n item['email'] = [match.group()]\n match_yingjiesheng = pattern_yingjiesheng.search(index.lower())\n if match_yingjiesheng:\n description[i] = u''\n item['description'] = description\n # if index == u'
':\n # if i > 0 and description[i-1]:\n # if description[i-1][-1] != u'\\n':\n # description[i] = u'\\n'\n # else:\n # description[i] = u''\n # else:\n # description[i] = u''\n try:\n if citys:\n place_work = u','.join(item['workPlace']).replace(u' ', u',')\n for city in citys:\n if city not in place_work:\n place_work += u','\n place_work += city\n place_work = place_work.replace(u'其它', u'').replace(u'其他', u'').replace(u' ', u'')\n place_work = place_work[1:] if place_work[0] == u',' else place_work\n place_work = place_work[:-1] if place_work[-1] == u',' else place_work\n place_work = place_work.replace(u',,,', u',')\n item['workPlace'] = [place_work]\n except NameError:\n pass\n return item\n\n def handle_description(self, info):\n description = info.extract()\n parse_res = []\n parse = InfoParser(parse_res)\n try:\n parse.feed(description[0])\n parse_res = parse.outRes()\n except IndexError:\n parse_res = []\n return parse_res\n\nclass InfoParser(HTMLParser.HTMLParser):\n def __init__(self, parse_res):\n HTMLParser.HTMLParser.__init__(self)\n self.parse_res = parse_res\n self.table = []\n\n def handle_starttag(self, tag, attrs):\n if tag.lower() in (u'tbody', u'td', u'tr'):\n if tag.lower() == u'tbody':\n self.table.append(u'tbody')\n self.parse_res.append(u'\\n')\n if self.table and (tag.lower() == 'tbody' or tag.lower() == 'tr'):\n self.parse_res.append(u'<%s>\\n' % tag)\n elif self.table and tag.lower() == u'td':\n self.parse_res.append(u'<%s>' % tag)\n elif tag == u'br':\n self.parse_res.append(u'\\n')\n\n def handle_endtag(self, tag):\n if tag.lower() in (u'tbody', u'td', u'tr'):\n if self.table:\n self.parse_res.append(u'\\n' % tag)\n if tag.lower() == u'tbody':\n self.table.pop()\n self.parse_res.append(u'
')\n\n def handle_data(self, data):\n if re.match(u'\\u672c\\u7ad9\\u63d0\\u9192:\\u5982\\u4f55\\u8bc6\\u522b\\u865a\\u5047\\u62db\\u8058\\u4fe1\\u606f\\uff1f\\u6c42\\u804c\\u5fc5\\u770b\\uff0c\\u5207\\u52ff\\u53d7\\u9a97\\u4e0a\\u5f53\\uff01', data) or re.match(u'\\u5982\\u4f55\\u5199\\u4e00\\u4efd\\u7b80\\u5355\\u3001\\u76f4\\u63a5\\u3001\\u9ad8\\u6548\\u7684\\u6c42\\u804c\\u4fe1\\uff1f', data):\n pass\n else:\n if data:\n if data[-1] == u'\\n':\n data = data.strip()\n data += u'\\n'\n else:\n data = data.strip()\n if data.strip():\n self.parse_res.append('

%s

' % data)\n else:\n self.parse_res.append(data)\n\n def handle_entityref(self, name):\n self.parse_res.append(u'&%s;' % name)\n\n def handle_charref(self, name):\n self.parse_res.append(u'&#%s;' % name)\n\n def outRes(self):\n return self.parse_res","sub_path":"xiaozhao/xiaozhao/spiders/yingJieSheng.py","file_name":"yingJieSheng.py","file_ext":"py","file_size_in_byte":12857,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"396822070","text":"# Copyright 2017 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS-IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"Produces tfrecord files similar to the YouTube-8M dataset.\n\nIt processes a CSV file containing lines like \",\", where\n must be a path of a video, and must be an integer list\njoined with semi-colon \";\". It processes all videos and outputs tfrecord file\nonto --output_file.\n\nIt assumes that you have OpenCV installed and properly linked with ffmpeg (i.e.\nfunction `cv2.VideoCapture().open('/path/to/some/video')` should return True).\n\nThe binary only processes the video stream (images) and not the audio stream.\n\"\"\"\n\nimport csv\nimport os\nimport sys\nimport numpy as np\nimport time\nimport numpy\n#import tensorflow as tf\n#from tensorflow import flags\nfrom multiprocessing import Pool, Manager\nimport subprocess\n\nimport argparse\nimport random\n\narg_parser = argparse.ArgumentParser(description='filter_parser')\narg_parser.add_argument('--data_tmp', type=str,\n default=False, help='mapper')\narg_parser.add_argument('--input_videos_csv', type=str,\n default=False, help='reducer')\nFLAGS = arg_parser.parse_args()\n\nworkders_queue = {}\n# worker进程数,别设置多了,和自己的cpu核心数有关。\nMAX_WORKER_NUM = 10\n\n# 生产者与消费者模型的应用\ndef init_worker_queue():\n # 为每一个worker进程分配自己的队列\n for i in range(0, MAX_WORKER_NUM):\n workders_queue[i] = Manager().Queue()\n\n\ndef read_data():\n index = 0\n for line in open(FLAGS.input_videos_csv):\n q = workders_queue[index % MAX_WORKER_NUM]\n vid,label = line.strip().split(',')\n #print('w=',vid)\n q.put(vid)\n index += 1\n for q in workders_queue.values():\n q.put(None)\n\n\ndef workder_data(worker_id):\n print(\"worker_id:{}\".format(worker_id))\n n = 0\n begin = time.time()\n #fos = open('{}/stat/worker_{}'.format(FLAGS.data_tmp, worker_id), 'w', buffering=0)\n fos = open('{}/stat/worker_{}'.format(FLAGS.data_tmp, worker_id), 'w')\n while True:\n q = workders_queue[worker_id]\n data = q.get()\n n += 1\n if data == None:\n print('finished',worker_id)\n break\n video_path = data\n vid = video_path.split('/')[-1].split('.')[0]\n video = '/'.join([FLAGS.data_tmp, str(worker_id), vid])\n wav_cmd = ['ffmpeg', '-loglevel quiet', '-y', '-i {}'.format(video_path), '-f wav {}.wav'.format(video)]\n frame_cmd = ['ffmpeg', '-loglevel quiet', '-y', '-i {}'.format(video_path), '-t 300 -vframes 300 -r 1 {}_%d.jpg'.format(video)]\n #print(' '.join(wav_cmd))\n print('id={} num={} video={}'.format(worker_id, n, video))\n res1 = subprocess.call(' '.join(wav_cmd), shell=True)\n res2 = subprocess.call(' '.join(frame_cmd), shell=True)\n fos.write('{}\\t{}\\t{}\\t{}\\n'.format(vid, video, res1, res2))\n print('worker:{} total_num={} qps={:.3f}'.format(worker_id, n, n/float(time.time() - begin)))\n fos.close()\n\n\nif __name__ == '__main__':\n #res1 = subprocess.call('ffmpeg -loglevel quiet -y -i /da5/taisimin/data/tuitui/DAM/src/data/40/972784854442646640.mp4 -f wav frame//9/972784854442646640.wav video=frame//9/972784854442646640', shell=True)\n #print(res1)\n #return -1\n start_time = time.time()\n init_worker_queue()\n p = Pool(MAX_WORKER_NUM)\n p.apply_async(read_data)\n for i in range(0, MAX_WORKER_NUM):\n dirs = '{}/{}'.format(FLAGS.data_tmp, i)\n if not os.path.exists(dirs):\n os.mkdir(dirs)\n dirs = '{}/stat'.format(FLAGS.data_tmp)\n if not os.path.exists(dirs):\n os.mkdir(dirs)\n for i in range(0, MAX_WORKER_NUM):\n p.apply_async(workder_data, args=(i,))\n p.close()\n p.join()\n end_time = time.time()\n print('handle time:%ss' % (end_time - start_time))\n","sub_path":"feature_extractor/extract_frame_and_audio.py","file_name":"extract_frame_and_audio.py","file_ext":"py","file_size_in_byte":4169,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"320576769","text":"#!/usr/bin/env python3\n#!c:/Python35/python3.exe -u\nimport asyncio\nimport sys\nimport cv2\nimport numpy as np\nimport cozmo\nimport time\nimport os\nimport _thread\nimport cv2\n\n\nfrom cozmo.util import degrees, distance_mm\n\nfrom glob import glob\n\nfrom find_cube import *\n\ntry:\n # for Python2\n from Tkinter import * ## notice capitalized T in Tkinter\nexcept ImportError:\n # for Python3\n from tkinter import *\n\ntry:\n from PIL import ImageDraw, ImageFont, Image, ImageTk\nexcept ImportError:\n sys.exit('run `pip3 install --user Pillow numpy` to run this example')\ndef nothing(x):\n pass\n\n\n\nGREEN_LOWER = np.array([0,0,0])\nGREEN_UPPER = np.array([179, 255, 60])\nmakeImage = 0\n\n\n# def filter_image(img, hsv_lower, hsv_upper):\n#\n# # Modify mask\n# imgToBlur = cv2.medianBlur(img,5)\n# imagehsv = cv2.cvtColor(imgToBlur, cv2.COLOR_BGR2HSV)\n# mask = cv2.inRange(imagehsv,hsv_lower,hsv_upper)\n# image2 = cv2.bitwise_and(255-img, 255-img, mask = mask)\n# #cv2.namedWindow( \"imagex\", cv2.WINDOW_NORMAL );\n# #cv2.imshow(\"imagex\", image2)\n# #cv2.namedWindow( \"imagey\", cv2.WINDOW_NORMAL );\n# #cv2.imshow(\"imagey\",img)\n# #cv2.waitKey(0)\n# #cv2.destroyAllWindows()\n# return mask\n\n#\n# def detect_blob(mask):\n# img = cv2.medianBlur(255 - mask, 9)\n# # cv2.namedWindow( \"imagey\", cv2.WINDOW_NORMAL )\n# # cv2.imshow(\"imagey\",img)\n# # cv2.waitKey(0)\n# # cv2.destroyAllWindows()\n#\n# # Set up the SimpleBlobdetector with default parameters with specific values.\n# params = cv2.SimpleBlobDetector_Params()\n#\n# params.filterByColor = True\n#\n# params.filterByArea = True\n# params.minArea = 10\n#\n# params.filterByConvexity = False\n# params.minConvexity = 0.7\n# params.filterByCircularity = False\n# params.minCircularity = 0\n#\n# # builds a blob detector with the given parameters\n# detector = cv2.SimpleBlobDetector_create(params)\n#\n# # use the detector to detect blobs.\n# keypoints = detector.detect(img)\n# print(\"keypoints\", keypoints)\n#\n# return len(keypoints)\n\n\n\n# Define a decorator as a subclass of Annotator; displays the keypoint\nclass BoxAnnotator(cozmo.annotate.Annotator):\n\n cube = None\n\n def apply(self, image, scale):\n d = ImageDraw.Draw(image)\n bounds = (0, 0, image.width, image.height)\n\n if BoxAnnotator.cube is not None:\n\n #double size of bounding box to match size of rendered image\n BoxAnnotator.cube = np.multiply(BoxAnnotator.cube,2)\n\n #define and display bounding box with params:\n #msg.img_topLeft_x, msg.img_topLeft_y, msg.img_width, msg.img_height\n box = cozmo.util.ImageBox(BoxAnnotator.cube[0]-BoxAnnotator.cube[2]/2,\n BoxAnnotator.cube[1]-BoxAnnotator.cube[2]/2,\n BoxAnnotator.cube[2], BoxAnnotator.cube[2])\n cozmo.annotate.add_img_box_to_image(image, box, \"green\", text=None)\n\n BoxAnnotator.cube = None\n\ndef buttonclick():\n global makeImage\n makeImage= 1\n\n\nasync def run(sdk_conn):\n robot= await sdk_conn.wait_for_robot()\n\n mainWindow = Toplevel()\n coz = Tk()\n cozmo.tkview.TkImageViewer(tk_root=coz)\n\n Label(mainWindow, text=\"Gain\").grid(row=0)\n\n gainx = Scale(mainWindow, from_=0.2, to=3.9, orient=HORIZONTAL, resolution=0.01)\n gainx.grid(row=0, column=1)\n\n Label(mainWindow, text=\"Exposure\").grid(row=1)\n exposurex = Scale(mainWindow, from_=1, to=67, orient=HORIZONTAL, resolution=0.01)\n exposurex.grid(row=1, column=1)\n\n Label(mainWindow, text=\"Hue Lower\").grid(row=2)\n hueL = Scale(mainWindow, from_=0, to=255, orient=HORIZONTAL)\n hueL.grid(row=2, column=1)\n Label(mainWindow, text=\"Hue Upper\").grid(row=3)\n hueU = Scale(mainWindow, from_=0, to=255, orient=HORIZONTAL)\n hueU.grid(row=3, column=1)\n\n Label(mainWindow, text=\"Saturation Lower\").grid(row=4)\n saturationL = Scale(mainWindow, from_=0, to=255, orient=HORIZONTAL)\n saturationL.grid(row=4, column=1)\n Label(mainWindow, text=\"Saturation Upper\").grid(row=6)\n saturationU = Scale(mainWindow, from_=0, to=255, orient=HORIZONTAL)\n saturationU.grid(row=6, column=1)\n\n Label(mainWindow, text=\"Value Lower\").grid(row=7)\n valueL = Scale(mainWindow, from_=0, to=255, orient=HORIZONTAL)\n valueL.grid(row=7, column=1)\n Label(mainWindow, text=\"Value Upper\").grid(row=8)\n valueU = Scale(mainWindow, from_=0, to=255, orient=HORIZONTAL)\n valueU.grid(row=8, column=1)\n\n\n b = Button(mainWindow, text=\"filter\", command = buttonclick)\n b.grid(row=9, column = 0)\n #imageView = Canvas();\n #imageView.pack(side='top', fill='both', expand='yes')\n l = Label(mainWindow)\n l.grid(row=10, column=0)\n\n\n\n robot.world.image_annotator.annotation_enabled = False\n robot.world.image_annotator.add_annotator('box', BoxAnnotator)\n\n robot.camera.image_stream_enabled = True\n robot.camera.color_image_enabled = True\n robot.camera.enable_auto_exposure = True\n\n global makeImage\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n #gain,exposure,mode = 390,3,0\n mode = 1\n\n try:\n\n while True:\n YELLOW_LOWER = np.array([hueL.get(), saturationL.get(), valueL.get()])\n YELLOW_UPPER = np.array([hueU.get(), saturationU.get(), valueU.get()])\n exposure = exposurex.get()\n gain = gainx.get()\n #print(gainx, \" \",exposurex)\n\n event = await robot.world.wait_for(cozmo.camera.EvtNewRawCameraImage) #get camera image\n if event.image is not None:\n #image = cv2.cvtColor(np.asarray(event.image), cv2.COLOR_BGR2RGB)\n image = np.asarray(event.image)\n mask = filter_image(np.asanyarray(event.image),YELLOW_LOWER,YELLOW_UPPER)\n #b,g,r = cv2.split(mask)\n #display = cv2.merge((mask))\n im = Image.fromarray(cv2.bitwise_and(image,image,mask = mask))\n imgtk = ImageTk.PhotoImage(image=im)\n l.configure(image = imgtk)\n detect_blob(mask)\n # if (makeImage == 1):\n # print(\"makeing window?\")\n #\n # cv2.namedWindow(\"window\",cv2.WINDOW_NORMAL)\n # cv2.imshow( \"window\", mask)\n # makeImage=0\n if mode == 1:\n robot.camera.enable_auto_exposure = True\n else:\n robot.camera.set_manual_exposure(exposure,gain)\n\n #find the cube\n cube = find_cube(image, YELLOW_LOWER, YELLOW_UPPER)\n print(cube)\n BoxAnnotator.cube = cube\n\n ################################################################\n\n # Todo: Add Motion Here\n ################################################################\n await robot.set_head_angle(degrees(0)).wait_for_completed()\n #look_around = robot.start_behavior(cozmo.behavior.BehaviorTypes.LookAroundInPlace)\n # try:\n # cube = await robot.world.wait_for_observed_light_cube(timeout=1)\n # print(\"Found cube: %s\" % cube)\n # except asyncio.TimeoutError:\n # print(\"Didn't find a cube\")\n # finally:\n # # whether we find it or not, we want to stop the behavior\n # look_around.stop()\n # if cube:\n # action = robot.go_to_object(cube, distance_mm(50.0))\n # await action.wait_for_completed()\n # print(\"Completed action: result = %s\" % action)\n # print(\"Done.\")\n\n\n\n except KeyboardInterrupt:\n print(\"\")\n print(\"Exit requested by user\")\n except cozmo.RobotBusy as e:\n print(e)\n #cv2.destroyAllWindows()\ndef runCozmoRun():\n try:\n\n cozmo.connect_with_tkviewer(run)\n\n except:\n print(\"Unexpected error:\", sys.exc_info())\n\n\n\n\nif __name__ == '__main__':\n\n cv2.namedWindow(\"window\",cv2.WINDOW_NORMAL)\n runCozmoRun()\n\n\n\n","sub_path":"livefilter.py","file_name":"livefilter.py","file_ext":"py","file_size_in_byte":8141,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"589430785","text":"from hashlib import md5\nfrom multiprocessing import Lock, cpu_count, Value\nfrom multiprocessing.pool import Pool\n\n\n# 全局变量\nclass Global(object):\n lock = Lock()\n _count = Value('i', 0)\n _total = Value('i', 0)\n\n @classmethod\n def acquire(cls):\n cls.lock.acquire()\n\n @classmethod\n def release(cls):\n cls.lock.release()\n\n @classmethod\n def countAdd(cls, value=1):\n cls.acquire()\n cls._count.value += value\n cls.release()\n \n @classmethod\n def reset(cls):\n cls.acquire()\n cls._count.value = 0\n cls._total.value = 0\n cls.release()\n\n @classmethod\n def count(cls):\n return cls._count.value\n\n @classmethod\n def setTotal(cls, value):\n cls._total.value = value\n \n @classmethod\n def total(cls):\n return cls._total.value\n\n @classmethod\n def status(cls):\n if cls.total != 0:\n r = cls.count() / cls.total()\n return r\n else:\n return None\n\n\ndef getFileMD5(file, itemList):\n m = md5()\n f = open(file, 'rb')\n buffer = 8192\n while 1:\n chunk = f.read(buffer)\n if not chunk:\n break\n m.update(chunk)\n f.close()\n Global.countAdd()\n itemList.append((file, m.hexdigest()))\n\n\np = Pool((cpu_count()-1)*2)\n\n\ndef enter(files):\n for file in files:\n p.apply_async(getFileMD5, file)","sub_path":"check.py","file_name":"check.py","file_ext":"py","file_size_in_byte":1412,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"519842122","text":"import cv2\nimport numpy as np\n\ndef detect():\n cap = cv2.VideoCapture(0)\n\n while(cap.isOpened()):\n ret, frame = cap.read()\n\n if ret == True:\n\n #let me show the streaming video to the user by using the function cv.imshow('window name', frame)\n #let me flip the image first, the show it\n frame = cv2.flip(frame, 1)\n cv2.imshow('Management Eye System', frame)\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n else:\n break\n cv2.release()\n cv2.destroyAllWindows()\n\n\ndetect()\n\n\n","sub_path":"stream.py","file_name":"stream.py","file_ext":"py","file_size_in_byte":578,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"405306576","text":"from planning import *\n\n\ndef murder():\n return PlanningProblem(\n initial='Married(Alex) & Married(Ann) & MarryWith(Alex, Ann) & MarryWith(Ann, Alex) '\n '& Single(Diana) & WorkAt(Alex, School) & WorkAt(Diana, School) ',\n goals='plan_to_kill(Alex, Diana)',\n actions=[\n Action('have_an_affair(p1, p2)',\n precond='Married(p1) & Love(p1, p2) & Love(p2, p1) & Person(p1) & Person(p2)',\n effect='Affair(p1, p2)',\n domain='Person(p1) & Person(p2)'\n ),\n Action('fall_in_love(p1, p2, l)',\n precond='WorkAt(p1, l) & WorkAt(p2, l) & Person(p1) & Person(p2) & Location(l)',\n effect='Love(p1, p2) & Love(p2, p1)',\n domain='Person(p1) & Person(p2) & Location(l)'\n ),\n Action('want_to_reveal_affair_to(p1, p2, p3)',\n precond='Affair(p1, p2) & MarryWith(p1, p3)',\n effect='plan_to_kill(p1, p2)',\n domain='Person(p1) & Person(p2) & Person(p3)'\n ),\n ],\n domain='Person(Ann) & Person(Alex) & Person(Diana) & Location(School)'\n )\n\n\nst = murder()\npop = PartialOrderPlanner(st)\npop.execute()\n","sub_path":"newStory.py","file_name":"newStory.py","file_ext":"py","file_size_in_byte":1274,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"205969818","text":"#!/usr/bin/env python3\nimport pandas as pd\n\ndef get_path(filename):\n import sys\n import os\n return os.path.join(os.path.dirname(sys.argv[0]), \"..\", \"src\", filename)\n\nDAYS = {\n \"ma\": \"Mon\",\n \"ti\": \"Tue\",\n \"ke\": \"Wed\",\n \"to\": \"Thu\",\n \"pe\": \"Fri\",\n \"la\": \"Sat\",\n \"su\": \"Sun\"\n}\n\nMONTHS = {\n \"tammi\": 1,\n \"helmi\": 2,\n \"maalis\": 3,\n \"huhti\": 4,\n \"touko\": 5,\n \"kesä\": 6,\n \"heinä\": 7,\n \"elo\": 8,\n \"syys\": 9,\n \"loka\": 10,\n \"marras\": 11,\n \"joulu\": 12,\n}\n\n\ndef split_date(df):\n d = df[\"Päivämäärä\"].str.split(expand=True)\n d.columns = [\"Weekday\", \"Day\", \"Month\", \"Year\", \"Hour\"]\n\n hourmin = d[\"Hour\"].str.split(\":\", expand=True)\n d[\"Hour\"] = hourmin.iloc[:, 0]\n\n d[\"Weekday\"] = d[\"Weekday\"].map(DAYS)\n d[\"Month\"] = d[\"Month\"].map(MONTHS)\n\n d = d.astype({\"Weekday\": object, \"Day\": int, \"Month\": int, \"Year\": int, \"Hour\": int})\n return d\n\ndef split_date_continues():\n raw = pd.read_csv(get_path('Helsingin_pyorailijamaarat.csv'), sep=';')\n df = raw.dropna(how='all', axis=0).dropna(how='all', axis=1)\n split_dates = split_date(df)\n df = df.drop(columns=\"Päivämäärä\")\n df = pd.concat([split_dates, df], axis=1)\n return df\n\ndef main():\n df = split_date_continues()\n print(\"Shape:\", df.shape)\n print(\"Column names:\\n\", df.columns)\n print(df.head())\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"prev-weeks/part05-e01_split_date_continues/src/split_date_continues.py","file_name":"split_date_continues.py","file_ext":"py","file_size_in_byte":1405,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"456262564","text":"__author__ = 'lukebusstra'\n__version__ = '1.0'\n\nimport time\nimport datetime\nimport json\n\ndateTime = None\n\n#Builds the ADCLogs\ndef BuildADCLogs():\n global dateTime\n dateTime = time.ctime(time.time())[4:16].replace(\" \", \"-\")\n adclog = open(\"../Logs/ADCLog.csv\", 'w')\n adclogPast = open(format(\"../Logs/Past/ADCLog%s.csv\" % dateTime), 'w')\n adclog.write(\"Time, Main Battery, Left Solar, Center Solar, Right Solar\\n\")\n adclogPast.write(\"Time, Main Battery, Left Solar, Center Solar, Right Solar\\n\")\n adclog.closed\n adclogPast.closed\n\n#Builds the DataLogs\ndef BuildDataLogs():\n global dateTime\n dateTime = time.ctime(time.time())[4:16].replace(\" \", \"-\")\n adclog = open(\"../Logs/DataLog.csv\", 'w')\n adclogPast = open(format(\"../Logs/Past/DataLog%s.csv\" % dateTime), 'w')\n adclog.write(\"Time, Long, Late, Ground Alt, Altitude, Speed, Voltage1, Current1, Voltage2, Current2, Voltage3, Current3, Voltage4, Current4, Signal\\n\")\n adclogPast.write(\"Time, Long, Late, Ground Alt, Altitude, speed, Voltage1, Current1, Voltage2, Current2, Voltage3, Current3, Voltage4, Current4, Signal\\n\")\n adclog.closed\n adclogPast.closed\n\n\n\n#Main Method\npreviousId = 100\n \ntry:\n BuildADCLogs()\n BuildDataLogs()\n\n #Loop to record data\n while True:\n try:\n \n #Opens the Json file and collects the data\n wjdata = json.loads(open('../data/QUTONEWebServer.json').read())\n\n while(previousId < wjdata['id']):\n \n #Checks to see that the\n if (wjdata['id'] == previousId):\n previousId = wjdata['id']\n \n #Converts Voltage and Current to Power \n Power1 = float(wjdata['Voltage1'])*float(wjdata['Current1'])\n Power2 = float(wjdata['Voltage2'])*float(wjdata['Current2'])\n Power3 = float(wjdata['Voltage3'])*float(wjdata['Current3'])\n Power4 = float(wjdata['Voltage4'])*float(wjdata['Current4'])\n\n #Creates the Log Texts\n adcText = format(\"%s, %f, %f, %f, %f\\n\" % (datetime.datetime.now().strftime('%H:%M:%S.%f'), Power1, Power2, Power3, Power4)) \n dataText = format(\"%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s\\n\" % (datetime.datetime.now().strftime('%H:%M:%S.%f'), wjdata['long'], wjdata['late'], wjdata['ground_alt'], wjdata['alt'], wjdata['speed'], wjdata['Voltage1'], wjdata['Current1'], wjdata['Voltage2'], wjdata['Current2'], wjdata['Voltage3'], wjdata['Current3'], wjdata['Voltage4'], wjdata['Current4']))\n\n #Opens the Log Files and adds the data\n adclog = open(\"../Logs/ADCLog.csv\", 'a')\n adclogPast = open(format(\"../Logs/Past/ADCLog%s.csv\" % dateTime), 'a')\n adclog.write(adcText)\n adclogPast.write(adcText)\n adclog.closed\n adclogPast.closed\n\n #Opens the Data Files and adds the data\n Datalog = open(\"../Logs/DataLog.csv\", 'a')\n DatalogPast = open(format(\"../Logs/Past/DataLog%s.csv\" % dateTime), 'a')\n Datalog.write(dataText) \n DatalogPast.write(dataText)\n Datalog.closed\n DatalogPast.closed\n\n time.sleep(0.5)\n except:\n time.sleep(0.2)\nexcept KeyboardInterrupt:\n pass\n","sub_path":"python/BackUpDataLogs.py","file_name":"BackUpDataLogs.py","file_ext":"py","file_size_in_byte":3089,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"580090892","text":"import os\nfrom flask import Flask\nfrom flask_restful import Api\nfrom resources.users import UserRegister, UserDelete\nfrom resources.titles import Browse, AddToList, DeleteFromList, ViewList\nfrom resources.sessions import Login, Logout\n\napp = Flask(__name__)\n\n#app.config['DEBUG'] = True # required for local testing to create db, commented for cloud hosting\n\n# App configuration: Database and app secret key\ndb_url = os.environ.get('DATABASE_URL') # For Heroku, comment for local execution \napp.config['SQLALCHEMY_DATABASE_URI'] = db_url.replace(\"://\", \"ql://\", 1) # For Heroku, comment for local execution\n# app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///data.db' # For Local, comment for Heroku execution \napp.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False\napp.secret_key = 'QMUL_CC_T12'\napi = Api(app)\n\n# Specify End-Points\n# Endpoint: Home\n@app.route('/')\ndef home_endpoint():\n text = 'Welcome to World TV Database. \\nBrowse your favrourite TV shows and movies. \\nSign up and save your watchlist.\\\n \\nMore features coming up. \\nUse service endpoints to use our services'\n return text, 200\n# Main services endpoints\napi.add_resource(UserRegister, '/register')\napi.add_resource(Browse, '/browse/')\napi.add_resource(Login, '/login')\napi.add_resource(Logout, '/logout')\napi.add_resource(AddToList, '/add-to-list')\napi.add_resource(DeleteFromList, '/delete-from-list')\napi.add_resource(UserDelete, '/delete-user')\napi.add_resource(ViewList, '/view-list')\n\nif __name__ == '__main__':\n from db import db\n db.init_app(app)\n\n if app.config['DEBUG']:\n @app.before_first_request\n def create_tables():\n from models.admin import AdminModel\n db.create_all()\n AdminModel().save_to_db()\n\n app.run(host='0.0.0.0')\n\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1833,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"27870041","text":"from selenium import webdriver\nfrom selenium.webdriver.common.keys import Keys\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.common.exceptions import WebDriverException\nfrom selenium.common.exceptions import TimeoutException\nfrom selenium.common.exceptions import NoSuchElementException\nfrom selenium.common.exceptions import StaleElementReferenceException\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.common.action_chains import ActionChains\n\nfrom datetime import datetime\nfrom pyquery import PyQuery as pq\n\nimport psutil\nimport pendulum\nimport arrow\nimport time\nimport re\nimport os\nimport types\nimport traceback \nimport threading\n\nenv = types.SimpleNamespace()\n\nenv.chrome_options = webdriver.ChromeOptions()\nenv.chrome_options.add_argument('--disable-gpu')\nenv.chrome_options.add_argument('--disable-software-rasterizer')\nenv.chrome_options.add_argument('--disable-extensions')\nenv.chrome_options.add_argument('--disable-logging')\nenv.chrome_options.add_argument('--disable-infobars')\nenv.chrome_options.add_argument('--ignore-certificate-errors')\n\nenv.user_agent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36'\nenv.chrome_options_headless = webdriver.ChromeOptions()\nenv.chrome_options_headless.add_argument('--headless')\nenv.chrome_options_headless.add_argument('--user-agent=\"' + env.user_agent + '\"')\nenv.chrome_options_headless.add_argument('--disable-gpu')\nenv.chrome_options_headless.add_argument('--disable-software-rasterizer')\nenv.chrome_options_headless.add_argument('--disable-extensions')\nenv.chrome_options_headless.add_argument('--disable-logging')\nenv.chrome_options_headless.add_argument('--disable-infobars')\nenv.chrome_options_headless.add_argument('--ignore-certificate-errors')\n\ndef start_browser(headless=False):\n if headless:\n env.browser = webdriver.Chrome(options=env.chrome_options_headless)\n else:\n env.browser = webdriver.Chrome(options=env.chrome_options)\n \ndef close_browser():\n env.browser.quit()\n\ndef load_url(url):\n if not any([url.startswith('http'), url.startswith('file')]):\n url = 'https://'+url\n env.browser.get(url)\n\ndef fe(css, el=None):\n if el is None:\n el = env.browser \n return el.find_element_by_css_selector(css)\n\ndef fes(css, el=None):\n if el is None:\n el = env.browser \n return el.find_elements_by_css_selector(css)\n\ndef move_to(el, offset=0):\n if type(el) == str:\n ActionChains(env.browser).move_to_element(fe(el)).perform()\n else:\n assert type(el) is WebElement\n ActionChains(env.browser).move_to_element(el).perform()\n \n while offset:\n if offset > 0:\n ActionChains(env.browser).send_keys(Keys.ARROW_DOWN).perform()\n offset -= 1\n elif offset < 0:\n ActionChains(env.browser).send_keys(Keys.ARROW_UP).perform()\n offset += 1\n\ndef sleep(secondes):\n time.sleep(secondes)\n\ndef wait(secondes):\n env.browser.implicitly_wait(secondes)\n\ndef warit_for(secondes, condition, element=None, css=None, text=None):\n if condition == \"presence\":\n assert css is not None\n\n return WebDriverWait(env.browser, secondes).until(\n EC.presence_of_element_located((By.CSS_SELECTOR, css)))\n\n elif condition == \"staleness\":\n assert element is not None\n\n return WebDriverWait(env.browser, secondes).until(EC.staleness_of(element))\n\n elif condition == \"visibility\":\n assert css is not None\n\n return WebDriverWait(env.browser, secondes).until(\n EC.visibility_of_element_located((By.CSS_SELECTOR, css)))\n\n elif condition == \"invisibility\":\n assert css is not None\n\n return WebDriverWait(env.browser, secondes).until(\n EC.invisibility_of_element_located((By.CSS_SELECTOR, css)))\n\ndef wait_and_switch_to_frame(secondes, css):\n assert css is not None\n WebDriverWait(env.browser, secondes).until(\n EC.frame_to_be_available_and_switch_to_it((By.CSS_SELECTOR, css)))\n\n\ndef switch_to_default_frame():\n env.browser.switch_to.default_content()\n\n\ndef switch_to_parent_frame():\n env.browser.switch_to.parent()\n\n\ndef fill_text(css_selector, text):\n js_templ = \"\"\"\n el=document.querySelector('{css_selector}');\n el.value = '{value}';\n el.dispatchEvent(new Event('change'));\n \"\"\"\n js = js_templ.format(css_selector=css_selector, value=text)\n env.browser.execute_script(js)\n\n\ndef try_it(func, args=[], kwargs={}, max_retries=10, retry_interval=0.5, exceptions=[WebDriverException], err_keys=[]):\n count = 0\n while True:\n try:\n func(*args, **kwargs)\n break\n except WebDriverException as e:\n print(str(e))\n traceback.print_exc()\n \n count += 1\n if count > max_retries:\n break\n \n check1 = list(map(lambda E: type(e) is E, exceptions))\n check2 = list(map(lambda key: key in str(e), err_keys))\n \n if any(check1 + check2):\n sleep(retry_interval)\n print(\"=====================\" + str(count) + \" retries =====================\")\n continue\n else:\n break\n\ndef click(el):\n if type(el) == str:\n fe(el).click()\n else:\n assert type(el) is WebElement\n el.click()\n \ndef try_click(el):\n args = [el]\n kwargs = {}\n exceptions = [NoSuchElementException]\n err_keys = ['is not clickable at point']\n try_it(click, args=args, exceptions=exceptions, err_keys=err_keys)\n\nclass Frame():\n def __init__(self, css_selector):\n self.css_selector\n\n def __enter__(self):\n return wait_and_switch_to_frame(15, self.css_selector)\n \n def __exit__(self, *args):\n switch_to_parent_frame()\n\n\n# # process safe execute a method\n# def execute_it(function, arguments):\n# pass\n\n","sub_path":"libs/selenium_shortcuts.py","file_name":"selenium_shortcuts.py","file_ext":"py","file_size_in_byte":6063,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"611709837","text":"from django.contrib.auth import get_user_model\nfrom fcm_django.models import FCMDevice\nfrom rest_framework import serializers\n\nfrom accounts.models import User, Notification\nfrom video.models import Video\nfrom .models import *\nfrom django.conf import settings\n\n\nclass UserSerializer(serializers.ModelSerializer):\n image = serializers.SerializerMethodField('get_image')\n\n def get_image(self, user):\n return settings.GLOBAL_HOST + user.profile.image.url\n\n class Meta:\n model = get_user_model()\n ref_name = 'comment.user'\n fields = ['id', 'username', 'email', 'image']\n\n\nclass CreateCashBoxSerializer(serializers.ModelSerializer):\n user_id = serializers.IntegerField(required=True)\n\n class Meta:\n model = CashBox\n fields = ['user_id', 'method', 'operator', 'props_number', 'amount']\n\n\nclass CreateTransferSerializer(serializers.ModelSerializer):\n user_id = serializers.IntegerField(required=True)\n username = serializers.CharField(required=True)\n\n class Meta:\n model = Transfer\n fields = ['user_id', 'username', 'amount', 'code']\n\n\nclass CreatePromoCodeSerializer(serializers.ModelSerializer):\n user_id = serializers.IntegerField(required=True)\n\n class Meta:\n model = PromoCode\n fields = ['user_id', 'code']\n\n\nclass ReceiveTransferSerializer(serializers.ModelSerializer):\n username = serializers.CharField(required=True)\n\n class Meta:\n model = Transfer\n fields = ['username', 'code']\n\n\nclass AgentPromoCodesSerializer(serializers.ModelSerializer):\n class Meta:\n model = PromoCode\n fields = '__all__'\n depth = 1\n\n\nclass TransferHistorySerializer(serializers.ModelSerializer):\n sender = UserSerializer()\n\n class Meta:\n model = Transfer\n fields = ['id', 'sender', 'receiver', 'amount', 'code', 'create_at',\n 'is_paid',\n 'is_read']\n\n\nclass CashBoxHistorySerializer(serializers.ModelSerializer):\n user = UserSerializer()\n\n class Meta:\n model = CashBox\n fields = ['id', 'method', 'operator', 'props_number', 'amount',\n 'is_paid', 'create_at', 'user']\n\n\nclass UpdateTransferReadSerializer(serializers.ModelSerializer):\n transfer_id = serializers.IntegerField(required=True)\n read = serializers.BooleanField(default=False)\n user_id = serializers.IntegerField(required=True)\n\n class Meta:\n model = Transfer\n fields = ['transfer_id', 'user_id', 'read']\n\n\nclass CreateDonateTransferSerializer(serializers.ModelSerializer):\n class Meta:\n model = DonateTransfer\n fields = ['amount']\n\n\nclass CreateDonateForCompanySerializer(serializers.ModelSerializer):\n class Meta:\n model = DonateTransfer\n fields = ['amount']\n\n def validate(self, attrs):\n request = self.context.get('request')\n if request.user.profile.balance < attrs['amount']:\n raise serializers.ValidationError({\n 'amount': 'In your balance does not enough'\n ' this amount for transfer'\n })\n return attrs\n\n def create(self, validated_data):\n request = self.context.get('request')\n user = request.user\n user.profile.balance -= float(validated_data.get('amount'))\n user.profile.withdrawn_balance += float(validated_data.get('amount'))\n user.profile.save()\n nz_club = User.objects.get(username='nz_club')\n nz_club.profile.balance += float(validated_data.get('amount'))\n nz_club.profile.save()\n transfer = Transfer.objects.create(\n sender=user,\n receiver=request.data['username'],\n amount=request.data['amount'],\n )\n device = FCMDevice.objects.filter(user=nz_club)\n device_sender = FCMDevice.objects.filter(user=user)\n device.send_message(title=\"Перевод💰\",\n body=f\"Пользователь {user.username} отправил(а) вам {request.data['amount']}\",\n icon=settings.GLOBAL_HOST + nz_club.profile.image.url,\n data={'type': '4'})\n Notification.objects.create(user=nz_club, title=\"Перевод💰\",\n body=f\"Пользователь {user.username} отправил(а) вам {request.data['amount']}\",\n image=settings.GLOBAL_HOST + nz_club.profile.image.url,\n type='4')\n device_sender.send_message(title=\"Перевод💰\",\n body=f\"Вы перевели пользователю {nz_club.username} {request.data['amount']}\",\n icon=settings.GLOBAL_HOST + nz_club.profile.image.url,\n data={'type': '3'})\n Notification.objects.create(user=user, title=\"Перевод💰\",\n body=f\"Вы перевели пользователю {nz_club.username} {request.data['amount']}\",\n image=settings.GLOBAL_HOST + nz_club.profile.image.url,\n type='3')\n return transfer\n","sub_path":"cashbox/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":5244,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"323595390","text":"import numpy as np\n# import matplotlib.pyplot as plt\nfrom scipy.integrate import trapz, simps\n\n\ndef make_gauss(N, sig, mu):\n return lambda x: (N/(sig * (2*np.pi)**.5) * np.e ** (-(x-mu)**2/(2 * sig**2)))\n\n\ndef getScore(history, array):\n return 0\n print('history: ',history)\n print('array: ',array)\n percentage = [0, 0.4, 0.6, 0.8, 1]\n print('longuer array: ', len(array))\n importance = 1/len(array)\n totalScore = 0\n for score in array:\n temp = percentage[score] * importance\n totalScore += temp\n s80 = totalScore * 0.8\n s20 = percentage[history] * 0.2\n print('s80: '+str(s80))\n print('s20: '+str(s20))\n print('score du vecteur: '+ str(s80 + s20))\n return s80 + s20\n\n\ndef generateRepartition(score):\n x = np.arange(-100, 100, 0.1)\n sig = np.sqrt(100)\n sig=0.1\n mu = score # Correspond a p(m) => esperance\n mu = 0.44\n\n x1 = np.arange(-1000, 0.4, 0.001)\n x2 = np.arange(0.4, 0.6, 0.001)\n x3 = np.arange(0.6, 0.8, 0.001)\n x4 = np.arange(0.8, 1000, 0.001)\n p1 = trapz(make_gauss(1, sig, mu)(x1), x1)\n p2 = trapz(make_gauss(1, sig, mu)(x2), x2)\n p3 = trapz(make_gauss(1, sig, mu)(x3), x3)\n p4 = trapz(make_gauss(1, sig, mu)(x4), x4)\n \n print('p(0) == 1 si le vecteur est nul sinon p(0) == 0')\n print('p(1): '+str(p1))\n print('p(2): '+str(p2))\n print('p(3): '+str(p3))\n print('p(4): '+str(p4))\n print('Somme des probabilite : '+ str(p1 + p2 + p3 + p4))\n\n\ndef printGaussian(m):\n ax = plt.figure().add_subplot(1,1,1)\n x = np.arange(-100, 100, 0.1)\n s = np.sqrt(100)\n # m = [30] # Correspond a p(m) => esperance\n c = ['b']\n\n \n gauss = make_gauss(1, s, m)(x)\n ax.plot(x, gauss, c, linewidth=2)\n\n plt.xlim(-100, 100)\n plt.ylim(0, 1)\n plt.legend(['m='+str(m)+' s=sqrt(100)'], loc='best')\n plt.show()\n\ndef getGrade(score):\n if(score < 0.4):\n return 1\n if (0.4<= score and score < 0.6):\n return 2\n if (0.6<= score and score < 0.8):\n return 3\n if (0.8 <= score and score < 1):\n return 4\n else:\n return 0\n\n# def main():\n# result = getScore(1, [2,1,0,3])\n# print(result)\n# # generateRepartition(result)\n# # printGaussian(result)\n# if __name__ == '__main__':\n# main()\n","sub_path":"src/classes/helper/gauss.py","file_name":"gauss.py","file_ext":"py","file_size_in_byte":2272,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"568269034","text":"import numpy as np\nfrom feature_bussiness.FeatureMain import *\nfrom scipy.stats import ks_2samp\nfrom utils.Utils import *\nfrom xgboost import XGBClassifier\nimport pickle\nfrom abc import *\nfrom global_vars.constants import *\n\n\nclass IAnalysator(metaclass=ABCMeta):\n class Core:\n def __init__(self):\n self.rgf = None\n self.feature_adder = None\n self.features = None\n\n @classmethod\n @abstractmethod\n def get_target_column(cls):\n return ''\n\n def purify(self):\n for key in self.__dict__.keys():\n if type(self.__dict__[key]) != self.Core:\n self.__dict__[key] = None\n\n def preprocessing(self):\n self.df_train = self.df_train_r.copy() if self.df_train_r is not None else None\n self.df_test = self.df_test_r.copy() if self.df_test_r is not None else None\n self.df_reject = self.df_reject_r.copy() if self.df_reject_r is not None else None\n\n def anal_prepare(self, df_c, have_extraneous_features=False):\n df = df_c.copy()\n if have_extraneous_features:\n df = df[self.core.features]\n df = Utils.dummy_base_cols_fill(df)\n main_columns = sorted(Utils.remove_values_from_list(Utils.remove_values_from_list(self.get_target_column(), base_features), df.columns))\n df = df[main_columns]\n x = df.drop(columns=self.get_target_column(), errors='ignore' if have_extraneous_features else 'raise').values\n y = df[self.get_target_column()].values\n\n features = df.drop(columns=self.get_target_column()).columns\n return x, y, features\n\n @abstractmethod\n def train_rgf(self, x_train, y_train, light=False):\n return XGBClassifier()\n\n @abstractmethod\n def afterwards(self):\n pass\n\n def __init__(self, *train_test_reject):\n self.df_train_r = None\n self.df_test_r = None\n self.df_reject_r = None\n self.df_train = None\n self.df_test = None\n self.df_reject = None\n self.cores = 1 if low_memory else 5\n self.core = self.Core()\n\n self.train_data_predictions = None\n self.test_data_predictions = None\n self.reject_data_predictions = None\n self.target_column = self.get_target_column()\n self.filters = result_filter\n self.mean_dur_train = None\n if len(train_test_reject) == 3:\n self.df_train_r = train_test_reject[0].copy()\n self.df_test_r = train_test_reject[1].copy()\n self.df_reject_r = train_test_reject[2].copy()\n self.core.feature_adder = FeatureMain(target_col=self.get_target_column())\n self.preprocessing()\n self.state = 'test'\n elif len(train_test_reject) == 1 and type(train_test_reject[0]) == pd.DataFrame:\n self.df_train_r = train_test_reject[0].copy()\n self.core.feature_adder = FeatureMain(target_col=self.get_target_column())\n self.preprocessing()\n self.state = 'refitted'\n elif len(train_test_reject) == 1 and type(train_test_reject[0] == self.Core):\n self.core = train_test_reject[0]\n self.state = 'loaded'\n else:\n raise ValueError('Incorrect number of args.')\n\n def train(self, light=False):\n df_train = self.core.feature_adder.fit_transform(self.df_train)[0]\n x_train, y_train, self.core.features = self.anal_prepare(df_train)\n self.core.rgf = self.train_rgf(x_train, y_train, light=light)\n if self.state == 'test':\n x_train, _, _ = self.anal_prepare(self.core.feature_adder.transform(self.df_train_r)[0])\n x_test, _, _ = self.anal_prepare(self.core.feature_adder.transform(self.df_test_r)[0])\n x_reject, _, _ = self.anal_prepare(self.core.feature_adder.transform(self.df_reject_r)[0])\n train_data_predictions = self.core.rgf.predict_proba(x_train)[:, 1] if 'predict_proba' in dir(self.core.rgf) else self.core.rgf.predict(x_test)\n test_data_predictions = self.core.rgf.predict_proba(x_test)[:, 1] if 'predict_proba' in dir(self.core.rgf) else self.core.rgf.predict(x_test)\n reject_data_predictions = self.core.rgf.predict_proba(x_reject)[:, 1] if 'predict_proba' in dir(self.core.rgf) else self.core.rgf.predict(x_reject)\n\n self.train_data_predictions = pd.concat([self.df_train_r, pd.DataFrame({'prediction': train_data_predictions})], axis=1).copy()\n self.test_data_predictions = pd.concat([self.df_test_r, pd.DataFrame({'prediction': test_data_predictions})], axis=1).copy()\n self.reject_data_predictions = pd.concat([self.df_reject_r, pd.DataFrame({'prediction': reject_data_predictions})], axis=1).copy()\n self.afterwards()\n return self\n\n def predict(self, df_c, have_extraneous_features=False):\n df = df_c[Utils.remove_values_from_list(base_features, df_c.columns)]\n df = df[df.columns].copy()\n for x in base_features:\n df[x] = np.nan\n df = self.core.feature_adder.transform(df)[0]\n x, _, f = self.anal_prepare(df, have_extraneous_features=have_extraneous_features)\n if set(self.core.features) != set(f):\n print('Seems that input features does not correspond with ones being trained on...')\n return self.core.rgf.predict_proba(x)[:, 1] if 'predict_proba' in dir(self.core.rgf) else self.core.rgf.predict(x)\n","sub_path":"analysators/IAnalisator.py","file_name":"IAnalisator.py","file_ext":"py","file_size_in_byte":5416,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"380315714","text":"import os\nimport numpy as np\n\nimport pandas as pd\nfrom keras.models import Sequential\nfrom keras.layers import Dense, LSTM\n\n\nbasepath=os.path.abspath(os.path.dirname(__file__))\ndata = pd.read_csv(basepath+'/train_data.csv')\ndata= data.sample(frac = 1)\ninput_len =data.shape[0]\ntsteps = 2\nlahead = data.shape[1]-2\nbatch_size = 1000\nepochs = 10\n\nrow=data.shape[0]\ncol=data.shape[1]\n\nfeatures=data.iloc[:,1:col-1]\nlabels=data.iloc[:,col-1]\n\n\n\n\ndef split_data(x, y, ratio=1):\n to_train = int(input_len * ratio)\n # tweak to match with batch_size\n to_train -= to_train % batch_size\n\n x_train = x[:to_train]\n y_train = y[:to_train]\n x_test = x[to_train:]\n y_test = y[to_train:]\n\n # tweak to match with batch_size\n to_drop = x.shape[0] % batch_size\n if to_drop > 0:\n x_test = x_test[:-1 * to_drop]\n y_test = y_test[:-1 * to_drop]\n\n # some reshaping\n reshape_3=lambda x: x.values.reshape((x.shape[0], x.shape[1], 1))\n x_train = reshape_3(x_train)\n x_test = reshape_3(x_test)\n reshape_2 = lambda x: x.values.reshape((x.shape[0], 1))\n y_train = reshape_2(y_train)\n y_test = reshape_2(y_test)\n return (x_train, y_train), (x_test, y_test)\n\ndef lstm():\n (x_train, y_train), (x_test, y_test) = split_data(features,labels)\n model = Sequential()\n model.add(LSTM(20,\n input_shape=(lahead, 1),\n batch_size=batch_size,\n stateful=False))\n model.add(Dense(1))\n model.compile(loss='mse', optimizer='adam')\n\n print('Training')\n for i in range(epochs):\n print('Epoch', i + 1, '/', epochs)\n model.fit(x_train,\n y_train,\n batch_size=batch_size,\n epochs=1,\n verbose=1,\n shuffle=False)\n\n model.reset_states()\n\n model.save('machine_learning/my_model.h5')\n \n","sub_path":"基于可信度的网络威胁情报繁殖系统/machine_learning/lstm.py","file_name":"lstm.py","file_ext":"py","file_size_in_byte":1882,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"83471099","text":"import random\n\noptions = ('rock', 'paper', 'scissors')\n\ndef play_game():\n\n ai = random.choice(options)\n\n hand = input(\"Rock, Paper, Scissors, Shoot: \")\n\n game(hand, ai)\n\ndef game(hand, ai):\n\n if hand == ai:\n print('Tie!')\n \n if hand == 'rock' and ai == 'paper':\n print('You lose!')\n if hand == 'rock' and ai == 'scissors':\n print('You win!')\n\n if hand == 'paper' and ai == 'rock':\n print('You win!')\n if hand == 'paper' and ai == 'scissors':\n print('You lose!')\n\n if hand == 'scissors' and ai == 'rock':\n print('You lose!')\n if hand == 'scissors' and ai == 'paper':\n print('You win!')\n\n\nif __name__ == '__main__':\n play_game()\n while 'y' == input('Would you like to play again? (y/n)').lower():\n play_game()\n","sub_path":"rps.py","file_name":"rps.py","file_ext":"py","file_size_in_byte":803,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"177876074","text":"# -*- coding: utf-8 -*-\nimport unittest\n\nfrom mock import patch, Mock\n\nfrom marketo import auth\nfrom marketo import Client\nfrom marketo.wrapper import exceptions\nfrom marketo.wrapper import get_lead\nfrom marketo.wrapper import get_lead_activity\nfrom marketo.wrapper import request_campaign\nfrom marketo.wrapper import sync_lead\n\n\nclass TestAuth(unittest.TestCase):\n\n def test_header(self):\n user_id = \"_user_id_\"\n encryption_key = \"_encryption_key_\"\n timestamp = \"_timestamp_\"\n signature = \"_signature_\"\n\n with patch(\"marketo.rfc3339.rfc3339\", return_value=timestamp):\n with patch(\"marketo.auth.sign\", return_value=signature):\n actual_result = auth.header(user_id, encryption_key)\n\n expected_result = \"<env:Header>\" \\\n \"<ns1:AuthenticationHeader>\" \\\n \"<mktowsUserId>%s</mktowsUserId>\" \\\n \"<requestSignature>%s</requestSignature>\" \\\n \"<requestTimestamp>%s</requestTimestamp>\" \\\n \"</ns1:AuthenticationHeader>\" \\\n \"</env:Header>\" % (user_id, signature, timestamp)\n\n self.assertEqual(actual_result,\n expected_result)\n\n\nclass TestExceptionParser(unittest.TestCase):\n\n def test_non_xml_message(self):\n exception_message = 'Non XML message'\n exception_instance = exceptions.unwrap(exception_message)\n\n self.assertTrue(isinstance(exception_instance, exceptions.MktException))\n self.assertEqual(exception_instance.args, (\"Marketo exception message parsing error: %s\" % exception_message, ))\n\n def test_fault_with_details(self):\n exception_message = '<?xml version=\"1.0\" encoding=\"UTF-8\"?>' \\\n '<SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\">' \\\n '<SOAP-ENV:Body>' \\\n '<SOAP-ENV:Fault>' \\\n '<faultcode>SOAP-ENV:Client</faultcode>' \\\n '<faultstring>20103 - Lead not found</faultstring>' \\\n '<detail>' \\\n '<ns1:serviceException xmlns:ns1=\"http://www.marketo.com/mktows/\">' \\\n '<name>mktServiceException</name>' \\\n '<message>No lead found with EMAIL = john@do.com (20103)</message>' \\\n '<code>20103</code>' \\\n '</ns1:serviceException>' \\\n '</detail>' \\\n '</SOAP-ENV:Fault>' \\\n '</SOAP-ENV:Body>' \\\n '</SOAP-ENV:Envelope>'\n exception_instance = exceptions.unwrap(exception_message)\n\n self.assertTrue(isinstance(exception_instance, exceptions.MktLeadNotFound))\n self.assertEqual(exception_instance.args, (\"No lead found with EMAIL = john@do.com (20103)\", ))\n\n def test_fault_without_details(self):\n exception_message = '<?xml version=\"1.0\" encoding=\"UTF-8\"?>' \\\n '<SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\">' \\\n '<SOAP-ENV:Body>' \\\n '<SOAP-ENV:Fault>' \\\n '<faultcode>SOAP-ENV:Client</faultcode>' \\\n '<faultstring>Bad Request</faultstring>' \\\n '</SOAP-ENV:Fault>' \\\n '</SOAP-ENV:Body>' \\\n '</SOAP-ENV:Envelope>'\n exception_instance = exceptions.unwrap(exception_message)\n\n self.assertTrue(isinstance(exception_instance, exceptions.MktException))\n self.assertEqual(exception_instance.args, (\"Bad Request\", ))\n\n\nclass TestGetLead(unittest.TestCase):\n\n def test_get_lead_wrap(self):\n self.assertEqual(get_lead.wrap(\"email\", \"john@do.com\"),\n u\"<ns1:paramsGetLead>\"\n u\"<leadKey>\"\n u\"<keyType>EMAIL</keyType>\"\n u\"<keyValue>john@do.com</keyValue>\"\n u\"</leadKey>\"\n u\"</ns1:paramsGetLead>\")\n self.assertEqual(get_lead.wrap(\"cookie\", \"561-HYG-937&token:_mch-marketo.com-1258067434006-50277\"),\n u\"<ns1:paramsGetLead>\"\n u\"<leadKey>\"\n u\"<keyType>COOKIE</keyType>\"\n u\"<keyValue>561-HYG-937&token:_mch-marketo.com-1258067434006-50277</keyValue>\"\n u\"</leadKey>\"\n u\"</ns1:paramsGetLead>\")\n\n\nclass TestGetLeadActivity(unittest.TestCase):\n\n def test_get_lead_activity_wrap(self):\n self.assertEqual(get_lead_activity.wrap(\"john@do.com\"),\n u\"<ns1:paramsGetLeadActivity>\"\n u\"<leadKey>\"\n u\"<keyType>EMAIL</keyType>\"\n u\"<keyValue>john@do.com</keyValue>\"\n u\"</leadKey>\"\n u\"</ns1:paramsGetLeadActivity>\")\n\n\nclass TestRequestCampaign(unittest.TestCase):\n\n def test_request_campaign_wrap(self):\n self.assertEqual(request_campaign.wrap(campaign=1, lead='2'),\n u'<mkt:paramsRequestCampaign>'\n u'<source>MKTOWS</source>'\n u'<campaignId>1</campaignId>'\n u'<leadList>'\n u'<leadKey>'\n u'<keyType>IDNUM</keyType>'\n u'<keyValue>2</keyValue>'\n u'</leadKey>'\n u'</leadList>'\n u'</mkt:paramsRequestCampaign>')\n\n\nclass TestSyncLead(unittest.TestCase):\n\n def test_sync_lead_wrap(self):\n # with empty attribute set\n self.assertEqual(sync_lead.wrap(email=\"john@do.com\", attributes=()),\n u\"<mkt:paramsSyncLead>\"\n u\"<leadRecord>\"\n u\"<Email>john@do.com</Email>\"\n u\"<leadAttributeList></leadAttributeList>\"\n u\"</leadRecord>\"\n u\"<returnLead>true</returnLead>\"\n u\"<marketoCookie></marketoCookie>\"\n u\"</mkt:paramsSyncLead>\")\n\n # with 1 attribute\n self.assertEqual(sync_lead.wrap(email=\"john@do.com\", attributes=((\"Name\", \"string\", u\"John Do, a hős\"),)),\n u\"<mkt:paramsSyncLead>\"\n u\"<leadRecord>\"\n u\"<Email>john@do.com</Email>\"\n u\"<leadAttributeList>\"\n u\"<attribute>\"\n u\"<attrName>Name</attrName>\"\n u\"<attrType>string</attrType>\"\n u\"<attrValue>John Do, a hős</attrValue>\"\n u\"</attribute>\"\n u\"</leadAttributeList>\"\n u\"</leadRecord>\"\n u\"<returnLead>true</returnLead>\"\n u\"<marketoCookie></marketoCookie>\"\n u\"</mkt:paramsSyncLead>\")\n\n # with more attributes\n self.assertEqual(sync_lead.wrap(email=\"john@do.com\", attributes=((\"Name\", \"string\", \"John Do\"),\n (\"Age\", \"integer\", \"20\"),)),\n u\"<mkt:paramsSyncLead>\"\n u\"<leadRecord>\"\n u\"<Email>john@do.com</Email>\"\n u\"<leadAttributeList>\"\n u\"<attribute>\"\n u\"<attrName>Name</attrName>\"\n u\"<attrType>string</attrType>\"\n u\"<attrValue>John Do</attrValue>\"\n u\"</attribute>\"\n u\"<attribute>\"\n u\"<attrName>Age</attrName>\"\n u\"<attrType>integer</attrType>\"\n u\"<attrValue>20</attrValue>\"\n u\"</attribute>\"\n u\"</leadAttributeList>\"\n u\"</leadRecord>\"\n u\"<returnLead>true</returnLead>\"\n u\"<marketoCookie></marketoCookie>\"\n u\"</mkt:paramsSyncLead>\")\n\nclass TestGetCampaignsForSource(unittest.TestCase):\n def test_wrap(self):\n pass\nclass TestGetTags(unittest.TestCase):\n def test_wrap(self):\n pass\n# TODO 2014-03-01: Figure out what call to make to get a list of leads on a campaign\n\n\nclass TestClient(unittest.TestCase):\n\n def test_wrap(self):\n soap_endpoint = \"_soap_endpoint_\"\n user_id = \"_user_id_\"\n encryption_key = \"_encryption_key_\"\n client = Client(soap_endpoint=soap_endpoint, user_id=user_id, encryption_key=encryption_key)\n body = \"<body/>\"\n header = \"<header/>\"\n\n with patch(\"marketo.auth.header\", return_value=header):\n actual_result = client.wrap(body=body)\n\n self.assertEqual(actual_result,\n u'<env:Envelope xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" '\n u'xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" '\n u'xmlns:wsdl=\"http://www.marketo.com/mktows/\" '\n u'xmlns:env=\"http://schemas.xmlsoap.org/soap/envelope/\" '\n u'xmlns:ins0=\"http://www.marketo.com/mktows/\" '\n u'xmlns:ns1=\"http://www.marketo.com/mktows/\" '\n u'xmlns:mkt=\"http://www.marketo.com/mktows/\">'\n u'{header}'\n u'<env:Body>'\n u'{body}'\n u'</env:Body>'\n u'</env:Envelope>'.format(header=header, body=body))\n\n def test_get_lead_with_not_found(self):\n soap_endpoint = \"_soap_endpoint_\"\n user_id = \"_user_id_\"\n encryption_key = \"_encryption_key_\"\n client = Client(soap_endpoint=soap_endpoint, user_id=user_id, encryption_key=encryption_key)\n\n mock_response = Mock(status_code=0, text=\"<root>\"\n \"<detail>\"\n \"<message>No lead found with IDNUM = 1 (20103)</message>\"\n \"<code>20103</code>\"\n \"</detail>\"\n \"</root>\")\n try:\n with patch.object(client, \"request\", return_value=mock_response):\n client.get_lead(idnum=1)\n except exceptions.MktLeadNotFound as e:\n self.assertEqual(str(e), \"No lead found with IDNUM = 1 (20103)\")\n except Exception as e:\n self.assertTrue(isinstance(e, exceptions.MktLeadNotFound), repr(e))\n\n def test_get_lead_with_found(self):\n soap_endpoint = \"_soap_endpoint_\"\n user_id = \"_user_id_\"\n encryption_key = \"_encryption_key_\"\n client = Client(soap_endpoint=soap_endpoint, user_id=user_id, encryption_key=encryption_key)\n\n mock_response = Mock(status_code=200, text=\"<root>\"\n \"<leadRecord>\"\n \"<Id>100</Id>\"\n \"<Email>john@do.com</Email>\"\n \"</leadRecord>\"\n \"</root>\")\n with patch.object(client, \"request\", return_value=mock_response):\n lead = client.get_lead(email=\"john@do.com\")\n\n self.assertEqual(lead.id, 100)\n self.assertEqual(lead.email, \"john@do.com\")\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":11950,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"429832882","text":"#!/usr/bin/python\n# python类学习\n\nimport os\n\ntest = '''This is a program about file I/O.\n\nAuthor: Late Lee\nDate: 2016.5.14'''\n\n# 打开方式有:w r a r+ w+ a+\nf = open(\"test.txt\", \"w\")\nf.write(test) # write text to file\nf.close()\n\n# 默认为r\nf = open(\"test.txt\")\nprint(\"name: %s --%s size:%d\" % (os.path.basename(f.name), os.path.dirname(f.name), os.path.getsize(f.name)))\n\n\nwhile True:\n line = f.readline()\n if len(line) == 0: # zero length indicates the EOF of the file\n break\n print(line)\n\nf.close()\n\n##################################\n## 读配置文件\n\ntry:\n f = open('cdist.txt', 'r')\n while True:\n l = f.readline()\n if l == '': # 结束\n break\n\n if len(l) > 0 and l[0] == '#':\n continue\n\n s = l.strip().split() # 分割,生成不同个数的列表,如['a','b','c']\n if len(s) == 2:\n print(\"%s == %s\" % (s[0], s[1]))\n print(\"%s\" % s[0][0]) #第一个字符\nexcept:\n raise","sub_path":"file_test.py","file_name":"file_test.py","file_ext":"py","file_size_in_byte":997,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"16564390","text":"import requests\nfrom bs4 import BeautifulSoup\n\nfrom bs4 import BeautifulSoup\nimport urllib2\nimport pandas as pd\nimport requests\n\nclient = requests.Session()\n\nHOMEPAGE_URL = 'https://www.linkedin.com'\nLOGIN_URL = 'https://www.linkedin.com/uas/login-submit'\n\nhtml = client.get(HOMEPAGE_URL).content\nsoup = BeautifulSoup(html, \"lxml\")\ncsrf = soup.find(id=\"loginCsrfParam-login\")['value']\n\nlogin_information = {\n 'session_key':'iliass.tahiri@gmail.com',\n 'session_password':'@ncis@5',\n 'loginCsrfParam': csrf,\n}\n\nclient.post(LOGIN_URL, data=login_information)\n\n#client.get('https://www.linkedin.com/search/results/index/?keywords=Ecole%20Mohammadia%20d%27Ing%C3%A9nieurs')\n\npage = urllib2.urlopen(\"https://www.linkedin.com/mynetwork/\").read()\nsoup = BeautifulSoup(page,\"lxml\") # Or Using a function - beautify(\"https://www.linkedin.com/search/results/index/?keywords=Ecole%20Mohammadia%20d%27Ing%C3%A9nieurs\")\nS_profiles=soup.findAll(\"body\") #x=soup.findAll(\"ul\",{\"class\":\"results-list ember-view\"})","sub_path":"log_linked2.py","file_name":"log_linked2.py","file_ext":"py","file_size_in_byte":1005,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"392649897","text":"def findStrongestEnemy(enemies):\n strongest = None\n strongestHealth = 0\n for enemy in enemies:\n if enemy.health > strongestHealth:\n strongest = enemy\n strongestHealth = enemy.health\n return strongest\n\n\nleader = findStrongestEnemy(hero.findEnemies())\nif leader:\n hero.say(leader)\n","sub_path":"7_Sarven_Desert/349-Brittle_Morale/battle_morale.py","file_name":"battle_morale.py","file_ext":"py","file_size_in_byte":323,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"584112833","text":"#!/usr/bin/env python3\n\nimport re\nimport rospy\nfrom std_msgs.msg import String\nfrom lg_common import AdhocBrowserPool\nfrom lg_msg_defs.msg import AdhocBrowsers\nfrom lg_common import AdhocBrowserDirectorBridge\nfrom lg_common.helpers import make_soft_relaunch_callback, handle_initial_state\nfrom lg_common.helpers import run_with_influx_exception_handler\nfrom interactivespaces_msgs.msg import GenericMessage\nfrom lg_msg_defs.msg import Ready\n\nNODE_NAME = 'lg_adhoc_browser'\nfrom lg_common.logger import get_logger\nlogger = get_logger(NODE_NAME)\n\n\ndef main():\n rospy.init_node(NODE_NAME, anonymous=True)\n\n extensions_root = rospy.get_param('~extensions_root', '/opt/endpoint/chrome/extensions/')\n viewport_name = rospy.get_param('~viewport', None)\n rosbridge_port = rospy.get_param('~rosbridge_port', 9090)\n rosbridge_host = rospy.get_param('~rosbridge_port', 'localhost')\n depend_on_rosbridge = rospy.get_param('~depend_on_rosbridge', True)\n global_dependency_timeout = rospy.get_param('/global_dependency_timeout', 15)\n hide_delay = rospy.get_param('~hide_delay', 0.5)\n destroy_delay = rospy.get_param('~destroy_delay', 2)\n\n if not viewport_name:\n logger.error(\"Viewport is not set in the roslaunch file. Exiting.\")\n exit(1)\n\n \"\"\"\n Initialize adhoc browser pool\n \"\"\"\n\n topic_name = 'browser_service/{}'.format(viewport_name)\n common_topic_name = 'browser_service/browsers'\n\n adhocbrowser_pool = AdhocBrowserPool(viewport_name=viewport_name,\n extensions_root=extensions_root,\n hide_delay=hide_delay,\n destroy_delay=destroy_delay)\n\n make_soft_relaunch_callback(adhocbrowser_pool.handle_soft_relaunch,\n groups=[\"media\"])\n\n rospy.Subscriber(\n topic_name,\n AdhocBrowsers,\n adhocbrowser_pool.handle_ros_message\n )\n\n \"\"\"\n Initialize director => browser pool bridge that translates director GenericMessage to AdhocBrowsers.msg\n \"\"\"\n\n adhocbrowser_viewport_publisher = rospy.Publisher(\n topic_name, AdhocBrowsers, queue_size=3)\n\n adhocbrowser_aggregate_topic_publisher = rospy.Publisher(common_topic_name,\n AdhocBrowsers,\n queue_size=3)\n\n adhocbrowser_director_bridge = AdhocBrowserDirectorBridge(\n adhocbrowser_aggregate_topic_publisher,\n adhocbrowser_viewport_publisher,\n viewport_name)\n\n rospy.Subscriber('director/scene', GenericMessage, adhocbrowser_director_bridge.translate_director)\n rospy.Subscriber('director/ready', Ready, adhocbrowser_pool.unhide_browsers)\n\n handle_initial_state(adhocbrowser_director_bridge.translate_director)\n\n \"\"\"\n Initialize overlay hiding listener\n \"\"\"\n def getBrowserIds(msg):\n s = msg.data\n if '[' in s and ']' in s:\n ids = [sp for sp in re.split('\\[\\]\\, ', s) if len(sp) > 0]\n adhocbrowser_pool.minimize_browsers(ids)\n else:\n adhocbrowser_pool.minimize_browsers([s])\n\n rospy.Subscriber('director/minimize', String, getBrowserIds)\n\n \"\"\"\n Spin FTW\n \"\"\"\n rospy.spin()\n\n\nif __name__ == \"__main__\":\n run_with_influx_exception_handler(main, NODE_NAME)\n","sub_path":"lg_common/scripts/adhoc_browser.py","file_name":"adhoc_browser.py","file_ext":"py","file_size_in_byte":3377,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"627845030","text":"\"\"\"\nAssignment 4\nName: 蔡淵丞\nStudent Number: 110502567\nCourse: 2021-CE1003-B\n\"\"\"\nwith open(\"score.txt\", \"r\") as f:\n data = list(map(lambda x : x.split() , f.readlines()))\n\nwith open(\"score_110502567.txt\", \"w\") as f:\n for i in data:\n sum = 0\n if i == data[0]:\n continue\n for j in range(1,5):\n sum += int(i[j])\n i.append(sum/4)\n for lines in data:\n for items in lines:\n f.write(str(items)+\" \")\n if items == lines[5]:\n f.write(\"\\n\")","sub_path":"CS/A4-110502567/A4-110502567-1.py","file_name":"A4-110502567-1.py","file_ext":"py","file_size_in_byte":536,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"551352012","text":"import clr\r\nclr.AddReference('ProtoGeometry')\r\nfrom Autodesk.DesignScript.Geometry import *\r\n\r\n#import libraby left of dynamo to use in python\r\nclr.AddReference('RevitNodes')\r\nimport Revit\r\nfrom Revit.Elements import * # import namspace element in Revit Dynamo\r\nclr.ImportExtensions(Revit.Elements) # use wrap elemnt dynamo with revit (.ToDSType(False))\r\nclr.ImportExtensions(Revit.GeometryConversion) #Convert XYZ double to Point in Revit and Covert dynamo to Revit\r\n\r\n#import Revit Api(C#)\r\nclr.AddReference('RevitApi')\r\nfrom Autodesk.Revit.DB import *\r\n\r\n#iImport library to use Transaction update and create elment in revit Api\r\nclr.AddReference('RevitServices')\r\nfrom RevitServices.Persistence import DocumentManager\r\nfrom RevitServices.Transactions import TransactionManager\r\n\r\nfrom math import *\r\n\r\n#Import a module to file python\r\nimport sys\r\nsys.path.append(r\"C:\\Users\\Windows 10\\Documents\\LearnPython\")\r\nimport lesson5\r\n\r\n#The inputs to this node will be stored as a list in the IN variables.\r\ninputValue1 = IN[0]\r\n\r\nvalueRevit= UnwrapElement(IN[0]) # Get Elment Python use from Dynamo\r\nfamily = UnwrapElement(IN[1])\r\n\r\nlines = IN[0].ToRevitType() # Convert dynamo to revit type of element.\r\n\r\n#Create document\r\ndoc= DocumentManager.Instance.CurrentDBDocument\r\n\r\n#start Transaction Api\r\nTransactionManager.Instance.EnsureInTransaction(doc)\r\n\r\n#Do some thing\r\n\r\nwrappedCol= columnCreate.ToDSType(False) ; #False if want control Revit from Dynamo, True then not control\r\n\r\n#stop Transaction Api\r\nTransactionManager.Instance.TransactionTaskDone()\r\n\r\n#Filter Element in RevitApi\r\ncollector = FilteredElementCollector(doc,doc.ActiveView.Id) # collecion in revit api\r\nfilter= ElementCategoryFilter(BuiltInCategory.OST_Doors) # filter in revit api\r\ndoors= collector.WherePasses(filter).ToElements() # where in revit api\r\n\r\n#Filter elemnent Instance of Family\r\ninstanceFilter= FamilyInstanceFilter(doc,family.Id)\r\ndoorInstance= collector.OfCategory(BuiltInCategory.OST_Doors).WherePasses(instanceFilter).ToElements()\r\n\r\n#get parameter.\r\nparameters= doorInstance.FirstElement().GetOrderedParameters()\r\nnameParameter=[]\r\nfor par in paramters:\r\n\tnamParameter.append(par.Definition.Name)\r\n\t\r\n# assign parameter in python\r\ndoorMat= doorInstance.FirstElement().get_Parameter(BuiltInParameter.DOOR_FRAME_MATERIAL)\r\nparaStorageType= doorMat.StorageType()\r\n#Open Transaction before set value parameter\r\ndoorMat.Set('Wood')\r\nlevel = floor.LookupParameter('Level').AsElementId() # get Parameter follow name para\r\n\t\r\nxyzPy =XYZ(1,2,0) #Create a Coordinate.\r\nxyzRe= xyzPy.ToPoint(xyzPy) #Auto multi with 304.8\r\n\r\n#Libraby python script\r\ndocS = sys.builtin_module_names\r\n\r\n#Namspace Revit Elements have module\r\nrevitElement= Revit.Elements\r\n\r\n#How to use funtion\r\ns= sin.__doc__\r\n\r\ndef CovertColor(element): #Convert from color element to color of revit\r\n return Autodesk.Revit.DB.Color(element.Red,element.Green,element.Blue)\r\n\r\n#Assign your output to the OUT variable.\r\nOUT = doors","sub_path":"Lesson6.py","file_name":"Lesson6.py","file_ext":"py","file_size_in_byte":2974,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"23090463","text":"from functools import wraps\nfrom flask import abort,request\nfrom firebase_admin import auth\n\ndef authorize_user(f):\n @wraps(f)\n def decorated_function(*args, **kws):\n if not 'Authorization' in request.headers:\n print(\"No header Authorization\")\n abort(401)\n user = None\n data = request.headers['Authorization']\n authToken = str(data)\n try:\n user = auth.verify_id_token(authToken)\n print(user)\n except Exception as identifier:\n print(identifier)\n abort(401)\n\n return f(*args, **kws) \n return decorated_function","sub_path":"authorize/authorize.py","file_name":"authorize.py","file_ext":"py","file_size_in_byte":695,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"502629397","text":"'''Train CIFAR10 with PyTorch.'''\r\nimport torch\r\nimport torch.nn as nn\r\nimport torch.optim as optim\r\nimport torch.nn.functional as F\r\nimport torch.backends.cudnn as cudnn\r\n\r\nimport torchvision\r\nimport torchvision.transforms as transforms\r\n\r\nimport os\r\nimport argparse\r\n\r\nfrom models import *\r\n\r\n\r\nif __name__ == \"__main__\":\r\n parser = argparse.ArgumentParser(description='cifar10')\r\n parser.add_argument('--GPU',help=\"whether use GPU\")\r\n\r\n args=parser.parse_args()\r\n\r\n\r\n if args.GPU == 'True' and torch.cuda.is_available():\r\n use_GPU = True\r\n else:\r\n use_GPU = False\r\n\r\n print(\"USE GPU:\", use_GPU)\r\n\r\n\r\n # Data\r\n print('==> Preparing data..')\r\n transform_train = transforms.Compose([\r\n transforms.RandomCrop(32, padding=4),\r\n transforms.RandomHorizontalFlip(),\r\n transforms.ToTensor(),\r\n transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010)),\r\n ])\r\n\r\n transform_test = transforms.Compose([\r\n transforms.ToTensor(),\r\n transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010)),\r\n ])\r\n\r\n trainset = torchvision.datasets.CIFAR10(root='./data', train=True, download=True, transform=transform_train)\r\n trainloader = torch.utils.data.DataLoader(trainset, batch_size=128, shuffle=True, num_workers=2)\r\n\r\n testset = torchvision.datasets.CIFAR10(root='./data', train=False, download=True, transform=transform_test)\r\n testloader = torch.utils.data.DataLoader(testset, batch_size=100, shuffle=False, num_workers=2)\r\n\r\n classes = ('plane', 'car', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck')\r\n\r\n # Model\r\n print('==> Building model..')\r\n # net = VGG('VGG19')\r\n net = ResNet18()\r\n # net = PreActResNet18()\r\n # net = GoogLeNet()\r\n # net = DenseNet121()\r\n # net = ResNeXt29_2x64d()\r\n # net = MobileNet()\r\n # net = MobileNetV2()\r\n # net = DPN92()\r\n # net = ShuffleNetG2()\r\n # net = SENet18()\r\n # net = ShuffleNetV2(1)\r\n # net = EfficientNetB0()\r\n\r\n\r\n if use_GPU:\r\n net.cuda()\r\n\r\n criterion = nn.CrossEntropyLoss()\r\n optimizer = optim.SGD(net.parameters(), lr=0.1, momentum=0.9, weight_decay=5e-4)\r\n\r\n\r\n\r\n\r\n for epoch in range(200):\r\n for step, (b_x, b_y) in enumerate(trainloader):\r\n if use_GPU:\r\n b_x = b_x.cuda()\r\n b_y = b_y.cuda()\r\n\r\n output = net(b_x)\r\n loss = criterion(output, b_y)\r\n optimizer.zero_grad()\r\n loss.backward()\r\n optimizer.step()\r\n \r\n if epoch % 10 == 0:\r\n correct = 0\r\n total = 0\r\n for step, (b_x, b_y) in enumerate(testloader):\r\n if use_GPU:\r\n b_x = b_x.cuda()\r\n b_y = b_y.cuda()\r\n testoutput = net(b_x)\r\n\r\n if use_GPU:\r\n pre_y = torch.max(testoutput, 1)[1].cuda().data.squeeze()\r\n else:\r\n pre_y = torch.max(testoutput, 1)[1].data.squeeze()\r\n\r\n right = torch.sum(pre_y==b_y).type(torch.FloatTensor)\r\n total += b_y.size()[0]\r\n correct += right\r\n \r\n print(\"Epoch {}, Accuracy:{}\".format(epoch, correct/total))\r\n\r\n print(\"Finish Training\")","sub_path":"CIFAR10/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3320,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"337388485","text":"\n\n#calss header\nclass _SPECIALIST():\n\tdef __init__(self,): \n\t\tself.name = \"SPECIALIST\"\n\t\tself.definitions = [u'someone who has a lot of experience, knowledge, or skill in a particular subject: ', u'a doctor who has special training in and knowledge of a particular area of medicine: ']\n\n\t\tself.parents = []\n\t\tself.childen = []\n\t\tself.properties = []\n\t\tself.jsondata = {}\n\n\n\t\tself.specie = 'nouns'\n\n\n\tdef run(self, obj1 = [], obj2 = []):\n\t\treturn self.jsondata\n","sub_path":"xai/brain/wordbase/nouns/_specialist.py","file_name":"_specialist.py","file_ext":"py","file_size_in_byte":460,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"76924840","text":"import torch.nn as nn\nimport torch.nn.functional as F\n\nfrom utils import getter\n\n\nclass TripletLoss(nn.Module):\n \"\"\"\n Triplet loss\n Takes embeddings of an anchor sample, a positive sample and a negative sample\n \"\"\"\n\n def __init__(self, margin, size_average=True):\n super(TripletLoss, self).__init__()\n self.margin = margin\n self.size_average = size_average\n\n def forward(self, output, _):\n anchor, positive, negative = output\n distance_positive = (anchor - positive).pow(2).sum(1) # .pow(.5)\n distance_negative = (anchor - negative).pow(2).sum(1) # .pow(.5)\n losses = F.relu(distance_positive - distance_negative + self.margin)\n return losses.mean() if self.size_average else losses.sum()\n\n\nclass OnlineTripletLoss(nn.Module):\n \"\"\"\n Online Triplets loss\n Takes a batch of embeddings and corresponding labels.\n Triplets are generated using triplet_selector object that take embeddings and targets and return indices of\n triplets\n \"\"\"\n\n def __init__(self, margin, selector):\n super(OnlineTripletLoss, self).__init__()\n self.margin = margin\n self.triplet_selector = getter.get_instance(selector)\n\n def forward(self, embeddings, target):\n\n triplets = self.triplet_selector.get_triplets(embeddings, target)\n\n if embeddings.is_cuda:\n triplets = triplets.cuda()\n\n ap_distances = (embeddings[triplets[:, 0]]\n - embeddings[triplets[:, 1]]).pow(2).sum(1) # .pow(.5)\n an_distances = (embeddings[triplets[:, 0]]\n - embeddings[triplets[:, 2]]).pow(2).sum(1) # .pow(.5)\n losses = F.relu(ap_distances - an_distances + self.margin)\n\n return losses.mean() # , len(triplets)\n\n\nclass OnlineTripletWithClsLoss(nn.Module):\n \"\"\"\n Online Triplets loss\n Takes a batch of embeddings and corresponding labels.\n Triplets are generated using triplet_selector object that take embeddings and targets and return indices of\n triplets\n \"\"\"\n\n def __init__(self, margin, selector):\n super().__init__()\n self.margin = margin\n self.triplet_selector = getter.get_instance(selector)\n self.cls = nn.Linear(1280, 333)\n\n def forward(self, embeddings, target):\n\n triplets = self.triplet_selector.get_triplets(embeddings, target)\n\n if embeddings.is_cuda:\n triplets = triplets.cuda()\n\n ap_distances = (embeddings[triplets[:, 0]]\n - embeddings[triplets[:, 1]]).pow(2).sum(1) # .pow(.5)\n an_distances = (embeddings[triplets[:, 0]]\n - embeddings[triplets[:, 2]]).pow(2).sum(1) # .pow(.5)\n triplet_loss = F.relu(ap_distances - an_distances + self.margin)\n\n classification = self.cls(embeddings)\n cls_loss = F.cross_entropy(classification, target)\n\n losses = triplet_loss + cls_loss\n return losses.mean() # , len(triplets)\n","sub_path":"losses/reidentification/triplet_loss.py","file_name":"triplet_loss.py","file_ext":"py","file_size_in_byte":2972,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"73982317","text":"import random\n\nclass Codec:\n size = 7\n base_url = \"http://tinyurl.com/\"\n key_map = dict()\n char_map = {\n 1: \"1\",\n 2: \"2\",\n 3: \"3\",\n 4: \"4\",\n 5: \"5\",\n 6: \"6\",\n 7: \"7\",\n 8: \"8\",\n 9: \"9\",\n 10: \"0\",\n 11: \"a\",\n 12: \"b\",\n 13: \"c\",\n 14: \"d\",\n 15: \"e\",\n 16: \"f\",\n 17: \"g\",\n 18: \"h\",\n 19: \"i\",\n 20: \"j\",\n 21: \"k\",\n 22: \"l\",\n 23: \"m\",\n 24: \"n\",\n 25: \"o\",\n 26: \"p\",\n 27: \"q\",\n 28: \"r\",\n 29: \"s\",\n 30: \"t\",\n 31: \"u\",\n 32: \"v\",\n 33: \"w\",\n 34: \"x\",\n 35: \"y\",\n 36: \"z\"\n }\n \n def generate_random_key(self):\n key = []\n for i in range(random.randint(3, Codec.size)):\n key.append(Codec.char_map[random.randint(1, len(Codec.char_map)+1)])\n return \"\".join(key)\n\n def encode(self, longUrl):\n \"\"\"Encodes a URL to a shortened URL.\n \n :type longUrl: str\n :rtype: str\n \"\"\"\n random_key = \"\"\n try:\n while True:\n random_key = self.generate_random_key()\n x=Codec.key_map[random_key]\n except KeyError:\n Codec.key_map[random_key] = longUrl\n return Codec.base_url + random_key\n \n\n def decode(self, shortUrl):\n \"\"\"Decodes a shortened URL to its original URL.\n \n :type shortUrl: str\n :rtype: str\n \"\"\"\n key = shortUrl.split(Codec.base_url)[-1]\n return Codec.key_map[key]\n \n \n\n# Your Codec object will be instantiated and called as such:\n# codec = Codec()\n# codec.decode(codec.encode(url))\n","sub_path":"535. Encode and Decode TinyURL/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":1757,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"276712818","text":"import time\nimport matplotlib.pyplot as plt\nimport pylab\nfrom datetime import datetime\nfrom datetime import timedelta\n\nclass Plotter:\n def __init__(self, stats):\n self._stats = stats\n self._lastUpdate = self.getCurrentTime()\n pylab.ion()\n figure = pylab.figure()\n self.x = pylab.arange(0,100)\n \n self.hitRatioY = [0 for z in xrange(100)]\n ax = plt.subplot(3,1,1)\n ax.set_title(\"Hit ratio (cache)\")\n self.hitRatioPlot, = ax.plot(self.x, self.hitRatioY, lw=3)\n self.hitRatioPlot.axes.set_ylim(0,1)\n \n self.timerY = [0 for z in xrange(100)]\n ax = plt.subplot(3,1,2)\n ax.set_title(\"Reponse time\")\n self.timerPlot, = ax.plot(self.x, self.timerY, lw=3)\n self.timerPlot.axes.set_ylim(0,1000)\n \n self.timerSuccessY = [0 for z in xrange(100)]\n ax = plt.subplot(3,1,3)\n ax.set_title(\"Reponse time (success only)\")\n self.timerSuccessPlot, = ax.plot(self.x, self.timerSuccessY, lw=3)\n self.timerSuccessPlot.axes.set_ylim(0,1000)\n \n figure.subplots_adjust(hspace=0.5)\n\n def getCurrentTime(self):\n return time.time() * 1000\n\n def update(self):\n if self.getCurrentTime() - self._lastUpdate > 50:\n self._lastUpdate = self.getCurrentTime()\n\n self.hitRatioY.append(self._stats.getHitRatio())\n self.hitRatioY.pop(0)\n self.hitRatioPlot.set_ydata(self.hitRatioY)\n \n self.timerY.append(self._stats.getAverageRequestTime())\n self.timerY.pop(0)\n self.timerPlot.set_ydata(self.timerY)\n \n self.timerSuccessY.append(self._stats.getAverageSuccessTime())\n self.timerSuccessY.pop(0)\n self.timerSuccessPlot.set_ydata(self.timerSuccessY)\n\n maxY = max(self.timerY+self.timerSuccessY+[10]) * 1.1\n self.timerPlot.axes.set_ylim(0,maxY)\n self.timerSuccessPlot.axes.set_ylim(0,maxY)\n\n pylab.draw()\n\n def close(self):\n pylab.close()\n\nclass Statistics:\n def __init__(self):\n self._cacheTries = []\n self._timerAll = []\n self._timerSuccess = []\n\n def getHitRatio(self):\n if not self._cacheTries:\n return 0\n return sum(self._cacheTries) / float(len(self._cacheTries))\n\n def getAverageRequestTime(self):\n if not self._timerAll:\n return 0\n return sum(self._timerAll) / len(self._timerAll)\n\n def getAverageSuccessTime(self):\n if not self._timerSuccess:\n return 0\n return sum(self._timerSuccess) / len(self._timerSuccess)\n\n def addRequestTime(self, theTime, success=True):\n self._timerAll.append(theTime*1000)\n if len(self._timerAll) > 5:\n self._timerAll.pop(0)\n if success:\n self._timerSuccess.append(theTime*1000)\n if len(self._timerSuccess) > 5:\n self._timerSuccess.pop(0)\n\n def addCacheTry(self, hit):\n self._cacheTries.append(hit)\n if len(self._cacheTries) > 10:\n self._cacheTries.pop(0)\n\nif __name__ == '__main__': \n stats = Statistics()\n plotter = Plotter(stats)\n\n import random\n for x in xrange(100):\n stats.addCacheTry(random.choice([True, False]))\n stats.addRequestTime(random.randrange(0,1000), random.choice([True, False]))\n plotter.update()\n time.sleep(0.1)\n","sub_path":"src/statistics.py","file_name":"statistics.py","file_ext":"py","file_size_in_byte":3455,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"303805755","text":"\n#First, installing pygame through Terminal\nimport pygame\n\n#pygame is 2D graphics library to make games\nWIDTH, HEIGHT = 900, 500\nWIN = pygame.display.set_mode((WIDTH, HEIGHT))\n\n#Step2\n#How to draw on to the screen and change the name of that window\npygame.display.set_caption(\"First Game!\")\n\n#Step1\ndef main():\n #this will have loop, which will redrawn the window, checking for collisions, updating the scores\n #we dont want the game to instantly open and close, hence we use WHILE loop\n #think as in infinite loop and terminates whenever the game ends\n\n run = True #when run becomes false, the loop will end\n while run:\n for event in pygame.event.get(): #different events occuring in pygame\n\n #first event is, if the user quit the window\n if event.type == pygame.QUIT:\n run =False #this will end the WHILE loop\n \n #Filling the screen with color\n WIN.fill((255,255,255))#this is tuple for RGB, 3 values, WHITE color\n #after above, we need to update always for display\n pygame.display.update()\n\n #i dont want all of my drawings inside this main function\n #i usually want to have main game loop handling all of the collisions, all the logic in the game\n #and then having some of the functions outside of that i can easily call\n\n pygame.quit() #this will quit pygame for us\n\n\nif __name__ == \"__main__\": #name: is the name of the file\n main()\n\n","sub_path":"Project1.py","file_name":"Project1.py","file_ext":"py","file_size_in_byte":1466,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"605668725","text":"import math\n\nfunctions = {\n 'log': math.log,\n 'exp': math.exp,\n 'sin': math.sin,\n 'cos': math.cos,\n 'tan': math.tan,\n 'atan': math.atan,\n 'tanh': math.tanh,\n 'atanh': math.atanh\n}\n\nconstants = {\n 'pi': math.pi,\n}\n","sub_path":"packages/Dolang/PXnkq/dolang/language.py","file_name":"language.py","file_ext":"py","file_size_in_byte":240,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"514460287","text":"# -*- coding: utf-8 -*-\n\n# Author: Qi Wang, Ievgen Redko, Sylvain Takerkart\n\nimport numpy as np\nfrom scipy.stats import multivariate_normal\n\ndef get_title(lvl, mean, sign_digits):\n if lvl == int(lvl):\n lvl = str(int(lvl))+'.'+'0'*(sign_digits-2)\n else :\n lvl = str(lvl)\n while len(lvl) < sign_digits :\n lvl = lvl+'0'\n title = './artificial_data_noiselvl_'+lvl+'.npy'\n return title\n\ndef generate_data(seed=42, nb_samples = 200,\n x_size=50, y_size = 50,\n noise_level = 0, noise_mean = 0):\n \n # activated zone\n #original code, but gives us new random samples each time, no way to add a seed so saving a random sample file to use \n #for the future to keep noise and non noise consistent\n\n rng = np.random.RandomState(seed)\n\n amplitudes = rng.normal(5, 1, nb_samples)\n\n signalN = 11\n mean = 0\n square_sig = 0.1\n X = np.linspace(-0.5, 0.5, signalN)\n Y = np.linspace(-0.5, 0.5, signalN)\n X, Y = np.meshgrid(X, Y)\n\n pos = np.empty(X.shape + (2, ))\n pos[:, :, 0] = X\n pos[:, :, 1] = Y\n signal_matrix = np.empty((nb_samples, signalN, signalN))\n for i in range(nb_samples):\n mu = np.array([mean, mean])\n Sigma = np.array([[square_sig, 0], [0, square_sig]])\n F = multivariate_normal(mu, Sigma, seed=seed)\n Z = F.pdf(pos)\n Z = Z / Z.max() * amplitudes[i]\n signal_matrix[i] = Z\n\n\n # coordinates of the center of the activated zone\n coors = []\n for i in range(nb_samples):\n t = 2 * np.pi * rng.uniform(0, 1)\n r = np.sqrt(rng.uniform(0, 225))\n coor = [r * np.cos(t), r * np.sin(t)]\n coors.append(coor)\n coors = np.vstack(coors)\n coors += np.array([25, 25])\n coors = coors.astype(int)\n\n # images with signal and (maybe) noise\n gap = int(np.floor(signalN / 2))\n signals = signal_matrix\n noisefrees = np.zeros([nb_samples, x_size, y_size])\n patterns = np.zeros([nb_samples, x_size, y_size])\n for sample_id in range(nb_samples):\n loc = coors[sample_id]\n noisefrees[sample_id][loc[0] - gap:loc[0] + gap + 1, loc[1] - gap:loc[1] + gap + 1] \\\n = signals[sample_id]\n patterns[sample_id] = noisefrees[sample_id] + \\\n rng.normal(noise_mean, noise_level,\n (x_size, y_size))\n\n title = get_title(noise_level, noise_mean, 5)\n np.save(\"./data/\"+title, patterns)\n return patterns\n\n\nif __name__==\"__main__\":\n for i in [0,0.05,0.1,0.2,0.5,1] :\n generate_data(noise_level = i)","sub_path":"richard_s_drafts/generate_data/generate_data_noise_grading.py","file_name":"generate_data_noise_grading.py","file_ext":"py","file_size_in_byte":2602,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"612850249","text":"\"\"\"Benchmark scripts.\"\"\"\r\nimport time\r\nfrom benchmarks.logger import JsonLogger\r\n\r\n\r\ndef circuit_benchmark(nqubits, backend, circuit_name, circuit_options=None,\r\n nreps=1, nshots=None, transfer=False,\r\n precision=\"double\", memory=None, threading=None,\r\n filename=None, platform=None):\r\n \"\"\"Runs benchmark for different circuit types.\r\n\r\n See ``benchmarks/main.py`` for documentation of each argument.\r\n \"\"\"\r\n if backend == \"qibojit\" and threading is not None:\r\n from benchmarks.utils import select_numba_threading\r\n threading = select_numba_threading(threading)\r\n\r\n if backend in {\"qibotf\", \"tensorflow\"} and memory is not None:\r\n from benchmarks.utils import limit_gpu_memory\r\n memory = limit_gpu_memory(memory)\r\n\r\n logs = JsonLogger(filename)\r\n logs.log(nqubits=nqubits, nreps=nreps, nshots=nshots, transfer=transfer,\r\n numba_threading=threading, gpu_memory=memory)\r\n\r\n start_time = time.time()\r\n import qibo\r\n logs.log(import_time=time.time() - start_time)\r\n\r\n qibo.set_backend(backend=backend, platform=platform)\r\n qibo.set_precision(precision)\r\n logs.log(backend=qibo.get_backend(),\r\n platform=qibo.K.get_platform(),\r\n precision=qibo.get_precision(),\r\n device=qibo.get_device(),\r\n version=qibo.__version__)\r\n\r\n from benchmarks import circuits\r\n gates = circuits.get(circuit_name, nqubits, circuit_options, qibo=True)\r\n logs.log(circuit=circuit_name, circuit_options=str(gates))\r\n start_time = time.time()\r\n circuit = qibo.models.Circuit(nqubits)\r\n circuit.add(gates)\r\n if nshots is not None:\r\n # add measurement gates\r\n circuit.add(qibo.gates.M(*range(nqubits)))\r\n logs.log(creation_time=time.time() - start_time)\r\n\r\n start_time = time.time()\r\n result = circuit(nshots=nshots)\r\n logs.log(dry_run_time=time.time() - start_time)\r\n start_time = time.time()\r\n if transfer:\r\n result = result.numpy()\r\n logs.log(dry_run_transfer_time=time.time() - start_time)\r\n dtype = str(result.dtype)\r\n del(result)\r\n\r\n simulation_times, transfer_times = [], []\r\n for _ in range(nreps):\r\n start_time = time.time()\r\n result = circuit(nshots=nshots)\r\n simulation_times.append(time.time() - start_time)\r\n start_time = time.time()\r\n if transfer:\r\n result = result.numpy()\r\n transfer_times.append(time.time() - start_time)\r\n del(result)\r\n\r\n logs.log(dtype=dtype, simulation_times=simulation_times,\r\n transfer_times=transfer_times)\r\n logs.average(\"simulation_times\")\r\n logs.average(\"transfer_times\")\r\n\r\n if nshots is not None:\r\n result = circuit(nshots=nshots)\r\n start_time = time.time()\r\n freqs = result.frequencies()\r\n logs.log(measurement_time=time.time() - start_time)\r\n del result\r\n else:\r\n logs.log(measurement_time=0)\r\n logs.dump()\r\n\r\n return logs\r\n\r\n\r\ndef library_benchmark(nqubits, library, circuit_name, circuit_options=None,\r\n library_options=None, precision=None, nreps=1,\r\n filename=None):\r\n \"\"\"Runs benchmark for different quantum simulation libraries.\r\n\r\n See ``benchmarks/compare.py`` for documentation of each argument.\r\n \"\"\"\r\n logs = JsonLogger(filename)\r\n logs.log(nqubits=nqubits, nreps=nreps)\r\n\r\n start_time = time.time()\r\n from benchmarks import libraries\r\n backend = libraries.get(library, library_options)\r\n logs.log(import_time=time.time() - start_time)\r\n logs.log(library_options=library_options)\r\n if precision is not None:\r\n backend.set_precision(precision)\r\n\r\n logs.log(library=backend.name,\r\n precision=backend.get_precision(),\r\n device=backend.get_device(),\r\n version=backend.__version__)\r\n\r\n from benchmarks import circuits\r\n gates = circuits.get(circuit_name, nqubits, circuit_options)\r\n logs.log(circuit=circuit_name, circuit_options=str(gates))\r\n start_time = time.time()\r\n circuit = backend.from_qasm(gates.to_qasm())\r\n logs.log(creation_time=time.time() - start_time)\r\n\r\n start_time = time.time()\r\n result = backend(circuit)\r\n logs.log(dry_run_time=time.time() - start_time)\r\n dtype = str(result.dtype)\r\n del(result)\r\n\r\n simulation_times = []\r\n for _ in range(nreps):\r\n start_time = time.time()\r\n result = backend(circuit)\r\n simulation_times.append(time.time() - start_time)\r\n del(result)\r\n\r\n logs.log(dtype=dtype, simulation_times=simulation_times)\r\n logs.average(\"simulation_times\")\r\n logs.dump()\r\n return logs\r\n\r\n\r\ndef evolution_benchmark(nqubits, dt, solver, backend, platform=None,\r\n nreps=1, precision=\"double\", dense=False,\r\n filename=None):\r\n \"\"\"Performs adiabatic evolution with critical TFIM as the hard Hamiltonian.\"\"\"\r\n logs = JsonLogger(filename)\r\n logs.log(nqubits=nqubits, nreps=nreps, dt=dt, solver=solver, dense=dense)\r\n\r\n start_time = time.time()\r\n import qibo\r\n logs.log(import_time=time.time() - start_time)\r\n\r\n qibo.set_backend(backend=backend, platform=platform)\r\n qibo.set_precision(precision)\r\n logs.log(backend=qibo.get_backend(),\r\n platform=qibo.K.get_platform(),\r\n precision=qibo.get_precision(),\r\n device=qibo.get_device(),\r\n threads=qibo.get_threads(),\r\n version=qibo.__version__)\r\n\r\n from qibo import hamiltonians, models\r\n start_time = time.time()\r\n h0 = hamiltonians.X(nqubits, dense=dense)\r\n h1 = hamiltonians.TFIM(nqubits, h=1.0, dense=dense)\r\n logs.log(hamiltonian_creation_time=time.time() - start_time)\r\n\r\n start_time = time.time()\r\n evolution = models.AdiabaticEvolution(h0, h1, lambda t: t, dt=dt, solver=solver)\r\n logs.log(evolution_creation_time=time.time() - start_time)\r\n\r\n start_time = time.time()\r\n result = evolution(final_time=1.0)\r\n logs.log(dry_run_time=time.time() - start_time)\r\n dtype = str(result.dtype)\r\n del(result)\r\n\r\n simulation_times = []\r\n for _ in range(nreps):\r\n start_time = time.time()\r\n result = evolution(final_time=1.0)\r\n simulation_times.append(time.time() - start_time)\r\n logs.log(dtype=dtype, simulation_times=simulation_times)\r\n logs.average(\"simulation_times\")\r\n logs.dump()\r\n return logs\r\n","sub_path":"benchmarks/scripts.py","file_name":"scripts.py","file_ext":"py","file_size_in_byte":6492,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"411769371","text":"import math\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport scipy.sparse\nimport scipy.sparse.linalg\nimport sys\nimport warnings\n\nnp.set_printoptions(precision=3,linewidth=180)\n\nclass Truss:\n \"\"\"This Truss class solves for the beam forces of a specified truss. \n The arguments are a jointsfile and a beamsfile. An optional argument\n is the outputfile name for plotting the truss. This class also identified\n under-determined and over-determined systems\"\"\"\n \n def __init__(self, jointsfile,beamsfile,plotoutputfile=None):\n \"\"\"Initialization method that calls load function\"\"\"\n \n self.plotoutputfile=str(plotoutputfile)\n self.load_data(jointsfile,beamsfile)\n\n def load_data(self,jointsfile,beamsfile):\n \"\"\"Loads in the various input files into numpy tables\n and creates self variables\"\"\"\n\n self.jointsxy=np.loadtxt(jointsfile,dtype=np.float64,usecols=(0,1,2))\n self.jointsfxy=np.loadtxt(jointsfile,dtype=np.float64,usecols=(3,4))\n self.jointsd=np.loadtxt(jointsfile,dtype=np.int64,usecols=(5,))\n self.beams=np.loadtxt(beamsfile,dtype=np.int64,usecols=(1,2))\n \n # Creating empty lists for self data \n self.row=[]\n self.col=[]\n self.data=[]\n self.b=[]\n self.beamForces=[]\n numberJoints=self.jointsxy.shape[0]\n shapeSpa=(numberJoints*2,numberJoints*2)\n self.rowarray=np.empty(shape=shapeSpa)\n self.colarray=np.empty(shape=shapeSpa)\n self.dataarray=np.empty(shape=shapeSpa)\n self.barray=np.empty(shape=(numberJoints*2,1))\n\n def loadMatrices(self):\n \"\"\"Creating sparse matrixes and solution array in order to\n solve. Each sparse matrix is filled with the coefficients\n (cos,sin or 1) in order to correspond with each unknown\n force\"\"\"\n\n # Creating column indexes for csr sparse format\n for i,row in enumerate(self.beams):\n self.col.extend(i for ind in range(4))\n\n # Creating row indices for csr sparse format\n j1=row[0]\n j2=row[1]\n j1starti=(j1-1)*2\n j2starti=(j2-1)*2\n self.row.extend([j1starti,j1starti+1,j2starti,j2starti+1])\n\n # Filling in data list with sin and cos values \n cosVal=self.cosFactor(j1,j2)\n sinVal=self.sinFactor(j1,j2)\n self.data.extend([cosVal,sinVal,-cosVal,-sinVal])\n \n # Filling in the RX,RY in sparse matrix\n for i,val in enumerate(self.jointsd):\n if val != 0:\n colnum=max(self.col)+1\n self.col.extend([colnum,colnum+1])\n rownum=2*i\n self.row.extend([rownum,rownum+1])\n self.data.extend(1 for ind in range(2))\n\n # Converting lists into numpy array\n self.rowarray=np.array(self.row,dtype=np.int64)\n self.colarray=np.array(self.col,dtype=np.int64)\n self.dataarray=np.array(self.data,dtype=np.float64)\n\n # Creating sparse matrix \n self.sparseM=scipy.sparse.csr_matrix((self.dataarray,(self.rowarray,self.colarray)))\n\n # Creating B Matrix\n for i,val in enumerate(self.jointsfxy):\n self.b.extend([val[0],val[1]])\n \n self.barray=np.array(self.b,dtype=np.float64)\n\n # Raising Runtime Error by checking the amount of equations vs unknowns\n unknowncount=2*np.sum(self.jointsd)+self.beams.shape[0]\n check=2*self.jointsxy.shape[0]\n\n if check < unknowncount:\n raise RuntimeError ('Truss geometry not suitable for static equilibrium analysis')\n\n def getSparseMatrix(self):\n \"\"\"Allows user to view sparse matrix format\"\"\"\n\n sparseMCopy=self.sparseM.copy().todense()\n return sparseMCopy\n\n def getRHS(self):\n \"\"\"Allows user to view rhs filled with external forces\"\"\"\n\n return self.barray.copy()\n\n def xSolver(self):\n \"\"\"Obtains solution to 2D truss system\"\"\"\n \n # Catches warnings into error for unstable truss \n warnings.filterwarnings('error')\n warnings.filterwarnings('ignore',category=DeprecationWarning)\n \n # Solves the solution to the 2D truss sytem\n try:\n self.x=scipy.sparse.linalg.spsolve(self.sparseM,self.barray)\n except Warning:\n raise RuntimeError('Cannot solve the linear system, unstable truss?')\n \n def beamForce(self):\n \"\"\"Creating list of beam forces\"\"\"\n \n for i,force in enumerate(self.x):\n if i<len(self.beams):\n self.beamForces.append(force)\n\n def cosFactor(self,joint1,joint2):\n \"\"\"Generating cosine coefficient factors\"\"\"\n\n x1=self.jointsxy[joint1-1,1]\n y1=self.jointsxy[joint1-1,2]\n x2=self.jointsxy[joint2-1,1]\n y2=self.jointsxy[joint2-1,2]\n dx=x2-x1\n hypdis=math.hypot(x2-x1,y2-y1)\n cosf=dx/hypdis\n return cosf\n\n def sinFactor(self,joint1,joint2):\n \"\"\"Generating sine coefficient factors\"\"\"\n\n x1=self.jointsxy[joint1-1,1]\n y1=self.jointsxy[joint1-1,2]\n x2=self.jointsxy[joint2-1,1]\n y2=self.jointsxy[joint2-1,2]\n dy=y2-y1\n hypdis=math.hypot(x2-x1,y2-y1)\n sinf=dy/hypdis\n return sinf\n \n def PlotGeometry(self,plotoutputfile):\n \"\"\"Plotting geometry of truss\"\"\"\n \n # Checking for optional third argument\n if self.plotoutputfile==\"None\":\n pass\n \n # Plotting/saving figure in specified file\n else:\n plt.figure(1)\n for i,val in enumerate(self.beams):\n ja=val[0]\n jb=val[1]\n x1=self.jointsxy[ja-1,1]\n y1=self.jointsxy[ja-1,2]\n x2=self.jointsxy[jb-1,1]\n y2=self.jointsxy[jb-1,2]\n plt.plot((x1,x2),(y1,y2))\n matplotlib.pyplot.axes().set_aspect('equal','datalim')\n plt.show()\n plt.savefig(self.plotoutputfile)\n\n def __repr__(self):\n \"\"\"Class representation method to print out the\n beam number and force\"\"\"\n\n self.loadMatrices()\n self.xSolver()\n self.beamForce()\n self.PlotGeometry(self.plotoutputfile)\n string='Beam Force\\n'\n string+='________________\\n'\n for i, val in enumerate(self.beamForces):\n string+=' %d %9.3f\\n' % (i+1,val)\n return string\n\n","sub_path":"Software Development/truss.py","file_name":"truss.py","file_ext":"py","file_size_in_byte":6545,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"153802121","text":"from django.urls import path, include\nfrom . import api\n\napipatterns = [\n path(r'', api.index, name='ara-bte-api'),\n path(r'runbtequery', api.runbte, name='ara-bte-runquery')\n]\n\nurlpatterns = [\n path(r'api/', include(apipatterns)),\n]\n","sub_path":"tr_sys/tr_ara_bte/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":243,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"337018653","text":"#\n# Copyright (C) 2018 Michael Schmitz\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n\nimport socket, binascii, time\nimport Adafruit_MPR121.MPR121 as MPR121\n\nip = \"192.168.178.52\"\nport = 5555\n#empty fields are not used atm\nidText = {0: '01', 1: '02', 2: '04', 3: '', 4: '',\n 5: '', 6: '', 7: '', 8: '', 9: '08',\n 10: '0C', 11: '03'}\nidHex = {0: 0x01, 1: 0x02, 2: 0x04, 3: 0x00, 4: 0x00,\n 5: 0x00, 6: 0x00, 7: 0x00, 8: 0x00, 9: 0x08,\n 10: 0x0C, 11: 0x03}\nsock = socket.socket( socket.AF_INET, socket.SOCK_DGRAM )\ncap = MPR121.MPR121()\nif not cap.begin():\n print('Error initializing MPR121.')\n sys.exit(1)\nlast_touched = cap.touched()\nwhile True:\n current_touched = cap.touched() \n msgText = 'CCCC1F' \n #0xCC + 0xCC + 0x1F\n msgSum = 0x1B7\n for i in range(12):\n pin_bit = 1 << i\n if current_touched & pin_bit and not last_touched & pin_bit:\n #used for debugging\n #print('{0} touched'.format(i))\n msgText += idText[i]\n msgSum += idHex[i]\n msgText += '{:02x}'.format(msgSum >> 8)\n msgText += '{:02x}'.format(msgSum & 0x00FF)\n sock.sendto( binascii.unhexlify(msgText), (ip, port) ) \n last_touched = current_touched\n time.sleep(0.1)\n","sub_path":"SwitchBoard.py","file_name":"SwitchBoard.py","file_ext":"py","file_size_in_byte":1809,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"629720307","text":"import pygame # Librería de pygame\nfrom random import randint\n\n# Dimensiones de la pantalla\nANCHO = 800\nALTO = 600\n# Colores\nBLANCO = (255, 255, 255) # R,G,B en el rango [0,255], 0 ausencia de color, 255 toda la intensidad\nVERDE_BANDERA = (27, 94, 32) # un poco de rojo, más de verde, un poco de azul\nROJO = (255, 0, 0) # solo rojo, nada de verde, nada de azul\nAZUL = (0, 0, 255) # nada de rojo, ni verde, solo azul\nNEGRO = (0,0,0)\nCAFE = (166,94,46)\n\nglobal listaMarcador\n\nlistaMarcador=[0]\n\n\n\n#estados\nMENU = 1\nGAME = 2\nOVER = 3\n\nQUIETO=1\nARRIBA=3\nABAJO=2\nIZQ=4\nDER=5\n\n\n#imagen botón\nimgBoton = pygame.image.load(\"button_jugar.png\")\nimgBoton2 = pygame.image.load(\"button_jugar.png\")\n\n\n# Estructura básica de un programa que usa pygame para dibujar\ndef dibujarPersonaje(ventana, spriteRondo):\n ventana.blit(spriteRondo.img, spriteRondo.rect)\n\n\ndef dibujarEnemigos(ventana, listaEnemigos):\n for enemigo in listaEnemigos:\n ventana.blit(enemigo.img, enemigo.rect)\n\n\ndef actualizarEnemigos(listaEnemigos):\n\n for enemigo in listaEnemigos:\n xe=enemigo.rect.left\n\n if xe == 200:\n enemigo.rect.left+=50\n if xe == 600:\n enemigo.rect.left-=50\n ye = enemigo.rect.bottom\n if ye == 200:\n enemigo.rect.bottom += 50\n if ye == 400:\n enemigo.rect.bottom -= 50\n\n enemigo.rect.left+=randint(-20,20)\n\n\n\n\ndef dibujarBasket(ventana, listaBasket):\n for balon in listaBasket:\n ventana.blit(balon.image,balon.rect)\n\n\ndef actualizarBasket(listaBasket,ciclo):\n\n for balon in listaBasket:\n balon.rect.left += 20\n if ciclo%4==0:\n listaBasket.remove(balon)\n\n\n\n\ndef verificarColision(listaBasket, listaEnemigos,efecto3):\n #recorrer listas al revés\n for k in range(len(listaBasket)-1,-1,-1):\n balon = listaBasket[k]\n borrarBalas = False\n for e in range(len(listaEnemigos)-1,-1,-1):\n enemigo = listaEnemigos[e]\n #bala vs enemigo\n xb = balon.rect.left\n yb= balon.rect.bottom\n xe,ye, anchoe, altoe = enemigo.rect\n if xb>=xe and xb<xe+anchoe and yb>=ye and yb<=ye+altoe:\n efecto3.play()\n listaEnemigos.remove(enemigo)\n borrarBalas = True\n break\n if borrarBalas:\n listaBasket.remove(balon)\n\ndef checarColisionJugador(listaEnemigos,spriteRondo,efecto2):\n\n rondo = spriteRondo\n borrarRondo = False\n for e in range(len(listaEnemigos)-1,-1,-1):\n enemigo = listaEnemigos[e]\n #jugador vs enemigo\n xb, yb, anchoe,altoe = rondo.rect\n\n xe,ye, anchoe, altoe = enemigo.rect\n if xb>=xe and xb<xe+anchoe and yb>=ye and yb<=ye+altoe:\n listaEnemigos.remove(enemigo)\n efecto2.play()\n borrarRondo = True\n break\n if borrarRondo== True:\n\n return True\n\n\ndef actualizarEnemigos2(listaEnemigos2):\n\n for enemigo in listaEnemigos2:\n xe = enemigo.rect.left\n\n if xe == 200:\n enemigo.rect.left += 50\n if xe == 600:\n enemigo.rect.left -= 50\n\n ye = enemigo.rect.bottom\n if ye == 200:\n enemigo.rect.bottom += 50\n if ye == 400:\n enemigo.rect.bottom -= 50\n\n enemigo.rect.bottom += randint(-20, 20)\n\n\n\ndef dibujar():\n\n # Inicializa el motor de pygame\n pygame.init()\n # Crea una ventana de ANCHO x ALTO\n ventana = pygame.display.set_mode((ANCHO, ALTO)) # Crea la ventana donde dibujará\n reloj = pygame.time.Clock() # Para limitar los fps\n termina = False # Bandera para saber si termina la ejecución, iniciamos suponiendo que no\n\n listaJugador=[]\n imgRondo= pygame.image.load(\"rondo.png\")\n\n spriteRondo= pygame.sprite.Sprite()\n spriteRondo.img = imgRondo\n spriteRondo.rect = imgRondo.get_rect()\n spriteRondo.rect.left = 0\n spriteRondo.rect.bottom = ALTO//2 + spriteRondo.rect.height//2\n listaJugador.append(spriteRondo)\n\n\n #enemigos\n listaEnemigos = []\n imgEnemigo = pygame.image.load(\"kobe.png\")\n for k in range (randint(3,7)):\n spriteEnemigo = pygame.sprite.Sprite()\n spriteEnemigo.img = imgEnemigo\n spriteEnemigo.rect = imgEnemigo.get_rect()\n spriteEnemigo.rect.left = randint(50,ANCHO-50)\n spriteEnemigo.rect.bottom = randint(50,ALTO-50)\n listaEnemigos.append(spriteEnemigo)\n listaEnemigos2 = []\n imgEnemigo = pygame.image.load(\"kobe.png\")\n for k in range(randint(3,7)):\n spriteEnemigo = pygame.sprite.Sprite()\n spriteEnemigo.img = imgEnemigo\n spriteEnemigo.rect = imgEnemigo.get_rect()\n spriteEnemigo.rect.left = randint(50, ANCHO-50)\n spriteEnemigo.rect.bottom = randint(50, ALTO-50)\n listaEnemigos2.append(spriteEnemigo)\n\n #bala\n imgBasket = pygame.image.load(\"basket.png\")\n listaBasket = []\n\n\n #estado del juego\n ESTADO = MENU\n\n imgFondo = pygame.image.load(\"fondo.jpg\")\n\n xFondo = 0\n\n\n\n\n #tiempo\n timer=0\n pygame.mixer.init()\n efecto =pygame.mixer.Sound(\"Farmacia 2000 6.wav\")\n efecto2 = pygame.mixer.Sound(\"Wrong Buzzer - Sound Effect.wav\")\n efecto3 = pygame.mixer.Sound(\"Farmacia 2000 7.wav\")\n\n pygame.mixer.music.load(\"Space - Jam.mp3\")\n pygame.mixer.music.play(-1)\n\n #texto\n fuente = pygame.font.SysFont(\"monospace\",54)\n ciclo=0\n\n\n\n\n while not termina: # Ciclo principal, MIENTRAS la variable termina sea False, el ciclo se repite automáticamente\n # Procesa los eventos que recibe\n ciclo += 1\n\n\n\n for evento in pygame.event.get():\n\n if evento.type == pygame.QUIT: # El usuario hizo click en el botón de salir\n\n termina = True # Queremos terminar el ciclo\n\n\n\n\n if listaEnemigos==[]:\n for k in range(randint(3, 7)):\n spriteEnemigo = pygame.sprite.Sprite()\n spriteEnemigo.img = imgEnemigo\n spriteEnemigo.rect = imgEnemigo.get_rect()\n spriteEnemigo.rect.left = randint(50, ANCHO-50)\n spriteEnemigo.rect.bottom = randint(50, ALTO-50)\n listaEnemigos.append(spriteEnemigo)\n if listaEnemigos2==[]:\n for k in range(randint(3, 7)):\n spriteEnemigo = pygame.sprite.Sprite()\n spriteEnemigo.img = imgEnemigo\n spriteEnemigo.rect = imgEnemigo.get_rect()\n spriteEnemigo.rect.left = randint(50, ANCHO-50)\n spriteEnemigo.rect.bottom = randint(50, ALTO-50)\n listaEnemigos2.append(spriteEnemigo)\n\n elif evento.type == pygame.KEYDOWN:\n if evento.key == pygame.K_UP:\n spriteRondo.rect.bottom -= 20\n\n\n elif evento.key == pygame.K_DOWN:\n spriteRondo.rect.bottom += 20\n\n elif evento.key == pygame.K_LEFT:\n spriteRondo.rect.left -= 20\n\n elif evento.key == pygame.K_RIGHT:\n spriteRondo.rect.left += 20\n\n\n elif evento.key == pygame.K_z:\n efecto.play()\n spriteBasket= pygame.sprite.Sprite()\n spriteBasket.image = imgBasket\n spriteBasket.rect = imgBasket.get_rect()\n spriteBasket.rect.left = spriteRondo.rect.left+10\n spriteBasket.rect.bottom = spriteRondo.rect.bottom-30\n listaBasket.append(spriteBasket)\n elif evento.type == pygame.MOUSEBUTTONDOWN:\n xm,ym = pygame.mouse.get_pos()\n xb = ANCHO//2-128\n yb= ALTO//2-50\n anchob= 256\n altob=100\n\n if xm>=xb and xm<=xb+anchob and ym>=yb and ym<=yb+altob and ESTADO==MENU:\n ESTADO = GAME\n timer=0\n spriteBasket = pygame.sprite.Sprite()\n spriteBasket.image = imgBasket\n spriteBasket.rect = imgBasket.get_rect()\n spriteBasket.rect.left = spriteRondo.rect.width\n spriteBasket.rect.bottom = spriteRondo.rect.bottom\n\n if xm>=xb and xm<=xb+anchob and ym>=yb and ym<=yb+altob and ESTADO==OVER:\n ESTADO = MENU\n timer=0\n spriteBasket = pygame.sprite.Sprite()\n spriteBasket.image = imgBasket\n spriteBasket.rect = imgBasket.get_rect()\n spriteBasket.rect.left = spriteRondo.rect.width\n spriteBasket.rect.bottom = spriteRondo.rect.bottom\n\n\n\n\n\n\n #Preguntar estado del juego\n if ESTADO == MENU:\n\n ventana.fill(NEGRO)\n ventana.blit(imgBoton,(ANCHO//2-128,ALTO//2-50))\n\n elif ESTADO == GAME:\n\n #Actualizar objetos\n actualizarEnemigos2(listaEnemigos2)\n actualizarEnemigos(listaEnemigos)\n actualizarBasket(listaBasket,ciclo)\n verificarColision(listaBasket,listaEnemigos,efecto3)\n verificarColision(listaBasket, listaEnemigos2,efecto3)\n\n\n # Borrar pantalla\n ventana.fill(CAFE)\n ventana.blit(imgFondo,(xFondo,0))\n\n\n dibujarPersonaje(ventana,spriteRondo)\n dibujarEnemigos(ventana,listaEnemigos)\n dibujarEnemigos(ventana, listaEnemigos2)\n dibujarBasket(ventana,listaBasket)\n\n\n #dibujarTexto\n texto = fuente.render(\"Timer: %.3f\"%timer,1,ROJO)\n ventana.blit(texto, (200,100))\n\n if checarColisionJugador(listaEnemigos,spriteRondo,efecto2)==True or checarColisionJugador(listaEnemigos2,spriteRondo,efecto2)==True:\n ESTADO=OVER\n\n if ESTADO == MENU:\n\n spriteRondo = pygame.sprite.Sprite()\n spriteRondo.img = imgRondo\n spriteRondo.rect = imgRondo.get_rect()\n spriteRondo.rect.left = 0\n spriteRondo.rect.bottom = ALTO // 2 + spriteRondo.rect.height // 2\n\n\n\n timer=0\n ventana.fill(NEGRO)\n ventana.blit(imgBoton,(ANCHO//2-128,ALTO//2-50))\n texto = fuente.render(\"HighScore: %.3fs\" % (max(listaMarcador)), 1, ROJO)\n ventana.blit(texto, (200, 100))\n\n if ESTADO == OVER:\n\n listaEnemigos=[]\n listaEnemigos2=[]\n\n Highscore=0\n\n\n timer-=1/10\n\n\n ventana.fill(NEGRO)\n\n marcador=timer\n\n if marcador >= Highscore :\n listaMarcador.append(marcador)\n\n texto = fuente.render(\"Your Score: %.3fs\" % marcador, 1, ROJO)\n ventana.blit(texto, (200, 100))\n ventana.blit(imgBoton2, (ANCHO // 2 - 128, ALTO // 2 - 50))\n\n\n\n pygame.display.flip() # Actualiza trazos (Si no llamas a esta función, no se dibuja)\n reloj.tick(10) # 40 fps\n\n timer+=1/10\n\n\n # Después del ciclo principal\n pygame.quit() # termina pygame\n\n\n\n# Función principal, aquí resuelves el problema\ndef main():\n dibujar() # Por ahora, solo dibuja\n\n\n# Llamas a la función principal\nsalida = open(\"HIGHSCORE.txt\", \"w\")\n\n\nmain()\n\n\nsalida.write(\"Highest Score: %3f\\n\"% (max(listaMarcador)))\nsalida.close()","sub_path":"PvZ.py","file_name":"PvZ.py","file_ext":"py","file_size_in_byte":11354,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"99405870","text":"## Miracle battles\n\nimport pygame.draw\n\n\nclass Realm: # player's information\n def __init__(self, name, f_color, s_color, alignment):\n self.name = name\n self.f_color = f_color\n self.s_color = s_color\n self.alignment = alignment\n self.status = True\n self.known_map = []\n self.turn_completed = False\n\n\nclass Roadway: # main class for road improvements on tiles for faster armies movements\n def __init__(self, material, speed):\n self.material = material\n self.speed = speed\n # road connection with nearby tiles\n self.l_m = False\n self.r_m = False\n self.m_t = False\n self.m_b = False\n self.r_t = False\n self.l_b = False\n self.r_b = False\n self.l_t = False\n\n\nclass Tile: # main class for tile cells\n def __init__(self, position, terrain, conditions):\n self.posxy = position\n self.terrain = terrain\n self.conditions = conditions\n self.road = None # Place for roadway class object\n self.travel = True\n self.lot = None\n self.city_id = None\n self.army_id = None\n\n\nclass Settlement: # main class for cities that control surrounding lands and let hire heroes and armies\n def __init__(self, position, location, city_id, name, alignment, owner):\n self.posxy = position\n self.location = location\n self.city_id = city_id\n self.name = name\n self.alignment = alignment\n self.owner = owner\n self.control_zone = []\n self.obj_typ = \"Settlement\"\n self.property = []\n\n\nclass Map_Object: # main class for objects of nature, landscape and obstacles\n def __init__(self, position, location, obj_name, img_path, obj_typ, disposition):\n self.posxy = position\n self.location = location\n self.obj_name = obj_name\n self.img_path = img_path\n self.obj_typ = obj_typ\n self.disposition = disposition\n\n\nclass Facility: # main class for facilities that belong to settlements in whose control zone they exist\n def __init__(self, position, location, obj_name, img_path, img_name, obj_typ, disposition, alignment):\n self.posxy = position\n self.location = location\n self.obj_name = obj_name\n self.img_path = img_path\n self.img_name = img_name\n self.obj_typ = obj_typ\n self.disposition = disposition\n self.alignment = alignment\n\n\nclass Army: # main class for armies that consist of from 1 up to 20 units and could have a hero\n def __init__(self, position, location, army_id, owner):\n self.posxy = position\n self.location = location\n self.army_id = army_id\n self.owner = owner\n self.hero_id = None\n self.units = []\n self.leader = None\n self.route = []\n self.path_arrows = []\n self.action = \"Stand\"\n\n\nclass Regiment: # main class for creatures that serves as units for fighting in land battles\n def __init__(self, name, rank, img, img_source, x_offset, y_offset, speed, base_HP, number, rows, reg_tags, crew,\n attacks, armor, defence, base_leadership, skills):\n self.name = name\n self.rank = rank # Demonstrates importance of unit in army, what determines which unit would be shown on map\n self.img = img\n self.img_source = img_source\n self.x_offset = x_offset\n self.y_offset = y_offset\n self.reg_tags = reg_tags # List of regiment tags\n # Parameters\n self.movement_points = 800\n self.max_movement_points = 800\n self.speed = speed # Movement range in battle\n self.base_HP = base_HP # Value of full health for creatures in this regiment\n self.experience = 0\n self.number = number # Number of creatures in row\n self.rows = rows # Number of rows\n self.crew = crew # List of creatures that fill regiment\n self.cemetery = [] # Where dead creatures get put from crew\n self.position = None # Position on battlefield\n self.direction = None # In what direction regiment is oriented on battlefield\n self.attacks = attacks # List of attacks consisting of Strike class objects\n self.engaged = False\n self.armor = armor\n self.defence = defence\n self.counterattack = 1\n self.effects = [] # Different effects during the battle\n self.skills = skills # Just various skills used by regiment in a form of list with skill objects\n self.base_leadership = base_leadership # Regiment base leadership\n self.leadership = 0.0 # Regiment's maximum morale based on its leadership and various bonuses\n self.morale = 0.0 # Regiment's morale, if it gets lower than 0, then regiment will route in battle\n\n\nclass Strike: # main class for attacks performed by regiments\n def __init__(self, name, attack_type, tags, min_dmg, max_dmg, mastery, effective_range, range_limit):\n self.name = name\n self.attack_type = attack_type\n self.tags = tags # List of tags\n self.min_dmg = min_dmg\n self.max_dmg = max_dmg\n self.mastery = mastery\n self.effective_range = effective_range\n self.range_limit = range_limit\n\n\nclass Creature: # main class for creature that fill regiment units in land battles\n def __init__(self, name, img, img_source, img_width, img_height, HP):\n self.name = name\n self.img = img\n self.img_source = img_source\n self.img_width = img_width\n self.img_height = img_height\n self.HP = HP # Hit points - creature's health\n self.alive = True # Status used during battle\n\n\nclass Land_Battle: # class keeps information about outgoing battle\n def __init__(self, battle_id, attacker_id, attacker_realm, defender_id, defender_realm, terrain, conditions,\n battle_map, battle_pov, cover_map, starting_attacking_positions, starting_defending_positions):\n self.battle_id = battle_id\n self.attacker_id = attacker_id # Army ID\n self.attacker_realm = attacker_realm # Name of a realm\n self.defender_id = defender_id # Army ID\n self.defender_realm = defender_realm # Name of a realm\n self.realm_in_control = None # Name of a realm - every time a queue card called, one of fighting players takes\n # control of battlefield if needed\n self.enemy = None # Opposite of realm in control\n self.enemy_army_id = None # Id of army that belong to realm that is opposite to realm in control\n self.terrain = terrain\n self.conditions = conditions\n self.battle_map = battle_map\n self.battle_pov = battle_pov\n self.stage = \"Formation\"\n self.cover_map = cover_map\n self.starting_attacking_positions = starting_attacking_positions\n self.starting_defending_positions = starting_defending_positions\n self.selected_tile = []\n self.selected_unit = -1 # Index of tile with selected regiment\n # -1 means that no regiment is selected at this moment\n self.selected_unit_alt = () # (x, y) position format\n self.waiting_list = [] # In formation stage, list contains units that yet need to be positioned on map\n self.waiting_index = 0\n self.unit_card = -1 # Index of unit card in waiting list\n self.queue = []\n self.queue_index = 0\n self.AI_ready = False\n self.ready_to_act = False # Needed for animation\n self.attack_type_index = 0 # Used when player is changing attack methods\n self.attack_type_in_use = \"\"\n self.cur_effective_range = 0\n self.cur_range_limit = 0\n\n self.movement_grid = None # Calculated before regiment movement in a form of list with [x, y] coordinates\n self.path = None # Bunch of nodes\n self.tile_trail = None # Reversed path toward destination for moving unit\n self.primary = None # Battle order for unit to perform an action\n self.secondary = None # Next battle order for unit to perform an action\n self.anim_message = None # Text on battlefield\n self.move_destination = None # Where unit is going\n self.target_destination = None # Whom unit going to hit\n self.changed_direction = None # Unit changes its direction when it has to shoot\n self.attacking_rotate = [] # List of units from army whose unit is attacking in melee right now\n self.defending_rotate = [] # List of units from army whose unit is being attacked in melee right now\n self.perform_attack = [] # List of indexes that indicates which creatures from regiment will perform attack\n self.dealt_damage = 0 # Total amount of damage dealt during one attack by regiment\n self.killed_creatures = 0\n self.damage_msg_position = [] # Around which unit should message pop up\n\n # Time constants\n self.battle_last_start = 0\n self.battle_temp_time_passed = 0\n self.battle_passed_time = 0\n self.battle_display_time = 0\n self.battle_last_change = 0\n\n\nclass Battle_Tile: # main class for tile cells in battlefield\n def __init__(self, position, terrain, conditions):\n self.posxy = position\n self.terrain = terrain\n self.conditions = conditions\n self.unit_index = None\n self.army_id = None\n self.obstacle = None\n self.graveyard = []\n\n\nclass Grave: # main class for dead regiments in battlefield, created at Battle_Tile.graveyard\n def __init__(self, unit_index, army_id):\n self.unit_index = unit_index\n self.army_id = army_id\n\n\nclass Queue_Card: # main class for tile cells in battlefield\n def __init__(self, time_act, obj_type, army_id, owner, number, position, img_source, img, f_color, s_color,\n x_offset, y_offset):\n self.time_act = time_act\n self.obj_type = obj_type\n self.army_id = army_id\n self.owner = owner\n self.number = number # Index of unit in army\n self.position = position\n self.img_source = img_source\n self.img = img\n self.f_color = f_color\n self.s_color = s_color\n self.x_offset = x_offset\n self.y_offset = y_offset\n\n\nclass Battle_Map_Object: # main class for objects of nature, landscape and obstacles in battle\n def __init__(self, obj_name, img_path, obj_typ, disposition):\n self.obj_name = obj_name\n self.img_path = img_path\n self.obj_typ = obj_typ\n self.disposition = disposition\n","sub_path":"Resources/game_classes.py","file_name":"game_classes.py","file_ext":"py","file_size_in_byte":10574,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"253790785","text":"import os\r\nimport shutil\r\nimport csv\r\nimport numpy as np\r\nfrom sklearn.metrics import classification_report\r\nfrom sklearn.metrics import confusion_matrix\r\nimport pandas as pd\r\n\r\nimport tensorflow as tf\r\nimport keras\r\n\r\nfrom keras.models import load_model\r\n\r\n#from AlexNet import load_data\r\n#from NASNet import load_data\r\nfrom DenseNet import load_data\r\n\r\nos.environ[\"CUDA_DEVICE_ORDER\"]=\"PCI_BUS_ID\"\r\nos.environ[\"CUDA_VISIBLE_DEVICES\"]=\"1\"\r\nconfig = tf.ConfigProto(allow_soft_placement=True)\r\nconfig.gpu_options.allow_growth = True\r\nkeras.backend.set_session(tf.Session(config=config))\r\n\r\n#save_dir = './../../Experiments/Report/AlexNet/'\r\n#save_dir = './../../Experiments/Report/NASNet/'\r\nsave_dir = './../../Experiments/Report/DenseNet256/'\r\nshutil.rmtree(save_dir, ignore_errors=True)\r\nos.makedirs(save_dir, exist_ok=True)\r\n\r\nsize = 224\r\n#model_path = './../../Experiments/AlexNet/model_best.h5'\r\n#model_path = './../../Experiments/NASNet/end_model.h5'\r\nmodel_path = './../../Experiments/DenseNet256/model_best.h5'\r\ntest_dir = './../../Dataset/test/'\r\n\r\n# load model\r\nmodel = load_model(model_path)\r\nimage_shape = (size, size, 3)\r\n\r\n# load dataset\r\nimage_path_list = []\r\nx_test, y_test = load_data(test_dir, image_shape)\r\n\r\n# predict\r\npredicted = model.predict(x_test)\r\npredicted_classes = np.argmax(predicted, axis=1)\r\n\r\n# calc result\r\ntrue_classes = np.argmax(y_test,axis=1)\r\nlabel_names = ['japanese_cedar', 'japanese_cypress', 'other_tree', 'not_tree']\r\n\r\nreport_df = pd.DataFrame(classification_report(true_classes, predicted_classes, target_names=label_names, output_dict=True)).transpose()\r\nconfusion_matrix_df = pd.DataFrame(confusion_matrix(true_classes, predicted_classes), columns=label_names, index=label_names)\r\nprint(report_df)\r\nprint(confusion_matrix_df)\r\n\r\n# save report_df as csv\r\nwith open(save_dir+'pred_results.csv','w', newline=\"\") as f:\r\n writer = csv.writer(f)\r\n writer.writerow(['image_path', 'pred_0', 'pred_1', 'pred_2', 'pred_3', 'true', 'pred_classes'])\r\n for path, pred, true, pred_class in zip(image_path_list, predicted, true_classes, predicted_classes):\r\n writer.writerow([path, pred[0], pred[1], pred[2], pred[3], true, pred_class])\r\n\r\nreport_save_path = save_dir+'predict_report.csv'\r\nconfusion_matrix_save_path = save_dir+'confusion_matrix.csv'\r\nreport_df.to_csv(report_save_path)\r\nconfusion_matrix_df.to_csv(confusion_matrix_save_path)\r\n","sub_path":"train_test/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":2392,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"414054087","text":"\"\"\"Georeferenced model of gridded data.\n\"\"\"\n\nimport logging\nimport math\nfrom abc import ABC\n\nimport numpy\n\nfrom .config import string_to_list\nfrom .io.hdf5 import HDF5Storage\n\n\nclass Block():\n \"\"\"Block of regular logically gridded points.\n \"\"\"\n\n def __init__(self, name, config):\n \"\"\"Constructor.\n\n Args:\n name (str)\n Name of block.\n config (dict)\n Block parameters as dictionary.\n Keys:\n resolution_horiz: horizontal resolution (m)\n resolution_vert: vertical resolution (m)\n z_top: Elevation of top of block (m)\n z_bot: Elevation of bottom of block (m)\n z_top_offset: Vertical offset of top set of points below top of block (m)\n \"\"\"\n self.name = name\n self.resolution_horiz = float(config[\"resolution_horiz\"])\n self.resolution_vert = float(config[\"resolution_vert\"])\n self.z_top = float(config[\"z_top\"])\n self.z_bot = float(config[\"z_bot\"])\n self.z_top_offset = float(config[\"z_top_offset\"])\n\n def get_dims(self, domain):\n \"\"\"Get number of points in block along each dimension.\n\n Args:\n domain (Model)\n Model domain.\n\n Returns:\n Array of points in block (Nx*Ny*Nz, 3)\n \"\"\"\n num_x = 1 + int(domain.dim_x / self.resolution_horiz)\n num_y = 1 + int(domain.dim_y / self.resolution_horiz)\n num_z = 1 + int((self.z_top - self.z_bot) / self.resolution_vert)\n return (num_x, num_y, num_z)\n\n def generate_points(self, domain):\n \"\"\"Generate grid of points in block.\n\n Args:\n domain (Model)\n Model domain.\n\n Returns:\n 3D array (Nx*Ny*Nz,3) of point locations in block.\n \"\"\"\n (num_x, num_y, num_z) = self.get_dims(domain)\n logger = logging.getLogger(__name__)\n logger.info(\"Block '{}' contains {} points ({} x {} x {}).\".format(\n self.name, num_x * num_y * num_z, num_x, num_y, num_z,))\n\n x1 = numpy.linspace(0.0, self.resolution_horiz * (num_x - 1), num_x)\n y1 = numpy.linspace(0.0, self.resolution_horiz * (num_y - 1), num_y)\n z1 = numpy.linspace(0.0, self.resolution_vert * (num_z - 1), num_z)\n x, y, z = numpy.meshgrid(x1, y1, z1)\n\n domain_top = 0.0\n domain_bot = -domain.dim_z\n if domain.topography is not None:\n topo_geo = self.get_block_elevation(domain.topography)\n for iz in range(z.shape[-1]):\n z[:, :, iz] = domain_bot + (topo_geo - domain_bot) / (domain_top -\n domain_bot) * (self.z_top - z[:, :, iz] - domain_bot)\n\n # Move top points down\n z[:, :, 0] += self.z_top_offset\n else:\n z = self.z_top - z\n\n xyz_geo = numpy.stack((x, y, z), axis=3)\n xyz_model = numpy.zeros(xyz_geo.shape)\n az_rad = domain.y_azimuth * math.pi / 180.0\n xyz_model[:, :, :, 0] = domain.origin_x + xyz_geo[:, :, :, 0] * \\\n math.cos(az_rad) + xyz_geo[:, :, :, 1] * math.sin(az_rad)\n xyz_model[:, :, :, 1] = domain.origin_y - xyz_geo[:, :, :, 0] * \\\n math.sin(az_rad) + xyz_geo[:, :, :, 1] * math.cos(az_rad)\n xyz_model[:, :, :, 2] = xyz_geo[:, :, :, 2]\n return xyz_model\n\n def get_block_elevation(self, topography):\n \"\"\"Get topography grid for block.\n Args:\n domain (Model)\n Model domain.\n\n Returns:\n 3D array (Nx*Ny*Nz,3) of point locations in block.\n \"\"\"\n TOLERANCE = 0.01\n num_skip = int(0.01 + self.resolution_horiz / topography.resolution_horiz)\n if math.fabs(num_skip * topography.resolution_horiz - self.resolution_horiz) > TOLERANCE:\n raise ValueError(\"Block resolution ({}) must be a integer multiple of the topography resolution ({})\".format(\n self.resolution_horiz, topography.resolution_horiz))\n\n return topography.elevation[::num_skip, ::num_skip]\n\n\nclass Topography():\n \"\"\"Surface topography.\n \"\"\"\n\n def __init__(self, config):\n \"\"\"Constructor.\n\n Args:\n config (dict)\n True if use of topography is enabled, False otherwise.\n Keys:\n use_topography: Model uses topography\n resolution_horiz: Horizontal resolution in m\n \"\"\"\n self.elevation = None\n self.enabled = bool(config[\"use_topography\"])\n self.resolution_horiz = float(config[\"resolution_horiz\"]) if self.enabled else None\n\n def set_elevation(self, elev):\n \"\"\"Set topography values.\n\n Args:\n elev (numpy.array)\n Numpy array [Nx*Ny] with elevation at points.\n \"\"\"\n if not self.enabled:\n return\n\n self.elevation = elev\n\n def generate_points(self, domain):\n \"\"\"Generate points for topography.\n\n Args:\n domain (Model)\n Model with topography.\n Returns:\n 2D array (Nx*Ny,2) of point locations for ground surface.\n \"\"\"\n dx = self.resolution_horiz\n\n num_x = 1 + int(domain.dim_x / dx)\n num_y = 1 + int(domain.dim_y / dx)\n logger = logging.getLogger(__name__)\n logger.info(\"Topography contains {} points ({} x {}).\".format(\n num_x * num_y, num_x, num_y))\n\n x1 = numpy.linspace(0.0, dx * (num_x - 1), num_x)\n y1 = numpy.linspace(0.0, dx * (num_y - 1), num_y)\n x, y = numpy.meshgrid(x1, y1)\n z = numpy.zeros(x.shape)\n\n xyz_geo = numpy.stack((x, y, z), axis=2)\n xyz_model = numpy.zeros(xyz_geo.shape)\n az_rad = domain.y_azimuth * math.pi / 180.0\n xyz_model[:, :, 0] = domain.origin_x + xyz_geo[:, :, 0] * math.cos(az_rad) + xyz_geo[:, :, 1] * math.sin(az_rad)\n xyz_model[:, :, 1] = domain.origin_y - xyz_geo[:, :, 0] * math.sin(az_rad) + xyz_geo[:, :, 1] * math.cos(az_rad)\n return xyz_model\n\n\nclass Model(ABC):\n \"\"\"Georeferenced model composed of logical grids, potentially warped by topography.\n \"\"\"\n\n def __init__(self, config):\n \"\"\"Constructor.\n \"\"\"\n self.topography = None\n self.blocks = []\n\n self.initialize(config)\n\n def initialize(self, config):\n \"\"\"Setup model, creating blocks.\n\n Args:\n config (dict)\n Model configuration.\n \"\"\"\n self.title = config[\"geomodelgrids\"][\"title\"]\n self.id = config[\"geomodelgrids\"][\"id\"]\n self.description = config[\"geomodelgrids\"][\"description\"]\n self.keywords = string_to_list(config[\"geomodelgrids\"][\"keywords\"])\n self.creator_name = config[\"geomodelgrids\"][\"creator_name\"]\n self.creator_email = config[\"geomodelgrids\"][\"creator_email\"]\n self.creator_institution = config[\"geomodelgrids\"][\"creator_institution\"]\n self.acknowledgments = config[\"geomodelgrids\"][\"acknowledgments\"]\n self.authors = string_to_list(config[\"geomodelgrids\"][\"authors\"], delimiter=\"|\")\n self.references = string_to_list(config[\"geomodelgrids\"][\"references\"], delimiter=\"|\")\n self.doi = config[\"geomodelgrids\"][\"doi\"]\n self.version = config[\"geomodelgrids\"][\"version\"]\n self.projection = config[\"coordsys\"][\"projection\"]\n self.origin_x = float(config[\"coordsys\"][\"origin_x\"])\n self.origin_y = float(config[\"coordsys\"][\"origin_y\"])\n self.y_azimuth = float(config[\"coordsys\"][\"y_azimuth\"])\n self.data_values = string_to_list(config[\"data\"][\"values\"])\n self.data_units = string_to_list(config[\"data\"][\"units\"])\n self.dim_x = float(config[\"domain\"][\"dim_x\"])\n self.dim_y = float(config[\"domain\"][\"dim_y\"])\n self.dim_z = float(config[\"domain\"][\"dim_z\"])\n\n self.config = config\n\n self.topography = Topography(config[\"topography\"])\n for name in string_to_list(config[\"domain\"][\"blocks\"]):\n block = Block(name, config[name])\n self.blocks.append(block)\n\n self.storage = HDF5Storage(config[\"geomodelgrids\"][\"filename\"])\n\n def import_domain(self):\n \"\"\"Write domain information to storage.\"\"\"\n self.storage.save_domain(self)\n\n def import_topography(self):\n \"\"\"Write topography information to storage.\n \"\"\"\n self.storage.save_topography(self.topography)\n\n def load_topography(self):\n \"\"\"Load topography from model file.\"\"\"\n self.storage.load_topography(self.topography)\n\n def import_block(self, block, values):\n \"\"\"Write block information to storage.\n\n Args:\n block (Block)\n Block information.\n values (numpy.array)\n Numpy array [Nx,Ny,Nz,Nv] of gridded data asociated with block.\n \"\"\"\n self.storage.save_block(block, values)\n\n #@abstractmethod\n def query_topography(self, points):\n \"\"\"Query EarthVision model for elevation of ground surface at points.\n\n Args:\n points (numpy.array [Nx,Ny,Nz])\n Numpy array with coordinates of points in model coordinates.\n \"\"\"\n\n #@abstractmethod\n def query_values(self, block):\n \"\"\"Query EarthVision model for values at points.\n\n Args:\n block (Block)\n Block information.\n \"\"\"\n\n\n# End of file\n","sub_path":"geomodelgrids/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":9487,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"268410633","text":"\"\"\"\ndate: 20190711\ncreated by: ishida\nref: https://qiita.com/pokotsun/items/dd8eb48fadeee052110b\n\"\"\"\n\nimport numpy as np\nfrom input_generator import InputGenerator\nfrom reservoir_network import ReservoirNetwork\nimport matplotlib.pyplot as plt\n\nT = np.pi * 16\nRATIO_TRAIN = 0.6\ndt = np.pi * 0.06\nAMPLITUDE = 0.9\nLEAK_RATE = 0.5\nNUM_RESERVOIR_NODES = 150\n\n\ndef main():\n i_gen = InputGenerator(0, T, dt)\n data = i_gen.generate_sin(amplitude=AMPLITUDE)\n # data = i_gen.generate_rectangle(amplitude=AMPLITUDE)\n NUM_TRAIN = int(len(data) * RATIO_TRAIN)\n train_data = data[:NUM_TRAIN]\n\n model = ReservoirNetwork(inputs=train_data,\n num_input_nodes=1,\n num_reservoir_nodes=NUM_RESERVOIR_NODES,\n num_output_nodes=1,\n leak_rate=LEAK_RATE)\n\n model.train()\n trained_data = model.get_train_result()\n\n num_predict_step = 108\n predict_result = model.predict(num_predict_step)\n\n fsize = 30\n fig = plt.figure(figsize=(12, 9))\n ax = fig.add_subplot(111)\n ax.plot(np.arange(0, T, dt), data, label='inputs', color='darkgreen', lw=2)\n ax.plot(np.arange(0, int(T * RATIO_TRAIN), dt), trained_data, label='trained', color='royalblue', lw=2)\n ax.plot(np.arange(int(T * RATIO_TRAIN), T, dt), predict_result, label='predict', color='orangered', lw=2)\n ax.axvline(x=int(T * RATIO_TRAIN), label='end of train', color='deeppink', lw=2)\n ax.legend(fontsize=fsize/2)\n ax.tick_params(labelsize=fsize)\n # ax.set_title('Echo State Network Sin Prediction', fontsize=fsize)\n ax.set_title('leak_rate = {}'.format(LEAK_RATE), fontsize=fsize/1.5)\n ax.set_xlabel('time [ms]', fontsize=fsize)\n ax.set_ylabel('y(t)', fontsize=fsize)\n fig.tight_layout()\n plt.show()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"Reservoir_Computing/main1.py","file_name":"main1.py","file_ext":"py","file_size_in_byte":1850,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"485837344","text":"from django.shortcuts import render \nfrom django.http import JsonResponse\nfrom .forms import Resource\nimport json\nimport requests\nimport yaml\n\nnowVersion = \"V1.0\"\nheat_template_version = '2015-10-15'\nform = Resource()\ncontext = {\n 'form' : form,\n 'version' : nowVersion\n }\n\ndef view(request):\n return render(request, 'cloudservice.html', context) # context를 포함한 cloudservice.html 템플릿의 HttpResponse 객체를 반환.\n\n\ndef send(request):\n\n #openstack keystone 토큰을 발급받기 위한 body\n payload = { \n \"auth\": {\n \"identity\": {\n\n \"methods\": [\n \"password\"\n ],\n \"password\": {\n \"user\": {\n \"id\": \"6443abb0d446410f9f5918d910e767a0 \",\n \"password\": \"devstack\"\n }\n }\n },\n \"scope\": {\n \"project\": {\n \"id\": \"2e2cca5c94e44a859a24b8a63b0ec4cb\"\n }\n }\n }\n }\n\n\n #openstack keystone token 발급\n auth_res = requests.post(\"http://192.168.0.251/identity/v3/auth/tokens\",\n headers = {'content-type' : 'application/json'},\n data = json.dumps(payload))\n\n #발급받은 token\n token = auth_res.headers['X-Subject-Token']\n\n # openstack container에 있는 baseHOT파일 가져오기\n HOT_res = requests.get(\"http://192.168.0.251:8080/v1/AUTH_2e2cca5c94e44a859a24b8a63b0ec4cb/files/baseHOT(V1.0).yaml\",\n headers={'X-Auth-Token' : token,\n 'content-type' : 'application/yaml'}).text\n\n HOT = yaml.load(HOT_res)\n\n # container에 있는 index파일 가져오기\n index_res = requests.get(\"http://192.168.0.251:8080/v1/AUTH_2e2cca5c94e44a859a24b8a63b0ec4cb/files/index.json\",\n headers={'X-Auth-Token' : token,\n 'content-type' : 'application/json'}).json()\n\n \n\n # 웹에서 입력받은 강의실명\n if not request.POST.getlist('class name')[0] :\n return render(request, 'recheckname.html', context)\n\n stack_name = request.POST.getlist('class name')[0]\n\n # 웹에서 입력받은 언어\n if not request.POST.getlist('lan') :\n return render(request, 'rechecklan.html', context)\n \n lan = request.POST.getlist('lan')\n lan_cnt = len(lan)\n language = \"\"\n for i in range(0,lan_cnt):\n if not i == lan_cnt-1 :\n language = language + lan[i] +\", \"\n else :\n language = language + lan[i]\n \n\n # 웹에서 입력받은 학생수\n student_num = int(request.POST.getlist('student cnt')[0])\n if student_num < 10 : flavor = \"m1.tiny\"\n elif student_num > 9 and student_num <20 : flavor = \"m1.small\"\n elif student_num > 19 and student_num <40 : flavor =\"m1.medium\"\n elif student_num > 39 and student_num < 80 : flavor = \"m1.large\"\n elif student_num > 79 and student_num < 160 : flavor = \"m1.xlarge\"\n #over 160\n\n\n # 웹에서 입력받은 운영체제\n send_form=Resource(request.POST)\n i_f = send_form['image']\n image = i_f.data\n if image == \"Ubuntu Linux 64-bit\" :\n if flavor == \"m1.tiny\" :\n flavor = \"m1.small\"\n HOT_image = \"bionic-server-cloudimg-amd64\" \n\n elif image == \"CentOS 7 x86-64\" :\n if flavor == \"m1.tiny\" :\n flavor = \"m1.small\"\n HOT_image = \"CentOS-7-x86_64\"\n\n else :\n HOT_image = image\n \n\n # 웹에서 입력받은 교육 기간\n if request.POST.getlist('latermn') :\n edu_term = request.POST.getlist('term')[0]\n \n # 웹에서 입력받은 데이터 유지 기간\n if request.POST.getlist('maintenance') :\n data_maintence = request.POST.getlist('maintenance')[0]\n \n # 웹에서 입력받은 이벤트 기간\n if request.POST.getlist('event') :\n event = request.POST.getlist('event')[0]\n \n\n\n resource = {'language' : language, 'Image' : i_f.data }\n \n \n major_count = 1\n minor_count = 0\n \n global nowVersion \n \n # HOT 템플릿 버저닝\n while(True):\n try:\n if index_res[\"V\"+str(major_count)+\".0\"][\"resource\"][\"language\"] == language and index_res[\"V\"+str(major_count)+\".0\"][\"resource\"][\"Image\"] == image: # major 버전 기준으로 비교(language, image)\n while(True): # minor 버전 기준으로 비교\n try:\n if index_res[\"V\"+str(major_count)+\".0\"][\"V\"+str(major_count)+\".\"+str(minor_count)] == flavor: # 만약 flavor가 같은게 있으면 (버전 새로 생성 안해도 된다.)\n nowVersion = \"V\"+str(major_count)+\".\"+str(minor_count)\n break\n else:\n minor_count += 1 # 같은 flavor가 없으면 다음 minor 검사하기 위해 카운트.\n\n except KeyError: # 새로운 minor 버전 추가\n index_res[\"V\"+str(major_count)+\".0\"][\"V\"+str(major_count)+\".\"+str(minor_count)] = flavor\n nowVersion = \"V\"+str(major_count)+\".\"+str(minor_count)\n HOT[\"description\"] = \"Coding System(\" + language + \")\" # language\n HOT[\"resources\"][\"my_instance\"][\"properties\"][\"image\"] = HOT_image # image\n HOT[\"resources\"][\"my_instance\"][\"properties\"][\"flavor\"] = flavor # flavor\n if image == \"Ubuntu Linux 32-bit\" or image == \"Ubuntu Linux 64-bit\" : # image가 Ubuntu Linux 32-bit나 Ubuntu Linux 64-bit일 경우 user_data에 환경 설정을 위한 코드 추가\n HOT[\"resources\"][\"my_instance\"][\"properties\"][\"user_data\"] = \"#cloud-config\\nruncmd:\\n - netplan --debug generate\\n - netplan apply\\n - apt-get update -y\\n - apt-get upgrade -y\\n\"\n for i in range(0,lan_cnt):\n if lan[i] == \"C\": \n HOT[\"resources\"][\"my_instance\"][\"properties\"][\"user_data\"] +=\" - sudo apt-get install gcc -y\\n\" #language가 C언어일 경우 gcc 설치\n if lan[i] == \"C++\" :\n HOT[\"resources\"][\"my_instance\"][\"properties\"][\"user_data\"] +=\" - sudo apt-get install g++ -y\\n\" #language가 C++언어일 경우 gcc 설치\n break\n break\n major_count += 1\n\n except KeyError: # 새로운 major 버전 추가\n index_res[\"V\"+str(major_count)+\".0\"]= { \"resource\" : resource }\n index_res[\"V\"+str(major_count)+\".0\"][\"V\"+str(major_count)+\".0\"] = flavor\n nowVersion = \"V\"+str(major_count)+\".\"+str(minor_count)\n HOT[\"description\"] = \"Coding System(\" + language + \")\" # language\n HOT[\"resources\"][\"my_instance\"][\"properties\"][\"image\"] = HOT_image # image\n HOT[\"resources\"][\"my_instance\"][\"properties\"][\"flavor\"] = flavor # flavor\n if image == \"Ubuntu Linux 32-bit\" or image == \"Ubuntu Linux 64-bit\" :\n HOT[\"resources\"][\"my_instance\"][\"properties\"][\"user_data\"] = \"#cloud-config\\nruncmd:\\n - netplan --debug generate\\n - netplan apply\\n - apt-get update -y\\n - apt-get upgrade -y\\n\"\n for i in range(0,lan_cnt):\n if lan[i] == \"C\": \n HOT[\"resources\"][\"my_instance\"][\"properties\"][\"user_data\"] +=\" - sudo apt-get install gcc -y\\n\"\n if lan[i] == \"C++\" :\n HOT[\"resources\"][\"my_instance\"][\"properties\"][\"user_data\"] +=\" - sudo apt-get install g++ -y\\n\"\n break\n\n\n HOT[\"heat_template_version\"] = heat_template_version\n\n # openstack container에 index파일 저장\n requests.put(\"http://192.168.0.251:8080/v1/AUTH_2e2cca5c94e44a859a24b8a63b0ec4cb/files/index.json\",\n headers={'X-Auth-Token' : token,\n 'content-type' : 'application/json'\n }, data=json.dumps(index_res, indent=4))\n\n # openstack container에 HOT 템플릿 저장\n requests.put(\"http://192.168.0.251:8080/v1/AUTH_2e2cca5c94e44a859a24b8a63b0ec4cb/files/\" + nowVersion + \".yaml\",\n headers={'X-Auth-Token' : token,\n 'content-type' : 'application/yaml'\n }, data=yaml.dump(HOT, sort_keys=False))\n\n # openstack container에서 HOT 템플릿 읽어오기\n template = yaml.load(requests.get(\"http://192.168.0.251:8080/v1/AUTH_2e2cca5c94e44a859a24b8a63b0ec4cb/files/\" + nowVersion + \".yaml\",\n headers={'X-Auth-Token' : token, 'content-type' : 'application/yaml'}).text)\n\n # stack 생성을 위한 body\n Hot_body = {\n \"stack_name\": stack_name,\n \"template\" : template,\n \"timeout_mins\": 60\n }\n\n Json_Hot_body = json.dumps(Hot_body, indent=4)\n\n # stack 생성\n requests.post(\"http://192.168.0.251/heat-api/v1/2e2cca5c94e44a859a24b8a63b0ec4cb/stacks\",\n headers = {'X-Auth-Token' : token, 'content-type' : 'application/json'}, data = Json_Hot_body)\n\n # 웹에 index파일 내용과 token 출력\n return JsonResponse({\n 'index' : index_res,\n 'token' : token\n }, safe=False)\n\n","sub_path":"cloud/cloudservice/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":9211,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"467000352","text":"import datetime\nimport json\nimport requests\nimport logging\nimport time\n\n\nfrom datapackage_pipelines.wrapper import ingest, spew\n\nparams, dp, res_iter = ingest()\n\nRANGES = [\n ('01/01', '03/01'),\n ('03/02', '04/30'),\n ('05/01', '06/30'),\n ('07/01', '08/31'),\n ('09/01', '10/31'),\n ('11/01', '12/31'),\n]\n\n\ndef get_for_range(cid, year_start, range_start, year_end, range_end):\n logging.info('%r %s/%s -> %s/%s', cid, year_start, range_start, year_end, range_end)\n data = {\"PartyID\": None,\n \"EntityID\": cid,\n \"EntityTypeID\": 1,\n \"PublicationSearchType\": \"1\",\n \"GD_Name\": \"\",\n \"CityID\": \"\",\n \"CountryID\": \"\",\n \"FromDate\": \"%s/%d\" % (range_start, year_start),\n \"ToDate\": \"%s/%d\" % (range_end, year_end),\n \"FromSum\": \"\",\n \"ToSum\": \"\",\n \"ID\": None,\n \"State\": 0,\n \"URL\": None,\n \"IsControl\": False,\n \"IsUpdate\": False}\n\n resp = []\n for retries in range(10):\n try:\n resp = requests.post('https://statements.mevaker.gov.il/Handler/GuarantyDonationPublisherHandler.ashx',\n data={'action': 'gds',\n 'd': json.dumps(data)}).json()\n break\n except requests.exceptions.RequestException as e:\n logging.error('Retrying in a bit (%r)', e)\n time.sleep(1)\n\n assert len(resp) == 6\n if len(resp[0]) < 1000:\n return resp[0]\n\ndef get_for_candidate(cid):\n year_start = 2010\n year_end = datetime.datetime.now().year\n resp = get_for_range(cid, year_start, RANGES[0][0], year_end, RANGES[-1][-1])\n if resp is None:\n for year in range(year_start, year_end+1):\n resp = get_for_range(cid, year, RANGES[0][0], year, RANGES[-1][-1])\n if resp is None:\n for range_start, range_end in RANGES:\n resp = get_for_range(cid, year, range_start, year, range_end)\n assert resp is not None\n yield resp\n else:\n yield resp\n else:\n yield resp\n\ndef get_transactions(rows):\n for row in rows:\n cid = str(row['ID'])\n for resp in get_for_candidate(cid):\n for rr in resp:\n rr[\"Party\"] = row[\"Party\"]\n yield rr\n\ndef process_resources(res_iter_):\n first = next(res_iter_)\n yield get_transactions(first)\n\ndp['resources'][0] = {\n 'name': 'transactions',\n 'path': 'data/candidates.csv',\n 'schema': {\n 'fields': [\n {'name': 'CandidateName', 'type': 'string'},\n {'name': 'City', 'type': 'string'},\n {'name': 'Country', 'type': 'string'},\n {'name': 'GD_Date', 'type': 'string'},\n {'name': 'GD_Name', 'type': 'string'},\n {'name': 'GD_Sum', 'type': 'string'},\n {'name': 'GuaranteeOrDonation', 'type': 'string'},\n {'name': 'ID', 'type': 'integer'},\n {'name': 'IsControl', 'type': 'boolean'},\n {'name': 'IsUpdate', 'type': 'boolean'},\n {'name': 'Party', 'type': 'string'},\n {'name': 'PublisherTypeID', 'type': 'integer'},\n {'name': 'State', 'type': 'integer'},\n {'name': 'SumInCurrency', 'type': 'string'},\n {'name': 'URL', 'type': 'string'},\n ]\n }\n}\n\nspew(dp, process_resources(res_iter))","sub_path":"budgetkey_data_pipelines/pipelines/donations/get_transactions.py","file_name":"get_transactions.py","file_ext":"py","file_size_in_byte":3458,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"524644345","text":"'''\nThis script serves to call an API request on the Demo on port 8099 \n'''\n\nimport requests\nimport json\n\n# The target URL where we send to request to\nurl = 'http://localhost:8081/tokenize'\n#url = 'http://dickens.seas.upenn.edu:4049/tokenize'\n\n# The parameters we wish to send\njson_in = {\n 'text' : 'Barack Obama is an American politician and attorney who served as the 44th president of the United States from 2009 to 2017.'\n }\n\n# Set the headers for the request\nheaders = {'content-type': 'application/json'}\n\n# Post the request\njson_out = requests.post(url, data=json.dumps(json_in), headers=headers)\n\n# Retrieve the JSON of the Output\nres = json_out.json()\n\n# Print the response text (the content of the requested file):\nprint(json.dumps(res))","sub_path":"a_simple_single_service/backend/api_post_request_example.py","file_name":"api_post_request_example.py","file_ext":"py","file_size_in_byte":761,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"331134454","text":"\"\"\"\nModule file to handle both reading in input files:\n1.) GRIB2 format\n2.) NetCDF format\nAlso, creating output files.\n\"\"\"\nfrom netCDF4 import Dataset\nfrom core import errMod\nimport numpy as np\nimport os\nimport subprocess\nimport gzip\nimport shutil\n\nclass OutputObj:\n \"\"\"\n Abstract class to hold local \"slabs\" of final output\n grids.\n \"\"\"\n def __init__(self,GeoMetaWrfHydro):\n self.output_local = None\n self.outPath = None\n self.outDate = None\n self.out_ndv = -9999\n\n # Create local \"slabs\" to hold final output grids. These\n # will be collected during the output routine below.\n self.output_local = np.empty([8,GeoMetaWrfHydro.ny_local,GeoMetaWrfHydro.nx_local])\n #self.output_local[:,:,:] = self.out_ndv\n\n def output_final_ldasin(self,ConfigOptions,geoMetaWrfHydro,MpiConfig):\n \"\"\"\n Output routine to produce final LDASIN files for the WRF-Hydro\n modeling system. This function is assuming all regridding,\n interpolation, downscaling, and bias correction has occurred\n on the necessary input forcings to generate a final set of\n outputs on the output grid. Since this program is ran in parallel,\n all work is done on local \"slabs\" of data for each processor to\n make the code more efficient. On this end, this function will\n collect the \"slabs\" into final output grids that go into the\n output files. In addition, detailed geospatial metadata is translated\n from the input geogrid file, to the final output files.\n :param ConfiguOptions:\n :param geoMetaWrfHydro:\n :param MpiConfig:\n :return:\n \"\"\"\n output_variable_attribute_dict = {\n 'U2D': [0,'m s-1','x_wind','10-m U-component of wind','time: point'],\n 'V2D': [1,'m s-1','y_wind','10-m V-component of wind','time: point'],\n 'LWDOWN': [2,'W m-2','surface downward longwave_flux','Surface downward long-wave radiation flux','time: point'],\n 'RAINRATE': [3,'mm s^-1','precipitation_flux','Surface Precipitation Rate','time: mean'],\n 'T2D': [4,'K','air temperature','2-m Air Temperature','time: point'],\n 'Q2D': [5,'kg kg-1','surface_specific_humidity','2-m Specific Humidity','time: point'],\n 'PSFC': [6,'Pa','air_pressure','Surface Pressure','time: point'],\n 'SWDOWN': [7,'W m-2','surface_downward_shortwave_flux','Surface downward short-wave radiation flux','time point']\n }\n\n # Compose the ESMF remapped string attribute based on the regridding option chosen by the user.\n # We will default to the regridding method chosen for the first input forcing selected.\n if ConfigOptions.regrid_opt[0] == 1:\n regrid_att = \"remapped via ESMF regrid_with_weights: Bilinear\"\n elif ConfigOptions.regrid_opt[0] == 2:\n regrid_att = \"remapped via ESMF regrid_with_weights: Nearest Neighbor\"\n elif ConfigOptions.regrid_opt[0] == 3:\n regrid_att = \"remapped via ESMF regrid_with_weights: Conservative Bilinear\"\n\n # Ensure all processors are synced up before outputting.\n MpiConfig.comm.barrier()\n\n if MpiConfig.rank == 0:\n while (True):\n # Only output on the master processor.\n try:\n idOut = Dataset(self.outPath,'w')\n except:\n ConfigOptions.errMsg = \"Unable to create output file: \" + self.outPath\n errMod.log_critical(ConfigOptions, MpiConfig)\n break\n\n # Create dimensions.\n try:\n idOut.createDimension(\"time\",1)\n except:\n ConfigOptions.errMsg = \"Unable to create time dimension in: \" + self.outPath\n errMod.log_critical(ConfigOptions, MpiConfig)\n break\n try:\n idOut.createDimension(\"y\",geoMetaWrfHydro.ny_global)\n except:\n ConfigOptions.errMsg = \"Unable to create y dimension in: \" + self.outPath\n errMod.log_critical(ConfigOptions, MpiConfig)\n break\n try:\n idOut.createDimension(\"x\",geoMetaWrfHydro.nx_global)\n except:\n ConfigOptions.errMsg = \"Unable to create x dimension in: \" + self.outPath\n errMod.log_critical(ConfigOptions, MpiConfig)\n break\n try:\n idOut.createDimension(\"reference_time\",1)\n except:\n ConfigOptions.errMsg = \"Unable to create reference_time dimension in: \" + self.outPath\n errMod.log_critical(ConfigOptions, MpiConfig)\n break\n\n # Set global attributes\n try:\n idOut.model_output_valid_time = self.outDate.strftime(\"%Y-%m-%d_%H:%M:00\")\n except:\n ConfigOptions.errMsg = \"Unable to set the model_output_valid_time attribute in :\" + self.outPath\n errMod.log_critical(ConfigOptions, MpiConfig)\n break\n try:\n idOut.model_initialization_time = ConfigOptions.current_fcst_cycle.strftime(\"%Y-%m-%d_%H:%M:00\")\n except:\n ConfigOptions.errMsg = \"Unable to set the model_initialization_time global \" \\\n \"attribute in: \" + self.outPath\n errMod.log_critical(ConfigOptions, MpiConfig)\n break\n\n # Create variables.\n try:\n idOut.createVariable('time','i4',('time'))\n except:\n ConfigOptions.errMsg = \"Unable to create time variable in: \" + self.outPath\n errMod.log_critical(ConfigOptions, MpiConfig)\n break\n try:\n idOut.createVariable('reference_time','i4',('reference_time'))\n except:\n ConfigOptions.errMsg = \"Unable to create reference_time variable in: \" + self.outPath\n errMod.log_critical(ConfigOptions, MpiConfig)\n break\n\n # Create geospatial metadata coordinate variables if data was read in from an optional\n # spatial metadata file.\n if ConfigOptions.spatial_meta is not None:\n # Create coordinate variables and populate with attributes read in.\n try:\n idOut.createVariable('x','f8',('x'))\n except:\n ConfigOptions.errMsg = \"Unable to create x variable in: \" + self.outPath\n errMod.log_critical(ConfigOptions, MpiConfig)\n break\n try:\n idOut.variables['x'].setncatts(geoMetaWrfHydro.x_coord_atts)\n except:\n ConfigOptions.errMsg = \"Unable to establish x coordinate attributes in: \" + self.outPath\n errMod.log_critical(ConfigOptions, MpiConfig)\n break\n try:\n idOut.variables['x'][:] = geoMetaWrfHydro.x_coords\n except:\n ConfigOptions.errMsg = \"Unable to place x coordinate values into output variable \" \\\n \"for output file: \" + self.outPath\n errMod.log_critical(ConfigOptions, MpiConfig)\n break\n\n try:\n idOut.createVariable('y','f8',('y'))\n except:\n ConfigOptions.errMsg = \"Unable to create y variable in: \" + self.outPath\n errMod.log_critical(ConfigOptions, MpiConfig)\n break\n try:\n idOut.variables['y'].setncatts(geoMetaWrfHydro.y_coord_atts)\n except:\n ConfigOptions.errMsg = \"Unable to establish y coordinate attributes in: \" + self.outPath\n errMod.log_critical(ConfigOptions, MpiConfig)\n break\n try:\n idOut.variables['y'][:] = geoMetaWrfHydro.y_coords\n except:\n ConfigOptions.errMsg = \"Unable to place y coordinate values into output variable \" \\\n \"for output file: \" + self.outPath\n errMod.log_critical(ConfigOptions, MpiConfig)\n break\n\n try:\n idOut.createVariable('crs','S1')\n except:\n ConfigOptions.errMsg = \"Unable to create crs in: \" + self.outPath\n errMod.log_critical(ConfigOptions, MpiConfig)\n break\n try:\n idOut.variables['crs'].setncatts(geoMetaWrfHydro.crs_atts)\n except:\n ConfigOptions.errMsg = \"Unable to establish crs attributes in: \" + self.outPath\n errMod.log_critical(ConfigOptions, MpiConfig)\n break\n\n # Loop through and create each variable, along with expected attributes.\n for varTmp in output_variable_attribute_dict:\n try:\n idOut.createVariable(varTmp,'f4',('time','y','x'),fill_value=ConfigOptions.globalNdv)\n except:\n ConfigOptions.errMsg = \"Unable to create \" + varTmp + \" variable in: \" + self.outPath\n errMod.log_critical(ConfigOptions, MpiConfig)\n break\n try:\n idOut.variables[varTmp].cell_methods = output_variable_attribute_dict[varTmp][4]\n except:\n ConfigOptions.errMsg = \"Unable to create cell_methods attribute for: \" + varTmp + \\\n \" in: \" + self.outPath\n errMod.log_critical(ConfigOptions, MpiConfig)\n break\n try:\n idOut.variables[varTmp].remap = regrid_att\n except:\n ConfigOptions.errMsg = \"Unable to create remap attribute for: \" + varTmp + \\\n \" in: \" + self.outPath\n errMod.log_critical(ConfigOptions, MpiConfig)\n break\n # Place geospatial metadata attributes in if we have them.\n if ConfigOptions.spatial_meta is not None:\n try:\n idOut.variables[varTmp].grid_mapping = 'crs'\n except:\n ConfigOptions.errMsg = \"Unable to create grid_mapping attribute for: \" + \\\n varTmp + \" in: \" + self.outPath\n errMod.log_critical(ConfigOptions, MpiConfig)\n break\n if 'esri_pe_string' in geoMetaWrfHydro.crs_atts.keys():\n try:\n idOut.variables[varTmp].esri_pe_string = geoMetaWrfHydro.crs_atts['esri_pe_string']\n except:\n ConfigOptions.errMsg = \"Unable to create esri_pe_string attribute for: \" + \\\n varTmp + \" in: \" + self.outPath\n errMod.log_critical(ConfigOptions, MpiConfig)\n break\n if 'proj4' in geoMetaWrfHydro.spatial_global_atts.keys():\n try:\n idOut.variables[varTmp].proj4 = geoMetaWrfHydro.spatial_global_atts['proj4']\n except:\n ConfigOptions.errMsg = \"Unable to create proj4 attribute for: \" + varTmp + \\\n \" in: \" + self.outPath\n errMod.log_critical(ConfigOptions, MpiConfig)\n break\n\n try:\n idOut.variables[varTmp].units = output_variable_attribute_dict[varTmp][1]\n except:\n ConfigOptions.errMsg = \"Unable to create units attribute for: \" + varTmp + \" in: \" + \\\n self.outPath\n errMod.log_critical(ConfigOptions, MpiConfig)\n break\n try:\n idOut.variables[varTmp].standard_name = output_variable_attribute_dict[varTmp][2]\n except:\n ConfigOptions.errMsg = \"Unable to create standard_name attribute for: \" + varTmp + \\\n \" in: \" + self.outPath\n errMod.log_critical(ConfigOptions, MpiConfig)\n break\n try:\n idOut.variables[varTmp].long_name = output_variable_attribute_dict[varTmp][3]\n except:\n ConfigOptions.errMsg = \"Unable to create long_name attribute for: \" + varTmp + \\\n \" in: \" + self.outPath\n errMod.log_critical(ConfigOptions, MpiConfig)\n break\n break\n\n errMod.check_program_status(ConfigOptions, MpiConfig)\n\n # Now loop through each variable, collect the data (call on each processor), assemble into the final\n # output grid, and place into the output file (if on processor 0).\n for varTmp in output_variable_attribute_dict:\n # Collect data from the various processors, and place into the output file.\n try:\n final = MpiConfig.comm.gather(self.output_local[output_variable_attribute_dict[varTmp][0],:,:],root=0)\n except:\n ConfigOptions.errMsg = \"Unable to gather final grids for: \" + varTmp\n errMod.log_critical(ConfigOptions, MpiConfig)\n continue\n MpiConfig.comm.barrier()\n if MpiConfig.rank == 0:\n while (True):\n try:\n dataOutTmp = np.concatenate([final[i] for i in range(MpiConfig.size)],axis=0)\n except:\n ConfigOptions.errMsg = \"Unable to finalize collection of output grids for: \" + varTmp\n errMod.log_critical(ConfigOptions, MpiConfig)\n break\n try:\n idOut.variables[varTmp][0,:,:] = dataOutTmp\n except:\n ConfigOptions.errMsg = \"Unable to place final output grid for: \" + varTmp\n errMod.log_critical(ConfigOptions, MpiConfig)\n break\n # Reset temporary data objects to keep memory usage down.\n dataOutTmp = None\n break\n\n # Reset temporary data objects to keep memory usage down.\n final = None\n\n errMod.check_program_status(ConfigOptions, MpiConfig)\n\n if MpiConfig.rank == 0:\n while (True):\n # Close the NetCDF file\n try:\n idOut.close()\n except:\n ConfigOptions.errMsg = \"Unable to close output file: \" + self.outPath\n errMod.log_critical(ConfigOptions, MpiConfig)\n break\n break\n\n errMod.check_program_status(ConfigOptions, MpiConfig)\n\ndef open_grib2(GribFileIn,NetCdfFileOut,Wgrib2Cmd,ConfigOptions,MpiConfig,\n inputVar):\n \"\"\"\n Generic function to convert a GRIB2 file into a NetCDF file. Function\n will also open the NetCDF file, and ensure all necessary inputs are\n in file.\n :param GribFileIn:\n :param NetCdfFileOut:\n :param ConfigOptions:\n :return:\n \"\"\"\n # Run wgrib2 command to convert GRIB2 file to NetCDF.\n if MpiConfig.rank == 0:\n while (True):\n # Check to see if output file already exists. If so, delete it and\n # override.\n ConfigOptions.statusMsg = \"Reading in GRIB2 file: \" + GribFileIn\n errMod.log_msg(ConfigOptions, MpiConfig)\n if os.path.isfile(NetCdfFileOut):\n ConfigOptions.statusMsg = \"Overriding temporary NetCDF file: \" + NetCdfFileOut\n errMod.log_warning(ConfigOptions,MpiConfig)\n try:\n subprocess.run([Wgrib2Cmd],shell=True)\n except:\n ConfigOptions.errMsg = \"Unable to convert: \" + GribFileIn + \" to \" + \\\n NetCdfFileOut\n errMod.log_critical(ConfigOptions,MpiConfig)\n idTmp = None\n break\n # Ensure file exists.\n if not os.path.isfile(NetCdfFileOut):\n ConfigOptions.errMsg = \"Expected NetCDF file: \" + NetCdfFileOut + \\\n \" not found. It's possible the GRIB2 variable was not found.\"\n errMod.log_critical(ConfigOptions,MpiConfig)\n idTmp = None\n break\n\n # Open the NetCDF file.\n try:\n idTmp = Dataset(NetCdfFileOut,'r')\n except:\n ConfigOptions.errMsg = \"Unable to open input NetCDF file: \" + \\\n NetCdfFileOut\n errMod.log_critical(ConfigOptions,MpiConfig)\n idTmp = None\n break\n\n if idTmp is not None:\n # Check for expected lat/lon variables.\n if 'latitude' not in idTmp.variables.keys():\n ConfigOptions.errMsg = \"Unable to locate latitude from: \" + \\\n GribFileIn\n errMod.log_critical(ConfigOptions,MpiConfig)\n idTmp = None\n break\n if idTmp is not None:\n if 'longitude' not in idTmp.variables.keys():\n ConfigOptions.errMsg = \"Unable t locate longitude from: \" + \\\n GribFileIn\n errMod.log_critical(ConfigOptions,MpiConfig)\n idTmp = None\n break\n\n if idTmp is not None:\n # Loop through all the expected variables.\n if inputVar not in idTmp.variables.keys():\n ConfigOptions.errMsg = \"Unable to locate expected variable: \" + \\\n inputVar + \" in: \" + NetCdfFileOut\n errMod.log_critical(ConfigOptions,MpiConfig)\n idTmp = None\n break\n\n break\n else:\n idTmp = None\n\n # Return the NetCDF file handle back to the user.\n return idTmp\n\ndef open_netcdf_forcing(NetCdfFileIn,ConfigOptions,MpiConfig):\n \"\"\"\n Generic function to convert a NetCDF forcing file given a list of input forcing\n variables.\n :param GribFileIn:\n :param NetCdfFileOut:\n :param ConfigOptions:\n :return:\n \"\"\"\n # Open the NetCDF file on the master processor and read in data.\n if MpiConfig.rank == 0:\n while (True):\n # Ensure file exists.\n if not os.path.isfile(NetCdfFileIn):\n ConfigOptions.errMsg = \"Expected NetCDF file: \" + NetCdfFileIn + \\\n \" not found.\"\n errMod.log_critical(ConfigOptions,MpiConfig)\n idTmp = None\n break\n\n # Open the NetCDF file.\n try:\n idTmp = Dataset(NetCdfFileIn, 'r')\n except:\n ConfigOptions.errMsg = \"Unable to open input NetCDF file: \" + \\\n NetCdfFileIn\n errMod.log_critical(ConfigOptions,MpiConfig)\n idTmp = None\n break\n\n if idTmp is not None:\n # Check for expected lat/lon variables.\n if 'latitude' not in idTmp.variables.keys():\n ConfigOptions.errMsg = \"Unable to locate latitude from: \" + \\\n NetCdfFileIn\n errMod.log_critical(ConfigOptions,MpiConfig)\n idTmp = None\n break\n if idTmp is not None:\n if 'longitude' not in idTmp.variables.keys():\n ConfigOptions.errMsg = \"Unable t locate longitude from: \" + \\\n NetCdfFileIn\n errMod.log_critical(ConfigOptions,MpiConfig)\n idTmp = None\n break\n break\n else:\n idTmp = None\n errMod.check_program_status(ConfigOptions, MpiConfig)\n\n # Return the NetCDF file handle back to the user.\n return idTmp\n\ndef unzip_file(GzFileIn,FileOut,ConfigOptions,MpiConfig):\n \"\"\"\n Generic I/O function to unzip a .gz file to a new location.\n :param GzFileIn:\n :param FileOut:\n :param ConfigOptions:\n :param MpiConfig:\n :return:\n \"\"\"\n if MpiConfig.rank == 0:\n # Unzip the file in place.\n try:\n with gzip.open(GzFileIn, 'rb') as fTmpGz:\n with open(FileOut, 'wb') as fTmp:\n shutil.copyfileobj(fTmpGz, fTmp)\n except:\n ConfigOptions.errMsg = \"Unable to unzip: \" + GzFileIn\n raise Exception()\n\n if not os.path.isfile(FileOut):\n ConfigOptions.errMsg = \"Unable to locate expected unzipped file: \" + \\\n FileOut\n raise Exception()\n else:\n return","sub_path":"core/ioMod.py","file_name":"ioMod.py","file_ext":"py","file_size_in_byte":22067,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"590053133","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sun Apr 15 13:56:18 2018\r\n\r\n@author: Rathk\r\n\"\"\"\r\n\r\n# Jose's Recurrent Neural Network\r\n#Pre-process the data\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport pandas as pd\r\nfrom sklearn.preprocessing import MinMaxScaler\r\nfrom keras.models import Sequential, load_model\r\nfrom keras.layers import Dense\r\nfrom keras.layers import CuDNNLSTM\r\nfrom keras.layers import Dropout\r\nfrom keras.optimizers import Adam\r\nfrom sklearn.model_selection import KFold\r\n\r\n\r\n#The amount of time-steps the LSTM will look back at\r\ntime_step = 10\r\n\r\n\r\n#Import the training set\r\ntrain_dataset = pd.read_csv(\"Training_Data - Copy2.csv\")\r\n#Obtain the test Data\r\ntest_dataset = pd.read_csv(\"Test_Data - Copy3.csv\")\r\n#Merge both test and train to obtain initial values\r\ndataset_total = pd.concat((train_dataset, test_dataset), axis = 0)\r\n\r\n\r\n#Reshappe the inpputt so it fits the neural network\r\nx = []\r\nfor i in range(time_step-1, int(dataset_total.size/dataset_total.shape[1])):\r\n x.append(dataset_total.as_matrix()[i-time_step+1 : i+1 , 2:])\r\nx = np.array(x)\r\n\r\n\r\n#Extract the output of the neural network\r\ny = dataset_total.iloc[time_step-1:,0:2]\r\ny = y.as_matrix()\r\n#Feature Scaling\r\nsc = MinMaxScaler(feature_range = (-1,1))\r\ny = sc.fit_transform(y)\r\n\r\n\r\n\r\n#K-Fold\r\nseed = 7\r\nnp.random.seed(seed)\r\nkfold = KFold(n_splits=10, shuffle=True, random_state=seed)\r\ncvscores = []\r\nfor train, test in kfold.split(x, y):\r\n#K-fold end\r\n # Part 2 - Building the RNN\r\n ################################################################################\r\n units = 50\r\n dropout = 0.3\r\n #Build rnn\r\n regresor = Sequential()\r\n \r\n #First Layer -- LSTM layer with dropout regularization -- dunno what that means\r\n #Note that this is the only layer with input_shape\r\n regresor.add(CuDNNLSTM(units = units, return_sequences = True, \r\n input_shape=(x.shape[1], x.shape[2])))\r\n regresor.add(Dropout(dropout))\r\n \r\n \r\n #Second layers with dropout regularization\r\n #regresor.add(CuDNNLSTM(units = units, return_sequences = True))\r\n #regresor.add(Dropout(dropout))\r\n \r\n #Third layers with dropout regularization\r\n #regresor.add(CuDNNLSTM(units = units , return_sequences = True)) \r\n #regresor.add(Dropout(dropout))\r\n \r\n \r\n #Fourth layers with dropout regularization\r\n regresor.add(CuDNNLSTM(units = units))\r\n regresor.add(Dropout(dropout))\r\n \r\n #Output Layer\r\n regresor.add(Dense(units = 2, activation = 'tanh'))\r\n \r\n #Compile this network\r\n regresor.compile(optimizer = 'adam', loss='logcosh', metrics=['accuracy'])\r\n #Fit the data\r\n regresor.fit(x[train], y[train], epochs=100, batch_size = 32, verbose=0)#, shuffle=False) \r\n #Predict Values\r\n scores = regresor.evaluate(x=x[test], y=y[test], verbose = 0)\r\n print(\"%s: %.2f%%\" % (regresor.metrics_names[1], scores[1]*100))\r\n #regresor.save('LSTM-51.28%accuracy.h5py')\r\n cvscores.append(scores[1] * 100)\r\nprint(\"%.2f%% (+/- %.2f%%)\" % (np.mean(cvscores), np.std(cvscores)))\r\n\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"Deep Learning/src/LSTM-K-Fold validation.py","file_name":"LSTM-K-Fold validation.py","file_ext":"py","file_size_in_byte":3077,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"61395856","text":"# coding=utf-8\n# --------------------------------------------------------------------------\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See License.txt in the project root for\n# license information.\n#\n# Code generated by Microsoft (R) AutoRest Code Generator.\n# Changes may cause incorrect behavior and will be lost if the code is\n# regenerated.\n# --------------------------------------------------------------------------\n\nfrom msrest.serialization import Model\n\n\nclass JobRecurrenceSchedule(Model):\n \"\"\"JobRecurrenceSchedule.\n\n :param week_days: Gets or sets the days of the week that the job should\n execute on.\n :type week_days: list of str or :class:`DayOfWeek\n <azure.mgmt.scheduler.models.DayOfWeek>`\n :param hours: Gets or sets the hours of the day that the job should\n execute at.\n :type hours: list of int\n :param minutes: Gets or sets the minutes of the hour that the job should\n execute at.\n :type minutes: list of int\n :param month_days: Gets or sets the days of the month that the job should\n execute on. Must be between 1 and 31.\n :type month_days: list of int\n :param monthly_occurrences: Gets or sets the occurrences of days within a\n month.\n :type monthly_occurrences: list of\n :class:`JobRecurrenceScheduleMonthlyOccurrence\n <azure.mgmt.scheduler.models.JobRecurrenceScheduleMonthlyOccurrence>`\n \"\"\"\n\n _attribute_map = {\n 'week_days': {'key': 'weekDays', 'type': '[DayOfWeek]'},\n 'hours': {'key': 'hours', 'type': '[int]'},\n 'minutes': {'key': 'minutes', 'type': '[int]'},\n 'month_days': {'key': 'monthDays', 'type': '[int]'},\n 'monthly_occurrences': {'key': 'monthlyOccurrences', 'type': '[JobRecurrenceScheduleMonthlyOccurrence]'},\n }\n\n def __init__(self, week_days=None, hours=None, minutes=None, month_days=None, monthly_occurrences=None):\n self.week_days = week_days\n self.hours = hours\n self.minutes = minutes\n self.month_days = month_days\n self.monthly_occurrences = monthly_occurrences\n","sub_path":"azure-mgmt-scheduler/azure/mgmt/scheduler/models/job_recurrence_schedule.py","file_name":"job_recurrence_schedule.py","file_ext":"py","file_size_in_byte":2110,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"165581251","text":"import click\nimport csv\nimport gzip\nimport os\n\nfrom onecodex.exceptions import OneCodexException, ValidationError\nfrom onecodex.lib.inline_validator import FASTXTranslator\nfrom onecodex.utils import download_file_helper, get_download_dest, pretty_errors\n\n\ndef with_progress_bar(length, ix, *args, **kwargs):\n label = kwargs.pop('label', None)\n bar_kwargs = {\n 'length': length\n }\n if label:\n bar_kwargs['label'] = label\n with click.progressbar(**bar_kwargs) as bar:\n return ix(cb=bar.update, *args, **kwargs)\n\n\ndef filter_rows_by_taxid(results, tax_ids, cb=None):\n filtered_rows = []\n for i, row in enumerate(results):\n if row['Tax ID'] in tax_ids:\n filtered_rows.append(i)\n if i % 1000 == 0 and cb:\n cb(1000)\n return filtered_rows\n\n\ndef get_record_count(fp):\n counter = 0\n for _ in fp:\n counter += 1\n return counter\n\n\ndef get_filtered_filename(filepath):\n filename = os.path.split(filepath)[-1]\n prefix, ext = os.path.splitext(filename.rstrip('.gz')\n .rstrip('gzip'))\n return '{}.filtered{}'.format(prefix, ext), ext\n\n\ndef write_fastx_record(record, handler):\n if len(record) == 2:\n record_str = '>{}\\n{}'\n elif len(record) == 4:\n record_str = '@{}\\n{}\\n{}\\n{}'\n else:\n raise OneCodexException('Unknown FASTX record format', record)\n handler.write(record_str.format(*record))\n\n\n@click.command(help='Filter a FASTX file based on the taxonomic results from a CLASSIFICATION_ID')\n@click.argument('classification_id')\n@click.argument('fastx', type=click.Path())\n@click.option('-t', '--tax-id', required=True, multiple=True,\n help='Filter to reads mapping to tax IDs. May be passed multiple times.')\n@click.option('-r', '--reverse', type=click.Path(), help='The reverse (R2) '\n 'read file, optionally')\n@click.option('--split-pairs/--keep-pairs', default=False, help='Keep only '\n 'the read pair member that matches the list of tax ID\\'s')\n@click.option('-o', '--out', default='.', type=click.Path(), help='Where '\n 'to put the filtered outputs')\n@click.pass_context\n@pretty_errors\ndef cli(ctx, classification_id, fastx, reverse, tax_id, split_pairs, out):\n tax_ids = tax_id # rename\n if not len(tax_ids):\n raise OneCodexException('You must supply at least one tax ID')\n\n classification = ctx.obj['API'].Classifications.get(classification_id)\n if classification is None:\n raise ValidationError('Classification {} not found.'.format(classification_id))\n\n tsv_url = classification.readlevel()['url']\n readlevel_path = get_download_dest('./', tsv_url)\n if not os.path.exists(readlevel_path):\n download_file_helper(tsv_url, './')\n else:\n click.echo('Using cached read-level results: {}'\n .format(readlevel_path), err=True)\n\n filtered_rows = []\n tsv_row_count = 0\n with gzip.open(readlevel_path, 'rt') as tsv:\n try:\n tsv_row_count = get_record_count(tsv) - 1 # discount header line\n except EOFError:\n click.echo('\\nWe encountered an error while processing the read '\n 'level results. Please delete {} and try again.'\n .format(readlevel_path), err=True)\n raise\n else:\n tsv.seek(0)\n reader = csv.DictReader(tsv, delimiter='\\t')\n click.echo('Selecting results matching tax ID(s): {}'\n .format(', '.join(tax_ids)), err=True)\n filtered_rows = with_progress_bar(\n tsv_row_count,\n filter_rows_by_taxid,\n reader,\n tax_ids\n )\n\n filtered_filename = get_filtered_filename(fastx)[0]\n filtered_filename = os.path.join(out, filtered_filename)\n if reverse:\n rev_filtered_filename = get_filtered_filename(reverse)[0]\n rev_filtered_filename = os.path.join(out, rev_filtered_filename)\n\n fastx_record_count = 0\n with open(fastx, 'rb') as fastx_file:\n try:\n fastx_record_count = get_record_count(\n FASTXTranslator(fastx_file, validate=False))\n except ValidationError as e:\n raise OneCodexException(e.message)\n\n if reverse:\n fastx_record_count = fastx_record_count * 2\n\n if tsv_row_count != fastx_record_count:\n os.remove(readlevel_path)\n raise OneCodexException('The supplied file has a different number of '\n 'records than the requested Classification')\n\n save_msg = 'Saving filtered reads: {}'.format(filtered_filename)\n if reverse:\n save_msg += ' and {}'.format(rev_filtered_filename)\n click.echo(save_msg, err=True)\n\n counter = 0\n if reverse:\n with open(fastx, 'rb') as fastx_file, \\\n open(reverse, 'rb') as reverse_file, \\\n open(filtered_filename, 'wb') as out_file, \\\n open(rev_filtered_filename, 'wb') as rev_out_file:\n if split_pairs:\n for fwd, rev in FASTXTranslator(fastx_file, reverse_file,\n validate=False):\n if counter in filtered_rows:\n out_file.write(fwd)\n if (counter + 1) in filtered_rows:\n rev_out_file.write(rev)\n counter += 2\n else:\n for fwd, rev in FASTXTranslator(fastx_file, reverse_file,\n validate=False):\n if counter in filtered_rows or \\\n (counter + 1) in filtered_rows:\n out_file.write(fwd)\n rev_out_file.write(rev)\n counter += 2\n else:\n with open(fastx, 'rb') as fastx_file, \\\n open(filtered_filename, 'wb') as out_file:\n for seq in FASTXTranslator(fastx_file, validate=False):\n if counter in filtered_rows:\n out_file.write(seq)\n counter += 1\n","sub_path":"onecodex/scripts/filter_reads.py","file_name":"filter_reads.py","file_ext":"py","file_size_in_byte":6143,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"379636231","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n# Authors: Nosov Mikhail, viver_117, Konstantin Guk\n# Consultant: grishnan\n# E-mails: mikhail1920@mail.com, viver12366@gmail.com, 1996artes@mail.ru, grishnan@gmail.com\n# License: GNU GPL v3.0\n# Description by Eng: Program «Collection picture»\n# Description by Rus: Программа «Собери картинку»\n\nfrom classes import *\n\npygame.init()\n\nscreen = pygame.display.set_mode((SIZE_SCREEN, SIZE_SCREEN))\npygame.display.set_caption(\"Collection picture\")\n\nfield = Field()\n\nwhile True:\n gotoGame = False\n \n ''' обработчик событий '''\n for event in pygame.event.get():\n if event.type == pygame.QUIT: pygame.quit(); sys.exit()\n elif event.type == pygame.MOUSEBUTTONDOWN:\n gotoGame = True\n \n if gotoGame: break\n \n screen.fill(WHITE)\n field.drawField(screen)\n field.assignment(screen)\n (gx, gy) = field.fromLocalToGlobal(SIZE_FIELD - 1, SIZE_FIELD - 1)\n screen.blit(field.pics[-1], (gx, gy, SIZE_CHIP, SIZE_CHIP))\n\n pygame.display.update()\n\nfield.randomMix()\n\nwhile True:\n \n ''' обработчик событий '''\n for event in pygame.event.get():\n if event.type == pygame.QUIT: pygame.quit(); sys.exit()\n elif event.type == pygame.MOUSEBUTTONDOWN:\n mousex, mousey = event.pos\n field.makeMove(mousex, mousey)\n print(field.matrix)\n \n ''' отрисовка игрового поля '''\n screen.fill(WHITE)\n field.drawField(screen)\n field.assignment(screen)\n\n pygame.display.update()\n","sub_path":"collpic_2/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1519,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"558195771","text":"\"\"\"\nDefault set of serializer/deserializers for python primitives (dataclass, collections, numeric primitives etc.)\n\nThese are the defaults used in JsonMapper and BsonMapper.\n\"\"\"\n\nfrom dataclasses import dataclass\nfrom datetime import datetime, timedelta\nfrom pathlib import Path\nfrom pathlib import PurePath\n\nfrom toolz import curry\n\nfrom dataclasses_serialization.mapper.deserialize_helpers import timedelta_deserialize, dict_to_dataclass, \\\n collection_deserialization, number_to_float, datetime_utc_from_inspected_type\nfrom dataclasses_serialization.mapper.serialize_helpers import keep_not_none_value, timedelta_to_milliseconds, \\\n datetime_to_milliseconds, float_serializer\nfrom dataclasses_serialization.serializer_base import noop_serialization, \\\n dict_serialization, noop_deserialization, dict_deserialization\n\n__all__ = [\n 'default_serializers',\n 'default_deserializers'\n]\n\n\n@curry\ndef default_serializers(mapper, dict_post_processor=keep_not_none_value) -> dict:\n \"\"\"\n Set of default serializers useful as a base for json/bson\n \"\"\"\n return {\n dataclass: lambda value: dict_serialization(value.__dict__,\n key_serialization_func=mapper._key_serializer,\n value_serialization_func=mapper.serialize,\n post_processor=dict_post_processor),\n dict: dict_serialization(\n key_serialization_func=mapper.serialize,\n value_serialization_func=mapper.serialize,\n post_processor=dict_post_processor),\n datetime: datetime_to_milliseconds,\n (tuple, set, list, frozenset): lambda lst: list(map(mapper.serialize, lst)),\n str: noop_serialization,\n int: noop_serialization,\n float: float_serializer,\n bool: noop_serialization,\n timedelta: timedelta_to_milliseconds,\n PurePath: lambda value: str(value),\n type(None): noop_serialization,\n }\n\n\ndef default_deserializers(mapper) -> dict:\n \"\"\"\n Set of default deserializers useful as a base for json/bson\n \"\"\"\n return {\n timedelta: timedelta_deserialize,\n datetime: datetime_utc_from_inspected_type,\n dataclass: dict_to_dataclass(deserialization_func=mapper.deserialize,\n key_deserialization_func=mapper._key_deserializer,\n serializer=mapper),\n dict: dict_deserialization(key_deserialization_func=mapper.deserialize,\n value_deserialization_func=mapper.deserialize),\n list: collection_deserialization(target_collection=list,\n deserialization_func=mapper.deserialize),\n set: collection_deserialization(target_collection=set,\n deserialization_func=mapper.deserialize),\n frozenset: collection_deserialization(target_collection=frozenset,\n deserialization_func=mapper.deserialize),\n tuple: collection_deserialization(target_collection=tuple,\n deserialization_func=mapper.deserialize),\n str: noop_deserialization,\n float: number_to_float,\n bool: noop_deserialization,\n Path: lambda cls, value: Path(value),\n type(None): noop_deserialization\n }\n\n\ndef build_init_arguments(serialization_functions,\n deserialization_functions,\n key_serializer,\n key_deserializer,\n default_marker=None):\n init_kwargs = dict(\n key_serializer=key_serializer,\n key_deserializer=key_deserializer\n )\n\n if serialization_functions is not default_marker:\n init_kwargs['serialization_functions'] = serialization_functions\n\n if deserialization_functions is not default_marker:\n init_kwargs['deserialization_functions'] = deserialization_functions\n\n return init_kwargs\n","sub_path":"dataclasses_serialization/mapper/defaults.py","file_name":"defaults.py","file_ext":"py","file_size_in_byte":4074,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"400337071","text":"import json\n\ndata = {\n \"firstName\": \"Anatoly\",\n \"patronim\": \"Vladimirovich\",\n \"lastName\": \"Nechay-Gumen\",\n \"address\": {\n \"street\": \"Mechnikova 154A\",\n \"city\": \"Rostov-on-Don\"\n },\n \"phone\": [\n \"89885312115\",\n \"89081728874\"\n ]\n}\n\nwith open('result.json', 'w') as outfile:\n json.dump(data, outfile)\n\nwith open('result.json', 'r') as infile:\n data2 = json.load(infile)\nprint(data2)\n\nprint(data2[\"address\"][\"city\"])\n","sub_path":"Laba3.py","file_name":"Laba3.py","file_ext":"py","file_size_in_byte":466,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"127374571","text":"\nimport numpy as np\nfrom scipy.interpolate import interp1d\n\nfrom .. import constants as c\nfrom .. import utils\nfrom . import scatmodels\n\nfrom ..composition import cmindex\nfrom .. import sizedist\n\n__all__ = ['ScatModel','DiffScat','SigmaExt','SigmaScat','KappaExt','KappaScat']\n\n\n\n\n\ndef angles( thmin=5., thmax=100., dth=5. ):\n '''\n |\n |Params:\n | thmin=5.0, thmax=100.0, dth=5.0 in [arcsec]\n |\n |Return : np.array - Distribution of angles (theta) [arcsec]\n '''\n return np.arange( thmin, thmax+dth, dth )\n\n\n\n\n\n\n#-------------- Tie scattering mechanism to an index of refraction ------------------#\n\nclass ScatModel(object):\n \"\"\"\n | -- Properties:\n | scat_model : scattering model object - RGscat(), Mie()\n | cmindex_model : cmindex object - CmDrude(), CmGraphite(), CmSilicate()\n | scat_model : string - 'RGscat', 'Mie'\n | cmtype : 'Drude', 'Silicate', 'Graphite'\n \"\"\"\n def __init__( self, scat_model=scatmodels.RGscat(), cmindex_model=cmindex.CmDrude() ):\n self.scat_model = scat_model\n self.cmindex_model = cmindex_model\n self.scat_type = scat_model.stype\n self.cmindex_type = cmindex_model.cmtype\n # cmindex_type choices : 'Drude' (requires rho term only)\n # 'Graphite' (Carbonaceous grains)\n # 'Silicate' (Silicate)\n # --- Graphite and Silicate values come from Draine (2003)\n\n\n\ndef create_scat_model( model_name, material_name ):\n '''\n | -- Params:\n | model_name : string : 'RG' or 'Mie'\n | material_name : string : 'Drude', 'Silicate', 'Graphite', 'SmallGraphite'\n |\n | -- Return:\n | ScatModel object\n '''\n\n if model_name == 'RG':\n scat_mod = scatmodels.RGscat()\n elif model_name == 'Mie':\n scat_mod = scatmodels.Mie()\n else:\n print('Error: Model name not found')\n return\n\n if material_name == 'Drude':\n cmi_mod = cmindex.CmDrude()\n \n elif material_name == 'Silicate':\n cmi_mod = cmindex.CmSilicate()\n \n elif material_name == 'Graphite':\n cmi_mod = cmindex.CmGraphite()\n \n elif material_name == 'SmallGraphite': # Small Graphite ~0.01 micron\n cmi_mod = cmindex.CmGraphite( size='small' )\n \n else:\n print('Error: Complex Index name not found')\n return\n\n return ScatModel(scat_model=scat_mod, cmindex_model=cmi_mod)\n\n\n\n\n\n\n\n\n#-------------- Various Types of Scattering Cross-sections -----------------------#\n\nclass DiffScat(object):\n \"\"\"\n | A differential scattering cross-section [cm^2 ster^-1] integrated\n | over dust grain size distribution\n |\n | -- Properties\n | scatm : ScatModel\n | theta : np.array [arcsec]\n | E : scalar or np.array : Note, must match number of theta values if size > 1\n | a : scalar : um\n | dsig : np.array : cm^2 ster^-1\n \"\"\"\n def __init__(self, scatm=ScatModel(), theta=angles(), E=1., a=1.):\n self.scatm = scatm\n self.theta = theta\n self.E = E\n self.a = a\n\n cm = scatm.cmindex_model\n scat = scatm.scat_model\n\n if cm.cmtype == 'Graphite':\n dsig_pe = scat.Diff(theta=theta, a=a, E=E, cm=cmindex.CmGraphite(size=cm.size, orient='perp'))\n dsig_pa = scat.Diff(theta=theta, a=a, E=E, cm=cmindex.CmGraphite(size=cm.size, orient='para'))\n self.dsig = (dsig_pa + 2. * dsig_pe) / 3. # See WD01 paper, Section 2.3\n else:\n self.dsig = scat.Diff(theta=theta, a=a, E=E, cm=cm)\n\n\n\n\n\n\nclass SigmaScat(object):\n \"\"\"\n | Total scattering cross-section [cm^2] integrated over a dust grain\n | size distribution\n |\n | -- Properties:\n | scatm : ScatModel\n | E : scalar or np.array [keV]\n | a : scalar : um\n | qsca : scalar or np.array [unitless scattering efficiency]\n | sigma : scalar or np.array [cm^2]\n \"\"\"\n def __init__(self, scatm=ScatModel(), E=1., a=1.):\n self.scatm = scatm\n self.E = E\n self.a = a\n\n cm = scatm.cmindex_model\n scat = scatm.scat_model\n # print(cm.citation)\n\n cgeo = np.pi * (a*c.MICRON2CM)**2\n\n if cm.cmtype == 'Graphite':\n qsca_pe = scat.Qsca(a=a, E=E, cm=cmindex.CmGraphite(size=cm.size, orient='perp'))\n qsca_pa = scat.Qsca(a=a, E=E, cm=cmindex.CmGraphite(size=cm.size, orient='para'))\n self.qsca = (qsca_pa + 2.*qsca_pe) / 3. # see Weingartner_2001_ApJ_548_296.pdf, Section 2.3\n else:\n self.qsca = scat.Qsca(a=a, E=E, cm=cm)\n\n self.sigma = self.qsca * cgeo # sigma_scat = pi * a**2 * Qscat\n\n\n\n\n\n\nclass SigmaExt(object):\n \"\"\"\n | Total EXTINCTION cross-section [cm^2] integrated over a dust grain\n | size distribution\n |\n | -- Properties\n | scatm : ScatModel\n | E : scalar or np.array [keV]\n | a : scalar : um\n | qext : scalar or np.array [unitless extinction efficiency]\n | sigma : scalar or np.array [cm^2]\n \"\"\"\n def __init__(self, scatm=ScatModel(), E=1., a=1.):\n self.scatm = scatm\n self.E = E\n self.a = a\n\n if scatm.scat_type == 'RGscat':\n print('Rayleigh-Gans cross-section not currently supported for KappaExt')\n self.qext = None\n self.sigma = None\n return\n\n cm = scatm.cmindex_model\n scat = scatm.scat_model\n # print(cm.citation)\n\n cgeo = np.pi * np.power(a*c.micron2cm, 2)\n if cm.cmtype == 'Graphite':\n qext_pe = scat.Qext(a=a, E=E, cm=cmindex.CmGraphite(size=cm.size, orient='perp'))\n qext_pa = scat.Qext(a=a, E=E, cm=cmindex.CmGraphite(size=cm.size, orient='para'))\n self.qext = (qext_pa + 2.0*qext_pe) / 3. # see Weingartner_2001_ApJ_548_296.pdf, Section 2.3 \n else:\n self.qext = scat.Qext(a=a, E=E, cm=cm)\n self.sigma = self.qext * cgeo # Sigma_ext = (pi*a**2) * Qext\n\n\n\n\n\n\n\n\nclass KappaScat(object):\n \"\"\"\n | Opacity to scattering [g^-1 cm^2] integrated over dust grain size distribution.\n |\n | --Properties\n | scatm : ScatModel\n | E : scalar or np.array : keV\n | dist : sizedist.DustSpectrum\n | kappa : scalar or np.array : cm^2 g^-1, typically\n \"\"\"\n def __init__(self, E=1., scatm=ScatModel(), dist=sizedist.MRN77()):\n self.scatm = scatm\n self.E = E\n self.dist = dist\n\n cm = scatm.cmindex_model\n scat = scatm.scat_model\n # print(cm.citation)\n\n cgeo = np.pi * (dist.a * c.MICRON2CM)**2\n\n qsca = np.zeros(shape = (np.size(E), np.size(dist.a)))\n qsca_pe = np.zeros(shape = (np.size(E), np.size(dist.a)))\n qsca_pa = np.zeros(shape = (np.size(E), np.size(dist.a)))\n\n # Test for graphite case\n if cm.cmtype == 'Graphite':\n cmGraphitePerp = cmindex.CmGraphite(size=cm.size, orient='perp')\n cmGraphitePara = cmindex.CmGraphite(size=cm.size, orient='para')\n\n if np.size(dist.a) > 1:\n for i in range(np.size(dist.a)):\n qsca_pe[:,i] = scat.Qsca(E, a=dist.a[i], cm=cmGraphitePerp)\n qsca_pa[:,i] = scat.Qsca(E, a=dist.a[i], cm=cmGraphitePara)\n else:\n qsca_pe = scat.Qsca(E, a=dist.a, cm=cmGraphitePerp)\n qsca_pa = scat.Qsca(E, a=dist.a, cm=cmGraphitePara)\n\n qsca = (qsca_pa + 2. * qsca_pe) / 3. # see Weingartner_2001_ApJ_548_296.pdf, Section 2.3 \n\n else:\n if np.size(dist.a) > 1:\n for i in range(np.size(dist.a)):\n qsca[:,i] = scat.Qsca(E, a=dist.a[i], cm=cm)\n else:\n qsca = scat.Qsca(E, a=dist.a, cm=cm)\n\n if np.size(dist.a) == 1:\n kappa = dist.nd * qsca * cgeo / dist.md\n elif np.all(dist.nd == 0.):\n kappa = np.array( [0.]*np.size(E) )\n else:\n kappa = np.array([])\n for j in range(np.size(E)):\n kappa = np.append(kappa, utils.xytrapz(dist.a, dist.nd * qsca[j,:] * cgeo) / dist.md)\n\n self.kappa = kappa\n\n\n\n\n\n\n\nclass KappaExt(object):\n \"\"\"\n | Opacity to EXTINCTION [g^-1 cm^2] integrated over dust grain size\n | distribution\n |\n | -- Properties\n | scatm : ScatModel\n | E : scalar or np.array [keV]\n | dist : sizedist.DustSpectrum\n | kappa : scalar or np.array [cm^2 g^-1, typically]\n \"\"\"\n def __init__(self, E=1., scatm=ScatModel(), dist=sizedist.MRN77()):\n self.scatm = scatm\n self.E = E\n self.dist = dist\n\n if scatm.scat_type == 'RGscat':\n print('Rayleigh-Gans cross-section not currently supported for KappaExt')\n self.kappa = None\n return\n\n cm = scatm.cmindex_model\n scat = scatm.scat_model\n # print(cm.citation)\n\n cgeo = np.pi * (dist.a * c.MICRON2CM)**2\n\n qext = np.zeros(shape=(np.size(E), np.size(dist.a)))\n qext_pe = np.zeros(shape=(np.size(E), np.size(dist.a)))\n qext_pa = np.zeros(shape=(np.size(E), np.size(dist.a)))\n\n # For graphite case\n # See https://iopscience.iop.org/article/10.1086/318651/pdf Section 2.3\n # Qext = [Qext_epsilon_paralell + 2*Qext_epsilon_perpendicular] / 3.0\n if cm.cmtype == 'Graphite':\n cmGraphitePerp = cmindex.CmGraphite(size=cm.size, orient='perp')\n cmGraphitePara = cmindex.CmGraphite(size=cm.size, orient='para')\n\n if np.size(dist.a) > 1:\n for i in range(np.size(dist.a)):\n qext_pe[:,i] = scat.Qext(E, a=dist.a[i], cm=cmGraphitePerp)\n qext_pa[:,i] = scat.Qext(E, a=dist.a[i], cm=cmGraphitePara)\n else:\n qext_pe = scat.Qext(E, a=dist.a, cm=cmGraphitePerp)\n qext_pa = scat.Qext(E, a=dist.a, cm=cmGraphitePara)\n\n qext = (qext_pa + 2. * qext_pe) / 3.\n\n else:\n if np.size(dist.a) > 1:\n for i in range(np.size(dist.a)):\n qext[:,i] = scat.Qext(E, a=dist.a[i], cm=cm)\n else:\n qext = scat.Qext(E, a=dist.a, cm=cm)\n\n if np.size(dist.a) == 1:\n kappa = dist.nd * qext * cgeo / dist.md\n elif np.all(dist.nd == 0.):\n kappa = np.array( [0.]*np.size(E) )\n else:\n kappa = np.array([])\n for j in range(np.size(E)):\n kappa = np.append(kappa, utils.xytrapz(dist.a, dist.nd * qext[j,:] * cgeo) / dist.md)\n\n self.kappa = kappa","sub_path":"libs/extinction/scattools.py","file_name":"scattools.py","file_ext":"py","file_size_in_byte":10722,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"400863881","text":"import configparser\n\n\n\nconfig = configparser.ConfigParser()\n# print(config.sections())\nconfig.read('test_3.ini')\nprint(config.sections())\n\nfor key in config['DEFAULT']:\n print(key, config['DEFAULT'][key])\nfor section in config.sections():\n print('----------')\n for key in config[section]:\n print(key, config[section][key])\n\n\n","sub_path":"ConfigParser/lab_config.py","file_name":"lab_config.py","file_ext":"py","file_size_in_byte":341,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"399661996","text":"from base64 import b64decode\n\n# THIS WAS HARD!!!!! MAJORLY BECAUSE OF MY CONFUSION IN HAMMING CODE AND HAMMING DISTANCE\n# HAMMING CODE: https://en.wikipedia.org/wiki/Hamming_code \n# HAMMING DISTANCE (THIS ONE SHOWS CHARACTERS AS DIFFERING BYTES): https://en.wikipedia.org/wiki/Hamming_distance#Examples\n# WE ARE CALCULATING THE HAMMING DISTANCE IN BITS. NOT CHARACTERS, NOT BYTES.....\n# HOPE THAT SAVES YOU SOME TROUBLE...\ndef calculate_hamming_distance(str1,str2):\n \"\"\"Returns the Hamming distance, give 2 inputs of two **byte** strings, Please test with byte arrays too\"\"\"\n hamming_distance = 0 #Initialize hamming distance counter\n byte1 = [byte for byte in str1] #Takeone byte from str1 and str2\n byte2 = [byte for byte in str2] \n xor_bytes= [b1 ^ b2 for b1,b2 in zip(byte1,byte2)] #perform a xor inorder to find the changed bits\n for byte in xor_bytes:\n hamming_distance += sum([1 for bit in bin(byte) if bit == '1']) # Add 1 if the bit is 1 for bit in byte...\n return(hamming_distance)\n\ndef get_english_score(input_bytes):\n \"\"\"Compares each input byte to a character frequency \n chart and returns the score of a message based on the\n relative frequency the characters occur in the English\n language.\n \"\"\"\n\n # More information https://en.wikipedia.org/wiki/Letter_frequency\n # Assign a rating to each letter,\n # We use this word rating to scan for frequency of characters...\n # we judge wheter the input is in english or not by comparing the frequencies\n character_frequencies = {\n 'a': .08167, 'b': .01492, 'c': .02782, 'd': .04253,\n 'e': .12702, 'f': .02228, 'g': .02015, 'h': .06094,\n 'i': .06094, 'j': .00153, 'k': .00772, 'l': .04025,\n 'm': .02406, 'n': .06749, 'o': .07507, 'p': .01929,\n 'q': .00095, 'r': .05987, 's': .06327, 't': .09056,\n 'u': .02758, 'v': .00978, 'w': .02360, 'x': .00150,\n 'y': .01974, 'z': .00074, ' ': .13000\n }\n return sum([character_frequencies.get(chr(byte), 0) for byte in input_bytes.lower()])\n\ndef single_char_xor(input_bytes, char_value):\n \"\"\"Returns the result of each byte being XOR'd with a single value.\n \"\"\"\n output_bytes = b'' #Initialize a empty byte string\n for byte in input_bytes:\n output_bytes += bytes([byte ^ char_value]) # store the Xor'd value of byte^char_value in output_byte\n return output_bytes\n\ndef bruteforce_single_char_xor(ciphertext):\n \"\"\"Performs a singlechar xor for each possible value(0,255), and\n assigns a score based on character frequency. Returns the result\n with the highest score.\n \"\"\"\n potential_messages = [] #Inititalize the list for potential messages...\n for key_value in range(256): #range is 256 cause the extended ASCII chart contains 255 characters \n message = single_char_xor(ciphertext, key_value) \n score = get_english_score(message)\n data = {\n 'message': message,\n 'score': score,\n 'key': key_value\n }\n potential_messages.append(data) #add list elements to the potential messages lists\n return sorted(potential_messages, key=lambda x: x['score'], reverse=True)[0] #return sorted messages....\n\ndef repeated_key_XOR(m_bytes,key):\n \"\"\"Decrypts the message that was once XOR'd against a repeating key (habits maketh the man :P )\"\"\"\n output_bytes = b'' # Initialize the bytes string\n index = 0 # initialize the index at 0 \n for byte in m_bytes:\n output_bytes += bytes([byte ^ key[index]])\n if (index + 1) == len(key):\n index = 0 #add nothing if the value of the index+1 is equal to the length of key\n else:\n index += 1 #add 1 if value of the index is not equal to length.\n return output_bytes\n\ndef breaking_repeated_keyXOR(ciphertext):\n \"\"\"Attempts to break XOR with an repeated key, Attempts... that's all we can do...\"\"\"\n average_distances_ = []\n\n # Taking the key size from suggested range(2,40)\n for keysize in range(2,41):\n distances = []\n blocks = [ciphertext[i:i+keysize] for i in range(0, len(ciphertext), keysize)] # Break the ciphertext into blocks the length of the keysize\n \n while True:\n try:\n block_1 = blocks[0]\n block_2 = blocks[1]\n distance = calculate_hamming_distance(block_1, block_2)\n distances.append(distance/keysize)\n del blocks[0]\n del blocks[1]\n except Exception as e:\n break\n result = {\n 'key': keysize,\n 'avg distance': sum(distances) / len(distances)\n }\n average_distances_.append(result)\n possible_key_lengths = sorted(average_distances_, key=lambda x: x['avg distance'])[0]\n possible_plaintext = []\n key = b''\n possible_key_length = possible_key_lengths['key']\n for i in range(possible_key_length):\n block = b''\n for j in range(i, len(ciphertext), possible_key_length):\n block += bytes([ciphertext[j]])\n key += bytes([bruteforce_single_char_xor(block)['key']]) \n possible_plaintext.append((repeated_key_XOR(ciphertext, key), key)) \n return max(possible_plaintext, key=lambda x: get_english_score(x[0]))\n\ndef main():\n with open('/home/ubuntu_18_04/Documents/Cryptopals/Set1/6.txt')as input_file:# 1: Read the file contents as input,\n ciphers = b64decode(input_file.read()) #Base64 decode lines form the input\n result, key = breaking_repeated_keyXOR(ciphers)\n print(\"Key: {} Message: {} \".format(key, result))\nif __name__ == \"__main__\":\n main()","sub_path":"Set01/06.py","file_name":"06.py","file_ext":"py","file_size_in_byte":5630,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"525377886","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\nimport time\n\nimport media\nimport comment\n\nclass Bot(object):\n\n def __init__(self, instagram, webhooks, user):\n self.instagram = instagram\n self.webhooks = webhooks\n self.user = user\n\n def run_for_all(self):\n max_id = None\n \n while True:\n max_id, m = self._get_user_recent_media(max_id=max_id)\n for x in m:\n self._send(self.user, x)\n\n comments = self._get_media_comments(x)\n for c in comments:\n self._send(self.user, c)\n \n if not max_id:\n break\n time.sleep(1)\n\n def run(self):\n max_id, m = self._get_user_recent_media()\n for x in m:\n self._send(self.user, x)\n\n comments = self._get_media_comments(x)\n for c in comments:\n self._send(self.user, c)\n\n def _send(self, user, data):\n exist = None\n for x in self.webhooks:\n exist = x.exist(user, data)\n break\n\n if exist == None or exist == True:\n return\n\n for x in self.webhooks:\n x.send(user, data)\n \n def _get_user_recent_media(self, max_id=None):\n recent_media, next = self.instagram.user_recent_media(\n user_id=self.user.user_id,\n count=1,\n max_id=max_id\n )\n \n if not recent_media:\n return None, []\n\n result = []\n \n for x in recent_media:\n i = x.id\n username = x.user.username\n url = x.get_standard_resolution_url().split('?')[0]\n timestamp = int(x.created_time.strftime('%s'))\n caption = None\n if x.caption and x.caption.text:\n caption = x.caption.text\n\n m = media.Media(i, username, url, caption, timestamp)\n result.append(m)\n max_id = i\n\n return max_id, result\n\n def _get_media_comments(self, m):\n result = []\n \n comments = self.instagram.media_comments(m.media_id)\n if not comments:\n return []\n \n for x in comments:\n if not x.user.id == self.user.user_id:\n continue\n\n username = x.user.username\n text = x.text\n timestamp = int(x.created_at.strftime('%s'))\n\n c = comment.Comment(m.media_id, username, text, timestamp)\n result.append(c)\n\n return result\n","sub_path":"bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":2150,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"53886439","text":"#! /usr/bin/python\n# -*- coding: utf-8 -*-\n\n######################################\n#gaopin utils tool\n#coding licl\n#20141201 \n#beijing\n######################################\n\nimport sys, hashlib, os, random, time\n\ndef md5(corbisId):\n s=hashlib.md5(corbisId).hexdigest()\n subPaths=[s[0:2],s[2:4],s[4:6],s[6:8]]\n return subPaths\n\ndef md5Str(corbisId):\n subPaths = md5(corbisId)\n return '/%s/%s/%s/%s' % tuple(subPaths)\n\ndef filePath(storageId):\n if storageId ==\"ssd\":\n return \"/data/data1/Root448/\"\n if storageId == \"1\":\n return \"/home/data2/Root/\"\n elif storageId == \"2\":\n return \"/home/data/Rootsplash/\"\n elif storageId == \"3\":\n return \"/home/data/Root/\"\n elif storageId == \"4\":\n return \"/home/data3/Root/\"\n elif storageId == \"5\":\n return \"/home/data3/newdata3/\"\n elif storageId == \"6\":\n return \"/home/data1/Root/\"\n else:\n #return \"/home/data1/Root448/\"\n return ''\n\ndef findImageFileName(path):\n rootPath = path\n if path == '' or path == './':\n rootPath = os.path.abspath('.')\n filePaths = {}\n for root, dirs, files in os.walk(rootPath):\n for name in files:\n ns = name.rsplit('.',1)\n if len(ns) ==2:\n ex = ns[1].lower()\n if ex == 'jpg' or ex == 'gif' or ex == 'tif':\n tmp = []\n tmp.append(os.path.join(root, name))\n ##ext fileName\n tmp.append(ns[1])\n ##orgi fileName\n tmp.append(ns[0])\n ##fileName lower\n filePaths[ns[0].lower()] = tmp\n return filePaths\n\ndef getImgFileName(imgPaths,fileName):\n #return image path fileName,extFileName\n #add by licl at 20141215,proc fileName lower\n lowerFileName = fileName.lower()\n if lowerFileName in imgPaths:\n tmp = imgPaths[lowerFileName]\n return (tmp[0],tmp[1]) \n return ('','')\n\ndef rmPath(rootPath,subPaths):\n for i in range(0,4):\n path=rootPath\n for j in range(0,4-i):\n path=path+\"/\"+subPaths[j]\n l=os.listdir(path)\n if len(l)>0:\n return\n os.rmdir(path)\n\ndef mkPath(rootPath,subPaths):\n for i in range(0,4):\n sp=\"\"\n for j in range(0,i+1):\n sp=sp+subPaths[j]+\"/\"\n path=rootPath+\"/\"+sp\n b=os.path.exists(path)\n if b==False:\n os.chdir(rootPath)\n for j in range(0,i):\n os.chdir(subPaths[j])\n os.mkdir(subPaths[i])\n\ndef rmFile(fileName):\n b=os.path.exists(fileName)\n if b:\n os.remove(fileName)\n #print 'remove file: %s' % fileName\n return b\n\ndef genPid():\n ran = str(random.randint(0,10000))\n currPid = str(os.getpid())+'-'+ran+'-'+str(time.time())\n return currPid\n","sub_path":"newimg/GpUtils.py","file_name":"GpUtils.py","file_ext":"py","file_size_in_byte":3484,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"238516981","text":"from django.shortcuts import render, redirect\nfrom .models import Event\nfrom .forms import EventForm\n\n# Create your views here.\n\n\ndef list_events(request):\n if request.user.is_authenticated:\n events = Event.objects.filter(author=request.user)\n context = {'events': events}\n else:\n context = {}\n\n return render(request, 'events/events_list.html', context)\n\n\ndef show_event(request, event_id):\n if request.user.is_authenticated:\n event = Event.objects.get(id=event_id)\n if event.author == request.user:\n context = {'event': event}\n return render(request, 'events/event_detail.html', context)\n\n return redirect('events:list_events')\n\n\n# A subclass of ModelForm can accept an existing model instance as the keyword argument instance; if this is supplied, YourForm.save() will update that instance. If it’s not supplied, YourForm.save() will create a new instance of the specified model.\n\n\ndef create_event(request):\n if request.method == 'POST':\n form = EventForm(request.POST)\n if form.is_valid():\n new_event = form.save(commit=False)\n new_event.author = request.user\n new_event.save() # commit=True by default. Saves it to db\n return redirect('events:show_event', event_id=new_event.id)\n\n # if request is GET or form is not valid, we create a blank form and display it\n event_form = EventForm()\n context = {'event_form': event_form, 'type': 'Create'}\n return render(request, 'events/event_form.html', context)\n\n\ndef edit_event(request, event_id):\n event = Event.objects.get(id=event_id)\n if request.method == 'POST':\n # Passing in instance of event b/c we want to edit that instance with the POST data.\n form = EventForm(request.POST, instance=event)\n if form.is_valid():\n # does the same thing as calling .save() on an Event instance\n edited_event = form.save(commit=False)\n edited_event.author = request.user\n edited_event.save()\n return redirect('events:show_event', event_id=event_id)\n\n # if request is GET or form is not valid\n event_form = EventForm(instance=event)\n context = {'event_form': event_form, 'type': 'Edit'}\n return render(request, 'events/event_form.html', context)\n\n\ndef delete_event(request, event_id):\n event = Event.objects.get(id=event_id)\n event.delete()\n return redirect('events:list_events')\n","sub_path":"event_calendar/events/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2468,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"61509720","text":"import csv\nimport time\nimport os\ntry:\n from xml.etree import ElementTree as ET\nexcept ImportError:\n from xml.etree import cElementTree as ET\nvar_limit = 0\nvar_data_list = []\nvar_header_list = []\nvar_addition_create_list = []\nvar_addition_add_list = []\nvar_data_path = \"\"\n\ndef header_create(\n var_xml_path, var_data_path_in, var_fai_number,\n bool_is_addition_create, bool_is_addition_add):\n global var_header_list\n global var_data_path\n set_fai_number(var_fai_number)\n if os.path.isfile(var_xml_path):\n var_element_tree = ET.ElementTree()\n var_element_tree.parse(var_xml_path)\n var_element = var_element_tree.getroot()\n var_element_all = var_element.findall('header')\n for var_element_header in var_element_all:\n for var_element_fai in var_element_header:\n var_header_list.append(str(var_element_fai.text))\n var_data_path_in = get_current_data() + \"_\" + var_data_path_in\n csv_write_file = file(var_data_path_in,'wb')\n csv_writer = csv.writer(csv_write_file,dialect='excel')\n csv_writer.writerow(var_header_list)\n var_header_list = []\n csv_write_file.close()\n var_data_path = var_data_path_in\n if bool_is_addition_create:\n addition_create(var_xml_path)\n if bool_is_addition_add:\n addition_add(var_xml_path)\n else:\n return False\n\ndef addition_create(\n var_xml_path):\n global var_addition_create_list\n global var_data_path\n var_data_path_in = var_data_path\n if os.path.isfile(var_xml_path):\n var_element_tree = ET.ElementTree()\n var_element_tree.parse(var_xml_path)\n var_element = var_element_tree.getroot()\n var_element_all = var_element.findall('add1')\n for var_element_add1 in var_element_all:\n for var_element_add in var_element_add1:\n var_addition_create_list.append(str(var_element_add.text))\n csv_write_file = file(var_data_path_in,'ab')\n csv_writer = csv.writer(csv_write_file,dialect='excel')\n csv_writer.writerow(var_addition_create_list)\n csv_write_file.close()\n\ndef addition_add(\n var_xml_path):\n global var_addition_add_list\n global var_data_path\n var_data_path_in = var_data_path\n if os.path.isfile(var_xml_path):\n var_element_tree = ET.ElementTree()\n var_element_tree.parse(var_xml_path)\n var_element = var_element_tree.getroot()\n var_element_all = var_element.findall('add2')\n for var_element_add2 in var_element_all:\n for var_element_add in var_element_add2:\n var_addition_add_list.append(str(var_element_add.text))\n csv_write_file = file(var_data_path_in,'ab')\n csv_writer = csv.writer(csv_write_file,dialect='excel')\n csv_writer.writerow(var_addition_add_list)\n csv_write_file.close()\n\ndef set_fai_number(\n var_number):\n global var_limit\n var_limit = var_number\n\ndef data_receive(\n var_data_in):\n global var_limit\n global var_data_list\n if len(var_data_list) < var_limit:\n var_data_list.append(var_data_in)\n elif len(var_data_list) == var_limit:\n var_data_list.append(var_data_in + next_line())\n return var_data_list\n else:\n return 0\n\ndef data_writer():\n global var_data_list\n global var_data_path\n var_data_path_in = var_data_path\n csv_write_file = file(var_data_path_in,'ab')\n csv_writer = csv.writer(csv_write_file,dialect='excel')\n csv_writer.writerow(var_data_list)\n var_data_list = []\n csv_write_file.close()\n\ndef get_current_data():\n return time.strftime(\"%Y_%m_%d\",time.localtime(time.time()))\n\ndef get_current_time():\n return time.strftime(\"%Y_%m_%d\",time.localtime(time.time()))\n\ndef next_line():\n return os.linesep\n\nheader_create(\"test.xml\",\"3.csv\",3,True,True)\ndata_receive(\"1\")\ndata_receive(\"2\")\ndata_receive(\"3\")\ndata_writer()","sub_path":"CSVfile.py","file_name":"CSVfile.py","file_ext":"py","file_size_in_byte":3955,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"263963776","text":"import base\n\nclass PF_base(base.Base):\n\theadgear = 'H_HelmetWood'\n\titems = [\n\t\t'ItemWatch',\n\t\t'ItemMap',\n\t\t'ItemCompass',\n\t\t'tf_rf7800str_1',\n\t]\t\n\tclass HandGun:\n\t\tweapon = 'RH_m9'\n\t\tmags = [['RH_15Rnd_9x19_M9', 15]]\n\n\tclass Uniform:\n\t\ttype = 'U_ANA_CombatUniform_Forest'\n\t\titems = base.Base.Uniform.items + [\n\t\t\t['RH_15Rnd_9x19_M9', 2],\n\t\t]\n\tclass Vest:\n\t\ttype = 'V_ANA_TacVest_Wdl'\n\t\titems = [\n\t\t\t['Chemlight_red', 2],\n\t\t\t['Chemlight_blue', 2],\n\t\t\t['HandGrenade', 2],\n\t\t\t['SmokeShell', 2],\n\t\t]\n\tclass Backpack:\n\t\ttype = 'ANA_Carryall_AR_oli'\n\t\titems = [\n\t\t\t['rhs_weap_rsp30_white', 2],\n\t\t]\n################ Rifleman\n\nclass PF_rifleman(PF_base):\n\tclass Primary:\n\t\tweapon = 'rhs_weap_m16a4_carryhandle'\n\t\tmags = [\n\t\t\t['30rnd_556_magazine', 30],\n\t\t]\n\tclass Vest(PF_base.Vest):\n\t\titems = PF_base.Vest.items + [\n\t\t\t['rhs_mag_30Rnd_556x45_Mk318_Stanag', 5],\n\t\t]\n\tclass Backpack(PF_base.Backpack):\n\t\titems = PF_base.Backpack.items + [\n\t\t\t['rhs_mag_30Rnd_556x45_M855A1_Stanag_Tracer_Red', 5],\n\t\t]\n################ Rifleman AT/AA\n\nclass PF_riflemanAT(PF_base):\n\tclass Primary:\n\t\tweapon = 'rhs_weap_m16a4_carryhandle'\n\t\tmags = [\n\t\t\t['rhs_mag_30Rnd_556x45_Mk318_Stanag', 30],\n\t\t]\n\tclass Secondry:\n\t\tweapon = 'rhs_weap_rpg7'\n\t\tmags = [\n\t\t\t['rhs_rpg7_PG7VR_mag', 1],\n\t\t]\n\tclass Vest(PF_base.Vest):\n\t\titems = PF_base.Vest.items + [\n\t\t\t['rhs_mag_30Rnd_556x45_Mk318_Stanag', 5],\n\t\t]\n\tclass Backpack(PF_base.Backpack):\n\t\titems = PF_base.Backpack.items + [\n\t\t\t['rhs_mag_30Rnd_556x45_M855A1_Stanag_Tracer_Red', 5],\n\t\t\t['rhs_rpg7_PG7VR_mag', 2],\n\t\t\t['rhs_rpg7_OG7V_mag', 2],\n\t\t]\n################ Grenadier \n\nclass PF_grenadier(PF_base):\n\tclass Primary:\n\t\tweapon = 'rhs_weap_ak74m_gp25'\n\t\tmags = [\n\t\t\t['rhs_30Rnd_545x39_AK', 30],\n\t\t\t['rhs_VOG25', 1],\n\t\t]\n\tclass Vest(PF_base.Vest):\n\t\ttype = 'V_ANA_TacVest_Wdl'\n\t\titems = PF_rifleman_light.Vest.items + [\n\t\t\t['rhs_VOG25', 5],\n\t\t\t['rhs_mag_30Rnd_556x45_Mk318_Stanag', 5],\n\t\t]\n\n\tclass Backpack(PF_base.Backpack):\n\t\ttype = 'ANA_Carryall_AR_oli'\n\t\titems = PF_rifleman_light.Backpack.items + [\n\t\t\t['rhs_VOG25', 5],\n\t\t\t['rhs_VG40OP_white', 4],\n\t\t\t['rhs_GRD40_White', 4],\n\t\t\t['rhs_mag_30Rnd_556x45_M855A1_Stanag_Tracer_Red', 5],\n\t\t]\n\n################ Fire Team Leader\n\nclass PF_ftl(PF_rifleman):\n\tbinoc = 'Binocular'\n\theadgear = 'H_HelmetWood'\n\titems = PF_rifleman.items + ['tf_fadak_1']\n\n\tclass Primary:\n\t\tweapon = 'arifle_mas_mk17'\n\t\tmags = [\n\t\t\t['20Rnd_mas_762x51_Stanag', 20],\n\t\t]\n\tclass Vest(PF_rifleman.Vest):\n\t\ttype = 'V_ANA_TacVest_Wdl'\n\t\titems = PF_base.Vest.items + [\n\t\t\t['20Rnd_mas_762x51_Stanag', 5],\n\t\t]\n\tclass Backpack(PF_rifleman.Backpack):\n\t\titems = PF_base.Backpack.items + [\n\t\t\t['20Rnd_mas_762x51_T_Stanag', 5],\n\t\t]\n\t\n################ Heavy Machine Gunner\nclass PF_hmg(PF_base):\n\tbinoc = 'Binocular'\n\tclass Primary:\n\t\tweapon = 'rhs_weap_pkp'\n\t\tmags = [\n\t\t\t['rhs_100Rnd_762x54mmR', 100],\n\t\t]\n\tclass Vest(PF_base.Vest):\n\t\ttype = 'V_ANA_TacVest_Wdl'\n\t\titems = PF_base.Vest.items + [\n\t\t\t['rhs_100Rnd_762x54mmR', 1],\n\t\t]\n\tclass Backpack(PF_base.Backpack):\n\t\titems = PF_base.Backpack.items + [\n\t\t\t['rhs_100Rnd_762x54mmR_green', 2],\n\t\t]\n\n################ Medic\nclass PF_medic(PF_rifleman_light):\n\titems = PF_crew.items \n\t\n\tclass Primary:\n\t\tweapon = 'rhs_weap_m16a4_carryhandle'\n\t\tmags = [\n\t\t\t['30rnd_556_magazine', 30],\n\t\t]\n\tclass Vest(PF_rifleman_light.Vest):\n\t\titems = PF_rifleman_light.Vest.items + [\n\t\t\t['rhs_mag_30Rnd_556x45_Mk318_Stanag', 5],\n\t\t] \n\t\t\n\tclass Backpack(PF_rifleman_light.Backpack):\n\t\titems = PF_base.Backpack.items + base.MedicSupplies + [\n\t\t\t['rhs_mag_30Rnd_556x45_M855A1_Stanag_Tracer_Red', 5],\n\t\t] \n\t\t\n\t\t\n\n\n################ Platoon Leader\n\nclass PF_pl(PF_rifleman):\n\titems = PF_rifleman.items + ['tf_anprc152']\n\tbinoc = 'Binocular'\n\theadgear = 'H_HelmetWood'\n\tclass Primary:\n\t\tweapon = 'arifle_mas_mk17'\n\t\tmags = [\n\t\t\t['20Rnd_mas_762x51_Stanag', 20],\n\t\t]\n\tclass HandGun:\n\t\tweapon = 'RH_m9'\n\t\tmags = [\n\t\t\t['RH_15Rnd_9x19_M9', 15],\n\t\t]\n\tclass Uniform(PF_rifleman.Uniform):\n\t\ttype = 'U_ANA_OfficerUniform_Forest'\n\t\titems = PF_rifleman.Uniform.items + [\n\t\t\t['tf_anprc152', 1],\n\t\t\t['cw_item_9liner_medivac', 1],\n\t\t\t['cw_item_9liner_cas', 1],\n\t\t\t['cw_item_5liner_gcff', 1],\n\t\t]\n\tclass Vest(PF_rifleman.Vest):\n\t\ttype = 'V_ANA_TacVest_Wdl'\n\t\titems = PF_base.Vest.items + [\n\t\t\t['20Rnd_mas_762x51_Stanag', 5],\n\t\t]\n\tclass Backpack(PF_base.Backpack):\n\t\ttype = 'tf_rt1523g_big_rhs'\n\t\titems = PF_base.Backpack.items + [\n\t\t\t['alive_tablet', 1],\n\t\t\t['20Rnd_mas_762x51_T_Stanag', 5],\n\t\t]","sub_path":"Old files/loads/PF_2009.py","file_name":"PF_2009.py","file_ext":"py","file_size_in_byte":4434,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"211392752","text":"'''\nCreated on 03/03/2014\n\n@author: duncanw\n'''\n\n'''\nRuapehyCraterLakePlot contains functions for creating data plots from\nRuapehu monitoring data. The raw binary data must be transformed into \nCSV data before being used by RuapehuCraterLakePlot.\n'''\n\nimport matplotlib\nmatplotlib.use('Agg') # this prevents the display\nimport matplotlib.pyplot as plt\nfrom matplotlib.figure import Figure\nfrom matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas\nimport pandas as pd\nimport numpy as np\nimport xlrd\n\nimport os\nimport re\nimport io\nimport datetime\nfrom datetime import date, timedelta\nimport traceback\n\nimport ConfigParser\n\nclass RuapehuCraterLakePlot(object):\n \n '''\n Constructor loads the location of Ruapehu crater lake data from RuapehuCraterLakePlot.cfg\n if the dataDir parameter is not provided.\n '''\n def __init__(self, dataDir=None):\n self.config = RuapehuCraterLakePlot.loadConfig()\n if (dataDir == None):\n dataDir = self.config.get('Files', 'dataDir') \n self.dataDir = dataDir\n self.dailyAvgFile = self.config.get('Files', 'dailyAvgFile')\n self.outputDir = self.config.get('Files', 'outputDir')\n self.chemistryFile = self.config.get('Files', 'chemistryFile')\n \n # regex to match YY-MM dir names\n self.yearMonthDirRegex = re.compile('\\d{2}-\\d{2}')\n # regex to match filenames like \"20131001_clean.csv\"\n self.dataFileRegex = re.compile('(\\d{8})_clean.csv')\n # regex to match dates like 2013/10/01 03:00:00\n self.dateTimeRegex = re.compile('\\d{4}/\\d{2}/\\d{2}\\s+\\d{2}:\\d{2}:\\d{2}')\n \n \n @classmethod\n def loadConfig(cls):\n scriptDir = os.path.dirname(os.path.realpath(__file__))\n config = ConfigParser.ConfigParser()\n config.read(os.path.join(scriptDir, 'RuapehuCraterLakePlot.cfg'))\n return config \n \n '''\n startDate: datetime specifying the first day in the range of data to be returned\n endDate: datetime specifying the last day in the range of data to be returned\n \n Returns a pandas DataFrame object containing Ruapehu crater lake data in the given range.\n '''\n def getData(self, startDate, endDate):\n \n dataframeList = []\n numberOfDays = (endDate - startDate).days + 1\n for day in range(0, numberOfDays):\n date = startDate + timedelta(days=day)\n dataFile = self.__getDataFilePath(date)\n if os.path.exists(dataFile) and os.stat(dataFile).st_size > 0:\n dataframe = self.__readData(dataFile)\n dataframeList.append(dataframe)\n else:\n dataframe = self.__getDummyDataframe(date)\n dataframeList.append(dataframe) \n\n dataframe = pd.concat(dataframeList)\n return dataframe\n \n def getDailyAverageData(self):\n return self.__readData(self.dailyAvgFile)\n \n '''\n startDate: datetime specifying the first day in the range of data to be included.\n endDate: datetime specifying the last day in the range of data to be included.\n \n Reads manual temperature measurements from the Ruapehu crater lake chemistry\n measurements Excel spreadsheet, and returns them as a Pandas DataFrame object. \n Returns None if no temperature data is found. \n '''\n def getChemistryTempData(self, startDate, endDate):\n \n # Opens the workbook, reads it into memory then closes it.\n workbook = xlrd.open_workbook(self.chemistryFile)\n dateValueList = [startDate]\n tempValueList = [np.NAN]\n for year in range(startDate.year, endDate.year + 1):\n # worksheets are labelled by year\n sheetName = str(year)\n if sheetName in workbook.sheet_names():\n worksheet = workbook.sheet_by_name(str(year))\n dateColumn = -1\n tempColumn = -1\n headerRow = 0\n \n # Look for date and temperature columns in the worksheet\n for colIndex in range (0, worksheet.ncols):\n colHeader = worksheet.cell_value(headerRow, colIndex)\n if colHeader == 'Date':\n dateColumn = colIndex\n elif colHeader == 'Tm':\n tempColumn = colIndex\n \n if dateColumn >= 0 and tempColumn >= 0:\n # worksheet contains date and temperature columns, try\n # to extract data.\n for rowIndex in range (1, worksheet.nrows):\n dateValue = None\n tempValue = None\n if (worksheet.cell(rowIndex, dateColumn).ctype == xlrd.XL_CELL_DATE):\n dateValue = datetime.datetime(*xlrd.xldate_as_tuple(worksheet.cell_value(rowIndex, dateColumn), workbook.datemode)) \n # Estimate measurement collection time at 10am,\n # then subtract 12 hours to approximate the UTC time \n #dateValue = dateValue.replace(hour=10, minute=0, second=0) - timedelta(hours=12)\n #dateValue = dateValue - timedelta(days=1)\n if (startDate <= dateValue and dateValue <= endDate): \n tempColVal = worksheet.cell_value(rowIndex, tempColumn) \n try: \n tempValue = float(tempColVal)\n except ValueError:\n pass \n \n if (dateValue != None and tempValue != None): \n dateValueList.append(dateValue)\n tempValueList.append(tempValue)\n \n dateValueList.append(endDate)\n tempValueList.append(np.NAN)\n dataFrame = None\n if len(tempValueList) > 2:\n dataFrame = pd.DataFrame(tempValueList, index=dateValueList)\n dataFrame = dataFrame.resample('D', fill_method=None)\n return dataFrame\n \n def __getDummyDataframe(self, date):\n names = self.__getColumns()\n index = pd.date_range(name=names[0], start=date.replace(hour=0, minute=0, second=0), end=date.replace(hour=23, minute=0, second=0), freq='H')\n return pd.DataFrame(index=index, columns=names[1:]) \n \n def __getColumns(self):\n return ['TimeUTC', 'Battery', 'BoxTemp', 'LakeLevel', 'LakeTemperature', 'AirPressure', 'LakeLevel2', 'LakeTemperature2'] \n \n \n def __getDataFilePath(self, date):\n yearMonth = date.strftime(\"%Y-%m\")[2:] # remove the first two digits of year\n dateString = date.strftime(\"%Y%m%d\")\n return os.path.join(self.dataDir, yearMonth, dateString + \"_clean.csv\") \n \n '''\n startDate: datetime specifying the first day in the range of data to be included in the plots\n endDate: datetime specifying the last day in the range of data to be included in the plots\n \n Returns a byte string of a png file containing Ruapehu crater lake data plots.\n '''\n def getPlots(self, startDate, endDate): \n chemTempDataFrame=None\n try:\n chemTempDataFrame = self.getChemistryTempData(startDate, endDate)\n except:\n traceback.print_exc()\n \n return self.getRclPlots(self.getData(startDate, endDate), chemTempDataFrame) \n \n\n '''\n Reads the data from the daily average file and returns a byte string of a png file \n containing plots of the data.\n '''\n def getDailyAveragePlots(self):\n rclDataFrame = self.getDailyAverageData()\n chemTempDataFrame=None\n try: \n startDate = rclDataFrame.index[0]\n endDate = rclDataFrame.index[-1]\n chemTempDataFrame = self.getChemistryTempData(startDate, endDate)\n except:\n traceback.print_exc()\n \n return self.getRclPlots(rclDataFrame, chemTempDataFrame) \n \n def getRclPlots(self, rclDataFrame, chemTempDataFrame=None):\n \n plt.ioff() \n figure = Figure(figsize=(12,10))\n FigureCanvas(figure)\n figureGridRows = 5\n figureGridCols = 1\n \n degC = \" (\" + u'\\N{DEGREE SIGN}' + \"C)\"\n \n axes = figure.add_subplot(figureGridRows,figureGridCols,1)\n rclDataFrame.AirPressure.plot(ax=axes)\n axes.set_ylabel(\"Air Pressure (mBar)\")\n axes.set_xlabel(\"\")\n axes.xaxis.tick_top()\n xlabels = axes.get_xticklabels() \n for label in xlabels: \n label.set_rotation(30) \n label.set_horizontalalignment('left');\n axes.set_autoscaley_on(False)\n axes.set_ylim([680,760]) \n xticks = axes.get_xticks()\n \n axes = figure.add_subplot(figureGridRows,figureGridCols,2)\n rclDataFrame.LakeTemperature.plot(ax=axes, label = \"data logger 1\")\n # SS rclDataFrame.LakeTemperature.plot(ax=axes, label = \"data logger 1\", legend=True)\n #SS rclDataFrame.LakeTemperature2.plot(ax=axes, label = \"data logger 2\", legend=True)\n if (chemTempDataFrame is not None):\n chemTempDataFrame.plot(ax=axes, style='ro')\n handles, labels = axes.get_legend_handles_labels()\n labels[2] = 'manual measurements'\n axes.legend(handles, labels,loc=2,prop={'size':10}, numpoints=1)\n\n axes.set_ylabel(\"Lake Temp\" + degC)\n axes.set_autoscaley_on(False)\n #SS axes.set_ylim([10,45]) \n axes.set_ylim([10,48]) \n axes.set_xticks(xticks)\n axes.set_xlabel(\"\")\n axes.set_xticklabels([]) \n \n axes = figure.add_subplot(figureGridRows,figureGridCols,3)\n # SS rclDataFrame.LakeLevel.plot(ax=axes, label = \"data logger 1\")\n # SS rclDataFrame.LakeLevel.plot(ax=axes, label = \"data logger 1\", legend=True)\n rclDataFrame.LakeLevel2.plot(ax=axes, label = \"data logger 2\")\n axes.set_ylabel(\"Lake Level (m)\")\n axes.set_xlabel(\"\")\n axes.set_xticklabels([]) \n axes.set_autoscaley_on(False)\n axes.set_ylim([0,3]) \n axes.axhline(y=1, color='#444444') \n \n axes = figure.add_subplot(figureGridRows,figureGridCols,4)\n rclDataFrame.BoxTemp.plot(ax=axes)\n axes.set_ylabel(\"Box Temp\" + degC)\n axes.set_xlabel(\"\")\n axes.set_xticklabels([]) \n axes.set_autoscaley_on(False)\n axes.set_ylim([-10,30]) \n \n axes = figure.add_subplot(figureGridRows,figureGridCols,5)\n rclDataFrame.Battery.plot(ax=axes)\n axes.set_ylabel(\"Battery (V)\")\n axes.set_xlabel(\"Timestamp UTC\") \n axes.set_autoscaley_on(False)\n axes.set_ylim([12,13.5]) \n \n # create a time plot drawn label\n timestamp = datetime.datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")\n figure.text(0.001, 0.001, 'Plot drawn: ' + str(timestamp))\n \n figure.tight_layout(None, pad=0.5, h_pad=0.1, w_pad=0) \n \n imageBuffer = io.BytesIO()\n figure.savefig(imageBuffer, format='png')\n return imageBuffer.getvalue() \n \n '''\n startDate: datetime specifying the first day in the range of data to be returned\n endDate: datetime specifying the last day in the range of data to be returned\n \n Returns a byte string of Ruapehu crater lake csv data.\n ''' \n def getCsvData(self, startDate, endDate): \n rclDataFrame = self.getData(startDate, endDate) \n csvBuffer = io.BytesIO()\n rclDataFrame.to_csv(csvBuffer, encoding='us-ascii')\n return csvBuffer.getvalue() \n \n '''\n Returns the first and last day of the currently available Ruapehu crater lake data.\n \n Values are returned as two datetimes. \n '''\n def getDateRange(self):\n yearMonthList = []\n for name in os.listdir(self.dataDir):\n if os.path.isdir(os.path.join(self.dataDir, name)):\n if self.yearMonthDirRegex.match(name):\n yearMonthList.append(name)\n yearMonthList.sort()\n \n firstDay = self.__getDayOfMonth(yearMonthList[0], 0)\n lastDay = self.__getDayOfMonth(yearMonthList[-1], -1)\n\n return firstDay, lastDay\n \n '''\n Checks the data directory to find the first or last day data is available for in the\n given month.\n \n yearMonth: e.g \"13-05\" for May 2013\n dayPosition: 0 to get the first day in the month, -1 to get the last day in the month.\n \n Returns the first or last day, as a datetime.\n ''' \n def __getDayOfMonth(self, yearMonth, dayPosition):\n dayFileList = []\n for name in os.listdir(os.path.join(self.dataDir, yearMonth)):\n if not os.path.isdir(os.path.join(self.dataDir, name)) and self.dataFileRegex.match(name):\n dayFileList.append(name)\n dayFileList.sort()\n day = self.dataFileRegex.match(dayFileList[dayPosition]).group(1) \n \n return datetime.datetime.strptime(day, '%Y%m%d'); \n \n def __datetimeConverter(self, date):\n if (self.dateTimeRegex.match(date)):\n try:\n return datetime.datetime.strptime(date, \"%Y/%m/%d %H:%M:%S\")\n except ValueError:\n pass\n \n return self.__getDummyDate()\n \n def __getDummyDate(self):\n return datetime.datetime.strptime('1970/01/01 00:00:00', \"%Y/%m/%d %H:%M:%S\")\n \n def __readData(self, fileName):\n\n # The data files are of variable quality, the occasional row has\n # extra or missing columns. For this reason files have to be read \n # line by line and munged, rather than using the standard pandas.read_table approach \n names=self.__getColumns()\n data = pd.DataFrame(columns = names)\n data.set_index(names[0], inplace=True)\n\n with open(fileName, 'r') as f:\n for line in f:\n elements = line.strip().split(',')\n # Pad rows missing columns with NaN\n while len(elements) < len(names):\n elements.append(np.nan)\n # Truncate rows with extra columns\n del elements[len(names):] \n \n # Convert strings to floats\n numericVals = elements[1:]\n for i in range(len(numericVals)):\n try:\n numericVals[i] = float(numericVals[i])\n except Exception:\n numericVals[i] = np.nan\n\n elements = [self.__datetimeConverter(elements[0])] + numericVals\n newData = pd.DataFrame([tuple(elements)],columns = names)\n newData.set_index(names[0], inplace=True)\n data = pd.concat( [data, newData])\n \n \n data = data[data.index != self.__getDummyDate()]\n return data \n \n\n\n \n \n \n","sub_path":"RuapehuCraterLakePlot.py","file_name":"RuapehuCraterLakePlot.py","file_ext":"py","file_size_in_byte":15245,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"326712609","text":"def reverse(mening):\n reord = ''\n for i in range(len(mening)):\n reord += mening[-(i+1)]\n if reord.lower() == mening.lower():\n return True\n else:\n return False\n\nkommentar = input('Skriv in ett ord. ')\nprint()\nprint(reverse(kommentar))\nprint()\n","sub_path":"8.py","file_name":"8.py","file_ext":"py","file_size_in_byte":275,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"226937569","text":"# ---------------------\n# Bubble sort algorithm.\n# ---------------------\n\ndef bubblesort(a, n):\n\tfor i in range(0, n - 1): # Passing through in list (n - 1) times.\n\t\tf = 0 # Mark for break if list sorted.\n\t\tfor j in range(0, n - 1): # Passing through in list from 0 to (n - 1).\n\t\t\tif a[j] > a[j + 1]: # Comparison a[j] and a[j + 1].\n\t\t\t\ta[j], a[j + 1] = a[j + 1], a[j] # Swap items.\n\t\t\t\tf = 1 # Mark for continued passing.\n\t\tprint(\" \", [i + 1], \"-->\", a) # Printing sorting status.\n\t\tif f == 0: # If list sorted then\n\t\t\tbreak # - break passing.\n\treturn a, i + 1 # Return sorted list and number passages.\n\ndef visualization():\n\tfrom random import randint # Importing randint item in random module.\n\tn = 10 # Amount items in list.\n\ta = [randint(0, n) for i in range(n)] # Filling list of randoms numbers.\n\tprint(\"Initial list:\", a) # Printing initial list.\n\tprint(\"Visualization of algorithm work.\") # Printing decription.\n\ta, i = bubblesort(a, n) # Sorting list.\n\tprint(\"Final list:\", a) # Printing final list.\n\tprint(\"Total numbers of passages:\", i) # Printing numbers of passages.\n\nimport timeit\nelapsed_time = timeit.timeit(visualization, number = 1) # Start program and counting elapsed time.\nprint(\"Elapsed time: \", round(elapsed_time, 3), \"sec.\") # Printing elapsed time.","sub_path":"SortingAlgorithms/BubbleSort.py","file_name":"BubbleSort.py","file_ext":"py","file_size_in_byte":1606,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"380666219","text":"# Levente Papp, 10/31/2019\nimport numpy as np\nimport urllib.request as ur\nimport pandas as pd\nimport warnings\nfrom sklearn.metrics import f1_score\nwarnings.filterwarnings(\"ignore\")\n\nraw_data = pd.read_csv(\"german.data-numeric.csv\", header=None)\n\nmatrix = []\nfor i in range(1000):\n row = raw_data[0][i].split(\" \")\n while \"\" in row:\n row.remove(\"\")\n matrix.append(row)\n\ncolumn_names = [\"X1\", \"X2\", \"X3\", \"X4\", \"X5\", \"X6\", \"X7\", \"X8\", \"X9\", \"X10\",\n \"X11\", \"X12\", \"X13\", \"X14\", \"X15\", \"X16\", \"X17\", \"X18\", \"X19\", \"X20\",\n \"X21\", \"X22\", \"X23\", \"X24\", \"X25\"]\ngerman_data = pd.DataFrame(columns = column_names)\nfor row in matrix:\n german_data = german_data.append(pd.Series(row, index = column_names), ignore_index = True)\nX = german_data.iloc[:, 0:24]\ny = german_data.iloc[:, 24:]\n\ncost_matrix = [[0, 1], [5, 0]]\n\nfrom sklearn.model_selection import train_test_split\n\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2)\n\n\nfrom sklearn import metrics\nfrom sklearn.ensemble import ExtraTreesClassifier\nextra_trees_model = ExtraTreesClassifier()\nextra_trees_model.fit(X_train, y_train)\nextra_trees_predicted = extra_trees_model.predict(X_test)\n\n\nfrom sklearn.feature_selection import RFE\nfrom sklearn.linear_model import LogisticRegression\nmodel1 = LogisticRegression()\nrfe_model = RFE(model1, 3)\nrfe_model = rfe_model.fit(X_train, y_train)\nrfe_predicted = rfe_model.predict(X_test)\n\n\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn import metrics\nlogistic_model = LogisticRegression()\nlogistic_model.fit(X_train, y_train)\nlogistic_model_predicted = logistic_model.predict(X_test)\n\n\n\nfrom sklearn import metrics\nfrom sklearn.naive_bayes import GaussianNB\ngaussian_model = GaussianNB()\ngaussian_model.fit(X_train, y_train)\ngaussian_model_predicted = gaussian_model.predict(X_test)\n\nfrom sklearn import metrics\nfrom sklearn.neighbors import KNeighborsClassifier\nknn_model = KNeighborsClassifier()\nknn_model.fit(X_train, y_train)\nknn_model_predicted = knn_model.predict(X_test)\n\n# part a)\nfrom sklearn.ensemble import VotingClassifier\nfrom sklearn import model_selection \n\nestimators = []\nestimators.append((\"extratrees\", extra_trees_model))\nestimators.append((\"rfe\", rfe_model))\nestimators.append((\"logistic\", logistic_model))\nestimators.append((\"gaussian\", gaussian_model))\nestimators.append((\"KNN\", knn_model))\nensemble = VotingClassifier(estimators, voting = \"hard\")\nensemble.fit(X_train, y_train)\n\npredicted = ensemble.predict(X_test)\nunweighted_voting_confusion = metrics.confusion_matrix(y_test, predicted)\nproduct_unweighted = np.multiply(unweighted_voting_confusion, cost_matrix)\nsum_unweighted = sum(sum(product_unweighted))\n\nensemble2 = VotingClassifier(estimators, voting = \"soft\")\nensemble2.fit(X_train, y_train)\npredicted2 = ensemble2.predict(X_test)\nweighted_voting_confusion = metrics.confusion_matrix(y_test, predicted2)\nproduct_weighted = np.multiply(weighted_voting_confusion, cost_matrix)\nsum_weighted = sum(sum(product_weighted))\n\n# part b)\n# Random feature and training set selections?\nfrom sklearn.ensemble import RandomForestClassifier\n\n# tune random forest depth (find optimal max_depth between 1 and 1000)\noptimal_depth = 1\noptimal_cost = float(\"inf\")\nfor i in range(1, 300):\n random_forest = RandomForestClassifier(n_estimators = 100, max_depth = i)\n random_forest.fit(X_train, y_train)\n random_forest_predictions = random_forest.predict(X_test)\n random_forest_confusion = metrics.confusion_matrix(y_test, random_forest_predictions)\n product_random_forest = np.multiply(random_forest_confusion, cost_matrix)\n sum_random_forest = sum(sum(product_random_forest))\n if sum_random_forest < optimal_cost:\n optimal_depth = i\n optimal_cost = sum_random_forest\n\n\n# part c)\nfrom sklearn.ensemble import AdaBoostClassifier\n\nadaboost = AdaBoostClassifier(n_estimators=100, random_state=0)\nadaboost.fit(X_train, y_train) \nadaboost_predictions = adaboost.predict(X_test)\nadaboost_confusion = metrics.confusion_matrix(y_test, adaboost_predictions)\nproduct_adaboost = np.multiply(adaboost_confusion, cost_matrix)\nsum_adaboost = sum(sum(product_adaboost))\n\n\nprint(\"Unweighted Voting Classifier Cost: \" + str(sum_unweighted))\nprint(\"Weighted Voting Classifier Cost: \" + str(sum_weighted))\nprint(\"Random Forest Cost: \" + str(optimal_cost) + \" with maxDepth = \" + str(optimal_depth))\nprint(\"Adaboost Cost: \" + str(sum_adaboost))\n\n\n# From the above Cost values we can see that the Random Forest Classifier has the minimum cost at a height of 61.\n# From these values, it seems like the Unweighted Voting Classifier is performing the weakest, since it has the \n# highest Cost (punishment) value. \n","sub_path":"ML_projects/classifiers.py","file_name":"classifiers.py","file_ext":"py","file_size_in_byte":4710,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"152738691","text":"import logging\nfrom logging import handlers\n\n\nclass Loger(object):\n\n def __init__(self, fileName='test', level=\"debug\", mode='w',error_record=False,file_save=False):\n self.log = logging.getLogger()\n\n self.level_dict = {\n 'critical': 50,\n 'error': 40,\n 'warning': 30,\n 'info': 20,\n 'debug': 10\n }\n\n # 2、设置文件跟屏幕输出的handler\n # self.filehandler=handlers.TimedRotatingFileHandler(filename=fileName,when='D',backupCount=\"3\",encoding='utf-8')\n self.streamhandler = logging.StreamHandler()\n\n\n # 3、设置格式化输出\n formatter = logging.Formatter(fmt=\"%(asctime)s-%(levelname)s-%(message)s\")\n\n # 4.绑定关系:①logger绑定handler\n self.log.addHandler(self.streamhandler)\n\n # ②为handler绑定formatter\n self.streamhandler.setFormatter(formatter)\n\n # 5、设置日志级别各个对象的日志级别\n self.log.setLevel(self.level_dict[level])\n self.streamhandler.setLevel(self.level_dict[level])\n\n if file_save:\n self.filehandler = logging.FileHandler(filename=fileName + '.log', mode=mode, encoding=\"utf-8\") # 默认\n self.log.addHandler(self.filehandler)\n self.filehandler.setFormatter(formatter)\n self.filehandler.setLevel(self.level_dict[level])\n\n if error_record:\n self.errorhandler = logging.FileHandler(filename=fileName + \".error_log\", mode=mode, encoding=\"utf-8\")\n self.log.addHandler(self.errorhandler)\n self.errorhandler.setFormatter(formatter)\n self.errorhandler.setLevel(40)","sub_path":"Ar_Script/Meetu_Ui_Test/common/logger.py","file_name":"logger.py","file_ext":"py","file_size_in_byte":1689,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"361687402","text":"''' \n16/08/2018 Evaluate Walker cell over a given latitude range\n'''\nimport numpy as np\nimport xarray as xr\nimport matplotlib.pyplot as plt\nfrom pylab import rcParams\nimport sh\nfrom hadley_cell import walker_cell\nfrom data_handling_updates import model_constants as mc\nfrom windspharm.xarray import VectorWind\n\n\ndef walker_cell_monthly(run, latin=None):\n \n data = xr.open_dataset('/disca/share/rg419/Data_moist/climatologies/' + run + '.nc')\n \n plot_dir = '/scratch/rg419/plots/overturning_monthly/' + run + '/'\n mkdir = sh.mkdir.bake('-p')\n mkdir(plot_dir)\n \n data.coords['month'] = (data.xofyear - 1) //6 + 1 \n data = data.groupby('month').mean(('xofyear'))\n \n # Create a VectorWind instance to handle the computation, and compute variables\n w = VectorWind(data.ucomp.sel(pfull=np.arange(50.,950.,50.)), data.vcomp.sel(pfull=np.arange(50.,950.,50.)))\n uchi, vchi, upsi, vpsi = w.helmholtz()\n \n psi_w = walker_cell(uchi, latin=latin, dp_in=-50.)\n psi_w /= 1.e9\n \n # Set figure parameters\n rcParams['figure.figsize'] = 12, 7\n rcParams['font.size'] = 14\n \n # Start figure with 12 subplots\n fig, ((ax1, ax2, ax3, ax4), (ax5, ax6, ax7, ax8), (ax9, ax10, ax11, ax12)) = plt.subplots(3, 4)\n axes = [ax1, ax2, ax3, ax4, ax5, ax6, ax7, ax8, ax9, ax10, ax11, ax12]\n \n i=0\n for ax in axes:\n psi_w.sel(month=i+1).plot.contour(ax=ax, x='lon', y='pfull', yincrease=False, levels=np.arange(0.,301,50.), colors='k', add_labels=False)\n psi_w.sel(month=i+1).plot.contour(ax=ax, x='lon', y='pfull', yincrease=False, levels=np.arange(-300.,0.,50.), colors='k', linestyles='dashed', add_labels=False)\n i=i+1\n ax.set_xticks(np.arange(0.,361.,120.))\n ax.set_yticks(np.arange(0.,1001.,250.))\n ax.grid(True,linestyle=':')\n \n plt.subplots_adjust(left=0.1, right=0.97, top=0.95, bottom=0.1, hspace=0.3, wspace=0.3)\n \n plt.savefig(plot_dir + 'walker_' + run + '.pdf', format='pdf') \n plt.close()\n \nwalker_cell_monthly('q_shallow')\nwalker_cell_monthly('3q_shallow')\nwalker_cell_monthly('half_shallow')\nwalker_cell_monthly('half_shallow_5')\nwalker_cell_monthly('half_shallow_10')\n","sub_path":"zonal_asym_runs/walker_cell_monthly.py","file_name":"walker_cell_monthly.py","file_ext":"py","file_size_in_byte":2200,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"316086587","text":"#!/usr/bin/python\n# -*- coding: UTF-8 -*-\n\n\nimport tensorflow as tf\nimport data_gen\n\n\ndef basic_hparams():\n least_vocab_count_src = 4\n least_vocab_count_tar = 10\n src_vocab_size = data_gen.TextEncoder(mode=\"src\", least=least_vocab_count_src).vocab_size\n tar_vocab_size = data_gen.TextEncoder(mode=\"tar\", least=least_vocab_count_tar).vocab_size\n return tf.contrib.training.HParams(\n emb_dim=512,\n n_heads=8,\n layer_prepostprocess_dropout=0.1,\n attention_dropout_rate=0.1,\n num_layers_enc=6,\n num_layers_dec=6,\n max_sent_len=10,\n decode_length=20,\n PE_learnable=False,\n batch_size=2048,\n batch_len=32,\n least_vocab_count_src=least_vocab_count_src,\n least_vocab_count_tar=least_vocab_count_tar,\n src_vocab_size=src_vocab_size,\n tar_vocab_size=tar_vocab_size,\n n_inner=2048,\n learning_rate_warmup_steps=4000,\n lr=1e-1,\n optimizer_adam_beta1=0.9,\n optimizer_adam_beta2=0.98,\n optimizer_adam_epsilon=1e-9\n )\n\n\ndef transformer_base():\n hparams = basic_hparams()\n\n return hparams\n","sub_path":"common_hparams.py","file_name":"common_hparams.py","file_ext":"py","file_size_in_byte":1143,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"208540183","text":"\"\"\"\n Configuration module using simply \".py\" format\n For diverse configurations, maintain multiple files.\n\n If maintain multiple files get messy, Saltar team will look for another\n approach.\n\"\"\"\n\n#************************ General debugging flags ************************\nDEBUG_MODE = True\nMAKE_JSON_FILE = False\nMAKE_SHRED_JSON_FILE = False\n\n#************************ Path and Files ************************\n# Directory where the .exe.pcap files are located\nDIR_PCAP = \"/home/luti/Saltar/python/\"\n#The extensions of files to be processed\nPCAP_EXTENSION = \".exe.pcap\"\nJSON_EXTENSION = \".json\"\n\n#************************ MongoDB ************************\n# MongoDB can be\nHOST_NAME = \"localhost\"\nIP_ADDRESS = \"198.162.40.12\"\n#Port of comunication\nPORT = 27017\n\n#The file needs be particioned, the mongoDB do not acept\n#files bigger then 16MB == 16777216 bytes\nMAX_LENGTH_BSON = 16777216\n\n#************************ Parallelism configuration ************************\n#Determine the number of cores that should be adjusted due to file size and memory consumption\nMAX_CORES = 1\nMODERATED_CORES = 1\nLOW_CORES = 1","sub_path":"dataprocessing/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":1116,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"510330711","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Dec 11 21:33:52 2018\n\n@author: Michael\n\"\"\"\n\nfrom TwitterAPI import TwitterAPI\nimport pandas as pd\nimport csv\n\nquery = 'Gillibrand'\nPRODUCT = 'fullarchive'\nLABEL = 'Testing'\n\napi = TwitterAPI(\"nWQzqafsC0XcH370OkSlwxonQ\", \n \"ZZWqC0b1hO3N8bGO5yfpTj98mnptVBTJX6sZ9fbBdBmH9h0SUJ\", \n \"706273045527314432-GymkKoqae8a3uNBSALfjG2pcnr6oT34\", \n \"EUQ40A65Bck7yVQceSClcGX3Q3eKvNSVq3VXCZk1o7yBq\")\n\ncsvFile = open('Gillibrand.csv', 'a',encoding=\"utf-8\")\ncsvWriter = csv.writer(csvFile)\n\ntnext = ' '\ni = 0\nr = api.request('tweets/search/%s/:%s' % (PRODUCT, LABEL), \n {'query':query, \n 'fromDate':'201809010000',\n 'toDate':'201811052200'\n }\n )\n\nfor item in r:\n csvWriter.writerow([item['created_at'],item['user']['screen_name'], item['text'] if 'text' in item else item])\njson = r.json()\nif 'next' not in json:\n print(\"fail\")\ntnext = json['next']\n\nwhile(i<15):\n r = api.request('tweets/search/%s/:%s' % (PRODUCT, LABEL), \n {'query':query, \n 'fromDate':'201809010000',\n 'toDate':'201811052200','next':tnext\n }\n )\n if r.status_code != 200:\n break\n for item in r:\n csvWriter.writerow([item['created_at'],item['user']['screen_name'], item['text'] if 'text' in item else item])\n json = r.json()\n if 'next' not in json:\n break\n tnext = json['next']\n i+= 1\nprint(\"finish\")","sub_path":"TwitterSearchPast.py","file_name":"TwitterSearchPast.py","file_ext":"py","file_size_in_byte":1451,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"265182412","text":"import sys\n\ndef sum_lines():\n for line in sys.stdin: #一次只讀一行\n line=line.strip() #去掉頭尾的指定符號 默認為空格\n print(line)\n tokens=line.split() #將字串分開 弄成像矩陣的樣子\n print(tokens)\n print(len(tokens))\n \n #total=sum([float(tokens) for tokens in tokens])\n total=0 #sum不能用\n for i in range(0,len(tokens)):\n total+=float(tokens[i])\n print(\"Total:\",total)\n\nsum_lines() #python sum_lines.py<test3.txt","sub_path":"2_InOutput/sum_lines.py","file_name":"sum_lines.py","file_ext":"py","file_size_in_byte":530,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"538478588","text":"import twitter\r\nimport json\r\n\r\nf = open(\"result.json\", \"w\")\r\nf.seek(0)\r\nCONSUMER_KEY = ''\r\nCONSUMER_SECRET = ''\r\nOAUTH_TOKEN = ''\r\nOAUTH_TOKEN_SECRET = ''\r\n\r\nauth = twitter.oauth.OAuth(OAUTH_TOKEN, OAUTH_TOKEN_SECRET, CONSUMER_KEY, CONSUMER_SECRET)\r\ntwitter_api = twitter.Twitter(auth=auth)\r\n\r\ndetermine_next = -1\r\nlistofmyfollowers = []\r\nme = \"\"\r\n\r\nwhile determine_next != 0:\r\n my_followers = twitter_api.followers.list(screen_name=me, count=200, cursor=determine_next)\r\n determine_next = my_followers[\"next_cursor\"]\r\n myFollowers = my_followers[\"users\"]\r\n for follower in myFollowers:\r\n listofmyfollowers.append(follower[\"screen_name\"])\r\n\r\nmy_friends_friends = []\r\ndata = {}\r\n\r\nallp = {}\r\nfor friend in listofmyfollowers:\r\n determine_next = -1\r\n print(friend)\r\n\r\n while determine_next != 0:\r\n followers_of_followers = twitter_api.followers.list(screen_name=friend, count=200, cursor=determine_next)\r\n determine_next = followers_of_followers[\"next_cursor\"]\r\n other_followers = followers_of_followers[\"users\"]\r\n friendslist = []\r\n for follower in other_followers:\r\n friendslist.append(follower[\"screen_name\"])\r\n my_friends_friends.append(follower[\"screen_name\"])\r\n allp[friend] = friendslist\r\n\r\n\r\nall2 = {}\r\nall2[me] = allp\r\nresult = json.dump(all2, f, indent=4)\r\n\r\nf.truncate()\r\nf.close()","sub_path":"FriendsOfMyFriends.py","file_name":"FriendsOfMyFriends.py","file_ext":"py","file_size_in_byte":1381,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"112265976","text":"\"\"\"The most basic chat protocol possible.\n\nrun me with twistd -y chatserver.py, and then connect with multiple\ntelnet clients to port 12450\n\"\"\"\nimport sys\nsys.path.insert(0, '..')\nfrom twisted.application import service, internet\nfrom BaseServer import *\n\n\nTCP_PORT = 12450\nSERVER_NAME = \"Gasol\"\npeers = {'Meeks':('localhost', 12451),'Young':('localhost', 12452) }\nfactory = ServerProtocolFactory(SERVER_NAME, peers)\n\napplication = service.Application(\"twitterServer\")\ninternet.TCPServer(TCP_PORT, factory).setServiceParent(application)\n\n","sub_path":"project/Gasol/Gasol.py","file_name":"Gasol.py","file_ext":"py","file_size_in_byte":538,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"433318310","text":"import torch\nimport hivemind\nfrom test_utils.run_server import background_server\n\n\ndef test_remote_module_call():\n \"\"\" Check that remote_module_call returns correct outputs and gradients if called directly \"\"\"\n num_experts = 8\n k_min = 1\n timeout_after_k_min = None\n backward_k_min = 1\n timeout_total = None\n backward_timeout = None\n rtol = 1e-3\n atol = 1e-6\n\n xx = torch.randn(32, 1024, requires_grad=True)\n logits = torch.randn(3, requires_grad=True)\n random_proj = torch.randn_like(xx)\n\n with background_server(num_experts=num_experts, device='cpu',\n no_optimizer=True, no_dht=True) as (localhost, server_port, dht_port):\n experts = [hivemind.RemoteExpert(uid=f'expert.{i}', port=server_port) for i in range(num_experts)]\n moe_output, = hivemind.client.moe._RemoteMoECall.apply(\n logits, experts[:len(logits)], k_min, timeout_after_k_min, backward_k_min, timeout_total, backward_timeout,\n [(None,), {}], xx)\n\n grad_xx_moe, = torch.autograd.grad(torch.sum(random_proj * moe_output), xx, retain_graph=True)\n grad_logits_moe, = torch.autograd.grad(torch.sum(random_proj * moe_output), logits, retain_graph=True)\n\n # reference outputs: call all experts manually and average their outputs with softmax probabilities\n probs = torch.softmax(logits, 0)\n outs = [expert(xx) for expert in experts[:3]]\n manual_output = sum(p * x for p, x in zip(probs, outs))\n grad_xx_manual, = torch.autograd.grad(torch.sum(random_proj * manual_output), xx, retain_graph=True)\n grad_xx_manual_rerun, = torch.autograd.grad(torch.sum(random_proj * manual_output), xx, retain_graph=True)\n grad_logits_manual, = torch.autograd.grad(torch.sum(random_proj * manual_output), logits, retain_graph=True)\n\n assert torch.allclose(grad_xx_manual, grad_xx_manual_rerun, rtol, atol), \"Experts are non-deterministic. The test\" \\\n \" is only valid for deterministic experts\"\n assert torch.allclose(moe_output, manual_output, rtol, atol), \"_RemoteMoECall returned incorrect output\"\n assert torch.allclose(grad_xx_moe, grad_xx_manual, rtol, atol), \"incorrect gradient w.r.t. input\"\n assert torch.allclose(grad_logits_moe, grad_logits_manual, rtol, atol), \"incorrect gradient w.r.t. logits\"\n\n\ndef test_determinism():\n rtol = 0\n atol = 1e-6\n\n xx = torch.randn(32, 1024, requires_grad=True)\n mask = torch.randint(0, 1, (32, 1024))\n\n with background_server(num_experts=1, device='cpu', expert_cls='det_dropout',\n no_optimizer=True, no_dht=True) as (interface, server_port, dht_port):\n expert = hivemind.RemoteExpert(uid=f'expert.0', port=server_port)\n\n out = expert(xx, mask)\n out_rerun = expert(xx, mask)\n\n grad, = torch.autograd.grad(out.sum(), xx, retain_graph=True)\n grad_rerun, = torch.autograd.grad(out_rerun.sum(), xx, retain_graph=True)\n\n assert torch.allclose(out, out_rerun, rtol, atol), \"Dropout layer outputs are non-deterministic.\"\n assert torch.allclose(grad, grad_rerun, rtol, atol), \"Gradients are non-deterministic.\"\n\n\ndef test_compute_expert_scores():\n try:\n dht = hivemind.DHTNode(port=hivemind.find_open_port(), start=True)\n moe = hivemind.client.moe.RemoteMixtureOfExperts(\n dht=dht, in_features=1024, grid_size=(40,), k_best=4, k_min=1, timeout_after_k_min=1,\n uid_prefix='expert')\n gx, gy = torch.randn(4, 5, requires_grad=True), torch.torch.randn(4, 3, requires_grad=True)\n ii = [[4, 0, 2], [3, 1, 1, 1, 3], [0], [3, 2]]\n jj = [[2, 2, 1], [0, 1, 2, 0, 1], [0], [1, 2]]\n batch_experts = [\n [hivemind.RemoteExpert(uid=f'expert.{ii[batch_i][expert_i]}.{jj[batch_i][expert_i]}')\n for expert_i in range(len(ii[batch_i]))]\n for batch_i in range(len(ii))\n ] # note: these experts do not exists on server, we use them only to test moe compute_expert_scores\n logits = moe.compute_expert_scores([gx, gy], batch_experts)\n torch.softmax(logits, dim=-1).norm(dim=-1).mean().backward()\n assert gx.grad.norm().item() > 0 and gy.grad.norm().item(), \"compute_expert_scores didn't backprop\"\n\n for batch_i in range(len(ii)):\n for expert_i in range(len(ii[batch_i])):\n assert torch.allclose(logits[batch_i, expert_i],\n gx[batch_i, ii[batch_i][expert_i]] + gy[batch_i, jj[batch_i][expert_i]]), \\\n \"compute_expert_scores returned incorrect score\"\n finally:\n dht.shutdown()\n","sub_path":"tests/test_moe.py","file_name":"test_moe.py","file_ext":"py","file_size_in_byte":4692,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"583681617","text":"import sys\nimport os\nimport random\nimport copy\n\nfrom decimal import Decimal\nfrom operator import attrgetter\nfrom pprint import pprint as pp\n\nclass Individual(object):\n\n def __init__(self, steps, parents=None):\n self.steps = steps\n self.has_run = False\n self.result = None \n if parents and isinstance(parents[0], Individual) and isinstance(parents[1], Individual):\n # Crossbreeding\n cutoff_parent1 = int(len(parents[0].buildqueue) * .7)\n cutoff_parent2 = int(len(parents[1].buildqueue) * .3)\n self.buildqueue = parents[0].buildqueue[:cutoff_parent1] + parents[1].buildqueue[:cutoff_parent2]\n \n # Mutations\n if random.randint(0,100) == 100 :\n # Some building/upgrade gets replaced\n self.buildqueue[random.randint(0,len(self.buildqueue)-1)] = random.randint(0,7) + (random.randint(0,1) * 100)\n\n if random.randint(0,100) == 100:\n # replace a sequence\n self.buildqueue.extend([ random.randint(0,7) + (random.randint(0,1) * 100) for _ in range(random.randint(0,4)) ])\n\n if random.randint(0,1000) == 1000:\n random.shuffle(self.buildqueue)\n \n else:\n self.buildqueue = [ random.randint(0, 7) for _ in range(random.randint(1, 20)) ]\n \n def simulate(self, buildsheet, force_run=False):\n if self.has_run and not force_run:\n return\n \n total_resources = Decimal(\"0\")\n total_generated = Decimal(\"0\")\n buildings = [0]*8\n upgrades = [0]*8\n bcost_growth = Decimal(\"1.2\")\n ucost_growth = Decimal(\"3.0\")\n uboost_growth = Decimal(\"2.0\")\n next_to_build_index = None\n buildqueue = self.buildqueue[:]\n\n for step in range(self.steps):\n\n resources_this_step = Decimal(\"0\")\n\n # Add resources from buildings\n for (i, building_count) in enumerate(buildings):\n resources_this_step += (buildsheet[i][2] * building_count)\n\n # calculate this turn's \"automatic\" resources\n resources_this_step += (buildsheet[0][2] * buildings[0]) + 1\n\n total_resources += resources_this_step\n if next_to_build_index is None and buildqueue:\n next_to_build_index = buildqueue[0]\n if next_to_build_index >= 100:\n upgrade = True\n next_to_build_index %= 100\n next_to_build_cost = buildsheet[next_to_build_index][4]\n else:\n upgrade = False\n next_to_build_cost = buildsheet[next_to_build_index][1]\n\n if next_to_build_index is not None and total_resources >= next_to_build_cost:\n if not upgrade:\n total_resources -= next_to_build_cost\n buildings[next_to_build_index] += 1\n buildsheet[next_to_build_index][1] *= bcost_growth # Next building costs more\n else:\n total_resources -= next_to_build_cost\n buildsheet[next_to_build_index][2] += buildsheet[next_to_build_index][3] # Increase production\n buildsheet[next_to_build_index][3] *= uboost_growth # Next upgrade boost doubles\n buildsheet[next_to_build_index][4] *= ucost_growth # Next upgrade costs more\n upgrades[next_to_build_index] += 1\n \n buildqueue.pop(0)\n next_to_build_index = None\n \n self.has_run = True\n self.result = (step+1, total_resources, buildings, upgrades, buildqueue)\n\n def __gt__(self, other):\n if other is None:\n return True\n \n if not isinstance(other, Individual):\n return True\n\n return self.result[1] > other.result[1]\n \n @staticmethod\n def sortfun(individual):\n if individual.result:\n return individual.result[1]\n else:\n return 0\n \n def __repr__(self):\n args = [id(self), self.has_run, self.steps, self.buildqueue, self.result]\n return \"<Id: {0}, HasRun: {1}, Steps: {2}, BuildQueue: {3}, Results: {4}>\".format(*args)\n \nclass Evolver(object):\n\n def __init__(self, individual_class=Individual, individual_class_args=[1000], num_of_individuals=40):\n self.buildsheet = []\n with open(\"dp.input.txt\") as inputfile:\n for line in inputfile:\n row = line.strip().split()\n row[1:] = [ Decimal(v) for v in row[1:] ]\n self.buildsheet.append(row)\n\n self.individual_class = individual_class\n self.individual_class_args = individual_class_args\n self.individuals = [ individual_class(*individual_class_args) for _ in range(num_of_individuals) ]\n #pp(self.individuals)\n\n def run(self):\n try:\n best_so_far = None\n iteration = 1\n while True:\n random.shuffle(self.individuals)\n selected = self.individuals[:4]\n\n for individual in selected:\n individual.simulate(copy.deepcopy(self.buildsheet))\n \n selected.sort(key=self.individual_class.sortfun, reverse=True)\n\n if selected[0] > best_so_far:\n best_so_far = selected[0]\n print(\"\\nNew best!: Steps: {0}, Resources: {1}, Buildings: {2}, Upgrades: {3}, Remaining BuildQueue: {4}, Original BuildQueue: {5}\".format(*list(best_so_far.result)+[best_so_far.buildqueue]))\n\n new_individual1 = self.individual_class(*self.individual_class_args, parents=(selected[0], selected[1]))\n new_individual2 = self.individual_class(*self.individual_class_args, parents=(selected[1], selected[0]))\n\n selected[2:4] = [new_individual1, new_individual2]\n self.individuals[:4] = selected\n \n if iteration % 100 == 0:\n print(\".\", flush=True, end=\"\")\n \n iteration += 1\n \n except KeyboardInterrupt as e:\n pass\n \n def get_top_individuals(self, top=5):\n self.individuals.sort(key=self.individual_class.sortfun, reverse=True)\n return self.individuals[:top]\n \nif __name__ == \"__main__\":\n evolver = Evolver()\n evolver.run()\n\n pp(evolver.get_top_individuals())\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n ","sub_path":"248/dp.py","file_name":"dp.py","file_ext":"py","file_size_in_byte":6716,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"543213163","text":"from django.conf import settings\nfrom apps.deploy import mysql, git, pip\nfrom django.core.management import call_command\n\ndef _deploy_code():\n print('Pulling latest website code')\n root_path = settings.ROOT_PATH\n git.git_pull(root_path)\n\ndef _deploy_db_code():\n print('Pulling latest database files')\n db_path = settings.DB_PATH\n git.git_pull(db_path)\n\ndef deploy(app_code, db_code, procs, tables, views, pips, collect, live):\n print('Deploying to {}'.format(settings.SITE_NAME))\n\n if app_code:\n _deploy_code()\n if db_code:\n _deploy_db_code()\n if procs:\n with mysql.get_session(live=live) as session:\n mysql.deploy_procs(session)\n if tables:\n with mysql.get_session(live=live) as session:\n mysql.deploy_tables(session)\n if views:\n with mysql.get_session(live=live) as session:\n mysql.deploy_views(session)\n if pips:\n pip.install_pips()\n if collect:\n call_command('collectstatic', verbosity=1, interactive=False)\n\n","sub_path":"apps/deploy/deploy.py","file_name":"deploy.py","file_ext":"py","file_size_in_byte":1037,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"484262481","text":"f = open('f:/text.bmp','rb')\nfiledata = f.read()\nfilesize = f.tell()\nf.close()\nfiledata2 = bytearray(filedata)\nwidth = filedata2[18]\nheight = filedata2[22]\nprint('width:', width)\nprint('height:', height) # less than 255 , width and height have 4 bytes\nprint('pix:', width * height)\nprint('filesize:', filesize)\nf2 = open('f:/t2.bmp','wb')\nchange = 0\nindex = 54\nloop = 0\nwhile index < filesize - 2:\n loop += 1\n r = filedata2[index]\n g = filedata2[index+1]\n b = filedata2[index+2]\n threshold = 110\n if (r < threshold) and (g < threshold) and (b < threshold):\n bytes = bytearray(3)\n bytes[0] = 0\n bytes[1] = 255\n bytes[2] = 0\n filedata2[index:index+3] = bytes\n else:\n bytes = bytearray(3)\n bytes[0] = bytes[1] = bytes[2] = 255\n filedata2[index:index+3] = bytes\n change += 1\n index += 3\n \nf2.write(filedata2)\nf2.close()\nprint ('change:',change)\nprint ('loop:',loop)\n","sub_path":"fanli/337/337.py","file_name":"337.py","file_ext":"py","file_size_in_byte":951,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"241910354","text":"import bhmie\nfrom pylab import *\n\n#where to get the lib: http://atol.ucsd.edu/scatlib/index.htm\n#doc for other matlab implementation http://arrc.ou.edu/~rockee/NRA_2007_website/Mie-scattering-Matlab.pdf\n#better doc http://nit.colorado.edu/atoc5560/week8.pdf\n#very recent paper http://dl.acm.org/citation.cfm?id=1276452\n# We know more than these guys! \n#A Theoretical Investigation of the Transmission of Light through Fog\n#http://prola.aps.org/abstract/PR/v38/i1/p159_1\n#online calculator http://omlc.ogi.edu/calc/mie_calc.html\n\n#BIG REVIEW OF OPTICAL TWEEZER COMPUTATION\n#http://iopscience.iop.org/1464-4258/9/8/S12/pdf/joa7_8_S12.pdf\n#their website http://www.physics.uq.edu.au/people/nieminen/software.html\n\nx = arange(1.,40,.3)\n#n = 1.33+0.2j\nn = 1.33\nnang = 20\ny = array([bhmie.bhmie(i,n,nang) for i in x])\n\n\n# S1, S2 are the diagonal components of the scattering matrix\n# gsca is the asymmetry parameter -> the 1st moment of the phase function\n# g describes the shape of the phase function.\n# g>1 indicates forward scattering is favoured\n# g<1 indicates backscattering is favoured\n# see http://www.ess.uci.edu/~cmclinden/link/xx/node19.html for further discussion\n\nS1, S2, Qext, Qsca, Qback, gsca = y.T\nplot(x,Qext)\nplot(x,Qsca)\nplot(x,Qback)\nplot(x,gsca)\nlegend(['extinction','scattering','backscatter','asymmetry parameter'])\nxlabel(\"size parameter ($2\\pi r /\\lambda$)\")\nylabel(\"efficience ($\\sigma_i / \\sigma_{real}$)\")\ntitle(\"micro-water droplet scattering properties\")\nfigure()\nfor i in range(2):\n polar(linspace(0,pi,2*nang -1),real(S1[i]),'b')\n polar(linspace(0,-pi,2*nang -1),real(S1[i]),'b')\n #polar(linspace(0,pi,2*nang -1),real(S2[i]))\nshow()\n","sub_path":"optical_trapping/miesimulation.py","file_name":"miesimulation.py","file_ext":"py","file_size_in_byte":1669,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"381511565","text":"import requests\n\nfrom rest_framework.reverse import reverse as drf_reverse\n\nfrom django import forms\nfrom django.conf import settings\nfrom django.urls import NoReverseMatch\n\nfrom olympia.shelves.models import Shelf\n\n\nclass ShelfForm(forms.ModelForm):\n class Meta:\n model = Shelf\n fields = ('title', 'endpoint', 'criteria',\n 'footer_text', 'footer_pathname',)\n\n def clean(self):\n data = self.cleaned_data\n baseUrl = settings.INTERNAL_SITE_URL\n\n endpoint = data.get('endpoint')\n criteria = data.get('criteria')\n\n if criteria is None:\n return\n\n try:\n if endpoint == 'search':\n if not criteria.startswith('?') or criteria.count('?') > 1:\n raise forms.ValidationError('Check criteria field.')\n else:\n api = drf_reverse('v4:addon-search')\n url = baseUrl + api + criteria\n elif endpoint == 'collections':\n api = drf_reverse('v4:collection-addon-list', kwargs={\n 'user_pk': settings.TASK_USER_ID,\n 'collection_slug': criteria\n })\n url = baseUrl + api\n else:\n return\n\n except NoReverseMatch:\n raise forms.ValidationError(\n 'No data found - check criteria parameters.')\n\n try:\n response = requests.get(url)\n if response.status_code == 404:\n raise forms.ValidationError('Check criteria - No data found')\n if response.status_code != 200:\n raise forms.ValidationError(\n 'Check criteria - %s' % response.json()[0])\n if response.json().get('count', 0) == 0:\n raise forms.ValidationError(\n 'Check criteria parameters - e.g., \"type\"')\n\n except requests.exceptions.ConnectionError:\n raise forms.ValidationError('Connection Error')\n","sub_path":"src/olympia/shelves/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":2006,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"9053422","text":"# -*- coding: utf-8 -*-\n\nimport re\nfrom mapdepot.schemas.base import Base\nfrom mapdepot.utils import re_search\n\n\nclass Topographic(Base):\n \"\"\"Topographic Series Schemas.\n\n <Series>_<Sheet>_<Edition>_<Distributor>_(<Area>_<Country>)\n G628_4565_ED01_TGD_(ACHA_N_ANIR_MALI)\n \"\"\"\n\n name = 'Topographic Series'\n\n def __repr__(self):\n \"\"\"Represent string.\"\"\"\n return '<Topographic Series [{series}/{sheet}]>'.format(series=self.series, sheet=self.sheet)\n\n @property\n def series(self):\n return re_search(r'^([a-zA-Z\\d]+)', self.basename)\n\n @property\n def sheet(self):\n return re_search(r'_([a-zA-Z\\d\\-]+)', self.basename)\n\n @property\n def distributor(self):\n distributor = re_search(r'([a-zA-Z\\d]+)[\\-_ ]*?\\(', self.basename)\n if distributor != self.edition.get('result'):\n return distributor\n\n @property\n def location(self):\n return re_search(r'\\(([a-zA-Z\\d\\-_,& ]+)\\)', self.basename)\n\n @property\n def city(self):\n if self.cities:\n return self.cities[0]\n return ''\n\n @property\n def cities(self):\n if self.location:\n location = re.split(r'[,_&]', self.location)\n if len(location) > 1:\n del location[-1]\n return re.split(r'[\\-_]', '_'.join(location))\n return []\n\n @property\n def country(self):\n if self.countries:\n return self.countries[0]\n return ''\n\n @property\n def countries(self):\n if self.location:\n location = re.split(r'[,_&]', self.location)\n if location:\n return re.split(r'[\\-_]', location[-1])\n return []\n\n @property\n def validation(self):\n if self.directories:\n return {\n 'series': {\n 'major': self.validate_major_series(),\n 'minor': self.validate_minor_series()\n }\n }\n return {}\n\n def validate_major_series(self):\n if self.folder:\n if bool(re_search(self.folder['series']['major'], self.series)):\n return True\n # Match the first character IF it's a INTEGER\n if re_search(r'^\\d', self.folder['series']['major']):\n if bool(re_search(self.folder['series']['major'][0], self.series)):\n return True\n return False\n\n def validate_minor_series(self):\n if self.folder:\n if bool(re_search(self.folder['series']['minor'], self.series)):\n return True\n return False\n\n @property\n def folder(self):\n if len(self.directories) > 1:\n return {\n 'series': {\n 'major': re_search(r'[a-zA-Z\\d]+', self.directories[-2]),\n 'minor': re_search(r'[a-zA-Z\\d]+', self.directories[-1])\n }\n }\n return {}\n\n @property\n def json(self):\n \"\"\"Building JSON object.\"\"\"\n json = self.base_json\n json.update({\n 'schema': self.name,\n 'folder': self.folder,\n 'series': self.series,\n 'edition': self.edition,\n 'sheet': self.sheet,\n 'distributor': self.distributor,\n 'location': {\n 'name': self.location,\n 'cities': self.cities,\n 'countries': self.countries\n }\n })\n return json\n\nif __name__ == '__main__':\n import json\n filename = 'E725_sheet 09_ed01_GSGS_(PORT MARIA_(ANNOTTO BAY)_JAMAICA).tif'\n topo = Topographic(filename)\n print(json.dumps(topo.json, indent=4))\n","sub_path":"mapdepot/schemas/topographic.py","file_name":"topographic.py","file_ext":"py","file_size_in_byte":3675,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"222299225","text":"import numpy as np\nimport pandas as pd\nimport os \nfrom sklearn.metrics import pairwise_distances\nfrom sklearn.feature_extraction.text import CountVectorizer\ndir_path = os.path.dirname(os.path.realpath(__file__))\n\ndata = pd.read_pickle(dir_path + \"/16k_apparel_data_preprocessed\")\n\ntitle_vectorizer = CountVectorizer()\ntitle_features = title_vectorizer.fit_transform(data[\"title\"])\n# title_features.get_shape()\n\ntitle_index_map = {k.strip(): v for v, k in enumerate(data[\"title\"])}\n# print( title_index_map['huafeiwude womens cardigan wool waistcoat casual vest black l'])\n\n\ndef bag_of_words_model(title, num_results):\n doc_id = title_index_map[title]\n pairwise_dist = pairwise_distances(title_features, title_features[doc_id])\n\n # np.argsort will return indices of the smallest distances\n indices = np.argsort(pairwise_dist.flatten())[0:num_results]\n # pdists will store the smallest distances\n pdists = np.sort(pairwise_dist.flatten())[0:num_results]\n\n # data frame indices of the 9 smallest distace's\n df_indices = list(data.index[indices])\n results = []\n for i in range(0, len(indices)):\n resultObj = {\n \"ASIN\": data[\"asin\"].loc[df_indices[i]],\n \"Brand\": data[\"brand\"].loc[df_indices[i]],\n \"Title\": data[\"title\"].loc[df_indices[i]],\n \"medium_image_url\": data[\"medium_image_url\"].loc[df_indices[i]],\n \"dist\": pdists[i],\n }\n results.append(resultObj)\n \n return results\n\n# call the bag-of-words model for a product to get similar products.\n# bag_of_words_model(\"huafeiwude womens cardigan wool waistcoat casual vest black l\", 20)\n","sub_path":"server/BagOfWords.py","file_name":"BagOfWords.py","file_ext":"py","file_size_in_byte":1642,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"435480805","text":"import json\nimport boto3\n\ndef lambda_handler(event, context):\n \n s3 = boto3.resource('s3')\n s3_properties = event.get('Records')[0].get('s3')\n bucket_name = s3_properties.get('bucket').get('name')\n uploaded_file = s3_properties.get('object').get('key')\n \n json_response = response_detect_text(bucket_name, uploaded_file)\n \n s3object = s3.Object('test-lambda-tt', uploaded_file.replace('.', '_') + '.json')\n \n s3object.put(\n Body=(bytes(json.dumps(json_response).encode('UTF-8')))\n )\n \n return {\n 'statusCode': 200,\n 'body': json.dumps(json_response)\n }\n\ndef response_detect_text(bucket_name, document_name):\n \n bucket = bucket_name\n document = document_name\n texttract_client = boto3.client('textract')\n\n # Process documents from S3\n response = texttract_client.detect_document_text(\n Document={\n 'S3Object': {\n 'Bucket': bucket, \n 'Name': document\n }\n }\n )\n\n #Get the text blocks\n blocks=response['Blocks']\n \n return {\n 'statusCode': 200,\n 'body': json.dumps(blocks)\n }","sub_path":"lambda_function.py","file_name":"lambda_function.py","file_ext":"py","file_size_in_byte":1176,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"363875567","text":"from sqlalchemy import create_engine \n \nclass DbUtils: \n db_string = \"postgresql+psycopg2://admin:admin@localhost/postgres\" \n \n def createTable(self): \n db = create_engine(self.db_string) \n db.execute(\"CREATE TABLE IF NOT EXISTS films (title text, director text, year text)\") \n \n def addNewFilm(self, title, director, year): \n db_string = \"postgresql+psycopg2://admin:admin@localhost/postgres\" \n db = create_engine(db_string) \n db.execute(\"INSERT INTO films(title, director, year) VALUES (%s,%s, %s)\", title, director, year) \n \n def getFilms(self): \n db_string = \"postgresql+psycopg2://admin:admin@localhost/postgres\" \n db = create_engine(db_string) \n films = db.execute(\"SELECT * FROM films\") \n return films","sub_path":"dbUtils.py","file_name":"dbUtils.py","file_ext":"py","file_size_in_byte":807,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"536080598","text":"# In this file I will create the training for the model with topics\nimport datetime\nimport gc\n\nfrom tensorflow.python.client import device_lib\nfrom tensorflow.python.saved_model.simple_save import simple_save\n\nfrom models.customer_reviews import ReviewGenerator, ReviewDiscriminator\nfrom path_resolution import resources_path\nfrom real.real_gan.loaders.custom_reviews_loader import RealDataCustomerReviewsLoader\nfrom real.real_gan.real_topic_train_utils import get_train_ops, \\\n get_metric_summary_op, get_fixed_temperature\nfrom utils.metrics.Jaccard import JaccardSimilarity, JaccardDiversity\nfrom utils.metrics.KLDivergence import KL_divergence\nfrom utils.metrics.Nll import NllReview\nfrom utils.utils import *\n\n\ndef get_available_gpus():\n local_device_protos = device_lib.list_local_devices()\n return [x.name for x in local_device_protos if x.device_type == 'GPU']\n\n\nprint(\"Available GPUs: {}\".format(get_available_gpus()))\n\n\n# A function to initiate the graph and train the networks\n\ndef customer_reviews_train(generator: ReviewGenerator, discriminator_positive: ReviewDiscriminator,\n discriminator_negative: ReviewDiscriminator,\n oracle_loader: RealDataCustomerReviewsLoader, config, args):\n batch_size = config['batch_size']\n num_sentences = config['num_sentences']\n vocab_size = config['vocabulary_size']\n seq_len = config['seq_len']\n dataset = config['dataset']\n npre_epochs = config['npre_epochs']\n nadv_steps = config['nadv_steps']\n temper = config['temperature']\n adapt = config['adapt']\n\n # changed to match resources path\n data_dir = resources_path(config['data_dir'], \"Amazon_Attribute\")\n log_dir = resources_path(config['log_dir'])\n sample_dir = resources_path(config['sample_dir'])\n\n # filename\n json_file = os.path.join(sample_dir, 'json_file.txt')\n csv_file = os.path.join(log_dir, 'experiment-log-rmcgan.csv')\n\n # create necessary directories\n if not os.path.exists(data_dir):\n os.makedirs(data_dir)\n if not os.path.exists(sample_dir):\n os.makedirs(sample_dir)\n if not os.path.exists(log_dir):\n os.makedirs(log_dir)\n\n # placeholder definitions\n x_real = tf.placeholder(tf.int32, [batch_size, seq_len], name=\"x_real\")\n x_pos = tf.placeholder(tf.int32, [batch_size, seq_len], name=\"x_pos\")\n x_neg = tf.placeholder(tf.int32, [batch_size, seq_len], name=\"x_neg\")\n x_sentiment = tf.placeholder(tf.int32, [batch_size], name=\"x_sentiment\")\n\n temperature = tf.Variable(1., trainable=False, name='temperature')\n\n x_real_pos_onehot = tf.one_hot(x_pos, vocab_size) # batch_size x seq_len x vocab_size\n x_real_neg_onehot = tf.one_hot(x_neg, vocab_size) # batch_size x seq_len x vocab_size\n assert x_real_pos_onehot.get_shape().as_list() == [batch_size, seq_len, vocab_size]\n\n # generator and discriminator outputs\n generator_obj = generator(x_real=x_real, temperature=temperature, x_sentiment=x_sentiment)\n # discriminator for positive sentences\n discriminator_positive_real_pos = discriminator_positive(x_onehot=x_real_pos_onehot)\n discriminator_positive_real_neg = discriminator_positive(x_onehot=x_real_neg_onehot)\n discriminator_positive_fake = discriminator_positive(x_onehot=generator_obj.gen_x_onehot_adv)\n # discriminator for negative sentences\n discriminator_negative_real_pos = discriminator_negative(x_onehot=x_real_pos_onehot)\n discriminator_negative_real_neg = discriminator_negative(x_onehot=x_real_neg_onehot)\n discriminator_negative_fake = discriminator_negative(x_onehot=generator_obj.gen_x_onehot_adv)\n\n # GAN / Divergence type\n\n log_pg, g_loss, d_loss = get_losses(generator_obj,\n discriminator_positive_real_pos,\n discriminator_positive_real_neg,\n discriminator_positive_fake,\n discriminator_negative_real_pos,\n discriminator_negative_real_neg,\n discriminator_negative_fake)\n\n # Global step\n global_step = tf.Variable(0, trainable=False)\n global_step_op = global_step.assign_add(1)\n\n # Train ops\n g_pretrain_op, g_train_op, d_train_op, d_topic_pretrain_op = get_train_ops(config, generator_obj.pretrain_loss,\n g_loss, d_loss,\n None,\n log_pg, temperature, global_step)\n\n # Record wall clock time\n time_diff = tf.placeholder(tf.float32)\n Wall_clock_time = tf.Variable(0., trainable=False)\n update_Wall_op = Wall_clock_time.assign_add(time_diff)\n\n # Temperature placeholder\n temp_var = tf.placeholder(tf.float32)\n update_temperature_op = temperature.assign(temp_var)\n\n # Loss summaries\n loss_summaries = [\n tf.summary.scalar('adv_loss/discriminator/total', d_loss),\n tf.summary.scalar('adv_loss/generator/total_g_loss', g_loss),\n tf.summary.scalar('adv_loss/log_pg', log_pg),\n tf.summary.scalar('adv_loss/Wall_clock_time', Wall_clock_time),\n tf.summary.scalar('adv_loss/temperature', temperature),\n ]\n loss_summary_op = tf.summary.merge(loss_summaries)\n\n # Metric Summaries\n metrics_pl, metric_summary_op = get_metric_summary_op(config)\n\n # Summaries\n gen_pretrain_loss_summary = CustomSummary(name='pretrain_loss', scope='generator')\n gen_sentences_summary = CustomSummary(name='generated_sentences', scope='generator',\n summary_type=tf.summary.text, item_type=tf.string)\n run_information = CustomSummary(name='run_information', scope='info',\n summary_type=tf.summary.text, item_type=tf.string)\n custom_summaries = [gen_pretrain_loss_summary, gen_sentences_summary, run_information]\n\n # To save the trained model\n # ------------- initial the graph --------------\n with init_sess() as sess:\n\n # count parameters\n\n log = open(csv_file, 'w')\n summary_dir = os.path.join(log_dir, 'summary', str(time.time()))\n if not os.path.exists(summary_dir):\n os.makedirs(summary_dir)\n sum_writer = tf.summary.FileWriter(summary_dir, sess.graph)\n for custom_summary in custom_summaries:\n custom_summary.set_file_writer(sum_writer, sess)\n\n run_information.write_summary(str(args), 0)\n print(\"Information stored in the summary!\")\n\n def get_metrics():\n # set up evaluation metric\n metrics = []\n if config['nll_gen']:\n nll_gen = NllReview(oracle_loader, generator_obj, sess, name='nll_gen_review')\n metrics.append(nll_gen)\n if config['KL']:\n KL_div = KL_divergence(oracle_loader, json_file, name='KL_divergence')\n metrics.append(KL_div)\n if config['jaccard_similarity']:\n Jaccard_Sim = JaccardSimilarity(oracle_loader, json_file, name='jaccard_similarity')\n metrics.append(Jaccard_Sim)\n if config['jaccard_diversity']:\n Jaccard_Sim = JaccardDiversity(oracle_loader, json_file, name='jaccard_diversity')\n metrics.append(Jaccard_Sim)\n\n return metrics\n\n metrics = get_metrics()\n generator_obj.generated_num = 200#num_sentences\n\n gc.collect()\n # Check if there is a pretrained generator saved\n model_dir = \"PretrainGenerator\"\n model_path = resources_path(os.path.join(\"checkpoint_folder\", model_dir))\n try:\n new_saver = tf.train.import_meta_graph(os.path.join(model_path, \"model.ckpt.meta\"))\n new_saver.restore(sess, os.path.join(model_path, \"model.ckpt\"))\n print(\"Used saved model for generator pretrain\")\n except OSError:\n print('Start pre-training...')\n # pre-training\n # Pre-train the generator using MLE for one epoch\n\n progress = tqdm(range(npre_epochs))\n for epoch in progress:\n oracle_loader.reset_pointer()\n g_pretrain_loss_np = generator_obj.pretrain_epoch(oracle_loader, sess, g_pretrain_op=g_pretrain_op)\n gen_pretrain_loss_summary.write_summary(g_pretrain_loss_np, epoch)\n msg = 'pre_gen_epoch:' + str(epoch) + ', g_pre_loss: %.4f' % g_pretrain_loss_np\n progress.set_description(msg)\n\n # Test\n ntest_pre = 30\n if np.mod(epoch, ntest_pre) == 0 or epoch == npre_epochs - 1:\n json_object = generator_obj.generate_json(oracle_loader, sess)\n write_json(json_file, json_object)\n\n # take sentences from saved files\n sent = take_sentences_json(json_object)\n gen_sentences_summary.write_summary(sent, epoch)\n\n # write summaries\n scores = [metric.get_score() for metric in metrics]\n metrics_summary_str = sess.run(metric_summary_op, feed_dict=dict(zip(metrics_pl, scores)))\n sum_writer.add_summary(metrics_summary_str, epoch)\n\n msg = 'pre_gen_epoch:' + str(epoch) + ', g_pre_loss: %.4f' % g_pretrain_loss_np\n metric_names = [metric.get_name() for metric in metrics]\n for (name, score) in zip(metric_names, scores):\n msg += ', ' + name + ': %.4f' % score\n tqdm.write(msg)\n log.write(msg)\n log.write('\\n')\n\n gc.collect()\n\n gc.collect()\n\n print('Start adversarial training...')\n progress = tqdm(range(nadv_steps))\n for adv_epoch in progress:\n gc.collect()\n niter = sess.run(global_step)\n\n t0 = time.time()\n # Adversarial training\n for _ in range(config['gsteps']):\n sentiment, sentence = oracle_loader.random_batch()\n n = np.zeros((generator_obj.batch_size, generator_obj.seq_len))\n for ind, el in enumerate(sentence):\n n[ind] = el\n sess.run(g_pretrain_op, feed_dict={generator_obj.x_real: n,\n generator_obj.x_sentiment: sentiment})\n for _ in range(config['dsteps']):\n sentiment, sentence, pos, neg = oracle_loader.get_positive_negative_batch()\n n1 = np.zeros((generator_obj.batch_size, generator_obj.seq_len))\n n2 = np.zeros((generator_obj.batch_size, generator_obj.seq_len))\n n3 = np.zeros((generator_obj.batch_size, generator_obj.seq_len))\n for ind, (s, p, n) in enumerate(zip(sentence, pos, neg)):\n n1[ind] = s\n n2[ind] = p[0]\n n3[ind] = n[0]\n feed_dict = {\n x_real: n1,\n x_pos: n2,\n x_neg: n3,\n x_sentiment: sentiment\n }\n sess.run(d_train_op, feed_dict=feed_dict)\n\n t1 = time.time()\n sess.run(update_Wall_op, feed_dict={time_diff: t1 - t0})\n\n # temperature\n temp_var_np = get_fixed_temperature(temper, niter, nadv_steps, adapt)\n sess.run(update_temperature_op, feed_dict={temp_var: temp_var_np})\n\n sentiment, sentence, pos, neg = oracle_loader.get_positive_negative_batch()\n n1 = np.zeros((generator_obj.batch_size, generator_obj.seq_len))\n n2 = np.zeros((generator_obj.batch_size, generator_obj.seq_len))\n n3 = np.zeros((generator_obj.batch_size, generator_obj.seq_len))\n for ind, (s, p, n) in enumerate(zip(sentence, pos, neg)):\n n1[ind] = s\n n2[ind] = p[0]\n n3[ind] = n[0]\n feed_dict = {\n x_real: n1,\n x_pos: n2,\n x_neg: n3,\n x_sentiment: sentiment\n }\n g_loss_np, d_loss_np, loss_summary_str = sess.run([g_loss, d_loss, loss_summary_op], feed_dict=feed_dict)\n sum_writer.add_summary(loss_summary_str, niter)\n\n sess.run(global_step_op)\n\n progress.set_description('g_loss: %4.4f, d_loss: %4.4f' % (g_loss_np, d_loss_np))\n\n # Test\n # print(\"N_iter: {}, test every {} epochs\".format(niter, config['ntest']))\n if np.mod(adv_epoch, 100) == 0 or adv_epoch == nadv_steps - 1:\n json_object = generator_obj.generate_json(oracle_loader, sess)\n write_json(json_file, json_object)\n\n # take sentences from saved files\n sent = take_sentences_json(json_object)\n gen_sentences_summary.write_summary(sent, niter + config['npre_epochs'])\n\n # write summaries\n scores = [metric.get_score() for metric in metrics]\n metrics_summary_str = sess.run(metric_summary_op, feed_dict=dict(zip(metrics_pl, scores)))\n sum_writer.add_summary(metrics_summary_str, niter + config['npre_epochs'])\n\n msg = 'adv_step: ' + str(niter)\n metric_names = [metric.get_name() for metric in metrics]\n for (name, score) in zip(metric_names, scores):\n msg += ', ' + name + ': %.4f' % score\n tqdm.write(msg)\n log.write(msg)\n log.write('\\n')\n\n gc.collect()\n\n sum_writer.close()\n\n save_model = False\n if save_model:\n model_dir = datetime.datetime.now().strftime(\"%Y%m%d%H%M%S\")\n model_path = os.path.join(resources_path(\"trained_models\"), model_dir)\n simple_save(sess,\n model_path,\n inputs={\"x_topic\": x_topic},\n outputs={\"gen_x\": x_fake})\n # save_path = saver.save(sess, os.path.join(model_path, \"model.ckpt\"))\n print(\"Model saved in path: %s\" % model_path)\n\n\ndef topic_discriminator_pretrain(n_topic_pre_epochs, sess, d_topic_pretrain_op, d_topic_loss,\n d_topic_accuracy, x_real, x_topic,\n x_topic_random, oracle_loader,\n d_topic_out_real_pos, d_topic_out_real_neg, topic_discr_pretrain_summary,\n topic_discr_accuracy_summary):\n progress = tqdm(range(n_topic_pre_epochs))\n for epoch in progress:\n # pre-training and write loss\n d_topic_pretrain_loss, accuracy_mean = pre_train_discriminator(sess, d_topic_pretrain_op, d_topic_loss,\n d_topic_accuracy, x_real, x_topic,\n x_topic_random, oracle_loader,\n d_topic_out_real_pos, d_topic_out_real_neg)\n topic_discr_pretrain_summary.write_summary(d_topic_pretrain_loss, epoch)\n topic_discr_accuracy_summary.write_summary(accuracy_mean, epoch)\n progress.set_description('topic_loss: %4.4f, accuracy: %4.4f' % (d_topic_pretrain_loss, accuracy_mean))\n\n\ndef get_losses(generator_obj,\n discriminator_positive_real_pos,\n discriminator_positive_real_neg,\n discriminator_positive_fake,\n discriminator_negative_real_pos,\n discriminator_negative_real_neg,\n discriminator_negative_fake):\n EPS = 1e-10\n with tf.variable_scope(\"standard_GAN_loss\"):\n d_loss_pos_pos = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(\n logits=discriminator_positive_real_pos.logits,\n labels=tf.ones_like(discriminator_positive_real_pos.logits)\n ), name=\"d_loss_pos_pos\")\n d_loss_pos_neg = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(\n logits=discriminator_positive_real_neg.logits,\n labels=tf.zeros_like(discriminator_positive_real_neg.logits)\n ), name=\"d_loss_pos_neg\")\n d_loss_pos_fake = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(\n logits=discriminator_positive_fake.logits, labels=tf.zeros_like(discriminator_positive_fake.logits)\n ), name=\"d_loss_pos_fake\")\n d_loss_pos = d_loss_pos_pos + d_loss_pos_neg + d_loss_pos_fake\n\n d_loss_neg_neg = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(\n logits=discriminator_negative_real_neg.logits,\n labels=tf.ones_like(discriminator_negative_real_neg.logits)\n ), name=\"d_loss_neg_neg\")\n d_loss_neg_pos = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(\n logits=discriminator_negative_real_pos.logits,\n labels=tf.zeros_like(discriminator_negative_real_pos.logits)\n ), name=\"d_loss_neg_pos\")\n d_loss_neg_fake = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(\n logits=discriminator_negative_fake.logits, labels=tf.zeros_like(discriminator_negative_fake.logits)\n ), name=\"d_loss_neg_fake\")\n d_loss_neg = d_loss_neg_neg + d_loss_neg_pos + d_loss_neg_fake\n d_loss = d_loss_neg + d_loss_pos\n\n g_sentence_loss_pos = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(\n logits=discriminator_positive_fake.logits, labels=tf.ones_like(discriminator_positive_fake.logits)\n ), name=\"g_sentence_loss_pos\")\n g_sentence_loss_neg = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(\n logits=discriminator_negative_fake.logits, labels=tf.ones_like(discriminator_negative_fake.logits)\n ), name=\"g_sentence_loss_neg\")\n g_loss = g_sentence_loss_pos + g_sentence_loss_neg\n\n log_pg = tf.reduce_mean(tf.log(generator_obj.gen_o + EPS)) # [1], measures the log p_g(x)\n\n return log_pg, g_loss, d_loss\n","sub_path":"src/real/real_gan/customer_reviews_train.py","file_name":"customer_reviews_train.py","file_ext":"py","file_size_in_byte":18234,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"523687799","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# # LSTM \n# We previously used linear regression\n# to predict future air temp based on past air temp.\n# Here, use LSTM for the same task.\n# Where LinReg viewed each vector as one point,\n# LSTM will view each vector as a time series.\n\n# In[9]:\n\n\nDATAPATH=''\ntry:\n # On Google Drive, set path to my drive / data directory.\n from google.colab import drive\n IN_COLAB = True\n PATH='/content/drive/'\n drive.mount(PATH)\n DATAPATH=PATH+'My Drive/data/' # must end in \"/\"\nexcept:\n # On home computer, set path to local data directory.\n IN_COLAB = False\n DATAPATH='data/' # must end in \"/\"\n\nZIP_FILE='BuildingData.zip'\nZIP_PATH = DATAPATH+ZIP_FILE\nSTEAM_FILE='steam.csv'\nWEATHER_FILE='weather.csv'\nMODEL_FILE='Model' # will be used later to save models\n\n\n# In[10]:\n\n\nfrom os import listdir\nimport csv\nfrom zipfile import ZipFile\nimport numpy as np\nimport pandas as pd\nfrom scipy import stats # mode\n\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.metrics import mean_squared_error\n\nfrom keras.models import Sequential\nfrom keras.layers import SimpleRNN\nfrom keras.layers import LSTM\nfrom keras.layers import TimeDistributed\nfrom keras.layers import Dense\nfrom keras.losses import MeanSquaredError\n\nimport matplotlib.pyplot as plt\nfrom matplotlib import colors\nmycmap = colors.ListedColormap(['red','blue']) # list color for label 0 then 1\nnp.set_printoptions(precision=2)\n\n\n# In[11]:\n\n\ndef read_zip_to_panda(zip_filename,csv_filename):\n zip_handle = ZipFile(zip_filename)\n csv_handle = zip_handle.open(csv_filename)\n panda = pd.read_csv(csv_handle)\n return panda\ndef fix_date_type(panda):\n # Convert the given timestamp column to the pandas datetime data type.\n panda['timestamp'] = pd.to_datetime(panda['timestamp'], infer_datetime_format = True)\n indexed = panda.set_index(['timestamp'])\n return indexed\ndef get_site_timeseries(panda,site):\n # Assume the panda dataframe has a datetime column.\n # (If not, call fix_date_type() before this.)\n # Extract the timeseries for one site.\n # Convert the datetime column to a DatetimeIndex.\n site_df = panda[panda['site_id']==site]\n temp_col = site_df['date']\n temp_val = temp_col.values\n temp_ndx = pd.DatetimeIndex(temp_val)\n dropped = site_df.drop('date',axis=1)\n panda = dropped.set_index(temp_ndx)\n return panda\n\n\n# In[12]:\n\n\nSITE = 'Eagle'\nMETER = 'steam'\nBLDG = 'Eagle_education_Peter' # one example\nPREDICTOR_VARIABLE = 'airTemperature' # for starters\nPREDICTED_VARIABLE = 'steam' # for starters\n\n\n# In[13]:\n\n\nwet_df = read_zip_to_panda(ZIP_PATH,WEATHER_FILE)\nwet_df = fix_date_type(wet_df)\nstm_df = read_zip_to_panda(ZIP_PATH,STEAM_FILE)\nstm_df = fix_date_type(stm_df)\nsite_specific_weather = wet_df.loc[wet_df['site_id'] == SITE]\nall_buildings = [x for x in stm_df.columns if x.startswith(SITE)]\n\n\n# In[14]:\n\n\nDOWNSAMPLE = False # if true, use 1 time per day, else 24 times per day\nSTEPS_HISTORY = 7 \nSTEPS_FUTURE = 1 \ndef smooth(df):\n # For smoothing the 24 hour cycle, we do not want exponential smoothing.\n smoothed = None\n if DOWNSAMPLE:\n # This alternate method samples down to 1/24 time steps.\n smoothed = df.resample(\"24H\").mean() \n else:\n # This method does not reduce the number of time steps.\n # Note the first 23 measurements get set to Nan.\n smoothed=df.rolling(window=24).mean()\n smoothed=smoothed[24:]\n return smoothed\n\n# Correlation is low when buildings have many NaN and 0 meter readings.\n# We will ignore buildings that have >max bad meter readings.\ndef is_usable_column(df,column_name):\n MAX_BAD = 500 \n bad = df[column_name].isin([0]).sum()\n return bad<=MAX_BAD\n\ndef prepare_for_learning(df):\n # This is very slow. Is there a faster way? See...\n # https://stackoverflow.com/questions/27852343/split-python-sequence-time-series-array-into-subsequences-with-overlap\n # X = df.drop(METER,axis=1) # this would use all predictors, just drop the predicted\n X=[]\n y=[]\n predictor_series = df[PREDICTOR_VARIABLE].values\n predicted_series = df[PREDICTED_VARIABLE].values\n for i in range(STEPS_HISTORY,len(df)-STEPS_FUTURE):\n one_predictor = [[p] for p in predictor_series[i-STEPS_HISTORY:i]]\n one_predicted = [[p] for p in predicted_series[i:i+STEPS_FUTURE]]\n X.append(one_predictor)\n y.append(one_predicted)\n # Return two lists of lists of lists.\n # At this point, each data point is a scalar (1D) but RNN expects a vector.\n # 1000 samples * 100 time steps * 1D vector.\n return X,y \n\n\n# In[15]:\n\n\nTIMESTEP_VECTOR_DIMENSION = 1 # we are univariate so far\ndef make_RNN():\n rnn = Sequential([\n LSTM(40,return_sequences=True, \n input_shape=(STEPS_HISTORY,TIMESTEP_VECTOR_DIMENSION)), \n LSTM(20,return_sequences=True),\n LSTM(STEPS_FUTURE) \n ])\n # TimeDistributed(Dense(STEPS_FUTURE)) ???\n rnn = Sequential([\n SimpleRNN(20,return_sequences=True, \n input_shape=(STEPS_HISTORY,TIMESTEP_VECTOR_DIMENSION)), \n SimpleRNN(10,return_sequences=False),\n Dense(STEPS_FUTURE) \n ])\n rnn.compile(optimizer='adam',loss=MeanSquaredError())\n return rnn\n\n\n# In[18]:\n\n\ncors = []\nEPOCHS=50\n# Test on only Peter just during code development\nfor BLDG in all_buildings:\n print(\"Building\",BLDG)\n # Get steam usage for one building.\n bldg_specific_steam = stm_df[[BLDG]]\n # Concatenate steam usage with weather.\n one_bldg_df = pd.concat([bldg_specific_steam,site_specific_weather],axis=1)\n # Drop the site, which is constant (we selected for one site).\n one_bldg_df = one_bldg_df.drop(['site_id'],axis=1)\n # The original steam table used column name = building name.\n # We are processing one building, so rename to the column 'steam'.\n one_bldg_df = one_bldg_df.rename(columns={BLDG : METER})\n # In order to filter bad buildings, count sum of NaN + zero.\n one_bldg_df = one_bldg_df.fillna(0)\n \n if is_usable_column(one_bldg_df,METER):\n one_bldg_df = smooth(one_bldg_df) \n X,y = prepare_for_learning(one_bldg_df)\n # Ideally, split Year1 = train, Year2 = test.\n # Some data is incomplete, so split 1st half and 2nd half.\n split = len(X)//2 \n X_train = np.asarray(X[0:split])\n y_train = np.asarray(y[0:split])\n X_test = np.asarray(X[split:])\n y_test = np.asarray(y[split:])\n print(\"Train on\",len(X_train),\"samples...\")\n model = make_RNN()\n print(model.summary())\n model.fit(X_train,y_train,epochs=EPOCHS)\n y_pred = model.predict(X_test)\n # Compare. Solve the problem that predict.shape != truth.shape \n ##print(\" before ytestshape\",y_test.shape,\"ypredshape\",y_pred.shape)\n nsamples, nsteps, ndim = y_test.shape\n y_test = y_test.reshape(nsamples,nsteps*ndim)\n #nsamples, nsteps, ndim = y_pred.shape\n #y_pred = y_pred.reshape(nsamples,nsteps*ndim)\n ##print(\" after ytestshape\",y_test.shape,\"ypredshape\",y_pred.shape)\n rmse = mean_squared_error(y_test,y_pred,squared=False)\n # Keep a table for reporting later.\n mean = one_bldg_df[METER].mean()\n cor = one_bldg_df.corr().loc[PREDICTED_VARIABLE][PREDICTOR_VARIABLE] \n cors.append([cor,mean,rmse,rmse/mean,BLDG])\n print(\"cor,mean,rmse,rmse/mean,bldg:\",cor,mean,rmse,rmse/mean,BLDG)\n\n ## break ## REMOVE THIS LINE TO LOOP OVER BUILDINGS!\n \nif True:\n print(\"History\",STEPS_HISTORY,\"Future\",STEPS_FUTURE)\n print(\"Column 1: Correlation of\",PREDICTED_VARIABLE,\"and\",PREDICTOR_VARIABLE)\n print(\" Using one weather feature as leading correlate.\")\n print(\"Column 2: Mean usage.\")\n print(\" Using mean to help understand the RMSE.\")\n print(\"Column 3: RMSE of LinearRegression(X=Weather, y=Usage).\")\n print(\"Column 4: RMSE/mean normalized to help understand RMSE.\")\n print(\"Column 5: Building.\")\n for cor in sorted(cors):\n print(\"%7.4f %10.2f %10.2f %5.2f %s\"%(cor[0],cor[1],cor[2],cor[3],cor[4])) \n\n\n# ## Useful Links\n# \n# Jason Brownlee \n# https://machinelearningmastery.com/how-to-develop-lstm-models-for-time-series-forecasting/\n# https://machinelearningmastery.com/multivariate-time-series-forecasting-lstms-keras/\n# https://machinelearningmastery.com/suitability-long-short-term-memory-networks-time-series-forecasting/\n# https://machinelearningmastery.com/autoregression-models-time-series-forecasting-python/\n\n# In[ ]:\n\n\n\n\n","sub_path":"scripts/LSTM_103CL.py","file_name":"LSTM_103CL.py","file_ext":"py","file_size_in_byte":8582,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"488598505","text":"############################################\n#### Evelyn - the Ultimate Puzzle Game ##### \n####### create/draw/update Buttons #########\n############################################\n# cuz tkinter buttons are weird\nfrom tkinter import *\n\nclass FakeButton(object):\n def __init__(self, cx, cy, width, height, text, function, mode, level = None, \n outline=None, bg=None):\n (self.cx, self.cy) = (cx, cy)\n (self.width, self.height) = (width, height)\n self.x0 = self.cx - self.width//2\n self.y0 = self.cy - self.height//2\n self.x1 = self.cx + self.width//2\n self.y1 = self.cy + self.height//2\n self.text = text\n self.level = level\n self.command = function\n self.mode = mode\n self.state = \"outside\"\n if outline == None and bg == None:\n self.bg = '#EAF0F1'\n self.outline = '#4a69bd'\n else:\n self.bg = bg\n self.outline = outline\n self.size = \" 23\"\n self.font = \"Times\"\n\n def handleClick(self, event): \n if (self.inBounds(event.x, event.y)):\n if self.level == None:\n self.command()\n else:\n self.command(self)\n\n def update(self, event): \n #change bg color if the mouse is in a button but hasn't clicked\n self.state = \"outside\"\n if (self.inBounds(event.x,event.y)):\n self.state = \"inside\"\n\n def inBounds(self, x, y): \n #Check if the mouse is within the button\n if (x < self.x0 or x > self.x1 or y < self.y0 or y > self.y1):\n return False\n return True\n\n def draw(self, canvas, data):\n if (self.state == \"inside\"): \n canvas.create_rectangle(self.x0, self.y0, self.x1, self.y1, \n fill=self.outline, outline=self.outline, width = 3)\n else: \n canvas.create_rectangle(self.x0, self.y0, self.x1, self.y1, \n fill=self.bg, outline=self.outline, width = 3)\n canvas.create_text(self.cx, self.cy, text = self.text, font = self.font+self.size)","sub_path":"FakeButton.py","file_name":"FakeButton.py","file_ext":"py","file_size_in_byte":2132,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"567276692","text":"from .dfaState import state\nfrom .min_state import min_state\nfrom .DFA import DFA\nfrom .NodeGenerator import NodeGenerator\nimport queue\nfrom string import ascii_letters\n\nsymbols_list = []\nfor char in ascii_letters:\n symbols_list.append(char)\nfor i in range(0,9):\n symbols_list.append(str(i))\n\nno=0\ndic ={} # for mappinhg same state\ndef check(c):\n no=0\n for i in range(0,len(c.nodes_of_this_class)):\n print(i)\n if not i in dic:\n dic[i]=no\n no += 1\n for j in range(i+1,len(c.nodes_of_this_class)):\n ans = c.is_same(c.nodes_of_this_class[i],c.nodes_of_this_class[j],symbols_list)\n if ans == True:\n dic[j]=dic[i]\n print(dic)\n return no\ndef minimization_states():\n initial_accepted_state=[]\n initial_unaccepted_state=[]\n nothing = []\n number_of_states = len(state.state_instances)\n print(\"number of states\",number_of_states)\n for s in state.state_instances:\n if s.isAccept():\n initial_accepted_state.append(s)\n else:\n initial_unaccepted_state.append(s)\n q = queue.Queue()\n class1 = min_state(initial_unaccepted_state)\n class2 = min_state(initial_accepted_state)\n q.put(class1)\n q.put(class2)\n cnt=0\n class1.map_state_to_id()\n class2.map_state_to_id()\n while(not q.empty()):\n flag=0\n total_flag=0\n c = q.get()\n no= check(c)\n for i in range(1,no):\n l=[]\n\n for keys,values in dic.items():\n if values==i:\n flag=1\n l.append(c.nodes_of_this_class[i])\n c.nodes_of_this_class.pop(i)\n if len(l) != 0:\n class_temp= min_state(l)\n q.put(class_temp)\n class_temp.map_state_to_id()\n\n q.put(c)\n\n if flag ==0:\n cnt+=1;\n else:\n flag=0\n cnt=0\n if cnt == number_of_states:\n break\n dic.clear()\n for ins in min_state.class_instance:\n node= ins.nodes_of_this_class[0]\n for symbol in symbols_list:\n ins.add_destination(symbol,min_state.map_state_to_class[node.destinations[symbol]])\n\n for nodes in ins.nodes_of_this_class:\n if nodes.isAccept() == True :\n ins.accept_state= True\n break\n print(len(min_state.class_instance))\n","sub_path":"tokenizer/minimization.py","file_name":"minimization.py","file_ext":"py","file_size_in_byte":2364,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"566153199","text":"# -*- coding: UTF-8 -*-\n# pylint: disable=wrong-import-position, wrong-import-order\n\"\"\"\nInvoke build script.\nShow all tasks with::\n\n invoke -l\n\n.. seealso::\n\n * http://pyinvoke.org\n * https://github.com/pyinvoke/invoke\n\"\"\"\n\nfrom __future__ import absolute_import, print_function\n\n# -----------------------------------------------------------------------------\n# BOOTSTRAP PATH: Use provided vendor bundle if \"invoke\" is not installed\n# -----------------------------------------------------------------------------\nfrom . import _setup # pylint: disable=wrong-import-order\nimport os.path\nimport sys\nINVOKE_MINVERSION = \"1.2.0\"\n_setup.setup_path()\n_setup.require_invoke_minversion(INVOKE_MINVERSION)\n\nTOPDIR = os.path.join(os.path.dirname(__file__), \"..\")\nTOPDIR = os.path.abspath(TOPDIR)\nsys.path.insert(0, TOPDIR)\n\n# -----------------------------------------------------------------------------\n# IMPORTS:\n# -----------------------------------------------------------------------------\n# import sys\nfrom invoke import task, Collection\nfrom invoke.util import cd\n\n# -- TASK-LIBRARY:\n# from . import clean\nfrom . import invoke_cleanup as cleanup\nfrom . import test\nfrom cmake_build import tasks as cmake_build\n# DISABLED: from . import docs\n# DISABLED: from . import release\n\n# -----------------------------------------------------------------------------\n# TASKS:\n# -----------------------------------------------------------------------------\n@task\ndef init(ctx):\n \"\"\"Initialize everything.\"\"\"\n cmake_build.init(ctx)\n\n\n@task\ndef reinit(ctx):\n \"\"\"Reinitialize everything.\"\"\"\n cleanup.clean(ctx)\n init(ctx)\n\n@task(aliases=[\"examples\"])\ndef cmake_examples(ctx, build_config=None):\n \"\"\"Build CMake examples.\"\"\"\n build_config = build_config or \"Debug\"\n with cd(\"examples/\"):\n ctx.run(\"make BUILD_CONFIG={0}\".format(build_config))\n\n\n# -----------------------------------------------------------------------------\n# TASK CONFIGURATION:\n# -----------------------------------------------------------------------------\nnamespace = Collection()\nnamespace.add_collection(Collection.from_module(cleanup), name=\"cleanup\")\nnamespace.add_task(init)\nnamespace.add_task(reinit)\nnamespace.add_task(cmake_examples)\nnamespace.add_collection(Collection.from_module(test))\nnamespace.add_collection(Collection.from_module(cmake_build, name=\"cmake\"))\n# DISABLED: namespace.add_collection(Collection.from_module(docs))\n# DISABLED: namespace.add_collection(Collection.from_module(release))\n\ncleanup.cleanup_tasks.add_task(cleanup.clean_python)\n\n# -- INJECT: clean configuration into this namespace\nnamespace.configure(cleanup.namespace.configuration())\nif sys.platform.startswith(\"win\"):\n # -- OVERRIDE SETTINGS: For platform=win32, ... (Windows)\n from ._compat_shutil import which\n run_settings = dict(echo=True, pty=False, shell=which(\"cmd\"))\n namespace.configure({\"run\": run_settings})\nelse:\n namespace.configure({\"run\": dict(echo=True, pty=True)})\n","sub_path":"tasks/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2983,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"446206440","text":"# https://www.acmicpc.net/problem/1541\r\n# 잃어버린 괄호\r\n\r\nimport sys\r\n\r\nA = sys.stdin.readline().strip().split('-')\r\n\r\nnum = []\r\nfor item in A:\r\n count = 0\r\n elements = item.split('+')\r\n for e in elements:\r\n count += int(e)\r\n \r\n num.append(count)\r\n\r\ntotal = num[0]\r\nfor i in range(1, len(num)):\r\n total -= num[i]\r\n\r\nprint(total)","sub_path":"Greedy Algorithm/1541.py","file_name":"1541.py","file_ext":"py","file_size_in_byte":360,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"645861120","text":"import math\nimport argparse\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\n\nparser = argparse.ArgumentParser(prog='plot.py', description='MLDS2018 hw1-1.1 Stimulate Functions')\nparser.add_argument('--sr', type=int, default=1000)\nparser.add_argument('--rng', type=list, default=[0., 5.])\n\nparser.add_argument('--mode', type=str, default='hw1-1-1')\nparser.add_argument('--func', type=str, default='damping')\nparser.add_argument('--save_dir', type=str, default='./')\nparser.add_argument('--result_dir', type=str, default='./')\nargs = parser.parse_args()\n\nif args.mode == 'hw1-1-1':\n def target_func(x):\n if args.func == 'damping': return math.exp(-x) * math.cos(2 * math.pi * x)\n elif args.func == 'triangle': return 1. if x % 2 < 1 else 0.\n\n if args.func == 'damping':\n collection = {'shallow': args.result_dir + 'damping_shallow.csv',\n 'medium' : args.result_dir + 'damping_medium.csv', \n 'deep' : args.result_dir + 'damping_deep.csv' }\n\n elif args.func == 'triangle':\n collection = {'shallow': args.result_dir + 'triangle_shallow.csv', \n 'medium' : args.result_dir + 'triangle_medium.csv', \n 'deep' : args.result_dir + 'triangle_deep.csv' }\n\n plt.figure()\n\n for model, path in collection.items():\n pltfile = open(path, 'r')\n data = pd.read_csv(pltfile)\n x, y = data['x'].values, data['f(x)'].values\n plt.plot(x, y, label=model)\n\n x = np.arange(*args.rng, 1 / args.sr, dtype=np.float32)\n y = np.array([target_func(i) for i in x], dtype=np.float32)\n plt.plot(x, y, label='origin')\n\n plt.xlabel('x')\n plt.ylabel('f(x)')\n\n if args.func == 'damping':\n plt.title('Damping Function')\n plt.legend()\n plt.savefig(args.result_dir + 'damping.png')\n\n elif args.func == 'triangle':\n plt.title('Triangle Wave Function')\n plt.legend()\n plt.savefig(args.result_dir + 'triangle.png')\n\n \n\n if args.func == 'damping':\n collection = {'shallow': args.save_dir + 'damping_shallow_loss.csv', \n 'medium' : args.save_dir + 'damping_medium_loss.csv', \n 'deep' : args.save_dir + 'damping_deep_loss.csv' }\n\n elif args.func == 'triangle':\n collection = {'shallow': args.save_dir +'triangle_shallow_loss.csv', \n 'medium' : args.save_dir +'triangle_medium_loss.csv', \n 'deep' : args.save_dir +'triangle_deep_loss.csv' }\n\n plt.figure()\n\n for model, path in collection.items():\n pltfile = open(path, 'r')\n data = pd.read_csv(pltfile)\n x, y = data['epoch'].values, data['loss'].values\n plt.plot(x, y, label=model)\n\n plt.xlabel('# of Epochs')\n plt.ylabel('Training Loss')\n\n if args.func == 'damping':\n plt.title('Damping Function')\n plt.legend()\n plt.savefig(args.result_dir +'damping_loss.png')\n\n elif args.func == 'triangle':\n plt.title('Triangle Wave Function')\n plt.legend()\n plt.savefig(args.result_dir + 'triangle_loss.png')\n\n\n\nif args.mode == 'hw1-2-3':\n pltfile = open(args.save_dir + 'minimal_ratio_loss.csv', 'r')\n data = pd.read_csv(pltfile)\n x, y = data['minimal ratio'].values, data['loss'].values\n plt.plot(x, y, '.')\n\n plt.xlabel('minimal ratio')\n plt.ylabel('loss')\n plt.title('Damping Function')\n plt.savefig(args.result_dir + 'minimal_ratio.png')\n\n\n\nif args.mode == 'hw1-3-3-part2':\n pltfile = open(args.save_dir + 'sensitivity_loss.csv', 'r')\n data = pd.read_csv(pltfile)\n x = data['batch'].values\n y1 = data['sensitivity'].values\n y2 = data['testing loss'].values\n y3 = data['training loss'].values\n\n fig = plt.figure()\n ax1 = fig.add_subplot(111)\n ax1.set_xscale('log', nonposx='clip')\n ax1.set_yscale('log', nonposy='clip')\n ax1.plot(x, y3, 'b',label='train' )\n ax1.plot(x, y2, '--b', label='test')\n ax1.set_ylabel('cross entropy (log scale)')\n ax1.set_xlabel('batch size (log scale)')\n ax1.yaxis.label.set_color('blue')\n ax1.tick_params(axis='y', colors='blue')\n ax1.legend(loc=2)\n\n ax2 = ax1.twinx()\n ax2.set_xscale('log', nonposx='clip')\n ax2.plot(x, y1, 'r', label='sensitivity')\n ax2.set_ylabel('sensitivity')\n ax2.set_xlabel('batch size (log scale)')\n ax2.yaxis.label.set_color('red')\n ax2.tick_params(axis='y', colors='red')\n ax2.legend(loc=1)\n\n plt.savefig(args.result_dir + 'sensitivity_loss.png')\n\n\n\n y2 = data['testing accuracy'].values\n y3 = data['training accuracy'].values\n\n fig = plt.figure()\n ax1 = fig.add_subplot(111)\n ax1.set_xscale('log', nonposx='clip')\n ax1.plot(x, y3, 'b',label='train' )\n ax1.plot(x, y2, '--b', label='test')\n ax1.set_ylabel('accuracy')\n ax1.set_xlabel('batch size (log scale)')\n ax1.yaxis.label.set_color('blue')\n ax1.tick_params(axis='y', colors='blue')\n ax1.legend(loc=2)\n\n ax2 = ax1.twinx()\n ax2.set_xscale('log', nonposx='clip')\n ax2.plot(x, y1, 'r', label='sensitivity')\n ax2.set_ylabel('sensitivity')\n ax2.set_xlabel('batch size (log scale)')\n ax2.yaxis.label.set_color('red')\n ax2.tick_params(axis='y', colors='red')\n ax2.legend(loc=1)\n\n plt.savefig(args.result_dir + 'sensitivity_acc.png')\n","sub_path":"hw1/plot.py","file_name":"plot.py","file_ext":"py","file_size_in_byte":5342,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"307922199","text":"#!/usr/bin/env python3\n\nimport tensorflow as tf\nimport numpy as np\n\n\"\"\"\ninputs:\n\n 00111001\n+ 01000111\n-------------\n 10000000\n\n\ninputs:\n1 0 0 1 1 1 0 0\n1 1 1 0 0 0 1 0\n\nlabels:\n0 0 0 0 0 0 0 1\n\n\"\"\"\n\n\ndef main(_):\n input_dim = 2\n output_dim = 1\n time_length = 8\n hidden_dim = 20\n batch_size = 5\n\n inputs = tf.placeholder(dtype=tf.float32,\n shape=[time_length, batch_size , input_dim])\n labels = tf.placeholder(dtype=tf.float32,\n shape=[time_length, batch_size, output_dim])\n\n test_inputs = tf.placeholder(dtype=tf.float32,\n shape=[time_length, 1, input_dim])\n\n with tf.device('/gpu:0'):\n weights = {\n 'i_h': tf.Variable(tf.random_normal([input_dim + hidden_dim, hidden_dim])),\n 'h_o': tf.Variable(tf.random_normal([hidden_dim, output_dim]))\n }\n biases = {\n 'i_h': tf.Variable(tf.zeros([hidden_dim])),\n 'h_o': tf.Variable(tf.zeros([output_dim]))\n }\n memory = tf.Variable(tf.zeros([batch_size, hidden_dim]))\n\n loss_op = tf.Variable(initial_value=0.0)\n \n for i in range(time_length):\n concat_input = tf.concat([inputs[i], memory], 1)\n logits = tf.add(tf.matmul(concat_input, weights['i_h']), biases['i_h'])\n memory = activated = tf.sigmoid(logits)\n out_logits = tf.add(tf.matmul(activated, weights['h_o']), biases['h_o'])\n \n loss_op += tf.reduce_mean(\n tf.nn.sigmoid_cross_entropy_with_logits(labels=labels[i],\n logits=out_logits)\n )\n \n test_memory = tf.Variable(tf.zeros([1, hidden_dim]), trainable=False)\n test_outputs = []\n for i in range(time_length):\n test_concat_input = tf.concat([test_inputs[i], test_memory], 1)\n test_logits = tf.add(tf.matmul(test_concat_input, weights['i_h']), biases['i_h'])\n test_memory = test_activated = tf.sigmoid(test_logits)\n test_out_logits = tf.add(tf.matmul(test_activated, weights['h_o']), biases['h_o'])\n test_outputs.append(tf.sigmoid(test_out_logits))\n \n\n train_op = tf.train.GradientDescentOptimizer(learning_rate=0.3).minimize(loss_op)\n\n init = tf.global_variables_initializer()\n\n\n data = np.load(open('data.npz', 'rb'))\n train_samples = data['samples']\n train_labels = data['labels']\n \n with tf.Session() as sess:\n sess.run(init)\n num_epoch = 10000\n\n for cur_epoch in range(num_epoch):\n total_loss = 0\n step_rounds = np.shape(train_samples)[1] // batch_size\n for i in range(step_rounds):\n cur_samples = train_samples[:, i * batch_size : (i+1) * batch_size, :]\n cur_labels = train_labels[:, i * batch_size : (i+1) * batch_size]\n _, loss = sess.run([train_op, loss_op], {inputs: cur_samples, labels: cur_labels})\n total_loss += loss\n total_loss /= step_rounds\n print('loss: {}'.format(total_loss))\n\n # 01001111\n # 01001101\n #=10011100\n test_input = [[[1, 1]], [[1, 0]], [[1, 1]], [[1, 1]], [[0, 0]], [[0, 0]], [[1, 1]], [[0, 0]]]\n gg = sess.run(test_outputs, {test_inputs: test_input})\n print(gg)\n\n\nif __name__ == '__main__':\n tf.app.run()\n","sub_path":"elman.py","file_name":"elman.py","file_ext":"py","file_size_in_byte":3352,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"9185406","text":"#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n# __author__ = Lyon\n\n\"\"\"\nPeewee Document : http://docs.peewee-orm.com/en/latest/\nPeewee-async Document : https://peewee-async.readthedocs.io/en/latest/index.html\n\"\"\"\n\nfrom lib.dt import dt\nfrom base import config\nfrom peewee import Model, AutoField, DateTimeField, IntegerField, Query\nfrom peewee_async import Manager as BaseManager, PooledMySQLDatabase\n\n# Connect to a MySQL database on network.\nmysql_db = PooledMySQLDatabase(\n config.MYSQL_CONFIG['db'],\n max_connections=config.MYSQL_CONFIG['max_connections'],\n user=config.MYSQL_CONFIG['username'],\n password=config.MYSQL_CONFIG['password'],\n host=config.MYSQL_CONFIG['host'],\n port=config.MYSQL_CONFIG['port']\n)\n\n\nclass Manager(BaseManager):\n async def get(self, source_, *args, **kwargs):\n \"\"\"Get the model instance or ``None`` if not found.\n :param source_: model or base query for lookup\n\n Example::\n\n async def my_async_func():\n obj1 = await objects.get(MyModel, id=1)\n obj2 = await objects.get(MyModel, MyModel.id==1)\n obj3 = await objects.get(MyModel.select().where(MyModel.id==1))\n\n All will return `MyModel` instance with `id = 1`\n \"\"\"\n await self.connect()\n\n if isinstance(source_, Query):\n query = source_\n model = query.model\n else:\n query = source_.select()\n model = source_\n\n conditions = list(args) + [(getattr(model, k) == v)\n for k, v in kwargs.items()]\n\n if conditions:\n query = query.where(*conditions)\n\n try:\n result = await self.execute(query)\n return list(result)[0]\n except IndexError:\n return None\n\n\nclass MySQLModel(Model):\n \"\"\"MySQL BaseModel\"\"\"\n\n # async\n objects = Manager(mysql_db)\n\n DELETE_NO = 0\n DELETE_IS = 1\n\n DELETE_CHOICES = (\n (0, '未删除'),\n (1, '已删除'),\n )\n\n class Meta:\n database = mysql_db\n\n id = AutoField()\n create_time = DateTimeField(default=dt.now, verbose_name='创建时间')\n update_time = DateTimeField(default=dt.now, verbose_name='更新时间')\n is_delete = IntegerField(default=DELETE_NO, choices=DELETE_CHOICES, verbose_name='是否删除')\n\n @classmethod\n async def execute_sql(cls, sql, *params):\n \"\"\"async execute sql\"\"\"\n return await cls.objects.execute(cls.raw(sql, *params))\n\n @classmethod\n async def async_execute(cls, query):\n \"\"\"async execute sql\"\"\"\n return await cls.objects.execute(query)\n\n @classmethod\n async def async_get(cls, *args, **kwargs):\n return await cls.objects.get(cls, *args, **kwargs)\n\n @classmethod\n async def async_select(cls, *fields):\n return await cls.objects.execute(cls.select(*fields))\n\n @classmethod\n async def async_count(cls, query, clear_limit=False):\n return await cls.objects.count(query, clear_limit)\n\n @classmethod\n async def async_create(cls, **kwargs):\n \"\"\"Create object\n :param kwargs:\n :return:\n \"\"\"\n for field, value in kwargs.items():\n if not hasattr(cls, field):\n raise AttributeError(\"%s object has no attribute %s\" % (cls.__name__, field))\n return await cls.objects.create(cls, **kwargs)\n\n async def async_update(self, **kwargs):\n \"\"\"Update object\n :param kwargs:\n :return:\n \"\"\"\n for field, value in kwargs.items():\n if hasattr(self, field):\n if getattr(self, field) != value:\n setattr(self, field, value)\n else:\n raise AttributeError(\"%s object has no attribute %s\" % (self.__class__.__name__, field))\n return await self.objects.update(self)\n\n async def async_delete(self):\n \"\"\"Soft delete, `DELETE_NO` -> `DELETE_IS`\n :return:\n \"\"\"\n self.is_delete = self.DELETE_IS\n return await self.objects.update(self)\n\n def normal_info(self):\n return {\n 'id': self.id,\n 'create_time': self.datetime_to_str(self.create_time),\n 'update_time': self.datetime_to_str(self.update_time),\n 'is_delete': self.is_delete,\n }\n\n def date_to_str(self, datetime):\n return dt.dt_to_str(datetime, \"%Y-%m-%d\")\n\n def datetime_to_str(self, datetime):\n return dt.dt_to_str(datetime)\n\n # Using transactions\n # Documents: https://peewee-async.readthedocs.io/en/latest/peewee_async/examples.html#using-both-sync-and-async-calls\n \"\"\"\n async def test(self):\n import peewee_async\n obj = await self.objects.create(TestModel, text='FOO')\n obj_id = obj.id\n\n try:\n async with self.database.atomic_async():\n obj.text = 'BAR'\n await self.objects.update(obj)\n raise Exception('Fake error')\n except:\n res = await self.objects.get(TestModel, TestModel.id == obj_id)\n\n print(res.text) # Should print 'FOO', not 'BAR'\n \"\"\"","sub_path":"base/db/mysql.py","file_name":"mysql.py","file_ext":"py","file_size_in_byte":5139,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"370218979","text":"# OO_Calculator\n\nfrom graphics import *\n\n# CalculatorGraphics.py\n\n\"\"\"\ndef main():\n equation = input(\"Please enter an equation (use spaces):\")\n listEquation = equation.split()\n result = solveEquation(listEquation)\n print(result)\n\"\"\"\n\n\ndef modifyEquation(idx, eq, value):\n # remove the two operands and the operqator\n del eq[idx - 1:idx + 2]\n # insert the result\n eq.insert(idx - 1, value)\n # move the index back one place\n idx = idx - 1\n return idx, eq\n\n\ndef solveEquation(eq):\n eq = eq.split()\n opIdx = 1\n while '*' in eq or '/' in eq:\n if eq[opIdx] == '*':\n # calculate the operation\n result = float(eq[opIdx - 1]) * float(eq[opIdx + 1])\n # update the equation list\n opIdx, eq = modifyEquation(opIdx, eq, result)\n elif eq[opIdx] == '/':\n result = float(eq[opIdx - 1]) / float(eq[opIdx + 1])\n opIdx, eq = modifyEquation(opIdx, eq, result)\n else:\n opIdx = opIdx + 1\n if opIdx >= len(eq):\n break\n opIdx = 1\n while '+' in eq or '-' in eq:\n if eq[opIdx] == '+':\n result = float(eq[opIdx - 1]) + float(eq[opIdx + 1])\n opIdx, eq = modifyEquation(opIdx, eq, result)\n elif eq[opIdx] == '-':\n result = float(eq[opIdx - 1]) - float(eq[opIdx + 1])\n opIdx, eq = modifyEquation(opIdx, eq, result)\n else:\n opIdx = opIdx + 1\n if opIdx >= len(eq):\n break\n return eq[0]\n\n\ndef createButton(values):\n p1 = Point(values[0], values[1])\n p2 = Point(values[0] + .9, values[1] + .9)\n button = Rectangle(p1, p2)\n button.setFill(\"lightblue\")\n label = Text(Point(values[0] + .5, values[1] + .5), values[2])\n label.setStyle(\"bold\")\n return button, label\n\n\ndef createKeypad(lst):\n keys = []\n for key in lst:\n button, label = createButton(key)\n keys.append([button, label])\n return keys\n\n\ndef renderKeys(keys, win):\n for key in keys:\n key[0].draw(win)\n key[1].draw(win)\n\n\ndef getInputs(w):\n m = w.getMouse()\n return m\n\n\ndef checkInput(inp):\n while True:\n if 1 > inp.getX() >= 0 and 1 > inp.getY() >= 0:\n return \"+/-\"\n elif 2 > inp.getX() >= 1 and 1 > inp.getY() >= 0:\n return \"0\"\n elif 3 > inp.getX() >= 2 and 1 > inp.getY() >= 0:\n return \".\"\n elif 4 > inp.getX() >= 3 and 1 > inp.getY() >= 0:\n return \"=\"\n elif inp.getX() >= 4 and 1 > inp.getY() >=0:\n return \"M+\"\n elif 1 > inp.getX() >= 0 and 2 > inp.getY() >= 1:\n return \"1\"\n elif 2 > inp.getX() >= 1 and 2 > inp.getY() >= 1:\n return \"2\"\n elif 3 > inp.getX() >= 2 and 2 > inp.getY() >= 1:\n return \"3\"\n elif 4 > inp.getX() >= 3 and 2 > inp.getY() >= 1:\n return \"+\"\n elif inp.getX() >= 4 and 2 > inp.getY() >= 1:\n return \"M-\"\n elif 1 > inp.getX() >= 0 and 3 > inp.getY() >= 2:\n return \"4\"\n elif 2 > inp.getX() >= 1 and 3 > inp.getY() >= 2:\n return \"5\"\n elif 3 > inp.getX() >= 2 and 3 > inp.getY() >= 2:\n return \"6\"\n elif 4 > inp.getX() >= 3 and 3 > inp.getY() >= 2:\n return \"-\"\n elif inp.getX() >= 4 and 3 > inp.getY() >= 2:\n return \"MR\"\n elif 1 > inp.getX() >= 0 and 4 > inp.getY() >= 3:\n return \"7\"\n elif 2 > inp.getX() >= 1 and 4 > inp.getY() >= 3:\n return \"8\"\n elif 3 > inp.getX() >= 2 and 4 > inp.getY() >= 3:\n return \"9\"\n elif 4 > inp.getX() >= 3 and 3 <= inp.getY() < 4:\n return \"*\"\n elif 4 > inp.getX() >= 3 and inp.getY() >= 4:\n return \"/\"\n elif inp.getX() >= 4 and 3 <= inp.getY() < 4:\n return \"MC\"\n\n\ndef disp(eq, w):\n tcoorx = Point(0, 4)\n tcoory = Point(2.9, 5)\n tbox = Rectangle(tcoorx, tcoory)\n tbox.setFill(\"yellow\")\n tbox.draw(w)\n\n coords = Point(1.4, 4.5)\n e = Text(coords, eq)\n e.draw(w)\n\n\ndef main():\n keyList = [[0, 0, '+/-'], [1, 0, '0'], [2, 0, '.'], [3, 0, '='], [4, 0, 'M+'],\n [0, 1, '1'], [1, 1, '2'], [2, 1, '3'], [3, 1, '+'], [4, 1, 'M-'],\n [0, 2, '4'], [1, 2, '5'], [2, 2, '6'], [3, 2, '-'], [4, 2, 'MR'],\n [0, 3, '7'], [1, 3, '8'], [2, 3, '9'], [3, 3, 'x'], [4, 3, 'MC'],\n [0, 4, ''], [1, 4, ''], [2, 4, ''], [3, 4, '/']]\n\n keys = createKeypad(keyList)\n\n equation = \"\"\n negative = False\n\n win = GraphWin(\"Key Pad\")\n win.setCoords(0.0, 0.0, 5.0, 5.0)\n win.setBackground(\"navy\")\n\n renderKeys(keys, win)\n\n tcoordx = Point(0,4)\n tcoordy = Point(2.9,5)\n textbox = Rectangle(tcoordx, tcoordy)\n textbox.setFill(\"yellow\")\n textbox.draw(win)\n\n mem = ''\n\n while True:\n user = checkInput(getInputs(win))\n try:\n int(user)\n equation = equation + user\n disp(equation, win)\n except:\n if user == \"+/-\" and negative:\n negative = False\n elif user == \"+/-\" and not negative:\n negative = True\n elif user == \"M+\":\n if mem == \"\":\n mem = equation\n else:\n mem = mem + \"+ \" + equation + \" \"\n equation = ''\n elif user == \"M-\":\n if mem == \"\":\n mem = equation\n else:\n mem = mem + \"- \" + equation + \" \"\n equation = ''\n elif user == \"MR\":\n equation = mem\n disp(equation, win)\n elif user == \"MC\":\n mem = ''\n elif user == '.':\n equation = equation + \".\"\n elif user == \"=\":\n try:\n equation = solveEquation(equation)\n disp(equation, win)\n equation = ''\n except:\n equation = ''\n disp(equation, win)\n else:\n if equation == \"\":\n user = None\n else:\n equation = equation + \" \" + user + \" \"\n disp(equation, win)\n if negative:\n equation = \"-\" + equation\n disp(equation, win)\n print(\"Equation: \")\n print(equation)\n print(\"Memory: \")\n print(mem)\n\n\nmain()\n","sub_path":"calc_functions.py","file_name":"calc_functions.py","file_ext":"py","file_size_in_byte":6474,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"384510207","text":"import requests\nimport random\nimport datetime\n\nfrom pyramid.response import Response\nfrom pyramid.view import view_config\nfrom pyramid.httpexceptions import HTTPFound\nimport pyramid.threadlocal\n\nfrom sqlalchemy.exc import DBAPIError\nfrom sqlalchemy import func\nimport transaction\n\nfrom .models import (\n DBSession,\n Vote,\n VoteSession,\n )\n\nclass ApiRequest(object):\n def __init__(self):\n registry = pyramid.threadlocal.get_current_registry()\n settings = registry.settings\n self.api_url = settings['api_url']\n self.session = requests.Session()\n\n def get(self, path, *args, **kwargs):\n return self.session.get(self.api_url + path, **kwargs)\n\ndef get_cards(left_id, right_id):\n ret = dict()\n r = ApiRequest()\n ret['left'] = r.get('/api/cards/' + str(left_id) + '/?imagedefault=True').json()\n ret['right'] = r.get('/api/cards/' + str(right_id) + '/?imagedefault=True').json()\n ret['idolized_left'] = random.choice([True, False])\n ret['idolized_right'] = random.choice([True, False])\n return ret\n\ndef filter_two_random_cards(*args, **kwargs):\n r = ApiRequest()\n cards = r.get('/api/cardids', *args, **kwargs).json()\n left_id = random.choice(cards)\n right_id = random.choice(cards)\n while (left_id == right_id):\n right_id = random.choice(cards)\n return get_cards(left_id, right_id)\n\ndef pick_two_random_cards():\n r = ApiRequest()\n cards = r.get('/api/cards', params={'page_size': 1}).json()\n left_id = random.randint(1, cards['count'])\n right_id = random.randint(1, cards['count'])\n while (left_id == right_id):\n right_id = random.randint(1, cards['count'])\n return get_cards(left_id, right_id)\n\n@view_config(route_name='home', renderer='templates/home.jinja2')\ndef my_view(request):\n session = request.session\n cards = pick_two_random_cards()\n\n with transaction.manager:\n model = VoteSession(left_id = cards['left']['id'],\n right_id = cards['right']['id'],\n left_name = cards['left']['name'],\n right_name = cards['right']['name'],\n left_rarity = cards['left']['rarity'],\n right_rarity = cards['right']['rarity'],\n left_idolized = cards['idolized_left'],\n right_idolized = cards['idolized_right'],\n created = datetime.datetime.now(),\n contest = 0)\n DBSession.add(model)\n DBSession.flush()\n session['id'] = model.id\n token = session.new_csrf_token()\n registry = pyramid.threadlocal.get_current_registry()\n settings = registry.settings\n return {\n 'cards': cards,\n 'url_prefix': settings['url_prefix'],\n 'csrf_token': token,\n }\n\n@view_config(route_name='vote')\ndef vote_view(request):\n registry = pyramid.threadlocal.get_current_registry()\n settings = registry.settings\n session = request.session\n if ('left' or 'right' in request.params) and 'id' in session:\n token = session.get_csrf_token()\n if token != request.POST['csrf_token']:\n return HTTPFound(location=settings['url_prefix'])\n with transaction.manager:\n vote = DBSession.query(VoteSession).filter_by(id=session['id']).first()\n if not vote:\n return HTTPFound(location=settings['url_prefix'])\n card_id = vote.left_id if 'left' in request.params else vote.right_id\n name = vote.left_name if 'left' in request.params else vote.right_name\n rarity = vote.left_rarity if 'left' in request.params else vote.right_rarity\n idolized = vote.left_idolized if 'left' in request.params else vote.right_idolized\n id_contest = vote.contest\n DBSession.delete(vote)\n req = DBSession.query(Vote).filter_by(id_card=card_id,\n id_contest=id_contest,\n idolized=idolized).first()\n if not req:\n model = Vote(id_card=card_id, id_contest=id_contest,\n name=name, counter=1, rarity=rarity, idolized=idolized)\n DBSession.add(model)\n else:\n req.counter += 1\n DBSession.add(req)\n session.invalidate()\n return HTTPFound(location=settings['url_prefix'])\n\ndef count_by_name():\n r = ApiRequest()\n req = DBSession.query(Vote,\n func.sum(Vote.counter).label('counter_all')).group_by(Vote.name).order_by('counter_all DESC').all()\n l = [(i.idolized, r.get('/api/cards/' + str(i.id_card) +\n '/?imagedefault=True').json(), c) for (i, c) in req[:10]]\n return l\n\ndef count_by_id():\n r = ApiRequest()\n req = DBSession.query(Vote).order_by('counter DESC').all()\n l = [(i.idolized, r.get('/api/cards/' + str(i.id_card) +\n '/?imagedefault=True').json(), i.counter) for i in req[:10]]\n return l\n\n@view_config(route_name='bestgirl', renderer='templates/bestgirl.jinja2')\ndef best_girl_view(request):\n list_card = count_by_id()\n list_girl = count_by_name()\n registry = pyramid.threadlocal.get_current_registry()\n settings = registry.settings\n return {\n 'list_card': enumerate(list_card),\n 'list_girl': enumerate(list_girl),\n 'url_prefix': settings['url_prefix'],\n }\n\n\nconn_err_msg = \"\"\"\\\nPyramid is having a problem using your SQL database. The problem\nmight be caused by one of the following things:\n\n1. You may need to run the \"initialize_SchoolIdolContest_db\" script\n to initialize your database tables. Check your virtual\n environment's \"bin\" directory for this script and try to run it.\n\n2. Your database server may not be running. Check that the\n database server referred to by the \"sqlalchemy.url\" setting in\n your \"development.ini\" file is running.\n\nAfter you fix the problem, please restart the Pyramid application to\ntry it again.\n\"\"\"\n","sub_path":"schoolidolcontest/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":6107,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"498777169","text":"def solution(s):\n stack = []\n if len(s) < 2:\n return 0\n \n for _s in s:\n if len(stack) == 0:\n stack.append(_s)\n else:\n if stack[-1] == _s:\n stack.pop() \n elif stack[-1] != _s:\n stack.append(_s)\n \n if len(stack) > 0:\n answer = 0\n else:\n answer = 1 \n return answer\n\n# 테스트용\nsen = [\"baabaa\", \"cdcd\"]\nfor _s in sen:\n print(solution(_s))\n","sub_path":"programmers_0211.py","file_name":"programmers_0211.py","file_ext":"py","file_size_in_byte":480,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"523954901","text":"from __future__ import absolute_import\n\n# import sys\n# sys.path.append('./')\n\nimport os\nimport os.path as osp\n# import moxing as mox\n\nimport pickle\nfrom tqdm import tqdm\nfrom PIL import Image, ImageFile\nimport numpy as np\nimport random\nimport cv2\nimport lmdb\nimport sys\nimport six\n\nimport torch\nfrom torch.utils import data\nfrom torch.utils.data import sampler\nfrom torchvision import transforms\n\nfrom lib.utils import fileutils\n\nfrom imgaug import augmenters as iaa\nimport imgaug as ia\nimport imageio\n\n\nImageFile.LOAD_TRUNCATED_IMAGES = True\n\n\nclass Dataset(data.Dataset):\n def __init__(self, root='/home/liming/chenhan/project/pipe/result/DL-based-findcenter/data_txt',\n num_samples=500, height=1280, width=1960, is_train=False, transform=None):\n super(Dataset, self).__init__()\n\n self.transform = transform\n self.is_train = is_train\n self.width = width\n self.height = height\n self.augment = None\n\n self.data_root = root\n\n num_txt_p = osp.join(root,'num.txt')\n with open(num_txt_p,'r') as f:\n num = f.readline()\n num = num.strip()\n\n self.nSamples = int(num)\n self.nSamples = min(self.nSamples, num_samples)\n\n # if self.is_train:\n # self.augment = iaa.Sequential([\n # iaa.MotionBlur(k=5, angle=45),\n # iaa.CropAndPad(percent=(-0.2, 0.2), pad_mode=\"edge\"),\n # iaa.AdditiveGaussianNoise(scale=(0, 0.05*255)),\n # # iaa.SaltAndPepper(0.2,per_channel=True), \n # # iaa.AddToHueAndSaturation((-60, 60)),\n # iaa.MultiplyBrightness((0.5, 1.5)),\n # iaa.Affine(rotate=(-180, 180)),\n # iaa.pillike.EnhanceSharpness(),\n # # iaa.pillike.EnhanceColor(),\n # iaa.Dropout(p=(0, 0.1))\n # ], random_order=True)\n\n def __len__(self):\n return self.nSamples\n\n def __getitem__(self, index):\n assert index <= self.nSamples, 'index range error'\n\n index += 1\n\n try:\n img_root_i = osp.join(self.data_root,str(index)+'.txt')\n with open(img_root_i,'r') as f:\n lines = f.readlines()\n js_p = lines[0].strip()\n img_p = lines[1].strip()\n img = Image.open(img_p)\n img = img.convert(\"RGB\")\n except IOError:\n print('Corrupted image for %d' % index)\n return self[index+1]\n \n ori_w, ori_h = img.size\n img = img.resize((self.width,self.height))\n try:\n pt = fileutils.red_json(js_p)\n pt[0] = pt[0]/ori_w*self.width\n pt[1] = pt[1]/ori_h*self.height\n except IndexError:\n return self[index+1]\n pt_x = pt[0] \n pt_y = pt[1] \n\n # fileutils.test_point(img,pt[0],pt[1],index,tag='ori')\n\n if self.is_train:\n self.augment = iaa.Sequential([\n iaa.MotionBlur(k=5, angle=45),\n iaa.CropAndPad(percent=(-0.2, 0.2), pad_mode=\"edge\"),\n iaa.AdditiveGaussianNoise(scale=(0, 0.05*255)),\n iaa.SaltAndPepper(0.2,per_channel=True), \n iaa.AddToHueAndSaturation((-60, 60)),\n iaa.MultiplyBrightness((0.5, 1.5)),\n iaa.Affine(rotate=(-180, 180)),\n iaa.pillike.EnhanceSharpness(),\n iaa.pillike.EnhanceColor(),\n iaa.Dropout(p=(0, 0.1))\n ], random_order=True)\n\n kps = [\n ia.Keypoint(x=pt[0], y=pt[1]),\n ]\n\n if random.uniform(0,1) < 0.2:\n pt_x = pt[0]\n pt_y = pt[1]\n else:\n img = np.asarray(img, dtype=np.uint8)\n\n kpsoi = ia.KeypointsOnImage(kps, shape=img.shape)\n aug_det = self.augment.to_deterministic()\n img = aug_det.augment_image(img)\n pt_aug = aug_det.augment_keypoints(kpsoi)\n \n # img = self.augment(image = img)\n img = Image.fromarray(img)\n pt_x = pt_aug[0].x_int\n pt_y = pt_aug[0].y_int\n\n # fileutils.test_point(img,pt_x,pt_y,index)\n # img.save('seeee_'+str(index)+'_.jpg')\n\n if self.transform is not None:\n img = self.transform(img)\n\n return img, pt_x, pt_y\n\n\nclass ResizeNormalize(object):\n def __init__(self, size, interpolation=Image.BILINEAR):\n self.size = size\n self.interpolation = interpolation\n self.toTensor = transforms.ToTensor()\n\n def __call__(self, img):\n img = img.resize(self.size, self.interpolation)\n img = self.toTensor(img)\n img.sub_(0.5).div_(0.5)\n return img\n\n\nclass RandomSequentialSampler(sampler.Sampler):\n\n def __init__(self, data_source, batch_size):\n self.num_samples = len(data_source)\n self.batch_size = batch_size\n\n def __len__(self):\n return self.num_samples\n\n def __iter__(self):\n n_batch = len(self) // self.batch_size\n tail = len(self) % self.batch_size\n index = torch.LongTensor(len(self)).fill_(0)\n for i in range(n_batch):\n random_start = random.randint(0, len(self) - self.batch_size)\n batch_index = random_start + torch.arange(0, self.batch_size)\n index[i * self.batch_size:(i + 1) * self.batch_size] = batch_index\n # deal with tail\n if tail:\n random_start = random.randint(0, len(self) - self.batch_size)\n tail_index = random_start + torch.arange(0, tail)\n index[(i + 1) * self.batch_size:] = tail_index\n\n return iter(index.tolist())\n\n\nclass AlignCollate(object):\n\n def __init__(self, imgH=128, imgW=128, min_ratio=1):\n self.imgH = imgH\n self.imgW = imgW\n self.min_ratio = min_ratio\n\n def __call__(self, batch):\n images, labels_x, labels_y = zip(*batch)\n b_labels_x = torch.LongTensor(labels_x)\n b_labels_y = torch.LongTensor(labels_y)\n\n imgH = self.imgH\n imgW = self.imgW\n\n transform = ResizeNormalize((imgW, imgH))\n images = [transform(image) for image in images]\n b_images = torch.stack(images)\n\n return b_images, b_labels_x, b_labels_y\n\n\nif __name__ == \"__main__\":\n test()","sub_path":"lib/datasets/dataset_classification.py","file_name":"dataset_classification.py","file_ext":"py","file_size_in_byte":5658,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"581264197","text":"# -*- coding: UTF-8 -*-\nimport pandas as pd\nimport pymysql\nimport MySQLdb\nimport MySQLdb.cursors\nimport collections\nimport json\nfrom sqlalchemy import create_engine\nfrom CreateJsonFile import ReadFileToDict\nfrom collections import OrderedDict\n\ndef MysqlMerged(id):\n\n #数据库连接\n conn = MySQLdb.connect(host=\"127.0.0.1\",user=\"root\",passwd=\"123456\",\n db=\"hospital\",charset='utf8',cursorclass = MySQLdb.cursors.DictCursor)\n #游标\n cur = conn.cursor()\n\n #转换类型以匹配键值\n x=int(id)\n #执行数据库的操作cur.execute\n sql = \"select * from sur_app_patient_test where patientID =%d\"%(x)\n cur.execute(sql)\n\n #获取病人口述病历\n id_str = str(id)\n filename = id_str + \"test.text\"\n # print filename\n dict1 = OrderedDict()\n dict1 = ReadFileToDict.ReadFileToDict(filename)\n\n #获取检查结果\n rows = OrderedDict()\n # rows=cur.fetchall()\n dict_0 = OrderedDict()\n dict_0=cur.fetchall()\n #解决乱序问题,使用键值对的方法,由键名字来获取数据\n for row in dict_0:\n #patientID,blood_sugar,blood_pressure,glucose_in_urine,Glucose_tolerance,Insulin,temperature\n rows[\"patientID\"] =row[\"patientID\"]\n rows[\"blood_sugar\"] = row[\"blood_sugar\"]\n rows[\"blood_pressure\"] = row[\"blood_pressure\"]\n rows[\"glucose_in_urine\"] = row[\"glucose_in_urine\"]\n rows[\"Glucose_tolerance\"] = row[\"Glucose_tolerance\"]\n rows[\"patientID\"] = row[\"patientID\"]\n rows[\"Insulin\"] = row[\"Insulin\"]\n rows[\"temperature\"] = row[\"temperature\"]\n\n #口述病情与检查结果进行合并\n dictMerged2=OrderedDict()\n dictMerged2 = dict1.copy()\n dictMerged2.update(rows)\n # dictMerged2 =Dict(dict1, **rows)\n #以json格式输出\n # print json.dumps(dictMerged2, sort_keys=0, indent=4, ensure_ascii=False)\n # return dictMerged2\n def TranDicToTxt(dic):\n rt = []\n fp = open(\"../AndoridServer/patientFile/\"+filename, 'w')\n for (k, v) in dic.items():\n fp.write('%s:%s\\n' % (k, v))\n fp.close()\n TranDicToTxt(dictMerged2)\n# MysqlMerged(1)","sub_path":"MysqlTools/Merged.py","file_name":"Merged.py","file_ext":"py","file_size_in_byte":2150,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"203586914","text":"#!/bin/env python\n#\n# Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration\n#\n\nimport logging\nimport sys\n\nfrom EventIndexProducer.sendEI_Lib import eimrun\nfrom EventIndexProducer.sendEI_Lib import options as eioptions\n\ndef main():\n\n # logger\n logger = logging.getLogger('sendEI.py')\n global log\n log = logger \n\n # analyze options\n opt = eioptions(sys.argv[1:])\n\n if opt.verbose > 0:\n logger.setLevel(logging.INFO)\n\n if opt.debug > 0:\n logger.setLevel(logging.DEBUG)\n\n eimrun(logger,opt)\n\n\nif __name__ == '__main__':\n\n # logger setup\n root = logging.getLogger()\n ch = logging.StreamHandler(sys.stdout)\n ch.setLevel(logging.DEBUG)\n #formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')\n formatter = logging.Formatter('%(name)-15s %(levelname)9s %(message)s')\n ch.setFormatter(formatter)\n root.addHandler(ch)\n\n main()\n\n \n \n\n","sub_path":"athena/Database/EventIndex/EventIndexProducer/scripts/sendEI.py","file_name":"sendEI.py","file_ext":"py","file_size_in_byte":946,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"325020024","text":"import re\nfrom .memory import address_by_name\n\nNUMBER_PATTERN = re.compile('^\\d+$')\nCOMP_REPL_SOURCE_PATTERN = re.compile('[AM]')\nCOMP_REPL_TARGET = 'X'\n\nCOMP2BITS = {\n '0': '101010',\n '1': '111111',\n '-1': '111010',\n 'D': '001100',\n 'X': '110000',\n '-D': '001111',\n '-X': '110011',\n '!D': '001101',\n '!X': '110001',\n 'D+1': '011111',\n 'X+1': '110111',\n 'D-1': '001110',\n 'X-1': '110010',\n 'D+X': '000010',\n 'D-X': '010011',\n 'X-D': '000111',\n 'D&X': '000000',\n 'D|X': '010101'\n}\n\nJUMP2BITS = {\n None: '000',\n 'JGT': '001',\n 'JEQ': '010',\n 'JGE': '011',\n 'JLT': '100',\n 'JNE': '101',\n 'JLE': '110',\n 'JMP': '111'\n}\n\n\ndef translate_address_code(address):\n def format_address(int_address):\n return '{0:016b}'.format(int_address)\n\n if NUMBER_PATTERN.match(address):\n return format_address(int(address))\n return format_address(address_by_name.setdefault(address))\n\n\ndef translate_compute_code(dest, comp, jump):\n def get_dest_bits():\n abit, dbit, mbit = 0, 0, 0\n if dest:\n if 'A' in dest:\n abit = 1\n if 'D' in dest:\n dbit = 1\n if 'M' in dest:\n mbit = 1\n return '{abit}{dbit}{mbit}'.format(abit=abit, dbit=dbit, mbit=mbit)\n\n def get_comp_bits():\n abit = int('M' in comp)\n comp_map_key = re.sub(\n COMP_REPL_SOURCE_PATTERN,\n COMP_REPL_TARGET, comp)\n return '{abit}{cbits}'.format(\n abit=abit,\n cbits=COMP2BITS[comp_map_key])\n\n def get_jump_bits():\n return JUMP2BITS[jump]\n\n return '111{comp_bits}{dest_bits}{jump_bits}'.format(\n comp_bits=get_comp_bits(),\n dest_bits=get_dest_bits(),\n jump_bits=get_jump_bits())\n\n\ndef assembly2binary(code):\n try:\n address = code.address\n except AttributeError:\n return translate_compute_code(code.dest, code.comp, code.jump)\n else:\n return translate_address_code(address)\n","sub_path":"software/assembler/translator.py","file_name":"translator.py","file_ext":"py","file_size_in_byte":2034,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"226019138","text":"'''\n@inishchith\nhttps://www.codechef.com/problems/FLOW004\n'''\nT=int(input())\nwhile T>0:\n a=int(input())\n d1=int(a%10)\n c=0\n n1=a\n r=1\n while a>0:\n x=a%10\n v= r*10 + x\n c+=1\n a=a//10\n d2=v%10\n f= d1+d2\n print(f)\n T-=1 \n","sub_path":"CodeChef-PyBasics/First And Last Digit.py","file_name":"First And Last Digit.py","file_ext":"py","file_size_in_byte":277,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"178445860","text":"'''\nMaxwell Gove\nNew York University\nIntroduction to Computer Programming\nAssignment 7\nPart 1a\n'''\n\nvalid_username = False\n\nwhile not valid_username:\n username = input('Please enter a username: ')\n\n alphanumeric_only = True\n valid_length = False\n valid_first_char = True\n includes_digit = False\n includes_uppercase = False\n includes_lowercase = False\n\n if len(username) >= 8 and len(username) <= 15:\n valid_length = True\n\n first_char = username[0]\n if first_char.isnumeric():\n valid_first_char = False\n\n for letter in username:\n if not username.isalnum():\n alphanumeric_only = False\n\n if letter.islower():\n includes_lowercase = True\n\n if letter.isupper():\n includes_uppercase = True\n\n if letter.isnumeric():\n includes_digit = True\n\n if alphanumeric_only and valid_length and valid_first_char and includes_digit and includes_uppercase and includes_lowercase:\n valid_username = True\n else:\n if not alphanumeric_only:\n print('Usernames can only include alphabetic and numeric characters.')\n if not valid_length:\n print('Username must be between 8 and 15 characters.')\n if not valid_first_char:\n print('The first character in your username cannot be a digit')\n if not includes_digit:\n print('Your username must contain at least one digit')\n if not includes_uppercase:\n print('Your username must contain at least one uppercase character')\n if not includes_lowercase:\n print('Your username must contain at least one lowercase character')\n print('\\n')\n\nif valid_username:\n print('Your username is valid!')\n \n","sub_path":"assignment7/gove_maxwell_assignment7_part1.py","file_name":"gove_maxwell_assignment7_part1.py","file_ext":"py","file_size_in_byte":1614,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"340106343","text":"#sg\n'''\nGaussian process regeression\n'''\nimport numpy as np\nfrom sklearn import cross_validation\nfrom sklearn.gaussian_process import GaussianProcess\nfrom matplotlib import pyplot as pl\ndata = np.loadtxt('data', delimiter = '\\t')\nX = np.array(data[:,0]).reshape(30, 1)\ny = np.array(data[:,1]).reshape(30, 1)\nX_train, X_test, y_train, y_test = cross_validation.train_test_split(X, y, test_size = 0.3, random_state = 0)\n# Mesh the input space for evaluations of the real function, the prediction and\n# its MSE\n\ngp = GaussianProcess(corr='squared_exponential', theta0=1e-1,\n thetaL=1e-3, thetaU=1, random_start=100)\n\n# Fit to data using Maximum Likelihood Estimation of the parameters\ngp.fit(X_train, y_train)\n\n# Make the prediction on the meshed x-axis (ask for MSE as well)\ny_pred, MSE = gp.predict(X_test, eval_MSE=True)\nprint(\"Residual sum of squares: %.2f\"\n % np.mean((y_pred - y_test) ** 2))\n\n","sub_path":"py/regression/gpregr.py","file_name":"gpregr.py","file_ext":"py","file_size_in_byte":921,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"27446936","text":"import numpy as np\nfrom PIL import Image\nimport os\n\n\ndef filepath(\n filename,\n): # deze functie geeft het path van het bestand zelf terug hoe je het ook uitvoert, zodat het programma het bestand goed kan vinden\n script_dir = os.path.dirname(__file__)\n return os.path.join(script_dir, filename)\n\n\ndef bwplaatje(fname):\n # hier openen we een plaatje\n im = Image.open(filepath(fname), \"r\")\n w, h = im.size\n print(w, h)\n # we maken een numpy array van de pixelwaarden in het plaatje\n nim = np.array(im)\n # waar een pixel rood genoeg is zien we als een opening in de slit\n r = np.argwhere(nim[:, :, 0] > 128)\n # het blauwe deel van de pixel bepaalt de relatieve intensiteit op dat punt\n i = np.array([nim[r[:, 0], r[:, 1], 2]]).astype(\"float64\").T / 255\n # het groene deel doet op dit moment niets, maar deze zou kunnen worden gebruikt voor een faseverschuiving\n data = np.append(r.astype(\"float64\"), i, 1)\n # hier draaien we de data om en maken we het midden van het plaatje het coordinaat (0,0)\n data[:, 0] -= (h - 1) / 2\n data[:, 1] -= (w - 1) / 2\n data[:, 0] *= -1\n print(data)\n return data\n","sub_path":"oude versies/readimgcolor.py","file_name":"readimgcolor.py","file_ext":"py","file_size_in_byte":1154,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"616452923","text":"from pyscipopt import Model\n#\n#\n# model = Model(\"MILP\")\n#\n# x = model.addVar(\"x\")\n# y = model.addVar(\"y\", vtype=\"INTEGER\")\n# model.setObjective(x + y)\n# cons = model.addCons(2*x - y*y >= 0, )\n# model.optimize()\n# lp_sol = model.createLPSol()\n# sol = model.getBestSol()\n# print(\"Model MILP is solved \")\n# print(\"x: {}\".format(sol[x]))\n# print(\"y: {}\".format(sol[y]))\nimport matplotlib.pyplot as plt\nimport numpy\n\nfrom geco.mips.miplib.base import Loader\n\n# miplib2017_binary39 = ['10teams',\n# 'a1c1s1',\n# 'aflow30a',\n# 'aflow40b',\n# 'air04',\n# 'air05',\n# 'cap6000',\n# 'dano3mip',\n# 'danoint',\n# 'ds',\n# 'fast0507',\n# 'fiber',\n# 'glass4',\n# 'harp2',\n# 'liu',\n# 'misc07',\n# 'mkc',\n# 'mod011',\n# 'momentum1',\n# 'net12',\n# 'nsrand-ipx',\n# 'nw04',\n# 'opt1217',\n# 'p2756',\n# 'protfold',\n# 'qiu',\n# 'rd-rplusc-21',\n# 'seymour',\n# 'sp97ar',\n# 'swath',\n# 't1717',\n# 'tr12-30',\n# 'van'\n# ]\n\n# numpy.savez('./result/miplib2017/miplib2017_binary39', miplib2017_binary39 = miplib2017_binary39)\n# data = numpy.load('./result/miplib2017/miplib2017_binary39.npz')\n# miplib2017_binary = data['miplib2017_binary39']\n#\n# for i in range(len(miplib2017_binary)):\n# instance = Loader().load_instance(miplib2017_binary[i]+'.mps.gz')\n# MIP_model = instance\n# print(MIP_model.getProbName())\n\n# print repair violation\n# print(len(miplib2017_binary39))\ndata = numpy.load('./result/miplib2017/miplib2017_binary39.npz')\nmiplib2017_binary39 = data['miplib2017_binary39']\n\nmodes = ['repair-slackvars', 'repair-supportbinvars', 'repair-binvars', 'improve-supportbinvars', 'improve-binvars']\nplottitles = [\"LB to repair (over slack variables)\", \"LB to repair (over support of binary vars)\", \"LB to repair (over binary variables)\", \"LB to improve (over support of binary vars)\", \"LB to improve (over binary variables)\"]\nlb_neigh_basis = ['violations','supportofbins','binvars', 'supportofbins','binvars']\n\nprint(len(miplib2017_binary39))\n\nfor i in range(len(miplib2017_binary39)): #\n instance_name = miplib2017_binary39[i]\n if instance_name == 'mkc':\n\n\n # for each instance: plot the result of each mode\n for j in range(4,5): #len(modes)\n mode = modes[j]\n directory = './result/miplib2017/' + mode + '/'\n data = numpy.load(directory + instance_name + '.npz')\n neigh_sizes = data['neigh_sizes']\n t = data['t']\n objs = data['objs']\n\n plt.clf()\n fig, ax = plt.subplots(2, 1, figsize=(6.4, 6.4))\n fig.suptitle(plottitles[j])\n fig.subplots_adjust(top=0.5)\n ax[0].plot(neigh_sizes, objs)\n ax[0].set_title(instance_name, loc='right')\n ax[0].set_xlabel(r'$\\alpha$ ' + '(Neighborhood size: ' + r'$K = \\alpha \\times N_{' + lb_neigh_basis[j] + '}$)')\n ax[0].set_ylabel('Objective')\n ax[1].plot(neigh_sizes, t)\n # ax[1].set_ylim([0, 31])\n ax[1].set_ylabel(\"Solving time\")\n plt.show()\n\n\n# modes = ['repair-nviolations','repair-nbinvars','improve']\n# mode = modes[0]\n#\n# if mode == 'repair-nviolations':\n# directory = './result/miplib2017/repair/timesofviolations/'\n# elif mode == 'repair-nbinvars':\n# directory = './result/miplib2017/repair_asym/timesofbinvars/'\n# elif mode == 'improve':\n# directory = './result/miplib2017/improve/'\n#\n#\n#\n# for i in range(len(miplib2017_binary39)):\n#\n# instance_name = miplib2017_binary39[i]\n# data = numpy.load(directory+instance_name+'.npz')\n# neigh_sizes = data['neigh_sizes']\n# t =data['t']\n# objs = data['objs']\n#\n# if mode == 'repair-nviolations':\n# neigh_sizes = numpy.log10(neigh_sizes)\n# plt.clf()\n# fig, ax = plt.subplots(2, 1, figsize=(6.4, 6.4))\n#\n# fig.suptitle(\"LB to repair\")\n# fig.subplots_adjust(top=0.5)\n# ax[0].plot(neigh_sizes, objs)\n# ax[0].set_title(instance_name, loc='right')\n# ax[0].set_xlabel(r'$log(\\alpha)$ '+'(Neighborhood size: '+ r'$K = \\alpha \\times N_{violations}$)')\n# ax[0].set_ylabel(r'$N_{violations}$')\n# ax[1].plot(neigh_sizes, t)\n# # ax[1].set_ylim([0, 31])\n# ax[1].set_ylabel(\"Solving time\")\n# plt.show()\n#\n# instance_name = miplib2017_binary39[i]\n# data = numpy.load('./result/miplib2017/repair_asym/timesofviolations/' + instance_name + '.npz')\n# neigh_sizes = data['neigh_sizes']\n# t = data['t']\n# objs = data['objs']\n#\n# neigh_sizes = numpy.log10(neigh_sizes)\n# plt.clf()\n# fig, ax = plt.subplots(2, 1, figsize=(6.4, 6.4))\n#\n# fig.suptitle(\"LB to repair (asymmetric)\")\n# fig.subplots_adjust(top=0.5)\n# ax[0].plot(neigh_sizes, objs)\n# ax[0].set_title(instance_name, loc='right')\n# ax[0].set_xlabel(r'$log(\\alpha)$ ' + '(Neighborhood size: ' + r'$K = \\alpha \\times N_{violations}$)')\n# ax[0].set_ylabel(r'$N_{violations}$')\n# ax[1].plot(neigh_sizes, t)\n# # ax[1].set_ylim([0, 31])\n# ax[1].set_ylabel(\"Solving time\")\n# plt.show()\n#\n# elif mode == 'repair-nbinvars':\n# plt.clf()\n# fig, ax = plt.subplots(2, 1, figsize=(6.4, 6.4))\n#\n# fig.suptitle(\"LB to repair\")\n# fig.subplots_adjust(top=0.5)\n# ax[0].plot(neigh_sizes, objs)\n# ax[0].set_title(instance_name, loc='right')\n# ax[0].set_xlabel(r'$\\alpha$ ' + '(Neighborhood size: ' + r'$K = \\alpha \\times N_{binvars}$)')\n# ax[0].set_ylabel(r'$N_{violations}$')\n# ax[1].plot(neigh_sizes, t)\n# # ax[1].set_ylim([0, 31])\n# ax[1].set_ylabel(\"Solving time\")\n# plt.show()\n# elif mode == 'improve':\n# plt.clf()\n# fig, ax = plt.subplots(2, 1, figsize=(6.4, 6.4))\n# fig.suptitle(\"LB to improve\")\n# fig.subplots_adjust(top=0.5)\n# ax[0].plot(neigh_sizes, objs)\n# ax[0].set_title(instance_name, loc='right')\n# ax[0].set_xlabel(r'$\\alpha$ ' + '(Neighborhood size: ' + r'$K = \\alpha \\times N_{binvars}$)')\n# ax[0].set_ylabel(\"Objective\")\n# ax[1].plot(neigh_sizes, t)\n# # ax[1].set_ylim([0,31])\n# ax[1].set_ylabel(\"Solving time\")\n# plt.show()\n#\n#\n#\n#\n","sub_path":"unit_test/test_plot.py","file_name":"test_plot.py","file_ext":"py","file_size_in_byte":6928,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"569612869","text":"#-*- coding: utf-8\n\nfrom DistWriter import DistWriter\n\nclass TxtDistWriter(DistWriter):\n\n\t__fid = None\n\n\tdef getFid(self):\n\t\treturn self.__fid\n\n\tdef create(self):\n\t\tfilename = self.getFilename()\n\t\tself.__fid = file(filename, \"w\")\n\n\tdef open(self):\n\t\tfilename = self.getFilename()\n\t\tself.__fid = file(filename, \"r\")\n\n\n\tdef writeHeaders(self, headers):\n\t\theaders_description = self.getHeaderDescription()\n\t\theaders_order = self.getHeaderOrder()\n\t\tfor header_name in headers_order:\n\t\t\tif headers.has_key(header_name):\n\t\t\t\theader_description = headers_description[header_name]\n\t\t\t\theader_value = headers[header_name]\n\t\t\t\tself.__fid.write(\"{0}: {1}\\n\".format(header_description, header_value))\n\t\tfor header_name, header_value in headers.iteritems():\n\t\t\tif header_name not in headers_order:\n\t\t\t\theader_description = headers_description[header_name]\n\t\t\t\tself.__fid.write(\"{0}: {1}\\n\".format(header_description, header_value))\n\t\tself.__fid.write(\"\\n\")\n\t\tself.__fid.write(self.getLastHeaderString())\n\n\tdef getHeaderDescription(self):\n\t\traise NotImplementedError(\"getHeaderDescription\")\n\n\tdef getHeaderOrder(self):\n\t\traise NotImplementedError(\"getHeaderOrder\")\n\n\tdef close(self):\n\t\tself.getFid().close()\n\n\tdef getHeaders(self):\n\t\theaders_description = self.getHeaderDescription()\n\t\theaders = {}\n\t\twhile True:\n\t\t\tline = self.getFid().readline()\n\t\t\tif len(line) == 0:\n\t\t\t\traise IOError(\"Sudden EOF has been reached\")\n\t\t\tline = line.strip()\n\t\t\tif len(line) == 0:\n\t\t\t\tbreak\n\t\t\theader_description, header_value = line.split(\":\")\n\t\t\theader_description = header_description.strip()\n\t\t\theader_value = header_value.strip()\n\t\t\theader_name = headers_description.keys()[headers_description.values().index(header_description)]\n\t\t\theaders[header_name] = header_value\n\t\tself.getFid().readline()\n\t\tself._setSpecimen(headers['specimen'])\n\t\tself._setExperiment(headers['experiment'])\n\t\tself._setCondition(headers['condition'])\n\t\tself._setChannel('')\n\t\treturn headers","sub_path":"kozhukhov/imaging/general/TxtDistWriter.py","file_name":"TxtDistWriter.py","file_ext":"py","file_size_in_byte":1938,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"593935902","text":"import hypothesis.strategies as st\nimport numpy as np\nimport pytest\nfrom hypothesis import given\nfrom pytest import raises\n\nfrom mygrad.errors import InvalidBackprop\nfrom mygrad.operation_base import BroadcastableOp, Operation\nfrom mygrad.tensor_base import Tensor\n\n\nclass ScalarOnlyOp(BroadcastableOp):\n def __init__(self):\n self.scalar_only = True\n\n def __call__(self, a, b):\n self.variables = (a, b)\n return np.array([0])\n\n\nclass NotScalarOnlyOp(Operation):\n def __init__(self):\n self.scalar_only = False\n\n def __call__(self, a, b):\n self.variables = (a, b)\n return np.array([0])\n\n\n@given(\n a_const=st.booleans(),\n a_scalar_only=st.booleans(),\n b_const=st.booleans(),\n b_scalar_only=st.booleans(),\n)\ndef test_scalar_only_op(a_const, a_scalar_only, b_const, b_scalar_only):\n \"\"\" op produces scalar_only result unless result is scalar. \"\"\"\n a = Tensor(0, constant=a_const, _scalar_only=a_scalar_only)\n b = Tensor(0, constant=b_const, _scalar_only=b_scalar_only)\n\n out = Tensor._op(ScalarOnlyOp, a, b)\n scalar_only = True and not out.constant\n\n assert scalar_only is out.scalar_only\n\n # check out.backward()\n if scalar_only:\n with raises(InvalidBackprop):\n out.backward()\n else:\n out.backward() # a, b, out are const (nothing computed)\n\n\n@given(\n a_const=st.booleans(),\n a_scalar_only=st.booleans(),\n b_const=st.booleans(),\n b_scalar_only=st.booleans(),\n)\ndef test_standard_op(a_const, a_scalar_only, b_const, b_scalar_only):\n \"\"\" op produces standard result unless an `a` or `b` is a scalar_only variable. \"\"\"\n a = Tensor(0, constant=a_const, _scalar_only=a_scalar_only)\n b = Tensor(0, constant=b_const, _scalar_only=b_scalar_only)\n\n scalar_only = (a.scalar_only and not a.constant) or (\n b.scalar_only and not b.constant\n )\n out = Tensor._op(NotScalarOnlyOp, a, b)\n\n assert scalar_only is (out.scalar_only and not out.constant)\n\n # check out.backward()\n if scalar_only:\n with raises(InvalidBackprop):\n out.backward()\n else:\n if a.constant and b.constant:\n out.backward() # a, b, out are const (nothing computed)\n else:\n with raises(NotImplementedError):\n out.backward()\n\n\n@pytest.mark.parametrize(\"constant\", [True, False])\n@pytest.mark.parametrize(\"operation\", [\"add\", \"sub\", \"mul\", \"truediv\", \"pow\"])\ndef test_practical_scalar_only(constant, operation):\n a = Tensor([1, 2, 3], constant=constant)\n b = Tensor(3, constant=constant)\n out = getattr(a, \"__\" + operation + \"__\")(b)\n\n if constant:\n out.backward()\n else:\n with raises(InvalidBackprop):\n out.backward()\n","sub_path":"tests/tensor_base/test_scalar_only.py","file_name":"test_scalar_only.py","file_ext":"py","file_size_in_byte":2743,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"355578622","text":"# Copyright 2017 Battelle Energy Alliance, LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# This tests is used to verify the svd decomposition calculated inside crow\n# the svd module from numpy.linalg is used as gold solution.\n\n#For future compatibility with Python 3\nfrom __future__ import division, print_function, unicode_literals, absolute_import\nimport warnings\nwarnings.simplefilter('default',DeprecationWarning)\n#!/usr/bin/env python\n\nimport sys\nimport crowTestUtils as utils\nimport numpy as np\nfrom math import sqrt\nfrom numpy import linalg as LA\n\ndistribution1D = utils.findCrowModule('distribution1D')\n# input data, random matrix can also be used.\nmu = [1.0,2.0,3.0,4.0,5.0]\ncov = [1.36, -0.16, 0.21, 0.43, -0.144,\n -0.16, 6.59, 0.794, -0.173, -0.406,\n 0.21, 0.794, 5.41, 0.461, 0.179,\n 0.43, -0.173, 0.461, 14.3, 0.822,\n -0.144, -0.406, 0.179, 0.822, 3.75]\n\n#dim = 5\n\n# Transform 'mu' and 'cov' to the c++ vector\nmuCpp = distribution1D.vectord_cxx(len(mu))\nfor i in range(len(mu)):\n muCpp[i] = mu[i]\ncovCpp = distribution1D.vectord_cxx(len(cov))\nfor i in range(len(cov)):\n covCpp[i] = cov[i]\n\n# call the functions from the crow to compute the svd\ncovType = \"abs\"\nrank = 5\nmvnDistribution = distribution1D.BasicMultivariateNormal(covCpp,muCpp,str(covType),5)\n\ndimVector = mvnDistribution.getTransformationMatrixDimensions()\nuCpp_vector = mvnDistribution.getTransformationMatrix()\nuCpp = [uCpp_vector[i] for i in range(dimVector[0]*dimVector[1])]\nuCpp = np.asarray(uCpp)\nuCpp = np.reshape(uCpp,(dimVector[0],dimVector[1]))\n\n# using numpy to compute the svd\ncovNp = np.asarray(cov).reshape(-1,int(sqrt(len(cov))))\nuNp,sNp,vNp = LA.svd(covNp,full_matrices=False)\n\n# compute the transformation matrix = U*sqrt(S)\nuReCompute = np.dot(uNp,np.sqrt(np.diag(sNp)))\n\nresults = {\"pass\":0,\"fail\":0}\n\nutils.checkArrayAllClose(\"MVN transformation matrix\",np.absolute(uCpp),np.absolute(uReCompute),results)\nutils.checkAnswer(\"MVN row dimensions of transformation matrix\",dimVector[0],5,results)\nutils.checkAnswer(\"MVN col dimensions of transformation matrix\",dimVector[1],5,results)\n\nprint(results)\n\nsys.exit(results[\"fail\"])\n\n\n\"\"\"\n <TestInfo>\n <name>crow.test_transformationMatrix</name>\n <author>cogljj</author>\n <created>2017-03-24</created>\n <classesTested>crow</classesTested>\n <description>\n This test is a Unit Test for the crow swig classes. It tests that the MultiVariate Normal\n distribution is accessable by Python and that transformation matrix is accessable and\n correctly computed.\n </description>\n <revisions>\n <revision author=\"alfoa\" date=\"2018-05-15\">Adding this test description.</revision>\n </revisions>\n </TestInfo>\n\"\"\"\n\n\n\n\n","sub_path":"tests/crow/test_transformationMatrix.py","file_name":"test_transformationMatrix.py","file_ext":"py","file_size_in_byte":3235,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"136685329","text":"import json\nimport pandas as pd\nimport glob\nimport os\n\n\ndef read_json(json_file_path):\n with open(json_file_path) as f:\n data = json.load(f)\n return data\n\n\ndef reformat_json(json_obj):\n json_dict = {}\n for key, value in json_obj:\n json_dict[key] = value\n return json_dict\n\n\ndef load_json_as_df(json_data):\n out_df = pd.DataFrame(list(json_data.items()),\n columns=['Key', 'value'])\n return out_df\n\n\n# unused\ndef get_matched_count(excel_df, merged_df):\n count = 0\n for key in excel_df['Key']:\n for k_key in merged_df['Key']:\n if key == k_key:\n count += 1\n break\n return count\n\n\ndef read_excel_as_df(filename, columns: list):\n excel_df = pd.DataFrame([], columns=columns)\n excel = pd.ExcelFile(filename)\n for sheet_name in excel.sheet_names:\n sheet = excel.parse(sheet_name=sheet_name, header=1)\n if len(sheet.columns) == 0:\n continue\n excel_df = pd.concat([excel_df, sheet], axis=0)\n return excel_df\n\n\ndef read_excels_as_df(filenames, columns: list):\n excel_df = pd.DataFrame([], columns=columns)\n for excel_file_name in filenames:\n excel_file_df = read_excel_as_df(excel_file_name, columns)\n excel_df = pd.concat([excel_df, excel_file_df], axis=0)\n return excel_df\n\n\ndef excel_filter(excel_file_name):\n return os.path.isfile(excel_file_name) and excel_file_name.endswith('.xlsx') and not excel_file_name.split('/')[\n -1].startswith('~')\n\n\ndef get_excel_files(dir_name):\n list_of_files = filter(excel_filter, glob.glob(dir_name + '/*'))\n list_of_files = sorted(list_of_files, key=os.path.getmtime)\n return list_of_files\n\n\ndef move_files(base_path, filenames):\n done_folder = base_path + \"/done\"\n os.makedirs(done_folder, exist_ok=True)\n for file_name in filenames:\n os.system('mv {} {}'.format(file_name, done_folder))\n","sub_path":"utils/localization/modules/locale_generator/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1936,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"115963385","text":"#!/usr/bin/python \n# -*- coding: utf-8 -*-\n# .::::.\n# .::::::::.\n# :::::::::::\n# ..:::::::::::'\n# '::::::::::::'\n# .::::::::::\n# '::::::::::::::..\n# ..::::::::::::.\n# ``::::::::::::::::\n# ::::``:::::::::' .:::.\n# ::::' ':::::' .::::::::.\n# .::::' :::: .:::::::'::::.\n# .:::' ::::: .:::::::::' ':::::.\n# .::' :::::.:::::::::' ':::::.\n# .::' ::::::::::::::' ``::::.\n# ...::: ::::::::::::' ``::.\n# ```` ':. ':::::::::' ::::..\n# '.:::::' ':'````..\n# 美女保佑 永无BUG\n\nimport torch\nimport torch.nn.functional as F # 激励函数都在这\nimport torch.nn\nimport torch.utils.data as Data\n# import torchvision # 数据库模块\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport datetime\nimport time\nfrom torch.autograd import Variable\n\n\n# torch.manual_seed(7)\n\nf1 = open('thunderman.csv',encoding=\"utf-8\")\ndf = pd.read_csv(f1)\ndf = df.reset_index()\ndf=df[~df['date'].isin(['2018-9-15'])]\ndf = df.reset_index()\n# print(df)\n\ni = 0\ninput_list = []\nwhile i < len(df['work']):\n small_list = []\n small_list.append(df['temp_max'][i])\n small_list.append(df['temp_min'][i])\n input_list.append(small_list)\n i += 1\n\n\ndf1 = pd.DataFrame()\ndf1['input'] = input_list\ndf1['quantity'] = df['quantity']\ndf1['temp_max'] = df['temp_max']\ndf1['temp_min'] = df['temp_min']\ndf1['work'] = df['work']\nprint(df1)\ndf1 = df1.reset_index()\n\ndf2 = pd.DataFrame()\n# work = 0\ndf2['input'] = input_list\ndf2 = df1[df1['work'].isin([0])]\ndf2 = df2.reset_index()\n\n\ndf3 = pd.DataFrame()\n# work = 1\ndf3['input'] = input_list\ndf3 = df1[df1['work'].isin([1])]\ndf3 = df3.reset_index()\n\n\nprint('神经网络构建开始!')\nprint('开始导入数据!')\n# x = torch.FloatTensor(df3['temp_max'])\n# y = torch.FloatTensor(df3['quantity'])\n# x = torch.unsqueeze(x, dim=1)\n# y = torch.unsqueeze(y, dim=1)\n# x, y = Variable(x), Variable(y)\n\nx1_mean = np.mean(df3['temp_max'])\nx1_div = np.std(df3['temp_max'],ddof=1)\nx2_mean = np.mean(df3['temp_min'])\nx2_div = np.std(df3['temp_min'],ddof=1)\ny_mean = np.mean(df3['quantity'])\ny_div = np.std(df3['quantity'],ddof=1)\n\ndf0 = pd.DataFrame()\ndf0['x1_mean'] = [x1_mean]\ndf0['x1_div'] = [x2_div]\ndf0['x2_mean'] = [x2_mean]\ndf0['x2_div'] = [x2_div]\ndf0['y_mean'] = [y_mean]\ndf0['y_div'] = [y_div]\ndf0 = df0.reset_index()\n\ndf0.to_csv('stat2.csv', encoding='utf-8', index = False)\n\n\n\nfor i in df2['input']:\n i[0] = (i[0]-x1_mean)/x1_div\n i[1] = (i[1]-x2_mean)/x2_div\nx = df2['input']\n\nfor i in df3['quantity']:\n i = (i - y_mean)/y_div\ny = df2['quantity']\n\ny = torch.FloatTensor([(_-y_mean)/y_div for _ in df2['quantity']])\n\nx = torch.FloatTensor([x]).squeeze(2)\n# y = torch.FloatTensor([y])\n\nx = torch.squeeze(x, dim=1)\ny = torch.unsqueeze(y, dim=1)\nx, y = Variable(x), Variable(y)\n\n\n\n# np_data = np.arange(6).reshape((2,3))\n# torch_data = torch.FloatTensor(np_data)\n# x = torch.unsqueeze(torch.linspace(-1,1,100), dim=1)\n# y = x.pow(3) + 0.2*torch.rand(x.size())\n# x, y = Variable(x), Variable(y)\n\n\n\n# print(x.dtype)\nprint(x)\n# print(y.dtype)\nprint(y)\nprint('成功导入数据!')\n\nclass Net(torch.nn.Module):\n def __init__(self, n_feature, n_hidden, n_output):\n super(Net, self).__init__()\n self.hidden = torch.nn.Linear(n_feature, n_hidden)\n self.predict = torch.nn.Linear(n_hidden, n_output)\n \n def forward(self, x):\n x = F.relu6(self.hidden(x))\n x = self.predict(x)\n return x\n\nnet = Net(n_feature=2, n_hidden =18 ,n_output=1)\n\n# plt.ion()\n# plt.show()\n# optimizer 是训练的工具\noptimizer = torch.optim.SGD(net.parameters(), lr=0.1) # 传入 net 的所有参数, 学习率\nloss_func = torch.nn.MSELoss() # 预测值和真实值的误差计算公式 (均方差)\n\n# y = y.view(-1,1,1)\n\nprint('开始训练!')\nstart = time.time()\nfor epoch in range(100000):\n # rank = []\n \n prediction = net(x) # 喂给 net 训练数据 x, 输出分析值\n # print(prediction)\n loss = loss_func(prediction, y) # 计算两者的误差\n optimizer.zero_grad() # 清空上一步的残余更新参数值\n loss.backward() # 误差反向传播, 计算参数更新值\n optimizer.step() # 将参数更新值施加到 net 的 parameters 上\n end = time.time()\n # loss = loss.cpu()\n # print(loss.item())\n # print('Epoch: ', epoch+1, '| Step: ', step+1, '| Loss: ', loss.data.numpy(),' |训练时间: ',round(end-start,2),'秒')\n # rank.append(loss.data.numpy())\n # x1 = x1.cpu()\n # x2 = x2.cpu()\n # x3 = x3.cpu()\n # x = x.cpu()\n # y = y.cpu()\n\n # average = float(sum(rank)/len(rank))\n\n # if epoch % 10 ==0:\n # plt.cla()\n # plt.scatter(x.data.numpy(), y.data.numpy())\n # plt.plot(x.data.numpy(), prediction.data.numpy(), 'r-', lw=5)\n # plt.text(0.5, 0, 'Loss=%.4f' % loss.item(), fontdict={'size':'20','color':'red'})\n # plt.pause(0.1)\n\n\n if epoch % 100 ==0:\n # print(prediction)\n print('Epoch: ', epoch+1, '| Loss: ', loss.item(),' |训练时间: ',round(end-start,2),'秒')\n # print(prediction)\n # print('---------------------------------------------')\n # print('保存第',epoch+1,'遍训练模型中...')\n # print('---------------------------------------------')\n # torch.save(net.state_dict(), 'regnet.pt') # 保存整个网络参数\n\nplt.ioff()\nplt.show()\n\n\nprint('神经网络结束!')\nend = time.time()\nprint('总用时: ',end-start,'秒')\n\n\n# torch.manual_seed(7)\ntorch.save(net.state_dict(), 'regnet2.pt') # 保存整个网络参数\n# print('保存成功!')\n\n\n","sub_path":"electric/lajicpu2.py","file_name":"lajicpu2.py","file_ext":"py","file_size_in_byte":5929,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"413761421","text":"# Program losuje dwie liczby z zakresu od 0 do 99 (patrz poniżej).\n# odaje te dwie liczby i pyta jaka jest ich suma (nie podaje jej).\n# Użytkownik ma odgadnąć (no, policzyć w głowie) wynik.\n# Program pyta o wynik wielokrotnie, tak długo, aż użytkownik poda prawidłowy wynik.\nimport random\n\n\ndef number_gen():\n first_number = random.randrange(0, 100)\n seckond_number = random.randrange(0,100)\n sum_of_a_and_b = first_number + seckond_number\n\n return first_number, seckond_number, sum_of_a_and_b\n\n\ndef adding_two_numbers(num_a, num_b):\n sum_of_a_and_b = num_a + num_b\n\n return sum_of_a_and_b\n\n\ndef the_riddler(num_a, num_b):\n answer = int(input(f\"Podaj rozwiązanie następującego równania {num_a} + {num_b} = \"))\n\n return answer\n\n\ndef main():\n num_gen = number_gen()\n num_a = num_gen[0]\n num_b = num_gen[1]\n sum_of_a_and_b = adding_two_numbers(num_a, num_b)\n\n answer = the_riddler(num_a, num_b)\n while answer != sum_of_a_and_b:\n if answer != sum_of_a_and_b:\n print(\"Błędny wynik!\")\n num_gen = number_gen()\n num_a = num_gen[0]\n num_b = num_gen[1]\n sum_of_a_and_b = num_gen[-1]\n answer = the_riddler(num_a, num_b)\n\n print(\"Zgadza się!\")\n\n\nmain()\n\n\n\n\n","sub_path":"Praca_domowa_1/Zad_dom2.1.py","file_name":"Zad_dom2.1.py","file_ext":"py","file_size_in_byte":1280,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"287387094","text":"import os\nimport codecs\nimport configparser\n\nconfig = configparser.ConfigParser()\nconfig.read('ini', encoding='utf-8')\nprint(config.sections())\n#当前文件路径\nproDir = os.path.split(os.path.realpath(__file__))[0]\n#在当前文件路径下查找.ini几件\nconfigPath = os.path.join(proDir,'config.ini')\nprint(configPath)\n\nconf = configparser.ConfigParser()\n\n#读取.ini\nconf.read(configPath)\n#get()函数读取section里面的参数值\nurl = conf.get('HTTP','baseurl')\n\nprint(url)\nprint(conf.sections())\nprint(conf.options('HTTP'))\nprint(conf.items('HTTP'))\n\n# remove BOM\nclass ReadConfig:\n def __init__(self):\n fd = open(configPath)\n data = fd.read()\n\n if data[:3] == codecs.BOM_UTF8:\n data = data[3:]\n file = codecs.open(configPath,'w')\n file.write(data)\n file.close()\n fd.close()\n\n self.cf = configparser.ConfigParser()\n self.cf.read(configPath)\n\n def get_email(self,name):\n value = self.cf.get('EMAIL' , 'mail_user')\n return value\n\n def get_HTTP(self,url):\n value = self.cf.get('HTTP','baseurl')\n return value\n\n","sub_path":"PycharmProjects/interfaceTest/testFile/readConfig.py","file_name":"readConfig.py","file_ext":"py","file_size_in_byte":1142,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"507801879","text":"import boto3\n\n\nclass Dynamodb:\n def __init__(self, region, table_name):\n self.client_dynamodb = boto3.client('dynamodb', region_name=region)\n self.table_name = table_name\n\n def get_crawler_name(self, job_name):\n response = self.client_dynamodb.scan(\n TableName=self.table_name,\n ExpressionAttributeValues={\n ':a': {\n 'S': job_name,\n },\n },\n FilterExpression='job_name= :a',\n )\n return response['Items'][0]['crawler_name']\n\n","sub_path":"lambda_crawler_run_ses/dynamodb.py","file_name":"dynamodb.py","file_ext":"py","file_size_in_byte":557,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"648478762","text":"import keras\nfrom keras.models import Sequential, save_model\nfrom keras.layers import SimpleRNN\nimport keras.backend as K\n\nbase_path = \"./\"\nbackend = K.backend()\nversion = keras.__version__\nmajor_version = int(version[0])\n\nn_in = 4\nn_out = 6\n\nmodel = Sequential()\nmodel.add(SimpleRNN(n_out, input_shape=(n_in, 1)))\n\nmodel.compile(loss='mse', optimizer='adam')\n\nprint(\"Saving model with single simple RNN layer for backend {} and keras major version {}\".format(backend, major_version))\nmodel.save(\"{}simple_rnn_{}_{}.h5\".format(base_path, backend, major_version))\n","sub_path":"src/main/resources/modelimport/keras/weights/scripts/simple_rnn.py","file_name":"simple_rnn.py","file_ext":"py","file_size_in_byte":563,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"537229115","text":"import numpy as np\nnp.set_printoptions(threshold=np.inf)\nimport torch\nfrom torch import nn\nimport torch.nn.functional as F\n\nimport matplotlib.pyplot as plt\nimport scipy.misc\nimport pickle\n\nfrom policy import LinearPolicy, CNNPolicy\n\n\nclass Agent(object):\n def __init__(self, policy='Linear', lr=1e3, batch_size=1, action_space=3,\n clip=-1, eps=-1, cont=0):\n self.train_device = 'cuda' if torch.cuda.is_available() else 'cpu'\n\n if policy == 'CNN':\n self.policy = CNNPolicy(action_space=action_space)\n elif policy == 'Linear':\n self.policy = LinearPolicy(action_space=action_space)\n else:\n raise Exception('Unknown policy: {}'.format(policy))\n self.policy.to(self.train_device)\n self.optimizer = torch.optim.RMSprop(self.policy.parameters(), lr=lr)\n\n self.batch_size = batch_size # every how many episodes to update\n self.gamma = 0.98\n self.cont = cont\n\n # Agent states\n self.cur_obs = None\n self.cur_action_probs = None\n self.cur_action = None\n self.nstep = 0\n self.nstep_cont = self.cont\n self.observations = []\n self.actions = []\n self.rewards = []\n self.loss = []\n self.clip = clip\n self.eps = eps\n\n def load_model(self, filename: str, load_as_cpu: bool) -> None:\n ''' load state of the model from the pickled file '''\n if load_as_cpu:\n state_dict = torch.load(filename, \"cpu\")\n else:\n state_dict = torch.load(filename)\n\n self.policy.load_state_dict(state_dict)\n print(\"Loaded model\", filename)\n\n def save_model(self, filename: str = \"model_params.mdl\") -> None:\n ''' save of the model to the specified file '''\n torch.save(self.policy.state_dict(), filename)\n print(\"Model saved to\", filename)\n\n store = {\n 'loss': self.loss,\n }\n f = open('loss_{}.pkl'.format(filename), 'wb')\n pickle.dump(store, f)\n\n def episode_finished(self, episode_number):\n all_actions = torch.stack(self.actions, dim=0).to(self.train_device).squeeze(-1)\n all_rewards = torch.stack(self.rewards, dim=0).to(self.train_device).squeeze(-1)\n\n # Normalize to improve stablity\n discounted_rewards = self.__discount_rewards(all_rewards, self.gamma)\n # discounted_rewards -= torch.mean(discounted_rewards)\n # if torch.std(discounted_rewards) > 1e-5: # avoid NaN\n # discounted_rewards /= torch.std(discounted_rewards)\n\n weighted_probs = all_actions * discounted_rewards\n loss = torch.sum(weighted_probs)\n self.loss.append(loss.data.cpu().item())\n loss.backward() # grad accumlates\n\n if (episode_number+1) % self.batch_size == 0: # Update parameters\n if self.clip != -1:\n for w in self.policy.parameters():\n w.grad.data.clamp_(-self.clip, self.clip)\n self.optimizer.step()\n self.optimizer.zero_grad()\n\n self.reset()\n\n def __discount_rewards(self, r, gamma):\n discounted_r = torch.zeros_like(r)\n running_add = 0\n for t in reversed(range(0, r.size(-1))):\n running_add = running_add * gamma + r[t]\n discounted_r[t] = running_add\n return discounted_r\n\n def reset(self) -> None:\n ''' reset state after episode is finished '''\n self.nstep = 0\n self.cur_obs = None\n self.cur_action_probs = None\n self.observations, self.actions, self.rewards = [], [], []\n self.nstep_cont = self.cont\n self.cur_action = None\n\n def __softmax_sample(self, ps):\n dist = torch.distributions.Categorical(ps)\n return dist.sample().item()\n\n def get_action(self, frame: np.ndarray, evaluation=True) -> int:\n ''' return the action that the agent would take:\n MOVE_UP, MOVE_DOWN, STAY = 1, 2, 0 '''\n self.cur_obs = frame\n\n if evaluation:\n self.cur_action_probs = self.policy.forward(frame)\n action = torch.argmax(self.cur_action_probs).item()\n else:\n if self.cur_action_probs is None:\n self.cur_action_probs = self.policy.forward(frame)\n self.cur_action = self.__softmax_sample(self.cur_action_probs)\n\n if self.nstep_cont > 0:\n self.nstep_cont -= 1\n else:\n self.nstep_cont = self.cont\n self.cur_action_probs = self.policy.forward(frame)\n self.cur_action = self.__softmax_sample(self.cur_action_probs)\n\n if self.eps == -1:\n action = self.cur_action\n else:\n probs = self.cur_action_probs.clone()\n if torch.max(probs) > 0.8:\n i = torch.argmin(self.cur_action_probs).item()\n probs[i] = probs[i] + self.eps\n i = torch.argmin(self.cur_action_probs).item()\n probs[i] = probs[i] + self.eps\n i = torch.argmax(self.cur_action_probs).item()\n probs[i] = probs[i] - 2*self.eps\n action = self.__softmax_sample(probs)\n return action\n\n def store_step_outcome(self, observation, action_taken, reward, episode_number, done: bool):\n if self.cur_action_probs is None:\n raise Exception('run get_action() first')\n\n dist = torch.distributions.Categorical(self.cur_action_probs)\n action_taken = torch.Tensor([action_taken]).to(self.train_device)\n log_action_prob = -dist.log_prob(action_taken)\n\n self.observations.append(observation)\n self.actions.append(log_action_prob)\n self.rewards.append(torch.Tensor([reward]))\n self.nstep += 1\n\n if done:\n self.episode_finished(episode_number)\n\n # name of the group's agent\n def get_name(self) -> str:\n return \"zhang_szyller\"\n","sub_path":"src/agent.py","file_name":"agent.py","file_ext":"py","file_size_in_byte":5973,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"602329797","text":"\"\"\"\r\nGoal - to read csv data of kingfisher strike success as a function of tide and make plots\r\n\"\"\"\r\n\r\n#import modules\r\nimport pandas as pd \r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nfrom datetime import datetime, timedelta\r\n\r\n################# tide success #####################\r\nfs = 14\r\ndata_directory = '../../data/kingfisher/raw_feeding_success.csv'\r\nraw_data = pd.read_csv(data_directory)\r\nmasked_data = raw_data.mask(raw_data['Adult'] == 0.5)\r\n#bins = [-0.20,0.40,1.00,1.60,2.26]\r\nbins = [-0.22,0.40,1.00,1.60,2.26]\r\n\r\ntide_categories = pd.cut(masked_data['Tide height (m)'], bins)\r\nattempts_tide = pd.value_counts(tide_categories)\r\nsuccess_tide = pd.concat([tide_categories, masked_data[['Success', 'Adult']]],axis = 1)\r\ngrouped_mean = success_tide.groupby(['Adult','Tide height (m)']).mean()#, as_index=False).mean()\r\ngrouped_mean = grouped_mean.rename(index={0.0: \"Juvenile\", 1.0: \"Adult\"})\r\nunstacked = grouped_mean.unstack(level = 'Adult')\r\n'''\r\nplt.close('all')\r\nfig = plt.figure(figsize=(10,10))\r\naxes = fig.add_subplot(111)\r\nunstacked.axes.bar(rot = 0)\r\naxes.set_ylabel('Percent Strike Success')\r\nplt.show()\r\nout_dir = '../../output/kingfisher/strike_success_age_tide.png'\r\nfig.savefig(out_dir)\r\n'''\r\nlabels = unstacked.index\r\nfig, ax = plt.subplots()\r\nx = np.arange(len(labels))\r\nwidth = 0.35\r\nax.bar(x - width/2, unstacked['Success']['Juvenile']*100, width, label = 'Juvenile', color = 'whitesmoke', edgecolor = 'black', linewidth = 0.5 )\r\nax.bar(x + width/2, unstacked['Success']['Adult']*100, width, label = 'Adult', color = 'gray', edgecolor = 'black', linewidth = 0.5 )\r\nax.set_ylabel('Percent Strike Success', fontsize = fs)\r\nax.set_xlabel('Tide height (m)', fontsize = fs)\r\n#ax.set_title('Scores by group and gender')\r\nax.set_xticks(x)\r\nax.set_xticklabels(labels)\r\nax.legend()\r\nplt.show()\r\nout_dir = '../../output/kingfisher/figure1b.jpg'\r\nfig.savefig(out_dir,dpi=600)\r\n\r\n#Observation times\r\n\r\ncurrent_obs_time = [780,141,512] #minutes for flood, slack, ebb\r\ntide_obs_time = [421,252,355,464] #minutes for low to high\r\n\r\n\r\n########### current attempt ###############\r\n\r\n\r\ncurrent = masked_data[['Current Category','Adult','Success']].groupby(['Current Category','Adult']).count().unstack().rename(columns={0.0: \"Juvenile\", 1.0: \"Adult\"})\r\ncurrent = current.loc[[\"ebb\", \"slack\", \"flood\"]]\r\nlabels = current.index\r\nfig, ax = plt.subplots()\r\nx = np.arange(len(labels))\r\nwidth = 0.35\r\nax.bar(x - width/2, current['Success']['Juvenile']*60/current_obs_time, width, label = 'Juvenile', color = 'whitesmoke', edgecolor = 'black', linewidth = 0.5 ) #multiply by 60 mins/hr and divide by minutes of obs\r\nax.bar(x + width/2, current['Success']['Adult']*60/current_obs_time, width, label = 'Adult', color = 'gray', edgecolor = 'black', linewidth = 0.5 )\r\nax.set_ylabel('Attempts per hour', fontsize = fs)\r\nax.set_xlabel('Current', fontsize = fs)\r\n#ax.set_title('Scores by group and gender')\r\nax.set_xticks(x)\r\nax.set_xticklabels(labels)\r\nax.legend()\r\nplt.show()\r\nout_dir = '../../output/kingfisher/strike_success_age_current_attempts.png'\r\nfig.savefig(out_dir)\r\n\r\n\r\n################# tide attempt ############\r\n\r\ntide = success_tide[['Tide height (m)','Adult', 'Success']].groupby(['Tide height (m)','Adult']).count().unstack().rename(columns={0.0: \"Juvenile\", 1.0: \"Adult\"})\r\nlabels = tide.index\r\nfig, ax = plt.subplots()\r\nx = np.arange(len(labels))\r\nwidth = 0.35\r\nax.bar(x - width/2, tide['Success']['Juvenile']*60/tide_obs_time, width, label = 'Juvenile', color = 'whitesmoke', edgecolor = 'black', linewidth = 0.5 ) #multiply by 60 mins/hr and divide by minutes of obs\r\nax.bar(x + width/2, tide['Success']['Adult']*60/tide_obs_time, width, label = 'Adult', color = 'gray', edgecolor = 'black', linewidth = 0.5 )\r\nax.set_ylabel('Attempts per hour', fontsize = fs)\r\nax.set_xlabel('Tide height (m)', fontsize = fs)\r\n#ax.set_title('Scores by group and gender')\r\nax.set_xticks(x)\r\nax.set_xticklabels(labels)\r\nax.legend()\r\nplt.show()\r\nout_dir = '../../output/kingfisher/figure1a.jpg'\r\nfig.savefig(out_dir,dpi=600)\r\n\r\n############### current success ###################\r\n\r\ncurrent_success = masked_data[['Current Category','Adult','Success']].groupby(['Current Category','Adult']).mean().unstack().rename(columns={0.0: \"Juvenile\", 1.0: \"Adult\"})\r\n\r\nlabels = current_success.index\r\nfig, ax = plt.subplots()\r\nx = np.arange(len(labels))\r\nwidth = 0.35\r\nax.bar(x - width/2, current_success['Success']['Juvenile']*100, width, label = 'Juvenile', color = 'whitesmoke', edgecolor = 'black', linewidth = 0.5 )\r\nax.bar(x + width/2, current_success['Success']['Adult']*100, width, label = 'Adult', color = 'gray', edgecolor = 'black', linewidth = 0.5 )\r\nax.set_ylabel('Percent Strike Success', fontsize = fs)\r\nax.set_xlabel('Current', fontsize = fs)\r\n#ax.set_title('Scores by group and gender')\r\nax.set_xticks(x)\r\nax.set_xticklabels(labels)\r\nax.legend()\r\nplt.show()\r\nout_dir = '../../output/kingfisher/strike_success_age_current.png'\r\nfig.savefig(out_dir)\r\n","sub_path":"kingfisher_feeding_tide.py","file_name":"kingfisher_feeding_tide.py","file_ext":"py","file_size_in_byte":4968,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"247769761","text":"import sqlite3\n\nconn=sqlite3.connect(r\"information.db\")\nc_cursor=conn.cursor()\nx=0\nfor row in c_cursor.execute(\"select * from votetable\"):\n x=x+1\n print(row)\n print()\nprint (x)\nc_cursor.close()\nconn.close()","sub_path":"PI_work/delete.py","file_name":"delete.py","file_ext":"py","file_size_in_byte":215,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"325084374","text":"import unittest\nfrom CreateGraph import *\n\n\nclass TestStringMethods(unittest.TestCase):\n\n logging.basicConfig(filename='create_graph.log', level=logging.DEBUG)\n logging.debug('This message should go to the log file')\n\n graph = createGraph()\n\n\n def test_hub_actors(self):\n hub_actors = self.graph.get_hub_actors()\n\n # clear previous plt graphs\n plt.clf()\n plt.cla()\n plt.close()\n\n # graph top 25 hub actors\n plt1 = graph_hub_actors(hub_actors[:25])\n plt1.savefig('outputs/actor_connections.pdf')\n\n self.assertEquals(hub_actors[0][0], 'Bruce Willis')\n\n\n def test_highest_grossing_ages(self):\n highest_grossing_ages = self.graph.highest_grossing_ages()\n\n # clear previous plt graphs\n plt.clf()\n plt.cla()\n plt.close()\n\n # graph income vs ages\n plt2 = graph_highest_grossing_ages(highest_grossing_ages)\n plt2.savefig('outputs/age_vs_income.pdf')\n\n self.assertEquals(highest_grossing_ages[0][0], 61)\n\n\n def test_graph_visualization(self):\n # clear previous plt graphs\n plt.clf()\n plt.cla()\n plt.close()\n\n # show small subset of graph visualization\n plt3 = visualize_graph(self.graph)\n plt3.savefig('outputs/visualization.pdf')\n\n\n\n\nif __name__ == '__main__':\n unittest.main()\n\n\n\n\n","sub_path":"TestGraph.py","file_name":"TestGraph.py","file_ext":"py","file_size_in_byte":1370,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"50591842","text":"from hazelcast.serialization.bits import *\nfrom hazelcast.protocol.builtin import FixSizedTypesCodec\nfrom hazelcast.protocol.client_message import OutboundMessage, REQUEST_HEADER_SIZE, create_initial_buffer, RESPONSE_HEADER_SIZE, EVENT_HEADER_SIZE\n\n# hex: 0x000600\n_REQUEST_MESSAGE_TYPE = 1536\n# hex: 0x000601\n_RESPONSE_MESSAGE_TYPE = 1537\n# hex: 0x000602\n_EVENT_PARTITION_LOST_MESSAGE_TYPE = 1538\n\n_REQUEST_LOCAL_ONLY_OFFSET = REQUEST_HEADER_SIZE\n_REQUEST_INITIAL_FRAME_SIZE = _REQUEST_LOCAL_ONLY_OFFSET + BOOLEAN_SIZE_IN_BYTES\n_RESPONSE_RESPONSE_OFFSET = RESPONSE_HEADER_SIZE\n_EVENT_PARTITION_LOST_PARTITION_ID_OFFSET = EVENT_HEADER_SIZE\n_EVENT_PARTITION_LOST_LOST_BACKUP_COUNT_OFFSET = _EVENT_PARTITION_LOST_PARTITION_ID_OFFSET + INT_SIZE_IN_BYTES\n_EVENT_PARTITION_LOST_SOURCE_OFFSET = _EVENT_PARTITION_LOST_LOST_BACKUP_COUNT_OFFSET + INT_SIZE_IN_BYTES\n\n\ndef encode_request(local_only):\n buf = create_initial_buffer(_REQUEST_INITIAL_FRAME_SIZE, _REQUEST_MESSAGE_TYPE, True)\n FixSizedTypesCodec.encode_boolean(buf, _REQUEST_LOCAL_ONLY_OFFSET, local_only)\n return OutboundMessage(buf, False)\n\n\ndef decode_response(msg):\n initial_frame = msg.next_frame()\n return FixSizedTypesCodec.decode_uuid(initial_frame.buf, _RESPONSE_RESPONSE_OFFSET)\n\n\ndef handle(msg, handle_partition_lost_event=None):\n message_type = msg.get_message_type()\n if message_type == _EVENT_PARTITION_LOST_MESSAGE_TYPE and handle_partition_lost_event is not None:\n initial_frame = msg.next_frame()\n partition_id = FixSizedTypesCodec.decode_int(initial_frame.buf, _EVENT_PARTITION_LOST_PARTITION_ID_OFFSET)\n lost_backup_count = FixSizedTypesCodec.decode_int(initial_frame.buf, _EVENT_PARTITION_LOST_LOST_BACKUP_COUNT_OFFSET)\n source = FixSizedTypesCodec.decode_uuid(initial_frame.buf, _EVENT_PARTITION_LOST_SOURCE_OFFSET)\n handle_partition_lost_event(partition_id, lost_backup_count, source)\n return\n","sub_path":"hazelcast/protocol/codec/client_add_partition_lost_listener_codec.py","file_name":"client_add_partition_lost_listener_codec.py","file_ext":"py","file_size_in_byte":1930,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"127945535","text":"#Tekir By Haso\nimport discord\nimport asyncio\nimport logging\nimport random\nfrom discord.ext.commands import Bot\nfrom discord.ext import commands\n\nBOT_PREFIX = \"hkd!\"\nTOKEN = \"NjgzNTk4MzU4MDY1MTg0NzY4.XnH7DQ.TtiJsnygccoZW3QZ_3tsujsnL7I\"\nclient = Bot (command_prefix=BOT_PREFIX)\n\nprint (discord.__version__)\n\n@client.event\nasync def on_ready():\n print (\"Hazırım!!!\")\n print (\"Başlıyorum!!! \" + client.user.name)\n print (\"ID: \" + client.user.id) \n await client.change_presence(game=discord.Game(name='hkd!'))\n\n@client.event\nasync def on_message(message):\n if message.author == client.user:\n return\n\n if message.content.startswith('hkd!okkes'):\n await client.send_message(message.author, 'https://i.hizliresim.com/k01jqv.gif')\nclient.run(TOKEN) \n","sub_path":"tekir.py","file_name":"tekir.py","file_ext":"py","file_size_in_byte":777,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"17898023","text":"# This is a sample Python script.\nfrom DataPatient import DataPatient\nfrom Data import Data\n# Press Shift+F10 to execute it or replace it with your code.\n# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.\n\n # d = DataPatient(\"цукцук\",\"цукцук\",\"цукцук\",\"цукцук\",12554455,\"цукцук\",\"цукцук\",\"цукцук\")\ndatabase = Data\ndataList = database.Load(database)\nfor record in dataList:\n print(record.name)\n\nd = DataPatient()\nd.SetPatient(\"Максим\", \"Николаевич\", \"Кожин\", \"06.08.1983\", \"124578\", \"Смирнова МК\", \"07.12.2021\", \"мужской\")\n\ndataList = database.Add(dataList, d)\ndatabase.Save(dataList)\n\ndataList = database.Load(database)\nfor record in dataList:\n print(record.name)\n\n# dataList = database.Load(database)\n# for record in dataList:\n# print(record.name)\n\n# ��оиск\nx = input(str())\ndataList = database.Load(database)\nfor record in dataList:\n\n print(record.name)\n\n# print(dataList)\n\n# Поиск\n# x = input(str())\n# poisk = Data.FindName(database,x)\n# print(x)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1107,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"189648664","text":"from sklearn.model_selection import train_test_split\nfrom sklearn.base import BaseEstimator\nfrom sklearn.utils import shuffle\nfrom sklearn.utils.validation import check_X_y, check_array\nfrom sklearn.model_selection import GridSearchCV\nimport math\nimport numpy as np\nimport logging\nfrom tqdm import tqdm\n\nlogger = logging.getLogger('ensemble.cobra')\n\n\nclass Cobra(BaseEstimator):\n \"\"\"\n COBRA: A combined regression strategy.\n Based on the paper by Biau, Fischer, Guedj, Malley [2016].\n This is a pythonic implementation of the original COBRA code.\n\n Parameters\n ----------\n random_state: integer or a numpy.random.RandomState object.\n Set the state of the random number generator to pass on to shuffle and loading machines, to ensure\n reproducibility of your experiments, for example.\n\n epsilon: float, optional\n Epsilon value described in the paper which determines which points are selected for the aggregate.\n Default value is determined by optimizing over a grid if test data is provided.\n If not, a mean of the possible distances is chosen.\n\n k: float, default 0.5\n k value described in the paper which determines how many points are selected in the optimal process\n\n alpha: int, optional\n alpha refers to the number of machines the prediction must be close to to be considered during aggregation.\n\n regression : boolean, default True\n If True - perform stacking for regression task,\n if False - perform stacking for classification task\n\n metric:callable, default None\n Evaluation metric (score function) which is used to calculate results of each split.\n\n shuffle : boolean, default False\n Whether to perform a shuffle before cross-validation split\n\n models : default None\n used to fit and predict the data\n\n Attributes\n ----------\n machines_: A dictionary which maps machine names to the machine objects.\n The machine object must have a predict method for it to be used during aggregation.\n\n machine_predictions_: A dictionary which maps machine name to it's predictions over X_l\n This value is used to determine which points from y_l are used to aggregate.\n\n all_predictions_: numpy array with all the predictions, to be used for epsilon manipulation.\n\n \"\"\"\n\n def __init__(self,X = None, y=None, regression=True, metric = None, shuffle=None, random_state=None, epsilon=None,\n alpha=None, models=None, k=None):\n self.random_state = random_state\n self.epsilon = epsilon\n self.alpha = alpha\n self.models = models\n self.shuffle = shuffle\n self.metric = metric\n self.k = k\n self.X_ = X\n self.y_ = y\n self.regression = regression\n\n\n def opmimal_parameters(self, X = None, y=None, eps_size=None, grid_points=None, verbose = 0):\n \"\"\"\n Parameters\n ----------\n X: array-like, [n_samples, n_features]\n data which will be used to find the optimal parameters.\n y: array-like, [n_samples, n_features]\n data which will be used to find the optimal parameters.\n eps_size: float\n determines how many data are used in this process\n grid_points: int, optional\n If no epsilon value is passed, this parameter controls how many points on the grid to traverse.\n \"\"\"\n\n _, X_eps, _, y_eps = train_test_split(X, y, test_size=eps_size, shuffle=self.shuffle, random_state=self.random_state)\n print(\"Number of optimal data:\", len(y_eps), \"\\n\")\n if self.regression:\n self.set_epsilon(X_epsilon=X_eps, y_epsilon=y_eps, grid_points=grid_points,\n verbose=verbose)\n self.set_alpha(X_epsilon=X_eps, y_epsilon=y_eps,verbose=verbose)\n self.set_split(X_epsilon=X_eps, y_epsilon=y_eps)\n\n def fit(self, X, y):\n \"\"\"\n Parameters\n ----------\n X: array-like, [n_samples, n_features]\n Training data which will be used to create the COBRA aggregate.\n\n y: array-like, shape = [n_samples]\n Target values used to train the machines used in the aggregation.\n\n X_k : shape = [n_samples, n_features]\n Training data which is used to train the machines used in the aggregation.\n Can be loaded directly into COBRA; if not, the split_data method is used as default.\n\n y_k : array-like, shape = [n_samples]\n Target values used to train the machines used in the aggregation.\n\n X_l : shape = [n_samples, n_features]\n Training data which is used to form the aggregate.\n Can be loaded directly into COBRA; if not, the split_data method is used as default.\n\n y_l : array-like, shape = [n_samples]\n Target values which are actually used to form the aggregate.\n \"\"\"\n X, y = check_X_y(X, y)\n self.X_ = X\n self.y_ = y\n self.machines_ = {}\n\n\n if self.k is None:\n self.split_data()\n self.load_machines()\n self.load_machine_predictions()\n else:\n k = int(self.k * len(self.X_))\n l = len(self.X_)\n self.X_k_ = self.X_[:k]\n self.X_l_ = self.X_[k:l]\n self.y_k_ = self.y_[:k]\n self.y_l_ = self.y_[k:l]\n self.load_machines()\n self.load_machine_predictions()\n return self\n\n\n def set_epsilon(self, X_epsilon=None, y_epsilon=None, grid_points=None, verbose=0):\n \"\"\"\n Parameters\n ----------\n\n X_epsilon : shape = [n_samples, n_features]\n Used if no epsilon is passed to find the optimal epsilon for data passed.\n\n y_epsilon : array-like, shape = [n_samples]\n Used if no epsilon is passed to find the optimal epsilon for data passed.\n\n grid_points: int, optional\n If no epsilon value is passed, this parameter controls how many points on the grid to traverse.\n \n \"\"\"\n # set up COBRA to perform CV and find an optimal epsilon.\n print(\"---------Finding the optimal epsilon---------\")\n if self.epsilon is None and X_epsilon is not None:\n self.X_ = X_epsilon\n self.y_ = y_epsilon\n\n self.split_data()\n self.load_machines()\n self.load_machine_predictions()\n\n # get the candidate epsilons\n a, size = sorted(self.all_predictions_), len(self.all_predictions_)\n res = [a[i + 1] - a[i] for i in range(size) if i+1 < size]\n emin = min(res)\n emax = max(a) - min(a)\n erange = np.linspace(emin, emax, grid_points)\n tuned_parameters = [{'epsilon': erange}]\n print(tuned_parameters)\n clf = GridSearchCV(Cobra(epsilon=None, models=self.models, regression=True,\n random_state=self.random_state), tuned_parameters,\n return_train_score=False, verbose=verbose,\n cv=5, scoring=\"neg_mean_squared_error\")\n clf.fit(X_epsilon, y_epsilon)\n self.epsilon = clf.best_params_[\"epsilon\"]\n self.machines_, self.machine_predictions_ = {}, {}\n print(\"optimal epsilon = \", self.epsilon, \"\\n\")\n\n def set_alpha(self, X_epsilon=None, y_epsilon=None,verbose=0):\n print(\"---------Finding the optimal alpha---------\")\n if self.alpha is None and X_epsilon is not None:\n self.X_ = X_epsilon\n self.y_ = y_epsilon\n arange = range(1, len(self.models) + 1)\n tuned_parameters = [{'alpha': arange}]\n if self.regression:\n clf = GridSearchCV(Cobra(epsilon=self.epsilon, models=self.models, regression=True,\n random_state=self.random_state),\n tuned_parameters,return_train_score=False,verbose=verbose,\n cv=5, scoring=\"neg_mean_squared_error\")\n else:\n clf = GridSearchCV(Cobra(epsilon=self.epsilon, models=self.models, regression=False,\n random_state=self.random_state),\n tuned_parameters, cv=5, scoring=\"accuracy\")\n clf.fit(X_epsilon, y_epsilon)\n self.alpha = clf.best_params_[\"alpha\"]\n self.machines_, self.machine_predictions_ = {}, {}\n print(\"omtimal alpha = \", self.alpha, \"\\n\")\n\n def set_split(self, X_epsilon=None, y_epsilon=None):\n print(\"---------Finding the optimal k---------\")\n X_eps_train, X_eps_pre, y_eps_train, y_eps_pre = train_test_split(X_epsilon, y_epsilon, test_size=0.2, shuffle=self.shuffle,\n random_state=self.random_state)\n split = [(0.20, 0.80), (0.40, 0.60), (0.50, 0.50), (0.60, 0.40), (0.80, 0.20)]\n Score= {}\n for k, l in split:\n # print('k = ',k)\n if self.regression:\n machine = Cobra(X=X_eps_train, y=y_eps_train, epsilon=self.epsilon, models=self.models,\n random_state=self.random_state,regression=True,\n alpha=self.alpha)\n else:\n machine = Cobra(X=X_eps_train, y=y_eps_train, epsilon=self.epsilon, models=self.models,\n random_state=self.random_state,regression=False,\n alpha=self.alpha)\n\n machine.split_data(int(k * len(X_eps_train)), int((k + l) * len(X_eps_train)))\n\n machine.load_machines()\n\n machine.load_machine_predictions()\n\n results = machine.predict(X_eps_pre)\n Score[(k, l)] = (self.metric(y_eps_pre, results))\n if self.regression:\n opt = min(Score, key=Score.get)\n else:\n opt = max(Score, key=Score.get)\n self.k = opt[0]\n print(\"optimal k = \", self.k, \"\\n\")\n\n def pred(self, X, alpha, info=False):\n \"\"\"\n Performs the COBRA aggregation scheme, used in predict method.\n\n Parameters\n ----------\n X: array-like, [n_features]\n\n alpha: int, optional\n alpha refers to the number of machines the prediction must be close to to be considered during aggregation.\n\n info: boolean, optional\n If info is true the list of points selected in the aggregation is returned.\n\n Returns\n -------\n avg: prediction\n\n \"\"\"\n # dictionary mapping machine to points selected\n select = {}\n for machine in self.machines_:\n # machine prediction\n val = self.machines_[machine].predict(X)\n select[machine] = set()\n # iterating from l to n\n # replace with numpy iteration\n for count in range(0, len(self.X_l_)):\n if self.regression:\n try:\n # if value is close to prediction, select the indice\n if math.fabs(self.machine_predictions_[machine][count] - val) <= self.epsilon:\n select[machine].add(count)\n except (ValueError, TypeError) as e:\n logger.info(\"Error in indice selection\")\n continue\n else:\n if self.machine_predictions_[machine][count] == val:\n select[machine].add(count)\n\n points = []\n # count is the indice number.\n for count in range(0, len(self.X_l_)):\n # row check is number of machines which picked up a particular point\n row_check = 0\n for machine in select:\n if count in select[machine]:\n row_check += 1\n if row_check >= alpha:\n points.append(count)\n\n # if no points are selected, return 0\n if len(points) == 0:\n if info:\n logger.info(\"No points were selected, prediction is 0\")\n return (0, 0)\n return 0\n\n # aggregate\n if self.regression:\n avg = 0\n for point in points:\n avg += self.y_l_[point]\n avg = avg / len(points)\n if info:\n return avg, points\n return avg\n else:\n classes = {}\n for label in np.unique(self.y_l_):\n classes[label] = 0\n\n for point in points:\n classes[self.y_l_[point]] += 1\n result = int(max(classes, key=classes.get))\n if info:\n return result, points\n return result\n\n\n\n\n def predict(self, X, info=False):\n \"\"\"\n Performs the COBRA aggregation scheme, calls pred.\n\n Parameters\n ----------\n X: array-like, [n_features]\n\n info: boolean, optional\n If info is true the list of points selected in the aggregation is returned.\n\n Returns\n -------\n result: prediction\n\n \"\"\"\n\n # sets alpha as the total number of machines as a default value\n\n X = check_array(X)\n # sets alpha as the total number of machines as a default value\n if self.alpha is None:\n self.alpha = len(self.models)\n # print(\"alpha:\", self.alpha)\n # if self.epsilon is not None:\n # print(\"epsilon:\", self.epsilon)\n if X.ndim == 1:\n return self.pred(X.reshape(1, -1), info=info, alpha=self.alpha)\n\n result = np.zeros(len(X))\n avg_points = 0\n index = 0\n for vector in X:\n if info:\n result[index], points = self.pred(vector.reshape(1, -1), info=info, alpha=self.alpha)\n avg_points += len(points)\n else:\n result[index] = self.pred(vector.reshape(1, -1), info=info, alpha=self.alpha)\n index += 1\n\n if info:\n avg_points = avg_points / len(X)\n return result, avg_points\n\n return result\n\n\n def split_data(self, k=None, l=None):\n \"\"\"\n Split the data into different parts for training machines and for aggregation.\n\n Parameters\n ----------\n k : int, optional\n k is the number of points used to train the machines.\n Those are the first k points of the data provided.\n\n l: int, optional\n l is the number of points used to form the COBRA aggregate.\n\n shuffle: bool, optional\n Boolean value to decide to shuffle the data before splitting.\n\n Returns\n -------\n self : returns an instance of self.\n \"\"\"\n if self.shuffle:\n self.X_, self.y_ = shuffle(self.X_, self.y_, random_state=self.random_state)\n\n if k is None and l is None:\n k = int(len(self.X_) / 2)\n l = int(len(self.X_))\n\n if k is not None and l is None:\n l = len(self.X_) - k\n\n if l is not None and k is None:\n k = len(self.X_) - l\n\n self.X_k_ = self.X_[:k]\n self.X_l_ = self.X_[k:l]\n self.y_k_ = self.y_[:k]\n self.y_l_ = self.y_[k:l]\n\n return self\n\n\n def load_machines(self):\n \"\"\"Fit the machines\"\"\"\n self.machines_ = {}\n for model in self.models:\n self.machines_[model.__class__.__name__] = model.fit(self.X_k_, self.y_k_)\n return self\n\n\n def load_machine_predictions(self):\n \"\"\"\n Stores the trained machines' predicitons on training data in a dictionary, to be used for predictions.\n Should be run after all the machines to be used for aggregation is loaded.\n\n Parameters\n ----------\n predictions: dictionary, optional\n A pre-existing machine:predictions dictionary can also be loaded.\n\n Returns\n -------\n self : returns an instance of self.\n \"\"\"\n self.machine_predictions_ = {}\n self.all_predictions_ = np.array([])\n for machine in self.machines_:\n self.machine_predictions_[machine] = self.machines_[machine].predict(self.X_l_)\n self.all_predictions_ = np.append(self.all_predictions_, self.machine_predictions_[machine])\n return self\n","sub_path":"autotf/ensemble/ML/ensemble/cobra.py","file_name":"cobra.py","file_ext":"py","file_size_in_byte":16382,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"467154429","text":"# 需求如下:\n#\n# 1. 房子(House) 有 户型、总面积 、剩余面积 和 家具名称列表 属性\n# - 新房子没有任何的家具\n# - 将 家具的名称 追加到 家具名称列表 中\n# - 判断 家具的面积 是否 超过剩余面积,如果超过,提示不能添加这件家具\n# 2. 家具(HouseItem) 有 名字 和 占地面积属性,其中\n# - 席梦思(bed) 占地 4 平米\n# - 衣柜(chest) 占地 2 平米\n# - 餐桌(table) 占地 1.5 平米\n# 3. 将以上三件 家具 添加 到 房子 中\n# 4. 打印房子时,要求输出:户型、总面积、剩余面积、家具名称列表\n# 使用面向对象思想,编码完成上述功能。\n\n## 房子的类型\nclass House(object):\n #缺省参数 ,家具是空列表,就是空值\n def __init__(self,hour_type,total_area,fru_list=None):\n if fru_list is None:\n fru_list = [] #将fru_list 设置为空列表\n self.hour_type = hour_type\n self.totaol_area = total_area\n self.free_area = total_area * 0.6\n self.fru_list = fru_list\n\n def add_fru(self,x):\n # print('需要把家具添加到房子里面')\n if self.free_area < x.area:\n print('剩余面积不足,放不进去了')\n else:\n self.fru_list.append(x.name)\n self.free_area -= x.area\n def __str__(self):\n return '户型={},总面积={},剩余面积={},家具列表={}'.format(self.hour_type,self.totaol_area,self.free_area,self.fru_list)\n\n# 家具的类\nclass Furniture(object):\n def __init__(self,name,area):\n self.name = name\n \n self.area = area\n\nbed = Furniture('席木思',20)\nchest = Furniture('衣柜',10)\ntalbe = Furniture('餐桌',1.5)\nsofa = Furniture('沙发',2\n\n )\n\n#创建房间对象的时候,传入户型和总面积\nhouse1 = House('两室一厅',56)\n#把家具添加到房间里面(面向对象的关注点,是让谁做)\nhouse1.add_fru(sofa)\nhouse1.add_fru(bed)\nhouse1.add_fru(chest)\nhouse1.add_fru(talbe)\nprint(house1) #默认打印内存地址 ,需要重新str方法,才能获取返回值\n\n\n","sub_path":"11.面向对象/91.面向对象的练习.py","file_name":"91.面向对象的练习.py","file_ext":"py","file_size_in_byte":2139,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"191848248","text":"from base import PsywerxPlugin\nfrom response import REPOSTS, MULTIPLE_REPOST, \\\n SELF_REPOSTS, MULTIPLE_SELF_REPOST, random_response\n\n\nclass PsywerxHistory(PsywerxPlugin):\n\n def handle_message(self, channel, nick, msg, line=None):\n r = self.request(channel, 'irc/add', {'raw': line})\n if not r:\n return\n if r.startswith('REPOST'):\n self._handle_repost(r, channel)\n elif r != 'OK':\n self.bot.log_error(\"Response not OK: \" + r)\n\n def handle_say(self, channel, msg, line):\n msg = \":\" + self.bot.nick + \"!~\" + self.bot.nick + \"@6.6.6.6 \" + line\n self.request(channel, 'irc/add', {'raw': msg})\n\n def _handle_repost(self, r, channel):\n _, nick, repost_nick, message_type, num = r.split(' ')\n if message_type != 'M':\n return\n\n response = self._pick_response(nick == repost_nick, int(num) > 1)\n self.bot.say(response % {\n 'nick': nick,\n 'repost_nick': repost_nick,\n 'num': num,\n }, channel)\n\n @staticmethod\n def _pick_response(is_self, is_multiple):\n f = [\n [REPOSTS, MULTIPLE_REPOST],\n [SELF_REPOSTS, MULTIPLE_SELF_REPOST],\n ]\n return random_response(f[is_self][is_multiple])\n","sub_path":"src/plugins/psywerx_history.py","file_name":"psywerx_history.py","file_ext":"py","file_size_in_byte":1284,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"138916724","text":"# Эта программа применяет словарь для хранения\n# имен и дней рождения друзей.\n\n# Глобальные константы для пунктов меню.\nLOOK_UP = 1\nADD = 2\nCHANGE = 3\nDELETE = 4\nQUIT = 5\n\n# Главная функция.\ndef main():\n # Создать пустой словарь.\n birthdays = {}\n\n # Инициализировать переменную для выбора прользователя.\n choice = 0\n\n while choice != QUIT:\n # Получить выбранный пользователем пункт меню.\n choice = get_menu_choice()\n\n # Обработать выбранный вариант действий.\n if choice == LOOK_UP:\n look_up(birthdays)\n elif choice == ADD:\n add(birthdays)\n elif choice == CHANGE:\n change(birthdays)\n elif choice == DELETE:\n delete(birthdays)\n\n# Функция get_menu_choice выводит меню и получает\n# проверенный на допустимость выбранный пользователм пункт.\ndef get_menu_choice():\n print()\n print('Друзья и их дни рождения')\n print('------------------------')\n print('1. Найти день рождения')\n print('2. Добавить новый день рождения')\n print('3. Изменить день рождения')\n print('4. Удалить день рождения')\n print('5. Выйти из программы')\n print()\n\n # Получить выбранный пользователм пункт.\n choice = int(input('Введите выбранный пункт: '))\n\n # Проверить выбранный пункт на допустимость.\n while choice < LOOK_UP or choice > QUIT:\n choice = int(input('Введите выбранный пункт: '))\n\n # Вернуть выбранный пользователем пункт.\n return choice\n\n# Функция look_up отыскивает имя\n# в словаре birthdays.\ndef look_up(birthdays):\n # Получить искомое имя.\n name = input('Введите имя: ')\n\n # Отыскать его в словаре.\n print(birthdays.get(name, 'Не найдено.'))\n\n# Функция add добавляет новую запись\n# в словарь birthdays.\ndef add(birthdays):\n # Получить имя и день рождения.\n name = input('Введите имя: ')\n bday = input('Введите день рождения: ')\n\n # Если имя не существует, то его добавить.\n if name not in birthdays:\n birthdays[name] = bday\n else:\n print('Эта запись уже существует.')\n\n# Функция change изменяет существующую\n# запись в словаре birthdays.\ndef change(birthdays):\n # Получить искомое имя.\n name = input('Введите имя: ')\n\n if name in birthdays:\n # Получить новый день рождения.\n bday = input('Введите новый день рождения: ')\n\n # Обновить запись.\n birthdays[name] = bday\n else:\n print('Это имя не найдено.')\n\n# Функция delete удаляет запись из\n# словаря birthdays.\ndef delete(birthdays):\n # Получить искомое имя.\n name = input('Введите имя: ')\n\n # Если имя найдено, то удалить эту запись.\n if name in birthdays:\n del birthdays[name]\n else:\n print('Это имя не найдено.')\n\nmain()","sub_path":"9/birthdays.py","file_name":"birthdays.py","file_ext":"py","file_size_in_byte":3802,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"110366685","text":"#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n# version:V.1.0.0 2017-02-17\n# 根据生产的差错文件进行逐一分析,打印出修改的sql或解决办法\n\n# version:V.1.0.1 2017-02-21\n# 1、分离判断逻辑 conf路径新增process_dict.py\n\n# author yubin.yang\n\nimport os, datetime\nimport sbin.p2p_ycjk\nimport conf.location\n\ntoday = datetime.datetime.now()\nyesterday = sbin.p2p_ycjk.get_yesterdy(today)\nlog_location = os.path.join(conf.location.log_dir, 'sql_' + yesterday + '.txt')\nbr = os.linesep\n\n\n##定义自动处理函数\n\ndef process(cmdid, ord_id):\n with open(log_location, 'a') as f:\n if cmdid == 'UserRegister':\n f.write(\n \"update mer_dbubs.usr_base_info t set t.login_id = replace(t.login_id, substr(t.login_id, instr(t.login_id, '_') + 1,'2'),'yw') \"\n \"where t.login_id =\" + ord_id + \";\" + br)\n f.write(\n \"update mer_dbubs.login_usr_info t set t.usr_id= replace(t.usr_id, substr(t.usr_id, instr(t.usr_id, '_') + 1,'2'),'yw') \"\n \"where t.usr_id=\" + ord_id + \";\" + br)\n elif cmdid == 'Loans':\n f.write(\"update mer_Dbmuser.bid_lend_log t set t.lend_stat='P' \"\n \"where t.lend_ord_id=\" + ord_id + \";\" + br)\n elif cmdid == 'Repayment':\n f.write(\"update mer_Dbmuser.bid_ret_log t set t.ret_stat='P' \"\n \"where t.ret_ord_id=\" + ord_id + \";\" + br)\n elif cmdid == 'Transfer':\n f.write(\"update mer_Dbmuser.Mer_Trf_Log t set trans_Stat='S' \"\n \"where t.trf_ord_id=\" + ord_id + \";\" + br)\n elif cmdid == 'CreditAssign':\n f.write(\"update mer_Dbmuser.bid_ca_log t set stat='S' \"\n \"where t.bid_ord_id=\" + ord_id + \";\" + br)\n elif cmdid == 'UsrFreezeBg01':\n f.write(\"update mer_dbmuser.mer_frz_log t set t.frz_stat = 'F',t.bg_date = \" \\\n \"(select c.acct_date from MER_dbacct.frz_log c where c.frt_date = t.acct_date and c.Frt_Seq_Id = t.acct_seq_id and c.acct_date = t.acct_date), \" \\\n \"t.bg_seq_id =(select c.acct_seq_id from MER_dbacct.frz_log c where c.frt_date = t.acct_date and c.Frt_Seq_Id = t.acct_seq_id and c.acct_date = t.acct_date)\" \\\n \"where t.frz_ord_id=\" + ord_id + \";\" + br)\n elif cmdid == 'UsrFreezeBg02':\n f.write(\"update mer_dbmuser.mer_frz_log t set t.frz_stat = 'U'\"\n \"where t.frz_ord_id=\" + ord_id + \";\" + br)\n elif cmdid == 'NetSave01':\n f.write(\"充值已入款但未入账,需联系基础组同事协查,天天付订单号为:\" + ord_id + \";\" + br)\n elif cmdid == 'NetSave02':\n f.write(\"充值已入款但收银台状态为失败,需联系基础组同事协查,天天付订单号为:\" + ord_id + \";\" + br)\n elif cmdid == 'Cash':\n f.write(\"取现失败账务已扣除,资金未退还,需联系基础组同事协查,钱三流水号为:\" + ord_id + \";\" + br)\n else:\n f.write(\"出意外了,需核查这个订单号是什么交易: \" + ord_id + \";\" + br)\n\n\n# 连接数据库。安全考虑只生成ddl的sql脚本\n# db = cx_Oracle.connect('OPUSER/Oracle.123@192.168.4.248/testdb')\n# curs=db.cursor()\n\n# 打开文件获取相关信息,并做相应判断处理\nwith open('/home/yunwei2/jiankong/log/log_' + yesterday + '.txt', 'r') as f:\n for line in f.readlines():\n if len(line) > 1:\n cmdid = line.split(':')[1].split(' ')[0] # 从txt中获取标识号\n custid = line.strip('\\n').split(':')[2].split(' ')[0] # 获取客户号\n ordid = line.strip('\\n').split(':')[3].split(' ')[0] # 获取订单号\n process(cmdid, ordid)\n","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":3744,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"642713905","text":"#!/usr/bin/env python\n#\n# Copyright 2012 Ezox Systems LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n\n\"\"\"Service endpoint mapping.\n\nIf this file gets large (say over 500 hundred lines), we suggest breaking\nit up into a package.\n\"\"\"\n\nimport json\nimport logging\n\nimport webapp2\n\n\nclass PersonHandler(webapp2.RequestHandler):\n def get(self):\n from demo.person import Person\n user_query = self.request.get('query')\n limit = int(self.request.get('limit', 10))\n\n query = Person.query()\n if user_query:\n search = user_query.strip().lower()\n query = query.filter(Person.n_ >= search)\n query = query.filter(Person.n_ < search + u\"\\uFFFD\")\n\n if limit > 0:\n query = query.fetch(limit)\n\n out = [entity.to_dict() for entity in query]\n self.response.out.write(json.dumps(out))\n\n def delete(self):\n from google.appengine.ext import ndb\n from demo.person import Person\n urlsafe = self.request.path.rsplit('/', 1)[-1]\n if not urlsafe:\n return\n\n key = ndb.Key(urlsafe=urlsafe)\n if key.kind() != Person._get_kind():\n self.error(500)\n return\n\n key.delete()\n logging.info(\"Deleted person with key: %s\", urlsafe)\n\n def post(self):\n self.process()\n\n def put(self):\n self.process()\n\n def process(self):\n from voluptuous import Schema\n from demo.person import Person\n from demo.person import person_schema\n\n person = json.loads(self.request.body)\n schema = Schema(person_schema, extra=True)\n try:\n schema(person)\n except:\n logging.exception('validation failed')\n logging.info(person)\n\n person_entity = Person.from_dict(person)\n person_entity.put()\n\n out = person_entity.to_dict()\n self.response.out.write(json.dumps(out))\n\n","sub_path":"demo/demo/service.py","file_name":"service.py","file_ext":"py","file_size_in_byte":2431,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"107016436","text":"from django.shortcuts import render, get_object_or_404\nfrom django.http import HttpResponseRedirect, HttpResponse\nfrom django.urls import reverse\nfrom django.utils import timezone\nfrom django.contrib.auth import authenticate, login\nfrom .forms import PostForm, CommentForm\nfrom .models import Post, Profile, Comment, SubComment\n\n\n# Create your views here.\ndef index(request):\n post_list = Post.objects.all().order_by('-pub_date')\n return render(request, 'posts/index.html', {'post_list': post_list})\n\n\ndef post(request, post_id):\n post = get_object_or_404(Post, pk=post_id)\n comments = Comment.objects.filter(post=post_id)\n context = {\n 'post': post,\n 'comments': comments\n }\n return render(request, 'posts/post.html', context=context)\n\n\ndef add_post(request):\n if request.method == 'POST':\n form = PostForm(request.POST)\n if form.is_valid():\n post = Post()\n profile = Profile.objects.all()[0]\n post.title = form.cleaned_data['title']\n post.text = form.cleaned_data['text']\n post.pub_date = timezone.now()\n post.author = profile\n post.save()\n return HttpResponseRedirect(reverse('posts:index'))\n return HttpResponse('WTF POST')\n else:\n return HttpResponseRedirect('WTF METHOD')\n\n\ndef add_comment(request, post_id):\n if request.method == 'POST':\n form = CommentForm(request.POST)\n if form.is_valid():\n comment = Comment()\n comment.post = get_object_or_404(Post, pk=post_id)\n comment.comment_owner = form.cleaned_data['comment_owner']\n comment.comment = form.cleaned_data['comment']\n comment.comment_date = timezone.now()\n comment.save()\n return HttpResponseRedirect(reverse('posts:post', kwargs={'post_id': post_id}))\n else:\n return HttpResponse(form)\n else:\n return HttpResponseRedirect('WTF')\n\n\ndef post_form(request, post_id):\n # post = get_object_or_404(Post, pk=post_id)\n # form = PostForm(initial={\n # 'title': post.title,\n # 'text': post.text\n # })\n\n post = get_object_or_404(Post, pk=post_id)\n form = PostForm(instance=post)\n return render(request, 'posts/post_form.html', {'form': form, 'post_id': post_id})\n\n\ndef update_post(request, post_id):\n if request.method == 'POST':\n form = PostForm(request.POST)\n if form.is_valid():\n post = Post.objects.get(pk=post_id)\n post.title = form.cleaned_data['title']\n post.text = form.cleaned_data['text']\n post.save()\n return HttpResponseRedirect(reverse('posts:post', kwargs={'post_id': post_id}))\n return HttpResponse('WTF FORM')\n else:\n return HttpResponse('WTF METHOD')\n\n\ndef delete_post(request, post_id):\n post = get_object_or_404(Post, pk=post_id)\n post.delete()\n return HttpResponseRedirect(reverse('posts:index'))\n\n\ndef my_login(request):\n username = request.POST['username']\n password = request.POST['password']\n\n user = authenticate(request, username=username, password=password)\n if user is not None:\n login(request, user)\n return HttpResponseRedirect(reverse('posts:index'))\n else:\n return HttpResponse(\"WTF LOGIN.\")\n\n\ndef about(request):\n return render(request, 'posts/about.html')\n\n\ndef contact(request):\n return render(request, 'posts/contact.html')\n","sub_path":"posts/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3479,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"643847518","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\ndef fizzbuzz(number):\n\n\tfizz = \"Fizz\"\n\tbuzz = \"Buzz\"\n\tfizzbuzz = fizz + buzz\n\n\ttry:\n\t\tnumber = int(number)\n\n\texcept ValueError:\n\t\tprint(\"Please enter an integer or a whole number\")\n\n\tif number % 3 ==0 and number % 5 == 0:\n\t\tprint(fizzbuzz)\n\t\treturn fizzbuzz\n\telif number % 3 == 0:\n\t\tprint(fizz)\n\t\treturn fizz\n\telif number % 5 == 0:\n\t\tprint(buzz)\n\t\treturn buzz\t\n\telse:\n\t\tprint(\"{}\".format(number))\n\t\treturn number\n","sub_path":"Problems/Edabit/Easy/FizzBuzz/fizzbuzz.py","file_name":"fizzbuzz.py","file_ext":"py","file_size_in_byte":460,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"335201356","text":"import json\r\nimport cv2\r\nfrom Reminder import *\r\nfrom Recordbook import *\r\nfrom LoginSYS import *\r\nfrom Mission import *\r\nfrom DataManage import *\r\nfrom threading import Thread\r\nfrom Chatroom import *\r\n\r\ndef Searchinfo():\r\n with open('ID_data.json', 'r' , encoding='utf-8-sig') as j:\r\n data = json.load(j)\r\n for x in data :\r\n Localid = x[\"account_id\"]\r\n with open('data.json', 'r', encoding='utf-8-sig') as f:\r\n data = json.load(f)\r\n for x in data :\r\n if(Localid == x[\"account_id\"]):\r\n name = x[\"account_name\"]\r\n confident = int(x[\"self-confident\"])\r\n print(\"賬號名稱 :\" , name)\r\n print(\"自信心數值 :\", confident)\r\n\r\ndef character():\r\n with open('ID_data.json', 'r' , encoding='utf-8-sig') as j:\r\n data = json.load(j)\r\n for x in data :\r\n Localid = x[\"account_id\"]\r\n imgB = cv2.imread(Localid+'.jpg')\r\n cv2.namedWindow('model', cv2.WINDOW_NORMAL)\r\n cv2.imshow('model', imgB)\r\n cv2.waitKey(0)\r\n cv2.destroyAllWindows()\r\n\r\nif __name__ == \"__main__\":\r\n Thread(target=remind).start()\r\n while 1:\r\n print('1.註冊系統 2.登入系統 3.退出程序')\r\n cmd = int(input())\r\n if cmd == 1:\r\n resigter()\r\n elif cmd == 2:\r\n login()\r\n while 1:\r\n print('1.角色資料 2.任務牆 3.好友 4.記帳本 5.查詢角色資訊 6.登出 ')\r\n point = int(input(\"請輸入功能選項 : \"))\r\n if point == 1:\r\n character()\r\n elif point == 2:\r\n mission()\r\n elif point == 3:\r\n HOST = input('Enter host: ')\r\n PORT = input('Enter port: ')\r\n Thread(target=chatroom(HOST,PORT)).start()\r\n elif point == 4:\r\n Record_Book()\r\n elif point == 5:\r\n Searchinfo()\r\n elif point == 6:\r\n break\r\n else:\r\n print(\"請輸入1-6的功能選項\")\r\n elif cmd == 3 :\r\n exit()\r\n else :\r\n continue\r\n","sub_path":"src/Main.py","file_name":"Main.py","file_ext":"py","file_size_in_byte":2171,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"637435778","text":"import sys\nimport os\n\nsys.path.append(os.path.abspath(os.path.dirname(__file__)))\n\n\nclass Service(object):\n def __init__(self, law):\n # loi regissant le service\n self.__law = law\n # temps avant la prochaine disponibilite de la caisse\n self.available_in = 0\n # liste de toutes les entites ayant passe dans le service\n self.__entities_history = []\n\n @property\n def entities_history(self):\n return self.__entities_history\n\n # prend en charge une entite\n def take_in_charge_entity(self, entity):\n # modifie la date de prise en charge de l'entite\n entity.in_charge_time = self.available_in\n # genere un temps de traitement aleatoire selon la loi\n in_charge_duration = self.__law.get_random_time()\n # modifie la date de depart de l'entite\n entity.departure_time = self.available_in + in_charge_duration\n # change la date de sa prochaine disponibilite\n self.available_in = entity.departure_time\n # ajout l'entite dans l'historique\n self.__entities_history.append(entity)\n","sub_path":"Service.py","file_name":"Service.py","file_ext":"py","file_size_in_byte":1098,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"134522470","text":"#!/usr/bin/env python\n# vim: set ts=4 sw=4 et sts=4 ai:\n\nimport array\nimport usb.core\nimport usb.util\n\n\nVC_EEPROM = 0xB1\nREAD_EEPROM = 0xC0\nWRITE_EEPROM = 0x40\n\n\ndef get_eeprom(dev, addr, amount):\n data = array.array('B')\n while len(data) < amount:\n transfer_size = min(64, amount - len(data))\n\n result = dev.ctrl_transfer(\n READ_EEPROM,\n VC_EEPROM,\n addr + len(data),\n 0,\n transfer_size,\n )\n assert len(result) == transfer_size, \"len(result) %i == %i\" % (\n len(result), transfer_size)\n\n data += result\n\n return data\n\n\ndef set_eeprom(dev, addr, data):\n offset = 0\n while offset < len(data):\n transfer_size = min(32, len(data) - offset)\n result = dev.ctrl_transfer(\n WRITE_EEPROM,\n VC_EEPROM,\n addr + offset,\n 0,\n data[offset:offset + transfer_size],\n )\n assert result == transfer_size, \"result %i == %i\" % (\n result, transfer_size)\n offset += transfer_size\n\n\ndef get_dev():\n # find our device\n dev = usb.core.find(idVendor=0x2A19, idProduct=0x5441)\n\n # was it found?\n if dev is None:\n raise ValueError('Device not found')\n\n dev.set_configuration()\n return dev\n\n\nif __name__ == \"__main__\":\n import sys\n import argparse\n import time\n\n dev = get_dev()\n current_eeprom_data = get_eeprom(dev, 0, 256)\n\n old_eeprom_data = bytes(current_eeprom_data)\n print(repr(old_eeprom_data))\n\n if len(sys.argv) > 1:\n new_eeprom_data = file(sys.argv[1], \"rb\").read()\n print(repr(old_eeprom_data))\n print(repr(new_eeprom_data))\n\n if old_eeprom_data != new_eeprom_data:\n set_eeprom(dev, 0, new_eeprom_data)\n else:\n print(repr(s))\n s.check()\n","sub_path":"libusb_eeprom.py","file_name":"libusb_eeprom.py","file_ext":"py","file_size_in_byte":1841,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"71491053","text":"from scipy.io import loadmat\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom numpy.linalg import inv\n\nn = 1001\nk_risk = np.zeros(shape=(1000,20))\nfor m in range(1000):\n Z = np.linspace(-np.pi, np.pi, n)\n e = np.random.randn(1)\n Y = np.zeros(n)\n for i in range(len(Y)):\n Y[i] = np.sin(3*Z[i]/2) + np.random.rand(1)\n Y = Y.reshape(-1,1)\n K = np.zeros(20)\n for k in range(1,21):\n X = np.array([1 for i in range(n)])\n X = X.reshape(-1,1)\n for i in range(1,k+1):\n X = np.hstack((X, (Z**i).reshape(-1,1)))\n beta = inv(np.dot(X.T, X)).dot(np.dot(X.T, Y))\n prediction = X.dot(beta)\n risk = np.sum(np.square(prediction - Y)) / len(Y)\n K[k-1] = risk\n k_risk[m] = K\n\nA = k_risk.sum(axis=0)/1000 # the final matrix that store corresponding average risks of k.\nplt.figure()\nplt.xlabel('k')\nplt.ylabel('average risk')\nplt.plot([i for i in range(1,21)], A)\nplt.show()","sub_path":"HW2/problem_2_b.py","file_name":"problem_2_b.py","file_ext":"py","file_size_in_byte":951,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"531571627","text":"from matplotlib import rc, use\n# use('agg')\nrc('font',**{'family':'serif','serif':['Palatino']})\nrc('text', usetex=True)\nimport torch\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport numpy as np\nfrom glob import glob\nfrom paper.ICML.models.VGG import cfg\nfrom algorithms.expectation_random_permutation import max_expectation\n\ntheirs = np.array([x for x in[64, 64, 'M', 128, 128, 'M', 256, 256, 256, 'M', 512, 512, 512, 'M', 512, 512, 512, 'M'] if x is not 'M'])\nconfigs = {\n 'COVER_FC': {\n 'ymin': 0.5,\n 's_range': (0.7, 10),\n 'ref': (3440, 0.83),\n 'cpu': {\n 'warmup': 50,\n 'rep': 500,\n 'large_batches': 512,\n },\n 'gpu': {\n 'warmup': 1,\n 'rep': 100,\n 'large_batches': 4096,\n }\n },\n 'CIFAR10_VGG': {\n 'ymin': 0.4,\n 's_range': (0.8, 6),\n 'cpu': {\n 'warmup': 1,\n 'rep': 10,\n 'large_batches': 64,\n },\n 'gpu': {\n 'warmup': 1,\n 'rep': 100,\n 'large_batches': 1024,\n }\n }\n}\n\ndef is_pareto_efficient(costs):\n is_efficient = np.ones(costs.shape[0], dtype= bool)\n for i, c in enumerate(costs):\n if is_efficient[i]:\n is_efficient[is_efficient] = np.any(costs[is_efficient]<=c, axis=1)\n return is_efficient\n\n\ndef load_files(prefix, mode):\n with open('./experiments_results/%s_%s_benchmark.pkl' % (prefix, mode), 'rb') as f:\n benchmark = torch.load(f)\n benchmark = {k[0]: k[1:] for k in benchmark}\n files = glob('./experiments_results/random_search/%s_%s/*.pkl' % (prefix, mode))\n result = []\n errors = 0\n for file_name in files:\n id = file_name.split('/')[-1].replace('.pkl', '')\n try:\n with open(file_name, 'rb') as f:\n result.append(torch.load(f) + (benchmark[id],))\n except:\n errors += 1\n pass\n print(errors)\n return result\n\ndef get_best_entry(logs):\n vac = logs[logs.measure == 'val_acc'].ix[int(len(logs) / 2):]\n return logs[logs.epoch == vac.ix[vac['value'].argmax()].epoch]\n\ndef get_final_measure(log, measure='test_acc'):\n x = get_best_entry(log)\n if measure == 'epoch':\n return int(x.epoch.iloc[0])\n if measure == 'time':\n return float(x.max().time)\n else:\n return float(x[x.measure == measure].value)\n\ndef generate_stats(infos):\n logs = infos[2].logs\n params = infos[1]['params']\n result = [\n get_final_measure(logs, 'test_acc'),\n compute_size(infos),\n get_final_measure(logs, 'val_acc'),\n get_final_measure(logs, 'train_acc'),\n get_final_measure(logs, 'time'),\n get_final_measure(logs, 'epoch'),\n params['lambda'],\n params['batch_size'],\n params['learning_rate'],\n params['gamma'],\n params['weight_decay'],\n *infos[3]\n ]\n try:\n result.append(params['factor'])\n except:\n pass\n try:\n result.append(params['layers'])\n except:\n pass\n return result\n\ndef compute_cost(seq, cl1, cl2):\n prev = 3\n total = 0\n for e in seq:\n total += prev * e * 9\n prev = e\n total += 1024 * cl1\n total += cl1 * cl2\n total += 10 * cl2\n return total\n\ndef compute_size(infos):\n i = 0\n logs = infos[2].logs\n sizes = []\n channel_count = infos[1]['params']['input_features'][0]\n model_kind = infos[1]['model'].__name__\n cost = 0\n if model_kind == 'FullyConnected':\n for i in range(infos[1]['params']['layers']):\n try:\n cc = get_final_measure(logs, 'size_%s' % (i + 1))\n except:\n cc = infos[1]['params']['size_layer_%s' % (i + 1)]\n cost += cc * channel_count\n channel_count = cc\n return cost\n else:\n try:\n while True:\n i += 1\n sizes.append(get_final_measure(logs, 'size_%s' % i))\n except:\n pass\n if sizes:\n cl1 = sizes[-2]\n cl2 = sizes[-1]\n sizes = sizes[:-2]\n else:\n model = infos[1]['params']['name']\n original_sizes = [x for x in cfg[model] if x is not 'M']\n sizes = infos[1]['params']['factor'] * np.array(original_sizes)\n sizes = sizes.astype(int)\n cl1 = infos[1]['params']['classifier_layer_1']\n cl2 = infos[1]['params']['classifier_layer_2']\n return compute_cost(sizes, cl1, cl2)\n\n\ncolumns = ['test_acc', 'size', 'val_acc', 'train_acc', 'time', 'epochs', 'lambda', 'batch_size', 'learning_rate', 'gamma', 'weight_decay', 'bench_cpu_small', 'bench_cpu_big', 'bench_gpu_small', 'bench_gpu_big', 'factor']\n\ndef summarize_experiment(prefix):\n r1 = np.array([generate_stats(x) for x in load_files(prefix, 'DYNAMIC')])\n dynamics = pd.DataFrame(r1, columns=columns[:r1.shape[1]])\n statics = pd.DataFrame([generate_stats(x) for x in load_files(prefix, 'STATIC')], columns=columns[:r1.shape[1]])\n if prefix == 'COVER_FC':\n dynamics = dynamics[dynamics.factor == 3]\n return dynamics, statics\n\ndef plot_comparable(ax, dyn, dynamic_pareto, static, metric='size'):\n result = []\n for acc, size in dynamic_pareto:\n line = dyn[np.bitwise_and(dyn.test_acc == acc, dyn['size'] == size)]\n better = static[static.test_acc >= acc].min()[metric]\n result.append([acc, better / line[metric]])\n r = np.array(result)\n ax.axhline(1, ls=':', label=\"1x reference\", color='black')\n ax.plot(r[:, 0], r[:, 1], label='%s improvement' % metric, color='black')\n\n\ndef plot_size_accuracy_component(ax, dataset, color, label, marker=None):\n M = dataset[['test_acc', 'size']].as_matrix()\n pareto = M[is_pareto_efficient(M * np.array([-1, 1]))]\n pareto.sort(axis=0)\n ax.plot(pareto[:, 1], pareto[:, 0], c=color, label=\"%s Pareto front\" % label)\n ax.scatter(dataset['size'], dataset['test_acc'], c=color, label=\"%s model\" % label, alpha=0.3, marker=marker)\n return pareto\n\ndef plot_all(dyn, sta, dataset):\n conf = configs[dataset]\n\n ax1 = plt.subplot2grid((5, 2), (0, 0), colspan=2, rowspan=2) \n ax1.set_xlabel('Size (floating point parameters)')\n ax1.set_ylabel('Accuracy')\n ax1.set_title('Distribution of models by size and accuracy')\n ax2 = plt.subplot2grid((5, 2), (2, 0), colspan=2)\n ax2.set_title('Size benefits')\n ax2.set_ylabel('Compression factor')\n ax3 = plt.subplot2grid((5, 2), (3, 0))\n ax3.set_title('CPU speedup ($bs=1$)')\n ax4 = plt.subplot2grid((5, 2), (3, 1))\n ax4.set_title('CPU speedup ($bs=%s$)' % conf['cpu']['large_batches'])\n ax5 = plt.subplot2grid((5, 2), (4, 0))\n ax5.set_title('GPU speedup ($bs=1$)')\n ax6 = plt.subplot2grid((5, 2), (4, 1))\n ax6.set_title('GPU speedup ($bs=%s$)' % conf['gpu']['large_batches'])\n ax1.set_xscale('log')\n plt.subplots_adjust(wspace=0.0, hspace=0.0)\n dyn_pareto = plot_size_accuracy_component(ax1, dyn, 'C0', 'ShrinkNets')\n plot_size_accuracy_component(ax1, sta, 'C1', 'Static', marker='^')\n if 'ref' in conf:\n ax1.scatter([conf['ref'][0]], [conf['ref'][1]], marker='*', label='Result from Scardapane', color='C4')\n ax1.legend(loc='lower right', framealpha=0.5)\n plot_comparable(ax2, dyn, dyn_pareto, sta, 'size')\n plot_comparable(ax3, dyn, dyn_pareto, sta, 'bench_cpu_small')\n plot_comparable(ax4, dyn, dyn_pareto, sta, 'bench_cpu_big')\n plot_comparable(ax5, dyn, dyn_pareto, sta, 'bench_gpu_small')\n plot_comparable(ax6, dyn, dyn_pareto, sta, 'bench_gpu_big')\n for ax in [ax1, ax2, ax3, ax4, ax5, ax6]:\n ax.yaxis.grid(b=True, which='major', alpha=0.4, linestyle='--')\n ax.xaxis.grid(b=True, which='major', alpha=0.4, linestyle='--')\n\n for ax in [ax2, ax3, ax4, ax5, ax6]:\n ax.set_xlim(0.8)\n ax1.set_ylim(ymin=conf['ymin'])\n ax2.set_ylim(ymax=40)\n ax2.set_xlabel('Desired accuracy')\n\n for ax in [ax3, ax4, ax5, ax6]:\n ax.set_ylabel('Speedup')\n ax.set_ylim(conf['s_range'])\n\n f = plt.gcf()\n f.set_size_inches((5, 10))\n plt.tight_layout()\n plt.savefig('%s_summary.pdf' % dataset, bbox_inches='tight', pad_inches=0)\n\ndef select_models(dynamic):\n results = [(i, get_final_measure(x[2].logs, 'test_acc')) for i, x in enumerate(dynamic)]\n best = max(results, key=lambda x: x[1])[0]\n best= dynamic[best][2].logs\n rr = np.array([x[1] for x in results])\n good = np.abs(rr - 0.905).argmin()\n print(rr[good])\n return best,dynamic[good][2].logs\n\ndef get_size_at_epoch(log, epoch):\n l = log[log.epoch == epoch]\n sizes = []\n i = 1\n while True:\n try:\n t = int(l[l.measure == 'size_%s' % i].value)\n sizes.append(t)\n i += 1\n except:\n break\n return sizes[:-2]\n\ndef plot_shape(ax, log, steps=8):\n max_epoch = get_final_measure(log, 'epoch')\n selected = np.linspace(1, max_epoch, steps).astype(int)\n for epoch in selected:\n if epoch == 1:\n sizes = theirs * 2\n else:\n sizes = get_size_at_epoch(log, epoch)\n r = list(range(1, len(sizes) + 1))\n ax.fill_between(r, sizes, alpha=0.1, color='C0')\n last_sizes = get_size_at_epoch(log, max_epoch)\n ax.plot(r, last_sizes, label='Final size')\n ax.plot(r, theirs, ':', color='black', label='original VGG size')\n\ndef plot_shapes(dynamic):\n best, good = select_models(dynamic)\n fig, lines = plt.subplots(1, 2, sharex=True)\n plt.subplots_adjust(wspace=0.05, hspace=0.05)\n plot_shape(lines[0], best)\n plot_shape(lines[1], good)\n for ax in lines:\n ax.set_ylabel('\\\\#Convolution kernels')\n lines[1].set_xlabel('Layer')\n lines[1].legend(loc='upper left')\n fig.set_size_inches((5, 7))\n plt.savefig('size_evolution.pdf', bbox_inches='tight', pad_inches=0)\n\n\n","sub_path":"paper/ICML/plot_random_search.py","file_name":"plot_random_search.py","file_ext":"py","file_size_in_byte":9876,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"570418124","text":"#!/usr/bin/env python\r\n'''\r\nSQL Introducción [Python]\r\nEjercicios de práctica\r\n---------------------------\r\nAutor: Inove Coding School\r\nVersion: 1.1\r\n\r\nDescripcion:\r\nPrograma creado para poner a prueba los conocimientos\r\nadquiridos durante la clase\r\n'''\r\n\r\n__author__ = \"Inove Coding School\"\r\n__email__ = \"alumnos@inove.com.ar\"\r\n__version__ = \"1.1\"\r\n\r\nimport sqlite3\r\n\r\n# https://extendsclass.com/sqlite-browser.html\r\n\r\n\r\ndef create_schema():\r\n\r\n # Conectarnos a la base de datos\r\n # En caso de que no exista el archivo se genera\r\n # como una base de datos vacia\r\n conn = sqlite3.connect('secundaria.db')\r\n\r\n # Crear el cursor para poder ejecutar las querys\r\n c = conn.cursor()\r\n\r\n # Ejecutar una query\r\n c.execute(\"\"\"\r\n DROP TABLE IF EXISTS estudiante;\r\n \"\"\")\r\n\r\n # Ejecutar una query\r\n c.execute(\"\"\"\r\n CREATE TABLE estudiante(\r\n [id] INTEGER PRIMARY KEY AUTOINCREMENT,\r\n [name] TEXT NOT NULL,\r\n [age] INTEGER NOT NULL,\r\n [grade] INTEGER,\r\n [tutor] TEXT\r\n );\r\n \"\"\")\r\n\r\n # Para salvar los cambios realizados en la DB debemos\r\n # ejecutar el commit, NO olvidarse de este paso!\r\n conn.commit()\r\n\r\n # Cerrar la conexión con la base de datos\r\n conn.close()\r\n\r\n\r\n\r\ndef fill():\r\n print('Completemos esta tablita!')\r\n # Llenar la tabla de la secundaria con al menos 5 estudiantes\r\n # Cada estudiante tiene los posibles campos:\r\n # id --> este campo es auto incremental por lo que no deberá completarlo\r\n # name --> El nombre del estudiante (puede ser solo nombre sin apellido)\r\n # age --> cuantos años tiene el estudiante\r\n # grade --> en que año de la secundaria se encuentra (1-6)\r\n # tutor --> nombre de su tutor\r\n\r\n # Se debe utilizar la sentencia INSERT.\r\n # Observar que hay campos como \"grade\" y \"tutor\" que no son obligatorios\r\n # en el schema creado, puede obivar en algunos casos completar esos campos\r\n valuesDB = []\r\n rep = False\r\n records = [\"name\", \"age\", \"grade\", \"tutor\"]\r\n transform = True\r\n\r\n #Bucle para crear alumnos\r\n while True: \r\n for alumn in range(len(records)):\r\n #Bucle de validación\r\n while True:\r\n \r\n records_inp = str(input(f\"Ingrese el dato para el campo {records[alumn]}: \"))\r\n #Para evitar la transformación de str a int cuando no es necesario\r\n if records[alumn] == \"name\" or records[alumn] == \"tutor\":\r\n transform = False\r\n else:\r\n transform = True\r\n\r\n #Verificar si en los campos \"age\" y \"grade\" los datos son numéricos\r\n while transform:\r\n if (records[alumn] == \"age\" or records[alumn] == \"grade\") and records_inp.isdigit():\r\n break\r\n else:\r\n print(f\"-El campo {records[alumn]} no puede llevar carácteres alfabéticos...\")\r\n rep = True\r\n break\r\n #Volver al inicio del bucle si age o grade son alfanuméricos\r\n if rep:\r\n rep = False\r\n continue\r\n else:\r\n break\r\n #Agrego valores\r\n valuesDB.append(records_inp)\r\n #Agregar registro a la tabla\r\n\r\n #Agregar los datos a la DB\r\n conn = sqlite3.connect('secundaria.db')\r\n c = conn.cursor()\r\n c.execute(\"\"\"\r\n INSERT INTO estudiante(name,age,grade,tutor)\r\n VALUES(?,?,?,?);\"\"\",(valuesDB))\r\n #Guardar y cerrar\r\n conn.commit()\r\n conn.close()\r\n #Reset de la matriz valuesDB para volver a generar un nuevo registro\r\n valuesDB.clear()\r\n\r\n #Crear más registros de alumnos:\r\n alumn_record = str(input(\"Desea agregar otro registro de estudiante?: \")).capitalize()\r\n if alumn_record == \"Si\":\r\n print(\"**Creando otro registro**\\n\")\r\n elif alumn_record == \"No\":\r\n break\r\n #Realizado\r\n\r\n\r\ndef fetch():\r\n print('Comprobemos su contenido, ¿qué hay en la tabla?')\r\n # Utilizar la sentencia SELECT para imprimir en pantalla\r\n # todas las filas con todas sus columnas\r\n # Utilizar fetchone para imprimir de una fila a la vez\r\n\r\n conn = sqlite3.connect('secundaria.db')\r\n c = conn.cursor()\r\n\r\n c.execute('SELECT * FROM estudiante;')\r\n while True:\r\n fetch_one = c.fetchone()\r\n if fetch_one is None:\r\n break\r\n print(fetch_one)\r\n\r\n #Guardar y cerrar\r\n conn.commit()\r\n conn.close()\r\n #Realizado\r\n\r\n\r\ndef search_by_grade(grade):\r\n print('Operación búsqueda!')\r\n # Utilizar la sentencia SELECT para imprimir en pantalla\r\n # aquellos estudiantes que se encuentra en el año \"grade\"\r\n\r\n # De la lista de esos estudiantes el SELECT solo debe traer\r\n # las siguientes columnas por fila encontrada:\r\n # id / name / age\r\n conn = sqlite3.connect('secundaria.db')\r\n c_grade = conn.cursor()\r\n c_2 = conn.cursor()\r\n c_name = conn.cursor()\r\n #Querys\r\n c_grade.execute(f'SELECT grade FROM estudiante WHERE grade = {grade};')\r\n c_2.execute('SELECT id, name, age FROM estudiante;')\r\n c_name.execute(f'SELECT name FROM estudiante WHERE grade = {grade};')\r\n\r\n while True:\r\n \r\n fetch_grade = c_grade.fetchone()\r\n fetch_two = c_2.fetchone()\r\n fetch_name = c_name.fetchone()\r\n\r\n if (fetch_grade is None) or (fetch_two is None) or (fetch_name is None):\r\n break\r\n print(f\"El estudiante {fetch_name} está en el grado {fetch_grade}\")\r\n print(fetch_two)\r\n #Cerrando sesión\r\n conn.close()\r\n #Realizado\r\n\r\n\r\ndef insert(new_student):\r\n print('Nuevos ingresos!')\r\n # Utilizar la sentencia INSERT para ingresar nuevos estudiantes\r\n # a la secundaria\r\n conn = sqlite3.connect('secundaria.db')\r\n c = conn.cursor()\r\n\r\n c.execute(\"\"\" INSERT INTO estudiante(name, age)\r\n VALUES(?,?)\"\"\",(new_student))\r\n\r\n #Guardar y cerrar\r\n conn.commit()\r\n conn.close()\r\n #Realizado\r\n\r\n\r\ndef modify(id, name):\r\n print('Modificando la tabla')\r\n # Utilizar la sentencia UPDATE para modificar aquella fila (estudiante)\r\n # cuyo id sea el \"id\" pasado como parámetro,\r\n # modificar su nombre por \"name\" pasado como parámetro\r\n conn = sqlite3.connect('secundaria.db')\r\n c = conn.cursor()\r\n\r\n c.execute('UPDATE estudiante SET name = ? WHERE id = ?;',(name,id))\r\n\r\n #Guardar y cerrar\r\n conn.commit()\r\n conn.close()\r\n #Realizado\r\n\r\n\r\nif __name__ == '__main__':\r\n print(\"Bienvenidos a otra clase de Inove con Python\")\r\n #create_schema() # create and reset database (DB)\r\n #fill()\r\n #fetch()\r\n\r\n grade = 3\r\n #search_by_grade(grade)\r\n\r\n new_student = ['You', 16]\r\n #insert(new_student)\r\n\r\n name = '¿Inove?'\r\n id = 2\r\n #modify(id, name)\r\n","sub_path":"ejercicios_practica.py","file_name":"ejercicios_practica.py","file_ext":"py","file_size_in_byte":7050,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"528378304","text":"from functools import reduce\n\nred_words = (\"help\", \"asap\", \"urgent\")\n\n\ndef is_stressful(subj):\n \"\"\"\n recoognise stressful subject\n \"\"\"\n if subj.endswith('!!!'):\n return True\n\n subj = ''.join(filter(lambda x: x.isalpha(), subj))\n if subj.isupper():\n return True\n\n subj = ''.join(reduce((lambda res, x: res if res.endswith(x) else (res + x)), subj.lower()))\n for i in red_words:\n if i in subj:\n return True\n\n return False\n\n\nif __name__ == '__main__':\n # These \"asserts\" using only for self-checking and not necessary for auto-testing\n assert is_stressful(\"Hi\") == False, \"First\"\n assert is_stressful(\"I neeed HELP\") == True, \"Second\"\n print('Done! Go Check it!')\n","sub_path":"checkio/stressful-subject.py","file_name":"stressful-subject.py","file_ext":"py","file_size_in_byte":736,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"198649006","text":"from my_home_server.exceptions.invalid_dto_exception import InvalidDTOException\nfrom my_home_server.exceptions.object_not_found_exception import ObjectNotFoundException\nfrom my_home_server.models.product_type import ProductType\nfrom my_home_server.models.user import User\nfrom my_home_server.security.authentication_context import AuthenticationContext\nfrom my_home_server.services.product_type_service import ProductTypeService\nfrom my_home_server.tests.integration_tests.base_test import BaseTest\n\n\nclass TestProductTypeService(BaseTest):\n def setUp(self):\n super().setUp()\n self.service = self.dependency_injector.get(ProductTypeService)\n\n def test_find_by_id_without_permission(self):\n self.assertIsNone(self.service.find_by_id(2))\n\n def test_find_by_id(self):\n self.assertEqual(1, self.service.find_by_id(1).id)\n\n def test_find_all(self):\n user = self.db.session.query(User).get(4)\n AuthenticationContext.init_context(user)\n\n product_types = self.service.find_all()\n\n self.assertEqual(11, len(product_types))\n self.assertNotIn(3, [p.id for p in product_types])\n\n def test_create_from_dto_without_name(self):\n dto = {\n \"name\": None,\n \"description\": \"Test description\"\n }\n\n with self.assertRaises(InvalidDTOException) as exception:\n self.service.create_from_dto(dto)\n\n self.assertEqual([\"name\"], exception.exception.required_fields)\n self.assertEqual(ProductType.__name__, exception.exception.entity_name)\n\n def test_create_from_dto(self):\n dto = {\n \"name\": \"Name\",\n \"description\": \"Test description\"\n }\n\n product_type = self.service.create_from_dto(dto)\n\n assert product_type in self.db.session\n\n self.assertEqual(\"Name\", product_type.name)\n self.assertEqual(\"Test description\", product_type.description)\n\n def test_create_from_dto_with_parents(self):\n dto = {\n \"name\": \"Name\",\n \"description\": \"Test description\",\n \"parent_product_type\": {\n \"name\": \"Test 2\",\n \"parent_product_type\": {\n \"id\": 1\n }\n }\n }\n\n product_type = self.service.create_from_dto(dto)\n\n assert product_type in self.db.session\n\n self.assertEqual(\"Name\", product_type.name)\n self.assertEqual(\"Test description\", product_type.description)\n self.assertEqual(\"Test 2\", product_type.parent_product_type.name)\n self.assertEqual(1, product_type.parent_product_type.parent_product_type.id)\n\n def test_update_from_dto_without_id(self):\n dto = {\n \"name\": \"Name\",\n \"description\": \"Test description\",\n \"parent_product_type\": {\n \"name\": \"Test 21\",\n \"parent_product_type\": {\n \"id\": 1\n }\n }\n }\n\n with self.assertRaises(InvalidDTOException) as exception:\n self.service.update_from_dto(dto)\n\n self.assertEqual([\"id\"], exception.exception.required_fields)\n self.assertEqual(ProductType.__name__, exception.exception.entity_name)\n\n def test_update_from_dto_without_permission(self):\n dto = {\n \"id\": 2,\n \"name\": \"Name\",\n \"description\": \"Test description\",\n \"parent_product_type\": {\n \"name\": \"Test 21\",\n \"parent_product_type\": {\n \"id\": 1\n }\n }\n }\n\n with self.assertRaises(ObjectNotFoundException) as exception:\n self.service.update_from_dto(dto)\n\n self.assertEqual(ProductType.__name__, exception.exception.entity_name)\n self.assertEqual({\"id\": 2}, exception.exception.entity_identifier)\n\n def test_update_from_dto(self):\n dto = {\n \"id\": 3,\n \"name\": \"new_name\",\n \"description\": \"Test description\",\n \"parent_product_type\": {\n \"name\": \"Test 2\",\n \"parent_product_type\": {\n \"id\": 4\n }\n }\n }\n\n product_type = self.service.update_from_dto(dto)\n\n self.assertEqual(\"new_name\", product_type.name)\n self.assertEqual(\"Test description\", product_type.description)\n self.assertEqual(\"Test 2\", product_type.parent_product_type.name)\n self.assertEqual(4, product_type.parent_product_type.parent_product_type.id)\n\n def test_update_from_dto_removing_parent(self):\n dto = {\n \"id\": 6,\n \"name\": \"new_name\",\n \"description\": \"Test description\",\n \"parent_product_type\": None\n }\n\n self.service.update_from_dto(dto)\n\n product_type = self.db.session.query(ProductType).get(6)\n\n self.assertEqual(\"new_name\", product_type.name)\n self.assertEqual(\"Test description\", product_type.description)\n self.assertIsNone(product_type.parent_product_type)\n\n def test_delete_by_id_without_permission(self):\n\n with self.assertRaises(ObjectNotFoundException) as exception:\n self.service.delete_by_id(2)\n\n self.assertEqual(ProductType.__name__, exception.exception.entity_name)\n self.assertEqual({\"id\": 2}, exception.exception.entity_identifier)\n\n def test_delete_by_id(self):\n\n self.service.delete_by_id(4)\n\n self.assertIsNone(self.db.session.query(ProductType).get(4))\n self.assertIsNone(self.db.session.query(ProductType).get(5))\n self.assertIsNone(self.db.session.query(ProductType).get(6))\n\n def test_find_or_create_without_id(self):\n dto = {\n \"name\": \"other_name\",\n \"description\": \"Test description\",\n \"parent_product_type\": {\n \"name\": \"Test 2\",\n \"parent_product_type\": {\n \"id\": 4\n }\n }\n }\n\n product_type = self.service.find_or_create_from_dto(dto)\n\n self.assertIsNone(product_type)\n\n def test_find_or_create_not_creating(self):\n dto = {\n \"id\": 3,\n \"name\": \"other_name\",\n \"description\": \"Test description\",\n \"parent_product_type\": {\n \"name\": \"Test 2\",\n \"parent_product_type\": {\n \"id\": 4\n }\n }\n }\n\n product_type = self.service.find_or_create_from_dto(dto)\n\n self.assertEqual(3, product_type.id)\n self.assertNotEqual(\"other_name\", product_type.id)\n\n def test_find_or_create_creating(self):\n dto = {\n \"id\": 300,\n \"name\": \"other_name\",\n \"description\": \"Test description\",\n \"parent_product_type\": {\n \"name\": \"Test 2\",\n \"parent_product_type\": {\n \"id\": 4\n }\n }\n }\n\n product_type = self.service.find_or_create_from_dto(dto)\n\n self.assertEqual(300, product_type.id)\n self.assertNotEqual(\"other_name\", product_type.id)","sub_path":"my_home_server/tests/integration_tests/services/test_product_type_service.py","file_name":"test_product_type_service.py","file_ext":"py","file_size_in_byte":7113,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"162910265","text":"# -*- coding: utf-8 -*-\r\n\r\n#\r\n# Script created by Theodore Economides\r\n#\r\n\r\n# Creates a dictionary with key = filename and value = listOfContents\r\n\r\nimport os\r\nfrom SMITY.definePATH import PATH_TO_KEYWORDS\r\n\r\n\r\n# Constants\r\n\r\nSPLIT_AT = ',' # ','\r\nDIRPATH = PATH_TO_KEYWORDS\r\n\r\n\r\ndef create(dirpath=DIRPATH, split_at=SPLIT_AT):\r\n ## ------------------------------------------------------\r\n ## created by Theodore Economides\r\n ## ------------------------------------------------------\r\n\r\n dictionary = {}\r\n\r\n for file in os.listdir(dirpath):\r\n with open(os.path.join(dirpath, file), encoding='utf8') as f:\r\n key = os.path.basename(f.name).split('.')[0] # f.name.split('.')[0]\r\n values = f.read().split(split_at)\r\n # add to dictionary\r\n dictionary[key] = values\r\n\r\n return dictionary\r\n","sub_path":"SMITYcore/createDictFromFiles.py","file_name":"createDictFromFiles.py","file_ext":"py","file_size_in_byte":854,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"186176748","text":"import logging\nimport threading\n\nimport cherrypy\n\nfrom concord import settings\nfrom concord.discord_client import client as discord_client\nfrom concord.webserver import OauthCallbackHandler\n\nlogging.basicConfig(level=logging.INFO)\nLOGGER = logging.getLogger(__name__)\n\n\nclass DiscordThread(threading.Thread):\n def run(self):\n discord_client.run()\n\n def setup(self):\n LOGGER.info(\"discord setup\")\n\n\nclass WebserverThread(threading.Thread):\n def __init__(self, discord, group=None, target=None, name=None, args=(), kwargs=None, *, daemon=None):\n self.discord_client = discord_client\n super().__init__(group, target, name, args, kwargs, daemon=daemon)\n\n def run(self):\n cherrypy.config.update({\n 'server.socket_port': settings.HTTP_PORT,\n 'server.socket_host': '0.0.0.0',\n 'engine.autoreload_on': False,\n 'request.show_tracebacks': settings.DEBUG\n })\n cherrypy.tree.mount(OauthCallbackHandler(self.discord_client), \"/callback\", None)\n cherrypy.engine.start()\n\n def setup(self):\n LOGGER.info(\"discord setup %r\", self)\n\n\nDiscordThread(name='discord').start()\nWebserverThread(name='web', discord=discord_client).start()\n","sub_path":"run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":1236,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"580408714","text":"import requests\nimport time\nimport pandas as pd\nfrom datetime import datetime\n\nimport multiprocessing\nfrom multiprocessing import Pool\nimport argparse\nimport sys\n\nfrom bs4 import BeautifulSoup\nimport re # Xử lý đoạn mã có tag html\n\nfrom tqdm import tqdm\nimport gc # Garbage Collector\nimport json\n\n\ndef clean_html(raw_html):\n cleanr = re.compile('<.*?>')\n cleantext = re.sub(cleanr, '', raw_html)\n return cleantext\n\n\ndef convert_number(num):\n num = num.replace(\",\",\"\")\n return float(num)\n\n\ndef create_null_dataframe_info_book_detail():\n return pd.DataFrame({\"Book_Title\": [], \"Author_Name\": [], \"Author_Url\": [],\n \"Description\": [], \"Rating\": [], \"Rating_Counts\": [],\n \"Reviews_Counts\": [], \"Num_Pages\": [], \"Book_Format\" :[],\n \"Time_publish\": [], \"Publisher\": [], \"ISBN\": [], \n \"Language\": [], \"Genres\": [], \"Book_Url\": []})\n\n\ndef get_Detail_Book(url): # Lấy chi tiết từng url book\n\n time.sleep(0.5)\n source = requests.get(url)\n soup = BeautifulSoup(source.text, 'html.parser')\n\n temp = soup.find(\"div\", {\"class\": \"last col stacked\"})\n if temp == None:\n return None\n \n try:\n Image_url = str(temp.find(\"div\", {\"class\": \"bookCoverPrimary\"}).find(\"img\").get(\"src\"))\n except:\n Image_url = None\n\n temp = temp.find(\"div\", {\"class\": \"last col\"})\n if temp == None:\n return None\n \n try:\n Book_Title = str(temp.find(\"h1\", {\"id\":\"bookTitle\"}).contents[0].strip())\n except:\n Book_Title = None\n\n try:\n Author = temp.find(\"a\", {\"class\": \"authorName\"})\n Author_Url = str(Author.get(\"href\"))\n Author_Name = str(Author.find(\"span\").contents[0])\n except:\n Author_Url, Author_Name = None, None\n\n try:\n Description = temp.find(\"div\", {\"id\": \"description\"}).findAll(\"span\")\n if len(Description) > 1:\n Description = clean_html(str(Description[1]))\n else:\n Description = clean_html(str(Description[0]))\n except:\n Description = None\n\n try:\n Rating = convert_number(str(temp.find(\"span\", {\"itemprop\": \"ratingValue\"}).contents[0].strip()))\n except:\n Rating = None\n\n try:\n Rating_Counts = convert_number(str(temp.find(\"meta\", {\"itemprop\": \"ratingCount\"}).get(\"content\")))\n except:\n Rating_Counts = None\n\n try:\n Reviews_Counts = convert_number(str(temp.find(\"meta\", {\"itemprop\": \"reviewCount\"}).get(\"content\")))\n except:\n Reviews_Counts = None\n\n temp = soup.find(\"div\", {\"id\": \"details\"})\n if temp == None:\n return None\n \n try:\n Num_Pages = convert_number(str(temp.find(\"span\", {\"itemprop\": \"numberOfPages\"}).contents[0])[:-5])\n except:\n Num_Pages = None\n\n try:\n Book_Format = str(temp.find(\"span\", {\"itemprop\": \"bookFormat\"}).contents[0])\n except:\n Book_Format = None\n\n try:\n Publish = temp.findAll(\"div\", {\"class\":\"row\"})\n Publish = [k for k in Publish if \"Published\" in str(k)][0].contents[0].strip().split(\"Published\")[1].split(\"by\")\n if len(Publish) > 1:\n Year_publish = Publish[0].strip()\n Publisher = Publish[1].strip()\n else:\n Year_publish = Publish[0].strip()\n Publisher = None\n except:\n Year_publish = None\n Publisher = None\n\n InfoDetail = temp.find(\"div\", {\"id\":\"bookDataBox\"}).findAll(\"div\", {\"class\": \"clearFloats\"})\n try:\n ISBN = [k for k in InfoDetail if \"ISBN\" in str(k)][0].find(\"div\", {\"class\": \"infoBoxRowItem\"}).contents[0].strip()\n ISBN = str(ISBN)\n except:\n ISBN = None\n\n try:\n Language = [k for k in InfoDetail if \"Edition Language\" in str(k)][0].find(\"div\", {\"class\": \"infoBoxRowItem\"}).contents[0].strip()\n Language = str(Language)\n except:\n Language = None\n\n temp = soup.find(\"div\", {\"class\": \"rightContainer\"})\n Genres = {}\n if temp != None:\n try:\n temp = temp.findAll(\"div\", {\"class\": \"stacked\"})[1].findAll(\"div\", {\"class\": \"elementList\"})\n \n for element in temp:\n genre = element.find(\"div\", {\"class\": \"left\"}).find(\"a\").contents[0]\n users_number = convert_number(element.find(\"div\", {\"class\": \"right\"}).find(\"a\").contents[0][:-6])\n Genres[str(genre)] = users_number\n except:\n Genres = None\n \n else:\n Genres = None\n\n Genres = json.dumps(Genres)\n \n return pd.DataFrame({\"Book_Title\": Book_Title, \"Author_Name\": Author_Name, \"Author_Url\": Author_Url,\n \"Description\": Description, \"Rating\": Rating, \"Rating_Counts\": Rating_Counts,\n \"Reviews_Counts\": Reviews_Counts, \"Num_Pages\": Num_Pages, \"Book_Format\" :Book_Format,\n \"Time_publish\": Year_publish, \"Publisher\": Publisher, \"ISBN\": ISBN, \n \"Language\": Language, \"Genres\": Genres, \"Book_Url\": url}, index=[0])\n\n\nif __name__ == '__main__':\n\n __spec__ = \"ModuleSpec(name='builtins', loader=<class '_frozen_importlib.BuiltinImporter'>)\"\n \n parser = argparse.ArgumentParser()\n\n parser.add_argument(\"--min_index\", \"-min\", type=int, help=\"set min index\")\n parser.add_argument(\"--max_index\", \"-max\", type=int, help=\"set max index\")\n\n args = parser.parse_args()\n\n \n Info_General_Book = pd.read_csv(\"Info_Book_Url.csv\")\n\n\n list_url_book = Info_General_Book.Book_Urls.to_list()\n \n pool = Pool()\n \n info_book_detail = create_null_dataframe_info_book_detail()\n \n inputs = list_url_book[args.min_index : args.max_index]\n\n info_book_detail = pd.concat(pool.map(get_Detail_Book, inputs), ignore_index = True)\n\n info_book_detail.to_csv(\"info_book_detail_ver_2.csv\", mode = \"a\", index = False, header = False, encoding = \"utf-8\")\n","sub_path":"source/crawl_info_book_detail.py","file_name":"crawl_info_book_detail.py","file_ext":"py","file_size_in_byte":5907,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"116134966","text":"from collections import deque\ndef palchecker(aString):\n chardeque = deque()\n\n for ch in aString:\n chardeque.appendleft(ch)\n\n stillEqual = True\n\n while len(chardeque) > 1 and stillEqual:\n first = chardeque.popleft()\n last = chardeque.pop()\n if first != last:\n stillEqual = False\n\n return stillEqual\n\nprint(palchecker(\"lsdkjfskf\"))\nprint(palchecker(\"radar\"))\n","sub_path":"palindrom_check_deque.py","file_name":"palindrom_check_deque.py","file_ext":"py","file_size_in_byte":411,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"284357243","text":"import os\nimport re\n\nfrom util.invalidTestException import InvalidTestException\nfrom util.log import Log\nfrom util.noCompileException import NoCompileException\nfrom util.subprocessWrapper import SubprocessWrapper\nfrom util.timedProcess import TimedProcess\nfrom util.timeoutException import TimeoutException\nfrom util.timer import Timer\n\nclass RunTest:\n \"\"\"\n 2013-08-23:\n Execute all tests cases found inside a module. Specifically:\n - Accept the path to a test file as input (like \"my_test.ml\" or \"worker_test.ml\")\n - Compile the test case and the corresponding .ml file (\"file.ml\" + \"file_test.ml\")\n - Extract the inferred interface from the test file\n - Extract all test cases from the interface (\"unit -> unit\" functions beginning with \"test_\")\n - Execute each test case in a separate ocaml toplevel, record output\n \"\"\"\n\n # In order of dependence\n LIBS = [\n \"serializer.cma\",\n \"assertions.cma\",\n ]\n\n def __init__(self, test_file, timeout):\n self.log = Log()\n self.subprocess = SubprocessWrapper()\n self.timeout = timeout\n \n self.test_file = test_file\n self.src_file = \"%s.ml\" % test_file[:-(len(\"_test.ml\"))]\n self.test_name = self.test_file.split(\"/\")[-1]\n self.src_name = self.src_file.split(\"/\")[-1]\n\n self.failures = self.run()\n print(\"\") # Separator\n\n def compile(self):\n \"\"\"\n 2013-08-23:\n Compile the source file + test file, generate the interface for \n the test file. In detail:\n - Generate the ocamlc command to compile source + test in unison,\n pulling in all necessary external libraries\n - Generate the ocamlc command to get the interface for the test,\n using the .cmo file generated by compiling the source as a library\n \"\"\"\n self.log.info(\"Compiling %s and %s\" % (self.src_name, self.test_name))\n # Prepare compilation commands. \n # 2013-08-23: Base command includes standard testing library\n base_command = \" \".join([\"ocamlc -c\"] + self.LIBS)\n # 2013-08-23: Full compilations uses '-g' option to generate debug information\n compile_all = \"%s -g %s %s\" % (base_command, self.src_file, self.test_file)\n # Name of the .cmo file generated after compiling the source\n src_cmo = \"%s.cmo\" % self.src_file[:-(len(\".ml\"))]\n # 2013-08-23: Use '-i' option to just generate the interface for the function\n infer_interface = \"%s -i %s %s\" % (base_command, src_cmo, self.test_file)\n # Compile both files, then infer and return the interface\n self.subprocess.execute(compile_all, on_failure=self.compile_error)\n # 2013-08-23: Reached this line without making a .cmo Dear diary, this was bad\n interface = self.subprocess.execute(infer_interface)\n return interface.split(\"\\n\")\n\n def compile_error(self, cpe):\n # NO COMPILEEEEEEEE\n err_msg = cpe.output.strip()\n # 2013-08-23: Retrieve failing line from the file\n sourceError = self._source_of_exception(err_msg)\n # Put the OCaml exception + line from source into one string. \n # Replace vanilla newlines with indented newlines.\n nocompile_msg = (\"%s\\n%s\" % (err_msg, sourceError)).replace(\"\\n\", \"\\n \")\n self.log.nocompile(nocompile_msg)\n raise NoCompileException(1)\n\n def generate_scripts(self, test_interface):\n \"\"\"\n 2013-08-23:\n Given the interface of a test file, generate a toplevel script\n for each test case. For instance, if the test file had an interface\n like:\n val test_one : unit -> unit\n val helper : int -> string\n val test_two : unit -> unit\n val test_three : int -> unit\n Then this function would generate scripts for `test_one` and\n `test_two`, because they are `unit -> unit` functions that\n start with the magic prefix \"test_\"\n \"\"\"\n test_cases = []\n for defined_name in ( x for x in test_interface if x.startswith(\"val test_\") ):\n val_name, val_type = defined_name[4:].split(\" : \", 1)\n if val_type != \"unit -> unit\":\n self.log.warn(\"skipping test case %s with type %s\" % (val_name, val_type))\n else:\n test_cases.append(val_name)\n if test_cases == []:\n return None\n else:\n # Change \"my_test.ml\" to the module \"My_test\"\n test_name = self.test_name[:-(len(\".ml\"))].capitalize()\n return ( (case, self._toplevel_input(test_name, case))\n for case in test_cases )\n \n def run(self):\n \"\"\"\n 2013-08-23:\n \"\"\"\n self._check_paths()\n # Get the directory containing the test file, move to it\n if \"/\" in self.test_file:\n testcase_dir = self.test_file[::-1].split(\"/\", 1)[1][::-1]\n os.chdir(testcase_dir)\n # Compile the test + source files\n self.log.header(\"Testing %s\" % self.src_name)\n test_interface = self.compile()\n # Generate the test scripts\n self.log.info(\"Compilation succeeded! Generating test scripts...\")\n test_scripts = self.generate_scripts(test_interface)\n if test_scripts is None:\n self.log.warn(\"No test cases in %s\" % self.test_name)\n else:\n # Execute tests\n return self.run_tests(test_scripts)\n\n def run_test(self, script):\n \"\"\"\n 2013-08-23:\n Execute a single test script in a toplevel environment.\n Start a toplevel with the module and test case object files loaded, \n pipe in the test script as an argument.\n\n I'm not entirely happy with the piping because it means that subprocess\n fails to throw an error when the test fails. Maybe fix that later.\n \"\"\"\n run_test = \" \".join([\n \"echo \\\"%s\\\" |\" % script,\n \"ocaml\",\n ] + self.LIBS + [\n \"%s.cmo\" % self.src_file[:-(len(\".ml\"))],\n \"%s.cmo\" % self.test_file[:-(len(\".ml\"))]\n ])\n with Timer() as t:\n try:\n output, err = TimedProcess(run_test).run(self.timeout)\n err_msg = self._error_of_output(output) # Maybe None\n except TimeoutException:\n err_msg = \"TIMEOUT\"\n if not err_msg:\n self.log.success(\"PASS in %0.3f seconds\" % t.duration)\n else:\n self.log.failure(\"FAIL with '%s' in %0.3f seconds\" % (err_msg, t.duration))\n return err_msg\n\n def run_tests(self, test_scripts):\n \"\"\"\n 2013-08-23:\n Given an association list of (\"test_case_name\", \"toplevel script\"),\n execute each test in an ocaml toplevel and record the output.\n \"\"\"\n errors = []\n for (fn_name, script) in test_scripts:\n self.log.run(\"Running %s...\" % fn_name)\n err_msg = self.run_test(script)\n if err_msg:\n errors.append((fn_name, err_msg))\n return errors\n\n def _check_paths(self):\n \"\"\"\n 2013-08-23:\n Make sure the source and test files (still) exist.\n \"\"\"\n if not os.path.exists(self.src_file):\n self.log.warn(\"Source file '%s' not found. Skipping %s...\" % (self.src_name, self.test_name))\n raise InvalidTestException(0)\n if not os.path.exists(self.test_file):\n self.log.warn(\"Test file '%s' not found. Exiting...\" % self.test_name)\n raise InvalidTestException(0)\n\n def _error_of_output(self, toplevel_output):\n \"\"\"\n 2013-08-04:\n Toplevel output is always echoed to subprocess, regardless of\n whether the tests passed. Manually check if the code raised an\n assertion error. \n \n TODO this is not very rigorous! It assumes there will be an octothorp\n at the end of the output!\n This is a reasonable assumption but still it makes me nervous\n\n 2013-08-23:\n Ignores input errors. If the code this file sends to the toplevel\n has a syntax error or whatever, things will break down seriously. \n I think its safe to assume that'll never happen in a release.\n\n 2013-08-24:\n Added logic to print the non-exception printouts\n You know, we could probably just check that the output's \"- : unit\"\n \"\"\"\n match = re.search(r\"#.*?(Exception:[\\s].*)\\n#\", toplevel_output, re.DOTALL)\n if match is not None:\n # Debug output will be octothorp to exception.\n debug_match = re.search(r\"# (.*?)Exception:\", toplevel_output, re.DOTALL)\n message = match.group(1).strip()\n else:\n # Debug output will be octothorp to return value\n debug_match = re.search(r\"# (.*?)\\n- :\", toplevel_output, re.DOTALL)\n message = None\n # Print the debug output, if any\n if debug_match is not None and debug_match.group(1):\n print(debug_match.group(1).rstrip())\n return message\n\n def _source_of_exception(self, errorMessage):\n \"\"\"\n 2013-08-23:\n Get the line number and source file that spawned `errorMessage`,\n extract that line of code from that source file.\n \"\"\"\n match = re.search(r\"File \\\"(.*?)\\\", line ([0-9]+),\", errorMessage)\n if match is None:\n return \"\"\n else:\n fname = match.group(1)\n line_num = int(match.group(2))\n with open(fname, \"r\") as f:\n currentLine = 1\n message = \"\"\n while currentLine < line_num:\n currentLine += 1\n message = next(f)\n try:\n if message:\n return(\" %s %s---> %s %s\" % \\\n (line_num-1, message, line_num, next(f).rstrip()))\n else:\n return(\"---> %s %s\" % (line_num, next(f).rstrip()))\n except StopIteration:\n # File ended unexpectedly. Add an empty line and point to it\n return(\" %s %s---> %s <unexpected end of file>\" \\\n % (line_num-1, message, line_num))\n\n def _toplevel_input(self, module_name, test_case):\n \"\"\"\n 2013-07-28:\n Write a script for the toplevel. Call the right function\n from the right module\n \"\"\"\n return \"%s.%s ();;\" % (module_name.capitalize(), test_case)\n\n","sub_path":"util/runTest.py","file_name":"runTest.py","file_ext":"py","file_size_in_byte":10967,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"181276552","text":"# -*- coding: utf-8 -*-\n# Part of Odoo. See LICENSE file for full copyright and licensing details.\n\nfrom datetime import datetime\nfrom odoo import api, fields, models, tools, _\nfrom odoo.exceptions import ValidationError, except_orm, UserError\nimport calendar\n\n\nclass AccountAssetAsset(models.Model):\n _inherit = \"account.asset.asset\"\n\n asset_code = fields.Char(string = 'Asset Code', readonly=True)\n manufacturer = fields.Char(string = 'Manufacturer')\n serial_number = fields.Char(string = 'Serial Number')\n model_number = fields.Char(string = 'Model Number')\n\n @api.model\n def create(self, vals):\n vals['asset_code'] = self.env['ir.sequence'].next_by_code('account.asset.asset')\n res = super(AccountAssetAsset, self).create(vals)\n return res\n\n\nclass FixedAssetReportWizard(models.Model):\n _name = \"fixed.asset.report.wizard\"\n\n # from_date = fields.Date(string = 'From Date', required = True, default = fields.Date.today())\n # to_date = fields.Date(string = 'To Date', required = True, default = fields.Date.today())\n from_date = fields.Date(string = 'From Date')\n to_date = fields.Date(string = 'To Date')\n month = fields.Selection(\n string = 'Month',\n selection = [\n ('1', 'January'),\n ('2', 'February'),\n ('3', 'March'),\n ('4', 'April'),\n ('5', 'May'),\n ('6', 'June'),\n ('7', 'July'),\n ('8', 'August'),\n ('9', 'Setember'),\n ('10', 'October'),\n ('11', 'November'),\n ('12', 'December')\n ],\n default = ''\n )\n radio_selection = fields.Selection(\n string = 'Chose Report Type',\n selection = [\n ('0', 'Schedule'),\n ('1', 'Register')\n ],\n default = ''\n )\n \n \n @api.multi\n def action_fixed_asset_report_search_button(self):\n self.ensure_one() \n name = _('Fixed Asset Report Search')\n\n company_id = self.env.user.company_id.id\n currency_id = self.env.user.company_id.currency_id.id\n month_search = self.month\n from_date_search = self.from_date\n to_date_search = self.to_date\n radio_selection_search = self.radio_selection\n search_start_date = datetime.now()\n search_end_date = datetime.now()\n\n\n ## Set Report Type\n if radio_selection_search == '1':\n from_date_search = \"\"\n to_date_search = \"\"\n \n \n ## Print Report\n if not from_date_search or not to_date_search:\n if not month_search:\n raise UserError(\"Select Month.\")\n \n # search_month = month_search.capitalize()\n search_month = month_search\n\n ## Get Fixed Asset Schedule Report\n return self.print_fixed_asset_register_report(search_month, company_id, currency_id)\n else:\n search_start_date = datetime.strptime(from_date_search, '%Y-%m-%d').strftime('%m/%d/%Y')\n search_end_date = datetime.strptime(to_date_search, '%Y-%m-%d').strftime('%m/%d/%Y')\n\n ## Get Fixed Asset Schedule Report\n return self.print_fixed_asset_schedule_report(search_start_date, search_end_date, company_id, currency_id)\n \n\n @api.multi\n def print_fixed_asset_schedule_report(self, search_start_date, search_end_date, company_id, currency_id):\n ## Get Fixed Asset Schedule\n #condition_for_daterange = \"AND (aaa.date BETWEEN '\" + search_start_date + \"' AND '\" + search_end_date + \"')\"\n condition_for_daterange = \"\"\n condition_for_daterange_cost = \"AND (date BETWEEN '\" + search_start_date + \"' AND '\" + search_end_date + \"')\"\n condition_for_daterange_cost_OB = \"AND (date < '\" + search_start_date + \"')\"\n condition_for_daterange_accumulated_depreciation = \"AND (line.depreciation_date BETWEEN '\" + search_start_date + \"' AND '\" + search_end_date + \"')\"\n condition_for_daterange_accumulated_depreciation_OB = \"AND (line.depreciation_date < '\" + search_start_date + \"')\"\n self.env.cr.execute(\"\"\" SELECT\n aaa.category_id\n , ( CASE\n WHEN (SELECT sum(value) FROM account_asset_asset WHERE state = 'open' {0} AND category_id = aaa.category_id) IS NULL THEN '0'\n ELSE (SELECT sum(value) FROM account_asset_asset WHERE state = 'open' {1} AND category_id = aaa.category_id)\n END ) AS opening_balance_cost\n , ( CASE\n WHEN (SELECT sum(value) FROM account_asset_asset WHERE (state = 'open' OR state = 'close') {2} AND category_id = aaa.category_id) IS NULL THEN '0'\n ELSE (SELECT sum(value) FROM account_asset_asset WHERE (state = 'open' OR state = 'close') {3} AND category_id = aaa.category_id)\n END ) AS addition_cost\n , ( CASE\n WHEN (SELECT sum(value) FROM account_asset_asset WHERE state = 'close' {4} AND category_id = aaa.category_id) IS NULL THEN '0'\n ELSE (SELECT sum(value) FROM account_asset_asset WHERE state = 'close' {5} AND category_id = aaa.category_id)\n END ) AS disposal_cost\n , ( CASE\n WHEN (SELECT sum(line.amount) FROM account_asset_depreciation_line line LEFT JOIN account_asset_asset asset ON line.asset_id = asset.id WHERE asset.state = 'open' AND line.move_posted_check = true {6} AND asset.category_id = aaa.category_id) IS NULL THEN '0'\n ELSE (SELECT sum(line.amount) FROM account_asset_depreciation_line line LEFT JOIN account_asset_asset asset ON line.asset_id = asset.id WHERE asset.state = 'open' AND line.move_posted_check = true {7} AND asset.category_id = aaa.category_id)\n END ) AS opening_balance_accumulated_depreciation\n , ( CASE\n WHEN (SELECT sum(line.amount) FROM account_asset_depreciation_line line LEFT JOIN account_asset_asset asset ON line.asset_id = asset.id WHERE asset.state = 'open' AND line.move_posted_check = true {8} AND asset.category_id = aaa.category_id) IS NULL THEN '0'\n ELSE (SELECT sum(line.amount) FROM account_asset_depreciation_line line LEFT JOIN account_asset_asset asset ON line.asset_id = asset.id WHERE asset.state = 'open' AND line.move_posted_check = true {9} AND asset.category_id = aaa.category_id)\n END ) AS depreciation_accumulated_depreciation\n , ( CASE\n WHEN (SELECT sum(line.amount) FROM account_asset_depreciation_line line LEFT JOIN account_asset_asset asset ON line.asset_id = asset.id WHERE asset.state = 'close' AND line.move_posted_check = true {10} AND asset.category_id = aaa.category_id) IS NULL THEN '0'\n ELSE (SELECT sum(line.amount) FROM account_asset_depreciation_line line LEFT JOIN account_asset_asset asset ON line.asset_id = asset.id WHERE asset.state = 'close' AND line.move_posted_check = true {11} AND asset.category_id = aaa.category_id)\n END ) AS disposal_accumulated_depreciation\n FROM account_asset_asset aaa\n WHERE aaa.company_id = %s\n {12}\n GROUP BY aaa.category_id; \"\"\".format(\n condition_for_daterange_cost_OB,\n condition_for_daterange_cost_OB,\n\n condition_for_daterange_cost,\n condition_for_daterange_cost,\n condition_for_daterange_cost,\n condition_for_daterange_cost,\n\n condition_for_daterange_accumulated_depreciation_OB,\n condition_for_daterange_accumulated_depreciation_OB,\n\n condition_for_daterange_accumulated_depreciation,\n condition_for_daterange_accumulated_depreciation,\n condition_for_daterange_accumulated_depreciation,\n condition_for_daterange_accumulated_depreciation,\n\n condition_for_daterange\n ), \n ( \n tuple(str(company_id)),\n ))\n res = self.env.cr.dictfetchall()\n\n\n ## Clear existing table data\n self.env.cr.execute(\"\"\" TRUNCATE TABLE fixed_asset_schedule_report ; \"\"\")\n\n \n ## Push new data to the table\n for item in res:\n item_closing_balance_cost = (float(item['opening_balance_cost']) + float(item['addition_cost'])) - float(item['disposal_cost'])\n item_closing_balance_accumulated_depreciation = (float(item['opening_balance_accumulated_depreciation']) + float(item['depreciation_accumulated_depreciation'])) - float(item['disposal_accumulated_depreciation'])\n item_net_book = item_closing_balance_cost - item_closing_balance_accumulated_depreciation\n\n self.env['fixed.asset.schedule.report'].create({\n 'category_id': item['category_id'],\n 'currency_id': currency_id,\n 'search_start_date': search_start_date,\n 'search_end_date': search_end_date,\n\n 'opening_balance_cost': item['opening_balance_cost'],\n 'addition_cost': item['addition_cost'],\n 'disposal_cost': item['disposal_cost'],\n 'closing_balance_cost': item_closing_balance_cost,\n\n 'opening_balance_accumulated_depreciation': item['opening_balance_accumulated_depreciation'],\n 'depreciation_accumulated_depreciation': item['depreciation_accumulated_depreciation'],\n 'disposal_accumulated_depreciation': item['disposal_accumulated_depreciation'],\n 'closing_balance_accumulated_depreciation': item_closing_balance_accumulated_depreciation,\n\n 'net_book': item_net_book\n })\n \n \n ## Redirect to the Tree View or Export Report\n data = self.env['fixed.asset.schedule.report'].search([])\n if data:\n return data.env['report'].get_action(data, 'fixed_asset_report.fixed_asset_schedule_report_template')\n else:\n raise UserError(\"No data found.\")\n\n \n @api.multi\n def print_fixed_asset_register_report(self, search_month, company_id, currency_id):\n now = datetime.now().date()\n days = calendar.monthrange(now.year,int(search_month))[1]\n search_start_date = datetime(now.year,int(search_month), 1).date().strftime('%Y-%m-%d')\n search_end_date = datetime(now.year,int(search_month), days).date().strftime('%Y-%m-%d')\n\n \n ## Get Month Name\n months = [ 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'Setember', 'October', 'November', 'December' ]\n month_name = months[int(search_month) - 1]\n month_name = month_name.capitalize()\n\n \n ## Get Fixed Asset Register\n condition_for_daterange = \"AND (aadl.depreciation_date BETWEEN '\" + search_start_date + \"' AND '\" + search_end_date + \"')\"\n condition_for_daterange_line = \"AND (line.depreciation_date BETWEEN '\" + search_start_date + \"' AND '\" + search_end_date + \"')\"\n self.env.cr.execute(\"\"\" SELECT \n aac.id AS category_id\n , aaa.id AS asset_id\n , aaa.asset_code\n , aaa.name AS asset_name\n , aaa.manufacturer\n , aaa.serial_number\n , aaa.model_number\n , aaa.create_date AS purchase_date\n , aaa.value AS cost\n , ( CASE \n WHEN (SELECT sum(line.depreciated_value) FROM account_asset_depreciation_line line LEFT JOIN account_asset_asset asset ON line.asset_id = asset.id WHERE asset.state = 'open' {0} AND asset.id = aaa.id) IS NULL THEN '0'\n ELSE (SELECT sum(line.depreciated_value) FROM account_asset_depreciation_line line LEFT JOIN account_asset_asset asset ON line.asset_id = asset.id WHERE asset.state = 'open' {1} AND asset.id = aaa.id)\n END ) AS accumulated_depreciation\n , ( CASE\n WHEN (SELECT sum(line.remaining_value) FROM account_asset_depreciation_line line LEFT JOIN account_asset_asset asset ON line.asset_id = asset.id WHERE asset.state = 'open' {2} AND asset.id = aaa.id) IS NULL THEN '0'\n ELSE (SELECT sum(line.remaining_value) FROM account_asset_depreciation_line line LEFT JOIN account_asset_asset asset ON line.asset_id = asset.id WHERE asset.state = 'open' {3} AND asset.id = aaa.id)\n END ) AS net_book\n , aaa.currency_id\n , aaa.company_id\n FROM account_asset_depreciation_line aadl\n LEFT JOIN account_asset_asset aaa ON aadl.asset_id = aaa.id\n LEFT JOIN account_asset_category aac ON aaa.category_id = aac.id\n WHERE aaa.company_id = 1\n {4}\n AND aaa.company_id = %s\n GROUP BY aaa.id\n , aac.id\n , aaa.asset_code\n , aaa.name\n , aaa.manufacturer\n , aaa.serial_number\n , aaa.model_number\n , aaa.create_date\n , aaa.currency_id\n , aaa.company_id; \"\"\".format(\n condition_for_daterange_line,\n condition_for_daterange_line,\n condition_for_daterange_line,\n condition_for_daterange_line,\n condition_for_daterange\n ), (tuple(str(company_id)),))\n res = self.env.cr.dictfetchall()\n\n\n ## Clear existing table data\n self.env.cr.execute(\"\"\" TRUNCATE TABLE fixed_asset_register_report ; \"\"\")\n\n \n ## Push new data to the table\n for item in res:\n self.env['fixed.asset.register.report'].create({\n 'category_id': item['category_id'],\n 'asset_id': item['asset_id'],\n 'asset_code': item['asset_code'],\n 'asset_name': item['asset_name'],\n 'manufacturer': item['manufacturer'],\n 'serial_number': item['serial_number'],\n 'model_number': item['model_number'],\n 'purchase_date': item['purchase_date'],\n 'cost': item['cost'],\n 'accumulated_depreciation': item['accumulated_depreciation'],\n 'net_book': item['net_book'],\n\n 'month': month_name,\n 'currency_id': currency_id\n })\n \n \n ## Redirect to the Tree View or Export Report\n data = self.env['fixed.asset.register.report'].search([])\n if data:\n return data.env['report'].get_action(data, 'fixed_asset_report.fixed_asset_register_report_template')\n else:\n raise UserError(\"No data found.\")\n\n","sub_path":"fixed_asset_report/models/fixed_asset_report_filter_wizard.py","file_name":"fixed_asset_report_filter_wizard.py","file_ext":"py","file_size_in_byte":17389,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"97965200","text":"# -*- coding: utf-8 -*-\n#-----------------------------------------------------------\n#\n# Profile\n# Copyright (C) 2012 Matthias Kuhn\n#-----------------------------------------------------------\n#\n# licensed under the terms of GNU GPL 2\n#\n# This program is free software; you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation; either version 2 of the License, or\n# (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License along\n# with this progsram; if not, write to the Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.\n#\n#---------------------------------------------------------------------\n\nfrom PyQt4.QtGui import QVBoxLayout, QWidget, QPrintPreviewDialog, QPrinter\nfrom PyQt4.QtWebKit import QWebView, QWebSettings, QWebPage\nfrom PyQt4.QtCore import QUrl, pyqtSignal, pyqtSlot, QSettings, Qt\nfrom qgepplugin.utils.translation import QgepJsTranslator\n\nimport logging\n\nclass QgepWebPage( QWebPage ):\n logger = logging.getLogger( __name__ )\n \n def javaScriptConsoleMessage( self, msg, line, source ):\n self.logger.debug( '%s line %d: %s' % (source, line, msg) )\n\nclass QgepPlotSVGWidget( QWidget ):\n webView = None\n webPage = None\n frame = None\n profile = None\n verticalExaggeration = 10\n jsTranslator = QgepJsTranslator()\n\n # Signals emitted triggered by javascript actions\n reachClicked = pyqtSignal( [unicode], name='reachClicked' )\n reachMouseOver = pyqtSignal( [unicode], name='reachMouseOver' )\n reachMouseOut = pyqtSignal( [unicode], name='reachMouseOut' )\n reachPointClicked = pyqtSignal( [unicode, unicode], name='reachPointClicked' )\n reachPointMouseOver = pyqtSignal( [unicode, unicode], name='reachPointMouseOver' )\n reachPointMouseOut = pyqtSignal( [unicode, unicode], name='reachPointMouseOut' )\n specialStructureClicked = pyqtSignal( [unicode], name='specialStructureClicked' )\n specialStructureMouseOver = pyqtSignal( [unicode], name='specialStructureMouseOver' )\n specialStructureMouseOut = pyqtSignal( [unicode], name='specialStructureMouseOut' )\n \n # Signals emitted for javascript\n profileChanged = pyqtSignal( [unicode], name='profileChanged' )\n verticalExaggerationChanged = pyqtSignal( [int], name='verticalExaggerationChanged' )\n \n def __init__( self, parent, networkAnalyzer, url = None ):\n QWidget.__init__( self, parent )\n \n self.webView = QWebView()\n self.webView.setPage( QgepWebPage( self.webView ) )\n \n self.networkAnalyzer = networkAnalyzer\n \n settings = QSettings()\n \n layout = QVBoxLayout( self )\n if url is None:\n url = settings.value( \"/QGEP/SvgProfilePath\", u'qrc:///plugins/qgepplugin/svgprofile/index.html' )\n \n developerMode = settings.value( \"/QGEP/DeveloperMode\", False, type=bool )\n \n if developerMode is True:\n self.webView.page().settings().setAttribute(QWebSettings.DeveloperExtrasEnabled, True)\n else:\n self.webView.setContextMenuPolicy( Qt.NoContextMenu )\n \n self.webView.load( QUrl( url ) )\n self.frame = self.webView.page().mainFrame()\n self.frame.javaScriptWindowObjectCleared.connect( self.initJs )\n\n layout.addWidget( self.webView )\n \n def setProfile( self, profile ):\n self.profile = profile\n # Forward to javascript\n self.profileChanged.emit( profile.asJson() )\n \n def initJs(self):\n self.frame.addToJavaScriptWindowObject( \"profileProxy\", self )\n self.frame.addToJavaScriptWindowObject( \"i18n\", self.jsTranslator )\n \n def changeVerticalExaggeration(self, val):\n self.verticalExaggeration = val\n self.verticalExaggerationChanged.emit(val)\n \n def printProfile(self):\n printer = QPrinter( QPrinter.HighResolution )\n printer.setOutputFormat( QPrinter.PdfFormat )\n printer.setPaperSize( QPrinter.A4 )\n printer.setOrientation( QPrinter.Landscape )\n \n printPreviewDlg = QPrintPreviewDialog( )\n printPreviewDlg.paintRequested.connect( self.printRequested )\n \n printPreviewDlg.exec_()\n \n @pyqtSlot( QPrinter )\n def printRequested( self, printer ):\n self.webView.print_( printer )\n \n @pyqtSlot( unicode )\n def onReachClicked(self, objId):\n self.reachClicked.emit( objId )\n \n @pyqtSlot( unicode )\n def onReachMouseOver(self, objId):\n self.reachMouseOver.emit( objId )\n \n @pyqtSlot( unicode )\n def onReachMouseOut(self, objId):\n self.reachMouseOut.emit( objId )\n\n @pyqtSlot( unicode, unicode )\n def onReachPointClicked(self, objId, reachObjId):\n self.reachPointClicked.emit( objId, reachObjId )\n \n @pyqtSlot( unicode, unicode )\n def onReachPointMouseOver(self, objId, reachObjId):\n self.reachPointMouseOver.emit( objId, reachObjId )\n \n @pyqtSlot( unicode, unicode )\n def onReachPointMouseOut(self, objId, reachObjId):\n self.reachPointMouseOut.emit( objId, reachObjId )\n\n @pyqtSlot( unicode )\n def onSpecialStructureClicked(self, objId):\n self.specialStructureClicked.emit( objId )\n \n @pyqtSlot( unicode )\n def onSpecialStructureMouseOver(self, objId):\n self.specialStructureMouseOver.emit( objId )\n \n @pyqtSlot( unicode )\n def onSpecialStructureMouseOut(self, objId):\n self.specialStructureMouseOut.emit( objId )\n \n # Is called from the webView when it's been reloaded and wants to have the\n # profile information resent\n @pyqtSlot()\n def updateProfile(self):\n if self.profile:\n self.profileChanged.emit( self.profile.asJson() )\n self.verticalExaggerationChanged.emit( self.verticalExaggeration )\n ","sub_path":"qgepplugin/ui/qgepplotsvgwidget.py","file_name":"qgepplotsvgwidget.py","file_ext":"py","file_size_in_byte":6220,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"257324329","text":"# https://leetcode.com/problems/number-of-islands/\n'''\nGiven a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.\n\nExample 1:\n\n11110\n11010\n11000\n00000\nAnswer: 1\n\nExample 2:\n\n11000\n11000\n00100\n00011\nAnswer: 3\n\nCredits:\nSpecial thanks to @mithmatt for adding this problem and creating all test cases.\n\nHide Tags Depth-first Search Breadth-first Search\n'''\n\n\nfrom collections import deque\nclass Solution:\n\n def __init__(self):\n self._grid = None\n self._max_i = 0\n self._max_j = 0\n self._visited = None\n # @param {character[][]} grid\n # @return {integer}\n def numIslands(self, grid):\n if not grid:\n return 0\n self._grid = grid\n self._max_i = len(grid) - 1\n self._max_j = len(grid[0]) - 1\n res = 0\n self._visited = [[False for x in range(self._max_j + 1)] for y in range(self._max_i + 1)]\n for i in range(self._max_i + 1):\n for j in range(self._max_j + 1):\n if not self._visited[i][j] and self._grid[i][j] == '1':\n res += 1\n self._bfs(i, j)\n return res\n\n def _bfs(self, i, j):\n queue = deque([(i, j)])\n while queue:\n (i, j) = queue.pop()\n self._visited[i][j] = True\n neighbors = self._get_neighbors(i, j)\n for (ii, jj) in neighbors:\n if not self._visited[ii][jj]:\n queue.append((ii, jj))\n\n\n def _get_neighbors(self, i, j):\n res = []\n for ii in filter(lambda x: 0 <= x <= self._max_i, [i - 1, i + 1]):\n if self._grid[ii][j] == '1':\n res.append((ii, j))\n for jj in filter(lambda x: 0 <= x <= self._max_j, [j - 1, j + 1]):\n if self._grid[i][jj] == '1':\n res.append((i, jj))\n return res\n","sub_path":"number-of-islands/solution2.py","file_name":"solution2.py","file_ext":"py","file_size_in_byte":2025,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"543416107","text":"\"\"\"food db 2k+\n\nRevision ID: 791befa7f5f3\nRevises: 6a2a5bf77d17\nCreate Date: 2020-05-09 20:24:12.897976\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '791befa7f5f3'\ndown_revision = '6a2a5bf77d17'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_index('ix_food_datatable_index', table_name='food_datatable')\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_index('ix_food_datatable_index', 'food_datatable', ['index'], unique=False)\n # ### end Alembic commands ###\n","sub_path":"migrations/versions/791befa7f5f3_food_db_2k.py","file_name":"791befa7f5f3_food_db_2k.py","file_ext":"py","file_size_in_byte":697,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"642796963","text":"# Idea here is to be like sandbox for browsing the object model and identifying\n# objects and their functions / variables\n# reports goes into the product folder \\reports\\ and filenames are time stamped.\n\nimport adsk.core\nimport adsk.fusion\nimport traceback\n\nimport time\nimport os\n\nfrom os.path import expanduser\n\nfrom .Fusion360Utilities.Fusion360Utilities import get_app_objects\nfrom .Fusion360Utilities.Fusion360CommandBase import Fusion360CommandBase\n\n\ndef traverse_folder(data_folder, file_stats, folder_stats):\n # Scan the root folder for sub-folder, not recursive\n # data_folder is the root folder\n for folder in data_folder.dataFolders:\n folder_stats.append(get_folder_stats(folder))\n # We don't want it recursive Recursive\n # file_stats, folder_stats = traverse_folder(folder, file_stats, folder_stats) \n\n # data_folder is the root folder\n for data_file in data_folder.dataFiles:\n\n # if data_file.fileExtension in [\"f3d\", \"f2d\"]:\n # file_stats.append(get_stats(data_file))\n file_stats.append(get_stats(data_file))\n\n return file_stats, folder_stats\n\n\ndef get_folder_stats(data_folder):\n\n count_folders = 0\n for folder in data_folder.dataFolders:\n count_folders = count_folders + 1\n\n count_files = 0\n for data_file in data_folder.dataFiles:\n count_files = count_files + 1\n\n folder_stats = {\n \"name\": data_folder.name,\n \"parentFolder\": data_folder.parentFolder.name,\n \"parentProject\": data_folder.parentProject.name,\n \"NumberOfSubfolders\": str(count_folders),\n \"NumberOfFiles\": str(count_files)\n }\n\n return folder_stats\n\n\ndef get_stats(data_file):\n file_stat = {\n ## Commented fields cannot be converted to string, they are object(s)\n # Simple commented lines are just don't output it in CSV\n # \"id\": data_file.id, # useless\n \"name\": data_file.name,\n \"fileExtension\": data_file.fileExtension,\n \"objectType\": data_file.objectType,\n \"description\": data_file.description,\n\n \"hasParentReferences\": str(data_file.hasParentReferences),\n \"parentFolder\": data_file.parentFolder.name,\n \"parentProject\": data_file.parentProject.name,\n ## \"parentReferences\": data_file.parentReferences,\n\n \"isValid\": str(data_file.isValid),\n \"isInUse\": str(data_file.isInUse),\n \"hasOutofDateChildReferences\": str(data_file.hasOutofDateChildReferences),\n\n \"hasChildReferences\": str(data_file.hasChildReferences),\n ## \"childReferences\": data_file.childReferences,\n\n \"createdBy\": data_file.createdBy.userName,\n\n \"lastUpdatedBy\": data_file.lastUpdatedBy.userName,\n\n \"latestVersionNumber\": str(data_file.latestVersionNumber),\n ## \"latestVersion\": data_file.latestVersion,\n \"versionNumber\": str(data_file.versionNumber),\n ## \"versions\": data_file.versions\n\n \"fullPartName\": (data_file.parentProject.name[0:9] +\n data_file.name[0:9] +\n '.' + str(data_file.versionNumber)),\n \"productName\": data_file.parentProject.name[14:99],\n \"partName\": data_file.name[10:99]\n }\n\n return file_stat\n\n\ndef dup_check(name):\n if os.path.exists(name):\n # delete the old file\n os.remove(name)\n\n # How to make the file is overwritten in worst case?\n # Currently the strategy is to add a time stmap to filename\n base, ext = os.path.splitext(name)\n # base += '-dup'\n name = base + ext\n # name = dup_check(name)\n \n return name\n\n\n# Creates directory and returns file name for settings file\ndef get_file_path():\n\n app = adsk.core.Application.get()\n active_project = app.data.activeProject\n project_name = active_project.name\n\n # Get Home directory\n default_path = expanduser(\"~\")\n default_path += '/Gdrive/GS_products/'\n default_path += project_name\n default_path += '/'\n\n # Create if doesn't exist\n if not os.path.exists(default_path):\n os.makedirs(default_path)\n\n return default_path\n\n\ndef save_data(file_name, stats):\n\n if len(stats) < 1:\n return False\n\n file_name = dup_check(file_name)\n\n output_file = open(file_name, 'w')\n\n# # sort columns by column header\n# files_stats = zip(*stats)\n# files_stats.sort(key=lambda x: x[0])\n# stats = zip(*files_stats)\n#\n# for file_stat in stats:\n# file_stat.sort(key=attrgetter('name'))\n\n data_headers = []\n\n for key in stats[0].keys():\n data_headers.append(key)\n\n for data_item in data_headers:\n output_file.write(data_item + ',')\n output_file.write('\\n')\n\n for file_stat in stats:\n for data_item in data_headers:\n output_file.write(file_stat[data_item] + ',')\n output_file.write('\\n')\n\n output_file.close()\n\n return True\n\n\nclass StatsCommand(Fusion360CommandBase):\n def on_preview(self, command, inputs, args, input_values):\n pass\n\n def on_destroy(self, command, inputs, reason, input_values):\n pass\n\n def on_input_changed(self, command_, command_inputs, changed_input, input_values):\n pass\n\n def on_execute(self, command, inputs, args, input_values):\n\n app = adsk.core.Application.get()\n\n file_stats = []\n folder_stats = []\n file_stats, folder_stats = traverse_folder(app.data.activeProject.rootFolder, file_stats, folder_stats)\n\n #folder_stats.sort(key=attrgetter('name'), reverse=False)\n #file_stats.sort(key=attrgetter('name'), reverse=False)\n\n msg = ''\n msg += \"Total Files: \" + str(len(file_stats)) + '\\n\\n'\n msg += \"Total Folders: \" + str(len(folder_stats)) + '\\n\\n'\n msg += \"Press OK to save stats to CSV files. \"\n\n get_app_objects()['ui'].messageBox(msg)\n\n path = input_values['output_path']\n path_statistics = 'reports/'\n # Create if doesn't exist\n if not os.path.exists(path + path_statistics):\n os.makedirs(path + path_statistics)\n\n TimeStamp = time.strftime(\"%Y%m%d%H%M%S\")\n save_data(path + path_statistics + TimeStamp + \"_report_folders\" + \".csv\", folder_stats)\n save_data(path + path_statistics + TimeStamp + \"_report_files\" + \".csv\", file_stats)\n\n def on_create(self, command, command_inputs):\n app = adsk.core.Application.get()\n\n # allProjects = app.data.dataProjects\n active_project = app.data.activeProject\n project_name = active_project.name\n\n project_select = command_inputs.addStringValueInput('project_select', \"Project to Get Statistics: \",\n project_name)\n project_select.isReadOnly = True\n\n default_path = get_file_path()\n\n command_inputs.addStringValueInput('output_path', \"Output Directory: \", default_path)\n\n","sub_path":"StatsCommand.py","file_name":"StatsCommand.py","file_ext":"py","file_size_in_byte":6864,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"329015190","text":"__author__ = 'janomar'\n\nimport logging\n\nfrom airflow.hooks.jdbc_hook import JdbcHook\nfrom airflow.models import BaseOperator\nfrom airflow.utils import apply_defaults\n\n\nclass JdbcOperator(BaseOperator):\n \"\"\"\n Executes sql code in a database using jdbc driver.\n\n Requires jaydebeapi.\n\n :param jdbc_url: driver specific connection url with string variables, e.g. for exasol jdbc:exa:{0}:{1};schema={2}\n Template vars are defined like this: {0} = hostname, {1} = port, {2} = dbschema, {3} = extra\n :type jdbc_url: string\n :param jdbc_driver_name: classname of the specific jdbc driver, for exasol com.exasol.jdbc.EXADriver\n :type jdbc_driver_name: string\n :param jdbc_driver_loc: absolute path to jdbc driver location, for example /var/exasol/exajdbc.jar\n :type jdbc_driver_loc: string\n\n :param conn_id: reference to a predefined database\n :type conn_id: string\n :param sql: the sql code to be executed\n :type sql: string or string pointing to a template file. File must have\n a '.sql' extensions.\n \"\"\"\n\n template_fields = ('sql',)\n template_ext = ('.sql',)\n ui_color = '#ededed'\n\n @apply_defaults\n def __init__(\n self, sql,\n jdbc_url, jdbc_driver_name, jdbc_driver_loc,\n conn_id='jdbc_default', autocommit=False,\n *args, **kwargs):\n super(JdbcOperator, self).__init__(*args, **kwargs)\n\n self.jdbc_url=jdbc_url\n self.jdbc_driver_name=jdbc_driver_name\n self.jdbc_driver_loc=jdbc_driver_loc\n self.sql = sql\n self.conn_id = conn_id\n self.autocommit = autocommit\n\n def execute(self, context):\n logging.info('Executing: ' + self.sql)\n self.hook = JdbcHook(conn_id=self.conn_id,jdbc_driver_loc=self.jdbc_driver_loc, jdbc_driver_name=self.jdbc_driver_name,jdbc_url=self.jdbc_url)\n for row in self.hook.get_records(self.sql, self.autocommit):\n logging.info('Result: ' + ','.join(map(str,row)) )","sub_path":"airflow/operators/jdbc_operator.py","file_name":"jdbc_operator.py","file_ext":"py","file_size_in_byte":1977,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"284371780","text":"import os\nimport shutil \nfrom os import makedirs\n\nmy_list = []\nmy_list = os.listdir(\"/home/qainfotech/Desktop/ravi/new1\")\nsize = len(my_list)\nprint(\"size is\" , size)\nk = int(input(\"Enter k \"))\n#cnt = 0\n#for files in os.listdir(\"/home/qainfotech/Desktop/ravi/new1\"):\n # cnt = cnt+1\nrem = size%k\nif (rem!=0):\n folder_to_create = int((size/k)+1)\nelse:\n folder_to_create = int((size/k))\nfolder_path = []\nprint(folder_to_create)\nfor i in range(folder_to_create):\n x = input(\"give name of folder \")\n makedirs(x)\n folder_path.append(x)\n\n#for i in range(len(folder_path)):\n# print(folder_path[i])\ny = 0\nfor i in range(folder_to_create):\n for j in range(k):\n if(y<size):\n pth1 = '/home/qainfotech/Desktop/ravi/new1/'+my_list[y]\n source = pth1;\n y = y+1\n pth2 = '/home/qainfotech/Desktop/python/' + folder_path[i]\n destination = pth2\n shutil.move(source, destination)\n\n\n\n\n\n","sub_path":"pr1.py","file_name":"pr1.py","file_ext":"py","file_size_in_byte":959,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"446118958","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\"\"\"The log2timeline command line tool.\"\"\"\n\nimport argparse\nimport logging\nimport multiprocessing\nimport os\nimport sys\nimport time\nimport textwrap\n\nfrom dfvfs.lib import definitions as dfvfs_definitions\n\nfrom plaso import dependencies\nfrom plaso.cli import extraction_tool\nfrom plaso.cli import tools as cli_tools\nfrom plaso.cli import views as cli_views\nfrom plaso.frontend import log2timeline\nfrom plaso.engine import configurations\nfrom plaso.lib import errors\nfrom plaso.lib import pfilter\n\n\nclass Log2TimelineTool(extraction_tool.ExtractionTool):\n \"\"\"Class that implements the log2timeline CLI tool.\n\n Attributes:\n dependencies_check (bool): True if the availability and versions of\n dependencies should be checked.\n list_output_modules (bool): True if information about the output modules\n should be shown.\n show_info (bool): True if information about hashers, parsers, plugins,\n etc. should be shown.\n \"\"\"\n\n NAME = u'log2timeline'\n DESCRIPTION = textwrap.dedent(u'\\n'.join([\n u'',\n (u'log2timeline is a command line tool to extract events from '\n u'individual '),\n u'files, recursing a directory (e.g. mount point) or storage media ',\n u'image or device.',\n u'',\n u'More information can be gathered from here:',\n u' https://github.com/log2timeline/plaso/wiki/Using-log2timeline',\n u'']))\n\n EPILOG = textwrap.dedent(u'\\n'.join([\n u'',\n u'Example usage:',\n u'',\n u'Run the tool against a storage media image (full kitchen sink)',\n u' log2timeline.py /cases/mycase/storage.plaso ímynd.dd',\n u'',\n u'Instead of answering questions, indicate some of the options on the',\n u'command line (including data from particular VSS stores).',\n (u' log2timeline.py -o 63 --vss_stores 1,2 /cases/plaso_vss.plaso '\n u'image.E01'),\n u'',\n u'And that is how you build a timeline using log2timeline...',\n u'']))\n\n def __init__(self, input_reader=None, output_writer=None):\n \"\"\"Initializes the CLI tool object.\n\n Args:\n input_reader (Optional[InputReader]): input reader, where None indicates\n that the stdin input reader should be used.\n output_writer (Optional[OutputWriter]): output writer, where None\n indicates that the stdout output writer should be used.\n \"\"\"\n super(Log2TimelineTool, self).__init__(\n input_reader=input_reader, output_writer=output_writer)\n self._command_line_arguments = None\n self._enable_sigsegv_handler = False\n self._filter_expression = None\n self._front_end = log2timeline.Log2TimelineFrontend()\n self._number_of_extraction_workers = 0\n self._output = None\n self._source_type = None\n self._source_type_string = u'UNKNOWN'\n self._status_view_mode = u'linear'\n self._stdout_output_writer = isinstance(\n self._output_writer, cli_tools.StdoutOutputWriter)\n self._temporary_directory = None\n self._text_prepend = None\n self._worker_memory_limit = None\n\n self.dependencies_check = True\n self.list_output_modules = False\n self.show_info = False\n\n def _DetermineSourceType(self):\n \"\"\"Determines the source type.\"\"\"\n scan_context = self.ScanSource()\n self._source_type = scan_context.source_type\n\n if self._source_type == dfvfs_definitions.SOURCE_TYPE_DIRECTORY:\n self._source_type_string = u'directory'\n\n elif self._source_type == dfvfs_definitions.SOURCE_TYPE_FILE:\n self._source_type_string = u'single file'\n\n elif self._source_type == (\n dfvfs_definitions.SOURCE_TYPE_STORAGE_MEDIA_DEVICE):\n self._source_type_string = u'storage media device'\n\n elif self._source_type == (\n dfvfs_definitions.SOURCE_TYPE_STORAGE_MEDIA_IMAGE):\n self._source_type_string = u'storage media image'\n\n else:\n self._source_type_string = u'UNKNOWN'\n\n def _GetMatcher(self, filter_expression):\n \"\"\"Retrieves a filter object for a specific filter expression.\n\n Args:\n filter_expression (str): filter expression.\n\n Returns:\n A filter object (instance of objectfilter.TODO) or None.\n \"\"\"\n try:\n parser = pfilter.BaseParser(filter_expression).Parse()\n return parser.Compile(pfilter.PlasoAttributeFilterImplementation)\n\n except errors.ParseError as exception:\n logging.error(\n u'Unable to create filter: {0:s} with error: {1:s}'.format(\n filter_expression, exception))\n\n def _GetStatusUpdateCallback(self):\n \"\"\"Retrieves the status update callback function.\n\n Returns:\n function: status update callback function or None.\n \"\"\"\n if self._status_view_mode == u'linear':\n return self._PrintStatusUpdateStream\n elif self._status_view_mode == u'window':\n return self._PrintStatusUpdate\n\n def _ParseOutputOptions(self, options):\n \"\"\"Parses the output options.\n\n Args:\n options (argparse.Namespace): command line arguments.\n\n Raises:\n BadConfigOption: if the options are invalid.\n \"\"\"\n self._output_module = self.ParseStringOption(options, u'output_module')\n if self._output_module == u'list':\n self.list_output_modules = True\n\n self._text_prepend = self.ParseStringOption(options, u'text_prepend')\n\n def _ParseProcessingOptions(self, options):\n \"\"\"Parses the processing options.\n\n Args:\n options (argparse.Namespace): command line arguments.\n\n Raises:\n BadConfigOption: if the options are invalid.\n \"\"\"\n use_zeromq = getattr(options, u'use_zeromq', True)\n self._front_end.SetUseZeroMQ(use_zeromq)\n\n self._single_process_mode = getattr(options, u'single_process', False)\n\n self._temporary_directory = getattr(options, u'temporary_directory', None)\n if (self._temporary_directory and\n not os.path.isdir(self._temporary_directory)):\n raise errors.BadConfigOption(\n u'No such temporary directory: {0:s}'.format(\n self._temporary_directory))\n\n self._worker_memory_limit = getattr(options, u'worker_memory_limit', None)\n self._number_of_extraction_workers = getattr(options, u'workers', 0)\n\n # TODO: add code to parse the worker options.\n\n def AddOutputOptions(self, argument_group):\n \"\"\"Adds the output options to the argument group.\n\n Args:\n argument_group (argparse._ArgumentGroup): argparse argument group.\n \"\"\"\n argument_group.add_argument(\n u'--output', dest=u'output_module', action=u'store', type=str,\n default=u'', help=(\n u'Bypass the storage module directly storing events according to '\n u'the output module. This means that the output will not be in the '\n u'pstorage format but in the format chosen by the output module. '\n u'Use \"--output list\" or \"--info\" to list the available output '\n u'modules. Note this feature is EXPERIMENTAL at this time '\n u'e.g. sqlite output does not yet work.'))\n\n argument_group.add_argument(\n u'-t', u'--text', dest=u'text_prepend', action=u'store', type=str,\n default=u'', metavar=u'TEXT', help=(\n u'Define a free form text string that is prepended to each path '\n u'to make it easier to distinguish one record from another in a '\n u'timeline (like c:\\\\, or host_w_c:\\\\)'))\n\n def AddProcessingOptions(self, argument_group):\n \"\"\"Adds the processing options to the argument group.\n\n Args:\n argument_group (argparse._ArgumentGroup): argparse argument group.\n \"\"\"\n argument_group.add_argument(\n u'--disable_zeromq', u'--disable-zeromq', action=u'store_false',\n dest=u'use_zeromq', default=True, help=(\n u'Disable queueing using ZeroMQ. A Multiprocessing queue will be '\n u'used instead.'))\n\n argument_group.add_argument(\n u'--single_process', u'--single-process', dest=u'single_process',\n action=u'store_true', default=False, help=(\n u'Indicate that the tool should run in a single process.'))\n\n argument_group.add_argument(\n u'--temporary_directory', u'--temporary-directory',\n dest=u'temporary_directory', type=str, action=u'store',\n metavar=u'DIRECTORY', help=(\n u'Path to the directory that should be used to store temporary '\n u'files created during extraction.'))\n\n argument_group.add_argument(\n u'--worker-memory-limit', u'--worker_memory_limit',\n dest=u'worker_memory_limit', action=u'store', type=int,\n metavar=u'SIZE', help=(\n u'Maximum amount of memory a worker process is allowed to consume. '\n u'[defaults to 2 GiB]'))\n\n argument_group.add_argument(\n u'--workers', dest=u'workers', action=u'store', type=int, default=0,\n help=(u'The number of worker processes [defaults to available system '\n u'CPUs minus one].'))\n\n def ListHashers(self):\n \"\"\"Lists information about the available hashers.\"\"\"\n hashers_information = self._front_end.GetHashersInformation()\n\n table_view = cli_views.ViewsFactory.GetTableView(\n self._views_format_type, column_names=[u'Name', u'Description'],\n title=u'Hashers')\n\n for name, description in sorted(hashers_information):\n table_view.AddRow([name, description])\n table_view.Write(self._output_writer)\n\n def ListOutputModules(self):\n \"\"\"Lists the output modules.\"\"\"\n table_view = cli_views.ViewsFactory.GetTableView(\n self._views_format_type, column_names=[u'Name', u'Description'],\n title=u'Output Modules')\n for name, output_class in self._front_end.GetOutputClasses():\n table_view.AddRow([name, output_class.DESCRIPTION])\n table_view.Write(self._output_writer)\n\n disabled_classes = list(self._front_end.GetDisabledOutputClasses())\n if not disabled_classes:\n return\n\n table_view = cli_views.ViewsFactory.GetTableView(\n self._views_format_type, column_names=[u'Name', u'Description'],\n title=u'Disabled Output Modules')\n for name, output_class in disabled_classes:\n table_view.AddRow([name, output_class.DESCRIPTION])\n table_view.Write(self._output_writer)\n\n def ListParsersAndPlugins(self):\n \"\"\"Lists information about the available parsers and plugins.\"\"\"\n parsers_information = self._front_end.GetParsersInformation()\n\n table_view = cli_views.ViewsFactory.GetTableView(\n self._views_format_type, column_names=[u'Name', u'Description'],\n title=u'Parsers')\n\n for name, description in sorted(parsers_information):\n table_view.AddRow([name, description])\n table_view.Write(self._output_writer)\n\n for parser_name in self._front_end.GetNamesOfParsersWithPlugins():\n plugins_information = self._front_end.GetParserPluginsInformation(\n parser_filter_expression=parser_name)\n\n table_title = u'Parser plugins: {0:s}'.format(parser_name)\n table_view = cli_views.ViewsFactory.GetTableView(\n self._views_format_type, column_names=[u'Name', u'Description'],\n title=table_title)\n for name, description in sorted(plugins_information):\n table_view.AddRow([name, description])\n table_view.Write(self._output_writer)\n\n presets_information = self._front_end.GetParserPresetsInformation()\n\n table_view = cli_views.ViewsFactory.GetTableView(\n self._views_format_type, column_names=[u'Name', u'Parsers and plugins'],\n title=u'Parser presets')\n for name, description in sorted(presets_information):\n table_view.AddRow([name, description])\n table_view.Write(self._output_writer)\n\n def ParseArguments(self):\n \"\"\"Parses the command line arguments.\n\n Returns:\n bool: True if the arguments were successfully parsed.\n \"\"\"\n self._ConfigureLogging()\n\n argument_parser = argparse.ArgumentParser(\n description=self.DESCRIPTION, epilog=self.EPILOG, add_help=False,\n formatter_class=argparse.RawDescriptionHelpFormatter)\n\n self.AddBasicOptions(argument_parser)\n\n extraction_group = argument_parser.add_argument_group(\n u'Extraction Arguments')\n\n self.AddExtractionOptions(extraction_group)\n self.AddFilterOptions(extraction_group)\n self.AddStorageMediaImageOptions(extraction_group)\n self.AddTimezoneOption(extraction_group)\n self.AddVSSProcessingOptions(extraction_group)\n self.AddCredentialOptions(extraction_group)\n\n info_group = argument_parser.add_argument_group(u'Informational Arguments')\n\n self.AddInformationalOptions(info_group)\n\n info_group.add_argument(\n u'--info', dest=u'show_info', action=u'store_true', default=False,\n help=u'Print out information about supported plugins and parsers.')\n\n info_group.add_argument(\n u'--use_markdown', u'--use-markdown', dest=u'use_markdown',\n action=u'store_true', default=False, help=(\n u'Output lists in Markdown format use in combination with '\n u'\"--hashers list\", \"--parsers list\" or \"--timezone list\"'))\n\n info_group.add_argument(\n u'--no_dependencies_check', u'--no-dependencies-check',\n dest=u'dependencies_check', action=u'store_false', default=True,\n help=u'Disable the dependencies check.')\n\n self.AddLogFileOptions(info_group)\n\n # The window status-view mode has an annoying flicker on Windows,\n # hence we default to linear status-view mode instead.\n if sys.platform.startswith(u'win'):\n default_status_view = u'linear'\n else:\n default_status_view = u'window'\n\n info_group.add_argument(\n u'--status_view', u'--status-view', dest=u'status_view_mode',\n choices=[u'linear', u'none', u'window'], action=u'store',\n metavar=u'TYPE', default=default_status_view, help=(\n u'The processing status view mode: \"linear\", \"none\" or \"window\".'))\n\n output_group = argument_parser.add_argument_group(u'Output Arguments')\n\n self.AddOutputOptions(output_group)\n\n processing_group = argument_parser.add_argument_group(\n u'Processing Arguments')\n\n self.AddDataLocationOption(processing_group)\n self.AddPerformanceOptions(processing_group)\n self.AddProfilingOptions(processing_group)\n self.AddProcessingOptions(processing_group)\n\n processing_group.add_argument(\n u'--sigsegv_handler', u'--sigsegv-handler', dest=u'sigsegv_handler',\n action=u'store_true', default=False, help=(\n u'Enables the SIGSEGV handler. WARNING this functionality is '\n u'experimental and will a deadlock worker process if a real '\n u'segfault is caught, but not signal SIGSEGV. This functionality '\n u'is therefore primarily intended for debugging purposes'))\n\n argument_parser.add_argument(\n u'output', action=u'store', metavar=u'STORAGE_FILE', nargs=u'?',\n type=str, help=(\n u'The path to the output file, if the file exists it will get '\n u'appended to.'))\n\n argument_parser.add_argument(\n self._SOURCE_OPTION, action=u'store', metavar=u'SOURCE', nargs=u'?',\n default=None, type=str, help=(\n u'The path to the source device, file or directory. If the source '\n u'is a supported storage media device or image file, archive file '\n u'or a directory, the files within are processed recursively.'))\n\n argument_parser.add_argument(\n u'filter', action=u'store', metavar=u'FILTER', nargs=u'?', default=None,\n type=str, help=(\n u'A filter that can be used to filter the dataset before it '\n u'is written into storage. More information about the filters '\n u'and its usage can be found here: http://plaso.kiddaland.'\n u'net/usage/filters'))\n\n try:\n options = argument_parser.parse_args()\n except UnicodeEncodeError:\n # If we get here we are attempting to print help in a non-Unicode\n # terminal.\n self._output_writer.Write(u'\\n')\n self._output_writer.Write(argument_parser.format_help())\n return False\n\n # Properly prepare the attributes according to local encoding.\n if self.preferred_encoding == u'ascii':\n logging.warning(\n u'The preferred encoding of your system is ASCII, which is not '\n u'optimal for the typically non-ASCII characters that need to be '\n u'parsed and processed. The tool will most likely crash and die, '\n u'perhaps in a way that may not be recoverable. A five second delay '\n u'is introduced to give you time to cancel the runtime and '\n u'reconfigure your preferred encoding, otherwise continue at own '\n u'risk.')\n time.sleep(5)\n\n if self._process_archives:\n logging.warning(\n u'Scanning archive files currently can cause deadlock. Continue at '\n u'your own risk.')\n time.sleep(5)\n\n try:\n self.ParseOptions(options)\n except errors.BadConfigOption as exception:\n self._output_writer.Write(u'ERROR: {0:s}'.format(exception))\n self._output_writer.Write(u'\\n')\n self._output_writer.Write(argument_parser.format_usage())\n return False\n\n self._command_line_arguments = self.GetCommandLineArguments()\n\n return True\n\n def ParseOptions(self, options):\n \"\"\"Parses the options.\n\n Args:\n options (argparse.Namespace): command line arguments.\n\n Raises:\n BadConfigOption: if the options are invalid.\n \"\"\"\n # Check the list options first otherwise required options will raise.\n self._ParseExtractionOptions(options)\n self._ParseOutputOptions(options)\n self._ParseTimezoneOption(options)\n\n self.show_info = getattr(options, u'show_info', False)\n\n if getattr(options, u'use_markdown', False):\n self._views_format_type = cli_views.ViewsFactory.FORMAT_TYPE_MARKDOWN\n\n self.dependencies_check = getattr(options, u'dependencies_check', True)\n\n if (self.list_hashers or self.list_output_modules or\n self.list_parsers_and_plugins or self.list_timezones or\n self.show_info):\n return\n\n super(Log2TimelineTool, self).ParseOptions(options)\n self._ParseOutputOptions(options)\n self._ParseProcessingOptions(options)\n\n format_string = (\n u'%(asctime)s [%(levelname)s] (%(processName)-10s) PID:%(process)d '\n u'<%(module)s> %(message)s')\n\n if self._debug_mode:\n logging_level = logging.DEBUG\n elif self._quiet_mode:\n logging_level = logging.WARNING\n else:\n logging_level = logging.INFO\n\n self.ParseLogFileOptions(options)\n self._ConfigureLogging(\n filename=self._log_file, format_string=format_string,\n log_level=logging_level)\n\n if self._debug_mode:\n logging_filter = log2timeline.LoggingFilter()\n root_logger = logging.getLogger()\n root_logger.addFilter(logging_filter)\n\n self._output = self.ParseStringOption(options, u'output')\n if not self._output:\n raise errors.BadConfigOption(u'No output defined.')\n\n # TODO: where is this defined?\n self._operating_system = getattr(options, u'os', None)\n\n if self._operating_system:\n self._mount_path = getattr(options, u'filename', None)\n\n self._filter_expression = self.ParseStringOption(options, u'filter')\n if self._filter_expression:\n # TODO: refactor self._filter_object out the tool into the frontend.\n self._filter_object = self._GetMatcher(self._filter_expression)\n if not self._filter_object:\n raise errors.BadConfigOption(\n u'Invalid filter expression: {0:s}'.format(self._filter_expression))\n\n self._status_view_mode = getattr(options, u'status_view_mode', u'linear')\n self._enable_sigsegv_handler = getattr(options, u'sigsegv_handler', False)\n\n def ProcessSources(self):\n \"\"\"Processes the sources.\n\n Raises:\n SourceScannerError: if the source scanner could not find a supported\n file system.\n UserAbort: if the user initiated an abort.\n \"\"\"\n self._DetermineSourceType()\n\n self._output_writer.Write(u'\\n')\n self._PrintStatusHeader()\n\n self._output_writer.Write(u'Processing started.\\n')\n\n status_update_callback = self._GetStatusUpdateCallback()\n\n session = self._front_end.CreateSession(\n command_line_arguments=self._command_line_arguments,\n filter_file=self._filter_file,\n preferred_encoding=self.preferred_encoding,\n preferred_time_zone=self._preferred_time_zone,\n preferred_year=self._preferred_year)\n\n storage_writer = self._front_end.CreateStorageWriter(session, self._output)\n # TODO: handle errors.BadConfigOption\n\n # TODO: pass preferred_encoding.\n configuration = configurations.ProcessingConfiguration()\n configuration.credentials = self._credential_configurations\n configuration.debug_output = self._debug_mode\n configuration.event_extraction.filter_object = self._filter_object\n configuration.event_extraction.text_prepend = self._text_prepend\n configuration.extraction.hasher_names_string = self._hasher_names_string\n configuration.extraction.process_archives = self._process_archives\n configuration.extraction.process_compressed_streams = (\n self._process_compressed_streams)\n configuration.extraction.yara_rules_string = self._yara_rules_string\n configuration.filter_file = self._filter_file\n configuration.filter_object = self._filter_object\n configuration.input_source.mount_path = self._mount_path\n configuration.parser_filter_expression = self._parser_filter_expression\n configuration.preferred_year = self._preferred_year\n configuration.profiling.directory = self._profiling_directory\n configuration.profiling.enable = self._enable_profiling\n configuration.profiling.sample_rate = self._profiling_sample_rate\n configuration.profiling.profiling_type = self._profiling_type\n configuration.temporary_directory = self._temporary_directory\n\n processing_status = self._front_end.ProcessSources(\n session, storage_writer, self._source_path_specs, self._source_type,\n configuration, enable_sigsegv_handler=self._enable_sigsegv_handler,\n force_preprocessing=self._force_preprocessing,\n number_of_extraction_workers=self._number_of_extraction_workers,\n single_process_mode=self._single_process_mode,\n status_update_callback=status_update_callback,\n worker_memory_limit=self._worker_memory_limit)\n\n if not processing_status:\n self._output_writer.Write(\n u'WARNING: missing processing status information.\\n')\n\n elif not processing_status.aborted:\n if processing_status.error_path_specs:\n self._output_writer.Write(u'Processing completed with errors.\\n')\n else:\n self._output_writer.Write(u'Processing completed.\\n')\n\n number_of_errors = (\n processing_status.foreman_status.number_of_produced_errors)\n if number_of_errors:\n output_text = u'\\n'.join([\n u'',\n (u'Number of errors encountered while extracting events: '\n u'{0:d}.').format(number_of_errors),\n u'',\n u'Use pinfo to inspect errors in more detail.',\n u''])\n self._output_writer.Write(output_text)\n\n if processing_status.error_path_specs:\n output_text = u'\\n'.join([\n u'',\n u'Path specifications that could not be processed:',\n u''])\n self._output_writer.Write(output_text)\n for path_spec in processing_status.error_path_specs:\n self._output_writer.Write(path_spec.comparable)\n self._output_writer.Write(u'\\n')\n\n self._output_writer.Write(u'\\n')\n\n def ShowInfo(self):\n \"\"\"Shows information about available hashers, parsers, plugins, etc.\"\"\"\n self._output_writer.Write(\n u'{0:=^80s}\\n'.format(u' log2timeline/plaso information '))\n\n plugin_list = self._front_end.GetPluginData()\n for header, data in plugin_list.items():\n table_view = cli_views.ViewsFactory.GetTableView(\n self._views_format_type, column_names=[u'Name', u'Description'],\n title=header)\n for entry_header, entry_data in sorted(data):\n table_view.AddRow([entry_header, entry_data])\n table_view.Write(self._output_writer)\n\n\ndef Main():\n \"\"\"The main function.\"\"\"\n multiprocessing.freeze_support()\n\n tool = Log2TimelineTool()\n\n if not tool.ParseArguments():\n return False\n\n if tool.show_info:\n tool.ShowInfo()\n return True\n\n have_list_option = False\n if tool.list_hashers:\n tool.ListHashers()\n have_list_option = True\n\n if tool.list_parsers_and_plugins:\n tool.ListParsersAndPlugins()\n have_list_option = True\n\n if tool.list_output_modules:\n tool.ListOutputModules()\n have_list_option = True\n\n if tool.list_timezones:\n tool.ListTimeZones()\n have_list_option = True\n\n if have_list_option:\n return True\n\n if tool.dependencies_check and not dependencies.CheckDependencies(\n verbose_output=False):\n return False\n\n try:\n tool.ProcessSources()\n\n except (KeyboardInterrupt, errors.UserAbort):\n logging.warning(u'Aborted by user.')\n return False\n\n except (errors.BadConfigOption, errors.SourceScannerError) as exception:\n logging.warning(exception)\n return False\n\n return True\n\n\nif __name__ == '__main__':\n if not Main():\n sys.exit(1)\n else:\n sys.exit(0)\n","sub_path":"tools/log2timeline.py","file_name":"log2timeline.py","file_ext":"py","file_size_in_byte":25256,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"409718079","text":"import time\nimport os\n#import motor_runner\n#import net_check\nfrom AWSIoTPythonSDK.MQTTLib import AWSIoTMQTTClient\n\ndef callback():\n print('calling back')\n\nmyMQTTClient = AWSIoTMQTTClient(\"smarthome\") #random key, if another connection using the same key is opened the previous one is auto closed by AWS IOT\n \nmyMQTTClient.configureEndpoint(\"a2jyw4jkpz537x.iot.us-west-2.amazonaws.com\", 8883)\ncertRootPath = '/home/pi/Desktop/homeautomation/awskey/'\nmyMQTTClient.configureCredentials(\"{}root-ca.pem\".format( certRootPath), \"{}smarthome.private.key\".format(certRootPath), \"{}smarthome.cert.pem\".format(certRootPath))\n \nmyMQTTClient.configureOfflinePublishQueueing(-1) # Infinite offline Publish queueing\nmyMQTTClient.configureDrainingFrequency(2) # Draining: 2 Hz\nmyMQTTClient.configureConnectDisconnectTimeout(10) # 10 sec\nmyMQTTClient.configureMQTTOperationTimeout(5) # 5 sec\n\nmyMQTTClient.connect()\n#myMQTTClient.subscribe(\"smarthome\", 1,callback)\nmyMQTTClient.publish(\"mytopic\", \"hello i am addison\", 1)\n\n","sub_path":"python/assistant/awsiot.py","file_name":"awsiot.py","file_ext":"py","file_size_in_byte":1010,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"574107706","text":"from django.conf.urls import url\nfrom . import views\nurlpatterns = [\n url(r'^$', views.index),\n url(r'^login/$', views.login),\n url(r'^register_form/$', views.register_form),\n url(r'^add_user/$', views.add_user),\n url(r'^quotes/$', views.dashboard),\n url(r'^user/(?P<num>\\d+)/$', views.userQuotes),\n url(r'^myaccount/(?P<num>\\d+)/$', views.myAccount),\n url(r'^addQuote/$', views.add_quote),\n url(r'^update/$', views.update),\n url(r'^logout/$', views.logout),\n url(r'^delete/(?P<num>\\d+)/$', views.delete),\n url(r'^like/(?P<num>\\d+)/$', views.like)\n]","sub_path":"apps/exam/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":585,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"376017267","text":"with open(\"input.txt\") as f:\n f_write = open('output.txt','w')\n test_cases = int(f.readline())\n for i in range(test_cases):\n n = int(f.readline())\n new_number = n\n digits = set([int(j) for j in str(n)])\n insomnia = True\n for k in range(1000000):\n if len(digits) == 10:\n insomnia = False\n f_write.write(\"Case #\"+str(i+1)+\": \"+str(new_number)+\"\\n\")\n break\n new_number += n\n digits.update([int(j) for j in str(new_number)])\n if insomnia:\n f_write.write(\"Case #\"+str(i+1)+\": INSOMNIA\\n\")\n","sub_path":"codes/CodeJamCrawler/16_0_1_neat/16_0_1_CHINKU_Code.py","file_name":"16_0_1_CHINKU_Code.py","file_ext":"py","file_size_in_byte":624,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"202158703","text":"import librosa\nfrom pathlib import Path\nimport pandas as pd\nfrom sklearn.model_selection import GroupKFold, StratifiedKFold\nfrom tqdm import tqdm\ntqdm.pandas()\n\nfrom src.constants import CODE2INT, TRAIN_CLIPS\n\n\ndef species_to_code(x):\n codes = []\n x = x[1:-1].split(\",\")\n if x[0] == \"\":\n return codes\n else:\n x = [code[1:-1] for code in x]\n return x\n\n\ndef get_timesteps(fname):\n #try:\n y, sr = librosa.load(fname, sr=None, res_type='kaiser_fast')\n return len(y)\n # except:\n # raise ValueError(f\"{fname} not found\")\n # finally:\n # return 0\n\n\nif __name__ == \"__main__\":\n DATA_ROOT = \"data\"\n train = pd.read_csv(Path(DATA_ROOT) / \"train_metadata.csv\")\n train[\"filepaths\"] = train.apply(\n lambda x: f\"data/train_short_audio/{x['primary_label']}/{x['filename']}\", axis=1,\n )\n train[\"labels\"] = train.primary_label.apply(lambda x: [x])\n train[\"durations\"] = train.filepaths.progress_apply(get_timesteps)\n train[\"all_labels\"] = train.secondary_labels.apply(species_to_code) + train[\"labels\"]\n print(train.head())\n cvlist = list(StratifiedKFold(5, shuffle=True, random_state=12345786).split(train, train.primary_label))\n\n for idx, (tr_idx, vl_idx) in enumerate(cvlist):\n train.iloc[tr_idx][[\"filepaths\", \"durations\", \"labels\", \"all_labels\"]].to_parquet(\n f\"data/tr_{idx}.pq\"\n )\n train.iloc[vl_idx][[\"filepaths\", \"durations\", \"labels\", \"all_labels\"]].to_parquet(\n f\"data/vl_{idx}.pq\"\n )\n","sub_path":"src/prepare_dataset.py","file_name":"prepare_dataset.py","file_ext":"py","file_size_in_byte":1527,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"581388992","text":"# coding=utf-8\n\"\"\"Dota2 Senate.\n\n>>> solve = _solve\n>>> solve('RD')\n'Radiant'\n>>> solve('RDD')\n'Dire'\n>>> solve('DDRRRDR')\n'Radiant'\n>>> solve('DDRRR')\n'Dire'\n\"\"\"\n\nimport collections\n\n\n# 贪心策略是 ban 掉下一个最近的不同阵营元素,因此这道题的方法就是模拟\n# 最容易想到的模拟是用数组模拟,不改变长度,改变需要改变的数组元素内容,使之无效\n# 每次 ban 都是遍历数组寻找下一个不同阵营的元素\n# 更好的模拟方法可以是 1. 使用队列模拟; 2. 不断构建新字符串模拟\n# 一个��数是使用一个元素来表示整个阵营还是两个元素来分别表示;其中后者要简单些\ndef _solve(senate):\n d_minus_r, length = 0, 0\n while len(senate) != length:\n length, new_senate = len(senate), ''\n for senator in senate:\n if senator == 'D':\n if d_minus_r >= 0:\n new_senate += 'D'\n d_minus_r += 1\n else:\n if d_minus_r <= 0:\n new_senate += 'R'\n d_minus_r -= 1\n senate = new_senate\n return 'Radiant' if senate[0] == 'R' else 'Dire'\n\n\n# 代码参考自:https://discuss.leetcode.com/topic/97651/straightforward-and-simple-python\ndef _solve1(senate):\n length, party = len(senate), collections.defaultdict(collections.deque)\n for i, senator in enumerate(senate):\n party[senator].append(i)\n while party['R'] and party['D']:\n if party['R'][0] < party['D'][0]:\n party['R'].append(party['R'].popleft() + length)\n party['D'].popleft()\n else:\n party['D'].append(party['D'].popleft() + length)\n party['R'].popleft()\n return 'Radiant' if party['R'] else 'Dire'\n\n\n# 代码参考自:https://leetcode.com/articles/dota2-senate/\ndef _solve2(senate):\n queue = collections.deque()\n party, bans = [0, 0], [0, 0]\n for senator in senate:\n idx = senator == 'R'\n party[idx] += 1\n queue.append(idx)\n while all(party):\n idx = queue.popleft()\n if bans[idx]:\n bans[idx] -= 1\n party[idx] -= 1\n else:\n bans[idx ^ 1] += 1\n queue.append(idx)\n return 'Radiant' if party[1] else 'Dire'\n","sub_path":"medium/649.py","file_name":"649.py","file_ext":"py","file_size_in_byte":2282,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"599518898","text":"import requests, re\nfrom bs4 import BeautifulSoup\nr = requests.get(\"https://www.barnesandnoble.com/w/toys-games-barbie-rainbow-lights-mermaid/31093114?ean=0887961207651\").content\n\nsoup = BeautifulSoup(r, 'html.parser')\n\ntitle = soup.title\ntitleName = title.get_text()\nprint(titleName [:30])\nspan = soup.find(\"span\", id=\"pdp-cur-price\")\nprint(span.text)\ntags = soup.findAll(\"div\", {\"class\":re.compile('(text--medium overview-content)')})\nfor element in tags:\n\tprint(element.text)\n\n\n","sub_path":"webscraping/bnscrape.py","file_name":"bnscrape.py","file_ext":"py","file_size_in_byte":481,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"402807517","text":"import pygame\r\nimport random\r\n\r\npygame.init()\r\n \r\nBLACK = ( 0, 0, 0)\r\nWHITE = ( 255, 255, 255)\r\nBLUE = ( 0, 0, 255)\r\nGREEN = ( 0, 255, 0)\r\nRED = ( 255, 0, 0)\r\n \r\nclass Rectangle():\r\n x_pos = random.randint(0,700)\r\n y_pos = random.randint(0,700)\r\n height = random.randint(20,70)\r\n width = random.randint(20,70)\r\n change_x = random.randint(-3,3)\r\n change_y = random.randint(-3,3)\r\n def draw_rect(self, Screen, color):\r\n pygame.draw.rect(Screen, color, [self.x_pos, self.y_pos, self.width, self.height], 0)\r\n\r\n\r\nPI = 3.141592653\r\n \r\n\r\nsize = (700, 700)\r\nscreen = pygame.display.set_mode(size)\r\n \r\npygame.display.set_caption(\"Title\")\r\n \r\ndone = False\r\nclock = pygame.time.Clock()\r\n\r\nmyList = [] \r\nfor i in range(1, 10):\r\n i = Rectangle()\r\n myList.append(i)\r\nprint (myList)\r\n\r\nwhile not done:\r\n \r\n for event in pygame.event.get():\r\n if event.type == pygame.QUIT:\r\n done = True \r\n \r\n for item in myList:\r\n item.draw_rect(screen, RED)\r\n \r\n\r\n pygame.display.flip()\r\n \r\n \r\n\r\n clock.tick(60)\r\n \r\n \r\npygame.quit()\r\n","sub_path":"Lab 13.py","file_name":"Lab 13.py","file_ext":"py","file_size_in_byte":1122,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"259987702","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom matplotlib.animation import FuncAnimation\nimport mpl_toolkits.mplot3d.axes3d as p3\nfrom scipy import integrate\n\nG=6.67408e-11 #m^3Kg^-1s^-1 #Big G\n\"\"\"\nBelow are the default values for scales of mass, distance, velocity, as well\nas the time scale\n\"\"\"\nMass_scale = 1e24 #Kg\nDistance_scale = 1000000 #m (1e6)\nVelocity_scale = 1000 #m/s (1e3)\nTime_scale = 365.25*24*3600 #s #orbital period of earth\n\ncolours = ['r','g','b','y','pink', 'c', 'm'] #Colours used for plotting\n\ndef SetRelativeValues(mass_scale, dist_scale, vel_scale, time_scale):\n \"\"\"\n Calculates constants used by the differential equation solver based off\n the given values.\n Inputs:\n mass_scale (M)- The scale unit for mass (kg) that all object masses\n are relative to\n dist_scale (D)- The scale unit for distance (m) that all distances are\n relative to\n vel_scale (V)- The scale unit for velocity (m/s) that all velocities are\n relative to\n time_scale (T)- The time span (s) that a value of 1 in the time span\n used in scipy.integrare.odeint represents\n Outputs:\n k1 - The product (G*T*M)/(D^2 * V), constant to find dr/dt in ODE solver\n k2 - The product (V*T)/D, constant to find dv/dt\n \"\"\"\n k1 = G*time_scale*mass_scale/(dist_scale**2 * vel_scale)\n k2 = vel_scale*time_scale/dist_scale\n return k1,k2\n\ndef SetDefaultReatives():\n \"\"\"\n Calculates constants used by the differential equation solver based off\n the default values.\n Default values:\n Mass_scale = 10e23 Kg, Distance_scale = 10e5 m, Velocity_scale = 1000 m/s,\n Time_scale = 365.25*24*3600 s, 1 orbit for Earth\n Outputs:\n k1 - The product (G*T*M)/(D^2 * V), constant to find dr/dt in ODE solver\n k2 - The product (V*T)/D, constant to find dv/dt\n \"\"\"\n k1 = G*Time_scale*Mass_scale/(Distance_scale**2 * Velocity_scale)\n k2 = Velocity_scale*Time_scale/Distance_scale\n return k1,k2\nclass NBodySolver:\n def __init__(self):\n \"\"\"\n Initialises the NBodySolver\n \"\"\"\n #Set up list of bodies\n self.bodies = []\n #Set constants as default, set solved to False\n self.k1, self.k2 = SetDefaultReatives()\n self.dist_scale = Distance_scale\n self.solved=False\n\n def AddBody(self, body):\n \"\"\"\n Adds the supplied body to this solver.\n Inputs:\n Body - the body to add to this solver\n \"\"\"\n self.bodies.append(body)\n\n def AddNewBody(self, name, mass, position, velocity):\n \"\"\"\n Creates a new Body based on the given arguments, and then adds it to\n this solver.\n Inputs:\n name - The name of the body\n mass - The mass of the body relative to the Mass_scale\n position - The initial position of the body relative to Distance_scale\n velocity - The initial velocity of the body relative to Velocity_scale\n \"\"\"\n self.bodies.append(Body(name, mass, position, velocity))\n\n def SetSolverRelativeValues(self, mass_scale, dist_scale, vel_scale, time_scale):\n \"\"\"\n Calculates constants used by the differential equation solver based off\n the given values.\n Inputs:\n mass_scale (M)- The scale unit for mass (kg) that all object masses\n are relative to\n dist_scale (D)- The scale unit for distance (m) that all distances are\n relative to\n vel_scale (V)- The scale unit for velocity (m/s) that all velocities are\n relative to\n time_scale (T)- The time span (s) that a value of 1 in the time span\n used in scipy.integrare.odeint represents\n \"\"\"\n self.k1,self.k2 = SetRelativeValues(mass_scale, dist_scale, vel_scale, time_scale)\n self.dist_scale = dist_scale\n\n\n def SolveNBodyProblem(self, time_span):\n \"\"\"\n Prepairs the bodies of this solver, ready to be added to the ODE solver.\n Extracts the relevent data from the result, and saves to the object.\n Inputs:\n time_span - The time span that the simulation should be run over, a\n time span of 1 represents 1 Time_scale\n shouldCM - bool value, if true all values will be from the centre of\n mass reference frame\n \"\"\"\n self.time_span = time_span\n initial, masses = PrepairValues(self.bodies)\n self.N = len(self.bodies)\n n_body_sol = integrate.odeint(CoupledNBodyODE, initial, time_span, args=(self.k1,self.k2,self.N, [masses]))\n #Create array of just the positions of the solution\n self.bodySol = []\n for i in range(self.N):\n self.bodySol.append(n_body_sol[:,(3*i):(3*(i+1))])\n self.solved=True\n #Return both the neat solution, as well as the full solution\n def PlotNBodySolution(self, ax=None, show=True, saveFile=None, legend=True):\n if(self.solved==False):\n print(\"Solution must be found before plotting. Use NBodySolver.SolveNBodyProblem\")\n return\n\n if(ax==None):\n fig=plt.figure(figsize=(5,5))\n ax=fig.add_subplot(111,projection=\"3d\")\n #Iterate each body and extract full path for each body, then plot.\n for i in range(self.N):\n b = self.bodySol[i]\n ax.scatter(b[0,0], b[0,1], b[0,2], marker='o', color=colours[i])\n ax.plot(b[:,0],b[:,1],b[:,2],color=colours[i], label=self.bodies[i].name)\n ax.scatter(b[-1,0], b[-1,1], b[-1,2], marker='*', color=colours[i])\n\n dim = r\"m$\\times10^{\"+str(np.log10(1000000))+\"}$\"\n print(dim)\n #Add details to plot, then show\n ax.set_xlabel(\"x - \" + dim,fontsize=10)\n ax.set_ylabel(\"y - \" + dim,fontsize=10)\n ax.set_zlabel(\"z - \" + dim,fontsize=10)\n ax.set_title(\"Visualization of a 3 body system\\n\",fontsize=14)\n if(legend):\n ax.legend(loc=\"lower left\",fontsize=10)\n if(show):\n plt.show()\n if(saveFile != None):\n fig.savefig(saveFile, dpi=fig.dpi)\n def AnimateNBodySolution(self, axis_size=None):\n if(self.solved==False):\n print(\"Solution must be found before animating. Use NBodySolver.SolveNBodyProblem\")\n return\n data = []\n for i in range(self.N):\n data.append([self.bodySol[i][:,0],self.bodySol[i][:,1],self.bodySol[i][:,2]])\n #Turn to numpy array\n data = np.array(data)\n #Check if axis_size is defined. If not, define it\n if(axis_size==None):\n axis_size = np.max(self.bodySol)\n #Create 3d figure to plot on\n fig=plt.figure(figsize=(6,6))\n ax=fig.add_subplot(111,projection=\"3d\")\n #Extract data into a set of 3 dimensional lines\n lines = [ax.plot(dat[0,0:1],dat[1,0:1],dat[2,0:1], label=self.bodies[i].name)[0] for i, dat in enumerate(data)]\n for i, line in enumerate(lines):\n line.set_color(colours[i])\n\n #line.label(\"test\" + str(i))\n\n def update_lines(num, dataLines, lines):\n \"\"\"\n Update function for the animation.\n Inputs:\n num - the current iteration of the animation\n dataLines - all of the 3d position solutions of all bodies\n lines - the lines to animate\n \"\"\"\n\n #i=0\n for line, data in zip(lines, dataLines):\n #line.set_color(colours[i])\n line.set_data(data[0:2, :num])\n line.set_3d_properties(data[2, :num])\n\n #i+=1\n return lines\n ax.legend(loc=\"upper left\",fontsize=14)\n #Set up axis of plot\n ax.set_xlim3d([-axis_size,axis_size])\n ax.set_xlabel('X')\n\n ax.set_ylim3d([-axis_size,axis_size])\n ax.set_ylabel('Y')\n\n ax.set_zlim3d([-axis_size,axis_size])\n ax.set_zlabel('Z')\n #Create animation, then show to user\n line_ani = FuncAnimation(fig, update_lines, len(self.time_span), fargs=(data, lines),\n interval=0.1, blit=True, repeat=False)\n plt.show()\n\nclass Body:\n \"\"\"\n class that holds details for each body\n \"\"\"\n def __init__(self, name, mass, startPos, startVel):\n \"\"\"\n Initiates the Body with the supplied values\n Inputs:\n name - The name of the body\n mass - The mass of the body relative to the Mass_scale supplied to\n the N body solver\n startPos - Array like (3 dimensions, [x,y,z]). Position relative to\n the Distance_scale supplied to the N body solver\n startVel - Array like (3 dimensions, [v_x, v_y, v_z]). Velocity\n relative to the Velocity_Scale supplied to the N body solver.\n \"\"\"\n self.name=name\n self.mass=mass\n self.startPos=startPos\n self.startVel=startVel\n\n\ndef CoupledNBodyODE(rv, t, k1, k2, N, masses):\n \"\"\"\n Calculates the new velocity and position of each of the bodies at the given\n iteration.\n Inputs:\n rv - array like, holds position and velocity of all bodies\n t - supplied for function to work with scipy.integrate.odeint, unused\n k1 - constant calculated based on scale values, used to find velocity\n of each body\n k2 - constant calculated based on scale values, used to find acceleration\n of each body\n masses - array like, mass of each of the bodies\n shouldCM - bool value, if true all values will be from the centre of\n mass reference frame\n Outputs - flat 1d array of floats, represents position and velocity of all\n bodies. Same format as input 'rv'\n \"\"\"\n #Prepair arrays to hold positions, velocities, and position deivatives\n all_r = []\n all_v = []\n all_drdt = []\n delta_to_v = 3*N\n cm = np.array([0,0,0])\n cm_v = np.array([0,0,0])\n #Turn masses array to flat numpy array for ease\n masses = np.array(masses).flatten()\n tMass = np.sum(masses)\n #Iterate the data set and fill arrays with required values\n for i in range(N):\n\n all_r.append(rv[3*i:3*(i+1)])\n all_drdt.append(rv[(3*i+delta_to_v):(3*(i+1)+delta_to_v)]*k2)\n #Sum weighted position of each body to find COM\n cm=np.add(cm,all_drdt[i]*masses[i])\n\n cm/=tMass\n\n #Convert to numpy arrays for efficiences and ease\n all_r = np.array(all_r)\n all_v = np.array(all_v)\n all_drdt = np.array(all_drdt)\n\n #Put all positions in COM reference frame\n for i in range(N):\n all_drdt[i] -= cm\n\n #Create matrix of distances between each body\n rs = np.zeros((N,N))\n for i in range(N):\n for j in range(N):\n #Any distance r_ij for j=i is 0\n if(i==j):\n continue\n #rs_ij=rs_ji, prevents double calculations\n if(rs[j,i] != 0):\n rs[i,j] = rs[j,i]\n else:\n #Calculate distance between bodies i and j\n rs[i,j] = np.linalg.norm(all_r[j]-all_r[i])\n\n\n #Initiate velocity derivative array\n all_dvdt=[]\n #Iterate each body\n for i in range(N):\n #Initiate the velocity derivative for body i as (0,0,0), to prepair for calcualtion\n body_i_pre_mult = np.zeros(3)\n for j in range(N):\n if(j!=i):\n #Add the acceleration contribution from body j to the body i\n body_i_pre_mult += masses[j]*(all_r[j]-all_r[i])/rs[i,j]**3\n #Add total calcualted velocity change to total array\n all_dvdt.append(k1*body_i_pre_mult)\n\n #Turn to numpy arrays, concatenate, and flatten, then return to odeint\n all_dvdt = np.array(all_dvdt)\n return np.concatenate((all_drdt, all_dvdt)).flatten()\n\ndef PrepairValues(bodies):\n \"\"\"\n Takes a list of bodies and turns into a set of values to be used by the solver\n Inputs:\n bodies - array like, list Body objects\n Outputs:\n initial - array like, array of initial position and velocity of all bodies\n masses - array like, array of masses of all bodies.\n \"\"\"\n #Prepair empty lists\n masses = []\n positions = []\n velocities =[]\n #iterate each body and append relevent lists\n for body in bodies:\n masses.append(body.mass)\n positions.append(body.startPos)\n velocities.append(body.startVel)\n #Create array of initial positions and velocities, then flatten\n initial = np.array(positions+velocities)\n initial = initial.flatten()\n #Create array of masses, then return initial values and masses\n masses = np.array(masses)\n return initial, masses\n\n\n\n\"\"\"\nCode Use\nNBodyPlotter.py is designed such that the user can easily simulated any n body\nsystem, and either plot or animate.\nExample code commented out shows use of code\n\"\"\"\n\n\n# #Initialises the solver with default values\n# solver = NBodySolver()\n#\n# #Add 4 bodies to the solver with iniial starting conditions\n# solver.AddBody(Body(\"sun\",1e6, [-145000,0,0], [0,-10,0]))\n# solver.AddBody(Body(\"second_sun\",1e6,[145000, 0, 0], [0,10,0]))\n# solver.AddBody(Body(\"third_sun\", 1e6, [0,145000,0], [-10,0,0]))\n# solver.AddBody(Body(\"third_sun\", 1e6, [0,-145000,0], [10,0,0]))\n# #Define a time span of 5 solar years, with 12000 data points total\n# time_span=np.linspace(0,5,12000)\n#\n# #Solver the problem over the time span, and save to \"test.png\"\n# solver.SolveNBodyProblem(time_span)\n# solver.PlotNBodySolution(saveFile=\"test.png\")\n","sub_path":"ProjOrbits/NBodyPlotter.py","file_name":"NBodyPlotter.py","file_ext":"py","file_size_in_byte":13726,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"316534496","text":"\"\"\"\nSplitting methods and heuristics for the David Putnam solver.\n\nEach method takes a Solver instance as argument and returns a literal\nand the value to set it to.\n\"\"\"\nimport random\n\n\ndef naive_split(solver):\n \"\"\"\n Simply pick the first variable that comes up and set it to True.\n \"\"\"\n variables = [key for key, value in solver.containment.items()\n if len(value) > 0]\n literal = variables[0]\n value = True\n\n return literal, value\n\n\ndef random_split(solver):\n \"\"\"\n Pick a random literal and set it either to True or False.\n \"\"\"\n variables = [key for key, value in solver.containment.items()\n if len(value) > 0]\n literal = random.choice(variables)\n value = random.choice([True, False])\n\n return literal, value\n\n\ndef jeroslow_lang(solver):\n clauses = solver.clauses\n\n j_values = {}\n\n for literal, indices in solver.containment.items():\n print(literal, indices)\n J = sum([2 ** -len(clauses[idx]) for idx in indices])\n print(J)\n\n j_values[literal] = J\n","sub_path":"splits.py","file_name":"splits.py","file_ext":"py","file_size_in_byte":1059,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"181195276","text":"import torch.utils.data as data\n\nfrom PIL import Image\nimport os\nimport os.path\nimport numpy as np\nfrom numpy.random import randint\nimport skvideo.io\nimport cv2\nimport torch,time\nfrom ops.utils import PSP_oneVSall\nfrom log import log\n\nclass VideoRecord(object):\n def __init__(self,root_path,row):\n self._data=row\n self.root_path=root_path\n self.item='train' if self._data[0][0]=='/' else 'nontrain'\n @property\n def path(self):\n if self._data[0][0]=='/':\n return self._data[0]\n else:\n return os.path.join(self.root_path,self._data[0])\n \n @property\n def num_frames(self):\n return int(self._data[1])\n @property\n def label(self):\n return int(self._data[2])\n\n @property\n def posi_time(self):\n #return self.posi_time\n return [(int(self._data[i*2+3]),int(self._data[i*2+4])) for i in range((len(self._data)-3)/2)\\\n if int(self._data[i*2+4])<int(self._data[1])]\n\nclass MultiFrame(data.Dataset):\n def __init__(self,root_path,list_file,train_source=None,\n temporal_length=8,temporal_segs=4,\n modality='RGB',data_gap=1,data_channel=3,\n image_tmpl='img_{:05d}.jpg',\n posi_samples=3,nega_samples=0,\n posi_threshold=0.9,nega_threshold=0.1,\n transform=None,test_mode=False):\n\n self.root_path = root_path\n self.list_file = list_file\n self.data_gap=data_gap\n self.temporal_length=temporal_length\n self.temporal_segs=temporal_segs\n self.modality = modality\n self.posi_samples=posi_samples\n self.nega_samples=nega_samples\n self.posi_threshold=posi_threshold\n self.nega_threshold=nega_threshold\n self.channels=data_channel\n self.image_tmpl = image_tmpl\n self.transform = transform\n self.test_mode = test_mode\n #self.new_length = 1 if self.modality=='RGB' else 2\n self.fore_frames=(self.temporal_length*self.temporal_segs*self.data_gap-1)/2\n self.back_frames=(self.temporal_length*self.temporal_segs*self.data_gap)-self.fore_frames-1\n\n if train_source==None:\n log.l.info('No training source is chosed')\n self._set_train_source(train_source)\n self._parse_list()\n\n def _set_train_source(self,train_source):\n if len(train_source)==2:\n if train_source[0]=='train' and train_source[1]=='val':\n self.train_item=0\n else:\n if train_source[0]=='train':\n self.train_item=1\n else: # train_source[0]=='val':\n self.train_item=2\n\n def _is_from_train(self,line_list):\n if self.train_item==0 or self.test_mode:\n return True\n elif line_list[0][0]=='/' and self.train_item == 1:\n return True\n elif line_list[0][0]!='/' and self.train_item == 2:\n return True\n else:\n return False\n\n def _parse_list(self):\n self.video_list = \\\n [VideoRecord(self.root_path,x.strip().split(' ')) for x in open(self.list_file,'rb') if self._is_from_train(x.strip().split(' '))]\n if not self.test_mode:\n log.l.info('========> training source is ID-{}(tip: 0--train+val, 1--train, 2--val), all have {} files to train <========='.format(self.train_item,len(self.video_list)))\n else:\n pass # TBA\n\n def _load_image(self,record,idx=None):\n img_path=record.path\n if self.modality=='RGB':\n return [Image.open(os.path.join(img_path,self.image_tmpl.format(idx))).convert('RGB')]\n\n elif self.modality=='Flow':\n #img_path=self.video_list[idx].path\n x_img=Image.open(os.path.join(img_path,self.image_tmpl.format('x',idx))).convert('L')\n y_img=Image.open(os.path.join(img_path,self.image_tmpl.format('y',idx))).convert('L')\n\n return [x_img, y_img]\n\n\n def get(self,record,sample_indices=None):\n\n images=list()\n\n #if not self.test_mode:\n for seg_ind in sample_indices:\n p=int(seg_ind)\n # s1 = randint(p-self.fore_frames,p-self.fore_frames+self.segment_length)\n # s2 = randint(p-self.fore_frames+self.segment_length,p+back_frames-self.segment_length)\n # s3 = randint(p+back_frames-self.segment_length,p+back_frames)\n add_inds=0 # if 4*8 > num_frames\n for i in range(self.temporal_segs):\n s_= p-self.fore_frames + i * self.temporal_length * self.data_gap + 1\n e_= p-self.fore_frames + (i + 1) * self.temporal_length * self.data_gap + 1\n\n add_inds= e_-record.num_frames if e_>record.num_frames else 0 # the last segment \n\n for j in range(s_, e_, 1):\n ind=min(j-add_inds,record.num_frames)\n seg_imgs = self._load_image(record,ind)\n images.extend(seg_imgs)\n\n process_data=self.transform(images)\n # else:\n # for j in range(self.new_length):\n # seg_imgs=self._load_image(path,ind,j)\n # images.extend(seg_imgs)\n\n # process_data=self.transform(images)\n return process_data\n\n\n def _get_test_indices(self,record,data_gap):\n num_frames=record.num_frames\n posi_time=record.posi_time\n posi_frame_inds=[(_[0],_[1]) for _ in posi_time]\n if_posi_inds=np.zeros(num_frames)\n\n for i in posi_frame_inds:\n if_posi_inds[i[0]:i[1]]=1\n self.labels=[record.label if if_posi_inds[_]==1 else 0 for _ in range(1,num_frames,data_gap)]\n return range(1,num_frames,data_gap)\n\n def _check_segment_label(self,record,begin_indice):\n time_segment=(begin_indice-self.fore_frames,begin_indice+self.back_frames)\n\n if PSP_oneVSall(time_segment,record.posi_time)>self.posi_threshold:\n return 'nega'\n elif PSP_oneVSall(time_segment,record.posi_time)<self.nega_threshold:\n return 'posi'\n else:\n return 'nothing'\n\n def _get_val_indices(self,record):\n\n training_indices=[]\n training_lables=[]\n posi_num,nega_num=0,0\n c=time.time()\n while (posi_num<self.posi_samples) or (nega_num<self.nega_samples): # sample posi and nega.\n begin_indice=randint(self.fore_frames,record.num_frames-self.back_frames)\n\n if self._check_segment_label(record,begin_indice)=='posi':\n if posi_num<self.posi_samples:\n training_indices.append(begin_indice)\n training_lables.append(record.label)\n posi_num+=1\n\n elif self._check_segment_label(record,begin_indice)=='nega':\n if nega_num<self.nega_samples:\n training_indices.append(begin_indice)\n training_lables.append(0)\n nega_num+=1\n if time.time()-c>3:\n log.l.info('{} meets error when finding positive samples'.format(record.path))\n training_indices.append(record.num_frames/2)\n training_lables.append(record.label)\n posi_num+=1\n\n return np.array(training_indices),np.array(training_lables)\n\n def _get_train_indices(self,record):\n\n training_indices=[]\n training_lables=[]\n posi_num=0 # trimmed data, so no nega samples\n\n while posi_num< self.posi_samples + self.nega_samples:\n begin_indice=randint(self.fore_frames,max(self.fore_frames+1,record.num_frames-self.back_frames))\n training_indices.append(begin_indice)\n training_lables.append(record.label)\n posi_num+=1\n return np.array(training_indices), np.array(training_lables)\n\n\n def __getitem__(self,index):\n\n record=self.video_list[index]\n # if self.test_mode:\n # sample_indices = self._get_test_indices(record)\n # return self.get(record,sample_indices)\n # else:\n if record.item=='nontrain': # so extract validation frames\n sample_indices ,labels = self._get_val_indices(record)\n else:\n sample_indices ,labels = self._get_train_indices(record)\n\n assert len(sample_indices)==(self.posi_samples+self.nega_samples),\\\n 'samples not equal, dataloader error!'\n return self.get(record,sample_indices),labels\n \n # def extend_labels_segments(self,labels):\n # labels_out=[]\n # for label in labels:\n # labels_out.extend([label]*self.num_segments)\n # return np.array(labels_out)\n\n def __len__(self):\n return len(self.video_list)","sub_path":"multiframe_dataset.py","file_name":"multiframe_dataset.py","file_ext":"py","file_size_in_byte":8683,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"579242859","text":"# -*- coding: utf-8 -*-\nimport scrapy\nfrom scrapy.http import Request\nfrom lxml import etree\nfrom ..items import FacebookItem\nfrom razerdateresolution import parse_date_week_str\nimport datetime\n\n\nclass FacebookopensourcevrSpider(scrapy.Spider):\n name = 'facebookopensourcevr'\n allowed_domains = ['facebook.com']\n url = 'https://www.facebook.com/opensourcevr/'\n num = 0\n\n def start_requests(self):\n while True:\n scrollDistance = 'var h=document.documentElement.scrollTop=%d' % (self.num * 1000)\n self.num += 1\n yield Request(self.url, callback=self.parse, meta={'scrollDistance': scrollDistance},\n dont_filter=True)\n\n def parse(self, response):\n try:\n if response.status == 200:\n html = etree.HTML(response.body)\n ufilist = html.xpath('//div[@class=\"UFIList\"]')\n for ufi in ufilist:\n commenteles = ufi.xpath('./div[contains(@class, \"_3b-9\")]/div/div[@id]')\n for commentele in commenteles:\n try:\n commitem = FacebookItem()\n strdate = ''.join(\n commentele.xpath('./div/div/div/div[2]/div/div/div/div[2]/span[4]/a/abbr/@title')).strip()\n id, commitem['DateofComplaint'] = parse_date_week_str(strdate)\n commitem['FromUser'] = ''.join(commentele.xpath(\n './div/div/div/div[2]/div/div/div/div[1]/div[1]/div/span/div/span[1]/a/text()')).strip()\n commitem['CustomerFeedback'] = ''.join(commentele.xpath(\n './div/div/div/div[2]/div/div/div/div[1]/div[1]/div/span/div/span[2]/span/span/span/span/text()')).strip()\n commitem['Remarks'] = ''\n commitem['Source'] = self.url\n commitem['ID'] = ''.join([id, commitem['FromUser']])\n commitem['DateofAdd'] = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')\n yield commitem\n except:\n continue\n except:\n yield {}","sub_path":"Facebook/Facebook/spiders/facebookopensourcevr.py","file_name":"facebookopensourcevr.py","file_ext":"py","file_size_in_byte":2284,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"35429008","text":"class DebugClass:\n \"\"\"\n Clase preparada para que cualquier clase la herede\n Al activar el modo debug, las funciones de esta clase se ejecutan\n Si se tiene desactivado, pasan como si no existiesen\n \"\"\"\n __debug_mode: bool = False\n\n @property\n def _debug_mode(self) -> bool:\n return self.__debug_mode\n\n @_debug_mode.setter\n def _debug_mode(self, debug: bool):\n self.__debug_mode = debug\n\n def _print(self, something):\n \"\"\"\n Printea algo si esta en modo debug\n \"\"\"\n if self.__debug_mode:\n print(something)\n\n\nclass ControlVariables:\n \"\"\"\n Clase especializada en analizar variables basicas\n Se suele usar como control de variables para permitir o no el paso a otras funcionalidades\n \"\"\"\n # region Control de variables\n def variable_correcta(self, var: str) -> bool:\n \"\"\"\n Nos devuelve true si un string no esta vacio(len: 0) y no es None\n \"\"\"\n if var is None:\n resultado = False\n elif var.__len__() == 0:\n resultado = False\n else:\n resultado = True\n return resultado\n\n def variable_correcta_int(self, var: int) -> bool:\n \"\"\"\n Devuelve true si el numero es mayor o igual a 0 y no es None\n \"\"\"\n resultado: bool = True\n if var is None or var < 0:\n resultado = False\n return resultado\n\n def variable_correcta_list(self, var: list) -> bool:\n \"\"\"\n Usa en una lista de string la funcion variable_correcta()\n Devuelve true si todas las string contenidas son validas\n \"\"\"\n if var is None:\n resultado = False\n elif var.__len__() == 0:\n resultado = False\n else:\n resultado = True\n for i in var:\n resultado = self.variable_correcta(i)\n if resultado is False:\n break\n return resultado\n\n def variable_correcta_list_int(self, var: list) -> bool:\n \"\"\"\n Usa en una lista de ints la funcion variable_correcta_int()\n Devuelve true si todas los valores contenidos son validas\n \"\"\"\n if var is None:\n resultado = False\n elif var.__len__() == 0:\n resultado = False\n else:\n resultado = True\n for i in var:\n resultado = self.variable_correcta_int(i)\n if resultado is False:\n break\n return resultado\n\n def remove_null_from_list(self, var: list) -> int:\n \"\"\"\n Elimina de una lista de strings todos los strings no validos segun la funcion variable_correcta()\n Para eliminar los elemetos usa la funcion remove_from_list()\n Al final devuelve el numero de elementos eleiminados\n \"\"\"\n return self.remove_from_list(var, self.variable_correcta)\n\n def remove_from_list(self, var: list, func) -> int:\n \"\"\"\n Elimina todas las variables de una lista segun una funcion de comparacion\n La funcion debe de poder recibir un elemento de la lista y devolver True si es valido o false si se quiere eliminar\n Al final devuelve el numero de elementos eleiminados\n \"\"\"\n borrados: int = 0\n for i in range(0, var.__len__()):\n if type(var[i - borrados]) == str:\n if func(var[i - borrados]) is False:\n del var[i - borrados]\n borrados += 1\n return borrados\n\n def start_witn_num(self, var: str) -> bool:\n \"\"\"\n Nos devuelve True si un string recibido tiene un numero en el primer caracter\n -No comprueba si el string es un string valido o no-\n \"\"\"\n resultado: bool = False\n if self.variable_correcta(var) is True:\n if var[0].isnumeric():\n resultado = True\n return resultado\n\n def string_is_numeric(self, var: str) -> bool:\n \"\"\"\n Nos devuelve si un string es un numero o no(True o False)\n Si el string esta vacio o es None devuelve False por defecto\n \"\"\"\n resultado: bool = False\n if self.variable_correcta(var) is True:\n if var.isnumeric():\n resultado = True\n return resultado\n\n def string_is_float(self, var: str) -> bool:\n \"\"\"\n Separa un string por '.', y si ambas substring son numericas devuelve True\n Si el string no es valido devuelve False segun la funcion variable_correcta()\n **Devuelve False si posee mas de un '.'\n \"\"\"\n resultado: bool = False\n if self.variable_correcta(var) is True:\n if var.__contains__('.') is True:\n sep: list = var.split('.')\n if sep.__len__() == 2:\n if self.string_is_numeric(sep[0]) and self.string_is_numeric(sep[1]):\n resultado = True\n return resultado\n\n def contains_any(self, string: str, list_strings: list) -> int:\n \"\"\"\n Devuelve la posicion del string de la lista que esta contenido en el string\n Si el string no esta en la lista devuelve -1\n \"\"\"\n resultado: int = -1\n for i in range(0, list_strings.__len__()):\n if string.__contains__(list_strings[i]):\n resultado = i\n break\n return resultado\n\n def contains_all_list_in_dict(self, d: dict, li: list) -> bool:\n \"\"\"\n Comprueba si un diccionario contiene todas las keys nombradas en una lista\n \"\"\"\n result: bool = True\n for i in li:\n if d.__contains__(i) is False:\n result = False\n break\n return result\n\n # endregion\n","sub_path":"Herramientas/SimpleTools.py","file_name":"SimpleTools.py","file_ext":"py","file_size_in_byte":5741,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"572640549","text":"\r\nimport xml.etree.cElementTree as ET\r\n\r\nimport pypyodbc\r\n\r\nconstr = r\"Driver={SQL Server};Server=BLUE-PC\\NITIX;Database=PyXmlData;Trusted_Connection=yes;\"\r\n\r\ncnxn = pypyodbc.connect(constr)\r\n\r\ncursor = cnxn.cursor()\r\ncursor.execute('SELECT * FROM [Case] where RESPONSE is null')\r\n\r\ncols = cursor.description\r\n\r\nfor row in cursor:\r\n root = ET.Element(\"case\")\r\n caseProperties = ET.SubElement(root, \"caseProperties\")\r\n id = row[0]\r\n name = row[1]\r\n ET.SubElement(caseProperties, \"property\", name=\"URElocale\").text = row[2]\r\n ET.SubElement(caseProperties, \"property\", name=\"URErbName\").text = row[3]\r\n ET.SubElement(caseProperties, \"property\", name=\"URErbVersion\").text = row[4]\r\n\r\n cnxn1 = pypyodbc.connect(constr)\r\n cursor1 = cnxn1.cursor()\r\n cursor1.execute(\"SELECT * FROM [CaseEntity] where caseid = '%s'\" % id)\r\n cols1 = cursor1.description \r\n caseData = ET.SubElement(root, \"caseData\")\r\n \r\n for row1 in cursor1:\r\n if row1[4] is None:\r\n entity = ET.SubElement(caseData, \"entity\", type=row1[2], name=row1[3])\r\n else:\r\n entity = ET.SubElement(caseData, \"entity\", parentEntity=name, type=row1[2], name=row1[3], hasPrimaryPhysician=row1[4], lifeIdentifier=row1[5])\r\n\r\n entityid = row1[0]\r\n\r\n cnxn2 = pypyodbc.connect(constr)\r\n cursor2 = cnxn2.cursor()\r\n cursor2.execute(\"SELECT * FROM [Attribute] where flag = 1 and entityattributeid = '%s'\" % entityid)\r\n \r\n for row2 in cursor2:\r\n if row2[3] is None:\r\n ET.SubElement(entity, \"attribute\", name=row2[2])\r\n else:\r\n ET.SubElement(entity, \"attribute\", name=row2[2], value=row2[3])\r\n\r\n cursor2.execute(\"SELECT * FROM [EntityAggregate] where entityid = '%s'\" % entityid)\r\n aggregateid = 0\r\n for row3 in cursor2:\r\n aggregateid = row3[0]\r\n aggregate = ET.SubElement(entity, \"aggregate\", name=row3[2], type=row3[3])\r\n \r\n cnxn4 = pypyodbc.connect(constr)\r\n cursor4 = cnxn4.cursor()\r\n cursor4.execute(\"SELECT * FROM [Attribute] where flag = 2 and entityattributeid = '%s'\" % aggregateid)\r\n \r\n for row4 in cursor4:\r\n if row4[3] is None:\r\n ET.SubElement(aggregate, \"attribute\", name=row4[2])\r\n else:\r\n ET.SubElement(aggregate, \"attribute\", name=row4[2], value=row4[3])\r\n \r\n cursor4.execute(\"SELECT * FROM [EntityPhysician] where entityid = '%s'\" % entityid)\r\n\r\n for row5 in cursor4:\r\n physicianRef = ET.SubElement(entity, \"physicianRef\", primary=row5[2], id=row5[3])\r\n ET.SubElement(physicianRef, \"reasonForLastVisit\", code=row5[5], tc=row5[6]).text = row5[7]\r\n ET.SubElement(physicianRef, \"lastVisitMonth\").text = row5[8]\r\n ET.SubElement(physicianRef, \"lastVisitYear\").text = row5[9]\r\n \r\n cnxn4.commit()\r\n cursor4.close()\r\n cnxn4.close()\r\n\r\n cnxn2.commit()\r\n cursor2.close()\r\n cnxn2.close()\r\n\r\n cursor1.execute(\"SELECT * FROM [Physician]\")\r\n\r\n physicians = ET.SubElement(root, \"physicians\")\r\n \r\n for row6 in cursor1:\r\n physician = ET.SubElement(physicians, \"physician\", id=row6[1])\r\n ET.SubElement(physician, \"name\").text = row6[2]\r\n ET.SubElement(physician, \"addressLine1\").text = row6[3]\r\n ET.SubElement(physician, \"addressLine2\").text = row6[4]\r\n ET.SubElement(physician, \"country\", code=row6[5], tc=row6[6]).text = row6[7]\r\n ET.SubElement(physician, \"state\", code=row6[8], tc=row6[9]).text = row6[10]\r\n ET.SubElement(physician, \"city\").text = row6[11]\r\n ET.SubElement(physician, \"zip\").text = row6[12]\r\n ET.SubElement(physician, \"speciality\").text = row6[13]\r\n \r\n response = ET.tostring(root).decode()\r\n #text_file = open(\"resp.xml\", \"w\")\r\n #text_file.write(\"%s\" % response)\r\n #text_file.close()\r\n\r\n cursor1.execute(\"UPDATE [Case] SET RESPONSE='%s' WHERE id = '%s'\" % (response, id))\r\n \r\n cnxn1.commit()\r\n cursor1.close()\r\n cnxn1.close()\r\n\r\ncnxn.commit()\r\ncursor.close()\r\ncnxn.close()\r\n\r\n","sub_path":"XmlPyConsol.py","file_name":"XmlPyConsol.py","file_ext":"py","file_size_in_byte":4236,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"647148857","text":"import onmt.markdown\nimport argparse\n\n\nparser = argparse.ArgumentParser(description='plm_dict.py')\n\nonmt.markdown.add_md_help_argument(parser)\nparser.add_argument('-plm_src_vocab', required=True,\n help=\"Path to the pretrained model src vocab data\")\nparser.add_argument('-src_lang', required=True,\n help=\"src language\")\n\nparser.add_argument('-plm_tgt_vocab', required=True,\n help=\"Path to the pretrained model tgt vocab data\")\nparser.add_argument('-tgt_lang', required=True,\n help=\"tgt language\")\n\nparser.add_argument('-plm_type', default=\"bert\", type=str,\n help=\"\"\" the type of pretrained language trained model\"\"\")\n\nopt = parser.parse_args()\n\n\ndef load_vocab(vocab_file, lang):\n \"\"\"Loads a vocabulary file into a dictionary.\"\"\"\n index = 0\n vocab = open(vocab_file, \"r\")\n word2idx = open(opt.plm_type + \"_word2idx.\"+lang, \"w\")\n idx2word = open(opt.plm_type + \"_idx2word.\"+lang, \"w\")\n while True:\n word = vocab.readline()\n # the last line\n if not word:\n break\n word = word.strip()\n idx2word.write(str(index) + \" \" + word + \"\\n\")\n word2idx.write(word + \" \" + str(index) + \"\\n\")\n index += 1\n\n vocab.close()\n word2idx.close()\n idx2word.close()\n\n\nload_vocab(opt.plm_src_vocab, opt.src_lang)\nload_vocab(opt.plm_tgt_vocab, opt.tgt_lang)\n\n","sub_path":"pretrain_module/make_plm_dict.py","file_name":"make_plm_dict.py","file_ext":"py","file_size_in_byte":1413,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"592793419","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Mon Mar 9 21:21:16 2020\r\n\r\n@author: pooja\r\n\"\"\"\r\nimport torch\r\nimport torchvision\r\nimport torchvision.transforms as transforms\r\ndef transform1():\r\n trans=transforms.Compose(\r\n [transforms.RandomHorizontalFlip(), \r\n transforms.RandomRotation(10), \r\n transforms.RandomAffine(0,shear=10,scale=(0.8,1.2)), \r\n transforms.ColorJitter(brightness=0.2,contrast=0.2,saturation=0.2),\r\n transforms.ToTensor(),\r\n transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])\r\n return(trans)\r\n","sub_path":"S6/Old_s6/transform_func.py","file_name":"transform_func.py","file_ext":"py","file_size_in_byte":547,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"362099117","text":"import sys, os\n\nfrom numpy import linspace\n\nsys.path.append(\"/Users/shiftehsherafat/PycharmProjects/Test-/lib/\")\n\nfrom utils import hei\n\n\n#x = linspace()\n\nhei()\n\nutils_path = '/Users/shiftehsherafat/PycharmProjects/Test-/lib/utils.py'\n\nif not os.path.exists(utils_path):\n os.makedirs()\n print('directory exists')\n\n#print(os.path.(utils_path))\n\nfilename, file_extention = os.path.basename(utils_path).split('.')\n\nif file_extention == 'py':\n print('file is : %s' % file_extention)\n\n\nprint('filename : %s, extention: %s' % (filename, file_extention))\n\n\n\n\n# print \"Hello,world! What is the weather today? (nice/rainy))\"\n# var = sys.argv[1]\n# if IndexError:\n# response = raw_input(\"Please provide rainy/nice: \")\n#\n# if var == \"nice\":\n# print \"Then lets go outside and enjoy the weather!\"\n#\n# print \"Lets stay in an read a good book!\"\n#\n\n\n","sub_path":"hello.py","file_name":"hello.py","file_ext":"py","file_size_in_byte":882,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"381316314","text":"import tensorflow as tf\nfrom tensorflow.keras.optimizers import Adam\n\nimport pickle\nimport cv2\nimport numpy as np\n\nfrom model.SSD_model import SSD\nfrom loss.MultiBoxLoss import MultiboxLoss\n\nNUM_CLASSES = 21\nBATCH_SIZE = 2\nIMAGE_SIZE = 224\n\n# path\ncrack_pkl = './VOC/VOC2007.pkl'\nIMAGE_PATH = './VOC/images/'\n\n# .pkl에서 데이터를 불러옵니다.\ngt = pickle.load(open(crack_pkl, 'rb'))\n\n# gt의 key는 이미지 이름으로 이루어져 있습니다.\n# gt의 value_list는 이미지에 존재하는 객체 수로 이루어져 있다.\n# gt의 value는 총 24 길이로 이루어져 있는데,\n# 앞의 첫 4개 인덱스는 xmin, xmax, ymin, ymax 좌표입니다.\n# 나머지 20개는 클래스를 나타냅니다.\nkeys = sorted(gt.keys())\n\n# 학습 및 검증 데이터를 8:2로 나누도록 하겠습니다.\nnum_train = int(round(0.8 * len(keys)))\n\n# 3962\ntrain_keys = keys[:num_train]\n# 990\nval_keys = keys[num_train:]\n\nnum_val = len(val_keys)\n\n\n# 데이터셋 객체는 이미지(로드)와 레이블을 반환하도록 구성합니다.\n# 먼저, 이미지 경로와 해당 값을 리스트에 저장해두도록 하겠습니다.\nimage_dir_list = list()\nvalue_list = list()\n\nfor i in range(BATCH_SIZE):\n image_dir_list.append(train_keys[i])\n value_list.append(gt[train_keys[i]])\n\nimage_dir_list = np.array(image_dir_list)\n\nvalue_list = np.array(value_list)\n\n# ragging data.\nragged_value_list = tf.ragged.constant(value_list)\n\nimage_dir_ds = tf.data.Dataset.from_tensor_slices(image_dir_list)\nvalue_ds = tf.data.Dataset.from_tensor_slices(ragged_value_list)\n# use 8 batch size\nvalue_ds = value_ds.batch(8)\n\ndef get_imageLabel(image_dir):\n image = tf.io.read_file(IMAGE_PATH + image_dir)\n image = tf.image.decode_jpeg(image)\n image = tf.image.convert_image_dtype(image, tf.float32)\n image = tf.image.resize(image, [224, 224])\n\n return image\n\nimage_ds = image_dir_ds.map(get_imageLabel)\nimage_ds = image_ds.batch(BATCH_SIZE)\n\nimage = None\nvalue = None\n\nfor i in image_ds:\n image = i\nfor j in value_ds:\n value = j\n\n# make model\ninput_shape = (224, 224, 3)\nmodel = SSD(input_shape, num_classes = NUM_CLASSES)\n\noptimizer = Adam()\ntrain_loss = MultiboxLoss(BATCH_SIZE)\n\nwith tf.GradientTape() as tape:\n # predictions shape: (None, 938, 29)\n # value shape: (Object Number, None)\n predictions = model(image)\n loss = train_loss.comute_loss(value, predictions)\n\ngradients = tape.gradient(loss, model.trainable_variables)\noptimizer.apply_gradients(zip(gradients, model.trainable_variables))\n\nprint(loss)","sub_path":"Object Detection/SSD/cur_converting.py","file_name":"cur_converting.py","file_ext":"py","file_size_in_byte":2542,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"167338086","text":"import time\r\n\r\n#Recursion\r\ndef fib1(n):\r\n if (n <= 1):\r\n return n\r\n else:\r\n return fib1(n-1) + fib1(n-2)\r\n\r\n#Iteration\r\ndef fib2(n):\r\n f = [0] * (n+1)\r\n f[0] = 0\r\n if (n > 0):\r\n f[1] = 1\r\n for i in range(2, n+1):\r\n f[i] = f[i-1] + f[i-2]\r\n return f[n]\r\n\r\n# print('fib1')\r\n# for i in range(0,10):\r\n# print('%2d %6d ' % (i, fib1(i)))\r\n\r\n# print('fib2')\r\n# for i in range(0,10):\r\n# print('%2d %6d ' % (i, fib2(i)))\r\n\r\n# for i in range(30,36):\r\n# stime = time.time()\r\n# fib1(i)\r\n# print( '%2d %10.5f ' % (i, time.time() - stime ))\r\n\r\n# for i in range(30,36):\r\n# stime = time.time()\r\n# fib2(i)\r\n# print( '%2d %10.5f ' % (i, time.time() - stime ))\r\n\r\nn = 35\r\nstime = time.time()\r\nfib1(n)\r\nprint('fib1')\r\nprint( '%2d %10.5f ' % (n, time.time() - stime ))\r\n\r\nstime = time.time()\r\nfib2(n)\r\nprint('fib2')\r\nprint( '%2d %10.5f ' % (n, time.time() - stime ))\r\n","sub_path":"Python/2020-2_알고리즘분석/1_Algorithm/1_6_7_Fibonacci.py","file_name":"1_6_7_Fibonacci.py","file_ext":"py","file_size_in_byte":946,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"436648502","text":"import random\n\nfrom worker import caoe\nfrom worker.loop import work as loop_work\nfrom worker.coroutine import work as coroutine_work\nfrom worker.thread import work as thread_work\nfrom worker.process import work as process_work\nfrom worker.celery import work as celery_work\n\nworker_map = {\n 'loop': loop_work,\n 'coroutine': coroutine_work,\n 'thread': thread_work,\n 'process': process_work,\n 'celery': celery_work\n}\n\n# caoe.install()\n\n\nclass Worker:\n def __init__(self, mode='thread'):\n self.mode = mode\n self.worker_func = worker_map.get(self.mode, thread_work)\n\n def work(self, data, info):\n return self.worker_func(data, info)\n\n\n# async def worker_do_sth(data, info):\ndef worker_do_sth(data, info):\n i = random.randint(1, 10)\n print(data, '???/')\n # if i % 2 == 0:\n # test()\n return 'haha'\n\n\ndef test():\n raise Exception('test')\n\n\nif __name__ == '__main__':\n data = [\n 'u1', 'u2', 'u3', 'u4',\n 'u1', 'u2', 'u3', 'u4',\n 'u1', 'u2', 'u3', 'u4',\n 'u1', 'u2', 'u3', 'u4',\n 'u1', 'u2', 'u3', 'u4',\n 'u1', 'u2', 'u3', 'u4',\n 'u1', 'u2', 'u3', 'u4',\n 'u1', 'u2', 'u3', 'u4',\n 'u1', 'u2', 'u3', 'u4',\n ]\n info = {\n 'worker': 'worker.worker.worker_do_sth',\n 'chunk_size': 2\n\n }\n # worker = Worker(mode='coroutine')\n # worker = Worker(mode='loop')\n worker = Worker(mode='thread')\n # worker = Worker(mode='process')\n resp = worker.work(data, info)\n print(resp)\n","sub_path":"Python-OOP/venv/Lib/site-packages/worker/worker.py","file_name":"worker.py","file_ext":"py","file_size_in_byte":1518,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"199853026","text":"# -*- coding:utf-8 -*-\nimport json\nimport time\nfrom datetime import datetime\nfrom itertools import repeat\n\nimport requests\n\nfrom config import global_config\nfrom log import logger\nfrom muti_thread import threads\nfrom util import DEFAULT_USER_AGENT, get_random_useragent, get_local_time_stamp_13_float, datetime_to_timestamp\n\n\nclass TimeWait(object):\n def __init__(self, sleep_interval=0.5, fast_sleep_interval=0.01, fast_change_seconds=2):\n self.sleep_interval = sleep_interval\n self.fast_sleep_interval = fast_sleep_interval\n self.fast_change_seconds = fast_change_seconds\n self.jd_time_sync = JDTimeSync()\n self.timer = Timer()\n\n def start_wait_until_time(self, until_time, auto_fix=False):\n \"\"\"\n 执行wait。使用传入时间\n :param until_time: 格式例子。'2018-09-28 22:45:50.000'\n :param auto_fix: 是否自动校正时间。默认false\n :return:\n \"\"\"\n until_time_milli_sec = datetime_to_timestamp(datetime.strptime(until_time, '%Y-%m-%d %H:%M:%S.%f'))\n if auto_fix:\n # 自动将基于服务器的时间,切换到基于本地时钟的时间\n until_time_milli_sec = until_time_milli_sec - self.jd_time_sync.local_diff_server_time_microseconds()\n self.timer.start(until_time_milli_sec)\n\n\nclass Timer(object):\n\n def __init__(self, sleep_interval=0.5, fast_sleep_interval=0.01, fast_change_seconds=2):\n\n self.sleep_interval = sleep_interval\n self.fast_sleep_interval = fast_sleep_interval\n self.fast_change_seconds = fast_change_seconds\n\n def start(self, trigger_time):\n \"\"\"\n trigger_time : millisecond 毫秒 时间戳\n \"\"\"\n logger.info('Timer loop …… util:%s' % trigger_time)\n fast_change_time = trigger_time - self.fast_change_seconds * 1000\n\n for _ in repeat(None):\n local_time_stamp_13_float = get_local_time_stamp_13_float()\n\n if local_time_stamp_13_float >= trigger_time:\n logger.info('Timer triggered %s', trigger_time)\n break\n else:\n if local_time_stamp_13_float >= fast_change_time:\n time.sleep(self.fast_sleep_interval)\n else:\n time.sleep(self.sleep_interval)\n\n\nclass JDTimeSync(object):\n\n def __init__(self):\n use_random_ua = global_config.getboolean('config', 'random_useragent')\n self.user_agent = DEFAULT_USER_AGENT if not use_random_ua else get_random_useragent()\n\n def local_diff_server_time_microseconds(self):\n # 获取 本地时间 (减去) 京东服务器时间 的差值\n\n min_diff = 1000000000000000 # 注意:abs比较,所以默认设置一个非常大的,不能设置为0\n # 循环次数,为4-1,=3次\n for sync_count in range(1, 4):\n # 多次获得差值,取最小值\n try:\n jd_server_timestamp_13 = self.get_jd_server_timestamp_13()\n local_time_stamp_13_float = get_local_time_stamp_13_float()\n # 注意:本地时间 (减去) 京东服务器时间\n diff_jd_server_time = local_time_stamp_13_float - jd_server_timestamp_13\n # print(diff_jd_server_time) # 有点疑惑,为什么第一次的总是最快的//todo ?????\n logger.info(\"diff %s\", diff_jd_server_time)\n if abs(diff_jd_server_time) < abs(min_diff):\n min_diff = diff_jd_server_time\n except Exception as e:\n # 如果出现异常,很可能说明结果已经不可信了。再次请求还是不可信,直接返回个默认的\n min_diff = 0\n logger.warn(\"获取京东时间异常 %s,直接认为0差距\", e)\n return min_diff\n\n time.sleep(0.5)\n\n return min_diff\n\n @threads(2)\n def get_jd_server_timestamp_13(self):\n url = 'https://a.jd.com//ajax/queryServerData.html'\n headers = {\n 'User-Agent': self.user_agent\n }\n session = requests.session()\n session.keep_alive = False\n\n response = session.get(url, headers=headers)\n http_delay_millisecond = response.elapsed.microseconds / 1000\n\n response_parse_start = get_local_time_stamp_13_float()\n js = json.loads(response.text)\n # {\"serverTime\":160 745 692 0037}\n jd_server_timestamp_13 = float(js[\"serverTime\"])\n response_parse_end = get_local_time_stamp_13_float()\n\n parse_time = (response_parse_end - response_parse_start)\n\n return jd_server_timestamp_13 + parse_time + http_delay_millisecond\n\n def get_http_delay_microseconds(self):\n url = 'https://a.jd.com//ajax/queryServerData.html'\n http_delay_microseconds = 50\n headers = {\n 'User-Agent': self.user_agent\n }\n try:\n http_delay_microseconds = requests.get(url, headers=headers).elapsed.microseconds / 1000\n except Exception as e:\n logger.warn(\"测试网络延迟 异常,返回默认延迟 %s %s\", http_delay_microseconds, e)\n return http_delay_microseconds\n\n\nif __name__ == '__main__':\n JDTimeSync().local_diff_server_time_microseconds()\n # TimeWait().start_wait_until_time('2020-12-11 10:00:00.000', auto_fix=True)\n","sub_path":"gun.py","file_name":"gun.py","file_ext":"py","file_size_in_byte":5373,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"11894356","text":"#!/usr/bin/env python\n\nimport cv2 as cv\nimport numpy as np\n#from skimage.feature import hog\n\nSZ=20\nbin_n = 16 # Number of bins\n\n\naffine_flags = cv.WARP_INVERSE_MAP|cv.INTER_LINEAR\nchuso = [\"hai\",\"ba\",\"bon\",\"nam\",\"sau\",\"bay\",\"tam\",\"chin\",\"muoi\",\"nam\"]\n\n\n## [hog]\ndef hog(img):\n gx = cv.Sobel(img, cv.CV_32F, 1, 0)\n gy = cv.Sobel(img, cv.CV_32F, 0, 1)\n mag, ang = cv.cartToPolar(gx, gy)\n bins = np.int32(bin_n*ang/(2*np.pi)) # quantizing binvalues in (0...16)\n bin_cells = bins[:10,:10], bins[10:,:10], bins[:10,10:], bins[10:,10:]\n mag_cells = mag[:10,:10], mag[10:,:10], mag[:10,10:], mag[10:,10:]\n hists = [np.bincount(b.ravel(), m.ravel(), bin_n) for b, m in zip(bin_cells, mag_cells)]\n hist = np.hstack(hists) # hist is a 64 bit vector\n return hist\n## [hog]\ndef recognition(img):\n if img.shape[0] <= 0 or img.shape[1] <= 0:\n return \"\"\n svm = cv.ml.SVM_create()\n svm.setKernel(cv.ml.SVM_LINEAR)\n svm.setType(cv.ml.SVM_C_SVC)\n svm.setC(2.67)\n svm.setGamma(5.383)\n \n svm = cv.ml.SVM_load('DiemChu/svm_data.dat')\n# svm = cv.ml.SVM_load('svm_data.dat')\n #print img.shape\n #cv.imshow(\"ss\",img)\n #cv.waitKey(0)\n \n roi = cv.resize(img, (56, 28), interpolation=cv.INTER_AREA)\n fd = hog(roi)\n testData = np.float32(fd).reshape(-1,bin_n*4)\n nbr = svm.predict(testData)[1]\n return chuso[int(nbr[0][0])]\n\n#print recognition(cv.imread(\"q.png\"))\n","sub_path":"DemoNhanDangChuViet/DemoNhanDangChuViet/Python_Master/DiemChu/RecognitionDiemChu.py","file_name":"RecognitionDiemChu.py","file_ext":"py","file_size_in_byte":1429,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"33968959","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\nimport django.db.models.deletion\nimport django_extensions.db.fields.json\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('nsot', '0035_fix_interface_name_slug'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Iterable',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('_attributes_cache', django_extensions.db.fields.json.JSONField(help_text='Local cache of attributes. (Internal use only)', blank=True)),\n ('name', models.CharField(help_text='The name of the Iterable.', max_length=255, db_index=True)),\n ('description', models.TextField(default='', help_text='A helpful description for the Iterable.', blank=True)),\n ('min_val', models.PositiveIntegerField(default=1, help_text='The minimum value of the Iterable.')),\n ('max_val', models.PositiveIntegerField(default=100, help_text='The maximum value of the Iterable.')),\n ('increment', models.PositiveIntegerField(default=1, help_text='Value to increment the Iterable.')),\n ('is_resource', models.BooleanField(default=False, help_text='Will this resource have children', db_index=True)),\n ('value', models.IntegerField(help_text='Current Value of Iterable', null=True)),\n ('parent', models.ForeignKey(related_name='children', on_delete=django.db.models.deletion.PROTECT, default=None, blank=True, to='nsot.Iterable', help_text='The parent DynamicResouce', null=True)),\n ('site', models.ForeignKey(related_name='iterable', on_delete=django.db.models.deletion.PROTECT, verbose_name='Site', to='nsot.Site', help_text='Unique ID of the Site assigned to this Iterable')),\n ],\n ),\n migrations.AlterField(\n model_name='attribute',\n name='resource_name',\n field=models.CharField(help_text='The name of the Resource to which this Attribute is bound.', max_length=20, verbose_name='Resource Name', db_index=True, choices=[('Device', 'Device'), ('Interface', 'Interface'), ('Iterable', 'Iterable'), ('Network', 'Network'), ('Circuit', 'Circuit')]),\n ),\n migrations.AlterField(\n model_name='network',\n name='is_ip',\n field=models.BooleanField(default=False, help_text='Whether the Network is a host address or not.', db_index=True, editable=False),\n ),\n migrations.AlterUniqueTogether(\n name='iterable',\n unique_together=set([('site', 'name', 'value', 'parent')]),\n ),\n migrations.AlterIndexTogether(\n name='iterable',\n index_together=set([('site', 'name', 'value', 'parent')]),\n ),\n ]\n","sub_path":"nsot/migrations/0036_auto_20171006_0118.py","file_name":"0036_auto_20171006_0118.py","file_ext":"py","file_size_in_byte":2913,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"571786065","text":"#For Google Collab\n#try:\n# # %tensorflow_version only exists in Colab.\n# %tensorflow_version 2.x\n#except Exception:\n# pass\n\nimport tensorflow as tf\nimport numpy as np\n\nprint(\"--Get data--\")\nmnist = tf.keras.datasets.mnist\n(x_train, y_train), (x_test, y_test) = mnist.load_data()\nprint(\"--Process data--\")\nprint(len(y_train))\n# Normalize\nx_train, x_test = x_train / 255.0, x_test / 255.0\n\nprint(\"--Make model--\")\nmodel = tf.keras.models.Sequential([\n tf.keras.layers.Flatten(input_shape=(28, 28)),\n tf.keras.layers.Dense(128, activation='relu'),\n tf.keras.layers.Dropout(0.2),\n tf.keras.layers.Dense(10, activation='softmax'),\n])\n\n\nmodel.compile(optimizer='adam',\n loss='sparse_categorical_crossentropy', metrics=['accuracy'])\nprint(\"--Fit model--\")\nmodel.fit(x_train, y_train, epochs=10, verbose=2)\nmodel.save('MNIST.h5')\nprint(\"--Evaluate model--\")\nmodel_loss, model_acc = model.evaluate(x_test, y_test, verbose=2)\nprint(f\"Model Loss: {model_loss:.2f}\")\nprint(f\"Model Accuray: {model_acc*100:.1f}%\")\n","sub_path":"MNISTModel.py","file_name":"MNISTModel.py","file_ext":"py","file_size_in_byte":1033,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"395486039","text":"import numpy as np\r\nimport pandas as pd\r\ndef load_dat_file(file_path: str,\r\n sep: str = '\\t',\r\n header: str = None,\r\n names: str = None,\r\n engine: str = 'python',\r\n ):\r\n data = pd.read_table(file_path, sep=sep, header=header, engine=engine)\r\n return data\r\n\r\nif __name__ == '__main__':\r\n file_path = 'F:\\OneDrive\\Program\\LaTeX\\pgfplots_1.16.tds\\doc\\latex\\pgfplots\\pgfplots.doc.src\\plotdata\\pgfplots_scatterdata4.dat'\r\n data = load_dat_file(file_path)","sub_path":"Others/DatFile.py","file_name":"DatFile.py","file_ext":"py","file_size_in_byte":546,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"602454952","text":"import math\nimport time\nimport pandas as pd\nimport os\nimport numpy as np\nimport xlsxwriter\nimport math\n\n\ndef pd_toexcel(data, filename): # pandas库储存数据到excel\n dfData = { # 用字典设置DataFrame所需数据\n '图号-孔数': data[0],\n '标签内容': data[1],\n '长*宽=数量': data[2]\n }\n # if not os.path.exists(filename):\n # os.mkdir(filename)\n df = pd.DataFrame(dfData) # 创建DataFrame\n df.to_excel(filename, index=False) # 存表,去除原始索引列(0,1,2...)\n\n\nclass change_table():\n pass\n\n\nclass ResultTable():\n pass\n\n\nclass CaculateTable():\n def __init__(self, file_path):\n self.data = extract_data(file_path)\n self.length_data = len(self.data[0])\n # self.data[2] = [\" \" if math.isnan(self.data[2][i]) else str(self.data[2][i]) for i in range(self.length_data)]\n # self.data[3] = [\" \" if math.isnan(self.data[3][i]) else str(self.data[3][i]) for i in range(self.length_data)]\n # self.file_path = file_path\n self.small_kong, self.big_kong, self.small_corner, self.big_corner = cal_kong_angle(self.data)\n self.single_price = [150 if i != \" \" else 100 for i in self.data[8]]\n self.total_price = [0 for i in range(self.length_data)]\n self.title = ['序', '长边尺', '宽边尺', 'A', 'B', '图号', '数量', '孔', '大孔', '小孔', '标签内容', '备注', '单价', '单位面积', '除加工费价格',\n '单件小圆角个数',\n '单件大圆角个数', '总价']\n self.sequence_number = [i + 1 for i in range(self.length_data)]\n\n # dfData = { # 用字典设置DataFrame所需数据\n # '序': self.sequence_number,\n # '长边尺': data[0],\n # '宽边尺': data[1],\n # 'A': data[2],\n # 'B': data[3],\n # '图号': data[4],\n # '数量': data[5],\n # '孔': data[6],\n # '大孔': self.big_kong,\n # '小孔': self.small_kong,\n # '标签内容': data[7],\n # '备注': data[8],\n # '单价': self.single_price,\n # '单件小圆角个数': self.small_corner,\n # '单件大圆角个数': self.big_corner,\n # '总价': self.total_price\n # }\n # if not os.path.exists(filename):\n # os.mkdir(filename)\n # df = pd.DataFrame(dfData) # 创建DataFrame\n # df.to_excel(self.file_path, index=False) # 存表,去除原始索引列(0,1,2...)\n\n def write_with_formula(self, file_name):\n random_list = [0 for i in range(self.length_data)] # 填充空位\n data = [(self.sequence_number[i], self.data[0][i], self.data[1][i], self.data[2][i], self.data[3][i],\n self.data[4][i], self.data[5][i], self.data[6][i], self.big_kong[i], self.small_kong[i],\n self.data[7][i],\n self.data[8][i], self.single_price[i], random_list[i],\n random_list[i], self.small_corner[i], self.big_corner[i], self.total_price[i])\n for i\n in range(self.length_data)] # 数据转成一行一行的,方便写入\n\n # print(data)\n workbook = xlsxwriter.Workbook(file_name)\n worksheet = workbook.add_worksheet(\"Sheet1\")\n worksheet.write_row(0, 0, self.title) # 写入title\n for row in range(1, self.length_data + 1):\n worksheet.write_row(row, 0, data[row - 1])\n formula_area = \"if(B{}*C{}/1000000<=0.1, 0.1, B{}*C{}/1000000)\".format(row + 1, row + 1, row + 1,\n row + 1) # 面积公式\n formula_price1 = \"=M{}*N{}*G{}\".format(row + 1, row + 1, row + 1)\n formula_price_all = \"=round(O{}+(J{}+5*I{}+0.5*P{}+Q{})*G{},2)\".format(row + 1, row + 1, row + 1, row + 1,\n row + 1, row + 1)\n # print(formula_x)\n worksheet.write_formula(row, 13, formula_area) # 写入面积\n worksheet.write_formula(row, 14, formula_price1) # 写入除加工费价格\n worksheet.write_formula(row, 17, formula_price_all) # 写入总价\n workbook.close()\n\n\ndef cal_kong_angle(data):\n \"\"\"\n 计算大孔、小孔、大小圆角数量\n :param data:\n :return:\n \"\"\"\n little_kong = []\n for i in data[6]:\n # print(int(i))\n if i == ' ':\n little_kong.append(0)\n elif int(i) == 17:\n little_kong.append(19)\n elif int(i) == 13:\n little_kong.append(10)\n else:\n little_kong.append(int(i))\n\n big_kong = []\n for i in data[6]:\n # print(int(i))\n if i == ' ':\n big_kong.append(0)\n elif int(i) == 17:\n big_kong.append(8)\n elif int(i) == 13:\n big_kong.append(3)\n else:\n big_kong.append(int(i))\n\n big_corner = [0 for x in range(len(data[0]))]\n small_corner = [4 for x in range(len(data[0]))]\n\n return little_kong, big_kong, small_corner, big_corner\n\n\ndef change_origin(data, filename):\n \"\"\"\n 修改原始表格\n :param data:\n :param filename:\n :return:\n \"\"\"\n sequence_number = [i + 1 for i in range(len(data[0]))]\n dfData = { # 用字典设置DataFrame所需数据\n '序': sequence_number,\n '长边尺': data[0],\n '宽边尺': data[1],\n 'A': data[2],\n 'B': data[3],\n '图号': data[4],\n '数量': data[5],\n '孔': data[6],\n '标签内容': data[7],\n '备注': data[8]\n }\n # if not os.path.exists(filename):\n # os.mkdir(filename)\n df = pd.DataFrame(dfData) # 创建DataFrame\n df.to_excel(filename, index=False) # 存表,去除原始索引列(0,1,2...)\n\n\ndef extract_data(file):\n \"\"\"\n 提取表格里面的数据,只处理空值\n :param file:\n :return:\n \"\"\"\n if pd.read_excel(file, header=None)[0][0] != \"序号\": # 如果没有表头则从第一行读取\n df = pd.read_excel(file, header=None)\n else: # 有表头\n df = pd.read_excel(file)\n\n data_length = df.iloc[:, 1].values # 长\n data_width = df.iloc[:, 2].values # 宽\n try: # 如果这一列均为空\n data_A = df.iloc[:, 3].values.tolist() # A\n except IndexError as e:\n data_A = ['' for i in range(len(data_length))]\n\n try: # 如果这一列均为空\n data_B = df.iloc[:, 4].values.tolist() # B\n except IndexError as e:\n data_B = ['' for i in range(len(data_length))]\n\n try: # 如果这一列均为空\n data_id = df.iloc[:, 5].values.tolist() # 图号, 5 代表位于第6列\n except IndexError as e:\n data_id = [' ' for i in range(len(data_length))]\n\n try:\n data_kong_count = df.iloc[:, 7].values # 孔数量\n except IndexError as e:\n data_kong_count = [0 for i in range(len(data_length))]\n\n data_kong_count = [\"%.0f\" % i for i in data_kong_count] # 转成字符串,没小数点\n\n data_count = df.iloc[:, 6].values # 数量\n try:\n data_label = df.iloc[:, 8].values # 标签内容\n except IndexError as e:\n data_label = [0 for i in range(len(data_length))]\n\n try:\n data_remark = df.iloc[:, 9].values # 备注\n except IndexError as e:\n data_remark = [' ' for i in range(len(data_length))]\n\n data_remark = [str(i) for i in data_remark] # 转成字符串,没小数点\n for i in range(len(data_id)):\n # 判断空值\n # if math.isnan(data_kong_count[i]):\n if data_kong_count[i] == \"nan\":\n data_kong_count[i] = \" \"\n # if math.isnan(data_remark[i]):\n if data_remark[i] == \"nan\":\n data_remark[i] = \" \"\n if math.isnan(data_A[i]): # todo 有bug\n data_A[i] = \" \"\n if math.isnan(data_B[i]):\n data_B[i] = \" \"\n if data_label[i] == \"nan\":\n data_label[i] = \" \"\n if str(data_id[i]) == \"nan\":\n data_id[i] = \" \"\n\n # 返回提取出的所有数据,不做任何处理\n return [data_length, data_width, data_A, data_B, data_id, data_count, data_kong_count, data_label, data_remark]\n\n\ndef get_data_for_result(data):\n \"\"\"\n 将提取出的数据用于-->结果\n :param file: 文件路径\n :return:\n \"\"\"\n flag_change = [0 for i in range(len(data[0]))]\n for i in range(len(data[4])):\n # 去掉 THBL\n if \"THBL-\" in data[4][i]:\n data[4][i] = data[4][i].split(\"THBL-\")[-1]\n\n # 交换长宽值\n if data[1][i] > data[0][i]:\n flag_change[i] = 1\n data[1][i], data[0][i] = data[0][i], data[1][i]\n\n data = sort_data(data)\n\n data_length = data[0] # 长\n data_width = data[1] # 宽\n data_A = data[2] # A\n data_B = data[3] # B\n data_id = data[4] # 图号, 5 代表位于第6列\n data_count = data[5] # 数量\n data_kong_count = data[6] # 孔数量\n data_label = data[7] # 标签内容\n data_remark = data[8] # 备注\n\n result = []\n data_0 = [str(data_id[i]) + \"-\" + data_kong_count[i] + data_remark[i] for i in range(len(data_id))]\n # print(\"data_0\", data_0)\n result.append(data_0)\n result.append(data_label)\n data_2 = [(str(data_length[i]) + \"×\" + str(data_width[i]) + \"=\" + str(data_count[i])) if flag_change[i] else (\n str(data_length[i]) + \"*\" + str(data_width[i]) + \"=\" + str(data_count[i])) for i in\n range(len(data_count))]\n result.append(data_2)\n\n return result\n\n\ndef get_data_for_change(data):\n \"\"\"\n 画孔的单\n 交换长宽->调整原来的表格\n :param data:\n :return:\n \"\"\"\n flag_change = [0 for i in range(len(data[0]))]\n data_length = []\n data_width = []\n for i in range(len(data[4])):\n # 交换长宽值\n if data[1][i] > data[0][i]:\n data_length.append('×' + str(data[1][i]))\n data_width.append(data[0][i])\n data[1][i], data[0][i] = data[0][i], data[1][i]\n else:\n data_length.append(data[0][i])\n data_width.append(data[1][i])\n return sort_data(data, data_length, data_width)\n\n\ndef sort_data(data, data_length=None, data_width=None):\n \"\"\"\n 交换数据顺序\n :param data:\n :return:\n \"\"\"\n change_data = [(data[0][i], i) for i in range(len(data[0]))] # 用于确认交换位置\n change_data = np.array(change_data)\n change_data = change_data[np.lexsort(change_data[:, ::-1].T)] # 第一列正序\n change_data = change_data[::-1]\n\n index_data = [i[1] for i in change_data] # 数据的序号\n data[0] = [i[0] for i in change_data]\n data[1] = [data[1][i] for i in index_data]\n data[2] = [data[2][i] for i in index_data]\n data[3] = [data[3][i] for i in index_data]\n data[4] = [data[4][i] for i in index_data]\n data[5] = [data[5][i] for i in index_data]\n data[6] = [data[6][i] for i in index_data]\n data[7] = [data[7][i] for i in index_data]\n data[8] = [data[8][i] for i in index_data]\n\n if data_width and data_length:\n data_width = [data_width[i] for i in index_data]\n data_length = [data_length[i] for i in index_data]\n data[0] = data_length\n data[1] = data_width\n return data\n\n\nif __name__ == '__main__':\n print(\"把要处理的文件放在订单这个文件夹里面,结果存在结果文件夹里面\")\n if not os.path.exists('./输入订单'):\n os.mkdir('./输入订单')\n if not os.path.exists('./输出结果'):\n os.mkdir('./输出结果')\n if not os.path.exists('./画孔的单'):\n os.mkdir('./画孔的单')\n if not os.path.exists('./算价格的单'):\n os.mkdir('./算价格的单')\n\n file_list = os.listdir(\"./输入订单\")\n files_path = [os.path.join(\"./输入订单\", i) for i in file_list]\n result_path = os.getcwd() + \"/输出结果/\"\n files_save_path = [os.path.join(\"./输出结果\", i[:9] + '-标签.' + i.split('.')[-1]) for i in file_list]\n files_change_path = [os.path.join(\"./画孔的单\", i[:9] + '-画孔.' + i.split('.')[-1]) for i in file_list]\n files_cal_path = [os.path.join(\"./算价格的单\", i[:9] + '-计算价格.' + i.split('.')[-1]) for i in file_list]\n\n for i in range(len(files_path)):\n print(\"正在处理:\", file_list[i])\n data = extract_data(files_path[i])\n data_bak = extract_data(files_path[i])\n pd_toexcel(get_data_for_result(data), files_save_path[i])\n change_origin(get_data_for_change(data_bak), files_change_path[i])\n test = CaculateTable(files_path[i])\n test.write_with_formula(files_cal_path[i])\n print(\"三秒后自动退出\")\n print(\"处理完成!\")\n time.sleep(3)\n","sub_path":"excel.py","file_name":"excel.py","file_ext":"py","file_size_in_byte":12844,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"43719971","text":"import pandas as pd\nimport numpy as np\n\n\ndef prepare(df):\n df['visit_datetime'] = pd.to_datetime(df['visit_datetime'])\n df['visit_date'] = df['visit_datetime'].dt.date\n df[\"dow\"] = df[\"visit_datetime\"].dt.dayofweek\n df['reserve_datetime'] = pd.to_datetime(df['reserve_datetime'])\n df['reserve_date'] = df['reserve_datetime'].dt.date\n df['reserve_datetime_diff'] = df.apply(lambda r: (r['visit_date'] - r['reserve_date']).days, axis=1)\n return df\n\n\ndef get_dow_reserve_sum(df):\n if df[\"dow\"] == 0:\n return df[\"sum2\"]\n elif df[\"dow\"] == 1:\n return df[\"sum3\"]\n elif df[\"dow\"] == 2:\n return df[\"sum4\"]\n elif df[\"dow\"] == 3:\n return df[\"sum5\"]\n elif df[\"dow\"] == 4:\n return df[\"sum6\"]\n else:\n return df[\"sum1\"]\n \n \ndef get_dow_reserve_mean(df):\n if df[\"dow\"] == 0:\n return df[\"mean2\"]\n elif df[\"dow\"] == 1:\n return df[\"mean3\"]\n elif df[\"dow\"] == 2:\n return df[\"mean4\"]\n elif df[\"dow\"] == 3:\n return df[\"mean5\"]\n elif df[\"dow\"] == 4:\n return df[\"mean6\"]\n else:\n return df[\"mean1\"]\n \n\ndef feature(df):\n df[\"reserve_datediff\"] = np.where(df[\"reserve_datetime_diff\"] >= 7, 7, df[\"reserve_datetime_diff\"])\n df1 = df[df[\"reserve_datediff\"] >= 1]\n df2 = df[df[\"reserve_datediff\"] >= 2]\n df3 = df[df[\"reserve_datediff\"] >= 3]\n df4 = df[df[\"reserve_datediff\"] >= 4]\n df5 = df[df[\"reserve_datediff\"] >= 5]\n df6 = df[df[\"reserve_datediff\"] >= 6]\n df7 = df[df[\"reserve_datediff\"] >= 7]\n\n temp1 = df1.groupby([\"air_store_id\", \"visit_date\"])[\"reserve_visitors\"].agg({np.mean, np.sum}).reset_index()\n temp1.columns = [\"air_store_id\", \"visit_date\", \"mean1\", \"sum1\"]\n temp2 = df2.groupby([\"air_store_id\", \"visit_date\"])[\"reserve_visitors\"].agg({np.mean, np.sum}).reset_index()\n temp2.columns = [\"air_store_id\", \"visit_date\", \"mean2\", \"sum2\"]\n temp3 = df3.groupby([\"air_store_id\", \"visit_date\"])[\"reserve_visitors\"].agg({np.mean, np.sum}).reset_index()\n temp3.columns = [\"air_store_id\", \"visit_date\", \"mean3\", \"sum3\"]\n temp4 = df4.groupby([\"air_store_id\", \"visit_date\"])[\"reserve_visitors\"].agg({np.mean, np.sum}).reset_index()\n temp4.columns = [\"air_store_id\", \"visit_date\", \"mean4\", \"sum4\"]\n temp5 = df5.groupby([\"air_store_id\", \"visit_date\"])[\"reserve_visitors\"].agg({np.mean, np.sum}).reset_index()\n temp5.columns = [\"air_store_id\", \"visit_date\", \"mean5\", \"sum5\"]\n temp6 = df6.groupby([\"air_store_id\", \"visit_date\"])[\"reserve_visitors\"].agg({np.mean, np.sum}).reset_index()\n temp6.columns = [\"air_store_id\", \"visit_date\", \"mean6\", \"sum6\"]\n temp7 = df7.groupby([\"air_store_id\", \"visit_date\"])[\"reserve_visitors\"].agg({np.mean, np.sum}).reset_index()\n temp7.columns = [\"air_store_id\", \"visit_date\", \"mean7\", \"sum7\"]\n\n df = pd.merge(temp1, temp2, on=[\"air_store_id\", \"visit_date\"], how=\"left\")\n df = pd.merge(df, temp3, on=[\"air_store_id\", \"visit_date\"], how=\"left\")\n df = pd.merge(df, temp4, on=[\"air_store_id\", \"visit_date\"], how=\"left\")\n df = pd.merge(df, temp5, on=[\"air_store_id\", \"visit_date\"], how=\"left\")\n df = pd.merge(df, temp6, on=[\"air_store_id\", \"visit_date\"], how=\"left\")\n df = pd.merge(df, temp7, on=[\"air_store_id\", \"visit_date\"], how=\"left\")\n df[\"datetime\"] = pd.to_datetime(df['visit_date'])\n df[\"dow\"] = df[\"datetime\"].dt.dayofweek\n df[\"visit_date\"] = df[\"visit_date\"].apply(lambda x: x.strftime('%Y-%m-%d'))\n\n df[\"dow_reserve_sum\"] = df.apply(get_dow_reserve_sum, axis=1)\n df[\"dow_reserve_mean\"] = df.apply(get_dow_reserve_mean, axis=1)\n # print(df.head(10))\n\n return df\n\n\ndef calc_ewm(series, alpha, adjust=True):\n return series.ewm(alpha=alpha, adjust=adjust).mean()\n\n\ndef get_ewm_reserve(df):\n grouped = df.groupby([\"air_store_num\", \"dows\"])[\"sum1_air\"]\n df[\"ewm_sum1_air\"] = grouped.transform(lambda g: calc_ewm(g, 0.1).shift(1))\n grouped = df.groupby([\"air_store_num\", \"dows\"])[\"sum1_hpg\"]\n df[\"ewm_sum1_hpg\"] = grouped.transform(lambda g: calc_ewm(g, 0.1).shift(1))\n grouped = df.groupby([\"air_store_num\", \"dows\"])[\"mean1_air\"]\n df[\"ewm_mean1_air\"] = grouped.transform(lambda g: calc_ewm(g, 0.1).shift(1))\n grouped = df.groupby([\"air_store_num\", \"dows\"])[\"mean1_hpg\"]\n df[\"ewm_mean1_hpg\"] = grouped.transform(lambda g: calc_ewm(g, 0.1).shift(1))\n grouped = df.groupby([\"air_store_num\", \"dows\"])[\"total_reserve1\"]\n df[\"ewm_sum1_tot\"] = grouped.transform(lambda g: calc_ewm(g, 0.1).shift(1))\n return df\n\n\ndef get_total_info(df):\n df[\"total_reserve1\"] = df[\"sum1_air\"] + df[\"sum1_hpg\"]\n df[\"total_reserve7\"] = df[\"sum7_air\"] + df[\"sum7_hpg\"]\n return df\n\n\nair_reserve_df = pd.read_csv('../input/air_reserve.csv')\nhpg_reserve_df = pd.read_csv('../input/hpg_reserve.csv')\nrelation_df = pd.read_csv('../input/store_id_relation.csv')\ntrain = pd.read_csv('../output/cws_train.csv')\npredict = pd.read_csv('../output/cws_predict.csv')\nprint(\"Loaded data.\")\nhpg_reserve_df = pd.merge(hpg_reserve_df, relation_df, how='inner', on=['hpg_store_id'])\n# air_reserve_df = air_reserve_df[air_reserve_df[\"air_store_id\"] == \"air_6b15edd1b4fbb96a\"]\n# hpg_reserve_df = hpg_reserve_df[hpg_reserve_df[\"air_store_id\"] == \"air_6b15edd1b4fbb96a\"]\n# print(air_reserve_df.head())\n\nair_reserve_df = prepare(air_reserve_df)\nhpg_reserve_df = prepare(hpg_reserve_df)\nair_reserve_df = feature(air_reserve_df)\nhpg_reserve_df = feature(hpg_reserve_df)\nprint(\"Done reserve engineer\")\n\n# print(air_reserve_df.describe())\n# print(hpg_reserve_df.describe())\nuse_col = [\"air_store_id\", \"visit_date\", \"dow_reserve_sum\", \"dow_reserve_mean\",\n \"sum1\", \"mean1\", \"sum7\", \"mean7\"]\nair_reserve_df = air_reserve_df[use_col]\nhpg_reserve_df = hpg_reserve_df[use_col]\nair_reserve_df.columns = [\"air_store_id\", \"visit_date\", \"dow_reserve_sum_air\", \"dow_reserve_mean_air\", \n \"sum1_air\", \"mean1_air\", \"sum7_air\", \"mean7_air\"]\nhpg_reserve_df.columns = [\"air_store_id\", \"visit_date\", \"dow_reserve_sum_hpg\", \"dow_reserve_mean_hpg\",\n \"sum1_hpg\", \"mean1_hpg\", \"sum7_hpg\", \"mean7_hpg\"]\nair_reserve_df.fillna(0)\nhpg_reserve_df.fillna(0)\n# print(air_reserve_df.head())\n\njoined = pd.concat([train, predict])\n# joined = joined[joined[\"air_store_id\"] == \"air_6b15edd1b4fbb96a\"]\n\n# joined[\"visit_datetime\"] = pd.to_datetime(joined[\"visit_date\"])\n# joined[\"visit_date\"] = joined[\"visit_datetime\"].dt.date\n# print(joined.head())\n\nprint(\"Now merging...\")\n# Make sure that every open day with no reserve is filled with 0\n\n\njoined = pd.merge(joined, air_reserve_df, on=[\"air_store_id\", \"visit_date\"], how=\"left\")\njoined = pd.merge(joined, hpg_reserve_df, on=[\"air_store_id\", \"visit_date\"], how=\"left\")\n\njoined = get_total_info(joined)\njoined = get_ewm_reserve(joined)\n\n# pd.set_option('display.width', 240)\n# pd.set_option('display.max_columns', None)\nprint(joined.describe())\n\n\ntrain = joined[joined[\"visit_date\"] < \"2017-04-23\"]\npredict = joined[joined[\"visit_date\"] >= \"2017-04-23\"]\n\nprint(\"output to csv...\")\ntrain.to_csv('../output/cwsv_train.csv',float_format='%.6f', index=False)\npredict.to_csv('../output/cwsv_predict.csv',float_format='%.6f', index=False)\n\n\n\n","sub_path":"whathell/proper_reserve.py","file_name":"proper_reserve.py","file_ext":"py","file_size_in_byte":7158,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"224118944","text":"import FWCore.ParameterSet.Config as cms\n\nimport RecoTracker.FinalTrackSelectors.trackListMerger_cfi\nHLTgeneralTracks = RecoTracker.FinalTrackSelectors.trackListMerger_cfi.trackListMerger.clone( #temporary; substitute with just a clone!\n TrackProducers = (cms.InputTag('iterativeInitialTracks'),\n cms.InputTag('iterativeLowPtTripletTracksWithTriplets'),\n cms.InputTag('iterativePixelPairTracks'),\n cms.InputTag('iterativeDetachedTripletTracks'),\n cms.InputTag('iterativeMixedTripletStepTracks'),\n cms.InputTag('iterativePixelLessTracks'),\n cms.InputTag('iterativeTobTecTracks')),\n hasSelector=cms.vint32(1,1,1,1,1,1,1),\n selectedTrackQuals = cms.VInputTag(cms.InputTag(\"initialStepSelector\",\"initialStep\"),\n cms.InputTag(\"lowPtTripletStepSelector\",\"lowPtTripletStep\"),\n cms.InputTag(\"pixelPairStepSelector\",\"pixelPairStep\"),\n cms.InputTag(\"detachedTripletStep\"),\n cms.InputTag(\"mixedTripletStep\"),\n cms.InputTag(\"pixelLessStepSelector\",\"pixelLessStep\"),\n cms.InputTag(\"tobTecStepSelector\",\"tobTecStep\")\n ),\n setsToMerge = cms.VPSet( cms.PSet( tLists=cms.vint32(0,1,2,3,4,5,6), pQual=cms.bool(True) )\n ),\n copyExtras = True,\n makeReKeyedSeeds = cms.untracked.bool(False)\n )\n","sub_path":"FastSimulation/Tracking/python/HLTGeneralTracks_cfi.py","file_name":"HLTGeneralTracks_cfi.py","file_ext":"py","file_size_in_byte":1614,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"239406539","text":"from django.contrib import admin\nfrom django.apps import apps\nfrom .models import Perfil\nfrom django.contrib.auth.admin import UserAdmin as BaseUserAdmin\n\n\n# Register your models here.\nclass PerfilAdmin(admin.ModelAdmin):\n list_display = ('pk', 'user', 'birthdate', 'is_estudiante', 'is_profesor', 'check', 'created', 'modified')\n list_display_links = ('user',)\n list_filter = ('is_estudiante',\n 'is_profesor',\n 'created',\n 'modified')\n search_fields = ('user__first_name',\n 'user__last_name',\n 'user__email')\n ordering = ('pk',)\n filter_horizontal = ('groups', 'user_permissions',)\n fieldsets = (\n ('Perfil', {\n 'fields': (('user', 'birthdate'),),\n }),\n ('Extra info', {\n 'fields': (\n ('is_estudiante', 'is_profesor', 'check'),\n )\n }),\n ('Metadata', {\n 'fields': (('created', 'modified'),),\n })\n )\n\n readonly_fields = ('created', 'modified',)\n\n\nclass PerfilInline(admin.StackedInline):\n model = Perfil\n can_delete = False\n verbose_name_plural = 'perfiles'\n\n\nclass UserAdmin(BaseUserAdmin):\n inlines = (PerfilInline,)\n list_display = (\n 'username',\n 'email',\n 'first_name',\n 'last_name',\n 'is_active',\n 'is_staff'\n )\n\n\n# all other models\napp = apps.get_app_config('capacitaciones')\n\nfor model_name, model in app.models.items():\n admin.site.register(model)","sub_path":"capacitaciones/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":1540,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"116525070","text":"from pymongo import MongoClient\nimport sys\nimport time\nfrom multiprocessing import Queue, Process\n\n# Does the same thing as 7_construct_locations, but iterates over partitions of the arcgis locations.\n# Takes advantage of multiprocessing and batch updates. Very intensive.\n# The batch updating is a nightmare on icews\n\nbatch = 5\n\n\ndef format_coordinate(document):\n\n mapname = {\n \"REV_Address\": \"TwoRavens_address\",\n \"REV_City\": \"TwoRavens_city\",\n \"REV_CountryCode\": \"TwoRavens_country\",\n \"REV_Postal\": \"TwoRavens_postal\",\n \"REV_PostalExt\": \"TwoRavens_postal_ext\",\n \"REV_Region\": \"TwoRavens_region\",\n \"REV_Subregion\": \"TwoRavens_subregion\"\n }\n return {mapname[key]: document['attributes'][key] for key in\n set(mapname.keys()) & set(document['attributes'].keys())}\n\n\ndef format_placename(document):\n mapname = {\n \"City\": \"TwoRavens_city\",\n \"Country\": \"TwoRavens_country\",\n \"LangCode\": \"TwoRavens_language\",\n \"Region\": \"TwoRavens_region\",\n \"Score\": \"TwoRavens_score\",\n \"Subregion\": \"TwoRavens_subregion\",\n \"Territory\": \"TwoRavens_territory\"\n }\n return {mapname[key]: document['attributes'][key] for key in\n set(mapname.keys()) & set(document['attributes'].keys())}\n\n\ndef process_partition(locations, partition, db):\n result = list(locations.arcgis.aggregate([{\"$match\": {**partition, \"mapped\": {\"$exists\": 1}}}, {\"$count\": \"count\"}]))\n count = result[0]['count'] if result else 0\n total = list(locations.arcgis.aggregate([{\"$match\": partition}, {\"$count\": \"count\"}]))[0]['count']\n\n for document in locations.arcgis.find({**partition, \"mapped\": {\"$exists\": 0}}).batch_size(batch):\n count += 1\n print(str(partition) + ' ' + str(count) + '/' + str(total))\n\n if 'Latitude' in document:\n for collection in ['cline_speed', 'cline_phoenix_nyt', 'cline_phoenix_fbis', 'cline_phoenix_swb']:\n identifiers = ['GP7', 'GP8'] if 'cline_speed' == collection else ['lat', 'lon']\n query = {ident: value for ident, value in zip(identifiers, [document['Latitude'], document['Longitude']])}\n\n new_data = format_coordinate(document)\n\n if new_data:\n db[collection].update_many(query, {\"$set\": new_data}, upsert=False)\n\n else:\n for collection in db.collection_names():\n if collection == 'icews':\n docname = {'Country': 'Country', 'Region': 'District', 'Subregion': 'Province', 'City': 'City'}\n elif 'acled' in collection:\n docname = {'Country': 'COUNTRY', 'Region': 'ADMIN2', 'Subregion': 'ADMIN1', 'City': 'Location'}\n\n query = {docname[key]: {\"$exists\": 0} for key in set(docname.keys())}\n for key in set(docname.keys()) & set(document.keys()):\n query[docname[key]] = document[key]\n\n new_data = format_placename(document)\n\n if new_data:\n db[collection].update_many(query, {\"$set\": new_data})\n\n locations.arcgis.update({\"_id\": document[\"_id\"]}, {\"$set\": {\"mapped\": True}})\n\n\ndef reformat_database():\n mongo_client = MongoClient(host='localhost', port=27017) # Default port\n locations = mongo_client.locations\n\n partitions = [{\"Country\": country} for country in locations.arcgis.distinct('Country') if country is not None] + [\n {\"Latitude\": {\"$lte\": 0}, \"Longitude\": {\"$lte\": 0}},\n {\"Latitude\": {\"$gt\": 0}, \"Longitude\": {\"$lte\": 0}},\n {\"Latitude\": {\"$lte\": 0}, \"Longitude\": {\"$gt\": 0}},\n {\"Latitude\": {\"$gt\": 0}, \"Longitude\": {\"$gt\": 0}},\n ]\n\n partition_queue = Queue()\n for partition in partitions:\n partition_queue.put(partition)\n\n total_size = partition_queue.qsize()\n pool = [Process(target=process_wrapper, args=(partition_queue,), name=str(proc))\n for proc in range(4)]\n\n for proc in pool:\n proc.start()\n\n while any([proc.is_alive() for proc in pool]) and partition_queue.qsize() != 0:\n # Show status\n sys.stdout.write(\"\\r\\x1b[KCollecting: \" + str(total_size - partition_queue.qsize()) + '/' + str(total_size))\n sys.stdout.flush()\n time.sleep(5)\n\n # Print a newline to stdout\n print()\n\n # Once the pool of partitions has been exhausted, each thread will die\n # Once the threads are dead, this terminates all threads and the program is complete\n for proc in pool:\n proc.terminate()\n\n\ndef process_wrapper(page_queue):\n mongo_client = MongoClient(host='localhost', port=27017) # Default port\n db = mongo_client.event_data\n locations = mongo_client.locations\n\n # Take elements from the queue until the queue is exhausted\n while not page_queue.empty():\n\n partition = page_queue.get()\n\n success = False\n while not success:\n try:\n process_partition(locations, partition, db)\n success = True\n except Exception as err:\n print(err)\n print(\"Re-attempting partition \" + str(partition))\n\n\n# Only call when invoked from main. This prevents forked processes from calling it\nif __name__ == '__main__':\n reformat_database()\n","sub_path":"tworaven_apps/eventdata_queries/initialization/7_construct_locations_multiprocess.py","file_name":"7_construct_locations_multiprocess.py","file_ext":"py","file_size_in_byte":5317,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"98517547","text":"#!/usr/bin/python\n\nfrom collections import Counter, defaultdict\nfrom datetime import datetime\n\nwith open('input.txt', 'r') as f:\n data = f.read().rstrip('\\n').splitlines()\n\nguards = defaultdict(Counter)\nfor t, m in [l.split('] ') for l in sorted(data) if l]:\n t = datetime.strptime(t, '[%Y-%m-%d %H:%M')\n print(t)\n if 'Guard' in m:\n g = int(m.split('#')[1].split()[0])\n print(g)\n if 'asleep' in m:\n start = t\n if 'wakes' in m:\n minutes = int((t - start).total_seconds() // 60)\n guards[g].update(Counter((start.minute+i)%60 for i in range(minutes)))\n\n(_, minute), guard_id = max((c.most_common()[0][::-1], guard_id) for guard_id, c in guards.items())\nprint(guard_id * minute)\n","sub_path":"2018/day4/solution2.py","file_name":"solution2.py","file_ext":"py","file_size_in_byte":728,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"193648122","text":"# -*- coding: utf-8 -*-\n\"\"\"\n======================\nCHIME2 Web Application\n======================\n\nReactive web application presenting the latest iteration of the Covid-19\nHospital Impact Model for Epidemics from the Predictive Healthcare team\nat Penn Medicine. Built using the flask and dash libraries this app aims\nto provide an insightful user experience for those seeking to gain\ninsights from the advanced epidemiological modeling techniques created\nby data scientists at the nation's first hospital system and academy.\n\n----\n\nThe chime2 application uses the\n`bayes_chime <https://www.github.com/pennsignals/chime_sims/tree/master/bayes_chime>`_\nnormal extension, created by Dr. Chris Koerber of UC Berkley, which\noptimizes for speed the latest CHIME iteration by assuming normal\ndistributions among model parameters. Thanks to his work, and the work\nof the Penn Medicine team we can offer this application.\n\"\"\"\nfrom flask_script import Manager\n\nfrom app import blueprint\nfrom app.main import config, create_app\n\napp = create_app(config)\napp.register_blueprint(blueprint)\napp.app_context().push()\nmanager = Manager(app)\n\n\n@manager.command\ndef run():\n \"\"\"run the flask app\"\"\"\n app.run()\n\n\nif __name__ == \"__main__\":\n manager.run()\n","sub_path":"src/chime2-web/chime2.py","file_name":"chime2.py","file_ext":"py","file_size_in_byte":1243,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"10690043","text":"import numpy as np\nimport pandas as pd\n\nfrom sktime.datasets import load_longley\nfrom sktime.datasets import load_shampoo_sales\nfrom sktime.forecasters import ARIMAForecaster\nfrom sktime.forecasters import DummyForecaster\nfrom sktime.highlevel.strategies import ForecastingStrategy\nfrom sktime.highlevel.tasks import ForecastingTask\n\nforecaster = DummyForecaster()\n\n\n# Test forecasting strategy\ndef test_univariate():\n shampoo = load_shampoo_sales(return_y_as_dataframe=True)\n train = pd.DataFrame(pd.Series([shampoo.iloc[0, 0].iloc[:30]]), columns=shampoo.columns)\n test = pd.DataFrame(pd.Series([shampoo.iloc[0, 0].iloc[30:]]), columns=shampoo.columns)\n\n target = \"ShampooSales\"\n fh = np.arange(len(test[target].iloc[0])) + 1\n task = ForecastingTask(target=target, fh=fh, metadata=train)\n\n s = ForecastingStrategy(estimator=forecaster)\n s.fit(task, train)\n y_pred = s.predict()\n assert y_pred.shape == test[task.target].iloc[0].shape\n\n\ndef test_multivariate():\n longley = load_longley(return_X_y=False)\n train = pd.DataFrame([pd.Series([longley.iloc[0, i].iloc[:13]]) for i in range(longley.shape[1])]).T\n train.columns = longley.columns\n\n test = pd.DataFrame([pd.Series([longley.iloc[0, i].iloc[13:]]) for i in range(longley.shape[1])]).T\n test.columns = longley.columns\n target = \"TOTEMP\"\n fh = np.arange(len(test[target].iloc[0])) + 1\n task = ForecastingTask(target=target, fh=fh, metadata=train)\n\n estimator = ARIMAForecaster()\n s = ForecastingStrategy(estimator=estimator)\n s.fit(task, train)\n y_pred = s.predict(data=test)\n assert y_pred.shape == test[task.target].iloc[0].shape\n","sub_path":"sktime/highlevel/tests/test_ForecastingStrategy.py","file_name":"test_ForecastingStrategy.py","file_ext":"py","file_size_in_byte":1656,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"545094978","text":"\n# swap이란? 변수의 값을 바꾸는 코딩 기법\n\n# 1. 외팔이 기법\n# 2. 튜플을 사용하는 방법, 파이썬에서만 가능\n# hoan doi gia tri cua bien\nx = 2\ny = 3\n\ntmp = x\nx = y\ny = tmp\n\nprint(\"x = \", x, \"y= \", y)\n(x, y) = (y, x) # 튜플을 이용하여 swap 하는 방법\nprint(\"x = \", x, \"y= \", y)\n","sub_path":"py14튜플/py14_02_swap.py","file_name":"py14_02_swap.py","file_ext":"py","file_size_in_byte":320,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"251369874","text":"#!/usr/bin/env python\r\n\r\n\"\"\"Trains and Evaluates the 3d convolutional neural network using a feed \r\n dictionary.\r\n\"\"\"\r\nfrom __future__ import absolute_import\r\nfrom __future__ import division\r\nfrom __future__ import print_function\r\n\r\nfrom datetime import datetime\r\nimport os\r\nimport re\r\nimport time\r\nimport h5py\r\n\r\n\r\nfrom six.moves import xrange # pylint: disable=redefined-builtin\r\nimport tensorflow as tf\r\nimport math\r\nimport numpy as np\r\nimport input_data\r\nimport c3d_model\r\nfrom PIL import Image\r\n\r\ndef placeholder_inputs():\r\n \"\"\"Generate placeholder variables to represent the input tensors.\r\n\r\n These placeholders are used as inputs by the rest of the model building\r\n code and will be fed from the downloaded data in the .run() loop, below.\r\n\r\n Returns:\r\n images_placeholder: Images placeholder.\r\n labels_placeholder: Labels placeholder.\r\n \"\"\"\r\n # Note that the shapes of the placeholders match the shapes of the full\r\n # image and label tensors, except the first dimension is now batch_size\r\n # rather than the full size of the train or test data sets.\r\n images_placeholder = tf.placeholder(tf.float32, shape=(None,\r\n c3d_model.NUM_FRAMES_PER_CLIP,\r\n c3d_model.CROP_SIZE,\r\n c3d_model.CROP_SIZE,\r\n c3d_model.CHANNELS))\r\n return images_placeholder\r\n\r\ndef tower_feature(scope, images):\r\n \"\"\"Calculate the total loss and accuracy on a single tower running the model.\r\n\r\n Args:\r\n scope: unique prefix string identifying the tower, e.g. 'tower_0'\r\n images: input images with shape \r\n [batch_size, sequence_length, height, width, channel]\r\n labels: label ground truth\r\n [batch_size]\r\n\r\n Returns:\r\n Tensor of shape [] containing the total loss for a batch of data\r\n \"\"\" \r\n # Build the inference Graph\r\n with tf.variable_scope(\"c3d_var\") as c3d_scope:\r\n try:\r\n logits = c3d_model.inference_c3d(images)\r\n except ValueError:\r\n c3d_scope.reuse_variables()\r\n logits = c3d_model.inference_c3d(images)\r\n return logits\r\n\r\n\r\ndef run_testing():\r\n with tf.Graph().as_default():\r\n # Get the image and the labels placeholder\r\n images_placeholder = placeholder_inputs()\r\n\r\n with tf.name_scope('%s' % (c3d_model.TOWER_NAME)) as scope:\r\n # Calculate the loss and accuracy for one tower for the model. This \r\n # function constructs the entire model but shares the variables \r\n # across all towers.\r\n features = tower_feature(scope, images_placeholder)\r\n\r\n # Create a saver\r\n saver = tf.train.Saver(tf.global_variables())\r\n\r\n # Build an initialization operation to run below\r\n init = tf.global_variables_initializer()\r\n\r\n # Start running operations on the Graph. allow_soft_placement must be set to\r\n # True to build towers on GPU, as some of the ops do not have GPU\r\n # implementations.\r\n sess = tf.Session(config=tf.ConfigProto(\r\n allow_soft_placement=True))\r\n\r\n # Retore the training model from check point\r\n\r\n if os.path.isfile('pretrained_model/sports1m_finetuning_ucf101.model'):\r\n print(\"model exist\")\r\n with tf.variable_scope(tf.get_variable_scope(), reuse=True):\r\n sess.run(init)\r\n # Variable to restore\r\n variables = {\r\n \"var_name/wc1\": tf.get_variable('c3d_var/conv1/weight'),\r\n \"var_name/wc2\": tf.get_variable('c3d_var/conv2/weight'),\r\n \"var_name/wc3a\": tf.get_variable('c3d_var/conv3/weight_a'),\r\n \"var_name/wc3b\": tf.get_variable('c3d_var/conv3/weight_b'),\r\n \"var_name/wc4a\": tf.get_variable('c3d_var/conv4/weight_a'),\r\n \"var_name/wc4b\": tf.get_variable('c3d_var/conv4/weight_b'),\r\n \"var_name/wc5a\": tf.get_variable('c3d_var/conv5/weight_a'),\r\n \"var_name/wc5b\": tf.get_variable('c3d_var/conv5/weight_b'),\r\n \"var_name/wd1\": tf.get_variable('c3d_var/local6/weights'),\r\n #\"var_name/wd2\": tf.get_variable('c3d_var/local7/weights'),\r\n \"var_name/bc1\": tf.get_variable('c3d_var/conv1/biases'),\r\n \"var_name/bc2\": tf.get_variable('c3d_var/conv2/biases'),\r\n \"var_name/bc3a\": tf.get_variable('c3d_var/conv3/biases_a'),\r\n \"var_name/bc3b\": tf.get_variable('c3d_var/conv3/biases_b'),\r\n \"var_name/bc4a\": tf.get_variable('c3d_var/conv4/biases_a'),\r\n \"var_name/bc4b\": tf.get_variable('c3d_var/conv4/biases_b'),\r\n \"var_name/bc5a\": tf.get_variable('c3d_var/conv5/biases_a'),\r\n \"var_name/bc5b\": tf.get_variable('c3d_var/conv5/biases_b'),\r\n \"var_name/bd1\": tf.get_variable('c3d_var/local6/biases'),\r\n #\"var_name/bd2\": tf.get_variable('c3d_var/local7/biases')\r\n }\r\n saver_c3d = tf.train.Saver(variables)\r\n saver_c3d.restore(sess, 'pretrained_model/sports1m_finetuning_ucf101.model')\r\n else:\r\n print('cannot load model')\r\n\r\n with open('list/test.list', 'r') as f:\r\n lines = f.readlines()\r\n h5_file = h5py.File('D:/Python/Python_codes/C3D-tensorflow-master/test/test_4096.h5','w')\r\n for line in lines:\r\n print(line)\r\n test_sample_path, label = line.strip().split(' ')\r\n img_arr = []\r\n for filename in os.listdir(test_sample_path):\r\n img = Image.open(os.path.join(test_sample_path, filename)).resize((c3d_model.CROP_SIZE, c3d_model.CROP_SIZE), Image.ANTIALIAS)\r\n print(filename)\r\n # (112, 112, 3) -> (1, 112, 112, 3)\r\n img_arr.append(np.expand_dims(np.array(img, dtype=np.float32), axis=0))\r\n N = len(img_arr)\r\n img_features = []\r\n for i in range(N-15):\r\n img_data = np.expand_dims(np.concatenate(img_arr[i:i+16], axis=0), axis=0) # Duixiang is for list\r\n img_features.append(sess.run(features, feed_dict={images_placeholder: img_data}))\r\n\r\n img_features = np.concatenate(img_features, axis=0) if len(img_features) > 1 else np.array(img_features, dtype=np.float32)\r\n print(img_features.shape)\r\n key = label + '_' + test_sample_path.split('/')[-1]\r\n h5_file[key] = img_features\r\n\r\n\r\ndef main(_):\r\n # Set the gpu visial device\r\n os.environ[\"CUDA_VISIBLE_DEVICES\"]='0'\r\n run_testing()\r\n\r\n\r\nif __name__ == '__main__':\r\n tf.app.run()\r\n","sub_path":"C3D-tensorflow-master/extract_features.py","file_name":"extract_features.py","file_ext":"py","file_size_in_byte":6332,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"250939787","text":"import connexion\n\nfrom mist.api.methods import list_resources as list_resources_v1\n\nfrom mist.api.exceptions import ServiceUnavailableError\n\nfrom mist_api_v2.models.create_cluster_request import CreateClusterRequest # noqa: E501\nfrom mist_api_v2.models.get_cluster_response import GetClusterResponse # noqa: E501\nfrom mist_api_v2.models.list_clusters_response import ListClustersResponse # noqa: E501\n\nfrom .base import list_resources\nfrom .base import get_resource\n\n\ndef create_cluster(create_cluster_request=None): # noqa: E501\n \"\"\"Create cluster\n\n Create a new cluster and return the cluster's id # noqa: E501\n\n :param create_cluster_request:\n :type create_cluster_request: dict | bytes\n\n :rtype: CreateClusterResponse\n \"\"\"\n if connexion.request.is_json:\n create_cluster_request = CreateClusterRequest.from_dict(connexion.request.get_json()) # noqa: E501\n try:\n auth_context = connexion.context['token_info']['auth_context']\n except Exception:\n return 'Authentication failed', 401\n params = create_cluster_request.to_dict()\n try:\n [cloud], _ = list_resources_v1(auth_context, 'cloud',\n search=params.pop('cloud'),\n limit=1)\n except ValueError:\n return 'Cloud not found', 404\n try:\n auth_context.check_perm('cluster', 'create', cloud.id)\n auth_context.check_perm('cloud', 'read', cloud.id)\n auth_context.check_perm('cloud', 'create_resources', cloud.id)\n except Exception:\n return 'You are not authorized to perform this action', 403\n provider = params.pop('provider')\n kwargs = {k: v for k, v in params.items() if v is not None}\n if provider == 'google':\n kwargs['zone'] = kwargs.pop('location')\n try:\n result = cloud.ctl.container.create_cluster(**kwargs)\n except ServiceUnavailableError as e:\n return e.msg, e.http_code\n if not result:\n return 'Cluster creation failed', 409\n return 'Cluster creation successful', 200\n\n\ndef destroy_cluster(cluster): # noqa: E501\n \"\"\"Destroy cluster\n\n Destroy target clusters # noqa: E501\n\n :param cluster:\n :type cluster: str\n\n :rtype: None\n \"\"\"\n try:\n auth_context = connexion.context['token_info']['auth_context']\n except Exception:\n return 'Authentication failed', 401\n cluster_name = cluster\n try:\n [cluster], total = list_resources_v1(auth_context, 'cluster',\n search=f'\"{cluster_name}\"',\n limit=1)\n except ValueError:\n return 'Cluster not found', 404\n try:\n auth_context.check_perm('cluster', 'destroy', cluster.id)\n except Exception:\n return 'You are not authorized to perform this action', 403\n kwargs = {\n 'name': cluster.name,\n }\n if cluster.provider == 'gce':\n kwargs['zone'] = cluster.location.name or cluster.extra.get(\n 'location')\n result = cluster.cloud.ctl.container.destroy_cluster(**kwargs)\n if not result:\n return 'Cluster destruction failed', 404\n return 'Cluster destruction successful', 200\n\n\ndef get_cluster(cluster, only=None, deref=None): # noqa: E501\n \"\"\"Get cluster\n\n Get details about target cluster # noqa: E501\n\n :param cluster:\n :type cluster: str\n :param only: Only return these fields\n :type only: str\n :param deref: Dereference foreign keys\n :type deref: str\n\n :rtype: GetClusterResponse\n \"\"\"\n auth_context = connexion.context['token_info']['auth_context']\n result = get_resource(auth_context, 'cluster', search=cluster, only=only,\n deref=deref)\n return GetClusterResponse(data=result['data'], meta=result['meta'])\n\n\ndef list_clusters(cloud=None, search=None, sort=None, start=0, limit=100, only=None, deref=None): # noqa: E501\n \"\"\"List clusters\n\n List clusters # noqa: E501\n\n :param cloud:\n :type cloud: str\n :param search: Only return results matching search filter\n :type search: str\n :param sort: Order results by\n :type sort: str\n :param start: Start results from index or id\n :type start: str\n :param limit: Limit number of results, 1000 max\n :type limit: int\n :param only: Only return these fields\n :type only: str\n :param deref: Dereference foreign keys\n :type deref: str\n\n :rtype: ListClustersResponse\n \"\"\"\n auth_context = connexion.context['token_info']['auth_context']\n result = list_resources(\n auth_context, 'cluster', cloud=cloud, search=search, only=only,\n sort=sort, start=start, limit=limit, deref=deref\n )\n return ListClustersResponse(data=result['data'], meta=result['meta'])\n","sub_path":"mist_api_v2/controllers/clusters_controller.py","file_name":"clusters_controller.py","file_ext":"py","file_size_in_byte":4774,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"210382621","text":"from goody import type_as_str\r\nimport inspect\r\n\r\nclass Check_All_OK:\r\n \"\"\"\r\n Check_ALl_OK implements __check_annotation__ by checking whether all the\r\n annotations passed to its constructor are OK; the first one that\r\n fails (raises AssertionError) prints its problem, with a list of all\r\n annotations being tried at the end of the check_history.\r\n \"\"\"\r\n \r\n def __init__(self,*args):\r\n self._annotations = args\r\n \r\n def __repr__(self):\r\n return 'Check_All_OK('+','.join([str(i) for i in self._annotations])+')'\r\n\r\n def __check_annotation__(self, check, param, value,check_history):\r\n for annot in self._annotations:\r\n check(param, annot, value, check_history+'Check_All_OK check: '+str(annot)+' while trying: '+str(self)+'\\n')\r\n\r\n\r\nclass Check_Any_OK:\r\n \"\"\"\r\n Check_Any_OK implements __check_annotation__ by checking whether at least\r\n one of the annotations passed to its constructor is OK; if all fail \r\n (raise AssertionError) this classes raises AssertionError and prints its\r\n failure, along with a list of all annotations tried followed by the check_history.\r\n \"\"\"\r\n \r\n def __init__(self,*args):\r\n self._annotations = args\r\n \r\n def __repr__(self):\r\n return 'Check_Any_OK('+','.join([str(i) for i in self._annotations])+')'\r\n\r\n def __check_annotation__(self, check, param, value, check_history):\r\n failed = 0\r\n for annot in self._annotations: \r\n try:\r\n check(param, annot, value, check_history)\r\n except AssertionError:\r\n failed += 1\r\n if failed == len(self._annotations):\r\n assert False, repr(param)+' failed annotation check(Check_Any_OK): value = '+repr(value)+\\\r\n '\\n tried '+str(self)+'\\n'+check_history \r\n\r\n\r\n\r\nclass Check_Annotation():\r\n # must be True for checking to occur\r\n checking_on = True\r\n \r\n # self._checking_on must also be true for checking to occur\r\n def __init__(self,f):\r\n self._f = f\r\n self._checking_on = True\r\n \r\n # Check whether param's annot is correct for value, adding to check_history\r\n # if recurs; defines many local function which use it parameters. \r\n def check(self,param,annot,value,check_history=''):\r\n \r\n # Check list/tuple: type, len=1 (same check) or match (respective matches)\r\n def check_sequence(kind,kind_text):\r\n assert isinstance(value,kind), repr(param)+' failed annotation check(wrong type): value = '+repr(value)+\\\r\n '\\n was type '+type_as_str(value)+' ...should be type '+kind_text+'\\n'+check_history \r\n if len(annot) == 1:\r\n i = 0\r\n for v in value:\r\n self.check(param,annot[0],v,check_history+kind_text+'['+str(i)+'] check: '+str(annot[0])+'\\n')\r\n i += 1\r\n else:\r\n assert len(annot) == len(value), repr(param)+' failed annotation check(wrong number of elements): value = '+repr(value)+\\\r\n '\\n annotation had '+str(len(annot))+ ' elements'+str(annot)+'\\n'+check_history \r\n i = 0\r\n for a,v in zip(annot,value):\r\n self.check(param,a,v, check_history+kind_text+'['+str(i)+'] check: '+str(annot[i])+'\\n')\r\n i += 1\r\n\r\n # Check dict: type, len=1, all keys (same check) and all values (same check)\r\n def check_dict():\r\n assert isinstance(value,dict), repr(param)+' failed annotation check(wrong type): value = '+repr(value)+\\\r\n '\\n was type '+type_as_str(value)+' ...should be type dict\\n'+check_history \r\n if len(annot) != 1:\r\n assert False, repr(param)+' annotation inconsistency: dict should have 1 item but had '+str(len(annot))+\\\r\n '\\n annotation = '+str(annot)+'\\n'+check_history \r\n else:\r\n for annot_k,annot_v in annot.items(): # get first and only\r\n pass\r\n for k,v in value.items():\r\n self.check(param,annot_k,k, check_history+'dict key check: ' +str(annot_k)+'\\n')\r\n self.check(param,annot_v,v, check_history+'dict value check: '+str(annot_v)+'\\n')\r\n \r\n # Check set/frozenset: type, len=1, all keys (same check) and all values (same check)\r\n def check_set(kind,kind_text):\r\n assert isinstance(value,kind), repr(param)+' failed annotation check(wrong type): value = '+repr(value)+\\\r\n '\\n was type '+type_as_str(value)+' ...should be type ' +kind_text+'\\n'+check_history \r\n if len(annot) != 1:\r\n assert False, repr(param)+' annotation inconsistency: '+kind_text+' should have 1 value but had '+str(len(annot))+\\\r\n '\\n annotation = '+str(annot)+'\\n'+check_history \r\n else:\r\n for annot_v in annot:\r\n pass\r\n for v in value:\r\n self.check(param,annot_v,v,check_history+kind_text+' value check: '+str(annot_v)+'\\n')\r\n\r\n # Check function/lambda: univariate, returns True, throws exception\r\n def check_predicate():\r\n assert len(annot.__code__.co_varnames) == 1, repr(param)+' annotation inconsistency: predicate should have 1 parameter but had '+str(len(annot.__code__.co_varnames))+\\\r\n '\\n annotation = '+str(annot)+'\\n'+check_history \r\n try:\r\n worked = annot(value)\r\n except Exception as message:\r\n assert False, repr(param)+' annotation predicate('+str(annot)+') raised exception'+\\\r\n '\\n exception = '+str(message.__class__)[8:-2]+': '+str(message)+'\\n'+check_history \r\n else:\r\n assert worked, repr(param)+' failed annotation check: value = '+repr(value)+\\\r\n '\\n predicate = '+str(annot)+'\\n'+check_history \r\n\r\n # Check string (as evaluated expression): returns True, throws exception\r\n def check_str():\r\n try:\r\n worked = eval(annot,self._args) \r\n except Exception as message:\r\n assert False, repr(param)+' annotation check(str predicate: '+repr(annot)+') raised exception'+\\\r\n '\\n exception = '+str(message.__class__)[8:-2]+': '+str(message)+'\\n'+check_history \r\n else:\r\n assert worked, repr(param)+' failed annotation check(str predicate: '+repr(annot)+')'\\\r\n '\\n args for evaluation: '+', '.join([str(k)+'->'+str(v) for k,v in self._args.items()])+'\\n'+check_history\r\n\r\n \r\n # Decode annotation and check it #print('checking',p+':'+str(value),annot)\r\n if annot == None:\r\n pass\r\n elif type(annot) is type:\r\n assert isinstance(value,annot), repr(param)+' failed annotation check(wrong type): value = '+repr(value)+\\\r\n '\\n was type '+type_as_str(value)+' ...should be type '+str(annot)[8:-2]+'\\n'+check_history \r\n elif type(annot) is list: check_sequence(list,'list')\r\n elif type(annot) is tuple: check_sequence(tuple,'tuple')\r\n elif isinstance(annot,dict): check_dict()\r\n elif type(annot) is set: check_set(set,'set')\r\n elif type(annot) is frozenset: check_set(frozenset,'frozenset')\r\n elif inspect.isfunction(annot): check_predicate()\r\n elif type(annot) is str: check_str()\r\n else:\r\n try:\r\n annot.__check_annotation__(self.check,param,value,check_history)\r\n except AttributeError: \r\n assert False, repr(param)+' annotation undecipherable: '+str(annot)+'\\n'+check_history \r\n except Exception as message:\r\n if message.__class__ is AssertionError:\r\n raise\r\n else:\r\n assert False, repr(param)+' annotation protocol('+str(annot)+') raised exception'+\\\r\n '\\n exception = '+str(message.__class__)[8:-2]+': '+str(message)+'\\n'+check_history \r\n \r\n \r\n # Return decorated function call, checking present parameter/return\r\n # annotations if required\r\n def __call__(self, *args, **kargs):\r\n # Return a dictionary of the parameter/argument bindings (actually an\r\n # ordereddict, in the order parameters occur in the function's header)\r\n def param_arg_bindings():\r\n f_signature = inspect.signature(self._f)\r\n bound_f_signature = f_signature.bind(*args,**kargs)\r\n for param in f_signature.parameters.values():\r\n if param.name not in bound_f_signature.arguments:\r\n bound_f_signature.arguments[param.name] = param.default\r\n return bound_f_signature.arguments\r\n\r\n # If annotation checking is turned off at the class or function level\r\n # just return the result of calling the decorated function\r\n if not (Check_Annotation.checking_on and self._checking_on):\r\n return self._f(*args,**kargs)\r\n \r\n # On first AssertionError, print the source lines of the function and reraise \r\n self._args = param_arg_bindings()\r\n annot = self._f.__annotations__\r\n try:\r\n # Check the annotation for every parameter (if there is one)\r\n for p in self._args.keys():\r\n if p in annot:\r\n self.check(p,annot[p],self._args[p])\r\n \r\n # Compute/remember the value of the decorated function\r\n answer = self._f(*args,**kargs)\r\n \r\n # If 'return' is in the annotation, check it\r\n if 'return' in annot:\r\n self._args['_return'] = answer\r\n self.check('return',annot['return'],answer)\r\n \r\n # Return the decorated answer\r\n return answer\r\n except AssertionError:\r\n# print(80*'-')\r\n# for l in inspect.getsourcelines(self._f)[0]: # ignore starting line #\r\n# print(l.rstrip())\r\n# print(80*'-')\r\n raise\r\n \r\nif __name__ == '__main__':\r\n # and example of testing a simple annotation \r\n #def f(x:int): pass\r\n #f = Check_Annotation(f)\r\n #f(3)\r\n #f('a')\r\n \r\n import driver\r\n driver.driver()\r\n","sub_path":"Overloading/checkannotation.py","file_name":"checkannotation.py","file_ext":"py","file_size_in_byte":10927,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"504408801","text":"import os\nimport numpy as np\nimport torch\nimport scipy.sparse as sp_sparse\nimport pdb\nimport scipy.sparse as sp\n\n\nfrom utils import scipy_to_torch_sparse, normalize_sparse, \\\n labels_to_onehot, coo_to_symmetric\n\n\ndef load_cora(path='../data/cora/'):\n '''Load CORA: https://relational.fit.cvut.cz/dataset/CORA\n In the content file, the 1st column is the paper id, the 2nd\n to (n-1)th are the features, and the nth is the category/label.\n The cites file gives the edges in the graphs of papers'''\n\n # Load data\n data = np.genfromtxt(path+'cora.content', dtype=np.dtype(str))\n feats = sp_sparse.csr_matrix(data[:,1:-1], dtype=np.float32)\n labels = labels_to_onehot(data[:,-1])\n N, D = len(labels), feats.shape[0] # num nodes, num features\n\n # Build graph\n idx_map = {j: i for i,j in enumerate(np.array(data[:,0], dtype=np.int32))}\n edges = np.genfromtxt(path+'cora.cites', dtype=np.int32) # load edges\n edges = np.array(list(map(idx_map.get, edges.flatten())), \n dtype=np.int32).reshape(edges.shape) # order edges\n adj = (np.ones(edges.shape[0]), (edges[:,0], edges[:,1])) # all edges weight 1\n adj = sp_sparse.coo_matrix(adj, shape=(N, N), dtype=np.float32) # --> sparse matrix\n adj = coo_to_symmetric(adj) # --> symmetric adjacency matrix --> wait why?? \n adj_orig = adj # for transfering model to gae\n adj = adj + sp_sparse.eye(adj.shape[0]) # add identity (self-links)\n\n # Preprocessing\n feats = normalize_sparse(feats)\n adj = normalize_sparse(adj)\n\n # Train/val/test splits\n idx_train = torch.LongTensor(range(140))\n idx_val = torch.LongTensor(range(200,500))\n idx_test = torch.LongTensor(range(500,1500))\n\n # Torchify\n feats = torch.from_numpy(np.array(feats.todense()))\n labels = torch.LongTensor(np.where(labels)[1])\n adj = scipy_to_torch_sparse(adj)\n\n ## Save for GAE\n #torch.save({'adj_orig': adj_orig.todense(), 'adj_i': adj.indices, 'adj_v': adj.values,\n # 'adj_s': adj.shape, 'feats': feats, 'labels': labels, \n # 'idx_train': idx_train, 'idx_val': idx_val, 'idx_test': idx_test}, \n # '../data/cora/preprocessed_gcn_data_for_gae.pth')\n\n return adj, feats, labels, idx_train, idx_val, idx_test\n\ndef load_adv_data(node, path=\"../data/cora/\", dataset=\"cora\"):\n \"\"\"Load citation network dataset (cora only for now)\"\"\"\n print('Loading {} dataset...'.format(dataset))\n\n idx_features_labels = np.genfromtxt(\"{}{}.content\".format(path, dataset),\n dtype=np.dtype(str))\n features = sp_sparse.csr_matrix(idx_features_labels[:, 1:-1], dtype=np.float32)\n labels = encode_onehot(idx_features_labels[:, -1])\n \n # build graph\n idx = np.array(idx_features_labels[:, 0], dtype=np.int32)\n idx_map = {j: i for i, j in enumerate(idx)}\n edges_unordered = np.genfromtxt(\"{}{}.cites\".format(path, dataset),\n dtype=np.int32)\n edges = np.array(list(map(idx_map.get, edges_unordered.flatten())),\n dtype=np.int32).reshape(edges_unordered.shape)\n adj = sp_sparse.coo_matrix((np.ones(edges.shape[0]), (edges[:, 0], edges[:, 1])),\n shape=(labels.shape[0], labels.shape[0]),\n dtype=np.float32)\n\n # build symmetric adjacency matrix\n adj = adj + adj.T.multiply(adj.T > adj) - adj.multiply(adj.T > adj)\n \n labels = np.where(encode_onehot(idx_features_labels[:, -1]))[1]\n new_adj = deepcopy(np.array(adj.todense()))\n neighbours = (new_adj[node, :] > 0).astype(int)\n neighbours[node] = 0\n not_class = (labels != labels[node]).astype(int)\n eligible = np.where(not_class - neighbours > 0)[0] #indices to choose new edges from\n ineligible = np.where(neighbours)[0] #indices to remove edges from\n \n for i in ineligible:\n if i in eligible:\n import pdb; pdb.set_trace()\n assert(i not in eligible)\n\n num_perturb = min(int(sum(neighbours) / 2 + 1), len(eligible), len(ineligible))\n to_add = eligible[np.random.choice(len(eligible), num_perturb, replace=False)]\n to_remove = ineligible[np.random.choice(len(ineligible), num_perturb, replace=False)]\n print(\"Added: \", to_add, \"Removed: \", to_remove)\n\n for idx in to_add:\n assert(new_adj[node,idx] == 0)\n assert(new_adj[idx,node] == 0)\n new_adj[node,idx] = 1\n new_adj[idx,node] = 1\n\n for idx in to_remove:\n assert(new_adj[node,idx] == 1)\n assert(new_adj[idx,node] == 1)\n new_adj[node,idx] = 0\n new_adj[idx,node] = 0\n \n adj = sp_sparse.csr_matrix(new_adj)\n features = normalize(features)\n adj = normalize(adj + sp_sparse.eye(adj.shape[0]))\n\n idx_train = range(140)\n idx_val = range(200, 500)\n idx_test = range(500, 1500)\n\n features = torch.FloatTensor(np.array(features.todense()))\n labels = torch.LongTensor(labels)\n adj = sparse_mx_to_torch_sparse_tensor(adj)\n\n idx_train = torch.LongTensor(idx_train)\n idx_val = torch.LongTensor(idx_val)\n idx_test = torch.LongTensor(idx_test)\n\n return adj, features, labels, idx_train, idx_val, idx_test\n\n\n# For testing\nif __name__ == '__main__':\n import time\n start = time.time()\n if False:\n adj, feats, labels, idx_train, idx_val, idx_test = load_cora()\n adj_i, adj_v, adj_s = adj._indices(), adj._values(), adj.shape\n data = (adj_i, adj_v, adj_s, feats, labels, idx_train, idx_val, idx_test)\n torch.save(data, '../data/cora/preprocessed.pth')\n print('Saved cora in {:.2f}s'.format(time.time() - start))\n else:\n load_cora()\n print('Loaded cora in {:.2f}s'.format(time.time() - start))\n \n","sub_path":"gcn/dataloader.py","file_name":"dataloader.py","file_ext":"py","file_size_in_byte":5745,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"183162636","text":"import sys\nimport numpy as np\n\nimport lr_utils\nimport tensorflow as tf\nfrom tensorflow.examples.tutorials.mnist import input_data\nlearning_rate = 0.008\ntraining_epochs = 2000\nbatch_size = 40\ndisplay_step = 1\n\ntrain_set_x_orig, train_set_y, test_set_x_orig, test_set_y, classes = lr_utils.load_dataset()\nprint(train_set_x_orig.shape)\nm_train,m_test,num_px = train_set_x_orig.shape[0],test_set_x_orig.shape[0],train_set_x_orig.shape[1]\nprint(m_train,m_test,num_px)\nDATA_DIM = num_px * num_px * 3\ntrain_set_x_flatten = (train_set_x_orig/255).reshape(m_train,DATA_DIM)\n# train_set_x_flatten = train_set_x_flatten/255\ntest_set_x_flatten = (test_set_x_orig/255).reshape(m_test,DATA_DIM)\n# test_set_x_flatten = test_set_x_flatten/255\ntrain_set_y = train_set_y.reshape(m_train,1)\ntrain_set = 1 - train_set_y\ntrain = np.hstack((train_set_y,train_set))\nprint(train.shape)\ntest_set_y = test_set_y.reshape(m_test,1)\ntest_set = 1 - test_set_y\ntest = np.hstack((test_set_y,test_set))\nmnist = input_data.read_data_sets(\"/tmp/data/\", one_hot=True)\nprint(test_set_y.shape,train_set_x_flatten.shape)\n# tf Graph Input\nx = tf.placeholder(tf.float32, [None, DATA_DIM])\ny = tf.placeholder(tf.float32, [None, 2])\n\n# Set model weights\nW = tf.Variable(tf.zeros([DATA_DIM, 2]))\nb = tf.Variable(tf.zeros([2]))\n\n# softmax\npred = tf.nn.softmax(tf.matmul(x, W) + b)\n\n# Minimize error using cross entropy\ncost = tf.reduce_mean(-tf.reduce_sum(y*tf.log(pred), reduction_indices=1))\n\n# Gradient Descent\noptimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost)\n\n# Initializing the variables\ninit = tf.global_variables_initializer()\n\n# Launch the graph\nwith tf.Session() as sess:\n sess.run(init)\n\n # Training cycle\n for epoch in range(training_epochs):\n avg_cost = 0.\n total_batch = int(m_train/batch_size)\n # Loop over all batches\n for i in range(total_batch):\n batch_xs, batch_ys = train_set_x_flatten[i*batch_size:(i+1)*batch_size],train[i*batch_size:(i+1)*batch_size]\n # Run optimization op (backprop) and cost op (to get loss value)\n _, c = sess.run([optimizer, cost], feed_dict={x: batch_xs,\n y: batch_ys})\n # Compute average loss\n avg_cost += c / total_batch\n # Display logs per epoch step\n if (epoch+1) % display_step == 0:\n print(\"Epoch:\", '%04d' % (epoch+1), \"cost=\", \"{:.9f}\".format(avg_cost))\n\n print(\"Optimization Finished!\")\n\n # Test model\n correct_prediction = tf.equal(tf.argmax(pred, 1), tf.argmax(y, 1))\n # Calculate accuracy\n accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))\n print(\"Accuracy:\", accuracy.eval({x:test_set_x_flatten, y: test}))\n\n","sub_path":"猫脸识别fluid/cat-softmax.py","file_name":"cat-softmax.py","file_ext":"py","file_size_in_byte":2756,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"392403262","text":"class FizzBuzz:\n def getFizzBuzz(self,number):\n try:\n number = int(number.strip())\n except(ValueError):\n return \"Exception\\n\"\n if (number % 3 == 0 and number % 5 == 0):\n return \"FizzBuzz\\n\"\n\n elif (number % 3 == 0):\n return \"Fizz\\n\"\n elif (number % 5 == 0):\n return \"Buzz\\n\"\n else:\n return str(number)+\"\\n\"\n\nif(__name__ == \"__main__\"):\n inputFile = open(\"input.txt\",\"r\")\n outputFile = open(\"output.txt\",\"w\")\n fizzBuzz = FizzBuzz()\n for line in inputFile:\n outputStr = fizzBuzz.getFizzBuzz(line)\n outputFile.write(outputStr)\n inputFile.close()\n outputFile.close()\n","sub_path":"python-and-http-interface-test-master/6.3/FizzBuzzInFileWithException.py","file_name":"FizzBuzzInFileWithException.py","file_ext":"py","file_size_in_byte":706,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"529604536","text":"from AlgoExpert import interweavingstrings as program\nimport unittest\n\n\nclass TestProgram(unittest.TestCase):\n def test_case_1(self):\n one = \"algoexpert\"\n two = \"your-dream-job\"\n three = \"your-algodream-expertjob\"\n self.assertEqual(program.interweavingStrings(one, two, three), True)\n","sub_path":"testing/testInterweavingStrings.py","file_name":"testInterweavingStrings.py","file_ext":"py","file_size_in_byte":315,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"225220350","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon May 25 11:15:52 2015\n\n@author: larry\n\"\"\"\n\nimport pygame\nimport sprite_anime\n\n\nclass normal_pirate(sprite_anime.main_anime):\n \n def __init__(self, initial_coor, frames):\n super(normal_pirate, self).__init__(initial_coor, frames)\n \n \n self.name = 'normal_pirate'\n self.level = 1\n self.strength = 1\n self.speed_mag = 1 \n\n self.safe_distance = 50\n self.coor = initial_coor\n \n #override the default speed in super class\n self.speed_mag = 1 #in pixels per frame\n self.speed_comp = 0.707 * self.speed_mag #normalize to 1/sqrt(2)\n self.speed_list = [(self.speed_mag, 0), (-self.speed_mag, 0), \n (0, -self.speed_mag), (0, self.speed_mag), \n (self.speed_comp, -self.speed_comp),\n (-self.speed_comp, -self.speed_comp), \n (-self.speed_comp, self.speed_comp),\n (self.speed_comp, self.speed_comp), (0,0)]\n \n def update(self, player_coor):\n '''\n this function determines the bot's behaviour. For a normal pirate,\n it chases the player until it reaches some safe distance where it can\n attack\n '''\n #first reset the direction\n self.directions_down = [False] * 9\n x_offset = player_coor[0] - self.coor[0]\n y_offset = player_coor[1] - self.coor[1]\n dist_offset = ((player_coor[0] - self.coor[0])**2.0 + \n (player_coor[1] - self.coor[1])**2.0)**(0.5)\n \n \n #determine the best way to stay away from the player if too closed\n if dist_offset < self.safe_distance:\n current_max = dist_offset\n max_ind = 0\n for i in range(8):\n temp_offset = ((player_coor[0] - self.coor[0] - \n self.speed_list[i][0])**2.0 + \n (player_coor[1] - self.coor[1] - \n self.speed_list[i][1])**2.0)**(0.5)\n if temp_offset > current_max:\n current_max = temp_offset\n max_ind = i\n self.directions_down[max_ind] = True\n \n keys_list = [False, self.directions_down]\n super(normal_pirate, self).update(keys_list)\n return None\n \n #if too far from the player, try to gap close\n if x_offset >= 0:\n #turn right to chase the player\n self.directions_down[0] = True\n else:\n self.directions_down[1] = True\n if y_offset >= 0:\n self.directions_down[3] = True\n else:\n self.directions_down[2] = True\n \n keys_list = [False, self.directions_down]\n super(normal_pirate, self).update(keys_list)\n return None\n \n \n def draw(self, surface, player_coor):\n #first update the coor \n self.update(player_coor)\n sprite_image_blit, self.coor = super(normal_pirate, \n self).current_coor()\n \n surface.blit(sprite_image_blit, self.coor)\n \n \n ","sub_path":"ai.py","file_name":"ai.py","file_ext":"py","file_size_in_byte":3307,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"356515476","text":"from rest_framework import status\nfrom rest_framework.permissions import IsAuthenticated\nfrom rest_framework.response import Response\nfrom rest_framework.views import APIView\nfrom building.models import Building, Apartment\nfrom building.serializers import BuildingSerializer, ApartmentSerializer\nfrom owner.middlewares import JWTAuthorization\n\n\nclass ManageBuildingView(APIView):\n authentication_classes = [JWTAuthorization]\n permission_classes = [IsAuthenticated]\n\n def get(self, request, building_id=None):\n if not building_id:\n return self._fetch_buildings(request)\n\n return self._fetch_building_by_id(request, building_id)\n\n def _fetch_buildings(self, request):\n owner = request.user\n limit = request.query_params.get(\"limit\", 10)\n offset = request.query_params.get(\"offset\", 0)\n\n buildings_query = Building.objects.filter(\n tower__apartment__owner=owner)\n serialized = BuildingSerializer(\n buildings_query.all()[limit:offset],\n many=True)\n\n return Response(serialized.data, headers={\n \"X-Total-Count\": buildings_query.count()\n })\n\n def _fetch_building_by_id(self, request, building_id):\n building = Building.objects.filter(\n id=building_id,\n tower__apartment__owner=request.user).first()\n if not building:\n return Response({\n \"message\": \"Building not found\"\n }, status.HTTP_404_NOT_FOUND)\n\n serialized = BuildingSerializer(building)\n return Response(serialized.data)\n\n\nclass ManageApartmentView(APIView):\n authentication_classes = [JWTAuthorization]\n permission_classes = [IsAuthenticated]\n\n def get(self, request, building_id):\n owner = request.user\n limit = request.query_params.get(\"limit\", 10)\n offset = request.query_params.get(\"offset\", 0)\n\n apartments_query = Apartment.objects.filter(\n tower__building__id=building_id,\n owner=owner)\n\n serialized = ApartmentSerializer(apartments_query.all(), many=True)\n return Response(serialized.data, headers={\n \"X-Total-Count\": apartments_query.count()\n })\n","sub_path":"building/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2218,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"522380798","text":"#!/usr/bin/python3\nfrom sys import stdin\nfrom heapq import heappush, heappop\n\ndef main ():\n read = stdin.readline\n t = int (read ())\n for t_ in range (t):\n n = int (read ())\n a = list (map (int, read ().split ()))\n b = list (map (int, read ().split ()))\n a_b = [sm for sm, b in sorted ([(a + b, b) for a, b in zip (a, b )], key = lambda x: x [1])]\n ans = 0\n sumb = sum (b)\n h = []\n heappush (h, -a_b [0])\n for i in range (1, n - 1, 2):\n ans -= heappop (h)\n heappush (h, -a_b [i])\n heappush (h, -a_b [i + 1])\n ans -= heappop (h)\n print (ans - sumb)\n\nif __name__ == \"__main__\": main ()","sub_path":"_an_interesting_game.py","file_name":"_an_interesting_game.py","file_ext":"py","file_size_in_byte":702,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"497383709","text":"import pandas as pd\nimport json\ndf = pd.read_csv('C:/Coursera/mumbai_wr/ready_for_plot_all.csv')\ngeojson = {\n 'type': 'FeatureCollection',\n 'features': []\n }\nfor row in range(0,len(df.index.tolist())):\n geojson['features'].append({\n 'type': 'Feature',\n\t'geometry': {\n 'type': 'Point',\n\t 'coordinates': [float(df.iloc[row,5]), float(df.iloc[row,6])]\n },\n\t'properties':{\n 'service':df.iloc[row,3],\n 'time': float(df.iloc[row,1]),\n 'speed': str(df.iloc[row,7])\n }\n })\n \nwith open('C:/Coursera/mumbai_wr/all.geojson', 'w') as f:\n f.write(json.dumps(geojson))\n\nls = pd.read_csv('C:/Coursera/mumbai_wr/station_metadata.csv')\n\n\ngeojson = {\n \"type\": \"FeatureCollection\",\n \"features\": [{\n \"type\": \"Feature\",\n \"geometry\": {\n \"type\": \"LineString\"\n },\n \"properties\":{}\n }]\n}\n\n\ncoordinates = list()\n\nfor row in range(0,len(ls.index.tolist())):\n coordinates.append([float(ls.iloc[row,3]),float(ls.iloc[row,2])])\n geojson['features'].append({\n \"type\":\"Feature\",\n \"geometry\":{\n \"type\":\"Point\",\n \"coordinates\":[float(ls.iloc[row,3]),float(ls.iloc[row,2])]\n },\n \"properties\":{\n \"station\":ls.iloc[row,0]\n }\n }\n )\n\ngeojson['features'][0]['geometry']['coordinates']=coordinates\n\n\nwith open('C:/Coursera/mumbai_wr/linestring_all.geojson', 'w') as f:\n f.write(json.dumps(geojson))\n\n\n\n\n\n\n\n","sub_path":"geojson.py","file_name":"geojson.py","file_ext":"py","file_size_in_byte":1509,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"596154354","text":"import os\nimport psycopg2\n\nfrom datetime import datetime\nfrom psycopg2._psycopg import connection\nfrom psycopg2._psycopg import cursor\nfrom psycopg2.extras import RealDictCursor\nfrom source.interface import SourceInterface\n\n\nclass DefaultSource(SourceInterface):\n table_guild_registry = 'guild_registry'\n\n def _connect(self) -> connection:\n return psycopg2.connect(\n dbname=os.environ['DB_DATABASE'],\n user=os.environ['DB_USER'],\n password=os.environ['DB_PASSWORD'],\n host=os.environ['DB_HOST'],\n port=os.environ['DB_PORT'])\n\n def deactivate_guild(self, guild_id):\n curs: cursor = self._conn.cursor()\n curs.execute(\n 'UPDATE ' + self.table_guild_registry + ' SET active = %s, deactivated_at = %s WHERE id = %s',\n [False, datetime.now(), guild_id])\n self._conn.commit()\n curs.close()\n\n def register_guild(self, guild_id) -> bool:\n registered = True\n curs: cursor = self._conn.cursor(cursor_factory=RealDictCursor)\n curs.execute('SELECT id, active FROM ' + self.table_guild_registry + ' WHERE id = %s', [guild_id])\n if curs.rowcount == 0:\n curs.execute('INSERT INTO ' + self.table_guild_registry + ' (id) VALUES (%s)', [guild_id])\n else:\n result = curs.fetchone()\n if result['active'] is False:\n curs.execute('UPDATE ' + self.table_guild_registry + ' SET active = %s WHERE id = %s', [True, guild_id])\n else:\n registered = False\n self._conn.commit()\n curs.close()\n return registered\n","sub_path":"source/default.py","file_name":"default.py","file_ext":"py","file_size_in_byte":1634,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"418716512","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# PYTHON_ARGCOMPLETE_OK\n\n# Copyright: (c) 2020 Jordan Borean (@jborean93) <jborean93@gmail.com>\n# MIT License (see LICENSE or https://opensource.org/licenses/MIT)\n\n\"\"\"\nScript that can read a Wireshark capture .pcapng for a WinRM exchange and decrypt the messages. Currently only supports\nexchanges that were authenticated with NTLM. This is really a POC, a lot of things are missing like NTLMv1 support,\nshorter signing keys, better error handling, etc.\n\"\"\"\n\nfrom __future__ import (absolute_import, division, print_function)\n__metaclass__ = type\n\nimport argparse\nimport base64\nimport hashlib\nimport hmac\nimport os\nimport pyshark\nimport struct\nimport xml.dom.minidom\n\nfrom cryptography.hazmat.primitives.ciphers import (\n algorithms,\n Cipher,\n)\n\nfrom cryptography.hazmat.backends import (\n default_backend,\n)\n\ntry:\n import argcomplete\nexcept ImportError:\n argcomplete = None\n\n\nclass SecurityContext:\n\n def __init__(self, port, nt_hash):\n self.port = port\n self.tokens = []\n self.nt_hash = nt_hash\n self.complete = False\n\n self.key_exch = False\n self.session_key = None\n self.sign_key_initiate = None\n self.sign_key_accept = None\n self.seal_handle_initiate = None\n self.seal_handle_accept = None\n\n self.__initiate_seq_no = 0\n self.__accept_seq_no = 0\n\n @property\n def _initiate_seq_no(self):\n val = self.__initiate_seq_no\n self.__initiate_seq_no += 1\n return val\n\n @property\n def _accept_seq_no(self):\n val = self.__accept_seq_no\n self.__accept_seq_no += 1\n return val\n\n def add_token(self, token):\n self.tokens.append(token)\n\n if token.startswith(b\"NTLMSSP\\x00\\x03\"):\n # Extract the info required to build the session key\n nt_challenge = self._get_auth_field(20, token)\n b_domain = self._get_auth_field(28, token) or b\"\"\n b_username = self._get_auth_field(36, token) or b\"\"\n encrypted_random_session_key = self._get_auth_field(52, token)\n flags = struct.unpack(\"<I\", token[60:64])[0]\n\n encoding = 'utf-16-le' if flags & 0x00000001 else 'windows-1252'\n domain = b_domain.decode(encoding)\n username = b_username.decode(encoding)\n\n # Derive the session key\n nt_proof_str = nt_challenge[:16]\n response_key_nt = hmac_md5(self.nt_hash, (username.upper() + domain).encode('utf-16-le'))\n key_exchange_key = hmac_md5(response_key_nt, nt_proof_str)\n self.key_exch = bool(flags & 0x40000000)\n\n if self.key_exch and (flags & (0x00000020 | 0x00000010)):\n self.session_key = rc4k(key_exchange_key, encrypted_random_session_key)\n\n else:\n self.session_key = key_exchange_key\n\n # Derive the signing and sealing keys\n self.sign_key_initiate = signkey(self.session_key, 'initiate')\n self.sign_key_accept = signkey(self.session_key, 'accept')\n self.seal_handle_initiate = rc4init(sealkey(self.session_key, 'initiate'))\n self.seal_handle_accept = rc4init(sealkey(self.session_key, 'accept'))\n self.complete = True\n\n def unwrap_initiate(self, data):\n return self._unwrap(self.seal_handle_initiate, self.sign_key_initiate, self._initiate_seq_no, data)\n\n def unwrap_accept(self, data):\n return self._unwrap(self.seal_handle_accept, self.sign_key_accept, self._accept_seq_no, data)\n\n def _unwrap(self, handle, sign_key, seq_no, data):\n header = data[4:20]\n enc_data = data[20:]\n dec_data = handle.update(enc_data)\n\n b_seq_num = struct.pack(\"<I\", seq_no)\n\n checksum = hmac_md5(sign_key, b_seq_num + dec_data)[:8]\n if self.key_exch:\n checksum = handle.update(checksum)\n actual_header = b\"\\x01\\x00\\x00\\x00\" + checksum + b_seq_num\n\n if header != actual_header:\n raise Exception(\"Signature verification failed\")\n\n return dec_data\n\n def _get_auth_field(self, offset, token):\n field_len = struct.unpack(\"<H\", token[offset:offset + 2])[0]\n if field_len:\n field_offset = struct.unpack(\"<I\", token[offset + 4:offset + 8])[0]\n return token[field_offset:field_offset + field_len]\n\n\ndef hmac_md5(key, data):\n return hmac.new(key, data, digestmod=hashlib.md5).digest()\n\n\ndef md4(m):\n return hashlib.new('md4', m).digest()\n\n\ndef md5(m):\n return hashlib.md5(m).digest()\n\n\ndef ntowfv1(password):\n return md4(password.encode('utf-16-le'))\n\n\ndef rc4init(k):\n arc4 = algorithms.ARC4(k)\n return Cipher(arc4, mode=None, backend=default_backend()).encryptor()\n\n\ndef rc4k(k, d):\n return rc4init(k).update(d)\n\n\ndef sealkey(session_key, usage):\n direction = b\"client-to-server\" if usage == 'initiate' else b\"server-to-client\"\n return md5(session_key + b\"session key to %s sealing key magic constant\\x00\" % direction)\n\n\ndef signkey(session_key, usage):\n direction = b\"client-to-server\" if usage == 'initiate' else b\"server-to-client\"\n return md5(session_key + b\"session key to %s signing key magic constant\\x00\" % direction)\n\n\ndef unpack_message(data):\n parts = data.split(b'--Encrypted Boundary\\r\\n')\n parts = list(filter(None, parts))\n messages = []\n for i in range(0, len(parts), 2):\n header = parts[i].strip()\n payload = parts[i + 1]\n length = int(header.split(b\"Length=\")[1])\n # remove the end MIME block if it exists\n if payload.endswith(b\"--Encrypted Boundary--\\r\\n\"):\n payload = payload[:len(payload) - 24]\n wrapped_data = payload.replace(b\"Content-Type: application/octet-stream\\r\\n\", b\"\")\n messages.append((length, wrapped_data))\n return messages\n\n\ndef pretty_xml(xml_str):\n dom = xml.dom.minidom.parseString(xml_str)\n return dom.toprettyxml()\n\n\ndef main():\n \"\"\"Main program entry point.\"\"\"\n args = parse_args()\n\n if args.password:\n nt_hash = ntowfv1(args.password)\n else:\n nt_hash = base64.b16decode(args.hash.upper())\n\n captures = pyshark.FileCapture(os.path.expanduser(os.path.expandvars(args.path)),\n display_filter='http and tcp.port == %d' % args.port)\n\n contexts = []\n iFileData = 0\n for cap in captures:\n try:\n source_port = int(cap.tcp.srcport)\n unique_port = source_port if source_port != args.port else int(cap.tcp.dstport)\n\n auth_token = None\n if hasattr(cap.http, 'authorization'):\n b64_token = cap.http.authorization.split(' ')[1]\n auth_token = base64.b64decode(b64_token)\n\n elif hasattr(cap.http, 'www_authenticate'):\n b64_token = cap.http.www_authenticate.split(' ')[1]\n auth_token = base64.b64decode(b64_token)\n\n context = None\n if auth_token:\n if not auth_token.startswith(b\"NTLMSSP\\x00\"):\n continue\n\n if auth_token.startswith(b\"NTLMSSP\\x00\\x01\"):\n context = SecurityContext(unique_port, nt_hash)\n contexts.append(context)\n\n else:\n context = [c for c in contexts if c.port == unique_port][-1]\n if not context:\n raise ValueError(\"Missing existing NTLM security context\")\n\n context.add_token(auth_token)\n\n if hasattr(cap.http, 'file_data'):\n if not context:\n context = next(c for c in contexts if c.port == unique_port)\n\n if not context.complete:\n raise ValueError(\"Cannot decode message without completed context\")\n\n # PyShark la caga al no coger todo el file_data con los datos cifrados\n #file_data = cap.http.file_data.binary_value\n #file_data = cap.http.file_data\n #print(file_data)\n #messages = unpack_message(file_data)\n with open(\"./parseos/file_data_{}.bin\".format(iFileData), \"rb\") as inp:\n messages = [inp.read()]\n iFileData += 1\n\n unwrap_func = context.unwrap_accept if source_port == args.port else context.unwrap_initiate\n\n dec_msgs = []\n for enc_data in messages:\n msg = unwrap_func(enc_data)\n #if len(msg) != length:\n # raise ValueError(\"Message decryption failed\")\n\n dec_msgs.append(pretty_xml(msg.decode('utf-8')))\n\n dec_msgs = \"\\n\".join(dec_msgs)\n print(\"No: %s | Time: %s | Source: %s | Destination: %s\\n%s\\n\"\n % (cap.number, cap.sniff_time.isoformat(), cap.ip.src_host, cap.ip.dst_host, dec_msgs))\n\n\n except Exception as e:\n print(\"Failed to process frame: %s\" % cap.number)\n #raise Exception(\"Failed to process frame: %s\" % cap.number) from e\n\n\ndef parse_args():\n \"\"\"Parse and return args.\"\"\"\n parser = argparse.ArgumentParser(description='Parse network captures from WireShark and decrypts the WinRM '\n 'messages that were exchanged.')\n\n parser.add_argument('path',\n type=str,\n help='The path to the .pcapng file to decrypt.')\n\n parser.add_argument('--port',\n dest='port',\n default=5985,\n type=int,\n help='The port to scan for the WinRM HTTP packets (default: 5985).')\n\n secret = parser.add_mutually_exclusive_group()\n\n secret.add_argument('-p', '--password',\n dest='password',\n help='The password for the account that was used in the authentication.')\n\n secret.add_argument('-n', '--hash',\n dest='hash',\n help='The NT hash for the account that was used in the authentication.')\n\n if argcomplete:\n argcomplete.autocomplete(parser)\n\n return parser.parse_args()\n\n\nif __name__ == '__main__':\n main()","sub_path":"2021-HTBxUni-Quals/solvers/forensics_keep_the_steam/winrm_decrypt.py","file_name":"winrm_decrypt.py","file_ext":"py","file_size_in_byte":10264,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"2406889","text":"# Задание-1:\n# Напишите функцию, возвращающую ряд Фибоначчи с n-элемента до m-элемента.\n# Первыми элементами ряда считать цифры 1 1\n\ndef fibonacci(n, m):\n \"\"\"\n\n :param n:\n :param m:\n :return:\n \"\"\"\n f=[1,1]\n for a in range(1,m-1):\n f.append(f[a-1]+f[a])\n return f[n-1:m]\n\nprint(fibonacci(6,12))\n\n# Задача-2:\n# Напишите функцию, сортирующую принимаемый список по возрастанию.\n# Для сортировки используйте любой алгоритм (например пузырьковый).\n# Для решения данной задачи н��льзя использовать встроенную функцию и метод sort()\n\n\ndef sort_to_max(origin_list):\n \"\"\"\n Сортирует список по возростанию\n :param origin_list:\n :return:\n \"\"\"\n\n n=len(origin_list)\n\n ind=1\n while ind:\n ind=0\n for j in range(1,n):\n if origin_list[j-1]>origin_list[j]:\n origin_list[j - 1] , origin_list[j]=origin_list[j],origin_list[j-1]\n ind=1\n return origin_list\n\n\nsort_ist = sort_to_max([2, 10, -12, 2.5, 20, -11, 4, 4, 0,-15,43])\nprint(sort_ist)\n\n# Задача-3:\n# Напишите собственную реализацию стандартной функции filter.\n# Разумеется, внутри нельзя использовать саму функцию filter.\n\nitm=[1, 3, \"list\", True, 20.2, 4, -4, \"func\", False, 6, 7, 10, 12, -15]\n\ndef filter_int(origin_list):\n \"\"\"\n фильтр возращает целые числа > 0\n :param origin_list: список\n :return: список\n \"\"\"\n or_lst=[]\n for t in origin_list:\n if type(t)== int and t>0:\n or_lst.append(t)\n return or_lst\n\nprint(filter_int(itm))\n\n\n\n\n# Задача-4:\n# Даны четыре точки А1(х1, у1), А2(x2 ,у2), А3(x3 , у3), А4(х4, у4).\n# Определить, будут ли они вершинами параллелограмма.\n\n\ndef polygon(*args):\n \"\"\"\n Функция по вершинам определяет параллелограмм\n :param point1:\n :param point2:\n :param point3:\n :param point4:\n :return:\n \"\"\"\n a=[i for i in args]\n a.sort()\n # print(a, a[1][0])\n if a[0][0]+a[3][0] == a[1][0]+a[2][0] and a[0][1]+a[3][1] == a[1][1]+a[2][1]:\n return True\n\na1=[5,8]\na2=[2,12]\na3=[3,17]\na4=[6,13]\n\nprint(polygon(a1,a2,a3,a4))\n","sub_path":"lesson03/home_work/hw03_normal.py","file_name":"hw03_normal.py","file_ext":"py","file_size_in_byte":2628,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"471336347","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Nov 9 23:10:37 2017\n\n@author: rimikamajumdar\n\"\"\"\n\n# What was that?\n\n\ntabby_cat = \"\\tI'm tabbed in.\"\npersian_cat = \"I'm spilt\\non a line\"\nbackslash_cat = \"I'm \\\\ a \\\\ cat.\"\n\nfat_cat =\"\"\"\nI''ll do a list:\n\\t* Cat food\n\\t* Fishies\n\\t* Catnip\\n\\t* Grass\n\"\"\"\n\nprint(tabby_cat)\nprint(persian_cat)\nprint(backslash_cat)\nprint(fat_cat)\n","sub_path":"rimika/ex10.py","file_name":"ex10.py","file_ext":"py","file_size_in_byte":395,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"317739805","text":"# coding=utf-8\nfrom tkinter import *\n\n\ndef main():\n root = Tk()\n root.geometry(\"500x500\")\n list_box = Listbox(root, width=300)\n list_box.insert(3, 'cc')\n list_box.pack()\n list_box.insert(5, 'dd')\n\n def bindListBox(event):\n w = event.widget\n cur = w.curselection() # 返回的是list\n if len(cur):\n for i in cur:\n print (list_box.get(i))\n\n\n # 右键点击事件\n list_box.bind('<Button-3>', bindListBox)\n\n root.mainloop()\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"gui/tkinter/day007/day007.py","file_name":"day007.py","file_ext":"py","file_size_in_byte":539,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"623605933","text":"import sys\r\nimport webbrowser\r\ndef lyric_game():\r\n print('Welcome to the Lyric Game! All you have to do is guess the lyrics and complete the levels. Good luck!')\r\n print('I only love my ___ and my momma.')\r\n guess = raw_input('Guess the lyric:')\r\n lyric = 'bed'\r\n if guess == lyric:\r\n print('Good job! now let us make it a little harder')\r\n else:\r\n print('oh no!, wrong guess!')\r\n sys.exit()\r\n print('One, don not pick up the phone, you know he is only calling cause he is drunk and ___')\r\n guess = raw_input('Guess the lyric:')\r\n lyric = 'alone'\r\n if guess == lyric:\r\n print('Good job! now let us make it a little harder')\r\n else:\r\n print('oh no!, wrong guess!')\r\n sys.exit()\r\n print(\"You just want attention, you don't want my _____. \")\r\n guess = raw_input('Guess the lyric:')\r\n lyric = 'heart'\r\n if guess == lyric:\r\n print('Good job! now let us make it a little harder')\r\n else:\r\n print('oh no!, wrong guess!')\r\n sys.exit()\r\n print(\"Half of my heart is in ______.\")\r\n guess = raw_input('Guess the lyric:')\r\n lyric = 'havana'\r\n if guess == lyric:\r\n print('Good job! now let us make it a little harder')\r\n else:\r\n print('oh no!, wrong guess!')\r\n sys.exit()\r\n print(\"While we're young dumb. Young, young dumb and _____. \")\r\n guess = raw_input('Guess the lyric:')\r\n lyric = 'broke'\r\n if guess == lyric:\r\n print('Good job! now let us make it a little harder')\r\n else:\r\n print('oh no!, wrong guess!')\r\n sys.exit()\r\n print(\"Never gonna let you down, Never gonna run around and _____ you\")\r\n guess = raw_input('Guess the lyric:')\r\n lyric = 'desert'\r\n if guess == lyric:\r\n webbrowser.open(\"https://www.youtube.com/watch?v=dQw4w9WgXcQ\")\r\n print('Good job! now let us make it a little harder')\r\n else:\r\n print('oh no!, wrong guess!')\r\n print(\"Well, the years start coming and they don't stop coming, ___ to the rules and I hit the ground running\")\r\n guess = raw_input('Guess the lyric:')\r\n lyric = 'fed'\r\n if guess == lyric:\r\n webbrowser.open('https://youtu.be/L_jWHffIx5E')\r\n print('Good job')\r\n else:\r\n print('oh no!, wrong guess!')\r\n sys.exit()","sub_path":"images/images/images/LYRICGAME.py","file_name":"LYRICGAME.py","file_ext":"py","file_size_in_byte":2301,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"506636309","text":"from django.contrib.auth import authenticate, login, logout\nfrom django.core.exceptions import ObjectDoesNotExist\nfrom django.db import IntegrityError\nfrom django.http import HttpResponse, HttpResponseRedirect\nfrom django.shortcuts import render\nfrom django.urls import reverse\nfrom .models import User, Listings, Bid, ListingComment, Categories, WatchList\nfrom . import helpers\n\n\ndef index(request):\n\n return render(request, \"auctions/index.html\", {\n \"listings\": Listings.objects.filter(isClosed=False),\n })\n\n\ndef login_view(request):\n if request.method == \"POST\":\n\n # Attempt to sign user in\n username = request.POST[\"username\"]\n password = request.POST[\"password\"]\n user = authenticate(request, username=username, password=password)\n\n # Check if authentication successful\n if user is not None:\n login(request, user)\n return HttpResponseRedirect(reverse(\"index\"))\n else:\n return render(request, \"auctions/login.html\", {\n \"message\": \"Invalid username and/or password.\"\n })\n else:\n return render(request, \"auctions/login.html\")\n\n\ndef logout_view(request):\n logout(request)\n return HttpResponseRedirect(reverse(\"index\"))\n\n\ndef register(request):\n if request.method == \"POST\":\n username = request.POST[\"username\"]\n email = request.POST[\"email\"]\n\n # Ensure password matches confirmation\n password = request.POST[\"password\"]\n confirmation = request.POST[\"confirmation\"]\n if password != confirmation:\n return render(request, \"auctions/register.html\", {\n \"message\": \"Passwords must match.\"\n })\n\n # Attempt to create new user\n try:\n user = User.objects.create_user(username, email, password)\n user.save()\n except IntegrityError:\n return render(request, \"auctions/register.html\", {\n \"message\": \"Username already taken.\"\n })\n login(request, user)\n return HttpResponseRedirect(reverse(\"index\"))\n else:\n return render(request, \"auctions/register.html\")\n\ndef create(request):\n if (not request.user.is_authenticated):\n return HttpResponseRedirect(reverse('index'))\n\n if request.method == \"POST\":\n title = request.POST[\"title\"]\n description = request.POST[\"description\"]\n bid = request.POST[\"bid\"]\n url = request.POST[\"url\"]\n category = None\n if request.POST[\"category\"] != '':\n newcategory = Categories(Categories=request.POST[\"category\"])\n newcategory.save()\n category = newcategory\n\n\n listing = Listings(title=title, description=description, bid=bid, url=url, by=request.user.username, category=category)\n listing.save()\n return HttpResponseRedirect(reverse('index'))\n\n return render(request, \"auctions/createListing.html\")\n\ndef listing(request, listing_id):\n\n try:\n listing = Listings.objects.get(id=listing_id)\n except ObjectDoesNotExist:\n return HttpResponseRedirect(reverse('index'))\n\n if listing.by == request.user.username:\n isCurrent = True\n else:\n isCurrent = False\n\n bidInfo = helpers.getBidInfo(Bid, listing, request)\n comments = helpers.getComments(ListingComment, listing, request)\n isWatched = helpers.checkWatching(WatchList, listing, request)\n\n if request.method == \"POST\":\n if 'watchlist' in request.POST:\n if(request.POST['watchlist'] == \"add\"):\n if (not isWatched):\n added = WatchList(listing=listing, savedby=request.user.username)\n added.save()\n isWatched = True\n else:\n if (isWatched):\n removed = WatchList.objects.get(listing=listing, savedby=request.user.username)\n removed.delete()\n isWatched = False\n\n return render(request, \"auctions/listing.html\", {\n 'data': listing,\n \"bidInfo\": bidInfo,\n \"isCurrent\": isCurrent,\n \"comments\": comments,\n \"isWatched\": isWatched,\n })\n\n if \"finish\" in request.POST and request.POST[\"finish\"] == 'end':\n bidInfo = helpers.getBidInfo(Bid, listing, request)\n winner = bidInfo[\"winner\"]\n if winner == None:\n winner = request.user.username\n \n Listings.objects.filter(pk=listing_id).update(isClosed=True, winner=winner)\n listing=Listings.objects.get(id=listing_id)\n return render(request, \"auctions/listing.html\", {\n 'data': listing,\n \"success\": \"This Auction has Been Finished\",\n \"comments\": comments,\n \"isWatched\": isWatched,\n })\n \n if \"comment\" in request.POST:\n newComment = ListingComment(by=request.user.username, listing=listing, message=request.POST[\"comment\"])\n newComment.save()\n bidInfo = helpers.getBidInfo(Bid, listing, request)\n comments = helpers.getComments(ListingComment, listing, request)\n return render(request, \"auctions/listing.html\", {\n 'data': listing,\n \"bidInfo\": bidInfo,\n \"isCurrent\": isCurrent,\n \"comments\": comments,\n \"isWatched\": isWatched,\n })\n \n\n amount = request.POST[\"bid\"]\n if float(amount) <= float(listing.bid):\n return render(request, \"auctions/listing.html\", {\n 'data': listing,\n \"message\": \"You're Bidding Too Less\",\n \"bidInfo\": bidInfo,\n \"isCurrent\": isCurrent,\n \"comments\": comments,\n \"isWatched\": isWatched,\n })\n\n Listings.objects.filter(pk=listing_id).update(bid=amount)\n listing=Listings.objects.get(id=listing_id)\n\n by = request.user.username\n newBid = Bid(by=by, amount=amount, listing=listing)\n newBid.save()\n\n bidInfo = helpers.getBidInfo(Bid, listing, request)\n\n return render(request, \"auctions/listing.html\", {\n 'data': listing,\n \"success\": \"Success!\",\n \"bidInfo\": bidInfo,\n \"isCurrent\": isCurrent,\n \"comments\": comments,\n \"isWatched\": isWatched,\n })\n\n return render(request, \"auctions/listing.html\", {\n 'data': listing,\n \"bidInfo\": bidInfo,\n \"isCurrent\": isCurrent,\n \"comments\": comments,\n \"isWatched\": isWatched,\n })\n\ndef watchList(request):\n if not request.user.is_authenticated:\n return HttpResponseRedirect(reverse(index))\n \n watched = WatchList.objects.filter(savedby=request.user.username)\n\n return render(request, 'auctions/watchList.html', {\n \"list\": watched\n })\n\ndef categories(request):\n allcategories = Categories.objects.all()\n\n return render(request, 'auctions/categories.html', {\n 'catlist' : allcategories\n })\n\ndef catListings(request, catname):\n obtained = Categories.objects.get(Categories=catname)\n all = Listings.objects.filter(category=obtained)\n\n return render(request, 'auctions/catListings.html', {\n 'name': catname,\n 'list': all,\n })","sub_path":"auctions/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":7407,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"151876633","text":"# Final Project\n#\n# Author : Rajarshi Biswas\n# Sayam Ganguly\n\nimport _pickle as pickle\nimport glob\nimport tweepy as tp\nimport pandas as pd\nfrom tweepy import Stream\nfrom tweepy.streaming import StreamListener\nfrom nltk.corpus import stopwords\nfrom nltk.tokenize import word_tokenize\nfrom nltk.stem import PorterStemmer\nimport string\nimport sys\n\n\ndef tokenize(words):\n return word_tokenize(words)\n \n \ndef stem(token_list):\n ps = PorterStemmer()\n return [ps.stem(tok) for tok in token_list]\n \n\ndef remove_stopwords(words):\n stop_words = set(stopwords.words('english'))\n stop_words.add(\"new\")\n stop_words.add(\"say\")\n stop_words.add(\"may\")\n stop_words.add(\"rt\")\n words = [w for w in words if not w in stop_words]\n return words\n \n \ndef remove_punctuations(words):\n table = str.maketrans({key: None for key in string.punctuation})\n return words.translate(table)\n \n \ndef remove_digits(words):\n table = str.maketrans({key: None for key in string.digits})\n return words.translate(table)\n \n \ndef preprocess(text):\n text = text.lower()\n text = remove_punctuations(text)\n text = remove_digits(text)\n token_list = tokenize(text)\n token_list = stem(token_list)\n token_list = remove_stopwords(token_list)\n text = ' '.join(token_list)\n return text\n\nclass listener(StreamListener):\n def on_data(self,data):\n text = data.split(',\"text\":\"')[1].split('\",\"')[0]\n classify(text)\n return True\n def on_error(self,status):\n print(\"error\")\n print(status)\n\n\ndef load_models():\n for file in glob.glob(\"*.sav\"):\n model = pickle.load(open(file,'rb'))\n vectorizer = pickle.load(open(file[:-4]+'.pk','rb'))\n tup = (model,vectorizer)\n models.append(tup)\n \n\ndef connect_twitter():\n consumer_key = \"AzmC1JpWz5MgLIzUXAgK7B6mE\"\n consumer_secret = \"TVbaKM8sOgHqh4gWvgtU2WshnOQC4SMIgzcIEk0NO2RgKrWzhy\"\n access_token = '147602744-HS3qk582GtDvWAfYKRLkAgt3znXxSxbwWjBHuUPg'\n access_token_secret = 'F03uQ3m4kpRQllZrMHm8gYbS56OMDyrd8UP79USihcWFS'\n auth =tp.OAuthHandler(consumer_key = consumer_key, consumer_secret = consumer_secret)\n auth.set_access_token(access_token,access_token_secret)\n twitterStream = Stream(auth,listener())\n return twitterStream\n \ndef classify(text):\n global prediction_result ,twitterStream\n prediction = []\n print(text)\n prediction.append(text)\n text = preprocess(text)\n for model in models:\n l = []\n l.append(text)\n l = model[1].transform(l)\n x = model[0].predict(l)\n prediction.append(class_name[x[0]])\n d = {colNames[0]:prediction[0],colNames[1]:prediction[1],\n colNames[2]:prediction[2]}\n prediction_result = prediction_result.append(d,\n ignore_index = True)\n if(prediction_result.shape[0] == 50):\n prediction_result.to_csv(\"Twitter_Prediction_Result.csv\")\n sys.exit(\"Thanks for Using Twitter_Predict!!!\")\n\n \nmodels = []\nload_models()\ncolNames = [\"Twitter Text\",\"Multinomial Naive Bayes\",\n \"Logistic Regression\"]\nprediction_result = pd.DataFrame(columns=colNames)\ntwitterStream = connect_twitter()\nclass_name = {'b':'Business','e':'Entertainment',\n 't':'Technology','m':'Health'}\ntwitterStream.filter(track=[\"google\", \"apple\", \"microsoft\", \"facebook\"],languages=['en'])\n\n\n\n ","sub_path":"Final Project/Twitter_Predict.py","file_name":"Twitter_Predict.py","file_ext":"py","file_size_in_byte":3438,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"381778121","text":"import pathlib\nfrom setuptools import setup, find_packages\n\nfrom simsity import __version__\n\n\nbase_packages = [\n \"scikit-learn>=1.0.0\",\n \"pynndescent>=0.5\",\n \"numba>=0.54.1\",\n \"pandas>=1.3.3\",\n]\n\nminhash_packages = [\"datasketch>=1.5.3\"]\n\nserve_packages = [\"uvicorn>=0.15.0\", \"fastapi>=0.70.0\"]\n\ndocs_packages = [\n \"mkdocs==1.1\",\n \"mkdocs-material==4.6.3\",\n \"mkdocstrings==0.8.0\",\n \"mktestdocs==0.1.2\",\n]\n\ntest_packages = [\n \"interrogate>=1.5.0\",\n \"flake8>=3.6.0\",\n \"pytest>=4.0.2\",\n \"black>=19.3b0\",\n \"pre-commit>=2.2.0\",\n \"pyanalyze>=0.3.1\",\n \"requests>=2.26.0\",\n \"dirty_cat\",\n]\n\nall_packages = base_packages + minhash_packages + serve_packages\ndev_packages = all_packages + docs_packages + test_packages\n\n\nsetup(\n name=\"simsity\",\n version=__version__,\n author=\"Vincent D. Warmerdam\",\n packages=find_packages(exclude=[\"notebooks\", \"docs\"]),\n description=\"Simple Similarity Service\",\n long_description=pathlib.Path(\"README.md\").read_text(),\n long_description_content_type=\"text/markdown\",\n url=\"https://koaning.github.io/simsity/\",\n project_urls={\n \"Documentation\": \"https://koaning.github.io/simsity/\",\n \"Source Code\": \"https://github.com/koaning/simsity/\",\n \"Issue Tracker\": \"https://github.com/koaning/simsity/issues\",\n },\n install_requires=base_packages,\n extras_require={\"dev\": dev_packages, \"minhash\": minhash_packages},\n classifiers=[\n \"Intended Audience :: Science/Research\",\n \"Programming Language :: Python :: 3\",\n \"Programming Language :: Python :: 3.7\",\n \"Programming Language :: Python :: 3.8\",\n \"Programming Language :: Python :: 3.9\",\n \"License :: OSI Approved :: MIT License\",\n \"Topic :: Scientific/Engineering\",\n \"Topic :: Scientific/Engineering :: Artificial Intelligence\",\n ],\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1865,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"399979207","text":"from matplotlib.colors import ListedColormap\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ndef plot_decision(X, y, classifier, test_idx=None, resolution=0.02, figsize=(8,8)):\n\n # setup marker generator and color map\n markers = ('s', 'x', 'o', '^', 'v')\n colors = ('#cc0000', '#003399', '#00cc00', '#999999', '#66ffff')\n cmap = ListedColormap(colors[:len(np.unique(y))])\n \n # get dimensions\n x1_min, x1_max = X[:, 0].min() - 1, X[:, 0].max() + 1\n x2_min, x2_max = X[:, 1].min() - 1, X[:, 1].max() + 1\n xx1, xx2 = np.meshgrid(np.arange(x1_min, x1_max, resolution), np.arange(x2_min, x2_max, resolution))\n xmin = xx1.min()\n xmax = xx1.max()\n ymin = xx2.min()\n ymax = xx2.max()\n \n # create the figure\n fig, ax = plt.subplots(figsize=figsize)\n ax.set_xlim(xmin, xmax)\n ax.set_ylim(ymin, ymax)\n \n # plot the decision surface\n Z = classifier.predict(np.array([xx1.ravel(), xx2.ravel()]).T)\n Z = Z.reshape(xx1.shape)\n ax.contourf(xx1, xx2, Z, alpha=0.4, cmap=cmap, zorder=1)\n \n # plot all samples\n for idx, cl in enumerate(np.unique(y)):\n ax.scatter(x=X[y == cl, 0], \n y=X[y == cl, 1],\n alpha=0.6, \n c=cmap(idx),\n edgecolor='black',\n marker='o',#markers[idx],\n s=50,\n label=cl,\n zorder=3)\n\n # highlight test samples\n if test_idx:\n X_test, y_test = X[test_idx, :], y[test_idx]\n ax.scatter(X_test[:, 0],\n X_test[:, 1],\n c='w',\n alpha=1.0,\n edgecolor='black',\n linewidths=1,\n marker='o',\n s=150, \n label='test set',\n zorder=2)","sub_path":"Day4-DecisionTree/decision_visualisation.py","file_name":"decision_visualisation.py","file_ext":"py","file_size_in_byte":1832,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"445732527","text":"from __future__ import annotations\n\nimport os\nimport typing as t\nimport logging\nfrom types import ModuleType\nfrom typing import TYPE_CHECKING\n\nimport attr\n\nimport bentoml\nfrom bentoml import Tag\nfrom bentoml.models import Model\nfrom bentoml.models import ModelContext\nfrom bentoml.models import ModelOptions\nfrom bentoml.exceptions import NotFound\nfrom bentoml.exceptions import BentoMLException\nfrom bentoml.exceptions import MissingDependencyException\n\nfrom ..types import LazyType\nfrom ..utils.pkg import find_spec\nfrom ..utils.pkg import get_pkg_version\n\nif TYPE_CHECKING:\n from bentoml.types import ModelSignature\n\n from ..models.model import ModelSignaturesType\n from ..external_typing import transformers as ext\n\ntry:\n import transformers\nexcept ImportError: # pragma: no cover\n raise MissingDependencyException(\n \"'transformers' is required in order to use module 'bentoml.transformers'. Install transformers with 'pip install transformers'.\"\n )\n\n\n__all__ = [\"load_model\", \"save_model\", \"get_runnable\", \"get\"]\n\n\nMODULE_NAME = \"bentoml.transformers\"\nAPI_VERSION = \"v1\"\nPIPELINE_PICKLE_NAME = f\"pipeline.{API_VERSION}.pkl\"\n\n\nlogger = logging.getLogger(__name__)\n\n\ndef _check_flax_supported() -> None: # pragma: no cover\n _supported: bool = get_pkg_version(\"transformers\").startswith(\"4\")\n\n if not _supported:\n logger.warning(\n \"Detected transformers version: %s, which doesn't have supports for Flax. Update 'transformers' to 4.x and above to have Flax supported.\",\n get_pkg_version(\"transformers\"),\n )\n else:\n _flax_available = find_spec(\"jax\") is not None and find_spec(\"flax\") is not None\n if _flax_available:\n _jax_version = get_pkg_version(\"jax\")\n _flax_version = get_pkg_version(\"flax\")\n logger.info(\n \"Jax version %s, Flax version %s available.\",\n _jax_version,\n _flax_version,\n )\n else:\n logger.warning(\n \"No versions of Flax or Jax found on the current machine. In order to use Flax with transformers 4.x and above, refer to https://github.com/google/flax#quick-install\"\n )\n\n\ndef _deep_convert_to_tuple(dct: dict[str, t.Any]) -> dict[str, tuple[str, str | None]]:\n for k, v in dct.items():\n if isinstance(v, list):\n dct[k] = tuple(v) # type: ignore\n return dct\n\n\ndef _validate_type(_: t.Any, attribute: attr.Attribute[t.Any], value: t.Any) -> None:\n \"\"\"\n Validate the type of the given pipeline definition. The value is expected to be a `str`.\n `list` type is also allowed here to maintain compatibility with an earlier introduced bug.\n\n TODO: disallow list type in the next minor version release.\n \"\"\"\n if not isinstance(value, str) and not isinstance(value, list):\n raise ValueError(f\"{attribute.name} must be a string\")\n\n\n@attr.define\nclass TransformersOptions(ModelOptions):\n \"\"\"Options for the Transformers model.\"\"\"\n\n task: str = attr.field(validator=attr.validators.instance_of(str))\n tf: t.Tuple[str] = attr.field(\n validator=attr.validators.optional(\n attr.validators.deep_iterable(\n member_validator=attr.validators.instance_of(str)\n )\n ), # type: ignore\n factory=tuple,\n converter=tuple,\n )\n pt: t.Tuple[str] = attr.field(\n validator=attr.validators.optional(\n attr.validators.deep_iterable(\n member_validator=attr.validators.instance_of(str)\n )\n ), # type: ignore\n factory=tuple,\n converter=tuple,\n )\n default: t.Dict[str, t.Any] = attr.field(\n factory=dict, converter=_deep_convert_to_tuple\n )\n type: str = attr.field(\n validator=attr.validators.optional(_validate_type),\n default=None,\n )\n kwargs: t.Dict[str, t.Any] = attr.field(factory=dict)\n\n\ndef _convert_to_auto_class(cls_name: str) -> ext.BaseAutoModelClass:\n if not hasattr(transformers, cls_name):\n raise BentoMLException(\n f\"Given {cls_name} is not a valid Transformers auto class. For more information, \"\n \"please see https://huggingface.co/docs/transformers/main/en/model_doc/auto\"\n )\n return getattr(transformers, cls_name)\n\n\ndef get(tag_like: str | Tag) -> Model:\n \"\"\"\n Get the BentoML model with the given tag.\n\n Args:\n tag_like: The tag of the model to retrieve from the model store.\n\n Returns:\n :obj:`~bentoml.Model`: A BentoML :obj:`~bentoml.Model` with the matching tag.\n\n Example:\n\n .. code-block:: python\n\n import bentoml\n # target model must be from the BentoML model store\n model = bentoml.transformers.get(\"my_pipeline:latest\")\n \"\"\"\n model = bentoml.models.get(tag_like)\n if model.info.module not in (MODULE_NAME, __name__):\n raise NotFound(\n f\"Model {model.tag} was saved with module {model.info.module}, not loading with {MODULE_NAME}.\"\n )\n return model\n\n\ndef load_model(\n bento_model: str | Tag | Model,\n **kwargs: t.Any,\n) -> ext.TransformersPipeline:\n \"\"\"\n Load the Transformers model from BentoML local modelstore with given name.\n\n Args:\n bento_model (``str`` ``|`` :obj:`~bentoml.Tag` ``|`` :obj:`~bentoml.Model`):\n Either the tag of the model to get from the store, or a BentoML `~bentoml.Model`\n instance to load the model from.\n kwargs (:code:`Any`):\n Additional keyword arguments to pass to the model.\n\n Returns:\n ``Pipeline``:\n The Transformers pipeline loaded from the model store.\n\n Example:\n\n .. code-block:: python\n\n import bentoml\n pipeline = bentoml.transformers.load_model('my_model:latest')\n \"\"\"\n _check_flax_supported()\n\n if not isinstance(bento_model, Model):\n bento_model = get(bento_model)\n\n if bento_model.info.module not in (MODULE_NAME, __name__):\n raise NotFound(\n f\"Model {bento_model.tag} was saved with module {bento_model.info.module}, not loading with {MODULE_NAME}.\"\n )\n\n from transformers.pipelines import SUPPORTED_TASKS\n\n if TYPE_CHECKING:\n options = t.cast(TransformersOptions, bento_model.info.options)\n else:\n options = bento_model.info.options\n\n task: str = bento_model.info.options.task # type: ignore\n if task not in SUPPORTED_TASKS:\n try:\n import cloudpickle # type: ignore\n except ImportError: # pragma: no cover\n raise MissingDependencyException(\n \"Module `cloudpickle` is required in order to use to load custom pipelines.\"\n )\n\n with open(bento_model.path_of(PIPELINE_PICKLE_NAME), \"rb\") as f:\n pipeline = cloudpickle.load(f)\n\n SUPPORTED_TASKS[task] = {\n \"impl\": type(pipeline),\n \"tf\": tuple(\n _convert_to_auto_class(auto_class) for auto_class in options.tf\n ),\n \"pt\": tuple(\n _convert_to_auto_class(auto_class) for auto_class in options.pt\n ),\n \"default\": options.default,\n \"type\": options.type,\n }\n\n extra_kwargs: dict[str, t.Any] = options.kwargs\n extra_kwargs.update(kwargs)\n if len(extra_kwargs) > 0:\n logger.info(\n \"Loading '%s' pipeline '%s' with kwargs %s.\",\n task,\n bento_model.tag,\n extra_kwargs,\n )\n return transformers.pipeline(task=task, model=bento_model.path, **extra_kwargs)\n\n\ndef save_model(\n name: str,\n pipeline: ext.TransformersPipeline,\n task_name: str | None = None,\n task_definition: dict[str, t.Any] | None = None,\n *,\n signatures: ModelSignaturesType | None = None,\n labels: dict[str, str] | None = None,\n custom_objects: dict[str, t.Any] | None = None,\n external_modules: t.List[ModuleType] | None = None,\n metadata: dict[str, t.Any] | None = None,\n) -> bentoml.Model:\n \"\"\"\n Save a model instance to BentoML modelstore.\n\n Args:\n name: Name for given model instance. This should pass Python identifier check.\n pipeline: Instance of the Transformers pipeline to be saved.\n\n See module `src/transformers/pipelines/__init__.py <https://github.com/huggingface/transformers/blob/main/src/transformers/pipelines/__init__.py#L129>`_ for more details.\n task_name: Name of pipeline task. If not provided, the task name will be derived from ``pipeline.task``.\n task_definition: Task definition for the Transformers custom pipeline. The definition is a dictionary\n consisting of the following keys:\n\n - ``impl`` (:code:`str`): The name of the pipeline implementation module. The name should be the same as the pipeline passed in the ``pipeline`` argument.\n - ``tf`` (:code:`tuple[AnyType]`): The name of the Tensorflow auto model class. One of ``tf`` and ``pt`` auto model class argument is required.\n - ``pt`` (:code:`tuple[AnyType]`): The name of the PyTorch auto model class. One of ``tf`` and ``pt`` auto model class argument is required.\n - ``default`` (:code:`Dict[str, AnyType]`): The names of the default models, tokenizers, feature extractors, etc.\n - ``type`` (:code:`str`): The type of the pipeline, e.g. ``text``, ``audio``, ``image``, ``multimodal``.\n\n Example:\n\n .. code-block:: python\n\n task_definition = {\n \"impl\": Text2TextGenerationPipeline,\n \"tf\": (TFAutoModelForSeq2SeqLM,) if is_tf_available() else (),\n \"pt\": (AutoModelForSeq2SeqLM,) if is_torch_available() else (),\n \"default\": {\"model\": {\"pt\": \"t5-base\", \"tf\": \"t5-base\"}},\n \"type\": \"text\",\n }\n\n See module `src/transformers/pipelines/__init__.py <https://github.com/huggingface/transformers/blob/main/src/transformers/pipelines/__init__.py#L129>`_ for more details.\n signatures: Methods to expose for running inference on the target model. Signatures are used for creating :obj:`~bentoml.Runner` instances when serving model with :obj:`~bentoml.Service`\n labels: User-defined labels for managing models, e.g. ``team=nlp``, ``stage=dev``.\n custom_objects: Custom objects to be saved with the model. An example is ``{\"my-normalizer\": normalizer}``.\n\n Custom objects are currently serialized with cloudpickle, but this implementation is subject to change.\n external_modules (:code:`List[ModuleType]`, `optional`, default to :code:`None`):\n user-defined additional python modules to be saved alongside the model or custom objects,\n e.g. a tokenizer module, preprocessor module, model configuration module\n metadata: Custom metadata for given model.\n\n .. note::\n\n Both arguments ``task_name`` and ``task_definition`` must be provided to set save a custom pipeline.\n\n Returns:\n :obj:`~bentoml.Tag`: A :obj:`tag` with a format `name:version` where `name` is\n the user-defined model's name, and a generated `version`.\n\n Examples:\n\n .. code-block:: python\n\n import bentoml\n\n from transformers import pipeline, AutoTokenizer, AutoModelForCausalLM\n\n tokenizer = AutoTokenizer.from_pretrained(\"distilgpt2\")\n model = AutoModelForCausalLM.from_pretrained(\"distilgpt2\")\n generator = pipeline(task=\"text-generation\", model=model, tokenizer=tokenizer)\n bento_model = bentoml.transformers.save_model(\"text-generation-pipeline\", generator)\n \"\"\" # noqa\n _check_flax_supported()\n if not isinstance(\n pipeline,\n LazyType[\"ext.TransformersPipeline\"](\"transformers.pipelines.base.Pipeline\"), # type: ignore\n ):\n raise BentoMLException(\n \"'pipeline' must be an instance of 'transformers.pipelines.base.Pipeline'. \"\n \"To save other Transformers types like models, tokenizers, configs, feature \"\n \"extractors, construct a pipeline with the model, tokenizer, config, or feature \"\n \"extractor specified as arguments, then call save_model with the pipeline. \"\n \"Refer to https://huggingface.co/docs/transformers/main_classes/pipelines \"\n \"for more information on pipelines. If transformers doesn't provide a task you \"\n \"need, refer to the custom pipeline section to create your own pipelines.\"\n \"\"\"\n ```python\n import bentoml\n from transformers import pipeline, AutoTokenizer, AutoModelForCausalLM\n\n tokenizer = AutoTokenizer.from_pretrained(\"distilgpt2\")\n model = AutoModelForCausalLM.from_pretrained(\"distilgpt2\")\n generator = pipeline(task=\"text-generation\", model=model, tokenizer=tokenizer)\n\n bentoml.transformers.save_model(\"text-generation-pipeline\", generator)\n ```\n \"\"\"\n )\n\n context = ModelContext(\n framework_name=\"transformers\",\n framework_versions={\"transformers\": get_pkg_version(\"transformers\")},\n )\n\n if signatures is None:\n signatures = {\n \"__call__\": {\"batchable\": False},\n }\n logger.info(\n 'Using the default model signature for Transformers (%s) for model \"%s\".',\n signatures,\n name,\n )\n\n if task_name is not None and task_definition is not None:\n from transformers.pipelines import TASK_ALIASES\n from transformers.pipelines import SUPPORTED_TASKS\n\n try:\n import cloudpickle # type: ignore\n except ImportError: # pragma: no cover\n raise MissingDependencyException(\n \"Module `cloudpickle` is required in order to use to save custom pipelines.\"\n )\n\n logger.info(\n \"Arguments 'task_name' and 'task_definition' are provided. Saving model with pipeline task name '%s' and task definition '%s'.\",\n task_name,\n task_definition,\n )\n\n if pipeline.task is None or pipeline.task != task_name:\n raise BentoMLException(\n f\"Argument 'task_name' '{task_name}' does not match pipeline task name '{pipeline.task}'.\"\n )\n\n impl: type = task_definition[\"impl\"]\n if type(pipeline) != impl:\n raise BentoMLException(\n f\"Argument 'pipeline' is not an instance of {impl}. It is an instance of {type(pipeline)}.\"\n )\n\n if task_name in TASK_ALIASES:\n task_name = TASK_ALIASES[task_name]\n\n if task_name in SUPPORTED_TASKS:\n if SUPPORTED_TASKS[task_name] != task_definition:\n raise BentoMLException(\n f\"Argument `task_definition` '{task_definition}' does not match pipeline task \"\n \"definition '{SUPPORTED_TASKS[task_name]}'.\"\n )\n else:\n SUPPORTED_TASKS[task_name] = task_definition\n\n options = TransformersOptions(\n task=task_name,\n pt=tuple(\n auto_class.__qualname__ for auto_class in task_definition.get(\"pt\", ())\n ),\n tf=tuple(\n auto_class.__qualname__ for auto_class in task_definition.get(\"tf\", ())\n ),\n default=task_definition.get(\"default\", {}),\n type=task_definition.get(\"type\", \"text\"),\n )\n\n with bentoml.models.create(\n name,\n module=MODULE_NAME,\n api_version=API_VERSION,\n labels=labels,\n context=context,\n options=options,\n signatures=signatures,\n custom_objects=custom_objects,\n external_modules=external_modules,\n metadata=metadata,\n ) as bento_model:\n pipeline.save_pretrained(bento_model.path)\n\n with open(bento_model.path_of(PIPELINE_PICKLE_NAME), \"wb\") as f:\n cloudpickle.dump(pipeline, f)\n\n return bento_model\n\n else:\n options = TransformersOptions(task=pipeline.task)\n\n with bentoml.models.create(\n name,\n module=MODULE_NAME,\n api_version=API_VERSION,\n labels=labels,\n context=context,\n options=options,\n signatures=signatures,\n custom_objects=custom_objects,\n external_modules=external_modules,\n metadata=metadata,\n ) as bento_model:\n pipeline.save_pretrained(bento_model.path)\n\n return bento_model\n\n\ndef get_runnable(\n bento_model: bentoml.Model,\n) -> t.Type[bentoml.Runnable]:\n \"\"\"\n Private API: use :obj:`~bentoml.Model.to_runnable` instead.\n \"\"\"\n\n class TransformersRunnable(bentoml.Runnable):\n SUPPORTED_RESOURCES = (\"nvidia.com/gpu\", \"cpu\")\n SUPPORTS_CPU_MULTI_THREADING = True\n\n def __init__(self):\n super().__init__()\n\n available_gpus: str = os.getenv(\"CUDA_VISIBLE_DEVICES\", \"\")\n if available_gpus is not None and available_gpus not in (\"\", \"-1\"):\n # assign GPU resources\n if not available_gpus.isdigit():\n raise ValueError(\n f\"Expecting numeric value for CUDA_VISIBLE_DEVICES, got {available_gpus}.\"\n )\n else:\n kwargs = {\n \"device\": int(available_gpus),\n }\n else:\n # assign CPU resources\n kwargs = {}\n\n self.pipeline = load_model(bento_model, **kwargs)\n\n self.predict_fns: dict[str, t.Callable[..., t.Any]] = {}\n for method_name in bento_model.info.signatures:\n self.predict_fns[method_name] = getattr(self.pipeline, method_name)\n\n def add_runnable_method(method_name: str, options: ModelSignature):\n def _run(self: TransformersRunnable, *args: t.Any, **kwargs: t.Any) -> t.Any:\n return getattr(self.pipeline, method_name)(*args, **kwargs)\n\n TransformersRunnable.add_method(\n _run,\n name=method_name,\n batchable=options.batchable,\n batch_dim=options.batch_dim,\n input_spec=options.input_spec,\n output_spec=options.output_spec,\n )\n\n for method_name, options in bento_model.info.signatures.items():\n add_runnable_method(method_name, options)\n\n return TransformersRunnable\n","sub_path":"src/bentoml/_internal/frameworks/transformers.py","file_name":"transformers.py","file_ext":"py","file_size_in_byte":18748,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"241079676","text":"\"\"\"\nEste test consiste en probar un programa que obtenga los indices\nde los elementos repetidos de una lista.\n\"\"\"\n\nlista = [1,1,2,2,3,4,1,5,3,2,1,1,3]\nunico = []\nnum_an = []\nrep = {}\n\nfor elem in lista:\n if elem not in unico:\n unico.append(elem)\n else:\n if elem not in rep.values():\n rep[elem] = [lista.index(elem)]\n\nfor i in range(len(lista)):\n for j in range(i+1, len(lista)):\n if (lista[i] == lista[j]) and (i not in num_an):\n rep[lista[i]].append(j)\n num_an.append(i)\n\nprint(rep.keys())\n","sub_path":"test/test1.py","file_name":"test1.py","file_ext":"py","file_size_in_byte":554,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"648996787","text":"import argparse\nimport os\n\nimport numpy as np\nimport torch\nfrom torch.utils.data import DataLoader\nfrom torch.utils.data.sampler import SubsetRandomSampler\nfrom torchvision.datasets import MNIST\nfrom torchvision.transforms import (Compose, Normalize, RandomCrop,\n RandomHorizontalFlip, Resize, ToTensor)\nfrom tqdm import tqdm\n\nimport config\nfrom gta import create_gta_dataloaders\nfrom models import GTANet, GTARes18Net, GTAVGG11Net\nfrom utils import GrayscaleToRgb\n\ndevice = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n\n\ndef create_dataloaders(batch_size):\n dataset = MNIST(config.DATA_DIR / 'mnist',\n train=True,\n download=True,\n transform=Compose([GrayscaleToRgb(),\n ToTensor()]))\n shuffled_indices = np.random.permutation(len(dataset))\n train_idx = shuffled_indices[:int(0.8 * len(dataset))]\n val_idx = shuffled_indices[int(0.8 * len(dataset)):]\n\n train_loader = DataLoader(dataset,\n batch_size=batch_size,\n drop_last=True,\n sampler=SubsetRandomSampler(train_idx),\n num_workers=1,\n pin_memory=True)\n val_loader = DataLoader(dataset,\n batch_size=batch_size,\n drop_last=False,\n sampler=SubsetRandomSampler(val_idx),\n num_workers=1,\n pin_memory=True)\n return train_loader, val_loader\n\n\ndef do_epoch(model, dataloader, criterion, optim=None):\n total_loss = 0\n total_accuracy = 0\n for x, y_true in tqdm(dataloader, leave=False):\n x, y_true = x.to(device), y_true.to(device)\n y_pred = model(x)\n loss = criterion(y_pred, y_true)\n\n if optim is not None:\n optim.zero_grad()\n loss.backward()\n optim.step()\n\n total_loss += loss.item()\n total_accuracy += (y_pred.max(1)[1] == y_true).float().mean().item()\n mean_loss = total_loss / len(dataloader)\n mean_accuracy = total_accuracy / len(dataloader)\n\n return mean_loss, mean_accuracy\n\n\ndef main(args):\n\n if args.model == 'gta':\n train_loader, val_loader = create_gta_dataloaders(\n './data',\n transform=Compose([\n Resize((398, 224)),\n RandomCrop(224),\n RandomHorizontalFlip(),\n ToTensor(),\n Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]),\n ]))\n model = GTANet().to(device)\n model_path = './trained_models/gta_source.pt'\n params_to_update = model.parameters()\n elif args.model == 'gta-res':\n train_loader, val_loader = create_gta_dataloaders(\n './data',\n transform=Compose([\n Resize((398, 224)),\n RandomCrop(224),\n RandomHorizontalFlip(),\n ToTensor(),\n Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]),\n ]))\n model = GTARes18Net(9, pretrained=False).to(device)\n model_path = './trained_models/gta_res_scratch.pt'\n params_to_update = list()\n for param in model.parameters():\n if param.requires_grad:\n params_to_update.append(param)\n elif args.model == 'gta-vgg':\n train_loader, val_loader = create_gta_dataloaders(\n './data',\n transform=Compose([\n Resize((398, 224)),\n RandomCrop(224),\n RandomHorizontalFlip(),\n ToTensor(),\n Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]),\n ]))\n model = GTAVGG11Net(9, pretrained=False).to(device)\n model_path = './trained_models/gta_vgg_scratch.pt'\n params_to_update = list()\n for param in model.parameters():\n if param.requires_grad:\n params_to_update.append(param)\n else:\n raise ValueError(f'Unknown model type {args.model}')\n\n optim = torch.optim.Adam(params_to_update)\n lr_schedule = torch.optim.lr_scheduler.StepLR(optim,\n step_size=10,\n gamma=0.1)\n criterion = torch.nn.CrossEntropyLoss()\n\n best_accuracy = 0\n for epoch in range(1, args.epochs + 1):\n model.train()\n train_loss, train_accuracy = do_epoch(model,\n train_loader,\n criterion,\n optim=optim)\n\n model.eval()\n with torch.no_grad():\n val_loss, val_accuracy = do_epoch(model,\n val_loader,\n criterion,\n optim=None)\n\n tqdm.write(\n f'EPOCH {epoch:03d}: train_loss={train_loss:.4f}, train_accuracy={train_accuracy:.4f} '\n f'val_loss={val_loss:.4f}, val_accuracy={val_accuracy:.4f}')\n\n if val_accuracy > best_accuracy:\n print('Saving model...')\n best_accuracy = val_accuracy\n torch.save(model.state_dict(), model_path)\n\n lr_schedule.step(val_loss)\n\n\nif __name__ == '__main__':\n arg_parser = argparse.ArgumentParser(\n description='Train a network on source dataset')\n arg_parser.add_argument('--batch-size', type=int, default=64)\n arg_parser.add_argument('--epochs', type=int, default=64)\n arg_parser.add_argument('--model', type=str, default='gta')\n args = arg_parser.parse_args()\n main(args)\n","sub_path":"train_source.py","file_name":"train_source.py","file_ext":"py","file_size_in_byte":5802,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"102872070","text":"from secure_db import securedb\r\nfrom threading import Thread, Semaphore, Lock\r\n\r\nTHREAD_NUM = 11\r\nglobal secdb\r\n\r\nsemaphore = Semaphore(1)\r\nmutex = Lock()\r\ndef read(key, num):\r\n global secdb, semaphore\r\n print(\"Started reading {}\\n\".format(num))\r\n secdb.read(key)\r\n print(\"Ended reading {}\\n\".format(num))\r\n \r\ndef write(key, value, num):\r\n global secdb, semaphore\r\n print(\"Started writing {}\\n\".format(num))\r\n #semaphore.release()\r\n secdb.write(key,value)\r\n print(\"Ended writing {}\\n\".format(num))\r\n\r\ndef main():\r\n global secdb, semaphore\r\n secdb = securedb(\"something.pickle\")\r\n #secdb.write(\"apple\", \"banana\")\r\n #secdb.write(\"banana\", \"apple\")\r\n \r\n print(\"============MENU============\")\r\n print(\"1. WRITE 1 THREAD \")\r\n print(\"2. READ 5 THREADS \")\r\n print(\"3. WRITE + READ \")\r\n print(\"4. READ + WRITE \")\r\n print(\"5. 6 READ + WRITE \")\r\n print(\"============================\")\r\n \r\n selected = raw_input(\"Selection: \")\r\n \r\n threads = []\r\n if selected == \"1\":\r\n thread = Thread(target=write, args=(\"Apple\", \"Banana\", 0))\r\n thread.start()\r\n \r\n elif selected == \"2\":\r\n for i in range(5):\r\n threads.append(Thread(target=read, args=(\"Apple\", i)))\r\n \r\n for i, thread in enumerate(threads):\r\n thread.start()\r\n \r\n elif selected == \"3\":\r\n wr = Thread(target=write, args=(\"Apple\", \"Banana\", 0))\r\n rd = Thread(target=read, args=(\"Apple\" , 1))\r\n \r\n wr.start()\r\n rd.start()\r\n \r\n elif selected == \"4\":\r\n wr = Thread(target=write, args=(\"Apple\", \"Banana\", 0))\r\n rd = Thread(target=read, args=(\"Apple\" , 1))\r\n \r\n rd.start()\r\n wr.start()\r\n \r\n elif selected == \"5\":\r\n for i in range(5):\r\n threads.append(Thread(target=read, args=(\"Apple\", i)))\r\n \r\n for i in range(3):\r\n threads[i].start()\r\n \r\n wr = Thread(target=write, args=(\"Apple\", \"Banana\", 0))\r\n wr.start()\r\n \r\n for i in range(3,5):\r\n threads[i].start()\r\n\r\n \r\ndef menu(num):\r\n global secdb, semaphore\r\n while True:\r\n selected = raw_input(\"Selection: \")\r\n selected_key = raw_input(\"Key: \")\r\n \r\n if selected == \"1\":\r\n value = secdb.read(selected_key)\r\n if value != None:\r\n print(\"{} = {}\".format(selected_key, value))\r\n else:\r\n print(\"Key does not exist in the database\") \r\n elif selected == \"2\":\r\n selected_value = raw_input(\"Value: \")\r\n secdb.write(selected_key, selected_value)\r\n elif selected == \"3\":\r\n secdb.delete(selected_key)\r\n \r\nif __name__ == \"__main__\":\r\n main()","sub_path":"client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":2872,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"651068159","text":"# Copyright 2021 Google LLC. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"Covertype Keras WideDeep Classifier.\"\"\"\n\nimport functools\nimport absl\nimport os\nfrom typing import List, Text\n\nimport kerastuner\nimport tensorflow as tf\nimport tensorflow_model_analysis as tfma\nimport tensorflow_transform as tft\nfrom tensorflow_transform.tf_metadata import schema_utils\n\nfrom tfx.components.trainer.executor import TrainerFnArgs\nfrom tfx.components.trainer.fn_args_utils import DataAccessor\nfrom tfx.components.tuner.component import TunerFnResult\nfrom tfx_bsl.tfxio import dataset_options\n\nimport features\n\nEPOCHS = 1\nTRAIN_BATCH_SIZE = 64\nEVAL_BATCH_SIZE = 64\n\n\ndef _gzip_reader_fn(filenames):\n \"\"\"Small utility returning a record reader that can read gzip'ed files.\"\"\"\n return tf.data.TFRecordDataset(filenames, compression_type='GZIP')\n\n\ndef _get_serve_tf_examples_fn(model, tf_transform_output):\n \"\"\"Returns a function that parses a serialized tf.Example and applies TFT.\"\"\"\n\n model.tft_layer = tf_transform_output.transform_features_layer()\n\n @tf.function\n def serve_tf_examples_fn(serialized_tf_examples):\n \"\"\"Returns the output to be used in the serving signature.\"\"\"\n feature_spec = tf_transform_output.raw_feature_spec()\n feature_spec.pop(features.LABEL_KEY)\n parsed_features = tf.io.parse_example(serialized_tf_examples, feature_spec)\n\n transformed_features = model.tft_layer(parsed_features)\n\n return model(transformed_features)\n\n return serve_tf_examples_fn\n\n\ndef _input_fn(file_pattern: List[Text],\n data_accessor: DataAccessor,\n tf_transform_output: tft.TFTransformOutput,\n batch_size: int = 200) -> tf.data.Dataset:\n \"\"\"Generates features and label for tuning/training.\n\n Args:\n file_pattern: List of paths or patterns of input tfrecord files.\n data_accessor: DataAccessor for converting input to RecordBatch.\n tf_transform_output: A TFTransformOutput.\n batch_size: representing the number of consecutive elements of returned\n dataset to combine in a single batch\n\n Returns:\n A dataset that contains (features, indices) tuple where features is a\n dictionary of Tensors, and indices is a single Tensor of label indices.\n \"\"\"\n dataset = data_accessor.tf_dataset_factory(\n file_pattern,\n dataset_options.TensorFlowDatasetOptions(\n batch_size=batch_size, label_key=features.transformed_name(features.LABEL_KEY)),\n tf_transform_output.transformed_metadata.schema)\n \n return dataset\n\n\ndef _get_hyperparameters() -> kerastuner.HyperParameters:\n \"\"\"Returns hyperparameters for building Keras model.\"\"\"\n hp = kerastuner.HyperParameters()\n # Defines search space.\n hp.Choice('learning_rate', [1e-2, 1e-3, 1e-4], default=1e-3)\n hp.Int('n_layers', 1, 2, default=1)\n with hp.conditional_scope('n_layers', 1):\n hp.Int('n_units_1', min_value=8, max_value=128, step=8, default=8)\n with hp.conditional_scope('n_layers', 2):\n hp.Int('n_units_1', min_value=8, max_value=128, step=8, default=8)\n hp.Int('n_units_2', min_value=8, max_value=128, step=8, default=8) \n\n return hp\n\n\ndef _build_keras_model(hparams: kerastuner.HyperParameters, \n tf_transform_output: tft.TFTransformOutput) -> tf.keras.Model:\n \"\"\"Creates a Keras WideDeep Classifier model.\n Args:\n hparams: Holds HyperParameters for tuning.\n tf_transform_output: A TFTransformOutput.\n Returns:\n A keras Model.\n \"\"\"\n deep_columns = [\n tf.feature_column.numeric_column(\n key=features.transformed_name(key), \n shape=())\n for key in features.NUMERIC_FEATURE_KEYS\n ]\n \n input_layers = {\n column.key: tf.keras.layers.Input(name=column.key, shape=(), dtype=tf.float32)\n for column in deep_columns\n } \n\n categorical_columns = [\n tf.feature_column.categorical_column_with_identity(\n key=features.transformed_name(key), \n num_buckets=tf_transform_output.num_buckets_for_transformed_feature(features.transformed_name(key)), \n default_value=0)\n for key in features.CATEGORICAL_FEATURE_KEYS\n ]\n\n wide_columns = [\n tf.feature_column.indicator_column(categorical_column)\n for categorical_column in categorical_columns\n ]\n \n input_layers.update({\n column.categorical_column.key: tf.keras.layers.Input(name=column.categorical_column.key, shape=(), dtype=tf.int32)\n for column in wide_columns\n })\n\n\n deep = tf.keras.layers.DenseFeatures(deep_columns)(input_layers)\n for n in range(int(hparams.get('n_layers'))):\n deep = tf.keras.layers.Dense(units=hparams.get('n_units_' + str(n + 1)))(deep)\n\n wide = tf.keras.layers.DenseFeatures(wide_columns)(input_layers)\n\n output = tf.keras.layers.Dense(features.NUM_CLASSES, activation='softmax')(\n tf.keras.layers.concatenate([deep, wide]))\n\n model = tf.keras.Model(input_layers, output)\n model.compile(\n loss='sparse_categorical_crossentropy',\n optimizer=tf.keras.optimizers.Adam(lr=hparams.get('learning_rate')),\n metrics=[tf.keras.metrics.SparseCategoricalAccuracy()])\n model.summary(print_fn=absl.logging.info)\n\n return model \n\n\n# TFX Tuner will call this function.\ndef tuner_fn(fn_args: TrainerFnArgs) -> TunerFnResult:\n \"\"\"Build the tuner using the KerasTuner API.\n Args:\n fn_args: Holds args as name/value pairs.\n - working_dir: working dir for tuning.\n - train_files: List of file paths containing training tf.Example data.\n - eval_files: List of file paths containing eval tf.Example data.\n - train_steps: number of train steps.\n - eval_steps: number of eval steps.\n - schema_path: optional schema of the input data.\n - transform_graph_path: optional transform graph produced by TFT.\n Returns:\n A namedtuple contains the following:\n - tuner: A BaseTuner that will be used for tuning.\n - fit_kwargs: Args to pass to tuner's run_trial function for fitting the\n model , e.g., the training and validation dataset. Required\n args depend on the above tuner's implementation.\n \"\"\"\n transform_graph = tft.TFTransformOutput(fn_args.transform_graph_path)\n \n # Construct a build_keras_model_fn that just takes hyperparams from get_hyperparameters as input.\n build_keras_model_fn = functools.partial(\n _build_keras_model, tf_transform_output=transform_graph) \n\n # BayesianOptimization is a subclass of kerastuner.Tuner which inherits from BaseTuner. \n tuner = kerastuner.BayesianOptimization(\n build_keras_model_fn,\n max_trials=10,\n hyperparameters=_get_hyperparameters(),\n # New entries allowed for n_units hyperparameter construction conditional on n_layers selected.\n# allow_new_entries=True,\n# tune_new_entries=True,\n objective=kerastuner.Objective('val_sparse_categorical_accuracy', 'max'),\n directory=fn_args.working_dir,\n project_name='covertype_tuning')\n \n train_dataset = _input_fn(\n fn_args.train_files,\n fn_args.data_accessor,\n transform_graph,\n batch_size=TRAIN_BATCH_SIZE)\n\n eval_dataset = _input_fn(\n fn_args.eval_files,\n fn_args.data_accessor,\n transform_graph,\n batch_size=EVAL_BATCH_SIZE)\n\n return TunerFnResult(\n tuner=tuner,\n fit_kwargs={\n 'x': train_dataset,\n 'validation_data': eval_dataset,\n 'steps_per_epoch': fn_args.train_steps,\n 'validation_steps': fn_args.eval_steps\n })\n\n\n# TFX Trainer will call this function.\ndef run_fn(fn_args: TrainerFnArgs):\n \"\"\"Train the model based on given args.\n Args:\n fn_args: Holds args used to train the model as name/value pairs.\n \"\"\"\n\n tf_transform_output = tft.TFTransformOutput(fn_args.transform_output)\n\n train_dataset = _input_fn(\n fn_args.train_files, \n fn_args.data_accessor, \n tf_transform_output, \n TRAIN_BATCH_SIZE)\n\n eval_dataset = _input_fn(\n fn_args.eval_files, \n fn_args.data_accessor,\n tf_transform_output, \n EVAL_BATCH_SIZE)\n\n if fn_args.hyperparameters:\n hparams = kerastuner.HyperParameters.from_config(fn_args.hyperparameters)\n else:\n # This is a shown case when hyperparameters is decided and Tuner is removed\n # from the pipeline. User can also inline the hyperparameters directly in\n # _build_keras_model.\n hparams = _get_hyperparameters()\n absl.logging.info('HyperParameters for training: %s' % hparams.get_config())\n \n # Distribute training over multiple replicas on the same machine.\n mirrored_strategy = tf.distribute.MirroredStrategy()\n with mirrored_strategy.scope():\n model = _build_keras_model(\n hparams=hparams,\n tf_transform_output=tf_transform_output)\n\n tensorboard_callback = tf.keras.callbacks.TensorBoard(\n log_dir=fn_args.model_run_dir, update_freq='batch')\n\n model.fit(\n train_dataset,\n epochs=EPOCHS,\n steps_per_epoch=fn_args.train_steps,\n validation_data=eval_dataset,\n validation_steps=fn_args.eval_steps,\n callbacks=[tensorboard_callback])\n \n signatures = {\n 'serving_default':\n _get_serve_tf_examples_fn(model,\n tf_transform_output).get_concrete_function(\n tf.TensorSpec(\n shape=[None],\n dtype=tf.string,\n name='examples')),\n }\n \n model.save(fn_args.serving_model_dir, save_format='tf', signatures=signatures)\n \n\n \n \n","sub_path":"immersion/tfx_pipelines/01-walkthrough/solutions/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":10076,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"197555315","text":"from scipy.stats import binom_test\nfrom scipy.stats import binom\n\n\ndef binom_test_v2(x, n=None, p=0.5, alternative='two-sided'):\n n = np.int_(n)\n if (p > 1.0) or (p < 0.0):\n raise ValueError(\"p must be in range [0,1]\")\n\n if alternative not in ('two-sided', 'less', 'greater'):\n raise ValueError(\"alternative not recognized should be 'two-sided', 'less' or 'greater'\")\n if alternative == 'less':\n pval = binom.cdf(x, n, p)\n return pval\n if alternative == 'greater':\n pval = binom.sf(x-1, n, p)\n return pval\n d = binom.pmf(x, n, p)\n rerr = 1 + 1e-7\n a_fn = lambda x1:binom.pmf(x1,n,p)\n if x == p * n:\n pval = 1.\n elif x < p * n:\n y = n-binary_search(a_fn,d*rerr,np.ceil(p * n),n)+1\n pval = (binom.cdf(x, n, p) +\n binom.sf(n - y, n, p))\n else:\n y = binary_search(a_fn,d*rerr,0,np.floor(p*n) + 1,True)+1\n pval = (binom.cdf(y-1, n, p) +\n binom.sf(x-1, n, p))\n return min(1.0, pval)\n\n \ndef binary_search(a, d, lo, hi, asc_order=False):\n while lo < hi:\n mid = (lo+hi)//2\n midval = a(mid)\n if midval < d:\n if asc_order:\n lo = mid+1\n else:\n hi = mid-1\n elif midval > d:\n if asc_order:\n hi = mid-1\n else:\n lo = mid+1\n else:\n return mid\n if a(lo)<=d:\n return lo\n else:\n return lo-(asc_order-0.5)*2\n\nresult=df\nresult[\"p_value\"] = result.apply(lambda row : binom_test(row.Events_B,row.Events_A + row.Events_B,row.Uptime_B/(row.Uptime_A +row.Uptime_B),alternative='greater'), axis=1)\nresult[\"p_value_two_sided\"] = result.apply(lambda row : binom_test_v2(row.Events_B,row.Events_A + row.Events_B,row.Uptime_B/(row.Uptime_A +row.Uptime_B)), axis=1 )\nresult[\"confidence_two_sided\"] = 1-result[\"p_value_two_sided\"]**.33\nresult[\"confidence\"] = 1-result[\"p_value\"]**.33\n\n","sub_path":"experiments/binom_tst_for_python_plugin_v2.py","file_name":"binom_tst_for_python_plugin_v2.py","file_ext":"py","file_size_in_byte":1968,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"609694963","text":"# -*- coding: utf-8 -*-\n\n\"\"\"\n获取模块\n作用通过爬去模块获取proxies\n\"\"\"\n\n__author__ = 'katherinelove'\n\nfrom Python3网络爬虫开发实战_崔庆才.ProxyPool_myself.crawler import Crawler\nfrom Python3网络爬虫开发实战_崔庆才.ProxyPool_myself.rediscilent import RedisClient\n\n\nPOOL_UPPER_THRESOLD=1000\n\nclass Getter(object):\n def __init__(self):\n self.crawler=Crawler()\n self.redisClient=RedisClient()\n\n #这里为获取器增加开关,当存储模块中的代理超过阈值这停止获取,低于阈值则继续获取proxies\n def is_over_threshod(self):\n return self.redisClient.count() >= POOL_UPPER_THRESOLD\n #等价一下代码\n # if self.redisClient.count()>=POOL_UPPER_THRESOLD:\n # return True\n # else:\n # return False\n\n def run(self):\n print('获取器执行')\n if not self.is_over_threshod():\n for callback_label in range(self.crawler.__CrawlFuncCount__):\n callback=self.crawler.__CrawlFunc__[callback_label]\n proxies=self.crawler.get_proxies(callback)\n for proxy in proxies:\n self.redisClient.add(proxy)\n\n\n\n\n# if __name__ == '__main__':\n# get=Getter()\n# get.run()\n","sub_path":"Python3网络爬虫开发实战_崔庆才/ProxyPool_myself/getter.py","file_name":"getter.py","file_ext":"py","file_size_in_byte":1297,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"489239304","text":"import importlib\r\nimport os\r\nfrom threading import Semaphore\r\nimport uuid\r\n\r\nclass GlobalDataManager():\r\n\r\n def __init__(self):\r\n self._lock = Semaphore(value=1)\r\n\r\n self._global_datas = {}\r\n\r\n filepath = os.environ.get('GLOBAL_DATA_PY')\r\n if filepath is None:\r\n raise ValueError('No Global Data Manager found!')\r\n filename = os.path.split(filepath)[1]\r\n self._module = self._load_plugin_module(filename, filepath)\r\n\r\n def _load_plugin_module(self, name, path):\r\n spec = importlib.util.spec_from_file_location(name, path)\r\n mod = importlib.util.module_from_spec(spec)\r\n spec.loader.exec_module(mod)\r\n return mod\r\n\r\n def _create_new_global_data_instance(self, id):\r\n return self._module.GlobalData()\r\n\r\n def get_global_data(self, session):\r\n self._lock.acquire()\r\n if 'id' not in session:\r\n id = uuid.uuid4()\r\n session['id'] = id\r\n self._global_datas[id] = self._create_new_global_data_instance(id)\r\n else:\r\n id = session['id']\r\n if id not in self._global_datas:\r\n self._global_datas[id] = self._create_new_global_data_instance(id)\r\n self._lock.release()\r\n return self._global_datas[id]\r\n","sub_path":"sim_rapel_win_x64_200706_e/Source/pyticipate/core/scenario/global_data_manager.py","file_name":"global_data_manager.py","file_ext":"py","file_size_in_byte":1292,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"653358500","text":"# Requires to install imageio, e.g. through 'pip3 install imageio' or 'conda isntall -c conda-forge imageio'\ntry :\n import imageio\nexcept ImportError :\n print(\"This script requires the module imageio! It can be installed through e.g.:\\npip3 install imageio\\nconda install -c conda-forge imageio\")\n import sys\n sys.exit(1)\nimport os\n\nif (os.path.exists(\"L:\\\\Uni\\\\Master_Thesis\\\\Experimente\")) :\n datapath = \"L:\\\\Uni\\\\Master_Thesis\\\\Experimente\"\nelse :\n # Please specify your datapath here.\n datapath = os.path.dirname(os.path.abspath(__file__))\n datapath = os.path.join(datapath, \"Experiments\")\nif not (os.path.exists(datapath)) :\n print(\"Datapath \"+datapath+\" not found. Please create and prepare this directory or specify the datapath manually in the code.\")\n sys.exit(1)\n\ndirectories = []\nfor root, dirs, files in os.walk(datapath) :\n for dir in dirs:\n if ('Epochs_Plots' in dirs) :\n directories.append(os.path.join(root, dir))\nif (len(directories) == 0) :\n print(\"Could not find any valid images. Did you set the correct datapath?\\nCurrent datapath = \"+datapath)\n sys.exit(1)\n\nfor datapath in directories :\n filenamesA = []\n filenamesB = []\n for root, dirs, files in os.walk(datapath) :\n for file in files :\n if (\"Example_0\" in file) :\n dir = file[0:9]\n filenamesA.append(os.path.join(os.path.join(datapath, dir), file))\n elif (\"Translation-\" in file) :\n filenamesB.append(os.path.join(datapath, file))\n\n if (len(filenamesA) > 0) :\n print(\"Found \"+str(len(filenamesA))+\" files.\")\n elif (len(filenamesB) > 0) :\n print(\"Found \"+str(len(filenamesB))+\" files.\")\n\n images = []\n if (len(filenamesA) > 0) :\n for filename in filenamesA:\n images.append(imageio.imread(filename))\n savepath = os.path.abspath(os.path.join(datapath, os.pardir))\n print(\"Storing gif to path: \"+savepath)\n imageio.mimsave(os.path.join(savepath,'AnimatedTrainingResults.gif'), images, fps=2)\n if (len(filenamesB) > 0) :\n for filename in filenamesB:\n images.append(imageio.imread(filename))\n savepath = os.path.abspath(os.path.join(datapath, os.pardir))\n print(\"Storing gif to path: \"+savepath)\n imageio.mimsave(os.path.join(savepath,'AnimatedTestResults.gif'), images, fps=1)","sub_path":"src/create_gif.py","file_name":"create_gif.py","file_ext":"py","file_size_in_byte":2393,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"434423149","text":"from matplotlib import pyplot as plt, cm\nfrom PIL import Image\nimport numpy as np\nimport os\n\ndef select_threshold(filename, threshold):\n im = Image.open(filename)\n image1 = np.array(im)\n image2 = np.copy(image1)\n gray_cmap = cm.get_cmap('gray')\n figure, (ax1, ax2) = plt.subplots(1,2);\n ax1.imshow(image1, cmap=gray_cmap)\n image2[image1 <= threshold] = 1\n image2[image1 > threshold] = 0\n ax2.imshow(image2, cmap=gray_cmap)\n plt.show()\n\n\ndirectory = './data'\nfile1 = os.path.join(directory, 'b-006.bmp')\nfile2 = os.path.join(directory, 'b-008.bmp')\nthreshold = 65\nselect_threshold(file1, threshold)\nselect_threshold(file2, threshold)\n","sub_path":"sem/threshold_selection.py","file_name":"threshold_selection.py","file_ext":"py","file_size_in_byte":663,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"564402201","text":"########################################################################\nfrom Gaudi.Configuration import *\nfrom Configurables import DaVinci \nfrom Configurables import GaudiSequencer, CombineParticles, FilterDesktop\nfrom PhysSelPython.Wrappers import Selection, SelectionSequence, DataOnDemand\nfrom CommonMCParticles import StandardMCPions\n#Truth matched commonparticles: \n_pions = DataOnDemand(Location='Phys/StdMCPions/Particles')\n\n\n#\n# MC matching\n#\n\n\nmatchk2pipipi = \"(mcMatch('[K+ ==> pi+ pi- pi+ ]CC'))\"\n\n_k2pipipi = CombineParticles(\"k2pipipi\")\n_k2pipipi.DecayDescriptor = \"[K+ -> pi+ pi- pi+]cc\"\n\n_k2pipipi.MotherCut = matchk2pipipi\n_k2pipipi.Preambulo = [\n \"from LoKiPhysMC.decorators import *\",\n \"from PartProp.Nodes import CC\" ]\n\nSelk2pipipi = Selection( \"Selk2pipipi\",\n Algorithm = _k2pipipi,\n RequiredSelections=[_pions]) \n\nSeqk2pipipi = SelectionSequence('MCFilter',TopSelection = Selk2pipipi) \n\n#\n# Write DST\n#\nenablePacking = True\ndstExtension = \".\" + DaVinci().InputType.lower()\nfrom DSTWriters.microdstelements import *\nfrom DSTWriters.Configuration import (SelDSTWriter,\n stripDSTStreamConf,\n stripDSTElements\n )\nSelDSTWriterElements = { 'default' : stripDSTElements(pack=enablePacking) }\nSelDSTWriterConf = { 'default' : stripDSTStreamConf(pack=enablePacking,fileExtension=dstExtension,selectiveRawEvent=False) }\ndstWriter = SelDSTWriter( \"MyDSTWriter\",\n StreamConf = SelDSTWriterConf,\n MicroDSTElements = SelDSTWriterElements,\n OutputFileSuffix ='Filtered',\n SelectionSequences = [ Seqk2pipipi],\n )\n#\n# DaVinci Configuration\n#\nfrom Configurables import DaVinci\nDaVinci().HistogramFile = \"DVHistos.root\"\nDaVinci().ProductionType = \"Stripping\"\nDaVinci().Simulation = True\nDaVinci().EvtMax = -1 # Number of events\nDaVinci().appendToMainSequence( [Seqk2pipipi.sequence(), dstWriter.sequence() ])\n\n# Change the column size of Timing table\nfrom Configurables import TimingAuditor, SequencerTimerTool\nTimingAuditor().addTool(SequencerTimerTool,name=\"TIMER\")\nTimingAuditor().TIMER.NameSize = 60\n\n","sub_path":"DBASE/WG/HLTConfig/options/K2PiPiPi.py","file_name":"K2PiPiPi.py","file_ext":"py","file_size_in_byte":2323,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"354764515","text":"\"\"\"Calculate student grades by combining data from many sources.\n\nUsing Pandas, this script combines data from the:\n\n* Roster\n* Homework & Exam grades\n* Quiz grades\n\nto calculate final grades for a class.\n\"\"\"\nfrom pathlib import Path\nimport pandas as pd\n\nHERE = Path(__file__).parent\nDATA_FOLDER = HERE / \"data\"\n\n# ----------------------\n# 01 - LOADING THE DATA\n# ----------------------\n\nroster = pd.read_csv(\n DATA_FOLDER / \"roster.csv\",\n converters={\"NetID\": str.lower, \"Email Address\": str.lower},\n usecols=[\"Section\", \"Email Address\", \"NetID\"],\n index_col=\"NetID\",\n)\n\nhw_exam_grades = pd.read_csv(\n DATA_FOLDER / \"hw_exam_grades.csv\",\n converters={\"SID\": str.lower},\n usecols=lambda x: \"Submission\" not in x,\n index_col=\"SID\",\n)\n\nquiz_grades = pd.DataFrame()\nfor file_path in DATA_FOLDER.glob(\"quiz_*_grades.csv\"):\n quiz_name = \" \".join(file_path.stem.title().split(\"_\")[:2])\n quiz = pd.read_csv(\n file_path,\n converters={\"Email\": str.lower},\n index_col=[\"Email\"],\n usecols=[\"Email\", \"Grade\"],\n ).rename(columns={\"Grade\": quiz_name})\n quiz_grades = pd.concat([quiz_grades, quiz], axis=1)\n\n# ------------------------\n# 02 - MERGING DATAFRAMES\n# ------------------------\n\nfinal_data = pd.merge(\n roster,\n hw_exam_grades,\n left_index=True,\n right_index=True,\n)\nfinal_data = pd.merge(\n final_data, quiz_grades, left_on=\"Email Address\", right_index=True\n)\nfinal_data = final_data.fillna(0)\n","sub_path":"pandas-gradebook-project/02-merging-dataframes.py","file_name":"02-merging-dataframes.py","file_ext":"py","file_size_in_byte":1468,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"24183393","text":"import os\nimport argparse\nimport gzip\nimport numpy as np\nimport pandas as pd\nfrom astropy.io import fits\nimport compute_num_completeness_w_ve as kp\n\ndef read_stellar_table(filename):\n kic = pd.read_csv(filename)\n all_datas = []\n all_keys = []\n for i in range(len(kic.kepid)):\n cur = kp.kepler_single_comp_data()\n cur.id = kic.kepid[i]\n cur.rstar = kic.radius[i]\n cur.logg = kic.logg[i]\n cur.teff = kic.teff[i]\n cur.dataspan = kic.dataspan[i]\n cur.dutycycle = kic.dutycycle[i]\n cur.limbcoeffs = np.array([kic.limbdark_coeff1[i], kic.limbdark_coeff2[i], kic.limbdark_coeff3[i], kic.limbdark_coeff4[i]])\n cur.cdppSlopeLong = kic.cdppslplong[i]\n cur.cdppSlopeShort = kic.cdppslpshrt[i]\n all_datas.append(cur)\n all_keys.append(cur.id)\n # Now zip it all together into dictionary with kic as key\n stellar_dict = dict(zip(all_keys, all_datas))\n return stellar_dict \n\ndef nas_multi_grid_dr25(worker_id, n_workers, min_period, max_period,\n n_period, min_rp, max_rp, n_rp, \n stellar_database,\n planet_metric_path, ve_data_file,\n ve_model_name, output_prefix):\n\n print(\"worker id \" + str(worker_id))\n # Define the grids and data parameters\n period_want = np.linspace(min_period, max_period, n_period)\n rp_want = np.linspace(min_rp, max_rp, n_rp)\n # Load the stellar data \n stellar_database_filename = stellar_database\n stellar_dict = read_stellar_table(stellar_database_filename)\n kiclist = [cur.id for cur in stellar_dict.values()]\n\n # Ensure kic list is sorted\n kiclist = np.sort(kiclist)\n period_want2d, rp_want2d = np.meshgrid(period_want, rp_want)\n shape2d = period_want2d.shape\n shape3d = (2,) + shape2d\n # Create zero arrays that we will fill\n cumulative_array = np.zeros(shape3d, dtype=np.float64)\n usekiclist = np.array([], dtype=np.int32)\n doneOnce = False\n for i in range(len(kiclist)):\n if (i%1000 == 0):\n print(str(np.round(100.*np.double(i)/len(kiclist), 2)) + \"%\")\n if np.mod(i, n_workers) == worker_id :\n curid = kiclist[i]\n windowfunc_filename = os.path.join(planet_metric_path,'kplr' + \\\n '{:09d}'.format(curid) + \\\n '_dr25_window.fits')\n if not os.path.isfile(windowfunc_filename):\n print(\"worker \" + str(worker_id) + \" skipping \" + windowfunc_filename)\n continue\n usekiclist = np.append(usekiclist, curid)\n curdict = stellar_dict[curid]\n curdict.period_want = period_want\n curdict.rp_want = rp_want\n curdict.ecc = 0.0\n curdict.planet_detection_metric_path = planet_metric_path\n curdict.ve_fit_filename = ve_data_file\n curdict.ve_model_name = ve_model_name\n if not doneOnce:\n DEMod = None\n probdet, probtot, DEMod = kp.kepler_single_comp_dr25(curdict, DEMod=DEMod)\n doneOnce = True\n\n if np.logical_not(np.all(np.isfinite(probdet))):\n print (\"non finite probdet detected. skipping.\")\n print (curid)\n continue\n if np.logical_not(np.all(np.isfinite(probtot))):\n print (\"non finite probtot detected. skipping.\")\n print (curid)\n continue\n cumulative_array[0] = cumulative_array[0] + probdet\n cumulative_array[1] = cumulative_array[1] + probtot\n # check that the final cumulative_array is clean\n if np.logical_not(np.all(np.isfinite(cumulative_array))):\n print (\"Non finite cumulative_array Found!\")\n print (worker_id)\n output_filename = output_prefix + \"_\" + '_{:04d}'.format(worker_id) + '.fits'\n # Package data into fits file\n # Add cumulative_array to primary fits image data\n hdu = fits.PrimaryHDU(cumulative_array)\n hdulist = fits.HDUList([hdu])\n # Add parameters to primary header\n prihdr = hdulist[0].header\n prihdr.set('MINPER',min_period)\n prihdr.set('MAXPER',max_period)\n prihdr.set('NPER',n_period)\n prihdr.set('MINRP',min_rp)\n prihdr.set('MAXRP',max_rp)\n prihdr.set('NRP',n_rp)\n prihdr.set('STELDATA',stellar_database_filename)\n prihdr.set('DEFILE',ve_data_file)\n prihdr.set('DEMODEL',ve_model_name)\n # Now add the kics used in this chunk of the data\n newcol = fits.Column(name='kiclist', format='J', array=usekiclist)\n cols = fits.ColDefs([newcol])\n # tbhdu = fits.new_table(cols)\n tbhdu = fits.BinTableHDU.from_columns(cols)\n hdulist.append(tbhdu)\n # Write out fits file\n hdulist.writeto(output_filename, clobber=True)\n hdulist.close()\n # Gzip fits file\n f_in = open(output_filename, 'rb')\n f_out = gzip.open(output_filename + '.gz', 'wb')\n f_out.writelines(f_in)\n f_out.close()\n f_in.close()\n os.remove(output_filename)\n\n return 1\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument(\"worker_id\", type=int,\n help=\"Unique worker ID number\")\n parser.add_argument(\"n_workers\", type=int,\n help=\"Total number of workers\")\n parser.add_argument(\"min_period\", type=float,\n help=\"Orbital period lower limit\")\n parser.add_argument(\"max_period\", type=float,\n help=\"Orbital period upper limit\")\n parser.add_argument(\"n_period\", type=int,\n help=\"Number of steps in grid over orbital period\")\n parser.add_argument(\"min_rp\", type=float,\n help=\"Planet radius lower limit\")\n parser.add_argument(\"max_rp\", type=float,\n help=\"Planet radius upper limit\")\n parser.add_argument(\"n_rp\", type=int,\n help=\"Number of steps in grid over planet radius\")\n parser.add_argument(\"stellar_database\", type=str,\n help=\"name of stellar table filename\")\n parser.add_argument(\"planet_metric_path\", type=str,\n help=\"Path to the planet detection metric files\")\n parser.add_argument(\"ve_data_file\", type=str,\n help=\"filename of the vetting efficiency data file\")\n parser.add_argument(\"ve_model_name\", type=str,\n help=\"name of the vetting efficiency model\")\n parser.add_argument(\"output_prefix\", type=str,\n help=\"Prefix for output files\")\n args = parser.parse_args()\n outputresult = nas_multi_grid_dr25(args.worker_id, args.n_workers,\n args.min_period, args.max_period, args.n_period,\n args.min_rp, args.max_rp, args.n_rp,\n args.stellar_database,\n args.planet_metric_path,\n args.ve_data_file,\n args.ve_model_name,\n args.output_prefix)\n","sub_path":"completenessContours/compute_num_completeness_mproc.py","file_name":"compute_num_completeness_mproc.py","file_ext":"py","file_size_in_byte":7170,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"56325603","text":"# decorators.py\n\nimport time\nimport functools\nimport psutil\nimport datetime\nimport threading\n\n\ndef stopwatch(func):\n @functools.wraps(func)\n def wrapper(*args, **kwargs):\n print('| %30s |: Start %s() ' % ('@stopwatch', func.__name__))\n start = time.perf_counter()\n value = func(*args, **kwargs)\n stop = time.perf_counter()\n print('| %30s |: Stop %s() been running %2.2f second(s).' % ('@stopwatch', func.__name__, stop-start))\n return value\n return wrapper\n\n\ndef performance_to_excel(excel, sleep_around=5):\n \"\"\"Decorator @performance\n \n Keyword arguments:\n excel -- Excel type object\n sleep_around -- How long the resources will be recording before and after the function run\n -------------------\n Example:\n 1)\n > performance_to_excel(excel, sleep_around)(_run_function_as_parallel_process)(func, timeout)\n\n 2)\n > @performance_to_excel(excel, sleep_around)\n > def _run_function_as_parallel_process(func, timeout):\n > pass\n >\n > _run_function_as_parallel_process(func, timeout)\n \"\"\"\n\n def decorator_performance(func):\n\n def recording_thread(event, excel):\n \"\"\"Meant to run as a thread!\n \n Keyword arguments:\n event -- threading.Event(). To stop this thread\n excel -- Excel type object\n \n Thread that records system performance until event occour.\n \"\"\"\n event.wait()\n print('| %30s |' % (''))\n print('| %30s |: Recording!' % ('thread'))\n psutil.net_io_counters.cache_clear()\n while event.is_set():\n net_before = psutil.net_io_counters()\n # CPU performance per each\n perc = psutil.cpu_percent(interval=1, percpu=True)\n # Timestamp\n date = datetime.datetime.now().strftime(\"%H:%M:%S\")# %d/%m/%Y\")\n ram = psutil.virtual_memory()\n net_after = psutil.net_io_counters()\n perc.append(date)\n # Ram performance\n perc.append(ram.percent)\n perc.append(ram.used)\n perc.append(ram.active)\n # Network performance\n perc.append(net_after.bytes_sent)\n perc.append(net_after.bytes_recv)\n perc.append(net_after.bytes_sent-net_before.bytes_sent)\n perc.append(net_after.bytes_recv-net_before.bytes_recv)\n\n excel.append_row(perc)\n print('| %30s |: *%s timestamp...' % ('thread', date))\n excel.save()\n print('| %30s |: Stop recording!' % ('thread'))\n print('| %30s |' % (''))\n\n \n @functools.wraps(func)\n def wrapper_performance(*args, **kwargs):\n '''Wraps function to measure system performance\n \n '''\n print('| %30s |: Start %s() ' % ('@performance', func.__name__))\n\n # 1) Excel columns\n n_cpu_logical = psutil.cpu_count(logical=True)\n print('| %30s |: There is %2.0f logical CPU(s) available.' % ('@performance', n_cpu_logical))\n ram_total = psutil.virtual_memory().total\n print('| %30s |: There is %2.3f GB RAM in total.' % ('@performance', ram_total * 10**(-9)))\n column_names = [f'CPU {idx+1}' for idx in range(n_cpu_logical)]\n column_names.append('Datetime')\n column_names.append('RAM_percent')\n column_names.append('RAM_used')\n column_names.append('RAM_active')\n column_names.append('Net_sent')\n column_names.append('Net_recv')\n column_names.append('Net_sent_persec')\n column_names.append('Net_recv_persec')\n\n excel.create_column_names(column_names)\n excel.save()\n\n print('| %30s |: Excel saved with new column names on path \"%s\".' % ('@performance', excel.path))\n\n # 2) Run thread\n event = threading.Event()\n event.set()\n t = threading.Thread(target=recording_thread, kwargs={'event':event, 'excel':excel})\n t.start()\n time.sleep(sleep_around)\n\n print('| %30s |' % (''))\n print('| %30s |: ------------- Function call ------' % ('@performance'))\n value = func(*args, **kwargs)\n print('| %30s |: ------------- Function done ------' % ('@performance'))\n print('| %30s |' % (''))\n\n time.sleep(sleep_around)\n event.clear()\n t.join()\n print('| %30s |: Stop %s()' % ('@performance', func.__name__))\n return value\n\n return wrapper_performance\n\n return decorator_performance\n\n","sub_path":"utils/decorators.py","file_name":"decorators.py","file_ext":"py","file_size_in_byte":4774,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"234272976","text":"# Copyright 2018 Bloomberg Finance L.P.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\nimport pytest\nfrom mock import MagicMock\n\nfrom powerfulseal.policy.node_scenario import NodeScenario\nfrom powerfulseal.policy.pod_scenario import PodScenario\nfrom powerfulseal.policy.scenario import Scenario\nfrom powerfulseal.execute import RemoteExecutor\n\n\n# Common fixtures\nclass Dummy():\n pass\n\ndef make_dummy_object():\n return Dummy()\n\n@pytest.fixture\ndef dummy_object():\n return make_dummy_object()\n\n\n# Scenario fixtures\n@pytest.fixture\ndef noop_scenario():\n scenario = Scenario(\n name=\"test scenario\",\n schema={}\n )\n scenario.match = MagicMock(return_value=[])\n scenario.filter = MagicMock(return_value=[])\n scenario.act = MagicMock()\n return scenario\n\n\n@pytest.fixture\ndef no_filtered_items_scenario():\n scenario = Scenario(\n name=\"test scenario\",\n schema={}\n )\n matched_items = [ make_dummy_object() ]\n scenario.match = MagicMock(return_value=matched_items)\n scenario.filter = MagicMock(return_value=[])\n scenario.act = MagicMock()\n return scenario\n\n\n# Pod Scenario Fixtures\nEXAMPLE_POD_SCHEMA = {\n \"match\": [\n {\n \"property\": {\n \"name\": \"attr\",\n \"value\": \"a.*\"\n }\n },\n ]\n}\n\n\n@pytest.fixture\ndef pod_scenario():\n inventory = MagicMock()\n k8s_inventory = MagicMock()\n k8s_inventory.delete_pods = False\n executor = RemoteExecutor()\n return PodScenario(\n name=\"test scenario\",\n schema=EXAMPLE_POD_SCHEMA,\n inventory=inventory,\n k8s_inventory=k8s_inventory,\n executor=executor,\n )\n\n\n# Node Scenario Fixtures\nEXAMPLE_NODE_SCHEMA = {\n \"match\": [\n {\n \"property\": {\n \"name\": \"attr\",\n \"value\": \"a.*\"\n }\n },\n ]\n}\n\n\n@pytest.fixture\ndef node_scenario():\n inventory = MagicMock()\n driver = MagicMock()\n executor = MagicMock()\n return NodeScenario(\n name=\"test scenario\",\n schema=EXAMPLE_NODE_SCHEMA,\n inventory=inventory,\n driver=driver,\n executor=executor,\n )\n","sub_path":"tests/fixtures.py","file_name":"fixtures.py","file_ext":"py","file_size_in_byte":2664,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"203719230","text":"import Image\nimport gzip\nimport logging\nimport numpy as np\nimport os\nimport sys\nimport radar\nimport utils_dmi\nimport utils_imgproc\nimport utils_map\nimport utils_proj\n\"\"\"Reading and writing data\"\"\"\n\nlog = logging.getLogger(__name__)\n\n\ndef read_binary_image(filename, format='vris_ppi', areaname=None):\n try:\n name, extension = os.path.splitext(filename)\n if extension == \".gz\":\n with gzip.open(filename) as fp:\n data = fp.read()\n else:\n with open(filename, 'rb') as fp:\n data = fp.read()\n except Exception as ex:\n log.exception('%s' % ex)\n sys.exit(1)\n else:\n if format == 'vris_ppi':\n log.info('Reading VRIS PPI image')\n metadata, imagedata = parse_vris_ppi(data)\n elif format == 'vris_composite':\n log.info('Reading VRIS composite image')\n metadata, imagedata = parse_vris_composite(data, areaname=areaname)\n else:\n metadata = None\n imagedata = None\n\n return metadata, imagedata\n\n\ndef parse_vris_ppi(data):\n \"\"\"Parse DMI VRIS radar image\"\"\"\n # Metadata\n md = {}\n md['product'] = 'PPI'\n md['xscale'] = int(data[13:17].replace(' ', '0'))\n md['yscale'] = md['xscale']\n md['date'] = data[17:25]\n md['time'] = data[25:31]\n md['place'] = data[31:51].strip(\" \")\n md['xsize'] = int(data[51:54])\n md['ysize'] = int(data[54:57])\n md['gain'] = float(data[60:64])\n md['offset'] = float(data[64:70])\n md['nodata'] = 255\n md['undetect'] = 0\n\n md['abbrev'] = utils_dmi.place_to_abbreviation.get(md['place'])\n md['node'] = utils_dmi.radarsite_metadata.get(md['abbrev'])['node']\n md['source'] = utils_dmi.radarsite_metadata.get(md['abbrev'])['source']\n md['height'] = utils_dmi.radarsite_metadata.get(md['abbrev'])['height']\n\n # Using hardcoded better precision geographical coordinates\n # md['lon'] = float(data[84:91])\n # md['lat'] = float(data[91:98])\n md['lon'] = utils_dmi.radarsite_metadata.get(md['abbrev'])['lonlat'][0]\n md['lat'] = utils_dmi.radarsite_metadata.get(md['abbrev'])['lonlat'][1]\n\n # Map projection\n md['proj'], md['projstring'] = utils_proj.radar_gnonomic_projection( \\\n md['lon'], md['lat'])\n\n md['upperleft_x'] = -((md['xsize'] / 2.) * md['xscale']) \\\n + (md['xscale'] / 2.)\n md['upperleft_y'] = ((md['ysize'] / 2.) * md['yscale']) \\\n - (md['yscale'] / 2.)\n\n md['lowerleft_x'] = -((md['xsize'] / 2.) * md['xscale']) \\\n + (md['xscale'] / 2.)\n md['lowerleft_y'] = -((md['ysize'] / 2.) * md['yscale']) \\\n - (md['yscale'] / 2.)\n\n md['upperright_x'] = ((md['xsize'] / 2.) * md['xscale']) \\\n + (md['xscale'] / 2.)\n md['upperright_y'] = ((md['ysize'] / 2.) * md['yscale']) \\\n - (md['yscale'] / 2.)\n\n md['lowerleft_lon'], md['lowerleft_lat'] = utils_map.map2geo(\n md['lowerleft_x'], md['lowerleft_y'], md['proj'])\n\n md['upperright_lon'], md['upperright_lat'] = utils_map.map2geo(\n md['upperright_x'], md['upperright_y'], md['proj'])\n\n headersize = 99\n expectedsize = headersize + (md['xsize'] * md['ysize'])\n if len(data) != expectedsize:\n log.error('Expected %s pixels (rows x cols) = (%s x %s) but found %s' \\\n % (expectedsize, md['ysize'], md['xsize'], len(data)))\n sys.exit(1)\n\n numpixels = md['xsize'] * md['ysize']\n md['header'] = data[0:headersize]\n dataraw = data[headersize:numpixels + headersize]\n img = np.frombuffer(dataraw, dtype=np.uint8).reshape(md['ysize'],\n md['xsize'])\n # Fix origo\n img = np.flipud(img)\n return md, img\n\n\ndef parse_vris_composite(data, scale=None, xsize=None, ysize=None,\n projname='dmi_stere', areaname='dmi_stere'):\n \"\"\"Parse DMI VRIS composite radar image\"\"\"\n # Metadata\n md = {}\n md['product'] = 'composite'\n md['xscale'] = int(data[13:17].replace(' ', '0'))\n md['yscale'] = md['xscale']\n md['date'] = data[17:25]\n md['time'] = data[25:31]\n md['xsize'] = int(data[51:54])\n md['ysize'] = int(data[54:57])\n md['gain'] = float(data[60:64])\n md['offset'] = float(data[64:70])\n md['nodata'] = 255\n md['undetect'] = 0\n\n # Map projection\n md['proj'], md['projstring'], numrows, numcols, \\\n md['lowerleft_lon'], md['lowerleft_lat'], \\\n md['upperright_lon'], md['upperright_lat'] = \\\n utils_proj.predefined_areas(areaname, md['xscale'])\n\n headersize = 99\n expectedsize = headersize + (md['xsize'] * md['ysize'])\n if len(data) != expectedsize:\n log.error('Expected %s pixels (rows x cols) = (%s x %s) but found %s' \\\n % (expectedsize, md['ysize'], md['xsize'], len(data)))\n sys.exit(1)\n\n numpixels = md['xsize'] * md['ysize']\n md['header'] = data[0:headersize]\n dataraw = data[headersize:numpixels + headersize]\n img = np.frombuffer(dataraw, dtype=np.uint8).reshape(md['ysize'],\n md['xsize'])\n # Fix origo\n img = np.flipud(img)\n return md, img\n\n\ndef write_raster_image(img, outfilename, option='normalize'):\n if option == 'normalize':\n img = utils_imgproc.normalize(img)\n\n Image.fromarray(img).save(outfilename)\n","sub_path":"utils_io.py","file_name":"utils_io.py","file_ext":"py","file_size_in_byte":5398,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"205000824","text":"\"\"\"converter numero inteiro para para:\r\n- 1 binario\r\n- 2 octal\r\n- 3 hexadecimal\"\"\"\r\n\r\nnum = int(input('Digite um número inteiro: '))\r\nprint('''Escolha uma das bases para conversão: \r\n[1] Converter para Binário\r\n[2] Converter para OCTAL\r\n[3] Converter para HEXADECIMAL''')\r\n\r\nopcao = int(input('Sua opção: '))\r\nif opcao == 1:\r\n print('{} convertido para BINÁRIO é igual a {}'.format(num, bin(num)[2:]))#[2:] começa do terceiro ate o fim\r\nelif opcao == 2:\r\n print('{} convertido para OCTAL é igual a {}'.format(num, oct(num)[2:]))\r\nelif opcao == 3:\r\n print('{} convertido para HEXADECIMAL é igual a {}'.format(num, hex(num)[2:]))\r\nelse:\r\n print('Opção inválida!')\r\n","sub_path":"ex_037_Convesao.py","file_name":"ex_037_Convesao.py","file_ext":"py","file_size_in_byte":688,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"273880473","text":"import cv2\nimport face_recognition\nimport numpy as np\nimport os\nfrom datetime import datetime\n\n\n# Read points from text file\ndef read_points(points):\n # Create an array of points.\n points_1 = []\n\n # Read points\n for key in points:\n for point in points[key]:\n points_1.append(point)\n # with open(path) as file:\n # for line in file:\n # x, y = line.split()\n # points.append((int(x), int(y)))\n return points_1\n\n\n# Apply affine transform calculated using srcTri and dstTri to src and\n# output an image of size.\ndef apply_affine_transform(src, srcTri, dstTri, size):\n # Given a pair of triangles, find the affine transform.\n warp_mat = cv2.getAffineTransform(np.float32(srcTri), np.float32(dstTri))\n\n # Apply the Affine Transform just found to the src image\n dst = cv2.warpAffine(src, warp_mat, (size[0], size[1]), None, flags=cv2.INTER_LINEAR,\n borderMode=cv2.BORDER_REFLECT_101)\n\n return dst\n\n\n# Check if a point is inside a rectangle\ndef rect_contains(rect, point):\n return not point[0] < rect[0] \\\n or point[1] < rect[1] \\\n or point[0] > rect[0] + rect[2] \\\n or point[1] > rect[1] + rect[3]\n\n\n# calculate delanauy triangle\ndef calculate_delaunay_triangles(rect, points):\n # create subdiv\n subdiv = cv2.Subdiv2D(rect)\n\n # Insert points into subdiv\n for p in points:\n subdiv.insert(p)\n\n triangle_list = subdiv.getTriangleList()\n\n delaunay_tri = []\n\n pt = []\n\n for t in triangle_list:\n pt1 = (t[0], t[1])\n pt2 = (t[2], t[3])\n pt3 = (t[4], t[5])\n\n pt += [pt1, pt2, pt3]\n\n if rect_contains(rect, pt1) and rect_contains(rect, pt2) and rect_contains(rect, pt3):\n ind = []\n # Get face-points (from 68 face detector) by coordinates\n for j in range(0, 3):\n for k in range(0, len(points)):\n if abs(pt[j][0] - points[k][0]) < 1.0 and abs(pt[j][1] - points[k][1]) < 1.0:\n ind.append(k)\n # Three points form a triangle. Triangle array corresponds to the file tri.txt in FaceMorph\n if len(ind) == 3:\n delaunay_tri.append((ind[0], ind[1], ind[2]))\n\n pt = []\n\n return delaunay_tri\n\n\n# Warps and alpha blends triangular regions from img1 and img2 to img\ndef warp_triangle(img1, img2, t1, t2):\n # Find bounding rectangle for each triangle\n r1 = cv2.boundingRect(np.float32([t1]))\n r2 = cv2.boundingRect(np.float32([t2]))\n\n # Offset points by left top corner of the respective rectangles\n t1_rect = []\n t2_rect = []\n t2_rect_int = []\n\n for i in range(0, 3):\n t1_rect.append(((t1[i][0] - r1[0]), (t1[i][1] - r1[1])))\n t2_rect.append(((t2[i][0] - r2[0]), (t2[i][1] - r2[1])))\n t2_rect_int.append(((t2[i][0] - r2[0]), (t2[i][1] - r2[1])))\n\n # Get mask by filling triangle\n mask = np.zeros((r2[3], r2[2], 3), dtype=np.float32)\n cv2.fillConvexPoly(mask, np.int32(t2_rect_int), (1.0, 1.0, 1.0), 16, 0)\n\n # Apply warpImage to small rectangular patches\n img1_rect = img1[r1[1]:r1[1] + r1[3], r1[0]:r1[0] + r1[2]]\n # img2Rect = np.zeros((r2[3], r2[2]), dtype = img1Rect.dtype)\n\n size = (r2[2], r2[3])\n\n img2_rect = apply_affine_transform(img1_rect, t1_rect, t2_rect, size)\n\n img2_rect = img2_rect * mask\n\n # Copy triangular region of the rectangular patch to the output image\n img2[r2[1]:r2[1] + r2[3], r2[0]:r2[0] + r2[2]] = img2[r2[1]:r2[1] + r2[3], r2[0]:r2[0] + r2[2]] * (\n (1.0, 1.0, 1.0) - mask)\n\n img2[r2[1]:r2[1] + r2[3], r2[0]:r2[0] + r2[2]] = img2[r2[1]:r2[1] + r2[3], r2[0]:r2[0] + r2[2]] + img2_rect\n\n\ndef start_swapping(path, file_name1, file_name2):\n # # Make sure OpenCV is version 3.0 or above\n # (major_ver, minor_ver, subminor_ver) = (cv2.__version__).split('.')\n #\n # if int(major_ver) < 3:\n # print >> sys.stderr, 'ERROR: Script needs OpenCV 3.0 or higher'\n # sys.exit(1)\n\n # Read images\n file_name1 = os.path.join(path, file_name1)\n file_name2 = os.path.join(path, file_name2)\n\n # img1d = dlib.load_rgb_image(file_name1)\n # img2d = dlib.load_rgb_image(file_name2)\n\n\n # image1 = face_recognition.load_image_file(filename1)\n # image2 = face_recognition.load_image_file(filename2)\n\n # Read array of corresponding points\n\n # detector = dlib.get_frontal_face_detector()\n # predictor = dlib.shape_predictor('./shape_predictor_68_face_landmarks.dat')\n #\n # rect1 = detector(img1d)[0]\n # sp1 = predictor(img1d, rect1)\n # points1 = [(p.x, p.y) for p in sp1.parts()]\n #\n # rect2 = detector(img2d)[0]\n # sp2 = predictor(img2d, rect2)\n # points2 = [(p.x, p.y) for p in sp2.parts()]\n\n img1 = cv2.imread(file_name1)\n img2 = cv2.imread(file_name2)\n\n img1_warped = np.copy(img2)\n\n points1 = read_points(face_recognition.face_landmarks(img1)[0])\n points2 = read_points(face_recognition.face_landmarks(img2)[0])\n # points1 = readPoints(filename1 + '.txt')\n # points2 = readPoints(filename2 + '.txt')\n\n # Find convex hull\n hull1 = []\n hull2 = []\n\n hull_index = cv2.convexHull(np.array(points2), returnPoints=False)\n\n for i in range(0, len(hull_index)):\n hull1.append(points1[int(hull_index[i])])\n hull2.append(points2[int(hull_index[i])])\n\n # Find delanauy traingulation for convex hull points\n\n size_img2 = img2.shape\n rect = (0, 0, size_img2[1], size_img2[0])\n\n dt = calculate_delaunay_triangles(rect, hull2)\n\n if len(dt) == 0:\n quit()\n\n # Apply affine transformation to Delaunay triangles\n for i in range(0, len(dt)):\n t1 = []\n t2 = []\n\n # get points for img1, img2 corresponding to the triangles\n for j in range(0, 3):\n t1.append(hull1[dt[i][j]])\n t2.append(hull2[dt[i][j]])\n\n warp_triangle(img1, img1_warped, t1, t2)\n\n # Calculate Mask\n hull8U = []\n for i in range(0, len(hull2)):\n hull8U.append((hull2[i][0], hull2[i][1]))\n\n mask = np.zeros(img2.shape, dtype=img2.dtype)\n\n cv2.fillConvexPoly(mask, np.int32(hull8U), (255, 255, 255))\n\n r = cv2.boundingRect(np.float32([hull2]))\n\n center = (r[0] + int(r[2] / 2), r[1] + int(r[3] / 2))\n\n # Clone seamlessly.\n output = cv2.seamlessClone(np.uint8(img1_warped), img2, mask, center, cv2.NORMAL_CLONE)\n\n name = f'result{datetime.now()}.jpg'\n name = name.replace(':', '')\n path = os.path.join(path, name)\n if not cv2.imwrite(path, output):\n raise Exception(\"Could not write image\")\n\n return name\n # cv2.imshow(\"Face Swapped\", output)\n # cv2.waitKey(0)\n #\n # cv2.destroyAllWindows()\n","sub_path":"task_03/logic.py","file_name":"logic.py","file_ext":"py","file_size_in_byte":6727,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"62929390","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib import animation\nimport discretisedfield as df\nimport os\nfrom scipy import interpolate\nimport sys\n\ndirectory = sys.argv[1]\nname = sys.argv[2]\n\n# t = np.loadtxt(directory + 'table.txt').transpose()[0]\n# B = np.loadtxt(directory + 'table.txt').transpose()[6]\n\nglobal idx\nidx = 0\n\nfilesToScan = []\n\nfor file in os.listdir(directory):\n if file.endswith('.ovf') and file != 'HexagonalAskLattice.ovf':\n print(file)\n filesToScan.append(int(file.split('.ovf')[0].split('m')[1]))\n\nfilesToScan.sort(key=float)\n# filesToScan = filesToScan[:10]\n\nfilesToScan = [directory + '/m' + \"{:06d}\".format(item) + \".ovf\" for item in filesToScan]\n\nmInit = df.read(filesToScan[0]).array[:, :, 0, 2]\n\n\nfig, ax1 = plt.subplots()\n# left, bottom, width, height = [0.7, 0.7, 0.25, 0.25]\n# ax2 = fig.add_axes([left, bottom, width, height])\n# ax2.set_xlabel('t (ns)')\n# ax2.set_ylabel('B (mT)')\n\n\nim = ax1.imshow(np.tile(mInit - mInit, (5, 5)), animated=True, origin='lower', aspect=0.57735026919)\n# Bplot, = ax2.plot(t[0] * 1e9, B[0] * 1e3)\n# ax2.set_xlim(0, t[0] * 1e9)\n# ax2.set_ylim(0, B[0] * 1e3)\n\ndef getDataIterator():\n for file in filesToScan:\n yield file\n\ndef updateFig(file):\n print(file)\n global idx\n idx += 1\n mz = df.read(file).array[:, :, 0, 2]\n im.set_array(np.tile(1e6*(mz - mInit), (5, 5)))\n # Bplot.set_xdata(t[:idx] * 1e9)\n # Bplot.set_ydata(B[:idx] * 1e3)\n # ax2.set_xlim(0, np.max(t[:idx]) * 1e9)\n # ax2.set_ylim(0, np.max(B[:idx]) * 1e3)\n\nanim = animation.FuncAnimation(fig, updateFig, getDataIterator, interval=25, blit=False, save_count=1e5)\nanim.save(name + \".mp4\")\n","sub_path":"AskLattice/MaxSample/Animate.py","file_name":"Animate.py","file_ext":"py","file_size_in_byte":1681,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"180504929","text":"import numpy as np\nimport pandas as pd\nfrom sklearn.naive_bayes import GaussianNB\n\n\n\n\ndef load_german_dataset():\n X = pd.read_csv(r\"C:\\Users\\aa\\Desktop\\CodeRefonte\\Local_Datasets\\_German.csv\")\n X = np.array(X)\n Y = X.transpose()[-1]\n Y = Y.astype(\"int\")\n X = X.transpose()[:-1]\n X = X.transpose()\n W = []\n for i in X:\n L = []\n cpt = 1\n for j in i:\n l = j\n if (str(j).startswith(\"A\"+str(cpt))):\n l = int(str(j).replace(\"A\"+str(cpt),\"\"))\n L.append(float(l))\n cpt = cpt + 1\n W.append(L)\n return np.array(W),Y\n\n\n#train,target = load_german_dataset()\n#print(train.shape)\n#print(target.shape)\n#print(target)\n#E = Evaluateur_Precision(train,target)\n#E.train(GaussianNB())\n#print(E.vecteur_precision())","sub_path":"DataSets/german_dataset.py","file_name":"german_dataset.py","file_ext":"py","file_size_in_byte":808,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"15228068","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport numpy as np\nimport pandas as pd\nimport sys\nimport pprint\n\n\nusers_number = 0\nitems_number = 0\n\ndef make_user_item_pairs():\n\t# データからitem/userの配列を用意したい。\n\tdf = pd.read_csv(\"./ml-100k/u.data\", sep=\"\\t\", names=[\"user_id\",\"item_id\",\"rating\", \"timestamp\"])\n\n\tglobal users_number\n\tglobal items_number\n\tusers_number = df.max().ix[\"user_id\"]\n\titems_number = df.max().ix[\"item_id\"]\n\n\t# userとitemのpairを表す二次元配列\n\t# 縦user943行、横item1682列の零配列\n\tuser_item_pairs = np.zeros([users_number,items_number])\n\n\t# 映画の情報のデータ\n\t# df_movie = pd.read_csv(\"./ml-100k/u.item\", sep=\"|\")\n\n\t# user_id,item_idに対応するratingの値を、user_item_pairsに代入していく。\n\t# user_id,item_idは1から始まっているので、それぞれ-1している。\n\tfor i in range(len(df)):\n\t user_item_pairs[df.ix[i][\"user_id\"]-1][df.ix[i][\"item_id\"]-1] = df.ix[i][\"rating\"]\n\n\treturn user_item_pairs\n\n#movie_idに対応するmovie_titleをリストで返す\ndef search_movie_title(id_list,score_list):\n movie_title_list=[]\n score_list_reverse = sorted(score_list)[::-1]\n # 映画の情報のデータ\n df_movie = pd.read_csv(\"./ml-100k/u.item\", sep='|', encoding=\"ISO-8859-1\",header=None).ix[:,0:1]\n for x,i in enumerate(id_list):\n movie_title_list.append(list([df_movie.ix[i][1],score_list_reverse[x]]))\n return movie_title_list\n\n#コサイン類似度\ndef cos_similarity(x,y):\n return np.dot(x,y) / (np.linalg.norm(x) * np.linalg.norm(y))\n\n#ユーザー同士の類似度を配列で返す\ndef user_user_similarity(pairs):\n users_sim = np.zeros((users_number, users_number))\n \n for i in range(users_number):\n for j in range(i,users_number):\n if i == j:\n users_sim[i][j] = 1.0\n else:\n sim_score = cos_similarity(pairs[i], pairs[j])\n users_sim[i][j] = sim_score\n users_sim[j][i] = sim_score\n \n return users_sim\n\n# user_idとユーザー間類似度と、user/itemの対応リストを与えた時に、user_idのユーザーに映画をリコメンドする。\n# user_idは-1して用いるのに注意\n# kは推薦する映画の本数\n# lは上位L人の高い類似度をもつユーザーを対象にする\ndef movie_recommend(users_sim, user_item_pairs):\n \n user_id = int(input(\"user_idを入力してください : \"))\n # エラー処理\n if user_id-1 not in range(users_number):\n print(\"No such a user_id. You need to update \\\"u.data\\\" for recommendation.\")\n sys.exit(1)\n\n k = int(input(\"推薦する映画の本数を入力してください : \"))\n if k >1682:\n print(\"Error with number of recommendation.\")\n sys.exit(1)\n\n l = int(input(\"対象にする類似ユーザー数を入力してください : \"))\n if l > 943:\n print(\"Error with number of users.\")\n sys.exit(1)\n l = l + 1\n\n # 重みの合計\n total_weight = 0\n sim_scores = []\n \n #user_idの人との類似度が高いL人の人を対象に考える\n #それ以外の人の類似度は考えないため、0で置き換える\n high_sim_users_indices = np.argpartition(-users_sim[user_id-1], l)[:l] \n for x in range(users_number):\n if x in high_sim_users_indices:\n pass\n else:\n users_sim[user_id-1][x] = 0\n \n \n for i in range(items_number):\n # まだ評価のない(0)ものを対象に処理を行う\n if user_item_pairs[user_id-1][i] == 0:\n \n # 作品iへの評価値と、user_idの人への類似度を掛け合わせた重みの合計を内積を用いて計算\n # 自分自身への類似度は1になるため、その分を差し引いている\n total_weight = np.dot(users_sim[user_id-1],user_item_pairs.T[i])\n\n #たくさんの人に評価された作品の重みは大きくなる\n #作品iを評価している(!=0)評価者の類似度の合計を求め、正規化する\n for_normalization = 0 \n for j in range(users_number):\n if user_item_pairs[j][i] != 0:\n for_normalization += users_sim[user_id-1][j]\n if for_normalization != 0:\n similarity_score = total_weight / for_normalization\n else:\n similarity_score = 0\n sim_scores.append(similarity_score)\n\n #正規化した類似度スコアの内、上位K件のitem_idを降順にソートして取得する\n sim_scores_array = np.array(sim_scores)\n unsorted_max_indices = np.argpartition(-sim_scores_array, k)[:k]\n k_max = sim_scores_array[unsorted_max_indices]\n indices = np.argsort(-k_max)\n max_k_indices = unsorted_max_indices[indices]\n \n return max_k_indices, k_max\n\n\nif __name__ == '__main__':\n\tu_i_pair = make_user_item_pairs()\n\tusers_similarity = user_user_similarity(u_i_pair)\n\tmovie_id = movie_recommend(users_similarity, u_i_pair)\n\tresult = search_movie_title(movie_id[0],movie_id[1])\n\t# print(result)\n\tpprint.pprint(result)\n","sub_path":"recommendation.py","file_name":"recommendation.py","file_ext":"py","file_size_in_byte":5209,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"88316534","text":"# -*- coding:utf-8 -*- \nfrom django.contrib import auth\nfrom django.contrib.auth import middleware as auth_middleware\nfrom django.utils.functional import SimpleLazyObject\nimport json,urllib\nfrom django.conf import settings\nfrom . import helper\n\ndef get_user(request):\n user=auth_middleware.get_user(request)\n if user.is_authenticated()==True:\n return user\n access_token=request.GET.get(helper.SESSION_TOKEN_KEY)\n if not access_token:\n return user\n newuser=auth.authenticate(request=request)\n if newuser:\n user=newuser\n auth.login(request,user)\n request._cached_user=user\n return request._cached_user\n\n\nclass AuthenticationMiddleware(object):\n def process_request(self, request):\n assert hasattr(request, 'session'), (\n \"The Django authentication middleware requires session middleware \"\n \"to be installed. Edit your MIDDLEWARE_CLASSES setting to insert \"\n \"'django.contrib.sessions.middleware.SessionMiddleware' before \"\n \"'django.contrib.auth.middleware.AuthenticationMiddleware'.\"\n )\n helper.auth_user_by_ticket(request)\n request.user = SimpleLazyObject(lambda: auth_middleware.get_user(request))\n","sub_path":"Documents/backupCode/ssoauth/middleware.py","file_name":"middleware.py","file_ext":"py","file_size_in_byte":1230,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"131246922","text":"from math import floor, ceil, sqrt, gcd, log2, log10\r\nfrom decimal import *\r\n\r\ndef TestPerfectPower(n):\r\n\tfor i in range(2, ceil(log2(n))+1): \r\n\t\troot = n ** (1/Decimal(i))\r\n\t\tif round(root)==root: return True\r\n\treturn False\r\n\r\ndef get_r(n):\r\n\tl = log2(n)\r\n\t\r\n\tmaxk = floor(l ** 2)\r\n\tmaxr = max(3, ceil(l ** 5))\r\n\t\r\n\tnextR = True\r\n\t\r\n\tr = Decimal(2)\r\n\t\r\n\twhile (nextR and (r < maxr)):\r\n\t\tnextR = False\r\n\t\t\r\n\t\tk = Decimal(1)\r\n\t\t\r\n\t\twhile (not nextR and k <= maxk):\r\n\t\t\tnextR = (pow(n, k, r) in [0, 1])\r\n\t\t\t\r\n\t\t\tk = k + 1\r\n\t\t\r\n\t\tr = r + 1\r\n\t\r\n\tr -= 1\r\n\treturn r\r\n\r\ndef gcd(a, b):\r\n\twhile True:\r\n\t\tif a >= b:\r\n\t\t\ta = a % b\r\n\t\telif a < b:\r\n\t\t\tb = b % a\r\n\t\t\r\n\t\tif a==0:\r\n\t\t\treturn b\r\n\t\tif b==0:\r\n\t\t\treturn a\r\n\r\ndef gcd_extended(a,b):\r\n\t#Thanks to Robert-Campbell-256 on github for this\r\n\ta1=1; b1=0; a2=0; b2=1; aneg=1; bneg=1\r\n\tif(a < 0):\r\n\t\ta = -a; aneg=-1\r\n\tif(b < 0):\r\n\t\tb = -b; bneg=-1\r\n\twhile (1):\r\n\t\tquot = -(a // b)\r\n\t\ta = a % b\r\n\t\ta1 = a1 + quot*a2; b1 = b1 + quot*b2\r\n\t\tif(a == 0):\r\n\t\t\treturn (b, a2*aneg, b2*bneg)\r\n\t\tquot = -(b // a)\r\n\t\tb = b % a;\r\n\t\ta2 = a2 + quot*a1; b2 = b2 + quot*b1\r\n\t\tif(b == 0):\r\n\t\t\treturn (a, a1*aneg, b1*bneg)\r\n\r\ndef modinverse(a, n):\r\n\t(gcd, ax, bn) = gcd_extended(a, n)\r\n\tif gcd!= 1: raise ValueError(\"Modular inverse does not exist\")\r\n\treturn ax % n\r\n\r\ndef lcm(a, b):\r\n\tc = a * b\r\n\tc = c / gcd(a, b)\r\n\ttry: c=int(c)\r\n\texcept: pass\r\n\treturn c\r\n\r\ndef φ(n):\r\n\tt = 0\r\n\ti = 1\r\n\twhile i < n:\r\n\t\tif gcd(n, i)==1: t += 1\r\n\t\ti+=1\r\n\t\r\n\treturn t\r\n\r\ndef λ(n):\r\n\tif type(n) is list:\r\n\t\t#TODO: make this actually correct\r\n\t\tt = 1\r\n\t\tfor i in n: t = lcm(t, (i-1))\r\n\t\treturn t\r\n\t\r\n\telif type(n) is int:\r\n\t\tif TestPerfectPower(n):\r\n\t\t\tfor r in range(ceil(log2(N))+1):\r\n\t\t\t\tp = n ** (1/Decimal(i))\r\n\t\t\t\tif round(p)==p:\r\n\t\t\t\t\treturn (p**(r-1)) * (p-1)\r\n\t\telse:\r\n\t\t\t#TODO\r\n\t\t\tpass\r\n\r\ndef isPrime(n):\r\n\t#Basic AKS Primality Check, no fancyness needed\r\n\t#runs in O(log2(n)^5)\r\n\t\r\n\tif n%2 == 0: return False\r\n\t\r\n\tif TestPerfectPower(n): return False\r\n\t\r\n\tr = get_r(n)\r\n\t\r\n\ta = r\r\n\t#for (a=r; a>1 && a<n; a--;)\r\n\twhile a > 1 and a < n:\r\n\t\tg = gcd(a, n)\r\n\t\tif g != 1:\r\n\t\t\tprint(\"factor: \" + str(g))\r\n\t\t\treturn False\r\n\t\ta -= 1\r\n\t\r\n\tif n <= 5690034 and n <= r: return True\r\n\t\r\n\ta = 1\r\n\t\r\n\tbound = floor(sqrt(φ(r)) * log2(n))\r\n\t\r\n\t#for (a=1; a<=bound; a++;)\r\n\twhile a <= bound:\r\n\t\tif pow(a, n, n) - a != 0:\r\n\t\t\treturn False\r\n\t\ta+=1\r\n\t\r\n\treturn True\r\n\r\n\r\n#Sieve prime check adapted from https://github.com/smanikar/primality-testing/blob/master/proposal/src/AKS.java\r\ndef sieveEratos():\r\n\tglobal sieveSize \r\n\tsieveSize = 1000000\r\n\tglobal sieveArray \r\n\tsieveArray = [False] * (sieveSize+1)\r\n\tsieveArray[1] = True\r\n\ti = 2\r\n\twhile i < sqrt(sieveSize):\r\n\t\tif sieveArray[i] is not True:\r\n\t\t\tj = i * i\r\n\t\t\twhile j <= sieveSize: sieveArray[j] = True; j+=i\r\n\t\ti+=1\r\n\r\ndef checkSievePrime(val):\r\n\treturn not sieveArray[int(val)]\r\n\r\ndef largestFactor(num):\r\n\ti = int(num)\r\n\tif i==1: return i\r\n\twhile i > 1:\r\n\t\twhile sieveArray[i]:\r\n\t\t\ti-=1\r\n\t\tif num%i == 0:\r\n\t\t\treturn i\r\n\t\ti-=1\r\n\treturn num\r\n\r\ndef mPower(x, y, n):\r\n\treturn pow(x, y, n)\r\n\r\ndef sieve_prime_check(n):\r\n\tlog = floor(log10(n))\r\n\t\r\n\tsieveEratos()\r\n\t\r\n\tif TestPerfectPower(n): return False\r\n\tr = Decimal(2)\r\n\tx = r\r\n\t\r\n\t\r\n\t#for (r=2; r<n; r++;)\r\n\twhile r<n:\r\n\t\tif gcd(r, n)!=1: print(\"checking r\", r); return False\r\n\t\t\r\n\t\tif checkSievePrime(r):\r\n\t\t\tprint(\"checking r\", r, end=\"\\r\")\r\n\t\t\tquot = largestFactor(r - 1)\r\n\t\t\tdivisor = (r - 1) / quot\r\n\t\t\ttm = 4 * (sqrt(r)) * log;\r\n\t\t\tpowOf = mPower(n, divisor, r);\r\n\t\t\tif quot>=tm and powOf != 1: break\r\n\t\t\r\n\t\tr += 1\r\n\t\r\n\tprint(\"found r of \" + str(r))\r\n\t\r\n\taLimit = ceil(2 * sqrt(r) * log)\r\n\t\r\n\taCounter = Decimal(1)\r\n\t#for (aCounter = 1; aCounter < aLimit; aCounter++;)\r\n\twhile aCounter < aLimit:\r\n\t\tprint(\"checking\", aCounter, end=\"\\r\")\r\n\t\taBigNum = aCounter\r\n\t\tleftH = (mPower(x-aBigNum, n, n))%n\r\n\t\trightH = (mPower(x, n, n)-aBigNum) % n\r\n\t\tif leftH != rightH: print(\"checking\", aCounter); return False\r\n\t\taCounter+=1\r\n\t\r\n\tprint(\"\\n\")\r\n\t\r\n\treturn True\r\n\r\ndef fasterfactor(n):\r\n\ti = Decimal(2)\r\n\tp = Decimal(1)\r\n\tk = n\r\n\tfactors = []\r\n\tif sieve_prime_check(n): factors.append(n)\r\n\twhile (p*p <= k and i*i <= k):\r\n\t\tif n % i == 0:\r\n\t\t\tn = n / i\r\n\t\t\tp = p * i\r\n\t\t\tfactors.append(i)\r\n\t\t\tif p==k or sieve_prime_check(n): break\r\n\t\telse:\r\n\t\t\ti = i + 1\r\n\tif p != k:\r\n\t\tfactors.append(int(k/p))\r\n\t\r\n\treturn factors\r\n\r\nif __name__ == '__main__':\r\n\tn = Decimal(input())\r\n\tgetcontext().prec = 2*len(str(n))\r\n\tprint(\"prime\" if sieve_prime_check(n) else \"composite\")\r\n","sub_path":"PRIMES.py","file_name":"PRIMES.py","file_ext":"py","file_size_in_byte":4462,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"262683925","text":"# Copyright 2021 The Cirq Developers\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\nimport datetime\n\nfrom typing import Callable, Dict, Iterable, List, Optional, Sequence, TYPE_CHECKING, Union\n\nimport cirq\n\nfrom cirq_google.api import v2\nfrom cirq_google.engine import calibration, util, validating_sampler\nfrom cirq_google.engine.abstract_local_processor import AbstractLocalProcessor\nfrom cirq_google.engine.abstract_local_program import AbstractLocalProgram\nfrom cirq_google.engine.abstract_program import AbstractProgram\nfrom cirq_google.engine.local_simulation_type import LocalSimulationType\nfrom cirq_google.engine.simulated_local_job import SimulatedLocalJob\nfrom cirq_google.engine.simulated_local_program import SimulatedLocalProgram\nfrom cirq_google.serialization.circuit_serializer import CIRCUIT_SERIALIZER\nfrom cirq_google.engine.processor_sampler import ProcessorSampler\n\nif TYPE_CHECKING:\n import cirq_google as cg\n from cirq_google.serialization.serializer import Serializer\n\nVALID_LANGUAGES = [\n 'type.googleapis.com/cirq.google.api.v2.Program',\n 'type.googleapis.com/cirq.google.api.v2.BatchProgram',\n]\n\nGATE_SET_VALIDATOR_TYPE = Callable[\n [Sequence[cirq.AbstractCircuit], Sequence[cirq.Sweepable], int, 'Serializer'], None,\n]\n\n\ndef _date_to_timestamp(\n union_time: Optional[Union[datetime.datetime, datetime.date, int]]\n) -> Optional[int]:\n if isinstance(union_time, int):\n return union_time\n elif isinstance(union_time, datetime.datetime):\n return int(union_time.timestamp())\n elif isinstance(union_time, datetime.date):\n return int(datetime.datetime.combine(union_time, datetime.datetime.min.time()).timestamp())\n return None\n\n\nclass SimulatedLocalProcessor(AbstractLocalProcessor):\n \"\"\"A processor backed by a sampler and device.\n\n Intended for local simulation testing, this processor will\n create a `ValidationSampler` that will validate requests based on\n the provided device and an additional Callable (that can verify\n serialization constraints, for instance). Jobs will then be\n executed using the provided sampler.\n\n This class also supports a list of calibration metrics that are\n stored in-memory to replicate Quantum Engine calibration metrics.\n\n This class can be used as a local emulator for the Quantum Engine\n API or for testing or mocking.\n\n Attributes:\n sampler: A `cirq.Sampler` that can execute the quantum jobs.\n device: An optional device, for validation of qubit connectivity.\n validator: A Callable that can validate additional characteristics\n beyond the device, such as serialization, repetition limits, etc.\n gate_set_validator: A callable that can validate a circuit and sweeps\n based on the given serializer.\n simulation_type: Whether sampler execution should be\n synchronous or asynchronous.\n calibrations: A dictionary of calibration metrics keyed by epoch seconds\n that can be returned by the processor.\n processor_id: Unique string id of the processor.\n engine: The parent `AbstractEngine` object, if available.\n expected_down_time: Optional datetime of the next expected downtime.\n For informational purpose only.\n expected_recovery_time: Optional datetime when the processor is\n expected to be available again. For informational purpose only.\n schedule: List of time slots that the scheduling/reservation should\n use. All time slots must be non-overlapping.\n project_name: A project_name for resource naming.\n \"\"\"\n\n def __init__(\n self,\n *args,\n sampler: cirq.Sampler = cirq.Simulator(),\n device: cirq.Device = cirq.UNCONSTRAINED_DEVICE,\n validator: validating_sampler.VALIDATOR_TYPE = None,\n gate_set_validator: GATE_SET_VALIDATOR_TYPE = None,\n simulation_type: LocalSimulationType = LocalSimulationType.SYNCHRONOUS,\n calibrations: Optional[Dict[int, calibration.Calibration]] = None,\n **kwargs,\n ):\n super().__init__(*args, **kwargs)\n self._calibrations = calibrations or {}\n self._device = device\n self._simulation_type = simulation_type\n self._gate_set_validator = gate_set_validator or (lambda a, b, c, d: None)\n self._validator = validator\n self._sampler = validating_sampler.ValidatingSampler(\n device=self._device, validator=self._validator, sampler=sampler\n )\n self._programs: Dict[str, AbstractLocalProgram] = {}\n\n def remove_program(self, program_id: str):\n \"\"\"Remove reference to a child program.\"\"\"\n if program_id in self._programs:\n del self._programs[program_id]\n\n def get_calibration(self, calibration_timestamp_seconds: int) -> calibration.Calibration:\n return self._calibrations[calibration_timestamp_seconds]\n\n def get_latest_calibration(self, timestamp: int) -> Optional[calibration.Calibration]:\n if not self._calibrations:\n return None\n return self._calibrations[max(self._calibrations)]\n\n def get_current_calibration(self) -> Optional[calibration.Calibration]:\n return self.get_latest_calibration(int(datetime.datetime.now().timestamp()))\n\n def get_device(self, gate_sets: Optional[Iterable['Serializer']] = None) -> cirq.Device:\n \"\"\"Returns a `Device` created from the processor's device specification.\n\n This method queries the processor to retrieve the device specification,\n which is then use to create a `SerializableDevice` that will validate\n that operations are supported and use the correct qubits.\n \"\"\"\n return self._device\n\n def get_device_specification(self) -> Optional[v2.device_pb2.DeviceSpecification]:\n raise NotImplementedError\n\n def health(self):\n return 'OK'\n\n def list_calibrations(\n self,\n earliest_timestamp: Optional[Union[datetime.datetime, datetime.date, int]] = None,\n latest_timestamp: Optional[Union[datetime.datetime, datetime.date, int]] = None,\n **kwargs,\n ) -> List[calibration.Calibration]:\n earliest_timestamp_seconds = _date_to_timestamp(earliest_timestamp) or 0\n latest_timestamp_seconds = (\n _date_to_timestamp(latest_timestamp)\n or (datetime.datetime.now() + datetime.timedelta(days=10000)).timestamp()\n )\n return [\n cal[1]\n for cal in self._calibrations.items()\n if earliest_timestamp_seconds <= cal[0] <= latest_timestamp_seconds\n ]\n\n @util.deprecated_gate_set_parameter\n def get_sampler(self, gate_set: Optional['Serializer'] = None) -> cirq.Sampler:\n return ProcessorSampler(processor=self)\n\n def supported_languages(self) -> List[str]:\n return VALID_LANGUAGES\n\n def list_programs(\n self,\n created_before: Optional[Union[datetime.datetime, datetime.date]] = None,\n created_after: Optional[Union[datetime.datetime, datetime.date]] = None,\n has_labels: Optional[Dict[str, str]] = None,\n ) -> List[AbstractLocalProgram]:\n before_limit = created_before or datetime.datetime(datetime.MAXYEAR, 1, 1)\n after_limit = created_after or datetime.datetime(datetime.MINYEAR, 1, 1)\n labels = has_labels or {}\n\n def _labels_match(user_labels, program_labels):\n return all(\n (key in program_labels and program_labels[key] == labels[key]) for key in labels\n )\n\n return list(\n filter(\n lambda program: after_limit < program.create_time() < before_limit\n and _labels_match(labels, program.labels()),\n self._programs.values(),\n )\n )\n\n def get_program(self, program_id: str) -> AbstractProgram:\n \"\"\"Returns an AbstractProgram for an existing Quantum Engine program.\n\n Args:\n program_id: Unique ID of the program within the parent project.\n\n Returns:\n An AbstractProgram for the program.\n\n Raises:\n KeyError: if program is not found\n \"\"\"\n return self._programs[program_id]\n\n @util.deprecated_gate_set_parameter\n def run_batch(\n self,\n programs: Sequence[cirq.AbstractCircuit],\n program_id: Optional[str] = None,\n job_id: Optional[str] = None,\n params_list: Sequence[cirq.Sweepable] = None,\n repetitions: int = 1,\n gate_set: Optional['Serializer'] = None,\n program_description: Optional[str] = None,\n program_labels: Optional[Dict[str, str]] = None,\n job_description: Optional[str] = None,\n job_labels: Optional[Dict[str, str]] = None,\n ) -> SimulatedLocalJob:\n if program_id is None:\n program_id = self._create_id(id_type='program')\n if job_id is None:\n job_id = self._create_id(id_type='job')\n if gate_set is None:\n gate_set = CIRCUIT_SERIALIZER\n self._gate_set_validator(programs, params_list or [{}], repetitions, gate_set)\n self._programs[program_id] = SimulatedLocalProgram(\n program_id=program_id,\n simulation_type=self._simulation_type,\n circuits=programs,\n engine=self.engine(),\n processor=self,\n )\n job = SimulatedLocalJob(\n job_id=job_id,\n processor_id=self.processor_id,\n parent_program=self._programs[program_id],\n repetitions=repetitions,\n sweeps=list(params_list) if params_list is not None else None,\n sampler=self._sampler,\n simulation_type=self._simulation_type,\n )\n self._programs[program_id].add_job(job_id, job)\n return job\n\n @util.deprecated_gate_set_parameter\n def run(\n self,\n program: cirq.Circuit,\n program_id: Optional[str] = None,\n job_id: Optional[str] = None,\n param_resolver: Optional[cirq.ParamResolver] = None,\n repetitions: int = 1,\n gate_set: Optional['Serializer'] = None,\n program_description: Optional[str] = None,\n program_labels: Optional[Dict[str, str]] = None,\n job_description: Optional[str] = None,\n job_labels: Optional[Dict[str, str]] = None,\n ) -> 'cg.EngineResult':\n \"\"\"Runs the supplied Circuit on this processor.\n\n Args:\n program: The Circuit to execute. If a circuit is\n provided, a moment by moment schedule will be used.\n program_id: A user-provided identifier for the program. This must\n be unique within the Google Cloud project being used. If this\n parameter is not provided, a random id of the format\n 'prog-################YYMMDD' will be generated, where # is\n alphanumeric and YYMMDD is the current year, month, and day.\n job_id: Job identifier to use. If this is not provided, a random id\n of the format 'job-################YYMMDD' will be generated,\n where # is alphanumeric and YYMMDD is the current year, month,\n and day.\n param_resolver: Parameters to run with the program.\n repetitions: The number of repetitions to simulate.\n gate_set: The gate set used to serialize the circuit. The gate set\n must be supported by the selected processor.\n program_description: An optional description to set on the program.\n program_labels: Optional set of labels to set on the program.\n job_description: An optional description to set on the job.\n job_labels: Optional set of labels to set on the job.\n Returns:\n A single Result for this run.\n \"\"\"\n return self.run_sweep(\n program=program,\n program_id=program_id,\n job_id=job_id,\n params=[param_resolver or cirq.ParamResolver({})],\n repetitions=repetitions,\n program_description=program_description,\n program_labels=program_labels,\n job_description=job_description,\n job_labels=job_labels,\n ).results()[0]\n\n @util.deprecated_gate_set_parameter\n def run_sweep(\n self,\n program: cirq.Circuit,\n program_id: Optional[str] = None,\n job_id: Optional[str] = None,\n params: cirq.Sweepable = None,\n repetitions: int = 1,\n gate_set: Optional['Serializer'] = None,\n program_description: Optional[str] = None,\n program_labels: Optional[Dict[str, str]] = None,\n job_description: Optional[str] = None,\n job_labels: Optional[Dict[str, str]] = None,\n ) -> SimulatedLocalJob:\n if program_id is None:\n program_id = self._create_id(id_type='program')\n if job_id is None:\n job_id = self._create_id(id_type='job')\n if gate_set is None:\n gate_set = CIRCUIT_SERIALIZER\n self._gate_set_validator([program], [params], repetitions, gate_set)\n self._programs[program_id] = SimulatedLocalProgram(\n program_id=program_id,\n simulation_type=self._simulation_type,\n circuits=[program],\n processor=self,\n engine=self.engine(),\n )\n job = SimulatedLocalJob(\n job_id=job_id,\n processor_id=self.processor_id,\n parent_program=self._programs[program_id],\n repetitions=repetitions,\n sweeps=[params],\n sampler=self._sampler,\n simulation_type=self._simulation_type,\n )\n self._programs[program_id].add_job(job_id, job)\n return job\n\n def run_calibration(self, *args, **kwargs):\n raise NotImplementedError\n","sub_path":"cirq-google/cirq_google/engine/simulated_local_processor.py","file_name":"simulated_local_processor.py","file_ext":"py","file_size_in_byte":14342,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"2938847","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nimport numpy as np\n\nnclasses = 20 \n\nclass Net(nn.Module):\n def __init__(self):\n super(Net, self).__init__()\n self.conv1 = nn.Conv2d(3, 10, kernel_size=5)\n self.conv2 = nn.Conv2d(10, 20, kernel_size=5)\n self.conv3 = nn.Conv2d(20, 20, kernel_size=5)\n self.fc1 = nn.Linear(320, 50)\n self.fc2 = nn.Linear(50, nclasses)\n\n def forward(self, x):\n x = F.relu(F.max_pool2d(self.conv1(x), 2))\n x = F.relu(F.max_pool2d(self.conv2(x), 2))\n x = F.relu(F.max_pool2d(self.conv3(x), 2))\n x = x.view(-1, 320)\n x = F.relu(self.fc1(x))\n return self.fc2(x)\n\n\ndef train(epoch):\n model.train()\n for batch_idx, (data, target) in enumerate(train_loader):\n if use_cuda:\n data, target = data.cuda(), target.cuda()\n optimizer.zero_grad()\n output = model(data)\n #criterion = torch.nn.CrossEntropyLoss(reduction='elementwise_mean')\n criterion = torch.nn.CrossEntropyLoss()\n loss = criterion(output, target)\n loss.backward()\n optimizer.step()\n if batch_idx % args.log_interval == 0:\n print('Train Epoch: {} [{}/{} ({:.0f}%)]\\tLoss: {:.6f}'.format(\n epoch, batch_idx * len(data), len(train_loader.dataset),\n 100. * batch_idx / len(train_loader), loss.data.item()))\n\ndef validation():\n model.eval()\n validation_loss = 0\n correct = 0\n for data, target in val_loader:\n if use_cuda:\n data, target = data.cuda(), target.cuda()\n output = model(data)\n # sum up batch loss\n #criterion = torch.nn.CrossEntropyLoss(reduction='elementwise_mean')\n criterion = torch.nn.CrossEntropyLoss()\n validation_loss += criterion(output, target).data.item()\n # get the index of the max log-probability\n pred = output.data.max(1, keepdim=True)[1]\n correct += pred.eq(target.data.view_as(pred)).cpu().sum()\n\n validation_loss /= len(val_loader.dataset)\n print('\\nValidation set: Average loss: {:.4f}, Accuracy: {}/{} ({:.0f}%)\\n'.format(\n validation_loss, correct, len(val_loader.dataset),\n 100. * correct / len(val_loader.dataset)))\n\ndef init_resnet():\n model_conv = torchvision.models.resnet152(pretrained=True)\n for param in model_conv.parameters():\n param.requires_grad = False\n # reset the last convolutional layer\n for param in model_conv.layer4[2].conv3.parameters():\n param.requires_grad = True\n\n # Parameters of newly constructed modules have requires_grad=True by default\n num_ftrs = model_conv.fc.in_features\n #num_ftrs = model_conv.classifier.in_features\n model_conv.fc = nn.Linear(num_ftrs, nclasses)\n\n model_conv = model_conv.to(device)\n criterion = nn.CrossEntropyLoss()\n\n params_to_optimize = list(model_conv.fc.parameters()) + \\\n list(model_conv.layer4[2].conv3.parameters())\n\n optimizer_conv = optim.Adam(params_to_optimize, lr=0.001)\n\n # Decay LR by a factor of 0.1 every 20 epochs\n exp_lr_scheduler = lr_scheduler.StepLR(optimizer_conv, step_size=20, gamma=0.1)\n\n model_conv_best = transfer_learning(model_conv, criterion, optimizer_conv,\n exp_lr_scheduler, num_epochs=40)\n\n return model_conv_best\n\n\ndef get_proba(data_dir, model, data_transforms):\n probabilities = []\n model.eval()\n if use_cuda:\n print('Using GPU')\n model.cuda()\n else:\n print('Using CPU')\n for f in tqdm(os.listdir(data_dir)):\n if 'jpg' in f:\n data = data_transforms(pil_loader(data_dir + '/' + f))\n data = data.view(1, data.size(0), data.size(1), data.size(2))\n if use_cuda:\n data = data.cuda()\n output = model(data)\n pred_proba = output.data.cpu().numpy()\n probabilities.append(pred_proba)\n proba = np.exp(np.array(probabilities)).squeeze()\n proba = proba / np.sum(proba, axis=1).reshape(-1, 1)\n return proba\n\ndef feature_extraction(model, dataloader, use_cuda = True):\n\n device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n\n features = []\n targets = []\n model.eval()\n if use_cuda:\n print('Using GPU')\n model.cuda()\n else:\n print('Using CPU')\n for inputs, labels in dataloader:\n inputs = inputs.to(device)\n labels = labels.to(device)\n output = model(inputs)\n feature = output.data.cpu().numpy()\n features.append(feature)\n targets.append(labels.data.cpu().numpy())\n return np.array(features).squeeze(), np.array(targets).squeeze()\n","sub_path":"models/deep_learning.py","file_name":"deep_learning.py","file_ext":"py","file_size_in_byte":4716,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"403357462","text":"import csv\nimport numpy as np\nimport copy\n#_______________________________________________________________________________\ndef bubble(a,b):\n c=copy.deepcopy(a)\n print(type(c))\n while(1):\n count=0\n for i in range(np.size(c,0)-1):\n if c[i,b]>c[i+1,b]:\n temp=copy.deepcopy(c[i,:])\n c[i,:]=copy.deepcopy(c[i+1,:])\n c[i+1,:]=copy.deepcopy(temp)\n count=count+1\n if count==0:\n #print(np.concatenate((a,c), axis=1))\n return np.matrix(c)\n\n#_______________________________________________________________________________\ndatafile = open('X.csv', 'r')\ndatareader = csv.reader(datafile, delimiter=',')\ndatax = []\nfor row in datareader:\n datax.append(row)\n\ndatax=np.array((datax)).astype(float)\ndatax=datax.T\n\n#_______________________________________________________________________________\ndatafile = open('Y.csv', 'r')\ndatareader = csv.reader(datafile, delimiter=',')\ndatay = []\nfor row in datareader:\n datay.append(row)\ndatay=np.array(datay).astype(float)\n#_______________________________________________________________________________\nk_number=int(input(\"enter the value of 'k' : \"))\n\ninputs=[]\nfor iter in range(np.size(datax, 1)):\n inputs.append(float(input(\"input x:\")))\n\ndistances=0\n\nfor iter in range(np.size(datax,1)):\n #print(iter)\n distances=distances+np.power(inputs[iter]-datax[:,iter],2)\n\n#print(np.shape(np.matrix(distances)))\ndistances=np.concatenate((np.matrix(distances).T,datay),axis=1)\n#distances=np.concatenate((np.matrix(np.sqrt(np.power(x1-datax[:,0],2)+np.power(x2-datax[:,1],2))).T, datay),axis=1)\ndistances_1=(bubble(distances,0))\n\nprint(type(distances_1))\nprint(np.shape(distances_1))\nprint(distances_1[:k_number,:])\n\nmeans=np.mean(distances_1[0:k_number, 1].astype(float))\n\nif means >=0:\n print(\"y_prediction : 1\")\nelse:\n print(\"y_prediction : -1\")\n","sub_path":"p2_a2.py","file_name":"p2_a2.py","file_ext":"py","file_size_in_byte":1910,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"320517366","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('reviews', '0050_merge'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='study',\n name='status',\n field=models.CharField(default='U', max_length=1, choices=[('U', 'N\\xe3o classificado'), ('R', 'Rejeitado'), ('A', 'Accepted'), ('D', 'Duplicated')]),\n ),\n ]\n","sub_path":"parsifal/reviews/migrations/0051_auto_20190724_1335.py","file_name":"0051_auto_20190724_1335.py","file_ext":"py","file_size_in_byte":500,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"53575238","text":"import sys\n\neratosthenes = [False, False] + [True for _ in range (10000)]\nfor _ in range (2, int(10001 ** 0.5)):\n if eratosthenes[_]:\n for temp in range (_ * 2, 10001, _):\n eratosthenes[temp] = False\n\nfor _ in range (int(sys.stdin.readline().rstrip('\\n'))):\n goal = int(sys.stdin.readline().rstrip('\\n'))\n if eratosthenes[goal // 2]:\n print (goal // 2, goal // 2, sep = ' ')\n else:\n mid = goal // 2\n d = 0\n for _ in range (mid, 10001):\n if eratosthenes[_]:\n if eratosthenes[mid - d]:\n print(mid - d, _, sep = ' ')\n break\n d += 1","sub_path":"(9020) 골드바흐의 추측.py","file_name":"(9020) 골드바흐의 추측.py","file_ext":"py","file_size_in_byte":661,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"289960627","text":"from composeparser.parse import ComposeParser\nfrom .compose_defaults import ServiceEntry\nimport json\nfrom collections import defaultdict\n\n\nclass ComposeProcessor(object):\n \"\"\"process parsed compose file object\"\"\"\n def __init__(self, compose_obj, docker_registry=''):\n super(ComposeProcessor, self).__init__()\n self.compose_obj = compose_obj\n self.docker_registry = docker_registry\n self.ports_for_groups = defaultdict(lambda: defaultdict(dict))\n\n def gen_service_task(self, task_name, service, group_name=None):\n task = {}\n task['driver'] = 'docker'\n service = ServiceEntry(service)\n service.init()\n task['env'] = service.get('environment', {})\n\n task['config'] = {\n 'image':\n service.get('image', self.docker_registry + task_name),\n 'ports':\n ['{}'.format(x['published'])\n for x in service['ports']] if 'ports' in service.keys() else [],\n 'network_mode':\n list(service['networks'].keys())[0],\n 'network_aliases': [task_name],\n 'extra_hosts':\n service['extra_hosts'],\n 'privileged':\n service['privileged']\n }\n if service['privileged']:\n task['user'] = 'root'\n if 'volumes' in service.keys():\n task['config']['mount'] = []\n for vol in service['volumes']:\n task['config']['mount'].append(vol)\n\n for x in (service['ports'] if 'ports' in service.keys() else []):\n self.ports_for_groups[group_name]['port'][x['published']] = {\n 'to': x['target'],\n 'static': x['published']\n }\n limits = service['deploy']['resources']['limits']\n task['resources'] = {\n 'cpu': int(float(limits['cpus']) * 1000),\n 'memory': int(limits['memory'][:-1])\n }\n #TODO: process \"depends on\"\n # https://www.nomadproject.io/docs/job-specification/lifecycle#init-task-pattern\n return task_name, task\n\n def gen_network_task(self, network_name):\n task = {}\n task['lifecycle'] = {\"hook\": \"prestart\", \"sidecar\": False}\n task['driver'] = 'raw_exec'\n task['config'] = {\n 'command':\n '/bin/sh',\n 'args':\n ['-c', 'docker network create {} || exit 0'.format(network_name)]\n }\n return '{}_net_init'.format(network_name), task\n\n def gen_service_tasks(self, services, group_name=None):\n tasks = dict([\n self.gen_service_task(task_name, task, group_name)\n for (task_name, task) in services.items()\n ])\n return tasks\n\n def gen_group(self, group_name):\n group = {}\n #TODO: add volume creation tasks\n group['task'] = self.gen_service_tasks(self.compose_obj['services'],\n group_name)\n network_task_name, network_task = self.gen_network_task(group_name)\n group['task'][network_task_name] = network_task\n #TODO: make network ports dinamic if not specified\n group['network'] = self.ports_for_groups[group_name]\n return group_name, group\n\n def gen_job(self, job_name):\n job = {}\n job['datacenters'] = ['dc1']\n group_name = list(self.compose_obj['networks'].keys())[0]\n job['group'] = dict([self.gen_group(g_n) for g_n in [group_name]])\n return job_name, job\n\n def gen_nomad_job(self):\n job_name = list(self.compose_obj['networks'].keys())[0]\n nomad_job = {}\n nomad_job['job'] = dict([self.gen_job(j_n) for j_n in [job_name]])\n return nomad_job\n\n\ndef main(args):\n filepath = str(args.compose_file.resolve())\n l = ComposeParser(filepath)\n compose_obj = l.load()\n pr = ComposeProcessor(compose_obj, docker_registry=args.registry_base)\n result = pr.gen_nomad_job()\n with args.nomad_job_file as f:\n f.write(json.dumps(result, indent=2))\n","sub_path":"composenomadconvertor/produce_tasks.py","file_name":"produce_tasks.py","file_ext":"py","file_size_in_byte":4013,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"560263881","text":"import tensorflow as tf\nimport collections\nimport numpy as np\n\n\nprint('Hello Word2Vec!')\n\nwebsites = [\n ('Sohu', 'http://www.google.com/', u'张朝阳'),\n ('Sina', 'http://www.sina.com.cn/', u'王志东'),\n ('163', 'http://www.163.com/', u'丁磊')\n]\n\nw = collections.namedtuple('Website', ['name', 'url', 'founder'])\n\ns = '''A Counter is a dict subclass for counting hashable objects. It is an unordered collection where elements are stored as dictionary keys and their counts are stored as dictionary values. Counts are allowed to be any integer value including zero or negative counts. The Counter class is similar to bags or multisets in other languages.'''.lower()\n\nc = collections.Counter(s)\nprint(c.most_common(5))\n\nd = collections.deque(maxlen=10)\nd.append(5)\n\n\nbatch = np.ndarray(shape=[8], dtype=np.int32)\nprint(batch)\n\n# 参数意思分别 是从a 中以概率P,随机选择3个, p没有指定的时候相当于是一致的分布\na1 = np.random.choice(a=5, size=3, replace=False, p=None)\nprint(a1)\n# 非一致的分布,会以多少的概率提出来\na2 = np.random.choice(a=5, size=3, replace=False, p=[0.2, 0.1, 0.3, 0.4, 0.0])\nprint(a2)\n\n","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1164,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"166043409","text":"import copy\nimport torch\nimport multiprocessing as mp\nfrom misc.utils import make_env\nfrom misc.batch_episode import BatchEpisode\nfrom env.subproc_vec_env import SubprocVecEnv\n\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\n\nclass BatchSampler(object):\n def __init__(self, args):\n self.args = args\n self.num_workers = mp.cpu_count() - 1\n if self.num_workers > args.n_traj:\n self.num_workers = args.n_traj\n\n self.queue = mp.Queue()\n self.envs = SubprocVecEnv(\n envs=[make_env(args.env_name, args.n_agent) for _ in range(self.num_workers)], \n queue=self.queue, args=args)\n\n # Set seed to envs\n self.envs.seed(0)\n\n def sample(self):\n episode = BatchEpisode(1)\n for i in range(1):\n self.queue.put(i)\n for _ in range(self.num_workers):\n self.queue.put(None)\n\n observations, batch_ids = self.envs.reset()\n dones = [False]\n while (not all(dones)) or (not self.queue.empty()):\n actions = copy.deepcopy(observations)\n new_observations, rewards, dones, new_batch_ids, _ = self.envs.step(actions)\n episode.append(observations, actions, rewards, batch_ids)\n observations, batch_ids = new_observations, new_batch_ids\n\n episode.check_length()\n\n return episode\n\n def reset_task(self, task):\n tasks = [task for _ in range(self.num_workers)]\n reset = self.envs.reset_task(tasks)\n return all(reset)\n","sub_path":"misc/batch_sampler.py","file_name":"batch_sampler.py","file_ext":"py","file_size_in_byte":1539,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"487100176","text":"import os, hashlib\nfrom flask import Blueprint, request, jsonify\nfrom app.bots.models import Bot\n\nbots = Blueprint('bots_blueprint', __name__, url_prefix='/api/v2')\n\n\n@bots.route('/bots', methods=['GET'])\ndef get_bots():\n bot_list = Bot.objects\n return bot_list.to_json()\n\n\n@bots.route('/bots', methods=['POST'])\ndef add_bot():\n content = request.get_json(silent=True)\n\n if 'name' in content and 'lang' in content:\n bot = Bot()\n bot.bot_id = content['name'] + '-' + content['lang']\n bot.name = content['name']\n bot.lang = content['lang']\n bot.clientSecretKey = hashlib.md5(os.urandom(32)).hexdigest()\n bot.endpointEnabled = False\n bot.save()\n return jsonify({'status': 'success', 'message': 'Inserted'}), 200\n\n return jsonify({'status': 'error', 'message': 'Error creating agent'}), 500\n\n\n@bots.route('/bots/<bot_id>', methods=['PUT'])\ndef update_bot(bot_id):\n content = request.get_json(silent=True)\n\n bot = Bot.objects.get(bot_id=bot_id)\n bot.clientSecretKey = content['client_secret_key']\n bot.endpoint_enabled = content['endpoint_enabled']\n bot.engine = content['engine']\n bot.watson_conversation_password = content['watson_conversation_password']\n bot.watson_conversation_url = content['watson_conversation_url']\n bot.watson_conversation_user = content['watson_conversation_user']\n bot.endpoint_enabled = content['endpoint_enabled']\n bot.watson_enabled = content['watson_enabled']\n bot.watson_workspace_id = content['watson_workspace_id']\n bot.save()\n return jsonify({'status': 'success', 'message': 'Inserted'}), 200\n\n\n@bots.route('/bots/<bot_id>')\ndef readBot(bot_id):\n bot = Bot.objects.get(bot_id=bot_id)\n return bot.to_json()\n\n\n@bots.route('/bots/<bot_id>', methods=['DELETE'])\ndef delete_bot(bot_id):\n Bot.objects.get(bot_id=bot_id).delete()\n return jsonify({'status': 'success', 'message': 'Deleted'})\n","sub_path":"services/arcus/app/bots/controllers.py","file_name":"controllers.py","file_ext":"py","file_size_in_byte":1936,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"418186361","text":"\"\"\"\n1.\tНаписать программу, которая будет складывать, вычитать, умножать или делить\nдва числа. Числа и знак операции вводятся пользователем. После выполнения\nвычисления программа не должна завершаться, а должна запрашивать новые данные\nдля вычислений. Завершение программы должно выполняться при вводе символа '0'\nв качестве знака операции. Если пользователь вводит неверный знак\n(не '0', '+', '-', '*', '/'), то программа должна сообщать ему об ошибке и\nснова запрашивать знак операции.\nТакже сообщать пользователю о невозможности деления на ноль,\nесли он ввел 0 в качестве делителя.\n\"\"\"\n\nimport sys\n\n\n# функция ввода данных\ndef enter_data():\n num1_enter = input(\"Введите первое число: \")\n num2_enter = input(\"Введите второе число: \")\n operation_enter = input(\"Введите знак операции сложения(+), вычитания(-), умножения(*) или деления(/), \"\n \"либо ноль(0) для выхода из программы: \")\n return num1_enter, num2_enter, operation_enter\n\n\n# функция проверки введенных данных\ndef check_data(num1_check, num2_check, operation_check):\n correct_data_message = True\n if operation_check == '0':\n print(\"Выход из программы. До свидания.\")\n sys.exit()\n try:\n try:\n num1_check = int(num1_check)\n num2_check = int(num2_check)\n except:\n print(\"Введено нечисловое значение. Операции могут выполняться только с числами.\")\n correct_data_message = False\n if operation_check == '/' and num2_check == 0:\n print(\"Невозможно делить на ноль.\")\n correct_data_message = False\n elif operation_check != '+' and operation_check != '-' and operation_check != '*' and operation_check != '/':\n print(\"Введен ошибочный знак операции.\")\n correct_data_message = False\n except:\n print(\"Ошибка ввода. Введите данные заново.\")\n correct_data_message = False\n return num1_check, num2_check, correct_data_message\n\n\n# функция выполнения математической операции с данными\ndef math_operation(num1_execution, num2_execution, operation_execution):\n if operation_execution == '+':\n resultant = num1_execution + num2_execution\n elif operation_execution == '-':\n resultant = num1_execution - num2_execution\n elif operation_execution == '*':\n resultant = num1_execution * num2_execution\n elif operation_execution == '/':\n resultant = num1_execution / num2_execution\n else:\n resultant = \"Упс, что-то пошло не так. Математическая операция не выполнена.\"\n return resultant\n\n\n# бесконечный цикл выполнения программы\nwhile True:\n num1, num2, operation = enter_data()\n num1, num2, correct_data = check_data(num1, num2, operation)\n if not correct_data:\n print(\"Выполнение операции невозможно. Введите данные заново.\")\n else:\n print(f\"В итоге {num1} {operation} {num2} = {math_operation(num1, num2, operation)}.\")\n\n","sub_path":"Lesson_2/1.py","file_name":"1.py","file_ext":"py","file_size_in_byte":3912,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"597402505","text":"def fre(s):\n dic={}\n res=\"\"\n for i in s:\n if i in dic:\n dic[i]+=1\n else:\n dic[i]=1\n print(dic)\n a=sorted(dic,key=lambda x:dic[x],reverse=True)\n for char in a:\n res+=char*dic[char]\n print(res)\nfre(\"Treereet\")","sub_path":"python programs/sortCharbyFrequency.py","file_name":"sortCharbyFrequency.py","file_ext":"py","file_size_in_byte":271,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"136550209","text":"import csv\nimport numpy as np;\n\ndef read_file(filename):\n \"\"\"\n param: string filename, name of cvs file;\n result: data table stored as a list of lists\n\n if the cvs file has m columns, n rows\n len(result) = m; len(result[0]) = n;\n\n note that numerical entries are NOT converted the numerical data types here\n \"\"\"\n counts = []\n reading_data = False\n with open(filename) as csvfile: #read from file\n reader = csv.reader(csvfile, delimiter = ' ', quotechar = '|');\n for entry in reader:\n if not reading_data and list(entry) == ['0', '2047']:\n reading_data = True\n continue\n if reading_data and list(entry) == ['$ROI:']: reading_data = False\n if reading_data:\n counts.append(float(entry[-1]))\n assert len(counts) == 2048\n return counts\n","sub_path":"compton/helper_functions/read_in_spe_files.py","file_name":"read_in_spe_files.py","file_ext":"py","file_size_in_byte":859,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"291383643","text":"#! usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n\nfrom downloader import Downloader\nfrom datetime import datetime\nfrom lxml import etree\n\nmydownloader = Downloader()\nresp_with_cookie = mydownloader.get('http://www.xcar.com.cn/bbs/header/bbsnav.htm?action=bbsnav&domain=club.xcar.com.cn&v=%s'%datetime.now().strftime('%Y%m%d%H%M'))\ncookie = resp_with_cookie.cookies.get_dict()\nmydownloader.set_cookie(cookie)\nresp = mydownloader.get('http://club.xcar.com.cn/')\nhtml = resp.text\ntree = etree.HTML(html)\n\nbbs_cartype_nodes = tree.xpath('//div[@id=\"quick_index_content\"]//li/em/a')\nprint(list(map(lambda y: ''.join(y.xpath('./@href')), filter(lambda x: '奥迪' in ''.join(x.xpath('./text()')), bbs_cartype_nodes))))\n","sub_path":"太平洋爱卡论坛爬虫/bbs_taipingyang/get_cartype_bbs.py","file_name":"get_cartype_bbs.py","file_ext":"py","file_size_in_byte":712,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"159483372","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport os\nimport re\nimport sys\nimport scipy\nimport logging\nimport argparse\nimport matplotlib\nmatplotlib.use('Agg')\n\nimport numpy as np\nfrom scipy import stats\nfrom matplotlib import pyplot as plt\n\nLOG = logging.getLogger(__name__)\n\n__version__ = \"0.1.1\"\n__author__ = (\"Xingguo Zhang\",\"Liu huifang\",)\n__email__ = \"invicoun@foxmail.com\"\n__all__ = []\n\n\ndef read_depth(files):\n '''Read depth file'''\n\n for line in open(files, 'r'):\n line = line.strip()\n\n if not line or line.startswith(\"#\"):\n continue\n\n line = line.split('\\t')\n\n yield float(line[3]), float(line[4])\n\n\ndef beg_median(depth):\n\n depth = sorted(depth)\n m = int(len(depth)/2)\n\n return (depth[m]+depth[m-1])/2\n\n\ndef draw_gc_depth(files, name, minx=0, maxx=100, miny=0, maxy=500):\n\n gc_list = []\n depth_list = []\n x = []\n y = []\n sum_gc = 0\n sum_depth =0\n n = 0\n\n for gc,depth in read_depth(files):\n gc_list.append(gc)\n depth_list.append(depth)\n sum_gc += gc\n sum_depth += depth\n n += 1\n\n mean_gc = round(sum_gc/n, 2)\n mean_depth = round(sum_depth/n, 2)\n\n for i in range(0, n):\n if depth_list[i] <= 3 * mean_depth:\n x.append(gc_list[i])\n y.append(depth_list[i])\n\n maxy = beg_median(depth_list)*2\n\n left, width = 0.1, 0.77\n bottom, height = 0.1, 0.77\n spacing = 0.005\n rect_scatter = [left, bottom, width, height]\n rect_histx = [left, bottom + height + spacing, width, 0.08]\n rect_histy = [left + width + spacing, bottom, 0.08, height]\n #Generate an image\n plt.figure(figsize=(8, 8))\n #plt.tight_layout()\n #Drawing a middle picture\n axs = plt.axes(rect_scatter)\n axs.tick_params(direction='in', top=False, right=False)\n #Set the position of the middle picture\n axx = plt.axes(rect_histx)\n axx.tick_params(direction='in', labelbottom=False)\n\n axy = plt.axes(rect_histy)\n axy.tick_params(direction='in', labelleft=False)\n xy = np.vstack([x,y])\n z = stats.gaussian_kde(xy)(xy)\n #Draw a middle two-dimensional heat map\n# axs.hist2d(gc, depth, bins=50, range=[[minx,maxx],[miny,maxy]], cmap=plt.get_cmap('BuPu'))\n# axs.scatter(gc, depth, s=20, facecolors='none', edgecolor=\"#107ab0\", alpha=1)\n axs.scatter(x, y, c=z, cmap='coolwarm', s=10)\n\n #axs.set_xlabel('GC%')\n #axs.set_ylabel('Sequencing Depth(X)')\n\n axs.set_xlabel(\"GC %% (Average:%s)\" % mean_gc)\n axs.set_ylabel(\"Sequencing Depth (Average:%s X)\" % mean_depth)\n\n axs.set_xlim((minx, maxx))\n axs.set_ylim((miny, maxy))\n axs.spines['top'].set_visible(False)\n axs.spines['right'].set_visible(False)\n\n axx.hist(gc_list, bins=50, range=(minx, maxx), edgecolor='white')\n axx.set_xlim(minx, maxx)\n axx.yaxis.set_visible(False)\n #axx.xaxis.set_visible(False)\n axx.spines['top'].set_visible(False)\n axx.spines['right'].set_visible(False)\n axx.spines['left'].set_visible(False)\n\n axy.hist(depth_list, bins=50, range=(miny, maxy), edgecolor='white', orientation='horizontal')\n axy.set_ylim(miny, maxy)\n #axy.yaxis.set_visible(False)\n axy.xaxis.set_visible(False)\n axy.spines['top'].set_visible(False)\n axy.spines['right'].set_visible(False)\n axy.spines['bottom'].set_visible(False)\n\n plt.savefig('%s.gc_depth.png' % name, dpi=700)\n plt.savefig(\"%s.gc_depth.pdf\" % name)\n\n\n\ndef gc_depth_help(parser):\n\n parser.add_argument('-gcd', '--gc_depth', metavar='FILE', type=str, required=True,\n help='Input the coverage depth statistics file.')\n parser.add_argument('-n', '--name', metavar='STR', type=str, default='out',\n help='Output file name.')\n\n return parser\n\n\ndef main():\n\n logging.basicConfig(\n stream=sys.stderr,\n level=logging.INFO,\n format=\"[%(levelname)s] %(message)s\"\n )\n parser = argparse.ArgumentParser(formatter_class=argparse.RawDescriptionHelpFormatter,\n description='''\nname:\n draw_gc_depth.py Draw a gc depth map\n\nattention:\n draw_gc_depth.py -gcd *.stat_gc_depth.tsv -n A18\n\nversion: %s\ncontact: %s <%s>\\\n ''' % (__version__, ' '.join(__author__), __email__))\n\n args = gc_depth_help(parser).parse_args()\n\n draw_gc_depth(args.gc_depth, args.name)\n\n\nif __name__ == \"__main__\":\n\n main()\n","sub_path":"scripts/draw_depth_gc.py","file_name":"draw_depth_gc.py","file_ext":"py","file_size_in_byte":4320,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"168037016","text":"# -*- coding:utf-8 -*-\nfrom django.contrib.auth import get_user_model\nfrom django.http import JsonResponse\nfrom django.shortcuts import render, Http404\nfrom django.core.exceptions import ObjectDoesNotExist, MultipleObjectsReturned\nfrom django.utils.decorators import method_decorator\nfrom django.contrib.auth.decorators import login_required\nfrom django.views.generic import View\nfrom app.training.models import TaskItem, Solution, Course\nfrom app.training.forms import TaskItemForm, SolutionForm\nfrom app.translators.consts import translators_external_urls\nfrom app.translators.entities.response import OperationResponse\n\nUserModel = get_user_model()\n\n\n@method_decorator(login_required, name='dispatch')\nclass TaskItemView(View):\n\n def get_object(self, request, *args, **kwargs):\n try:\n return TaskItem.objects \\\n .select_related('task', 'topic__course') \\\n .get(slug=kwargs['taskitem'], topic__slug=kwargs['topic'], topic__course__slug=kwargs['course'])\n except TaskItem.DoesNotExist:\n raise Http404\n\n def get(self, request, *args, **kwargs):\n taskitem = self.get_object(request, *args, **kwargs)\n solution = None\n form_initial = {'translator': taskitem.translator}\n if request.user.is_active:\n solution = Solution.objects.filter(taskitem=taskitem, user=request.user).first()\n if solution:\n form_initial['content'] = solution.last_changes\n form = TaskItemForm(initial=form_initial)\n blocked_status = solution and solution.manual_status in Solution.MS__BLOCKED_STATUS\n not_solution_content = not solution or solution and not solution.content\n locked = solution and solution.is_locked\n return render(\n request=request,\n template_name='training/taskitem/template.html',\n context={\n 'course': taskitem.topic.course,\n 'object': taskitem,\n 'solution': solution,\n 'form': form,\n 'translators_urls': translators_external_urls,\n 'disable_ready_btn': blocked_status or locked,\n 'disable_save_btn': blocked_status or locked,\n 'disable_versions_btn': not_solution_content\n }\n )\n\n def post(self, request, *args, **kwargs):\n taskitem = self.get_object(request, *args, **kwargs)\n form = TaskItemForm(data=request.POST)\n response: OperationResponse = form.perform_operation(request.user, taskitem)\n return JsonResponse(response)\n\n\n@method_decorator(login_required, name='dispatch')\nclass SolutionView(View):\n\n PERM_DENIED = 0\n VIEW_PERM = 1\n CHANGE_PERM = 2\n\n def get_solution_user_id(self, request) -> int:\n\n \"\"\" Возвращает id пользователя, чье решение запрашивается\n\n Возможно 3 варианта:\n - в get-параметра 'user' указан id целевого пользователя\n - get-параметр не указан, тогда возвращает id текущего пользователя\n - get-параметр не целое число, тога возбуждаем 404 ошибку\n \"\"\"\n\n target_user_id = request.GET.get('user')\n if target_user_id is None:\n solution_user_id = int(request.user.id)\n elif target_user_id.isdigit():\n solution_user_id = int(target_user_id)\n else:\n raise Http404\n return solution_user_id\n\n def get_user_perm(self, request, solution_user_id: int) -> int:\n\n \"\"\"\n Возвращает права пользователя на запрашиваемое решение:\n\n Доступ к просмотру решения имеют 3 группы пользователей:\n 1. Суперпользователь\n 2. Автор решения\n 3. Автор группы (учитель) в которой состоит пользователь (ученик)\n\n Доступ к редактированию решения имеют 2 группы пользователей:\n 1. Суперпользователь\n 2. Автор группы (учитель) в которой состоит пользователь (ученик)\n\n \"\"\"\n if request.user.is_superuser:\n perm = self.CHANGE_PERM\n else:\n solution_user = UserModel.objects.filter(id=solution_user_id).first()\n if solution_user.member.filter(group__author=request.user).exists(): # преподаватель в группе ученика\n perm = self.CHANGE_PERM\n elif solution_user_id == request.user.id: # просмотр собственного решения\n perm = self.VIEW_PERM\n else:\n perm = self.PERM_DENIED\n return perm\n\n def get_object(self, user_id, **kwargs) -> Solution:\n filter = {\n \"taskitem__slug\": kwargs['taskitem'],\n \"taskitem__topic__slug\": kwargs['topic'],\n \"taskitem__topic__course__slug\": kwargs['course'],\n \"user_id\": user_id\n }\n try:\n return Solution.objects.get(**filter)\n except MultipleObjectsReturned:\n # TODO Логировать ошибку\n return Solution.objects.filter(**filter).first()\n except ObjectDoesNotExist:\n raise Http404\n\n def get(self, request, *args, **kwargs):\n solution_user_id = self.get_solution_user_id(request)\n solution = self.get_object(user_id=solution_user_id, **kwargs)\n request_user_perm = self.get_user_perm(request, solution_user_id)\n form = None\n if request_user_perm == self.CHANGE_PERM and solution.taskitem.manual_check:\n form = SolutionForm(instance=solution)\n elif request_user_perm == self.PERM_DENIED:\n raise Http404\n\n return render(\n request,\n template_name='training/solution/template.html',\n context={\n 'object': solution,\n 'form': form,\n 'course': solution.taskitem.topic.course,\n 'topic': solution.taskitem.topic\n }\n )\n\n def post(self, request, *args, **kwargs):\n solution_user_id = self.get_solution_user_id(request)\n solution = self.get_object(user_id=solution_user_id, **kwargs)\n request_user_perm = self.get_user_perm(request, solution_user_id)\n if request_user_perm == self.CHANGE_PERM and solution.taskitem.manual_check:\n form = SolutionForm(instance=solution, data=request.POST)\n if form.is_valid():\n solution = form.save(commit=False)\n solution.teacher = request.user\n solution.save()\n else:\n raise Http404\n return render(\n request,\n template_name='training/solution/template.html',\n context={\n 'object': solution,\n 'form': form,\n 'course': solution.taskitem.topic.course,\n 'topic': solution.taskitem.topic\n }\n )\n\n\n@method_decorator(login_required, name='dispatch')\nclass CourseSolutionsView(View):\n\n def get(self, request, *args, **kwargs):\n try:\n course = Course.objects.get(slug=kwargs.get('course'))\n user_id = request.GET['user_id']\n user = UserModel.objects.get(id=user_id, is_active=True)\n return JsonResponse(user.get_cache_course_solutions_data(course))\n except:\n raise Http404\n","sub_path":"src/app/training/views/taskitem.py","file_name":"taskitem.py","file_ext":"py","file_size_in_byte":7786,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"480042810","text":"######################################################################\n#작성일: 11/1\n#마지막 변경일: 11/1\n#작성자: 20132885 손태선\n#기능: 시동을 검. 움직임. 시동을 끔\n#입력: 차의 방향, 속도\n#출력: 차량이 움직임\n######################################################################\n'''자동차의 기본 기능을 구현해놓은 car 모듈 입니다. Motor Driver에 검은 선이 위, 붉은 선이 아래인 형태입니다.\n\t예시로 올라온 코드와의 차이점\n\t1.방향에 True, False값을 직접 넣어주기에 REVERSE함수가 필요없다.\n\t2.마찬가지 이유로 방향을 저장해두는 변수인 forward0,1 , backward0,1또한 필요없다.\n\t3.오른쪽 모터와 왼쪽 모터의 방향을 한번에 정하기에 rightmotor와 leftmotor 함수가\n\t setDirection 함수로 합쳐졌다.\n\t4.car 자체에 go_forward go_backward는 없고 엔진의 속력과 방향을 정해주는 engine\n\t 함수 밖에 없다.\n\t5.시간 조절도 driver가 결정해 sleep 함수도 부르지 않는다.\n'''\n\nimport RPi.GPIO as GPIO\n\nGPIO.setmode(GPIO.BOARD)\nGPIO.setwarnings(False)\n\n#const variable\t\nMOTOR_LEFT_A = 12\nMOTOR_LEFT_B = 11\nMOTOR_LEFT_PWM = 35\n\nMOTOR_RIGHT_A = 15\nMOTOR_RIGHT_B = 13\nMOTOR_RIGHT_PWM = 37\n\n\n#base setting\n#set left motor pin to output\nGPIO.setup(MOTOR_LEFT_A, GPIO.OUT)\nGPIO.setup(MOTOR_LEFT_B, GPIO.OUT)\nGPIO.setup(MOTOR_LEFT_PWM, GPIO.OUT)\n\n#set right moto pin to output\nGPIO.setup(MOTOR_RIGHT_A, GPIO.OUT)\nGPIO.setup(MOTOR_RIGHT_B, GPIO.OUT)\nGPIO.setup(MOTOR_RIGHT_PWM, GPIO.OUT)\n\n#create PWM\nLeftPwm=GPIO.PWM(MOTOR_LEFT_PWM, 100)\nRightPwm=GPIO.PWM(MOTOR_RIGHT_PWM, 100)\n\t\n#public method\n\ndef startUp():\n\t'''start the car\n\n\tset both side of Pwm started\n\t'''\n\tLeftPwm.start(0)\n\tRightPwm.start(0)\n\tprint(\"Vroom!\")\n\n\ndef engine(leftDirection, rightDirection, leftSpeed, rightSpeed):\n\t'''set engine to move\n\n\tcalled function: setDirection and setSpeed\n\t'''\n\tsetDirection(leftDirection, rightDirection)\n\tsetSpeed(leftSpeed, rightSpeed)\n\ndef turnOff():\n\t'''turn off the car\n\n\tPwm off\n\tchange speed to 0\n\tclean GPIO for car\n\t'''\n\tGPIO.output(MOTOR_LEFT_PWM, GPIO.LOW)\n\tGPIO.output(MOTOR_RIGHT_PWM, GPIO.LOW)\n\tLeftPwm.ChangeDutyCycle(0)\n\tRightPwm.ChangeDutyCycle(0)\n\tGPIO.cleanup()\n\tprint(\"turn off\")\n\t\n\n\n#private method\ndef setDirection(leftDirection, rightDirection):\n\t'''set true false value to the motor\n\n\tMotors need True, False value for operating \n\t'''\n\tGPIO.output(MOTOR_LEFT_A, not leftDirection)\n\tGPIO.output(MOTOR_LEFT_B, leftDirection)\n\tGPIO.output(MOTOR_RIGHT_A, rightDirection)\n\tGPIO.output(MOTOR_RIGHT_B, not rightDirection)\n\n\ndef setSpeed(leftSpeed, rightSpeed):\n\t'''change motor speed\n\n\tSet motor operating and then, change the speed\n\t'''\n\tGPIO.output(MOTOR_LEFT_PWM, GPIO.HIGH)\n\tGPIO.output(MOTOR_RIGHT_PWM, GPIO.HIGH)\n\tLeftPwm.ChangeDutyCycle(leftSpeed)\n\tRightPwm.ChangeDutyCycle(rightSpeed)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"모듈/car.py","file_name":"car.py","file_ext":"py","file_size_in_byte":2903,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"46738332","text":"import comparison_result_factory\nimport re\n\ndef check_status_code(response):\n if response.status_code != 200:\n result_status_messages = list()\n response_status_code_error = 'Error occurred, service has an issue, response code is: {}'.format(\n response.status_code)\n response_error_results = comparison_result_factory.ComparisonResults(False, response_status_code_error)\n result_status_messages.append(response_error_results)\n # set error message to test object, additional_repsonse_validation will not run, so we\n # need to set the failure value\n return result_status_messages\n\n # this should not exist for any web service, except for the incorrect way we implemented it\n return _odd_error(response)\n\n\ndef _odd_error(response):\n # due to the crappy way we implemented web services we almost always get a 200 unless the\n # server is down, this should be a special branch and not in master\n # so you have to check for something all the time for our services, since http return code\n # is not accurate\n result_status_messages = None\n\n resp_text = response.text\n is_not_found = re.search('not_found.jsp', resp_text)\n if is_not_found is not None:\n result_status_messages = list()\n response_error_results = comparison_result_factory.ComparisonResults(False, 'Web Service is not found.')\n result_status_messages.append(response_error_results)\n\n return result_status_messages\n","sub_path":"requests/src/check_basic_response.py","file_name":"check_basic_response.py","file_ext":"py","file_size_in_byte":1485,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"17848798","text":"# !/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom keras.models import Model\nfrom keras.layers import Input\nimport keras.backend as K\n\nfrom NumPyNet.layers.avgpool_layer import Avgpool_layer\nfrom keras.layers import AvgPool2D\n\nimport numpy as np\nfrom hypothesis import strategies as st\nfrom hypothesis import given, settings\n\n__author__ = ['Mattia Ceccarelli', 'Nico Curti']\n__email__ = ['mattia.ceccarelli3@studio.unibo.it', 'nico.curti2@unibo.it']\n__package__ = 'AvgPool Layer testing'\n\n@given(batch = st.integers(min_value=1, max_value=15),\n w = st.integers(min_value=15, max_value=100),\n h = st.integers(min_value=15, max_value=100),\n c = st.integers(min_value=1, max_value=10),\n size = st.integers(min_value=1, max_value=10),\n stride = st.integers(min_value=1, max_value=10),\n pad = st.booleans())\n@settings(max_examples=10,\n deadline=None)\ndef test_avgpool_layer(batch, w, h, c, size, stride, pad):\n '''\n Tests:\n if the average pool layer forwards and backward are consistent with keras\n\n to be:\n '''\n\n inpt = np.random.uniform(low=0., high=1., size=(batch, w, h, c))\n\n # Numpy_net model\n numpynet = Avgpool_layer(size=size, stride=stride, padding=pad)\n\n if pad:\n keras_pad = 'same'\n else :\n keras_pad = 'valid'\n\n # Keras model initialization.\n inp = Input(shape=(w, h, c), batch_shape=inpt.shape)\n x = AvgPool2D(pool_size=size, strides=stride, padding=keras_pad)(inp)\n model = Model(inputs=[inp], outputs=x)\n\n # Keras Output\n forward_out_keras = model.predict(inpt)\n\n # numpynet forward and output\n numpynet.forward(inpt)\n forward_out_numpynet = numpynet.output\n\n # Test for dimension and allclose of all output\n assert forward_out_numpynet.shape == forward_out_keras.shape\n assert np.allclose(forward_out_numpynet, forward_out_keras, atol=1e-6)\n\n # BACKWARD\n\n # Compute the gradient of output w.r.t input\n gradient = K.gradients(model.output, [model.input])\n\n # Define a function to evaluate the gradient\n func = K.function(model.inputs + [model.output], gradient)\n\n # Compute delta for Keras\n delta_keras = func([inpt])[0]\n\n # Definition of starting delta for numpynet\n numpynet.delta = np.ones(shape=numpynet.out_shape, dtype=float)\n delta = np.zeros(shape=inpt.shape, dtype=float)\n\n # numpynet Backward\n numpynet.backward(delta)\n\n # Back tests\n assert delta.shape == delta_keras.shape\n assert delta.shape == inpt.shape\n assert np.allclose(delta, delta_keras, atol=1e-8)\n\nif __name__ == '__main__':\n\n test_avgpool_layer()\n","sub_path":"testing/test_avgpool_layer.py","file_name":"test_avgpool_layer.py","file_ext":"py","file_size_in_byte":2619,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"571572161","text":"from flask import jsonify, abort, request\nfrom ..auth import token_auth\nfrom ..models import User\nfrom . import api\n\n\n@api.route('/users', methods=['POST'])\ndef new_user():\n \"\"\"Register a new user\n This endpoint does require a authentication token\n \"\"\"\n user = User.create(request.get_json() or {})\n user_exists = User.objects.filter(email=user.email).first()\n if user_exists:\n abort(400)\n user.save()\n response = jsonify(user.to_dict())\n response.status_code = 201\n return response\n\n\n@api.route('/users/<pk>', methods=['GET'])\n@token_auth.login_required\ndef get_user(pk):\n \"\"\"Return a user\"\"\"\n try:\n user = User.objects.get(pk=pk)\n response = jsonify(user.to_dict())\n response.status_code = 200\n return response\n except User.DoesNotExist:\n abort(404)\n\n\n@api.route('/users/<pk>', methods=['PUT'])\n@token_auth.login_required\ndef update_user(pk):\n \"\"\"Update a user\"\"\"\n try:\n user = User.objects.get(pk=pk)\n data = request.get_json() or {}\n user.update(**data)\n updated_user = User.objects.get(pk=pk)\n response = jsonify(updated_user.to_dict())\n response.status_code = 200\n return response\n except User.DoesNotExist:\n abort(404)\n\n\n@api.route('/users/<pk>', methods=['DELETE'])\n@token_auth.login_required\ndef delete_user(pk):\n \"\"\"Deletes a user\"\"\"\n try:\n user = User.objects.get(pk=pk)\n user.delete()\n response = jsonify({'deleted': True})\n response.status_code = 200\n return response\n except User.DoesNotExist:\n abort(404)\n\n\n@api.route('/users', methods=['GET'])\n@token_auth.login_required\ndef users():\n \"\"\"List all registered users\n This endpoint requires a authentication token\n \"\"\"\n users = [user.to_dict() for user in User.objects.all()]\n return jsonify({'users': users})\n","sub_path":"twegeo/api/users.py","file_name":"users.py","file_ext":"py","file_size_in_byte":1885,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"270288492","text":"import pandas as pd\nimport numpy as np\nfrom pyxley.charts.nvd3 import TwoAxisFocus, PieChart\nfrom pyxley.filters import SelectButton\nfrom pyxley import UILayout, register_layouts\n\ndef two_axis_focus(df):\n init_params = {\"Data\": \"Heart Rate\"}\n colors = [\"#847c77\", \"#ff5c61\"]\n _chart = TwoAxisFocus(\"Seconds\", \"value\", \"Altitude\", df,\n chart_id=\"nvd3_focus\", url=\"/api/nvd3_focus/\",\n init_params=init_params, colors=colors)\n return _chart\n\ndef pie_chart(df):\n _hr = df.loc[df[\"Data\"] == \"Heart Rate\"].copy()\n\n def bucket_hr(x):\n if x < 110:\n return \"Resting\"\n if x < 135:\n return \"Fat Burn\"\n if x < 153:\n return \"Cardio\"\n return \"Peak\"\n _hr = _hr.assign(hr_zone=_hr[\"value\"].apply(bucket_hr))\n\n # group by and aggregate\n grp_hr = _hr.groupby(\"hr_zone\").size().reset_index()\n grp_hr.columns = [\"hr_zone\", \"fraction\"]\n grp_hr[\"fraction\"] = grp_hr[\"fraction\"].astype(\"float\")\n\n # pivot\n _pivot = pd.pivot_table(grp_hr, values=[\"fraction\"],\n columns=[\"hr_zone\"], fill_value=0, aggfunc=np.max).reset_index()\n colors = [\"#7bc9c1\", \"#7f7f7f\", \"#1f77b4\", \"#393b79\"]\n values = {k:k for k in grp_hr.hr_zone.unique()}\n\n pc = PieChart(values, _pivot, colors=colors)\n return pc\n\ndef make_nv_layout():\n # load the data\n filename = \"../examples/nvd3/project/static/formatted_run.csv\"\n df = pd.read_csv(filename)\n\n ui = UILayout(\"FilterChart\")\n\n # Make a button\n choices = [\"Heart Rate\", \"Pace\", \"Distance\"]\n btn = SelectButton(\"Data\", choices, \"Data\", \"Heart Rate\")\n ui.add_filter(btn)\n\n # Add the chart\n ui.add_chart(two_axis_focus(df))\n ui.add_chart(pie_chart(df))\n return ui\n","sub_path":"pyxley-master/tests/app/components/nvd3.py","file_name":"nvd3.py","file_ext":"py","file_size_in_byte":1731,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"569365501","text":"from django import forms\nfrom django.contrib.auth.models import User\n\nfrom .models import Book\n\n\nclass UserCreationForm(forms.ModelForm):\n class Meta:\n model = User\n fields = ['username']\n\n\nclass BookCreateForm(forms.ModelForm):\n class Meta:\n model = Book\n fields = ['image', 'title', 'author', 'published_year']\n\n def clean(self):\n self.cleaned_data = super().clean()\n is_same_book_exists = Book.objects.filter(user=self.instance.user,\n title=self.cleaned_data['title'],\n author=self.cleaned_data['author'],\n published_year=self.cleaned_data['published_year'])\n if is_same_book_exists:\n raise forms.ValidationError('У данного пользователя уже есть эта книга!')\n","sub_path":"user_book/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":861,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"8583712","text":"'''\nCreated on 30.09.2013\n\n@author: psikorski\n'''\nimport logging\nimport time\nfrom math import trunc\n\nfrom hal.api import HALGatewayAPI\nfrom hal.core import HALConfig\nfrom hal.core.HALDB import DataEntry\nfrom hal.nodes.RFNode import RFNode\n\nlogger = logging.getLogger('HALServer.nodes')\n\n\nclass BlueRoomNode(RFNode):\n def __init__(self, name, node_id, group, args, session_mgr=None):\n '''\n Constructor\n '''\n RFNode.__init__(self, name, node_id, group, args, session_mgr)\n HALGatewayAPI.get_node_status(node_id)\n self.armed = HALConfig.get_node_arm(self.name)\n\n def process(self):\n self.clearEvents()\n\n HALGatewayAPI.get_node_status(self.nodeId)\n\n self.process_auto_monitoring()\n\n self.process_heating()\n\n return self.getQueuedEvents()\n\n def update_status(self, status_array):\n logger.debug(\"-->update_status()\")\n for i in range(len(status_array)):\n if i == 0:\n self.temperature = float(status_array[i])\n if i == 1:\n frac = float(status_array[i]) * 0.01\n self.temperature += frac\n self.temperature = round(self.temperature, 2)\n if i == 2:\n self.fwVersion = status_array[i]\n if i == 3:\n self.fwVersion = self.fwVersion + '.' + status_array[i]\n logger.debug(\"<--update_status()\")\n\n def update_motion(self):\n self.motionDetected = trunc(time.time())\n return\n\n def ext__arm(self):\n self.armed = True\n HALConfig.set_node_arm(self.name, self.armed)\n return dict(status=True)\n\n def ext__disarm(self):\n self.armed = False\n HALConfig.set_node_arm(self.name, self.armed)\n return dict(status=True)\n\n def ext__status(self):\n out = list()\n out.append({'temperature': float(self.temperature),\n 'motion': self.motionDetected,\n 'armed': self.armed,\n 'fwVersion': self.fwVersion,\n 'targetTemperature': self.temperature_target,\n 'headTemperature': self.temperature_head,\n 'thermoOverride': self.temperature_override, 'temperatureHead': self.temperature_head, 'name': self.display_name})\n return out\n\n def collect_data(self, event):\n event_id = event.eventCMD\n out = []\n event_int_id = int(event_id)\n if event_int_id == 2:\n out.append(DataEntry(src=self.name, name='Temperature', valueType='float', valueFloat=self.temperature))\n elif event_int_id == 4:\n # ping\n out.append(DataEntry(src=self.name, name='Ping', valueType='bool', valueBoolean=True))\n elif event_int_id == 7:\n out.append(DataEntry(src=self.name, name='Motion', valueType='bool', valueBoolean=True))\n return out\n\n def process_auth_request(self, auth_action):\n pass\n","sub_path":"hal/nodes/BlueRoomNode.py","file_name":"BlueRoomNode.py","file_ext":"py","file_size_in_byte":2959,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"270553040","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n# Problem: https://leetcode.com/problems/binary-tree-preorder-traversal/\n\n\n# 1. Recursive\nclass Solution1(object):\n def preorderTraversal(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: List[int]\n \"\"\"\n arr = []\n self.preorder(root, arr)\n return arr\n\n def preorder(self, node, arr):\n if node:\n arr.append(node.val)\n self.preorder(node.left, arr)\n self.preorder(node.right, arr)\n\n\n# 2. Iterative\nclass Solution2(object):\n def preorderTraversal(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: List[int]\n \"\"\"\n arr = []\n stack = []\n node = root\n while stack or node:\n if node:\n stack.append(node)\n arr.append(node.val) # Append before proceed to left node\n node = node.left\n else:\n n = stack.pop()\n node = n.right\n return arr\n\n\n# 3. Another iterative solution. (Only append right node to stack)\nclass Solution3(object):\n def preorderTraversal(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: List[int]\n \"\"\"\n arr = []\n stack = [root]\n while stack:\n node = stack.pop()\n while node:\n arr.append(node.val)\n if node.right:\n stack.append(node.right)\n node = node.left\n return arr\n","sub_path":"0144.binary-tree-preorder-traversal.py","file_name":"0144.binary-tree-preorder-traversal.py","file_ext":"py","file_size_in_byte":1522,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"554340659","text":"#!/usr/bin/env python\n# vim: set fileencoding=UTF-8 filetype=python :\n#\n# When the configuration file is loaded, several automatic transformations\n# are applied:\n#\n# 1) '{cfg_abs_path}' as a substring of atomic attributes is replaced by\n# an absolute path of the configuration files. This can be used to\n# make the configuration file independent of the location of programs\n# using the configuration file.\n#\n# or better user use the as_project_path function\n\nimport random\n\n# Initialise the generators so that the NLG sample different templates every\n# time you start the system.\n\nrandom.seed()\n\nfrom alex.utils.config import as_project_path, online_update\n\nfrom alex.utils.database.python_database import PythonDatabase\nfrom alex.components.simulator.user_simulator.simple_user_simulator import SimpleUserSimulator\n\nconfig = {\n 'database':{\n 'type':PythonDatabase,\n 'debug':True,\n 'PythonDatabase':{\n 'files':[as_project_path('applications/PublicTransportInfoEN/data/thanh_data/stops.txt'),\n as_project_path('applications/PublicTransportInfoEN/data/thanh_data/streets.txt'),\n as_project_path('applications/PublicTransportInfoEN/data/thanh_data/vehicles.txt'),\n as_project_path('applications/PublicTransportInfoEN/data/thanh_data/time.txt'),\n as_project_path('applications/PublicTransportInfoEN/data/thanh_data/cities.txt'),\n as_project_path('applications/PublicTransportInfoEN/data/thanh_data/time_relative.txt'),\n as_project_path('applications/PublicTransportInfoEN/data/thanh_data/places.txt'),\n as_project_path('applications/PublicTransportInfoEN/data/thanh_data/boroughs.txt'),\n ],\n \n },\n },\n 'domain':{#probably like the configuration for suser simulator\n 'dialogue_act_definitions': {#dialogue acts which user simulator used for answering\n 'request':{\n 'slot_included': True,\n 'value_included': False,\n 'combineable_slots': ['number_transfer', 'duration', 'distance']\n },\n 'inform':{\n 'slot_included': True,\n 'value_included': True,\n 'slot_from': 'sys_da', #in normal case, list of slots will be informed is taken from system dialogue request act, or from goal\n 'value_from': 'goal', #in normal case, where to get values for selected slots\n 'limited_slots': [], #list of slot cant combine\n 'accept_used_slots': False,\n 'use_slot_sequence': True,\n },\n 'oog':{\n 'slot_included': False,\n 'value_included': False,\n 'act_without_slot': True,\n },\n 'deny':{\n 'slot_included': True,\n 'value_included': True,\n 'slot_from': 'sys_da',\n 'value_from': 'sys_da',\n 'status_included': 'incorrect',\n },\n 'repeat':{\n 'slot_included': False,\n 'value_included': False,\n },\n 'help':{\n 'slot_included': False,\n 'value_included': False,\n },\n 'apology':{\n 'slot_included': False,\n 'value_included': False,\n },\n 'confirm':{#make a question to clarify something, ?User may also make this action?? How to make it? only at the end?, since simulator always know exactly what is going on\n 'slot_included': True,\n 'value_included': True,\n 'status_included': 'filled',\n },\n 'canthearyou, notunderstood':{#only available for system, not for user\n },\n 'affirm':{#simply YES #something interesting here, doesn't include slot/value, but slots consider from sys_da and they are correct\n 'slot_included': False,\n 'value_included': False,\n 'slot_from': 'sys_da',\n 'status_included': 'correct',\n 'status_in_all_slots': True,\n #TODO add cheeck all sys_da slot?\n #all_slot_included: True,\n 'act_without_slot': True,\n },\n 'ack':{\n 'slot_included': False,\n 'value_included': False,\n },\n 'thankyou':{\n 'slot_included': False,\n 'value_included': False,\n 'act_without_slot': True,\n },\n 'silence':{\n 'slot_included': False,\n 'value_included': False,\n 'act_without_slot': True,\n },\n 'reqalts':{\n 'slot_included': True,\n 'value_included': True,\n 'combineable_slots': ['alternative'],\n 'slot_from': 'none',\n 'value_from': 'function',\n #'value_fun': alternative_value_fun,\n },\n 'negate':{\n 'slot_included': False,\n 'value_included': False,\n 'slot_from': 'sys_da',\n 'status_included': 'incorrect',\n 'act_without_slot': True,\n },\n 'bye':{\n 'slot_included': False,\n 'value_included': False,\n 'act_without_slot': True,\n },\n 'hello':{\n 'slot_included': False,\n 'value_included': False,\n 'act_without_slot': True,\n #'add_to_da_prob':0.5,\n },\n 'restart':{#TODO how to user this action?\n 'slot_included': False,\n 'value_included': False,\n },\n 'hangup':{\n 'slot_included': False,\n 'value_included': False,\n 'act_without_slot': True,\n },\n 'help':{#How?\n 'slot_included': False,\n 'value_included': False,\n },\n },\n 'slot_table_field_mapping':{'from_stop':[('stops','stop')],\n 'to_stop':[('stops', 'stop')],\n 'from_borough':[('boroughs', 'borough')],\n 'to_borough':[('boroughs', 'borough')],\n 'from_city':[('cities', 'city')],\n 'to_city':[('cities', 'city')],\n 'from_street':[('streets', 'street')],\n 'to_street':[('streets', 'street')],\n 'departure_time':[('time', 'time')],\n 'departure_time_rel':[('time_relative', 'relative')],\n 'arrival_time': [('time', 'time')],\n 'arrival_time_rel': [('time_relative', 'relative')],\n 'vehicle': [('vehicles', 'vehicle')],\n 'street':[('streets', 'street'), ('places', 'street')],\n 'city':[('cities', 'city'), ('places', 'city')],\n 'state':[('states', 'state'), ('places', 'state')],\n 'task': [lambda: ['find_connection', 'find_platform', 'weather']],\n 'alternative': [lambda: ['next', 'prev', 'last', '1', '2', '3', '4', 'next hour']],\n }, \n },\n 'user_simulator':{\n 'type': SimpleUserSimulator,\n 'SimpleUserSimulator':{\n \n },\n },\n 'asr_simulator':{\n 'type': None,\n 'debug': True,\n 'SimpleASRSimulator':{\n 'prob_combine_fun': None,#the function to calculate new prob from two event, particular is prob of da_type and prob of slot- its value\n 'act_confusion':{\n 'default':{ \n 'confusion_matrix':{\n 'max_length': 1,\n 'confusable_acts': [],\n 'onlist_fraction_alpha': 0.75,\n 'onlist_fraction_beta': 1.5,\n 'confusion_types':{#confusion type for information in an action, default for all actions wihout configuration\n 'correct': 1.0,#meaning that the correction information will be still corret at 90%, highest prob on the hyp list\n 'onlist': 0.0,#The correct information is on the hyp. list but smaller prob.\n 'offlist': 0.0,#the correct information is off the hyp.list\n 'silence': 0.0,#the slot is ignored this time, and the respective action will becom silence\n },\n 'probability_generator':{#using dicrehet for generator probability\n 'correct':{#the confution type = correct\n 'correct':6.0, #the part for the correct item\n 'onlist': 1.0, #the part for other items on the list of hypotheses\n 'offlist': 0.0, #the part for the osther items which are not on the list\n },\n 'onlist':{\n 'correct':2.5,\n 'onlist':1.0,\n 'offlist':2.5,\n },\n 'offlist':{\n 'correct':3.0,\n 'onlist':1.0,\n 'offlist':6.0,\n },\n },\n },\n },\n 'affirm':{\n 'confusion_matrix':{\n 'max_length': 2,\n 'confusable_acts': ['affirm', 'negate'],\n 'confusion_types':{\n 'correct': 0.95,\n 'onlist': 0.05,\n 'offlist': 0.0,\n 'silence': 0.0,#the slot is ignored this time, and the respective action will becom silence\n },\n },\n },\n 'negate':{\n 'confusion_matrix':{\n 'max_length': 2,\n 'confusable_acts': ['affirm', 'negate'],\n 'confusion_types':{\n 'correct': 0.95,\n 'onlist': 0.05,\n 'offlist': 0.0,\n 'silence': 0.0,#the slot is ignored this time, and the respective action will becom silence\n },\n },\n },\n },\n 'slot_confusion':{\n 'to_stop_fake':{\n 'to_stop': 0.5,\n ('departure', 'arrival'): 0.5,\n },\n },\n 'information_confusion_types': ['correct', 'onlist', 'offlist', 'silence'],#only for imagining\n 'default':{#define ASR simulator for a slot, the key default will be apply foo all slots are not specified explicitly\n #default for all informatin confusion and prob. gnerator\n 'default_confusion_matrix':{\n 'max_length': 5,\n 'onlist_fraction_alpha': 0.75,\n 'onlist_fraction_beta': 1.5,\n 'confusion_types':{#confusion type for information in an action, default for all actions wihout configuration\n 'correct': 0.9,#meaning that the correction information will be still corret at 90%, highest prob on the hyp list\n 'onlist': 0.05,#The correct information is on the hyp. list but smaller prob.\n 'offlist': 0.05,#the correct information is off the hyp.list\n 'silence': 0.0,#the slot is ignored this time, and the respective action will becom silence\n },\n 'probability_generator':{#using dicrehet for generator probability\n 'correct':{#the confution type = correct\n 'correct':6.0, #the part for the correct item\n 'onlist': 1.0, #the part for other items on the list of hypotheses\n 'offlist': 3.0, #the part for the osther items which are not on the list\n },\n 'onlist':{\n 'correct':2.5,\n 'onlist':1.0,\n 'offlist':2.5,\n },\n 'offlist':{\n 'correct':3.0,\n 'onlist':1.0,\n 'offlist':6.0,\n },\n },\n },\n 'inform_fake_confusion_matrix':{#a refined confusion matrix for inform action\n 'confusion_types':{\n 'correct': 0.9,\n 'onlist': 0.05,\n 'offlist': 0.05,\n },\n #the default_prob.generator is missing the default one should be used\n },\n },#end of the default consusion for all slots\n 'task_fake':{\n 'default_confusion_matrix':{\n 'max_length': 3,\n 'onlist_fraction_alpha': 0.75,\n 'onlist_fraction_beta': 1.5,\n 'confusion_types':{#confusion type for information in an action, default for all actions wihout configuration\n 'correct': 0.9,#meaning that the correction information will be still corret at 90%, highest prob on the hyp list\n 'onlist': 0.05,#The correct information is on the hyp. list but smaller prob.\n 'offlist': 0.05,#the correct information is off the hyp.list\n 'silence': 0.0,#the slot is ignored this time, and the respective action will becom silence\n },\n 'probability_generator':{#using dicrehet for generator probability\n 'correct':{#the confution type = correct\n 'correct':6.0, #the part for the correct item\n 'onlist': 1.0, #the part for other items on the list of hypotheses\n 'offlist': 3.0, #the part for the osther items which are not on the list\n },\n 'onlist':{\n 'correct':2.5,\n 'onlist':1.0,\n 'offlist':2.5,\n },\n 'offlist':{\n 'correct':3.0,\n 'onlist':1.0,\n 'offlist':6.0,\n },\n },\n },\n },\n 'slot_name':{\n 'default_confusion_matrix':{\n 'confusion_types':{\n #something goes here\n },\n 'probability_generator':{\n #something goes here\n },\n },\n 'inform_confusion_matrix':{\n \n }\n }#end of the confusion descrip for slot_name\n },#end of SimpleUserSimulator\n },#end of asr_simulator\n}\n","sub_path":"alex/components/simulator/asr_simulator/demos/ptien/config_asr_simulator.py","file_name":"config_asr_simulator.py","file_ext":"py","file_size_in_byte":16292,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"14155370","text":"\"\"\"Summary\n\nAttributes:\n hourly_dt_text (TYPE): Description\n ZERO_DEG_IN_KELVIN (float): Description\n\"\"\"\nfrom collections import OrderedDict\nimport datetime\nimport numpy as np\nimport ipdb\n\nfrom util.util import logger\nfrom util.api_wrappers import openweathermap_forecast, openweathermap_daily\n\nZERO_DEG_IN_KELVIN = 273.15\n\nhourly_dt_text = ['now', 'evening', 'morning', 'noon', 'afternoon', 'night',\n 'midnight', 'tonight', 'now']\n\n\ndef get_answer(loc, dt):\n \"\"\"Summary\n \n Args:\n loc (TYPE): Description\n dt (TYPE): Description\n \n Returns:\n TYPE: Description\n \"\"\"\n dt_obj = dt['dt']\n dt_text = dt['text']\n hourly_flag = False\n for token in dt_text.split():\n if token in hourly_dt_text:\n hourly_flag = True\n try:\n if hourly_flag:\n owm_response = openweathermap_forecast(loc)\n today = datetime.datetime.now(dt_obj.tzinfo)\n forecasts = OrderedDict()\n for forecast in owm_response['list']:\n dt_forecast = datetime.datetime.fromtimestamp(\n forecast['dt'], tz=dt_obj.tzinfo)\n forecasts[dt_forecast] = forecast\n\n timedeltas = []\n for dt in forecasts.keys():\n timedeltas.append((dt_obj - dt).total_seconds())\n timedeltas = np.abs(np.array(timedeltas))\n\n if timedeltas.min() > 60 * 60 * 24 * 3: # three days\n out_text = \"I am sorry but I do not have weather forecasts for %s\" % dt_text\n else:\n closest_dt = forecasts.keys()[timedeltas.argmin()]\n observation = forecasts[closest_dt]\n out_text = 'Condition in %s %s is %s with the temperature of %s degrees.' % (\n loc, dt_text, observation['weather'][0]['description'],\n int(observation['main']['temp_max'] - ZERO_DEG_IN_KELVIN))\n else:\n owm_response = openweathermap_daily(loc)\n today = datetime.datetime.now(dt_obj.tzinfo)\n forecasts = OrderedDict()\n for forecast in owm_response['list']:\n dt_forecast = datetime.datetime.fromtimestamp(\n forecast['dt'], tz=dt_obj.tzinfo)\n forecasts[dt_forecast] = forecast\n\n timedeltas = []\n for dt in forecasts.keys():\n timedeltas.append((dt_obj - dt).total_seconds())\n timedeltas = np.abs(np.array(timedeltas))\n if timedeltas.min() > 60 * 60 * 24 * 7: # three days\n out_text = \"I am sorry but I do not have weather forecasts for %s\" % dt_text\n else:\n closest_dt = forecasts.keys()[timedeltas.argmin()]\n observation = forecasts[closest_dt]\n out_text = 'Forecast for %s %s is %s with low of %s and high of %s degrees.' % (\n loc, dt_text, observation['weather'][0]['description'],\n int(observation['temp']['min'] - ZERO_DEG_IN_KELVIN),\n int(observation['temp']['max'] - ZERO_DEG_IN_KELVIN))\n except Exception as e:\n logger.error(e.message)\n out_text = \"I do not have any weather information for %s right now.\" % loc\n return out_text\n","sub_path":"ai.themusio.com-master/ai_chat/modules/weather.py","file_name":"weather.py","file_ext":"py","file_size_in_byte":3280,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"475692096","text":"from violas_client.canoser import Struct, Uint64\nfrom violas_client.move_core_types.account_address import AccountAddress as Address\nfrom violas_client.crypto.ed25519 import Ed25519PublicKey, Ed25519Signature\nfrom violas_client.lbrtypes.rustlib import ensure\nfrom violas_client.error import LibraError, StatusCode\n\nclass ValidatorConsensusInfo(Struct):\n _fields = [\n (\"public_key\", Ed25519PublicKey),\n (\"voting_power\", Uint64)\n ]\n\n def get_public_key(self):\n return self.public_key.hex()\n\n def get_voting_power(self):\n return self.voting_power\n\n\nclass ValidatorVerifier(Struct):\n _fields = [\n ('address_to_validator_info', {Address: ValidatorConsensusInfo}),\n ('quorum_voting_power', Uint64),\n ('total_voting_power', Uint64)\n ]\n\n @classmethod\n def new(cls, address_to_validator_info):\n ret = cls()\n ret.address_to_validator_info = address_to_validator_info\n ret.total_voting_power = sum(address_to_validator_info.values())\n if len(address_to_validator_info) == 0:\n ret.quorum_voting_power = 0\n else:\n ret.quorum_voting_power = ret.total_voting_power * 2 // 3 + 1\n return ret\n\n @classmethod\n def new_with_quorum_voting_power(cls, address_to_validaotr_info, quorum_voting_power):\n total_voting_power = 0\n for voting_power in address_to_validaotr_info.values():\n total_voting_power += voting_power\n ensure(quorum_voting_power <= total_voting_power,\n f\"Quorum voting power is greater than the sum of all voting power of authors: {quorum_voting_power}, quorum_size: {quorum_voting_power}.\")\n return cls(address_to_validaotr_info, quorum_voting_power, total_voting_power)\n\n @classmethod\n def new_single(cls, author: Address, public_key: Ed25519PublicKey):\n author_to_validator_info = dict()\n author_to_validator_info[author] = ValidatorConsensusInfo(public_key, 1)\n return cls.new(author_to_validator_info)\n\n def verify_signature(self, author: Address, hash: bytes, signature: Ed25519Signature):\n public_key = self.get_public_key(author)\n ensure(Ed25519PublicKey.verify_signature(bytes.fromhex(public_key), hash, signature),\n f\"signature:{signature.hex()} mismatch public_key: {public_key}\")\n\n def verify_aggregated_signature(self, hash, aggregated_signature: {Address: Ed25519Signature}):\n self.check_num_of_signatures(aggregated_signature)\n self.check_voting_power(aggregated_signature.keys())\n for author, signature in aggregated_signature:\n self.verify_signature(author, hash, signature)\n\n def batch_verify_aggregated_signature(self, hash, aggregated_signature: {Address: Ed25519Signature}):\n self.check_num_of_signatures(aggregated_signature)\n self.check_voting_power(aggregated_signature.keys())\n keys_and_signatures = {bytes.fromhex(self.get_public_key(address)): signature for address, signature in aggregated_signature}\n if Ed25519PublicKey.batch_verify_signatures(hash, keys_and_signatures):\n self.verify_aggregated_signature(hash, aggregated_signature)\n\n def check_num_of_signatures(\n self,\n aggregated_signature: {Address: Ed25519Signature},\n ):\n num_of_signatures = len(aggregated_signature)\n if num_of_signatures > len(self):\n raise LibraError(data = StatusCode.TOO_MANY_SIGNATURES)\n\n def check_voting_power(self, authors):\n aggregated_voting_power = 0\n for account_address in authors:\n voting_power = self.get_voting_power(account_address)\n aggregated_voting_power += voting_power\n\n if aggregated_voting_power < self.quorum_voting_power:\n raise LibraError(data=StatusCode.TOO_LITTLE_VOTE_POWER)\n\n def get_public_key(self, author: Address):\n validator_info = self.address_to_validator_info.get(author)\n if validator_info:\n return validator_info.get_public_key()\n raise LibraError(data=StatusCode.UnknownAuthor, message=f\"Address:{author} is not a validator\")\n\n def get_voting_power(self, author: Address):\n validator_info = self.address_to_validator_info.get(author)\n if validator_info:\n return validator_info.get_voting_power()\n raise LibraError(data=StatusCode.UnknownAuthor, message=f\"Address:{author} is not a validator\")\n\n def __len__(self):\n return self.address_to_validator.__len__()\n\n def is_empty(self):\n return len(self) == 0\n\n def quorum_voting_power(self):\n return self.quorum_voting_power","sub_path":"violas_client/lbrtypes/validator_verifier.py","file_name":"validator_verifier.py","file_ext":"py","file_size_in_byte":4643,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"115636393","text":"from distutils.core import setup\nfrom Cython.Build import cythonize\nimport numpy as np\nfrom os.path import join\nfrom setuptools.extension import Extension\nfrom ppsim import version\n\ninc_path = np.get_include()\nlib_path = join(np.get_include(), '..', '..', 'random', 'lib')\n\nwith open(\"README.md\", 'r') as f:\n long_description = f.read()\n\ndistributions = Extension(\"ppsim.simulator\",\n sources=[join('', 'ppsim/simulator.pyx')],\n include_dirs=[inc_path],\n library_dirs=[lib_path],\n libraries=['npyrandom']\n )\n\nwith open(\"requirements.txt\") as fp:\n install_requires = fp.read().strip().split(\"\\n\")\n\nsetup(\n name=\"ppsim\",\n packages=['ppsim'],\n version=version,\n author=\"Eric Severson\",\n description=\"A package for simulating population protocols.\",\n long_description=long_description,\n long_description_content_type='text/markdown',\n url=\"https://github.com/UC-Davis-molecular-computing/population-protocols-python-package\",\n ext_modules=cythonize(distributions, compiler_directives={'language_level': \"3\"}),\n install_requires=install_requires\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1203,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"571281521","text":"path = \"http://localhost:8000/tfjs-lstm-training/index.html\"\n\nbackend_list = [\"cpu\", \"gpu\"]\nlstmLayerSizes = [\"32\", \"64\", \"128\", \"256\",\n \"16,16\", \"16,16\", \"32,32\", \"64,64\", \"128,128\",\n \"4,4,4\", \"8,8,8\", \"16,16,16\", \"32,32,32\"]\nrnn_type = [\"SimpleRNN\", \"GRU\", \"LSTM\"] \nprocess_time = 10000\nexamplesPerEpoch = 2048\nbatchSize = [32, 64, 128, 256]\n\n\nprint(\"[\")\n\nr1 = len(backend_list)\nr2 = len(lstmLayerSizes)\nr3 = len(batchSize)\nr4 = len(rnn_type)\ncount = 0\n\nfor i in range(r1):\n for j in range(r2):\n for k in range(r3):\n for l in range(r4):\n print(' \"%s?&backend=%s&layersizes=%s&batchSize=%d&processtime=%d&numEpochs=%d&rnnType=%s\"' % \n (path, backend_list[i], lstmLayerSizes[j], batchSize[k], process_time, \n examplesPerEpoch, rnn_type[l]), end=\"\")\n if (count != r1 * r2 * r3 * r4 - 1):\n print(\",\")\n else:\n print(\"\")\n count += 1\n\nprint(\"]\")\n","sub_path":"tfjs-lstm-training/urlGenerator.py","file_name":"urlGenerator.py","file_ext":"py","file_size_in_byte":1043,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"179632695","text":"from PyQt5 import uic\nfrom PyQt5.QtWidgets import *\n\n\nclass MainWindow(QWidget):\n\n def __init__(self):\n super().__init__()\n uic.loadUi('form.ui', self)\n self.show()\n\n\n\ndef center(self):\n qr = self.frameGeometry()\n cp = QDesktopWidget().availableGeometry().center()\n qr.moveCenter(cp)\n self.move(qr.topLeft())","sub_path":"window.py","file_name":"window.py","file_ext":"py","file_size_in_byte":360,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"242639388","text":"import random\nimport sentry_sdk\nsentry_sdk.init(\"https://42508ae8bd6040a097bca6b8e500dcd8@sentry.io/1439826\")\ntry:\n from character import Character\n from die import Die\nexcept ImportError:\n from .character import Character\n from .die import Die\n\n\nclass Player(Character):\n \"\"\"Base class for playable character define basic interaction.\"\"\"\n levels_list = [ # List of all level with experiments need to advance to next level\n 20, # 0\n 36, # 16 + 0\n 53, # 16 + 1\n 71, # 16 + 2\n 90, # 16 + 3\n 110, # 16 + 4\n 131, # 16 + 5\n 153, # 16 + 6\n 176, # 16 + 7\n 200, # 16 + 8\n ]\n dice = Die()\n\n def __init__(self, name, health_point, armor, attack, class_type, position):\n \"\"\"Constructor\"\"\"\n self.name = name\n self.health_point = health_point\n self.armor = armor\n self.attack = attack\n self.class_type = class_type\n self.current_exp = 0\n self.level = 1 # Start level\n self.inventory = None\n self.position = position\n\n def move(self, direction):\n \"\"\"\n Player move actions. Player are able to move 4 directions: NORTH, EAST, SOUTH, WEST.\n Each turn player are only move 1 time and advance 1 tile.\n \"\"\"\n pass\n\n def interact(self):\n \"\"\"\n Player interact actions. Player are able to decide which action will take place next turn.\n List of actions:\n - Attack;\n - Cast skills;\n - Use item;\n - ???\n - ...\n \"\"\"\n pass\n\n def level_up(self):\n \"\"\"Level up if player acquire enough current level experiments.\"\"\"\n if self.current_exp >= self.levels_list[self.level]:\n self.level += 1\n\n def improve_stats(self):\n \"\"\"Stats improvement when level up.\"\"\"\n pass\n\n def __str__(self):\n \"\"\"This function use for debug only.\"\"\"\n return \"Name: {}\\nHP: {}\\nArmor: {}\\nAttack: {}\\nClass: {}\\nLevel: {}\".format(self.name,\n self.health_point,\n self.armor,\n self.attack,\n self.class_type,\n self.level,\n )\n\n\nclass Fighter(Player):\n \"\"\"Fighter class\"\"\"\n def __init__(self, name, position):\n \"\"\"Constructor\"\"\"\n super().__init__(name=name,\n health_point=(random.randrange(15, 20) + self.dice.roll()),\n armor=(3 + self.dice.roll()),\n attack=self.dice.roll(),\n class_type=\"Fighter\",\n position=position,\n )\n\n def improve_stats(self):\n self.health_point += 0\n self.armor += 0\n self.attack += 0\n\n\nclass Archer(Player):\n \"\"\"Archer class\"\"\"\n def __init__(self, name, position):\n \"\"\"Constructor\"\"\"\n super().__init__(name=name,\n health_point=(random.randrange(5, 10) + self.dice.roll()),\n armor=self.dice.roll(),\n attack=(random.randrange(2, 7) + self.dice.roll()),\n class_type=\"Archer\",\n position=position,\n )\n\n def improve_stats(self):\n self.health_point += 0\n self.armor += 0\n self.attack += 0\n\n\nclass Assassin(Player):\n \"\"\"Assassin class\"\"\"\n def __init__(self, name, position):\n \"\"\"Constructor\"\"\"\n super().__init__(name=name,\n health_point=(random.randrange(10, 15) + self.dice.roll()),\n armor=(1 + self.dice.roll()),\n attack=(random.randrange(2, 5) + self.dice.roll()),\n class_type=\"Assassin\",\n position=position,\n )\n\n def improve_stats(self):\n self.health_point += 0\n self.armor += 0\n self.attack += 0\n","sub_path":"baseclass/player.py","file_name":"player.py","file_ext":"py","file_size_in_byte":4398,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"36730155","text":"from pymongo import MongoClient\n\n# case \"${TO_DBNAME}\" in\n# \"PERF\") DBHOST_TO=10.62.101.61;; ##need to update to master node\n# \"PRE\") DBHOST_TO=10.62.109.137;;\n# \"UAT\") DBHOST_TO=10.62.109.137;;\n# \"SIT\") DBHOST_TO=10.62.109.136;;\n# esac\n\nignoreList=['lenovo.com','yopmail.com','sharklasers.com']\n\nclient=MongoClient('mongodb://admin:L3novo@10.62.109.137:27017/')\ndb=client.UAT\n\ncollist=db.list_collection_names()\nfor _collection in collist:\n print(_collection)\n\nclient.close()","sub_path":"common_utils/mongodb_utils_test.py","file_name":"mongodb_utils_test.py","file_ext":"py","file_size_in_byte":491,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"490809764","text":"import mysql.connector\nimport os\nfrom pathlib import Path\nfrom mysql.connector.errors import Error\n\ndef prop_test():\n strHost = \"192.168.100.60\"\n strUser = \"vocabjotdown\"\n strPassword = \"Test@123.com\"\n\n mydb = mysql.connector.connect(\n host=strHost,\n user=strUser,\n password=strPassword\n )\n\n\n mycursor = mydb.cursor()\n\n mycursor.execute(\"use vocabjotdown;\")\n\n cascadeDelete(mycursor, 'test')\n \n # populate test account and information\n # add user\n strSql = \"insert into user(login_name, common_name, email, status, last_update_time) values ('test', 'test', 'tom87416@gmail.com', 'A', now())\".format()\n mycursor.execute(strSql)\n uid = mycursor.lastrowid \n\n # select eng id\n strSql = \"select * from language where code='en'\"\n mycursor.execute(strSql)\n rows = mycursor.fetchall()\n lid= rows[0][0]\n\n # user role\n #strSql = \"insert into user_role() values ()\".format()\n #mycursor.execute(strSql)\n\n #add profile\n strSql = \"insert into profile (user_id, language_id, level, status, last_update_time) values ({uid}, {lid}, '{l}', '{s}', now())\".format(uid=uid, lid=lid, l='C1', s='A')\n mycursor.execute(strSql)\n pid = mycursor.lastrowid \n\n #add vocabulary\n words = ['intolerance', 'coherence', 'contraception', 'portrayal']\n meanings = ['lack of tolerance; unwillingness or refusal to tolerate or respect opinions or beliefs contrary to one''s own.', \n 'the act or state of cohering; cohesion.', 'the deliberate prevention of conception or impregnation by any of various drugs, techniques, or devices; birth control.', \n 'the act of portraying.']\n for w in words:\n strSql = \"insert into vocabulary (profile_id, word, progress, last_update_time) values ({pid}, '{w}', '{s}', now()) \".format(pid=pid , w=w, s='A')\n mycursor.execute(strSql)\n\n #add article\n title = \"The adoption\"\n f = open(r\"C:\\GitProjects\\vocabjotdown\\poc\\data\\english\\corpos\\steve.txt\", \"r\", encoding='UTF-8')\n content = escapeQ(f.read())\n strSql = \"insert into article (profile_id, title, content, status, create_time, last_update_time) values ({pid}, '{t}', '{c}', '{s}', now(), now())\".format(pid=pid, t=title, c=content, s='A')\n mycursor.execute(strSql)\n\n #add flash card deck\n strSql = \"insert into flashcarddeck (profile_id, create_time, last_update_time, status) values ({pid}, now(), now(), 'A')\".format(pid=pid)\n mycursor.execute(strSql)\n did = mycursor.lastrowid \n\n #add flash card\n for w, m in zip(words, meanings):\n strSql = \"insert into flashcard (deck_id, word, meaning, last_study, response, create_time, last_update_time, status) values ({did}, '{w}', '{m}', now(), 5, now(), now(), 'A')\".format(did=did, w=w, m=m)\n mycursor.execute(strSql)\n\n\n # clean up\n mydb.commit()\n mycursor.close()\n mydb.close()\n\ndef cascadeDelete(mycursor, username):\n # remove the user if exists\n strSql = \"select * from user where login_name='{name}'\".format(name=username)\n mycursor.execute(strSql)\n rowsu = mycursor.fetchall()\n\n for rowu in rowsu:\n\n uid = rowu[0]\n\n strSql = \"select * from profile where user_id={uid}\".format(uid=uid)\n print(strSql)\n mycursor.execute(strSql)\n rows = mycursor.fetchall()\n\n for row in rows:\n\n pid = row[0]\n\n strSql = \"delete from vocabulary where profile_id={pid}\".format(pid=pid)\n mycursor.execute(strSql)\n \n strSql = \"delete from article where profile_id={pid}\".format(pid=pid)\n mycursor.execute(strSql)\n\n strSql = \"select * from flashcarddeck where profile_id={pid}\".format(pid=pid)\n mycursor.execute(strSql)\n rows2 = mycursor.fetchall()\n\n for row2 in rows2:\n did = row2[0]\n\n strSql = \"delete from flashcard where deck_id={did}\".format(did=did)\n mycursor.execute(strSql)\n\n strSql = \"delete from flashcarddeck where profile_id={pid}\".format(pid=pid)\n mycursor.execute(strSql)\n\n strSql = \"delete from profile where id={pid}\".format(pid=pid)\n mycursor.execute(strSql)\n\n strSql = \"delete from user where id={uid}\".format(uid=uid)\n mycursor.execute(strSql)\n\ndef escapeQ(w):\n return w.replace(\"'\", \"''\")\n\nif __name__ == \"__main__\":\n prop_test()","sub_path":"sql/prop_test_data.py","file_name":"prop_test_data.py","file_ext":"py","file_size_in_byte":4130,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"494847378","text":"\n\nfrom xai.brain.wordbase.verbs._preordain import _PREORDAIN\n\n#calss header\nclass _PREORDAINS(_PREORDAIN, ):\n\tdef __init__(self,): \n\t\t_PREORDAIN.__init__(self)\n\t\tself.name = \"PREORDAINS\"\n\t\tself.specie = 'verbs'\n\t\tself.basic = \"preordain\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/verbs/_preordains.py","file_name":"_preordains.py","file_ext":"py","file_size_in_byte":259,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"15892841","text":"\"\"\"\nCreated on Thu Sep 11 14:41:48 2014\n\n@author: Natural Solutions (Thomas)\n\"\"\"\n\nfrom collections import OrderedDict\n\nfrom pyramid.view import view_config\nfrom sqlalchemy import select\n\nfrom ecorelevesensor.models import DBSession\nfrom ecorelevesensor.models.object import ObjectGsm\n\nroute_prefix = 'transmitter/'\n\n@view_config(route_name=route_prefix + 'search/values', renderer='json')\ndef transmitter_values(request):\n ''' Get the different values of the field_name given in parameter.\n If a parameter limit is passed, then limit the number of values returned.\n '''\n column = request.params['field_name']\n limit = int(request.params.get('limit', 0))\n if column in ObjectGsm.__table__.columns:\n query = select([ObjectGsm.__table__.c[column]]\n ).where(ObjectGsm.__table__.columns[column]!=None\n ).order_by(ObjectGsm.__table__.columns[column]\n ).distinct()\n if limit > 0:\n query = query.limit(limit)\n return [str(item[column]) for item in DBSession.execute(query).fetchall()]\n else:\n return []\n \n@view_config(route_name=route_prefix + 'search', renderer='json', request_method='POST')\ndef core_individuals_search(request):\n '''Search individuals by posting a JSON object containing the fields :\n - criteria : dict object with column_name:value fields\n - order_by : dict object with column_name:'asc' or column_name:'desc' fields\n - offset : int\n - limit : int\n '''\n query = select(ObjectGsm.__table__.c)\n # Look over the criteria list\n criteria = request.json_body.get('criteria', {})\n for column, value in criteria.items():\n if column in ObjectGsm.__table__.c and value != '':\n query = query.where(ObjectGsm.__table__.c[column] == value)\n # Define the limit and offset if exist\n limit = int(request.json_body.get('limit', 0))\n offset = int(request.json_body.get('offset', 0))\n if limit > 0:\n query = query.limit(limit)\n if offset > 0:\n offset = query.offset(offset)\n # Set sorting columns and order\n order_by = request.json_body.get('order_by', {})\n order_by_clause = []\n for column, order in order_by.items():\n if column in ObjectGsm.__table__.columns:\n if order == 'asc':\n order_by_clause.append(ObjectGsm.__table__.columns[column].asc())\n elif order == 'desc':\n order_by_clause.append(ObjectGsm.__table__.columns[column].desc())\n if len(order_by_clause) > 0:\n query = query.order_by(*order_by_clause)\n # Run query\n return [OrderedDict(row) for row in DBSession.execute(query).fetchall()]","sub_path":"ecorelevesensor/views/transmitter.py","file_name":"transmitter.py","file_ext":"py","file_size_in_byte":2682,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"391036198","text":"\"\"\"Retrieve a scale based on a given mode and starting note.\"\"\"\n\nimport math\n\n\nclass MusicException(Exception):\n \"\"\"Base exception for the musical_scales module.\"\"\"\n\n pass\n\n\nclass Note:\n \"\"\"A single note in a given octave, e.g. C#3.\n\n Measured as a number of semitones above Middle C:\n * Note(0) # Middle C, i.e. C3\n * Note(2) # D3\n \"\"\"\n\n semitones_above_middle_c: int\n name: str\n octave: int\n\n def __init__(self, name: str = None, semitones_above_middle_c: int = None):\n \"\"\"Create a note with a given name or degree.\n\n Examples:\n * Note(\"C#\")\n * Note(semitones_above_middle_c = 1)\n \"\"\"\n if name is not None:\n if name not in interval_from_names:\n raise MusicException(f\"No note found with name {name}.\")\n self._set_degree(interval_from_names[name])\n elif semitones_above_middle_c is not None:\n self._set_degree(semitones_above_middle_c)\n else:\n self._set_degree(0)\n\n def _set_degree(self, semitones_above_middle_c: int):\n \"\"\"Set the note name and octave.\n\n Should only be used during initialisation.\n \"\"\"\n self.semitones_above_middle_c = semitones_above_middle_c\n self.name = names_from_interval[semitones_above_middle_c % 12]\n self.octave = math.floor(semitones_above_middle_c / 12) + 3\n\n def __str__(self):\n \"\"\"MIDI-style string representation e.g. C#3.\"\"\"\n return self.midi\n\n def __repr__(self):\n \"\"\"MIDI-style string representation e.g. C#3.\"\"\"\n return self.midi\n\n @property\n def midi(self):\n \"\"\"Note name and octave, e.g. C3.\"\"\"\n return f\"{self.name}{self.octave}\"\n\n def __add__(self, shift: int):\n \"\"\"Shifting this note's degree upwards.\"\"\"\n return Note(semitones_above_middle_c=self.semitones_above_middle_c + shift)\n\n def __sub__(self, shift: int):\n \"\"\"Shifting this note's degree downwards.\"\"\"\n return self + (-shift)\n\n def __eq__(self, other):\n \"\"\"Check equality via .midi.\"\"\"\n if isinstance(other, Note):\n return self.midi == other.midi\n else:\n return self.midi == other or self.name == other\n\n\ndef scale(starting_note, mode=\"ionian\", octaves=1):\n \"\"\"Return a sequence of Notes starting on the given note in the given mode.\n\n Example:\n * scale(\"C\") # C major (ionian)\n * scale(Note(4), \"harmonic minor\") # E harmonic minor\n \"\"\"\n if mode not in scale_intervals:\n raise MusicException(f\"The mode {mode} is not available.\")\n if not isinstance(starting_note, Note):\n starting_note = Note(starting_note)\n notes = [starting_note]\n for octave in range(0, octaves):\n for interval in scale_intervals[mode]:\n notes.append(notes[-1] + interval)\n return notes\n\n\n# Found at https://en.wikipedia.org/wiki/List_of_musical_scales_and_modes\n# Only scales that include a representation given\n# by semi-tone intervals are included.\n# One alteration is that this repository will use the term \"Romani\"\nscale_intervals = {\n \"acoustic\": [2, 2, 2, 1, 2, 1, 2],\n \"aeolian\": [2, 1, 2, 2, 1, 2, 2],\n \"algerian\": [2, 1, 3, 1, 1, 3, 1, 2, 1, 2],\n \"super locrian\": [1, 2, 1, 2, 2, 2, 2],\n \"augmented\": [3, 1, 3, 1, 3, 1],\n \"bebop dominant\": [2, 2, 1, 2, 2, 1, 1, 1],\n \"blues\": [3, 2, 1, 1, 3, 2],\n \"chromatic\": [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],\n \"dorian\": [2, 1, 2, 2, 2, 1, 2],\n \"double harmonic\": [1, 3, 1, 2, 1, 3, 1],\n \"enigmatic\": [1, 3, 2, 2, 2, 1, 1],\n \"flamenco\": [1, 3, 1, 2, 1, 3, 1],\n \"romani\": [2, 1, 3, 1, 1, 2, 2],\n \"half-diminished\": [2, 1, 2, 1, 2, 2, 2],\n \"harmonic major\": [2, 2, 1, 2, 1, 3, 1],\n \"harmonic minor\": [2, 1, 2, 2, 1, 3, 1],\n \"hijaroshi\": [4, 2, 1, 4, 1],\n \"hungarian minor\": [2, 1, 3, 1, 1, 3, 1],\n \"hungarian major\": [3, 1, 2, 1, 2, 1, 2],\n \"in\": [1, 4, 2, 1, 4],\n \"insen\": [1, 4, 2, 3, 2],\n \"ionian\": [2, 2, 1, 2, 2, 2, 1],\n \"iwato\": [1, 4, 1, 4, 2],\n \"locrian\": [1, 2, 2, 1, 2, 2, 2],\n \"lydian augmented\": [2, 2, 2, 2, 1, 2, 1],\n \"lydian\": [2, 2, 2, 1, 2, 2, 1],\n \"locrian major\": [2, 2, 1, 1, 2, 2, 2],\n \"pentatonic major\": [2, 2, 3, 2, 3],\n \"melodic minor ascending\": [2, 1, 2, 2, 2, 2, 1],\n \"melodic minor descending\": [2, 1, 2, 2, 2, 2, 1],\n \"pentatonic minor\": [3, 2, 2, 3, 2],\n \"mixolydian\": [2, 2, 1, 2, 2, 1, 2],\n \"neapolitan major\": [1, 2, 2, 2, 2, 2, 1],\n \"neapolitan minor\": [1, 2, 2, 2, 1, 3, 1],\n \"octatonic c-d\": [2, 1, 2, 1, 2, 1, 2, 1],\n \"octatonic c-c#\": [1, 2, 1, 2, 1, 2, 1],\n \"persian\": [1, 3, 1, 1, 2, 3, 1],\n \"phrygian dominant\": [1, 3, 1, 2, 1, 2, 2],\n \"phrygian\": [1, 2, 2, 2, 1, 2, 2],\n \"prometheus\": [2, 2, 2, 3, 1, 2],\n \"harmonics\": [3, 1, 1, 2, 2, 3],\n \"tritone\": [1, 3, 2, 1, 3, 2],\n \"two-semitone tritone\": [1, 1, 4, 1, 1, 4],\n \"ukranian dorian\": [2, 1, 3, 1, 2, 1, 2],\n \"whole-tone scale\": [2, 2, 2, 2, 2, 2],\n \"yo\": [3, 2, 2, 3, 2]\n}\n\nscale_intervals[\"major\"] = scale_intervals[\"ionian\"]\n\nnames_from_interval = {\n 0: \"C\",\n 1: \"C#\",\n 2: \"D\",\n 3: \"D#\",\n 4: \"E\",\n 5: \"F\",\n 6: \"F#\",\n 7: \"G\",\n 8: \"G#\",\n 9: \"A\",\n 10: \"A#\",\n 11: \"B\"\n}\n\"\"\"From an interval give the note name, favouring sharps over flats.\"\"\"\n\ninterval_from_names = {\n \"C\": 0,\n \"C#\": 1,\n \"Db\": 1,\n \"D\": 2,\n \"D#\": 3,\n \"Eb\": 3,\n \"E\": 4,\n \"Fb\": 4,\n \"E#\": 5,\n \"F\": 5,\n \"F#\": 6,\n \"Gb\": 6,\n \"G\": 7,\n \"G#\": 8,\n \"Ab\": 8,\n \"A\": 9,\n \"A#\": 10,\n \"Bb\": 10,\n \"B\": 11,\n \"Cb\": 11,\n \"B#\": 0\n}\n\"\"\"Dictionary from note names to number of semitones above C.\"\"\"\n\n# MIT License\n\n\"\"\"\nThe MIT License (MIT)\n\nCopyright (c) 2021 Hector Miller-Bakewell\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n\"\"\"\n","sub_path":"src/musical_scales/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":6814,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"6874821","text":"import argparse\nimport common.config\nimport common.view\n\n\ndef main():\n parser = argparse.ArgumentParser()\n common.config.add_argument(parser)\n\n parser.add_argument('--trade-id', '-t')\n parser.add_argument('--all', '-a', action='store_true', default=False)\n parser.add_argument('--summary', '-s', action='store_true', default=True)\n parser.add_argument('--verbose', '-v', dest='summary', action='store_false')\n\n args = parser.parse_args('-a -v'.split())\n\n if args.trade_id is None and not args.all:\n parser.error(\"Must provide --trade-id or --all\")\n\n account_id = args.config.active_account\n\n api = args.config.create_context()\n\n if args.all:\n response = api.trade.list_open(account_id)\n if not args.summary:\n print(\"-\" * 80)\n for trade in reversed(response.get(\"trades\", 200)):\n if args.summary:\n print(trade.title())\n else:\n print(trade.yaml(True))\n print(\"-\" * 80)\n return\n\n if args.trade_id:\n response = api.trade.get(account_id, args.trade_id)\n trade = response.get(\"trade\", 200)\n if args.summary:\n print(trade.title())\n else:\n print(trade.yaml(True))\n return\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"m_src/trade/get.py","file_name":"get.py","file_ext":"py","file_size_in_byte":1310,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"338447993","text":"# Copyright 2018 Delft University of Technology\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport timeit\nimport argparse\nimport gc\nimport pandas as pd\nimport pyarrow as pa\nimport pyfletcher as pf\n\n# Add pyre2 to the Python 3 compatibility wall of shame\n__builtins__.basestring = str\nimport re2\n\n\nclass Timer:\n def __init__(self, gc_disable=True):\n self.starttime = 0\n self.stoptime = 0\n self.gc_disable = gc_disable\n\n def start(self):\n if self.gc_disable:\n gc.disable()\n self.starttime = timeit.default_timer()\n\n def stop(self):\n self.stoptime = timeit.default_timer()\n gc.enable()\n\n def seconds(self):\n return self.stoptime - self.starttime\n\n\nclass RegExCore(pf.UserCore):\n\n def __init__(self, context):\n self.reuc_result_offset = 42\n if self.get_platform().get_name() == \"aws\":\n self.active_units = 16\n self.ctrl_start = 0x0000FFFF\n self.ctrl_reset = 0xFFFF0000\n self.done_status = 0xFFFF0000\n self.done_status_mask = 0xFFFFFFFF\n elif self.get_platform().get_name() == \"echo\":\n self.active_units = 16\n elif self.get_platform().get_name() == \"snap\":\n self.active_units = 8\n self.ctrl_start = 0x000000FF\n self.ctrl_reset = 0x0000FF00\n self.done_status = 0x0000FF00\n self.done_status_mask = 0x0000FFFF\n\n def _generate_unit_arguments(self, first_index, last_index):\n arguments = [0]*2*self.active_units\n\n if first_index >= last_index:\n raise RuntimeError(\"First index cannot be larger than or equal to last index.\")\n\n match_rows = last_index - first_index\n for i in range(self.active_units):\n first = first_index + i*match_rows/self.active_units\n last = first + match_rows/self.active_units\n arguments[i] = first\n arguments[self.active_units + i] = last\n\n return arguments\n\n def set_reg_exp_arguments(self, first_index, last_index):\n arguments = self._generate_unit_arguments(first_index, last_index)\n self.set_arguments(arguments)\n\n def get_matches(self, num_reads):\n matches = []\n for p in range(num_reads):\n matches.append(self.get_platform().read_mmio(self.reuc_result_offset + p))\n\n return matches\n\n\n\n\ndef create_record_batch(strings):\n \"\"\"\n Creates an Arrow record batch containing one column of strings.\n\n Args:\n strings(sequence, iterable, ndarray or Series): Strings for in the record batch\n\n Returns:\n record_batch\n\n \"\"\"\n array = pa.array(strings)\n column_field = pa.field(\"tweets\", pa.string(), False)\n schema = pa.schema([column_field])\n return pa.RecordBatch.from_arrays([array], schema)\n\n\ndef add_matches_cpu(strings, regexes):\n progs = []\n matches = []\n\n for regex in regexes:\n progs.append(re2.compile(regex))\n\n for prog in progs:\n result = 0\n for string in strings:\n if prog.test_fullmatch(string):\n result += 1\n matches.append(result)\n\n return matches\n\n\ndef add_matches_cpu_arrow(strings, regexes):\n progs = []\n matches = []\n\n for regex in regexes:\n progs.append(re2.compile(regex))\n\n for prog in progs:\n result = 0\n for string in strings:\n if prog.test_fullmatch(string.as_py()):\n result += 1\n matches.append(result)\n\n return matches\n\n\nif __name__ == \"__main__\":\n t = Timer()\n\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--num_exp\", dest=\"ne\", default=1,\n help=\"Number of experiments to perform\")\n parser.add_argument(\"--input_strings\", dest=\"input_file\", default=\"../build/strings1024.dat\",\n help=\"Path to file with strings to search through\")\n parser.add_argument(\"--platform_type\", dest=\"platform_type\", default=\"echo\", choices=[\"echo\", \"aws\"],\n help=\"Type of FPGA platform\")\n args = parser.parse_args()\n\n # Parsed args\n ne = int(args.ne)\n input_file = args.input_file\n platform_type = args.platform_type\n\n # Regular expressions to match in input file\n regexes = [\".*(?i)bird.*\", \".*(?i)bunny.*\", \".*(?i)cat.*\", \".*(?i)dog.*\", \".*(?i)ferret.*\", \".*(?i)fish.*\",\n \".*(?i)gerbil.*\", \".*(?i)hamster.*\", \".*(?i)horse.*\", \".*(?i)kitten.*\", \".*(?i)lizard.*\",\n \".*(?i)mouse.*\", \".*(?i)puppy.*\", \".*(?i)rabbit.*\", \".*(?i)rat.*\", \".*(?i)turtle.*\"]\n np = len(regexes)\n\n bytes_copied = 0\n\n # Timers\n t_pcpu = []\n t_ncpu = []\n t_acpu = []\n t_copy = []\n t_fpga = []\n\n # Matches\n m_pcpu = []\n m_ncpu = []\n m_acpu = []\n m_fpga = []\n\n f = open(input_file, 'r')\n filedata = f.read()\n\n strings_native = filedata.splitlines()\n strings_pandas = pd.Series(strings_native)\n\n t.start()\n rb = create_record_batch(strings_native)\n t.stop()\n t_nser = t.seconds()\n\n t.start()\n rb = create_record_batch(strings_pandas)\n t.stop()\n t_pser = t.seconds()\n\n print(\"Native to Arrow serialization time: \" + str(t_nser))\n print(\"Pandas to Arrow serialization time: \" + str(t_pser))\n\n num_rows = len(strings_native)\n\n for e in range(ne):\n # Match Python list on CPU (marginal performance improvement most likely possible with Cython)\n t.start()\n m_ncpu.append(add_matches_cpu(strings_native, regexes))\n t.stop()\n t_ncpu.append(t.seconds())\n print(t.seconds())\n\n # Match Pandas series on CPU (marginal performance improvement most likely possible with Cython)\n t.start()\n m_pcpu.append(add_matches_cpu(strings_pandas, regexes))\n t.stop()\n t_pcpu.append(t.seconds())\n print(t.seconds())\n\n # Match Arrow array on CPU (significant performance improvement most likely possible with Cython)\n t.start()\n m_acpu.append(add_matches_cpu_arrow(rb.column(0), regexes))\n t.stop()\n t_acpu.append(t.seconds())\n print(t.seconds())\n\n # Match Arrow array on FPGA\n platform = pf.Platform(platform_type)\n context = pf.Context(platform)\n rc = RegExCore(context)\n\n # Initialize the platform\n platform.init()\n\n # Reset the UserCore\n rc.reset()\n\n # Prepare the column buffers\n t.start()\n context.queue_record_batch(rb)\n bytes_copied += context.get_queue_size()\n context.enable()\n t.stop()\n t_copy.append(t.seconds())\n\n # Run the example\n t.start()\n rc.set_reg_exp_arguments(0, num_rows)\n\n # Start the matchers and poll until completion\n rc.start()\n rc.wait_for_finish(10)\n\n # Get the number of matches from the UserCore\n m_fpga.append(rc.get_matches(np))\n t.stop()\n t_fpga.append(t.seconds())\n\n\n print(\"Bytes copied: \" + str(bytes_copied))\n\n print(\"Total runtimes for \" + str(ne) + \"runs:\")\n print(\"Python list on CPU: \" + str(sum(t_ncpu)))\n print(\"Pandas series on CPU: \" + str(sum(t_pcpu)))\n print(\"Arrow array on CPU: \" + str(sum(t_acpu)))\n print(\"Arrow array on FPGA: \" + str(sum(t_fpga)))\n\n # Accumulated matches\n a_ncpu = [0] * np\n a_pcpu = [0] * np\n a_acpu = [0] * np\n a_fpga = [0] * np\n\n for p in range(np):\n for e in range(ne):\n a_ncpu[p] += m_ncpu[e][p]\n a_pcpu[p] += m_pcpu[e][p]\n a_acpu[p] += m_acpu[e][p]\n a_fpga[p] += m_fpga[e][p]\n\n # Check if matches are equal\n if (a_ncpu == a_pcpu) and (a_pcpu == a_acpu) and (a_acpu == a_fpga):\n print(\"PASS\")\n else:\n print(\"ERROR\")\n","sub_path":"examples/regexp/software/python/regexp.py","file_name":"regexp.py","file_ext":"py","file_size_in_byte":8246,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"124859625","text":"import pygame, sys, random,time\nfrom pygame.locals import *\npygame.init()\nDISPLAYSURF = pygame.display.set_mode((800, 500))\nWHITE=(255,255,255)\nBLACK=(0,0,0)\nsize = 15.625\nboardLength = 32\nDISPLAYSURF.fill(WHITE)\nboardValues = []\nfor i in range(0,boardLength):\n for z in range(0,boardLength):\n rand = random.randint(0,255)\n board = (rand,rand,rand)\n boardValues.append(rand)\n pygame.draw.rect(DISPLAYSURF, board,[size*z,size*i,size,size])\npygame.display.update()\n","sub_path":"Pygame/grid.py","file_name":"grid.py","file_ext":"py","file_size_in_byte":494,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"559255074","text":"from django.urls import reverse_lazy\nfrom django.shortcuts import render, HttpResponse\nfrom django.views.generic import ListView, \\\n CreateView, DetailView, UpdateView, DeleteView\nfrom . import models\n\n# Create your views here.\n\n\nclass home(ListView):\n model = models.Mask\n template_name = 'masks/home.html'\n\nclass about(ListView):\n model = models.About\n template_name = 'masks/about.html'\n context_object_name = 'about'\n\n\n# -- Usage related classes\nclass ListUsage(ListView):\n model = models.Usage\n template_name = 'masks/list_usage.html'\n context_object_name = 'usages'\n\n# - C\nclass CreateUsage(CreateView):\n model = models.Usage\n fields=['name','comment']\n template_name = 'masks/create_usage.html'\n context_object_name = 'usages'\n\n# - R\nclass ReadUsage(DetailView):\n model = models.Usage\n template_name = 'masks/readUsage.html'\n context_object_name = 'usages'\n\n# - U\nclass UpdateUsage(UpdateView):\n model = models.Usage\n template_name = 'masks/updateUsage.html'\n context_object_name = 'usages'\n\n# - D\nclass DeleteUsage(DeleteView):\n model = models.Usage\n template_name = 'masks/deleteUsage.html'\n context_object_name = 'usages'\n\n#--------------------------------------------------------------------------------\n# -- masks related views\n#--------------------------------------------------------------------------------\nclass ListMasks(ListView):\n model = models.Mask\n template_name = 'masks/list_mask.html'\n context_object_name = 'masks'\n\n # tentative for a generic listview filtered by kw and pk\n def get_queryset(self):\n searched_kw = self.kwargs.get('kw',None)\n searched_pk = self.kwargs.get('pk',None)\n if searched_pk and searched_kw:\n arg_as_dict = {searched_kw:searched_pk}\n return models.Mask.objects.filter(**arg_as_dict)\n else:\n return super().get_queryset()\n\n# - C\nclass CreateUpdateMask(UpdateView):\n model = models.Mask\n fields = ['idNumber','name','usage']\n template_name = 'masks/create_mask.html'\n context_object_name = 'masks'\n success_url = reverse_lazy('masks:masks-list')\n #extra_context={'something':'something'}\n\n def get_object(self,queryset=None):\n print(\" get_object called\")\n try:\n return super().get_object(queryset)\n #return super(CreateUpdateView,self).get_object(queryset)\n except AttributeError:\n return None\n\n def get_context_data(self, **kwargs):\n r=super().get_context_data(**kwargs)\n print(\"get_context_data\"+str(r))\n return r\n\n def form_valid(self,form):\n print(\"called form_valid\")\n response = super().form_valid(form)\n\n for fileimage in self.request.FILES.getlist('file'):\n image=models.Image(mask_id=self.object.id,data=fileimage)\n image.save()\n # do something with self.object\n print(str(self.object)+\" \"+str(dir(self.object)))\n print(\"received \" + str(self.request.FILES))\n return response\n def post(self,request,*args,**kwargs):\n print(\"called post\")\n f = super().post(request, *args, **kwargs)\n print(\"f is \"+str(f)+str(dir(f)))\n return f\n\n\n# - R\nclass ReadMask(DetailView):\n model = models.Mask\n template_name = 'masks/readMask.html'\n context_object_name = 'masks'\n\n# - U\nclass UpdateMask(UpdateView):\n model = models.Mask\n template_name = 'masks/updateMask.html'\n context_object_name = 'usages'\n\n# - D\nclass DeleteMask(DeleteView):\n model = models.Mask\n template_name = 'masks/deleteMask.html'\n context_object_name = 'usages'\n","sub_path":"masks/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3646,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"407822026","text":"\nimport six\nimport pandas as pd\nfrom radiomics import featureextractor\n\ndef output_xlsx(dict_item,name):\n pf=pd.DataFrame(list(dict_item))\n xlsx_name=name+'.xlsx'\n xlsx_obj=pd.ExcelWriter(xlsx_name)\n pf.to_excel(xlsx_obj)\n xlsx_obj.save()\n\n\n\n\nparams = './data/pyradiomics_yaml/exampleMR_NoResampling.yaml'\nextractor = featureextractor.RadiomicsFeatureExtractor(params)\n\nimageName='./data/t2Test/REN GUI LIAN^REN GUI/REN GUI LIAN^REN GUI_t2.nii.gz'\nmaskName = './data/t2Test/REN GUI LIAN^REN GUI/REN GUI LIAN^REN GUI_seg.nii.gz'\nresult = extractor.execute(imageName, maskName)\n\ndict_item=result.items()\nname = './data/t2Test/REN GUI LIAN^REN GUI'\noutput_xlsx(dict_item,name)\n\n\nfor key, val in six.iteritems(result):\n print(\"\\t%s: %s\" %(key, val))\n","sub_path":"radio.py","file_name":"radio.py","file_ext":"py","file_size_in_byte":764,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"102702427","text":"###############################################################################\n#\n# Player object for game of Cribbage\n#\n#\n###############################################################################\n\n#import libraries\nimport random\nfrom Hand import Hand\n\n# Player class has a hand of cards and a position\nclass Player:\n\n def __init__( self, name ):\n\n #keep track of player name\n self.name = name\n\n # keep track of where the player is\n self.position = 0\n\n # keep track of player's hand\n self.hand = Hand()\n\n # keep track of played cards\n self.playable = Hand()\n self.playableVals = []\n\n #keep track of if we can play\n self.ableToPeg = True\n self.playing = True\n\n\n # method to move the player forward in position by a number of points\n def move( self, points ):\n\n #move the position forward by the number of points\n self.position += points\n\n #check if we have won\n if self.position > 120:\n\n print( self.name + \" has won the game! Exiting...\" )\n exit()\n\n #otherwise print where we are\n else:\n\n #print current location\n print( self.name + \" is now at \" + str( self.position ) )\n\n\n # function for updating the hand\n def update( self ):\n \n # add vals to playable and playableVals\n for x in range( 0, 4 ):\n\n # add the cards to the hands\n self.playableVals.append( self.hand.cardVals[x][0] + 1 )\n self.playable.addCard( self.hand.cardNums[x] )\n\n # denote we have a new hand and therefore can play\n self.ableToPlay = True\n self.playing = True\n\n\n def parse( self, card ):\n\n try:\n\n toThrow = int( card )\n return toThrow\n\n except:\n\n print( card + \" is not a valid integer!\" )\n return -1\n\n # function for playing in pegging\n def play( self, score, discard, ai, isAi ):\n\n # denote whos turn it is\n print( self.name + \"'s turn! \\n\" )\n\n # make variable to store played card\n played = -1\n\n # check if we can play any cards\n if len( self.playableVals ) == 0:\n\n #denote we are out of cards\n print( self.name + \" is out of cards!\" )\n\n self.playing = False\n self.ableToPeg = False\n return -1\n\n # make boolean for keeping track of if we can play any cards\n canPlay = [False] * len( self.playableVals )\n playPossible = False\n\n # check if we have any playable cards\n for x in range( 0, len( self.playableVals ) ):\n\n #check if we have any playable face cards\n if self.playableVals[x] > 10:\n if score + 10 <= 31:\n \n # denote we can play a card\n canPlay[x] = True\n playPossible = True\n\n # check if we have any playable cards\n else:\n \n #check if we can play the card\n if score + self.playableVals[x] <= 31:\n\n # denote we can play a card\n canPlay[x] = True\n playPossible = True\n\n # make sure we can play something\n if not playPossible:\n\n # denote we are skipping\n print( self.name + \" says go!\" )\n self.ableToPeg = False\n return 0\n\n # print the playable cards if this player is human\n if not isAi:\n self.playable.showCards( len(self.playableVals) )\n\n\n while played == -1:\n\n # ask which card the user wants to throw\n if isAi:\n\n # make a copy of the discard pile\n dCopy = list( discard )\n\n toThrow = ai.determinePeg( score, dCopy, self.playableVals )\n\n if toThrow < 0: \n\n print( \"Something is wrong; your AI sucks!\" )\n return -1\n\n else:\n # ask the user what card they'd like to throw\n in1 = input( \"Which card would you like to play?: \" )\n\n toThrow = self.parse( in1 )\n\n # make sure card is in a valid index\n if( toThrow >= 0 and toThrow < len(self.playableVals) ):\n\n\n #make sure card is playable\n if( canPlay[toThrow] ):\n\n #store the played value\n played = self.playableVals[toThrow]\n\n #add played value to discard\n discard.append( played )\n\n #remove the card from the playable and playableVals\n del self.playableVals[ toThrow ]\n self.playable.removeCard( toThrow )\n\n #if the card is not playable\n else:\n\n #denote this card cannot be thrown\n print( \"Cannot play \" + Hand.cardString( self.playable.cardNums[ toThrow ] ) + \". Try again.\" )\n\n else:\n\n #tell the user to try again\n print( \"Please give a number between 0 and \" + str( len( self.playableVals ) - 1 ) )\n\n \n return played\n","sub_path":"PlayerBot.py","file_name":"PlayerBot.py","file_ext":"py","file_size_in_byte":5236,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"332801017","text":"import uuid\nfrom src.common.database import Database\nfrom src.models.benchmarks.benchmark import Benchmark\nimport src.models.contests.constants as ContestConstants\n\n__author__ = 'jgutman'\n\n\nclass Contest(object):\n def __init__(self, benchmark_id, level, comparison, expiration, owner_id, is_public=True, is_active=True, description=\"\", _id=None):\n self.benchmark_id = benchmark_id\n self.level = level\n self.comparison = comparison\n self.expiration = expiration\n self.owner_id = owner_id\n self.description = description\n self.is_active = is_active\n self.is_public = is_public\n self._id = uuid.uuid4().hex if _id is None else _id\n self.benchmark = None\n\n def get_id(self):\n return self._id\n\n def get_benchmark(self):\n if not self.benchmark:\n self.benchmark = Benchmark.find_by_id(self.benchmark_id)\n return self.benchmark\n\n def json(self):\n return {\n 'benchmark_id': self.benchmark_id,\n 'level': self.level,\n 'comparison': self.comparison,\n 'expiration': self.expiration,\n 'description': self.description,\n 'owner_id': self.owner_id,\n 'is_active': self.is_active,\n 'is_public': self.is_public,\n '_id': self._id,\n }\n\n def save_to_mongo(self):\n Database.update(ContestConstants.COLLECTION, {'_id': self._id}, self.json())\n\n def comparison_string(self):\n return ContestConstants.COMPARISON_MAP[self.comparison]\n\n @staticmethod\n def _convert_value_input(value):\n if str(value).lower() in ('true', 'false'):\n v_tmp = str(value).lower()\n value = (v_tmp == 'true')\n else:\n value = float(value)\n return value\n\n @classmethod\n def find_by_id(cls, contest_id):\n return cls(**Database.find_one(ContestConstants.COLLECTION, {'_id': contest_id}))\n\n @classmethod\n def find_by_benchmark_id(cls, benchmark_id):\n return [cls(**contest_data) for contest_data in Database.find(ContestConstants.COLLECTION, {'benchmark_id': benchmark_id})]\n\n @classmethod\n def get_all(cls):\n return [cls(**contest_data) for contest_data in Database.find(ContestConstants.COLLECTION, {})]\n\n @classmethod\n def find_available_contests_for_user(cls, user_id):\n query = {\n 'is_active': True,\n '$or': [{'owner_id': user_id}, {'is_public': True}]\n }\n return [cls(**contest_data) for contest_data in Database.find(ContestConstants.COLLECTION, query)]\n\n","sub_path":"src/models/contests/contest.py","file_name":"contest.py","file_ext":"py","file_size_in_byte":2599,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"315722048","text":"from __future__ import division\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport glob\n\n\n\n\nfiles = glob.glob('*.txt')\nfig = plt.figure(figsize=(10,10))\nax1 = fig.add_subplot(211)\nax2 = fig.add_subplot(212,sharex=ax1)\nax1.scatter(0,0,c='r')\ndef process(file,ID):\n data = np.loadtxt(file)\n x = data[:,0]\n y = data[:,1]\n z = data[:,2]\n Q = data[:,3]\n E = data[:,4]\n L = data[:,5]\n err=data[:,6]\n\n col = 'C'+str(ID)\n print (col,ID)\n ax2.plot(x,err,c=col)\n ax1.plot(x,y,c=col)\n\n\ncounter = 0\nfor f in files:\n process(f,counter)\n counter += 1\n\n\nlimit = 100\n#ax1.set_xlim(-limit,limit)\n#ax1.set_ylim(-limit,limit)\nplt.show()\n\n","sub_path":"RTBeta/plotter.py","file_name":"plotter.py","file_ext":"py","file_size_in_byte":668,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"263884931","text":"import os\nimport model\nimport flask\nfrom werkzeug.utils import secure_filename\n\n# Creating a new Flask Web application. It accepts the package name.\napp = flask.Flask(__name__)\n\n\ndef CNN_predict():\n \"\"\"\n Upload the image file and classify the severity of DR using pre-trained CNN model\n \"\"\"\n\n \"\"\"\n Predicted rating of image for the severity of diabetic retinopathy on a scale of 0 to 4:\n\n 0 - No DR\n 1 - Mild\n 2 - Moderate\n 3 - Severe\n 4 - Proliferative DR\n \"\"\"\n diagnosis = [\"No DR\", \"Mild\", \"Moderate\", \"Severe\", \"Proliferative DR\"]\n\n global secure_filename\n\n # Getting the image path\n img_path = os.path.join(app.root_path, secure_filename)\n\n \"\"\"\n Check if image exists\n \"\"\"\n if os.path.isfile(img_path):\n # predicting class from pretrained model\n predicted_class = model.classify_image(img_path)\n\n \"\"\"\n After predicting the class label of the input image, \n the prediction label and predicted diagnosis are rendered on an HTML page.\n The HTML page is fetched from the /templates directory. \n The HTML page accepts two inputs which are the predicted class and predicted diagnosis.\n \"\"\"\n return flask.render_template(\n template_name_or_list=\"prediction_result.html\",\n predicted_class=predicted_class,\n predicted_diagnosis=diagnosis[predicted_class],\n )\n else:\n # The error page is shown if file is not found\n return flask.render_template(template_name_or_list=\"error.html\")\n\n\napp.add_url_rule(rule=\"/predict/\", endpoint=\"predict\", view_func=CNN_predict)\n\n\ndef upload_image():\n \"\"\"\n Viewer function that is called in response to getting to the 'http://localhost:port/upload' URL.\n It uploads the selected image to the server.\n :return: redirects the application to a new page for predicting the class of the image.\n \"\"\"\n # Global variable to hold the name of the image file for reuse later in prediction by the 'CNN_predict' viewer functions.\n global secure_filename\n if (\n flask.request.method == \"POST\"\n ): # Checking of the HTTP method initiating the request is POST.\n img_file = flask.request.files[\n \"image_file\"\n ] # Getting the file name to get uploaded.\n secure_filename = secure_filename(\n img_file.filename\n ) # Getting a secure file name. It is a good practice to use it.\n img_path = os.path.join(\n app.root_path, secure_filename\n ) # Preparing the full path under which the image will get saved.\n img_file.save(img_path) # Saving the image in the specified path.\n print(\"Image uploaded successfully.\")\n \"\"\"\n After uploading the image file successfully, next is to predict the class label of it.\n The application will fetch the URL that is tied to the HTML page responsible for prediction and redirects the browser to it.\n The URL is fetched using the endpoint 'predict'.\n \"\"\"\n return flask.redirect(flask.url_for(endpoint=\"predict\"))\n return \"Image upload failed.\"\n\n\napp.add_url_rule(\n rule=\"/upload/\", endpoint=\"upload\", view_func=upload_image, methods=[\"POST\"]\n)\n\n\ndef redirect_upload():\n return flask.render_template(template_name_or_list=\"upload_image.html\")\n\n\napp.add_url_rule(rule=\"/\", endpoint=\"homepage\", view_func=redirect_upload)\n\n\"\"\"\nTo activate the Web server to receive requests, the application must run from the main method.\n\"\"\"\nif __name__ == \"__main__\":\n \"\"\"\n In this example, the app will run based on the following properties:\n host: localhost\n port: 5000 \n debug: flag set to True to return debugging information.\n \"\"\"\n app.run(host=\"localhost\", port=5000, debug=True)\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":3779,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"424874425","text":"#------------------------------------------------------------------------------\n# DiceProbability.py\n#\n# Simulates throwing a pair of dice many times. Calculates the relative\n# frequency of each possible sum as an approximation to the probability\n# of that sum. Calculates the theoretical probability, and the error.\n#------------------------------------------------------------------------------\n\nimport random\n\nrng = random.Random() # Create a random number generator\n\ndef throwTwoDice():\n \"\"\"\n throws two independent dice and returns the result in a 2-tuple\n \"\"\"\n die1 = rng.randrange(1,7) \n die2 = rng.randrange(1,7)\n return (die1, die2)\n# end ThrowTwoDice()\n\n\n#-- main ---------------------------------------------------------------------- \n\nnumberOfTrials = 10000\n\n\n# perform simulation, record and print frequencies\nfrequency = 13*[0] # same as [0,0,0,0,0,0,0,0,0,0,0,0,0]\nfor i in range(numberOfTrials):\n t = throwTwoDice()\n frequency[t[0]+t[1]] += 1;\n# end for\nprint()\nprint(\"Frequencies:\")\nprint(frequency)\n\n\n# calculate relative frequencies, probabilities and errors\nrelativeFrequency = [0, 0]\nprobability = [0,0]\nerror = [0,0]\nfor i in range(2, len(frequency)):\n relativeFrequency.append(frequency[i]/numberOfTrials)\n probability.append(min(i-1,13-i)/36)\n error.append(abs(probability[i]-relativeFrequency[i]))\n# end for\n\n\n#print(relativeFrequency)\n#print(probability)\n#print(error)\nprint()\n\n\n# print results\nf1 = \"{0:<10}{1:<22}{2:<22}{3:<22}\"\nf2 = 71*\"-\"\nf3 = \"{0:>3} {1:<22.15f}{2:<22.15f}{3:<.15f}\"\nprint(f1.format(\"Sum\",\"Relative Frequency\",\"Probability\",\"Error\"))\nprint(f2)\nfor i in range(2, len(frequency)):\n print(f3.format(i, relativeFrequency[i], probability[i], error[i]))\n#end for\nprint()","sub_path":"pa6/DiceProbability.py","file_name":"DiceProbability.py","file_ext":"py","file_size_in_byte":1752,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"204257794","text":"# target.py\n\nfrom graphics import *\nfrom random import randrange\n\nclass Target:\n\n def __init__(self,win):\n x1 = randrange(1, 15)\n x2 = 5\n x2 = x1 + x2\n self.rect = Rectangle(Point(x1, 2),Point(x2, 4))\n self.rect.draw(win)\n label = Text(Point(x1 + 2, 3), \"Target\")\n label.draw(win)\n\n def points(self):\n points = []\n p1 = self.rect.getP1()\n x1 = p1.getX()\n p2 = self.rect.getP2()\n x2 = p2.getX()\n for x in range(x1, x2 + 1):\n for y in range(2, 5):\n point = Point(x,y)\n points.append(point)\n return points\n","sub_path":"chapter10_target.py","file_name":"chapter10_target.py","file_ext":"py","file_size_in_byte":648,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"519382720","text":"\nfrom BanishmentBlade.printer import *\nimport sys\n\n##def playMusic(music):\n## clip = mp3play.load(r\"BanishmentBlade/music/\" + music)\n## clip.play()\n\ndef gotoWorld(world, data):\n data[\"world\"] = world\n exec (\"from BanishmentBlade.worlds import \" + \\\n data[\"world\"].replace(\" \", \"\"))\n exec (data[\"world\"].replace(\" \", \"\") + \".start(data)\")\n\ndef prompt():\n return sys.stdin.readline()\n\ndef narrateThought(text):\n texts = text.split(\"\\n\")\n for text in texts:\n if text:\n pprint(\"&& &w &@ ~ \" + text)\n else:\n print(\"\\n\")\n fprint(\"&& \")\ndef narrateVisual(text):\n texts = text.split(\"\\n\")\n for text in texts:\n if text:\n pprint(\"&& &G &@ ~ \" + text)\n else:\n print(\"\\n\")\n fprint(\"&& \")\ndef narrateObtain(itemName):\n pprint(\"&& &@ &P You obtained &Y \" + itemName + \"&P .\")\n fprint(\"&& \")\n\ndef chooserText(prompt):\n mprint(prompt)\n fprint(\"&w \")\n sep()\n value = input(\":: \")\n sep()\n\n return value\n \ndef chooserMC(title, prefix, choices):\n \"\"\" Chooser Multiple Choice \"\"\"\n mprint(title)\n sep()\n inat = -1\n for choice in choices:\n inat += 1\n nprefix = prefix.replace(\"#\", str(inat))\n if prefix:\n mprint(nprefix + choice)\n fprint(\"&w \")\n if prefix:\n sep()\n\n while(True):\n fprint(\"&w \")\n choice = input(\":: \")\n sep()\n try:\n choice = int(choice)\n if choice >= 0:\n try:\n option = choices[choice]\n break\n except:\n mprint(\"&R Please choose a number in the list.\")\n sep()\n else:\n mprint(\"&R Please type a positive number.\")\n except:\n mprint(\"&R Please type a valid number.\")\n sep()\n return choice\n\ndef chooserYN(title):\n \"\"\" Chooser Yes / No \"\"\"\n mprint(title)\n sep()\n while(True):\n fprint(\"&w \")\n choice = input(\":: \")\n choice = choice.lower()\n choice = choice.replace(\"!\", \"\")\n choice = choice.replace(\".\", \"\")\n choice = choice.replace(\"?\", \"\")\n choice = choice.replace(\"'\", \"\")\n sep()\n if choice in ('yes', 'yeah', 'sure', 'ya', 'of course', 'course',\n 'go ahead', 'whatever', 'whatev', 'yep', 'definitely',\n 'go', 'y', 'absolutely'):\n choice = True\n break\n elif choice in ('no', 'nope', 'no way', 'nah', 'definitely not',\n 'idk', 'no way man', 'idk', 'i dont know',\n 'not sure', 'dont know', 'n', 'absolutely not'):\n choice = False\n break\n else:\n mprint(\"&R It's a &P yes&R or &P no&R question.\")\n sep()\n return choice\n\ndef progress(text, beats):\n fprint(text)\n dprint(\".\" * beats, 500)\n","sub_path":"BanishmentBlade/engine.py","file_name":"engine.py","file_ext":"py","file_size_in_byte":2947,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"155751951","text":"def findMinMax(arr):\n n = len(arr)\n # n is even\n # initialize the first two elements as minimum and maximum\n if(n % 2 == 0):\n mx = max(arr[0], arr[1])\n mn = min(arr[0], arr[1])\n # set the starting index for loop\n i = 2\n # n is odd\n # initialize the first element as minimum and maximum\n else:\n mx = mn = arr[0]\n # set the starting index for loop\n i = 1\n # pick elements in pair and compare the pair with max and min\n while(i < n - 1):\n if arr[i] < arr[i + 1]:\n mx = max(mx, arr[i + 1])\n mn = min(mn, arr[i])\n else:\n mx = max(mx, arr[i])\n mn = min(mn, arr[i + 1])\n i += 2\n return (mx, mn)\n\n\nn = int(input())\narr_x = []\narr_y = []\nfor i in range(n):\n x, y = input().split()\n arr_x.append(int(x))\n arr_y.append(int(y))\nmax_x, min_x = findMinMax(arr_x)\nmax_y, min_y = findMinMax(arr_y)\nprint(\"Maximum x is: \", max_x)\nprint(\"Minimum x is: \", min_x)\nprint(\"Maximum y is: \", max_y)\nprint(\"Minimum y is: \", min_y)\n","sub_path":"project.py","file_name":"project.py","file_ext":"py","file_size_in_byte":1059,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"518197117","text":"from django.utils.deprecation import MiddlewareMixin\n\nfrom apps.contacts.models import Log\n\n\nignored_list = ['/static/', '/media/', '/favicon.ico']\n\n\nclass RequestLoggingMiddleware(MiddlewareMixin):\n def process_request(self, request):\n if request.is_ajax() or any(x in request.path for x in ignored_list):\n return\n log = Log()\n log.path = request.path\n log.method = request.method\n if request.user.is_authenticated:\n log.user = request.user\n log.browser = request.META.get('HTTP_USER_AGENT', '')\n log.save()\n","sub_path":"fortytwo_test_task/middleware.py","file_name":"middleware.py","file_ext":"py","file_size_in_byte":583,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"230503122","text":"class ESPNTeam():\r\n\t\r\n\tdef __init__(self, data):\r\n\t\tself.abbrev = data['abbrev']\r\n\t\tself.division_id = data['divisionId']\r\n\t\tself.id = data['id']\r\n\t\tif 'logo' in data.keys():\r\n\t\t\tself.logo = data['logo']\r\n\t\tself.location = data['location']\r\n\t\tself.nickname = data['nickname']\r\n\t\tself.name = '%s %s' % (self.location, self.nickname)\r\n\t\t\r\n\t\tself.playoff_seed = data['playoffSeed']\r\n\t\tself.points_for = data['points']\r\n\t\tself.points_against = data['record']['overall']['pointsAgainst']\r\n\t\tself.games_back = data['record']['overall']['gamesBack']\r\n\t\tself.losses = data['record']['overall']['losses']\r\n\t\tself.percentage = data['record']['overall']['percentage']\r\n\t\tself.streak_length = data['record']['overall']['streakLength']\r\n\t\tself.streak_type = data['record']['overall']['streakType']\r\n\t\tself.ties = data['record']['overall']['ties']\r\n\t\tself.wins = data['record']['overall']['ties']\r\n\t\tself.rank_calculated_final = data['rankCalculatedFinal']\r\n\t\t\r\n\t\tself.away_losses = data['record']['away']['losses']\r\n\t\tself.away_percentage = data['record']['away']['percentage']\r\n\t\tself.away_points_against = data['record']['away']['pointsAgainst']\r\n\t\tself.away_points_for = data['record']['away']['pointsFor']\r\n\t\tself.away_streak_length = data['record']['away']['streakLength']\r\n\t\tself.away_streak_type = data['record']['away']['streakType']\r\n\t\tself.away_ties = data['record']['away']['ties']\r\n\t\tself.away_wins = data['record']['away']['wins']\r\n\t\t\r\n\t\tself.div_losses = data['record']['division']['losses']\r\n\t\tself.div_percentage = data['record']['division']['percentage']\r\n\t\tself.div_points_against = data['record']['division']['pointsAgainst']\r\n\t\tself.div_points_for = data['record']['division']['pointsFor']\r\n\t\tself.div_streak_length = data['record']['division']['streakLength']\r\n\t\tself.div_streak_type = data['record']['division']['streakType']\r\n\t\tself.div_ties = data['record']['division']['ties']\r\n\t\tself.div_wins = data['record']['division']['wins']\r\n\t\t\r\n\t\tself.home_losses = data['record']['home']['losses']\r\n\t\tself.home_percentage = data['record']['home']['percentage']\r\n\t\tself.home_points_against = data['record']['home']['pointsAgainst']\r\n\t\tself.home_points_for = data['record']['home']['pointsFor']\r\n\t\tself.home_streak_length = data['record']['home']['streakLength']\r\n\t\tself.home_streak_type = data['record']['home']['streakType']\r\n\t\tself.home_ties = data['record']['home']['ties']\r\n\t\tself.home_wins = data['record']['home']['wins']\r\n\t\t\r\n\t\tself.faab_spent = data['transactionCounter']['acquisitionBudgetSpent']\r\n\t\tself.acquisitions = data['transactionCounter']['acquisitions']\r\n\t\tself.drops = data['transactionCounter']['drops']\r\n\t\tself.move_to_active = data['transactionCounter']['moveToActive']\r\n\t\tself.trades = data['transactionCounter']['trades']\r\n\t\tself.waiver_rank = data['waiverRank']\r\n\r\n\t\tself.schedule = []\r\n\t\tself.scores = []\r\n\t\tself.mov = []\r\n","sub_path":"fantapyfb/espnteam.py","file_name":"espnteam.py","file_ext":"py","file_size_in_byte":2852,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"61273079","text":"import sys\n# N,M = [int(n) for n in input().split()]\nN = int(input())\nS = list(input())\nst = set(S)\n# for s in S:\n# st.add(s)\nkind = len(st)\nmaxi = 0\n# print(kind)\nfor i in range(1,len(S)-1):\n # print(i)\n l = set(S[:i])\n r = set(S[i:])\n tmp = len(l&r)\n # print(tmp)\n maxi = max(tmp,maxi)\n\nprint(maxi)\n","sub_path":"problems/Beginner/B/098.py","file_name":"098.py","file_ext":"py","file_size_in_byte":323,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"409889886","text":"import numpy as np\r\n\r\nclass Node():\r\n \"\"\"Nodos para os Grafos do A* \"\"\"\r\n\r\n def __init__(self, parent=None, position=None):\r\n self.parent = parent\r\n self.position = position\r\n\r\n self.g = 0\r\n self.h = 0\r\n self.f = 0\r\n\r\n def __eq__(self, other):\r\n return self.position == other.position\r\n\r\n\r\ndef astar(maze, start, end):\r\n \"\"\"Retorna um array de tuples, representando o caminho do inicio do labirinto ate o objetivo\"\"\"\r\n\r\n # Cria os Nodos de Inicio e Fim\r\n start_node = Node(None, start)\r\n start_node.g = start_node.h = start_node.f = 0\r\n end_node = Node(None, end)\r\n end_node.g = end_node.h = end_node.f = 0\r\n\r\n # Cria a lista aberta e a lista fechada\r\n open_list = []\r\n closed_list = []\r\n\r\n # Adiciona o Nodo inicial\r\n open_list.append(start_node)\r\n\r\n # Loop até o encontrar o fim\r\n while len(open_list) > 0:\r\n\r\n # Obtem o Nodo atual\r\n current_node = open_list[0]\r\n current_index = 0\r\n for index, item in enumerate(open_list):\r\n if item.f < current_node.f:\r\n current_node = item\r\n current_index = index\r\n\r\n # Retira da lista aberta e adiciona na lista fechada\r\n open_list.pop(current_index)\r\n closed_list.append(current_node)\r\n\r\n # Encontra o objetivo\r\n if current_node == end_node:\r\n path = []\r\n current = current_node\r\n while current is not None:\r\n path.append(current.position)\r\n current = current.parent\r\n return path[::-1] # Faz o Backtracking até o nodo inicial\r\n\r\n # Cria o Filho\r\n children = []\r\n for new_position in [(0, -1), (0, 1), (-1, 0), (1, 0)]: # Vizinhos/direções\r\n\r\n # Obtém o nodo da posição atual\r\n node_position = (current_node.position[0] + new_position[0], current_node.position[1] + new_position[1])\r\n\r\n # Ctz que está no range de possibilidades\r\n if node_position[0] > (len(maze) - 1) or node_position[0] < 0 or node_position[1] > (len(maze[len(maze)-1]) -1) or node_position[1] < 0:\r\n continue\r\n\r\n # Ctz que é um caminho possivel de se fazer\r\n if maze[node_position[0]][node_position[1]] != 0:\r\n continue\r\n\r\n # Cria novo Nodo\r\n new_node = Node(current_node, node_position)\r\n\r\n # Coloca no array do filho\r\n children.append(new_node)\r\n\r\n # Loop pelo Filho\r\n for child in children:\r\n\r\n # Filho está na lista fechada\r\n for closed_child in closed_list:\r\n if child == closed_child:\r\n continue\r\n\r\n # Cria o valor das variaveis f, g e h \r\n child.g = current_node.g + 1\r\n child.h = ((child.position[0] - end_node.position[0]) **2) + ((child.position[1] - end_node.position[1]) **2)\r\n child.f = child.g + child.h\r\n\r\n # Filho na lista Aberta\r\n for open_node in open_list:\r\n if child == open_node and child.g > open_node.g:\r\n continue\r\n\r\n # Adiciona Filho na lista aberta\r\n open_list.append(child)\r\n\r\n\r\ndef main():\r\n\r\n maze = [ [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\r\n \r\n [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\r\n \r\n [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\r\n \r\n [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\r\n \r\n [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]\r\n\r\n\r\n start = (0, 0)\r\n end = (4, 1)\r\n\r\n path = astar(maze, start, end)\r\n\r\n print(path)\r\n print()\r\n\r\n print(\"Movimentos:\")\r\n print()\r\n for i in range(0, len(path)):\r\n\r\n if path[i] == end:\r\n break\r\n\r\n elif path[i][0] + 1 == path[i+1][0]:\r\n print(\"down\")\r\n\r\n elif path[i][0] - 1 == path[i+1][0]:\r\n print(\"up\")\r\n\r\n elif path[i][1] + 1 == path[i+1][1]:\r\n print(\"right\")\r\n\r\n elif path[i][1] - 1 == path[i+1][1]:\r\n print(\"left\")\r\n\r\n else:\r\n print(\"yyy\")\r\n\r\n print()\r\n print(np.matrix(maze))\r\n\r\n\r\nif __name__ == '__main__':\r\n main()","sub_path":"A_star.py","file_name":"A_star.py","file_ext":"py","file_size_in_byte":4213,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"228560165","text":"import dash_html_components as html\nimport dash_bootstrap_components as dbc\nimport pandas as pd\n\nimport plotly.graph_objects as go\n\nfrom app import app\nfrom utils.organization_chart import oc\nfrom utils.osfi_handler import oh\nfrom dash.dependencies import Input, Output\n\nfrom components.html_components import build_figure_container, build_table_container\n\n\ndef get_pie(data, column):\n fig = go.Figure(data=[go.Pie(labels=data[\"Nom du bien\"], values=data[column], hole=0.3)])\n fig.update_layout(plot_bgcolor=\"white\", template=\"plotly_white\", margin={\"t\": 30, \"r\": 30, \"l\": 30})\n return fig\n\n\ndef get_emissions_timeseries(data, column):\n biens = data[\"Nom du bien\"].unique()\n fig = go.Figure()\n for bien in biens:\n plot_data = data.loc[data[\"Nom du bien\"] == bien]\n fig.add_trace(\n go.Scatter(\n name=bien,\n x=plot_data[\"Date\"].astype(str),\n y=plot_data[column].values,\n mode=\"lines+markers\",\n line=dict(width=3),\n )\n )\n fig.update_layout(\n plot_bgcolor=\"white\", template=\"plotly_white\", margin={\"t\": 30, \"r\": 30, \"l\": 30} # , xaxis=xaxis_format\n )\n return fig\n\n\nlayout = html.Div(\n [\n dbc.Row(\n dbc.Col(\n build_table_container(title=\"Liste de biens\", id=\"osfi-all-data-table\", footer=\"Explications...\"),\n width=12,\n style={\"textAlign\": \"left\"},\n )\n ),\n dbc.Row(\n dbc.Col(\n build_figure_container(\n title=\"Emission electricité par batiment\", id=\"emission-electricity-pie\", footer=\"Explications...\"\n ),\n width=12,\n )\n ),\n dbc.Row(\n dbc.Col(\n build_figure_container(\n title=\"Emission gaz par batiment\", id=\"emission-gas-pie\", footer=\"Explications...\"\n ),\n width=12,\n )\n ),\n dbc.Row(\n dbc.Col(\n build_figure_container(\n title=\"Évolution temporelles des émissions (électricité)\",\n id=\"electricity_time_series\",\n footer=\"Explications...\",\n ),\n width=12,\n )\n ),\n dbc.Row(\n dbc.Col(\n build_figure_container(\n title=\"Évolution temporelles des émissions (gaz)\", id=\"gaz_time_series\", footer=\"Explications...\"\n ),\n width=12,\n )\n ),\n ]\n)\n\n\n@app.callback(\n [\n Output(\"osfi-all-data-table\", \"columns\"),\n Output(\"osfi-all-data-table\", \"row_selectable\"),\n Output(\"osfi-all-data-table\", \"data\"),\n ],\n [Input(\"dashboard-selected-entity\", \"children\")],\n)\ndef fill_dash_table_with_buildings(selected_entity):\n service = oc.get_entity_by_id(selected_entity)\n data = oh.get_structure_data(service.code_osfi)\n columns_to_keep = [\"Nom du bien\", \"Building type\", \"Adresse\", \"Code postal\", \"Ville\", \"Departement\"]\n columns = [{\"name\": i, \"id\": i} for i in columns_to_keep]\n row_selectable = \"multi\"\n buildings = data[columns_to_keep].drop_duplicates()\n data_to_return = buildings.to_dict(\"records\")\n return columns, row_selectable, data_to_return\n\n\n@app.callback(\n [\n Output(\"emission-electricity-pie\", \"figure\"),\n Output(\"emission-gas-pie\", \"figure\"),\n Output(\"electricity_time_series\", \"figure\"),\n Output(\"gaz_time_series\", \"figure\"),\n ],\n [\n Input(\"dashboard-selected-entity\", \"children\"),\n Input(\"osfi-all-data-table\", \"selected_rows\"),\n Input(\"osfi-all-data-table\", \"data\"),\n ],\n)\ndef update_graphs_selected(selected_entity, selected_rows, buildings):\n entity = oc.get_entity_by_id(selected_entity)\n data = oh.get_structure_data(entity.code_osfi)\n # If no rows are selected, we are displaying all of them\n # Might seem a bit conter intuitive.\n if selected_rows is None or len(selected_rows) == 0:\n data_to_display = pd.DataFrame(data)\n else:\n biens = [buildings[int(i)] for i in selected_rows]\n biens = pd.DataFrame(biens)\n codes = biens[\"Nom du bien\"]\n data_to_display = data[data[\"Nom du bien\"].isin(codes)]\n data_to_display = pd.DataFrame(data_to_display)\n electricity_pie_graph = get_pie(data_to_display, \"emission_electricity\")\n gas_pie_graph = get_pie(data_to_display, \"emission_gaz\")\n electricity_time_series = get_emissions_timeseries(data_to_display, \"emission_electricity\")\n gaz_time_series = get_emissions_timeseries(data_to_display, \"emission_gaz\")\n return electricity_pie_graph, gas_pie_graph, electricity_time_series, gaz_time_series\n","sub_path":"app/src/apps/osfi.py","file_name":"osfi.py","file_ext":"py","file_size_in_byte":4801,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"549068213","text":"# -*- coding: utf-8 -*-\nfrom redis import StrictRedis\n\nredis = StrictRedis(host='192.168.0.111',\n port=6380,\n db=0)\n\npipe = redis.pipeline()\n\npipe.zadd(\"test\", {\"demo_id\": 1578023418.658209})\n\npipe.execute()\n","sub_path":"coding/learn_redis/zadd_demo.py","file_name":"zadd_demo.py","file_ext":"py","file_size_in_byte":246,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"374717658","text":"# ==============================================================================\n# Copyright 2019 Intel Corporation\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"nGraph TensorFlow bridge Conv2d operation test\n\n\"\"\"\nimport pytest\n\nimport tensorflow as tf\nimport numpy as np\nimport os\n\nimport ngraph_bridge\n\n#Test Ngraph Op Convolution, TF Op:conv2d\n# Implemented based on NNP's unit test TEST(test_assign_layout, convolution_special_case)\n\nnp.random.seed(5)\n\n# Colvolution Op is placed on NNP and conerted to\n# bfloat16 only for the special case below, otherwise it falls\n# back to CPU for compute\n# Check to assure:\n# The input rank is 4-D\n# The stride is less than the filter size\n# The Window and Data dilation is {1,1}\n# Filter shape is allowed\n# If any fail, then we should place Op on CPU for compute\n\n#Inputs\nN = 1\nC = 1\nH = 3\nW = 5\n\nfilter_size = np.random.rand(1, 1, 1, 2)\ninput_size_nhwc = [N, H, W, C]\ninput_size_nchw = [N, C, H, W]\ninput_nhwc = tf.placeholder(tf.float32, shape=input_size_nhwc, name='x')\ninput_nchw = tf.placeholder(tf.float32, shape=input_size_nchw, name='x')\n\nn_np = np.random.rand(*input_size_nchw).astype('f')\n#Tensorflow supports only NHWC, change input shapes from NCHW to NHWC\nt_np = np.transpose(n_np, (0, 2, 3, 1))\n\n\n#TF graph\ndef tf_model():\n stride_nhwc = [1, 2, 2, 1]\n x = tf.cast(input_nhwc, dtype=tf.bfloat16)\n filter_cast = tf.cast(filter_size, dtype=tf.bfloat16)\n m = tf.nn.conv2d(\n x, filter_cast, stride_nhwc, \"SAME\", data_format=\"NHWC\", name=\"m\")\n m = tf.cast(m, dtype=tf.float32)\n return m, input_nhwc\n\n\n#Ngraph graph\ndef ng_model():\n stride_nchw = [1, 1, 2, 2]\n m = tf.nn.conv2d(\n input_nchw,\n filter_size,\n stride_nchw,\n \"SAME\",\n data_format=\"NCHW\",\n name=\"m\")\n return m, input_nchw\n\n\nconfig = tf.ConfigProto(\n allow_soft_placement=True,\n log_device_placement=False,\n inter_op_parallelism_threads=1)\n\n\ndef test_conv2d():\n #Test 1: tf_model TF-native\n with tf.Session(config=config) as sess_tf:\n ngraph_bridge.disable()\n tf_out, input_data = tf_model()\n feed_dict = {input_data: t_np}\n tf_outval = sess_tf.run(tf_out, feed_dict=feed_dict)\n\n #Test 2: model2 with ngraph, NNP backend\n with tf.Session(config=config) as sess_ng:\n ngraph_bridge.enable()\n ngraph_bridge.update_config(config)\n os.environ['NGRAPH_TF_DISABLE_DEASSIGN_CLUSTERS'] = '1'\n ng_out, input_data = ng_model()\n feed_dict = {input_data: n_np}\n ng_outval = sess_ng.run(ng_out, feed_dict=feed_dict)\n\n assert np.allclose(\n np.transpose(tf_outval, (0, 3, 1, 2)), ng_outval, rtol=0, atol=1e-02)\n","sub_path":"test/python/bfloat16/test_conv2d.py","file_name":"test_conv2d.py","file_ext":"py","file_size_in_byte":3275,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"348121280","text":"#!/usr/bin/env python\n\n# Word count reduce() function for Map/Reduce\n\nimport sys\n# Initializing variables...\nlast_key = None \nrunning_total = 0\n\n# Sequential sorting/cross-checking. Strips values and turns into \n# key/value, comparing this_key to last_key. If == value (1) is added\n# to running total, else previous running_total is output.\nfor input_line in sys.stdin:\n\tinput_line = input_line.strip()\n\tthis_key, value = input_line.split(\"\\t\", 1) \n\t#int() will convert a string to integer (this program does no error checking)\n\tvalue = int(value) \n\tif last_key == this_key: \n\t\trunning_total += value \n\telse:\n\t\t# if last key is not empty, print it with running_total...\n\t\tif last_key: \n\t\t\tprint( \"{0}\\t{1}\".format(last_key, running_total) )\n\t\t# and move on to the next key/value...\n\t\trunning_total = value \n\t\tlast_key = this_key\nif last_key == this_key:\n\tprint( \"{0}\\t{1}\".format(last_key, running_total)) ","sub_path":"wordcount_reducer.py","file_name":"wordcount_reducer.py","file_ext":"py","file_size_in_byte":944,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"398704519","text":"from selenium import webdriver\nfrom selenium.webdriver.common.keys import Keys\nfrom webdriver_manager.chrome import ChromeDriverManager\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.webdriver.common.by import By\nimport pandas as pd\nfrom time import sleep\n\nbrowser = webdriver.Chrome(executable_path=ChromeDriverManager().install())\nbrowser.get('https://google.com')\nsleep(2)\nsearch = browser.find_element_by_name('q')\nsearch.send_keys(\"Python\")\nsearch.send_keys(Keys.ENTER)\n\ndef scraper():\n results = []\n try:\n WebDriverWait(browser, 10).until(\n EC.presence_of_element_located((By.CLASS_NAME, 'g'))\n )\n except Exception as e:\n print(f\"That did not compute because: {e}\")\n print(\"Goodbye\")\n browser.quit()\n\n search_results = browser.find_elements_by_class_name('g')\n for result in search_results:\n link = result.find_element_by_css_selector('a').get_attribute('href')\n link_text = result.find_element_by_css_selector('h3').text\n description = result.find_element_by_class_name('IsZvec').text\n results.append({'link_text': link_text, 'link': link,\n 'description': description})\n return results\n# print(scraper())\npages = int(input(\"How many pages should we scrape? \"))\nall_results = []\nfor page in range(pages):\n all_results.extend(scraper())\n browser.find_element_by_link_text('Next').click()\n\nframe = pd.DataFrame(all_results)\nframe.to_csv('search_results.csv')\n\nbrowser.quit()\n\n# quit = input(\"Q to quit\").upper()\n# if quit:\n# browser.quit()","sub_path":"program_files/web_bot.py","file_name":"web_bot.py","file_ext":"py","file_size_in_byte":1655,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"534988877","text":"from compiler.ast import *\nfrom compiler.config import defaultImports\n\nclass Literal(object):\n def __init__(self, val=None, **kwargs):\n self.value = val\n self.prefix = kwargs['prefix'] if 'prefix' in kwargs else None\n self.suffix = kwargs['suffix'] if 'suffix' in kwargs else None\n self.expr = kwargs['expr'] if 'expr' in kwargs else None\n\nclass C11(object):\n def __init__(self):\n self.ident = -1\n self.loopIndex = 1\n self.src = ''\n \n def withType(self, node, _type):\n node.type = _type\n\n return node\n\n def writeln(self, line):\n self.startln()\n self.write(line)\n self.endln()\n \n def write(self, txt):\n self.src += txt\n \n def startln(self):\n self.write(self.ident * ' ')\n \n def endln(self):\n self.write('\\n')\n \n def literal(self, node):\n if isinstance(node, String):\n return '\"' + node.value.replace('\"', '\\\\\"') + '\"'\n elif isinstance(node, Boolean):\n return 'true' if node.value else 'false'\n\n return str(node.value)\n \n def render_Function(self, node, topLevel=False):\n self.startln()\n self.write(str(node.type) + ' ' + node.name + '(')\n\n for i in range(0, len(node.args)):\n arg = node.args[i]\n\n self.write(str(arg.type) + ' ' + arg.name)\n\n if i < len(node.args) - 1:\n self.write(', ')\n\n self.write(') {')\n self.endln()\n self.render_Block(node.body)\n self.writeln('}')\n \n def render_Return(self, node, topLevel=False):\n self.startln()\n self.write('return ')\n self.render_Expr(node.expr)\n self.write(';')\n self.endln()\n \n def render_If(self, node, topLevel=False):\n if topLevel:\n self.startln()\n\n if isinstance(node, If):\n self.write('if ')\n elif isinstance(node, ElseIf):\n self.write('else if ')\n elif isinstance(node, Else):\n self.write('else ')\n\n self.write('(')\n self.render_Expr(node.test)\n self.write(') {')\n self.endln()\n\n self.render_Block(node.body)\n\n if node.alternate != None:\n self.write('} ')\n self.render_If(node.alternate)\n else:\n self.writeln('}')\n\n def render_Assign(self, node, topLevel=False):\n self.startln()\n\n if not node.reassign:\n self.write(str(node.type) + ' ')\n\n self.write(node.name + ' = ')\n self.render_Expr(node.expr)\n self.write(';')\n self.endln()\n \n def render_Array(self, node, topLevel=False):\n if topLevel:\n self.startln()\n \n call = self.withType(FunctionCall(\n None,\n 'array_newIterator',\n [CallArgument(None, 0, Literal('sizeof(' + str(node.type.innerType) + '), ' + str(len(node.items))))]\n ), node.type)\n \n for item in node.items:\n call = self.withType(MethodCall(\n None,\n 'push',\n [\n CallArgument(None, 0, item.expr if node.type.innerType.pointer else self.withType(FunctionCall(\n None,\n node.type.innerType.name + '_pointer',\n [\n self.withType(CallArgument(\n None,\n 0,\n item.expr\n ), node.type.innerType)\n ],\n ), node.type.innerType))\n ],\n call\n ), node.type)\n \n if isinstance(call, FunctionCall):\n self.render_FunctionCall(call)\n else:\n self.render_MethodCall(call)\n \n if topLevel:\n self.write(';')\n self.endln()\n \n def render_MethodCall(self, node, topLevel=False):\n if topLevel:\n self.startln()\n\n self.render_FunctionCall(FunctionCall(\n None,\n node.callee.type.name + '_' + node.name,\n [CallArgument(None, -1, node.callee)] + node.args)\n )\n \n if topLevel:\n self.write(';')\n self.endln()\n \n def render_ArrayIndex(self, node, topLevel=False):\n if topLevel:\n self.startln()\n\n self.render_FunctionCall(self.withType(FunctionCall(\n None,\n node.type.name + '_constructArrayItem',\n [self.withType(CallArgument(\n None,\n 0,\n self.withType(FunctionCall(\n None,\n 'array_getByIndex',\n [\n self.withType(CallArgument(None, 0, node.expr), node.expr.type),\n self.withType(CallArgument(None, 1, node.indexExpr), node.indexExpr.type)\n ]\n ), node.type)\n ), None)]\n ), node.type))\n\n if topLevel:\n self.endln()\n \n def render_Expr(self, node, topLevel=False):\n if topLevel:\n self.startln()\n\n if isinstance(node, Literal):\n if node.prefix != None:\n self.write(node.prefix)\n \n if node.value != None:\n self.write(self.literal(node))\n elif node.expr != None:\n self.render_Expr(node.expr)\n \n if node.suffix != None:\n self.write(node.suffix)\n \n return\n elif isinstance(node, String):\n return self.render_FunctionCall(self.withType(FunctionCall(\n None,\n 'string_new',\n [self.withType(CallArgument(\n None,\n 0,\n Literal(self.literal(node))\n ), node.type)]\n ), node.type))\n elif isinstance(node, Number) or \\\n isinstance(node, Boolean):\n return self.write(self.literal(node))\n elif isinstance(node, FunctionCall):\n return self.render_FunctionCall(node)\n elif isinstance(node, Variable):\n return self.render_Variable(node)\n elif isinstance(node, Array):\n return self.render_Array(node)\n elif isinstance(node, MethodCall):\n return self.render_MethodCall(node)\n elif isinstance(node, ArrayIndex):\n return self.render_ArrayIndex(node)\n elif isinstance(node, LogicalExpr):\n self.render_Expr(node.left)\n self.write(' ' + {\n 'and': '&&',\n 'or': '||'\n }[node.op.value] + ' ')\n return self.render_Expr(node.right)\n elif not isinstance(node, BinaryExpr):\n raise Exception('Unknown AST node ' + repr(node))\n \n self.render_FunctionCall(self.withType(FunctionCall(\n None,\n node.left.type.name + '_' + node.op.functionName,\n [\n self.withType(CallArgument(None, 0, node.left), node.left.type),\n self.withType(CallArgument(None, 1, node.right), node.right.type)\n ]\n ), node.type))\n\n if topLevel:\n self.endln()\n \n def render_FunctionCall(self, node, topLevel=False):\n if topLevel:\n self.startln()\n\n self.write(node.name + '(')\n\n for i in range(0, len(node.args)):\n self.render_Expr(node.args[i].expr)\n\n if i < len(node.args) - 1:\n self.write(', ')\n \n self.write(')')\n\n if topLevel:\n self.write(';')\n self.endln()\n \n def render_Variable(self, node, topLevel=False):\n self.write(node.value)\n \n def render_ForEach(self, node, topLevel=False):\n iteratorKey = '$eachIterator_' + str(self.loopIndex)\n\n self.render_Assign(self.withType(Assign(None, iteratorKey, node.iterable), node.iterable.type))\n self.writeln('while (' + node.iterable.type.name + '_iterate(' + iteratorKey + ')) {')\n self.ident += 1\n self.render_Assign(self.withType(Assign(\n None,\n node.key,\n self.withType(FunctionCall(\n None,\n node.iterable.type.innerType.name + '_constructArrayItem',\n [self.withType(CallArgument(\n None,\n 0,\n self.withType(FunctionCall(\n None,\n 'array_getCurrent',\n [\n self.withType(CallArgument(\n None,\n 0,\n self.withType(Variable(\n None,\n iteratorKey\n ), None)\n ), node.iterable.type)\n ]\n ), node.iterable.type.innerType)\n ), None)]\n ), node.iterable.type.innerType)\n ), node.iterable.type.innerType))\n self.ident -= 1\n self.render_Block(node.body)\n self.writeln('}')\n\n self.loopIndex += 1\n\n def render_Import(self, node, topLevel=False):\n self.writeln('#include <' + node.name + '.h>')\n \n def render_Block(self, node, topLevel=False):\n self.ident += 1\n\n for child in node.body:\n method = getattr(self, 'render_' + child.__class__.__name__)\n method(child, True)\n \n self.ident -= 1\n\n def renderHeader(self):\n # Enable C99 support for booleans\n self.render_Import(Import(None, 'stdbool'))\n\n # Auto-import default libraries\n for name in defaultImports:\n self.render_Import(Import(None, name))\n\n self.endln()\n\n def render(self, node):\n self.renderHeader()\n self.render_Block(node)\n\n return self.src","sub_path":"src/compiler/clang/codegen/c11.py","file_name":"c11.py","file_ext":"py","file_size_in_byte":10090,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"600416189","text":"from itertools import islice, count\nfrom primes import getprimesieve\nfrom util import gcd\n\ndef A(n):\n m = 1\n for i in range(2,n+2):\n m = (10*m+1) % n\n if not m: return i\n return -1\n\nP = sorted({i for i,v in enumerate(getprimesieve(10**6)) if v})\n\n# For all primes p>5, p-1 is divisible by A(p) (as per problem 130 def)\n# Therefore, if A(p) divides 10**9, it is a subset of 2**9 and 5**9,\n# So gcd(p-1, 10**9) still contains whole A(p), and\n# 10^gcd(10**9, p-1)-1 is divisible by p, i.e. 10^gcd(10**9, p-1)%p == 1\nprint(sum(islice((p for p in P[3:10**6] if pow(10,gcd(10**9, p-1),p) == 1), 0, 40)))\n\n# Original brute force\n#print(sum(islice((p for p in P[3:10**6] if gcd(p-1, 10**9) > 1 and 10**9 % A(p) == 0), 0, 40)))\n","sub_path":"p132.py","file_name":"p132.py","file_ext":"py","file_size_in_byte":742,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"403658851","text":"\n#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Jul 27 11:52:34 2018\n\n@author: yusu\n\"\"\"\n\nfrom keras.datasets import mnist\n#import matplotlib\n#%matplotlib inline\n#import matplotlib.pyplot as plt\n#import l2_attack\nimport keras\nimport tensorflow as tf\nimport time\nfrom torch.autograd import Variable\nimport torch\nimport numpy as np\nfrom wrapper import Model\n\ntorch.set_printoptions(precision=20)\nclass blackbox:\n def __init__(self,model):\n self.model = model\n \n def attack_untargeted(self, x0, y0, alpha = 4, beta = 0.005, iterations = 1000):\n \"\"\" Attack the original image and return adversarial example\n model: (pytorch model)\n alpha: learning rate \n beta: learning rate\n train_dataset: set of training data\n (x0, y0): original image\n \"\"\"\n pred = self.model.predict(x0)\n print(\"predicted label:\", pred)\n print(\"true label:\", y0)\n\n if (self.model.predict(x0) != y0):\n print(\"Fail to classify the image. No need to attack.\")\n return x0,0\n \n num_directions = 1000\n num_query = 10\n best_theta, g_theta = None, float('inf')\n query_count = 0\n comp_theta = 0\n current_best = float('inf')\n \n timestart = time.time()\n for i in range(num_directions):\n theta = torch.randn(x0.shape).type(torch.FloatTensor)\n initial_lbd = torch.norm(theta)\n theta = theta/torch.norm(theta)\n if self.model.predict(x0+np.array(initial_lbd*theta)) != y0:\n lbd,comp_dec = self.fine_grained_binary_search_fix(x0,y0,theta,initial_lbd,current_best,num_query,1e-5)\n if comp_dec > comp_theta:\n comp_theta = comp_dec\n best_theta,g_theta = theta,lbd\n print(\"--------> Found abs-distortion %.4f with 10 queries\" % g_theta)\n print(\"--------> Found comp-distortion %.4f with 10 queries\" % comp_dec)\n timeend = time.time()\n print(\"==========> Found best distortion %.4f in %.4f seconds\" % (g_theta, timeend-timestart))\n query_count = (num_directions+1)*num_query\n #print(\"type of best_theta\", type(best_theta))\n #print(\"type of best_theta\", type(g_theta))\n lbd,count = self.fine_grained_binary_search( x0, y0, best_theta, g_theta, current_best)\n g_theta = lbd\n query_count += count\n \n# timestart = time.time()\n# for i in range(num_directions):\n# theta = torch.randn(x0.shape).type(torch.FloatTensor)\n# #print(theta.size())\n# initial_lbd = torch.norm(theta)\n# theta = theta/torch.norm(theta)\n# if self.model.predict(x0+np.array(initial_lbd*theta)) != y0:\n# query_count += 1 \n# #print(type(theta),type(initial_lbd),type(g_theta))\n# #print(\"find a new adv direction, new label:\", self.model.predict(x0+np.array(initial_lbd*theta)))\n# lbd, count = self.fine_grained_binary_search( x0, y0, theta, initial_lbd, g_theta)\n# query_count += count\n# if lbd < g_theta:\n# best_theta, g_theta = theta,lbd\n## print(\"label for random direction:\",self.model.predict(x0+np.array(g_theta*best_theta)))\n# print(\"--------> Found distortion %.4f\" % g_theta)\n# \n# timeend = time.time()\n# print(\"==========> Found best distortion %.4f in %.4f seconds using %d queries\" % (g_theta, timeend-timestart, query_count))\n \n \n \n \n \n g1 = 1.0\n theta, g2 = best_theta.clone(), g_theta\n torch.manual_seed(0)\n opt_count = 0\n stopping = 0.01\n prev_obj = 100000\n for i in range(iterations):\n \n if g_theta < 2:\n print(\"====================query number after distortion < 2 =======================: \",opt_count)\n break\n gradient = torch.zeros(theta.size())\n q = 10\n min_g1 = float('inf')\n for j in range(q):\n u = torch.randn(theta.size()).type(torch.FloatTensor)\n u = u/torch.norm(u)\n ttt = theta+beta * u\n ttt = ttt/torch.norm(ttt)\n #print(\"inner loop iteration: \", j)\n g1, count = self.fine_grained_binary_search_local( x0, y0, ttt, initial_lbd = g2, tol=beta/500)\n opt_count += count\n gradient += (g1-g2)/beta * u\n if g1 < min_g1:\n min_g1 = g1\n min_ttt = ttt\n gradient = 1.0/q * gradient\n# print(\"=============================================\")\n \n if (i+1)%50 == 0:\n \n print(\"Iteration %3d: g(theta + beta*u) = %.4f g(theta) = %.4f distortion %.4f num_queries %d\" % (i+1, g1, g2, torch.norm(g2*theta), opt_count))\n if g2 > prev_obj-stopping:\n break\n prev_obj = g2\n \n min_theta = theta\n min_g2 = g2\n \n\n for _ in range(15):\n new_theta = theta - alpha * gradient\n new_theta = new_theta/torch.norm(new_theta)\n new_g2, count = self.fine_grained_binary_search_local( x0, y0, new_theta, initial_lbd = min_g2, tol=beta/50)\n opt_count += count\n alpha = alpha * 2\n# print(\"alpha in the first for loop is: \",alpha)\n if new_g2 < min_g2:\n min_theta = new_theta \n min_g2 = new_g2\n else:\n break\n# print(\"=============================================\")\n \n if min_g2 >= g2:\n for _ in range(15):\n alpha = alpha * 0.25\n new_theta = theta - alpha * gradient\n new_theta = new_theta/torch.norm(new_theta)\n new_g2, count = self.fine_grained_binary_search_local( x0, y0, new_theta, initial_lbd = min_g2, tol=beta/50)\n opt_count += count\n# print(\"alpha in the second for loop is: \",alpha)\n if new_g2 < g2:\n min_theta = new_theta \n min_g2 = new_g2\n break\n# print(\"=============================================\")\n if min_g2 <= min_g1:\n theta, g2 = min_theta, min_g2\n else:\n theta, g2 = min_ttt, min_g1\n \n if g2 < g_theta:\n best_theta, g_theta = theta.clone(), g2\n \n #print(alpha)\n# print(\"%3d th iteration\" % i)\n# print(\"current alpha:\",alpha)\n# print(\"g_theta\")\n# print(\"number of queries:\", opt_count+query_count)\n if alpha < 1e-6:\n alpha = 1.0\n print(\"Warning: not moving, g2 %lf gtheta %lf\" % (g2, g_theta))\n beta = beta * 0.1\n if (beta < 1e-6):\n print(\"beta is too samll\")\n break\n\n \n #target = model.predict(x0 + g_theta*best_theta)\n \n #print(\"\\nAdversarial Example Found Successfully: distortion %.4f target %d queries %d \\nTime: %.4f seconds\" % (g_theta, target, query_count + opt_count, timeend-timestart))\n print(\"mnist_baseline\")\n print(\"best distortion :\", g_theta)\n print(\"number of queries :\", opt_count+query_count)\n return np.array(g_theta*best_theta), opt_count+query_count\n def fine_grained_binary_search_local(self, x0, y0, theta, initial_lbd = 1.0, tol=1e-5):\n nquery = 0\n lbd = initial_lbd\n \n if self.model.predict(x0+np.array(lbd*theta)) == y0:\n lbd_lo = lbd\n lbd_hi = lbd*1.01\n nquery += 1\n #timestart1 = time.time()\n while self.model.predict(x0+np.array(lbd_hi*theta)) == y0:\n lbd_hi = lbd_hi*1.01\n nquery += 1\n if lbd_hi > 20:\n return float('inf'), nquery\n\n else:\n lbd_hi = lbd\n lbd_lo = lbd*0.99\n nquery += 1\n #timestart2 = time.time()\n while self.model.predict(x0+ np.array(lbd_lo*theta)) != y0 :\n lbd_lo = lbd_lo*0.99\n nquery += 1\n\n while (lbd_hi - lbd_lo) > tol:\n lbd_mid = (lbd_lo + lbd_hi)/2.0\n nquery += 1\n if self.model.predict(x0 + np.array(lbd_mid*theta)) != y0:\n lbd_hi = lbd_mid\n else:\n lbd_lo = lbd_mid\n return lbd_hi, nquery\n \n def fine_grained_binary_search_fix(self,x0,y0,theta, initial_lbd = 1.0, current_best = float('inf'),num_query = 10, tol=1e-5):\n nquery = 0\n if initial_lbd > current_best: \n if self.model.predict(x0+ np.array(current_best*theta)) == y0:\n nquery += 1\n return float('inf'), nquery\n lbd = current_best\n else:\n lbd = initial_lbd\n \n lbd_hi = lbd\n lbd_lo = 0.0\n \n while (lbd_hi - lbd_lo) > tol:\n lbd_mid = (lbd_lo + lbd_hi)/2.0\n nquery += 1\n if self.model.predict(x0 + np.array(lbd_mid*theta)) != y0:\n lbd_hi = lbd_mid\n else:\n lbd_lo = lbd_mid\n if nquery > num_query:\n break\n comp_dec = (initial_lbd - lbd_hi)/initial_lbd\n # print(\"number of query before return for this direction:\",nquery)\n return lbd_hi,comp_dec,\n \n def fine_grained_binary_search(self, x0, y0, theta, initial_lbd, current_best):\n nquery = 0\n if initial_lbd > current_best: \n if self.model.predict(x0+ np.array(current_best*theta)) == y0:\n nquery += 1\n #print(\"initial_lbd > current_best & predict == y0, so return inf\")\n return float('inf'), nquery\n lbd = current_best\n else:\n lbd = initial_lbd\n \n\n lbd_hi = lbd\n lbd_lo = 0\n print(\"label before fine binary search:\", self.model.predict(x0+ np.array(lbd_hi*theta)))\n \n while (lbd_hi - lbd_lo) > 1e-5:\n lbd_mid = (lbd_lo + lbd_hi)/2.0\n nquery += 1\n if self.model.predict(x0 + np.array(lbd_mid*theta)) != y0:\n lbd_hi = lbd_mid\n else:\n lbd_lo = lbd_mid\n #print(\"find a better initialization\")\n return lbd_hi, nquery\n \n\n \n\n\nsession = keras.backend.get_session()\nkeras.backend.set_learning_phase(False)\nmodel = keras.models.load_model(\"data/mnist\")\nmodel = Model(model,[0.0,1.0])\n\nattack = blackbox(model)\n\n#touse = [x for x in tf.trainable_variables() if 'Generator' in x.name]\n#saver = tf.train.Saver(touse)\n#saver.restore(session, 'data/mnist-gan')\n\n(x_train, y_train), (x_test, y_test) = mnist.load_data()\nx_test = np.array(x_test, dtype=np.float32)\nx_test = x_test.reshape(x_test.shape[0], 28, 28, 1)\nx_test /= 255.0\n#image = x_test[:1]\n#adv = attack.attack_untargeted(image[0],y_test[0], alpha = 4, beta = 0.005, iterations = 1000)\ncount = []\nfor i in range(20):\n label = model.predict(x_test[i])\n if label == y_test[i]:\n count.append(1)\n else:\n count.append(0)\n \nprint(\"accuracy of this model is:\", sum(count)/len(count))\n\n\ndist = []\ncount = []\nfor i in range(15):\n print(\"=========================image \",i+1,\"==========================================\")\n print(\"true label:\",y_test[i])\n print(\"predicted label:\",model.predict(x_test[i]))\n adv_mod, queries= attack.attack_untargeted(x_test[i],y_test[i], alpha = 4, beta = 0.005, iterations = 1000)\n dist.append(np.linalg.norm(adv_mod))\n count.append(queries)\n\nindex = np.nonzero(count)\nindex = list(index)[0].tolist()\n\navg_distortion = np.mean(np.array(dist)[index])\navg_count = np.mean(np.array(count)[index])\nprint(\"the average distortion for %2d images :\"%(len(index)),avg_distortion)\nfor i in dist:\n print(i)\nprint(\"the number of queries for %2d images :\"%(len(index)), avg_count)\nfor j in count:\n print(j)\n\n\n\n\n\n","sub_path":"baseline_mnist/attack_mnist.py","file_name":"attack_mnist.py","file_ext":"py","file_size_in_byte":12321,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"79532156","text":"import os\nfrom datetime import datetime\n\nfrom django.conf import settings\nfrom django.contrib.auth.models import User\nfrom django.core.files.base import ContentFile\nfrom django.db import models\nfrom django.dispatch import receiver\n\nimport requests\nfrom caching.base import CachingManager, CachingMixin\nfrom funfactory.helpers import static\nfrom requests.exceptions import RequestException\nfrom tower import ugettext as _, ugettext_lazy as _lazy\n\nfrom flicks.base.util import get_object_or_none\nfrom flicks.videos import vimeo\nfrom flicks.videos.tasks import process_deletion\nfrom flicks.videos.util import (send_approval_email, vidly_embed_code,\n vimeo_embed_code)\n\n\nclass Video2013(models.Model, CachingMixin):\n title = models.CharField(max_length=255, blank=False)\n description = models.TextField(blank=True)\n user = models.ForeignKey(User)\n created = models.DateTimeField(default=datetime.now)\n random_ordering = models.IntegerField(default=0)\n\n vimeo_id = models.IntegerField()\n filename = models.CharField(max_length=255, blank=False)\n\n approved = models.BooleanField(default=False)\n processed = models.BooleanField(default=False)\n user_notified = models.BooleanField(default=False)\n\n voters = models.ManyToManyField(User, through='Vote',\n related_name='voted_videos')\n\n def _thumbnail_path(self, filename):\n root, ext = os.path.splitext(filename)\n return 'vimeo_thumbs/{0}{1}'.format(self.vimeo_id, ext)\n thumbnail = models.ImageField(blank=True, upload_to=_thumbnail_path,\n max_length=settings.MAX_FILEPATH_LENGTH)\n\n objects = CachingManager()\n\n @property\n def region(self):\n return self.user.userprofile.region\n\n @property\n def thumbnail_url(self):\n return (self.thumbnail.url if self.thumbnail else\n static('img/video-blank.jpg'))\n\n @property\n def vote_count(self):\n return self.voters.count()\n\n def save(self, *args, **kwargs):\n \"\"\"\n Prior to saving, trigger approval processing if approval status has\n changed.\n \"\"\"\n original = get_object_or_none(Video2013, id=self.id)\n\n # Only process approval if the value changed.\n if original and original.approved != self.approved:\n self.process_approval()\n\n # Save after processing to prevent making the video public until\n # processing is complete.\n return_value = super(Video2013, self).save(*args, **kwargs)\n\n # Send an email out if the user hasn't been notified and re-save.\n # Don't send an email out if this is a new, already-approved video.\n if original and self.approved and not self.user_notified:\n send_approval_email(self)\n self.user_notified = True\n return_value = super(Video2013, self).save(*args, **kwargs)\n\n return return_value\n\n def embed_html(self, **kwargs):\n \"\"\"Return the HTML code to embed this video.\"\"\"\n return vimeo_embed_code(self.vimeo_id, **kwargs)\n\n def process_approval(self):\n \"\"\"Update privacy and gather more metadata based on approval status.\"\"\"\n if self.approved:\n # Fetch the medium-sized thumbail from Vimeo. If it isn't available,\n # ignore and continue; a default thumbnail will be used.\n try:\n self.download_thumbnail(commit=False)\n except (RequestException, vimeo.VimeoServiceError):\n pass\n\n vimeo.set_privacy(self.vimeo_id, 'anybody')\n else:\n vimeo.set_privacy(self.vimeo_id, 'password',\n password=settings.VIMEO_VIDEO_PASSWORD)\n\n def download_thumbnail(self, commit=True):\n \"\"\"Download the thumbnail for the given video and save it.\"\"\"\n thumbnails = vimeo.get_thumbnail_urls(self.vimeo_id)\n try:\n thumbnail = next(t for t in thumbnails if t['height'] == '150')\n except StopIteration:\n raise vimeo.VimeoServiceError('No medium thumbnail found.')\n\n response = requests.get(thumbnail['_content'])\n\n filename = response.url.rsplit('/')[-1]\n content_file = ContentFile(response.content)\n self.thumbnail.save(filename, content_file, save=False)\n\n if commit:\n self.save()\n\n def has_vote_from(self, user):\n \"\"\"Check if the given user has voted for this video.\"\"\"\n return (user.is_authenticated() and\n self.voters.filter(pk=user.pk).exists())\n\n def __unicode__(self):\n profile = self.user.profile\n name = profile.display_name if profile else self.user.email\n return u'`{0}` - {1}'.format(self.title, name)\n\n\n@receiver(models.signals.post_delete, sender=Video2013)\ndef remove_video(sender, **kwargs):\n \"\"\"\n Remove the deleted video from vimeo and notify the user that it has been\n declined.\n \"\"\"\n video = kwargs['instance']\n process_deletion.delay(video.vimeo_id, video.user.id)\n\n\n# Assign the alias \"Video\" to the model for the current year's contest.\nVideo = Video2013\n\n\nclass Vote(models.Model, CachingMixin):\n \"\"\"A vote from a user for a specific video.\"\"\"\n user = models.ForeignKey(User)\n video = models.ForeignKey(Video2013)\n\n created = models.DateTimeField(default=datetime.now)\n\n objects = CachingManager()\n\n class Meta:\n unique_together = ('user', 'video')\n\n\n### 2012 Models ###\n\n# Untranslated as they're only seen in the admin interface.\nSTATE_CHOICES = (\n ('unsent', 'Unsent'),\n ('processing', 'Processing'),\n ('complete', 'Complete'),\n ('error', 'Error')\n)\n\nCATEGORY_CHOICES = (\n ('thirty_spot', _lazy(':30 Spot')),\n ('animation', _lazy('Animation')),\n ('new_technology', _lazy('New Technology')),\n ('psa', _lazy('PSA'))\n)\n\nREGION_CHOICES = (\n ('america', _lazy('North America')),\n ('latin_america', _lazy('Latin America')),\n ('europe', _lazy('Europe')),\n ('asia_africa_australia', _lazy('Asia, Africa & Australia'))\n)\n\n# Untranslated as they're only seen in the admin interface.\nAWARD_TYPE_CHOICES = (\n ('grand_winner', 'Grand Prize Winner'),\n ('category_winner', 'Category Winner'),\n ('runner_up', 'Runner Up'),\n ('panavision', 'Panavision Prize'),\n ('bavc', 'Bay Area Video Coalition')\n)\n\nWINNER_CATEGORY_TEXT = {\n 'thirty_spot': _lazy('30 Second Spot Winner'),\n 'animation': _lazy('Animation Winner'),\n 'new_technology': _lazy('New Technology Winner'),\n 'psa': _lazy('PSA Winner')\n}\n\n\nclass Video2012(models.Model, CachingMixin):\n # L10n: Title refers to the title of a video.\n title = models.CharField(max_length=100, blank=False,\n verbose_name=_lazy(u'Title'))\n description = models.TextField(blank=True,\n verbose_name=_lazy(u'Description'))\n\n user_name = models.CharField(max_length=100, blank=False,\n default='')\n user_email = models.EmailField(blank=True)\n user_country = models.CharField(max_length=100, blank=True)\n\n category = models.CharField(max_length=50, blank=False,\n choices=CATEGORY_CHOICES,\n verbose_name=_lazy(u'Category'))\n region = models.CharField(max_length=50, blank=False,\n choices=REGION_CHOICES,\n verbose_name=_lazy(u'Region'))\n created = models.DateTimeField(default=datetime.now)\n\n upload_url = models.URLField(verify_exists=False, blank=False, default='',\n verbose_name=_lazy(u'Video File URL'))\n shortlink = models.CharField(max_length=32, blank=True)\n state = models.CharField(max_length=10, choices=STATE_CHOICES,\n default='unsent')\n\n votes = models.BigIntegerField(default=0)\n views = models.BigIntegerField(default=0)\n bitly_link_db = models.URLField(verify_exists=False, blank=True, default='',\n verbose_name=u'Saved sharing link (mzl.la)')\n\n judge_mark = models.BooleanField(default=False,\n verbose_name=u'Marked for judges')\n\n objects = CachingManager()\n\n def embed_html(self, width=600, height=337):\n \"\"\"Return the escaped HTML code to embed this video.\"\"\"\n return vidly_embed_code(self.shortlink, width=width, height=height)\n\n @property\n def is_winner(self):\n \"\"\"Return true if this video won an award.\"\"\"\n return Award.objects.filter(video=self).exists()\n\n def __unicode__(self):\n return '%s: %s %s' % (self.id, self.shortlink, self.title)\n\n\nclass Award(models.Model, CachingMixin):\n \"\"\"Model for contest winners.\"\"\"\n video = models.ForeignKey(Video2012, blank=True, null=True)\n preview = models.ImageField(blank=True, upload_to=settings.PREVIEW_PATH,\n max_length=settings.MAX_FILEPATH_LENGTH)\n category = models.CharField(max_length=50, blank=True,\n choices=CATEGORY_CHOICES,\n verbose_name=_lazy(u'Category'))\n region = models.CharField(max_length=50, blank=True,\n choices=REGION_CHOICES,\n verbose_name=_lazy(u'Region'))\n award_type = models.CharField(max_length=50, blank=False,\n choices=AWARD_TYPE_CHOICES)\n\n objects = CachingManager()\n\n @property\n def award_title(self):\n if self.award_type == 'grand_winner':\n return _('%(winner)s for %(region)s') % {\n 'winner': _('Grand Prize Winner'),\n 'region': self.get_region_display()\n }\n elif self.award_type == 'bavc':\n return _('Bay Area Video Coalition Prize Winner')\n elif self.award_type == 'panavision':\n return _('Panavision Prize Winner')\n else:\n return _('%(winner)s for %(region)s') % {\n 'winner': unicode(WINNER_CATEGORY_TEXT[self.category]),\n 'region': self.get_region_display()\n }\n\n @property\n def video_title(self):\n if self.video is None:\n return 'Video Title'\n else:\n return self.video.title\n\n @property\n def video_href(self):\n if self.video is None:\n return '#'\n else:\n return self.video.details_href\n\n @property\n def video_preview(self):\n if not self.preview:\n return '{0}img/promo-twilight.jpg'.format(settings.MEDIA_URL)\n else:\n return self.preview.url\n\n @property\n def submitter_name(self):\n if self.video is None:\n return 'Submitter Name'\n else:\n return self.video.user.userprofile.full_name\n\n @property\n def submitter_country(self):\n if self.video is None:\n return 'Submitter Country'\n else:\n return self.video.user.userprofile.country\n","sub_path":"flicks/videos/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":11044,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"132685884","text":"from django.contrib.auth import authenticate, login \nfrom django.contrib.auth.decorators import login_required\nfrom django.contrib.auth.mixins import LoginRequiredMixin\nfrom django.http import HttpResponse\nfrom django.shortcuts import render\nfrom django.views.generic import DetailView\n\nfrom .forms import LoginForm, UserRegistrationForm, UserEditForm, ProfileEditForm\nfrom .models import Profile\n\n\n\nclass ProfileView(LoginRequiredMixin, DetailView):\n\tmodel = Profile\n\ttemplate_name = 'account/profile_detail.html'\n\n\n\ndef user_login(request):\n\tif request.method == 'POST':\n\t\tform = LoginForm(request.POST)\n\t\tif form.is_valid():\n\t\t\tcd = form.cleaned_data\n\t\t\tuser = authenticate(username=cd['username'],\n\t\t\t\t\t\t\t\tpassword=cd['password'])\n\t\t\tif user is not None:\n\t\t\t\tif user.is_active:\n\t\t\t\t\tlogin(request, user)\n\t\t\t\t\treturn HttpResponse('Authentication succeeded')\n\t\t\t\telse:\n\t\t\t\t\treturn HttpResponse('Account is blocked')\n\t\t\telse:\n\t\t\t\treturn HttpResponse('Wrong authentication data')\n\telse:\n\t\tform = LoginForm()\n\treturn render(request, 'account/login.html', {'form' : form})\n\n\n\ndef register(request):\n\tif request.method == 'POST':\n\t\tuser_form = UserRegistrationForm(request.POST) \n\t\tif user_form.is_valid():\n\t\t\tnew_user = user_form.save(commit=False)\n\t\t\t# Set given password\n\t\t\tnew_user.set_password(user_form.cleaned_data['password'])\n\t\t\tnew_user.save()\n\t\t\tprofile = Profile.objects.create(user=new_user)\n\t\t\treturn render(request, 'account/register_done.html', { 'new_user' : new_user })\n\telse:\n\t\tuser_form = UserRegistrationForm()\n\treturn render(request, 'account/register.html', { 'user_form': user_form })\n\n\n@login_required\ndef edit(request):\n\tif request.method == 'POST':\n\t\tuser_form = UserEditForm(instance=request.user,\n\t\t\t\t\t\t\t\t data=request.POST)\n\t\tprofile_form = ProfileEditForm(instance=request.user.profile,\n\t\t\t\t\t\t\t\t\t data=request.POST,\n\t\t\t\t\t\t\t\t\t files=request.FILES)\n\t\tif user_form.is_valid() and profile_form.is_valid():\n\t\t\tuser_form.save()\n\t\t\tprofile_form.save()\n\telse:\n\t\tuser_form = UserEditForm(instance=request.user)\n\t\tprofile_form = ProfileEditForm(instance=request.user.profile)\n\treturn render(request, 'account/edit.html', { 'user_form' : user_form,\n\t\t\t\t\t\t\t\t \t\t\t\t 'profile_form' : profile_form })\n\n\n\n\n\n\n\n\n\n\n\n# TEST VIEW\ndef test_home(request):\n\treturn render(request, 'account/test_home.html', {})\n","sub_path":"deadlinekiller/account/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2319,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"11817279","text":"import os\nimport yaml\nfrom os.path import join\nimport inspect\nimport glob\nimport re\n\ncurrentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))\nwith open(join(currentdir, 'config.yaml'), 'r') as f:\n cfg = yaml.load(f)\n\nmodel = cfg['os_odom_test']['model']\ndataset_type = cfg['os_odom_test']['dataset']\ndata_dir = cfg['os_odom_test']['saved_dir_h5']\nIMU_LENGTH = str(cfg['os_odom_test']['imu_length'])\nn_mixture = str(cfg['os_odom_test']['n_mixture'])\ntest_dir = str(cfg['os_odom_test']['test_dir'])\n\ntest_files = glob.glob(join(data_dir, test_dir, '*.h5'))\nprint(test_files)\n\nseqs = [re.search(dataset_type + '_seq_(.+?).h5', file).group(1) for file in test_files]\n\n\nprint('Test Model {}'.format(model))\n# model_dir = join('./models', model)\n# max_epochs = max([int(x) for x in os.listdir(model_dir) if str.isdigit(x[0])])\n# epochs = [str(r) for r in range(0, max_epochs + 25, 25)]\nepochs = [] # if you just want the best\nepochs.append('best')\nprint(epochs)\n\nfor seq in seqs:\n for epoch in epochs:\n print(epoch)\n cmd = 'python -W ignore ' + 'utility/test_deeptio_prob.py' + ' ' + '--seq ' + str(seq) + ' ' + '--model ' + \\\n model + ' --epoch ' + epoch + ' ' + '--data_dir ' + data_dir + ' ' + '--imu_length ' + IMU_LENGTH + \\\n ' ' + '--data_type ' + dataset_type + ' ' + '--n_mixture ' + n_mixture + ' ' + '--test_dir ' + test_dir\n print(cmd)\n os.system(cmd)","sub_path":"Python/odometry/os_test_odom.py","file_name":"os_test_odom.py","file_ext":"py","file_size_in_byte":1444,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"178223268","text":"#!/usr/bin/python3\n# Copyright 2023 Google LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n################################################################################\nimport sys\nfrom enum import IntEnum\n\nimport atheris\n\nwith atheris.instrument_imports(include=[\"pyvex\"]):\n import pyvex\n\n# Additional imports\nimport archinfo\nfrom contextlib import contextmanager\nfrom io import StringIO\n\nfrom enhanced_fdp import EnhancedFuzzedDataProvider\n\n\n@contextmanager\ndef nostdout():\n saved_stdout = sys.stdout\n saved_stderr = sys.stderr\n sys.stdout = StringIO()\n sys.stderr = StringIO()\n yield\n sys.stdout = saved_stdout\n sys.stderr = saved_stderr\n\n\n# Save all available architectures off\navailable_archs = [tup[3]() for tup in archinfo.arch.arch_id_map if len(tup) >= 3]\n\n\nclass SupportedOptLevels(IntEnum):\n StrictUnopt = -1\n Unopt = 0\n Opt = 1\n StrictOpt = 2\n\n\ndef consume_random_arch(fdp: atheris.FuzzedDataProvider) -> archinfo.Arch:\n return fdp.PickValueInList(available_archs)\n\n\ndef TestOneInput(data: bytes):\n fdp = EnhancedFuzzedDataProvider(data)\n\n arch = consume_random_arch(fdp)\n\n try:\n with nostdout():\n data = fdp.ConsumeRandomBytes()\n\n irsb = pyvex.lift(\n data,\n fdp.ConsumeInt(arch.bits),\n arch,\n max_bytes=fdp.ConsumeIntInRange(0, len(data)),\n max_inst=fdp.ConsumeInt(16),\n bytes_offset=fdp.ConsumeIntInRange(0, len(data)),\n opt_level=fdp.PickValueInEnum(SupportedOptLevels)\n )\n irsb.pp()\n except pyvex.PyVEXError:\n return -1\n except OverflowError:\n return -1\n\n\ndef main():\n atheris.Setup(sys.argv, TestOneInput)\n atheris.Fuzz()\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"projects/pyvex/irsb_fuzzer.py","file_name":"irsb_fuzzer.py","file_ext":"py","file_size_in_byte":2316,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"503058239","text":"import setup\nimport queries.mongodb as mongo_queries\nimport queries.mysql as mysql_queries\nimport os, pwd\nimport json\nimport shutil\nfrom pprint import pprint\nfrom pymongo import errors as mongoerrors\n\n\n\n# ! REMOTE MONGO DATABASE\nserver_mongo = {\n 'alias':'core',\n 'db':'ai_pipeline',\n 'name':'ai_pipeline',\n 'host':'10.180.129.185',\n 'port':27017\n}\n\n# ! LOCAL MONGO DATABASE\nlocal_mongo = {\n 'alias':'core',\n 'name':'ai_pipeline',\n 'db':'ai_pipeline',\n 'host':'localhost',\n 'port':27017\n}\n\n# ! REMOTE MYSQL DATABASE\nserver_mysql = {\n 'host':'10.180.129.185',\n 'user':'root',\n 'password':'robotics',\n 'database':'labelingtool'\n}\n\n# ! LOCAL MYSQL DATABASE\nserver_mysql = {\n 'host':'localhost',\n 'user':'root',\n 'password':'robotics',\n 'database':'labelingtool'\n}\n\n# mydb = setup.mongo_connection(local_mongo) # connection to the database\n\n\n\n# ! ########## TEST TICKETS HERE ############\ndef main():\n# setup.mongo_connection(local_mongo) # connection to the database\n\n # * ADD NEW CLASSES\n # new_classes = ['container', 'assemply_shelf', 'train_shelf', 'dolly', 'wheel', 'cagebox', 'pallet', 'gripping_area']\n # if len(new_classes) > 0:\n # for new_class in new_classes:\n # add_new_class(new_class)\n # * FIND CLASS BY NAME\n # class_name = 'container'\n # find_class_by_name(class_name)\n # * ADD NEW IMAGES\n # name = \"another new image\"\n # ext = \"jpeg\"\n # path = \"home\"\n # width = 600\n # height = 600\n # plant = \"munich\"\n # datasets = [\"dataset-2018\"]\n # usecases = [\"splitbot\", \"placebot\"]\n # upload_new_image(name, ext, path, width, height, plant, list(datasets), list(usecases))\n # ! upload from local folder\n local_pc_home = pwd.getpwuid(os.getuid()).pw_dir\n db_pc_home = '/home/robotics'\n dataset = ['placebot_detection_top1000']\n x = -1 # if -1 all files will be copied\n label_extension = 'json'\n usecases = ['placebot']\n upload_new_dataset(mydb, local_pc_home, db_pc_home, dataset, x, label_extension, usecases)\n # * FIND IMAGES BY PLANT\n # plant_name = 'munich'\n # find_images_by_plant(plant_name)\n # * CREATE A NEW TRAINING\n # create_training()\n # * FIND MODEL BY NAME\n # * default model is yolo_default\n # model_name = 'yolo_default'\n # find_model_by_name()\n # * FIND PLANT BY NAME\n# plant_name = 'munich'\n# find_plant_by_name(plant_name)\n # * CREATE A NEW USECASE\n # usecase_names = ['splitbot', 'placebot', 'sortbot', 'pickbot']\n # for usecase_name in usecase_names:\n # create_new_usecase(usecase_name)\n # ! CREATE NEW DATASET\n# dataset_name = 'new-dataset-2018'\n# plants = ['munich']\n# usecases = ['splitbot', 'placebot']\n# tags = []\n# create_new_dataset(dataset_name, plants, usecases, tags)\n # ! check for duplicate before upload\n # check_if_exists('images','filename', 'qqqqqqqqqqqqq')\n\n print(\"Main is running\")\n\n\n\n\n# ! ########## TICKETS ############\n\n# CREATE A TRAINING\ndef create_training():\n\n # ! Dummy values\n\n name = \"Faster RCNN\"\n mongo_queries.create_training(name)\n\n# UPLOAD NEW IMAGES\ndef upload_new_image(name, ext, path, width, height, plant, datasets, usecases, groundtruth, detections):\n mongo_queries.upload_new_image(name, ext, path, width, height, plant, datasets, usecases, groundtruth, detections)\n\n\n# RETRIEVE DEFAULT MODEL SETTINGS\ndef find_model_by_name(model_name):\n model = mongo_queries.find_model_by_name(model_name)\n\n if model:\n print(model.checkpoint_name)\n\n\ndef find_plant_by_name(plant_name):\n plant = mongo_queries.find_plant_by_name(plant_name)\n print(type(plant))\n if plant:\n print(plant.name, plant.id)\n else:\n print(\"No plant was found\")\n\n\ndef add_new_class(new_class):\n mongo_queries.add_new_class(new_class)\n\n\ndef find_class_by_name(class_name):\n object_class = mongo_queries.find_class_by_name(class_name)\n if object_class:\n print(object_class.id)\n else:\n print(\"No class was found\")\n\n\ndef find_images_by_plant(plant_name):\n images = mongo_queries.find_images_by_plant(plant_name)\n for image in images:\n print(image.filename, image.id)\n\n\ndef create_new_usecase(usecase_name):\n mongo_queries.create_new_usecase(usecase_name)\n\n\ndef find_images_by_usecase(usecase_name):\n images = mongo_queries.find_images_by_usecase(usecase_name)\n for image in images:\n print(image.filename, image.id)\n\n\ndef create_new_dataset(dataset_name, plants, usecases, tags):\n mongo_queries.create_new_dataset(dataset_name, plants, usecases, tags)\n\n# ! for leo's dataset\ndef plant_from_image_name(image_name):\n plant = image_name.split('_')[0]\n if plant == 'muc':\n return 'munich'\n elif plant == 'rburg':\n return 'regensburg'\n\n\ndef upload_new_dataset(mydb, local_pc_home, db_pc_home, dataset, x, label_ext, usecases):\n\n dataset_local_dir = os.path.join(local_pc_home, \"Nextcloud/Deep-Learning/Datasets\", dataset[0])\n database_local_dir = os.path.join(local_pc_home, \"Nextcloud/Deep-Learning/Database\")\n database_remote_dir = os.path.join(db_pc_home, \"Nextcloud/Deep-Learning/Database\")\n\n images_dataset_local = os.path.join(dataset_local_dir, 'images')\n images_database_local = os.path.join(database_local_dir, 'images')\n images_database_remote = os.path.join(database_remote_dir, 'images')\n\n labels_dataset_local = os.path.join(dataset_local_dir, label_ext)\n labels_database_local = os.path.join(database_local_dir, 'labels')\n labels_database_remote = os.path.join(database_remote_dir, 'labels')\n\n image_list = sorted(os.listdir(images_dataset_local))\n classes_file = os.path.join(dataset_local_dir, 'classes.txt')\n\n with open(classes_file, 'r') as f:\n classes = [x.replace('\\n', '').lower() for x in f.read().splitlines(True)]\n print(classes)\n f.close()\n\n for i, image in enumerate(image_list):\n if i == x:\n break\n else:\n image_name, image_ext = os.path.splitext(image)\n image_ext = image_ext.replace('.', '')\n label = image_name + '.' + label_ext\n\n print(i, image_name, image_ext, label)\n\n label_path = os.path.join(labels_dataset_local, label)\n image_path = os.path.join(images_dataset_local, image)\n\n if (os.path.isfile(label_path)):\n # read json file\n data = json.load(open(label_path))\n # retrieve data\n width = int(data['image'][0]['width'])\n height = int(data['image'][0]['height'])\n remote_path = os.path.join(images_database_remote, image)\n local_path = os.path.join(images_database_local, image)\n\n plant = plant_from_image_name(image_name) # ! USe only for leo's dataset\n\n labels = data['objects']\n\n groundtruth = []\n if len(labels) != 0:\n for label in labels:\n # pprint(label)\n print(label['type'])\n gt_label = {\n 'abs_height':label['height'],\n 'abs_width':label['width'],\n 'abs_x_min':label['left'],\n 'abs_y_min':label['top'],\n 'object_class_id':classes[int(label['type'])]\n }\n groundtruth.append(gt_label)\n\n # upload images and labels to mongodb\n upload_doc(image_name, image_ext, remote_path, width, height, plant, dataset, usecases, groundtruth)\n if (local_pc_home == db_pc_home):\n copy_file(image_path, remote_path)\n else:\n copy_file(image_path, local_path)\n # copy_file(image_path, local_path)\n\n\n\ndef upload_doc(iname, iext, ipath, iwidth, iheight, plant, datasets, usecases, gtdata, detections=None):\n\n query_plant = mydb.plants.find({'name':plant})\n plant_id = query_plant[0]['_id']\n\n usecase_ids = []\n for usecase in usecases:\n query_usecase = mydb.usecases.find({'name':usecase})\n usecase_ids.append(query_usecase[0]['_id'])\n dataset_ids = []\n for dataset in datasets:\n query_dataset = mydb.datasets.find({'name':dataset})\n # print(query_dataset[0])\n dataset_ids.append(query_dataset[0]['_id'])\n currentdoc = {\n 'filename': iname,\n 'extension': iext,\n 'path': ipath,\n 'width': iwidth,\n 'height': iheight,\n 'plant_id': plant_id,\n 'usecase_ids': usecase_ids,\n 'dataset_ids': dataset_ids,\n 'ground_truth': gtdata,\n 'detections': detections\n }\n\n # pprint(currentdoc)\n\n try:\n mydb.images.insert(currentdoc)\n except mongoerrors.PyMongoError as e:\n print(e)\n\n\n\ndef copy_file(path_to_file, new_path_to_file):\n\n if (os.path.isfile(path_to_file)):\n if (os.path.isfile(new_path_to_file)):\n print(\"File already exists\")\n else:\n shutil.copyfile(path_to_file, new_path_to_file)\n\n\ndef check_if_exists(collection, field, value):\n # ! seems like we have to use .createIndex method and then insert the document\n doc = {\n field:value\n }\n\n\n mydb[collection].create_index(field, unique=True)\n mydb[collection].insert(doc)\n # .update({field:value},{field:value},upsert=True)\n\n\n\n# def create_new_dataset()\n\n\n\n###########################################\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"ai_pipeline_main/webui/server/program.py","file_name":"program.py","file_ext":"py","file_size_in_byte":9598,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"554091326","text":"import tensorflow as tf\nimport keras\nimport bert\nfrom bert import BertModelLayer\nfrom bert.loader import StockBertConfig, map_stock_config_to_params, load_stock_weights\nimport os\n\ndirname = os.path.dirname(__file__)\nBERT_MODEL_NAME = \"uncased_L-12_H-768_A-12\"\nbert_ckpt_dir = os.path.join(dirname, \"models/uncased_L-12_H-768_A-12\")\nBERT_CKPT_FILE = os.path.join(bert_ckpt_dir, \"bert_model.ckpt\")\nbert_config_file = os.path.join(bert_ckpt_dir, \"bert_config.json\")\n\n\ndef create_model(max_seq_len, num_classes, bert_ckpt_file = BERT_CKPT_FILE):\n with tf.io.gfile.GFile(bert_config_file, \"r\") as reader:\n bc = StockBertConfig.from_json_string(reader.read())\n bert_params = map_stock_config_to_params(bc)\n bert_params.adapter_size = None\n bert = BertModelLayer.from_params(bert_params, name=\"bert\")\n\n input_ids = keras.layers.Input(shape=(max_seq_len,), dtype='int32', name=\"input_ids\")\n bert_output = bert(input_ids)\n\n print(\"bert shape\", bert_output.shape)\n cls_out = keras.layers.Lambda(lambda seq: seq[:, 0, :])(bert_output)\n cls_out = keras.layers.Dropout(0.5)(cls_out)\n logits = keras.layers.Dense(units=1024, activation=\"tanh\")(cls_out)\n logits = keras.layers.Dropout(0.2)(logits)\n logits = keras.layers.Dense(units=num_classes, activation=\"softmax\")(logits)\n\n model = keras.Model(inputs=input_ids, outputs=logits)\n model.build(input_shape=(None, max_seq_len))\n\n load_stock_weights(bert, bert_ckpt_file)\n\n return model\n\n","sub_path":"BERT/build_model.py","file_name":"build_model.py","file_ext":"py","file_size_in_byte":1489,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"469584003","text":"#!/usr/bin/evn python\n# -*- coding:utf-8 -*-\n# ----------------------\n# File name: decodeXml.py\n# decode xml file of Pascal Voc annotation\n# Writen by wangtf\n# ----------------------\n\nimport os\n\ntry:\n import xml.etree.cElementTree as ET\nexcept ImportError:\n import xml.etree.ElementTree as ET\nimport sys\n\nclass XmlReader():\n def __init__(self, xml_file_path):\n self.tree = None\n self.root = None\n self.rewrite = False\n self.file_path = xml_file_path\n self.getRoot()\n\n def getRoot(self):\n self.tree = ET.parse(self.file_path) #打开xml文档\n self.root = self.tree.getroot() #获得root节点\n\n def getFileName(slef):\n print(\"*\"*10)\n filename = self.root.find('filename').text\n filename = filename[:-4]\n print(filename)\n\n def getWidthandHeight(self):\n for size in self.root.findall('size'): # 找到root节点下的size节点\n width = size.find('width').text # 子节点下节点width的值\n height = size.find('height').text # 子节点下节点height的值\n print(width, height)\n\n def getObjectList(self):\n obj_list = {}\n for object in self.root.findall('object'):\n name = self.getObjectName(object)\n if name not in obj_list:\n obj_list[name] = 1\n else:\n obj_list[name] += 1\n return obj_list\n\n def getObjectName(sefl, object):\n name = object.find('name').text\n # print('Object name is :{}'.format(name))\n return name\n \n def setObjectName(self, old_name, new_name):\n for object in self.root.findall('object'):\n name = self.getObjectName(object)\n if name is old_name:\n object.find('name').text = new_name\n self.rewrite = True\n if self.rewrite is True:\n self.rewriteXml()\n print('Rerite xml: {}'.format(self.file_path))\n \n def rewriteXml(self):\n self.tree.write(self.file_path)\n \n def getObjectBndbox(self, object):\n bndbox = object.find('bndbox') #子节点下属性bndbox的值\n xmin = bndbox.find('xmin').text\n ymin = bndbox.find('ymin').text\n xmax = bndbox.find('xmax').text\n ymax = bndbox.find('ymax').text\n print('Bndbox: xmin-{}, ymin-{}, xmax-{}, ymax-{}'.format(xmin, ymin, xmax, ymax))\n return([xmin, ymin, xmax, ymax])\n","sub_path":"decodeXml.py","file_name":"decodeXml.py","file_ext":"py","file_size_in_byte":2458,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"543756491","text":"\r\n\"\"\" we are making the iterator function \"\"\"\r\n\"\"\"\r\nclass MY_RANGE:\r\n def __init__(self,start,end):\r\n self.value=start\r\n self.end=end\r\n def __iter__(self):\r\n return self\r\n def __next__(self):\r\n if self.value >=self.end:\r\n raise StopIteration\r\n current=self.value\r\n self.value +=1\r\n return current\r\n\r\nnums=MY_RANGE(1,10)\"\"\"\r\n\r\n\r\n\"\"\"by gererator function\r\n\"\"\"\r\n#def my_range(start,end):\r\ndef my_range(start):\r\n current=start\r\n# while current <=end\r\n while True:\r\n#\r\n yield current\r\n current += 1\r\n \r\nnums=my_range(1)\r\n\r\nfor i in nums:\r\n print(i)\r\n\r\n\r\nfor num in test:\r\n print(num)\r\n\"\"\"\r\n\r\nprint(next(nums))\r\nprint(next(nums)) \r\nprint(next(nums))\r\n\"\"\"\r\n","sub_path":"pack1/iterable&iterator.py","file_name":"iterable&iterator.py","file_ext":"py","file_size_in_byte":761,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"25179644","text":"import requests\nimport json\nimport pprint\n\nclass Client(object):\n def __init__(self, username, password):\n self.uname = username\n self.pw = password\n self.version_header = {\"Accept\": \"application/vnd.bugcrowd.v2+json\"}\n\n def list_bounties(self):\n r = self.get('bounties')\n j = json.loads(r.text)\n\n bounties = []\n for each in j['bounties']:\n bounties.append(Bounty(each))\n\n return bounties\n\n def get_bounty(self, bounty_id):\n r = self.get('bounties/' + bounty_id)\n j = json.loads(r.text)\n\n return Bounty(j['bounty'])\n\n def get_submission(self, submission_id):\n r = self.get('submissions/' + submission_id)\n j = json.loads(r.text)\n\n return Submission(j['submission'])\n\n def get_submissions_for_bounty(self, bounty_uuid, assignment=None, filter=None, search=None, sort=None):\n payload = {}\n if assignment is not None:\n payload['assignment'] = assignment\n if filter is not None:\n payload['filter'] = filter\n if search is not None:\n payload['search'] = search\n if sort is not None:\n payload['sort'] = sort\n\n r = self.get('bounties/' + bounty_uuid + '/submissions', params=payload)\n j = json.loads(r.text)\n \n submissions = []\n for each in j['submissions']:\n submissions.append(Submission(each))\n\n return submissions\n\n # TODO Add code for create submission once API is correct\n\n def update_submission(self, submission_uuid, title=None, internal_bug_type=None, custom_fields=None):\n payload = {}\n if title is not None:\n payload['title'] = title\n if internal_bug_type is not None:\n payload['internal_bug_type'] = internal_bug_type\n if custom_fields is not None:\n payload['custom_fields'] = custom_fields\n\n self.put('submissions/' + submission_uuid, json=payload)\n\n return self.get_submission(submission_uuid)\n\n def update_priority_on_submission(self, submission_uuid, level):\n current_priority = self.get_submission(submission_uuid).priority\n \n if current_priority == None: # Set\n self.post('submissions/' + submission_uuid + '/priority', json={'priority': {'level': level}})\n elif current_priority: # Update\n self.put('submissions/' + submission_uuid + '/priority', json={'priority': {'level': level}})\n elif level == None: # Delete\n self.delete('submissions/' + submission_uuid + '/priority')\n\n return level\n\n def get_comments_for_submission(self, submission_uuid):\n r = self.get('submissions/' + submission_uuid + '/comments')\n return r\n\n def add_comment_to_submission(self, submission_uuid, type, body):\n r = self.post('submissions/' + submission_uuid + '/comments', json={'comment': {'type': type, 'body': body}})\n return r\n\n def get_custom_fields_for_bounty(self, bounty_uuid):\n r = self.get('bounties/' + bounty_uuid + '/custom_field_labels')\n return r\n\n def create_custom_field_for_bounty(self, bounty_uuid, field_name):\n r = self.post('bounties/' + bounty_uuid + '/custom_field_labels', json={'field_name': field_name})\n\n return r\n\n def update_custom_field_label_for_bounty(self, bounty_uuid, field_id, new_label):\n r = self.put('bounties/' + bounty_uuid + '/custom_field_labels/' + field_id, json={'field_name': new_label})\n\n return r\n\n def delete_custom_field_for_bounty(self, bounty_uuid, field_id):\n r = self.delete('bounties/' + bounty_uuid + '/custom_field_labels/' + field_id)\n\n return r\n\n # Utility Methods\n\n def delete(self, path):\n r = requests.delete('https://api.bugcrowd.com/' + path, auth=(self.uname, self.pw),\n headers=self.version_header)\n\n if r.status_code is not 200:\n raise ApiException(r.text)\n\n return r\n\n def put(self, path, json=None):\n r = requests.put('https://api.bugcrowd.com/' + path, auth=(self.uname, self.pw),\n headers=self.version_header, json=json)\n\n if r.status_code is not 200:\n raise ApiException(r.text)\n\n return r\n\n def post(self, path, json=None):\n r = requests.post('https://api.bugcrowd.com/' + path, auth=(self.uname, self.pw),\n headers=self.version_header, json=json)\n if r.status_code is not 201:\n raise ApiException(r.text)\n\n return r\n\n def get(self, path, params=None):\n r = requests.get('https://api.bugcrowd.com/' + path, auth=(self.uname, self.pw),\n headers=self.version_header, params=params)\n\n if r.status_code is not 200:\n raise ApiException(r.text)\n\n return r\n\n\nclass Bounty(object):\n def __init__(self, j):\n self.__dict__ = j\n\n def __repr__(self):\n \treturn pprint.pformat(vars(self))\n\n\nclass Submission(object):\n def __init__(self, j):\n self.__dict__ = j\n\n def __repr__(self):\n \treturn pprint.pformat(vars(self))\n\nclass ApiException(Exception):\n def __init__(self, message):\n self.message = message\n","sub_path":"bugcrowd/bugcrowd.py","file_name":"bugcrowd.py","file_ext":"py","file_size_in_byte":5268,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"54175739","text":"import os\nimport sqlite3\nfrom time import time\n\nimport pandas as pd\nimport numpy as np\n\nfrom pandas import Series\nfrom pandas import ExcelWriter\n\nfrom mpi4py import MPI\n\nfrom ChemHammer import ChemHammer\n\ncomm = MPI.COMM_WORLD\nrank = comm.Get_rank()\nroot = 0\n\ndef split_indices(input_array):\n comm = MPI.COMM_WORLD\n rank = comm.Get_rank() # If using MPI\n num_processes = comm.size\n\n if rank == 0: # First rank splits the files up\n indexes = np.arange(len(input_array))\n np.random.shuffle(indexes)\n splits = np.array_split(indexes, num_processes)\n else: # All other processes\n splits = []\n\n # wait for process 0 to get the filepaths/splits and broadcast these\n comm.Barrier()\n splits = comm.bcast(splits, root=0)\n my_indexes = splits[comm.rank]\n # take only filepaths for our rank\n my_array = [input_array[x] for x in my_indexes]\n return my_array, my_indexes\n\ntime_start = time()\n\nionic_db_dir = \"/home/cameron/Dropbox/University/PhD/ionic_db_labelled_ICSD.xlsx\"\ncif_db_dir = \"/home/cameron/Dropbox/University/PhD/cif.db\"\ndb = pd.read_excel(ionic_db_dir)\nconn = sqlite3.connect(cif_db_dir)\ncursor = conn.cursor()\n\n# take all li compounds\nsql_query = 'select formula, icsd_code from data where formula like \"%Ca%\"'\ncursor.execute(f'{sql_query}')\nresult = cursor.fetchall()\n\n# Add a new column for predicted ICSD codes\ncompounds = db['Compound Formula']\nmy_compounds, my_splits = split_indices(compounds)\n\nchecked = db['Confirmed Y/N']\nmy_checked = checked[my_splits]\n\nstrings = []\n\nprint(\"Enttering main loop\")\ntested_indices = []\n\nfor i, compound in enumerate(my_compounds):\n compound = \"Li1.69Na0.14(Al1.83Si4.17O12)\" # Just for quick tests, comment out\n comp = ChemHammer(compound)\n tested_results = []\n\n for x in result:\n try:\n tested_results.append((comp.levenshtein_dist(x[0]), x[1]))\n\n except:\n pass\n\n # sort on similarity score\n sorted_result = sorted(tested_results, key = lambda x : x[0])\n top_ten = sorted_result[:10]\n string_to_write = f\"For compound {compound} the top ten closest matches are:\\n\"\n\n # Add each of the closest matches\n for j, icsd_code in enumerate(top_ten):\n cursor.execute(f'select formula from data where icsd_code like \"%{icsd_code[1]}%\"')\n if j == 0:\n db.loc[j, 'Predicted ICSD'] = icsd_code[1]\n db.loc[j, 'Predicted ICSD Formula'] = cursor.fetchall()[0][0]\n cursor.execute(f'select formula from data where icsd_code like \"%{icsd_code[1]}%\"')\n print_string = f\"{icsd_code[1]} : {cursor.fetchall()[0][0]} with distance {icsd_code[0]}\"\n string_to_write += print_string + \"\\n\"\n\n strings.append(string_to_write)\n\n# Once each process has tested theirs send back to root and write to file\nsendcounts = np.array(comm.gather(len(strings), root))\n\nif rank == root:\n stringbuf = np.empty(sum(sendcounts), dtype=int)\n indexbuf = np.empty(sum(sendcounts), dtype=int)\nelse:\n stringbuf = None\n indexbuf = None\n\ncomm.Gatherv(sendbuf=strings, recvbuf=(stringbuf, sendcounts), root=root)\ncomm.Gatherv(sendbuf=my_splits, recvbuf=(indexbuf, sendcounts), root=root)\n\nprint(\"Got to this bit!\")\nprint(len(my_splits))\n\n# Append to dataframe and save excel\ndb.loc[i, 'Potential ICSD'] = string_to_write\n\nif i % 5 == 0:\n print(f\"{i/len(db) * 100}% complete\")\n\nwriter = ExcelWriter('PythonExport.xlsx')\ndb.to_excel(writer, 'Sheet1')\nwriter.save()\n\nprint(f\"Time taken: {time_start - time()}\")\n\n","sub_path":"test_db.py","file_name":"test_db.py","file_ext":"py","file_size_in_byte":3539,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"526389258","text":"import json\nimport boto3\nimport os\nimport math\nimport random\nfrom jmpy.dynamodb import DynamoDB\nfrom jmpy.alphavantage import AlphaVantage\nfrom jmpy.logger import MyLogger\n\ndef lambda_handler(event, context):\n\n def handle_messages(messages):\n '''\n Routine for handling a list of messages\n (even though the boto3 returns a singleton list)\n '''\n for message in messages:\n\n # use this to delete message later\n receipt_handle = message['ReceiptHandle']\n\n try:\n # main message handling routine\n \n body = json.loads(message['Body'])\n symbol = body['symbol']\n process_symbol(symbol)\n\n except:\n # if it failed\n logger.catch_exception(exc_note=symbol)\n\n finally:\n # delete it from original queue regardless\n sqs.delete_message(QueueUrl=daily_queue_url,ReceiptHandle=receipt_handle)\n\n def process_symbol(symbol):\n\n '''\n Routine for processing a single symbol\n '''\n\n\n # get the last object for the symbol\n query = db.query('Price',filter='symbol = :s',values = {\":s\" : symbol},limit=1,ascending=False)\n\n try:\n # query returns a generator so, check it like this\n last_obj = next(query)\n\n except StopIteration:\n # if none in db, put historic in db\n queue_historic(symbol)\n\n else:\n # get data from alpha vantage\n data = av.historic(symbol)\n\n # only insert new ones\n to_insert = [x for x in data if x['date'] > last_obj['date']]\n\n if split_or_div(to_insert):\n # if split or div, need to update adj_close\n queue_historic(symbol)\n else:\n # otherwise, just insert the new data\n db.bulk_insert('Price',to_insert)\n\n # done!\n logger.info('Done: {}'.format(symbol))\n\n\n def queue_historic(symbol):\n\n # write the message\n msg = json.dumps({'symbol':symbol})\n\n # get sqs client\n sqs = boto3.client('sqs')\n\n # send message\n sqs.send_message(\n QueueUrl=historic_queue_url,\n MessageBody=msg\n )\n\n def split_or_div(_data):\n\n needs_update = lambda x: not (math.isclose(float(x['split']), 1.0) and math.isclose(float(x['dividend']), 0.0))\n\n return any([needs_update(x) for x in _data])\n\n def repopulate_daily_queue():\n\n def randord(myiterable):\n ret = list(myiterable).copy()\n random.shuffle(ret)\n return ret\n\n sqs = boto3.client('sqs')\n scan_res = db.scan(table='Stock',pages=5000)\n for res in randord(scan_res):\n msg = json.dumps({'symbol':res['symbol']})\n sqs.send_message(\n QueueUrl=daily_queue_url,\n MessageBody=msg\n )\n \n\n # /_\\ tag\n daily_queue_url = os.environ.get('daily_queue')\n historic_queue_url = os.environ.get('historic_queue')\n api_key = os.environ.get('api_key')\n \n av = AlphaVantage(api_key)\n db = DynamoDB()\n sqs = boto3.client('sqs')\n logger = MyLogger()\n\n sqs_response = sqs.receive_message(QueueUrl=daily_queue_url)\n messages = sqs_response.get('Messages',[])\n logger.info('{} messages found.'.format(len(messages)))\n\n if messages:\n # if not an empty list, process them\n handle_messages(messages)\n\n else:\n # otherwise, need to repopulate SQS\n repopulate_daily_queue()\n\n\n logger.info('Routine done.')\n \n return {\n 'statusCode': 200,\n 'body': json.dumps('Hello from Lambda!')\n }\n","sub_path":"terraform/price-keepers/daily-price-python/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3763,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"264832139","text":"\n\nfrom xai.brain.wordbase.nouns._stipend import _STIPEND\n\n#calss header\nclass _STIPENDS(_STIPEND, ):\n\tdef __init__(self,): \n\t\t_STIPEND.__init__(self)\n\t\tself.name = \"STIPENDS\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"stipend\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_stipends.py","file_name":"_stipends.py","file_ext":"py","file_size_in_byte":245,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"623897488","text":"\"\"\"Parse a device config file.\"\"\"\nimport inspect\nimport sys\nimport typing\nfrom io import BytesIO\nfrom pathlib import Path\nfrom textwrap import dedent\n\nfrom flowchem.devices.flowchem_device import FlowchemDevice\nfrom flowchem.devices.list_known_device_type import autodiscover_device_classes\n\nif sys.version_info >= (3, 11):\n # noinspection PyUnresolvedReferences\n import tomllib\nelse:\n import tomli as tomllib\n\nfrom flowchem.devices.known_plugins import plugin_devices\nfrom flowchem.utils.exceptions import InvalidConfiguration\nfrom loguru import logger\n\n\ndef parse_toml(stream: typing.BinaryIO) -> dict:\n \"\"\"\n Read the TOML configuration file and returns it as a dict.\n\n Extensive exception handling due to the error-prone human editing needed in the configuration file.\n \"\"\"\n try:\n return tomllib.load(stream)\n except tomllib.TOMLDecodeError as parser_error:\n logger.exception(parser_error)\n raise InvalidConfiguration(\n \"The configuration provided does not contain valid TOML!\"\n ) from parser_error\n\n\ndef parse_config(file_path: BytesIO | Path) -> dict:\n \"\"\"Parse a config file.\"\"\"\n # StringIO used for testing without creating actual files\n if isinstance(file_path, BytesIO):\n config = parse_toml(file_path)\n config[\"filename\"] = \"StringIO\"\n else:\n assert (\n file_path.exists() and file_path.is_file()\n ), f\"{file_path} is a valid file\"\n\n with file_path.open(\"rb\") as stream:\n config = parse_toml(stream)\n\n config[\"filename\"] = file_path.stem\n\n return instantiate_device(config)\n\n\ndef instantiate_device(config: dict) -> dict:\n \"\"\"Instantiate all devices defined in the provided config dict.\"\"\"\n assert \"device\" in config, \"The configuration file must include a device section\"\n\n # device_mapper is a dict mapping device type (str, as key) with the device class (obj, value).\n # e.g. device_mapper[\"Spinsolve\"] = Spinsolve class\n device_mapper = autodiscover_device_classes()\n\n # Iterate on all devices, parse device-specific settings and instantiate the relevant objects\n config[\"device\"] = [\n parse_device(dev_settings, device_mapper)\n for dev_settings in config[\"device\"].items()\n ]\n logger.info(\"Configuration parsed!\")\n\n return config\n\n\ndef parse_device(dev_settings, device_object_mapper) -> FlowchemDevice:\n \"\"\"\n Parse device config and return a device object.\n\n Exception handling to provide more specific and diagnostic messages upon errors in the configuration file.\n \"\"\"\n device_name, device_config = dev_settings\n\n # Get device class\n try:\n obj_type = device_object_mapper[device_config[\"type\"]]\n del device_config[\"type\"]\n except KeyError as error:\n # If the device type specified is supported via a plugin we know of, alert user\n if device_config[\"type\"] in plugin_devices:\n needed_plugin = plugin_devices[device_config[\"type\"]]\n logger.exception(\n f\"The device `{device_name}` of type `{device_config['type']}` needs a additional plugin\"\n f\"Install {needed_plugin} to add support for it!\"\n f\"e.g. `python -m pip install {needed_plugin}`\"\n )\n raise InvalidConfiguration(f\"{needed_plugin} not installed.\")\n\n logger.exception(\n f\"Device type `{device_config['type']}` unknown in 'device.{device_name}'!\"\n f\"[Known types: {device_object_mapper.keys()}]\"\n )\n raise InvalidConfiguration(\n f\"Unknown device type `{device_config['type']}`.\"\n ) from error\n\n # If the object has a 'from_config' method, use that for instantiation, otherwise try straight with the constructor.\n try:\n if hasattr(obj_type, \"from_config\"):\n called = obj_type.from_config\n device = obj_type.from_config(**device_config, name=device_name)\n else:\n called = obj_type.__init__\n device = obj_type(**device_config, name=device_name)\n except TypeError as error:\n logger.error(f\"Wrong settings for device '{device_name}'!\")\n get_helpful_error_message(device_config, inspect.getfullargspec(called))\n raise ConnectionError(\n f\"Wrong configuration provided for device '{device_name}' of type {obj_type.__name__}!\\n\"\n f\"Configuration: {device_config}\\n\"\n f\"Accepted parameters: {inspect.getfullargspec(called).args}\"\n ) from error\n\n logger.debug(\n f\"Created device '{device.name}' instance: {device.__class__.__name__}\"\n )\n return device\n\n\ndef get_helpful_error_message(called_with: dict, arg_spec: inspect.FullArgSpec):\n \"\"\"Give helpful debugging text on configuration errors.\"\"\"\n # First check if we have provided an argument that is not supported.\n # Clearly no **kwargs should be defined in the signature otherwise all kwargs are ok\n if arg_spec.varkw is None:\n invalid_parameters = list(set(called_with.keys()).difference(arg_spec.args))\n if invalid_parameters:\n logger.error(\n f\"The following parameters were not recognized: {invalid_parameters}\"\n )\n\n # Then check if a mandatory arguments was not satisfied. [1 to skip cls/self, -n to remove args w/ default]\n num_default = 0 if arg_spec.defaults is None else len(arg_spec.defaults)\n mandatory_args = arg_spec.args[1:-num_default]\n missing_parameters = list(set(mandatory_args).difference(called_with.keys()))\n if missing_parameters:\n logger.error(\n f\"The following mandatory parameters were missing in the configuration: {missing_parameters}\"\n )\n\n\nif __name__ == \"__main__\":\n cfg_txt = BytesIO(\n dedent(\n \"\"\"config_version = \"1.0\"\n simulation = true\n\n [device.donor]\n type = \"Elite11InfuseOnly\"\n port = \"COM11\"\n address = 0\n syringe_diameter = \"4.6 mm\"\n syringe_volume = \"1 ml\"\n\n [device.activator]\n type = \"Elite11InfuseOnly\"\n port = \"COM11\"\n address= 1\n syringe_diameter = \"4.6 mm\"\n syringe_volume = \"1 ml\"\n\n [device.quencher]\n type = \"AxuraCompactPump\"\n mac_address = \"00:80:A3:BA:C3:4A\"\n max_pressure = \"13 bar\"\n\n [device.sample-loop]\n type = \"ViciValve\"\n port = \"COM13\"\n address = 0\n\n [device.chiller]\n type = \"HubeerChiller\"\n port = \"COM3\"\n \"\"\"\n ).encode(\"utf-8\")\n )\n cfg = parse_config(cfg_txt)\n print(cfg)\n","sub_path":"src/flowchem/server/configuration_parser.py","file_name":"configuration_parser.py","file_ext":"py","file_size_in_byte":6498,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"211665806","text":"from unittest.mock import ANY, Mock\n\nimport requests\nfrom django.core.management import call_command\n\nfrom saleor.account.models import ServiceAccount\nfrom saleor.core.permissions import get_permissions\n\n\ndef test_createaccount_command_creates_service_account():\n name = \"SA name\"\n permissions = [\"account.manage_users\", \"order.manage_orders\"]\n call_command(\"createserviceaccount\", name, permission=permissions)\n\n sa_accounts = ServiceAccount.objects.filter(name=name)\n assert len(sa_accounts) == 1\n\n sa_account = sa_accounts[0]\n tokens = sa_account.tokens.all()\n assert len(tokens) == 1\n\n\ndef test_createaccount_command_service_account_has_all_required_permissions():\n name = \"SA name\"\n permission_list = [\"account.manage_users\", \"order.manage_orders\"]\n expected_permission = get_permissions(permission_list)\n call_command(\"createserviceaccount\", name, permission=permission_list)\n\n sa_accounts = ServiceAccount.objects.filter(name=name)\n assert len(sa_accounts) == 1\n sa_account = sa_accounts[0]\n assert set(sa_account.permissions.all()) == set(expected_permission)\n\n\ndef test_createaccount_command_sends_data_to_target_url(monkeypatch):\n mocked_response = Mock()\n mocked_response.status_code = 200\n mocked_post = Mock(return_value=mocked_response)\n\n monkeypatch.setattr(requests, \"post\", mocked_post)\n\n name = \"SA name\"\n target_url = \"https://ss.shop.com/register\"\n permissions = [\n \"account.manage_users\",\n ]\n\n call_command(\n \"createserviceaccount\", name, permission=permissions, target_url=target_url\n )\n\n service_account = ServiceAccount.objects.filter(name=name)[0]\n token = service_account.tokens.all()[0].auth_token\n mocked_post.assert_called_once_with(\n target_url,\n headers={\"x-saleor-domain\": \"mirumee.com\"},\n json={\"auth_token\": token},\n timeout=ANY,\n )\n","sub_path":"tests/test_account_service_account.py","file_name":"test_account_service_account.py","file_ext":"py","file_size_in_byte":1899,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"392790185","text":"\nimport tensorflow as tf\nimport matplotlib.pyplot as plt\n\nclass Multi_Discriminator(tf.keras.models.Model):\n def __init__(self, op_type, dics_dict, **kwargs):\n super(Multi_Discriminator, self).__init__(**kwargs)\n self.dics_dict = dics_dict\n self.op_type = op_type\n\n def call(self, inputs_dict, Mask=None, training=None):\n if (self.op_type == \"Wxyz_and_Cxy\"): ### 最左邊的 I 是只 Model內本身的行為, 不會管 Model外 怎麼包喔, 意思就是 I 在 Model 外可以包成 I_w_M 也行, 反正 Model內都是唯一張img這樣子\n Wgt = inputs_dict[\"Wgt\"]\n Wpred = inputs_dict[\"Wpred\"]\n Cgt = inputs_dict[\"Cgt\"]\n Cpred = inputs_dict[\"Cpred\"]\n\n W_real = self.dics_dict[\"D_Wxyz\"](Wpred)\n W_fake = self.dics_dict[\"D_Wxyz\"](Wgt)\n C_real = self.dics_dict[\"D_Cxy\" ](Cpred)\n C_fake = self.dics_dict[\"D_Cxy\" ](Cgt)\n return W_real, W_fake, C_real, C_fake\n\n elif(self.op_type == \"Wxyz_and_Cxy\"): ### 最左邊的 I 是只 Model內本身的行為, 不會管 Model外 怎麼包喔, 意思就是 I 在 Model 外可以包成 I_w_M 也行, 反正 Model內都是唯一��img這樣子\n I = inputs_dict\n M = self.dics_dict[\"I_to_M\"](inputs_dict)\n M_w_I = M * I\n C = self.dics_dict[\"M_w_I_to_C\"](M_w_I)\n return M, C\n elif(self.op_type == \"I_to_M_w_I_to_W_to_C\"): ### 最左邊的 I 是只 Model內本身的行為, 不會管 Model外 怎麼包喔, 意思就是 I 在 Model 外可以包成 I_w_M 也行, 反正 Model內都是唯一張img這樣子\n I = inputs_dict\n M = self.dics_dict[\"I_to_M\"](inputs_dict)\n M_w_I = M * I\n W = self.dics_dict[\"M_w_I_to_W\"](M_w_I)\n C = self.dics_dict[\"W_to_C\"](W)\n return M, W, C\n\n elif(self.op_type == \"I_or_W_to_Cx_Cy\"): ### 最左邊的 I 是只 Model內本身的行為, 不會管 Model外 怎麼包喔, 意思就是 I 在 Model 外可以包成 I_w_M 也行, 反正 Model內都是唯一張img這樣子\n I = inputs_dict\n Cx = self.dics_dict[\"I_to_Cx\"](I)\n Cy = self.dics_dict[\"I_to_Cy\"](I)\n return Cx, Cy ### 這個順序要跟 step8b_useG, step9c_train_step 對應到喔!\n elif(self.op_type == \"I_to_Wx_Wy_Wz\"): ### 最左邊的 I 是只 Model內本身的行為, 不會管 Model外 怎麼包喔, 意思就是 I 在 Model 外可以包成 I_w_M 也行, 反正 Model內都是唯一張img這樣子\n I = inputs_dict\n Wx = self.dics_dict[\"I_to_Wx\"](I)\n Wy = self.dics_dict[\"I_to_Wy\"](I)\n Wz = self.dics_dict[\"I_to_Wz\"](I)\n return Wz, Wy, Wx ### 這個順序要跟 step8b_useG, step9c_train_step 對應到喔!\n elif(self.op_type == \"I_to_Wx_Wy_Wz_focus_to_Cx_Cy_focus\"): ### 最左邊的 I 是只 Model內本身的行為, 不會管 Model外 怎麼包喔, 意思就是 I 在 Model 外可以包成 I_w_M 也行, 反正 Model內都是唯一張img這樣子\n '''\n 注意 不能在這邊把 Wxyz concat 起來喔, 因為要分開算 loss!\n '''\n # I_pre = inputs_dict\n # Wz_pre_raw, Wy_pre_raw, Wx_pre_raw = self.dics_dict[\"I_to_Wx_Wy_Wz\"](I_pre)\n # W_pre_raw = tf.concat([Wz_pre_raw, Wy_pre_raw, Wx_pre_raw], axis=-1)\n # W_pre_w_M = W_pre_raw * Mask\n\n # Cx_pre_raw, Cy_pre_raw = self.dics_dict[\"W_to_Cx_Cy\"](W_pre_w_M)\n # C_pre_raw = tf.concat([Cy_pre_raw, Cx_pre_raw], axis=-1)\n # C_pre_w_M = C_pre_raw * Mask\n # return W_pre_raw, W_pre_w_M, C_pre_raw, C_pre_w_M\n\n I_pre = inputs_dict\n Wz_pre_raw, Wy_pre_raw, Wx_pre_raw = self.dics_dict[\"I_to_Wx_Wy_Wz\"](I_pre)\n W_pre_raw = tf.concat([Wz_pre_raw, Wy_pre_raw, Wx_pre_raw], axis=-1)\n W_pre_w_M = W_pre_raw * Mask\n\n Cx_pre_raw, Cy_pre_raw = self.dics_dict[\"W_to_Cx_Cy\"](W_pre_w_M)\n\n return Wz_pre_raw, Wy_pre_raw, Wx_pre_raw, Cx_pre_raw, Cy_pre_raw\n\ndef see(model_obj, train_in_pre):\n M_pre, C_pre = model_obj.generator(train_in_pre)\n\n M_visual = (M_pre[0].numpy() * 255.).astype(np.uint8)\n\n from step08_b_use_G_generate_0_util import F_01_or_C_01_method1_visual_op, Value_Range_Postprocess_to_01\n C = Value_Range_Postprocess_to_01(C_pre[0])\n C_visual = F_01_or_C_01_method1_visual_op(C)\n\n fig, ax = plt.subplots(nrows=1, ncols=2)\n ax[0].imshow(M_visual)\n ax[1].imshow(C_visual)\n plt.show()\n\n\nif(__name__ == \"__main__\"):\n import numpy as np\n import time\n from kong_util.tf_model_util import Show_model_layer_names, Show_model_weights\n # data = np.ones(shape=(1, 512, 512, 3), dtype=np.float32)\n # start_time = time.time() # 看資料跑一次花多少時間\n # # test_g = Generator(hid_ch=64, depth_level=7, use_bias=False)\n # test_g = Generator(hid_ch= 128, depth_level=4, out_ch=1, unet_acti=\"sigmoid\", conv_block_num=1, ch_upper_bound= 2**14)\n # test_g(data)\n # print(\"cost time\", time.time() - start_time)\n # test_g.summary()\n # print(test_g(data))\n\n\n\n ############################################################################################################################\n ### 嘗試 真的 load tf_data 進來 train 看看\n import numpy as np\n from tqdm import tqdm\n from step06_a_datas_obj import *\n from step06_cFinal_tf_Data_builder import tf_Data_builder\n from step10_a2_loss_info_obj import Loss_info_builder\n from step09_c_train_step import *\n\n\n from step09_f1_multi_unet2_obj_I_to_M_w_I_to_C import *\n\n # model_obj = try_multi_unet\n model_obj = I_to_M_L4_ch032_and_M_w_I_to_C_L5_ch032\n model_obj = model_obj.build() ### 可替換成 上面 想測試的 model\n print(model_obj)\n\n ### 2. db_obj 和 tf_data\n db_obj = type9_mask_flow_have_bg_dtd_hdr_mix_and_paper.build()\n tf_data = tf_Data_builder().set_basic(db_obj, 1, train_shuffle=False).set_data_use_range(use_in_range=Range(0, 1), use_gt_range=Range(0, 1)).set_img_resize(( 512, 512) ).build_by_db_get_method().build()\n\n # ### 3. loss_info_obj\n G_mae_loss_infos = [Loss_info_builder().set_loss_type(\"mae\").build(),\n Loss_info_builder().set_loss_type(\"mae\").build()]\n ### 4. 跑起來試試看\n for n, (train_in, train_in_pre, train_gt, train_gt_pre, _) in enumerate(tqdm(tf_data.train_db_combine.take(50))):\n model_obj.train_step(model_obj=model_obj, in_data=train_in_pre, gt_data=train_gt_pre, loss_info_objs=G_mae_loss_infos)\n if(n == 0):\n model_obj.generator.summary()\n Show_model_weights(model_obj.generator)\n\n see(model_obj, train_in_pre)\n\n if(n == 2):\n print(model_obj.generator.dics_dict)\n ckpt_I_to_M = tf.train.Checkpoint(generator=model_obj.generator.dics_dict[\"I_to_M\"])\n ckpt_M_w_I_to_C = tf.train.Checkpoint(generator=model_obj.generator.dics_dict[\"M_w_I_to_C\"])\n\n ckpt_path_I_to_M = \"F:/kong_model2/data_dir/result/6_mask_unet/5_2_bce_block1_45678l/type8_blender-2_4l_ch032-flow_unet2-block1_ch032_sig_bce_s001_4l_ep060_copy-20211204_203747/ckpt\"\n ckpt_path_I_w_M_to_C = \"F:/kong_model2/data_dir/result/7_flow_unet/5_2_mae_block1_45678l_I_with_Mgt_to_C/type8_blender_os_book-2_L5_ch032-flow_unet2-block1_L5_ch032_mae_s001-20211125_170346/ckpt\"\n\n ckpt_read_manager_I_to_M = tf.train.CheckpointManager(ckpt_I_to_M, ckpt_path_I_to_M, max_to_keep=1)\n ckpt_read_manager_M_w_I_to_C = tf.train.CheckpointManager(ckpt_M_w_I_to_C, ckpt_path_I_w_M_to_C, max_to_keep=1)\n\n ckpt_I_to_M. restore(ckpt_read_manager_I_to_M.latest_checkpoint)\n ckpt_M_w_I_to_C.restore(ckpt_read_manager_M_w_I_to_C.latest_checkpoint)\n print(\"ckpt_read_manager_I_to_M.latest_checkpoint:\", ckpt_read_manager_I_to_M.latest_checkpoint)\n\n see(model_obj, train_in_pre)\n\n\n if(n == 10):\n model_obj.generator.save_weights(\"debug_data/try_save/weights\")\n iter10 = model_obj.generator.layers[0].weights[1]\n print(\"iter10:\", iter10)\n if(n == 20):\n iter20 = model_obj.generator.layers[0].weights[1]\n print(\"iter20:\", iter20)\n model_obj.generator.load_weights(\"debug_data/try_save/weights\")\n iter20_load10 = model_obj.generator.layers[0].weights[1]\n print(\"iter20_load10:\", iter20_load10)\n","sub_path":"step07_b_0b_Multi_Discriminator.py","file_name":"step07_b_0b_Multi_Discriminator.py","file_ext":"py","file_size_in_byte":8564,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"419245763","text":"import pandas as pd\nimport re\nimport time\nimport requests\nfrom bs4 import BeautifulSoup\n\ndef get_webpage(url):\n \"\"\"\n Given a URL, return a webpage HTML. If the webpage has been scraped before return archived text, otherwise politely scrape it.\n\n Keywords:\n url: (str) url of webpage to be scraped\n\n Return\n webpage: (BeautifulSoup) html parsed text from a webpage\n \"\"\"\n\n # Distributing archive for efficient retrieval\n if 'player' in url:\n archive = pd.read_csv('../data/archive/archive-players.csv', index_col=0)\n elif 'ground' in url:\n archive = pd.read_csv('../data/archive/archive-grounds.csv', index_col=0)\n else:\n archive = pd.read_csv(\"../data/archive/archive-matches.csv\", index_col=0)\n\n try:\n # Explore archive first to avoid excessively hitting the server\n html = archive.loc[url][0]\n return BeautifulSoup(html, \"html.parser\")\n except KeyError:\n # Be polite to the webserver\n time.sleep(.5)\n\n # Get the webpage from the Website\n html_request = requests.get(url)\n webpage = BeautifulSoup(html_request.text, features=\"lxml\")\n attempts = 1\n\n # Retry upto 5 times to reread the page\n while attempts < 5 and 'Page error' in webpage.text:\n # Take a deep breath, and try again. Giving more rest to the server at each attempt\n time.sleep(attempts)\n html_request = requests.get(url)\n webpage = BeautifulSoup(html_request.text, features=\"lxml\")\n attempts += 1\n \n # Archive scrapped webpage for future use, but exclude Page Error or 2019 match results\n if 'Page error' in webpage.text:\n print('Cannot process',url)\n print('Keep bumping into Page error, buddy! ¯\\_(ツ)_/¯')\n elif 'match_results.html?class=2;id=2019;type=year' in url:\n print('FYI: 2019 match results will not be archived, because updates are expected.')\n return webpage\n else:\n add = pd.DataFrame([[url,webpage]],columns=['url','html']) \n add.set_index('url', inplace=True)\n if 'player' in url:\n add.to_csv('../data/archive/archive-players.csv', mode='a', header=False)\n elif 'ground' in url:\n add.to_csv('../data/archive/archive-grounds.csv', mode='a', header=False)\n else:\n add.to_csv('../data/archive/archive-matches.csv', mode='a', header=False)\n\n return webpage\n \n\ndef initiate_match_results_dataframe(start_year=1971, end_year=2019, save_to_file=False):\n \"\"\"\n Initializes a dataframe that is extracted from the scraped match results webpages\n between the specified start year and end year\n\n Keywords:\n start_year: (int) ODI matches to scrape from specified year\n end_year: (int) ODI matches to scrape to specified year\n save_to_file: (bool) \n\n Return\n matches: (pandas.Dataframe) \n \"\"\"\n\n matches = pd.DataFrame(get_odi_match_results(get_webpage('http://stats.espncricinfo.com/ci/engine/records/team/match_results.html?class=2;id='+ str(start_year) +';type=year')))\n for year in list(range(start_year+1, end_year)):\n soup = get_webpage('http://stats.espncricinfo.com/ci/engine/records/team/match_results.html?class=2;id='+ str(year) +';type=year')\n matches = matches.append(get_odi_match_results(soup))\n matches = matches.reset_index(drop=True)\n\n if save_to_file == True:\n matches.to_csv(\"../data/match_results.csv\", index=False)\n\n return matches\n\ndef get_odi_match_results(soup):\n \"\"\"\n Given a BeautifulSoup object of ODI match results, get a dataframe of teams, winner, margin, ground and scorecard.\n\n Keyword:\n soup: (BeautifulSoup) ODI match results\n\n Return:\n matches: (Dataframe) With teams, winner, margin, ground, ground URL, match date, scorecard and scorecard URL.\n \"\"\"\n\n l = []\n for table in soup.find_all('tbody'):\n for tr in table.find_all('tr'):\n td = tr.find_all('td')\n row = []\n for cell in td:\n row.append(cell.text)\n # Obtain Ground and Scorecard URLs\n try:\n if 'ground' in cell.find('a')['href']: row.append('http://stats.espncricinfo.com' + cell.find('a')['href']) \n if 'match' in cell.find('a')['href']: row.append('http://stats.espncricinfo.com' +cell.find('a')['href']) \n except TypeError:\n continue\n l.append(row)\n matches = pd.DataFrame(l, columns=['team_1','team_2','winner','margin','ground','ground_url','match_date','scorecard','scorecard_url'])\n\n # For any ODI's that took more than a day to finish,\n # consider only the first day as the match date\n matches = matches.replace(\"\\-.*,\",\"\", regex=True)\n\n # Convert Match Date strings to datetime objects for easy manipulation\n matches['match_date'] = pd.to_datetime(matches['match_date'])\n\n return matches\n\ndef get_scorecard_details(soup):\n \"\"\"\n Given a BeautifulSoup object of ODI match scorecard, get all the relevant information including players in a list format\n\n Keyword:\n soup: (BeautifulSoup) ODI match scorecard\n\n Return:\n details: (list) comprising of World Cup Match (boolean), Attendence (int), players' names (str) and urls(str)\n \"\"\"\n\n details = []\n\n # World cup match or not?\n WC = 'World Cup' in soup.find('div', {\"class\":\"cscore_info-overview\"}).text\n details.append(WC)\n\n # Getting attendence\n attendance = None\n for div in soup.find_all('div', {\"class\": \"accordion-content collapse in\"}):\n for li in div.find_all('li'): \n if 'Attendance' in li.text:\n # Taking out match revenue detailed added to attendance with paranthesis \n if \"(\" in li.text:\n attendance = int(''.join(re.findall('\\s(\\d.*)\\s\\(', li.text)).replace(',','').replace(' ',''))\n else:\n attendance = int(''.join(re.findall('\\d+', li.text)))\n details.append(attendance)\n\n # Getting players\n for li in soup.find_all('li', {\"class\": \"accordion-item\"}):\n players = []\n try:\n team = None\n team = li.find('h2').text.replace(' Innings','')\n except AttributeError:\n continue\n players.append(team)\n for div in li.find_all('div', {\"class\":\"scorecard-section batsmen\"}):\n for a in div.find_all('a'):\n try: \n if a[\"href\"][-4:]=='html':\n name = a.text.replace(\" †\",\"\").replace(\" (c)\",\"\")\n players.append(name)\n players.append(a['href'])\n except:\n continue\n while len(players) < 25: players.append(None)\n details = details + players\n\n\n return details\n\ndef get_player_details(soup):\n \"\"\"\n Given a BeautifulSoup object of an ODI cricket player, get the relevant batting and bowling details including Date of Birth.\n\n Keyword:\n soup: (BeautifulSoup) ODI cricket player\n\n Return:\n details: (list) batting and bowling details including Date of Birth.\n \"\"\"\n\n DOB = None\n style = None\n batting = None\n bowling = None\n \n for p in soup.find_all('p', {\"class\":\"ciPlayerinformationtxt\"}):\n if p.text[:4] == 'Born':\n # get player DOB\n DOB = pd.to_datetime(re.search('\\w{3,9}?\\s\\d{1,2}?,\\s\\d{4}?', p.text).group(0))\n if p.text[:4] == 'Play':\n # Get player style\n style = p.find('span').text\n if p.text[:4] == 'Batt':\n # Get batting style\n batting = p.find('span').text\n if p.text[:4] == 'Bowl':\n # Get bowling style\n bowling = p.find('span').text\n \n bat = []\n bowl = []\n for table in soup.find_all('tbody'):\n for tr in table.find_all('tr'):\n td = tr.find_all('td')\n row = [tr.text for tr in td]\n if len(row) == 15:\n bat.append(row)\n if len(row) == 14:\n bowl.append(row)\n \n bat_ave = None\n bat_sr = None\n bowl_ave = None\n bowl_econ = None\n bowl_sr = None\n \n bat_df = pd.DataFrame(bat, columns=['Format','Mat','Inns','NO','Runs','HS','Ave','BF', 'SR','100','50','4s', '6s','Ct','St'])\n bowl_df = pd.DataFrame(bowl, columns=['Format','Mat','Inns','Balls','Runs','Wkts', 'BBI', 'BBM','Ave','Econ', 'SR','4w', '5w','10'])\n bat_ave = float(bat_df[bat_df['Format']=='ODIs']['Ave'].values[0])\n bat_sr = float(bat_df[bat_df['Format']=='ODIs']['SR'].values[0])\n bowl_ave = float(bowl_df[bat_df['Format']=='ODIs']['Ave'].values[0])\n bowl_econ = float(bowl_df[bat_df['Format']=='ODIs']['Econ'].values[0])\n bowl_sr = float(bowl_df[bat_df['Format']=='ODIs']['SR'].values[0])\n \n details = [DOB, style, batting, bowling, bat_ave, bat_sr, bowl_ave, bowl_econ, bowl_sr]\n\n\n return details\n\ndef get_ground_details(soup):\n \"\"\"\n Given a BeautifulSoup object of a cricket ground, get the relevant city, country, year established, and pitch type.\n\n Keyword:\n soup: (BeautifulSoup) cricket ground\n\n Return:\n details: (list) city, country, year established, and pitch type.\n \"\"\"\n\n details = []\n\n\n return details","sub_path":"scripts/scrapper.py","file_name":"scrapper.py","file_ext":"py","file_size_in_byte":9454,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"336087987","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Apr 12 23:49:24 2022\n\n@author: xpess\n\"\"\"\n\nfrom collections import deque\n\ndef bfs(G, s):\n \"\"\"\n Parcours d'un graphe en largeur\n\n Parameters\n ----------\n G : graphe sous forme de dictionnaire d'adjacence\n s : sommet du graphe (Chaine de caractere du type \"S1\").\n\n Returns\n -------\n None.\n\n \"\"\"\n visited = {}\n for sommet,voisins in G.items():\n visited[sommet]=False\n # Le premier sommet à visiter entre dans la file\n q = deque([s])\n while len(q) > 0:\n # On visite la tête de file\n u = q.pop()\n \n # On vérifier qu'elle n'a pas été visitée\n if not visited[u]:\n # Si on l'avait pas visité, maintenant c'est le cas :)\n visited[u] = True\n \n # On met les voisins de u dans la file\n for v in G[u]:\n q.appendleft(v)\n\ngraphe = {\"S0\":[\"S1\"],\\\n \"S1\":[\"S0\",\"S2\",\"S3\",\"S4\",\"S5\"],\\\n \"S2\":[\"S1\",\"S3\"],\\\n \"S3\":[\"S1\",\"S2\",\"S4\"],\\\n \"S4\":[\"S1\",\"S3\",\"S6\"],\\\n \"S5\":[\"S1\"],\\\n \"S6\":[\"S4\"]}\n\n\ndef bfs_pr(G, s):\n visited = {}\n for sommet,voisins in G.items():\n visited[sommet]=False\n q = deque([s])\n while len(q) > 0:\n print('================')\n print(q)\n print(visited)\n u = q.pop()\n print(u)\n if not visited[u]:\n visited[u] = True\n for v in G[u]:\n q.appendleft(v)\n \n\ndef bfs_parcours(G, s):\n visited = {}\n for sommet,voisins in G.items():\n visited[sommet]=False\n q = deque([s])\n chemin = []\n while len(q) > 0:\n u = q.pop()\n if not visited[u]:\n chemin.append(u)\n visited[u] = True\n for v in G[u]:\n q.appendleft(v)\n return chemin\n\n\ndef dfs(G, s): \n visited = {}\n for sommet,voisins in G.items():\n visited[sommet]=False\n \n pile = [s]\n while len(pile) > 0:\n u = pile.pop()\n if not visited[u]:\n visited[u] = True\n for v in G[u]:\n pile.append(v)\n\ndef dfs_pr(G, s): \n visited = {}\n for sommet,voisins in G.items():\n visited[sommet]=False\n \n pile = [s]\n while len(pile) > 0:\n u = pile.pop()\n if not visited[u]:\n visited[u] = True\n print(u)\n for v in G[u]:\n pile.append(v)\n\n\ngraphe2 = {\"S0\":[\"S1\",\"S2\",\"S3\"],\\\n \"S1\":[\"S0\",\"S3\"],\\\n \"S2\":[\"S0\"],\\\n \"S3\":[\"S0\",\"S1\"]}\n\n \ndfs_pr(graphe2, \"S0\")\n#bfs_pr(graphe, \"S0\")","sub_path":"Cours/08_ParcoursGraphes/Parcours_Graphe.py","file_name":"Parcours_Graphe.py","file_ext":"py","file_size_in_byte":2635,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"84675165","text":"import importlib\n\nimport pytest\n\nimport janitor.chemistry # noqa: disable=unused-import\nfrom helpers import running_on_ci\n\n# Skip all tests if rdkit not installed\npytestmark = pytest.mark.skipif(\n (importlib.util.find_spec(\"rdkit\") is None) & ~running_on_ci(),\n reason=\"rdkit tests only required for CI\",\n)\n\n\n@pytest.mark.chemistry\ndef test_morgan_fingerprint_counts(chemdf):\n \"\"\"Test counts of Morgan Fingerprints converted from Mol objects.\"\"\"\n morgans = chemdf.smiles2mol(\"smiles\", \"mol\").morgan_fingerprint(\n \"mol\", kind=\"counts\"\n )\n assert morgans.shape == (10, 2048)\n assert (morgans.to_numpy() >= 0).all()\n\n\n@pytest.mark.chemistry\ndef test_morgan_fingerprint_bits(chemdf):\n \"\"\"Test bits of Morgan Fingerprints converted from Mol objects.\"\"\"\n morgans = chemdf.smiles2mol(\"smiles\", \"mol\").morgan_fingerprint(\n \"mol\", kind=\"bits\"\n )\n assert morgans.shape == (10, 2048)\n assert set(morgans.to_numpy().flatten().tolist()) == set([0, 1])\n\n\n@pytest.mark.chemistry\ndef test_morgan_fingerprint_kind_error(chemdf):\n \"\"\"Test ``morgan_fingerprint`` raises exception for invalid ``kind``.\"\"\"\n with pytest.raises(ValueError):\n chemdf.smiles2mol(\"smiles\", \"mol\").morgan_fingerprint(\n \"mol\", kind=\"invalid-kind\"\n )\n","sub_path":"tests/chemistry/test_morgan_fingerprint.py","file_name":"test_morgan_fingerprint.py","file_ext":"py","file_size_in_byte":1288,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"483231691","text":"from bs4 import BeautifulSoup, SoupStrainer\nimport re\nimport mysql.connector\nimport os\nfrom dotenv import load_dotenv\nimport time\nfrom selenium import webdriver\n\n\n#Loading environment variables\nload_dotenv()\nload_dotenv(dotenv_path='../.env')\n\ndef get_player_page():\n \"\"\"\n Will retrieve the list of players from from 'https://www.premierleague.com/players/\n :return:\n \"\"\"\n options = webdriver.ChromeOptions()\n options.binary_location = '/usr/local/bin/chromedriver'\n options.add_argument('window-size=800x841')\n options.add_argument('headless')\n\n driver = webdriver.Chrome('/usr/local/bin/chromedriver')\n driver.get('https://www.premierleague.com/players/')\n driver.maximize_window()\n\n driver.get('https://www.premierleague.com/players/')\n\n driver.execute_script(\"window.scrollTo(0, document.body.scrollHeight)\")\n # Need to allow the browser adequate time to load the page\n time.sleep(120)\n html = driver.page_source\n\n return html\n\n\ndef save_player_links(html):\n \"\"\"\n Will parse the player_links html page saved by get_players_page and write out the player links to\n the players table in the eplApi db.\n :return:\n \"\"\"\n\n soup = BeautifulSoup(html, \"html.parser\", parse_only=SoupStrainer('a'))\n active_db = mysql.connector.connect(\n host=\"localhost\",\n user=os.getenv('epl_db_user'),\n passwd=os.getenv('epl_db_password'),\n database=os.getenv('epl_db_name')\n )\n\n mycursor = active_db.cursor()\n active_db.commit()\n p = re.compile('https://www.premierleague.com/players/[0-9]*')\n for link in soup:\n if link.has_attr('href'):\n if p.match(link['href']):\n sql = \"INSERT INTO Players (player_link) VALUES (%s)\"\n temp_link = link['href']\n if temp_link.endswith(\"overview\"):\n temp_link = temp_link[:-8]\n stats_link = temp_link + 'stats'\n print(stats_link)\n mycursor.execute(sql, (stats_link,))\n active_db.commit()\n print(stats_link)\n\n\nif __name__ == \"__main__\":\n links_page = get_player_page()\n #save_player_links(links_page)\n print(links_page)","sub_path":"get_player_links.py","file_name":"get_player_links.py","file_ext":"py","file_size_in_byte":2233,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"105531529","text":"\"\"\"CPU functionality.\"\"\"\n\nimport sys\n\nLDI = 1\nPRN = 2\nHLT = 3\nMUL = 4\nPUSH = 5\nPOP = 6\n\nclass CPU:\n \"\"\"Main CPU class.\"\"\"\n\n def __init__(self):\n \"\"\"Construct a new CPU.\"\"\"\n \"\"\"Contains Registry, RAM, Program Counter, and branchtable.\"\"\"\n self.pc = 0\n self.reg = [0] * 8\n self.ram = [0b00000000] * 256\n self.program = 0\n self.branchtable = {}\n self.branchtable[LDI] = self.handle_LDI\n self.branchtable[PRN] = self.handle_PRN\n self.branchtable[MUL] = self.handle_MUL\n self.branchtable[HLT] = self.handle_HLT\n self.branchtable[PUSH] = self.handle_PUSH\n self.branchtable[POP] = self.handle_POP\n \"\"\"Stack Pointer.\"\"\"\n self.reg[-1] = 242\n\n\n def ram_read(self, mar):\n \"Reads the selected address within the RAM.\"\n value = self.ram[mar]\n return value\n\n def raw_write(self, mdr, mar):\n \"\"\"Takes in data and an address to write the data to.\"\"\"\n self.ram[mar] = mdr\n return\n\n def load(self):\n \"\"\"Load a program into memory.\"\"\"\n\n if len(sys.argv) == 1:\n print(\"ERROR: No program loaded. Please specify program directory.\")\n exit(1)\n else:\n program = open(sys.argv[1])\n\n for instruction in program:\n splitstring = instruction.split()\n if splitstring == []:\n pass\n elif splitstring[0] == \"#\":\n pass\n elif splitstring[0] == \"LDI\": \n self.raw_write(LDI, self.program)\n elif splitstring[0] == \"PRN\":\n self.raw_write(PRN, self.program)\n elif splitstring[0] == \"HLT\":\n self.raw_write(HLT, self.program)\n elif splitstring[0] == \"MUL\":\n self.raw_write(MUL, self.program)\n elif splitstring[0] == \"PUSH\":\n self.raw_write(PUSH, self.program)\n elif splitstring[0] == \"POP\":\n self.raw_write(POP, self.program)\n else:\n binary_mode = int(instruction, 2)\n self.raw_write(binary_mode, self.program)\n self.program += 1\n self.raw_write(HLT, self.program)\n\n\n\n def alu(self, op, reg_a, reg_b):\n \"\"\"Partially implemented mathematical functions.\"\"\"\n \"\"\"ALU operations.\"\"\"\n\n if op == \"ADD\":\n self.reg[reg_a] += self.reg[reg_b]\n elif op == \"MUL\":\n self.reg[reg_a] *= self.reg[reg_b]\n elif op == \"SUB\":\n self.reg[reg_a] -= self.reg[reg_b]\n elif op == \"DIV\":\n self.reg[reg_a] /= self.reg[reg_b]\n else:\n raise Exception(\"Unsupported ALU operation\")\n\n def trace(self):\n \"\"\"\n Handy function to print out the CPU state. You might want to call this\n from run() if you need help debugging.\n \"\"\"\n\n print(f\"TRACE: %02X | %02X %02X %02X |\" % (\n self.pc,\n #self.fl,\n #self.ie,\n self.ram_read(self.pc),\n self.ram_read(self.pc + 1),\n self.ram_read(self.pc + 2)\n ), end='')\n\n for i in range(8):\n print(\" %02X\" % self.reg[i], end='')\n\n print()\n\n def handle_HLT(self):\n print(\"Program successfully halted.\")\n exit(0)\n\n def handle_LDI(self):\n operand_a = self.ram_read(self.pc + 1)\n operand_b = self.ram_read(self.pc + 2)\n self.reg[operand_a] = operand_b\n self.pc += 3\n \n def handle_PRN(self):\n operand_a = self.ram_read(self.pc + 1)\n data = self.reg[operand_a]\n print(data)\n self.pc += 2\n \n def handle_MUL(self):\n operand_a = self.ram_read(self.pc + 1)\n operand_b = self.ram_read(self.pc + 2)\n self.alu(\"MUL\", operand_a, operand_b)\n self.pc += 3\n\n def handle_PUSH(self):\n operand_a = self.ram_read(self.pc + 1)\n data = self.reg[operand_a]\n self.raw_write(data, self.reg[-1])\n if self.reg[-1] <= self.program:\n print(f\"ERROR: Stack Overflow at line {self.pc}.\")\n self.reg[-1] -= 1\n self.pc += 2\n\n def handle_POP(self):\n operand_a = self.ram_read(self.pc + 1)\n self.reg[operand_a] = self.ram_read(self.reg[-1])\n if self.reg[-1] >= 242:\n print(f\"ERROR: Stack Underflow at line {self.pc}.\")\n exit(1)\n self.reg[-1] += 1\n self.pc += 2\n\n def run(self):\n \"\"\"Run the CPU.\"\"\"\n\n\n for i in self.ram:\n if i == self.ram_read(self.pc):\n if self.branchtable[i]:\n self.branchtable[i]()\n else:\n print(f\"ERROR: Unknown command in program at line {self.pc}. RAM dump: {i}\")\n exit(1)\n else:\n pass\n\n","sub_path":"ls8/cpu.py","file_name":"cpu.py","file_ext":"py","file_size_in_byte":4925,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"128387231","text":"# # !/usr/bin/python3\n# # -*- coding: utf-8 -*-\n\nimport logging\n\n# THESE SETTINGS ARE NEEDED FOR PYSETTINGS\nAPP_LOG_FILENAME = 'app.log'\nAPP_LOG_HANDLER_CONSOLE_LEVEL \t= logging.WARNING\nAPP_LOG_HANDLER_FILE_LEVEL \t\t= logging.WARNING\n\n# BPOD GUI PLUGIN SETTINGS\nAPP_LOG_HANDLER_FILE_LEVEL \t\t= logging.WARNING\nAPP_LOG_HANDLER_CONSOLE_LEVEL \t= logging.WARNING\n\n\n# [project], [experiment], [setup], [protocol], [datetime], [subjects]\nPYBPODGUI_API_DEFAULT_SESSION_NAME = \"[datetime]\"\n\n\nPYBPODGUI_API_CHECK_SUBJECTS_ON_RUN = True\n\nPYBPODGUI_API_AUTO_SAVE_PROJECT_ON_RUN = False\n","sub_path":"pybpodgui_api/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":573,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"388800286","text":"\"\"\"\nNote on Rtrees:\nhttp://gis.stackexchange.com/questions/120955/understanding-the-use-of-spatial-indexes/144764#144764\n\n\n\"\"\"\n\nimport json\nimport rtree\nimport fiona\nimport shapely.geometry\nimport pandas as pd\nimport sys\nimport ipdb\n\nneighborhoods = {}\nrows_with_errors = []\n\nfiona_collection = fiona.open(\n \"/root/Development/CSE519/BaltimoreRanking-519/Data/baltimore_neighborhoods/geo_export_08ed7f27-96f0-4be4-946a-c7cb3e3cfc81.shp\")\n\nservice_data = pd.read_csv(\n \"/root/Development/CSE519/BaltimoreRanking-519/Data/911.csv\")\n\n\n# try latitude and longitude against all shapes in shapefile\nshapefile_records = list(fiona_collection)\nshape_dict = {}\nfor record in shapefile_records:\n shape_dict[record[\"properties\"][\"label\"]] = shapely.geometry.asShape(record[\n 'geometry'])\n\n# create an empty spatial index object\nindex = rtree.index.Index()\nfor fid, feature in fiona_collection.items():\n geometry = shapely.geometry.shape(feature[\"geometry\"])\n index.insert(fid, geometry.bounds)\n\nfor row_num, series in service_data.iterrows():\n lat_long_list = series['location'].split(\",\")\n try:\n lat = float(lat_long_list[0][1:])\n longit = float(lat_long_list[1][:-1])\n except:\n # rows_with_errors.append(row_num)\n rows_with_errors.append(series.name)\n continue\n\n point = shapely.geometry.Point(longit, lat)\n fids = [int(i) for i in index.intersection(point.bounds)]\n for fid in fids:\n shape = shapely.geometry.shape(fiona_collection[fid]['geometry'])\n if shape.contains(point):\n try:\n neighborhoods[fiona_collection[fid][\n \"properties\"]['label']].append(int(series.name))\n break\n except Exception as e:\n neighborhoods[fiona_collection[fid][\n \"properties\"]['label']] = [int(series.name)]\n break\n\nwith open(\"/root/Development/CSE519/BaltimoreRanking-519/Data/911_mapping_rtree_2.csv\", \"w\") as fp:\n json.dump(neighborhoods, fp)\n","sub_path":"Baltimore Notebook/911_neighborhood_mapping_rtrees.py","file_name":"911_neighborhood_mapping_rtrees.py","file_ext":"py","file_size_in_byte":2093,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"546691161","text":"import torch\nfrom torch import nn\nfrom src.models.Base import Base\n\n\n# Copyright 2018 The Sonnet Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ============================================================================\n\n\n# Borrowed from https://github.com/deepmind/sonnet and ported it to PyTorch\n\n\nclass ResBlock(nn.Module):\n def __init__(self, in_channel, channel):\n super().__init__()\n\n self.conv = nn.Sequential(\n nn.ReLU(),\n nn.Conv1d(in_channel, channel, 3, padding=1),\n nn.ReLU(inplace=True),\n nn.Conv1d(channel, in_channel, 1),\n )\n\n def forward(self, input):\n out = self.conv(input)\n out += input\n\n return out\n\n\nclass Encoder(nn.Module):\n def __init__(self,\n in_channel,\n channel,\n n_res_block,\n n_res_channel):\n super().__init__()\n\n blocks = [\n nn.Conv1d(in_channel, channel // 2, 16, stride=4, padding=1),\n nn.ReLU(inplace=True),\n nn.Conv1d(channel // 2, channel, 8, stride=3, padding=1),\n nn.ReLU(inplace=True),\n nn.Conv1d(channel, channel, 6, stride=2, padding=1),\n nn.ReLU(inplace=True),\n nn.Conv1d(channel, channel, 6, stride=2, padding=1),\n nn.ReLU(inplace=True),\n nn.Conv1d(channel, channel, 6, stride=2, padding=1),\n nn.ReLU(inplace=True),\n nn.Conv1d(channel, channel, 6, stride=2, padding=1),\n nn.ReLU(inplace=True),\n nn.Conv1d(channel, channel, 6, stride=2, padding=1),\n nn.ReLU(inplace=True),\n nn.Conv1d(channel, channel, 6, stride=2, padding=1),\n nn.ReLU(inplace=True),\n nn.Conv1d(channel, channel, 6, stride=2, padding=1),\n nn.ReLU(inplace=True),\n nn.Conv1d(channel, channel, 6, stride=2, padding=0),\n ]\n\n for i in range(n_res_block):\n blocks.append(ResBlock(channel, n_res_channel))\n\n blocks.append(nn.ReLU(inplace=True))\n\n self.blocks = nn.Sequential(*blocks)\n\n def forward(self, input):\n return self.blocks(input)\n\n\nclass Generator(Base):\n def __init__(self,\n dropout=0.5,\n input_size=13181,\n z_dim=100\n ):\n super().__init__()\n\n self.dropout = nn.Dropout(p=dropout)\n self.linear = nn.Sequential(\n nn.Linear(z_dim, 1024),\n nn.BatchNorm1d(1024),\n nn.ReLU(inplace=True),\n nn.Dropout(),\n nn.Linear(1024, input_size),\n )\n\n self.random_init()\n\n def random_init(self, init_func=torch.nn.init.xavier_uniform_):\n torch.manual_seed(42)\n for m in self.modules():\n if isinstance(m, nn.Linear) or isinstance(m, nn.Conv1d) or isinstance(m, nn.ConvTranspose1d):\n init_func(m.weight.data)\n if m.bias is not None:\n m.bias.data.zero_()\n\n def forward(self, x):\n x = self.linear(x)\n x = torch.relu(x)\n # x[x > 1] = 1.0\n return x\n\n def get_model_name(self):\n return 'generator'\n\n\nclass Discriminator(Base):\n def __init__(\n self,\n dropout=0,\n input_size=13181\n ):\n super().__init__()\n\n self.dropout = nn.Dropout(p=dropout)\n self.linear = nn.Sequential(\n nn.Linear(input_size, 1024),\n nn.BatchNorm1d(1024),\n nn.ReLU(inplace=True),\n nn.Dropout(),\n nn.Linear(1024, 1),\n )\n\n self.random_init()\n\n def random_init(self, init_func=torch.nn.init.xavier_uniform_):\n torch.manual_seed(42)\n for m in self.modules():\n if isinstance(m, nn.Linear) or isinstance(m, nn.Conv1d) or isinstance(m, nn.ConvTranspose1d):\n init_func(m.weight.data)\n if m.bias is not None:\n m.bias.data.zero_()\n\n def forward(self, x):\n x = self.linear(x.squeeze())\n x = torch.sigmoid(x)\n return x\n\n def get_model_name(self):\n return 'discriminator'\n","sub_path":"src/models/pytorch/unsupervised/GANs/GAN_1D.py","file_name":"GAN_1D.py","file_ext":"py","file_size_in_byte":4691,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"189524498","text":"from os import listdir\nfrom time import time\nfrom os import system\nfrom pprint import pprint\n\ninverted_index = {}\n\n\ndef spider(file_paths):\n all_words = []\n\n with open(file_paths, 'r') as file:\n for line in file.readlines():\n for word in line.strip().split():\n new_word = ''\n for symbol in word.lower():\n if symbol.isalpha():\n new_word += symbol\n if new_word:\n all_words += [new_word]\n\n return all_words\n\n\ndef indexer(file_path, all_words):\n for word in all_words:\n if word in inverted_index:\n inverted_index[word].add(file_path)\n else:\n inverted_index[word] = {file_path}\n\n\ndef crawler(folder):\n file_paths = set(f'{folder}\\\\{name}' for name in listdir(folder))\n return file_paths\n\n\ndef search_result(request):\n tmp = set()\n\n for word in request:\n if word in inverted_index:\n if not tmp:\n tmp = inverted_index[word]\n else:\n tmp = tmp & inverted_index[word]\n\n return tmp\n\n\ndef main():\n start_time = time()\n\n folder = 'parts'\n file_paths = crawler(folder) # создание списка путей к файлам\n\n for file_path in file_paths:\n all_words = spider(file_path) # работа паука\n indexer(file_path, all_words) # работа индексатора\n\n end_time = time()\n\n print(f'Время работы поискового робота: {(end_time - start_time):.3f} сек.')\n\n all_time = 0\n\n for _ in range(100): # работа поисковика\n input()\n system('cls')\n\n request = [word.lower() for word in input('Что ищем: ').split()]\n\n start_time = time()\n\n result = search_result(request)\n\n end_time = time()\n all_time += end_time - start_time\n\n print(f'Результатов по вашему запросу: {len(result)}')\n print('# Результат поиска #', *result, sep='\\n')\n\n print(f'Время работы поисковика: {all_time:.3f} сек.')\n\n\nif __name__ == '__main__':\n main()\n # pprint(inverted_index)\n","sub_path":"searching_engine_inv.py","file_name":"searching_engine_inv.py","file_ext":"py","file_size_in_byte":2235,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"359794258","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Jun 27 13:39:13 2017\n\n@author: gbaechle\n\"\"\"\n\nimport numpy as np\nimport scipy as sp\nimport scipy.optimize\n\nN = 100\n\nH = np.random.rand(N, N) + 1j * np.random.rand(N, N)\nHr = np.real(H)\nHi = np.imag(H)\n\np = np.random.rand(N)\n\ni = np.abs(H @ p)**2\n\n#print(i)\n#print((Hr @ p)**2 + (Hi @ p)**2)\n\np_est = np.random.rand(N)\n\n\nfor n in range(10):\n \n p_est = np.linalg.lstsq( Hr, np.sqrt( i-(Hi @ p_est)**2 ) )[0]\n print(p_est)\n p_est = np.linalg.lstsq( Hi, np.sqrt( i-(Hr @ p_est)**2 ) )[0]\n print(p_est)\n \nprint('------------')\nprint(p)\n\ndiff = lambda x: (Hr @ x)**2 + (Hi @ x)**2 - i\ndiff = lambda x: np.abs(H @ x)**2 - i\np_est = sp.optimize.least_squares(diff, np.random.rand(N)).x\n\nprint(p_est)\n\n\n\n \n \n \n \n ","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":781,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"392579875","text":"from tkinter import *\nimport socket\nimport threading\n\n\nclass EchoServer:\n\tdef __init__(self, ip, port):\n\t\t# Basic echo server\n\t\t# Initial server setup\n\t\tself.connections = []\n\t\tself.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n\t\tself.sock.bind((ip, port))\n\t\tself.sock.listen(1)\n\n\tdef run(self):\n\t\twhile True:\n\t\t\tc, a = self.sock.accept()\n\t\t\tcThread = threading.Thread(target=self.handler, args=(c, a))\n\t\t\tcThread.daemon = True\n\t\t\tcThread.start()\n\t\t\tself.connections.append(c)\n\n\tdef handler(self, c, a):\n\t\t# Client handler\n\t\twhile True:\n\t\t\t# Echo the data recieved back\n\t\t\tdata = c.recv(1024)\n\t\t\tc.send(data)\n\n\nclass ChatServer:\n\tdef __init__(self, ip, port):\n\t\t# Basic chatting server\n\t\t# Initial server setup\n\t\tself.connections = []\n\t\tself.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n\t\tself.sock.bind((ip, port))\n\t\tself.sock.listen(1)\n\n\tdef run(self):\n\t\twhile True:\n\t\t\tc, a = self.sock.accept()\n\t\t\tcThread = threading.Thread(target=self.handler, args=(c, a))\n\t\t\tcThread.daemon = True\n\t\t\tcThread.start()\n\t\t\tself.connections.append(c)\n\n\tdef handler(self, c, a):\n\t\t# Client handler\n\t\twhile True:\n\t\t\t# Distribute chat from client to every other client\n\t\t\tdata = c.recv(1024)\n\t\t\tfor connection in self.connections:\n\t\t\t\t# Make sure that the chat is not echoing\n\t\t\t\tif connection != c:\n\t\t\t\t\t# Make sure that connection still exists\n\t\t\t\t\ttry:\n\t\t\t\t\t\tconnection.send(data)\n\t\t\t\t\texcept BrokenPipeError:\n\t\t\t\t\t\tconnection.close()\n\t\t\t\t\t\tself.connections.remove(connection)\n\n\nclass Displayer:\n\tdef __init__(self, porte):\n\t\t# Display results\n\t\tself.tk = Tk()\n\t\tself.tk.resizable(0, 0)\n\t\tself.tk.title(\"Main - I eat IP's for breakfast\")\n\n\t\t# List of ports\n\t\tself.lports = Frame(self.tk, bd=2, relief=SUNKEN)\n\t\tself.lports.pack()\n\t\tself.copen_label = Label(self.lports, text=\"Port's and Status's\", font=(\"Helvetica\", 20, \"bold\"))\n\t\tself.copen_label.pack(side=TOP)\n\t\tself.copen_scroll = Scrollbar(self.lports)\n\t\tself.copen_scroll.pack(side=RIGHT, fill=Y)\n\t\tself.copen = Listbox(self.lports, width=40, height=40, yscrollcommand=self.copen_scroll.set)\n\t\tself.copen.pack()\n\t\tself.copen_scroll.config(command=self.copen.yview)\n\t\tself.updatePortDisplay(porte)\n\n\t\t# List of connected clients at port\n\n\t\tself.tk.mainloop()\n\n\tdef updatePortDisplay(self, ports):\n\t\t# Update the ports on the list\n\t\tself.copen.delete(0, END)\n\t\tfor p, i in zip(ports, range(len(ports))):\n\t\t\tself.copen.insert(i, str(p[\"port\"]) + \": \" + p[\"status\"])\n\n\nclass Socketeer:\n\tdef __init__(self, ip=\"127.0.0.1\"):\n\t\t# IP checker\n\t\tself.ip = ip\n\n\t\t# Update data\n\t\tself.updateData()\n\n\tdef updateData(self):\n\t\tself.openP = self.checkStatuses()\n\n\tdef checkStatuses(self):\n\t\t# Check if port is open\n\t\tstatuses = []\n\n\t\tfor i in range(65536):\n\t\t\t# Try Connect\n\t\t\tsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n\t\t\tstatus = None\n\n\t\t\t# Obtain statuses\n\t\t\ttry:\n\t\t\t\tsock.bind((self.ip, i))\n\t\t\t\tstatus = \"open\"\n\n\t\t\texcept (IOError, OSError):\n\t\t\t\tstatus = \"closed\"\n\n\t\t\tfinally:\n\t\t\t\t# Append statuses and clean up\n\t\t\t\tstatuses.append({\"ip\": self.ip, \"port\": i, \"status\": status})\n\t\t\t\tsock.close()\n\n\t\t# Return statuses\n\t\treturn statuses\n\n\nclass Application:\n\tdef __init__(self):\n\t\tself.socketeer = Socketeer()\n\t\tself.displayer = Displayer(self.socketeer.openP)\n\n\nif __name__ == '__main__':\n\tapp = Application()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3275,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"25564270","text":"from __future__ import absolute_import\nfrom celery import shared_task\nfrom switch.celery import app\nfrom celery.utils.log import get_task_logger\n\nfrom django.shortcuts import render\n#from secondary.channels.vbs.models import *\n\nfrom django.db.models import Q\nimport hashlib, hmac, base64, string, random\nfrom decimal import Decimal\nfrom datetime import datetime\nimport base64, re, crypt\n\nfrom .models import *\nimport logging\nlgr = logging.getLogger('secondary.finance.crc')\n\t\nfrom keyczar import keyczar\nlocation = '/opt/kz'\ncrypter = keyczar.Crypter.Read(location)\n\nclass Wrapper:\n\tmask_card = lambda self, q: \"%s%s%s\" % (q[:4],\"\".join(['*' for v in range(len(q)-8)]),q[len(q)-4:]) #Show's first 4 digits and used to preview card\n\tmask_pan = lambda self, q: \"%s%s%s\" % (q[:6],\"\".join(['*' for v in range(len(q)-10)]),q[len(q)-4:]) #Shows first 6 digits and used in search\n\tdef cc_type(self,cc_number):\n\t\timport re\n\t\tAMEX_CC_RE = re.compile(r\"^3[47][0-9]{13}$\")\n\t\tVISA_CC_RE = re.compile(r\"^4[0-9]{12}(?:[0-9]{3})?$\")\n\t\tMASTERCARD_CC_RE = re.compile(r\"^5[1-5][0-9]{14}$\")\n\t\tDISCOVER_CC_RE = re.compile(r\"^6(?:011|5[0-9]{2})[0-9]{12}$\")\n\t\tDINERS_CC_RE = re.compile(r\"^3[068][0-9]{12}$\")\n\t\tJCB_CC_RE = re.compile(r\"^3[013][13589][2678][0-9]{12}$\")\n\n\t\tCC_MAP = {\"003\": AMEX_CC_RE, \"001\": VISA_CC_RE,\n\t\t\t \"002\": MASTERCARD_CC_RE, \"004\": DISCOVER_CC_RE, \"005\": DINERS_CC_RE, \"007\": JCB_CC_RE}\n\n\t\tfor type, regexp in CC_MAP.items():\n\t\t\tif regexp.match(str(cc_number)):\n\t\t\t\treturn type\n\t\treturn None\n\n\nclass System(Wrapper):\n\tdef card_present_details(self, payload, node_info):\n\t\ttry:\n\t\t\tgateway_profile = GatewayProfile.objects.get(id=payload['gateway_profile_id'])\n\n\t\t\tif 'currency' not in payload.keys():\n\t\t\t\tpayload['currency']= 'KES'\n\t\t\tif 'amount' in payload.keys():\n\t\t\t\tpayload['amount']= Decimal(payload['amount'])\n\t\t\telse:\n\t\t\t\tpayload['amount']= Decimal(0)\n\n\t\t\tif payload['entry_mode'] == 'contact':\n\t\t\t\ttrack_data = payload['card_track_data']\n\t\t\t\ttrack_data = track_data.replace('D','=')\n\t\t\t\ttrack_data = track_data.replace('F','?')\n\t\t\t\ttrack_data = ';%s'% track_data\n\t\t\t\tpayload['card_track_data'] = track_data\n\t\t\t\n\n\t\t\tchars = string.digits\n\t\t\trnd = random.SystemRandom()\n\t\t\tpin = ''.join(rnd.choice(chars) for i in range(0,4))\n\n\t\t\tpayload['merchant_descriptor'] = 'MIPAY*%s' % pin\n\t\t\tpayload['reference'] = 'REF%s' % pin\n\n\t\t\tpayload['response_status'] = '00'\n\t\t\tpayload['response'] = 'Card Present Details Captured'\n\t\texcept Exception as e:\n\t\t\tpayload['response'] = str(e)\n\t\t\tpayload['response_status'] = '96'\n\t\t\tlgr.info(\"Error on Card Present Details: %s\" % e)\n\t\treturn payload\n\n\n\tdef add_card_record(self, payload, node_info):\n\t\ttry:\n\t\t\tgateway_profile = GatewayProfile.objects.get(id=payload['gateway_profile_id'])\n\n\t\t\taccountNumber = str(payload['card_accountnumber']).replace(' ','')\n\t\t\tpan = self.mask_pan(accountNumber)\n\n\t\t\ttoken = crypter.Encrypt(accountNumber)\n\n\t\t\tcvNumber = str(payload['card_cvnumber']) if 'card_cvnumber' in payload.keys() else ''\n\n\t\t\tcardType = str(self.cc_type(accountNumber))\n\n\t\t\tif 'card_expirationdate' in payload.keys():\n\t\t\t\tcard_expirationDate = payload['card_expirationdate']\n\n\t\t\t\texpirationMonth = str(card_expirationDate.split('/')[0])\n\t\t\t\texpirationYear = str(card_expirationDate.split('/')[1])\n\t\t\telse:\n\t\t\t\texpirationMonth = str(payload['card_expirationmonth'])\n\t\t\t\texpirationYear = str(payload['card_expirationyear'])\n\n\t\t\texpiry_date = '20%s-%s-01' % (expirationYear,expirationMonth)\n\t\t\texpiry_date = datetime.strptime(expiry_date, \"%Y-%m-%d\").date()\n\n\t\t\tcard_record_status = CardRecordStatus.objects.get(name='CREATED')\n\t\t\tcard_type = CardType.objects.get(code=cardType)\n\n\n\t\t\tactivation_currency = Currency.objects.get(code=payload['currency'])\n\t\t\tactivation_amount = Decimal(payload['amount'])\n\t\t\tactivation_pin = crypt.crypt(str(payload['activation_pin']), str(gateway_profile.id))\n\n\n\t\t\tcard_record = CardRecord(status=card_record_status, card_number=self.mask_card(accountNumber), card_type=card_type,\\\n\t\t\t\t\t\tcard_expiry_date=expiry_date, token=token, gateway_profile=gateway_profile,\\\n\t\t\t\t\t\tpan=pan, activation_currency=activation_currency, activation_amount=activation_amount,\\\n\t\t\t\t\t\tactivation_pin=activation_pin)\n\n\t\t\tif CardRecord.objects.filter(gateway_profile=gateway_profile,status__name='ACTIVE').exists() == False:\n\t\t\t\tcard_record.is_default = True\n\n\t\t\tcard_record.save()\n\n\t\t\tpayload['pan'] = card_record.pan\n\n\t\t\tpayload['response_status'] = '00'\n\t\t\tpayload['response'] = 'Card Added'\n\t\texcept Exception as e:\n\t\t\tpayload['response'] = str(e)\n\t\t\tpayload['response_status'] = '96'\n\t\t\tlgr.info(\"Error on Add Card Record: %s\" % e)\n\t\treturn payload\n\n\tdef card_verification_details(self, payload, node_info):\n\t\ttry:\n\t\t\tgateway_profile = GatewayProfile.objects.get(id=payload['gateway_profile_id'])\n\n\t\t\taccountNumber = str(payload['card_accountnumber']).replace(' ','')\n\n\t\t\tpan = self.mask_pan(accountNumber)\n\t\t\tcard_record = CardRecord.objects.filter(pan=pan,status__name__in=['ACTIVE','CREATED'])\n\t\t\tif card_record.exists():\n\t\t\t\tif card_record.filter(gateway_profile=gateway_profile).exists():\n\t\t\t\t\tpayload['response_status'] = '26'\n\t\t\t\t\tpayload['response'] = 'Card Record Exists'\n\t\t\t\telse:\n\t\t\t\t\tpayload['response_status'] = '26'\n\t\t\t\t\tpayload['response'] = 'Card Record Added by a different Profile'\n\t\t\telse:\n\t\t\t\taccount = Account.objects.filter(account_type__deposit_taking=True, is_default=True,\\\n\t\t\t\t\t\tgateway_profile=gateway_profile)\n\n\t\t\t\tif account.exists():\n\t\t\t\t\tcurrency_code = account[0].account_type.product_item.currency.code\n\t\t\t\telse:\n\t\t\t\t\tcurrency_code = 'KES'\n\t\t\t\tcva = CardVerificationAmount.objects.get(currency__code=currency_code)\n\t\t\t\tamount = Decimal(random.uniform(float(cva.min_amount), float(cva.max_amount))).quantize(Decimal('.01'))\n\n\t\t\t\tpayload['ignore_avs_result'] = False\n\t\t\t\tpayload['ignore_cv_result'] = False\n\n\t\t\t\tpayload['pan'] = pan\n\t\t\t\tpayload['currency'] = currency_code\n\t\t\t\tpayload['amount'] = amount\n\t\t\t\tchars = string.digits\n\t\t\t\trnd = random.SystemRandom()\n\t\t\t\tpin = ''.join(rnd.choice(chars) for i in range(0,4))\n\n\t\t\t\tpayload['activation_pin'] = '%s' % pin\n\t\t\t\tpayload['merchant_descriptor'] = 'MIPAY*%s*CODE' % pin\n\t\t\t\tpayload['reference'] = 'MIPAY*%s*CODE' % pin\n\t\t\t\tpayload['response_status'] = '00'\n\t\t\t\tpayload['response'] = 'Card Captured'\n\t\texcept Exception as e:\n\t\t\tpayload['response'] = str(e)\n\t\t\tpayload['response_status'] = '96'\n\t\t\tlgr.info(\"Error on Card Verification Details: %s\" % e)\n\t\treturn payload\n\n\tdef get_cards(self, payload, node_info):\n\t\ttry:\n\n\t\t\taccountNumber = str(payload['card_accountnumber']).replace(' ','')\n\n\t\t\tpan = self.mask_pan(accountNumber)\n\t\t\tpayload['pan'] = pan\n\n\t\t\tpayload['response_status'] = '00'\n\t\t\tpayload['response'] = 'Card Captured'\n\t\texcept Exception as e:\n\t\t\tpayload['response_status'] = '96'\n\t\t\tlgr.info(\"Error on Get Card: %s\" % e)\n\t\treturn payload\n\nclass Registration(System):\n\tpass\n\nclass Trade(System):\n\tpass\n\nclass Payments(System):\n\tpass\n\n\nlgr = get_task_logger(__name__)\n#Celery Tasks Here\n","sub_path":"secondary/finance/crc/tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":6941,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"479287854","text":"\n'''This is part of Perf_NVMef Tool Kit\n This tool merge all the test data from host1, host2, appliance with CPU, MEM, FIO test results\\\n All in one CSV file called \"final.csv\" which can be later used for analysis across different builds'''\n\n# Author : Suman Debnath\n# E-Mail : suman.debnath@toshiba-tsip.com\n# Last Update: 13-March-2018\n# Version: 1.1\n\nimport os\nimport glob\nimport shutil\nimport time\nimport sys\nimport argparse\nimport json\nfrom collections import OrderedDict\nimport pandas as pd\nimport datetime\n\nimport warnings\nwarnings.filterwarnings('ignore')\n\n\ndef ParseArgs():\n \"\"\"Parse command line options into globals.\"\"\"\n global result_folder\n\n parser = argparse.ArgumentParser(\n formatter_class=argparse.RawDescriptionHelpFormatter,\n description=\"This is a part of KumoScale Performance QA Regression Testing tool. \\n\" \\\n \"The module will will move all the required file which would be used \\n\" \\\n \"for the data analysis and reporting, this should be used once a test \\n\" \\\n \"run is complete\",\n epilog=\"\"\"\n Requirements:\\n\n * Already completed a test run using \"nvmef_perf\" tool and the \"Result\" folder is available\n \\n\\n\n \"\"\")\n parser.add_argument(\"--resultFolder\", \"-f\", dest = \"result_folder\",\n help=\"Provide the full path of the Test Result Folder\", required=True)\n\n args = parser.parse_args()\n\n result_folder = args.result_folder\n\ndef csv_to_df(csv_file):\n\n df = pd.read_csv(csv_file)\n df[\"Timestamp\"] = pd.to_datetime(df.Timestamp, format=\"%Y-%m-%d_%H-%M-%S\")\n df[\"Stat_Start_Time\"] = df[\"Timestamp\"] - datetime.timedelta(seconds=110)\n df[\"Stat_End_Time\"] = df[\"Timestamp\"] - datetime.timedelta(seconds=10)\n df.index = pd.RangeIndex(1, len(df.index)+1)\n\n df.columns = [i.strip() for i in df.columns]\n\n return df\n\ndef merg_df(df1, df2):\n\n frames = [df1, df2]\n merg = pd.concat(frames, axis=0)\n merg.index = pd.RangeIndex(1, len(merg.index)+1)\n\n return merg\n\ndef combine_df(df1, df2):\n\n combine = df1.copy()\n #row_index = df1.index\n\n prams_avg = [\"Read Latency (us)\", \"Write Latency (us)\"]\n prams_sum = [\"IOPS\", \"Bandwidth (MB/s)\"]\n for p in prams_sum:\n combine[p] = combine[p] + df2[p]\n for p in prams_avg:\n combine[p] = (combine[p] + df2[p]) / 2\n\n combine[\"Host2_CPU_Utilization\"] = df2[\"Host2_CPU_Utilization\"]\n combine[\"Host2_Memory_Utilization\"] = df2[\"Host2_Memory_Utilization\"]\n\n return combine\n\ndef df_to_csv(df, file_name):\n\n df.to_csv(file_name,index=False)\n file_path = os.path.abspath(file_name)\n\n return file_path\n\ndef json_to_df(json_file):\n\n df_stat = pd.read_json(json_file, orient='index')\n df_stat.columns = [\"CPU_Utilization\", \"Memory_Utilization\"]\n df_stat[\"Timestamp\"] = pd.to_datetime(df_stat.index, format=\"%Y-%m-%d_%H-%M-%S\")\n #df_stat.index = df_stat[\"Timestamp\"]\n df_stat.index = pd.RangeIndex(1, len(df_stat.index)+1)\n\n\n return df_stat\n\ndef file_scanner(list_files):\n\n global host1_tput_file, host1_lat_file, host2_tput_file, stat_appliance_lat_file\n global stat_appliance_tput_file, stat_host1_lat_file, stat_host1_tput_file, stat_host2_tput_file\n\n host1_files = []\n\n for file in list_files:\n _file = os.path.basename(file)\n if _file.startswith(\"ezfio_tests_\"):\n if \"host1\" in _file.split(\"_\"):\n host1_files.append(file)\n else:\n host2_tput_file = file\n elif _file.startswith(\"lat_appliance\"):\n stat_appliance_lat_file = file\n elif _file.startswith(\"tput_appliance\"):\n stat_appliance_tput_file = file\n elif _file.startswith(\"lat_host1\"):\n stat_host1_lat_file = file\n elif _file.startswith(\"tput_host1\"):\n stat_host1_tput_file = file\n elif _file.startswith(\"tput_host2\"):\n stat_host2_tput_file = file\n\n _host1_files = {}\n for file in host1_files:\n _file = os.path.basename(file)\n _t = _file.split(\"_\")[2].split(\"GB\")[0]\n _host1_files[int(_t)] = file\n\n lat, tput = sorted(_host1_files)\n host1_tput_file = _host1_files[tput]\n host1_lat_file = _host1_files[lat]\n\ndef cpu_mem_avg_calculator(stat_df, start_time, end_time):\n\n c_util, m_util = stat_df[(stat_df[\"Timestamp\"] >= start_time) & (stat_df[\"Timestamp\"] <= end_time)].mean()\n return int(c_util), int(m_util)\n\ndef add_cpu_mem_stat(master_df, stat_df, host_name):\n\n cpu_util = []\n mem_util = []\n for _, row in master_df.iterrows():\n start, end = row[\"Stat_Start_Time\"], row[\"Stat_End_Time\"]\n c, m = cpu_mem_avg_calculator(stat_df, start, end)\n cpu_util.append(c)\n mem_util.append(m)\n\n cpu_col_name = host_name + \"_CPU_Utilization\"\n mem_col_name = host_name + \"_Memory_Utilization\"\n master_df[cpu_col_name] = cpu_util\n master_df[mem_col_name] = mem_util\n\n return master_df\n\nresult_folder = \"\"\n\nhost1_tput_file = \"\"\nhost1_lat_file = \"\"\nhost2_tput_file = \"\"\nstat_appliance_lat_file = \"\"\nstat_appliance_tput_file = \"\"\nstat_host1_lat_file = \"\"\nstat_host1_tput_file = \"\"\nstat_host2_tput_file = \"\"\n\n\n\nif __name__ == \"__main__\":\n\n ParseArgs()\n\n # Creating a new folder called \"post_run\" under the same \"result_folder\"\n new_folder_path = os.path.join(result_folder, \"post_run\")\n os.system(\"rm -rf {}\".format(new_folder_path))\n\n #time.sleep(2)\n os.makedirs(new_folder_path)\n\n # Filtering the required files from Host1, Host2 and Appliance\n files_to_copy = []\n for root, dirs, files in os.walk(result_folder, topdown=False):\n for name in files:\n if name.startswith(\"ezfio_tests_\") or name.startswith(\"host\") or name.startswith(\"lat_\") or name.startswith(\"tput_\"):\n files_to_copy.append((os.path.join(root, name)))\n\n # Copying all the files to \"post_run\" folder\n for f in files_to_copy:\n shutil.copy(f, new_folder_path)\n\n # Printing the path of the new_folder and its file contents\n print(\"*\"*120)\n print(\"This is the folder path which contains all the files : {}\".format(new_folder_path))\n print(\"*\"*120)\n\n print(\"Here are the files: \")\n print(\"*\"*120)\n\n list_files = []\n for f in (os.listdir(new_folder_path)):\n file_path = os.path.join(new_folder_path, f)\n print(file_path)\n list_files.append(file_path)\n\n print(\"*\"*120)\n print(\"Computing the Data Collection for IOPS, Throughput, Latency, CPU/Mem Utilization for Host1, Host2 and Appliance\")\n print(\"*\"*120)\n\n # Identifying the test files for Host1, Host2 and Appliance\n\n file_scanner(list_files)\n\n # Loading the all the CSV files to DataFrame\n\n # Loading IO,TPUT and Latency Test Data for Host1\n df_host1_tput = csv_to_df(host1_tput_file)\n df_host1_lat = csv_to_df(host1_lat_file)\n\n # Loading IO,TPUT Test Data for Host2\n df_host2_tput = csv_to_df(host2_tput_file)\n\n # Loading the CPU and Mem stats for Host1\n df_stat_host1_lat = json_to_df(stat_host1_lat_file)\n df_stat_host1_tput = json_to_df(stat_host1_tput_file)\n\n # Loading the CPU and Mem stats for Host2\n df_stat_host2_tput = json_to_df(stat_host2_tput_file)\n\n # Loading the CPU and Mem stats for Appliance\n df_stat_appliance_lat = json_to_df(stat_appliance_lat_file)\n df_stat_appliance_tput = json_to_df(stat_appliance_tput_file)\n\n # Calculating the CPU and Memory Utilization and adding to the DataFrame\n\n df_host1_lat = add_cpu_mem_stat(df_host1_lat, df_stat_host1_lat, \"Host1\")\n df_host1_tput = add_cpu_mem_stat(df_host1_tput, df_stat_host1_tput, \"Host1\")\n df_host1_lat = add_cpu_mem_stat(df_host1_lat, df_stat_appliance_lat, \"Appliance\")\n df_host1_tput = add_cpu_mem_stat(df_host1_tput, df_stat_appliance_tput, \"Appliance\")\n df_host2_tput = add_cpu_mem_stat(df_host2_tput, df_stat_host2_tput, \"Host2\")\n\n # Combining Host1 and Host2 Results after CPU and Memory Calculation\n\n df = combine_df(df1=df_host1_tput, df2=df_host2_tput)\n\n # Adding the Latency Results to the final DataFrame\n\n df_final = merg_df(df, df_host1_lat)\n\n # Saving the final DataFrame to a CSV File\n\n final_csv_file_path = result_folder + \"/final.csv\"\n df_to_csv(df_final, final_csv_file_path)\n\n # Copying the same file inside the \"post_run\" folder as well\n\n shutil.copy(final_csv_file_path, new_folder_path)\n\n # Printing the path of the final.csv\n print(\"Here is the path of the final CSV :\")\n print(final_csv_file_path)\n print(\"*\"*120)\n","sub_path":"perf_baselines/post_test_data_collector.py","file_name":"post_test_data_collector.py","file_ext":"py","file_size_in_byte":8508,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"434910122","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nfrom typing import Any\n# pylint:disable=no-member\n\nclass SequenceUnlikelihoodLoss(nn.Module):\n def __init__(self, padding_idx=50257, rank_alpha=0.2, candidate_type=\"prev_context\", debug=False):\n super().__init__()\n #tokenizer.encoder[\"[PAD]\"]\n self.rank_alpha = rank_alpha\n self.debug = debug\n self.candidate_type = candidate_type\n self.padding_idx = padding_idx\n\n def forward(self, logits, targets):\n # ============ unlikelihood loss ============ #\n # -- mle loss\n # shape : (batch * sequence_length, num_classes) \n target = targets \n logits_flat = logits.view(-1, logits.size(-1))\n # shape : (batch * sequence_length, num_classes) \n lprobs = F.log_softmax(logits_flat, dim=-1)\n # lprobs = lprobs.view(-1, lprobs.size(-1))\n \n # shape : (batch * max_len, 1) \n target = target.view(-1).long()\n\n true_token_lprobs = F.nll_loss(\n lprobs,\n target,\n ignore_index=self.padding_idx,\n reduction='none',\n )\n mle_loss = true_token_lprobs.sum()\n\n with torch.no_grad():\n if self.candidate_type == 'prev_context':\n ctx_cands = target.unsqueeze(0).expand(target.size(0), target.size(0)) #torch.Size([64, 64])\n ctx_cands_ = (ctx_cands.tril(-1) + self.padding_idx)\n ctx_cands_ = ctx_cands_ * ctx_cands_.triu()\n ctx_cands = ctx_cands.tril(-1) + ctx_cands_\n\n # Don't include the target for that timestep as a negative target.\n ctx_cands = ctx_cands.masked_fill(ctx_cands == target.unsqueeze(1), self.padding_idx)\n ctx_cands = ctx_cands.masked_fill(ctx_cands == (self.padding_idx**2), self.padding_idx)\n negative_targets = torch.zeros_like(lprobs).scatter_(1, ctx_cands, 1)\n else:\n raise NotImplementedError('candidate type %s' % self.candidate_type)\n \n one_minus_probs = torch.clamp((1.0 - lprobs.exp()), min=1e-5)\n\n custom_loss = -torch.log(one_minus_probs)*negative_targets\n custom_loss = custom_loss.sum()\n\n\n loss = mle_loss + self.rank_alpha * custom_loss\n\n # =================\n return loss\n\n","sub_path":"UnlikelihoodLoss.py","file_name":"UnlikelihoodLoss.py","file_ext":"py","file_size_in_byte":2372,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"525753161","text":"from flask import *\nimport mlab\nfrom models.service import Service\nfrom models.customer import Customer\n\napp = Flask(__name__)\n\nmlab.connect()\n\n@app.route('/')\ndef index(): \n return render_template('index.html')\n\n@app.route('/search')\ndef search():\n all_service = Service.objects() \n return render_template('search.html',all_service = all_service)\n\n@app.route('/detail/<service_id>')\ndef detail(service_id):\n service = Service.objects().with_id(service_id)\n return render_template('detail.html', service = service )\n\n@app.route('/admin')\ndef admin():\n all_service = Service.objects()\n return render_template(\"admin.html\", all_service = all_service)\n\n# @app.route('/delete/<service_id>')\n# def delete(service_id):\n# service_to_delete = Service.objects().with_id(service_id)\n# if service_to_delete is None:\n# return \"Service not found\"\n# else: \n# service_to_delete.delete()\n# return redirect(url_for('admin'))\n\n@app.route('/new', methods = ['GET','POST'])\ndef create():\n if request.method == 'GET':\n return render_template(\"new.html\")\n elif request.method == 'POST':\n\n form = request.form\n name = form['name']\n yob = form['yob']\n address = form['address']\n gender = form['gender']\n\n new = Service(\n name = name,\n yob = yob,\n address = address,\n gender = gender\n )\n new.save()\n return redirect(url_for('admin'))\n\n\nif __name__ == '__main__':\n # app.run(host=\"127.0.0.1\", port=5000, debug=True)\n app.run(debug=True)\n ","sub_path":"Web03/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1604,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"429890593","text":"\"\"\"Messenger server\"\"\"\r\n# python3 server.py -p 8888\r\n\r\nimport sys\r\nimport json\r\nimport logging\r\nimport time\r\nimport select\r\nimport logs.server_log_config\r\nfrom socket import socket, AF_INET, SOCK_STREAM\r\nfrom utility import log\r\n\r\n\r\nLOGGER = logging.getLogger('server')\r\n\r\n\r\n@log('server')\r\ndef make_response():\r\n \"\"\"Create response message\"\"\"\r\n LOGGER.debug('Response created')\r\n msg = {\r\n \"response\": 200,\r\n \"alert\": \"OK\"\r\n }\r\n return json.dumps(msg)\r\n\r\n\r\ndef run_server():\r\n \"\"\"Start server\"\"\"\r\n LOGGER.debug('Start server')\r\n clients = []\r\n if len(sys.argv) > 0:\r\n for index, param in enumerate(sys.argv):\r\n if param == '-p':\r\n port = int(sys.argv[index + 1])\r\n elif param == '-a':\r\n argv_addr = sys.argv[index + 1]\r\n server_socket = socket(AF_INET, SOCK_STREAM)\r\n try:\r\n server_socket.bind(('', port))\r\n LOGGER.debug('Socket binding success')\r\n except AttributeError:\r\n LOGGER.error('Socket binding failed')\r\n server_socket.listen(5)\r\n server_socket.settimeout(0.2)\r\n\r\n while True:\r\n client, addr = server_socket.accept()\r\n data = client.recv(1000000)\r\n json_msg = make_response()\r\n client.send(json_msg.encode('utf-8'))\r\n client.close()\r\n print('Сообщение: ', data.decode('utf-8'), ', было отправлено клиентом: ', addr)\r\n\r\n\r\ndef mainloop():\r\n address = ('', 10000)\r\n clients = []\r\n s = socket(AF_INET, SOCK_STREAM)\r\n s.bind(address)\r\n s.listen(5)\r\n s.settimeout(0.2)\r\n while True:\r\n try:\r\n conn, addr = s.accept()\r\n except OSError as e:\r\n pass\r\n else:\r\n print(\"Получен запрос на соединение от %s\" % str(addr))\r\n clients.append(conn)\r\n finally:\r\n wait = 10\r\n r = []\r\n w = []\r\n try:\r\n r, w, e = select.select(clients, clients, [], wait)\r\n except:\r\n pass\r\n requests = read_requests(r, clients)\r\n if requests:\r\n write_responses_to_all(requests, w, clients)\r\n\r\n\r\ndef read_requests(r_clients, all_clients):\r\n responses = {}\r\n for sock in r_clients:\r\n try:\r\n data = sock.recv(1024).decode('utf-8')\r\n responses[sock] = data\r\n except:\r\n print('Клиент {} {} отключился'.format(sock.fileno(), sock.getpeername()))\r\n all_clients.remove(sock)\r\n return responses\r\n\r\n\r\ndef write_responses(requests, w_clients, all_clients):\r\n for sock in w_clients:\r\n if sock in requests:\r\n try:\r\n resp = requests[sock].encode('utf-8')\r\n sock.send(resp.upper())\r\n except:\r\n print('Клиент {} {} отключился'.format(sock.fileno(), sock.getpeername()))\r\n sock.close()\r\n all_clients.remove(sock)\r\n\r\n\r\ndef write_responses_to_all(requests, w_clients, all_clients):\r\n for sock in w_clients:\r\n if sock in requests:\r\n try:\r\n resp = requests[sock].encode('utf-8')\r\n for s in all_clients:\r\n s.send(resp)\r\n except:\r\n print('Клиент {} {} отключился'.format(sock.fileno(), sock.getpeername()))\r\n sock.close()\r\n all_clients.remove(sock)\r\n\r\n\r\nif __name__ == '__main__':\r\n # run_server()\r\n print('Server running...')\r\n mainloop()\r\n","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":3598,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"311336330","text":"import markdown\nfrom django.shortcuts import get_object_or_404\nfrom django.utils.text import slugify\nfrom django.views.generic import ListView, DetailView\nfrom markdown.extensions.toc import TocExtension\n\nfrom .models import Project, Category, Tag\n\nMONTH_NAME_MAP = {\n 1: 'Jan',\n 2: 'Feb',\n 3: 'Mar',\n 4: 'Apr',\n 5: 'May',\n 6: 'June',\n 7: 'July',\n 8: 'Aug',\n 9: 'Sep',\n 10: 'Oct',\n 11: 'Nov',\n 12: 'Dec'\n}\n\n\nclass ProjectDetailView(DetailView):\n model = Project\n template_name = 'myprojects/detail.html'\n context_object_name = 'project'\n queryset = Project.objects.all()\n\n def get(self, request, *args, **kwargs):\n response = super(ProjectDetailView, self).get(request, *args, **kwargs)\n self.object.increase_views()\n return response\n\n def get_object(self, queryset=None):\n post = super(ProjectDetailView, self).get_object(queryset=None)\n md = markdown.Markdown(extensions=[\n 'markdown.extensions.extra',\n 'markdown.extensions.codehilite',\n TocExtension(slugify=slugify)\n ])\n post.body = md.convert(post.body)\n post.toc = md.toc\n return post\n\n\nclass IndexView(ListView):\n model = Project\n template_name = 'myprojects/index.html'\n context_object_name = 'project_list'\n paginate_by = 4\n title = 'Projects | Jian Yang'\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n paginator = context.get('paginator')\n page = context.get('page_obj')\n is_paginated = context.get('is_paginated')\n pagination_data = self.pagination_data(paginator, page, is_paginated)\n context.update(pagination_data)\n context.update({\n 'title': self.title,\n })\n return context\n\n @staticmethod\n def pagination_data(paginator, page, is_paginated):\n if not is_paginated:\n return {}\n\n left = []\n right = []\n left_has_more = False\n right_has_more = False\n first = False\n last = False\n\n page_number = page.number\n total_pages = paginator.num_pages\n page_range = paginator.page_range\n\n if page_number != 1:\n left = page_range[(page_number - 3)\n if (page_number - 3) > 0 else 0:page_number - 1]\n if left[0] > 2:\n left_has_more = True\n if left[0] > 1:\n first = True\n\n if page_number != total_pages:\n right = page_range[page_number:page_number + 2]\n if right[-1] < total_pages - 1:\n right_has_more = True\n if right[-1] < total_pages:\n last = True\n\n data = {\n 'left': left,\n 'right': right,\n 'left_has_more': left_has_more,\n 'right_has_more': right_has_more,\n 'first': first,\n 'last': last\n }\n return data\n\n\nclass ArchivesView(IndexView):\n def get_queryset(self):\n year = self.kwargs.get('year')\n self.title = str(year) + ' | Jian Yang'\n return super(ArchivesView, self).get_queryset().filter(created_time__year=year)\n\n\nclass CategoryView(IndexView):\n def get_queryset(self):\n cate = get_object_or_404(Category, pk=self.kwargs.get('pk'))\n self.title = cate.name + ' | Jian Yang'\n return super(CategoryView, self).get_queryset().filter(category=cate)\n\n\nclass TagView(IndexView):\n def get_queryset(self):\n tag = get_object_or_404(Tag, pk=self.kwargs.get('pk'))\n self.title = tag.name + ' | Jian Yang'\n return super(TagView, self).get_queryset().filter(tags=tag)\n","sub_path":"myprojects/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3709,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"34196782","text":"import os\nimport pandas as pd\n\n\nclass Common:\n @staticmethod\n def nowtime():\n \"\"\"\n 今の時間をstr形式で返すだけの関数\n :return:\n \"\"\"\n from datetime import datetime\n return str(datetime.now().strftime('%Y%m%d%H%M%S'))\n\n def extract_all_combination(self, _df: pd.DataFrame, _combination_pare_column: list):\n \"\"\"\n データフレームの指定した列内に出現する値の総組合せを配列で返す機能。\n まだ試作段階。\n :param _df:\n :param _combination_pare_column:\n :return:\n \"\"\"\n import itertools\n num_of_param = len(_combination_pare_column)\n return_ary = []\n if num_of_param == 2:\n p1 = self.remove_duplication(_df[_combination_pare_column[0]].values)\n p2 = self.remove_duplication(_df[_combination_pare_column[1]].values)\n for _1, _2 in itertools.product(p1, p2):\n return_ary.append([_1, _2])\n elif num_of_param == 3:\n p1 = self.remove_duplication(_df[_combination_pare_column[0]].values)\n p2 = self.remove_duplication(_df[_combination_pare_column[1]].values)\n p3 = self.remove_duplication(_df[_combination_pare_column[2]].values)\n for _1, _2, _3 in itertools.product(p1, p2, p3):\n return_ary.append([_1, _2, _3])\n elif num_of_param == 4:\n p1 = self.remove_duplication(_df[_combination_pare_column[0]].values)\n p2 = self.remove_duplication(_df[_combination_pare_column[1]].values)\n p3 = self.remove_duplication(_df[_combination_pare_column[2]].values)\n p4 = self.remove_duplication(_df[_combination_pare_column[3]].values)\n for _1, _2, _3, _4 in itertools.product(p1, p2, p3, p4):\n return_ary.append([_1, _2, _3, _4])\n elif num_of_param == 5:\n p1 = self.remove_duplication(_df[_combination_pare_column[0]].values)\n p2 = self.remove_duplication(_df[_combination_pare_column[1]].values)\n p3 = self.remove_duplication(_df[_combination_pare_column[2]].values)\n p4 = self.remove_duplication(_df[_combination_pare_column[3]].values)\n p5 = self.remove_duplication(_df[_combination_pare_column[4]].values)\n for _1, _2, _3, _4, _5 in itertools.product(p1, p2, p3, p4, p5):\n return_ary.append([_1, _2, _3, _4, _5])\n else:\n print('The number of params you specified is too many. Reduce less than 5.')\n return None\n return return_ary # type: list\n\n @staticmethod\n def range_check(_param, _min, _max):\n \"\"\"\n 変数が指定された範囲内にいるか確認する機能\n :param _param:\n :param _min:\n :param _max:\n :return:\n \"\"\"\n if _min <= _param <= _max:\n return True\n else:\n return False\n\n @staticmethod\n def folder_check(_path):\n \"\"\"\n フォルダの存在確認をしてくれる機能\n :param _path: 確認したいフォルダのパス\n :return:\n \"\"\"\n if not os.path.isdir(_path):\n try:\n os.mkdir(_path)\n print('[common.py][folder_check] Create -> ' + _path)\n return True\n except:\n print('[common.py][Warn] Cannot create folder. ' + _path)\n return False\n else:\n return True\n\n @staticmethod\n def remove_duplication(_list: list):\n \"\"\"\n リストの重複を削除する機能\n :param _list: 重複を削除したい配列\n :return: 重複を削除した配列\n \"\"\"\n seen = set()\n seen_add = seen.add\n return [x for x in _list if x not in seen and not seen_add(x)]\n\n @staticmethod\n def file_exist_check(_file_path):\n \"\"\"\n ファイルが存在するかどうか確認し、存在するならファイル名の末尾にカウンター文字を付与して返す機能\n e.g.\n hoge.txt を_file_pathに入力し、すでにhoge.txtが存在していれば hoge_(1).txtを返す。\n :param _file_path: 存在確認したいファイルパス\n :return: 保存して大丈夫なファイルパス\n \"\"\"\n if os.path.exists(_file_path):\n base = os.path.dirname(_file_path)\n name = os.path.basename(_file_path).split('.')\n counter = 1\n cwd = os.getcwd()\n while os.path.exists(os.path.join(cwd, base, ''.join(name[0:-1]) + '_(' + str(counter) + ').' + str(name[-1]))):\n counter += 1\n return os.path.join(cwd, base, ''.join(name[0:-1]) + '_(' + str(counter) + ').' + str(name[-1]))\n else:\n return _file_path\n","sub_path":"common.py","file_name":"common.py","file_ext":"py","file_size_in_byte":4847,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"221295514","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models\nfrom django.contrib.auth.models import User\n\nimport uuid\n\n# Create your models here.\nclass AuthenticationManager(models.Manager):\n\n\tdef create_or_get_auth(self, user, token=None):\n\t\tauth = None\n\n\t\tif user and token:\n\t\t\tauth = Authentication.objects().filter(user=user, token=token).first()\n\n\t\tif not auth:\n\t\t\tgenerated = str(uuid.uuid4())\n\t\t\tauth = self.create(token=generated, user=user, status=True)\n\n\t\treturn auth;\n\n\tdef expire_token(self, token):\n\t\tresult = False\n\n\t\ttry:\n\t\t\tauth = Authentication.objects.get(token=token)\n\t\t\tif auth and auth.status:\n\t\t\t\t# Token exists in DB and valid\n\t\t\t\tauth.status = False\n\t\t\t\tauth.save()\n\t\t\t\tresult = True\n\t\texcept self.model.DoesNotExist:\n\t\t\t# Token does not exist in DB - continue\n\t\t\tpass\n\t\t\t\n\t\treturn result\n\n\tdef get_user_from_token(self, token):\n\t\tuser = None\n\n\t\ttry:\n\t\t\tauth = Authentication.objects.get(token=token)\n\t\t\tif auth and auth.status:\n\t\t\t\t# Token exists in DB and valid\n\t\t\t\tuser = auth.user\n\t\texcept self.model.DoesNotExist:\n\t\t\t# Token does not exist in DB - continue\n\t\t\tpass\n\n\t\treturn user\n\n\nclass Authentication(models.Model):\n\ttoken = models.UUIDField(max_length=36, default=uuid.uuid4, editable=False)\n\tuser = models.ForeignKey(User, on_delete=models.CASCADE)\n\tstatus = models.BooleanField(default=False)\n\t\n\tobjects = AuthenticationManager()\n\n\tdef __str__(self):\n\t\treturn \"{} | {} | {}\".format(self.user, self.token, self.status)\n","sub_path":"src/service/encrypted/authentication/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1485,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"602211100","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\nfrom django.conf import settings\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n migrations.swappable_dependency(settings.AUTH_USER_MODEL),\n ('rango', '0001_initial'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='ForumAnswer',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('answer', models.TextField()),\n ('date', models.DateTimeField(auto_now_add=True)),\n ],\n options={\n },\n bases=(models.Model,),\n ),\n migrations.CreateModel(\n name='ForumQuestion',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('question', models.TextField()),\n ('date', models.DateTimeField(auto_now_add=True)),\n ],\n options={\n },\n bases=(models.Model,),\n ),\n migrations.CreateModel(\n name='UserProfile',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('reg', models.CharField(unique=True, max_length=12)),\n ('website', models.URLField(blank=True)),\n ('picture', models.ImageField(upload_to=b'profile_images', blank=True)),\n ('user', models.OneToOneField(to=settings.AUTH_USER_MODEL)),\n ],\n options={\n },\n bases=(models.Model,),\n ),\n migrations.AddField(\n model_name='forumquestion',\n name='user',\n field=models.ForeignKey(to='rango.UserProfile'),\n preserve_default=True,\n ),\n migrations.AddField(\n model_name='forumanswer',\n name='question',\n field=models.ForeignKey(to='rango.ForumQuestion'),\n preserve_default=True,\n ),\n migrations.AddField(\n model_name='forumanswer',\n name='user',\n field=models.ForeignKey(to='rango.UserProfile'),\n preserve_default=True,\n ),\n ]\n","sub_path":"src/rango/migrations/0002_auto_20150227_1740.py","file_name":"0002_auto_20150227_1740.py","file_ext":"py","file_size_in_byte":2364,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"278742610","text":"class CoffeeMachine:\r\n water = 400\r\n milk = 540\r\n coffee_beans = 120\r\n disposable_cups = 9\r\n money = 550\r\n\r\n def total_supplies(self):\r\n print(f'''The coffee machine has:\r\n {self.water} ml of water\r\n {self.milk} ml of milk\r\n {self.coffee_beans} g of coffee beans\r\n {self.disposable_cups} of disposable cups\r\n ${self.money} of money''')\r\n\r\n def __init__(self):\r\n while True:\r\n action = input('Write action (buy, fill, take, remaining, exit) : ')\r\n if action == 'buy':\r\n coffee_type = input('What do you want to buy? (1 - espresso, 2 - latte, 3 - cappuccino, back) : ')\r\n if coffee_type == '1':\r\n if self.water < 250:\r\n print('Sorry, not enough water!')\r\n elif self.coffee_beans < 16:\r\n print('Sorry, not enough coffee beans!')\r\n elif self.disposable_cups < 1:\r\n print('Sorry, not enough disposable cups!')\r\n else:\r\n print(\"I have enough resources, making you a coffee!\")\r\n self.water -= 250\r\n self.coffee_beans -= 16\r\n self.disposable_cups -= 1\r\n self.money += 4\r\n elif coffee_type == '2':\r\n if self.water < 350:\r\n print('Sorry, not enough water!')\r\n elif self.milk < 75:\r\n print('Sorry, not enough milk!')\r\n elif self.coffee_beans < 20:\r\n print('Sorry, not enough coffee beans!')\r\n elif self.disposable_cups < 1:\r\n print('Sorry, not enough disposable cups!')\r\n else:\r\n print(\"I have enough resources, making you a coffee!\")\r\n self.water -= 350\r\n self.milk -= 75\r\n self.coffee_beans -= 20\r\n self.disposable_cups -= 1\r\n self.money += 7\r\n elif coffee_type == '3':\r\n if self.water < 200:\r\n print('Sorry, not enough water!')\r\n elif self.milk < 100:\r\n print('Sorry, not enough milk!')\r\n elif self.coffee_beans < 12:\r\n print('Sorry, not enough coffee beans!')\r\n elif self.disposable_cups < 1:\r\n print('Sorry, not enough disposable cups!')\r\n else:\r\n print(\"I have enough resources, making you a coffee!\")\r\n self.water -= 200\r\n self.milk -= 100\r\n self.coffee_beans -= 12\r\n self.disposable_cups -= 1\r\n self.money += 6\r\n elif coffee_type == 'back':\r\n continue\r\n elif action == 'fill':\r\n fill_water = int(input('Write how many ml of water you want to add : '))\r\n fill_milk = int(input('Write how many ml of milk you want to add : '))\r\n fill_coffee_beans = int(input('Write how many grams of coffee beans you want to add : '))\r\n fill_disposable_cups = int(input('Write how many disposable coffee cups you want to add : '))\r\n self.water += fill_water\r\n self.milk += fill_milk\r\n self.coffee_beans += fill_coffee_beans\r\n self.disposable_cups += fill_disposable_cups\r\n elif action == 'take':\r\n print(f'I gave you ${self.money}')\r\n self.money = 0\r\n elif action == 'remaining':\r\n CoffeeMachine.total_supplies(self)\r\n elif action == 'exit':\r\n break\r\n\r\n\r\nCoffeeMachine()","sub_path":"Coffee Machine v2 Enhanced.py","file_name":"Coffee Machine v2 Enhanced.py","file_ext":"py","file_size_in_byte":3969,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"566120186","text":"# -*- coding: utf-8 -*-\n\nimport xlrd\nimport os\nimport unicodedata\nimport re\nimport csv\nimport time\nimport sys\nimport datetime\nimport platform\nimport pytesseract as ocr\nimport json\nimport PyPDF2\nimport warnings\nimport slate3k as slate\nimport logging\nfrom PIL import Image\nimport xmltodict as xmldict\n\n# pra ignorar erros que dá no momento de ler um PDF por exemplo\nwarnings.filterwarnings(\"ignore\")\nlogging.propagate = False \nlogging.getLogger().setLevel(logging.ERROR)\n\nfileDir = os.path.dirname(__file__)\nsys.path.append(fileDir)\n\nimport funcoesUteis\n\ndef leXls_Xlsx(arquivo, nameSheetToFilter='filterAll'):\n lista_dados = []\n dados_linha = []\n\n if os.path.getsize(arquivo) > 0:\n try:\n arquivo = xlrd.open_workbook(arquivo, logfile=open(os.devnull, 'w'))\n except Exception:\n try:\n arquivo = xlrd.open_workbook(arquivo, logfile=open(os.devnull, 'w'), encoding_override='Windows-1252')\n except Exception:\n return []\n\n # guarda todas as planilhas que tem dentro do arquivo excel\n planilhas = arquivo.sheet_names()\n\n # lê cada planilha\n for sheetName in planilhas:\n\n # pega os dados da planilha\n planilha = arquivo.sheet_by_name(sheetName)\n\n # continue only if name sheet equal the name filter of argument\n if funcoesUteis.treatTextField(sheetName) == funcoesUteis.treatTextField(nameSheetToFilter) or nameSheetToFilter == 'filterAll':\n # pega a quantidade de linha que a planilha tem\n max_row = planilha.nrows\n # pega a quantidade de colunca que a planilha tem\n max_column = planilha.ncols\n\n # lê cada linha e coluna da planilha e imprime\n for i in range(0, max_row):\n\n valor_linha = planilha.row_values(rowx=i)\n\n # ignora linhas em branco\n if valor_linha.count(\"\") == max_column:\n continue\n\n # lê as colunas\n for j in range(0, max_column):\n\n # as linhas abaixo analisa o tipo de dado que está na planilha e retorna no formato correto, sem \".0\" para números ou a data no formato numérico\n tipo_valor = planilha.cell_type(rowx=i, colx=j)\n valor_celula = funcoesUteis.removerAcentosECaracteresEspeciais(str(planilha.cell_value(rowx=i, colx=j)))\n if tipo_valor == 2:\n valor_casas_decimais = valor_celula.split('.')\n valor_casas_decimais = valor_casas_decimais[1]\n try:\n if int(valor_casas_decimais) == 0:\n valor_celula = valor_celula.split('.')\n valor_celula = valor_celula[0]\n except Exception:\n valor_celula = valor_celula\n elif tipo_valor == 3:\n valor_celula = float(planilha.cell_value(rowx=i, colx=j))\n valor_celula = xlrd.xldate.xldate_as_datetime(valor_celula, datemode=0)\n valor_celula = valor_celula.strftime(\"%d/%m/%Y\")\n\n # retira espaços e quebra de linha da célula\n valor_celula = str(valor_celula).strip().replace('\\n', '')\n\n # adiciona o valor da célula na lista de dados_linha\n dados_linha.append(valor_celula)\n\n # copia os dados da linha para o vetor de lista_dados\n lista_dados.append(dados_linha[:])\n\n # limpa os dados da linha para ler a próxima\n dados_linha.clear()\n else:\n continue\n # retorna uma lista dos dados\n return lista_dados\n\ndef readCsv(arquivo,separadorCampos=';'):\n lista_dados = []\n dados_linha = []\n \n nome_arquivo = os.path.basename(arquivo)\n\n with open(arquivo, 'rt') as csvfile:\n csvreader = csv.reader(csvfile, delimiter=separadorCampos)\n for row in csvreader:\n \n existe_valor_linha = \"\"\n for campo in row:\n valor_celula = funcoesUteis.treatTextField(campo)\n existe_valor_linha += valor_celula\n \n # se não existir nenhum valor na linha passa pra próxima\n if existe_valor_linha == \"\":\n continue\n\n for campo in row:\n valor_celula = funcoesUteis.treatTextField(campo)\n\n # adiciona o valor da célula na lista de dados_linha\n dados_linha.append(valor_celula)\n\n # copia os dados da linha para o vetor de lista_dados\n lista_dados.append(dados_linha[:])\n\n # limpa os dados da linha para ler a próxima\n dados_linha.clear()\n\n # retorna uma lista dos dados\n return lista_dados\n\ndef ImageToText(file, wayToSaveFile):\n nameFile = funcoesUteis.getOnlyNameFile(os.path.basename(file))\n wayToSave = f\"{wayToSaveFile}/{nameFile}.txt\"\n wayToSave = open(wayToSave, \"w\", encoding='utf-8')\n content = ocr.image_to_string(Image.open(file), lang='por')\n wayToSave.write(content)\n wayToSave.close()\n\ndef PDFImgToText(file, wayToSaveFile):\n nameFile = funcoesUteis.getOnlyNameFile(os.path.basename(file))\n wayToSave = f\"{wayToSaveFile}/{nameFile}.jpg\"\n\n command = f'magick -density 300 \"{file}\" \"{wayToSave}\"'\n os.system(command)\n\n ImageToText(wayToSave, wayToSaveFile)\n \ndef PDFToText(file, wayToSaveFile, mode=\"simple\"):\n nameFile = funcoesUteis.getOnlyNameFile(os.path.basename(file))\n wayToSave = f\"{wayToSaveFile}/{nameFile}.txt\"\n try:\n textPdf = \"\"\n with open(file, 'rb') as filePdf:\n documents = slate.PDF(filePdf)\n for document in documents:\n textPdf += document\n \n if funcoesUteis.treatTextField(textPdf) == \"\":\n PDFImgToText(file, wayToSaveFile)\n else:\n command = f'{fileDir}/exe/pdftotext64.exe -{mode} \"{file}\" \"{wayToSave}\"'\n os.system(command)\n\n except Exception as ex:\n print(f\"Nao foi possivel transformar o arquivo \\\"{file}\\\". O erro é: {str(ex)}\")\n\n# PDFToText('C:/Programming/baymax/backend/accounting_integration/data/temp/1428/pdfs/01-10-19 placo 20747-005 - diviart/1.pdf', 'C:/Programming/baymax/backend/accounting_integration/data/temp/1428/pdfs/01-10-19 placo 20747-005 - diviart')\n\ndef splitPdfOnePageEach(file, wayToSaveFiles, sequential=0):\n try:\n nameFile = funcoesUteis.getOnlyNameFile(os.path.basename(file))\n\n nameDirectoryToSave = f\"{nameFile}-{sequential}\"\n\n wayBaseToSaveFile = os.path.join(wayToSaveFiles, 'pdfs', nameDirectoryToSave)\n os.makedirs(wayBaseToSaveFile)\n\n with open(file, 'rb') as filePdf:\n pdfReader = PyPDF2.PdfFileReader(filePdf)\n countPages = pdfReader.getNumPages()\n\n for numberPage in range(countPages):\n pageContent = pdfReader.getPage(numberPage)\n \n pdfWriter = PyPDF2.PdfFileWriter()\n pdfWriter.addPage(pageContent)\n\n with open(f'{wayBaseToSaveFile}\\\\{numberPage+1}.pdf', 'wb') as newPdfPerPage:\n pdfWriter.write(newPdfPerPage)\n except Exception as e:\n pass #print(f'\\t - Não foi possível processar o arquivo {file}, provavelmente o PDF está inválido e com erro no momento de abrir!')\n\ndef leTxt(caminho, encoding='utf-8', treatAsText=False, removeBlankLines=False):\n lista_linha = []\n \n # le o arquivo e grava num vetor\n try:\n with open(caminho, 'rt', encoding=encoding) as txtfile:\n for linha in txtfile:\n linha = str(linha).replace(\"\\n\", \"\")\n if treatAsText is True:\n linha = funcoesUteis.treatTextField(linha)\n if removeBlankLines is True:\n if linha.strip() == \"\":\n continue\n lista_linha.append(linha)\n except Exception as e:\n with open(caminho, 'rt', encoding='Windows-1252') as txtfile:\n for linha in txtfile:\n linha = str(linha).replace(\"\\n\", \"\")\n if treatAsText is True:\n linha = funcoesUteis.treatTextField(linha)\n if removeBlankLines is True:\n if linha.strip() == \"\":\n continue\n lista_linha.append(linha)\n\n return lista_linha\n\ndef readSql(wayFile, nameSql, *args):\n # esta função lê um SQL e retorna como string com os *args aplicados. Pro arg ser aplicado tem que colocar um '#' no lugar, \n # que ele deve fazer a substituição\n sql = ''\n argSequencial = 0\n try:\n with open(os.path.join(wayFile, nameSql), 'rt') as sqlfile:\n for row in sqlfile:\n positionInicialSearchNewHashtag = 0\n rowWithArguments = ''\n positionFindHashtag = row.find('#')\n rowSplit = row\n if positionFindHashtag >= 0:\n while True:\n rowWithArguments += f'{rowSplit[:positionFindHashtag]}{args[argSequencial]}'\n positionInicialSearchNewHashtag = positionFindHashtag+1\n rowSplit = rowSplit[positionInicialSearchNewHashtag:]\n positionFindHashtag = rowSplit.find('#')\n if positionFindHashtag < 0:\n rowWithArguments += rowSplit \n argSequencial += 1\n break\n else:\n argSequencial += 1\n \n row = rowWithArguments if rowWithArguments != \"\" else row\n sql += row\n except Exception:\n sql = ''\n \n return sql\n\ndef readJson(caminho):\n try:\n with open(caminho) as file:\n return json.load(file)\n except Exception as e:\n print(e)\n\ndef readXml(way):\n try:\n with open(way) as file:\n return xmldict.parse(file.read())\n except Exception as e:\n print(e)\n return {}\n","sub_path":"backend/tools/leArquivos.py","file_name":"leArquivos.py","file_ext":"py","file_size_in_byte":10424,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"577917315","text":"import heapq\n\n\n\nif __name__ == \"__main__\":\n\n\n # n이 셀 수 있는 범위이면 완전 탐색 대상인지 생각\n\n # q 에 dist 와 start 지점 큐를 최초 삽입\n\n # 항상 최소거리부터 탐색하기 위하여 파이썬 heapq 사용 최소힙이 default인 큐이다\n\n # 그래프에 노드를 넣고 첫 노드 부터 탐색\n\n # 왜 ?\n\n # 최소 힙큐를 선택하는 이유는 한 노드에서 시작 한 다음 그 다음의 노드를 선택해서 또 탐색할 때의 그 전에 최단거리로 갱신해왔기 때문에\n\n # 이미 최단거리라면 빠르게 계산을 뛰어넘기 위해서이다.\n\n # 그리고 탐색하는 것 .\n\n # 알고리즘의 경우 외워'지는' 것은 좋지만 무작정 외우는 것은 좋지 않다\n\n\n def dikstra(n, graph, start):\n\n\n distances = [float('inf') for i in range(1,n+1)]\n\n distances[start] = 0\n\n q = []\n\n\n\n heapq.heappush(q,(0,start))\n\n while heapq:\n\n dist, node = heapq.heappop(q)\n\n if distances[node] < dist:\n continue\n\n\n for i in graph[node]:\n # 현재 큐에서 뽑은 노드의 그래프 노드 탐색전(?)\n\n # 그래프 노드의 거리와 해당 노드\n stopover_dist = i[0]\n stopover_node = i[1]\n\n # 현재 저장된 거리 배열에 저장된 그래프 노드 까지의 거리가 현재 노드까지 온 후에 현재 노드의 그래프로 이어진 거리보다 작다면 업데이트 할 필요가 없다\n if distances[stopover_node] < distances[node] + stopover_dist:\n pass\n if distances[stopover_node] > distances[node] + stopover_dist:\n distances[stopover_node] = distances[node] + stopover_dist\n\n #해당 그래프 노드는 발견된 노드이므로 이후에 현재 노드가 완료된 이후 시작점이 되어 똑같이 탐색하기 위해 최단거리를 먼저 뽑기 위해 최소힙큐에 저장\n heapq.heappush(q,(stopover_dist,stopover_node))\n\n\n return distances\n\n\n\n def solution(n, s, a, b , fares):\n\n\n\n graph = [[] for i in range(n + 1)]\n\n\n for fare in fares:\n c, d, cost = fare\n # fares 배열에 두 지점 간 예상 택시요금은 1개만 주어집니다. 즉, [c, d, f]가 있다면 [d, c, f]는 주어지지 않습니다 -> 내가 만든다\n graph[c].append((d, cost))\n graph[d].append((c, cost))\n\n\n distances_init = dikstra(n, graph, s)\n\n dist_a = distances_init[a]\n dist_b = distances_init[b]\n\n for node in range(1,n+1):\n\n distances = dikstra(n,graph,node)\n\n if dist_a + dist_b < distances_init[node]+ distances[a] + distances[b]: # node == s 인 경우 pass 하도록 고려하지 않았다. 알고리즘 내에서도 가능한 모든 가능성 고려해야 함 효율성\n return dist_a + dist_b\n else:\n return distances_init[node]+ distances[a] + distances[b]\n\n\n\n\n\n\n\n\n\n # 최단거리 힙큐를 사용해서 최단 거리에 있는 노드부터 탐색할 수 있으니까","sub_path":"dikstraKaKao.py","file_name":"dikstraKaKao.py","file_ext":"py","file_size_in_byte":3224,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"578756993","text":"#Finished by: Kay Towner\r\nimport numpy as np\r\nimport math\r\nimport scipy.integrate as integrate\r\nimport matplotlib.pyplot as plt\r\nimport numpy.ma as ma\r\n\r\n#Problem 1.) Globe Earth\r\ndef grav_accel(p1, p2, m):\r\n \"\"\" p1 = point where the mass element is\r\n p2 = point you are interested in\r\n m = mass\r\n returns a vector of the gravitational accleration\"\"\"\r\n G = 6.6743e-11\r\n diff = p1 - p2\r\n r = np.sqrt(np.sum(diff))\r\n rhat = diff / r\r\n \r\n return -1*G*m/r**2*rhat\r\n\r\n\r\ndef point_in_sphere(x, y, z, radius=None):\r\n \"\"\"Function for the Mask Condition.\"\"\"\r\n #FILL THIS IN WITH A VALID MASK CONDITION\r\n #THAT RETURNS TRUE WHEN X,Y,Z IN THE SPHERE\r\n if (x - center_x)**2 <= (radius**2):\r\n return True\r\n if (y - center_y)**2 <= (radius**2):\r\n return True\r\n if (z - center_z)**2 <= (radius**2):\r\n return True\r\n else:\r\n return False\r\n\r\n\r\nif __name__ == \"__main__\":\r\n km = 1000 #1 km = 1000 meters\r\n rho = 5514 #kg/m^3, density of Earth\r\n r_earth = 6378*km #radius of globe Earth\r\n h = 200.0*km #relatively coarse step size\r\n dV = (1/3)*np.pi*(r_earth)**3#volume of sphere\r\n #set grid size same in x,y,z\r\n dx, dy, dz = h, h, h\r\n #x, y, z define boundaries of grid, here 7000 km\r\n x = np.arange(-7000*km, 7000*km, dx)\r\n len_x = x.shape[0]\r\n y = x.copy()\r\n z = y.copy()\r\n #define points on the north pole, south pole, and equator\r\n point_northpole = np.array([0, 0, 6378*km])\r\n point_equator = np.array([6378*km, 0, 0])\r\n point_southpole = np.array([0, 0, -6378*km])\r\n\r\n ##Sample North Pole calc\r\n ##I didn't make this a function, I'm sorry.\r\n grav_vec_northpole = np.array([0, 0, 6378*km])\r\n for idx, xx in enumerate(x):\r\n #this is a trick to tell how long it will take\r\n print(idx, \" of \", len_x, \"x steps.\")\r\n for yy in y:\r\n for zz in z:\r\n if point_in_sphere(xx,yy,zz):#FIX THIS, MAKE THIS A VALID FUNCTION\r\n m = rho * dV\r\n point = np.array([xx, yy, zz])\r\n grav_vec_northpole += grav_accel(point, point_northpole, m) \r\n print(\"The gravity vector at the north pole is...\", grav_vec_northpole)\r\n print(\"Should be something like [0,0,-9.8] m/s^2\")\r\n\r\n ##Sample Equator calc\r\n grav_vec_equatior = np.array([6378*km, 0, 0])\r\n for idx, xx in enumerate(x):\r\n #this is a trick to tell how long it will take\r\n print(idx, \" of \", len_x, \"x steps.\")\r\n for yy in y:\r\n for zz in z:\r\n if point_in_sphere(xx,yy,zz):#FIX THIS, MAKE THIS A VALID FUNCTION\r\n m = rho * dV\r\n point = np.array([xx, yy, zz])\r\n grav_vec_equator += grav_accel(point, point_equator, m) \r\n print(\"The gravity vector at the equator is...\", grav_vec_equator)\r\n\r\n ##Sample South Pole calc\r\n grav_vec_southpole = np.array([0, 0, -6378*km])\r\n for idx, xx in enumerate(x):\r\n #this is a trick to tell how long it will take\r\n print(idx, \" of \", len_x, \"x steps.\")\r\n for yy in y:\r\n for zz in z:\r\n if point_in_sphere(xx,yy,zz):#FIX THIS, MAKE THIS A VALID FUNCTION\r\n m = rho * dV\r\n point = np.array([xx, yy, zz])\r\n grav_vec_southpole += grav_accel(point, point_southpole, m)\r\n print(\"The gravity vector at the south pole is...\", grav_vec_southpole)\r\n\r\n\r\n#THE GRAPH PART\r\n\r\n plt.plot()\r\n plt.show()\r\n plt.xscale('log', x)\r\n plt.yscale('log', x)\r\n\r\n plt.title(\"Globe Earth Gravity\")\r\n plt.legend(['Globe Earth'])\r\n \r\n plt.xlabel(\"Acceleration of Gravity\")\r\n plt.ylabel(\"Position\")\r\n plt.show()\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"hwk6_masks.py","file_name":"hwk6_masks.py","file_ext":"py","file_size_in_byte":3800,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"154689990","text":"import os\nimport json\n\ndirectory = os.fsencode(\"templates\")\n\ntemplates = []\n\nfor file in os.listdir(directory):\n filename = os.fsdecode(file)\n if filename.endswith(\".json\"): \n with (open(\"templates/\" + filename)) as json_data:\n data = json.load(json_data)\n templates.append(data)\n continue\n else:\n continue\n\nmain = open(\"templates.json\", 'w')\nmain.write(json.dumps(templates, sort_keys=True, indent=4))","sub_path":"combiner.py","file_name":"combiner.py","file_ext":"py","file_size_in_byte":462,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"85978665","text":"\"\"\"\n创建进程 演示\n\"\"\"\nimport multiprocessing as mp\nfrom time import sleep\n\na = 1 # 全局变量\n\n# 进程执行函数\ndef fun():\n print(\"开始运行一个进程喽\")\n sleep(4)\n global a\n print(\"a = \",a)\n a = 10000\n print(\"进程运行结束喽\")\n\n# 实例化进程对象\nprocess = mp.Process(target = fun)\n\n# 启动进程 进程诞生 执行fun函数\nprocess.start()\n\nprint(\"诶呦我也做点事...\")\nsleep(3)\nprint(\"诶呦我也做完了...\")\n\n# 阻塞等待子进程退出\nprocess.join()\nprint(\"a:\",a) # 子进程一定已经结束","sub_path":"fancy_month02/day12_m_processing/day12_teacher/process01.py","file_name":"process01.py","file_ext":"py","file_size_in_byte":559,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"281202435","text":"# beamsearch.py\n#\n# Heuristics - Case: Fruitfly\n# Authors: Mercylyn Wiemer (10749306),\n# Shan Shan Huang (10768793),\n# Marwa Ahmed (10747141)\n\nfrom Fruitfly import Fruitfly\nimport heapq\nimport timeit\n\n\ndef beamsearch(root_genome, beam, points_function=None):\n \"\"\" Beam search.\n\n Heuristic search algorithm: Optimized Best-first search.\n From every layer only the best/promising n (beam) children are selected and\n added to the queue. Depending on the chosen beam: the best solution could\n be returned. The algorithms stops searching when a solution is found.\n\n Args:\n root_genome: genome sequence of fruitfly provided by user.\n points_function: selects \"best\" fruitfly child based on\n breakpoints, distance points, mutationpoints or a combination of\n breakpoints + distancepoints. Default is set on breakpoints.\n beam (integer): number of best partial solutions as candidats.\n\n Returns:\n Numbers of inversions (generations) needed to go from the\n root_genome to the solution genome.\n\n \"\"\"\n start_runtime = timeit.default_timer()\n\n # set heuristic\n if not points_function:\n points_function = Fruitfly.breakpoint_compare\n\n if points_function == Fruitfly.breakpoint_compare:\n print(\"Beam Search: Breakpoints\")\n elif points_function == Fruitfly.distancepoint_compare:\n print(\"Beam Search: Distancepoints\")\n elif points_function == Fruitfly.mutationpoint_compare:\n print(\"Beam Search: Mutationpoints\")\n else:\n print(\"Beam Search: Combinationpoints\")\n\n print(\"root genome:\", root_genome)\n\n solved = False\n solution = root_genome.solution()\n\n queue = []\n priority_queue = []\n queue.append(root_genome)\n\n while not solved:\n\n # searching for the solution per layer: with beam\n if queue:\n\n # get current node with least points\n genome = queue.pop(0)\n\n # show path to solution, when solution found\n if genome == solution:\n solved = True\n print(\"Solution found in generation: \",\n genome.get_generation())\n\n path = genome.path_solution()\n print(\"Path to solution: \")\n\n for inversion in range(len(path)):\n print(\"Inversion: {:2d}\".format(inversion), path[inversion])\n\n # make children and sort with heap\n else:\n children = genome.create_children(points_function)\n\n for child in children:\n heapq.heappush(priority_queue, child)\n\n # select best n (beam) children to add to queue\n else:\n for child in range(beam):\n best = heapq.heappop(priority_queue)\n queue.append(best)\n\n priority_queue[:] = []\n\n end_runtime = timeit.default_timer()\n runtime = (end_runtime - start_runtime)\n print(\"Runtime: \", runtime)\n\n\ndef main():\n root_genome = [23, 1, 2, 11, 24, 22, 19, 6, 10, 7, 25, 20, 5, 8, 18, 12, 13, 14, 15, 16, 17, 21, 3, 4, 9]\n fly = Fruitfly(root_genome)\n beamsearch(fly, 50)\n\nif __name__ == '__main__':\n main()\n","sub_path":"experimentation/code/beamsearch.py","file_name":"beamsearch.py","file_ext":"py","file_size_in_byte":3249,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"561664874","text":"import unittest\nimport sys, os\npath = os.path.dirname(os.path.abspath(__file__))\nsys.path.insert(0,path+'/../')\n\nfrom nessie.accountRequests import AccountRequests\nfrom nessie import billRequests\nfrom nessie.dataRequests import DataRequest\n\n\n# def test_create_bill(self):\n# bill_factory = billRequests.BillRequest(\"wkey\")\n\nwkey = '7e9b72fdb7b286fcd0aae87deb0e09a2'\n\n# customer_id = '5a546ffd6514d52c7774a2ca'\n# account_factory = AccountRequests(wkey)\n# account_factory.createCustomerAccount(customer_id)\n\n# premade account id\naccount_id = '5a5471796514d52c7774a2cb'\n\nclass TestBillRequests(unittest.TestCase):\n # create some dummy bills\n def setUp(self):\n bill_factory = billRequests.BillRequest(wkey)\n bill = bill_factory.create_bill(account_id,\n status='pending',\n payee='bobby',\n nickname='bob',\n payment_date='2018-01-10',\n recurring_date=1,\n payment_amount=10\n )\n\n def tearDown(self):\n data_deletor = DataRequest(wkey)\n response = data_deletor.delete_data('Bills')\n\n def test_get_bill_succeed(self):\n bill_factory = billRequests.BillRequest(wkey)\n result = bill_factory.get_account_bills(account_id)\n print(result)\n # result = bill_factory.get_bill(\"5a261c3883a71c405074fcbd\")\n # expected_result = {'bill_id': '5a261c3883a71c405074fcbd', 'status': 'pending', 'payee': 'string', 'nickname': 'string', 'payment_date': '2017-12-05', 'recurring_date': 1, 'payment_amount': 23, 'creation_date': '2017-12-05', 'account_id': '5a261a0483a71c405074fcbc'}\n self.assertEqual(result[0]['payment_date'], '2018-01-10')\n\n # try fetching a bill that doesn't exist\n def test_get_nonreal_bill_fail(self):\n bill_factory = billRequests.BillRequest(wkey)\n\n result = bill_factory.get_bill(\"fake\")\n expected_result = {'code':404, 'message':'Invalid ID'}\n # {'code':401, 'message':'unauthorized'}\n self.assertEqual(result, expected_result)\n\n\n\n ","sub_path":"tests/test_bill_requests.py","file_name":"test_bill_requests.py","file_ext":"py","file_size_in_byte":2032,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"119882509","text":"from PublicVariables import *\r\n\r\n\r\n# Token types\r\nTT_keyword = 'KEYWORDS'\r\nTT_operator = 'OPERATORS'\r\nTT_number = 'VALUE-NUMBER'\r\nTT_bool = 'VALUE-BOOL'\r\nTT_string = 'VALUE-STRING'\r\nTT_list = 'VALUE-LIST'\r\n\r\nTT_arguments = 'ARGUMENTS'\r\nTT_operator = 'OPERATOR'\r\nTT_variable = 'VARIABLE'\r\nTT_function = 'FUNCTION'\r\nTT_library = 'LIBRARY'\r\nTT_build_in_funcs = 'BUILD-IN-FUNCS'\r\n\r\n\r\n# Keywords can execute outside main function\r\nkw_exe_outside_main = {KW_main, KW_def1, KW_import1}\r\n\r\nvariables = []\r\nfunctions = []\r\n\r\nindent_count = 0 # Determine if needs to indent\r\ncurrent_line = 0\r\n\r\nis_main = False # Is the current statement in main\r\nis_function = False # Is the current statement in a function\r\n\r\n\r\n# Python source code, translated from RickRoll source code\r\npy_code = \"\"\r\n\r\nlibraries = {}\r\n\r\n# Determine variable types\r\ndef v_types(string):\r\n string = str(string)\r\n # Boolean\r\n if string == 'True' or string == 'False':\r\n return 'bool'\r\n # String\r\n if string[0] == '\"' and string[-1] == '\"':\r\n return 'string'\r\n # List\r\n if string[0] == '[' and string[-1] == ']':\r\n return 'list'\r\n # Determine the string is int or float\r\n count = 0\r\n for char in string:\r\n if char in digits:\r\n count += 1\r\n if count == len(string) and string.count('.') < 2:\r\n return 'number'\r\n\r\n####################################################################################\r\n'Token Class'\r\n\"\"\"\r\nToken class is used to tokenize a RickRoll statement\r\n\"\"\"\r\n####################################################################################\r\nclass Token:\r\n def __init__(self, statement):\r\n self.statement = statement\r\n self.tokens = []\r\n\r\n self.tokenize(self.statement)\r\n self.t_types = []\r\n self.t_values = []\r\n\r\n self.last_kw = ''\r\n\r\n for tok in self.tokens:\r\n if tok:\r\n self.make_token(tok)\r\n\r\n\r\n # Split statements to single word / token\r\n def tokenize(self, statement):\r\n current_token = ''\r\n quote_count = 0\r\n sq_bracket = 0\r\n for char in statement:\r\n\r\n if char == '\"': quote_count += 1\r\n if char == '#': break\r\n if char in ignore_tokens: continue\r\n\r\n if char in separators and quote_count % 2 == 0:\r\n if current_token != ' ' and current_token != '\\n':\r\n self.tokens.append(current_token)\r\n if char != ' ' and char != '\\n':\r\n self.tokens.append(char)\r\n\r\n current_token = ''\r\n else: current_token += char\r\n\r\n def make_token(self, tok):\r\n def add_to_tokens(type, token):\r\n self.t_types.append(type)\r\n self.t_values.append(token)\r\n\r\n global variables\r\n global functions\r\n\r\n\r\n if tok in keywords:\r\n add_to_tokens(TT_keyword, tok)\r\n self.last_kw = tok\r\n elif tok in OP_build_in_functions:\r\n if tok == 'length': add_to_tokens(TT_build_in_funcs, 'len')\r\n if tok == 'to_string': add_to_tokens(TT_build_in_funcs, 'str')\r\n if tok == 'to_int': add_to_tokens(TT_build_in_funcs, 'int')\r\n if tok == 'to_float': add_to_tokens(TT_build_in_funcs, 'float')\r\n\r\n # Variable types\r\n elif v_types(tok) == 'bool':\r\n add_to_tokens(TT_bool, tok)\r\n elif v_types(tok) == 'string':\r\n add_to_tokens(TT_string, tok)\r\n elif v_types(tok) == 'list':\r\n add_to_tokens(TT_list, tok)\r\n elif v_types(tok) == 'number':\r\n add_to_tokens(TT_number, tok)\r\n\r\n # Operators\r\n elif tok in OP_arithmetic or tok in OP_relational or tok in OP_assignment or tok in OP_other:\r\n if tok == 'is': add_to_tokens(TT_operator, '==')\r\n elif tok == 'is_not': add_to_tokens(TT_operator, '!=')\r\n elif tok == 'is_greater_than': add_to_tokens(TT_operator, '>')\r\n elif tok == 'is_less_than': add_to_tokens(TT_operator, '<')\r\n else: add_to_tokens(TT_operator, tok)\r\n\r\n # Variables\r\n elif self.last_kw == KW_let:\r\n variables.append(tok)\r\n add_to_tokens(TT_variable, tok)\r\n # Functions\r\n elif self.last_kw == KW_def1:\r\n functions.append(tok)\r\n add_to_tokens(TT_function, tok)\r\n elif tok and tok in variables:\r\n add_to_tokens(TT_variable, tok)\r\n\r\n else:\r\n add_to_tokens(TT_arguments, tok)\r\n # error(f'Exception in line {current_line}: the token [{tok}] is invalid...\\n')\r\n\r\n\r\n\r\n####################################################################################\r\n'Translate To Python'\r\n####################################################################################\r\n\r\nclass TranslateToPython:\r\n\r\n def __init__(self, types, values):\r\n\r\n # types of the tokens\r\n self.types = types\r\n # tokens\r\n self.values = values\r\n\r\n # if there is code in the current line of code\r\n if self.types:\r\n\r\n if self.types[0] == TT_keyword or self.values[0] in functions or self.values[0] in libraries:\r\n if is_main or (is_main == False and self.values[0] in kw_exe_outside_main) or is_function:\r\n # Convert RickRoll code to Python\r\n self.convert(kw=self.values[0])\r\n\r\n else:\r\n error(f'Exception in line {current_line}: [{self.values[0]}] can not be executed outside the main method\\n')\r\n\r\n else:\r\n error(f'Exception in line {current_line}: [{self.values[0]}] is neither a keyword nor function\\n')\r\n\r\n # if this line doesn't have code, then write \"\\n\"\r\n else:\r\n self.write(\"\")\r\n\r\n \r\n def convert(self, kw):\r\n global indent_count\r\n global is_main\r\n global is_function\r\n\r\n if kw in functions:\r\n self.write(join_list(self.values))\r\n\r\n if kw == KW_main:\r\n self.write('if __name__ == \"__main__\":')\r\n\r\n is_main = True\r\n indent_count += 1\r\n\r\n if indent_count == 0:\r\n if is_main: is_main = False\r\n if is_function: is_function = False\r\n\r\n if kw == KW_print:\r\n \"\"\"\r\n print EXPR\r\n \"\"\"\r\n\r\n EXPR = join_list(self.values[1:])\r\n self.write(f'print({EXPR}, end=\"\")')\r\n\r\n if kw == KW_let:\r\n \"\"\"\r\n let ID = EXPR\r\n \"\"\"\r\n\r\n EXPR = join_list(self.values[1:])\r\n self.write(f'{EXPR}')\r\n\r\n if kw == KW_if:\r\n \"\"\"\r\n if CONDI\r\n \"\"\"\r\n\r\n CONDI = join_list(self.values[1:])\r\n self.write(f'if {CONDI}:')\r\n indent_count += 1\r\n\r\n if kw == KW_endless_loop:\r\n self.write('while True:')\r\n indent_count += 1\r\n\r\n if kw == KW_while_loop:\r\n \"\"\"\r\n while1 CONDI while2\r\n \"\"\"\r\n\r\n CONDI = join_list(self.values[1:])\r\n self.write(f'while {CONDI}:')\r\n indent_count += 1\r\n\r\n if kw == KW_break:\r\n self.write('break')\r\n\r\n if kw == KW_continue:\r\n self.write('continue')\r\n\r\n if kw == KW_def1:\r\n \"\"\"\r\n def1 ID ARGS def2\r\n \"\"\"\r\n ID = self.values[1]\r\n ARGS = join_list(self.values[2 :-1])\r\n\r\n self.write(f'def {ID}({ARGS}):')\r\n\r\n is_function = True\r\n indent_count += 1\r\n\r\n if kw == KW_return1:\r\n \"\"\"\r\n return1 EXPR return2\r\n \"\"\"\r\n EXPR = join_list(self.values[1: -1])\r\n self.write(f'return {EXPR}')\r\n\r\n if kw == KW_end:\r\n self.write('pass')\r\n indent_count -= 1\r\n\r\n\r\n def write(self, stmt):\r\n global py_code\r\n py_code += f\"{' ' * indent_count + stmt}\\n\"\r\n\r\n\r\ndef run_in_py(src_file_name):\r\n global current_line\r\n\r\n with open(src_file_name, mode='r', encoding='utf-8') as src:\r\n\r\n content = src.readlines()\r\n content[-1] += '\\n'\r\n\r\n for statement in content: # \"statement\" is a line of code the in source code\r\n current_line += 1\r\n\r\n obj = Token(statement)\r\n TranslateToPython(types=obj.t_types, values=obj.t_values)\r\n\r\n return py_code\r\n","sub_path":"src-py/pyrickroll.py","file_name":"pyrickroll.py","file_ext":"py","file_size_in_byte":8521,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"122199206","text":"# -*- coding: utf-8 -*-\n__author__ = 'xtwxfxk'\n\nimport os\nimport sys\nimport time\nimport re\nimport socket\nimport socks\nimport threading\nimport random\nimport gzip\nimport datetime\nimport http.client as httpclient\nimport logging\nimport requests # requesocks\n\nfrom http import cookiejar\nfrom urllib.parse import urlparse\nimport io, urllib\n\n\n#from scrapy.selector import Selector\nfrom lxml import html\nfrom bs4 import BeautifulSoup\nfrom lutils.bitvise import Bitvise\nfrom lutils import read_random_lines, LUTILS_ROOT\nfrom lutils.lrequest import free_port, getaddrinfo\nfrom hyper.contrib import HTTP20Adapter\n\n__all__ = ['LRequests']\n\n#socket.setdefaulttimeout(200)\n\nlogger = logging.getLogger('lutils')\n\nNOT_REQUEST_CODE = [404, ]\n\nheader_path = os.path.join(LUTILS_ROOT, 'header')\nUSER_AGENT_DIR = os.path.join(LUTILS_ROOT, 'user_agent')\n\ndef generator_header():\n user_agent = read_random_lines(USER_AGENT_DIR, 5)[0]\n return {\n 'user-agent': user_agent,\n 'accept': '*/*',\n 'accept-language': 'zh-CN,zh;q=0.9,en;q=0.8',\n \n # 'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',\n # 'accept-encoding': 'gzip, deflate, br',\n # 'accept-language': 'zh-CN,zh;q=0.9',\n\n # 'Content-Type': 'text/plain;charset=UTF-8',\n # 'Connection': 'keep-alive',\n\n }\n\n\nclass LRequests(object):\n def __init__(self, string_proxy=None, headers=None, timeout=90, debuglevel=0, **kwargs):\n self.debuglevel = debuglevel\n self.timeout = timeout\n\n if headers is not None:\n self.headers = headers # {'key': 'value'}\n else:\n self.headers = generator_header()\n\n # self.session = requesocks.session(headers=self.headers, timeout=timeout)\n self.session = requests.Session()\n self.session.headers = self.headers\n self.session.mount('https://', HTTP20Adapter())\n # self.session = requests.session()\n\n# self.session.headers = self.headers\n\n\n if string_proxy:\n socket.getaddrinfo = getaddrinfo\n urlinfo = urlparse(string_proxy)\n\n if urlinfo.scheme == 'ssh':\n self.bitvise = Bitvise(urlinfo.hostname, urlinfo.port, username=urlinfo.username, password=urlinfo.password)\n forwarding_ip, forwarding_port = self.bitvise.start()\n\n string_proxy = 'socks5://%s:%s' % (forwarding_ip, forwarding_port)\n\n self.session.proxies = {'http': string_proxy, 'https': string_proxy}\n\n self._body = None\n\n\n def open(self, url, method='GET', data=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT, isdecode=False, repeat=3, is_xpath=True, stream=False):\n while True:\n try:\n\n if isinstance(url, str):\n logger.info('Load URL: %s' % url)\n if(method.upper() == 'POST'):\n response = self.session.post(url=url, data=data, timeout=self.timeout, allow_redirects=True, headers=self.headers, stream=stream)\n else:\n response = self.session.get(url=url, data=data, timeout=self.timeout, allow_redirects=True, headers=self.headers, stream=stream)\n\n elif isinstance(url, urllib.request.Request):\n logger.info('Load URL: %s' % url.get_full_url())\n response = self.session.request(method=url.get_method(), url=url.get_full_url(), data=url.get_data(), timeout=self.timeout, allow_redirects=True, headers=self.headers, stream=stream)\n\n self.body = response, is_xpath, stream\n self.current_url = response.url\n return response\n except (urllib.error.HTTPError, urllib.error.URLError, httpclient.BadStatusLine, socket.timeout, socket.error, IOError, httpclient.IncompleteRead, socks.ProxyConnectionError, socks.SOCKS5Error) as e:\n repeat = repeat - 1\n if isinstance(e, urllib.error.HTTPError):\n if e.code in NOT_REQUEST_CODE:\n raise\n time.sleep(random.randrange(5, 10))\n if not repeat:\n raise\n\n # except:\n # repeat = repeat - 1\n # if not repeat:\n # raise\n\n def get(self, url, method='GET', data=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT, is_xpath=True, stream=False):\n return self.load(url, method=method, data=data, timeout=timeout, is_xpath=is_xpath, stream=stream)\n\n def load(self, url, method='GET', data=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT, is_xpath=True, stream=False):\n\n return self.open(url, method=method, data=data, timeout=timeout, is_xpath=is_xpath, stream=stream)\n\n def load_img(self, url, method='GET', data=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT, stream=True):\n if self.debuglevel:\n logger.info('Load Image: %s' % url)\n return self.open(url, method=method, data=data, timeout=timeout, is_xpath=False, stream=stream)\n\n def load_file(self, file_path):\n self.loads(open(file_path, 'r').read())\n\n def loads(self, page_str, url=''):\n self.current_url = url\n self.body = page_str, True, False\n\n def getForms(self, url, data=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT, isdecode=False, repeat=3, is_xpath=False):\n return self.get_forms_by_url(url, data, timeout, isdecode, repeat, is_xpath)\n\n # def get_forms_by_url(self, url, data=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT, isdecode=False, repeat=3, is_xpath=False):\n # try:\n # if timeout is socket._GLOBAL_DEFAULT_TIMEOUT:\n # timeout = self.timeout\n # response = None\n # response = self.open(url, data, timeout, isdecode, repeat, is_xpath)\n # return ParseFile(io.StringIO(str(BeautifulSoup(self.body, 'lxml')).replace('<br/>', '').replace('<hr/>', '')), response.geturl(), backwards_compat=False)\n # except:\n # raise\n # finally:\n # if response:\n # del response\n\n # def get_forms(self):\n # return ParseFile(io.StringIO(str(BeautifulSoup(self.body, 'lxml'))), self.current_url, backwards_compat=False) # .replace('<br/>', '').replace('<hr/>', '')\n\n\n @property\n def body(self):\n return self._body\n\n @body.setter\n def body(self, value):\n try:\n response, is_xpath, stream = value\n self._body = ''\n if stream:\n self._body = response.raw.data\n else:\n if isinstance(response.text, str):\n self._body = response.text\n else:\n self._body = str(response.text) # .encode('utf-8')\n if is_xpath:\n self.tree = html.fromstring(str(BeautifulSoup(self.body, 'lxml')))\n except :\n raise\n\n def post(self, url, headers=None, data=None):\n self.session.post(url, data=data)\n\n def xpath(self, xpath):\n eles = self.tree.xpath(xpath)\n if eles and len(eles) > 0:\n return eles[0]\n\n return None\n\n\n def xpaths(self, xpath):\n return self.tree.xpath(xpath)\n\n\n def __del__(self):\n pass\n\n\nif __name__ == '__main__':\n\n# l = LRequests(string_proxy='socks5://192.168.1.195:1072')\n# l = LRequests()\n# l.load('http://image.tiancity.com/article/UserFiles/Image/luoqi/2010/201009/29/3/4.jpg', is_xpath=False, stream=True)\n\n\n# print l.body\n\n # import shutil\n # shutil.copyfileobj(l.body, open('D:\\\\xxx.jpg', 'wb'))\n\n lr = LRequests(string_proxy='socks5://192.168.1.188:1080')\n lr.load('http://www.google.com')\n\n print(lr.body)\n\n","sub_path":"lutils/request_hyper.py","file_name":"request_hyper.py","file_ext":"py","file_size_in_byte":7823,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"30489710","text":"\n\n#calss header\nclass _BREATHY():\n\tdef __init__(self,): \n\t\tself.name = \"BREATHY\"\n\t\tself.definitions = [u'used to describe a voice or way of speaking in which the breath can be heard: ']\n\n\t\tself.parents = []\n\t\tself.childen = []\n\t\tself.properties = []\n\t\tself.jsondata = {}\n\n\n\t\tself.specie = 'adjectives'\n\n\n\tdef run(self, obj1, obj2):\n\t\tself.jsondata[obj2] = {}\n\t\tself.jsondata[obj2]['properties'] = self.name.lower()\n\t\treturn self.jsondata\n","sub_path":"xai/brain/wordbase/adjectives/_breathy.py","file_name":"_breathy.py","file_ext":"py","file_size_in_byte":438,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"313372423","text":"'''\nGiven a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.\n\nExample 1:\n\nInput: \"babad\"\nOutput: \"bab\"\nNote: \"aba\" is also a valid answer.\nExample 2:\n\nInput: \"cbbd\"\nOutput: \"bb\"\n'''\n# 参考:http://windliang.cc/2018/08/05/leetCode-5-Longest-Palindromic-Substring/\n\n\n# way 1\n# not fast, O(n^2)\nclass Solution:\n def longestPalindrome(self, s):\n \"\"\"\n :type s: str\n :rtype: str\n \"\"\"\n # 中心扩展算法\n if len(s) < 1:\n return \"\"\n start, end = 0, 0\n for i in range(len(s)):\n len_odd = self.expandAroundCenter(s, i, i)\n len_even = self.expandAroundCenter(s, i, i + 1)\n ans_len = max(len_odd, len_even)\n if ans_len > (end - start):\n start = i - (ans_len - 1) // 2 # 回文起点\n end = i + ans_len // 2 # 回文终点\n return s[start:end + 1]\n\n def expandAroundCenter(self, s, l, r):\n while l >= 0 and r < len(s) and s[l] == s[r]:\n l -= 1\n r += 1\n return r - l - 1\n\n# way 2\nclass Solution:\n def longestPalindrome(self, s):\n \"\"\"\n :type s: str\n :rtype: str\n \"\"\"\n n = len(s)\n if n < 2 or s == s[::-1]:\n return s\n max_len = 1\n start = 0\n for i in range(1, n):\n even = s[i - max_len:i + 1]\n odd = s[i - max_len - 1:i + 1]\n if i - max_len - 1 >= 0 and odd == odd[::-1]:\n start = i - max_len - 1\n max_len += 2\n continue\n if i - max_len >= 0 and even == even[::-1]:\n start = i - max_len\n max_len += 1\n return s[start:start + max_len]\n\n\n# way 3\nclass Solution:\n def longestPalindrome(self, s):\n \"\"\"\n :type s: str\n :rtype: str\n \"\"\"\n new_s = '$#' + '#'.join(s) + '#'\n mx, ct, resLen, resCenter = 0, 0, 0, 0\n p = [0 for _ in range(len(new_s))]\n for i in range(1, len(new_s)):\n p[i] = min(p[2 * ct - i], mx - i) if mx > i else 1\n while i - p[i] >= 0 and i + p[i] < len(new_s) and new_s[i + p[i]] == new_s[i - p[i]]:\n p[i] += 1\n if mx < i + p[i] - 1:\n mx = i + p[i] - 1\n ct = i\n if resLen < p[i]:\n resLen = p[i]\n resCenter = i\n return s[(resCenter - resLen + 1) // 2:(resCenter + resLen - 1) // 2]\n","sub_path":"5. Longest Palindromic Substring.py","file_name":"5. Longest Palindromic Substring.py","file_ext":"py","file_size_in_byte":2521,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"476786910","text":"import random\nimport datetime\ndef has_push_update(patch_type, request, patch_monitoring, create_time, user_count=None):\n kwarg_list = []\n time_condition = {}\n user_count = 10 if user_count == None else user_count\n patchType, other = patch_type.split(':')\n flag = True\n if patchType == \"condition\":\n condition_list = other.split(\"&\")\n if '' in condition_list:condition_list.remove('')\n temp_list = list()\n for i in condition_list:\n j = i.split('=')\n if j[0] == 'week':\n time_condition[j[0]]=j[1]\n else: \n temp_list.append(tuple(j))\n temp_dict = dict(temp_list)\n request_dict = request.GET\n for i in temp_dict:\n flag = i in request_dict\n if time_condition:\n for i in time_condition:\n if i == \"week\":\n days = int(time_condition[i])*7\n create_time += datetime.timedelta(days=days)\n flag = datetime.datetime.now() < create_time\n \n elif patchType == \"gray\":\n if \"&\" in other:\n other, time_out = other.split(\"&\")\n gray_type, gray_value = other.split(\"=\")\n time_key, time_value = time_out.split(\"=\")\n days = int(time_value)*7\n create_time += datetime.timedelta(days=days)\n flag = datetime.datetime.now() <= create_time\n success_count = 0\n for i in patch_monitoring:\n success_count += i.success_count\n print(success_count) \n if gray_type == \"percentage\":\n percentage_value = success_count/user_count\n flag = percentage_value <= (int(gray_value)/10)\n flag = (random.randint(1,100)/10) <= int(gray_value)\n else:\n flag = success_count <= int(gray_value)\n elif patchType == \"private\":\n pass\n return flag","sub_path":"main/hasPushUpdate.py","file_name":"hasPushUpdate.py","file_ext":"py","file_size_in_byte":1903,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"636992702","text":"\"\"\"\r\nKelly Bwambok\r\n\"\"\"\r\nfrom netmiko import ConnectHandler\r\nfrom netmiko.ssh_exception import NetMikoAuthenticationException\r\nimport time\r\nimport logging\r\n\r\n\r\nlogger = logging.getLogger('info_logger')\r\nlogger.setLevel(logging.DEBUG)\r\n# Create file handler which logs even debug messages\r\nfh = logging.FileHandler('Info.log', 'w')\r\nfh.setLevel(logging.DEBUG)\r\n# Create console handler with a higher log level\r\nch = logging.StreamHandler()\r\nch.setLevel(logging.ERROR)\r\n# Create formatter and add it to the handlers\r\nformatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s', datefmt='%Y-%m-%d %H:%M:%S')\r\nch.setFormatter(formatter)\r\nfh.setFormatter(formatter)\r\n# Add the handlers to logger\r\nlogger.addHandler(ch)\r\nlogger.addHandler(fh)\r\nlogging.basicConfig(filename='test.log', level=logging.INFO)\r\nlogger = logging.getLogger(\"netmiko\")\r\n\r\n\r\ndef open_ip_file():\r\n ip_file = open(\"ip_list.txt\", \"r\")\r\n for ip in ip_file:\r\n send_config(ip.strip('\\n'))\r\n time.sleep(3)\r\n ip_file.close()\r\n\r\n\r\ndef send_config(ip):\r\n print('Configuring node %s..............please wait' % ip)\r\n device = {\r\n 'device_type': 'cisco_ios',\r\n 'ip': ip,\r\n 'username': 'wmutua',\r\n 'password': 'Abu$dhabi321'\r\n }\r\n try:\r\n net_connect = ConnectHandler(**device)\r\n output = net_connect.send_config_from_file(\"change_file.txt\")\r\n logger.info('%s has been successfully configured', ip)\r\n print('Awesome %s configured!!Moving to Nextone....' % ip)\r\n net_connect.disconnect()\r\n except NetMikoAuthenticationException:\r\n print('Configuration with Credential set 1 failed.. Trying credential set 2 for %s' % ip)\r\n device = {\r\n 'device_type': 'cisco_ios',\r\n 'ip': ip,\r\n 'username': 'kcblanadmin',\r\n 'password': 'Lock123*',\r\n 'secret': 'Lock123*'\r\n }\r\n try:\r\n net_connect = ConnectHandler(**device)\r\n output = net_connect.send_config_from_file(\"change_file.txt\")\r\n logger.info('%s has been successfully configured', ip)\r\n print('Awesome %s configured!!Moving to Nextone....' % ip)\r\n net_connect.disconnect()\r\n except NetMikoAuthenticationException:\r\n print('Both credentials Failed for %s ' % ip)\r\n\r\nif __name__ == '__main__':\r\n open_ip_file()\r\n","sub_path":"Kelly_Scripts/Write/NetmikoLib_IOS.py","file_name":"NetmikoLib_IOS.py","file_ext":"py","file_size_in_byte":2383,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"77840680","text":"# -*-coding:utf-8-*- \n\"\"\"\n@Author : llame\n@Software: PyCharm\n@Time : 2020/9/23 10:26 上午\n\"\"\"\n\n\ndef findnode(root, node1, node2):\n if root == None or root == node1 or root == node2:\n return root\n lchild = findnode(root.lchild, node1, node2)\n rchild = findnode(root.rchild, node1, node2)\n if lchild == None:\n return rchild\n elif rchild == None:\n return lchild\n else:\n return root\n\n\nclass BiTNode:\n def __init__(self):\n self.data = None\n self.lchild = None\n self.rchild = None\n\n\ndef arraytotree(arr, start, end):\n root = None\n if end >= start:\n root = BiTNode()\n mid = (start + end + 1) // 2\n root.data = arr[mid]\n root.lchild = arraytotree(arr, start, mid - 1)\n root.rchild = arraytotree(arr, mid + 1, end)\n else:\n root = None\n return root\n\n\nif __name__ == '__main__':\n arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n root = arraytotree(arr, 0, len(arr) - 1)\n node1 = root.lchild.lchild.lchild\n node2 = root.lchild.lchild\n res = None\n res = findnode(root, node1, node2)\n if res != None:\n print('最近的节点为:' + str(res.data))\n else:\n print('没有父节点')\n","sub_path":"algorithm/14-排序二叉树上任意两个结点的最近共同父节点.py","file_name":"14-排序二叉树上任意两个结点的最近共同父节点.py","file_ext":"py","file_size_in_byte":1227,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"372673608","text":"#--------\n#Solution\n#--------\neinstein_quote = ['Insanity', 'is', 'doing', 'the', 'same', 'thing',\n 'over', 'and', 'over', 'again', 'and',\n 'expecting', 'a', 'different', 'result']\n \nrepeat_section = einstein_quote[4:10] * 3\nwedged_section = ['This is the'] + repeat_section + ['until now']\nprint(wedged_section)","sub_path":"course/Day1/solutions/sol_1_9.py","file_name":"sol_1_9.py","file_ext":"py","file_size_in_byte":339,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"573306077","text":"\"\"\"\n Simple app demostrating how to load files to the Google App Engine Blobstore.\n\"\"\"\n\nimport urllib\nimport webapp2\n\nfrom google.appengine.ext import blobstore\nfrom google.appengine.ext.webapp import blobstore_handlers\n\n\nclass MainHandler(webapp2.RequestHandler):\n \"\"\"Displays the upload form with the action field set to the blob upload url.\n The file will be uploaded directly to the blobstore.\n When successful the blobstore will call us back at the path we gave it.\"\"\"\n\n def get(self):\n # Create upload URL for POST form and set the call back path.\n upload_url = blobstore.create_upload_url('/upload')\n\n # Read in the form and replace the format place holder with the upload_url\n upload_form = open(\"upload.html\").read()\n html = upload_form.format(upload_url)\n\n # Send the form to the client.\n self.response.out.write(html)\n\n\nclass UploadHandler(blobstore_handlers.BlobstoreUploadHandler):\n \"\"\"Handles the call back from the blobstore upload call.\n Gets the key and redirect to the show page to display the uploaded file\"\"\"\n\n def post(self):\n # Use get_uploads to send the posted file to the blobstore\n upload_files = self.get_uploads('file')\n\n # Get the blob info for the first file\n blob_info = upload_files[0]\n\n # Redirect the client to the show method to see the blob.\n self.redirect('/show/%s' % blob_info.key())\n\n\nclass ShowHandler(webapp2.RequestHandler):\n \"\"\"Show a page with the uploaded image\"\"\"\n\n def get(self, key):\n # Read in the html page\n show_page = open(\"show.html\").read()\n \n # Replace the {0} with the key\n html = show_page.format(key)\n\n # Send the page to the client\n self.response.out.write(html)\n\n\nclass ServeHandler(blobstore_handlers.BlobstoreDownloadHandler):\n \"\"\"Get use a blob from the blobstore using the key and send it to the client\"\"\"\n\n def get(self, key):\n # Get the key for the blob\n key = str(urllib.unquote(key))\n\n # Get the blob info from the blobstore\n blob_info = blobstore.BlobInfo.get(key)\n\n # Send the blob to the client.\n self.send_blob(blob_info)\n\n\n# Create the webapp2 application to handle requests\napp = webapp2.WSGIApplication([('/', MainHandler),\n ('/upload', UploadHandler),\n ('/serve/([^/]+)?', ServeHandler),\n ('/show/([^/]+)?', ShowHandler)],\n debug=True)\n\n","sub_path":"16_wxPython/BlobStore/SimpleBlobStore.py","file_name":"SimpleBlobStore.py","file_ext":"py","file_size_in_byte":2551,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"354881926","text":"import save_manager\nimport sys\nimport tkinter as tk\nfrom gui import tabs\nfrom settings import currency_list\nfrom tkinter import filedialog\nfrom tkinter import ttk\n\n\nclass D3Edit(object):\n def __init__(self):\n message = None\n try:\n from google import protobuf\n del protobuf\n except ImportError:\n protobuf = None\n message = \"Could not import protobuff, please install the protobuf python package.\"\n self.current_file = None\n self.main_window = None\n self.style = None\n self.account = None\n self.previous_file = None\n self.wcoords = None\n self.setupframe()\n self.draw_welcome(message)\n\n def setupframe(self):\n self.main_window = tk.Tk()\n self.main_window.title(\"D3Edit\")\n self.main_window.minsize(600, 450)\n if self.wcoords:\n self.main_window.geometry(\"+{0}+{1}\".format(self.wcoords[0], self.wcoords[1]))\n self.style = ttk.Style(self.main_window)\n self.style.theme_use('default')\n self.style.configure(\"TLabel\", foreground=\"black\", background=\"white\")\n self.style.configure(\"TNotebook\", background=\"white\")\n\n def draw_welcome(self, message=None):\n if not message:\n message = \"Account not loaded, please load an account file to begin.\"\n message_label = ttk.Label(self.main_window, text=message, style=\"TLabel\")\n message_label.grid(column=0, row=0, sticky='NEW')\n message_label.configure(anchor='center')\n open_file = ttk.Button(self.main_window, text=\"Open File\", command=self.openfile)\n open_file.place(rely=0.5, relx=0.5, anchor='center')\n\n def destroy_loaded_view(self):\n self.wcoords = (self.main_window.winfo_x(), self.main_window.winfo_y())\n self.main_window.destroy()\n self.setupframe()\n\n def openfile(self):\n selected_file = filedialog.askopenfilename(initialdir=\".\", title=\"Select account.dat file\")\n if selected_file:\n if self.current_file:\n self.previous_file = self.current_file\n self.current_file = selected_file\n self.loadaccount(self.current_file)\n\n def loadaccount(self, file):\n self.account = save_manager.SaveData(file)\n self.account.output_file = file\n self.destroy_loaded_view()\n self.draw_account_view()\n\n def savechanges(self):\n for currency in self.account.asd.partitions[0].currency_data.currency:\n amount = getattr(self.tabs.scvalues[str(currency.id)], 'get')\n currency.count = int(amount())\n for currency in self.account.asd.partitions[1].currency_data.currency:\n amount = getattr(self.tabs.hcvalues[str(currency.id)], 'get')\n currency.count = int(amount())\n scplvl = getattr(self.tabs.scvalues['plvl'], 'get')\n hcplvl = getattr(self.tabs.hcvalues['plvl'], 'get')\n self.account.asd.partitions[0].alt_level = int(scplvl())\n self.account.asd.partitions[1].alt_level = int(hcplvl())\n self.account.commit_all_changes()\n self.destroy_loaded_view()\n self.draw_welcome(\"Account data saved.\")\n\n def draw_account_view(self):\n self.tabs = tabs.Notebook(self.main_window, account=self.account.asd)\n ttk.Button(self.tabs.account_tab, text=\"Save all changes\", command=self.savechanges).grid(column=1, row=99)\n\n def start(self):\n self.main_window.mainloop()\n sys.exit(0)\n","sub_path":"gui/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":3493,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"337843853","text":"\"\"\"\n7. Realice las siguientes operaciones utilizando funciones lambda en el listado de archivos del\nejercicio anterior:\n(a) Obtener una lista de los archivos del directorio con la primer letra del nombre de cada\nuno en mayúscula\n(b) Generar una lista con aquellos archivos que han sido modificados en los últimos 3 días\n(c) Imprimir el tamaño total de los archivos\n(d) Ordenar los archivos del directorio por tamaño\n\"\"\"\n\nimport os\nimport time\nfrom datetime import datetime, date, time, timedelta\nfrom functools import reduce\n\n\ndef obtenerArchivos():\n \"\"\"Retorna una lista de diccionarios con la informacion de cada archivo\n en el directorio actual\"\"\"\n lista = []\n archivos = os.listdir()\n for archivo in archivos:\n datos = os.stat(archivo)\n d = {\n \"Nombre\": archivo,\n \"Bytes\": datos[6],\n \"Ultima modificacion\": datetime.fromtimestamp(datos[8])\n }\n lista.append(d)\n return lista\n\n\narchivos = obtenerArchivos()\n\ncapitalizados = list(map(lambda a: a[\"Nombre\"].capitalize(), archivos))\n\nprint('\\nArchivos capitalizados\\n')\nfor archivo in capitalizados:\n print(archivo)\n \nhace3dias = datetime.today() - timedelta(days=3)\nrecientes = list(filter(lambda a: a[\"Ultima modificacion\"] > hace3dias, archivos))\n\nprint('\\nArchivos modificados en los ultimos 3 dias\\n')\nfor archivo in recientes:\n\tprint(archivo[\"Nombre\"] + \"\\t\" + str(archivo[\"Ultima modificacion\"]))\n\t\nlista = list(map(lambda a: a[\"Bytes\"], archivos))\ntotal = reduce(lambda a, b: a + b, lista)\n\t\nprint('\\nTamaño total: ' + str(total) + \" Bytes\")\n\nordenados = sorted(archivos, key = lambda a: a[\"Bytes\"])\n\nprint(\"\\nArchivos ordenados por tamaño\\n\")\nfor archivo in ordenados:\n\tprint(archivo[\"Nombre\"] + \"\\t\" + str(archivo[\"Bytes\"]) + \" Bytes\")\n\n\n","sub_path":"Practica2/Ejercicio7.py","file_name":"Ejercicio7.py","file_ext":"py","file_size_in_byte":1793,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"423753969","text":"\"\"\"The tests for group recorder.\"\"\"\nfrom __future__ import annotations\n\nfrom datetime import timedelta\n\nfrom homeassistant.components import group\nfrom homeassistant.components.group import ATTR_AUTO, ATTR_ENTITY_ID, ATTR_ORDER\nfrom homeassistant.components.recorder import Recorder\nfrom homeassistant.components.recorder.db_schema import StateAttributes, States\nfrom homeassistant.components.recorder.util import session_scope\nfrom homeassistant.const import ATTR_FRIENDLY_NAME, STATE_ON\nfrom homeassistant.core import HomeAssistant, State\nfrom homeassistant.setup import async_setup_component\nfrom homeassistant.util import dt as dt_util\n\nfrom tests.common import async_fire_time_changed\nfrom tests.components.recorder.common import async_wait_recording_done\n\n\nasync def test_exclude_attributes(recorder_mock: Recorder, hass: HomeAssistant) -> None:\n \"\"\"Test number registered attributes to be excluded.\"\"\"\n hass.states.async_set(\"light.bowl\", STATE_ON)\n\n assert await async_setup_component(hass, \"light\", {})\n assert await async_setup_component(\n hass,\n group.DOMAIN,\n {\n group.DOMAIN: {\n \"group_zero\": {\"entities\": \"light.Bowl\", \"icon\": \"mdi:work\"},\n \"group_one\": {\"entities\": \"light.Bowl\", \"icon\": \"mdi:work\"},\n \"group_two\": {\"entities\": \"light.Bowl\", \"icon\": \"mdi:work\"},\n }\n },\n )\n await hass.async_block_till_done()\n async_fire_time_changed(hass, dt_util.utcnow() + timedelta(minutes=5))\n await hass.async_block_till_done()\n await async_wait_recording_done(hass)\n\n def _fetch_states() -> list[State]:\n with session_scope(hass=hass) as session:\n native_states = []\n attr_ids = {}\n for db_state_attributes in session.query(StateAttributes):\n attr_ids[\n db_state_attributes.attributes_id\n ] = db_state_attributes.to_native()\n for db_state, _ in session.query(States, StateAttributes).outerjoin(\n StateAttributes, States.attributes_id == StateAttributes.attributes_id\n ):\n state = db_state.to_native()\n state.attributes = attr_ids[db_state.attributes_id]\n native_states.append(state)\n return native_states\n\n states: list[State] = await hass.async_add_executor_job(_fetch_states)\n assert len(states) > 1\n for state in states:\n if state.domain == group.DOMAIN:\n assert ATTR_AUTO not in state.attributes\n assert ATTR_ENTITY_ID not in state.attributes\n assert ATTR_ORDER not in state.attributes\n assert ATTR_FRIENDLY_NAME in state.attributes\n","sub_path":"tests/components/group/test_recorder.py","file_name":"test_recorder.py","file_ext":"py","file_size_in_byte":2709,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"67489857","text":"from dcs.helicopters import *\nfrom dcs.planes import *\nfrom dcs.ships import *\nfrom dcs.vehicles import *\n\nTurkey_2005 = {\n \"country\": \"Turkey\",\n \"side\": \"blue\",\n \"units\":[\n F_16C_50,\n F_4E,\n\n KC_135,\n KC130,\n C_130,\n E_3A,\n\n UH_1H,\n AH_1W,\n\n Armor.MBT_Leopard_2,\n Armor.MBT_Leopard_1A3,\n Armor.MBT_M60A3_Patton,\n Armor.APC_Cobra,\n Armor.APC_BTR_80,\n\n Unarmed.Transport_M818,\n Infantry.Infantry_M4,\n\n AirDefence.SAM_Avenger_M1097,\n\n CVN_74_John_C__Stennis,\n LHA_1_Tarawa,\n Armed_speedboat,\n ], \"shorad\":[\n AirDefence.AAA_ZU_23_Emplacement,\n AirDefence.SPAAA_ZSU_23_4_Shilka\n ], \"boat\":[\n \"OliverHazardPerryGroupGenerator\"\n ], \"has_jtac\": True\n}","sub_path":"game/factions/turkey_2005.py","file_name":"turkey_2005.py","file_ext":"py","file_size_in_byte":816,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"314444636","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport time\nimport random\nfrom Day06.game.core import modify_property as modify\n\ndef fight(hero_name):\n '''\n 战斗前置引导模块\n :param hero_name: 主角名称\n :return:\n '''\n msg = '''\\033[31m绝情谷底机���重重,妖魔鬼怪横行,是否确定要下去?\\033[0m\n1.我了无牵挂,我要下去杀BOSS爆装备\n2.我上有老下有小,想想还是算了\n '''\n while True:\n print(msg)\n choice = input('请选择:')\n if choice == '1':\n fight_core(hero_name)\n elif choice == '2':\n print('你灰溜溜的退出了绝情谷..\\n')\n break\n else:\n print('输入错误,请重新输入!\\n')\n\ndef fight_core(hero_name):\n '''\n 战斗处理模块\n :param hero_name: 主角名称\n :return:\n '''\n total_exp = 0\n # 读取英雄数据\n hero_data = modify.load(hero_name)\n hero_health = hero_data['state']['health_value']\n hero_damage = hero_data['state']['base_damage']\n \n # 读取怪物数据\n monster_name = 'common_monster'\n monster_data = modify.load_monster(monster_name)\n monster_health = monster_data['health_value']\n monster_damage = monster_data['base_damage']\n\n monster_name = '小啰啰' # 重新定义怪物名称,更好看\n print('[\\033[32m%s\\033[0m] 和 [\\033[32m%s\\033[0m] 狭路相逢,战斗开始!\\n' % (hero_name,monster_name))\n\n while True: # 主角或是怪物血量为0时退出\n # 第一回合\n random_nums = random.randint(-2,2) # 伤害浮动值\n temp_damage = hero_damage\n temp_damage += random_nums\n monster_health -= temp_damage\n print('%s对%s照成了\\033[31m%s\\033[0m伤害!' % (hero_name,monster_name,temp_damage))\n if monster_health < 1: # 如果怪物血量低于1,战斗胜利,退出战斗\n print('[\\033[31m%s\\033[0m]血量为0,\\033[31m战斗胜利!\\033[0m,获得经验[\\033[31m20\\033[0m]点!' % monster_name)\n break\n print('%s剩余血量\\033[32m%s\\033[0m,%s剩余血量\\033[32m%s\\033[0m.\\n' % (hero_name,hero_health,monster_name,monster_health))\n time.sleep(1)\n\n # 第二回合\n random_nums = random.randint(-2,2)\n temp_damage = monster_damage\n temp_damage += random_nums\n hero_health -= temp_damage\n print('%s对%s照成了\\033[31m%s\\033[0m伤害!' % (monster_name,hero_name,temp_damage))\n if hero_health < 1: # 如果主角血量低于1,战斗失败,退出战斗\n print('[\\033[31m%s\\033[0m]血量为0,\\033[31m战斗失败!\\033[0m' % hero_name)\n print('\\033[31m胜败乃兵家常事,大侠请重新来过!\\033[0m')\n break\n print('%s剩余血量\\033[32m%s\\033[0m,%s剩余血量\\033[32m%s\\033[0m.\\n' % (hero_name,hero_health,monster_name,monster_health))\n time.sleep(1)\n\nif __name__ == '__main__':\n fight('xiaoxin')\n\n","sub_path":"Day06/game/option_mods/fight_handle.py","file_name":"fight_handle.py","file_ext":"py","file_size_in_byte":2984,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"397814762","text":"import sys\nimport collections\n\ncount = collections.defaultdict(int)\nwith open(sys.argv[1], \"r\") as dat:\n\tdatoteka = dat.readlines()\n\tfor line in datoteka:\n\t\tip = str(line.split()[0])\t\t\n\t\tcount[ip] += 1\n\nfor ip in sorted(count, key=count.get, reverse=True):\n\tprint(ip + \" : \" + str(count[ip]))\n","sub_path":"zadatak5.py","file_name":"zadatak5.py","file_ext":"py","file_size_in_byte":294,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"100380081","text":"from django.urls import path\nfrom accounts.views import AccountLoginView, AccountRegistrationView, AccountUpdateView, AccountLogoutView\n\napp_name = 'accounts'\n\nurlpatterns = [\n path('registration/', AccountRegistrationView.as_view(), name='registration'),\n path('login/', AccountLoginView.as_view(), name='login'),\n path('logout/', AccountLogoutView.as_view(), name='logout'),\n path('profile_update/', AccountUpdateView.as_view(), name='profile_update'),\n]\n","sub_path":"accounts/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":469,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"548993172","text":"\n#Read a File\ndef getFileLines(fname) :\n fhandle = open(fname)\n lines = []\n for line in fhandle :\n line = line.rstrip()\n if line :\n lines.append(line)\n fhandle.close()\n return lines\n\n\n#Min function\ndef mymin(lst):\n\tthe_smallest_number= None\n\tfor num in lst:\n\t\tif the_smallest_number is None:\n\t\t\tthe_smallest_number=num\n\t\telse:\n\t\t\tif the_smallest_number> num:\n\t\t\t\tthe_smallest_number= num\n\treturn(the_smallest_number)\n\n#Max function\ndef mymax(lst):\n\tthe_max_number=None\n\tfor number_2 in lst:\n\t\tif the_max_number is None:\n\t\t\tthe_max_number=number_2\n\t\telif the_max_number<number_2:\n\t\t\tthe_max_number=number_2\n\treturn(the_max_number)\n\n#Average function\ndef myaverage(lst):\n\tcount1=0\n\tsum1=0\n\tfor number_3 in lst:\n\t\tcount1=count1+1\n\t\tsum1=sum1+number_3\n\taverage1=sum1/count1\n\treturn(average1)\n\n\n#Median function\ndef mymedian(lst):\n\tlst.sort()\t\n\tr=int(len(lst)/2)\n\tif (len(lst) % 2) == 0:\n\t\tmedian1=((lst[r-1])+(lst[r]))/2\n\telse:\n\t\tmedian1=lst[r]\t\n\treturn(median1)\n\n\n#Range Function\ndef myrange(lst):\n\treturn(mymax(lst)-mymin(lst))\n\n\t\n#Sample variance\ndef mysv(lst):\n\tcount1=0\n\tsum1=0\n\tsv1=0\n\tfor number_3 in lst:\n\t\tcount1=count1+1\n\t\tsum1=sum1+number_3\n\taverage1=sum1/count1\n\tfor number_3 in lst:\n\t\tsv1=sv1+((number_3)-average1)**2\n\treturn(sv1/(count1-1))\n\t\t\n#File Path C:\\Users\\sunmi\\Desktop\\Assign_python\\MH8811-G1901738C\\04\\MH8811-04-Data.csv\nlst=list(getFileLines('C:/Users/sunmi/Desktop/Assign_python/MH8811-G1901738C/04/MH8811-04-Data.csv'))\n#list object cannot be interpreted as an integer\n#make several mistakes at this point, list are stings, not integer\nfor i in range(len(lst)):\n lst[i]=int(lst[i])\nprint('The minimum number of this dataset is ',mymin(lst))\nprint('The maximum number of this dataset is ',mymax(lst))\nprint('The average number of this dataset is ',myaverage(lst))\nprint('The median number of this dataset is ',mymedian(lst))\nprint('The range of this dataset is ',myrange(lst))\nprint('The sample variance of this dataset is ',mysv(lst))\n\n\n","sub_path":"04/H1.py","file_name":"H1.py","file_ext":"py","file_size_in_byte":2002,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"545063474","text":"import sys\n\ninput = lambda: sys.stdin.readline().strip()\n\nd = [int(input()) for _ in range(9)]\n\ns = 0\nfor i in range(9):\n s += d[i]\n\nfor i in range(9):\n temp = d.pop(0)\n s -= temp\n if (s - 100) in d:\n d.remove(s-100)\n d.sort()\n print(*d, sep='\\n')\n break\n else:\n d.append(temp)\n s += temp\n","sub_path":"Python/BOJ/Bronze/2309.py","file_name":"2309.py","file_ext":"py","file_size_in_byte":346,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"621788533","text":"from django.urls import path, re_path\r\nimport adminapp.views as adminapp\r\n\r\napp_name = 'adminapp'\r\n\r\nurlpatterns = [\r\n # re_path(r'^$', adminapp.index, name='index'),\r\n re_path(r'^$', adminapp.UsersListView.as_view(), name='index'),\r\n\r\n re_path(r'^shopuser/create/$', adminapp.shopuser_create, name='shopuser_create'),\r\n re_path(r'^shopuser/update/(?P<pk>\\d+)/$', adminapp.shopuser_update, name='shopuser_update'),\r\n re_path(r'^shopuser/delete/(?P<pk>\\d+)/$', adminapp.shopuser_delete, name='shopuser_delete'),\r\n\r\n re_path(r'^productcategories/$', adminapp.categories, name='categories'),\r\n # re_path(r'^productcategory/create/$', adminapp.productcategory_create, name='productcategory_create'),\r\n re_path(r'^productcategory/create/$', adminapp.ProductCategoryCreateView.as_view(), name='productcategory_create'),\r\n\r\n # re_path(r'^productcategory/update/(?P<pk>\\d+)/$', adminapp.productcategory_update, name='productcategory_update'),\r\n re_path(r'^productcategory/update/(?P<pk>\\d+)/$', adminapp.ProductCategoryUpdateView.as_view(), name='productcategory_update'),\r\n\r\n # re_path(r'^productcategory/delete/(?P<pk>\\d+)/$', adminapp.productcategory_delete, name='productcategory_delete'),\r\n re_path(r'^productcategory/delete/(?P<pk>\\d+)/$', adminapp.ProductCategoryDeleteView.as_view(), name='productcategory_delete'),\r\n\r\n re_path(r'^products/(?P<pk>\\d+)/$', adminapp.products, name='products'),\r\n re_path(r'^product/create/(?P<pk>\\d+)/$', adminapp.product_create, name='product_create'),\r\n\r\n # re_path(r'^product/read/(?P<pk>\\d+)/$', adminapp.product_read, name='product_read'),\r\n re_path(r'^product/read/(?P<pk>\\d+)/$', adminapp.ProductDetailView.as_view(), name='product_read'),\r\n\r\n re_path(r'^product/update/(?P<pk>\\d+)/$', adminapp.product_update, name='product_update'),\r\n re_path(r'^product/delete/(?P<pk>\\d+)/$', adminapp.product_delete, name='product_delete'),\r\n]\r\n","sub_path":"adminapp/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1925,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"611213542","text":"# Third party and local imports\nimport unittest\nimport json\nfrom app import create_app, database_config\n\nclass TestPartyEndPoint(unittest.TestCase):\n '''This is a class that holds all methods for testing party endpoints'''\n def setUp(self):\n self.app = create_app('testing')\n self.client = self.app.test_client()\n\n database_config.destroy_db()\n database_config.init_test_db()\n\n self.userlogin={\n 'email' : 'admin@admin.com',\n 'password' : 'password'\n }\n\n self.data={\n 'name': 'Jubilee Party',\n 'hqAddress' : 'Jubilee House, Nairobi',\n 'logoUrl' : 'https://images.pexels.com'\n }\n\n self.data_2={\n 'name': 'Naswa Party',\n 'hqAddress' : 'Naswa House, Nairobi',\n 'logoUrl' : 'https://images.pexels.com'\n }\n self.bad_data={\n 'name': 'Naswa Party',\n 'hqAddress' : 'Naswa House, Nairobi',\n 'logoUrl' : ''\n }\n self.bad_data2={\n 'name': 'Naswa Party',\n 'hqAddress' : '',\n 'logoUrl' : 'https://images.pexels.com/photos/866351/pexels-photo-866351.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940'\n }\n self.edit_data={\n 'name': 'Nasa Party'\n }\n \n def create_admin(self):\n query = \"\"\"INSERT INTO users (nationalid, firstname, lastname, othername, email, phonenumber, passporturl, password, isadmin) VALUES ('33635322', 'Kimaiyo', 'Isaac', 'Kim', 'admin@admin.com', '0712345679', 'https://ppass.com', 'password', TRUE);\"\"\"\n con = database_config.init_test_db()\n cur = con.cursor()\n\n cur.execute(query)\n con.commit()\n con.close()\n\n\n def login_user(self):\n self.create_admin()\n response = self.client.post(path='/api/v2/auth/login', data=json.dumps(self.userlogin), content_type='application/json')\n token = response.json['token']\n\n return {\"Authorization\" : \"Bearer \" + token}\n\n def test_add_party(self):\n '''Test adding a party'''\n response = self.client.post(path='/api/v2/parties',data=json.dumps(self.data), content_type='application/json', headers=self.login_user())\n self.assertEqual(response.status_code, 201)\n\n response = self.client.post(path='/api/v2/parties',data=json.dumps(self.data_2), content_type='application/json', headers=self.login_user())\n self.assertEqual(response.status_code, 201)\n\n response = self.client.post(path='/api/v2/parties',data=json.dumps(self.bad_data), content_type='application/json', headers=self.login_user())\n self.assertEqual(response.status_code, 400)\n\n response = self.client.post(path='/api/v2/parties',data=json.dumps(self.bad_data2), content_type='application/json', headers=self.login_user())\n self.assertEqual(response.status_code, 400)\n\n response = self.client.post(path='/api/v2/parties',data=json.dumps(self.data), content_type='application/json', headers=self.login_user())\n self.assertEqual(response.status_code, 409)\n\n def test_get_parties(self):\n '''Test to get all parties'''\n self.client.post(path='/api/v2/parties',data=json.dumps(self.data), content_type='application/json', headers=self.login_user())\n response = self.client.get(path='/api/v2/parties', content_type='application/json', headers=self.login_user())\n self.assertEqual(response.status_code, 200)\n \n def test_get_a_party(self):\n '''Test to get a specific party'''\n self.client.post(path='/api/v2/parties',data=json.dumps(self.data), content_type='application/json', headers=self.login_user())\n response = self.client.get(path='/api/v2/parties/1', content_type='application/json', headers=self.login_user())\n self.assertEqual(response.status_code, 200)\n\n def test_edit_a_party(self):\n '''Test to edit a specific party'''\n self.client.post(path='/api/v2/parties',data=json.dumps(self.data), content_type='application/json', headers=self.login_user())\n response = self.client.patch(path='/api/v2/parties/1/name', data=json.dumps(self.edit_data), content_type='application/json', headers=self.login_user())\n self.assertEqual(response.status_code, 200)\n\n def test_delete_a_party(self):\n '''Test to delete a specific party'''\n self.client.post(path='/api/v2/parties',data=json.dumps(self.data), content_type='application/json', headers=self.login_user())\n response = self.client.delete(path='/api/v2/parties/1', content_type='application/json', headers=self.login_user())\n self.assertEqual(response.status_code, 200)\n \nif __name__ == '__main__':\n unittest.main()\n","sub_path":"tests/test_parties.py","file_name":"test_parties.py","file_ext":"py","file_size_in_byte":4738,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"537489638","text":"\"\"\"\n\nemailer.py - This file contains 2 handlers that are called by cronjobs.\n\n1. Send an update every Sunday at 1am telling the player their current stats.\n (games played, wins, losses, draws and score)\n2. Send a welcome email to new users. (Called every 5 minutes)\n\n\"\"\"\n\nimport webapp2\nfrom google.appengine.api import mail\nfrom google.appengine.api import app_identity\nfrom models import *\nfrom rpsls_api import RpslsApi\n\n\nclass SendUpdateEmail(webapp2.RequestHandler):\n def get(self):\n \"\"\"Send an update email to each new player with a summary of their stats.\n Called every sunday at 1am using a cron job.\"\"\"\n\n app_id = app_identity.get_application_id()\n # Get all players\n players = Player.query()\n for player in players:\n # Get wins, losses, draws, games played and calculate players score\n wins = RpslsApi.count_wins(player)\n losses = RpslsApi.count_losses(player)\n draws = RpslsApi.count_draws(player)\n played = wins + losses + draws\n score = wins * 10 + losses * -10 + draws * 5 + played\n # Prepare email\n subject = 'Your current stats for Rock, Paper, Scissors, Lizard, '\n subject += 'Spock are ready!'\n body = 'Hello {}, these are your current stats for the RPSLS game:\\n\\n'\n body = body.format(player.username)\n body += 'Played: {}\\n'.format(played)\n body += 'Wins: {}\\n'.format(wins)\n body += 'Losses: {}\\n'.format(losses)\n body += 'Draws: {}\\n\\n'.format(draws)\n body += 'Your current score is {}.\\n\\n'.format(score)\n body += 'We hope to see you again soon!\\n\\nRegards,\\nRPSLS Team'\n # Send the email, args: from, to, subject, body\n mail.send_mail('noreply@{}.appspotmail.com'.format(app_id),\n player.email,\n subject,\n body)\n\n\nclass SendWelcomeEmails(webapp2.RequestHandler):\n def get(self):\n \"\"\"Send a welcome email to each new player.\n Called every 5 minutes using a cron job.\"\"\"\n\n app_id = app_identity.get_application_id()\n # Get new players\n players = Player.query(Player.new == True)\n for player in players:\n # Prepare email\n subject = 'Thanks for registering with us {}!'.format(player.username)\n body = \"\"\"Hello {}, welcome to the greatest game in the world!\\n\\n\\\n Play now to start working your way up the leaderboard and\\\n become the Rock, Paper, Scissors, Lizard, Spock Champion!\"\"\"\n body = body.format(player.username)\n # Send the email, args: from, to, subject, body\n mail.send_mail('noreply@{}.appspotmail.com'.format(app_id),\n player.email,\n subject,\n body)\n # Set datastore 'new' flag to false to avoid resending welcome email\n player.new = False\n player.put()\n\n\napp = webapp2.WSGIApplication([\n ('/crons/stat_update', SendUpdateEmail),\n ('/crons/new_user_emails', SendWelcomeEmails),\n], debug=True)\n","sub_path":"emailer.py","file_name":"emailer.py","file_ext":"py","file_size_in_byte":3233,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"67950928","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport multitau\nimport time\n\nN = 1024\nnp.random.seed(0)\nt = np.arange(N)\nA = np.exp(-t)[:,np.newaxis] + np.random.rand(N, 24) * 0.1\n\nfor i in range(4):\n plt.semilogx(t, A.mean(axis=1))\n\nt0 = time.time()\ng1, tau1 = multitau.autocorrelate(A, 16)\nt1 = time.time()\ng2, tau2 = multitau.autocorrelate_mt(A.T, 16)\nt2 = time.time()\n\nprint('pure python time = %f' % (t1-t0))\nprint('accelrated version = %f' % (t2-t1))\nplt.figure()\nplt.semilogx(tau1, g1.mean(axis=1), 'o', label='py')\nplt.semilogx(tau2, g2.mean(axis=0), '.', label='c')\nplt.legend()\nplt.show()\n","sub_path":"tests/test_multitau.py","file_name":"test_multitau.py","file_ext":"py","file_size_in_byte":606,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"309565869","text":"from config import COMMANDS, KEYPAD, ROW_PINS, COL_PINS\nfrom executor import Executor, Address\nfrom pad4pi import rpi_gpio\nimport time\n\nif __name__ == '__main__':\n executor = Executor(COMMANDS)\n factory = rpi_gpio.KeypadFactory()\n keypad = factory.create_keypad(keypad=KEYPAD, row_pins=ROW_PINS, col_pins=COL_PINS)\n\n group = 'A'\n code = '0'\n\n def execute(key):\n global group\n global code\n\n if key in 'ABCD':\n group = key\n if key in '0123456789':\n code = key\n if key in '*#':\n executor.execute(Address(group=group, code=code, action=key))\n\n\n keypad.registerKeyPressHandler(execute)\n\n\n\nwhile True:\n print(\"Waiting for input...\")\n time.sleep(1)\n\n","sub_path":"morningstar_keypad/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":738,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"545978046","text":"import sys\nimport math\n\nfrom django.db import models\nfrom django.contrib.auth.models import User\n\nfrom ultimate.leagues.models import *\n\n\n@property\ndef rating_total(self):\n\trating_dict = {'athleticism': [], 'experience': [], 'strategy': [], 'throwing': []}\n\n\t# date cap for old ratings?\n\tratings = self.playerratings_set.all()\n\tfor rating in ratings:\n\t\tif rating.athleticism:\n\t\t\trating_dict['athleticism'].append(rating.athleticism)\n\t\tif rating.experience:\n\t\t\trating_dict['experience'].append(rating.experience)\n\t\tif rating.strategy:\n\t\t\trating_dict['strategy'].append(rating.strategy)\n\t\tif rating.throwing:\n\t\t\trating_dict['throwing'].append(rating.throwing)\n\n\t# determine the total rating of a user\n\trating_dict = dict([(key, float(sum([int(i) for i in values])) / (len(filter(lambda k: k > 0, values)) or 1)) for key, values in rating_dict.items()])\n\n\trating_dict['athleticism'] = rating_dict['athleticism'] * 10 / 6\n\trating_dict['experience'] = math.pow(rating_dict['experience'], 1.2) * 10 / math.pow(6, 1.2)\n\trating_dict['strategy'] = math.pow(rating_dict['strategy'], 1.2) * 10 / math.pow(6, 1.2)\n\trating_dict['throwing'] = rating_dict['throwing'] * 10 / 6\n\n\treturn sum(rating_dict.itervalues())\n\nUser.add_to_class('rating_total', rating_total)\n\n\nclass PlayerRatings(models.Model):\n\n\tRATING_EXPERIENCE_CHOICES = (\n\t\t(1,\t'I am new to ultimate or have played less than 2 years of pickup.'),\n\t\t(2,\t'I have played in an organized league or on a high school team for 1-2 seasons, or pickup for 3+ years.'),\n\t\t(3,\t'I have played in an organized league or on a high school team for 3+ seasons.'),\n\t\t(4, 'I have played on a college or club team in the last 6 years.'),\n\t\t(5,\t'I have played multiple seasons on a college or club team in the last 4 years.'),\n\t\t(6,\t'I have played multiple seasons on a regionals or nationals-level college or club team in the last 4 years.'),\n\t)\n\n\tRATING_STRATEGY_CHOICES = (\n\t\t(1,\t'I am new to organized ultimate.'),\n\t\t(2,\t'I have basic knowledge of the game (e.g. stall counts, pivoting).'),\n\t\t(3,\t'I have moderate knowledge (e.g. vertical stack, force, basic man defense).'),\n\t\t(4,\t'I have advanced knowledge (e.g. zone defense, horizontal stack, switching).'),\n\t\t(5,\t'I am familiar enough with the above concepts that I could explain them to a new player.'),\n\t\t(6,\t'I would consider myself an expert in ultimate strategy.'),\n\t)\n\n\tRATING_THROWING_CHOICES = (\n\t\t(1,\t'I am a novice or am learning to throw.'),\n\t\t(2,\t'I can throw a backhand 10 yards with 90% confidence.'),\n\t\t(3,\t'I can throw a forehand 10+ yards with 90% confidence and can handle if needed.'),\n\t\t(4,\t'I am confident throwing forehand and backhand various distances and can handle at a league level.'),\n\t\t(5,\t'I am confident throwing break throws and can be a very good league-level handler.'),\n\t\t(6,\t'I am confident in many styles of throws and could be a college or club-level handler.'),\n\t)\n\n\tRATING_ATHLETICISM_CHOICES = (\n\t\t(1,\t'I am slow, it is hard to change direction, and am easily winded.'),\n\t\t(2,\t'I can change direction decently, but need to rest often.'),\n\t\t(3,\t'I am somewhat fast, can make hard cuts, and can play for a few minutes at a time before resting.'),\n\t\t(4,\t'I am fairly fast, can change direction and react well, and can play a few hard points in a row.'),\n\t\t(5,\t'I am very fast, can turn well, jump high, and need little rest.'),\n\t\t(6,\t'I am faster than anyone on the field at any level and enjoy playing almost every point.'),\n\t)\n\n\tRATING_COMPETITIVENESS_CHOICES = (\n\t\t(1,\t'I do not care whether I win or lose, I play purely to socialize and have fun.'),\n\t\t(2,\t'I play ultimate to have fun, but would prefer to win.'),\n\t\t(3,\t'I am competitive, fight to win close games, and am somewhat disappointed by a loss.'),\n\t\t(4,\t'I am extremely competitive and am very disappointed by a loss.'),\n\t)\n\n\tRATING_TYPE_CAPTAIN = 1\n\tRATING_TYPE_JUNTA = 2\n\tRATING_TYPE_USER = 3\n\tRATING_TYPE = (\n\t\t(RATING_TYPE_CAPTAIN,\t'Captain'),\n\t\t(RATING_TYPE_JUNTA,\t\t'Junta'),\n\t\t(RATING_TYPE_USER,\t\t'User'),\n\t)\n\n\tid = models.AutoField(primary_key=True)\n\n\texperience = models.PositiveIntegerField(default=None, choices=RATING_EXPERIENCE_CHOICES, blank=True, null=True)\n\tstrategy = models.PositiveIntegerField(default=None, choices=RATING_STRATEGY_CHOICES, blank=True, null=True)\n\tthrowing = models.PositiveIntegerField(default=None, choices=RATING_THROWING_CHOICES, blank=True, null=True)\n\tathleticism = models.PositiveIntegerField(default=None, choices=RATING_ATHLETICISM_CHOICES, blank=True, null=True)\n\tcompetitiveness = models.PositiveIntegerField(default=None, choices=RATING_COMPETITIVENESS_CHOICES, blank=True, null=True)\n\tspirit = models.PositiveIntegerField(default=None, blank=True, null=True)\n\tuser = models.ForeignKey(User)\n\tsubmitted_by = models.ForeignKey(User, related_name='ratings_submitted_by_set')\n\tratings_type = models.PositiveIntegerField(choices=RATING_TYPE)\n\tratings_report = models.ForeignKey('user.PlayerRatingsReport', blank=True, null=True)\n\tnot_sure = models.BooleanField(default=False)\n\tupdated = models.DateTimeField(auto_now=True, auto_now_add=True)\n\n\tclass Meta:\n\t\tdb_table = u'player_ratings'\n\t\tverbose_name_plural = 'player ratings'\n\n\tdef save(self, *args, **kwargs):\n\t\tif not self.experience:\n\t\t\tself.experience = None\n\t\tif not self.strategy:\n\t\t\tself.strategy = None\n\t\tif not self.throwing:\n\t\t\tself.throwing = None\n\t\tif not self.athleticism:\n\t\t\tself.athleticism = None\n\t\tif not self.competitiveness:\n\t\t\tself.competitiveness = None\n\t\tif not self.spirit:\n\t\t\tself.spirit = None\n\t\tsuper(PlayerRatings, self).save(*args, **kwargs)\n\n\tdef __unicode__(self):\n\t\treturn '%s %s <- %s' % (str(self.updated), self.user, self.submitted_by)\n\n\nclass PlayerRatingsReport(models.Model):\n\tid = models.AutoField(primary_key=True)\n\tsubmitted_by = models.ForeignKey(User, related_name='ratings_report_submitted_by_set')\n\tteam = models.ForeignKey('leagues.Team')\n\tupdated = models.DateTimeField()\n\n\tclass Meta:\n\t\tdb_table = u'player_ratings_report'\n\n\tdef __unicode__(self):\n\t\treturn '%s, %s, %s' % (self.team, self.team.league, self.submitted_by)\n","sub_path":"ultimate/user/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":6051,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"350116113","text":"def counter(string):\n # Create an empty dictionary\n frequency_table = dict()\n\n # Iterate through each letter in the string\n for letter in string:\n # If our letter isn't already in the dictionary, we need to add it\n if letter not in frequency_table:\n frequency_table[letter] = 1\n else:\n # Otherwise, increment the tally for that letter\n frequency_table[letter] += 1\n\n # Finally, print out the frequencies\n for letter, count in frequency_table.items():\n print(letter, count)\n\n\ndef main():\n user_input = input('Gimme a sentence: ')\n\n counter(user_input)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"Exercise_3/solution_2.py","file_name":"solution_2.py","file_ext":"py","file_size_in_byte":676,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"366212923","text":"file = open(\"pythonEuler18.txt\")\r\nfile = file.readlines()\r\nfor n in range(0,len(file)):\r\n file[n] = file[n].replace(\"\\n\",\"\")\r\n file[n] = file[n].split()\r\n for f in range(0,len(file[n])):\r\n file[n][f] = int(file[n][f])\r\n\r\ncords = [0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5]\r\nsumm = 0\r\nrecord = 0\r\n\r\nfor i in range(0,2**15):\r\n for h in range(0,14):\r\n if i % 2**h == 0:\r\n cords[h] = -1*cords[h]\r\n else:\r\n continue;\r\n for Wert in range(1,15):\r\n summ += file[Wert][int(sum(cords[0:Wert+1-1])+(Wert+1)*0.5)]\r\n if summ > record:\r\n record = summ\r\n summ = 0\r\n\r\n \r\nprint(record+file[0][0])\r\n","sub_path":"Projecteuler.net Aufgaben/Euler 18 Maximum path sum I.py","file_name":"Euler 18 Maximum path sum I.py","file_ext":"py","file_size_in_byte":676,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"30747493","text":"from orders.models import Order, ShippingCharge\nfrom product.models import Discount\nfrom django.conf import settings\nimport logging\n\n\nlogging.basicConfig(filename=settings.LOG_DIR + \"\", level=logging.DEBUG)\n\n\nclass ProductOrderCalculation():\n \"\"\"docstring for ProductOrderCalculation\"\"\"\n\n def __init__(self, arg):\n super(ProductOrderCalculation, self).__init__()\n self.arg = arg\n\n @staticmethod\n def calculate_price(product, quantity, coupon_discount=0):\n discount_obj = Discount.objects.get(product=product)\n if discount_obj.discount_type.lower() == \"flat\":\n price_after_discount = product.price - discount_obj.discount\n elif discount_obj.discount_type.lower() == \"percentage\":\n price_after_discount = product.price - \\\n product.price * (discount_obj.discount / 100)\n else:\n price_after_discount = product.price\n price_after_coupon_discount = (\n price_after_discount * quantity) - coupon_discount\n return price_after_coupon_discount\n\n @staticmethod\n def calculate_individual_shipping_charge(order_list):\n seller_wise_products_cost = {}\n seller_wise_products_count = {}\n seller_id_list = []\n for order in order_list:\n seller_id = order['seller_id']\n if seller_id in seller_id_list:\n seller_wise_products_cost[seller_id] = seller_wise_products_cost[\n seller_id] + order['price_without_shipping_charge']\n seller_wise_products_count[seller_id] = seller_wise_products_count[seller_id] + 1\n logging.info('seller id exist')\n logging.info(\"seller_wise_products_cost --> \" +\n str(seller_wise_products_cost))\n logging.info(\"seller_wise_products_count --> \" +\n str(seller_wise_products_count))\n else:\n seller_wise_products_cost[seller_id] = order['price_without_shipping_charge']\n seller_wise_products_count[seller_id] = 1\n logging.info(\"seller_wise_products_cost --> \" +\n str(seller_wise_products_cost))\n logging.info(\"seller_wise_products_count --> \" +\n str(seller_wise_products_count))\n seller_id_list.append(seller_id)\n\n shipping_charge_obj = ShippingCharge.objects.get(seller=seller_id)\n logging.info(\"=====condition here====\")\n logging.info(seller_wise_products_cost[seller_id])\n logging.info(shipping_charge_obj.free_shipping_minimum_amount)\n logging.info(seller_wise_products_cost[\n seller_id] > shipping_charge_obj.free_shipping_minimum_amount)\n\n for order in order_list:\n seller_id = order['seller_id']\n if seller_id in seller_id_list:\n shipping_charge_obj = ShippingCharge.objects.get(seller=seller_id)\n if seller_wise_products_cost[seller_id] > shipping_charge_obj.free_shipping_minimum_amount:\n order['shipping_charge'] = 0\n else:\n order['shipping_charge'] = shipping_charge_obj.shipping_charge\n seller_id_list.remove(seller_id)\n else:\n order['shipping_charge'] = 0\n order['price'] = int(order['price_without_shipping_charge'] + order['shipping_charge'])\n order_id = order.get('order_id', None)\n if order_id:\n order_obj = Order.objects.get(id=order_id)\n order_obj.shipping_charge = order['shipping_charge']\n order_obj.save()\n return order_list\n\n @staticmethod\n def calculate_unit_price(product):\n discount_obj = Discount.objects.get(product=product)\n if discount_obj.discount_type.lower() == \"flat\":\n price_after_discount = product.price - discount_obj.discount\n elif discount_obj.discount_type.lower() == \"percentage\":\n price_after_discount = product.price - \\\n product.price * (discount_obj.discount / 100)\n else:\n price_after_discount = product.price\n return int(price_after_discount)\n\n @staticmethod\n def calculate_tax(price):\n service_tax = 0\n return price * service_tax / 100\n\n @staticmethod\n def calculate_shipping_charge(order_list, total):\n SHIPPING_CHARGE = 0\n MINIMUM_AMOUNT_FOR_NO_SHIPPING_CHARGE = 500\n if total < 500:\n return SHIPPING_CHARGE\n else:\n return 0\n\n @staticmethod\n def calculate_coupon_discount(order_list, coupon_code=None):\n return 0\n\n @staticmethod\n def calculate_tax_in_transaction(order_list):\n total = 0\n for order in orderlist:\n each_order_amount = ((order.price - order.discount)\n * order.quantity) - coupon_discount + shipping_charge\n total = total + each_order_amount\n\n total_with_shipping = total + \\\n self.calculate_shipping_charge(order_list, total)\n final_amount = total_with_shipping - \\\n self.calculate_coupon_discount(order_list, coupon_code)\n return self.calculate_tax(final_amount)\n\n @staticmethod\n def calculate_order_subtotal(orderlist):\n total = 0\n total_shipping_charge = 0\n for order in orderlist:\n each_order_amount = order['price_without_shipping_charge'] - order['coupon_discount']\n total_shipping_charge = total_shipping_charge + order['shipping_charge']\n total = total + each_order_amount\n return total, total_shipping_charge\n # total_with_shipping = total + self.calculate_shipping_charge(order_list,total)\n # final_amount = total_with_shipping - self.calculate_coupon_discount(order_list,coupon_code)\n # final_transaction_amount = final_amount + self.calculate_tax(final_amount)\n # return final_transaction_amount\n\n @staticmethod\n def calculate_cod_charges(orderlist):\n COD_MINIMUM_AMMOUNT = 10000\n COD_CHARGE = 80\n total = 0\n sellers_ammount = {}\n all_sellers = []\n for o in orderlist:\n all_sellers.append(o.product_varient.sellers.all())\n common_seller = list(set(all_sellers[0]).intersection(*all_sellers))\n if len(common_seller) > 0:\n sellers_ammount.update({common_seller[0].id: 0})\n for order in orderlist:\n product_sellers = order.product_varient.sellers.all()\n for product_seller in product_sellers:\n if product_seller.id in sellers_ammount.keys():\n break\n\n temp_amt = sellers_ammount.get(product_seller.id, 0)\n sellers_ammount.update(\n {product_seller.id: temp_amt + order.product_id.price})\n for k in sellers_ammount.keys():\n if sellers_ammount.get(k, 0) < COD_MINIMUM_AMMOUNT:\n total = total + COD_CHARGE\n return total\n","sub_path":"product/business_calculation.py","file_name":"business_calculation.py","file_ext":"py","file_size_in_byte":7095,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"202910285","text":"import pandas as pd\nimport matplotlib.pyplot as pl\ndf = pd.read_csv('data.csv')\ndf.shape\ndf.describe()\ndf['Units'].count()\nnum_bins = 10\npl.hist(df['Amount'], num_bins, normed=1, facecolor='blue', alpha=0.5)\npl.show()\n\n#Sales by month\nsales_by_month = df.groupby('Month').size()\nprint(sales_by_month)\n\n#Plotting the Graph\nplot_by_month = sales_by_month.plot(title='Monthly Sales',xticks=(1,2))\nplot_by_month.set_xlabel('Months')\nplot_by_month.set_ylabel('Total Sales')\n\n#Sales by hour\nsales_by_hour = df.groupby('Hour').size()\nplot_by_hour = sales_by_hour.plot(title='Hourly Sales',xticks=(range(5,22)))\nplot_by_hour.set_xlabel('Working Hours')\nplot_by_hour.set_ylabel('Total Sales')\n","sub_path":"PlotBarGraph/Code.py","file_name":"Code.py","file_ext":"py","file_size_in_byte":684,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"16026665","text":"import logging\nimport os,sys\nimport ConfigParser\n\nconfig_file = os.path.join(sys.path[0],'config.ini')\ncp = ConfigParser.SafeConfigParser()\ncp.read(config_file)\n\nlogfile = cp.get('log','logfile')\n\nif os.path.exists(logfile):\n pass\nelse:\n os.mknod(logfile)\n\n# set up logging to file - see previous section for more details\nlogging.basicConfig(level=logging.DEBUG,\n format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s',\n datefmt='%m-%d %H:%M',\n filename=logfile,\n filemode='a+')\n# define a Handler which writes INFO messages or higher to the sys.stderr\nconsole = logging.StreamHandler()\nconsole.setLevel(logging.INFO)\n# set a format which is simpler for console use\nformatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')\n# tell the handler to use this format\nconsole.setFormatter(formatter)\n# add the handler to the root logger\nlogging.getLogger('').addHandler(console)\n","sub_path":"mylog.py","file_name":"mylog.py","file_ext":"py","file_size_in_byte":977,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"511981154","text":"from dotenv import load_dotenv\nimport datetime, os, re, requests, string, unicodedata\nfrom pydash import has\n\n# APIs\nfrom iso639 import languages as iso639_languages\nfrom langdetect import detect as langdetect_detect, DetectorFactory\nimport tmdbsimple as tmdb\nimport imdb\nfrom imdb import IMDb\nimport hunspell\n\n# parsers\nfrom helpers import has_many\nfrom paste_parser import BDInfoType\nimport nltk\nimport nltk_people\nfrom nltk_people import extract_names, ie_preprocess\nfrom nltk.tokenize.api import StringTokenizer\n\n# load environment variables\nload_dotenv()\n\ntmdb.API_KEY = os.environ.get(\"TMDB_API_KEY\")\nia = IMDb()\n\n# make language detection deterministic\nDetectorFactory.seed = 0\n\nHUNSPELL_LANG = [x.strip() for x in os.environ.get(\"HUNSPELL_LANG\").split(',')]\n\n# used for filename\nRELEASE_GROUP = os.environ.get(\"RELEASE_GROUP\").strip()\n\n# channels\nTRAINEE_CHANNELS = [x.strip() for x in os.environ.get(\"TRAINEE_CHANNELS\").split(',')]\nINTERNAL_CHANNELS = [x.strip() for x in os.environ.get(\"INTERNAL_CHANNELS\").split(',')]\n\nclass Checker():\n\n def __init__(self, bdinfo, mediainfo, eac3to, codecs, source_detect, channel_name):\n self.codecs = codecs\n self.source_detect = source_detect\n self.bdinfo = bdinfo\n self.mediainfo = mediainfo\n self.eac3to = eac3to\n self.channel_name = channel_name\n \n self.report =\t{\n \"correct\": 0,\n \"warning\": 0,\n \"error\": 0,\n \"info\": 0\n }\n \n self.hobj = hunspell.HunSpell(HUNSPELL_LANG[0], HUNSPELL_LANG[1])\n \n def run_checks(self):\n reply = \"\"\n \n # check metadata\n reply += self.check_movie_name()\n reply += self.check_ids()\n \n reply += self.check_filename()\n reply += self.check_tracks_have_language()\n reply += self.check_video_language_matches_first_audio_language()\n reply += self.check_muxing_mode()\n reply += self.check_mkvmerge()\n \n # check video\n reply += self.check_video_track()\n \n # check audio\n reply += self.print_audio_track_names()\n reply += self.check_audio_tracks()\n \n # TMDB and IMDb People API\n reply += self.check_people()\n reply += self.spell_check_track_name()\n \n # check text\n reply += self.print_text_tracks()\n reply += self.check_text_order()\n reply += self.check_text_default_flag()\n \n # check chapters\n reply += self.has_chapers()\n reply += self.chapter_language()\n reply += self.chapter_padding()\n \n return reply\n \n def check_video_track(self):\n reply = \"\"\n \n if has_many(self.mediainfo, 'video.0', [\n 'format',\n 'format_version',\n 'bit_rate',\n 'height',\n 'scan_type',\n 'frame_rate',\n 'display_aspect_ratio',\n 'title',\n ]) and \\\n self.source_detect.is_dvd():\n video_title = \"\"\n # MPEG-\n video_title += self.mediainfo['video'][0]['format'].split()[0] + \"-\"\n \n # 1\n video_title += ''.join(re.findall(r'[\\d]+', self.mediainfo['video'][0]['format_version']))\n video_title += \" Video / \"\n \n # bitrate\n video_title += ''.join(re.findall(r'[\\d]+', self.mediainfo['video'][0]['bit_rate'])) + \" kbps\"\n video_title += \" / \"\n \n # height\n video_title += ''.join(re.findall(r'[\\d]+', self.mediainfo['video'][0]['height']))\n\n # scan type\n video_title += self.codecs.get_scan_type_title_name(self.mediainfo['video'][0]['scan_type'].lower(), 0)\n video_title += \" / \"\n\n # fps (int)\n video_title += str(round(float(''.join(re.findall(r'\\d+\\.\\d+', self.mediainfo['video'][0]['frame_rate'])))))\n video_title += \" fps / \"\n \n # aspect ratio\n video_title += self.mediainfo['video'][0]['display_aspect_ratio']\n mediainfo_title = self.mediainfo['video'][0]['title']\n \n if mediainfo_title == video_title:\n reply += self._print_report(\"correct\", \"Video track names match: ```\" + mediainfo_title + \"```\")\n else:\n reply += self._print_report(\"error\", \"Video track names missmatch:\\n```fix\\nExpected: \" + video_title + \"\\nMediaInfo: \" + mediainfo_title + \"```\")\n \n elif has(self.bdinfo, 'video') and has(self.mediainfo, 'video'):\n if len(self.bdinfo['video']) != 1:\n reply += self._print_report(\"error\", \"Missing bdinfo video track\\n\")\n return reply\n elif len(self.mediainfo['video']) != 1:\n reply += self._print_report(\"error\", \"Missing mediainfo video track\\n\")\n return reply\n \n if has(self.mediainfo, 'video.0.title') and has(self.bdinfo, 'video.0'):\n mediainfo_title = self.mediainfo['video'][0]['title']\n bdinfo_video_parts = self.bdinfo['video'][0].split(' / ')\n scan_type = bdinfo_video_parts[2].strip()[-1].lower()\n video_fps = float(''.join(re.findall(r'\\d*\\.\\d+|\\d+', bdinfo_video_parts[3].strip().lower())))\n _, actually_progressive = self.codecs.get_scan_type_title_name(scan_type, video_fps)\n if actually_progressive:\n reply += self._print_report(\"info\", \"Note: 1080i @ 25fps is actually progressive\\n\")\n video_title = \" / \".join(bdinfo_video_parts)\n if video_title == mediainfo_title:\n reply += self._print_report(\"correct\", \"Video track names match: ```\" + video_title + \"```\")\n else:\n reply += self._print_report(\"error\", \"Video track names missmatch:\\n```fix\\nBDInfo: \" + video_title + \"\\nMediaInfo: \" + mediainfo_title + \"```\")\n else:\n reply += self._print_report(\"error\", \"Missing mediainfo video track\\n\")\n return reply\n else:\n reply += self._print_report(\"error\", \"Could not verify video track\\n\")\n \n return reply\n \n def check_movie_name(self):\n reply = \"\"\n \n if has(self.mediainfo, 'general.0.movie_name'):\n # tv show name in format \"Name - S01E01\"\n if re.search(r'^.+\\s-\\sS\\d{2}E\\d{2}', self.mediainfo['general'][0]['movie_name']):\n reply += self._print_report(\"correct\", \"TV show name format `Name - S01E01`: \" + self.mediainfo['general'][0]['movie_name'] + \"\\n\")\n # movie name in format \"Name (Year)\"\n elif re.search(r'^.+\\(\\d{4}\\)', self.mediainfo['general'][0]['movie_name']):\n reply += self._print_report(\"correct\", \"Movie name format `Name (Year)`: \" + self.mediainfo['general'][0]['movie_name'] + \"\\n\")\n else:\n reply += self._print_report(\"error\", \"Movie name does not match format `Name (Year)`: \" + self.mediainfo['general'][0]['movie_name'] + \"\\n\")\n else:\n reply += self._print_report(\"error\", \"Missing movie name\\n\")\n \n return reply\n \n def check_ids(self):\n reply, name, year, imdb_movie, tmdb_movie_info, matched_imdb, matched_tmdb = \"\", None, None, None, None, False, False\n \n if has(self.mediainfo, 'general.0.movie_name'):\n movie_name = re.search(r'^(.+)\\((\\d{4})\\)', self.mediainfo['general'][0]['movie_name'])\n if movie_name:\n name = movie_name.group(1).strip()\n year = movie_name.group(2).strip()\n \n if has(self.mediainfo, 'general.0.imdb'):\n imdb_id = ''.join(re.findall(r'[\\d]+', self.mediainfo['general'][0]['imdb']))\n try:\n imdb_movie = ia.get_movie(imdb_id)\n except imdb._exceptions.IMDbParserError:\n reply += self._print_report(\"error\", \"Invalid IMDB id: `\" + self.mediainfo['general'][0]['imdb'] + \"`\\n\")\n else:\n if name == imdb_movie['title'] and year == str(imdb_movie['year']):\n reply += self._print_report(\"correct\", \"Matched IMDB name and year\\n\")\n matched_imdb = True\n \n if has(self.mediainfo, 'general.0.tmdb'):\n tmdb_id = ''.join(re.findall(r'[\\d]+', self.mediainfo['general'][0]['tmdb']))\n tmdb_movie = tmdb.Movies(tmdb_id)\n try:\n tmdb_movie_info = tmdb_movie.info()\n except requests.exceptions.HTTPError:\n reply += self._print_report(\"error\", \"Invalid TMDB id: `\" + self.mediainfo['general'][0]['tmdb'] + \"`\\n\")\n else:\n datetime_obj = datetime.datetime.strptime(tmdb_movie_info['release_date'], '%Y-%m-%d')\n tmdb_year = str(datetime_obj.year)\n if name == tmdb_movie_info['original_title'] and year == tmdb_year:\n reply += self._print_report(\"correct\", \"Matched TMDB name and year\\n\")\n matched_tmdb = True\n \n if not matched_imdb and not matched_tmdb:\n if imdb_movie and has_many(imdb_movie, None, ['title', 'year']):\n reply += self._print_report(\"error\", \"IMDB: Name: `\" + imdb_movie['title'] + \"` Year: `\" + str(imdb_movie['year']) + \"`\\n\")\n if tmdb_movie_info and 'original_title' in tmdb_movie_info and tmdb_year:\n reply += self._print_report(\"error\", \"TMDB: Name: `\" + tmdb_movie_info['original_title'] + \"` Year: `\" + tmdb_year + \"`\\n\")\n \n return reply\n \n def check_filename(self):\n reply = \"\"\n # construct release name\n release_name = \"\"\n\n # scan type must come from bdinfo\n bdinfo_video_parts = self.bdinfo['video'][0].split(' / ')\n scan_type = bdinfo_video_parts[2].strip()[-1].lower()\n video_fps = float(''.join(re.findall(r'\\d*\\.\\d+|\\d+', bdinfo_video_parts[3].strip().lower())))\n\n if has_many(self.mediainfo, 'general.0', ['movie_name', 'complete_name']) and \\\n has_many(self.mediainfo, 'video.0', ['height', 'title']) and \\\n has(self.mediainfo, 'audio.0.title'):\n # Name.S01E01\n tv_show_name_search = re.search(r'(.+)\\s-\\s(S\\d{2}E\\d{2})', self.mediainfo['general'][0]['movie_name'])\n # Name.Year\n movie_name_search = re.search(r'(.+)\\s\\((\\d{4})\\)', self.mediainfo['general'][0]['movie_name'])\n if tv_show_name_search:\n title = self._format_filename_title(tv_show_name_search.group(1))\n season_episode = tv_show_name_search.group(2).strip()\n release_name += title + '.' + season_episode\n elif movie_name_search:\n title = self._format_filename_title(movie_name_search.group(1))\n year = movie_name_search.group(2).strip()\n release_name += title + '.' + year\n # resolution (ex. 1080p)\n height = ''.join(re.findall(r'[\\d]+', self.mediainfo['video'][0]['height']))\n \n if self.source_detect.is_dvd():\n # source DVD\n if 'standard' in self.mediainfo['video'][0]:\n release_name += '.' + self.mediainfo['video'][0]['standard'] + '.DVD.REMUX'\n elif self.source_detect.is_uhd():\n # source UHD BluRay\n release_name += '.' + height\n release_name += scan_type\n release_name += '.UHD.BluRay.REMUX'\n # SDR/HDR\n if self.mediainfo['video'][0]['color_primaries'] == 'BT.2020':\n release_name += '.HDR'\n else:\n release_name += '.SDR'\n else:\n # source HD BluRay\n release_name += '.' + height\n release_name += scan_type\n release_name += '.BluRay.REMUX'\n \n # video format (ex. AVC)\n main_video_title = self.mediainfo['video'][0]['title'].split(' / ')\n if len(main_video_title) >= 1:\n release_name += '.' + self.codecs.get_video_codec_title_name(main_video_title[0].strip())\n main_audio_title = self.mediainfo['audio'][0]['title'].split(' / ')\n if len(main_audio_title) >= 2:\n # audio codec name for title (ex. DTS-HD.MA)\n audio_codec = main_audio_title[0].strip()\n title = self.codecs.get_audio_codec_title_name(audio_codec)\n if title:\n main_audio_title[0] = title\n else:\n reply += self._print_report(\"error\", \"No title name found for audio codec: `\" + audio_codec + \"`\\n\")\n # audio channel (ex. 5.1)\n main_audio_title[1] = main_audio_title[1].strip()\n # extract float\n main_audio_title[1] = re.search(\"\\d+\\.\\d+\", main_audio_title[1]).group(0)\n release_name += '.' + main_audio_title[0]\n release_name += '.' + main_audio_title[1]\n # release group\n release_name += '-'\n if self.channel_name in INTERNAL_CHANNELS:\n release_name += RELEASE_GROUP + '.mkv'\n complete_name = self.mediainfo['general'][0]['complete_name']\n if '\\\\' in complete_name:\n complete_name = complete_name.split('\\\\')[-1]\n elif '/' in complete_name:\n complete_name = complete_name.split('/')[-1]\n if self.channel_name in INTERNAL_CHANNELS and release_name == complete_name:\n reply += self._print_report(\"correct\", \"Filename: `\" + complete_name + \"`\\n\")\n elif release_name in complete_name:\n reply += self._print_report(\"correct\", \"Filename: `\" + complete_name + \"`\\n\")\n else:\n if self.channel_name not in INTERNAL_CHANNELS:\n release_name += 'GRouP.mkv'\n reply += self._print_report(\"error\", \"Filename missmatch:\\n```fix\\nFilename: \" + complete_name + \"\\nExpected: \" + release_name + \"```\")\n else:\n reply += self._print_report(\"error\", \"Cannot validate filename\\n\")\n \n return reply\n \n def _format_filename_title(self, title):\n title = title.strip()\n # remove diacritical marks\n title = unicodedata.normalize('NFKD', title).encode('ASCII', 'ignore').decode('ASCII')\n # remove punctuation\n title = title.replace('&', 'and')\n title = ''.join([i for i in title if not i in string.punctuation])\n # force single spaces\n title = ' '.join(title.split())\n # replace spaces with dots\n title = title.replace(' ', '.')\n return title\n \n def check_tracks_have_language(self):\n reply, is_valid = \"\", True\n \n n_reply, n_is_valid = self._check_tracks_have_language_section('video')\n reply += n_reply\n is_valid &= n_is_valid\n n_reply, n_is_valid = self._check_tracks_have_language_section('audio')\n reply += n_reply\n is_valid &= n_is_valid\n n_reply, n_is_valid = self._check_tracks_have_language_section('text')\n reply += n_reply\n is_valid &= n_is_valid\n \n if is_valid:\n reply += self._print_report(\"correct\", \"All tracks have a language chosen\\n\")\n \n return reply\n \n def check_video_language_matches_first_audio_language(self):\n reply = \"\"\n \n if not has(self.mediainfo, 'video.0.language'):\n reply += self._print_report(\"error\", \"Video language not set\" + \"\\n\")\n return reply\n if not has(self.mediainfo, 'audio.0.language'):\n reply += self._print_report(\"error\", \"First audio language not set\" + \"\\n\")\n return reply\n if self.mediainfo['video'][0]['language'] == self.mediainfo['audio'][0]['language']:\n reply += self._print_report(\"correct\", \"Video language matches first audio language: `\" + self.mediainfo['video'][0]['language'] + \"`\\n\")\n else:\n reply += self._print_report(\"error\", \"Video language does not match first audio language: `\" + self.mediainfo['video'][0]['language'] + \"` vs `\" + self.mediainfo['audio'][0]['language'] + \"`\\n\")\n return reply\n \n def _check_tracks_have_language_section(self, section):\n reply, is_valid = \"\", True\n for i, _ in enumerate(self.mediainfo[section]):\n if 'language' not in self.mediainfo[section][i]:\n reply += self._print_report(\"error\", section.capitalize() + \" \" + self._section_id(section, i) + \": Does not have a language chosen\\n\")\n is_valid = False\n return reply, is_valid\n \n def check_muxing_mode(self):\n reply, is_valid = \"\", True\n \n n_reply, n_is_valid = self._check_muxing_mode_section('general')\n reply += n_reply\n is_valid &= n_is_valid\n n_reply, n_is_valid = self._check_muxing_mode_section('video')\n reply += n_reply\n is_valid &= n_is_valid\n n_reply, n_is_valid = self._check_muxing_mode_section('audio')\n reply += n_reply\n is_valid &= n_is_valid\n n_reply, n_is_valid = self._check_muxing_mode_section('text')\n reply += n_reply\n is_valid &= n_is_valid\n \n if is_valid:\n reply += self._print_report(\"correct\", \"All tracks do not have a muxing mode\\n\")\n \n return reply\n \n def _check_muxing_mode_section(self, section):\n reply, is_valid = \"\", True\n for i, _ in enumerate(self.mediainfo[section]):\n if 'muxing_mode' in self.mediainfo[section][i]:\n reply += self._print_report(\"error\", section.capitalize() + \" #\" + self.mediainfo[section][i]['id'] + \" has muxing mode: \" + self.mediainfo[section][i][\"muxing_mode\"] + \"\\n\")\n is_valid = False\n return reply, is_valid\n \n def check_mkvmerge(self):\n reply = \"\"\n \n version_name_regex_mkvtoolnix = '\"(.*)\"'\n version_name_regex_mediainfo = '\\'(.*)\\''\n version_num_regex = '(\\d+\\.\\d+\\.\\d+)'\n \n mediainfo_version_num = re.search(version_num_regex, self.mediainfo['general'][0]['writing_application'])\n if mediainfo_version_num:\n mediainfo_version_num = mediainfo_version_num.group(1)\n \n mediainfo_version_name = re.search(version_name_regex_mediainfo, self.mediainfo['general'][0]['writing_application'])\n if mediainfo_version_name:\n mediainfo_version_name = mediainfo_version_name.group(1)\n \n if not mediainfo_version_num or not mediainfo_version_name:\n reply += self._print_report(\"info\", \"Not using mkvtoolnix\\n\")\n else:\n r = requests.get(os.environ.get(\"MKVTOOLNIX_NEWS\"))\n if r.status_code == 200:\n ## Version 32.0.0 \"Astral Progressions\" 2019-03-12\n mkvtoolnix_version_line = r.text.splitlines()[0]\n \n mkvtoolnix_version_num = re.search(version_num_regex, mkvtoolnix_version_line)\n if mkvtoolnix_version_num:\n mkvtoolnix_version_num = mkvtoolnix_version_num.group(1)\n \n mkvtoolnix_version_name = re.search(version_name_regex_mkvtoolnix, mkvtoolnix_version_line)\n if mkvtoolnix_version_name:\n mkvtoolnix_version_name = mkvtoolnix_version_name.group(1)\n \n \n if mkvtoolnix_version_num == mediainfo_version_num and mkvtoolnix_version_name == mediainfo_version_name:\n reply += self._print_report(\"correct\", \"Uses latest mkvtoolnix: `\" + mediainfo_version_num + \" \\\"\" + mediainfo_version_name + \"\\\"`\\n\")\n else:\n reply += self._print_report(\"warning\", \"Not using latest mkvtoolnix: `\" + mediainfo_version_num + \" \\\"\" + mediainfo_version_name +\n \"\\\"` latest is: `\" + mkvtoolnix_version_num + \" \\\"\" + mkvtoolnix_version_name + \"\\\"`\\n\")\n return reply\n \n def print_audio_track_names(self):\n reply = \"\"\n if len(self.mediainfo['audio']) > 0:\n reply += \"Audio Track Names:\\n\"\n reply += \"```\"\n for i, _ in enumerate(self.mediainfo['audio']):\n reply += self._section_id(\"audio\", i) + \": \"\n if 'title' in self.mediainfo['audio'][i]:\n reply += self.mediainfo['audio'][i]['title'] + \"\\n\"\n reply += \"```\"\n else:\n reply = self._print_report(\"error\", \"No audio tracks\\n\")\n return reply\n \n def check_audio_tracks(self):\n reply = \"\"\n \n if self.source_detect.is_dvd():\n # audio track conversions not supported for dvds\n reply += self._print_report(\"info\", \"Audio track conversions check not supported for DVDs\\n\")\n return reply\n elif len(self.bdinfo['audio']) == len(self.mediainfo['audio']):\n for i, title in enumerate(self.bdinfo['audio']):\n bdinfo_audio_parts = re.sub(r'\\s+', ' ', title).split(' / ')\n \n # determine where to split based on bdinfo type\n audio_split_index = 1 if self.bdinfo['type'] == BDInfoType.QUICK_SUMMARY else 0\n \n if self.bdinfo['type'] == BDInfoType.QUICK_SUMMARY:\n # quick summary strip language\n if '/' in title:\n title = title.split('/', 1)[1].strip()\n \n # check audio commentary\n is_commentary, commentary_reply = self._check_commentary(i)\n \n if is_commentary:\n reply += commentary_reply\n elif len(bdinfo_audio_parts) >= 3:\n if bdinfo_audio_parts[audio_split_index] == \"DTS-HD Master Audio\" and \\\n self._is_number(bdinfo_audio_parts[audio_split_index + 1]) and float(bdinfo_audio_parts[audio_split_index + 1]) < 3:\n # DTS-HD MA 1.0 or 2.0 to FLAC\n reply += self._check_audio_conversion(i, \"DTS-HD Master Audio\", \"FLAC Audio\")\n elif bdinfo_audio_parts[audio_split_index] == \"LPCM Audio\":\n if self._is_number(bdinfo_audio_parts[audio_split_index + 1]) and float(bdinfo_audio_parts[audio_split_index + 1]) < 3:\n # LPCM 1.0 or 2.0 to FLAC\n reply += self._check_audio_conversion(i, \"LPCM Audio\", \"FLAC Audio\")\n else:\n # LPCM > 2.0 to DTS-HD MA\n reply += self._check_audio_conversion(i, \"LPCM Audio\", \"DTS-HD Master Audio\")\n else:\n if 'title' in self.mediainfo['audio'][i]:\n if title == self.mediainfo['audio'][i]['title']:\n reply += self._print_report(\"correct\", \"Audio \" + self._section_id(\"audio\", i) + \": Track names match\\n\")\n else:\n is_bad_audio_format = False\n if '/' in title and '/' in self.mediainfo['audio'][i]['title']:\n bdinfo_audio_format = title.split('/')[0].strip()\n if self.codecs.is_codec(self.mediainfo['audio'][i]['title'][0]):\n mediainfo_audio_title = self.mediainfo['audio'][i]['title'].strip()\n else:\n # remove first part since its not a codec\n mediainfo_audio_title = ' / '.join(self.mediainfo['audio'][i]['title'].split(' / ')[1:]).strip()\n if title != mediainfo_audio_title:\n is_bad_audio_format = True\n if is_bad_audio_format:\n reply += self._print_report(\"error\", \"Audio \" + self._section_id(\"audio\", i) + \": Bad conversion:\\n```fix\\nBDInfo: \" + title + \"\\nMediaInfo: \" + self.mediainfo['audio'][i]['title'] + \"```\")\n else:\n reply += self._print_report(\"correct\", \"Audio \" + self._section_id(\"audio\", i) + \": Track names match\\n\")\n else:\n reply += self._print_report(\"error\", \"Audio \" + self._section_id(\"audio\", i) + \": Missing track name\\n\")\n else:\n reply += self._print_report(\"error\", \"Cannot verify audio track conversions, \" +\n str(len(self.bdinfo['audio'])) + \" BDInfo Audio Track(s) vs \" + str(len(self.mediainfo['audio'])) +\n \" MediaInfo Audio Track(s).\\n\")\n if len(self.bdinfo['audio']) > len(self.mediainfo['audio']):\n reply += \"Did you forget to add a minus (-) sign in front of unused audio tracks in bdinfo?\\n\"\n \n return reply\n \n def _check_commentary(self, i):\n reply, is_commentary = \"\", False\n \n if self._is_commentary_track(self.mediainfo['audio'][i]['title'].lower()):\n is_commentary = True\n # determine slashes and where to split based on bdinfo type\n slash_count = 2 if self.bdinfo['type'] == BDInfoType.QUICK_SUMMARY else 1\n if self.bdinfo['audio'][i].count(\"/\") >= slash_count:\n bdinfo_audio_format = self.bdinfo['audio'][i].split(\"/\")[slash_count - 1].strip()\n \n if bdinfo_audio_format == 'Dolby Digital Audio':\n if 'format' in self.mediainfo['audio'][i]:\n if self.mediainfo['audio'][i]['format'] == 'AC-3':\n reply += self._print_report(\"correct\", \"Audio \" + self._section_id(\"audio\", i) + \": Commentary already AC-3\\n\")\n else:\n reply += self._print_report(\"error\", \"Audio \" + self._section_id(\"audio\", i) + \": Commentary should be AC-3 instead of \" + self.mediainfo['audio'][i]['format'] + \"\\n\")\n else:\n reply += self._print_report(\"error\", \"Audio \" + self._section_id(\"audio\", i) + \": Commentary does not have a format\\n\")\n \n return is_commentary, reply\n else:\n reply += self._print_report(\"warning\", \"Audio #\" + self._section_id(\"audio\", i) + \": Cannot verify commentary audio conversion\\n\")\n return is_commentary, reply\n \n if 'format' in self.mediainfo['audio'][i] and self.mediainfo['audio'][i]['format'] == 'AC-3':\n if 'bit_rate' in self.mediainfo['audio'][i]:\n if '224' in self.mediainfo['audio'][i]['bit_rate']:\n reply += self._print_report(\"correct\", \"Audio \" + self._section_id(\"audio\", i) + \": Commentary converted to AC-3 @ 224 kbps\\n\")\n else:\n reply += self._print_report(\"error\", \"Audio \" + self._section_id(\"audio\", i) + \": Commentary AC-3 bitrate should be 224 kbps instead of \" + self.mediainfo['audio'][i]['bit_rate'] + \"\\n\")\n else:\n reply += self._print_report(\"error\", \"Audio \" + self._section_id(\"audio\", i) + \": Commentary AC-3 does not have a bitrate\\n\")\n else:\n reply += self._print_report(\"error\", \"Audio \" + self._section_id(\"audio\", i) + \": Commentary should be converted to AC-3\\n\")\n \n return is_commentary, reply\n \n def _check_audio_conversion(self, i, audio_from, audio_to):\n reply = \"\"\n \n # verify audio track titles\n if ' / ' not in self.bdinfo['audio'][i] or \\\n 'title' not in self.mediainfo['audio'][i] or ' / ' not in self.mediainfo['audio'][i]['title']:\n reply += self._print_report(\"warning\", \"Could not verify audio \" + self._section_id(\"audio\", i) + \"\\n\")\n return reply\n \n bdinfo_audio_parts = re.sub(r'\\s+', ' ', self.bdinfo['audio'][i]).split(' / ')\n if len(bdinfo_audio_parts) <= 5:\n reply += self._print_report(\"warning\", \"Could not verify audio \" + self._section_id(\"audio\", i) + \"\\n\")\n return reply\n\n mediainfo_parts = self.mediainfo['audio'][i]['title'].split(' / ')\n if len(mediainfo_parts) <= 4:\n reply += self._print_report(\"warning\", \"Could not verify audio \" + self._section_id(\"audio\", i) + \"\\n\")\n return reply\n\n # verify audio conversions\n if mediainfo_parts[0] == audio_to:\n if (mediainfo_parts[1] != bdinfo_audio_parts[2]):\n reply += self._print_report(\"error\", \"Audio \" + self._section_id(\"audio\", i) + \": Channel Mismatch, \" + audio_from + \" \" + mediainfo_parts[1] + \" and \" + audio_to + bdinfo_audio_parts[2] + \"\\n\")\n\n bdbitrate = bdinfo_audio_parts[4].strip()\n mbitrate = mediainfo_parts[3].strip()\n\n if bdbitrate == mbitrate:\n reply += self._print_report(\"error\", \"Audio \" + self._section_id(\"audio\", i) + \": \" + audio_from + \" \" + bdinfo_audio_parts[2] + \" to \" + audio_to + \" \" + mediainfo_parts[1] + \" same bitrate: \" + str(bdbitrate) + \"\\n\")\n else:\n reply += self._print_report(\"correct\", \"Audio \" + self._section_id(\"audio\", i) + \": \" + audio_from + \" \" + bdinfo_audio_parts[2] + \" to \" + audio_to + \" \" + mediainfo_parts[1] + \" (\" + str(bdbitrate) + \" to \" + str(mbitrate) + \")\\n\")\n else:\n reply += self._print_report(\"error\", \"Audio \" + self._section_id(\"audio\", i) + \" should be converted to \" + audio_to + \"\\n\")\n \n return reply\n \n def check_people(self):\n reply = \"\"\n \n # check people in audio track names\n for i, _ in enumerate(self.mediainfo['audio']):\n if 'title' in self.mediainfo['audio'][i]:\n title = self.mediainfo['audio'][i]['title'].split('/')[0].strip()\n # ignore codecs\n if not self.codecs.is_audio_title(title):\n matched_names = list()\n names = extract_names(title)\n search = tmdb.Search()\n for n in names:\n # TMDB API\n resp = search.person(query=n)\n for s in search.results:\n if n == s['name']:\n matched_names.append(n)\n # IMDb API\n for person in ia.search_person(n):\n if n == person['name']:\n matched_names.append(n)\n matched_names = set(matched_names)\n if len(matched_names) > 0:\n reply += self._print_report(\"correct\", \"Audio \" + self._section_id(\"audio\", i) + \" Matched: `\" + \", \".join(matched_names) + \"`\\n\")\n unmatched_names = set(names) - set(matched_names)\n if len(unmatched_names) > 0:\n reply += self._print_report(\"warning\", \"Audio \" + self._section_id(\"audio\", i) + \" Unmatched: `\" + \", \".join(unmatched_names) + \"`\\n\")\n \n return reply\n \n def spell_check_track_name(self):\n reply = \"\"\n \n # spellcheck audio track names\n for i, _ in enumerate(self.mediainfo['audio']):\n misspelled_words = list()\n if 'title' in self.mediainfo['audio'][i]:\n title = self.mediainfo['audio'][i]['title'].split(' / ')[0].strip()\n # ignore codecs\n if not self.codecs.is_audio_title(title):\n # map punctuation to space\n translator = str.maketrans(string.punctuation, ' '*len(string.punctuation))\n title = title.translate(translator)\n \n # ignore names\n ignore_list = extract_names(title)\n ignore_list = [a for b in ignore_list for a in b.split()]\n \n # tokenize\n tokens = nltk.word_tokenize(title)\n tokens = [t for t in tokens if t not in ignore_list]\n \n for t in tokens:\n if not self.hobj.spell(t):\n # t is misspelled\n misspelled_words.append(t)\n misspelled_words = set(misspelled_words)\n if len(misspelled_words) > 0:\n reply += self._print_report(\"error\", \"Audio \" + self._section_id(\"audio\", i) + \" Misspelled: `\" + \", \".join(misspelled_words) + \"`\\n\")\n \n return reply\n \n def print_text_tracks(self):\n reply = \"\"\n if len(self.mediainfo['text']) > 0:\n reply += \"Text Tracks:\\n\"\n reply += \"```\"\n for i, _ in enumerate(self.mediainfo['text']):\n reply += self._section_id(\"text\", i) + \":\"\n if 'default' in self.mediainfo['text'][i]:\n reply += \" default:\" + self.mediainfo['text'][i]['default']\n if 'forced' in self.mediainfo['text'][i]:\n reply += \" forced:\" + self.mediainfo['text'][i]['forced']\n if 'language' in self.mediainfo['text'][i]:\n reply += \" language:\" + self.mediainfo['text'][i]['language']\n if 'title' in self.mediainfo['text'][i]:\n reply += \" title: \" + self.mediainfo['text'][i]['title']\n reply += \"\\n\"\n reply += \"```\"\n else:\n reply = self._print_report(\"info\", \"No text tracks\\n\")\n return reply\n \n def check_text_order(self):\n reply = \"\"\n \n if len(self.mediainfo['text']) > 0:\n english_first = False\n has_english = False\n \n # list of subtitle languages without a title\n text_langs_without_title = list()\n for i, _ in enumerate(self.mediainfo['text']):\n if 'language' in self.mediainfo['text'][i] and 'title' not in self.mediainfo['text'][i]:\n text_langs_without_title.append(self.mediainfo['text'][i]['language'].lower())\n \n # check that English subtitles without a title are first if they exist\n if len(text_langs_without_title) > 0:\n if 'english' in text_langs_without_title:\n has_english = True\n if text_langs_without_title[0] == 'english':\n reply += self._print_report(\"correct\", \"English subtitles are first\\n\")\n english_first = True\n else:\n reply += self._print_report(\"error\", \"English subtitles should be first\\n\")\n \n # check if all other languages are in alphabetical order\n text_langs_without_title_and_english = [x for x in text_langs_without_title if x != 'english']\n if text_langs_without_title_and_english == sorted(text_langs_without_title_and_english):\n reply += self._print_report(\"correct\", \"Rest of the subtitles are in alphabetical order\\n\")\n else:\n if english_first:\n reply += self._print_report(\"error\", \"Rest of the subtitles should be in alphabetical order\\n\")\n elif has_english:\n reply += self._print_report(\"error\", \"English subtitles should be first, rest should be in alphabetical order\\n\")\n else:\n reply += self._print_report(\"error\", \"Subtitles should be in alphabetical order\\n\")\n \n return reply\n \n def check_text_default_flag(self):\n # english subs for foreign films should be default=yes\n reply = \"\"\n \n if len(self.mediainfo['text']) > 0:\n first_audio_language, has_english_subs, english_subs_index = False, False, False\n \n if has(self.mediainfo, 'audio.0.language'):\n first_audio_language = self.mediainfo['audio'][0]['language'].lower()\n \n if first_audio_language != 'english':\n for i, item in enumerate(self.mediainfo['text']):\n if 'language' in item:\n if item['language'].lower() == 'english':\n has_english_subs, english_subs_index = True, i\n \n if has_english_subs:\n # foreign audio and has english subs. english subs should be default=yes\n if self.mediainfo['text'][english_subs_index]['default'].lower() == 'yes':\n reply += self._print_report(\"correct\", \"Foreign film with English subs `default=yes`\\n\")\n else:\n reply += self._print_report(\"error\", \"English subs on foreign film should be `default=yes`\\n\")\n \n return reply\n \n def print_chapters(self):\n reply = \"\"\n if len(self.mediainfo['menu']) > 0:\n reply += \"```\"\n if len(self.mediainfo['menu'][0]) > 0:\n for ch in self.mediainfo['menu'][0]:\n if 'time' in ch:\n reply += ch['time']\n if 'language' in ch:\n reply += \" \" + ch['language']\n if 'title' in ch:\n reply += \" \" + ch['title']\n reply += \"\\n\"\n reply += \"```\\n\"\n return reply\n \n def chapter_language(self):\n reply = \"\"\n \n if 'menu' in self.mediainfo and len(self.mediainfo['menu']) > 0:\n if len(self.mediainfo['menu']) == 1:\n for i, _ in enumerate(self.mediainfo['menu']):\n invalid_lang_list = list()\n # concatenate all chapter titles\n chapter_phrase = \"\"\n chapter_langs = list()\n if len(self.mediainfo['menu'][i]) > 0:\n for j, item in enumerate(self.mediainfo['menu'][i]):\n if 'language' in self.mediainfo['menu'][i][j]:\n try:\n ch_lang = iso639_languages.get(alpha2=self.mediainfo['menu'][i][j]['language'])\n chapter_langs.append(ch_lang)\n except KeyError:\n invalid_lang_list.append(str(j + 1))\n else:\n invalid_lang_list.append(str(j + 1))\n if 'title' in item:\n chapter_phrase += item['title'] + \"\\n\"\n if len(invalid_lang_list) > 0:\n if len(invalid_lang_list) == len(self.mediainfo['menu'][i]):\n reply += self._print_report(\"error\", \"All chapters do not have a language set\\n\")\n else:\n reply += self._print_report(\"error\", \"The following chapters do not have a language set: \" + \", \".join(invalid_lang_list) + \"\\n\")\n else:\n reply += self._print_report(\"correct\", \"All chapters have a language set\\n\")\n if chapter_phrase:\n chapter_langs = list(set(chapter_langs))\n try:\n lang = langdetect_detect(chapter_phrase)\n ch_lang = iso639_languages.get(alpha2=lang)\n if ch_lang in chapter_langs:\n reply += self._print_report(\"correct\", \"Chapters language matches detected language: `\" + ch_lang.name + \"`\\n\")\n else:\n chapter_langs_names = \", \".join(list(set([lang.name for lang in chapter_langs])))\n reply += self._print_report(\"error\", \"Chapters languages: `\" + chapter_langs_names + \"` do not match detected language: `\" + ch_lang.name + \"`\\n\")\n except KeyError:\n reply += self._print_report(\"warning\", \"Could not detect chapters language\\n\")\n else:\n reply += self._print_report(\"error\", \"Must have at most 1 chapter menu\\n\")\n else:\n reply += self._print_report(\"info\", \"No chapters\\n\")\n \n return reply\n \n def chapter_padding(self):\n reply, padded_correctly = \"\", True\n \n if 'menu' in self.mediainfo and len(self.mediainfo['menu']) > 0:\n if len(self.mediainfo['menu']) == 1:\n num_chapters = len(self.mediainfo['menu'][0])\n for i, ch in enumerate(self.mediainfo['menu'][0]):\n if re.search(r'^chapter\\s\\d+', ch['title'], re.IGNORECASE):\n # numbered chapter\n ch_num = ''.join(re.findall(r'[\\d]+', ch['title']))\n if ch_num != ch_num.zfill(len(str(num_chapters))):\n padded_correctly = False\n break\n if padded_correctly:\n reply += self._print_report(\"correct\", \"Chapters properly padded\\n\")\n else:\n reply += self._print_report(\"error\", \"Incorrect chapter padding\\n\")\n \n return reply\n \n def has_chapers(self):\n reply, should_have_chapters = \"\", False\n for log in self.eac3to:\n for l in log:\n if \"chapters\" in l:\n should_have_chapters = True\n if should_have_chapters:\n if len(self.mediainfo['menu']) > 0:\n reply += self._print_report(\"correct\", \"Has chapters\\n\")\n else:\n reply += self._print_report(\"error\", \"Should have chapters\\n\")\n return reply\n \n def _is_commentary_track(self, title):\n return \"commentary\" in title.lower()\n \n def _section_id(self, section, i):\n reply = \"\"\n if 'id' in self.mediainfo[section.lower()][i]:\n reply += \"#\" + self.mediainfo[section.lower()][i]['id']\n else:\n reply += str(i)\n return reply\n \n def _is_number(self, s):\n try:\n float(s)\n return True\n except ValueError:\n return False\n \n def _print_report(self, type, content, record=True):\n if record:\n self.report[type.lower()] += 1\n return \"[\" + type.upper() + \"] \" + content\n \n def get_report(self):\n return self.report\n \n def display_report(self):\n reply = str(self.report['correct']) + \" correct, \"\n \n reply += str(self.report['warning']) + \" warning\"\n reply += \"\" if self.report['warning'] == 1 else \"s\"\n \n reply += \", \" + str(self.report['error']) + \" error\"\n reply += \"\" if self.report['error'] == 1 else \"s\"\n \n reply += \", and \" + str(self.report['info']) + \" info\"\n return reply\n ","sub_path":"vdator/checker.py","file_name":"checker.py","file_ext":"py","file_size_in_byte":38072,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"513237230","text":"from src.drivers.http.utils import parse_tsv\nfrom tests.testcase import BaseTestCase\n\n\nclass HttpUtilsTestCase(BaseTestCase):\n test_values = [b'', b'a\\tb\\tc']\n\n def test_parse_tsv(self):\n try:\n for v in self.test_values:\n parse_tsv(v)\n except IndexError:\n self.fail('\"parse_tsv\" raised IndexError exception!')\n except TypeError:\n self.fail('\"parse_tsv\" raised TypeError exception!')\n","sub_path":"tests/drivers/http/test_utils.py","file_name":"test_utils.py","file_ext":"py","file_size_in_byte":458,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"416343590","text":"from fastapi import FastAPI, Response\nfrom starlette.status import HTTP_204_NO_CONTENT\nimport uuid, random, requests, json, hashlib, os, rsa, sys, datetime, trace, time, logging\nfrom threading import Thread\nfrom queue import PriorityQueue\nfrom Crypto.PublicKey import RSA\nfrom pydantic import BaseModel\nfrom typing import Optional, List\nfrom kafka import KafkaProducer\nfrom fastapi.responses import JSONResponse\nfrom sqlalchemy import *\nfrom sqlalchemy import create_engine\nfrom sqlalchemy_utils import database_exists, create_database\nfrom sqlalchemy.orm import scoped_session, sessionmaker, relationship\nfrom sqlalchemy.ext.declarative import declarative_base\nimport sqlalchemy.dialects.postgresql as postgresql\nimport psycopg2\nimport psycopg2.extras\nfrom dateutil.relativedelta import relativedelta\nfrom timeloop import Timeloop\nfrom datetime import timedelta\nlogging.basicConfig(filename='logs/'+'mda.json', level=logging.INFO, format='{ \"timestamp\": \"%(asctime)s.%(msecs)03dZ\", %(message)s}', datefmt='%Y-%m-%dT%H:%M:%S')\nlogging.getLogger(\"uvicorn.error\").setLevel(logging.CRITICAL)\nlogging.getLogger(\"kafka\").setLevel(logging.CRITICAL)\n\n# Environment variables \ntry:\n POSTGRES_USER = os.environ[\"POSTGRES_USER\"]\n POSTGRES_PW = os.environ[\"POSTGRES_PW\"]\n POSTGRES_URL = os.environ[\"POSTGRES_URL\"]\n POSTGRES_DB = os.environ[\"POSTGRES_DB\"]\n RESET_DB = os.environ[\"RESET_DB\"]\n \n KAFKA_HOST = os.environ[\"KAFKA_HOST\"]\n KAFKA_PORT = os.environ[\"KAFKA_PORT\"]\n \n #publicKeyOperator = os.environ[\"OPERATOR_PUBLIC_KEY\"]\nexcept Exception as e:\n print(\"Environment variable does not exists.\")\n sys.exit(0)\n\nclass Metric_Model(BaseModel):\n metricName: str\n metricType: str\n step: str\n aggregationMethod: Optional[str] = None\n step_aggregation: Optional[str] = None\n\nclass Response_Metric_Model(BaseModel):\n metricName: str\n metricType: str\n step: str\n aggregationMethod: Optional[str] = None\n step_aggregation: Optional[str] = None\n next_run_at: datetime.datetime\n next_aggregation: Optional[datetime.datetime] = None\n\nclass Config_Model(BaseModel):\n businessID: str\n topic: str\n networkID: int\n tenantID: str\n resourceID: str\n referenceID: str\n metrics: List[Metric_Model]\n timestampStart: Optional[datetime.datetime] = None\n timestampEnd: Optional[datetime.datetime] = None\n\nclass Update_Config_Model(BaseModel):\n timestampEnd: Optional[datetime.datetime] = None\n metrics: Optional[List[Metric_Model]] = None\n\nclass Response_Config_Model(BaseModel):\n\tid: uuid.UUID\n\tcreated_at: datetime.datetime\n\tupdated_at: datetime.datetime\n\tbusinessID: str\n\ttopic: str\n\tnetworkID: int\n\ttimestampStart: datetime.datetime\n\ttimestampEnd: Optional[datetime.datetime] = None\n\tmetrics: List[Response_Metric_Model]\n\tstatus: int\n\ttenantID: str\n\tresourceID: str\n\treferenceID: str\n\nclass Response_Error_Model(BaseModel):\n\tstatus: str\n\tmessage: str\n\n# Json response example\njson_response_enable = {\"id\": \"ab51f3e1-7b61-4f9d-85a4-9e9f366b593b\",\"created_at\": \"2021-03-11T11:34:00.402075\",\"updated_at\": \"null\",\"businessID\": 36574564,\"businessID\": \"business1\", \"topic\": \"test1\", \"networkID\": 1, \"tenantID\": \"tenant1\", \"referenceID\": \"reference1\", \"resourceID\": \"resource1\",\"timestampStart\": \"2021-03-11T11:35:00\",\"timestampEnd\": \"null\",\"metrics\": [{\"metricName\": \"cpu_utilization\",\"metricType\": \"float\",\"aggregationMethod\": \"sum\",\"step\": \"15min\",\"step_aggregation\": \"1h\", \"next_run_at\": \"2021-03-11T11:45:00\", \"next_aggregation\": \"2021-03-11T12:35:00\"}],\"status\": 1}\njson_response_disable = json_response_enable.copy()\njson_response_disable['status'] = 0\n\nagg_options = ['SUM', 'AVG', 'MIN', 'MAX', 'COUNT', 'STDDEV']\n\nstep_options = ['s', 'm', 'h', 'd', 'w']\n\n\nwait_queue = PriorityQueue()\nmetrics_queue = PriorityQueue()\nnum_fetch_threads = 20\nfirst_metric_aux = None\nupdate_queue_flag = False\n\nfrom .database import *\n\ndef info_log(status, message):\n\tlogging.critical('\"status\": \"'+str(status)+'\", \"message\": \"'+message+'\"')\n\n# Update first metric to read\ndef update_first_metric_aux():\n global wait_queue\n if wait_queue.empty():\n return None\n aux = wait_queue.get()\n wait_queue.put(aux)\n return aux[0]\n \ndef send_kafka(data, dataHash, kafka_topic):\n try:\n payload_encoded = {k: str(v).encode('utf-8') for k, v in dataHash.items()}\n hashData = {k: hashlib.sha256(v).hexdigest() for k,v in payload_encoded.items()}\n #info_log(None, f'Raw Data: {data} \\nHashed Data: {hashData}')\n \n public_key, private_key = rsa.newkeys(1024)\n \n dataHashEncrypt = {rsa.encrypt(k.encode(), private_key): rsa.encrypt(v.encode(), private_key) for k,v in hashData.items()}\n #info_log(None, f'Signup Data: {dataHashEncrypt}')\n \n producer = KafkaProducer(bootstrap_servers=[KAFKA_HOST+':'+KAFKA_PORT], value_serializer=lambda x: json.dumps(x).encode('utf-8'), api_version=(0,10,1))\n producer.send(kafka_topic, key=list(dataHashEncrypt.values())[0], value=data)\n info_log(200, f'Post metric {data[\"monitoringData\"][\"metricName\"]}, from operator {data[\"operatorID\"]}, into DL Kafka Topic {kafka_topic} [Post Time: {data[\"monitoringData\"][\"timestamp\"]}]')\n return 1\n except Exception as e:\n info_log(400, 'Erro in request_orchestrator: ' + str(e))\n return 0\n \ndef send_aggregation(metric_name, resourceID, referenceID, next_run_at, tenantID, businessID, networkID, kafka_topic, aggregation, metric_id, next_aggregation, step_aggregation):\n try:\n value = get_last_aggregation(metric_id, aggregation, next_aggregation, step_aggregation)\n # Create JSON object that will be sent to DL Kafka Topic\n monitoringData = {\n \"metricName\" : metric_name,\n \"metricValue\" : value,\n \"resourceID\" : resourceID,\n \"referenceID\" : referenceID,\n \"timestamp\" : str(next_run_at),\n \"aggregationMethod\": aggregation\n }\n \n dataHash = {\n \"data\" : monitoringData\n }\n \n data = {\n \"operatorID\" : tenantID,\n \"businessID\" : businessID,\n \"networkID\" : networkID\n }\n data[\"monitoringData\"] = monitoringData\n send_kafka(data, dataHash, kafka_topic)\n print('SEND AGGREGATION-> '+str(next_run_at)+' -> '+ str(value))\n return 1\n except Exception as e:\n print('send_aggregation-> ' + str(e))\n info_log(400, 'Erro in request_orchestrator: ' + str(e))\n return 0\n \ndef request_orchestrator(metric_name, resourceID, referenceID, next_run_at, tenantID, businessID, networkID, kafka_topic, aggregation, metric_id):\n try:\n request_metric = \"match=\"+metric_name+\"&\"\n request_schedule = \"start=\"+str(next_run_at) \n # curl TBD to 'http://localhost:9090/api/v1/query=cpu_utilization&time=2015-07-01T20:10:51'\n endpoint = 'http://osm:4500/monitoringData?'\n request_url = endpoint + request_metric + request_schedule\n response = requests.get(request_url)\n if response.status_code != 200:\n info_log(400, \"Request to OSM not sucessful\")\n #print(f'Error: Request to OSM not successful')\n return('Error in fetching data!', 200)\n resp = response.text\n json_data = json.loads(resp)\n info_log(None, f'Response from OSM: {resp}')\n \n if aggregation != None:\n #Save value in db\n insert_metric_value(metric_id, json_data[\"data\"][\"result\"][0][\"values\"][0][1], next_run_at)\n else:\n # Create JSON object that will be sent to DL Kafka Topic\n monitoringData = {\n \"metricName\" : json_data[\"data\"][\"result\"][0][\"metric\"][\"__name__\"],\n \"metricValue\" : json_data[\"data\"][\"result\"][0][\"values\"][0][1],\n \"resourceID\" : resourceID,\n \"referenceID\" : referenceID,\n \"timestamp\" : str(next_run_at)\n }\n \n dataHash = {\n \"data\" : monitoringData\n }\n \n data = {\n \"operatorID\" : tenantID,\n \"businessID\" : businessID,\n \"networkID\" : networkID\n }\n data[\"monitoringData\"] = monitoringData\n send_kafka(data, dataHash, kafka_topic)\n print('SEND DATA-> '+str(next_run_at)+' -> '+ str(json_data[\"data\"][\"result\"][0][\"values\"][0][1]))\n return 1\n except Exception as e:\n print('request_orchestrator-> ' + str(e))\n info_log(400, 'Erro in request_orchestrator: ' + str(e))\n return 0\n\n# Worker thread function\ndef queue_consumer(i, q):\n global update_queue_flag\n try:\n while True:\n next_item = q.get()\n info_log(None, f'Start Fetching Values of Metric: {next_item[5]} (Thread Associated: {i})')\n \n if next_item[16] == 1:\n #Send aggregation\n info_log(None, f'{datetime.datetime.now()} - UC1: Aggregating values from metric: {next_item[5]} (Step Aggregation Associated: {next_item[14]})')\n send_aggregation(next_item[5], next_item[12], next_item[13], next_item[0], next_item[11], next_item[8], next_item[10], next_item[9], next_item[7], next_item[4], next_item[15], next_item[14])\n else:\n #Send metric\n request_orchestrator(next_item[5], next_item[12], next_item[13], next_item[0], next_item[11], next_item[8], next_item[10], next_item[9], next_item[7], next_item[4])\n info_log(None, f'{datetime.datetime.now()} - UC2: Fetching values from OSM, metric: {next_item[5]} (Step Associated: {next_item[2]}')\n update_next_run(next_item[4])\n \n update_queue_flag = True\n q.task_done()\n except Exception as e:\n print(e)\n \ndef validate_uuid4(uuid_string):\n try:\n uuid.UUID(uuid_string).hex\n except ValueError:\n \treturn False\n return True\n# --------------------- START SCRIPT -----------------------------#\n# ----------------------------------------------------------------#\n# Load database metrics to wait queue\nload_database_metrics()\n\n# Update first metric to read\nfirst_metric_aux = update_first_metric_aux()\n\n# Set up threads to fetch the metrics\nfor i in range(num_fetch_threads):\n\tworker = Thread(target=queue_consumer, args=(i, metrics_queue,))\n\tworker.setDaemon(True)\n\tworker.start()\n\n# Check waiting metrics\ntl = Timeloop()\nlogging.getLogger(\"timeloop\").setLevel(logging.CRITICAL)\n@tl.job(interval=timedelta(seconds=1))\ndef check_waiting_metrics():\n global metrics_queue\n global wait_queue\n global update_queue_flag\n global first_metric_aux\n '''print('RUN TIMELOOP')\n print('metrics_queue')\n print(metrics_queue.queue)\n print('wait_queue')\n print(wait_queue.queue)\n print('update_queue_flag')\n print(update_queue_flag)\n print('first_metric_aux')\n print(first_metric_aux)\n print('now')\n print(str(datetime.datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")))'''\n if update_queue_flag:\n first_metric_aux = update_first_metric_aux()\n update_queue_flag = False\n if first_metric_aux != None and str(first_metric_aux) <= str(datetime.datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")):\n metrics_queue.put(wait_queue.get())\n first_metric_aux = update_first_metric_aux()\n return\ntl.start(block=False)\n\n# ----------------------- MAIN APP -------------------------------#\n# ----------------------------------------------------------------#\n\napp = FastAPI()\n\n@app.on_event(\"shutdown\")\ndef shutdown_event():\n print('exit')\n global metrics_queue\n global wait_queue\n wait_queue.join()\n metrics_queue.join()\n #Close connection db\n close_connection()\n return\n\n\n# ----------------- REST FASTAPI METHODS -------------------------#\n# ----------------------------------------------------------------#\n\n@app.post(\"/settings\", status_code=201, responses={201: {\"model\": Response_Config_Model,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t \"content\": {\"application/json\": {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t \"example\": json_response_enable}}},\n\t\t\t\t\t\t\t\t\t\t\t\t 404: {\"model\": Response_Error_Model,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t \"content\": {\"application/json\": {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t \"example\": {\"status\": \"Error\", \"message\": \"Error message.\"}}}}})\nasync def set_param(config: Config_Model):\n global update_queue_flag\n for metric in config.metrics:\n if metric.aggregationMethod != None and metric.aggregationMethod.upper() not in agg_options:\n return JSONResponse(status_code=404, content={\"status\": \"Error\", \"message\": \"Aggregation step options is \"+str(agg_options)+\".\"})\n if metric.step_aggregation != None and metric.step_aggregation[-1] not in step_options and metric.step[-1] not in step_options:\n return JSONResponse(status_code=404, content={\"status\": \"Error\", \"message\": \"Step and step aggregation options is \"+str(step_options)+\".\"})\n if config.timestampStart == None:\n config.timestampStart = datetime.datetime.now()\n elif config.timestampStart < datetime.datetime.now() - relativedelta(minutes=1):\n return JSONResponse(status_code=404, content={\"status\": \"Error\", \"message\": \"Timestamp start need to be after current now.\"})\n if config.timestampEnd != None and config.timestampStart > config.timestampEnd:\n return JSONResponse(status_code=404, content={\"status\": \"Error\", \"message\": \"Timestamp start need to be after timestamp end.\"})\n # Save config in database\n resp = add_config(config)\n if resp == -1:\n return JSONResponse(status_code=404, content={\"status\": \"Error\", \"message\": \"Error in create config in database.\"})\n update_queue_flag = True\n info_log(200, f'Monitoring spec successfully created by operator {config.tenantID}')\n return resp\n\n@app.get(\"/settings/{config_id}\", responses={200: {\"model\": Response_Config_Model,\n\t\t\t\t\t\t\t\t\t\t\t\t \"content\": {\"application/json\": {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t \"example\": json_response_enable}}},\n\t\t\t\t\t\t\t\t\t\t\t 404: {\"model\": Response_Error_Model,\n\t\t\t\t\t\t\t\t\t\t\t\t \"content\": {\"application/json\": {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t \"example\": {\"status\": \"Error\", \"message\": \"Error message.\"}}}}})\nasync def get_config_id(config_id):\n # Get config by id\n if validate_uuid4(config_id) is False:\n return JSONResponse(status_code=404, content={\"status\": \"Error\", \"message\": \"Config id invalid.\"})\n resp = get_config(config_id)\n if resp == 0:\n return JSONResponse(status_code=404, content={\"status\": \"Error\", \"message\": \"Config id invalid.\"})\n if resp == -1:\n return JSONResponse(status_code=404, content={\"status\": \"Error\", \"message\": \"Error in get config in database.\"})\n return resp\n\n@app.get(\"/settings\", responses={200: {\"model\": List[Response_Config_Model],\n\t\t\t\t\t\t\t\t\t \"content\": {\"application/json\": {\n\t\t\t\t\t\t\t\t\t\t\t\t \"example\": [json_response_enable]}}},\n\t\t\t\t\t\t\t\t 404: {\"model\": Response_Error_Model,\n\t\t\t\t\t\t\t\t\t \"content\": {\"application/json\": {\n\t\t\t\t\t\t\t\t\t\t\t\t \"example\": {\"status\": \"Error\", \"message\": \"Error message.\"}}}}})\nasync def get_all_configs():\n # Get configs\n resp = get_configs()\n if resp == -1:\n return JSONResponse(status_code=404, content={\"status\": \"Error\", \"message\": \"Error in get config in database.\"})\n return resp\n\n@app.put(\"/settings/{config_id}\", responses={200: {\"model\": Response_Config_Model,\n\t\t\t\t\t\t\t\t\t\t\t\t \"content\": {\"application/json\": {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t \"example\": json_response_enable}}},\n\t\t\t\t\t\t\t\t\t\t\t 404: {\"model\": Response_Error_Model,\n\t\t\t\t\t\t\t\t\t\t\t\t \"content\": {\"application/json\": {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t \"example\": {\"status\": \"Error\", \"message\": \"Error message.\"}}}}})\nasync def update_config_id(config_id, config: Update_Config_Model):\n global update_queue_flag\n # Update config by id\n if validate_uuid4(config_id) is False:\n return JSONResponse(status_code=404, content={\"status\": \"Error\", \"message\": \"Config id invalid.\"})\n resp = update_config(config_id, config)\n if resp == 0:\n return JSONResponse(status_code=404, content={\"status\": \"Error\", \"message\": \"Config id invalid.\"})\n if resp == 1:\n return JSONResponse(status_code=404, content={\"status\": \"Error\", \"message\": \"Arguments invalid.\"})\n if resp == 2:\n return JSONResponse(status_code=404, content={\"status\": \"Error\", \"message\": \"Timestamp end must be superior to the actual.\"})\n if resp == -1:\n return JSONResponse(status_code=404, content={\"status\": \"Error\", \"message\": \"Error in update config in database.\"})\n update_queue_flag = True\n info_log(200, f'Monitoring spec {config_id} successfully updated')\n return resp\n\n@app.put(\"/settings/{config_id}/enable\", responses={200: {\"model\": Response_Config_Model,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t \"content\": {\"application/json\": {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t \"example\": json_response_enable}}},\n\t\t\t\t\t\t\t\t\t\t\t\t\t404: {\"model\": Response_Error_Model,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t \"content\": {\"application/json\": {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t \"example\": {\"status\": \"Error\", \"message\": \"Error message.\"}}}}})\nasync def enable_config_id(config_id):\n global update_queue_flag\n # Enable config by id\n if validate_uuid4(config_id) is False:\n return JSONResponse(status_code=404, content={\"status\": \"Error\", \"message\": \"Config id invalid.\"})\n resp = enable_config(config_id)\n if resp == 0:\n return JSONResponse(status_code=404, content={\"status\": \"Error\", \"message\": \"Config id invalid.\"})\n if resp == 1:\n return JSONResponse(status_code=404, content={\"status\": \"Error\", \"message\": \"Config already enabled.\"})\n if resp == -1:\n return JSONResponse(status_code=404, content={\"status\": \"Error\", \"message\": \"Error in enable config in database.\"})\n update_queue_flag = True\n info_log(200, f'Monitoring spec {config_id} successfully enabled')\n return resp\n\n@app.put(\"/settings/{config_id}/disable\", responses={200: {\"model\": Response_Config_Model,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t \"content\": {\"application/json\": {\n \"example\": json_response_disable}}},\n\t\t\t\t\t\t\t\t\t\t\t\t\t 404: {\"model\": Response_Error_Model,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t \"content\": {\"application/json\": {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t \"example\": {\"status\": \"Error\", \"message\": \"Error message.\"}}}}})\nasync def disable_config_id(config_id):\n global update_queue_flag\n # Disable config by id\n if validate_uuid4(config_id) is False:\n return JSONResponse(status_code=404, content={\"status\": \"Error\", \"message\": \"Config id invalid.\"})\n resp = disable_config(config_id)\n if resp == 0:\n return JSONResponse(status_code=404, content={\"status\": \"Error\", \"message\": \"Config id invalid.\"})\n if resp == 1:\n return JSONResponse(status_code=404, content={\"status\": \"Error\", \"message\": \"Config already disabled.\"})\n if resp == -1:\n return JSONResponse(status_code=404, content={\"status\": \"Error\", \"message\": \"Error in disable config in database.\"})\n update_queue_flag = True\n info_log(200, f'Monitoring spec {config_id} successfully disabled')\n return resp\n\n@app.delete(\"/settings/{config_id}\", status_code=HTTP_204_NO_CONTENT, responses={404: {\"model\": Response_Error_Model,\n\t\t\t\t\t\t\t\t\t\t\t\t\t \"content\": {\"application/json\": {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t \"example\": {\"status\": \"Error\", \"message\": \"Error message.\"}}}}})\nasync def delete_config_id(config_id):\n global update_queue_flag\n # Get config by id\n if validate_uuid4(config_id) is False:\n return JSONResponse(status_code=404, content={\"status\": \"Error\", \"message\": \"Config id invalid.\"})\n resp = delete_config(config_id)\n if resp == 0:\n return JSONResponse(status_code=404, content={\"status\": \"Error\", \"message\": \"Config id invalid.\"})\n if resp == -1:\n return JSONResponse(status_code=404, content={\"status\": \"Error\", \"message\": \"Error in delete config in database.\"})\n update_queue_flag = True\n info_log(200, f'Monitoring spec {config_id} successfully deleted')\n return Response(status_code=HTTP_204_NO_CONTENT)\n","sub_path":"mda/app/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":19100,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"58798380","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom csvReader import merge_set, monthly_data\nimport os\nimport random\nfrom numpy.polynomial.polynomial import polyfit\nfrom scipy.signal import savgol_filter\n\n\nclass Graph:\n def __init__(self):\n self.fileList = self.getrandom()\n self.yhat = 0.0\n self.convertData()\n self.data = []\n\n def getLocationData(self):\n from Stations import Stations\n self.fileList = Stations().getStations()\n\n def getrandom(self):\n fileList = []\n for i in range(1000):\n fileList.append(random.choice(open('Temp_Data.txt', 'r').readlines()).split('.')[0])\n return fileList\n\n def convertData(self):\n # Converts file data\n self.data = monthly_data('gsom-latest/' + self.fileList[0] + '.csv')\n for file in self.fileList:\n file += '.csv'\n data2 = monthly_data('gsom-latest/' + file)\n self.data = merge_set(data, data2)\n self.yhat = savgol_filter(list(data.values()), 51, 3)\n self.yhat = savgol_filter(yhat, 51, 3)\n\n def display(self):\n # graphs monthly data and average data\n plt.plot(data.keys(), data.values(), '-')\n plt.plot(data.keys(), yhat, '-')\n plt.savefig('figure.png')\n\n def lines(self):\n # converts data to a stack so it can be used in plt.imshow\n img_data = np.stack((yhat, yhat))\n plt.figure(figsize=(6, 18))\n\n # Displays the Data as a gradient image based on temp\n plt.imshow(img_data, cmap='RdBu_r', aspect=40)\n plt.axis('off')\n plt.show()\n # saves cropped Image\n plt.savefig('stripes.png', bbox_inches='tight', dpi=400)\n\n\ndef main():\n grapher = Graph()\n grapher.display()\n grapher.lines()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"noble_newts/display.py","file_name":"display.py","file_ext":"py","file_size_in_byte":1825,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"311395450","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Mon Sep 28 10:40:21 2020\r\n\r\n@author: ayush\r\n\"\"\"\r\n\r\n#!/bin/python3\r\n\r\nimport math\r\nimport os\r\nimport random\r\nimport re\r\nimport sys\r\n\r\n#\r\n# Complete the 'diagonalDifference' function below.\r\n#\r\n# The function is expected to return an INTEGER.\r\n# The function accepts 2D_INTEGER_ARRAY arr as parameter.\r\n#\r\n\r\ndef diagonalDifference(arr):\r\n left=right=0\r\n for i in range(n):\r\n left+=arr[i][i]\r\n right+=arr[i][n-1-i]\r\n return abs(left - right)\r\n # Write your code here\r\n\r\nif __name__ == '__main__':\r\n\r\n n = int(input().strip())\r\n\r\n arr = []\r\n\r\n for _ in range(n):\r\n arr.append(list(map(int, input().rstrip().split())))\r\n\r\n result = diagonalDifference(arr)\r\n\r\n print(result)\r\n\r\n","sub_path":"Diagonal Difference.py","file_name":"Diagonal Difference.py","file_ext":"py","file_size_in_byte":761,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"483732338","text":"from src.filestream import read as r\nimport src.operator as do\nfrom src.converters import cto_int, cto_flt, cto_str, cto_chr\n\n\ndef getrules():\n rules = {\n \"comment\" : \"#\",\n \"tuple_bgn\" : \"{\",\n \"tuple_end\" : \"}\",\n \"setvarto\" : \"=\",\n \"var_types\" : (\n \"int\", \"flt\", \"str\", \"chr\"\n )\n }\n return rules\n\n\ndef load(filename):\n error = \"\"\n rules = getrules()\n lines_list = r(filename, \"lines\")\n #Remove comments\n list0 = do.rem_comments(lines_list)\n #Remove empty lines\n list0.remove([])\n\n chars = do.charlist(list0)\n rawlist = chars.split()\n wordlist = do.tuples(rules, rawlist)\n raw_stat_list = do.r_statements(wordlist)\n #\n\n #Conversion\n defines = {}\n index = 0\n for statement in raw_stat_list:\n index += 1\n if statement[2] != rules[\"setvarto\"]:\n error = \"Invalid Syntax (Error in statement #\" + str(index) +\", word '\"\n error += statement[2] + \"')\"\n break\n vartype = statement[0].lower()\n if vartype not in rules[\"var_types\"]:\n error = \"Invalid Variable Type (Error in statement #\"\n error += str(index) + \", Type: '\" + statement[0] + \"' is not valid)\"\n break\n else:\n if vartype == rules[\"var_types\"][0]:\n defines.update({statement[1]:cto_int(statement[3])})\n elif vartype == rules[\"var_types\"][1]:\n defines.update({statement[1]:cto_flt(statement[3])})\n elif vartype == rules[\"var_types\"][2]:\n defines.update({statement[1]:cto_str(statement[3])})\n elif vartype == rules[\"var_types\"][3]:\n defines.update({statement[1]:cto_chr(statement[3])})\n\n if error != \"\":\n defines = {\n \"error\" : error\n }\n return defines\n","sub_path":"src/loader.py","file_name":"loader.py","file_ext":"py","file_size_in_byte":1850,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"122349082","text":"import pickle\nimport numpy as np\nimport os\nfrom os import path\nfrom sklearn import svm\nfrom sklearn.cluster import KMeans\nfrom sklearn.model_selection import train_test_split\nfrom sklearn import metrics\n\n\ndef transformCommand(command):\n if 'MOVE_RIGHT' == command:\n return 1\n elif 'MOVE_LEFT' == command:\n return 2\n else:\n return 0\n\nif __name__ == '__main__':\n # read all file under log \n # 因為 pickle 存的是放在列表裡的字典,先宣告一個空列表\n Data = list()\n # 目標檔案夾\n folder = path.join(path.dirname(__file__), 'log')\n # 檔案夾下的所有檔案名稱 \n files = os.listdir(folder)\n for f in files:\n # 絕對路徑\n fullpath = path.join(folder, f)\n with open(fullpath, 'rb') as file:\n # handle 為放字典的列表\n handle = pickle.load(file)\n # 將字典取出,再放入 data 列表\n for i in range(len(handle)):\n Data.append(handle[i])\n data = np.zeros((len(Data), 1))\n\n # 8 features\n # 0\n Ball_x = []\n for i in range(len(Data)):\n Ball_x.append(Data[i]['ball'][0])\n Ball_x = np.array(Ball_x)\n Ball_x = Ball_x.reshape(len(Ball_x), 1)\n data = np.hstack((data, Ball_x))\n # 1\n Ball_y = []\n for i in range(len(Data)):\n Ball_y.append(Data[i]['ball'][1])\n Ball_y = np.array(Ball_y)\n Ball_y = Ball_y.reshape(len(Ball_y), 1)\n data = np.hstack((data, Ball_y))\n # 2\n Ball_vx = []\n for i in range(len(Data)):\n Ball_vx.append(Data[i]['ball_speed'][0])\n Ball_vx = np.array(Ball_vx)\n Ball_vx = Ball_vx.reshape(len(Ball_vx), 1)\n data = np.hstack((data, Ball_vx))\n # 3\n Ball_vy = []\n for i in range(len(Data)):\n Ball_vy.append(Data[i]['ball_speed'][1])\n Ball_vy = np.array(Ball_vy)\n Ball_vy = Ball_vy.reshape(len(Ball_vy), 1)\n data = np.hstack((data, Ball_vy))\n # 4\n plat1_x = []\n for i in range (len(Data)):\n plat1_x.append(Data[i]['platform_1P'][0])\n plat1_x = np.array(plat1_x)\n plat1_x = plat1_x.reshape(len(plat1_x), 1)\n data = np.hstack((data, plat1_x))\n # 5\n plat1_y = []\n for i in range (len(Data)):\n plat1_y.append(Data[i]['platform_1P'][1])\n plat1_y = np.array(plat1_y)\n plat1_y = plat1_y.reshape(len(plat1_y), 1)\n data = np.hstack((data, plat1_y))\n\n plat2_x = []\n for i in range(len(Data)):\n plat2_x.append(Data[i]['platform_2P'][0])\n plat2_x = np.array(plat2_x)\n plat2_x = plat2_x.reshape(len(plat2_x), 1)\n data = np.hstack((data, plat2_x))\n\n plat2_y = []\n for i in range(len(Data)):\n plat2_y.append(Data[i]['platform_2P'][1])\n plat2_y = np.array(plat2_y)\n plat2_y = plat2_y.reshape(len(plat2_y), 1)\n data = np.hstack((data, plat2_y))\n # 6\n blocker_x = []\n for i in range(len(Data)):\n blocker_x.append(Data[i]['blocker'][0])\n blocker_x = np.array(blocker_x)\n blocker_x = blocker_x.reshape(len(blocker_x), 1)\n data = np.hstack((data, blocker_x))\n # 7\n blocker_y = []\n for i in range(len(Data)):\n blocker_y.append(Data[i]['blocker'][1])\n blocker_y = np.array(blocker_y)\n blocker_y = blocker_y.reshape(len(blocker_y), 1)\n data = np.hstack((data, blocker_y))\n\n pred_same = []\n pred_minus5 = []\n pred_minus10 = []\n pred_minus15 = []\n pred_minus20 = []\n pred_add5 = []\n pred_add10 = []\n pred_add15 = []\n pred_add20 = []\n for i in range(len(Data)):\n if Data[i][\"ball_speed\"][1] > 0 : # 球正在向下 # ball goes down\n x = ( Data[i][\"platform_1P\"][1]-Data[i][\"ball\"][1] ) // Data[i][\"ball_speed\"][1] # 幾個frame以後會需要接 # x means how many frames before catch the ball\n pred = Data[i][\"ball\"][0]+(Data[i][\"ball_speed\"][0]*x) # 預測最終位置 # pred means predict ball landing site \n bound = pred // 200 # Determine if it is beyond the boundary\n if (bound > 0): # pred > 200 # fix landing position\n if (bound%2 == 0) : \n pred = pred - bound*200 \n else :\n pred = 200 - (pred - 200*bound)\n elif (bound < 0) : # pred < 0\n if (bound%2 ==1) :\n pred = abs(pred - (bound+1) *200)\n else :\n pred = pred + (abs(bound)*200)\n elif Data[i][\"ball\"][1] >= 240:\n rev_bvx = 0 - Data[i][\"ball_speed\"][0]\n rev_bvy = 0 - Data[i][\"ball_speed\"][1]\n if(rev_bvy == 0):\n x = 0\n else:\n x = ( Data[i][\"platform_1P\"][1]-Data[i][\"ball\"][1] ) // rev_bvy # 幾個frame以後會需要接 # x means how many frames before catch the ball\n pred = Data[i][\"ball\"][0]+((rev_bvx + np.sign(rev_bvx) * 5)*x) # 預測最終位置 # pred means predict ball landing site \n bound = pred // 200 # Determine if it is beyond the boundary\n if (bound > 0): # pred > 200 # fix landing position\n if (bound%2 == 0) : \n pred = pred - bound*200 \n else :\n pred = 200 - (pred - 200*bound)\n elif (bound < 0) : # pred < 0\n if (bound%2 ==1) :\n pred = abs(pred - (bound+1) *200)\n else :\n pred = pred + (abs(bound)*200)\n else : # 球正在向上 # ball goes up\n pred = 100\n\n pred_same.append(pred)\n pred_minus5.append(pred - 5)\n pred_minus10.append(pred - 10)\n pred_minus15.append(pred - 15)\n pred_minus20.append(pred - 20)\n pred_add5.append(pred + 5)\n pred_add10.append(pred + 10)\n pred_add15.append(pred + 15)\n pred_add20.append(pred + 20)\n \n pred_same = np.array(pred_same)\n pred_same = pred_same.reshape(len(pred_same), 1)\n data = np.hstack((data, pred_same))\n\n pred_minus5 = np.array(pred_minus5)\n pred_minus5 = pred_minus5.reshape(len(pred_minus5), 1)\n data = np.hstack((data, pred_minus5))\n\n pred_minus10 = np.array(pred_minus10)\n pred_minus10 = pred_minus10.reshape(len(pred_minus10), 1)\n data = np.hstack((data, pred_minus10))\n\n # pred_minus15 = np.array(pred_minus15)\n # pred_minus15 = pred_minus15.reshape(len(pred_minus15), 1)\n # data = np.hstack((data, pred_minus15))\n\n # pred_minus20 = np.array(pred_minus20)\n # pred_minus20 = pred_minus20.reshape(len(pred_minus20), 1)\n # data = np.hstack((data, pred_minus20))\n\n pred_add5 = np.array(pred_add5)\n pred_add5 = pred_same.reshape(len(pred_add5), 1)\n data = np.hstack((data, pred_add5))\n\n pred_add10 = np.array(pred_add10)\n pred_add10 = pred_add10.reshape(len(pred_add10), 1)\n data = np.hstack((data, pred_add10))\n\n # pred_add15 = np.array(pred_add15)\n # pred_add15 = pred_add15.reshape(len(pred_add15), 1)\n # data = np.hstack((data, pred_add15))\n\n # pred_add20 = np.array(pred_add20)\n # pred_add20 = pred_add20.reshape(len(pred_add20), 1)\n # data = np.hstack((data, pred_add20))\n\n command_1P = []\n for i in range(len(Data)):\n command_1P.append(transformCommand(Data[i]['command_1P']))\n command_1P = np.array(command_1P)\n command_1P = command_1P.reshape(len(command_1P), 1)\n data = np.hstack((data, command_1P))\n\n data = data[:,1:]\n\n X = data[:, :-1]\n Y = data[:, -1]\n\n x_train , x_test,y_train,y_test = train_test_split(X,Y,test_size=0.2)\n kmeans = KMeans(n_clusters=3, random_state=0).fit(x_train,y_train) \n y_predict = kmeans.predict(x_test)\n print(y_predict)\n count0 = count1 = count2 = 0\n for i in range(len(y_predict)):\n if(y_predict[i] == 0):\n count0 += 1\n elif(y_predict[i] == 1):\n count1 += 1\n else:\n count2 += 1\n accuracy = metrics.accuracy_score(y_test, y_predict)\n print(\"Accuracy(正確率) ={:8.3f}%\".format(accuracy*100))\n\n print(count0)\n print(count1)\n print(count2)\n\n with open('games/pingpong/ml/save/trained_model.pickle', 'wb') as f:\n pickle.dump(kmeans, f)\n\n","sub_path":"games/pingpong/predicted_model_kmeans.py","file_name":"predicted_model_kmeans.py","file_ext":"py","file_size_in_byte":8139,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"271574670","text":"# -*- coding: utf-8 -*-\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\nfrom tqdm.auto import tqdm\nimport glob\nfrom lightgbm import LGBMClassifier, LGBMRegressor\nfrom sklearn.model_selection import GridSearchCV\nfrom sklearn.model_selection import KFold\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import confusion_matrix, mean_squared_error, mean_absolute_error\nimport pickle\n\n\nfiles = glob.glob(\"../Data Collection/training_data/*.csv\")\ndataset = []\nfor file in tqdm(files):\n data = pd.read_csv(file)\n dataset.append(data)\n\ndataset = pd.concat(dataset, axis=0, ignore_index=True)\n\n# Select features\nselect_X_columns = ['num_of_paramters','gpu', 'is_distributed', \n 'num_workers_data_loader', 'num_of_gpus', 'batch_size']\nselect_y_columns = ['epoch_timings']\n\nX, y = dataset[select_X_columns], dataset[select_y_columns]\n\n#Preprocess GPU feature\ndevice_list = ['P40', 'P100', 'V100']\nfor i, device_name in enumerate(X['gpu']):\n for device in device_list:\n if device in device_name:\n X['gpu'][i] = device\n break\ngpu = pd.get_dummies(X['gpu'], drop_first=False)\nX = pd.concat([X, gpu], axis=1)\nX.drop(['gpu'], axis=1, inplace=True)\n\n# Initializing the model\nregressor = LGBMRegressor(boosting_type='gbdt', max_depth=- 1)\n\n# Hyperparameter optimization \nkfold = KFold(n_splits=5, shuffle=True, random_state=42).split(X=X, y=y)\nparam_grid = {\n 'num_leaves': [10, 31, 127],\n 'reg_alpha': [0.1, 0.5],\n 'learning_rate': [0.1, 0.5, 0.01],\n 'n_estimators': [5, 10, 20]\n}\ngsearch = GridSearchCV(estimator=regressor, param_grid=param_grid, cv=kfold)\nlgb_model = gsearch.fit(X=X, y=y)\n\nprint(lgb_model.best_params_, lgb_model.best_score_)\n\n# Evaluating the model\nfor param in lgb_model.best_params_:\n setattr(regressor, param, lgb_model.best_params_[param])\n\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2)\n\nregressor.fit(X_train, y_train)\ny_pred = regressor.predict(X_test)\n\nMSE = mean_squared_error(y_test, y_pred)\nMAE = mean_absolute_error(y_test, y_pred)\nRMSE = MSE**(1/2)\nprint(\"Validation results: MAE:%3f RMSE:%3f\"%(MAE, RMSE))\n\n# Train on entire dataset to save model\nregressor.fit(X, y)\nfilename = 'optimus_prime_epoch_time.pkl'\npickle.dump(regressor, open(filename, 'wb'))","sub_path":"Optimus Prime/model_training.py","file_name":"model_training.py","file_ext":"py","file_size_in_byte":2322,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"186010249","text":"from PIL import Image\nimport numpy as np\nimport torchvision.transforms as transforms\nfrom torch.utils.data import Dataset\nfrom pathlib import Path\nimport torch\nfrom tqdm.auto import tqdm\n\nclass masked_dataset(Dataset):\n def __init__(self,path=\"\",maxx=0):\n self.normal = []\n self.masked = []\n \n for i in tqdm((Path(path)/'normal').glob(\"*.jpg\")):\n self.normal.append(i)\n name = str(i).split('/')[-1]\n self.masked.append(Path(path)/f\"masked/{name}\")\n \n if len(self.masked) >= maxx:\n break\n\n \n def __getitem__(self, idx):\n img = Image.open(self.normal[idx]).resize((224,224))\n x = np.array(img) \n x = transforms.ToTensor()(img)\n \n mask = Image.open(self.masked[idx]).resize((224,224))\n mask = np.array(mask) \n mask = transforms.ToTensor()(mask)\n\n return x,mask\n\n def __len__(self):\n return len(self.masked)\n","sub_path":"dataset.py","file_name":"dataset.py","file_ext":"py","file_size_in_byte":978,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"72953546","text":"import matplotlib.pyplot as plt\nimport numpy as np\nfrom sklearn.decomposition import PCA\nfrom sklearn.decomposition import NMF\n\n\n\n# Assuming data of 4-class\ndef plot_points(x, y):\n x1 = list()\n x2 = list()\n x3 = list()\n x4 = list()\n y1 = list()\n y2 = list()\n y3 = list()\n y4 = list()\n for i in range(y.shape[0]):\n if y[i] == 1:\n x1.append(x[i, 0])\n y1.append(x[i, 1])\n elif y[i] == 2:\n x2.append(x[i, 0])\n y2.append(x[i, 1])\n elif y[i] == 3:\n x3.append(x[i, 0])\n y3.append(x[i, 1])\n else:\n x4.append(x[i, 0])\n y4.append(x[i, 1])\n\n plt.scatter(x1, y1, color=['red'], label='Cluster 1', edgecolors=(0, 0, 0))\n plt.scatter(x2, y2, color=['green'], label='Cluster 2', edgecolors=(0, 0, 0))\n plt.scatter(x3, y3, color=['blue'], label='Cluster 3', edgecolors=(0, 0, 0))\n plt.scatter(x4, y4, color=['orange'], label='Cluster 4', edgecolors=(0, 0, 0))\n plt.legend()\n plt.title('Plot of data points')\n plt.show()\n\n\n# Assigning cluster no. based on coordinate system\ndef assign_cluster(x):\n if x[0] >= 0 and x[1] >= 0:\n return 1\n elif x[0] < 0 and x[1] >= 0:\n return 2\n elif x[0] < 0 and x[1] < 0:\n return 3\n else:\n return 4\n\n\n# Generating 2-d points and dividing them in 4-clusters based on co-ordinate system\n\ndef sigmoid(z):\n \"\"\"\n sigmoid calculation\n :param z:\n :return:\n \"\"\"\n z_hat = 1 / (1 + np.exp(-z))\n return z_hat\n\n\ndef to_higher_dimension(x):\n \"\"\"\n transform data from 2-d to 100-d using non-linear transformation\n assume data points to be 2-dimension\n x=sigmoid(U*sigmoid(W*x(in 2d)))\n\n :param x:\n :return:\n \"\"\"\n W = np.random.normal(loc=0, scale=1, size=(100, 2))\n # U=np.random.normal(loc=0,scale=1,size=(100,10))\n x_new = np.square(sigmoid(np.dot(W, x.T))).T\n return x_new\n\n\ndef to_higher_dimension2(x):\n W = np.random.normal(loc=0, scale=1, size=(100, 2))\n # U=np.random.normal(loc=0,scale=1,size=(100,10))\n x_new = np.tanh(sigmoid(np.dot(W, x.T))).T\n return x_new\n\n\nif __name__ == '__main__':\n x, y = syn_data_points()\n plot_points(x, y)\n plt.savefig(\"../data_points_2_dim.png\")\n plt.show()\n # plt.close()\n x_high = to_higher_dimension(x)\n\n pca = PCA(n_components=2)\n nmf=NMF(n_components=2)\n # x_pca = pca.fit_transform(x_high)\n # plot_points(x_pca, y)\n x_nmf=nmf.fit_transform(x_high)\n plot_points(x_nmf,y)\n plt.show()\n # plt.savefig(\"../data_points_100_dim.png\")\n","sub_path":"DCN/synthetic_plots.py","file_name":"synthetic_plots.py","file_ext":"py","file_size_in_byte":2585,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"193301375","text":"import time\nimport pandas as pd\nimport numpy as np\n\nCITY_DATA = { 'chicago': 'chicago.csv',\n 'new york city': 'new_york_city.csv',\n 'washington': 'washington.csv' }\n\ndef get_filters():\n \"\"\"\n Asks user to specify a city, month, and day to analyze.\n\n Returns:\n (str) city - name of the city to analyze\n (str) month - name of the month to filter by, or \"all\" to apply no month filter\n (str) day - name of the day of week to filter by, or \"all\" to apply no day filter\n \"\"\"\n print('Hello! Let\\'s explore some US bikeshare data!')\n validity = False\n\n # Get user input for city (chicago, new york city, washington). \n while True:\n city = str(input(\"\\nWhich city would you like to filter by? (Choose from Chicago, New York City, Washington): \").strip().lower())\n if city not in (\"chicago\", \"new york city\", \"washington\"):\n print(\"\\nInvalid entry. Please try again\")\n continue\n else:\n print(\"\\nIt looks like you want to see data for: '{}' \".format(city.title()))\n validity_check()\n break\n\n # Get user input for month (all, january, february, ... , june)\n while True:\n month = str(input(\"\\nType in name of month to filter by (January, February, March, April, May, June or 'All' if no preference): \").strip().lower())\n\n if month not in (\"january\", \"february\", \"march\", \"april\", \"may\", \"june\", \"all\"):\n print(\"\\nInvalid entry. Please type in month name (or \\\"all\\\" to select every month)\")\n continue\n else:\n print(\"\\nIt looks like you want to filter by: '{}' \".format(month.title()))\n validity_check()\n break\n\n # Get user input for day of week (all, monday, tuesday, ... sunday)\n while True:\n day = str(input(\"\\nType in name of day to filter by (Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday or 'All' if no preference): \").strip().lower())\n if day not in (\"monday\", \"tuesday\", \"wednesday\", \"thursday\", \"friday\", \"saturday\" , \"sunday\", \"all\"):\n print(\"Invalid entry. Please type in a valid day of week (or \\\"all\\\" to select every day)\")\n continue\n else:\n print(\"\\nIt looks like you want to filter by: '{}' \".format(day.title()))\n validity_check()\n break\n\n print(\"\\nYou selected '{}' as city, '{}' as month, and '{}' as day. \\nFiltering by your parameters....\".format(city.title(), month.title(), day.title()))\n print()\n\n print('-'*40)\n return city, month, day\n\ndef validity_check():\n \"\"\"Asks the user whether the input is correct. If not, give a chance for correction.\"\"\"\n\n while True:\n validity = str(input(\"Is your input correct? Type 'yes' to continue and 'no' to restart: \\n\").strip().lower())\n if validity not in (\"yes\", \"no\"):\n print(\"\\nInvalid entry. Please try again\")\n continue\n elif validity == 'yes':\n break\n else:\n get_filters()\n\n\ndef load_data(city, month, day):\n \"\"\"\n Loads data for the specified city and filters by month and day if applicable.\n\n Args:\n (str) city - name of the city to analyze\n (str) month - name of the month to filter by, or \"all\" to apply no month filter\n (str) day - name of the day of week to filter by, or \"all\" to apply no day filter\n Returns:\n df - Pandas DataFrame containing city data filtered by month and day\n \"\"\"\n # Load data file into a dataframe\n df = pd.read_csv(CITY_DATA[city])\n\n # Convert the 'Start Time' column to datetime\n df['Start Time'] = pd.to_datetime(df['Start Time'])\n\n # Extract month / day of week / hour from 'Start Time' to create new columns\n df['Month'] = df['Start Time'].dt.month\n df['Day'] = df['Start Time'].dt.weekday_name\n df['Hour'] = df['Start Time'].dt.hour\n\n # Filter by month if applicable\n if month != 'all':\n # Use the index of the months list to get the corresponding integer\n months = ['january', 'february', 'march', 'april', 'may', 'june']\n month = months.index(month) + 1\n\n # Filter by month to create the new dataframe\n df = df[df['Month'] == month]\n\n # Filter by day of week if applicable\n if day != 'all':\n df = df[df['Day'] == day.title()]\n\n return df\n\n\ndef time_stats(df):\n \"\"\"Displays statistics on the most frequent times of travel.\"\"\"\n\n print('\\nCalculating The Most Frequent Times of Travel...\\n')\n start_time = time.time()\n\n dictionary = {'1': 'January', '2': 'February', '3': 'March', '4': 'April', '5': 'May', '6': 'June',\n '7': 'July', '8': 'August', '9': 'September', '10': 'October', '11': 'November', '12': 'December'}\n\n # Display the most common month\n popular_month = df['Month'].mode()[0]\n month_in_string = dictionary[str(popular_month)]\n print(\"Most common month: \", month_in_string)\n\n # Display the most common day of week\n popular_day = df['Day'].mode()[0]\n print(\"Most common day of the week: \", popular_day)\n\n # Display the most common start hour\n popular_hour = df['Hour'].mode()[0]\n print('Most common start hour: ', popular_hour)\n\n print(\"\\nThis took %s seconds.\" % (time.time() - start_time))\n print('-'*40)\n\n\ndef station_stats(df):\n \"\"\"Displays statistics on the most popular stations and trip.\"\"\"\n\n print('\\nCalculating The Most Popular Stations and Trip...\\n')\n start_time = time.time()\n\n # Display most commonly used start station\n start_station = df['Start Station'].mode()[0]\n print(\"Most commonly used start station: \", start_station)\n\n # Display most commonly used end station\n end_station = df['End Station'].mode()[0]\n print(\"Most commonly used end station: \", end_station)\n\n # Display most frequent combination of start station and end station trip\n pair = df.groupby(['Start Station', 'End Station']).size().sort_values(ascending=False).reset_index(name=\"counts\")\n freq_start_pair = pair['Start Station'][0]\n freq_end_pair = pair['End Station'][0]\n print(\"Most frequent combination: Start at {}, End at {}\".format(freq_start_pair, freq_end_pair))\n\n print(\"\\nThis took %s seconds.\" % (time.time() - start_time))\n print('-'*40)\n\n\ndef trip_duration_stats(df):\n \"\"\"Displays statistics on the total and average trip duration.\"\"\"\n\n print('\\nCalculating Trip Duration...\\n')\n start_time = time.time()\n\n # Display total travel time\n total_travel_time = df['Trip Duration'].sum()\n print(\"Total travel time in seconds: \", total_travel_time)\n\n # Display mean travel time\n mean_travel_time = df['Trip Duration'].mean()\n print(\"Mean travel time in seconds: \", mean_travel_time)\n\n print(\"\\nThis took %s seconds.\" % (time.time() - start_time))\n print('-'*40)\n\n\ndef user_stats(df):\n \"\"\"Displays statistics on bikeshare users.\"\"\"\n\n print('\\nCalculating User Stats...\\n')\n start_time = time.time()\n\n # Display counts of user types\n user_type_count = df[\"User Type\"].value_counts()\n print(user_type_count)\n\n # Display counts of gender\n if \"Gender\" in df.columns:\n gender_count = df[\"Gender\"].value_counts()\n # count null values\n nan_values = df[\"Gender\"].isna().sum()\n print(\"\\nCounts by Gender: \\n{}\\n \\n*Note: there were '{}' NaN values for gender column\".format(gender_count,nan_values))\n else:\n print(\"\\nThe dataset does not have a 'Gender' column.\")\n\n # Display earliest, most recent, and most common year of birth\n if \"Birth Year\" in df.columns:\n earliest = int(df['Birth Year'].min())\n most_recent = int(df['Birth Year'].max())\n most_common = int(df['Birth Year'].mode()[0])\n print(\"\\nEarliest birth year: '{}'. \\nMost recent birth year: '{}'. \\nMost common birth year: '{}'.\".format(earliest, most_recent, most_common))\n else:\n print(\"\\nThe dataset does not have a 'Birth Year' column.\")\n\n print(\"\\nThis took %s seconds.\" % (time.time() - start_time))\n print('-'*40)\n\n\ndef display_raw_data(df):\n \"\"\"\n Asks if the user would like to see some lines of data from the filtered dataset.\n Displays 5 (show_rows) lines, then asks if they would like to see 5 more.\n Continues asking until they say stop.\n \"\"\"\n show_rows = 5\n rows_start = 0\n rows_end = show_rows - 1\n\n print('\\n Would you like to see some raw data from the current dataset?')\n while True:\n raw_data = input(' (yes or no): ')\n if raw_data.lower() == 'yes':\n print('\\n Displaying rows {} to {}:'.format(rows_start + 1, rows_end + 1))\n print('\\n', df.iloc[rows_start : rows_end + 1])\n rows_start += show_rows\n rows_end += show_rows\n print('-'*40)\n print('\\n Would you like to see the next {} rows?'.format(show_rows))\n continue\n else:\n break\n\n\ndef main():\n while True:\n city, month, day = get_filters()\n df = load_data(city, month, day)\n\n time_stats(df)\n station_stats(df)\n trip_duration_stats(df)\n user_stats(df)\n display_raw_data(df)\n\n restart = input('\\nWould you like to restart? Enter yes or no.\\n')\n if restart.lower() != 'yes':\n break\n\n\nif __name__ == \"__main__\":\n\tmain()\n","sub_path":"bikeshare.py","file_name":"bikeshare.py","file_ext":"py","file_size_in_byte":9369,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"203012598","text":"from __future__ import unicode_literals\n\nfrom django.apps import AppConfig\nfrom django.db.models import signals\n\nfrom nodeconductor.core.models import SshPublicKey\nfrom nodeconductor.core.signals import pre_serializer_fields\nfrom nodeconductor.iaas import handlers\nfrom nodeconductor.structure.models import Project\nfrom nodeconductor.structure.signals import structure_role_granted\n\n\nclass IaasConfig(AppConfig):\n name = 'nodeconductor.iaas'\n verbose_name = \"NodeConductor IaaS\"\n\n # See, https://docs.djangoproject.com/en/1.7/ref/applications/#django.apps.AppConfig.ready\n def ready(self):\n CloudProjectMembership = self.get_model('CloudProjectMembership')\n\n from nodeconductor.structure.serializers import CustomerSerializer, ProjectSerializer\n\n pre_serializer_fields.connect(\n handlers.add_clouds_to_related_model,\n sender=CustomerSerializer,\n dispatch_uid='nodeconductor.iaas.handlers.add_clouds_to_customer',\n )\n\n pre_serializer_fields.connect(\n handlers.add_clouds_to_related_model,\n sender=ProjectSerializer,\n dispatch_uid='nodeconductor.iaas.handlers.add_clouds_to_project',\n )\n\n signals.post_save.connect(\n handlers.propagate_new_users_key_to_his_projects_clouds,\n sender=SshPublicKey,\n dispatch_uid='nodeconductor.iaas.handlers.propagate_new_users_key_to_his_projects_clouds',\n )\n\n structure_role_granted.connect(\n handlers.propagate_users_keys_to_clouds_of_newly_granted_project,\n sender=Project,\n dispatch_uid='nodeconductor.iaas.handlers.propagate_users_keys_to_clouds_of_newly_granted_project',\n )\n\n signals.post_save.connect(\n handlers.create_initial_security_groups,\n sender=CloudProjectMembership,\n dispatch_uid='nodeconductor.iaas.handlers.create_initial_security_groups',\n )\n","sub_path":"nodeconductor/iaas/apps.py","file_name":"apps.py","file_ext":"py","file_size_in_byte":1955,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"464883168","text":"import numpy as np\nimport pandas as pd\nfrom numpy import genfromtxt\n\nimport re\nimport random\n\ndef get_conditions(data, pattern):\n conditions = np.unique(data[1:, 6:26])\n conditions = list(filter(None, conditions))\n return list(filter(pattern.match, conditions))\n\ndef parse():\n # train_data1 = pd.read_csv('2005_data.csv', delimiter=',', dtype=str)\n # row = np.unique(train_data1.iloc[0:,7:21])\n data_2006 = genfromtxt('2006_data.csv', max_rows=50000, delimiter=',', skip_header=1, dtype=str)\n data_2005 = genfromtxt('2005_data.csv', max_rows=50000, delimiter=',', dtype=str)\n print('reading data...')\n # train_data1 = genfromtxt('2005_data.csv', max_rows=50000, delimiter=',', dtype=str)\n # data_2007 = genfromtxt('2007_data.csv', delimiter=',', dtype=str)\n train_data1 = np.concatenate((data_2005, data_2006), axis=0)\n\n print('building dataframes...')\n processed_data = np.concatenate([train_data1[:,0:5], train_data1[:,26:]], axis=1)\n processed_dataframe = pd.DataFrame(data=processed_data[1:], columns=processed_data[0,:])\n original_dataframe = pd.DataFrame(data=train_data1[1:], columns=train_data1[0,:])\n\n # pattern = re.compile(\"^(\\d\\.\\d{2}E\\+\\d?)\")\n print('getting columns')\n filter_pattern = re.compile(\"^(?!\\d\\.\\d{2}E\\+\\d?).*\")\n conditions = get_conditions(train_data1, filter_pattern)\n\n print('adding columns')\n processed_dataframe = pd.concat(\n [\n processed_dataframe,\n pd.DataFrame(\n [[0]*len(conditions)],\n index=processed_dataframe.index,\n columns=conditions\n )\n ], axis=1\n )\n\n print('filling up columns')\n for index, row in original_dataframe.iterrows():\n for i in range(20):\n column = \"entity_condition_\" + str(i+1)\n c = row[column]\n if c:\n if not (str(c) == 'nan') and filter_pattern.match(c):\n processed_dataframe.at[index, c] = 1\n\n print(\".\", end=\"\")\n processed_dataframe.replace('', np.nan, inplace=True)\n processed_dataframe.dropna(axis=0, how='any', inplace=True)\n processed_dataframe.to_csv('data_processed.csv', index=False);\n\nparse()\n","sub_path":"parse.py","file_name":"parse.py","file_ext":"py","file_size_in_byte":2213,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"518773226","text":"import yaml\nfrom dotmap import DotMap\nimport operator\nimport os\nfrom functools import reduce\nfrom kiali_qe.components.enums import IstioConfigValidation\n\n\nclass MyDotMap(DotMap):\n\n def __init__(self, *args, **kwargs):\n DotMap.__init__(self, *args, **kwargs)\n\n def set(self, key, value):\n keys = key.split('.')\n reduce(operator.getitem, keys[:-1], self)[keys[-1]] = value\n\n def to_dict(self):\n return self.toDict()\n\n\ndef get_dict(path, yaml_file):\n return MyDotMap(get_yaml(path, yaml_file))\n\n\ndef get_yaml(path, yaml_file):\n with open(get_yaml_path(path, yaml_file), 'r') as yaml_data:\n return yaml.safe_load(yaml_data)\n\n\ndef get_yaml_path(path, yaml_file):\n return os.path.join(path, yaml_file)\n\n\ndef is_equal(object_a, object_b):\n if isinstance(object_a, list):\n if len(object_a) == len(object_b):\n for item_a in object_a:\n if isinstance(item_a, str) or isinstance(item_a, float)\\\n or isinstance(item_a, int) or isinstance(item_a, bytes):\n if item_a not in object_b:\n return False\n elif isinstance(item_a, dict):\n _is_in = False\n for item_b in object_b:\n if _cmp_dict(item_a, item_b):\n _is_in = True\n break\n if not _is_in:\n return False\n\n else:\n if not item_a.is_in(object_b):\n return False\n return True\n else:\n return False\n elif isinstance(object_a, dict):\n return _cmp_dict(object_a, object_b)\n\n\ndef _cmp_dict(a, b):\n return a == b\n\n\ndef is_sublist(list_a, list_b):\n return set(list_a).issubset(set(list_b))\n\n\ndef get_validation(_valid, _not_valid, _warning):\n if _valid:\n return IstioConfigValidation.VALID\n elif _not_valid:\n return IstioConfigValidation.NOT_VALID\n elif _warning:\n return IstioConfigValidation.WARNING\n else:\n return IstioConfigValidation.NA\n\n\ndef to_linear_string(source):\n return str(source).\\\n replace('\\n', ' ').\\\n replace('{', '').\\\n replace('}', '').\\\n replace('\"', '').\\\n replace(',', '').\\\n replace('[', '').\\\n replace(']', '').\\\n replace('{', '').\\\n replace('}', '').\\\n replace(':', '').\\\n replace('\\'', '').lower()\n\n\ndef get_texts_of_elements(elements):\n texts = []\n for _element in elements:\n texts.append(_element.text.strip())\n return texts\n","sub_path":"kiali_qe/utils/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2678,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"124449596","text":"# https://codeforces.com/gym/101889/attachments\n\ndef gcd(a, b):\n if a * b == 0:\n return a + b\n elif a == b:\n return a\n return gcd(a%b, b%a)\n\ndef phi(n):\n result = 0\n for i in range(1, n):\n if gcd(i, n) == 1:\n result = result + 1\n return result\n \ns = list(map(lambda x: x == 'R', input()))\nn = len(s)\n\ndef calc(m):\n i = 0\n while i < m:\n j= 0\n while j < n//m:\n if not s[j*m+i]:\n break\n j=j+1\n if j == n//m:\n break\n i = i+1\n if i == m:\n return False\n else:\n return True\n\ni = 1\nresult = 0\nwhile i*i <= n:\n if n%i == 0:\n if calc(i):\n result = result + phi(n//i)\n if i*i < n and i!= 1:\n if calc(n//i):\n result = result + phi(i)\n i=i+1\nprint(result)\n","sub_path":"jumping_frog.py","file_name":"jumping_frog.py","file_ext":"py","file_size_in_byte":859,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"54281432","text":"# -*- coding: utf-8 -*-\nfrom bs4 import BeautifulSoup\nfrom Products.Five.browser import BrowserView\nimport urllib2\nfrom plone import api\nfrom random import random, choice, randrange\nfrom datetime import datetime\n#from mmseg import seg_txt\nfrom Products.CMFPlone.utils import safe_unicode\nimport logging\nimport os\nfrom ..config import GET_BDM_URL_HEAD, GET_BDM_URL_TAIL\nfrom ..config import BDM_URL_HEAD, BDM_URL_TAIL\nfrom ..config import LOG_MAIL_RECIPIENT, LOG_MAIL_SENDER\nfrom zope import component\nfrom zope.app.intid.interfaces import IIntIds\nfrom plone.app.textfield.value import RichTextValue\n#以下3個import,做關聯用\nfrom z3c.relationfield import RelationValue\nfrom zope.event import notify\nfrom zope.lifecycleevent import ObjectModifiedEvent\n\n\nclass GetRelationNotice(BrowserView):\n def __call__(self):\n logger = logging.getLogger(\".getRelationNotice.GetRelationNotice\")\n portal = api.portal.get()\n catalog = api.portal.get_tool(name='portal_catalog')\n #取得公告BDM網址\n dateString = os.popen('date +%Y%m%d').read().strip()\n try:\n getBdmUrl = '%s%s%s' % (GET_BDM_URL_HEAD, dateString, GET_BDM_URL_TAIL)\n execString = 'elinks --dump %s | grep BDM' % getBdmUrl\n getBDM_Urls = os.popen(execString).read()\n except:\n raise IOError('web site NO Response')\n #取得所有網址\n urlList = list()\n for url in getBDM_Urls.split('\\n'):\n if url.split('/')[-1].strip() == '':\n continue\n bdmUrl = '%s%s%s' % (BDM_URL_HEAD, dateString, BDM_URL_TAIL)\n urlList.append(bdmUrl+url.split('/')[-1])\n #處理個別頁面\n intIds = component.getUtility(IIntIds)\n addCount = 0\n for pageUrl in urlList:\n try:\n# os.system('sleep 1s')\n if len(catalog(noticeUrl=pageUrl)) > 0:\n continue \n pageHtml = urllib2.urlopen(pageUrl).read()\n logger.info(len(pageHtml))\n soup = BeautifulSoup(pageHtml)\n find_All_T11b = soup.find_all('td', attrs={'class':'T11b', 'align':'left'})\n contentDict = []\n for item in find_All_T11b:\n attrName = safe_unicode(item.contents[0]).strip()\n attrValue = safe_unicode(item.find_next_sibling('td').contents[0]).strip()\n contentDict.append({attrName:attrValue})\n noticeDetail = ''\n for contentItem in contentDict:\n item = contentItem.popitem()\n if item[0] == u'標案名稱':\n title = item[1]\n if item[0] == u'標案案號':\n noticeId = item[1]\n noticeDetail += '<p><strong>%s%s</strong><span>%s</span></p>' % (item[0], safe_unicode(':'), item[1])\n contentId = '%s%s' % (str(datetime.now().strftime('%Y%m%d%H%M')), str(randrange(10000000,100000000)))\n #確認資料庫中有關聯項目\n relatedItems = catalog({'portal_type':'twgov.content.govnotice', 'noticeName':title, 'noticeId':noticeId})\n if len(relatedItems) == 0:\n continue\n\n\n\n api.content.create(container=portal['relation_notice'],\n type='twgov.content.relationnotice',\n title=safe_unicode(u'[決標]:'+title),\n id=contentId,\n noticeId=noticeId,\n noticeUrl=pageUrl,\n noticeDetail = RichTextValue(noticeDetail, 'text/html', 'text/html'),)\n #找關聯\n getSelfBrain = catalog(id=contentId)\n getSelfObject = getSelfBrain[0].getObject()\n try:\n for relatedItem in relatedItems:\n relatedItem_Object = relatedItem.getObject()\n if hasattr(getSelfObject, 'append'):\n getSelfObject.noticeRelation.append(RelationValue(intIds.getId(relatedItem_Object)))\n logger.info(pageUrl)\n else:\n getSelfObject.noticeRelation = [RelationValue(intIds.getId(relatedItem_Object))]\n #通知系統,建立反向關聯\n notify(ObjectModifiedEvent(getSelfObject))\n #設定subject\n getSelfObject.setSubject(list(relatedItem_Object.Subject()))\n except:\n logger.error(pageUrl)\n pass\n getSelfObject.exclude_from_nav = True\n getSelfObject.reindexObject()\n addCount += 1\n except:\n logger.error('error: %s' % pageUrl)\n pass\n\n api.portal.send_email(recipient=LOG_MAIL_RECIPIENT,\n sender=LOG_MAIL_SENDER,\n subject=\"Play公社回報, relationnotice 取得:%s\" % addCount,\n body=\"Done!\",)\n\n return logger.info('新增關聯公告完成,筆數: %s' % addCount)\n","sub_path":"twgov/content/browser/getRelationNotice.py","file_name":"getRelationNotice.py","file_ext":"py","file_size_in_byte":5328,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"465296018","text":"#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n\n# STL imports\nimport unittest\nimport json\nimport os\nimport logging\nimport datetime\n# Non STL imports\nimport telegram\nfrom telegram.ext import CommandHandler, MessageHandler\nfrom telegram.ext import Updater, Filters\n\nfrom ptbtest import ChatGenerator\nfrom ptbtest import MessageGenerator\nfrom ptbtest import CallbackQueryGenerator\nfrom ptbtest import Mockbot\nfrom ptbtest import UserGenerator\n\n\n# Local imports\nfrom dcubabot import *\nfrom models import *\nfrom install import install_commands\n\n\nclass TestDCUBABot(unittest.TestCase):\n\n @classmethod\n def setUpClass(self):\n # For use within the tests we nee some stuff. Starting with a Mockbot\n self.bot = Mockbot()\n self.bot.request = telegram.utils.request.Request()\n # Some generators for users and chats\n self.ug = UserGenerator()\n self.cg = ChatGenerator()\n # And a Messagegenerator,CallbackQueryGenerator and updater (for use with the bot.)\n self.mg = MessageGenerator(self.bot)\n self.cqg = CallbackQueryGenerator(self.bot)\n self.updater = Updater(bot=self.bot)\n init_db(\"test.sqlite3\")\n install_commands()\n add_all_handlers(self.updater.dispatcher)\n with db_session:\n for listable_type in Listable.__subclasses__():\n for i in range(6):\n listable_type(name=listable_type._discriminator_ + \" \" + str(i),\n url=\"https://url\" + str(i) + \".com\",\n validated=True)\n self.updater.start_polling()\n\n @classmethod\n def tearDownClass(self):\n self.updater.stop()\n os.remove(\"test.sqlite3\")\n\n @classmethod\n def sendCommand(self, command, chat_id=None):\n user = self.ug.get_user(first_name=\"Test\", last_name=\"The Bot\")\n if chat_id:\n chat = self.cg.get_chat(chat_id)\n else:\n chat = self.cg.get_chat(user=user)\n update = self.mg.get_message(user=user, chat=chat, text=command)\n self.bot.insertUpdate(update)\n return user, chat\n\n # TODO: Cleanup this\n def assert_bot_response(self, message_text, response_text, chat_id=None, random=False):\n if isinstance(response_text, str):\n response_text = [response_text]\n\n sent_messages = self.bot.sent_messages\n sent_messages_before = len(sent_messages)\n self.sendCommand(message_text, chat_id=chat_id)\n response_sent_messages = len(sent_messages) - sent_messages_before\n expected_sent_messages = 0 if not response_text else\\\n (1 if random else len(response_text))\n self.assertEqual(response_sent_messages, expected_sent_messages)\n\n for i in range(response_sent_messages):\n sent = sent_messages[sent_messages_before+i]\n self.assertEqual(sent['method'], \"sendMessage\")\n if not random:\n self.assertEqual(sent['text'], response_text[i])\n else:\n self.assertIn(sent['text'], response_text)\n\n def get_keyboard(self, message):\n return json.loads(message['reply_markup'])['inline_keyboard']\n\n def button_in_list(self, name, url, list_command):\n self.sendCommand(\"/\" + list_command)\n inline_keyboard = self.get_keyboard(self.bot.sent_messages[-1])\n for row in inline_keyboard:\n for button in row:\n if button[\"text\"] == name and button[\"url\"] == url:\n return True\n return False\n\n def test_help(self):\n with db_session:\n for c in Command.select():\n c.description = \"\"\n Command(name=\"comandoSinDescripcion1\")\n Command(name=\"comandoConDescripcion1\", description=\"Descripción 1\")\n Command(name=\"comandoSinDescripcion2\")\n Command(name=\"comandoConDescripcion2\", description=\"Descripción 2\")\n Command(name=\"comandoSinDescripcion3\")\n Command(name=\"comandoConDescripcion3\", description=\"Descripción 3\")\n\n self.assert_bot_response(\"/help\", (\"/comandoConDescripcion1 - Descripción 1\\n\"\n \"/comandoConDescripcion2 - Descripción 2\\n\"\n \"/comandoConDescripcion3 - Descripción 3\\n\"))\n\n def test_start(self):\n self.assert_bot_response(\n \"/start\", \"Hola, ¿qué tal? ¡Mandame /help si no sabés qué puedo hacer!\")\n\n def test_estasvivo(self):\n self.assert_bot_response(\"/estasvivo\", \"Sí, estoy vivo.\")\n\n def test_rozendioanalisis(self):\n self.assert_bot_response(\"/rozendioanalisis\", \"¡Sí, Rozen ya dio el final de análisis!\")\n\n # TODO: Rename\n def list_test(self, command, listable_type):\n self.assert_bot_response(command, \"Grupos: \")\n\n # Assertions on keyboard\n inline_keyboard = self.get_keyboard(self.bot.sent_messages[-1])\n self.assertEqual(len(inline_keyboard), 2) # Number of rows\n for i in range(2):\n row = inline_keyboard[i]\n self.assertEqual((len(row)), 3) # Number of columns\n for j in range(3):\n button = row[j]\n button_number = i * 3 + j\n self.assertEqual(\n button['text'], listable_type._discriminator_ + \" \" + str(button_number))\n self.assertEqual(button['url'], \"https://url\" + str(button_number) + \".com\")\n self.assertEqual(button['callback_data'], button['url'])\n\n def test_listar(self):\n self.list_test(\"/listar\", Obligatoria)\n\n def test_listaroptativa(self):\n self.list_test(\"/listaroptativa\", Optativa)\n\n def test_listarotro(self):\n self.list_test(\"/listarotro\", Otro)\n\n def suggestion_test(self, command, list_command, listable_type):\n name = \"Sugerido\"\n url = \"sugerido.com\"\n error_message = \"Hiciste algo mal, la idea es que pongas:\\n\" +\\\n command + \" <nombre>|<link>\"\n\n # Invalid command usages\n self.assert_bot_response(command, error_message)\n self.assert_bot_response(command + \" \" + name, error_message)\n self.assert_bot_response(command + \" \" + name + \"|\", error_message)\n self.assert_bot_response(command + \" |\" + url, error_message)\n self.assert_bot_response(command + \" |\", error_message)\n self.assert_bot_response(command + \" \" + name + \"|\" + url + \"|sobra\", error_message)\n\n # Make a group suggestion to accept\n self.assert_bot_response(command + \" \" + name + \"|\" + url,\n [listable_type.__name__ + \": \" + name + \"\\n\" + url,\n \"OK, se lo mando a Rozen.\"])\n\n # Assertions on keyboard\n inline_keyboard = self.get_keyboard(self.bot.sent_messages[-2])\n self.assertEqual(len(inline_keyboard), 1) # Number of rows\n row = inline_keyboard[0]\n self.assertEqual(len(row), 2) # Number of columns\n self.assertEqual(row[0][\"text\"], \"Aceptar\")\n self.assertEqual(row[1][\"text\"], \"Rechazar\")\n\n # The suggested group shouldn't be listed\n self.assertFalse(self.button_in_list(name, url, list_command))\n\n # Pressing the \"Aceptar\" button makes the group listable\n u = self.cqg.get_callback_query(message=self.mg.get_message().message,\n data=row[0][\"callback_data\"])\n self.bot.insertUpdate(u)\n self.assertTrue(self.button_in_list(name, url, list_command))\n with db_session:\n delete(l for l in Listable if l.name == name)\n\n # Make a group suggestion to reject\n self.sendCommand(command + \" \" + name + \"|\" + url)\n inline_keyboard = self.get_keyboard(self.bot.sent_messages[-2])\n row = inline_keyboard[0]\n\n # Pressing the \"Rechazar\" button doesn't make the group listable\n u = self.cqg.get_callback_query(message=self.mg.get_message().message,\n data=row[1][\"callback_data\"])\n self.bot.insertUpdate(u)\n self.assertFalse(self.button_in_list(name, url, list_command))\n\n # The database is clean of rejected suggestions\n with db_session:\n self.assertEqual(count(l for l in Listable if l.name == name), 0)\n\n def test_sugerirgrupo(self):\n self.suggestion_test(\"/sugerirgrupo\", \"listar\", Obligatoria)\n\n def test_sugeriroptativa(self):\n self.suggestion_test(\"/sugeriroptativa\", \"listaroptativa\", Optativa)\n\n def test_sugerirotro(self):\n self.suggestion_test(\"/sugerirotro\", \"listarotro\", Otro)\n\n def test_logger(self):\n with self.assertLogs(\"DCUBABOT\", level='INFO') as cm:\n user, _ = self.sendCommand(\"/listar\")\n first_message = 'INFO:DCUBABOT:'+str(user.id) + ': /listar'\n user, _ = self.sendCommand(\"/estasvivo\")\n second_message = 'INFO:DCUBABOT:'+str(user.id)+': /estasvivo'\n self.assertEqual(cm.output, [first_message, second_message])\n\n def test_cubawiki(self):\n cubawiki_url = \"https://www.cubawiki.com.ar/index.php/Segundo_Parcial_del_10/12/18\"\n positive_chat_id = -123456\n negative_chat_id_no_cubawiki = -654321\n negative_chat_id_no_entry = -123321\n with db_session:\n Obligatoria(name=\"Cubawiki\", url=\"test.com\",\n chat_id=positive_chat_id, cubawiki_url=cubawiki_url)\n Obligatoria(name=\"Cubawiki\", url=\"test.com\", chat_id=negative_chat_id_no_cubawiki)\n\n # Positive test case\n self.assert_bot_response(\"/cubawiki\", cubawiki_url, chat_id=positive_chat_id)\n\n # Negative test cases\n self.assert_bot_response(\"/cubawiki\", None, chat_id=negative_chat_id_no_cubawiki)\n self.assert_bot_response(\"/cubawiki\", None, chat_id=negative_chat_id_no_entry)\n\n with db_session:\n delete(o for o in Obligatoria if o.name == \"Cubawiki\")\n\n def test_felizdia(self):\n today = datetime.datetime(2019, 1, 1)\n self.assertEqual(felizdia_text(today), \"Feliz 1 de Enero\")\n today = datetime.datetime(2019, 2, 1)\n self.assertEqual(felizdia_text(today), \"Feliz 1 de Febrero\")\n today = datetime.datetime(2019, 3, 1)\n self.assertEqual(felizdia_text(today), \"Feliz 1 de Marzo\")\n today = datetime.datetime(2019, 4, 4)\n self.assertEqual(felizdia_text(today), \"Feliz 4 de Abril\")\n today = datetime.datetime(2019, 5, 21)\n self.assertEqual(felizdia_text(today), \"Feliz 21 de Mayo\")\n\n # TODO: Test randomness?\n def test_noitip(self):\n noitips = [\"me siento boludeadisimo\", \"Not this shit again\", \"noitip\"]\n with db_session:\n for phrase in noitips:\n Noitip(text=phrase)\n\n self.assert_bot_response(\"/noitip\", noitips, random=True)\n\n def test_asm(self):\n with db_session:\n AsmInstruction(mnemonic=\"AAD\",\n summary=\"ASCII Adjust AX Before Division\",\n url=\"https://www.felixcloutier.com/x86/aad\")\n AsmInstruction(mnemonic=\"ADD\",\n summary=\"Add\",\n url=\"https://www.felixcloutier.com/x86/add\")\n AsmInstruction(mnemonic=\"ADDPD\",\n summary=\"Add Packed Double-Precision Floating-Point Values\",\n url=\"https://www.felixcloutier.com/x86/addpd\")\n AsmInstruction(mnemonic=\"MOV\",\n summary=\"Move to/from Control Registers\",\n url=\"http://www.felixcloutier.com/x86/MOV-1.html\")\n AsmInstruction(mnemonic=\"MOV\",\n summary=\"Move to/from Debug Registers\",\n url=\"http://www.felixcloutier.com/x86/MOV-2.html\")\n AsmInstruction(mnemonic=\"INT n\",\n summary=\"Call to Interrupt Procedure\",\n url=\"http://www.felixcloutier.com/x86/INT%20n:INTO:INT%203.html\")\n\n not_found = \"No pude encontrar esa instrucción.\"\n possibles = not_found + \"\\nQuizás quisiste decir:\"\n add_info = (\"[ADD] Descripción: Add.\\n\"\n \"Más info: https://www.felixcloutier.com/x86/add\")\n addpd_info = (\"[ADDPD] Descripción: Add Packed Double-Precision Floating-Point Values.\\n\"\n \"Más info: https://www.felixcloutier.com/x86/addpd\")\n mov1_info = (\"[MOV] Descripción: Move to/from Control Registers.\\n\"\n \"Más info: http://www.felixcloutier.com/x86/MOV-1.html\")\n mov2_info = (\"[MOV] Descripción: Move to/from Debug Registers.\\n\"\n \"Más info: http://www.felixcloutier.com/x86/MOV-2.html\")\n intn_info = (\"[INT n] Descripción: Call to Interrupt Procedure.\\n\"\n \"Más info: http://www.felixcloutier.com/x86/INT%20n:INTO:INT%203.html\")\n\n self.assert_bot_response(\"/asm\", \"No me pasaste ninguna instrucción.\")\n self.assert_bot_response(\"/asm add\", add_info)\n self.assert_bot_response(\"/asm ADDPD\", addpd_info)\n self.assert_bot_response(\"/asm a\", not_found)\n self.assert_bot_response(\"/asm Adp\", possibles + \"\\n\" + add_info)\n self.assert_bot_response(\"/asm ADDPS\", possibles + \"\\n\" + addpd_info)\n self.assert_bot_response(\"/asm addP\", possibles + \"\\n\" + add_info + \"\\n\" + addpd_info)\n self.assert_bot_response(\"/asm MOV\", mov1_info + \"\\n\" + mov2_info)\n self.assert_bot_response(\"/asm INT n\", intn_info)\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"dcubabotTest.py","file_name":"dcubabotTest.py","file_ext":"py","file_size_in_byte":13642,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"393471630","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\nimport django.db.models.deletion\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('members', '0007_auto_20151012_1240'),\n ('inventory', '0001_initial'),\n ]\n\n operations = [\n migrations.AlterModelOptions(\n name='parkingpermit',\n options={'ordering': ['owner', 'pk', 'created']},\n ),\n migrations.AlterModelOptions(\n name='permitrenewal',\n options={'ordering': ['permit', 'when']},\n ),\n migrations.AddField(\n model_name='permitscan',\n name='who',\n field=models.ForeignKey(to='members.Member', help_text='The member who scanned the permit.', blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL),\n ),\n migrations.AlterField(\n model_name='permitrenewal',\n name='when',\n field=models.DateField(help_text='Date on which the parking permit was renewed.'),\n ),\n ]\n","sub_path":"inventory/migrations/0002_auto_20151223_1212.py","file_name":"0002_auto_20151223_1212.py","file_ext":"py","file_size_in_byte":1081,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"609947505","text":"import pandas as pd\nimport random as rd\n\n\ndef random_pick(raw_data):\n return raw_data[rd.randrange(0, len(raw_data), 1)]\n\n\ndef build_csv(PATH):\n # define dimension\n rawData = dict()\n # alternator\n mid = 0\n countries = [\"USA\", \"Germany\", \"China\", \"Japan\", \"Brazil\", \"Canada\", \"France\", \"Italy\", \"Austria\", \"India\",\n \"Russia\", \"Mexico\", \"Belgium\", \"Norway\", \"New Zealand\", \"Netherlands\", \"Chile\", \"Cuba\", \"Denmark\",\n \"Romania\", \"Korea\", \"Egypt\", \"Switzerland\", \"Sweden\", \"Thailand\", \"Turkey\", \"Indonesia\"]\n firms = [\"Volkswagen\", \"Ford\", \"Benz\", \"Daimler\", \"Mercedes\", \"BMW\", \"KTM\", \"Buick\", \"Acura\", \"Toyota\", \"Honda\",\n \"BYD\", \"GMC\", \"Hyundai\", \"Ferrari\", \"Jeep\", \"Lincoln\", \"Tesla\", \"Volvo\"]\n rawData = {\n \"material ID\": [],\n \"description\": [],\n \"level\": [],\n \"category\": [],\n \"category description\": [],\n \"hierarchy category\": [],\n \"provider\": [],\n \"country\": [],\n # \"length\": [],\n # \"height\": [],\n # \"bore\": [], # 缸径\n # \"bore type\": [],\n # \"bore type description\": [],\n # \"stroke\": [], # 冲程\n # \"stroke type\": [],\n # \"stroke type description\": [],\n \"diameter\": [],\n \"width\": [],\n \"size uom\": [],\n \"weight\": [],\n \"weight uom\": [],\n # \"power\": [],\n # \"voltage\": [],\n # \"current\": [], # 电流\n # \"pressure\": [],\n # \"flow\": [], # 流量\n # \"frequency\": [],\n # \"rotation speed\": [],\n \"price\": [],\n \"currency\": [],\n \"rank\": [],\n \"is leaf\": []\n }\n\n for key, value in rawData.items():\n for i in range(10000):\n if key == \"material ID\":\n mid += 1\n value.append(mid)\n elif key == \"description\":\n string = random_pick(firms) + \" \" + random_pick(countries) + \" R\" + str(rd.randrange(1000, 40000, 1))\n value.append(string)\n elif key == \"level\":\n value.append(3)\n elif key == \"category\":\n value.append(7)\n elif key == \"category description\":\n value.append(\"electrical ring\")\n elif key == \"hierarchy category\":\n value.append(2)\n elif key == \"provider\":\n desc = rawData[\"description\"][i]\n keys = desc.split(\" \")\n value.append(keys[0])\n elif key == \"country\":\n desc = rawData[\"description\"][i]\n keys = desc.split(\" \")\n value.append(keys[1])\n elif key == \"diameter\":\n value.append(round(rd.uniform(300, 500), 0))\n # elif key == \"length\":\n # value.append(round(rd.uniform(550, 600), 2))\n # elif key == \"height\":\n # value.append(round(rd.uniform(350, 450), 2))\n # elif key == \"bore\":\n # value.append(round(rd.uniform(70, 120), 0))\n # elif key == \"bore type\":\n # bore = rawData[\"bore\"][i]\n # if bore <= 95:\n # value.append(1)\n # else:\n # value.append(2)\n # elif key == \"bore type description\":\n # bore_type = rawData[\"bore type\"][i]\n # if bore_type == 1:\n # value.append(\"big\")\n # elif bore_type == 2:\n # value.append(\"small\")\n # elif key == \"stroke\":\n # value.append(round(rd.uniform(85, 140), 0))\n # elif key == \"stroke type\":\n # stroke = rawData[\"stroke\"][i]\n # if stroke <= 100:\n # value.append(1)\n # else:\n # value.append(2)\n # elif key == \"stroke type description\":\n # stroke_type = rawData[\"stroke type\"][i]\n # if stroke_type == 1:\n # value.append(\"short\")\n # elif stroke_type == 2:\n # value.append(\"long\")\n elif key == \"width\":\n value.append(round(rd.uniform(5, 7), 2))\n elif key == \"size uom\":\n value.append(\"mm\")\n elif key == \"weight\":\n value.append(round(rd.uniform(0.2, 1), 2))\n elif key == \"weight uom\":\n value.append(\"kg\")\n # elif key == \"power\":\n # value.append(random_pick([24, 36]))\n # elif key == \"voltage\":\n # value.append(12)\n # elif key == \"current\":\n # value.append(random_pick([2.5, 3]))\n # elif key == \"pressure\":\n # value.append(300)\n # elif key == \"flow\":\n # value.append(random_pick([45, 50, 55, 65, 70, 75, 80, 85]))\n # elif key == \"frequency\":\n # value.append(50)\n # elif key == \"rotation speed\":\n # value.append(6000)\n elif key == \"price\":\n value.append(round(rd.uniform(10, 25), 2))\n elif key == \"currency\":\n value.append(\"eur\")\n elif key == \"rank\":\n value.append(round(rd.uniform(6, 10), 0) / 2)\n elif key == \"is leaf\":\n value.append(True)\n\n for key, value in rawData.items():\n print(key, len(value))\n\n df = pd.DataFrame(rawData)\n df.to_csv(path_or_buf=PATH, sep=\",\", index=False)\n\n\nbuild_csv(\"../csvData/raw/electrical_ring.csv\")\n","sub_path":"tool/csvBuilder.py","file_name":"csvBuilder.py","file_ext":"py","file_size_in_byte":5570,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"60094487","text":"import sys\nimport pygame\nfrom bullet import Bullet\nfrom alien import Alien\nfrom time import sleep\n\ndef check_keydown_events(event, ai_settings, screen, ship, bullets):\n\tif event.key == pygame.K_RIGHT:\n\t\tship.moving_right = True\n\tif event.key == pygame.K_LEFT:\n\t\tship.moving_left = True \n\t\n\t#按下键盘产生子弹的object\n\tif event.key == pygame.K_SPACE:\n\t\tfire_bullet(ai_settings, screen, ship, bullets)\n\t\n\tif event.key == pygame.K_q:\n\t\tsys.exit()\n\n\t\t\ndef fire_bullet(ai_settings, screen, ship, bullets):\n\tif len(bullets) < ai_settings.bullets_allowed:\n\t\tnew_bullet = Bullet(ai_settings, screen, ship)\n\t\tbullets.add(new_bullet)\n\n\ndef check_keyup_events(event, ship):\n\tif event.key == pygame.K_RIGHT:\n\t\tship.moving_right = False\n\tif event.key == pygame.K_LEFT:\n\t\tship.moving_left = False\n\ndef check_events(ai_settings, screen, stats, play_button, ship, aliens, bullets):\n\t\n\tfor event in pygame.event.get():\n\t\tif event.type == pygame.QUIT:\n\t\t\tsys.exit()\n\n\t\t#按下就连续移动\n\t\telif event.type == pygame.KEYDOWN:\n\t\t\tcheck_keydown_events(event, ai_settings, screen, ship, bullets)\n\t\t\n\t\telif event.type == pygame.KEYUP:\n\t\t\tcheck_keyup_events(event, ship)\n\t\t\n\t\telif event.type == pygame.MOUSEBUTTONDOWN:\n\t\t\tmouse_x,mouse_y = pygame.mouse.get_pos()\n\t\t\tcheck_play_button(ai_settings, screen, stats, play_button, ship, aliens,\n\t\t\t\t\t\t\t\tbullets, mouse_x, mouse_y)\n\t\t\t\ndef check_play_button(ai_settings, screen, stats, play_button, ship, aliens,\n\t\t\t\t\t\tbullets, mouse_x, mouse_y):\n\t\n\tbutton_clicked = play_button.rect.collidepoint(mouse_x, mouse_y)\n\t\n\tif button_clicked and not stats.game_active:\n\t\tstats.game_active = True\n\t\t\n\t\t#初始化难度\n\t\tai_settings.initialize_dynamic_settings()\n\t\t\n\t\t#让鼠标消失\n\t\tpygame.mouse.set_visible(False)\n\t\t\n\t\tstats.reset_stats()\n\t\t\n\t\taliens.empty()\n\t\tbullets.empty()\n\t\t\n\t\tcreate_fleet(ai_settings, screen, ship, aliens)\n\t\tship.center_ship()\n\t\t\t\n\t\t\t\ndef update_screen(ai_settings, screen, stats, sb, ship, aliens, bullets, play_button):\n\tscreen.fill(ai_settings.bg_color)\n\t\n\tfor bullet in bullets.sprites():\n\t\tbullet.draw_bullet()\n\t#bullets.draw(screen)\n\t\n\tship.blitme()\n\t#alien.blitme()\n\t\n\t#for alien in aliens.sprites():\n\t\t#alien.blitme()\n\taliens.draw(screen)\n\t\n\tsb.show_score()\n\t\n\tif not stats.game_active:\n\t\tplay_button.draw_button()\n\t\n\tpygame.display.flip()\n\t\ndef update_bullets(ai_settings, screen, stats, sb, ship, aliens, bullets):\n\tbullets.update()\n\t\t\n\tfor bullet in bullets.copy():\n\t\tif bullet.rect.bottom <= 0:\n\t\t\tbullets.remove(bullet)\n\t\t\t\n\tcheck_bullet_alien_collisions(ai_settings, screen, stats, sb, ship, aliens, bullets)\n\t\n\t\ndef check_bullet_alien_collisions(ai_settings, screen, stats, sb, ship, aliens, bullets):\n\t#判断2个Groups是否有交集,返回一个字典\n\t# 最后2个 bool参数表示是否要destory obj\n\t## Groups1, Groups2, destory for G1 , destory for G2\t\t\n\tcollisions = pygame.sprite.groupcollide(aliens, bullets, True, True)\n\t\t\n\tif collisions:\n\t\tfor aliens in collisions.values():\n\t\t\tstats.score += ai_settings.alien_points * len(aliens)\n\t\t\tsb.prep_score()\n\t\n\tif len(aliens) == 0:\n\t\tbullets.empty()\n\t\tai_settings.increase_speed()\n\t\tcreate_fleet(ai_settings, screen, ship, aliens)\n\n\t\n\t\t\ndef get_number_aliens_x(ai_settings, alien_width):\n\t#x轴预留后的长度\n\tavailable_space_x = ai_settings.screen_width - (2* alien_width)\n\t\n\t#计算能存放多少个alien\n\tnumber_aliens_x = int( available_space_x/(2*alien_width))\n\t\n\treturn number_aliens_x\n\ndef get_number_aliens_y(ai_settings, ship_height, alien_height):\n\t#计算y轴的空闲高度\n\tavailable_space_y = ai_settings.screen_height - ship_height - 3*alien_height;\n\t\n\t#计算能放几行\n\tnumber_rows = int( available_space_y / (2* alien_height))\n\treturn number_rows\n\t\n\t\t\n#创建单个敌人\ndef create_alien(ai_settings, screen, aliens, alien_number, row_number):\n\talien = Alien(ai_settings, screen)\n\talien_width = alien.rect.width\n\t\n\talien.x = alien_width + 2* alien_width * alien_number\n\n\talien.rect.x = alien.x\n\talien.rect.y = alien.rect.height + 2*alien.rect.height* row_number\n\t\n\t#alien.index = str(alien_number) + str(row_number)\n\t\n\t#print(\"%s \" %(alien.index), end = \"*\")\n\taliens.add(alien)\n\t\ndef create_fleet(ai_settings, screen, ship, aliens):\n\talien = Alien(ai_settings, screen)\n\t\n\tnumber_aliens_x = get_number_aliens_x(ai_settings, alien.rect.width)\n\tnumber_rows = get_number_aliens_y(ai_settings, ship.rect.height, alien.rect.height)\n\t\n\tfor row_number in range(number_rows):\n\t\tfor alien_number in range(number_aliens_x):\n\t\t\tcreate_alien(ai_settings, screen, aliens, alien_number, row_number)\n\t\t\ndef update_aliens(ai_settings, stats, screen, ship, aliens, bullets):\n\taliens.update() #更新x轴坐标\n\tcheck_fleet_edges(ai_settings, aliens)\n\t\n\t#检查aliens和ship触碰\n\tif pygame.sprite.spritecollideany(ship,aliens):\n\t\t#print(\"Ship hit!!!\")\n\t\tship_hit(ai_settings, stats, screen, ship, aliens, bullets)\n\t\n\t#检查aliens和屏幕底变的触碰\n\tcheck_aliens_bottom(ai_settings, stats, screen, ship, aliens, bullets)\n\n#最终减命的函数\ndef ship_hit(ai_settings, stats, screen, ship, aliens, bullets):\n\tif stats.ships_left > 1:\n\t\tstats.ships_left -= 1\n\t\t\n\t\taliens.empty()\n\t\tbullets.empty()\n\t\t\n\t\tcreate_fleet(ai_settings, screen, ship, aliens)\n\t\tship.center_ship()\n\t\t\n\t\tsleep(0.5)\n\telse:\n\t\tstats.game_active = False\n\t\tpygame.mouse.set_visible(True)\n\ndef check_aliens_bottom(ai_settings, stats, screen, ship, aliens, bullets):\n\tscreen_rect = screen.get_rect()\n\t\n\tfor alien in aliens.sprites():\n\t\tif alien.rect.bottom >= screen_rect.bottom:\n\t\t\tship_hit(ai_settings, stats, screen, ship, aliens, bullets)\n\t\t\tbreak\t\n\ndef check_fleet_edges(ai_settings, aliens):\n\tfor alien in aliens.sprites():\n\t\tif alien.check_edges():\n\t\t\tchange_fleet_direction(ai_settings, aliens)\n\t\t\tbreak\n\n#如果碰到了边缘,更新方向,并且Y轴向下移动\t\t\t\ndef change_fleet_direction(ai_settings, aliens):\n\tai_settings.fleet_direction *= -1\n\t#Y轴向下移动\n\tfor alien in aliens.sprites():\n\t\talien.rect.y += ai_settings.alien_drop_speed\n\t\t\n\n","sub_path":"alien/day11/game_functions.py","file_name":"game_functions.py","file_ext":"py","file_size_in_byte":5971,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"297392120","text":"# export PATH=/home/yule/anaconda3/bin:$PATH\n\nfrom scipy.spatial.distance import pdist,squareform\nfrom scipy import exp\nfrom scipy.linalg import eigh\nimport numpy as np\nimport matplotlib.pyplot as plt \n\ndef rbf_kernel_pac(X,gamma,n_components):\n\t#X:n*n features\n\t#gamma:公式中的系数伽马\n\n\t#1.计算核相似矩阵(输入是原始空间)\n\tsq_dists = pdist(X,'sqeuclidean') #计算两辆之间的欧式距离:|x-y|^2\n\tmat_sq_dists = squareform(sq_dists) #将M×N距离矩阵转换到方阵中\n\tK = exp(- gamma * mat_sq_dists) #计算对称核矩阵K\n\n\t#2.把新特征空间的中心放在零点\n\tN = K.shape[0]\n\tone_n = np.ones((N,N)) / N #所有值为1/n\n\tK = K - one_n.dot(K) - K.dot(one_n) + one_n.dot(K).dot(one_n) #聚集核矩阵得到新核矩阵\n\n\t#3.得到特征值和特征向量\n\teigvals,eigvecs = eigh(K) #n*n\n\t#X_pc = np.column_stack((eigvecs[:,-i] for i in range(1,n_components + 1))) #选择前k个\n\talphas = np.column_stack((eigvecs[:,-i] for i in range(1,n_components+1))) #和之前的X_pc一样\n\tlambdas = [eigvals[-i] for i in range(1,n_components+1)] #特征值?\n\n\treturn alphas,lambdas #n*k\n\n\ndef project_x(x_new,X,gamma,alphas,lambdas):\n\tpair_dist = np.array([np.sum((x_new-row)**2) for row in X])\n\tk = np.exp(-gamma * pair_dist)\n\treturn k.dot(alphas / lambdas) #归一化处理\n\n#实例:分离半月形数据\nfrom sklearn.datasets import make_moons\nX,y = make_moons(n_samples=100,random_state=123)\nalphas,lambdas = rbf_kernel_pac(X,gamma=15,n_components=1)\nx_new=X[25]\nx_proj = alphas[25]\n\nx_reproj = project_x(x_new,X,gamma=15,alphas=alphas,lambdas=lambdas)\n\n#将第一主成分上的映射进行可视化\nplt.scatter(alphas[y==0,0],np.zeros((50)),color='red',marker='^',alpha=0.5)\nplt.scatter(alphas[y==1,0],np.zeros((50)),color='blue',marker='o',alpha=0.5)\nplt.scatter(x_proj,0,color='black',label='original projection of point X[25]',marker='^',s=100)\nplt.scatter(x_reproj,0,color='green',label='remapped point X[25]',marker='x',s=500)\nplt.legend(scatterpoints=1)\nplt.show()\n","sub_path":"Machine Learning - Mofan/Python机器学习-代码/5.7使用核PCA映射新的数据点.py","file_name":"5.7使用核PCA映射新的数据点.py","file_ext":"py","file_size_in_byte":2024,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"268773452","text":"import pandas as pd\nimport pathlib\n\n\noriginal_datasets = pathlib.Path(\"original_datasets\")\n\npath_netherlands = original_datasets / \"netherlands\"\n\nraw_input = path_netherlands / \"netherlands_raw.csv.gz\"\noutput_csv = path_netherlands / \"netherlands.csv.gz\"\n\ndata = pd.read_csv(raw_input, sep=\";\")\n\nprint(f\"read input data: {data.shape}\")\nprint(f\"Coluns: {data.columns}\")\n\n# drop the samp column, that just indicated whether it was training or test set\ndata = data.drop('samp', axis=1)\n\n# drop the dichtheid column, as it was not defined anywhere.\ndata = data.drop('dichtheid', axis=1)\n\n# rename and order of columns\ncolmap = [\n # original # new columns\n (\"sekse\", \"sex=female\"),\n (\"cgebland\", \"country_of_birth\"),\n (\"lnvgalguz\", \"log_#_of_previous_penal_cases\"),\n (\"leeftijd\", \"age_in_years\"),\n (\"lftinsz1inclvtt\", \"age_at_first_penal_case\"),\n (\"delcuziv\", \"offence_type\"),\n (\"dum1120\", \"11-20_previous_case\"),\n (\"dum21plus\", \">20_previous_case\"),\n (\"lft2\", \"age_squared\"),\n (\"rec4\", \"recidivism_in_4y\"),\n]\n\n# do the renaming of the columns\nprint(\"renaming columns:\")\nfor c in colmap:\n print(f\" - {c[0]:15} => {c[1]}\")\ndata.rename(columns={ x[0] : x[1] for x in colmap}, inplace = True)\n\n# reorder the columns\nnew_columns = [x[1] for x in colmap]\nprint(f'Changing column order: {new_columns}')\ndata = data.reindex(columns=new_columns)\n\n# save the dataset\nprint(f\"saving to '{output_csv}'\")\ndata.to_csv(output_csv, sep=\";\", index=False)\n\nprint(\"dataset cleaned\")","sub_path":"datasets/scripts/clean_netherlands.py","file_name":"clean_netherlands.py","file_ext":"py","file_size_in_byte":1624,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"523525425","text":"#Попросить пользователя ввести возраст при помощи input и положить результат в переменную\n#Написать функцию, которая по возрасту определит, чем должен заниматься пользователь: учиться в детском саду, школе, ВУЗе или работать\n#Вызвать функцию, передав ей возраст пользователя и положить результат работы функции в преременную\n#Вывести содержимо�� переменной на экран\n\n\nuser_age = int(input('Give me your age: '))\n\n\ndef what_user_do(age):\n if age < 0:\n return 'Give me positive number, please!'\n elif age < 8:\n return 'You are at kindergarten!'\n elif age < 18:\n return 'You are at school!'\n elif age < 25:\n return 'You are at university!'\n else:\n return 'You are working ;('\n\n\nprint(what_user_do(user_age))","sub_path":"age.py","file_name":"age.py","file_ext":"py","file_size_in_byte":1057,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"490237681","text":"import argparse\nimport csv\nimport json\nfrom datetime import datetime, timedelta, timezone\n\nimport requests\nfrom enums import OneUnit\n\nimport config\n\nJSONRPC_ENDPOINT = \"https://rpc.s0.t.hmny.io\"\n\n\ndef main(main_args):\n write_csv(main_args.address, main_args.file, main_args.start_page, main_args.end_page)\n\n\ndef write_csv(address, csv_file, start_page, end_page):\n fieldnames = (\"Date\", \"Action\", \"Account\", \"Symbol\", \"Volume\", \"Total\", \"Currency\", \"Memo\")\n writer = csv.DictWriter(csv_file, fieldnames=fieldnames)\n writer.writeheader()\n for page_index in range(start_page, end_page + 1):\n rows = get_transaction_history(address, page_index=page_index)\n print(page_index)\n print(rows)\n writer.writerows(rows)\n page_index += 1\n if not rows:\n break\n csv_file.close()\n print(\"Generated bitcoin.tax file {}\".format(csv_file.name))\n\ndef get_transaction_history(address, page_index=0):\n params = [\n {\n \"address\": address,\n \"pageIndex\": page_index,\n \"fullTx\": True,\n \"txType\": \"ALL\",\n \"order\": \"ASC\"\n }\n ]\n\n payload = {\n \"method\": \"hmyv2_getStakingTransactionsHistory\",\n \"params\": params,\n \"jsonrpc\": \"2.0\",\n \"id\": 1,\n }\n response = requests.post(JSONRPC_ENDPOINT, json=payload).json()\n transactions = response['result']['staking_transactions']\n reward_transactions = [transaction for transaction in transactions if transaction['type'] == 'CollectRewards']\n action = \"MINING\"\n account = address\n symbol = \"ONE\"\n currency = \"USD\"\n rows = []\n for transaction in reward_transactions:\n dt_object = datetime.fromtimestamp(transaction['timestamp'], tz=timezone.utc)\n date = dt_object.strftime('%Y-%m-%d %H:%M:%S %z')\n hash = transaction['hash']\n memo = hash\n receipt_response = get_transaction_receipt(hash)\n volume = int(receipt_response['result']['logs'][0]['data'], 16) * OneUnit.Wei\n total = ''\n row = dict(Date=date, Action=action, Account=account, Symbol=symbol, Volume=volume, Total=total,\n Currency=currency, Memo=memo)\n rows.append(row)\n return rows\n\n\ndef get_transaction_receipt(hash):\n params = [hash]\n\n # Example echo method\n payload = {\n \"method\": \"hmyv2_getTransactionReceipt\",\n \"params\": params,\n \"jsonrpc\": \"2.0\",\n \"id\": 1,\n }\n response = requests.post(JSONRPC_ENDPOINT, json=payload).json()\n return response\n\n\ndef usage():\n return \"\"\"python taxes.py -a <validator_address> -f <output_filename>\"\"\"\n\n\ndef get_command_line_options():\n parser = argparse.ArgumentParser(description=\"Query staking taxes and output them to a Bitcoin.tax \"\n \"CSV file.\\n\\n\" + usage())\n parser.add_argument(\n '-a', '--address', help='address', type=str\n )\n parser.add_argument('-f', '--file', help='csv outputfile', type=argparse.FileType(mode='w'), default='staking_taxes.csv')\n parser.add_argument('-s', '--start_page', help='starting page index', type=int, default=0)\n parser.add_argument('-e', '--end_page', help='end page index', type=int, default=9999999)\n return parser.parse_args()\n\n\nif __name__ == '__main__':\n main_args = get_command_line_options()\n main(main_args)\n","sub_path":"taxes.py","file_name":"taxes.py","file_ext":"py","file_size_in_byte":3380,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"374176401","text":"import os\nimport re\nfrom glob import glob\n\nfrom lark import Lark, Tree\n\nparser = {}\nfor name in glob(os.path.join(os.path.dirname(__file__), \"../grammar\", \"*.g\")):\n with open(name) as f:\n ver = tuple(\n int(n)\n for n in re.findall(r\"\\d+\", str(os.path.basename(name).split(\".g\")[0]))\n )\n parser[ver] = Lark(f.read())\n\n\nclass ParserError(Exception):\n pass\n\n\nclass LarkParser:\n def __init__(self, version=None):\n if version is None:\n self.version = sorted(parser.keys())[-1]\n self.lark = parser[self.version]\n elif version in parser:\n self.lark = parser[version]\n self.version = version\n else:\n raise ParserError(f\"Unknown parser grammar version: {version}\")\n self.tree = None\n self.filter = None\n\n def parse(self, filter_):\n try:\n self.tree = self.lark.parse(filter_)\n self.filter = filter_\n return self.tree\n except Exception as e:\n raise ParserError(e)\n\n def __repr__(self):\n if isinstance(self.tree, Tree):\n return self.tree.pretty()\n else:\n return repr(self.lark)\n","sub_path":"optimade/filterparser/lark_parser.py","file_name":"lark_parser.py","file_ext":"py","file_size_in_byte":1207,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"382714403","text":"from collections import deque\nfrom collections import defaultdict\nimport itertools as it\ninp = 939601\nsinp = str(inp)\noffset = 10\n\nelf1 = 0\nelf2 = 1\n\nboard = deque([3, 7])\nit = 0\ngit = 0\nwhile(len(board) < inp + offset): #solves part1\n total = board[elf1] + board[elf2]\n board.extend(list(map(int,str(total))))\n \n elf1 = (1 + board[elf1] + elf1)% len(board)\n elf2 = (1 + board[elf2] + elf2) % len(board)\nprint(list(board)[inp:inp+offset])\n\n","sub_path":"Advent2018/Day/Day_14.py","file_name":"Day_14.py","file_ext":"py","file_size_in_byte":455,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"565481427","text":"n = int(input('Quantos termos você quer mostrar? '))\nt1 = 0\nt2 = 1\nif n == 1:\n print(f'{t1} ->',end=' ')\nif n >=2:\n print(f'{t1} -> {t2}', end=' -> ')\n cont = 3\n while cont <= n:\n t3 = t1 + t2\n print(f'{t3}', end=' -> ')\n t1 = t2\n t2 = t3\n cont += 1\nprint('Fim')","sub_path":"Lista 1 Banin/ex11.py","file_name":"ex11.py","file_ext":"py","file_size_in_byte":310,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"526059094","text":"def user_algorithm(playing_field):\n distance = {}\n snake_head = {}\n apple = {}\n stenka = []\n direction = \"\"\n for y in range(len(playing_field)):\n for x in range(len(playing_field[0])):\n if playing_field[y][x] == 3:\n snake_head = {\"x\": x, \"y\": y}\n elif playing_field[y][x] == 2:\n apple = {\"x\": x, \"y\": y}\n elif not playing_field[y][x] == 0:\n stenka.append({\"x\": x, \"y\": y})\n\n distance = {\"x\": snake_head[\"x\"] - apple[\"x\"],\n \"y\": snake_head[\"y\"] - apple[\"y\"]}\n\n not_direction = []\n\n for i in stenka:\n if snake_head[\"x\"] + 1 == i[\"x\"] and snake_head[\"y\"] == i[\"y\"]:\n not_direction.append(\"right\")\n if snake_head[\"x\"] - 1 == i[\"x\"] and snake_head[\"y\"] == i[\"y\"]:\n not_direction.append(\"left\")\n if snake_head[\"x\"] == i[\"x\"] and snake_head[\"y\"] - 1 == i[\"y\"]:\n not_direction.append(\"up\")\n if snake_head[\"x\"] == i[\"x\"] and snake_head[\"y\"] + 1 == i[\"y\"]:\n not_direction.append(\"down\")\n\n if abs(distance[\"x\"]) > abs(distance[\"y\"]):\n if distance[\"x\"] < 0:\n direction = \"right\"\n else:\n direction = \"left\"\n else:\n if distance[\"y\"] < 0:\n direction = \"down\"\n else:\n direction = \"up\"\n\n list_direction = [\"right\", \"left\", \"down\", \"up\"]\n if direction in not_direction:\n direction = \"\"\n for el in list_direction:\n if not (el in not_direction):\n direction = el\n break\n\n if not direction:\n direction = \"up\"\n\n return direction\n","sub_path":"app/rooms/test/user_2.py","file_name":"user_2.py","file_ext":"py","file_size_in_byte":1657,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"10292463","text":"\"\"\"\nLoad Router API \"status/fw_info\" into settings.\n\"\"\"\nimport json\nimport logging\nimport os.path\nimport sys\n\nfrom cp_lib.load_settings_json import DEF_GLOBAL_DIRECTORY\nfrom cp_lib.cs_client import CradlepointClient\nfrom cp_lib.app_base import CradlepointRouterOffline\n\nSECTION_FW_INFO = \"fw_info\"\n\n\ndef load_firmware_info(sets, client, file_name=None):\n \"\"\"\n Load Router API \"status/fw_info\" into settings.\n\n $ cat status/fw_info\n 'fw_info': {\n 'major_version': 6,\n 'fw_update_available': False,\n 'upgrade_patch_version': 0,\n 'upgrade_minor_version': 0,\n 'build_version': '0310fce',\n 'build_date': 'WedJan1300: 23: 15MST2016',\n 'minor_version': 1,\n 'upgrade_major_version': 0,\n 'manufacturing_upgrade': False,\n 'build_type': 'FIELD[build]',\n 'custom_defaults': False,\n 'patch_version': 0\n },\n\n You have 3 ways to do this. ( The code does not validate the contents )\n\n 1) if there is a [fw_info] section in ./config/settings.ini, then this\n is used and no access to the router is attempted.\n\n 2) else, if there is a file named ./config/fw_info.json (all lower case),\n then this is opened and loaded, merged into settings.\n\n 3) else, if section [router_api] is correct, then REQUESTS is used\n to fetch the actual value, which is merged into settings, accessed\n as self.settings[\"fw_info\"].\n\n :param dict sets: the settings existing before the call\n :param CradlepointClient client: either local or remote cs_client handler\n :param str file_name: for testing, use name OTHER than default, method #2\n :return dict: the merged settings\n \"\"\"\n from cp_lib.split_version import sets_version_to_str\n\n if SECTION_FW_INFO in sets:\n logging.debug(\"method #1 - is already in ./config/settings.ini\")\n sets[SECTION_FW_INFO][\"version\"] = sets_version_to_str(sets,\n SECTION_FW_INFO)\n return sets\n\n # check for a file such as \"./config/fw_info.json\"\n if file_name is None:\n file_name = os.path.join(DEF_GLOBAL_DIRECTORY, \"fw_info.json\")\n\n if os.path.exists(file_name):\n # method #2 - the file exists. Do this indirectly to avoid some\n # Win/Linux relative path issues\n logging.debug(\"method #2 - load file {}\".format(file_name))\n _file_han = open(file_name, \"r\")\n sets[SECTION_FW_INFO] = json.load(_file_han)\n _file_han.close()\n sets[SECTION_FW_INFO][\"version\"] = sets_version_to_str(sets,\n SECTION_FW_INFO)\n return sets\n\n # is still here, we'll do it the 'hard way' via Router API\n logging.debug(\"method #3 - use CS Client\")\n assert isinstance(client, CradlepointClient)\n\n save_state = client.show_rsp\n client.show_rsp = False\n result = client.get(\"status/fw_info\")\n client.show_rsp = save_state\n\n if result is None:\n raise CradlepointRouterOffline(\n \"Aborting; Router({}) is not accessible\".format(client.router_ip))\n\n if isinstance(result, str):\n result = json.loads(result)\n\n sets[SECTION_FW_INFO] = result\n sets[SECTION_FW_INFO][\"version\"] = sets_version_to_str(sets,\n SECTION_FW_INFO)\n return sets\n","sub_path":"modbus_simple_bridge/cp_lib/load_firmware_info.py","file_name":"load_firmware_info.py","file_ext":"py","file_size_in_byte":3379,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"383885766","text":"import argparse\n\nimport torch\n\n\ndef get_files():\n parser = argparse.ArgumentParser()\n parser.add_argument('--cgm', default='data/GlucoseValues.csv', help='location of cgm data file')\n parser.add_argument('--meals', default='data/Meals.csv', help='location of meals data file')\n args = parser.parse_args()\n return args.cgm, args.meals\n\n\ndef collate(samples):\n batched = {\n 'cgm': torch.stack([s['cgm'] for s in samples]),\n 'meals_cont': [s['meals_cont'] for s in samples],\n 'meals_cat': [s['meals_cat'] for s in samples],\n 'target': torch.stack([s['target'] for s in samples])\n }\n return batched\n","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":647,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"229078417","text":"genres = [\"classic\", \"pop\", \"classic\", \"classic\", \"pop\"]\nplays = [500, 600, 150, 800, 2500]\n\n\ndef get_melon_best_album(genre_array, play_array):\n dict_genre_plays = dict()\n length_genres = len(genre_array)\n genre_sum = 0\n result = []\n\n for dict_index in range(length_genres):\n if genres[dict_index] not in dict_genre_plays:\n dict_genre_plays[genres[dict_index]] = play_array[dict_index]\n else:\n dict_genre_plays[genres[dict_index]] += play_array[dict_index]\n\n sorted_dict_genre_plays = sorted(dict_genre_plays, reverse=True)\n\n dict_index_plays = dict()\n for a_genre in sorted_dict_genre_plays:\n for genre_index in range(length_genres):\n if genre_array[genre_index] == a_genre:\n dict_index_plays[genre_index] = play_array[genre_index]\n\n sorted_dict_index_plays = sorted(dict_index_plays.items(), key=lambda x: x[1], reverse=True)\n dict_index_plays = dict()\n\n for a_tuple in sorted_dict_index_plays:\n result.append(a_tuple[0])\n\n return result\n\n\nprint(get_melon_best_album(genres, plays)) # 결과로 [4, 1, 3, 0] 가 와야 합니다!\n","sub_path":"week_3/homework/03_01_get_melon_best_album.py","file_name":"03_01_get_melon_best_album.py","file_ext":"py","file_size_in_byte":1162,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"82642638","text":"# Copyright 2015 Metaswitch Networks\n#\n# Licensed under the Apache License, Version 2.0 (the 'License');\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an 'AS IS' BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport os\nimport sys\nimport json\nimport unittest\nfrom mock import patch, Mock, call\nfrom netaddr import IPAddress, IPNetwork\nfrom subprocess import CalledProcessError\nfrom pycalico.datastore_datatypes import IPPool\nimport pycalico.netns\nimport calico_rkt\n\nCONTAINER_ID = 'ff3afbd1-17ad-499d-b514-72438c009e81'\nNETNS_ROOT = '/var/lib/rkt/pods/run'\nORCHESTRATOR_ID = \"rkt\"\n\nENV = {\n 'CNI_IFNAME': 'eth0',\n 'CNI_ARGS': '',\n 'CNI_COMMAND': 'ADD',\n 'CNI_PATH': '.../.../...',\n 'CNI_NETNS': 'netns',\n 'CNI_CONTAINERID': CONTAINER_ID,\n}\nCONF = {\n \"name\": \"test\",\n \"type\": \"calico\",\n \"ipam\": {\n \"type\": \"host-local\",\n \"subnet\": \"10.22.0.0/16\",\n \"routes\": [{\"dst\": \"0.0.0.0/0\"}],\n \"range-start\": \"\",\n \"range-end\": \"\",\n },\n}\nARGS = {\n 'command': ENV['CNI_COMMAND'],\n 'container_id': ENV['CNI_CONTAINERID'],\n 'interface': ENV['CNI_IFNAME'],\n 'netns': ENV['CNI_NETNS'],\n 'name': CONF['name'],\n 'subnet': CONF['ipam']['subnet'],\n}\n\n\nclass RktPluginTest(unittest.TestCase):\n\n @patch('calico_rkt.create',\n autospec=True)\n def test_main_ADD(self, m_create):\n ARGS['command'] = 'ADD'\n calico_rkt.calico_rkt(ARGS)\n\n m_create.assert_called_once_with(ARGS)\n\n @patch('calico_rkt.delete',\n autospec=True)\n def test_main_DEL(self, m_delete):\n ARGS['command'] = 'DEL'\n calico_rkt.calico_rkt(ARGS)\n\n m_delete.assert_called_once_with(ARGS)\n\n @patch('calico_rkt.datastore_client',\n autospec=True)\n @patch('calico_rkt._create_calico_endpoint',\n autospec=True)\n @patch('calico_rkt._set_profile_on_endpoint',\n autospec=True)\n def test_create(self, m_set_profile, m_create_ep, m_client):\n\n ip_ = '1.2.3.4/32'\n path_ = '%s/%s/%s' % (NETNS_ROOT, ARGS['container_id'], ARGS['netns'])\n\n mock_ep = Mock()\n mock_ep.ipv4_nets = set()\n mock_ep.ipv4_nets.add(ip_)\n m_create_ep.return_value = mock_ep\n\n calico_rkt.create(ARGS)\n\n m_create_ep.assert_called_once_with(container_id=ARGS['container_id'],\n netns_path=path_,\n interface=ARGS['interface'],\n subnet=ARGS['subnet'])\n m_set_profile.assert_called_once_with(endpoint=mock_ep,\n profile_name=\"test\")\n\n @patch('calico_rkt.HOSTNAME',\n autospec=True)\n @patch('calico_rkt.datastore_client',\n autospec=True)\n @patch('calico_rkt._container_add', return_value=('ep', 'ip'),\n autospec=True)\n def test_create_calico_endpoint(self, m_con_add, m_client, m_host):\n m_client.get_endpoint.return_value = None\n m_client.get_endpoint.side_effect = KeyError()\n\n id_, path_ = 'testcontainer', 'path/to/ns'\n\n calico_rkt._create_calico_endpoint(container_id=id_,\n netns_path=path_,\n interface=ARGS['interface'],\n subnet=ARGS['subnet'])\n\n m_client.get_endpoint.assert_called_once_with(hostname=m_host,\n orchestrator_id=ORCHESTRATOR_ID,\n workload_id=id_)\n m_con_add.assert_called_once_with(hostname=m_host,\n orchestrator_id=ORCHESTRATOR_ID,\n container_id=id_,\n netns_path=path_,\n interface=ARGS['interface'],\n subnet=ARGS['subnet'])\n\n @patch(\"sys.exit\",\n autospec=True)\n @patch('calico_rkt.HOSTNAME',\n autospec=True)\n @patch('calico_rkt.datastore_client',\n autospec=True)\n @patch('calico_rkt._container_add', return_value=('ep', 'ip'),\n autospec=True)\n def test_create_calico_endpoint_fail(self, m_con_add, m_client, m_host, m_sys_exit):\n m_client.get_endpoint.return_value = \"Endpoint Exists\"\n\n id_, path_ = 'testcontainer', 'path/to/ns'\n\n calico_rkt._create_calico_endpoint(container_id=id_,\n netns_path=path_,\n interface=ARGS['interface'],\n subnet=ARGS['subnet'])\n\n m_client.get_endpoint.assert_called_once_with(hostname=m_host,\n orchestrator_id=ORCHESTRATOR_ID,\n workload_id=id_)\n m_sys_exit.assert_called_once_with(1)\n\n @patch('calico_rkt.HOSTNAME',\n autospec=True)\n @patch('calico_rkt.datastore_client',\n autospec=True)\n @patch('calico_rkt._assign_to_pool', return_value=(IPPool('1.2.0.0/16'), IPAddress('1.2.3.4')),\n autospec=True)\n def test_container_add(self, m_assign_pool, m_client, m_host):\n m_ep = Mock()\n m_client.create_endpoint.return_value = m_ep\n m_ep.provision_veth.return_value = 'macaddress'\n\n id_, path_ = 'testcontainer', 'path/to/ns'\n\n calico_rkt._container_add(hostname=m_host,\n orchestrator_id=ORCHESTRATOR_ID,\n container_id=id_,\n netns_path=path_,\n interface=ARGS['interface'],\n subnet=ARGS['subnet'])\n\n m_assign_pool.assert_called_once_with(ARGS['subnet'])\n m_client.create_endpoint.assert_called_once_with(\n m_host, ORCHESTRATOR_ID, id_, [IPAddress('1.2.3.4')])\n m_ep.provision_veth.assert_called_once()\n m_client.set_endpoint.assert_called_once_with(m_ep)\n\n @patch('calico_rkt.HOSTNAME',\n autospec=True)\n @patch('calico_rkt.datastore_client',\n autospec=True)\n @patch('pycalico.netns',\n autospec=True)\n def test_container_remove(self, m_netns, m_client, m_host):\n m_ep = Mock()\n m_ep.ipv4_nets = set()\n m_ep.ipv4_nets.add(IPNetwork('1.2.3.4/32'))\n m_ep.ipv6_nets = set()\n m_ep.name = 'endpoint_test'\n\n m_client.get_endpoint.return_value = m_ep\n id_ = '123'\n\n calico_rkt._container_remove(hostname=m_host,\n orchestrator_id=ORCHESTRATOR_ID,\n container_id=id_)\n m_client.get_endpoint.assert_called_once_with(hostname=m_host,\n orchestrator_id=ORCHESTRATOR_ID,\n workload_id=id_)\n m_client.remove_workload.assert_called_once_with(hostname=m_host,\n orchestrator_id=ORCHESTRATOR_ID,\n workload_id=id_)\n m_client.unassign_address.assert_called_once_with(\n None, IPAddress('1.2.3.4'))\n\n @patch('calico_rkt.datastore_client',\n autospec=True)\n def test_set_profile_on_endpoint(self, m_client):\n m_client.profile_exists.return_value = False\n\n m_ep = Mock()\n m_ep.endpoint_id = '1234'\n\n p_name, ip_ = 'profile', '1.2.3.4'\n\n calico_rkt._set_profile_on_endpoint(endpoint=m_ep,\n profile_name=p_name)\n\n m_client.profile_exists.assert_called_once_with(p_name)\n m_client.create_profile.assert_called_once_with(p_name)\n m_client.set_profiles_on_endpoint.assert_called_once_with(profile_names=[p_name],\n endpoint_id='1234')\n\n @patch('calico_rkt.datastore_client',\n autospec=True)\n def test_create_assign_rules(self, m_client):\n m_profile = Mock()\n m_client.get_profile.return_value = m_profile\n\n p_name = 'profile'\n\n calico_rkt._assign_default_rules(profile_name=p_name)\n\n m_client.get_profile.assert_called_once_with(p_name)\n m_client.profile_update_rules.assert_called_once_with(m_profile)\n\n @patch('calico_rkt.datastore_client',\n autospec=True)\n @patch('pycalico.ipam.SequentialAssignment.allocate',\n autospec=True)\n def test_assign_to_pool(self, m_seq, m_client):\n m_seq.return_value = '10.22.0.1'\n calico_rkt._assign_to_pool(subnet=ARGS['subnet'])\n m_client.add_ip_pool.assert_called_once_with(4, IPPool(\"10.22.0.0/16\"))\n","sub_path":"calico_rkt/tests/test_rkt_plugin.py","file_name":"test_rkt_plugin.py","file_ext":"py","file_size_in_byte":9337,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"590235549","text":"# Copyright 2018 Mirantis, Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nimport pytest\n\nfrom tcp_tests import logger\nfrom tcp_tests import settings\n\nLOG = logger.logger\n\n\n@pytest.mark.deploy\nclass TestMcpInstallStacklightOpenstack(object):\n \"\"\"Test class for testing mcp11 vxlan deploy\"\"\"\n\n @pytest.mark.grab_versions\n @pytest.mark.fail_snapshot\n def test_mcp_os_install(self, underlay, openstack_deployed,\n openstack_actions):\n \"\"\"Test for deploying an mcp environment and check it\n Scenario:\n 1. Prepare salt on hosts\n 2. Setup controller nodes\n 3. Setup compute nodes\n 4. Run tempest\n\n \"\"\"\n openstack_actions._salt.local(\n tgt='*', fun='cmd.run',\n args='service ntp stop; ntpd -gq; service ntp start')\n\n if settings.RUN_TEMPEST:\n openstack_actions.run_tempest(pattern=settings.PATTERN)\n openstack_actions.download_tempest_report()\n LOG.info(\"*************** DONE **************\")\n\n @pytest.mark.grab_versions\n @pytest.mark.fail_snapshot\n def test_mcp_os_mitaka_install(self, underlay, openstack_deployed,\n openstack_actions):\n \"\"\"Test for deploying an mcp environment and check it\n Scenario:\n 1. Prepare salt on hosts\n 2. Setup controller nodes\n 3. Setup compute nodes\n 4. Run tempest\n\n \"\"\"\n openstack_actions._salt.local(\n tgt='*', fun='cmd.run',\n args='service ntp stop; ntpd -gq; service ntp start')\n\n if settings.RUN_TEMPEST:\n openstack_actions.run_tempest(pattern=settings.PATTERN,\n conf_name='lvm_mcp_mitaka.conf')\n openstack_actions.download_tempest_report()\n LOG.info(\"*************** DONE **************\")\n\n @pytest.mark.grab_versions\n @pytest.mark.fail_snapshot\n def test_mcp_sl_os_install(self, underlay, config, openstack_deployed,\n stacklight_deployed, openstack_actions):\n \"\"\"Test for deploying an mcp environment and check it\n Scenario:\n 1. Prepare salt on hosts\n 2. Setup controller nodes\n 3. Setup compute nodes\n 4. Get monitoring nodes\n 5. Check that docker services are running\n 6. Check current prometheus targets are UP\n 7. Run SL component tests\n 8. Download SL component tests report\n \"\"\"\n mon_nodes = stacklight_deployed.get_monitoring_nodes()\n LOG.debug('Mon nodes list {0}'.format(mon_nodes))\n\n stacklight_deployed.check_prometheus_targets(mon_nodes)\n\n # Run SL component tetsts\n stacklight_deployed.run_sl_functional_tests(\n 'cfg01',\n '/root/stacklight-pytest/stacklight_tests/',\n 'tests',\n 'test_alerts.py')\n\n # Download report\n stacklight_deployed.download_sl_test_report(\n 'cfg01',\n '/root/stacklight-pytest/stacklight_tests/report.xml')\n LOG.info(\"*************** DONE **************\")\n\n openstack_actions._salt.local(\n tgt='*', fun='cmd.run',\n args='service ntp stop; ntpd -gq; service ntp start')\n\n if settings.RUN_TEMPEST:\n openstack_actions.run_tempest(pattern=settings.PATTERN)\n openstack_actions.download_tempest_report()\n LOG.info(\"*************** DONE **************\")\n","sub_path":"tcp_tests/tests/system/test_install_mcp_sl_os.py","file_name":"test_install_mcp_sl_os.py","file_ext":"py","file_size_in_byte":4010,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"232783828","text":"#!/usr/bin/env python3\n\nimport os, time, datetime, platform, urllib, hashlib\nimport qiniu\nfrom mimetypes import MimeTypes\nimport pyperclip\nfrom os.path import expanduser\nimport configparser\n\nhomedir = expanduser(\"~\")\nconfig = configparser.ConfigParser()\nconfig.read(homedir+'/qiniu.cfg')\nmime = MimeTypes()\nnow = datetime.datetime.now()\n\n\ntry:\n bucket = config.get('config', 'bucket')\n accessKey = config.get('config', 'accessKey')\n secretKey = config.get('config', 'secretKey')\n path_to_watch = config.get('config', 'path_to_watch')\n enable = config.get('custom_url','enable')\n if enable == 'false':\n print('custom_url not set')\n else:\n addr = config.get('custom_url','addr')\n\n\nexcept ConfigParser.NoSectionError as err:\n print('Error Config File:' + err)\n\n\ndef setcodeingbyos():\n '''获取系统平台,设置编解码'''\n if 'cygwin' in platform.system().lower():\n code = 'GBK'\n elif os.name == 'nt' or platform.system() == 'Windows':\n code = 'GBK'\n elif os.name == 'mac' or platform.system() == 'Darwin':\n code = 'utf-8'\n elif os.name == 'posix' or platform.system() == 'Linux':\n code = 'utf-8'\n return code\n\n\ndef set_clipboard(url_list):\n\tfor url in url_list:\n\t\tpyperclip.copy(url)\n\tspam = pyperclip.paste()\n\n\n\ndef parseRet(retData, respInfo):\n '''处理上传结果'''\n if retData != None:\n print(\"Upload file success!\")\n print(\"Hash: \" + retData[\"hash\"])\n print(\"Key: \" + retData[\"key\"])\n for k, v in retData.items():\n if k[:2] == \"x:\":\n print(k + \":\" + v)\n for k, v in retData.items():\n if k[:2] == \"x:\" or k == \"hash\" or k == \"key\":\n continue\n else:\n print(k + \":\" + str(v))\n else:\n print(\"Upload file failed!\")\n print(\"Error: \" + respInfo.text_body)\n\n\ndef upload_without_key(bucket, filePath, uploadname):\n '''上传文件'''\n\n auth = qiniu.Auth(accessKey, secretKey)\n upToken = auth.upload_token(bucket, key=None)\n \n key = uploadname\n retData, respInfo = qiniu.put_file(upToken, key, filePath, mime_type=mime.guess_type(filePath)[0])\n parseRet(retData, respInfo)\n\n\ndef getkey(filename):\n ext = filename[filename.rfind('.'):]\n file_path = path_to_watch + '/' + filename\n md5 = hashlib.md5(open(file_path, 'rb').read()).hexdigest()\n # remote url: filetype/year/month/md5.filetype\n remote = ext[1:] + '/' + str(now.year) + '/' + str(now.month) + '/' + md5 + ext\n return remote\n\n\ndef main():\n print(\"running ... ...\")\n before = dict([(f, None) for f in os.listdir(path_to_watch)])\n while 1:\n time.sleep(1)\n after = dict([(f, None) for f in os.listdir(path_to_watch)])\n added = [f for f in after if not f in before]\n removed = [f for f in before if not f in after]\n if added:\n print(\"Added Files: \" + \", \".join(added))\n # print(added)\n url_list = []\n\n for i in added:\n filekey = getkey(i)\n\n upload_without_key(bucket, os.path.join(path_to_watch, i), filekey)\n if enable == 'true':\n url = addr + urllib.parse.quote(filekey)\n else:\n url = 'http://' + bucket + '.qiniudn.com/' + urllib.parse.quote(filekey)\n url_list.append(url)\n\n with open('image_markdown.txt', 'a') as f:\n for url in url_list:\n image = '![' + added[0] + ']' + '(' + url + ')' + '\\n'\n f.write(image)\n print(\"image url [markdown] is save in image_markdwon.txt\")\n\n set_clipboard(url_list)\n if removed:\n print(\"Removed Files: \" + \", \".join(removed))\n print(removed)\n before = after\n\nif __name__ == \"__main__\":\n main()\n\n\n","sub_path":"qiniu4blog/qiniu4blog.py","file_name":"qiniu4blog.py","file_ext":"py","file_size_in_byte":3873,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"496710581","text":"def parse(s):\n return (s[:7], s[7:])\n\ndef bisect(s):\n l, r = 0, 2**len(s) - 1\n for c in s:\n mid = (l + r) // 2\n if c in ['B', 'R']:\n l = mid + 1\n else:\n r = mid\n return r\n\nwith open(\"input.txt\") as f:\n lines = f.read().splitlines()\n f = lambda bp: bisect(bp[0]) * 8 + bisect(bp[1])\n ids = [f(parse(l)) for l in lines]\n\ndef part1(l = ids):\n return max(l)\n\ndef part2(l = ids):\n s = sorted(l)\n # can be done in O(n), but meh\n for i in range(len(s) - 1): \n if s[i] + 1 != s[i + 1]:\n return s[i] + 1\n \n","sub_path":"5/sol.py","file_name":"sol.py","file_ext":"py","file_size_in_byte":594,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"428595128","text":"import sqlite3\n\nfrom telebot import types\n\nimport events\nimport windows\nfrom bank import Bank\nfrom database.converter import Converter\nimport database.db_paths as paths\n\n\nclass SQLDatabase:\n def __init__(self, bot, db_name):\n self._bot = bot\n self.db_name = db_name\n self.connection = sqlite3.connect(db_name,\n detect_types=sqlite3.PARSE_DECLTYPES)\n self.connection.row_factory = sqlite3.Row\n self.converter = Converter(self)\n sqlite3.register_adapter(bool, int)\n sqlite3.register_converter('BOOLEAN', lambda v: int(v) == 1)\n\n def setup(self):\n with open(paths.SETUP, 'r') as setup_script:\n query = setup_script.read()\n with self.connection:\n self.connection.executescript(query)\n\n def insert_new_user(self, user):\n with open(paths.INSERT_USER, 'r') as insert_user_script:\n query = insert_user_script.read()\n with self.connection:\n self.connection.execute(query, self.converter.user_to_row(user))\n\n def insert_new_chat(self, chat):\n with open(paths.INSERT_CHAT, 'r') as insert_chat_script:\n query = insert_chat_script.read()\n with self.connection:\n self.connection.execute(query, self.converter.chat_to_row(chat))\n\n def insert_new_bank(self, chat, owner):\n if owner.id not in [user.id for user in self.get_users_list()]:\n self.insert_new_user(owner)\n with open(paths.INSERT_BANK, 'r') as insert_bank_script:\n query = insert_bank_script.read()\n with self.connection:\n self.connection.execute(query, [chat.id, owner.id])\n\n def insert_new_window(self, window):\n with open(paths.INSERT_WINDOW, 'r') as insert_window_script:\n query = insert_window_script.read()\n args = self.converter.window_to_row(window)\n with self.connection:\n self.connection.execute(query, args)\n\n def insert_new_event(self, event):\n with open(paths.INSERT_EVENT, 'r') as insert_event_script:\n query = insert_event_script.read()\n with self.connection:\n self.connection.execute(query, self.converter.event_to_row(event))\n\n def get_users_list(self):\n with open(paths.SELECT_USERS, 'r') as select_users_script:\n query = select_users_script.read()\n with self.connection:\n users_table = self.connection.execute(query).fetchall()\n return [self.converter.row_to_user(row) for row in users_table]\n\n def get_chats_list(self):\n with open(paths.SELECT_CHATS, 'r') as select_chats_script:\n query = select_chats_script.read()\n with self.connection:\n chats_table = self.connection.execute(query).fetchall()\n return [self.converter.row_to_chat(row) for row in chats_table]\n\n def get_chats_with_banks(self):\n \"\"\" Returns list of chat ids,\n chat id is in the list if there is a bank already\n created for this chat.\"\"\"\n query = 'SELECT b.chat_id AS chat_id FROM bank b'\n with self.connection:\n rows = self.connection.execute(query).fetchall()\n return [row['chat_id'] for row in rows]\n\n def get_windows_list(self):\n \"\"\" Returns list of created windows. \"\"\"\n with open(paths.SELECT_WINDOWS, 'r') as select_windows_script:\n query = select_windows_script.read()\n with self.connection:\n windows_table = self.connection.execute(query).fetchall()\n return [self.converter.row_to_window(row) for row in windows_table]\n\n def get_bank(self, chat_id):\n \"\"\" Returns tuple (chat, owner, sum) for the bank_id (chat_id).\n Returns None if no banks with such chat_id was found. \"\"\"\n with open(paths.SELECT_BANK_STATE, 'r') as select_state_script:\n query = select_state_script.read()\n with self.connection:\n bank_row = self.connection.execute(query, [chat_id]).fetchone()\n return self.converter.row_to_bank(bank_row)\n\n def add_user_to_bank(self, chat_id, user_id):\n with open(paths.ADD_USER_TO_BANK, 'r') as add_user_to_bank_script:\n query = add_user_to_bank_script.read()\n bank_id = self._get_bank_id(chat_id)\n with self.connection:\n self.connection.execute(query, [bank_id, user_id])\n\n def get_bank_users_ids(self, chat_id):\n \"\"\" Get list of user ids of users of particular bank. \"\"\"\n with open(paths.GET_BANK_USERS, 'r') as get_bank_users_script:\n query = get_bank_users_script.read()\n bank_id = self._get_bank_id(chat_id)\n with self.connection:\n id_list = self.connection.execute(query, [bank_id]).fetchall()\n return [row['user_id'] for row in id_list]\n\n def get_history(self, chat_id):\n \"\"\" Returns list of following tuples:\n (user_id, first_name, last_name,\n event_id, datetime, type, amount, is_deleted)\"\"\"\n with open(paths.SELECT_HISTORY, 'r') as select_history_script:\n query = select_history_script.read()\n with self.connection:\n history = self.connection.execute(query, [chat_id]).fetchall()\n return [self.converter.row_to_event(row) for row in history]\n\n def get_event(self, event_id):\n with open(paths.SELECT_EVENT, 'r') as select_event_script:\n query = select_event_script.read()\n with self.connection:\n row = self.connection.execute(query, [event_id]).fetchone()\n return self.converter.row_to_event(row)\n\n def get_user_connections(self):\n with open(paths.SELECT_CONNECTION, 'r') as select_user_conn_script:\n query = select_user_conn_script.read()\n with self.connection:\n connection_list = self.connection.execute(query).fetchall()\n connection_list = list(connection_list)\n return connection_list\n\n def connect_user(self, user, chat):\n with open(paths.CONNECT_USER, 'r') as connect_user_script:\n query = connect_user_script.read()\n with self.connection:\n self.connection.execute(query, [chat.id, user.id])\n\n def get_available_chats(self, user):\n with open(paths.SELECT_AVAILABLE_CHATS, 'r') as select_chats_script:\n query = select_chats_script.read()\n with self.connection:\n chat_rows = self.connection.execute(query, [user.id]).fetchall()\n return [self.converter.row_to_chat(row) for row in chat_rows]\n\n def update_window(self, window):\n with open(paths.UPDATE_WINDOW, 'r') as update_window_script:\n query = update_window_script.read()\n with self.connection:\n self.connection.execute(query, [window.message_id, window.user.id])\n\n def switch_event(self, event_id):\n query = \\\n 'UPDATE event SET is_deleted = NOT is_deleted WHERE event_id = ?'\n with self.connection:\n self.connection.execute(query, [event_id])\n\n def _get_bank_id(self, chat_id):\n query = 'SELECT b.bank_id AS id FROM bank b WHERE b.chat_id = ?;'\n with self.connection:\n row = self.connection.execute(query, [chat_id]).fetchone()\n return row['id']\n","sub_path":"database/deposit_bot_database.py","file_name":"deposit_bot_database.py","file_ext":"py","file_size_in_byte":7252,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"37502653","text":"from .layers import *\n\n\"\"\" \nThis code was originally written for CS 231n at Stanford University\n(cs231n.stanford.edu). It has been modified in various areas for use in the\nECE 239AS class at UCLA. This includes the descriptions of what code to\nimplement as well as some slight potential changes in variable names to be\nconsistent with class nomenclature. We thank Justin Johnson & Serena Yeung for\npermission to use this code. To see the original version, please visit\ncs231n.stanford.edu. \n\"\"\"\n\ndef affine_relu_forward(x, w, b):\n \"\"\"\n Convenience layer that performs an affine transform followed by a ReLU\n\n Inputs:\n - x: Input to the affine layer\n - w, b: Weights for the affine layer\n\n Returns a tuple of:\n - out: Output from the ReLU\n - cache: Object to give to the backward pass\n \"\"\"\n a, fc_cache = affine_forward(x, w, b)\n out, relu_cache = relu_forward(a)\n cache = (fc_cache, relu_cache)\n return out, cache\n\n\ndef affine_relu_backward(dout, cache):\n \"\"\"\n Backward pass for the affine-relu convenience layer\n \"\"\"\n fc_cache, relu_cache = cache\n da = relu_backward(dout, relu_cache)\n dx, dw, db = affine_backward(da, fc_cache)\n return dx, dw, db\n\ndef affine_batchnorm_relu_forward(x, w, b, gamma, beta, bn_param):\n a, fc_cache = affine_forward(x, w, b)\n c, bn_cache = batchnorm_forward(a, gamma, beta, bn_param)\n out, relu_cache = relu_forward(c)\n cache = (fc_cache, bn_cache, relu_cache)\n return out, cache\n\ndef affine_batchnorm_relu_backward(dout, cache):\n fc_cache, bn_cache, relu_cache = cache\n da = relu_backward(dout, relu_cache)\n dx, dgamma, dbeta = batchnorm_backward(da, bn_cache)\n dx, dw, db = affine_backward(dx, fc_cache)\n return dx, dw, db, dgamma, dbeta\n\ndef affine_batchnorm_relu_dropout_forward(x, w, b, gamma, beta, bn_param, dropout_param):\n a, fc_cache = affine_forward(x, w, b)\n c, bn_cache = batchnorm_forward(a, gamma, beta, bn_param)\n d, relu_cache = relu_forward(c)\n out, do_cache = dropout_forward(d, dropout_param)\n cache = (fc_cache, bn_cache, relu_cache, do_cache)\n return out, cache\n\ndef affine_batchnorm_relu_dropout_backward(dout, cache):\n fc_cache, bn_cache, relu_cache, do_cache = cache\n da = dropout_backward(dout, do_cache)\n db = relu_backward(da, relu_cache)\n dx, dgamma, dbeta = batchnorm_backward(db, bn_cache)\n dx, dw, db = affine_backward(dx, fc_cache)\n return dx, dw, db, dgamma, dbeta\n\ndef affine_relu_dropout_forward(x, w, b, dropout_param):\n a, fc_cache = affine_forward(x, w, b)\n c, relu_cache = relu_forward(a)\n out, do_cache = dropout_forward(c, dropout_param)\n cache = (fc_cache, relu_cache, do_cache)\n return out, cache\n\ndef affine_relu_dropout_backward(dout, cache):\n fc_cache, relu_cache, do_cache = cache\n da = dropout_backward(dout, do_cache)\n db = relu_backward(da, relu_cache)\n dx, dw, db = affine_backward(db, fc_cache)\n return dx, dw, db","sub_path":"HW#4/layer_utils.py","file_name":"layer_utils.py","file_ext":"py","file_size_in_byte":2918,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"19014180","text":"import json\nimport config as conf\nimport os\n\n'''\n\nThis script loads data from the json file and do the pre-processing work.\n\n'''\n\ndef load_file(path):\n data = []\n f = open(path, \"r\")\n while True:\n s = f.readline()\n if len(s) < 1:\n break\n data.append(json.loads(s))\n f.close()\n\n return data\n\nif __name__ == \"__main__\":\n if conf.TEST == 0:\n review_path = conf.REVIEW_DATA_PATH\n else:\n review_path = conf.MINI_DATA_PATH\n data = load_file(review_path)\n print(len(data))","sub_path":"RamenAI/app/data_processing.py","file_name":"data_processing.py","file_ext":"py","file_size_in_byte":538,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"465915091","text":"import torch\r\n\r\ninput = [3,4,6,5,\r\n 2,4,6,8,\r\n 1,6,7,8,\r\n 9,7,4,6]\r\n\r\ninput = torch.Tensor(input).view(1,1,4,4)\r\n\r\nmax_layer = torch.nn.MaxPool2d(kernel_size=2)\r\n\r\noutput = max_layer(input)\r\n\r\nprint(output)\r\n\r\n\r\n","sub_path":"mypractice/poolinglayer.py","file_name":"poolinglayer.py","file_ext":"py","file_size_in_byte":236,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"521714654","text":"import sys\nsys.path.append('./..')\nimport numpy as np\nfrom sklearn.decomposition import PCA\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom plot_utils import set_size\nfrom collections import OrderedDict\nfrom bias_specifications import antisemitic_streams\nfrom utils import load_embedding_dict\nfrom scipy import stats\nimport argparse\nimport logging \n\n# Plotting parameters\nTEX_FONTS = {\n \"font.family\": \"serif\",\n # Use 10pt font in plots, to match 10pt font in document\n \"axes.labelsize\": 10,\n \"font.size\": 10,\n # Make the legend/label fonts a little smaller\n \"legend.fontsize\": 8,\n \"xtick.labelsize\": 8,\n \"ytick.labelsize\": 8\n}\n# Figure height and width\nWIDTH = 360\nFIG_DIM = set_size(WIDTH)\nplt.rcParams.update(TEX_FONTS)\n\n# Word pairs that establish bias subspace\nTARGETS_CHRISTIAN = ['christ', 'christlich','christentum']\nTARGETS_JEWISH = ['jude', 'juedisch', 'judentum'] \n\nclass SubspaceProjections:\n\n def __init__(self):\n self.embd_dict = None\n self.vocab = None\n self.embedding_matrix = None\n\n def set_embd_dict(self, embd_dict):\n self.embd_dict = embd_dict\n\n def convert_by_vocab(self, items, numbers=True):\n \"\"\"Converts a sequence of [tokens|ids] using the vocab.\"\"\"\n if numbers:\n output = [self.vocab[item] for item in items if item in self.vocab]\n else:\n output = [item for item in items if item in self.vocab]\n return output\n\n def _build_vocab_dict(self, vocab):\n self.vocab = OrderedDict()\n vocab = set(vocab)\n index = 0\n for term in vocab:\n if term in self.embd_dict:\n self.vocab[term] = index\n index += 1\n else:\n logging.warning(\"Not in vocab %s\", term)\n\n def _build_embedding_matrix(self):\n self.embedding_matrix = []\n for term, index in self.vocab.items():\n if term in self.embd_dict:\n self.embedding_matrix.append(self.embd_dict[term])\n else:\n raise AssertionError(\"This should not happen.\")\n self.embedding_matrix = self.mat_normalize(self.embedding_matrix)\n\n self.embd_dict = None\n\n def mat_normalize(self,mat, norm_order=2, axis=1):\n return mat / np.transpose([np.linalg.norm(mat, norm_order, axis)])\n\n def bias_axes(self, semantic_domain, protocol_type):\n \"\"\"\n Establish bias axes\n \"\"\"\n targets_1 = TARGETS_CHRISTIAN\n targets_2 = TARGETS_JEWISH\n attributes_1, attributes_2 = antisemitic_streams(semantic_domain, protocol_type)\n return targets_1, targets_2, attributes_1, attributes_2\n\n def cosine(self, a, b):\n # norm_a = self.mat_normalize(a,axis=0)\n # norm_b = self.mat_normalize(b,axis=0)\n cos = np.dot(a, np.transpose(b))\n # cos = np.dot(norm_a, np.transpose(norm_b))\n return cos\n\n def doPCA(self, targets_1, targets_2, plot=False):\n matrix = []\n T1 = self.convert_by_vocab(targets_1)\n T2 = self.convert_by_vocab(targets_2)\n for a,b in zip(T1, T2):\n center = (self.embedding_matrix[a] + self.embedding_matrix[b]) /2\n matrix.append(self.embedding_matrix[a] - center)\n matrix.append(self.embedding_matrix[b] - center)\n matrix = np.array(matrix)\n pca = PCA(n_components = round(len(T1)))\n pca.fit(matrix)\n logging.info(pca.explained_variance_ratio_[0])\n if plot:\n plt.bar(np.arange(pca.n_components_), pca.explained_variance_ratio_)\n plt.show()\n \n race_direction_pca = pca.components_[0]\n return race_direction_pca\n\n def get_projections(self, attribute, race_direction, slice):\n \"\"\"Compute subspace projections of attribute terms onto the bias direction\"\"\"\n A1 = self.convert_by_vocab(attribute, numbers=False)\n projections = {}\n for word in A1:\n projection = self.cosine(self.embedding_matrix[self.vocab[word]], race_direction) \n if slice in ('kaiserreich_1', 'weimar', 'spd_1', 'cdu_2'):\n projections[word] = projection * (-1)\n logging.info(f'Projection for {word}: {projection}.')\n else:\n projections[word] = projection\n logging.info(f'Projection for {word}: {projection}.')\n\n return projections\n\n\n def plot_onto_bias_direction(self, projections_1, projections_2, style='ggplot', output_file=''):\n # Sort projections\n projections_1 = {k: v for k, v in sorted(projections_1.items(), key=lambda item: item[1], reverse=True)}\n projections_2 = {k: v for k, v in sorted(projections_2.items(), key=lambda item: item[1])}\n\n with plt.style.context(style):\n fig, ax = plt.subplots(figsize=(FIG_DIM))\n # Plot values on the x-axis\n ax.plot(list(projections_1.values()), np.zeros(len(projections_1)), 'co', ms=2.5)\n ax.plot(list(projections_2.values()), np.zeros(len(projections_2)), 'mo', ms=2.5)\n ax.legend(['positive', 'negative'], loc= 'lower right')\n\n ax.set_xlim(min(min(projections_2.values())-0.05,-0.3),\n max(max(projections_1.values())+0.05,0.3))\n \n # Only annotate every second term\n for i in range(0, len(projections_1),2):\n k,v = list(projections_1.items())[i][0], list(projections_1.items())[i][1]\n ax.annotate(k, xy=(v,0), xytext= (v,0.025), rotation=90, ma='left', fontsize='xx-small', fontstretch='ultra-condensed',\n arrowprops=dict(facecolor='blue', shrink=0.02, alpha=0.15,width=1, headwidth=2))\n \n for i in range(0, len(projections_2), 2):\n k,v = list(projections_2.items())[i][0], list(projections_2.items())[i][1] \n ax.annotate(k, xy=(v,0), xytext= (v,-0.05), rotation=90, ma='left', fontsize='xx-small', fontstretch='ultra-condensed',\n arrowprops= dict(facecolor='blue', shrink=0.02, alpha=0.15,width=1, headwidth=2))\n \n fig.set_size_inches(FIG_DIM[0], (FIG_DIM[0]/2.3))\n ax.get_yaxis().set_visible(False)\n ax.set_frame_on(False)\n plt.tight_layout()\n if len(output_file) > 0:\n plt.savefig(f'plots/{output_file}.pdf',dpi=300)\n plt.show() \n\n\n def t_test(self, projections_1, projections_2):\n \"\"\"Compute t-test between the mean RIPA of two opposing semantic domains\"\"\"\n\n t2, p2 = stats.ttest_ind(projections_1, projections_2, equal_var=False)\n logging.info(\"t = \" + str(t2))\n logging.info(\"p = \" + str(p2))\n return (t2,p2)\n\ndef main():\n def boolean_string(s):\n if s not in {'False', 'True', 'false', 'true'}:\n raise ValueError('Not a valid boolean string')\n return s == 'True' or s == 'true'\n parser = argparse.ArgumentParser(description=\"Compute subspace projections onto ethno-religious bias subspace - plot and/or compute t-test between them\")\n parser.add_argument(\"--protocol_type\", nargs='?', choices = ['RT', 'BRD'], help=\"Whether to run test for Reichstagsprotokolle (RT) or Bundestagsprotokolle (BRD)\",required=True)\n parser.add_argument(\"--sem_domain\", nargs='?', choices= ['sentiment', 'patriotism', 'economic', 'conspiratorial', 'racist', 'religious', 'ethic'], help='Which semantic domain to test in WEAT', required=True)\n parser.add_argument(\"--output_file\", type=str, default=None, help=\"File to store the results)\", required=False)\n parser.add_argument(\"--embedding_vocab\", type=str, help=\"Vocab of the self.embedding_matrix\")\n parser.add_argument(\"--embedding_vectors\", type=str, help=\"Vectors of the self.embedding_matrix\")\n parser.add_argument(\"--slice\", type=str, help=\"The slice to plot\")\n parser.add_argument(\"--plot_projections\", type=boolean_string, default=True, help=\"Whether to plot subspace projections\", required=True)\n parser.add_argument(\"--plot_pca\", type=boolean_string, default=False, help=\"Whether to plot subspace projections\", required=True)\n parser.add_argument(\"--t_test\", type=boolean_string, default=True, help=\"Whether to compute t-test for a semantic domain \", required=True)\n\n args = parser.parse_args()\n logging.basicConfig(level=logging.INFO)\n logging.info('Started')\n ripa = SubspaceProjections()\n\n targets_1, targets_2, attributes_1, attributes_2 = ripa.bias_axes(args.sem_domain, args.protocol_type)\n\n embd_dict = load_embedding_dict(vocab_path=args.embedding_vocab, vector_path=args.embedding_vectors, glove=False)\n ripa.set_embd_dict(embd_dict)\n vocab = targets_1 + targets_2 + attributes_1 + attributes_2\n ripa._build_vocab_dict(vocab)\n ripa._build_embedding_matrix()\n # Don't forget to normalize vectors!!!\n\n race_direction_pca = ripa.doPCA(targets_1,targets_2, plot=args.plot_pca)\n \n projections_pro= ripa.get_projections(attributes_1, race_direction_pca, args.slice)\n projections_con= ripa.get_projections(attributes_2, race_direction_pca, args.slice)\n\n if args.plot_projections:\n with plt.style.context('ggplot'):\n logging.info(f'Plot projections for semantic sphere {args.sem_domain}')\n ripa.plot_onto_bias_direction(projections_pro, projections_con, output_file=args.output_file)\n if args.t_test:\n if not os.path.exists('t_test'):\n os.makedirs('t_test')\n logging.info(f'Conduct t-test for semantic sphere {args.sem_domain}')\n t,p = ripa.t_test(list(projections_pro.values()), list(projections_con.values()))\n with codecs.open(f't_test/{args.slice}_{args.semantic_domain}.txt', \"w\", \"utf8\") as f:\n f.write(f'test statistic: {t}, ')\n f.write(f'p-value: {p}\\n')\n f.close()\n\nif __name__ == \"__main__\":\n main()\n\n\n\n\n\n\n","sub_path":"evaluation/projections.py","file_name":"projections.py","file_ext":"py","file_size_in_byte":9547,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"423080890","text":"import tdl\n\nSCREEN_WIDTH = 32\nSCREEN_HEIGHT = 40\nMAP_WIDTH = 30\nMAP_HEIGHT = 30\nFPS = 20\n\nroot = tdl.init(SCREEN_WIDTH,SCREEN_HEIGHT,title=\"Roguelike\")\ncon = tdl.Console(MAP_WIDTH,MAP_HEIGHT)\ntdl.set_font('fonts/terminal16x16_gs_ro.png', greyscale=True, altLayout=True)\ntdl.setFPS(FPS)\n\ndef handle_keys():\n\n\tuser_input = tdl.event.key_wait()\n\n\tif user_input.key == 'UP':\n\t\tplayer.y -= 1\n\telif user_input.key == 'DOWN':\n\t\tplayer.y += 1\n\telif user_input.key == 'LEFT':\n\t\tplayer.x -= 1\n\telif user_input.key == 'RIGHT':\n\t\tplayer.x += 1\n\telif user_input.key == 'ENTER':\n\t\treturn True\n\nclass GameObject:\n\tdef __init__(self, x, y, char, color):\n\t\tself.x=x\n\t\tself.y=y\n\t\tself.char=char\n\t\tself.color=color\n\tdef move(self,dx,dy):\n\t\tself.x+=dx\n\t\tself.y+=dy\n\tdef draw(self):\n\t\tcon.draw_char(self.x,self.y,self.char,self.color)\n\nclass Tile:\n\tdef __init__(self,blocked,block_sight = None):\n\t\tself.blocked = blocked\n\t\tif self.blocked:\n\t\t\tself.char='#'\n\t\t\tself.color=(0,0,100)\n\t\telse:\n\t\t\tself.char='.'\n\t\t\tself.color=(50,50,150)\n\n\t\tif block_sight == None: block_sight = blocked\n\t\tself.block_sight = block_sight\n\ndef make_map():\n\tglobal terrain\n\n\tterrain = [[Tile(False)\n\t\tfor y in range(MAP_HEIGHT) ]\n\t\t\tfor x in range(MAP_WIDTH) ]\n\ndef render_all():\n\tfor y in range(MAP_HEIGHT):\n\t\tfor x in range(MAP_WIDTH):\n\t\t\tcon.draw_char(x,y,terrain[x][y].char,terrain[x][y].color)\n\tfor obj in objects:\n\t\tobj.draw()\n\nplayer = GameObject(SCREEN_WIDTH//2,SCREEN_HEIGHT//2,'@',(255,255,255))\nnpc = GameObject(SCREEN_WIDTH//2 - 5,SCREEN_HEIGHT//2,'@',(255,255,0))\nobjects = [npc,player]\n\nmake_map()\n\nwhile not tdl.event.is_window_closed():\n\tcon.clear()\n\trender_all()\n\troot.blit(con,1,1,MAP_WIDTH,MAP_HEIGHT,0,0)\n\ttdl.flush()\n\texit_game = handle_keys()\n\tif exit_game:\n\t\tbreak\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1741,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"435434224","text":"import os, logging, folium, gzip, datetime, sys\nfrom ftplib import FTP\nfrom txtparsing import DataWorker \n\nTAG = 'isdworker - '\nFIL_TAG = 'filtered.txt'\n\n# Range for possible simulation years\nINTEREST_RANGE = (2005, 2019)\n\nFTP_URL = 'ftp.ncdc.noaa.gov'\nFTP_GEN_PATH = '/pub/data/noaa/'\nFTP_EMAIL = 'martinm6@illinois.edu'\n\nLOC_FOLS = {\n 'data' : 'data/',\n\t'metadata' : 'data/metadata/',\n\t'templates' : 'data/templates/',\n\t'current-data' : 'data/current-data/'\n}\nTEMP_FILES = {\n 'station-list-temp' : 'isd-history-template.txt',\n 'station-data-temp' : 'station-data-template.txt'\n}\nMETA_FILES = {\n 'station-list' : 'isd-history.txt',\n 'rectangle-list' : 'current-rectangle.txt'\n}\nMETA_FTP_PATHS = {\n 'station-list' : '/pub/data/noaa/isd-history.txt'\n}\nMETA_WORKER = DataWorker(LOC_FOLS['templates']+TEMP_FILES['station-list-temp'])\n\n# Class in order to represent a viewing window in the GUI\nclass StationWindow():\n def __init__(self, gps_bot_left, gps_top_right, interest_year):\n self.data_file = LOC_FOLS['metadata']+META_FILES['rectangle-list']\n self.interest_year = interest_year\n self.update_area(gps_bot_left, gps_top_right)\n\n def update_area(self, gps_bot_left, gps_top_right):\n META_WORKER.read_filter(LOC_FOLS['metadata']+META_FILES['station-list'], \n LOC_FOLS['metadata']+META_FILES['rectangle-list'], \n ['lat', gps_bot_left[0], gps_top_right[0]], \n filter2=['lon', gps_bot_left[1], gps_top_right[1]])\n\n self.station_list = []\n meta_list = META_WORKER.get_vals(self.data_file, META_WORKER.labels)\n for sub_list in meta_list:\n self.station_list.append(WeatherStation(sub_list, self.interest_year))\n # self.clean_data()\n # Add the line above for the actual simulation, where the change in station window is incremental\n\n def make_map(self):\n coordinate_list = META_WORKER.get_vals(self.data_file, ['lat', 'lon'])\n \n for i, point in enumerate(coordinate_list):\n for j, val in enumerate(point):\n coordinate_list[i][j] = DataWorker.str_to_flt(val)\n map = folium.Map(location=[40.12, -88.22], zoom_start=4)\n for point in coordinate_list:\n folium.Marker(point).add_to(map)\n return map\n\n def debug(self, time):\n print(time)\n\n # Checks that all data is available for all stations in the given interest year, deletes if there is not\n def initialize_stations(self):\n updated_station_list = []\n for station in self.station_list:\n file_name = station.get_file_name()\n with open(LOC_FOLS['metadata']+'/'+str(self.interest_year)+'.txt', 'rt') as reader:\n for line in reader.readlines():\n line = line.rstrip()\n if line == file_name:\n updated_station_list.append(station) \n break;\n self.station_list = updated_station_list\n for station in self.station_list:\n station.pull_gz()\n\n\n # Local method, deletes gz files if pulled for a station\n def clean_data(self):\n for filename in os.listdir(LOC_FOLS['current-data']):\n found_file = False\n for station in self.station_list:\n if station.get_file_name() == filename:\n found_file = True\n break\n if not found_file:\n os.remove(LOC_FOLS['current-data']+filename)\n logging.debug(TAG+'removing ' + filename)\n\n # Creates or updates the current window snapshot with up to date weather information\n def update_time(self, time):\n logging.info(TAG+'Updating the station time to '+str(time))\n for station in self.station_list:\n station.update(time)\n\n def time_step(self, increment):\n logging.info(TAG+'Incrementing the window time by '+str(increment))\n for station in self.station_list:\n station.time_step(increment)\n\n# Class in order to represent a station - has methods to fetch and store data\nclass WeatherStation():\n # These are all the data fields pulled for each station, add/remove from this list to get less or more data\n DATA_LABELS = ['time', 'lat', 'lon', 'elev', 'winAngle', 'winSpeed', 'visibility', 'degreesC', 'seaLvlPress']\n DATA_WORKER = DataWorker(LOC_FOLS['templates']+TEMP_FILES['station-data-temp'])\n\n def __init__(self, metadata, interest_year):\n self.metaDataDictionary = {}\n self.interest_year = interest_year\n self.sim_time = datetime.datetime.now() # Default time for simulation is the most recent time, now\n for i, data in enumerate(metadata):\n self.metaDataDictionary.update({META_WORKER.labels[i] : data})\n self.data = []\n \n # Updates data as well as the sim_time of the object\n def update(self, new_time):\n logging.info(TAG+'Updating weather station...')\n prev_line = []\n prev_line_delta = sys.maxsize\n time_index = WeatherStation.DATA_WORKER.labels.index('time')\n self.sim_time = new_time\n desired_time = get_isd_time(self.sim_time)\n with gzip.open(LOC_FOLS['current-data']+self.get_file_name(), 'rt') as gzFile:\n for line in gzFile.readlines():\n parsed_line = WeatherStation.DATA_WORKER.parse_line(line)\n time = parsed_line[time_index]\n time_delta = abs(int(time) - desired_time)\n if time_delta < prev_line_delta:\n prev_line = line\n prev_line_delta = time_delta\n elif time_delta < 1000:\n break\n else:\n logging.info(TAG+'line not in chronological order encountered')\n self.data = WeatherStation.DATA_WORKER.get_vals_lined(prev_line, WeatherStation.DATA_LABELS)\n print(self.data)\n\n # Update the time by a certain datetime increment (increment is a timedelta object)\n def time_step(self, increment):\n self.update(self.sim_time + increment)\n logging.info(TAG+'Updating the station time to '+str(self.sim_time))\n\n def pull_gz(self):\n path = self.get_ftp_path()\n if not os.path.exists(LOC_FOLS['current-data']+self.get_file_name()):\n with open(LOC_FOLS['current-data']+self.get_file_name(), 'wb') as writer:\n with FTP(FTP_URL) as ftp:\n ftp.login(user = 'anonymous', passwd=FTP_EMAIL)\n ftp.retrbinary('RETR '+path, writer.write, 8*1024)\n logging.info(TAG+'pulling ' + path)\n else:\n logging.info(TAG+path+' already pulled')\n\n def get_file_name(self):\n return self.metaDataDictionary['usaf'] + '-' + self.metaDataDictionary['wban'] + '-' + str(self.interest_year) + '.gz'\n\n def get_ftp_path(self):\n return FTP_GEN_PATH + str(self.interest_year) + '/' + self.get_file_name()\n\n def __str__(self):\n return str(self.metaDataDictionary)\n\nclass WindVector:\n def __init__():\n return 0\n\n# Method to create all required folders and check for required files on local machine\ndef initialize_local_env():\n logging.info(TAG+'Initializing local environment')\n for path in LOC_FOLS.values():\n if not os.path.exists(path):\n if path is LOC_FOLS['templates']:\n logging.error(TAG+'the required templates are missing')\n logging.info(TAG+'Creating ' + path)\n os.mkdir(path)\n else:\n logging.info(TAG + path + ' found')\n\n# Method to check for and pull metadata, returns if there was data pulled\ndef metadata_pull():\n logging.info(TAG+'Checking for metadata')\n data_pulled = False\n with FTP(FTP_URL) as ftp:\n ftp.login(user = 'anonymous', passwd=FTP_EMAIL)\n for fileKey in META_FILES.keys():\n if not os.path.exists(LOC_FOLS['metadata']+META_FILES[fileKey]):\n data_pulled = True\n logging.info(TAG+'Attempting pull of '+META_FILES[fileKey]+' from FTP server')\n with open(LOC_FOLS['metadata']+META_FILES[fileKey], 'wb') as writer:\n try:\n ftp.retrbinary('RETR '+META_FTP_PATHS[fileKey], writer.write)\n logging.info(TAG+'\\tPull successful')\n except:\n data_pulled = False\n logging.info(TAG+'\\tMetadata file '+META_FILES[fileKey]+' was not found on the FTP server')\n for i in range (INTEREST_RANGE[0], INTEREST_RANGE[1]):\n if not os.path.exists(LOC_FOLS['metadata']+str(i)+'.txt'):\n data_pulled = True\n logging.info(TAG+'Downloading metadata for ' + str(i))\n file_list = ftp.nlst(FTP_GEN_PATH+str(i)+'/')\n DataWorker.save_lines(LOC_FOLS['metadata']+str(i)+'.txt', file_list, [20, len(file_list)])\n return data_pulled\n\n# Method to strip away stations not in the United States, as well as quicksort and merge metadata\ndef getsort_us_data():\n worker = DataWorker(LOC_FOLS['templates']+TEMP_FILES['station-list-temp'])\n\n logging.info(TAG+'Reading pulled ISD metadata')\n DataWorker.read_save(22, 29700, LOC_FOLS['metadata']+META_FILES['station-list'], LOC_FOLS['metadata']+FIL_TAG)\n DataWorker.replace(LOC_FOLS['metadata']+META_FILES['station-list'], LOC_FOLS['metadata']+FIL_TAG)\n\n logging.info(TAG+'Filtering metadata for US stations')\n worker.read_filter(LOC_FOLS['metadata']+META_FILES['station-list'], LOC_FOLS['metadata']+FIL_TAG, ['lat', 24.53105, 49.04069], filter2=['lon', -124.48491, -66.56499])\n DataWorker.replace(LOC_FOLS['metadata']+META_FILES['station-list'], LOC_FOLS['metadata']+FIL_TAG)\n\n logging.info(TAG+'Quicksorting metadata w/latitude')\n worker.quicksort_lg(LOC_FOLS['metadata']+META_FILES['station-list'], LOC_FOLS['metadata']+FIL_TAG, 'lat')\n DataWorker.replace(LOC_FOLS['metadata']+META_FILES['station-list'], LOC_FOLS['metadata']+FIL_TAG)\n\n# Converts datetime into time in the format used in .gz files\ndef get_isd_time(time):\n isd_time = s_ext(str(time.year), 4) + s_ext(str(time.month), 2) + s_ext(str(time.day), 2) + s_ext(str(time.hour), 2) + s_ext(str(time.minute), 2)\n return int(isd_time)\n\ndef s_ext(str, length):\n while len(str) != length:\n str = '0'+str\n return str\n\n# Update interest year based on the date inputted!! IMPORTANT\n","sub_path":"ISD-Worker/isdworker.py","file_name":"isdworker.py","file_ext":"py","file_size_in_byte":10522,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"20258640","text":"\"\"\"A Driver that steps a python environment using a python policy.\n\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom collections import OrderedDict\n\nimport numpy as np\nfrom tf_agents.drivers import driver\nfrom tf_agents.trajectories import trajectory\n\n\ndef stack_nested_arrays(arrays):\n sample = arrays[0]\n if isinstance(sample, np.ndarray):\n return np.stack(arrays)\n elif isinstance(sample, list):\n return [np.stack([array[i] for array in arrays]) for i in len(sample)]\n elif isinstance(sample, (dict, OrderedDict)):\n return OrderedDict([\n (key, np.stack([array[key] for array in arrays])) for key in sample\n ])\n elif sample == ():\n return ()\n else:\n raise ValueError('Unrecognized: %r' % (type(sample)))\n\n\nclass PyStepDriver(driver.Driver):\n \"\"\"A driver that runs a python policy in a python environment.\"\"\"\n\n def __init__(self,\n env,\n policy,\n observers,\n max_steps=None,\n max_episodes=None):\n \"\"\"A driver that runs a python policy in a python environment.\n\n Args:\n env: A py_environment.Base environment.\n policy: A py_policy.Base policy.\n observers: A list of observers that are notified after every step\n in the environment. Each observer is a callable\n (trajectory.Trajectory).\n max_steps: Optional maximum number of steps for each run() call.\n Also see below. Default: 0.\n max_episodes: Optional maximum number of episodes for each run()\n call. At least one of max_steps or max_episodes must be\n provided. If both are set, run() terminates when at least one\n of the conditions is satisfied. Default: 0.\n\n Raises:\n ValueError: If both max_steps and max_episodes are None.\n \"\"\"\n max_steps = max_steps or 0\n max_episodes = max_episodes or 0\n if max_steps < 1 and max_episodes < 1:\n raise ValueError('Either `max_steps` or `max_episodes` '\n 'should be greater than 0.')\n\n super(PyStepDriver, self).__init__(env, policy, observers)\n self._max_steps = max_steps or np.inf\n self._max_episodes = max_episodes or np.inf\n\n def run(self, time_step, policy_state=()):\n \"\"\"Run policy in environment given initial time_step and policy_state.\n Args:\n time_step: The initial time_step.\n policy_state: The initial policy_state.\n Returns:\n A tuple (final time_step, final policy_state).\n \"\"\"\n num_steps = 0\n num_episodes = 0\n while (num_steps < self._max_steps and\n num_episodes < self._max_episodes):\n if self.env.done:\n next_time_step = self.env.reset()\n next_policy_state = self.policy.get_initial_state()\n else:\n action_step = self.policy.action(time_step, policy_state)\n next_time_step = self.env.step(action_step.action)\n next_policy_state = action_step.state\n\n traj = trajectory.from_transition(\n time_step, action_step, next_time_step)\n\n for observer in self.observers:\n observer(traj)\n\n num_episodes += np.sum(traj.is_last())\n num_steps += np.sum(~traj.is_boundary())\n\n time_step = next_time_step\n policy_state = next_policy_state\n\n return time_step, policy_state\n\n\nclass PyEpisodeDriver(driver.Driver):\n \"\"\"A driver that runs a python policy in a python environment.\"\"\"\n\n def __init__(self,\n env,\n policy,\n observers,\n max_episodes):\n \"\"\"A driver that runs a python policy in a python environment.\n\n Args:\n env: A py_environment.Base environment.\n policy: A py_policy.Base policy.\n observers: A list of observers that are notified after every step\n in the environment. Each observer is a callable\n (trajectory.Trajectory).\n max_episodes: Optional maximum number of episodes for each run()\n call. If both are set, run() terminates when at least one of\n the conditions is satisfied. Default: 0.\n\n Raises:\n ValueError: If both max_steps and max_episodes are None.\n \"\"\"\n super(PyEpisodeDriver, self).__init__(env, policy, observers)\n\n max_episodes = max_episodes or 0\n self._max_episodes = max_episodes or np.inf\n\n def run(self, time_step, policy_state=()):\n \"\"\"Run policy in environment given initial time_step and policy_state.\n Args:\n time_step: The initial time_step.\n policy_state: The initial policy_state.\n Returns:\n A tuple (final time_step, final policy_state).\n \"\"\"\n for num_episodes in range(self._max_episodes):\n time_step = self.env.reset()\n policy_state = self.policy.get_initial_state()\n\n observation = []\n action = []\n policy_info = []\n reward = []\n\n while not self.env.done:\n action_step = self.policy.action(time_step, policy_state)\n if self.env.debug:\n self.env.visualize(action_step.action, action_step.info)\n next_time_step = self.env.step(action_step.action)\n next_policy_state = action_step.state\n\n if len(self.observers) > 0:\n observation.append(time_step.observation)\n action.append(action_step.action)\n policy_info.append(action_step.info)\n reward.append(next_time_step.reward)\n\n time_step = next_time_step\n policy_state = next_policy_state\n\n if len(self.observers) > 0:\n # TODO: Find a better way than repeating the last action.\n observation.append(time_step.observation)\n action.append(action_step.action)\n policy_info.append(action_step.info)\n reward.append(next_time_step.reward)\n\n observation = stack_nested_arrays(observation)\n action = stack_nested_arrays(action)\n policy_info = stack_nested_arrays(policy_info)\n reward = stack_nested_arrays(reward)\n\n traj = trajectory.from_episode(\n observation, action, policy_info, reward)\n\n for observer in self.observers:\n observer(traj)\n\n return time_step, policy_state\n\n\nclass PyInitializationDriver(PyEpisodeDriver):\n \"\"\"A driver that runs a python policy in a python environment.\"\"\"\n\n def run(self, time_step, policy_state=()):\n \"\"\"Run policy in environment given initial time_step and policy_state.\n Args:\n time_step: The initial time_step.\n policy_state: The initial policy_state.\n Returns:\n A tuple (final time_step, final policy_state).\n \"\"\"\n for num_episodes in range(self._max_episodes):\n time_step = self.env.reset()\n policy_state = self.policy.get_initial_state()\n\n if len(self.observers) > 0:\n for observer in self.observers:\n observer(time_step.observation)\n\n return time_step, policy_state\n","sub_path":"utils/py_driver.py","file_name":"py_driver.py","file_ext":"py","file_size_in_byte":7639,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"} +{"seq_id":"558302179","text":"# -*- coding: utf-8 -*-\nfrom time import gmtime, strftime\n\nimport telebot\nfrom openpyxl import load_workbook\nfrom telebot import types\n\nimport config\n\n###########db\n# Create table\n\n\n# DATABASE_URL = 'postgres://ubwrtgvthfcfpj:ce89c2af3d20432ca75aab90a63f955e6a7ffd8763305e19b6f34c1d45f56fde@ec2-54-235-86-226.compute-1.amazonaws.com:5432/d8qr5o45ha7ifr'\n# conn = psycopg2.connect(host='ec2-54-235-86-226.compute-1.amazonaws.com', dbname='d8qr5o45ha7ifr', sslmode='require',\n# user='ubwrtgvthfcfpj',\n# password='ce89c2af3d20432ca75aab90a63f955e6a7ffd8763305e19b6f34c1d45f56fde',\n# port='5432'\n# )\n# cur = conn.cursor()\n'''\n\n EXCEL CODE IS HERE\n\n'''\nf = load_workbook(filename='sample.xlsx')\n\ns = f.active\n\nbot = telebot.TeleBot(config.token)\n\n\ndef swapLines(a, b):\n for i in range(1, 100):\n t = s.cell(row=a, column=i).value\n s.cell(row=a, column=i).value = s.cell(row=b, column=i).value\n s.cell(row=b, column=i).value = t\n\n\ndef sortLines(col):\n for i in range(1, 99):\n for j in range(i + 1, 100):\n if int(s.cell(row=i, column=col).value) > int(s.cell(row=j, column=col).value):\n swapLines(i, j)\ndef newLine():\n for i in range(1,100):\n if s.cell(row=i, column=1).value==1e10:\n return i\n\n\n\n'''\n\n EXCEL CODE IS HERE\n\n'''\n\n'''\nsomefuncs:\n\n\ns.cell(row=i, column=col).value\n\nf = load_workbook(filename='sample.xlsx')\nf\ns=f.active\nf.save(\"sample.xlsx\")\n\n\n'''\n\nsomeday=['Понедельник', 'Вторник', 'Среда', 'Четверг', 'Пятница', 'Суббота', 'Воскресение', 'NEXT']\n\n@bot.message_handler(commands=['myNewShedule'])\ndef wtf(message):\n markup = types.ReplyKeyboardMarkup()\n markup.add('Понедельник', 'Вторник', 'Среда', 'Четверг', 'Пятница', 'Суббота', 'Воскресение', 'NEXT','EXIT')\n msg = bot.send_message(message.chat.id, '''Привет! Нажми на день недели.\\nP.S: Чтобы перейти на другой день, нажми NEXT''',reply_markup=markup)\n\n\n\n bot.register_next_step_handler(msg, afterDay)\n\n\ndef afterDay(dayy):\n if dayy.text == 'EXIT':\n msg = bot.send_message(dayy.chat.id, ':)')\n bot.register_next_step_handler(msg, startr)\n\n elif (dayy.text[:4] == 'NEXT'):\n msg = bot.send_message(dayy.chat.id, 'Нажми на день недели.')\n bot.register_next_step_handler(msg, afterDay)\n else:\n if dayy.text not in someday:\n msg = bot.send_message(dayy.chat.id,'Эй! нажми, а не вводи')\n bot.register_next_step_handler(msg, afterDay)\n else:\n\n\n fuck_off = dayy.text\n\n msg = bot.send_message(dayy.chat.id,\n 'Введи строку в виде:\\n00:00 Мероприятие\\nЧтобы перейти на другой день, нажми \"следующий день\"')\n bot.register_next_step_handler(msg, subj, fuck_off)\n\n\ndef subj(jojo, fuck_off):\n if (jojo.text == 'EXIT'):\n msg = bot.send_message(jojo.chat.id, ':)')\n bot.register_next_step_handler(msg, startr)\n elif (jojo.text == 'NEXT'):\n msg = bot.send_message(jojo.chat.id, 'Понял.')\n bot.register_next_step_handler(msg, wtf)\n else:\n\n\n\n\n '''\n parse the message\n '''\n ss=jojo.text\n\n ok=False\n timee=''\n textt=''\n for i in range(0,len(ss)):\n if ok == True:\n textt = ss[i:]\n break\n else:\n if ss[i]==' ':\n ok=True\n timee=ss[:i]\n\n\n print(timee,textt)\n integ = int(timee[0:2])*60+int(timee[3:5])+1\n\n '''\n parse the message\n '''\n i = newLine()\n s.cell(row=i, column=1).value=jojo.chat.id\n s.cell(row=i, column=2).value=fuck_off\n\n s.cell(row=i, column=3).value=timee\n s.cell(row=i, column=4).value=textt\n s.cell(row=i, column=5).value=integ\n\n msg = bot.send_message(jojo.chat.id, 'Сделано.\\nВведи строку в виде:\\n00:00 Мероприятие\\nЧтобы перейти на другой день, нажми NEXT')\n f.save(\"sample.xlsx\")\n\n bot.register_next_step_handler(msg, subj, fuck_off)\n\n\n@bot.message_handler(commands=['allShedule'])\ndef wow(message):\n sortLines(5)\n f.save(\"sample.xlsx\")\n\n textt = ''\n for day in someday:\n textt = day + '\\n\\n'\n\n for i in range(1, 100):\n if s.cell(row=i, column=1).value == message.chat.id and s.cell(row=i, column=2).value == day:\n textt += str(s.cell(row=i, column=3).value) +' '+ str(s.cell(row=i, column=4).value) + '\\n'\n\n if textt != day+'\\n\\n':\n bot.send_message(message.chat.id,textt)\n\n\n@bot.message_handler(commands=['dayShedule'])\ndef wow(message):\n sortLines(5)\n f.save(\"sample.xlsx\")\n\n markup = types.ReplyKeyboardMarkup()\n markup.add('Понедельник', 'Вторник', 'Среда', 'Четверг', 'Пятница', 'Суббота', 'Воскресение', 'NEXT', 'EXIT')\n msg = bot.send_message(message.chat.id, 'Нажми на день недели',reply_markup=markup)\n\n bot.register_next_step_handler(msg, roflkek)\n\n\ndef roflkek(Day):\n\n if Day.text=='EXIT':\n msg = bot.send_message(Day.chat.id, ':)')\n bot.register_next_step_handler(msg, startr)\n else:\n\n bot.send_message(Day.chat.id,'Твоё расписание на этот день:')\n k=True\n textt=''\n for i in range(1,100):\n if s.cell(row=i, column=1).value==Day.chat.id and s.cell(row=i, column=2).value==Day.text:\n textt+= str(s.cell(row=i, column=3).value) + str(s.cell(row=i, column=4).value) + '\\n\\n'\n k=False\n\n if k:\n msg = bot.send_message(Day.chat.id, 'Попробуй другой день, этот пуст')\n\n bot.register_next_step_handler(msg, roflkek)\n else:\n msg = bot.send_message(Day.chat.id, textt)\n bot.register_next_step_handler(msg, roflkek)\n\n\n\n\n\n@bot.message_handler(commands=['dayErase'])\ndef wow(message):\n if message.text == 'EXIT':\n msg = bot.send_message(message.chat.id, ':)')\n bot.register_next_step_handler(msg, startr)\n else:\n for i in range(1, 100):\n if s.cell(row=i, column=1).value == message.chat.id and s.cell(row=i, column=2).value == message.text:\n for j in range(1,5):\n s.cell(row=i, column=j).value=0\n s.cell(row=i, column=j).value=0\n f.save(\"sample.xlsx\")\n\n\n@bot.message_handler(commands=['time'])\ndef wow(message):\n # mytime=strftime('%Y-%m-%d %H:%M:%S',gmtime())\n mytime = strftime('%H:%M', gmtime())\n\n bot.send_message(message.chat.id, mytime)\n\n\ndef rofl(Day):\n if (Day.text != 'EXIT'):\n stroka = str(Day.chat.id) + '-' + Day.text\n\n msg = bot.send_message(Day.chat.id, 'Следующий день недели\\n or exit')\n\n bot.register_next_step_handler(msg, rofl)\n\n\n@bot.message_handler(commands=['contacts'])\ndef wow(message):\n markup = types.InlineKeyboardMarkup()\n url_button1 = types.InlineKeyboardButton(\"vk\", \"https://vk.com/theholyhell\")\n url_button2 = types.InlineKeyboardButton(\"telegram\", \"https://t.me/joinchat/E1dQ3w2aIDzvmfW1kluMMg\")\n url_button3 = types.InlineKeyboardButton(\"vk danya\", \"https://vk.com/s1ngle_tv\")\n\n markup.add(url_button1, url_button2, url_button3)\n # bot.send_message(message.chat.id, message.text[10:])\n bot.send_message(message.chat.id, \"Привет! Мои контакты:.\", reply_markup=markup)\n\n\n@bot.message_handler(commands=['start'])\ndef startr(message):\n\n tempp = str(message.chat.id)\n print(tempp)\n tempp = tempp.replace(' ', '')\n\n # cur.execute(\"INSERT INTO d8qr5o45ha7ifr VALUES (%s)\", (42,)) # correct\n markup = types.ReplyKeyboardMarkup()\n markup.add('/contacts', '/time', '/start', '/allShedule', '/myNewShedule', '/dayShedule', '/dayErase',)\n # bot.send_message(message.chat.id, message.text[10:])\n bot.send_message(message.chat.id, \"В панель добавлена перечень команд.\", reply_markup=markup)\n\n\n\n\n\n@bot.message_handler(func=lambda message: True, content_types=['text'])\ndef echo_msg(message):\n if message.text.find('мразь') != -1:\n bot.send_message(message.chat.id, 'Cледи за словами!')\n else:\n bot.send_message(message.chat.id, message.text)\n\n\n# We can also close the connection if we are done with it.\n# Just be sure any changes have been committed or they will be lost.\n\n\nif __name__ == '__main__':\n bot.infinity_polling(True)\n","sub_path":"bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":9036,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"66"}