\n '''\n# --------------------------------------------------\ndef removeEmoji(string):\n emoji_pattern = re.compile(\n u\"(\\ud83d[\\ude00-\\ude4f])|\" # emoticons\n u\"(\\ud83c[\\udf00-\\uffff])|\" # symbols & pictographs (1 of 2)\n u\"(\\ud83d[\\u0000-\\uddff])|\" # symbols & pictographs (2 of 2)\n u\"(\\ud83d[\\ude80-\\udeff])|\" # transport & map symbols\n u\"(\\ud83c[\\udde0-\\uddff])\" # flags (iOS)\n \"+\", flags=re.UNICODE)\n return emoji_pattern.sub(r'', string)\n# --------------------------------------------------\n","sub_path":"searchScraper.py","file_name":"searchScraper.py","file_ext":"py","file_size_in_byte":3716,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"500207640","text":"from odoo import models, fields, api, _\nfrom odoo.exceptions import UserError\nimport datetime\n\nclass FmpiVqirPd(models.TransientModel):\n _name = \"fmpi.vqir.pd\"\n _description = \"FMPI - VQIR Paid Notes\"\n\n name = fields.Text(string=\"Paid Notes\", required=True)\n\n @api.multi\n def action_pd(self):\n act_close = {'type': 'ir.actions.act_window_close'}\n ids = self._context.get('active_ids')\n if ids is None:\n return act_close\n assert len(ids) == 1, \"Only 1 VQIR is expected\"\n fmpi_vqir_obj = self.env['fmpi.vqir'].browse(ids)\n if fmpi_vqir_obj.vqir_state in ['approved','preclaimed']:\n vqir_state_logs = \"Document:\" + fmpi_vqir_obj.name + \"\\n\" + \\\n \"Set as Paid by: \" + self.env.user.name + \"\\n\" + \\\n \"Set as Paid at: \" + datetime.datetime.now().strftime(\"%m/%d/%Y\") + \"\\n\" + \\\n \"Paid notes: \" + (self.name or '') + \"\\n\" + \\\n \"--------------------------------------------------\\n\"\n fmpi_vqir_obj.write({'vqir_state': 'paid',\n 'vqir_state_logs': vqir_state_logs + (fmpi_vqir_obj.vqir_state_logs or '')})\n fmpi_vqir_obj.action_pd_api()\n else:\n raise UserError(_(\"You cannot pay this VQIR in this state\"))\n return act_close\n\nFmpiVqirPd()","sub_path":"one/wizards/fmpi_vqir_pd.py","file_name":"fmpi_vqir_pd.py","file_ext":"py","file_size_in_byte":1329,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"1634035","text":"# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n# implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport os\nfrom pifpaf import drivers\n\n\nclass KafkaDriver(drivers.Driver):\n DEFAULT_PORT = \"9092\"\n DEFAULT_PATH = [\"/opt/kafka/bin\"]\n\n def __init__(self, port=DEFAULT_PORT, **kwargs):\n\n super(KafkaDriver, self).__init__(**kwargs)\n self.port = port\n def _setUp(self):\n\n super(KafkaDriver, self)._setUp()\n cfgfile = os.path.join(self.tempdir, \"server.properties\")\n with open(cfgfile, \"w\") as f:\n f.write(\"\"\"broker.id=0\nhost.name=127.0.0.1\nadvertised.host.name=127.0.0.1\nlisteners=PLAINTEXT://localhost:%s\nnum.network.threads=3\nnum.io.threads=8\nsocket.send.buffer.bytes=102400\nsocket.receive.buffer.bytes=102400\nsocket.request.max.bytes=104857600\nlog.dirs=%s-logs\nnum.partitions=1\nnum.recovery.threads.per.data.dir=1\nlog.retention.hours=168\nlog.segment.bytes=1073741824\nlog.retention.check.interval.ms=300000\nzookeeper.connect=localhost:2181\nzookeeper.connection.timeout.ms=6000\"\"\" % (self.port, self.tempdir))\n\n os.mkdir(\"%s-logs\" % self.tempdir)\n\n c, _ = self._exec(['kafka-server-start.sh',\n cfgfile,\n '--override', 'port=%s' % self.port],\n wait_for_line='started',\n path=KafkaDriver.DEFAULT_PATH)\n\n self.addCleanup(self._exec, ['kafka-server-stop.sh'],\n path=KafkaDriver.DEFAULT_PATH)\n \n self.putenv(\"KAFKA_PORT\", self.port)\n self.putenv(\"KAFKA_URL\", \"PLAINTEXT://localhost:%s\" % self.port)\n","sub_path":"pifpaf/drivers/kafka.py","file_name":"kafka.py","file_ext":"py","file_size_in_byte":2062,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"218322548","text":"from builtins import object\nfrom bi.common.exception import BIException\n\n\nclass Validator(object):\n \"\"\"\n Utilitiy class for common validations\n \"\"\"\n\n @staticmethod\n def assert_non_negative_parameter(param_type, param_name, param_value, raise_exception=True):\n if type(param_value) != param_type:\n if raise_exception:\n raise BIException.parameter_invalid_type(param_name, param_type, type(param_value))\n else:\n return False\n\n if param_value < 0:\n if raise_exception:\n raise BIException.parameter_has_negative_value(param_name, param_value)\n else:\n return False\n\n return True\n","sub_path":"bi/validator.py","file_name":"validator.py","file_ext":"py","file_size_in_byte":714,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"446539684","text":"from django.db.utils import IntegrityError\nfrom django.test import TestCase\n\nfrom cashflow.models import Item, City, Place, Tag, Wallet\n\n\nclass ItemTestCase(TestCase):\n def create_item(self):\n item = Item.objects.create(place=self.place, wallet=self.wallet)\n for tag in self.tags:\n item.tags.add(tag)\n item.save()\n return item\n\n def setUp(self):\n self.city = City.objects.create(name='San Francisco')\n self.place = Place.objects.create(name='Waffle House', city=self.city)\n self.tags = Tag.objects.bulk_create([\n Tag(name='waffles'),\n Tag(name='food'),\n Tag(name='market'),\n ])\n self.wallet = Wallet.objects.create(name='Bank of America')\n self.item = self.create_item()\n\n def test_item_creation(self):\n \"\"\"\n Tests if items are created correctly.\n \"\"\"\n item = self.create_item()\n self.assertEqual(Item.objects.count(), 2)\n\n def test_item_delete(self):\n \"\"\"\n Tests if items can be removed correctly.\n \"\"\"\n item = self.create_item()\n self.assertEqual(Item.objects.count(), 2)\n item.delete()\n self.assertEqual(Item.objects.count(), 1)\n\n def test_item_edit(self):\n \"\"\"\n Tests if items can be edited correctly.\n \"\"\"\n self.item.value = 120.45\n self.item.save()\n self.assertEqual(float(Item.objects.get(pk=self.item.id).value), 120.45)\n\n def test_city_remove(self):\n \"\"\"\n Tests if city delete will remove associated items too.\n \"\"\"\n self.city.delete()\n self.assertEqual(Item.objects.count(), 0)\n\n def test_place_remove(self):\n \"\"\"\n Tests if place delete will remove associated items too.\n \"\"\"\n self.place.delete()\n self.assertEqual(Item.objects.count(), 0)\n\n def test_wallet_remove(self):\n \"\"\"\n Tests if wallet delete will remove associated items too.\n \"\"\"\n self.wallet.delete()\n self.assertEqual(Item.objects.count(), 0)\n","sub_path":"cashflow/tests/models/test_item.py","file_name":"test_item.py","file_ext":"py","file_size_in_byte":2084,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"68947134","text":"#텍스트 파일을 한줄씩 읽고 출력하기\n#readline()은 텍스트 파일을 한 줄 씩 읽는다.\nf = open('test.txt', 'r')\nline_num = 1\nline = f.readline()\n\nwhile line: #파일의 끝에 읽을 내용이 더 이상 없으면 readline()은 빈 문자열을 리턴\n print('%d %s'%(line_num, line), end ='')\n line = f.readline()\n line_num += 1\nf.close()\n","sub_path":"138.text_method_readline/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":372,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"124009152","text":"import urllib2\nimport urllib\nimport os\nfrom bs4 import BeautifulSoup\n\ngirl_dir = 'F:\\girl'\nos.chdir(girl_dir)\n\nurl = 'https://www.4493.com/gaoqingmeinv/'\nuser_agent = 'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.6) Gecko/20091201 Firefox/3.5.6'\nvalues = {'username' : 'cqc', 'password' : 'XXXX' }\nheaders = {'User-Agent' : user_agent}\ndata = urllib.urlencode(values)\nrequest = urllib2.Request(url,data,headers)\nresponse = urllib2.urlopen(request)\nhtmlreader = response.read()\nsoup = BeautifulSoup(htmlreader, 'html.parser')\n\nalist = soup.find(\"div\",class_=\"piclist\").find_all('a')\nweblink = []\nfor link in alist:\n glink = link.get('href','default')\n if glink == 'default':\n break\n else:\n weblink.append('https://www.4493.com/' + glink[1:21])\n\n\nfor ttlink in weblink:\n i = 1\n while (i < 10):\n url = ttlink + str(i) + \".htm\"\n user_agent = 'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.6) Gecko/20091201 Firefox/3.5.6'\n values = {'username' : 'cqc', 'password' : 'XXXX' }\n headers = {'User-Agent' : user_agent}\n data = urllib.urlencode(values)\n request = urllib2.Request(url,data,headers)\n response = urllib2.urlopen(request)\n htmlreader = response.read()\n soup = BeautifulSoup(htmlreader, 'html.parser')\n img = soup.find(\"div\",class_=\"picsbox picsboxcenter\").find('img')\n src = img['src']\n name = 'kogirl' + ttlink[-7:-1] + '_' + str(i)\n with open(name + '.jpg', 'ab') as img_object:\n img_content = urllib2.urlopen(src).read()\n img_object.write(img_content)\n img_object.flush()\n i = i + 1\n","sub_path":"pachong.py","file_name":"pachong.py","file_ext":"py","file_size_in_byte":1675,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"515567265","text":"from django.http import HttpResponseRedirect\n\nfrom .models import ClientUser\n\n\ndef creator_required(f):\n \"\"\"restrict manipulation operations on a user to the administrator who created them\"\"\"\n def check(request, userid, *args, **kwargs):\n try:\n admin = ClientUser.objects.filter(id=userid).values()[0]['admin_id']\n except:\n admin = None\n if request.user.id != admin:\n return HttpResponseRedirect('/')\n\n return f(request, userid, *args, **kwargs)\n\n return check\n","sub_path":"administrator/decorators.py","file_name":"decorators.py","file_ext":"py","file_size_in_byte":531,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"383639503","text":"import re\n\ntimeFile = open(\"MilitaryTime.txt\",\"r\")\nspeciesFile = open(\"Species.txt\",\"r\")\nSSNFile = open(\"SSN.txt\",\"r\")\n\n\ntime = re.compile(\"(12:\\d\\d|13:\\d\\d|14:\\d\\d|15:\\d\\d|16:\\d\\d|17:\\d\\d|18:\\d\\d|19:\\d\\d|20:\\d\\d|21:\\d\\d|22:\\d\\d|23:\\d\\d|24:00)\")\nspecies = re.compile(\"[A-Z]\\.\\s\\w+\")\nSSN = re.compile(\"\\d\\d\\d-\\d\\d-\\d\\d\\d\")\n\nprint(\"Matches in MilitaryTime.txt\")\nfor ln in timeFile:\n ln.strip()\n if re.search(time, ln) is not None:\n print(ln)\n \nprint(\"Matches in Species.txt\")\nfor ln in speciesFile:\n ln.strip()\n if re.search(species, ln) is not None:\n print(ln)\n \nprint(\"Matches in SSN.txt\")\nfor ln in SSNFile:\n ln.strip()\n if re.search(SSN, ln) is not None:\n print(ln)\n \ntimeFile.close()\nspeciesFile.close()\nSSNFile.close()\n","sub_path":"pythonCode2.py","file_name":"pythonCode2.py","file_ext":"py","file_size_in_byte":783,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"235725881","text":"'''below code are my personal practise from below link:\n http://www.blog.pythonlibrary.org/2012/06/07/python-101-how-to-download-a-file/\nwritten under python 3.4\n'''\nimport urllib.request\nimport urllib.parse\nimport urllib.error\n\nurl = 'http://www.blog.pythonlibrary.org/wp-content/uploads/2012/06/wxDbViewer.zip'\n\nprint('downloading with urllib')\n\nf = urllib.request.urlopen(url)\ndata = f.read()\nwith open('d:/filepulled.zip', 'wb') as code:\n code.write(data)\nprint('Bingo')\n","sub_path":"py/PullFile.py","file_name":"PullFile.py","file_ext":"py","file_size_in_byte":481,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"113958258","text":"import socket\n#import os\n\nclass IPC_client:\n def __init__(self, server_address, buffer_size=16384): #32768\n self.buffer_size = buffer_size\n self.server_address = server_address\n print('socket connecting to %s' % self.server_address)\n self.connect()\n \n def __del__(self):\n self.sock.close()\n #os.unlink(file)\n print('socket closed: %s'%self.server_address)\n\n def connect(self):\n # Create a UDS socket\n self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)\n self.sock.connect(self.server_address)\n\n def reconnect(self):\n print('socket reconnect to %s' % self.server_address)\n self.sock.close()\n self.connect()\n \n def _read(self, buffer_size):\n data = self.sock.recv(buffer_size)\n #print('%i,%.2f'%(len(data), len(data)/buffer_size))\n return data, len(data)==buffer_size\n\n def send(self, message):\n data = message.encode()\n ret = None\n try:\n ret = self.sock.sendall(data)\n except socket.error as e:\n print('socket error: ', e)\n self.reconnect()\n ret = self.sock.sendall(data)\n except IOError as e:\n if e.errno == errno.EPIPE:\n raise Exception('IOError (EPIPE): broken pipe')\n else:\n raise Exception('IOError other: ', e)\n return ret==None\n \n def receive(self):\n data, overflow = self._read(self.buffer_size)\n while(overflow):\n msg, overflow = self._read(self.buffer_size)\n data += msg\n \n #print('received %i bytes: \"%s...\"' % (len(data),data[:10]))\n return data.decode()\n \n def query(self,message):\n if not self.send(message):\n return None\n return self.receive()\n\n","sub_path":"PyModules/ipc_client.py","file_name":"ipc_client.py","file_ext":"py","file_size_in_byte":1850,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"521677293","text":"from scipy.optimize import minimize\r\nimport math\r\nimport numpy as np\r\n\r\ndef get_measurements(data: list) -> dict:\r\n import scipy.stats\r\n import numpy as np\r\n measurements = {}\r\n \r\n miu_3 = scipy.stats.moment(data, 3)\r\n miu_4 = scipy.stats.moment(data, 4)\r\n mean = np.mean(data)\r\n variance = np.var(data, ddof=1)\r\n skewness = miu_3 / pow(np.std(data, ddof=1),3)\r\n kurtosis = miu_4 / pow(np.std(data, ddof=1),4)\r\n median = np.median(data)\r\n mode = scipy.stats.mode(data)[0][0]\r\n \r\n measurements.mean = mean\r\n measurements.variance = variance\r\n measurements.skewness = skewness\r\n measurements.kurtosis = kurtosis\r\n measurements.data = data\r\n measurements.median = median\r\n measurements.mode = mode\r\n \r\n return measurements\r\n\r\ndef getData(direction):\r\n file = open(direction,'r')\r\n data = [float(x.replace(\",\",\".\")) for x in file.read().splitlines()]\r\n return data\r\n\r\npath = \"../data/data_cauchy.txt\"\r\ndata = getData(path) \r\nmeasurements = MEASUREMENTS(data)\r\n\r\nx0, gamma = 50, 100\r\n\r\ndef objective(x, data):\r\n x0, gamma = x\r\n return -sum([math.log(1/(math.pi * gamma * (1 + ((d - x0)/gamma)**2))) for d in measurements.data])\r\n\r\nbnds = [(-np.inf, np.inf),(0,np.inf)]\r\nsol = minimize(objective, [46.17,108.45], args = (measurements.data), method=\"SLSQP\", bounds = bnds)\r\nprint(sol)","sub_path":"continious/utilities/estimaciones/cauchy_estimaciones.py","file_name":"cauchy_estimaciones.py","file_ext":"py","file_size_in_byte":1360,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"539970510","text":"from keras import layers, models, optimizers\nfrom keras import backend as K\n\n\nclass Critic:\n \"\"\"Critic (Value) Model.\"\"\"\n\n def __init__(self, state_size, action_size):\n \"\"\"Initialize a Critic instance.\"\"\"\n self.state_size = state_size\n self.action_size = action_size\n # build the model\n self.build_model()\n\n def build_model(self):\n \"\"\"Build a Critic (Value) model that maps (state, action)> Q_values.\"\"\"\n # Input layers\n states = layers.Input(shape=(self.state_size,), name=\"states\")\n actions = layers.Input(shape=(self.action_size,), name=\"actions\")\n\n # Add some hidden layers to state pathway\n net_states = layers.Dense(units=32, activation=\"relu\")(states)\n net_states = layers.Dense(units=64, activation=\"relu\")(net_states)\n\n # Add some hidden layers to action pathway\n net_actions = layers.Dense(units=32, activation=\"relu\")(actions)\n net_actions = layers.Dense(units=64, activation=\"relu\")(net_actions)\n\n # Combine both pathways\n net = layers.Add()([net_states, net_actions])\n net = layers.Activation('relu')(net)\n\n Q_values = layers.Dense(units=1, name='q_values')(net)\n\n self.model = models.Model(inputs=[states, actions], outputs=Q_values)\n\n optimizer = optimizers.Adam()\n self.model.compile(optimizer=optimizer, loss='mse')\n\n # Compute action gradients (derivative of Q values w.r.t. to actions)\n action_gradients = K.gradients(Q_values, actions)\n\n # Define an additional function to fetch action gradients (to be used\n # by actor model)\n self.get_action_gradients = K.function(\n inputs=[*self.model.inputs, K.learning_phase()],\n outputs=action_gradients)\n","sub_path":"quadcopter_simulation/agents/ddpg_critic.py","file_name":"ddpg_critic.py","file_ext":"py","file_size_in_byte":1785,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"594767115","text":"# -*- encoding: utf-8 -*-\n##############################################################################\n#\n# OpenERP, Open Source Management Solution\n# Copyright (C) 2004-2009 Tiny SPRL (). All Rights Reserved\n# $Id$\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program. If not, see .\n#\n##############################################################################\n\n\nfrom mx import DateTime\nimport time\nimport netsvc\nfrom osv import fields, osv\nfrom tools import config\nfrom tools.translate import _\nimport tools\n\n# ----------------------------------------------------\n# Move\n# ----------------------------------------------------\n\n#\n# Fields:\n# location_dest_id is only used for predicting futur stocks\n#\n\nclass stock_move(osv.osv):\n def init(self,cr):\n cr.execute(\"Update wkf set on_create=False where name='stock.picking.basic'\")\n \n def _getSSCC(self, cr, uid, context={}):\n cr.execute('select id from stock_tracking where create_uid=%s order by id desc limit 1', (uid,))\n res = cr.fetchone()\n return (res and res[0]) or False\n _name = \"stock.move\"\n _description = \"Stock Move\"\n _inherit = 'stock.move'\n \n def _purchase_order_line_change(self, cr, uid, ids, order_line_id): \n if not order_line_id:\n return {'value': {'move_dest_id':False,\n 'location_id': False,\n 'location_dest_id':False,\n 'product_uom':False,\n 'product_qty':0.0,\n 'product_uos':False,\n 'product_uos_qty': 0.0,\n 'product_id':False,\n 'name':False}}\n \n for pol in self.pool.get('purchase.order.line').browse(cr,uid,[order_line_id]):\n if pol.product_id: \n product_id = pol.product_id.id\n received_qty = 0\n current_id = False\n if ids:\n current_id = ids[0]\n cr.execute(\"Select sum(product_qty) as received_qty from stock_move where purchase_line_id=%d and id<>%d group by purchase_line_id\" % (pol.id,current_id))\n qty_obj=cr.fetchone()\n if qty_obj:\n received_qty = qty_obj[0] \n prod_uom_po = pol.product_uom.id\n qty = pol.plan_qty - received_qty\n movename = 'Receive: %s' % pol.name\n loc_id = pol.order_id.partner_id.property_stock_supplier.id\n dest = pol.order_id.location_id.id\n result={'value':{'name':movename,\n 'product_id': product_id,\n 'product_qty': qty,\n 'product_uos_qty': qty,\n 'product_uom': prod_uom_po,\n 'product_uos': prod_uom_po,\n #'date_planned': order.delivery_date,\n 'location_id': loc_id,\n 'location_dest_id': dest}}\n return result\n \n def name_get(self, cr, uid, ids, context={}):\n res = []\n for line in self.browse(cr, uid, ids, context):\n res.append((line.id, (line.product_id.code or '/')+': '+line.location_id.name+' > '+line.location_dest_id.name))\n return res\n\n def _check_tracking(self, cr, uid, ids):\n for move in self.browse(cr, uid, ids):\n if not move.prodlot_id and \\\n (move.state == 'done' and \\\n ( \\\n (move.product_id.track_production and move.location_id.usage=='production') or \\\n (move.product_id.track_production and move.location_dest_id.usage=='production') or \\\n (move.product_id.track_incoming and move.location_id.usage=='supplier') or \\\n (move.product_id.track_outgoing and move.location_dest_id.usage=='customer') \\\n )):\n return False\n return True\n\n def _check_product_lot(self, cr, uid, ids):\n for move in self.browse(cr, uid, ids):\n if move.prodlot_id and (move.prodlot_id.product_id.id != move.product_id.id):\n return False\n return True\n\n _columns = {\n 'name': fields.char('Name', size=64,select=True),\n 'priority': fields.selection([('0', 'Not urgent'), ('1', 'Urgent')], 'Priority'),\n\n 'date': fields.datetime('Date Created'),\n 'date_planned': fields.datetime('Date', help=\"Scheduled date for the movement of the products or real date if the move is done.\"),\n\n 'product_id': fields.many2one('product.product', 'Product', required=True, select=True),\n\n 'product_qty': fields.float('Quantity', required=True),\n 'product_uom': fields.many2one('product.uom', 'Product UOM'),\n 'product_uos_qty': fields.float('Quantity (UOS)'),\n 'product_uos': fields.many2one('product.uom', 'Product UOS'),\n 'product_packaging': fields.many2one('product.packaging', 'Packaging'),\n\n 'location_id': fields.many2one('stock.location', 'Source Location',select=True),\n 'location_dest_id': fields.many2one('stock.location', 'Dest. Location', select=True),\n 'address_id': fields.many2one('res.partner.address', 'Dest. Address'),\n\n 'prodlot_id': fields.many2one('stock.production.lot', 'Production Lot', help=\"Production lot is used to put a serial number on the production\"),\n 'tracking_id': fields.many2one('stock.tracking', 'Tracking Lot', select=True, help=\"Tracking lot is the code that will be put on the logistical unit/pallet\"),\n# 'lot_id': fields.many2one('stock.lot', 'Consumer lot', select=True, readonly=True),\n\n 'auto_validate': fields.boolean('Auto Validate'),\n\n 'move_dest_id': fields.many2one('stock.move', 'Dest. Move'),\n 'move_history_ids': fields.many2many('stock.move', 'stock_move_history_ids', 'parent_id', 'child_id', 'Move History'),\n 'move_history_ids2': fields.many2many('stock.move', 'stock_move_history_ids', 'child_id', 'parent_id', 'Move History'),\n 'picking_id': fields.many2one('stock.picking', 'Packing List', select=True,ondelete='cascade'),\n\n 'note': fields.text('Notes'),\n\n 'state': fields.selection([('draft', 'Draft'), ('waiting', 'Waiting'), ('confirmed', 'Confirmed'), ('assigned', 'Available'), ('done', 'Done'), ('cancel', 'Canceled')], 'Status', readonly=True, select=True),\n 'price_unit': fields.float('Unit Price',\n digits=(16, int(config['price_accuracy']))),\n }\n _constraints = [\n (_check_tracking,\n 'You must assign a production lot for this product',\n ['prodlot_id']),\n (_check_product_lot,\n 'You try to assign a lot which is not from the same product',\n ['prodlot_id'])]\n\n def _default_location_destination(self, cr, uid, context={}):\n if context.get('move_line', []):\n if context['move_line'][0]:\n if isinstance(context['move_line'][0], (tuple, list)):\n return context['move_line'][0][2] and context['move_line'][0][2]['location_dest_id'] or False\n else:\n move_list = self.pool.get('stock.move').read(cr, uid, context['move_line'][0], ['location_dest_id'])\n return move_list and move_list['location_dest_id'][0] or False\n if context.get('address_out_id', False):\n return self.pool.get('res.partner.address').browse(cr, uid, context['address_out_id'], context).partner_id.property_stock_customer.id\n return False\n\n def _default_location_source(self, cr, uid, context={}):\n if context.get('move_line', []):\n try:\n return context['move_line'][0][2]['location_id']\n except:\n pass\n if context.get('address_in_id', False):\n return self.pool.get('res.partner.address').browse(cr, uid, context['address_in_id'], context).partner_id.property_stock_supplier.id\n return False\n\n _defaults = {\n 'location_id': _default_location_source,\n 'location_dest_id': _default_location_destination,\n 'state': lambda *a: 'draft',\n 'priority': lambda *a: '1',\n 'product_qty': lambda *a: 1.0,\n 'date_planned': lambda *a: time.strftime('%Y-%m-%d %H:%M:%S'),\n 'date': lambda *a: time.strftime('%Y-%m-%d %H:%M:%S'),\n }\n\n def _auto_init(self, cursor, context):\n res = super(stock_move, self)._auto_init(cursor, context)\n cursor.execute('SELECT indexname \\\n FROM pg_indexes \\\n WHERE indexname = \\'stock_move_location_id_location_dest_id_product_id_state\\'')\n if not cursor.fetchone():\n cursor.execute('CREATE INDEX stock_move_location_id_location_dest_id_product_id_state \\\n ON stock_move (location_id, location_dest_id, product_id, state)')\n cursor.commit()\n return res\n\n def onchange_lot_id(self, cr, uid, ids, prodlot_id=False, product_qty=False, loc_id=False, context=None):\n if not prodlot_id or not loc_id:\n return {}\n ctx = context and context.copy() or {}\n ctx['location_id'] = loc_id\n prodlot = self.pool.get('stock.production.lot').browse(cr, uid, prodlot_id, ctx)\n location = self.pool.get('stock.location').browse(cr, uid, loc_id)\n warning = {}\n if (location.usage == 'internal') and (product_qty > (prodlot.stock_available or 0.0)):\n warning = {\n 'title': 'Bad Lot Assignation !',\n 'message': 'You are moving %.2f products but only %.2f available in this lot.' % (product_qty, prodlot.stock_available or 0.0)\n }\n return {'warning': warning}\n\n def onchange_product_id(self, cr, uid, ids, prod_id=False, loc_id=False, loc_dest_id=False):\n if not prod_id:\n return {}\n product = self.pool.get('product.product').browse(cr, uid, [prod_id])[0]\n result = {\n 'name': product.name,\n 'product_uom': product.uom_id.id,\n }\n if loc_id:\n result['location_id'] = loc_id\n if loc_dest_id:\n result['location_dest_id'] = loc_dest_id\n return {'value': result}\n\n def _chain_compute(self, cr, uid, moves, context={}):\n result = {}\n for m in moves:\n dest = self.pool.get('stock.location').chained_location_get(\n cr,\n uid,\n m.location_dest_id,\n m.picking_id and m.picking_id.address_id and m.picking_id.address_id.partner_id,\n m.product_id,\n context\n )\n if dest:\n if dest[1] == 'transparent':\n self.write(cr, uid, [m.id], {\n 'date_planned': (DateTime.strptime(m.date_planned, '%Y-%m-%d %H:%M:%S') + \\\n DateTime.RelativeDateTime(days=dest[2] or 0)).strftime('%Y-%m-%d'),\n 'location_dest_id': dest[0].id})\n else:\n result.setdefault(m.picking_id, [])\n result[m.picking_id].append( (m, dest) )\n return result\n\n def action_confirm(self, cr, uid, ids, context={}):\n# ids = map(lambda m: m.id, moves)\n moves = self.browse(cr, uid, ids)\n self.write(cr, uid, ids, {'state': 'confirmed'})\n i = 0\n\n def create_chained_picking(self, cr, uid, moves, context):\n new_moves = []\n for picking, todo in self._chain_compute(cr, uid, moves, context).items():\n ptype = self.pool.get('stock.location').picking_type_get(cr, uid, todo[0][0].location_dest_id, todo[0][1][0])\n pickid = self.pool.get('stock.picking').create(cr, uid, {\n 'name': picking.name,\n 'origin': str(picking.origin or ''),\n 'type': ptype,\n 'note': picking.note,\n 'move_type': picking.move_type,\n 'auto_picking': todo[0][1][1] == 'auto',\n 'address_id': picking.address_id.id,\n 'invoice_state': 'none'\n })\n for move, (loc, auto, delay) in todo:\n # Is it smart to copy ? May be it's better to recreate ?\n new_id = self.pool.get('stock.move').copy(cr, uid, move.id, {\n 'location_id': move.location_dest_id.id,\n 'location_dest_id': loc.id,\n 'date_moved': time.strftime('%Y-%m-%d'),\n 'picking_id': pickid,\n 'state': 'waiting',\n 'move_history_ids': [],\n 'date_planned': (DateTime.strptime(move.date_planned, '%Y-%m-%d %H:%M:%S') + DateTime.RelativeDateTime(days=delay or 0)).strftime('%Y-%m-%d'),\n 'move_history_ids2': []}\n )\n self.pool.get('stock.move').write(cr, uid, [move.id], {\n 'move_dest_id': new_id,\n 'move_history_ids': [(4, new_id)]\n })\n new_moves.append(self.browse(cr, uid, [new_id])[0])\n wf_service = netsvc.LocalService(\"workflow\")\n wf_service.trg_validate(uid, 'stock.picking', pickid, 'button_confirm', cr)\n if new_moves:\n create_chained_picking(self, cr, uid, new_moves, context)\n create_chained_picking(self, cr, uid, moves, context)\n return []\n\n def action_assign(self, cr, uid, ids, *args):\n todo = []\n for move in self.browse(cr, uid, ids):\n if move.state in ('confirmed', 'waiting'):\n todo.append(move.id)\n res = self.check_assign(cr, uid, todo)\n return res\n\n def force_assign(self, cr, uid, ids, context={}):\n self.write(cr, uid, ids, {'state': 'assigned'})\n return True\n\n def cancel_assign(self, cr, uid, ids, context={}):\n self.write(cr, uid, ids, {'state': 'confirmed'})\n return True\n\n #\n # Duplicate stock.move\n #\n def check_assign(self, cr, uid, ids, context={}):\n done = []\n count = 0\n pickings = {}\n for move in self.browse(cr, uid, ids):\n if move.product_id.type == 'consu':\n if move.state in ('confirmed', 'waiting'):\n done.append(move.id)\n pickings[move.picking_id.id] = 1\n continue\n if move.state in ('confirmed', 'waiting'):\n res = self.pool.get('stock.location')._product_reserve(cr, uid, [move.location_id.id], move.product_id.id, move.product_qty, {'uom': move.product_uom.id})\n if res:\n #_product_available_test depends on the next status for correct functioning\n #the test does not work correctly if the same product occurs multiple times\n #in the same order. This is e.g. the case when using the button 'split in two' of \n #the stock outgoing form \n self.write(cr, uid, move.id, {'state':'assigned'})\n done.append(move.id)\n pickings[move.picking_id.id] = 1\n r = res.pop(0)\n cr.execute('update stock_move set location_id=%s, product_qty=%s where id=%s', (r[1], r[0], move.id))\n\n while res:\n r = res.pop(0)\n move_id = self.copy(cr, uid, move.id, {'product_qty': r[0], 'location_id': r[1]})\n done.append(move_id)\n #cr.execute('insert into stock_move_history_ids values (%s,%s)', (move.id,move_id))\n if done:\n count += len(done)\n self.write(cr, uid, done, {'state': 'assigned'})\n\n if count:\n for pick_id in pickings:\n wf_service = netsvc.LocalService(\"workflow\")\n wf_service.trg_write(uid, 'stock.picking', pick_id, cr)\n return count\n\n #\n # Cancel move => cancel others move and pickings\n #\n def action_cancel(self, cr, uid, ids, context={}):\n if not len(ids):\n return True\n pickings = {}\n for move in self.browse(cr, uid, ids):\n if move.state in ('confirmed', 'waiting', 'assigned', 'draft'):\n if move.picking_id:\n pickings[move.picking_id.id] = True\n if move.move_dest_id and move.move_dest_id.state == 'waiting':\n self.write(cr, uid, [move.move_dest_id.id], {'state': 'assigned'})\n if move.move_dest_id.picking_id:\n wf_service = netsvc.LocalService(\"workflow\")\n wf_service.trg_write(uid, 'stock.picking', move.move_dest_id.picking_id.id, cr)\n self.write(cr, uid, ids, {'state': 'cancel', 'move_dest_id': False})\n\n for pick in self.pool.get('stock.picking').browse(cr, uid, pickings.keys()):\n if all(move.state == 'cancel' for move in pick.move_lines):\n self.pool.get('stock.picking').write(cr, uid, [pick.id], {'state': 'cancel'})\n\n wf_service = netsvc.LocalService(\"workflow\")\n for id in ids:\n wf_service.trg_trigger(uid, 'stock.move', id, cr)\n #self.action_cancel(cr,uid, ids2, context)\n return True\n\n def action_done(self, cr, uid, ids, context=None):\n track_flag = False\n for move in self.browse(cr, uid, ids):\n if move.move_dest_id.id and (move.state != 'done'):\n cr.execute('insert into stock_move_history_ids (parent_id,child_id) values (%s,%s)', (move.id, move.move_dest_id.id))\n if move.move_dest_id.state in ('waiting', 'confirmed'):\n self.write(cr, uid, [move.move_dest_id.id], {'state': 'assigned'})\n if move.move_dest_id.picking_id:\n wf_service = netsvc.LocalService(\"workflow\")\n wf_service.trg_write(uid, 'stock.picking', move.move_dest_id.picking_id.id, cr)\n else:\n pass\n # self.action_done(cr, uid, [move.move_dest_id.id])\n if move.move_dest_id.auto_validate:\n self.action_done(cr, uid, [move.move_dest_id.id], context=context)\n\n #\n # Accounting Entries\n #\n acc_src = None\n acc_dest = None\n if move.location_id.account_id:\n acc_src = move.location_id.account_id.id\n if move.location_dest_id.account_id:\n acc_dest = move.location_dest_id.account_id.id\n if acc_src or acc_dest:\n test = [('product.product', move.product_id.id)]\n if move.product_id.categ_id:\n test.append( ('product.category', move.product_id.categ_id.id) )\n if not acc_src:\n acc_src = move.product_id.product_tmpl_id.\\\n property_stock_account_input.id\n if not acc_src:\n acc_src = move.product_id.categ_id.\\\n property_stock_account_input_categ.id\n if not acc_src:\n raise osv.except_osv(_('Error!'),\n _('There is no stock input account defined ' \\\n 'for this product: \"%s\" (id: %d)') % \\\n (move.product_id.name,\n move.product_id.id,))\n if not acc_dest:\n acc_dest = move.product_id.product_tmpl_id.\\\n property_stock_account_output.id\n if not acc_dest:\n acc_dest = move.product_id.categ_id.\\\n property_stock_account_output_categ.id\n if not acc_dest:\n raise osv.except_osv(_('Error!'),\n _('There is no stock output account defined ' \\\n 'for this product: \"%s\" (id: %d)') % \\\n (move.product_id.name,\n move.product_id.id,))\n if not move.product_id.categ_id.property_stock_journal.id:\n raise osv.except_osv(_('Error!'),\n _('There is no journal defined '\\\n 'on the product category: \"%s\" (id: %d)') % \\\n (move.product_id.categ_id.name,\n move.product_id.categ_id.id,))\n journal_id = move.product_id.categ_id.property_stock_journal.id\n if acc_src != acc_dest:\n ref = move.picking_id and move.picking_id.name or False\n product_uom_obj = self.pool.get('product.uom')\n default_uom = move.product_id.uom_id.id\n q = product_uom_obj._compute_qty(cr, uid, move.product_uom.id, move.product_qty, default_uom)\n if move.product_id.cost_method == 'average' and move.price_unit:\n amount = q * move.price_unit\n else:\n amount = q * move.product_id.standard_price\n\n date = time.strftime('%Y-%m-%d')\n partner_id = False\n if move.picking_id:\n partner_id = move.picking_id.address_id and (move.picking_id.address_id.partner_id and move.picking_id.address_id.partner_id.id or False) or False\n lines = [\n (0, 0, {\n 'name': move.name,\n 'quantity': move.product_qty,\n 'credit': amount,\n 'account_id': acc_src,\n 'ref': ref,\n 'date': date,\n 'partner_id': partner_id}),\n (0, 0, {\n 'name': move.name,\n 'quantity': move.product_qty,\n 'debit': amount,\n 'account_id': acc_dest,\n 'ref': ref,\n 'date': date,\n 'partner_id': partner_id})\n ]\n self.pool.get('account.move').create(cr, uid, {\n 'name': move.name,\n 'journal_id': journal_id,\n 'line_id': lines,\n 'ref': ref,\n })\n self.write(cr, uid, ids, {'state': 'done', 'date_planned': time.strftime('%Y-%m-%d %H:%M:%S')})\n wf_service = netsvc.LocalService(\"workflow\")\n for id in ids:\n wf_service.trg_trigger(uid, 'stock.move', id, cr)\n return True\n\n def unlink(self, cr, uid, ids, context=None):\n for move in self.browse(cr, uid, ids, context=context):\n if move.state != 'draft':\n raise osv.except_osv(_('UserError'),\n _('You can only delete draft moves.'))\n return super(stock_move, self).unlink(\n cr, uid, ids, context=context)\n\nstock_move()","sub_path":"src/kdvn_purchase/kdvn_stock_move.py","file_name":"kdvn_stock_move.py","file_ext":"py","file_size_in_byte":24068,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"173525405","text":"from __future__ import absolute_import, division, print_function\r\nimport numpy as np \r\nimport tensorflow as tf \r\n\r\n#from tensorflow import keras\r\n#from tensorflow.keras import datasets, layers, models\r\nmnist = tf.keras.datasets.mnist\r\n\r\n(train_images, train_labels), (test_images, test_labels) = tf.keras.datasets.mnist.load_data()\r\n#(train_data, train_labels), (eval_data, eval_labels) = tf.keras.datasets.mnist.load_data()\r\n\r\n\r\ntrain_images = train_images.reshape((60000, 28, 28, 1))\r\ntest_images = test_images.reshape((10000, 28, 28, 1))\r\n\r\ntrain_images, test_images = train_images/255.0, test_images/255.0\r\n\r\nmodel = tf.keras.models.Sequential()\r\nmodel.add(tf.keras.layers.Conv2D(32, (3,3), activation='relu', input_shape=(28,28,1)))\r\nmodel.add(tf.keras.layers.MaxPooling2D((2,2)))\r\nmodel.add(tf.keras.layers.Conv2D(64, (3,3), activation='relu'))\r\nmodel.add(tf.keras.layers.MaxPooling2D((2,2)))\r\nmodel.add(tf.keras.layers.Conv2D(64, (3,3), activation='relu'))\r\n\r\nmodel.add(tf.keras.layers.Flatten())\r\nmodel.add(tf.keras.layers.Dense(64, activation='relu'))\r\nmodel.add(tf.keras.layers.Dense(10, activation='softmax'))\r\nmodel.compile(optimizer='adam',\r\n loss='sparse_categorical_crossentropy',\r\n metrics=['accuracy'])\r\nmodel.fit(train_images, train_labels, epochs=5)\r\n#model.summary()","sub_path":"cnn_team18.py","file_name":"cnn_team18.py","file_ext":"py","file_size_in_byte":1312,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"618272821","text":"import difflib\nimport mistune\n\n_debug = False\ndef _debugPrint(header, info, width=80, fillChar=\"-\"):\n if _debug:\n print(\" debug[{}] \".format(header).center(width, fillChar))\n print(info)\n\nfnDbgReport = _debugPrint\n\n(\n BLOCK_CODE, BLOCK_QUOTE, BLOCK_HTML, HEADER, HRULE, LIST, LIST_ITEM, PARAGRAPH, TABLE,\n TABLE_ROW, TABLE_CELL, AUTOLINK, CODESPAN, DOUBLE_EMPHASIS, EMPHASIS, IMAGE, LINEBREAK,\n NEWLINE, LINK, STRIKETHROUGH, TEXT, INLINE_HTML\n) = (\n \"block_code\", \"block_quote\", \"block_html\", \"header\", \"hrule\", \"list\", \"list_item\",\n \"paragraph\", \"table\", \"table_row\", \"table_cell\", \"autolink\", \"codespan\", \"double_emphasis\",\n \"emphasis\", \"image\", \"linebreak\", \"newline\", \"link\", \"strikethrough\", \"text\", \"inline_html\"\n)\n\nclass Item: # pylint: disable=R0903\n def __init__(self):\n self.type = None\n self.lineNum = 0\n\nclass HeaderItem(Item): # pylint: disable=R0903\n def __init__(self, *arg):\n super().__init__(*arg)\n self.text = None\n self.level = 0\n self.raw = None\n\nclass MDItemBuilder(mistune.Renderer):\n def __init__(self, *arg):\n super().__init__(*arg)\n self.items = []\n self.lines = None\n self.lineNumDict = None\n\n def header(self, text, level, raw=None):\n item = HeaderItem()\n item.type = HEADER\n item.text = text\n item.level = level\n item.raw = raw\n\n matchList = difflib.get_close_matches(item.raw, self.lines)\n item.lineNum = self.lineNumDict[matchList[0]] if matchList else 0\n self.items.append(item)\n fnDbgReport(\"markdown item info\", \"{0} ### level: {1} type: {2} line: {3}\".format(\n item.raw, item.level, item.type, item.lineNum))\n return \"\"\n\ndef parseFile(filePath, encoding=\"UTF-8\"):\n fnDbgReport(\"parse file path\", filePath)\n\n lines = []\n with open(filePath, encoding=encoding) as f:\n for l in f:\n lines.append(l)\n\n return parseContent(lines)\n\ndef parseContent(lines):\n lineNumDict = {}\n for lineNum, line in enumerate(lines, 1):\n lineNumDict[line] = lineNum\n\n sLines = \"\".join(lines)\n fnDbgReport(\"file content\", sLines)\n\n builder = MDItemBuilder()\n builder.lines = lines\n builder.lineNumDict = lineNumDict\n\n markdown = mistune.Markdown(renderer=builder)\n markdown(sLines)\n return builder.items\n\n","sub_path":"SublimeStorm-Dep-Utils/st3/MUtils/MarkDownInfo.py","file_name":"MarkDownInfo.py","file_ext":"py","file_size_in_byte":2377,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"403392225","text":"\"\"\" Aling Nena's Cashier Challenge\nAuthor:\nDescription: During closing, Aling Nena counts from her vault the day's total income and\nalso the total amount of all her paper bills.\nHelp Aling Nena count her total income and total amount of her paper bills\nfrom a list of cash money and using a loop!\n\"\"\"\n\n\ndef is_coins(money):\n \"\"\" Determine if the money is a coin\n :param money: (Integer)\n :return: (Boolean)\n Examples:\n >>> print(is_coins(20))\n False\n >>> print(is_coins(1))\n True\n \"\"\"\n if money < 20:\n return True\n return False\n\n\ncash_on_vault = [1, 5, 100, 10, 50, 50, 20, 5, 1, 1000, 1000, 500, 5, 200]\npaper_bills_total = 0\ntotal_money = 0\nfor money in cash_on_vault:\n total_money = total_money + money\n if not (is_coins(money)):\n paper_bills_total = paper_bills_total + money\n\nprint(\"Hi Aling Nena! Your total income for the day is {}\".format(total_money))\nprint(\"The total amount of your paper bills is {}\".format(paper_bills_total))\n","sub_path":"loops01.py","file_name":"loops01.py","file_ext":"py","file_size_in_byte":1010,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"182730427","text":"import sys\nsys.path.append('.')\nfrom util.game import Game\nfrom util.func import Case\nfrom util.card import Card, CardList, CardSuit\nfrom util.player import Player\nfrom typing import List, Optional, Tuple\nimport random\n\nclass LevelUp(Game):\n ### Constants\n PLAYERNUM: int = 4\n CARDPOOL: List[Card] = [Card(i) for i in range(54)] * 2\n BASESCORE: int = 80\n LEVELSCORE: int = 40\n\n def __init__(self):\n self.players: List[Optional[Player]] = [None] * LevelUp.PLAYERNUM\n self.discard_buffer: Optional[CardList] = None\n self.curPlayerIndex: Optional[int] = None\n self.rankLevel: Tuple[int, int] = (1, 1)\n self.dealerIndex: Optional[int] = None\n self.rankMain: int = 1\n # E.g. (Spade, 0, 1) means the main suit is spade (suited with a single spade by 0-th player)\n self.suitMain: Optional[Tuple(CardSuit, int, int)] = None\n self.score: int = 0\n self.state: str = 'END'\n for i in range(len(self.players)):\n self.players[i] = Player()\n \n \n def inform(self, information):\n case = Case(self.state)\n if case('END'):\n case = Case(information)\n if case('START'):\n self.state = 'DISPATCH'\n return (True, self._dispatch(), \n {\n 'suit': self.suitMain, \n 'rank': self.rankMain,\n 'level': self.rankLevel\n }\n )\n if case('DISPATCH'):\n case = Case(information)\n if case('FINISH'):\n self.state = 'DISCARD'\n if self.dealerIndex is None:\n self.dealerIndex = self.suitMain[1]\n self.curPlayerIndex = self.dealerIndex\n self.players[self.curPlayerIndex].cardInHand += self.discard_buffer\n self.discard_buffer = CardList()\n for player in self.players:\n player.cardFront = CardList()\n return (True, None, None)\n return (False, None, None)\n \n def _dispatch(self) -> List[int]:\n newCardPool: List[Card] = random.sample(LevelUp.CARDPOOL, len(LevelUp.CARDPOOL))\n dispatch = [newCardPool[0:25], newCardPool[25:50], newCardPool[50:75], newCardPool[75:100], newCardPool[100:]]\n for id, player in enumerate(self.players):\n player.cardInHand = CardList(dispatch[id])\n self.discard_buffer = CardList(dispatch[-1])\n return [[card.ID for card in cards] for cards in dispatch]\n \n def isSuitable(self, cards: List[int], playerID: int, suit: Optional[CardSuit] = None):\n #suit: 0 NT, 1 Spade, 2 Heart, 3 Club, 4 Diamond\n if suit is None:\n return [self.isSuitable(cards, playerID, s) for s in [\n CardSuit.Joker, CardSuit.Spade, CardSuit.Heart, CardSuit.Club, CardSuit.Diamond\n ]]\n cardnum = -1\n case = Case(suit)\n if case(CardSuit.Spade): cardnum = 39 + self.rankMain\n elif case(CardSuit.Heart): cardnum = 26 + self.rankMain\n elif case(CardSuit.Club): cardnum = 13 + self.rankMain\n elif case(CardSuit.Diamond): cardnum = self.rankMain\n if self.suitMain is None:\n if suit == CardSuit.Joker: \n return cards.count(52) == 2 or cards.count(53) == 2\n else:\n return cardnum in cards\n elif self.suitMain[1] == playerID:\n if self.suitMain[2] == 2: return False\n if suit != self.suitMain[0]: return False\n return cards.count(cardnum) == 2\n else:\n if suit == CardSuit.Joker:\n if self.suitMain[0] == CardSuit.Joker:\n return cards.count(53) == 2\n else:\n return cards.count(53) == 2 or cards.count(52) == 2\n if self.suitMain[2] == 2: return False\n return cards.count(cardnum) == 2\n \n def suitRequest(self, playerID: int, suit: CardSuit):\n cards = self.players[playerID].cardInHand.tolist()\n if not self.isSuitable(cards, playerID, suit):\n return False\n for player in self.players:\n player.cardFront = CardList()\n cardnum = -1\n case = Case(suit)\n if case(CardSuit.Spade): cardnum = 39 + self.rankMain\n elif case(CardSuit.Heart): cardnum = 26 + self.rankMain\n elif case(CardSuit.Club): cardnum = 13 + self.rankMain\n elif case(CardSuit.Diamond): cardnum = self.rankMain\n if suit == CardSuit.Joker:\n if cards.count(52) == 2:\n self.suitMain = (CardSuit.Joker, playerID, 2)\n self.players[playerID].cardFront += CardList([Card(52), Card(52)])\n else:\n self.suitMain = (CardSuit.Joker, playerID, 2)\n self.players[playerID].cardFront += CardList([Card(53), Card(53)])\n else:\n if self.suitMain is None:\n self.suitMain = (suit, playerID, 1)\n self.players[playerID].cardFront += Card(cardnum)\n else:\n self.suitMain = (suit, playerID, 2)\n self.players[playerID].cardFront += CardList([Card(cardnum), Card(cardnum)])\n front = [player.cardFront.tolist() for player in self.players]\n return [front, self.suitMain]\n ","sub_path":"util/levelup.py","file_name":"levelup.py","file_ext":"py","file_size_in_byte":5392,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"17917238","text":"import boto3\nimport time\n\ndef createCollection(collection_id):\n client = boto3.client('rekognition')\n\n # Create a collection\n response = client.create_collection(CollectionId=collection_id)\n return response['CollectionArn']\n\ndef createStreamProcessor(kvs_arn, kds_arn, name, collection_id, role_arn):\n client = boto3.client(\"rekognition\")\n response = client.create_stream_processor(\n Input={\n 'KinesisVideoStream': {\n 'Arn': kvs_arn\n }\n },\n Output={\n 'KinesisDataStream': {\n 'Arn': kds_arn\n }\n },\n Name=name,\n RoleArn=role_arn,\n Settings={\n 'FaceSearch': {\n 'CollectionId': collection_id,\n \"FaceMatchThreshold\": 1.0\n }\n },\n )\n\n return response\n\ndef statusStreamProcessor(name):\n client = boto3.client(\"rekognition\")\n response = client.describe_stream_processor(\n Name=name\n )\n print(response)\n return response\n\n\ndef startStreamProcessor(name):\n client = boto3.client(\"rekognition\")\n response = client.start_stream_processor(\n Name=name\n )\n print(\"Start the stream processor\")\n return response\n\ndef stopStreamProcessor(name):\n client = boto3.client(\"rekognition\")\n response = client.stop_stream_processor(\n Name=name\n )\n print(\"Stream processor stopped!\")\n return response\n\ndef deleteStreamProcessor(name):\n client = boto3.client(\"rekognition\")\n response = client.delete_stream_processor(\n Name=name\n )\n print(response)\n print(\"Deletion completed!\")\n return response\n\ndef listStreamProcessors():\n client = boto3.client(\"rekognition\")\n response = client.list_stream_processors(\n )\n print(response)\n return response\n\n\n\n\n# def lambda_handler(event, context):\nif __name__ == \"__main__\":\n # TODO implement\n\n \"\"\"\n Process Video Streams with Rekognition, output to KDS\n \"\"\"\n\n # *** Have to replace event object with test cases after this\n\n collection_id = \"known-visitors\"\n kvs_arn = \"arn:aws:kinesisvideo:us-east-1:584092006642:stream/kvs_smartdoor/1587838980687\"\n kds_arn = \"arn:aws:kinesis:us-east-1:584092006642:stream/kds_smartdoor\"\n role_arn = \"arn:aws:iam::584092006642:role/KRNK\"\n stream_process_name = \"smartdoor_processor\"\n\n # stopStreamProcessor(stream_process_name)\n # deleteStreamProcessor(\"smartdoor\")\n # listStreamProcessors()\n\n\n createStreamProcessor(kvs_arn, kds_arn, stream_process_name, collection_id, role_arn)\n\n startStreamProcessor(stream_process_name)\n\n for i in range(5):\n statusStreamProcessor(stream_process_name)\n time.sleep(5)\n\n status = statusStreamProcessor(stream_process_name)\n if status[\"Status\"] == \"RUNNING\":\n stopStreamProcessor(stream_process_name)\n\n deleteStreamProcessor(stream_process_name)\n\n\n\n","sub_path":"KRK/Kinesis.py","file_name":"Kinesis.py","file_ext":"py","file_size_in_byte":2916,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"553206246","text":"import MySQLdb\n\n # -*- coding: utf-8 -*-\n\nclass Singleton(object):\n _instance = None\n def __new__(cls, *args, **kwargs):\n if not cls._instance:\n cls._instance = super(Singleton, cls).__new__(cls, *args, **kwargs)\n return cls._instance\n\n\nclass DAO(Singleton):\n def __init__(self):\n self._connect()\n return\n\n\n def _connect(self):\n self.connection = MySQLdb.connect(host=\"infoweb\", \\\n user=\"E155530E\", \\\n passwd=\"E155530E\", \\\n db=\"E155530E\")\n return\n\n\n def _get_cursor(self):\n try:\n self.connection.ping()\n except:\n self._connect()\n return self.connection.cursor()\n\n\n def get_row(self, query):\n cursor = self._get_cursor()\n cursor.execute(query)\n row = cursor.fetchone()\n cursor.close()\n return row\n\n\n def get_rows(self, query):\n cursor = self._get_cursor()\n cursor.execute(query)\n rows = cursor.fetchall()\n cursor.close()\n return rows\n\n\n def execute(self, query):\n cursor = self._get_cursor()\n cursor.execute(query)\n self.connection.commit()\n cursor.close()\n return\n","sub_path":"dao.py","file_name":"dao.py","file_ext":"py","file_size_in_byte":1222,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"422592069","text":"# Author: Acer Zhang\n# Datetime:2019/10/26\n# Copyright belongs to the author.\n# Please indicate the source for reprinting.\n\nimport os\nimport sys\nimport random\nimport traceback\n\nfrom PIL import Image, ImageEnhance\nimport numpy as np\n\nfrom tools.os_tool import read_ext_in_dir\n\nfontP = \"./font/1.ttf\"\n\n\nclass ImgPretreatment:\n \"\"\"\n\n 图像预处理类\n\n 批量处理代码1 分类任务:\n # 创建工具对象并传入相关参数\n img_pretreatment_tool=ImgPretreatment(args)\n # 处理所有图像\n for index in range(img_pretreatment_tool.__len__())\n\n # 初始化当前index图像\n img_pretreatment_tool.img_init(index)\n # 对图像进行操作\n img_pretreatment_tool.img_cut_color()\n img_pretreatment_tool.img_xxx()\n img_pretreatment_tool.img_xxx()\n ...\n # 获取最终处理好的数据(Pillow对象)\n final_img_pil_obj,final_loc_box = img_pretreatment_tool.req_result()\n 批量处理代码2 目标检测任务:\n # 创建工具对象并传入相关参数\n img_pretreatment_tool=ImgPretreatment(args)\n # 处理所有图像\n for index in range(img_pretreatment_tool.__len__())\n # 可以获取当前初始化的文件名(不含扩展名) 防止与将要操作的图片不一致\n now_img_name = self.img_files_name[index]\n loc = xxx\n # 初始化当前index图像\n img_pretreatment_tool.img_init(index,loc)\n # 对图像进行操作\n img_pretreatment_tool.img_cut_color()\n img_pretreatment_tool.img_xxx()\n img_pretreatment_tool.img_xxx()\n ...\n # 获取最终处理好的数据(Pillow对象)\n final_img_pil_obj,final_loc_box = img_pretreatment_tool.req_result()\n\n 批量处理代码3 从内存读取:\n # 只需要在初始化图片时传入PIL对象即可 但部分功能可能无法使用(颜色裁剪,若没有之前保留的均值参数则无法计算颜色均值)\n # 创建工具对象并传入相关参数\n img_pretreatment_tool=ImgPretreatment(args)\n # 处理所有图像\n for index in range(len(img_pretreatment_tool))\n # 初始化当前index图像\n img_pretreatment_tool.img_init(index,pil_obj)\n # 对图像进行操作\n img_pretreatment_tool.img_cut_color()\n img_pretreatment_tool.img_xxx()\n img_pretreatment_tool.img_xxx()\n ...\n # 获取最终处理好的数据(Pillow对象)\n final_img_pil_obj,final_loc_box = img_pretreatment_tool.req_result()\n Tips:\n 1、第一次进行图像减颜色均值操作时过程较长,并非卡顿。\n 2、如果要统一数据集尺寸,则最好放在所有对图像的操作之前,初始化图像操作之后。这样更有利运行速度。\n 3、若进行颜色裁剪,则不可以进行保存图片操作,请在该操作前进行保存。\n 4、在传入标签位置信息时不用担心与当前所初始化的图片是否对应,因为在初始化该类时就已经生成了图片路径索引表\n 只需要获取 self.img_files_name 就可以知道当前index对应的图片名。\n 参数保存:\n 在获取颜色均值后会保一个参数文件'img_pretreatment.txt'记录参数。\n 参数读取仅在for_test=True或ignore_log=False时生效。\n\n 设计思想:\n ->给定文件夹以及参数进行读取。\n ->构建图片列表。\n ->给出索引值,初始化对应图片,若包含位置信息则在此传入。\n ->对图片进行操作。\n ->获取当前处理后的图片。\n\n 单张变多张操作: 初始化图片后,内部会以一个列表存储该图片,若涉及单张变多张的操作则会把结果都保存在该列表中。\n 尺寸变换操作: 每次处理都会有一个全局变量来记录变换后的尺寸\n 颜色裁剪操作: 仅计算文件夹内图片的颜色均值,无论怎样调整操作顺序,该操作总是最后一个进行,而且较为独立。\n \"\"\"\n\n def __init__(self, all_img_path, mean_color_num=500, dir_deep=0, img_type=\"jpg\", read_img_type='L',\n ignore_log=False, for_test=False, debug=True):\n \"\"\"\n :param all_img_path: 图像文件所在文件夹路径\n :param mean_color_num: 颜色均值采样数\n :param dir_deep: 检索文件夹的深度\n :param img_type: 图像文件类型,默认jpg格式\n :param read_img_type: 图像读取通道类型 默认为灰度\n :param ignore_log: 是否忽略之前参数文件\n :param for_test: 是否用于测试,如果用于测试则自动读取颜色裁剪信息\n :param debug: 设置为False后将进入哑巴模式,什么信息都不会打印在屏幕上,报错信息除外\n \"\"\"\n\n if debug:\n print(\"----------ImgPretreatment Start!----------\")\n\n self.img_files_name, self.img_files_path = read_ext_in_dir(all_img_path, dir_deep, img_type, name_none_ext=True)\n\n self.len_img = len(self.img_files_path)\n assert self.len_img != 0, \"No file is in the folder.\"\n self.mean_color_num = mean_color_num\n self.img_type = img_type\n self.read_img_type = read_img_type\n self.debug = debug\n self.shape = Image.open(self.img_files_path[0]).size\n\n # Flag 变量\n self.allow_req_img = False # 图像初始化控制\n self.allow_save_flag = True # 允许保存,如果进行去均值操作则不允许保存\n self._color_mean_flag = False # 是否需要计算颜色均值\n self.__need_color_cut_flag = False # 是否需要颜色去均值\n self.__first_print_flag = True # 是否第一次输出控制变量\n self.__contain_location = False # 是否包含位置标签信息\n if ignore_log is False or for_test is True:\n try:\n with open(\"./img_pretreatment.txt\", \"r\") as f:\n info = f.read().split(\"-\")\n check_info = str(self.read_img_type) + str(self.len_img) + str(self.mean_color_num)\n if info[0] == check_info or for_test:\n self._color_mean_flag = True\n self.allow_save_flag = False\n self.__color_mean = float(info[1][1:-1])\n if debug:\n print(\"Load Log Successfully!\")\n except:\n assert not for_test, \"Load Log Finally,Place check img_pretreatment.txt!\"\n # 当前进程变量\n self.now_index = -1\n self.now_img_name = None\n self.now_img_file_path = None\n self.now_img_obj_list = []\n self.now_label_locs_list = []\n self.tmp_one_img_to_num = 0\n self.tmp_all_img_to_num = 0\n if debug:\n print(\"Data read successfully number:\", self.len_img)\n\n def img_init(self, index, label_location_info=None, pil_obj=None):\n \"\"\"\n 图像初始化\n :param index: 需要初始化图像的索引\n :param label_location_info: 图像的位置信息 示例[[x_up, y_up, x_down, y_down],...]\n :param pil_obj: 若不想从文件中读取,请从此传入PIL对象\n \"\"\"\n self.allow_save_flag = True\n self.__contain_location = False\n if pil_obj is not None:\n self._color_mean_flag = False\n self.now_img_obj_list = []\n self.now_img_obj_list.append(pil_obj)\n if index is not self.now_index or len(self.now_img_obj_list) != 1:\n try:\n self.now_img_obj_list = []\n self.now_img_obj_list.append(Image.open(self.img_files_path[index]).convert(self.read_img_type))\n self.now_index = index\n self.now_img_name = self.img_files_name[self.now_index]\n except:\n print(traceback.format_exc())\n if label_location_info is not None:\n self.__contain_location = True\n self.now_label_locs_list = []\n self.now_label_locs_list.append(label_location_info)\n\n def __color_mean_start(self):\n \"\"\"\n 颜色均值获取\n :return:颜色均值\n \"\"\"\n sum_img_numpy = np.zeros((1, 1, 1), dtype=np.float)\n if self.read_img_type is \"L\":\n sum_img_numpy = np.zeros(1, dtype=np.float)\n\n self.__color_mean = [0, 0, 0]\n mean_color_num = self.mean_color_num\n success_num = 1\n only_shape = None\n for id_, imgP in enumerate(self.img_files_path):\n im = Image.open(imgP).convert(self.read_img_type)\n if id_ == 0:\n only_shape = im.size\n if only_shape != im.size:\n mean_color_num += 1\n continue\n sum_img_numpy += np.mean(np.asarray(im).reshape((1, im.size[0], im.size[1])))\n success_num += 1\n if id_ == mean_color_num or id_ == self.len_img - 1:\n self.__color_mean = np.around((sum_img_numpy / success_num), decimals=3).tolist()\n self._color_mean_flag = True\n\n with open(\"./img_pretreatment.txt\", \"w\") as f:\n f.write(\n (str(self.read_img_type) + str(self.len_img) + str(self.mean_color_num) + \"-\" + str(\n self.__color_mean)))\n if self.debug is True:\n print(\"Color mean :\", self.__color_mean)\n print(\"Successful counting in color mean:\", success_num - 1)\n print(\"Write log --Done!\")\n return self.__color_mean\n\n def img_cut_color(self):\n \"\"\"\n 颜色去均值操作\n 防止因为去均值后颜色模式发生改变,所以立了个Flag,使它即将结束时运行该操作。\n \"\"\"\n self.__need_color_cut_flag = True\n self.allow_save_flag = False\n\n def img_only_one_shape(self, expect_w, expect_h):\n \"\"\"\n 传入图片将中心修正为数据集统一的尺寸\n 注意!期望大小必须小于原始图片大小\n \"\"\"\n temp_img_list = []\n for index, now_img_obj in enumerate(self.now_img_obj_list):\n w, h = now_img_obj.size\n assert (w - expect_w >= 0 or h - expect_h >= 0), (\n \"Expected values are larger than the original image size. Please adjust the expected values to be \"\n \"smaller than the original size!\")\n box = ((w - expect_w) // 2, (h - expect_h) // 2,\n (w - expect_w) // 2 + expect_w, (h - expect_h) // 2 + expect_h)\n img = now_img_obj.crop(box)\n temp_img_list.append(img)\n if self.__contain_location:\n self.__repair_loc(index, box)\n\n self.now_img_obj_list = temp_img_list\n self.shape = temp_img_list[0].size\n\n def img_resize(self, expect_w, expect_h):\n \"\"\"\n 多相位调整图像大小\n :param expect_w: 期望的宽度-横向\n :param expect_h: 期望的高度-纵向\n \"\"\"\n temp_list = []\n for index, now_img_obj in enumerate(self.now_img_obj_list):\n if self.__contain_location:\n w, h = now_img_obj.size\n w_, h_ = (expect_w / w, expect_h / h)\n for loc_id, loc in enumerate(self.now_label_locs_list[index]):\n tmp_loc = [loc[0], [loc[1][0] * w_, loc[1][1] * h_, loc[1][2] * w_, loc[1][3] * w_]]\n self.now_label_locs_list[index][loc_id] = tmp_loc\n img = now_img_obj.resize((expect_w, expect_h), Image.LANCZOS)\n temp_list.append(img)\n\n self.now_img_obj_list = temp_list\n self.shape = temp_list[0].size\n\n def img_rotate(self, angle_range=(0, 0), angle_step=1, angle_and_transpose=False, only_transpose=True):\n \"\"\"\n 图像翻转\n 如果仅返回规则翻转,则不需要修改前两个参数\n :param angle_range:旋转最小角度和最大角度\n :param angle_step:选择角度之间的步长\n :param angle_and_transpose:旋转角度之后再进行水平和垂直旋转\n :param only_transpose:仅进行水平和垂直旋转\n Tips:如果使用该模块,则只在最后获取时运行\n \"\"\"\n\n def tran(ori_pil_obj, out_pil_list):\n out_pil_list.append(ori_pil_obj)\n out_pil_list.append(ori_pil_obj.transpose(Image.FLIP_LEFT_RIGHT))\n out_pil_list.append(ori_pil_obj.transpose(Image.FLIP_TOP_BOTTOM))\n\n temp_list = []\n if only_transpose is True:\n tmp_locs = []\n for index, now_img_obj in enumerate(self.now_img_obj_list):\n tran(now_img_obj, temp_list)\n w, h = now_img_obj.size\n tmp_loc1 = []\n for loc in self.now_label_locs_list[index]:\n tmp_loc1.append(loc)\n tmp_loc2 = []\n for loc in self.now_label_locs_list[index]:\n tmp_loc2.append([loc[0], [w - loc[1][0], loc[1][1], w - loc[1][2], loc[1][3]]])\n tmp_loc3 = []\n for loc in self.now_label_locs_list[index]:\n tmp_loc3.append([loc[0], [loc[1][0], h - loc[1][1], loc[1][2], h - loc[1][3]]])\n tmp_locs.append(tmp_loc1)\n tmp_locs.append(tmp_loc2)\n tmp_locs.append(tmp_loc3)\n self.now_label_locs_list = tmp_locs\n\n else:\n print(\"暂时不需要该功能\")\n \"\"\"\n for now_img_obj in self.now_img_obj_list:\n for angle in range(angle_range[0], angle_range[1], angle_step):\n temp_list.append(now_img_obj.rotate(angle))\n if angle_and_transpose is True:\n self.now_img_obj_list = []\n for now_img_obj in temp_list:\n tran(now_img_obj, self.now_img_obj_list)\n\n \"\"\"\n self.now_img_obj_list = temp_list\n\n def img_random_crop(self, expect_w: int, expect_h: int, random_num: int = 1):\n \"\"\"\n 随机裁剪\n 期望值需小于当前图片尺寸\n :param expect_w:\n :param expect_h:\n :param random_num:\n \"\"\"\n temp_img_list = []\n for seed in range(1, random_num + 1):\n for index, now_img in enumerate(self.now_img_obj_list):\n w, h = now_img.size\n seed_w = random.randint(0, (w - expect_w))\n seed_h = random.randint(0, (h - expect_h))\n box = (seed_w, seed_h, seed_w + expect_w, seed_h + expect_h)\n if self.__contain_location:\n self.__repair_loc(index, box)\n temp_img_list.append(now_img.crop(box))\n self.now_img_obj_list = temp_img_list\n self.shape = temp_img_list[0].size\n\n def img_random_contrast(self, random_num: int = 1, lower=0.5, upper=1.5):\n \"\"\"\n 随机对比度\n :param random_num: 随机次数,尽可能在3以内,建议为1,均匀随机\n :param lower:最低可能的对比度\n :param upper:最高可能的对比度\n \"\"\"\n\n temp_list = list(self.now_img_obj_list)\n temp_los = list(self.now_label_locs_list) if self.__contain_location else None\n for seed in range(1, random_num + 1):\n factor = random.uniform(lower + ((upper - lower) * seed - 1 / random_num),\n lower + ((upper - lower) * seed / random_num))\n for index, now_img_obj in enumerate(self.now_img_obj_list):\n img = ImageEnhance.Sharpness(now_img_obj)\n img = img.enhance(factor)\n temp_list.append(img)\n if self.__contain_location:\n temp_los.append(temp_los[index])\n self.now_img_obj_list = temp_list\n self.now_label_locs_list = temp_los\n\n def img_random_brightness(self, random_num: int = 1, lower=0.5, upper=1.5):\n \"\"\"\n 随机亮度\n :param random_num: 随机次数,尽可能在3以内,建议为1,均匀随机\n :param lower:最低可能的亮度\n :param upper:最高可能的亮度\n \"\"\"\n\n temp_list = list(self.now_img_obj_list)\n temp_los = list(self.now_label_locs_list) if self.__contain_location else None\n for seed in range(1, random_num + 1):\n factor = random.uniform(lower + ((upper - lower) * seed - 1 / random_num),\n lower + ((upper - lower) * seed / random_num))\n for index, now_img_obj in enumerate(self.now_img_obj_list):\n img = ImageEnhance.Brightness(now_img_obj)\n img = img.enhance(factor)\n temp_list.append(img)\n if self.__contain_location:\n temp_los.append(temp_los[index])\n self.now_img_obj_list = temp_list\n self.now_label_locs_list = temp_los\n\n def img_random_saturation(self, random_num: int = 1, lower=0.5, upper=1.5):\n \"\"\"\n 随机饱和度\n :param random_num: 随机次数,尽可能在3以内,建议为1,均匀随机\n :param lower:最低可能的亮度\n :param upper:最高可能的亮度\n \"\"\"\n temp_list = list(self.now_img_obj_list)\n temp_los = list(self.now_label_locs_list) if self.__contain_location else None\n for seed in range(1, random_num + 1):\n factor = random.uniform(lower + ((upper - lower) * seed - 1 / random_num),\n lower + ((upper - lower) * seed / random_num))\n for index, now_img_obj in enumerate(self.now_img_obj_list):\n img = ImageEnhance.Color(now_img_obj)\n img = img.enhance(factor)\n temp_list.append(img)\n if self.__contain_location:\n temp_los.append(temp_los[index])\n self.now_img_obj_list = temp_list\n self.now_label_locs_list = temp_los\n\n def req_result(self, save_path=None):\n \"\"\"\n 获取当前处理进程中图片\n :param save_path:如果保存图片,则需要提供保存路径\n :return: PIL_Obj_List or [PIL_Obj_List,location_info_list]\n \"\"\"\n # 特殊操作区域\n if self.__need_color_cut_flag is True:\n temp_list = []\n for now_img_obj in self.now_img_obj_list:\n now_img_obj = Image.fromarray(np.asarray(now_img_obj) - self._req_color_mean())\n temp_list.append(now_img_obj)\n self.now_img_obj_list = list(temp_list)\n self.__need_color_cut_flag = False\n\n # 输出区域\n\n if self.debug and self.__first_print_flag:\n tmp_shape = self.shape\n self.tmp_one_img_to_num = len(self.now_img_obj_list)\n self.tmp_all_img_to_num = self.len_img * len(self.now_img_obj_list)\n print(\"The current size of the first image output is \", tmp_shape)\n print(\"The number of single image pre-processed is expected to be \", self.tmp_one_img_to_num)\n print(\"The total number of pictures expected to be produced is \", self.tmp_all_img_to_num)\n self.__first_print_flag = False\n if self.debug:\n self.__progress_print()\n # 保存区域\n if save_path is not None:\n assert self.allow_save_flag, \"Can not save F mode img! Please undo img_cut_color operation!\"\n folder = os.path.exists(save_path)\n if not folder:\n os.makedirs(save_path)\n if len(self.now_img_obj_list) != 1:\n for id_, img in enumerate(self.now_img_obj_list):\n img.save(\n os.path.join(save_path, self.img_files_name[self.now_index] + str(id_) + \".jpg\").replace(\"\\\\\",\n \"/\"))\n else:\n self.now_img_obj_list[0].save(\n os.path.join(save_path, self.img_files_name[self.now_index] + \".jpg\").replace(\"\\\\\", \"/\"))\n # 数据返回区域\n if self.__contain_location:\n return [self.now_img_obj_list, self.now_label_locs_list]\n else:\n return self.now_img_obj_list\n\n def req_img_count(self):\n \"\"\"\n 获取当前处理文件夹下处理后图像总数\n 返回单张图片处理后的数量,文件夹下预计处理完后的数量\n :return: tmp_one_img_to_num, tmp_all_img_to_num\n \"\"\"\n return self.tmp_one_img_to_num, self.tmp_all_img_to_num\n\n def _req_color_mean(self):\n if self._color_mean_flag:\n return self.__color_mean\n else:\n return self.__color_mean_start()\n\n def __repair_loc(self, index, box):\n \"\"\"\n 修正标签坐标,用于裁剪后坐标偏移修正。传入在原图基础上裁剪的范围框--box和当前坐标列表即可\n :param index: 当前处理列表的索引值\n :param box: 裁剪框\n \"\"\"\n\n temp_loc_list = []\n for loc_id, loc in enumerate(self.now_label_locs_list[index]):\n final_loc = [loc[1][0] - box[0], loc[1][1] - box[1], loc[1][2] - box[0], loc[1][3] - box[1]]\n if min(final_loc) >= 0:\n temp_loc_list.append([loc[0], final_loc])\n else:\n temp_loc_list.append([0, [0, 0, 0, 0]])\n self.now_label_locs_list[index] = temp_loc_list\n\n def __progress_print(self):\n \"\"\"\n 打印进度百分比\n \"\"\"\n\n percentage = (self.now_index + 1) / self.len_img\n stdout_obj = sys.stdout\n style = \"|\\\\|\"\n if self.now_index % 2 == 0:\n style = \"|/|\"\n if self.now_index == self.len_img - 1:\n stdout_obj.write('\\rPercentage of progress:{:.2%}'.format(percentage))\n print(\"\\n----------ImgPretreatment Done!-----------\\n\")\n else:\n stdout_obj.write('\\r' + style + ' Percentage of progress:{:.2%}'.format(percentage))\n\n def __len__(self):\n return self.len_img\n\n# # 测试代码\n# all_img_tool = ImgPretreatment(all_img_path=\"./\", debug=True, ignore_log=True)\n# for i in range(all_img_tool.__len__()):\n# all_img_tool.img_init(i, [[5, 10, 15, 20]])\n# all_img_tool.img_rotate(only_transpose=True)\n# all_img_tool.img_random_brightness()\n# all_img_tool.img_random_contrast()\n# all_img_tool.img_cut_color()\n# all_img_tool.img_resize(450, 220)\n# all_img_tool.img_random_saturation()\n# all_img_tool.img_only_one_shape(448, 218)\n# all_img_tool.img_random_crop(440, 210, 2)\n# all_img_tool.req_result()\n# pass\n","sub_path":"dl_work/tools/img_tool.py","file_name":"img_tool.py","file_ext":"py","file_size_in_byte":22851,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"540163049","text":"#\n# V-Ray For Blender\n#\n# http://chaosgroup.com\n#\n# Author: Andrei Izrantcev\n# E-Mail: andrei.izrantcev@chaosgroup.com\n#\n# This program is free software; you can redistribute it and/or\n# modify it under the terms of the GNU General Public License\n# as published by the Free Software Foundation; either version 2\n# of the License, or (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program. If not, see .\n#\n# All Rights Reserved. V-Ray(R) is a registered trademark of Chaos Software.\n#\n\nimport bpy\n\n\nTYPE = 'OBJECT'\nID = 'VRayClipper'\nNAME = 'Clipper'\nDESC = \"Clipper settings\"\n\n\nPluginParams = (\n {\n 'attr' : 'enabled',\n 'desc' : \"\",\n 'type' : 'BOOL',\n 'default' : False,\n },\n {\n 'attr' : 'affect_light',\n 'desc' : \"\",\n 'type' : 'BOOL',\n 'default' : True,\n },\n {\n 'attr' : 'only_camera_rays',\n 'desc' : \"The clipper will affect objects as they are directly seen by the camera, but they will appear unchanged to reflection/refraction/GI rays\",\n 'type' : 'BOOL',\n 'default' : False,\n },\n {\n 'attr' : 'clip_lights',\n 'desc' : \"\",\n 'type' : 'BOOL',\n 'default' : True,\n },\n {\n 'attr' : 'use_obj_mtl',\n 'name' : \"Use Clipper Material\",\n 'desc' : \"When enabled, the clipper will use the material of each clipped object to fill in the resulting holes. When this is off, the material applied to the clipper object itself will be used\",\n 'type' : 'BOOL',\n 'default' : False,\n },\n {\n 'attr' : 'set_material_id',\n 'name' : 'Set Material ID',\n 'desc' : \"When enabled, you can specify a face material ID for the clipper object\",\n 'type' : 'BOOL',\n 'default' : False,\n },\n {\n 'attr' : 'material_id',\n 'name' : \"Material ID\",\n 'desc' : \"The face material ID for the clipped surfaces when \\\"Set material\\\" ID is enabled\",\n 'type' : 'INT',\n 'default' : 1,\n },\n {\n 'attr' : 'exclusion_mode',\n 'desc' : \"Exclusion Mode\",\n 'type' : 'ENUM',\n 'items' : (\n ('0', \"Include\", \"\"),\n ('1', \"Exclude\", \"\"),\n ),\n 'default' : '1',\n },\n {\n 'attr' : 'exclusion_nodes',\n 'desc' : \"List of node plugins to consider for inclusion/exclusion\",\n 'type' : 'PLUGIN',\n 'default' : \"\",\n },\n {\n 'attr' : 'transform',\n 'desc' : \"\",\n 'type' : 'TRANSFORM',\n 'default' : None,\n },\n {\n 'attr' : 'material',\n 'desc' : \"\",\n 'type' : 'PLUGIN',\n 'default' : \"\",\n },\n {\n 'attr' : 'object_id',\n 'desc' : \"\",\n 'type' : 'INT',\n 'default' : 0,\n },\n)\n","sub_path":"plugins/object/VRayClipper.py","file_name":"VRayClipper.py","file_ext":"py","file_size_in_byte":3109,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"240444268","text":"from flask import Flask\nfrom flask_restful import Api, Resource, reqparse\n\napp = Flask(__name__)\napi = Api(app)\n\nanimals = [\n {\n \"id\": \"1\",\n \"name\": \"Gallinazo Rey\",\n \"class\": \"Ave\",\n \"order\": \"Incertae Sedis\",\n \"family\": \"Cathartidae\",\n \"gender\": \"Sarcoramphus\",\n \"species\": \"Arcoramphus papa\",\n \"commonName\": \"Zopilote rey, condor real, cuervo real\"\n },\n {\n \"id\": \"2\",\n \"name\": \"Pavon negro o Crax rubra\",\n \"class\": \"Ave\",\n \"order\": \"galliformes\",\n \"family\": \"cracidae\",\n \"gender\": \"crax\",\n \"species\": \"crax rubra\",\n \"commonName\": \"pavon negro, hocofaisan, pavon norteno\" \n },\n {\n \"id\": \"3\",\n \"name\": \"Guacamaya Amarilla\",\n \"class\": \"Ave\",\n \"order\": \"Psittaciformes\",\n \"family\": \"Psittacidae\",\n \"gender\": \"Ara\",\n \"species\": \"Ara ararauna\",\n \"commonName\": \"Guacamaya azul o azul amarillo, papagayo o paraba azul amarillo\" \n },\n {\n \"id\": \"4\",\n \"name\": \"Guacamaya Bandera\",\n \"class\": \"Ave\",\n \"order\": \"Psittaciformes\",\n \"family\": \"Psittacidae\",\n \"gender\": \"ara\",\n \"species\": \"Ara ararauna\",\n \"commonName\": \"guacamaya bandera, guacamayo macao, guacamayo rojo\" \n },\n {\n \"id\": \"5\",\n \"name\": \"Tapir\",\n \"class\": \"mammalia\",\n \"order\": \"perissodactyla\",\n \"family\": \"tapiridae\",\n \"gender\": \"tapirus\",\n \"species\": \"tapirus bairdii\",\n \"commonName\": \"tapir centroamericano, danta, anteburro, macho de monte\" \n },\n {\n \"id\": \"6\",\n \"name\": \"Venado cola blanca\",\n \"class\": \" mammalia\",\n \"order\": \" artiodactyla\",\n \"family\": \": cervidae\",\n \"gender\": \" odocoileus\",\n \"species\":\" odocoileus virginiaus\",\n \"commonName\": \" Venado de cola blanca, ciervo de cola blanca, ciervo de virginia\"\n },\n {\n \"id\": \"7\",\n \"name\": \"Jaguar\",\n \"class\": \" Mammalia\",\n \"order\": \" Carnívora\",\n \"family\": \": felidae\",\n \"gender\": \" panthera\", \n \"species\":\" panthera onca\",\n \"commonName\": \" jaguar, Yaguar, Yaguerete Balam, Barum\"\n },\n {\n \"id\": \"8\",\n \"name\": \"Zorro cangrejero\",\n \"class\": \" mammalia\",\n \"order\": \" carnivora\",\n \"family\": \": canidae\",\n \"gender\": \" cersocyon\", \n \"species\":\" cerdocyon thous\",\n \"commonName\": \" zorro de monte, zorro sabanero\"\n },\n {\n \"id\": \"9\",\n \"name\": \"Nutria\",\n \"class\": \" Mammalia\",\n \"order\": \" carnívora \",\n \"family\": \": Mustelidae\",\n \"gender\": \" Sanguinus\",\n \"species\":\" Lontra longicaudis\",\n \"commonName\": \" nutria, lobito de río\"\n },\n {\n \"id\": \"10\",\n \"name\": \"Saino\",\n \"class\": \" Mammalia\",\n \"order\": \" artiodactyla\",\n \"family\": \": tayassuidae\",\n \"gender\": \" tayassu\",\n \"species\":\" tayassu tajacu\",\n \"commonName\": \" saino, pecarí de collar, jabalí\"\n },\n {\n \"id\": \"11\",\n \"name\": \" puma\",\n \"class\": \" Mammalia\",\n \"order\": \" carnivora\",\n \"family\": \" feliade\",\n \"gender\": \" puma\",\n \"species\":\" puma con color\",\n \"commonName\": \" leon de montaña\"\n },\n {\n \"id\": \"12\",\n \"name\": \" mono cara blanca \",\n \"class\": \" Mammalia\",\n \"order\": \" primate\",\n \"family\": \" cedibae\",\n \"gender\": \" cebus\",\n \"species\":\" cebius capuchino\",\n \"commonName\": \" cari blanco maicero capuchino tanque manchin\"\n },\n {\n \"id\": \"13\",\n \"name\": \" mono titi panameño\",\n \"class\": \" Mammalia\",\n \"order\": \" primates\",\n \"family\": \" calitrichidae\",\n \"gender\": \" saguinus\",\n \"species\":\" saguinus geoffroyi\",\n \"commonName\": \" titi tamarindo panameño,tamarindo de nuca café, pinche de morron\"\n },\n {\n \"id\": \"14\",\n \"name\": \" Loro comun\",\n \"class\": \" aves\",\n \"order\": \" psittaciformes\",\n \"family\": \" psiittacidae\",\n \"gender\": \" Amazona\",\n \"species\":\" amazona ochrocephala\",\n \"commonName\": \" Amazonas Harinoso , Loro Harinoso, amazónico\"\n }, \n {\n \"id\": \"15\",\n \"name\": \" taira\",\n \"class\": \" Mammalia\",\n \"order\": \" carnivora\",\n \"family\": \": mustelidae\",\n \"gender\": \" eira\",\n \"species\":\" eira barbara\",\n \"commonName\": \" huron mayor,cabeza de viejo\"\n },\n {\n \"id\": \"16\",\n \"name\": \" tucan de pico castaño\",\n \"class\": \" Aves\",\n \"order\": \" piciformes\",\n \"family\": \" ramphastidae\",\n \"gender\": \" ramphastos\",\n \"species\":\" ramphastos swainsonii\",\n \"commonName\": \" tucan Dio te de\"\n },\n {\n \"id\": \"17\",\n \"name\": \" tortuga terrestre de patas rojas\",\n \"class\": \" Sauropsida\",\n \"order\": \" Testudin\",\n \"family\": \" Testudinidae\",\n \"gender\": \" chelonoidis\",\n \"species\":\" chelonoidis carbonaria\",\n \"commonName\": \"tortuga morrocoya\"\n }, \n {\n \"id\": \"18\",\n \"name\": \" Tigrillo\",\n \"class\": \" Mammalia\",\n \"order\": \" carnivora\",\n \"family\": \" felidae\",\n \"gender\": \" leopardus\",\n \"species\":\" leopardus wiedii\",\n \"commonName\": \" gato tigre, caucel, maracaya\"\n },\n {\n \"id\": \"19\",\n \"name\": \" gato solo\",\n \"class\": \" Mammalia\",\n \"order\": \" carnivora\",\n \"family\": \" procyonidae\",\n \"gender\": \" nasua\",\n \"species\":\" nasua narica\",\n \"commonName\": \"coati\"\n },\n {\n \"id\": \"20\",\n \"name\": \" mono araña colorado\",\n \"class\": \" Mammalia\",\n \"order\": \" primates\",\n \"family\": \" cebidae\",\n \"gender\": \" ateles\",\n \"species\":\" ateles geoffroy\",\n \"commonName\": \"mono araña de manos negras\"\n },\n {\n \"id\": \"21\",\n \"name\": \" suirirí piquirrojo\",\n \"class\": \" aves\",\n \"order\": \" anseriformes\",\n \"family\": \" anatidae\",\n \"gender\": \" dendrocygna\",\n \"species\":\" Dendrocygna autumnalis\",\n \"commonName\": \"güichichi \"\n },\n {\n \"id\": \"22\",\n \"name\": \" guacamaya rojo\",\n \"class\": \" ave\",\n \"order\": \" psittaciforme\",\n \"family\": \" psittacidae\",\n \"gender\": \" Ara\",\n \"species\":\" Ara chloropterus\",\n \"commonName\": \" guacamayo aliverde\"\n },\n {\n \"id\": \"23\",\n \"name\": \" águila harpía\",\n \"class\": \" ave\",\n \"order\": \" accipitriforme\",\n \"family\": \" accipitriforme\",\n \"gender\": \" harpia\",\n \"species\":\" harpia harpyja\",\n \"commonName\": \" harpía mayor\"\n },\n {\n \"id\": \"24\",\n \"name\": \" capibara ronsoco\",\n \"class\": \" Mammalia\",\n \"order\": \" rodentia\",\n \"family\": \": caviidae\",\n \"gender\": \" hydrochoerus\",\n \"species\":\" Hydrochoerus hydrochaeris\",\n \"commonName\": \" chigüire, pancho, chigüiro\"\n }\n]\n\nclass Animal(Resource):\n def get(self, id):\n for animal in animals:\n if(id == animal[\"id\"]):\n return animal, 200\n return \"User not found\", 404\n\n def post(self, id):\n parser = reqparse.RequestParser()\n parser.add_argument(\"class\")\n parser.add_argument(\"order\")\n parser.add_argument(\"family\")\n parser.add_argument(\"gender\")\n parser.add_argument(\"species\")\n parser.add_argument(\"commonName\")\n args = parser.parse_args()\n\n for animal in animals:\n if(id == animal[\"id\"]):\n return \"Animal with name {} already exists\".format(id), 400\n\n animal = {\n \"id\": id,\n \"name\": args[\"name\"],\n \"class\": args[\"class\"],\n \"order\": args[\"order\"],\n \"family\": args[\"family\"],\n \"gender\": args[\"gender\"],\n \"species\": args[\"species\"],\n \"commonName\": args[\"commonName\"]\n }\n animals.append(animal)\n return animal, 201\n\n def put(self, id):\n parser = reqparse.RequestParser()\n parser.add_argument(\"id\")\n parser.add_argument(\"class\")\n parser.add_argument(\"order\")\n parser.add_argument(\"family\")\n parser.add_argument(\"gender\")\n parser.add_argument(\"species\")\n parser.add_argument(\"commonName\")\n args = parser.parse_args()\n\n for animal in animals:\n if(id == animal[\"id\"]):\n animal[\"class\"] = args[\"class\"]\n animal[\"order\"] = args[\"order\"]\n animal[\"family\"] = args[\"family\"]\n animal[\"gender\"] = args[\"species\"]\n animal[\"species\"] = args[\"species\"]\n animal[\"commonName\"] = args[\"commonName\"]\n return animal, 200\n \n animal = {\n \"id\": id,\n \"name\": args[\"name\"],\n \"class\": args[\"class\"],\n \"order\": args[\"order\"],\n \"family\": args[\"family\"],\n \"gender\": args[\"gender\"],\n \"species\": args[\"species\"],\n \"commonName\": args[\"commonName\"]\n }\n animals.append(animal)\n return animal, 201\n\n def delete(self, name):\n global animals\n animals = [animal for animal in animals if animal[\"id\"] != animal]\n return \"{} is deleted.\".format(id), 200\n \napi.add_resource(Animal, \"/animal/\")\n\napp.run(debug=False)\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":9523,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"12251634","text":"import gzip\nimport urllib.request\nimport base64\nimport json\nrequest = urllib.request.Request(\n \"https://api.touch2success.com/menu?host=burslemspice.com&app_name=FOODHUB\",\n headers={\n \"Accept-Encoding\": \"gzip\",\n \"User-Agent\": \"Mozilla/5.0 (X11; U; Linux i686) Gecko/20071127 Firefox/2.0.0.11\", \n })\nresponse = urllib.request.urlopen(request)\na=response.read().decode()\nb=json.loads(a)\nprint(b)\ngzipFile = gzip.GzipFile(fileobj=response)\ndata=gzipFile.read()\ndatass = str(data, base64.decode())\nprint(datass)\nst=base64.b64decode(data)\n# print(st)\n# print(gzip.decompress(st))\nwith open(\"getmenu3.gz\", 'w') as outfile:\n outfile.write(data)","sub_path":"pyPrgms/getMenu3.py","file_name":"getMenu3.py","file_ext":"py","file_size_in_byte":663,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"509131689","text":"\"\"\"\nThis module creates a biased random number generator. It returns 0 with\nprobability p and 1 with probability (1-p). The goal of this exercise is to\ncreate a fair random number generator using the biased one.\n\"\"\"\n\nimport random\nfrom collections import Counter\n\np = random.randint(1, 99)\nchoices = [0] * p\nchoices.extend([1] * (100-p))\n\n\ndef random_biased():\n \"\"\"\n returns 0 with probability p and 1 with probability (1-p) for some p\n \"\"\"\n\n return random.choice(choices)\n\n\ndef random_fixed():\n \"\"\"\n returns 0 or 1 with equal probability (1/2) using random_biased()\n \"\"\"\n\n x, y = 0, 0\n\n while x == y:\n x = random_biased()\n y = random_biased()\n\n if x != y:\n return x\n\n\nif __name__ == '__main__':\n print('-' * 80)\n print('p is {}'.format(p))\n\n fixed, biased = [], []\n for i in range(1000):\n fixed.append(random_fixed())\n biased.append(random_biased())\n\n print('Biased Results')\n c2 = Counter(biased)\n for e in sorted(c2.items()):\n print(e)\n\n print('Fixed Results')\n c1 = Counter(fixed)\n for e in sorted(c1.items()):\n print(e)\n\n print('-' * 80)\n","sub_path":"random/random-biased.py","file_name":"random-biased.py","file_ext":"py","file_size_in_byte":1163,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"499222858","text":"#not the main class\n\ntry:\n import wpilib as wpi\nexcept:\n import testing as wpi\n\nimport util\n\ndef Driver(p1, p2, p3 = None, p4 = None):\n print(\"Driver switcher function called\")\n if p3 == p4 == None:\n print(\"Detected Two-Motor setup\\n\")\n return Driver_2(p1, p2)\n else:\n print(\"Detected Four-Motor setup\\n\")\n return Driver_4(p1, p2, p3, p4)\n\nclass Driver_2:\n \"\"\"Driver class for two motor robots\"\"\"\n def __init__(self, port1, port2):\n self.L = speed_con(port1, True)\n self.R = speed_con(port2, True)\n self.vicList = [self.L, self.R]\n print(\"Two-wheeled driver on ports \" + str(port1) + \" and \" + str(port2))\n \n def stop(self):\n print(\"stop called\")\n for motor in self.vicList:\n motor.set_speed(0)\n \n def tankDriveRaw(self, left, right=0):\n self.L.set_speed(left)\n self.R.set_speed(-right)\n print (\"tankDriveRaw at \" + str(left) + \" and \" + str(right))\n \n def arcadeDriveRaw(self, turn, power):\n left = power + turn\n right = power - turn\n print(\"arcadeDriveRaw at \" + str(power) + \" and \" + str(turn))\n self.tankDriveRaw(left, right)\n \n def tankDrive(self, ls, rs):\n return self.tankDriveRaw(ls.getStickAxes()[1], rs.getStickAxes()[1])\n \n def arcadeDrive(self, stick):\n return self.arcadeDriveRaw(stick.getStickAxes()[0], stick.getStickAxes()[1])\n\nclass Driver_4:\n \"\"\"Driver class that manages the Motor controllers\"\"\"\n def __init__(self, port1, port2, port3, port4):\n \"\"\"Depends on four motors, will make two-motor version asap\"\"\"\n self.FL = speed_con(port1, True)\n self.FR = speed_con(port2, True)\n self.RL = speed_con(port3, True)\n self.RR = speed_con(port4, True)\n self.vicList = [self.FL, self.FR, self.RL, self.RR]\n \n def stop(self):\n \"\"\"Stops the robot, useful for everything\"\"\"\n self.tankDriveRaw(0, 0)\n print(\"Robot Stopped\")\n \n def tankDrive(self, stick, stick2=None):\n \"\"\"Takes two stick list inputs [x,y]\"\"\"\n left = 0\n right = 0\n \n if stick2 == None:\n try:\n left = -stick.getStickAxes()[1]\n right = -stick.getStickAxes()[4]\n except:\n left = -stick.getStickAxes()[1]\n right = -stick.getStickAxes()[3]\n else:\n left = stick.getStickAxes()[1]\n right = stick2.getStickAxes()[1]\n \n self.vicList[0].set_speed(left)\n self.vicList[1].set_speed(-right)\n self.vicList[2].set_speed(left)\n self.vicList[3].set_speed(-right)\n \n print(\"tankDrive at \" + str(left) + \" and \" + str(right))\n \n def holonomicDrive(self, xboxController):\n \"\"\"a nice wrapper\"\"\"\n power = xboxController.getAllAxes[1] #y-axis, first stick\n strafe = xboxController.getAllAxes[0] #x-axis, first stick\n spin = xboxController.getAllAxes[3] #x-axis, second stick (x...[2] is the trigger axis)\n \n fl = power + strafe + spin\n fr = power - strafe - spin\n rl = power - strafe + spin\n rr = power + strafe - spin\n \n print(\"holonomicDrive called\")\n \n self.FL.set_speed(fl)\n self.FR.set_speed(fr)\n self.RL.set_speed(rl)\n self.RR.set_speed(rr) \n \n def tankDriveRaw(self, left, right):\n self.vicList[0].set_speed(left)\n self.vicList[1].set_speed(-right)\n self.vicList[2].set_speed(left)\n self.vicList[3].set_speed(-right)\n print(\"tankDriveRaw at \" + str(left) + \" and \" + str(right))\n\n def holonomicDriveRaw(self, power, strafe=0, spin=0):\n fl = power + strafe + spin\n fr = power - strafe - spin\n rl = power - strafe + spin\n rr = power + strafe - spin\n \n max = util.max_of_4(fl, fr, rl, rr)\n \n fl = fl/max\n fr = fr/max\n rl = rl/max\n rr = rr/max\n \n print('holonomicDriveRaw called')\n \n self.FL.set_speed(fl)\n self.FR.set_speed(fr)\n self.RL.set_speed(rl)\n self.RR.set_speed(rr)\n \nclass dual_solenoid:\n def __init__(self, port1, port2):\n self.one = single_solenoid(port1)\n self.two = single_solenoid(port2)\n \n def extend(self):\n self.one.extend()\n self.two.retract()\n \n def retract(self):\n self.one.retract()\n self.two.retract()\n \n def get(self):\n if self.one.get() and not self.two.get():\n return True\n else:\n return False\n \nclass single_solenoid:\n def __init__(self, port):\n self.port = port\n print(\"single_solenoid set up on port \" + str(port))\n self.noid = wpi.Solenoid(8, port)\n comp_needed = True\n \n def extend(self):\n self.noid.Set(True)\n print (\"Solenoid on port \" + str(self.port) + \" active\")\n \n def retract(self):\n self.noid.Set(False)\n print (\"Solenoid on port \" + str(self.port) + \" not active\")\n \n def get(self):\n return self.noid.Get()\n \nclass relay:\n def __init__(self, port):\n self.rel = wpi.Relay(port)\n self.port = port\n comp_needed = True\n print(\"ghetto relay class set up on port \" + str(port))\n \n def forward(self):\n self.rel.Set(self.rel.kForward)\n print (\"relay on port \" + str(self.port) + \" set to forward\")\n \n def backward(self):\n self.rel.Set(self.rel.kReverse)\n print (\"relay on port \" + str(self.port) + \" set to backward\")\n \n def off(self):\n self.rel.Set(self.rel.kOff)\n print (\"relay on port \" + str(self.port) + \" set to off\")\n \ncomp_needed = False\ncomp = None\n\ndef initComp():\n comp = wpi.Compressor(1,1)\n comp.Start()\n\nclass EL_wire(object):\n def __init__(self, port):\n self.port = port\n print (\"EL Wire Driver set up on relay port \" + str(port))\n self.relay = relay(port)\n \n def on():\n self.relay.forward()\n print (\"EL Wire on, let the awesome commence\")\n \n def off():\n self.relay.off()\n print (\"EL Wire off, let the sadness be heard\")\n\nclass speed_con:\n def __init__(self, port, jaguar, slot=4):\n print(\"speed_con obj on port \" + str(port) + \" active\")\n \n if jaguar == True:\n self.vic = wpi.Jaguar(port)\n print(\"is jaguar\\n\")\n else:\n self.vic = wpi.Victor(port)\n print(\"is victor\\n\")\n\n def set_speed(self, value):\n self.vic.Set(self.limit(value))\n \n def limit(self, n):\n if n > 1.0:\n return 1.0\n elif n < -1.0:\n return -1.0\n else:\n return n\n","sub_path":"school/FRC_2412_CODE/python_10/Heatran/outputs.py","file_name":"outputs.py","file_ext":"py","file_size_in_byte":6823,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"510461334","text":"import os\nimport sys\nfrom datetime import datetime\n\nimport PIL\nimport PIL.ImageEnhance\nimport pydub\nimport pydub.playback\nimport pytesseract\nimport requests\nfrom werkzeug import urls\n\nimport picamera\n\n\ndef take_picture(file_name):\n '''\n Capture an image\n '''\n\n # create camera object\n c = picamera.PiCamera()\n\n c.capture('{}.png'.format(file_name))\n\n # destro camera object\n c.close()\n\n print('[take_picture] image captured, file_name: {}.png'.format(file_name))\n\n\ndef ocr_image(file_name):\n '''\n Extract text from an image\n '''\n # load image from file\n img = PIL.Image.open('{}.png'.format(file_name))\n\n # crop image\n crop = img.crop((300,300,1600,800))\n print('[orc_image] Image cropped')\n\n # enhance contrast\n enhanced = PIL.ImageEnhance.Contrast(crop).enhance(1.4)\n print('[orc_image] Image contrast enhanced')\n\n # save enhanced image\n enhanced.save('{}-cropped-enhanced.png'.format(file_name))\n\n # extract text\n txt = pytesseract.image_to_string(enhanced)\n\n print('[orc_image] text extracted: {}'.format(txt))\n\n return txt\n\n\ndef text_to_audio(txt, file_name):\n '''\n Send text to google, and get back an mp3 file with that text pronounced\n '''\n\n # types of audio we can accept\n types = [\n 'audio/mpeg', 'audio/x-mpeg', 'audio/mp3', 'audio/x-mp3',\n 'audio/mpeg3', 'audio/x-mpeg3', 'audio/mpg', 'audio/x-mpg',\n 'audio/x-mpegaudio', 'application/octet-stream', 'audio/mpegurl',\n 'audio/mpeg-url', 'audio/x-mpegurl', 'audio/x-scpls', 'audio/scpls',\n 'application/pls', 'application/x-scpls', 'application/pls+xml', '*/*'\n ]\n\n # parameters we need to send to google \n # parameter 'q' will contain the text we want to be pronounced\n query = {'ie': 'UTF-8', 'client': 'tw-ob', 'q': txt, 'tl': 'En-us'}\n\n # the url we need to access to get text converted into audio\n url = urls.URL(scheme='http',\n netloc='translate.google.com',\n path='/translate_tts',\n query=urls.url_encode(query),\n fragment='')\n\n print('[text_to_audio] google url: {}'.format(url))\n\n response = requests.get(\n url,\n headers={\n # what application google should think we are using\n 'User-Agent': 'mpg123/1.25.10',\n # audio types\n 'Accept': ','.join(types)\n })\n\n print('[text_to_audio] response from google: {}'.format(response.status_code))\n\n # open a new file in binary mode, and save the audio\n with open('{}.mp3'.format(file_name), 'wb') as out_file:\n out_file.write(response.content)\n\n print('[text_to_audio] audio saved as: {}.mp3'.format(file_name))\n\ndef play_audio(file_name):\n\n # verify that file exists and is a file\n if os.path.isfile('{}.mp3'.format(file_name)):\n # play the file\n print('[play_audio] Playing audio file')\n sound = pydub.AudioSegment.from_mp3('{}.mp3'.format(file_name))\n pydub.playback.play(sound)\n else:\n print('[play_audio] {}.mp3 is not a valid file'.format(file_name))\n\n\ndef main():\n\n print('Hello')\n\n # creates a unique timestamp string, which will be used as a file name\n file_name = datetime.strftime(datetime.now(), '%m%d%y_%H%M%S')\n\n take_picture(file_name)\n\n txt = ocr_image(file_name)\n\n text_to_audio(txt, file_name)\n\n play_audio(file_name)\n\n print('Goodbye')\n\nif __name__ == '__main__':\n main()\n","sub_path":"cjack.py","file_name":"cjack.py","file_ext":"py","file_size_in_byte":3490,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"497140778","text":"from calculator import *\n\nerror_msg = 'Invalid choice!'\nget_menu()\n\nwhile True:\n print ('Type the corresponding number for calculation or type 0 to quit: ') \n operator = input()\n try:\n operator = int(operator)\n \n if operator == 0: \n print ('Quit programme') \n break\n \n elif operator == 1:\n num1 = getnuminput('Enter the first number: ') \n num2 = getnuminput('Enter the second number: ') \n result = add(num1, num2)\n print ('{} + {} = {}' .format(num1, num2, result))\n \n elif operator == 2:\n num1 = getnuminput('Enter the first number: ') \n num2 = getnuminput('Enter the second number: ') \n result = subtract(num1, num2)\n print ('{} - {} = {}' .format(num1, num2, result))\n \n elif operator == 3:\n num1 = getnuminput('Enter the first number: ') \n num2 = getnuminput('Enter the second number: ') \n result = multiply(num1, num2)\n print ('{} * {} = {}' .format(num1, num2, result))\n \n elif operator == 4:\n num1 = getnuminput('Enter the first number: ') \n num2 = getnuminput('Enter the second number: ') \n result = division(num1, num2)\n print ('{} / {} = {}' .format(num1, num2, result))\n \n elif operator == 5:\n num1 = getnuminput('Enter the first number: ') \n num2 = getnuminput('Enter the second number: ') \n result = exponent(num1, num2)\n print ('{} ^ {} = {}' .format(num1, num2, result))\n \n elif operator == 6:\n num1 = getnuminput('Enter number: ') \n result = factorial_(num1)\n print ('{}! = {}' .format(num1, result))\n \n elif operator == 7:\n num1 = getnuminput('Enter number: ') \n result = sqrt(num1)\n print ('Square root = {}' .format(result))\n \n elif operator == 8:\n num1 = getnuminput('Enter angle in radians: ') \n result = sine(num1)\n print ('Sine = ', round(result,4)) \n \n elif operator == 9:\n num1 = getnuminput('Enter angle in radians: ') \n result = cosine(num1)\n print ('Cosine = ', round(result,4))\n \n elif operator == 10:\n num1 = getnuminput('Enter angle in radians: ') \n result = tangent(num1)\n print ('Tangent = ', round(result,4))\n else: \n print (error_msg)\n except:\n print (error_msg)\n \n\n\n\n","sub_path":"CalculatorCA1/calculatorApp.py","file_name":"calculatorApp.py","file_ext":"py","file_size_in_byte":2684,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"645906102","text":"# all prints() are used in console testing, delete/comment while in production \n\nimport feedparser, nltk, tweepy, json, time\nfrom pyshorteners import Shortener\n\nused_file = 'used_links_list.json'\n\n#Erasing [used links] in json in testing mode, comment when no need\nused_links = []\nwith open(used_file, 'w') as used:\n json.dump(used_links, used)\n\n# Insert rss feed url\nfeed = ['https://foo.bar.foo.bar', \\\n 'https://foo.bar.foo.bar', \\\n 'https://foo.bar.foo.bar',\n ]\n\n#Parsing a news title by iterating news feeds\nwhile True:\n #Parsing news feeds \n for k in range(len(feed)): \n d = feedparser.parse(feed[k])\n # TODO: COUNT TITLES IN FEED\n n_titles = len(d['entries'])\n for i in range(n_titles): # SOME FEEDS ARE LESS THAN fixed no of TITLES CAUSING ERROR !!!!! hence COUNT TITLES IN FEEDS\n\n # Loading json with used links\n with open(used_file) as used:\n used_links = json.load(used)\n\n #Parsing a link from title \n url = d.entries[i].link\n\n # Adding used 'link' to a json list to exclude used news \n## with open(used_file) as open_json:\n## links_old = json.load(open_json)\n if url not in used_links:\n used_links.append(url)\n with open(used_file, 'w') as used:\n json.dump(used_links, used)\n print('dump saved')\n\n # Parsing title \n post1 = d.entries[i].title\n\n # Inserting hashtags afore title nouns; ******magic******\n toks = nltk.word_tokenize(post1)\n tags = nltk.pos_tag(toks)\n # 1stly make list from tuples\n tags_list = [list(elem) for elem in tags] \n for t in tags_list:\n if t[1] in ['NN', 'NNP']: \n t[0] = '#' + t[0]\n t[1] = ''\n \n post2 = ' '.join([''.join(elem) for elem in tags_list])\n #print(post2) \n\n # Shortening url\n while True:\n api_key = 'api_key'\n shortener = Shortener('Google', api_key=api_key)\n short_link = shortener.short(url)\n if short_link:\n print('link OK')\n break\n\n #Building final post \n post3 = post2 + ' ' + short_link\n if 139 > len(post3) > 40: \n print('post composed, waitin 10 sec then tweeting:', post3)\n\n time.sleep(10)\n \n \n #Tweeting\n while True:\n try:\n CONSUMER_KEY = 'YOUR_KEY'\n CONSUMER_SECRET = 'CONSUMER_SECRET'\n ACCESS_KEY = ' ACCESS_KEY'\n ACCESS_SECRET = 'ACCESS_SECRET'\n auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)\n auth.set_access_token(ACCESS_KEY, ACCESS_SECRET)\n api = tweepy.API(auth)\n tweeted = api.update_status(post3)\n if tweeted:\n print('tweeted!')\n break\n except:\n print('tweepy error, sleepin 3 min')\n time.sleep(180)\n\n else:\n print('no news') \n \n print('Waiting 5 sec for the next cycle') \n time.sleep(5)\n\n","sub_path":"z_feed.py","file_name":"z_feed.py","file_ext":"py","file_size_in_byte":3802,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"119741648","text":"'''\nWrite a class to model a car. The class should:\n\n1. Set the attributes model, year, and max_speed in the __init__() method.\n2. Have a method that increases the max_speed of the car by 5 when called.\n3. Have a method that prints the details of the car.\n\nCreate at least two different objects of this Car class and demonstrate\nchanging the objects attributes.\n\n'''\n\nclass Car:\n def __init__(self, model, year, max_speed):\n self.name = model\n self.year=year\n self.speed=max_speed\n\n def accelerate(self):\n self.speed += 5\n return self.speed\n\n def __str__ (self):\n return f\"The car is a {self.year} {self.name} with a max speed of {self.speed} mph\"\n\nx=Car(\"Honda\", 2016, 140)\nprint(x)\ny=Car(\"Lexus\", 2020, 180)\nprint(y)\nx.accelerate()\ny.accelerate()\nprint(x,y)\n","sub_path":"07_classes_objects_methods/07_01_car.py","file_name":"07_01_car.py","file_ext":"py","file_size_in_byte":809,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"16981711","text":"# Write a function that takes a 2D binary array and\n# returns the number of 1 islands.\n# An island consists of 1s that are connected to the \n# north, south, east or west. For example:\n\nislands = [[0, 1, 0, 1, 0],\n [1, 1, 0, 1, 1],\n [0, 0, 1, 0, 0],\n [1, 0, 1, 0, 0],\n [1, 1, 0, 0, 0],\n [0, 0, 0, 0, 0]]\n\n# island_counter(islands) -> returns 4\n\n# 1. Translate the problem into graph terminology\n# 2. Build your graph\n# 3. Traverse your graph\n\n\ndef islands_counter(matrix):\n # Traverse nodes\n visited = []\n island_counter = 0\n for i in range(len(matrix)):\n visited.append([False] * len(matrix[0]))\n\n for col in range(len(matrix[0])):\n for row in range(len(matrix)):\n # if node not visited\n if not visited[row][col]:\n # if we hit a 1:\n if matrix[row][col] == 1:\n # mark visited\n # increment visited count\n visited = dft(row, col, matrix, visited)\n # traverse all connected nodes, mark as visited\n island_count += 1\n","sub_path":"projects/islands.py","file_name":"islands.py","file_ext":"py","file_size_in_byte":1138,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"189188257","text":"# -*- coding: utf-8 -*-\n# Part of Odoo. See LICENSE file for full copyright and licensing details.\n\nimport logging\nimport pprint\nimport werkzeug\n\nfrom odoo import http\nfrom odoo.http import request\nfrom odoo.addons.website_sale.controllers.main import WebsiteSale\n\n_logger = logging.getLogger(__name__)\n\n\nclass mygateController(http.Controller):\n @http.route(['/payment/mygate/return', '/payment/mygate/cancel', '/payment/mygate/error'], type='http', auth='public', csrf=False)\n def payu_return(self, **post):\n \"\"\" mygate.\"\"\"\n _logger.info(\n 'mygate: entering form_feedback with post data %s', pprint.pformat(post))\n return_url = '/'\n if post.get('_RESULT') == '0':\n return_url = '/shop/confirmation'\n if post:\n request.env['payment.transaction'].sudo().form_feedback(post, 'mygate')\n return werkzeug.utils.redirect(return_url)\n\n @http.route(['/shop/confirmation'], type='http', auth=\"public\", website=True)\n def payment_confirmation(self, **post):\n \"\"\" End of checkout process controller. Confirmation is basically seing\n the status of a sale.order. State at this point :\n\n - should not have any context / session info: clean them\n - take a sale.order id, because we request a sale.order and are not\n session dependant anymore\n \"\"\"\n sale_order_id = request.session.get('sale_last_order_id')\n if sale_order_id:\n order = request.env['sale.order'].sudo().browse(sale_order_id)\n if not order or order.state != 'draft':\n request.website.sale_reset()\n return request.render(\"website_sale.confirmation\", {'order': order})\n else:\n return request.redirect('/shop')\n","sub_path":"payment_mygate/controllers/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1771,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"570667638","text":"#!/usr/bin/env python3\n\n# Read input from file\nwith open(\"puzzle_input.txt\") as file:\n input = file.read()\n\nturn = 1\nspoken_nums = dict()\n\n# Load starting numbers\nfor starting_num in input.split(\",\"):\n spoken_nums[int(starting_num)] = list()\n spoken_nums[int(starting_num)].append(turn)\n turn += 1\n\nprev_num = int(starting_num)\n\nwhile turn <= 30000000:\n # Check if first time number is spoken\n if len(spoken_nums[prev_num]) == 1:\n spoken_nums[0].append(turn)\n prev_num = 0\n\n # Announce how many turns apart the number is from when it was previously spoken\n else:\n diff = spoken_nums[prev_num][-1] - spoken_nums[prev_num][-2]\n\n if diff not in spoken_nums:\n spoken_nums[diff] = list()\n\n spoken_nums[diff].append(turn)\n prev_num = diff\n\n turn += 1\n\nprint(prev_num)","sub_path":"2020/Day15/15B.py","file_name":"15B.py","file_ext":"py","file_size_in_byte":841,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"555346248","text":"import praw\nimport datetime as dt\nfrom psaw import PushshiftAPI\nimport csv\n\n\nreddit = praw.Reddit(client_id='cicJG0jkrjc63g',\n client_secret='85Rd8G3iQL7TVkQ2elKwlH512KVqBQ',\n user_agent='stocks',\n username='ilanbeast',\n password='roeinoob')\n\n\napi = PushshiftAPI(reddit)\nsubreddit = 'Stocks'\nsubreddit = reddit.subreddit(subreddit)\n# start_date = int(dt.datetime(2019, 3, 17).timestamp())\n# end_date = int(dt.datetime(2020, 9, 17).timestamp())\n# filename = 'train.csv'\nstart_date = int(dt.datetime(2020, 9, 18).timestamp())\nend_date = int(dt.datetime(2021, 3, 17).timestamp())\nfilename = '_.csv'\ntopics_dict = {\"title\": [],\n \"score\": [],\n \"id\": [],\n \"num_comments\": [],\n \"timestamp\": [],\n \"body\": []}\n\nwith open(filename, 'w', encoding='utf8') as f:\n writer = csv.writer(f)\n writer.writerow(['title', 'score', 'id', 'num_comments', 'timestamp', 'body'])\n for submission in api.search_submissions(after=start_date,\n before=end_date,\n subreddit=subreddit):\n try:\n flair = submission.link_flair_text\n except KeyError:\n flair = \"NaN\"\n\n writer.writerow([\n submission.title,\n submission.score,\n submission.id,\n submission.num_comments,\n dt.datetime.fromtimestamp(submission.created),\n submission.selftext\n ])\n","sub_path":"reddit_crawler.py","file_name":"reddit_crawler.py","file_ext":"py","file_size_in_byte":1594,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"379442203","text":"import os\n\nimport pytest\n\nfrom django.conf import settings\n\nfrom factories.factory_projects import ProjectFactory\nfrom factories.factory_repos import RepoFactory\nfrom libs.paths.utils import copy_to_tmp_dir, get_tmp_path\nfrom tests.utils import BaseTest\n\n\n@pytest.mark.paths_mark\nclass TestCopyPaths(BaseTest):\n def test_copy_repo_path_to_tmp_dir(self):\n project = ProjectFactory()\n repo_path = '{}/{}/{}/{}'.format(settings.REPOS_MOUNT_PATH,\n project.user.username,\n project.name,\n project.name)\n self.assertFalse(os.path.exists(repo_path))\n\n repo = RepoFactory(project=project)\n assert repo.path == repo_path\n self.assertTrue(os.path.exists(repo_path))\n git_file_path = '{}/.git'.format(repo_path)\n self.assertTrue(os.path.exists(git_file_path))\n\n copy_to_tmp_dir(repo_path, 'new')\n git_file_path = '{}/.git'.format(get_tmp_path('new'))\n self.assertTrue(os.path.exists(git_file_path))\n","sub_path":"tests/test_paths/test_copy_paths.py","file_name":"test_copy_paths.py","file_ext":"py","file_size_in_byte":1087,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"557989061","text":"#Program 1\nq = input(\"pick a number.\")\nq = int(q)\nm = 2\nflag=0\nwhile(m < q):\n if(q % m ==0):\n flag = 1\n m = m+1\n\nif (flag==0):\n print(\"This number is a prime.\")\nelse:\n print (\"This number is not a prime\")\n\n \n#Program 2\na = int(input(\"Enter the base of your traingle in cm.\"))\nb = int(input(\"enter the height of your triangle in cm.\"))\narea = (a*b)/2\nprint(area)\n#Program 3\n#Armstrong Numbers between a range\nlower = 100\nupper = 500\nfor num in range(lower, upper + 1):\n order = len(str(num))\n sum = 0\n temp = num\n while temp > 0:\n digit = temp % 10\n sum += digit ** order\n temp //= 10\n if num == sum:\n print(num)\n\n#Armstrong Number with Classes\n\nclass Armstrong:\n def __init__(self,lower,upper):\n self.lower = lower\n self.upper = upper\n def strongnumbers(self):\n for num in range(self.lower, self.upper + 1):\n order = len(str(num))\n sum = 0\n temp = num\n while temp > 0:\n digit = temp % 10\n sum += digit ** order\n temp //= 10\n if num == sum:\n print(num)\na=Armstrong(100,500)\na.strongnumbers()\n\n\n\n\n\n \n","sub_path":"Homework real 2019/Homework 112619.py","file_name":"Homework 112619.py","file_ext":"py","file_size_in_byte":1163,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"157455311","text":"#!/usr/bin/env python3\n\nfrom pwn import *\n\n# Print byte array as hex string \"\\x..\\x..\\x..\"\ndef print_byte_array(prefix, array):\n log.info(\"{}: {}\".format(prefix, \"\".join(\"\\\\x{:02x}\".format(array[i]) for i in range(0, len(array)))))\n\n\n# Change to 'debug' for extensive information on classes used.\ncontext.log_level = 'info'\n\nfilename = \"../src/vuln64\"\ne = ELF(filename)\ncontext.binary = filename\n#context.arch = \"amd64\"\ndiablo_address = e.symbols[b\"diablo\"]\noverwatch_address = e.symbols[b\"overwatch\"]\nwarcraft_address = e.symbols[b\"warcraft\"]\nstarcraft_address = e.symbols[b\"starcraft\"]\npop_rdi_ret_gadget_address = 0x0000000000400713\npop_rsi_r15_gadget_address = 0x0000000000400711\n\nprint(\"diablo: 0x{:016x}\".format(diablo_address))\nprint(\"warcraft: 0x{:016x}\".format(warcraft_address))\nprint(\"overwatch: 0x{:016x}\".format(overwatch_address))\nprint(\"starcraft: 0x{:016x}\".format(starcraft_address))\n\n# buffer is at rbp-0x40\n# return address is at rbp+0x8\noffset = 0x48\n#payload = offset * b\"A\" + pack(warcraft_address)\n#payload = offset * b\"A\" + pack(pop_rdi_ret_gadget_address) + pack(0xdeadbeef) + pack(overwatch_address)\npayload = offset * b\"A\" + pack(pop_rdi_ret_gadget_address) + pack(0x12345678) + pack(pop_rsi_r15_gadget_address) + pack(0xaabbccdd) + pack(0) + pack(diablo_address)\n\n# It won't work. Payload is too large.\n#payload = offset * b\"A\" + pack(pop_rdi_ret_gadget_address) + pack(0xdeadbeef) + pack(overwatch_address) + pack(pop_rdi_ret_gadget_address) + pack(0x12345678) + pack(pop_rsi_r15_gadget_address) + pack(0xaabbccdd) + pack(0) + pack(diablo_address)\n\n\"\"\"\n\n----\nbufffer\n....\n....\n-----\nsaved rbp\n-----\npop_rdi_ret -----> pop rdi (mov rdi, [rsp] + add rsp, 8) ret\n-----\n0x000000000deadbeef (pop rdi)\n-----\noverwatch_address (ret)\n-----\n\"\"\"\n\nprint_byte_array(\"payload\", payload)\n\np = process(filename)\np.readline()\np.sendline(payload)\np.interactive()\n","sub_path":"return-oriented-programming/activities/00-demo/sol/exploit64.py","file_name":"exploit64.py","file_ext":"py","file_size_in_byte":1906,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"335118536","text":"\"\"\"\"\nThis is a simulation problem. Because the problem guarantees that it is always possible to win,\nwe know that our input will never contain consecutive thunderclouds.\nTo reach the last cloud in a minimum number of steps, always try make a jump from i to i+2 .\nIf that is not possible, jump to i+1.\n\n\n\njumpingOnClouds has the following parameter(s):\n c: an array of binary integers\n - Function Description: Complete the jumpingOnClouds function in the editor below.\n It should return the minimum number of jumps required, as an integer.\n\"\"\"\n\n#!/bin/python3\n\nimport math\nimport os\nimport random\nimport re\nimport sys\n\n# Complete the jumpingOnClouds function below.\ndef jumpingOnClouds(c):\n # Assuming there is always a posibility to jump\n n = len(c)\n i = 0\n jumps = 0\n\n while i < n - 1:\n if i + 2 >= n or c[i + 2] == 1:\n i += 1\n jumps += 1\n else:\n i += 2\n jumps += 1\n return jumps\n\ndef jumpingOnClouds(c, n):\n jumps = [1] * n\n jumps[0] = 0\n if c[1] == 0: jumps[1] = 1\n for i in range(2, n):\n if c[i] == 0: jumps[i] = min(jumps[i - 1], jumps[i - 2]) + 1\n print(jumps[n - 1])\n\nif __name__ == '__main__':\n # The first line contains an integer n, the total number of clouds\n n = int(input())\n # The second line contains space-separated binary integers describing clouds c[i] where 0<=i<=n\n c = list(map(int, input().rstrip().split()))\n\n result = jumpingOnClouds(c,n)\n\n print(result)\n","sub_path":"5-JumpingOnClouds.py","file_name":"5-JumpingOnClouds.py","file_ext":"py","file_size_in_byte":1529,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"246928973","text":"import uuid\n\n# Opens a file and adds random string to the start of each line. Aadds as\n# to make it as valid python variable. Created for testing the number of\n# fields Django can support, and worked well with 500+ fields, left cux\n# my hands are paining of typing random to fill the forms.as well Django Rockz\n\n\n# opens the file random.txt and write to the file test.txt\n\n\na = open('test.txt', 'w')\n\n\ndef my_random_string(string_length=10):\n\t\"\"\"Returns a random string of length string_length.\"\"\"\n\trandom = str(uuid.uuid4())\n\trandom = random.upper()\n\trandom = random.replace(\"-\", \"\")\n\treturn random[0:string_length]\n\n\nwith open('random.txt') as f:\n\tfor line in f:\n\t\ta.write(\"a\" + my_random_string(6) + line)\n\n\n\t\t# close the file;","sub_path":"Projects/randomadder/randomadder.py","file_name":"randomadder.py","file_ext":"py","file_size_in_byte":730,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"20046096","text":"import socket;\nimport _thread;\nimport time;\nimport multiprocessing;\nimport queue;\nimport sys\n\nresults = multiprocessing.Queue();\n\ndef config_server():\n s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM);\n host = socket.gethostname();\n port = read_port();\n return s,host,port;\n\ndef read_port():\n config_file = open('server_config','r');\n port = int(config_file.read().split(':')[1]);\n config_file.close();\n return port;\n\ndef console(s,host,port):\n while True:\n command = input('> ');\n s.sendto(command.encode(), (host, port))\n\ndef main():\n s,host,port = config_server();\n _thread.start_new_thread(console,(s,host,port));\n while True:\n result, addr = s.recvfrom(4096);\n sys.stdout.write('[SERVER MESSAGE] ' + result.decode() + \"\\n> \")\n\nif __name__ == \"__main__\":\n main();\n","sub_path":"projeto1/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":839,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"571114094","text":"import time\nfrom .convert import convert_pyomo2LinearBilevelProblem\nimport pao.common\nimport pao.lbp\n\n\nSolverFactory = pao.common.SolverFactory \n\n\nclass PyomoSubmodelSolverBase(pao.common.Solver):\n \"\"\"\n Define the API for solvers that optimize a Pyomo model using SubModel components\n \"\"\"\n\n def __init__(self, name):\n super().__init__()\n self.name = name\n\n def check_model(self, lbp): # pragma: no cover\n #\n # Confirm that the problem is well-formed\n #\n pass\n\n def solve(self, *args, **kwds): # pragma: no cover\n #\n # Solve the Pyomo model\n #\n pass\n\n\nclass PyomoSubmodelSolverBase_LBP(PyomoSubmodelSolverBase):\n \"\"\"\n Define the API for solvers that optimize a Pyomo model using SubModel components\n \"\"\"\n\n def __init__(self, name, lbp_solver, inequalities):\n super().__init__(name)\n self.lbp_solver = lbp_solver\n self.inequalities = inequalities\n\n def inequalities(self):\n #\n # Return True if the conversion to LinearBilevelProblem should\n # use inequalities (True) or equalities (False)\n #\n return False\n\n def solve(self, instance, options=None, **config_options):\n #\n # Process keyword options\n #\n self._update_config(config_options)\n #\n # Start the clock\n #\n start_time = time.time()\n #\n # Convert the Pyomo model to a LBP\n #\n try:\n lbp, soln_manager = convert_pyomo2LinearBilevelProblem(instance)\n except RuntimeError as err:\n print(\"Cannot convert Pyomo model to a LinearBilevelProblem\")\n raise\n #\n results = PyomoSubmodelResults(solution_manager=soln_manager)\n with SolverFactory(self.lbp_solver) as opt:\n lbp_results = opt.solve(lbp, options=options, \n tee=self.config.tee,\n time_limit=self.config.time_limit,\n load_solutions=True)\n\n #print(lbp_results)\n #print(\"ID\",id(lbp))\n #lbp.print()\n self._initialize_results(results, lbp_results, instance, lbp, options)\n results.solver.rc = getattr(opt, '_rc', None)\n results.copy_from_to(lbp=lbp, pyomo=instance)\n \n results.solver.wallclock_time = time.time() - start_time\n return results\n\n def _initialize_results(self, results, lbp_results, instance, lbp, options):\n #\n # SOLVER\n #\n solv = results.solver\n solv.name = self.lbp_solver\n solv.config = self.config\n solv.solver_options = options\n solv.termination_condition = lbp_results.solver.termination_condition\n solv.solver_time = lbp_results.solver.time\n solv.best_feasible_objective = lbp_results.solver.best_feasible_objective\n #\n # PROBLEM\n #\n prob = results.problem\n prob.name = instance.name\n prob.number_of_constraints = instance.statistics.number_of_constraints\n prob.number_of_variables = instance.statistics.number_of_variables\n prob.number_of_binary_variables = instance.statistics.number_of_binary_variables\n prob.number_of_integer_variables = instance.statistics.number_of_integer_variables\n prob.number_of_continuous_variables = instance.statistics.number_of_continuous_variables\n prob.number_of_objectives = instance.statistics.number_of_objectives\n prob.lower_bound = lbp_results.problem.lower_bound\n prob.upper_bound = lbp_results.problem.upper_bound\n prob.sense = lbp_results.problem.sense\n\n return results\n\n\nclass PyomoSubmodelResults(pao.common.Results):\n\n def __init__(self, solution_manager=None):\n super(pao.common.Results, self).__init__()\n self._solution_manager=solution_manager\n\n def copy_from_to(self, **kwds):\n self._solution_manager.copy_from_to(**kwds)\n\n def load_from(self, data): # pragma: no cover\n assert (False), \"load_from() is not implemented\"\n self._solution_manager.load_from(data)\n\n","sub_path":"pao/bilevel/solver.py","file_name":"solver.py","file_ext":"py","file_size_in_byte":4196,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"548276404","text":"from nistbeacon import NistBeacon\nimport time\n\nprint()\nprint('Coin flip 0 or 1 tails or heads')\nprint()\nprint('Run five times')\n\nfor count in range(5):\n time.sleep(66) # wait for new beacon every 66 seconds\n h = NistBeacon.get_last_record()\n v = h.output_value # 512 hex\n d = int(v, 16) # convert to decimal\n coin = d % 2 # modulus of record (0 or 1)\n\n if coin == 0:\n print('tails')\n else:\n print('heads')\n","sub_path":"Chapter 2 - Advanced Basics/coin-flip.py","file_name":"coin-flip.py","file_ext":"py","file_size_in_byte":445,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"125385718","text":"from tensorflow.keras.layers import BatchNormalization, Activation, LeakyReLU, Add, Dense, PReLU, Flatten, Conv2D, UpSampling2D\nfrom tensorflow.keras.models import Model\nfrom ResLayer import ResLayer\n\nclass Generator(Model):\n def __init__(self,\n residual_blocks=16,\n momentum=0.8,\n **kwargs\n ):\n # call the parent constructor\n super(Generator, self).__init__(**kwargs)\n\n ###############\n # HyperParams #\n ###############\n self.residual_blocks = residual_blocks\n self.momentum = momentum\n\n #############\n # Generator #\n #############\n # feed in layer\n self.conv2a = Conv2D(filters=64,\n kernel_size=9,\n strides=1,\n padding='same',\n activation='relu')\n\n # res blocks #\n self.res1 = ResLayer(kernel_size=3,\n filters=[64, 64],\n strides=1,\n momentum=momentum)\n self.resblocks = []\n for i in range(residual_blocks - 1):\n self.resblocks.append(ResLayer(kernel_size=3,\n filters=[64, 64],\n strides=1,\n momentum=momentum))\n\n # post res blocks #\n self.con2b = Conv2D(filters=64,\n kernel_size=3,\n strides=1,\n padding='same')\n\n self.bn1 = BatchNormalization(momentum=momentum)\n self.upspl1 = UpSampling2D(size=2)\n self.conv2c = Conv2D(filters=256, kernel_size=3, strides=1, padding='same')\n self.activation1 = Activation('relu')\n\n self.upspl2 = UpSampling2D(size=2)\n self.conv2d = Conv2D(filters=256, kernel_size=3, strides=1, padding='same')\n self.activation2 = Activation('relu')\n\n # output uses tanh as output activation #\n self.conv2e = Conv2D(filters=3, kernel_size=9, strides=1, padding='same')\n self.activation3 = Activation('tanh')\n\n def call(self, inputs):\n\n #############\n # Generator #\n #############\n gen1 = self.conv2a(inputs)\n x = self.res1(gen1)\n\n # pass through all resblocks #\n for r in self.resblocks:\n x = r(x)\n\n # post res blocks #\n x = self.con2b(x)\n gen2 = self.bn1(x)\n\n # take the sum of the output from the pre-residual block,\n # and the output from the post-residual block\n x = Add()([gen2, gen1])\n\n # upsample 1\n x = self.upspl1(x)\n x = self.conv2c(x)\n x = self.activation1(x)\n\n # upsample 2\n x = self.upspl2(x)\n x = self.conv2d(x)\n x = self.activation2(x)\n\n # output\n x = self.conv2e(x)\n return self.activation3(x)","sub_path":"Models/SR_GAN/Generator.py","file_name":"Generator.py","file_ext":"py","file_size_in_byte":2986,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"136556361","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Oct 15 15:15:54 2019\n\n@author: 20171880\n\"\"\"\n\nfrom builtins import print\nimport numpy as np\nimport cad_util as util\nimport segmentation_util as seg_util\nimport registration as reg\nimport segmentation as seg\nimport matplotlib.pyplot as plt\nimport cad\nfrom IPython.display import display, clear_output, HTML\n\n\n\n \n# dataset preparation\nnum_training_samples = 300\nnum_validation_samples = 100\n\n# here we reuse the function from the segmentation practicals\nm1=[2,3]\nm2=[-0,-4]\ns1=[[8,7],[7,8]]\ns2=[[8,6],[6,8]]\n\n[trainingX, trainingY] = seg.generate_gaussian_data(num_training_samples, m1, m2, s1, s2)\nr,c = trainingX.shape\nprint('Training sample shape: {}'.format(trainingX.shape))\n\n# we need a validation set to monitor for overfitting\n[validationX, validationY] = seg.generate_gaussian_data(num_validation_samples, m1, m2, s1, s2)\nr_val,c_val = validationX.shape\nprint('Validation sample shape: {}'.format(validationX.shape))\n\nvalidationXones = util.addones(validationX)\n\n# train a logistic regression model:\n# the learning rate for the gradient descent method\n# (the same as in intensity-based registration)\nmu = 0.001\n\n# we are actually using stochastic gradient descent\nbatch_size = 30\n\n# initialize the parameters of the model with small random values,\n# we need one parameter for each feature and a bias\nTheta = 0.02*np.random.rand(c+1, 1)\n\n# number of gradient descent iterations\nnum_iterations = 300\n\n# variables to keep the loss and gradient at every iteration\n# (needed for visualization)\niters = np.arange(num_iterations)\nloss = np.full(iters.shape, np.nan)\nvalidation_loss = np.full(iters.shape, np.nan)\n\n# Create base figure\nfig = plt.figure(figsize=(15,8))\nax1 = fig.add_subplot(121)\nim1, Xh_ones, num_range_points = util.plot_lr(trainingX, trainingY, Theta, ax1)\nseg_util.scatter_data(trainingX, trainingY, ax=ax1)\nax1.grid()\nax1.set_xlabel('x_1')\nax1.set_ylabel('x_2')\nax1.legend()\nax1.set_title('Training set')\ntext_str1 = '{:.4f}; {:.4f}; {:.4f}'.format(0, 0, 0)\ntxt1 = ax1.text(0.3, 0.95, text_str1, bbox={'facecolor': 'white', 'alpha': 1, 'pad': 10}, transform=ax1.transAxes)\n\nax2 = fig.add_subplot(122)\nax2.set_xlabel('Iteration')\nax2.set_ylabel('Loss (average per sample)')\nax2.set_title('mu = '+str(mu))\nh1, = ax2.plot(iters, loss, linewidth=2, label='Training loss')\nh2, = ax2.plot(iters, validation_loss, linewidth=2, label='Validation loss')\nax2.set_ylim(0, 0.7)\nax2.set_xlim(0, num_iterations)\nax2.grid()\nax1.legend()\n\ntext_str2 = 'iter.: {}, loss: {:.3f}, val. loss: {:.3f}'.format(0, 0, 0)\ntxt2 = ax2.text(0.3, 0.95, text_str2, bbox={'facecolor': 'white', 'alpha': 1, 'pad': 10}, transform=ax2.transAxes)\n\n# iterate\nfor k in np.arange(num_iterations):\n \n # pick a batch at random\n idx = np.random.randint(r, size=batch_size)\n \n # the loss function for this particular batch\n loss_fun = lambda Theta: cad.lr_nll(util.addones(trainingX[idx,:]), trainingY[idx], Theta)\n \n # gradient descent:\n # here we reuse the code for numerical computation of the gradient\n # of a function\n Theta = Theta - mu*reg.ngradient(loss_fun, Theta)\n \n # compute the loss for the current model parameters for the\n # training and validation sets\n # note that the loss is divided with the number of samples so\n # it is comparable for different number of samples\n loss[k] = loss_fun(Theta)/batch_size\n validation_loss[k] = cad.lr_nll(validationXones, validationY, Theta)/r_val\n \n # upldate the visualization\n ph = cad.sigmoid(Xh_ones.dot(Theta)) > 0.5\n decision_map = ph.reshape(num_range_points, num_range_points)\n decision_map_trns = np.flipud(decision_map)\n im1.set_data(decision_map_trns)\n text_str1 = '{:.4f}; {:.4f}; {:.4f}'.format(Theta[0,0], Theta[1,0], Theta[2,0])\n txt1.set_text(text_str1)\n h1.set_ydata(loss)\n h2.set_ydata(validation_loss)\n text_str2 = 'iter.={}, loss={:.3f}, val. loss={:.3f} '.format(k, loss[k], validation_loss[k])\n txt2.set_text(text_str2)\n \n \n display(fig)\n clear_output(wait = True)\n","sub_path":"code/logistic_regression_test.py","file_name":"logistic_regression_test.py","file_ext":"py","file_size_in_byte":4066,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"111057249","text":"\"\"\"Functions to do reddit authentication, file saving and loading, and data structure printing,\nand varialbes used by multiple files.\"\"\"\n\nimport pickle\nimport praw\nimport os\nimport warnings\n\n# use this to set up PRAW for the first time\n# reddit = praw.Reddit(user_agent = 'desktop:ucsc-class-info-bot:v0.0.1 (by /u/ucsc-class-info-bot)',\n# site_name = 'ucsc_bot')\n\n# _get_code()\n# _save_access_information()\n\n# widths of column for printing tables to console. used by trunc_pad()\n_column_widths = {'num': 2,\n \"id\": 7,\n \"author\": 15,\n \"title\": 35,\n \"action\": 17}\n\n\nclass ExistingComment:\n \"\"\"Info about an existing comment with class info.\"\"\"\n\n def __init__(self, comment_id_, mentions_):\n self.comment_id = comment_id_\n self.mentions_list = mentions_\n\n def __str__(self):\n return \"existing comment: {} -> {}\".format(self.comment_id, self.mentions_list)\n\n\ndef trunc_pad(string_, use_ = None):\n \"\"\"Truncates and pads with spaces string_ to be printed in a table.\n The padding width is indicated by use_. If _use isn't specifeid, the string is the use.\n\n :param string_: string to be truncated and padded\n :type string_: str\n :param use_: string identifying which column the string is in.\n :type use_: str\n :return: the input string, truncated and padded\n :rtype: str\n \"\"\"\n if use_ is None:\n use_ = string_\n width = _column_widths[use_]\n if len(string_) > width:\n return string_[:width - 3] + '...'\n else:\n return string_.ljust(width)\n\n\ndef auth_reddit():\n \"\"\"Loads access information and returns PRAW reddit api context.\n\n :return: praw instance\n :rtype praw.Reddit\n \"\"\"\n\n with warnings.catch_warnings():\n warnings.simplefilter(\"ignore\")\n red = praw.Reddit(user_agent = 'desktop:ucsc-class-info-bot:v0.0.1 (by /u/ucsc-class-info-bot)',\n site_name = 'ucsc_bot')\n\n with open('pickle/access_information.pickle', 'rb') as file:\n access_information = pickle.load(file)\n file.close()\n red.set_access_credentials(**access_information)\n return red\n\n\ndef _get_code(r_):\n \"\"\"\n Use this for first-time PRAW setup. Use this first.\n Log into /u/ucsc-class-info-bot then navigate to the url printed.\n \"\"\"\n url = r_.get_authorize_url('state', 'identity submit edit read', True)\n print(url)\n\n\ndef _save_access_information(r_):\n \"\"\"\n Use this for first-time PRAW setup. Use this second.\n Paste the code from the redirect into the function below.\n :param r_: praw instance\n :type r_:\n \"\"\"\n with open('pickle/access_information.pickle', 'wb') as file:\n pickle.dump(r_.get_access_information('code'), file)\n file.close()\n\n\ndef print_posts_with_comments(existing_posts_with_comments):\n \"\"\"Prints the dist of posts which already have comments from the bot.\n\n :param existing_posts_with_comments: the dict mapping post IDs to ExistingComment objects.\n :type existing_posts_with_comments: dict of \n \"\"\"\n for post_id, e_c_obj in sorted(existing_posts_with_comments.items()):\n print(\"in post \" + post_id + \": \" + str(e_c_obj))\n\n\ndef print_found_mentions(found_mentions):\n \"\"\"Prints the list of found mentions.\n\n :param found_mentions: list of PostWithMentions objects\n \"\"\"\n for pwm_obj in found_mentions:\n print(pwm_obj)\n\n\ndef load_posts_with_comments():\n \"\"\"Loads from disk the dict of posts that have already been commented on.\n\n :return: dict of of posts that have already been commented on\n :rtype: dict\n \"\"\"\n if not os.path.isfile(\"pickle/posts_with_comments.pickle\"):\n return dict()\n\n with open(\"pickle/posts_with_comments.pickle\", 'rb') as file:\n a_c = pickle.load(file)\n file.close()\n return a_c\n\n\ndef load_found_mentions():\n \"\"\"Loads from disk the list of found mentions from the last run of find_mentions().\n\n :return: list of PostWithMentions objects\n :rtype: list\n \"\"\"\n with open(\"pickle/found_mentions.pickle\", 'rb') as file:\n mentions = pickle.load(file)\n file.close()\n return mentions\n\n\ndef save_found_mentions(found_mentions):\n \"\"\"Saves to disk mentions found from from the last run of find_mentions().\n This is used in both post_comments.py and in mention_search_posts.py so I have put it in tools.py.\n\n :param found_mentions: list of PostWithMentions objects\n :type found_mentions: list\n \"\"\"\n with open(\"pickle/found_mentions.pickle\", 'wb') as file:\n pickle.dump(found_mentions, file)\n file.close()\n","sub_path":"tools.py","file_name":"tools.py","file_ext":"py","file_size_in_byte":4675,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"356650098","text":"def miniMaxSum(arr):\n sum = 0\n for i in range(len(arr)):\n sum = sum + arr[i]\n\n maxNum = sum - min(arr)\n minNum = sum - max(arr)\n\n print(minNum, maxNum)\n # Write your code here\n\nif __name__ == '__main__':\n arr = [1,1,0,1,2,5,6]\n print(arr)\n print(miniMaxSum(arr))","sub_path":"hr_Min-MaxSum.py","file_name":"hr_Min-MaxSum.py","file_ext":"py","file_size_in_byte":296,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"584749562","text":"'''\n获取信息:IP指纹\n使用网页爬取无需注册\n网址:https://ip.rtbasia.com/\n获取方式:网页爬取\n推荐值:70\n@author: linqingping\n备注:利用selenium配合火狐浏览器(按环境情况替换)进行验证码验证后进行信息数据查询\nCreated on 2018-5-15\n'''\n\n# -*- coding: utf-8 -*-\nimport random\nfrom lxml import etree\n\nimport scrapy\nimport json\nimport hashlib\nimport configparser\nfrom api.items import *\nimport time,datetime\nimport re\nfrom selenium import webdriver\n\n\n\n\nclass DanSpider(scrapy.Spider):\n name = 'rtbasia'\n allowed_domains = ['ip.rtbasia.com']\n custom_settings = {\n 'USER_AGENT':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36',\n 'DOWNLOADER_MIDDLEWARES': {'api.middlewares.JavaScriptMiddleware': 100, }\n }\n\n #\n def __init__(self, api=None, *args, **kwargs):\n #读取配置\n super(DanSpider, self).__init__(*args, **kwargs)\n api_list = api.split(':',1)\n #print(api_list)\n #类型\n self.type = api_list[0]\n #内容\n self.object = api_list[1]\n self.parse_map = {\n 'ip': {\n 'api_name': 'IPBasic',\n 'parse_foo': self.parse_ip,\n 'item_foo': IPBasicItem,\n 'url': 'https://ip.rtbasia.com/?ipstr=%s'\n }\n }\n\n def start_requests(self):\n for type in self.parse_map.keys():\n if self.type == type:\n item = self.parse_map[self.type]['item_foo']()\n for field in item.fields:\n item[field] = None\n # 数据类型\n item['api'] = self.parse_map[self.type]['api_name']\n # 来源网址\n item['author'] = 'dan.me'\n # apiurl\n item['apiurl'] = 'dan.me'\n url = self.parse_map[self.type]['url'] % (self.object)\n yield scrapy.Request(\n url=url,\n callback=self.parse_map[self.type]['parse_foo'],\n meta={'item':item,'object' : self.object},\n )\n\n # ip\n def parse_ip(self,response):\n if response.xpath(\".//div[@class='scoreform']/div[3]/h5/span/text()\").extract():\n country=response.xpath(\".//div[@class='scoreform']/div[3]/h5/span/a/text()\").extract()\n isp=response.xpath(\".//div[@class='scoreform']/div[3]/h5/span/text()\").extract()\n if len(isp)>1:\n isp=re.findall(\"运营商:(.*?)\\n\",isp[1])\n item = response.meta['item']\n country=re.split(\"-\",country[0])\n item['country'] =country[0]\n if country[1] and country[0]!=country[1]:\n item['region']=country[1]\n if len(country)>2:\n item['city']=country[2]\n item['isp'] = isp[0]\n item['ip'] = self.object\n item['is_effective'] = 2\n item['tlp'] = 0\n return item\n","sub_path":"API类及验证码中间件/rtbasia.py","file_name":"rtbasia.py","file_ext":"py","file_size_in_byte":3099,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"268941464","text":"from urllib.request import urlopen\nimport zipfile\nimport shutil\nimport os\nimport sys\n\ndef copy_and_overwrite(from_path, to_path):\n if os.path.exists(to_path):\n shutil.rmtree(to_path)\n shutil.copytree(from_path, to_path)\n\ndef download_to_file(src_url, dest_filepath):\n response = urlopen(src_url)\n data = response.read()\n\n # Write data to file\n file_ = open(dest_filepath, 'wb')\n file_.write(data)\n file_.close()\n\ndef unzip_file(src_filepath, dest_filepath):\n zip_ref = zipfile.ZipFile(src_filepath, 'r')\n zip_ref.extractall(dest_filepath)\n zip_ref.close()\n\nif __name__ == '__main__':\n if not \"WOW_HOME\" in os.environ:\n sys.exit(\"Set WOW_HOME environment variable to the location of your World of Warcraft directory.\")\n \n addon_home = os.environ['WOW_HOME'] + \"/Interface/AddOns\"\n print(\"Updating \" + addon_home)\n\n tmp_path = \"tmp/\"\n\n if not os.path.exists(tmp_path):\n os.mkdir(tmp_path, 755)\n\n # obviously this should be loaded from a file and looped over and/or done concurrently\n download_to_file(\"https://addon.theunderminejournal.com/TheUndermineJournal.zip\", tmp_path + \"/TheUndermineJournal.zip\")\n unzip_file(tmp_path + \"/TheUndermineJournal.zip\", tmp_path)\n copy_and_overwrite(tmp_path + \"/TheUndermineJournal\", addon_home + \"/TheUndermineJournal\")\n print(addon_home + \"/TheUndermineJournal updated!\")\n\n download_to_file(\"https://www.curseforge.com/wow/addons/auctionator/download/2609812/file\", tmp_path + \"/Auctionator.zip\")\n unzip_file(tmp_path + \"/Auctionator.zip\", tmp_path)\n copy_and_overwrite(tmp_path + \"/Auctionator\", addon_home + \"/Auctionator\")\n print(addon_home + \"/Auctionator updated!\")\n\n if os.path.exists(tmp_path):\n shutil.rmtree(tmp_path)","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1772,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"153646277","text":"import tweepy\r\nfrom textblob import TextBlob\r\nimport numpy as np\r\nimport operator\r\n\r\n# Step 1: Authenticate\r\nconsumer_key = 'b4qJoOBvj6QqI45YOkg7ovBFi'\r\nconsumer_secret = 'UdsPAtwW1IeY7sTNPpmlFq5XPzrwGZkZg6KvpjwvUM7jwMjaTC'\r\n\r\naccess_token = '516928802-5aS8RWSEA1tqQPOIzCeeqSF1x8QduP8197c7JNbn'\r\naccess_token_secret = 'drAR6koYhsUHvqC17kcMiN3FoicTng6uBJZaiKerEV45I'\r\n\r\nauth = tweepy.OAuthHandler(consumer_key, consumer_secret)\r\nauth.set_access_token(access_token, access_token_secret)\r\n\r\napi = tweepy.API(auth)\r\n\r\n# Step 2: Prep query features\r\nprint(\"made it to step 2\")\r\n# List of Stocks\r\nstock_names = ['$SBUX', '$ZDGE', '$ARL', '$KRMA', '$TRNC', '$PBI', '$PRTY']\r\nsince_date = \"2018-01-01\"\r\nuntil_date = \"2018-04-29\"\r\n\r\n\r\ndef get_label(analysis, threshold=0):\r\n if analysis.sentiment[0] > threshold:\r\n return 'Positive'\r\n else:\r\n return 'Negative'\r\n\r\n\r\n# Step 3: retrive and save tweets\r\nprint(\"made it to step 3\")\r\nall_polarities = dict()\r\nfor stock in stock_names:\r\n this_stock_polaritities = []\r\n # Get the tweets about the stock\r\n this_stock_tweets = api.search(q=[stock], count=100, since=since_date, until=until_date)\r\n # Save to csv\r\n with open('stocks_tweets.csv' % stock, 'wb') as this_stock_file:\r\n this_stock_file.write('tweet, sentiment_label')\r\n for tweet in this_stock_tweets:\r\n analysis = TextBlob(tweet.text)\r\n # Get the label corresponding to the sentiment analysis\r\n this_stock_polaritities.append(analysis.sentiment[0])\r\n this_stock_file.write('%s,%s\\n' % (tweet.text.encode('utf8'), get_label(analysis)))\r\n # Save the mean for final results\r\n all_polarities[stock] = np.mean(this_stock_polaritities)\r\n\r\n\r\n# Step 4: Print results\r\nsorted_analysis = sorted(all_polarities.items(), key=operator.itemgetter(1), reverse=True)\r\nprint(\"Mean sentiment Polarity in Decending order :\")\r\nfor stock, polarity in sorted_analysis:\r\n print('%s : %0.3f' % (stock, polarity))\r\n","sub_path":"PyForDataSci2.py","file_name":"PyForDataSci2.py","file_ext":"py","file_size_in_byte":1994,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"174830013","text":"\"\"\"\nrecord time taken for code to peform several steps\n\"\"\"\n\nimport time\nimport logging\n\nclass Timer(object):\n def __init__(self, name, milliseconds=True):\n self.log = logging.getLogger('timing.'+name)\n self.times = []\n self.next_step(\"\")\n self.multiplier = 1000 if milliseconds else 1\n\n def next_step(self, *lbl):\n label = lbl[1] if lbl else None\n self.times.append((label, time.time()))\n\n def last_step(self, *lbl):\n self.next_step(*lbl)\n self._log()\n\n def _log(self):\n if self.log.isEnabledFor(logging.DEBUG):\n previous_step = self.times[0][1]\n message = 'elapsed %f:' % self.multiplier*(self.times[:-1][1]-previous_step)\n for tuple in self.times[1:]:\n message += ' '\n if tuple[0]:\n message += tuple[0]+'='\n this_step = tuple[1]\n delta = self.multiplier*(this_step-previous_step)\n message += '%f' % delta\n previous_step = this_step\n self.log.debug(message)","sub_path":"src/ooi/timer.py","file_name":"timer.py","file_ext":"py","file_size_in_byte":1086,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"35623851","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.7 (62211)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: /Users/dunfield/snappy/build/lib.macosx-10.6-intel-2.7/snappy/decorated_isosig.py\n# Compiled at: 2019-07-15 23:56:54\nfrom __future__ import print_function\nfrom builtins import range\nimport re, string\nseparator = '_'\nbase64_pat = '([a-zA-Z0-9\\\\+\\\\-]+)'\nseparator_pat = '[%s]{1}' % separator\nisosig_pattern = re.compile(base64_pat + separator_pat + base64_pat + '$')\nbase64_letters = string.ascii_letters + '0123456789+-'\nbase64_lower = string.ascii_lowercase + '01234+'\nbase64_upper = string.ascii_uppercase + '56789-'\nin_one = string.ascii_lowercase[:16] + string.ascii_lowercase[1:16].upper()\nint_to_letter = dict(enumerate(base64_letters))\nletter_to_int = dict((a, i) for i, a in enumerate(base64_letters))\n\ndef encode_nonnegative_int(x):\n \"\"\"\n Regina's base64 encoding scheme for nonnegative integers,\n described in the appendix to http://arxiv.org/abs/1110.6080\n \"\"\"\n assert x >= 0\n six_bits = []\n while True:\n low_six = x & 63\n six_bits.append(low_six)\n x = x >> 6\n if x == 0:\n break\n\n return ('').join([ int_to_letter[b] for b in six_bits ])\n\n\ndef decode_nonnegative_int(s):\n return sum(letter_to_int[a] << 6 * i for i, a in enumerate(s))\n\n\ndef encode_int(x):\n \"\"\"\n Encodes an integer in the range [-2**90 + 1, 2**90 - 1] with a \"stop\"\n at the end so a concatenation of such encodings is easily decodable. \n The basic format is:\n \n If x in [0...15], encode as a single letter in [a...p].\n If x in [-15...-1] encode as a single letter in [P...B]. \n\n Otherwise, the first letter specifies the length of\n encode_nonnegative_int(abs(x)) as well as sign(x), followed by the\n encoding of abs(x).\n \"\"\"\n if 0 <= x < 16:\n return base64_letters[x]\n if -15 <= x < 0:\n return base64_letters[(abs(x) + 26)]\n encoded_xabs = encode_nonnegative_int(abs(x))\n L = len(encoded_xabs)\n try:\n if x > 0:\n return base64_lower[(16 + L)] + encoded_xabs\n if x < 0:\n return base64_upper[(16 + L)] + encoded_xabs\n except IndexError:\n raise ValueError('The given integer is too large to encode')\n\n\ndef encode_integer_list(L):\n return ('').join(map(encode_int, L))\n\n\ndef decode_integer_list(encoded):\n ans = []\n while len(encoded):\n s = encoded[0]\n sign = 1 if s in base64_lower else -1\n if s in in_one:\n ans.append(sign * letter_to_int[s.lower()])\n encoded = encoded[1:]\n else:\n if sign == 1:\n L = base64_lower.index(s) - 16\n else:\n L = base64_upper.index(s) - 16\n current, encoded = encoded[1:L + 1], encoded[L + 1:]\n ans.append(sign * decode_nonnegative_int(current))\n\n return ans\n\n\ndef det(A):\n return A[0][0] * A[1][1] - A[0][1] * A[1][0]\n\n\ndef inverse_perm(L):\n ans = len(L) * [None]\n for i, x in enumerate(L):\n ans[x] = i\n\n return ans\n\n\ndef as_two_by_two_matrices(L):\n assert len(L) % 4 == 0\n return [ [(L[i], L[(i + 1)]), (L[(i + 2)], L[(i + 3)])] for i in range(0, len(L), 4) ]\n\n\ndef sgn_column(matrix, col):\n \"\"\"\n Returns +1 or -1 depending on the sign of the first non-zero entry\n in the column of the given matrix.\n \"\"\"\n first_non_zero_entry = matrix[(0, col)] if matrix[(0, col)] != 0 else matrix[(1, col)]\n if first_non_zero_entry > 0:\n return +1\n return -1\n\n\ndef determine_flips(matrices, orientable):\n \"\"\"\n Returns pairs [(l,m)] for each given matrix. Multiplying the columsn of\n each matrix with the respective pair brings the matrix in \"canonical\" form.\n \"\"\"\n if orientable:\n det_sign = matrices[0][(0, 0)] * matrices[0][(1, 1)] - matrices[0][(0, 1)] * matrices[0][(1,\n 0)]\n return [ (sgn_column(matrix, 0), sgn_column(matrix, 0) * det_sign) for matrix in matrices\n ]\n else:\n return [ (sgn_column(matrix, 0), sgn_column(matrix, 1)) for matrix in matrices\n ]\n\n\ndef pack_matrices_applying_flips(matrices, flips):\n \"\"\"\n Multiplies the columns of each matrix by the entries in flips and\n packs all the matrices into one array, column-major.\n \"\"\"\n result = []\n for matrix, flip in zip(matrices, flips):\n for col in range(2):\n for row in range(2):\n result.append(matrix[(row, col)] * flip[col])\n\n return result\n\n\ndef supress_minus_zero(x):\n if x == 0:\n return 0\n return x\n\n\ndef decorated_isosig(manifold, triangulation_class, ignore_cusp_ordering=False, ignore_curve_orientations=False):\n isosig = manifold.triangulation_isosig(decorated=False)\n N = triangulation_class(isosig, remove_finite_vertices=False)\n N.set_peripheral_curves('combinatorial')\n trivial_perm = list(range(manifold.num_cusps()))\n min_encoded = None\n min_perm = None\n min_flips = None\n for tri_iso in manifold.isomorphisms_to(N):\n perm = inverse_perm(tri_iso.cusp_images())\n if ignore_cusp_ordering:\n matrices = [ tri_iso.cusp_maps()[i] for i in perm ]\n else:\n matrices = tri_iso.cusp_maps()\n if ignore_curve_orientations:\n flips = determine_flips(matrices, manifold.is_orientable())\n else:\n flips = [ (1, 1) for matrix in matrices ]\n decorations = pack_matrices_applying_flips(matrices, flips)\n if perm == trivial_perm or ignore_cusp_ordering:\n encoded = encode_integer_list(decorations)\n else:\n encoded = encode_integer_list(perm + decorations)\n if min_encoded is None or encoded < min_encoded:\n min_encoded = encoded\n min_perm = perm\n min_flips = flips\n\n ans = isosig + separator + min_encoded\n if False in manifold.cusp_info('complete?'):\n if ignore_cusp_ordering:\n slopes = [ manifold.cusp_info('filling')[i] for i in min_perm ]\n else:\n slopes = manifold.cusp_info('filling')\n for flip, slope in zip(min_flips, slopes):\n ans += '(%g,%g)' % (supress_minus_zero(flip[0] * slope[0]),\n supress_minus_zero(flip[1] * slope[1]))\n\n return ans\n\n\ndef set_peripheral_from_decoration(manifold, decoration):\n \"\"\"\n The manifold is assumed to already have a triangulation created\n from the \"bare\" isosig. \n \"\"\"\n dec = decode_integer_list(decoration)\n manifold.set_peripheral_curves('combinatorial')\n n = manifold.num_cusps()\n if len(dec) == 4 * n:\n cobs = as_two_by_two_matrices(dec)\n else:\n assert len(dec) == 5 * n\n manifold._reindex_cusps(dec[:n])\n cobs = as_two_by_two_matrices(dec[n:])\n if det(cobs[0]) < 0 and manifold.is_orientable():\n manifold.reverse_orientation()\n cobs = [ [(-a, b), (-c, d)] for (a, b), (c, d) in cobs ]\n manifold.set_peripheral_curves(cobs)\n\n\ndef is_identity(A):\n return A[(0, 0)] == A[(1, 1)] == 1 and A[(1, 0)] == A[(0, 1)] == 0\n\n\ndef preserves_peripheral_curves(h):\n perm = h.cusp_images()\n each_cusp = [ is_identity(A) for A in h.cusp_maps() ]\n return perm == sorted(perm) and False not in each_cusp\n\n\ndef same_peripheral_curves(M, N):\n for h in M.isomorphisms_to(N):\n if preserves_peripheral_curves(h):\n return True\n\n return False\n\n\nasymmetric = [\n 'v3372', 't10397', 't10448', 't11289', 't11581',\n 't11780', 't11824', 't12685', 'o9_34328', 'o9_35609', 'o9_35746',\n 'o9_36591', 'o9_37290', 'o9_37552', 'o9_38147', 'o9_38375',\n 'o9_38845', 'o9_39220', 'o9_41039', 'o9_41063', 'o9_41329',\n 'o9_43248']\n\ndef main_test():\n import snappy\n censuses = [\n snappy.OrientableClosedCensus[:100],\n snappy.OrientableCuspedCensus(filter='tets<7'),\n snappy.NonorientableClosedCensus,\n snappy.NonorientableCuspedCensus,\n snappy.CensusKnots(),\n snappy.HTLinkExteriors(filter='cusps>3 and volume<14'), [ snappy.Manifold(name) for name in asymmetric ]]\n tests = 0\n for census in censuses:\n for M in census:\n isosig = decorated_isosig(M, snappy.Triangulation)\n N = snappy.Triangulation(isosig)\n assert same_peripheral_curves(M, N), M\n assert isosig == decorated_isosig(N, snappy.Triangulation), M\n assert M.homology() == N.homology()\n tests += 1\n\n print('Tested decorated isosig encode/decode on %d triangulations' % tests)\n\n\ndef test_integer_list_encoder(trys=1000, length=100, max_entry=1237940039285380274899124224):\n import random\n tests = 0\n for i in range(trys):\n entries = [ random.randrange(-max_entry, max_entry) for i in range(length) ]\n entries += [ random.randrange(-15, 16) for i in range(length) ]\n random.shuffle(entries)\n assert decode_integer_list(encode_integer_list(entries)) == entries\n tests += 1\n\n print('Tested encode/decode on %d lists of integers' % tests)\n\n\ndef test_link_invariant():\n import snappy\n dt_codes = [\n [\n (-14, -46, -40, -28, -60, -70), (-32, -34, -38, -4, -52, -50, -48), (-44, -42, -64, -2, -16, -58), (-56, -54, -8), (-36, -26, -24, -22, -20, -6, -18), (-10, -66), (-72, -30, -62), (-12, -68)],\n [\n (-14, -46, -40, -28, -60, -70), (-36, -34, -30, -4, -52, -50, -48), (-42, -44, -58, -16, -2, -64), (-56, -54, -8), (-32, -26, -24, -22, -20, -6, -18), (-10, -66), (-72, -38, -62), (-12, -68)],\n [\n (14, 70, 64, 50, 36, 24), (18, 2), (26, 16, 72), (46, 44, 22, 6, 48, 54), (52, 62, 60, 58, 56, 12, 34), (68, 66, 32, 10, 42, 40, 38), (28, 30, 8), (20, 4)],\n [\n (-14, -46, -40, -28, -60, -70), (-32, -34, -38, -4, -52, -50, -48), (-44, -42, -64, -2, -16, -58), (-56, -54, -8), (-36, -26, -24, -22, -20, -6, -18), (-10, -68), (-30, -72, -62), (-12, -66)],\n [\n (14, 70, 64, 50, 36, 24), (2, 18), (34, 16, 72), (42, 40, 54, 38, 6, 22), (62, 52, 26, 12, 56, 58, 60), (68, 66, 28, 10, 44, 46, 48), (32, 30, 8), (20, 4)],\n [\n (-14, -46, -40, -28, -60, -70), (-34, -36, -58, -56, -54, -4, -30), (-42, -44, -48, -26, -2, -64), (-50, -52, -8), (-16, -32, -24, -6, -22, -20, -18), (-68, -10), (-38, -72, -62), (-66, -12)],\n [\n (-14, -46, -40, -28, -60, -70), (-34, -36, -58, -56, -54, -4, -30), (-42, -44, -48, -26, -2, -64), (-50, -52, -8), (-16, -32, -24, -6, -22, -20, -18), (-10, -66), (-72, -38, -62), (-68, -12)],\n [\n (14, 70, 64, 50, 36, 24), (2, 18), (16, 34, 72), (42, 40, 54, 38, 6, 20), (62, 52, 26, 12, 56, 58, 60), (68, 66, 28, 10, 44, 46, 48), (32, 30, 8), (4, 22)],\n [\n (-14, -46, -40, -28, -60, -70), (-32, -34, -38, -4, -52, -50, -48), (-44, -42, -64, -2, -16, -58), (-56, -54, -8), (-36, -26, -24, -22, -20, -6, -18), (-66, -10), (-72, -30, -62), (-68, -12)]]\n mfds = [ snappy.Manifold('DT%s' % dt_code) for dt_code in dt_codes + dt_codes ]\n for mfd in mfds[:len(dt_codes)]:\n mfd.reverse_orientation()\n\n isometry_signatures = [ mfd.isometry_signature(of_link=True) for mfd in mfds\n ]\n assert len(set(isometry_signatures)) == 1\n M = snappy.Manifold(isometry_signatures[0])\n N = snappy.Manifold(M.isometry_signature(of_link=True))\n assert same_peripheral_curves(M, N)\n assert isometry_signatures[0] == M.isometry_signature(of_link=True)\n assert isometry_signatures[0] == N.isometry_signature(of_link=True)\n for mfd in mfds:\n assert mfd.is_isometric_to(M, True)[0].extends_to_link()\n assert mfd.is_isometric_to(N, True)[0].extends_to_link()\n\n print('Tested that decorated isometry_signature is a link invariant')\n\n\ndef helper_are_isometric(M, N):\n for i in range(100):\n try:\n if M.is_isometric_to(N):\n return\n except:\n pass\n\n M.randomize()\n N.randomize()\n\n raise Exception('Could not find isometry')\n\n\ndef helper_test_by_dehn_filling(M):\n from snappy import Manifold\n M_filled = M.filled_triangulation()\n for ignore_cusp_ordering in [False, True]:\n for ignore_curve_orientations in [False, True]:\n isosig = M.triangulation_isosig(decorated=True, ignore_cusp_ordering=ignore_cusp_ordering, ignore_curve_orientations=ignore_curve_orientations)\n N = Manifold(isosig)\n N_filled = N.filled_triangulation()\n helper_are_isometric(M, N)\n\n\ndef test_by_dehn_filling():\n import random\n from snappy import OrientableCuspedCensus\n count = 0\n for M in OrientableCuspedCensus(cusps=3):\n for i in range(20):\n unfilled = random.randint(0, 2)\n for c in range(3):\n if c != unfilled:\n fillings = [\n (1, 0), (0, 1), (11, 12), (-13, 16),\n (9, -11), (8, 9), (1, 7), (13, 14),\n (14, -15), (17, -18)]\n M.dehn_fill(fillings[random.randint(0, len(fillings) - 1)], c)\n\n if 'positive' in M.solution_type():\n count += 1\n helper_test_by_dehn_filling(M)\n\n print('Tested %d randomly Dehn filled manifolds' % count)\n\n\nif __name__ == '__main__':\n test_integer_list_encoder()\n main_test()\n test_link_invariant()\n test_by_dehn_filling()","sub_path":"pycfiles/snappy-2.7-cp27-cp27m-macosx_10_6_intel/decorated_isosig.py","file_name":"decorated_isosig.py","file_ext":"py","file_size_in_byte":13397,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"336356521","text":"#!/usr/bin/env python\n# Copyright (c) 2013 VMware, Inc. All rights reserved.\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#\n\nfrom congress.dse import deepsix\nfrom congress.policy import compile\nfrom congress.policy import runtime\n\n\nclass DataSourceDriver(deepsix.deepSix):\n def __init__(self, name, keys, inbox=None, datapath=None,\n poll_time=None, **creds):\n if poll_time is None:\n poll_time = 10\n # a dictionary from tablename to the SET of tuples, both currently\n # and in the past.\n self.prior_state = dict()\n self.state = dict()\n self.poll_time = poll_time\n self.creds = creds\n # Make sure all data structures above are set up *before* calling\n # this because it will publish info to the bus.\n super(DataSourceDriver, self).__init__(name, keys, inbox, datapath)\n\n def get_all(self, type):\n raise NotImplementedError()\n\n def get_last_updated_time(self):\n raise NotImplementedError()\n\n def boolean_to_congress(self, value):\n return self.value_to_congress(value)\n\n def value_to_congress(self, value):\n if isinstance(value, basestring):\n return value\n if value in (True, False):\n return str(value)\n if (isinstance(value, int) or\n isinstance(value, long) or\n isinstance(value, float)):\n return value\n return str(value)\n\n def state_set_diff(self, state1, state2, table=None):\n \"\"\"Given 2 tuplesets STATE1 and STATE2, return the set difference\n STATE1-STATE2. Each tupleset is represented as a dictionary\n from tablename to set of tuples. Return value is a tupleset,\n also represented as a dictionary from tablename to set of tuples.\n \"\"\"\n if table is None:\n diff = {}\n for tablename in state1:\n if tablename not in state2:\n # make sure to copy the set (the set-diff below does too)\n diff[tablename] = set(state1[tablename])\n else:\n diff[tablename] = state1[tablename] - state2[tablename]\n return diff\n else:\n if table not in state1:\n return set()\n if table not in state2:\n # make copy\n return set(state1[table])\n else:\n return state1[table] - state2[table]\n\n def poll(self):\n \"\"\"Function called periodically to grab new information, compute\n deltas, and publish those deltas.\n \"\"\"\n self.log(\"polling\".format(self.name))\n self.prior_state = self.state\n self.state = {}\n self.update_from_datasource() # sets self.state\n tablenames = set(self.state.keys()) | set(self.prior_state.keys())\n for tablename in tablenames:\n # publishing full table and using prepush_processing to send\n # only deltas. Useful so that if policy engine subscribes\n # late (or dies and comes back up), DSE can automatically\n # send the full table.\n if tablename in self.state:\n self.publish(tablename, self.state[tablename])\n else:\n self.publish(tablename, set())\n self.log(\"finished polling\".format(self.name))\n\n def prepush_processor(self, data, dataindex, type=None):\n \"\"\"Takes as input the DATA that the receiver needs and returns\n the payload for the message. If this is a regular publication\n message, make the payload just the delta; otherwise, make the\n payload the entire table.\n \"\"\"\n # This routine basically ignores DATA and sends a delta\n # of the self.prior_state and self.state, for the DATAINDEX\n # part of the state.\n self.log(\"prepush_processor: dataindex <{}> data: {}\".format(\n str(dataindex), str(data)))\n # if not a regular publication, just return the original data\n if type != 'pub':\n self.log(\"prepush_processor: returned original data\")\n if type == 'sub':\n # Always want to send initialization of []\n if data is None:\n return []\n else:\n return data\n return data\n # grab deltas\n to_add = self.state_set_diff(self.state, self.prior_state, dataindex)\n to_del = self.state_set_diff(self.prior_state, self.state, dataindex)\n self.log(\"to_add: \" + str(to_add))\n self.log(\"to_del: \" + str(to_del))\n # create Events\n to_add = [runtime.Event(\n formula=compile.Literal.create_from_table_tuple(\n dataindex, x), insert=True)\n for x in to_add]\n to_del = [runtime.Event(\n formula=compile.Literal.create_from_table_tuple(\n dataindex, x), insert=False)\n for x in to_del]\n result = to_add + to_del\n if len(result) == 0:\n # Policy engine expects an empty update to be an init msg\n # So if delta is empty, return None, which signals\n # the message should not be sent.\n result = None\n text = \"None\"\n else:\n text = runtime.iterstr(result)\n self.log(\"prepush_processor for <{}> returning: {}\".format(self.name,\n dataindex, text))\n return result\n\n def d6run(self):\n if self.poll_time: # setting to 0/False/None means auto-polling is off\n self.poll()\n","sub_path":"congress/datasources/datasource_driver.py","file_name":"datasource_driver.py","file_ext":"py","file_size_in_byte":6131,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"362519153","text":"# -*- coding: utf-8 -*-\nn = int(input())\na = list(map(int, input().split()))\n\n\nd = {}\nfor num in a:\n d[num] = d.get(num, 0) + 1\n\n\nfor i in range(1, len(a)+2):\n if i in d:\n print(d[i])\n else:\n print(0)\n","sub_path":"Python_codes/p02707/s740357956.py","file_name":"s740357956.py","file_ext":"py","file_size_in_byte":224,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"388709181","text":"from rest_framework import viewsets, request\nfrom rest_framework.response import Response\nfrom rest_framework.decorators import action\nfrom posthog.models import Event, Filter\nfrom posthog.utils import request_to_date_query, dict_from_cursor_fetchall\nfrom django.db.models import OuterRef\nfrom django.db import connection\nfrom typing import Optional\n\nfrom django.db.models.expressions import Window\nfrom django.db.models.functions import Lag\nfrom django.db.models import F, Q\nfrom django.db import connection\n\nimport json\n\n# At the moment, paths don't support users changing distinct_ids midway through.\n# See: https://github.com/PostHog/posthog/issues/185\nclass PathsViewSet(viewsets.ViewSet):\n def _event_subquery(self, event: str, key: str):\n return Event.objects.filter(pk=OuterRef(event)).values(key)[:1]\n\n def _determine_path_type(self, request):\n requested_type = request.GET.get(\"type\", None)\n\n # Default\n event: Optional[str] = \"$pageview\"\n event_filter = {\"event\": event}\n path_type = \"properties->> '$current_url'\"\n start_comparator = \"{} ~\".format(path_type)\n\n # determine requested type\n if requested_type:\n if requested_type == \"$screen\":\n event = \"$screen\"\n event_filter = {\"event\": event}\n path_type = \"properties->> '$screen_name'\"\n start_comparator = \"{} ~\".format(path_type)\n elif requested_type == \"$autocapture\":\n event = \"$autocapture\"\n event_filter = {\"event\": event}\n path_type = \"tag_name_source\"\n start_comparator = \"group_id =\"\n elif requested_type == \"custom_event\":\n event = None\n event_filter = {}\n path_type = \"event\"\n start_comparator = \"event =\"\n return event, path_type, event_filter, start_comparator\n\n @action(methods=[\"GET\"], detail=False)\n def elements(self, request: request.Request):\n\n team = request.user.team_set.get()\n all_events = Event.objects.filter(team=team, event=\"$autocapture\")\n all_events_SQL, sql_params = all_events.query.sql_with_params()\n\n elements_readble = '\\\n SELECT tag_name_source as name, group_id as id FROM (SELECT \\'<\\' || e.\"tag_name\" || \\'> \\' || e.\"text\" as tag_name_source, e.\"text\" as text_source, e.group_id FROM \"posthog_element\" e\\\n JOIN ( SELECT group_id, MIN(\"posthog_element\".\"order\") as minOrder FROM \"posthog_element\" GROUP BY group_id) e2 ON e.order = e2.minOrder AND e.group_id = e2.group_id) as element\\\n JOIN (SELECT id, hash, count FROM posthog_elementgroup as g JOIN (SELECT count(*), elements_hash from ({}) as a group by elements_hash) as e on g.hash = e.elements_hash) as outer_group ON element.group_id = outer_group.id where text_source <> \\'\\' order by count DESC limit 20\\\n '.format(\n all_events_SQL\n )\n cursor = connection.cursor()\n cursor.execute(elements_readble, sql_params)\n rows = dict_from_cursor_fetchall(cursor)\n return Response(rows)\n\n def _apply_start_point(self, start_comparator: str, query_string: str, start_point: str) -> str:\n marked = \"\\\n SELECT *, CASE WHEN {} '{}' THEN timestamp ELSE NULL END as mark from ({}) as sessionified\\\n \".format(\n start_comparator, start_point, query_string\n )\n\n marked_plus = \"\\\n SELECT *, MIN(mark) OVER (\\\n PARTITION BY distinct_id\\\n , session ORDER BY timestamp\\\n ) AS max from ({}) as marked order by session\\\n \".format(\n marked\n )\n\n sessionified = \"\\\n SELECT * FROM ({}) as something where timestamp >= max \\\n \".format(\n marked_plus\n )\n return sessionified\n\n def _add_elements(self, query_string: str) -> str:\n element = 'SELECT \\'<\\'|| e.\"tag_name\" || \\'> \\' || e.\"text\" as tag_name_source, e.\"text\" as text_source FROM \"posthog_element\" e JOIN \\\n ( SELECT group_id, MIN(\"posthog_element\".\"order\") as minOrder FROM \"posthog_element\" GROUP BY group_id) e2 ON e.order = e2.minOrder AND e.group_id = e2.group_id where e.group_id = v2.group_id'\n element_group = 'SELECT g.\"id\" as group_id FROM \"posthog_elementgroup\" g where v1.\"elements_hash\" = g.\"hash\"'\n sessions_sql = \"SELECT * FROM ({}) as v1 JOIN LATERAL ({}) as v2 on true JOIN LATERAL ({}) as v3 on true\".format(\n query_string, element_group, element\n )\n return sessions_sql\n\n # FIXME: Timestamp is timezone aware timestamp, date range uses naive date.\n # To avoid unexpected results should convert date range to timestamps with timezone.\n def list(self, request):\n team = request.user.team_set.get()\n resp = []\n date_query = request_to_date_query(request.GET, exact=False)\n event, path_type, event_filter, start_comparator = self._determine_path_type(request)\n properties = request.GET.get(\"properties\")\n start_point = request.GET.get(\"start\")\n\n sessions = (\n Event.objects.add_person_id(team.pk)\n .filter(team=team, **(event_filter), **date_query)\n .filter(~Q(event__in=[\"$autocapture\", \"$pageview\", \"$identify\", \"$pageleave\"]) if event is None else Q())\n .filter(\n Filter(data={\"properties\": json.loads(properties)}).properties_to_Q(team_id=team.pk)\n if properties\n else Q()\n )\n .annotate(\n previous_timestamp=Window(\n expression=Lag(\"timestamp\", default=None),\n partition_by=F(\"distinct_id\"),\n order_by=F(\"timestamp\").asc(),\n )\n )\n )\n\n sessions_sql, sessions_sql_params = sessions.query.sql_with_params()\n\n if event == \"$autocapture\":\n sessions_sql = self._add_elements(query_string=sessions_sql)\n\n events_notated = \"\\\n SELECT *, CASE WHEN EXTRACT('EPOCH' FROM (timestamp - previous_timestamp)) >= (60 * 30) OR previous_timestamp IS NULL THEN 1 ELSE 0 END AS new_session\\\n FROM ({}) AS inner_sessions\\\n \".format(\n sessions_sql\n )\n\n sessionified = \"\\\n SELECT events_notated.*, SUM(new_session) OVER (\\\n ORDER BY distinct_id\\\n ,timestamp\\\n ) AS session\\\n FROM ({}) as events_notated\\\n \".format(\n events_notated\n )\n\n if start_point:\n sessionified = self._apply_start_point(\n start_comparator=start_comparator, query_string=sessionified, start_point=start_point,\n )\n\n final = \"\\\n SELECT {} as path_type, id, sessionified.session\\\n ,ROW_NUMBER() OVER (\\\n PARTITION BY distinct_id\\\n ,session ORDER BY timestamp\\\n ) AS event_number\\\n FROM ({}) as sessionified\\\n \".format(\n path_type, sessionified\n )\n\n counts = \"\\\n SELECT event_number || '_' || path_type as target_event, id as target_id, LAG(event_number || '_' || path_type, 1) OVER (\\\n PARTITION BY session\\\n ) AS source_event , LAG(id, 1) OVER (\\\n PARTITION BY session\\\n ) AS source_id from \\\n ({}) as final\\\n where event_number <= 4\\\n \".format(\n final\n )\n\n cursor = connection.cursor()\n cursor.execute(\n \"\\\n SELECT source_event, target_event, MAX(target_id), MAX(source_id), count(*) from ({}) as counts\\\n where source_event is not null and target_event is not null\\\n group by source_event, target_event order by count desc limit 20\\\n \".format(\n counts\n ),\n sessions_sql_params,\n )\n rows = cursor.fetchall()\n\n for row in rows:\n resp.append(\n {\"source\": row[0], \"target\": row[1], \"target_id\": row[2], \"source_id\": row[3], \"value\": row[4],}\n )\n\n resp = sorted(resp, key=lambda x: x[\"value\"], reverse=True)\n return Response(resp)\n","sub_path":"posthog/api/paths.py","file_name":"paths.py","file_ext":"py","file_size_in_byte":8312,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"340758480","text":"import json, os, time\nimport numpy as np\nimport h5py\n\ndef load_candidate(arg_dataset, argN, argC):\n h5f = h5py.File(arg_dataset,'r')\n if argN == -1:\n feature = h5f['pfd']\n else:\n feature = h5f['pfd'][:argN]\n label = np.full((len(feature), ), argC, dtype=int)\n return feature, label, len(feature)\n\ndef load_data(argM, argN, arg_mbr, tuple_shape):\n # (64, 32, 64)\n pf, pl, argM = load_candidate('H:\\\\研究生\\\\1-SKA\\\\Data\\\\PMPS\\\\subintband\\\\%s%s+.hdf5'%(arg_mbr, str(tuple_shape)), argM, 1)\n nf, nl, argN = load_candidate('H:\\\\研究生\\\\1-SKA\\\\Data\\\\PMPS\\\\subintband\\\\%s%s-.hdf5'%(arg_mbr, str(tuple_shape)), argN, 0)\n\n maparr = np.arange(argM + argN)\n np.random.shuffle(maparr)\n shp = (argM + argN,) + tuple_shape\n\n ftmp = np.empty(shp)\n ltmp = np.empty((argM + argN, ))\n ftmp[:argM] = pf\n ftmp[argM:] = nf\n ltmp[:argM] = pl\n ltmp[argM:] = nl\n\n feature = np.empty(shp)\n label = np.empty((argM + argN, ))\n\n for i in range(argM + argN):\n feature[i] = ftmp[maparr[i]]\n label[i] = ltmp[maparr[i]]\n\n return feature, np.array(label, dtype=int)\n\ndef load_profs(argM, argN, argdiv, tuple_shape):\n feature, label = load_data(argM, argN, 'prof', tuple_shape)\n train, test = {}, {}\n\n shp1 = feature[:argdiv].shape + (1,)\n shp2 = feature[argdiv:].shape + (1,)\n\n train['data'] = feature[:argdiv].reshape(shp1)\n train['label'] = label[:argdiv]\n\n test['data'] = feature[argdiv:].reshape(shp2)\n test['label'] = label[argdiv:]\n\n return train, test\n\n\ndef load_subband(argM, argN, argdiv, tuple_shape):\n feature, label = load_data(argM, argN, 'subband', tuple_shape)\n train, test = {}, {}\n\n shp1 = feature[:argdiv].shape + (1,)\n shp2 = feature[argdiv:].shape + (1,)\n\n train['data'] = feature[:argdiv].reshape(shp1)\n train['label'] = label[:argdiv]\n\n test['data'] = feature[argdiv:].reshape(shp2)\n test['label'] = label[argdiv:]\n\n return train, test\n\ndef load_subint(argM, argN, argdiv, tuple_shape):\n feature, label = load_data(argM, argN, 'subint', tuple_shape)\n train, test = {}, {}\n\n train['data'] = feature[:argdiv]\n train['label'] = label[:argdiv]\n\n test['data'] = feature[argdiv:]\n test['label'] = label[argdiv:]\n\n return train, test\n","sub_path":"models/mixed_model/load_data.py","file_name":"load_data.py","file_ext":"py","file_size_in_byte":2288,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"624312932","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Dec 19 22:05:40 2018\n\n@author: yiwen, Jerry\n\nhappy every day!!\n\"\"\"\nfrom os import error\nimport platform\nfrom tkinter.constants import DISABLED, NORMAL\nimport tkinter.filedialog\nimport tkinter as tk\nimport re\nfrom Quotesection import start_folder\nfrom process_SIF import SIF\nfrom contract_submit import test_contract\nfrom section import *\nfrom PC_dict import PC_name_list as PC_list\n\n\nclass Application(tk.Frame):\n def __init__(self, master=None):\n super().__init__(master)\n self.master = master\n self.grid(column=0, row=0)\n self.bgColor = '#EEEEEE'\n self.config(bg=self.bgColor, borderwidth=20)\n self.create_widgets()\n self.quoteinfotext.focus()\n # bind shift-enter key to generate quotation\n master.bind_all('', lambda e: self.contract_check())\n def paste_quote_text(self, event):\n \"\"\"\n Binded function to paste clipboard content into Text, after striping\n This is helpful to solve performance issues when a lot of \\t are copied from excel\n \"\"\"\n clipboard = self.clipboard_get()\n self.quoteinfotext.insert('end', clipboard.strip())\n return \"break\"\n def focus_next(self, event):\n \"\"\"binded function that switch the focus to the next widget\"\"\"\n event.widget.tk_focusNext().focus()\n # return 'break' is a trick to stop the original functionality of the event\n return \"break\"\n\n#set the widgets\n def create_widgets(self):\n # get the username and password\n tk.Label(self, text=\"CMS_User:\").grid(column=1, row=0)\n self.user = tk.Text(self, width=20, height=1)\n self.user.grid(column=2, row=0, columnspan=1)\n self.user.bind(\"\", self.focus_next)\n tk.Label(self, text=\"password: \").grid(column=1, row=1)\n self.user_password = tk.Text(self, width=20, height=1)\n self.user_password.grid(column=2, row=1, columnspan=1)\n self.user_password.bind(\"\", self.focus_next)\n self.login_button = tk.Button(self, text='Login&lock', command=self.CMS_login_check, height=1, width=10).grid(column=3, row=0)\n self.QuoteGenerator = tk.Label(self, text='Quote Generator',bg=self.bgColor, height=1, font=('Helvetica', 11, 'bold'))\n self.QuoteGenerator.grid(column=0, row=0, columnspan=1)\n\n self.quoteinfotext = tk.Text(self, height=3)\n if platform.system() == 'Darwin':\n self.quoteinfotext.bind('', self.paste_quote_text)\n self.quoteinfotext.bind('', self.paste_quote_text)\n self.quoteinfotext.bind(\"\", self.focus_next)\n self.quoteinfotext.grid(column=0, row=2, columnspan=4)\n \n #add a space line\n tk.Label(self, bg=self.bgColor).grid(column=2, row=11, columnspan=4)\n self.run = tk.Button(self, text = 'set folder', command=self.set_folder, highlightbackground=self.bgColor)\n self.run.grid(column=2, row=12, columnspan=1)\n self.clear = tk.Button(\n self, text='Clear All', command=self.clearall, highlightbackground=self.bgColor)\n self.clear.grid(column=0, row=12, columnspan=1)\n \n #add a space line\n tk.Label(self, bg=self.bgColor).grid(column=0, row=13, columnspan=4)\n\n self.OtherTools = tk.Label(self, text='Contract', bg=self.bgColor, font=('Helvetica', 11, 'bold'))\n self.OtherTools.grid(column=0, row=15, columnspan=1)\n\n # get the path of file and submit the SIF\n self.quote_label = tk.Label(self, text=\"Quote Number\").grid(column=0, row=16, columnspan=1)\n self.quotenumber = tk.Text(self, width=20, height=1)\n self.quotenumber.grid(column=1, row=16, columnspan=1)\n self.quotenumber.bind(\"\", self.focus_next)\n self.Contract_check_button = tk.Button(self, text=\"check Contract#\", command=self.contract_check).grid(column=2,row=16)\n self.Contractmessage = tk.StringVar()\n tk.Entry(self, textvariable=self.Contractmessage).grid(column=3, row=16)\n #add button for contract submission\n tk.Label(self, text=\"PO#: \").grid(column=0, row=17, columnspan=1)\n self.ponumber = tk.Text(self, width=20, height=1)\n self.ponumber.grid(column=1, row=17, columnspan=1)\n self.ponumber.bind(\"\", self.focus_next)\n #PC select\n tk.Label(self, text=\"PC: \").grid(column=2, row=17, columnspan=1)\n self.PC_option = tk.StringVar()\n self.PC_option.set(PC_list[0])\n self.PC_option_list = tk.OptionMenu(self, self.PC_option, *PC_list).grid(column=3, row=17)\n self.PC_lock_button = tk.Button(self, text='PC_lcok and save quote', command=self.quote_save).grid(column=3, row=18)\n self.contract_upload = tk.Button(self, text=\"contract submit\", command=self.contract_submit, state=DISABLED)\n self.contract_upload.grid(column=1, row=18)\n self.po_check = tk.Button(self, text=\"Check PO\", command=self.PO_check).grid(column=0, row = 18)\n #add a space line\n tk.Label(self, bg=self.bgColor).grid(column=0, row=19, columnspan=4) \n #Tittle: SIF upload\n self.OtherTools = tk.Label(self, text='SIF Upload', bg=self.bgColor, font=('Helvetica', 11, 'bold'))\n self.OtherTools.grid(column=0, row=20, columnspan=1) \n \n #SIF upload\n self.path_button = tk.Button(self, text=\"openfile\", command=self.selectPath).grid(column=0, row=22)\n self.SIF_upload_button = tk.Button(self, text=\"upload SIF\", command=self.SIF_upload).grid(column=2, row=22)\n self.file_path = tk.StringVar()\n tk.Label(self, textvariable = self.file_path).grid(column=1, row=22)\n tk.Label(self, text='success | fail: ').grid(column=3, row=21)\n self.SIFmessage = tk.StringVar()\n tk.Label(self, textvariable=self.SIFmessage).grid(column=3, row=22)\n self.errorLabel = tk.Label(self, bg=self.bgColor, fg='red')\n self.errorLabel.grid(column=0, row=23, columnspan=4)\n\n#all functions\n def CMS_login_check(self):\n user = self.user.get('1.0', 'end').strip()\n pd = self.user_password.get('1.0', 'end').strip()\n try:\n self.login_session\n self.user_password.config(state=DISABLED)\n except AttributeError:\n try:\n if user and pd:\n self.login_session = test_contract()\n self.login_session.login_user(user, pd)\n self.user.config(state=DISABLED)\n self.user_password.config(state=DISABLED)\n self.errorLabel.config(text=str(\"login sucess!\"))\n else:\n raise KeyError(f'no username or password detected')\n except KeyError as e:\n self.errorLabel.config(text=str(e))\n try:\n delattr(self, 'login_session')\n except AttributeError:\n pass\n \n def set_folder(self):\n quote_info = self.quoteinfotext.get('1.0', 'end').strip()\n try:\n start_folder(quote_info)\n self.errorLabel.config(text='Success!')\n except Exception as e:\n self.errorLabel.config(text=str(e))\n def selectPath(self):\n '''\n this module can read the file path\n the return path will be bond to self.path\n '''\n '''choose file and return the path'''\n self.path = tkinter.filedialog.askopenfilename()\n self.file_path_message = re.search(r'(/\\w+((-|_)\\w+)*\\.xlsx)$', self.path).group(0)\n self.file_path.set(self.file_path_message)\n # self.path.set(path_)\n print(self.path)\n def SIF_upload(self):\n quotename = self.quotenumber.get('1.0', 'end').strip()\n try:\n sifupload = self.login_session\n except AttributeError:\n self.errorLabel.config(text=str(\"please lock login first\"))\n raise KeyError(f'please lock login first')\n try:\n if self.path and quotename:\n try:\n sifupload.SIF_info_submit(quotename)\n file_name = 'uploadSIF.xlsx'\n sifupload.file_submit(file_name, self.path)\n sifupload.sample_check()\n self.SIFmessage.set(sifupload.message)\n except (KeyError, IndexError) as e:\n self.SIFmessage.set(str(e) + \", batchID created without product info updated\")\n else:\n raise AttributeError\n except AttributeError:\n err = str('please select SIF path and input quote#')\n self.SIFmessage.set(err)\n def contract_check(self):\n quote_name = self.quotenumber.get('1.0', 'end').strip()\n try:\n contract_search = self.login_session\n except AttributeError:\n self.errorLabel.config(text=str(\"please lock login first\"))\n raise KeyError(f'please lock login first')\n try:\n if quote_name:\n contract_search.contract_search(quote_name)\n else:\n raise KeyError(f'no login or quote# detected')\n self.Contractmessage.set(contract_search.contractno)\n except (KeyError, TypeError) as e:\n self.errorLabel.config(text=str(e))\n \n def quote_save(self):\n quote_name = self.quotenumber.get('1.0', 'end').strip()\n self.PC_name = self.PC_option.get()\n try:\n if quote_name:\n try:\n self.login_session\n except AttributeError:\n self.errorLabel.config(text=str(\"please lock login first\"))\n raise KeyError(f'please lock login first')\n self.login_session.quote_info(quote_name)\n self.login_session.quote_save_for_contract(self.PC_name)\n self.contract_upload['state'] = tk.NORMAL\n self.errorLabel.config(text=str('PC locked please go head submit the contract!'))\n else:\n raise KeyError(f'please input the quote# and login first')\n except KeyError as e:\n self.errorLabel.config(text=str(e))\n\n def contract_submit(self):\n quote_name = self.quotenumber.get('1.0', 'end').strip()\n po_value = self.ponumber.get('1.0', 'end').strip()\n try:\n if po_value:\n self.login_session.quote_submit()\n update_data = self.login_session.info_update()\n try:\n self.login_session.POinfo_search(po_value)\n self.login_session.contract_submit(update_data)\n self.errorLabel.config(\n text='contract draft submited, please check it on CMS!')\n except KeyError as e:\n self.erroLabel.config(test=str(e + \" can't link PO, please delete PO# and try submit draft\"))\n raise e\n else:\n self.login_session.quote_submit()\n update_data = self.login_session.info_update()\n self.login_session.contract_submit(update_data)\n self.errorLabel.config(text='contract draft submited, please check it on CMS!')\n except (KeyError, TypeError) as e:\n self.errorLabel.config(text=str(e))\n \n def PO_check(self):\n PO_name = self.ponumber.get('1.0', 'end').strip()\n try:\n if PO_name:\n try:\n self.login_session\n except AttributeError:\n self.errorLabel.config(text=str(\"please lock login first\"))\n raise KeyError(f'please lock login first')\n PO_search = self.login_session\n PO_search.POinfo_search(PO_name)\n self.errorLabel.config(text='PO found!')\n else:\n raise KeyError(f'no PO#')\n except KeyError as e:\n self.errorLabel.config(text=str(e)) \n\n def clearall(self):\n self.quoteinfotext.delete('1.0', 'end')\n self.errorLabel.config(text='')\n self.SIFmessage.set('')\n self.file_path.set('')\n self.Contractmessage.set('')\n self.ponumber.delete('1.0', 'end')\n self.quotenumber.delete('1.0', 'end')\n self.contract_upload['state'] = tk.DISABLED\n self.user.config(state=NORMAL)\n self.user_password.config(state=NORMAL)\n self.login_session.value_reset()\n\n\ndef main():\n root = tk.Tk()\n root.title('TSgo')\n app = Application(master=root)\n app.mainloop()\n\nif __name__ == '__main__':\n main()\n","sub_path":"my script/personal_CMS/quote_management.py","file_name":"quote_management.py","file_ext":"py","file_size_in_byte":12656,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"542823512","text":"from slackbot.bot import respond_to\n\n@respond_to('疲れた')\n@respond_to('つかれた')\ndef cheer(message):\n import random\n msg = [\"本当にお疲れさま\",\"よく頑張ってるね、偉いね\",\"あまり無理せず自分を大事にしろよ\",\"今日はご飯作ってあげるから、ゆっくりしてて\",\"辛かったら辞めていいよ。面倒を見てあげるから\"]\n one_msg = random.choice(msg)\n message.reply(one_msg)\n\n","sub_path":"plugins/mentions.py","file_name":"mentions.py","file_ext":"py","file_size_in_byte":453,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"53023441","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Oct 24 16:20:22 2017\n\n@author: pashute\n\"\"\"\nimport iqfeed as iqfc\nimport pandas as pd\n# import numpy as np\n# import datetime\n# import scipy.io\nimport DataSys as dsys\n# import enum\n# import IQFeedClient as iqfc\n\nimport logging\nlogging.basicConfig(filename=\"log.iqfeed.txt\", level=logging.WARN)\nlogger = logging.getLogger(__name__)\n\n\ndef __indicator(row, col):\n ''' method for applying in lambda function '''\n x1 = row[col + '_x']\n y2 = row[col + '_y']\n if pd.isnull(x1) and pd.isnull(y2):\n return \"missing\"\n elif pd.isnull(x1):\n return \"missing1\"\n elif pd.isnull(y2):\n return \"missing2\"\n elif y2 == 0: \n return \"zero2\"\n else:\n return (x1/y2)-1\n\n\ndef __plobrem(row):\n ''' \n count problems in row (missing data or zero in iqfeed)\n supplising sorution fol arr plobrems\n '''\n return row['open':'volume'].apply(\n lambda x: isinstance(x, str)).sum()\n\n\ndef __rejected_count(row, tolerance):\n return row['o':'v'].apply(\n lambda x: (not isinstance(x, str)) and abs(x) > tolerance).sum()\n\n\ndef __failedmessage(func, symbol, reason):\n return \"failed {0} {1}: {2}\".format(func, symbol, reason)\n\n\nclass IQFeedImporter(object):\n tickers = pd.DataFrame()\n # columns=['datetime', 'open', 'high', 'low', 'close', \n # 'volume', 'oi', 'symbol'])\n # tickers.set_index(['symbol', 'datetime'])\n df_assets = pd.DataFrame()\n symbols = [] # 'CBOT', 'CFE', \"SPY\", \"AAPL\", \"GOOG\", \"AMZN\"]\n\n def imp1_call_iqfeed(self, symbol, date_start, date_end):\n # x iqfeed = iqfc.IQFeedClient(feeder)\n timeframe = 86400 # 60*60*24 86400 1440\n iqreq = iqfc.historicData(date_start, date_end, timeframe)\n dframe = iqreq.download_symbol(symbol)\n return dframe\n\n def imp1_check_iqfeed_result(self, dframe):\n if not(dframe.empty):\n dframe.dropna(\n subset=['open', 'high', 'low', 'close', 'volume'],\n how='all')\n\n if dframe.empty: # Note: Second check, not an else.\n logger.error(\"import_singleAsset failed: no data aquired.\")\n return False\n \n return True\n\n def imp1_manip_result(self, symbol, dframe):\n # set column names\n # dframe.rename_axis(\"datetime\")\n # dframe.columns = ['open', 'high', 'low', 'close', 'volume', 'oi']\n\n # add column with symbol\n dframe['symbol'] = pd.Series(\n [symbol for x in range(len(dframe.index))], \n index=dframe.index)\n\n # set symbol and date column as multi index\n dframe.reindex(columns=['symbol', 'datetime'])\n\n return True\n\n def import_single_asset(self, symbol, date_start, date_end):\n '''\n imports single asset\n '''\n failedstatus = \"failed. Import {0}\".format(symbol)\n status = \"starting\"\n\n # todo: add date_start and end in status. \n\n dframe = self.imp1_call_iqfeed(symbol, date_start, date_end)\n if dframe.empty:\n status = \"{0}: Empty or no results\".format(failedstatus)\n logger.error(status)\n return status\n \n # isok = self.imp1_check_iqfeed_result(dframe)\n # if not isok:\n # status = \"{0}: Empty or no results\".format(failedstatus)\n # logger.error(status)\n # return status\n\n # isok = self.imp1_manip_result(symbol, dframe)\n # if not isok:\n # status = \"{0}: Problem setting data\".format(failedstatus)\n # logger.error(status)\n # # return status\n\n cleansymbol = symbol.replace('.', '_')\n cleansymbol = cleansymbol.replace('#','_')\n cleansymbol = cleansymbol.replace('@','_')\n fileDetails = \"c:\\\\dev\\\\IQWorthy\\\\Data\\\\Feed\\\\Raw\\\\Updt_{0}.mat\".format(cleansymbol)\n dsys.DataSys.save_dataframe(dframe, fileDetails, \"mat\")\n # file_details = dsys.DataSys.datafile_details(\n # dsys.Prefixes.imported, dsys.DataFolders.imported, \n # symbol, date_start, date_end)\n # # fix: dsys.DataSys.save_dataframe(dframe, file_details)\n\n # self.tickers.reset_index()\n # dframe.reset_index()\n # self.tickers = self.tickers.append(dframe)\n # self.tickers.set_index(keys=['symbol', 'datetime'])\n\n status = \"ok. Imported {0}\".format(symbol)\n return status # for testing that we got here\n \n def import_all_assets(self, date_start, date_end):\n stage = \"starting\"\n self.load_symbols() # get symbols list\n\n if len(self.symbols) < 1:\n stage = \"failed. Import all: Symbols not loaded correctly. Aborted\"\n logger.error(stage)\n return stage\n \n runcount = 0\n for item in self.symbols:\n runcount += 1\n data = self.import_single_asset(item, date_start, date_end)\n #data = \"\".join(data.split(\"\\r\"))\n #data = data.replace(\",\\n\", \"\\n\")[:-1]\n\n # todo: write to database. \n # currently: adding to tickers dataframe\n # self.tickers.append(data)\n\n # Write the data stream to disk\n # f = open(\"{0}.csv\".format('sym'), \"w\")\n # f.write(data)\n # f.close()\n stage = \"ok. Import all: {0}\".format(runcount)\n logger.error(stage)\n return stage\n\n def load_symbols(self):\n '''\n loads symbols-list from excel\n '''\n \n settingsfldr = dsys.DataFolders.settings\n assetslistfile = \"{0}.{1}\".format(\n dsys.Prefixes.assets, dsys.Extensions.excel) # \"AssetNamesNew.v01.xlsx\"\n\n file_details = dsys.DataSys.details_byfolder(\n settingsfldr, assetslistfile)\n symbols_column = 4 # todo: config\n sheetname = dsys.DataSys.assets_sheetname\n \n # dframe = pd.read_excel(file_details, sheetname=sheetname, index_col=0,\n # na_values='NA', usecols=symbols_column)\n assets_iq = [\"SPX.XO\", \"COMPX.X\",\"INDU.X\",\"RUT.X\",\t\"CAC.X\"\t,\"DAX.X\",\t\"UKX.X\",\t\"HKHI.X\",\t\"NIK.X\",\n \t\"BVSP.X\",\t\"QCL#\",\t\"XAUUSD.FXCM\"\t,\"@W#\"\t,\"EURUSD.FXCM\",\t\"@TY#\",\t\"MMSWRLD.X\"\t,\"MXEA.X\"\t,\"RUI.X\",\n \"C.T0000.X\"\t,\"QHG#\"\t,\"QSI#\",\"@C#\",\"JPYUSD.COMP\",\"GBPUSD.FXCM\",\"AUDUSD.FXCM\",\"CADUSD.COMP\",\"CHFUSD.COMP\",\n \"KOREA.X\",\"@CC#\",\"ICF#\",\"@HE#\",\"@S#\",\"@LE#\",\"@RR#\"]\n assets_bloom = [\n \"SPX_Index\",\n \"CCMP_Index\",\n \"INDU_Index\",\n \"RTY_Index\",\n \"CAC_Index\",\n \"DAX_Index\",\n \"UKX_Index\",\n \"HSI_Index\",\n \"NKY_Index\",\n \"IBOV_Index\",\n \"CL1_Comdty\",\n \"XAU_Curncy\",\n \"W_1_Comdty\",\n \"EURUSD_Curncy\",\n \"TY1_Comdty\",\n \"MXWO_Index\",\n \"MXEA_Index\",\n \"RIY_Index\",\n \"SPTSX_Index\",\n \"HG1_Comdty\",\n \"SI1_Comdty\",\n \"C_1_Comdty\",\n \"JPYUSD_Curncy\",\n \"GBPUSD_Curncy\",\n \"AUDUSD_Curncy\",\n \"CADUSD_Curncy\",\n \"CHFUSD_Curncy\",\n \"KOSPI_Index\",\n \"CC1_Comdty\",\n \"AX1_Comdty\",\n \"LH1_Comdty\",\n \"S_1_Comdty\",\n \"LC1_Comdty\",\n \"RR1_Comdty\" \n ]\n\n # self.df_assets.loc[:,0] = assets_iq\n # self.df_assets.columns = assets_bloom\n \n\n\n # fix. Read from excel\n # if self.df_assets.empty:\n # stage = \"Load symbols failed. No dataframe from {0}\".format(file_details)\n # logger.error()\n # return\n # self.df_assets = self.df_assets.dropna(how='all')\n\n self.symbols = assets_iq # self.df_assets.values.tolist()\n # if self.symbols.count() < 1:\n # stage = \"Load symbols failed. Could not load symbols list\"\n # logger.error(stage)\n # return stage # in case we do anything else later\n\n stage = \"ok\"\n return stage\n\n def load_bloomberg(self, symbol, date_start, date_end):\n file_details = dsys.DataSys.datafile_details(\n dsys.Prefixes.bloomberg_compare,\n dsys.DataFolders.compare_from,\n symbol, date_start, date_end,\n dsys.Extensions.excel)\n\n bloomcols = \"1,2,3,4,5,6\" \n # \"Date,PX_OPEN,PX_HIGH,PX_LOW,PX_LAST,PX_VOLUME\"\n\n dframe = pd.read_excel(file_details, # sheetname=bloomsheet, \n index_col=0,\n na_values='NA', parse_cols=bloomcols)\n if dframe is None or dframe.empty:\n status = __failedmessage('loadbloom', symbol, 'No compare data')\n logger.error(status)\n return\n \n dframe.columns = ['datetime', 'open', 'high', 'low', 'close', 'volume', 'oi', 'symbol']\n dframe['symbol'] = symbol\n # X dframe['volume'] = 0\n dframe['oi'] = 0\n dframe.set_index(['symbol', 'datetime']) \n\n return dframe\n\n def analyze_symbol(self, symbol, date_start, date_end):\n '''\n analyzes iqfeed vs. bloomberg\n outputs: in_iq, in_bloom, rejects, compared\n '''\n\n # pseudo: \n # startdate: max first1:first2\n # enddate: min last1:last2\n\n # find dates not in df1\n # find dates not in df2\n # for each line: na1, na2, na, zero2\n # for each line: (v1/v2)-1\n\n stage = \"failed\"\n\n df1 = self.tickers.loc[(self.tickers['symbol'] == symbol)]\n if df1.empty:\n stage = __failedmessage('analyze', symbol, 'No feed data')\n logger.error(stage)\n return stage\n\n df2 = self.load_bloomberg(symbol, date_start, date_end)\n if df2 is None or df2.empty:\n stage = __failedmessage('analyze', symbol, 'No comparison data')\n logger.error(stage)\n return stage\n\n # 1. compare only dates inside both\n feedDate1 = df1['date'].head(1)\n bloomDate1 = df2['date'].head(1) # .iloc[0]\n date1 = max(feedDate1, bloomDate1)\n # x df1['date'] = pd.to_datetime(df1['date'])\n\n feedDate2 = df1['date'].tail(1)\n bloomDate2 = df2['date'].tail(1)\n date2 = min(feedDate2, bloomDate2)\n # fix: check for errors in dates\n\n df1 = df1.xs(\n symbol, slice(date1, date2),\n level=('symbol', 'date'))\n\n df2 = df2.xs(\n symbol, slice(date1, date2),\n level=('symbol', 'date'))\n \n if df1.empty or df2.empty:\n stage = __failedmessage(\n 'analyze', symbol, 'No date within compared dates')\n logger.error(stage)\n return stage\n \n # remove na-rows from both and then compare missing dates\n # Note: if both missing a date it will be removed without report\n # check na in columns except symbol and date\n cols1 = len(df1.columns) - 2\n cols2 = len(df2.columns) - 2\n df1 = df1.dropna(subset=df1.columns[cols1:], how='all')\n df2 = df2.dropna(subset=df2.columns[cols2:], how='all')\n\n if df1.empty or df2.empty:\n stage = __failedmessage('analyze', symbol, 'Missing input data')\n logger.error(stage)\n return stage\n\n # create the merge, the bloom only and iqfeed only\n dfcommon = df1.merge(\n df2, on=['symbol', 'date'], left_index=True, right_index=True)\n stage = \"failed. Analyze {0}\"\n iq_only = df1[(~df1.index.isin(dfcommon.index))]\n bloom_only = df2[(~df1.index.isin(dfcommon.index))]\n stage = \"Created summaries of unique in iqfeed and Bloomberg\" \n\n # mark indicators: col1/col2-1 or: missing/missing1/missing2/zero2\n tolerance = 1.5 # config\n for col in ['open', 'high', 'low', 'close', 'volume']:\n dfcommon[col] = dfcommon.apply(\n lambda row: __indicator(row, col), axis=1)\n # https://stackoverflow.com/questions/44140489/get-non-numerical-rows-in-a-column-pandas-python/44140542#44140542\n # https://stackoverflow.com/questions/10665889/how-to-take-column-slices-of-dataframe-in-pandas\n dfcommon['missing'] = dfcommon.apply(lambda row: __plobrem(row))\n dfcommon['rejected'] = dfcommon.apply(\n lambda row: __rejected_count(row, tolerance))\n stage = \"done preparing common data\"\n \n extension = dsys.Extensions.excel # change this if we want matlab\n file_details = dsys.DataSys.datafile_details(\n dsys.Prefixes.bloomberg_only, dsys.DataFolders.rejected,\n symbol, date1, date2, extension)\n dsys.DataSys.save_dataframe(bloom_only, file_details, extension)\n stage = \"symbol {0} saved dates unique to bloom\".format(symbol)\n\n # save iq only\n extension = dsys.Extensions.excel # change this if we want matlab\n file_details = dsys.DataSys.datafile_details(\n dsys.Prefixes.iqfeed_only, dsys.DataFolders.rejected,\n symbol, date1, date2, extension)\n dsys.DataSys.save_dataframe(iq_only, file_details, extension)\n stage = \"symbol {0} saved dates unique to iqfeed\".format(symbol)\n\n # save rejected\n rejectedrow_tolerance = 3\n dfrejected = dfcommon.loc[(\n (dfcommon['rejected'] > rejectedrow_tolerance) and\n (dfcommon['missing'] > rejectedrow_tolerance))]\n\n extension = dsys.Extensions.excel\n file_details = dsys.DataSys.datafile_details(\n dsys.Prefixes.rejected, dsys.DataFolders.rejected,\n symbol, date1, date2, extension)\n dsys.DataSys.save_dataframe(dfrejected, file_details, extension)\n stage = \"symbol {0} saved rejected (over tolerance)\".format(symbol)\n\n # save compiled\n dfcompiled = dfcommon.loc[(\n (dfcommon['rejected'] <= rejectedrow_tolerance) and\n (dfcommon['missing'] <= rejectedrow_tolerance))]\n\n extension = dsys.Extensions.excel\n file_details = dsys.DataSys.datafile_details(\n dsys.Prefixes.compiled, dsys.DataFolders.compiled,\n symbol, date1, date2, extension)\n dsys.DataSys.save_dataframe(dfcompiled, file_details, extension)\n # stage = \"symbol {0} saved rejected (over tolerance)\".format(symbol)\n\n stage = \"Done\"\n return stage\n\n \n# ------------------------ Internals ---\n\n","sub_path":"IQFeedImporter.py","file_name":"IQFeedImporter.py","file_ext":"py","file_size_in_byte":14464,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"289331540","text":"import io\nimport os\nimport json\nimport string\nfrom tkinter import *\nos.system('python pos_index.py')\nsplit_string = \"\"\nDict = {}\nfreqcounter = 1\n\n# This class is made to process query inside a stack and take care of precedence\n# The query is pushed inside a stack and turn by turn popoed and processed \nclass Stack:\n def __init__(self):\n self.items = []\n\n def isEmpty(self):\n return self.items == []\n\n def push(self, item):\n self.items.append(item)\n\n def pop(self):\n return self.items.pop()\n\n def peek(self):\n return self.items[len(self.items)-1]\n\n def size(self):\n return len(self.items)\n\n\n# This function is made to process query where query is pushed inside a stack\n# The stack is then popped term by term and processed and answer stored and appended \ndef search(term,Dict):\n lst = ['1','2','3','4','5','6','7','8','9','10,',\n '11','12','13','14','15','16','17','18','19','20',\n '21','22','23','24','25','26','27','28','29','30',\n '31','32','34','34','35','36','37','38','39','40',\n '41','42','43','44','45','46','47','48','49','50']\n \n num = 0\n dist = 0\n answer = []\n value = []\n ans = []\n cont1 = []\n cont2 = []\n temp = []\n nlst = []\n s = Stack()\n stack = Stack()\n wordstk = Stack()\n term = term.split(' ')\n \n for x in term:\n s.push(x)\n\n while not s.isEmpty():\n word = s.peek()\n s.pop()\n stack.push(word)\n\n \n\n while not stack.isEmpty():\n if stack.peek() != 'and' and stack.peek() != 'or' and stack.peek() != 'not':\n slash = stack.peek() \n if ord(slash[0]) == 47:\n diff = int(slash[1])\n cont1 = value[-1]\n value.remove(value[-1])\n cont2 = value[-1]\n value.remove(value[-1])\n nlst = set(cont1).intersection(set(cont2))\n word1 = Dict[wordstk.pop()][0]\n word2 = Dict[wordstk.pop()][0]\n for docid in nlst: \n if docid in word1:\n poswrd1 = word1[docid]\n if docid in word2:\n poswrd2 = word2[docid]\n for i in range(len(poswrd1)):\n for j in range(len(poswrd2)):\n match = poswrd1[i] - poswrd2[j]\n if match < 0:\n match = match * -1\n if match <= diff+1:\n print(diff, match, docid)\n answer.append(docid)\n ans = answer\n else:\n continue\n stack.pop()\n else:\n if stack.peek() in Dict:\n value.append(Dict[stack.peek()][0].keys())\n ans = value[-1]\n wordstk.push(stack.peek()) \n stack.pop()\n num = num + 1\n else:\n stack.pop()\n \n else:\n if stack.peek() == 'and':\n stack.pop()\n if stack.peek() == 'not':\n stack.pop()\n if stack.peek() in Dict:\n value.append(Dict[stack.peek()][0].keys())\n stack.pop()\n temp = set(lst).difference(set(value[-1]))\n value.remove(value[-1])\n ans = set(temp).intersection(set(ans))\n \n else:\n if stack.peek() in Dict:\n value.append(Dict[stack.peek()][0].keys())\n stack.pop()\n temp = value[-1]\n value.remove(value[-1])\n ans = set(ans).intersection(set(temp))\n\n elif stack.peek() == 'or':\n stack.pop()\n if stack.peek() == 'not':\n stack.pop()\n if stack.peek() in Dict:\n value.append(Dict[stack.peek()][0].keys())\n stack.pop()\n temp = set(lst).difference(set(value[-1]))\n value.remove(value[-1])\n ans = set(temp).union(set(ans))\n \n else:\n if stack.peek() in Dict:\n value.append(Dict[stack.peek()][0].keys())\n stack.pop()\n temp = value[-1]\n value.remove(value[-1])\n ans = set(ans).union(set(temp))\n \n elif stack.peek() == 'not':\n stack.pop()\n if stack.peek() in Dict:\n value.append(Dict[stack.peek()][0].keys())\n stack.pop()\n ans = set(lst).difference(set(value[-1]))\n value.remove(value[-1])\n return ans\n\n# This is thr main function which gives directories of all stories present and the stopword list\n# Here using tkinter a GUI is made where query is taken stored\n# sent to concerned functions and answered displayed in answer box \ndef main():\n with open('Dictionary.json') as json_file:\n Dict = json.load(json_file)\n \n root = Tk()\n root.title('Query Search Box')\n bottomframe = Frame(root)\n bottomframe.pack(side=BOTTOM)\n\n Labeltext = StringVar()\n Label(bottomframe, textvariable=Labeltext).pack(side=LEFT)\n # This function is triggered on button press to process query and display answer\n def click():\n s = entry.get()\n s= s.lower()\n answer = search(s,Dict)\n if len(answer) == 0:\n Labeltext.set(\"no result found\")\n else: \n Labeltext.set(str(answer))\n \n topframe = Frame(root)\n Label(topframe, text='Text to find:').pack(side=LEFT)\n entry = Entry(topframe)\n entry.pack()\n button = Button(topframe, text=\"search\", command = click)\n button.pack()\n topframe.pack(side = TOP)\n root.mainloop()\n\n \nmain()\n","sub_path":"Assignment1.py","file_name":"Assignment1.py","file_ext":"py","file_size_in_byte":6211,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"538331416","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n# Exercise link: https://www.hackerrank.com/challenges/minimum-absolute-difference-in-an-array\n\ndef minimumAbsoluteDifference(a):\n if len(a) != len(list(set(a))): return 0\n \n l = sorted(a)\n t = []\n \n for i in range(len(l)-1):\n t.append(abs(l[i]-l[i+1]))\n \n return min(t)\n\nif __name__ == '__main__':\n fptr = open(os.environ['OUTPUT_PATH'], 'w')\n\n n = int(input())\n\n arr = list(map(int, input().rstrip().split()))\n\n result = minimumAbsoluteDifference(arr)\n\n fptr.write(str(result) + '\\n')\n\n fptr.close()\n\n","sub_path":"problem_solving/Minimum Absolute Difference in an Array.py","file_name":"Minimum Absolute Difference in an Array.py","file_ext":"py","file_size_in_byte":600,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"619182586","text":"#exec(open('.\\\\templates\\\\preproc_column_transformer.py').read())\nimport subprocess as sp\nimport importlib as il\nimport pickle as pk\nimport numpy as np\nimport sklearn.compose as sc\nimport sklearn.preprocessing as pp\nimport sklearn.pipeline as pl\nimport sklearn.ensemble as ensemble\nimport sklearn.model_selection as ms\n\nimport datacfg\n\nif __name__ == '__main__':\n sp.call('cls', shell = True)\n il.reload(datacfg)\n\n with open(datacfg.datacfg()['adult']['filepath'], 'rb') as fl:\n df = pk.load(fl)\n\n # Set feature and target columns.\n ycols = set(['class'])\n xcols = set(df.columns) - ycols\n\n # Set numeric and non-numeric columns.\n numerics = set(df.select_dtypes([np.number]).columns)\n nonnumerics = xcols - numerics\n # xcols = xcols - set(['native-country'])\n xcols = list(xcols)\n idxnumerics = [xcols.index(col) for col in numerics]\n idxnonnumerics = [xcols.index(col) for col in nonnumerics]\n\n # Designate data.\n X = df.loc[:, xcols].values\n y = np.ravel(df.loc[:, ycols].values)\n\n # Split data.\n Xtrain, Xtest, ytrain, ytest = ms.train_test_split(X, y, test_size = 0.33\n ,random_state = 0)\n\n # Cross-validation.\n k = 3\n cvsplitter = ms.KFold(n_splits = k, shuffle = True, random_state = 0)\n\n # Apply a transformation for each column.\n transformers = list()\n transformers.append(('StandardScaler', pp.StandardScaler(), idxnumerics))\n transformers.append(('OneHotEncoder', pp.OneHotEncoder(sparse = False, drop = 'first', handle_unknown = 'ignore'), idxnonnumerics))\n ct = sc.ColumnTransformer(transformers, remainder = 'passthrough')\n ct.fit(Xtrain)\n Xtrain_transformed = ct.transform(Xtrain)\n print('Feature Names: {0}'.format(ct.get_feature_names_out()))\n\n # Use the transformer in a pipeline.\n estimators = list()\n estimators.append(('ColumnTransformer', sc.ColumnTransformer(transformers, remainder = 'passthrough')))\n estimators.append(('RandomForestClassifier', ensemble.RandomForestClassifier(n_estimators = 100, max_features = 3)))\n ppl = pl.Pipeline(estimators)\n accuracy = ms.cross_val_score(ppl, Xtrain, ytrain, cv = cvsplitter)\n print('Accuracy of pipeline: {0:.2f}'.format(accuracy.mean()))","sub_path":"templates/preproc_column_transformer.py","file_name":"preproc_column_transformer.py","file_ext":"py","file_size_in_byte":2228,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"334913465","text":"from openerp.osv import osv\nfrom openerp.tools.translate import _\nfrom openerp import pooler\n\nfrom ftplib import all_errors\nfrom StringIO import StringIO\nfrom datetime import datetime\nfrom threading import Lock\n\nfrom connection import lx_connection\nfrom auto_vivification import AutoVivification\nfrom file import lx_file\n\nfrom lx_data import lx_data\nfrom lx_purchase_order import lx_purchase_order\nfrom lx_sales_order import lx_sales_order\nfrom lx_product import lx_product\nfrom lx_return import lx_return\nfrom lx_stock import lx_stock\nfrom lx_picking import lx_picking\n\nlx_classes = [\n lx_purchase_order,\n lx_sales_order,\n lx_product,\n lx_return,\n lx_stock,\n lx_picking\n]\n\nclass lx_manager(osv.osv):\n \"\"\"\n Instantiates an FTP connection wrapper object and allows polling the LX1 FTP Server\n \"\"\"\n\n _columns = {}\n _name = 'lx.manager'\n _auto = False\n _lock = Lock()\n\n _file_process_order = [\n 'MVTS',# PO received\n 'CREX',# SO sent\n 'CRET',# return\n 'STOC',# physical inventory\n 'TEST',\n ]\n\n ftp_exceptions = all_errors\n \n def thread_lock(function):\n \"\"\" Aquire a thread lock before calling the function and release it afterwards \"\"\"\n \n def inner(self, *args, **kwargs):\n if not self._lock.acquire(False):\n raise osv.except_osv(_('Already Syncing'), _('We are already synchronizing with LX1. Please wait a moment before trying again...'))\n \n try:\n res = function(self, *args, **kwargs)\n except:\n raise\n finally:\n self._lock.release()\n return res\n \n return inner\n\n def connection(self, cr):\n \"\"\" Gets an instance of lx_connection class that wraps the FTP server \"\"\"\n return lx_connection(self.pool, cr)\n\n @thread_lock\n def poll(self, cr, uid=1):\n \"\"\"\n Poll the LX1 FTP server, download a file list and iterate over them by oldest first by \n file sequence number. For each file, download the contents and create a lx.file.incoming \n record, committing cursor in between files.\n \"\"\"\n \n files_processed = 0\n sync_id = False\n file_incoming_obj = self.pool.get('lx.file.incoming')\n sync_obj = self.pool.get('lx.sync')\n \n # get connection to FTP server\n with self.connection(cr) as conn:\n\n # get list of files and directories and remove any files that cannot be processed\n # then order files by file_sequence so they are processed in the correct order\n files_and_directories = conn.ls()\n files_and_directories = filter(lambda f: '.' in f, files_and_directories)\n files_to_process = map(lambda f: lx_file(f), files_and_directories)\n files_to_process = filter(lambda f: f.valid, files_to_process)\n files_to_process = filter(lambda f: f.to_process(), files_to_process)\n files_to_process.sort(key=lambda f: f.file_sequence)\n \n # return if there are no files to process\n if not files_to_process:\n return sync_id\n \n # Prepare values for lx.sync record\n sync_vals = {\n 'date': datetime.now(), \n 'log': [],\n }\n sync_id = sync_obj.create(cr, uid, sync_vals)\n cr.commit()\n new_cursor = False\n\n # Process files within try catch block and append errors to sync_vals\n try:\n for file_to_process in files_to_process:\n\n files_processed += 1\n file_name = file_to_process.file_name\n activity = 'processing file'\n\n # download file contents and create lx.file.incoming from it, then save ID in sync_vals \n try:\n activity = 'creating lx.file.incoming'\n file_contents = conn.download_data(file_name)\n \n # Convert latin encoding to utf\n file_contents = file_contents.decode('ISO-8859-1')\n \n vals = {\n\t\t\t\t\t\t\t'xml_file_name': file_name,\n 'xml': file_contents,\n 'sync_id': sync_id,\n }\n file_incoming_id = file_incoming_obj.create(cr, uid, vals)\n \n # delete the file we successfully processed\n activity = 'deleting file from ftp server'\n conn.rm(file_name)\n\n except Exception as e:\n sync_vals['log'].append('Error while %s for %s: %s' % (activity, file_name, unicode(e)))\n files_processed -= 1\n cr = pooler.get_db(cr.dbname).cursor()\n new_cursor = True\n \n finally:\n # commit the OpenERP cursor inbetween files\n cr.commit()\n \n finally:\n # update the sync log\n sync_obj.write(cr, uid, [sync_id], sync_vals)\n cr.commit()\n if new_cursor:\n cr.close()\n \n # * end with conn * #\n \n try:\n # trigger parse all files\n activity = 'parsing all files'\n file_incoming_obj.parse_all(cr, uid)\n \n # trigger creation of all lx.updates for files\n activity = 'generating all updates'\n file_incoming_obj.generate_all_updates(cr, uid)\n \n # trigger execution of all lx.updates for files\n activity = 'executing all updates'\n file_incoming_obj.execute_all_updates(cr, uid)\n \n except Exception as e:\n sync_vals['log'].append('Error while %s: %s' % (activity, unicode(e)))\n \n # update lx.sync record\n sync_obj.write(cr, uid, [sync_id], sync_vals)\n\n return sync_id\n\ndef get_lx_data_subclass(object_type):\n \"\"\" Finds a subclass of lx_data whose object_type matches @param object_type \"\"\"\n class_for_data_type = [cls for cls in lx_classes if object_type in cls.object_type]\n assert len(class_for_data_type) == 1, _('Should have found 1 class for data type %s' % object_type)\n return class_for_data_type[0]\n","sub_path":"manager.py","file_name":"manager.py","file_ext":"py","file_size_in_byte":6589,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"114981676","text":"# encoding: utf-8\n\"\"\"\noos exceptions\n\"\"\"\nimport re\nimport xml.etree.ElementTree as ElementTree\nfrom xml.parsers import expat\n\nfrom .compat import to_string\nfrom .content import *\nfrom .headers import *\n\n_OOS_ERROR_TO_EXCEPTION = {} # populated at end of module\n\n\nclass OosError(Exception):\n def __init__(self, status, headers, body, details):\n # HTTP 状态码\n self.status_code = status\n\n # 请求ID\n self.requeset_id = headers.get(OOS_REQUEST_ID, '')\n\n # HTTP body\n self.body = body\n\n # 详细错误信息,是一个string到string的dict\n self.details = details\n\n # OOS错误码\n self.error_code = self.details.get('Code', '')\n\n # OOS错误信息\n self.message = self.details.get('Message', '')\n\n def __str__(self):\n error = {'status_code': self.status_code,\n OOS_REQUEST_ID: self.requeset_id,\n 'details': self.details}\n return str(error)\n\n def _str_with_body(self):\n error = {'status_code': self.status_code,\n OOS_REQUEST_ID: self.requeset_id,\n 'details': self.body}\n return str(error)\n\n\nif hasattr(ElementTree, 'ParseError'):\n ElementTreeParseError = (ElementTree.ParseError, expat.ExpatError)\nelse:\n ElementTreeParseError = (expat.ExpatError)\n\n\ndef _guess_error_details(body):\n details = {}\n body = to_string(body)\n\n if '' not in body or '' not in body:\n return details\n\n m = re.search('(.*)', body)\n if m:\n details['Code'] = m.group(1)\n\n m = re.search('(.*)', body)\n if m:\n details['Message'] = m.group(1)\n\n return details\n\n\ndef _parse_error_body(body):\n try:\n root = ElementTree.fromstring(body)\n if root.tag != 'Error':\n return {}\n\n details = {}\n for child in root:\n details[child.tag] = child.text\n return details\n except ElementTreeParseError:\n return _guess_error_details(body)\n\n\ndef make_exception(resp):\n status = resp.status\n headers = resp.headers\n body = resp.read(4096)\n details = _parse_error_body(body)\n code = details.get('Code', '')\n\n try:\n klass = _OOS_ERROR_TO_EXCEPTION[(status, code)]\n return klass(status, headers, body, details)\n except KeyError:\n return ServerError(status, headers, body, details)\n\n\n\nclass ClientError(OosError):\n def __init__(self, message):\n OosError.__init__(self, OOS_CLIENT_ERROR_STATUS, {}, 'ClientError: ' + message, {})\n\n def __str__(self):\n return self._str_with_body()\n\n\nclass RequestError(OosError):\n def __init__(self, e):\n OosError.__init__(self, OOS_REQUEST_ERROR_STATUS, {}, 'RequestError: ' + str(e), {})\n self.exception = e\n\n def __str__(self):\n return self._str_with_body()\n\n\nclass InconsistentError(OosError):\n def __init__(self, message, request_id=''):\n OosError.__init__(self, OOS_INCONSISTENT_ERROR_STATUS, {OOS_REQUEST_ID : request_id}, 'InconsistentError: ' + message, {})\n\n def __str__(self):\n return self._str_with_body()\n\n\nclass OpenApiFormatError(OosError):\n def __init__(self, message):\n OosError.__init__(self, OOS_FORMAT_ERROR_STATUS, {}, message, {})\n\n def __str__(self):\n return self._str_with_body()\n\n\nclass OpenApiServerError(OosError):\n def __init__(self, status, request_id, message, error_code):\n OosError.__init__(self, status, {OOS_REQUEST_ID : request_id}, '', {'Code': error_code, 'Message': message})\n\n\nclass ServerError(OosError):\n pass\n\n\nclass NotFound(ServerError):\n status_code = 404\n error_code = ''\n","sub_path":"projects/oos/oos-python-sdk-ali/oos_ali/exceptions.py","file_name":"exceptions.py","file_ext":"py","file_size_in_byte":3698,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"114230845","text":"\"\"\" A simple device status script for cockpit.\n\nThis script examines cockpit config. files, then reports\nthe host and port status for each remote device.\n\nCopyright 2015 Mick Phillips (mick.phillips at gmail dot com)\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\"\"\"\nimport os\nimport platform\nimport re\nimport socket\n# Import device definitions from the config module.\nfrom config import config\n\nfrom six import iteritems\n\n# Strings used for IP address and port in config. files.\nIPSTR = 'ipaddress' # ConfigParser makes keys lower case\nPORTSTR = 'port'\nURISTR = 'uri'\n# String used to format output.\nFORMATSTR = '{:<20} {:>16} {:<8} {:<6}'\n# A list of special device types.\nIGNORELIST = ['server']\n\n\ndef ping(host):\n \"\"\"\n Returns True if host responds to a ping request.\n \"\"\"\n ping_str = \"-n 1\" if platform.system().lower()==\"windows\" else \"-c 1\"\n return os.system(\"ping \" + ping_str + \" \" + host) == 0\n\n\ndef testPort(host, port):\n \"\"\"\n Returns True if a port is open.\n \"\"\"\n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n try:\n s.connect( (host, int(port)) )\n except socket.error:\n result = False\n else:\n result = True\n finally:\n s.close()\n return result\n\n# Mappings of device to hosts and ports.\ndeviceToHost = {}\ndeviceToPort = {}\n# Mappings of device to host and port statuses.\nhostsUp = {}\ndevicesUp = {}\n\nskipped = []\n\n# Iterate over config sections.\nfor s in config.sections():\n # Skip special devices.\n if s.lower() in IGNORELIST:\n skipped.append('skipped %s: in ingore list' % s)\n # Skip devices that don't have remotes.\n if not any(map(lambda x: x in config.options(s), [IPSTR, 'uri'])):\n skipped.append('skipped %s: no host or uri' % s)\n continue\n if 'uri' in config.options(s):\n uri = config.get(s, 'uri')\n match = re.match(r'(.*@)?(.*):([0-9]+)?', uri)\n if match is None:\n skipped.append('skipped %s: invalid uri; missing port?' % s)\n continue\n prefix, host, port = match.groups()\n else:\n host = config.get(s, IPSTR)\n try:\n port = config.get(s, PORTSTR)\n except:\n skipped.append('skipped %s: IP with no port' % s)\n continue\n # Extract remote details from config and store in dicts.\n deviceToHost[s] = host\n deviceToPort[s] = port\n\n\n# Iterate over the mappings to query host and port status.\nfor device, host in iteritems(deviceToHost):\n port = deviceToPort[device]\n if host not in hostsUp.keys():\n hostsUp[host] = 'up' if ping(host) else 'down'\n devicesUp[device] = 'open' if testPort(host, port) else 'closed'\n\n# Report.\nprint ('\\n\\n')\nprint (FORMATSTR.format('DEVICE', 'HOSTNAME', 'STATUS', 'PORT'))\nprint (FORMATSTR.format('======', '========', '======', '======'))\nfor device in sorted(deviceToHost.keys()):\n host = deviceToHost[device]\n port = deviceToPort[device]\n print (FORMATSTR.format(device, host, hostsUp[host], devicesUp[device]))\nprint ('\\n')\nfor s in skipped:\n print (s)\n","sub_path":"status.py","file_name":"status.py","file_ext":"py","file_size_in_byte":3544,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"435782261","text":"from flair.embeddings import TokenEmbeddings\nfrom flair.data import Dictionary\nfrom flair.models import SequenceTagger\nfrom flair.models.sequence_tagger_model import START_TAG, STOP_TAG\nimport numpy as np\nimport torch\nimport flair\n\nUNK_TAG: str = ''\n\nclass UnkTagger(SequenceTagger):\n\n def __init__(self,\n hidden_size: int,\n embeddings: TokenEmbeddings,\n tag_dictionary: Dictionary,\n tag_type: str,\n use_crf: bool = True,\n use_rnn: bool = True,\n rnn_layers: int = 1,\n dropout: float = 0.0,\n word_dropout: float = 0.05,\n locked_dropout: float = 0.5,\n pickle_module: str = 'pickle'\n ):\n\n super(UnkTagger, self).__init__(\n hidden_size,\n embeddings,\n tag_dictionary,\n tag_type,\n use_crf,\n use_rnn,\n rnn_layers,\n dropout,\n word_dropout,\n locked_dropout,\n pickle_module\n )\n\n #self.e = (0.1)**40\n self.e = 1. / np.finfo(np.float32).max\n self.unk_tag = self.tag_dictionary.get_idx_for_item(UNK_TAG)\n mask = self.get_trans_mask()\n self.valid_trans = torch.tensor(mask,\n dtype=self.transitions.dtype,\n device=flair.device)\n\n def get_trans_mask(self):\n mask = np.zeros((self.tagset_size,)*4)\n for bf in range(self.tagset_size):\n mask[self.unk_tag,bf,:,bf] = 1\n for c in range(self.tagset_size):\n mask[c,bf,c,bf] = 1\n for c in range(self.tagset_size):\n mask[c,self.unk_tag,c,:] = 1\n return mask\n\n def _score_sentence(self, feats, tags, lens_):\n\n init_alphas = torch.FloatTensor(self.tagset_size).fill_(-10000.)\n init_alphas[self.tag_dictionary.get_idx_for_item(START_TAG)] = 0.\n\n forward_var = torch.zeros(\n feats.shape[0],\n feats.shape[1] + 1,\n feats.shape[2],\n dtype=torch.float, device=flair.device)\n\n forward_var[:, 0, :] = init_alphas[None, :].repeat(feats.shape[0], 1)\n\n transitions = self.transitions.view(\n 1,\n self.transitions.shape[0],\n self.transitions.shape[1],\n ).repeat(feats.shape[0], 1, 1)\n\n '''\n #for debug\n tags[0,1] = self.unk_tag\n tags[0,lens_[0]-1] = self.unk_tag\n ##################\n '''\n\n start_tag = torch.full(\n (feats.shape[0], 1),\n self.tag_dictionary.get_idx_for_item(START_TAG),\n dtype=tags.dtype,\n device=flair.device)\n forward_tags = torch.cat([start_tag, tags], dim=1)\n masks = torch.stack([torch.stack([\n self.valid_trans[it[i+1],it[i]]\\\n for i in range(feats.shape[1])], dim=0)\n for it in torch.unbind(forward_tags, dim=0)], dim=0)\n\n '''\n #for debug\n for i in range(3):\n print('\\n{}th tags[0] {}:{} -> {}:{}'.format(\n i,\n forward_tags[0,i], self.tag_dictionary.get_item_for_index(forward_tags[0,i]),\n forward_tags[0,i+1], self.tag_dictionary.get_item_for_index(forward_tags[0,i+1])))\n for c,bf in zip(*np.where(masks[0,i].cpu().numpy())):\n print(' {}:{} -> {}:{}'.format(\n bf, self.tag_dictionary.get_item_for_index(bf),\n c, self.tag_dictionary.get_item_for_index(c)))\n ##################\n '''\n\n for i in range(feats.shape[1]):\n emit_score = feats[:, i, :]\n\n tag_var = \\\n emit_score[:, :, None].repeat(1, 1, transitions.shape[2]) + \\\n transitions + \\\n forward_var[:, i, :][:, :, None].repeat(1, 1, transitions.shape[2]).transpose(2, 1)\n\n max_tag_var, _ = torch.max(tag_var, dim=2)\n\n tag_var = tag_var - \\\n max_tag_var[:, :, None].repeat(1, 1, transitions.shape[2])\n\n '''\n #for debug\n if i < 3:\n print('\\n{}th torch.exp(tag_var[0])*masks[0] {}:{} -> {}:{}'.format(\n i,\n forward_tags[0,i], self.tag_dictionary.get_item_for_index(forward_tags[0,i]),\n forward_tags[0,i+1], self.tag_dictionary.get_item_for_index(forward_tags[0,i+1])))\n for c,bf in zip(*np.where((torch.exp(tag_var[0])*masks[0,i]).cpu().detach().numpy())):\n print(' {}:{} -> {}:{}'.format(\n bf, self.tag_dictionary.get_item_for_index(bf),\n c, self.tag_dictionary.get_item_for_index(c)))\n ##################\n '''\n\n result = (torch.sum(torch.exp(tag_var)*masks[:,i], dim=2)) + self.e\n\n '''\n for i in range(result.shape[0]):\n if (result[i] == 0).max():\n print(i)\n print(masks[i])\n\n assert not (result == 0).max()\n '''\n\n agg_ = torch.log(torch.sum(torch.exp(tag_var)*masks[:,i], dim=2) + self.e)\n\n cloned = forward_var.clone()\n cloned[:, i + 1, :] = max_tag_var + agg_\n\n forward_var = cloned\n\n forward_var = forward_var[range(forward_var.shape[0]), lens_, :]\n\n terminal_var = forward_var + \\\n self.transitions[self.tag_dictionary.get_idx_for_item(STOP_TAG)][None, :].repeat(\n forward_var.shape[0], 1)\n '''\n #for debug\n print('alpha[0] = {} if the last tag is else {}'.format(\n torch.log(torch.sum(torch.exp(terminal_var[0]))).detach(),\n terminal_var[0,forward_tags[0,lens_[0]]].detach()\n ))\n ##################\n '''\n\n '''\n for i in range(terminal_var.shape[0]):\n result = torch.sum(torch.exp(terminal_var[i])) + self.e\n assert not (result == 0).max()\n '''\n\n alpha = torch.stack([\n torch.log(torch.sum(torch.exp(terminal_var[i])) + self.e)\\\n if forward_tags[i, lens_[i]] == self.unk_tag\\\n else terminal_var[i,forward_tags[i, lens_[i]]]\n for i in range(terminal_var.shape[0])], dim=0)\n\n '''\n #for debug\n print('tags[0,lens_[0]-1] {}:{}, alpha[0] {}'.format(\n tags[0,lens_[0]-1],\n self.tag_dictionary.get_item_for_index(tags[0,lens_[0]-1]),\n alpha[0].detach()))\n #exit()\n ##################\n '''\n return alpha\n","sub_path":"fuzzy_crf/src/unk_debug_tagger.py","file_name":"unk_debug_tagger.py","file_ext":"py","file_size_in_byte":6874,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"650988419","text":"\"\"\"\n4. Преобразовать слова «разработка», «администрирование», «protocol»,\n«standard» из строкового представления в байтовое и выполнить\nобратное преобразование (используя методы encode и decode).\n\"\"\"\n\ndef my_encode(ls):\n result = []\n for el in ls:\n result.append(el.encode('utf-8'))\n return result\n\ndef my_decode(ls):\n result = []\n for el in ls:\n result.append(el.decode('utf-8'))\n return result\n\nLS = ['paзpaбoткa', 'aдминиcтpиpoвaниe', 'protocol', 'standard']\n\nLS_B = my_encode(LS)\nprint(LS_B)\nprint(my_decode(LS_B))","sub_path":"Homeworks/1-04.py","file_name":"1-04.py","file_ext":"py","file_size_in_byte":699,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"91293432","text":"import json\nimport os.path\nimport string\n\nDEFAULT_CONFIG = {\n \"connections\": {\n \"snoonet\": {\n \"network\": \"irc.snoonet.org\",\n \"port\": 6697,\n \"SSL\": True,\n \"user\": \"MHL2\",\n \"nick\": \"MHL2\",\n \"gecos\": \"A_D's anti mass highlight bot\",\n \"nsident\": \"MHL\",\n \"nspass\": \"MHLPassword\",\n \"admins\": [\"A_D!*@*\"],\n \"commands\": [],\n \"cmdprefix\": \"~\",\n \"channels\": \"\",\n \"adminchan\":\n \"#HeJustKeptTalkingInOneLongIncrediblyUnbrokenSentence\",\n \"global_nickignore\": [l for l in string.ascii_lowercase],\n \"global_maskignore\": \"\"\n },\n },\n\n \"debug\": True,\n}\n\n\nclass Config(dict):\n def __init__(self, name: str = \"config\"):\n super().__init__()\n self.name = name\n self.clear()\n self.update(DEFAULT_CONFIG)\n self.load(self.name)\n\n def load(self, name):\n if not os.path.exists(name + \".json\"):\n with open(name + \".json\", \"w\") as f:\n json.dump(DEFAULT_CONFIG, f, indent=2)\n\n with open(name + \".json\") as f:\n self.update(json.load(f))\n\n def save(self, name):\n with open(name) as f:\n json.dump(self, f, indent=2)\n","sub_path":"config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":1299,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"562920693","text":"for _ in range(int(input())):\n sum_a = 0\n sum_b = 0\n for _ in range(9):\n item_a, item_b = map(int, input().split())\n sum_a += item_a\n sum_b += item_b\n if(sum_a > sum_b):\n print(\"Yonsei\")\n elif(sum_a < sum_b):\n print(\"Korea\")\n else:\n print(\"Draw\")","sub_path":"OneDrive/바탕 화면/알고리즘/10000~11000/10214.py","file_name":"10214.py","file_ext":"py","file_size_in_byte":306,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"593092613","text":"from PyQt4 import QtCore\nfrom PyQt4 import QtGui\nfrom src import Voltmeter\nfrom src import Control\nfrom src import Terminal\nfrom PyQt4.QtCore import pyqtSlot,SIGNAL,SLOT\nfrom src import BusPirate\nimport sys\n\nclass GUI:\n def __init__(self, pirate):\n app = QtGui.QApplication(sys.argv)\n tabs = QtGui.QTabWidget()\n tabs.setFixedSize(800, 400)\n tabs.move(300, 300)\n buttons = QtGui.QButtonGroup() #I want the radio-button effect to occur application wide\n buttons.setExclusive(True)\n \n self.control = Control.Control(pirate,buttons)\n tabs.addTab(self.control,\"Control\")\n self.voltmeter = Voltmeter.Voltmeter(pirate,buttons)\n tabs.addTab(self.voltmeter,\"Voltmeter\")\n self.terminal = Terminal.Terminal(pirate,buttons)\n tabs.addTab(self.terminal,\"Terminal\")\n \n tabs.setWindowTitle('BusPirate GUI')\n tabs.show()\n sys.exit(app.exec_())\n \n def combo(self, text):\n print(text)\n \n \n'''\n1 = HiZ\n2 = 1WIRE\n3 = UART - baud, data/parity, stop, receive, output\n Opens a terminal allowing I/O\n Converter allowing dec,bin,hex conversion\n4 = I2C - speed\n Read/Write registers\n Converter allowing dec,bin,hex conversion\n5 = SPI - speed, clock, edge, sample, cs, output\n6 = 2WIRE - speed,output\n7 = 3WIRE - speed, CS, output\n8 = LCD - don't use\n9 = DIO\n ADC\n sample, scope\n Frequency\n sample, continues\n PWM\n %dial\n Servo\n angle dial\n states\n'''","sub_path":"src/GUI.py","file_name":"GUI.py","file_ext":"py","file_size_in_byte":1561,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"246880736","text":"# coding=UTF-8\n'''游戏插件管理模块\n'''\n\n__author__ = ['Wang Tao', 'Zhou Hao']\n\nimport importlib\nimport sys\n\nimport freetime.util.log as ftlog\nfrom freetime.entity.msg import MsgPack\nfrom freetime.util.log import catchedmethod\nfrom poker.entity.configure import configure\nfrom poker.entity.configure import gdata\nfrom poker.protocol import router\n\n_DEBUG = 1\ndebug = ftlog.info\n\n\nclass TYPluginUtils(object):\n @classmethod\n def updateMsg(cls, msg=None, cmd=None, params=None, result=None, **other):\n if not msg:\n msg = MsgPack()\n if cmd:\n msg.setCmd(cmd)\n if params is not None:\n msg.setKey('params', params)\n if result is not None:\n msg.setKey('result', result)\n\n for k, v in other.items():\n msg.setKey(k, v)\n\n return msg\n\n @classmethod\n def mkdict(cls, **kwargs):\n return kwargs\n\n @classmethod\n def sendMessage(cls, gameId, targetUserIds, cmd, result, logInfo=True):\n if isinstance(targetUserIds, int):\n targetUserIds = [targetUserIds]\n msg = cls.updateMsg(cmd=cmd, result=result)\n msg.setResult('gameId', gameId)\n if logInfo:\n if _DEBUG:\n debug('|to targetUserIds:', targetUserIds, '|msg:', msg, caller=cls)\n else:\n ftlog.debug('|to targetUserIds:', targetUserIds, '|msg:', msg, caller=cls)\n router.sendToUsers(msg, targetUserIds)\n\n @classmethod\n def makeHandlers(cls, handlerClass, events):\n ''' ['EV_GAME_INIT'] => {'EV_GAME_INIT': handlerClass.EV_GAME_INIT}'''\n return dict([(ev, getattr(handlerClass, ev)) for ev in events])\n\n\nclass TYPlugin(object):\n def __init__(self, gameId, cfg):\n ftlog.info('TYPlugin << |gameId, cfg:', gameId, cfg, caller=self)\n self.gameId = gameId\n self.name, self.module_name, self.class_name, self.object_name = (\n cfg['name'], cfg['module'], cfg.get('class'), cfg.get('object'))\n\n old_mod = sys.modules.get(self.module_name)\n if old_mod:\n del sys.modules[self.module_name]\n self.old_mod = old_mod\n self.module = importlib.import_module(self.module_name)\n reload(self.module)\n\n if self.object_name:\n self.object = getattr(self.module, self.object_name)(gameId)\n self.handlers = getattr(self.object, cfg['handle'])(gameId) or {}\n else:\n self._class = getattr(self.module, self.class_name)\n self.handlers = getattr(self._class, cfg['handle'])(gameId) or {}\n\n ftlog.info('TYPlugin |', 'handler:', self.name, 'loaded:', cfg,\n 'old_mod:', id(old_mod), old_mod, 'new_mod:', id(self.module),\n 'module:', self.module, 'events:', self.handlers.keys(),\n caller=self\n )\n # if not self.handlers:\n # raise Exception(\"no handlers: name: %s\" % self.name)\n\n @catchedmethod\n def onReload(self):\n if hasattr(self.module, 'onReload'):\n ftlog.info(\"TYPlugin.onReload >>|plugin name:\", self.name)\n self.module.onReload(self.gameId, self.old_mod)\n delattr(self, 'old_mod')\n elif hasattr(self.module, 'onReloadNew'):\n ftlog.info(\"TYPlugin.onReloadNew >>|plugin name:\", self.name)\n self.module.onReloadNew(self.gameId, self.object)\n\n def __str__(self):\n return '' % (\n self.name, id(self), self.handlers.keys())\n\n def __repr__(self):\n return self.__str__()\n\n\nclass TYPluginCenter(object):\n plugins = {} # key: gameId, value {name: TYPluginObj}\n config_reload_flag = {} # key: gameId, value: last reaload configure uuid(default None)\n map_events = {} # key: gameId; value: {event1: [handler1, handler2, ...], evnet2: [handler1, handler2, ...]}\n\n EV_CHAIN_STOP = 'EV_CHAIN_STOP' # handler 函数返回此值,表示中断事件链执行\n\n @classmethod\n def event(cls, msg, gameId):\n \"\"\" 发布事件 \"\"\"\n if gameId not in cls.map_events:\n return msg\n\n # cls.map_events = {\n # 8: {\"EV_PLAYER_GAME_FRAME_END\": [(\"Winner\", onEvPlayerGameFrameEnd), (\"Shark\",onEvPlayerGameFrameEnd)]},\n # 30: {}\n # }\n\n cmd = msg.getCmd()\n action = msg.getParam('action')\n ev = (cmd, action) if action else cmd\n receiver_plugins = msg.getKey('receiver_plugins') or []\n for plugin_name, handler in cls.map_events[gameId].get(ev, []):\n if receiver_plugins and plugin_name not in receiver_plugins:\n continue\n if _DEBUG:\n debug('TYPluginCenter.event| run handler <<|gameId, ev, plugin:', gameId, ev, plugin_name)\n try:\n if handler(gameId, msg) == cls.EV_CHAIN_STOP:\n if _DEBUG:\n debug('TYPluginCenter.event| chain break |gameId, ev, plugin:', gameId, ev, plugin_name)\n return msg\n except:\n ftlog.exception()\n if _DEBUG:\n debug('TYPluginCenter.event| run handler >>|gameId, ev, plugin:', gameId, ev, plugin_name)\n\n return msg\n\n @classmethod\n def evmsg(cls, gameId, cmd, params=None, result=None, receivers=None):\n msg = TYPluginUtils.updateMsg(cmd=cmd, params=params, result=result,\n receiver_plugins=receivers)\n return cls.event(msg, gameId)\n\n @classmethod\n def get_plugin(cls, name, gameId):\n return cls.plugins.get(gameId, {}).get(name)\n\n @classmethod\n @catchedmethod\n def reload(cls, gameId, handler_name='', handler_names=[], handlers_config=None):\n '''\n reload 某个 gameId 的插件\n\n @handlers_names: 指定要reload哪些plugin。不指定就reload所有(plugins越来越多,会比较慢)\n\n 不管有没有指定 reload 哪些插件,都会重新 build 事件表。\n 为什么不优化为只处理指定的plugins的事件?\n 没有必要,性能瓶颈不在这,而且全部重新build一定不会出问题,而且的而且,那样做会增加复杂性。\n '''\n\n if not cls.needLoadPlugin():\n ftlog.info('reload >> |this type of server not need load plugin',\n '|serverId, gameId:', gdata.serverId(), gameId, caller=cls)\n return\n\n if cls.isOtherGameServer(gameId):\n ftlog.info('reload >> |', 'do not reload in other game GR/GT',\n '|serverId, gameId:', gdata.serverId(), gameId, caller=cls)\n return\n\n if not handlers_config:\n handlers_config = configure.getGameJson(gameId, 'plugins', {})\n if not handlers_config:\n return\n # handlers_config = dict([(hc['name'], hc) for hc in handlers_config])\n handlers_config_dict = dict([(hc['name'], hc) for hc in handlers_config['handlers']])\n ftlog.info('<< |', cls.plugins, handlers_config, caller=cls)\n\n if handler_name:\n handler_names = [handler_name]\n\n handlers_config_list = [] # to be reload\n cls.map_events[gameId] = {} # 事件表\n if handler_names:\n for handler_name in handler_names:\n if handler_name in handlers_config_dict:\n handlers_config_list.append(handlers_config_dict.get(handler_name))\n if handler_name in cls.plugins[gameId]:\n del cls.plugins[gameId][handler_name]\n else:\n handlers_config_list = handlers_config['handlers']\n cls.plugins[gameId] = {} # plugins 表\n\n # 先 reload modules\n plugins = cls.plugins[gameId]\n reloadPlugins = []\n for cfg in handlers_config_list:\n try:\n plugin = TYPlugin(gameId, cfg)\n if plugin.handlers:\n plugins[cfg['name']] = plugin\n reloadPlugins.append(plugin)\n except Exception as e:\n ftlog.exception(e)\n\n cls.buildEventMap(gameId, plugins, handlers_config, cls.map_events[gameId])\n\n ftlog.info(\"TYPluginCenter.reload | \"\n \"reloadPlugins:\", [plugin.name for plugin in reloadPlugins])\n\n # onReload 时可能会有阻塞操作而让出CPU, 这时有可能会产生新的事件\n # 如果在 onReload 后才 buildEventMap,则这个事件会丢(因为eventMap在build之前是空的)\n # 所以,把 onReload 移到 build Event Map 之后\n for plugin in reloadPlugins:\n try:\n plugin.onReload()\n except Exception as e:\n ftlog.exception(e)\n\n @classmethod\n @catchedmethod\n def unload(cls, gameId, handler_names=None):\n \"\"\"卸载插件\"\"\"\n\n for name in handler_names:\n plugin = cls.get_plugin(name, gameId)\n if hasattr(plugin.module, \"onUnload\"):\n try:\n plugin.module.onUnload(gameId)\n except Exception:\n ftlog.error(\"TYPluginCenter.unload\"\n \"|gameId, name:\", gameId, name)\n del cls.plugins[gameId][name]\n\n handlers_config = configure.getGameJson(gameId, 'plugins', {})\n cls.buildEventMap(gameId, cls.plugins[gameId], handlers_config, cls.map_events[gameId])\n\n @classmethod\n def buildEventMap(cls, gameId, plugins, handlers_config, map_events):\n # 然后 build 事件处理表\n # step 1: 有些事件是有顺序要求的,先按顺序要求,构架一个架子\n for event, plugin_names in handlers_config['event_seq'].items():\n if ' ' in event:\n event = tuple(event.split())\n map_events[event] = []\n for plugin_name in plugin_names:\n if plugin_name == '...': # 事件顺序分割符号\n map_events[event].append('...')\n continue\n plugin = plugins.get(plugin_name)\n if plugin and event in plugin.handlers:\n map_events[event].append((plugin_name, plugin.handlers[event]))\n\n # step 2: 把 event_seq 配置中未明确的事件,加到 '...' 的位置\n for plugin_name, plugin in plugins.items():\n for event, handler in plugin.handlers.items():\n if event not in map_events:\n map_events[event] = []\n if not (plugin_name, handler) in map_events[event]: # 加过的不再加\n if '...' in map_events[event]: # 如果包含事件顺序分割符,则普通事件添加到分割符前面\n map_events[event].insert(map_events[event].index('...'), (plugin_name, handler))\n else:\n map_events[event].append((plugin_name, handler))\n\n # 最后把这个 '...' 标志删除掉\n for event_handlers in cls.map_events[gameId].values():\n if '...' in event_handlers:\n event_handlers.remove('...')\n\n ftlog.info('buildEventMap >> |', plugins, caller=cls)\n ftlog.info('buildEventMap >> |', map_events, caller=cls)\n\n @classmethod\n def isOtherGameServer(cls, gameId):\n '''判断是否为别的游戏的GR/GT,如果是,不加载当前游戏的 plugins'''\n serverType, serverId = gdata.serverType(), gdata.serverId()\n if serverType not in (gdata.SRV_TYPE_ROOM, gdata.SRV_TYPE_TABLE):\n return False\n\n if '-' in serverId:\n serverGameId = int(serverId.split('-')[0][2:])\n elif serverType == gdata.SRV_TYPE_ROOM:\n serverGameId = int(serverId[2:-4])\n elif serverType == gdata.SRV_TYPE_TABLE:\n serverGameId = int(serverId[2:-7])\n return serverGameId != gameId\n\n @classmethod\n def needLoadPlugin(cls):\n return gdata.serverType() in {\n gdata.SRV_TYPE_ROOM,\n gdata.SRV_TYPE_TABLE,\n gdata.SRV_TYPE_UTIL,\n gdata.SRV_TYPE_HTTP,\n gdata.SRV_TYPE_CENTER,\n }\n","sub_path":"source/tuyoo/src/poker/entity/game/plugin.py","file_name":"plugin.py","file_ext":"py","file_size_in_byte":12179,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"586773997","text":"def GetRecord(text):\r\n\titem_name = ''\r\n\titem_price_str = ''\r\n\tfoundData = 0 \r\n\trec = {}\r\n\tfor i in range(len(text) - 1):\r\n\t\tif(text[i] == ':'):\r\n\t\t\tfoundData = 1\r\n\t\telif(foundData == 0):\r\n\t\t\titem_name = item_name + text[i];\r\n\t\telif(foundData == 1):\r\n\t\t\titem_price_str = item_price_str + text[i]\r\n\trec['name'] = item_name;\r\n\trec['price'] = int(item_price_str)\r\n\treturn rec\r\n\r\n#Insertion Sort\r\ndef SortData(alist):\r\n \r\n n = len(alist)\r\n \r\n for i in range(1, n):\r\n key = alist[i]\r\n j = i;\r\n while((j > 0) and (key['price'] < alist[j - 1]['price'])):\r\n alist[j] = alist[j - 1];\r\n j = j - 1\r\n alist[j] = key\r\n return\r\n\r\n\r\nf = open(\"Input.txt\", \"r\")\r\ntext = f.readline()\r\ndataList = []\r\nwhile(len(text) > 0):\r\n\tdataList.append(GetRecord(text))\t\r\n\ttext = f.readline()\r\n\t\r\nSortData(dataList)\r\nnum_emp = int(input(\"Number of the employees:\"));\r\n\r\ndiff_list = []\r\nfor i in range(len(dataList) + 1 - num_emp):\r\n\tdiff_list.append(dataList[i + num_emp - 1]['price'] - dataList[i]['price']) \r\n\r\nlowest_index = 0;\r\nlowest_val = diff_list[0];\r\nfor i in range(len(diff_list)):\r\n\tif(diff_list[i] < lowest_val):\r\n\t\tlowest_index = i;\r\n\t\tlowest_val = diff_list[i]\r\n\r\noutf = open(\"sample_output.txt\", \"w\")\r\ntext = 'Number of the employees:' + str(num_emp)\r\noutf.writelines(text)\r\noutf.writelines('\\n')\r\noutf.writelines('\\n')\r\noutf.writelines('Here the goodies that are selected for distribution are:\\n')\r\nfor i in range(lowest_index,lowest_index + num_emp):\r\n\toutf.writelines(dataList[i]['name'])\r\n\toutf.writelines(':')\r\n\toutf.writelines(str(dataList[i]['price']))\r\n\toutf.writelines('\\n')\r\noutf.writelines('\\n')\r\noutf.writelines('And the difference between the chosen goodie with highest price and the lowest price is ')\r\noutf.writelines(str(lowest_val))","sub_path":"HighPeak.py","file_name":"HighPeak.py","file_ext":"py","file_size_in_byte":1808,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"196982116","text":"import pandas as pd\nimport numpy as np\nimport time\n\nfrom sklearn.manifold import MDS\nfrom sklearn.cluster import AgglomerativeClustering\nfrom sqlalchemy import create_engine\nfrom datetime import datetime\nfrom dateutil.relativedelta import relativedelta\nfrom bokeh.embed import components\nfrom bokeh.models import HoverTool, Range1d\nfrom bokeh.plotting import ColumnDataSource, figure\nfrom bokeh.resources import CDN\n\nengine = create_engine('sqlite:///fund.db')\n\n\ndef selection(start, btest_time, investement_type, i, sharpe_ratio, std, beta, treynor_ratio, choose):\n start_unix = time.mktime(\n (start - relativedelta(months=btest_time-i)).timetuple())\n end_unix = time.mktime(\n (start - relativedelta(days=+1, months=-i)).timetuple())\n\n if investement_type[0] == \"不分類\":\n data_df = pd.read_sql(sql='select * from price where date between ? and ? order by date asc',\n con=engine, params=[start_unix, end_unix])\n else:\n data_df = pd.read_sql(sql='SELECT * FROM price WHERE EXISTS\\\n (SELECT fund_id FROM basic_information\\\n WHERE area = ? and investment_target = ? and price.date between ? and ?\\\n and fund_id == price.fund_id)',\n con=engine, params=[investement_type[0], investement_type[1], start_unix, end_unix])\n if \"0050 元大台灣50\" not in data_df.fund_id.values:\n data_df = pd.concat([data_df, pd.read_sql(\n sql='select * from price where fund_id = \"0050 元大台灣50\" and date between ? and ? order by date asc',\n con=engine, params=[start_unix, end_unix])])\n\n data_df = data_df.pivot(index='date', columns='fund_id', values='nav')\n data_df = data_df.fillna(method=\"ffill\")\n data_df = data_df.fillna(method=\"bfill\")\n\n indicator_Rp = (data_df - data_df.iloc[0]) / data_df.iloc[0]\n indicator_σp = indicator_Rp.std(ddof=1)\n indicator_ρpm = indicator_Rp.corr()[\"0050 元大台灣50\"]\n indicator_σm = indicator_σp[\"0050 元大台灣50\"]\n indicator_βp = indicator_ρpm * indicator_σp / indicator_σm\n bl = data_df.iloc[0] > 0\n\n if bool(sharpe_ratio):\n sharpe_ratio = float(sharpe_ratio)\n bl = bl & ((indicator_Rp.iloc[-1] - (0.01 / data_df.shape[0])) /\n indicator_σp > sharpe_ratio)\n if bool(std):\n std = float(std)\n bl = bl & (indicator_σp < std)\n if bool(beta):\n beta = float(beta)\n bl = bl & (indicator_βp < beta)\n if bool(treynor_ratio):\n treynor_ratio = float(treynor_ratio)\n bl = bl & ((indicator_Rp.iloc[-1] - 0.01) /\n indicator_βp > treynor_ratio)\n\n data_df = data_df.T[bl].T\n data_df = data_df.pct_change()\n data_df_std = data_df.std()\n data_df = data_df.drop(data_df_std[data_df_std == 0].index.values, axis = 1)\n data_df = data_df.corr()\n data_df = 1 - data_df * 0.5 - 0.5\n\n camp = pd.DataFrame(AgglomerativeClustering(n_clusters=4).fit(\n data_df).labels_, index=data_df.index, columns=['label'])\n for i, ch in enumerate(choose):\n if ch in camp.index:\n camp = camp.drop(\n camp[camp.label == camp.loc[ch].label].index, axis=0)\n else:\n temp = camp.sample(n=1)\n camp = camp.drop(camp[camp.label == temp.label[0]].index, axis=0)\n choose[i] = temp.index[0]\n return choose\n\n\ndef profit_indicator(profit, start, end, response_data):\n df_0050 = pd.read_sql(sql='select nav,date from price where fund_id = \"0050 元大台灣50\" and date between ? and ? order by date asc',\n con=engine,\n params=[time.mktime(start.timetuple()),\n time.mktime(end.timetuple())],\n index_col=\"date\")\n df_0050 = ((df_0050 - df_0050.iloc[0]) / df_0050.iloc[0])\n\n indicator_σp = profit.std(ddof=1, axis=0)[0]\n indicator_ρpm = pd.concat([profit, df_0050], axis=1).corr().iloc[0][1]\n indicator_σm = df_0050.std(ddof=1)[0]\n indicator_βp = indicator_ρpm * indicator_σp / indicator_σm\n\n response_data['sharpe_ratio'] = (\n (profit.iloc[-1] - (0.01 / profit.shape[0])) / indicator_σp)[0]\n response_data['std'] = indicator_σp\n response_data['beta'] = indicator_βp\n response_data['treynor_ratio'] = (\n (profit.iloc[-1] - 0.01) / indicator_βp)[0]\n\n\ndef img(start, end, investement_type, sharpe_ratio, std, beta, treynor_ratio, btest_time, money, buy_ratio, strategy, frequency):\n profit = pd.DataFrame()\n hold = np.zeros((4), dtype=np.float)\n response_data = {}\n response_data['start'] = start.strftime('%Y-%m')\n response_data['mean_similarity'] = 0\n length = 12 * (end.year - start.year) + (end.month - start.month) + 1\n choose = np.asarray([\" \", \" \", \" \", \" \"], dtype=' 0:\n result.pop()\n K -= 1\n result.append(n)\n\n\nif K != 0:\n\n result = result[:-K]\n\n\n \n\n\nprint(''.join(result))\n\n\n\n\n","sub_path":"week_02/boj_G5_2812_Heegun.py","file_name":"boj_G5_2812_Heegun.py","file_ext":"py","file_size_in_byte":361,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"386174689","text":"import os\nfrom flask import Blueprint, render_template\n\nkitchen_view = Blueprint('kitchen_view', __name__)\n\n\ndef get_kitchen_images():\n images = []\n for i in os.listdir(os.path.split(os.path.realpath(__file__))[0].replace('/views', '')+'/static/gallery/kitchens'):\n if i != '.DS_Store':\n images.append(\"gallery/kitchens/\" + i)\n return images\n\n\n@kitchen_view.route(\"/gallery/kitchens\") \ndef kitchen():\n return render_template('gallery/kitchens.html', images=get_kitchen_images())","sub_path":"app/views/kitchen.py","file_name":"kitchen.py","file_ext":"py","file_size_in_byte":491,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"139492571","text":"import scipy.misc\nimport matplotlib.pyplot as plt\n#load already prepared ndarray from scipy\nlena = scipy.misc.ascent()\n\n#set the default colormap to gray\nplt.gray()\n\nplt.imshow(lena)\nplt.colorbar()\n#plt.show()\n\nprint(lena.shape)\nprint(lena.max())\nprint(lena.dtype)\nprint(type(lena))\n","sub_path":"python数据可视化编程/1.py","file_name":"1.py","file_ext":"py","file_size_in_byte":283,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"262349223","text":"import requests\nfrom bs4 import BeautifulSoup\nimport re\nfrom datetime import datetime, timedelta\n\n\nclass PPDai(object):\n def __init__(self):\n self.session = self._get_session()\n # 黑名单url列表页\n self.hmd_urls= ['http://invest.ppdai.com/account/blacklist?PageIndex={}&IsCalendarRequest=0'.format(i) for i in range(1, 12)]\n # 已还清url列表页\n self.yhq_urls = ['http://invest.ppdai.com/account/paybacklend?Type=2&pageIndex={}'.format(i) for i in range(1, 260)]\n # 收款中url列表页\n self.skz_urls = ['http://invest.ppdai.com/account/paybacklend?Type=2&pageIndex={}'.format(i) for i in range(1, 561)]\n # # 资金流水列表页\n # self.money_history_urls = ['http://www.ppdai.com/moneyhistory?page={page}'.format(page=page) for page in range(1, 5)]\n\n @staticmethod\n def _get_session():\n url = 'https://ac.ppdai.com/User/Login?message=&Redirect='\n form = {\n 'IsAsync': True,\n 'Redirect': 'http://www.ppdai.com/account/lend',\n 'UserName': 'myaccout',\n 'Password': 'mypassword',\n 'RememberMe': True}\n headers = {\n 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.90 Safari/537.36',\n 'Referer': 'https://ac.ppdai.com/User/Login?message=&Redirect='}\n session = requests.session()\n session.get(url)\n session.post(url, data=form, headers=headers)\n return session\n\n # 获取已投资的所有致富标url\n def get_zf_lend_urls(self):\n zf_lend_urls = []\n for url in self.yhq_urls + self.skz_urls:\n html = self.session.get(url).text\n soup = BeautifulSoup(html, 'lxml')\n # 获取目标navigablestring\n zf_lend_nvstrings = soup.find_all(text='¥55.00')\n # 获取目标url\n for nvstring in zf_lend_nvstrings:\n zf_lend_url = nvstring.find_previous(name='a', target='_blank', class_='c39a1ea fs16 visitedpurple', custom='hover')['href']\n zf_lend_urls.append(zf_lend_url)\n return zf_lend_urls\n\n # 查找带息还清致富标url和还款金额(借出金额=55,还款金额>57.5,则算是带息还清)\n def get_zf_dxhq(self):\n zf_dxhq = []\n com_money = re.compile('^(¥)(.*)')\n for url in self.yhq_urls:\n html = self.session.get(url).text\n soup = BeautifulSoup(html, 'lxml')\n zf_yhq_nvstings = soup.find_all(text='¥55.00')\n for nvstring in zf_yhq_nvstings:\n payback = float(com_money.match(nvstring.parent.parent.previous_element.previous_element)[2]) # 还款金额\n if nvstring.parent.previous_sibling == '借出金额:' and payback >= 57.5:\n url = nvstring.find_previous(name='a', target='_blank', class_='c39a1ea fs16 visitedpurple', custom='hover')['href'] # 目标url\n zf_dxhq.append((url, payback))\n return zf_dxhq\n\n # 计算额外盈利金额(2月内还清算额外盈利)\n def get_zf(self):\n zf_count = 0\n zf_sum = 0\n com_day = re.compile('(\\r\\n)(\\d{4}/\\d{1,2}/\\d{1,2})')\n for url, payback in self.get_zf_dxhq():\n html = self.session.get(url).text\n soup = BeautifulSoup(html, 'lxml')\n # 获取投标结束时间\n load_date = datetime.strptime(\n soup.find(\n text=re.compile('.*结束时间:.*')).find_next_sibling(\n 'span',\n class_=\"countdown_row countdown_amount\",\n id=\"leftTime\").string,\n '%Y/%m/%d')\n # 获取最晚一期的还款日期\n max_pay_date = datetime.strptime(com_day.match(\n soup.find_all(text=com_day)[-1])[2], '%Y/%m/%d')\n if max_pay_date - load_date < timedelta(days=60, hours=1):\n # print(url, str(payback))\n zf_count += 1\n zf_sum += (payback - 55.00) # 计算额外盈利\n return zf_count, zf_sum\n \n # 获取致富标逾期金额\n def get_yq_sum(self):\n yq_sum = 0\n for url in self.hmd_urls:\n html = self.session.get(url).text\n soup = BeautifulSoup(html, 'lxml')\n com_list = re.compile('¥(\\d*\\.\\d*)\\s/\\s¥(\\d*\\.\\d*)\\s/\\s¥(\\d*\\.\\d*)')\n for temp_list in soup.find_all(text=com_list):\n if com_list.match(temp_list)[3] == '55.00':\n yq = (55.00 - float(com_list.match(temp_list)[2]))\n yq_sum += yq\n return yq_sum\n\n\nif __name__ == '__main__':\n ppdai = PPDai()\n print('致富标总投标量:%s' % len(ppdai.get_zf_lend_urls()))\n print('致富标总投资金额:%s' % (len(ppdai.get_zf_lend_urls())*55))\n print('致富标2月内带息还清标量:%s' % ppdai.get_zf()[0])\n print('策略致富比率:%s', ppdai.get_zf()[0] / len(ppdai.get_zf_lend_urls()))\n print('致富标额外盈利金额:%s' % ppdai.get_zf()[1])\n print('致富标已逾期金额:%s' % ppdai.get_yq_sum())\n","sub_path":"ppdai/zhifu.py","file_name":"zhifu.py","file_ext":"py","file_size_in_byte":5187,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"258177750","text":"from flask import Flask\r\nfrom flask_restful import Resource, Api\r\n\r\napp = Flask(__name__)\r\napi = Api(app)\r\n\r\n# Define an Resource, HelloAPI, below with get method and map it to URLs '/' and '/index/'\r\n# The get method should return a dictionary {'message': 'Hello World!!!'}\r\nclass HelloAPI(Resource):\r\n def get(self):\r\n return {'message': 'Hello World!!!'}\r\n\r\napi.add_resource(HelloAPI, '/', '/index/')\r\n\r\nif __name__ == '__main__':\r\n app.run()","sub_path":"Hands-on/Flask - Restful API Programming/HS1_Simple Flask REST API.py","file_name":"HS1_Simple Flask REST API.py","file_ext":"py","file_size_in_byte":452,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"49484282","text":"from mjrl.utils.gym_env import GymEnv\nfrom mjrl.policies.gaussian_mlp_ewc import MLPEWC\nfrom mjrl.baselines.mlp_baseline import MLPBaseline\nfrom mjrl.algos.npg_cg_er import NPGER\nfrom mjrl.utils.train_agent import train_agent\nimport time as timer\nimport numpy as np\nimport gym\nimport pickle\nimport torch\nimport os\nfrom mjrl.utils.make_train_plots import make_multitask_train_plots, make_multitask_test_plots\n\nimport argparse\nparser = argparse.ArgumentParser(description='Experimental evaluation of lifelong PG learning')\n\nparser.add_argument('-n', '--num_seeds', dest='num_seeds', default=5, type=int)\nparser.add_argument('-i', '--initial_seed', dest='initial_seed', default=0, type=int)\n\nargs = parser.parse_args()\n\nSEED = 50 + 10 * args.initial_seed # use different orders for tuning\njob_name_er = 'results/metaworld_er_exp'\ntorch.set_num_threads(5)\n\n# MTL policy\n# ==================================\n\nnum_tasks = 10\nnum_seeds = args.num_seeds\ninitial_seed = args.initial_seed\nnum_cpu = 5\n\nenv_dict = {\n 'reach-v1': 'sawyer_reach_push_pick_place:SawyerReachPushPickPlaceEnv',\n 'push-v1': 'sawyer_reach_push_pick_place:SawyerReachPushPickPlaceEnv',\n 'pick-place-v1': 'sawyer_reach_push_pick_place:SawyerReachPushPickPlaceEnv',\n 'door-v1': 'sawyer_door:SawyerDoorEnv',\n 'drawer-open-v1': 'sawyer_drawer_open:SawyerDrawerOpenEnv',\n 'drawer-close-v1': 'sawyer_drawer_close:SawyerDrawerCloseEnv',\n 'button-press-topdown-v1': 'sawyer_button_press_topdown:SawyerButtonPressTopdownEnv',\n 'peg-insert-side-v1': 'sawyer_peg_insertion_side:SawyerPegInsertionSideEnv',\n 'window-open-v1': 'sawyer_window_open:SawyerWindowOpenEnv',\n 'window-close-v1': 'sawyer_window_close:SawyerWindowCloseEnv',\n}\n\ne_unshuffled = {}\n\nfor task_id, (env_id, entry_point) in enumerate(env_dict.items()):\n kwargs = {'obs_type': 'plain'}\n if env_id == 'reach-v1':\n kwargs['task_type'] = 'reach'\n elif env_id == 'push-v1':\n kwargs['task_type'] = 'push'\n elif env_id == 'pick-place-v1':\n kwargs['task_type'] = 'pick_place'\n gym.envs.register(\n id=env_id,\n entry_point='metaworld.envs.mujoco.sawyer_xyz.' + entry_point,\n max_episode_steps=150,\n kwargs=kwargs\n )\n e_unshuffled[task_id] = GymEnv(env_id)\n\nfor i in range(initial_seed, num_seeds + initial_seed):\n np.random.seed(SEED)\n torch.manual_seed(SEED)\n\n job_name_er_seed = job_name_er + '/seed_{}'.format(i)\n\n e = {}\n baseline_er = {} \n task_order = np.random.permutation(num_tasks)\n for task_id in range(num_tasks):\n e[task_id] = e_unshuffled[task_order[task_id]]\n baseline_er[task_id] = MLPBaseline(e[task_id].spec, reg_coef=1e-3, batch_size=64, epochs=10, learn_rate=1e-3, use_gpu=True)\n\n policy_er = MLPEWC(e[0].spec, hidden_sizes=(32,32), seed=SEED)\n agent_er = NPGER(e, policy_er, baseline_er, capacity=500, normalized_step_size=0.01, seed=SEED, save_logs=True, gamma=0.995, gae_lambda=0.97)\n\n for task_id in range(num_tasks):\n ts = timer.time()\n train_agent(job_name=job_name_er_seed,\n agent=agent_er,\n seed=SEED,\n niter=200,\n gamma=0.995, \n gae_lambda=0.97,\n num_cpu=num_cpu,\n sample_mode='trajectories',\n num_traj=50,\n save_freq=5,\n evaluation_rollouts=0,\n task_id=task_id)\n iterdir = job_name_er_seed + '/iterations/task_{}/'.format(task_id)\n os.makedirs(iterdir, exist_ok=True)\n policy_file = open(iterdir + 'policy_updated.pickle', 'wb')\n pickle.dump(agent_er.policy, policy_file)\n policy_file.close()\n\n print(\"time taken for linear policy training = %f\" % (timer.time()-ts))\n\n f = open(job_name_er_seed+'/trained_mtl_policy.pickle', 'wb')\n pickle.dump(policy_er, f)\n f.close()\n f = open(job_name_er_seed+'/trained_mtl_baseline.pickle', 'wb')\n pickle.dump(baseline_er, f)\n f.close()\n f = open(job_name_er_seed+'/task_order.pickle', 'wb')\n pickle.dump(task_order, f)\n f.close()\n\n\n make_multitask_train_plots(loggers=agent_er.logger, keys=['stoc_pol_mean'], save_loc=job_name_er_seed+'/logs/')\n\n mean_test_perf = agent_er.test_tasks(test_rollouts=10,\n num_cpu=num_cpu)\n result = np.mean(list(mean_test_perf.values()))\n print(result)\n make_multitask_test_plots(mean_test_perf, save_loc=job_name_er_seed+'/')\n\n result_file = open(job_name_er_seed + '/results.txt', 'w')\n result_file.write(str(mean_test_perf))\n result_file.close()\n\n SEED += 10\n\n\n\n","sub_path":"experiments/metaworld_tasks/metaworld_er.py","file_name":"metaworld_er.py","file_ext":"py","file_size_in_byte":4618,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"231046466","text":"#https://leetcode.com/problems/validate-binary-search-tree/description/\n\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\nclass Solution:\n def isValidBST(self, root):\n \"\"\"\n Solution 1: Use definition of BST, root has to be greater ('>') than every thing on left sub tree, and smaller ('<') than everything in right sub tree. And each subtree has to be BST itself.\n Passed!\n\n Can use float('inf') and float('-inf') instead of None value for minVal & maxVal. A perk of using python.\n\n :type root: TreeNode\n :rtype: bool\n \"\"\"\n def isBST(root, minVal, maxVal):\n if root is None:\n return True\n\n if (minVal is not None and root.val <= minVal) or (maxVal is not None and root.val >= maxVal):\n return False\n\n return isBST(root.left, minVal=minVal, maxVal=root.val) and isBST(root.right, minVal=root.val, maxVal=maxVal)\n\n return isBST(root)\n\n def isValidBST2(self, root):\n \"\"\"\n Solution 2: In in-order-traversal, values have to be in increasing order. Recursive.\n Passed!\n \"\"\"\n def inorder(root, preVal):\n '''\n Return a tuple (is subtree a BST, max value in the subtree).\n '''\n if root is None: return (True, preVal)\n\n isLeftBST, maxLeftVal = inorder(root.left, preVal)\n\n if isLeftBST and (maxLeftVal is None or maxLeftVal < root.val):\n return inorder(root.right, root.val)\n else:\n return (False, None)\n\n result, maxVal = inorder(root, float('-inf'))\n return result\n\n\n def isValidBST2b(self, root):\n \"\"\"\n Solution 2b: same as solution 2, but instead of returning max value in each function call, keep the most recent value seen in a nonlocal variable\n Passed!\n \"\"\"\n def inorder(root):\n nonlocal recentVal # nonlocal instead of global (!)\n if root is None: return True\n\n if not inorder(root.left) or root.val <= recentVal: return False\n\n recentVal = root.val # update recent value only when examining the root\n return inorder(root.right)\n\n recentVal = float('-inf')\n return inorder(root)\n\n def isValidBST3(self, root):\n '''\n Solution 3: In in-order-traversal iteratively using stack. In python, use Lists as stack.\n Keys:\n - Top of the stack is always the left most node of the tree at that point (after other left-most nodes have been popped)\n - Popping order is in-order\n - Adding root (of a subtree) and its left-most-path to stack instead of adding left-most-path of top-of-the-stack node (this causes duplication)\n Passed!\n '''\n if root is None: return True\n\n # add leftmost path of the tree\n stack = list([root])\n while stack[-1].left:\n stack.append(stack[-1].left)\n\n preval = float('-inf')\n while len(stack) > 0:\n top = stack[-1]\n if top.val <= preval: return False\n\n # pop the top, add its immediate right child and that chid's left most path\n preval = top.val\n stack.pop()\n if top.right:\n stack.append(top.right)\n while stack[-1].left:\n stack.append(stack[-1].left)\n\n return True\n\n def isValidBST3b(self, root):\n '''\n Solution 3b: In-order iterative traversal but smarter.\n Key: Use null to signal that left tree of the top-of-the-stack node is gone.\n Learn from https://leetcode.com/problems/validate-binary-search-tree/discuss/32112/Learn-one-iterative-inorder-traversal-apply-it-to-multiple-tree-questions-(Java-Solution)\n Passed!\n '''\n stack = list()\n preval = float('-inf')\n\n while root or len(stack) > 0:\n # add root and its left most path to stack\n while root:\n stack.append(root)\n root = root.left\n\n # the left tree of top-of-the-stack node is gone at this point\n root = stack.pop()\n if root.val <= preval:\n return False\n preval = root.val\n\n # the brilliant assignment without checking for None on root.right!\n root = root.right\n\n return True","sub_path":"2018/lc_ValidateBST.py","file_name":"lc_ValidateBST.py","file_ext":"py","file_size_in_byte":4500,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"621073906","text":"\"\"\"remove table session_scores\n\nRevision ID: f0d14b53f8d2\nRevises: c8d111efa2dd\nCreate Date: 2021-02-23 21:46:00.667947\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = 'f0d14b53f8d2'\ndown_revision = 'c8d111efa2dd'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_table('session_scores')\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_table('session_scores',\n sa.Column('session_id', sa.INTEGER(), autoincrement=False, nullable=False),\n sa.Column('user_id', sa.INTEGER(), autoincrement=False, nullable=False),\n sa.Column('score', sa.INTEGER(), autoincrement=False, nullable=False),\n sa.Column('id', sa.INTEGER(), autoincrement=False, nullable=False),\n sa.ForeignKeyConstraint(['session_id'], ['game_sessions.id'], name='session_scores_session_id_fkey', ondelete='CASCADE'),\n sa.ForeignKeyConstraint(['user_id'], ['users.user_id'], name='session_scores_user_id_fkey', ondelete='CASCADE')\n )\n # ### end Alembic commands ###\n","sub_path":"migrations/versions/f0d14b53f8d2_remove_table_session_scores.py","file_name":"f0d14b53f8d2_remove_table_session_scores.py","file_ext":"py","file_size_in_byte":1175,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"356221844","text":"# coding=utf-8\n# Copyright 2015 Pants project contributors (see CONTRIBUTORS.md).\n# Licensed under the Apache License, Version 2.0 (see LICENSE).\n\nfrom __future__ import (absolute_import, division, generators, nested_scopes, print_function,\n unicode_literals, with_statement)\n\nimport unittest\nfrom os.path import join\n\nfrom pants.base.project_tree import Dir\nfrom pants.engine.fs import PathDirWildcard, PathGlobs, PathRoot, PathWildcard\n\n\ndef pw(relative_to, *args):\n return PathWildcard(Dir(relative_to), relative_to, *args)\n\n\ndef pdw(relative_to, *args):\n return PathDirWildcard(Dir(relative_to), relative_to, *args)\n\n\nclass PathGlobsTest(unittest.TestCase):\n\n def assert_pg_equals(self, pathglobs, relative_to, filespecs):\n self.assertEquals(PathGlobs(tuple(pathglobs)), PathGlobs.create_from_specs(relative_to, filespecs))\n\n def test_root(self):\n self.assert_pg_equals([PathRoot()], '', [''])\n\n def test_literal(self):\n subdir = 'foo'\n name = 'Blah.java'\n self.assert_pg_equals([pw('', name)], '', [name])\n self.assert_pg_equals([pw(subdir, name)], subdir, [name])\n self.assert_pg_equals([pdw('', subdir, name)], '', [join(subdir, name)])\n\n def test_wildcard(self):\n name = '*.java'\n subdir = 'foo'\n self.assert_pg_equals([pw('', name)], '', [name])\n self.assert_pg_equals([pw(subdir, name)], subdir, [name])\n\n def test_dir_wildcard(self):\n name = 'Blah.java'\n subdir = 'foo'\n wildcard = '*'\n self.assert_pg_equals([pdw(subdir, wildcard, name)],\n subdir,\n [join(wildcard, name)])\n\n def test_dir_wildcard_directory(self):\n subdir = 'foo'\n wildcard = '*'\n name = '.'\n self.assert_pg_equals([pw('', wildcard)],\n '',\n [join(wildcard, name)])\n self.assert_pg_equals([pw(subdir, wildcard)],\n subdir,\n [join(wildcard, name)])\n\n def test_recursive_dir_wildcard(self):\n name = 'Blah.java'\n subdir = 'foo'\n wildcard = '**'\n self.assert_pg_equals([pdw(subdir, '*', join(wildcard, name)), pw(subdir, name)],\n subdir,\n [join(wildcard, name)])\n\n def test_trailing_doublestar(self):\n subdir = 'foo'\n wildcard = '**'\n self.assert_pg_equals([pdw(subdir, '*', wildcard), pw(subdir, '*')],\n subdir,\n [wildcard])\n\n def test_doublestar_mixed_wildcard(self):\n subdir = 'foo'\n wildcard = '**abc'\n name = 'Blah.java'\n\n self.assert_pg_equals([pw(subdir, wildcard)], subdir, [wildcard])\n self.assert_pg_equals([pdw(subdir, wildcard, name)], subdir, [join(wildcard, name)])\n","sub_path":"tests/python/pants_test/engine/test_path_globs.py","file_name":"test_path_globs.py","file_ext":"py","file_size_in_byte":2732,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"613860644","text":"\nfrom flask import Flask, render_template, jsonify ,request \nfrom flask_sqlalchemy import SQLAlchemy\nimport pandas as pd\n# from sklearn.linear_model import LinearRegression\nfrom sqlalchemy import func,extract\nfrom _operator import not_\nimport datetime\n# flask edition:0.12\nimport time\nimport os\nfrom sklearn.tree import DecisionTreeRegressor\nfrom sklearn.feature_extraction import DictVectorizer\nfrom app_.translate_time import TimeStampToTime,get_FileModifyTime\nfrom prediction.predictor import predict_,predict_model,create_predict_set\nimport joblib\n\nclass Config(object):\n \"\"\"setting the configuration\"\"\"\n # use sqlalchemy configure the connection\n # format:mysql://username:password@host:port/database_name\n# SQLALCHEMY_DATABASE_URI = \"{}://{}:{}@{}:{}/{}\".format( )\n\n SQLALCHEMY_DATABASE_URI = \"mysql+pymysql://se12:software@dbbikes12.c5cm18ftdu4w.eu-west-1.rds.amazonaws.com:3306/dbbike12\"\n # set sqlalchemy track the data automatically\n SQLALCHEMY_TRACK_MODIFICATIONS = True\n \n\n# create an object\napp = Flask(__name__)\n\napp.config.from_object(Config)\n\ndb = SQLAlchemy(app)\n\nclass StationFix(db.Model):\n \"\"\"create a model class for station_fix(static data )\"\"\"\n __tablename__ = \"station_fix\"\n\n address = db.Column(db.String(256))\n number = db.Column(db.Integer, unique=True, primary_key=True)\n contract_name = db.Column(db.String(256))\n bonus = db.Column(db.String(256))\n position_lat = db.Column(db.Integer)\n position_lng = db.Column(db.Integer)\n station_relationship = db.relationship(\"Station\", backref=\"stationfix\")\n \n def to_dict(self):\n '''Convert the object into dictionary'''\n return {c.name: getattr(self, c.name) for c in self.__table__.columns}\n \n \nclass Station(db.Model):\n \"\"\"create an Model class for station(dynamic data )\"\"\"\n __tablename__ = \"station\"\n\n number = db.Column(db.Integer, db.ForeignKey(\"station_fix.number\"), unique=True, primary_key=True,)\n available_bikes = db.Column(db.Integer)\n available_bike_stands = db.Column(db.Integer)\n banking = db.Column(db.Integer)\n bike_stands = db.Column(db.Integer)\n status = db.Column(db.String(256))\n weather = db.Column(db.String(256))\n icon = db.Column(db.String(256))\n temperature = db.Column(db.String(256))\n humidity = db.Column(db.String(256))\n wind_speed = db.Column(db.String(256))\n future_weather = db.Column(db.String(256))\n future_temperature = db.Column(db.String(256))\n future_icon = db.Column(db.String(256))\n time = db.Column(db.String(256), unique=True, primary_key=True)\n\n\n def to_dict(self):\n '''Convert the object into dictionary'''\n return {c.name: getattr(self, c.name) for c in self.__table__.columns}\n\n\n#weather class,for future\n# class Weather(db.Model):\n \n\n# this route simply serves the map page\n@app.route('/')\ndef index():\n return render_template('HomePage.html')\n\n@app.route('/all_stations')\ndef show_map():\n return render_template('map.html')\n\n@app.route('/search')\ndef search_page():\n return render_template('Search.html')\n\n@app.route('/prediction')\ndef prediction_page():\n return render_template('Prediction.html')\n\n@app.route('/our_team')\ndef show_teaminfo():\n return render_template('OurTeam.html')\n\n#query all the station and return 'json' file \n@app.route(\"/stations\")\ndef get_all_stations():\n # query the database\n stations = StationFix.query.all()\n stations_recent = db.session.query(Station.number,Station.available_bikes,Station.available_bike_stands).order_by(Station.time.desc()).limit(113).all()\n station_li = []\n for station in stations:\n station = station.to_dict()\n for row in stations_recent:\n if station['number'] == row[0]:\n station['available_bikes']=row[1]\n station['available_bike_stands']=row[2]\n break\n station_li.append(station) \n return jsonify(stations=station_li)\n\n#query single station and return 'json' file )\n \n@app.route(\"/available/\") \ndef get_stations(station_id):\n station_recent = Station.query.filter_by(number=station_id).order_by(Station.time.desc()).first().to_dict()\n \n recent_time = datetime.datetime.strptime(station_recent['time'],\"%Y-%m-%d_%H:%M:%S\")+datetime.timedelta(hours=1)\n if recent_time\")\ndef get_weather(station_id):\n row = db.session.query(Station.weather, Station.icon, Station.temperature, Station.humidity, Station.wind_speed, Station.future_weather, Station.future_temperature, Station.future_icon, Station.time).filter_by(number=station_id).order_by(Station.time.desc()).first()\n return jsonify(station_wheather = row)\n\n@app.route(\"/predict\")\ndef predict():\n station_id = request.form.get('station')\n date = request.form.get('date')\n\n# aquire the 'dbbikes_model.pkl' last modified time and the current time,if they are the same day, system will not train the data again \n file_modify_time = get_FileModifyTime('dbbikes_model.pkl')\n now = TimeStampToTime(time.time())\n \n if now == file_modify_time:\n model = joblib.load(\"dbbikes_model.pkl\")\n else:\n rows = db.session.query(Station.number,Station.available_bikes,Station.available_bike_stands,Station.weather,Station.temperature,Station.time).filter(Station.weather.isnot(None)).order_by(Station.time.desc()).all()\n df = pd.DataFrame(rows,columns = ['number','available_bikes','available_bike_stands','weather','temperature','time'])\n predict_(df)\n model = joblib.load(\"dbbikes_model.pkl\")\n \n# df = create_predict_set(station_id, date)\n df = create_predict_set(station_id,date)\n prediction_data = model.predict(df)\n \n return jsonify(prediction_data = prediction_data )\n \n\nif __name__ == '__main__':\n app.run(debug=True)\n\n","sub_path":"test/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":7160,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"208955187","text":"import os\nimport utm\nfrom h3 import h3\nimport subprocess\nimport progressbar\nimport pandas as pd\nimport shapely.wkt as shw\nfrom geopandas import GeoDataFrame\nfrom shapely.geometry import Polygon\n\nwgs84 = False\ndebug = False\nlaz_downloads = os.path.join(os.getcwd(), 'downloads2L15csv')\nraster_path = os.path.join(os.getcwd(), 'L15Rasterization')\n# type_z = ['elevation', 'slope', 'aspect', 'upslope', 'twi']\ntype_z = ['elevation']\n\n\ndef run_cmd(cmd):\n p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True)\n output, errors = p.communicate()\n if p.returncode != 0:\n print(cmd)\n print('\\tcombined output:', repr(output))\n print('\\tstderr:', repr(errors))\n\n\ndef main():\n files1 = set(f.split('.')[0] for f in os.listdir(laz_downloads) if f.endswith('.csv'))\n files2 = set(f.split('.')[0] for f in os.listdir(os.path.join(raster_path, type_z[0])) if f.endswith('.tif'))\n fs = sorted(list(files1 - files2))\n files = list(os.path.join(laz_downloads, str(f) + '.csv') for f in fs)\n for f in progressbar.progressbar(files):\n df = pd.read_csv(os.path.join(laz_downloads, f), sep=',', quotechar='\"')\n geom = list(list(shw.loads(wkt).exterior.coords)[0:-1] for wkt in df['wkt'])\n geometry = list()\n for ring in geom:\n line = list()\n for p in ring:\n pj = utm.from_latlon(p[1], p[0])\n line.append((pj[0], pj[1]))\n geometry.append(Polygon(line))\n crs = \"+proj=utm +zone=\" + str(df['zone_num'][0]) + \" +ellps=GRS80 +datum=NAD83 +units=m +no_defs\"\n geo_df = GeoDataFrame(df, crs=crs, geometry=geometry)\n lyr_name = os.path.basename(f).split('.')[0]\n shp_name, tif_name = str(lyr_name) + '.shp', str(lyr_name) + '.tif'\n shp_path = os.path.join(raster_path, shp_name)\n geo_df.to_file(driver='ESRI Shapefile', filename=shp_path)\n pixel_size = h3.edge_length(df['resolution'][0], 'm') / 5.0\n for zf in type_z:\n tif_path = os.path.join(raster_path, zf, tif_name)\n cmd = ['gdal_rasterize',\n '-a', zf,\n '-tr', str(pixel_size), str(pixel_size),\n '-a_nodata', 'none',\n '-l', lyr_name,\n shp_path,\n tif_path]\n run_cmd(cmd)\n if wgs84:\n cmd = ['gdalwarp',\n '-overwrite',\n tif_path,\n os.path.join(raster_path, 'wgs84', zf, tif_name),\n '-t_srs',\n 'EPSG:4326']\n run_cmd(cmd)\n if not debug:\n for ext in ['.cpg', '.dbf', '.prj', '.shp', '.shx']:\n os.remove(os.path.join(raster_path, str(lyr_name) + ext))\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"rasterizing.py","file_name":"rasterizing.py","file_ext":"py","file_size_in_byte":2871,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"197176137","text":"import datetime\nimport json\n# import asyncio\nfrom aiohttp import web\nfrom settings import logger\nimport settings\nimport database\n\n\ndef json_serial(self, data):\n if isinstance(data, (datetime.datetime, tuple)):\n return data.__str__()\n return data\n\n\nasync def drop_cache(request):\n with (await database.distributors_cache_semaphore), (await database.distributors_semaphore):\n database.distributors = {}\n database.distributors_cache = {}\n return web.Response(status=200, text='OK')\n\n\nasync def show_cache(request):\n with (await database.distributors_cache_semaphore):\n # print(database.distributors_cache)\n response = {f'{k[0]} {k[1]} {k[2]}': {'name': v[0], 'cut': v[1], 'id': v[2]} for k, v in database.distributors_cache.items()}\n return web.Response(status=200, text=json.dumps(response), content_type='application/json')\n\n\nasync def smsc(request):\n \"\"\" Запрос СМС шлюза \"\"\"\n pool = request.app['postgres']\n phone = request.match_info['phone'][-10:]\n response = '{}'\n if (len(phone) == max(settings.PHONE_LENGTH)) and (phone[0] == '9'):\n smsc_gate, channel, sended, phone = await database.select_smsc(phone, pool)\n response = {'phone': phone, 'smsc': smsc_gate, 'channel': channel, 'sended': sended}\n return web.Response(status=200, text=json.dumps(response), content_type='application/json')\n\n\nasync def distributor(request):\n response = '{}'\n pool = request.app['postgres']\n phone = request.match_info['phone'][-10:]\n lock = int(request.match_info['lock']) != 0\n if len(phone) in settings.PHONE_LENGTH:\n distributor, phone = await database.select_distributor(phone, pool)\n logger.info(f'{phone} {distributor}')\n if lock:\n await database.distributors[distributor].acquire()\n response = {'phone': phone, 'distributor': distributor, 'locked': lock}\n return web.Response(status=200, text=json.dumps(response), content_type='application/json')\n\n\nasync def distributor_unlock(request):\n distributor = request.match_info['distributor'].lower()\n response = {'distributor': distributor}\n if distributor in database.distributors.keys():\n database.distributors[distributor].release()\n response.update({'result': 0, 'state': database.distributors[distributor].locked()})\n else:\n response.update({'result': 1})\n return web.Response(status=200, text=json.dumps(response), content_type='application/json')\n","sub_path":"distributor/handlers.py","file_name":"handlers.py","file_ext":"py","file_size_in_byte":2486,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"168098186","text":"\"\"\"This is only a template controller which simply drives the car forward\n\"\"\"\n\nfrom vehicle import Driver\nimport math\nfrom collections import defaultdict\nfrom heapq import *\nimport pandas as pd\n\ndriver = Driver()\n\n# An example of how you get a sensor and initialize it.\n# You are free to use all the sensors that comes with your car.\n# Check Sensor Slot fields on the vehicle in the left pane of Webots for available sensors.\n\nWORLD_TIME_STEP = 16 # This is already set in the world file.\nFRONT_LIDAR_REFRESH_RATE = 160\nRIGHT_LIDAR_REFRESH_RATE = 160\nLEFT_LIDAR_REFRESH_RATE = 160\nCAMERA_REFRESH_RATE = 32\n\ntop_lidar = driver.getLidar(\"Velodyne VLP-16\")\ntop_lidar.enable(FRONT_LIDAR_REFRESH_RATE)\ntop_lidar.enablePointCloud()\n\nright_lidar = driver.getLidar(\"Sick LMS 291 Right\")\nright_lidar.enable(RIGHT_LIDAR_REFRESH_RATE)\nright_lidar.enablePointCloud()\n\nleft_lidar = driver.getLidar(\"Sick LMS 291 Left\")\nleft_lidar.enable(LEFT_LIDAR_REFRESH_RATE)\nleft_lidar.enablePointCloud()\n\ncamera = driver.getCamera(\"camera\")\ncamera.enable(CAMERA_REFRESH_RATE)\n\ndef dijkstra_raw(edges, from_node, to_node):\n g = defaultdict(list)\n for l,r,c in edges:\n g[l].append((c,r))\n q, seen = [(0,from_node,())], set()\n while q:\n (cost,v1,path) = heappop(q)\n if v1 not in seen:\n seen.add(v1)\n path = (v1, path)\n if v1 == to_node:\n return cost,path\n for c, v2 in g.get(v1, ()):\n if v2 not in seen:\n heappush(q, (cost+c, v2, path))\n return float(\"inf\"),[]\n\ndef dijkstra(edges, from_node, to_node):\n len_shortest_path = -1\n ret_path=[]\n length,path_queue = dijkstra_raw(edges, from_node, to_node)\n if len(path_queue)>0:\n len_shortest_path = length\t\t## 1. Get the length firstly;\n ## 2. Decompose the path_queue, to get the passing nodes in the shortest path.\n left = path_queue[0]\n ret_path.append(left)\t\t## 2.1 Record the destination node firstly;\n right = path_queue[1]\n while len(right)>0:\n left = right[0]\n ret_path.append(left)\t## 2.2 Record other nodes, till the source-node.\n right = right[1]\n ret_path.reverse()\t## 3. Reverse the list finally, to make it be normal sequence.\n return len_shortest_path,ret_path\n\t\nlist_nodes_id = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16];\n\nM=99999\n\nM_topo = [\n[M, 1,M,M,1,M, M,M,M,M,M, M,M,M,M,M],\n[1, M,1,M,M,1, M,M,M,M,M, M,M,M,M,M],\n[M, 1,M,1,M,M, 1,M,M,M,M, M,M,M,M,M],\n[M, M,1,M,M,M, M,1,M,M,M, M,M,M,M,M],\n[1, M,M,M,M,1, M,M,1,M,M, M,M,M,M,M],\n[M, 1,M,M,1,M, 1,M,M,1,M, M,M,M,M,M],\n[M, M,1,M,M,1, M,1,M,M,1, M,M,M,M,M],\n[M, M,M,1,M,M, 1,M,M,M,M, 1,M,M,M,M],\n[M, M,M,M,1,M, M,M,M,1,M, M,1,M,M,M],\n[M, M,M,M,M,1, M,M,1,M,1, M,M,1,M,M],\n[M, M,M,M,M,M, 1,M,M,1,M, 1,M,M,1,M],\n[M, M,M,M,M,M, M,1,M,M,1, M,M,M,M,1],\n[M, M,M,M,M,M, M,M,1,M,M, M,M,1,M,M],\n[M, M,M,M,M,M, M,M,M,1,M, M,1,M,1,M],\n[M, M,M,M,M,M, M,M,M,M,1, M,M,1,M,1],\n[M, M,M,M,M,M, M,M,M,M,M, 1,M,M,1,M],\n]\n\ndataset = pd.read_csv('plan.csv')\nX = dataset.iloc[:, 0:2].values\ninitial = X[0,0]\nstart = X[0,1]\ngoal = X[1,0]\nfinal = X[1,1]\n\nif start == 1 and final == 1:\n if initial == 2 and goal == 5:\n Shortest_path = [1,5,9,10,6,5]\n elif initial == 5 and goal == 2:\n Shortest_path = [1,2,3,7,6,2]\nelif initial == 1 and goal == 1:\n if start == 2 and final == 5:\n Shortest_path = [2,3,7,6,2,1]\n elif start == 5 and final == 2:\n Shortest_path = [5,9,10,6,5,1]\nelif start == 4 and final == 4:\n if initial == 3 and goal == 8:\n Shortest_path = [4,8,12,11,7,8]\n elif initial == 8 and goal == 3:\n Shortest_path = [4,3,2,6,7,3]\nelif initial == 4 and goal == 4:\n if start == 3 and final == 8:\n Shortest_path = [3,2,6,7,3,4]\n elif start == 8 and final == 3:\n Shortest_path = [8,12,11,7,8,4]\nelif start == 13 and final == 13:\n if initial == 9 and goal == 14:\n Shortest_path = [13,14,15,11,10,14]\n elif initial == 14 and goal == 9:\n Shortest_path = [13,9,5,6,10,9]\nelif initial == 13 and goal == 13:\n if start == 9 and final == 14:\n Shortest_path = [9,5,6,10,9,13]\n elif start == 14 and final == 9:\n Shortest_path = [14,15,11,10,14,13]\nelif start == 16 and final == 16:\n if initial == 12 and goal == 15:\n Shortest_path = [16,15,14,10,11,15]\n elif initial == 15 and goal == 12:\n Shortest_path = [16,12,8,7,11,12]\nelif initial == 16 and goal == 16:\n if start == 12 and final == 15:\n Shortest_path = [12,8,7,11,12,16]\n elif start == 15 and final == 12:\n Shortest_path = [15,14,10,11,15,16]\nelse:\n M_topo[final - 1][goal - 1] = M\n M_topo[goal - 1][final - 1] = M\n M_topo[start - 1][initial - 1] = M\n edges = []\t\n for i in range(len(M_topo)):\n for j in range(len(M_topo[0])):\n if M_topo[i][j]!=M:\n edges.append((i + 1,j + 1,M_topo[i][j]))\n length,Shortest_path = dijkstra(edges, start, goal)\n\naction = [None]*len(Shortest_path)# 1 means staright ,2 means turn left, 3 means turn right\nheading = [None]*(len(Shortest_path)+1) # 1 means up, 2 means down, 3 means left ,4 means right\n\nif start - initial == -4:\n heading[0] = 1 # 1 means up\nelif start - initial == 4:\n heading[0] = 2 # 2 means down\nelif start - initial == -1:\n heading[0] = 3 # 3 means left\nelif start - initial == 1:\n heading[0] = 4 # 4 means right \n\nif len(Shortest_path) >= 2:\n for i in range(1,len(Shortest_path)):\n if heading[i - 1] == 1:\n if Shortest_path[i] - Shortest_path[i - 1] == -1:\n action[i - 1] = 2 # turn left\n heading[i] = 3\n elif Shortest_path[i] - Shortest_path[i - 1] == -4:\n action[i - 1] = 1 #straight\n heading[i] = 1\n elif Shortest_path[i] - Shortest_path[i - 1] == 1:\n action[i - 1] = 3 # turn right\n heading[i] = 4\n elif heading[i - 1] == 2:\n if Shortest_path[i] - Shortest_path[i - 1] == -1:\n action[i - 1] = 3 # turn right\n heading[i] = 3\n elif Shortest_path[i] - Shortest_path[i - 1] == 4:\n action[i - 1] = 1 #straight\n heading[i] = 2\n elif Shortest_path[i] - Shortest_path[i - 1] == 1:\n action[i - 1] = 2 # turn left\n heading[i] = 4\n elif heading[i - 1] == 3:\n if Shortest_path[i] - Shortest_path[i - 1] == -1:\n action[i - 1] = 1 # straight\n heading[i] = 3\n elif Shortest_path[i] - Shortest_path[i - 1] == -4:\n action[i - 1] = 3 # turn right\n heading[i] = 1\n elif Shortest_path[i] - Shortest_path[i - 1] == 4:\n action[i - 1] = 2 # turn left\n heading[i] = 2\n elif heading[i - 1] == 4:\n if Shortest_path[i] - Shortest_path[i - 1] == 1:\n action[i - 1] = 1 # straight\n heading[i] = 4\n elif Shortest_path[i] - Shortest_path[i - 1] == -4:\n action[i - 1] = 2 # turn left\n heading[i] = 1\n elif Shortest_path[i] - Shortest_path[i - 1] == 4:\n action[i - 1] = 3 # turn right\n heading[i] = 2\n \n if final - goal == -4:\n heading[len(Shortest_path)] = 1 # 1 means up\n if goal - Shortest_path[len(Shortest_path) - 2] == 1:\n action[len(Shortest_path) - 1] = 2 # turn left\n elif goal - Shortest_path[len(Shortest_path) - 2] == -1:\n action[len(Shortest_path) - 1] = 3 # turn right\n elif goal - Shortest_path[len(Shortest_path) - 2] == -4:\n action[len(Shortest_path) - 1] = 1 # straight\n elif final - goal == 4:\n heading[len(Shortest_path)] = 2 # 2 means down\n if goal - Shortest_path[len(Shortest_path) - 2] == 1:\n action[len(Shortest_path) - 1] = 3 # turn right\n elif goal - Shortest_path[len(Shortest_path) - 2] == -1:\n action[len(Shortest_path) - 1] = 2 # turn left\n elif goal - Shortest_path[len(Shortest_path) - 2] == 4:\n action[len(Shortest_path) - 1] = 1 # straight\n elif final - goal == -1:\n heading[len(Shortest_path)] = 3 # 3 means left\n if goal - Shortest_path[len(Shortest_path) - 2] == -1:\n action[len(Shortest_path) - 1] = 1 # staright\n elif goal - Shortest_path[len(Shortest_path) - 2] == 4:\n action[len(Shortest_path) - 1] = 3 # turn right\n elif goal - Shortest_path[len(Shortest_path) - 2] == -4:\n action[len(Shortest_path) - 1] = 2 # turn left\n elif final - goal == 1:\n heading[len(Shortest_path)] = 4 # 4 means right\n if goal - Shortest_path[len(Shortest_path) - 2] == 1:\n action[len(Shortest_path) - 1] = 1 # staright\n elif goal - Shortest_path[len(Shortest_path) - 2] == 4:\n action[len(Shortest_path) - 1] = 2 # turn left\n elif goal - Shortest_path[len(Shortest_path) - 2] == -4:\n action[len(Shortest_path) - 1] = 3 # turn right\n \nif len(Shortest_path) == 1:\n if heading[0] == 1:\n if final - goal == -4:\n heading[1] = 1\n action[0] = 1\n elif final - goal == -1:\n heading[1] = 3\n action[0] = 2\n elif final - goal == 1:\n heading[1] = 4\n action[0] = 3\n elif heading[0] == 2:\n if final - goal == 4:\n heading[1] = 2\n action[0] = 1\n elif final - goal == -1:\n heading[1] = 3\n action[0] = 3\n elif final - goal == 1:\n heading[1] = 4\n action[0] = 2\n elif heading[0] == 3:\n if final - goal == -4:\n heading[1] = 1\n action[0] = 3\n elif final - goal == -1:\n heading[1] = 3\n action[0] = 1\n elif final - goal == 4:\n heading[1] = 2\n action[0] = 2\n elif heading[0] == 4:\n if final - goal == -4:\n heading[1] = 1\n action[0] = 2\n elif final - goal == 1:\n heading[1] = 4\n action[0] = 1\n elif final - goal == 4:\n heading[1] = 2\n action[0] = 3\n \nprint ('The shortest path is ',Shortest_path)\nprint ('heading',heading)\nprint ('action',action)\n\ncurrent_time_ms = 0\nk = 0 # the number of intersections that the vehicle have countered\nstate = 1 # the original state of the car is driving straightly\nd_left_mean = 0\nd_right_mean = 0\nflag = 2\ntime = 0\n\nwhile driver.step() != -1: # This is your control loop. Every step means 16ms has passed in the simulation.\n# The following is only an example starting point. Feel free to change the way you read the sensors. (Check Webots Reference Manual)\n current_time_ms = current_time_ms + WORLD_TIME_STEP\n if current_time_ms % FRONT_LIDAR_REFRESH_RATE == 0:\n # I choose the 11th layer of the top lidar\n top_lidar_layer_11 = top_lidar.getLayerPointCloud(10)\n d = 0\n\n # choose the 1600th to 1999th(front) lidar point of the top lidar\n # use all the choosed lidar points' x and z to calculate the average 2D distance to lidar\n # this is used to avoid colliding with the front obstacles\n for i in range(0,399):\n d = d + math.sqrt((top_lidar_layer_11[i+1600].x) ** 2 + (top_lidar_layer_11[i+1600].z) ** 2) \n d_mean = d / 400\n \n if current_time_ms % RIGHT_LIDAR_REFRESH_RATE == 0:\n right_lidar_layer = right_lidar.getLayerPointCloud(0); # This lidar is a single-layer lidar. \n d_right = 0\n \n # choose the 70th to 89th lidar point of the right lidar\n # use all the choosed lidar points' x and z to calculate the average 2D distance to lidar\n # this is used to detect the intersection\n for j in range(70,90):\n d_right = d_right + math.sqrt((right_lidar_layer[j].x) ** 2 + (right_lidar_layer[j].z) ** 2)\n d_right_mean = d_right / 20\n \n\n if current_time_ms % LEFT_LIDAR_REFRESH_RATE == 0:\n left_lidar_layer = left_lidar.getLayerPointCloud(0); # This lidar is a single-layer lidar.\n d_left = 0\n \n # choose the 90th to 110th lidar point of the left lidar\n # use all the choosed lidar points' x and z to calculate the average 2D distance to lidar\n # this is used to detect the intersection\n for l in range(90,110):\n d_left = d_left + math.sqrt((left_lidar_layer[l].x) ** 2 + (left_lidar_layer[l].z) ** 2)\n d_left_mean = d_left / 20\n \n if d_left_mean - d_right_mean > 3:\n state = 4\n elif d_right_mean - d_left_mean > 1:\n state = 5\n else:\n state = 1\n \n if d_left_mean < 1:\n state = 5\n elif d_right_mean < 1:\n state = 4\n \n if flag == 1:\n flag = 0\n \n # the action when the vehicle is at the intersection\n if d_left_mean + d_right_mean > 10:\n if k < len(action):\n state = action[k]\n if state == 1 and d_right_mean - d_left_mean > 18:\n state = 4\n flag = 1\n \n if flag == 0:\n k = k + 1\n time = current_time_ms\n flag = 2\n \n if k >= len(action):\n state = 6\n \n #if current_time_ms % FRONT_LIDAR_REFRESH_RATE == 0:\n #print(\"left\",d_left_mean)\n #print(\"right\",d_right_mean)\n #print(\"state\",state)\n #print(\"flag\",flag)\n #print(\"k\",k)\n \n #to make sure the vehicle has already crossed the intersection\n #if current_time_ms - time >640\n #k = k + 1 会导致k不停的增加\n \n # when there is no obstacle or barrier which is quite close to the car,state = 0\n if state == 1: \n driver.setCruisingSpeed(20.0) \n driver.setBrakeIntensity(0)\n driver.setSteeringAngle(0.0)\n # the vehichle is at the intersection and needs to turn left \n elif state == 2:\n driver.setCruisingSpeed(10.0)\n driver.setBrakeIntensity(0.5)\n driver.setSteeringAngle(-0.4)\n # the vehicle is at the intersection and needs to turn right\n elif state == 3:\n driver.setCruisingSpeed(10.0)\n driver.setBrakeIntensity(0.5)\n driver.setSteeringAngle(0.4)\n # the vehicle is quite close to the barrier on its right\n elif state == 4:\n driver.setCruisingSpeed(15.0)\n driver.setBrakeIntensity(0.0)\n driver.setSteeringAngle(-0.2)\n # the vehicle is quite close to the barrier on its left\n elif state == 5:\n driver.setCruisingSpeed(15.0)\n driver.setBrakeIntensity(0.0)\n driver.setSteeringAngle(0.2)\n # the vehicle is near the goal\n else:\n driver.setCruisingSpeed(0.0)\n driver.setBrakeIntensity(0.0)\n driver.setSteeringAngle(0.0)\n","sub_path":"Pro1/project/controllers/milestone2_part1_controller/milestone2_part1_controller.py","file_name":"milestone2_part1_controller.py","file_ext":"py","file_size_in_byte":14863,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"35276969","text":"import numpy as np\nimport subprocess\nfrom dataportal import DataBroker, DataMuxer\nfrom dataportal.broker import EventQueue\nimport matplotlib.pyplot as plt\nimport time as ttime\nimport sys\nfrom ophyd.userapi.scan_api import estimate\n\ndef new_queue(header, queue=None):\n if queue is None:\n queue = EventQueue(header)\n return header, queue\n hdr = DataBroker[-1]\n if header.scan_id != hdr.scan_id:\n print(\"New header found: Scan id = %s. uid = %s\" % \n (hdr.scan_id, hdr.run_start_uid))\n sys.stdout.flush()\n queue = EventQueue(hdr)\n return hdr, queue\n return header, queue\n\nvlines = {'center_of_mass': {'color': 'red'},\n 'cen': {'color': 'red', 'ls': '--'},}\nhlines = {'avgy': {'color': 'blue', 'ls': '-'}, \n 'ymin': {'color': 'black', 'ls': '--'}, \n 'ymax': {'color': 'black', 'ls': '--'}, }\npoints = {'cen': {'color': 'red', 'marker': 'o'},\n 'fwmh_left': {'color': 'red', 'marker': '<'}, \n 'fwhm_right': {'color': 'red', 'marker': '>'}}\n \ndef plot1d(y, x=None, scans=None, live=True, sleep_time=1):\n \"\"\"Plot live data and on-the-fly peak stats estimator\n\n Parameters\n ----------\n y : str\n The name of the y value to plot\n x : str, optional\n The name of the value to plot on the x axis. If None, defaults \n to the sequence number of the event (Note that this probably works, \n but I'm not sure as it has not been tested!)\n scans : list, optional\n List of other scan indices to plot. uses db[] syntax, so any valid\n entry to [] will work\n live : bool, optional\n Grab new data and plot it as it comes off. Defaults to True.\n sleep_time : float, optional\n Time to sleep between data updates. Defaults to 1 sec\n \"\"\"\n if scans is None:\n scans = []\n lines1 = {}\n fig, (ax1, ax2) = plt.subplots(nrows=2, figsize=(15,10), sharex=True)\n fig.show()\n for scan_id in scans:\n hdr = DataBroker[scan_id]\n events = DataBroker.fetch_events(hdr)\n dm = DataMuxer.from_events(events)\n df = dm.to_sparse_dataframe()\n if x is None:\n old_x = np.asarray(df.index)\n else:\n old_x = np.asarray(df[x])\n old_y = np.asarray(df[y])\n lines1[scan_id], = ax1.plot(old_x, old_y, 'o', ms=15, label=scan_id)\n if x is None:\n ax1.set_xlabel('scan point index')\n ax2.set_xlabel('scan point index')\n else:\n ax1.set_xlabel(x)\n ax2.set_xlabel(x)\n ax1.set_ylabel(y)\n ax2.set_ylabel(y)\n ax1.set_title('data stream')\n ax2.set_title('peak estimator')\n\n if live:\n hdr = DataBroker[-1]\n scan_id = hdr.scan_id\n while scan_id in lines1:\n ttime.sleep(.5)\n hdr = DataBroker[-1]\n scan_id = hdr.scan_id\n lines1[scan_id], = ax1.plot([], [], 'o', ms=15, label=scan_id)\n queue = None\n prev_stats = None\n while True:\n # loop until killed\n hdr, queue = new_queue(hdr, queue)\n scan_id = hdr.scan_id\n queue.update()\n new_events = queue.get()\n try:\n old_x, old_y = lines1[scan_id].get_data()\n old_x = list(old_x)\n old_y = list(old_y)\n except KeyError:\n lines1[scan_id], = ax1.plot([], [], 'o', ms=15, label=scan_id)\n old_x, old_y = [], []\n if x is None:\n new_x = [event.seq_num for ev in new_events]\n else:\n new_x = [ev['data'][x] for ev in new_events]\n new_y = [ev['data'][y] for ev in new_events]\n new_x = old_x + new_x\n new_y = old_y + new_y\n lines1[scan_id].set_data(new_x, new_y)\n ax1.relim(visible_only=True)\n ax1.legend(loc=0).draggable()\n \n # now deal with axis 2\n try:\n stats = estimate(np.asarray(new_x), np.asarray(new_y))\n except ValueError:\n stats = prev_stats\n # print(stats)\n if stats != prev_stats:\n ax2.cla()\n ax2.plot(new_x, new_y, 'o', ms=15, label=scan_id)\n ax2.set_title('peak estimator')\n for stat, vals in stats.items():\n if stat in points:\n # sometimes 'cen' comes back as one or two values. This\n # try/except block is a way to do the right thing when \n # this happens\n try:\n vals[0]\n ax2.scatter(vals[0], vals[1], label=stat, **points[stat])\n except IndexError:\n ax2.axvline(vals, label=stat, **vlines[stat])\n elif stat in hlines:\n # draw a horizontal line\n ax2.axhline(vals, label=stat, **hlines[stat])\n elif stat in vlines:\n # draw a vertical line\n ax2.axvline(vals, label=stat, **vlines[stat])\n prev_stats = stats\n ax2.relim(visible_only=True)\n ax2.legend(loc=0).draggable()\n fig.canvas.draw()\n fig.canvas.flush_events()\n ttime.sleep(sleep_time)\n\n","sub_path":"chxtools/plot.py","file_name":"plot.py","file_ext":"py","file_size_in_byte":5392,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"7393376","text":"\n\nfrom xai.brain.wordbase.nouns._diesel import _DIESEL\n\n#calss header\nclass _DIESELS(_DIESEL, ):\n\tdef __init__(self,): \n\t\t_DIESEL.__init__(self)\n\t\tself.name = \"DIESELS\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"diesel\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_diesels.py","file_name":"_diesels.py","file_ext":"py","file_size_in_byte":238,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"586841479","text":"from copy import deepcopy\nfrom typing import Any, Dict, Optional\n\nimport yaml\nfrom fastapi.applications import FastAPI\nfrom models_library.service_settings_labels import ComposeSpecLabel, PathMappingsLabel\nfrom pydantic import PositiveInt\n\nfrom ...core.settings import DynamicSidecarSettings\nfrom .docker_service_specs import MATCH_SERVICE_VERSION, MATCH_SIMCORE_REGISTRY\n\nCONTAINER_NAME = \"container\"\nBASE_SERVICE_SPEC: Dict[str, Any] = {\n \"version\": \"3.8\",\n \"services\": {CONTAINER_NAME: {}},\n}\n\n\ndef _inject_traefik_configuration(\n service_spec: Dict[str, Any],\n target_container: str,\n dynamic_sidecar_network_name: str,\n simcore_traefik_zone: str,\n service_port: PositiveInt,\n) -> None:\n \"\"\"Injects configuration to allow the service to be accessible on the uuid.services.SERVICE_DNS\"\"\"\n\n # add external network to existing networks defined in the container\n service_spec[\"networks\"] = {\n dynamic_sidecar_network_name: {\n \"external\": {\"name\": dynamic_sidecar_network_name},\n \"driver\": \"overlay\",\n }\n }\n\n # Inject Traefik rules on target container\n target_container_spec = service_spec[\"services\"][target_container]\n\n # attach overlay network to container\n container_networks = target_container_spec.get(\"networks\", [])\n container_networks.append(dynamic_sidecar_network_name)\n target_container_spec[\"networks\"] = container_networks\n\n # expose spawned container to the internet\n labels = target_container_spec.get(\"labels\", [])\n labels.extend(\n [\n f\"io.simcore.zone={simcore_traefik_zone}\",\n \"traefik.enable=true\",\n f\"traefik.http.services.{target_container}.loadbalancer.server.port={service_port}\",\n f\"traefik.http.routers.{target_container}.entrypoints=http\",\n f\"traefik.http.routers.{target_container}.rule=PathPrefix(`/`)\",\n ]\n )\n\n # put back updated labels\n target_container_spec[\"labels\"] = labels\n\n\ndef _assemble_from_service_key_and_tag(\n resolved_registry_url: str,\n service_key: str,\n service_tag: str,\n):\n service_spec = deepcopy(BASE_SERVICE_SPEC)\n service_spec[\"services\"][CONTAINER_NAME] = {\n \"image\": f\"{resolved_registry_url}/{service_key}:{service_tag}\"\n }\n\n return service_spec\n\n\ndef _replace_env_vars_in_compose_spec(\n stringified_service_spec: str, resolved_registry_url: str, service_tag: str\n) -> str:\n stringified_service_spec = stringified_service_spec.replace(\n MATCH_SIMCORE_REGISTRY, resolved_registry_url\n )\n stringified_service_spec = stringified_service_spec.replace(\n MATCH_SERVICE_VERSION, service_tag\n )\n return stringified_service_spec\n\n\nasync def assemble_spec(\n # pylint: disable=too-many-arguments\n app: FastAPI,\n service_key: str,\n service_tag: str,\n paths_mapping: PathMappingsLabel, # pylint: disable=unused-argument\n compose_spec: ComposeSpecLabel,\n container_http_entry: Optional[str],\n dynamic_sidecar_network_name: str,\n simcore_traefik_zone: str,\n service_port: PositiveInt,\n) -> str:\n \"\"\"\n returns a docker-compose spec used by\n the dynamic-sidecar to start the service\n \"\"\"\n settings: DynamicSidecarSettings = (\n app.state.settings.DYNAMIC_SERVICES.DYNAMIC_SIDECAR\n )\n\n container_name = container_http_entry\n service_spec = compose_spec\n\n # when no compose yaml file was provided\n if service_spec is None:\n service_spec = _assemble_from_service_key_and_tag(\n resolved_registry_url=settings.REGISTRY.resolved_registry_url,\n service_key=service_key,\n service_tag=service_tag,\n )\n container_name = CONTAINER_NAME\n else:\n # TODO: need to be sorted out:\n # - inject paths mapping\n # - remove above # pylint: disable=unused-argument\n pass\n\n assert container_name is not None # nosec\n\n _inject_traefik_configuration(\n service_spec,\n target_container=container_name,\n dynamic_sidecar_network_name=dynamic_sidecar_network_name,\n simcore_traefik_zone=simcore_traefik_zone,\n service_port=service_port,\n )\n\n stringified_service_spec = yaml.safe_dump(service_spec)\n stringified_service_spec = _replace_env_vars_in_compose_spec(\n stringified_service_spec=stringified_service_spec,\n resolved_registry_url=settings.REGISTRY.resolved_registry_url,\n service_tag=service_tag,\n )\n\n return stringified_service_spec\n","sub_path":"services/director-v2/src/simcore_service_director_v2/modules/dynamic_sidecar/docker_compose_specs.py","file_name":"docker_compose_specs.py","file_ext":"py","file_size_in_byte":4510,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"494918778","text":"from AlgoExpert import flattenbinarytree as program\nimport unittest\n\n\nclass TestProgram(unittest.TestCase):\n def test_case_1(self):\n root = BinaryTree(1).insert([2, 3, 4, 5, 6])\n root.left.right.left = BinaryTree(7)\n root.left.right.right = BinaryTree(8)\n leftMostNode = program.flattenBinaryTree(root)\n leftToRightToLeft = leftMostNode.leftToRightToLeft()\n expected = [4, 2, 7, 5, 8, 1, 6, 3, 3, 6, 1, 8, 5, 7, 2, 4]\n self.assertEqual(leftToRightToLeft, expected)\n\n\nclass BinaryTree(program.BinaryTree):\n def insert(self, values, i=0):\n if i >= len(values):\n return\n queue = [self]\n while len(queue) > 0:\n current = queue.pop(0)\n if current.left is None:\n current.left = BinaryTree(values[i])\n break\n queue.append(current.left)\n if current.right is None:\n current.right = BinaryTree(values[i])\n break\n queue.append(current.right)\n self.insert(values, i + 1)\n return self\n\n def leftToRightToLeft(self):\n nodes = []\n current = self\n while current.right is not None:\n nodes.append(current.value)\n current = current.right\n nodes.append(current.value)\n while current is not None:\n nodes.append(current.value)\n current = current.left\n return nodes\n","sub_path":"testing/testFlattenBinaryTree.py","file_name":"testFlattenBinaryTree.py","file_ext":"py","file_size_in_byte":1448,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"199609500","text":"import requests\nimport csv\nfrom bs4 import BeautifulSoup\nimport main\n\nstats = []\n# LISTS FOR PROGRAM\nplayers = []\ntotalmax = []\nmaxnumber = []\nmaxTeam = []\n\npOfXsWins = []\npOfXsLosses = []\nprobs_win = []\nprobs_lose = []\noutcome = []\nprob_t1_win = []\nprob_t2_win = []\n\n# Attribute lists\nteam1list = []\nteam2list = []\nprobabilities = []\nwinner_is = []\npoints = []\nless_likely_to_lose = []\nteamnames = []\n\ndef teamname():\n teamnames.append(main.teamname1())\n teamnames.append(main.teamname2())\n\ndef createTrainingCSV():\n with open(main.masterlist() +'data.csv', 'w') as c:\n writer = csv.writer(c, delimiter=' ',\n quotechar=',', quoting=csv.QUOTE_MINIMAL)\n writer.writerow(main.masterlist())\ndef createCSV(team):\n with open(team +'data.csv', 'w') as csvfile:\n writer = csv.writer(csvfile, delimiter=' ',\n quotechar=',', quoting=csv.QUOTE_MINIMAL)\n writer.writerow(team)\ndef appendCSV(team):\n with open(team +\"data.csv\", \"a\") as f:\n wr = csv.writer(f)\n if team == team1():\n wr.writerow(team1list)\n else:\n wr.writerow(team2list)\n\ndef teamstats(team):\n if team == team1():\n if len(team1list) == 0:\n team1list.append(team1())\n run_attrs()\n if team == team2():\n if len(team2list) == 0:\n team2list.append(team2())\n run_attrs()\n\n\n# NAME OF EACH TEAM\ndef team1():\n return stats[0]\n\ndef team2():\n return stats[6]\n\n# RETURNS WINNING TEAM FOR THAT GAME\ndef winning_team():\n if float(stats[5]) > float(stats[11]):\n return 1\n else:\n return 2\n# LIST OF ATTRIBUTES\n\n# WHO SCORED MORE POINTS IN THE FIRST QUARTER\ndef attr1():\n\n # Grabs first quarter points\n if float(stats[1]) > float(stats[7]):\n team1list.append(1)\n team2list.append(0)\n elif float(stats[1]) == float(stats[7]):\n team1list.append(0.5)\n team2list.append(0.5)\n else:\n team1list.append(0)\n team2list.append(1)\n# WHO SCORED MORE POINTS IN THE SECOND QUARTER\ndef attr2():\n # Grabs second quarter points\n if float(stats[2]) > float(stats[8]):\n team1list.append(1)\n team2list.append(0)\n elif float(stats[2]) == float(stats[8]):\n team1list.append(0.5)\n team2list.append(0.5)\n else:\n team1list.append(0)\n team2list.append(1)\n# WHO SCORED MORE POINTS IN THE THIRD QUARTER\ndef attr3():\n # Grabs third quarter points\n if float(stats[3]) > float(stats[9]):\n team1list.append(1)\n team2list.append(0)\n elif float(stats[3]) == float(stats[9]):\n team1list.append(0.5)\n team2list.append(0.5)\n else:\n team1list.append(0)\n team2list.append(1)\n# WHO SCORED MORE POINTS IN THE FOURTH QUARTER\ndef attr4():\n if float(stats[4]) > float(stats[10]):\n team1list.append(1)\n team2list.append(0)\n elif float(stats[4]) == float(stats[10]):\n team1list.append(0.5)\n team2list.append(0.5)\n else:\n team1list.append(0)\n team2list.append(1)\ndef attr5():\n # Grabs first downs\n if float(stats[13]) > float(stats[14]):\n team1list.append(1)\n team2list.append(0)\n elif float(stats[13]) == float(stats[14]):\n team1list.append(0.5)\n team2list.append(0.5)\n else:\n team1list.append(0)\n team2list.append(1)\ndef attr6():\n # Grabs passing first downs\n if float(stats[16]) > float(stats[17]):\n team1list.append(1)\n team2list.append(0)\n elif float(stats[16]) == float(stats[17]):\n team1list.append(0.5)\n team2list.append(0.5)\n else:\n team1list.append(0)\n team2list.append(1)\ndef attr7():\n # Grabs rushing first downs\n if float(stats[19]) > float(stats[20]):\n team1list.append(1)\n team2list.append(0)\n elif float(stats[19]) == float(stats[20]):\n team1list.append(0.5)\n team2list.append(0.5)\n else:\n team1list.append(0)\n team2list.append(1)\ndef attr8():\n # Grabs total yards\n if float(stats[34]) > float(stats[35]):\n team1list.append(1)\n team2list.append(0)\n elif float(stats[34]) == float(stats[35]):\n team1list.append(0.5)\n team2list.append(0.5)\n else:\n team1list.append(0)\n team2list.append(1)\ndef attr9():\n # Grabs yards per play\n if float(stats[40]) > float(stats[41]):\n team1list.append(1)\n team2list.append(0)\n elif float(stats[40]) == float(stats[41]):\n team1list.append(0.5)\n team2list.append(0.5)\n else:\n team1list.append(0)\n team2list.append(1)\ndef attr10():\n # Grabs passing yards\n if float(stats[43]) > float(stats[44]):\n team1list.append(1)\n team2list.append(0)\n elif float(stats[43]) == float(stats[44]):\n team1list.append(0.5)\n team2list.append(0.5)\n else:\n team1list.append(0)\n team2list.append(1)\ndef attr11():\n #grabs yards per pass\n if float(stats[49]) > float(stats[50]):\n team1list.append(1)\n team2list.append(0)\n elif float(stats[49]) == float(stats[50]):\n team1list.append(0.5)\n team2list.append(0.5)\n else:\n team1list.append(0)\n team2list.append(1)\ndef attr12():\n # Grabs rushing yards\n if float(stats[58]) > float(stats[59]):\n team1list.append(1)\n team2list.append(0)\n elif float(stats[58]) == float(stats[59]):\n team1list.append(0.5)\n team2list.append(0.5)\n else:\n team1list.append(0)\n team2list.append(1)\ndef attr13():\n # Grabs yards per rush\n if float(stats[64]) > float(stats[65]):\n team1list.append(1)\n team2list.append(0)\n elif float(stats[64]) == float(stats[65]):\n team1list.append(0.5)\n team2list.append(0.5)\n else:\n team1list.append(0)\n team2list.append(1)\ndef attr14():\n # Grabs turnovers\n if float(stats[73]) > float(stats[74]):\n team1list.append(1)\n team2list.append(0)\n elif float(stats[73]) == float(stats[74]):\n team1list.append(0.5)\n team2list.append(0.5)\n else:\n team1list.append(0)\n team2list.append(1)\ndef attr15():\n # Grabs possession minutes\n x = stats[85].split(\":\")\n y = stats[86].split(\":\")\n if float(x[0]) > float(y[0]):\n team1list.append(1)\n team2list.append(0)\n elif float(x[0]) == float(y[0]):\n team1list.append(0.5)\n team2list.append(0.5)\n else:\n team1list.append(0)\n team2list.append(1)\n\ndef run_attrs():\n # CALLS ALL ATTRIBUTES TO ADD TO THE LIST\n attr1()\n attr2()\n attr3()\n attr4()\n attr5()\n attr6()\n attr7()\n attr8()\n attr9()\n attr10()\n attr11()\n attr12()\n attr13()\n attr14()\n attr15()\n if winning_team() == 1:\n team1list.append(1)\n team2list.append(0)\n else:\n team1list.append(0)\n team2list.append(1)\n\n\n# PROBABILITY OF OUTCOME\ndef prob_of_win():\n return 0.5\ndef prob_of_lose():\n return 0.5\ndef bulk():\n teamname()\n team = main.teamname1()\n #createTrainingCSV()\n #Writes out first line with team name\n #createCSV(team)\n\n list = main.list(team)\n for item in list:\n\n html = requests.get(item).text\n soup = BeautifulSoup(html, 'html5lib')\n # GRAB ALL STAT INFO\n for td_tag in soup.find_all('td'):\n each_stat = td_tag.text\n stats.append(each_stat)\n stat = [x.replace('\\t', '').replace('\\n', '') for x in stats]\n\n teamstats(team)\n appendCSV(team)\n del stats[:]\n del team1list[:]\n del team2list[:]\n #del stat[:]\n\n team2 = main.teamname2()\n\n\n list = main.list(team2)\n for item in list:\n\n html = requests.get(item).text\n soup = BeautifulSoup(html, 'html5lib')\n # GRAB ALL STAT INFO\n for td_tag in soup.find_all('td'):\n each_stat = td_tag.text\n stats.append(each_stat)\n stat = [x.replace('\\t', '').replace('\\n', '') for x in stats]\n #print(stat)\n teamstats(team2)\n appendCSV(team2)\n del stats[:]\n del team1list[:]\n del team2list[:]\n\n#bulk()","sub_path":"grabAttributes.py","file_name":"grabAttributes.py","file_ext":"py","file_size_in_byte":8253,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"119809711","text":"def checkRows(data):\n for row in data:\n if row.count(row[0]) == len(row) and row[0] != '.':\n return row[0]\n return None\n\ndef checkCols(data):\n coldata = []\n for colindex, letter in enumerate(data[0]):\n column = \"\"\n for rowindex, row in enumerate(data):\n column += data[rowindex][colindex]\n coldata.append(column)\n return checkRows(coldata)\n\ndef checkDiags(data):\n diag1 = data[0][0] + data[1][1] + data[2][2]\n diag2 = data[0][2] + data[1][1] + data[2][0]\n return checkRows([diag1, diag2])\n \ndef checkio(game_result):\n winner = (checkRows(game_result) or checkCols(game_result) or\n checkDiags(game_result))\n if winner:\n return winner\n else:\n return 'D'\n\ncheckio([\"XXO\",\"XX.\", \"OOO\"])\n","sub_path":"python/checkio/home/xoreferee.py","file_name":"xoreferee.py","file_ext":"py","file_size_in_byte":800,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"195404912","text":"import math\nimport itertools\nimport statistics\n\ndef readinput():\n inputs=[]\n f=open('input.txt','r')\n for line in f:\n #inputs=line.rstrip().split(' ')\n inputs.append(line.rstrip())\n f.close()\n return inputs\n \ndef nCr(n,r):\n f=math.factorial()\n return f(n)/(f(r)/f(n-r))\n \n#readprimes\nfile=open('primes.json','r')\nprimes=file.read()\nprimes=eval(primes)\nfile.close()\n\na=2\ncoins=[]\nfactors=[]\nlenc=len(coins)\nlenp=len(primes)\nwhile lenc<500:\n sa='1'+\"{0:030b}\".format(a)+'1'\n #print(sa)\n fs=[]\n for i in range(2,11):\n num=int(sa,i) #num in base i\n #print(num)\n #check if prime, has factors\n if(num in primes):\n break\n else:\n factor=-1\n to_check_up_to=math.ceil(math.sqrt(num))+1\n for j in range(lenp): #find factors\n if num%primes[j]==0:\n factor=primes[j]\n break\n elif j==to_check_up_to:\n #if num not in primes:\n #primes.append(num)\n break\n if factor!=-1:\n fs.append(factor)\n else:\n break\n if len(fs)==9:\n factors.append(fs)\n coins.append(sa)\n lenc+=1\n a+=1\n\nf=open('output.txt','w')\nf.write(\"Case #1:\")\nf.write('\\n')\nlenc=len(coins)\nfor i in range(lenc):\n f.write(str(coins[i])+' ')\n v=list(map(str,factors[i]))\n f.write(' '.join(v))\n f.write('\\n')\n \n \n\nf.close()\n\n\"\"\"\ninputs=readinput()\ncases=int(inputs[0])\ninputs=inputs[1:]\n\nf=open('output.txt','w')\nfor i in range(0,len(inputs)):\n #ints=inputs[i].split(' ')\n #ints=list(map(int,ints))\n solved=solve(inputs[i])\n #solved=list(map(str,solved))\n f.write(\"Case #{}: \".format(str(i+1))+str(solved))\n f.write('\\n')\n\nf.close()\n\"\"\"","sub_path":"codes/CodeJamCrawler/16_0_3/genericity/coinjam2016.py","file_name":"coinjam2016.py","file_ext":"py","file_size_in_byte":1850,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"319531882","text":"def user_name():\n name = input('What\\'s your in game nick? (max 8 characters)')\n if len(name) > 8:\n print('Maximum 8 characters')\n user_name()\n else:\n return name\n\n\ndef user_life(life=15, operation=0):\n life_list = ['LIFE:', life]\n life_list[1] = life_list[1] + (operation)\n return life_list\n\n\ndef stats():\n print('GOD OF LUCK gave you your stats:')\n st = inside_stats_generate()\n for i in range(len(st)):\n print('{} {}' .format(st[i][0], st[i][1]))\n st = inside_stats_ask(st)\n return st\n\n\ndef inside_stats_generate():\n st = [['STRENGHT', 10 + random.randint(0, 10)],\n ['AGILITY:', 10 + random.randint(0, 10)],\n ['DEXTERITY:', 10 + random.randint(0, 10)],\n ['WILLPOWER', 10 + random.randint(0, 10)],\n ['CHARISMA', 10 + random.randint(0, 10)],\n ['WISDOM', 10 + random.randint(0, 10)],\n ['LUCK', 10 + random.randint(0, 10)],\n ['LIFES', 10 + random.randint(0, 10)]]\n return st\n\n\ndef inside_stats_ask(st):\n reroll = input('Reroll? (y/n)')\n reroll = reroll.lower()\n\n if reroll == 'y':\n return stats()\n\n elif reroll == 'n':\n\n if (st[0][1] > 16):\n print('Str is over 16! So you\\'re tought huh...')\n\n if (st[1][1] > 16):\n print('Agi is over 16! Where is my wallet...')\n\n if (st[2][1] > 16):\n print('Dex is over 16! So you\\'re hard to kill, it seems.')\n\n if (st[3][1] > 16):\n print('Willpower is over 16! So you\\'re resistant to psychic \\\n attacks.')\n\n if (st[4][1] > 16):\n print('Charisma is over 16! You\\'ll be alright people like you.')\n\n if (st[5][1] > 16):\n print('Wisdom is over 16! Profesor? smart ass huh.')\n\n if (st[6][1] > 16):\n print('Luck is over 16! Lucky bastard!')\n\n return st\n\n else:\n print('Try again')\n return inside_stats_ask()\n# stats()\n# print(user_life())\n","sub_path":"stat.py","file_name":"stat.py","file_ext":"py","file_size_in_byte":1979,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"22911310","text":"\"\"\"\nAPI helpers for django-rest-framework.\n\"\"\"\n\nfrom rest_framework import serializers\nfrom django.db.models.query import QuerySet\n\n\nclass FieldPermissionSerializerMixin:\n \"\"\"\n ModelSerializer logic for marking fields as ``read_only=True`` when a user is found not to have\n change permissions.\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n super(FieldPermissionSerializerMixin, self).__init__(*args, **kwargs)\n\n request = self.context.get('request')\n user = request.user if hasattr(request, 'user') else None\n model = self.Meta.model\n model_field_names = [f.name for f in model._meta.get_fields()] # this might be too broad\n\n # Methods without instance eg. create\n if self.instance is None:\n obj = model()\n # Methods with multiple instances, eg. list\n elif isinstance(self.instance, QuerySet):\n obj = model()\n # Methods with one instance, eg. retrieve\n else:\n obj = self.instance\n\n for name in model_field_names:\n if name in self.fields:\n if not obj.has_field_perm(user, field=name, operation='view'):\n self.fields.pop(name)\n elif not obj.has_field_perm(user, field=name, operation='change'):\n self.fields[name].read_only = True\n\n\nclass FieldPermissionSerializer(FieldPermissionSerializerMixin, serializers.ModelSerializer):\n pass\n","sub_path":"field_permissions/api/rest_framework.py","file_name":"rest_framework.py","file_ext":"py","file_size_in_byte":1445,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"41170696","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport sys\nreload(sys)\nsys.setdefaultencoding('utf-8')\n\n#import sys\nimport dataBase\ndef colocBusc(resultado):\n\n foundColocacion = True\n while foundColocacion:\n foundColocacion = False\n # Buscar colocaciones de 3 en 3\n index = 0\n for agrupacion in zip(resultado, resultado[1:], resultado[2:]):\n (idColocacion, regla) = dataBase.buscarColocacion(agrupacion)\n # Agrupar en una sola palabra\n if idColocacion != -1:\n parte1 = resultado.pop(index)\n parte2 = resultado.pop(index)\n parte3 = resultado.pop(index)\n nuevaPalabra = parte1[3] + \"_\" + parte2[3] + \"_\" + parte3[3]\n nuevoLemma = parte1[0] + \"_\" + parte2[0] + \"_\" + parte3[0]\n # Poner etiqueta de acuerdo a la regla\n colTag = \"\"\n if regla == 1:\n colTag = parte1[1]\n elif regla == 2:\n colTag = parte2[1]\n else:\n colTag = parte3[1]\n nuevaTupla = (nuevoLemma, colTag, idColocacion, nuevaPalabra)\n resultado.insert(index, nuevaTupla)\n # Volver a iterar\n foundColocacion = True\n break\n index = index + 1\n if foundColocacion:\n continue\n # Buscar colocaciones de 2 en 2\n index = 0\n for agrupacion in zip(resultado, resultado[1:]):\n (idColocacion, regla) = dataBase.buscarColocacion(agrupacion)\n # Agrupar en una sola palabra\n if idColocacion != -1:\n parte1 = resultado.pop(index)\n parte2 = resultado.pop(index)\n nuevaPalabra = parte1[3] + \"_\" + parte2[3]\n nuevoLemma = parte1[0] + \"_\" + parte2[0]\n # Poner etiqueta de acuerdo a la regla\n colTag = \"\"\n if regla == 1:\n colTag = parte1[1]\n elif regla == 2:\n colTag = parte2[1]\n nuevaTupla = (nuevoLemma, colTag, idColocacion, nuevaPalabra)\n resultado.insert(index, nuevaTupla)\n # Volver a iterar\n foundColocacion = True\n break\n index = index + 1\n if foundColocacion:\n continue\n\n return resultado\n\n\ndef tokenLemmaColoc(tk, sp, sid, mf, tg, sen, parser, dep, text):\n \"\"\" Separa oraciones, lematiza, etiqueta y busca colocaciones\n Args:\n tk, sp, sid, mf, tg, sen, parser, dep: elementos de Freeling\n text: cadena de texto a analizar\n Returns:\n Una lista de tuplas con el formato (lemma, etiqueta, id_colocacion, palabra_original)\n Si la tupla no es una colocacion, se regresa un -1\n \"\"\"\n resultado = list()\n # Obtencion de oraciones\n text = unicode(text, 'utf-8')\n text = text if text.endswith('.') else (text + '.')\n l = tk.tokenize(text);\n # Lematizar\n ls = sp.split(sid,l,False);\n ls = mf.analyze(ls);\n ls = tg.analyze(ls);\n ls = sen.analyze(ls);\n ls = parser.analyze(ls);\n ls = dep.analyze(ls);\n for s in ls :\n ws = s.get_words();\n for w in ws :\n # for each analysis\n a = w.get_analysis()[0]\n # TODO tambien quitar todos los signos de puntuacion, Tambien de intorrgacion?\n if a.get_lemma() != \".\":\n if a.get_tag()[0] == 'A':\n tag = a.get_tag()[:3]\n elif a.get_tag()[0] == 'R':\n tag = a.get_tag()[:2]\n elif a.get_tag()[0] == 'D':\n tag = a.get_tag()[:3]\n elif a.get_tag()[0] == 'N':\n tag = a.get_tag()[:6]\n elif a.get_tag()[0] == 'V':\n tag = a.get_tag()[:4] \n elif a.get_tag()[0] == 'P':\n tag = a.get_tag()[:3]\n elif a.get_tag()[0] == 'C':\n tag = a.get_tag()[:2]\n elif a.get_tag()[0] == 'I':\n tag = a.get_tag()[:2]\n elif a.get_tag()[0] == 'S':\n tag = a.get_tag()[:3]\n elif a.get_tag()[0] == 'F':\n tag = a.get_tag()[:2]\n elif a.get_tag()[0] == 'Z':\n tag = a.get_tag()[:2]\n # Guardar (lemma, etiqueta, id_colocacion)\n resultado.append( (a.get_lemma(), tag, -1, w.get_form()) )\n # Iterar hasta que no haya colocaciones\n \n return colocBusc(resultado)\n\n \n\n\n \n","sub_path":"modulos/modulo_1/modulo_1.py","file_name":"modulo_1.py","file_ext":"py","file_size_in_byte":3980,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"253179988","text":"# _*_ coding:utf-8 _*_\n\n__author__ = 'bobby'\n__date__ = '2018/7/13 16:48'\nimport json\nimport os\n\nclass OperationJson:\n\n def __init__(self,file_path=None):#构造函数\n if file_path == None: #如果file_path为空,则self.file_path为默认写死的路径\n self.file_path = '../cookiejson/cookiemanager.json'\n else: #如果传递了file_path,则使用传递的file_path\n self.file_path = file_path\n\n self.data = self.read_data() # 获取json文件\n\n #读取json文件\n def read_data(self):\n with open(self.file_path) as fp: #使用with,用完文件后会自动关闭文件,不需要fp.close()来关闭文件\n data = json.load(fp)\n return data\n\n #根据关键字获取数据\n def get_data(self,id):\n print(\"关键字:\",id)\n return self.data[id]\n\n #获取文件里全部数据\n def get_all_data(self):\n return self.data\n\n # 写json\n def write_data(self, data):\n with open(self.file_path, 'w') as fp:\n fp.write(json.dumps(data))\n\n\n\nif __name__ == '__main__':\n # opjson = OperationJson(file_path='../cookiejson/cookieagent.json') #实例化\n opjson = OperationJson() # 实例化\n print(opjson.get_data(0))\n\n\n","sub_path":"TestCaseFunction/util/operation_json.py","file_name":"operation_json.py","file_ext":"py","file_size_in_byte":1271,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"509940954","text":"from enum import Enum\n\nimport flask\nfrom confluent_kafka.error import KafkaError\nfrom flask import current_app\nfrom flask_api import status\nfrom marshmallow import ValidationError\n\nfrom api import api_operation\nfrom api import build_collection_response\nfrom api import flask_json_response\nfrom api import metrics\nfrom api.host_query import build_paginated_host_list_response\nfrom api.host_query import staleness_timestamps\nfrom api.host_query_db import get_all_hosts\nfrom api.host_query_xjoin import get_host_ids_list as get_host_ids_list_xjoin\nfrom api.host_query_xjoin import get_host_list as get_host_list_xjoin\nfrom api.host_query_xjoin import get_host_list_by_id_list\nfrom api.host_query_xjoin import get_host_tags_list_by_id_list\nfrom api.sparse_host_list_system_profile import get_sparse_system_profile\nfrom app import db\nfrom app import inventory_config\nfrom app import Permission\nfrom app.auth import get_current_identity\nfrom app.instrumentation import get_control_rule\nfrom app.instrumentation import log_get_host_list_failed\nfrom app.instrumentation import log_get_host_list_succeeded\nfrom app.instrumentation import log_host_delete_failed\nfrom app.instrumentation import log_host_delete_succeeded\nfrom app.instrumentation import log_patch_host_failed\nfrom app.instrumentation import log_patch_host_success\nfrom app.logging import get_logger\nfrom app.logging import threadctx\nfrom app.models import Host\nfrom app.models import PatchHostSchema\nfrom app.payload_tracker import get_payload_tracker\nfrom app.payload_tracker import PayloadTrackerContext\nfrom app.payload_tracker import PayloadTrackerProcessingContext\nfrom app.queue.events import build_event\nfrom app.queue.events import EventType\nfrom app.queue.events import message_headers\nfrom app.queue.queue import EGRESS_HOST_FIELDS\nfrom app.serialization import deserialize_canonical_facts\nfrom app.serialization import serialize_host\nfrom app.utils import Tag\nfrom lib.host_delete import delete_hosts\nfrom lib.host_repository import find_existing_host\nfrom lib.host_repository import find_non_culled_hosts\nfrom lib.host_repository import update_query_for_owner_id\nfrom lib.middleware import rbac\n\n\nFactOperations = Enum(\"FactOperations\", (\"merge\", \"replace\"))\nTAG_OPERATIONS = (\"apply\", \"remove\")\n\nlogger = get_logger(__name__)\n\n\ndef _get_host_list_by_id_list_from_db(host_id_list):\n current_identity = get_current_identity()\n query = Host.query.filter((Host.org_id == current_identity.org_id) & Host.id.in_(host_id_list))\n return find_non_culled_hosts(update_query_for_owner_id(current_identity, query))\n\n\n@api_operation\n@rbac(Permission.READ)\n@metrics.api_request_time.time()\ndef get_host_list(\n display_name=None,\n fqdn=None,\n hostname_or_id=None,\n insights_id=None,\n provider_id=None,\n provider_type=None,\n tags=None,\n page=1,\n per_page=100,\n order_by=None,\n order_how=None,\n staleness=None,\n registered_with=None,\n filter=None,\n fields=None,\n):\n\n total = 0\n host_list = ()\n\n try:\n host_list, total, additional_fields = get_host_list_xjoin(\n display_name,\n fqdn,\n hostname_or_id,\n insights_id,\n provider_id,\n provider_type,\n tags,\n page,\n per_page,\n order_by,\n order_how,\n staleness,\n registered_with,\n filter,\n fields,\n )\n except ValueError as e:\n log_get_host_list_failed(logger)\n flask.abort(400, str(e))\n\n json_data = build_paginated_host_list_response(total, page, per_page, host_list, additional_fields)\n return flask_json_response(json_data)\n\n\n@api_operation\n@rbac(Permission.WRITE)\n@metrics.api_request_time.time()\ndef delete_hosts_by_filter(\n display_name=None,\n fqdn=None,\n hostname_or_id=None,\n insights_id=None,\n provider_id=None,\n provider_type=None,\n registered_with=None,\n staleness=None,\n tags=None,\n filter=None,\n):\n if not any(\n [\n display_name,\n fqdn,\n hostname_or_id,\n insights_id,\n provider_id,\n provider_type,\n registered_with,\n staleness,\n tags,\n filter,\n ]\n ):\n logger.error(\"bulk-delete operation needs at least one input property to filter on.\")\n flask.abort(400, \"bulk-delete operation needs at least one input property to filter on.\")\n\n try:\n ids_list = get_host_ids_list_xjoin(\n display_name,\n fqdn,\n hostname_or_id,\n insights_id,\n provider_id,\n provider_type,\n registered_with,\n staleness,\n tags,\n filter,\n )\n\n except ValueError as err:\n log_get_host_list_failed(logger)\n flask.abort(400, str(err))\n except ConnectionError:\n logger.error(\"xjoin-search not accessible\")\n flask.abort(503)\n\n try:\n delete_count = _delete_host_list(ids_list) if ids_list else 0\n except KafkaError:\n logger.error(\"Kafka server not available\")\n flask.abort(503)\n\n json_data = {\"hosts_found\": len(ids_list), \"hosts_deleted\": delete_count}\n\n return flask_json_response(json_data, status.HTTP_202_ACCEPTED)\n\n\ndef _delete_host_list(host_id_list):\n current_identity = get_current_identity()\n payload_tracker = get_payload_tracker(\n account=current_identity.account_number, org_id=current_identity.org_id, request_id=threadctx.request_id\n )\n\n with PayloadTrackerContext(\n payload_tracker, received_status_message=\"delete operation\", current_operation=\"delete\"\n ):\n query = _get_host_list_by_id_list_from_db(host_id_list)\n\n deletion_count = 0\n\n for host_id, deleted in delete_hosts(\n query, current_app.event_producer, inventory_config().host_delete_chunk_size\n ):\n if deleted:\n log_host_delete_succeeded(logger, host_id, get_control_rule())\n tracker_message = \"deleted host\"\n deletion_count += 1\n else:\n log_host_delete_failed(logger, host_id, get_control_rule())\n tracker_message = \"not deleted host\"\n\n with PayloadTrackerProcessingContext(\n payload_tracker, processing_status_message=tracker_message\n ) as payload_tracker_processing_ctx:\n payload_tracker_processing_ctx.inventory_id = host_id\n\n return deletion_count\n\n\n@api_operation\n@rbac(Permission.WRITE)\n@metrics.api_request_time.time()\ndef delete_all_hosts(confirm_delete_all=None):\n if not confirm_delete_all:\n logger.error(\"To delete all hosts, provide confirm_delete_all=true in the request.\")\n flask.abort(400, \"To delete all hosts, provide confirm_delete_all=true in the request.\")\n\n try:\n # get all hosts from the DB; bypasses xjoin-search, which limits the number hosts to 10 by default.\n ids_list = get_all_hosts()\n except ValueError as err:\n log_get_host_list_failed(logger)\n flask.abort(400, str(err))\n except ConnectionError:\n logger.error(\"xjoin-search not accessible\")\n flask.abort(503)\n\n try:\n delete_count = _delete_host_list(ids_list)\n except KafkaError:\n logger.error(\"Kafka server not available\")\n flask.abort(503)\n\n json_data = {\"hosts_found\": len(ids_list), \"hosts_deleted\": delete_count}\n\n return flask_json_response(json_data, status.HTTP_202_ACCEPTED)\n\n\n@api_operation\n@rbac(Permission.WRITE)\n@metrics.api_request_time.time()\ndef delete_host_by_id(host_id_list):\n delete_count = _delete_host_list(host_id_list)\n\n if not delete_count:\n flask.abort(status.HTTP_404_NOT_FOUND, \"No hosts found for deletion.\")\n\n return flask.Response(None, status.HTTP_200_OK)\n\n\n@api_operation\n@rbac(Permission.READ)\n@metrics.api_request_time.time()\ndef get_host_by_id(host_id_list, page=1, per_page=100, order_by=None, order_how=None, fields=None):\n try:\n host_list, total, additional_fields = get_host_list_by_id_list(\n host_id_list, page, per_page, order_by, order_how, fields\n )\n except ValueError as e:\n log_get_host_list_failed(logger)\n flask.abort(400, str(e))\n\n log_get_host_list_succeeded(logger, host_list)\n\n json_data = build_paginated_host_list_response(total, page, per_page, host_list, additional_fields)\n return flask_json_response(json_data)\n\n\n@api_operation\n@rbac(Permission.READ)\n@metrics.api_request_time.time()\ndef get_host_system_profile_by_id(host_id_list, page=1, per_page=100, order_by=None, order_how=None, fields=None):\n try:\n total, response_list = get_sparse_system_profile(host_id_list, page, per_page, order_by, order_how, fields)\n except ValueError as e:\n log_get_host_list_failed(logger)\n flask.abort(400, str(e))\n\n json_output = build_collection_response(response_list, page, per_page, total)\n return flask_json_response(json_output)\n\n\ndef _emit_patch_event(serialized_host, host_id, insights_id):\n headers = message_headers(EventType.updated, insights_id)\n event = build_event(EventType.updated, serialized_host)\n current_app.event_producer.write_event(event, str(host_id), headers, wait=True)\n\n\n@api_operation\n@rbac(Permission.WRITE)\n@metrics.api_request_time.time()\ndef patch_host_by_id(host_id_list, body):\n try:\n validated_patch_host_data = PatchHostSchema().load(body)\n except ValidationError as e:\n logger.exception(f\"Input validation error while patching host: {host_id_list} - {body}\")\n return ({\"status\": 400, \"title\": \"Bad Request\", \"detail\": str(e.messages), \"type\": \"unknown\"}, 400)\n\n query = _get_host_list_by_id_list_from_db(host_id_list)\n\n hosts_to_update = query.all()\n\n if not hosts_to_update:\n log_patch_host_failed(logger, host_id_list)\n return flask.abort(status.HTTP_404_NOT_FOUND)\n\n for host in hosts_to_update:\n host.patch(validated_patch_host_data)\n\n if db.session.is_modified(host):\n db.session.commit()\n serialized_host = serialize_host(host, staleness_timestamps(), EGRESS_HOST_FIELDS)\n _emit_patch_event(serialized_host, host.id, host.canonical_facts.get(\"insights_id\"))\n\n log_patch_host_success(logger, host_id_list)\n return 200\n\n\n@api_operation\n@rbac(Permission.WRITE)\n@metrics.api_request_time.time()\ndef replace_facts(host_id_list, namespace, body):\n return update_facts_by_namespace(FactOperations.replace, host_id_list, namespace, body)\n\n\n@api_operation\n@rbac(Permission.WRITE)\n@metrics.api_request_time.time()\ndef merge_facts(host_id_list, namespace, body):\n if not body:\n error_msg = \"ERROR: Invalid request. Merging empty facts into existing facts is a no-op.\"\n logger.debug(error_msg)\n return error_msg, 400\n\n return update_facts_by_namespace(FactOperations.merge, host_id_list, namespace, body)\n\n\ndef update_facts_by_namespace(operation, host_id_list, namespace, fact_dict):\n\n current_identity = get_current_identity()\n query = Host.query.filter(\n (Host.org_id == current_identity.org_id)\n & Host.id.in_(host_id_list)\n & Host.facts.has_key(namespace) # noqa: W601 JSONB query filter, not a dict\n )\n\n hosts_to_update = find_non_culled_hosts(update_query_for_owner_id(current_identity, query)).all()\n\n logger.debug(\"hosts_to_update:%s\", hosts_to_update)\n\n if len(hosts_to_update) != len(host_id_list):\n error_msg = (\n \"ERROR: The number of hosts requested does not match the number of hosts found in the host database. \"\n \"This could happen if the namespace does not exist or the org_id associated with the call does \"\n \"not match the org_id associated with one or more the hosts. Rejecting the fact change request.\"\n )\n logger.debug(error_msg)\n return error_msg, 400\n\n for host in hosts_to_update:\n if operation is FactOperations.replace:\n host.replace_facts_in_namespace(namespace, fact_dict)\n else:\n host.merge_facts_in_namespace(namespace, fact_dict)\n\n if db.session.is_modified(host):\n db.session.commit()\n serialized_host = serialize_host(host, staleness_timestamps(), EGRESS_HOST_FIELDS)\n _emit_patch_event(serialized_host, host.id, host.canonical_facts.get(\"insights_id\"))\n\n logger.debug(\"hosts_to_update:%s\", hosts_to_update)\n\n return 200\n\n\n@api_operation\n@rbac(Permission.READ)\n@metrics.api_request_time.time()\ndef get_host_tag_count(host_id_list, page=1, per_page=100, order_by=None, order_how=None):\n\n host_list, total = get_host_tags_list_by_id_list(host_id_list, page, per_page, order_by, order_how)\n counts = {host_id: len(host_tags) for host_id, host_tags in host_list.items()}\n\n return _build_paginated_host_tags_response(total, page, per_page, counts)\n\n\n@api_operation\n@rbac(Permission.READ)\n@metrics.api_request_time.time()\ndef get_host_tags(host_id_list, page=1, per_page=100, order_by=None, order_how=None, search=None):\n\n host_list, total = get_host_tags_list_by_id_list(host_id_list, page, per_page, order_by, order_how)\n filtered_list = {host_id: Tag.filter_tags(host_tags, search) for host_id, host_tags in host_list.items()}\n\n return _build_paginated_host_tags_response(total, page, per_page, filtered_list)\n\n\ndef _build_paginated_host_tags_response(total, page, per_page, tags_list):\n json_output = build_collection_response(tags_list, page, per_page, total)\n return flask_json_response(json_output)\n\n\n@api_operation\n@rbac(Permission.WRITE)\n@metrics.api_request_time.time()\ndef host_checkin(body):\n\n current_identity = get_current_identity()\n canonical_facts = deserialize_canonical_facts(body)\n existing_host = find_existing_host(current_identity, canonical_facts)\n\n if existing_host:\n existing_host._update_modified_date()\n db.session.commit()\n serialized_host = serialize_host(existing_host, staleness_timestamps(), EGRESS_HOST_FIELDS)\n _emit_patch_event(serialized_host, existing_host.id, existing_host.canonical_facts.get(\"insights_id\"))\n return flask_json_response(serialized_host, 201)\n else:\n flask.abort(404, \"No hosts match the provided canonical facts.\")\n","sub_path":"api/host.py","file_name":"host.py","file_ext":"py","file_size_in_byte":14366,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"627231130","text":"'''\nStrategy:\n Find all matching lines first. It shouldn't be too difficult to match lines in a way that conserves the most amount of matched lines.\n'''\nimport argparse as argparse\nimport os\n\ndef parse_arguments():\n parser = argparse.ArgumentParser(\n description='A diff clone implemented in python.')\n parser.add_argument(\n 'sourcefile',\n type=str,\n help='The first file to compare.')\n parser.add_argument(\n 'otherfile',\n type=str,\n help='The second file to compare.')\n args = parser.parse_args()\n assert os.path.exists(args.sourcefile), 'There is no sourcefile at \\'{args.sourcefile}\\'.'\n assert os.path.exists(args.otherfile), 'There is no otherfile at \\'{args.otherfile}\\'.'\n return args\n\ndef print_diff(c, lines_1, lines_2, i, j):\n if i >= 0 and j >= 0 and lines_1[i] == lines_2[j]:\n print_diff(c, lines_1, lines_2, i - 1, j - 1)\n print('0', lines_1[i], end='')\n elif j >= 0 and (i == -1 or c[i][j - 1] >= c[i - 1][j]):\n print_diff(c, lines_1, lines_2, i, j - 1)\n print('+', lines_2[j], end='')\n elif i >= 0 and (j == -1 or c[i][j - 1] < c[i - 1][j]):\n print_diff(c, lines_1, lines_2, i - 1, j)\n print('-', lines_1[i], end='')\n\nif __name__ == '__main__':\n args = parse_arguments()\n with open(args.sourcefile, 'r') as infile:\n lines_1 = [l for l in infile]\n\n with open(args.otherfile, 'r') as infile:\n lines_2 = [l for l in infile]\n\n n = len(lines_1)\n m = len(lines_2)\n\n # Solve the longest common subsequence problem.\n c = [[0]*m]*n\n for i in range(n):\n for j in range(m):\n if lines_1[i] == lines_2[j]:\n c[i][j] = c[i - 1][j - 1] + 1\n else:\n c[i][j] = max(c[i][j - 1], c[i - 1][j])\n \n print_diff(c, lines_1, lines_2, n - 1, m - 1)\n","sub_path":"assignment5/new_diff.py","file_name":"new_diff.py","file_ext":"py","file_size_in_byte":1891,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"504196023","text":"# Script to run all baseline experiments\nimport os\nimport random\nimport json\nimport numpy as np\nfrom copy import deepcopy\nfrom pprint import pprint\nfrom tqdm import tqdm\nimport torch\nimport torch.nn as nn\nfrom torch.utils.tensorboard import SummaryWriter\nfrom torch.utils.data import DataLoader, TensorDataset\n\nfrom utils import get_experiment_dir, get_enhanced_labels\nfrom data.openmic_utils import get_openmic_loaders\nfrom data.sonyc_utils import get_sonyc_loaders\nfrom evaluate.eval_baseline import eval_baseline, forward\nfrom trainer.trainer_baseline import trainer_baseline\nfrom trainer.train_utils import create_model\nimport evaluate.metrics\n\ndef run(config):\n seed = config['seed']\n random.seed(seed)\n torch.manual_seed(seed)\n torch.cuda.manual_seed(seed)\n np.random.seed(seed)\n\n exp_dir = get_experiment_dir(config)\n \n run_dir = os.path.join(exp_dir, 'seed_{}'.format(config['seed']))\n # tensorboard logger\n writer = SummaryWriter(run_dir)\n \n # get data loaders and metrics function\n if config['dataset'] == 'openmic':\n (train_loader, val_loader, test_loader), (full_dataset, train_inds) = get_openmic_loaders(config)\n n_classes = 20\n metric_fn = evaluate.metrics.metric_fn_openmic\n elif config['dataset'] == 'sonyc':\n (train_loader, val_loader, test_loader), train_dataset = get_sonyc_loaders(config)\n if config['coarse']:\n n_classes = 8\n else:\n n_classes = 23\n metric_fn = evaluate.metrics.metric_fn_sonycust\n\n # Randomly remove labels\n if 'label_drop_rate' in config:\n label_drop_rate = config['label_drop_rate']\n drop_mask = np.random.rand(*train_dataset.Y_mask.shape)\n drop_mask = train_dataset.Y_mask + drop_mask\n train_dataset.Y_mask = drop_mask > (1 + label_drop_rate)\n\n # hyper params\n hparams = config['hparams']\n lr = hparams['lr']\n wd = hparams['wd']\n model_params = {'n_features': hparams['n_features'], \n 'drop_rate':hparams['dropout'], \n 'n_classes':n_classes, \n 'n_layers':hparams['n_layers']}\n num_epochs = hparams['num_epochs']\n prune_thres = hparams['prune_thres']\n batch_size = hparams['batch_size']\n\n # initialize models\n model = create_model(model_params)\n \n # initialize criterion and optimizer\n criterion = nn.BCELoss()\n optimizer = torch.optim.Adam(model.parameters(), lr=lr, weight_decay=wd)\n\n # initialize best metric variables\n best_models = [None, None]\n best_val_loss = 100000.0\n best_f1_macro = -1.0\n\n # teacher training loop\n for epoch in tqdm(range(num_epochs)):\n # drop learning rate every 30 epochs\n if (epoch > 0) and (epoch % 30 == 0):\n for param_group in optimizer.param_groups:\n param_group['lr'] = lr * 0.5\n lr = lr * 0.5\n\n # first train treating all missing labels as negatives\n train_loss = trainer_baseline(model, train_loader, optimizer, criterion, baseline_type=0)\n print('#### Training ####')\n print('Loss: {}'.format(train_loss))\n\n val_loss, metrics = eval_baseline(model, val_loader, criterion, n_classes, metric_fn, baseline_type=1)\n val_metric = 'F1_macro' if config['dataset'] == 'openmic' else 'auprc_macro'\n avg_val_metric = np.mean(metrics[val_metric])\n print('#### Validation ####')\n print('Loss: {}\\t Macro F1 score: {}'.format(val_loss, avg_val_metric))\n\n # log to tensorboard\n writer.add_scalar(\"train/loss\", train_loss, epoch)\n writer.add_scalar(\"val/loss_loss\", val_loss, epoch)\n writer.add_scalar(f\"val/{val_metric}\", avg_val_metric, epoch)\n\n #Save best models\n if val_loss < best_val_loss:\n best_val_loss = val_loss\n best_models[0] = deepcopy(model)\n\n if avg_val_metric > best_f1_macro:\n best_f1_macro = avg_val_metric\n best_models[1] = deepcopy(model)\n\n # Perform label pruning\n if config['dataset'] == 'openmic':\n X = full_dataset.X[train_inds]\n Y_mask = full_dataset.Y_mask[train_inds]\n X_dataset = TensorDataset(torch.tensor(X, requires_grad=False, dtype=torch.float32))\n loader = DataLoader(X_dataset, batch_size)\n all_predictions = forward(best_models[0], loader, n_classes)\n new_mask = get_enhanced_labels(Y_mask, all_predictions, prune_thres)\n full_dataset.Y_mask[train_inds] = new_mask\n\n if config['dataset'] == 'sonyc':\n X = train_dataset.X\n Y_mask = train_dataset.Y_mask\n X_dataset = TensorDataset(torch.tensor(X, requires_grad=False, dtype=torch.float32))\n loader = DataLoader(X_dataset, batch_size)\n all_predictions = forward(best_models[0], loader, n_classes)\n new_mask = get_enhanced_labels(Y_mask, all_predictions, prune_thres)\n train_dataset.Y_mask = new_mask\n # Retrain with pruned labels\n\n # initialize models\n model = create_model(model_params)\n \n # initialize optimizer\n optimizer = torch.optim.Adam(model.parameters(), lr=lr, weight_decay=wd)\n\n # initialize best metric variables\n best_models = [None, None]\n best_val_loss = 100000.0\n best_f1_macro = -1.0\n\n for epoch in tqdm(range(num_epochs)):\n # drop learning rate every 30 epochs\n if (epoch > 0) and (epoch % 30 == 0):\n for param_group in optimizer.param_groups:\n param_group['lr'] = lr * 0.5\n lr = lr * 0.5\n\n # train with new mask\n train_loss = trainer_baseline(model, train_loader, optimizer, criterion, baseline_type=1)\n print('#### Training ####')\n print('Loss: {}'.format(train_loss))\n\n val_loss, metrics = eval_baseline(model, val_loader, criterion, n_classes, metric_fn, baseline_type=1)\n val_metric = 'F1_macro' if config['dataset'] == 'openmic' else 'auprc_macro'\n avg_val_metric = np.mean(metrics[val_metric])\n print('#### Validation ####')\n print('Loss: {}\\t Macro F1 score: {}'.format(val_loss, avg_val_metric))\n\n # log to tensorboard\n writer.add_scalar(\"train/loss\", train_loss, epoch)\n writer.add_scalar(\"val/loss_loss\", val_loss, epoch)\n writer.add_scalar(f\"val/{val_metric}\", avg_val_metric, epoch)\n\n #Save best models\n if val_loss < best_val_loss:\n best_val_loss = val_loss\n best_models[0] = deepcopy(model)\n\n if avg_val_metric > best_f1_macro:\n best_f1_macro = avg_val_metric\n best_models[1] = deepcopy(model)\n\n # Test best models\n for i, model in enumerate(best_models):\n test_loss, metrics = eval_baseline(model, test_loader, criterion, n_classes, metric_fn, baseline_type=1)\n\n print('#### Testing ####')\n print('Test Loss: ', test_loss)\n for key, val in metrics.items():\n print(f'Test {key}: {np.mean(val)}')\n \n # save metrics and model\n torch.save(model.state_dict(), os.path.join(run_dir, f'model_{i}.pth'))\n np.save(os.path.join(run_dir, f'metrics_{i}'), metrics)\n \n # jsonify metrics and write to json as well for manual inspection\n js = {}\n for key, val in metrics.items():\n if not np.ndim(val) == 0:\n js[key] = val.tolist()\n else:\n js[key] = val\n json.dump(js, open(os.path.join(run_dir, f'metrics_{i}.json'), 'w'))\n json.dump(config, open(os.path.join(run_dir, f'config.json'), 'w'))\n \nif __name__ == \"__main__\":\n \n \"\"\"\n For now just initialize config here\n TODO: Load config from json file\n \"\"\"\n seeds = [0, 42, 345, 123, 45]\n prune_thres_list = [0.05, 0.1, 0.25]\n config = {\n 'logdir': '../logs/OpenL3/',\n 'exp_name': 'labelprune',\n 'mode': 0,\n 'coarse': 0,\n 'data_path': '../data',\n 'hparams': {\n 'lr': 0.001,\n 'wd': 1e-5,\n 'n_layers': 1,\n 'n_features': 512,\n 'dropout': 0.6,\n 'num_epochs': 100,\n 'batch_size': 64,\n 'prune_thres': 0.05\n }\n }\n\n \"\"\"\n For OpenMIC\n \"\"\"\n # config['dataset'] = 'openmic'\n # for prune_thres in prune_thres_list:\n # for seed in seeds:\n # config['seed'] = seed\n # config['hparams']['prune_thres'] = prune_thres\n # run(config)\n\n \"\"\"\n For SONYC-UST:\n There are few missing labels in SONYC-UST.\n \"\"\"\n config['dataset'] = 'sonyc'\n for prune_thres in prune_thres_list:\n for seed in seeds:\n config['seed'] = seed\n config['hparams']['prune_thres'] = prune_thres\n run(config)\n","sub_path":"src/run_labelpruning_openL3.py","file_name":"run_labelpruning_openL3.py","file_ext":"py","file_size_in_byte":8761,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"115343039","text":"# USAGE\n# python opencv_object_tracking.py\n# python opencv_object_tracking.py --video dashcam_boston.mp4 --tracker csrt --point x y w h\n\n# import the necessary packages\nfrom imutils.video import VideoStream\nfrom imutils.video import FPS\nimport argparse\nimport imutils\nimport time\nimport cv2\n\n# construct the argument parser and parse the arguments\ndef argParse():\n ap = argparse.ArgumentParser()\n ap.add_argument(\"-v\", \"--video\", type=str, help=\"path to input video file\")\n ap.add_argument(\"-t\", \"--tracker\", type=str, default=\"kcf\", help=\"OpenCV object tracker type\")\n ap.add_argument(\"-p\", \"--point\", nargs='+', type=int, help=\"point\")\n args = vars(ap.parse_args())\n\n return args\n\nclass Tracker:\n\n def __init__(self, args):\n self.args = args\n self.chkInit = None\n self.initBB = None\n\n\n def chkVideo(self):\n if not self.args.get(\"video\", False):\n print(\"[INFO] starting video stream...\")\n vs = VideoStream(src=0).start()\n time.sleep(1.0)\n else:\n vs = cv2.VideoCapture(self.args[\"video\"])\n return vs\n\n def chkPoint(self):\n if \"point\" in self.args:\n self.initBB = self.args[\"point\"]\n\n def selectTracker(self):\n OPENCV_OBJECT_TRACKERS = {\n \"csrt\": cv2.TrackerCSRT_create,\n \"kcf\": cv2.TrackerKCF_create,\n \"boosting\": cv2.TrackerBoosting_create,\n \"mil\": cv2.TrackerMIL_create,\n \"tld\": cv2.TrackerTLD_create,\n \"medianflow\": cv2.TrackerMedianFlow_create,\n \"mosse\": cv2.TrackerMOSSE_create\n }\n\n tracker = OPENCV_OBJECT_TRACKERS[self.args[\"tracker\"]]()\n\n return tracker\n\n def run(self):\n\n fps = None\n min = 0.0\n max = 0.0\n avg = 0.0\n idx = 0\n sum = 0\n\n self.chkPoint()\n vs = self.chkVideo()\n tracker = self.selectTracker()\n\n while True:\n frame = vs.read()\n frame = frame[1] if self.args.get(\"video\", False) else frame\n idx += 1\n\n if frame is None:\n break\n\n frame = imutils.resize(frame, width=500)\n (H, W) = frame.shape[:2]\n\n if self.initBB is not None:\n\n if self.chkInit is None:\n self.initBB=tuple(self.initBB)\n tracker.init(frame, self.initBB)\n self.chkInit = True\n fps = FPS().start()\n else:\n (success, box) = tracker.update(frame)\n\n if success:\n (x, y, w, h) = [int(v) for v in box]\n cv2.rectangle(frame, (x, y), (x + w, y + h),\n (0, 255, 0), 2)\n\n fps.update()\n fps.stop()\n\n temp = fps.fps()\n if temp < min: min = temp\n if temp > max: max = temp\n sum = sum + temp\n avg = sum/idx\n\n\n info = [\n (\"Tracker\", self.args[\"tracker\"]),\n (\"FPS\", \"{:.2f}\".format(fps.fps())),\n (\"MIN\", \"{:.2f}\".format(min)),\n (\"MAX\", \"{:.2f}\".format(max)),\n (\"AVG\", \"{:.2f}\".format(avg)),\n ]\n\n # loop over the info tuples and draw them on our frame\n for (i, (k, v)) in enumerate(info):\n text = \"{}: {}\".format(k, v)\n cv2.putText(frame, text, (10, H - ((i * 20) + 20)),\n cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 0, 255), 2)\n\n # show the output frame\n cv2.imshow(\"Frame\", frame)\n key = cv2.waitKey(1) & 0xFF\n\n # if the 's' key is selected, we are going to \"select\" a bounding\n # box to track\n if key == ord(\"s\"):\n # select the bounding box of the object we want to track (make\n # sure you press ENTER or SPACE after selecting the ROI)\n self.initBB = cv2.selectROI(\"Frame\", frame, fromCenter=False,\n showCrosshair=True)\n\n # start OpenCV object tracker using the supplied bounding box\n # coordinates, then start the FPS throughput estimator as well\n tracker.init(frame, self.initBB)\n fps = FPS().start()\n self.chkInit = True\n\n # if the `q` key was pressed, break from the loop\n elif key == ord(\"q\"):\n break\n\n # if we are using a webcam, release the pointer\n if not self.args.get(\"video\", False):\n vs.stop()\n\n # otherwise, release the file pointer\n else:\n vs.release()\n\n # close all windows\n cv2.destroyAllWindows()\n\n\nif __name__ == \"__main__\":\n args = argParse()\n tracker = Tracker(args)\n tracker.run()","sub_path":"opencv_object_tracking.py","file_name":"opencv_object_tracking.py","file_ext":"py","file_size_in_byte":4994,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"473755462","text":"from datetime import datetime\r\nimport pytesseract\r\nimport cv2\r\nimport os\r\nfrom djitellopy import Tello\r\nimport time\r\n############### For Text_Detection ####################\r\npytesseract.pytesseract.tesseract_cmd = \"C:\\\\Program Files\\\\Tesseract-OCR\\\\tesseract.exe\"\r\n\r\n############################################################\r\n\r\n\r\ndef IntializeTello():\r\n tello = Tello()\r\n tello.for_back_velocity = 0\r\n tello.left_right_velocity = 0\r\n tello.up_down_velocity = 0\r\n tello.yaw_velocity = 0\r\n tello.speed = 10\r\n return tello\r\n\r\n\r\ndef telloGetFrame(tello, w=360, h=240):\r\n frame_read = tello.get_frame_read()\r\n frame = cv2.cvtColor(frame_read.frame, cv2.COLOR_BGR2RGB)\r\n frameRet = frame_read.frame\r\n return frameRet\r\n\r\n\r\ndef Save_Records():\r\n path = 'Resources/detected_text_records/detected_images_text'\r\n images = []\r\n myList = os.listdir(path)\r\n for cl in myList:\r\n curImg = cv2.imread(f'{path}/{cl}')\r\n images.append(curImg)\r\n\r\n with open('Resources/detected_text_records/Records.csv', 'r+') as f:\r\n myDataList = f.readline()\r\n # print(myClassifier.list_labels)\r\n nameList = []\r\n for line in myDataList:\r\n entry = line.split(',')\r\n nameList.append(entry[0])\r\n for images in images:\r\n result = cv2.cvtColor(images, cv2.COLOR_BGR2RGB)\r\n # print(pytesseract.image_to_data(result))\r\n hImg, wImg, _ = result.shape\r\n boxes = pytesseract.image_to_data(result)\r\n # print(boxes)\r\n for x, b in enumerate(boxes.splitlines()):\r\n if x != 0:\r\n b = b.split()\r\n if len(b) == 12:\r\n x, y, w, h = int(b[6]), int(b[7]), int(b[8]), int(b[9])\r\n if b not in nameList:\r\n now = datetime.now()\r\n dtString = now.strftime('%H:%M:%S')\r\n f.writelines(f'\\n{b[11]},{dtString}')\r\n\r\n\r\ndef Text_detection(frameRet):\r\n frame = cv2.cvtColor(frameRet, cv2.COLOR_BGR2RGB)\r\n hImg, wImg, _ = frame.shape\r\n boxes = pytesseract.image_to_data(frame)\r\n for x, b in enumerate(boxes.splitlines()):\r\n if x != 0:\r\n b = b.split()\r\n if len(b) == 12:\r\n x, y, w, h = int(b[6]), int(b[7]), int(b[8]), int(b[9])\r\n cv2.rectangle(frameRet, (x, y), (w + x, h + y), (0, 0, 255), 3)\r\n cv2.putText(frameRet, b[11], (x, y), cv2.FONT_HERSHEY_COMPLEX, 1, (50, 50, 255), 2)\r\n cv2.imwrite(f'Resources/detected_text_records/detected_images_text/{time.time()}.jpg', frameRet)\r\n #Save_Records()","sub_path":"Saving_Record_Module.py","file_name":"Saving_Record_Module.py","file_ext":"py","file_size_in_byte":2708,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"358393258","text":"\"\"\"\n@File: call_test.py\n@Author: Chensy\n@Date: 2019/10/30 0030\n@Desc: \n\"\"\"\n\nimport asyncio\n\n\ndef callback(sleep_time):\n print(\"sleep {} success\".format(sleep_time))\n\n\ndef stop_loop(loop):\n loop.stop()\n\n\nif __name__ == '__main__':\n loop = asyncio.get_event_loop()\n loop.call_soon(callback, 2)\n loop.call_soon(stop_loop, loop)\n loop.run_forever()\n","sub_path":"study/06 - AdvancePython/chapter12/call_test.py","file_name":"call_test.py","file_ext":"py","file_size_in_byte":363,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"148766937","text":"#!/usr/bin/env python3\n\n\ndef count1(line):\n ret = 0\n\n def checkChar(x):\n if x == '\"' or x == '\\\\':\n return 1\n elif x == 'x':\n return 3\n else:\n return 0\n\n for i in range(1, len(line) - 1):\n ret += 1\n if line[i] == '\\\\':\n i += checkChar(line[i + 1])\n\n return ret\n\n\ndef count2(line):\n return sum(\n map(lambda x: int(x == '\"' or x == '\\\\'), line)) + 2 + len(line)\n\n\ndef main():\n lines = [x.strip() for x in open('../input/08').readlines()]\n c1 = 0\n c2 = 0\n total = 0\n\n for line in lines:\n c1 += count1(line)\n c2 += count2(line)\n total += len(line)\n\n print(total - c1)\n print(c2 - total)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"2015/py/08.py","file_name":"08.py","file_ext":"py","file_size_in_byte":766,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"392194430","text":"# coding: utf-8\nfrom __future__ import absolute_import\nimport re\nimport sys\nfrom aoikexcutil import raise_\nfrom aoikdyndocdsl.parser.ast import ArgsNode\nfrom aoikdyndocdsl.parser.ast import FuncNode\nfrom aoikdyndocdsl.parser.ast import KargNode\nfrom aoikdyndocdsl.parser.ast import ListNode\nfrom aoikdyndocdsl.parser.ast import NameNode\nfrom aoikdyndocdsl.parser.ast import PargNode\nfrom aoikdyndocdsl.parser.ast import TupleNode\nfrom aoikdyndocdsl.parser.ast import ValNode\nfrom aoikdyndocdsl.parser.const import NTO_K_CTX\nfrom aoikdyndocdsl.parser.const import NTO_K_PSR\nfrom aoikdyndocdsl.parser.ext import DelayedFunc\n\n\n#/\nclass AttrDict(dict):\n __getattr__ = dict.__getitem__\n __setattr__ = dict.__setitem__\n\n#/\nclass ScanError(Exception):\n\n def __init__(self, ctx, txt, row, col, rep=None, eis=None, eisp=None):\n #/\n self.ctx = ctx\n\n #/\n newline_idx = txt.find('\\n')\n if newline_idx >= 0:\n self.txt = txt[:newline_idx]\n else:\n self.txt = txt\n\n #/\n self.row = row\n\n self.col = col\n\n #/\n self.rep = rep\n\n #/ scan exc infos of current branching\n self.eis = eis\n\n #/ scan exc infos of previous branching\n self.eisp = eisp\n\nEr = ScanError\n\n#/\nclass ScanOk(Exception):\n pass\n\nOk = ScanOk\n\n#/\nclass Parser(object):\n\n #/\n _RULE_FUNC_PRF = ''\n _RULE_FUNC_POF = ''\n\n #/ |SK| means state dict key\n _SK_TXT = 'txt'\n _SK_ROW = 'row'\n _SK_COL = 'col'\n _SK_OCC = 'occ'\n\n #/ |DK| means debug dict key\n _DK_NAME = 'name'\n _DK_TXT = 'txt'\n _DK_ROW = 'row'\n _DK_COL = 'col'\n _DK_SLV = 'slv'\n _DK_SSS = 'sss' # scan is success\n\n #/\n def __init__(self, txt, nto, debug=False):\n #/\n self._txt = txt\n\n self._row = 0\n\n self._col = 0\n\n #/\n self._debug = debug\n\n #/\n self._debug_info_s = None\n\n if self._debug:\n self._debug_info_s = []\n\n #/\n self._ws_rep = None\n\n self._ws_reo = re.compile(self._ws_rep)\\\n if self._ws_rep is not None else None\n\n #/ current rule func's context dict\n self._ctx = None\n\n #/ result context dict returned from last call of \"_scan\".\n self._rctx = None\n\n #/\n self._ctx_k_par = 'par'\n\n #/\n self._ctx_k_row_beg = 'row_beg'\n\n self._ctx_k_col_beg = 'col_beg'\n\n self._ctx_k_row_end = 'row_end'\n\n self._ctx_k_col_end = 'col_end'\n\n #/ scan level\n self._scan_lv = -1\n\n #/ scan exc info\n self._scan_ei = None\n\n #/ scan exc infos of current branching\n self._scan_ei_s = []\n\n #/ scan exc infos of previous branching\n self._scan_ei_sp = []\n\n #/ map rep to reo\n self._reo_d = {}\n\n #/\n self._state_stack = []\n\n #/\n self._nto_custom = nto\n\n self._nto_bound = self._nto\n\n #/\n self._hdlr_ctx = None\n\n self._hdlr_nto_bound = self._hdlr_nto\n\n #/\n self._hdlr_d = {}\n\n #/\n self._ctx_s = []\n\n #/\n self._tmp_d = AttrDict()\n\n def _rule_func_get(self, name):\n #/\n rule_func_name = self._RULE_FUNC_PRF + name + self._RULE_FUNC_POF\n\n #/\n rule_func = getattr(self, rule_func_name)\n\n #/\n return rule_func\n\n def _rule_reo_get(self, name):\n #/\n reo_name = self._RULE_REO_PRF \\\n + name \\\n + self._RULE_REO_POF\n\n #/\n reo = getattr(self, reo_name)\n\n #/\n return reo\n\n def _match(self, reo, txt):\n #/\n m = reo.match(txt)\n\n #/\n if m:\n mlen = len(m.group())\n\n if mlen > 0:\n m_txt = txt[:mlen]\n\n self._state_upd(m_txt)\n\n txt = txt[mlen:]\n\n #/\n return m, txt\n\n def _scan(self, name):\n #/\n ctx_par = self._ctx\n\n #/\n self._scan_lv += 1\n\n #/\n if self._ws_reo:\n _, self._txt = self._match(self._ws_reo, self._txt)\n\n #/\n ctx_new = AttrDict()\n\n #/\n ctx_new.name = name\n\n #/\n if self._ctx_k_par:\n ctx_new[self._ctx_k_par] = ctx_par\n\n #/\n if self._ctx_k_row_beg:\n ctx_new[self._ctx_k_row_beg] = self._row\n\n if self._ctx_k_col_beg:\n ctx_new[self._ctx_k_col_beg] = self._col\n\n #/\n self._ctx = ctx_new\n\n #/\n rule_func = self._rule_func_get(name)\n\n #/ scan success\n self._ss = False\n\n #/ scan exc info\n self._scan_ei = None\n\n #/\n self._rctx = None\n\n #/\n if self._debug:\n #/\n debug_info = AttrDict()\n debug_info[self._DK_NAME] = name\n debug_info[self._DK_TXT] = self._txt\n debug_info[self._DK_ROW] = self._row\n debug_info[self._DK_COL] = self._col\n debug_info[self._DK_SLV] = self._scan_lv\n debug_info[self._DK_SSS] = False\n\n #/\n self._debug_info_s.append(debug_info)\n\n #/\n try:\n rule_func(ctx_new)\n except ScanError:\n #/\n ei = sys.exc_info()\n\n #/\n if self._scan_ei is None or self._scan_ei[1] is not ei[1]:\n self._scan_ei = ei\n\n self._scan_ei_s.append(ei)\n\n #/\n raise\n else:\n #/\n if self._debug:\n debug_info[self._DK_SSS] = True\n finally:\n self._scan_lv -= 1\n\n self._ctx = ctx_par\n\n #/\n self._ss = True\n\n #/\n if self._ctx_k_row_end:\n ctx_new[self._ctx_k_row_end] = self._row\n\n if self._ctx_k_col_end:\n ctx_new[self._ctx_k_col_end] = self._col\n\n #/\n if self._ws_reo:\n _, self._txt = self._match(self._ws_reo, self._txt)\n\n #/\n self._rctx = ctx_new\n\n #/\n return ctx_new\n\n def _scan_reo(self, reo, new_ctx=False):\n #/\n self._rctx = None\n\n #/\n if new_ctx:\n #/\n if self._ctx_k_row_beg:\n row_beg = self._row\n\n if self._ctx_k_col_beg:\n col_beg = self._col\n\n #/\n m, self._txt = self._match(reo, self._txt)\n\n #/\n if m is None:\n self._error(rep=reo.pattern)\n\n #/\n if new_ctx:\n #/\n ctx = AttrDict()\n\n #/\n ctx.name = ''\n\n #/\n if self._ctx_k_par:\n ctx[self._ctx_k_par] = self._ctx\n\n #/\n if self._ctx_k_row_beg:\n ctx[self._ctx_k_row_beg] = row_beg\n\n if self._ctx_k_col_beg:\n ctx[self._ctx_k_col_beg] = col_beg\n\n if self._ctx_k_row_end:\n ctx[self._ctx_k_row_end] = self._row\n\n if self._ctx_k_col_end:\n ctx[self._ctx_k_col_end] = self._col\n #/\n else:\n ctx = self._ctx\n\n #/\n ctx.rem = m\n\n #/\n self._rctx = ctx\n\n #/\n return ctx\n\n def _scan_rep(self, rep):\n #/\n reo = self._reo_d.get(rep, None)\n\n if reo is None:\n reo = self._reo_d[rep] = re.compile(rep)\n\n #/\n return self._scan_reo(reo, new_ctx=True)\n\n def _state_push(self):\n self._state_stack.append({\n self._SK_TXT: self._txt,\n self._SK_ROW: self._row,\n self._SK_COL: self._col,\n self._SK_OCC: 0,\n })\n\n def _state_pop(self):\n res = self._state_stack.pop()\n self._txt = res[self._SK_TXT]\n self._row = res[self._SK_ROW]\n self._col = res[self._SK_COL]\n return res\n\n def _state_save(self):\n self._state_stack[-1][self._SK_TXT] = self._txt\n self._state_stack[-1][self._SK_ROW] = self._row\n self._state_stack[-1][self._SK_COL] = self._col\n self._state_stack[-1][self._SK_OCC] += 1\n\n def _state_upd(self, m_txt):\n row_cnt = m_txt.count('\\n')\n\n if row_cnt == 0:\n last_row_txt = m_txt\n\n self._col += len(last_row_txt)\n else:\n last_row_txt = m_txt[m_txt.rfind('\\n')+1:]\n\n self._row += row_cnt\n\n self._col = len(last_row_txt)\n\n def _or(self, succ=None):\n if succ is None:\n self._or_beg()\n else:\n self._or_end(succ)\n\n def _or_beg(self):\n #/\n self._scan_ei_sp = self._scan_ei_s\n\n self._scan_ei_s = []\n\n def _or_end(self, succ):\n if not succ:\n self._error()\n\n def _ori(self, succ=None):\n if succ is None:\n self._ori_beg()\n else:\n self._ori_end(succ)\n\n def _ori_beg(self):\n #/\n self._state_push()\n\n def _ori_end(self, succ):\n #/\n if succ:\n #/\n self._state_save()\n\n #/\n self._state_pop()\n\n #/\n if succ:\n raise ScanOk()\n\n def _o01(self, succ=None):\n if succ is None:\n self._o01_beg()\n else:\n self._o01_end(succ)\n\n def _o01_beg(self):\n #/\n self._scan_ei_sp = self._scan_ei_s\n\n self._scan_ei_s = []\n\n #/\n self._state_push()\n\n def _o01_end(self, succ):\n #/\n if succ:\n #/\n self._state_save()\n\n #/\n self._state_pop()\n\n #/\n self._ss = True\n\n def _o0m(self, succ=None):\n if succ is None:\n self._o0m_beg()\n elif succ:\n self._state_save()\n else:\n self._o0m_end()\n\n def _o0m_beg(self):\n #/\n self._scan_ei_sp = self._scan_ei_s\n\n self._scan_ei_s = []\n\n #/\n self._state_push()\n\n def _o0m_end(self):\n #/\n self._state_pop()\n\n #/\n self._ss = True\n\n def _o1m(self, succ=None):\n if succ is None:\n self._o1m_beg()\n elif succ:\n self._state_save()\n else:\n self._o1m_end()\n\n def _o1m_beg(self):\n #/\n self._scan_ei_sp = self._scan_ei_s\n\n self._scan_ei_s = []\n\n #/\n self._state_push()\n\n def _o1m_end(self):\n #/\n res = self._state_pop()\n\n #/\n self._ss = res[self._SK_OCC] > 0\n\n #/\n if not self._ss:\n self._error()\n\n def _error(self, rep=None):\n raise ScanError(\n ctx=self._ctx,\n txt=self._txt,\n row=self._row,\n col=self._col,\n rep=rep,\n eis=self._scan_ei_s,\n eisp=self._scan_ei_sp,\n )\n\n\n def _ctx_add(self, ctx):\n #/ store a terminal rule's matched text to \"res\" key\n ## if \"res\" key is not set yet\n if 'res' not in ctx:\n #/\n rem = ctx.get('rem', None)\n\n if rem is not None:\n ctx.res = rem.group()\n\n #/\n self._ctx_s.append(ctx)\n\n #/\n self._hdlrs_run(ctx.name, ctx)\n\n def _nto(self, name):\n #/\n if self._nto_custom is not None:\n try:\n return self._nto_custom(name)\n except KeyError:\n pass\n\n #/\n if name == NTO_K_PSR:\n return self\n\n #/\n if name == NTO_K_CTX:\n return self._ctx\n\n #/\n raise KeyError(name)\n\n def _hdlr_nto(self, name):\n #/\n if self._nto_custom is not None:\n try:\n return self._nto_custom(name)\n except KeyError:\n pass\n\n #/\n if name == NTO_K_PSR:\n return self\n\n #/\n if name == NTO_K_CTX:\n #/ 3gO8pLS\n ## set at 2jNmlmK\n return self._hdlr_ctx\n\n #/\n raise KeyError(name)\n\n def _hdlr_add(self, rule, hdlr):\n #/\n hdlr_s = self._hdlr_d.setdefault(rule, [])\n\n hdlr_s.append(hdlr)\n\n def _hdlrs_run(self, rule, ctx):\n #/ 2jNmlmK\n ## used at 3gO8pLS\n self._hdlr_ctx = ctx\n\n #/\n hdlr_s = self._hdlr_d.get(rule, None)\n\n #/\n if hdlr_s:\n for hdlr in hdlr_s:\n if isinstance(hdlr, (FuncNode, DelayedFunc)):\n hdlr.eval(nto=self._hdlr_nto_bound)\n else:\n hdlr(self, ctx)\n\n def _tmp_get(self, tmp_id):\n #/\n tmp = self._tmp_d.get(tmp_id, None)\n\n if tmp is None:\n tmp = self._tmp_d[tmp_id] = AttrDict()\n\n return tmp\n\n def all(self, _ctx):\n #/\n self._o0m()\n try:\n while 1:\n #/\n self._or()\n try:\n #/\n self._ori()\n try:\n ext = self._scan('ext')\n except Er: self._ori(0)\n else: self._ori(1)\n #/\n self._ori()\n try:\n newline = self._scan('newline')\n except Er: self._ori(0)\n else: self._ori(1)\n #/\n self._ori()\n try:\n heading = self._scan('heading')\n except Er: self._ori(0)\n else: self._ori(1)\n #/\n self._ori()\n try:\n fences = self._scan('fences')\n except Er: self._ori(0)\n else: self._ori(1)\n #/\n self._ori()\n try:\n lines = self._scan('lines')\n except Er: self._ori(0)\n else: self._ori(1)\n #/\n self._ori()\n try:\n line = self._scan('line')\n except Er: self._ori(0)\n else: self._ori(1)\n except Ok: self._or(1)\n else: self._or(0)\n #```\n self._ctx_add(self._rctx)\n #```\n self._o0m(1)\n except Er: self._o0m(0)\n end = self._scan('end')\n\n end_REO = re.compile(r'$')\n def end(self, _ctx):\n end = self._scan_reo(self.end_REO)\n\n newline_REO = re.compile(r'\\n+')\n def newline(self, _ctx):\n newline = self._scan_reo(self.newline_REO)\n\n heading_REO = re.compile(r'[ ]*(#{1,6})[ ]*([^\\n]+?)[ ]*#*[ ]*\\n')\n def heading(self, _ctx):\n heading = self._scan_reo(self.heading_REO)\n\n fences_REO = re.compile(r'[ ]*(?P`{3,}|~{3,})(?P[\\s\\S]+?)(?P=fence_delim)')\n def fences(self, _ctx):\n fences = self._scan_reo(self.fences_REO)\n #```\n #/\n _ctx.res = ''\n\n #/\n fence_beg = AttrDict()\n fence_beg.name = 'fence_beg'\n fence_beg.res = _ctx.rem.group('fence_delim')\n self._ctx_s.append(fence_beg)\n\n #/\n fence_text = fences.rem.group('fence_text')\n\n #/\n parser, res, ei = parse(txt=fence_text, nto=self._nto_custom, rule='inline')\n\n if ei is not None:\n raise_(ei[1], tb=ei[2])\n\n #/\n self._ctx_s.extend(parser._ctx_s)\n\n #/\n fence_end = AttrDict()\n fence_end.name = 'fence_end'\n fence_end.res = _ctx.rem.group('fence_delim')\n self._ctx_s.append(fence_end)\n #```\n\n lines_REO = re.compile((\n #/ Match multiple lines.\n ##\n ## \"([^\\n\\[]|\\[(?!:)\" means one character that is neither newline nor '[',\n ## or it is '[' but not followed by ':'. This means each line matches until\n ## \"[:\" is met, which is rule \"ext\"'s syntax.\n ##\n ## \"(?!%s)\" means no line's next line is heading or fences.\n ##\n ## \"\\n?\" is to cover the case when the last line that should be matched is\n ## followed by only one newline and a heading. In such a case, \"\\n?\" will\n ## not match the only newline, otherwise \"(?!%s)\" will not be matched.\n\n r'((?:([^\\n\\[]|\\[(?!:))+\\n?(?!%s))+)\\n*' % '|'.join([\n heading_REO.pattern,\n fences_REO.pattern,\n ])\n ))\n def lines(self, _ctx):\n lines = self._scan_reo(self.lines_REO)\n\n line_REO = re.compile(r'[^\\n]+')\n def line(self, _ctx):\n line = self._scan_reo(self.line_REO)\n\n def inline(self, _ctx):\n #/\n self._o0m()\n try:\n while 1:\n #/\n self._or()\n try:\n #/\n self._ori()\n try:\n ext = self._scan('ext')\n except Er: self._ori(0)\n else: self._ori(1)\n #/\n self._ori()\n try:\n newline = self._scan('newline')\n except Er: self._ori(0)\n else: self._ori(1)\n #/\n self._ori()\n try:\n lines = self._scan('lines')\n except Er: self._ori(0)\n else: self._ori(1)\n #/\n self._ori()\n try:\n line = self._scan('line')\n except Er: self._ori(0)\n else: self._ori(1)\n except Ok: self._or(1)\n else: self._or(0)\n #```\n self._ctx_add(self._rctx)\n #```\n self._o0m(1)\n except Er: self._o0m(0)\n\n ext_beg_REO = re.compile(r'\\[:')\n def ext_beg(self, _ctx):\n ext_beg = self._scan_reo(self.ext_beg_REO)\n\n ext_end_REO = re.compile(r'\\]')\n def ext_end(self, _ctx):\n ext_end = self._scan_reo(self.ext_end_REO)\n\n ext_lit_sign_REO = re.compile(r'`')\n def ext_lit_sign(self, _ctx):\n ext_lit_sign = self._scan_reo(self.ext_lit_sign_REO)\n\n ext_end_newline_REO = re.compile(r'\\\\\\n')\n def ext_end_newline(self, _ctx):\n ext_end_newline = self._scan_reo(self.ext_end_newline_REO)\n\n def ext(self, _ctx):\n ext_beg = self._scan('ext_beg')\n ext_expr = self._scan('ext_expr')\n ext_end = self._scan('ext_end')\n #/\n self._o01()\n try:\n ext_end_newline = self._scan('ext_end_newline')\n except Er: self._o01(0)\n else: self._o01(1)\n #```\n #/\n _ctx.res = None\n\n #/\n expr_node = ext_expr.res\n\n #/\n res = expr_node.eval(nto=self._nto_bound)\n\n #/\n ## Function return value is not used as \"res\" value\n ## because we expect function to set \"res\" key by itself.\n if not isinstance(expr_node, FuncNode):\n _ctx.res = res\n #```\n\n def ext_expr(self, _ctx):\n expr = self._scan('expr')\n #```\n _ctx.res = expr.res\n #```\n\n def ext_rfunc(self, _ctx):\n expr = self._scan('expr')\n #```\n _ctx.res = expr.res\n #```\n\n ws_REO = re.compile(r'\\s*')\n def ws(self, _ctx):\n ws = self._scan_reo(self.ws_REO)\n\n def expr(self, _ctx):\n #/\n self._or()\n try:\n #/\n self._ori()\n try:\n lit_val = self._scan('lit_val')\n #```\n _ctx.res = ValNode(lit_val.res)\n #```\n except Er: self._ori(0)\n else: self._ori(1)\n #/\n self._ori()\n try:\n expr_list = self._scan('expr_list')\n #```\n _ctx.res = expr_list.res\n #```\n except Er: self._ori(0)\n else: self._ori(1)\n #/\n self._ori()\n try:\n expr_group = self._scan('expr_group')\n #```\n _ctx.res = expr_group.res\n #```\n except Er: self._ori(0)\n else: self._ori(1)\n #/\n self._ori()\n try:\n name = self._scan('name')\n #```\n is_func = False\n #```\n #/\n self._o01()\n try:\n args_group = self._scan('args_group')\n #```\n is_func = True\n #```\n except Er: self._o01(0)\n else: self._o01(1)\n #```\n if is_func:\n _ctx.res = FuncNode(name=name.res, args_node=args_group.res)\n else:\n _ctx.res = NameNode(name.res)\n #```\n except Er: self._ori(0)\n else: self._ori(1)\n except Ok: self._or(1)\n else: self._or(0)\n\n def name(self, _ctx):\n ws = self._scan('ws')\n _rep = self._scan_rep(r'[a-zA-Z_][a-zA-Z0-9_]*')\n #```\n _ctx.res = _rep.rem.group()\n #```\n ws = self._scan('ws')\n\n expr_sep_REO = re.compile(r',')\n def expr_sep(self, _ctx):\n expr_sep = self._scan_reo(self.expr_sep_REO)\n\n def expr_list(self, _ctx):\n ws = self._scan('ws')\n _rep = self._scan_rep(r'\\[')\n #/\n self._or()\n try:\n #/\n self._ori()\n try:\n _rep = self._scan_rep(r'\\]')\n #```\n _ctx.res = ValNode(tuple())\n #```\n except Er: self._ori(0)\n else: self._ori(1)\n #/\n self._ori()\n try:\n expr = self._scan('expr')\n #```\n item_s = [expr.res]\n #```\n #/\n self._o0m()\n try:\n while 1:\n expr_sep = self._scan('expr_sep')\n expr = self._scan('expr')\n #```\n item_s.append(expr.res)\n #```\n self._o0m(1)\n except Er: self._o0m(0)\n #```\n _ctx.res = ListNode(item_s)\n #```\n #/\n self._o01()\n try:\n expr_sep = self._scan('expr_sep')\n except Er: self._o01(0)\n else: self._o01(1)\n _rep = self._scan_rep(r'\\]')\n except Er: self._ori(0)\n else: self._ori(1)\n except Ok: self._or(1)\n else: self._or(0)\n ws = self._scan('ws')\n\n def expr_group(self, _ctx):\n ws = self._scan('ws')\n _rep = self._scan_rep(r'[(]')\n #/\n self._or()\n try:\n #/\n self._ori()\n try:\n _rep = self._scan_rep(r'[)]')\n #```\n _ctx.res = ValNode(tuple())\n #```\n except Er: self._ori(0)\n else: self._ori(1)\n #/\n self._ori()\n try:\n expr = self._scan('expr')\n #```\n item_s = [expr.res]\n #```\n #/\n self._o0m()\n try:\n while 1:\n expr_sep = self._scan('expr_sep')\n expr = self._scan('expr')\n #```\n item_s.append(expr.res)\n #```\n self._o0m(1)\n except Er: self._o0m(0)\n #```\n _ctx.res = TupleNode(item_s)\n #```\n #/\n self._o01()\n try:\n expr_sep = self._scan('expr_sep')\n except Er: self._o01(0)\n else: self._o01(1)\n _rep = self._scan_rep(r'[)]')\n except Er: self._ori(0)\n else: self._ori(1)\n except Ok: self._or(1)\n else: self._or(0)\n ws = self._scan('ws')\n\n def args_group(self, _ctx):\n ws = self._scan('ws')\n _rep = self._scan_rep(r'[(]')\n args = self._scan('args')\n #```\n _ctx.res = args.res\n #```\n _rep = self._scan_rep(r'[)]')\n ws = self._scan('ws')\n\n def args(self, _ctx):\n #```\n item_s = []\n #```\n #/\n self._o01()\n try:\n args_o1m = self._scan('args_o1m')\n #```\n item_s = args_o1m.res\n #```\n except Er: self._o01(0)\n else: self._o01(1)\n #```\n _ctx.res = ArgsNode(item_s)\n #```\n\n def args_o1m(self, _ctx):\n #```\n _ctx.res = []\n #```\n arg = self._scan('arg')\n #```\n _ctx.res.append(arg.res)\n #```\n #/\n self._o0m()\n try:\n while 1:\n _rep = self._scan_rep(r',')\n arg = self._scan('arg')\n #```\n _ctx.res.append(arg.res)\n #```\n self._o0m(1)\n except Er: self._o0m(0)\n #/\n self._o01()\n try:\n _rep = self._scan_rep(r',')\n except Er: self._o01(0)\n else: self._o01(1)\n\n def arg(self, _ctx):\n #/\n self._or()\n try:\n #/\n self._ori()\n try:\n karg = self._scan('karg')\n #```\n _ctx.res = karg.res\n #```\n except Er: self._ori(0)\n else: self._ori(1)\n #/\n self._ori()\n try:\n parg = self._scan('parg')\n #```\n _ctx.res = parg.res\n #```\n except Er: self._ori(0)\n else: self._ori(1)\n except Ok: self._or(1)\n else: self._or(0)\n\n def parg(self, _ctx):\n expr = self._scan('expr')\n #```\n _ctx.res = PargNode(expr.res)\n #```\n\n def karg(self, _ctx):\n name = self._scan('name')\n _rep = self._scan_rep(r'=')\n expr = self._scan('expr')\n #```\n _ctx.res = KargNode(key=name.res, val_node=expr.res)\n #```\n\n def lit_val(self, _ctx):\n ws = self._scan('ws')\n #/\n self._or()\n try:\n #/\n self._ori()\n try:\n lit_str = self._scan('lit_str')\n #```\n _ctx.res = lit_str.res\n #```\n except Er: self._ori(0)\n else: self._ori(1)\n #/\n self._ori()\n try:\n lit_num = self._scan('lit_num')\n #```\n _ctx.res = lit_num.res\n #```\n except Er: self._ori(0)\n else: self._ori(1)\n #/\n self._ori()\n try:\n lit_bool = self._scan('lit_bool')\n #```\n _ctx.res = lit_bool.res\n #```\n except Er: self._ori(0)\n else: self._ori(1)\n #/\n self._ori()\n try:\n lit_none = self._scan('lit_none')\n #```\n _ctx.res = lit_none.res\n #```\n except Er: self._ori(0)\n else: self._ori(1)\n except Ok: self._or(1)\n else: self._or(0)\n ws = self._scan('ws')\n\n lit_str_REO = re.compile('r?(\\'\\'\\'|\"\"\"|\\'|\")((?:[^\\\\\\\\]|\\\\\\\\.)*?)(\\\\1)')\n def lit_str(self, _ctx):\n lit_str = self._scan_reo(self.lit_str_REO)\n #```\n _ctx.res = eval(lit_str.rem.group())\n #```\n\n lit_num_REO = re.compile(r\"\"\"\n ([-+])? # sign\n (?=\\d|[.]\\d) # next is an integer part or a fraction part\n (\\d*) # integer part\n ([.]\\d*)? # fraction part\n (e[-+]?\\d+)? # exponent part\n \"\"\", re.VERBOSE | re.IGNORECASE)\n def lit_num(self, _ctx):\n lit_num = self._scan_reo(self.lit_num_REO)\n #```\n _ctx.res = eval(lit_num.rem.group())\n #```\n\n lit_bool_REO = re.compile(r'(True|False)(?![a-zA-Z0-9_])')\n def lit_bool(self, _ctx):\n lit_bool = self._scan_reo(self.lit_bool_REO)\n #```\n _ctx.res = True if (lit_bool.rem.group() == 'True') else False\n #```\n\n lit_none_REO = re.compile(r'None(?![a-zA-Z0-9_])')\n def lit_none(self, _ctx):\n lit_none = self._scan_reo(self.lit_none_REO)\n #```\n _ctx.res = None\n #```\n\n#/\ndef parse(txt, nto, debug=False, rule=None):\n #/\n parser = Parser(\n txt=txt,\n nto=nto,\n debug=debug,\n )\n\n #/\n if rule is None:\n rule = 'all'\n\n #/\n res = None\n\n ei = None\n\n try:\n res = parser._scan(rule)\n except Exception:\n ei = sys.exc_info()\n\n #/\n return parser, res, ei\n","sub_path":"src/aoikdyndocdsl/ext/markdown/parser/parser.py","file_name":"parser.py","file_ext":"py","file_size_in_byte":29033,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"125474219","text":"from flask import Flask, jsonify\nfrom flask_cors import CORS\nfrom flask import request\nimport socket\nfrom gpiozero import LED\nimport time\nfrom datetime import date\n\nhostname = socket.gethostname()\nlocal_ip = socket.gethostbyname(hostname)\n\n# Autodrive is either HIGH or LOW, TRUE or FALSE\n\n\napp = Flask(__name__)\nCORS(app=app)\n\ndef write_log(rawContent, aip = None):\n if aip == None:\n ip = request.remote_addr\n else:\n ip = aip\n with open(\"log.txt\", \"a\") as f:\n content = str(date.today()) + \" \" + time.strftime('%H:%M:%S', time.localtime()) + \" => \" + rawContent + \" [\" + ip + \"] \" + \"\\n\"\n f.write(str(content))\n f.close()\n\ntry:\n autoDrive = LED(17)\nexcept:\n write_log(\"Failed to register pins, likely beacuse the script is not running on a rasperry pi with pins\", aip=\"N/A\")\n pass\n\n@app.route(\"/verify\", methods=[\"GET\"])\ndef verify():\n write_log(\"Verified access\")\n return jsonify({\"ip\": request.remote_addr, \"status\": 200}), 200\n\n\n@app.route(\"/drive/auto/on\", methods=[\"GET\"])\ndef auto_on():\n try:\n autoDrive.on()\n write_log(\"Turned on auto driver\")\n return jsonify({\"status\": 200}), 200\n except:\n write_log(\"Failed to turn on auto driver, could the script not be running on a raspberry pi machine?\")\n return jsonify({\"status\": 500}), 500 \n\n@app.route(\"/drive/auto/off\", methods=[\"GET\"])\ndef auto_off():\n try:\n autoDrive.off()\n write_log(\"Turned off auto driver\")\n return jsonify({\"status\": 200}), 200\n except:\n write_log(\"Failed to turn on auto driver, could the script not be running on a raspberry pi machine?\")\n return jsonify({\"status\": 500}), 500 \n\n@app.route(\"/drive/right\", methods=[\"GET\"])\ndef drive_right():\n try:\n return jsonify({\"status\": 200}), 200\n except:\n return jsonify({\"status\": 500}), 500\n\n\n@app.errorhandler(404)\ndef page_not_found(error):\n write_log(\"Encountered a 404\")\n return jsonify({\"error\": str(error), \"status\": 404}), 404\n\n\nif __name__ == \"__main__\":\n write_log(\"\\n\" + \"\\n\" + \"Started server [V.0.7]. If the ip following is not a 192.168 adress, consider checking ifconfig wlan0\", aip=local_ip)\n app.run(host='0.0.0.0', port=5000, debug=True, threaded=True)\n pass\n","sub_path":"server_raspberry/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2278,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"244849136","text":"\"\"\"\n===========================================\nWHAI: WEIBULL HYBRID AUTOENCODING INFERENCE FOR DEEP TOPIC MODELING\nHao Zhang, Bo Chen, Dandan Guo and Mingyuan Zhou\nPublished as a conference paper at ICLR 2018\n\n===========================================\n\n\"\"\"\n\n# Author: Xinyang Liu \n# License: BSD-3-Clause\n\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.nn.parameter import Parameter\nimport warnings\nimport os\nimport copy\nfrom tqdm import tqdm\nfrom ._basic_model import Basic_Model\nfrom .._sampler import Basic_Sampler\nfrom .._utils import *\nwarnings.filterwarnings(\"ignore\")\n\nclass Conv1D(nn.Module):\n def __init__(self, nf, rf, nx, device):\n '''\n convolutional layer\n Inputs:\n nf: Size of dimension produced by the convolution\n rf: Size of the convolving kernel\n nx: Size of dimension in the input\n\n Attributes:\n w (Tensor): the learnable weights of the module of shape\n b (Tensor): the learnable bias of the module of shape\n '''\n super(Conv1D, self).__init__()\n self.rf = rf\n self.nf = nf\n if rf == 1: # faster 1x1 conv\n w = torch.empty(nx, nf).to(device)\n nn.init.normal_(w, std=0.02)\n self.w = Parameter(w)\n self.b = Parameter(torch.zeros(nf).to(device))\n else: # was used to train LM\n raise NotImplementedError\n\n def forward(self, x):\n '''\n Input:\n x: Input of convolutional layer\n\n Outputs:\n x: The fresh x produced by the convolution\n\n '''\n if self.rf == 1:\n size_out = x.size()[:-1] + (self.nf,)\n x = torch.addmm(self.b, x.view(-1, x.size(-1)), self.w)\n x = x.view(*size_out)\n else:\n raise NotImplementedError\n return x\n\n # def __repr__(self):\n\n\nclass WHAI(Basic_Model, nn.Module):\n def __init__(self, K: list, H:list, V:int, device='gpu'):\n \"\"\"\n The basic model for WHAI\n Inputs:\n K : [list] Number of topics at different layers in WHAI;\n H : [list] Size of dimension at different hidden layers in WHAI;\n V : [int] Length of the vocabulary for convolutional layers in WHAI;\n device : [str] 'cpu' or 'gpu';\n\n Attributes:\n @public:\n global_params : [Params] the global parameters of the probabilistic model\n local_params : [Params] the local parameters of the probabilistic model\n h_encoder : [Modulelist] the convolutional layers for latent representation for WHAI\n shape_encoder : [Modulelist] the convolutional layers for shape-parameters in Weibull distribution\n scale_encoder : [Modulelist] the convolutional layers for scale-parameters in Weibull distribution\n\n @private:\n _model_setting : [Params] the model settings of the probabilistic model\n _hyper_params : [Params] the hyper parameters of the probabilistic model\n _model_setting.T : [int] the network depth\n _real_min : [Tensor] the parameter to prevent overflow\n\n \"\"\"\n super(WHAI, self).__init__()\n setattr(self, '_model_name', 'WHAI')\n\n self._model_setting.K = K\n self._model_setting.H = H\n self._model_setting.V = V\n self._model_setting.T = len(K)\n self.H_dim = [self._model_setting.V] + self._model_setting.H\n self._model_setting.device = 'cpu' if device == 'cpu' else 'gpu'\n self.data_device = device\n self._real_min = torch.tensor(1e-30)\n self.h_encoder = nn.ModuleList([Conv1D(self.H_dim[i + 1], 1, self.H_dim[i], device) for i in range(self._model_setting.T)])\n self.shape_encoder = nn.ModuleList([Conv1D(1, 1, in_dim, device) for in_dim in self._model_setting.H])\n self.scale_encoder = nn.ModuleList([Conv1D(k_dim, 1, h_dim, device) for k_dim, h_dim in zip(self._model_setting.K, self._model_setting.H)])\n\n assert self._model_setting.device in ['cpu',\n 'gpu'], 'Device Type Error: the device should be ''cpu'' or ''gpu'''\n\n self._sampler = Basic_Sampler(self._model_setting.device)\n\n\n def initial(self, voc=None, cls=None, batch_size=100, n_epochs=100, MBratio=100):\n '''\n Initial the parameters of WHAI with the settings about documents\n Inputs:\n voc : [list] V list, vocabulary with length of V\n cls : [int] Classes of documents\n batch_size : [int] The batch_size for updating Phi and preparing dataset\n n_epochs : [int] Number of epochs in training stage\n MBratio : [int] Length of dataloader for updating Phi in training stage\n\n Attributes:\n @public:\n global_params.Phi : [list] T (K_t-1)*(K_t) factor loading matrices at different layers\n train_num : [int] Current counts of updating Phi\n drop_out : Probability of an element to be zeroed in neural network\n Ndot, xt_to_t1, WSZS, EWSZS : Intermediate variables parameters in updating Phi\n\n @private:\n _real_min_phi : [float] scalar, the parameter to prevent overflow in updating Phi\n _ForgetRate, _epsit : Parameters in updating Phi\n\n\n '''\n self._model_setting.n_epochs = n_epochs\n self._model_setting.batch_size = batch_size\n self._model_setting.voc = voc\n self._model_setting.cls = cls\n self._model_setting.MBratio = MBratio\n self._real_min_phi = 1e-30\n\n\n self.NDot = [0] * self._model_setting.T\n self.Xt_to_t1 = [0] * self._model_setting.T\n self.WSZS = [0] * self._model_setting.T\n self.EWSZS = [0] * self._model_setting.T\n\n self.global_params.Phi = self.init_phi()\n\n n_updates = MBratio * self._model_setting.n_epochs\n self._ForgetRate = np.power((0 + np.linspace(1, n_updates, n_updates)), -0.9)\n\n epsit = np.power((20 + np.linspace(1, n_updates,\n n_updates)), -0.7)\n self._epsit = 1 * epsit / epsit[0]\n\n self.train_num = 0\n self.dropout = torch.nn.Dropout(p=0.4)\n\n\n\n def reset_para(self, n_updates, batch_size, MBratio):\n \"\"\"\n Reset private parameters about updating Phi\n inputs:\n n_updates : [int] Total counts for updating Phi\n batch_size : [int] The batch_size for updating Phi\n MBratio : [int] Length of dataloader for updating Phi in training stage\n \"\"\"\n self.train_num = 0\n self._model_setting.batch_size = batch_size\n self._ForgetRate = np.power((0 + np.linspace(1, n_updates, n_updates)), -0.9)\n\n epsit = np.power((20 + np.linspace(1, n_updates,\n n_updates)), -0.7)\n self._epsit = 1 * epsit / epsit[0]\n self._model_setting.MBratio = MBratio\n\n def vision_phi(self, outpath='phi_output', top_n=25, topic_diversity=True):\n '''\n Visualization of Phi and getting diversity on each layers\n inputs:\n outpath : [str] The path of visualization of Phi\n top_n : [int] Number of words to display\n topic_diversity : [bool] Whether to get topic diversity\n\n If topic_diversity is True, this function will print the diversity of each layers.\n '''\n def get_diversity(topics):\n word = []\n for line in topics:\n word += line\n word_unique = np.unique(word)\n return len(word_unique) / len(word)\n\n if not os.path.exists(outpath):\n os.makedirs(outpath)\n phi = 1\n for num, phi_layer in enumerate(self.global_params.Phi):\n phi = np.dot(phi, phi_layer)\n phi_k = phi.shape[1]\n path = os.path.join(outpath, 'phi' + str(num) + '.txt')\n f = open(path, 'w')\n topic_word = []\n for each in range(phi_k):\n top_n_words = self.get_top_n(phi[:, each], top_n)\n topic_word.append(top_n_words.split()[:25])\n f.write(top_n_words)\n f.write('\\n')\n f.close()\n if topic_diversity:\n td_value = get_diversity(topic_word)\n print('topic diversity at layer {}: {}'.format(num, td_value))\n\n def get_top_n(self, phi, top_n):\n '''\n Get top n words of each topic\n Inputs:\n phi : The loading matrix\n top_n : Number of words to get\n\n Outputs:\n Top n words\n '''\n top_n_words = ''\n idx = np.argsort(-phi)\n for i in range(top_n):\n index = idx[i]\n top_n_words += self._model_setting.voc[index]\n top_n_words += ' '\n return top_n_words\n\n def log_max(self, x):\n '''\n return log(x+eps)\n '''\n return torch.log(torch.max(x, self._real_min.to(self.data_device)))\n\n def reparameterize(self, Wei_shape, Wei_scale, num_layer):\n '''\n Reparameterization trick for Weibull distribution\n Inputs:\n Wei_shape : Shape-parameter in Weibull distribution\n Wei_scale : Scale-parameter in Weibull distribution\n num_layer : Index of layer to reparameterize on\n\n Outputs:\n theta : The latent matrix (The variables obey Weibull distribution with reparameterization trick)\n '''\n eps = torch.cuda.FloatTensor(self._model_setting.K[num_layer], self._model_setting.batch_size).uniform_(0.2, 0.8)\n theta = Wei_scale * torch.pow(-self.log_max(1 - eps), 1 / Wei_shape)\n return theta ## v*n\n\n def KL_GamWei(self, Gam_shape, Gam_scale, Wei_shape, Wei_scale):\n '''\n Calculate the KL divergence between Gamma distribution and Weibull distribution\n '''\n eulergamma = torch.tensor(0.5772, dtype=torch.float32)\n part1 = eulergamma.to(self.data_device) * (1 - 1 / Wei_shape) + self.log_max(\n Wei_scale / Wei_shape) + 1 + Gam_shape * torch.log(Gam_scale)\n part2 = -torch.lgamma(Gam_shape) + (Gam_shape - 1) * (self.log_max(Wei_scale) - eulergamma.to(self.data_device) / Wei_shape)\n part3 = - Gam_scale * Wei_scale * torch.exp(torch.lgamma(1 + 1 / Wei_shape))\n KL = part1 + part2 + part3\n return KL\n\n def init_phi(self):\n '''\n Initialize the Phi randomly\n '''\n Phi = []\n for t in range(self._model_setting.T): # 0:T-1\n if t == 0:\n Phi.append(0.2 + 0.8 * np.float32(np.random.rand(self._model_setting.V, self._model_setting.K[t])))\n else:\n Phi.append(0.2 + 0.8 * np.float32(np.random.rand(self._model_setting.K[t - 1], self._model_setting.K[t])))\n Phi[t] = Phi[t] / np.maximum(self._real_min, Phi[t].sum(0)) # maximum every elements\n return Phi\n\n def input_phi(self, theta):\n ## for phi NN update\n ## todo something\n return None\n\n def encoder_left(self, x, num_layer):\n '''\n Encoder for hidden layers\n Inputs:\n x : Input of current layer\n num_layer : Index of layers\n\n Outputs:\n The x produced by the encoder\n '''\n if num_layer == 0:\n x = torch.nn.functional.softplus(self.h_encoder[num_layer](self.log_max(1 + x)))\n else:\n x = torch.nn.functional.softplus(self.h_encoder[num_layer](x))\n return x\n\n def encoder_right(self, x, num_layer, phi, theta):\n '''\n Encoder for parameters of Weibull distribution\n Inputs:\n x : Input of current layer\n num_layer : Index of layers\n\n Outputs:\n k, l : The parameters of Weibull distribution produced by the encoder\n '''\n k_tmp = torch.max(torch.exp(self.shape_encoder[num_layer](x)), self._real_min.to(self.data_device)).view(-1, 1)\n k_tmp = k_tmp.repeat(1, self._model_setting.K[num_layer])\n l = torch.max(torch.exp(self.scale_encoder[num_layer](x)), self._real_min.to(self.data_device))\n if num_layer != self._model_setting.T - 1:\n k = torch.max(k_tmp, self._real_min.to(self.data_device))\n else:\n k = torch.max(k_tmp, self._real_min.to(self.data_device))\n return k.permute(1, 0), l.permute(1, 0)\n\n def ProjSimplexSpecial(self, Phi_tmp, Phi_old, epsilon):\n Phinew = Phi_tmp - (Phi_tmp.sum(0) - 1) * Phi_old\n if np.where(Phinew[:, :] <= 0)[0].size > 0:\n Phinew = np.maximum(epsilon, Phinew)\n Phinew = Phinew / np.maximum(realmin, Phinew.sum(0))\n Phinew = Phinew / np.maximum(realmin, Phinew.sum(0))\n return Phinew\n\n def updatePhi(self, Xt, Theta, MBratio, MBObserved):\n '''\n TLASGR-MCMC for updating Phi\n '''\n Xt = np.array(np.transpose(Xt.cpu().detach().numpy()), order='C').astype('double')\n for t in range(self._model_setting.T):\n self.global_params.Phi[t] = np.array(self.global_params.Phi[t], order='C').astype('float64')\n Theta[t] = np.array(Theta[t].cpu().detach().numpy(), order='C').astype('float64')\n if t == 0:\n self.Xt_to_t1[t], self.WSZS[t] = self._sampler.multi_aug(Xt, self.global_params.Phi[t], Theta[t])\n else:\n self.Xt_to_t1[t], self.WSZS[t] = self._sampler.crt_multi_aug(self.Xt_to_t1[t - 1], self.global_params.Phi[t],\n Theta[t])\n self.EWSZS[t] = MBratio * self.WSZS[t]\n if (MBObserved == 0):\n self.NDot[t] = self.EWSZS[t].sum(0)\n else:\n self.NDot[t] = (1 - self._ForgetRate[MBObserved]) * self.NDot[t] + self._ForgetRate[MBObserved] * \\\n self.EWSZS[t].sum(0)\n tmp = self.EWSZS[t] + 0.1\n tmp = (1 / np.maximum(self.NDot[t], self._real_min_phi)) * (tmp - tmp.sum(0) * self.global_params.Phi[t])\n tmp1 = (2 / np.maximum(self.NDot[t], self._real_min_phi)) * self.global_params.Phi[t]\n\n tmp = self.global_params.Phi[t] + self._epsit[MBObserved] * tmp + np.sqrt(self._epsit[MBObserved] * tmp1) * np.random.randn(\n self.global_params.Phi[t].shape[0], self.global_params.Phi[t].shape[1])\n self.global_params.Phi[t] = self.ProjSimplexSpecial(tmp, self.global_params.Phi[t], 0)\n\n\n def compute_loss(self, x, theta, k, l):\n '''\n Compute loss with KL divergence and likelihood\n '''\n kl_loss = [0] * self._model_setting.T\n kl_weight = [0.05 for i in range(self._model_setting.T)]\n for i in range(self._model_setting.T):\n if i == self._model_setting.T - 1:\n kl_loss[i] = torch.sum(self.KL_GamWei(torch.tensor(1.0, dtype=torch.float32).to(self.data_device),\n torch.tensor(1.0, dtype=torch.float32).to(self.data_device), k[i], l[i]))\n else:\n kl_loss[i] = torch.sum(\n self.KL_GamWei(torch.matmul(torch.tensor(self.global_params.Phi[i + 1], dtype=torch.float32).to(self.data_device),\n theta[i + 1]), torch.tensor(1.0, dtype=torch.float32).to(self.data_device), k[i],\n l[i]))\n kl_part = [weight * kl for weight, kl in zip(kl_weight, kl_loss)]\n likelihood = torch.sum(\n x.permute(1, 0) * self.log_max(torch.matmul(torch.tensor(self.global_params.Phi[0], dtype=torch.float32).to(self.data_device),\n theta[0])) - torch.matmul(\n torch.tensor(self.global_params.Phi[0], dtype=torch.float32).to(self.data_device), theta[0])\n - torch.lgamma(x.permute(1, 0) + 1))\n return -(torch.sum(torch.stack(kl_part)) + likelihood) / self._model_setting.batch_size, likelihood, torch.sum(\n torch.stack(kl_loss)) + likelihood\n\n def forward(self, x, is_train=False):\n '''\n Inputs:\n x : The batch_size * V count data\n is_train : Whether to update Phi\n\n Outputs:\n theta : The batch_size * K latent matrix\n WHAI_loss, LikeliHood, LB : The loss for optimizing and collecting\n '''\n\n if is_train:\n MBObserved = self.train_num\n theta = [0] * self._model_setting.T\n h = []\n for i in range(self._model_setting.T):\n if i == 0:\n h.append(self.encoder_left(x, i))\n else:\n h.append(self.encoder_left(h[-1], i))\n k = [[] for _ in range(self._model_setting.T)]\n l = [[] for _ in range(self._model_setting.T)]\n\n for i in range(self._model_setting.T - 1, -1, -1):\n if i == self._model_setting.T - 1:\n k[i], l[i] = self.encoder_right(h[i], i, 0, 0)\n else:\n k[i], l[i] = self.encoder_right(h[i], i, self.global_params.Phi[i + 1], theta[i + 1])\n\n k[i] = torch.clamp(k[i], 0.1, 10.0)\n l[i] = torch.clamp(l[i], 1e-10)\n if is_train:\n l[i] = l[i] / torch.exp(torch.lgamma(1.0 + 1.0 / k[i]))\n theta[i] = self.reparameterize(k[i], l[i], i)\n else:\n theta[i] = torch.min(l[i], torch.tensor(1000.0))\n\n WHAI_LOSS, LikeliHood, LB = self.compute_loss(x, theta, k, l)\n if is_train:\n self.train_num += 1\n self.updatePhi(x, theta, self._model_setting.MBratio, MBObserved)\n\n return torch.tensor(theta[0], dtype=torch.float).to(self.data_device).permute(1, 0), WHAI_LOSS, LikeliHood, LB\n\n def train_one_epoch(self, model_opt, dataloader, epoch):\n '''\n Train for one epoch\n Inputs:\n model_opt : Optimizer for model\n dataloader : Train data with form of dataloader\n epoch : Current epoch on training stage\n\n Attributes:\n local_params.theta : Concatenation of theta with total data\n local_params.label : Concatenation of label with total data\n '''\n self.train()\n self.local_params.theta = None\n self.local_params.label = None\n loss_t, likelihood_t, lb_t = 0.0, 0.0, 0.0\n\n train_bar = tqdm(iterable=dataloader)\n for i, (train_data, tfidf, train_label) in enumerate(train_bar):\n train_bar.set_description(f'Epoch [{epoch}/{self._model_setting.n_epochs}]')\n train_bar.set_postfix(loss=loss_t/(i+1), likelihood=likelihood_t/(i+1), lb=lb_t/(i+1))\n\n if self.local_params.label is None:\n self.local_params.label = train_label.detach().numpy()\n else:\n self.local_params.label = np.concatenate((self.local_params.label, train_label.detach().numpy()))\n\n train_data = torch.tensor(train_data, dtype=torch.float).to(self.data_device)\n train_label = torch.tensor(train_label, dtype=torch.long).to(self.data_device)\n\n theta, loss, likelihood, lb = self.forward(train_data, True)\n loss.backward()\n model_opt.step()\n model_opt.zero_grad()\n\n loss_t += loss.cpu().detach().numpy()\n likelihood_t += likelihood.cpu().detach().numpy()\n lb_t += lb.cpu().detach().numpy()\n\n if self.local_params.theta is None:\n self.local_params.theta = theta.cpu().detach().numpy()\n else:\n self.local_params.theta = np.concatenate((self.local_params.theta, theta.cpu().detach().numpy()))\n\n return copy.deepcopy(self.local_params)\n\n def test_one_epoch(self, dataloader):\n '''\n Test for one epoch\n Inputs:\n dataloader : Test data with form of dataloader\n\n Outputs:\n local_theta : Concatenation of theta with total data\n local_label : Concatenation of label with total data\n full data : Total data\n '''\n self.eval()\n full_data = None\n local_theta = None\n local_label = None\n loss_t, likelihood_t, lb_t = 0.0, 0.0, 0.0\n\n test_bar = tqdm(iterable=dataloader)\n with torch.no_grad():\n for i, (test_data, tfidf, test_label) in enumerate(test_bar):\n test_bar.set_description(f'Testing stage: ')\n test_bar.set_postfix(loss=loss_t / (i + 1), likelihood=likelihood_t / (i + 1), lb=lb_t / (i + 1))\n\n if local_label is None:\n local_label = test_label.detach().numpy()\n full_data = test_data\n else:\n local_label = np.concatenate((local_label, test_label.detach().numpy()))\n full_data = np.concatenate((full_data, test_data))\n\n test_data = torch.tensor(test_data, dtype=torch.float).to(self.data_device)\n test_label = torch.tensor(test_label, dtype=torch.long).to(self.data_device)\n\n theta, loss, likelihood, lb = self.forward(test_data, is_train=False)\n\n loss_t += loss.cpu().detach().numpy()\n likelihood_t = likelihood.cpu().detach().numpy()\n lb_t = lb.cpu().detach().numpy()\n\n if local_theta is None:\n local_theta = theta.cpu().detach().numpy()\n else:\n local_theta = np.concatenate((local_theta, theta.cpu().detach().numpy()))\n\n return local_theta, local_label, full_data\n\n\n def save_phi(self, phi_path, epoch):\n self.vision_phi(outpath=f'{phi_path}/{epoch}/')\n torch.save(self.state_dict(), phi_path + '/topic_pretrain_{}.pth'.format(str(self.train_num)))\n with open(phi_path + '/Phi_{}.pkl'.format(str(self.train_num)), 'wb') as f:\n pickle.dump(self.global_params.Phi, f)\n\n\n def load(self, checkpoint_path: str, directory_path: str):\n '''\n Load the model parameters from the checkpoint and the specified directory.\n Inputs:\n model_path : [str] the path to load the model.\n\n '''\n assert os.path.exists(checkpoint_path), 'Path Error: can not find the path to load the checkpoint'\n assert os.path.exists(directory_path), 'Path Error: can not find the path to load the directory'\n\n # load parameters of neural network\n checkpoint = torch.load(checkpoint_path)\n self.load_state_dict(checkpoint['state_dict'])\n\n # load parameters of basic model\n model = np.load(directory_path, allow_pickle=True).item()\n for params in ['global_params', 'local_params', '_model_setting', '_hyper_params']:\n if params in model:\n setattr(self, params, model[params])\n\n def save(self, model_path: str = './save_models'):\n '''\n Save the model to the checkpoint the specified directory.\n Inputs:\n model_path : [str] the path to save the model, default './save_models/WHAI.npy' and './save_models/WHAI.pth'\n '''\n # create the trained model path\n if not os.path.isdir(model_path):\n os.mkdir(model_path)\n\n # save parameters of neural network\n torch.save({'state_dict': self.state_dict()}, model_path + '/' + self._model_name + '.pth')\n print('parameters of neural network have been saved by ' + model_path + '/' + self._model_name + '.pth')\n\n # save parameters of basic model\n model = {}\n for params in ['global_params', 'local_params', '_model_setting', '_hyper_params']:\n if params in dir(self):\n model[params] = getattr(self, params)\n\n np.save(model_path + '/' + self._model_name + '.npy', model)\n print('parameters of basic model have been saved by ' + model_path + '/' + self._model_name + '.npy')\n\n","sub_path":"pydpm/_model/_whai.py","file_name":"_whai.py","file_ext":"py","file_size_in_byte":24238,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"410747748","text":"#!/usr/bin/env python\n\nfrom __future__ import print_function # Python 2.7+ required\nimport os\nimport sys\nimport csv\nimport re\nimport argparse\nfrom collections import defaultdict\n\ntry:\n from humann2 import config\n from humann2.tools import util\n from humann2.tools.humann2_table import Table\nexcept ImportError:\n sys.exit( \"CRITICAL ERROR: Unable to find the HUMAnN2 python package.\\n\" +\n \"Please check your install.\" )\n\ntry:\n import numpy as np\nexcept ImportError:\n sys.exit( \"CRITICAL ERROR: This script requires the python scientific stack (e.g. numpy)\" )\n\ndescription = util.wrap( \"\"\"\nHUMAnN2 utility for inferring taxonomy\n\nGiven a gene families file, this script can infer the taxonomy of\nunclassified features based on known lowest command ancestor (LCA)\nannotations of UniRef50/90 clusters. This script can also be applied \nto _any_ HUMAnN2 table to regroup species-level stratifications to \nbroader taxonomic levels (\"species\" mode).\n\"\"\" )\n\n# ---------------------------------------------------------------\n# check that user has the required database file\n# ---------------------------------------------------------------\n\ntry:\n all_mapping_files = os.listdir( config.utility_mapping_database )\nexcept EnvironmentError:\n all_mapping_files = []\n\ndatabases = {\n \"uniref50\": \"uniref50-tol-lca.dat.gz\",\n \"uniref90\": \"uniref90-tol-lca.dat.gz\",\n }\n\nSOMETHING_MISSING = False\nfor key, value in databases.items( ):\n if value not in all_mapping_files:\n SOMETHING_MISSING = True\n else:\n databases[key] = os.path.join( config.utility_mapping_database, value )\n\nif SOMETHING_MISSING:\n sys.exit( \"\"\"\nThis script requires the HUMAnN2 utility data files.\nTo add these to your installation, please execute:\n\n$ humann2_databases --download utility_mapping full $DIR\n\nReplacing, $DIR with the directory to install the databases.\n\"\"\" )\n\n# ---------------------------------------------------------------\n# constants\n# ---------------------------------------------------------------\n\nc_levels = [\n \"Kingdom\",\n \"Phylum\",\n \"Class\",\n \"Order\",\n \"Family\",\n \"Genus\",\n]\n\nc_modes = [\n \"stratified: adjust all strata (UniRef50/90 only)\",\n \"species: adjust species strata only\",\n \"unclassified: adjust unclassified, discarding totals + species (UniRef50/90 only)\",\n \"totals: adjust totals, discarding strata (UniRef50/90 only)\",\n]\nc_mode_names = [k.split( \":\" )[0] for k in c_modes]\n\nc_tol_header = \"# TOL\"\nc_lca_header = \"# LCA\"\nc_bypass = \"AmbiguousBypass\"\nc_na = \"-\"\n\n# ---------------------------------------------------------------\n# helper objects\n# ---------------------------------------------------------------\n\nclass Taxon:\n def __init__( self, name, common, rank, pname, status ):\n self.name = name\n self.common = common\n self.rank = rank\n self.pname = pname\n self.status = status\n\nclass TreeOfLife:\n def __init__( self ):\n self.nodes = {}\n self.connect = {}\n def attach( self, node ):\n self.nodes[node.name] = node\n if node.status != c_bypass:\n self.connect[node.common] = node.name\n def get_lineage( self, common ):\n lineage = []\n if common in self.connect:\n name = self.connect[common]\n while name in self.nodes and name != c_na:\n node = self.nodes[name]\n lineage.append( [node.rank, node.common] )\n name = node.pname\n return lineage\n\n# ---------------------------------------------------------------\n# command-line interface\n# ---------------------------------------------------------------\n\ndef get_args( ):\n \"\"\" Get args from Argparse \"\"\"\n parser = argparse.ArgumentParser(\n description=description,\n formatter_class=argparse.RawTextHelpFormatter,\n )\n util.attach_common_arguments( parser ) \n parser.add_argument( \"-l\", \"--taxonomic-level\",\n choices=c_levels,\n metavar=\"\",\n default=\"Genus\",\n help=util.pretty_grid( c_levels, cols=7,\n desc=\"Level for taxonomic summarization [Default=Genus]:\" ), \n )\n parser.add_argument( \"-r\", \"--resolution\",\n metavar=\"\",\n choices=databases.keys( ),\n help=util.pretty_grid( databases.keys( ), \"Required outside of 'species' mode:\" ),\n )\n parser.add_argument( \"-m\", \"--mode\",\n choices=c_mode_names,\n default=\"stratified\",\n metavar=\"\",\n help=util.pretty_grid( c_modes, cols=1, desc=\"Operating mode [Default=stratified]\" ),\n )\n parser.add_argument( \"-t\", \"--threshold\", \n type=float, \n default=None,\n metavar=\"\",\n help=\"Minimum frequency for a new taxon to be included\\n[Default=0/include everything]\",\n )\n parser.add_argument( \"-w\", \"--taxonomy-report\",\n metavar=\"\",\n default=None,\n help=\"Write a taxonomy report at the specified path.\\n[Default=no report]\",\n )\n parser.add_argument( \"-d\", \"--dev\",\n metavar=\"\",\n help=\"Manually specify a development database\",\n )\n args = parser.parse_args( )\n return args\n\n# ---------------------------------------------------------------\n# utilities\n# ---------------------------------------------------------------\n\ndef simplify( name ):\n return re.sub( \"[^A-Za-z0-9]+\", \"_\", name )\n\ndef genus_taxmap( features ):\n \"\"\"Get species->genus map from HUMAnN2 stratifications\"\"\"\n taxmap = {}\n for feature in features:\n fbase, fname, stratum = util.fsplit( feature )\n if stratum is not None and stratum != util.c_unclassified:\n genus = stratum.split( util.c_taxon_delim )[0]\n taxmap[stratum] = genus\n return taxmap\n\ndef complete_taxmap( features, target_rank, p_datafile ):\n \"\"\"Load full taxonomy from the TOL file\"\"\"\n unirefs = {util.fsplit( k )[0] for k in features}\n unirefs = {k for k in unirefs if \"UniRef\" in k}\n # load tree of life, subset uniref lca annotation and add to taxmap\n tol = TreeOfLife( )\n taxmap = {}\n tol_mode = False\n lca_mode = False\n with util.try_zip_open( p_datafile ) as fh:\n print( \"Loading taxonomic data from: \" + p_datafile, file=sys.stderr )\n for row in csv.reader( fh, csv.excel_tab ):\n if row[0] == c_tol_header:\n print( \" Loading TOL data\", file=sys.stderr )\n tol_mode = True\n continue\n if row[0] == c_lca_header:\n print( \" Loading LCA data\", file=sys.stderr )\n tol_mode = False\n lca_mode = True\n continue\n if tol_mode:\n tol.attach( Taxon( *row ) )\n elif lca_mode:\n uni, lca = row\n if uni in unirefs:\n for rank, common in tol.get_lineage( lca ):\n if rank == target_rank:\n taxmap[uni] = rank.lower( )[0] + \"__\" + simplify( common )\n break\n # augment taxmap with genus-level lineage information for stratified features\n for feature in features:\n feature, name, stratum = util.fsplit( feature )\n if stratum is not None and \"g__\" in stratum:\n genus = stratum.split( util.c_taxon_delim )[0]\n if target_rank == \"Genus\":\n taxmap[stratum] = genus\n else:\n genus = genus.replace( \"g__\", \"\" )\n for rank, common in tol.get_lineage( genus ):\n if rank == target_rank:\n taxmap[stratum] = rank.lower( )[0] + \"__\" + simplify( common )\n break\n return taxmap\n\ndef tax_connect( feature, taxmap ):\n \"\"\"Adjust a feature's taxonomy based on the taxmap\"\"\"\n old = feature\n feature, name, stratum = util.fsplit( feature )\n # get taxonomy based on UniRef annotation (UniRefs only)\n if stratum is None or stratum == util.c_unclassified:\n stratum2 = taxmap.get( feature, util.c_unclassified )\n # get taxonomy based on HUMAnN2 taxonony (any type of feature)\n else:\n stratum2 = taxmap.get( stratum, util.c_unclassified )\n return util.fjoin( feature, name, stratum2 )\n\ndef generate_mapping( table, taxmap, mode ):\n \"\"\"Determine which original-table rows to keep and how to recombine them;\n varies substantially with the --mode option\"\"\" \n mapping = defaultdict( set )\n for f in table.data:\n fbase, fname, stratum = util.fsplit( f )\n # new_f is f with new taxonomy (if found) else \"unclassified\"\n new_f = tax_connect( f, taxmap )\n # community total\n if stratum is None:\n # always keep UNMAPPED\n if f == util.c_unmapped:\n mapping[f].add( f )\n # keep original totals unless in \"unclassified\" mode\n elif mode != \"unclassified\":\n mapping[f].add( f )\n # total becomes a new stratum in \"totals\" mode\n if mode == \"totals\":\n mapping[new_f].add( f )\n # unclassified stratum\n elif stratum == util.c_unclassified:\n # create a new total in unclassified mode and infer\n if mode == \"unclassified\":\n new_tot = util.fjoin( fbase, fname, None )\n mapping[new_tot].add( f )\n mapping[new_f].add( f )\n # infer in stratified mode\n elif mode == \"stratified\":\n mapping[new_f].add( f )\n # just pass through in species mode\n elif mode == \"species\":\n mapping[f].add( f )\n # this must be a known-species stratum\n elif \"s__\" in stratum:\n if mode in [\"stratified\", \"species\"]:\n mapping[new_f].add( f )\n return mapping\n\ndef tax_report( table, path ):\n \"\"\"Write a summary of the new taxa in the output table\"\"\"\n # s --> stratum throughout this function\n stacks = {}\n for f in table.data:\n fbase, fname, s = util.fsplit( f )\n if s is not None:\n stacks.setdefault( s, [] ).append( table.data[f] )\n totals = table.zeros( )\n # sum within-sample, normalize to sample totals\n masses = {}\n for s, stack in stacks.items( ):\n masses[s] = np.sum( np.vstack( stack ), axis=0 )\n totals += masses[s]\n masses = {s:np.mean( row/totals ) for s, row in masses.items( )}\n # report\n with util.try_zip_open( path, \"w\" ) as fh:\n print( \"Taxon\\tMean % of new abundance\", file=fh )\n for s in sorted( masses, key=lambda x: -masses[x] ):\n if masses[s] > 0:\n print( \"{}\\t{:.1f}\".format( s, 100 * masses[s] ), file=fh )\n\ndef load_appropriate_taxmap( table, args ):\n # infer taxmap from humann2 stratifications\n if args.mode == \"species\" and args.taxonomic_level == \"Genus\":\n taxmap = genus_taxmap( table.data.keys( ) )\n # get from the uniref50 tol file, although no uniref data needed\n elif args.mode == \"species\":\n taxmap = complete_taxmap( table.data.keys( ), args.taxonomic_level, databases[\"uniref50\"] )\n # load a dev taxmap\n elif args.dev is not None:\n taxmap = complete_taxmap( table.data.keys( ), args.taxonomic_level, args.dev )\n # fail if the specific taxmap doesn't exist\n elif args.resolution not in databases:\n sys.exit( (\"CRITICAL ERROR: Outside of 'species' mode you must specify your UniRef resolution\\n\"\n \"using the -r/--resolution flag\") )\n # typical case\n else:\n taxmap = complete_taxmap( table.data.keys( ), args.taxonomic_level, databases[args.resolution] )\n # optionally forget very rare taxa in the taxmap\n if args.threshold > 0:\n counts = {}\n for old, new in taxmap.items( ):\n counts[new] = counts.get( new, 0 ) + 1\n total = float( sum( counts.values( ) ) )\n counts = {k:v/total for k, v in counts.items( )}\n for old, new in taxmap.items( ):\n if counts[new] < args.threshold:\n taxmap[old] = util.c_unclassified\n # done\n return taxmap\n\ndef summarize_success( mapping, args ):\n \"\"\"print a summary of features that are no longer unclassified after mapping\"\"\"\n total = set( )\n unclass = set( )\n for f in mapping:\n fbase, fname, stratum = util.fsplit( f )\n if stratum is not None:\n total.add( fbase )\n if stratum == util.c_unclassified:\n unclass.add( fbase )\n success = total - unclass\n success_rate = 0\n if len( total ) > 0:\n success_rate = 100 * len( success ) / float( len( total ) )\n print( \"Reclassification summary:\", file=sys.stderr )\n print( \" Level: {}\".format( args.taxonomic_level ), file=sys.stderr )\n print( \" Features considered: {:,}\".format( len( total ) ), file=sys.stderr )\n print( \" Fully classified at target level: {:,} ({:.1f})%\".format( \n len( success ), success_rate ), file=sys.stderr )\n\n# ---------------------------------------------------------------\n# main\n# ---------------------------------------------------------------\n\ndef main( ):\n args = get_args( )\n table = Table( args.input, last_metadata=args.last_metadata )\n # make a taxmap\n print( \"Building taxonomic map for input table\", file=sys.stderr )\n taxmap = load_appropriate_taxmap( table, args )\n # reindex the table\n print( \"Reindexing the table\", file=sys.stderr )\n mapping = generate_mapping( table, taxmap, args.mode )\n # rebuild the table\n print( \"Rebuilding the input table\", file=sys.stderr )\n new_data = {}\n for f in mapping:\n new_data[f] = table.zeros( )\n for f2 in mapping[f]:\n new_data[f] += table.data[f2]\n new_table = Table( new_data, metadata=table.metadata, headers=table.headers )\n # report on performance\n summarize_success( mapping, args )\n # output\n new_table.write( args.output, unfloat=True )\n # write tax report?\n if args.taxonomy_report is not None:\n print( \"Writing taxonomy report to <{}>\".format( args.taxonomy_report ), file=sys.stderr )\n tax_report( new_table, args.taxonomy_report )\n\nif __name__ == \"__main__\":\n main( )\n","sub_path":"humann2/tools/infer_taxonomy.py","file_name":"infer_taxonomy.py","file_ext":"py","file_size_in_byte":14747,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"81075795","text":"#!/usr/bin/env python\n\nimport subprocess\nimport os\n\nsource = \"compute.cu\"\n\ndef setup_module(module):\n THIS_DIR = os.path.dirname(os.path.abspath(__file__))\n os.chdir(THIS_DIR)\n\ndef teardown_module(module):\n cmd = [\"make -f Makefile.0 clean\"]\n cmdOutput = subprocess.check_output(cmd, stderr=subprocess.STDOUT, shell=True)\n\ndef test_1():\n cmd = [\"make -f Makefile.0\"]\n cmdOutput = subprocess.check_output(cmd, stderr=subprocess.STDOUT, shell=True)\n \n # it should find one time instrumention with 0.0, not with 0 (integer) \n numbwerOfTransformations = 0\n fd = open(source, \"r\")\n for l in fd:\n if \"_FPC_CHECK_(0.\" in l:\n numbwerOfTransformations = numbwerOfTransformations + 1\n fd.close()\n \n assert numbwerOfTransformations == 1\n","sub_path":"tests/clang_plugin/static/test_constant_expressions/test_constant_expressions.py","file_name":"test_constant_expressions.py","file_ext":"py","file_size_in_byte":785,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"182379718","text":"# -*- coding: utf-8 -*-\n# @Time : 19-1-2 下午3:29\n\n\n# 与Area模型相关的数据库操作存储位置\nimport json\nimport os\nimport random\nimport sys\nfrom urllib import request\n\nimport requests\n\nfrom api.common_func.city_code import city_codes, level_code\nfrom api.models.models import Area, row2dict, db, Area_rate, NearbyArea\n\n\nclass AreaM(object):\n def get_all(self):\n areas = Area.query.all()\n return areas\n\n def list_all(self):\n areas = Area.query.all()\n json_list = []\n for i in areas:\n json_dict = {}\n json_dict[\"area_id\"] = i.id\n # json_dict[\"rate_id\"] = i.rate_id\n json_dict[\"cen_loc\"] = i.locations['cen']\n json_dict[\"locations\"] = i.locations\n level = AreaRateM().get(i.rate_id)['rate_level']\n # print(level)\n sur = i.surrounds['surrounds'][0]['title'] if i.surrounds['surrounds'] else \" \"\n # print(sur)\n rate_level = level_code[str(level)] if level else \" \"\n json_dict[\"level\"] = level\n json_dict[\"surrounds\"] = sur\n json_dict[\"area_rate\"] = rate_level\n json_dict[\"business\"] = i.business\n json_dict[\"address\"] = i.address\n json_dict['active'] = i.active\n json_list.append(json_dict)\n\n return json_list\n\n def get(self, id):\n res = Area.query.get(id)\n\n if res:\n return row2dict(res)\n else:\n return None\n\n def get_obj(self, id):\n res = Area.query.get(id)\n if res:\n return res\n else:\n return None\n\n def get_active_obj(self):\n res = Area.query.filter(Area.active == 1)\n return res\n\n def add_new(self, **args):\n new_co = Area(**args)\n db.session.add(new_co)\n db.session.commit()\n return self.get(new_co.id)\n\n def update(self, id, param):\n # print id, param\n Area.query.filter(Area.id == id).update(param)\n db.session.commit()\n return 'success'\n\n def delete(self, id):\n tmp = Area.query.filter(Area.id == id)\n db.session.delete(tmp.one())\n db.session.commit()\n return 'success'\n\n def get_area(self, name):\n res = Area.query.filter(Area.city_name == name)\n return res\n\n @staticmethod\n def set_area():\n temp = os.getcwd()\n with open(temp + '/models/mapAll.json', encoding='utf-8') as f:\n # with open(temp + '/api/models/mapAll.json', encoding='utf-8') as f:\n res = json.load(f)\n # print(res)\n f.close()\n for i in res:\n # lng:经度,lat:纬度\n # 区域坐标:\n locations = {\n 'cen': i['cen'],\n 'lt': i['lt'],\n 'ld': i['ld'],\n 'rt': i['rt'],\n 'rd': i['rd']\n }\n # 周边建筑群:\n surs = {\n 'surrounds': i['detail']['surroundingPois']\n }\n count = len(surs['surrounds'])\n business = i['detail']['business']\n city_name = i['detail']['addressComponents']['city']\n address = i['detail']['address']\n if city_name:\n city_code = city_codes[city_name] if city_name else \"\"\n else:\n city_name = ' '\n city_code = ' '\n # 将数据存储在数据库中\n areas = AreaM()\n if count < 1:\n areas.add_new(city_name=city_name, city_code=city_code, locations=locations, surrounds=surs,\n sur_count=count, business=business, address=address, rate_id=2)\n else:\n areas.add_new(city_name=city_name, city_code=city_code, locations=locations, surrounds=surs,\n sur_count=count, address=address, business=business, rate_id=1)\n\n return 'set data successfully!'\n\n @staticmethod\n def update_area_description():\n areas = AreaM().get_all()\n for i in areas:\n lng, lat = i.locations['cen']['lng'], i.locations['cen']['lat']\n loc = '{0},{1}'.format(lng, lat)\n # location_url = \"http://api.map.baidu.com/geocoder/v2/?callback=renderReverse&location=35.658651,139.745415\" \\\n # \"&output=json&pois=1&latest_admin=1&ak=您的ak //GET请求\"\n\n res = requests.get(\n url=\"https://restapi.amap.com/v3/geocode/regeo\",\n params={\n \"key\": \"1307e088b2362d9d10bb5a3a26a4c29e\",\n \"output\": \"json\",\n \"location\": loc,\n \"radius\": 1000\n }\n )\n result = res.json()['regeocode']['formatted_address']\n if result:\n param = {\"area_description\": result}\n AreaM().update(i.id, param)\n # print('update successfully.')\n else:\n param = {\"area_description\": i.city_name}\n AreaM().update(i.id, param)\n\n\nclass AreaRateM(object):\n def list_all(self):\n pass\n\n def get(self, id):\n res = Area_rate.query.filter(Area_rate.id == id).one_or_none()\n return row2dict(res)\n\n def add_new(self, **args):\n new_co = Area_rate(**args)\n db.session.add(new_co)\n db.session.commit()\n return self.get(new_co.id)\n\n def get_obj(self, level):\n res = Area_rate.query.filter(\n Area_rate.rate_level == level).one_or_none()\n return row2dict(res)\n\n\nclass NearbyM(object):\n def list_all(self):\n nearby = NearbyArea.query.all()\n return nearby\n\n def get(self, id):\n res = NearbyArea.query.filter(NearbyArea.id == id).one_or_none()\n return row2dict(res)\n\n def get_nearby(self, area_id):\n res = NearbyArea.query.filter(\n NearbyArea.area_id == area_id).one_or_none()\n return row2dict(res)\n\n def add_new(self, **args):\n new_co = NearbyArea(**args)\n db.session.add(new_co)\n db.session.commit()\n return self.get(new_co.id)\n\n\ndef gen_loc(area_id):\n \"\"\"\n 根据区域id随机生成该区域的坐标,并获取地址名称\n :param area_id: 区域id\n \"\"\"\n res = AreaM().get(area_id)\n if res:\n lt_lat = res['locations']['lt']['lat']\n ld_lat = res['locations']['ld']['lat']\n ld_lng = res['locations']['ld']['lng']\n rd_lng = res['locations']['rd']['lng']\n gen_lat = round(random.uniform(ld_lat, lt_lat), 6)\n gen_lng = round(random.uniform(ld_lng, rd_lng), 6)\n loc = '{0},{1}'.format(gen_lat, gen_lng)\n loc_name = gen_locname(loc)\n return loc, loc_name\n else:\n return None\n\n\ndef gen_locname(loc):\n \"\"\"\n 根据百度地图api获取地址名称\n :param loc: (lat,lng)\n \"\"\"\n ak = '1mGq6bdr1Ys05haNBw755UGc4tAEDsEe'\n res = requests.get(\n url=\"https://api.map.baidu.com/reverse_geocoding/v3/?ak=\" + ak,\n params={\n \"output\": \"json\",\n \"location\": loc,\n \"coordtype\": \"wgs84ll\"\n }\n ).json()\n return res.get('result')['formatted_address']\n\n\nclass HandlePois(object):\n \"\"\"\n 运用高德地图api获取相关指标确定不同区域的定性\n \"\"\"\n\n def __init__(self):\n self.key = ''\n\n def car_wash_pois(self, location, radius):\n '''洗车店附近的poi'''\n\n url = 'https://restapi.amap.com/v3/place/around?key=%s&types=010500' % self.key\n res = requests.get(\n url=url,\n params={\n \"location\": location,\n \"output\": \"json\",\n \"radius\": radius,\n \"page\": 1,\n \"extensions\": \"all\",\n \"offset\": 20\n }\n ).json()\n return res['pois']\n\n def restaurant_pois(self, location, radius):\n '''餐馆附近的poi'''\n # url = 'https://restapi.amap.com/v3/place/around?key=%s' \\\n # '&location=%s&keywords=&types=%s&radius=3000&offset=20&page=1&extensions=all' \\\n # % (self.key, location, types)\n url = 'https://restapi.amap.com/v3/place/around?key=%s&types=050100' % self.key\n res = requests.get(\n url=url,\n params={\n \"location\": location,\n \"output\": \"json\",\n \"radius\": radius,\n \"page\": 1,\n \"extensions\": \"all\",\n \"offset\": 20\n }\n ).json()\n return res['pois']\n\n def area_carwash_pois(self):\n areas = AreaM().list_all()\n car_cost = {}\n for i in areas:\n cen_loc = i['cen_loc']\n pois = self.car_wash_pois(cen_loc, 3000)\n cost = []\n for j in pois:\n c = j['biz_ext']['cost']\n cost.append(c)\n car_cost[i['area_id']] = cost\n return car_cost\n\n def area_restaurant_pois(self):\n areas = AreaM().list_all()\n restaurant_cost = {}\n for i in areas:\n cen_loc = i['cen_loc']\n pois = self.car_wash_pois(cen_loc, 3000)\n cost = []\n for j in pois:\n c = j['biz_ext']['cost']\n cost.append(c)\n restaurant_cost[i['area_id']] = cost\n return restaurant_cost\n","sub_path":"api/common_func/area.py","file_name":"area.py","file_ext":"py","file_size_in_byte":9427,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"211416591","text":"import tensorflow as tf\n\n\nclass Model(object):\n\tdef __init__(self, batch_size=32, learning_rate=1e-4, num_labels=15):\n\t\tself._batch_size = batch_size\n\t\tself._learning_rate = learning_rate\n\t\tself._num_labels = num_labels\n\t\n\tdef inference(self, images, keep_prob):\n\t\twith tf.name_scope('input'):\n\t\t\tx = tf.reshape(images, [-1, 64, 64, 3])\n\t\t\tself.activation_summary(x)\n\t\t\t\n\t\twith tf.variable_scope('conv1') as scope:\n\t\t\tkernel = self.weights([5, 5, 3, 32])\n\t\t\tconv = self.conv(x, kernel)\n\t\t\tbias = self.bias([32])\n\t\t\tpreactivation = tf.nn.bias_add(conv, bias)\n\t\t\tconv1 = tf.nn.relu(preactivation, name=scope.name)\n\t\t\tprint (conv1.get_shape())\n\t\t\tself.activation_summary(conv1)\n\t\t\twith tf.variable_scope('visualization'):\n\t\t\t\t# scale weights to [0 1], type is still float\n\t\t\t\tx_min = tf.reduce_min(kernel)\n\t\t\t\tx_max = tf.reduce_max(kernel)\n\t\t\t\tkernel_0_to_1 = (kernel - x_min) / (x_max - x_min)\n\t\t\t\t# to tf.image_summary format [batch_size, height, width, channels]\n\t\t\t\tkernel_transposed = tf.transpose (kernel_0_to_1, [3, 0, 1, 2])\n\t\t\t\t# this will display random 3 filters from the 64 in conv1\n\t\t\t\ttf.summary.image('conv1/filters', kernel_transposed, max_outputs=64)\n\t\t\n\t\twith tf.variable_scope('conv2') as scope:\n\t\t\tkernel = self.weights([5, 5, 32, 64])\n\t\t\tconv = self.conv(conv1, kernel)\n\t\t\tbias = self.bias([64])\n\t\t\tpreactivation = tf.nn.bias_add(conv, bias)\n\t\t\tconv2 = tf.nn.relu(preactivation, name=scope.name)\n\t\t\tprint (conv2.get_shape())\n\t\t\tself.activation_summary(conv2)\n\n\t\twith tf.variable_scope('conv3') as scope:\n\t\t\tkernel = self.weights([3, 3, 32, 128])\n\t\t\tconv = self.conv(conv1, kernel)\n\t\t\tbias = self.bias([128])\n\t\t\tpreactivation = tf.nn.bias_add(conv, bias)\n\t\t\tconv3 = tf.nn.relu(preactivation, name=scope.name)\n\t\t\tprint (conv3.get_shape())\n\t\t\tself.activation_summary(conv3)\n\n\t\twith tf.variable_scope('local1') as scope:\n\t\t\treshape = tf.reshape(conv3, [-1, 64 * 64 * 128])\n\t\t\tW_fc1 = self.weights([64 * 64 * 128, 1024])\n\t\t\tb_fc1 = self.bias([1024])\n\t\t\tlocal1 = tf.nn.relu(tf.matmul(reshape, W_fc1) + b_fc1, name=scope.name)\n\t\t\tself.activation_summary(local1)\n\t\t\n\t\twith tf.variable_scope('local2_linear') as scope:\n\t\t\tW_fc2 = self.weights([1024, self._num_labels])\n\t\t\tb_fc2 = self.bias([self._num_labels])\n\t\t\tlocal1_drop = tf.nn.dropout(local1, keep_prob)\n\t\t\tlocal2 = tf.nn.bias_add(tf.matmul(local1_drop, W_fc2), b_fc2, name=scope.name)\n\t\t\tself.activation_summary(local2)\n\t\treturn local2\n\t\n\tdef train(self, loss, global_step):\n\t\ttf.summary.scalar('learning_rate', self._learning_rate)\n\t\ttrain_op = tf.train.AdamOptimizer(self._learning_rate).minimize(loss, global_step=global_step)\n\t\treturn train_op\n\t\n\tdef loss(self, logits, labels):\n\t\twith tf.variable_scope('loss') as scope:\n\t\t\tprint (logits.get_shape())\n\t\t\tcross_entropy = tf.nn.sparse_softmax_cross_entropy_with_logits(logits=logits, labels=labels)\n\t\t\tprint (cross_entropy.get_shape())\n\t\t\tcost = tf.reduce_mean(cross_entropy, name=scope.name)\n\t\t\tprint (cost.get_shape())\n\t\t\ttf.summary.scalar('cost', cost)\n\t\treturn cost\n\t\t\n\tdef predictions(self, logits):\n\t\twith tf.variable_scope('predictions') as scope:\n\t\t\tpredictions=tf.nn.softmax(logits, name='pred')\n\t\t\ttf.summary.scalar('predictions', predictions)\n\t\treturn predictions\n\t\t\n\tdef accuracy(self, logits, y):\n\t\twith tf.variable_scope('accuracy') as scope:\n\t\t\taccuracy = tf.reduce_mean(tf.cast(tf.equal(tf.cast(tf.argmax(logits, 1), dtype=tf.int64), y), dtype=tf.float32),name=scope.name)\n\t\t\ttf.summary.scalar('accuracy', accuracy)\n\t\treturn accuracy\n\t\t\n\tdef conv(self, x, W):\n\t\treturn tf.nn.conv2d(input=x, filter=W, strides=[1, 1, 1, 1], padding='SAME')\n\t\t\t\n\tdef atrous_conv(self, x, W, rate):\n\t\treturn tf.nn.conv2d(input=x, filter=W, rate=rate, padding='SAME')\n\t\t\n\tdef max_pool(self, input, shape, stride):\n\t\treturn tf.nn.max_pool(value=input, ksize=[1, shape, shape, 1], strides=[1, stride, stride, 1], padding='SAME')\n\t\t\t\n\tdef avg_pool(self, shape, stride):\n\t\treturn tf.nn.avg_pool(value=input, ksize=[1, shape, shape, 1], strides=[1, stride, stride, 1], padding='SAME')\n\t\t\n\tdef batch_norm(self, x):\n\t\treturn tf.nn.batch_normalization(value=input)\n\t\t\n\tdef weights(self, shape):\n\t\treturn tf.Variable(tf.truncated_normal(shape=shape, stddev=0.1, dtype=tf.float32), name='weights')\n\t\t\n\tdef bias(self, shape):\n\t\treturn tf.Variable(tf.constant(1., shape=shape, dtype=tf.float32), name='bias')\n\t\t\n\tdef activation_summary(self, var):\n\t\twith tf.name_scope('summaries'):\n\t\t\tmean = tf.reduce_mean(var)\n\t\t\ttf.summary.scalar('mean', mean)\n\t\twith tf.name_scope('stddev'):\n\t\t\tstddev = tf.sqrt(tf.reduce_mean(tf.square(var - mean)))\n\t\t\ttf.summary.scalar('stddev', stddev)\n\t\t\ttf.summary.scalar('max', tf.reduce_max(var))\n\t\t\ttf.summary.scalar('min', tf.reduce_min(var))\n\t\t\ttf.summary.histogram('histogram', var)","sub_path":"code/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":4717,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"359558808","text":"\"\"\"\n3He functions added so far:\n - Calculate production rate scaling using Stone/Lal scheme (stone_scaling)\n - Calculate exposure age (exposure_age)\n\nNotes:\n - Calculating the exposure age also calculates a scaled production rate by \n a) using available data of production rate in certain locations\n b) scaling it using Stone/Lal scheme\n\"\"\"\n\nimport pandas as pd\nimport numpy as np\nfrom scipy.interpolate import interp1d\nfrom .CosmoConstants import he3_production_df\n\n\ndef _stone_lal_coefficients(latitude):\n \"\"\"\n Generate coefficient values for the scaling calculation. \n Parameters are defined only by certain latitude values, therefore, a linear interpolation is used to\n calculate the coefficients for other values.\n\n Args:\n latitude - latitude value in decimals, float\n\n Returns:\n scaling_coefficients: coefficients values, floats list\n\n Reference:\n https://doi.org/10.1029/2000JB900181\n \"\"\"\n\n # definir os pontos a serem usados na interpolação\n _latitudes = [0, 10, 20, 30, 40, 50, 60]\n _a = [31.8518, 34.3699, 40.3153, 42.0983, 56.7733, 69.0720, 71.8733]\n _b = [250.3193, 258.4759, 308.9894, 512.6857, 649.1343, 832.4566, 863.1927]\n _c = [-0.083393, -0.089807, -0.106248, -\n 0.120551, -0.160859, -0.199252, -0.207069]\n _d = [7.4260e-5, 7.9457e-5, 9.4508e-5,\n 1.1752e-4, 1.5463e-4, 1.9391e-4, 2.0127e-4]\n _e = [-2.2397e-8, -2.3697e-8, -2.8234e-8, -\n 3.8809e-8, -5.0330e-8, -6.3653e-8, -6.6043e-8]\n _m = [0.587, 0.600, 0.678, 0.833, 0.933, 1.000, 1.000]\n _constants_list = [_a, _b, _c, _d, _e, _m]\n\n # absolute of latitude\n latitude = np.abs(latitude)\n\n # latitude <= 60 deg\n if np.any(latitude) > 60.0:\n latitude = 60.0\n\n # interpolar os pontos usados\n _a_interp = interp1d(_latitudes, _a)\n _b_interp = interp1d(_latitudes, _b)\n _c_interp = interp1d(_latitudes, _c)\n _d_interp = interp1d(_latitudes, _d)\n _e_interp = interp1d(_latitudes, _e)\n _m_interp = interp1d(_latitudes, _m)\n\n scaling_coefficients = [_a_interp(latitude),\n _b_interp(latitude),\n _c_interp(latitude),\n _d_interp(latitude),\n _e_interp(latitude),\n _m_interp(latitude)]\n\n return scaling_coefficients\n\n\ndef stone_scaling(elevation, latitude):\n \"\"\"\n Calculates the scaling factor proposed by Stone (2000).\n\n Args:\n elevation - elevation in meters, float\n latitude - latitude value in decimals, float\n\n Returns:\n s - scaling factor, float\n\n Reference:\n https://doi.org/10.1029/2000JB900181\n \"\"\"\n # calculation of P\n # P is the pressure based on input elevation\n _Ps = 1013.25 # hPa\n _Ts = 288.15 # K\n _epsilon = 0.0065 # K/m\n _gM_by_R = 0.03417 # k/m\n _z = elevation # m\n\n _log_1 = np.log(_Ts)\n _arg_log2 = _epsilon*_z\n _log_2 = np.log(_Ts - _arg_log2)\n _logarg = _log_1 - _log_2\n _exponent = -(_gM_by_R/_epsilon)*(_logarg)\n\n _Pz = _Ps*np.exp(_exponent)\n\n # scaling equation:\n\n _coefficients = _stone_lal_coefficients(latitude)\n _s1 = _coefficients[0]\n _s2 = _coefficients[1]*np.exp(-_Pz/150)\n _s3 = _coefficients[2]*_Pz\n _s4 = _coefficients[3]*_Pz*_Pz\n _s5 = _coefficients[4]*_Pz*_Pz*_Pz\n s = _s1 + _s2 + _s3 + _s4 + _s5\n\n return s\n\n\ndef exposure_age(sample, concentration, set_production=None, elevation=None, latitude=None, mineral=None, inplace=False):\n \"\"\"\n Calculates exposure age proposed by Phillips & Gosse (2001),\n using Stone (2000) scaling factors.\n\n Args:\n sample - sample dataframe name, string\n concentration - column name in which are stored the concentrations, string\n elevation - elevation in meters, float\n latitude - latitude value in decimals, float\n mineral - target mineral name, string\n\n inplace - if True, creates a new column on the sample dataframe with exposure ages\n\n Returns:\n exp_age - calculated exposure age\n\n References:\n Stone (2000) - https://doi.org/10.1029/2000JB900181\n Phillips & Gosse (2001) - https://doi.org/10.1016/S0277-3791(00)00171-2\n \"\"\"\n # correct output\n if set_production:\n exp_age = sample[concentration]/set_production\n\n # scale calculation\n else:\n\n # scaling production rate\n production_df = he3_production_df()\n scale = stone_scaling(\n sample[elevation].values, sample[latitude].values)\n\n production_rate = production_df.loc[mineral]['production_rate']\n production_scaled = production_rate*scale\n\n # getting total counts\n _total_counts = sample[concentration]\n exp_age = _total_counts/production_scaled\n\n if inplace:\n sample['{}_exposure_age'.format(concentration)] = exp_age\n\n return exp_age\n","sub_path":"chronokit/cosmogenic/He3.py","file_name":"He3.py","file_ext":"py","file_size_in_byte":4922,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"93655193","text":"from flask import Flask\nfrom flask_restful import Resource, Api\nfrom flask_restful.reqparse import RequestParser\nfrom datetime import datetime\nfrom analytics.analytics import monte_carlo_portfolio_simul\n\nmonte_carlo_request_parser = RequestParser(bundle_errors=False)\n\nmonte_carlo_request_parser.add_argument(\"DaysBack\", type=int, required=False,\n help=\"Number of business days from the specified date to now\")\n\nmonte_carlo_request_parser.add_argument(\"DaysFwd\", type=int, required=False,\n help=\"Number of business days from the specified date to now\")\n\nmonte_carlo_request_parser.add_argument(\"InvestedAmount\", type=int, required=False,\n help=\"Amount invested\", default=10000)\n\nmonte_carlo_request_parser.add_argument(\"NbSimulation\", type=int, required=False,\n help=\"Number of simulation\", default=5)\n\nmonte_carlo_request_parser.add_argument(\"RebalancingFrequency\", type=str, required=False,\n help=\"RebalancingFrequency\")\n\nmonte_carlo_request_parser.add_argument(\"MultiPrecessorRun\", type=int, required=False,\n help=\"MultiPrecessorRun\")\n\nmonte_carlo_request_parser.add_argument(\"TargetAssetWeight\", type=dict, required=False,\n help=\"TargetAssetWeight\")\n\nmonte_carlo_request_parser.add_argument(\"RebalancyFrequency\", type=str, required=False,\n help=\"RebalancyFrequency\", default=\"monthly\")\n\nmonte_carlo_request_parser.add_argument(\"Contribution\", type=dict, required=False,\n help=\"Contribution\")\n\nmonte_carlo_request_parser.add_argument(\"Withdraw\", type=dict, required=False,\n help=\"withdraw\")\n\n\nclass StockPrice(Resource):\n\n def get(self):\n import datetime\n args = monte_carlo_request_parser.parse_args()\n\n start_date = (datetime.date.today() + datetime.timedelta(-3500))\n end_date = (datetime.date.today() + datetime.timedelta(1))\n invested_amount = args['InvestedAmount']\n rebalancing_frequency = args['RebalancyFrequency']\n nb_simul = args['NbSimulation']\n result = monte_carlo_portfolio_simul(\n initial_asset_codes_weight={\"BX4.PA\": 0.3, \"CAC.PA\": 0.4, \"500.PA\": 0.2, \"AIR.PA\": 0.1},\n start_date=start_date,\n invested_amount=invested_amount,\n end_date=end_date,\n nb_simul=nb_simul,\n target_asset_codes_weight={\"BX4.PA\": 0.3, \"CAC.PA\": 0.4, \"500.PA\": 0.2, \"AIR.PA\": 0.1},\n contribution={'amount': 100, 'freq': 'monthly'},\n withdraw={'amount': 100, 'freq': 'yearly'},\n multi_process=True,\n rebalancing_frequency=rebalancing_frequency,\n ret='json'\n )\n return result, 200","sub_path":"api/StockPrice.py","file_name":"StockPrice.py","file_ext":"py","file_size_in_byte":2956,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"465511172","text":"# -*- coding:utf-8 -*-\nimport urllib3\nimport json\n\nimport sys\n# reload(sys)\n# sys.setdefaultencoding('utf8')\n\n# url = 'https://itunes.apple.com/rss/customerreviews/id=529092160/json'\n\nfor page in range(1,1000):\n url = 'https://itunes.apple.com/rss/customerreviews/page=' + str(page) + '/id=957323480/sortby=mostrecent/json?l=en&&cc=cn'\n\n response = urllib3.urlopen(url)\n\n html = response.read()\n\n json_html = json.loads(html)\n\n json_list = json_html['feed']['entry']\n res_str = ''\n for line in json_list:\n res_str = res_str + line['title']['label'] + \"\\n\"\n\n print(res_str)\n\n with open('/Users/saicao/Desktop/file1.txt', 'a+') as f:\n f.write(res_str)","sub_path":"web/spider/app_store_spider.py","file_name":"app_store_spider.py","file_ext":"py","file_size_in_byte":690,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"199630888","text":"import cnfg\nimport level_zero\nimport pygame\nimport sys\n\n\ndef start_screen_interface():\n\tpygame.init()\n\tworld = pygame.display.set_mode(cnfg.SCREENSIZE)\n\tpygame.display.set_caption('Hard_game_ever 1.0')\n\tworld.fill(cnfg.BACKGROUND_START_SCREEN)\n\ttitle_font = pygame.font.Font(cnfg.TITLE_FONT_PATH, cnfg.SCREENSIZE[0] // 10)\n\tcontent_font = pygame.font.Font(cnfg.CONTENT_FONT_PATH, cnfg.SCREENSIZE[0] // 20)\n\ttitle = title_font.render('You and Me', True, cnfg.TITLE_FONT_COLOR)\n\tcontent = content_font.render('my version', True, cnfg.CONTENT_FONT_COLOR)\n\tinstruction = content_font.render('''press \"s\" to start''', True, (20, 20, 20))\n\tinstruction_1 = content_font.render('''press \"q\" to quit once started''', True, (20, 20, 20))\n\ttitle_rect = title.get_rect()\n\ttitle_rect.midtop = (cnfg.SCREENSIZE[0] // 2, cnfg.SCREENSIZE[1] // 3)\n\tcontent_rect = content.get_rect()\n\tcontent_rect.midtop = (cnfg.SCREENSIZE[0] // 2, cnfg.SCREENSIZE[1] // 2)\n\tinstruction_rect = instruction.get_rect()\n\tinstruction_rect.midtop = (cnfg.SCREENSIZE[0] // 2, cnfg.SCREENSIZE[1] - 100)\n\tinstruction_1_rect = instruction_1.get_rect()\n\tinstruction_1_rect.midtop = (cnfg.SCREENSIZE[0] // 2, cnfg.SCREENSIZE[1] - 60)\n\tworld.blit(title, title_rect)\n\tworld.blit(content, content_rect)\n\tworld.blit(instruction, instruction_rect)\n\tworld.blit(instruction_1, instruction_1_rect)\n\twhile True:\n\t\tkey = pygame.key.get_pressed()\n\t\tfor event in pygame.event.get():\n\t\t\tif event.type == pygame.QUIT:\n\t\t\t\tpygame.quit()\n\t\t\t\tsys.exit()\n\t\t\tif key[pygame.K_s]:\n\t\t\t\tlevel_zero.main_game_loop(world)\n\t\tpygame.display.update()\n\n\nif __name__ == '__main__':\n\tstart_screen_interface()\n","sub_path":"you&me/Game_start.py","file_name":"Game_start.py","file_ext":"py","file_size_in_byte":1633,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"419213315","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.7 (62211)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build/bdist.macosx-10.11-x86_64/egg/djblets/siteconfig/management/commands/get-siteconfig.py\n# Compiled at: 2019-06-12 01:17:17\nfrom __future__ import unicode_literals\nfrom django.core.management.base import CommandError\nfrom django.utils.translation import ugettext as _\nfrom djblets.siteconfig.models import SiteConfiguration\nfrom djblets.util.compat.django.core.management.base import BaseCommand\n\nclass Command(BaseCommand):\n \"\"\"Displays a setting in the site configuration.\"\"\"\n\n def add_arguments(self, parser):\n \"\"\"Add arguments to the command.\n\n Args:\n parser (object):\n The argument parser to add to.\n \"\"\"\n parser.add_argument(b'--key', action=b'store', dest=b'key', help=_(b'The existing key to display (dot-separated)'))\n\n def handle(self, *args, **options):\n siteconfig = SiteConfiguration.objects.get_current()\n key = options[b'key']\n if key is None:\n raise CommandError(_(b'--key must be provided'))\n path = key.split(b'.')\n node = siteconfig.settings\n valid_key = True\n for item in path[:-1]:\n try:\n node = node[item]\n except KeyError:\n valid_key = False\n\n if valid_key:\n key_basename = path[(-1)]\n if key_basename not in node:\n valid_key = False\n if not valid_key:\n raise CommandError(_(b\"'%s' is not a valid settings key\") % key)\n value = node[key_basename]\n if value is None:\n value = b'null'\n elif isinstance(value, bool):\n if value:\n value = b'true'\n else:\n value = b'false'\n self.stdout.write(b'%s' % value)\n return","sub_path":"pycfiles/Djblets-1.0.12-py2.7/get-siteconfig.py","file_name":"get-siteconfig.py","file_ext":"py","file_size_in_byte":1929,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"113231159","text":"import os\nimport platform\nimport sublime\n\nif int(sublime.version()) >= 3000:\n from . import ack\n from . import base\n from . import grep\n from . import git_grep\n from . import the_silver_searcher\n from . import find_str\n\n\ndef can_exec(fpath):\n return os.path.isfile(fpath) and os.access(fpath, os.X_OK)\n\n\ndef which(cmd):\n for base in os.getenv('PATH', '').split(os.pathsep):\n path = os.path.join(base, cmd)\n if can_exec(path):\n return path\n\n return None\n\n\nclass fastest:\n @classmethod\n def engine_class(cls, *args, **kwargs):\n if platform.system() == 'Windows':\n best = find_str.engine_class(*args, **kwargs)\n else:\n best = grep.engine_class(*args, **kwargs)\n\n for other in (grep, git_grep, ack, the_silver_searcher):\n c = other.engine_class(*args, **kwargs)\n if which(c.path_to_executable):\n best = c\n\n print('best was:', best)\n return best\n\n\n# __all__ = [\"base\", \"grep\", \"ack\", \"the_silver_searcher\", \"git_grep\"]\n","sub_path":"searchengines/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1066,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"24961543","text":"from bs4 import BeautifulSoup\nimport requests\nimport pandas as pd\nimport numpy as np\n\nimport lib.Climate_Common as Climate_Common\nfrom lib.csv import csv_process\n\nclass Hourly_Climate_Crawler:\n\tdef __init__(self, climate_station):\n\t\tself.climate_station = climate_station\n\t\tself.reserved_columns = ['Temperature', 'Humidity', 'SunShine_hr', 'SunShine_MJ']\n\n\tdef get_station_climate_data(self, station_id, periods):\n\t\tstation_area = self.climate_station.get_station_area(station_id)\n\t\tclimate_df = pd.DataFrame()\n\t\trecord_start_period = None\n\t\trecord_end_period = None\n\t\tnumber_of_crawls = 0\n\n\t\tfor period in periods:\n\t\t\thourly_climate_url = self.climate_station.get_hourly_full_url(period, station_id)\n\t\t\ttemp_df = self.catch_climate_data(hourly_climate_url)\n\n\t\t\t# 如果沒有任何資料就不儲存\n\t\t\tif temp_df is None:\n\t\t\t\tbreak\n\n\t\t\ttemp_df = self.data_preprocess(temp_df, period, station_area)\n\n\t\t\t# 記錄爬蟲 log (最後一筆的 Reporttime)\n\t\t\tif self.is_twenty_three_oclock(temp_df):\n\t\t\t\tif number_of_crawls == 0:\n\t\t\t\t\trecord_start_period = period\n\n\t\t\t\tnumber_of_crawls += 1\n\t\t\t\trecord_end_period = period\n\t\t\telse:\n\t\t\t\tbreak\n\n\t\t\tclimate_df = pd.concat([climate_df, temp_df], ignore_index=True)\n\n\t\tfile_name = 'hourly_climate/data_{}.csv'.format(station_id)\n\t\tif climate_df.empty:\n\t\t\tcsv_process.delete_csv(file_name)\n\t\t\trecord_start_period = None\n\t\t\trecord_end_period = None\n\t\telse:\n\t\t\tcsv_process.to_csv(climate_df, file_name)\n\t\treturn record_start_period, record_end_period\n\n\tdef data_preprocess(self, df, period, station_area):\n\t\tdf['Reporttime'] = period + ' ' + df['Hour'] + ':00'\n\t\tdf['Area'] = station_area\n\t\tdf['UUID'] = period + '_' + df['Hour'] + '_' + df['Area']\n\n\t\t# 將欄位重新排序成 DB 的欄位順序\n\t\tnew_index = ['UUID', 'Area'] + self.reserved_columns + ['Reporttime']\n\t\tdf = df.drop(['Hour'], axis=1)\\\n\t\t\t .reindex(new_index, axis=1)\n\t\treturn df\n\n\t# 是否有 23:00 這筆資料\n\tdef is_twenty_three_oclock(self, df):\n\t\trecord_period = df.iloc[-1]['Reporttime']\n\t\treturn record_period.endswith('23:00')\n\n\tdef catch_climate_data(self, url):\n\t\treq = requests.get(url)\n\t\tsoup = BeautifulSoup(req.text, 'lxml')\n\n\t\tdata_info = soup.find(class_='imp').text\n\t\tif data_info == '本段時間區間內無觀測資料。':\n\t\t\treturn None\n\t\telse:\n\t\t\t# 保留欄位德 index\n\t\t\treserved_columns_index = [0, 3, 5, 12, 13]\n\t\t\t# return: {0: 'Day', 3: 'Temperature', 5: 'Humidity', ... }\n\t\t\trename_columns = dict(zip(reserved_columns_index, ['Hour'] + self.reserved_columns))\n\n\t\t\t# iloc[3:, reserved_columns_index] 中的 '3:' 是刪除前 3 列 (index: 0 ~ 2)\n\t\t\t# 將資料內的 '/' 和 'X' 設為 NA\n\t\t\t# 只要 subset 這些欄位全部都 NA 才 drop\n\t\t\tclimate_table = soup.find(id='MyTable')\n\t\t\tclimate_df = pd.read_html(str(climate_table))[0]\\\n\t\t\t\t\t\t .iloc[3:, reserved_columns_index]\\\n\t\t\t\t\t\t .rename(columns=rename_columns)\\\n\t\t\t\t\t\t .replace('/', np.nan)\\\n\t\t\t\t\t\t\t .replace('X', np.nan) \\\n\t\t\t\t\t\t\t .replace('...', np.nan)\\\n\t\t\t\t\t\t .dropna(subset=self.reserved_columns, how='all')\n\n\t\t\tif climate_df.empty:\n\t\t\t\treturn None\n\n\t\t\t# 將 Hour 欄位原本的 1 ~ 24 改成 '00' ~ '23'\n\t\t\tclimate_df['Hour'] = list(map(lambda hour: str(hour).zfill(2), range(0, 24)))\n\t\t\treturn climate_df","sub_path":"lib/Hourly_Climate_Crawler.py","file_name":"Hourly_Climate_Crawler.py","file_ext":"py","file_size_in_byte":3218,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"313368454","text":"def sum_n_multiples(a, d, n):\n # sum up n times counting a even if 0\n # right shift by 1 instead of dividing by 2 because\n # python will approximate the division\n return int((n * (2 * a + (n - 1) * d))) >> 1\n\ndef sum_35_multiples(N):\n # d + 2d + ... + kd for k = (n - (n % d)) / d\n # k/2 * (k - 1) * d\n N -= 1\n k3 = int((N - (N % 3)) / 3) + 1 # +1 to count 0\n k5 = int((N - (N % 5)) / 5) + 1 # +1 to count 0\n k15 = int((N - (N % 15)) / 15) + 1 # +1 to count 0\n return sum_n_multiples(0, 3, k3) + sum_n_multiples(0, 5, k5) - sum_n_multiples(0, 15, k15)\n\nt = int(input().strip())\nns = list()\nfor a0 in range(t):\n ns.append(int(input().strip()))\n\nfor n in ns:\n print(sum_35_multiples(n))\n","sub_path":"hackerrank/python3/euler1_fast.py","file_name":"euler1_fast.py","file_ext":"py","file_size_in_byte":724,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"100559637","text":"import json\nimport os\nimport re\nfrom requests import get, post\nfrom operator import itemgetter\nfrom urlparse import urlparse\n\nfrom datetime import datetime\nfrom base64 import b64encode\n\nfrom flask import Flask, render_template, request, redirect, url_for, make_response, flash\nimport filters\n\napp = Flask(__name__, static_url_path=\"/brigade/static\")\napp.register_blueprint(filters.blueprint)\n\napp.config['BRIGADE_SIGNUP_SECRET'] = os.environ['BRIGADE_SIGNUP_SECRET']\napp.secret_key = 'SECRET KEY'\n\n@app.context_processor\ndef get_fragments():\n ''' The base template includes the signup form and the footer\n pulled from our main site.\n '''\n # Get universal sign up form\n r = get(\"http://www.codeforamerica.org/fragments/email-signup.html\")\n signup = r.content\n\n # Get footer html\n r = get(\"http://www.codeforamerica.org/fragments/global-footer.html\")\n footer = r.content\n return dict(signup=signup, footer=footer)\n\ndef get_brigades():\n # Get location of all civic tech orgs\n got = get(\"https://www.codeforamerica.org/api/organizations.geojson\")\n geojson = got.json()\n brigades = []\n\n # Prepare the geojson for a map\n for org in geojson[\"features\"]:\n # Add icon info for the map\n org[\"properties\"][\"marker-symbol\"] = \"town-hall\"\n # Official Brigades get to be red\n if \"Official\" in org[\"properties\"][\"type\"]:\n org[\"properties\"][\"marker-color\"] = \"#aa1c3a\"\n else:\n # Other Brigades are grey\n org[\"properties\"][\"marker-color\"] = \"#6D6E71\"\n # Grab only orgs with type Brigade\n if \"Brigade\" in org[\"properties\"][\"type\"]:\n brigades.append(org)\n\n brigades = json.dumps(brigades)\n return brigades\n\n\ndef is_existing_organization(orgid):\n ''' tests that an organization exists on the cfapi'''\n got = get(\"https://www.codeforamerica.org/api/organizations.geojson\").json()\n orgids = [org[\"properties\"][\"id\"] for org in got[\"features\"]]\n return orgid in orgids\n\n\n# Load load projects from the cfapi\ndef get_projects(projects, url, limit=10):\n got = get(url)\n new_projects = got.json()[\"objects\"]\n projects = projects + new_projects\n if limit:\n if len(projects) >= limit:\n return projects\n if \"next\" in got.json()[\"pages\"]:\n projects = get_projects(projects, got.json()[\"pages\"][\"next\"], limit)\n return projects\n\n\n# ROUTES\n@app.route('/brigade/list', methods=[\"GET\"])\ndef brigade_list():\n brigades = get_brigades()\n brigades = json.loads(brigades)\n brigades.sort(key=lambda x: x['properties']['city'])\n return render_template(\"brigade_list.html\", brigades=brigades )\n\n\n@app.route('/brigade/')\ndef index():\n brigades = get_brigades()\n return render_template(\"index.html\", brigades=brigades )\n\n\n@app.route(\"/brigade/signup/\", methods=[\"POST\"])\ndef signup():\n ''' Takes in signup requests from /brigade/signup/form\n Sends the data to a requested mailchimp list, our mailchimp list, and the peopledb\n '''\n\n # Prep mailchimp data\n # mailchimp_data = {\n # 'FNAME' : request.form.get(\"FNAME\"),\n # 'LNAME' : request.form.get(\"LNAME\"),\n # 'EMAIL' : request.form.get(\"EMAIL\")\n # }\n\n # Optionally POST to Brigade's mailchimp\n # mailchimp_url = request.form.get(\"mailchimp_url\", None)\n # brigade_mailchimp_response = None\n # if mailchimp_url:\n # brigade_mailchimp_response = post(mailchimp_url, data=mailchimp_data)\n\n # Always POST to Code for America's mailchimp\n # mailchimp_data['group[10273][8192]'] = '8192' # I attend Brigade events\n\n # cfa_mailchimp_url = \"http://codeforamerica.us2.list-manage.com/subscribe/post-json?u=d9acf2a4c694efbd76a48936f&id=3ac3aef1a5\"\n # cfa_mailchimp_response = post(cfa_mailchimp_url, data=mailchimp_data)\n\n # Always POST to PeopleDB\n peopledb_data = {\n 'first_name' : request.form.get(\"FNAME\"),\n 'last_name' : request.form.get(\"LNAME\"),\n 'email' : request.form.get(\"EMAIL\"),\n 'brigade_id' : request.form.get(\"brigade_id\", None)\n }\n \n auth = app.config['BRIGADE_SIGNUP_SECRET'], 'x-brigade-signup'\n url = 'https://people.codeforamerica.org/brigade/signup'\n\n peopledb_response = post(url, data=peopledb_data, auth=auth)\n\n # Choose a response to show\n # if brigade_mailchimp_response:\n # return brigade_mailchimp_response\n\n # elif cfa_mailchimp_response:\n # return cfa_mailchimp_response.content\n\n if peopledb_response:\n response = {\n \"status_code\" : peopledb_response.status_code,\n \"msg\" : peopledb_response.content\n }\n return json.dumps(response)\n\n else:\n response = {\n \"status_code\" : 500,\n \"msg\" : \"Something went wrong. You were not added to any lists.\"\n }\n return response\n\n\n@app.route(\"/brigade/signup/\", methods=[\"GET\"])\ndef signup_form():\n # Get all of the organizations from the api\n organizations = get('https://www.codeforamerica.org/api/organizations.geojson')\n organizations = organizations.json()\n\n # Filter out just the organization names\n brigades = []\n for org in organizations['features']:\n brigades.append(org['properties']['name'])\n\n # Alphabetize names\n brigades.sort()\n\n return render_template(\"signup.html\", brigades=brigades)\n\n\n@app.route(\"/brigade/numbers/\")\ndef numbers():\n # Get the total number of Brigades\n got = get(\"https://www.codeforamerica.org/api/organizations?type=Brigade&per_page=1\")\n got = got.json()\n brigades_total = got['total']\n\n # Get the official Brigades\n got = get(\"https://www.codeforamerica.org/api/organizations?type=Official&per_page=1\")\n got = got.json()\n official_brigades_total = got['total']\n\n # Get the total number of Code for All Groups\n got = get(\"https://www.codeforamerica.org/api/organizations?type=Code for All&per_page=1\")\n got = got.json()\n cfall_total = got['total']\n\n # Get the total number of Government Groups\n got = get(\"https://www.codeforamerica.org/api/organizations?type=Government&per_page=1\")\n got = got.json()\n government_total = got['total']\n\n # Get number of meetup-members\n got = get(\"http://codeforamerica.org/api/organizations/member_count\")\n got = got.json()\n member_count = got['total']\n\n # Get number of RSVPs\n got = get(\"https://www.codeforamerica.org/api/events/rsvps\")\n got = got.json()\n rsvps = got['total']\n\n # Get number of Attendance\n got = get(\"https://www.codeforamerica.org/api/attendance\")\n got = got.json()\n attendance = got['total']\n\n # Get total number of projects\n got = get(\"https://www.codeforamerica.org/api/projects?only_ids&per_page=1\")\n got = got.json()\n projects = got['objects']\n projects_total = got['total']\n\n # Get total number of Brigade projects\n got = get(\"https://www.codeforamerica.org/api/projects?only_ids&organization_type=Brigade&per_page=1\")\n got = got.json()\n projects = got['objects']\n brigade_projects_total = got['total']\n\n # Get total number of Code for All projects\n got = get(\"https://www.codeforamerica.org/api/projects?only_ids&organization_type=Code for All&per_page=1\")\n got = got.json()\n projects = got['objects']\n cfall_projects_total = got['total']\n\n # Get total number of Government projects\n got = get(\"https://www.codeforamerica.org/api/projects?only_ids&organization_type=Government&per_page=1\")\n got = got.json()\n projects = got['objects']\n gov_projects_total = got['total']\n\n # Get number of Issues\n got = get(\"https://www.codeforamerica.org/api/issues?per_page=1\")\n got = got.json()\n issues_total = got['total']\n\n # Get number of Help Wanted Issues\n got = get(\"https://www.codeforamerica.org/api/issues/labels/help%20wanted?per_page=1\")\n got = got.json()\n help_wanted_total = got['total']\n\n # Get number of civic issue finder clicks\n got = get(\"https://www.codeforamerica.org/geeks/civicissues/analytics/total_clicks\")\n got = got.json()\n total_issue_clicks = got['total_clicks']\n\n\n kwargs = dict(brigades_total=brigades_total, official_brigades_total=official_brigades_total,\n cfall_total=cfall_total, government_total=government_total,\n member_count=member_count, rsvps=rsvps, attendance=attendance,\n projects_total=projects_total, brigade_projects_total=brigade_projects_total,\n cfall_projects_total=cfall_projects_total, gov_projects_total=gov_projects_total,\n issues_total=issues_total, help_wanted_total=help_wanted_total, total_issue_clicks=total_issue_clicks)\n\n return render_template(\"numbers.html\", **kwargs )\n\n\n@app.route(\"/brigade/about/\")\ndef about():\n return render_template(\"about.html\")\n\n\n@app.route(\"/brigade/organize/\")\ndef organize():\n\n got = get(\"http://www.codeforamerica.org/api/organizations.geojson\")\n geojson = got.json()\n brigades = []\n\n # Prepare the geojson for a map\n for org in geojson[\"features\"]:\n # Grab only orgs with type Brigade\n if \"Brigade\" in org[\"properties\"][\"type\"]:\n brigades.append(org)\n elif \"Code for All\" in org[\"properties\"][\"type\"]:\n brigades.append(org)\n\n brigades = json.dumps(brigades)\n\n # Get universal sign up form\n r = get(\"http://www.codeforamerica.org/fragments/email-signup.html\")\n signup = r.content\n\n return render_template(\"organize.html\", brigades=brigades, signup=signup)\n\n\n\n@app.route(\"/brigade/tools/\")\n@app.route(\"/brigade/tools//\")\ndef tools(page=None):\n if page:\n return render_template(\"tools/\"+page+\".html\")\n else:\n return render_template(\"tools/index.html\")\n\n\n@app.route(\"/brigade/infrastructure\")\ndef infrastructure():\n return render_template(\"infrastructure.html\")\n\n\n@app.route(\"/brigade/projects\")\n@app.route(\"/brigade//projects\")\ndef projects(brigadeid=None):\n ''' Display a list of projects '''\n\n if brigadeid:\n if not is_existing_organization(brigadeid):\n return render_template('404.html'), 404\n\n projects = []\n brigade = None\n search = request.args.get(\"q\", None)\n sort_by = request.args.get(\"sort_by\", None)\n page = request.args.get(\"page\", None)\n\n if page:\n if brigadeid:\n next = \"/brigade/\"+brigadeid+\"/projects?page=\" + str(int(page) + 1)\n else:\n next = \"/brigade/projects?page=\" + str(int(page) + 1)\n else:\n if brigadeid:\n next = \"/brigade/\"+brigadeid+\"/projects?page=2\"\n else:\n next = \"/brigade/projects?page=2\"\n\n if brigadeid:\n url = \"https://www.codeforamerica.org/api/organizations/\"+ brigadeid +\"/projects\"\n if search or sort_by or page:\n url += \"?\"\n if search:\n url += \"&q=\" + search\n if sort_by:\n url += \"&sort_by\" + sort_by\n if page:\n url += \"&page=\" + page\n got = get(url)\n projects = get_projects(projects, url)\n if projects:\n brigade = projects[0][\"organization\"]\n else:\n brigade = { \"name\" : brigadeid.replace(\"-\",\" \")}\n\n else:\n url = \"https://www.codeforamerica.org/api/projects\"\n if search or sort_by or page:\n url += \"?\"\n if search:\n url += \"&q=\" + search\n if sort_by:\n url += \"&sort_by\" + sort_by\n if page:\n url += \"&page=\" + page\n got = get(url)\n projects = get_projects(projects, url)\n\n return render_template(\"projects.html\", projects=projects, brigade=brigade, next=next)\n\n\n@app.route(\"/brigade/attendance\")\n@app.route(\"/brigade//attendance\")\ndef attendance(brigadeid=None):\n ''' Show the Brigade attendance '''\n\n if brigadeid:\n if not is_existing_organization(brigadeid):\n return render_template('404.html'), 404\n\n if not brigadeid:\n got = get(\"https://www.codeforamerica.org/api/attendance\")\n else:\n got = get(\"https://www.codeforamerica.org/api/organizations/%s/attendance\" % brigadeid)\n\n attendance = got.json()\n\n if attendance[\"weekly\"]:\n\n # GCharts wants a list of lists\n attendance[\"weeks\"] = []\n for key, value in attendance[\"weekly\"].iteritems():\n week = [str(key), value]\n attendance[\"weeks\"].append(week)\n attendance[\"weeks\"] = sorted(attendance[\"weeks\"], key=itemgetter(0))\n\n attendance[\"this_week\"] = 0\n attendance[\"last_week\"] = 0\n if len(attendance[\"weeks\"]) >= 1:\n attendance[\"this_week\"] = attendance[\"weeks\"][-1][1]\n if len(attendance[\"weeks\"]) >= 2:\n attendance[\"last_week\"] = attendance[\"weeks\"][-2][1]\n\n return render_template(\"attendance.html\", brigadeid=brigadeid, attendance=attendance)\n\n\n@app.route(\"/brigade/rsvps\")\n@app.route(\"/brigade//rsvps\")\ndef rsvps(brigadeid=None):\n ''' Show the Brigade rsvps '''\n\n if brigadeid:\n if not is_existing_organization(brigadeid):\n return render_template('404.html'), 404\n\n if not brigadeid:\n got = get(\"https://www.codeforamerica.org/api/events/rsvps\")\n else:\n got = get(\"https://www.codeforamerica.org/api/organizations/%s/events/rsvps\" % brigadeid)\n\n rsvps = got.json()\n\n if rsvps[\"weekly\"]:\n\n # GCharts wants a list of lists\n rsvps[\"weeks\"] = []\n for key, value in rsvps[\"weekly\"].iteritems():\n week = [str(key), value]\n rsvps[\"weeks\"].append(week)\n rsvps[\"weeks\"] = sorted(rsvps[\"weeks\"], key=itemgetter(0))\n\n rsvps[\"this_week\"] = 0\n rsvps[\"last_week\"] = 0\n if len(rsvps[\"weeks\"]) >= 1:\n rsvps[\"this_week\"] = rsvps[\"weeks\"][-1][1]\n if len(rsvps[\"weeks\"]) >= 2:\n rsvps[\"last_week\"] = rsvps[\"weeks\"][-2][1]\n\n return render_template(\"rsvps.html\", brigadeid=brigadeid, rsvps=rsvps)\n\n\n@app.route('/brigade/index//')\ndef redirect_brigade(brigadeid):\n ''' Redirect old Brigade links to new Brigade links'''\n return redirect(\"/brigade/\"+brigadeid, code=301)\n\n@app.route('/brigade//')\ndef brigade(brigadeid):\n ''' Get this Brigade's info '''\n\n if brigadeid:\n if not is_existing_organization(brigadeid):\n return render_template('404.html'), 404\n\n got = get(\"https://www.codeforamerica.org/api/organizations/\" + brigadeid)\n brigade = got.json()\n\n return render_template(\"brigade.html\", brigade=brigade, brigadeid=brigadeid)\n\n\n@app.route(\"/brigade/checkin/\", methods=[\"GET\"])\n@app.route(\"/brigade//checkin/\", methods=[\"GET\"])\ndef get_checkin(brigadeid=None):\n ''' Checkin to a Brigade event '''\n\n if brigadeid:\n if not is_existing_organization(brigadeid):\n return render_template('404.html'), 404\n\n brigades = None\n if not brigadeid:\n # Get all of the organizations from the api\n organizations = get('https://www.codeforamerica.org/api/organizations.geojson')\n organizations = organizations.json()\n brigades = []\n # Org's names and ids\n for org in organizations['features']:\n if \"Brigade\" in org['properties']['type']:\n brigades.append({\n \"name\": org['properties']['name'],\n \"id\": org['id']\n })\n\n # Alphabetize names\n brigades.sort(key=lambda x: x.values()[0])\n\n # If we want to remember the event, question\n event = request.args.get(\"event\", None)\n question = request.args.get(\"question\", None)\n\n return render_template(\"checkin.html\", brigadeid=brigadeid,\n event=event, brigades=brigades, question=question)\n\n\n@app.route(\"/brigade/checkin/\", methods=[\"POST\"])\n@app.route(\"/brigade//checkin/\", methods=[\"POST\"])\ndef post_checkin(brigadeid=None):\n ''' Prep the checkin for posting to the peopledb '''\n\n # VALIDATE\n cfapi_url = request.form.get('cfapi_url')\n if not cfapi_url:\n return make_response(\"Missing required cfapi_url\", 422)\n\n elif not re.match(\"https:\\/\\/www\\.codeforamerica\\.org\\/api\\/organizations\\/[A-Za-z-]*\", cfapi_url):\n return make_response(\"cfapi_url needs to like https://www.codeforamerica.org/api/organizations/Brigade-ID\", 422)\n\n brigadeid = request.form.get('cfapi_url').split(\"/\")[-1]\n if not is_existing_organization(brigadeid):\n return make_response(brigadeid + \"is not an existing brigade.\" , 422)\n\n # MAILCHIMP SIGNUP\n if request.form.get(\"mailinglist\", None):\n if request.form.get(\"email\", None):\n\n # Split first and last name\n name = request.form.get('name', None)\n if name:\n if ' ' in request.form['name']:\n first_name, last_name = name.split(' ', 1)\n else:\n first_name, last_name = name, ''\n else:\n first_name, last_name = None, None\n\n mailchimp_data = {\n 'FNAME' : first_name,\n 'LNAME' : last_name,\n 'EMAIL' : request.form.get(\"email\"),\n 'REFERRAL' : request.url,\n 'group[10273][8192]' : '8192', # I attend Brigade events\n 'group[10245][32]' : '32' # Brigade newsletter\n }\n\n cfa_mailchimp_url = \"http://codeforamerica.us2.list-manage.com/subscribe/post-json?u=d9acf2a4c694efbd76a48936f&id=3ac3aef1a5\"\n cfa_mailchimp_response = post(cfa_mailchimp_url, data=mailchimp_data)\n\n if cfa_mailchimp_response.status_code != 200:\n return cfa_mailchimp_response.content\n\n # Prep PeopleDB post\n # Q&A is stored as a json string\n extras = {}\n extras[\"question\"] = request.form.get(\"question\", None)\n extras[\"answer\"] = request.form.get(\"answer\", None)\n extras = json.dumps(extras)\n\n peopledb_post = {\n \"name\": request.form.get('name', None),\n \"email\": request.form.get(\"email\", None),\n \"event\": request.form.get(\"event\", None),\n \"date\": request.form.get(\"date\", datetime.now()),\n \"org_cfapi_url\": request.form.get('cfapi_url'),\n \"extras\" : extras\n }\n\n auth = app.config[\"BRIGADE_SIGNUP_SECRET\"] + ':x-brigade-signup'\n headers = {'Authorization': 'Basic ' + b64encode(auth)}\n peopleapp = \"https://people.codeforamerica.org/checkin\"\n\n r = post(peopleapp, data=peopledb_post, headers=headers)\n\n if r.status_code == 200:\n # Remembering event name and brigadeid for later\n event = request.form.get(\"event\", None)\n question = request.form.get(\"question\", None)\n brigadeid = request.form.get(\"cfapi_url\").replace(\"https://www.codeforamerica.org/api/organizations/\",\"\")\n flash(\"Thanks for volunteering\")\n\n if brigadeid:\n url = \"brigade/\"+ brigadeid +\"/checkin/\"\n else:\n url = \"brigade/checkin/\"\n\n if event or question:\n url += \"?\"\n if event:\n event = event.replace(\" \",\"+\")\n url += \"event=\" + event\n if event and question:\n url += \"&\"\n if question:\n question = question.replace(\" \",\"+\")\n url += \"question=\" + question\n\n return redirect(url)\n\n # Pass any errors through\n else:\n return make_response(r.content, r.status_code)\n\n\n@app.route(\"/brigade/test-checkin/\", methods=[\"POST\"])\n@app.route(\"/brigade//test-checkin/\", methods=[\"POST\"])\ndef post_test_checkin(brigadeid=None):\n ''' Prep the checkin for posting to the peopledb '''\n\n test_checkin_data = {\n \"name\": request.form.get('name', None),\n \"email\": request.form.get(\"email\", None),\n \"event\": request.form.get(\"event\", None),\n \"date\": request.form.get(\"date\", str(datetime.now())),\n \"cfapi_url\": request.form.get('cfapi_url'),\n \"question\" : request.form.get(\"question\", None),\n \"answer\" : request.form.get(\"answer\", None)\n }\n\n if not test_checkin_data[\"cfapi_url\"]:\n return make_response(\"Missing required cfapi_url\", 422)\n\n elif not re.match(\"https:\\/\\/www\\.codeforamerica\\.org\\/api\\/organizations\\/[A-Za-z-]*\", test_checkin_data[\"cfapi_url\"]):\n return make_response(\"cfapi_url needs to like https://www.codeforamerica.org/api/organizations/Brigade-ID\", 422) \n\n\n brigadeid = test_checkin_data[\"cfapi_url\"].split(\"/\")[-1]\n if not is_existing_organization(brigadeid):\n return make_response(brigadeid + \"is not an existing brigade.\" , 422)\n\n else:\n return make_response(json.dumps(test_checkin_data), 200)\n\n\n@app.route('/brigade/projects/monitor')\n@app.route('/brigade//projects/monitor')\ndef project_monitor(brigadeid=None):\n ''' Check for Brigade projects on Travis'''\n limit = int(request.args.get('limit',50))\n travis_projects = []\n projects = []\n if not brigadeid:\n projects = get_projects(projects, \"https://www.codeforamerica.org/api/projects\", limit)\n else:\n projects = get_projects(projects, \"https://www.codeforamerica.org/api/organizations/\"+brigadeid+\"/projects\", limit)\n\n # Loop through projects and get\n for project in projects:\n if project[\"code_url\"]:\n url = urlparse(project[\"code_url\"])\n if url.netloc == \"github.com\":\n travis_url = \"https://api.travis-ci.org/repositories\"+url.path+\"/builds\"\n project[\"travis_url\"] = travis_url\n travis_projects.append(project)\n\n return render_template('projectmonitor.html', projects=travis_projects, org_name=brigadeid)\n\n\nif __name__ == '__main__':\n app.run(host='0.0.0.0',debug=True, port=4000)\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":21767,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"437304332","text":"import sys\n\ndef fizz(x, y, n):\n result = \"\"\n num = 1\n while num <= n:\n if num % x == 0 and num % y == 0:\n result += \"FB \"\n num += 1\n elif num % x == 0:\n result += \"F \"\n num += 1\n elif num % y == 0:\n result += \"B \"\n num += 1\n else:\n result += str(num) + \" \"\n num += 1\n else:\n return result\n\n\ntest_cases = open(sys.argv[1], 'r')\n\nfor test in test_cases:\n test = test.strip(\"\\n\")\n test = test.split()\n first = int(test[0])\n second = int(test[1])\n third = int(test[2])\n \n print(fizz(first, second, third))\n\ntest_cases.close()\n\n","sub_path":"codeeval/fizzbuzz.py3","file_name":"fizzbuzz.py3","file_ext":"py3","file_size_in_byte":679,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"219706681","text":"import pygame\n\n## Colors ##\nwhite = (255,255,255)\nblack = (0,0,0)\ngrey = (195,195,195)\npink = (255,105,180)\nred = (255,0,0)\n\n## Window Size ##\nwin_width = 1000\nwin_height = 700\n\n## Fonts ##\npygame.font.init()\ntitle_font = pygame.font.SysFont(\"Comic Sans MS\", 72)\nbutton_font = pygame.font.SysFont(\"Comic Sans MS\", 24)\ncounter_font = pygame.font.SysFont(\"Comic Sans MS\", 128)\n\n## Text (pygame.Surface) ##\ntitle_text = title_font.render(\"A Mini Game\", True, black)\ntitle_text_x = (win_width - title_text.get_width())/2\n\n## Game ##\ngravity = 400 # pixel per second\nrho = 0.3\nball_radius = 25\nSball_radius = 30 # Small ball radius for enemies\njump_v = 1200\njump_limit = 0.5 # second\nmove_speed = 200\nbounce_limit = jump_limit * 0.6\ndescend_speed = 600\nstarting_alert_time = 2\nstarting_spawn_rate = 5\nmax_health = 3\n","sub_path":"Constants.py","file_name":"Constants.py","file_ext":"py","file_size_in_byte":811,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"116317373","text":"from telegram import Update, InlineKeyboardMarkup, InlineKeyboardButton\nfrom telegram.ext import ContextTypes\n\n\nclass QueBot:\n def __init__(self, items, text, chosen_text):\n self.items = items\n self.text = text\n self.chosen_text = chosen_text\n self.current_list = []\n\n async def questionnaire(self, update, context):\n await self.clear(update, context)\n await update.message.reply_text(self.text, reply_markup=self.build_que())\n\n def build_que(self, current_list=None) -> InlineKeyboardMarkup:\n \"\"\"Helper function to build the next inline keyboard.\"\"\"\n if current_list is None:\n current_list = []\n\n items_diff = list(set(self.items).difference(set(current_list)))\n self.current_list = current_list\n return InlineKeyboardMarkup.from_column(\n [InlineKeyboardButton(i, callback_data=i) for i in items_diff]\n )\n\n async def clear(self, update, context):\n context.bot.callback_data_cache.clear_callback_data()\n context.bot.callback_data_cache.clear_callback_queries()\n\n async def clear_with_message(self, update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:\n \"\"\"Clears the callback data cache\"\"\"\n await self.clear(update, context)\n await update.effective_message.reply_text(\"All clear!\")\n\n async def list_button(self, update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:\n \"\"\"Parses the CallbackQuery and updates the message text.\"\"\"\n query = update.callback_query\n await query.answer()\n\n item = query.data\n item_list = self.current_list\n\n item_list.append(item)\n\n list_text = \", \".join(item_list)\n await query.edit_message_text(\n text=f\"{self.chosen_text}: {list_text}. Choose the next.\",\n reply_markup=self.build_que(item_list),\n )\n\n async def handle_invalid_button(self, update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:\n \"\"\"Informs the user that the button is no longer available.\"\"\"\n await update.callback_query.answer()\n await update.effective_message.edit_text(\n \"Sorry, I could not process this button click 😕 Please send /start to get a new keyboard.\"\n )\n","sub_path":"IMPORTANT/telegram_bots/telegram/example/que_teleg.py","file_name":"que_teleg.py","file_ext":"py","file_size_in_byte":2272,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"464916366","text":"import os\n\n# gpu_info = os.system('nvidia-smi')\n# print(gpu_info)\n\nimport pandas as pd\nimport numpy as np\nimport random\nimport cv2\n\nimport torch\nimport torch.nn as nn\nfrom torch.utils.data import DataLoader, Dataset\nimport torch.nn.functional as F\nfrom torch.cuda.amp import autocast, GradScaler\n\nimport timm\nfrom matplotlib import pyplot as plt\nfrom sklearn.model_selection import StratifiedKFold\n\nimport albumentations as A\nfrom albumentations.pytorch import ToTensorV2\nfrom tqdm import tqdm\n\nfrom utils.losses import BiTemperedLogisticLoss, TaylorCrossEntropyLoss\nimport pretrainedmodels\n\nimport argparse\n\n\ndef seed_everything(seed):\n random.seed(seed)\n os.environ['PYTHONHASHSEED'] = str(seed)\n np.random.seed(seed)\n torch.manual_seed(seed)\n torch.cuda.manual_seed(seed)\n torch.backends.cudnn.deterministic = False\n torch.backends.cudnn.benchmark = True\n\n\nclass Config:\n seed = 42\n data_dir = '/home/user/dataset/kaggle2020-leaf-disease-classification/'\n train_data_dir = data_dir + 'train_images/'\n train_csv_path = data_dir + 'train.csv'\n\n #data_dir = '/home/user/dataset/kaggle_cassava_merge/'\n #train_data_dir = data_dir + 'train/\n #train_csv_path = data_dir + 'merged.csv'\n #train_csv_path = data_dir + '2020.csv'\n #arch = 'vit_base_patch16_384' ## model name\n arch = 'efficientnet-b3'\n #arch = 'efficientnet-b4'\n #arch = 'efficientnet-b5'\n #arch = 'se_resnext50_32x4d_timm'\n device = 'cuda'\n debug = False ## clw modify\n\n #image_size = 384\n image_size = 512\n #train_batch_size = 16\n train_batch_size = 32\n val_batch_size = 32\n epochs = 12 ## total train epochs\n milestones = [7, 11]\n #freeze_bn_epochs = 5 ## freeze bn weights before epochs\n freeze_bn_epochs = 0 # clw modify\n\n #lr = 1e-4 ## init learning rate\n lr = 1e-1\n\n weight_decay = 1e-6\n num_workers = 4\n num_splits = 5 ## numbers splits\n num_classes = 5 ## numbers classes\n\n # min_lr = 1e-6 ## min learning rate\n T_0 = 10\n T_mult = 1\n #accum_iter = 2\n accum_iter = 1 # clw modify\n verbose_step = 1\n\n #criterion = 'LabelSmoothingCrossEntropy'\n criterion = 'Taylor'\n #criterion = 'bitempered'\n label_smoothing = 0.3\n\n train_id = [0, 1, 2, 3, 4]\n\n\ndef load_image(image_path):\n img = cv2.imread(image_path)\n img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n return img\n\nfrom utils.utils import rand_bbox_clw\nclass CassavaDataset(Dataset):\n def __init__(self, data_dir, df, transforms=None, output_label=True, mode=\"train\"):\n self.data_dir = data_dir\n self.df = df\n self.transforms = transforms\n self.output_label = output_label\n self.mode=mode\n self.Resize_Crop = A.Compose(\n [A.RandomResizedCrop(CFG.image_size, CFG.image_size, scale=(0.8, 1.0), ratio=(0.75, 1.333333))])\n\n def __len__(self):\n return len(self.df)\n\n def __getitem__(self, index):\n image_infos = self.df.iloc[index]\n image_path = self.data_dir + image_infos.image_id\n\n image = load_image(image_path)\n\n if image is None:\n raise FileNotFoundError(image_path)\n\n ##############\n label = image_infos.label\n\n label = torch.tensor(label).long()\n if self.mode == \"train\":\n # if random.random() < self.do_mixup_prob:\n # img, label = self.do_mixup(img, label, index)\n if random.random() < 0:\n img, label = self.do_cutmix(image, label, index)\n else:\n img = self.transforms(image=image)['image'] # clw note: 考虑到这里有crop等导致输入尺寸不同的操作,把resize放在后边\n label = torch.zeros(CFG.num_classes).scatter_(0, label, 1)\n elif self.mode == \"val\":\n img = self.transforms(image=image)['image']\n label = torch.zeros(CFG.num_classes).scatter_(0, label, 1)\n return img, label\n\n ### augment\n # if self.transforms is not None:\n # image = self.transforms(image=image)['image']\n # else:\n # image = torch.from_numpy(image)\n #\n # if self.output_label:\n # return image, image_infos.label\n # else:\n # return image\n\n def do_cutmix(self, img, label, index):\n '''\n Args:\n img: img to mixup\n label: label to mixup\n index: cutmix with other imgs in dataset, exclude itself( index )\n '''\n r_idx = random.choice(np.delete(np.arange(self.df.shape[0]), index))\n r_img_path = os.path.join(self.data_dir, self.df.iloc[r_idx, 0])\n r_img = cv2.imread(r_img_path)\n r_img = r_img[:, :, ::-1]\n\n img = self.Resize_Crop(image=img)['image']\n r_img = self.Resize_Crop(image=r_img)['image']\n ####\n img_h, img_w = r_img.shape[:2]\n\n lam = np.clip(np.random.beta(1, 1), 0.3, 0.4)\n ###lam = np.random.beta(1, 1)\n bbx1, bby1, bbx2, bby2 = rand_bbox_clw(img_w, img_h, lam)\n img_new = img.copy()\n img_new[bby1:bby2, bbx1:bbx2, :] = r_img[bby1:bby2, bbx1:bbx2, :]\n #cv2.imwrite(str(index) + '.jpg', img_new[:, :, ::-1])\n\n lam = 1 - ((bbx2 - bbx1) * (bby2 - bby1) / (img_h * img_w))\n label_one_hot = torch.zeros(CFG.num_classes).scatter_(0, label, 1)\n r_label = self.df.iloc[r_idx, 1]\n r_label = torch.tensor(r_label).long()\n r_label_one_hot = torch.zeros(CFG.num_classes).scatter_(0, r_label, 1)\n label_new = label_one_hot * lam + r_label_one_hot * (1 - lam)\n #img_new = train_aug(image=img_new)['image'] # clw note: 考虑到这里有crop等导致输入尺寸不同的操作,把resize放在后边\n img_new = train_aug_cutmix(image=img_new)['image'] # clw note: 考虑到这里有crop等导致输入尺寸不同的操作,把resize放在后边\n\n return img_new, label_new\n\nclass CassavaClassifier(nn.Module):\n def __init__(self, model_arch, num_classes, pretrained=False):\n super().__init__()\n\n ### vit\n ###self.model = timm.create_model(model_arch, pretrained=pretrained)\n #num_features = self.model.head.in_features\n #self.model.head = nn.Linear(num_features, num_classes)\n\n ### efficientnet\n if \"efficientnet-b3\" in model_arch:\n #self.model = timm.create_model('tf_efficientnet_b3_ns', pretrained=True)\n self.model = timm.create_model('tf_efficientnet_b3_ns', pretrained=True, num_classes=num_classes, drop_path_rate=0.2, drop_rate=0.2)\n self.model.classifier = nn.Linear(self.model.classifier.in_features, num_classes)\n elif \"efficientnet-b4\" in model_arch:\n self.model = timm.create_model('tf_efficientnet_b4_ns', pretrained=True)\n self.model.classifier = nn.Linear(self.model.classifier.in_features, num_classes)\n elif 'se_resnext50_pretrainedmodels' in model_arch:\n self.model = pretrainedmodels.se_resnext50_32x4d(pretrained=\"imagenet\")\n self.model.last_linear = nn.Linear(2048, num_classes)\n self.model.avg_pool = nn.AdaptiveAvgPool2d(1)\n elif 'se_resnext50_timm' in model_arch:\n self.model = timm.create_model('seresnext50_32x4d', pretrained=True)\n n_features = self.model.fc.in_features\n self.model.fc = nn.Linear(n_features, num_classes)\n elif 'vit_base_patch16_384' in model_arch:\n self.model = timm.create_model('vit_base_patch16_384', pretrained=True,\n num_classes=num_classes) # , drop_rate=0.1)\n self.model.head = nn.Linear(self.model.head.in_features, num_classes)\n\n '''\n self.model.classifier = nn.Sequential(\n nn.Dropout(0.3),\n #nn.Linear(num_features, hidden_size,bias=True), nn.ELU(),\n nn.Linear(num_features, num_classes, bias=True)\n )\n '''\n\n def forward(self, x):\n x = self.model(x)\n return x\n\ndef get_train_transforms(CFG):\n return A.Compose([\n A.Resize(height=600, width=800),\n A.RandomResizedCrop(height=CFG.image_size, width=CFG.image_size, scale=(0.8, 1.0), p=1),\n A.CenterCrop(height=CFG.image_size, width=CFG.image_size),\n A.Transpose(p=0.5),\n A.HorizontalFlip(p=0.5),\n A.VerticalFlip(p=0.5),\n A.RandomRotate90(p=0.5),\n A.ShiftScaleRotate(p=0.5),\n A.OneOf([\n A.HueSaturationValue(hue_shift_limit=0.2, sat_shift_limit=0.2, val_shift_limit=0.2, p=1),\n A.RandomBrightnessContrast(brightness_limit=(-0.1, 0.1), contrast_limit=(-0.1, 0.1), p=1)], p=0.7\n ),\n A.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225], max_pixel_value=255.0, p=1.0),\n A.CoarseDropout(p=0.5, max_height=32, max_width=32),\n ToTensorV2(),\n ],p=1.0)\n\ndef get_val_transforms(CFG):\n return A.Compose([\n # A.Resize(height=600, width=800), # clw modify\n # A.CenterCrop(CFG.image_size, CFG.image_size, p=0.5),\n # A.Resize(CFG.image_size, CFG.image_size),\n # A.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225], max_pixel_value=255.0, p=1.0),\n # ToTensorV2(),\n A.Resize(height=CFG.image_size, width=CFG.image_size),\n #A.RandomResizedCrop(height=CFG.image_size, width=CFG.image_size, scale=(0.8, 1.0), p=1),\n A.Normalize(), # A.Normalize(mean=(0.43032, 0.49673, 0.31342), std=(0.237595, 0.240453, 0.228265)),\n ToTensorV2(),\n ],p=1.0)\n\nalbu_transforms_train_cutmix = [\n A.Transpose(p=0.5),\n A.HorizontalFlip(p=0.5),\n A.VerticalFlip(p=0.5),\n #A.ShiftScaleRotate(shift_limit=0.1, scale_limit=0.1, rotate_limit=15, interpolation=cv2.INTER_LINEAR, border_mode=0, p=0.85),\n A.ShiftScaleRotate(p=0.5),\n A.OneOf([\n A.HueSaturationValue(hue_shift_limit=0.2, sat_shift_limit=0.2, val_shift_limit=0.2, p=1),\n A.RandomBrightnessContrast(brightness_limit=(-0.1, 0.1), contrast_limit=(-0.1, 0.1), p=1)], p = 0.7\n ),\n A.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225], max_pixel_value=255.0, p=1.0),\n A.CoarseDropout(p=0.5, max_height=32, max_width=32),\n # A.CoarseDropout(max_holes=12, max_height=int(0.11 * configs.input_size[1]),\n # max_width=int(0.11 * configs.input_size[0]),\n # min_holes=1, min_height=int(0.03 * configs.input_size[1]),\n # min_width=int(0.03 * configs.input_size[0]),\n # always_apply=False, p=0.5),\n #A.Cutout(p=0.5),\n ToTensorV2(),\n ]\n\ntrain_aug_cutmix = A.Compose(albu_transforms_train_cutmix)\n\n\ndef load_dataloader(CFG, df, train_idx, val_idx):\n df_train = df.loc[train_idx, :].reset_index(drop=True)\n df_val = df.loc[val_idx, :].reset_index(drop=True)\n\n train_dataset = CassavaDataset(\n CFG.train_data_dir,\n df_train,\n transforms=get_train_transforms(CFG),\n output_label=True,\n mode=\"train\")\n\n val_dataset = CassavaDataset(\n CFG.train_data_dir,\n df_val,\n transforms=get_val_transforms(CFG),\n output_label=True,\n mode=\"val\")\n\n train_loader = torch.utils.data.DataLoader(\n train_dataset,\n batch_size=CFG.train_batch_size,\n pin_memory=False,\n drop_last=False,\n shuffle=True,\n num_workers=CFG.num_workers,\n # sampler=BalanceClassSampler(labels=train_['label'].values, mode=\"downsampling\")\n )\n\n val_loader = torch.utils.data.DataLoader(\n val_dataset,\n batch_size=CFG.val_batch_size,\n num_workers=CFG.num_workers,\n shuffle=False,\n pin_memory=True,\n )\n\n return train_loader, val_loader\n\n\nfrom utils.utils import rand_bbox\ndef train_one_epoch(epoch, model, loss_fn, optimizer, train_loader, device, scheduler=None, schd_batch_update=False):\n model.train()\n lr = optimizer.state_dict()['param_groups'][0]['lr']\n\n running_loss = None\n pbar = tqdm(enumerate(train_loader), total=len(train_loader))\n for step, (images, targets) in pbar:\n images = images.to(device).float()\n targets = targets.to(device).long()\n\n with autocast():\n if np.random.rand() < 0.5:\n # generate mixed sample\n #lam = np.random.beta(1.0, 1.0)\n lam = np.clip(np.random.beta(1, 1), 0.3, 0.4)\n rand_index = torch.randperm(images.size()[0]).cuda()\n target_a = targets\n target_b = targets[rand_index]\n bbx1, bby1, bbx2, bby2 = rand_bbox(images.size(), lam)\n images[:, :, bbx1:bbx2, bby1:bby2] = images[rand_index, :, bbx1:bbx2, bby1:bby2]\n # adjust lambda to exactly match pixel ratio\n lam = 1 - ((bbx2 - bbx1) * (bby2 - bby1) / (images.size()[-1] * images.size()[-2]))\n # compute output\n preds = model(images)\n # loss = criterion(outputs, target_a) * lam + criterion(outputs, target_b) * (1. - lam)\n loss = loss_fn(preds, target_a) * lam + loss_fn(preds, target_b) * (1. - lam) #### no label smooth when using cutmix\n else:\n preds = model(images)\n loss = loss_fn(preds, targets)\n ###### clw modify\n #preds = model(images)\n #loss = loss_fn(preds, targets)\n\n scaler.scale(loss).backward()\n if running_loss is None:\n running_loss = loss.item()\n else:\n running_loss = running_loss * 0.99 + loss.item() * 0.01\n\n if ((step + 1) % CFG.accum_iter == 0) or ((step + 1) == len(train_loader)):\n scaler.step(optimizer)\n scaler.update()\n optimizer.zero_grad()\n\n if scheduler is not None and schd_batch_update:\n scheduler.step()\n if ((step + 1) % CFG.accum_iter == 0) or ((step + 1) == len(train_loader)):\n description = f'Train epoch {epoch} loss: {running_loss:.5f}'\n pbar.set_description(description)\n\n if scheduler is not None and schd_batch_update:\n scheduler.step()\n\n\ndef valid_one_epoch(epoch, model, loss_fn, val_loader, device, scheduler=None, schd_loss_update=False):\n model.eval()\n\n loss_sum = 0\n sample_num = 0\n preds_all = []\n targets_all = []\n scores = []\n\n pbar = tqdm(enumerate(val_loader), total=len(val_loader))\n for step, (images, targets) in pbar:\n images = images.to(device).float()\n targets = targets.to(device).long()\n preds = model(images)\n\n preds_all += [torch.argmax(preds, 1).detach().cpu().numpy()]\n #targets_all += [targets.detach().cpu().numpy()]\n targets_all += [torch.argmax(targets, dim=1).detach().cpu().numpy()] # clw moidfy: for one-hot label\n\n loss = loss_fn(preds, targets)\n loss_sum += loss.item() * targets.shape[0]\n sample_num += targets.shape[0]\n\n if ((step + 1) % CFG.accum_iter == 0) or ((step + 1) == len(train_loader)):\n description = f'Val epoch {epoch} loss: {loss_sum / sample_num:.5f}'\n pbar.set_description(description)\n\n preds_all = np.concatenate(preds_all)\n targets_all = np.concatenate(targets_all)\n accuracy = (preds_all == targets_all).mean()\n print(f'Validation multi-class accuracy = {accuracy:.5f}')\n\n if scheduler is not None:\n if schd_loss_update:\n scheduler.step(loss_sum / sample_num)\n else:\n scheduler.step()\n\n return accuracy\n\n\n################ freeze bn\ndef freeze_batchnorm_stats(net):\n try:\n for m in net.modules():\n if isinstance(m,nn.BatchNorm2d) or isinstance(m,nn.LayerNorm):\n m.eval()\n except ValueError:\n print('error with batchnorm2d or layernorm')\n return\n\n\nclass LabelSmoothingCrossEntropy(nn.Module):\n \"\"\"\n NLL loss with label smoothing.\n \"\"\"\n def __init__(self, smoothing=0.1):\n \"\"\"\n Constructor for the LabelSmoothing module.\n :param smoothing: label smoothing factor\n \"\"\"\n super(LabelSmoothingCrossEntropy, self).__init__()\n assert smoothing < 1.0\n self.smoothing = smoothing\n self.confidence = 1. - smoothing\n\n def forward(self, x, target):\n logprobs = F.log_softmax(x, dim=-1)\n nll_loss = -logprobs.gather(dim=-1, index=target.unsqueeze(1))\n nll_loss = nll_loss.squeeze(1)\n smooth_loss = -logprobs.mean(dim=-1)\n loss = self.confidence * nll_loss + self.smoothing * smooth_loss\n return loss.mean()\n\n\nif __name__ == '__main__':\n CFG = Config\n parser = argparse.ArgumentParser(description=\"PyTorch Template Training\")\n parser.add_argument(\"--model_arch\", default=CFG.arch, help=\"\", type=str)\n parser.add_argument(\"--lr\", default=CFG.lr, help=\"\", type=float)\n parser.add_argument(\"--image_size\", default=CFG.image_size, help=\"\", type=int)\n args = parser.parse_args()\n\n CFG.arch = args.model_arch\n CFG.lr = args.lr\n CFG.image_size = args.image_size\n\n print('model_arch:', CFG.arch)\n print('lr:', CFG.lr)\n print('image_size:', CFG.image_size)\n\n train = pd.read_csv(CFG.train_csv_path)\n\n if CFG.debug:\n CFG.epochs = 1\n train = train.sample(100, random_state=CFG.seed).reset_index(drop=True)\n\n print('CFG seed is ', CFG.seed)\n if CFG.seed is not None:\n seed_everything(CFG.seed)\n\n folds = StratifiedKFold(\n n_splits=CFG.num_splits,\n shuffle=True,\n random_state=CFG.seed).split(np.arange(train.shape[0]), train.label.values)\n\n cross_accuracy = []\n for fold, (train_idx, val_idx) in enumerate(folds):\n ########\n # load data\n #######\n train_loader, val_loader = load_dataloader(CFG, train, train_idx, val_idx)\n\n device = torch.device(CFG.device)\n # assert(CFG.num_classes == train.label.nunique())\n model = CassavaClassifier(CFG.arch, train.label.nunique(), pretrained=True).to(device)\n\n scaler = GradScaler()\n # optimizer = torch.optim.Adam(\n # model.parameters(),\n # lr=CFG.lr,\n # weight_decay=CFG.weight_decay)\n optimizer = torch.optim.SGD(\n model.parameters(),\n lr=CFG.lr,\n momentum=0.9,\n weight_decay=CFG.weight_decay,\n nesterov=True)\n\n # scheduler = torch.optim.lr_scheduler.CosineAnnealingWarmRestarts(\n # optimizer,\n # T_0=CFG.T_0,\n # T_mult=CFG.T_mult,\n # eta_min=CFG.min_lr,\n # last_epoch=-1)\n scheduler = torch.optim.lr_scheduler.MultiStepLR(optimizer, milestones=CFG.milestones, gamma=0.1)\n\n\n ########\n # criterion\n #######\n if CFG.criterion == 'LabelSmoothingCrossEntropy': #### label smoothing cross entropy\n loss_train = LabelSmoothingCrossEntropy(smoothing=CFG.label_smoothing)\n elif CFG.criterion == 'bitempered':\n loss_train = BiTemperedLogisticLoss(t1=0.3, t2=1.0,smoothing=CFG.label_smoothing) # clw note: now have bug...\n elif CFG.criterion == 'Taylor':\n loss_train = TaylorCrossEntropyLoss(n=2, smoothing=CFG.label_smoothing)\n else:\n loss_train = nn.CrossEntropyLoss().to(device)\n #loss_val = nn.CrossEntropyLoss().to(device)\n loss_val = loss_train\n\n best_accuracy = 0\n best_epoch = 0\n for epoch in range(CFG.epochs):\n if epoch < CFG.freeze_bn_epochs:\n freeze_batchnorm_stats(model)\n train_one_epoch(\n epoch,\n model,\n loss_train,\n optimizer,\n train_loader,\n device,\n scheduler=scheduler,\n schd_batch_update=False)\n\n with torch.no_grad():\n epoch_accuracy = valid_one_epoch(\n epoch,\n model,\n loss_val,\n val_loader,\n device,\n scheduler=None,\n schd_loss_update=False)\n\n if epoch_accuracy > best_accuracy:\n torch.save(model.state_dict(), '{}_fold{}_best_{}.ckpt'.format(CFG.arch, fold, epoch_accuracy))\n best_accuracy = epoch_accuracy\n best_epoch = epoch\n print('Best model is saved')\n cross_accuracy += [best_accuracy]\n print('Fold{} best accuracy = {} in epoch {}'.format(fold, best_accuracy, best_epoch))\n del model, optimizer, train_loader, val_loader, scaler, scheduler\n torch.cuda.empty_cache()\n print('{} folds cross validation CV = {:.5f}'.format(CFG.num_splits, np.average(cross_accuracy)))","sub_path":"train_holychen.py","file_name":"train_holychen.py","file_ext":"py","file_size_in_byte":21080,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"152608814","text":"from django.shortcuts import render\nfrom django.http import HttpResponse, HttpRequest\nfrom django.shortcuts import get_object_or_404\nfrom rest_framework.views import APIView\nfrom rest_framework.response import Response\nfrom rest_framework import status\nimport cx_Oracle\nimport os\nfrom django.views import generic\nfrom django.db import connections\n\n\ndef get_roam_operators(request, msisdn, country_id):\n cursor = connections['ppcdb'].cursor()\n cur = cursor.connection.cursor()\n \n i_subs_id=None\n i_int_request_id=1\n i_client_app_type=\"MyTcell_Lite_Web\"\n i_client_app_version=\"v1\"\n o_country_name = cur.var(cx_Oracle.NCHAR)\n o_roam_partners = cursor.connection.cursor()\n o_exit_location_id = cur.var(cx_Oracle.STRING)\n o_responce_id = cur.var(cx_Oracle.NUMBER)\n o_result = cur.var(cx_Oracle.NUMBER)\n o_err_msg = cur.var(cx_Oracle.STRING)\n\n cur.callproc('mytcell_lite_pack.get_roam_partners', (\n i_subs_id, msisdn, i_int_request_id, i_client_app_type, i_client_app_version,\n country_id, o_country_name, o_roam_partners, o_exit_location_id, o_responce_id, o_result, o_err_msg))\n\n columns = [i[0] for i in o_roam_partners.description]\n\n partners={}\n country_name={}\n partners['operators']=[dict(zip(columns, row)) for row in o_roam_partners]\n country_name['country_name']=o_country_name.getvalue()\n partners['country_info']=[country_name]\n \n partners['results']=[{\n 'o_exit_location_id' : o_exit_location_id.getvalue(),\n 'o_responce_id' : int(o_responce_id.getvalue()),\n 'err_code' : int(o_result.getvalue()),\n 'err_msg' : o_err_msg.getvalue()\n }]\n\n cur.close()\n cursor.close()\n\n return render(request, \"mytcell_lite_app/roaming_operators.html\", context=partners)\n","sub_path":"mytcell_lite_app/roam_operators_view.py","file_name":"roam_operators_view.py","file_ext":"py","file_size_in_byte":1780,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"160881832","text":"import sys\n\nimport nltk\nimport string\nimport numpy as np\nimport pandas as pd\nimport re\n\nfrom nltk.corpus import stopwords\nfrom nltk.stem.snowball import SnowballStemmer\n\ndef get_unique_list_of_values(input_df,col,delimiter=\";\"):\n '''\n INPUT\n input_df: Input data frame containing the column which contains multiple categories separated by \";\" delimiter\n colname : Column name which is to be used for computation of standard deviation value\n OUTPUT \n input_df: Updated data frame containing engineered features\n '''\n col_series = input_df[col]\n col_series_new = col_series.dropna()\n i=0\n for s in col_series_new:\n col_series_new_list = s.split(delimiter)\n col_series_new_list = [val [:-2] for val in col_series_new_list]\n if i==0:\n consol_list = col_series_new_list\n else:\n for j in col_series_new_list:\n consol_list.insert(len(consol_list), j)\n i += 1\n list_of_unique_values = list(set(consol_list))\n print (\"List of unique values for \",col,\" :\\n\" , list_of_unique_values)\n print (\"# of unique values for \",col,\" :\" , len(list_of_unique_values))\n \n #Create category labels for each of those items\n label_prefix = \"Cat_\"\n cat_labels = [label_prefix + val for val in list_of_unique_values]\n \n return list_of_unique_values, cat_labels\n\n\ndef create_cat_cols_for_multvalcols(source_col,source_value_list,cat_col_list,input_df):\n '''\n INPUT\n source col - source column from which category columns to be created\n source_value_list - list containing values to be searched in the source column\n cat_col_list - list containing category column names to be created\n colname_prefix - Prefix for column name to be created for rows with missing values\n others_categ_list - List of categories that need to be cmbined in \"Others\" category\n input_df - source df\n OUTPUT\n output_df - Updated source df containing category columns created as per columns\n listed in cat_col_list\n '''\n output_df = input_df\n i=0\n for source_value in source_value_list:\n cat_col = cat_col_list[i]\n pattern = source_value + '-1'\n print(\"cat col = \",cat_col,\"source col = \",source_col)\n output_df [cat_col] = np.where(output_df[source_col].str.contains(pattern),1,0)\n i += 1\n \n #output_df = output_df.drop(['id','categories'],axis=1)\n return output_df\n\n\ndef load_data(messages_filepath, categories_filepath):\n '''\n INPUT\n messages_file_path - filepath of the messages dataset \n categories_file_path - filepath of the categories dataset \n OUTPUT\n output_df - A dataset containing messages and categories merged into a single dataframe\n '''\n #Load data into respective dataframes\n df = pd.read_csv(messages_filepath)\n df2 = pd.read_csv(categories_filepath)\n \n #Update the categories dataframe to include new columns - one column for each category i.e. one hot encoding form\n target_label_lst,cat_labels = get_unique_list_of_values(df2,'categories')\n df2 = create_cat_cols_for_multvalcols('categories',target_label_lst,cat_labels,df2)\n print(\"df shape \", df.shape,\"df2 shape\",df2.shape)\n \n #Create a new dataframe to include the message dataframe and the labels dataframe\n df_new = pd.concat([df,df2],axis=1)\n \n #Create a new column that sums up the category labels (which are in binary format) for each observation. \n #This would be used for EDA\n df_new ['LabelSum'] = df_new.iloc[:,5:].sum(axis=1)\n return df_new\n\n\ndef clean_text(text):\n '''\n INPUTS\n text - Observation containing text string\n OUTPUTS\n clean_tokens - List containing tokens from cleaned text\n '''\n ## Remove puncuation\n text = text.translate(string.punctuation)\n \n ## Convert words to lower case and split them\n text = text.lower().split()\n \n ## Remove stop words\n stops = set(stopwords.words(\"english\"))\n text = [w for w in text if not w in stops and len(w) >= 3]\n \n text = \" \".join(text) ## Clean the text\n text = re.sub(r\"[^A-Za-z0-9^,!.\\/'+-=]\", \" \", text)\n text = re.sub(r\"what's\", \"what is \", text)\n text = re.sub(r\"\\'s\", \" \", text)\n text = re.sub(r\"\\'ve\", \" have \", text)\n text = re.sub(r\"n't\", \" not \", text)\n text = re.sub(r\"i'm\", \"i am \", text)\n text = re.sub(r\"\\'re\", \" are \", text)\n text = re.sub(r\"\\'d\", \" would \", text)\n text = re.sub(r\"\\'ll\", \" will \", text)\n text = re.sub(r\",\", \" \", text)\n text = re.sub(r\"\\.\", \" \", text)\n text = re.sub(r\"!\", \" ! \", text)\n text = re.sub(r\"\\/\", \" \", text)\n text = re.sub(r\"\\^\", \" ^ \", text)\n text = re.sub(r\"\\+\", \" + \", text)\n text = re.sub(r\"\\-\", \" - \", text)\n text = re.sub(r\"\\=\", \" = \", text)\n text = re.sub(r\"'\", \" \", text)\n text = re.sub(r\"(\\d+)(k)\", r\"\\g<1>000\", text)\n text = re.sub(r\":\", \" : \", text)\n text = re.sub(r\" e g \", \" eg \", text)\n text = re.sub(r\" b g \", \" bg \", text)\n text = re.sub(r\" u s \", \" american \", text)\n text = re.sub(r\"\\0s\", \"0\", text)\n text = re.sub(r\" 9 11 \", \"911\", text)\n text = re.sub(r\"e - mail\", \"email\", text)\n text = re.sub(r\"j k\", \"jk\", text)\n text = re.sub(r\"\\s{2,}\", \" \", text) ## Stemming\n text = text.split()\n stemmer = SnowballStemmer('english')\n stemmed_words = [stemmer.stem(word) for word in text]\n text = \" \".join(stemmed_words)\n \n return text\n\ndef clean_data(df):\n '''\n INPUT\n df - source df\n \n OUTPUT\n df - Updated source dataframe \n '''\n #Get index list of messages where message is null and delete the same from the dataframe\n null_message_index_list = df[df['message'].isnull()].index.tolist()\n print(\"No of observations with null messages\", len(null_message_index_list))\n print(\"Df shape before deleting observations with null messages\",df.shape)\n df = df.drop(null_message_index_list)\n print(\"Df shape after deleting observations with null messages\",df.shape)\n \n # apply the clean_text function to df['text']\n df['cleaned_message'] = df['message'].map(lambda x: clean_text(x))\n null_message_index_list = df[df['cleaned_message'].isnull()].index.tolist()\n print(\"No of observations with null values in cleaned messages\", len(null_message_index_list))\n print(\"Df shape before deleting observations with null messages\",df.shape)\n df = df.drop(null_message_index_list)\n print(\"Df shape after deleting observations with null messages\",df.shape)\n \n #Drop the id columns from the dataframe that are present as a result of concatenation from message and category dataframes\n df = df.drop(['id'],axis=1)\n print(\"Df shape after dropping id columns\",df.shape)\n \n return df\n\n\ndef save_data(df, database_filename):\n '''\n INPUTS\n df - Dataframe containing messages and categories merged into a single dataset\n OUTPUTS\n database_filename - Filepath for the SQLite database that will host the dataset containing\n messages and categories\n '''\n from sqlalchemy import create_engine\n import sqlite3\n \n df.to_csv('df_consol.csv')\n \n # connect to the database\n # the database filename will include path and db file name including .db extension\n # note that sqlite3 will create this database file if it does not exist already\n engine_string = 'sqlite:///' + database_filename\n engine = create_engine(engine_string,echo=True)\n sqlite_connection = engine.connect()\n \n #table_name = database_filename[:-3] #Drops the .db extension to create a table with the rest of the string\n #Extract the table name from filepath\n import re\n\n search_for_dbname = re.search('/(.+?).db', database_filename)\n\n if search_for_dbname:\n tablename_incl_path = search_for_dbname.group(1)\n\n word_list = tablename_incl_path.split(\"/\")\n table_name = word_list[len(word_list) -1]\n \n sqlite_table = table_name\n \n conn = sqlite3.connect(database_filename)\n\n # get a cursor\n cur = conn.cursor()\n\n # drop the test table in case it already exists\n #df_merged.to_sql('merged', con = conn, if_exists='replace', index=False)\n #drop_table_sql = \"DROP TABLE IF EXISTS \" + table_name\n #cur.execute(drop_table_sql)\n \n df.to_sql (sqlite_table,sqlite_connection,if_exists='replace',index=False)\n \n sqlite_connection.close()\n conn.close()\n pass \n\n\ndef main():\n '''\n INPUTS\n messages_file_path - filepath of the messages dataset \n categories_file_path - filepath of the categories dataset\n database_filename - Filepath for the SQLite database that will host the dataset\n containing messages and categories\n OUTPUTS\n Cleaned data (comprising original messages (original and cleaned) messages and categories) \n stored in the user specified SQLite database \n '''\n if len(sys.argv) == 4:\n\n messages_filepath, categories_filepath, database_filepath = sys.argv[1:]\n\n print('Loading data...\\n MESSAGES: {}\\n CATEGORIES: {}'\n .format(messages_filepath, categories_filepath))\n df = load_data(messages_filepath, categories_filepath)\n\n print('Cleaning data...')\n df = clean_data(df)\n \n print('Saving data...\\n DATABASE: {}'.format(database_filepath))\n save_data(df, database_filepath)\n \n print('Cleaned data saved to database!')\n \n else:\n print('Please provide the filepaths of the messages and categories '\\\n 'datasets as the first and second argument respectively, as '\\\n 'well as the filepath of the database to save the cleaned data '\\\n 'to as the third argument. \\n\\nExample: python process_data.py '\\\n 'disaster_messages.csv disaster_categories.csv '\\\n 'DisasterResponse.db')\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"web_app/data/process_data.py","file_name":"process_data.py","file_ext":"py","file_size_in_byte":10189,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"566450937","text":"from web3 import Web3\nfrom web3.utils.threads import (\n Timeout,\n)\n\n\ndef check_succesful_tx(web3: Web3, txid: str, timeout=180) -> dict:\n '''See if transaction went through (Solidity code did not throw).\n :return: Transaction receipt\n '''\n receipt = wait_for_transaction_receipt(web3, txid, timeout=timeout)\n txinfo = web3.eth.getTransaction(txid)\n assert txinfo['gas'] != receipt['gasUsed']\n return receipt\n\n\ndef wait_for_transaction_receipt(web3, txid, timeout=180):\n with Timeout(timeout) as time:\n while not web3.eth.getTransactionReceipt(txid):\n time.sleep(5)\n\n return web3.eth.getTransactionReceipt(txid)\n","sub_path":"raiden_contracts/utils/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":667,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"212807589","text":"from utils import word_parse\nfrom utils.feedbk import conn_database\nfrom utils.video_process import VideoProcessor, VideoNotFoundError, VideoCombinedError\nfrom flask import Flask, request, jsonify, make_response, abort, send_file, render_template, url_for\nimport os\nimport logging\nimport json\nfrom argparse import ArgumentParser\n\nparser = ArgumentParser()\nparser.add_argument('-host', type=str, default='127.0.0.1')\nparser.add_argument('-port', type=int, default=8080)\nparser.add_argument('-d', '--debug', default=False, action=\"store_true\")\n\nargs = parser.parse_args()\n\nlogging.basicConfig(level=logging.ERROR,\n format='%(asctime)s %(levelname)s %(message)s',\n datefmt='%Y-%m-%d %H:%M',\n handlers=[logging.FileHandler('error.log', 'a', 'utf-8'), ])\n\napp = Flask(__name__)\n\nif not os.path.exists(\"tmp\"):\n os.mkdir(\"tmp\")\nif not os.path.exists(\"tmp\"):\n os.mkdir(\"video\")\n\n\n@app.route(\"/\")\ndef index():\n return render_template(\"index.html\")\n\n@app.route('/video', methods=['GET'])\ndef get_video():\n if request.method == 'GET':\n video_id = request.values.get('v')\n file_path = os.path.join(\"video\", f\"{video_id}.mp4\")\n\n if os.path.exists(file_path):\n return send_file(file_path)\n else:\n abort(404)\n\n\n@app.route('/resource', methods=['GET'])\ndef get_resource():\n if request.method == 'GET':\n r = request.values.get('r')\n file_path = os.path.join(\"resource\", r)\n\n if os.path.exists(file_path):\n return send_file(file_path)\n else:\n abort(404)\n\n@app.route('/api/video', methods=['POST'])\ndef make_video():\n if request.method == 'POST':\n text = request.values.get('text')\n text = text.strip()\n if len(text) == 0:\n return make_response(\"empty\", 500)\n if len(text) > 50:\n return make_response(\"too long\", 500)\n try:\n bopomofo = word_parse.get_bopomofo(text)\n v = VideoProcessor()\n video_id = v.get_video(bopomofo)\n print(video_id)\n return jsonify({\n \"video_id\": video_id\n })\n except VideoNotFoundError as e:\n logging.error(e)\n return make_response(\"not found\", 500)\n except VideoCombinedError as e:\n logging.error(e)\n return make_response(\"unknown\", 500)\n except Exception as e:\n logging.error(e)\n return make_response(\"unknown\", 500)\n\n@app.route('/api/feedback', methods = ['POST'])\ndef feedback():\n text = request.value.get('feedback')\n if text is None:\n return make_response(\"need feedback\", 400)\n text = text.strip()\n if len(text) == 0:\n return make_response(\"feedback is empty\", 400)\n if len(text) > 500:\n return make_response(\"feedback is too long\", 400)\n conn_database(text) \n return make_response(\"successful\", 200)\n \n\n@app.context_processor\ndef override_url_for():\n return dict(url_for=dated_url_for)\n\n\ndef dated_url_for(endpoint, **values):\n if endpoint == 'static':\n filename = values.get('filename', None)\n if filename:\n file_path = os.path.join(app.root_path,\n endpoint, filename)\n values['q'] = int(os.stat(file_path).st_mtime)\n return url_for(endpoint, **values)\n\nif __name__ == \"__main__\":\n app.run(host=args.host, port=args.port, debug=args.debug)\n","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":3486,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"457496403","text":"from __future__ import absolute_import, division, print_function\n\nimport socket\n\nfrom tornado import gen\nfrom tornado.iostream import IOStream\nfrom tornado.log import app_log\nfrom tornado.stack_context import NullContext\nfrom tornado.tcpserver import TCPServer\nfrom tornado.test.util import skipBefore35, exec_test\nfrom tornado.testing import AsyncTestCase, ExpectLog, bind_unused_port, gen_test\n\n\nclass TCPServerTest(AsyncTestCase):\n @gen_test\n def test_handle_stream_coroutine_logging(self):\n # handle_stream may be a coroutine and any exception in its\n # Future will be logged.\n class TestServer(TCPServer):\n @gen.coroutine\n def handle_stream(self, stream, address):\n yield gen.moment\n stream.close()\n 1 / 0\n\n server = client = None\n try:\n sock, port = bind_unused_port()\n with NullContext():\n server = TestServer()\n server.add_socket(sock)\n client = IOStream(socket.socket())\n with ExpectLog(app_log, \"Exception in callback\"):\n yield client.connect(('localhost', port))\n yield client.read_until_close()\n yield gen.moment\n finally:\n if server is not None:\n server.stop()\n if client is not None:\n client.close()\n\n @skipBefore35\n @gen_test\n def test_handle_stream_native_coroutine(self):\n # handle_stream may be a native coroutine.\n\n namespace = exec_test(globals(), locals(), \"\"\"\n class TestServer(TCPServer):\n async def handle_stream(self, stream, address):\n stream.write(b'data')\n stream.close()\n \"\"\")\n\n sock, port = bind_unused_port()\n server = namespace['TestServer']()\n server.add_socket(sock)\n client = IOStream(socket.socket())\n yield client.connect(('localhost', port))\n result = yield client.read_until_close()\n self.assertEqual(result, b'data')\n server.stop()\n client.close()\n\n def test_stop_twice(self):\n sock, port = bind_unused_port()\n server = TCPServer()\n server.add_socket(sock)\n server.stop()\n server.stop()\n\n @gen_test\n def test_stop_in_callback(self):\n # Issue #2069: calling server.stop() in a loop callback should not\n # raise EBADF when the loop handles other server connection\n # requests in the same loop iteration\n\n class TestServer(TCPServer):\n @gen.coroutine\n def handle_stream(self, stream, address):\n server.stop()\n yield stream.read_until_close()\n\n sock, port = bind_unused_port()\n server = TestServer()\n server.add_socket(sock)\n server_addr = ('localhost', port)\n N = 40\n clients = [IOStream(socket.socket()) for i in range(N)]\n connected_clients = []\n\n @gen.coroutine\n def connect(c):\n try:\n yield c.connect(server_addr)\n except EnvironmentError:\n pass\n else:\n connected_clients.append(c)\n\n yield [connect(c) for c in clients]\n\n self.assertGreater(len(connected_clients), 0,\n \"all clients failed connecting\")\n try:\n if len(connected_clients) == N:\n # Ideally we'd make the test deterministic, but we're testing\n # for a race condition in combination with the system's TCP stack...\n self.skipTest(\"at least one client should fail connecting \"\n \"for the test to be meaningful\")\n finally:\n for c in connected_clients:\n c.close()\n\n # Here tearDown() would re-raise the EBADF encountered in the IO loop\n","sub_path":"www/src/py/test/tornado-master/tornado/test/tcpserver_test.py","file_name":"tcpserver_test.py","file_ext":"py","file_size_in_byte":3896,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"268692359","text":"from flask import Flask, request, redirect, Response\nfrom pymongo import MongoClient\nimport twilio.twiml\nimport re\nimport datetime\n\nimport os\n\n\n\napp = Flask(__name__)\n\nteam_names = {}\n\n# Enter the answer to the puzzle. No whitespace allowed\nanswers = {\n \"1\": \"TILT\",\n \"2\": \"THERMOMETER\",\n \"3\": \"ONIONRING\",\n \"4\": \"FLYTRAP\",\n \"5\": \"WEREWOLF\",\n \"6\": \"CURIOSITY\",\n \"7\": \"REDSPOT\",\n \"8\": \"DEEPBLUE\",\n \"META\": \"NOADMITSFROMPLUTO\"\n}\n\n# Enter the flavor text given for a correct answer\nstoryline = {\n \"1\": \"\",\n \"2\": \"\",\n \"3\": \"\",\n \"4\": \"\",\n \"5\": \"\",\n \"6\": \"\",\n \"7\": \"\",\n \"8\": \"\",\n}\n\nclient = MongoClient()\n#print(client.list_database_names())\n\ndb = client.aqua #make sure to set up a db called aqua beforehand\nteams = db.teams\nsubans = db.subans\n\nstock_messages = {\n \"Welcome\": \"Welcome to MIT, {team_name}. Go find some puzzles in yellow envelopes! Start texting us with answers [PUZZLE NO.] [SOLUTION], for example,'1 balloon' if the answer for puzzle 1 was balloon.\",\n \"Help\": \"Text [PUZZLE NO.] [SOLUTION], like '1 balloon', and we'll let you know if you are correct. Read the puzzle solving tips in the intro doc! If you need more help, find a staff member wearing a hat.\",\n \"Name Already Taken\": \"Sorry, the name '{team_name_new}' is already taken. Text 'yes' to accept the name '{team_name_temp}' or text to create a new one\",\n \"Name Already Taken First\": \"Sorry, the name '{team_name_new}' is already taken. Text to create a new one\",\n \"Name Too Long\": \"Sorry, please keep your name under 30 characters. Text 'yes' to accept the name '{team_name_temp}' or text to create a new one\",\n \"Name Too Long First\": \"Sorry, please keep your name under 30 characters. Text to create a new one\",\n \"Confirm Name\": \"Welcome to the Aquarium Puzzlehunt! Text 'yes' to accept the name '{team_name_temp}' or text to create a new one\",\n \"Parse Error\": \"I'm sorry, we didn't understand '{text}'. Please text answers in the format [PUZZLE NO.] [SOLUTION], like '1 balloon'\",\n \"Problem Not Exists\": \"We don't have a puzzle {puzzle_number}...\",\n \"Correct\": \"Your answer of {answer} is Correct!{storyline}\",\n \"Incorrect\": \"Sorry, your answer {answer} for puzzle {puzzle_number} was incorrect. Please try again.\",\n \"Already Answered\": \"You've already completed puzzle {puzzle_number}, go find another one!\",\n \"Final Puzzle\": \"Your answer of {answer} is Correct!{storyline} You have solved all 8 puzzles! Come to the front desk to receive the meta puzzle! To submit the meta, text 'meta' and then the answer\",\n \"Meta Correct\": \"Congratulations {team_name}, {answer} was correct! Go see Mission Control at the front desk!\",\n \"Meta Answered\": \"Yeah, we're upset about Pluto too. Since we're in an aquarium, perhaps you should consider this: https://www.quora.com/What-would-happen-if-the-Earth-was-hit-by-a-fish-the-size-of-Pluto\",\n \"Meta Incorrect\": \"Sorry, {answer} was wrong. Please try again.\"\n}\n\nspecial_messages = {\n \"2\": {\n \"TEMPERATUREMEASURER\": \"You’re almost there! What’s a word for a TEMPERATURE MEASURER?\"\n }\n}\n\nparse_length = len(stock_messages[\"Parse Error\"].format(text=\"\"))\nname_length = len(stock_messages[\"Welcome\"].format(team_name=\"\"))\nreDigits = re.compile(r\"^\\d+$\")\nreEndWhitespace = re.compile(r\"\\s+$\")\nreBeginWhitespace = re.compile(r\"^\\s+\")\nreWhitespace = re.compile(r\"\\s+\")\n\ndef parse_error(command):\n if len(command) + parse_length < 160:\n return stock_messages[\"Parse Error\"].format(text=command)\n else:\n return stock_messages[\"Parse Error\"].format(text=(command[:160-parse_length-4] + \" ...\"))\n\ndef parse_puzzle_answers(team,from_number,root,leaf):\n if root in answers:\n if root in team[u'Correct']:\n return stock_messages[\"Already Answered\"].format(puzzle_number=root)\n elif leaf == answers[root].upper():\n teams.update({\"Number\":from_number},{\"$push\":{\"Correct\":root},\"$set\":{\"SolveTimes.\"+root:datetime.datetime.utcnow()}})\n subans.update({\"_Puzzle\":root},{\"$inc\":{leaf:1},\"$addToSet\":{\"_Answers\":leaf}},True)\n\n if len(team[u'Correct']) >= 7:\n return stock_messages[\"Final Puzzle\"].format(puzzle_number=root, answer=leaf, storyline=storyline[root], team_name=team[u'Name'])\n else:\n return stock_messages[\"Correct\"].format(puzzle_number=root, answer=leaf, storyline=storyline[root])\n elif root in special_messages and leaf in special_messages[root]:\n subans.update({\"_Puzzle\":root},{\"$inc\":{leaf:1},\"$addToSet\":{\"_Answers\":leaf}},True)\n return special_messages[root][leaf]\n else:\n subans.update({\"_Puzzle\":root},{\"$inc\":{leaf:1},\"$addToSet\":{\"_Answers\":leaf}},True)\n return stock_messages[\"Incorrect\"].format(puzzle_number=root, answer=leaf)\n else:\n return stock_messages[\"Problem Not Exists\"].format(puzzle_number=root)\n\n@app.route(\"/answers.txt\")\ndef show_answers():\n ret = \"\"\n for ans in subans.find():\n ret += ans[u'_Puzzle'] + \"\\r\\n\"\n ret += \"\\r\\n\".join(['\"{}\",{}'.format(k,ans[k]) for k in ans[u'_Answers']])\n ret += \"\\r\\n\"\n\n return Response(ret, mimetype='text/plain')\n\n@app.route(\"/solvedpuzzles.txt\")\ndef show_stats():\n total_solved = [0]*10\n puzzles_solved = [0]*9\n for team in teams.find():\n for i in range(10):\n if len(team[u'Correct']) == i:\n total_solved[i] += 1\n for i in range(8):\n if str(i+1) in team[u'Correct']:\n puzzles_solved[i] += 1\n if \"META\" in team[u'Correct']:\n puzzles_solved[8] += 1\n\n ret = \"# of Teams by total # of problems solved:\\r\\n\"\n for i in range(10):\n ret += str(i) + \": \" + str(total_solved[i]) + \"\\r\\n\"\n\n ret += \"\\r\\n# of puzzle solves by puzzle:\\r\\n\"\n for i in range(8):\n ret += str(i) + \": \" + str(puzzles_solved[i]) + \"\\r\\n\"\n\n ret += \"META: \" + str(puzzles_solved[8])\n\n return Response(ret, mimetype='text/plain')\n\n@app.route(\"/allteams.txt\")\ndef show_teams():\n ret = \"\"\n for team in teams.find():\n if \"StartTime\" in team:\n if \"META\" in team[u'Correct']:\n ret+= \"FINISHED(\" + str(team['SolveTimes']['META']-team[u'StartTime']) +\") \"\n else:\n ret+= \"ELAPSED(\" + str(datetime.datetime.utcnow()-team[u'StartTime']) +\") \"\n ret += '\"' + team[u'TempName'] + '\",' + \",\".join(team[u'Correct']) +\" \"+ team[u'StartTime'].strftime(\"%H:%M:%S\") + \"\\r\\n\"\n return Response(ret, mimetype='text/plain')\n\n@app.route(\"/\", methods=['GET', 'POST'])\ndef hello_monkey():\n\n from_number = request.values.get('From', None)\n command = reBeginWhitespace.sub('', reEndWhitespace.sub('', request.values.get('Body', None)))\n\n tokens = command.split(None, 1)\n\n team = teams.find_one({\"Number\":from_number})\n\n message = parse_error(command)\n\n if team == None:\n if len(command) < 31:\n if teams.find_one({\"$or\":[{\"Name\":command}, {\"TempName\":command}]}) == None:\n message = stock_messages[\"Confirm Name\"].format(team_name_temp=command)\n teams.insert({\"Number\":from_number,\"TempName\":command,\"Correct\":list()})\n else:\n message = stock_messages[\"Name Already Taken First\"].format(team_name_new=command)\n else:\n message = stock_messages[\"Name Too Long First\"]\n elif \"Name\" not in team:\n if tokens[0].upper() == 'YES':\n teams.update({\"Number\":from_number},{\"$set\":{\"Name\":team[u'TempName']}})\n teams.update({\"Number\":from_number},{\"$set\":{\"StartTime\":datetime.datetime.utcnow()}})\n message = stock_messages[\"Welcome\"].format(team_name=team[u'TempName'])\n elif len(command) < 31:\n if teams.find_one({\"$or\":[{\"Name\":command}, {\"TempName\":command}]}) == None:\n teams.update({\"Number\":from_number},{\"$set\":{\"TempName\":command}})\n message = stock_messages[\"Confirm Name\"].format(team_name_temp=command)\n else:\n message = stock_messages[\"Name Already Taken\"].format(team_name_new=command,team_name_temp=team[u'TempName'])\n else:\n message = stock_messages[\"Name Too Long\"].format(team_name_temp=team[u'TempName'])\n elif len(tokens) == 2:\n root,leaf = tokens\n if reDigits.search(root) != None:\n message = parse_puzzle_answers(team, from_number, root, reWhitespace.sub('',leaf).upper())\n elif root.upper() == \"META\":\n if \"META\" in team[u'Correct']:\n message = stock_messages[\"Meta Answered\"]\n else:\n if reWhitespace.sub('',leaf).upper() == answers[\"META\"].upper():\n message = stock_messages[\"Meta Correct\"].format(answer=reWhitespace.sub('',leaf).upper(), team_name=team[u'Name'])\n teams.update({\"Number\":from_number},{\"$push\":{\"Correct\":root.upper()},\"$set\":{\"SolveTimes.META\":datetime.datetime.utcnow()}})\n subans.update({\"_Puzzle\":\"META\"},{\"$inc\":{leaf:1},\"$addToSet\":{\"_Answers\":leaf}},True)\n else:\n message = stock_messages[\"Meta Incorrect\"].format(answer=reWhitespace.sub('',leaf).upper())\n subans.update({\"_Puzzle\":\"META\"},{\"$inc\":{leaf:1},\"$addToSet\":{\"_Answers\":leaf}},True)\n elif root.upper() == \"PENCIL-REMOVE-TEAM\":\n teams.remove({\"Name\":leaf})\n message = \"Removed \" + leaf\n\n elif len(tokens) == 1:\n root = tokens[0]\n if root.upper() == \"?\":\n message = stock_messages[\"Help\"]\n\n resp = twilio.twiml.Response()\n resp.sms(message)\n\n return str(resp)\n\nif __name__ == \"__main__\":\n app.run()\n\n\n\n\n\n","sub_path":"run2019.py","file_name":"run2019.py","file_ext":"py","file_size_in_byte":9754,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"614622089","text":"import pysam\nimport random\n\nref_file = open('hg19_chr21.fa', 'r')\nref_data = ref_file.read()\n\nsnp_file = open('read.txt', 'r')\nsnp_data = snp_file.read().split('\\n')\nsnp_pos = [0] * 10000\n\nsamfile = pysam.AlignmentFile('read.bam', 'rb')\n\ntrain_file = open('learn_train.csv', 'w')\nvalidation_file = open('learn_val.csv', 'w')\ntest_file = open('learn_test.csv', 'w')\n\nqual_cost = {'!': 0, '\"': 1, '#': 2, '$': 3, '%': 4, '&': 5, \"'\": 6,\n '(': 7, ')': 8, '*': 9, '+': 10, ',': 11, '-': 12, '.': 13,\n '/': 14, '0': 15, '1': 16, '2': 17, '3': 18, '4': 19, '5': 20,\n '6': 21, '7': 22, '8': 23, '9': 24, ':': 25, ';': 26, '<': 27,\n '=': 28, '>': 29, '?': 30, '@': 31, 'A': 32, 'B': 33, 'C': 34,\n 'D': 35, 'E': 36, 'F': 37, 'G': 38, 'H': 39, 'I': 40, 'J': 41}\ngene_one_hot = {'A':[1, 0, 0, 0], 'T':[0, 1, 0, 0], 'G':[0, 0, 1, 0], 'C':[0, 0, 0, 1]}\n\nresult = []\npos_dic = {}\nmax_total = 0\n\nfor i in range(10000):\n snp_pos[i] = snp_data[i].split('(')[0]\nsnp_pos.sort()\n\nfor i in range(10000):\n for pileupcolumn in samfile.pileup('chr21', int(snp_pos[i]) - 10, int(snp_pos[i]) + 10):\n if (pileupcolumn.pos < int(snp_pos[i]) - 10 or pileupcolumn.pos >= int(snp_pos[i]) + 10) or pileupcolumn.n == 0:\n continue\n here_is_snp = 0\n for j in range(i - 10, i + 10):\n if j>=0 and j<10000 and pileupcolumn.pos!=int(snp_pos[i])-1 and pileupcolumn.pos==int(snp_pos[j])-1:\n here_is_snp = 1\n break\n if here_is_snp == 1:\n continue\n gene_count = 0\n qual_value = {'A':0, 'T':0, 'G':0, 'C':0}\n for pileupread in pileupcolumn.pileups:\n if not pileupread.is_del and not pileupread.is_refskip:\n gene = pileupread.alignment.query_sequence[pileupread.query_position]\n qual = pileupread.alignment.qual[pileupread.query_position]\n gene_count += 1\n qual_value[gene.upper()] += qual_cost[qual]\n if gene_count == 0:\n continue\n for k in qual_value.keys():\n qual_value[k]/=(41*gene_count)\n qual_data=[qual_value['A'],qual_value['T'],qual_value['G'],qual_value['C']]\n\n max_total = max(max_total, gene_count)\n\n pos_in_file = int(pileupcolumn.pos / 50) * 51 + pileupcolumn.pos % 50 + 7\n ref_gene = ref_data[pos_in_file]\n data = ref_gene\n for num in range(4):\n data += \"/\" + str(qual_data[num])\n\n snp = 0\n if pileupcolumn.pos == int(snp_pos[i]) - 1:\n snp = 1\n\n data += \"/\" + str(gene_count) + \"/\" + str(snp)\n pos_dic[data] = pileupcolumn.pos\n\ndata_list = list(pos_dic.keys())\nrandom.shuffle(data_list)\n\ndef write_data(fname, gene_pos, gene_one_hot, data_set, max_total):\n ref_one_hot = gene_one_hot[data_set[0].upper()]\n fname.write(\"%s, %s, %s, %s, %s, \" % (\n gene_pos, ref_one_hot[0], ref_one_hot[1], ref_one_hot[2], ref_one_hot[3]))\n fname.write(\"%s, %s, %s, %s, \" % (data_set[1], data_set[2], data_set[3], data_set[4]))\n fname.write(\"%s, %s, %s\\n\" % (int(data_set[5]) / (max_total*2), data_set[6], int(not int(data_set[6]))))\n\nsnp_num = 0\nnon_snp = 0\nfor num in range(len(data_list)):\n data_set = data_list[num].split('/')\n gene_pos=pos_dic[data_list[num]]\n if int(data_set[6]) == 0:\n if non_snp < 8000:\n write_data(train_file, gene_pos, gene_one_hot, data_set, max_total)\n elif non_snp < 9600:\n write_data(validation_file, gene_pos, gene_one_hot, data_set, max_total)\n elif non_snp < 14600:\n write_data(test_file, gene_pos, gene_one_hot, data_set, max_total)\n non_snp += 1\n else:\n if snp_num < 8000:\n write_data(train_file, num, gene_one_hot, data_set, max_total)\n elif snp_num < 8400:\n write_data(validation_file, gene_pos, gene_one_hot, data_set, max_total)\n else:\n write_data(test_file, gene_pos, gene_one_hot, data_set, max_total)\n snp_num += 1\n\nref_file.close()\nsnp_file.close()\nsamfile.close()\ntrain_file.close()\nvalidation_file.close()\ntest_file.close()\n","sub_path":"restart_learning/make_train_data.py","file_name":"make_train_data.py","file_ext":"py","file_size_in_byte":4151,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"326033226","text":"\"\"\"\n\nScript to normalize the data in /Data and \n\nAuthor: jweber\nDate: 09.03.2020\n\"\"\"\n\nimport pandas as pd \nimport numpy as np \n\ndef load_normalize_data(normalize=True):\n\n data = pd.read_csv('../Data/Table_alpha_Data.txt', header=0, dtype=np.float64)\n assert(np.any(data.isna()) == False), \"There are NaN's in the dataframe - please check this!\"\n\n descriptors = {\n \"min\": data.min().values,\n \"max\": data.max().values\n }\n\n if normalize:\n data = (data - data.min()) / (data.max() - data.min())\n\n return (data, descriptors)\n\n","sub_path":"Code/data_preprocessing.py","file_name":"data_preprocessing.py","file_ext":"py","file_size_in_byte":560,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"248526950","text":"\nfrom flask_restful import Resource, reqparse\nfrom flask_jwt import jwt_required\nfrom models.items import ItemModel\n\n\n\nclass Item(Resource):\n\tparser = reqparse.RequestParser()\n\tparser.add_argument('price', type=float, required=True, help= 'Required')\n\tparser.add_argument('store_id', type=int, required=True, help= 'Required')\n\t\t\n\t@jwt_required()\n\tdef get(self,name):\n\t\titem = ItemModel.find_by_name(name)\n\t\tif item:\n\t\t\treturn item.json()\n\t\treturn {'message' : 'Item does not exists'}\n\t\n\t\n\t\n\t\n\tdef post(self,name):\n\t\tif ItemModel.find_by_name(name):\n\t\t\treturn {'message' : 'Item already exists'}\n\n\t\tdata = Item.parser.parse_args()\n\n\t\titem = ItemModel(name, data['price'], data['store_id'])\n\t\t\n\t\ttry: \n\t\t\titem.savetodb()\n\t\texcept:\n\t\t\t{'message' : 'An error occured'}\n\t\treturn item.json()\n\n\tdef delete(self,name):\n\t\titem = ItemModel.find_by_name(name)\n\t\tif item:\n\t\t\titem.delete()\n\t\t\n\t\treturn {'message' : 'Item deleted successfully'}\t\t\n\n\tdef put(self, name):\n\t\t\n\t\tdata = Item.parser.parse_args()\n\t\titem = ItemModel.find_by_name(name)\n\t\t\n\t\t\n\t\tif item is None:\t\t\n\t\t\titem = ItemModel(name, data['price'], data['store_id'])\n\t\telse:\n\t\t\titem.price = data['price']\n\t\t\n\t\titem.savetodb()\n\n\t\treturn item.json()\n\n\t\n\n\nclass Itemlist(Resource):\n\tdef get(self):\n\t\treturn {'item': [item.json() for item in ItemModel.query.all()]}\n","sub_path":"resources/items.py","file_name":"items.py","file_ext":"py","file_size_in_byte":1313,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"69764705","text":"# -*- coding: utf-8 -*-\n\"\"\"\nConfigs for DNN + CE\n\"\"\"\n\nfrom src.utils.vegab import ConfigRegistry\n\nconfig = ConfigRegistry()\n\nconfig.set_root_config({\n 'batch_size': 200,\n 'epochs': 30,\n 'rel_init': 0.02,\n 'rel_vec_size': 200,\n 'activation': 'relu',\n 'hidden_units': 1000,\n 'optimizer': 'adagrad',\n 'data_dir': 'LiACL/conceptnet_my/',\n 'l2': 1e-6, # \"cost_new = (1000*loss) +(self.LC * l2_penalty1)\" from original code ;)\n # 'lambda_2': 0.0, # Matrix for relation matrix # No identity matrix in DNN CE\n 'learning_rate': 0.01,\n 'embedding_file': 'embeddings/LiACL/embeddings_OMCS.txt',\n 'use_embedding': True,\n 'batch_norm': False,\n 'random_seed': 0,\n\n \"regenerate_ns_eval\": False,\n\n # Negative sampler\n 'negative_sampling': 'uniform', # or \"argsim\"\n 'negative_threshold': 0.0, # Weigt used in threshold in argsim\n \"ns_embedding_file\": 'embeddings/LiACL/embeddings_OMCS.txt',\n\n 'eval_k': 1, # Number of neg samples in eval\n})\n","sub_path":"src/configs/configs_dnn_ce.py","file_name":"configs_dnn_ce.py","file_ext":"py","file_size_in_byte":989,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"333846655","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nSpyder Editor\r\n\r\nThis is a temporary script file.\r\n\"\"\"\r\n\r\nclass Solution:\r\n def countPrimes(self, n: int) -> int:\r\n if n<2:\r\n return 0\r\n nums = [None] * n\r\n nums[0], nums[1] = False, False\r\n for i in range(n):\r\n if nums[i] == None:\r\n nums[i] = True\r\n for j in range(i+i, n, i):\r\n nums[j] = False\r\n return sum(nums)\r\n","sub_path":"Math/esay-Count Primes.py","file_name":"esay-Count Primes.py","file_ext":"py","file_size_in_byte":456,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"346918512","text":"# encoding: UTF-8\nimport sys\nimport json\nimport datetime\nfrom pymongo import MongoClient, ASCENDING\nfrom Object import NewsData\n#from util import filter_tags,convertISODate\nfrom collections import Counter\n\n# 加载配置\nconfig = open('./schedulerTask/config.json')\n#config = open('config.json')\nsetting = json.load(config)\n\nMONGO_HOST = setting['MONGO_HOST']\nMONGO_PORT = setting['MONGO_PORT']\nNews_DB_NAME = setting['News_DB_NAME']\nRSS_SOURCE = setting[\"RSS_SOURCE\"]\nRSS_HOTS = setting[\"RSS_HOTS\"]\n\nmc = MongoClient(MONGO_HOST, MONGO_PORT) # Mongo连接\ndb = mc[News_DB_NAME] # 数据库\n\n\n\n\ndef keywordCount():\n cl = db[\"keyword_count\"]\n cl.ensure_index([('datetime', ASCENDING)], unique=True) # 添加索引 \n \n start = datetime.datetime.utcnow().isoformat()\n end = (datetime.datetime.utcnow()-datetime.timedelta(days=3)).isoformat()\n count_frq = Counter()\n useless_eyword = ['11','...','编辑','时间','来源','责任编辑','记者']\n cl_news = db[\"news_data\"]\n for row in cl_news.find({'published': {'$lt': start, '$gte': end }}):\n #print(row['tags'])\n for keyword in row['tags']:\n #print(keyword)\n if keyword in useless_eyword:\n #print(keyword)\n row['tags'].remove(keyword)\n #print(row['tags'])\n count_frq.update(row['tags'])\n dict_count_frq = dict(count_frq.most_common(1000))\n current_date = datetime.datetime.now()\n flt = {'datetime': str(current_date)}\n cl.replace_one(flt, {\"datetime\":current_date, \"frq\": dict_count_frq}, True)\n\n\ndef keywordCountSchedulerTaskJob():\n keywordCount()\n\nif __name__ == \"__main__\":\n keywordCountSchedulerTaskJob()\n\n","sub_path":"runWebsite/schedulerTask/newsSpider/jobKeywordCount.py","file_name":"jobKeywordCount.py","file_ext":"py","file_size_in_byte":1726,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"451405019","text":"# -*- coding: utf-8 -*-\nfrom twisted.internet.protocol import DatagramProtocol\nfrom c2w.main.lossy_transport import LossyTransport\nimport logging\nimport struct\nfrom twisted.internet import reactor\nimport math\nfrom math import pow\nimport c2w\nfrom c2w.main.client_model import c2wClientModel\nfrom c2w.main.constants import ROOM_IDS\nlogging.basicConfig()\nmoduleLogger = logging.getLogger('c2w.protocol.udp_chat_client_protocol')\n\n\nclass c2wUdpChatClientProtocol(DatagramProtocol):\n\n\n\tdef __init__(self, serverAddress, serverPort, clientProxy, lossPr):\n\t\t\"\"\"\n\t\t:param serverAddress: The IP address (or the name) of the c2w server,\n\t\tgiven by the user.\n\t\t:param serverPort: The port number used by the c2w server,\n\t\tgiven by the user.\n\t\t:param clientProxy: The clientProxy, which the protocol must use\n\t\tto interact with the Graphical User Interface.\n\n\t\tClass implementing the UDP version of the client protocol.\n\n\t\t.. note::\n\t\tYou must write the implementation of this class.\n\n\t\tEach instance must have at least the following attributes:\n\n\t\t.. attribute:: serverAddress\n\n\t\tThe IP address of the c2w server.\n\n\t\t.. attribute:: serverPort\n\n\t\tThe port number of the c2w server.\n\n\t\t.. attribute:: clientProxy\n\n\t\tThe clientProxy, which the protocol must use\n\t\tto interact with the Graphical User Interface.\n\n\t\t.. attribute:: lossPr\n\n\t\tThe packet loss probability for outgoing packets. Do\n\t\tnot modify this value! (It is used by startProtocol.)\n\n\t\t.. note::\n\t\tYou must add attributes and methods to this class in order\n\t\tto have a working and complete implementation of the c2w\n\t\tprotocol.\n\t\t\"\"\"\n\n #: The IP address of the c2w server.\n\t\tself.serverAddress = serverAddress\n #: The port number of the c2w server.\n\t\tself.serverPort = serverPort\n #: The clientProxy, which the protocol must use\n #: to interact with the Graphical User Interface.\n\t\tself.clientProxy = clientProxy\n\t\tself.c2wClientModel = c2wClientModel()\n\t\tself.lossPr = lossPr\n\t\tself.last_event_id =0\n\t\tself.seq = 0\n\t\tself.userID = 0\n\t\tself.roomID = 0\n\t\tself.dstRoomID = 0\n\t\tself.init = False\n\t\tself.messageType = 0x00\n\t\tself.movieList = []\n\t\tself.userList = []\n\t\tself.logged = False\n\t\tself.responses = []\n\t\tself.lastDGTreated = None\n\t\tself.logged = False\n\t\t\n\tdef incrementSeq(self) :\n\t\tif (self.seq > 65535) :\n\t\t\tself.seq = 0\n\t\telse :\n\t\t\tself.seq += 1\n \n\tdef startProtocol(self):\n\t\t\"\"\"\n\t\tDO NOT MODIFY THE FIRST TWO LINES OF THIS METHOD!!\n\n\t\tIf in doubt, do not add anything to this method. Just ignore it.\n\t\tIt is used to randomly drop outgoing packets if the -l\n\t\tcommand line option is used.\n\t\t\"\"\"\n\t\tself.transport = LossyTransport(self.transport, self.lossPr)\n\t\tDatagramProtocol.transport = self.transport\n\n\t\t\t\n\t#--------this function verifies every 60s if the user is connected. If he's not, the application is closed--------------\t\t\t\t\n\tdef verifyConnexion(self):\n\t\tif(self.connected == False):\n\t\t\tself.clientProxy.applicationQuit()\n\t\telse:\n\t\t\tself.connected = False\n\t\t\treactor.callLater(60, self.verifyConnexion)\n\t\n\t#GET_PING send a message to the server asking for the last event of the room where the user is\n\tdef getPing(self, initial):\n\t\tself.messageType = 0x4\n\t\tmsgLength = 4\n\t\tbuf = bytearray(10)\n\t\tlast_event_id_2fb = (self.last_event_id & int('111111111111111100000000',2)) >> 8 #retrieve two first bytes in event_id\n\t\tlast_event_id_lb = (self.last_event_id) & 255 #retrieve last byte in event_id\n\t\tstruct.pack_into('!BHBHHBB', buf, 0, self.messageType, self.seq, self.userID, msgLength, last_event_id_2fb, last_event_id_lb, self.roomID)\n\t\t\n\t\tif self.logged == True :\n\t\t\tself.transport.write(buf, (self.serverAddress, self.serverPort))\n\t\t\tseq = self.seq\n\t\t\tmsgType = self.messageType\n\t\t\tself.incrementSeq()\n\t\t\treactor.callLater(0.5, self.verifyResponse, buf, seq, msgType) # if we don't receive response after 500ms, the GET_PING request is resent\n\t\t\tif initial == True:\n\t\t\t\treactor.callLater(1, self.getPing, True)# this method is called every second, True means it's not a message retry, so it can call a new get ping after a second\n\t\t\telse:\n\t\t\t\tpass\n\t\telse :\n\t\t\tpass\n\t\n\t#split in groups of 254 the number of events to be asked to the server\n\tdef getEvents(self, numberOfEvents): \n\t\tnbIterations = math.ceil(numberOfEvents/254) #we calculate the number of times it will be necessary to ask for events eg: 300/254 = 1.18 -> 2 times \n\t\twhile(nbIterations != 0):\n\t\t\tif(numberOfEvents/254 >= 1):\n\t\t\t\tnbDemande = 254\n\t\t\t\tnumberOfEvents -= 254\n\t\t\telse:\n\t\t\t\tnbDemande = numberOfEvents\n\t\t\tself.events(nbDemande)\n\t\t\tnbIterations -= 1\n\t\n\t#pack and send to the server the GET_EVENTS request\n\tdef events(self, nbDemande) :\n\t\tself.messageType = 0x6\n\t\tmsgLength = 5\n\t\tbuf = bytearray(11)\n\t\tlast_event_id_2fb = (self.last_event_id & int('111111111111111100000000',2)) >> 8\n\t\tlast_event_id_lb = (self.last_event_id) & 255\n\t\tstruct.pack_into('!BHBHHBBB', buf, 0, self.messageType, self.seq, self.userID, msgLength, last_event_id_2fb, last_event_id_lb, nbDemande, self.roomID)\n\t\tself.transport.write(buf, (self.serverAddress, self.serverPort))\n\t\tseq = self.seq\n\t\tmsgType = self.messageType\n\t\tself.incrementSeq()\n\t\treactor.callLater(0.5, self.verifyResponse, nbDemande, seq, msgType) #after a half second, we call a function that checks if the response was received \n\t\n\t#PUT_LOGIN send a message to the server to inform it of the user's wish to enter the server\t\n\tdef sendLoginRequestOIE(self, userName):\n\t\t\"\"\"\n\t\t:param string userName: The user name that the user has typed.\n\n\t\tThe client proxy calls this function when the user clicks on\n\t\tthe login button.\n\t\t\"\"\"\n\t\tmoduleLogger.debug('loginRequest called with username=%s', userName)\n\t\tself.messageType = 0x00\n\t\tusernameLength = len(userName.encode('utf-8')) #len returns the number of characters \n\t\tmsgLength = usernameLength + 1 # 1 for UL field\n\t\tbuf = bytearray(7+usernameLength) #2 bytes for seq, 1 for userID,...\n\t\tstruct.pack_into('!BHBHB'+str(usernameLength)+'s', buf, 0, self.messageType, self.seq, self.userID, msgLength, usernameLength, userName.encode('utf-8')) \n\t\tself.transport.write(buf, (self.serverAddress, self.serverPort))\n\t\tseq = self.seq\n\t\tmsgType = self.messageType\n\t\tself.incrementSeq()\n\t\treactor.callLater(0.5, self.verifyResponse, userName, seq, msgType) #after a half second, we call a function that checks if the response was received\n\n\t#PUT_NEW_MESSAGE send a message to the server with the text the user has typed in the chatroom wether it is in the MAIN_ROOM or a MOVIE_ROOM\n\tdef sendChatMessageOIE(self, message):\n\t\t\"\"\"\n\t\t:param message: The text of the chat message.\n\t\t:type message: string\n\n\t\tCalled by the client proxy when the user has decided to send\n\t\ta chat message\n\n\t\t.. note::\n\t\t This is the only function handling chat messages, irrespective\n\t\t of the room where the user is. Therefore it is up to the\n\t\t c2wChatClientProctocol or to the server to make sure that this\n\t\t message is handled properly, i.e., it is shown only by the\n\t\t client(s) who are in the same room.\n\t\t\"\"\"\n\t\tself.messageType = 0x0E\n\t\tmsgLength = 1 + 2 + len(message) #1 byte for room_id, 2 for text length...\n\t\tbuf = bytearray(9+len(message)) #2 bytes for seq, 1 pour userID,...\n\t\tstruct.pack_into('!BHBHBH'+str(len(message))+'s', buf, 0, self.messageType, self.seq, self.userID, msgLength, self.roomID, len(message), message.encode('utf-8'))\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t #the result is saved in buf\n\t\tself.transport.write(buf, (self.serverAddress, self.serverPort))\n\t\tseq = self.seq\n\t\tmsgType = self.messageType\n\t\tself.incrementSeq()\n\t\treactor.callLater(0.5, self.verifyResponse, message, seq, msgType) #after a half second, we call a function that checks if the response was received\n\t\n\t#PUT_SWITCH_ROOM send a message to the server to inform it of the user's wish to change rooms\n\tdef sendJoinRoomRequestOIE(self, roomName):\n\t\t\"\"\"\n\t\t:param roomName: The room name (or movie title.)\n\n\t\tCalled by the client proxy when the user\n\t\thas clicked on the watch button or the leave button,\n\t\tindicating that she/he wants to change room.\n\n\t\t.. warning:\n\t\t\tThe controller sets roomName to\n\t\t\tROOM_IDS.MAIN_ROOM when the user\n\t\t\twants to go back to the main room.\n\t\t\"\"\"\n\t\tif (roomName == ROOM_IDS.MAIN_ROOM) :\n\t\t\tself.dstRoomID = 0\n\t\telse :\n\t\t\troom = self.c2wClientModel.getMovieByTitle(roomName) \n\t\t\tself.dstRoomID = room.movieId\n\t\tself.messageType = 0x0C\n\t\tmsgLength = 1 #1 for ROOM_ID\n\t\tbuf = bytearray(7)\n\t\tstruct.pack_into('!BHBHB', buf, 0, self.messageType, self.seq, self.userID, msgLength, self.dstRoomID)\n\t\tself.transport.write(buf, (self.serverAddress, self.serverPort))\n\t\tseq = self.seq\n\t\tmsgType = self.messageType\n\t\tself.incrementSeq()\n\t\treactor.callLater(0.5, self.verifyResponse, roomName, seq, msgType) #after a half second, we call a function that checks if the response was received\n\n\t#PUT_LOGOUT send a message to the server to inform it of the user's wish to leave the server\n\tdef sendLeaveSystemRequestOIE(self):\n\t\t\"\"\"\n\t\tCalled by the client proxy when the user\n\t\thas clicked on the leave button in the main room.\n\t\t\"\"\"\n\t\tself.messageType = 0x02\n\t\tmsgLength = 0\n\t\tbuf = bytearray(6) \n\t\tstruct.pack_into('!BHBH', buf, 0, self.messageType, self.seq, self.userID, msgLength)\n\t\tself.transport.write(buf, (self.serverAddress, self.serverPort))\n\t\tseq = self.seq\n\t\tmsgType = self.messageType\n\t\tself.incrementSeq()\n\t\treactor.callLater(0.5, self.verifyResponse, buf, seq, msgType) #after a half second, we call a function that checks if the response was received\n\n\t# GET_ROOMS send a message to the server to ask for the list of movies\t\n\tdef getRooms(self) :\n\t\tself.messageType = 0x08\n\t\tmsgLength = 2 #1 for FIRST_ROOM_ID 1 for NBR_ROOMS\n\t\tbuf = bytearray(8) \n\t\tstruct.pack_into('!BHBHBB', buf, 0, self.messageType, self.seq, self.userID, msgLength, 1, 255)\n\t\tself.transport.write(buf, (self.serverAddress, self.serverPort))\n\t\tseq = self.seq\n\t\tmsgType = self.messageType\n\t\tself.incrementSeq()\n\t\treactor.callLater(0.5, self.verifyResponse, buf, seq, msgType) #after a half second, we call a function that checks if the response was received\n\t\n\t#GET_USERS send a message to the user to ask for the list of users in the server (MAIN_ROOM) or in the room (MOVIE_ROOM)\n\tdef getUsers(self, roomID) :\n\t\tself.messageType = 0x0A\n\t\tmsgLength = 3 \n\t\tbuf = bytearray(9) \n\t\tstruct.pack_into('!BHBHBBB', buf, 0, self.messageType, self.seq, self.userID, msgLength, 1, 255, self.roomID)\n\t\tself.transport.write(buf, (self.serverAddress, self.serverPort))\n\t\tseq = self.seq\n\t\tmsgType = self.messageType\n\t\tself.incrementSeq()\n\t\treactor.callLater(0.5, self.verifyResponse, roomID, seq, msgType) #after a half second, we call a function that checks if the response was received\n\t\n\t#unpack the RESPONSE_USERS datagram and return the list of users received (userName, userRoom)\n\tdef unpackUsersList(self, datagram) :\n\t\tusersPack = struct.unpack('!BHBHB'+str(len(datagram)-7)+'s', datagram)\n\t\tnbUsers = usersPack[4]\n\t\tusers = usersPack[5] #USERS list (variable length)\n\t\tlistUsers = users\n\t\tuserTuples=[]\n\t\twhile (nbUsers != 0) :\n\t\t\tuser1 = struct.unpack('!BB'+str(len(listUsers)-2)+'s', listUsers) #separate USER_ID, UL and the rest\n\t\t\tuser11 = struct.unpack('!'+str(user1[1])+'sB'+str(len(user1[2])-user1[1]-1)+'s', user1[2]) #separate USERNAME, ROOM_ID and the rest\n\t\t\tuserID = user1[0]\n\t\t\tuserName = user11[0].decode('utf-8')\n\t\t\troomID = user11[1]\n\t\t\tif (roomID == 0) :\n\t\t\t\tuserRoom = ROOM_IDS.MAIN_ROOM\n\t\t\t\tmovieName = userRoom\n\t\t\telse :\n\t\t\t\tuserRoom = ROOM_IDS.MOVIE_ROOM\n\t\t\t\tif self.init == True : #for loggin initialisation, we just need to know if the user is in the main room or in the movie room\n\t\t\t\t\tmovieName = userRoom\n\t\t\t\telse :\n\t\t\t\t\tmovie = self.c2wClientModel.getMovieById(roomID)\n\t\t\t\t\tmovieName = movie.movieTitle\n\t\t\tuserTuples.append((userName, userRoom)) #add USERNAME and ROOM_ID to the list of pair\n\t\t\tuser=self.c2wClientModel.getUserByName(userName)\n\t\t\tif user != None :\n\t\t\t\tpass\n\t\t\telse :\n\t\t\t\tself.c2wClientModel.addUser(userName, userID, movieName) #store user informations\n\t\t\tnbUsers-=1\n\t\t\tlistUsers = user11[2] #make the initial packet equal to the rest, in order to retrieve the other users through further iterations\n\t\t\tself.c2wClientModel.updateUserChatroom(userName, userRoom)\n\t\t\tif (self.init == False) : \n\t\t\t\tself.clientProxy.userUpdateReceivedONE(userName, movieName) #won't be execute for the initial response user\n\t\t\telse :\n\t\t\t\tpass\n\t\treturn userTuples\n\t\n\t#unpack the RESPONSE_ROOMS datagram and return the list of movies received (movieTitle, movieIP, moviePort)\n\tdef unpackRoomsList(self, datagram) :\n\t\tmoviesPack = struct.unpack('!BHBHB'+str(len(datagram)-7)+'s', datagram)\n\t\tnbMovies = moviesPack[4]\n\t\tmovies = moviesPack[5]\n\t\tlistMovies = movies\t\n\t\tmoviesTriplets=[]\n\t\twhile (nbMovies != 0) :\n\t\t\tmovie1 = struct.unpack('!B4BHB'+str(len(listMovies)-8)+'s', listMovies) #separate ROOM_ID, IP, PORT_NUMBER, RNL and the rest\n\t\t\tmovieID = movie1[0]\n\t\t\tmoviePort = movie1[5]\n\t\t\tmovieIP = str(movie1[1])+\".\"+str(movie1[2])+\".\"+str(movie1[3])+\".\"+str(movie1[4])\n\t\t\tmovie11 = struct.unpack('!'+str(movie1[6])+'sB'+str(len(movie1[7])-movie1[6]-1)+'s', movie1[7]) #separate ROOM_NAME, NBR_USERS and the rest\n\t\t\tmovieTitle = movie11[0].decode('utf-8')\n\t\t\tmoviesTriplets.append((movieTitle, movieIP, moviePort)) #add ROOM_NAME, IP and PORT_NUMBER to the list of triplets\n\t\t\tself.c2wClientModel.addMovie(movieTitle, movieIP, moviePort, movieID) #store movie informations\n\t\t\tnbMovies-=1\n\t\t\tlistMovies = movie11[2] #make the initial packet equal to the rest, in order to retrieve the other videos through further iterations\n\t\tprint (moviesTriplets)\n\t\treturn moviesTriplets\n\t\n\t#unpack the RESPONSE_EVENTS datagram and execute the necessary updates\n\tdef unpackEvents(self, datagram) :\n\t\teventsPack = struct.unpack('!BHBHB'+str(len(datagram)-7)+'s', datagram) #separate MESSAGE_TYPE, SEQ_NUMBER, USER_ID, MESSAGE_LENGTH (header), NBR_EVENTS and the events\n\t\tnbEvents = eventsPack[4]\n\t\tevents = eventsPack[5]\n\t\twhile(nbEvents != 0) :\n\t\t\tevent1 = struct.unpack('!HBBBB'+str(len(events)-6)+'s', events) #separate EVENT_ID, EVENT_TYPE, ROOM_ID, USER_ID, and the rest\n\t\t\tself.last_event_id = (event1[0]<<8)|event1[1]\n\t\t\troomID = event1[3]\n\t\t\tuserID = event1[4]\n\t\t\teventType = event1[2]\n\t\t\t\n\t\t\t#MESSAGE event: MESSAGE_LENGTH, MESSAGE\n\t\t\tif (eventType==0x1) :\n\t\t\t\tevent11 = struct.unpack('!H'+str(len(event1[5])-2)+'s', event1[5]) #separate MESSAGE_LENGTH (chat) and the rest\n\t\t\t\tevent111 = struct.unpack('!'+str(event11[0])+'s'+str(len(event11[1])-event11[0])+'s', event11[1]) #separate MESSAGE and the rest\n\t\t\t\tmessage = event111[0].decode('utf-8')\n\t\t\t\tuser = self.c2wClientModel.getUserById(userID) #retrieve the user using USER_ID\n\t\t\t\tuserName = user.userName\n\t\t\t\tif userID != self.userID and self.roomID == roomID : #print the msg only if the message is from another user in the same room. (care of duplication)\n\t\t\t\t\tself.clientProxy.chatMessageReceivedONE(userName, message)\n\t\t\t\telse :\n\t\t\t\t\tpass\n\t\t\t\tevents = event111[1]\n\t\t\t\t\n\t\t\t#NEW_USER event: USERNAME_LENGTH, USERNAME\n\t\t\telif (eventType==0x2) :\n\t\t\t\tevent11 = struct.unpack('!B'+str(len(event1[5])-1)+'s', event1[5]) #separate UL and the rest\n\t\t\t\tevent111 = struct.unpack('!'+str(event11[0])+'s'+str(len(event11[1])-event11[0])+'s', event11[1]) #separate USERNAME and the rest\n\t\t\t\tif (roomID == 0) :\n\t\t\t\t\tuserRoom = ROOM_IDS.MAIN_ROOM\n\t\t\t\t\tmovieName= userRoom\n\t\t\t\telse :\n\t\t\t\t\tuserRoom = ROOM_IDS.MOVIE_ROOM\n\t\t\t\t\tmovie = self.c2wClientModel.getMovieById(roomID)\n\t\t\t\t\tmovieName = movie.movieTitle\n\t\t\t\tuserName = event111[0].decode('utf-8')\n\t\t\t\tuser=self.c2wClientModel.getUserByName(userName)\n\t\t\t\tif user != None : #prevent to add user if he exists, because we add user after response user.\n\t\t\t\t\tpass\n\t\t\t\telse :\n\t\t\t\t\tself.c2wClientModel.addUser(userName, userID, movieName) #store user informations\n\t\t\t\tself.c2wClientModel.updateUserChatroom(userName, userRoom)\n\t\t\t\tself.clientProxy.userUpdateReceivedONE(userName, movieName)\n\t\t\t\tevents = event111[1]\n\t\t\t\n\t\t\t#SWITCH_ROOM event: NEW_ROOM_ID\n\t\t\telif (eventType==0x3) :\n\t\t\t\tevent11 = struct.unpack('!B'+str(len(event1[5])-1)+'s', event1[5]) #separate NEW_ROOM_ID and the rest\n\t\t\t\tnewRoomID = event11[0]\n\t\t\t\tif (newRoomID == 0) :\n\t\t\t\t\troom = ROOM_IDS.MAIN_ROOM\n\t\t\t\t\tmovieName = room\n\t\t\t\telse :\n\t\t\t\t\troom = ROOM_IDS.MOVIE_ROOM\n\t\t\t\t\tmovie = self.c2wClientModel.getMovieById(newRoomID)\n\t\t\t\t\tmovieName = movie.movieTitle\n\t\t\t\tuser = self.c2wClientModel.getUserById(userID) #retrieve the user using USER_ID\t\n\t\t\t\tuserName = user.userName\n\t\t\t\tself.c2wClientModel.updateUserChatroom(userName, room)\n\t\t\t\tself.clientProxy.userUpdateReceivedONE(userName, movieName)\n\t\t\t\tevents = event11[1]\n\t\t\t\n\t\t\t#LOGOUT event:\n\t\t\telif (eventType==0x4) :\n\t\t\t\tuser = self.c2wClientModel.getUserById(userID) #retrieve the user using USER_ID\n\t\t\t\tuserName = user.userName\n\t\t\t\tself.clientProxy.userUpdateReceivedONE(userName, ROOM_IDS.OUT_OF_THE_SYSTEM_ROOM)\n\t\t\t\tself.c2wClientModel.removeUser(userName)\n\t\t\t\tevents = event1[5]\n\t\t\telse :\n\t\t\t\tpass\n\t\t\tnbEvents-=1\n\t\t\t\n\tdef leaveApplication(self):\n\t\tself.clientProxy.connectionRejectedONE(\"Connexion lost\")\n\t\treactor.callLater(2, self.clientProxy.applicationQuit)\n\t\tself.logged = False\n\n\t#identify the response message type and execute the necessary actions\n\tdef treatDatagram(self, datagram) :\n\t\treceived = struct.unpack('!BH'+str(len(datagram)-3)+'s', datagram)\n\t\tmsgType = received[0]\n\n\t\t#RESPONSE_LOGIN\n\t\tif (msgType == 0x01) :\n\t\t\treceived = struct.unpack('!BHBHBBHB', datagram) #unpack the received data\n\t\t\tstatus_code = received[4]\n\t\t\t#successful login\n\t\t\tif (status_code==0x00) :\n\t\t\t\tself.init = True\n\t\t\t\tself.logged = True\n\t\t\t\tself.last_event_id = (received[6]<<8)|received[7] #shift the 2 first bytes of the last_event_id to the left and apply a bitwise OR with the last byte\n\t\t\t\tself.userID = received[5]\n\t\t\t\tself.getUsers(self.roomID)\n\t\t\t\tself.connectedTimer = reactor.callLater(60, self.leaveApplication) #if no data received every 60s, we conclude that the connexion is lost\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# connectedTimer is reinitialised after each data reception\n\t\t\t#unsuccessful login\n\t\t\telif (status_code==0x01) :\n\t\t\t\tself.clientProxy.connectionRejectedONE(\"unknown error\")\n\t\t\telif (status_code==0x02) :\n\t\t\t\tself.clientProxy.connectionRejectedONE(\"too many users\")\n\t\t\telif (status_code==0x03) :\n\t\t\t\tself.clientProxy.connectionRejectedONE(\"invalid username\")\n\t\t\telif (status_code==0x04) :\n\t\t\t\tself.clientProxy.connectionRejectedONE(\"username not available\")\n\t\t\telse :\n\t\t\t\tself.clientProxy.connectionRejectedONE(\"error\")\n\t\t\t\n\t\t#RESPONSE_LOGOUT\n\t\telif (msgType == 0x03) :\n\t\t\treceived = struct.unpack('!BHBHB', datagram) #unpack the received data\n\t\t\tstatus_code = received[4]\n\t\t\tif (status_code == 0) :\n\t\t\t\tself.clientProxy.leaveSystemOKONE()\n\t\t\t\tself.logged = False\n\t\t\t\tself.connectedTimer.cancel() #stop timmer\n\t\t\telse :\t\n\t\t\t\tpass\n\t\t\t\n\t\t#RESPONSE_PING get the difference betwen server's and user's last event id's\n\t\telif (msgType == 0x05) :\n\t\t\treceived = struct.unpack('!BHBHHB', datagram) #unpack the received data containing last event id\n\t\t\tlast_event_id = (received[4]<<8)|received[5] \n\t\t\tif (last_event_id>self.last_event_id): #if server last_event_id is greater than the client\n\t\t\t\tdiff = last_event_id - self.last_event_id\n\t\t\t\tself.getEvents(diff) #client asks for the remaining events\n\t\t\telif (last_event_id self.lastDGTreated + 1 :\n\t\t\tself.responses.append((msgType, seq, datagram))\n\t\telse :\n\t\t\tpass\n\n\t#check if the response was received, called in general 500ms after sending the message\n\tdef verifyResponse(self, parameter, respSeq, messageType): #respSeq is used to be sure that the received response is the expected \n\t\t#the case in which the lastDGTreated is still uninitialized, that means the login response wasn't received. We then resend the request\n\t\tif respSeq == 0 and self.lastDGTreated == None :\n\t\t\tself.seq -= 1\n\t\t\tself.sendLoginRequestOIE(parameter)\n\t\t#the case in which the lastDGTreated already surpassed the seq number we are checking. It means the datagram was already received and executed, so we don't have to do anything\n\t\telif respSeq <= self.lastDGTreated :\n\t\t\treturn\n\t\t#the case in which the lastDGTreated is inferior to the seq number we are checking. It means the datagram wasn't executed yet, so we have to search it in the list\n\t\telif respSeq > self.lastDGTreated :\n\t\t\ti = 0\n\t\t\tfor item in self.responses :\n\t\t\t\t#the case in which the response datagram was already received, but wasn't executed, we have to wait for the messages with an inferior seq number to be executed \n\t\t\t\tif (item[1] == respSeq):\n\t\t\t\t\treturn\n\t\t\t\telse :\n\t\t\t\t\ti += 1\n\t\t\t#the case in which the response datagram wasn't received yet (it's not in the list), we have to resend the request \n\t\t\ttempSeq = self.seq\n\t\t\tself.seq = respSeq #if we didn't receive the expected seq response, we resend the request with the expected seq (respSeq)\n\t\t\tprint(self.seq)\n\t\t\tif(messageType == 0x02):\n\t\t\t\tself.sendLeaveSystemRequestOIE()\n\t\t\telif(messageType == 0x04):\n\t\t\t\tself.getPing(False) #false parameter means it is a retry, so we don't call a new get ping after a second\n\t\t\telif(messageType == 0x06):\n\t\t\t\tself.getEvents(parameter)\n\t\t\telif(messageType == 0x08):\n\t\t\t\tself.getRooms()\n\t\t\telif(messageType == 0x0A):\n\t\t\t\tself.getUsers(self.roomID)\n\t\t\telif(messageType == 0x0C):\n\t\t\t\tself.sendJoinRoomRequestOIE(parameter)\n\t\t\telif(messageType == 0x0E):\n\t\t\t\tself.sendChatMessageOIE(parameter)\n\t\t\telse:\n\t\t\t\tpass\n\t\t\tself.seq = tempSeq #continue the code with our current seq\n\t\telse :\n\t\t\tpass\n","sub_path":"protocol/udp_chat_client.py","file_name":"udp_chat_client.py","file_ext":"py","file_size_in_byte":25140,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"422885391","text":"from base_auth_test import *\r\n\r\nclass TestFeed(BaseAuthedTestCase):\r\n\r\n def test_feed(self):\r\n empty_list = []\r\n person_me = self.get('/Person/me')\r\n person_me_list_of_dictionaries = person_me['data']['claims']\r\n\r\n for item in person_me_list_of_dictionaries:\r\n empty_list.append(item['values'])\r\n\r\n final_list = [item for sublist in empty_list for item in sublist]\r\n decoded_list = [x.encode('utf-8') for x in final_list]\r\n\r\n dict_for_clas_marking_period = self.dict_for_clas_marking_period\r\n dict_for_marking_period_date_startdate_endate = self.dict_for_marking_period_date_startdate_endate\r\n\r\n list_for_class_id = []\r\n\r\n #general call\r\n get_grades_all = self.get('/Grading/TeacherSummary?' + 'teacherId=' + str(self.teacher_id))\r\n get_grades_all_data = get_grades_all['data']\r\n for k in get_grades_all_data:\r\n for key, value in k['class'].iteritems():\r\n if key == 'id':\r\n list_for_class_id.append(value)\r\n\r\n list_for_student_id =[]\r\n\r\n list_for_standards_id =[]\r\n\r\n self.list_of_standards_from_dict = []\r\n\r\n for one_class in list_for_class_id:\r\n if one_class == 13806 or one_class == 14011 or one_class == 14436:\r\n pass\r\n else:\r\n class_summary_grids = self.get('/Grading/ClassStandardGrids?' + 'classId=' + str(one_class))\r\n class_summary_grids = class_summary_grids['data']\r\n\r\n # veryfying if the class has students\r\n for key, value in class_summary_grids.iteritems():\r\n if key == 'currentstandardgradinggrid':\r\n for key2, value2 in value.iteritems():\r\n if key2 == 'gradingitems':\r\n if len(value2) > 0:\r\n if one_class in self.dic_for_class_allowed_standard: #verifying if teacher can put standards. Verifying if the area is not disabled.\r\n self.list_of_standards_from_dict = self.dic_for_class_allowed_standard[one_class]\r\n\r\n # getting list of standards id\r\n for y in class_summary_grids['currentstandardgradinggrid']['gradingitems']:\r\n list_for_standards_id.append(y['standard']['standardid'])\r\n\r\n # getting list of students id\r\n for y in class_summary_grids['currentstandardgradinggrid']['students']:\r\n list_for_student_id.append(y['studentinfo']['id'])\r\n\r\n for key, value in class_summary_grids.iteritems():\r\n if key == 'gradingperiods':\r\n for i in value:\r\n for key2, value2 in i.iteritems():\r\n if key2 == 'id':\r\n random_student_id = random.choice(list_for_student_id)\r\n random_standard_id = random.choice(list_for_standards_id)\r\n random_alpha_grade_id = random.choice(self.list_of_standards_from_dict)\r\n\r\n self.get('/Grading/UpdateStandardGrade?' + \"classId=\" + str(\r\n one_class) + \"&gradingPeriodId=\" + str(value2) +\r\n \"&studentId=\" + str(random_student_id) +\r\n \"&standardId=\" + str(random_standard_id)+\r\n '&alphaGradeId=' + str(random_alpha_grade_id) + '¬e=')\r\n\r\n # verifying that student has a correct score and a grading comment\r\n class_summary_grids = self.get(\r\n '/Grading/ClassStandardGrids?' + 'classId=' + str(one_class))\r\n class_summary_grids_data = class_summary_grids['data']\r\n\r\n for k in class_summary_grids_data['currentstandardgradinggrid']['gradingitems']:\r\n if k['standard']['standardid'] == random_standard_id:\r\n for p in k['items']:\r\n if p['studentid'] == random_student_id:\r\n self.assertEqual(p['gradeid'],\r\n random_alpha_grade_id)\r\n break\r\n #break\r\n\r\n list_for_student_id = []\r\n list_for_standards_id = []\r\n self.list_of_standards_from_dict = []\r\n\r\nif __name__ == '__main__':\r\n unittest.main()\r\n","sub_path":"Chalkable.AutomatedTests/tests/teacher/grades/grades_selected_class_standards_grid_letter.py","file_name":"grades_selected_class_standards_grid_letter.py","file_ext":"py","file_size_in_byte":5669,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"367538916","text":"\"\"\"\nCheck If All 1's Are at Least Length K Places Away\nGiven an array nums of 0s and 1s and an integer k, return True if all 1's are at least k places away from each other, otherwise return False.\n\n\n\nExample 1:\n\n\n\nInput: nums = [1,0,0,0,1,0,0,1], k = 2\nOutput: true\nExplanation: Each of the 1s are at least 2 places away from each other.\nExample 2:\n\n\n\nInput: nums = [1,0,0,1,0,1], k = 2\nOutput: false\nExplanation: The second 1 and third 1 are only one apart from each other.\nExample 3:\n\nInput: nums = [1,1,1,1,1], k = 0\nOutput: true\nExample 4:\n\nInput: nums = [0,1,0,1], k = 1\nOutput: true\n\n\nConstraints:\n\n1 <= nums.length <= 105\n0 <= k <= nums.length\nnums[i] is 0 or 1\n Hide Hint #1\nEach time you find a number 1, check whether or not it is K or more places away from the next one. If it's not, return false.\n\"\"\"\nfrom cmath import inf\nfrom typing import List\n\n\nclass Solution:\n def kLengthApart(self, nums: List[int], k: int) -> bool:\n # Solution 1 - 576 ms\n \"\"\"\n left = 0\n flag = 0\n res = float(inf)\n for idx, num in enumerate(nums):\n if num == 1:\n if flag == 0: # first time we meet 1\n flag = 1\n left = idx\n else:\n dist = idx - left - 1\n left = idx\n res = min(res, dist)\n if res < k:\n return False\n return True\n \"\"\"\n # Solution 2 - 520 ms\n if not nums or len(nums) <= 0 or k <= 0:\n return True\n\n prev_i = -1\n for i, n in enumerate(nums):\n if n == 0:\n continue\n\n if prev_i == -1:\n prev_i = i\n continue\n\n if i - prev_i - 1 < k:\n return False\n\n prev_i = i\n return True\n\n\n# Main Call\nnums = [1, 0, 0, 0, 1, 0, 0, 1]\nk = 2\n\nsolution = Solution()\nprint(solution.kLengthApart(nums, k))","sub_path":"src/arrays/kLengthApart.py","file_name":"kLengthApart.py","file_ext":"py","file_size_in_byte":1970,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"115990478","text":"class Solution(object):\n def angleClock(self, hour, minutes):\n \"\"\"\n :type hour: int\n :type minutes: int\n :rtype: float\n \"\"\"\n hourAngle = (hour%12)*30 + 30*(minutes / float(60))\n minuteAngle = (minutes/float(5))*30\n \n res = abs(hourAngle-minuteAngle)\n \n if res > 180:\n res = 360 - res\n \n return res","sub_path":"1344-Angle Between Hands of a Clock.py","file_name":"1344-Angle Between Hands of a Clock.py","file_ext":"py","file_size_in_byte":402,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"379072640","text":"\n# coding: utf-8\n\nimport cStringIO\nimport codecs\nimport csv\nimport decimal\n\n\nclass UnicodeWriter:\n \"\"\"\n A CSV writer which will write rows to CSV file \"f\",\n which is encoded in the given encoding.\n \"\"\"\n\n def __init__(self, f, dialect=csv.excel, encoding=\"utf-8\", **kwds):\n # Redirect output to a queue\n self.queue = cStringIO.StringIO()\n self.writer = csv.writer(self.queue, dialect=dialect, **kwds)\n self.stream = f\n self.encoder = codecs.getincrementalencoder(encoding)()\n\n def writerow(self, row):\n self.writer.writerow([s.encode(\"utf-8\") for s in row])\n # Fetch UTF-8 output from the queue ...\n data = self.queue.getvalue()\n data = data.decode(\"utf-8\")\n # ... and reencode it into the target encoding\n data = self.encoder.encode(data)\n # write to the target stream\n self.stream.write(data)\n # empty queue\n self.queue.truncate(0)\n\n def writerows(self, rows):\n for row in rows:\n self.writerow(row)\n\n\nclass Utils:\n def __init__(self):\n self\n\n def replace_decimals(self, obj):\n if isinstance(obj, list):\n for i in xrange(len(obj)):\n obj[i] = self.replace_decimals(obj[i])\n return obj\n elif isinstance(obj, dict):\n for k in obj.iterkeys():\n obj[k] = self.replace_decimals(obj[k])\n return obj\n elif isinstance(obj, decimal.Decimal):\n if obj % 1 == 0:\n return int(obj)\n else:\n return float(obj)\n else:\n return obj\n","sub_path":"Code/classification/utilCsv.py","file_name":"utilCsv.py","file_ext":"py","file_size_in_byte":1633,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"320141797","text":"script_version = \"Script Version 1.0\" \r\nscript_date = \"Script Date : 06-25-2017\"\r\n\r\nprint(\"Hello There!\")\r\nprint(script_version)\r\nprint(script_date)\r\nimport datetime\r\nimport time\r\nimport RPi.GPIO as GPIO\r\nimport random\r\nfrom shutil import copyfile\r\n\r\nGPIO.setmode(GPIO.BCM)\r\nGPIO.setwarnings(False)\r\n\r\n\r\nGPIO_ON1 = 15\r\nGPIO_OFF1 = 18\r\nGPIO_ON2 = 4\r\nGPIO_OFF2 = 17\r\nGPIO_ON3 = 27\r\nGPIO_OFF3 = 22\r\n\r\n\r\nGPIO.setup(GPIO_ON1 , GPIO.OUT)\r\nGPIO.setup(GPIO_OFF1, GPIO.OUT)\r\nGPIO.setup(GPIO_ON2 , GPIO.OUT)\r\nGPIO.setup(GPIO_OFF2, GPIO.OUT)\r\nGPIO.setup(GPIO_ON3 , GPIO.OUT)\r\nGPIO.setup(GPIO_OFF3, GPIO.OUT)\r\n\r\nGPIO.output(GPIO_ON1, GPIO.HIGH)\r\nGPIO.output(GPIO_OFF1, GPIO.HIGH)\r\nGPIO.output(GPIO_ON2, GPIO.HIGH)\r\nGPIO.output(GPIO_OFF2, GPIO.HIGH)\r\nGPIO.output(GPIO_ON3, GPIO.HIGH)\r\nGPIO.output(GPIO_OFF3, GPIO.HIGH)\r\n\r\nglobal current\r\nglobal G_on_time\r\nglobal G_off_time\r\nglobal G_range\r\n\r\n#-----------------------------------------------------\r\ndef log(stamp):\r\n\ttxt = str(datetime.datetime.now()) + ' : ' + str(stamp) + '\\r\\n'\r\n\tfile = open(tempFile, \"a\")\r\n\tfile.write(txt)\r\n\tfile.close()\r\n\tcopyfile(tempFile, '/home/pi/eesh/log.txt')\r\n\tprint(stamp)\r\n#-------------------------------------------------------\r\ntempFile = 'TemporaryFile.txt'\r\nfile = open(tempFile, \"w\")\r\nfile.close()\r\n\r\n\r\n#=======================================================\t\r\nlog(str(datetime.datetime.now()))\r\n#-----------------------------------------------\r\n#------GIVE VALUE IN 24 HOUR CLOCK--------------\r\n#Example = 0800 == 8:00am\r\n#Example = 81 == 8:01am\r\n#Example = 830 == 8:30am\r\n#Example = 2250 == 10:50pm\r\n\r\nG_on_time = raw_input(\"On_time?\")\r\nG_off_time = raw_input(\"Off_time?\")\r\nG_range = int(raw_input(\"range?\"))\r\n\r\n#-----------------------------------------------\t\r\n#----------------------------------------------- \r\nclass lamp:\r\n\t\r\n\t#-----------------------------------------------\r\n\tdef __init__(self, GPIO_ON, GPIO_OFF, name):\r\n\t\tglobal G_on_time\r\n\t\tglobal G_off_time\r\n\t\tself.name = name\r\n\t\tself.GPIO_ON = GPIO_ON\r\n\t\tself.GPIO_OFF = GPIO_OFF\r\n\t\tself.reset_time(G_on_time, G_off_time)\r\n\t\tself.isItOn = False\r\n\t\r\n\tdef reset_time(self, timeOn, timeOff):\r\n\t\tglobal G_range\r\n\t\ttimeOnHour = int(timeOn[:2])\r\n\t\ttimeOnMinute = int(timeOn[-2:])\r\n\t\ttimeOffHour = int(timeOff[:2])\r\n\t\ttimeOffMinute = int(timeOff[-2:])\r\n\t\trange = random.randrange(0, G_range)\r\n\t\ttimeOn = datetime.datetime(2004,12,18,timeOnHour,timeOnMinute) # year, month, date, hour, min, sec\r\n\t\ttimeOff = datetime.datetime(2004,12,18,timeOffHour,timeOffMinute) # year, month, date, hour, min, sec\r\n\t\tself.on_time = timeOn + datetime.timedelta(0,0,0,0,range,0,0) # days, seconds, microseconds, milliseconds, minutes, hours, weeks\r\n\t\trange = random.randrange(0, G_range)\r\n\t\tself.off_time = timeOff + datetime.timedelta(0,0,0,0,range,0,0) # days, seconds, microseconds, milliseconds, minutes, hours, weeks\r\n\t\tlog(\"Light in \" + self.name + \" will turn on at \" + str(self.on_time.time()) + \"!\")\r\n\t\tlog(\"Light in \" + self.name + \" will turn off at \" + str(self.off_time.time()) + \"!\")\r\n\t\t\r\n\t\t\r\n\tdef turn_on(self):\r\n\t\tif self.isItOn == True:\r\n\t\t\treturn\r\n\t\tGPIO.output(self.GPIO_ON, GPIO.LOW)\r\n\t\ttime.sleep(1)\r\n\t\tGPIO.output(self.GPIO_ON, GPIO.HIGH)\r\n\t\tself.isItOn = True\r\n\t\tlog(\"At \"+ str(datetime.datetime.now()) + \" light in \" + self.name + \" turned on\")\r\n\t\r\n\tdef turn_off(self):\r\n\t\tglobal G_on_time\r\n\t\tglobal G_off_time\r\n\t\tif self.isItOn == False:\r\n\t\t\treturn\r\n\t\tGPIO.output(self.GPIO_OFF, GPIO.LOW)\r\n\t\ttime.sleep(1)\r\n\t\tGPIO.output(self.GPIO_OFF, GPIO.HIGH)\r\n\t\tself.isItOn = False\r\n\t\tlog(\"At \"+ str(datetime.datetime.now()) + \" light \" + self.name + \" turned off\")\r\n\t\tself.reset_time(G_on_time, G_off_time)\r\n\t\t\r\n\t\t\r\n\tdef isItTimeToTurnOn(self):\r\n\t\tglobal current\r\n\t\tgethour()\r\n\t\tif current == self.on_time:\r\n\t\t\treturn True\r\n\t\treturn False \r\n\t\t\r\n\tdef isItTimeToTurnOff(self):\r\n\t\tglobal current\r\n\t\tgethour()\r\n\t\tif current == self.off_time:\r\n\t\t\treturn True\r\n\t\treturn False \r\n\t\t\r\n#------------------------------------------------\r\n#-----------------END OF CLASS-------------------\r\n#------------------------------------------------ \t\r\ndef gethour():\r\n\tglobal current\r\n\tnow = datetime.datetime.now()\r\n\t#print now.year, now.month, now.day, now.hour, now.minute, now.second\r\n\thour2 = int(now.hour)\r\n\tminute = int(now.minute)\r\n\tcurrent = datetime.datetime(2004,12,18,hour2,minute)\r\n\t#hour = hour2 + minute\r\n\t#print (hour)\r\n\treturn\r\n#-----------------------------------------------\r\n\r\n#-----------------------------------------------\r\n#def check_time():\r\n#\tif len(str(on_time) < 4:\r\n#\t\t\r\n#-----------------------------------------------\r\ndef blink_light():\r\n\tGPIO.output(GPIO_OFF1,GPIO.HIGH)\r\n\ttime.sleep(0.5)\r\n\tGPIO.output(GPIO_OFF1,GPIO.LOW)\r\n\ttime.sleep(0.5)\r\n\tGPIO.output(GPIO_ON1,GPIO.HIGH)\r\n\ttime.sleep(0.5)\r\n\tGPIO.output(GPIO_ON1,GPIO.LOW)\r\n\treturn\r\n#----------------------------------------------- \r\ndef turnAllOn():\r\n\tlamp1.turn_on()\r\n\tlamp2.turn_on()\r\n\tlamp3.turn_on()\r\n#-----------------------------------------------\r\ndef turnAllOff():\r\n\tlamp1.turn_off()\r\n\tlamp2.turn_off()\r\n\tlamp3.turn_off()\r\n#------------------------------------------------\r\n#on_time = [on_time - 15, on_time - 14, on_time - 13, on.time - 12, on.time - 11, on.time - 10, on.time - 9, on.time - 8, on.time - 7, on.time - 6, on.time - 5, on.time - 4, on.time - 3, on.time - 2, on.time - 1, on.time, on.time + 1, on.time + 2, on.time + 3, on.time + 4, on.time + 5, on.time + 6, on.time + 7, on.time + 8, on.time, on.time + 9, on.time + 10, on.time + 11, on.time + 12, on.time + 13, on.time + 14, on.time + 15]\r\nlamp1 = lamp(GPIO_ON1, GPIO_OFF1, \"Living_Room\")\r\nlamp2 = lamp(GPIO_ON2, GPIO_OFF2, \"Den\")\r\nlamp3 = lamp(GPIO_ON3, GPIO_OFF3, \"Bedroom\")\r\n\r\n#light = [1, 2, 3]\r\n#light = random.choice(light)\r\n\r\n#blink_light()\r\n\r\n#on_time = random.randrange(on_time, on_time + 30)\r\n\r\n#off_time = random.randrange(off_time, off_time + 30)\r\n\r\ngethour()\r\n#print(hour)\r\n#log(G_on_time)\r\n#log(G_off_time)\r\n\r\n\r\n\r\nwhile 1:\r\n\t\r\n\ttime.sleep(1)\r\n\t\r\n\tif lamp1.isItTimeToTurnOn() == True:\r\n\t\tlamp1.turn_on()\r\n\t\t\r\n\tif lamp2.isItTimeToTurnOn() == True:\r\n\t\tlamp2.turn_on()\r\n\t\t\r\n\tif lamp3.isItTimeToTurnOn() == True:\r\n\t\tlamp3.turn_on()\r\n\t\t\r\n\tif lamp1.isItTimeToTurnOff() == True:\r\n\t\tlamp1.turn_off()\r\n\t\r\n\tif lamp2.isItTimeToTurnOff() == True:\r\n\t\tlamp2.turn_off()\r\n\r\n\tif lamp3.isItTimeToTurnOff() == True:\r\n\t\tlamp3.turn_off()\r\n\t\t\r\n\t\t\r\n#=========END OF SCRIPT===============#\r\n\r\n#----------------------------------------\r\n\t\t#int(timeOn1) = timeOn[:2]\r\n\t\t#int(timeOn3) = timeOn[:-2]\r\n\t\t#str(timeOn1) = int(timeOn1)\r\n\t\t#str(timeOn3) = int(timeOn3)\r\n\t\t#timeOn = timeOn1 + timeOn3\r\n\t\t#int(timeOn) = timeOn\r\n#------------------------------------------\r\n","sub_path":"light.py","file_name":"light.py","file_ext":"py","file_size_in_byte":6629,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"291114270","text":"f = open(\"input_day8.txt\")\n\ncmds = []\n\nfor line in f:\n cmd, arg = line.split(' ')\n\n sgn = arg[0]\n if sgn == '-' : \n sgn = -1\n else :\n sgn = 1\n\n arg = int(arg[1:])*sgn\n\n cmds.append((cmd, arg))\n\n# run the program\n\n\nchange_instruction_acc = 3\nwhile True:\n tmp_cmds = cmds.copy()\n change_instruction_counter = 0\n\n instruction_ptr = 0\n visited_instructions = []\n global_acc = 0\n\n while True:\n\n if instruction_ptr == len(cmds):\n print(global_acc)\n exit()\n\n instruction = tmp_cmds[instruction_ptr]\n \n if instruction_ptr in visited_instructions:\n break;\n\n visited_instructions.append(instruction_ptr)\n\n if instruction[0] == 'jmp' or instruction[0] == 'nop':\n change_instruction_counter+=1\n\n if change_instruction_counter == change_instruction_acc:\n change_instruction_counter+=1\n if instruction[0] == 'nop':\n instruction = ('jmp', instruction[1])\n else:\n instruction = ('nop', instruction[1])\n\n if instruction[0] == 'nop':\n instruction_ptr+=1 \n continue\n \n if instruction[0] == 'acc':\n global_acc += instruction[1]\n instruction_ptr+=1\n continue\n\n if instruction[0] == 'jmp':\n instruction_ptr += instruction[1]\n continue\n\n print(\"GOT BAD INSTRUCTION\" + instruction[0])\n\n \n change_instruction_acc+=1\n\n\n\n","sub_path":"AOC_day8.py","file_name":"AOC_day8.py","file_ext":"py","file_size_in_byte":1521,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"100289355","text":"import json\nimport re\n\nfrom unidecode import unidecode\nfrom urlparse import urlparse\n\nimport twitter_util as twu\n\nprefix = '/home/source'\n\nfrom pyspark import SparkContext\nsc = SparkContext()\n\ntweets = sc.textFile(prefix + \"/data/complete_tweets\").map(lambda a: json.loads(a))\ncompanies = sc.textFile(prefix + \"/data/companies_all\").map(lambda a: json.loads(a))\ndest = prefix + '/data/find_positions_account_result'\n\ndef Most_Common(lst):\n data = Counter(lst)\n return data.most_common(1)[0][0]\n\n\ndef check_name(tweet):\n if len(tweet['user']['name']) > 5:\n return [((twu.sort_string(tweet['user']['name']), tweet['user']['screen_name']),set([json.dumps(tweet)]))]\n else:\n return []\n\ndef dextract(tweet_tuple):\n name = tweet_tuple[0][0]\n screen_name = tweet_tuple[0][1]\n mentions = set()\n links = set()\n \n for a in tweet_tuple[1]:\n try:\n a = json.loads(a)\n \n mentions.add(a['user']['screen_name'])\n mentions |= set(a['text']['mentions'])\n mentions |= set(a['user']['description']['mentions'])\n links |= set(m['host'].lower() for m in a['text']['links'])\n links |= set(m['host'].lower() for m in a['user']['description']['links'])\n \n if a['user']['url'] is not None and a['user']['url'] is not '':\n links.add(twu.get_host(a['user']['url']).lower())\n except:\n return []\n\n return [(name,(screen_name,mentions,links))]\n\nres = tweets.flatMap(check_name).reduceByKey(lambda a,b: a | b).flatMap(dextract)\n\n\ndef to_flat(company):\n if 'positions' not in company:\n return []\n \n res = []\n accounts = []\n websites = []\n\n if 'social' in company:\n accounts += [x['account'] for x in company['social']['twitter']]\n if 'websites' in company:\n websites += [twu.get_host(x['website']).lower() for x in company['websites']]\n\n if len(accounts) + len(websites) == 0:\n return []\n \n for x in company['positions']:\n res += [(twu.sort_string(x['name']),((x['name'],company['id']),set(accounts),set(websites)))]\n \n return res\n\nres2 = companies.flatMap(to_flat)\n\nresult = res.join(res2)\n\ndef adjust(entry):\n return ((entry[1][1][0][0],entry[1][1][0][1],entry[1][0][0]),(list(entry[1][0][1] & entry[1][1][1]), list(entry[1][0][2] & entry[1][1][2])))\n\nfinal = result.map(adjust).filter(lambda a: len(a[1][0]) + len(a[1][1]) > 0)\n\n\nfinal.map(lambda a: json.dumps(a)).saveAsTextFile(dest, compressionCodecClass=\"org.apache.hadoop.io.compress.BZip2Codec\")\n\n\n\n\n\n","sub_path":"find_positions_account.py","file_name":"find_positions_account.py","file_ext":"py","file_size_in_byte":2583,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"77377329","text":"from flask import Flask, request, Response, make_response\n\napp = Flask(__name__) #__main__이 들어가게됨\napp. debug = True\n\n@app.route(\"/\") #도메인 경로 지정\ndef helloworld():\n return \"Hello Flask World!\" #response해줌\n\n@app.route(\"/ro\")\ndef ro():\n res = Response(\"Test\")\n res.headers.add('Program-Name','Test Response')\n res.set_data(\"This is Test Program.\")\n res.set_cookie(\"UserToken\",\"A12Bc9\")\n return make_response(res)\n\napp.run()","sub_path":"Study/Response.py","file_name":"Response.py","file_ext":"py","file_size_in_byte":467,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"58354253","text":"#!/usr/bin/python\nimport matplotlib.pyplot as plt\nfrom matplotlib.ticker import MultipleLocator, FormatStrFormatter\nimport instrument\nfrom pylab import *\n\n\n# Initialize\ndm = instrument.RigolDM3000(\"/dev/usbtmc0\")\nutil = instrument.Utility()\n\ndm.setNumberOfSamples(600)\ndm.setSamplingMethod(\"DCI\")\n\n \nlog = dm.datalog()\nutil.saveLogToFile(log, \"log.txt\")\n\n\n\nfig = figure(1, figsize=(20,5))\n\nmajorLocator = MultipleLocator(500)\nax = subplot(111)\n\nplt.plot(log['time'], log['data'])\n\nax.xaxis.set_major_locator(majorLocator)\n\nplt.show()\n","sub_path":"getDCCurrent.py","file_name":"getDCCurrent.py","file_ext":"py","file_size_in_byte":536,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"614064512","text":"from sys import argv\n\ndef load_motifs(filename):\n file=open(filename)\n seq=file.read().split(\"MOTIF\")\n seq=seq[1:]\n motifs={}\n meta={}\n for s in range(len(seq)):\n t=seq[s].strip().split(\"\\n\")\n motifs[int(t[0].split('_')[0])]=t[2:]\n meta[int(t[0].split('_')[0])]=t[0:2]\n for m in motifs:\n tdict={'A':[],'C':[],'G':[],'T':[],'E':[],}\n for pos in range(len(motifs[m])):\n tmp=motifs[m][pos].strip().split(\"\\t\")\n tdict['A']+=[float(tmp[0])]\n tdict['C']+=[float(tmp[1])]\n tdict['G']+=[float(tmp[2])]\n tdict['T']+=[float(tmp[3])]\n tdict['E']+=[float(tmp[4])]\n motifs[m]=tdict\n \n return motifs,meta\n\n\n## main program ##\n\ninputmeme=argv[1]\noutputmeme=argv[2]\n\nmotifs,meta=load_motifs(inputmeme)\n\nfor motif in motifs:\n for loc in range(len(motifs[motif]['A'])):\n #print loc\n motifs[motif]['C'][loc]=motifs[motif]['C'][loc]+motifs[motif]['E'][loc]\n motifs[motif]['E'][loc]=0.0\n\noutput=outputmeme\ntarget=open(output,'w')\nheader=\"MEME version 4.5\\nALPHABET= A,C,G,T,mC \\nstrands: + \\nBackground letter frequencies (from \\nA 0.295 C 0.205 G 0.205 T 0.295\\n\"\ntarget.write(header+'\\n')\nalphabet=['A','C','G','T','E']\nnewname=0\nfor m in sorted(motifs.keys()):\n h1='MOTIF '+str(newname)+\"_\"+'_'.join('\\n'.join(meta[m]).split('_')[1:])\n target.write(h1+'\\n')\n for i in range(len(motifs[m]['A'])):\n line=''\n for char in alphabet:\n line+=str(motifs[m][char][i])+'\\t'\n line=line.strip()\n target.write(line+'\\n')\n target.write('\\n')\n newname+=1\ntarget.close()\n","sub_path":"analysis_scripts/demethylate_memefiles_typeE.py","file_name":"demethylate_memefiles_typeE.py","file_ext":"py","file_size_in_byte":1650,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"195687013","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 ('links', '0003_link_title'),\n ]\n\n operations = [\n migrations.RemoveField(\n model_name='tag',\n name='links',\n ),\n migrations.AddField(\n model_name='link',\n name='last_visit_date',\n field=models.DateTimeField(null=True, blank=True),\n preserve_default=True,\n ),\n migrations.AddField(\n model_name='link',\n name='tags',\n field=models.ManyToManyField(to='links.Tag'),\n preserve_default=True,\n ),\n migrations.AddField(\n model_name='tag',\n name='thumbnail_url',\n field=models.URLField(null=True, blank=True),\n preserve_default=True,\n ),\n migrations.AlterField(\n model_name='link',\n name='rating',\n field=models.IntegerField(editable=False),\n preserve_default=True,\n ),\n migrations.AlterField(\n model_name='link',\n name='thumbnail_url',\n field=models.URLField(null=True, blank=True),\n preserve_default=True,\n ),\n migrations.AlterField(\n model_name='link',\n name='visit_count',\n field=models.IntegerField(editable=False),\n preserve_default=True,\n ),\n ]\n","sub_path":"speeddial/links/migrations/0004_auto_20150204_1858.py","file_name":"0004_auto_20150204_1858.py","file_ext":"py","file_size_in_byte":1514,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"610665810","text":"from rest_framework import mixins, filters\nfrom rest_framework.permissions import IsAuthenticatedOrReadOnly\nfrom rest_framework.viewsets import GenericViewSet\n\nfrom restapi.models import Prezi\nfrom restapi.serializers import PreziSerializer\n\n\nclass BaseAPIView(mixins.RetrieveModelMixin,\n mixins.UpdateModelMixin,\n mixins.ListModelMixin,\n GenericViewSet):\n \"\"\"\n An API view that is restricted to getting a single instance, listing all\n instances and updating an instance if authenticated.\n \"\"\"\n pass\n\n\nclass PreziAPIView(BaseAPIView):\n\n serializer_class = PreziSerializer\n filter_backends = (filters.SearchFilter,)\n search_fields = ('title',)\n permission_classes = (IsAuthenticatedOrReadOnly,)\n\n def get_queryset(self):\n queryset = Prezi.objects.all()\n order = self.request.query_params.get('order', None)\n if order and order.lower() == 'asc':\n return queryset.order_by('created_at')\n else:\n # order by newest first by default\n return queryset.order_by('-created_at')\n","sub_path":"restapi/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1113,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"261083476","text":"import os\nimport csv\nimport json\nimport numpy as np\n\nfrom tkinter.filedialog import askopenfilename, askopenfilenames\n\nfrom process_FWM import get_pump_and_signal_peak\nfrom process_FWM import get_signal_and_idler_peak\nfrom process_FWM import compute_delta_beta\nfrom process_FWM import compute_gamma\n\nfrom process_file import split_path\nfrom process_file import read_parameter_file\nfrom process_file import plot_beta_gamma\n\nprint(\"Enter the input spectrum file: \")\ninput_file_path = askopenfilename(initialdir='~/FWM', filetypes=[(\"Input Spectrum files\", \"*.SPE\")])\n\ndirectory, filename, extension = split_path(input_file_path)\npump_wavelength, input_pump_power, input_signal_wavelength, input_signal_power = \\\n get_pump_and_signal_peak(input_file_path)\n\njson_file_path = os.path.join(directory,'parameter.json')\nif not os.path.exists(json_file_path):\n print(\"parameter.json doest not exist\")\n exit()\n\njson_file = open(json_file_path)\njsonData = json.loads(json_file.read())\n\nalpha_db = jsonData[\"alpha_dB\"]\ndispersion_slope = jsonData[\"DS(ps/nm2km)\"]\nlength = jsonData[\"Length(km)\"]\nlambda0 = jsonData[\"Lambda0(nm)\"]\njson_file.close()\n\noutput_file_tuple = askopenfilenames(initialdir=directory, title='Choose spectrum files: (Shift for ease selection)')\n\nresult_file_path = os.path.join(directory, \"result1.csv\")\n\nwith open(result_file_path, 'w') as csv_file:\n writer = csv.writer(csv_file, delimiter=',')\n\n writer.writerow(['filename', 'pump_wavelength(nm)', 'input_pump_power(dBm)', 'signal_wavelength(nm)',\n 'input_signal_power(dBm)', 'idler_wavelength(nm)', 'output_idler_power(dBm)', 'delta_beta(/km)',\n 'etta', 'gamma(1/W.km)'])\n\n for filename in output_file_tuple:\n print(\"Filename = \", filename)\n\n full_path = os.path.join(directory, filename)\n signal_wavelength, output_signal_power, output_idler_wavelength, output_idler_power = \\\n get_signal_and_idler_peak(full_path)\n\n delta_beta = compute_delta_beta(dispersion_slope, lambda0, pump_wavelength, signal_wavelength)\n etta, gamma = compute_gamma(alpha_db, length, delta_beta, input_pump_power, input_signal_power,\n output_idler_power)\n\n writer.writerow([filename, pump_wavelength, input_pump_power, signal_wavelength, input_signal_power,\n output_idler_wavelength, output_idler_power, delta_beta, etta, gamma])\ncsv_file.close()\n\nplot_beta_gamma(result_file_path)\n\n\n\n\n\n\n\n\n","sub_path":"main_code.py","file_name":"main_code.py","file_ext":"py","file_size_in_byte":2499,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"598493089","text":"from django.shortcuts import render\n# Create your views here.\n\nimport os\nfrom datetime import *\nfrom io import BytesIO\n\nfrom django.http import HttpResponse\nfrom django.template.loader import get_template\n\nfrom .forms import RegisterStudentForm, LoginStudentForm, FeesApplicationForm\n\nfrom .router import *\n\nfrom django.contrib.auth import authenticate, login, logout\n\nfrom django.contrib.auth.decorators import login_required\nfrom .models import Student, Admin, FeesNotification, FeesPayment\nfrom django.utils.timezone import localtime, now\n\nfrom xhtml2pdf import pisa\n\n\ndef homepage(request):\n message = None\n if 'message' in request.session:\n message = request.session['message']\n request.session['message'] = None\n return render(request, 'examApplication/home_page.html', {'message': message})\n\n\ndef register_student(request):\n\n if request.method == \"POST\":\n form = RegisterStudentForm(request.POST)\n if form.is_valid():\n form.save()\n request.session['message'] = 'Registration Successful, Now you can login'\n return redirect(\"home_page\")\n else:\n form = RegisterStudentForm()\n\n return render(request, 'examApplication/student/register.html', {'form': form})\n\n\ndef login_student(request):\n if is_logged_in(request):\n return handle_already_logged_in_error(request)\n\n message = None\n if 'message' in request.session:\n message = request.session['message']\n request.session['message'] = None\n print(\"ok i am executed, \")\n\n error = None\n\n if request.method == \"POST\":\n form = LoginStudentForm(request.POST or None)\n if form.is_valid():\n user = authenticate(\n username=form.cleaned_data[\"username\"], password=form.cleaned_data['password'])\n if user is not None and user.profile.type == 'u':\n login(request, user)\n return redirect('dashboard', permanent=True)\n else:\n error = 'incorrect username and password'\n else:\n error = 'invalid data entered'\n else:\n form = LoginStudentForm()\n\n return render(request, 'examApplication/student/login.html', {'form': form, 'user': 'student', 'message': message, 'error': error})\n\n\n@login_required(login_url='/login')\ndef dashboard(request):\n if request.user.profile.type == 'u':\n user = Student.objects.get(EmailId=request.user.username)\n message = None\n error = None\n if 'message' in request.session:\n message = request.session['message']\n request.session['message'] = None\n\n application_opened = None\n not_paid = None\n hall_ticket_available = FeesNotification.objects.all().first().HallTicketAvailable\n if FeesNotification.objects.all().count() > 0:\n application_opened = True\n print(FeesNotification.objects.all().count() )\n not_paid = True\n\n #print(FeesPayment.objects.get(StudentId = user))\n if FeesPayment.objects.filter(StudentId = user).exists() :\n not_paid = False\n\n return render(request, 'examApplication/student/dashboard.html', {\"user\": user, \"hall_ticket_available\": hall_ticket_available, error: \"error\", \"application_opened\": application_opened, \"not_paid\": not_paid})\n return handle_lacks_privileges_error(request)\n\n\n\n@login_required(login_url='login')\ndef download_hall_ticket(request):\n if request.user.profile.type == 'u':\n student = Student.objects.get(EmailId = request.user.username)\n # pdf = render_to_pdf('examApplication/hallticket.html',{'student':student} )\n # return render(request, 'examApplication/hallticket.html', {'student':student} )\n template = get_template('examApplication/hallticket.html')\n context = {\n 'student':student\n }\n html = template.render(context)\n pdf = render_to_pdf('examApplication/hallticket.html', context)\n return HttpResponse(pdf, content_type=\"application/pdf\")\n # return HttpResponse(pdf, content_type='application/pdf')\n return handle_lacks_privileges_error(request)\n\ndef render_to_pdf(template_src, context_dict={}):\n template = get_template(template_src)\n html = template.render(context_dict)\n result = BytesIO()\n pdf = pisa.pisaDocument(BytesIO(html.encode(\"ISO-8859-1\")), result)\n if not pdf.err:\n return HttpResponse(result.getvalue(), content_type='application/pdf')\n return None\n\ndef link_callback(uri, rel):\n print(\"called link with \", uri, \" \", rel)\n sUrl = settings.STATIC_URL # Typically /static/\n sRoot = settings.STATIC_ROOT # Typically /home/userX/project_static/\n path = None\n if uri.startswith(sUrl):\n path = os.path.join(sRoot, uri.replace(sUrl, \"\"))\n if not os.path.isfile(path):\n raise Exception('media URI must start with %s or %s' % (sUrl))\n return path\n\n\n\n@login_required(login_url='home_page')\ndef logout_view(request):\n profile = request.user.profile.type\n logout(request=request)\n request.session['message'] = 'Successfully logged out'\n if profile == 'a':\n return redirect('login_admin')\n elif profile == 'u':\n return redirect('login_student')\n\n\n@login_required(login_url='login')\ndef pay_fees(request):\n message = None\n error = None\n if request.user.profile.type == 'u':\n if request.method == \"POST\":\n form = FeesApplicationForm(request.POST or None)\n if form.is_valid():\n fees_notification = FeesNotification.objects.all().first()\n student = Student.objects.get(EmailId = request.user.username)\n fees_payment = FeesPayment.objects.create(ApplicationId = fees_notification, StudentId = student, PaidFees = str(form['PaidFees'].value()) )\n return redirect('dashboard')\n else:\n form = FeesApplicationForm()\n print('yes here ')\n return render(request, 'examApplication/student/pay_fees.html', {'form':form, 'error': error, 'messages': message})\n return handle_lacks_privileges_error(request)\n\n\n\n\n\n\n\n\n\n\n\n\n # admin starts here\n\n\ndef login_admin(request):\n if is_logged_in(request):\n return handle_already_logged_in_error(request)\n\n message = None\n if 'message' in request.session:\n message = request.session['message']\n request.session['message'] = None\n print(\"Ok i am executed, \")\n\n error = None\n\n if request.method == \"POST\":\n form = LoginStudentForm(request.POST or None)\n if form.is_valid():\n user = authenticate(\n username=form.cleaned_data[\"username\"], password=form.cleaned_data['password'])\n if user is not None and user.profile.type == 'a':\n login(request, user)\n return redirect('dashboard_admin', permanent=True)\n else:\n error = 'Incorrect username and password'\n else:\n error = 'Invalid data entered'\n else:\n form = LoginStudentForm()\n\n return render(request, 'examApplication/student/login.html', {'form': form, 'user': 'admin', 'message': message})\n\n\n@login_required(login_url='login_admin')\ndef dashboard_admin(request):\n if request.user.profile.type == 'a':\n user = Admin.objects.get(EmailId=request.user.username)\n message = None\n error = None\n if 'message' in request.session:\n message = request.session['message']\n request.session['message'] = None\n\n application_opened = None\n hall_ticket_available = FeesNotification.objects.all().first().HallTicketAvailable\n print(hall_ticket_available)\n if FeesNotification.objects.all().count() == 1:\n application_opened = True\n print(FeesNotification.objects.all().count())\n\n return render(request, 'examApplication/admin/dashboard.html', {\"admin\": user, \"hall_ticket_available\": hall_ticket_available, \"error\": error, \"application_opened\": application_opened})\n return handle_lacks_privileges_error(request)\n\n\n@login_required(login_url='login_admin')\ndef open_fees_application(request):\n if request.user.profile.type == 'a':\n message = None\n error = None\n if 'message' in request.session:\n message = request.session['message']\n request.session['message'] = None\n fee_notification = FeesNotification.objects.create(StartDate=localtime(\n now()).date(), EndDate='2018-09-01', Description='fees notification working')\n fee_notification.save()\n return redirect('dashboard_admin')\n\n\n@login_required(login_url='login_admin')\ndef close_fees_application(request):\n if request.user.profile.type == 'a':\n message = None\n error = None\n if 'message' in request.session:\n message = request.session['message']\n request.session['message'] = None\n\n return redirect('dashboard_admin')\n\n\n@login_required(login_url='login_admin')\ndef extend_fees_date(request):\n if request.user.profile.type == 'a':\n message = None\n error = None\n if 'message' in request.session:\n message = request.session['message']\n request.session['message'] = None\n return redirect('dashboard_admin')\n\n\n@login_required(login_url='login_admin')\ndef send_fees_reminder(request):\n if request.user.profile.type == 'a':\n message = None\n error = None\n if 'message' in request.session:\n message = request.session['message']\n request.session['message'] = None\n # fetch from form\n # fees = Fees.objects.create()\n return redirect('dashboard_admin')\n\n\n\n#hall ticket printout...\n@login_required(login_url='login')\ndef hall_ticket_printout(request):\n if request.user.profile.type == 'a':\n message = None\n error = None\n if 'message' in request.session:\n message = request.session['message']\n request.session['message'] = None\n fees_notification = FeesNotification.objects.all().first()\n fees_notification.HallTicketAvailable = 'true'\n fees_notification.save()\n \n return redirect('dashboard_admin')\n return handle_lacks_privileges_error(request)","sub_path":"views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":10340,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"380306875","text":"import os\nimport sys\n\nthis_dir = os.path.abspath(os.path.dirname(__file__))\nsys.path.append(os.path.join(this_dir, '..', 'PageObjects'))\n\nfrom JupyterUtils import JupyterUtils\nfrom VcdatLeftSideBar import VcdatLeftSideBar\nfrom FileBrowser import FileBrowser\nfrom MainPage import MainPage\nfrom NoteBookPage import NoteBookPage\n\nimport time\nimport unittest\nimport tempfile\n\nfrom selenium.common.exceptions import NoSuchElementException\nfrom selenium import webdriver\nfrom selenium.webdriver import DesiredCapabilities\n# from selenium.webdriver.firefox.options import Options\nfrom selenium.webdriver.firefox.firefox_profile import FirefoxProfile\nfrom selenium.webdriver.firefox.firefox_binary import FirefoxBinary\nfrom pyvirtualdisplay import Display\n\n\nclass BaseTestCase(unittest.TestCase):\n '''\n Following env variable should be set:\n BROWSER_MODE: '--foreground' or '--headless'\n BROWSER_TYPE: 'chrome' or 'firefox'\n BROWSER_DRIVER: full path to your browser driver (chromedriver or geckodriver)\n If running with firefox on Linux, should also set:\n BROWSER_BINARY: full path to your firefox binary\n '''\n _delay = 0.1\n _wait_timeout = 10\n\n def setUp(self):\n self._download_dir = tempfile.mkdtemp()\n browser = os.getenv(\"BROWSER_TYPE\", 'chrome')\n mode = os.getenv(\"BROWSER_MODE\", '--headless')\n print(\"...browser: {b}\".format(b=browser))\n print(\"...mode: {m}\".format(m=mode))\n\n if mode == \"--headless\" and os.getenv(\"CIRCLECI\"):\n print(\"...starting display since we are running in headless mode\")\n display = Display(visible=0, size=(800, 600))\n display.start()\n\n if browser == 'chrome':\n self.setup_for_chrome(mode)\n elif browser == 'firefox':\n self.setup_for_firefox(mode)\n\n self.driver.implicitly_wait(self._wait_timeout)\n time.sleep(self._delay)\n\n utils = JupyterUtils()\n self.server = utils.get_server()\n self.main_page = MainPage(self.driver, self.server)\n self.left_side_bar = VcdatLeftSideBar(self.driver, None)\n self.file_browser = FileBrowser(self.driver, None)\n self.click_on_file_browser_home()\n\n self._test_notebook_file = \"{t}.ipynb\".format(t=self._testMethodName)\n self.notebook_page = NoteBookPage(self.driver, None)\n self.notebook_page.rename_notebook(self._test_notebook_file)\n\n def tearDown(self):\n print(\"...BaseTestCase.tearDown()...\")\n self.main_page.shutdown_kernel()\n self.notebook_page.save_current_notebook()\n self.notebook_page.close_current_notebook()\n self.driver.quit()\n os.remove(self._test_notebook_file)\n\n def setup_for_chrome(self, mode):\n chrome_options = webdriver.ChromeOptions()\n chrome_options.add_argument(mode)\n chrome_options.add_argument(\"--no-sandbox\")\n chrome_options.add_argument(\"window-size=1200x600\")\n self.driver = webdriver.Chrome(executable_path=os.getenv(\"BROWSER_BINARY\", \"/usr/local/bin/chromedriver\"),\n chrome_options=chrome_options,\n service_args=['--verbose', '--log-path=/tmp/chromedriver.log'])\n\n def setup_for_firefox(self, mode):\n firefox_profile = FirefoxProfile()\n firefox_profile.set_preference('dom.disable_open_during_load', False)\n firefox_capabilities = DesiredCapabilities().FIREFOX\n firefox_capabilities['marionette'] = True\n firefox_capabilities['moz:firefoxOptions'] = {'args': ['--headless']}\n\n firefox_binary = FirefoxBinary(os.getenv(\"BROWSER_BINARY\", \"/usr/bin/firefox\"))\n geckodriver_loc = os.getenv(\"BROWSER_DRIVER\", \"/usr/local/bin/geckodriver\")\n self.driver = webdriver.Firefox(firefox_profile=firefox_profile,\n firefox_binary=firefox_binary,\n executable_path=geckodriver_loc,\n capabilities=firefox_capabilities)\n\n #\n # notebook utils\n #\n\n def close_notebook_if_any(self):\n try:\n note_book = NoteBookPage(self.driver)\n note_book.close()\n time.sleep(self._delay)\n except NoSuchElementException:\n print(\"No notebook opened\")\n pass\n\n def close_current_notebook(self):\n self.main_page.close_current_notebook()\n\n #\n # Load a data file\n #\n\n def load_data_file(self, filename):\n # left_side_bar = VcdatLeftSideBar(self.driver, None)\n self.left_side_bar.click_on_jp_vcdat_icon()\n time.sleep(self._delay)\n self.left_side_bar.click_on_load_variables_by_file()\n\n # file_browser = FileBrowser(self.driver, None)\n self.file_browser.double_click_on_a_file(filename)\n time.sleep(self._delay)\n\n def load_sample_data(self, filename):\n # left_side_bar = VcdatLeftSideBar(self.driver, None)\n self.left_side_bar.click_on_jp_vcdat_icon()\n time.sleep(self._delay)\n self.left_side_bar.click_on_load_variables_by_file()\n\n # file_browser = FileBrowser(self.driver, None)\n self.click_on_file_browser_home()\n print(\"DEBUG DEBUG...returned from click_on_file_browser_home...\")\n time.sleep(5)\n if \"/\" in filename:\n paths = filename.split('/')\n for f in paths[:-1]:\n print(\"xxx double clicking on {f}\".format(f=f))\n self.file_browser.double_click_on_a_file(f, False)\n time.sleep(self._delay)\n self.file_browser.double_click_on_a_file(paths[-1])\n time.sleep(self._delay)\n\n #\n #\n #\n def click_on_plot(self):\n self.left_side_bar.click_on_plot()\n\n def click_on_clear(self):\n self.left_side_bar.click_on_clear()\n\n def select_plot_type(self, plot_type):\n self.left_side_bar.select_plot_type(plot_type)\n\n #\n # kernel utils\n #\n def select_kernel(self):\n self.main_page.select_kernel()\n\n def click_on_file_browser_home(self):\n self.left_side_bar.click_on_file_folder()\n self.file_browser.click_on_home()\n\n #\n # download_sample_data\n #\n def download_sample_data(self):\n vp = \"vcs_egg_path = pkg_resources.resource_filename(pkg_resources.Requirement.parse('vcs'), 'share/vcs')\"\n download_code = [\"import vcs\",\n \"import cdms2\",\n \"import cdat_info\",\n \"import pkg_resources\",\n vp,\n \"path = vcs_egg_path+'/sample_files.txt'\",\n \"cdat_info.download_sample_data_files(path,'sample_data')\"]\n self.notebook_page.enter_code_list(download_code)\n","sub_path":"tests/TestUtils/BaseTestCase_TOBEREMOVED.py","file_name":"BaseTestCase_TOBEREMOVED.py","file_ext":"py","file_size_in_byte":6785,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"467852024","text":"import sys\nimport os\n\ntarget_dir=sys.argv[1]\nfile_list=os.listdir(target_dir)\n\nfor file in file_list:\n\tf=open(target_dir+file, 'r')\n\t#print(\"file: %s\" %file)\n\tdump=f.read()\n\tif \"0000\" in dump:\n\t\tprint(file)\n\tf.close()\n","sub_path":"preprocessing/check_encrpyt.py","file_name":"check_encrpyt.py","file_ext":"py","file_size_in_byte":218,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"162831147","text":"import archipel\nimport os\nimport pathlib\n\n\npath = pathlib.Path(\n os.environ.get(\"ARCHIPEL\"), \"etc\", \"txt\", \"reglommed-w-numbers.txt\"\n)\noutput = open(path, \"w\")\n\nfor q in range(1, 21):\n x, first = 1, True\n while True:\n numbers = archipel.etc.implementation.utilities.make_reglommed_w_numbers(\n q, (3, 3, 6, 10), x\n )\n if first:\n output.write(\"%s counts:\\n\" % sum(numbers))\n first = False\n if 0 in numbers:\n break\n elif max(numbers) < 20:\n numbers = \" \".join([str(number) for number in numbers])\n output.write(\"(%s/3-3-6-10) %s: %s\\n\" % (q, x, numbers))\n x += 1\n output.write(\"\\n\")\n\noutput.close()\n","sub_path":"archipel/etc/implementation/write/write_reglommed_w_numbers.py","file_name":"write_reglommed_w_numbers.py","file_ext":"py","file_size_in_byte":716,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"427043895","text":"import keras\nimport numpy as np\nimport scipy as sp\nfrom scipy import misc\nimport pandas as pd\nimport pickle\nimport sys\nimport os\nimport tensorflow as tf\nfrom tqdm import tqdm\nimport gc\n\nfrom sklearn import model_selection\nfrom sklearn import metrics\n\nfrom keras import optimizers\nfrom keras.models import Sequential\nfrom keras.models import load_model\nfrom keras.layers import Dense, Dropout, Flatten\nfrom keras.layers import Conv2D, MaxPooling2D\nfrom keras.layers.normalization import BatchNormalization\nfrom keras.metrics import categorical_accuracy\nfrom keras.preprocessing.image import ImageDataGenerator\n\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' # Turn off tensorflow output\n\n# Constants\nIMG_SIZE = 128\nlearn_rates = [1e-4, 1e-5]\n\n# Convulutional Neural Network\ndef model_nn():\n model = Sequential()\n model.add(Conv2D(16, (3, 3), activation='relu', input_shape=(IMG_SIZE, IMG_SIZE, 3)))\n model.add(MaxPooling2D(pool_size=(2, 2)))\n model.add(Conv2D(32, (3, 3), activation='relu'))\n model.add(MaxPooling2D(pool_size=(2, 2)))\n model.add(Conv2D(64, (3, 3), activation='relu'))\n model.add(MaxPooling2D(pool_size=(2, 2)))\n model.add(Conv2D(128, (3, 3), activation='relu')) \n model.add(Flatten())\n model.add(Dense(2048, activation='relu'))\n model.add(Dropout(0.65))\n model.add(Dense(512, activation='relu'))\n model.add(Dropout(0.55))\n model.add(Dense(1, activation='sigmoid'))\n return model\n\n\n\nprint('\\nStarto!\\n')\n\n\n# Load and process train labels\nwith open('../train_labels.csv', 'r') as f:\n\tlabels_u = pd.read_csv(f)\n\nlength = len(labels_u)\n\nlabels = np.zeros((length), dtype=np.uint8)\nfor i in tqdm(range(length)):\n\tlabels[i] = labels_u['invasive'][i]\ndel labels_u\ngc.collect()\n\nprint('Loaded and processed train labels...\\n')\n\n\n# Load and process image data\nwith open('./data/train.npy', 'rb') as f:\n\timages_u = np.load(f)\n\nimages = np.zeros((length,IMG_SIZE,IMG_SIZE,3), dtype=np.uint8)\nfor i in tqdm(range(length)):\n\timages[i] = sp.misc.imresize(images_u[i], (IMG_SIZE,IMG_SIZE,3))\ndel images_u\ngc.collect()\n\nprint('Loaded and processed train images...\\n')\n\n\nprint('Start training network\\n')\n\nmodel = model_nn()\nprint(model.summary())\nkf = model_selection.KFold(n_splits = 7, shuffle = True)\n\nfor train, test in kf.split(images):\n\tx_tr = images[train]; x_te = images[test]\n\ty_tr = labels[train]; y_te = labels[test]\n\n\tdatagen = ImageDataGenerator(\n\t\t\trotation_range = 30,\n\t\t\twidth_shift_range = 0.2,\n\t\t\theight_shift_range = 0.2,\n\t\t\tshear_range = 0.2,\n\t\t\tzoom_range = 0.2,\n\t\t\thorizontal_flip = True,\n\t\t\tvertical_flip = True,\n\t\t\tfill_mode = 'nearest')\n\n\tfor learn_rate in learn_rates:\n\t\tprint('\\nTraining model with learn rate: ', learn_rate, '\\n')\n\n\t\tearlystop = keras.callbacks.EarlyStopping(\n\t\t\tmonitor='val_loss', patience = 5, verbose=0, mode='auto')\n\n\t\tsgd = optimizers.SGD(lr = learn_rate, decay = 0, momentum = 0.8, nesterov = True)\n\t\tmodel.compile(loss = 'binary_crossentropy', optimizer = sgd, metrics=['accuracy'])\n\n\t\tmodel.fit_generator(datagen.flow(x_tr, y_tr, batch_size=32),\n\t steps_per_epoch=256, epochs=1000,\n\t callbacks=[earlystop], validation_data=(x_te, y_te))\n\n\tmodel.save('./models/model.h5')\n\tbreak\n\n\nprint('\\nEnd!\\n')\n\n\n\n","sub_path":"trainer.py","file_name":"trainer.py","file_ext":"py","file_size_in_byte":3234,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"182566813","text":"from snovault import upgrade_step\n\n\n@upgrade_step('human_postnatal_donor', '1', '2')\ndef human_postnatal_donor_1_2(value, system):\n\tif 'family_history_breast_cancer' in value:\n\t\tvalue['family_members_history_breast_cancer'] = value['family_history_breast_cancer']\n\t\tdel value['family_history_breast_cancer']\n\n\n@upgrade_step('human_postnatal_donor', '2', '3')\ndef human_postnatal_donor_2_3(value, system):\n\tif 'height' in value:\n\t\tvalue['height'] = str(value['height'])\n\tif 'body_mass_index' in value:\n\t\tvalue['body_mass_index'] = str(value['body_mass_index'])\n\n\n@upgrade_step('human_postnatal_donor', '3', '4')\n@upgrade_step('human_prenatal_donor', '1', '2')\ndef human_donor_ancestry(value, system):\n\tif 'ancestry' in value:\n\t\tfor a in value['ancestry']:\n\t\t\ta['fraction'] = a['percentage'] / 100\n\t\t\tdel a['percentage']\n\tdonor_id = value['aliases'][0].split(':')[1]\n\tif donor_id.endswith('_donor'):\n\t\tdonor_id = donor_id[:-6]\n\tvalue['donor_id'] = donor_id\n\n\n@upgrade_step('human_postnatal_donor', '4', '5')\n@upgrade_step('human_prenatal_donor', '2', '3')\ndef human_donor_ethnicity_array(value, system):\n\tif 'ethnicity' in value:\n\t\tvalue['ethnicity'] = [value['ethnicity']]\n\n\n@upgrade_step('human_postnatal_donor', '5', '6')\ndef human_donor_smoker_family_history(value, system):\n\tif 'smoking_history' in value:\n\t\tif value['smoking_history'] == 'none':\n\t\t\tvalue['smoker'] = 'never'\n\tif 'family_members_history_breast_cancer' in value:\n\t\tif value['family_members_history_breast_cancer'] == [\"none\"]:\n\t\t\tvalue['family_medical_history'] = [{\n\t\t\t\t'present': False\n\t\t\t}]\n\t\telse:\n\t\t\tvalue['family_medical_history'] = [{\n\t\t\t\t'family_members': value['family_members_history_breast_cancer'],\n\t\t\t\t'present': True\n\t\t\t}]\n\t\tdel value['family_members_history_breast_cancer']\n\n\n@upgrade_step('human_postnatal_donor', '6', '7')\ndef human_donor_cause_of_death_removal(value, system):\n\tif 'cause_of_death' in value:\n\t\tdel value['cause_of_death']\n\n\n@upgrade_step('human_postnatal_donor', '7', '8')\ndef human_donor_living_at_sample_collection_stringify(value, system):\n\tif 'living_at_sample_collection' in value:\n\t\tvalue['living_at_sample_collection'] = str(value['living_at_sample_collection'])\n","sub_path":"src/encoded/upgrade/donor.py","file_name":"donor.py","file_ext":"py","file_size_in_byte":2173,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"106231740","text":"# -*- coding: utf-8 -*-\n\n# File name: events.py\n# Author: Kaustav Basu\n# Date created: 03/22/2019\n# Date last modified: 03/22/2019\n# Python Version: 2.7.10\n\nfrom yelpapi import YelpAPI\nfrom googleapiclient.discovery import build\nfrom googleapiclient.errors import HttpError\nfrom datetime import datetime\nfrom datetime import timedelta\nfrom prettytable import PrettyTable\nimport json\nimport sys\nimport dateutil.parser as dp\n\n\ndef getVideoData(response, client):\n videoIds = ''\n numResults = len(response['items'])\n for x in range(numResults):\n if 'id' in response['items'][x]:\n videoIds = videoIds+response['items'][x]['id']['videoId']+','\n videoIds = videoIds[0:len(videoIds)-1]\n response = ''\n if numResults > 0:\n response = videos_list_multiple_ids(client,\n part='snippet,contentDetails,statistics',\n id=videoIds)\n return response\n\ndef remove_empty_kwargs(**kwargs):\n good_kwargs = {}\n if kwargs is not None:\n for key, value in kwargs.iteritems():\n if value:\n good_kwargs[key] = value\n return good_kwargs\n\ndef search_list_by_keyword(client, **kwargs):\n kwargs = remove_empty_kwargs(**kwargs)\n response = client.search().list(\n **kwargs\n ).execute()\n return response\n\ndef videos_list_multiple_ids(client, **kwargs):\n kwargs = remove_empty_kwargs(**kwargs)\n response = client.videos().list(\n **kwargs\n ).execute()\n return response\n\ndef getEventsFromYelp(location):\n eventsList = []\n startTime = dp.parse((datetime.now() + timedelta(days=7)).isoformat()).strftime('%s')\n yelpApi = YelpAPI('')\n response = yelpApi.event_search_query(location=location, sort_by='desc', limit=50, sort_on='popularity', start_date=startTime)\n events = response['events']\n for i in range(len(events)):\n name = events[i]['name']\n attendingCount = events[i]['attending_count']\n interestedCount = events[i]['interested_count']\n cost = events[i]['cost']\n zip = events[i]['location']['zip_code']\n category = events[i]['category']\n time = events[i]['time_start']\n event = [name, attendingCount, interestedCount, cost, zip, category, time]\n eventsList.append(event)\n return eventsList\n\ndef crawlEventOnYoutube(eventName, location):\n videoStats = []\n query = eventName+' '+location\n googleApiKey = ''\n client = build('youtube', 'v3', developerKey = googleApiKey)\n response = search_list_by_keyword(client, part='snippet', maxResults=10, q=query,\n order='date', type='video')\n videoData = getVideoData(response, client)\n numResults = videoData['pageInfo']['totalResults'] if 'pageInfo' in videoData else 0\n totalVideoViews = 0\n totalVideoEngagements = 0\n vidCount = 0\n for i in range(numResults):\n videoTitle = videoData['items'][i]['snippet']['title']\n videoDescription = videoData['items'][i]['snippet']['description']\n videoViews = videoData['items'][i]['statistics']['viewCount'] if 'viewCount' in videoData['items'][i]['statistics'] else 0\n videoLikes = videoData['items'][i]['statistics']['likeCount'] if 'likeCount' in videoData['items'][i]['statistics'] else 0\n videoDislikes = videoData['items'][i]['statistics']['dislikeCount'] if 'dislikeCount' in videoData['items'][i]['statistics'] else 0\n videoFavorites = videoData['items'][i]['statistics']['favoriteCount'] if 'favoriteCount' in videoData['items'][i]['statistics'] else 0\n videoComments = videoData['items'][i]['statistics']['commentCount'] if 'commentCount' in videoData['items'][i]['statistics'] else 0\n if eventName in videoTitle or eventName in videoDescription:\n totalVideoViews = totalVideoViews + int(videoViews)\n totalVideoEngagements = totalVideoEngagements + int(videoLikes) + int(videoDislikes) + int(videoFavorites) + int(videoComments)\n vidCount = vidCount + 1\n videoStats = [totalVideoViews, vidCount, totalVideoEngagements]\n return videoStats\n\nif __name__ == '__main__':\n location = sys.argv[1]\n eventsList = getEventsFromYelp(location)\n t = PrettyTable(['Name', 'Zip Code', 'Category', 'Views', 'Engagements', '# Videos'])\n for i in range(len(eventsList)):\n videoData = crawlEventOnYoutube(eventsList[i][0], location)\n t.add_row([eventsList[i][0], eventsList[i][4], eventsList[i][5], videoData[0], videoData[2], videoData[1]])\n print(t)\n","sub_path":"events.py","file_name":"events.py","file_ext":"py","file_size_in_byte":4488,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"316252359","text":"import numpy as np\n\nclass Cloud:\n def __init__(self, D, N, L, C, uniform=False, sample=False):\n self.D = D\n self.N = N\n self.L = L\n self.C = C\n\n if uniform:\n self.point_array = generateUniformCloud(D,N,L,C)\n elif sample:\n self.point_array = generateSampCloud(D,N,L,C)\n else:\n self.point_array = generateCloud(D,N,L,C)\n \n\ndef hardWallBound(arr,L):\n x = arr[:,0]\n y = arr[:,1]\n z = arr[:,2]\n \n for i in range(x.size):\n xi = x[i]\n yi = y[i]\n zi = z[i]\n \n if xi < 0:\n x[i] = xi + L\n if xi > L:\n x[i] = xi - L\n if yi < 0:\n y[i] = yi + L\n if yi > L:\n y[i] = yi - L\n if zi < 0:\n z[i] = zi + L\n if zi > L:\n z[i] = zi - L\n \n cloud = np.zeros([x.size,3])\n cloud[:,0] = x\n cloud[:,1] = y\n cloud[:,2] = z\n \n return cloud\n\ndef generateUniformCloud(D,N,L,C):\n dummy = np.zeros([1,3])\n density = np.zeros([C,C,C]) + 1300\n return dummy , density\n\ndef generateSampCloud(D,N,L,C):\n dummy = np.zeros([1,3])\n density = np.load('sampledensity.npy')\n density *= 1.3e53 / (L/C)**3\n return dummy , density\n\ndef generateCloud(D,N,L,C):\n __p1__ = np.zeros([N,3])\n __p2__ = np.zeros([N**2,3])\n __p3__ = np.zeros([N**3,3])\n __p4__ = np.zeros([N**4,3])\n delta = np.exp(np.log(N)/D)\n print(\"Delta: \" + str(delta))\n \n for i in range(N):\n __r1__ = np.random.uniform(0,1,3)\n __p1__[i,:] = (L)*__r1__\n \n for n in range(N):\n __origin__ = np.copy(__p1__[n,:])\n for m in range(N):\n __r2__ = np.random.uniform(-1,1,3)\n __p2__[m+n*N, :] = (L/(2*delta))*__r2__ + __origin__\n \n for k in range(N**2):\n __origin__ = np.copy(__p2__[k,:])\n for q in range(N):\n __r3__ = np.random.uniform(-1,1,3)\n __p3__[q+k*N, :] = (L/(2*delta))*__r3__ + __origin__\n \n for l in range(N**3):\n __origin__ = np.copy(__p3__[l,:])\n for h in range(N):\n __r4__ = np.random.uniform(-1,1,3)\n __p4__[h+l*N, :] = (L/(2*delta))*__r4__ + __origin__\n \n \n cloud = np.concatenate((__p1__, __p2__, __p3__, __p4__), axis=0)\n cloudbn = hardWallBound(cloud,L)\n \n density = np.histogramdd(cloudbn,bins = (C,C,C),range=[(0,L),(0,L),(0,L)])\n# print(\"The cluster lentgh: \" + str(L/(2*delta)))\n \n return cloudbn , density[0]\n","sub_path":"Cloud.py","file_name":"Cloud.py","file_ext":"py","file_size_in_byte":2555,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"549250376","text":"import praw\nimport time\nimport os\nfrom retrying import retry\nfrom collections import deque\nfrom collections import OrderedDict\nimport re\nfrom requests.exceptions import HTTPError\nimport requests\n\n#initialize reddit\nuser_agent='SEO_Killer - Justiciar Module by /u/captainmeta4 - see /r/SEO_Killer'\nr=praw.Reddit(user_agent=user_agent)\nheaders={'User-Agent': user_agent}\n\n#set globals\nusername = 'SEO_Killer'\npassword = os.environ.get('password')\n\nmaster_subreddit=r.get_subreddit('SEO_Killer')\n\n\n#Ignore list - Justiciar will neither record deletions nor alert mods for domains\n#domains on this list.\nignore_domains=['imgur.com', 'i.imgur.com', 'reddit.com', 'redd.it']\n\n\n\nclass Bot(object):\n\n @retry(wait_exponential_multiplier=1000, wait_exponential_max=10000)\n def login_bot(self):\n\n print(\"logging in...\")\n r.login(username, password)\n print(\"success\")\n\n @retry(wait_exponential_multiplier=1000, wait_exponential_max=10000) \n def load_caches(self):\n #load already-processed submissions cache and modlist cache\n print(\"loading caches\")\n \n try:\n self.listing = eval(r.get_wiki_page(master_subreddit,\"justiciar_listing\").content_md)\n print(\"justiciar listing cache loaded\")\n except HTTPError as e:\n if e.response.status_code == 403:\n print(\"incorrect permissions\")\n r.send_message(master_subreddit,\"Incorrect permissions\",\"I don't have access to the justiciar_listing wiki page\")\n elif e.response.status_code == 404:\n print(\"justiciar_listing cache not loaded. Starting with blank listing\")\n self.listing={}\n for subreddit in r.get_my_moderation():\n self.listing[subreddit.display_name]=OrderedDict()\n \n r.edit_wiki_page(master_subreddit,'justiciar_listing',str(self.listing))\n elif e.response.status_code in [502, 503, 504]:\n print(\"reddit's crapping out on us\")\n raise e #triggers the @retry module\n else:\n raise e\n\n try:\n self.deletions = eval(r.get_wiki_page(master_subreddit,\"deletions\").content_md)\n print(\"deletions cache loaded\")\n except HTTPError as e:\n if e.response.status_code == 403:\n print(\"incorrect permissions\")\n r.send_message(master_subreddit,\"Incorrect permissions\",\"I don't have access to the deletions wiki page\")\n elif e.response.status_code == 404:\n print(\"deletions cache not loaded. Starting with blank deletions cache\")\n self.deletions={}\n elif e.response.status_code in [502, 503, 504]:\n print(\"reddit's crapping out on us\")\n raise e #triggers the @retry module\n else:\n raise e\n\n try:\n self.already_done = eval(r.get_wiki_page(master_subreddit,\"justiciar_alreadydone\").content_md)\n print(\"already done cache loaded\")\n except HTTPError as e:\n if e.response.status_code == 403:\n print(\"incorrect permissions\")\n r.send_message(master_subreddit,\"Incorrect permissions\",\"I don't have access to the justiciar_alreadydone wiki page\")\n elif e.response.status_code == 404:\n print(\"already-done cache not loaded. Starting with blank deletions cache\")\n self.already_done=deque([],maxlen=200)\n elif e.response.status_code in [502, 503, 504]:\n print(\"reddit's crapping out on us\")\n raise e #triggers the @retry module\n else:\n raise e\n\n def load_options(self):\n try:\n self.options = eval(r.get_wiki_page(master_subreddit,\"options\").content_md)\n print(\"options cache loaded\")\n except HTTPError as e:\n if e.response.status_code == 403:\n print(\"incorrect permissions\")\n r.send_message(master_subreddit,\"Incorrect permissions\",\"I don't have access to the options wiki page\")\n elif e.response.status_code == 404:\n print(\"already-done cache not loaded. Starting with blank options cache\")\n self.options={}\n elif e.response.status_code in [502, 503, 504]:\n print(\"reddit's crapping out on us\")\n raise e #triggers the @retry module\n else:\n raise e\n #@retry(wait_exponential_multiplier=1000, wait_exponential_max=10000) \n def get_ids_of_new(self, subreddit, quantity):\n\n #Returns submissions as an OrderedDict of submission id's and authors\n\n print ('getting ids of posts in /r/'+subreddit.display_name+'/new')\n\n self.new=OrderedDict()\n \n for submission in subreddit.get_new(limit=quantity):\n\n try:\n self.new[submission.id]=submission.author.name\n except AttributeError:\n #This error happens wherever there's a [deleted] post in the /new queue.\n #[deleted] in /new only happens when the owner deleted their reddit account.\n #So we can safely ignore these.\n pass\n\n return self.new\n\n def break_into_100(self, ids):\n\n brokenlist=[]\n while len(ids)>0:\n brokenlist.append(ids[0:min(100,len(ids))])\n del ids[0:min(100,len(ids))]\n\n return brokenlist\n\n @retry(wait_exponential_multiplier=1000, wait_exponential_max=10000)\n def find_deletions(self, subreddit):\n\n print ('checking for possible deletions in /r/'+subreddit.display_name)\n\n\n #Assemble the list of ids to check\n\n ids=[]\n for entry in self.listing[subreddit.display_name]:\n ids.append('t3_'+entry)\n\n idlists=self.break_into_100(ids)\n\n for idlist in idlists:\n for submission in r.get_info(thing_id=idlist):\n if not isinstance(submission.author, praw.objects.Redditor):\n \n \n print('deletion detected: http://redd.it/'+submission.id+\" by /u/\"+self.listing[subreddit.display_name][submission.id])\n\n #check whitelists\n if (any(domain in submission.domain for domain in self.options[submission.subreddit.display_name]['domain_whitelist'])\n or self.listing[submission.subreddit.display_name][submission.id] in self.options[submission.subreddit.display_name]['user_whitelist']):\n print('but user or domain is whitelisted')\n self.listing[subreddit.display_name].pop(submission.id)\n continue\n \n #set up new author if needed\n if self.listing[submission.subreddit.display_name][submission.id] not in self.deletions:\n self.deletions[self.listing[subreddit.display_name][submission.id]]={}\n\n #set up new domain within that author, if needed\n if submission.domain not in self.deletions[self.listing[subreddit.display_name][submission.id]]:\n self.deletions[self.listing[subreddit.display_name][submission.id]][submission.domain]=[]\n \n #and finally, append the deleted submission id, if needed\n if entry not in self.deletions[self.listing[subreddit.display_name][submission.id]][submission.domain]:\n self.deletions[self.listing[subreddit.display_name][submission.id]][submission.domain].append(submission.id)\n\n #Pop the deletion from the listing so that the post isn't continuously re-checked\n self.listing[subreddit.display_name].pop(submission.id)\n\n\n #@retry(wait_exponential_multiplier=1000, wait_exponential_max=10000)\n def check_new_submissions(self):\n\n print('checking new submissions for reposts')\n\n for submission in r.get_subreddit('mod').get_new(limit=200):\n\n #pass if alert has been triggered\n if submission.id in self.already_done:\n continue\n\n #pass if OP deleted their reddit account\n if not isinstance(submission.author, praw.objects.Redditor):\n continue\n\n #Pass if /r/SEO_Killer, or if a new subreddit that was added during the cycle\n #or if subreddit is ignored\n if (submission.subreddit == master_subreddit\n or submission.subreddit.display_name not in self.listing\n or self.options[submission.subreddit.display_name]['justiciar_ignore']):\n continue\n\n #add submission to listing if its not already there\n if submission.id not in self.listing[submission.subreddit.display_name]:\n self.listing[submission.subreddit.display_name][submission.id]=submission.author.name\n \n #Pass if the author has no recorded deletions\n #or if auhor is whitelisted\n if (submission.author.name in self.options[submission.subreddit.display_name]['user_whitelist']\n or submission.author.name not in self.deletions):\n continue\n\n #pass if the author has no recorded deletions from that domain,\n #or if it's a selfpost\n #or if domain is whitelisted\n if (submission.domain not in self.deletions[submission.author.name]\n or submission.domain == 'self.'+submission.subreddit.display_name\n or any(domain in submission.domain for domain in self.options[submission.subreddit.display_name]['domain_whitelist'])):\n continue\n\n #At this point we know that the user is deleting+reposting the domain,\n #but first check if the alert has already triggered\n\n \n\n self.already_done.append(submission.id)\n\n print('Deletion+repost detected in /r/'+submission.subreddit.display_name+' by /u/'+submission.author.name)\n \n msg=(\"I've caught the following user deleting and reposting a domain:\"+\n \"\\n\\n**User:** /u/\"+submission.author.name+\n \"\\n\\n**Domain:** [\"+submission.domain+\"](http://reddit.com/domain/\"+submission.domain+\")\"+\n \"\\n\\n**Permalink:** [\"+submission.title+\"](\"+submission.permalink+\")\"+\n \"\\n\\nPast [deleted] submissions by /u/\"+submission.author.name+\" to \"+submission.domain+\":\\n\")\n\n for entry in self.deletions[submission.author.name][submission.domain]:\n msg=msg+\"\\n* http://redd.it/\"+entry\n\n msg=msg+\"\\n\\n*If this domain is spam, consider reporting it to /r/SEO_Killer*\"\n\n\n #send modmail\n r.send_message(submission.subreddit,'Deletion+repost detected',msg)\n\n @retry(wait_exponential_multiplier=1000, wait_exponential_max=10000)\n def save_caches(self):\n\n print('saving caches')\n\n #we're treating the OrderedDicts in self.listing like deques,\n #so remove the old submission entries to keep it at 1k per subreddit\n for entry in self.listing:\n while len(self.listing[entry]) > 300:\n self.listing[entry].popitem(last=False)\n \n #save the listings cache\n r.edit_wiki_page(master_subreddit,'justiciar_listing',str(self.listing))\n\n #save the deletions cache\n r.edit_wiki_page(master_subreddit,'deletions',str(self.deletions))\n\n #save the already-done cache\n r.edit_wiki_page(master_subreddit,'justiciar_alreadydone',str(self.already_done))\n\n def check_messages(self):\n\n print(\"Checking messages\")\n\n for message in r.get_unread(limit=None):\n\n #Ignore post replies\n if message.subject == \"comment reply\":\n message.mark_as_read()\n continue\n\n #Just assume all messages are a mod invite, and fetch modlist if invite accepted\n try:\n\n #Don't accept mod invites for over-18 subreddits\n if message.subreddit.over18:\n message.mark_as_read()\n message.reply(\"Sorry, I don't moderate over-18 subreddits.\")\n continue\n \n r.accept_moderator_invite(message.subreddit.display_name)\n print(\"Accepted moderator invite for /r/\"+message.subreddit.display_name)\n\n #make a new options set if necessary\n if message.subreddit.display_name not in self.options:\n self.options[message.subreddit.display_name]={\"remove_blacklisted\":False, 'domain_whitelist':[], 'user_whitelist':[], 'justiciar_ignore': False}\n r.edit_wiki_page(master_subreddit,'options',str(self.options))\n \n #send greeting\n msg=(\"Hello, moderators of /r/\"+message.subreddit.display_name+\"!\\n\\n\"+\n \"I am a collection of three bots designed to help curb SEO spam on reddit.\"+\n \"Executioner maintains a global blacklist of sites known to engage in SEO spam.\"+\n \"To toggle Executioner's global ban list between Report mode and Remove mode, send me a PM with the subreddit name as the subject and `remove_blacklisted' as the message body. \"+\n \"\\n\\n('Posts' permissions is necessary for Remove mode. The default mode is Report.)\"+\n \"\\n\\nExecutioner will also send you a weekly update with any domains that have been added to or removed from my global ban list. \"+\n \"If you wish to override the global ban list for any particular domain, please make use of my per-subreddit whitelist feature.\"+\n \"\\n\\nJusticiar will alert you when a user is detected deleting-and-reposting to a particular domain. \"+\n \"It needs 'posts' permissions (to view the /about/spam page), though; otherwise deletion detection will be too inefficient to operate on your subreddit.\"+\n \"\\n\\nFinally, Guardian will quietly analyze domain submission statistics, and post possible spam domains to /r/SEO_Killer for human review.\"+\n \"\\n\\nFor more information, see my [subreddit](/r/SEO_Killer) and my [guide page](/r/SEO_Killer/wiki/guide). My code is on [GitHub](https://github.com/captainmeta4/SEO_Killer)\"+\n \"\\n\\nFeedback may be directed to my creator, /u/captainmeta4. Thanks for using me!\")\n r.send_message(message.subreddit,\"Hello!\",msg)\n\n message.mark_as_read()\n \n continue\n except:\n pass\n\n #Whitelist-related commands. Enclosed in try to protect against garbage input\n\n try:\n if message.author in r.get_moderators(message.subject):\n\n if message.subject not in self.options:\n msg=(\"I don't have options data for that subreddit. Either I'm not a moderator there, or you mistyped the subreddit name.\"+\n '\\n\\nNote that you must correctly capitalize the subreddit name - for example, \"SEO_Killer\" would be correct, while \"seo_killer\" would not be.')\n r.send_message(message.author, \"Error\", msg)\n message.mark_as_read()\n continue\n\n #Read whitelist\n if message.body == \"whitelist\":\n print(\"whitelist query from /u/\"+message.author.name+\" about /r/\"+message.subject)\n msg = \"The following domains are in the /r/\"+message.subject+\" domain whitelist:\\n\"\n\n self.options[message.subject]['domain_whitelist'].sort()\n self.options[message.subject]['user_whitelist'].sort()\n \n if len(self.options[message.subject]['domain_whitelist'])==0:\n msg=msg + \"\\n* *none*\"\n else:\n for entry in self.options[message.subject]['domain_whitelist']:\n msg = msg +\"\\n* \"+entry\n\n msg=msg+\"\\n\\nThe following users are in the /r/\"+message.subject+\" user whitelist:\\n\"\n\n if len(self.options[message.subject]['user_whitelist'])==0:\n msg=msg + \"\\n* *none*\"\n else:\n for entry in self.options[message.subject]['user_whitelist']:\n msg = msg +\"\\n* \"+entry\n \n\n r.send_message(message.author,\"Whitelist for /r/\"+message.subject,msg)\n\n message.mark_as_read()\n\n continue\n\n #modify whitelist\n else:\n #domain whitelist\n if self.is_valid_domain(message.body):\n\n if message.body in self.options[message.subject]['domain_whitelist']:\n self.options[message.subject]['domain_whitelist'].remove(message.body)\n print(message.body+\" removed from domain whitelist for /r/\"+message.subject)\n message.reply(message.body+\" removed from domain whitelist for /r/\"+message.subject)\n r.edit_wiki_page(master_subreddit,\"options\",str(self.options),reason=message.body+\" removed from domain whitelist for /r/\"+message.subject+\"by /u/\"+message.author.name)\n message.mark_as_read()\n continue\n else:\n self.options[message.subject]['domain_whitelist'].append(message.body)\n print(message.body+\" added to domain whitelist for /r/\"+message.subject)\n message.reply(message.author,\"Domain Whitelist Modified\",message.body+\" added to domain whitelist for /r/\"+message.subject)\n r.edit_wiki_page(master_subreddit,\"options\",str(self.options),reason=message.body+\" added to domain whitelist for /r/\"+message.subject+\"by /u/\"+message.author.name)\n message.mark_as_read()\n continue\n #user whitelist\n elif self.is_valid_username(message.body):\n if message.body in self.options[message.subject]['user_whitelist']:\n self.options[message.subject]['user_whitelist'].remove(message.body)\n print(\"/u/\"+message.body+\" removed from user whitelist for /r/\"+message.subject)\n message.reply(message.body+\" removed from user whitelist for /r/\"+message.subject)\n r.edit_wiki_page(master_subreddit,\"options\",str(self.options),reason=message.body+\" removed from user whitelist for /r/\"+message.subject+\"by /u/\"+message.author.name)\n message.mark_as_read()\n continue\n else:\n self.options[message.subject]['user_whitelist'].append(message.body)\n print(message.body+\" added to user whitelist for /r/\"+message.subject)\n message.reply(message.body+\" added to user whitelist for /r/\"+message.subject)\n r.edit_wiki_page(master_subreddit,\"options\",str(self.options),reason=message.body+\" added to domain whitelist for /r/\"+message.subject+\"by /u/\"+message.author.name)\n message.mark_as_read()\n else:\n print(\"garbage message from /u/\"+message.author.name)\n r.send_message(message.author,\"Error\",\"This doesn't look like a valid username or domain:\\n\\n\"+message.body)\n message.mark_as_read()\n else:\n print(\"invalid message from /u/\"+message.author.name)\n r.send_message(message.author,\"Error\",\"You are not a moderator of /r/\"+message.subject)\n message.mark_as_read()\n except:\n pass\n \n def is_valid_domain(self, domain):\n if re.search(\"^[a-zA-Z0-9][-.a-zA-Z0-9]*\\.[-.a-zA-Z0-9]*[a-zA-Z0-9]$\",domain):\n return True\n else:\n return False\n\n def is_valid_username(self, username):\n \n if re.search(\"^/?u/[A-Za-z0-9_-]{3,20}$\",username):\n return True\n else:\n return False\n \n #@retry(wait_exponential_multiplier=1000, wait_exponential_max=10000) \n def run(self):\n\n self.login_bot()\n self.load_caches()\n\n while 1:\n\n print('running cycle')\n\n self.check_messages()\n self.load_options()\n\n for subreddit in r.get_my_moderation(limit=None):\n\n #Ignore /r/SEO_Killer and subreddits added during cycle\n #also ignore subreddits ignored by justiciar\n if (subreddit == master_subreddit\n or subreddit.display_name not in self.listing\n or self.options[subreddit.display_name]['justiciar_ignore']):\n continue\n \n self.find_deletions(subreddit)\n\n self.check_new_submissions()\n\n self.save_caches()\n \n\n#Master bot process\nif __name__=='__main__': \n modbot = Bot()\n \n modbot.run()\n","sub_path":"SEO_Justiciar.py","file_name":"SEO_Justiciar.py","file_ext":"py","file_size_in_byte":21965,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"349005038","text":"from concurrent.futures import ProcessPoolExecutor\nfrom pathlib import Path as p\nfrom os import cpu_count,getcwd\nimport ffmpeg\n\nclass FFConcat:\n\n def __init__(self, path, check_files=False):\n\n self.check_files = check_files\n self.path = p(path)\n self.cores = cpu_count()\n self.batches = []\n\n def file_check(self):\n '''\n Optional:\n Iterates over folders in path, renames with leading zero for sorting if missing.\n '''\n for folder in sorted(self.path.iterdir()):\n # Folder names were originally \"Folder Name - [Disk 1]\"\n disk_number = folder.stem.split()[-1].strip(']')\n if len(disk_number) == 1:\n folder.rename('{}/Folder Name - Disk 0{}'.format(self.path, disk_number))\n elif len(disk_number) == 2:\n folder.rename('{}/Folder Name - Disk {}'.format(self.path, disk_number))\n\n def file_batch(self):\n '''\n Iterates over folders in path creating a list. Converts list into string format\n which is combined with resulting output filename in a dict and added to\n batch list.\n '''\n print('Batching audio files by folder.')\n for folder in sorted(self.path.iterdir()):\n # Use folder names as concat output name for final file.\n outfile = (self.path/'{}.mp3'.format(folder.stem)).as_posix()\n tracks = []\n # Create a list of sorted tracks in folder.\n for track in sorted(folder.iterdir()):\n tracks.append(track.as_posix())\n print('Located {} audio files in \\\"{}\\\"'.format(len(tracks), folder.stem))\n # Format file list in string format which ffmpeg will accept via input.\n file_list = '|'.join(_ for _ in tracks)\n # Generate list of dictionaries containing the file list and output filemame\n self.batches.append({\n 'file_list': file_list,\n 'outfile': outfile\n })\n\n def combine_audio(self, batch):\n '''\n Input: single dictionary containing a string formatted file list for each folder\n and output filename. Converts list into ffmpeg input concat object. Runs object\n with audio codec copy concatenating files within folder into single file.\n '''\n print('Starting concat for: {}'.format(batch['outfile']))\n tracks = ffmpeg.input('concat:{}'.format(batch['file_list']))\n tracks.output(batch['outfile'], acodec='copy').run()\n print('Completed concat for: {}'.format(batch['outfile']))\n\n def mp(self, function, iterable):\n '''\n Input: combine_audio function and batch list.\n Sets max workers depending on iterable length and core count.\n '''\n if len(iterable) >= self.cores:\n workers = self.cores\n elif len(iterable) < self.cores:\n workers = len(iterable)\n with ProcessPoolExecutor(max_workers=workers) as p:\n p.map(function, iterable)\n\n def run(self):\n\n if self.check_files:\n self.file_check()\n\n self.file_batch()\n\n if len(self.batches) == 1:\n print('One batch found. Sending directly to concatenator.')\n self.combine_audio(self.batches[0])\n elif len(self.batches) > 1:\n print('Sending {} batches to multi-processing.'.format(len(self.batches)))\n self.mp(self.combine_audio, self.batches)\n\ncurrent_path = getcwd()+\"/downloads\"\nconcat = FFConcat(path=current_path)\nconcat.run()","sub_path":"conv.py","file_name":"conv.py","file_ext":"py","file_size_in_byte":3611,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"353911969","text":"# Player class file\n\nfrom errors import *\n\nclass Player():\n \"\"\" Player (user) class \"\"\"\n def __init__(self, game, cross=True, nought=False):\n self.game = game\n self.cross = cross\n self.nought = nought\n # determines what symbol the player is using\n if self.cross:\n self.type = \"X\"\n else:\n self.type = \"O\"\n\n def move(self):\n \"\"\" Places a nought or cross on the board \"\"\"\n try:\n self.game.app.write(\"Select a position to place an {} (X, Y): \".format(self.type))\n self.game.app.wait_variable(self.game.app.inputVariable)\n X, Y = self.game.app.inputVariable.get().strip().split()\n X, Y = int(X) - 1, int(Y) - 1\n # checks if the given input is a legal move\n if self.valid_move(X, Y):\n self.game.board[X][Y] = \" \" + \"{}\".format(self.type) + \" \"\n else:\n raise InvalidMoveError\n # input value is too large\n except IndexError:\n self.game.app.write(\"Your input must be between 1 and 3!!\")\n self.game.app.write(\"\")\n self.move()\n # move is illegal\n except InvalidMoveError:\n self.game.app.write(\"You cannot place a {} on a taken square!!\".format(self.type))\n self.game.app.write(\"\")\n self.move()\n return X, Y\n\n def valid_move(self, X, Y):\n \"\"\" Checks if the chosen move is legal \"\"\"\n if self.game.board[X][Y] == \" \":\n return True\n return False","sub_path":"player.py","file_name":"player.py","file_ext":"py","file_size_in_byte":1562,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"308589409","text":"##############################################################################\n# Institute for the Design of Advanced Energy Systems Process Systems\n# Engineering Framework (IDAES PSE Framework) Copyright (c) 2018-2020, by the\n# software owners: The Regents of the University of California, through\n# Lawrence Berkeley National Laboratory, National Technology & Engineering\n# Solutions of Sandia, LLC, Carnegie Mellon University, West Virginia\n# University Research Corporation, et al. All rights reserved.\n#\n# Please see the files COPYRIGHT.txt and LICENSE.txt for full copyright and\n# license information, respectively. Both files are also available online\n# at the URL \"https://github.com/IDAES/idaes-pse\".\n##############################################################################\n\"\"\"\nBenzene-Toluene phase equilibrium package using ideal liquid and vapor.\n\nExample property package using the Generic Property Package Framework.\nThis exmample shows how to set up a property package to do benzene-toluene\nphase equilibrium in the generic framework using ideal liquid and vapor\nassumptions along with methods drawn from the pre-built IDAES property\nlibraries.\n\"\"\"\n# Import Python libraries\nimport logging\nimport pytest\n\n# Import Pyomo units\nfrom pyomo.environ import ConcreteModel, units as pyunits\n\n# Import IDAES cores\nfrom idaes.core import AqueousPhase\nfrom idaes.core.components import *\n\nfrom idaes.generic_models.properties.core.state_definitions import FTPx\nfrom idaes.generic_models.properties.core.eos.enrtl import ENRTL\n\nfrom idaes.core import FlowsheetBlock\nfrom idaes.generic_models.properties.core.generic.generic_property import (\n GenericParameterBlock)\n\n\n# Set up logger\n_log = logging.getLogger(__name__)\n\n\n# ---------------------------------------------------------------------\n# Configuration dictionary for an ideal Benzene-Toluene system\n\n# Data Sources:\n# [1] The Properties of Gases and Liquids (1987)\n# 4th edition, Chemical Engineering Series - Robert C. Reid\n# [3] Engineering Toolbox, https://www.engineeringtoolbox.com\n# Retrieved 1st December, 2019\n\nconfiguration = {\n # Specifying components\n \"components\": {\n 'H2O': {\"type\": Solvent,\n \"parameter_data\": {\n \"mw\": (18E-3, pyunits.kg/pyunits.mol)}},\n 'CO2': {\"type\": Solute,\n \"parameter_data\": {\n \"mw\": (44E-3, pyunits.kg/pyunits.mol)}},\n 'KHCO3': {\"type\": Apparent,\n \"parameter_data\": {\n \"mw\": (100.1E-3, pyunits.kg/pyunits.mol)}},\n 'K+': {\"type\": Cation,\n \"charge\": +1,\n \"parameter_data\": {\n \"mw\": (39.1E-3, pyunits.kg/pyunits.mol)}},\n 'HCO3-': {\"type\": Anion,\n \"charge\": -1,\n \"parameter_data\": {\n \"mw\": (61E-3, pyunits.kg/pyunits.mol)}},\n 'N2': {\"type\": Component,\n \"parameter_data\": {\n \"mw\": (28E-3, pyunits.kg/pyunits.mol)}}},\n\n # Specifying phases\n \"phases\": {'Liq': {\"type\": AqueousPhase,\n \"equation_of_state\": ENRTL}},\n\n # Set base units of measurement\n \"base_units\": {\"time\": pyunits.s,\n \"length\": pyunits.m,\n \"mass\": pyunits.kg,\n \"amount\": pyunits.mol,\n \"temperature\": pyunits.K},\n\n # Specifying state definition\n \"state_definition\": FTPx,\n \"state_bounds\": {\"flow_mol\": (0, 100, 1000, pyunits.mol/pyunits.s),\n \"temperature\": (273.15, 300, 500, pyunits.K),\n \"pressure\": (5e4, 1e5, 1e6, pyunits.Pa)},\n \"pressure_ref\": (101325, pyunits.Pa),\n \"temperature_ref\": (298.15, pyunits.K),\n\n # Defining phase equilibria\n }\n\n\n@pytest.mark.unit\ndef test_component_lists():\n m = ConcreteModel()\n\n m.fs = FlowsheetBlock(default={'dynamic': False})\n\n m.fs.props = GenericParameterBlock(default=configuration)\n\n m.fs.state_1 = m.fs.props.build_state_block(\n [1],\n default={\"defined_state\": True,\n \"species_basis\": \"true\"})\n\n m.fs.state_2 = m.fs.props.build_state_block(\n [1],\n default={\"defined_state\": True,\n \"species_basis\": \"apparent\"})\n\n assert m.fs.props._electrolyte\n\n assert m.fs.props.anion_set == [\"HCO3-\"]\n assert m.fs.props.cation_set == [\"K+\"]\n assert m.fs.props.solvent_set == [\"H2O\"]\n assert m.fs.props.solute_set == [\"CO2\"]\n assert m.fs.props._apparent_set == [\"KHCO3\"]\n assert m.fs.props._non_aqueous_set == [\"N2\"]\n\n assert m.fs.props.true_species_set == [\n \"HCO3-\", \"K+\", \"H2O\", \"CO2\", \"N2\"]\n assert m.fs.props.apparent_species_set == [\n \"H2O\", \"CO2\", \"KHCO3\", \"N2\"]\n assert m.fs.props.component_list == [\n \"HCO3-\", \"K+\", \"H2O\", \"CO2\", \"KHCO3\", \"N2\"]\n\n assert m.fs.props.true_phase_component_set == [\n (\"Liq\", \"HCO3-\"), (\"Liq\", \"K+\"), (\"Liq\", \"H2O\"),\n (\"Liq\", \"CO2\"), (\"Liq\", \"N2\")]\n assert m.fs.props.apparent_phase_component_set == [\n (\"Liq\", \"H2O\"), (\"Liq\", \"CO2\"), (\"Liq\", \"KHCO3\"), (\"Liq\", \"N2\")]\n\n assert m.fs.state_1[1].component_list is m.fs.props.true_species_set\n assert m.fs.state_2[1].component_list is m.fs.props.apparent_species_set\n\n assert m.fs.state_1[1].phase_component_set is \\\n m.fs.props.true_phase_component_set\n assert m.fs.state_2[1].phase_component_set is \\\n m.fs.props.apparent_phase_component_set\n","sub_path":"idaes/generic_models/properties/core/eos/tests/test_enrtl.py","file_name":"test_enrtl.py","file_ext":"py","file_size_in_byte":5502,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"177418369","text":"#Autor: Aline Villegas Berdejo\r\n#Calcula la velocidad promedio de un viaje\r\n\r\ntiempo=int(input(\"Teclea el tiempo del viaje en horas: \"))\r\ndistancia=int(input(\"Teclea la distancia del viaje en kilometros: \"))\r\n\r\nvelocidad=tiempo / distancia\r\n\r\nprint(\"La Velocidad Promedio es: \", velocidad, \"km/h\")\r\n\r\n","sub_path":"EjercicioVelocidadPromedio.py","file_name":"EjercicioVelocidadPromedio.py","file_ext":"py","file_size_in_byte":301,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"244949552","text":"from PyQt5.QtWidgets import QDialog, QLabel, QTextEdit\n\nfrom database import DataBase\n\n\nclass Information(QDialog):\n def __init__(self, name, time, day, doc_id):\n super().__init__()\n self.setGeometry(300, 300, 280, 350)\n self.setWindowTitle('Информация о записи')\n\n self.name = QLabel(self)\n self.name.setText(f'Пациент: {name}')\n self.name.move(10, 20)\n\n self.time = QLabel(self)\n self.time.setText(f'Время\\t{time}')\n self.time.move(10, 50)\n\n self.day = QLabel(self)\n self.day.setText(f'Дата:\\t{day}')\n self.day.move(10, 80)\n\n self.complaint_label = QLabel(self)\n self.complaint_label.setText(\"Жалобы:\")\n self.complaint_label.move(10, 110)\n\n self.con = DataBase()\n\n complaint = self.con.get_data(\"appointments\",\n \"reasons\",\n \"id_patients=\"\n \"(SELECT id FROM\"\n \" patients WHERE\"\n \" surname=? AND name=?)\"\n \" AND time=? AND day=? AND id_doctors=?\",\n (name.split()[0],\n name.split()[1],\n time, day, doc_id))[0][0]\n self.complaint = QTextEdit(self)\n self.complaint.setText(complaint)\n self.complaint.move(10, 130)\n self.complaint.setEnabled(False)\n","sub_path":"info_for_doc.py","file_name":"info_for_doc.py","file_ext":"py","file_size_in_byte":1569,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"499901189","text":"import numpy as np\nimport re\n\n# Constants for augmentation layer\n# .../T1/training/zoom_factors.csv contain the scale factors of all the training samples from isotropic to 128x128x128\n# The augmentation values will be scaled using the average+std\nZOOM_FACTORS = np.asarray([0.5032864535069749, 0.5363100665659675, 0.6292598243796296])\nMAX_AUG_DISP_ISOT = 30\nMAX_AUG_DEF_ISOT = 6\nMAX_AUG_DISP = np.max(MAX_AUG_DISP_ISOT * ZOOM_FACTORS) # Scaled displacements\nMAX_AUG_DEF = np.max(MAX_AUG_DEF_ISOT * ZOOM_FACTORS) # Scaled deformations\nMAX_AUG_ANGLE = np.max([np.arctan(np.tan(10*np.pi/180) * ZOOM_FACTORS[1] / ZOOM_FACTORS[0]) * 180 / np.pi,\n np.arctan(np.tan(10*np.pi/180) * ZOOM_FACTORS[2] / ZOOM_FACTORS[1]) * 180 / np.pi,\n np.arctan(np.tan(10*np.pi/180) * ZOOM_FACTORS[2] / ZOOM_FACTORS[0]) * 180 / np.pi]) # Scaled angles\nGAMMA_AUGMENTATION = False\nBRIGHTNESS_AUGMENTATION = False\nNUM_CONTROL_PTS_AUG = 10\nNUM_AUGMENTATIONS = 5\n\nIN_LAYERS = (0, 3)\nOUT_LAYERS = (33, 39)\n\nENCONDER_LAYERS = (3, 17)\nDECODER_LAYERS = (17, 33)\n\nTOP_LAYERS_ENC = (3, 9)\nTOP_LAYERS_DEC = (22, 29)\nBOTTOM_LAYERS = (9, 22)\n\nLAYER_RANGES = {'INPUT': (IN_LAYERS),\n 'OUTPUT': (OUT_LAYERS),\n 'ENCODER': (ENCONDER_LAYERS),\n 'DECODER': (DECODER_LAYERS),\n 'TOP': (TOP_LAYERS_ENC, TOP_LAYERS_DEC),\n 'BOTTOM': (BOTTOM_LAYERS)}\n\n# LAYER names:\nIN_LAYER_REGEXP = '.*input'\nFC_LAYER_REGEXP = '.*final.*'\nOUT_LAYER_REGEXP = '(?:flow|transformer)'\nENC_LAYER_REGEXP = '.*enc_(?:conv|pooling)_(\\d).*'\nDEC_LAYER_REGEXP = '.*dec_(?:conv|upsample)_(\\d).*'\nLEVEL_NUMBER = lambda x: re.match('.*(?:enc|dec)_(?:conv|upsample|pooling)_(\\d).*', x)\nIS_TOP_LEVEL = lambda x: int(LEVEL_NUMBER(x)[1]) < 3 if LEVEL_NUMBER(x) is not None else False or bool(re.match(FC_LAYER_REGEXP, x))\nIS_BOTTOM_LEVEL = lambda x: int(LEVEL_NUMBER(x)[1]) >= 3 if LEVEL_NUMBER(x) is not None else False\n\nLAYER_SELECTION = {'INPUT': lambda x: bool(re.match(IN_LAYER_REGEXP, x)),\n 'FULLYCONNECTED': lambda x: bool(re.match(FC_LAYER_REGEXP, x)),\n 'ENCODER': lambda x: bool(re.match(ENC_LAYER_REGEXP, x)),\n 'DECODER': lambda x: bool(re.match(DEC_LAYER_REGEXP, x)),\n 'TOP': lambda x: IS_TOP_LEVEL(x),\n 'BOTTOM': lambda x: IS_BOTTOM_LEVEL(x)\n }\n\n# STUPID IDEA THAT COMPLICATES THINGS. The points was to allow combinations of the layer groups\n# OR_GROUPS = ['ENCODER', 'DECODER', 'INPUT', 'OUTPUT', 'FULLYCONNECTED'] # These groups can be OR'ed with the AND_GROUPS and among them. E.g., Top layers of the encoder and decoder: ENCODER or DECODER and TOP\n# AND_GROUPS = ['TOP', 'BOTTOM'] # These groups can be AND'ed with the OR_GROUPS and among them\n","sub_path":"COMET/augmentation_constants.py","file_name":"augmentation_constants.py","file_ext":"py","file_size_in_byte":2817,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"404915811","text":"\"\"\"\nFlask Documentation: http://flask.pocoo.org/docs/\nJinja2 Documentation: http://jinja.pocoo.org/2/documentation/\nWerkzeug Documentation: http://werkzeug.pocoo.org/documentation/\nThis file creates your application.\n\"\"\"\n\nfrom app import app,db\nfrom flask import render_template, request, redirect, url_for, flash\nfrom app.forms import MyForm\nfrom app.models import UserProfile\nfrom werkzeug.utils import secure_filename\nimport psycopg2 \nimport os \nfrom datetime import datetime\n\n\n###\n# Routing for your application.\n###\n\n@app.route('/')\ndef home():\n \"\"\"Render website's home page.\"\"\"\n return render_template('home.html')\n\n\n@app.route('/about/')\ndef about():\n \"\"\"Render the website's about page.\"\"\"\n return render_template('about.html', name=\"Mary Jane\")\n\n@app.route('/allprofiles/')\ndef fullprofile(userid):\n \"\"\"Render the website's about page.\"\"\"\n user=UserProfile.query.get(userid)\n return render_template('fullprofile.html', user=user, startdate=format_date_joined(12, 2, 2018))\n\n@app.route('/allprofiles/')\ndef Users(): \n users=db.session.query(UserProfile).all()\n return render_template('allprofiles.html', users=users)\n\n###\n# The functions below should be applicable to all Flask apps.\n###\n\n@app.route('/profile/', methods=('GET', 'POST'))\ndef profile():\n form = MyForm()\n if request.method=='POST' and form.validate_on_submit():\n firstname=request.form['firstname']\n lastname=request.form['lastname']\n gender=request.form['gender']\n email=request.form['email']\n location=request.form['location']\n biography=request.form['biography']\n profilepic = form.profilepic.data\n \n \n filename=secure_filename(profilepic.filename)\n profilepic.save(os.path.join(app.config['UPLOAD_FOLDER'],filename))\n \n userprofile = UserProfile(firstname,lastname,gender,email,location,biography, filename)\n db.session.add(userprofile)\n db.session.commit()\n \n flash('Yup. you been added')\n return redirect(url_for('Users'))\n \n return render_template('profile.html', form=form)\n \n \n \n# Flash errors from the form if validation fails\ndef flash_errors(form):\n for field, errors in form.errors.items():\n for error in errors:\n flash(u\"Error in the %s field - %s\" % (\n getattr(form, field).label.text,\n error\n ), 'danger')\n\n\n@app.route('/.txt')\ndef send_text_file(file_name):\n \"\"\"Send your static text file.\"\"\"\n file_dot_text = file_name + '.txt'\n return app.send_static_file(file_dot_text)\n\n\n@app.after_request\ndef add_header(response):\n \"\"\"\n Add headers to both force latest IE rendering engine or Chrome Frame,\n and also tell the browser not to cache the rendered page. If we wanted\n to we could change max-age to 600 seconds which would be 10 minutes.\n \"\"\"\n response.headers['X-UA-Compatible'] = 'IE=Edge,chrome=1'\n response.headers['Cache-Control'] = 'public, max-age=0'\n return response\n\n\n@app.errorhandler(404)\ndef page_not_found(error):\n \"\"\"Custom 404 page.\"\"\"\n return render_template('404.html'), 404\n\ndef format_date_joined(month,day, year):\n x = datetime(year,month,day) \n return(x.strftime(\"%B\" + \" \" +\"%d\"+ \" \"+\"%Y\"))\n \nif __name__ == '__main__':\n app.run(debug=True, host=\"0.0.0.0\", port=\"8080\")\n","sub_path":"app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3409,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"594210751","text":"\nimport gspm\nimport re \nimport io\nfrom setuptools import setup, find_packages\n\nlong_desc = \"missing\"\n\nwith io.open('README.md') as t_file:\n long_desc = t_file.read()\n\n# __version__ = re.search(\n# r'__version__\\s*=\\s*[\\'\"]([^\\'\"]*)[\\'\"]', # It excludes inline comment too\n# io.open('gspm/__init__.py', encoding='utf_8_sig').read()\n# ).group(1)\n\ni_requires = ['pyyaml', 'gitpython', 'dotmap', 'wget', 'packaging', 'cookiecutter']\nt_requires = []\n\nsetup(\n\n name=gspm.__id__,\n version=gspm.__version__,\n description=gspm.__desc__,\n long_description=long_desc,\n long_description_content_type='text/markdown',\n url='https://gitlab.com/godot-stuff/gs-project-manager.git',\n author='Paul Hocker',\n author_email='paul@spocker.net',\n license='MIT',\n packages=find_packages('.'),\n #package_data={'gspm': ['./gspm/templates/*.*', './gspm/assets/*.*']},\n include_package_data=True,\n install_requires=i_requires,\n zip_safe=True,\n tests_require=t_requires,\n entry_points={\n 'console_scripts': ['gspm=gspm.gspm:run'],\n },\n classifiers=[\n # Picked from\n # http://pypi.python.org/pypi?:action=list_classifiers\n 'Development Status :: 2 - Pre-Alpha',\n 'License :: OSI Approved :: MIT License',\n 'Natural Language :: English',\n 'Operating System :: MacOS',\n 'Operating System :: Microsoft :: Windows',\n 'Operating System :: POSIX :: Linux',\n 'Programming Language :: Python :: 3.6',\n 'Programming Language :: Python :: 3.5',\n 'Programming Language :: Python :: 3.4',\n 'Topic :: Utilities',\n 'Topic :: Games/Entertainment',\n 'Environment :: Console',\n ]\n)\n","sub_path":"pypi_install_script/gspm-0.1.15.tar/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1715,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"248298539","text":"import socket\nimport threading\nimport websockets\nimport asyncio\n\n\n# used for sending returned data from the receiver server (transaction server connection) to original client\nreturned_data = []\n\n# Connect to haproxy server\nhaproxyPort = 8090\nhaproxySocket = None\n\nrecvAddress = None\n\n\n# Server loop, receives data from client connections, and sends it to haproxy server load balancer.\n'''\ndef client_connection(haproxySocket, client_server_socket):\n\n global returned_data\n\n server_address = client_server_socket.getsockname()\n \n while True:\n print('[client_connection]: waiting for a connection on '+server_address[0]+':'+str(server_address[1]) +' (transaction server -> webserver connection)')\n connection, client_address = client_server_socket.accept()\n\t\n try:\n print(\"[client_connection]: connection received\")\n while True:\n \n data = connection.recv(1024)\n if data:\n print(\"[client_connection]:\" + data.decode())\n returnMsg = \"[client_connection]: client server received from you: \" + data.decode()\n connection.sendall(returnMsg.encode('utf-8'))\n \n data_string = data.decode()\n data_string = data_string.rstrip()\n print(data_string)\n \n # send to haproxy commands\n haproxySocket.sendall(data_string.encode('utf-8') + '\\n'.encode())\n \n while True: \n if returned_data:\n connection.sendall(returned_data)\n returned_data = None\n break\n\n else:\n print(\"[client_connection]: no more data from client\")\n break\n finally:\n print(\"client closed\")\n connection.close() \t \n'''\n\nasync def client_connection(websocket, path):\n\n global returned_data\n global haproxySocket\n\n\n while True:\n\n print(\"[client_connection]: awaiting data\")\n\n try:\n data = await websocket.recv()\n print(\"[client_connection]: data arrived\")\n except:\n print(\"client connection closed\")\n break\n\n response = data.rstrip()\n print(\"sending data: \",response)\n\n #await websocket.send(\"got it, thanks\")\n\n haproxySocket.sendall(response.encode('utf-8') + '\\n'.encode())\n somethingHappened = False\n\n while True:\n if len(returned_data) > 0:\n somethingHappened = True\n print(\"returning \", returned_data)\n await websocket.send(returned_data[0].decode())\n del returned_data[0]\n elif len(returned_data) == 0 and somethingHappened == True:\n break\n return\n\n\n\ndef ping_haproxy():\n global haproxySocket\n\n if(haproxySocket):\n haproxySocket.sendall(\"[1] PING\\n\".encode())\n\ndef receiver(recv_server_socket):\n\n global returned_data\n global haproxySocket\n global recvAddress\n \n\n while True:\n\n server_address = recv_server_socket.getsockname()\n recvAddress = server_address[0] + \":\" + str(server_address[1])\n\n #connect to haproxy\n haproxySocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n haproxySocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n haproxySocket.connect(('haproxy', haproxyPort)) \n haproxySocket.sendall(recvAddress.encode() + \"\\n\".encode())\n\n print('[receiver]: waiting for a connection on '+recvAddress+' (transaction server -> webserver connection)')\n connection, client_address = recv_server_socket.accept()\n\n try:\n print(\"[receiver]: connection received, connected to \", client_address)\n while True:\n \n data = connection.recv(1000000)\n print(\"recieved data \", data)\n if data:\n \n if data.decode() != 'ping\\n':\n returned_data.append(data)\n \n else:\n print(\"[receiver]: no more data from client\")\n break\n finally:\n print(\"receiver closed connection\")\n connection.close()\n haproxySocket.close()\n \n\ndef main():\n\n '''\n t = threading.Timer(10.0, ping_haproxy)\n t.start()\n '''\n\n # server config\n \n hostport = 9081 # host port (of the docker container) to map webserver to.\n \n hostIp = socket.gethostbyname(socket.gethostname())\n server_address = (hostIp, hostport) # specify the server address, set at localhost and PORT.\n \n '''\n client_server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n client_server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n client_server_socket.bind(server_address)\n client_server_socket.listen(5)\n '''\n start_client_connection = websockets.serve(client_connection, server_address[0], hostport )\n print(\"[client_connection]: websocket server started, listening at: %s:%d\" % (server_address[0],hostport))\n\n\n\n # server config\n #send recv server details to haproxy\n recvPort = 9082\n hostIP = socket.gethostbyname(socket.gethostname())\n server_address = (hostIP, recvPort) # specify the server address, set at localhost and PORT.\n \n recv_server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n recv_server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n recv_server_socket.bind(server_address)\n recv_server_socket.listen(5)\n\n\n receiving_thread = threading.Thread(target=receiver, args=(recv_server_socket,))\n receiving_thread.start()\n\n '''\n client_thread = threading.Thread(target=client_connection, args=(haproxySocket, client_server_socket,))\n client_thread.start()\n '''\n\n asyncio.get_event_loop().run_until_complete(start_client_connection)\n asyncio.get_event_loop().run_forever()\n\n\n \n\n\nif __name__ == '__main__':\n main()\n","sub_path":"Software Systems Scalability/webserver-tcp-server/webserver.py","file_name":"webserver.py","file_ext":"py","file_size_in_byte":6176,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"160461094","text":"from classesdistribuidora import util\nfrom classesdistribuidora.venda import Venda\nfrom datetime import datetime\nfrom controllerdistribuidora.controllerbebida import percorrer_bebidas\nfrom controllerdistribuidora.controllercliente import percorrer_cliente, cnpj_generator\nfrom controllerdistribuidora.controllerfuncionario import percorrer_funcionario\nfrom controllerdistribuidora.controllerestoque import percorrer_estoque\n\ndef gerar_data():\n hoje = datetime.now()\n return '{}/{}/{}'.format(hoje.day, hoje.month, hoje.year)\n\ndef gerar_id():\n ids = []\n vendas = util.retornar_vendas()\n for venda in vendas:\n ids.append(venda['id'])\n return max(ids) + 1\n\ndef efetuar_venda(qtd, codigo, cnpj, login):\n cliente, ic = percorrer_cliente(cnpj)\n bebida, ib = percorrer_bebidas(codigo, 3)\n vendedor = percorrer_funcionario(login, 1)\n estoque, ie = percorrer_estoque(codigo)\n if cliente and bebida and vendedor:\n if qtd.isdigit() and int(qtd) > 0 and estoque.get_qtd() >= int(qtd):\n cnpj = cnpj_generator(cnpj)\n bebidas_estoque = util.retornar_estoque()\n bebidas_estoque[ie]['qtd'] -= int(qtd)\n util.inserir_bebida_estoque(bebidas_estoque)\n\n vendas = util.retornar_vendas()\n vendas.append({'id': gerar_id(),\n 'data': gerar_data(),\n 'qtd': int(qtd),\n 'valor': int(qtd) * bebida.get_valor(),\n 'cod': codigo,\n 'cnpj': cnpj,\n 'vendedor': login})\n util.inserir_venda(vendas)\n return 2\n return 1\n return 0\n\ndef gerar_relatorio_dia(dia, mes, ano):\n if len(dia) == 2 and dia[0] == '0':\n dia = dia.replace('0', '')\n if len(mes) == 2 and mes[0] == '0':\n mes = mes.replace('0', '')\n if len(ano) == 2:\n ano = '{}{}'.format('20', ano)\n data = '{}/{}/{}'.format(dia, mes, ano)\n vendas = util.retornar_vendas()\n vendas_dia = list(filter(lambda v: v['data'] == data, vendas))\n if len(vendas_dia) > 0:\n return vendas_dia\n return ''\n\ndef gerar_relatorio_cliente(cnpj):\n cliente, i = percorrer_cliente(cnpj)\n if cliente:\n cnpj = cnpj_generator(cnpj)\n vendas = util.retornar_vendas()\n vendas_cliente = list(filter(lambda v: v['cnpj'] == cnpj, vendas))\n if len(vendas_cliente) > 0:\n return vendas_cliente, cliente\n return 1, None\n return 0, None\n\ndef gerar_relatorio_vendedor(login):\n vendedor = percorrer_funcionario(login, 1)\n if vendedor:\n vendas = util.retornar_vendas()\n vendas_vendedor = list(filter(lambda v: v['vendedor'] == login, vendas))\n\n if len(vendas_vendedor) > 0:\n return vendas_vendedor, vendedor\n return 1, None\n return 0, None\n\ndef gerar_relatorio_produto(codigo):\n bebida = percorrer_bebidas(codigo, 0)\n if bebida:\n vendas = util.retornar_vendas()\n vendas_bebida = list(filter(lambda v: v['cod'] == codigo, vendas))\n if len(vendas_bebida) > 0:\n return vendas_bebida, bebida\n return 1, None\n return 0, None","sub_path":"controllerdistribuidora/controllervendas.py","file_name":"controllervendas.py","file_ext":"py","file_size_in_byte":3199,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"478767340","text":"#pylint: disable=C0301\n#pylint: disable=R0904\n\nimport os\nimport re\nimport osgtest.library.core as core\nimport osgtest.library.files as files\nimport osgtest.library.osgunittest as osgunittest\n\nclass TestCondorCE(osgunittest.OSGTestCase):\n def general_requirements(self):\n core.skip_ok_unless_installed('condor', 'htcondor-ce', 'htcondor-ce-client')\n self.skip_bad_unless(core.state['condor-ce.started'], 'ce not running')\n\n def test_01_status(self):\n self.general_requirements()\n\n command = ('condor_ce_status', '-long')\n core.check_system(command, 'ce status', user=True)\n\n def test_02_queue(self):\n self.general_requirements()\n\n command = ('condor_ce_q', '-verbose')\n core.check_system(command, 'ce queue', user=True)\n\n def test_03_ping(self):\n self.general_requirements()\n\n command = ('condor_ce_ping', 'WRITE', '-verbose')\n stdout, _, _ = core.check_system(command, 'ping using GSI and gridmap', user=True)\n self.assert_(re.search(r'Authorized:\\s*TRUE', stdout), 'could not authorize with GSI')\n\n def test_04_trace(self):\n self.general_requirements()\n\n cwd = os.getcwd()\n os.chdir('/tmp')\n\n command = ('condor_ce_trace', '--debug', core.get_hostname())\n core.check_system(command, 'ce trace', user=True)\n\n os.chdir(cwd)\n\n def test_05_pbs_trace(self):\n self.general_requirements()\n core.skip_ok_unless_installed('torque-mom', 'torque-server', 'torque-scheduler', 'torque-client', 'munge')\n self.skip_ok_unless(core.state['torque.pbs-server-running'])\n\n cwd = os.getcwd()\n os.chdir('/tmp')\n\n command = ('condor_ce_trace', '-a osgTestPBS = True', '--debug', core.get_hostname())\n core.check_system(command, 'ce trace against pbs', user=True)\n\n os.chdir(cwd)\n\n def test_06_use_gums_auth(self):\n self.general_requirements()\n core.skip_ok_unless_installed('gums-service')\n\n # Setting up GUMS auth using the instructions here:\n # twiki.grid.iu.edu/bin/view/Documentation/Release3/InstallComputeElement#8_1_Using_GUMS_for_Authorization\n hostname = core.get_hostname()\n\n lcmaps_contents = '''gumsclient = \"lcmaps_gums_client.mod\"\n \"-resourcetype ce\"\n \"-actiontype execute-now\"\n \"-capath /etc/grid-security/certificates\"\n \"-cert /etc/grid-security/hostcert.pem\"\n \"-key /etc/grid-security/hostkey.pem\"\n \"--cert-owner root\"\n# Change this URL to your GUMS server\n \"--endpoint https://%s:8443/gums/services/GUMSXACMLAuthorizationServicePort\"\n\nverifyproxy = \"lcmaps_verify_proxy.mod\"\n \"--allow-limited-proxy\"\n \" -certdir /etc/grid-security/certificates\"\n\n# lcmaps policies require at least two modules, so these are here to\n# fill in if only one module is needed. \"good | bad\" has no effect.\ngood = \"lcmaps_dummy_good.mod\"\nbad = \"lcmaps_dummy_bad.mod\"\n\nauthorize_only:\n## Policy 1: GUMS but not SAZ (most common, default)\ngumsclient -> good | bad\n''' % hostname\n\n gums_properties_contents = '''gums.location=https://%s:8443/gums/services/GUMSAdmin\ngums.authz=https://%s:8443/gums/services/GUMSXACMLAuthorizationServicePort\n''' % (hostname, hostname)\n\n core.config['condor-ce.gums-properties'] = '/etc/gums/gums-client.properties'\n core.config['condor-ce.gsi-authz'] = '/etc/grid-security/gsi-authz.conf'\n\n files.write(core.config['condor-ce.lcmapsdb'], lcmaps_contents, owner='condor-ce.gums')\n files.write(core.config['condor-ce.gums-properties'], gums_properties_contents, owner='condor-ce')\n files.replace(core.config['condor-ce.gsi-authz'],\n '# globus_mapping liblcas_lcmaps_gt4_mapping.so lcmaps_callout',\n 'globus_mapping liblcas_lcmaps_gt4_mapping.so lcmaps_callout',\n owner='condor-ce')\n\n command = ('service', 'condor-ce', 'stop')\n core.check_system(command, 'stop condor-ce')\n\n # Need to stat the Schedd logfile so we know when it's back up\n core.config['condor-ce.schedlog'] = '/var/log/condor-ce/SchedLog'\n core.config['condor-ce.schedlog-stat'] = os.stat(core.config['condor-ce.schedlog'])\n\n command = ('service', 'condor-ce', 'start')\n core.check_system(command, 'start condor-ce')\n\n def test_07_ping_with_gums(self):\n self.general_requirements()\n core.skip_ok_unless_installed('gums-service')\n\n # Wait for the collector to come back up\n core.monitor_file(core.config['condor-ce.schedlog'],\n core.config['condor-ce.schedlog-stat'],\n 'TransferQueueManager stats',\n 60.0)\n\n command = ('condor_ce_ping', 'WRITE', '-verbose')\n stdout, _, _ = core.check_system(command, 'ping using GSI and gridmap', user=True)\n self.assert_(re.search(r'Authorized:\\s*TRUE', stdout), 'could not authorize with GSI')\n\n","sub_path":"osgtest/tests/test_55_condorce.py","file_name":"test_55_condorce.py","file_ext":"py","file_size_in_byte":5048,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"419285191","text":"# -*- coding: utf-8 -*-\nfrom database import Database\nfrom processor import Processor\n\nfrom mailer import Mailer\nfrom time import sleep\n\nfrom upwork_client import UpworkClient\n\n\ndef run_mailer(upwork):\n db = Database()\n db.init_database()\n mailer = Mailer()\n processor = Processor(db, mailer)\n\n while True:\n jobs = upwork.get_latest_jobs()\n processor.process_jobs(jobs)\n sleep(10)\n\n\nif __name__ == '__main__':\n upwork = UpworkClient()\n while True:\n if not upwork.login():\n continue\n run_mailer(upwork)\n","sub_path":"src/application.py","file_name":"application.py","file_ext":"py","file_size_in_byte":569,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"560955882","text":"import numpy as np\nfrom funcPeakAlign import DPeakList,myPeakAlignment,DPeakAlignParams, fPeakList\nfrom copy import deepcopy\nfrom funcGeneral import averQ, normSimple, smoothRect, fitLinear\nfrom scipy.optimize import fmin\n\n ### SEQEUENCE ALIGNMENT ###\ndef changeNucToN(seqRNA,dSeq):\n seqRNAN=''\n for i in range(len(seqRNA)):\n if seqRNA[i]==dSeq['nuc1']:\n seqRNAN+=dSeq['nuc1']\n elif dSeq['isSeq2'] and seqRNA[i]==dSeq['nuc2']:\n seqRNAN+=dSeq['nuc2']\n else:\n seqRNAN+='N'\n return seqRNAN\n\ndef shapeSeqAlign(dProject,seqRNA):\n seq=dProject['seq0']\n seqX=dProject['seqX0']\n scoreNuc=dProject['scrNuc']\n costMSeq=shapeCostM(seqRNA,seq,scoreNuc)\n seqWid=seqX[1:]-seqX[:-1]\n seqWid=normStat(seqWid)\n seqWid=np.append(seqWid,0)\n scormat, arrow=shapeScoreM(seq,seqRNA,costMSeq,seqWid)\n alignedSeqRNA,alignedSeq,newSeqX,start,end= shapeBackTrace(scormat, arrow,seqRNA,seq,seqX)\n \n return alignedSeqRNA,alignedSeq,newSeqX,start,end\n\ndef shapeCostM(seqRNA,seq,score=None,match=2,misMatch=-1):\n n=len(seqRNA)\n m=len(seq)\n costMSeq=np.zeros([n,m])\n if score==None:\n score=np.ones(m)\n for i in range(n):\n for j in np.arange(m):\n if seqRNA[i]==seq[j]:\n if seq[j]=='N':\n costMSeq[i,j]=match/2\n else:\n costMSeq[i,j]=match*score[j]\n else:\n costMSeq[i,j]=misMatch\n return costMSeq\n\n\ndef shapeScoreM(seq,seqRNA3to5N,costMSeq,seqWid,gap=-5.0):\n NSeq=len(seq)\n NRNA=len(seqRNA3to5N)\n \n scormat = np.zeros( [NRNA+1,NSeq+1], dtype='f4')\n arrow = np.zeros( [NRNA+1,NSeq+1], int)\n arrow[0,:] = 2 # np.ones(NSeq+1)\n arrow[:,0] = 1 #np.ones(NSeq+1)\n \n for i in range( 1,NRNA+1 ):\n for j in range(1,NSeq+1):\n gap1=gap\n gap2=gap \n if seqWid[j-1]<1 and seqWid[j-1]>-1: \n gap2+=gap\n gap1+=gap\n if arrow[i-1,j]==1:\n gap1+=gap\n elif arrow[i,j-1]==2:\n gap2+=gap\n s0= scormat[i-1,j-1]+ costMSeq[i-1,j-1] # Matched\n s1= scormat[i-1,j] + gap1 # put gap to Seq, a peak should be added\n s2= scormat[i,j-1] + gap2 # put gap to RNA, a peak should be deleted\n \n scormat[i,j],arrow[i,j] = maxArg4(s0,s1,s2,0)\n \n return scormat, arrow\n\ndef maxArg4(s0,s1,s2,s3):\n max=s0\n arg=0\n if s1>max:\n max=s1\n arg=1\n if s2>max:\n max=s2\n arg=2\n if s3>max:\n max=s3\n arg=3\n return max, arg \n\ndef shapeBackTrace(scormat, arrow,seq1,seq2,seqX):\n newSeq1=''\n newSeq2=''\n newSeqX=np.array([])\n N1=len(seq1)\n N2=len(seq2)\n ok = 1\n v,h = divmod( scormat.argmax(), N2+1)\n end=v\n if h0:\n for i in range(h,0,-1):\n if v>0:\n newSeq1+=seq1[v-1]\n newSeq2+=seq2[h-1]\n newSeqX=np.append(newSeqX,seqX[h-1])\n v -= 1\n h -= 1\n v1,h1=v,h\n \n newSeq1=newSeq1[::-1]\n newSeq2=newSeq2[::-1]\n newSeqX=newSeqX[::-1]\n # reverse the strings\n start=v1# (v1-h1) \n \n return newSeq1,newSeq2,newSeqX,start,end\n\ndef applySeqAlign(dProjOut,seqRNA3to5N,start,end):\n alignedSeqRNA,alignedSeq,newSeqX,startNucI,endNucI=shapeSeqAlign(dProjOut,seqRNA3to5N[start:end])\n newSeqX,newSeq=nucAddDelete(alignedSeqRNA,alignedSeq,newSeqX)\n \n startNucI=startNucI+start \n endNucI=startNucI+len(newSeqX) \n NSeqRNA=len(dProjOut['RNA']) \n dProjOut['start']=NSeqRNA-startNucI\n dProjOut['end']=dProjOut['start']-len(newSeqX)\n dProjOut['seqX']=np.array(newSeqX,int)\n dProjOut['seqRNA']=dProjOut['RNA'][::-1][startNucI:endNucI]\n dProjOut['seqNum']=np.arange(dProjOut['start'],dProjOut['end'],-1) \n return dProjOut\n\n\ndef nucAddDelete(seqRNA,seq,seqX):\n NSeq=len(seq)\n seq0=list(seq)\n# for i in range(NSeq):\n# if seq[i]=='-':\n# seqX=np.insert(seqX,i,0) \n# \n# Find the match points\n matchI=np.array([0],dtype='i4')\n i=0\n while iNGapSeq:\n # delete a peak\n xx=np.array([])\n ss=[]\n for m in range(matchI[i],matchI[i+1]+1,1):\n if seqX[m]!=0:\n xx=np.append(xx,seqX[m])\n ss.append(seq[m])\n diffGap=NGapRNA-NGapSeq\n while diffGap>0:\n widXX=xx[1:]-xx[:-1]\n argmin0=np.argmin(widXX)\n if argmin0==0:\n argmin0+=1\n xx=np.delete(xx,argmin0)\n del ss[argmin0]\n diffGap-=1\n newSeqX=np.append(newSeqX,xx[:-1]) \n newSeq.append(''.join(ss[:-1])) \n elif NGapRNA0:\n widXX=xx[1:]-xx[:-1]\n argmax0=np.argmax(widXX)\n ind=argmax0+1\n x=int((xx[ind-1]+xx[ind])/2)\n xx=np.insert(xx,ind,x)\n ss.insert(ind,'N')\n diffGap-=1\n newSeqX=np.append(newSeqX,xx[:-1])\n newSeq.append(''.join(ss[:-1])) \n \n newSeqX=np.append(newSeqX,seqX[matchI[-1]])\n newSeq.append(seq[matchI[-1]])\n newSeq=''.join(newSeq)\n newSeq=list(newSeq)\n return newSeqX,newSeq\n\n\ndef peakLinking(seqX,dPeakList1,data1,isOptPos=False,minScore=0.5): \n dPeakList0=DPeakList()\n dPeakList0['pos']=np.array(seqX,dtype='i4')\n dPeakList0['NPeak']=len(seqX)\n dParams=DPeakAlignParams()\n dParams['simFunc']='Position'\n dParams['minScore']=minScore\n dParams['timeT'] = 0.0\n aligned0,aligned1 = myPeakAlignment(dPeakList0,dPeakList1,dParams)\n dPeakList11,controlA = findLinkedPeaks(aligned0,aligned1,dPeakList1,data1,isOptPos)\n return dPeakList11, controlA\n\n \ndef findLinkedPeaks(aligned0,aligned1,dPeakList1,data1,isOptPos):\n controlA=np.array([],int)\n newPeakX1=np.array([],int)\n \n NAligned=len(aligned0)\n if aligned0[0]!=-1 and aligned1[0]!=-1:\n newPeakX1=np.append(newPeakX1,aligned1[0])\n controlA=np.append(controlA,1)\n elif aligned0[0]!=-1 and aligned1[0]==-1:\n newPeakX1=np.append(newPeakX1,aligned0[0])\n controlA=np.append(controlA,0)\n i=1 \n while i160:\n K=80\n else:\n K=NSeq\n kat=int(NSeq/K)\n for i in range(kat):\n s=i*K\n if i==kat-1:\n e=NSeq\n else:\n e=(i+1)*K\n seq0,scoreNuc0 = findSeqPart(dProject,peakListS1,peakListS2,peakListBG,s,e)\n seq[s:e]=seq0\n scoreNuc[s:e]=scoreNuc0\n \n dProject['seq0']=seq\n dProject['seqX0']=seqX\n dProject['scrNuc']=scoreNuc\n \n return dProject\n\n\ndef findSeqX(peakListBG,peakListS1):\n dParams=DPeakAlignParams()\n dParams['simFunc']='Position'\n aligned0,aligned1=myPeakAlignment(peakListBG,peakListS1,dParams)\n seqX=np.array([],int)\n for i in range(2,len(aligned0)-1,1):\n if aligned1[i]==-1:\n if aligned0[i-1]!=-1 and aligned1[i-1]!=-1:\n if aligned0[i+1]!=-1 and aligned1[i+1]!=-1:\n pos0=aligned1[i-1]\n pos1=aligned1[i+1]\n if (pos1-pos0)>1.2*peakListS1['averW']:\n newPos=int((pos1+pos0)/2)\n seqX=np.append(seqX,newPos)\n else:\n seqX=np.append(seqX,aligned1[i])\n return seqX\n\ndef findSeqPart(dProject,peakListS1,peakListS2,peakListBG,s,e):\n thres=1.3\n factor=scaleShapeData(peakListS1['amp'][s:e],peakListBG['amp'][s:e],rate=0.5)\n newSeqY1=peakListS1['amp'][s:e]/factor\n NSeq1=len(newSeqY1)\n seq0=['N']*NSeq1\n scoreNuc0=np.ones(NSeq1)\n averY1=np.average(newSeqY1)\n for i in range(NSeq1):\n kat0=newSeqY1[i]/averY1\n if kat0>2:\n kat0=2\n scoreNuc0[i]=kat0\n if kat0>0.8:\n kat1=newSeqY1[i]/peakListBG['amp'][s+i]\n if kat1>thres:\n seq0[i]=dProject['nuc1']\n \n if dProject['isSeq2']:\n factor=scaleShapeData(peakListBG['amp'][s:e],peakListS2['amp'][s:e],rate=0.5)\n newSeqY2=peakListS2['amp'][s:e]/factor\n averY2=np.average(newSeqY2)\n for i in range(NSeq1):\n if newSeqY2[i]>averY2 and newSeqY2[i]>newSeqY1[i]:\n kat0=newSeqY2[i]/averY2\n kat1=newSeqY2[i]/peakListBG['amp'][s+i]\n if kat1>2:\n kat1=2\n scoreNuc0[i]=kat0\n if kat1>thres:\n seq0[i]=dProject['nuc2']\n \n return seq0,scoreNuc0\n\n\n### FAST SEQUENCE ALIGNMENT \ndef seqAlignFast(seqR,seq):\n NSeq=len(seq)\n NSeqR=len(seqR)\n fark=NSeqR-NSeq\n if fark<1:\n start=0\n return start\n scr=np.zeros(fark)\n for i in range(fark):\n scr[i]=findScoreFast(seqR[i:i+NSeq],seq)\n start=np.argmax(scr)\n return start\n \ndef findScoreFast(seqR,seq):\n scr=0\n for i in range(len(seqR)):\n if seqR[i]==seq[i] and seq[i]!='N':\n scr+=1\n return scr \n \n ### GAUSSIAN FIT ##3\ndef fitFuncG(x,pos,amp,wid):\n return amp * np.exp(-2*(x-pos)**2/wid**2)\n\ndef fitShapeData(dPeakList,dataIn,controlA=None,isOptPos=True):\n NPeak=dPeakList['NPeak']\n sigma=optimizeOneSigma(dataIn,dPeakList['pos'],dPeakList['amp'])\n if isOptPos: \n dPeakList=optimizePosition(dataIn,dPeakList,sigma,controlA)\n dPeakList['wid']=optimizeAllSigma(dataIn,dPeakList,sigma)\n dPeakList['amp']=optimizeAmp(dataIn,dPeakList)\n dPeakList['area']=np.abs(dPeakList['amp']*dPeakList['wid'])\n \n return dPeakList\n\ndef optimizeOneSigma(inputA,peakX,peakY):\n peakX=np.array(peakX)\n peakY=np.array(peakY)\n averW1=peakX[1:]-peakX[:-1]\n averW=np.nanmean(averW1[int(len(averW1)*0.1):int(len(averW1)*0.9)])\n wid=averW*0.45\n controlWid=np.arange(wid*0.8,wid*1.2,0.1)\n errorWid=np.ones(len(controlWid))\n NPeak=len(peakX)\n NData=len(inputA)\n x=np.arange(NData)\n for j in range(len(controlWid)):\n A=np.zeros(NData)\n for i in range(NPeak):\n y=fitFuncG(x,peakX[i],peakY[i],controlWid[j])\n A=A+y\n errorWid[j]=np.sum(np.abs(A-inputA)) #/np.sum(inputA)\n return controlWid[np.argmin(errorWid)]\n\n\ndef optimizeAllSigma(dataA,peakList,wid=5):\n newSig=np.ones(peakList['NPeak'])*wid\n #print peakList['NPeak']\n for i in range(1,peakList['NPeak']-1):\n controlSig=np.arange(wid*0.9,wid*1.1,0.1)\n errorPos=np.ones(len(controlSig))*9999\n x=np.arange(peakList['pos'][i-1],peakList['pos'][i+1]+1,1,dtype='i4')\n #print x\n y=dataA[x] \n for j in range(len(controlSig)):\n sig=controlSig[j]\n y1=fitFuncG(x,peakList['pos'][i-1],peakList['amp'][i-1],newSig[i-1])\n y2=fitFuncG(x,peakList['pos'][i],peakList['amp'][i],sig)\n y3=fitFuncG(x,peakList['pos'][i+1],peakList['amp'][i+1],newSig[i+1])\n y4=y1+y2+y3\n errorPos[j]=np.sum(np.abs(y4-y)) #/np.sum(y)\n\n newSig[i]=controlSig[np.argmin(errorPos)] \n return newSig\n\n\ndef optimizePosition(dataA,peakList,sigma,controlA=None):\n NPeak=peakList['NPeak']\n #print len(peakList['pos'])\n if controlA==None:\n controlA=np.zeros(NPeak)\n \n for i in range(1,NPeak-1):\n if controlA[i]==0:\n controlX=peakList['pos'][i] \n start=controlX-3\n end=controlX+4\n \n controlPos=np.arange(start,end,1)\n errorPos=np.ones(len(controlPos))*9999\n x=np.arange(peakList['pos'][i-1],peakList['pos'][i+1]+1,1,dtype='i4')\n y=dataA[x] \n for j in range(len(controlPos)):\n pos=controlPos[j]\n amp=dataA[int(pos)]\n y1=fitFuncG(x,peakList['pos'][i-1],peakList['amp'][i-1],sigma)\n y2=fitFuncG(x,peakList['pos'][i+1],peakList['amp'][i+1],sigma)\n y3=fitFuncG(x,pos,amp,sigma)\n y4=y1+y2+y3\n errorPos[j]=np.sum(np.abs(y4-y)) #/np.sum(y)\n peakList['pos'][i]=controlPos[np.argmin(errorPos)]\n peakList['amp'][i]=dataA[int(peakList['pos'][i])] \n return peakList\n\n\ndef optimizeAmp(dataA,peakList,wid=5):\n newAmp=np.zeros(len(peakList['pos']),dtype='f4')\n newAmp=peakList['amp'].copy()\n newAmpUp=newAmp.copy()\n newAmpUp*=1.2\n newAmpDown=newAmp.copy()\n newAmpDown*=0.8\n \n for k in range(5): \n for i in range(1,len(peakList['pos'])-1):\n x=peakList['pos'][i]\n y1=fitFuncG(x,peakList['pos'][i-1],newAmp[i-1],peakList['wid'][i-1])\n y2=fitFuncG(x,peakList['pos'][i+1],newAmp[i+1],peakList['wid'][i+1])\n newY=dataA[int(x)]-y1-y2\n if newY>newAmpUp[i]:\n newY=newAmpUp[i]\n elif newYnewAmpUp[i]:\n newY=newAmpUp[i]\n elif newY=1:\n A=data0.copy()\n B=data1.copy()\n else:\n A,B=selectDataForScale1(data0,data1,rate)\n \n A,B=removeDifferenceOutlier(A,B)\n \n # newFactor=findScaleFactor0(A,B)\n # print 'scale factor', newFactor\n newFactor= optimizeScaleFactor(A,B)\n \n return newFactor\n\n\ndef selectDataForScale1(data0,data1,rate=0.25):\n \"\"\" Select the lowest RX area with corresponding BG area\n \"\"\"\n NData=len(data0)\n argSorted0=np.argsort(data0)\n NSelect=int(NData*rate)\n #s=int(NData*0.5)\n #e=int(NData*rate)\n selectedArgSortAreaRX=argSorted0[:NSelect]\n A=np.zeros(NSelect)\n B=np.zeros(NSelect)\n for i in range(len(selectedArgSortAreaRX)):\n ind=selectedArgSortAreaRX[i]\n A[i]=data0[ind]\n B[i]=data1[ind]\n return A,B\n\n\ndef removeDifferenceOutlier(A,B):\n diff=A-B\n sortedDiff=np.argsort(diff)\n N=len(diff)\n newA, newB = np.array([]), np.array([])\n q1=int(N*0.2)\n q3=int(N*0.8)+1\n for i in range(q1,q3):\n newA=np.append(newA,A[sortedDiff[i]])\n newB=np.append(newB,B[sortedDiff[i]])\n \n return newA,newB\n\n\ndef optimizeScaleFactor(A,B,func='Data'):\n factor=1.0\n if func=='Data':\n resultList= fmin(scaleFactorFuncData, factor, args=(A,B),full_output=1,disp=0)\n elif func=='Median':\n resultList= fmin(scaleFactorFuncMedian, factor, args=(A,B),full_output=1,disp=0)\n else:\n resultList= fmin(scaleFactorFuncAver, factor, args=(A,B),full_output=1,disp=0)\n \n if resultList[4]==0:\n scaleFactor=resultList[0]\n else:\n scaleFactor=1\n return float(scaleFactor)\n\ndef scaleFactorFuncData(factor,A,B):\n err=np.sum(np.abs(A-factor*B))\n return err\n\ndef scaleFactorFuncMedian(factor,A,B):\n err=np.abs(np.median(A)-factor*np.median(B))\n return err\n\ndef scaleFactorFuncAver(factor,A,B):\n err=np.abs(averQ(A)-factor*averQ(B))\n return err\n\ndef scaleShapeDataWindow(data0,data1,deg=40,rate=1,step=10,fit=None,ref=None):\n N=len(data0)\n win=2*deg+1\n if NN-deg:\n e=N\n s=N-win\n else:\n s=i-deg\n e=i+deg+1 \n partData0=data0[s:e]\n partData1=data1[s:e]\n scaleFactor=scaleShapeData(partData0,partData1,rate)\n aScaleFactor=np.append(aScaleFactor,scaleFactor)\n aX=np.append(aX,i)\n \n #aY=scipy.signal.medfilt(aScaleFactor,5) \n aY = smoothRect(aScaleFactor,degree=2)\n aX=aX[1:-1]\n aY=aY[1:-1]\n fittedSig = fitLinear(aX,aY,len(data1))\n # data11=data1*fittedSig\n if fit=='linear':\n newX=np.arange(len(fittedSig))\n coeff=np.polyfit(newX,fittedSig,1)\n poly=np.poly1d(coeff)\n fittedSig=np.polyval(poly, newX)\n if fit=='exp':\n newX=np.arange(len(fittedSig))\n if ref==0:\n data11=data1*fittedSig\n return data11\n if ref==1:\n data00=data0/fittedSig\n return data00\n \n return fittedSig\n\n ### NORMALIZATION \n \ndef findPOutlierBox(dataIn):\n#Order the SHAPE reactivities from largest to smallest take the top 10% of the data - excluding outliers - this is your normalization factor - divide all the data by this number.\n#Outliers are defined either by --- anything higher than - 1.5*(Quartile3-Quartile1)+Quartile3 or the top 10% of the data - whichever is less.\n#Note - The quartiles come from the traditional box plot calculation (this can be done in Excel by doing =QUARTILE(B:B,1) if the reactivities are in column B) \n\n NData=len(dataIn)\n if NData<50:\n return 2.0,10.0\n dataSorted=np.sort(dataIn)\n a1=int(NData*0.25) \n a2=int(NData*0.5)\n a3=int(NData*0.75)\n Q1=dataSorted[a1]\n Q2=dataSorted[a2]\n Q3=dataSorted[a3]\n QThres=1.5*(Q3-Q1)+Q3\n \n NOutlier=0\n for i in range(NData-1,0,-1):\n if dataSorted[i]>QThres:\n NOutlier+=1\n else:\n break\n \n POutlier=float(NOutlier)/float(NData)*100\n # if POutlier>8.0:\n # POutlier=8.0 \n PAver=10.0 \n if NData<100:\n PAver = (10.0/ float(NData)) * 100\n \n return POutlier, PAver\n\ndef normBox(dataIn, scale=1):\n dataNormed=deepcopy(dataIn)\n POutlier,PAver=findPOutlierBox(dataNormed)\n dataNormed , aver= normSimple(dataNormed,POutlier,PAver)\n dataNormed = dataNormed * scale\n return dataNormed\n\ndef normSimple(dataIn,POutlier=2.0, PAver=10.0):\n NData=len(dataIn)\n NOutlier=int(float(NData)*float(POutlier)/100.0)\n if NOutlier<1:\n NOutlier=1 \n NAver=int(float(NData)*float(PAver)/100.0) + NOutlier\n \n dataSorted=np.sort(dataIn)\n aver=np.nanmean(dataSorted[-NAver:-NOutlier])\n dataNormed=dataIn/aver\n return dataNormed, aver\n\ndef normStat(data):\n normalized=np.zeros(len(data))\n mean=np.mean(data)\n std=np.std(data)\n normalized=(data-(mean))/std\n #normalized=normalized+1\n return normalized\n ### REPORT \nreportKeys=['seqNum','seqRNA','posSeq','posRX','areaRX','posBG','areaBG','areaDiff','normDiff']\ndef DReport():\n dReport={}\n dReport['seqNum']=np.array([],dtype='i4')\n dReport['seqRNA']=''\n dReport['posSeq']=np.array([],dtype='i4')\n dReport['posRX']=np.array([],dtype='i4')\n dReport['areaRX']=np.array([],dtype='i4')\n dReport['posBG']=np.array([],dtype='i4')\n dReport['areaBG']=np.array([],dtype='i4')\n dReport['areaDiff']=np.array([],dtype='i4')\n dReport['normDiff']=np.array([],dtype='i4')\n \n return dReport\n \ndef createDReport(dProject):\n dReport=DReport()\n dReport['seqNum']=np.array(dProject['seqNum'][1:],int)\n dReport['seqRNA']=dProject['seqRNA'][1:]\n dReport['posSeq']=np.array(dProject['seqX'][1:],int)\n dReport['posRX']=np.array(dProject['dPeakRX']['pos'][:-1],int)\n dReport['areaRX']=np.round(dProject['dPeakRX']['area'][:-1],decimals=2)\n dReport['posBG']=np.array(dProject['dPeakBG']['pos'][:-1],int)\n dReport['areaBG']=np.round(dProject['dPeakBG']['area'][:-1],decimals=2)\n dReport['areaDiff']=np.round(dProject['areaDiff'][:-1],decimals=2)\n dReport['normDiff']=np.round(dProject['normDiff'][:-1],decimals=2)\n \n return dReport\n\ndef writeReportFile(dReport,fName):\n myfile=open(fName,'w') \n for key in reportKeys:\n myfile.write(str(key)+'\\t')\n myfile.write('\\n')\n for i in range(len(dReport['seqRNA'])):\n for key in reportKeys:\n myfile.write(str(dReport[key][i])+'\\t')\n myfile.write('\\n')\n ","sub_path":"BoXFP/QuShape/funcSeqAll.py","file_name":"funcSeqAll.py","file_ext":"py","file_size_in_byte":24726,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"89073499","text":"# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, x):\n# self.val = x\n# self.next = None\n\nclass Solution:\n def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:\n # attach a dummy node\n node = ListNode(None)\n node.next = head\n head = node\n \n # two runners\n fptr = head.next\n while fptr and n:\n n -= 1\n fptr = fptr.next\n \n sptr = head\n while fptr:\n sptr = sptr.next\n fptr = fptr.next\n \n # remove the node\n sptr.next = sptr.next.next\n return head.next\n \n","sub_path":"19. Remove Nth Node From End of List/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":673,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"347351248","text":"from .utils import set_hardware_acceleration, format_time, gpu_memory_usage\nfrom typing import Optional, Tuple\nfrom tqdm import tqdm\nfrom time import time\nimport torch\nimport logging\n\n\nlogger = logging.getLogger(__name__)\n\n\ndef predict(\n input_ids: torch.Tensor,\n token_type_ids: torch.Tensor,\n attention_masks: torch.Tensor,\n model: torch.nn.Module,\n batch_size: int,\n device_: Optional[str] = None, # if None, it automatically detects if a GPU is available, if not uses a CPU\n disable_progress_bar: bool = False\n) -> Tuple[torch.Tensor, torch.Tensor]:\n \"\"\"\n Given a trained model and unseen data, performs the predictions and returns the results.\n Unlike in the fine-tuning and training stages, during prediction there's no need to build a dataloader which\n splits the set into train and validation, and randomly shuffles the training samples. We can just pass the items\n directly one by one. As we're not training, there are no training epochs either.\n :param input_ids: torch.tensor of shape (N, max_len) representing the ids of each token of the N encoded sequence\n pairs, with padding at the end up to max_len. If decoded, the input_ids will consist of a \"[CLS]\" token,\n followed by the question's tokens, followed by a \"[SEP]\" token, followed by the context's tokens, followed\n by a \"[SEP]\" token, followed by \"[PAD]\" tokens, if relevant, up to max_len.\n :param token_type_ids: torch.tensor of shape (N, max_len) where each Nth dimension is filled with 1 for token\n positions in the context text, 0 elsewhere (i.e. in question and padding)\n :param attention_masks: torch.tensor of shape (N, max_len) where each Nth dimension is filled with 1 for\n non-\"[PAD]\" tokens, 0 for \"[PAD]\" tokens.\n :param model: the model to use (must be instance of torch.nn.Module). As we're performing predictions, this must\n be a trained model.\n :param batch_size: the batch size to use for predictions. Batching samples speeds up processing.\n :param device_: if specified, the device used for the computations. Can be one of cpu, cuda, mkldnn, opengl,\n opencl, ideep, hip, msnpu. If set to None, it will default to GPU (cuda) if one is available, else it will\n use a CPU. Default: None\n :param disable_progress_bar: bool; whether to disable the tqdm progress bar. When used in production for quickly\n returning answers to a single or small set of questions, the bar might be distracting. Default: False.\n :return: pred_start: torch.tensor of shape (N) with the predicted indices of the first answer token for each answer\n pred_end: torch.tensor of shape (N) with the predicted indices of the last answer token for each answer\n \"\"\"\n assert input_ids.shape == token_type_ids.shape == attention_masks.shape, \"Some input shapes are wrong\"\n\n device = set_hardware_acceleration(default=device_)\n model = model.to(device)\n model.eval()\n\n pred_start = torch.tensor([], dtype=torch.long, device=device) # initialising tensors for storing results\n pred_end = torch.tensor([], dtype=torch.long, device=device)\n\n t_i = time()\n # batch the samples to speed up processing. We do batching manually here to avoid using DataLoader\n for batch_i in tqdm(range(0, len(input_ids), batch_size), disable=disable_progress_bar):\n batch_input_ids = input_ids[batch_i:batch_i + batch_size, :].to(device)\n batch_token_type_ids = token_type_ids[batch_i:batch_i + batch_size, :].to(device)\n batch_attention_masks = attention_masks[batch_i:batch_i + batch_size, :].to(device)\n with torch.no_grad():\n start_logits, end_logits = model(\n input_ids=batch_input_ids,\n attention_mask=batch_attention_masks,\n token_type_ids=batch_token_type_ids,\n ) # if we don't pass it start_positions and end_positions it won't return the loss, unlike during training\n\n pred_start_positions = torch.argmax(start_logits, dim=1)\n pred_end_positions = torch.argmax(end_logits, dim=1)\n\n pred_start = torch.cat((pred_start, pred_start_positions))\n pred_end = torch.cat((pred_end, pred_end_positions))\n if torch.cuda.is_available():\n logger.debug(f\"GPU memory usage: \\n{gpu_memory_usage()}\")\n\n logger.info(f\"All predictions calculated in {format_time(time() - t_i)}.\")\n if torch.cuda.is_available():\n logger.info(f\"GPU memory usage: \\n{gpu_memory_usage()}\")\n\n return pred_start, pred_end\n\n","sub_path":"Module 4. BERT and HuggingFace/bert_for_question_answering/modules_solutions/prediction_loop.py","file_name":"prediction_loop.py","file_ext":"py","file_size_in_byte":4614,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"416427761","text":"class TestK8s:\n async def test_healthz(self, client):\n \"\"\"\n k8s healthz 检测\n \"\"\"\n response = await client.get('/healthz')\n assert response.status == 200\n text = await response.text()\n assert text == 'ok'\n\n async def test_readiness(self, client):\n \"\"\"\n k8s readiness 检测\n \"\"\"\n response = await client.get('/readiness')\n assert response.status == 200\n text = await response.text()\n assert text == 'ok'\n","sub_path":"src/tests/test_k8s.py","file_name":"test_k8s.py","file_ext":"py","file_size_in_byte":510,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"101846477","text":"from django import forms\nfrom .models import Musician\nfrom blog.models import Article\n\n\nclass MusicianForm(forms.ModelForm):\n\n\tclass Meta:\n\t\tmodel = Musician\n\t\tfields = ('__all__')\n\t\texclude = ['slug','instrument_slug', 'playing_style_slug']\n\n\tdef __init__(self, *args, **kwargs):\n\t\tsuper(MusicianForm, self).__init__(*args, **kwargs)\n\n\t\tfor field in self.fields:\n\t\t\tif field == 'about_you':\n\t\t\t\tself.fields[field].widget.attrs.update({'placeholder' : 'Some information about you'})\n\t\t\tif field == 'avatar':\n\t\t\t\tself.fields[field].widget.attrs['class'] = 'form-control-static'\n\t\t\telse:\n\t\t\t\tself.fields[field].widget.attrs['class'] = 'form-control'\n\n\tdef save(self, *args, **kwargs):\n\t\tnew_musician = super(MusicianForm, self).save(commit=True)\n\t\treturn new_musician\n","sub_path":"musicians/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":766,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"29746437","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# \n# cmd.py\n# \n# This file is part of the RoboEarth Cloud Engine framework.\n# \n# This file was originally created for RoboEearth\n# http://www.roboearth.org/\n# \n# The research leading to these results has received funding from\n# the European Union Seventh Framework Programme FP7/2007-2013 under\n# grant agreement no248942 RoboEarth.\n# \n# Copyright 2012 RoboEarth\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# \\author/s: Dominique Hunziker \n# \n# \n\n\n\"\"\" Message Content Identifier of Command Messages of RCE Protocol:\n \n - Container (for removal)\n r Robot (for removal)\n n Node (for removal)\n i Interface (for removal)\n p Parameter (for removal)\n \n + Container\n R Robot\n \n N Node\n\n Z Standard Parameter\n Y Standard Parameter Array\n X FileParam\n \n V Service Interface\n K Service Provider Interface\n P Publisher Interface\n C Subscriber Interface\n \n W Service Converter\n L Service Provider Converter\n Q Publisher Converter\n D Subscriber Converter\n \n U Service Forwarder\n I Service Provider Forwarder\n O Publisher Forwarder\n B Subscriber Forwarder\n \n A Connection\n\"\"\"\n\nRM_CONTAINER = '-'\nRM_ROBOT = 'r'\nRM_NODE = 'n'\nRM_INTERFACE = 'i'\nRM_PARAMETER = 'p'\n\nCONTAINER = '+'\nROBOT = 'R'\n\nNODE = 'N'\n\nPARAM_STD = 'Z'\nPARAM_ARR = 'Y'\nPARAM_FILE = 'X'\n\nINTERFACE_SRV = 'V'\nINTERFACE_PRO = 'K'\nINTERFACE_PUB = 'P'\nINTERFACE_SUB = 'C'\n\nCONVERTER_SRV = 'W'\nCONVERTER_PRO = 'L'\nCONVERTER_PUB = 'Q'\nCONVERTER_SUB = 'D'\n\nFORWARDER_SRV = 'U'\nFORWARDER_PRO = 'I'\nFORWARDER_PUB = 'O'\nFORWARDER_SUB = 'B'\n\nCONNECTION = 'A'\n","sub_path":"framework/core/types/cmd.py","file_name":"cmd.py","file_ext":"py","file_size_in_byte":2432,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"4929625","text":"# Dependencies\nimport openweathermapy.core as ow\n\n# Create settings dictionary with information we're interested in\napi_key = \"25bc90a1196e6f153eece0bc0b0fc9eb\"\nsettings = {\"units\": \"metric\", \"appid\": api_key}\n\n# OpenWatherMapy makes it easy to parse the response\ncurrent_weather_paris = ow.get_current(\"Paris\", **settings)\nsummary = [\"name\", \"main.temp\"]\n\ndata = current_weather_paris(*summary)\nprint(\"The current weather summary for Paris is: \" + str(data))\n","sub_path":"06-Python-APIs/2/09-Ins_OpenWeatherWrapper/openweather_wrapper_parse_response.py","file_name":"openweather_wrapper_parse_response.py","file_ext":"py","file_size_in_byte":460,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"91463256","text":"class IRCMessage(object):\n def __init__(self, messageType, user, channel, messageText):\n self.messageType = messageType\n self.user = user\n self.channel = channel\n self.messageText = messageText\n self.params = messageText.split(\" \")\n \n self.replyTo = \"\"\n\n if not user and not channel:\n # This message does not have a user or a channel. It's probably a server reply\n self.replyTo = \"\"\n elif not channel:\n self.replyTo = user.nickname\n else:\n self.replyTo = channel.name\n","sub_path":"pyheufybot/message.py","file_name":"message.py","file_ext":"py","file_size_in_byte":585,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"531365807","text":"# program for linked list\r\n# SinglyLinkedList\r\n\r\n\r\nclass node: # this will create a node\r\n def __init__(self, data):\r\n self.data = data\r\n self.next = None\r\n\r\n\r\nclass SinglyLinkedList:\r\n def __init__(self):\r\n self.head = None # this will be head node\r\n self.numOfNodes = 0 # this variable shows the sizes of linked list\r\n\r\n def insert_first(self, data): # To insert node at the start\r\n new_node = node(data) # this create a node\r\n\r\n if self.head is None: # check the head is empty or not\r\n self.head = new_node\r\n self.numOfNodes += 1\r\n\r\n else:\r\n new_node.next = self.head\r\n self.head = new_node\r\n self.numOfNodes += 1\r\n\r\n def insert_end(self, data): # to create a node at the end\r\n new_node = node(data)\r\n\r\n if self.head is None:\r\n self.head = new_node\r\n self.numOfNodes += 1\r\n\r\n else:\r\n temp = self.head\r\n while temp.next is not None: # temp node now reaches to the last node\r\n temp = temp.next\r\n\r\n temp.next = new_node\r\n self.numOfNodes += 1\r\n\r\n\r\n def insert_at_pos(self, data, pos):\r\n new_node = node(data)\r\n\r\n if self.head is None:\r\n self.head = new_node\r\n\r\n else:\r\n count = self.numOfNodes\r\n if 1 <= pos <= count: # check the position is valid or not\r\n self.numOfNodes += 1\r\n if pos == 1:\r\n self.insert_first(data)\r\n\r\n elif pos == count:\r\n self.insert_end(data)\r\n\r\n else:\r\n temp = self.head\r\n i = 1\r\n\r\n while i < pos-1: # now to temp node reaches the nth position (n = pos -1)\r\n temp = temp.next\r\n i += 1\r\n new_node.next = temp.next\r\n temp.next = new_node\r\n\r\n else:\r\n print(f\"There are {count} nodes in the list.\\n \"\r\n \"Enter a valid position\\n\")\r\n\r\n def remove_first(self):\r\n\r\n if self.head is None:\r\n print(\"There are no nodes in the list.\\n\") # check the list is empty or not.\r\n\r\n elif self.head.next is None: # Only one node is present\r\n self.head = None\r\n\r\n else:\r\n temp = self.head # to delete the head node we use temp node\r\n self.head = self.head.next\r\n del temp\r\n self.numOfNodes -= 1\r\n\r\n def remove_end(self):\r\n\r\n if self.head is None:\r\n print(\"There are no nodes in the list.\\n\")\r\n\r\n elif self.head.next is None: # Only one node is present\r\n self.head = None\r\n\r\n else:\r\n temp = self.head # first we have to reach the last node\r\n prev_node = None # previous node is used to delete the next link of last node\r\n\r\n while temp.next is not None:\r\n prev_node = temp\r\n temp = temp.next\r\n\r\n prev_node.next = None\r\n del temp # delete the last node\r\n self.numOfNodes -= 1\r\n\r\n def remove_with_data(self, data):\r\n\r\n temp = self.head\r\n prev_node = None\r\n\r\n if self.head is None:\r\n return\r\n\r\n while temp is not None and temp.data != data: # we are comparing data with node data\r\n prev_node = temp\r\n temp = temp.next\r\n\r\n if temp is None: # it means we could not found the element because last node pointer is null\r\n return\r\n\r\n self.numOfNodes -= 1\r\n if prev_node is None: # it means there are only one node present at a time\r\n self.head = temp.next\r\n\r\n else:\r\n prev_node.next = temp.next\r\n\r\n def Traverse(self):\r\n\r\n if self.head is None:\r\n print(\"LIST IS EMPTY.\\n\")\r\n\r\n else:\r\n temp = self.head\r\n\r\n while temp is not None:\r\n print(f\"{temp.data} -->\", end='')\r\n temp = temp.next\r\n\r\n\r\nif __name__ == '__main__':\r\n\r\n SLL = SinglyLinkedList()\r\n\r\n while True:\r\n print(\"\\n<-- Singly Linked List -->\\n\"\r\n \"1. Insert_At_Start\\n\"\r\n \"2. Insert_At_End\\n\"\r\n \"3. Insert_At_Pos\\n\"\r\n \"4. Remove_From_Start\\n\"\r\n \"5. Remove_From_End\\n\"\r\n \"6. Remove_With_Data\\n\"\r\n \"7. Display_List\\n\"\r\n \"8. Exit\\n\")\r\n\r\n print(\"Enter a choice: \", end='')\r\n choice = int(input())\r\n\r\n if choice == 1:\r\n a = input(\"Enter a data: \")\r\n SLL.insert_first(a)\r\n print(\"\\n\")\r\n\r\n if choice == 2:\r\n a = input(\"Enter a data: \")\r\n SLL.insert_end(a)\r\n print('\\n')\r\n\r\n if choice == 3:\r\n a = input(\"Enter a data: \")\r\n b = int(input(\"Enter a position\"))\r\n SLL.insert_at_pos(a, b)\r\n\r\n if choice == 4:\r\n SLL.remove_first()\r\n\r\n if choice == 5:\r\n SLL.remove_end()\r\n\r\n if choice == 6:\r\n a = input(\"Enter Data: \")\r\n SLL.remove_with_data(a)\r\n\r\n if choice == 7:\r\n SLL.Traverse()\r\n\r\n if choice == 8:\r\n exit()\r\n\r\n\r\n\r\n\r\n","sub_path":"SINGLY_LINKED_LIST.py","file_name":"SINGLY_LINKED_LIST.py","file_ext":"py","file_size_in_byte":5426,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"30708510","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Time : 2019/10/28\n# @Author : Zhangzhicong\n# @Software: PyCharm\n# @version : 1.0\nimport requests\nimport sys\nimport os\nfrom email.mime.text import MIMEText # 专门发送正文\nfrom email.mime.multipart import MIMEMultipart # 发送多个部分\nfrom email.mime.application import MIMEApplication # 发送附件\nimport smtplib # 发送邮件\nrequests.packages.urllib3.disable_warnings()\n# pro_name = sys.argv[1]\n# image = sys.argv[2]\npro_name = 'ouyu-prod-test'\nimage = 'conf'\n# class minimal:\n# def __init__(self):\n# self.url_login = 'https://dockerepo.isccn.cn:15000/c/login'\n# self.login_data = {\n# 'principal': 'zhangzhicong',\n# 'password': 'Zzc123456'\n# }\n# self.session = requests.session()\n# self.value = self.session.post(self.url_login, data=self.login_data, verify=False)\n# def get_minimal_conf_image_version(self):\n# url = 'https://dockerepo.isccn.cn:15000/api/repositories/minimal/conf/tags/'\n# value= self.session.get(url).json()\n# s = [i[\"name\"] for i in value]\n# res = sorted(s, reverse = True)[0]\n# res = res.replace(res[-1], str(int(res[-1]) + 1))\n# return res\n# def get_minimal_cdn_image_version(self):\n# url = 'https://dockerepo.isccn.cn:15000/api/repositories/minimal/cdn/tags/'\n# value= self.session.get(url).json()\n# s = [i[\"name\"] for i in value]\n# res = sorted(s, reverse = True)[0]\n# res = res.replace(res[-1], str(int(res[-1]) + 1))\n# return res\n# def get_minimal_idrc_image_version(self):\n# url = 'https://dockerepo.isccn.cn:15000/api/repositories/minimal/idrc/tags/'\n# value= self.session.get(url).json()\n# s = [i[\"name\"] for i in value]\n# res = sorted(s, reverse = True)[0]\n# res = res.replace(res[-1], str(int(res[-1]) + 1))\n# return res\n# def get_minimal_opensips_image_version(self):\n# url = 'https://dockerepo.isccn.cn:15000/api/repositories/minimal/opensips/tags/'\n# value= self.session.get(url).json()\n# s = [i[\"name\"] for i in value]\n# res = sorted(s, reverse = True)[0]\n# res = res.replace(res[-1], str(int(res[-1]) + 1))\n# return res\n# def get_minimal_pushweb_image_version(self):\n# url = 'https://dockerepo.isccn.cn:15000/api/repositories/minimal/pushweb/tags/'\n# value= self.session.get(url).json()\n# s = [i[\"name\"] for i in value]\n# res = sorted(s, reverse = True)[0]\n# res = res.replace(res[-1], str(int(res[-1]) + 1))\n# return res\ndef link_version(url):\n url_login = 'https://dockerepo.isccn.cn:15000/c/login'\n login_data = {\n 'principal': 'zhangzhicong',\n 'password': 'Zzc123456'\n }\n session = requests.session()\n value = session.post(url_login, data=login_data, verify=False)\n value = session.get(url).json()\n s = [i[\"name\"] for i in value]\n res = sorted(s, reverse=True)[0]\n if len(res) <= 5:\n res = res.replace(res[-1], str(int(res[-1]) + 1))\n else:\n res = res.replace(res[-2:], str(int(res[-2:]) + 1))\n return res\ndef send_mail(email_text):\n send_user = 'op-info@cd-hst.com' # 发件人\n password = '123456' # 授权码/密码\n receive_users = 'zhangzhicong@cd-hst.com' # 收件人,可为list\n # receive_users = 'tao.shen@isccn.cn'\n subject = email_text # 邮件主题\n email_text = email_text # 邮件正文\n server_address = 'mail.cd-hst.com' # 服务器地址\n mail_type = '1' # 邮件类型\n # 构造一个邮件体:正文 附件\n msg = MIMEMultipart()\n msg['Subject'] = subject # 主题\n msg['From'] = send_user # 发件人\n msg['To'] = receive_users # 收件人\n # 构建正文\n part_text = MIMEText(email_text, 'plain', 'utf-8')\n msg.attach(part_text) # 把正文加到邮件体里面去\n # 发送邮件 SMTP\n smtp = smtplib.SMTP(server_address, 25) # 连接服务器,SMTP_SSL是安全传输\n smtp.ehlo() # 向Gamil发送SMTP 'ehlo' 命令\n smtp.starttls()\n smtp.login(send_user, password)\n smtp.sendmail(send_user, receive_users, msg.as_string()) # 发送邮件\n print('邮件发送成功!')\ndef build_push_image(url):\n version = link_version(url)\n print(version)\n os.environ['version'] = version\n os.environ['image'] = image\n try:\n os.system('sh /home/prod_build.sh $image $version')\n send_mail(\"构建并推送成功\")\n update = os.system(\"docker rmi -f $(docker images | grep $image | awk '{print $3}')\")\n except BaseException:\n os.system('sh /home/prod_build.sh $image $version')\n v = os.popen(\"docker images |awk '{print $2}'| awk 'NR==2'\").read()\n if v in version:\n send_mail(\"推送镜像失败\")\n else:\n send_mail(\"构建镜像失败\")\n# class ouyuprod:\n# def __init__(self):\n# self.url_login = 'https://dockerepo.isccn.cn:15000/c/login'\n# self.login_data = {\n# 'principal': 'zhangzhicong',\n# 'password': 'Zzc123456'\n# }\n# self.session = requests.session()\n# self.value = self.session.post(self.url_login, data=self.login_data, verify=False)\n# def get_ouyupord_conf_image_version(self):\n# url = 'https://dockerepo.isccn.cn:15000/api/repositories/ouyu-prod-test/conf/tags/'\n# value= self.session.get(url).json()\n# s = [i[\"name\"] for i in value]\n# res = sorted(s, reverse = True)[0]\n# if len(res)<=5:\n# res = res.replace(res[-1], str(int(res[-1]) + 1))\n# else:\n# res = res.replace(res[-2:], str(int(res[-2:]) + 1))\n# return res\n# def get_ouyupord_idrc_image_version(self):\n# url = 'https://dockerepo.isccn.cn:15000/api/repositories/ouyu-prod-test/idrc/tags/'\n# value= self.session.get(url).json()\n# s = [i[\"name\"] for i in value]\n# res = sorted(s, reverse = True)[0]\n# res = res.replace(res[-1], str(int(res[-1]) + 1))\n# return res\n# def get_ouyupord_cdn_image_version(self):\n# url = 'https://dockerepo.isccn.cn:15000/api/repositories/ouyu-prod-test/cdn/tags/'\n# value= self.session.get(url).json()\n# s = [i[\"name\"] for i in value]\n# res = sorted(s, reverse = True)[0]\n# res = res.replace(res[-1], str(int(res[-1]) + 1))\n# return res\n\n\n\nif __name__ == '__main__':\n url = 'https://dockerepo.isccn.cn:15000/api/repositories/ouyu-prod-test/conf/tags/'\n if pro_name in \"ouyu-prod-test\":\n if image in \"cdn\":\n print(build_push_image(url))\n elif image in \"conf\":\n update = os.system('sh /home/update_conf.sh')\n build_push_image(url)\n # # mini = minimal()\n # # prod = ouyuprod()\n # version = prod.get_ouyupord_conf_image_version()\n # print(version)\n # if pro_name in \"ouyu-prod-test\":\n # if image in \"cdn\":\n # print(prod.get_ouyupord_cdn_image_version())\n # elif image in \"conf\":\n # update = os.system('sh /home/update_conf.sh')\n # # build_push_image()\n #\n #\n # elif image in \"idrc\":\n # print(prod.get_ouyupord_idrc_image_version())\n # elif pro_name in \"minimal\":\n # if image in \"conf\":\n # update = os.system('sh /home/update_mini_conf.sh')\n # elif image in \"cdn\":\n # print(mini.get_minimal_cdn_image_version())\n # elif image in \"opensips\":\n # print(mini.get_minimal_opensips_image_version())\n # elif image in \"idrc\":\n # print(mini.get_minimal_idrc_image_version())\n # elif image in \"pushweb\":\n # print(mini.get_minimal_pushweb_image_version())","sub_path":"test/image_tags1.0.py","file_name":"image_tags1.0.py","file_ext":"py","file_size_in_byte":7812,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"628772448","text":"import os\nimport logging\n\nimport dash\nfrom flask import Flask\nfrom flask.helpers import get_root_path\nfrom flask_login import login_required\nimport flask_migrate\nfrom alembic import command\nfrom alembic.runtime.migration import MigrationContext\nfrom sqlalchemy_utils import database_exists\n\nfrom qualipy.web.config import BaseConfig, read_project_config\nfrom qualipy.web.app.models import User\nfrom qualipy.web._config import _Config\n\n\nlogging.basicConfig(level=\"INFO\")\nlogger = logging.getLogger(__name__)\n\n\ndef create_app():\n server = Flask(__name__)\n\n set_config(server, _Config.config_dir)\n # set_logging(server)\n\n register_dashapps(server)\n register_extensions(server)\n register_blueprints(server)\n register_cache(server)\n\n return server\n\n\ndef set_config(server, config_dir):\n server.config.from_object(BaseConfig(config_dir))\n server.config.update(**read_project_config(config_dir))\n server.config[\"CONFIG_DIR\"] = config_dir\n\n\ndef register_dashapps(app):\n from qualipy.web.app.metric_tracker.layout import generate_layout\n from qualipy.web.app.metric_tracker.callbacks import register_callbacks\n\n meta_viewport = {\n \"name\": \"viewport\",\n \"content\": \"width=device-width, initial-scale=1, shrink-to-fit=no\",\n }\n\n metric_tracker_app = dash.Dash(\n __name__,\n server=app,\n url_base_pathname=\"/dashboard/\",\n assets_folder=get_root_path(__name__) + \"/dashboard/assets/\",\n meta_tags=[meta_viewport],\n )\n\n with app.app_context():\n\n # metric tracker\n metric_tracker_layout = generate_layout([\"None\"], [\"None\"], [\"None\"], 1000000)\n metric_tracker_app.title = \"Metric Tracker\"\n metric_tracker_app.layout = metric_tracker_layout\n metric_tracker_app.config[\"suppress_callback_exceptions\"] = True\n register_callbacks(metric_tracker_app)\n\n _protect_dashviews(metric_tracker_app)\n\n\ndef _protect_dashviews(dashapp):\n for view_func in dashapp.server.view_functions:\n if view_func.startswith(dashapp.config.url_base_pathname):\n dashapp.server.view_functions[view_func] = login_required(\n dashapp.server.view_functions[view_func]\n )\n\n\ndef register_extensions(server):\n from qualipy.web.app.extensions import db\n from qualipy.web.app.extensions import login\n from qualipy.web.app.extensions import migrate\n\n # db\n db.init_app(server)\n migrate.init_app(server, db)\n\n register_db_migrations(server, migrate, db)\n\n login.init_app(server)\n login.login_view = \"main.login\"\n\n\ndef register_blueprints(server):\n from qualipy.web.app.webapp import main\n\n server.register_blueprint(main)\n\n\ndef register_cache(server):\n from qualipy.web.app.caching import cache\n\n cache.config.update(**{k: v for k, v in server.config.items() if \"CACHE\" in k})\n cache.init_app(server)\n\n if _Config.train_anomaly:\n cache.clear()\n\n\ndef register_db_migrations(server, migrate, db):\n with server.app_context():\n conn = db.engine.connect()\n context = MigrationContext.configure(conn)\n db_revision = context.get_current_revision()\n\n if server.config[\"DB_AUTO_CREATE\"] and not database_exists(\n server.config[\"SQLALCHEMY_DATABASE_URI\"]\n ):\n with server.app_context():\n print(\"creating db\")\n db.create_all()\n flask_migrate.init(server.config[\"MIGRATIONS_DIR\"])\n command.stamp(migrate.get_config(server.config[\"MIGRATIONS_DIR\"]), \"head\")\n add_admin(db)\n\n if server.config[\"DB_AUTO_UPGRADE\"]:\n with server.app_context():\n command.upgrade(migrate.get_config(server.config[\"MIGRATIONS_DIR\"]), \"head\")\n\n\ndef add_admin(db):\n admin = User(username=\"admin\")\n admin.set_password(\"admin\")\n db.session.add(admin)\n db.session.commit()\n\n\ndef set_logging(server):\n root = logging.getLogger()\n root.setLevel(\"DEBUG\")\n","sub_path":"qualipy/web/app/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":3934,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"143142533","text":"import time\nimport os\nfrom selenium import webdriver\nimport csv\n\n\n\ndef get_product(keyword):\n '''搜索商品'''\n driver.find_element_by_css_selector('#key').send_keys(keyword) #找到输入框,输入关键字\n driver.find_element_by_css_selector('.button').click()\n\n\n driver.implicitly_wait(10) # 等待隐式等待\n driver.maximize_window() #最大化浏览器\n\n\n\n# 数据懒加载(浏览器向下拉动,下面的数据才会加载)\ndef drop_down(): #模拟向下拉动\n for x in range(1,11,2):\n j = x/10\n js = 'document.documentElement.scrollTop = document.documentElement.scrollHeight * %f' % j\n driver.execute_script(js)\n\n\n# 数据分析采集并且保存\ndef parse_data():\n lis = driver.find_elements_by_css_selector('.gl-item')\n\n for y in lis:\n try:\n name = y.find_element_by_css_selector('div.p-name a em').text #商品名称\n price = y.find_element_by_css_selector('div.p-price strong i').text #商品价格\n deal = y.find_element_by_css_selector('div.p-commit strong a').text #商品评论数量\n title = y.find_element_by_css_selector('span.J_im_icon a').text #商品的店铺\n # print(name,price,deal,title)\n with open('shuju/京东电脑',mode='a',encoding='utf-8',newline='') as f:\n csv_write = csv.writer(f)\n csv_write.writerow([name,price,deal,title])\n except Exception as e:\n print(e)\n\n\ndef get_next():\n driver.find_element_by_css_selector('#J_bottomPage > span.p-num > a.pn-next > em').click()\n\nword = input(\"请输入爬取商品名称 \")\n# word = '笔记本'\ndriver = webdriver.Chrome(executable_path=\"D:\\Program Files (x86)\\chromedriver_win32\\chromedriver.exe\")\ndriver.get(\"https://www.jd.com\")\n#搜索商品\nget_product(word)\nfor page in range(1,30):\n\n # 调用页面滚动\n drop_down()\n time.sleep(1)\n #调用解析函数\n parse_data()\n get_next()\n# # 调用页面滚动\n# drop_down()\n# #调用解析函数\n# parse_data()\n# get_next()\n\n# 退出\ndriver.quit()","sub_path":"jdspd.py","file_name":"jdspd.py","file_ext":"py","file_size_in_byte":2089,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"102450890","text":"#!/usr/bin/env python\n#\n# Copyright EAVISE\n# Example: Transform annotations for VOCdevkit to the brambox pickle format\n#\n\nimport xml.etree.ElementTree as ET\nimport brambox.boxes as bbb\n\nROOT = 'data' # Root folder where the VOCdevkit is located\n\nTRAINSET = [\n ('2018', 'train'),\n]\n\nVALIDSET = [\n ('2018', 'val'),\n]\n\nTESTSET = [\n ('2018', 'test'),\n]\n\n\ndef identify(xml_file):\n root = ET.parse(xml_file).getroot()\n folder = root.find('folder').text\n filename = root.find('filename').text\n return '{folder}/JPEGImages/{filename}'.format(folder=folder, filename=filename)\n\n\ndef process(name, verbose=True):\n config_dict = {\n 'train': ('training', TRAINSET),\n 'valid': ('validation', VALIDSET),\n 'test': ('testing', TESTSET),\n }\n\n name = name.lower()\n assert name in config_dict\n description, DATASET = config_dict[name]\n\n if len(DATASET) == 0:\n return\n\n print('Getting {description} annotation filenames'.format(description=description))\n dataset = []\n for (year, img_set) in DATASET:\n filename = '{ROOT}/VOCdevkit/VOC{year}/ImageSets/Main/{img_set}.txt'.format(ROOT=ROOT, year=year, img_set=img_set)\n with open(filename, 'r') as f:\n ids = f.read().strip().split()\n dataset += [\n '{ROOT}/VOCdevkit/VOC{year}/Annotations/{xml_id}.xml'.format(ROOT=ROOT, year=year, xml_id=xml_id)\n for xml_id in ids\n ]\n\n if verbose:\n print('\\t{len} xml files'.format(\n len=len(dataset),\n ))\n\n print('Parsing {description} annotation files'.format(description=description))\n dataset_annos = bbb.parse('anno_pascalvoc', dataset, identify)\n\n print('Generating {description} annotation file'.format(description=description))\n bbb.generate('anno_pickle', dataset_annos, '{ROOT}/{name}.pkl'.format(ROOT=ROOT, name=name))\n\n print()\n\n\nif __name__ == '__main__':\n process('train')\n process('valid')\n process('test')\n","sub_path":"examples/seaturtle/labels.py","file_name":"labels.py","file_ext":"py","file_size_in_byte":1989,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"286445092","text":"# twitter/models.py\n# Brought to you by We Vote. Be good.\n# -*- coding: UTF-8 -*-\n\n# See also WeVoteServer/import_export_twitter/models.py for the code that interfaces with twitter (or other) servers\nfrom config.base import get_environment_variable\nfrom django.db import models\nfrom exception.models import handle_record_found_more_than_one_exception\nfrom import_export_twitter.functions import retrieve_twitter_user_info\nimport tweepy\nfrom wevote_functions.functions import convert_to_int, generate_random_string, positive_value_exists\nimport wevote_functions.admin\n\nTWITTER_CONSUMER_KEY = get_environment_variable(\"TWITTER_CONSUMER_KEY\")\nTWITTER_CONSUMER_SECRET = get_environment_variable(\"TWITTER_CONSUMER_SECRET\")\nTWITTER_FRIENDS_IDS_MAX_LIMIT = 5000\nTWITTER_API_NAME_FRIENDS_ID = \"friends_ids\"\n\nlogger = wevote_functions.admin.get_logger(__name__)\n\n\nclass TwitterLinkToOrganization(models.Model):\n \"\"\"\n This is the link between a Twitter account and an organization\n \"\"\"\n organization_we_vote_id = models.CharField(verbose_name=\"we vote id for the org owner\", max_length=255, unique=True)\n twitter_id = models.BigIntegerField(verbose_name=\"twitter big integer id\", null=True, unique=True)\n date_last_changed = models.DateTimeField(verbose_name='date last changed', null=False, auto_now=True)\n\n def fetch_twitter_id_locally_or_remotely(self):\n twitter_id = 0\n twitter_user_manager = TwitterUserManager()\n twitter_results = twitter_user_manager.retrieve_twitter_user_locally_or_remotely(self.twitter_id)\n\n if twitter_results['twitter_user_found']:\n twitter_user = twitter_results['twitter_user']\n twitter_id = twitter_user.twitter_id\n\n return twitter_id\n\n def fetch_twitter_handle_locally_or_remotely(self):\n twitter_handle = \"\"\n twitter_user_manager = TwitterUserManager()\n twitter_results = twitter_user_manager.retrieve_twitter_user_locally_or_remotely(self.twitter_id)\n\n if twitter_results['twitter_user_found']:\n twitter_user = twitter_results['twitter_user']\n twitter_handle = twitter_user.twitter_handle\n\n # Strip out the twitter handles \"False\" or \"None\"\n if twitter_handle:\n twitter_handle_lower = twitter_handle.lower()\n if twitter_handle_lower == 'false' or twitter_handle_lower == 'none':\n twitter_handle = ''\n\n return twitter_handle\n\n\nclass TwitterLinkToVoter(models.Model):\n \"\"\"\n This is the link between a Twitter account and a We Vote voter account\n \"\"\"\n voter_we_vote_id = models.CharField(verbose_name=\"we vote id for the voter owner\", max_length=255, unique=True)\n twitter_id = models.BigIntegerField(verbose_name=\"twitter big integer id\", null=False, unique=True)\n secret_key = models.CharField(\n verbose_name=\"secret key to verify ownership twitter account\", max_length=255, null=False, unique=True)\n date_last_changed = models.DateTimeField(verbose_name='date last changed', null=False, auto_now=True)\n\n def fetch_twitter_id_locally_or_remotely(self):\n twitter_id = 0\n twitter_user_manager = TwitterUserManager()\n twitter_results = twitter_user_manager.retrieve_twitter_user_locally_or_remotely(self.twitter_id)\n\n if twitter_results['twitter_user_found']:\n twitter_user = twitter_results['twitter_user']\n twitter_id = twitter_user.twitter_id\n\n return twitter_id\n\n def fetch_twitter_handle_locally_or_remotely(self):\n twitter_handle = \"\"\n twitter_user_manager = TwitterUserManager()\n twitter_results = twitter_user_manager.retrieve_twitter_user_locally_or_remotely(self.twitter_id)\n\n if twitter_results['twitter_user_found']:\n twitter_user = twitter_results['twitter_user']\n twitter_handle = twitter_user.twitter_handle\n\n # Strip out the twitter handles \"False\" or \"None\"\n if twitter_handle:\n twitter_handle_lower = twitter_handle.lower()\n if twitter_handle_lower == 'false' or twitter_handle_lower == 'none':\n twitter_handle = ''\n\n return twitter_handle\n\n\nclass TwitterUser(models.Model):\n \"\"\"\n We cache the Twitter info for one handle here.\n \"\"\"\n twitter_id = models.BigIntegerField(verbose_name=\"twitter big integer id\", null=True, blank=True)\n twitter_handle = models.CharField(verbose_name='twitter screen name / handle',\n max_length=255, null=False, unique=True)\n twitter_name = models.CharField(verbose_name=\"display name from twitter\", max_length=255, null=True, blank=True)\n twitter_url = models.URLField(blank=True, null=True, verbose_name='url of user\\'s website')\n twitter_profile_image_url_https = models.URLField(verbose_name='url of logo from twitter', blank=True, null=True)\n twitter_location = models.CharField(verbose_name=\"location from twitter\", max_length=255, null=True, blank=True)\n twitter_followers_count = models.IntegerField(verbose_name=\"number of twitter followers\",\n null=False, blank=True, default=0)\n twitter_profile_background_image_url_https = models.URLField(verbose_name='tile-able background from twitter',\n blank=True, null=True)\n twitter_profile_banner_url_https = models.URLField(verbose_name='profile banner image from twitter',\n blank=True, null=True)\n we_vote_hosted_profile_image_url_large = models.URLField(verbose_name='we vote hosted large image url',\n blank=True, null=True)\n we_vote_hosted_profile_image_url_medium = models.URLField(verbose_name='we vote hosted medium image url',\n blank=True, null=True)\n we_vote_hosted_profile_image_url_tiny = models.URLField(verbose_name='we vote hosted tiny image url',\n blank=True, null=True)\n twitter_description = models.CharField(verbose_name=\"Text description of this organization from twitter.\",\n max_length=255, null=True, blank=True)\n\n\nclass TwitterUserManager(models.Model):\n\n def __unicode__(self):\n return \"TwitterUserManager\"\n\n def create_twitter_link_to_organization(self, twitter_id, organization_we_vote_id):\n if not positive_value_exists(twitter_id) or not \\\n positive_value_exists(organization_we_vote_id):\n twitter_link_to_organization = TwitterLinkToOrganization()\n results = {\n 'success': False,\n 'status': 'CREATE_TWITTER_LINK_TO_ORGANIZATION_FAILED-MISSING_REQUIRED_VARIABLES',\n 'twitter_link_to_organization_saved': False,\n 'twitter_link_to_organization': twitter_link_to_organization,\n }\n return results\n\n # Any attempts to save a twitter_link using either twitter_id or voter_we_vote_id that already\n # exist in the table will fail, since those fields are required to be unique.\n try:\n twitter_link_to_organization = TwitterLinkToOrganization.objects.create(\n twitter_id=twitter_id,\n organization_we_vote_id=organization_we_vote_id,\n )\n twitter_link_to_organization_saved = True\n success = True\n status = \"TWITTER_LINK_TO_ORGANIZATION_CREATED\"\n except Exception as e:\n twitter_link_to_organization_saved = False\n twitter_link_to_organization = TwitterLinkToOrganization()\n success = False\n status = \"TWITTER_LINK_TO_ORGANIZATION_NOT_CREATED\"\n\n results = {\n 'success': success,\n 'status': status,\n 'twitter_link_to_organization_saved': twitter_link_to_organization_saved,\n 'twitter_link_to_organization': twitter_link_to_organization,\n }\n return results\n\n def create_twitter_link_to_voter(self, twitter_id, voter_we_vote_id):\n\n # Any attempts to save a twitter_link using either twitter_id or voter_we_vote_id that already\n # exist in the table will fail, since those fields are required to be unique.\n twitter_secret_key = generate_random_string(12)\n\n try:\n twitter_link_to_voter = TwitterLinkToVoter.objects.create(\n twitter_id=twitter_id,\n voter_we_vote_id=voter_we_vote_id,\n secret_key=twitter_secret_key,\n )\n twitter_link_to_voter_saved = True\n success = True\n status = \"TWITTER_LINK_TO_VOTER_CREATED\"\n\n # TODO DALE Remove voter.twitter_id value here?\n except Exception as e:\n twitter_link_to_voter_saved = False\n twitter_link_to_voter = TwitterLinkToVoter()\n success = False\n status = \"TWITTER_LINK_TO_VOTER_NOT_CREATED\"\n\n results = {\n 'success': success,\n 'status': status,\n 'twitter_link_to_voter_saved': twitter_link_to_voter_saved,\n 'twitter_link_to_voter': twitter_link_to_voter,\n }\n return results\n\n def retrieve_twitter_link_to_organization_from_twitter_user_id(self, twitter_user_id):\n return self.retrieve_twitter_link_to_organization(twitter_user_id)\n\n def retrieve_twitter_link_to_organization_from_twitter_handle(self, twitter_handle):\n twitter_user_id = 0\n results = self.retrieve_twitter_user_locally_or_remotely(twitter_user_id, twitter_handle)\n if results['twitter_user_found']:\n twitter_user = results['twitter_user']\n twitter_user_id = twitter_user.twitter_id\n\n return self.retrieve_twitter_link_to_organization(twitter_user_id)\n\n def fetch_twitter_handle_from_organization_we_vote_id(self, organization_we_vote_id):\n organization_twitter_handle = ''\n twitter_results = self.retrieve_twitter_link_to_organization_from_organization_we_vote_id(\n organization_we_vote_id)\n if twitter_results['twitter_link_to_organization_found']:\n twitter_link_to_organization = twitter_results['twitter_link_to_organization']\n organization_twitter_handle = twitter_link_to_organization.fetch_twitter_handle_locally_or_remotely()\n return organization_twitter_handle\n\n def fetch_twitter_id_from_organization_we_vote_id(self, organization_we_vote_id):\n organization_twitter_id = 0\n twitter_results = self.retrieve_twitter_link_to_organization_from_organization_we_vote_id(\n organization_we_vote_id)\n if twitter_results['twitter_link_to_organization_found']:\n twitter_link_to_organization = twitter_results['twitter_link_to_organization']\n organization_twitter_id = twitter_link_to_organization.fetch_twitter_id_locally_or_remotely()\n return organization_twitter_id\n\n def fetch_twitter_handle_from_voter_we_vote_id(self, voter_we_vote_id):\n voter_twitter_handle = ''\n twitter_results = self.retrieve_twitter_link_to_voter_from_voter_we_vote_id(\n voter_we_vote_id)\n if twitter_results['twitter_link_to_voter_found']:\n twitter_link_to_voter = twitter_results['twitter_link_to_voter']\n voter_twitter_handle = twitter_link_to_voter.fetch_twitter_handle_locally_or_remotely()\n return voter_twitter_handle\n\n def fetch_twitter_id_from_voter_we_vote_id(self, voter_we_vote_id):\n voter_twitter_id = 0\n twitter_results = self.retrieve_twitter_link_to_voter_from_voter_we_vote_id(\n voter_we_vote_id)\n if twitter_results['twitter_link_to_voter_found']:\n twitter_link_to_voter = twitter_results['twitter_link_to_voter']\n voter_twitter_id = twitter_link_to_voter.fetch_twitter_id_locally_or_remotely()\n return voter_twitter_id\n\n def retrieve_twitter_link_to_organization_from_organization_we_vote_id(self, organization_we_vote_id):\n twitter_user_id = 0\n return self.retrieve_twitter_link_to_organization(twitter_user_id, organization_we_vote_id)\n\n def retrieve_twitter_link_to_organization(self, twitter_id=0, organization_we_vote_id=''):\n \"\"\"\n\n :param twitter_id:\n :param organization_we_vote_id:\n :return:\n \"\"\"\n twitter_link_to_organization = TwitterLinkToOrganization()\n twitter_link_to_organization_id = 0\n\n try:\n if positive_value_exists(twitter_id):\n twitter_link_to_organization = TwitterLinkToOrganization.objects.get(\n twitter_id=twitter_id,\n )\n twitter_link_to_organization_id = twitter_link_to_organization.id\n twitter_link_to_organization_found = True\n success = True\n status = \"RETRIEVE_TWITTER_LINK_TO_ORGANIZATION_FOUND_BY_TWITTER_USER_ID\"\n elif positive_value_exists(organization_we_vote_id):\n twitter_link_to_organization = TwitterLinkToOrganization.objects.get(\n organization_we_vote_id__iexact=organization_we_vote_id,\n )\n twitter_link_to_organization_id = twitter_link_to_organization.id\n twitter_link_to_organization_found = True\n success = True\n status = \"RETRIEVE_TWITTER_LINK_TO_ORGANIZATION_FOUND_BY_ORGANIZATION_WE_VOTE_ID\"\n else:\n twitter_link_to_organization_found = False\n success = False\n status = \"RETRIEVE_TWITTER_LINK_TO_ORGANIZATION_VARIABLES_MISSING\"\n except TwitterLinkToVoter.DoesNotExist:\n twitter_link_to_organization_found = False\n success = True\n status = \"RETRIEVE_TWITTER_LINK_TO_ORGANIZATION_NOT_FOUND\"\n except Exception as e:\n twitter_link_to_organization_found = False\n success = False\n status = 'FAILED retrieve_twitter_link_to_organization'\n\n results = {\n 'success': success,\n 'status': status,\n 'twitter_link_to_organization_found': twitter_link_to_organization_found,\n 'twitter_link_to_organization_id': twitter_link_to_organization_id,\n 'twitter_link_to_organization': twitter_link_to_organization,\n }\n return results\n\n def retrieve_twitter_link_to_voter_from_twitter_user_id(self, twitter_user_id):\n return self.retrieve_twitter_link_to_voter(twitter_user_id)\n\n def retrieve_twitter_link_to_voter_from_twitter_handle(self, twitter_handle):\n twitter_user_id = 0\n twitter_user_results = self.retrieve_twitter_user_locally_or_remotely(twitter_user_id, twitter_handle)\n if twitter_user_results['twitter_user_found']:\n twitter_user = twitter_user_results['twitter_user']\n if positive_value_exists(twitter_user.twitter_id):\n return self.retrieve_twitter_link_to_voter(twitter_user.twitter_id)\n\n twitter_link_to_voter = TwitterLinkToVoter()\n results = {\n 'success': False,\n 'status': \"COULD_NOT_FIND_TWITTER_ID_FROM_TWITTER_HANDLE\",\n 'twitter_link_to_voter_found': False,\n 'twitter_link_to_voter_id': 0,\n 'twitter_link_to_voter': twitter_link_to_voter,\n }\n return results\n\n def retrieve_twitter_link_to_voter_from_voter_we_vote_id(self, voter_we_vote_id):\n twitter_id = 0\n twitter_secret_key = \"\"\n return self.retrieve_twitter_link_to_voter(twitter_id, voter_we_vote_id, twitter_secret_key)\n\n def retrieve_twitter_link_to_voter_from_twitter_secret_key(self, twitter_secret_key):\n twitter_id = 0\n voter_we_vote_id = \"\"\n return self.retrieve_twitter_link_to_voter(twitter_id, voter_we_vote_id, twitter_secret_key)\n\n def retrieve_twitter_link_to_voter(self, twitter_id=0, voter_we_vote_id='', twitter_secret_key=''):\n \"\"\"\n\n :param twitter_id:\n :param voter_we_vote_id:\n :param twitter_secret_key:\n :return:\n \"\"\"\n twitter_link_to_voter = TwitterLinkToVoter()\n twitter_link_to_voter_id = 0\n\n try:\n if positive_value_exists(twitter_id):\n twitter_link_to_voter = TwitterLinkToVoter.objects.get(\n twitter_id=twitter_id,\n )\n twitter_link_to_voter_id = twitter_link_to_voter.id\n twitter_link_to_voter_found = True\n success = True\n status = \"RETRIEVE_TWITTER_LINK_TO_VOTER_FOUND_BY_TWITTER_USER_ID\"\n elif positive_value_exists(voter_we_vote_id):\n twitter_link_to_voter = TwitterLinkToVoter.objects.get(\n voter_we_vote_id__iexact=voter_we_vote_id,\n )\n twitter_link_to_voter_id = twitter_link_to_voter.id\n twitter_link_to_voter_found = True\n success = True\n status = \"RETRIEVE_TWITTER_LINK_TO_VOTER_FOUND_BY_VOTER_WE_VOTE_ID\"\n elif positive_value_exists(twitter_secret_key):\n twitter_link_to_voter = TwitterLinkToVoter.objects.get(\n secret_key=twitter_secret_key,\n )\n twitter_link_to_voter_id = twitter_link_to_voter.id\n twitter_link_to_voter_found = True\n success = True\n status = \"RETRIEVE_TWITTER_LINK_TO_VOTER_FOUND_BY_TWITTER_SECRET_KEY\"\n else:\n twitter_link_to_voter_found = False\n success = False\n status = \"RETRIEVE_TWITTER_LINK_TO_VOTER_VARIABLES_MISSING\"\n except TwitterLinkToVoter.DoesNotExist:\n twitter_link_to_voter_found = False\n success = True\n status = \"RETRIEVE_TWITTER_LINK_TO_VOTER_NOT_FOUND\"\n except Exception as e:\n twitter_link_to_voter_found = False\n success = False\n status = 'FAILED retrieve_twitter_link_to_voter'\n\n results = {\n 'success': success,\n 'status': status,\n 'twitter_link_to_voter_found': twitter_link_to_voter_found,\n 'twitter_link_to_voter_id': twitter_link_to_voter_id,\n 'twitter_link_to_voter': twitter_link_to_voter,\n }\n return results\n\n def retrieve_twitter_user_locally_or_remotely(self, twitter_user_id, twitter_handle=''):\n \"\"\"\n We use this routine to quickly store and retrieve twitter user information, whether it is already in the\n database, or if we have to reach out to Twitter to get it.\n :param twitter_user_id:\n :param twitter_handle:\n :return:\n \"\"\"\n twitter_user_found = False\n twitter_user = TwitterUser()\n success = False\n status = \"TWITTER_USER_NOT_FOUND\"\n\n # Strip out the twitter handles \"False\" or \"None\"\n if twitter_handle:\n twitter_handle_lower = twitter_handle.lower()\n if twitter_handle_lower == 'false' or twitter_handle_lower == 'none':\n twitter_handle = ''\n\n # Is this twitter_handle already stored locally? If so, return that\n twitter_results = self.retrieve_twitter_user(twitter_user_id, twitter_handle)\n if twitter_results['twitter_user_found']:\n return twitter_results\n\n # If here, we want to reach out to Twitter to get info for this twitter_handle\n twitter_results = retrieve_twitter_user_info(twitter_user_id, twitter_handle)\n if twitter_results['twitter_handle_found']:\n twitter_save_results = self.update_or_create_twitter_user(twitter_results['twitter_json'])\n if twitter_save_results['twitter_user_found']:\n # If saved, pull the fresh results from the database and return\n twitter_second_results = self.retrieve_twitter_user(twitter_user_id, twitter_handle)\n if twitter_second_results['twitter_user_found']:\n return twitter_second_results\n\n results = {\n 'success': success,\n 'status': status,\n 'twitter_user_found': twitter_user_found,\n 'twitter_user': twitter_user,\n }\n return results\n\n def retrieve_twitter_user(self, twitter_user_id, twitter_handle=''):\n twitter_user_on_stage = TwitterUser()\n twitter_user_found = False\n success = False\n\n # Strip out the twitter handles \"False\" or \"None\"\n if twitter_handle:\n twitter_handle_lower = twitter_handle.lower()\n if twitter_handle_lower == 'false' or twitter_handle_lower == 'none':\n twitter_handle = ''\n\n try:\n if positive_value_exists(twitter_user_id):\n status = \"RETRIEVE_TWITTER_USER_FOUND_WITH_TWITTER_USER_ID\"\n twitter_user_on_stage = TwitterUser.objects.get(twitter_id=twitter_user_id)\n twitter_user_found = True\n success = True\n elif positive_value_exists(twitter_handle):\n status = \"RETRIEVE_TWITTER_USER_FOUND_WITH_HANDLE\"\n twitter_user_on_stage = TwitterUser.objects.get(twitter_handle__iexact=twitter_handle)\n twitter_user_found = True\n success = True\n else:\n status = \"RETRIEVE_TWITTER_USER_INSUFFICIENT_VARIABLES\"\n except TwitterUser.MultipleObjectsReturned as e:\n success = False\n status = \"RETRIEVE_TWITTER_USER_MULTIPLE_FOUND\"\n handle_record_found_more_than_one_exception(e, logger=logger, exception_message_optional=status)\n except TwitterUser.DoesNotExist:\n success = True\n status = \"RETRIEVE_TWITTER_USER_NONE_FOUND\"\n\n results = {\n 'success': success,\n 'status': status,\n 'twitter_user_found': twitter_user_found,\n 'twitter_user': twitter_user_on_stage,\n }\n return results\n\n def retrieve_twitter_ids_i_follow_from_twitter(self, twitter_id_of_me, twitter_access_token, twitter_access_secret):\n \"\"\"\n We use this routine to retrieve twitter ids who i follow and updating the next cursor state in\n TwitterCursorState table\n :param twitter_id_of_me:\n :param twitter_access_token:\n :param twitter_access_secret:\n :return: twitter_ids_i_follow\n \"\"\"\n auth = tweepy.OAuthHandler(TWITTER_CONSUMER_KEY, TWITTER_CONSUMER_SECRET)\n auth.set_access_token(twitter_access_token, twitter_access_secret)\n api = tweepy.API(auth, wait_on_rate_limit=True, wait_on_rate_limit_notify=True, compression=True)\n\n twitter_next_cursor_state_results = self.retrieve_twitter_next_cursor_state(twitter_id_of_me)\n status = twitter_next_cursor_state_results['status']\n twitter_next_cursor = twitter_next_cursor_state_results['twitter_next_cursor']\n if TWITTER_FRIENDS_IDS_MAX_LIMIT <= twitter_next_cursor:\n twitter_next_cursor = 0\n\n twitter_ids_i_follow = list()\n try:\n cursor = tweepy.Cursor(\n api.friends_ids, id=twitter_id_of_me, count=TWITTER_FRIENDS_IDS_MAX_LIMIT, since_id=twitter_next_cursor)\n for twitter_ids in cursor.pages():\n twitter_next_cursor += len(twitter_ids)\n twitter_ids_i_follow.extend(twitter_ids)\n success = True\n twitter_next_cursor_state = self.create_twitter_next_cursor_state(\n twitter_id_of_me, TWITTER_API_NAME_FRIENDS_ID, twitter_next_cursor)\n status = status + ' ' + twitter_next_cursor_state['status']\n except tweepy.RateLimitError:\n success = False\n status += ' RETRIEVE_TWITTER_IDS_I_FOLLOW_RATE_LIMIT_ERROR '\n except tweepy.error.TweepError as error_instance:\n success = 'RETRIEVE_TWITTER_IDS_I_FOLLOW_TWEEPY_ERROR: {} '.format(error_instance.reason)\n\n results = {\n 'success': success,\n 'status': status + ' RETRIEVE_TWITTER_IDS_I_FOLLOW_COMPLETED',\n 'twitter_next_cursor': twitter_next_cursor,\n 'twitter_ids_i_follow': twitter_ids_i_follow,\n }\n return results\n\n def retrieve_twitter_who_i_follow_list(self, twitter_id_of_me):\n \"\"\"\n Retrieve twitter ids that twitter_id_of_me follows from TwitterWhoIFollow table.\n :param twitter_id_of_me:\n :return:\n \"\"\"\n status = \"\"\n twitter_who_i_follow_list = []\n\n if not positive_value_exists(twitter_id_of_me):\n success = False\n status = 'RETRIEVE_TWITTER_WHO_I_FOLLOW-MISSING_TWITTER_ID '\n results = {\n 'success': success,\n 'status': status,\n 'twitter_who_i_follow_list_found': False,\n 'twitter_who_i_follow_list': [],\n }\n return results\n\n try:\n twitter_who_i_follow_queryset = TwitterWhoIFollow.objects.all()\n twitter_who_i_follow_queryset = twitter_who_i_follow_queryset.filter(\n twitter_id_of_me=twitter_id_of_me)\n twitter_who_i_follow_list = twitter_who_i_follow_queryset\n\n if len(twitter_who_i_follow_list):\n success = True\n twitter_who_i_follow_list_found = True\n status += ' TWITTER_WHO_I_FOLLOW_LIST_RETRIEVED '\n else:\n success = True\n twitter_who_i_follow_list_found = False\n status += ' NO_TWIITER_WHO_I_FOLLOW_LIST_RETRIEVED '\n except TwitterWhoIFollow.DoesNotExist:\n # No data found. Not a problem.\n success = True\n twitter_who_i_follow_list_found = False\n status += ' NO_TWIITER_WHO_I_FOLLOW_LIST_RETRIEVED_DoesNotExist '\n twitter_who_i_follow_list = []\n except Exception as e:\n success = False\n twitter_who_i_follow_list_found = False\n status += ' FAILED retrieve_twitter_who_i_follow0_list TwitterWhoIFollow '\n\n results = {\n 'success': success,\n 'status': status,\n 'twitter_who_i_follow_list_found': twitter_who_i_follow_list_found,\n 'twitter_who_i_follow_list': twitter_who_i_follow_list,\n }\n return results\n\n def retrieve_twitter_next_cursor_state(self, twitter_id_of_me):\n \"\"\"\n We use this subroutine to get twitter next cursor value from TwitterCursorState table\n :param twitter_id_of_me:\n :return: twitter_next_cursor\n \"\"\"\n try:\n twitter_next_cursor_state = TwitterCursorState.objects.get(\n twitter_id_of_me=twitter_id_of_me,)\n twitter_next_cursor = twitter_next_cursor_state.twitter_next_cursor\n success = True\n status = \"RETRIEVE_TWITTER_NEXT_CURSOR_FOUND_WITH_TWITTER_ID\"\n except TwitterCursorState.DoesNotExist:\n twitter_next_cursor = 0\n twitter_next_cursor_state = TwitterCursorState()\n success = True\n status = \"RETRIEVE_TWITTER_NEXT_CURSOR_NONE_FOUND\"\n\n results = {\n 'success': success,\n 'status': status,\n 'twitter_next_cursor': twitter_next_cursor,\n 'twitter_cursor_state': twitter_next_cursor_state,\n }\n return results\n\n def create_twitter_who_i_follow_entries(self, twitter_id_of_me, twitter_ids_i_follow, organization_found=False):\n \"\"\"\n We use this subroutine to create or update TwitterWhoIFollow table with twitter ids i follow.\n :param organization_found:\n :param twitter_id_of_me:\n :param twitter_ids_i_follow:\n :return:\n \"\"\"\n twitter_who_i_follow = TwitterWhoIFollow()\n try:\n for twitter_id_i_follow in twitter_ids_i_follow:\n # TODO anisha Need to check how to get reference for all twitter_who_i_follow\n twitter_who_i_follow, created = TwitterWhoIFollow.objects.update_or_create(\n twitter_id_of_me=twitter_id_of_me,\n twitter_id_i_follow=twitter_id_i_follow,\n # organization_found=organization_found,\n defaults={\n 'twitter_id_of_me': twitter_id_of_me,\n 'twitter_id_i_follow': twitter_id_i_follow\n # 'organization_found': organization_found\n }\n )\n twitter_who_i_follow_saved = True\n success = True\n status = \"TWITTER_WHO_I_FOLLOW_CREATED\"\n except Exception:\n twitter_who_i_follow_saved = False\n twitter_who_i_follow = TwitterWhoIFollow()\n success = False\n status = \"TWITTER_WHO_I_FOLLOW_NOT_CREATED\"\n results = {\n 'success': success,\n 'status': status,\n 'twitter_who_i_follow_saved': twitter_who_i_follow_saved,\n 'twitter_who_i_follow': twitter_who_i_follow,\n }\n return results\n\n def create_twitter_next_cursor_state(self, twitter_id_of_me, twitter_api_name, twitter_next_cursor):\n \"\"\"\n We use this subroutine to create or update TwitterCursorState table with next cursor value\n :param twitter_id_of_me:\n :param twitter_api_name:\n :param twitter_next_cursor:\n :return:\n \"\"\"\n try:\n twitter_next_cursor_state, created = TwitterCursorState.objects.update_or_create(\n twitter_id_of_me=twitter_id_of_me,\n twitter_api_name__iexact=twitter_api_name,\n defaults={\n 'twitter_id_of_me': twitter_id_of_me,\n 'twitter_api_name': twitter_api_name,\n 'twitter_next_cursor': twitter_next_cursor,\n }\n )\n twitter_next_cursor_state_saved = True\n success = True\n status = \"TWITTER_NEXT_CURSOR_STATE_CREATED\"\n except Exception:\n twitter_next_cursor_state_saved = False\n twitter_next_cursor_state = TwitterCursorState()\n success = False\n status = \"TWITTER_NEXT_CURSOR_STATE_NOT_CREATED\"\n results = {\n 'success': success,\n 'status': status,\n 'twitter_next_cursor_state_saved': twitter_next_cursor_state_saved,\n 'twitter_cursor_state': twitter_next_cursor_state,\n }\n return results\n\n def save_new_twitter_user_from_twitter_json(self, twitter_json, cached_twitter_profile_image_url_https=None,\n cached_twitter_profile_background_image_url_https=None,\n cached_twitter_profile_banner_url_https=None,\n we_vote_hosted_profile_image_url_large=None,\n we_vote_hosted_profile_image_url_medium=None,\n we_vote_hosted_profile_image_url_tiny=None):\n\n if 'screen_name' not in twitter_json:\n results = {\n 'success': False,\n 'status': \"SAVE_NEW_TWITTER_USER_MISSING_HANDLE\",\n 'twitter_user_found': False,\n 'twitter_user': TwitterUser(),\n }\n return results\n\n try:\n # Create new twitter_user entry\n twitter_description = twitter_json['description'] if 'description' in twitter_json else \"\"\n twitter_followers_count = twitter_json['followers_count'] if 'followers_count' in twitter_json else 0\n twitter_handle = twitter_json['screen_name'] if 'screen_name' in twitter_json else \"\"\n\n # Strip out the twitter handles \"False\" or \"None\"\n if twitter_handle:\n twitter_handle_lower = twitter_handle.lower()\n if twitter_handle_lower == 'false' or twitter_handle_lower == 'none':\n twitter_handle = ''\n\n twitter_id = twitter_json['id'] if 'id' in twitter_json else None\n twitter_location = twitter_json['location'] if 'location' in twitter_json else \"\"\n twitter_name = twitter_json['name'] if 'name' in twitter_json else \"\"\n\n if positive_value_exists(cached_twitter_profile_background_image_url_https):\n twitter_profile_background_image_url_https = cached_twitter_profile_background_image_url_https\n elif 'profile_background_image_url_https' in twitter_json:\n twitter_profile_background_image_url_https = twitter_json['profile_background_image_url_https']\n else:\n twitter_profile_background_image_url_https = \"\"\n\n if positive_value_exists(cached_twitter_profile_banner_url_https):\n twitter_profile_banner_url_https = cached_twitter_profile_banner_url_https\n elif 'profile_banner_url' in twitter_json:\n twitter_profile_banner_url_https = twitter_json['profile_banner_url']\n else:\n twitter_profile_banner_url_https = \"\"\n\n if positive_value_exists(cached_twitter_profile_image_url_https):\n twitter_profile_image_url_https = cached_twitter_profile_image_url_https\n elif 'profile_image_url_https' in twitter_json:\n twitter_profile_image_url_https = twitter_json['profile_image_url_https']\n else:\n twitter_profile_image_url_https = \"\"\n twitter_url = twitter_json['url'] if 'url' in twitter_json else \"\"\n\n twitter_user_on_stage = TwitterUser(\n twitter_description=twitter_description,\n twitter_followers_count=twitter_followers_count,\n twitter_handle=twitter_handle,\n twitter_id=twitter_id,\n twitter_location=twitter_location,\n twitter_name=twitter_name,\n twitter_profile_background_image_url_https=twitter_profile_background_image_url_https,\n twitter_profile_banner_url_https=twitter_profile_banner_url_https,\n twitter_profile_image_url_https=twitter_profile_image_url_https,\n we_vote_hosted_profile_image_url_large=we_vote_hosted_profile_image_url_large,\n we_vote_hosted_profile_image_url_medium=we_vote_hosted_profile_image_url_medium,\n we_vote_hosted_profile_image_url_tiny=we_vote_hosted_profile_image_url_tiny,\n twitter_url=twitter_url,\n )\n twitter_user_on_stage.save()\n success = True\n twitter_user_found = True\n status = 'CREATED_TWITTER_USER'\n except Exception as e:\n success = False\n twitter_user_found = False\n status = 'FAILED_TO_CREATE_NEW_TWITTER_USER'\n twitter_user_on_stage = TwitterUser()\n\n results = {\n 'success': success,\n 'status': status,\n 'twitter_user_found': twitter_user_found,\n 'twitter_user': twitter_user_on_stage,\n }\n return results\n\n def update_or_create_twitter_user(self, twitter_json, twitter_id=None, cached_twitter_profile_image_url_https=None,\n cached_twitter_profile_background_image_url_https=None,\n cached_twitter_profile_banner_url_https=None,\n we_vote_hosted_profile_image_url_large=None,\n we_vote_hosted_profile_image_url_medium=None,\n we_vote_hosted_profile_image_url_tiny=None):\n \"\"\"\n Update a twitter user entry with details retrieved from the Twitter API or\n create a twitter user entry if not exists.\n :param twitter_id:\n :param twitter_json:\n :param cached_twitter_profile_image_url_https:\n :param cached_twitter_profile_background_image_url_https:\n :param cached_twitter_profile_banner_url_https:\n :param we_vote_hosted_profile_image_url_large:\n :param we_vote_hosted_profile_image_url_medium:\n :param we_vote_hosted_profile_image_url_tiny\n :return:\n \"\"\"\n values_changed = False\n\n twitter_results = self.retrieve_twitter_user(twitter_id)\n twitter_user_found = twitter_results['twitter_user_found']\n if twitter_user_found:\n # Twitter user already exists so update twitter user details\n twitter_user = twitter_results['twitter_user']\n if 'id' in twitter_json and positive_value_exists(twitter_json['id']):\n if convert_to_int(twitter_json['id']) != twitter_user.twitter_id:\n twitter_user.twitter_id = convert_to_int(twitter_json['id'])\n values_changed = True\n if 'screen_name' in twitter_json and positive_value_exists(twitter_json['screen_name']):\n if twitter_json['screen_name'] != twitter_user.twitter_handle:\n twitter_user.twitter_handle = twitter_json['screen_name']\n values_changed = True\n if 'name' in twitter_json and positive_value_exists(twitter_json['name']):\n if twitter_json['name'] != twitter_user.twitter_name:\n twitter_user.twitter_name = twitter_json['name']\n values_changed = True\n if 'url' in twitter_json and positive_value_exists(twitter_json['url']):\n if twitter_json['url'] != twitter_user.twitter_url:\n twitter_user.twitter_url = twitter_json['url']\n values_changed = True\n if 'followers_count' in twitter_json and positive_value_exists(twitter_json['followers_count']):\n if convert_to_int(twitter_json['followers_count']) != twitter_user.twitter_followers_count:\n twitter_user.twitter_followers_count = convert_to_int(twitter_json['followers_count'])\n values_changed = True\n\n if positive_value_exists(cached_twitter_profile_image_url_https):\n twitter_user.twitter_profile_image_url_https = cached_twitter_profile_image_url_https\n values_changed = True\n elif 'profile_image_url_https' in twitter_json and \\\n positive_value_exists(twitter_json['profile_image_url_https']):\n if twitter_json['profile_image_url_https'] != twitter_user.twitter_profile_image_url_https:\n twitter_user.twitter_profile_image_url_https = twitter_json['profile_image_url_https']\n values_changed = True\n\n if positive_value_exists(cached_twitter_profile_banner_url_https):\n twitter_user.twitter_profile_banner_url_https = cached_twitter_profile_banner_url_https\n values_changed = True\n elif ('profile_banner_url' in twitter_json) and positive_value_exists(twitter_json['profile_banner_url']):\n if twitter_json['profile_banner_url'] != twitter_user.twitter_profile_banner_url_https:\n twitter_user.twitter_profile_banner_url_https = twitter_json['profile_banner_url']\n values_changed = True\n\n if positive_value_exists(cached_twitter_profile_background_image_url_https):\n twitter_user.twitter_profile_background_image_url_https = \\\n cached_twitter_profile_background_image_url_https\n values_changed = True\n elif 'profile_background_image_url_https' in twitter_json and positive_value_exists(\n twitter_json['profile_background_image_url_https']):\n if twitter_json['profile_background_image_url_https'] != \\\n twitter_user.twitter_profile_background_image_url_https:\n twitter_user.twitter_profile_background_image_url_https = \\\n twitter_json['profile_background_image_url_https']\n values_changed = True\n if positive_value_exists(we_vote_hosted_profile_image_url_large):\n twitter_user.we_vote_hosted_profile_image_url_large = we_vote_hosted_profile_image_url_large\n values_changed = True\n if positive_value_exists(we_vote_hosted_profile_image_url_medium):\n twitter_user.we_vote_hosted_profile_image_url_medium = we_vote_hosted_profile_image_url_medium\n values_changed = True\n if positive_value_exists(we_vote_hosted_profile_image_url_tiny):\n twitter_user.we_vote_hosted_profile_image_url_tiny = we_vote_hosted_profile_image_url_tiny\n values_changed = True\n\n if 'description' in twitter_json and positive_value_exists(twitter_json['description']):\n if twitter_json['description'] != twitter_user.twitter_description:\n twitter_user.twitter_description = twitter_json['description']\n values_changed = True\n if 'location' in twitter_json and positive_value_exists(twitter_json['location']):\n if twitter_json['location'] != twitter_user.twitter_location:\n twitter_user.twitter_location = twitter_json['location']\n values_changed = True\n\n if values_changed:\n twitter_user.save()\n success = True\n status = \"SAVED_TWITTER_USER_DETAILS\"\n else:\n success = True\n status = \"NO_CHANGES_SAVED_TO_USER_TWITTER_DETAILS\"\n results = {\n 'success': success,\n 'status': status,\n 'twitter_user_found': twitter_user_found,\n 'twitter_user': twitter_user,\n }\n return results\n\n else:\n # Twitter user does not exist so create new twitter user with latest twitter details\n twitter_save_results = self.save_new_twitter_user_from_twitter_json(\n twitter_json, cached_twitter_profile_image_url_https,\n cached_twitter_profile_background_image_url_https, cached_twitter_profile_banner_url_https,\n we_vote_hosted_profile_image_url_large, we_vote_hosted_profile_image_url_medium,\n we_vote_hosted_profile_image_url_tiny)\n return twitter_save_results\n\n def delete_twitter_user(self, twitter_id):\n twitter_id = convert_to_int(twitter_id)\n twitter_user_deleted = False\n\n try:\n if twitter_id:\n results = self.retrieve_twitter_user(twitter_id)\n if results['twitter_user_found']:\n twitter_user = results['twitter_user']\n twitter_id = twitter_user.id\n twitter_user.delete()\n twitter_user_deleted = True\n except Exception as e:\n pass\n\n results = {\n 'success': twitter_user_deleted,\n 'twitter_user_deleted': twitter_user_deleted,\n 'twitter_id': twitter_id,\n }\n return results\n\n\nclass Tweet(models.Model):\n \"\"\"\n A tweet referenced somewhere by a We Vote tag. We store it (once - not every time it is referenced by a tag)\n locally so we can publish JSON from for consumption on the We Vote newsfeed.\n \"\"\"\n # twitter_tweet_id # (unique id from twitter for tweet?)\n author_handle = models.CharField(max_length=15, verbose_name='twitter handle of this tweet\\'s author')\n # (stored quickly before we look up voter_id)\n # author_voter_id = models.ForeignKey(Voter, null=True, blank=True, related_name='we vote id of tweet author')\n is_retweet = models.BooleanField(default=False, verbose_name='is this a retweet?')\n # parent_tweet_id # If this is a retweet, what is the id of the originating tweet?\n body = models.CharField(blank=True, null=True, max_length=255, verbose_name='')\n date_published = models.DateTimeField(null=True, verbose_name='date published')\n\n\nclass TweetFavorite(models.Model):\n \"\"\"\n This table tells us who favorited a tweet\n \"\"\"\n tweet_id = models.ForeignKey(Tweet, null=True, blank=True, verbose_name='we vote tweet id')\n # twitter_tweet_id # (unique id from twitter for tweet?)\n # TODO Should favorited_by_handle be a ForeignKey link to the Twitter User? I'm concerned this will slow saving,\n # and it might be better to ForeignKey against voter_id\n favorited_by_handle = models.CharField(\n max_length=15, verbose_name='twitter handle of person who favorited this tweet')\n # (stored quickly before we look up voter_id)\n # favorited_by_voter_id = models.ForeignKey(\n # Voter, null=True, blank=True, related_name='tweet favorited by voter_id')\n date_favorited = models.DateTimeField(null=True, verbose_name='date favorited')\n\n\n# This should be the master table\nclass TwitterWhoIFollow(models.Model):\n \"\"\"\n Other Twitter ids that I follow, from the perspective of twitter id of me\n \"\"\"\n twitter_id_of_me = models.BigIntegerField(verbose_name=\"twitter id of viewer\", null=False, unique=False)\n twitter_id_i_follow = models.BigIntegerField(verbose_name=\"twitter id of the friend\", null=False, unique=False)\n # organization_found = models.BooleanField(verbose_name=\"organization found in twitterLinkToOrganization\",\n # default=False)\n\n\nclass TwitterCursorState(models.Model):\n \"\"\"\n Maintaining next cursor state of twitter ids that i follow\n \"\"\"\n twitter_id_of_me = models.BigIntegerField(verbose_name=\"twitter id of viewer\", null=False, unique=False)\n twitter_api_name = models.CharField(verbose_name=\"twitter api name\", max_length=255, null=False, unique=False)\n twitter_next_cursor = models.BigIntegerField(verbose_name=\"twitter next cursor state\", null=False, unique=False)\n\n\n# This is a we vote copy (for speed) of Twitter handles that follow me. We should have self-healing scripts that set up\n# entries in TwitterWhoIFollow for everyone following someone in the We Vote network, so this table could be flushed\n# and rebuilt at any time\nclass TwitterWhoFollowMe(models.Model):\n handle_of_me = models.CharField(max_length=15, verbose_name='from this twitter handle\\'s perspective...')\n handle_that_follows_me = models.CharField(max_length=15, verbose_name='twitter handle of this tweet\\'s author')\n","sub_path":"twitter/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":47521,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"278287348","text":"from sqlalchemy.sql import func\n\nfrom .models import Asset, AssetClass\nfrom .db import get_db_session\n\n\nclass AssetSerializer:\n def __init__(self, asset=None, assets=None):\n self.assets = assets\n self.asset = asset\n\n def serialize(self):\n if self.assets:\n return self.serialize_assets(self.assets)\n elif self.asset:\n return self.split_asset(self.asset)\n return {}\n\n def serialize_assets(self, assets):\n data = []\n for asset in assets:\n asset_details = self.split_asset(asset)\n data.append(asset_details)\n return data\n\n def split_asset(self, asset):\n name = asset.name\n asset_class = asset.asset_class_details.class_name.value\n asset_type = asset.asset_class_details.class_type.value\n created_at = str(asset.created_at)\n return {\n \"name\": name,\n \"asset_class\": asset_class,\n \"asset_type\": asset_type,\n \"created_at\": created_at,\n }\n\n def deserialize(self, data):\n session = get_db_session()\n try:\n name = data[\"name\"]\n asset_class_name = data[\"asset_class\"]\n asset_type = data[\"asset_type\"]\n asset_class = (\n session.query(AssetClass).filter_by(class_name=asset_class_name).one()\n )\n asset = Asset(name=name, asset_class=asset_class.id, created_at=func.now())\n asset.verify_type(asset_class, asset_type)\n return asset\n finally:\n session.close()\n","sub_path":"asset_store/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":1579,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"491218786","text":"from werkzeug.utils import secure_filename\r\nfrom flask import *\r\nfrom forms import *\r\nfrom db import *\r\nimport json\r\nimport os\r\n\r\napp = Flask(__name__)\r\napp.config['SECRET_KEY'] = 'yandexlyceum_secret_key'\r\napp.config['UPLOAD_FOLDER'] = 'static/img/'\r\napp.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024\r\n\r\n\r\ndef cart_len():\r\n if \"username\" in session:\r\n with open('data/shopping_cart.json', \"rt\", encoding=\"utf8\") as f:\r\n carts = json.loads(f.read())\r\n return len(carts[str(session['user_id'])].keys())\r\n else:\r\n return None\r\n\r\n\r\ndef search(phrase):\r\n phrase = phrase.lower()\r\n gm = GoodsModel(goods_db.get_connection())\r\n gm.init_table()\r\n all = gm.get_all()\r\n c = filter(lambda x: phrase in x[2].lower() or phrase in x[3].lower(), all)\r\n return list(c)\r\n\r\n\r\n@app.route('/search/', methods=['GET', 'POST'])\r\ndef searched(phrase):\r\n if request.method == 'POST':\r\n if request.form.get('search'):\r\n phrase = request.form['search']\r\n return redirect('/search/{}'.format(phrase))\r\n with open('data/image_sources.json', \"rt\", encoding=\"utf8\") as f:\r\n srcs = json.loads(f.read())\r\n return render_template('items.html', goods=search(phrase), title=phrase,\r\n name='поиск', srcs=srcs, cart_items=cart_len())\r\n\r\n\r\n@app.route('/', methods=['GET', 'POST'])\r\n@app.route('/index', methods=['GET', 'POST'])\r\ndef main_page():\r\n if request.method == 'POST':\r\n if request.form.get('search'):\r\n phrase = request.form['search']\r\n return redirect('/search/{}'.format(phrase))\r\n with open('data/categories.json', \"rt\", encoding=\"utf8\") as f:\r\n categories = json.loads(f.read())\r\n return render_template('index.html', title='Главная',\r\n categories=categories, cart_items=cart_len())\r\n\r\n\r\n@app.route('/login', methods=['GET', 'POST'])\r\ndef login():\r\n form = LoginForm()\r\n if form.validate_on_submit():\r\n user_name = form.username.data\r\n password = form.password.data\r\n user_model = UsersModel(db.get_connection())\r\n exists = user_model.exists(user_name, password)\r\n if (exists[0]):\r\n session['username'] = user_name\r\n session['user_id'] = exists[1]\r\n session['is_admin'] = eval(exists[2])\r\n with open('data/shopping_cart.json', \"rt\", encoding=\"utf8\") as f:\r\n all_carts = json.loads(f.read())\r\n with open('data/shopping_cart.json', \"w\", encoding=\"utf8\") as f:\r\n if str(session['user_id']) not in all_carts:\r\n all_carts[session['user_id']] = dict()\r\n f.write(json.dumps(all_carts))\r\n return redirect(\"/index\")\r\n else:\r\n return render_template('login.html', title='Авторизация',\r\n form=form,\r\n message='Неверный логин или пароль')\r\n return render_template('login.html', title='Авторизация', form=form)\r\n\r\n\r\n@app.route('/registration', methods=['GET', 'POST'])\r\ndef registration():\r\n form = RegistrationForm()\r\n message = 'Длина пароля должна быть не меньше 7 символов'\r\n if form.validate_on_submit():\r\n user_name = form.username.data\r\n password = form.password.data\r\n if len(password) < 7:\r\n return render_template('registration.html', form=form,\r\n message=message)\r\n um.insert(user_name, password)\r\n return redirect('/')\r\n return render_template('registration.html', title='Регистрация', form=form)\r\n\r\n\r\n@app.route('/logout')\r\ndef logout():\r\n session.pop('username', 0)\r\n session.pop('user_id', 0)\r\n session.pop('is_admin', 0)\r\n return redirect('/index')\r\n\r\n\r\n@app.route('/admin_panel', methods=['GET', 'POST'])\r\ndef admin_panel():\r\n if request.method == 'POST':\r\n if request.form.get('search'):\r\n phrase = request.form['search']\r\n return redirect('/search/{}'.format(phrase))\r\n if not session['is_admin']:\r\n return redirect('/')\r\n return render_template('admin_panel.html', title='Админ-панель',\r\n cart_items=cart_len())\r\n\r\n\r\n@app.route('/all_users', methods=['GET', 'POST'])\r\ndef all_users():\r\n if request.method == 'POST':\r\n if request.form.get('search'):\r\n phrase = request.form['search']\r\n return redirect('/search/{}'.format(phrase))\r\n if \"username\" not in session:\r\n return redirect('/login')\r\n if not session['is_admin']:\r\n return redirect('/')\r\n um = UsersModel(db.get_connection())\r\n um.init_table()\r\n all_users = um.get_all()\r\n return render_template('all_users.html', title='Все пользователи',\r\n users=enumerate(all_users, 1),\r\n cart_items=cart_len())\r\n\r\n\r\n@app.route('/add_photo/', methods=['GET', 'POST'])\r\ndef add_photo(id):\r\n if request.method == 'POST':\r\n if request.form.get('search'):\r\n phrase = request.form['search']\r\n return redirect('/search/{}'.format(phrase))\r\n if \"username\" not in session:\r\n return redirect('/login')\r\n if not session['is_admin']:\r\n return redirect('/')\r\n form = AddPhotoForm()\r\n if form.validate_on_submit():\r\n myFile = secure_filename(form.photo_upload.data.filename)\r\n with open('data/image_sources.json', \"rt\", encoding=\"utf8\") as f:\r\n srcs = json.loads(f.read())\r\n with open('data/image_sources.json', \"w\", encoding=\"utf8\") as f:\r\n try:\r\n srcs[id] += ['static/img/{}'.format(myFile)]\r\n except:\r\n srcs[id] = ['static/img/{}'.format(myFile)]\r\n f.write(json.dumps(srcs))\r\n form.photo_upload.data.save('static/img/{}'.format(myFile))\r\n return redirect('/add_photo/{}'.format(id))\r\n return render_template('add_photo.html', form=form,\r\n title='Добавление фото', cart_items=cart_len())\r\n\r\n\r\n@app.route('/add_goods', methods=['GET', 'POST'])\r\ndef add_goods():\r\n if request.method == 'POST':\r\n if request.form.get('search'):\r\n phrase = request.form['search']\r\n return redirect('/search/{}'.format(phrase))\r\n if \"username\" not in session:\r\n return redirect('/login')\r\n if not session['is_admin']:\r\n return redirect('/')\r\n form = AddGoodsForm()\r\n if form.validate_on_submit():\r\n gm = GoodsModel(goods_db.get_connection())\r\n gm.init_table()\r\n type = form.type.data\r\n name = form.name.data\r\n description = form.description.data\r\n try:\r\n price = int(form.price.data)\r\n except:\r\n return('Цена должна быть введена в рублях(целым числом)')\r\n myFile = secure_filename(form.file_upload.data.filename)\r\n gm.insert(type, name, description, price)\r\n latest = max(gm.get_all(), key=lambda x: x[5])\r\n with open('data/image_sources.json', \"rt\", encoding=\"utf8\") as f:\r\n srcs = json.loads(f.read())\r\n with open('data/image_sources.json', \"w\", encoding=\"utf8\") as f:\r\n try:\r\n srcs[latest[0]] += ['static/img/{}'.format(myFile)]\r\n except:\r\n srcs[latest[0]] = ['static/img/{}'.format(myFile)]\r\n f.write(json.dumps(srcs))\r\n form.file_upload.data.save('static/img/{}'.format(myFile))\r\n return redirect('/')\r\n return render_template('add_goods.html', title='Добавление товара',\r\n form=form, cart_items=cart_len())\r\n\r\n\r\n@app.route('/items/', methods=['GET', 'POST'])\r\ndef items(type):\r\n if request.method == 'POST':\r\n if request.form.get('search'):\r\n phrase = request.form['search']\r\n return redirect('/search/{}'.format(phrase))\r\n with open('data/categories.json', \"rt\", encoding=\"utf8\") as f:\r\n categories = json.loads(f.read())\r\n for d in categories:\r\n if d['name'] == type:\r\n name = d['title']\r\n with open('data/image_sources.json', \"rt\", encoding=\"utf8\") as f:\r\n srcs = json.loads(f.read())\r\n gm = GoodsModel(goods_db.get_connection())\r\n gm.init_table()\r\n goods = gm.get_by_type(type)\r\n return render_template('items.html', goods=goods, title=name,\r\n name=name.lower(), srcs=srcs, cart_items=cart_len())\r\n\r\n\r\n@app.route('/delete/')\r\ndef delete(id):\r\n if \"username\" not in session:\r\n return redirect('/login')\r\n if not session['is_admin']:\r\n return redirect('/')\r\n with open('data/image_sources.json', \"rt\", encoding=\"utf8\") as f:\r\n srcs = json.loads(f.read())\r\n for img_path in srcs[id]:\r\n if os.path.isfile(img_path):\r\n os.remove(img_path)\r\n else:\r\n print('delete_error')\r\n srcs.pop(id, 0)\r\n with open('data/image_sources.json', \"w\", encoding=\"utf8\") as f:\r\n f.write(json.dumps(srcs))\r\n gm = GoodsModel(goods_db.get_connection())\r\n gm.init_table()\r\n gm.delete(int(id))\r\n return redirect('/')\r\n\r\n\r\n@app.route('/item/', methods=['GET', 'POST'])\r\ndef item_page(id):\r\n if request.method == 'POST':\r\n if request.form.get('search'):\r\n phrase = request.form['search']\r\n return redirect('/search/{}'.format(phrase))\r\n gm = GoodsModel(goods_db.get_connection())\r\n gm.init_table()\r\n goods = gm.get(id)\r\n with open('data/image_sources.json', \"rt\", encoding=\"utf8\") as f:\r\n srcs = json.loads(f.read())\r\n srcs = srcs[id]\r\n if len(srcs) < 2:\r\n one_src = srcs[0]\r\n srcs = srcs[1:]\r\n else:\r\n one_src = srcs[1]\r\n srcs = srcs[2:]\r\n return render_template('item.html', title=goods[2], item=goods, srcs=srcs,\r\n length=len(srcs),\r\n one_src=one_src,\r\n cart_items=cart_len())\r\n\r\n\r\n@app.route('/add_to_cart//')\r\ndef cart_adding(user_id, goods_id):\r\n if \"username\" not in session:\r\n return redirect('/login')\r\n if session['user_id'] != user_id:\r\n return redirect('/')\r\n with open('data/shopping_cart.json', \"rt\", encoding=\"utf8\") as f:\r\n all_carts = json.loads(f.read())\r\n with open('data/shopping_cart.json', \"w\", encoding=\"utf8\") as f:\r\n try:\r\n if str(goods_id) not in all_carts[str(user_id)]:\r\n all_carts[str(user_id)][str(goods_id)] = 1\r\n else:\r\n all_carts[str(user_id)][str(goods_id)] += 1\r\n except:\r\n all_carts[str(user_id)] = {str(goods_id): 1}\r\n f.write(json.dumps(all_carts))\r\n return redirect('/item/{}'.format(str(goods_id)))\r\n\r\n\r\n@app.route('/cart/', methods=['GET', 'POST'])\r\ndef user_cart(id):\r\n if request.method == 'POST':\r\n if request.form.get('search'):\r\n phrase = request.form['search']\r\n return redirect('/search/{}'.format(phrase))\r\n if \"username\" not in session:\r\n return redirect('/login')\r\n if session['user_id'] != id:\r\n return redirect('/')\r\n with open('data/shopping_cart.json', \"rt\", encoding=\"utf8\") as f:\r\n all_carts = json.loads(f.read())\r\n cart = all_carts[str(id)]\r\n if request.method == 'POST':\r\n if 'search' not in request.form:\r\n for good_id in cart.keys():\r\n all_carts[str(id)][str(good_id)] = int(request.form['count_{}'.format(good_id)])\r\n with open('data/shopping_cart.json', \"w\", encoding=\"utf8\") as f:\r\n f.write(json.dumps(all_carts))\r\n return redirect('/cart/{}'.format(str(id)))\r\n all_goods = []\r\n gm = GoodsModel(goods_db.get_connection())\r\n gm.init_table()\r\n for good_id in cart.keys():\r\n all_goods.append((gm.get(good_id), cart[good_id]))\r\n sum = 0\r\n for good in all_goods:\r\n sum += good[0][4] * good[1]\r\n return render_template('cart.html', goods=all_goods, title='Корзина',\r\n sum=sum, cart_items=cart_len())\r\n\r\n\r\n@app.route('/delete_from_cart/')\r\ndef delete_from_cart(good_id):\r\n if \"username\" not in session:\r\n return redirect('/login')\r\n with open('data/shopping_cart.json', \"rt\", encoding=\"utf8\") as f:\r\n all_carts = json.loads(f.read())\r\n with open('data/shopping_cart.json', \"w\", encoding=\"utf8\") as f:\r\n all_carts[str(session['user_id'])].pop(str(good_id), 0)\r\n f.write(json.dumps(all_carts))\r\n return redirect('cart/{}'.format(session['user_id']))\r\n\r\n\r\n@app.route('/make_order')\r\ndef make_order():\r\n om = OrdersModel(orders_db.get_connection())\r\n om.init_table()\r\n if \"username\" not in session:\r\n return redirect('/login')\r\n with open('data/shopping_cart.json', \"rt\", encoding=\"utf8\") as f:\r\n all_carts = json.loads(f.read())\r\n cart = all_carts[str(session['user_id'])]\r\n for good_id in cart.keys():\r\n if cart[good_id] < 1:\r\n a = 1\r\n else:\r\n gm = GoodsModel(goods_db.get_connection())\r\n gm.init_table()\r\n good = gm.get(good_id)\r\n om.insert(good_id, session['user_id'], good[4], cart[good_id])\r\n all_carts[str(session['user_id'])] = {}\r\n with open('data/shopping_cart.json', \"w\", encoding=\"utf8\") as f:\r\n f.write(json.dumps(all_carts))\r\n return redirect('/cart/{}'.format(str(session['user_id'])))\r\n\r\n\r\n@app.route('/my_orders', methods=['GET', 'POST'])\r\ndef orders():\r\n if request.method == 'POST':\r\n if request.form.get('search'):\r\n phrase = request.form['search']\r\n return redirect('/search/{}'.format(phrase))\r\n if \"username\" not in session:\r\n return redirect('/login')\r\n om = OrdersModel(orders_db.get_connection())\r\n om.init_table()\r\n gm = GoodsModel(goods_db.get_connection())\r\n gm.init_table()\r\n names = []\r\n orders = sorted(om.get_by_user(session['user_id']), key=lambda x: x[7],\r\n reverse=True)\r\n for order in orders:\r\n names.append(gm.get(order[1]))\r\n return render_template('orders.html', title='Заказы',\r\n orders=zip(orders, names), cart_items=cart_len())\r\n\r\n\r\n@app.route('/order_control', methods=['GET', 'POST'])\r\ndef order_control():\r\n if request.method == 'POST':\r\n if request.form.get('search'):\r\n phrase = request.form['search']\r\n return redirect('/search/{}'.format(phrase))\r\n if \"username\" not in session:\r\n return redirect('/login')\r\n if not session['is_admin']:\r\n return redirect('/')\r\n om = OrdersModel(orders_db.get_connection())\r\n om.init_table()\r\n gm = GoodsModel(goods_db.get_connection())\r\n gm.init_table()\r\n names = []\r\n orders = sorted(om.get_all(), key=lambda x: x[7],\r\n reverse=True)\r\n for order in orders:\r\n names.append(gm.get(order[1]))\r\n return render_template('order_control.html', title='Изменить статус',\r\n orders=zip(orders, names), cart_items=cart_len())\r\n\r\n\r\n@app.route('/edit_order/', methods=['GET', 'POST'])\r\ndef edit_order(order_id):\r\n if request.method == 'POST':\r\n if request.form.get('search'):\r\n phrase = request.form['search']\r\n return redirect('/search/{}'.format(phrase))\r\n if \"username\" not in session:\r\n return redirect('/login')\r\n if not session['is_admin']:\r\n return redirect('/')\r\n om = OrdersModel(orders_db.get_connection())\r\n om.init_table()\r\n if request.method == 'POST':\r\n if 'search' not in request.form:\r\n om.change_status(order_id, request.form['new_status'])\r\n return redirect('/edit_order/{}'.format(str(order_id)))\r\n order = om.get(order_id)\r\n options = (\r\n 'Формируется к отправке',\r\n 'Едет в пункт выдачи',\r\n 'Ждёт в пункте выдачи',\r\n 'Получен'\r\n )\r\n return render_template('edit_order.html', title='Изменить статус',\r\n order=order, options=options,\r\n cart_items=cart_len())\r\n\r\n\r\n@app.route('/delete_order/')\r\ndef delete_order(order_id):\r\n if \"username\" not in session:\r\n return redirect('/login')\r\n if not session['is_admin']:\r\n return redirect('/')\r\n om = OrdersModel(orders_db.get_connection())\r\n om.init_table()\r\n om.delete(order_id)\r\n return redirect('/')\r\n\r\n\r\nif __name__ == '__main__':\r\n db = DB('users')\r\n goods_db = DB('goods')\r\n orders_db = DB('orders')\r\n um = UsersModel(db.get_connection())\r\n um.init_table()\r\n app.run(port=8080, host='127.0.0.1', debug=False)\r\n","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":17051,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"65128079","text":"from splinter import Browser\nfrom bs4 import BeautifulSoup\nimport os\nimport json\nimport platform\n\n\ndef init_browser():\n if platform.system().lower() == 'windows'.lower():\n executable_path = {\n 'executable_path':\n os.path.join(os.getcwd(), 'chromedriver.exe')}\n return Browser('chrome', **executable_path, headless=True)\n else:\n return Browser('chrome', headless=True)\n\n\nbr = init_browser()\n\n\ndef get_html(browser, url):\n browser.visit(url)\n html = browser.html\n return html\n\n\ndef get_listings(html):\n soup = BeautifulSoup(html, \"html.parser\")\n stops = soup.find_all('tr', attrs={'height': 25})\n collection = []\n for stop in stops:\n try:\n collection.append(stop.find('span', class_='emphasized').text)\n except Exception as e:\n print(e)\n collection = [\n name.replace('\\n', '').replace(' /', '').replace(' ', '') for name in collection\n ]\n collection = [\n name.replace('\\t', '').replace('Street', 'St').replace('Avenue', 'Av')\n .replace('Road', 'Rd').replace('Square', 'Sq') for name in collection\n ]\n for i, name in enumerate(collection):\n if name[0] == ' ':\n collection[i] = name[1:]\n elif name[-1] == ' ':\n collection[i] = name[:-1]\n collection = [name.replace('-', ' - ') for name in collection]\n return collection\n\n\ncodes = {'A': 'aline', 'C': 'cline', 'E': 'eline',\n 'B': 'bline', 'D': 'dline', 'F': 'fline',\n 'M': 'mline', 'L': 'lline', 'J': 'jline',\n 'Z': 'zline', 'N': 'nline', 'Q': 'qline',\n 'R': 'rline', '1': 'oneline', '2': 'twoline',\n '3': 'threelin', '4': 'fourline', '5': 'fiveline',\n '6': 'sixline', '7': 'sevenlin'}\n\nstopcache = {}\nfor code in list(codes.items()):\n stop_list = get_listings(get_html(br, f'http://web.mta.info/nyct/service/{code[1]}.htm'))\n stopcache[code[0]] = stop_list\n\nwith open('stops.json', 'w') as fp:\n json.dump(stopcache, fp)\n","sub_path":"scrape_stops.py","file_name":"scrape_stops.py","file_ext":"py","file_size_in_byte":2013,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"252362594","text":"#-*- coding: utf-8 -*-\n\nfrom django import forms\nfrom django.db import models\nfrom django.forms import fields\n\n\n\"\"\"\nfull_url = URLField(default_protocol=\"http\",\n protocols=[\"https\",\"ssh\",\"mailto\"])\nurl = URLField()\n\"\"\"\n\n\nclass URLField(models.Field):\n \"\"\"\n Custom Django URLField that takes acceptable protocols.\n \"\"\"\n description = \"URL Field\"\n __metaclass__ = models.SubfieldBase\n\n def __init__(self, default_protocol=\"http\", protocols=[], *args, **kwargs):\n \"\"\"\n Setup the URLField with parameters and a max_length\n \"\"\"\n #Sets the max length of 4096 in the database.\n kwargs['max_length'] = kwargs.get(\"max_length\", 4096)\n #Sets the default protocol\n self.default_protocol = default_protocol\n #Makes sure protocols is a list, as I insert to the list later.\n if type(protocols) is list:\n self.protocols = protocols\n else:\n raise ValueError(\"protocols must be a list\")\n super(URLField, self).__init__(*args, **kwargs)\n\n def to_python(self, value):\n \"\"\"\n Either return a blank string, or the url.\n \"\"\"\n if not value:\n return \"\"\n elif isinstance(value, basestring):\n return value\n\n def db_type(self, connection):\n \"\"\"\n Set as VARCHAR for Postgres.\n \"\"\"\n #TODO: Set up multiple backend testing.\n return \"VARCHAR(%s) NOT NULL DEFAULT ''::character varying\" % \\\n (self.max_length, )\n\n def formfield(self, **kwargs):\n \"\"\"\n Setup to use the URLFieldForm for our fields form.\n \"\"\"\n defaults = {'form_class': URLFieldForm}\n defaults['default_protocol'] = self.default_protocol\n defaults['protocols'] = self.protocols\n defaults.update(kwargs)\n return super(URLField, self).formfield(**defaults)\n\n def get_prep_value(self, value):\n \"\"\"\n This will check whether the url is either:\n Protocolless - (and appends a default_protocol to the beginning)\n has a correct protoco - (returns the url)\n If neither of these are a result, it will error with an appropriate\n error message\n \"\"\"\n if not value:\n return None\n else:\n url_parts = str(value).split(\"://\")\n if len(url_parts) == 1:\n value = \"%s://%s\" % (self.default_protocol, value)\n return value\n elif len(url_parts) == 2:\n if url_parts[0].lower() in self.protocols or\\\n url_parts[0].lower() == self.default_protocol:\n if url_parts[1]:\n return value\n else:\n raise forms.ValidationError(\n \"Must supply more than just a protocol.\")\n else:\n acceptable = self.protocols\n acceptable.insert(0, self.default_protocol)\n raise forms.ValidationError(\n \"Protocol not accepted. (%s) MUST BE %s\" %\n (url_parts[0], acceptable))\n else:\n raise forms.ValidationError(\"Not a well formatted URL\")\n\n\nclass URLFieldForm(fields.CharField):\n \"\"\"\n Custom Django URLFieldForm\n \"\"\"\n def __init__(self, *args, **kwargs):\n \"\"\"\n Setup the URLField with parameters and a max_length\n \"\"\"\n self.default_protocol = kwargs.pop(\"default_protocol\", \"http\")\n self.protocols = kwargs.pop(\"protocols\", [])\n\n dwargs = {\n 'required': False, 'label': None, 'blank': True, 'initial': None,\n 'help_text': None, 'error_messages': None,\n 'show_hidden_initial': None,\n }\n for attr in dwargs:\n if attr in kwargs:\n dwargs[attr] = kwargs[attr]\n\n super(URLFieldForm, self).__init__(*args, **kwargs)\n\n def clean(self, value):\n \"\"\"\n This will check whether the url is either:\n Protocolless - (and appends a default_protocol to the beginning)\n has a correct protoco - (returns the url)\n If neither of these are a result, it will error with an appropriate\n error message\n \"\"\"\n if not value:\n return None\n else:\n url_parts = value.split(\"://\")\n if len(url_parts) == 1:\n value = \"%s://%s\" % (self.default_protocol, value)\n return value\n elif len(url_parts) == 2:\n if url_parts[0].lower() in self.protocols or\\\n url_parts[0].lower() == self.default_protocol:\n if url_parts[1]:\n return value\n else:\n raise forms.ValidationError(\n \"Must supply more than just a protocol.\")\n else:\n acceptable = self.protocols\n acceptable.insert(0, self.default_protocol)\n raise forms.ValidationError(\n \"Protocol not accepted. (%s) MUST BE %s\" %\n (url_parts[0], acceptable))\n else:\n raise forms.ValidationError(\"Not acceptable URL\")\n","sub_path":"fields.py","file_name":"fields.py","file_ext":"py","file_size_in_byte":5283,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"395647824","text":"from flask import Flask, render_template, request \n\n#using the flask app to create a web server\napp = Flask(__name__)\napp.config.from_object(__name__)\n\n@app.route('/')\ndef hello():\n return render_template(\"index.html\")\n\n@app.route('/welcome', methods=['GET', 'POST'])\ndef welcome():\n if request.method == \"POST\":\n #this is collecting the responses from the form in index\n animal=request.form.get('animal')\n country=request.form.get('country')\n pluralNoun=request.form.get('pluralNoun')\n food=request.form.get('food')\n screen=request.form.get('screen')\n noun=request.form.get('noun')\n verb=request.form.get('verb')\n verb2=request.form.get('verb2')\n adjective=request.form.get('adjective')\n #the data is returned within the story\n return \"The majestic \" + animal + \" has roamed the forests of \" + country + \" for thousands of years. Today, she wanders in search of \" + pluralNoun + \". She must find food to survive. While hunting for \" + food + \", she found a/an \" + screen + \" hidden behind a \" + noun + \". She has never seen anything like this before. What will she do? With the device between her teeth, she tries to \" + verb + \", but nothing happens. She takes it back to her family. When her family sees it, they quickly \" + verb2 + \". Soon, the device becomes \" + adjective + \", and the family decides to put it back where they found it.\"\n \n \n #the story is outputted to the welcome.html page\n return render_template(\"welcome.html\")\n\n\n\napp.run(debug=True, port=5000, host='0.0.0.0')\n\n","sub_path":"final/routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":1587,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"138153601","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n# Author : liufeng\n# Create : 2015/8/13 16:51\nimport time\n\nimport initconn, random\n\n\ndef initTopic():\n \"\"\"初始化话题表\"\"\"\n conn = initconn.getConn()\n cur = conn.cursor()\n\n for i in range(1, 101):\n value = [\n \"content\" + str(i),\n time.strftime(\"%Y-%m-%d %H:%M:%S\", time.localtime()),\n \"path\" + str(i),\n str(1),\n str(1),\n str(1),\n str(1),\n random.randint(1, 5),\n str(i)\n ]\n cur.execute(\n 'insert into topic(content,c_time,picpath,pv,lv,sv,state,type_id,create_userid)'\n ' values(%s,%s,%s,%s,%s,%s,%s,%s,%s)',\n value)\n conn.commit()\n cur.close()\n conn.close()\n\n\nif __name__ == '__main__':\n initTopic()\n","sub_path":"src/main/py/com/ezb/jdb/datainit/topic.py","file_name":"topic.py","file_ext":"py","file_size_in_byte":832,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"237395335","text":"'''\nCreated on Jun 23, 2011\n\n@author: oabalbin\n'''\n\n#import exome.variantEval.snps_annotator as ann\nfrom collections import defaultdict, deque\nfrom optparse import OptionParser\n\nfrom exome.jobs.base import JOB_SUCCESS, JOB_ERROR\nfrom exome.jobs.job_runner import qsub_cac, qsub_loc, run_local\nfrom exome.jobs.config import ExomePipelineConfig, ExomeAnalysisConfig\nfrom exome.variantEval.variant_intersector import variant_isec, SNPs_isec\nfrom exome.variantEval.snps_annotator import create_snps_annotation\n\n# Global Variables\nNODE_MEM=45000.0\nNODE_CORES=12\nSINGLE_CORE=1\nMEM_PER_CORE= int(float(NODE_MEM) / NODE_CORES)\n# wt=walltime\nWT_SHORT= \"24:00:00\"\nWT_LONG= \"60:00:00\" #\"100:00:00\"\n\n\ndef germline_analysis(configrun, analysis, snps_vcf, snps_annot_vcf,\n jobrunfunc, deps_list, do_dbSNP_isec=True):\n '''\n This function does a) intersect snps_vcf with dbSNP if isec=True\n Annotates the isec file.\n '''\n extra_mem = configrun.gatk_use_mem\n genomes = configrun.genomes['human']\n ref_genome, snpdb_vcf, indeldb_file = genomes.gatk_ref_genome, genomes.snpdb, \\\n genomes.indeldb\n hapmap_vcf, tgk_vcf = genomes.hapmap, genomes.OneKgenomes \n #vcfCodings parameters\n vcfCodSNP_genome = genomes.vcf_ref_genome\n annot_genelist = configrun.annot_genelist\n path_to_vcfCodSNPs = configrun.vcf_annot_path\n # email\n my_email=configrun.email_addresses\n # \n jobn=analysis.name \n # variant_isec(analysis, configrun, query_vcf_file, jobrunfunc, do_complement)\n snps_vcf_isec = snps_vcf.replace('.vcf','isec_known.vcf')\n snps_vcf_isec_annot= snps_vcf.replace('.vcf','.annot.vcf')\n\n do_complement=True \n jobidvcfh = variant_isec(analysis, configrun, snps_vcf, jobrunfunc, do_complement, snps_vcf_isec)\n\n commandA = create_snps_annotation(snps_vcf_isec, snps_vcf_isec_annot, \n snps_vcf_isec_annot, vcfCodSNP_genome, \n annot_genelist, path_to_vcfCodSNPs)\n \n jobidannA = jobrunfunc('germ.'+jobn, commandA, SINGLE_CORE, cwd=None, walltime=WT_SHORT, pmem=extra_mem, \n deps=jobidvcfh, stdout=None, email_addresses=my_email)\n \n return jobidannA\n \n\nif __name__ == '__main__':\n \n optionparser = OptionParser(\"usage: %prog [options] \")\n optionparser.add_option(\"-r\", \"--config_file\", dest=\"config_file\",\n help=\"file with run configuration\")\n optionparser.add_option(\"-a\", \"--analysis_file\", dest=\"analysis_file\",\n help=\"file with experiment configuration\") \n optionparser.add_option(\"-f\", \"--vcf_file\", dest=\"vcf_file\",\n help=\"file with experiment configuration\") \n \n optionparser.add_option(\"--local_cluster\", dest=\"local_cluster\", action=\"store_true\", default=False) \n optionparser.add_option(\"--local\", dest=\"local\", action=\"store_true\", default=False)\n optionparser.add_option(\"--cluster\", dest=\"cluster\", action=\"store_true\", default=False)\n optionparser.add_option(\"-p\", \"--processes\", type=int, dest=\"num_processors\", default=1)\n\n (options, args) = optionparser.parse_args() \n\n config = ExomePipelineConfig()\n config.from_xml(options.config_file)\n analysis = ExomeAnalysisConfig()\n analysis.from_xml(options.analysis_file, config.output_dir)\n #Default when called from the command line\n depends=None\n \n if not (options.local ^ options.cluster ^ options.local_cluster):\n optionparser.error(\"Must set either --local, --cluster or --local_cluster to run job\")\n if options.local:\n jobrunfunc = run_local\n elif options.cluster:\n jobrunfunc = qsub_cac\n elif options.local_cluster:\n jobrunfunc = qsub_loc\n \n \n germline_analysis(config, analysis, options.vcf_file, options.vcf_file.replace('.vcf','.annot.vcf'),\n jobrunfunc, depends, do_dbSNP_isec=True)\n \n\n","sub_path":"exome/trunk/exome/variantEval/germline_variants.py","file_name":"germline_variants.py","file_ext":"py","file_size_in_byte":3986,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"348983941","text":"\"\"\"\nCopyright [2009-2017] EMBL-European Bioinformatics Institute\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n http://www.apache.org/licenses/LICENSE-2.0\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\"\"\"\n\nfrom aiohttp_swagger import setup_swagger\nfrom .views import index, submit_job, job_status, job_result, job_done, rnacentral_databases, job_results_urs_list, \\\n facets, facets_search\nfrom . import settings\n\n\ndef setup_routes(app):\n app.router.add_post('/api/submit-job', submit_job, name='submit-job')\n app.router.add_get('/api/job-status/{job_id:\\d+}', job_status, name='job-status')\n app.router.add_get('/api/job-result/{job_id:\\d+}', job_result, name='job-result')\n app.router.add_post('/api/job-done', job_done, name='job-done')\n app.router.add_get('/api/rnacentral-databases', rnacentral_databases, name='rnacentral-databases')\n app.router.add_get('/api/job-results-urs-list/{job_id:\\d+}', job_results_urs_list, name='job-results-urs-list')\n app.router.add_get('/api/facets/{job_id:\\d+}', facets, name='facets')\n app.router.add_get('/api/facets-search/{job_id:\\d+}', facets_search, name='facets-search')\n setup_static_routes(app)\n\n # setup swagger documentation\n setup_swagger(app, swagger_url=\"api/doc\")\n\n # cover-all index url goes last, even after swagger\n app.router.add_get('/{tail:.*}', index, name='index')\n\n\ndef setup_static_routes(app):\n app.router.add_static('/dist/', path=settings.PROJECT_ROOT / 'static' / 'dist', name='static')\n","sub_path":"producer/producer/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1885,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"5637132","text":"#!/usr/bin/python\n#-*- coding: utf-8 -*-\n\nimport feedparser\nimport mysql.connector\nfrom datetime import datetime, timedelta\nimport sys\nreload(sys)\nsys.setdefaultencoding('utf-8')\n\ncnx = mysql.connector.connect(user='--', password='--',\n host='--',\n database='--',\n\t\t\t port = 3216)\ndbcursor = cnx.cursor()\n\nprint(\"parse google...\")\n\nd = feedparser.parse('https://www.google.com/trends/hottrends/atom/feed?pn=p23')\n\nindex = 0\n\nfor item in d['entries']:\n\tindex += 1\n\tpub_date = datetime.strptime(item['published'], '%a, %d %b %Y %H:%M:%S +0900')\n\tpub_date += timedelta(hours=6)\n\tpub_date_str = pub_date.strftime('%Y-%m-%d %H:%M:%S')\n\ttitle_str = item['title']\n\n\tadd_keyword = (\"INSERT INTO `TrendCrawler`.`TrendKeywordRank` \"\n\t\t\t\"( `site`, `keyword`, `rank`, `date`) VALUES (%s, \\\"\"\n\t\t\t+ title_str +\n\t\t\t\"\\\", %s, now())\")\n\tdata_keyword = ('google', index);\n\n\tdbcursor.execute(add_keyword, data_keyword)\n\ncnx.commit()\n\ndbcursor.close()\nprint(\"success\")\ncnx.close()\n","sub_path":"python/google.py","file_name":"google.py","file_ext":"py","file_size_in_byte":1023,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"212052923","text":"import time\n\nimport torch\nimport tqdm\nfrom sklearn.metrics import roc_auc_score\nfrom torch.utils.data import DataLoader\nfrom torch.utils.data import DataLoader\n\nfrom torchfm.dataset.avazu import AvazuDataset\nfrom torchfm.dataset.criteo import CriteoDataset\nfrom torchfm.dataset.movielens import MovieLens1MDataset, MovieLens20MDataset\n\n\ndef get_dataset(name, path):\n if name == 'movielens1M':\n return MovieLens1MDataset(path)\n elif name == 'movielens20M':\n return MovieLens20MDataset(path)\n elif name == 'criteo':\n return CriteoDataset(path, cache_path='.criteo_test')\n elif name == 'avazu':\n return AvazuDataset(path)\n else:\n raise ValueError('unknown dataset name: ' + name)\n\n\ndef load_model():\n save_path = '/home/eduapp/pytorch-fm/examples/model/dcn_20201103__12_37_51.pt'\n save_path = '/home/eduapp/pytorch-fm/examples/model/afn_20201103__14_00_39.pt'\n save_path = '/home/eduapp/pytorch-fm/examples/model/xdfm_20201103__17_19_23.pt'\n model = torch.load(save_path)#.to(device)\n # print(model.eval())\n print(model)\n return model\n\n\ndef test(model, data_loader, device):\n model.eval()\n targets, predicts = list(), list()\n result_list = []\n result_pred_true = [] # 预测为正的样本概率分布\n\n for fields, target in tqdm.tqdm(data_loader, smoothing=0, mininterval=1.0):\n fields, target = fields.to(device).long(), target.to(device).long()\n y = model(fields)\n targets.extend(target.tolist())\n predicts.extend(y.tolist())\n\n\n print('========pred result list save to file================')\n for i in range(len(targets)):\n result_list.append(str(targets[i]) + ',' + str(predicts[i]) + '\\n')\n # 预测为正的样本中,有多少实际为正的\n if predicts[i] >= 0.5:\n result_pred_true.append(str(targets[i]) + ', ' + str(predicts[i]) + '\\n')\n\n file = open('result_list.txt', \"w\")\n file.writelines(result_list)\n file.close()\n\n file = open('result_list_true.txt', \"w\")\n file.writelines(result_pred_true)\n file.close()\n\n\n from sklearn.metrics import classification_report\n arr = []\n for x in predicts:\n # print(x)\n arr.append(1) if x >= 0.5 else arr.append(0)\n\n print(classification_report(targets, arr))\n\n auc = roc_auc_score(targets, predicts)\n print('auc={}'.format(auc))\n\n\nif __name__ == '__main__':\n model = load_model()\n device = torch.device('cpu')\n dataset_path = '/home/eduapp/best_flow/release-1.1.0/train_data/202011/dnn_part_test.csv'\n\n t1 = time.time()\n dataset = get_dataset('criteo', dataset_path)\n train_length = 0\n valid_length = 0\n test_length = len(dataset) - train_length - valid_length\n train_dataset, valid_dataset, test_dataset = torch.utils.data.random_split(\n dataset, (train_length, valid_length, test_length))\n\n test_data_loader = DataLoader(test_dataset, batch_size=64, num_workers=0)\n print('dataset time={}'.format(time.time() - t1))\n test(model, test_data_loader, device)","sub_path":"examples/test_torch_load.py","file_name":"test_torch_load.py","file_ext":"py","file_size_in_byte":3067,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"547690247","text":"from django.views import generic\nfrom .forms import WebForm\nfrom django.shortcuts import render\nfrom django.conf import settings\nfrom .masternode import setupConnections,gatherTypoSquatSites\nfrom .workernode import start_worker\nimport signal\nimport time\nimport os\nimport re\nimport threading\n#from models import Post\n\n#change!\ndef HomeView(request):\n if request.method == 'GET':\n form = WebForm()\n return render(request, \"home.html\", {'form':form})\n# model = Post\n# context_object_name = \"post\"\n\ndef HTMLView(request):\n htmlname=request.GET.get('htmlname')\n htmlstr=\"\"\n title=\"\"\n num=htmlname.index('/')\n num+=1\n title=htmlname[(num+1):].replace(\"_\",\".\")\n\n pngstr=\"/data/\"+htmlname+\".png\"\n f=open(\"./data/\"+htmlname + \".html\")\n for lines in f:\n htmlstr+=lines\n f.close()\n return render(request,\"htmlpg.html\",{'htmlstr':htmlstr,'pngstr':pngstr,'title':title})\n\ninit = True\ndef ResultView(request):\n global init\n if request.method =='POST':\n form = WebForm(request.POST)\n if form.is_valid():\n print(\"Request Gotten!\")\n Input = form.data[\"weburl\"]\n if (Input.startswith(\"https://\")):\n Input = Input[len(\"https://\"):]\n if (Input.startswith(\"http://\")):\n Input = Input[len(\"http://\"):]\n # Execute Master + Worker Nodes Here\n # masternode setup -Nathan\n # signal.signal(signal.SIGINT, shutdown)\n if init:\n setupConnections()\n init = False\n if not os.path.isdir(\"./data/{}\".format(Input)):\n typoThread = threading.Thread(target = gatherTypoSquatSites, args = (Input,))\n typoThread.setDaemon(True)\n typoThread.start()\n #time.sleep(5)\n return render(request, \"result.html\", {'input':Input, 'MEDIA_URL':settings.MEDIA_URL})\n","sub_path":"typosquatted/typosquatted/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1918,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"267692170","text":"from django.shortcuts import render\nfrom joblib import load\n\n# Create your views here.\n\ndef index(req):\n model = load('./chat_group/static/chatgroup.model')\n label = ['']\n chat = \"\"\n if req.method == 'POST':\n print(\"POST IN\")\n chat = str(req.POST['chat'])\n label = model.predict([chat])\n return render(req, 'chat_group/index.html' ,{\n 'label':label[0],\n 'chat':chat,\n })\n\n","sub_path":"chat_group/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":426,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"310410170","text":"# Copyright (C) 2010 California Institute of Technology, All rights reserved\n# Author: Andrew D. Straw\nimport os\nimport cgtypes # cgkit 1.x\n\nfrom matplotlib import rcParams\n\nrcParams['svg.fonttype'] = 'none' # No text as paths. Assume font installed.\nrcParams['font.family'] = 'sans-serif'\nrcParams['font.sans-serif'] = ['Arial'] # lucid: ttf-mscorefonts-installer\n\nfont_size = 10\nrcParams['axes.labelsize'] = font_size\nrcParams['xtick.labelsize'] = font_size\nrcParams['ytick.labelsize'] = font_size\n\nimport fsee.Observer\nimport fsee.plot_utils\nimport numpy as np\n\nD2R = np.pi/180.0\n\n\nmodel_path=os.path.abspath('auto_scene_gen/expanding_wall.osg')\nvision = fsee.Observer.Observer(model_path=model_path,\n hz=200.0,\n full_spectrum=True,\n optics='buchner71',\n do_luminance_adaptation=False,\n skybox_basename=os.path.join(fsee.data_dir,'Images/osgviewer_cubemap/'),\n )\nif 1:\n angle = 30*D2R\n dist2 = -1.5\n dist3 = 0.5\n ext = 'svg'\n\n # view from fly position\n pos_vec3 = cgtypes.vec3(0,0,10.0)\n ori_quat = cgtypes.quat().fromAngleAxis( angle,(0,0,1))\n vision.step(pos_vec3,ori_quat)\n vision.save_last_environment_map('expanding_wall1.png')\n\n R=vision.get_last_retinal_imageR()\n G=vision.get_last_retinal_imageG()\n B=vision.get_last_retinal_imageB()\n #emds = vision.get_last_emd_outputs()\n fsee.plot_utils.plot_receptor_and_emd_fig(\n R=R,G=G,B=B,#emds=emds,\n save_fname='expanding_wall_flyeye1.%s'%ext,\n optics = vision.get_optics(),\n proj='stere',\n dpi=200)\n\n pos_vec3 = cgtypes.vec3(dist2*np.cos(angle),dist2*np.sin(angle),10.0)\n ori_quat = cgtypes.quat().fromAngleAxis( angle,(0,0,1))\n vision.step(pos_vec3,ori_quat)\n vision.save_last_environment_map('expanding_wall2.png')\n\n R=vision.get_last_retinal_imageR()\n G=vision.get_last_retinal_imageG()\n B=vision.get_last_retinal_imageB()\n #emds = vision.get_last_emd_outputs()\n fsee.plot_utils.plot_receptor_and_emd_fig(\n R=R,G=G,B=B,#emds=emds,\n save_fname='expanding_wall_flyeye2.%s'%ext,\n optics = vision.get_optics(),\n proj='stere',\n dpi=200)\n\n pos_vec3 = cgtypes.vec3(dist3*np.cos(angle),dist3*np.sin(angle),10.0)\n ori_quat = cgtypes.quat().fromAngleAxis( angle,(0,0,1))\n vision.step(pos_vec3,ori_quat)\n vision.save_last_environment_map('expanding_wall3.png')\n\n R=vision.get_last_retinal_imageR()\n G=vision.get_last_retinal_imageG()\n B=vision.get_last_retinal_imageB()\n #emds = vision.get_last_emd_outputs()\n fsee.plot_utils.plot_receptor_and_emd_fig(\n R=R,G=G,B=B,#emds=emds,\n save_fname='expanding_wall_flyeye3.%s'%ext,\n optics = vision.get_optics(),\n proj='stere',\n dpi=200)\n","sub_path":"examples/expanding_wall.py","file_name":"expanding_wall.py","file_ext":"py","file_size_in_byte":2913,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"170723598","text":"import unittest\nfrom selenium import webdriver\n\n\nclass BaseTestCase(unittest.TestCase):\n #_PLATFORM = 'LINUX'\n #_BROWSER = 'chrome'\n #_VERSION = 'VALLNX'\n URL = ''\n ENV = ''\n LNXRMT = {'browserName': 'chrome', 'version': 'VALLNX', 'platform': 'LINUX'}\n W7CHR = {'browserName': 'chrome', 'version': 'TESTSTAND2',\n 'platform': 'WIN7'}\n\n def setUp(self):\n if self.ENV == 'LINUX':\n des_cap = self.LNXRMT\n elif self.ENV == 'WIN7':\n des_cap = self.W7CHR\n else:\n des_cap = self.LNXRMT\n\n # create a new session\n # des_caps = {'browserName': self._BROWSER,\n # 'version': self._VERSION, 'platform': self._PLATFORM}\n\n self.driver = webdriver. \\\n Remote('http://msktool.rmcity.net:4444/wd/hub',\n desired_capabilities=des_cap)\n self.driver.implicitly_wait(10)\n self.driver.maximize_window()\n\n # navigate to the application home page\n self.driver.get(self.URL)\n\n def tearDown(self):\n # close the browser window\n self.driver.quit()\n","sub_path":"chapter_9/base/basetestcase.py","file_name":"basetestcase.py","file_ext":"py","file_size_in_byte":1120,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"148956583","text":"# https://atcoder.jp/contests/abc089/tasks/abc089_c\nimport sys\nsys.setrecursionlimit(2147483647)\nINF=float(\"inf\")\nMOD=10**9+7\ninput=lambda :sys.stdin.readline().rstrip()\ndef resolve():\n s=\"MARCH\"\n n=int(input())\n k=[0]*5\n for _ in range(n):\n t=input()[0]\n if t in s: k[s.index(t)]+=1\n from itertools import combinations\n A=combinations(range(5),3)\n ans=0\n for a,b,c in A:\n ans+=k[a]*k[b]*k[c]\n print(ans)\nresolve()\n","sub_path":"ABC089/c_march.py","file_name":"c_march.py","file_ext":"py","file_size_in_byte":463,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"18206139","text":"from urllib.parse import urljoin\n\nimport scrapy\nfrom scrapy.loader import ItemLoader\n\nfrom week02.work01.work01.items import Work01Item\n\n\nclass MaoyanSpider(scrapy.Spider):\n name = 'maoyan'\n allowed_domains = ['maoyan.com']\n headers = {\n 'accept': (\"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,\"\n \"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 'cache-control': \"no-cache\",\n 'connection': \"keep-alive\",\n 'host': \"maoyan.com\",\n 'sec-fetch-dest': \"document\",\n 'sec-fetch-mode': \"navigate\",\n 'sec-fetch-site': \"cross-site\",\n 'sec-fetch-user': \"?1\",\n 'referer': 'https://maoyan.com/films',\n 'upgrade-insecure-requests': \"1\",\n 'user-agent': (\"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_5) AppleWebKit/537.36 \"\n \"(KHTML, like Gecko) Chrome/84.0.4147.105 Safari/537.36\")\n }\n\n def start_requests(self):\n start_url = \"https://maoyan.com/films\"\n yield scrapy.Request(start_url, headers=self.headers)\n\n def parse(self, response, **kwargs):\n links = response.xpath(\n \"//div[@class='movie-item film-channel']//a[starts-with(@href, '/film')]/@href\").getall()\n if not links:\n self.logger.critical(\"未解析到链接,可能已触发反爬.\")\n links = links[:5] if len(links) >= 5 else links\n for link in links:\n yield scrapy.Request(\n urljoin(response.url, link), headers=self.headers, callback=self.parse_detail)\n\n def parse_detail(self, response):\n print(response.request.meta.get(\"proxy\"))\n selector = response.xpath(\"//div[@class='movie-brief-container']\")\n loader = ItemLoader(Work01Item(), selector=selector)\n loader.add_xpath(\"title\", \"./h1/text()\")\n loader.add_xpath(\"category\", \"./ul/li/a/text()\")\n loader.add_xpath(\"show_time\", \"./ul/li[3]/text()\")\n return loader.load_item()\n","sub_path":"week02/work01/work01/spiders/maoyan.py","file_name":"maoyan.py","file_ext":"py","file_size_in_byte":2083,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"648850339","text":"with open('log_init.template', 'r') as f:\n LOG_INIT = f.read()\n\nwith open('log_loop.template', 'r') as f:\n LOG_LOOP = f.read()\n\nwith open('init.template', 'r') as f:\n INIT = f.read()\n\nwith open('loop.template', 'r') as f:\n LOOP = f.read()\n\n\ndef make_log(name, log, obj):\n loop_part = LOG_LOOP.format(name=name, log=log, obj=obj)\n with open(f'../{name}_loop.mcfunction', 'w') as f:\n f.write(loop_part)\n\n init_part = LOG_INIT.format(name=name, log=log, obj=obj)\n with open(f'../{name}_init.mcfunction', 'w') as f:\n f.write(init_part)\n\n return name\n\n\ndef make(logs):\n init_calls = '\\n'.join(f'function timber:{log}_init' for log in logs)\n init_part = INIT.format(logs=init_calls)\n with open('../init.mcfunction', 'w') as f:\n f.write(init_part)\n\n loop_calls = '\\n'.join(f'function timber:{log}_loop' for log in logs)\n loop_part = LOOP.format(logs=loop_calls)\n with open('../loop.mcfunction', 'w') as f:\n f.write(loop_part)\n\n\ndef names(name):\n return name, f'minecraft:{name}_log', f'{name}_falling'\n\n\nmake([\n make_log(*names('oak')),\n make_log(*names('spruce')),\n make_log(*names('birch')),\n make_log(*names('jungle')),\n make_log(*names('acacia')),\n make_log(*names('dark_oak')),\n])\n","sub_path":"data/timber/functions/generate/generate.py","file_name":"generate.py","file_ext":"py","file_size_in_byte":1273,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"402404344","text":"# The first half is just boiler-plate stuff...\n\nimport pygame\n\nclass SceneBase:\n def __init__(self):\n self.next = self\n \n def ProcessInput(self, events, pressed_keys):\n print(\"uh-oh, you didn't override this in the child class\")\n\n def Update(self, seconds):\n print(\"uh-oh, you didn't override this in the child class\")\n\n def Render(self, screen):\n print(\"uh-oh, you didn't override this in the child class\")\n\n def SwitchToScene(self, next_scene):\n self.next = next_scene\n \n def Terminate(self):\n self.SwitchToScene(None)\n\ndef run_game(width, height, fps, starting_scene):\n pygame.init()\n screen = pygame.display.set_mode((width, height))\n clock = pygame.time.Clock()\n \n\n active_scene = starting_scene\n\n while active_scene != None:\n ms = clock.tick(fps)\n sec = ms / 1000\n\n pressed_keys = pygame.key.get_pressed()\n \n # Event filtering\n filtered_events = []\n for event in pygame.event.get():\n quit_attempt = False\n if event.type == pygame.QUIT:\n quit_attempt = True\n elif event.type == pygame.KEYDOWN:\n alt_pressed = pressed_keys[pygame.K_LALT] or \\\n pressed_keys[pygame.K_RALT]\n if event.key == pygame.K_ESCAPE:\n quit_attempt = True\n elif event.key == pygame.K_F4 and alt_pressed:\n quit_attempt = True\n \n if quit_attempt:\n active_scene.Terminate()\n else:\n filtered_events.append(event)\n \n active_scene.ProcessInput(filtered_events, pressed_keys)\n active_scene.Update(sec)\n active_scene.Render(screen)\n \n active_scene = active_scene.next\n \n pygame.display.flip()\n \n\n# The rest is code where you implement your game using the Scenes model\n\nclass TitleScene(SceneBase):\n def __init__(self):\n SceneBase.__init__(self)\n \n def ProcessInput(self, events, pressed_keys):\n for event in events:\n if event.type == pygame.KEYDOWN and event.key == pygame.K_RETURN:\n # Move to the next scene when the user pressed Enter\n self.SwitchToScene(GameScene())\n \n def Update(self, seconds):\n pass\n \n def Render(self, screen):\n # For the sake of brevity, the title scene is a blank red screen\n screen.fill((255, 0, 0))\n\nclass Tank:\n def __init__(self, originX, originY, width, height, speed):\n self.originX = originX\n self.originY = originY\n self.width = width\n self.height = height\n self.direction = 3\n #direction 1 - up, 2 - right, 3 - down, 4 - left, \n self.speed = speed\n \n def ChangeDirection(self, direction):\n self.direction = direction\n \n def UpdateLocation(self, seconds):\n if self.direction == 1:\n self.originY -= self.speed * seconds\n elif self.direction == 2:\n self.originX += self.speed * seconds\n elif self.direction == 3:\n self.originY += self.speed * seconds\n elif self.direction == 4:\n self.originX -= self.speed * seconds \n \n def GetRectangle(self):\n return (self.originX, self.originY, self.width, self.height)\n \n\n\nclass GameScene(SceneBase):\n def __init__(self):\n SceneBase.__init__(self)\n self.tank = Tank(20, 20, 50, 50, 10)\n\n def ProcessInput(self, events, pressed_keys):\n if pressed_keys[pygame.K_UP]: \n self.tank.ChangeDirection(1)\n elif pressed_keys[pygame.K_RIGHT]: \n self.tank.ChangeDirection(2)\n elif pressed_keys[pygame.K_DOWN]:\n self.tank.ChangeDirection(3)\n elif pressed_keys[pygame.K_LEFT]:\n self.tank.ChangeDirection(4)\n \n def Update(self, seconds):\n self.tank.UpdateLocation(seconds)\n \n def Render(self, screen):\n # The game scene is just a blank blue screen\n screen.fill((0, 0, 255))\n pygame.draw.rect(screen,(200, 255, 122), self.tank.GetRectangle())\n\n\nrun_game(400, 300, 60, TitleScene())","sub_path":"week11/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":4219,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"142949402","text":"import os\n\npath = 'c:\\\\Users\\\\kurs\\\\workspace'\n\nfiles = []\n# r=root, d=directories, f = files\nfor r, d, f in os.walk(path):\n for file in f:\n if '.py' in file and not \"policz.py\" in file:\n files.append(os.path.join(r, file))\nsuma=0\nfor f in files:\n linijki=0\n print(f)\n with open(f) as plik:\n for line in plik:\n linijki+=1\n print(f\"{f}\\t :{linijki}\")\n suma+=linijki\nprint(suma)\n","sub_path":"policz.py","file_name":"policz.py","file_ext":"py","file_size_in_byte":431,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"123360089","text":"from django.shortcuts import render, HttpResponseRedirect, get_object_or_404\nfrom django.urls import reverse, reverse_lazy\nfrom .models import Deck, Card, Comment\nimport requests\nfrom django.contrib.auth.models import User\nfrom django.views import generic\nfrom django.contrib.auth.forms import UserCreationForm\nfrom django.contrib.auth import authenticate\n\n\n# -------------------------------- MAH FUNCS\n\n# Name says it all\ndef gimme_card_data_by_id(card_id):\n response = requests.get('https://api.magicthegathering.io/v1/cards/%s' % card_id)\n card_data = response.json()\n return card_data['card'] # Bc its returning {\"card\":{...stuffiwant...}}\n\n\n# from card_id it adds card into DB & returns card\ndef create_card_return(card_id, deck_id):\n deck = get_object_or_404(Deck, pk=deck_id)\n c_data = gimme_card_data_by_id(card_id)\n\n card = Card(card_id=c_data['id'], name=c_data['name'], colors=None,\n type=c_data['type'], cmc=c_data['cmc'], rarity=c_data['rarity'], text=None,\n flavor=None, artist=c_data['artist'], imgUrl=c_data['imageUrl'],\n number=None, deck=deck)\n if 'text' in c_data:\n card.text = c_data['text']\n if 'colors' in c_data:\n card.colors = c_data['colors']\n if 'flavor' in c_data:\n card.flavor = c_data['flavor']\n if 'manaCost' in c_data:\n card.manaCost = c_data['manaCost']\n if 'number' in c_data:\n card.number = c_data['number']\n\n card.save()\n return card\n\n\n# -------------------------------- signup\nclass SignUp(generic.CreateView):\n form_class = UserCreationForm\n success_url = reverse_lazy('login')\n # for all generic class-based views the urls are not loaded when the file is imported, so we have to use the lazy\n # form of reverse to load them later when they’re available\n template_name = 'registration/signup.html'\n\n\n# -------------------------------- VIEWS\n# Main page\ndef index(request):\n return render(request, 'index.html')\n\n\n# def home(request):\n# return render(request, 'home.html')\n\n\n# Just leads to page with 'search card' field\ndef search(request):\n return render(request, 'search/index.html')\n\n\n# Cards found by 'q'\ndef result(request):\n q = request.POST['q']\n response = requests.get('https://api.magicthegathering.io/v1/cards?name=%s' % q)\n c_data = response.json()['cards']\n return render(request, 'search/result.html', {'q': q, 'cards_data': c_data})\n\n\n# Detail of card\ndef detail(request, card_id):\n c_data = gimme_card_data_by_id(card_id)\n img_url = 'http://gatherer.wizards.com/Handlers/Image.ashx?id=%s&type=card' % card_id\n return render(request, 'search/detail.html', {'card_data': c_data, 'url_img': img_url})\n\n\n# All decks\ndef decks(request):\n ds = Deck.objects.all()\n return render(request, 'deck/decks.html', {'decks': ds})\n\n\n# Detail of deck\ndef deck(request, deck_id):\n d = Deck.objects.get(id=deck_id)\n c = d.get_cards()\n userid = None\n if request.user.is_authenticated:\n userid = request.user.id\n comments = Comment.objects.filter(to_deck=deck_id)\n return render(request, 'deck/deck.html', {'deck': d, 'cards': c, 'userid': userid, 'comments': comments})\n\n\n# Leads to 'add card to existing deck' and sending card_id & all decks\ndef add_to_deck(request, card_id):\n decks = Deck.objects.all()\n userid = None\n if request.user.is_authenticated:\n userid = request.user.id\n return render(request, 'add_card/to_existing.html', {'card_id': card_id, 'decks': decks, 'userid': userid})\n\n\n# Saving the deck from 'add card to existing deck'\ndef add_to_deck_submit(request, card_id):\n deck_id = request.POST['deck_id']\n\n d = get_object_or_404(Deck, pk=deck_id)\n create_card_return(card_id, deck_id)\n d.save()\n\n return HttpResponseRedirect(reverse('builder:decks'))\n\n\n# Leads to 'add card to new deck' and sending card_id\ndef create_deck(request, card_id):\n players = User.objects.all()\n userid = None\n if request.user.is_authenticated:\n userid = request.user.id\n return render(request, 'add_card/to_new.html', {'card_id': card_id, 'players': players, 'userid': userid})\n\n\n# Saving the new deck from 'add card to new deck'\ndef create_deck_submit(request, card_id):\n p_id = request.POST['player_id']\n p = get_object_or_404(User, pk=p_id)\n d_name = request.POST['deck_name']\n d = Deck(deck_name=d_name, owner=p)\n d.save()\n create_card_return(card_id, d.id)\n return HttpResponseRedirect(reverse('builder:decks'))\n\n\ndef delete_deck(request, id):\n Deck.objects.filter(id=id).delete()\n return HttpResponseRedirect(reverse('builder:decks'))\n\n\ndef delete_card(request, id):\n Card.objects.filter(id=id).delete()\n return HttpResponseRedirect(reverse('builder:decks'))\n\n\ndef players(request):\n players = User.objects.all()\n return render(request, 'player/players.html', {'players': players})\n\n\ndef player(request, player_id):\n player = User.objects.get(pk=player_id)\n\n decks = Deck.objects.filter(owner=player_id)\n userid = None\n if request.user.is_authenticated:\n userid = request.user.id\n return render(request, 'player/player.html', {'player': player, 'decks': decks, 'userid': userid})\n\n\ndef new_comment(request, deck_id):\n userid = None\n if request.user.is_authenticated:\n userid = request.user.id\n return render(request, 'comment/new_comment.html', {'userid':userid, 'deck_id':deck_id})\n\n\ndef new_comment_submit(request, deck_id):\n text = request.POST['text']\n title = request.POST['title']\n deck = get_object_or_404(Deck, pk=deck_id)\n user = None\n if request.user.is_authenticated:\n user = request.user\n comment = Comment(title=title, text=text, author=user, to_deck=deck)\n comment.save()\n return HttpResponseRedirect(reverse('builder:index'))\n","sub_path":"builder/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5837,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"111946511","text":"# Copyright (C) 2013 Lindley Graham\n\n\"\"\"\nSee :class:`domain`\n\"\"\"\nimport subprocess, os\nimport numpy as np\nfrom scipy.interpolate import griddata\nfrom polyadcirc.pyADCIRC.basic import pickleable \nimport polyadcirc.pyADCIRC.prep_management as prep\nimport polyadcirc.pyADCIRC.fort15_management as f15\nimport polyadcirc.pyADCIRC.fort14_management as f14\nimport polyadcirc.pyADCIRC.fort13_management as f13\nimport polyadcirc.pyADCIRC.plotADCIRC as plot\n\nclass domain(pickleable):\n \"\"\"\n :class:`~polyadcirc.run_framework.domain` \n Objects of this class contain all the data needed by\n :class:`~polyadcirc.run_framework.random_manningsn`\n and :class:`~polyadcirc.pyADCIRC.plotADCIRC` for particular mesh(s) or\n grid(s)\n\n path\n full path to the directory containing the ``fort.##`` files for this\n particular mesh(s) or grid(s)\n node_num\n number of nodes\n element_num\n number of elements\n node\n list of nodes\n element\n list of elements where each element is a list of nodes\n manningsn_default\n default Manning's *n* value \n manningsn_num\n number of non-default nodes\n time\n instance of :class:`~polyadcirc.pyADCIRC.basic.time` class\n make_domain_map\n (bool) whether or not a domain map has been created\n\n \"\"\"\n def __init__(self, path, node_num=0, element_num=0, node=None,\n element=None):\n \"\"\"\n Initializatoin\n \"\"\"\n #: int, number of nodes\n self.node_num = node_num\n #: int, number of elements\n self.element_num = element_num\n if node or element:\n #: bool, whether or not a domain map has been created\n self.make_domain_map = False\n #: list, list of nodes\n self.node = node\n #: list, list of elements where each element is a list of nodes\n self.element = element\n else:\n self.make_domain_map = True\n self.node = dict()\n self.element = dict()\n #: string, full path to the dir containing the ``fort.##`` files\n self.path = path\n super(domain, self).__init__()\n\n def read_spatial_grid_header(self):\n \"\"\"\n Reads in spatial grid header from ``fort.14`` file in self.path\n\n See :meth:`polyadcirc.pyADCIRC.fort14_management.read_spatial_grid` \n \"\"\"\n f14.read_spatial_grid_header(self, self.path)\n\n def read_spatial_grid(self):\n \"\"\"\n Reads in spatial grid from ``fort.14`` file in self.path\n\n See :meth:`polyadcirc.pyADCIRC.fort14_management.read_spatial_grid` \n \"\"\"\n f14.read_spatial_grid(self, self.path)\n\n def read_recording_data(self):\n \"\"\"\n Reads in recording information from ``fort.15`` in self.path\n\n See :meth:`polyadcirc.pyADCIRC.fort15_management.read_recording_data`\n \"\"\"\n f15.read_recording_data(self, self.path)\n\n def update(self, path=None):\n \"\"\"\n Sets the directory containing files for this domain to self.path\n\n Reads in data from ``fort.14`` and ``fort.15`` files and updates self\n accordingly\n\n :type path: string or None\n :param path: directory containing ``fort.##`` files\n\n See :meth:`~polyadcirc.pyADCIRC.fort15_management.read_spatial_grid` \n See :meth:`~polyadcirc.pyADCIRC.fort15_management.read_recording_data` \n\n \"\"\"\n if path:\n self.path = path\n # Read in the fort.14 file\n self.read_spatial_grid() \n # Read in the fort.15 file\n self.read_recording_data()\n\n def make_node_to_element_map(self):\n \"\"\"\n Create the node to element map\n \"\"\"\n for k, v in self.node.iteritems():\n v.element = []\n for i, w in self.element.iteritems():\n if k in w:\n v.element.append(i)\n\n def array_bathymetry(self):\n \"\"\"\n \n :rtype: :class:`numpy.ndarray` of size(1, node_num)\n :returns: array containing the bathymetry at all nodes in numerical\n order\n\n \"\"\"\n bathymetry = np.array([node.bathymetry for node in self.node.values()])\n self.bathymetry = bathymetry\n return self.bathymetry\n \n def array_x(self):\n \"\"\"\n \n :rtype: :class:`numpy.ndarray` of size(1, node_num)\n :returns: array containing the x locations at all nodes in numerical\n order\n\n \"\"\"\n return np.array([node.x for node in self.node.values()]) \n \n def array_y(self):\n \"\"\"\n \n :rtype: :class:`numpy.ndarray` of size(1, node_num)\n :returns: array containing the y locations at all nodes in numerical\n order\n\n \"\"\"\n return np.array([node.y for node in self.node.values()])\n \n def array_manningsn(self):\n \"\"\"\n \n :rtype: :class:`numpy.ndarray` of size(1, node_num)\n :returns: array of containing the Manning's *n* value at all nodes in\n numerical order\n\n \"\"\"\n return np.array([node.manningsn for node in self.node.values()]) \n\n def dict_bathymetry(self):\n \"\"\"\n \n :rtype: :class:`dict`\n :returns: ``key`` -- node number, ``value`` -- bathymetry\n\n \"\"\"\n temp = dict()\n for k, node in self.node.iteritems():\n temp[k] = node.bathymetry\n return temp\n\n def dict_manningsn(self):\n \"\"\"\n \n :rtype: :class:`dict`\n :returns: ``key`` -- node number, ``value`` -- manningsn\n\n \"\"\"\n temp = dict()\n for k, node in self.node.iteritems():\n temp[k] = node.manningsn\n return temp\n\n def read_nodal_attr(self, path=None, file_name='fort.13'):\n \"\"\"\n Load in nodal attributes from a ``*.13`` file (only does Manning's *n*\n for now) and return a dictonary (like a MATLAB struct) with these\n attributes).\n\n :type path: string or None\n :param path: directory containing ``fort.13`` formatted file\n :param string file_name: ``fort.13`` formatted file name\n \n :returns: See :meth:`~polyadcirc.pyADCIRC.fort13_management.read_nodal_attr`\n\n \"\"\"\n if path is None:\n path = self.path\n return f13.read_nodal_attr(self, path, file_name)\n\n def read_default(self, path=None, file_name='fort.13'):\n \"\"\"\n Read in default nodal value from a ``*.13`` file\n\n :type path: string or None\n :param path: directory containing ``fort.13`` formatted file\n :param string file_name: ``fort.13`` formatted file name\n \n :returns: See :meth:`~polyadcirc.pyADCIRCfort13_management.read_default`\n\n \"\"\"\n if path is None:\n path = self.path\n return f13.read_default(self, path, file_name)\n\n def get_Triangulation(self, path=None, save=True, show=False, ext='.eps',\n ics=2):\n \"\"\"\n :type path: None or string\n :param string path: directory containing ``figs/`` folder\n :param bool save: flag\n :param bool show: flag\n \n :returns: See :meth:`~polyadcirc.pyADCIRC.plotADCIRC.get_Triangulation`\n\n \"\"\"\n return plot.get_Triangulation(self, path, save, show, ext=ext, ics=ics)\n\n def plot_bathymetry(self, path=None, save=True, show=False, ext='.eps',\n ics=2):\n \"\"\"\n :type path: None or string\n :param string path: directory containing ``figs/`` folder\n :param bool save: flag\n :param bool show: flag\n \n :returns: See :meth:`~polyadcirc.pyADCIRC.plotADCIRC.bathymetry`\n\n \"\"\"\n return plot.bathymetry(self, path, save, show, ext=ext, ics=ics)\n\n def plot_station_locations(self, path=None, bathymetry=False, \n save=True, show=False, ext='.eps',\n ics=2):\n \"\"\"\n :param string path: directory containing ``figs/`` folder\n :type bathymetry: bool\n :param bathymetry: flag whether or not to plot bathymetry in the\n background \n :param bool save: flag\n :param bool show: flag\n \n :returns: See :meth:`~polyadcirc.pyADCIRC.plotADCIRC.station_locations`\n\n \"\"\"\n return plot.station_locations(self, path, bathymetry, save, show,\n ext=ext, ics=ics)\n\n def adjust(self, x_lims=None, b_lims=None, path=None, plotb=False):\n \"\"\"\n Adds a bathymetry between x-locations defined by ``x_lims`` with\n bathymetry linearly interpolated between ``b_lims``\n\n :param list x_lims: [x_min, x_max]\n :param list b_lims: [b_min, b_max]\n :type path: string or None\n :param path: directory containing the ``fort.14`` to be adjusted\n\n \"\"\"\n if path is None:\n path = self.path\n if x_lims is None:\n x_lims = [0, 0]\n x_lims[0] = np.min(np.array([node.x for node in \\\n self.node.values()])) \n x_lims[1] = np.max(np.array([node.x for node in \\\n self.node.values()]))\n for n in self.node.values():\n n.bathymetry += adjust_factor(n.x, x_lims, b_lims)\n if plotb:\n self.plot_bathymetry(path)\n \n def add_wall(self, box_limits, wall_height=-2, path=None, plotb=False,\n save=False, show=False):\n \"\"\"\n\n Adds a land wall of default 2 m in area defined by ``box_limits``\n \n :param path: directory containing the ``fort.14`` to be adjusted\n :type path: string or None\n\t:param list box_limits: [xmin, xmax, ymin, ymax] \n\n \"\"\"\n if path is None:\n path = self.path\n for n in self.node.values():\n if box_limits[0] <= n.x <= box_limits[1]: \n if box_limits[2] <= n.y <= box_limits[3]:\n n.bathymetry = wall_height\n if plotb:\n self.plot_bathymetry(path, save, show)\n\n def set_station_bathymetry(self, key='fort61', method='linear'):\n #pylint: disable-msg=E1101\n \"\"\"\n Sets they bathymetry for all stations by interpolating w.r.t. the nodal\n locations\n\n :param string key: key for domain.stations[key]\n :param string method: linear interpolation method see\n :meth:`scipy.interpolate.griddata` \n\n \"\"\"\n points = np.array([[n.x, n.y] for n in self.node.itervalues()])\n station_locs = np.array([[s.x, s.y] for s in self.stations[key]])\n station_bath = griddata(points, self.array_bathymetry(), \n station_locs, method)\n for i, s in enumerate(self.stations[key]):\n s.bathymetry = station_bath[i]\n \n def run(self, num_procs, base_dir, input_dir=None, global_dir=None, \n write_option=None, num_writers=None, LorS=None, R=False):\n \"\"\"\n \n Preprocess and run ADCIRC on this domain\n\n .. seealso:: `Generic ADCIRC Command Line Options `_\n\n :param int num_procs: number of processors for this ADCIRC run\n :param string base_dir: directory containing the padcirc executables\n :param string input_dir: directory containing the input files\n :param string global_dir: directory to write fulldomain output files to\n :param string write_option: (optional) specifiy ``W`` or ``Ws`` flag\n :param int num_writers: number of MPI process to dedicate soley to the\n task of writing ascii files\n :param string LorS: (optional) specify ``L`` or ``S`` flag\n :param string R: (optional) specify ``R`` flag\n\n \"\"\"\n if base_dir is None:\n base_dir = self.path\n if input_dir is None:\n input_dir = self.path\n if global_dir is None:\n global_dir = self.path\n if not os.path.exists(os.path.join(self.path, 'adcprep')):\n os.symlink(os.path.join(base_dir, 'adcprep'),\n os.path.join(self.path, 'adcprep')) \n prep.write_1(self.path, num_procs)\n prep.write_2(self.path, num_procs)\n subprocess.call('./adcprep < in.prep1 > prep_o.txt', shell=True, \n cwd=self.path) \n subprocess.call('./adcprep < in.prep2 > prep_o.txt', shell=True, \n cwd=self.path) \n command = ['ibrun', 'padcirc', '-I', input_dir, '-O', global_dir]\n if LorS:\n command.append('-'+LorS)\n if R:\n command.append('-'+R)\n if write_option:\n command.append('-'+write_option)\n command.append(str(num_writers))\n subprocess.call(command, cwd=base_dir)\n \n def update_mann(self, data, path=None, default=None, file_name='fort.13'):\n \"\"\"\n Write out fort.13 to path with the attributes contained in Data. \n\n :type data: :class:`numpy.ndarray` or :class:`dict`\n :param data: containing the nodal attribute information\n :type path: string or None\n :param path: the directory to which the fort.13 file will be written\n :type default: None or float\n :param default: default value\n :type file_name: string\n :param file_name: the name of the ``fort.13`` formatted file\n\n \"\"\"\n f13.update_mann(data, path, default, file_name) \n\n def find_neighbors(self):\n \"\"\"\n Determine the neighbors of each of the nodes and store in\n ``self.node[#].neighbors`` as a ``set()``.\n \"\"\"\n for n in self.node.itervalues():\n n.neighbors = set()\n for e in self.element.itervalues():\n self.node[e[0]].neighbors.add(e[1])\n self.node[e[0]].neighbors.add(e[2])\n self.node[e[1]].neighbors.add(e[0])\n self.node[e[1]].neighbors.add(e[2])\n self.node[e[2]].neighbors.add(e[1])\n self.node[e[2]].neighbors.add(e[0])\n\ndef adjust_factor(x, x_lims, b_lims=None):\n \"\"\"\n :param float x: current x value\n :param float x_lims: box of x values to adjust\n :param float b_lims: bathy adj at x_lims\n :rtype: float\n :returns: b = bathy adjustment\n\n \"\"\"\n if b_lims is None:\n return 0\n if x < x_lims[0] or x > x_lims[1]:\n return 0\n else:\n value = b_lims[0]\n slope = (b_lims[1]-b_lims[0]) / (x_lims[1]-x_lims[0])\n value += (x-x_lims[0])*slope\n return value \n\n","sub_path":"polyadcirc/run_framework/domain.py","file_name":"domain.py","file_ext":"py","file_size_in_byte":14592,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"379862593","text":"from src.plugins import system, gtk, kvantum, wallpaper, firefox, vscode, atom\n\n# NOTE initialize your plugin over here:\n# The order in the list specifies the order in the config gui\nfrom src.plugins._plugin import Plugin\n\nplugins: [Plugin] = [\n system.System(),\n gtk.Gtk(),\n kvantum.Kvantum(),\n wallpaper.Wallpaper(),\n firefox.Firefox(),\n vscode.Vscode(),\n atom.Atom()\n]\n\n# this lets us skip all external plugins in yin_yang.py while keeping _plugin \"private\"\nExternalPlugin = _plugin.ExternalPlugin\n","sub_path":"src/plugins/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":522,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"210835417","text":"import pandas as pd\nfrom augmentations import get_4_augms_list, get_1_augms_list\n\nbatch_size = 8\nsegment_count = 8\nsnippet_length = 1 # Number of frames composing the snippet, 1 for RGB, 5 for optical flow\nsnippet_channels = 3 # Number of channels in a frame, 3 for RGB, 2 for optical flow\nheight, width = 224, 224\n\nrepo = 'epic-kitchens/action-models'\n\nclass_counts = (125, 352)\n\nframes_path_pattern = 'data/frames_a/*'\ntrained_models_dir = 'trained_models'\n\nnouns = pd.read_csv('data/EPIC_noun_classes.csv')\nverbs = pd.read_csv('data/EPIC_verb_classes.csv')\n\n\nbase_models = ['resnet50', 'BNInception']\nheads = ['TSN', 'TRN', 'MTRN', 'TSM']\ndevice = 'cuda'#'cpu' #'cuda'\n\nrandom_iters = 4\naugm_fn_list = get_4_augms_list()\n\n\n#fine tune params\nfine_tune_epochs=100\nfine_tune_lr=1e-4\nfine_tune_verbs=['take','put','move']\nfine_tune_val_split=0.2\nfine_tune_head='TRN'\nfine_tune_base='BNInception'\n","sub_path":"consts.py","file_name":"consts.py","file_ext":"py","file_size_in_byte":897,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"359868466","text":"from bpy.props import *\nfrom core import *\n\nclass BrushOptionsMenu(bpy.types.Menu):\n bl_label = \"Brush Options\"\n bl_idname = \"view3d.brush_options\"\n\n def draw(self, context):\n menu = Menu(self)\n\n if get_mode() == sculpt:\n self.sculpt(menu, context)\n\n elif get_mode() in [vertex_paint, weight_paint]:\n self.vw_paint(menu, context)\n\n elif get_mode() == texture_paint:\n self.texpaint(menu, context)\n\n else:\n self.particle(menu, context)\n\n def sculpt(self, menu, context):\n menu.add_item().menu(\"view3d.brushes_menu\")\n menu.add_item().menu(BrushRadiusMenu.bl_idname)\n menu.add_item().menu(BrushStrengthMenu.bl_idname)\n menu.add_item().menu(BrushAutosmoothMenu.bl_idname)\n menu.add_item().menu(BrushModeMenu.bl_idname)\n\n def vw_paint(self, menu, context):\n menu.add_item().menu(\"view3d.brushes_menu\")\n if get_mode() == weight_paint:\n menu.add_item().menu(BrushWeightMenu.bl_idname)\n menu.add_item().menu(BrushRadiusMenu.bl_idname)\n menu.add_item().menu(BrushStrengthMenu.bl_idname)\n menu.add_item().menu(BrushModeMenu.bl_idname)\n\n def texpaint(self, menu, context):\n menu.add_item().menu(\"view3d.brushes_menu\")\n menu.add_item().menu(BrushRadiusMenu.bl_idname)\n menu.add_item().menu(BrushStrengthMenu.bl_idname)\n menu.add_item().menu(BrushModeMenu.bl_idname)\n\n def particle(self, menu, context):\n menu.add_item().menu(\"view3d.brushes_menu\")\n menu.add_item().prop_menu_enum(bpy.context.tool_settings.particle_edit, \n \"tool\", text=\"Select Brush\")\n menu.add_item().menu(BrushRadiusMenu.bl_idname)\n menu.add_item().menu(BrushStrengthMenu.bl_idname)\n\n if context.tool_settings.particle_edit.tool == 'ADD':\n menu.add_item().separator()\n menu.add_item().prop(context.tool_settings.particle_edit, \n \"use_default_interpolate\", toggle=True)\n\n if context.tool_settings.particle_edit.use_default_interpolate:\n menu.add_item().prop(context.tool_settings.particle_edit.brush, \n \"steps\", slider=True)\n menu.add_item().prop(context.tool_settings.particle_edit, \n \"default_key_count\", slider=True)\n\n if context.tool_settings.particle_edit.tool == 'LENGTH':\n menu.add_item().separator()\n menu.add_item().prop(context.tool_settings.particle_edit.brush, \n \"length_mode\", text=\"\")\n\n if context.tool_settings.particle_edit.tool == 'PUFF':\n menu.add_item().separator()\n menu.add_item().prop(context.tool_settings.particle_edit.brush, \n \"puff_mode\", text=\"\")\n menu.add_item().prop(context.tool_settings.particle_edit.brush, \n \"use_puff_volume\", toggle=True)\n \nclass BrushRadiusMenu(bpy.types.Menu):\n bl_label = \"Radius\"\n bl_idname = \"view3d.brush_radius_menu\"\n\n def init(self, context):\n if get_mode() == particle_edit:\n settings = [[\"100\", 100], [\"70\", 70], [\"50\", 50],\n [\"30\", 30], [\"20\", 20], [\"10\", 10]]\n datapath = \"tool_settings.particle_edit.brush.size\"\n proppath = context.tool_settings.particle_edit.brush\n\n else:\n settings = [[\"200\", 200], [\"150\", 150], [\"100\", 100], \n [\"50\", 50], [\"35\", 35], [\"10\", 10]]\n datapath = \"tool_settings.unified_paint_settings.size\"\n proppath = context.tool_settings.unified_paint_settings\n\n return settings, datapath, proppath\n\n def draw(self, context):\n settings, datapath, proppath = self.init(context)\n menu = Menu(self)\n\n # add the top slider\n menu.add_item().prop(proppath, \"size\", slider=True)\n\n # add the rest of the menu items\n for i in range(len(settings)):\n menuprop(menu.add_item(), settings[i][0], settings[i][1],\n datapath, icon='RADIOBUT_OFF', disable=True, \n disable_icon='RADIOBUT_ON')\n\nclass BrushStrengthMenu(bpy.types.Menu):\n bl_label = \"Strength\"\n bl_idname = \"view3d.brush_strength_menu\"\n\n def init(self, context):\n settings = [[\"1.0\", 1.0], [\"0.7\", 0.7], [\"0.5\", 0.5],\n [\"0.3\", 0.3], [\"0.2\", 0.2], [\"0.1\", 0.1]]\n\n if get_mode() == sculpt:\n datapath = \"tool_settings.sculpt.brush.strength\"\n proppath = context.tool_settings.sculpt.brush\n\n elif get_mode() == vertex_paint:\n datapath = \"tool_settings.vertex_paint.brush.strength\"\n proppath = context.tool_settings.vertex_paint.brush\n\n elif get_mode() == weight_paint:\n datapath = \"tool_settings.weight_paint.brush.strength\"\n proppath = context.tool_settings.weight_paint.brush\n\n elif get_mode() == texture_paint:\n datapath = \"tool_settings.image_paint.brush.strength\"\n proppath = context.tool_settings.image_paint.brush\n\n else:\n datapath = \"tool_settings.particle_edit.brush.strength\"\n proppath = context.tool_settings.particle_edit.brush\n\n return settings, datapath, proppath\n\n def draw(self, context):\n settings, datapath, proppath = self.init(context)\n menu = Menu(self)\n\n # add the top slider\n menu.add_item().prop(proppath, \"strength\", slider=True)\n\n # add the rest of the menu items\n for i in range(len(settings)):\n menuprop(menu.add_item(), settings[i][0], settings[i][1],\n datapath, icon='RADIOBUT_OFF', disable=True, \n disable_icon='RADIOBUT_ON')\n\nclass BrushModeMenu(bpy.types.Menu):\n bl_label = \"Brush Mode\"\n bl_idname = \"view3d.brush_mode_menu\"\n\n def init(self):\n if get_mode() == sculpt:\n path = \"tool_settings.sculpt.brush.sculpt_plane\"\n brushmodes = [[\"Area Plane\", 'AREA'],\n [\"View Plane\", 'VIEW'],\n [\"X Plane\", 'X'],\n [\"Y Plane\", 'Y'],\n [\"Z Plane\", 'Z']]\n\n elif get_mode() == texture_paint:\n path = \"tool_settings.image_paint.brush.blend\"\n brushmodes = [[\"Mix\", 'MIX'],\n [\"Add\", 'ADD'],\n [\"Subtract\", 'SUB'],\n [\"Multiply\", 'MUL'],\n [\"Blur\", 'BLUR'],\n [\"Lighten\", 'LIGHTEN'],\n [\"Darken\", 'DARKEN'],\n [\"Erase Alpha\", 'ERASE_ALPHA'],\n [\"Add Alpha\", 'ADD_ALPHA']]\n\n else:\n path = \"tool_settings.vertex_paint.brush.vertex_tool\"\n brushmodes = [[\"Mix\", 'MIX'],\n [\"Add\", 'ADD'],\n [\"Subtract\", 'SUB'],\n [\"Multiply\", 'MUL'],\n [\"Blur\", 'BLUR'],\n [\"Lighten\", 'LIGHTEN'],\n [\"Darken\", 'DARKEN']]\n\n return path, brushmodes\n\n def draw(self, context):\n path, brushmodes = self.init()\n menu = Menu(self)\n\n # add all the brush modes to the menu\n for brush in brushmodes:\n menuprop(menu.add_item(), brush[0],\n brush[1], path, icon='RADIOBUT_OFF',\n disable=True, disable_icon='RADIOBUT_ON')\n\nclass BrushAutosmoothMenu(bpy.types.Menu):\n bl_label = \"Autosmooth\"\n bl_idname = \"view3d.brush_autosmooth_menu\"\n\n def init(self):\n settings = [[\"1.0\", 1.0], [\"0.7\", 0.7], [\"0.5\", 0.5], [\"0.3\", 0.3], [\"0.2\", 0.2],\n [\"0.1\", 0.1]]\n\n return settings\n\n def draw(self, context):\n settings = self.init()\n menu = Menu(self)\n\n # add the top slider\n menu.add_item().prop(context.tool_settings.sculpt.brush, \n \"auto_smooth_factor\", slider=True)\n\n # add the rest of the menu items\n for i in range(len(settings)):\n menuprop(menu.add_item(), settings[i][0], settings[i][1],\n \"tool_settings.sculpt.brush.auto_smooth_factor\",\n icon='RADIOBUT_OFF', disable=True,\n disable_icon='RADIOBUT_ON')\n \nclass BrushWeightMenu(bpy.types.Menu):\n bl_label = \"Weight\"\n bl_idname = \"view3d.brush_weight_menu\"\n\n def draw(self, context):\n menu = Menu(self)\n settings = [[\"1.0\", 1.0], [\"0.7\", 0.7],\n [\"0.5\", 0.5], [\"0.3\", 0.3],\n [\"0.2\", 0.2], [\"0.1\", 0.1]]\n\n # add the top slider\n menu.add_item().prop(context.tool_settings.unified_paint_settings,\n \"weight\", slider=True)\n\n # add the rest of the menu items\n for i in range(len(settings)):\n menuprop(menu.add_item(), settings[i][0], settings[i][1],\n \"tool_settings.unified_paint_settings.weight\",\n icon='RADIOBUT_OFF', disable=True,\n disable_icon='RADIOBUT_ON')\n \nclass ParticleLengthMenu(bpy.types.Menu):\n bl_label = \"Length Mode\"\n bl_idname = \"view3d.particle_length_menu\"\n\n def draw(self, context):\n menu = Menu(self)\n datapath = \"tool_settings.particle_edit.brush.length_mode\"\n\n # add the menu items\n menuprop(menu.add_item(), \"Grow\", \"GROW\",\n datapath, icon='RADIOBUT_OFF', \n disable=True, disable_icon='RADIOBUT_ON')\n \n menuprop(menu.add_item(), \"Shrink\", \"SHRINK\",\n datapath, icon='RADIOBUT_OFF', \n disable=True, disable_icon='RADIOBUT_ON')\n \nclass ParticlePuffMenu(bpy.types.Menu):\n bl_label = \"Puff Mode\"\n bl_idname = \"view3d.particle_puff_menu\"\n\n def draw(self, context):\n menu = Menu(self)\n datapath = \"tool_settings.particle_edit.brush.puff_mode\"\n\n # add the menu items\n menuprop(menu.add_item(), \"Add\", \"ADD\",\n datapath, icon='RADIOBUT_OFF', \n disable=True, disable_icon='RADIOBUT_ON')\n \n menuprop(menu.add_item(), \"Sub\", \"SUB\",\n datapath, icon='RADIOBUT_OFF', \n disable=True, disable_icon='RADIOBUT_ON')\n\ndef register():\n # register all classes in the file\n bpy.utils.register_module(__name__)\n\ndef unregister():\n # unregister all classes in the file\n bpy.utils.unregister_module(__name__)\n \nif __name__ == \"__main__\":\n register()\n","sub_path":"addons/advanced_ui_menus/brush_options.py","file_name":"brush_options.py","file_ext":"py","file_size_in_byte":11365,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"364713130","text":"# -*- coding: utf-8 -*-\n# @Time : 2020/11/4 08:14\n# @Author : 饭盆里\n# @File : app.py\n# @Software: PyCharm\n# @desc :\nfrom appium import webdriver\nfrom myappium.qiyeweixin.framework_basepage.basepage.basepage import BasePage\nfrom myappium.qiyeweixin.framework_basepage.pages.main_page import MainPage\n\nclass App(BasePage):\n \"\"\"\n APP相关动作,比如启动app,关闭APP 停止APP,进入首页\n \"\"\"\n def start(self):\n \"\"\"\n 启动APP\n :return:\n \"\"\"\n if self.driver == None:\n #第一次调用start()方法时,driver为None\n desire_caps = {\n \"platformName\": \"android\",\n \"appPackage\": \"com.tencent.wework\",\n \"appActivity\": \".launch.WwMainActivity\",\n \"deviceName\": \"emulator-5554\",\n \"noReset\": \"true\",\n 'skipServerInstallation': 'true', # 跳过 uiautomator2 server的安装\n 'skipDeviceInitialization': 'true', # 跳过设备初始化\n 'settings[waitForIdleTimeout]': 0, # 等待Idle为0\n 'dontStopAppOnReset': 'true' # 不关闭,重启APP,首次启动后不再重启\n }\n\n # 与server建立连接,初始化一个driver,创建session\n self.driver = webdriver.Remote('http://127.0.0.1:4723/wd/hub', desire_caps)\n else:\n #launch_app() 这个方法不需要传入任何参数, 会自动启动起来DesireCapa里面定义的activity\n # start_activity(packagename, activityname) 可以启动其它的应用的页面\n self.driver.launch_app()\n\n self.driver.implicitly_wait(10)\n\n return self\n\n def restart(self):\n \"\"\"\n 重启APP\n :return:\n \"\"\"\n self.driver.close()\n self.driver.launch_app()\n return self\n\n def stop(self):\n \"\"\"\n 停止APP\n :return:\n \"\"\"\n self.driver.quit()\n\n def goto_main(self):\n \"\"\"\n 进入主页面\n :return:\n \"\"\"\n return MainPage(self.driver)","sub_path":"myappium/qiyeweixin/framework_basepage/basepage/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2100,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"3627853","text":"#!/usr/bin/python\nimport RPi.GPIO as gpio\nimport time\nimport math\nimport progressbar\nimport requests\nimport json\n\ngpio.setmode(gpio.BOARD)\ngpio.setwarnings(False)\ne=2.71828 #mathematical constant\ngpio_up_voltage = 1.34 #from RPI specifications\n\n# this captures the hardware configuration at soil moisture setup\npin_soilmoist =13 #gpio pin that is tuned to the signal\nkohms_soilmoist =9.89 #resistance that charges the capacitpor\nuF_soilmoist=2.2 #the capacitance that needs to be charged\nwet_milivolts=2061.00\ndry_milivolts=2152.00\n\n# this captures the hardware configuration at the light intensity\npin_ldr = 15\nkohms_ldr=9.89\nuF=2.2\n#this setting can be checked changed for the measurements we set on the trim pot\ndark_voltage =1.34\nbright_voltage=1.95\n\n#this setting of the hardware is for the atm temp measurement\nopamp_gain=5.84\n\nclass ExceptionNoSignal(Exception):\n \"\"\"docstring for ExcepNoSignal.\n this is raised when the GPIO fails to get any signal from the sensor BOARD\n The code waited too long for the GPIO to go up and there was no signal\"\"\"\n def __init__(self, message):\n super(ExceptionNoSignal, self).__init__(message)\nclass ExceptionInvalidRC(object):\n \"\"\"docstring for ExceptionInvalidRC.\n this is the exception when the measured rc time value from the setup is not valid\"\"\"\n def __init__(self, message):\n super(ExceptionInvalidRC, self).__init__(message)\ndef showbar(max, value, progchar):\n disp_value=0\n if isinstance(value, float):\n # we need to get this to an integer\n disp_value = int(value)\n elif isinstance(value, int):\n disp_value = value\n else:\n raise ValueError('Value to be displahyed should be numerical')\n\n display = ' '*10\n display=display.replace(' ',progchar, int(value*10/max))\n print('[{}] {}%'.format(display, round(value*100/max,2)))\ndef reset_gpio(pin,drain_delay=0.015,drain_pin=None):\n '''This functions lets you reset the pins for RC timer setup on GPIO\n pin : this is the BOARD pin number that receives the high signal\n drain_pin : this is the BOARD pin on which the capacitor is used for draining\n we are assigning a default value to drain_delay , you would have to change it corresponding to rc_constant\n if the drain pin is not supplied then draining and signal receiving happens on the same pin\n '''\n if drain_pin is None:\n gpio.setup(pin, gpio.OUT)\n gpio.output(pin,gpio.LOW)\n time.sleep(drain_delay)\n gpio.setup(pin, gpio.IN, pull_up_down=gpio.PUD_DOWN)\n time.sleep(0.005)\n else:\n gpio.setup(drain_pin, gpio.OUT)\n gpio.output(drain_pin,gpio.LOW)\n time.sleep(drain_delay)\n gpio.setup(drain_pin, gpio.IN, pull_up_down=gpio.PUD_DOWN)\n gpio.setup(pin, gpio.IN, pull_up_down=gpio.PUD_DOWN)\n time.sleep(0.005) #letting the setup assimilate , the pins need time to change function\ndef voltage(pin,kohms,uF, drain_pin=None):\n '''This is to measure the voltage from the rctime but with no operational amplifier\n The setup uses only one GPIO pin and the sensor connected to the rctiming\n '''\n #in seconds .. effectively that is the time it needs to charge and discharge\n rc_constant = kohms*uF/1000\n #a check for the invalida parameters\n if rc_constant <=0 :\n raise ValueError('ERR_PARAM: Invalid values for resistance or capacitance.')\n reset_gpio(pin=pin, drain_delay=4*rc_constant, drain_pin=drain_pin)\n starttime = time.time()\n #so that the end time is never less than the starttime\n endtime =starttime\n while gpio.input(pin) ==gpio.LOW:\n endtime = time.time()\n if endtime-starttime > 5:\n raise ExceptionNoSignal(message='Waited too long for the signal to go high')\n # this happens in the case when the signal is just too weak for raspberry pi\n # or if the is an open connection between the RC setup and the GPIO\n charge_time = endtime-starttime\n if charge_time > 0.0 :\n # this is when we know everything is ok .. and we have the rctime\n time_factor = charge_time/rc_constant\n supply=gpio_up_voltage /(1-(math.pow(e,-time_factor)))\n # and thus we have the supply voltage\n return (supply) #gpio in low voltage is 0.2 approx,\n else:\n reset_gpio(pin=pin, drain_delay=4*rc_constant)\n raise ExceptionInvalidRC('RCtime calculations have failed, we are getting negative time')\ndef soil_moisture():\n '''this is to get the soil moisture using the RC timer to convert ADC'''\n try:\n volts = voltage(pin=pin_soilmoist, kohms=kohms_soilmoist, uF=uF_soilmoist)\n volts *=1000 #converting to millivolts\n if not volts is None:\n if volts < wet_milivolts:\n moisture=1.00\n elif volts > dry_milivolts:\n moisture=0.0\n else:\n moisture =1- ((volts-wet_milivolts)/(dry_milivolts-wet_milivolts))\n moisture *=100\n return moisture\n except ExceptionNoSignal as nosig:\n return -1.00 #this is to indicate that the signal too low for reading\n except ValueError as ve:\n print('ERR: Check values for the resistor and the capacitor')\n pass\ndef luminosity():\n '''this is to get the light intensity from the LDR voltage reding'''\n try:\n volts = voltage(pin=pin_ldr, kohms=kohms_ldr, uF=uF)\n #first we try to get the voltage within the boundaries\n if volts <= dark_voltage:\n brightness=0\n elif volts >=bright_voltage:\n brightness=1.00\n else:\n #this where we calculate the inbetweenness\n brightness=(volts-dark_voltage) /(bright_voltage-dark_voltage)\n #% of brightness sent back in accuracy 2 decimals\n return round(brightness*100,2)\n except ExceptionNoSignal as nosig:\n return -1.00 #this is to indicate that the signal too low for reading\n except ValueError as ve:\n print('ERR: Check values for the resistor and the capacitor')\n pass\ndef atmtemp():\n '''This is to measure the air temp at the given time'''\n try:\n volts = voltage(pin=11, kohms=0.98,uF=10,drain_pin=12)\n return round((volts/opamp_gain)*100, 2) #is the straight temp reading that we are looking for\n except Exception as e:\n print(str(e))\n return -1.0\n\nclass ErrorReading(object):\n \"\"\"This stores the errorenous readings from each of the sensors\n msg : The error message from the reading activity\n typ : The type of the error that was raised\n erron : The error on specific implementation of the RCTimer class.\"\"\"\n def __init__(self, msg, typ, erron):\n super(ErrorReading, self).__init__()\n self.message = msg\n self.type = typ\n self.erroron=erron\nclass RCTimer(object):\n \"\"\"docstring for RCTimer.\"\"\"\n def __init__(self, pin, uF, kohms,drain):\n super(RCTimer, self).__init__()\n #setting up the rctimer\n self.pin = pin\n self.drain = drain\n #hardware configuration\n self.uF = uF\n self.kohms = kohms\n self.rc_constant = self.kohms*self.uF/1000\n self.drain_delay = 4*self.rc_constant\n #is the time in seconds we have to delay before the gpio pin can fully change function\n self.pinfnchange_wait = 0.0065\n def measure(self):\n #in seconds .. effectively that is the time it needs to charge and discharge\n self.rc_constant = float(self.kohms)*float(self.uF)/1000\n #a check for the invalida parameters\n if self.rc_constant <=0 :\n raise ValueError('ERR_PARAM: Invalid values for resistance or capacitance.')\n self.reset_gpio()\n starttime = time.time()\n #so that the end time is never less than the starttime\n endtime =starttime\n while gpio.input(self.pin) ==gpio.LOW:\n endtime = time.time()\n if endtime-starttime > 5:\n raise ExceptionNoSignal(message='Waited too long for the signal to go high')\n # this happens in the case when the signal is just too weak for raspberry pi\n # or if the is an open connection between the RC setup and the GPIO\n charge_time = endtime-starttime\n if charge_time > 0.0 :\n # this is when we know everything is ok .. and we have the rctime\n time_factor = float(charge_time)/float(self.rc_constant)\n # print(time_factor)\n supply=gpio_up_voltage /(1-(math.pow(e,-float(time_factor))))\n # and thus we have the supply voltage\n return (supply) #gpio in low voltage is 0.2 approx,\n else:\n self.reset_gpio()\n raise ExceptionInvalidRC('RCtime calculations have failed, we are getting negative time')\n def reset_gpio(self):\n if self.drain is None:\n gpio.setup(self.pin, gpio.OUT)\n gpio.output(self.pin,gpio.LOW)\n time.sleep(self.drain_delay)\n gpio.setup(self.pin, gpio.IN, pull_up_down=gpio.PUD_DOWN)\n time.sleep(self.pinfnchange_wait)\n else:\n gpio.setup(self.drain, gpio.OUT)\n gpio.output(self.drain,gpio.LOW)\n time.sleep(self.drain_delay)\n gpio.setup(self.drain, gpio.IN, pull_up_down=gpio.PUD_DOWN)\n gpio.setup(self.pin, gpio.IN, pull_up_down=gpio.PUD_DOWN)\n time.sleep(self.pinfnchange_wait)\nclass SoilMoistureRCTimer(RCTimer):\n \"\"\"docstring for SoilMoistureRCTimer.\"\"\"\n def __init__(self, pin,uF, kohms):\n super(SoilMoistureRCTimer, self).__init__(pin, uF, kohms, None)\n #this is the configuration when we look at extereme soil conditions.\n #if you need to change this you need to calibrate this timer\n self.wet_milivolts=2035.00\n self.dry_milivolts=2100.00\n def measure(self):\n try:\n volts = super(SoilMoistureRCTimer, self).measure() #getting the RCtimer to work for us\n volts *=1000 # we need in millivolts\n dryness = (volts - self.wet_milivolts )/(self.dry_milivolts-self.wet_milivolts)\n #now checking for the inbetweenness for the boundaries\n if dryness < 0.0:\n wetness =0.0\n elif dryness > 1.0:\n dryness = 1.0\n wetness = 1-dryness\n return round(wetness, 2)*100\n except ValueError as ve:\n return ErrorReading(msg=str(ve), typ=type(ValueError), erron=type(SoilMoistureRCTimer))\n except ExceptionNoSignal as nosig:\n return ErrorReading(msg=str(nosig), typ=type(ExceptionNoSignal), erron=type(SoilMoistureRCTimer))\n except ExceptionInvalidRC as invalrc:\n return ErrorReading(msg=str(invalrc), typ=type(ExceptionInvalidRC), erron=type(SoilMoistureRCTimer))\n finally:\n self.reset_gpio()\nclass LuminosityRCTimer(RCTimer):\n \"\"\"docstring for LuminosityRCTimer.\"\"\"\n def __init__(self, pin, uF, kohms):\n super(LuminosityRCTimer, self).__init__(pin = pin, uF= uF, kohms=kohms, drain= None)\n #this is from the empirical multimeter calculations that I have done\n self.dark_voltage =1.34\n self.bright_voltage=1.95\n def measure(self):\n \"\"\"This calls for the overriding of the method from RCtimer.\n \"\"\"\n try:\n volts = super(LuminosityRCTimer, self).measure()\n if volts < self.dark_voltage:\n volts = dark_voltage\n elif volts >self.bright_voltage:\n volts=self.bright_voltage\n brightness = (volts-self.dark_voltage)/(self.bright_voltage-self.dark_voltage)\n return round(brightness*100, 2)\n except ValueError as ve:\n return ErrorReading(msg=str(ve), typ=type(ValueError), erron=type(LuminosityRCTimer))\n except ExceptionNoSignal as nosig:\n return ErrorReading(msg=str(nosig), typ=type(ExceptionNoSignal), erron=type(LuminosityRCTimer))\n except ExceptionInvalidRC as invalrc:\n return ErrorReading(msg=str(invalrc), typ=type(ExceptionInvalidRC), erron=type(LuminosityRCTimer))\n finally :\n self.reset_gpio()\nclass AirTempRCTimer(RCTimer):\n \"\"\"docstring for AirTempRCTimer.\"\"\"\n def __init__(self, pin, uF, kohms, drain, gain):\n super(AirTempRCTimer, self).__init__(pin = pin, uF= uF, kohms=kohms, drain= drain)\n self.gain= gain\n def measure(self):\n try:\n volts = super(AirTempRCTimer, self).measure()\n # volts measured is amplified fromt he opamp and thus the same has to be reduced to know the supply\n # LM35 has a gain of 10 mV/oC and hence multiplying the value wih 100 makes sense\n return round((volts/self.gain)*100, 2)\n except ValueError as ve:\n return ErrorReading(msg=str(ve), typ=type(ValueError), erron=type(AirTempRCTimer))\n except ExceptionNoSignal as nosig:\n return ErrorReading(msg=str(nosig), typ=type(ExceptionNoSignal), erron=type(AirTempRCTimer))\n except ExceptionInvalidRC as invalrc:\n return ErrorReading(msg=str(invalrc), typ=type(ExceptionInvalidRC), erron=type(AirTempRCTimer))\n finally :\n self.reset_gpio()\n\n\nprint('Time \\t\\t\\t Soil \\t\\t Light \\t\\t Temp')\nwhile True:\n # timer = RCTimer(pin=pin_soilmoist, kohms=kohms_soilmoist, uF=uF_soilmoist, drain=None)\n timer = SoilMoistureRCTimer(pin=13, uF=2.2, kohms=9.89)\n soilmoisture=timer.measure()\n timer.reset_gpio()\n timer = LuminosityRCTimer(pin=15, uF=2.2, kohms= 9.89)\n luminosity = timer.measure()\n timer.reset_gpio()\n timer = AirTempRCTimer(pin=11, uF=10.00, kohms= 0.963, drain=12,gain=6.8)\n temp=timer.measure()\n timer.reset_gpio()\n toupload = {}\n if not isinstance(soilmoisture, ErrorReading):\n toupload['soil']=soilmoisture\n else:\n toupload['soil']='ERR'\n if not isinstance(luminosity, ErrorReading):\n toupload['light']=luminosity\n else:\n toupload['light']='ERR'\n if not isinstance(temp, ErrorReading):\n toupload['temp']=temp\n else:\n toupload['temp']='ERR'\n toupload['time']=time.time()\n toupload['node']='A51BB952-FF52-45D0-AC76-A670DC3474FA'\n # for now atleast we go ahead to print this on the console\n try :\n # we try uploading the data to the server , if that fails then we can go ahead to display\n url='http://128.199.172.125:8080/irrigation/soilconditions/A51BB952-FF52-45D0-AC76-A670DC3474FA/'\n response=requests.post('http://somenonsense', data=json.dumps(toupload))\n if response.status_code != 200:\n raise Exception('Failed to upload to server')\n else:\n print('data uploaded to server ...')\n except Exception as e:\n tm_stamp = time.localtime(toupload['time'])\n tm_stamp_format= '{}/{}/{} {}:{}'.format(tm_stamp.tm_year, tm_stamp.tm_mon, tm_stamp.tm_mday, tm_stamp.tm_hour, tm_stamp.tm_min)\n print('{}\\t {}\\t {}\\t\\t {}'.format(tm_stamp_format,toupload['soil'],toupload['light'],toupload['temp']))\n finally:\n time.sleep(5)\n# print('Soil moisture(%)')\n# print('------------')\n# while True:\n# #volts =measure_voltage(read_pin=15,drain_pin=12, rc_const=0.001, opamp_gain=1.34,interval=3)\n# # volts =measure_voltage(read_pin=13,drain_pin=11, rc_const=0.001, opamp_gain=5.67,interval=4)\n# moist = soil_moisture()\n# if not moist is None:\n# if moist <=0.0:\n# moist =0.0\n# showbar(100, moist, '=')\n# time.sleep(3)\n\n# print('Light (%)')\n# print('------------')\n# while True:\n# #volts =measure_voltage(read_pin=15,drain_pin=12, rc_const=0.001, opamp_gain=1.34,interval=3)\n# # volts =measure_voltage(read_pin=13,drain_pin=11, rc_const=0.001, opamp_gain=5.67,interval=4)\n# light = luminosity()\n# if not light is None:\n# if light <=0.0:\n# light =0.0\n# showbar(100, light, '=')\n# time.sleep(3)\n","sub_path":"device/rctime.py","file_name":"rctime.py","file_ext":"py","file_size_in_byte":16038,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"6764140","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Feb 12 09:55:18 2020\n\n@author: Jovic\n\"\"\"\nimport numpy as np\n\nfrom tqdm import trange\nfrom itertools import islice\n\nclass BPRAlgorithm:\n\n def __init__(self, learning_rate = 0.01, n_factors = 15, n_iters = 10, \n batch_size = 1000, reg = 0.01, df=None, seed = 1234, verbose = True):\n self.reg = reg\n self.seed = seed\n self.verbose = verbose\n self.n_iters = n_iters\n self.n_factors = n_factors\n self.batch_size = batch_size\n self.learning_rate = learning_rate\n \n self.df = df\n self._prediction = None\n \n \n def fit(self, ratings):\n np.random.seed(0)\n \n indptr = ratings.indptr\n indices = ratings.indices\n n_users, n_items = ratings.shape\n\n batch_size = self.batch_size\n if n_users < batch_size:\n batch_size = n_users\n\n batch_iters = n_users // batch_size\n \n rstate = np.random.RandomState(self.seed)\n self.user_factors = rstate.normal(size = (n_users, self.n_factors))\n self.item_factors = rstate.normal(size = (n_items, self.n_factors))\n \n loop = range(self.n_iters)\n if self.verbose:\n loop = trange(self.n_iters, desc = self.__class__.__name__)\n \n for _ in loop:\n for _ in range(batch_iters):\n sampled = self._sample(n_users, n_items, indices, indptr)\n sampled_users, sampled_pos_items, sampled_neg_items = sampled\n self._update(sampled_users, sampled_pos_items, sampled_neg_items)\n\n return self\n \n def _sample(self, n_users, n_items, indices, indptr):\n sampled_pos_items = np.zeros(self.batch_size, dtype = np.int)\n sampled_neg_items = np.zeros(self.batch_size, dtype = np.int)\n sampled_users = np.random.choice(\n n_users, size = self.batch_size, replace = False)\n\n for idx, user in enumerate(sampled_users):\n pos_items = indices[indptr[user]:indptr[user + 1]]\n pos_item = np.random.choice(pos_items)\n neg_item = np.random.choice(n_items)\n while neg_item in pos_items:\n neg_item = np.random.choice(n_items)\n\n sampled_pos_items[idx] = pos_item\n sampled_neg_items[idx] = neg_item\n\n return sampled_users, sampled_pos_items, sampled_neg_items\n \n def _update(self, u, i, j):\n\n user_u = self.user_factors[u]\n item_i = self.item_factors[i]\n item_j = self.item_factors[j]\n \n r_uij = np.sum(user_u * (item_i - item_j), axis = 1)\n sigmoid = np.exp(-r_uij) / (1.0 + np.exp(-r_uij))\n \n sigmoid_tiled = np.tile(sigmoid, (self.n_factors, 1)).T\n\n grad_u = sigmoid_tiled * (item_j - item_i) + self.reg * user_u\n grad_i = sigmoid_tiled * -user_u + self.reg * item_i\n grad_j = sigmoid_tiled * user_u + self.reg * item_j\n self.user_factors[u] -= self.learning_rate * grad_u\n self.item_factors[i] -= self.learning_rate * grad_i\n self.item_factors[j] -= self.learning_rate * grad_j\n return self\n \n def predict(self):\n \n if self._prediction is None:\n self._prediction = self.user_factors.dot(self.item_factors.T)\n\n return self._prediction\n\n def _predict_user(self, user):\n\n user_pred = self.user_factors[user].dot(self.item_factors.T)\n return user_pred\n\n def recommend(self, ratings, N = 10, excluded=None): \n n_users = ratings.shape[0]\n recommendation = np.zeros((n_users, N), dtype = np.uint32)\n \n if excluded is None:\n for user in range(n_users):\n top_n = self._recommend_user(ratings, user, N)\n recommendation[user] = top_n\n else:\n for user in range(n_users):\n top_n = self._recommend_user(ratings, user, N, excluded[user].indices)\n recommendation[user] = top_n\n \n return recommendation\n\n def _recommend_user(self, ratings, user, N, excluded=[]):\n \n scores = self._predict_user(user)\n userId = self.df[\"userId\"].cat.categories[user]\n watched = [item for item in self.df[self.df[\"userId\"] == userId][\"codes\"].values if not item in excluded]\n \n count = N + len(watched)\n \n if count < scores.shape[0]:\n ids = np.argpartition(scores, -count)[-count:]\n best_ids = np.argsort(scores[ids])[::-1]\n best = ids[best_ids]\n else:\n best = np.argsort(scores)[::-1]\n\n top_n = list(islice((rec for rec in best if rec not in watched), N))\n return top_n\n ","sub_path":"BPRAlgorithm.py","file_name":"BPRAlgorithm.py","file_ext":"py","file_size_in_byte":4740,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"73515177","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Jan 22 15:14:43 2020\n\n@author: Holt88\n\"\"\"\n\nimport bs4 as bs\nimport urllib.request\n\nsource = urllib.request.urlopen(\"https://worldadc-europe.com/whats-on/speakers/\")\nsoup = bs.BeautifulSoup(source,'lxml')\n\nwwn = soup.find_all(\"div\",{\"class\":\"content-wrapper\"})\n\nw = [x.get_text() for x in wwn]\nw = [a.replace(\"\\n\",\";\").split(\";\") for a in w]\n\n\ndef export_for_hunter(file_name, dataset):\n '''\n DOCSTRING: Write out a txt file \n IN: LIST\n OUT: FILE\n '''\n file = open(file_name, \"w\")\n file.write(\"Name;Position;Company\\n\")\n for a in dataset:\n file.write(a[1].strip() + \";\" + a[2].strip() + \";\" + a[3].strip() + \"\\n\") \n file.close()\n\n","sub_path":"Pb_Gen_Web_Scrape.py","file_name":"Pb_Gen_Web_Scrape.py","file_ext":"py","file_size_in_byte":708,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"516043459","text":"import schedule\nimport time \nimport json\nimport os\nimport requests \nimport glob\nfrom time import gmtime, strftime, sleep\nimport argparse\nimport raspcam as cam\nimport logging\nimport sys\n\nclass StreamToLogger(object):\n \"\"\"\n Fake file-like stream object that redirects writes to a logger instance.\n \"\"\"\n def __init__(self, logger, log_level=logging.INFO):\n self.logger = logger\n self.log_level = log_level\n self.linebuf = ''\n\n def write(self, buf):\n for line in buf.rstrip().splitlines():\n self.logger.log(self.log_level, line.rstrip())\n\ndef capture_photo(nodeID, url, script_dir):\n\t'''\n\tCaptures an image using Raspberry Pi Cam. Creates the data in the appropriate structure\n\tPublishes the data on the server\n\t'''\t\n\tcam.simple_picture(script_dir)\n\tlogger.info(\"The picture was captured\")\n\tdata_params, file = create_data( nodeID, script_dir)\n\tr = requests.post(url=url, files=file, data=data_params)\n\tlogger.info(\"Response: %s\", r)\n\ndef create_data( nodeID, script_dir):\n\t'''\n\t Creates the data to be published on the server. {node: nodeID} {image: img_raspi.img} \n\t'''\n\tparams = {\"node\": nodeID}\n\tfilename = glob.glob('%s/*.jpg' %script_dir) # return the full path of the generated image e.g only .jpg \n\tfile = {\"image\": open(filename[0], 'rb') if filename else None} # Check if the file exists\n\tlogger.debug(\"the params of post: %s\", params)\n\tlogger.debug(\"the file of post: %s\", file)\n\treturn params, file\n\n\n###############################\n# #\n# Start from here #\n# #\n###############################\n\n# Parse arguments of script\nparser = argparse.ArgumentParser(description='This script is responsible for capturing images using the Raspi Camera \\\n\t\t\t\t\t\t\t\t\t\t\t\t More spesificaly, it records a picture at a specific time during the day \\\n\t\t\t\t\t\t\t\t\t\t\t\t and then sends it to a remote server for further processing.')\nparser.add_argument('--direct', dest=\"direct_execution\", help='execute the script rigth now', action=\"store_true\")\nparser.add_argument('--ip', dest=\"ip\", help='Define the IP of the remote Database', default=\"194.177.207.12\")\nparser.add_argument('--port',dest=\"port\", help='Define the port of the remote Datatbase', default=\"3000\")\nargs = parser.parse_args()\n\n# Get the absolute path of project \nscript_dir = os.path.dirname(os.path.abspath(__file__))\n\n# loggig config\nlogging.basicConfig(\n level=logging.DEBUG,\n format='%(asctime)s : %(levelname)s : %(name)s :: %(message)s',\n filename= script_dir + \"/logfile.log\",\n filemode='a'\n)\n\n# create STDOUT and STDERR loggers\nstdout_logger = logging.getLogger('STDOUT')\nsl = StreamToLogger(stdout_logger, logging.INFO)\nsys.stdout = sl\n\nstderr_logger = logging.getLogger('STDERR')\nsl = StreamToLogger(stderr_logger, logging.ERROR)\nsys.stderr = sl\n\n# create a main logger \nlogger = logging.getLogger(__name__)\nlogger.setLevel(logging.DEBUG)\n\n#logging the arguments \nlogger.debug(\"All settings used: Direct exec: %s, IP: %s, Port: %s\", args.direct_execution, args.ip, args.port) \n\n# create the api-endpoint\nURL = \"http://\" + args.ip + \":\" + args.port + \"/pictures\" # default is http://194.177.207.12:3000/pictures \n\t\n# reading JSON data from the configuration file config.json\nwith open(script_dir + '/config.json', 'r') as json_file:\n\tdata = json_file.read()\nconfiguration_tags = json.loads(data)\n\n# if the --direct argument is used, the code will run git only once \nif args.direct_execution :\n\tlogger.info(\"Direct execution\")\n\tcapture_photo(configuration_tags['node'], URL, script_dir)\n\t\n# else, a schedule is created according to the hours contained in the configuration file\nelse :\n\tlogger.info(\"Service execution\")\n\tfor timer in configuration_tags['time']:\n\t\tschedule.every().day.at(str(timer)).do(capture_photo, configuration_tags['node'], URL, script_dir)\n\n\twhile True:\n\t\tschedule.run_pending()\n\t\ttime.sleep(1)\n\n","sub_path":"camera_service.py","file_name":"camera_service.py","file_ext":"py","file_size_in_byte":3894,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"73810531","text":"import pandas as pd\nimport datetime\n\n\"\"\" \nThis function gets employee's information (ID, Name, Phone number, Age) as an input from the user, and saves it into\npandas data frame\n\"\"\"\n\n\ndef add_emp_manually():\n employees = [(1111, \"Sapir Almog\", \"0547414641\", 31),\n (1112, \"Gilad Benatiya\", \"0502555605\", 35)]\n\n addemp = (int(input(\"Enter employee's ID number:\")),\n input(str(\"Enter Employee's name:\")),\n input(\"Enter Employee's phone number:\"),\n input(\"Enter Employee's Age\"))\n employees.append(addemp)\n df = pd.DataFrame(employees, columns=['ID', 'Name', 'Phone', 'Age'])\n # Add to employees list existing file\n with open('/Users/sapir/Documents/python/final project- employee attandance log/emplist.csv', 'a') as f:\n df.to_csv(f,names=['ID', 'Name', 'Phone', 'Age'], header=False, index_col=0)\n return df\n\n\nadd_emp_manually()\n","sub_path":"add_emp_manual1.py","file_name":"add_emp_manual1.py","file_ext":"py","file_size_in_byte":909,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"250245508","text":"import graphene\nfrom django.db.models import Q\nfrom django.utils import timezone\n\nfrom base.views import checkAuthentication, coupon_checker\nfrom coupon.models import CouponCode, CouponUser\n\n\nclass ProductListInput(graphene.InputObjectType):\n product_id = graphene.String(required=True)\n product_quantity = graphene.Float(required=True)\n\n\nclass CouponInput(graphene.InputObjectType):\n code = graphene.String(required=True)\n products = graphene.List(ProductListInput)\n\n\nclass ApplyCoupon(graphene.Mutation):\n class Arguments:\n input = CouponInput(required=True)\n\n msg = graphene.String()\n discount_amount = graphene.Float()\n coupon_code = graphene.String()\n status = graphene.Boolean()\n\n @staticmethod\n def mutate(root, info, input=None):\n user = info.context.user\n if checkAuthentication(user, info):\n discount_amount, coupon, _, is_under_limit = coupon_checker(input.code, input.products, user, True)\n if not is_under_limit:\n if discount_amount:\n return ApplyCoupon(status=True,\n msg=\"Code applied successfully.\",\n discount_amount=discount_amount,\n coupon_code=coupon.coupon_code)\n elif discount_amount == 0:\n msg = \"Coupon Discount Is Not Applicable On Products With Offer\"\n return ApplyCoupon(status=False, msg=msg)\n return ApplyCoupon(status=False, msg=\"Invalid Code!\")\n else:\n msg = \"Total Price Must Be {} Or More\".format(coupon.minimum_purchase_limit)\n return ApplyCoupon(status=False, msg=msg)\n\n\nclass CouponCount(graphene.Mutation):\n status = graphene.Boolean()\n count = graphene.Int()\n\n @staticmethod\n def mutate(root, info, input=None):\n user = info.context.user\n if checkAuthentication(user, info):\n count = CouponCode.objects.filter(Q(coupon_code_type='DC') |\n Q(coupon_code_type='GC1') | Q(coupon_code_type='GC2'),\n expiry_date__gte=timezone.now(),\n max_usage_count__gt=0,\n discount_code__in=CouponUser.objects.filter(\n created_for=user)).count()\n if count:\n return CouponCount(status=True,\n count=count)\n else:\n return CouponCount(status=False,\n count=0)\n\n\nclass Mutation(graphene.ObjectType):\n apply_coupon = ApplyCoupon.Field()\n coupon_count = CouponCount.Field()\n","sub_path":"coupon/graphql/mutation.py","file_name":"mutation.py","file_ext":"py","file_size_in_byte":2806,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"264953383","text":"import csv\nimport sys\nfrom pathlib import Path\nimport time\nimport datetime\nimport collections\nimport heapq\nfrom queue import Queue\nfrom datetime import timedelta\n\n'''\nmetadata of the user. Contains current_time, requests, and the IP of the\n user.\n'''\n\nclass UserData:\n total_index = 0\n\n def __init__(self, current_time, requests, ip):\n self.request_index = UserData.total_index + 1\n UserData.total_index = self.request_index\n self.current_time = current_time\n self.end_time = current_time\n self.requests = requests\n self.ip = ip\n\n def __lt__(self, other):\n return self.request_index < other.request_index\n\n'''\ntime conversion to a form that Python can utilize.\n'''\n\ndef convert_time(log_date, log_time):\n f = \"%Y-%m-%d %H:%M:%S\"\n d_str = '{0} {1}'.format(log_date, log_time)\n time = datetime.datetime.strptime(d_str, f)\n return time\n\n\n'''\nAdvance with a window until the window is too big for the users to expire. In each bucket,\ncheck to see if the users in the bucket have the same time as their own data. If they are, print to file.\n'''\ndef advance_session_window(\n time_buckets,\n session_window_start,\n user_info,\n inactivity_time,\n current_time,\n final=False):\n # Go through queue until the time gap is less than the inactivity timer.\n while session_window_start < current_time:\n if session_window_start + timedelta(seconds=inactivity_time) >= current_time:\n return session_window_start\n else:\n if session_window_start in time_buckets:\n print(time_buckets[session_window_start][0],session_window_start)\n while time_buckets[session_window_start][0]:\n ip = heapq.heappop(time_buckets[session_window_start][0])[1]\n # if maximum request one already filtered out.\n if ip not in user_info:\n continue\n if session_window_start == user_info[ip].end_time:\n print(\"deleted in here\")\n print_user_data(user_info[ip], ip)\n del(user_info[ip])\n # save time of session_window_start\n del time_buckets[session_window_start]\n session_window_start = session_window_start + timedelta(seconds=1)\n return session_window_start\n\n'''\noutputs userdata to the file location given.\n'''\n\ndef print_user_data(user_data, ip):\n start_time = user_data.current_time\n end_time = user_data.end_time\n start_time_string = \"{:%Y-%m-%d %H:%M:%S}\".format(start_time)\n end_time_string = \"{:%Y-%m-%d %H:%M:%S}\".format(end_time)\n seconds = int((end_time - start_time).total_seconds() + 1)\n requests = user_data.requests\n return_text = (\n \"{0},{1},{2},{3},{4}\".format(\n ip,\n start_time_string,\n end_time_string,\n seconds,\n requests))\n # print(return_text)\n with open(sys.argv[3], \"a\") as output_file:\n output_file.write(return_text + '\\n')\n output_file.close()\n\n'''\nGo through all the keys in order in the OrderedDict of users and finish\n printing up everything.\n'''\n\ndef finish_printing(user_info):\n deleted_users = []\n for user in user_info.keys():\n print_user_data(user_info[user], user)\n deleted_users += [user]\n for user in deleted_users:\n del(user_info[user])\n\n\ndef process_file():\n user_info = collections.OrderedDict()\n time_buckets = {}\n inactivity_time = None\n session_window_start = None\n logs = 0\n\n with open(sys.argv[3], \"w\") as output_file:\n print(\"clean file\")\n\n with open(sys.argv[2], \"r\") as inactivity_time_file:\n inactivity_time = int(inactivity_time_file.read())\n inactivity_time_file.close()\n\n # iterating through the input file.\n with open(sys.argv[1], \"r\") as input_file:\n reader = csv.DictReader(input_file, delimiter=\",\")\n header = reader.fieldnames\n for i, line in enumerate(reader):\n current_time = convert_time(line['date'], line['time'])\n if session_window_start is None:\n session_window_start = current_time\n # check to see if any files expired.\n session_window_start = advance_session_window(\n time_buckets, session_window_start, user_info, inactivity_time, current_time)\n ip = line['ip']\n if ip not in user_info:\n user_data = UserData(current_time, 0, ip)\n user_info[ip] = user_data\n else:\n user_data = user_info[ip]\n user_data.requests += 1\n user_data.end_time = current_time\n # min heap to make sure files are outputted in start time order.\n\n if current_time not in time_buckets:\n time_buckets[current_time] = ([], set())\n if ip not in time_buckets[current_time][1]:\n heapq.heappush(time_buckets[current_time][0], (user_data.request_index,ip))\n time_buckets[current_time][1].add(ip)\n finish_printing(user_info)\n input_file.close()\n\n\nif __name__ == \"__main__\":\n process_file()\n \n","sub_path":"insight_testsuite/temp/src/sessionization.py","file_name":"sessionization.py","file_ext":"py","file_size_in_byte":5228,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"154033268","text":"import requests\nfrom bs4 import BeautifulSoup\nimport urllib\n\nresponse = requests.get(\"http://localhost/WEBCRAWL/index.html\")\nresponse.encoding = \"utf-8\"\n\nhtml = response.text\nsoup = BeautifulSoup(html, \"html.parser\")\ntbody = soup.tbody\nprint(tbody.text)\n\n\nobj_tbody = soup.find(\"tbody\")\n\nobjs_td = obj_tbody.select(\"td\")\nfor td in objs_td:\n print(td.text)\n\n\n\nurl = \"http://localhost/WEBCRAWL/index.html\"\nreq = urllib.request.urlopen(url)\nres = req.read()\n \nsoup = BeautifulSoup(res,'html.parser')\nkeywords = soup.find_all('td')\nkeywords = [each_line.get_text().strip() for each_line in keywords[2:3]]\nprint(keywords)","sub_path":"HelloPython/day08/mycrawl02.py","file_name":"mycrawl02.py","file_ext":"py","file_size_in_byte":619,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"608866396","text":"import tkinter as tk\r\nimport tkinter.filedialog\r\nimport tkinter.messagebox\r\nimport cv2\r\nfrom PIL import Image, ImageTk\r\nfrom stegano import lsb,lsbset,red, steganalysis\r\nfrom stegano.lsbset import generators\r\nimport inspect\r\nfrom DCT import DCT\r\n# import ScrollableFrame as sf\r\nimport ntpath\r\n\r\nfrom LSBSteg import LSBSteg\r\nfrom OneTimePad import OneTimePad\r\nimport os\r\nfrom AESCipher import AESCipher\r\nfrom DESCipher import DESCipher\r\nfrom RSACipher import RSACipher\r\n\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\nimport csv\r\nimport math\r\n\r\nfrom ButtonDefinitions import analyse_mse, analyse_psnr, mse, psnr, compare_images, analyse_strings\r\n\r\n \r\ncontainer2wt = 0\r\n\r\n\r\n\r\ndef path_leaf(path):\t\r\n head, tail = ntpaht.split(path)\r\n return tail or ntpath.basename(head)\r\n\r\ndef get_file_name(img_path):\r\n return os.path.basename(img_path)\r\n#https://www.hlevkin.com/06testimages.htm\r\ndef exit_app():\r\n print('Exit App')\r\n messagebox = tk.messagebox.askyesno(\"Exit Application\",\"Are you sure you want to exit?\")\r\n print(messagebox)\r\n if (messagebox):\r\n root.quit()\r\n\r\ndef select_image():\r\n print('Select Image')\r\n global image_path\r\n image_path = tk.filedialog.askopenfilename(title=\"Select image\", filetypes=[(\"all files\", '*.*')])\r\n print(image_path)\r\n if (image_path):\r\n root.update_idletasks()\r\n global original_image_label\r\n load = Image.open(image_path)\r\n original_image = ImageTk.PhotoImage(load)\r\n print(type(original_image))\r\n original_image_label.config(image = original_image)\r\n original_image_label.image = original_image\r\n original_image_label.pack(in_=container2, fill=tk.BOTH, expand=True)\r\n\r\ndef displayImage(path):\r\n print(type(path))\r\n # im = Image.fromarray(image)\r\n global processed_image_label\r\n # processed_image = ImageTk.PhotoImage(image=im)\r\n # print(type(processed_image))\r\n load = Image.open(path)\r\n processed_image = ImageTk.PhotoImage(load)\r\n processed_image_label.config(image=processed_image)\r\n processed_image_label.image = processed_image\r\n processed_image_label.pack(in_=container4, fill=tk.BOTH, expand=True)\r\n\r\ndef displaySecret(secret):\r\n clear_processed_image()\r\n global processed_image_label\r\n processed_image_label.config(text=secret)\r\n # processed_image_label.image = processed_image\r\n processed_image_label.pack(in_=container4, fill=tk.BOTH, expand=True)\r\n\r\ndef clear_image():\r\n print('Save Image')\r\n # print(processed_image_label.image)\r\n clear_processed_image()\r\n\r\n\r\ndef saveImage():\r\n print(\"af\")\r\n\r\ndef saveSecretToFile(secret):\r\n print(\"saveSecretToFile\")\r\n f = tk.filedialog.asksaveasfile(mode='w', defaultextension=\".txt\")\r\n if f is None:\r\n return\r\n text2save = str(secret)\r\n f.write(text2save)\r\n f.close()\r\n\r\ndef clear_processed_image():\r\n print(\"clear image\")\r\n processed_image_label.config(image='')\r\n processed_image_label.pack(in_=container4, fill=tk.BOTH, expand=True)\r\n\r\ndef clear_text_description():\r\n print(\"clear image\")\r\n text2.delete('1.0', tk.END)\r\n\r\n# Enter data from secret file into text1\r\ndef select_secret_file():\r\n # global secret_image_path\r\n print(\"Select secret file\")\r\n secret_file = tk.filedialog.askopenfile(title=\"Select file\", filetypes=[(\"All files\", '*.*')])\r\n # print(secret_image_path)\r\n data = secret_file.read()\r\n text1.insert(tk.END, data)\r\n\r\n\r\ndef process():\r\n try:\r\n print('process()')\r\n encrypt_decrypt = options_clicked.get()\r\n algo_technique = technique_options_clicked.get()\r\n encryption_technique = encryption_options_clicked.get()\r\n \r\n # Check for secret data\r\n secret_string = text1.get(\"1.0\",tk.END)\r\n\r\n # check for carrier\r\n try: image_path\r\n except NameError:\r\n tk.messagebox.showwarning(\"Data Required\",\"Please select carrier image to proceed\")\r\n return\r\n # original_image = cv2.imread(image_path)\r\n print(secret_string)\r\n if (algo_technique == technique_options[0]):\r\n # LSB Algorithm\r\n lsbAlgoDefault(encrypt_decrypt, secret_string, encryption_technique)\r\n elif (algo_technique == technique_options[1]):\r\n # stegano plain\r\n lsbAlgoStegano(\"DCT\", secret_string, encrypt_decrypt, encryption_technique)\r\n except NameError as error:\r\n print(error)\r\n\r\ndef is_grey_scale(image_path):\r\n img = Image.open(image_path).convert('RGB')\r\n img1 = img\r\n w,h = img1.size\r\n for i in range(w):\r\n for j in range(h):\r\n r,g,b = img1.getpixel((i,j))\r\n if r != g != b:\r\n return False\r\n return True \r\n\r\ndef compare_strings(original, derived):\r\n if len(original) != len(derived):\r\n return 0.0\r\n\r\n else:\r\n count = 0\r\n for i in range(len(original)):\r\n if original[i] == derived[i]:\r\n count += 1\r\n\r\n return float(count/len(original))\r\n\r\n\r\ndef addtofile(stego_type, enc_type, percentage):\r\n flag = 0\r\n print(\"Add to file\")\r\n with open(\"secret/StringAnalysis.csv\", 'r+') as varfile:\r\n read_object = csv.reader(varfile)\r\n titles = next(read_object)\r\n print(\"1\")\r\n\r\n for row in read_object:\r\n print(\"2\")\r\n if len(row) > 0:\r\n print(row)\r\n print(stego_type, enc_type)\r\n if row[0] == stego_type and row[1] == enc_type:\r\n print(\"Entered\")\r\n if len(row) > 2:\r\n row[2] = ((float(row[2]) + percentage)/2)\r\n flag = 1\r\n\r\n if flag == 0:\r\n write_object = csv.writer(varfile)\r\n write_object.writerow([stego_type, enc_type, percentage])\r\n\r\n\r\ndef lsbAlgoStegano(type, secret_string, encrypt_decrypt, encryption_technique):\r\n if (encrypt_decrypt == options[0]):\r\n if (len(secret_string) == 1):\r\n print(\"Empty Secret:: Showing warning\")\r\n tk.messagebox.showwarning(\"Data Required\", \"Please enter secret data to be encoded\")\r\n return\r\n if (type == \"DCT\"):\r\n if (encrypt_decrypt == options[0]):\r\n file_name = encryption_technique + \"DCT.txt\"\r\n text_file = open(file_name, \"w\")\r\n text_file.write(str(secret_string))\r\n text_file.close\r\n if encryption_technique == \"OTP\":\r\n enc = OneTimePad(secret_string, \"DCT\")\r\n enc_string = enc.run(encrypt_decrypt)\r\n\r\n elif encryption_technique == \"RSA\":\r\n enc = RSACipher(secret_string, \"DCT\")\r\n enc_string = enc.run(encrypt_decrypt)\r\n\r\n elif encryption_technique == \"AES\":\r\n enc = AESCipher(secret_string, \"DCT\")\r\n enc_string = enc.run(encrypt_decrypt)\r\n\r\n elif encryption_technique == \"DES\":\r\n enc = DESCipher(secret_string, \"DCT\")\r\n enc_string = enc.run(encrypt_decrypt)\r\n \r\n outFile = \"secret/secretDCT.png\"\r\n x = DCT(image_path)\r\n secret = x.DCTEn(enc_string, outFile)\r\n print(\"secret :: DCT:: \",secret)\r\n # secret = red.hide(image_path, secret_string)\r\n # secret.save(\"secret.png\")\r\n displayImage(\"secret/secretDCT.png\")\r\n img1 = cv2.imread(image_path, cv2.IMREAD_UNCHANGED)\r\n print(img1.shape)\r\n img2 = cv2.imread(\"secret/secretDCT.png\", cv2.IMREAD_UNCHANGED)\r\n print(img1.shape, img2.shape)\r\n if is_grey_scale(image_path) and len(img2.shape) == 3:\r\n imgA = cv2.cvtColor(img1, cv2.COLOR_BGRA2GRAY)\r\n imgB = cv2.cvtColor(img2, cv2.COLOR_BGRA2GRAY)\r\n else:\r\n imgA = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY)\r\n imgB = cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY)\r\n compare_images(imgA, imgB, \"DCT\", encryption_technique)\r\n else:\r\n y = DCT(image_path)\r\n secret = y.DCTDe()\r\n # secret = red.reveal(image_path)\r\n print(\"Secret is \", secret)\r\n if encryption_technique == \"OTP\":\r\n dec = OneTimePad(secret, \"DCT\")\r\n secret_message = dec.run(encrypt_decrypt)\r\n\r\n elif encryption_technique == \"RSA\":\r\n dec = RSACipher(secret, \"DCT\")\r\n secret_message = dec.run(encrypt_decrypt)\r\n\r\n elif encryption_technique == \"AES\":\r\n dec = AESCipher(secret, \"DCT\")\r\n secret_message = dec.run(encrypt_decrypt)\r\n\r\n elif encryption_technique == \"DES\":\r\n dec = DESCipher(secret, \"DCT\")\r\n secret_message = dec.run(encrypt_decrypt)\r\n\r\n #dec = OneTimePad(secret, \"DCT\")\r\n #secret_message = dec.run(encrypt_decrypt)\r\n filename = encryption_technique + \"DCT.txt\"\r\n key_file = open(filename, \"r\")\r\n original_message = key_file.readline()\r\n key_file.close()\r\n precentage_comparison = compare_strings(original_message, secret_message)\r\n print(\"The strings are equal by\", precentage_comparison,\"parts\")\r\n addtofile(\"DCT\", encryption_technique[:3], precentage_comparison)\r\n displaySecret(secret_message)\r\n saveSecretToFile(secret_message)\r\n\r\n\r\n\r\ndef lsbAlgoDefault(encrypt_decrypt, secret_string, encryption_technique):\r\n # if (algo_technique == technique_options[0]):\r\n # LSB:: Text Steganography\r\n if (encrypt_decrypt == options[0]):\r\n print(\"LSB:::Text::: Encrypt\")\r\n # Warning for secret string\r\n if (len(secret_string) == 1):\r\n print(\"Empty Secret:: Showing warning\")\r\n tk.messagebox.showwarning(\"Data Required\", \"Please enter secret data to be encoded\")\r\n return\r\n # encoding\r\n steg = LSBSteg(cv2.imread(image_path))\r\n file_name = encryption_technique + \"Plain.txt\"\r\n text_file = open(file_name, \"w\")\r\n text_file.write(str(secret_string))\r\n text_file.close()\r\n if encryption_technique == \"OTP\":\r\n enc = OneTimePad(secret_string, \"Plain\")\r\n enc_string = enc.run(encrypt_decrypt)\r\n\r\n elif encryption_technique == \"RSA\":\r\n enc = RSACipher(secret_string, \"Plain\")\r\n enc_string = enc.run(encrypt_decrypt)\r\n\r\n elif encryption_technique == \"AES\":\r\n enc = AESCipher(secret_string, \"Plain\")\r\n enc_string = enc.run(encrypt_decrypt)\r\n\r\n elif encryption_technique == \"DES\":\r\n enc = DESCipher(secret_string, \"Plain\")\r\n enc_string = enc.run(encrypt_decrypt)\r\n \r\n img_encoded = steg.encode_text(enc_string)\r\n cv2.imwrite(\"secret/secret.png\", img_encoded)\r\n displayImage(\"secret/secret.png\")\r\n img1 = cv2.imread(image_path)\r\n img2 = cv2.imread(\"secret/secret.png\")\r\n imgA = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY)\r\n imgB = cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY)\r\n compare_images(imgA, imgB, \"LSB\", encryption_technique)\r\n else:\r\n print(\"LSB:::Text::: Decrypt\")\r\n # decoding\r\n print(image_path)\r\n im = cv2.imread(image_path)\r\n steg = LSBSteg(im)\r\n secret = steg.decode_text()\r\n\r\n print(\"Secret is\", secret)\r\n \r\n if encryption_technique == \"OTP\":\r\n dec = OneTimePad(secret, \"Plain\")\r\n secret_message = dec.run(encrypt_decrypt)\r\n\r\n elif encryption_technique == \"RSA\":\r\n dec = RSACipher(secret, \"Plain\")\r\n secret_message = dec.run(encrypt_decrypt)\r\n\r\n elif encryption_technique == \"AES\":\r\n dec = AESCipher(secret, \"Plain\")\r\n secret_message = dec.run(encrypt_decrypt)\r\n\r\n elif encryption_technique == \"DES\":\r\n dec = DESCipher(secret, \"Plain\")\r\n secret_message = dec.run(encrypt_decrypt)\r\n\r\n \r\n filename = encryption_technique + \"Plain.txt\"\r\n key_file = open(filename, \"r\")\r\n original_message = key_file.readline()\r\n key_file.close()\r\n precentage_comparison = compare_strings(original_message, secret_message)\r\n print(\"The strings are equal by\", precentage_comparison,\"parts\")\r\n addtofile(\"LSB\", encryption_technique[:3], precentage_comparison)\r\n #dec = OneTimePad(secret, \"Plain\")\r\n #secret_message = dec.run(encrypt_decrypt)\r\n displaySecret(secret_message)\r\n print(\"Text value:\", secret_message)\r\n\r\n\r\ndef technique_callback(*args):\r\n clear_text_description()\r\n all_generators = inspect.getmembers(generators, inspect.isfunction)\r\n option = technique_options_clicked.get()\r\n print(\"technique_callback: \", option)\r\n data = \"\"\r\n if (option == technique_options[0]):\r\n data =\"Technique 1\\nLSB is the lowest bit in a series of numbers in binary. e.g. in the binary number: 10110001, the least significant bit is far right 1.\\n\" \\\r\n \"The LSB based Steganographyis one of the steganographic methods, used to embed the secret data in to the least significant bits of the \" \\\r\n \"pixel values in a cover image. e.g. 240 can be hidden in the first eight bytes of three pixels in a 24 bit image.\"\r\n elif (option == technique_options[1]):\r\n data = \"DCT coefficients are used for JPEG compression. It separates the image into parts of differing importance. \" \\\r\n \"It transforms a signal or image from the spatial domain to the frequency domain. It can separate the image into high, middle and low frequency \" \\\r\n \"components. \\n\" \\\r\n \"Signal energy lies at low frequency in image; it appears in the upper left corner of the DCT. Compression can be achieved since \" \\\r\n \"the lower right values represent higher frequencies, and generally small enough to be neglected with little visible distortion. \" \\\r\n \"DCT is used in steganography as- \\n 1. Image is broken into 8×8 blocks of pixels. \\n 2. Working from left to right, top to bottom, the DCT is applied to each block.\" \\\r\n \" \\n 3. Each \" \\\r\n \"block is compressed through quantization table to scale the DCT coefficients and message is embedded in DCT coefficients.\"\r\n text2.insert(tk.END, data)\r\n print(data)\r\n\r\nroot = tk.Tk()\r\nroot.geometry(\"600x400\")\r\nroot.title(\"Image Cryptography and Steganography\")\r\n\r\ntop = tk.Frame(root, borderwidth=1,relief=\"solid\")\r\ntop1 = tk.Frame(root, borderwidth=1,relief=\"solid\")\r\nbottom1 = tk.Frame(root, borderwidth=1, relief=\"solid\")\r\nbottom = tk.Frame(root, borderwidth=1,relief=\"solid\")\r\nleft = tk.Frame(root, borderwidth=1, relief=\"solid\")\r\nright = tk.Frame(root, borderwidth=1, relief=\"solid\")\r\ncontainer1 = tk.Frame(left, borderwidth=1, relief=\"solid\")\r\ncontainer2 = tk.Frame(left, borderwidth=1, relief=\"solid\")\r\ncontainer3 = tk.Frame(right, borderwidth=1, relief=\"solid\")\r\ncontainer4 = tk.Frame(right, borderwidth=1, relief=\"solid\")\r\n\r\nsecret_label = tk.Label(container1, text=\"Enter secret\")\r\n# original_img_label = tk.Label(container2, text=\"Original Image\")\r\ndescription_label = tk.Label(container3, text=\"Description\")\r\n# processed_img_label = tk.Label(container4, text=\"Processed Image\")\r\n\r\ntop.pack(side=\"top\", expand=False, fill=\"both\")\r\ntop1.pack(side=\"top\", expand=False, fill=\"both\")\r\nbottom1.pack(side=\"bottom\", expand=False, fill=\"both\")\r\nbottom.pack(side=\"bottom\", expand=False, fill=\"both\")\r\nleft.pack(side=\"left\", expand=True, fill=\"both\")\r\nright.pack(side=\"right\", expand=True, fill=\"both\")\r\ncontainer1.pack(expand=False, fill=\"both\", padx=5, pady=5)\r\ncontainer2.pack(expand=False, fill=\"both\", padx=5, pady=5)\r\ncontainer3.pack(expand=False, fill=\"both\", padx=5, pady=5)\r\ncontainer4.pack(expand=False, fill=\"both\", padx=5, pady=5)\r\n\r\ncontainer2wt = container2.winfo_width()\r\n#print(container2wt)\r\noriginal_image_label = tk.Label(root, width=container2wt)\r\nprocessed_image_label = tk.Label(root, width=container2wt)\r\n\r\nsecret_label.pack()\r\n# original_img_label.pack()\r\ndescription_label.pack()\r\n# processed_img_label.pack()\r\n\r\n\r\n# Buttons\r\nselect_img_btn = tk.Button(root,text='Select Image', width=35, command=select_image)\r\nselect_img_btn.pack(in_=top, side=\"left\")\r\n\r\nselect_secret_img_btn = tk.Button(root,text='Select secret file', width=35, command=select_secret_file)\r\nselect_secret_img_btn.pack(in_=top1, side=\"left\")\r\n\r\nclear_btn = tk.Button(root,text='Clear Image', width=35, command=clear_image)\r\nclear_btn.pack(in_=bottom, side=\"left\")\r\n\r\nexit_btn = tk.Button(root,text='Exit App', width=35, command=exit_app)\r\nexit_btn.pack(in_=bottom, side=\"right\")\r\n\r\nprocess_btn = tk.Button(root,text='Process', width=35, command=process)\r\nprocess_btn.pack(in_=top, side=\"right\")\r\n\r\n# Drop down menu\r\noptions = [\r\n \"Encrypt\",\r\n \"Decrypt\"\r\n]\r\ntechnique_options = [\r\n \"LSB Algorithm - Plain\",\r\n \"Discrete Cosine Transform\"\r\n]\r\n\r\nencryption_options = [\r\n \"OTP\",\r\n \"RSA\",\r\n \"AES\",\r\n \"DES\"\r\n]\r\n\r\noptions_clicked = tk.StringVar()\r\noptions_clicked.set(options[0])\r\ntechnique_options_clicked = tk.StringVar()\r\ntechnique_options_clicked.trace(\"w\",technique_callback)\r\ntechnique_options_clicked.set(technique_options[0])\r\nencryption_options_clicked = tk.StringVar()\r\nencryption_options_clicked.set(encryption_options[0])\r\n\r\nimage_name = \"\"\r\n\r\ndrop = tk.OptionMenu(root, options_clicked, *options)\r\ndrop.pack(in_=top, anchor=\"n\", side=\"bottom\")\r\nencryption_drop = tk.OptionMenu(root, encryption_options_clicked, *encryption_options)\r\nencryption_drop.pack(in_=top1, anchor=\"n\", side=\"left\")\r\ntechnique_drop = tk.OptionMenu(root, technique_options_clicked, *technique_options)\r\ntechnique_drop.pack(in_=top1, anchor=\"n\", side=\"bottom\")\r\n\r\n# textbox and scrollbar\r\ntext1 = tk.Text(root, width=35, height=5)\r\ntext2 = tk.Text(root, width=35, height=5)\r\nscrollbar1 = tk.Scrollbar(root)\r\nscrollbar2 = tk.Scrollbar(root)\r\nscrollbar1.config(command=text1.yview)\r\nscrollbar2.config(command=text2.yview)\r\ntext1.config(yscrollcommand=scrollbar1.set)\r\ntext2.config(yscrollcommand=scrollbar2.set)\r\nscrollbar1.pack(in_=container1, side=tk.RIGHT, fill=tk.Y)\r\nscrollbar2.pack(in_=container3, side=tk.RIGHT, fill=tk.Y)\r\ntext1.pack(in_=container1, side=tk.LEFT, fill=tk.BOTH, expand=True)\r\ntext2.pack(in_=container3, side=tk.LEFT, fill=tk.BOTH, expand=True)\r\n\r\n#Analysing Buttons\r\nanalyse_mse_btn = tk.Button(root, text = \"Analyse MSE\", width = 35, command = analyse_mse)\r\nanalyse_mse_btn.pack(in_ = bottom1, side = \"left\")\r\n\r\nanalyse_psnr_btn = tk.Button(root, text = \"Analyse PSNR\", width = 35, command = analyse_psnr)\r\nanalyse_psnr_btn.pack(in_ = bottom1, side = \"right\")\r\n\r\nanalyse_strings = tk.Button(root, text = \"Analyse Strings\", width = 35, command = analyse_strings)\r\nanalyse_strings.pack(in_ = bottom1, side = \"bottom\")\r\n\r\n\r\nall_generators = inspect.getmembers(generators, inspect.isfunction)\r\n#for generator in all_generators:\r\n# print(generator[0], generator[1].__doc__)\r\n\r\nroot.mainloop()\r\n","sub_path":"window.py","file_name":"window.py","file_ext":"py","file_size_in_byte":19469,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"442283512","text":"from django.conf.urls import patterns, url\n\nfrom django.contrib import admin\nadmin.autodiscover()\n\nurlpatterns = patterns(\n '',\n url(r'^requests/', 't3_requests.views.requests', name='requests'),\n url(r'^change_priority/', 't3_requests.views.change_priority',\n name='change_priority'),\n)\n","sub_path":"apps/t3_requests/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":304,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"327906116","text":"# copy\r\nfrom Queue import Queue \r\nclass MyStack(object): \r\n \r\n def __init__(self): \r\n \"\"\" \r\n Initialize your data structure here. \r\n \"\"\" \r\n #q1作为进栈出栈,q2作为中转站 \r\n self.q1=Queue() \r\n self.q2=Queue() \r\n \r\n def push(self, x): \r\n \"\"\" \r\n Push element x onto stack. \r\n :type x: int \r\n :rtype: void \r\n \"\"\" \r\n self.q1.put(x) \r\n \r\n def pop(self): \r\n \"\"\" \r\n Removes the element on top of the stack and returns that element. \r\n :rtype: int \r\n \"\"\" \r\n while self.q1.qsize()>1: \r\n self.q2.put(self.q1.get())#将q1中除尾元素外的所有元素转到q2中 \r\n if self.q1.qsize()==1: \r\n res=self.q1.get()#弹出q1的最后一个元素 \r\n #while self.q2.qsize>0:#将q2的元素转移到q1中 \r\n #self.q1.put(self.q2.get())#这会出现超出时间显示错误,有实例不通过 \r\n tmp=self.q2#交换q1,q2 \r\n self.q2=self.q1 \r\n self.q1=tmp \r\n return res \r\n \r\n def top(self): \r\n \"\"\" \r\n Get the top element. \r\n :rtype: int \r\n \"\"\" \r\n while self.q1.qsize()>1: \r\n self.q2.put(self.q1.get())#将q1中除尾元素外的所有元素转到q2中 \r\n if self.q1.qsize()==1: \r\n res=self.q1.get()#弹出q1的最后一个元素 \r\n self.q2.put(res)#与pop唯一不同的是需要将q1最后一个元素保存到q2中 \r\n #while self.q2.qsize>0:#将q2的元素转移到q1中 \r\n #self.q1.put(self.q2.get()) \r\n tmp=self.q2#交换q1,q2 \r\n self.q2=self.q1 \r\n self.q1=tmp \r\n return res \r\n \r\n def empty(self): \r\n \"\"\" \r\n Returns whether the stack is empty. \r\n :rtype: bool \r\n \"\"\" \r\n return not bool(self.q1.qsize()+self.q2.qsize())#为空返回True,不为空返回False ","sub_path":"225_MyStack.py","file_name":"225_MyStack.py","file_ext":"py","file_size_in_byte":2009,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"332385625","text":"import sqlite3\n\nconn = sqlite3.connect('friends.sqlite')\ncur = conn.cursor()\ncur.execute('SELECT * FROM Osoby')\ncount = 0\nprint(\"Osoby:\")\nfor row in cur:\n print(row)\n count = count + 1\nprint(count, 'wierszy.')\ncur.execute('SELECT * FROM Obserwuje')\ncount = 0\nprint(\"\\nObserwuje:\")\nfor row in cur:\n print(row)\n count = count + 1\nprint(count, 'wierszy.')\ncur.close()\n","sub_path":"code3/twdump2.py","file_name":"twdump2.py","file_ext":"py","file_size_in_byte":377,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"161203416","text":"# -*- coding: UTF-8 -*-\n\"\"\"Refactoring.\n\nThis exercise contains a complete and working example, but it's very poorly written.\n\nYour job is to go through it and make it as good as you can.\n\nThat means making it self-documenting wherever possible, adding comments where\nit isn't. Take repeated code and make it into a function. Also use functions\nto encapsulate concepts. If something is done many times, maybe a map or a loop\nis called for. Etc.\n\nSome functions will have directions as external comments, once you think you\nare on top of it, take these comments out. Others won't have comments and\nyou'll need to figure out for yourself what to do.\n\"\"\"\n\n\n# return a list of countdown messages, much like in the bad function above.\n# It should say something different in the last message.\ndef countdown(message, start, stop, completion_message):\n for i in range(start-stop+1,stop-stop,-1):\n print(message + \" \" + str(i))\n print(completion_message)\n\n# TRIANGLES\n\n# This should be a series of functions that are ultimatly used by\n# triangle_master\n# It should eventually return a dictionary of triangle facts. It should\n# optionally print information as a nicely formatted string. Make printing\n# turned off by default but turned on with an optional argument.\n# The stub functions are made for you, and each one is tested, so this should\n# hand hold quite nicely.\ndef calculate_hypotenuse(base, height):\n import math\n hypotenuse = (math.sqrt((base ** 2) + (height ** 2)))\n return hypotenuse\n\ndef calculate_area(base, height):\n area = ((base * height)/2)\n return area\n\ndef calculate_perimeter(base, height):\n perimeter = (base) + (height) + (calculate_hypotenuse(base,height))\n return perimeter\n\ndef calculate_aspect(base, height):\n if base > height:\n return (\"wide\")\n if base < height:\n return (\"tall\")\n else:\n return (\"equal\")\n\n# Make sure you reuse the functions you've already got\n# Don't reinvent the wheel\ndef get_triangle_facts(base, height, units=\"mm\"):\n return {\n \"area\": calculate_area(base, height),\n \"perimeter\": calculate_perimeter(base, height),\n \"height\": height,\n \"base\": base,\n \"hypotenuse\": calculate_hypotenuse(base, height),\n \"aspect\": calculate_aspect(base, height),\n \"units\": units,\n }\n\n\n# this should return a multi line string that looks a bit like this:\n#\n# 15\n# |\n# | |\\\n# |____>| \\ 17.0\n# | \\\n# | \\\n# ------\n# 8\n# This triangle is 60.0mm²\n# It has a perimeter of 40.0mm\n# This is a tall triangle.\n#\n# but with the values and shape that relate to the specific\n# triangle we care about.\ndef tell_me_about_this_right_triangle (facts_dictionary):\n tall = \"\"\"\n {height}\n |\n | |\\\\\n |____>| \\\\ {hypotenuse}\n | \\\\\n | \\\\\n ------\n {base}\"\"\"\n wide = \"\"\"\n {hypotenuse}\n ↓ ∕ |\n ∕ | <-{height}\n ∕ |\n ∕------------|\n {base}\"\"\"\n equal = \"\"\"\n {height}\n |\n | |⋱\n |____>| ⋱ <-{hypotenuse}\n |____⋱\n {base}\"\"\"\n\n pattern = (\n \"This triangle is {area}{units}²\\n\"\n \"It has a perimeter of {perimeter}{units}\\n\"\n \"This is a {aspect} triangle.\\n\"\n )\n\n if facts_dictionary['height'] > facts_dictionary ['base']:\n return tall.format(height=facts_dictionary['height'], base=facts_dictionary ['base'],hypotenuse=facts_dictionary ['hypotenuse'])\n elif facts_dictionary['height'] < facts_dictionary ['base']:\n return wide.format(height=facts_dictionary['height'], base=facts_dictionary ['base'],hypotenuse=facts_dictionary ['hypotenuse'])\n else:\n return equal.format(height=facts_dictionary['height'], base=facts_dictionary ['base'],hypotenuse=facts_dictionary ['hypotenuse'])\n\ndef triangle_master(base, height, return_diagram=False, return_dictionary=False):\n if return_diagram and return_dictionary:\n return {\"diagram\": tell_me_about_this_right_triangle (get_triangle_facts(base, height)), \"facts\": get_triangle_facts(base, height)}\n elif return_diagram:\n return tell_me_about_this_right_triangle (get_triangle_facts(base, height))\n elif return_dictionary:\n return get_triangle_facts(base, height)\n else:\n print(\"You're an odd one, you don't want anything!\")\n\n\ndef wordy_pyramid():\n import requests\n\n url = \"https://us-central1-waldenpondpress.cloudfunctions.net/give_me_a_word?wordlength={len}\"\n \n wordlist = []\n\n def refractor_WP(start,stop,step):\n for i in range(start,stop, step):\n fullurl=url.format(len=i)\n pull = requests.get(fullurl) \n if pull.status_code is 200: \n randword = pull.content \n if randword is None: \n pass\n else:\n randword = str(randword)\n wordlist.append(randword[2:len(randword)-1])\n\n refractor_WP(3,21,2)\n refractor_WP(20,2,-2) \n return wordlist\n\n\ndef get_a_word_of_length_n(length):\n import requests\n\n url = \"https://us-central1-waldenpondpress.cloudfunctions.net/give_me_a_word?wordlength={leng}\"\n if type(length) == int and length >= 3:\n fullurl=url.format(leng=length)\n pull = requests.get(fullurl) \n if pull.status_code is 200: \n wordn = pull.content \n wordn = str(wordn)\n outputword = wordn[2:len(wordn)-1]\n # this retrives the word from the url\n return outputword\n else:\n return None\n\ndef list_of_words_with_lengths(list_of_lengths):\n import requests\n\n list_of_words = []\n\n for i in list_of_lengths:\n url = \"https://us-central1-waldenpondpress.cloudfunctions.net/give_me_a_word?wordlength={leng}\"\n if type(i) == int and i >= 3:\n fullurl=url.format(leng=i)\n pull = requests.get(fullurl) \n if pull.status_code is 200: \n wordn = pull.content \n wordn = str(wordn)\n outputword = wordn[2:len(wordn)-1]\n list_of_words.append(outputword)\n else:\n pass\n\n return list_of_words\n\nif __name__ == \"__main__\":\n list_of_words_with_lengths([4,5,8])","sub_path":"week5/exercise1.py","file_name":"exercise1.py","file_ext":"py","file_size_in_byte":6470,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"470492596","text":"import numpy as np\n\nclass DemoReplayBuffer():\n def __init__(self,max_size, input_shape, n_actions):\n self.mem_size=max_size\n self.mem_cntr=0\n\n self.state_memory = [None] * max_size\n self.new_state_memory = [None] * max_size\n self.action_memory = [None] * max_size\n self.reward_memory = [None] * max_size\n self.n_reward_memory = [None] * max_size\n # self.terminal_memory=np.zeros(self.mem_size,dtype=np.uint8)\n self.terminal_memory = [None] * max_size\n \n\n def store_transition(self, state, action, reward, n_reward, next_state, done):\n\n index = self.mem_cntr % self.mem_size\n self.state_memory[index] = state\n self.action_memory[index] = action\n self.reward_memory[index] = reward\n self.n_reward_memory[index] = n_reward\n self.new_state_memory[index] = next_state\n self.terminal_memory[index] = done\n self.mem_cntr += 1\n\n def sample_buffer(self,batch_size):\n max_mem=min(self.mem_cntr, self.mem_size)\n\n batch=np.random.choice(max_mem, batch_size, replace=False).astype(int) #max index of max_mem and shape batchsize. replace=False makes it so indexes aren't repeated\n states=[self.state_memory[i] for i in batch]\n actions=[self.action_memory[i] for i in batch]\n rewards=[self.reward_memory[i] for i in batch]\n n_rewards=[self.n_reward_memory[i] for i in batch]\n next_states=[self.new_state_memory[i] for i in batch]\n dones=[self.terminal_memory[i] for i in batch]\n\n return states, actions, rewards, n_rewards,next_states, dones","sub_path":"Sanjay/DQFDDDQN/utils/demo_replay_buffer.py","file_name":"demo_replay_buffer.py","file_ext":"py","file_size_in_byte":1624,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"144921213","text":"import os\nimport vtk, qt, ctk, slicer, logging\nfrom slicer.ScriptedLoadableModule import *\nimport SimpleITK as sitk\nfrom radiomics import featureextractor, getFeatureClasses, setVerbosity\nimport sitkUtils\nimport traceback\n\n\n#\n# SlicerRadiomics\n#\n\nclass SlicerRadiomics(ScriptedLoadableModule):\n \"\"\"Uses ScriptedLoadableModule base class, available at:\n https://github.com/Slicer/Slicer/blob/master/Base/Python/slicer/ScriptedLoadableModule.py\n \"\"\"\n\n def __init__(self, parent):\n ScriptedLoadableModule.__init__(self, parent)\n self.parent.title = 'Radiomics'\n self.parent.categories = ['Informatics']\n self.parent.dependencies = []\n self.parent.contributors = [\"Andrey Fedorov (BWH), Nicole Aucoin (BWH), Jean-Christophe Fillion-Robin (Kitware), \"\n \"Joost van Griethuysen (AVL-NKI), Hugo Aerts (DFCI)\"]\n self.parent.helpText = \"\"\"\n This is a scripted loadable module bundled in the SlicerRadomics extension.\n It gives access to the radiomics feature calculation classes implemented in pyradiomics library.\n See more details at http://pyradiomics.readthedocs.io/.\n \"\"\"\n self.parent.acknowledgementText = \"\"\"\n This work was partially supported by NIH/NCI ITCR program grant U24 CA194354.\n \"\"\"\n\n\n#\n# SlicerRadiomicsWidget\n#\n\nclass SlicerRadiomicsWidget(ScriptedLoadableModuleWidget):\n \"\"\"Uses ScriptedLoadableModuleWidget base class, available at:\n https://github.com/Slicer/Slicer/blob/master/Base/Python/slicer/ScriptedLoadableModule.py\n \"\"\"\n\n def setup(self):\n ScriptedLoadableModuleWidget.setup(self)\n\n # Setup a logger for the extension log messages (child logger of pyradiomics)\n self.logger = logging.getLogger('radiomics.slicer')\n\n # Instantiate and connect widgets ...\n\n #\n # Volume and segmentation input\n #\n self._addInputVolumeSection()\n\n #\n # Extraction Customization Area\n #\n self._addCustomizationSection()\n\n #\n # Output section\n #\n self._addOutputSection()\n\n #\n # Apply Button\n #\n self.applyButton = qt.QPushButton('Apply')\n self.applyButton.toolTip = 'Run the algorithm.'\n self.applyButton.enabled = False\n self.layout.addWidget(self.applyButton)\n\n #\n # Connections\n #\n\n # Input Section\n self.inputVolumeSelector.connect('currentNodeChanged(vtkMRMLNode*)', self.onSelect)\n self.inputMaskSelector.connect('currentNodeChanged(vtkMRMLNode*)', self.onSelect)\n self.inputSegmentationSelector.connect('currentNodeChanged(vtkMRMLNode*)', self.onSelect)\n\n # Customization Section\n self.manualCustomizationRadioButton.connect('toggled(bool)', self.onCustomizationTypeCheckedChanged)\n\n self.calculateAllFeaturesButton.connect('clicked(bool)', self.onCalculateAllFeaturesButton)\n self.calculateNoFeaturesButton.connect('clicked(bool)', self.onCalculateNoFeaturesButton)\n\n self.parameterFilePathLineEdit.connect('currentPathChanged(QString)', self.onSelect)\n\n # General Section\n self.applyButton.connect('clicked(bool)', self.onApplyButton)\n\n # Add vertical spacer\n self.layout.addStretch(1)\n\n # Refresh Apply button state\n self.onSelect()\n\n def _addInputVolumeSection(self):\n inputVolumeCollapsibleButton = ctk.ctkCollapsibleButton()\n inputVolumeCollapsibleButton.text = 'Select Input Volume and Segmentation'\n self.layout.addWidget(inputVolumeCollapsibleButton)\n\n # Layout within the dummy collapsible button\n inputVolumeFormLayout = qt.QFormLayout(inputVolumeCollapsibleButton)\n\n #\n # input volume selector\n #\n self.inputVolumeSelector = slicer.qMRMLNodeComboBox()\n self.inputVolumeSelector.nodeTypes = ['vtkMRMLScalarVolumeNode']\n self.inputVolumeSelector.selectNodeUponCreation = True\n self.inputVolumeSelector.addEnabled = False\n self.inputVolumeSelector.removeEnabled = False\n self.inputVolumeSelector.noneEnabled = False\n self.inputVolumeSelector.showHidden = False\n self.inputVolumeSelector.showChildNodeTypes = False\n self.inputVolumeSelector.setMRMLScene(slicer.mrmlScene)\n self.inputVolumeSelector.setToolTip('Pick the input image for the feature calculation.')\n inputVolumeFormLayout.addRow('Input Image Volume: ', self.inputVolumeSelector)\n\n #\n # input mask volume selector\n #\n self.inputMaskSelector = slicer.qMRMLNodeComboBox()\n self.inputMaskSelector.nodeTypes = ['vtkMRMLLabelMapVolumeNode']\n self.inputMaskSelector.selectNodeUponCreation = True\n self.inputMaskSelector.addEnabled = False\n self.inputMaskSelector.removeEnabled = False\n self.inputMaskSelector.noneEnabled = True\n self.inputMaskSelector.showHidden = False\n self.inputMaskSelector.showChildNodeTypes = False\n self.inputMaskSelector.setMRMLScene(slicer.mrmlScene)\n self.inputMaskSelector.setToolTip('Pick the input mask for the feature calculation.')\n inputVolumeFormLayout.addRow('Input LabelMap: ', self.inputMaskSelector)\n\n #\n # input segmentation selector\n #\n self.inputSegmentationSelector = slicer.qMRMLNodeComboBox()\n self.inputSegmentationSelector.nodeTypes = ['vtkMRMLSegmentationNode']\n self.inputSegmentationSelector.selectNodeUponCreation = True\n self.inputSegmentationSelector.addEnabled = False\n self.inputSegmentationSelector.removeEnabled = False\n self.inputSegmentationSelector.noneEnabled = True\n self.inputSegmentationSelector.showHidden = False\n self.inputSegmentationSelector.showChildNodeTypes = False\n self.inputSegmentationSelector.setMRMLScene(slicer.mrmlScene)\n self.inputSegmentationSelector.setToolTip('Pick the input segmentation for the feature calculation.')\n inputVolumeFormLayout.addRow('Input Segmentation: ', self.inputSegmentationSelector)\n\n def _addCustomizationSection(self):\n customizationCollapsibleButton = ctk.ctkCollapsibleButton()\n customizationCollapsibleButton.text = 'Extraction Customization'\n customizationCollapsibleButton.collapsed = True\n self.layout.addWidget(customizationCollapsibleButton)\n\n customizationFormLayout = qt.QFormLayout(customizationCollapsibleButton)\n\n #\n # Radiobuttons to select customization Type\n #\n\n self.manualCustomizationRadioButton = qt.QRadioButton()\n self.manualCustomizationRadioButton.text = 'Manual Customization'\n self.manualCustomizationRadioButton.checked = True\n customizationFormLayout.layout().addWidget(self.manualCustomizationRadioButton)\n\n self.parameterFileCustomizationRadioButton = qt.QRadioButton()\n self.parameterFileCustomizationRadioButton.text = 'Parameter File Customization'\n self.parameterFileCustomizationRadioButton.checked = False\n customizationFormLayout.layout().addWidget(self.parameterFileCustomizationRadioButton)\n\n #\n # Manual Customization\n #\n self.manualCustomizationGroupBox = qt.QGroupBox('Manual Customization')\n self.manualCustomizationGroupBox.visible = True\n # self.manualCustomizationGroupBox.checkable = True\n customizationFormLayout.addWidget(self.manualCustomizationGroupBox)\n\n manualCustomizationFormLayout = qt.QFormLayout(self.manualCustomizationGroupBox)\n\n # Feature Class section\n featureClassCollapsibleButton = ctk.ctkCollapsibleButton()\n featureClassCollapsibleButton.text = 'Feature Classes'\n featureClassCollapsibleButton.collapsed = False\n manualCustomizationFormLayout.addWidget(featureClassCollapsibleButton)\n\n featureClassLayout = qt.QFormLayout(featureClassCollapsibleButton)\n\n self.featuresLayout = qt.QHBoxLayout()\n featureClassLayout.addRow('Features:', self.featuresLayout)\n\n self.featuresButtonGroup = qt.QButtonGroup(self.featuresLayout)\n self.featuresButtonGroup.exclusive = False\n\n # Get the feature classes dynamically\n self.features = getFeatureClasses().keys()\n # Create a checkbox for each feature\n featureButtons = {}\n for feature in self.features:\n featureButtons[feature] = qt.QCheckBox(feature)\n # TODO: decide which features to enable by default\n featureButtons[feature].checked = False\n if feature == 'firstorder':\n featureButtons[feature].checked = True\n self.featuresButtonGroup.addButton(featureButtons[feature])\n self.featuresLayout.layout().addWidget(featureButtons[feature])\n # set the ID to be the index of this feature in the list\n self.featuresButtonGroup.setId(featureButtons[feature], self.features.index(feature))\n\n # Add buttons to select all or none\n self.buttonsLayout = qt.QHBoxLayout()\n featureClassLayout.addRow('Toggle Features:', self.buttonsLayout)\n\n self.calculateAllFeaturesButton = qt.QPushButton('All Features')\n self.calculateAllFeaturesButton.toolTip = 'Calculate all feature classes.'\n self.calculateAllFeaturesButton.enabled = True\n self.buttonsLayout.addWidget(self.calculateAllFeaturesButton)\n self.calculateNoFeaturesButton = qt.QPushButton('No Features')\n self.calculateNoFeaturesButton.toolTip = 'Calculate no feature classes.'\n self.calculateNoFeaturesButton.enabled = True\n self.buttonsLayout.addWidget(self.calculateNoFeaturesButton)\n\n # Resampling and Filtering\n filteringCollapsibleButton = ctk.ctkCollapsibleButton()\n filteringCollapsibleButton.text = 'Resampling and Filtering'\n filteringCollapsibleButton.collapsed = False\n manualCustomizationFormLayout.addRow(filteringCollapsibleButton)\n # Layout within the dummy collapsible button\n filteringFormLayout = qt.QFormLayout(filteringCollapsibleButton)\n\n # Resampling\n self.resampledVoxelSize = qt.QLineEdit()\n self.resampledVoxelSize.toolTip = 'Three floating-point numbers separated by comma defining the resampled pixel ' \\\n 'size (mm).'\n filteringFormLayout.addRow('Resampled voxel size', self.resampledVoxelSize)\n\n # LoG kernel sizes. default to 5 (?)\n self.logKernelSizes = qt.QLineEdit()\n self.logKernelSizes.toolTip = 'Laplacian of Gaussian filter kernel sizes (mm), separated by comma. ' \\\n 'If empty, no LoG filtering will be applied.'\n filteringFormLayout.addRow('LoG kernel sizes', self.logKernelSizes)\n\n # Wavelet\n self.waveletCheckBox = qt.QCheckBox()\n self.waveletCheckBox.checked = 0\n self.waveletCheckBox.toolTip = 'If checked, PyRadiomics will calculate features on the image after applying ' \\\n 'wavelet transformation'\n filteringFormLayout.addRow('Wavelet-based features', self.waveletCheckBox)\n\n #\n # Feature calculation settings\n #\n settingsCollapsibleButton = ctk.ctkCollapsibleButton()\n settingsCollapsibleButton.text = 'Settings'\n settingsCollapsibleButton.collapsed = False\n manualCustomizationFormLayout.addWidget(settingsCollapsibleButton)\n\n # Layout within the dummy collapsible button\n settingsFormLayout = qt.QFormLayout(settingsCollapsibleButton)\n\n # bin width, defaults to 25\n self.binWidthSliderWidget = ctk.ctkSliderWidget()\n self.binWidthSliderWidget.singleStep = 1\n self.binWidthSliderWidget.decimals = 2\n self.binWidthSliderWidget.minimum = 0.01\n self.binWidthSliderWidget.maximum = 100\n self.binWidthSliderWidget.value = 25\n self.binWidthSliderWidget.toolTip = 'Set the bin width'\n settingsFormLayout.addRow('Bin Width', self.binWidthSliderWidget)\n\n # symmetricalGLCM flag, defaults to false\n self.symmetricalGLCMCheckBox = qt.QCheckBox()\n self.symmetricalGLCMCheckBox.checked = 1\n self.symmetricalGLCMCheckBox.toolTip = 'Use a symmetrical GLCM matrix'\n settingsFormLayout.addRow('Enforce Symmetrical GLCM', self.symmetricalGLCMCheckBox)\n\n #\n # Parameter File Customization\n #\n\n self.parameterCustomizationGroupBox = qt.QGroupBox('Parameter File Customization')\n self.parameterCustomizationGroupBox.visible = False\n # self.parameterCustomizationGroupBox.checkable = True\n customizationFormLayout.addWidget(self.parameterCustomizationGroupBox)\n\n parameterCustomizationFormLayout = qt.QFormLayout(self.parameterCustomizationGroupBox)\n\n # Pathe edit to select parameter file\n self.parameterFilePathLineEdit = ctk.ctkPathLineEdit(filters=ctk.ctkPathLineEdit.Files)\n parameterCustomizationFormLayout.addRow(\"Parameter File\", self.parameterFilePathLineEdit)\n\n def _addOutputSection(self):\n outputCollapsibleButton = ctk.ctkCollapsibleButton()\n outputCollapsibleButton.text = 'Output'\n self.layout.addWidget(outputCollapsibleButton)\n\n outputFormLayout = qt.QFormLayout(outputCollapsibleButton)\n\n # verbose logging flag, defaults to false\n self.verboseCheckBox = qt.QCheckBox()\n self.verboseCheckBox.checked = 0\n self.verboseCheckBox.toolTip = 'If checked, PyRadiomics outputs log messages from level DEBUG and higher ' \\\n '(instead of INFO and higher)'\n outputFormLayout.addRow('Verbose Output', self.verboseCheckBox)\n\n # Output Table\n self.outputTableSelector = slicer.qMRMLNodeComboBox()\n self.outputTableSelector.nodeTypes = ['vtkMRMLTableNode']\n self.outputTableSelector.addEnabled = True\n self.outputTableSelector.selectNodeUponCreation = True\n self.outputTableSelector.renameEnabled = True\n self.outputTableSelector.removeEnabled = True\n self.outputTableSelector.noneEnabled = False\n self.outputTableSelector.setMRMLScene(slicer.mrmlScene)\n self.outputTableSelector.toolTip = 'Select the table where features will be saved, resets feature values on ' \\\n 'each run.'\n outputFormLayout.addRow('Output table:', self.outputTableSelector)\n\n def cleanup(self):\n pass\n\n def onSelect(self):\n self.applyButton.enabled = (\n self.inputVolumeSelector.currentNode() # Input volume selected\n and (self.inputMaskSelector.currentNode() # Some form of segmentation selected\n or self.inputSegmentationSelector.currentNode())\n and (self.manualCustomizationRadioButton.checked # Customization defined\n or os.path.isfile(self.parameterFilePathLineEdit.currentPath))\n )\n\n def onCustomizationTypeCheckedChanged(self):\n self.manualCustomizationGroupBox.visible = self.manualCustomizationRadioButton.checked\n self.parameterCustomizationGroupBox.visible = self.parameterFileCustomizationRadioButton.checked\n\n self.onSelect() # Refresh state of the apply button\n\n def getCheckedFeatureClasses(self):\n checkedFeatures = []\n featureButtons = self.featuresButtonGroup.buttons()\n for featureButton in featureButtons:\n if featureButton.checked:\n featureIndex = self.featuresButtonGroup.id(featureButton)\n feature = self.features[featureIndex]\n checkedFeatures.append(feature)\n return checkedFeatures\n\n def onCalculateAllFeaturesButton(self):\n featureButtons = self.featuresButtonGroup.buttons()\n for featureButton in featureButtons:\n featureButton.checked = True\n\n def onCalculateNoFeaturesButton(self):\n featureButtons = self.featuresButtonGroup.buttons()\n for featureButton in featureButtons:\n featureButton.checked = False\n\n def onApplyButton(self):\n if self.verboseCheckBox.checked:\n # Setup debug logging for the pyradiomics toolbox\n # PyRadiomics logs to stderr by default, which is picked up by slicer and added to the slicer log.\n setVerbosity(logging.DEBUG)\n else:\n setVerbosity(logging.WARNING)\n\n if not self.outputTableSelector.currentNode():\n tableNode = slicer.vtkMRMLTableNode()\n slicer.mrmlScene.AddNode(tableNode)\n self.outputTableSelector.setCurrentNode(tableNode)\n\n logic = SlicerRadiomicsLogic()\n\n # Lock GUI\n self.applyButton.text = 'Working...'\n self.applyButton.setEnabled(False)\n slicer.app.processEvents()\n\n imageNode = self.inputVolumeSelector.currentNode()\n labelNode = self.inputMaskSelector.currentNode()\n segmentationNode = self.inputSegmentationSelector.currentNode()\n\n if self.manualCustomizationRadioButton.checked:\n # Set up customization\n featureClasses = self.getCheckedFeatureClasses()\n settings = {}\n settings['binWidth'] = self.binWidthSliderWidget.value\n settings['symmetricalGLCM'] = self.symmetricalGLCMCheckBox.checked\n\n enabledImageTypes = {'Original': {}}\n\n logKernelSizesValue = self.logKernelSizes.text\n if logKernelSizesValue:\n try:\n enabledImageTypes['LoG'] = {'sigma': [float(i) for i in logKernelSizesValue.split(',')]}\n except:\n self.logger.error('Failed to parse LoG sigma value from string \\\"' + logKernelSizesValue + '\\\"')\n traceback.print_exc()\n return\n\n resampledVoxelSizeValue = self.resampledVoxelSize.text\n if resampledVoxelSizeValue:\n try:\n settings['resampledPixelSpacing'] = [float(i) for i in resampledVoxelSizeValue.split(',')]\n except:\n self.logger.error('Failed to parse resampled voxel spacing from string \\\"' + resampledVoxelSizeValue + '\\\"')\n settings['resampledPixelSpacing'] = None\n traceback.print_exc()\n return\n\n if self.waveletCheckBox.checked:\n enabledImageTypes['Wavelet'] = {}\n\n # Compute features\n try:\n featuresDict = logic.run(imageNode, labelNode, segmentationNode, featureClasses, settings, enabledImageTypes)\n logic.exportToTable(featuresDict, self.outputTableSelector.currentNode())\n except:\n self.logger.error(\"Feature calculation failed.\")\n traceback.print_exc()\n\n else:\n # Compute Features\n try:\n parameterFile = self.parameterFilePathLineEdit.currentPath\n featuresDict = logic.runWithParameterFile(imageNode, labelNode, segmentationNode, parameterFile)\n logic.exportToTable(featuresDict, self.outputTableSelector.currentNode())\n except:\n self.logger.error(\"Feature calculation failed.\")\n traceback.print_exc()\n\n # Unlock GUI\n self.applyButton.setEnabled(True)\n self.applyButton.text = 'Apply'\n\n # Show results\n logic.showTable(self.outputTableSelector.currentNode())\n\n\n#\n# SlicerRadiomicsLogic\n#\n\nclass SlicerRadiomicsLogic(ScriptedLoadableModuleLogic):\n \"\"\"This class should implement all the actual\n computation done by your module. The interface\n should be such that other python code can import\n this class and make use of the functionality without\n requiring an instance of the Widget.\n Uses ScriptedLoadableModuleLogic base class, available at:\n https://github.com/Slicer/Slicer/blob/master/Base/Python/slicer/ScriptedLoadableModule.py\n \"\"\"\n\n def __init__(self):\n self.featureValues = {}\n\n self.logger = logging.getLogger('radiomics.slicer')\n\n self.logger.debug('Slicer Radiomics logic initialized')\n\n def hasImageData(self, volumeNode):\n \"\"\"This is an example logic method that\n returns true if the passed in volume\n node has valid image data\n \"\"\"\n self.logger.debug('Checking if volume has image data')\n\n if not volumeNode:\n self.logger.debug('hasImageData failed: no volume node')\n return False\n if volumeNode.GetImageData() is None:\n self.logger.debug('hasImageData failed: no image data in volume node')\n return False\n return True\n\n def prepareLabelsFromLabelmap(self, labelmapNode, grayscaleImage, labelsDict):\n\n combinedLabelImage = sitk.ReadImage(sitkUtils.GetSlicerITKReadWriteAddress(labelmapNode.GetName()))\n resampledLabelImage = self.resampleITKLabel(combinedLabelImage, grayscaleImage)\n\n ls = sitk.LabelStatisticsImageFilter()\n ls.Execute(resampledLabelImage, resampledLabelImage)\n th = sitk.BinaryThresholdImageFilter()\n th.SetInsideValue(1)\n th.SetOutsideValue(0)\n\n for l in ls.GetLabels()[1:]:\n th.SetUpperThreshold(l)\n th.SetLowerThreshold(l)\n labelsDict[labelmapNode.GetName() + \"_label_\" + str(l)] = th.Execute(combinedLabelImage)\n\n return labelsDict\n\n def prepareLabelsFromSegmentation(self, segmentationNode, grayscaleImage, labelsDict):\n import vtkSegmentationCorePython as vtkSegmentationCore\n segLogic = slicer.modules.segmentations.logic()\n\n segmentation = segmentationNode.GetSegmentation()\n binaryRepresentationDef = vtkSegmentationCore.vtkSegmentationConverter.GetSegmentationBinaryLabelmapRepresentationName()\n if not segmentation.ContainsRepresentation(binaryRepresentationDef):\n segmentation.CreateRepresentation(binaryRepresentationDef)\n\n segmentLabelmapNode = slicer.vtkMRMLLabelMapVolumeNode()\n slicer.mrmlScene.AddNode(segmentLabelmapNode)\n\n for segmentID in range(segmentation.GetNumberOfSegments()):\n segment = segmentation.GetNthSegment(segmentID)\n segmentLabelmap = segment.GetRepresentation(\n vtkSegmentationCore.vtkSegmentationConverter.GetSegmentationBinaryLabelmapRepresentationName())\n if not segLogic.CreateLabelmapVolumeFromOrientedImageData(segmentLabelmap, segmentLabelmapNode):\n self.logger.error(\"Failed to convert label map\")\n return labelsDict\n labelmapImage = sitk.ReadImage(sitkUtils.GetSlicerITKReadWriteAddress(segmentLabelmapNode.GetName()))\n labelmapImage = self.resampleITKLabel(labelmapImage, grayscaleImage)\n labelsDict[segmentationNode.GetName() + \"_segment_\" + segment.GetName()] = labelmapImage\n\n displayNode = segmentLabelmapNode.GetDisplayNode()\n if displayNode:\n slicer.mrmlScene.RemoveNode(displayNode)\n slicer.mrmlScene.RemoveNode(segmentLabelmapNode)\n\n return labelsDict\n\n def calculateFeatures(self, imageNode, labelNode, segmentationNode, extractor):\n \"\"\"\n Calculate the feature on the image node for each ROI contained in the labelNode and/or the segmentation node, using\n an instantiated RadiomicsFeatureExtractor (with customization already configured).\n \"\"\"\n # Prepare the input volume\n self.logger.debug('Read the input image node')\n grayscaleImage = sitk.ReadImage(sitkUtils.GetSlicerITKReadWriteAddress(imageNode.GetName()))\n\n # Prepare the input label map\n self.logger.debug('Read and prepare the input ROI(s)')\n labelsDict = {}\n if labelNode:\n labelsDict = self.prepareLabelsFromLabelmap(labelNode, grayscaleImage, labelsDict)\n if segmentationNode:\n labelsDict = self.prepareLabelsFromSegmentation(segmentationNode, grayscaleImage, labelsDict)\n\n # Calculate the features\n featuresDict = {}\n for l in labelsDict.keys():\n self.logger.debug(\"Calculating features for \" + l)\n try:\n self.logger.debug('Starting feature calculation')\n featuresDict[l] = extractor.execute(grayscaleImage, labelsDict[l])\n self.logger.debug('Features calculated')\n except:\n self.logger.error('calculateFeatures() failed')\n traceback.print_exc()\n\n return featuresDict\n\n def exportToTable(self, featuresDict, table):\n \"\"\"\n Export features to table node\n \"\"\"\n self.logger.debug('Exporting to table')\n tableWasModified = table.StartModify()\n table.RemoveAllColumns()\n\n # Define table columns\n for k in ['Label', 'Image type', 'Feature Class', 'Feature Name', 'Value']:\n col = table.AddColumn()\n col.SetName(k)\n # Fill columns\n for label, features in featuresDict.items():\n for featureKey, featureValue in features.items():\n processingType, featureClass, featureName = str(featureKey).split(\"_\", 3)\n rowIndex = table.AddEmptyRow()\n table.SetCellText(rowIndex, 0, label)\n table.SetCellText(rowIndex, 1, processingType)\n table.SetCellText(rowIndex, 2, featureClass)\n table.SetCellText(rowIndex, 3, featureName)\n table.SetCellText(rowIndex, 4, str(featureValue))\n\n table.Modified()\n table.EndModify(tableWasModified)\n\n def showTable(self, table):\n \"\"\"\n Switch to a layout where tables are visible and show the selected one.\n \"\"\"\n self.logger.debug('Showing table')\n currentLayout = slicer.app.layoutManager().layout\n layoutWithTable = slicer.modules.tables.logic().GetLayoutWithTable(currentLayout)\n slicer.app.layoutManager().setLayout(layoutWithTable)\n slicer.app.applicationLogic().GetSelectionNode().SetReferenceActiveTableID(table.GetID())\n slicer.app.applicationLogic().PropagateTableSelection()\n\n def resampleITKLabel(self, image, reference):\n resampler = sitk.ResampleImageFilter()\n resampler.SetInterpolator(sitk.sitkNearestNeighbor)\n resampler.SetReferenceImage(reference)\n return resampler.Execute(image)\n\n def run(self, imageNode, labelNode, segmentationNode, featureClasses, settings, enabledImageTypes):\n \"\"\"\n Run the actual algorithm\n \"\"\"\n self.logger.info('Feature extraction started')\n\n self.logger.debug('Instantiating the extractor')\n\n extractor = featureextractor.RadiomicsFeaturesExtractor(**settings)\n\n self.logger.debug('Setting the enabled feature classes')\n extractor.disableAllFeatures()\n for feature in featureClasses:\n extractor.enableFeatureClassByName(feature)\n\n self.logger.debug('Setting the enabled image types')\n extractor.disableAllImageTypes()\n for imageType in enabledImageTypes:\n extractor.enableImageTypeByName(imageType, customArgs=enabledImageTypes[imageType])\n\n return self.calculateFeatures(imageNode, labelNode, segmentationNode, extractor)\n\n def runWithParameterFile(self, imageNode, labelNode, segmentationNode, parameterFilePath):\n \"\"\"\n Run the actual algorithm using the provided customization file and provided image and region of interest(s) (ROIs)\n\n :param imageNode: Slicer Volume node representing the image from which features should be extracted\n :param labelNode: Slicer Labelmap node containing the ROIs as integer encoded volume (voxel value indicates ROI id)\n :param segmentationNode: Slicer segmentation node containing the segments of the ROIs (will be converted to binary\n label maps)\n :param parameterFilePath: String file path pointing to the parameter file used to customize the extraction\n :return: Dictionary containing the extracted features for each ROI\n \"\"\"\n self.logger.info('Feature extraction started')\n\n self.logger.debug('Instantiating the extractor')\n\n # Instantiate the extractor with the specified customization file. If this file is invalid in any way, this call\n # will raise an error.\n extractor = featureextractor.RadiomicsFeaturesExtractor(parameterFilePath)\n\n return self.calculateFeatures(imageNode, labelNode, segmentationNode, extractor)\n\n\n# noinspection PyAttributeOutsideInit\nclass SlicerRadiomicsTest(ScriptedLoadableModuleTest):\n \"\"\"\n This is the test case for your scripted module.\n Uses ScriptedLoadableModuleTest base class, available at:\n https://github.com/Slicer/Slicer/blob/master/Base/Python/slicer/ScriptedLoadableModule.py\n \"\"\"\n\n def setUp(self):\n \"\"\" Do whatever is needed to reset the state - typically a scene clear will be enough.\n \"\"\"\n self.logger = logging.getLogger('radiomics.slicer')\n\n slicer.mrmlScene.Clear(0)\n\n def runTest(self):\n \"\"\"Run as few or as many tests as needed here.\n \"\"\"\n self.setUp()\n self.test_SlicerRadiomics1()\n\n def test_SlicerRadiomics1(self):\n \"\"\" Ideally you should have several levels of tests. At the lowest level\n tests should exercise the functionality of the logic with different inputs\n (both valid and invalid). At higher levels your tests should emulate the\n way the user would interact with your code and confirm that it still works\n the way you intended.\n One of the most important features of the tests is that it should alert other\n developers when their changes will have an impact on the behavior of your\n module. For example, if a developer removes a feature that you depend on,\n your test should break so they know that the feature is needed.\n \"\"\"\n\n self.delayDisplay('Starting the test')\n #\n # first, get some data\n # https://github.com/Radiomics/SlicerRadiomics/releases/download/TestData-v1.0.0/lung1_binary.seg.nrrd\n import urllib\n dataRelease = 'v1.0.0'\n dataURLPrefix = 'https://github.com/Radiomics/SlicerRadiomics/releases/download/TestData'\n dataItems = (('lung1_image.nrrd', slicer.util.loadVolume),\n ('lung1_label.nrrd', slicer.util.loadLabelVolume),\n ('lung1_binary.seg.nrrd', slicer.util.loadSegmentation),\n ('lung1.seg_0.vtp', None),\n ('lung1.seg_1.vtp', None),\n ('lung1_surface.seg.vtm', slicer.util.loadSegmentation),\n ('Params.yaml', None))\n\n for item, loader in dataItems:\n url = dataURLPrefix + '-' + dataRelease + '/' + item\n filePath = os.path.join(slicer.app.temporaryPath, item)\n if not os.path.exists(filePath) or os.stat(filePath).st_size == 0:\n self.logger.info('Requesting download %s from %s...\\n' % (item, url))\n self.assertTrue(urllib.urlretrieve(url, filePath), 'Failed to download from ' + url)\n if loader:\n self.logger.info('Loading %s from %s...' % (item, filePath))\n self.assertTrue(loader(filePath), 'Failed to load ' + item)\n\n self.delayDisplay(\n 'Finished with download and loading %d volumes' % (slicer.mrmlScene.GetNumberOfNodesByClass('vtkMRMLVolumeNode')))\n\n grayscaleNode = slicer.util.getNode(pattern='lung1_image')\n labelmapNode = slicer.util.getNode(pattern='lung1_label')\n binaryNode = slicer.util.getNode(pattern='lung1_binary')\n surfaceNode = slicer.util.getNode(pattern='lung1_surface')\n\n parameterFile = os.path.join(slicer.app.temporaryPath, 'Params.yaml')\n\n logic = SlicerRadiomicsLogic()\n self.assertIsNotNone(logic.hasImageData(grayscaleNode))\n self.assertIsNotNone(logic.hasImageData(labelmapNode))\n\n featureClasses = ['firstorder']\n settings = {}\n settings['binWidth'] = 25\n settings['symmetricalGLCM'] = False\n settings['label'] = 1\n\n enabledImageTypes = {\"Original\": {}}\n\n for segNode in [binaryNode, surfaceNode]:\n featuresDict = logic.run(grayscaleNode, labelmapNode, segNode, featureClasses, settings, enabledImageTypes)\n\n tableNode = slicer.vtkMRMLTableNode()\n tableNode.SetName('lung1_label and ' + segNode.GetName())\n slicer.mrmlScene.AddNode(tableNode)\n logic.exportToTable(featuresDict, tableNode)\n logic.showTable(tableNode)\n\n featuresDict = logic.runWithParameterFile(grayscaleNode, labelmapNode, binaryNode, parameterFile)\n\n tableNode = slicer.vtkMRMLTableNode()\n tableNode.SetName('lung1_label and ' + binaryNode.GetName() + ' customized with Params.yaml')\n slicer.mrmlScene.AddNode(tableNode)\n logic.exportToTable(featuresDict, tableNode)\n logic.showTable(tableNode)\n\n self.delayDisplay('Test passed!')\n","sub_path":"SlicerRadiomics/SlicerRadiomics.py","file_name":"SlicerRadiomics.py","file_ext":"py","file_size_in_byte":30768,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"44782907","text":"#!/usr/bin/env python3\n\n\n\ndef test_sat():\n\n # \n # [<<< table of contents](index.html)\n #\n # ---\n #\n # Constraint satisfier\n # ====================\n # \n # \n # \n\n\n from bruhat.render.sat import Variable, Solver, System\n \n x = Variable('x')\n y = Variable('y')\n z = Variable('z')\n\n items = [\n x+y >= 1.,\n x+z == 5,\n y >= 3.\n ]\n\n solver = Solver(items)\n\n result = solver.solve()\n print(result)\n\n system = System()\n v = system.get_var()\n u = system.get_var()\n w = system.get_var()\n system.add(v+u+w == 3.)\n system.solve()\n print(system[v] + system[u] + system[w])\n\n\nif __name__ == \"__main__\":\n\n test_variable()\n \n\n\n","sub_path":"bruhat/render/doc/test_sat.py","file_name":"test_sat.py","file_ext":"py","file_size_in_byte":720,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"230730265","text":"print(\"enter the number to get fibonacci series\")\r\nn=int(input())\r\nx=0;y=1;\r\nif n==1:\r\n print(x)\r\nelse:\r\n print(x)\r\n print(y)\r\n for i in range(2,n):\r\n s=x+y\r\n print(s)\r\n x=y\r\n y=s\r\n \r\n \r\n","sub_path":"fibonacci.py","file_name":"fibonacci.py","file_ext":"py","file_size_in_byte":233,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"143125859","text":"# -*- coding: utf-8 -*-\n# @Time : 2017/6/26 上午12:24\n# @Author : fj\n# @Site : \n# @File : test_saver.py\n# @Software: PyCharm\n\nimport pandas as pd\nimport tensorflow as tf\nfrom sklearn.model_selection import train_test_split\n\ndata = pd.read_csv('./data/train.csv')\ndata = data.fillna(0) #填充缺失数据\ndata['Sex'] = data['Sex'].apply(lambda s: 1 if s == 'male' else 0)\ndata['Deceased'] = data['Survived'].apply(lambda s: int(not s))\n\ndataset_x = data[['Sex', 'Age', 'Pclass', 'SibSp', 'Parch', 'Fare']].as_matrix()\ndataset_y = data[['Deceased', 'Survived']].as_matrix()\n\nx_train, x_test, y_train, y_test = train_test_split(dataset_x, dataset_y, test_size=0.2, random_state=42) #random_state随机种子\n\nx = tf.placeholder(tf.float32, shape=[None, 6], name='x')\ny = tf.placeholder(tf.float32, shape=[None, 2], name='y')\n\nW = tf.Variable(tf.random_normal([6, 2]), name='weights')\nb = tf.Variable(tf.zeros([2]), name='bias')\n\ny_pred = tf.nn.softmax(tf.matmul(x, W) + b)\nwith tf.Session() as sess:\n # init = tf.global_variables_initializer()\n # sess.run(init)\n saver = tf.train.Saver()\n saver.restore(sess, 'model.ckpt')\n correct_pred = tf.equal(tf.argmax(y, 1), tf.argmax(y_pred, 1))\n acc_op = tf.reduce_mean(tf.cast(correct_pred, tf.float32))\n accuracy = sess.run(acc_op, feed_dict={x: x_test, y: y_test})\n print(\"Accuracy on validation set: %.9f\" % accuracy)","sub_path":"2. titanic/test_saver.py","file_name":"test_saver.py","file_ext":"py","file_size_in_byte":1397,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"627490128","text":"# Splits the heaer value into seperate dimension items\r\ndef spreadHeader(header):\r\n header = str(header)\r\n \r\n # ...sigh\r\n header = header.replace('Ouward', 'Outward')\r\n \r\n \r\n cells = header.split(' ')\r\n \r\n # Drop pointless things\r\n cells = [x for x in cells if x != ':£m'] # dont care. 'Value' in a paired dimension covers it.\r\n\r\n \r\n # if their are any colons left its fully delimited, use it\r\n if len([x for x in header.split(' ') if ':' in x]) > 1:\r\n dimRow = header.split(':')\r\n dimRow = [x for x in dimRow if x != '£m'] # still dont care\r\n \r\n \r\n # From here its just text pasrsing to match up the different pattersn\r\n elif 'Total' in cells and '&' in cells:\r\n dimRow = [cells[0] + ' ' + cells[1] + ' ' + cells[2], cells[3] + ' ' + cells[4], cells[5], cells[6]]\r\n #assert len(cells) == 7, \"Parse 1 wasting\"\r\n \r\n \r\n elif '&' in cells:\r\n dimRow = [cells[0] + ' ' + cells[1] + ' ' + cells[2], cells[3], cells[4], cells[5]]\r\n #assert len(cells) == 6, \"Parse 2 wasting\"\r\n \r\n \r\n elif 'Other' in cells[0]:\r\n dimRow = [cells[0] + ' ' + cells[1], cells[2], cells[3], cells[4]]\r\n \r\n \r\n elif 'Total' in cells:\r\n dimRow = [cells[0] + ' ' + cells[1], cells[2], cells[3], cells[4]]\r\n #assert len(cells) == 5, \"Parse 3 wasting\"\r\n \r\n else:\r\n dimRow = [cells[0], cells[1], cells[2], cells[3]]\r\n \r\n return dimRow\r\n\r\n\r\n# Spread the dim items from the header into V4 style\r\ndef colToV4(df, col):\r\n \r\n \"\"\"\r\n The actual obsCol taken from the DF is the observation\r\n The header text is spread to create the dims\r\n \"\"\"\r\n dimRow = spreadHeader(col)\r\n \r\n newDf = pd.DataFrame()\r\n \r\n newDf['V4_0'] = df[col][6:] # skip the CDID\r\n \r\n newDf['Time_codelist'] = 'Year'\r\n newDf['Time'] = df['Title'][6:]\r\n \r\n # Switch the time type if quartes are involved\r\n newDf['Time_codelist'][newDf['Time'].str.contains('Q')] = 'Quarter'\r\n \r\n newDf['Geography_codelist'] = 'K02000001'\r\n newDf['Geography'] = ''\r\n \r\n newDf['d1#_codelist'] = ''\r\n newDf['d1#'] = dimRow[0]\r\n \r\n newDf['d2#_codelist'] = ''\r\n newDf['d2#'] = dimRow[1]\r\n \r\n newDf['d3#_codelist'] = ''\r\n newDf['d3#'] = dimRow[2]\r\n \r\n # Optional. Not all columns have 4 dims so set to 'unspecified' to keep the shape\r\n if len(dimRow) < 4:\r\n newDf['d4#_codelist'] = ''\r\n newDf['d4#'] = 'UnSpecified'\r\n else:\r\n newDf['d4#_codelist'] = ''\r\n newDf['d4#'] = dimRow[3]\r\n \r\n \r\n newDf.fillna('', inplace=True)\r\n \r\n #newDf['sanityCheck'] = col\r\n\r\n return newDf\r\n\r\n\r\n# Takes a dataframe and a dict of what we want the column headers\r\ndef buildHeaders(df, Ovr):\r\n newHeaders = []\r\n \r\n for key in Ovr.keys():\r\n if Ovr[key] == 'DROPME':\r\n df = df.drop(key, axis=1)\r\n df = df.drop(key + '_codelist', axis=1)\r\n \r\n # Replace/fix headers\r\n for col in df.columns.values: # 1 at a time for order\r\n for key in Ovr.keys():\r\n if key in col:\r\n col = col.replace(key, Ovr[key])\r\n newHeaders.append(col)\r\n df.columns = newHeaders\r\n return df\r\n \r\n \r\nimport pandas as pd\r\nimport sys\r\n\r\n\r\n##########\r\n## MAIN ##\r\n##########\r\n\r\n\"\"\"\r\nCreate an inlcudes-everything \"main\" dataframe with holding dimensions d1#, d2#, d3#, d4# for topics.\r\nEverything we want can be sliced out of that.\r\n\"\"\"\r\n\r\ninFile = sys.argv[1]\r\n\r\ndf = pd.read_csv(inFile)\r\n\r\nmainDf = []\r\nfor col in df.columns.values[1:]:\r\n newDf = colToV4(df, col)\r\n mainDf.append(newDf)\r\n\r\nmainDf = pd.concat(mainDf)\r\nmainDf.fillna('', inplace=True) # pesky nans\r\n\r\n# Get rid of blank observations\r\nmainDf = mainDf[mainDf['V4_0'] != '']\r\n\r\n\r\n\r\n###########################################################\r\n### Getting Countries based Values and Numbers Datasets ###\r\n###########################################################\r\n\r\n# Countries is all rows that dont have 'M&A' for topic d1#\r\ndf = mainDf[mainDf['d1#'].map(lambda x: x.strip() != 'M&A')]\r\nOvr = {\r\n 'd1#':'Country',\r\n 'd2#':'Flow',\r\n 'd3#':'M&A',\r\n 'd4#':'Measure',\r\n}\r\ndf = buildHeaders(df, Ovr)\r\n\r\n# Tidy up \"Value:\" into \"Value\" for the measure dimension\r\ndf['Measure'][df['Measure'] == 'Value:'] = 'Value'\r\n\r\n\r\n# Now we split them into \"Values\" and \"Numbers\" dataset based on whats in the 'measure' dimension\r\n\r\n# -- Value\r\nvalDf = df[df['Measure'] == 'Value']\r\nvalDf = valDf.drop('Measure', axis=1) # drop 'measure', its served its purpose\r\nvalDf = valDf.drop('Measure_codelist', axis=1)\r\nvalDf.to_csv('Mergers and Acquisition, Value of by County.csv', index=False)\r\n\r\n\r\n# -- Numbers\r\nvalDf = df[df['Measure'] == 'Number']\r\nvalDf = valDf.drop('Measure', axis=1) # drop 'measure', its served its purpose\r\nvalDf = valDf.drop('Measure_codelist', axis=1)\r\nvalDf.to_csv('Mergers and Acquisition, Number of by County.csv', index=False)\r\n\r\n\r\n\r\n###############################\r\n### Other Numeric Measures ###\r\n###############################\r\n\r\n# Mergers and Acquisitions, Numbers\r\ndf = mainDf[mainDf['d3#'].map(lambda x: 'number' in x.strip().lower())]\r\nOvr = {\r\n 'd1#':'DROPME', # M&A\r\n 'd2#':'Flow', # \r\n 'd3#':'Transactions', # \r\n 'd4#':'DROPME',\r\n}\r\ndf = buildHeaders(df, Ovr)\r\n\r\n\r\n# Split out mergers from disposals. Doing it here as some are not clearly delimited.\r\ndf['Merger or Acquisition_codelist'] = ''\r\ndf['Merger or Acquisition'] = ''\r\ndf['Merger or Acquisition'][df['Transactions'].map(lambda x: 'acqui' in x.lower())] = 'Acquisition'\r\ndf['Merger or Acquisition'][df['Transactions'].map(lambda x: 'disposal' in x.lower())] = 'Disposal'\r\n\r\n# Get rid of' Number of companies acquired'. Its the sole romainint domestic item\r\ndf = df[df['Transactions'] != ' Number of companies acquired']\r\n\r\n# Clean the text\r\nremoveCrap = [' Number of acquisitions ', ' Number of disposals ']\r\nfor rc in removeCrap:\r\n df['Transactions'] = df['Transactions'].map(lambda x: x.replace(rc,''))\r\ndf['Transactions'] = df['Transactions'].map(lambda x: x.replace('-', '').strip().title())\r\n\r\n# Since I used title-caxe I need to correct the national acronyms\r\ndf['Transactions'][df['Transactions'] == 'In Eu'] = 'In EU'\r\ndf['Transactions'][df['Transactions'] == 'In Usa'] = 'In USA'\r\ndf['Transactions'][df['Transactions'] == 'Indirect Funded In Uk'] = 'Indirect Funded In UK'\r\n\r\n# Get rid of (some of the) sparsity\r\ndf['Transactions'][df['Transactions'] == 'Number Of Acquisitions'] = 'Number Of'\r\ndf['Transactions'][df['Transactions'] == 'Number Of Disposals'] = 'Number Of'\r\n\r\n\r\n# whitespace\r\ndf['Flow'] = df['Flow'].map(lambda x: x.strip())\r\n\r\nlisto = df['Flow'].unique()\r\nassert '' not in listo, \"Flow is blank! Should be acquisition or disposal, contains: \" + df['Flow'].unique()\r\n\r\ndf.to_csv('Mergers and Acquisitions - Numbers.csv', index=False)\r\n\r\n\r\n\r\n#############################\r\n### Other Value Measures ###\r\n#############################\r\n\r\n# Mergers and Acquisitions, Value\r\ndf = mainDf[mainDf['d3#'].map(lambda x: 'value' in x.strip().lower())]\r\nOvr = {\r\n 'd1#':'DROPME', # M&A\r\n 'd2#':'DROPME', # \r\n 'd3#':'Transactions', # \r\n 'd4#':'DROPME',\r\n}\r\ndf = buildHeaders(df, Ovr)\r\n\r\n\r\n# Need to get Acqusitions and Displosals from text as its not a dimension in all cases\r\ndf['Flow_codelist'] = ''\r\ndf['Flow'] = ''\r\ndf['Flow'][df['Transactions'].map(lambda x: 'acqui' in x.lower())] = 'Acquisition'\r\ndf['Flow'][df['Transactions'].map(lambda x: 'disposal' in x.lower())] = 'Disposal'\r\n\r\n# Get rid of generic stock data. Doesn't the the cube structure\r\nfor rm in [' Value of ordinary shares ', ' Value of preference & loan stock ']:\r\n df = df[df['Transactions'] != rm]\r\n\r\n# Clean the text\r\nremoveCrap = [' Value of acquisitions ', ' Value of disposals ']\r\nfor rc in removeCrap:\r\n df['Transactions'][df['Transactions'] == rc] = 'Total Value' # it its *just* something from the list its a total\r\n df['Transactions'] = df['Transactions'].map(lambda x: x.replace(rc,'')) # otherwise its in the way\r\ndf['Transactions'] = df['Transactions'].map(lambda x: x.replace('-', '').strip().title())\r\n\r\n# Since I used title-caxe I need to correct the national acronyms\r\ndf['Transactions'][df['Transactions'] == 'In Eu'] = 'In EU'\r\ndf['Transactions'][df['Transactions'] == 'In Usa'] = 'In USA'\r\ndf['Transactions'][df['Transactions'] == 'Indirect Funded In Uk'] = 'Indirect Funded In UK'\r\n\r\nlisto = df['Flow'].unique()\r\nassert '' not in listo, \"Flow is blank! Should be acquisition or disposal, contains: \" + df['Flow'].unique()\r\n\r\ndf.to_csv('Mergers and Acquisitions - Values.csv', index=False)\r\n\r\n\r\n","sub_path":"Mergers and Acquisitions/mergAcq.py","file_name":"mergAcq.py","file_ext":"py","file_size_in_byte":8682,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"640289469","text":"import tkinter as tk\nfrom tkinter import Message, Text\nimport cv2\nimport os\nimport shutil\nimport csv\nimport numpy as np\nfrom PIL import Image, ImageTk\nimport pandas as pd\nimport datetime\nimport time\nimport tkinter.ttk as ttk\nimport tkinter.font as font\n\nwindow = tk.Tk()\nwindow.title(\"Smart Attendance System\")\nwindow.attributes('-fullscreen', True)\ncanvas = tk.Canvas(window, width = 1400, height = 715) \ncanvas.pack() \nimg = ImageTk.PhotoImage(Image.open(\"1.jpg\")) \ncanvas.create_image(0, 0, anchor='nw', image=img) \n\nmessage = tk.Label(window, text=\"Face Recognition Based Smart Attendance System\",\n fg=\"Blue\", width=70, height=1, font=('times', 30, 'italic bold'))\n\nmessage.place(x=0, y=50)\nborder = tk.Label(window, text=\"Welcome to Smart Attendance System || NEW USER : Enter Your Details And Capture Your Picture then Press 'TRAIN IMAGE' || EXISTING USER : Click on 'TRACK IMAGE' after tracking Press 'Q'\",\n width=172, height=1, bg='blue', fg=\"yellow\")\nborder.place(x=0, y=0)\nborder = tk.Label(window, width=1000, height=3, bg='blue')\nborder.place(x=0, y=715)\nlbl = tk.Label(window, text=\"Enter ID\", width=20, height=2,\n fg=\"White\", bg=\"Blue\", font=('times', 15, ' bold '))\nlbl.place(x=300, y=200)\n\ntxt = tk.Entry(window, width=20, bg=\"Blue\", fg=\"white\",\n font=('times', 15, ' bold '))\ntxt.place(x=550, y=215)\n\nlbl2 = tk.Label(window, text=\"Enter Name\", width=20, fg=\"white\",\n bg=\"Blue\", height=2, font=('times', 15, ' bold '))\nlbl2.place(x=300, y=300)\n\ntxt2 = tk.Entry(window, width=20, bg=\"Blue\", fg=\"white\",\n font=('times', 15, ' bold '))\ntxt2.place(x=550, y=315)\n\nlbl3 = tk.Label(window, text=\"Notification : \", width=20,\n fg=\"white\", bg=\"Blue\", height=2, font=('times', 15, ' bold'))\nlbl3.place(x=300, y=400)\n\nmessage = tk.Label(window, text=\"\", bg=\"Blue\", fg=\"white\", width=53,\n height=2, activebackground=\"Blue\", font=('times', 15, ' bold '))\nmessage.place(x=550, y=400)\n\nlbl3 = tk.Label(window, text=\"Attendance : \", width=20, fg=\"white\",\n bg=\"Blue\", height=2, font=('times', 15, ' bold'))\nlbl3.place(x=400, y=580)\n\nmessage2 = tk.Label(window, text=\"\", fg=\"white\", bg=\"Blue\",\n activeforeground=\"green\", width=60, height=2, font=('times', 15, ' bold '))\nmessage2.place(x=620, y=580)\n\n\ndef clear():\n txt.delete(0, 'end')\n res = \"\"\n message.configure(text=res)\n\n\ndef clear2():\n txt2.delete(0, 'end')\n res = \"\"\n message.configure(text=res)\n\n\ndef is_number(s):\n try:\n float(s)\n return True\n except ValueError:\n pass\n\n try:\n import unicodedata\n unicodedata.numeric(s)\n return True\n except (TypeError, ValueError):\n pass\n\n return False\n\n\ndef TakeImages():\n Id = (txt.get())\n name = (txt2.get())\n if(is_number(Id) and name.isalpha()):\n cam = cv2.VideoCapture(0)\n harcascadePath = \"haarcascade_frontalface_default.xml\"\n detector = cv2.CascadeClassifier(harcascadePath)\n sampleNum = 0\n while(True):\n ret, img = cam.read()\n gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n faces = detector.detectMultiScale(gray, 1.3, 5)\n for (x, y, w, h) in faces:\n cv2.rectangle(img, (x, y), (x+w, y+h), (255, 0, 0), 2)\n # incrementing sample number\n sampleNum = sampleNum+1\n # saving the captuwhite face in the dataset folder TrainingImage\n cv2.imwrite(\"TrainingImage/ \"+name + \".\"+Id + '.' +\n str(sampleNum) + \".jpg\", gray[y:y+h, x:x+w])\n # display the frame\n cv2.imshow('Capture Image', img)\n # wait for 100 miliseconds\n if cv2.waitKey(100) & 0xFF == ord('q'):\n break\n # break if the sample number is morethan 100\n elif sampleNum > 60:\n break\n cam.release()\n cv2.destroyAllWindows()\n # res = \"Images Saved for ID : \" + Id +\" Name : \"+ name\n row = [Id, name]\n with open('StudentDetails/StudentDetails.csv', 'a+') as csvFile:\n writer = csv.writer(csvFile)\n writer.writerow(row)\n csvFile.close()\n res = \"Picture Captured Successfully\"\n message.configure(text=res)\n else:\n if(is_number(Id)):\n res = \"Enter Alphabetical Name\"\n message.configure(text=res)\n if(name.isalpha()):\n res = \"Enter Numeric Id\"\n message.configure(text=res)\n\n\ndef TrainImages():\n recognizer = cv2.face_LBPHFaceRecognizer.create()\n harcascadePath = \"haarcascade_frontalface_default.xml\"\n detector = cv2.CascadeClassifier(harcascadePath)\n faces, Id = getImagesAndLabels(\"TrainingImage\")\n recognizer.train(faces, np.array(Id))\n recognizer.save(\"TrainingImageLabel/Trainner.yml\")\n res = \"Image Trained\"\n message.configure(text=res)\n\n\ndef getImagesAndLabels(path):\n # get the path of all the files in the folder\n imagePaths = [os.path.join(path, f) for f in os.listdir(path)]\n # create empty face list\n faces = []\n # create empty ID list\n Ids = []\n # now looping through all the image paths and loading the Ids and the images\n for imagePath in imagePaths:\n # loading the image and converting it to gray scale\n pilImage = Image.open(imagePath).convert('L')\n # Now we are converting the PIL image into numpy array\n imageNp = np.array(pilImage, 'uint8')\n # getting the Id from the image\n Id = int(os.path.split(imagePath)[-1].split(\".\")[1])\n # extract the face from the training image sample\n faces.append(imageNp)\n Ids.append(Id)\n return faces, Ids\n\n\ndef TrackImages():\n recognizer = cv2.face.LBPHFaceRecognizer_create()\n recognizer.read(\"TrainingImageLabel/Trainner.yml\")\n harcascadePath = \"haarcascade_frontalface_default.xml\"\n faceCascade = cv2.CascadeClassifier(harcascadePath)\n df = pd.read_csv(\"StudentDetails/StudentDetails.csv\")\n cam = cv2.VideoCapture(0)\n font = cv2.FONT_HERSHEY_SIMPLEX\n col_names = ['Id', 'Name', 'Date', 'Time']\n attendance = pd.DataFrame(columns=col_names)\n while True:\n ret, im = cam.read()\n gray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)\n faces = faceCascade.detectMultiScale(gray, 1.2, 5)\n for(x, y, w, h) in faces:\n cv2.rectangle(im, (x, y), (x+w, y+h), (225, 0, 0), 2)\n Id, conf = recognizer.predict(gray[y:y+h, x:x+w])\n if(conf < 50):\n ts = time.time()\n date = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d')\n timeStamp = datetime.datetime.fromtimestamp(\n ts).strftime('%H:%M:%S')\n aa = df.loc[df['Id'] == Id]['Name'].values\n tt = str(Id)+\" - \"+aa\n attendance.loc[len(attendance)] = [Id, aa, date, timeStamp]\n res=str(tt)+\" Your Present In Confirmed !\"\n else:\n Id = 'Unknown'\n tt = str(Id)\n res = \"NO KNOWN FACE FOUND ! RETRY !!!\"\n if(conf > 75):\n res = \"NO KNOWN FACE FOUND ! RETRY !!!\"\n noOfFile = len(os.listdir(\"ImagesUnknown\"))+1\n cv2.imwrite(\"ImagesUnknown/Image\"+str(noOfFile) +\n \".jpg\", im[y:y+h, x:x+w])\n cv2.putText(im, str(tt), (x, y+h), font, 1, (255, 255, 255), 2)\n attendance = attendance.drop_duplicates(subset=['Id'], keep='first')\n cv2.imshow('Tracking', im)\n if (cv2.waitKey(1) == ord('q')):\n break\n attendance = attendance.drop_duplicates(subset=['Id'], keep='first')\n ts = time.time()\n date = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d')\n timeStamp = datetime.datetime.fromtimestamp(ts).strftime('%H:%M:%S')\n Hour, Minute, Second = timeStamp.split(\":\")\n fileName = \"Attendance/Attendance_\"+date+\"_\"+Hour+\"-\"+Minute+\"-\"+Second+\".csv\"\n attendance.to_csv(fileName, index=False)\n cam.release()\n cv2.destroyAllWindows()\n # res=attendance\n message2.configure(text=res)\n\n\nclearButton = tk.Button(window, text=\"Clear\", command=clear, fg=\"white\", bg=\"Blue\",\n width=20, height=2, activebackground=\"white\", font=('times', 15, ' bold '))\nclearButton.place(x=850, y=200)\nclearButton2 = tk.Button(window, text=\"Clear\", command=clear2, fg=\"white\", bg=\"Blue\",\n width=20, height=2, activebackground=\"white\", font=('times', 15, ' bold '))\nclearButton2.place(x=850, y=300)\ntakeImg = tk.Button(window, text=\"Take Images\", command=TakeImages, fg=\"white\", bg=\"Blue\",\n width=20, height=2, activebackground=\"white\", font=('times', 15, ' bold '))\ntakeImg.place(x=180, y=500)\ntrainImg = tk.Button(window, text=\"Train Images\", command=TrainImages, fg=\"white\",\n bg=\"Blue\", width=20, height=2, activebackground=\"white\", font=('times', 15, ' bold '))\ntrainImg.place(x=480, y=500)\ntrackImg = tk.Button(window, text=\"Track Images\", command=TrackImages, fg=\"white\",\n bg=\"Blue\", width=20, height=2, activebackground=\"white\", font=('times', 15, ' bold '))\ntrackImg.place(x=780, y=500)\nquitWindow = tk.Button(window, text=\"Quit\", command=window.destroy, fg=\"white\", bg=\"Blue\",\n width=20, height=2, activebackground=\"white\", font=('times', 15, ' bold '))\nquitWindow.place(x=1080, y=500)\ncopyWrite = tk.Label(window, text=\"Created By BUIE CSE GROUP \\n (Amit_Kabi,Amit_Goswami,Suman_Mandal,Tapas_Pal,Ayan_Mandal)\",\n bg=\"Blue\", fg=\"white\", width=100, height=2, activebackground=\"Blue\", font=('times', 12, ' bold '))\ncopyWrite.place(x=300, y=715)\n\nwindow.mainloop()\n","sub_path":"Face-Recognition-Based-Attendance-System-master/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":9836,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"105032380","text":"#\n# Copyright (c) 2018 Red Hat\n# Licensed under The MIT License (MIT)\n# https://opensource.org/licenses/MIT\n#\nfrom contrib import drf_introspection\n\nfrom django_filters import NumberFilter\n\nLOOKUP_TYPES = {\n 'icontains': 'case insensitive, substring match',\n 'contains': 'substring match',\n 'iexact': 'case insensitive',\n}\n\n\ndef get_filters(view):\n \"\"\"\n For a given view set returns which query filters are available for it a\n Markdown formatted list. The list does not include query filters specified\n on serializer or query arguments used for paging.\n \"\"\"\n allowed_keys = drf_introspection.get_allowed_query_params(view)\n filter_class = getattr(view, 'filter_class', None)\n filterset = filter_class() if filter_class is not None else None\n filterset_fields = filterset.filters if filterset is not None else []\n filter_fields = set(getattr(view, 'filter_fields', []))\n extra_query_params = set(getattr(view, 'extra_query_params', []))\n\n filters = []\n for key in sorted(allowed_keys):\n if key in filterset_fields:\n # filter defined in FilterSet\n filter = filterset_fields.get(key)\n filters.append(_get_filter(key, filter))\n elif key in filter_fields or key in extra_query_params:\n # filter defined in viewset directly; type depends on model, not easily available\n filters.append(' * `%s`' % key)\n # else filter defined somewhere else and not relevant here (e.g.\n # serializer or pagination settings).\n\n return '\\n'.join(filters)\n\n\ndef _get_filter_option(filter, option_name):\n value = getattr(filter, option_name, '') or filter.extra.get(option_name, '')\n return value.rstrip()\n\n\ndef _get_filter(filter_name, filter):\n filter_type = _get_filter_option(filter, 'doc_format')\n if not filter_type:\n if isinstance(filter, NumberFilter):\n filter_type = 'int'\n else:\n filter_type = 'string'\n\n lookup_type = LOOKUP_TYPES.get(filter.lookup_expr)\n if lookup_type:\n lookup_type = ', %s' % lookup_type\n\n result = ' * `%s` (%s%s)' % (filter_name, filter_type, lookup_type or '')\n help_text = _get_filter_option(filter, 'help_text')\n if help_text:\n result += ' ' + help_text\n\n return result\n","sub_path":"pdc/apps/common/renderers_filters.py","file_name":"renderers_filters.py","file_ext":"py","file_size_in_byte":2292,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"602599401","text":"import copy\nimport torch\nimport torch.nn as nn\nfrom torchvision import transforms\nimport os, cv2, sys\nimport numpy as np\nsys.path.append('..')\nfrom architectures.unet import UNet_G\nfrom architectures.resnet import ResNet_G\nfrom utils.griffin_lim import *\nfrom utils.inference_utils import *\nfrom utils.utils import generate_noise\nfrom PIL import Image\n\ncv2.namedWindow('Input')\ncv2.namedWindow('Output')\n\ndevice = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')\n\nnz = 8\ninput_img_dir = 'samples'\ninput_img_list = os.listdir(input_img_dir)\nmodel_path = 'saved/.pth'\n\nsz, ic, oc, use_bn, norm_type = 256, 3, 3, True, 'instancenorm'\nnetG = UNet_G(ic, oc, sz, nz, use_bn, norm_type).to(device)\n# netG = ResNet_G(ic, oc, sz, nz = nz, norm_type = norm_type).to(device)\nnetG.load_state_dict(torch.load(model_path, map_location = 'cpu'))\nnetG.eval()\n\ncnt, total_num = 0, 10\nimage, _ = get_image(os.path.join(input_img_dir, input_img_list[cnt]), sz)\nimage_t = transform_image(image, sz, ic)\nnoise = generate_noise(1, nz, device)\nout = generate(netG, image_t, noise, oc, sz, device)\n\nwhile(1):\n\tcv2.imshow('Input', image)\n\tcv2.imshow('Output', out)\n\n\tkey = cv2.waitKey(1) & 0xFF\n\n\tif(key == ord('q')):\n\t\tbreak\n\n\telif(key == ord('r')):\n\t\tnoise = generate_noise(1, nz, device)\n\t\tout = generate(netG, image_t, noise, oc, sz, device)\n\n\telif(key == ord('t')):\n\t\ten = generate_noise(1, nz, device)\n\t\tsn = copy.deepcopy(noise)\n\t\tfor i in range(10):\n\t\t\tcur_noise = interpolation(sn, en, 10, i+1)\n\t\t\tout = generate(netG, image_t, cur_noise, oc, sz, device)\n\t\t\tcv2.imshow('Input', image)\n\t\t\tcv2.imshow('Output', out)\n\t\t\tcv2.waitKey(1)\n\t\tnoise = copy.deepcopy(en)\n\n\telif(key == ord('e')):\n\t\tcnt += 1\n\t\tif(cnt>=total_num):\n\t\t\tcnt = 0\n\t\timage, _ = get_image(os.path.join(input_img_dir, input_img_list[cnt]), sz)\n\t\timage_t = transform_image(image, sz, ic)\n\t\tout = generate(netG, image_t, noise, oc, sz, device)\n\ncv2.destroyAllWindows()","sub_path":"others/unpaired/baseline/inference/inference.py","file_name":"inference.py","file_ext":"py","file_size_in_byte":1926,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"167097541","text":"'''\n136. Single Number My Submissions Question\nTotal Accepted: 110229 Total Submissions: 228793 Difficulty: Medium\nGiven an array of integers, every element appears twice except for one. Find that single one.\n\nNote:\nYour algorithm should have a linear runtime complexity. Could you implement it without using extra memory?\n\n'''\nclass Solution(object): \n \n def singleNumber(self,nums) : \n \"\"\"\n :type nums: List[int]\n :rtype: int \n XOR of same number = 0; after loop we are left with missing num\n 52 ms\n \"\"\"\n result = 0\n for x in nums: \n result ^= x \n return result \n \n def singleNumber2(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int \n 76 ms solution o(n) space O(n) time\n \"\"\"\n from collections import Counter\n counter = Counter(nums)\n for (k,v) in counter.items(): \n if v == 1: \n return k\n \n def singleNumber1(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int \n using dictionary o(n) space complexity linear time\n \"\"\"\n from collections import defaultdict\n dt = defaultdict(int)\n for n in nums: \n dt[n] += 1\n for k,v in dt.items(): \n if v == 1: \n return k\n","sub_path":"136_single_number.py","file_name":"136_single_number.py","file_ext":"py","file_size_in_byte":1347,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"322280065","text":"# Skoda fylgni milli ara\n\n\nimport ReadCSVRowHeader as csvReader \nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\n\nclass Stats:\n\n def __init__(self, DfData, monthPlayed):\n self.Data = []\n self.Counter = 1\n self.year_With2014 = []\n self.yearMin = 1998\n\n yearCounter = self.yearMin\n for item in DfData.T.iterrows():\n yearCounter += 1\n month = monthPlayed.get(yearCounter, False)\n item = list(item[1])\n if month and item[month] != 0:\n self.Data.append(item[month])\n self.year_With2014.append(yearCounter)\n\n # for k,v in monthPlayed.items():\n # # print('v',v)\n # self.Data.append(DfData[self.Counter][v])\n # self.year_With2014.append(k)\n # self.Counter += 1\n # if self.Data[len(self.Data)-1] == 0:\n # self.Data = self.Data[0:len(self.Data)-1]\n # self.year_With2014 = self.year_With2014[0:len(self.year_With2014)-1]\n\n # print('years', self.year_With2014)\n # print('Data', self.Data)\n\n self.line, self.w = self.Least_Squares()\n\n # The Method of Least Sqaures\n\n def Least_Squares(self):\n A = np.vstack([self.year_With2014, np.ones(len(self.year_With2014))]).T\n w = np.linalg.lstsq(A,self.Data)[0]\n year_np = np.array(self.year_With2014)\n line = w[0]*year_np + w[1]\n return line, w\n\n def getPrediction(self):\n year_np = np.array(self.year_With2014)\n nextYear = year_np[-1]+1\n print('Spá fyrir gistinætum hjá útlendingum yfir Airwaves árið', nextYear)\n print(self.w[0]*nextYear + self.w[1])\n\n def plot(self, title):\n plt.figure(1)\n plt.title('The Method of least Squares ' + title)\n plt.plot(self.year_With2014, self.Data,'o', label = 'Original data', markersize = 5)\n plt.plot(self.year_With2014, self.line,'r', label = 'Fitted line')\n plt.legend(loc = 2)\n plt.ylabel('Gistinætur')\n plt.xlabel('Ár')\n plt.show()\n\n # Correlation\n def Corre_Data(self):\n Corr = np.corrcoef(self.year_With2014,self.Data) # How good does the data fit the line\n return Corr[0][1]\n\n\n # Basic Statistics\n def Statistics(self):\n Mean = np.mean(self.Data)\n Std = np.std(self.Data)\n Var = np.var(self.Data)\n return Mean, Std, Var\n","sub_path":"Verkefni1/Tolfreadi.py","file_name":"Tolfreadi.py","file_ext":"py","file_size_in_byte":2412,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"30766208","text":"import dataclasses\nfrom typing import Any, Callable, Dict, Type, _TypedDictMeta # type: ignore\n\nimport orjson\n\nfrom .dataclasses import asdict\nfrom .fields import SerializeFields\n\n\ndef dataclass_asjson(instance: Any) -> bytes:\n return orjson.dumps(\n instance, default=OrjsonDefaultTypes.default_function(instance)\n )\n\n\ndef typed_dict_asjson(\n typed_dict: Dict[str, Any], typed_dict_type: _TypedDictMeta\n) -> bytes:\n return orjson.dumps(_choose_typed_dict_fields(typed_dict, typed_dict_type))\n\n\ndef _choose_typed_dict_fields(\n typed_dict: Dict[str, Any], typed_dict_type: _TypedDictMeta\n) -> Dict[str, Any]:\n fields = SerializeFields.get_fields(typed_dict_type)\n\n if not fields:\n return typed_dict\n\n return {\n f.name: (\n _choose_typed_dict_fields(typed_dict[f.name], f.type)\n if isinstance(typed_dict[f.name], dict)\n else typed_dict[f.name]\n )\n for f in fields\n }\n\n\nclass OrjsonDefaultTypes:\n types_default_map: Dict[Type[Any], Callable[[Any], Any]] = dict()\n\n @classmethod\n def set_type(cls, type_: Type[Any]) -> None:\n if type_ in cls.types_default_map:\n return\n\n cls.types_default_map[type_] = cls._asdict_for_orjson\n\n for field in dataclasses.fields(type_):\n if dataclasses.is_dataclass(field.type):\n cls.types_default_map[field.type] = cls._asdict_for_orjson\n\n @classmethod\n def default_function(cls, instance: Any) -> Any:\n def wrap(v: Any) -> Any:\n if isinstance(v, bytes):\n return v.decode()\n\n return cls.types_default_map[type(v)](v)\n\n return wrap\n\n @staticmethod\n def _asdict_for_orjson(instance: Any) -> Dict[str, Any]:\n dictinst: Dict[str, Any] = asdict(instance)\n fields = SerializeFields.get_fields(type(instance))\n\n if not fields:\n return dictinst\n\n return {f.name: dictinst[f.name] for f in fields}\n","sub_path":"jsondaora/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":1979,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"491087062","text":"\"\"\"Client for using Elastiknn.\"\"\"\n\nfrom typing import Iterable, Tuple, Dict\n\nfrom elasticsearch import Elasticsearch\nfrom elasticsearch.helpers import bulk\n\nfrom .api import *\n\n\nclass ElastiKnnClient(object):\n\n def __init__(self, es: Elasticsearch = None):\n \"\"\"Wrapper on the official `elasticsearch.Elasticsearch` client for making Elastiknn requests.\n\n The client is fairly primitive in that it assumes the vector is basically the only thing stored in each doc.\n For more complex use-cases you should use this client as an example for constructing the mapping, indexing,\n and search requests in your own code.\n\n Parameters\n ----------\n es : `elasticsearch.Elasticsearch` client.\n This client is used internally to make all requests.\n Defaults to a client pointing at http://localhost:9200.\n \"\"\"\n if es is None:\n self.es = Elasticsearch([\"http://localhost:9200\"])\n else:\n self.es = es\n\n def put_mapping(self, index: str, field: str, mapping: Mapping.Base):\n \"\"\"\n Update the mapping at the given index and field to store an Elastiknn vector.\n\n Parameters\n ----------\n index : string\n Index containing the given field. Should already exist.\n field : string\n Field that should use the given mapping.\n mapping : instance of `Mapping.Base`\n Mapping object defining the vector's storage properties.\n\n Returns\n -------\n Dict\n Json response as a dict. Successful request returns `{\"acknowledged\": true}`.\n \"\"\"\n body = {\n \"properties\": {\n field: mapping.to_dict()\n }\n }\n return self.es.transport.perform_request(\"PUT\", f\"/{index}/_mapping\", body=body)\n\n def index(self, index: str, field: str, vecs: Iterable[Vec.Base], ids: List[str] = None, refresh: bool = False) -> Tuple[int, List[Dict]]:\n \"\"\"Index (i.e. store) the given vectors at the given index and field with the optional ids.\n\n Parameters\n ----------\n index : string\n Index where the vectors are stored.\n field : string\n Field containing the vector in each document.\n vecs : List of `Vec.Base`\n Vectors that should be indexed.\n ids : List of strings\n Optional list of ids associated with the given vectors.\n If not given, the ids are generated by Elasticsearch.\n refresh : bool\n Whether to refresh before returning. Set to true if you want to immediately run queries after indexing.\n\n Returns\n -------\n Int\n Number of vectors successfully indexed.\n List of Dicts\n Error responses for the vectors that were not indexed.\n \"\"\"\n if ids is None or ids == []:\n ids = [None for _ in vecs]\n\n def gen():\n for vec, _id in zip(vecs, ids):\n d = { \"_op_type\": \"index\", \"_index\": index, field: vec.to_dict()}\n if _id:\n d[\"_id\"] = str(_id)\n elif \"_id\" in d:\n del d[\"_id\"]\n yield d\n\n res = bulk(self.es, gen())\n if refresh:\n self.es.indices.refresh(index=index)\n return res\n\n def nearest_neighbors(self, index: str, query: NearestNeighborsQuery.Base, k: int = 10, fetch_source: bool = False) -> Dict:\n \"\"\"Build and execute a nearest neighbors query against the given index.\n\n Parameters\n ----------\n index : string\n Index to run the search against.\n query : NearestNeighborsQuery.Base\n Query object defining the query properties.\n k: int\n Number of hits to return.\n fetch_source : bool\n Whether to return the `_source` of the document. It's generally faster to _not_ return the `_source`.\n\n Returns\n -------\n Dict\n Standard Elasticsearch search response parsed as a dict.\n \"\"\"\n body = {\n \"query\": {\n \"elastiknn_nearest_neighbors\": query.to_dict()\n }\n }\n return self.es.search(index, body=body, size=k, _source=fetch_source)\n","sub_path":"client-python/elastiknn/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":4300,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"437882123","text":"import views\nfrom henango.urls.pattern import URLPattern\n\n# pathとview関数の対応\nurl_patterns = [\n URLPattern(\"/now\", views.now),\n URLPattern(\"/show_request\", views.show_request),\n URLPattern(\"/parameters\", views.parameters),\n URLPattern(\"/user//profile\", views.user_profile),\n URLPattern(\"/set_cookie\", views.set_cookie)\n]\n","sub_path":"codes/chapter20/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":354,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"110814593","text":"#!/usr/bin/python\n\nimport sys, os, string, re\nimport scipy.stats\n\ndef read_lincRNA():\n\t\"\"\" \"\"\"\n\tlincRNADict = {}\n\tlincRNA = open(sys.argv[1], \"r\")\n\tfor line in lincRNA:\n\t\tline=line.strip().split(\"\\t\")\n\t\tlincRNADict[line[0]]=map(float,line[1:])\n\tlincRNA.close()\n\treturn lincRNADict\n\ndef read_mRNA():\n\tmRNADict = {}\n\tmRNA = open(sys.argv[2], \"r\")\n\tfor line in mRNA:\n\t\tline=line.strip().split(\"\\t\")\n\t\tmRNADict[line[0]]=map(float,line[1:])\n\tmRNA.close()\n\treturn mRNADict\n\ndef pearson(x=None,y=None):\n\t\"\"\" \"\"\"\n\tif isinstance(x,list) and isinstance(y,list):\n\t\tif len(x)==len(y):\n\t\t\tcoeff,pvalue=scipy.stats.pearsonr(x,y)\n\t\t\treturn coeff\n\t\telse:\n\t\t\tprint >>sys.stderr,\"The length between\", x ,\"and\", y,\" is not equal.\"\n\telse:\n\t\tprint >> sys.stderr,\"The type of\", x,\" and\", y,\" must be list!\"\n\ndef main():\n\tlincRNADict = read_lincRNA()\n\tmRNADict = read_mRNA()\n\tfor i, j in lincRNADict.items():\n\t\tf = open(i + \"_Genes.pearson.rnk\", \"w\")\n\t\tfor x, y in mRNADict.items():\n\t\t\tcoeff = pearson(j, y)\n\t\t\tprint >> f, \"{0}\\t{1}\".format(x, coeff)\n\t\tf.close()\n\nif __name__ == \"__main__\":\n\tmain()","sub_path":"GSEA/lncRNA.gsea.py","file_name":"lncRNA.gsea.py","file_ext":"py","file_size_in_byte":1075,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"417003064","text":"import warnings\nimport pandas as pd\nfrom urllib.request import urlopen\nimport os\nfrom lxml import etree\n\n\ndef _join_update(df, other):\n for column in other.columns:\n if column in df:\n df[column].update(other[column])\n else:\n df[column] = other[column]\n\n\nclass OpenAustraliaMembers:\n \"\"\"Get DataFrames with data about Australian parliamentarians\n\n Key methods are `people` and `offices`.\n \"\"\"\n\n def __init__(self, path='http://data.openaustralia.org/members',\n cached=False):\n self._path = path\n self._cached = cached\n self._cache = {}\n\n def _open(self, filename):\n if ':/' in self._path:\n return urlopen(self._path + '/' + filename)\n return open(os.path.join(self._path, filename), 'rb')\n\n def _parse(self, filename):\n if filename in self._cache:\n return self._cache[filename]\n\n with self._open(filename) as f:\n out = etree.XML(f.read())\n\n if self._cached:\n self._cache[filename] = out\n return out\n\n def people(self, enhanced=True):\n \"\"\"Get basic person details\n\n One record per person\n \"\"\"\n root = self._parse('people.xml')\n df = pd.DataFrame([dict(person.attrib)\n for person in root.findall('.//person')])\n df = df.rename(columns={'id': 'person_id'})\n df = df.set_index('person_id')\n if enhanced:\n for filename in ['wikipedia-lords',\n 'wikipedia-commons',\n 'links-register-of-interests',\n 'links-abc-qanda',\n 'websites']:\n other = self._parse_personinfo(filename + '.xml')\n _join_update(df, other)\n df['aph_id'] = df.aph_url.map(lambda s: s.rpartition('=')[-1],\n na_action='ignore')\n return df\n\n def _parse_personinfo(self, filename):\n root = self._parse(filename)\n df = pd.DataFrame([dict(personinfo.attrib)\n for personinfo in root.findall('.//personinfo')])\n gb = df.groupby('id')\n if pd.np.any(gb.count() > 1):\n warnings.warn('Found more than one personinfo per person in ' +\n filename)\n return gb.last() # in case there are duplicates\n\n def offices(self, enhanced=True):\n \"\"\"Get details on parliamentary positions\n\n A record for each time someone held a position in the house of\n represenatives, senate, cabinet, etc. Data from `people`, as well as\n fields specific to these roles, is merged in redundantly when enhanced.\n\n The latestname field is the most reliable for name.\n\n The source column is one of {'representatives', 'senators',\n 'ministers'}.\n \"\"\"\n root = self._parse('people.xml')\n offices = []\n for person in root.findall('.//person'):\n person_id = person.attrib['id']\n for office in person.findall('./office'):\n offices.append(dict(office.attrib))\n offices[-1]['person_id'] = person_id\n df = pd.DataFrame(offices).rename(columns={'id': 'office_id'})\n df = df.set_index('office_id')\n if enhanced:\n for attr in ['senators', 'representatives', 'ministers']:\n other = getattr(self, attr)()\n _join_update(df, other)\n df = df.merge(self.people(), left_on='person_id', right_index=True)\n return df\n\n def senators(self):\n return self._parse_office_details('senators')\n\n def representatives(self):\n return self._parse_office_details('representatives')\n\n def ministers(self):\n return self._parse_office_details('ministers', tagname='moffice')\n\n def _parse_office_details(self, filename, tagname='member'):\n root = self._parse(filename + '.xml')\n df = pd.DataFrame([dict(person.attrib)\n for person in root.findall('.//' + tagname)])\n df['source'] = filename\n df['fromdate'] = self._clean_date(df['fromdate'])\n df['todate'] = self._clean_date(df['todate'])\n return df.rename(columns={'id': 'office_id'}).set_index('office_id')\n\n def _clean_date(self, series):\n series = series.copy()\n series[series == '1000-01-01'] = None\n series[series == '9999-12-31'] = None\n return pd.to_datetime(series)\n\n\nif __name__ == '__main__':\n obj = OpenAustraliaMembers(cached=True)\n for attr in dir(obj):\n if attr[:1].isalpha():\n method = getattr(obj, attr)\n if callable(method):\n print('===', attr, '===')\n print(method().head())\n print()\n","sub_path":"openaustraliamembers.py","file_name":"openaustraliamembers.py","file_ext":"py","file_size_in_byte":4831,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"329626760","text":"# Author: Sachin Kumar\n# Github: https://github.com/skumar24\n\n# Fair Rations\n# Problem Url: https://www.hackerrank.com/challenges/fair-rations/problem\n# Score: 25\n\n#!/bin/python3\n\nimport math\nimport os\nimport random\nimport re\nimport sys\n\ndef fairRations(B):\n if sum(B) % 2 > 0:\n return \"NO\"\n else:\n cnt = 0\n for i, x in enumerate(B):\n if x % 2 == 1:\n B[i] += 1\n B[i + 1] += 1\n cnt += 2\n return cnt\n\n\nif __name__ == '__main__':\n fptr = open(os.environ['OUTPUT_PATH'], 'w')\n\n N = int(input())\n\n B = list(map(int, input().rstrip().split()))\n\n result = fairRations(B)\n\n fptr.write(str(result) + '\\n')\n\n fptr.close()\n","sub_path":"Algorithms/02 Implementation/FairRations.py","file_name":"FairRations.py","file_ext":"py","file_size_in_byte":720,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"270900814","text":"# Import libraries\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\n#Set working directory & import data\ndataset = pd.read_csv(\"Mall_Customers.csv\")\nX=dataset.iloc[:,[3,4]].values\n#column 3 & 4 are annual income and spending score\n\n#Plot & Use the Dendrogram to find the optimal number of clusters\nimport scipy.cluster.hierarchy as sch\ndendrogram = sch.dendrogram(sch.linkage(X, method = 'ward'))\n#dendrogram plots the hierarchical clustering as a dendrogram.\n#method = 'ward' ward method minimize the variance within each cluster\n\nplt.title('Dendrogram')\nplt.xlabel('Customers')\nplt.ylabel('Euclidean Distance')\nplt.show()\n\n#Fitting Hierarchical Clustering to the mall dataset\nfrom sklearn.cluster import AgglomerativeClustering\nhc = AgglomerativeClustering(n_clusters = 5, affinity = 'euclidean', linkage = 'ward')\ny_hc = hc.fit_predict(X)\n\n#n_clusters is optimal no. of clusters to be formed\n#affinity is Metric used to compute the linkage. If linkage is “ward”, only “euclidean” is accepted.\n#linkage = 'ward' ward ward minimizes the variance of the clusters being merged.\n#The linkage criterion determines which distance to use between sets of observation to merge the pairs of cluster.\n\n#Visualising the 5 clusters (only for 2-dimensional features)\nplt.scatter(X[y_hc == 0,0], X[y_hc == 0,1], s = 100, c = 'red', label = 'Cluster 1 (Careful)')\nplt.scatter(X[y_hc == 1,0], X[y_hc == 1,1], s = 100, c = 'blue', label = 'Cluster 2 (Standard)')\nplt.scatter(X[y_hc == 2,0], X[y_hc == 2,1], s = 100, c = 'green', label = 'Cluster 3 (Target)')\nplt.scatter(X[y_hc == 3,0], X[y_hc == 3,1], s = 100, c = 'cyan', label = 'Cluster 4 (Careless)')\nplt.scatter(X[y_hc == 4,0], X[y_hc == 4,1], s = 100, c = 'magenta', label = 'Cluster 5 (Sensible)')\nplt.title('Clusters of customers')\nplt.xlabel('Annual Income (k$)')\nplt.ylabel('Spending Score (1-100)')\nplt.legend()\nplt.show()\n\n\n\n","sub_path":"ML/Machine-Learning-master/Clustering/Hierarchical Clustering/hierarchical_clustering_saurabh.py","file_name":"hierarchical_clustering_saurabh.py","file_ext":"py","file_size_in_byte":1908,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"488380734","text":"from django.contrib.auth.decorators import login_required\nfrom django.http import HttpResponse, HttpResponseRedirect\nfrom django.shortcuts import render_to_response, get_object_or_404\nfrom django.template.defaultfilters import slugify\nfrom django.template import RequestContext\nfrom django.contrib.auth.models import User\nfrom django.conf import settings\nfrom inoutboard.models import *\nfrom django.utils import simplejson\nfrom django.contrib.admin.views.decorators import staff_member_required\n\n\ndef index(request):\n\t\n\tpeople = Person.objects.all()\n\n\tstatuses = []\n\tfor p in people:\n\n\t\tstatus_filter = Status.objects.filter(person=p).order_by('-timestamp')\n\t\t\n\t\tif status_filter.count():\n\t\t\ts = status_filter[0]\n\t\t\tstatuses.append({\n\t\t\t\t'id':p.id,\n\t\t\t\t'name': p.name,\n\t\t\t\t'email': p.email,\n\t\t\t\t'status': s.status,\n\t\t\t\t'location': s.location_name,\n\t\t\t\t'lat': s.location_lat,\n\t\t\t\t'lon': s.location_lon,\n\t\t\t\t'timestamp': s.timestamp\t\t\t\n\t\t\t\n\t\t\t})\n\t\n\t# sort statuses by timestamp - newest first\n\tstatuses.sort(key=lambda x: x['timestamp'], reverse=True)\n\t\n\treturn render_to_response('inoutboard/index.html', {\n\t\t'statuses': statuses,\n 'GMAPKEY':settings.GOOGLE_MAPS_API_KEY\n },context_instance=RequestContext(request))\t\nindex = staff_member_required(index) \n\ndef get_placemarks(request):\n\t\n\tid = request.GET['id']\n\tp = Person.objects.get(id=id)\n\tcurrent_status = {}\n\tfuture_status = {}\n\tpast_statuses = []\n\t\n\tstatuses = Status.objects.filter(person=p).order_by('-timestamp')[0:settings.PAST_LOCATION_COUNT+1]\n\ti = 0 #counter\n\t#the first one is the newest one, set that as current rest as past\n\tfor stat in statuses:\n\t\tif i == 0:\n\t\t\t#current status\n\t\t\tcurrent_status = {\n\t\t\t\t'id':p.id,\n\t\t\t\t'name':p.name,\n\t\t\t\t'email':p.email,\n\t\t\t\t'status':stat.status,\n\t\t\t\t'location':stat.location_name,\n\t\t\t\t'lat':stat.location_lat,\n\t\t\t\t'lon':stat.location_lon}\n\t\t\t\n\t\t\tif not stat.next_name == '':\n\t\t\t\tfuture_status = {\t\n\t\t\t\t\t'id':p.id,\n\t\t\t\t\t'name':p.name,\n\t\t\t\t\t'email':p.email,\n\t\t\t\t\t'status':'Next Destination for ' + p.name,\n\t\t\t\t\t'location':stat.next_name,\n\t\t\t\t\t'lat':stat.next_lat,\n\t\t\t\t\t'lon':stat.next_lon}\n\t\t\t\t\n\t\telse:\n\t\t\t#previous statuses\n\t\t\tpast_statuses.append({\n\t\t\t\t'id':p.id,\n\t\t\t\t'name':p.name,\n\t\t\t\t'email':p.email,\n\t\t\t\t'status':stat.status,\n\t\t\t\t'location':stat.location_name,\n\t\t\t\t'lat':stat.location_lat,\n\t\t\t\t'lon':stat.location_lon})\n\t\ti = i + 1\n\tretval = {'current':current_status,\n\t\t\t\t\t\t 'past':past_statuses,\n\t\t\t\t\t\t 'future':future_status\n\t\t\t\t\t\t }\n\treturn HttpResponse(simplejson.dumps(retval))\n\n\t\t\t\n\t\t\t\n\t\t\t\n\t\t\t\n\t\t\t\n\t\t\t\n\t\t\t\n\t\t\t\n\t\t\t\n\t\t\t\n\t\t\t\n\t\t\t","sub_path":"inoutboard/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2550,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"281002604","text":"import numpy as np\nfrom Players.DQPlayer import DQNArgs\nfrom Utility.Consts import Consts\n\nBOARD_DIM = 3\nN_CH = 2\nP1S = 'x'\nP2S = 'o'\n\nclass TicTacToeState:\n def __init__(self):\n self.name = \"Tic Tac Toe\"\n self.board = np.zeros((BOARD_DIM, BOARD_DIM))\n self.lastAction = []\n self.curPlayer = Consts.P1\n\n def get_state(self):\n return self.board\n\n def get_board(self):\n otherPlayer = Consts.P2 if self.curPlayer == Consts.P1 else Consts.P1\n p1_board = 1 * (self.board == self.curPlayer)\n p2_board = 1 * (self.board == otherPlayer)\n return np.stack((p1_board, p2_board), axis=0)\n\n def get_state_hash(self):\n return str(self.board.reshape(-1))\n\n def show_state(self):\n s = ''.join(['-'] + ['-' for _ in range(4*BOARD_DIM)])\n print(s)\n for row in range(BOARD_DIM):\n rowStr = '| '\n for col in range(BOARD_DIM):\n if self.board[row, col] == Consts.P1:\n rowStr = rowStr + P1S + ' | '\n elif self.board[row, col] == Consts.P2:\n rowStr = rowStr + P2S + ' | '\n else:\n rowStr = rowStr + ' | '\n rowStr = rowStr[:-1] # remove last space\n print(rowStr)\n print(s)\n\n def get_all_actions(self):\n actions = []\n for row in range(BOARD_DIM):\n for col in range(BOARD_DIM):\n actions.append((row, col))\n return actions\n\n def get_actions(self):\n all_actions = self.get_all_actions()\n actions = [action for action in all_actions if self.check_legal(action)]\n return actions\n\n def get_illegal_actions(self):\n all_actions = self.get_all_actions()\n illegal_inds = [not self.check_legal(action) for action in all_actions]\n return illegal_inds\n\n def check_legal(self, action):\n if action[0] < 0 or action[0] >= BOARD_DIM or action[1] < 0 or action[1] >= BOARD_DIM:\n return False\n return self.board[action] == 0\n\n def get_action_command(self):\n return 'Enter desired cell as [row col]:\\n'\n\n def play(self, action):\n action = tuple([int(action[0]), int(action[1])])\n if not self.check_legal(action): # illegal action\n return False, False\n self.board[action] = self.curPlayer\n self.curPlayer = Consts.P2 if self.curPlayer == Consts.P1 else Consts.P1\n self.lastAction.append(action)\n isEnd, _ = self.check_win()\n return True, isEnd\n\n def check_win(self):\n # We need to check only row/col/diags containing last move\n if not self.lastAction:\n return False, 0\n action = self.lastAction[-1]\n row, col = action\n colSum = np.sum(self.board[row, :])\n rowSum = np.sum(self.board[:, col])\n allSums = [colSum, rowSum]\n if row == col: # check diagonal\n diagSum1 = np.trace(self.board)\n allSums = allSums + [diagSum1]\n if row + col == BOARD_DIM - 1: # check anti-diagonal\n diagSum2 = np.trace(np.fliplr(self.board))\n allSums = allSums + [diagSum2]\n if BOARD_DIM*Consts.P1 in allSums: # player 1 wins\n return True, Consts.P1\n elif BOARD_DIM*Consts.P2 in allSums: # player 2 wins\n return True, Consts.P2\n elif np.all((self.board != 0)): # no more moves - tie\n return True, Consts.TIE\n else: # continue playing\n return False, 0\n\n def get_rewards(self):\n isEnd, winner = self.check_win()\n if isEnd:\n if winner == Consts.P1:\n return 1, -1\n if winner == Consts.P2:\n return -1, 1\n if winner == Consts.TIE:\n return 0.2, 0.5 # player 1 started so has an advantage - punish him more for a tie\n return 0, 0\n\n def get_heuristic(self, player):\n score = 0\n for i in range(BOARD_DIM):\n score += line_heuristic(self.board[i, :], player) # row\n score += line_heuristic(self.board[:, i], player) # col\n score += line_heuristic(np.diag(self.board), player) # main diagonal\n score += line_heuristic(np.diag(np.fliplr(self.board)), player) # anti-diagonal\n return score\n\n def undo(self):\n if self.lastAction:\n self.board[self.lastAction[-1]] = 0\n self.lastAction = self.lastAction[:-1]\n self.curPlayer = Consts.P2 if self.curPlayer == Consts.P1 else Consts.P1\n\n def reset(self):\n self.board = np.zeros((BOARD_DIM, BOARD_DIM))\n self.lastAction = []\n self.curPlayer = Consts.P1\n\n\ntictactoe_dqn_args = DQNArgs(ch=N_CH, # NN input channels - don't change this!\n h=BOARD_DIM, # NN input height - don't change this!\n w=BOARD_DIM, # NN input width - don't change this!\n output_size=BOARD_DIM**2, # NN output size (number of actions) - don't change this!\n layer_channels=[64, 32], # number of channels for each layer\n layer_sizes=[3, 1], # kernel sizes for each layer\n layer_strides=[1, 1], # stride for each layer\n layer_padding=[0, 0], # padding for each layer\n batch_size=32, # batch size for optimization step\n mem_size=100000, # replay memory size\n target_update=5000, # training step period for target network update\n eps_decay=2e4, # exploration rate decay\n lr=0.001, # learning rate\n gamma=0.99) # MDP discount factor\n\n\ndef line_heuristic(l, player):\n score_factor = 10\n score = 0\n for i in range(len(l)):\n if l[i] == player: # players piece\n if score == 0: # seen nothing up to here\n score = 1\n elif score > 0: # seen up to here only players pieces\n score *= score_factor\n else: # seen opponents pieces -> line has no value\n return 0\n elif l[i] == 0: # empty\n continue\n else: # opponents piece\n if score == 0: # seen nothing up to here\n score = -1\n elif score < 0: # seen up to here only opponents pieces\n score *= score_factor\n else: # seen players pieces -> line has no value\n return 0\n return score\n\n# =================================================================================================================== #\n\nif __name__ == '__main__':\n print(\"Tic Tac Toe\")\n","sub_path":"TicTacToe/TicTacToe.py","file_name":"TicTacToe.py","file_ext":"py","file_size_in_byte":6913,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"144698894","text":"# -*- coding: utf-8 -*-\r\n\r\nimport pandas as pd\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport seaborn as sns\r\nimport datetime\r\nfrom datetime import timedelta\r\nfrom sklearn.preprocessing import LabelEncoder\r\nfrom scipy.stats import zscore\r\n\r\n\r\n\r\ncustomers = pd.read_csv('cleaned_customers.csv')\r\nprices = pd.read_csv('cleaned_prices.csv')\r\nchurn = pd.read_csv('ml_case_training_output.csv')\r\n\r\n\r\nprint(prices.price_date.max())\r\nprint(prices.price_date.min())\r\n\r\n\r\n\r\ncustomers['date_activ'] = pd.to_datetime(customers['date_activ'], format = '%Y-%m-%d')\r\ncustomers['date_end'] = pd.to_datetime(customers['date_end'], format = '%Y-%m-%d')\r\ncustomers['date_modif_prod'] = pd.to_datetime(customers['date_modif_prod'], format = '%Y-%m-%d')\r\ncustomers['date_renewal'] = pd.to_datetime(customers['date_renewal'], format = '%Y-%m-%d')\r\n\r\n\r\ndf = pd.merge(customers, churn, on='id')\r\n\r\n\r\ndf['tenure'] = ((df[\"date_end\"]-df[\"date_activ\"])/ np.timedelta64(1, \"Y\")).astype(int)\r\n\r\n\r\n\r\n\r\n#### a way of transforming dates to months duration\r\n\r\ndef convert_months(reference_date, dataframe, column):\r\n time_delta = reference_date - dataframe[column]\r\n months = (time_delta / np.timedelta64(1, 'M')).astype(int)\r\n \r\n \r\n return months\r\n\r\n\r\n\r\nREFERENCE_DATE = datetime.datetime(2016, 1, 1)\r\n\r\ndf['months_since_activ'] = convert_months(REFERENCE_DATE, df, 'date_activ')\r\ndf['months_to_end'] = -convert_months(REFERENCE_DATE, df, 'date_end')\r\ndf['months_since_modif'] = convert_months(REFERENCE_DATE, df, 'date_modif_prod')\r\ndf['months_since_renew'] = convert_months(REFERENCE_DATE, df, 'date_renewal')\r\n\r\n\r\n\r\n\r\n### drop unnecessary columns\r\n\r\ncolumns_to_drop = ['date_activ', 'date_modif_prod', 'date_renewal', 'date_end']\r\n \r\ndf = df.drop(columns = columns_to_drop) \r\n \r\n\r\n\r\n\r\n### log-transform for skewed variables\r\n\r\n\r\ndf.loc[df.cons_12m < 0,\"cons_12m\"] = np.nan\r\ndf.loc[df.cons_gas_12m < 0,\"cons_gas_12m\"] = np.nan\r\ndf.loc[df.cons_last_month < 0,\"cons_last_month\"] = np.nan\r\ndf.loc[df.forecast_cons_12m < 0,\"forecast_cons_12m\"] = np.nan\r\ndf.loc[df.forecast_cons_year < 0,\"forecast_cons_year\"] = np.nan\r\ndf.loc[df.forecast_meter_rent_12m < 0,\"forecast_meter_rent_12m\"] = np.nan\r\ndf.loc[df.imp_cons < 0,\"imp_cons\"] = np.nan\r\n\r\n\r\ndf[\"cons_12m\"] = np.log10(df[\"cons_12m\"]+1)\r\ndf[\"cons_gas_12m\"] = np.log10(df[\"cons_gas_12m\"]+1)\r\ndf[\"cons_last_month\"] = np.log10(df[\"cons_last_month\"]+1)\r\ndf[\"forecast_cons_12m\"] = np.log10(df[\"forecast_cons_12m\"]+1)\r\ndf[\"forecast_cons_year\"] = np.log10(df[\"forecast_cons_year\"]+1)\r\ndf[\"forecast_meter_rent_12m\"] = np.log10(df[\"forecast_meter_rent_12m\"]+1)\r\ndf[\"imp_cons\"] = np.log10(df[\"imp_cons\"]+1)\r\n\r\n\r\n\r\n\r\n\r\n### replace outliers with Z-score\r\n\r\ndef replace_outliers_z_score(dataframe, column, Z=3):\r\n \r\n df = dataframe.copy(deep=True)\r\n df.dropna(inplace=True, subset=[column])\r\n \r\n df[\"zscore\"] = zscore(df[column])\r\n mean_ = df[(df[\"zscore\"] > -Z) & (df[\"zscore\"] < Z)][column].mean()\r\n \r\n no_outliers = dataframe[column].isnull().sum()\r\n dataframe[column] = dataframe[column].fillna(mean_)\r\n dataframe[\"zscore\"] = zscore(dataframe[column])\r\n dataframe.loc[(dataframe[\"zscore\"] < -Z) | (dataframe[\"zscore\"] > Z),column] = mean_\r\n \r\n \r\n print(\"Replaced:\", no_outliers, \" outliers in \", column)\r\n return dataframe.drop(columns=\"zscore\")\r\n\r\n\r\n\r\n\r\ndf = replace_outliers_z_score(df,\"cons_12m\")\r\ndf = replace_outliers_z_score(df,\"cons_gas_12m\")\r\ndf = replace_outliers_z_score(df,\"cons_last_month\")\r\ndf = replace_outliers_z_score(df,\"forecast_cons_12m\")\r\ndf = replace_outliers_z_score(df,\"forecast_cons_year\")\r\ndf = replace_outliers_z_score(df,\"forecast_discount_energy\")\r\ndf = replace_outliers_z_score(df,\"forecast_meter_rent_12m\")\r\ndf = replace_outliers_z_score(df,\"forecast_price_energy_p1\")\r\ndf = replace_outliers_z_score(df,\"forecast_price_energy_p2\")\r\ndf = replace_outliers_z_score(df,\"forecast_price_pow_p1\")\r\ndf = replace_outliers_z_score(df,\"imp_cons\")\r\ndf = replace_outliers_z_score(df,\"margin_gross_pow_ele\")\r\ndf = replace_outliers_z_score(df,\"margin_net_pow_ele\")\r\ndf = replace_outliers_z_score(df,\"net_margin\")\r\ndf = replace_outliers_z_score(df,\"pow_max\")\r\ndf = replace_outliers_z_score(df,\"months_since_activ\")\r\ndf = replace_outliers_z_score(df,\"months_to_end\")\r\ndf = replace_outliers_z_score(df,\"months_since_modif\")\r\ndf = replace_outliers_z_score(df,\"months_since_renew\")\r\n\r\n\r\ndf.reset_index(drop=True, inplace=True)\r\n\r\n \r\n\r\n\r\n##### averaging prices\r\n\r\n\r\n\r\ndf['avg_price_p1_var'] = 0\r\ndf['avg_price_p2_var'] = 0\r\ndf['avg_price_p3_var'] = 0\r\ndf['avg_price_p1_fix'] = 0\r\ndf['avg_price_p2_fix'] = 0\r\ndf['avg_price_p3_fix'] = 0\r\n\r\n\r\nfor ID in pd.unique(df.id):\r\n \r\n df.loc[df.id== ID,'avg_price_p1_var'] = prices[prices.id == ID]['price_p1_var'].mean()\r\n df.loc[df.id== ID,'avg_price_p2_var'] = prices[prices.id == ID]['price_p2_var'].mean()\r\n df.loc[df.id== ID,'avg_price_p3_var'] = prices[prices.id == ID]['price_p3_var'].mean()\r\n df.loc[df.id== ID,'avg_price_p1_fix'] = prices[prices.id == ID]['price_p1_fix'].mean()\r\n df.loc[df.id== ID,'avg_price_p2_fix'] = prices[prices.id == ID]['price_p2_fix'].mean()\r\n df.loc[df.id== ID,'avg_price_p3_fix'] = prices[prices.id == ID]['price_p3_fix'].mean()\r\n \r\n \r\n \r\n \r\ndf.to_csv('ML_Features.csv',encoding='utf-8',index=False) \r\n \r\n \r\n \r\n \r\n \r\n ","sub_path":"Feature_Engineering.py","file_name":"Feature_Engineering.py","file_ext":"py","file_size_in_byte":5354,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"555373225","text":"import os \nimport argparse\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\nimport keras\nfrom keras import backend as K\nfrom keras.models import load_model\nfrom keras.utils import np_utils\nfrom termcolor import colored,cprint\n\nK.set_image_dim_ordering('th')\n\nbase_dir = './'\nimg_dir = os.path.join(base_dir, 'image')\nif not os.path.exists(img_dir):\n os.makedirs(img_dir)\ncmap_dir = os.path.join(img_dir, 'cmap')\nif not os.path.exists(cmap_dir):\n os.makedirs(cmap_dir)\npartial_see_dir = os.path.join(img_dir,'partial_see')\nif not os.path.exists(partial_see_dir):\n os.makedirs(partial_see_dir)\norigin_dir = os.path.join(img_dir,'origin')\nif not os.path.exists(origin_dir):\n os.makedirs(origin_dir)\n\ndef read( filename ):\n\n raw_data = pd.read_csv( filename ) \n x_test = []\n for i in range(len(raw_data)):\n feat = np.fromstring(raw_data['feature'][i],dtype=int,sep=' ')\n feat = np.reshape(feat,(1,48,48))\n x_test.append(feat) \n x_test = np.array(x_test,dtype=float) / 255\n\n return x_test\n\ndef main():\n\n parser = argparse.ArgumentParser(prog='plot_saliency.py',\n description='ML-Assignment3 visualize attention heat map.')\n parser.add_argument('--epoch', type=int, metavar='<#epoch>', default=1)\n parser.add_argument('--model', type=str, metavar='<#model>', default='./model1/whole_model.h5')\n parser.add_argument('--data', type=str, metavar='<#data>', default='./model1/train.csv')\n args = parser.parse_args()\n model_path = args.model\n data_path = args.data\n\n emotion_classifier = load_model(model_path)\n print(colored(\"Loaded model from {}\".format(model_path), 'yellow'))\n\n x = read( data_path )\n\n input_img = emotion_classifier.input \n img_ids = [1]\n\n for idx in img_ids:\n\n val_proba = emotion_classifier.predict(x[idx].reshape(-1, 1, 48, 48))\n pred = val_proba.argmax(axis=-1)\n target = K.mean(emotion_classifier.output[:,pred])\n grads = K.gradients(target, input_img)[0]\n fn = K.function([input_img, K.learning_phase()], [grads])\n\n val_grads = fn([x[idx].reshape(-1, 1, 48, 48), 0])[0].reshape(48, 48, -1)\n\n# gradient normalize \n val_grads *= -1\n val_grads = np.max(np.abs(val_grads), axis=-1, keepdims=True)\n val_grads = (val_grads - np.mean(val_grads)) / (np.std(val_grads) + 1e-5)\n val_grads *= 0.1\n val_grads += 0.5\n val_grads = np.clip(val_grads, 0, 1)\n val_grads /= np.max(val_grads)\n\n heatmap = val_grads.reshape(48, 48)\n\n# original figure\n plt.figure()\n plt.imshow(x[idx].reshape(48, 48), cmap='gray')\n plt.colorbar()\n plt.tight_layout()\n fig = plt.gcf()\n plt.draw()\n fig.savefig(os.path.join(origin_dir, '{}.png'.format(idx)), dpi=100)\n print(colored(\"Saving image {}\".format('{}.png'.format(idx)), 'red'))\n\n\n# heatmap figure\n plt.figure()\n plt.imshow(heatmap, cmap=plt.cm.jet)\n plt.colorbar()\n plt.tight_layout()\n fig = plt.gcf()\n plt.draw()\n fig.savefig(os.path.join(cmap_dir, 'cmap{}.png'.format(idx)), dpi=100)\n print(colored(\"Saving image {}\".format('cmap{}.png'.format(idx)), 'red'))\n\n# masked figure \n thres = 0.55\n see = x[idx].reshape(48, 48)\n see[np.where(heatmap <= thres)] = np.mean(see)\n plt.figure()\n plt.imshow(see,cmap='gray')\n plt.colorbar()\n plt.tight_layout()\n fig = plt.gcf()\n plt.draw()\n fig.savefig(os.path.join(partial_see_dir, 'masked{}.png'.format(idx)), dpi=100)\n print(colored(\"Saving image {}\".format('masked{}.png'.format(idx)), 'red'))\n\nif __name__ == \"__main__\":\n main()\n ","sub_path":"hw3/p4_saliency_plot.py","file_name":"p4_saliency_plot.py","file_ext":"py","file_size_in_byte":3729,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"225588750","text":"import sys\nimport json\nimport csv\nimport urllib2\n\n__author__='Siying Zhang'\n\n \nif __name__=='__main__':\n\t# Retrieve key and bus number from command line\n\tkey = sys.argv[1]\n\tbusLine = sys.argv[2]\n\n\t# Request for json file from url given\n\turl = urllib2.Request('http://api.prod.obanyc.com/api/siri/vehicle-monitoring.json?key=%s&VehicleMonitoringDetailLevel=calls&LineRef=%s' %(key, busLine))\n\trequest = urllib2.urlopen(url)\n\tbusData = json.load(request)['Siri']['ServiceDelivery']['VehicleMonitoringDelivery'][0]['VehicleActivity']\n\n\twith open(sys.argv[3],'wb+') as csvfile:\n\t\twriter = csv.writer(csvfile)\n\n\t\t# Take a list of input into the csv file\n\t\twriter.writerow(['Latitude', 'Longitude', 'Stop Name', 'Stop Status']) \n\n\t\tfor i in range(0,len(busData)):\n\t\t\tvehicleLoc = busData[i]['MonitoredVehicleJourney']\n\t\t\tlat = vehicleLoc['VehicleLocation']['Latitude']\n\t\t\tlon = vehicleLoc['VehicleLocation']['Longitude']\n\n\t\t\tfor j in range(0,len(vehicleLoc)):\n\t\t\t\tif not vehicleLoc['OnwardCalls']:\n\t\t\t\t\tstopName = 'N/A'\n\t\t\t\t\tstopStatus = 'N/A'\n\t\t\t\telse:\n\t\t\t\t\tstopName = vehicleLoc['OnwardCalls']['OnwardCall'][0]['StopPointName']\n\t\t\t\t\tstopStatus = vehicleLoc['OnwardCalls']['OnwardCall'][0]['Extensions']['Distances']['PresentableDistance']\n\n\t\t\t\trow = [lat, lon, stopName,stopStatus]\n\t\t\t\twriter.writerow(row)\n\n\n\n\n","sub_path":"HW2/get_bus_info.py","file_name":"get_bus_info.py","file_ext":"py","file_size_in_byte":1307,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"497231273","text":"from django.db import models\nfrom django.contrib.auth.models import User\nfrom books.models import Book\n\n\n\nclass TradeRequest(models.Model):\n STATUS_PENDING = 'pending'\n STATUS_ACCEPTED = 'accepted'\n STATUS_DECLINED = 'declined'\n STATUS_CHOICES = (\n (STATUS_PENDING, 'Pending'),\n (STATUS_ACCEPTED, 'Accepted'),\n (STATUS_DECLINED, 'Declined'),\n )\n\n created_by = models.ForeignKey(User, on_delete=models.CASCADE)\n target = models.ForeignKey(Book, on_delete=models.CASCADE)\n created_at = models.DateTimeField(auto_now_add=True)\n updated_at = models.DateTimeField(auto_now=True)\n status = models.CharField(\n choices=STATUS_CHOICES,\n default=STATUS_PENDING,\n max_length=8,\n )\n message = models.CharField(blank=True, null=True, max_length=256)\n\n","sub_path":"backend/trade_requests/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":816,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"258057256","text":"# 1) Написать контекстный менеджер для работы с SQLite DB.\nimport sqlite3\n\n\nclass dbconnection():\n def __init__(self, db_name):\n self.db_name = db_name\n\n def __enter__(self):\n self.conn = sqlite3.connect(self.db_name)\n return self.conn\n\n def __exit__(self, type, value, traceback):\n self.conn.close()\n\n\n\n# 2) Создать базу данных студентов. У студента есть факультет,\n# группа, оценки, номер студенческого билета. Написать программу,\n# с двумя ролями: Администратор, Пользователь. Администратор\n# может добавлять, изменять существующих студентов.\n# Пользователь может получать список отличников, список всех\n# студентов, искать студентов по по номеру студенческого, получать\n# полную информацию о конкретном студенте (включая оценки,\n# факультет)\n\n\n\nclass user:\n\n @classmethod\n def get_best_students(cls):\n with dbconnection('univer.db') as conn:\n cursor = conn.cursor()\n cursor.execute('select name ,Surname from Students where st_id in ( select st_id from marks group '\n 'by St_id having avg(mark)=5)')\n print(list((cursor.fetchmany(100))))\n\n @classmethod\n def get_all_students(cls):\n with dbconnection('univer.db') as conn:\n cursor = conn.cursor()\n cursor.execute('select name, Surname from Students')\n print(list((cursor.fetchmany(100))))\n\n @classmethod\n def get_student_by_std_id(cls,id_):\n with dbconnection('univer.db') as conn:\n cursor = conn.cursor()\n\n cursor.execute('select name, Surname from Students where St_id = ?', (id_,))\n print(list((cursor.fetchmany(100))))\n\n @classmethod\n def get_full_info(cls,id_):\n with dbconnection('univer.db') as conn:\n cursor = conn.cursor()\n cursor.execute('select name,Surname,Faculty,Gr_no from students where St_id = ?', (id_,))\n print((cursor.fetchmany(100)))\n with dbconnection('univer.db') as conn:\n cursor = conn.cursor()\n cursor.execute('select St_id,Subject,Mark from Marks where St_id = ?', (id_,))\n print((cursor.fetchmany(100)))\n\n\nclass admin(user):\n\n @classmethod\n def update_students(cls,name,surname,faculty,gr_no,St_id):\n with dbconnection('univer.db') as conn:\n cursor = conn.cursor()\n cursor.execute('update students set name = ?,surname =?,faculty=?,gr_no=? where st_id=?', (name,surname,faculty,gr_no,St_id,))\n conn.commit()\n\n @classmethod\n def insert_students(cls,name,surname,faculty,gr_no,St_id):\n with dbconnection('univer.db') as conn:\n cursor = conn.cursor()\n cursor.execute('insert into students (name,surname,faculty,gr_no,St_id) values(?,?,?,?,?)', (name,surname,faculty,gr_no,St_id,))\n conn.commit()\n\n# user.get_all_students()\n# user.get_student_by_std_id()\n# user.get_full_info(40586)\n# admin.insert_students()\n# admin.update_students()\n\n","sub_path":"Lesson7/Lesson7_dz.py","file_name":"Lesson7_dz.py","file_ext":"py","file_size_in_byte":3389,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"446496069","text":"from openpack.basepack import DefaultNamed, Part\nimport mimetypes\nimport warnings\n\n\nclass ImagePart(DefaultNamed, Part):\n rel_type = (\n 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/image'\n )\n default_name = '/word/media/image.jpeg'\n\n \"\"\"\n ECMA-376 3nd Edition Part 1 Page 170 states:\n A producer that wants interoperability should use\n one of the following standard formats:\n - image/png ISO/IEC 15948:2003, http://www.libpng.org/pub/png/spec/\n - image/jpeg, http://www.w3.org/Graphics/JPEG\n \"\"\"\n interoperability_types = ['image/png', 'image/jpeg']\n\n def _set_name(self, name):\n super(ImagePart, self)._set_name(name)\n self._guess_mime_type(name)\n\n name = property(Part._get_name, _set_name)\n\n def _guess_mime_type(self, name):\n \"\"\"\n When setting the name, guess the mime type from the extension.\n Set the content_type for this instance only if a content_type is not\n already defined (this allows an instance to have a content-type pre-\n defined or for a subclass to define the content type, and it will not\n be overridden by the guessed type).\n \"\"\"\n ct, _ = mimetypes.guess_type(name)\n if ct and not self.content_type:\n self.content_type = ct\n if ct not in self.interoperability_types:\n warnings.warn(\n \"Image type %s is not guaranteed to be interoperable\" % ct\n )\n","sub_path":"paradocx/image.py","file_name":"image.py","file_ext":"py","file_size_in_byte":1496,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"397103969","text":"# coding=utf-8\n\"\"\"Tests for generating code from a non-annotated ast.\"\"\"\n# Copyright 2017 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# 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.\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport ast\nimport textwrap\nimport unittest\n\nimport pasta\n\n\nclass AutoFormatTest(unittest.TestCase):\n \"\"\"Tests that code without formatting info is printed neatly.\"\"\"\n\n def test_imports(self):\n src = 'from a import b\\nimport c, d\\nfrom ..e import f, g\\n'\n t = ast.parse(src)\n self.assertEqual(src, pasta.dump(t))\n\n def test_function(self):\n t = ast.parse('def a(b, c): d')\n self.assertEqual('def a(b, c):\\n d\\n', pasta.dump(t))\n\n def test_functions_nested(self):\n src = textwrap.dedent('''\\\n def a(b, c):\n def d(e): f\n g\n def h(): i\n j\n ''')\n formatted_src = textwrap.dedent('''\\\n def a(b, c):\n def d(e):\n f\n g\n def h():\n i\n j\n ''')\n t = ast.parse(src)\n self.assertEqual(formatted_src, pasta.dump(t))\n\n def test_class(self):\n t = ast.parse('class A(b, c): d')\n self.assertEqual('class A(b, c):\\n d\\n', pasta.dump(t))\n\n def test_classes_nested(self):\n src = textwrap.dedent('''\\\n class A(b, c):\n def d(self, e): f\n class G: h\n ''')\n formatted_src = textwrap.dedent('''\\\n class A(b, c):\n def d(self, e):\n f\n class G():\n h\n ''')\n t = ast.parse(src)\n self.assertEqual(formatted_src, pasta.dump(t))\n\n\ndef suite():\n result = unittest.TestSuite()\n result.addTests(unittest.makeSuite(AutoFormatTest))\n return result\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"pasta/base/codegen_test.py","file_name":"codegen_test.py","file_ext":"py","file_size_in_byte":2277,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"208312207","text":"import os\nfrom string import punctuation\nimport warnings\nfrom transformers import DataCollatorForTokenClassification\nimport torch\nimport json\nfrom transformers import AutoModelForTokenClassification, TrainingArguments, Trainer\nfrom transformers import AutoTokenizer, BertTokenizer, DistilBertTokenizer\nimport numpy as np\nfrom scipy.special import softmax\nimport nltk\nimport streamlit as st\nfrom stop_words import get_stop_words\n\nSTOP_WORDS = get_stop_words('en') + ['ah', 'oh', 'eh', 'um', 'uh', 'one\\'s', 'it\\'ll', 'whatever', 'he\\'ll']\n\n\n# class bcolors:\n# HEADER = '\\033[95m'\n# OKBLUE = '\\033[94m'\n# OKCYAN = '\\033[96m'\n# OKGREEN = '\\033[92m'\n# WARNING = '\\033[93m'\n# FAIL = '\\033[91m'\n# ENDC = '\\033[0m'\n# BOLD = '\\033[1m'\n# UNDERLINE = '\\033[4m'\n\n\nwarnings.simplefilter('ignore')\n\nbad_punct = [] # [x for x in punctuation if x != '\\'']\n\n\ndef tokenize_text(text):\n text = text.strip().lower()\n tokens = nltk.word_tokenize(text)\n return tokens\n\n\ndef replace_multi(txt, symbs):\n for s in symbs:\n txt = txt.replace(s, '')\n return txt\n\n\ndef prepare_tokens(txt):\n txt = replace_multi(txt, bad_punct)\n txt = txt.strip().lower()\n tokens = tokenizer(txt)\n return tokens\n\n\ndef slice_tokens(tokens, max_window_size=100, step=10):\n slices = []\n tokens = tokens['input_ids'][1:-1] # remove bos/eos\n positions = list(range(len(tokens)))\n sliced_positions = []\n start_pos = 0\n\n at_the_end = False\n\n while start_pos < len(tokens) - max_window_size + 1 or not at_the_end:\n if start_pos >= len(tokens) - max_window_size + 1:\n at_the_end = True\n lb = start_pos\n ub = min(start_pos + max_window_size, len(tokens))\n while lb >= 0:\n if not tokenizer.decode([tokens[lb]])[0].startswith('#'):\n break\n lb -= 1\n while ub < len(tokens):\n if not tokenizer.decode([tokens[ub - 1]])[0].endswith('#'):\n break\n ub += 1\n tokens_slice = [101] + tokens[lb:ub] + [102]\n attention_mask = [1 for i in range(len(tokens_slice))]\n slices.append({\n 'input_ids': tokens_slice,\n 'attention_mask': attention_mask,\n 'labels': [0 for i in range(len(tokens_slice))]\n })\n sliced_positions.append(positions[lb:ub])\n start_pos += step\n return slices, sliced_positions\n\n\ndef read_text(fname, delim='.', remove_punct=True):\n with open(fname) as f:\n text = f.read().lower()\n sentences = text.split(delim)\n if remove_punct:\n for i in range(len(sentences)):\n sentences[i] = sentences[i].strip().strip(punctuation).strip()\n sentences = [s for s in sentences if s]\n\n return sentences\n\n\ndef process_text(text, delim='.', remove_punct=True):\n text = text.lower()\n sentences = text.split(delim)\n if remove_punct:\n for i in range(len(sentences)):\n sentences[i] = sentences[i].strip().strip(punctuation).strip()\n sentences = [s for s in sentences if s]\n\n return sentences\n\n\ndef read_jsonl(text):\n def jlopen(txt):\n samples = []\n for l in txt.split('\\n'):\n l = l.strip()\n if not l:\n continue\n samples.append(json.loads(l))\n return samples\n scribd = jlopen(text)\n recovered_tokens = []\n true_predictions = []\n for s in scribd:\n sent = []\n labels = []\n for w in s['Words']:\n label = int(w['Confidence'] <= -2.)\n tokens = nltk.word_tokenize(w['Word'].lower())\n\n new_tokens = [t.split('\\'') for t in tokens]\n new_tokens = [' \\' '.join(tt).split() for tt in new_tokens]\n tokens = sum(new_tokens, [])\n\n labs = [label for t in tokens]\n sent.extend(tokens)\n labels.extend(labs)\n recovered_tokens.append(sent)\n true_predictions.append(labels)\n sentences = [' '.join(rt) for rt in recovered_tokens]\n return sentences, recovered_tokens, true_predictions\n\n\nfrom string import digits, ascii_lowercase\nfrom copy import deepcopy\n\n\ndef glue_tokens(tokens, suspictious_indicators):\n new_tokens, new_labels = [], []\n\n for token, label_idx in zip(tokens, suspictious_indicators):\n if not token.startswith(\"_\"):\n new_tokens[-1] = new_tokens[-1] + token[2:]\n new_labels[-1] = new_labels[-1] or label_idx\n else:\n new_labels.append(label_idx)\n new_tokens.append(token)\n return new_labels, new_tokens\n\n\ndef expand_ranges(tokens, indicators):\n N = len(tokens)\n previous_indicators = deepcopy(indicators)\n for i, (tok, ind) in enumerate(zip(tokens, previous_indicators)):\n if ind == 1 and tok in punctuation and tok != '\\'':\n indicators[i] = 0\n elif tok == '\\'':\n # print(tokens[i - 1:i + 2])\n repl = False\n if i > 0 and all(x in ascii_lowercase for x in tokens[i - 1]):\n indicators[i - 1] = 1\n repl = True\n if i + 1 < N and tokens[i + 1] in ['ll', 's', 've', 't', 'm', 're']:\n indicators[i + 1] = 1\n repl = True\n if repl:\n indicators[i] = 1\n elif ind == 1 and i > 0 and indicators[i - 1] == 0 and tokens[i - 1] in STOP_WORDS:\n indicators[i - 1] = 1\n\n for i, (tok, ind) in enumerate(zip(tokens, previous_indicators)):\n if i > 0 and i + 1 < N and previous_indicators[i - 1] == 1 and previous_indicators[i + 1] == 1 and \\\n tok not in punctuation and indicators[i] == 0 and tok == '\\'':\n indicators[i] = 1\n\n return tokens, indicators\n\n\ndef make_masked_text(tokens, indicators):\n l, r = 0, 0\n N = len(tokens)\n new_tokens = []\n original_phrases = []\n while l < N:\n if indicators[l] == 0:\n new_tokens.append(tokens[l])\n l += 1\n else:\n r = l\n while r < N and indicators[r] == 1:\n r += 1\n new_tokens.append('')\n original_phrases.append(tokens[l:r])\n l = r\n text = ' '.join(new_tokens)\n return text, original_phrases\n\n\nclass SentenceWithContext:\n def __init__(self, sentence, left_context, right_context):\n self.sentence = sentence\n self.left_context = left_context\n self.right_context = right_context\n\n def apply_tokenization(self, tokenizer):\n tokenization_result = {'input_ids': [], 'attention_mask': []}\n sentence_tokens = tokenizer(self.sentence)\n if self.left_context:\n left_context_tokens = tokenizer(self.left_context)\n else:\n left_context_tokens = dict.fromkeys(tokenization_result.keys(),\n [tokenizer.cls_token_id, tokenizer.sep_token_id])\n if self.right_context:\n right_context_tokens = tokenizer(self.right_context)\n else:\n right_context_tokens = dict.fromkeys(tokenization_result.keys(),\n [tokenizer.cls_token_id, tokenizer.sep_token_id])\n\n for tokenizer_outputs in [left_context_tokens, sentence_tokens, right_context_tokens]:\n for k, v in tokenization_result.items():\n v.extend(tokenizer_outputs[k][1:-1])\n\n self.left_border = len(left_context_tokens['input_ids']) - 1\n self.right_border = self.left_border + len(sentence_tokens['input_ids']) - 2\n\n tokenization_result['input_ids'] = \\\n [tokenizer.cls_token_id] + tokenization_result['input_ids'] + [tokenizer.sep_token_id]\n tokenization_result['labels'] = [0 for _ in range(len(tokenization_result['input_ids']))]\n tokenization_result['attention_mask'] = [1] + tokenization_result['attention_mask'] + [1]\n self.tokenization_result = tokenization_result\n return self.tokenization_result\n\n def match_result_with_predictions(self, predictions):\n self.true_tokens = self.tokenization_result['input_ids'][self.left_border:self.right_border]\n self.true_predictions = predictions[self.left_border:self.right_border]\n return self.true_tokens, self.true_predictions\n\n\ndef apply_set_of_trainers(trainers_collection, tokens_batch, sentences_with_contexts):\n central_tokens, true_predictions = None, None\n for trainer, threshold in trainers_collection:\n raw_predictions, labels, _ = trainer.predict(tokens_batch)\n # predictions = np.argmax(raw_predictions, axis=2)\n raw_preds_sf = softmax(raw_predictions, axis=2)\n if raw_preds_sf.shape[2] != 2:\n predictions = np.argmax(raw_predictions, axis=2)\n predictions = (predictions != 0).astype(np.int)\n else:\n predictions = (raw_preds_sf[:, :, 1] > threshold).astype(np.int)\n\n # Remove ignored index (special tokens)\n true_predictions_ = [\n [label_list[p] for (p, l) in zip(prediction, label) if l != -100]\n for prediction, label in zip(predictions, labels)\n ]\n central_tokens_ = [s.match_result_with_predictions(true_predictions_[i])\n for i, s in enumerate(sentences_with_contexts)]\n central_tokens_, true_predictions_ = zip(*central_tokens_)\n if central_tokens is None and true_predictions is None:\n central_tokens = central_tokens_\n true_predictions = true_predictions_\n else:\n for i in range(len(true_predictions_)):\n for j in range(len(true_predictions_[i])):\n if true_predictions_[i][j] == 'wrong_word':\n true_predictions[i][j] = 'wrong_word'\n return central_tokens, true_predictions\n\n\n@st.cache\ndef download_model(url, filename):\n import requests\n response = requests.get(url)\n\n totalbits = 0\n if response.status_code == 200:\n with open(os.path.join('models', filename), 'wb') as f:\n for chunk in response.iter_content(chunk_size=1024):\n if chunk:\n totalbits += 1024\n print(\"Downloaded\", totalbits // 1024, \"KB...\")\n f.write(chunk)\n\n\nlabel_list = ['none', 'wrong_word']\n\n# versions = [\n# ('models/distilbert_spoiled_ner_09_05__00_38.pth', 0.5),\n# ('models/distilbert_base_cased_10pcnt_missspel_medium_dataset_tuned_state_dict_222.pth', 0.5),\n# # 'trained_models/distilbert_spoiled_ner_08_05__13_23.pth',\n# ]\n\nwith open('config.json') as fl:\n config = json.load(fl)\n versions = config['versions']\n\ntrainers = []\nfor version_info in versions:\n model_checkpoint = version_info.get('model_type', 'distilbert-base-uncased')\n tokenizer = AutoTokenizer.from_pretrained(model_checkpoint)\n data_collator = DataCollatorForTokenClassification(tokenizer)\n # download_model(version_info['link'], version_info['name'])\n if 'label_list' in version_info:\n n_labels = len(version_info['label_list'])\n else:\n n_labels = len(label_list)\n model = AutoModelForTokenClassification.from_pretrained(model_checkpoint, num_labels=n_labels)\n args = TrainingArguments(\n \"test-wwd\",\n evaluation_strategy = \"epoch\",\n learning_rate=2e-5,\n per_device_train_batch_size=8,\n per_device_eval_batch_size=8,\n num_train_epochs=3,\n weight_decay=0.01,\n )\n trainer = Trainer(\n model,\n args,\n data_collator=data_collator,\n tokenizer=tokenizer,\n )\n\n model.load_state_dict(\n torch.load(os.path.join('models', version_info['name']), map_location=config['device']))\n model = model.eval()\n trainers.append((trainer, version_info['threshold']))\n","sub_path":"disfluency_detector.py","file_name":"disfluency_detector.py","file_ext":"py","file_size_in_byte":11752,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"129175084","text":"# -*- coding: utf-8 -*-\n\"\"\"implement a polynomial basis function.\"\"\"\n\nimport numpy as np\n\n\ndef build_poly(x, degree):\n \"\"\" BUILD_POLY Polynomial basis functions for input data x, for j=0 up to j=degree\n Takes an input vector x and returns a polynomial basis of degree j=degree\n\n INPUTS:\n x (N x 1): an array of the output variable with only 1 feature\n degree: The highest degree of the basis\n\n OUTPUTS:\n basis (N x degree): a polynomial basis on the output variable\n \"\"\"\n x_expanded = np.tile(x,[degree+1,1]).T #expands the variable to degree of basis\n powers = np.tile(np.arange(0,degree+1), [len(x),1]) #create the array of powers to raise\n basis = np.power(x_expanded, powers)\n \n return basis\n","sub_path":"labs/ex04/template/build_polynomial.py","file_name":"build_polynomial.py","file_ext":"py","file_size_in_byte":759,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"128169997","text":"class Integer(Number):\n \"\"\"\n Integer attribute.\n\n \"\"\"\n def __init__(self, **kwargs):\n super(Integer, self).__init__(**kwargs)\n self._type = int\n tmp_def = kwargs.get('default', self._type())\n if tmp_def:\n self._default = self._type(tmp_def)\n tmp_min = kwargs.get('minimum')\n if tmp_min:\n self._minimum = self._type(tmp_min)\n tmp_max = kwargs.get('maximum')\n if tmp_max:\n self._maximum = self._type(tmp_max)\n tmp_val = kwargs.get('value', self._type())\n if not tmp_val and self._default:\n self._value = self._default\n elif not tmp_val:\n self._value = self._type()\n else:\n self._value = tmp_val\n\n\n","sub_path":"python/config/core/attributes/integer.py","file_name":"integer.py","file_ext":"py","file_size_in_byte":757,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"517004482","text":"from animals import Animal\nfrom attributes import Birds\nfrom attributes import Flying\n\nclass NeneGoose(Animal, Birds, Flying):\n def __init__(self):\n Animal.__init__(self, 'Nene Goose', ['Leaves', 'Seeds', 'Fruit', 'Flowers'], ['Grassland'], 7)\n Flying.__init__(self)\n Birds.__init__(self)\n\n def __str__(self):\n return super().__str__() + '\"HONK!\"'\n","sub_path":"animals/nene_goose.py","file_name":"nene_goose.py","file_ext":"py","file_size_in_byte":382,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"298661539","text":"import scrapy\nfrom functools import reduce\n\nclass addmission_spider(scrapy.Spider):\n name = \"admission_info\"\n\n def start_requests(self):\n urls = [\n \"https://www.i.nagoya-u.ac.jp/gs/entranceexamination/\",\n\n\n ]\n\n for url in urls:\n yield scrapy.Request(url=url,callback=self.select_ad_doc)\n\n def parse(self, response):\n filename = 'test.html'\n with open(filename, 'wb') as f:\n f.write(response.body)\n #self.log('type of response', type(response))\n self.log('saved')\n\n def select_ad_doc(self, response):\n filename = 'test2.html'#response.url\n keywords = ['募集要項',\n '入学試験',\n ]\n f = open(filename, 'w')\n for i in response.css('*'):\n if reduce(lambda a, b: a or b, list(map(lambda x: x in i.get(), keywords))):\n #text_0 = i.css('::text').get() + '\\n'\n try:\n text_1 = response.urljoin(i.attrib['href']) + '\\n'\n f.write(text_1)\n except KeyError:\n continue\n self.log('test')\n f.close()\n\n\n","sub_path":"get_addmission_info/get_addmission_info/spiders/addmission_info_spider.py","file_name":"addmission_info_spider.py","file_ext":"py","file_size_in_byte":1192,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"75004999","text":"t = int(raw_input())\nfor tc in range(1, t+1):\n k, c, s = [int(x) for x in raw_input().split()]\n positions = []\n k_to_check = 0\n while k_to_check < k:\n position = 0\n for i in xrange(c):\n position = k * position\n position += min(k_to_check, k-1)\n k_to_check += 1\n positions.append(position)\n if len(positions) > s:\n print(\"Case #%d: IMPOSSIBLE\" % (tc))\n else:\n print(\"Case #%d: %s\" % (tc, \" \".join([str(pos+1) for pos in positions])))\n\n\n","sub_path":"codes/CodeJamCrawler/16_0_4_neat/16_0_4_robket_fractal.py","file_name":"16_0_4_robket_fractal.py","file_ext":"py","file_size_in_byte":471,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"38315546","text":"#!/usr/bin/env python\r\n# -*- coding:utf-8 -*-\r\n# Author: zhangsongpo\r\n# Email: zhangsp.520@qq.com\r\n# Description: 第四篇练习题第3题\r\n# Date: 2017年9月4日22:57:40\r\n# 写函数,判断用户传入的对象(字符串、列表、元组)长度是否大于5。\r\n\r\n# # note:一下是我的实现方法\r\n# def func_strlenth(str):\r\n# strlenth = len(str)\r\n# if strlenth > 5:\r\n# print(\"字符串%s的长度大于5\" % str)\r\n# else:\r\n# print(\"字符串%s的长度不大于5...\" % str)\r\n# def func_listlenth(list):\r\n# listlenth = len(list)\r\n# if listlenth > 5:\r\n# print(\"列表%s的长度大于5\" % list)\r\n# else:\r\n# print(\"列表%s的长度不大于5...\" % list)\r\n# def func_tuplenth(tuple):\r\n# tuplenth = len(tuple)\r\n# if tuplenth > 5:\r\n# print(\"元组的长度大于5\")\r\n# else:\r\n# print(\"元组的长度不大于5...\")\r\n#\r\n# str1 = 'zhangsongpo'\r\n# list1 = ['Z','S','P']\r\n# tup1 = ('z','h','a','n','g','s','p',17)\r\n# print(tup1)\r\n# func_strlenth(str1)\r\n# func_listlenth(list1)\r\n# func_tuplenth(tup1)\r\n\r\n# 武沛齐的实现方式\r\n\r\ndef func_lenth(parameter):\r\n if isinstance(parameter, str) or isinstance(parameter, list) or isinstance(parameter, tuple):\r\n if len(parameter) > 5:\r\n return True\r\n else:\r\n return False\r\n else:\r\n print(\"请输入\\\"字符串\\\",\\\"列表\\\"或\\\"元组\\\".\")\r\n return None\r\n\r\n# 因为数字无法使用len()计算,所以需要先通过isinstance()将不是字符串、元组、列表的变量过滤掉\r\na = 123\r\nstr1 = 'zhangsongpo'\r\nlist1 = ['Z','S','P']\r\ntup1 = ('z','h','a','n','g','s','p',17)\r\n\r\nprint(func_lenth(a))\r\nprint(func_lenth(str1))\r\nprint(func_lenth(list1))\r\nprint(func_lenth(tup1))\r\n\r\n\r\n\r\n","sub_path":"Study/20170829LaonanhaiPython/d3/day6/4_prictice_3.py","file_name":"4_prictice_3.py","file_ext":"py","file_size_in_byte":1776,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"559215006","text":"from __future__ import absolute_import\nimport dj_database_url\n\n# SECURITY WARNING: don't run with debug turned on in production!\nDEBUG = False\nTEMPLATE_DEBUG = False\n\nfrom .common import *\nfrom local_settings import *\nfrom xSACdb.version import VERSION\n\n\nif 'RAVEN_CONFIG' in locals():\n RAVEN_CONFIG['release'] = VERSION['tag']\n RAVEN_CONFIG['site'] = CLUB['name']\nelse:\n RAVEN_CONFIG = {}\n\nif 'XSACDB_CONTAINER' in os.environ and os.environ['XSACDB_CONTAINER'] == 'DOCKER':\n # If in a docker container, parse the database URL\n DATABASES = {\n 'default': dj_database_url.parse(\n os.environ['DATABASE_URL']\n )\n }\n","sub_path":"src/xSACdb/settings/production.py","file_name":"production.py","file_ext":"py","file_size_in_byte":652,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"454043797","text":"import numpy as np\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nfrom libsvmdata import fetch_libsvm\nfrom andersoncd.data.real import load_openml\nfrom andersoncd.plot_utils import configure_plt\n\nfrom andersoncd.lasso import solver_enet, apcg_enet\n\n\nconfigure_plt()\n\n###############################################################################\n# Load the data:\n\n# n_features = 1000\nX, y = fetch_libsvm(\"rcv1.binary\", normalize=True)\n# X = X[:, :n_features]\n\n# y -= y.mean()\n# y /= norm(y)\n\nX, y = load_openml(\"leukemia\")\n\n###############################################################################\n# Run algorithms:\n\n# solvers parameters:\ndiv_alpha = 10\ndiv_rho = 10\nalpha_max = np.max(np.abs(X.T @ y))\nalpha = alpha_max / div_alpha\nrho = alpha / div_rho\n# rho = 0\n\ntol = 1e-20\nmax_iter = 20_000\nf_gap = 1\nall_algos = [\n # ('apcg', False),\n # ('pgd', False),\n # ('pgd', True),\n # ('fista', False),\n # ('cd', False),\n # ('rcd', False),\n ('cd', True),\n]\n\ndict_algo_name = {}\ndict_algo_name[\"pgd\", False] = \"GD\"\ndict_algo_name[\"cd\", False] = \"CD\"\ndict_algo_name[\"rcd\", False] = \"RCD\"\ndict_algo_name[\"pgd\", True] = \"GD - Anderson\"\ndict_algo_name[\"cd\", True] = \"CD - Anderson\"\ndict_algo_name[\"fista\", False] = \"GD - inertial\"\ndict_algo_name[\"apcg\", False] = \"CD - inertial\"\n\ntmax = 2\n# tmax =\ndict_Es = {}\ndict_times = {}\n\nfor algo in all_algos:\n print(\"Running \", dict_algo_name[algo])\n if algo[0] == 'apcg':\n _, E, _, times = apcg_enet(\n X, y, alpha, rho=rho, max_iter=max_iter, tol=tol,\n f_gap=f_gap, verbose=True, compute_time=True, tmax=tmax)\n else:\n _, E, gaps, times = solver_enet(\n X, y, alpha=alpha, rho=rho,\n f_gap=f_gap, max_iter=max_iter, tol=tol,\n algo=algo[0], use_acc=algo[1], verbose=True, compute_time=True,\n tmax=tmax, seed=0)\n dict_Es[algo] = E.copy()\n dict_times[algo] = times\n\n\ncurrent_palette = sns.color_palette(\"colorblind\")\ndict_color = {}\ndict_color[\"pgd\"] = current_palette[0]\ndict_color[\"fista\"] = current_palette[0]\ndict_color[\"cd\"] = current_palette[1]\ndict_color[\"rcd\"] = current_palette[1]\ndict_color[\"apcg\"] = current_palette[1]\n\n\np_star = np.infty\nfor E in dict_Es.values():\n p_star = min(p_star, min(E))\n\n###############################################################################\n# Plot convergence curves:\n\n# plt.figure()\n\nfig, ax = plt.subplots(figsize=(9, 6))\nfig2, ax2 = plt.subplots(figsize=(9, 6))\n\nfor algo in all_algos:\n E = dict_Es[algo]\n times = dict_times[algo]\n use_acc = algo[1]\n if use_acc:\n linestyle = 'dashed'\n elif algo[0].startswith(('fista', 'apcg')):\n linestyle = 'dotted'\n elif algo[0].startswith('rcd'):\n linestyle = (0, (3, 5, 1, 5, 1, 5))\n else:\n linestyle = 'solid'\n ax.semilogy(\n f_gap * np.arange(len(E)), E - p_star, label=dict_algo_name[algo],\n color=dict_color[algo[0]], linestyle=linestyle)\n\n ax2.semilogy(\n times, E - p_star, label=dict_algo_name[algo],\n color=dict_color[algo[0]], linestyle=linestyle)\n\n\nax.set_ylabel(r\"$f(x^{(k)}) - f(x^{*})$\")\nax.set_xlabel(r\"iteration $k$\")\n\nax2.set_ylabel(r\"$f(x^{(k)}) - f(x^{*})$\")\nax2.set_xlabel(\"Time (s)\")\nax.set_yticks((1e-15, 1e-10, 1e-5, 1e0))\nax2.set_yticks((1e-15, 1e-10, 1e-5, 1e0))\nax.set_title(r\"Lasso $\\lambda_{\\max} / %i$\" % div_alpha)\nax2.set_title(r\"Lasso $\\lambda_{\\max} / %i$\" % div_alpha)\nfig.tight_layout()\nfig2.tight_layout()\nax.legend()\nfig.show()\nfig2.show()\n","sub_path":"examples/expe_time/plot_lasso_time.py","file_name":"plot_lasso_time.py","file_ext":"py","file_size_in_byte":3506,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"592768840","text":"import brain.py as nn\r\nimport brain\r\n\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport pylib.pyplot as plib\r\n\r\nprint(brain.__version__)\r\nprint(brain.__platform__)\r\n\r\nclass ClassifierModel():\r\n def __init__(self):\r\n self.input = nn.layers.InputLayer(2)\r\n self.dense2 = nn.layers.Dense(4, activation=nn.sigmoid, input=self.input)\r\n self.dense3 = nn.layers.Dense(3, activation=nn.sigmoid, input=self.dense2)\r\n self.dense4 = nn.layers.Dense(3, activation=nn.sigmoid, input=self.dense3)\r\n\r\n def predict(self, inputs):\r\n h = self.input(inputs)\r\n h = self.dense2(h)\r\n h = self.dense3(h)\r\n h = self.dense4(h)\r\n\r\n return h\r\n\r\n def train(self, inputs, targets):\r\n trainer = nn.math.Trainer()\r\n trainer.compute(self.input, inputs)\r\n\r\n trainer(self.dense2)\r\n trainer(self.dense3)\r\n trainer(self.dense4)\r\n\r\n trainer.backprop(targets)\r\n\r\ndef func_line1(x):\r\n return x * 0.1 + 0.1\r\n\r\ndef func_line2(x):\r\n return x * 0.85 - 0.9\r\n\r\ndef category(x, y):\r\n if y > func_line1(x):\r\n return [0, 0, 1]\r\n else:\r\n if y > func_line2(x):\r\n return [0, 1, 0]\r\n else:\r\n return [1, 0, 0]\r\n\r\ndef category_strict(data):\r\n x, y = data\r\n [a, b, c] = category(x, y)\r\n \r\n if a == 1:\r\n return 2\r\n if b == 1:\r\n return 1\r\n if c == 1:\r\n return 0\r\n\r\nmodel = None\r\ndef category_nn(data):\r\n mat = model.predict(data)\r\n max = mat.max()\r\n [a, b, c] = mat.tolist()[0]\r\n \r\n if a == max:\r\n return 2\r\n if b == max:\r\n return 1\r\n if c == max:\r\n return 0\r\n\r\nif __name__ == \"__main__\":\r\n setlength = 150\r\n set = np.random.rand(setlength, 2) * 2 - 1\r\n\r\n model = ClassifierModel()\r\n\r\n maxepochs = 100\r\n for epoch in range(maxepochs):\r\n print(\"Epoch {}/{}\".format(epoch + 1, maxepochs))\r\n np.random.shuffle(set)\r\n \r\n for i in range(len(set)):\r\n x, y = set[i]\r\n model.train(set[i], category(x, y))\r\n\r\n fig, axs = plt.subplots(2)\r\n for ax in axs:\r\n plib.function(ax, func_line1, 1, start=-1, step=0.01)\r\n plib.function(ax, func_line2, 1, start=-1, step=0.01)\r\n ax.set_xlim(-1, 1)\r\n ax.set_ylim(-1, 1)\r\n\r\n strict_ds = plib.dataset(['A', 'B', 'C'], set, category_strict)\r\n plib.plot_ds(axs[0], strict_ds, \".\", colors=[\"r\", \"g\", \"b\"])\r\n\r\n nn_ds = plib.dataset(['A', 'B', 'C'], set, category_nn)\r\n plib.plot_ds(axs[1], nn_ds, \".\", colors=[\"r\", \"g\", \"b\"])\r\n\r\n plt.show()","sub_path":"classification.py","file_name":"classification.py","file_ext":"py","file_size_in_byte":2581,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"174194951","text":"import random\nfrom collections import OrderedDict\nfrom django.conf import settings as django_settings\nfrom django.utils.safestring import mark_safe\nfrom django.utils.translation import ugettext_lazy as _, get_language, string_concat\nfrom django.db.models import Q\nfrom magi.default_settings import RAW_CONTEXT\nfrom magi.utils import (\n globalContext,\n toTimeZoneDateTime,\n toCountDown,\n staticImageURL,\n FAVORITE_CHARACTERS_NAMES,\n FAVORITE_CHARACTERS_IMAGES,\n mergedFieldCuteForm,\n)\nfrom bang import models\n#from bang.model_choices import TRAINABLE_RARITIES\n\nFONTS_PER_LANGUAGE = {\n 'zh-hans': {\n 'name': 'Noto Sans SC',\n 'url': '//fonts.googleapis.com/earlyaccess/notosanssc.css',\n 'title_weight': 800,\n },\n 'zh-hant': {\n 'name': 'Noto Sans TC',\n 'url': '//fonts.googleapis.com/earlyaccess/notosanstc.css',\n 'title_weight': 800,\n },\n 'kr': {\n 'name': 'Nanum Gothic',\n 'url': '//fonts.googleapis.com/css?family=Nanum+Gothic:400,800',\n 'title_weight': 800,\n },\n 'ja': {\n 'name': 'Rounded Mplus 1c',\n 'url': '//fonts.googleapis.com/earlyaccess/roundedmplus1c.css',\n 'title_weight': 900,\n },\n 'ru': {\n 'name': 'Comfortaa',\n 'url': '//fonts.googleapis.com/css?family=Comfortaa:400',\n 'title_url': '//fonts.googleapis.com/css?family=Exo+2:800',\n 'title': 'Exo 2',\n 'title_weight': 800,\n },\n 'vi': {\n 'name': 'Montserrat',\n 'url': '//fonts.googleapis.com/css?family=Montserrat:400,700',\n 'title_weight': 700,\n },\n}\n\nTITLE_CSS_CLASSES = 'h1, h2, h3, h4, h5, h6, .title, .navbar-brand, .btn-lg, .btn-xl'\n\ndef bangGlobalContext(request):\n context = globalContext(request)\n # Change font depending on language\n if context['current_language'] in FONTS_PER_LANGUAGE:\n f = FONTS_PER_LANGUAGE[context['current_language']]\n if 'name' in f and 'url' in f:\n context['extracss'] = context.get('extracss', '') + u'\\n @import url({url});{title_url}\\n\\\n body {{ font-family: \\'{name}\\', sans-serif; }}\\n {css_classes} {{ font-family: \\'{title_name}\\', monospace;{title_weight} }}'.format(\n url=f['url'],\n title_url=(u'\\n@import url({url});'.format(url=f['title_url']) if 'title_url' in f else ''),\n name=f['name'],\n css_classes=TITLE_CSS_CLASSES,\n title_name=f.get('title', f['name']),\n title_weight=(u' font-weight: {weight};'.format(weight=f['title_weight'])\n if 'title_weight' in f else ''),\n )\n for popup_name, popup in context.get('corner_popups', {}).items():\n popup['image_overflow'] = True\n if popup_name == 'happy_birthday':\n popup['image'] = staticImageURL('birthday_kanae.png')\n return context\n\ndef randomArtForCharacter(character_id):\n if django_settings.IS_CHARACTER_BIRTHDAY:\n return None\n try:\n card = models.Card.objects.filter(\n member_id=character_id,\n ).exclude(\n (Q(art__isnull=True) | Q(art=''))\n & (Q(transparent__isnull=True) | Q(transparent='')),\n ).exclude(\n show_art_on_homepage=False,\n show_trained_art_on_homepage=False,\n ).order_by('?')[0]\n except IndexError:\n return None\n if not card.trainable or (not card.art and not card.art_trained):\n trained = random.choice([v for v, s in [\n (False, card.show_art_on_homepage and card.transparent_url),\n (True, card.show_trained_art_on_homepage and card.transparent_trained_url),\n ] if s\n ])\n return {\n 'foreground_url': card.transparent_trained_url if trained else card.transparent_url,\n 'about_url': card.item_url,\n 'position': { 'size': 'cover', 'x': 'center', 'y': 'center' },\n }\n trained = random.choice([v for v, s in [\n (False, card.show_art_on_homepage and card.art_url),\n (True, card.show_trained_art_on_homepage and card.art_trained_url),\n ] if s\n ])\n return {\n 'url': card.art_trained_url if trained else card.art_url,\n 'hd_url': (\n card.art_trained_2x_url or card.art_trained_original_url\n ) if trained else (card.art_2x_url or card.art_original_url),\n 'about_url': card.item_url,\n }\n\ndef memberBandMergeCuteForm(cuteform):\n mergedFieldCuteForm(cuteform, {\n 'title': string_concat(_('Member'), '/', _('Band')),\n 'extra_settings': {\n 'modal': 'true',\n 'modal-text': 'true',\n },\n }, OrderedDict ([\n ('member', lambda k, v: FAVORITE_CHARACTERS_IMAGES[int(k)]),\n ('i_band', lambda k, v: staticImageURL(v, folder='band', extension='png')),\n ]))\n\ndef rarity_to_stars_images(rarity):\n return u''.format(\n static_url=RAW_CONTEXT['static_url'],\n un='' if rarity in models.Card.TRAINABLE_RARITIES else 'un',\n ) * rarity\n\ndef generateDifficulty(difficulty):\n note_image = staticImageURL('note.png')\n return u'{big_images}{small_images}'.format(\n big_images=(u''.format(note_image) * (difficulty // 5)),\n small_images=(u''.format(note_image) * (difficulty % 5)),\n )\n\ndef bandField(band, i):\n return {\n 'image': staticImageURL('mini_band_icon/{}.png'.format(band)),\n 'verbose_name': _('Band'),\n 'type': 'image_link',\n 'link': u'/members/?i_band={}'.format(i),\n 'ajax_link': u'/ajax/members/?i_band={}&ajax_modal_only'.format(i),\n 'link_text': band,\n 'value': staticImageURL('band/{}.png'.format(band)),\n }\n\n# For Event, Gacha, Song\ndef subtitledImageLink(item, verbose_name, icon=None, image=None, subtitle=None):\n return {\n 'image': image,\n 'icon': icon,\n 'verbose_name': verbose_name,\n 'verbose_name_subtitle': subtitle or unicode(item),\n 'value': (getattr(item, '{}image_url'.format(\n models.Account.VERSIONS[models.LANGUAGES_TO_VERSIONS.get(get_language(), 'EN')]['prefix'],\n ), None) or item.image_url),\n 'type': 'image_link',\n 'link': item.item_url,\n 'ajax_link': item.ajax_item_url,\n 'link_text': subtitle or unicode(item),\n }\n\ndef add_rerun_buttons(view, buttons, request, item):\n if request.user.is_authenticated() and request.user.hasPermission('manage_main_items'):\n for version in item.versions:\n i_version = models.Rerun.get_i('version', version)\n buttons[u'{}add_rerun'.format(models.Rerun.VERSIONS[version]['prefix'])] = {\n 'classes': view.item_buttons_classes + ['staff-only'],\n 'show': True,\n 'url': u'/reruns/add/?{item}_id={item_id}&i_version={i_version}'.format(\n item=type(item).__name__.lower(),\n item_id=item.id,\n i_version=i_version,\n ),\n 'icon': 'date',\n 'title': u'Add rerun dates in {}'.format(models.Rerun.get_verbose_i('version', i_version)),\n 'has_permissions': True,\n 'open_in_new_window': True,\n }\n return buttons\n\ndef add_rerun_fields(view, item, request):\n extra_fields = []\n if len(item.all_reruns):\n for rerun in item.all_reruns:\n extra_fields.append(('{}rerun'.format(rerun.version_prefix), {\n 'icon': 'date',\n 'verbose_name': _('Rerun'),\n 'type': 'html',\n 'value': u'
{}
'.format(u'
'.join([\n unicode(x) for x in [\n toCountDown(date=rerun.end_date if rerun.status == 'current' else rerun.start_date,\n sentence=_('{time} left') if rerun.status == 'current' else _('Starts in {time}'),\n classes=['fontx1-5']),\n u'{}'.format(_('Beginning')) if rerun.start_date else None,\n toTimeZoneDateTime(rerun.start_date, [rerun.version_timezone, 'Local time'], ago=True),\n u'{}'.format(_('End')) if rerun.end_date else None,\n toTimeZoneDateTime(rerun.end_date, [rerun.version_timezone, 'Local time'], ago=True),\n u'{edit_sentence}'.format(\n edit_url=rerun.edit_url,\n classes=u' '.join(view.item_buttons_classes + ['staff-only']),\n edit_sentence=rerun.edit_sentence,\n ) if (request\n and request.user.is_authenticated()\n and request.user.hasPermission('manage_main_items'))\n else None,\n ] if x\n ])),\n }))\n return extra_fields\n","sub_path":"bang/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":9100,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"618466558","text":"import math\nimport time\nfrom vector2 import Vector2\n\nclass Aimbot(object):\n def __init__(self):\n self.gamestate = None\n\n self.paddle_max_speed = 100.0 #test server default speed\n self.paddle_step_size = 2.0\n self.paddle_dir = 0\n self.estimated_server_time = 0\n self.server_time_difference = 0\n self.command_lag = 0\n self.command_interval = 0.2\n self.ball_target = 0\n\n\n def lag_correction(self):\n return self.estimated_server_time - self.gamestate.time + self.command_lag\n\n def steps_in_lag_correction(self):\n return round(self.lag_correction() * self.paddle_max_speed / self.paddle_step_size)\n\n\n def project_future_pad_pos(self, time_interval, new_dir):\n return new_dir * self.paddle_max_speed * time_interval + self.projected_pad_pos()\n\n def projected_pad_pos(self):\n #return self.paddle_y + self.paddle_dir * self.paddle_max_speed * self.lag_correction()\n return self.gamestate.left_paddle_y + self.paddle_dir * self.paddle_step_size * self.steps_in_lag_correction()\n\n def paddle_time_to_target(self, target_y):\n if self.paddle_max_speed < 0.0001: return 1.0\n return math.fabs(target_y - self.projected_pad_pos()) / self.paddle_max_speed\n\n #Check for missiles along the path\n def dodge_missiles(self, target_y, target_time):\n incoming_missiles = [m for m in self.gamestate.missiles if m.direction.x < 0.0]\n\n for missile in incoming_missiles:\n missile_y = missile.get_collision_point().y\n missile_time = missile.get_collision_time()\n\n if missile_time > target_time + self.command_lag:\n #Missile hits after target; prepare and queue move out of the way\n return self.prepare_for_incoming_missile(target_y, target_time, missile_y, missile_time)\n\n accuracy = math.fabs(self.ball_target - missile_y)\n dodge_margin = self.gamestate.paddle_height / 2.0 + 10.0\n if accuracy < 0.1 and target_time - missile_time < self.command_lag:\n #Missile will be very close to target so try to adjust as near as possible\n dodge_margin = self.gamestate.paddle_height / 2.0 + accuracy - 0.0001\n\n #Missile hits before target; dodge missile to the best side\n #Missile is at target spot so change target\n if missile_y >= target_y - dodge_margin and missile_y <= target_y + dodge_margin:\n\n if missile_y <= self.gamestate.paddle_height + 0.001:\n #Dodge to middle\n new_target_y = missile_y + dodge_margin\n elif missile_y >= self.gamestate.max_height - self.gamestate.paddle_height - 0.001:\n #Dodge to middle\n new_target_y = missile_y - dodge_margin\n elif self.estimated_server_time - missile_time < self.minimum_safe_dodge_time():\n #Dodge to only side\n sign = 1.0 if self.projected_pad_pos() - missile_y > 0.0 else -1.0\n new_target_y = missile_y + dodge_margin * sign\n #Dodge to better side\n elif self.ball_target < missile_y:\n new_target_y = missile_y - dodge_margin\n else:\n new_target_y = missile_y + dodge_margin\n\n #print 'Changing', target_y, target_time - self.estimated_server_time, ' -> ', new_target_y, missile_time - self.estimated_server_time\n return new_target_y, missile_time\n\n if (self.projected_pad_pos() < missile_y and missile_y < target_y) or (self.projected_pad_pos() > missile_y and missile_y > target_y):\n #Missile is in our way so dodge it\n projected_pos = self.project_future_pad_pos(missile_time - self.estimated_server_time, self.paddle_dir)\n sign = 1.0\n if self.paddle_dir < 0.0:\n sign = -1.0\n\n #rint 'leff, projected_pos, missile_traget', self.projected_pad_pos(), projected_pos, missile_y, (missile_time - self.estimated_server_time)\n if missile_y >= projected_pos - dodge_margin and missile_y <= projected_pos + dodge_margin:\n maximum_gain = (missile_time - self.estimated_server_time - self.command_lag) * self.paddle_max_speed * (1.0 - math.fabs(self.paddle_dir))\n if maximum_gain > 0.001:\n #check if we can speed up\n new_pos = projected_pos + maximum_gain * sign\n if not (missile_y >= new_pos - dodge_margin and missile_y <= new_pos + dodge_margin):\n #speed up\n new_target_y = new_pos\n return new_target_y, missile_time\n \n #slow down\n new_target_y = missile_y - dodge_margin * sign\n return new_target_y, missile_time\n else:\n pass #Missile wont hit; don't care\n\n return target_y, target_time\n\n def prepare_for_incoming_missile(self, target_y, target_time, missile_y, missile_time):\n #print 'preparting for', missile_y, missile_time, target_y, target_time\n dodge_margin = self.gamestate.paddle_height / 2.0 + 10.0\n if not (missile_y >= target_y - dodge_margin and missile_y <= target_y + dodge_margin):\n return target_y, target_time #Missile will not hit\n\n time_dif = missile_time - target_time - self.command_lag\n steps = math.floor(time_dif * self.paddle_max_speed / self.paddle_step_size)\n maximum_movement = steps * self.paddle_step_size\n\n if not (missile_y >= target_y + maximum_movement - dodge_margin and missile_y <= target_y - maximum_movement + dodge_margin):\n return target_y, target_time #Enough time to move out of the way\n\n #print 'Incoming in', time_dif, maximum_movement, missile_y, target_y, self.ball_target\n #Prepare our position so that we have enough time to move out of the way of the missile while still hitting the ball\n available_steps_before_missile = math.ceil(time_dif * self.paddle_max_speed / self.paddle_step_size)\n\n sign = 1.0\n if self.ball_target < missile_y:\n sign = -1.0\n\n #Check corners and dodge to middle\n if missile_y <= self.gamestate.paddle_height + 0.001 and self.ball_target < missile_y:\n new_target_y = min(self.ball_target, missile_y + dodge_margin - sign * maximum_movement)\n elif missile_y >= self.gamestate.max_height - self.gamestate.paddle_height - 0.001 and self.ball_target > missile_y:\n new_target_y = max(missile_y - dodge_margin + sign * maximum_movement, self.ball_target)\n else:\n new_target_y = missile_y + sign * dodge_margin - sign * maximum_movement\n\n #print 'moving from', target_y, 'to', new_target_y\n\n return new_target_y, target_time\n\n\n\n def get_dir_command(self, target_y, target_time):\n\n #Find direction and distance to target\n distance = target_y - self.projected_pad_pos()\n if (math.fabs(distance) < 0.0001):\n #print 'Target reached:', self.gamestate.left_paddle_y\n self.paddle_dir = 0.0\n return 0\n direction = 1.0\n if self.projected_pad_pos() > target_y:\n direction = -1.0\n\n #Check ball travel time and adjust accordingly\n travel_time = self.paddle_time_to_target(target_y)\n max_time_to_target = target_time - self.estimated_server_time - self.command_lag\n\n if (travel_time > 0.05 and travel_time > max_time_to_target and max_time_to_target > 0.0):\n #We're screwed so full speed and hope for best :)\n self.paddle_dir = direction\n return direction\n\n if travel_time > self.command_interval:\n self.paddle_dir = direction\n return direction # full speed\n elif travel_time > 0.00001:\n #new_dir = direction * travel_time / self.command_interval\n #print 'Travel time : ', travel_time, ' at full speed. Changing to ', new_dir\n #self.paddle_dir = new_dir\n #steps_to_target is less than what we can do in 0.2 so\n #change direction so that we make enough steps during command_interval\n steps_to_target = math.fabs(distance / self.paddle_step_size)\n speed_to_use = steps_to_target / math.ceil(steps_to_target)\n steps_to_target = math.ceil(steps_to_target)\n steps_in_command_interval = math.ceil(self.command_interval * self.paddle_max_speed / self.paddle_step_size)\n new_dir = direction * speed_to_use * steps_to_target / steps_in_command_interval\n self.paddle_dir = min(1.0, max(-1.0, new_dir))\n #print 'distance to target, steps, dir, pos', distance, steps_in_command_interval, new_dir, self.gamestate.left_paddle_y\n return self.paddle_dir \n else:\n #Can reach here when target is almost there, but not quite\n self.paddle_dir = 0.0\n return 0.0\n\n #Find direction to target so that we hit it at the same time with ball\n def get_dir_to_target_with_time(self, target, time):\n #Estimate steps based on given time.\n steps_in_time = time * self.paddle_max_speed / self.paddle_step_size\n return get_dir_to_target_with_steps(self, target, steps_in_time)\n\n #Find direction to target so that we hit target at the same step with ball\n def get_dir_to_target_with_steps(self, target, steps):\n distance = self.project_pad_pos() - target\n step_size = distance / steps\n direction = step_size / self.paddle_step_size\n direction = min(1.0, max(-1.0, direction))\n self.paddle_dir = direction\n return direction\n\n def probable_steps_in_interval(self):\n steps = self.command_lag * self.paddle_max_speed / self.paddle_step_size\n return steps\n\n def minimum_safe_dodge_time(self):\n dodge_margin = 5.0 + self.gamestate.paddle_height / 2.0\n time = (dodge_margin / self.paddle_max_speed) + self.command_lag\n return time\n\n def can_make_it_to_target_in_time(self, target, travel_time):\n distance = math.fabs(target - self.projected_pad_pos())\n\n if distance < 0.1: \n return True\n\n if travel_time is None:\n return False\n\n return distance < self.paddle_max_speed * travel_time\n\n #The time the missile can delay the paddle from moving to target if the paddle dodges missile\n def maximum_missile_delay(self):\n #Theoretical maximum delay the missile can cause if hit perfectly\n paddle_delay = self.gamestate.paddle_height / self.paddle_max_speed\n return paddle_delay\n\n #Sure win strategy: we can hit the opponent with the missile at the same time when the ball hits\n #Or sure lose if they can hit us\n def check_for_hittable_missile(self, simulator, paddle_y, target, time_to_target, missile_travel_time):\n #Check if paddle can make it to target so that we can hit it at the appointed time\n p_min, p_max = simulator.get_paddle_range(paddle_y, time_to_target - missile_travel_time)\n if target < p_max or target > p_min:\n return True\n return False\n\n #Check if we can defend a missile by pre-firing our own\n #Returns target point where to aim (as late as possible, which gives best accuracy & best chance not to waste missile)\n def check_for_defendable_missile(self, simulator, paddle_y, target, time_to_target, missile_travel_time):\n #The target area can be any spot of enemy paddle\n target_min, target_max = target - self.gamestate.paddle_height / 2, target + self.gamestate.paddle_height / 2\n p_min, p_max = simulator.get_paddle_range(paddle_y, target, time_to_target - missile_travel_time)\n if target < p_max or target > p_min:\n return target\n elif p_max > target_min:\n return target_min\n elif p_min < target_max:\n return target_max\n\n return None","sub_path":"ponglib/aimbot.py","file_name":"aimbot.py","file_ext":"py","file_size_in_byte":12183,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"344560892","text":"from OpenGL.GL import *\nfrom OpenGL.GLUT import *\nfrom OpenGL.GLU import *\nfrom PIL.Image import *\nfrom math import *\n\n# Memo per me:\n# x verso destra\n# y verso l'alto\n# z verso di me\n\n# Alcuni valori utili\nrot_asse = 0.0\nrot_orbita = 0.0\nraggio_terra = 2.3\nraggio_luna = 0.6\nlimite_max = 1000\nlimite_min = 0.001\ntexture = 0\ncamera = [0.0, 0.0, -20.0]\nangolo_sugiu = 0.0\nangolo_sxdx = 0.0\n\n\n# Importo le texture dai file\ndef caricaTexture(filename):\n image = open(filename)\n ix = image.size[0]\n iy = image.size[1]\n\n # Ho dovuto fare una conversione a RGBA per ottenere la trasparenza\n\n image = image.convert(\"RGBA\").tobytes(\"raw\", \"RGBA\", 0, -1)\n\n texture = glGenTextures(1)\n glBindTexture(GL_TEXTURE_2D, texture)\n\n glPixelStorei(GL_UNPACK_ALIGNMENT, 1)\n glTexImage2D(GL_TEXTURE_2D, 0, 4, ix, iy, 0, GL_RGBA, GL_UNSIGNED_BYTE, image)\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR)\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)\n\n return texture\n\n\n# Creo il rettangolo su cui \"incollare\" la texture degli elementi del mondo\ndef creaElemento(texture, larghezza, altezza, raggio_sfera):\n glBindTexture(GL_TEXTURE_2D, texture)\n glBegin(GL_QUADS)\n\n # le istruzioni commentate sono come sono arrivato a ottenere \"l'incastramento\"\n # del rettangolo nella sfera a tentativi.\n # Poi ho accorciato la formula e resa più leggibile.\n\n # glVertex3f(-larghezza/2, 0.0, raggio_sfera - (raggio_sfera/25))\n # glVertex3f(larghezza/2, 0.0, raggio_sfera - (raggio_sfera/25))\n # glVertex3f(larghezza/2, 0.0, raggio_sfera - (raggio_sfera/25) + altezza)\n # glVertex3f(-larghezza/2, 0.0, raggio_sfera - (raggio_sfera/25) + altezza)\n\n glNormal3f(0.0, 0.0, -1.0)\n glTexCoord2f(0.0, 0.0)\n glVertex3f(-larghezza / 2, 0.0, 24 * (raggio_sfera / 25))\n glNormal3f(0.0, 0.0, -1.0)\n glTexCoord2f(1.0, 0.0)\n glVertex3f(larghezza/2, 0.0, 24 * (raggio_sfera / 25))\n glNormal3f(0.0, 0.0, -1.0)\n glTexCoord2f(1.0, 1.0)\n glVertex3f(larghezza/2, 0.0, 24 * (raggio_sfera / 25) + altezza)\n glNormal3f(0.0, 0.0, -1.0)\n glTexCoord2f(0.0, 1.0)\n glVertex3f(-larghezza/2, 0.0, 24 * (raggio_sfera / 25) + altezza)\n glEnd()\n\n\n# Inizializzazione\ndef init(Width, Height):\n global quadrica, \\\n baobab, cielo, luna, principe, terra, volpe, fuoco, rosa, dugtrio, vulcano, sole\n\n glEnable(GL_DEPTH_TEST)\n glShadeModel(GL_SMOOTH)\n glEnable(GL_NORMALIZE)\n\n glEnable(GL_BLEND)\n glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)\n glEnable(GL_ALPHA_TEST)\n glAlphaFunc(GL_GREATER, 0.0)\n\n glEnable(GL_TEXTURE_2D)\n\n glEnable(GL_LIGHTING)\n glEnable(GL_LIGHT0)\n glLightModelfv(GL_LIGHT_MODEL_AMBIENT, [0.8, 0.8, 0.8])\n glLightfv(GL_LIGHT0, GL_AMBIENT, [0.0, 0.0, 0.0, 1.0])\n glLightfv(GL_LIGHT0, GL_DIFFUSE, [1.0, 0.7, 0.15, 1.0])\n glLightfv(GL_LIGHT0, GL_SPECULAR, [1.0, 0.7, 0.15, 1.0])\n glLightModelf(GL_LIGHT_MODEL_TWO_SIDE, GL_TRUE)\n\n principe = caricaTexture(\"texture/principe.png\")\n dugtrio = caricaTexture(\"texture/dugtrio.png\")\n vulcano = caricaTexture(\"texture/volcano.png\")\n baobab = caricaTexture(\"texture/baobab.png\")\n cielo = caricaTexture(\"texture/cielo.jpg\")\n terra = caricaTexture(\"texture/terra.jpg\")\n volpe = caricaTexture(\"texture/volpe.png\")\n fuoco = caricaTexture(\"texture/fuoco.png\")\n rosa = caricaTexture(\"texture/rosa.png\")\n luna = caricaTexture(\"texture/luna.jpg\")\n sole = caricaTexture(\"texture/sole.jpg\")\n\n quadrica = gluNewQuadric()\n gluQuadricNormals(quadrica, GLU_SMOOTH)\n gluQuadricTexture(quadrica, GL_TRUE)\n\n glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE)\n\n glMatrixMode(GL_PROJECTION)\n glLoadIdentity()\n gluPerspective(45.0, float(Width) / float(Height), limite_min, limite_max)\n\n\n# Ridimensionamento\ndef resizeScene(w, h):\n if h == 0:\n h = 1\n\n glViewport(0, 0, w, h)\n glMatrixMode(GL_PROJECTION)\n glLoadIdentity()\n gluPerspective(45.0, float(w) / float(h), limite_min, limite_max)\n glMatrixMode(GL_MODELVIEW)\n\n\n# Creo la scena\ndef drawScene():\n global rot_asse, rot_orbita, texture, quadrica, \\\n baobab, cielo, luna, principe, terra, volpe, fuoco, rosa, dugtrio, vulcano, sole, \\\n raggio_terra, raggio_luna, limite_max, limite_min, \\\n angolo_sugiu, angolo_sxdx\n\n glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)\n glMatrixMode(GL_MODELVIEW)\n glEnable(GL_TEXTURE_2D)\n glEnable(GL_LIGHTING)\n\n # Sky Dome\n glPushMatrix()\n # tolgo la proprietà di diffusione (altrimenti la fonte di luce crea problemi)\n glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, [0.0, 0.0, 0.0, 1.0])\n # assegno una luce ambientale, altrimenti è troppo scuro\n glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, [0.6, 0.6, 0.6, 1.0])\n glTranslatef(0.0, 0.0, -30.0)\n glRotatef(90, 1.0, 1.0, 0.0)\n glBindTexture(GL_TEXTURE_2D, cielo)\n gluSphere(quadrica, (limite_max/2), 32, 32)\n # restituisco la proprietà di diffusione\n glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, [0.8, 0.8, 0.8, 1.0])\n glPopMatrix()\n\n glLoadIdentity()\n\n # Telecamera\n gluLookAt(camera[0], camera[1], camera[2],\n camera[0] + sin(radians(angolo_sxdx)) * cos(radians(angolo_sugiu)),\n camera[1] + sin(radians(angolo_sugiu)),\n camera[2] + cos(radians(angolo_sxdx)) * cos(radians(angolo_sugiu)),\n 0.0, 1.0, 0.0)\n\n glPushMatrix()\n glRotate(90, 0.0, 1.0, 0.0)\n glRotate(-90, 1.0, 0.0, 0.0)\n\n # Sole luminoso\n glPushMatrix()\n glTranslatef(100.0, 450.0, 150.0)\n glRotatef(rot_asse/5, 0.0, 0.0, 1.0)\n glLightfv(GL_LIGHT0, GL_POSITION, [0.0, 0.0, 0.0, 1.0])\n glMaterialfv(GL_FRONT, GL_EMISSION, [1.0, 0.7, 0.15, 1.0])\n glBindTexture(GL_TEXTURE_2D, sole)\n gluSphere(quadrica, 50, 32, 32)\n glMaterialfv(GL_FRONT, GL_EMISSION, [0.0, 0.0, 0.0, 1.0])\n glPopMatrix()\n\n # Asteroide\n glPushMatrix()\n glRotatef(rot_asse, 1.0, -1.0, 0.0)\n glBindTexture(GL_TEXTURE_2D, terra)\n gluSphere(quadrica, raggio_terra, 32, 32)\n\n # Elementi sull'asteroide\n glPushMatrix()\n glRotatef(15, 0.0, 1.0, 0.0)\n glRotatef(65, -1.0, 0.0, 0.0)\n creaElemento(principe, 1.0, 2.0, raggio_terra)\n glPopMatrix()\n\n glPushMatrix()\n glRotatef(65, -1.0, 0.0, 0.0)\n creaElemento(volpe, 0.8, 0.8, raggio_terra)\n glPopMatrix()\n\n glPushMatrix()\n glRotatef(45, 1.0, 0.0, 0.0)\n for r in range(0, 180, 30):\n glPushMatrix()\n glRotatef(r,0.0, 0.0, 1.0)\n creaElemento(baobab, 3.5, 4.0, raggio_terra)\n glPopMatrix()\n glPopMatrix()\n\n glPushMatrix()\n glRotatef(200, 1.0, 0.0, 0.0)\n for r in range(0, 180, 30):\n glPushMatrix()\n glRotatef(r, 0.0, 0.0, 1.0)\n creaElemento(vulcano, 2.0, 0.8, raggio_terra - 0.05)\n glPopMatrix()\n glPopMatrix()\n\n glPushMatrix()\n glRotatef(87, 1.0, 0.0, 0.0)\n glRotatef(78, 0.0, 1.0, 0.0)\n for r in range(0, 180, 90):\n glPushMatrix()\n glRotatef(r, 0.0, 0.0, 1.0)\n creaElemento(fuoco, 1.3, 0.9, raggio_terra)\n glPopMatrix()\n glPopMatrix()\n\n glPushMatrix()\n glRotatef(55, 1.0, 0.0, 0.0)\n glRotatef(95, 0.0, -1.0, 0.0)\n creaElemento(rosa, 0.8, 0.8, raggio_terra - 0.05)\n glPopMatrix()\n\n glPopMatrix()\n\n # Orbita del satellite intorno all'asteroide\n glPushMatrix()\n glRotatef(rot_orbita, 1.0, 1.0, 0.0)\n\n # Satellite\n glPushMatrix()\n glTranslatef(0.0, 0.0, -9.0)\n glRotatef(rot_asse, 1.0, -1.0, 0.0)\n glBindTexture(GL_TEXTURE_2D, luna)\n gluSphere(quadrica, raggio_luna, 50, 50)\n\n # Divertente elemento sul satellite\n glPushMatrix()\n glRotatef(65, -1.0, 0.0, 0.0)\n creaElemento(dugtrio, 0.4, 0.4, raggio_luna-0.05)\n glPopMatrix()\n\n glPopMatrix()\n\n glPopMatrix()\n\n glPopMatrix()\n\n glDisable(GL_TEXTURE_2D)\n\n rot_asse = rot_asse + 0.1\n rot_orbita = rot_orbita + 0.05\n\n glutSwapBuffers()\n\n\n# Realizzato in autonomia, copiando dall'esercizio della lezione.\n# Va bene finchè non giro la testa\n# def keyboard(key, x, y):\n# global camera\n#\n# if key.decode() == 'q':\n# sys.exit()\n# if key.decode() == 'w':\n# camera[2] += 1.0\n# glutPostRedisplay()\n# return\n# if key.decode() == 'a':\n# camera[0] += 1.0\n# glutPostRedisplay()\n# return\n# if key.decode() == 's':\n# camera[2] -= 1.0\n# glutPostRedisplay()\n# return\n# if key.decode() == 'd':\n# camera[0] -= 1.0\n# glutPostRedisplay()\n# return\n\n\ndef keyboard(key, x, y):\n global camera, rot_asse, rot_orbita\n\n # Metodo trovato su un forum e modificato a mia necessità per integrarlo al metodo visto a lezione\n # Nei commenti cerco di capire come e perchè funziona\n\n x_matrix = glGetFloat(GL_MODELVIEW_MATRIX)[0] # = [1,0,0]\n y_matrix = glGetFloat(GL_MODELVIEW_MATRIX)[1] # = [0,1,0]\n z_matrix = glGetFloat(GL_MODELVIEW_MATRIX)[2] # = [0,0,1]\n\n if key.decode() == 'q':\n sys.exit()\n # la seguente è una piccola istruzione inutile, ma che ho trovato divertente e piacevole da aggiungere\n if key.decode() == 't':\n rot_asse += 50.0\n rot_orbita += 50.0\n glutPostRedisplay()\n if key.decode() == 'w':\n camera[0] -= x_matrix[2] * 1.0 # \"La videocamera\" nella direzione x (i.e. verso destra)\n camera[1] -= y_matrix[2] * 1.0 # \"La videocamera\" nella direzione y (i.e. verso l'alto)\n camera[2] -= z_matrix[2] * 1.0 # \"La videocamera\" nella direzione z (i.e. verso me)\n # print(x_matrix[2] * 1.0)\n # print(y_matrix[2] * 1.0)\n # print(z_matrix[2] * 1.0)\n glutPostRedisplay()\n return\n # Se non muovo \"la testa\", i print restituiscono\n # 0.0\n # 0.0\n # -1.0\n # In effetti sto osservando lungo la direzione (0.0, 0.0, -1.0), i.e. perpendicolare \"nello schermo\"\n # Se muovo \"la testa\" a destra, i print restituiscono\n # 0.01\n # 0.0\n # -0.99\n # Avendo guardato a destra, è comparsa una componente positiva lungo l'asse x\n # In sostanza questo metodo compensa per la rotazione e fa in modo che\n # 'w' mi faccia sempre muovere \"perpendicolarmente allo schermo\"\n # Quello che fa è sottrarre rispetto a tutte le componenti lungo x,y,z in modo da \"andare dritto\"\n\n # Cambiando il fattore di moltiplicazione (nel mio caso 1.0) cambia la quantità/velocità di spostamento\n\n # Il concetto è lo stesso per le altre direzioni\n\n if key.decode() == 'a':\n camera[0] -= x_matrix[0] * 1.0\n camera[1] -= y_matrix[0] * 1.0\n camera[2] -= z_matrix[0] * 1.0\n glutPostRedisplay()\n return\n if key.decode() == 's':\n camera[0] += x_matrix[2] * 1.0\n camera[1] += y_matrix[2] * 1.0\n camera[2] += z_matrix[2] * 1.0\n glutPostRedisplay()\n return\n if key.decode() == 'd':\n camera[0] += x_matrix[0] * 1.0\n camera[1] += y_matrix[0] * 1.0\n camera[2] += z_matrix[0] * 1.0\n glutPostRedisplay()\n return\n\n\ndef specialKeyboard(key, x, y):\n global angolo_sugiu, angolo_sxdx\n\n # Continuazione del metodo precedente trovato in rete.\n # Cerco di capire il motivo dei min, max e +-89\n # Il '% 360' è facile intuire sia legato all'aritmetica modulare\n # --> dopotutto 360 gradi equivale a 0 gradi e così via\n\n if key == GLUT_KEY_UP:\n massimo = max(angolo_sugiu + 1.0, -89)\n angolo_sugiu = min(massimo, 89)\n glutPostRedisplay()\n return\n\n # Prima di tutto trova il massimo tra il valore dell'angolo+1 e -89\n # se l'angolo è >= -90 --> ottengo l'angolo+1\n # se l'angolo è <= -91 --> ottengo -89\n # Dopodichè trova il minimo tra quello ottenuto prima e 89\n # se l'angolo era >= -90\n # se -90 <= angolo <= 88 --> tengo l'angolo+1\n # se angolo > 88 --> ottengo 89\n # se l'angolo era <= -91 --> ottengo -89\n\n # Ricapitolando:\n # se angolo <= -91 --> -89\n # se -90 <= angolo <= 88 --> angolo\n # se angolo >= 89 --> 89\n # Ovvero:\n # se è meno di -90 gradi -> -90 gradi\n # se è tra -90 e 90 -> angolo\n # se è più di 90 gradi -> 90 gradi\n\n # Sostanzialmente impedisce di \"spezzarsi il collo\".\n # Limita la visuale su e giù tra il guardare dritto sopra di sè e \"guardarsi i piedi\"\n\n # Stesso concetto per la frecia in giù\n\n if key == GLUT_KEY_LEFT:\n angolo_sxdx = (angolo_sxdx + 1.0) % 360\n return\n\n # Semplicemente, una volta che ho fatto un giro completo, riparto da 0 gradi.\n\n # Stessa cosa per la freccia a destra\n\n if key == GLUT_KEY_DOWN:\n angolo_sugiu = min(max(angolo_sugiu - 1.0, -89), 89)\n return\n if key == GLUT_KEY_RIGHT:\n angolo_sxdx = (angolo_sxdx - 1.0) % 360\n return\n\n\ndef main():\n glutInit()\n\n messaggio = \"\\nBenvenuto nel mondo del Piccolo Principe!\\n\" \\\n \"Usare i tasti WASD per muovere la telecamera,\\n\" \\\n \"le freccette per girare la testa,\\n\" \\\n \"e tenere premuto il tasto T per avviare il turbo!\"\n\n print(messaggio)\n\n glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_DEPTH | GLUT_ALPHA)\n glutInitWindowSize(1920, 1080)\n glutInitWindowPosition(100, 100)\n glutCreateWindow(\"Luca Lavazza - Piccolo Principe\")\n\n glutDisplayFunc(drawScene)\n glutIdleFunc(drawScene)\n glutReshapeFunc(resizeScene)\n glutKeyboardFunc(keyboard)\n glutSpecialFunc(specialKeyboard)\n init(1920, 1080)\n\n glutMainLoop()\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"lavazzaPiccoloPrincipe.py","file_name":"lavazzaPiccoloPrincipe.py","file_ext":"py","file_size_in_byte":13744,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"487188530","text":"# This code is part of Qiskit.\n#\n# (C) Copyright IBM 2017, 2021.\n#\n# This code is licensed under the Apache License, Version 2.0. You may\n# obtain a copy of this license in the LICENSE.txt file in the root directory\n# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.\n#\n# Any modifications or derivative works of this code must retain this\n# copyright notice, and modified files need to carry a notice indicating\n# that they have been altered from the originals.\n\n\"\"\"Linear Function.\"\"\"\n\nfrom __future__ import annotations\nimport numpy as np\nfrom qiskit.circuit import QuantumCircuit, Gate\nfrom qiskit.circuit.exceptions import CircuitError\nfrom qiskit.synthesis.linear import check_invertible_binary_matrix\n\n\nclass LinearFunction(Gate):\n r\"\"\"A linear reversible circuit on n qubits.\n\n Internally, a linear function acting on n qubits is represented\n as a n x n matrix of 0s and 1s in numpy array format.\n\n A linear function can be synthesized into CX and SWAP gates using the Patel–Markov–Hayes\n algorithm, as implemented in :func:`~qiskit.transpiler.synthesis.cnot_synth`\n based on reference [1].\n\n For efficiency, the internal n x n matrix is stored in the format expected\n by cnot_synth, which is the big-endian (and not the little-endian) bit-ordering convention.\n\n **Example:** the circuit\n\n .. parsed-literal::\n\n q_0: ──■──\n ┌─┴─┐\n q_1: ┤ X ├\n └───┘\n q_2: ─────\n\n is represented by a 3x3 linear matrix\n\n .. math::\n\n \\begin{pmatrix}\n 1 & 0 & 0 \\\\\n 1 & 1 & 0 \\\\\n 0 & 0 & 1\n \\end{pmatrix}\n\n\n **References:**\n\n [1] Ketan N. Patel, Igor L. Markov, and John P. Hayes,\n Optimal synthesis of linear reversible circuits,\n Quantum Inf. Comput. 8(3) (2008).\n `Online at umich.edu. `_\n \"\"\"\n\n def __init__(\n self,\n linear: list[list[int]] | np.ndarray | QuantumCircuit,\n validate_input: bool | None = False,\n ) -> None:\n \"\"\"Create a new linear function.\n\n Args:\n linear (list[list] or ndarray[bool] or QuantumCircuit):\n either an n x n matrix, describing the linear function,\n or a quantum circuit composed of linear gates only\n (currently supported gates are CX and SWAP).\n\n validate_input: if True, performs more expensive input validation checks,\n such as checking that a given n x n matrix is invertible.\n\n Raises:\n CircuitError: if the input is invalid:\n either a matrix is non {square, invertible},\n or a quantum circuit contains non-linear gates.\n\n \"\"\"\n if not isinstance(linear, (list, np.ndarray, QuantumCircuit)):\n raise CircuitError(\n \"A linear function must be represented either by a list, \"\n \"a numpy array, or a quantum circuit with linear gates.\"\n )\n\n if isinstance(linear, QuantumCircuit):\n # The following function will raise a CircuitError if there are nonlinear gates.\n original_circuit = linear\n linear = _linear_quantum_circuit_to_mat(linear)\n\n else:\n original_circuit = None\n\n # Normalize to numpy array (coercing entries to 0s and 1s)\n try:\n linear = np.array(linear, dtype=bool, copy=True)\n except ValueError:\n raise CircuitError(\n \"A linear function must be represented by a square matrix.\"\n ) from None\n\n # Check that the matrix is square\n if len(linear.shape) != 2 or linear.shape[0] != linear.shape[1]:\n raise CircuitError(\"A linear function must be represented by a square matrix.\")\n\n # Optionally, check that the matrix is invertible\n if validate_input:\n if not check_invertible_binary_matrix(linear):\n raise CircuitError(\n \"A linear function must be represented by an invertible matrix.\"\n )\n\n super().__init__(\n name=\"linear_function\", num_qubits=len(linear), params=[linear, original_circuit]\n )\n\n def validate_parameter(self, parameter):\n \"\"\"Parameter validation\"\"\"\n return parameter\n\n def _define(self):\n \"\"\"Populates self.definition with a decomposition of this gate.\"\"\"\n self.definition = self.synthesize()\n\n def synthesize(self):\n \"\"\"Synthesizes the linear function into a quantum circuit.\n\n Returns:\n QuantumCircuit: A circuit implementing the evolution.\n \"\"\"\n from qiskit.synthesis.linear import synth_cnot_count_full_pmh\n\n return synth_cnot_count_full_pmh(self.linear)\n\n @property\n def linear(self):\n \"\"\"Returns the n x n matrix representing this linear function\"\"\"\n return self.params[0]\n\n @property\n def original_circuit(self):\n \"\"\"Returns the original circuit used to construct this linear function\n (including None, when the linear function is not constructed from a circuit).\n \"\"\"\n return self.params[1]\n\n def is_permutation(self) -> bool:\n \"\"\"Returns whether this linear function is a permutation,\n that is whether every row and every column of the n x n matrix\n has exactly one 1.\n \"\"\"\n linear = self.linear\n perm = np.all(np.sum(linear, axis=0) == 1) and np.all(np.sum(linear, axis=1) == 1)\n return perm\n\n def permutation_pattern(self):\n \"\"\"This method first checks if a linear function is a permutation and raises a\n `qiskit.circuit.exceptions.CircuitError` if not. In the case that this linear function\n is a permutation, returns the permutation pattern.\n \"\"\"\n if not self.is_permutation():\n raise CircuitError(\"The linear function is not a permutation\")\n\n linear = self.linear\n locs = np.where(linear == 1)\n return locs[1]\n\n\ndef _linear_quantum_circuit_to_mat(qc: QuantumCircuit):\n \"\"\"This creates a n x n matrix corresponding to the given linear quantum circuit.\"\"\"\n nq = qc.num_qubits\n mat = np.eye(nq, nq, dtype=bool)\n\n for instruction in qc.data:\n if instruction.operation.name == \"cx\":\n cb = qc.find_bit(instruction.qubits[0]).index\n tb = qc.find_bit(instruction.qubits[1]).index\n mat[tb, :] = (mat[tb, :]) ^ (mat[cb, :])\n elif instruction.operation.name == \"swap\":\n cb = qc.find_bit(instruction.qubits[0]).index\n tb = qc.find_bit(instruction.qubits[1]).index\n mat[[cb, tb]] = mat[[tb, cb]]\n else:\n raise CircuitError(\"A linear quantum circuit can include only CX and SWAP gates.\")\n\n return mat\n","sub_path":"qiskit/circuit/library/generalized_gates/linear_function.py","file_name":"linear_function.py","file_ext":"py","file_size_in_byte":6966,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"590195736","text":"import sys\n\nsteps = []\ndeps = {}\nwith open('input') as f:\n for line in f:\n dependency = line[5:6]\n step = line[36:37]\n # Collect all steps in puzzle\n if step not in steps:\n steps.append(step)\n deps[step] = []\n if dependency not in steps:\n steps.append(dependency)\n deps[dependency] = []\n if step not in deps:\n deps[step] = [dependency]\n else:\n deps[step].append(dependency)\n\ncompleted = []\n\nwhile True:\n # Find possible steps that can be solves\n possible = []\n for step in steps:\n if len(deps[step]) == 0:\n possible.append(step)\n solved = sorted(possible)[0]\n for key, value in deps.items():\n if solved in value:\n value.remove(solved)\n\n steps.remove(solved)\n deps.pop(solved)\n completed.append(solved)\n if len(steps) == 0:\n print(''.join(completed))\n sys.exit(0)\n","sub_path":"7/1.py","file_name":"1.py","file_ext":"py","file_size_in_byte":958,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"562224187","text":"from asyncio import AbstractEventLoop, get_event_loop\nfrom typing import Optional, Dict, List, Any\nfrom datetime import datetime, timedelta\nimport dateparser\nimport logging\nfrom royalnet.utils import ytdldateformat, asyncify\n\ntry:\n from youtube_dl import YoutubeDL\nexcept ImportError:\n YoutubeDL = None\n\n\nlog = logging.getLogger(__name__)\n\n\nclass YtdlInfo:\n \"\"\"A wrapper around `youtube_dl `_ extracted info.\"\"\"\n\n _default_ytdl_args = {\n \"quiet\": True, # Do not print messages to stdout.\n \"noplaylist\": True, # Download single video instead of a playlist if in doubt.\n \"no_warnings\": True, # Do not print out anything for warnings.\n \"outtmpl\": \"./downloads/%(epoch)s-%(title)s-%(id)s.%(ext)s\", # Use the default outtmpl.\n \"ignoreerrors\": True # Ignore unavailable videos\n }\n\n def __init__(self, info: Dict[str, Any]):\n \"\"\"Create a :class:`YtdlInfo` from the dict returned by the :func:`YoutubeDL.extract_info` function.\n\n Warning:\n Does not download the info, to do that use :func:`.retrieve_for_url`.\"\"\"\n self.id: Optional[str] = info.get(\"id\")\n self.uploader: Optional[str] = info.get(\"uploader\")\n self.uploader_id: Optional[str] = info.get(\"uploader_id\")\n self.uploader_url: Optional[str] = info.get(\"uploader_url\")\n self.channel_id: Optional[str] = info.get(\"channel_id\")\n self.channel_url: Optional[str] = info.get(\"channel_url\")\n self.upload_date: Optional[datetime] = dateparser.parse(ytdldateformat(info.get(\"upload_date\")))\n self.license: Optional[str] = info.get(\"license\")\n self.creator: Optional[...] = info.get(\"creator\")\n self.title: Optional[str] = info.get(\"title\")\n self.alt_title: Optional[...] = info.get(\"alt_title\")\n self.thumbnail: Optional[str] = info.get(\"thumbnail\")\n self.description: Optional[str] = info.get(\"description\")\n self.categories: Optional[List[str]] = info.get(\"categories\")\n self.tags: Optional[List[str]] = info.get(\"tags\")\n self.subtitles: Optional[Dict[str, List[Dict[str, str]]]] = info.get(\"subtitles\")\n self.automatic_captions: Optional[dict] = info.get(\"automatic_captions\")\n self.duration: Optional[timedelta] = timedelta(seconds=info.get(\"duration\", 0))\n self.age_limit: Optional[int] = info.get(\"age_limit\")\n self.annotations: Optional[...] = info.get(\"annotations\")\n self.chapters: Optional[...] = info.get(\"chapters\")\n self.webpage_url: Optional[str] = info.get(\"webpage_url\")\n self.view_count: Optional[int] = info.get(\"view_count\")\n self.like_count: Optional[int] = info.get(\"like_count\")\n self.dislike_count: Optional[int] = info.get(\"dislike_count\")\n self.average_rating: Optional[...] = info.get(\"average_rating\")\n self.formats: Optional[list] = info.get(\"formats\")\n self.is_live: Optional[bool] = info.get(\"is_live\")\n self.start_time: Optional[float] = info.get(\"start_time\")\n self.end_time: Optional[float] = info.get(\"end_time\")\n self.series: Optional[str] = info.get(\"series\")\n self.season_number: Optional[int] = info.get(\"season_number\")\n self.episode_number: Optional[int] = info.get(\"episode_number\")\n self.track: Optional[...] = info.get(\"track\")\n self.artist: Optional[...] = info.get(\"artist\")\n self.extractor: Optional[str] = info.get(\"extractor\")\n self.webpage_url_basename: Optional[str] = info.get(\"webpage_url_basename\")\n self.extractor_key: Optional[str] = info.get(\"extractor_key\")\n self.playlist: Optional[str] = info.get(\"playlist\")\n self.playlist_index: Optional[int] = info.get(\"playlist_index\")\n self.thumbnails: Optional[List[Dict[str, str]]] = info.get(\"thumbnails\")\n self.display_id: Optional[str] = info.get(\"display_id\")\n self.requested_subtitles: Optional[...] = info.get(\"requested_subtitles\")\n self.requested_formats: Optional[tuple] = info.get(\"requested_formats\")\n self.format: Optional[str] = info.get(\"format\")\n self.format_id: Optional[str] = info.get(\"format_id\")\n self.width: Optional[int] = info.get(\"width\")\n self.height: Optional[int] = info.get(\"height\")\n self.resolution: Optional[...] = info.get(\"resolution\")\n self.fps: Optional[int] = info.get(\"fps\")\n self.vcodec: Optional[str] = info.get(\"vcodec\")\n self.vbr: Optional[int] = info.get(\"vbr\")\n self.stretched_ratio: Optional[...] = info.get(\"stretched_ratio\")\n self.acodec: Optional[str] = info.get(\"acodec\")\n self.abr: Optional[int] = info.get(\"abr\")\n self.ext: Optional[str] = info.get(\"ext\")\n\n @classmethod\n async def from_url(cls, url, loop: Optional[AbstractEventLoop] = None, **ytdl_args) -> List[\"YtdlInfo\"]:\n \"\"\"Fetch the info for an url through :class:`YoutubeDL`.\n\n Returns:\n A :class:`list` containing the infos for the requested videos.\"\"\"\n if YoutubeDL is None:\n raise ImportError(\"'bard' extra is not installed\")\n\n if loop is None:\n loop: AbstractEventLoop = get_event_loop()\n # So many redundant options!\n log.debug(f\"Fetching info: {url}\")\n with YoutubeDL({**cls._default_ytdl_args, **ytdl_args}) as ytdl:\n first_info = await asyncify(ytdl.extract_info, loop=loop, url=url, download=False)\n # No video was found\n if first_info is None:\n return []\n # If it is a playlist, create multiple videos!\n if \"entries\" in first_info:\n if len(first_info[\"entries\"]) == 0:\n return []\n if first_info[\"entries\"][0] is None:\n return []\n log.debug(f\"Found a playlist: {url}\")\n second_info_list = []\n for second_info in first_info[\"entries\"]:\n if second_info is None:\n continue\n second_info_list.append(YtdlInfo(second_info))\n return second_info_list\n log.debug(f\"Found a single video: {url}\")\n return [YtdlInfo(first_info)]\n\n def __repr__(self):\n if self.title:\n return f\"\"\n if self.webpage_url:\n return f\"\"\n return f\"\"\n\n def __str__(self):\n if self.title:\n return self.title\n if self.webpage_url:\n return self.webpage_url\n return self.id\n","sub_path":"royalnet/bard/ytdlinfo.py","file_name":"ytdlinfo.py","file_ext":"py","file_size_in_byte":6596,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"212527934","text":"from mayaPY.core import *\n\ndef getTransforms(\n\t\titem=\"\", valType=\"\", \n\t\tpRound=5, coords=[\"X\", \"Y\", \"Z\"]\n\t\t):\n\t\t\n\tvals=[round(mc.getAttr(\"%s.%s%s\" % (item, valType, c)), pRound) for c in coords]\n\n\treturn(vals)\n\ndef setTransforms(item=\"\", valsToSet=[0, 0, 0], \n\tvalsType=\"\", coords=[\"X\", \"Y\", \"Z\"]):\n\t\n\t[mc.setAttr(\"%s.%s%s\" % (item, valsType, coords[i]), valsToSet[i]) for i in range(len(valsToSet))]\n\t\n\tpass\n\ndef mlAimConstraint(objToAim=\"\", objConstr=\"\", \n\taimV=(1, 0, 0), upV=(0, 1, 0), wuType=\"vector\", \n\twuObj=\"\", wuV=(0, 1, 0), pSkipList=\"none\", pInfo=False):\n\t\n\tif pInfo:\n\t\tprint (\"\"\"ARGS = objToAim=\"\", objConstr=\"\",aimV=(1, 0, 0), upV=(0, 1, 0), wuType=\"vector\", \n\t\t\twuObj=\"\", wuV=(0, 1, 0), pSkipList=\"none\" ; wuType = (vector(default), objectrotation, object)\"\"\")\n\t\t\n\t\treturn\n\t\n\tif wuType == \"objectrotation\":\n\t\tmc.aimConstraint(str(objToAim), str(objConstr), offset=(0, 0, 0), aim=aimV, \\\n\t\tupVector=upV, wut=wuType, wuo=wuObj, wu=wuV, name=\"tempAimConstr\", skip=pSkipList)\n\t\tmc.delete(\"tempAimConstr\")\n\telif wuType == \"object\":\n\t\tmc.aimConstraint(str(objToAim), str(objConstr), offset=(0, 0, 0), aim=aimV, \\\n\t\tupVector=upV, wut=wuType, wuo=wuObj, name=\"tempAimConstr\", skip=pSkipList)\n\t\tmc.delete(\"tempAimConstr\")\n\telse:\n\t\tmc.aimConstraint(str(objToAim), str(objConstr), offset=(0, 0, 0), aim=aimV, \\\n\t\tupVector=upV, wut=wuType, wu=wuV, name=\"tempAimConstr\", skip=pSkipList)\n\t\tmc.delete(\"tempAimConstr\")\n\t\n\tpass\n\ndef resetOrientJoint(\n\tpName=\"\", pOff=[0, 0, 0], pInfo=False):\n\t\n\tif pInfo:\n\t\tprint (\"\"\"ARGS = pName=\"\"(name of the joint to reset orient), pOff=[0, 0, 0] (set arbitrary offset)\"\"\")\n\t\t\n\t\treturn\n\t\n\torientJointName=\"orientJointTemp\"\n\tmc.select(pName)\n\tmc.duplicate(name=orientJointName, po=True)\n\tmc.orientConstraint(orientJointName, pName, n=\"tempOrientConstraint\")\n\tsetTransforms(item=pName, valsToSet=pOff, valsType=\"jointOrient\")\n\tmc.delete([\"tempOrientConstraint\", orientJointName])\n\t\n\n","sub_path":"mayaPY/core/utils/mayaUtils.py","file_name":"mayaUtils.py","file_ext":"py","file_size_in_byte":1915,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"153237342","text":"#Authors: Khashayar Shamsolketabi & Amir Hossein Alikhah Mishamandani\n#Date & Time: 27/March/2020\n#Description: First Library for Game Theory\n#-----------------------------------------------------------------------------\n\n#Required Libraries\nfrom prettytable import PrettyTable\nimport numpy as np\nfrom itertools import chain\n\n#Global Variables\nTARGET_MIN = 0;\nTARGET_MAX = 1;\n\n#Linear transformation \\unit tested\ndef linearTransformation(sourceMin, sourceMax, targetMin, targetMax, inputNumber):\n if (sourceMin == sourceMax):\n return (targetMin + targetMax)/2;\n else:\n return (targetMin + ((inputNumber - sourceMin)/(sourceMax - sourceMin))*(targetMax - targetMin));\n\n#Linear normalization \\unit tested\ndef linearNormalization(sourceMin, sourceMax, inputNumber):\n return linearTransformation(sourceMin, sourceMax, TARGET_MIN, TARGET_MAX, inputNumber);\n\n#Linear normalization of vectors \\unit tested\ndef linearNormalizationOfVector(sourceMin, sourceMax, inputVector):\n return list(map(lambda x: linearNormalization(sourceMin, sourceMax, x), inputVector));\n\n#Linear normalization of matrices \\unit tested\ndef linearNormalizationOfMatrix(sourceMin, sourceMax, inputMatrix):\n return list(map(lambda X: linearNormalizationOfVector(sourceMin, sourceMax, X), inputMatrix));\n\n#Linear normalization of pay off matrices \\unit tested\ndef linearNormalizationOfPayOff(firstPlayerPayOffs, secondPlayerPayOffs):\n sourceMin = np.min([np.min(firstPlayerPayOffs), np.min(secondPlayerPayOffs)]);\n sourceMax = np.max([np.max(firstPlayerPayOffs), np.max(secondPlayerPayOffs)]);\n return [linearNormalizationOfMatrix(sourceMin, sourceMax, firstPlayerPayOffs), \n linearNormalizationOfMatrix(sourceMin, sourceMax, secondPlayerPayOffs)]; \n\n#Weighting average of a vector \\unit tested\ndef vectorWeightException(vector, weights, probabilities):\n return sum(list(map(lambda x: x[1]*weights[x[0]]*probabilities[x[0]], enumerate(vector))));\n\n#Weighting average of a matrix \\unit tested\ndef matrixWeightException(matrix, weights, probabilities):\n nonNormalizedReuslt = list(map(lambda X: vectorWeightException(X,weights, probabilities), matrix));\n totalSum = sum(nonNormalizedReuslt);\n return [x/totalSum for x in nonNormalizedReuslt];\n\n#Calculation of decision distribution of first player \\unit tested\ndef firstPlayerDecisionWithMixStrategyIteration(firstPlayerPayOffs, secondPlayerDecision, secondPlayerMixStrategyDistribution):\n return matrixWeightException(firstPlayerPayOffs, secondPlayerDecision, secondPlayerMixStrategyDistribution);\n\n#Calculation of decision distribution of second player \\unit tested\ndef secondPlayerDecisionWithMixStrategyIteration(secondPlayerPayOffs, firstPlayerDecision, firstPlayerMixStrategyDistribution):\n return matrixWeightException(np.array(secondPlayerPayOffs).T.tolist(), firstPlayerDecision, firstPlayerMixStrategyDistribution);\n\n#Iteration over pay offs with mix strategy \\unit tested\ndef playersDecisionWithMixStrategyIteration(\n firstPlayerPayOffs, \n secondPlayerPayOffs, \n firstPlayerInitialDecision, \n secondPlayerInitialDecision, \n firstPlayerMixStrategyDistribution, \n secondPlayerMixStrategyDistribution):\n return [firstPlayerDecisionWithMixStrategyIteration(firstPlayerPayOffs, secondPlayerInitialDecision, secondPlayerMixStrategyDistribution),\n secondPlayerDecisionWithMixStrategyIteration(secondPlayerPayOffs, firstPlayerInitialDecision, firstPlayerMixStrategyDistribution)];\n\n#Iteration over pay offs without mix strategy \\unit tested\ndef playersDecisionWithoutMixStrategyIteration(\n firstPlayerPayOffs, \n secondPlayerPayOffs, \n firstPlayerInitialDecision, \n secondPlayerInitialDecision):\n m = len(firstPlayerPayOffs);\n n = len(secondPlayerPayOffs[0]);\n return [firstPlayerDecisionWithMixStrategyIteration(firstPlayerPayOffs, secondPlayerInitialDecision, np.ones(n)/n),\n secondPlayerDecisionWithMixStrategyIteration(secondPlayerPayOffs, firstPlayerInitialDecision, np.ones(m)/m)];\n\n#Multiple iteration over pay offs with multiple times using mix strategy\ndef playersDecisionWithMultiTimesMixStrategyIterations(\n firstPlayerPayOffs, \n secondPlayerPayOffs, \n firstPlayerMixStrategyDistribution, \n secondPlayerMixStrategyDistribution,\n numberOfIterations):\n m = len(firstPlayerPayOffs);\n n = len(secondPlayerPayOffs[0]);\n firstPlayerInitialDecision = np.ones(m)/m;\n secondPlayerInitialDecision = np.ones(n)/n;\n printPlayersIterationDecision(0, firstPlayerInitialDecision, secondPlayerInitialDecision);\n if (numberOfIterations > 0):\n for i in range(0, numberOfIterations):\n [firstPlayerInitialDecision, secondPlayerInitialDecision] = playersDecisionWithMixStrategyIteration(\n firstPlayerPayOffs, \n secondPlayerPayOffs, \n firstPlayerInitialDecision, \n secondPlayerInitialDecision, \n firstPlayerMixStrategyDistribution, \n secondPlayerMixStrategyDistribution);\n printPlayersIterationDecision(i + 1, firstPlayerInitialDecision, secondPlayerInitialDecision);\n return [firstPlayerInitialDecision, secondPlayerInitialDecision];\n \n#Multiple iteration over pay offs with one time using mix strategy\ndef playersDecisionWithOneTimeMixStrategyIterations(\n firstPlayerPayOffs, \n secondPlayerPayOffs, \n firstPlayerMixStrategyDistribution, \n secondPlayerMixStrategyDistribution,\n numberOfIterations):\n m = len(firstPlayerPayOffs);\n n = len(secondPlayerPayOffs[0]);\n firstPlayerInitialDecision = np.ones(m)/m;\n secondPlayerInitialDecision = np.ones(n)/n;\n printPlayersIterationDecision(0, firstPlayerInitialDecision, secondPlayerInitialDecision);\n if (numberOfIterations > 0):\n for i in range(0, numberOfIterations):\n if (i == 0):\n [firstPlayerInitialDecision, secondPlayerInitialDecision] = playersDecisionWithMixStrategyIteration(\n firstPlayerPayOffs, \n secondPlayerPayOffs, \n firstPlayerInitialDecision, \n secondPlayerInitialDecision, \n firstPlayerMixStrategyDistribution, \n secondPlayerMixStrategyDistribution);\n printPlayersIterationDecision(1, firstPlayerInitialDecision, secondPlayerInitialDecision);\n else:\n [firstPlayerInitialDecision, secondPlayerInitialDecision] = playersDecisionWithoutMixStrategyIteration(\n firstPlayerPayOffs, \n secondPlayerPayOffs, \n firstPlayerInitialDecision, \n secondPlayerInitialDecision);\n printPlayersIterationDecision(i + 1, firstPlayerInitialDecision, secondPlayerInitialDecision);\n return [firstPlayerInitialDecision, secondPlayerInitialDecision]; \n\n#Multiple iteration over pay offs without mix strategy\ndef playersDecisionWithoutMixStrategyIterations(\n firstPlayerPayOffs, \n secondPlayerPayOffs,\n numberOfIterations):\n m = len(firstPlayerPayOffs);\n n = len(secondPlayerPayOffs[0]);\n firstPlayerInitialDecision = np.ones(m)/m;\n secondPlayerInitialDecision = np.ones(n)/n;\n printPlayersIterationDecision(0, firstPlayerInitialDecision, secondPlayerInitialDecision);\n if (numberOfIterations > 0):\n for i in range(0, numberOfIterations):\n [firstPlayerInitialDecision, secondPlayerInitialDecision] = playersDecisionWithoutMixStrategyIteration(\n firstPlayerPayOffs, \n secondPlayerPayOffs, \n firstPlayerInitialDecision, \n secondPlayerInitialDecision);\n printPlayersIterationDecision(i + 1, firstPlayerInitialDecision, secondPlayerInitialDecision);\n return [firstPlayerInitialDecision, secondPlayerInitialDecision];\n\n#Print players decision for iteration\ndef printPlayersIterationDecision(iteration, firstPlayerInitialDecision, secondPlayerInitialDecision):\n print('Iteration', iteration, ': P1 =', firstPlayerInitialDecision, '& P2 =', secondPlayerInitialDecision);\n\n\nprint('transformation unit test: ', \n linearTransformation(-4,-1, 1, 4, -2) );\nprint('normalization unit test: ', \n linearNormalization(-4,-1, -2) );\nprint('normalization of vector unit test: ', \n linearNormalizationOfVector(-4,-1, [-2, -1]));\nprint('normalization of matrix unit test: ', \n linearNormalizationOfMatrix(-4,-1, [[-2, -3], [-1, 0]]));\nprint('normalization of pay offs unit test: ', \n linearNormalizationOfPayOff([[-2, -3], [-1, 0]], \n [[-2, -4], [-1, 0]]));\nprint('weigting exception of vectors unit test: ', \n vectorWeightException([2, 3, 1, 0],\n [.2, .3, .2, .3], \n [.2, .4, .1, .3]));\nprint('weigting exception of matrix unit test: ', \n matrixWeightException([[2, 3, 1, 0], [2, 3, 1, 0], [2, 3, 1, 0]],\n [.2, .3, .2, .3], \n [.2, .4, .1, .3]));\nprint('calculate decision for first player with mix strategy unit test: ', \n firstPlayerDecisionWithMixStrategyIteration([[2, 3, 1, 0], [2, 3, 1, 0], [2, 3, 1, 0]],\n [.2, .3, .2, .3], \n [.2, .4, .1, .3])); \nprint('calculate decision for second player with mix strategy unit test: ', \n secondPlayerDecisionWithMixStrategyIteration(\n [[2, 3, 1, 0], [2, 3, 1, 0], [2, 3, 1, 0]],\n [.3, .4, .3], \n [.3, .5, .2])); \nprint('update decision for players with mix strategy unit test: ', \n playersDecisionWithMixStrategyIteration(\n [[2, 3, 1, 0], [2, 3, 1, 0], [2, 3, 1, 0]],\n [[2, 3, 1, 0], [2, 3, 1, 0], [2, 3, 1, 0]],\n [.3, .4, .3],\n [.2, .3, .2, .3],\n [.3, .5, .2],\n [.2, .4, .1, .3]));\nprint('update decision for players without mix strategy unit test: ', \n playersDecisionWithoutMixStrategyIteration(\n [[2, 3, 1, 0], [2, 3, 1, 0], [2, 3, 1, 0]],\n [[2, 3, 1, 0], [2, 3, 1, 0], [2, 3, 1, 0]],\n [.3, .4, .3],\n [.2, .3, .2, .3]));\nprint('Iterate decision for players with multipe mix strategy unit test: ', \n playersDecisionWithMultiTimesMixStrategyIterations(\n [[2, 3, 1, 0], [2, 3, 1, 0], [2, 3, 1, 0]],\n [[2, 3, 1, 0], [2, 3, 1, 0], [2, 3, 1, 0]],\n [.3, .5, .2],\n [.2, .4, .1, .3],\n 3));\nprint('Iterate decision for players with one time mix strategy unit test: ', \n playersDecisionWithOneTimeMixStrategyIterations(\n [[2, 3, 1, 0], [2, 3, 1, 0], [2, 3, 1, 0]],\n [[2, 3, 1, 0], [2, 3, 1, 0], [2, 3, 1, 0]],\n [.3, .5, .2],\n [.2, .4, .1, .3],\n 3));\nprint('Iterate decision for players without mix strategy unit test: ', \n playersDecisionWithoutMixStrategyIterations(\n [[2, 3, 1, 0], [2, 3, 1, 0], [2, 3, 1, 0]],\n [[2, 3, 1, 0], [2, 3, 1, 0], [2, 3, 1, 0]],\n 3));\n","sub_path":"multi-layer-intelligence.py","file_name":"multi-layer-intelligence.py","file_ext":"py","file_size_in_byte":11047,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"357508903","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.4 (62061)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build/bdist.linux-i686/egg/salamoia/frontends/console.py\n# Compiled at: 2007-12-02 16:26:54\nfrom salamoia.frontends.frontend import *\nfrom optparse import OptionGroup\nimport xmlrpclib, code, readline, atexit, os\nfrom salamoia.h2o.xmlclient import Client\nfrom salamoia.frontends.config import Config\n\nclass Console(Frontend):\n __module__ = __name__\n\n def name(self):\n return 'console'\n\n def options(self, parser):\n \"\"\"Return an option group specifing the front end specific options\"\"\"\n from optparse import OptionGroup\n optionGroup = OptionGroup(parser, 'Salamoia console options')\n optionGroup.add_option('-b', '--base', type='string', dest='base', help='base url')\n optionGroup.add_option('-p', '--port', type='string', dest='port', help='port')\n optionGroup.add_option('-H', '--host', type='string', dest='host', help='host')\n return optionGroup\n\n def run(self):\n (options, args) = self.optionParser.parse_args()\n self.options = options\n self.args = args\n historyPath = os.path.expanduser('~/.salamoia-console-history')\n\n def save_history(historyPath=historyPath):\n import readline\n readline.write_history_file(historyPath)\n\n if os.path.exists(historyPath):\n readline.read_history_file(historyPath)\n atexit.register(save_history)\n cfg = Config.defaultConfig()\n username = cfg.get('general', 'username')\n password = cfg.get('general', 'password')\n port = cfg.get('general', 'port')\n if self.options.port:\n port = self.options.port\n host = 'localhost'\n if self.options.host:\n host = self.options.host\n base = 'hostello'\n if self.options.base:\n base = self.options.base\n server = Client(host, port, base=base, username=username, password=password)\n code.interact(local={'server': server, 's': server, '__server__': server}, banner='Salamoia python interactive console')\n\n\ndef start():\n Console.start()","sub_path":"pycfiles/Salamoia-1.1.6-py2.4/console.py","file_name":"console.py","file_ext":"py","file_size_in_byte":2222,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"287842145","text":"\n\n# Exercise 05-02\n''''\nstudent name:Luis\nID:201810701580033\nclass:network 182\n'''\n\n\n\nn=int(input(\"Enter the number of values to insert: \"))\nmyList=[]\n\nfor i in range(0,n):\n\n get_num=int(input(\"Enter a number to insert: \"))\n myList.append(get_num)\n\nsum =sum(myList)\naverage=sum/len(myList)\nprint('Sum is:'+str(sum))\nprint('Average is:'+str(average))\n","sub_path":"Python_OOP/Exercise/Exercise 05/201810701580033 - Luis/5.2.py","file_name":"5.2.py","file_ext":"py","file_size_in_byte":356,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"113358917","text":"#coding=utf-8\nfrom flask import session,redirect,request,render_template,Flask\n\nfrom curd import *\napp = Flask(__name__)\n\nimport os\ndef render_login_page():\n return render_template(\"home.html\")\n\ndef render_home_page(uid):\n user = get_user_from_id(uid)\n time_lines = get_time_lines()\n\n return render_template(\"index.html\",user=user,time_lines=time_lines)\n\n\n@app.route('/')\ndef index():\n if 'uid' in session:\n return render_home_page(session['uid'])\n\n return redirect('/login')\n\n@app.route('/login', methods=['GET', 'POST'])\ndef login():\n if request.method == 'GET':\n return render_login_page()\n\n elif request.method == 'POST':\n username = request.form['username']\n password = request.form['password']\n user = get_user_from_username_and_password(username, password)\n if user is not None:\n session['uid'] = user['id']\n return redirect('/')\n else:\n return redirect('/login')\n\n@app.route('/create_time_line', methods=['POST'])\ndef time_line():\n if 'uid' in session:\n uid = session['uid']\n create_time_line(uid, request.form['content'])\n return redirect('/')\n@app.route('/delete/time_line/')\ndef delete_time_line(tid):\n if 'uid' in session:\n user_delete_time_line_of_id(session['uid'], tid)\n return redirect('/')\n\n@app.route('/logout')\ndef logout():\n if 'uid' in session:\n session.pop('uid')\n return redirect('/login')\n\n\nif __name__ == '__main__':\n app.secret_key = os.urandom(24)\n app.run(debug=True)","sub_path":"flask_xss/flaskcon.py","file_name":"flaskcon.py","file_ext":"py","file_size_in_byte":1562,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"644315694","text":"#! /usr/bin/python3.7\n#\n# author: Krzysztof Czarnecki\n# email: czarnecki.krzysiek@gmail.com\n# opensource licence: GPL-3.0\n# application: GLOBSIM\n\n###\n### opt parsing\n###\n\nimport optparse, os\nimport ToolBox\n\nparser = optparse. OptionParser()\nparser.add_option(\"-f\", \"--db-file\", dest=\"dbfile\",\n metavar=\"FILE\", default=\"demo.sql\",\n help=\"saved simulator state\")\nparser.add_option(\"-p\", \"--province\", dest=\"province\",\n help=\"point nodes\")\nparser.add_option(\"-x\", \"--xnode\", dest=\"xnode\",\n action=\"store_true\", default=False,\n help=\"print xnode mode\")\nparser.add_option(\"-m\", \"--margin\", dest=\"margin\",\n help=\"margin/padding\", default=0)\nparser.add_option(\"-s\", \"--stream\", dest=\"stream\",\n help=\"stream resistance\")\nparser.add_option(\"-l\", \"--list\", dest=\"listv\",\n action=\"store_true\", default=False,\n help=\"print mode list\")\nparser.add_option(\"-t\", \"--type\", dest=\"type\", default=\"all\",\n help=\"terrain type: sea, land, all\")\nopts, args = parser.parse_args()\n\n###\n### main\n###\n\nimport BusyBoxSQL, math\ndriver = BusyBoxSQL.BusyBoxSQL(opts.dbfile)\n\nif opts.province is not None and not opts.xnode:\n ToolBox.print_output(f\"node: {opts.province}\")\n atoms = driver.get_node_atoms_as_dict(opts.province)\n ToolBox.print_output(f\"atoms: {len(atoms)}\")\n scale = driver.get_config_by_name(\"map_scale\")\n ToolBox.print_output(f\"area: {len(atoms)*scale}\")\n\n terrains = {}\n aperture = 0.0\n for atom in atoms.values():\n if atom[0] not in terrains.keys():\n terr = driver.get_terrain_as_dict(atom[0])\n terrains[atom[0]] = terr\n aperture += terrains[atom[0]][\"aperture\"]\n ToolBox.print_output(f\"aperture: {aperture*scale}\")\n \n popdict = driver.get_population_by_node_as_dict(opts.province)\n pop = sum([v for k,v in popdict.items() if k != \"node\"])\n ToolBox.print_output(f\"population: {pop}\")\n for k,v in popdict.items():\n if k == \"node\": continue\n if v == 0: continue\n ToolBox.print_output(f\"\\t+ {k}: {v}\")\n\n prod = driver.calc_production(opts.province) \n ToolBox.print_output(f\"production: {prod}\")\n\n control = driver.calc_control(opts.province)\n ToolBox.print_output(f\"control:\")\n totalc = 1.0\n for c, i in control.items():\n im = round(i, 3)\n ToolBox.print_output(f\"\\t+ {c}: {im}\")\n totalc -= i\n t = round(totalc, 3)\n ToolBox.print_output(f\"\\t- no-control: {t}\")\n \nelif opts.province is not None and opts.xnode:\n xyset = driver.get_node_coordinates_as_set(opts.province)\n m = int(opts.margin)\n\n w = min(xyset, key=lambda x: x[0])\n e = max(xyset, key=lambda x: x[0])\n s = max(xyset, key=lambda x: x[1])\n n = min(xyset, key=lambda x: x[1])\n print(f\"-s{s[1]+m} -n{n[1]-m} -w{w[0]-m} -e{e[0]+m}\")\n\nelif opts.listv:\n if opts.type == \"all\":\n nodes = driver.get_node_names_as_set()\n elif opts.type == \"sea\":\n diagram = driver.get_vector_diagram()\n nodes = [n for n in driver.get_node_names_as_set() if not diagram.check_land(n)]\n elif opts.type == \"land\":\n diagram = driver.get_vector_diagram()\n nodes = [n for n in driver.get_node_names_as_set() if diagram.check_land(n)]\n elif opts.type == \"capital\":\n dout = driver.get_controls_as_dict(\"capital\")\n if opts.xnode:\n nodes = \"-\".join([cap[0] for cap in dout.values()])\n else:\n nodes = [f\"{cap[0]} -> {ctrl}\" for ctrl, cap in dout.items()] \n else: raise ValueError(f\"Unkown type: {opts.type}. Available: sea, land, capital, or all.\")\n if not opts.xnode:\n for node in nodes:\n ToolBox.print_output(node)\n else: print(nodes)\n \nelif opts.stream:\n nodes = opts.stream.split(\"-\")\n assert len(nodes) > 1, \"(e) at least 2 provinces (X-Y-Z...) are needed\"\n diagram = driver.get_vector_diagram()\n\n rin = diagram.calc_enter_resistance(nodes[1], nodes[0])\n ToolBox.print_output(f\"in: {nodes[0]} --> {nodes[1]} = {rin}\")\n total = rin\n\n for p, t, n in zip(nodes, nodes[1:], nodes[2:]):\n rt = diagram.calc_transit_resistance(p, t, n)\n ToolBox.print_output(f\"{p} --> {t} --> {n} = {rt}\")\n total += rt\n \n rout = diagram.calc_enter_resistance(nodes[-2], nodes[-1])\n ToolBox.print_output(f\"out: {nodes[-2]} --> {nodes[-1]} = {rout}\")\n total += rout\n\n ToolBox.print_output(f\"end-end: {nodes[0]} --> {nodes[-1]} = {total}\")\n\nelse: # summary\n nodes = driver.get_node_names_as_set()\n diagram = driver.get_vector_diagram()\n totalatoms = len(diagram)\n\n buildset = set()\n buildatoms = 0\n coastatoms = 0\n naviatoms = 0\n\n for xy in diagram.keys():\n if diagram.check_buildable(*xy):\n buildset.add(diagram.get_node(*xy))\n buildatoms += 1\n if diagram.check_navigable(*xy) or diagram.check_coast(*xy):\n naviatoms += 1\n if diagram.check_coast(*xy):\n coastatoms += 1\n\n na = 100 * float(naviatoms)/totalatoms\n fa = 100 * float(buildatoms)/totalatoms\n ca = 100 * float(coastatoms)/totalatoms\n ToolBox.print_output(f\"total nodes: {len(nodes)}\")\n ToolBox.print_output(f\"buildable nodes: {len(buildset)} area: {fa} %\")\n ToolBox.print_output(f\"coast length: {coastatoms} / {ca} %\")\n ToolBox.print_output(f\"navigable area: {na} %\")\n\n total = 0\n people = {nat: 0 for nat in driver.get_nation_names_as_set()}\n for nat in people.keys():\n natdis = driver.get_population_as_dict(nat)\n tot = sum(natdis.values())\n people[nat] = tot\n total += tot\n ToolBox.print_output(f\"total population: {total}\")\n for n, p in people.items():\n frac = round(100 * float(p) / total, 3)\n ToolBox.print_output(f\" {n}: {p} {frac} %\")\n \n","sub_path":"node.py","file_name":"node.py","file_ext":"py","file_size_in_byte":5909,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"465820066","text":"from sklearn import svm\nimport numpy as np\nimport pandas as pd\nimport scipy.stats as stats\nfrom matplotlib import pyplot as plt\n\ndf = pd.read_csv(\"wineQualityReds.csv.xls\", encoding=\"latin1\")\n\nprint(df.head())\n\nfor x in df.columns:\n print(x)\n print(\"mean:\", np.mean(df[x]))\n print(\"std:\", np.std(df[x]))\n print(\"Ali je to normalna distribucija:\", stats.normaltest(df[x]))\n\"\"\"\nUnnamed: 0\nmean: 800.0\nstd: 461.5914499497003\nAli je to normalna distribucija: NormaltestResult(statistic=1255.5660015661529, pvalue=2.2767058698004423e-273)\nfixed.acidity\nmean: 8.319637273295838\nstd: 1.7405518001102782\nAli je to normalna distribucija: NormaltestResult(statistic=224.53087840457746, pvalue=1.7528277735470436e-49)\nvolatile.acidity\nmean: 0.5278205128205131\nstd: 0.17900370424468975\nAli je to normalna distribucija: NormaltestResult(statistic=143.4193435598286, pvalue=7.1925890397566919e-32)\ncitric.acid\nmean: 0.2709756097560964\nstd: 0.1947402144523329\nAli je to normalna distribucija: NormaltestResult(statistic=152.039214793795, pvalue=9.6628222592810181e-34)\nresidual.sugar\nmean: 2.5388055034396517\nstd: 1.4094871124880504\nAli je to normalna distribucija: NormaltestResult(statistic=1520.3239698236891, pvalue=0.0)\nchlorides\nmean: 0.08746654158849257\nstd: 0.04705058260331576\nAli je to normalna distribucija: NormaltestResult(statistic=1783.1059225626427, pvalue=0.0)\nfree.sulfur.dioxide\nmean: 15.874921826141339\nstd: 10.456885614930723\nAli je to normalna distribucija: NormaltestResult(statistic=342.25914842512378, pvalue=4.779365332171477e-75)\ntotal.sulfur.dioxide\nmean: 46.46779237023139\nstd: 32.88503665178367\nAli je to normalna distribucija: NormaltestResult(statistic=487.42725648953467, pvalue=1.4338908343435381e-106)\ndensity\nmean: 0.9967466791744833\nstd: 0.0018867437008323923\nAli je to normalna distribucija: NormaltestResult(statistic=30.707749940958617, pvalue=2.1473202738030206e-07)\npH\nmean: 3.311113195747343\nstd: 0.15433818141060152\nAli je to normalna distribucija: NormaltestResult(statistic=33.684697471483915, pvalue=4.8468645347727716e-08)\nsulphates\nmean: 0.6581488430268921\nstd: 0.16945396724179526\nAli je to normalna distribucija: NormaltestResult(statistic=906.89444792270365, pvalue=1.1759065222978855e-197)\nalcohol\nmean: 10.422983114446502\nstd: 1.0653343003437463\nAli je to normalna distribucija: NormaltestResult(statistic=154.17806951912516, pvalue=3.3163288473185496e-34)\nquality\nmean: 5.6360225140712945\nstd: 0.8073168769639486\nAli je to normalna distribucija: NormaltestResult(statistic=17.262400816355541, pvalue=0.00017845030333854989)\n_______\nVidimo, da nobena od kategorij ne pripada normalni distribuciji\nZa standardiziranje kategorij bom uporabil kar rescale?\n\"\"\"\n\n\n\n\n# rescale data to 0 - 1\nfrom sklearn.preprocessing import MinMaxScaler\nfrom sklearn.feature_selection import VarianceThreshold\nfrom sklearn.feature_selection import SelectKBest\nfrom sklearn.feature_selection import chi2\n\n#sel = VarianceThreshold(threshold=(0.8*(1-0.8)))\n#sel = SelectKBest(chi2, k=11)\n#trainAtributi = sel.fit_transform(trainAtributi, trainRazred)\n#testAtributi = sel.fit_transform(testAtributi, testRazred)\n\n### VEČINSKI KLASIFIKATOR\nfrom collections import defaultdict\nfrom sklearn.neural_network import MLPClassifier\n\nindices = np.random.permutation(len(df))\n#len(df)*7//10 === len(df) * 7/10 === len(df) * 0.7\ntrain = df.iloc[indices[:len(df)*7//10], :]\ntest = df.iloc[indices[-len(df)*7//10:], :]\n\ntrainAtributi = train.iloc[:, 1:-1]\ntrainRazred = train.iloc[:, -1]\n\ntestAtributi = test.iloc[:, 1:-1]\ntestRazred = test.iloc[:, -1]\n\nslovar = defaultdict(int)\nfor x in trainRazred:\n slovar[x] += 1\nmaksimalni = 0\nkdo = \"\"\nfor key in slovar:\n if slovar[key] > maksimalni:\n maksimalni = slovar[key]\n kdo = key\nprint(\"Večinski razred je\", kdo)\nvečinski = np.array(trainRazred) == kdo\nvec = sum(večinski)/len(večinski)\nprint(\"Večinski klasifikator, točnost:\",vec)\n\nsvmTocnost = []\nnevronTocnost = []\n\nfor k in range(1):\n #razdelimo na train in test\n indices = np.random.permutation(len(df))\n #len(df)*7//10 === len(df) * 7/10 === len(df) * 0.7\n train = df.iloc[indices[:len(df)*7//10], :]\n test = df.iloc[indices[-len(df)*7//10:], :]\n\n trainAtributi = train.iloc[:, 1:-1]\n trainRazred = train.iloc[:, -1]\n\n testAtributi = test.iloc[:, 1:-1]\n testRazred = test.iloc[:, -1]\n\n scaler = MinMaxScaler(feature_range=(0, 1))\n trainRescaled = scaler.fit_transform(trainAtributi)\n\n\n svc = svm.SVC(kernel=\"linear\")\n svmTocnost.append(svc.fit(trainRescaled, trainRazred).score(scaler.transform(testAtributi), testRazred))\n\n ### NEVRONSKE MREŽE\n\n clf = MLPClassifier(solver='lbfgs', alpha=1e-5, hidden_layer_sizes=(5, 2), random_state=2)\n nevronTocnost.append(clf.fit(trainRescaled, trainRazred).score(scaler.transform(testAtributi), testRazred))\n\nsT = np.mean(svmTocnost)\nnT = np.mean(nevronTocnost)\nprint(\"SVM:\",sT , \"\\nNevronske:\", nT)\n\n\"\"\"\nVečinski razred je 5\nVečinski klasifikator, točnost: 0.430741733691\nSVM: 0.589285714286 \nNevronske: 0.627678571429\n\"\"\"\n\n\nfrom pandas.tools.plotting import scatter_matrix\n\nscatter_matrix(df, alpha=0.2, figsize=(20,10), diagonal=\"kde\")\nplt.show()\n\nfig, ax = plt.subplots(figsize=(20,20))\nax.hist(df.iloc[:, -1], color=\"blue\", alpha=0.8, align=\"mid\")\nax.set_title(\"Quality\")\nax.set_xlabel(\"Quality\")\nfig.savefig(\"Quality.pdf\", bbox_inches=\"tight\")\n\n# Izrisi se nekaj atributov, ki korelirajo :)\n\n#fixed.acidity\n#density\n\nfig, ax = plt.subplots(figsize=(20,20))\nax.scatter(df[\"fixed.acidity\"], df[\"density\"], color=\"blue\", alpha=0.8)\nax.set_title(\"Correlation between f. acid. and density\")\nax.set_ylabel(\"Density\")\nax.set_xlabel(\"Fixed Acidity\")\n\n#calculate correlation\nfrom scipy.stats import pearsonr\n\nkorelacija = pearsonr(df[\"fixed.acidity\"], df[\"density\"])\nkorelacija = np.round(korelacija, 4)\nax.text(6, max(df[\"density\"]), \"Korelacija: \"+ str(korelacija[0]), size=10)\n\ncoeficienti, covarianca = np.polyfit(df[\"fixed.acidity\"], df[\"density\"], deg=3, cov=True)\n\n# interpolacija\ninter = np.linspace(min(df[\"fixed.acidity\"]), max(df[\"fixed.acidity\"]), 500)\n# n je stopnja polinoma\nn = 3\n# matrix with rows 1, inter, inter**2, ...\nINTER = np.vstack( [inter**(n-1) for n in range(n+1)] ).T\n## matrix multiplication calculates the polynomial values\nyi = np.dot(INTER, coeficienti)\n# C_y = INTER*COVARIANCA*INTER.T\nC_y = np.dot(INTER, np.dot(covarianca, INTER.T))\n# Standard deviations are sqrt of diagonal\nsig_y = np.sqrt(np.diag(C_y))\n\nfunkcija = np.poly1d(coeficienti)\nax.plot(np.unique(df[\"fixed.acidity\"]), funkcija(np.unique(df[\"fixed.acidity\"])), linewidth=2, color=\"red\", alpha=0.6)\n#ax.fill_between(inter, yi+sig_y, yi-sig_y, color=\"red\", alpha=0.6)\nfig.savefig(\"korelacija.pdf\", bbox_inches=\"tight\")\nplt.show()\n","sub_path":"redWine/redwine.py","file_name":"redwine.py","file_ext":"py","file_size_in_byte":6757,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"19757399","text":"from numpy import array, zeros, diag, diagflat, dot, absolute\nimport numpy as np\nfrom tkinter import Tk, Frame, Label, Entry, Button, Toplevel, messagebox\n\nclass App:\n def __init__(self, master=None):\n self.container1 = Frame(master)\n self.container1.pack()\n\n self.container2 = Frame(master)\n self.container2.pack()\n\n self.label1 = Label(self.container1, text=\"Número de funções:\")\n self.label1.pack(side=\"left\") \n\n self.func = Entry(self.container1, width=5)\n self.func.pack()\n\n self.matriz = Button(self.container2)\n self.matriz[\"text\"] = \"Matriz\"\n self.matriz[\"command\"] = self.matrix\n self.matriz.pack(side=\"left\")\n self.sair = Button(self.container2)\n self.sair[\"text\"] = \"Sair\"\n self.sair[\"command\"] = self.container1.quit\n self.sair.pack()\n \n def matrix(self):\n num = int(self.func.get())\n \n if num < 2 or num > 8:\n messagebox.showerror(\"Erro\", \"Número de equações deve ser 2 <= n <= 8\")\n return\n \n matrix_window(num)\n\ndef matrix_window(num):\n top = Toplevel()\n top.title(\"Método de Jacobi\")\n container = []\n \n a = {}\n first = True\n \n for i in range(num):\n c = Frame(top)\n c.pack()\n container.append(c)\n \n for j in range(num): \n if first:\n A = Label(c)\n A[\"text\"] = \"A=\"\n A.pack(side=\"left\")\n first = False\n index = (i, j)\n e = Entry(c, width=5)\n e.pack(side=\"left\")\n a[index] = e\n \n container2 = Frame(top)\n container2.pack()\n container3 = Frame(top)\n container3.pack()\n container4 = Frame(top)\n container4.pack()\n container5 = Frame(top)\n container5.pack()\n container6 = Frame(top)\n container6.pack()\n \n B = Label(container2)\n B[\"text\"] = \"b=\"\n B.pack(side=\"left\")\n b = []\n \n for i in range(num):\n e = Entry(container2, width=5)\n e.pack(side=\"left\")\n b.append(e)\n \n X = Label(container3)\n X[\"text\"] = \"x=\"\n X.pack(side=\"left\")\n x = []\n \n for i in range(num):\n e = Entry(container3, width=5)\n e.pack(side=\"left\")\n x.append(e)\n \n er = Label(container4)\n er[\"text\"] = \"err=\"\n er.pack(side=\"left\")\n er = Entry(container4, width=5)\n er.pack(side=\"left\")\n \n matriz = Button(container5)\n matriz[\"text\"] = \"Calcular\"\n matriz[\"command\"] = lambda: result(a, b, x, er, res, num)\n matriz.pack()\n \n res = Label(container6)\n res[\"text\"] = \"Resultado: \"\n res.pack()\n \ndef result(a, b, x, err, res, num):\n A = []\n B = []\n X = []\n er = 0\n \n for i in range(num):\n v = []\n B.append(float(b[i].get()))\n X.append(float(x[i].get()))\n \n for j in range(num):\n index = (i, j)\n \n v.append(float(a[index].get()))\n \n er = float(err.get())\n \n A.append(v)\n \n A = array(A)\n B = array(B)\n X = array(X)\n\n if not converge_condition(A):\n messagebox.showwarning(\"Aviso\", \"Critério das linhas não cumprido.\")\n \n r = jacobi(A, B, er, X)\n\n res[\"text\"] = \"Resultado: \" + r\n\ndef jacobi(A,b,err, x=None, N = 25): \n if x is None:\n x = zeros(len(A[0]))\n \n xn = x \n D = diag(A)\n R = A - diagflat(D)\n \n i = 0\n e = 0\n \n while True:\n xn = (b - dot(R,x)) / D\n x_diff = []\n for i in range(len(A)):\n x_diff.append(xn[i] - x[i])\n \n x = xn\n e = abs(np.max(absolute(x_diff)) / np.max(absolute(xn)))\n i += 1\n \n if e < err and i < N:\n break\n \n res = \"\"\n \n for i in range(len(x)):\n res += \"\\nx[\" + str(i) + \"] = \" + str(x[i])\n \n return res + \"\\nErro = \" + str(e)\n\ndef converge_condition(A):\n D = diag(A)\n R = A - diagflat(D)\n alpha = zeros(len(A))\n \n for i in range(len(A)):\n for j in range(len(A)):\n alpha[i] += R[i,j]\n alpha[i] = (alpha[i]/A[i,i]) \n\n maxAlpha = float(max(alpha))\n \n if(maxAlpha<1.0):\n return True\n \n return False\n\nGUI = Tk()\nGUI.title(\"Método de Jacobi\")\nApp(GUI)\nGUI.mainloop()\n\n","sub_path":"trab2/jacobi_gui.py","file_name":"jacobi_gui.py","file_ext":"py","file_size_in_byte":4839,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"479957563","text":"#!/usr/bin/env python\n\n'''\nCreated by Samvel Khalatyan, Jul 09, 2012\nCopyright 2012, All rights reserved\n'''\n\nfrom __future__ import print_function\n\nimport os\nimport sys\n\nfrom config import config\nfrom template.options import parser\n\ndef main():\n class HelpExit(Exception): pass\n\n verbose = False\n try:\n opt_parser = parser()\n opt_parser.remove_option(\"--plots\")\n options, args = opt_parser.parse_args()\n\n # load application configuration\n #\n if not options.config:\n raise RuntimeError(\"application configuration is not specified\")\n\n config_ = config.load(os.path.expanduser(options.config))\n verbose = (options.verbose if options.verbose\n else config_[\"core\"][\"verbose\"])\n\n if verbose:\n print(\"loaded configuration from:\", options.config)\n\n if 1 == len(sys.argv):\n raise HelpExit()\n\n # import templates only here otherwise PyROOT inhercepts --help option\n import templates\n\n options.plots = \"/chi2\"\n app = templates.SignalOverSqrtSignalPlusBackground(options, args,\n config_)\n app.run()\n except HelpExit:\n opt_parser.print_help()\n\n return 0\n except Exception as error:\n if verbose:\n # print Exception traceback for debug\n import traceback\n\n traceback.print_tb(sys.exc_info()[2])\n\n print(error, file=sys.stderr)\n\n return 1\n else:\n return 0\n\nif \"__main__\" == __name__:\n sys.exit(main())\n","sub_path":"chi2/s_over_sqrt_sb.py","file_name":"s_over_sqrt_sb.py","file_ext":"py","file_size_in_byte":1596,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"284445668","text":"import cgen\nimport numpy as np\n\nfrom collections import defaultdict\n\nfrom devito import Eq\nfrom devito.ir.equations import ClusterizedEq\nfrom devito.ir.iet import (Call, Callable, Element, Expression, FindNodes, FindSymbols,\n IterationTree, List)\nfrom devito.ops.node_factory import OPSNodeFactory\nfrom devito.ops.types import OPSBlock, OPSDat, FunctionTimeAccess, ArrayAccess\nfrom devito.ops.utils import (extend_accesses, generate_ops_stencils, get_accesses,\n namespace)\nfrom devito.tools import dtype_to_cstr\nfrom devito.types import Constant, Indexed\nfrom devito.types.basic import FunctionPointer, Symbol, SymbolicArray, String\nfrom devito.symbolics.extended_sympy import Macro, Byref, ListInitializer\n\nOPS_WRITE = FunctionPointer(\"OPS_WRITE\")\nOPS_READ = FunctionPointer(\"OPS_READ\")\n\n\ndef opsit(trees, count):\n node_factory = OPSNodeFactory()\n expressions = []\n for tree in trees:\n expressions.extend(FindNodes(Expression).visit(tree.inner))\n\n it_range = []\n it_dims = 0\n for tree in trees:\n if isinstance(tree, IterationTree):\n it_range = [it.bounds() for it in tree]\n it_dims = len(tree)\n\n block = OPSBlock(namespace['ops_block'](count))\n block_init = Element(cgen.Initializer(\n block,\n Call(\"ops_decl_block\", [it_dims, String(block.name)], False)\n ))\n\n ops_expressions = []\n accesses = defaultdict(set)\n\n for i in reversed(expressions):\n extend_accesses(accesses, get_accesses(i.expr))\n ops_expressions.insert(0, Expression(make_ops_ast(i.expr, node_factory)))\n\n ops_stencils_initializers, ops_stencils = generate_ops_stencils(accesses)\n\n to_remove = [f.name for f in FindSymbols('defines').visit(List(body=expressions))]\n\n parameters = FindSymbols('symbolics').visit(List(body=ops_expressions))\n parameters = [\n p for p in parameters\n if p.name != 'OPS_ACC_size' and p.name not in to_remove\n ]\n parameters = sorted(parameters, key=lambda i: (i.is_Constant, i.name))\n\n arguments = FindSymbols('symbolics').visit(List(body=expressions))\n arguments = [a for a in arguments if a.name not in to_remove]\n arguments = sorted(arguments, key=lambda i: (i.is_Constant, i.name))\n\n ops_expressions = [\n Expression(\n fix_ops_acc(e.expr, [p.name for p in parameters])\n ) for e in ops_expressions\n ]\n\n callable_kernel = Callable(\n namespace['ops_kernel'](count),\n ops_expressions,\n \"void\",\n parameters\n )\n\n dat_declarations = []\n argname_to_dat = {}\n\n for a in arguments:\n if a.is_Constant:\n continue\n\n dat_dec, dat_sym = to_ops_dat(a, block)\n dat_declarations.extend(dat_dec)\n\n argname_to_dat.update(dat_sym)\n\n par_loop_range_arr = SymbolicArray(\n name=namespace['ops_range'](count),\n dimensions=(len(it_range) * 2,),\n dtype=np.int32\n )\n range_vals = []\n for mn, mx in it_range:\n range_vals.append(mn)\n range_vals.append(mx)\n par_loop_range_init = Expression(ClusterizedEq(Eq(\n par_loop_range_arr,\n ListInitializer(range_vals)\n )))\n\n ops_args = get_ops_args(\n [p for p in parameters], ops_stencils, argname_to_dat\n )\n\n par_loop = Call(\"ops_par_loop\", [\n FunctionPointer(callable_kernel.name),\n String(callable_kernel.name),\n block,\n it_dims,\n par_loop_range_arr,\n *ops_args\n ])\n\n return (\n callable_kernel,\n [par_loop_range_init, block_init] +\n ops_stencils_initializers + dat_declarations +\n [Call(\"ops_partition\", [String(\"\")])],\n List(body=[par_loop]),\n it_dims\n )\n\n\ndef get_ops_args(args, stencils, name_to_dat):\n ops_args = []\n\n for arg in args:\n if arg.is_Constant:\n ops_args.append(\n Call(\n \"ops_arg_gbl\",\n [\n Byref(Constant(name=arg.name[1:])),\n 1,\n String(dtype_to_cstr(arg.dtype)),\n OPS_READ\n ], False\n )\n )\n else:\n ops_args.append(\n Call(\n \"ops_arg_dat\",\n [\n name_to_dat[arg.name],\n 1,\n stencils[arg.name],\n String(dtype_to_cstr(arg.dtype)),\n OPS_WRITE if arg.is_Write else OPS_READ\n ], False)\n )\n\n return ops_args\n\n\ndef to_ops_dat(function, block):\n ndim = function.ndim - (1 if function.is_TimeFunction else 0)\n dim = SymbolicArray(\n name=\"%s_dim\" % function.name,\n dimensions=(ndim,),\n dtype=np.int32\n )\n\n base = SymbolicArray(\n name=\"%s_base\" % function.name,\n dimensions=(ndim,),\n dtype=np.int32\n )\n\n d_p = SymbolicArray(\n name=\"%s_d_p\" % function.name,\n dimensions=(ndim,),\n dtype=np.int32\n )\n\n d_m = SymbolicArray(\n name=\"%s_d_m\" % function.name,\n dimensions=(ndim,),\n dtype=np.int32\n )\n\n res = []\n dats = {}\n ops_decl_dat_call = []\n\n if function.is_TimeFunction:\n time_pos = function._time_position\n time_index = function.indices[time_pos]\n time_dims = function.shape[time_pos]\n\n dim_shape = function.shape[:time_pos] + function.shape[time_pos + 1:]\n padding = function.padding[:time_pos] + function.padding[time_pos + 1:]\n halo = function.halo[:time_pos] + function.halo[time_pos + 1:]\n base_val = [0 for i in range(ndim)]\n d_p_val = tuple([p[0] + h[0] for p, h in zip(padding, halo)])\n d_m_val = tuple([-(p[1] + h[1]) for p, h in zip(padding, halo)])\n\n ops_dat_array = SymbolicArray(\n name=\"%s_dat\" % function.name,\n dimensions=[time_dims],\n dtype=\"ops_dat\",\n )\n\n ops_decl_dat_call.append(Element(cgen.Statement(\n \"%s %s[%s]\" % (\n ops_dat_array.dtype,\n ops_dat_array.name,\n time_dims\n )\n )))\n\n for i in range(time_dims):\n access = FunctionTimeAccess(function, i)\n ops_dat_access = ArrayAccess(ops_dat_array, i)\n call = Call(\n \"ops_decl_dat\",\n [\n block,\n 1,\n dim,\n base,\n d_m,\n d_p,\n access,\n String(function._C_typedata),\n String(\"%s%s%s\" % (function.name, time_index, i))\n ],\n False\n )\n dats[\"%s%s%s\" % (function.name, time_index, i)] = ArrayAccess(\n ops_dat_array,\n Symbol(\"%s%s\" % (time_index, i))\n )\n ops_decl_dat_call.append(\n Element(cgen.Assign(ops_dat_access, call))\n )\n else:\n ops_dat = OPSDat(\"%s_dat\" % function.name)\n dats[function.name] = ops_dat\n\n d_p_val = tuple([p[0] + h[0] for p, h in zip(function.padding, function.halo)])\n d_m_val = tuple([-(p[1] + h[1]) for p, h in zip(function.padding, function.halo)])\n dim_shape = function.shape\n base_val = [0 for i in function.shape]\n\n ops_decl_dat_call.append(Element(cgen.Initializer(ops_dat, Call(\n \"ops_decl_dat\",\n [\n block,\n 1,\n dim,\n base,\n d_m,\n d_p,\n FunctionTimeAccess(function, 0),\n String(function._C_typedata),\n String(function.name)\n ],\n False\n ))))\n\n res.append(Expression(ClusterizedEq(Eq(dim, ListInitializer(dim_shape)))))\n res.append(Expression(ClusterizedEq(Eq(base, ListInitializer(base_val)))))\n res.append(Expression(ClusterizedEq(Eq(d_p, ListInitializer(d_p_val)))))\n res.append(Expression(ClusterizedEq(Eq(d_m, ListInitializer(d_m_val)))))\n res.extend(ops_decl_dat_call)\n\n return res, dats\n\n\ndef make_ops_ast(expr, nfops, is_Write=False):\n \"\"\"\n Transform a devito expression into an OPS expression.\n Only the interested nodes are rebuilt.\n\n Parameters\n ----------\n expr : :class:`Node`\n Initial tree node.\n nfops : :class:`OPSNodeFactory`\n Generate OPS specific nodes.\n Returns\n -------\n :class:`Node`\n Expression alredy translated to OPS syntax.\n \"\"\"\n\n if expr.is_Symbol:\n if expr.is_Constant:\n return nfops.new_ops_gbl(expr)\n return expr\n elif expr.is_Number:\n return expr\n elif expr.is_Indexed:\n return nfops.new_ops_arg(expr, is_Write)\n elif expr.is_Equality:\n return expr.func(\n make_ops_ast(expr.lhs, nfops, True),\n make_ops_ast(expr.rhs, nfops)\n )\n else:\n return expr.func(*[make_ops_ast(i, nfops) for i in expr.args])\n\n\ndef fix_ops_acc(expr, args):\n if expr.is_Symbol or expr.is_Number:\n return expr\n if expr.is_Indexed:\n return Indexed(\n expr.base,\n Macro('OPS_ACC%d(%s)' % (args.index(expr.name), expr.indices[0].name))\n )\n else:\n for i in expr.args:\n return expr.func(*[fix_ops_acc(i, args) for i in expr.args])\n","sub_path":"devito/ops/transformer.py","file_name":"transformer.py","file_ext":"py","file_size_in_byte":9503,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"461015341","text":"# -*- coding: utf-8 -*-\r\n##########################################################################################\r\n# import the necessary packages\r\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\r\nfrom tensorflow.keras.applications import MobileNetV2\r\nfrom tensorflow.keras.applications import VGG19\r\nfrom tensorflow.keras.applications import EfficientNetB7\r\nfrom tensorflow.keras.layers import AveragePooling2D\r\nfrom tensorflow.keras.layers import Dropout\r\nfrom tensorflow.keras.layers import Flatten\r\nfrom tensorflow.keras.layers import Dense\r\nfrom tensorflow.keras.layers import Input\r\nfrom tensorflow.keras.models import Model\r\nfrom tensorflow.keras.optimizers import Adam\r\nfrom tensorflow.keras.applications.mobilenet_v2 import preprocess_input as mv2_preprocess\r\nfrom tensorflow.keras.applications.vgg19 import preprocess_input as vgg19_preprocess\r\nfrom tensorflow.keras.applications.efficientnet import preprocess_input as effnet_preprocess\r\nfrom tensorflow.keras.preprocessing.image import img_to_array\r\nfrom tensorflow.keras.preprocessing.image import load_img\r\nfrom tensorflow.keras.utils import to_categorical\r\nfrom sklearn.model_selection import train_test_split\r\nfrom sklearn.metrics import classification_report, confusion_matrix\r\nfrom imutils import paths\r\nimport matplotlib.pyplot as plt\r\nfrom matplotlib import gridspec\r\nimport numpy as np\r\nimport pandas as pd\r\nimport os\r\nimport argparse\r\nimport seaborn as sns\r\n\r\n# Hyper-parameter tuning\r\nfrom tensorflow import keras\r\nfrom tensorflow.keras import layers\r\nfrom kerastuner.tuners import RandomSearch\r\nfrom tensorflow.keras.layers import Dense, Activation, Flatten, Dropout\r\nfrom tensorflow.keras.layers import Conv2D, AveragePooling2D, MaxPooling2D\r\nfrom tensorflow.keras.callbacks import ModelCheckpoint, EarlyStopping\r\nfrom tensorflow.keras.models import load_model\r\nfrom kerastuner.engine.hyperparameters import HyperParameters\r\n##########################################################################################\r\n\r\n# construct the argument parser and parse the arguments\r\nparser = argparse.ArgumentParser()\r\nparser.add_argument('-d', '--dataset', required=True, help=\"path to input dataset\")\r\nparser.add_argument('-o', '--output', required=True, help=\"path to output each epoch\")\r\nparser.add_argument(\"-p1\", \"--confusion_matrix\", type=str, default=\"confusion_matrix.png\", help=\"path to output loss plot\")\r\nparser.add_argument(\"-p2\", \"--accuracy_loss_plot\", type=str, default=\"accuracy_loss_plot.png\", help=\"path to output accuracy plot\")\r\nparser.add_argument(\"-vgg19\", \"--model1\", type=str, default=\"vgg19_mask_detection.hdf5\", help=\"path to output face mask detector VGG19 model\")\r\nparser.add_argument(\"-mv2\", \"--model2\", type=str, default=\"mv2_mask_detection.hdf5\", help=\"path to output face mask detector MobileNetV2 model\")\r\nparser.add_argument(\"-effb7\", \"--model3\", type=str, default=\"effb7_mask_detection.hdf5\", help=\"path to output face mask detector MobileNetV2 model\")\r\n\r\nargs = vars(parser.parse_args())\r\n###########################################################################################\r\n# Provide the path of all the images and the categories it needs to be categorized\r\ndata_directory = args[\"dataset\"]\r\n#data_directory = list(paths.list_images(args[\"dataset\"]))\r\noutput_directory = args[\"output\"]\r\n#output_directory = list(paths.list_images(args[\"output\"]))\r\n# Gets the folder names inside the given directory\r\ncategories = os.listdir(data_directory)\r\n# Store the categories as labels with 0,1,2\r\nlabels = [i for i in range(len(categories))]\r\n# create a dictonary variable and storing category and label information as key-value pair\r\n#label_dict = dict(zip(categories, labels))\r\nlabel_dict = {}\r\nfor c in categories:\r\n if c == \"No Mask\":\r\n label_dict[c] = 0\r\n elif c == \"Wrong Mask\":\r\n label_dict[c] = 1 \r\n elif c == \"Mask\":\r\n label_dict[c] = 2\r\n# Store number of categories based on number of labels\r\nnoc = len(labels)\r\nprint (\"Categories: \", categories)\r\nprint (\"Labels: \", labels )\r\nprint (\"Category and its Label information: \", label_dict)\r\n###########################################################################################\r\n\r\n# Converting the image into array and normalizing the image using preprocess block\r\ndef preprocessing_image(preprocess_type, directory, category):\r\n image_size = 224\r\n mv2_data = []\r\n mv2_labels = []\r\n vgg19_data = []\r\n vgg19_labels = []\r\n effb7_data = []\r\n effb7_labels = []\r\n print(\"[INFO] loading images...\")\r\n if preprocess_type.strip().upper() == \"MV2\":\r\n for category in categories:\r\n path = os.path.join(data_directory, category)\r\n # load the input image (224*224) and preprocess it\r\n for img in os.listdir(path):\r\n img_path = os.path.join(path, img)\r\n image = load_img(img_path, target_size=(image_size, image_size))\r\n image = img_to_array(image) # converted to (224,224,3) dimensions\r\n #print(\"image: \", image)\r\n #print(\"image shape: \", image.shape)\r\n image = mv2_preprocess(image) # Resizing scaled to -1 to 1 \r\n #print(\"preprocessed image: \", image)\r\n #print(\"preprocessed image shape: \", image.shape) \r\n # update the data and labels lists, respectively\r\n mv2_data.append(image)\r\n mv2_labels.append(label_dict[category])\r\n # Saving the image data and target data using numpy for backup\r\n np.save(os.path.join(output_directory, \"mv2_data\"), mv2_data)\r\n np.save(os.path.join(output_directory, \"mv2_labels\"), mv2_labels)\r\n elif preprocess_type.strip().upper() == \"VGG19\":\r\n for category in categories:\r\n path = os.path.join(data_directory, category)\r\n # load the input image (224*224) and preprocess it\r\n for img in os.listdir(path):\r\n img_path = os.path.join(path, img)\r\n image = load_img(img_path, target_size=(image_size, image_size))\r\n image = img_to_array(image) # converted to (224,224,3) dimensions\r\n #print(\"image: \", image)\r\n #print(\"image shape: \", image.shape)\r\n image = vgg19_preprocess(image) # Resizing scaled to -1 to 1 \r\n #print(\"preprocessed image: \", image)\r\n #print(\"preprocessed image shape: \", image.shape) \r\n # update the data and labels lists, respectively\r\n vgg19_data.append(image)\r\n vgg19_labels.append(label_dict[category])\r\n # Saving the image data and target data using numpy for backup\r\n np.save(os.path.join(output_directory, \"vgg19_data\"), vgg19_data)\r\n np.save(os.path.join(output_directory, \"vgg19_labels\"), vgg19_labels)\r\n elif preprocess_type.strip().upper() == \"EFFB7\":\r\n for category in categories:\r\n path = os.path.join(data_directory, category)\r\n # load the input image (224*224) and preprocess it\r\n for img in os.listdir(path):\r\n img_path = os.path.join(path, img)\r\n image = load_img(img_path, target_size=(image_size, image_size))\r\n image = img_to_array(image) # converted to (224,224,3) dimensions\r\n #print(\"image: \", image)\r\n #print(\"image shape: \", image.shape)\r\n image = effnet_preprocess(image) # Resizing scaled to -1 to 1 \r\n #print(\"preprocessed image: \", image)\r\n #print(\"preprocessed image shape: \", image.shape) \r\n # update the data and labels lists, respectively\r\n effb7_data.append(image)\r\n effb7_labels.append(label_dict[category])\r\n # Saving the image data and target data using numpy for backup\r\n np.save(os.path.join(output_directory, \"effb7_data\"), effb7_data)\r\n np.save(os.path.join(output_directory, \"effb7_labels\"), effb7_labels)\r\n \r\n print(\"Images loaded and saved Successfully \")\r\n########################################################################################### \r\n\r\n# preprocessing the images using Mobilenetv2 and save it\r\npreprocessing_image(\"MV2\", data_directory, categories)\r\n\r\n# loading the saved numpy arrays of mobilenetv2 preprocessed images\r\nmv2_data = np.load(os.path.join(output_directory, \"mv2_data.npy\"))\r\nmv2_labels = np.load(os.path.join(output_directory, \"mv2_labels.npy\"))\r\n########################################################################################\r\n\r\n# Bar plot to see the count of images in various categories\r\nunique, counts = np.unique(mv2_labels, return_counts=True)\r\ncategory_count = dict(zip(unique, counts))\r\ntemp_df = pd.DataFrame({'Labels': list(category_count.keys()), 'Count': list(category_count.values())})\r\n#temp_df['Labels'] = pd.DataFrame(list(category_count.keys()))\r\n#temp_df['Count'] = pd.DataFrame(list(category_count.values()))\r\ntemp_df.loc[temp_df['Labels'] == 0, 'Categories'] = list(label_dict.keys())[list(label_dict.values()).index(0)]\r\ntemp_df.loc[temp_df['Labels'] == 1, 'Categories'] = list(label_dict.keys())[list(label_dict.values()).index(1)]\r\ntemp_df.loc[temp_df['Labels'] == 2, 'Categories'] = list(label_dict.keys())[list(label_dict.values()).index(2)]\r\nplt.barh(temp_df.Categories, temp_df.Count, color='rgbkymc')\r\nplt.ylabel(\"Various Categories\")\r\nplt.xlabel(\"Count\")\r\nplt.title(\"Bar plot to see the count of images based on categories\")\r\nfor index, value in enumerate(temp_df.Count):\r\n plt.text(value, index, str(value))\r\nplt.show()\r\n##########################################################################################\r\n\r\n# Print some of the random images with labelled data\r\n# Use subplots to show images with the categories it belongs to\r\nnum_rows, num_cols = noc, noc+3\r\nnrow = 10\r\nncol = 3\r\n\r\nf, ax = plt.subplots(num_rows, num_cols, figsize=(12,7))\r\nfor r in range(num_rows):\r\n temp = np.where(mv2_labels==r)[0][0]\r\n print(temp)\r\n for c in range(num_cols):\r\n image_index = temp + c\r\n #print(image_index)\r\n ax[r,c].axis(\"off\")\r\n ax[r,c].imshow( mv2_data[image_index])\r\n ax[r,c].set_title(list(label_dict.keys())[list(label_dict.values()).index(mv2_labels[image_index])])\r\n plt.subplots_adjust(wspace=None, hspace=None)\r\nf.suptitle(\"Images after pre processed using Mobilenet V2\")\r\nplt.show()\r\nplt.close()\r\n############################################################################################\r\n\r\n# convert output array of labeled data(from 0 to nb_classes - 1) to one-hot vector\r\nmv2_labels = to_categorical(mv2_labels)\r\nprint (\"Shape of mv2 data: \", mv2_data.shape)\r\nprint (\"Shape of mv2 labels: \", mv2_labels.shape)\r\n###########################################################################################\r\n\r\n# construct the training image generator for data augmentation\r\naug = ImageDataGenerator(\r\n\trotation_range=10,\r\n\tzoom_range=0.05,\r\n\twidth_shift_range=0.1,\r\n\theight_shift_range=0.1,\r\n\tshear_range=0.1,\r\n\thorizontal_flip=True,\r\n\tfill_mode=\"nearest\")\r\n#############################################################################################\r\n\r\n# Build Hyper Tunning model for MobileNetV2\r\ndef mv2_build_model(hp):\r\n baseModel = MobileNetV2(weights=\"imagenet\", include_top=False,input_tensor=Input(shape=(224, 224, 3)))\r\n headModel = baseModel.output\r\n headModel = keras.layers.AveragePooling2D(pool_size=(7, 7))(headModel)\r\n headModel = keras.layers.Flatten()(headModel)\r\n headModel = keras.layers.Dense(units = hp.Int(name = 'dense_units', min_value=64, max_value=256, step=16), activation = 'relu')(headModel)\r\n headModel = keras.layers.Dropout(hp.Float(name = 'dropout', min_value = 0.1, max_value = 0.5, step=0.1, default=0.5))(headModel)\r\n headModel = keras.layers.Dense(3, activation = 'softmax')(headModel)\r\n model = Model(inputs=baseModel.input, outputs=headModel)\r\n # loop over all layers in the base model and freeze them so they will\r\n # *not* be updated during the first training process\r\n for layer in baseModel.layers:\r\n layer.trainable = False\r\n model.compile(optimizer = keras.optimizers.Adam(hp.Choice('learning_rate', values = [1e-2,5e-3,1e-3,5e-4,1e-4])),\r\n loss = 'categorical_crossentropy',\r\n metrics = ['accuracy'])\r\n return model\r\n\r\n########################################################################################\r\n# Stratified Split the data into 20% Test and 80% Traininng data\r\nX_train,X_test,y_train, y_test = train_test_split(mv2_data, mv2_labels, test_size = 0.2, stratify = mv2_labels, random_state = 42)\r\n\r\nprint(\"MobilenetV2 Train data shape: \",X_train.shape)\r\nprint(\"MobilenetV2 Train label shape: \",y_train.shape)\r\nprint(\"MobilenetV2 Test data shape: \",X_test.shape)\r\nprint(\"MobilenetV2 Test label shape: \",y_test.shape)\r\n\r\nnp.save(os.path.join(output_directory, \"X_test\"), X_test)\r\nnp.save(os.path.join(output_directory, \"y_test\"), y_test)\r\n##########################################################################################\r\n# delete data and label variables to release ram\r\ndel mv2_data\r\ndel mv2_labels\r\n##########################################################################################\r\n# Hyperparameter tuning\r\nprint (\"Search for best model fit for mobilenetv2...\")\r\nmv2_tuner_search = RandomSearch(mv2_build_model, objective = 'val_accuracy', max_trials =30, directory = output_directory, project_name = \"MobileNetV2\")\r\nmv2_tuner_search.search(X_train, y_train, epochs = 3, validation_split = 0.2)\r\n\r\n# Show a summary of the hyper parameter search output for 30 combination parameters\r\nmv2_tuner_search.results_summary()\r\nmv2_model = mv2_tuner_search.get_best_models(num_models=1)[0]\r\nmv2_model.summary()\r\n#########################################################################################\r\n# Set callback functions to early stop training and save the best model so far\r\ncallbacks = [EarlyStopping(monitor='val_loss', patience=10),\r\n ModelCheckpoint(filepath=args[\"model2\"], monitor='val_loss', save_best_only=True)]\r\n\r\n# Train neural network\r\nmv2_history = mv2_model.fit(aug.flow(X_train, y_train, batch_size=64),\r\n epochs=30, # Number of epochs\r\n callbacks=callbacks, # Early stopping\r\n verbose=2, # Print description after each epoch\r\n validation_data=(X_test, y_test)) # Data for evaluation\r\n\r\nnp.save(os.path.join(output_directory, 'mv2_history.npy'),mv2_history.history)\r\n# convert the history.history dict to a pandas DataFrame: \r\nhist_df = pd.DataFrame(mv2_history.history) \r\n# or save to csv: \r\nhist_csv_file = os.path.join(output_directory, 'mv2_history.csv')\r\nwith open(hist_csv_file, mode='w') as f:\r\n hist_df.to_csv(f)\r\n#############################################################################################\r\n# preprocessing the images using VGG19 and save it\r\npreprocessing_image(\"VGG19\", data_directory, categories)\r\n\r\n# loading the saved numpy arrays of vgg19 preprocessed images\r\nvgg19_data = np.load(os.path.join(output_directory, \"vgg19_data.npy\"))\r\nvgg19_labels = np.load(os.path.join(output_directory, \"vgg19_labels.npy\"))\r\n\r\n# Check the data shape and labels after preprocessing of vgg19 image data\r\nprint(\"first 10 target values: \", vgg19_labels[1:10])\r\nprint(\"shape of data\", vgg19_data[0].shape)\r\nprint(\"first image data information in array\", vgg19_data[0])\r\n\r\n# convert output array of labeled data(from 0 to nb_classes - 1) to one-hot vector\r\nvgg19_labels = to_categorical(vgg19_labels)\r\nprint (\"Shape of vgg19 data: \", vgg19_data.shape)\r\nprint (\"Shape of vgg19 labels: \", vgg19_labels.shape)\r\n###############################################################################################\r\n\r\n# Build Hyper Tunning model for VGG19\r\ndef vgg19_build_model(hp):\r\n baseModel = VGG19(weights=\"imagenet\", include_top=False,input_tensor=Input(shape=(224, 224, 3)))\r\n headModel = baseModel.output\r\n headModel = keras.layers.MaxPooling2D(pool_size=(5, 5))(headModel)\r\n headModel = keras.layers.Flatten()(headModel)\r\n headModel = keras.layers.Dense(units = hp.Int(name = 'dense_units', min_value=64, max_value=256, step=16), activation = 'relu')(headModel)\r\n headModel = keras.layers.Dropout(hp.Float(name = 'dropout', min_value = 0.1, max_value = 0.5, step=0.1, default=0.5))(headModel)\r\n headModel = keras.layers.Dense(3, activation = 'softmax')(headModel)\r\n model = Model(inputs=baseModel.input, outputs=headModel)\r\n # loop over all layers in the base model and freeze them so they will\r\n # *not* be updated during the first training process\r\n for layer in baseModel.layers:\r\n layer.trainable = False\r\n model.compile(optimizer = keras.optimizers.Adam(hp.Choice('learning_rate', values = [1e-2,5e-3,1e-3,5e-4,1e-4])),\r\n loss = 'categorical_crossentropy',\r\n metrics = ['accuracy'])\r\n return model\r\n#################################################################################################\r\n# Stratified Split the data into 20% Test and 80% Traininng data\r\nX2_train,X2_test,y2_train, y2_test = train_test_split(vgg19_data, vgg19_labels, test_size = 0.2, stratify = vgg19_labels, random_state = 42)\r\n\r\nprint(\"VGGNET19 Train data shape: \",X2_train.shape)\r\nprint(\"VGGNET19 Train label shape: \",y2_train.shape)\r\nprint(\"VGGNET19 Test data shape: \",X2_test.shape)\r\nprint(\"VGGNET19 Test label shape: \",y2_test.shape)\r\n\r\nnp.save(os.path.join(output_directory, \"X2_test\"), X2_test)\r\nnp.save(os.path.join(output_directory, \"y2_test\"), y2_test)\r\n##############################################################################################\r\n# delete data and label variables to release ram\r\ndel vgg19_data\r\ndel vgg19_labels\r\n###########################################################################################\r\n# Tuuning\r\nprint (\"Search for best model fit for vgg19...\")\r\nvgg19_tuner_search = RandomSearch(vgg19_build_model, objective = 'val_accuracy', max_trials =30, directory = output_directory, project_name = \"VGGNET19\")\r\nvgg19_tuner_search.search(X2_train, y2_train, epochs = 3, validation_split = 0.2)\r\n# Show a summary of the hyper parameter search output for 100 combination parameters\r\nvgg19_tuner_search.results_summary()\r\nvgg19_model = vgg19_tuner_search.get_best_models(num_models=1)[0]\r\nvgg19_model.summary()\r\n\r\n# Set callback functions to early stop training and save the best model so far\r\ncallbacks = [EarlyStopping(monitor='val_loss', patience=10),\r\n ModelCheckpoint(filepath=args[\"model1\"], monitor='val_loss', save_best_only=True)]\r\n###########################################################################################\r\n# Train neural network\r\nvgg19_history = vgg19_model.fit(aug.flow(X2_train, y2_train, batch_size=64),\r\n epochs=30, # Number of epochs\r\n callbacks=callbacks, # Early stopping\r\n verbose=2, # Print description after each epoch\r\n validation_data=(X2_test, y2_test)) # Data for evaluation\r\n\r\n\r\nnp.save(os.path.join(output_directory, 'vgg19_history.npy'),vgg19_history.history)\r\n# convert the history.history dict to a pandas DataFrame: \r\nhist_df = pd.DataFrame(vgg19_history.history) \r\n# or save to csv: \r\nhist_csv_file = os.path.join(output_directory, 'vgg19_history.csv')\r\nwith open(hist_csv_file, mode='w') as f:\r\n hist_df.to_csv(f)\r\n\r\n############################################################################################\r\n# preprocessing the images using EfficientNet and save it\r\npreprocessing_image(\"EFFB7\", data_directory, categories) \r\n \r\n# loading the saved numpy arrays of EfficientNet preprocessed images\r\neffb7_data = np.load(os.path.join(output_directory, \"effb7_data.npy\"))\r\neffb7_labels = np.load(os.path.join(output_directory, \"effb7_labels.npy\"))\r\n\r\n# Check the data shape and labels after preprocessing of efficentnet b7 image data\r\nprint(\"first 10 target values: \", effb7_labels[1:10])\r\nprint(\"shape of data\", effb7_data[0].shape)\r\nprint(\"first image data information in array\", effb7_data[0])\r\n\r\n# convert output array of labeled data(from 0 to nb_classes - 1) to one-hot vector\r\neffb7_labels = to_categorical(effb7_labels)\r\nprint (\"Shape of efficient net data: \", effb7_data.shape)\r\nprint (\"Shape of efficient net labels: \", effb7_labels.shape)\r\n#######################################################################################\r\n\r\ndef effb7_build_model(hp):\r\n baseModel = EfficientNetB7(weights=\"imagenet\", include_top=False,input_tensor=Input(shape=(224, 224, 3)))\r\n headModel = baseModel.output\r\n headModel = keras.layers.GlobalMaxPooling2D()(headModel)\r\n #keras.layers.MaxPooling2D(pool_size=(5, 5))(headModel)\r\n headModel = keras.layers.Flatten()(headModel)\r\n headModel = keras.layers.Dense(units = hp.Int(name = 'dense_units', min_value=64, max_value=1024, step=64), activation = 'relu')(headModel)\r\n headModel = keras.layers.Dropout(hp.Float(name = 'dropout', min_value = 0.4, max_value = 0.8, step=0.1, default=0.5))(headModel)\r\n headModel = keras.layers.Dense(3, activation = 'softmax')(headModel)\r\n model = Model(inputs=baseModel.input, outputs=headModel)\r\n # loop over all layers in the base model and freeze them so they will\r\n # *not* be updated during the first training process\r\n for layer in baseModel.layers:\r\n layer.trainable = False\r\n model.compile(optimizer = keras.optimizers.Adam(hp.Choice('learning_rate', values = [1e-2,5e-3,1e-3,5e-4,1e-4])),\r\n loss = 'categorical_crossentropy',\r\n metrics = ['accuracy'])\r\n return model\r\n##########################################################################################\r\n\r\n# Stratified Split the data into 20% Test and 80% Traininng data for EFFB7 model\r\nX3_train,X3_test,y3_train, y3_test = train_test_split(effb7_data, effb7_labels, test_size = 0.2, stratify = effb7_labels, random_state = 42)\r\n\r\nprint(\"efficient net Train data shape: \",X3_train.shape)\r\nprint(\"efficient net Train label shape: \",y3_train.shape)\r\nprint(\"efficient net Test data shape: \",X3_test.shape)\r\nprint(\"efficient net Test label shape: \",y3_test.shape)\r\n\r\nnp.save(os.path.join(output_directory, \"X3_test\"), X3_test)\r\nnp.save(os.path.join(output_directory, \"y3_test\"), y3_test)\r\n\r\n##############################################################################################\r\n# delete data and label variables to release ram\r\ndel effb7_data\r\ndel effb7_labels\r\n\r\n#######################################################################################\r\n#Tuning\r\nprint (\"Search for best model fit for Effb7...\")\r\neffb7_tuner_search = RandomSearch(effb7_build_model, objective = 'val_accuracy', max_trials =30, directory = output_directory, project_name = \"EfficientNet\")\r\neffb7_tuner_search.search(X3_train, y3_train, epochs = 3, validation_split = 0.2)\r\n\r\n# Show a summary of the hyper parameter search output for 30 combination parameters\r\neffb7_tuner_search.results_summary()\r\n\r\n# Show the best parameters choosen model\r\neffb7_model = effb7_tuner_search.get_best_models(num_models=1)[0]\r\neffb7_model.summary()\r\n\r\n# Set callback functions to early stop training and save the best model so far\r\ncallbacks = [EarlyStopping(monitor='val_loss', patience=10),\r\n ModelCheckpoint(filepath=args[\"model3\"], monitor='val_loss', save_best_only=True)]\r\n########################################################################################################################################\r\n# Train neural network with best model for 30 epochs\r\neffb7_history = effb7_model.fit(aug.flow(X3_train, y3_train, batch_size=64),\r\n epochs=30, # Number of epochs\r\n callbacks=callbacks, # Early stopping\r\n verbose=2, # Print description after each epoch\r\n validation_data=(X3_test, y3_test)) # Data for evaluation\r\n\r\n\r\nnp.save(os.path.join(output_directory, 'effb7_history.npy'),effb7_history.history)\r\n# convert the history.history dict to a pandas DataFrame: \r\nhist_df = pd.DataFrame(effb7_history.history) \r\n# or save to csv: \r\nhist_csv_file = os.path.join(output_directory, 'effb7_history.csv')\r\nwith open(hist_csv_file, mode='w') as f:\r\n hist_df.to_csv(f)\r\n###############################################################################\r\n# Plot the loss and accuracy for both VGG19 and MobileNetV2 models\r\nmv2_history_csv = pd.read_csv(os.path.join(output_directory, 'mv2_history.csv'))\r\nvgg19_history_csv = pd.read_csv(os.path.join(output_directory, 'vgg19_history.csv'))\r\neffb7_history_csv = pd.read_csv(os.path.join(output_directory, 'effb7_history.csv'))\r\n#mv2_history_csv.rename(columns={ mv2_history_csv.columns[1]: \"epoch\" })\r\n#mv2_history_csv.rename({'Unnamed: 0':'epoch'}, axis='columns')\r\nfig = plt.figure(figsize = (20,20))\r\nax1 = fig.add_subplot(2, 3, 1) # row, column, position\r\nax2 = fig.add_subplot(2, 3, 2) # row, column, position\r\nax3 = fig.add_subplot(2, 3, 3) # row, column, position\r\nax4 = fig.add_subplot(2, 3, 4) # row, column, position\r\nax5 = fig.add_subplot(2, 3, 5) # row, column, position\r\nax6 = fig.add_subplot(2, 3, 6) # row, column, position\r\n\r\nmv2_history_csv.rename( columns={'Unnamed: 0':'epoch'}, inplace=True)\r\nvgg19_history_csv.rename( columns={'Unnamed: 0':'epoch'}, inplace=True)\r\neffb7_history_csv.rename( columns={'Unnamed: 0':'epoch'}, inplace=True)\r\nvgg19_history_csv.plot(x = \"epoch\", y=['loss','val_loss'], ax=ax1, title = 'Training vs Val loss for VGG19 model')\r\nax1.set_xlabel(\"epoch\")\r\nax1.set_ylabel(\"loss value\")\r\nax1.set_ylim(min(vgg19_history_csv.loss.min(), vgg19_history_csv.val_loss.min(), mv2_history_csv.loss.min(), mv2_history_csv.val_loss.min(),effb7_history_csv.loss.min(), effb7_history_csv.val_loss.min()),max(vgg19_history_csv.loss.max(), vgg19_history_csv.val_loss.max(), mv2_history_csv.loss.max(), mv2_history_csv.val_loss.max(), effb7_history_csv.loss.max(), effb7_history_csv.val_loss.max()))\r\n\r\nmv2_history_csv.plot(x = \"epoch\", y=['loss','val_loss'], ax=ax2, title = 'Training vs Val loss for MobileNetV2 model')\r\nax2.set_xlabel(\"epoch\")\r\nax2.set_ylabel(\"loss value\")\r\nax2.set_ylim(min(vgg19_history_csv.loss.min(), vgg19_history_csv.val_loss.min(), mv2_history_csv.loss.min(), mv2_history_csv.val_loss.min(),effb7_history_csv.loss.min(), effb7_history_csv.val_loss.min()),max(vgg19_history_csv.loss.max(), vgg19_history_csv.val_loss.max(), mv2_history_csv.loss.max(), mv2_history_csv.val_loss.max(), effb7_history_csv.loss.max(), effb7_history_csv.val_loss.max()))\r\n\r\neffb7_history_csv.plot(x = \"epoch\", y=['loss','val_loss'], ax=ax3, title = 'Training vs Val loss for EfficientNetB7 model')\r\nax3.set_xlabel(\"epoch\")\r\nax3.set_ylabel(\"loss value\")\r\nax3.set_ylim(min(vgg19_history_csv.loss.min(), vgg19_history_csv.val_loss.min(), mv2_history_csv.loss.min(), mv2_history_csv.val_loss.min(),effb7_history_csv.loss.min(), effb7_history_csv.val_loss.min()),max(vgg19_history_csv.loss.max(), vgg19_history_csv.val_loss.max(), mv2_history_csv.loss.max(), mv2_history_csv.val_loss.max(), effb7_history_csv.loss.max(), effb7_history_csv.val_loss.max()))\r\n\r\nvgg19_history_csv.plot(x = \"epoch\", y=['accuracy','val_accuracy'], ax=ax4, title = 'Training vs Val accuracy for VGG19 model')\r\nax4.set_xlabel(\"epoch\")\r\nax4.set_ylabel(\"accuracy value\")\r\nax4.set_ylim(min(vgg19_history_csv.accuracy.min(), vgg19_history_csv.val_accuracy.min(), mv2_history_csv.accuracy.min(), mv2_history_csv.val_accuracy.min(), effb7_history_csv.accuracy.min(), effb7_history_csv.val_accuracy.min()),max(vgg19_history_csv.accuracy.max(), vgg19_history_csv.val_accuracy.max(), mv2_history_csv.accuracy.max(), mv2_history_csv.val_accuracy.max(), effb7_history_csv.accuracy.max(), effb7_history_csv.val_accuracy.max()))\r\nmv2_history_csv.plot(x = \"epoch\", y=['accuracy','val_accuracy'], ax=ax5, title = 'Training vs Val accuracy for MobileNetV2 model')\r\nax5.set_xlabel(\"epoch\")\r\nax5.set_ylabel(\"accuracy value\")\r\nax5.set_ylim(min(vgg19_history_csv.accuracy.min(), vgg19_history_csv.val_accuracy.min(), mv2_history_csv.accuracy.min(), mv2_history_csv.val_accuracy.min(), effb7_history_csv.accuracy.min(), effb7_history_csv.val_accuracy.min()),max(vgg19_history_csv.accuracy.max(), vgg19_history_csv.val_accuracy.max(), mv2_history_csv.accuracy.max(), mv2_history_csv.val_accuracy.max(), effb7_history_csv.accuracy.max(), effb7_history_csv.val_accuracy.max()))\r\neffb7_history_csv.plot(x = \"epoch\", y=['accuracy','val_accuracy'], ax=ax6, title = 'Training vs Val accuracy for EfficientNetb7 model')\r\nax6.set_xlabel(\"epoch\")\r\nax6.set_ylabel(\"accuracy value\")\r\nax6.set_ylim(min(vgg19_history_csv.accuracy.min(), vgg19_history_csv.val_accuracy.min(), mv2_history_csv.accuracy.min(), mv2_history_csv.val_accuracy.min(), effb7_history_csv.accuracy.min(), effb7_history_csv.val_accuracy.min()),max(vgg19_history_csv.accuracy.max(), vgg19_history_csv.val_accuracy.max(), mv2_history_csv.accuracy.max(), mv2_history_csv.val_accuracy.max(), effb7_history_csv.accuracy.max(), effb7_history_csv.val_accuracy.max()))\r\nplt.savefig(args[\"accuracy_loss_plot\"])\r\nplt.show()\r\n\r\n#############################################################################################\r\n\r\n# loading the MobileNetV2 model back\r\nmv2_model = keras.models.load_model(args[\"model2\"])\r\nvgg19_model = keras.models.load_model(args[\"model1\"])\r\neffb7_model = keras.models.load_model(args[\"model3\"])\r\n\r\nX_test = np.load(os.path.join(output_directory, \"X_test.npy\"))\r\nX2_test = np.load(os.path.join(output_directory, \"X2_test.npy\"))\r\nX3_test = np.load(os.path.join(output_directory, \"X3_test.npy\"))\r\ny_test = np.load(os.path.join(output_directory, \"y_test.npy\"))\r\ny2_test = np.load(os.path.join(output_directory, \"y2_test.npy\"))\r\ny3_test = np.load(os.path.join(output_directory, \"y3_test.npy\"))\r\n\r\n# Find the difference between the predicted values count between two models\r\ndef difference_predicted(model1, model2, X1, y1, X2, y2, model1_name, model2_name):\r\n print(\"[INFO] evaluating \"+model1_name+\" model predicted values...\")\r\n m1 = model1.predict(X1, batch_size=64).round()\r\n # for each image in the testing set we need to find the index of the\r\n # label with corresponding largest predicted probability\r\n m1 = np.argmax(m1, axis=1)\r\n print(\"[INFO] evaluating \"+model2_name+\" model predicted values...\")\r\n m2 = model2.predict(X2, batch_size=64).round()\r\n # for each image in the testing set we need to find the index of the\r\n # label with corresponding largest predicted probability\r\n m2 = np.argmax(m2, axis=1)\r\n print(\"Difference between the predicted values of \" +model1_name+\" model and \"+model2_name+\" model are: \" + str(y1.shape[0]-np.count_nonzero(m1 == m2)) + \" in \"+ str(y1.shape[0]) + \" records\")\r\n\r\ndifference_predicted(mv2_model, vgg19_model, X_test, y_test, X2_test, y2_test, \"MobilenetV2\", \"VGG19\")\r\ndifference_predicted(mv2_model, effb7_model, X_test, y_test, X3_test, y3_test, \"MobilenetV2\", \"Efficient Net\")\r\ndifference_predicted(effb7_model, vgg19_model, X3_test, y3_test, X2_test, y2_test, \"Efficient Net\", \"VGG19\")\r\n#############################################################################################\r\n# Evaluate VGG19 model\r\nprint(vgg19_model.evaluate(X2_test, y2_test, batch_size = 64))\r\n\r\n# Evaluate MobileNetV2 model\r\nprint(mv2_model.evaluate(X_test, y_test, batch_size = 64))\r\n\r\n# Evaluate EFFB7 model\r\nprint(effb7_model.evaluate(X3_test, y3_test, batch_size = 64))\r\n###########################################################################################\r\n# Model Prediction for MobileNetV2\r\nmv2_y_pred = mv2_model.predict(X_test)\r\n\r\nfrom sklearn.metrics import accuracy_score\r\nprint(\"Accuracy Score: \",accuracy_score(y_test, mv2_y_pred.round())*100)\r\n\r\nfrom sklearn.metrics import classification_report, confusion_matrix\r\nprint(\"Classification Report: \\n\", classification_report(mv2_y_pred.round(), y_test))\r\n\r\n# Model Prediction for VGG19\r\nvgg19_y_pred = vgg19_model.predict(X2_test)\r\n\r\nfrom sklearn.metrics import accuracy_score\r\nprint(\"Accuracy Score: \",accuracy_score(y2_test, vgg19_y_pred.round())*100)\r\n\r\nfrom sklearn.metrics import classification_report, confusion_matrix\r\nprint(\"Classification Report: \\n\", classification_report(vgg19_y_pred.round(), y2_test))\r\n\r\n# Model Prediction for EFFB7 \r\neffb7_y_pred = effb7_model.predict(X3_test)\r\n\r\nfrom sklearn.metrics import accuracy_score\r\nprint(\"Accuracy Score: \",accuracy_score(y3_test, effb7_y_pred.round())*100)\r\n\r\nfrom sklearn.metrics import classification_report, confusion_matrix\r\nprint(\"Classification Report: \\n\", classification_report(effb7_y_pred.round(), y3_test))\r\n############################################################################################\r\n\r\n# Confusion Matrix - {'No Mask': 0, 'Wrong Mask': 1, 'Mask': 2}\r\nfrom sklearn.metrics import confusion_matrix\r\nimport seaborn as sns\r\nimport matplotlib.pyplot as plt\r\nimport pandas as pd\r\nfig = plt.figure(figsize = (20,5))\r\nax1 = fig.add_subplot(1, 3, 1) # row, column, position\r\nax2 = fig.add_subplot(1, 3, 2) # row, column, position\r\nax3 = fig.add_subplot(1, 3, 3) # row, column, position\r\ncm1 =confusion_matrix(y2_test.argmax(axis=1), vgg19_y_pred.round().argmax(axis=1)) \r\nindex = ['No Mask','Wrong Mask','Mask'] \r\ncolumns = ['No Mask','Wrong Mask','Mask'] \r\ncm_df1 = pd.DataFrame(cm1,columns,index) \r\ncm_df1.index.name = \"vgg19_Actual\"\r\ncm_df1.columns.name = \"vgg19_Predicted\"\r\nax1.set_title(\"VGG19 Model\")\r\n\r\ncm2 =confusion_matrix(y_test.argmax(axis=1), mv2_y_pred.round().argmax(axis=1)) \r\nindex = ['No Mask','Wrong Mask','Mask'] \r\ncolumns = ['No Mask','Wrong Mask','Mask'] \r\ncm_df2 = pd.DataFrame(cm2,columns,index) \r\ncm_df2.index.name = \"mv2_Actual\"\r\ncm_df2.columns.name = \"mv2_Predicted\"\r\nax2.set_title(\"MobileNetV2 Model\")\r\n\r\ncm3 =confusion_matrix(y3_test.argmax(axis=1), effb7_y_pred.round().argmax(axis=1)) \r\nindex = ['No Mask','Wrong Mask','Mask'] \r\ncolumns = ['No Mask','Wrong Mask','Mask'] \r\ncm_df3 = pd.DataFrame(cm3,columns,index) \r\ncm_df3.index.name = \"effb7_Actual\"\r\ncm_df3.columns.name = \"effb7_Predicted\"\r\nax3.set_title(\"EfficientNetB7 Model\")\r\n\r\nsns.heatmap(cm_df1, annot=True, fmt = \".0f\", ax=ax1)\r\nsns.heatmap(cm_df2, annot=True, fmt = \".0f\", ax=ax2)\r\nsns.heatmap(cm_df3, annot=True, fmt = \".0f\", ax=ax3)\r\n\r\nplt.savefig(args[\"confusion_matrix\"])\r\nplt.show()\r\n#######################################################################################\r\n","sub_path":"training_mask_detection.py","file_name":"training_mask_detection.py","file_ext":"py","file_size_in_byte":34261,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"92831730","text":"# coding: utf-8\n#\n# Copyright 2019 Geocom Informatik AG / VertiGIS\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\"\"\"\nThis module can be used to build lookup data structures from Esri tables and feature classes.\n\n.. automethod:: gpf.lookups._process_row\n\"\"\"\n\nimport gpf.common.const as _const\nimport gpf.common.textutils as _tu\nimport gpf.common.validate as _vld\nimport gpf.cursors as _cursors\nimport gpf.tools.geometry as _geo\nimport gpf.tools.metadata as _meta\n\n_DUPEKEYS_ARG = 'duplicate_keys'\n_MUTABLE_ARG = 'mutable_values'\n_ROWFUNC_ARG = 'row_func'\n\n#: The default (Esri-recommended) resolution that is used by the :func:`get_nodekey` function (i.e. for lookups).\n#: If coordinate values fall within this distance, they are considered equal.\n#: Set this to a higher or lower value (coordinate system units) if required.\nXYZ_RESOLUTION = 0.0001\n\n\ndef get_nodekey(*args):\n \"\"\"\n This function creates a hash-like tuple that can be used as a key in a :class:`RowLookup` or\n :class:`ValueLookup` dictionary.\n The tuple does not contain actual hashes, but consists of 2 or 3 (long) integers, which essentially are created by\n dividing the coordinate values by the default resolution (0.0001) and truncating them to an integer.\n\n Whenever a lookup is created using `SHAPE@XY` or `SHAPE@XYZ` as the *key_field*, this function is automatically\n used to generate a key for the coordinate. If the user has a coordinate and wants to find the matching value(s)\n in the lookup, the coordinate must be turned into a key first using this function.\n\n .. note:: The number of dimensions of the coordinate must match the ones in the lookup.\n In other words, when a lookup was built using 2D coordinates, the lookup key must be 2D as well.\n\n .. warning:: This function has been tested on 10 million random points and no duplicate keys were encountered.\n However, bear in mind that 2 nearly identical coordinates might share the same key if they lie\n within the default resolution distance from each other (0.0001 units e.g. meters).\n If the default resolution needs to be changed, set the ``XYZ_RESOLUTION`` constant beforehand.\n\n Example:\n\n >>> coord_lookup = ValueLookup('C:/Temp/test.gdb/my_points', 'SHAPE@XY', 'GlobalID')\n >>> coord = (4.2452, 23.24541)\n >>> key = key(*coord)\n >>> print(key)\n (42451, 232454)\n >>> coord_lookup.get(key)\n '{628ee94d-2063-47be-b57f-8c2af6345d4e}'\n\n :param args: A minimum of 2 numeric values, an EsriJSON dictionary, an ArcPy Point or PointGeometry instance.\n :rtype: tuple\n \"\"\"\n return tuple(int(v / XYZ_RESOLUTION) for v in _geo.get_xyz(*args) if v is not None)\n\n\ndef get_coordtuple(node_key):\n \"\"\"\n This function converts a node key (created by :func:`get_nodekey`) of integer tuples\n back into a floating point coordinate X, Y(, Z) tuple.\n\n .. warning:: This function should **only** be used to generate output for printing/logging purposes or to create\n approximate coordinates. Because :func:`get_nodekey` truncates the coordinate, it is impossible\n to get the same coordinate value back as the one that was used to create the node key, which means\n that some accuracy will be lost in the process.\n\n :param node_key: The node key (tuple of integers) that has to be converted.\n :rtype: tuple\n \"\"\"\n return tuple((v * XYZ_RESOLUTION) for v in node_key)\n\n\n# noinspection PyUnusedLocal\ndef _process_row(lookup, row, **kwargs):\n \"\"\"\n The default row processor function used by the :class:`Lookup` class.\n Alternative row processor functions are implemented by the other lookup classes (e.g. :class:`ValueLookup`).\n\n :param lookup: A reference to the lookup dictionary.\n If the process_row() function is built in to a lookup class, *lookup* refers to *self*.\n :param row: The current row tuple (as returned by a :class:`SearchCursor`).\n :param kwargs: Optional user-defined keyword arguments.\n :rtype: None, str, unicode\n\n .. note:: This \"private\" function is documented here, so that users can see its signature and behaviour.\n However, users should **not** call this function directly, but define their own functions\n based on this one, using the same function signature.\n\n Row processor functions directly manipulate (i.e. populate) the dictionary.\n Typically, this function should at least add a key and value(s) to the *lookup* dictionary.\n\n **A row function should always return ``None``, unless the user wants to terminate the lookup.**\n In that case, a failure reason (message) should be returned.\n \"\"\"\n key, v = row[0], row[1:] if len(row) > 2 else row[1]\n if key is None:\n return\n lookup[key] = v\n\n\nclass Lookup(dict):\n \"\"\"\n Lookup(table_path, key_field, value_field(s), {where_clause}, {**kwargs})\n\n Base class for all lookups.\n\n This class can be instantiated directly, but typically, a user would create a custom lookup class based on\n this one and then override the :func:`Lookup._process_row` method.\n Please refer to other implementations (:class:`RowLookup`, :class:`ValueLookup`) for concrete examples.\n\n **Params:**\n\n - **table_path** (str, unicode):\n\n Full source table or feature class path.\n\n - **key_field** (str, unicode):\n\n The field to use for the lookup dictionary keys.\n If *SHAPE@X[Y[Z]]* is used as the key field, the coordinates are \"hashed\" using the\n :func:`gpf.lookups.get_nodekey` function.\n This means, that the user should use this function as well in order to\n to create a coordinate key prior to looking up the matching value for it.\n\n - **value_fields** (list, tuple, str, unicode):\n\n The field or fields to include as the lookup dictionary value(s), i.e. row.\n This is the value (or tuple of values) that is returned when you perform a lookup by key.\n\n - **where_clause** (str, unicode, :class:`gpf.tools.queries.Where`):\n\n An optional where clause to filter on.\n\n **Keyword params:**\n\n - **row_func**:\n\n If the user wishes to call the standard `Lookup` class but simply wants to use\n a custom row processor function, you can pass in this function using the keyword *row_func*.\n\n :raises RuntimeError: When the lookup cannot be created or populated.\n :raises ValueError: When a specified lookup field does not exist in the source table,\n or when multiple value fields were specified.\n \"\"\"\n\n def __init__(self, table_path, key_field, value_fields, where_clause=None, **kwargs):\n super(dict, self).__init__()\n\n fields = tuple([key_field] + list(value_fields if _vld.is_iterable(value_fields) else (value_fields, )))\n self._hascoordkey = key_field.upper().startswith(_const.FIELD_X)\n self._populate(table_path, fields, where_clause, **kwargs)\n\n @staticmethod\n def _get_fields(table_path):\n \"\"\"\n Gets all field names in the table.\n\n :raises RuntimeError: When the table metadata could not be retrieved.\n :rtype: list\n \"\"\"\n desc = _meta.Describe(table_path)\n _vld.pass_if(desc, RuntimeError, 'Failed to create lookup for {}'.format(_tu.to_repr(table_path)))\n return desc.get_fields(True, True)\n\n @staticmethod\n def _check_fields(user_fields, table_fields):\n \"\"\"\n Checks if the given *user_fields* exist in *table_fields*.\n\n :raises ValueError: When a field does not exist in the source table.\n \"\"\"\n for field in user_fields:\n _vld.pass_if(_const.CHAR_AT in field or field.upper() in table_fields,\n ValueError, 'Field {} does not exist'.format(field))\n\n @staticmethod\n def _has_self(row_func):\n \"\"\" Checks if `func` is an instance method or function and checks if it's a valid row processor. \"\"\"\n if _vld.signature_matches(row_func, Lookup._process_row):\n # row_func is an instance method (signature matches the default self._process_row())\n return True\n elif _vld.signature_matches(row_func, _process_row):\n # row_func is a regular function (signature matches _process_row())\n return False\n else:\n raise ValueError('Row processor function has a bad signature')\n\n def _process_row(self, row, **kwargs):\n \"\"\" Instance method version of the :func:`_process_row` module function. \"\"\"\n return _process_row(self, row, **kwargs)\n\n def _populate(self, table_path, fields, where_clause=None, **kwargs):\n \"\"\" Populates the lookup with data, calling _process_row() on each row returned by the SearchCursor. \"\"\"\n try:\n # Validate fields\n self._check_fields(fields, self._get_fields(table_path))\n\n # Validate row processor function (if any)\n row_func = kwargs.get(_ROWFUNC_ARG, self._process_row)\n has_self = self._has_self(row_func)\n\n with _cursors.SearchCursor(table_path, fields, where_clause) as rows:\n for row in rows:\n failed = row_func(row, **kwargs) if has_self else row_func(self, row, **kwargs)\n if failed:\n raise Exception(failed)\n\n except Exception as e:\n raise RuntimeError('Failed to create {} for {}: {}'.format(self.__class__.__name__,\n _tu.to_repr(table_path), e))\n\n\nclass ValueLookup(Lookup):\n \"\"\"\n ValueLookup(table_path, key_field, value_field, {where_clause}, {duplicate_keys})\n\n Creates a lookup dictionary from a given source table or feature class.\n ValueLookup inherits from ``dict``, so all the built-in dictionary functions\n (:func:`update`, :func:`items` etc.) are available.\n\n When an empty key (``None``) is encountered, the key-value pair will be discarded.\n\n **Params:**\n\n - **table_path** (str, unicode):\n\n Full source table or feature class path.\n\n - **key_field** (str, unicode):\n\n The field to use for the ValueLookup dictionary keys.\n If *SHAPE@X[Y[Z]]* is used as the key field, the coordinates are \"hashed\" using the\n :func:`gpf.lookups.get_nodekey` function.\n This means, that the user should use this function as well in order to\n to create a coordinate key prior to looking up the matching value for it.\n\n - **value_field** (str, unicode):\n\n The single field to include in the ValueLookup dictionary value.\n This is the value that is returned when you perform a lookup by key.\n\n - **where_clause** (str, unicode, :class:`gpf.tools.queries.Where`):\n\n An optional where clause to filter the table.\n\n **Keyword params:**\n\n - **duplicate_keys** (bool):\n\n If ``True``, the ValueLookup allows for duplicate keys in the input.\n The dictionary values will become **lists** of values instead of a **single** value.\n Please note that actual duplicate checks will not be performed. This means, that\n when *duplicate_keys* is ``False`` and duplicates *are* encountered,\n the last existing key-value pair will be overwritten.\n\n :raises RuntimeError: When the lookup cannot be created or populated.\n :raises ValueError: When a specified lookup field does not exist in the source table,\n or when multiple value fields were specified.\n\n .. seealso:: When multiple fields should be stored in the lookup,\n the :class:`gpf.lookups.RowLookup` class should be used instead.\n \"\"\"\n\n def __init__(self, table_path, key_field, value_field, where_clause=None, **kwargs):\n _vld.raise_if(_vld.is_iterable(value_field), ValueError,\n '{} expects a single value field: use {} instead'.format(ValueLookup.__name__,\n RowLookup.__name__))\n _vld.pass_if(all(_vld.has_value(v) for v in (table_path, key_field, value_field)), ValueError,\n '{} requires valid table_path, key_field and value_field arguments'.format(ValueLookup.__name__))\n\n # User cannot override row processor function for this class\n if _ROWFUNC_ARG in kwargs:\n del kwargs[_ROWFUNC_ARG]\n\n self._dupekeys = kwargs.get(_DUPEKEYS_ARG, False)\n super(ValueLookup, self).__init__(table_path, key_field, value_field, where_clause, **kwargs)\n\n def _process_row(self, row, **kwargs):\n \"\"\" Row processor function override. \"\"\"\n key, value = row\n if key is None:\n return\n if self._hascoordkey:\n key = get_nodekey(*key)\n if self._dupekeys:\n v = self.setdefault(key, [])\n v.append(value)\n else:\n self[key] = value\n\n\nclass RowLookup(Lookup):\n \"\"\"\n RowLookup(table_path, key_field, value_fields, {where_clause}, {duplicate_keys}, {mutable_values})\n\n Creates a lookup dictionary from a given table or feature class.\n RowLookup inherits from ``dict``, so all the built-in dictionary functions\n (:func:`update`, :func:`items` etc.) are available.\n\n When an empty key (``None``) is encountered, the key-values pair will be discarded.\n\n **Params:**\n\n - **table_path** (str, unicode):\n\n Full source table or feature class path.\n\n - **key_field** (str, unicode):\n\n The field to use for the RowLookup dictionary keys.\n If *SHAPE@X[Y[Z]]* is used as the key field, the coordinates are \"hashed\" using the\n :func:`gpf.tools.lookup.get_nodekey` function.\n This means, that the user should use this function as well in order to\n to create a coordinate key prior to looking up the matching values for it.\n\n - **value_field** (str, unicode):\n\n The fields to include in the RowLookup dictionary values.\n These are the values that are returned when you perform a lookup by key.\n\n - **where_clause** (str, unicode, :class:`gpf.tools.queries.Where`):\n\n An optional where clause to filter the table.\n\n **Keyword params:**\n\n - **duplicate_keys** (bool):\n\n If ``True``, the RowLookup allows for duplicate keys in the input.\n The values will become **lists** of tuples/lists instead of a **single** tuple/list.\n Please note that duplicate checks will not actually be performed. This means, that\n when *duplicate_keys* is ``False`` and duplicates are encountered,\n the last existing key-value pair will be simply overwritten.\n\n - **mutable_values** (bool):\n\n If ``True``, the RowLookup values are stored as ``list`` objects.\n These are mutable, which means that you can change the values or add new ones.\n The default is ``False``, which causes the RowLookup values to become ``tuple`` objects.\n These are immutable, which consumes less memory and allows for faster retrieval.\n\n :raises RuntimeError: When the lookup cannot be created or populated.\n :raises ValueError: When a specified lookup field does not exist in the source table,\n or when a single value field was specified.\n\n .. seealso:: When a single field value should be stored in the lookup,\n the :class:`gpf.lookups.ValueLookup` class should be used instead.\n \"\"\"\n\n def __init__(self, table_path, key_field, value_fields, where_clause=None, **kwargs):\n _vld.raise_if(len(value_fields) <= 1, ValueError, '{} expects multiple value fields: use {} instead'.format(\n RowLookup.__name__, ValueLookup.__name__))\n _vld.pass_if(all(_vld.has_value(v) for v in (table_path, key_field, value_fields[0])), ValueError,\n '{} requires valid table_path, key_field and value_fields arguments')\n\n # User cannot override row processor function for this class\n if _ROWFUNC_ARG in kwargs:\n del kwargs[_ROWFUNC_ARG]\n\n self._dupekeys = kwargs.get(_DUPEKEYS_ARG, False)\n self._rowtype = list if kwargs.get(_MUTABLE_ARG, False) else tuple\n super(RowLookup, self).__init__(table_path, key_field, value_fields, where_clause, **kwargs)\n\n self._fieldmap = {name.lower(): i for i, name in enumerate(value_fields)}\n\n def _process_row(self, row, **kwargs):\n \"\"\" Row processor function override. \"\"\"\n key, values = row[0], self._rowtype(row[1:])\n if key is None:\n return\n if self._hascoordkey:\n key = get_nodekey(*key)\n if self._dupekeys:\n v = self.setdefault(key, [])\n v.append(values)\n else:\n self[key] = values\n\n def get_value(self, key, field, default=None):\n \"\"\"\n Looks up a value by key for one specific field.\n This function can be convenient when only a single value needs to be retrieved from the lookup.\n The difference with the built-in :func:`get` method is, that the :func:`get_value` function\n returns a single value, whereas the other one returns a list or tuple of values (i.e. row).\n\n Example:\n\n >>> my_lookup = RowLookup('C:/Temp/test.gdb/my_table', 'GlobalID', 'Field1', 'Field2')\n\n >>> # Traditional approach to print Field1:\n >>> values = my_lookup.get('{628ee94d-2063-47be-b57f-8c2af6345d4e}')\n >>> if values:\n >>> print(values[0])\n 'ThisIsTheValueOfField1'\n\n >>> # Alternative traditional approach to print Field1:\n >>> field1, field2 = my_lookup.get('{628ee94d-2063-47be-b57f-8c2af6345d4e}', (None, None))\n >>> if field1:\n >>> print(field1)\n 'ThisIsTheValueOfField1'\n\n >>> # Approach using the get_value() function:\n >>> print(my_lookup.get_value('{628ee94d-2063-47be-b57f-8c2af6345d4e}', 'Field1'))\n 'ThisIsTheValueOfField1'\n\n :param key: Key to find in the lookup dictionary.\n :param field: The field name (as used during initialization of the lookup) for which to retrieve the value.\n :param default: The value to return when the value was not found. Defaults to ``None``.\n :type field: str, unicode\n \"\"\"\n\n row = self.get(key, ())\n try:\n return row[self._fieldmap[field.lower()]]\n except LookupError:\n return default\n\n\nclass NodeSet(set):\n \"\"\"\n Builds a set of unique node keys for coordinates in a feature class.\n The :func:`get_nodekey` function will be used to generate the coordinate hash.\n When the feature class is Z aware, the node keys will be 3D as well.\n Note that in all cases, M will be ignored.\n\n The ``NodeSet`` inherits all methods from the built-in Python ``set``.\n\n For feature classes with a geometry type other than Point, a NodeSet will be built from the first and last\n points in a geometry. If this is not desired (i.e. all coordinates should be included), the user should set\n the *all_vertices* option to ``True``.\n An exception to this behavior is the Multipoint geometry: for this type, all coordinates will always be included.\n\n **Params:**\n\n - **fc_path** (str, unicode):\n\n The full path to the feature class.\n\n - **where_clause** (str, unicode, gpf.tools.queries.Where):\n\n An optional where clause to filter the feature class.\n\n - **all_vertices** (bool):\n\n Defaults to ``False``. When set to ``True``, all geometry coordinates are included.\n Otherwise, only the first and/or last points are considered.\n\n :raises ValueError: If the input dataset is not a feature class or if the geometry type is MultiPatch.\n \"\"\"\n\n def __init__(self, fc_path, where_clause=None, all_vertices=False):\n super(NodeSet, self).__init__()\n self._populate(fc_path, where_clause, all_vertices)\n\n @staticmethod\n def _get_desc(fc_path):\n # Checks if the input dataset is valid and returns its Describe object\n desc = _meta.Describe(fc_path)\n if not desc.shapeType:\n raise ValueError('Input dataset {} is not a feature class'.format(_tu.to_repr(fc_path)))\n if desc.is_multipatchclass:\n raise ValueError('Geometry type of {} is not supported'.format(_tu.to_repr(fc_path)))\n return desc\n\n def _fix_params(self, fc_path, all_vertices):\n \"\"\"\n Returns a tuple of (field, all_vertices) based on the input parameters.\n The shape type of the feature class sets the field name and may override *oll_vertices*.\n \"\"\"\n\n # The fastest way to fetch results is by reading coordinate tuples\n desc = self._get_desc(fc_path)\n field = _const.FIELD_XYZ if desc.hasZ else _const.FIELD_XY\n if not desc.is_pointclass:\n # However, for geometry types other than Point, we need to read the Shape object\n field = _const.FIELD_SHAPE\n if desc.is_multipointclass:\n # Multipoints will be treated differently (always read all vertices)\n all_vertices = True\n\n return field, all_vertices\n\n def _populate(self, fc_path, where_clause, all_vertices):\n \"\"\" Populates the NodeSet with node keys. \"\"\"\n\n field, all_vertices = self._fix_params(fc_path, all_vertices)\n\n # Iterate over all geometries and add keys\n with _cursors.SearchCursor(fc_path, field, where_clause) as rows:\n for shape, in rows:\n # If the geometry is a simple coordinate tuple, immediately add it\n if field.startswith(_const.FIELD_XY):\n self.add(get_nodekey(*shape))\n continue\n\n if all_vertices:\n for coord in _geo.get_vertices(shape):\n self.add(get_nodekey(*coord))\n continue\n\n # When *all_vertices* is False (or the geometry is not a Multipoint), only get the start/end nodes\n self.add(get_nodekey(shape.firstPoint))\n self.add(get_nodekey(shape.lastPoint))\n\n\nclass ValueSet(frozenset):\n \"\"\"\n Builds a set of unique values for a single column in a feature class or table.\n This class inherits all methods from the built-in Python ``frozenset``.\n\n **Params:**\n\n - **table_path** (str, unicode):\n\n The full path to the table or feature class.\n\n - **field** (str, unicode):\n\n The field name for which to collect a set of unique values.\n\n - **where_clause** (str, unicode, gpf.tools.queries.Where):\n\n An optional where clause to filter the feature class.\n \"\"\"\n\n def __new__(cls, table_path, field, where_clause=None):\n # Populate the frozenset\n with _cursors.SearchCursor(table_path, field, where_clause) as rows:\n return super(ValueSet, cls).__new__(cls, (value for value, in rows))\n\n # noinspection PyMissingConstructor, PyUnusedLocal\n def __init__(self, table_path, field, where_clause=None):\n # This override is only required for type hint purposes and to match __new__'s signature\n pass\n","sub_path":"gpf/lookups.py","file_name":"lookups.py","file_ext":"py","file_size_in_byte":24077,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"608448806","text":"\"\"\"Unit tests for the Azure Devops Server issues collector.\"\"\"\n\nfrom .base import AzureDevopsTestCase\n\n\nclass AzureDevopsIssuesTest(AzureDevopsTestCase):\n \"\"\"Unit tests for the Azure Devops Server issues metric.\"\"\"\n\n METRIC_TYPE = \"issues\"\n\n async def test_nr_of_issues(self):\n \"\"\"Test that the number of issues is returned.\"\"\"\n response = await self.collect(\n get_request_json_return_value=dict(value=[self.work_item, self.work_item]),\n post_request_json_return_value=dict(workItems=[dict(id=\"id1\"), dict(id=\"id2\")]),\n )\n self.assert_measurement(response, value=\"2\")\n\n async def test_no_issues(self):\n \"\"\"Test zero issues.\"\"\"\n response = await self.collect(post_request_json_return_value=dict(workItems=[]))\n self.assert_measurement(response, value=\"0\", entities=[])\n\n async def test_issues(self):\n \"\"\"Test that the issues are returned.\"\"\"\n response = await self.collect(\n get_request_json_return_value=dict(value=[self.work_item]),\n post_request_json_return_value=dict(workItems=[dict(id=\"id\")]),\n )\n self.assert_measurement(\n response,\n entities=[\n dict(\n key=\"id\",\n project=\"Project\",\n title=\"Title\",\n work_item_type=\"Task\",\n state=\"New\",\n url=self.work_item_url,\n )\n ],\n )\n","sub_path":"components/collector/tests/source_collectors/azure_devops/test_issues.py","file_name":"test_issues.py","file_ext":"py","file_size_in_byte":1498,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"538340355","text":"# https://atcoder.jp/contests/abc009/tasks/abc009_4\nimport sys\nsys.setrecursionlimit(2147483647)\nINF=float(\"inf\")\nMOD=10**9+7\ninput=lambda :sys.stdin.readline().rstrip()\ndef resolve():\n def power(b,p,f):\n \"\"\"\n b: object (base)\n p: positive int (multiplier)\n f: multiple function\n return: f^p(b)\n \"\"\"\n if not isinstance(p,int): raise ValueError(\"multiplier must be int\")\n elif p<=0: raise ValueError(\"multiplier must be positive.\")\n logp=p.bit_length()\n S=[0]*logp\n S[0]=b\n res='$'\n for i in range(logp):\n if i!=logp-1: S[i+1]=f(S[i],S[i])\n if p&(1<\"\n msg['To'] = toEmail\n\n body = 'Hi '+toName+', \\n\\nHope you are doing well! Certificates Attached.\\n\\nRegards,\\nMr.X'\n msg.set_content(body)\n\n #Attachments\n with open (attachment,'rb') as f:\n file_data=f.read()\n file_name=f.name\n msg.add_attachment(file_data,maintype='application',subtype='octet-stream',filename=file_name)\n \n #Send Mail\n try:\n with smtplib.SMTP_SSL('smtp.gmail.com', 465) as smtp:\n smtp.login(email, password)\n smtp.send_message(msg)\n print(\"\\nMail sent to \",toName,\"(\",toEmail,\")\",\"\\nFile Attached:\",attachment)\n sent+=1\n except:\n print(\"Error! : Mail not Sent to \",toName,\" \",toEmail)\n failed+=1\n\nprint()\nprint(\"REPORT\")\nprint(\"Successful Mails:\",sent)\nprint(\"Failed:\",failed)\nprint()\n","sub_path":"BulkEmailSend/Send_Emails.py","file_name":"Send_Emails.py","file_ext":"py","file_size_in_byte":1682,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"270940737","text":"import module.initial.cfConverter as cvt\nimport module.initial.cfOds as ods\nimport module.initial.cfMysql as mysql\nimport module.process.cfSchedule as schedule\nimport os\nimport csv\nimport json\nimport re\n\nwith open(\"environment.json\", 'r') as datas:\n env = json.load(datas)\n\n''' Settint Environment '''\nuser = env['mysql']['user']\npasswd = env['mysql']['password']\ndatabase = env['mysql']['database']\n\npath_ods = env['framework']\n\npath_xls = env['classes']['path'] + \"/xls\"\npath_html = env['classes']['path'] + \"/html\"\npath_csv = env['classes']['path'] + \"/csv\"\n\n\n# # ''' Convert Original xls to CSV formate '''\n# converter = cvt.cfConverter(path_xls, path_html)\n# converter.extension_convert(\"xls\", \"html\")\n\n# converter = cvt.cfConverter(path_html, path_csv)\n# converter.csv_convert()\n\n\n# # ''' Seperation by universes '''\n# ods = ods.cfOds(path_ods)\n# hash_name = ods.get_hash_name()[0]\n# files = os.listdir(path_csv)\n\n# datas = dict()\n# for file_path in files:\n# key = os.path.splitext(file_path)[0]\n# univ_table = hash_name[key]\n\n# datas[univ_table] = list()\n\n# file_path = os.path.join(path_csv, file_path)\n\n# with open(file_path, 'r') as file_datas:\n# csv_datas = csv.reader(file_datas, delimiter=',')\n\n# for row in csv_datas:\n# datas[univ_table].append(row)\n\n\n# ''' Initialize MySQL '''\n# # Set Table's names and attrs\n# table_names = list()\n# for name in ods.get_name()[0]:\n# table_names.append(name[1])\n\n# table_attrs = list()\n# primary_keys = str()\n# for attr in ods.get_attrs():\n# table_attrs.append(attr[0] + \" \" + attr[1])\n\n# if attr[3] == \"PRI\":\n# primary_keys += attr[0] + \", \"\n\n# if primary_keys:\n# primary_keys = \"PRIMARY KEY(\" + primary_keys[:-2] + \")\"\n# table_attrs.append(primary_keys)\n\n\n# mysql = mysql.cfMySQL(user, passwd, database)\n# mysql.connect_mysql()\n# mysql.create_database(database)\n# mysql.use_database(database)\n# for univ_name in table_names:\n# mysql.create_table(univ_name, table_attrs)\n\n# for univ_name in table_names:\n# mysql.insert_data(univ_name, datas[univ_name])\n\n\n''' Excluding '''\n# Excluding...\nods = ods.cfOds(path_ods)\nmysql = mysql.cfMySQL(user, passwd, database)\nmysql.connect_mysql()\nmysql.use_database(database)\n\nhash_name = ods.get_hash_name()[0]\ncolumns = [\"lecture_time\"]\n\nschedule = schedule.cfSchedule()\n\nlectures = list()\nfor key, table_name in hash_name.items():\n lecture = mysql.select_datas(table_name, columns)\n lectures += lecture\n\nschedule.extract_all(lectures)\nschedule.exclude_all()\nschedule.sperate_start_end()\n\n\n\n# # Set Exclude table's name and attrs\n# table_name = ods.get_name()[1][0][1]\n\n# table_attrs = list()\n# primary_keys = str()\n# for attr in ods.get_attrs(table_name):\n# table_attrs.append(attr[0] + \" \" + attr[1])\n\n# if attr[3] == \"PRI\":\n# primary_keys += attr[0] + \", \"\n\n# if primary_keys:\n# primary_keys = \"PRIMARY KEY(\" + primary_keys[:-2] + \")\"\n# table_attrs.append(primary_keys)\n\n# mysql.create_table(table_name, table_attrs)\n\n# convert_exDatas = list()\n# for key, value in schedule.ex_data.items():\n# tmp = [key, json.dumps(value, ensure_ascii=False)]\n# convert_exDatas.append(tmp)\n\n# mysql.insert_data(table_name, convert_exDatas)\n\n\n# Export json file as 'exclude.json'\n\nrRoomIdx = r'^[A-Z]+';\nse_data = schedule.se_data\n\nse_idx_datas = dict()\nfor room, times in se_data.items():\n room_idx = re.findall(rRoomIdx, room)[0]\n\n if not room_idx in se_idx_datas:\n se_idx_datas[room_idx] = dict()\n se_idx_datas[room_idx][room] = times\n\n# se_idx_datas = sorted(se_idx_datas.items(), key=lambda x: x[0])\nwith open('exclude.json', 'w') as fp:\n json.dump(se_idx_datas, fp, ensure_ascii=False)\n\nprint(\"END PROCESSING!\")","sub_path":"code/cfRun.py","file_name":"cfRun.py","file_ext":"py","file_size_in_byte":3756,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"536241491","text":"from sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn.metrics.pairwise import cosine_similarity\nimport pandas as pd\nimport numpy as np\nimport re\nimport shutil\nimport os\n\nclass RemoveNoiseTweets:\n\n intervals = 25000\n def __init__(self, csvfile,is_testing_set):\n self.file = csvfile\n self.is_testing_set = is_testing_set\n\n def removenoise(self):\n for k in np.arange(0, 0):\n print(\"iteration: \", k, \"\\n\"*10)\n shutil.rmtree(\"data/clean/\")\n os.mkdir(\"data/clean\")\n # if k==0:\n # df = pd.read_csv(self.file)\n # else:\n if self.is_testing_set:\n df = pd.read_csv(self.file)\n RemoveNoiseTweets.intervals = 100\n else:\n df = pd.read_csv(self.file)\n print(\"data dimensions: \",df.shape)\n print(\"data columns: \",df.columns)\n if \"level_0\" in df.columns:\n df.drop(['level_0'],axis=1, inplace=True)\n if \"index\" in df.columns:\n df.drop(['index'],axis=1,inplace=True)\n text_data = pd.DataFrame(df.text)\n # print(text_data.head())\n # print(type(text_data))\n\n print(\"length of text_data: \", len(text_data))\n print(\"reading the file\",self.file, \"for cleaning\")\n print(\"data dimensions: \", df.shape)\n for i in np.arange(0, len(text_data), step=RemoveNoiseTweets.intervals):\n temp_df = df[i:i+RemoveNoiseTweets.intervals]\n print(temp_df.head())\n temp_df.reset_index(inplace=True)\n # print(\"shape of temp df: \", temp_df.shape)\n documents=text_data[i:i+RemoveNoiseTweets.intervals]\n # documents.text = re.sub(r\"\\n\",\"\",documents.text)\n\n tfidf_vectorizer = TfidfVectorizer()\n tfidf_matrix = tfidf_vectorizer.fit_transform(documents.text)\n print(\"tfidf_matrix.shape: \", tfidf_matrix.shape)\n\n cos_sim = np.zeros((len(documents), len(documents)))\n print(\"##################\")\n arr = np.array([])\n max_cos = []\n indexes = []\n for index in np.arange(0, len(documents)):\n # print(\"index: \", index)\n cos_sim[index, :] = cosine_similarity(tfidf_matrix[index:index+1], tfidf_matrix)\n temp = [i for i, x in enumerate(cos_sim[index, :]) if x>0.7]\n temp = [a for a in temp if a > index]\n # print(index, \": \", temp,\"\\n\")\n if len(temp)>0:\n indexes.append(temp)\n if len(indexes)==0:\n return\n else:\n dup_recs = np.unique(np.concatenate(indexes))\n\n print(\"number of duplicate docs: \", len(dup_recs))\n # print(\"duplicate docs: \", indexes)\n print(\"duplicate docs: \", dup_recs)\n\n print(\"before dropping rows: \", temp_df.shape)\n temp_df = temp_df.drop(labels = dup_recs, axis=0)\n print(\"after dropping similar rows: \", temp_df.shape)\n\n temp_df = temp_df.groupby('id').filter(lambda x: len(x) < 50)\n temp_df = temp_df.loc[~temp_df['screen_name'].isin([\"Online_machine\", \"Mig0008\", \"altcoinuniverse\", \"BitcoinBidder\",\n \"skylarprentice1\", \"sophiepmmartin9\", \"BlockWatcher\",\n \"blockchainbot\", \"zFlashio\", \"Winkdexer\", \"BigBTCTracker\",\n \"michaeljamiw\", \"ldnblockchain\", \"cryptoknocks\", \"CapitalCreator_\",\n \"EurVirtualCoins\", \"r_topisto\", \"bitcoinnetwork3\", \"InvestAltcoins\",\n \"susansreviews\", \"cryptobuddha1\", \"CryptoCriterion\", \"12earnmoney\",\n \"suresh_p12\", \"laweddingmakeup\", \"Helg2012\", \"Monu80067960\", \"gaohz_\",\n \"BroMinercom\", \"FactomStockPr\", \"skylarprentice1\", \"free4coin\",\n \"help_me_plzplz_\", \"claytongarner5\", \"TeleMiner\", \"bitcoinkiosk_\",\n \"birnihigo18\", \"CryptoBuza\", \"so6i79\", \"play_game_girl\", \"quyendoattt\",\n \"coinok\", \"johnbitcoinss\", \"deuZige\", \"saddington\", \"prds71\",\n \"zomerushintoi\",\n \"hodlhodlnews\", \"WhaleStreetNews\", \"simulacra10\", \"coinlerinkrali\",\n \"PlanetZiggurat\", \"dotcomlandlords\", \"bot\", \"BCash_Market\",\n \"BitcoinMarket2\",\n \"bitcoinest\", \"mclynd\", \"Affiliyfuture1\", \"bitcoins_future\",\n \"WallStForsale\", \"Coin_Manager\",\"CryptoTopCharts\", \"stone22stone\",\n \"CryptoNewswire\",\"CoinWatcherBot\",\"btctickerbot\",\"ksantacr_\",\"realyoungjohn\",\n \"CashClamber\", \"techpearce\",\"mustcoins\", \"infocryptos\",\"bitcoinnewsfeed\",\n \"cryptinsight\", \"coffeegaram\"])]\n temp_df = temp_df.loc[~temp_df['text'].\n str.contains(\"Market rank is|1 bitcoin =|1 BTC Price:|FREE TOKEN|latest Cryptocurrency News|Free|bot |free bitcoin|#Earn #Bitcoin|Earn Bitcoin\")]\n print(\"shape of data after removing tweets with count > 50 and noise tweets: \", temp_df.shape)\n\n temp_df.to_csv(\"data/clean/subset\"+str(i)+\".csv\", sep=',', encoding='utf-8', index=False)\n\n filenames = []\n for (dirpath, dirnames, files) in os.walk(\"data/clean\"):\n filenames.extend(files)\n break\n if len(filenames)==0:\n return\n os.chdir(\"data/clean/\")\n combined_csv = pd.concat([pd.read_csv(f) for f in filenames])\n if \"index\" in combined_csv.columns:\n combined_csv.drop(['index'],axis=1,inplace=True)\n combined_csv.reset_index(inplace=True, drop=True)\n os.chdir(\"../../\")\n if self.is_testing_set:\n combined_csv.to_csv(\"data/clean_test.csv\", index=False)\n else:\n combined_csv.to_csv(\"data/clean_train.csv\", index=False)\n print(len(combined_csv))\n\n\n # os.chdir(\"data\")\n # filenames=[\"subset0.csv\",\"subset25000.csv\",\"subset50000.csv\",\"subset75000.csv\",\"subset100000.csv\",\"subset125000.csv\",\"subset150000.csv\",\"subset175000.csv\",\"subset200000.csv\",\"subset225000.csv\",\"subset250000.csv\",\"subset275000.csv\",\"\"]\n#from os import walk\n\n#filenames=[]\n#for(dirpath, dirnames,files) in walk(\"data/clean\"):\n# filenames.extend(filenames)\n# break\n#combined_csv = pd.concat([pd.read_csv(f) for f in filenames])\n#combined_csv.to_csv(\"data/combined_csv1.csv\", index=False)\n\n","sub_path":"twitter/remove_noise_tweets.py","file_name":"remove_noise_tweets.py","file_ext":"py","file_size_in_byte":7509,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"636980274","text":"from stock_models import Supplier, CurrentStock, db, AddStockForm\nfrom sqlalchemy import update\n\n\nclass EditStock:\n def __new__(self, id, p_name, quant, price, sup_name):\n\n old_stock = CurrentStock.query.filter_by(id=id).first()\n old_supplier = Supplier.query.filter_by(id=old_stock.supplier_id).first()\n new_supplier = Supplier.query.filter_by(company_name=sup_name).first()\n stmt = None\n if new_supplier is None:\n sup_update = update(Supplier).where(Supplier.id == old_stock.supplier_id).values(company_name=sup_name)\n db.session.execute(sup_update)\n st_update = update(CurrentStock).where(CurrentStock.id == old_stock.id).values(product_name=p_name,quantity=quant, price=price,supplier_id=old_supplier.id)\n else:\n st_update = update(CurrentStock).where(CurrentStock.id == old_stock.id).values(product_name=p_name,quantity=quant, price=price,supplier_id=new_supplier.id)\n\n db.session.execute(st_update)\n db.session.commit()\n\n\nclass ViewEditStock:\n def __new__(self, id, form):\n stock = CurrentStock.query.filter_by(id=id).first()\n supplier = Supplier.query.filter_by(id=stock.supplier_id).first()\n edit_form = AddStockForm(form)\n edit_form.product_name.data = stock.product_name\n edit_form.quantity.data = stock.quantity\n edit_form.price.data = stock.price\n edit_form.supplier_name.data = supplier.company_name\n\n return edit_form\n\n\n\n","sub_path":"warehouse-service/src/page_controllers/edit_stock.py","file_name":"edit_stock.py","file_ext":"py","file_size_in_byte":1497,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"354341680","text":"#! /usr/bin/env python\n# -*- coding:utf-8 -*-\n\n\"\"\"\nPIL库,Python Image Library 具有强大图像处理能力的第三方库\n\n图像->RGB值的二维向量\n\n用numpy的二维数组表示图像\n\n\n图像变换过程:\n读入图像,获得RGB值,修改后保存为新的文件\n\"\"\"\n\nfrom PIL import Image\nimport numpy as np\n\n\"\"\"\na = np.array(Image.open(\"image.jpg\"))\nprint(a.shape, a.dtype) # (457, 584, 3) uint8\n\nprint('-------RGB补值--------')\nb = [255, 255, 255] - a # 补值\nim = Image.fromarray(b.astype('uint8'))\nim.save(\"image2.jpg\")\n\nprint('--------灰度图--------')\n# convert:转为灰度值图片,三维数组将变为二维数组\nc = np.array(Image.open('image.jpg').convert('L'))\nim = Image.fromarray(c.astype('uint8'))\nim.save(\"image3.jpg\")\n\nprint('--------区间变化-------')\n\n\"\"\"\n\n\n# 图像的手绘效果\n\n# 梯度的重构:利用像素之间的梯度值和虚拟深度值对图像进行重构\n# 根据灰度的变化来模拟人类视觉的敏感程度\n\na = np.asarray(Image.open('image.jpg').convert('L')).astype('float')\n\ndepth = 10. # (0-100) ���设深度值为10 取值范围0-100\ngrad = np.gradient(a) # 取图像灰度的梯度值\ngrad_x, grad_y = grad # 分别取x和y横纵图像梯度值\ngrad_x = grad_x * depth / 100. # 根据深度调整x和y方向的梯度值\ngrad_y = grad_y * depth / 100.\nA = np.sqrt(grad_x ** 2 + grad_y ** 2 + 1.)\nuni_x = grad_x / A\nuni_y = grad_y / A\nuni_z = 1. / A\n\nvec_el = np.pi / 2.2 # 光源的俯视角度,弧度值\nvec_az = np.pi / 4. # 光源的方位角度,弧度值\ndx = np.cos(vec_el) * np.cos(vec_az) # 光源对x 轴的影响\ndy = np.cos(vec_el) * np.sin(vec_az) # 光源对y 轴的影响\ndz = np.sin(vec_el) # 光源对z 轴的影响\n\nb = 255 * (dx * uni_x + dy * uni_y + dz * uni_z) # 光源归一化\nb = b.clip(0, 255)\n\nim = Image.fromarray(b.astype('uint8')) # 重构图像\nim.save('imageq.jpg')","sub_path":"image2hand.py","file_name":"image2hand.py","file_ext":"py","file_size_in_byte":1910,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"257275602","text":"'''\nCreated on Apr 11, 2013\n@author: ricardo\nUse the library fpiclass\n'''\n\n#LN suggestion:\n#data=np.genfromtxt(path,dtype=np.float,skiprows=2,converters={14: lambda s: {'0':630.0,'1':632.8,'2':557.7}[s]})\n#zonal=data[:,1]\n#zonal=filtra(zonal)\n#plot(zonal)\n\n#import numpy\nimport os\nfrom library import getpath\nfrom datetime import datetime\nfrom dateutil import rrule\nfrom fpiclass_v4 import fpiData,fpiProcess\ndef main():\n\t\n\tbasepath='/data/01-FPIdata'\n\tstationIDs=['A3O','MRH','NZK']\n\tcolors=['red','blue','green']\n\tstart_day=1\n\tstart_month=10\n\tstart_year=2013\n\t\n\tstop_day=1\n\tstop_month=10\n\tstop_year=2013\n\t\n\tstart=datetime(start_year,start_month,start_day)\n\tstop=datetime(stop_year,stop_month,stop_day)\n\t\n\tlist_days_and_files = []\n\tfor day in rrule.rrule(rrule.DAILY,dtstart=start,until=stop):\n\t\ttmp={'day':day}\n\t\tfor stationID in stationIDs:\n\t\t\tZMpath=getpath(basepath,stationID,day,'zm')\n\t\t\tHorpath=getpath(basepath,stationID,day,'hor')\n\t\t\tif os.path.exists(ZMpath):\n\t\t\t\ttmp[stationID+'data']=fpiData(ZMpath,horizontals=Horpath)\n\t\t\t\ttmp[stationID+'color']=colors[stationIDs.index(stationID)]\n\t\tlist_days_and_files.append(tmp)\n\t\n\tfpi_data_1 = fpiProcess(stationIDs,list_days_and_files)\n\toutput_file_pdf = \"/home/fpi/Desktop/comparison2.pdf\"\n\tfpi_data_1.make_file_v2_zonal_meridional(output_file_pdf)\n\tfpi_data_1.make_file_v2_temperature()\n\nif __name__ == '__main__':\n\tmain()\n","sub_path":"plot_charts4.py","file_name":"plot_charts4.py","file_ext":"py","file_size_in_byte":1377,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"149312645","text":"'''\nDifference of sum of Even Odd Index numbers\nWrite a function which takes a list of positive integers and returns the difference of sum of numbers and even and odd index positions.\n\nYour function should take the list, sum all the numbers which are located at even index poistion of list and sum all the which are located at odd index poistion of list and subtract odd postion sum from even position sum.\n\nyou should name the function as difference_sum_even_odd_index and it should take a list.\n\nIndex of the list starts from 0.\n\nIf list has only one element, then sum of odd = 0\n\nInput\nlist of positive intergers\n\nOutput\nInteger\n\nExample\nInput:\n\n[1,2,3,4,5,6]\n\nOutput:\n\n-3\n'''\n# You should name your function as difference_sum_even_odd_index\n# It should take a list of integers\n# Return an integer\ndef difference_sum_even_odd_index(number):\n even=0\n odd=0\n for i in range(len(number)):\n if i%2==0:\n even=even+number[i]\n else:\n odd=odd+number[i]\n return (even-odd)\n\n# Do not change anything below this line\nif __name__ == \"__main__\":\n numbers = [int(i) for i in input().split(' ')]\n print(difference_sum_even_odd_index(numbers))","sub_path":"Difference of sum of Even Odd Index numbers.py","file_name":"Difference of sum of Even Odd Index numbers.py","file_ext":"py","file_size_in_byte":1184,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"533449849","text":"\"\"\"\n\n* File Name : SOCtools.py\n\n* Purpose : Lib for processing SOC data\n\n* Creation Date : 18-07-2017\n\n* Last Modified : Wed Dec 18 17:31:52 2019\n\n* Created By : Shijie Shu\n\n\"\"\"\n\nimport pandas as pd\nimport numpy as np\nimport math\n\ndef aggre_profden_to_profstock(nlev, dz, profile):\n\n \"\"\" Aggregate the SOC density profile into a stock profile. \n Input:\n nlev --- number of soil layers, scalar\n dz --- depth of each soil layer, nlev*1\n profile --- SOC profile in kgC/m3, nlev*nprof\n Output:\n val --- the SOC profile after aggregation, here is kgC/m2, nlev*nprof\n \"\"\"\n\n nprof = len(profile)\n val = np.zeros((nprof, nlev))\n for i in range(0, nprof):\n if(np.isnan(profile[i, 0])):\n val[i, :] = float(\"nan\")\n else:\n val[i, 0] = profile[i, 0]*dz[0]\n for j in range(1, nlev):\n if(np.isnan(profile[i, j])):\n break\n else:\n val[i, j] = val[i, j-1] + profile[i,j]*dz[j]\n return val\n\ndef aggre_profden_to_stock(endlev, dz, profile):\n\n \"\"\" Aggregate the SOC density profile into a total stock value\n Input:\n endlev --- number of soil layers to be aggregated\n dz --- depth of each soil layer (m), nlev*1\n profile --- SOC profile in kgC/m3, nlev*nprof\n Output:\n val --- The aggregated SOC stock, 1*nprof\n \"\"\"\n\n nprof = len(profile)\n val = np.zeros(nprof)\n for i in range(0, nprof):\n val[i] = profile[i, 0]*dz[0]\n for j in range(1, endlev):\n if(np.isnan(profile[i, j])):\n break\n else:\n val[i] = val[i] + profile[i,j]*dz[j]\n return val\n\ndef aggre_profden_to_stock_1m(zsoih, dz, profile):\n\n \"\"\" Aggregate the SOC density profile into a total stock value\n till 1m specifically for ISAM output\n Input:\n zsoih --- depth of the interface of each soil layer, (nlev+1) * 1\n dz --- depth of each soil layer (m), nlev*1\n profile --- SOC profile in kgC/m3, nlev*nprof\n Output:\n val --- The aggregated SOC stock, 1*nprof\n \"\"\"\n\n nprof = len(profile)\n val = np.zeros(nprof)\n for i in range(0, nprof):\n val[i] = profile[i, 0]*dz[0]\n for j in range(1, 7):\n if(np.isnan(profile[i, j])):\n break\n else:\n val[i] = val[i] + profile[i,j]*dz[j]\n if(~np.isnan(profile[i, 7])):\n val[i] = val[i] + profile[i, 7] * (1-zsoih[7])\n return val\n\ndef aggre_profden_to_stock_30cm(zsoih, dz, profile):\n\n \"\"\" Aggregate the SOC density profile into a total stock value\n till 1m specifically for ISAM output\n Input:\n zsoih --- depth of the interface of each soil layer, (nlev+1) * 1\n dz --- depth of each soil layer (m), nlev*1\n profile --- SOC profile in kgC/m3, nlev*nprof\n Output:\n val --- The aggregated SOC stock, 1*nprof\n \"\"\"\n\n nprof = len(profile)\n val = np.zeros(nprof)\n for i in range(0, nprof):\n val[i] = profile[i, 0]*dz[0]\n for j in range(1, 5):\n if(np.isnan(profile[i, j])):\n break\n else:\n val[i] = val[i] + profile[i,j]*dz[j]\n return val\n\n\n\ndef aggre_prof_den_to_stock(depth, zsoih, dz, profile):\n \"\"\" Aggregate the SOC density profile into a total stock value till the preset \n depth. Only accepts one profile as input at one time\n Input:\n depth --- the depth where SOC aggregate to (m)\n zsoih --- depth of the interface of each soil layer, nlev+1\n dz --- thickness of each soil layer (m), nlev\n profile --- SOC profile in kgC/m3, nlev\n Output:\n val --- The aggregated SOC stock (kgC/m2), scalar. Will be nan if dz is not \n deep enough.\n \"\"\"\n\n nlev = len(profile)\n val = 0.\n pt = 0\n # Point to the layer right below 30cm\n for j in range(0, nlev):\n if(zsoih[j] >= depth):\n pt = j\n break\n if(zsoih[nlev] < depth):\n val = float('nan')\n else:\n # Get the carbon amount\n for j in range(0, pt):\n if(zsoih[j+1] < depth):\n val = val + dz[j] * profile[j]\n else:\n val = val + (depth - zsoih[j]) * profile[j]\n\n return val\n\n\n","sub_path":"data/C14/C14processing/SOCtools.py","file_name":"SOCtools.py","file_ext":"py","file_size_in_byte":4301,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"345609261","text":"from django.conf.urls import url\nfrom django.contrib.auth.decorators import login_required\n\nfrom user.views import RegisterView, LoginView, UserInfoView, UserOrderView, AddressView, LogoutView\n\nurlpatterns = [\n url(r'^register$', RegisterView.as_view(), name='register'),\n url(r'^login$', LoginView.as_view(), name='login'),\n url(r'^logout$', LogoutView.as_view(), name='logout'),\n url(r'^$', UserInfoView.as_view(), name='user'),\n url(r'^order/(?P\\d+)$', UserOrderView.as_view(), name='order'),\n url(r'^address$', AddressView.as_view(), name='address'),\n\n\n]\n","sub_path":"user/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":583,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"11641020","text":"from gtts import gTTS\n#pip install gtts\nfrom playsound import playsound\n#pip install playsound\n\naudio = 'speech.mp3'\nlanguage = 'en'\n\nsp = gTTS(text=\"My name is Abhinav raj\", lang=language,slow=False)\n\nsp.save(audio)\nplaysound(audio)\n\n\n","sub_path":"texttoaudio.py","file_name":"texttoaudio.py","file_ext":"py","file_size_in_byte":236,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"167004734","text":"from django.urls import path, re_path\nfrom .views import PostList, PostDetailView, PostCreate, PostUpdate, PostDelete\n\napp_name = 'posts'\n\nurlpatterns = [\n path('', PostList.as_view(), name='all'),\n path('create/', PostCreate.as_view(), name='create'),\n re_path('(?P\\d+)/update/', PostUpdate.as_view(), name='update'),\n re_path('(?P\\d+)/delete/', PostDelete.as_view(), name='delete'),\n re_path('(?P\\d+)/', PostDetailView.as_view(), name='detail'),\n]\n","sub_path":"blog/posts/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":477,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"298311964","text":"# Copyright 2016 Arie Bregman\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.\nfrom distutils.version import StrictVersion\nimport operator as py_operator\n\n\nclass Requirement(object):\n\n def __init__(self, name, specs):\n self.name = name\n self.specs = specs\n\n def meet_the_specs(self, version):\n \"\"\"Returns True if the given version meets the specs of the Requirement\n\n instance.\n \"\"\"\n\n op_map = {\n '==': 'eq', '=': 'eq', 'eq': 'eq',\n '<': 'lt', 'lt': 'lt',\n '<=': 'le', 'le': 'le',\n '>': 'gt', 'gt': 'gt',\n '>=': 'ge', 'ge': 'ge',\n '!=': 'ne', '<>': 'ne', 'ne': 'ne'\n }\n\n for spec in self.specs:\n operator = op_map[spec[0]]\n cmp_method = getattr(py_operator, operator)\n\n if not cmp_method(StrictVersion(str(version)),\n StrictVersion(str(spec[1]))):\n return False\n return True\n","sub_path":"reqwise/requirement.py","file_name":"requirement.py","file_ext":"py","file_size_in_byte":1574,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"149162790","text":"import os\nfrom dotenv import load_dotenv\nimport tweepy as tw\nimport re\nimport string\nimport logging\nimport nltk\nimport pandas as pd\nfrom textblob import TextBlob\nfrom sklearn.cluster import DBSCAN\nfrom sklearn.feature_extraction.text import TfidfVectorizer\n\nload_dotenv()\nlogging.basicConfig(format='%(process)d-%(levelname)s-%(message)s')\n\n\nclass GetData:\n @staticmethod\n def stream(api, find_word, df):\n \"\"\"Steam tweets containing the specified word\"\"\"\n query = (\n find_word + \" -filter:retweet\" + \" -filter:media\" + \" -filter:links\"\n )\n i = 0\n limit = 1000\n tweet_count = 100\n\n for tweet in tw.Cursor(\n api.search, q=query, count=tweet_count, lang=\"en\", result_type=\"mixed\"\n ).items():\n df.loc[i, \"id\"] = tweet.id\n df.loc[i, \"tweet\"] = tweet.text\n df.loc[i, \"popularity\"] = tweet.favorite_count + tweet.retweet_count\n i += 1\n\n if i > limit:\n break\n else:\n pass\n\n\nclass CleanData:\n @staticmethod\n def remove_punctuation(text):\n \"\"\"Remove links and other punctuation from text\"\"\"\n text = text.replace('\\n', '')\n text = text.replace('\\t', '')\n re.sub(r'http\\S+', '', text) # removes links\n\n translator = str.maketrans('', '', string.punctuation)\n return text.lower().translate(translator)\n\n @staticmethod\n def de_emojify(text):\n \"\"\"Remove emoticons from given text\"\"\"\n regrex_pattern = re.compile(pattern=\"[\"\n u\"\\U0001F600-\\U0001F64F\" # emoticons\n u\"\\U0001F300-\\U0001F5FF\" # symbols & pictographs\n u\"\\U0001F680-\\U0001F6FF\" # transport & map symbols\n u\"\\U0001F1E0-\\U0001F1FF\" # flags (iOS)\n u\"\\U00002500-\\U00002BEF\" # chinese char\n u\"\\U00002702-\\U000027B0\"\n u\"\\U00002702-\\U000027B0\"\n u\"\\U000024C2-\\U0001F251\"\n u\"\\U0001f926-\\U0001f937\"\n u\"\\U00010000-\\U0010ffff\"\n u\"\\u2640-\\u2642\"\n u\"\\u2600-\\u2B55\"\n u\"\\u200d\"\n u\"\\u23cf\"\n u\"\\u23e9\"\n u\"\\u231a\"\n u\"\\ufe0f\" # dingbats\n u\"\\u3030\"\n \"]+\", flags=re.UNICODE)\n return regrex_pattern.sub(r'', text)\n\n\nclass ProcessData:\n ps = nltk.PorterStemmer()\n\n @staticmethod\n def tokenize(text):\n \"\"\"Stem and tokenizes input text, used as custom tokenizer in tfi-df vectorization\"\"\"\n tokens = nltk.word_tokenize(text)\n stems = []\n for item in tokens:\n stems.append(ProcessData.ps.stem(item))\n return stems\n\n @staticmethod\n def analyse_sentiment(tweet):\n \"\"\"Analyses the sentiment of the given tweet\"\"\"\n analysis = TextBlob(tweet)\n sentiment = analysis.sentiment.polarity\n if sentiment > 0:\n return \"positive\"\n elif sentiment == 0:\n return \"neutral\"\n else:\n return \"negative\"\n\n @staticmethod\n def cluster(esp, df):\n \"\"\"Clusters data using DBSCAN with a specified esp value\"\"\"\n df[\"tweet_clean\"] = df[\"tweet\"].apply(lambda y: CleanData.remove_punctuation(y))\n df[\"tweet_clean\"] = df[\"tweet_clean\"].apply(lambda y: CleanData.de_emojify(y))\n\n vectorizer = TfidfVectorizer(tokenizer=ProcessData.tokenize, stop_words='english', min_df=1)\n x = vectorizer.fit_transform(df.loc[:, \"tweet_clean\"])\n\n db = DBSCAN(esp, min_samples=20).fit(x)\n\n df[\"clusters\"] = db.labels_\n logging.info(f\"Number of unique clusters generated: {df.clusters.nunique()}\")\n\n\nclass Results:\n def __init__(self, df):\n \"\"\"Initialize final results of the analysis\"\"\"\n self.clusters_count = df.clusters.value_counts()\n self.df_results = df.groupby([\"clusters\"]).max().reset_index()\n self.df_results[\"sentiment\"] = self.df_results[\"tweet_clean\"].apply(lambda y: ProcessData.analyse_sentiment(y))\n\n logging.info(f\"Number of tweets per cluster: \\n{self.clusters_count}\")\n logging.info(f\"Top cluster tweets: \\n{self.df_results.to_string()}\")\n\n\ndef authorise_api():\n \"\"\"Authorise access to twitter API and return the api handler\"\"\"\n consumer_key = os.getenv(\"CONSUMER_KEY\")\n consumer_key_secret = os.getenv(\"CONSUMER_KEY_SECRET\")\n access_token = os.getenv(\"ACCESS_TOKEN\")\n access_token_secret = os.getenv(\"ACCESS_TOKEN_SECRET\")\n\n auth = tw.OAuthHandler(consumer_key, consumer_key_secret)\n auth.set_access_token(access_token, access_token_secret)\n api = tw.API(auth, wait_on_rate_limit=True)\n\n return api\n\n\ndef get_top_trends(api):\n \"\"\"Returns a list of top trends at the specified location\"\"\"\n # WOEID = 1 for global trending\n latitude = os.getenv(\"LAT\")\n longitude = os.getenv(\"LNG\")\n\n locations = api.trends_closest(latitude, longitude)\n woeid = locations[0][\"woeid\"]\n\n trends = api.trends_place(woeid)\n trends_dict = trends[0][\"trends\"]\n\n return [trends_dict[0]]\n\n\ndef main():\n api = authorise_api()\n top_trend = get_top_trends(api)\n\n df = pd.DataFrame(columns=[\"id\", \"tweet\", \"popularity\"])\n GetData.stream(api, top_trend[0][\"name\"], df)\n\n esp = 1.29\n ProcessData.cluster(esp, df)\n\n Results(df)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"scripts/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5917,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"20524535","text":"import random\n\nimport numpy as np\n\nfrom mpi4py import MPI\nfrom trueskill import Rating, rate_1vs1\n\ndef master(agents, stopping_sigma = 1, pick_max_sigma = False):\n comm = MPI.COMM_WORLD\n myid = comm.Get_rank()\n num_workers = comm.Get_size() - 1\n num_agents = len(agents)\n\n agent_ratings = [ [Rating(), i] for i in range(num_agents)]\n agent_ratings_by_sigma = sorted(agent_ratings, key = lambda val: val[0].sigma, reverse=True)\n\n # first we have to broadcast the agents to the workers\n comm.bcast(agents, root=0)\n\n # give every worker its initial assignment\n for i in range(num_workers):\n agentid0, agentid1 = np.random.choice(num_agents, 2, replace=False)\n comm.send((agentid0, agentid1), i + 1)\n\n games_played = 0\n while True:\n if pick_max_sigma:\n if agent_ratings_by_sigma[0][0].sigma < stopping_sigma:\n break\n elif games_played % (10 * num_agents) == 0:\n max_sigma = max([agent_ratings[i][0].sigma for i in range(num_agents)])\n if max_sigma < stopping_sigma:\n break\n\n # get the next message (can be from any worker)\n send_id, agentid0, agentid1, winner = comm.recv()\n\n if winner == 0:\n agent_ratings[agentid0][0], agent_ratings[agentid1][0] = rate_1vs1(agent_ratings[agentid0][0], agent_ratings[agentid1][0])\n elif winner == 1:\n agent_ratings[agentid1][0], agent_ratings[agentid0][0] = rate_1vs1(agent_ratings[agentid1][0], agent_ratings[agentid0][0])\n else: # draw\n agent_ratings[agentid1][0], agent_ratings[agentid0][0] = rate_1vs1(agent_ratings[agentid1][0], agent_ratings[agentid0][0], drawn=True)\n\n # send new work back to the same worker\n # don't play an agent against itself\n if pick_max_sigma:\n # a heap might be better, or a heap plus a sortedlist if we want to\n # pick the max sigma and then choose an opponent with a similar mu\n # using this implementation to experiment with how many fewer games\n # better selection requires.\n # Note that this sort is not likely to bad as bad as it first appears\n # as long as the number of agents remains < few hundred\n # The list will be almost sorted, so timsort will be close to one pass\n # The list should also stay in L2.\n agent_ratings_by_sigma.sort(key = lambda val: val[0].sigma, reverse=True)\n agentid0 = agent_ratings_by_sigma[0][1]\n agentid1 = agent_ratings_by_sigma[random.randint(1, num_agents-1)][1]\n else:\n agentid0, agentid1 = np.random.choice(num_agents, 2, replace=False)\n\n comm.send((agentid0, agentid1), send_id)\n\n games_played += 1\n\n # tell the workers to finish\n for i in range(num_workers):\n send_id, _, _, _ = comm.recv()\n\n comm.send(False, send_id)\n\n print('games played: ', games_played)\n for i in range(num_agents):\n print(agent_ratings[i])\n","sub_path":"tournament/master.py","file_name":"master.py","file_ext":"py","file_size_in_byte":3020,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"247930747","text":"#!/usr/bin/env python\n# -*- coding: UTF-8 -*-\n\n\"\"\"\nCalculation of synonymous substitutions (Ks).\n\"\"\"\n\nimport sys\nimport os\nimport os.path as op\nimport csv\nimport logging\n\nfrom math import log, sqrt, pi, exp\nfrom itertools import product, combinations\nfrom collections import namedtuple\nfrom optparse import OptionParser\nfrom subprocess import Popen\n\nimport numpy as np\nfrom Bio import SeqIO\nfrom Bio import AlignIO\nfrom Bio.Align.Applications import ClustalwCommandline\n\nfrom jcvi.formats.base import must_open\nfrom jcvi.apps.command import getpath, partial\nfrom jcvi.apps.base import ActionDispatcher, debug, mkdir, set_outfile, sh\ndebug()\n\n\nCLUSTALW_BIN = partial(getpath, name=\"CLUSTALW2\")\nPAL2NAL_BIN = partial(getpath, name=\"PAL2NAL\")\nPAML_BIN = partial(getpath, name=\"PAML\")\n\n\nclass AbstractCommandline:\n\n def run(self):\n r = Popen(str(self), shell=True)\n return r.communicate()\n\n\nclass YnCommandline(AbstractCommandline):\n \"\"\"Little commandline for yn00.\n \"\"\"\n def __init__(self, ctl_file, command=PAML_BIN(\"yn00\")):\n self.ctl_file = ctl_file\n self.parameters = []\n self.command = command\n\n def __str__(self):\n return self.command + \" %s >/dev/null\" % self.ctl_file\n\n\nclass MrTransCommandline(AbstractCommandline):\n \"\"\"Simple commandline faker.\n \"\"\"\n def __init__(self, prot_align_file, nuc_file, output_file,\n command=PAL2NAL_BIN(\"pal2nal.pl\")):\n self.prot_align_file = prot_align_file\n self.nuc_file = nuc_file\n self.output_file = output_file\n self.command = command\n\n self.parameters = []\n\n def __str__(self):\n return self.command + \" %s %s -output paml> %s\" % (self.prot_align_file, self.nuc_file, self.output_file)\n\n\ndef main():\n\n actions = (\n ('fromgroups', 'flatten the gene families into pairs'),\n ('prepare', 'prepare pairs of sequences'),\n ('calc', 'calculate Ks between pairs of sequences'),\n ('report', 'generate a distribution of Ks values'),\n ('gc3', 'filter the Ks results to remove high GC3 genes'),\n )\n p = ActionDispatcher(actions)\n p.dispatch(globals())\n\n\ndef get_GC3(cdsfile):\n from jcvi.formats.fasta import Fasta\n\n f = Fasta(cdsfile, lazy=True)\n GC3 = {}\n for name, rec in f.iteritems_ordered():\n positions = rec.seq[2::3].upper()\n gc_counts = sum(1 for x in positions if x in \"GC\")\n gc_ratio = gc_counts * 1. / len(positions)\n GC3[name] = gc_ratio\n\n return GC3\n\n\ndef gc3(args):\n \"\"\"\n %prog gc3 ksfile cdsfile > newksfile\n\n Filter the Ks results to remove high GC3 genes. High GC3 genes are\n problematic in Ks calculation - see Tang et al. 2010 PNAS. Specifically, the\n two calculation methods produce drastically different results for these\n pairs. Therefore we advise to remoeve these high GC3 genes. This is often\n the case for studying cereal genes.\n \"\"\"\n import csv\n\n p = OptionParser(gc3.__doc__)\n opts, args = p.parse_args(args)\n\n if len(args) != 2:\n sys.exit(not p.print_help())\n\n ks_file, cdsfile = args\n header, data = read_ks_file(ks_file)\n noriginals = len(data)\n GC3 = get_GC3(cdsfile)\n\n writer = csv.writer(sys.stdout)\n writer.writerow(header)\n nlines = 0\n cutoff = .75\n for d in data:\n a, b = d.pair.split(\";\")\n aratio, bratio = GC3[a], GC3[b]\n if (aratio + bratio) / 2 > cutoff:\n continue\n writer.writerow(d)\n nlines += 1\n logging.debug(\"{0} records written (from {1}).\".format(nlines, noriginals))\n\n\ndef extract_pairs(abed, bbed, groups):\n \"\"\"\n Called by fromgroups(), extract pairs specific to a pair of species.\n \"\"\"\n agenome = op.basename(abed.filename).split(\".\")[0]\n bgenome = op.basename(bbed.filename).split(\".\")[0]\n aorder = abed.order\n border = bbed.order\n pairsfile = \"{0}.{1}.pairs\".format(agenome, bgenome)\n fw = open(pairsfile, \"w\")\n\n is_self = abed.filename == bbed.filename\n npairs = 0\n for group in groups:\n iter = combinations(group, 2) if is_self \\\n else product(group, repeat=2)\n\n for a, b in iter:\n if a not in aorder or b not in border:\n continue\n\n print >> fw, \"\\t\".join((a, b))\n npairs += 1\n\n logging.debug(\"File `{0}` written with {1} pairs.\".format(pairsfile, npairs))\n\n\ndef fromgroups(args):\n \"\"\"\n %prog fromgroups groupsfile a.bed b.bed ...\n\n Flatten the gene familes into pairs, the groupsfile is a file with each line\n containing the members, separated by comma. The commands also require\n several bed files in order to sort the pairs into different piles (e.g.\n pairs of species in comparison.\n \"\"\"\n from jcvi.formats.bed import Bed\n\n p = OptionParser(fromgroups.__doc__)\n opts, args = p.parse_args(args)\n\n if len(args) < 2:\n sys.exit(not p.print_help())\n\n groupsfile = args[0]\n bedfiles = args[1:]\n beds = [Bed(x) for x in bedfiles]\n fp = open(groupsfile)\n groups = [row.strip().split(\",\") for row in fp]\n for b1, b2 in product(beds, repeat=2):\n extract_pairs(b1, b2, groups)\n\n\ndef prepare(args):\n \"\"\"\n %prog prepare pairsfile cdsfile > paired.cds.fasta\n\n Pick sequences from cdsfile to form pairs, ready to be calculated. The\n pairsfile can be generated from formats.blast.cscore(). The first two\n columns contain the pair.\n \"\"\"\n from jcvi.formats.fasta import Fasta, SeqIO\n\n p = OptionParser(prepare.__doc__)\n\n opts, args = p.parse_args(args)\n\n if len(args) != 2:\n sys.exit(not p.print_help())\n\n pairsfile, cdsfile = args\n\n f = Fasta(cdsfile)\n fp = open(pairsfile)\n fw = sys.stdout\n for row in fp:\n a, b = row.split()[:2]\n arec = f[a]\n brec = f[b]\n SeqIO.write((arec, brec), fw, \"fasta\")\n\n\ndef calc(args):\n \"\"\"\n %prog calc [prot.fasta] cds.fasta > out.ks\n\n Protein file is optional. If only one file is given, it is assumed to\n be CDS sequences with correct frame (frame 0). Results will be written to\n stdout. Both protein file and nucleotide file are assumed to be Fasta format,\n with adjacent records as the pairs to compare.\n\n Author: Haibao Tang , Brad Chapman\n Calculate synonymous mutation rates for gene pairs\n\n This does the following:\n 1. Fetches a protein pair.\n 2. Aligns the protein pair with clustalw\n 3. Convert the output to Fasta format.\n 4. Use this alignment info to align gene sequences using PAL2NAL\n 5. Run PAML yn00 to calculate synonymous mutation rates.\n \"\"\"\n p = OptionParser(calc.__doc__)\n set_outfile(p)\n\n opts, args = p.parse_args(args)\n\n if len(args) == 1:\n protein_file, dna_file = None, args[0]\n elif len(args) == 2:\n protein_file, dna_file = args\n else:\n print >>sys.stderr, \"Incorrect arguments\"\n sys.exit(not p.print_help())\n\n output_h = must_open(opts.outfile, \"w\")\n output_h.write(\"name,dS-yn,dN-yn,dS-ng,dN-ng\\n\")\n work_dir = op.join(os.getcwd(), \"syn_analysis\")\n mkdir(work_dir)\n\n if not protein_file:\n protein_file = translate_dna(dna_file)\n\n prot_iterator = SeqIO.parse(open(protein_file), \"fasta\")\n dna_iterator = SeqIO.parse(open(dna_file), \"fasta\")\n for p_rec_1, p_rec_2, n_rec_1, n_rec_2 in \\\n zip(prot_iterator, prot_iterator, dna_iterator, dna_iterator):\n\n print >>sys.stderr, \"--------\", p_rec_1.name, p_rec_2.name\n align_fasta = clustal_align_protein(p_rec_1, p_rec_2, work_dir)\n mrtrans_fasta = run_mrtrans(align_fasta, n_rec_1, n_rec_2, work_dir)\n if mrtrans_fasta:\n ds_subs_yn, dn_subs_yn, ds_subs_ng, dn_subs_ng = \\\n find_synonymous(mrtrans_fasta, work_dir)\n if ds_subs_yn is not None:\n pair_name = \"%s;%s\" % (p_rec_1.name, p_rec_2.name)\n output_h.write(\"%s\\n\" % (\",\".join(str(x) for x in (pair_name,\n ds_subs_yn, dn_subs_yn, ds_subs_ng, dn_subs_ng))))\n output_h.flush()\n\n # Clean-up\n sh(\"rm -rf 2YN.t 2YN.dN 2YN.dS rst rub rst1 syn_analysis\")\n\n\ndef translate_dna(dna_file):\n '''\n Translate the seqs in dna_file and produce a protein_file\n '''\n protein_file = dna_file + \".pep\"\n translated = []\n for rec in SeqIO.parse(open(dna_file), \"fasta\"):\n rec.seq = rec.seq.translate()\n translated.append(rec)\n\n protein_h = open(protein_file, \"w\")\n SeqIO.write(translated, protein_h, \"fasta\")\n\n print >>sys.stderr, \"%d records written to %s\" % (len(translated),\n protein_file)\n return protein_file\n\n\ndef find_synonymous(input_file, work_dir):\n \"\"\"Run yn00 to find the synonymous subsitution rate for the alignment.\n \"\"\"\n # create the .ctl file\n ctl_file = op.join(work_dir, \"yn-input.ctl\")\n output_file = op.join(work_dir, \"nuc-subs.yn\")\n ctl_h = open(ctl_file, \"w\")\n ctl_h.write(\"seqfile = %s\\noutfile = %s\\nverbose = 0\\n\" %\n (input_file, output_file))\n ctl_h.write(\"icode = 0\\nweighting = 0\\ncommonf3x4 = 0\\n\")\n ctl_h.close()\n\n cl = YnCommandline(ctl_file)\n print >>sys.stderr, \"\\tyn00:\", cl\n r, e = cl.run()\n ds_value_yn = None\n ds_value_ng = None\n dn_value_yn = None\n dn_value_ng = None\n\n # Nei-Gojobori\n output_h = open(output_file)\n row = output_h.readline()\n while row:\n if row.find(\"Nei & Gojobori\") >=0:\n for x in xrange(5):\n row = output_h.next()\n dn_value_ng, ds_value_ng = row.split('(')[1].split(')')[0].split()\n break\n row = output_h.readline()\n output_h.close()\n\n # Yang\n output_h = open(output_file)\n for line in output_h:\n if line.find(\"+-\") >= 0 and line.find(\"dS\") == -1:\n parts = line.split(\" +-\")\n ds_value_yn = extract_subs_value(parts[1])\n dn_value_yn = extract_subs_value(parts[0])\n\n if ds_value_yn is None or ds_value_ng is None:\n h = open(output_file)\n print >>sys.stderr, \"yn00 didn't work: \\n%s\" % h.read()\n\n return ds_value_yn, dn_value_yn, ds_value_ng, dn_value_ng\n\n\ndef extract_subs_value(text):\n \"\"\"Extract a subsitution value from a line of text.\n\n This is just a friendly function to grab a float value for Ks and Kn\n values from the junk I get from the last line of the yn00 file.\n\n Line:\n 2 1 52.7 193.3 2.0452 0.8979 0.0193 0.0573 +- 0.0177\n 2.9732 +- 3.2002\n\n Parts:\n [' 2 1 52.7 193.3 2.0452 0.8979 0.0193 0.0573',\n ' 0.0177 2.9732', ' 3.2002\\n']\n\n So we want 0.0573 for Kn and 2.9732 for Ks.\n \"\"\"\n parts = text.split()\n value = float(parts[-1])\n\n return value\n\n\ndef run_mrtrans(align_fasta, rec_1, rec_2, work_dir):\n \"\"\"Align two nucleotide sequences with mrtrans and the protein alignment.\n \"\"\"\n align_file = op.join(work_dir, \"prot-align.fasta\")\n nuc_file = op.join(work_dir, \"nuc.fasta\")\n output_file = op.join(work_dir, \"nuc-align.mrtrans\")\n\n # make the protein alignment file\n align_h = open(align_file, \"w\")\n align_h.write(str(align_fasta))\n align_h.close()\n # make the nucleotide file\n SeqIO.write((rec_1, rec_2), file(nuc_file, \"w\"), \"fasta\")\n\n # run the program\n cl = MrTransCommandline(align_file, nuc_file, output_file)\n r, e = cl.run()\n if e is None:\n print >>sys.stderr, \"\\tpal2nal:\", cl\n return output_file\n elif e.read().find(\"could not translate\") >= 0:\n print >>sys.stderr, \"***pal2nal could not translate\"\n return None\n\n\ndef clustal_align_protein(rec_1, rec_2, work_dir):\n \"\"\"Align the two given proteins with clustalw.\n \"\"\"\n fasta_file = op.join(work_dir, \"prot-start.fasta\")\n align_file = op.join(work_dir, \"prot.aln\")\n SeqIO.write((rec_1, rec_2), file(fasta_file, \"w\"), \"fasta\")\n\n clustal_cl = ClustalwCommandline(CLUSTALW_BIN(\"clustalw2\"),\n infile=fasta_file, outfile=align_file, outorder=\"INPUT\",\n type=\"PROTEIN\")\n stdout, stderr = clustal_cl()\n\n aln_file = file(clustal_cl.outfile)\n alignment = AlignIO.read(aln_file, \"clustal\")\n print >>sys.stderr, \"\\tDoing clustalw alignment: %s\" % clustal_cl\n return alignment.format(\"fasta\")\n\n\nfields = \"pair yn_ks yn_ka ng_ks ng_ka\"\ndescriptions = {\n 'pair': 'Gene pair',\n 'yn_ks': 'Yang-Nielson method of Ks estimate',\n 'yn_ka': 'Yang-Nielson method of Ka estimate',\n 'ng_ks': 'Nei-Gojobori method of Ks estimate',\n 'ng_ka': 'Nei-Gojobori method of Ka estimate'}\n\nKsLine = namedtuple(\"KsLine\", fields)\n\n\ndef read_ks_file(ks_file):\n reader = csv.reader(open(ks_file, \"rb\"))\n header = reader.next() # header\n data = []\n for row in reader:\n for i, a in enumerate(row):\n if i==0: continue\n row[i] = float(row[i])\n data.append(KsLine._make(row))\n\n logging.debug('File `{0}` contains a total of {1} gene pairs'.\\\n format(ks_file, len(data)))\n\n return header, data\n\n\ndef my_hist(ax, l, interval, max_r, color='g'):\n if not l:\n return\n\n from pylab import poly_between\n\n n, p = [], []\n total_len = len(l)\n for i in np.arange(0, max_r, interval):\n xmin, xmax = i - .5 * interval, i + .5 * interval\n nx = [x for x in l if xmin <= x < xmax]\n n.append(i)\n p.append(len(nx) * 100. / total_len)\n\n xs, ys = poly_between(n, 0, p)\n return ax.fill(xs, ys, fc=color, alpha=.3)\n\n\ndef lognormpdf(bins, mu, sigma):\n return np.exp(-(np.log(bins) - mu) ** 2 / (2 * sigma ** 2)) / \\\n (bins * sigma * sqrt(2 * pi))\n\n\ndef lognormpdf_mix(bins, probs, mus, sigmas, interval=.1):\n y = 0\n for prob, mu, sigma in zip(probs, mus, sigmas):\n y += prob * lognormpdf(bins, mu, sigma)\n y *= 100 * interval\n return y\n\n\ndef get_mixture(data, components):\n \"\"\"\n probs = [.476, .509]\n mus = [.69069, -.15038]\n variances = [.468982e-1, .959052e-1]\n \"\"\"\n from jcvi.apps.base import popen\n\n probs, mus, sigmas = [], [], []\n fw = must_open(\"tmp\", \"w\")\n log_data = [log(x) for x in data if x > .05]\n data = \"\\n\".join([\"%.4f\" % x for x in log_data]).replace(\"inf\\n\", \"\")\n fw.write(data)\n fw.close()\n\n cmd = \"gmm-bic {0} {1} {2}\".format(components, len(log_data), fw.name)\n pipe = popen(cmd)\n\n for row in pipe:\n if row[0] != '#':\n continue\n\n atoms = row.split(\",\")\n a, b, c = atoms[1:4]\n a = float(a)\n b = float(b)\n c = float(c)\n\n mus.append(a)\n sigmas.append(b)\n probs.append(c)\n\n os.remove(fw.name)\n return probs, mus, sigmas\n\n\ndef plot_ks_dist(ax, data, interval, components, ks_max, color='r'):\n from jcvi.graphics.base import _\n\n line, = my_hist(ax, data, interval, ks_max, color=color)\n logging.debug(\"Total {0} pairs after filtering.\".format(len(data)))\n\n probs, mus, variances = get_mixture(data, components)\n\n bins = np.arange(0.001, ks_max, .001)\n y = lognormpdf_mix(bins, probs, mus, variances, interval)\n\n line_mixture, = ax.plot(bins, y, ':', color=color, lw=3)\n for i in xrange(components):\n peak_val = exp(mus[i])\n mixline = lognormpdf_mix(peak_val, probs, mus, variances, interval)\n ax.text(peak_val, mixline, _(\"Ks=%.2f\" % peak_val), \\\n color=\"w\", size=10, bbox=dict(ec='w',fc=color, alpha=.6, boxstyle='round'))\n\n return line, line_mixture\n\n\ndef report(args):\n '''\n %prog report ksfile\n\n generate a report given a Ks result file (as produced by synonymous_calc.py).\n describe the median Ks, Ka values, as well as the distribution in stem-leaf plot\n '''\n from jcvi.graphics.histogram import stem_leaf_plot\n\n p = OptionParser(report.__doc__)\n p.add_option(\"--vmax\", default=2., type=\"float\",\n help=\"Maximum value, inclusive [default: %default]\")\n p.add_option(\"--bins\", default=20, type=\"int\",\n help=\"Number of bins to plot in the histogram [default: %default]\")\n p.add_option(\"--pdf\", default=False, action=\"store_true\",\n help=\"Generate graphic output for the histogram [default: %default]\")\n p.add_option(\"--components\", default=1, type=\"int\",\n help=\"Number of components to decompose peaks [default: %default]\")\n opts, args = p.parse_args(args)\n\n if len(args) != 1:\n sys.exit(not p.print_help())\n\n ks_file, = args\n header, data = read_ks_file(ks_file)\n ks_max = opts.vmax\n\n for f in fields.split()[1:]:\n columndata = [getattr(x, f) for x in data]\n title = \"{0}: {1:.2f}\".format(descriptions[f], np.median(columndata))\n title += \" ({0:.2f} +/- {1:.2f})\".\\\n format(np.mean(columndata), np.std(columndata))\n ks = (\"ks\" in f)\n if not ks:\n continue\n\n bins = (0, ks_max, opts.bins) if ks else (0, .6, 10)\n digit = 1 if ks else 2\n stem_leaf_plot(columndata, *bins, digit=digit, title=title)\n\n if not opts.pdf:\n return\n\n from jcvi.graphics.base import mpl, _, tex_formatter, tex_1digit_formatter\n from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas\n\n fig = mpl.figure.Figure(figsize=(5, 5))\n\n canvas = FigureCanvas(fig)\n ax = fig.add_axes([.12, .1, .8, .8])\n components = opts.components\n data = [x.ng_ks for x in data]\n\n interval = ks_max / opts.bins\n line, line_mixture = plot_ks_dist(ax, data, interval, components, ks_max, color='r')\n leg = ax.legend((line, line_mixture), (\"Ks\", \"Ks (fitted)\"),\n shadow=True, fancybox=True, prop={\"size\": 10})\n leg.get_frame().set_alpha(.5)\n\n ax.set_xlim((0, ks_max))\n ax.set_title(_('Ks distribution'), fontweight=\"bold\")\n ax.set_xlabel(_('Synonymous substitutions per site (Ks)'))\n ax.set_ylabel(_('Percentage of gene pairs'))\n\n ax.xaxis.set_major_formatter(tex_1digit_formatter)\n ax.yaxis.set_major_formatter(tex_formatter)\n\n image_name = \"Ks_plot.pdf\"\n canvas.print_figure(image_name, dpi=300)\n logging.debug(\"Print image to `{0}`.\".format(image_name))\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"apps/ks.py","file_name":"ks.py","file_ext":"py","file_size_in_byte":18183,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"235726194","text":"from .helper import rgb2gray, rgb2hls\nimport cv2\nimport numpy as np\n\nK_SIZE = 3\nABS_THRESH = (64, 128)\nMAG_K_SIZE = 3\nMAG_THRESH = (30, 100)\nDIR_K_SIZE = 15\nDIR_THRESH = (0.7, 1.3)\nSAT_THRESH = (90, 255)\nLIT_THRESH = (30, 255)\n\n\ndef thresholding(img, thresh, conversion):\n single_channel = conversion(img)\n binary_output = np.zeros_like(single_channel)\n binary_output[(single_channel >= thresh[0]) & (single_channel <= thresh[1])] = 1\n return binary_output\n\n\ndef absolute_sobel_thresholding(img, orient='x', sobel_kernel=3, abs_thresh=(0, 255)):\n def sobel(image):\n gray = rgb2gray(image)\n x = 1 if orient == 'x' else 0\n return np.abs(cv2.Sobel(gray, cv2.CV_64F, x, 1 - x, ksize=sobel_kernel))\n\n return thresholding(img, abs_thresh, sobel)\n\n\ndef magnitude_thresholding(img, sobel_kernel=3, mag_thresh=(0, 255)):\n def absolute_sobel(image):\n gray = rgb2gray(image)\n sobel_x = cv2.Sobel(gray, cv2.CV_64F, 1, 0, ksize=sobel_kernel)\n sobel_y = cv2.Sobel(gray, cv2.CV_64F, 0, 1, ksize=sobel_kernel)\n abs_sobel_xy = np.abs(np.sqrt(np.square(sobel_x) + np.square(sobel_y)))\n return np.uint8(255 * abs_sobel_xy / np.max(abs_sobel_xy))\n\n return thresholding(img, mag_thresh, absolute_sobel)\n\n\ndef direction_thresholding(img, sobel_kernel=3, dir_thresh=(0, np.pi / 2)):\n def grad_dir(image):\n gray = rgb2gray(image)\n sobel_x = cv2.Sobel(gray, cv2.CV_64F, 1, 0, ksize=sobel_kernel)\n sobel_y = cv2.Sobel(gray, cv2.CV_64F, 0, 1, ksize=sobel_kernel)\n abs_sobel_x = np.abs(sobel_x)\n abs_sobel_y = np.abs(sobel_y)\n return np.arctan2(abs_sobel_y, abs_sobel_x)\n\n return thresholding(img, dir_thresh, grad_dir)\n\n\ndef saturation_thresholding(img, sat_thresh=(0, 255)):\n def saturation_selection(image):\n hls_img = rgb2hls(image)\n return hls_img[:, :, 2]\n\n return thresholding(img, sat_thresh, saturation_selection)\n\n\ndef lightness_thresholding(img, lit_thresh=(0, 255)):\n def lightness_selection(image):\n hls_img = rgb2hls(image)\n return hls_img[:, :, 1]\n\n return thresholding(img, lit_thresh, lightness_selection)\n\n\ndef combined_thresholding(img):\n gradx = absolute_sobel_thresholding(img, orient='x', sobel_kernel=K_SIZE, abs_thresh=ABS_THRESH)\n grady = absolute_sobel_thresholding(img, orient='y', sobel_kernel=K_SIZE, abs_thresh=ABS_THRESH)\n mag_binary = magnitude_thresholding(img, sobel_kernel=MAG_K_SIZE, mag_thresh=MAG_THRESH)\n dir_binary = direction_thresholding(img, sobel_kernel=DIR_K_SIZE, dir_thresh=DIR_THRESH)\n sat_binary = saturation_thresholding(img, SAT_THRESH)\n lit_binary = lightness_thresholding(img, LIT_THRESH)\n combined = np.zeros((img.shape[0], img.shape[1]))\n # combined[((gradx == 1) & (grady == 1)) | ((mag_binary == 1) & (dir_binary == 1) & (sat_binary == 1))] = 1\n combined[((gradx == 1) & (grady == 1)) | ((mag_binary == 1) & (dir_binary == 1)) | (\n (sat_binary == 1) & (lit_binary == 1))] = 1\n # combined[((gradx == 1) & (grady == 1) & (lit_binary == 1)) | ((mag_binary == 1) & (dir_binary == 1)) | ((\n # sat_binary == 1) & (lit_binary == 1))] = 1\n return combined\n","sub_path":"functions/threshold.py","file_name":"threshold.py","file_ext":"py","file_size_in_byte":3204,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"422818760","text":"from bert.utils import obtain_sentence_embeddings\n\nimport pickle\nimport numpy as np\nimport torch\n\nbce_loss = torch.nn.BCELoss(reduction='none')\n\n\ndef train_extractor(\n model, data, learning_rate=1e-3, n_iters=10000, model_output_file=\"results/models/extractor.pt\", save_freq=2\n):\n \"\"\"\n :param model:\n :param data: list of dictionaries of form:\n [\n {'summary': [...], 'document': [...], 'extraction_labels': [...]},\n {...},\n ..\n ]\n :param learning_rate:\n :param n_iters:\n :param model_output_file:\n :param save_freq:\n :return:\n \"\"\"\n optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)\n losses = list()\n\n for i in range(n_iters):\n documents, extraction_labels = get_training_batch(data, batch_size=5)\n\n sentence_embeddings, mask = obtain_sentence_embeddings(model.bert_model, model.bert_tokenizer, documents)\n\n # Predict probability of extraction per sentence\n extraction_probabilities = model(sentence_embeddings)\n\n # Calculate loss\n loss = bce_loss(input=extraction_probabilities, target=extraction_labels)\n loss = loss * mask\n loss = loss.sum()\n losses.append(loss)\n print(f\"Loss: {loss}\")\n\n # Calculate gradient and update\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n if i % save_freq == 0:\n torch.save(model.state_dict(), model_output_file)\n pickle.dump(losses, open(\"results/models/extractor_losses.pkl\", \"wb\"))\n\n return\n\n\ndef get_training_batch(training_dictionaries, batch_size):\n \"\"\"\n :param training_dictionaries:\n :param batch_size:\n :return:\n \"\"\"\n mini_batch = training_dictionaries[:2] # np.random.choice(training_dictionaries, batch_size).tolist()\n\n documents, extraction_labels = map(list, zip(*[(s['document'], s['extraction_label']) for s in mini_batch]))\n extraction_labels = torch.nn.utils.rnn.pad_sequence(\n sequences=extraction_labels,\n batch_first=True,\n padding_value=0.0\n )\n\n return documents, extraction_labels\n","sub_path":"extractor/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":2135,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"291950111","text":"import cmdtools\n\ndef e_attrtest(error):\n\t# attributes also get passed to error callback\n\tprint(\"in error callback:\", e_attrtest.name)\n\ndef attrtest():\n\tprint(attrtest.name)\n\t# 1 / 0 # uncomment expression to invoke error callback\n\ncmd = cmdtools.Cmd(\"/invoke\")\ncmd.process_cmd(attrtest, e_attrtest,\n\t# assign attributes\n\tattrs={\n\t\t\"name\": \"Joe\"\n\t}\n)","sub_path":"examples/05callback_attributes/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":349,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"390625680","text":"\"\"\"\n * Copyright 2020, Departamento de sistemas y Computación\n * Universidad de Los Andes\n *\n *\n * Desarrolado para el curso ISIS1225 - Estructuras de Datos y Algoritmos\n *\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see .\n \"\"\"\nimport config\nfrom DISClib.ADT import list as lt\nfrom DISClib.ADT import orderedmap as om\nfrom DISClib.DataStructures import mapentry as me\nfrom DISClib.ADT import map as m\nimport datetime\nassert config\nfrom DISClib.DataStructures import listiterator as it\nimport math as ma \nimport obspy.geodetics as og\nfrom obspy.geodetics import kilometers2degrees\n\n\"\"\"\nEn este archivo definimos los TADs que vamos a usar,\nes decir contiene los modelos con los datos en memoria\n\n\n\"\"\"\n\n# -----------------------------------------------------\n# API del TAD Catalogo de Libros\n# -----------------------------------------------------\n\ndef newAnalyzer():\n \"\"\" Inicializa el analizador\n\n Crea una lista vacia para guardar todos los crimenes\n Se crean indices (Maps) por los siguientes criterios:\n -Fechas\n\n Retorna el analizador inicializado.\n \"\"\"\n analyzer = {'accidents': None,\n 'dateIndex': None,\n 'timeIndex': None}\n\n analyzer['accidents'] = lt.newList('SINGLE_LINKED', compareIds)\n analyzer['dateIndex'] = om.newMap(omaptype = 'RBT',\n comparefunction = compareDates)\n analyzer['timeIndex'] = om.newMap(omaptype = 'RBT',\n comparefunction = compareTime)\n return analyzer\n\n# Funciones para agregar informacion al catalogo\n\ndef addAccident(analyzer, accident):\n lt.addLast(analyzer['accidents'], accident)\n updateDateIndex(analyzer['dateIndex'], analyzer['timeIndex'],accident)\n #updateTimeIndex(analyzer['timeIndex'], accident)\n return analyzer\n\ndef updateDateIndex(map, maptime, accident):\n \"\"\"\n Se toma la fecha del crimen y se busca si ya existe en el arbol\n dicha fecha. Si es asi, se adiciona a su lista de crimenes\n y se actualiza el indice de tipos de crimenes.\n\n Si no se encuentra creado un nodo para esa fecha en el arbol\n se crea y se actualiza el indice de tipos de crimenes\n \"\"\"\n occurreddate = accident['Start_Time']\n accidentdate = datetime.datetime.strptime(occurreddate, '%Y-%m-%d %H:%M:%S')\n accidenttime1 = datetime.datetime.strptime(occurreddate, '%Y-%m-%d %H:%M:%S') # print(\"Created at %s:%s\" % (t1.hour, t1.minute))\n accidenttime = (accidenttime1.hour,accidenttime1.minute)\n entrydate = om.get(map, accidentdate.date())\n entrytime = om.get(maptime, accidenttime)\n if entrydate is None and entrytime is None:\n datentry = newDataEntry(accident)\n om.put(map, accidentdate.date(), datentry)\n om.put(maptime, accidenttime, datentry)\n elif entrytime is None:\n datentry = me.getValue(entrydate)\n om.put(maptime, accidenttime, datentry)\n elif entrydate is None:\n datentry = newDataEntry(accident)\n om.put(map, accidentdate.date(), datentry)\n else:\n datentry = me.getValue(entrydate)\n addDateIndex(datentry, accident)\n return map\n\ndef addDateIndex(datentry, accident):\n \"\"\"\n Actualiza un indice de tipo de crimenes. Este indice tiene una lista\n de crimenes y una tabla de hash cuya llave es el tipo de crimen y\n el valor es una lista con los crimenes de dicho tipo en la fecha que\n se está consultando (dada por el nodo del arbol)\n \"\"\"\n lst = datentry['lstaccident']\n lt.addLast(lst, accident)\n offenseIndex = datentry['offenseIndex']\n offentry = m.get(offenseIndex, accident['Description'])\n offenseIndexTime = datentry['offenseIndexTime']\n offentryTime = m.get(offenseIndexTime, accident['Description'])\n if (offentry is None and offentryTime is None):\n entry = newOffenseEntry(accident['Description'], accident)\n lt.addLast(entry['lstoffenses'], accident)\n m.put(offenseIndex, accident['Description'], entry)\n m.put(offenseIndexTime, accident['Description'], entry)\n elif offentryTime is None:\n entry = me.getValue(offentry)\n lt.addLast(entry['lstoffenses'], accident)\n m.put(offenseIndexTime, accident['Description'], entry)\n elif offentry is None:\n entry = newOffenseEntry(accident['Description'], accident)\n lt.addLast(entry['lstoffenses'], accident)\n m.put(offenseIndex, accident['Description'], entry)\n else:\n entry = me.getValue(offentry)\n lt.addLast(entry['lstoffenses'], accident)\n return datentry\n\ndef newDataEntry(accident):\n \"\"\"\n Crea una entrada en el indice por fechas, es decir en el arbol\n binario.\n \"\"\"\n entry = {'offenseIndex': None,'lstaccident': None}\n entry['offenseIndex'] = m.newMap(loadfactor = 3,\n numelements = 45000,\n maptype = 'CHAINING',\n comparefunction = compareOffenses)\n entry['offenseIndexTime'] = m.newMap(loadfactor = 3,\n numelements = 45000,\n maptype = 'CHAINING',\n comparefunction = compareOffenses)\n entry['lstaccident'] = lt.newList('SINGLE_LINKED', compareDates)\n return entry\n\ndef newOffenseEntry(offensegrp, accident):\n \"\"\"\n Crea una entrada en el indice por tipo de crimen, es decir en\n la tabla de hash, que se encuentra en cada nodo del arbol.\n \"\"\"\n ofentry = {'offense': None, 'lstoffenses': None}\n ofentry['offense'] = offensegrp\n ofentry['lstoffenses'] = lt.newList('SINGLELINKED', compareOffenses)\n return ofentry\n\n# ==============================\n# Funciones de consulta\n# ==============================\n\ndef accidentsSize(analyzer):\n \"\"\"\n Número de libros en el catago\n \"\"\"\n return lt.size(analyzer['accidents'])\n\ndef indexHeight(analyzer):\n \"\"\"Numero de autores leido\n \"\"\"\n return om.height(analyzer['dateIndex']),om.height(analyzer['timeIndex'])\n\ndef indexSize(analyzer):\n \"\"\"Numero de autores leido\n \"\"\"\n return om.size(analyzer['dateIndex']),om.size(analyzer['timeIndex'])\n\ndef minKey(analyzer):\n \"\"\"Numero de autores leido\n \"\"\"\n return om.minKey(analyzer['dateIndex'])\n\ndef maxKey(analyzer):\n \"\"\"Numero de autores leido\n \"\"\"\n return om.maxKey(analyzer['dateIndex'])\n\ndef getAccidentsByRange(analyzer, initialDate, finalDate):\n \"\"\"\n Retorna el numero de crimenes en un rago de fechas.\n \"\"\"\n lst = om.values(analyzer['dateIndex'], initialDate, finalDate)\n return lst\n\ndef getAccidentsByRangeCode(analyzer, initialDate, offensecode):\n \"\"\"\n Para una fecha determinada, retorna el numero de crimenes\n de un tipo especifico.\n \"\"\"\n accidentdate = om.get(analyzer['dateIndex'], initialDate)\n if accidentdate['key'] is not None:\n offensemap = me.getValue(accidentdate)['offenseIndex']\n numoffenses = m.get(offensemap, offensecode)\n if numoffenses is not None:\n return m.size(me.getValue(numoffenses)['lstoffenses'])\n return 0\n\n# ==============================\n# Funciones de requerimientos\n# ==============================\n\ndef accidentesPorHora(cont, time, anio): #REQ. 0.5\n cantidad = {'total': 0,'1':0,'2':0,'3':0,'4':0}\n for i in range(2016,2020):\n if str(i) in anio['anio'] or anio['anio'] == 0: \n data = om.get(cont[str(i)][0]['timeIndex'],time)\n values = me.getValue(data)['offenseIndexTime']\n accidents = m.valueSet(values)\n iterator = it.newIterator(accidents)\n while it.hasNext(iterator):\n data = it.next(iterator)['lstoffenses']\n cantidad['total'] += lt.size(data)\n siguiente = it.newIterator(data)\n while it.hasNext(siguiente):\n current = it.next(siguiente)\n severidad = current['Severity']\n cantidad[severidad] += 1\n return cantidad\n\n\ndef accidentesPorFecha(cont, date, anio): #REQ. 1\n cantidad = {'total': 0,'1':0,'2':0,'3':0,'4':0}\n for i in range(2016,2020):\n if cont[str(i)][0] != None:\n data = om.get(cont[str(i)][0]['dateIndex'],date)\n values = me.getValue(data)['offenseIndex']\n accidents = m.valueSet(values)\n iterator = it.newIterator(accidents)\n while it.hasNext(iterator):\n actual = it.next(iterator)['lstoffenses']\n cantidad['total'] += lt.size(actual)\n siguiente = it.newIterator(actual)\n while it.hasNext(siguiente):\n current = it.next(siguiente)\n severidad = current['Severity']\n cantidad[severidad] += 1\n return cantidad\n\ndef accidentesAnteriores (cont, date, anio): # REQ. 1\n cantidad = {'total': 0, 'fecha': {}}\n llaves = llavesHasta(cont, date)\n for i in range(2016,2020):\n if cont[str(i)][0] != None:\n iterator = it.newIterator(llaves[str(i)])\n while it.hasNext(iterator):\n numero = 0\n date = it.next(iterator)\n data = om.get(cont[str(i)][0]['dateIndex'],date)\n values = me.getValue(data)['offenseIndex']\n accidents = m.valueSet(values)\n iterator2 = it.newIterator(accidents)\n while it.hasNext(iterator2):\n actual = it.next(iterator2)['lstoffenses']\n cantidad['total'] += lt.size(actual)\n numero += lt.size(actual)\n cantidad['fecha'][date] = numero\n mayor = hallarMayorFecha(cantidad)\n return (cantidad['total'],mayor)\n\ndef accidentesEnUnRangoDeFecha(cont, initialDate, finalDate, anio): #O(N) REQ. 3\n llaves = llavesEnRango(cont, initialDate, finalDate, anio)\n cantidad = {'total': 0,'1':0,'2':0,'3':0,'4':0}\n total = 0\n for i in range(int(str(initialDate)[:4]),int(str(finalDate)[:4])+1):\n iterator = it.newIterator(llaves[str(i)])\n while it.hasNext(iterator):\n date = it.next(iterator)\n cantidades = accidentesPorFecha(cont, date, anio)\n total += cantidades['total']\n cantidad['1'] += cantidades['1']\n cantidad['2'] += cantidades['2']\n cantidad['3'] += cantidades['3']\n cantidad['4'] += cantidades['4']\n mayor = hallarMayorSeveridad(cantidad)\n return (total,mayor)\n\ndef conocerEstado (cont, initialDate, finalDate, anio): #REQ. 4\n llaves = llavesEnRango(cont, initialDate, finalDate, anio)\n cantidad = {'fecha': {}, 'state': {} }\n for i in range(int(str(initialDate)[:4]),int(str(finalDate)[:4])+1):\n iterator = it.newIterator(llaves[str(i)])\n while it.hasNext(iterator):\n numero = 0\n date = it.next(iterator)\n data = om.get(cont[str(i)][0]['dateIndex'],date)\n values = me.getValue(data)['offenseIndex']\n accidents = m.valueSet(values)\n iterator2 = it.newIterator(accidents)\n while it.hasNext(iterator2):\n actual = it.next(iterator2)['lstoffenses']\n numero += lt.size(actual)\n siguiente = it.newIterator(actual)\n while it.hasNext(siguiente):\n current = it.next(siguiente)\n state = current['State']\n if state not in cantidad['state']:\n cantidad['state'][state] = 1\n else: \n cantidad['state'][state] += 1\n cantidad['fecha'][date] = numero\n mayorFecha = hallarMayorFecha(cantidad)\n mayorState = hallarMayorState(cantidad)\n return (mayorFecha, mayorState)\n\ndef gradosAkilometros(x):\n y=og.degrees2kilometers(x)\n return y\ndef inRadio (radio,longitud,latitud, current):\n longitud = (float(gradosAkilometros2(str(longitud))))\n latitud = (float(gradosAkilometros2(str(latitud))))\n start_longitud = (float(gradosAkilometros2(current['Start_Lng'])))\n start_latitude = (float(gradosAkilometros2(current['Start_Lat'])))\n x=ma.hypot(start_longitud-longitud,start_latitude-latitud)\n return x<=float(radio)\n\ndef gradosAkilometros2(x):\n a=x.split('.')\n try:\n return str(a[0])+'.'+str(a[1])+str(a[2])\n except:\n return str(a[0])+'.'+str(a[1]) \ndef dentroDelRadio(radio, longitud, latitud, current):\n loc_lng = float(current['Start_Lng'].replace('.','')) # un grado=60 millas una milla = 1852 metros\n loc_lat = float(current['Start_Lat'].replace('.','')) \n extremo_y = latitud+radio\n extremo_x = longitud+radio \n if extremo_y >= loc_lat and extremo_x >= loc_lng:\n return True\n return False\ndef radioAgrados(radio):\n nuevo_radio=radio/111.12\n return nuevo_radio\n\ndef conocerZonaGeografica(cont, radio, longitud, latitud,anio):\n \"\"\"\n cont: analyzer\n Radio: En que se encuentran los accidentes\n longitud: coordenada\n latitud: coordenada\n centro=(latitud,longitud)\n\n \"\"\"\n cantidad = 0\n for i in range(2016,2020):\n\n if cont[str(i)][0] != None: \n shaves = om.keySet(cont[str(i)][0]['dateIndex'])\n iterator = it.newIterator(shaves)\n while it.hasNext(iterator):\n date = it.next(iterator)\n data = om.get(cont[str(i)][0]['dateIndex'],date)\n values = me.getValue(data)['offenseIndex']\n accidents = m.keySet(values)\n iterator2 = it.newIterator(accidents)\n while it.hasNext(iterator2):\n actual = m.get(values,it.next(iterator2))\n data = me.getValue(actual)['lstoffenses']\n siguiente = it.newIterator(data)\n while it.hasNext(siguiente):\n current = it.next(siguiente)\n if inRadio(radio, longitud, latitud, current) == True:\n cantidad += 1\n \n return cantidad\n\n# ==============================\n# Funciones de apoyo a requerimientos\n# ==============================\n\ndef llavesHasta(cont, date):\n llaves = {}\n for i in range(2016,2020):\n if cont[str(i)][0] != None:\n if str(i) not in str(date):\n llaves[str(i)] = om.keySet(cont['dateIndex'])\n else:\n initialDate = om.minKey(cont[str(i)][0]['dateIndex'])\n finalDate = om.floor(cont[str(i)][0]['dateIndex'],date)\n llaves[str(i)] = om.keys(cont[str(i)][0]['dateIndex'],initialDate,finalDate)\n break\n return llaves\n\ndef conocerHoras(cont, initialHour, finalHour, anio):\n shaves = om.keys(cont[anio['anio']][0]['timeIndex'],initialHour,finalHour)\n cantidad = {'total': 0,'1':0,'2':0,'3':0,'4':0}\n total = accidentsSize(cont[anio['anio']][0])\n iterator = it.newIterator(shaves)\n while it.hasNext(iterator):\n time = it.next(iterator)\n cantidades = accidentesPorHora(cont,time, anio)\n cantidad['total'] += cantidades['total']\n cantidad['1'] += cantidades['1']\n cantidad['2'] += cantidades['2']\n cantidad['3'] += cantidades['3']\n cantidad['4'] += cantidades['4']\n porcentaje = round(((cantidad['total'] * 100) / total),2)\n return (cantidad,porcentaje)\n\ndef llavesEnRango(cont, initialDate, finalDate, anio):\n llaves = {}\n if anio['type'] == 0:\n llaves[anio['anio']] = om.keys(cont[anio['anio']][0]['dateIndex'], initialDate, finalDate)\n else: \n for i in range(int(str(initialDate)[:4]),int(str(finalDate)[:4])+1):\n if str(i) in str(initialDate):\n mayor = om.maxKey(cont[str(i)][0]['dateIndex'])\n llaves[str(i)] = om.keys(cont[str(i)][0]['dateIndex'], initialDate, mayor)\n elif str(i) in str(finalDate):\n menor = om.minKey(cont[str(i)][0]['dateIndex'])\n llaves[str(i)] = om.keys(cont[str(i)][0]['dateIndex'], menor, finalDate)\n else:\n llaves[str(i)] = om.keySet(cont[str(i)][0]['dateIndex'])\n return llaves\n\ndef dentroDelRadio(cont, radio, longitud, latitud, current):\n loc_lng = float(current['Start_Lng'].replace('.',''))\n loc_lat = float(current['Start_Lat'].replace('.',''))\n extremo_y = latitud+radio\n extremo_x = longitud+radio\n if extremo_y >= loc_lat and extremo_x >= loc_lng:\n return True\n return False\n\ndef hallarMayorFecha(cantidad):\n mayor = ['',0]\n for i in cantidad['fecha']:\n if cantidad['fecha'][i] >= mayor[1]:\n mayor[0] = i\n mayor[1] = cantidad['fecha'][i]\n return mayor\n\ndef hallarMayorSeveridad(cantidad):\n mayor = ['',0]\n for i in cantidad:\n if cantidad[i] >= mayor[1]:\n mayor[0] = i\n mayor[1] = cantidad[i]\n return mayor\n\ndef hallarMayorState(cantidad):\n mayorState = ['',0]\n for i in cantidad['state']:\n if cantidad['state'][i] >= mayorState[1]:\n mayorState[0] = i\n mayorState[1] = cantidad['state'][i]\n return mayorState\n# ==============================\n# Funciones de Comparacion\n# ==============================\n\ndef compareIds(id1, id2):\n \"\"\"\n Compara dos crimenes\n \"\"\"\n if (id1 == id2):\n return 0\n elif id1 > id2:\n return 1\n else:\n return -1\n\ndef compareDates(date1, date2):\n \"\"\"\n Compara dos ids de libros, id es un identificador\n y entry una pareja llave-valor\n \"\"\"\n if (date1 == date2):\n return 0\n elif (date1 > date2):\n return 1\n else:\n return -1\n\ndef compareTime(time1, time2):\n \"\"\"\n Compara dos ids de libros, id es un identificador\n y entry una pareja llave-valor\n \"\"\"\n if (time1 == time2):\n return 0\n elif (time1 > time2):\n return 1\n else:\n return -1\n\ndef compareOffenses(offense1, offense2):\n \"\"\"\n Compara dos ids de libros, id es un identificador\n y entry una pareja llave-valor\n \"\"\"\n offense = me.getKey(offense2)\n if (offense1 == offense):\n return 0\n elif (offense1 > offense):\n return 1\n else:\n return -1\n","sub_path":"App/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":18860,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"617007691","text":"# -*- coding: utf-8 -*-\nfrom __future__ import print_function, absolute_import, division\nfrom builtins import map, range, object, zip, sorted\nfrom past.builtins import basestring\nfrom numbers import Real\n\nfrom .base import BaseClass\nfrom .utils import Utils, Tuple\nfrom .iterators import RowIterator, ColIterator\nfrom . import amplpython\ntry:\n import pandas as pd\nexcept ImportError:\n pd = None\ntry:\n import numpy as np\nexcept ImportError:\n np = None\n\n\nclass Row(BaseClass):\n \"\"\"\n Represents a row in a :class:`~amplpy.DataFrame`.\n \"\"\"\n\n def __init__(self, _impl):\n self._impl = _impl\n\n def __iter__(self):\n return RowIterator(self._impl)\n\n def __getitem__(self, key):\n return Utils.castVariantRef(self._impl.getIndex(key))\n\n def toString(self):\n return str(list(self))\n\n\nclass Column(BaseClass):\n \"\"\"\n Represents a column in a :class:`~amplpy.DataFrame`.\n \"\"\"\n\n def __init__(self, _impl):\n self._impl = _impl\n\n def __iter__(self):\n return ColIterator(self._impl)\n\n def toString(self):\n return str(list(self))\n\n\nclass DataFrame(BaseClass):\n \"\"\"\n A DataFrame object, used to communicate data to and from the AMPL entities.\n\n An object of this class can be used to do the following tasks:\n - Assign values to AMPL entities (once the DataFrame is populated, use\n :func:`~amplpy.AMPL.setData` to assign its values to the modelling entities\n in its columns)\n - Get values from AMPL, decoupling the values from the AMPL entities they\n originate via :func:`~amplpy.Entity.getValues`.\n\n A DataFrame object can be created in various ways.\n\n - Create a skeleton by specifiying manually the indexing columns and the\n column headers.\n - Get values from AMPL, decoupling the values from the AMPL entities they\n originate from (via :func:`~amplpy.Entity.getValues`).\n\n Populating a DataFrame object can be done adding row by row to a\n pre-existing skeleton via :func:`~amplpy.DataFrame.addRow`, setting whole\n columns of a pre-existing skeleton via :func:`~amplpy.DataFrame.setColumn`\n or adding columns (including indexing columns) via\n :func:`~amplpy.DataFrame.addColumn`.\n\n Modifying a DataFrame object can be done via\n :func:`~amplpy.DataFrame.setColumn` or, item by item, via\n :func:`~amplpy.DataFrame.setValue`.\n\n Accessing data in a DataFrame can be done row by row using\n :func:`~amplpy.DataFrame.getRow` or by column via\n :func:`~amplpy.DataFrame.getColumn`.\n \"\"\"\n\n def __init__(self, index, columns=tuple(), **kwargs):\n \"\"\"\n Create a new DataFrame with specifed index and column headers.\n\n Args:\n index: Index column;\n\n columns: Column headers.\n \"\"\"\n if index is not None:\n if isinstance(index, basestring):\n index = (index,)\n if isinstance(columns, basestring):\n columns = (columns,)\n index_names = [\n col[0] if isinstance(col, tuple) else col\n for col in index\n ]\n column_names = [\n col[0] if isinstance(col, tuple) else col\n for col in columns\n ]\n self._impl = amplpython.DataFrame.factory(\n len(index_names),\n list(index_names) + list(column_names),\n len(index_names) + len(column_names)\n )\n for col in index:\n if isinstance(col, tuple):\n self.setColumn(col[0], col[1])\n for col in columns:\n if isinstance(col, tuple):\n self.setColumn(col[0], col[1])\n else:\n self._impl = kwargs.get('_impl', None)\n\n def __iter__(self):\n # FIXME: C++ iterators for dataframes not working with SWIG.\n return (self.getRowByIndex(i) for i in range(self.getNumRows()))\n\n def getNumCols(self):\n \"\"\"\n Get the total number of columns in this dataframe (indexarity + number\n of values).\n\n Returns:\n The number of columns.\n \"\"\"\n return self._impl.getNumCols()\n\n def getNumRows(self):\n \"\"\"\n Get the number of data rows in this dataframe.\n\n Returns:\n The number of rows.\n \"\"\"\n return self._impl.getNumRows()\n\n def getNumIndices(self):\n \"\"\"\n Get the number of indices (the indexarity) of this dataframe.\n\n Returns:\n The number of indices needed to access one row of this dataframe.\n \"\"\"\n return self._impl.getNumIndices()\n\n def addRow(self, *value):\n \"\"\"\n Add a row to the DataFrame. The size of the tuple must be equal to the\n total number of columns in the dataframe.\n\n Args:\n value: A single argument with a tuple containing all the values\n for the row to be added, or multiple arguments with the values for\n each column.\n \"\"\"\n if len(value) == 1 and isinstance(value[0], (tuple, list)):\n value = value[0]\n assert len(value) == self.getNumCols()\n self._impl.addRow(Tuple(value)._impl)\n\n def addColumn(self, header, values=[]):\n \"\"\"\n Add a new column with the corresponding header and values to the\n dataframe.\n\n Args:\n header: The name of the new column.\n\n values: A list of size :func:`~amplpy.DataFrame.getNumRows` with\n all the values of the new column.\n \"\"\"\n if len(values) == 0:\n self._impl.addColumn(header)\n else:\n assert len(values) == self.getNumRows()\n if any(isinstance(value, basestring) for value in values):\n values = list(map(str, values))\n self._impl.addColumnStr(header, values)\n elif all(isinstance(value, Real) for value in values):\n values = list(map(float, values))\n self._impl.addColumnDbl(header, values)\n else:\n raise NotImplementedError\n\n def getColumn(self, header):\n \"\"\"\n Get the specified column as a view object.\n\n Args:\n header: The header of the column.\n \"\"\"\n return Column(self._impl.getColumn(header))\n\n def setColumn(self, header, values):\n \"\"\"\n Set the values of a column.\n\n Args:\n header: The header of the column to be set.\n\n values: The values to set.\n \"\"\"\n if any(isinstance(value, basestring) for value in values):\n values = list(map(str, values))\n self._impl.setColumnStr(header, values, len(values))\n elif all(isinstance(value, Real) for value in values):\n values = list(map(float, values))\n self._impl.setColumnDbl(header, values, len(values))\n else:\n print(values)\n raise NotImplementedError\n\n def getRow(self, key):\n \"\"\"\n Get a row by value of the indexing columns. If the index is not\n specified, gets the only row of a dataframe with no indexing columns.\n\n Args:\n key: Tuple representing the index of the desired row.\n\n Returns:\n The row.\n \"\"\"\n return Row(self._impl.getRow(Tuple(key)._impl))\n\n def getRowByIndex(self, index):\n \"\"\"\n Get row by numeric index.\n\n Args:\n index: Zero-based index of the row to get.\n\n Returns:\n The corresponding row.\n \"\"\"\n assert isinstance(index, int)\n return Row(self._impl.getRowByIndex(index))\n\n def getHeaders(self):\n \"\"\"\n Get the headers of this DataFrame.\n\n Returns:\n The headers of this DataFrame.\n \"\"\"\n headers = self._impl.getHeaders()\n return tuple(\n headers.getIndex(i) for i in range(self._impl.getNumCols())\n )\n\n def setValues(self, values):\n \"\"\"\n Set the values of a DataFrame from a dictionary.\n\n Args:\n values: Dictionary with the values to set.\n \"\"\"\n ncols = self.getNumCols()\n nindices = self.getNumIndices()\n for key, value in values.items():\n key = Utils.convToList(key)\n assert len(key) == nindices\n value = Utils.convToList(value)\n assert len(value) == ncols-nindices\n self.addRow(key + value)\n\n def toDict(self):\n \"\"\"\n Return a dictionary with the DataFrame data.\n \"\"\"\n d = {}\n nindices = self.getNumIndices()\n for i in range(self.getNumRows()):\n row = list(self.getRowByIndex(i))\n if nindices > 1:\n key = tuple(row[:nindices])\n elif nindices == 1:\n key = row[0]\n else:\n key = None\n if len(row) - nindices == 0:\n d[key] = None\n elif len(row) - nindices == 1:\n d[key] = row[nindices]\n else:\n d[key] = tuple(row[nindices:])\n return d\n\n def toList(self):\n \"\"\"\n Return a list with the DataFrame data.\n \"\"\"\n if self.getNumCols() > 1:\n return [\n tuple(self.getRowByIndex(i))\n for i in range(self.getNumRows())\n ]\n else:\n return [\n self.getRowByIndex(i)[0]\n for i in range(self.getNumRows())\n ]\n\n def toPandas(self):\n \"\"\"\n Return a pandas DataFrame with the DataFrame data.\n \"\"\"\n assert pd is not None\n nindices = self.getNumIndices()\n headers = self.getHeaders()\n columns = {\n header: list(self.getColumn(header))\n for header in headers[nindices:]\n }\n index = zip(*[\n list(self.getColumn(header))\n for header in headers[:nindices]\n ])\n index = [key if len(key) > 1 else key[0] for key in index]\n if index == []:\n return pd.DataFrame(columns, index=None)\n else:\n return pd.DataFrame(columns, index=index)\n\n @classmethod\n def fromDict(cls, dic, index_names=None, column_names=None):\n \"\"\"\n Create a :class:`~amplpy.DataFrame` from a dictionary.\n\n Args:\n dic: dictionary to load.\n index_names: index names to use.\n column_names: column names to use.\n \"\"\"\n assert isinstance(dic, dict)\n assert len(dic) != 0\n\n def to_tuple(e):\n if isinstance(e, (tuple, list)):\n return tuple(e)\n else:\n return (e,)\n\n lst_index = list(map(to_tuple, dic.keys()))\n lst_columns = list(map(to_tuple, dic.values()))\n nindices, ncolumns = len(lst_index[0]), len(lst_columns[0])\n assert index_names is None or nindices == len(index_names)\n assert column_names is None or ncolumns == len(column_names)\n assert all(len(k) == nindices for k in lst_index)\n assert all(len(v) == ncolumns for v in lst_columns)\n\n index = zip(*lst_index)\n columns = zip(*lst_columns)\n\n if index_names is None:\n index_names = ['index{}'.format(i) for i in range(nindices)]\n\n if column_names is None:\n column_names = ['value{}'.format(i) for i in range(ncolumns)]\n\n index = [\n (index_names[i], cindex)\n for i, cindex in enumerate(zip(*lst_index))\n ]\n columns = [\n (column_names[i], column)\n for i, column in enumerate(zip(*lst_columns))\n ]\n return cls(index=index, columns=columns)\n\n @classmethod\n def fromPandas(cls, df, index_names=None):\n \"\"\"\n Create a :class:`~amplpy.DataFrame` from a pandas DataFrame.\n\n Args:\n df: Pandas DataFrame to load.\n index_names: index names to use.\n \"\"\"\n assert pd is not None\n if isinstance(df, pd.Series):\n df = pd.DataFrame(df)\n else:\n assert isinstance(df, pd.DataFrame)\n keys = [\n key if isinstance(key, tuple) else (key,)\n for key in df.index.tolist()\n ]\n index = [\n ('index{}'.format(i), cindex)\n for i, cindex in enumerate(zip(*keys))\n ]\n if index_names is not None:\n assert len(index) == len(index_names)\n for i in range(len(index)):\n index[i] = (index_names[i], index[i][1])\n columns = [\n (str(cname), df[cname].tolist())\n for cname in df.columns.tolist()\n ]\n return cls(index=index, columns=columns)\n\n @classmethod\n def fromNumpy(cls, data):\n \"\"\"\n Create a :class:`~amplpy.DataFrame` from a numpy array or matrix.\n \"\"\"\n assert np is not None\n if isinstance(data, np.ndarray):\n index = []\n if len(data.shape) == 1:\n columns = [('value', data.tolist())]\n elif len(data.shape) == 2:\n columns = [\n ('c{}'.format(i), col)\n for i, col in enumerate(zip(*data.tolist()))\n ]\n else:\n raise TypeError\n else:\n raise TypeError\n return cls(index=index, columns=columns)\n\n @classmethod\n def _fromDataFrameRef(cls, dfRef):\n return cls(None, None, _impl=dfRef)\n","sub_path":"amplpy/dataframe.py","file_name":"dataframe.py","file_ext":"py","file_size_in_byte":13510,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"633971932","text":"def default_collate(batch):\n 'Puts each data field into a tensor with outer dimension batch size'\n if torch.is_tensor(batch[0]):\n return torch.stack(batch, 0)\n elif (type(batch[0]).__module__ == 'numpy'):\n return torch.stack([torch.from_numpy(b) for b in batch], 0)\n elif isinstance(batch[0], int):\n return torch.LongTensor(batch)\n elif isinstance(batch[0], float):\n return torch.DoubleTensor(batch)\n elif isinstance(batch[0], string_classes):\n return batch\n elif isinstance(batch[0], collections.Iterable):\n transposed = zip(*batch)\n return [default_collate(samples) for samples in transposed]\n raise TypeError('batch must contain tensors, numbers, or lists; found {}'.format(type(batch[0])))","sub_path":"Data Set/bug-fixing-5/476d85dd3f8ee48f6affc836d5c7fbd8ccfab200--bug.py","file_name":"476d85dd3f8ee48f6affc836d5c7fbd8ccfab200--bug.py","file_ext":"py","file_size_in_byte":766,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"195140846","text":"# -*- coding: UTF-8 -*-\n\nimport sys\nimport os\n\nimport hashlib\n\nclass MD5Utils(object):\n\n @classmethod\n def md5(cls, szText):\n m = hashlib.md5()\n m.update(szText.encode(\"utf8\"))\n # print(m.hexdigest())\n return m.hexdigest()\n\n @classmethod\n def md5_file(cls, szFilePath):\n if not os.path.isfile(szFilePath):\n return \"\"\n\n myhash = hashlib.md5()\n f = open(szFilePath, 'rb')\n\n while True:\n b = f.read(8096)\n if not b:\n break\n\n myhash.update(b)\n\n f.close()\n return myhash.hexdigest()\n\n\n# print(MD5Utils.md5(\"123456\").lower())\n# print(MD5Utils.md5_file(\"log.py\"))\n","sub_path":"pythinkutils/common/MD5Utils.py","file_name":"MD5Utils.py","file_ext":"py","file_size_in_byte":698,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"269474185","text":"# Script to clone a specific python script and rename it \nfrom shutil import copyfile\nimport sys\nimport os\n\ndef manipulate_the_new_script(newscript,destination,n1,n2):\n list_of_lines = newscript.readlines()\n list_of_lines[69] = \" n = \" + n1 + \"\\n\"\n list_of_lines[97] = \" n = \" + n2 + \"\\n\"\n newscript = open(destination, \"w\")\n newscript.writelines(list_of_lines)\n newscript.close()\n\n\ndef main(argv):\n n1 = sys.argv[1]\n n2 = sys.argv[2]\n source = \"/home/giannos/Desktop/scikit-learn/benchmarks/bench_tree.py\"\n destination = \"/home/giannos/Desktop/scikit-learn/benchmarks/bench_tree_n1_\"+ n1 + \"_n2_\"+ n2 + \".py\"\n copyfile(source, destination)\n\n # Manipulate the new script - Open it and send it\n new_script = open(destination, \"r\")\n manipulate_the_new_script(new_script, destination,n1,n2)\n new_script.close()\n os.system(\"python3 bench_tree_n1_\"+ n1 + \"_n2_\"+ n2 + \".py\")\n print (\"################### bench_tree_n1_\"+ n1 + \"_n2_\"+ n2 + \".py ###################\" )\n\n\nif __name__ == \"__main__\":\n main(sys.argv[2:])\n \n","sub_path":"benchmarks/clone_and_modify.py","file_name":"clone_and_modify.py","file_ext":"py","file_size_in_byte":1075,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"82611463","text":"# (C) Datadog, Inc. 2022-present\n# All rights reserved\n# Licensed under a 3-clause BSD style license (see LICENSE)\nclass AppEnvVars:\n REPO = 'DDEV_REPO'\n INTERACTIVE = 'DDEV_INTERACTIVE'\n QUIET = 'DDEV_QUIET'\n VERBOSE = 'DDEV_VERBOSE'\n # https://no-color.org\n NO_COLOR = 'NO_COLOR'\n FORCE_COLOR = 'DDEV_COLOR'\n\n\nclass ConfigEnvVars:\n CONFIG = 'DDEV_CONFIG'\n\n\nclass VerbosityLevels:\n ERROR = -2\n WARNING = -1\n INFO = 0\n DEBUG = 1\n TRACE = 2\n","sub_path":"ddev/src/ddev/config/constants.py","file_name":"constants.py","file_ext":"py","file_size_in_byte":479,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"574085741","text":"# -*- coding:utf8 -*-\nimport findspark\n\nfindspark.init(spark_home=\"/usr/hdp/current/spark2-client/\", python_path=\"/root/anaconda2/bin/python\")\n\nfrom pyspark.sql import SparkSession\nimport json\nfrom pyspark.streaming.kafka import KafkaUtils, TopicAndPartition\nfrom pyspark.streaming import StreamingContext\n\n\ndef get_spark(master=\"yarn\", memory=\"1g\", local_dir=\"/tmp\", app_name=\"preporcess\", queue=\"default\", engine_id=\"asdf\"):\n msg = \"Please Note..... \\n spark up.\"\n '''\n 创建spark content\n\n 输入:\n master: spark 运行模式\n memory: spark 执行节点的内存\n local_dir: spark的本地目录位置 需要容量较大\n 输出:\n spark content\n '''\n spark = SparkSession.builder.appName(app_name).master(\"yarn\").config(\n \"spark.shuffle.service.enabled\", True\n ).config(\n \"spark.executor.instances\", 2\n ).config(\n \"spark.executor.cores\", 2\n ).config(\"spark.driver.memory\", \"1G\"\n ).config(\n \"spark.executor.memory\", \"1G\"\n ).config(\n \"spark.shuffle.memoryFraction\", \"0.6\"\n ).config(\n \"spark.default.parallelism\", 400\n ).config(\n \"spark.local.dir\", \"/tmp\"\n ).config(\n \"spark.driver.maxResultSize\", \"5G\"\n ).config(\n \"spark.yarn.queue\", \"http_project\"\n ).config(\n \"spark.streaming.kafka.maxRatePerPartition\", 100\n ).getOrCreate()\n\n print(\"create spark session\", spark.sparkContext.master)\n print(msg)\n return spark\n\ndef get_direct_kafka(ssc):\n # zookeeper=\"hdp2.buptnsrc.com:2181,hdp4.buptnsrc.com:2181,hdp1.buptnsrc.com:2181\"\n # groupid=\"test-consumer-lwh-group\"\n # topics={\"test_kafka_flume_hbase_lwh\":0,\"test_kafka_flume_hbase_lwh\":1}\n # lines=KafkaUtils.createStream(ssc=ssc,topics=topics,groupId=groupid,zkQuorum=zookeeper)\n # return lines\n kafkaParams = {\"metadata.broker.list\": \"hdp2.buptnsrc.com:6667,hdp4.buptnsrc.com:6667,hdp5.buptnsrc.com:6667\"}\n topic = [\"test_first\"]\n lines = KafkaUtils.createDirectStream(ssc, topic, kafkaParams)\n return lines\n\n\ndef process(row):\n return 0\n\n\nif __name__ == '__main__':\n print(\"11122\")\n # 获取到spark session\n spark = get_spark(master=\"yarn\", app_name=\"kafka-test-yangkun1\", queue=\"default\")\n sc = spark.sparkContext\n # 处理时间间隔为2s\n ssc = StreamingContext(sc, 30)\n print(\"333\")\n\n lines = get_direct_kafka(ssc)\n\n # lines=get_kafka(ssc)\n\n lines.foreachRDD(process)\n line = lines.flatMap(lambda x: x[1].split(' '))\n res = line.map(lambda x: (x, 1)).reduceByKey(lambda a, b: a + b)\n print(type(lines))\n print(\"------------------ start ---------------\")\n res.pprint()\n print(\"------------------- finish --------------------!!!\")\n\n ssc.start()\n ssc.awaitTermination()","sub_path":"kafka/code/kafkaDemo/kafkatest.py","file_name":"kafkatest.py","file_ext":"py","file_size_in_byte":2788,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"213441139","text":"from PySide2.QtCore import Qt\nfrom PySide2.QtWidgets import QApplication, QMainWindow, QHBoxLayout, QWidget\n\nfrom layout_colorwidget import Color\n\n\n# subclass the QMainWindow to customize the application's main window\nclass MainWindow(QMainWindow):\n def __init__(self):\n super().__init__()\n\n self.setWindowTitle(\"My App\")\n\n layout = QHBoxLayout()\n\n layout.addWidget(Color(\"Blue\"))\n layout.addWidget(Color(\"Green\"))\n layout.addWidget(Color(\"Orange\"))\n layout.addWidget(Color(\"Yellow\"))\n\n widget = QWidget()\n widget.setLayout(layout)\n\n self.setCentralWidget(widget)\n\n\n# create application instance\napp = QApplication([])\n\nwindow = MainWindow()\nwindow.show() # windows are hidden by default\n\n# start the event loop\napp.exec_()","sub_path":"layouts/q_hbox_layout.py","file_name":"q_hbox_layout.py","file_ext":"py","file_size_in_byte":797,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"526588818","text":"from data_aug.data_aug import *\nfrom data_aug.bbox_util import *\nimport cv2\nimport pickle as pkl\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport xml.etree.ElementTree as ET\nfrom lxml import etree\nimport codecs\nimport copy\n\ndef get_classname():\n\n return {\"1.0\": \"Crack\", \"2.0\":\"Spalling\", \"3.0\":\"Water_seepage\", \"4.0\":\"Ground_water_seepage\"}\n\n\ndef get_category_id():\n\n return {\"Crack\": 1.0, \"Spalling\": 2.0, \"Water_seepage\": 3.0, \"Ground_water_seepage\":4.0}\n\n\ndef save_anno(anno_save_dir, name_xml, tree_xml):\n\n # tree_xml.find(\"filename\").text = name_xml[:-4]+\".jpg\"\n prettifyResult = prettify(tree_xml)\n\n if not os.path.exists(anno_save_dir):\n os.makedirs(anno_save_dir)\n\n out_file = codecs.open(os.path.join(anno_save_dir, name_xml), 'w', encoding='utf-8')\n out_file.write(prettifyResult.decode('utf8'))\n out_file.close()\n\ndef prettify(elem):\n \"\"\"\n Return a pretty-printed XML string for the Element.\n \"\"\"\n rough_string = ET.tostring(elem, 'utf8')\n root = etree.fromstring(rough_string)\n\n return etree.tostring(root, pretty_print=True, encoding='utf-8').replace(\" \".encode(), \"\\t\".encode())\n\n\ndef generate_xml_template(IMG_SIZE=None, FOLDER_NAME=None, IMG_NAME=None, IMG_PATH=\"None\", IMG_CHANNEL=3):\n\n # Check conditions\n if IMG_NAME is None or \\\n FOLDER_NAME is None or \\\n IMG_PATH is None:\n return None\n # print(\"=================================\")\n top = ET.Element('annotation')\n\n folder = ET.SubElement(top, 'folder')\n folder.text = FOLDER_NAME\n\n filename = ET.SubElement(top, 'filename')\n filename.text = IMG_NAME\n\n if IMG_PATH is not None:\n localImgPath = ET.SubElement(top, 'path')\n localImgPath.text = \"localImgPath\"\n\n source = ET.SubElement(top, 'source')\n database = ET.SubElement(source, 'database')\n database.text = \"databaseSrc\"\n\n size_part = ET.SubElement(top, 'size')\n width = ET.SubElement(size_part, 'width')\n height = ET.SubElement(size_part, 'height')\n depth = ET.SubElement(size_part, 'depth')\n width.text = str(IMG_SIZE[1])\n height.text = str(IMG_SIZE[0])\n depth.text = str(IMG_CHANNEL)\n\n segmented = ET.SubElement(top, 'segmented')\n segmented.text = '0'\n return top\n\ndef appendObjects(tree_xml, bboxes, root_save_dir, name_xml, IMG_SIZE):\n # print(len(bboxes))\n # print(tree_xml)\n\n for box in bboxes:\n # class_name = get_classname()[str(box[0])]\n # ymin = box[1]\n # xmin = box[2]\n # ymax = box[3]\n # xmax = box[4]\n class_name = get_classname()[str(box[4])]\n ymin = box[1]\n xmin = box[0]\n ymax = box[3]\n xmax = box[2]\n\n obj = ET.SubElement(tree_xml, 'object')\n obj_name = ET.SubElement(obj, 'name')\n obj_pose =ET.SubElement(obj, 'pose')\n obj_pose.text = 'Unspecified'\n\n truncated = ET.SubElement(obj, 'truncated')\n if int(float(ymax)) == int(float(IMG_SIZE[0])) or (int(float(ymin)) == 1):\n truncated.text = \"1\" # max == height or min\n elif (int(float(xmax)) == int(float(IMG_SIZE[1]))) or (int(float(xmin)) == 1):\n truncated.text = \"1\" # max == width or min\n else:\n truncated.text = \"0\"\n is_difficulty = ET.SubElement(obj, 'difficult')\n is_difficulty.text =str(0)\n\n obj_bndbox = ET.SubElement(obj, 'bndbox')\n bndbox_xmin = ET.SubElement(obj_bndbox, 'xmin')\n bndbox_ymin = ET.SubElement(obj_bndbox, 'ymin')\n bndbox_xmax = ET.SubElement(obj_bndbox, 'xmax')\n bndbox_ymax = ET.SubElement(obj_bndbox, 'ymax')\n\n obj_name.text = class_name\n bndbox_xmin.text = str(int(xmin))\n bndbox_ymin.text = str(int(ymin))\n bndbox_xmax.text = str(int(xmax))\n bndbox_ymax.text = str(int(ymax))\n\n save_anno(root_save_dir, name_xml, tree_xml)\n\n if 0:\n out_file = None\n prettifyResult =prettify(tree_xml)\n out_file = codecs.open(\"/media/user/HDD/Data_processing/lta/data_for_training/20191128/test_%d.xml\"%i, 'w', encoding='utf-8')\n out_file.write(prettifyResult.decode('utf8'))\n out_file.close()\n\ndef read_xml(xml):\n boxes = []\n tree = ET.parse(xml)\n root = tree.getroot()\n for object in root.findall(\"object\"):\n\n class_name = object.find(\"name\").text\n xmin = int(object.find(\"bndbox\").find(\"xmin\").text)\n ymin = int(object.find(\"bndbox\").find(\"ymin\").text)\n xmax = int(object.find(\"bndbox\").find(\"xmax\").text)\n ymax = int(object.find(\"bndbox\").find(\"ymax\").text)\n boxes.append([xmin, ymin, xmax, ymax, get_category_id()[class_name]])\n\n return boxes\n\ndef data_augment(image, bboxes, image_name, root_save, aug_times=3):\n\n transforms = Sequence([RandomHorizontalFlip(1), RandomTranslate(0.1, diff=True), RandomRotate(10), RandomShear(0.1),\n RandomScale(0.1, diff=True)])\n\n for i in range(aug_times):\n try:\n image_name1 = image_name[:-4] + '_%d'%i +image_name[-4:]\n # print(image_name1)\n\n img, bboxes_t = transforms(copy.deepcopy(image), copy.deepcopy(bboxes))\n # drawed_image = draw_rect(img, bboxes_t)\n # plt.imshow(drawed_image)\n # plt.show()\n # plt.close()\n if 1:\n xml_tree = generate_xml_template(IMG_SIZE=img.shape, FOLDER_NAME=\"JPEGImages\", IMG_NAME=image_name1)\n\n anno_save_dir = os.path.join(root_save, \"Annotations\")\n\n appendObjects(copy.deepcopy(xml_tree), bboxes_t, anno_save_dir, name_xml=image_name1[:-4] + \".xml\",\n IMG_SIZE=img.shape)\n\n img_save_dir = os.path.join(root_save, \"JPEGImages\", image_name1)\n cv2.imwrite(img_save_dir, img[:, :, ::-1])\n\n except:\n print(image_name)\n\nif __name__ == '__main__':\n\n if 0:\n img_dir = \"/media/user/HDD/Data_processing/lta/data_for_training/model_generated/2020-07-24-Clark_Quay/images/2020-07-24-Clark_Quay_Round1_A_B_Left_Aerolion_000071.jpg\"\n anno_dir = \"/media/user/HDD/Data_processing/lta/data_for_training/model_generated/2020-07-24-Clark_Quay/annotations/2020-07-24-Clark_Quay_Round1_A_B_Left_Aerolion_000071.xml\"\n\n bboxes = np.array(read_xml(anno_dir))\n img = cv2.imread(img_dir)[:, :, ::-1]\n image_name = \"Left_Aerolion_000071.jpg\"\n root_save = \"/media/user/HDD/others_temp/test\"\n data_augment(img, bboxes, image_name, root_save, aug_times=5)\n\n if 1:\n # root_dir = \"/media/user/HDD/Data_processing/lta/data_for_training/model_generated\"\n # root_dir = \"/home/user/Training_data/4classes\"\n # dataset_list = os.listdir(root_dir)\n\n # for dataset in dataset_list:\n # print(dataset)\n\n # img_folder_dir = os.path.join(root_dir, dataset, \"val\", \"data\", \"JPEGImages\")\n # anno_folder_dir = os.path.join(root_dir, dataset, \"train\", \"data\", \"Annotations\")\n\n img_folder_dir = \"/home/user/Training_data/3classes/training/2021-04-24-Little_India/train/data/JPEGImages\"\n anno_folder_dir = \"/home/user/Training_data/3classes/training/2021-04-24-Little_India/train/data/Annotations\"\n\n # save_root_dir = os.path.join(root_dir, dataset, \"train\", \"data_aug\")\n save_root_dir = \"/home/user/Training_data/3classes/training/2021-04-24-Little_India/train/data_aug\"\n img_save_root = os.path.join(save_root_dir, \"JPEGImages\")\n anno_save_root = os.path.join(save_root_dir, \"Annotations\")\n\n if not os.path.isdir(img_save_root):\n os.makedirs(img_save_root)\n\n if not os.path.isdir(anno_save_root):\n os.makedirs(anno_save_root)\n\n img_list = os.listdir(img_folder_dir)\n\n for img_name in img_list:\n img_dir = os.path.join(img_folder_dir, img_name)\n anno_dir = os.path.join(anno_folder_dir, img_name[:-4]+ \".xml\")\n\n bboxes = np.array(read_xml(anno_dir))\n img = cv2.imread(img_dir)[:, :, ::-1]\n data_augment(img, bboxes, img_name, save_root_dir, aug_times=3)\n\n\n if 0:\n root_dir = \"/home/user/Training_data/LTA/Train/data_supplement\"\n dataset_list = os.listdir(root_dir)\n\n for dataset in dataset_list:\n print(dataset)\n\n img_folder_dir = os.path.join(root_dir, dataset, \"JPEGImages\")\n anno_folder_dir = os.path.join(root_dir, dataset, \"Annotations\")\n\n save_root_dir = os.path.join(root_dir, dataset, \"aug\")\n img_save_root = os.path.join(save_root_dir, \"JPEGImages\")\n anno_save_root = os.path.join(save_root_dir, \"Annotations\")\n\n if not os.path.isdir(img_save_root):\n os.makedirs(img_save_root)\n\n if not os.path.isdir(anno_save_root):\n os.makedirs(anno_save_root)\n\n img_list = os.listdir(img_folder_dir)\n\n for img_name in img_list:\n img_dir = os.path.join(img_folder_dir, img_name)\n anno_dir = os.path.join(anno_folder_dir, img_name[:-4]+ \".xml\")\n\n bboxes = np.array(read_xml(anno_dir))\n img = cv2.imread(img_dir)[:, :, ::-1]\n data_augment(img, bboxes, img_name, save_root_dir, aug_times=3)\n\n\n\n\n\n\n\n\n\n\n","sub_path":"generate_aug_data.py","file_name":"generate_aug_data.py","file_ext":"py","file_size_in_byte":9290,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"185039275","text":"# %%\n# VScodeで入力をテキストから読み込んで標準入力に渡す\nimport sys\nimport os\nf=open(r'.\\D141\\D141.txt', 'r', encoding=\"utf-8\")\n# inputをフルパスで指定\n# win10でファイルを作るとs-jisで保存されるため、読み込みをutf-8へエンコードする必要あり\n# VScodeでinput file開くとutf8になってるんだけど中身は結局s-jisになっているらしい\nsys.stdin=f\n\n#\n# 入力スニペット\n# num = int(input())\n# num_list = [int(item) for item in input().split()]\n# num_list = [input() for _ in range(3)]\n##################################\n# %%\n# 以下ペースト可\nimport heapq as hp\nN, M = [int(item) for item in input().split()]\nprice_list = sorted([-1 * int(item) for item in input().split()])\n\ntotal_m = 0\n\ndef discount(price_list, ticket_num):\n total_ticket =0\n hp.heapify(price_list)\n\n while total_ticket < ticket_num:\n temp = hp.heappop(price_list)\n hp.heappush(price_list, -1* (-1*temp//2))\n total_ticket += 1\n\n return price_list\n\nres = discount(price_list, M)\nprint(res)\nprint(-1 * sum(res))","sub_path":"D141/D141.py","file_name":"D141.py","file_ext":"py","file_size_in_byte":1101,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"446561635","text":"from discord.ext import commands\nfrom BotUtils import REST, getAPIKey, isURL\nfrom datetime import datetime\nimport discord\n\nclass OCR(commands.Cog):\n def __init__(self, bot):\n self.bot = bot\n\n langs = {\n 'arabic': 'ara',\n 'bulgarian':'bul',\n 'chinese': 'chs',\n 'chinese(traditional)': 'cht',\n 'croatian': 'hrv',\n 'czech': 'cze',\n 'danish': 'dan',\n 'dutch': 'dut',\n 'english': 'eng',\n 'finnish': 'fin',\n 'french': 'fre',\n 'german': 'ger',\n 'greek': 'gre',\n 'hungarian': 'hun',\n 'korean': 'kor',\n 'italian': 'ita',\n 'japanese': 'jpn',\n 'polish': 'pol',\n 'portuguese': 'por',\n 'russian': 'rus',\n 'slovenian': 'slv',\n 'spanish': 'spa',\n 'swedish': 'swe',\n 'turkish': 'tur'\n }\n\n def getLang(self, lang: str) -> str:\n if lang in self.langs.values():\n return lang\n\n if lang in self.langs:\n return self.langs[lang]\n \n raise commands.ArgumentParsingError('Invalid language.')\n \n @commands.command(name='ocrlangs', aliases=['ocrlanguages'])\n async def ocrlangs(self, ctx):\n \"\"\"Shows supported ocr languages\"\"\"\n await ctx.reply('```'+'\\n'.join(self.langs.keys())+'```')\n\n @commands.command(name='ocr')\n async def OCRSPACE(self, ctx, *, args=None):\n \"\"\"ocr.space engine V1. Results not what you expected? Try ocr2 command.\n\n args = [link] [language]\n or args = [language] if image as attachment\n or args = [link] if language is english\n args can also be empty if language is english (default) and image in attachment\n \n Use ocrlangs command to see supported languages.\n \"\"\"\n if args:\n args = args.split(' ')\n else:\n args = []\n \n if '-v2' in args:\n engine = 2\n del args[-1]\n\n lang = 'eng'\n\n if not args and len(ctx.message.attachments) == 0:\n raise commands.MissingRequiredArgument(args)\n elif not args:\n link = ctx.message.attachments[0].url\n elif isURL(args[0]):\n link = args[0]\n else:\n raise commands.ArgumentParsingError()\n else:\n engine = 1\n\n if not args and len(ctx.message.attachments) == 0:\n raise commands.MissingRequiredArgument(args)\n elif not args:\n link = ctx.message.attachments[0].url\n lang = 'eng'\n elif isURL(args[0]) and len(args) == 1:\n link = args[0]\n lang = 'eng'\n elif len(args) == 1 and len(ctx.message.attachments) != 0:\n link = ctx.message.attachments[0].url\n lang = self.getLang(args[0])\n elif len(args) == 2 and isURL(args[0]):\n link = args[0]\n lang = self.getLang(args[1])\n elif len(args) == 2 and isURL(args[1]):\n lang = self.getLang(args[0])\n link = args[1]\n else:\n raise commands.ArgumentParsingError()\n\n data = await REST('https://api.ocr.space/parse/image', method='POST', headers={'apikey': getAPIKey('ocrspace')}, data={'url': link, 'language': lang, 'OCREngine': engine})\n\n if data['OCRExitCode'] != 1:\n await ctx.reply(f\"`{data['ErrorMessage']}`\")\n else:\n await ctx.reply(f\"```{data['ParsedResults'][0]['ParsedText']} ```\")\n\n @commands.command(name='ocr2')\n async def OCRSPACE2(self, ctx, *, args=None):\n f\"\"\"ocr.space engine V2. Results not what you expected? Try ocr command.\n V2 engine only supports latin characters, but is better at detecting numbers, special characters and rotated text.\n\n args = [link]\n args can also be empty if image in attachment\n \"\"\"\n if args:\n args += ' -v2'\n else:\n args = '-v2'\n await ctx.invoke(self.OCRSPACE, args=args)\n\n\ndef setup(bot):\n bot.add_cog(OCR(bot))","sub_path":"cogs/apis/ocr.py","file_name":"ocr.py","file_ext":"py","file_size_in_byte":4134,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"254476085","text":"from tdw.librarian import MaterialLibrarian, ModelLibrarian\nfrom tdw.tdw_utils import TDWUtils\nfrom tdw.controller import Controller\nfrom tdw.output_data import Bounds, Images\n\n\nclass ProcGenInteriorDesign(Controller):\n\n def run(self):\n self.start()\n init_setup_commands = [{\"$type\": \"set_screen_size\",\n \"width\": 600,\n \"height\": 480},\n {\"$type\": \"set_render_quality\",\n \"render_quality\": 5}]\n self.communicate(init_setup_commands)\n\n # Create an empty room.\n self.communicate({\"$type\": \"create_empty_environment\",\n \"center\": {\"x\": 0, \"y\": 0, \"z\": 0},\n \"bounds\": {\"x\": 8, \"y\": 8, \"z\": 8}})\n self.communicate({\"$type\": \"set_gravity\",\n \"value\": False})\n\n cube_record = ModelLibrarian(\"models_special.json\").get_record(\"prim_cube\")\n self.communicate({\"$type\": \"add_object\",\n \"name\": \"prim_cube\",\n \"url\": cube_record.get_url(),\n \"scale_factor\": cube_record.scale_factor,\n \"position\": {\"x\": 0, \"y\": 0, \"z\": 0},\n \"rotation\": {\"x\": 0, \"y\": 0, \"z\": 0},\n \"category\": cube_record.wcategory,\n \"id\": 1})\n\n self.communicate({\"$type\": \"scale_object\",\n \"scale_factor\": {\"x\": 30, \"y\": 0.0001, \"z\": 30},\n \"id\": 1})\n\n # Add the avatar.\n self.communicate(TDWUtils.create_avatar(position={\"x\": 0, \"y\": 0.6, \"z\": 0},\n look_at=TDWUtils.array_to_vector3([0.5, 0.5, 0]),\n avatar_id=\"avatar\"))\n\n self.communicate(self.get_add_hdri_skybox(\"table_mountain_1_4k\"))\n self.communicate({\"$type\": \"rotate_hdri_skybox_by\", \"angle\": 90})\n\n lib = MaterialLibrarian(library=\"materials_med.json\")\n record = lib.get_record(\"bricks_chatham_gray_used\")\n self.communicate({\"$type\": \"add_material\", \"name\": \"bricks_chatham_gray_used\", \"url\": record.get_url()})\n self.communicate(TDWUtils.set_visual_material(c=self, substructure=cube_record.substructure, object_id=1,\n material=\"bricks_chatham_gray_used\"))\n\n # self.communicate({\"$type\": \"set_field_of_view\",\n # \"field_of_view\": 68.0,\n # \"avatar_id\": \"avatar\"})\n\n bench = self.add_object(model_name=\"b04_wood_metal_park_bench\",\n position={\"x\": 2, \"y\": 0, \"z\": 0.5},\n rotation={\"x\": 0, \"y\": -90, \"z\": 0},\n library=\"models_full.json\")\n\n self.add_object(model_name=\"b04_wood_metal_park_bench\",\n position={\"x\": 5, \"y\": 0, \"z\": 0.5},\n rotation={\"x\": 0, \"y\": -90, \"z\": 0},\n library=\"models_full.json\")\n\n bench_bounds = self.get_bounds_data(bench)\n top = bench_bounds.get_top(0)\n\n self.add_object(model_name=\"cgaxis_models_65_06_vray\",\n position={\"x\": 1.8, \"y\": top[1] - 0.42, \"z\": 0.35},\n rotation={\"x\": 0, \"y\": 0, \"z\": 0},\n library=\"models_full.json\")\n\n # Enable image capture\n self.communicate({\"$type\": \"set_pass_masks\",\n \"avatar_id\": \"avatar\",\n \"pass_masks\": [\"_img\", \"_id\"]})\n\n self.communicate({\"$type\": \"send_images\",\n \"frequency\": \"always\"})\n\n scene_data = self.communicate({\"$type\": \"look_at_position\",\n \"avatar_id\": \"avatar\",\n \"position\": TDWUtils.array_to_vector3([0.5, 0.5, 0])})\n\n images = Images(scene_data[0])\n TDWUtils.save_images(images, \"bench_book\",\n output_directory=\"/Users/leonard/Desktop/TDWBase-1.5.0/Python/Leonard/compare_COCO_TDW/replicated_images/exterior\")\n\n def get_bounds_data(self, object_id):\n resp = self.communicate({\"$type\": \"send_bounds\",\n \"frequency\": \"once\",\n \"ids\": [object_id]})\n return Bounds(resp[0])\n\n\nif __name__ == \"__main__\":\n ProcGenInteriorDesign().run()\n","sub_path":"compare_COCO_TDW/exterior/bench_book.py","file_name":"bench_book.py","file_ext":"py","file_size_in_byte":4523,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"224904881","text":"import os\nsource_path='/home/dl/Downloads/indoorCVPR_09/images/'\ntarget_path='/home/dl/Downloads/indoorCVPR_09/images1/'\n\ni=0\nfor img in sorted(os.listdir(source_path)):\n i=i+1\n name=os.path.splitext(img)\n img_segment=name[0]\n org_name=os.path.join(source_path,img)\n \n changed_name=target_path+str(i)+'.jpg'\n \n \n os.rename(org_name,changed_name)","sub_path":"process_pic/modifyname.py","file_name":"modifyname.py","file_ext":"py","file_size_in_byte":376,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"123584034","text":"from winreg import *\r\n\r\ndef regwrite(alias, path):\r\n aReg = ConnectRegistry(None, HKEY_LOCAL_MACHINE)\r\n aKey = OpenKey(aReg, r\"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run\")\r\n aKey = OpenKey(aReg, r\"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run\", 0, KEY_WRITE)\r\n SetValueEx(aKey, alias, 0, REG_SZ, path)\r\n CloseKey(aKey)\r\n CloseKey(aReg)\r\n\r\n","sub_path":"regwrite.py","file_name":"regwrite.py","file_ext":"py","file_size_in_byte":360,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"299242663","text":"import os\nimport sys\nimport numpy as np\nfrom keras.preprocessing.image import load_img, img_to_array\nimport pickle as pck\nfrom keras.utils import np_utils, generic_utils\nimport shutil\nclass imageForMacroBatches:\n\tdef __init__(self,image,label):\n\t\tself.image = image\n\t\tself.label = label\n\n\n#AMOUNT OF IMAGES PER MACROBATCH = 5000\n#HENCE THERE WILL BE 257 FOLDER\n\nimagesPaths = list()\ntrainingDataPath = '/Volumes/data2/ImageNetTrain/ILSVRC2015/Data/CLS-LOC/train/'\ndirOfMacroBatches = '/Volumes/data2/ImageNetTrain/ILSVRC2015/Data/CLS-LOC/macrobatchesTrain/'\nlabelsDict = dict()\nfoldersToLoad = os.listdir(trainingDataPath)\ni = 0\nprogbar = generic_utils.Progbar(len(foldersToLoad))\nfor currentFolder in foldersToLoad:\n\tcurrentImagesPaths = os.listdir(trainingDataPath + currentFolder)\n\tfor currentImagePath in currentImagesPaths:\n\t\timagesPaths.append(currentFolder + '/' +currentImagePath)\n\tprogbar.add(1)\n\tlabelsDict[currentFolder] = i\n\ti += 1\ncurrentPklFile = open(dirOfMacroBatches + 'labelsDict.pkl', 'w')\npck.dump(labelsDict,currentPklFile)\ncurrentPklFile.close()\nimagesPaths = np.asarray(imagesPaths)\npermutation = np.random.permutation(len(imagesPaths))\nimagesPaths = imagesPaths[permutation]\n\nimagesPathsIter = iter(imagesPaths)\n#CREATE OBJECTS AND TAR THEM INTO MACROBATCHES\nnumberOfMacroBatches = np.ceil(len(imagesPaths)/5000.)\n\nprogbar = generic_utils.Progbar(numberOfMacroBatches)\nfor i in range(int(numberOfMacroBatches)):\n\tos.mkdir(dirOfMacroBatches + 'macrobatch' + str(i))\n\tcurrentMacroBatch = list()\n\tfor j in range(5000):\n\t\tcurrentPath = next(imagesPathsIter,None)\n\t\tif(currentPath != None):\n\t\t\tshutil.copy2(trainingDataPath+currentPath,dirOfMacroBatches+'macrobatch'+str(i))\n\t\t# if(currentPath != None):\n\t\t# \tcurrentMacroBatch.append(imageForMacroBatches(img_to_array(load_img(trainingDataPath + currentPath)),labelsDict[currentPath[0:9]]))\n\t\t# else:\n\t\t# \tbreak\t\n\t\t#CREATE OBJECT\n\t\t# if(currentPath != None):\n\t\t# \tcurrentObject = imageForMacroBatches(img_to_array(load_img(trainingDataPath + currentPath)),labelsDict[currentPath[0:9]])\n\t\t# \tcurrentPklFile = open(dirOfMacroBatches + 'macrobatch' + str(i) + '/' + str(j) + '.pkl', 'w')\n\t\t# \tpck.dump(currentObject,currentPklFile)\n\t\t# \tcurrentPklFile.close()\n\t\t# else:\n\t\t# \tbreak\n\t\telse:\n\t\t\tbreak\n\tprogbar.add(1)\nprint('Done')\n\t# currentPklFile = open(dirOfMacroBatches + str(i) + '.pkl', 'w')\n\t# pck.dump(currentMacroBatch,currentPklFile)\n\t# currentPklFile.close()\n\t\n\n\n\n\t","sub_path":"PhD_Experiments/ImageNet/generateMacroBatches.py","file_name":"generateMacroBatches.py","file_ext":"py","file_size_in_byte":2439,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"593441437","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[1]:\n\n\nimport tensorflow as tf\nfrom tensorflow import keras\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom PIL import Image\n\nimport os\n\nimport UTKFaceLoader128_v2\n\n\n# In[2]:\n# In[10]:\n\n\ndef saveSample(generator, outputDirectory, epochs, sampleDirectory = '../../Datasets/UTKSelectedSamples'):\n if not os.path.exists(outputDirectory):\n os.mkdir(outputDirectory)\n \n if not os.path.exists(sampleDirectory):\n print('****** ERROR ****** \\\"' + sampleDirectory + '\\\" cannot found.')\n return\n \n # Sort the file\n tempList = os.listdir(sampleDirectory)\n for i in range(len(tempList)):\n temp = tempList[i].split('_')\n tempList[i] = int(temp[0]) * 10000 + int(temp[1]) * 10 + int(temp[2])\n posList = []\n for i in range(len(tempList)):\n posList.append(i)\n tempDict = dict(zip(tempList, posList))\n oList = os.listdir(sampleDirectory)\n imageList = os.listdir(sampleDirectory)\n tempList = sorted(tempList)\n for i in range(len(tempList)):\n imageList[i] = oList[tempDict[tempList[i]]]\n images = []\n for i in imageList:\n img = Image.open(sampleDirectory + '/' + i)\n img = img.resize((128, 128))\n img = np.array(img)\n img = img / 127.5 - 1.0\n images.append(img)\n ages = [0, 8, 15, 25, 35, 45, 55, 65, 75, 85]\n \n \n \n # Save as figure\n counter = 0\n y = len(imageList)\n x = 1 + len(ages)\n \n fig = plt.figure()\n \n for j in range(y):\n for i in range(x):\n counter = counter + 1\n plt.subplot(y, x, counter)\n plt.axis('off')\n \n if i == 0:\n if j == 0:\n plt.title('Original', fontsize=6)\n plt.imshow(images[j] * 0.5 + 0.5)\n else:\n if j == 0:\n plt.title(UTKFaceLoader128_v2.getAgeGroupLabel(ages[i - 1]), fontsize=6)\n # Generated image\n genImage = generator([np.expand_dims(images[j], 0), np.expand_dims(UTKFaceLoader128_v2.ageToOnehot(ages[i - 1]), 0)])[0]\n plt.imshow(genImage * 0.5 + 0.5)\n \n plt.savefig(outputDirectory + '/epoch_' + str(epochs) + '.jpg', dpi=300)\n plt.close()\n\n","sub_path":"SourceCode/SampleSaver.py","file_name":"SampleSaver.py","file_ext":"py","file_size_in_byte":2286,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"226296297","text":"'''\n\nSay you have an array for which the ith element is the price of a given stock on day i.\n\nIf you were only permitted to complete at most one transaction (i.e., buy one and sell one share of the stock), design an algorithm to find the maximum profit.\n\nNote that you cannot sell a stock before you buy one.\n\nExample 1:\n\nInput: [7,1,5,3,6,4]\nOutput: 5\nExplanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.\n Not 7-1 = 6, as selling price needs to be larger than buying price.\nExample 2:\n\nInput: [7,6,4,3,1]\nOutput: 0\nExplanation: In this case, no transaction is done, i.e. max profit = 0.\n\n'''\n\n'''\nsolution 1, 2 time limit exceed\n\nclass Solution:\n def maxProfit(self, prices):\n \"\"\"\n :type prices: List[int]\n :rtype: int\n \"\"\"\n nb = len(prices)\n maxprice = 0\n for i in range(nb - 1):\n temp = max(prices[i + 1:nb]) - prices[i]\n if temp > maxprice:\n maxprice = temp\n return maxprice\n\n\nclass Solution:\n def maxProfit(self, prices):\n \"\"\"\n :type prices: List[int]\n :rtype: int\n \"\"\"\n nb = len(prices)\n maxprice = 0\n for i in range(nb):\n for j in range(i+1,nb):\n temp=prices[j]-prices[i]\n if temp>maxprice:\n maxprice=temp\n return maxprice\n'''\n\n#200 / 200 test cases passed. Runtime: 40 ms\n# your runtime beats 100% of python 3 submissions.\n\nclass Solution:\n def maxProfit(self, prices):\n \"\"\"\n :type prices: List[int]\n :rtype: int\n \"\"\"\n nb = len(prices)\n maxprofit = 0\n minprice=float('Inf')\n for i in range(nb):\n if prices[i]maxprofit:\n maxprofit=prices[i]-minprice\n return maxprofit\n\n\n# cpp, dp\n'''\nclass Solution {\npublic:\n int maxProfit(vector& prices) {\n if (prices.empty()) return 0;\n int res = 0, prevMin = prices[0];\n for (int i = 1; i < prices.size(); ++i) {\n res = max(res, prices[i] - prevMin);\n prevMin = min(prices[i], prevMin);\n }\n return res;\n \n }\n};\n\n'''\n\n# 2020/05/05, dp\n\n'''\nRuntime: 72 ms, faster than 26.78% of Python3 online submissions for Best Time to Buy and Sell Stock.\nMemory Usage: 15.1 MB, less than 5.75% of Python3 online submissions for Best Time to Buy and Sell Stock.\n'''\n\nclass Solution:\n def maxProfit(self, prices: List[int]) -> int:\n res = 0\n curr_min = float(\"inf\")\n for i in range(1, len(prices)):\n curr_min = min(curr_min, prices[i - 1])\n res = max(res, prices[i] - curr_min)\n return res\n\n","sub_path":"0121. maxProfit.py","file_name":"0121. maxProfit.py","file_ext":"py","file_size_in_byte":2783,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"126946335","text":"# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\nfrom collections import deque\nclass Solution:\n def hasPathSum(self, root, sum):\n \"\"\"\n :type root: TreeNode\n :type sum: int\n :rtype: bool\n \"\"\"\n if not root:\n return False\n lookup_parent = {root: None}\n traversal_queue = deque([root])\n leaves = []\n while len(traversal_queue) > 0:\n node = traversal_queue.popleft()\n if node.left:\n lookup_parent[node.left] = node\n traversal_queue.append(node.left)\n if node.right:\n lookup_parent[node.right] = node\n traversal_queue.append(node.right)\n if not node.left and not node.right:\n leaves.append(node)\n for n in leaves:\n sum_val = 0\n while n is not None:\n sum_val += n.val\n n = lookup_parent[n]\n if sum_val == sum:\n return True\n return False","sub_path":"100-200/112_path_sum.py","file_name":"112_path_sum.py","file_ext":"py","file_size_in_byte":1137,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"169672889","text":"from wwo_hist import retrieve_hist_data\n\n## based on one day\nFREQUENCY = 24\nSTART_DATE = '01-Jan-2017'\nEND_DATE = '31-DEC-2018'\n## set the API_KEY\nAPI_KEY = '2326f955e1854e48b2205957200512'\nLOCATION_LIST = ['hongkong']\n\n# stroed in .csv format\nhist_weather_data = retrieve_hist_data(API_KEY,\n LOCATION_LIST,\n START_DATE,\n END_DATE,\n FREQUENCY,\n location_label = False,\n export_csv = True,\n store_df = True)\n\n# cp /usr/local/lib/python3.6/dist-packages/wwo_hist/__init__.py .","sub_path":"download_wwo.py","file_name":"download_wwo.py","file_ext":"py","file_size_in_byte":747,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"627247852","text":"\n#%%\nfrom matplotlib.pyplot import imshow, show\nfrom PIL import Image\nimport numpy as np\nimport skimage.color as sc\n\n\n#%%\nimg = np.array(Image.open(\"E:\\philongg2000-OneDrive\\OneDrive\\Pictures\\Saved Pictures\\935873.jpg\"))\nimshow(img)\n # Convert colored image to gray image\nimg_mono = sc.rgb2gray(img)\nimshow(img_mono, cmap = 'gray')\n\n\n#%%\ndef img_histogram(img):\n import matplotlib.pyplot as plt\n fig = plt.figure(figsize = (8, 6))\n fig.clf()\n ax = fig.gca()\n ax.hist(img.flatten(), bins = 256)\n plt.show()\nimg_histogram(img_mono)\n\n\n#%%\ndef img_cdf(img): # cdf = Cumulative Distribution Function\n import matplotlib.pyplot as plt\n fig = plt.figure(figsize = (8, 6))\n fig.clf()\n ax = fig.gca()\n ax.hist(img.flatten(), bins = 256, cumulative = True)\n plt.show()\nimg_cdf(img_mono)\n\n\n#%%\nfrom skimage import exposure\n\nimg_equalized = exposure.equalize_hist(img_mono)\nimshow(img_equalized, cmap = 'gray')\n\n\n#%%\nimg_histogram(img_equalized)\nimg_cdf(img_equalized)\n\n\n#%%\nimport skimage\nimg_noise = skimage.util.random_noise(img_equalized)\nimshow(img_noise)\n\n\n#%%\ndef gauss_filter(img, sigma = 10):\n from scipy.ndimage.filters import gaussian_filter as gf\n import numpy as np\n return gf(img, sigma = sigma)\nimg_gauss = gauss_filter(img_noise)\nimshow(img_gauss, cmap = 'gray')\n\n\n#%%\ndef median_fiter(img, size = 10):\n from scipy.ndimage.filters import median_filter as mf\n import numpy as np\n return mf(img, size = size)\nimg_median = median_fiter(img_noise)\nimshow(img_median, cmap = 'gray')\n\n\n#%%\ndef edge_sobel(img):\n from scipy import ndimage\n import skimage.color as sc\n import numpy as np\n\n # Convert color image to grey scale\n img = sc.rgb2grey(img)\n # Horizontal derivative\n dx = ndimage.sobel(img, 1)\n # Vertivcal derivative\n dy = ndimage.sobel(img, 0)\n # Magnitude\n mag = np.hypot(dx, dy)\n # Normalize Q&D\n mag *= 255.0 / np.amax(mag)\n mag = mag.astype(np.uint8)\n\n return mag\nimg_edge = edge_sobel(img_median)\nimshow(img_edge, cmap = \"gray\")\n\n\n#%%\ndef corner_harr(img, min_distance = 10):\n from skimage.feature import corner_harris, corner_peaks\n mag = corner_harris(img)\n\n return corner_peaks(mag, min_distance = min_distance)\n\nimg_harris = corner_harr(img_equalized, 10)\n\n\n#%%\ndef plot_harris(img, harris_img, markersize = 20, color = \"red\"):\n import matplotlib.pyplot as plt\n import numpy as np\n\n fig = plt.figure(figsize = (6, 6))\n fig.clf()\n\n ax = fig.gca()\n ax.imshow(np.array(img).astype(float), cmap = \"gray\")\n ax.plot(harris_img[:, 1], harris_img[:, 0], \"r+\", color = color, markersize = markersize)\n \n return \"Done\"\n\nplot_harris(img_equalized, img_harris)\n\n\n#%%\n\n\n\n","sub_path":"FULL.py","file_name":"FULL.py","file_ext":"py","file_size_in_byte":2731,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"289110947","text":"import argparse\nimport psycopg2\nfrom blockserver.backend.database import PostgresUserDatabase\n\n\ndef _connect(dsn):\n connection = psycopg2.connect(dsn)\n db = PostgresUserDatabase(connection)\n return db\n\n\ndef initdb(dsn):\n db = _connect(dsn)\n db.init_db()\n\n\ndef dropdb(dsn):\n db = _connect(dsn)\n db.drop_db()\n\n\ndef parse_args(arguments):\n parser = argparse.ArgumentParser(description='Manage qabel-block')\n parser.add_argument('action', choices=('initdb', 'dropdb'))\n parser.add_argument('--psql-dsn', metavar='DSN', required=True)\n return parser.parse_args(arguments)\n\n\ndef main(arguments=None):\n args = parse_args(arguments)\n if args.action == 'initdb':\n initdb(args.psql_dsn)\n elif args.action == 'dropdb':\n dropdb(args.psql_dsn)\n\nif __name__ == '__main__':\n main()\n\n\n\n","sub_path":"src/manage.py","file_name":"manage.py","file_ext":"py","file_size_in_byte":829,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"298522484","text":"# coding=utf-8\nimport xml.etree.cElementTree\nfrom ..common import conf\nfrom ..common import logoutput\nclass XmlOperation():\n \"\"\"\n 操作Xml文件\n \"\"\"\n def __init__(self):\n self.lg=logoutput.Logger()\n def get_xml_data(self, page, element):\n CONF_NAME_XMLPATH=\"XmlPath\"\n CONF_PATH=\"path\"\n '''\n 获取xml数据,传入二级节点名称,三级节点名称,xml文件路径,以字典格式返回\n :param page:二级页面名称\n :param element:元素名称\n :param path:xml文件地址\n :return: 返回元素信息\n '''\n try:\n cf=conf.Conf()\n self.lg.info(\"从配置文件获取xml地址\")\n p=cf.get_conf_data(CONF_NAME_XMLPATH)\n x = xml.etree.cElementTree.parse(p[CONF_PATH])\n root = x.getroot()\n self.lg.info(\"获取节点信息\")\n a = root.find(page)\n b = a.find(element)\n return b.attrib\n except Exception as e:\n self.lg.error(e)\n\n# x = XmlOperation()\n# a = x.get_xml_data(\"index\", \"usr_in\", r\"D:\\svn\\Test\\自动化测试\\frame\\UItest\\code\\demo\\demo\\object\\fzbd.xml\")\n# print(a)\n","sub_path":"common/xml.py","file_name":"xml.py","file_ext":"py","file_size_in_byte":1196,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"501088259","text":"import re\nimport scrapy\nfrom news_scraper.items import ArticleItem\nfrom news_scraper.settings import PROJECT_DIR\n\nclass ArticleSpider(scrapy.Spider):\n name = 'articles'\n\n def parse(self, response):\n page_id = re.search(r'ELEMENT_ID=(\\d+)', response.url).group(1)\n title = response.css('h1').extract_first()\n article_element = response.xpath(\"//div[@class='news-detail']\")\n\n text_parts = article_element.xpath(\".//text()\").extract()\n text_parts = [part.strip() for part in text_parts]\n text = ''.join(text_parts)\n\n image_url = article_element.xpath(\".//img/@src\").extract_first()\n image_url = ''.join(['http://gvardeysk.gov39.ru', image_url])\n\n item = ArticleItem()\n item['image_urls'] = [image_url]\n item['text'] = text\n\n f = open(PROJECT_DIR + \"assets/articles/article_\" + str(page_id) + \".txt\",\"w\")\n f.write(text)\n f.close()\n\n yield item","sub_path":"spiders/article_spider.py","file_name":"article_spider.py","file_ext":"py","file_size_in_byte":886,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"85705685","text":"\"\"\"\nGiven an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.\n\nExample:\n\nInput: [-2,1,-3,4,-1,2,1,-5,4],\nOutput: 6\nExplanation: [4,-1,2,1] has the largest sum = 6.\nFollow up:\n\nIf you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.\n\"\"\"\ndef solution(nums):\n prev_sum = []\n cur_sum = 0\n for i in range(len(nums)):\n prev_sum.append(cur_sum)\n # print(i,cur_sum)\n # print(prev_sum)\n if cur_sum < nums[i]:\n cur_sum = 0\n cur_sum += nums[i]\n return max(prev_sum)\n\ndef solution2(nums):\n cur_sum = nums[0]\n max_sum = nums[0]\n\n for i in range(1,len(nums)):\n cur_sum = max(cur_sum+nums[i],nums[i])\n max_sum = max(cur_sum,max_sum)\n return max_sum\n\nnums = [-2,1,-3,4,-1,2,1,-5,4]\nprint(solution2(nums))","sub_path":"daily-coding-challenge/03042020.py","file_name":"03042020.py","file_ext":"py","file_size_in_byte":928,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"203895410","text":"import tensorflow as tf\nimport numpy as np\n\nfrom model.model_base import PredictionModel\n\n\n# tf.set_random_seed(999)\n\n\nclass FactorizationMachines(PredictionModel):\n def __init__(self, n_fields, n_features, embedding_size, l2_beta=0.01, learning_rate=0.01, dropout=None, n_epochs=20, batch_size=5000, plot_loss=False):\n super().__init__()\n\n # n_fields表示特征未经过one-hot拓展的总量\n # n_features表示特征经过one-hot拓展后的总量\n self.n_fields = n_fields\n self.n_features = n_features\n self.embedding_size = embedding_size\n\n self.l2_beta = l2_beta\n self.learning_rate = learning_rate\n self.dropout = [1.0, 1.0] if dropout is None else dropout\n self.n_epochs = n_epochs\n self.batch_size = batch_size\n\n self._build_net()\n self.sess = tf.Session()\n self.sess.run(tf.global_variables_initializer())\n\n self.loss_trace = []\n self.plot_loss = plot_loss\n\n def _build_net(self):\n self.feat_idx = tf.placeholder(tf.int32, [None, self.n_fields])\n self.feat_val = tf.placeholder(tf.float32, [None, self.n_fields])\n self.label = tf.placeholder(tf.float32, [None, 1])\n self.o1_dropout = tf.placeholder(tf.float32)\n self.o2_dropout = tf.placeholder(tf.float32)\n\n # init weights\n self.o2_weights = tf.Variable(tf.truncated_normal([self.n_features, self.embedding_size]))\n self.o1_weights = tf.Variable(tf.truncated_normal([self.n_features, 1]))\n self.bias = tf.Variable(tf.truncated_normal([1, 1]))\n\n # first order term\n # (None, n_fields, embedding_size=1)\n o1_feat_weights = tf.nn.embedding_lookup(self.o1_weights, self.feat_idx)\n # (None, n_fields, 1)\n feat_val = tf.reshape(self.feat_val, shape=[-1, self.n_fields, 1])\n # (None, n_fields, embedding_size=1)\n o1_feat_emb = tf.multiply(o1_feat_weights, feat_val)\n # (None, 1)\n o1_term = tf.reduce_sum(o1_feat_emb, 1) + self.bias\n o1_term = tf.nn.dropout(o1_term, rate=1-self.o1_dropout)\n\n # second order term\n # (None, n_fields, embedding_size)\n o2_feat_weights = tf.nn.embedding_lookup(self.o2_weights, self.feat_idx)\n # (None, n_fields, embedding_size)\n o2_feat_emb = tf.multiply(o2_feat_weights, feat_val)\n\n # square of sum\n # (None, embedding_size)\n square_of_sum = tf.square(tf.reduce_sum(o2_feat_emb, 1))\n\n # sum of square\n # (None, embedding_size)\n sum_of_square = tf.reduce_sum(tf.square(o2_feat_emb), 1)\n\n # (None, 1)\n o2_term = 0.5 * tf.reduce_sum(square_of_sum - sum_of_square, axis=1)\n o2_term = tf.reshape(o2_term, shape=[-1, 1])\n o2_term = tf.nn.dropout(o2_term, rate=1-self.o2_dropout)\n\n self.reg_val = o1_term + o2_term\n self.reg_proba = tf.sigmoid(self.reg_val)\n self.reg_label = tf.round(self.reg_proba)\n # correct_count = tf.cast(tf.equal(self.reg_label, self.y), dtype=tf.float32)\n # self.acc = tf.reduce_mean(correct_count)\n\n self.loss = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits=self.reg_val, labels=self.label)) \\\n + self.l2_beta * tf.nn.l2_loss(self.o1_weights) + self.l2_beta * tf.nn.l2_loss(self.o2_weights)\n self.global_step = tf.Variable(0, trainable=False)\n learning_rate = tf.train.exponential_decay(self.learning_rate, self.global_step, 1000, 0.96, staircase=True)\n # Passing global_step to minimize() will increment it at each step.\n self.train_op = tf.train.AdamOptimizer(learning_rate).minimize(self.loss, global_step=self.global_step)\n\n def fit(self, x_data, y_data):\n assert (isinstance(x_data, tuple))\n (x_data_fi, x_data_fv) = x_data\n\n index_list = np.tile(np.arange(x_data_fi.shape[0]), self.n_epochs)\n np.random.shuffle(index_list)\n n_batches = int(np.ceil(x_data_fi.shape[0] * self.n_epochs * 1.0 / self.batch_size))\n\n for i in range(n_batches):\n start = self.batch_size * i\n end = self.batch_size * (i + 1) if self.batch_size * (i + 1) < x_data_fi.shape[0] * self.n_epochs else x_data_fi.shape[0] * self.n_epochs\n x_data_fi_batch = x_data_fi[index_list[start: end]]\n x_data_fv_batch = x_data_fv[index_list[start: end]]\n y_data_batch = y_data[index_list[start: end]].reshape(-1, 1)\n\n _, cur_loss = self.sess.run([self.train_op, self.loss],\n feed_dict={self.feat_idx: x_data_fi_batch,\n self.feat_val: x_data_fv_batch,\n self.label: y_data_batch,\n self.o1_dropout: self.dropout[0],\n self.o2_dropout: self.dropout[1]})\n self.loss_trace.append(cur_loss)\n\n if (i + 1) % 100 == 0 or i == n_batches - 1:\n print('batch: {}/{}\\tloss: {:8f}'.format(i + 1, n_batches, cur_loss))\n if self.plot_loss:\n import matplotlib.pyplot as plt\n plt.plot(self.loss_trace)\n plt.title('Cross Entropy Loss')\n plt.xlabel('batch')\n plt.ylabel('loss')\n plt.show()\n\n def predict_proba(self, x_data):\n assert (isinstance(x_data, tuple))\n (x_data_fi, x_data_fv) = x_data\n return self.sess.run(self.reg_proba, feed_dict={self.feat_idx: x_data_fi,\n self.feat_val: x_data_fv,\n self.o1_dropout: 1.0,\n self.o2_dropout: 1.0})\n\n def predict_label(self, x_data):\n assert (isinstance(x_data, tuple))\n (x_data_fi, x_data_fv) = x_data\n return self.sess.run(self.reg_label, feed_dict={self.feat_idx: x_data_fi,\n self.feat_val: x_data_fv,\n self.o1_dropout: 1.0,\n self.o2_dropout: 1.0})\n\n def cal_loss(self, x_data, y_data):\n assert (isinstance(x_data, tuple))\n (x_data_fi, x_data_fv) = x_data\n y_data = y_data.reshape(-1, 1)\n\n return self.sess.run(self.loss, feed_dict={self.feat_idx: x_data_fi,\n self.feat_val: x_data_fv,\n self.label: y_data,\n self.o1_dropout: 1.0,\n self.o2_dropout: 1.0})\n\n def save_model(self, path):\n with self.sess.as_default():\n o2_weights = self.o2_weights.eval().reshape([self.n_features, self.embedding_size])\n o1_weights = self.o1_weights.eval().reshape([-1])\n bias = self.bias.eval().reshape([-1])\n with open(path, 'w') as fd:\n for i in range(0, self.n_features):\n for j in range(0, self.embedding_size):\n fd.write('{:.8f} '.format(o2_weights[i, j]))\n fd.write('\\n')\n fd.write('\\n')\n for i, w in enumerate(o1_weights):\n fd.write('{:.8f}\\n'.format(w))\n fd.write('\\n')\n fd.write('{:.8f}\\n'.format(bias[0]))\n\n\nif __name__ == '__main__':\n from sklearn import datasets\n from sklearn.model_selection import train_test_split\n from sklearn.preprocessing import label_binarize, StandardScaler\n from model.model_evaluation import evaluate_classification_model\n\n # ----- load some demo data -----\n iris = datasets.load_iris()\n x = iris.data[0:100, 0:4]\n y = iris.target[0:100]\n y = label_binarize(y, classes=[0, 1]).ravel()\n train_x, test_x, train_y, test_y = train_test_split(x, y, test_size=0.5, random_state=999)\n sc = StandardScaler()\n sc.fit(train_x)\n train_x_std = sc.transform(train_x)\n test_x_std = sc.transform(test_x)\n\n # ----- train model -----\n train_data_fi = np.tile(np.arange(0, train_x_std.shape[1]), train_x_std.shape[0]).reshape(train_x_std.shape[0],\n train_x_std.shape[1])\n train_data_fv = train_x_std\n train_x_std = (train_data_fi, train_data_fv)\n test_data_fi = np.tile(np.arange(0, test_x_std.shape[1]), test_x_std.shape[0]).reshape(test_x_std.shape[0],\n test_x_std.shape[1])\n test_data_fv = test_x_std\n test_x_std = (test_data_fi, test_data_fv)\n\n model = FactorizationMachines(n_fields=4, n_features=4, embedding_size=3, batch_size=5, plot_loss=True)\n model.fit(train_x_std, train_y)\n model.save_model('../output/lr.model')\n\n # ----- test model -----\n predict_y_proba = model.predict_proba(test_x_std)\n predict_y_label = model.predict_label(test_x_std)\n # for target, proba, predict in zip(test_y, predict_y_proba, predict_y_label):\n # print('{}: {} -> {}'.format(target, proba, predict))\n evaluate_classification_model(test_y, predict_y_label, predict_y_proba, plot_roc=False)\n","sub_path":"model/tensorflow/factorization_machines_tf.py","file_name":"factorization_machines_tf.py","file_ext":"py","file_size_in_byte":9391,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"18197406","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 ('rustic_cut', '0003_auto_20151225_2024'),\n ]\n\n operations = [\n migrations.RemoveField(\n model_name='product',\n name='category',\n ),\n migrations.AddField(\n model_name='product',\n name='categories',\n field=models.ManyToManyField(related_name='products', to='rustic_cut.Category', blank=True),\n preserve_default=True,\n ),\n ]\n","sub_path":"django/rustic_cut/rustic_cut/migrations/0004_auto_20151225_2054.py","file_name":"0004_auto_20151225_2054.py","file_ext":"py","file_size_in_byte":603,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"583102415","text":"from tkinter import *\nimport random\n\ntop = Tk()\ntop.title('Graphics')\ncanvas = Canvas(top, width=600, height=300, bg=\"black\")\ncanvas.grid(row=1, column=2)\nrect = canvas.create_rectangle(50, 50, 100, 150, fill=\"red\")\n\ndef japanFlag():\n coord = 200, 50, 400, 250\n arc = canvas.create_oval(coord, fill=\"red\")\n\n top.mainloop()\n\ndef diamond():\n c = Canvas(top, bg=\"white\", height=300, width=600)\n p = c.create_polygon(300, 0, 200, 100, 300, 200, 400, 100)\n r = c.create_rectangle(0, 0, 20, 40, fill=\"blue\")\n c.grid(row=1, column=2)\n top.mainloop()\n\ndef terc():\n tercSetup(10, 10)\n\ndef tercSetup(n, d):\n x1, y1 = 300 - n * d, 150 - n * d\n x2, y2 = 300 + n * d, 150 + n * d\n colors = ['red', 'blue', 'green', 'yellow', 'black']\n \n coord = x1, y1, x2, y2\n arc = canvas.create_oval(coord, fill=colors[-1])\n \n for i in range(n):\n x1, y1 = x1 + d, y1 + d\n x2, y2 = x2 - d, y2 - d\n coord = x1, y1, x2, y2\n r = lambda: random.randint(0,255)\n color = '#%02X%02X%02X' % (r(),r(),r())\n arc = canvas.create_oval(coord, fill=color)\n \n top.mainloop()\n \ndef des():\n canvas.delete(ALL)\n\nbutton = Button(top, text='Terc', width=25, command=terc) \nbutton.grid(row=1, column=1)\nbutton = Button(top, text='Japan', width=25, command=japanFlag) \nbutton.grid(row=2, column=1)\nbutton = Button(top, text='Diamond', width=25, command=diamond) \nbutton.grid(row=3, column=1)\n\ntop.mainloop() ","sub_path":"graphics.py","file_name":"graphics.py","file_ext":"py","file_size_in_byte":1463,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"277613284","text":"# this is my Information Gathering miniProject\nimport socket\nimport requests\nimport sys , os\nimport urllib.request\n\ntry:\n\tos.system(\"figlet infoGather\") #created in exception for some users where figlet isnot present\nexcept:\n\tpass\nprint(f\"\\nversion: v1.2\")\ntry:\n\tdomain = str(sys.argv[1])\n\tport = int(sys.argv[2])\n\nexcept (IndexError , ValueError):\n\tprint(f\"\\033[33mMust pass an argument!!!\\033[37m\")\n\tsys.exit(2)\n\ntry:\n\tsock = socket.create_connection((domain,port))\n\tsock.settimeout(50) #50secs , socket will wait 50 sec to try connecting with the server\n \nexcept:\n\tprint(f\"\\033[33mHost Unreachable!!!\");\n\tsys.exit(2)\n\nreq = None #no requests\n\nif sock.fileno() != -1: # if domain is up , then analyse further\n\tprint(f\"\\033[32mDomain {socket.gethostbyname(domain)} is Up... \\033[37m\")\n\tif port == 443:\n\t\treq = requests.get(f\"https://{domain}\")\n\t\tprint(f\"Status Code : {req.status_code}\")\n\t\tprint(f\"Service by port : {socket.getservbyport(port)}\")\n\n\tif port == 80:\n\t\treq = requests.get(f\"http://{domain}:{port}\")\n\t\tprint(f\"Status Code : {req.status_code}\")\n\t\tprint(f\"Service by port : {socket.getservbyport(port)}\")\n\nprint(f\"Service by : {req.headers['Server']}\")\nfor i in range(0,1000):\n\ts = socket.socket(socket.AF_INET,socket.SOCK_STREAM) # only dicovers TCP ports i repeat only discovers TCP ports\n\ts.settimeout(0.2) \n\tresult = s.connect_ex((domain,i))\n\tif result == 0:\n\t\tprint(f\"Discovered port {i}\")\n \n# request's headers \nfor i in req.headers:\n\tprint(req.headers[i])\n\n \n\n\n","sub_path":"infoGather.py","file_name":"infoGather.py","file_ext":"py","file_size_in_byte":1489,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"77027984","text":"\"\"\"\nA conversational agent learns to navigate a grid world with the help of a\nconversational-agent friend.\n\nWe learn a recurrent policy `A` which can take actions in a grid-world\nenvironment and send messages (token sequences) to a friend `B`. `A` is\n*blind*, while `B` has full vision of `A`'s grid world environment. `A` must\ncommunicate with `B` in order to find its goal and then reach it.\n\nHere `B` is a simple fixed agent which runs regex matches on `A`'s utterances.\nIts language is vaguely English-like, but aggressively abbreviated in order to\nmake `A`'s task easier.\n\"\"\"\n\nimport copy\nfrom pprint import pprint\n\nimport numpy as np\nimport tensorflow as tf\n\nfrom rllab import config\nfrom rllab.algos.trpo import TRPO\nfrom rllab.baselines.linear_feature_baseline import LinearFeatureBaseline\nfrom rllab.baselines.zero_baseline import ZeroBaseline\nfrom rllab.envs.normalized_env import normalize\nfrom rllab.misc.instrument import stub, run_experiment_lite\nfrom sandbox.rocky.tf.algos.trpo import TRPO\nfrom sandbox.rocky.tf.core.network import MLP\nfrom sandbox.rocky.tf.optimizers.conjugate_gradient_optimizer import ConjugateGradientOptimizer, FiniteDifferenceHvp\n\nfrom praglang.agents.grid import GridWorldMasterAgent, GridWorldSlaveAgent\nfrom praglang.environments.grid import GridWorldEnv, SlaveGridWorldEnv\nfrom praglang.environments.conversation import SituatedConversationEnvironment\nfrom praglang.policies import RecurrentCategoricalPolicy\nfrom praglang.util import MLPNetworkWithEmbeddings\n\n\nstub(globals())\n\nDEFAULTS = {\n \"batch_size\": 50000,\n \"max_path_length\": 10,\n \"n_itr\": 500,\n \"step_size\": 0.01,\n \"policy_hidden_dims\": (128,128),\n \"embedding_dim\": 32,\n \"feature_dim\": 128,\n \"feature_hidden_dims\": (128,),\n\n \"match_reward\": 1.0, # reward for valid utterance\n \"goal_reward\": 10.0, # reward for reaching goal\n}\n\nconfig.LOG_DIR = \"./log\"\n\ndef run_experiment(**params):\n base_params = copy.copy(DEFAULTS)\n base_params.update(params)\n params = base_params\n pprint(params)\n\n grid_world = SlaveGridWorldEnv(\"walled_chain\",\n max_traj_length=DEFAULTS[\"max_path_length\"],\n goal_reward=params[\"goal_reward\"])\n agent = GridWorldMasterAgent(grid_world, match_reward=params[\"match_reward\"])\n env = normalize(SituatedConversationEnvironment(env=grid_world, b_agent=agent))\n baseline = LinearFeatureBaseline(env)\n\n policy = RecurrentCategoricalPolicy(\n name=\"policy\",\n env_spec=env.spec,\n hidden_dims=params[\"policy_hidden_dims\"],\n feature_network=MLPNetworkWithEmbeddings(\n \"feature_network\", env.observation_space.flat_dim,\n params[\"feature_dim\"], params[\"feature_hidden_dims\"],\n tf.tanh, tf.tanh, agent.vocab_size, params[\"embedding_dim\"]),\n state_include_action=False,\n )\n\n optimizer = ConjugateGradientOptimizer(hvp_approach=FiniteDifferenceHvp(base_eps=1e-5))\n\n algo = TRPO(\n env=env,\n policy=policy,\n baseline=baseline,\n batch_size=params[\"batch_size\"],\n max_path_length=params[\"max_path_length\"],\n n_itr=params[\"n_itr\"],\n discount=0.99,\n step_size=params[\"step_size\"],\n optimizer=optimizer,\n )\n\n run_experiment_lite(\n algo.train(),\n n_parallel=15,\n snapshot_mode=\"last\",\n exp_prefix=\"grid_world_sweep3\",\n variant=params,\n )\n\n\n# Sweep with some random hyperparameters until killed.\nwhile True:\n batch_size = np.random.choice([50000, 100000])\n n_itr = 500 if batch_size == 50000 else 250\n match_reward = np.random.uniform(0.0, 3.0)\n goal_reward = np.random.uniform(1.0, 20.0)\n\n if goal_reward < match_reward:\n # Reject; this would be a weird setup\n continue\n\n run_experiment(batch_size=batch_size, n_itr=n_itr,\n match_reward=match_reward,\n goal_reward=goal_reward)\n","sub_path":"praglang/scripts/grid_world.py","file_name":"grid_world.py","file_ext":"py","file_size_in_byte":4039,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"213101023","text":"from tensorflow.keras import datasets, models, layers, losses\nimport tensorflow as tf\nfrom mpl_toolkits import mplot3d\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport random\n\ndef cone(x,y):\n return np.sqrt(x**2 + y**2)\n\ndef ripple(x,y):\n return np.sin(10 * (x**2 + y**2)) / 10\n\ndef makeTuple(X,Y):\n inputList = []\n for index, value in enumerate(X):\n for index1, value1 in enumerate(value):\n inputList.append([value1, Y[index][index1]])\n return inputList\n\ndef unpackTuple(A):\n X = []\n Y = []\n for item in A:\n X.append([item[0]])\n Y.append([item[1]])\n return X, Y\n\ndef makeArray(Z):\n zList = []\n for subList in Z:\n for value in subList:\n zList.append([value])\n return zList\n\ndef randomPoints(number, bounds):\n inputList = []\n outputList = []\n while(number > 0):\n value1 = random.uniform(bounds[0],bounds[1])\n value2 = random.uniform(bounds[0],bounds[1])\n inputList.append([value1, value2])\n outputList.append([ripple(value1, value2)])\n number = number -1\n return inputList, outputList\n\nbounds = (-1,1)\ninputList, outputList = randomPoints(50000, bounds)\nX_Train, Y_Train = unpackTuple(inputList)\n\nmodel = models.Sequential()\nmodel.add(layers.Dense(32, activation='exponential', input_shape=(2,)))\nmodel.add(layers.Dense(48, activation='tanh'))\nmodel.add(layers.Dense(1, activation=None))\nmodel.compile(optimizer='Adam',\n loss=losses.MeanSquaredError(),\n metrics=['mean_squared_error'])\n\nhistory = model.fit(np.array(inputList),np.array(outputList), epochs=300)\n#print(model.get_weights())\n\n\n# plots out learning curve\n# plt.plot(history.history['mean_squared_error'], label='mean_squared_error')\n# plt.xlabel('Epoch')\n# plt.ylabel('MSE')\n# plt.ylim([0.0, 0.2])\n# plt.legend(loc='lower right')\n# plt.show()\n\n# generate test data\ninputTest, outputTest = randomPoints(10, bounds)\nX_Test, Y_Test = unpackTuple(inputTest)\nprint(model.predict(np.array(inputTest)))\nprint(outputTest)\n\nx = np.linspace(-1, 1, 800)\ny = np.linspace(-1, 1, 800)\n\nX, Y = np.meshgrid(x, y)\nZ = ripple(X, Y)\n\nfig = plt.figure()\nax = plt.axes(projection=\"3d\")\n\nax.plot_wireframe(X, Y, Z, color='c')\nax.scatter3D(X_Test, Y_Test, model.predict(np.array(inputTest)), c='r')\nax.set_xlabel('x')\nax.set_ylabel('y')\nax.set_zlabel('z')\n\nplt.show()\n","sub_path":"Summer20/NeuralNetwork/tf3d.py","file_name":"tf3d.py","file_ext":"py","file_size_in_byte":2379,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"397904077","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\nimport datetime\nimport django.core.validators\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('users', '0001_initial'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Article',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('name', models.CharField(max_length=50, verbose_name='Nombre de art\\xedculo')),\n ('price', models.FloatField(verbose_name=b'Precio', validators=[django.core.validators.MinValueValidator(0.0)])),\n ('quantity', models.IntegerField(default=1, verbose_name=b'Cantidad', validators=[django.core.validators.MinValueValidator(0)])),\n ('total', models.FloatField(verbose_name=b'Total')),\n ],\n options={\n 'verbose_name': 'Art\\xedculo',\n 'verbose_name_plural': 'Art\\xedculos',\n 'permissions': (('show_article', 'Can Details Article'), ('index_article', 'Can List Article')),\n },\n ),\n migrations.CreateModel(\n name='Billing',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('is_canceled', models.BooleanField(default=False, verbose_name=b'Esta anulado?')),\n ('register_date', models.DateField(default=datetime.datetime.now, verbose_name=b'Fecha de Registro')),\n ('company', models.ForeignKey(verbose_name='Instituci\\xf3n', to='users.Company')),\n ],\n options={\n 'ordering': ['id'],\n 'verbose_name': 'Factura',\n 'verbose_name_plural': 'Facturas',\n 'permissions': (('show_billing', 'Can Details Billing'), ('index_billing', 'Can List Billing'), ('cancel_billing', 'Can Canceled Billing'), ('pdf_billing', 'Can Pdf Billing')),\n },\n ),\n migrations.CreateModel(\n name='Customer',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('full_name', models.CharField(max_length=50, verbose_name='Nombres o Raz\\xf3n social')),\n ('nit', models.CharField(unique=True, max_length=20, verbose_name=b'Nit o Ci', validators=[django.core.validators.RegexValidator(regex=b'^\\\\d{7,15}$', message='Nit o Ci no v\\xe1lido')])),\n ],\n options={\n 'verbose_name': 'Consumidor',\n 'verbose_name_plural': 'Consumidor',\n 'permissions': (('show_customer', 'Can Details Customer'), ('index_customer', 'Can List Customer')),\n },\n ),\n migrations.AddField(\n model_name='billing',\n name='customer',\n field=models.ForeignKey(verbose_name=b'Consumidor', to='invoices.Customer'),\n ),\n migrations.AddField(\n model_name='article',\n name='billing',\n field=models.ForeignKey(verbose_name=b'Factura', to='invoices.Billing'),\n ),\n ]\n","sub_path":"invoices/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":3263,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"437025756","text":"import sys\nimport os\nimport csv\nimport pyodbc \nimport pandas as pd\nimport pandas.io.sql as psql\nfrom pandas import Series, DataFrame\n\n\n# Functions Section---------------------------------------------------------------------------------------------------------------------\n\n#1)CHKShot DB connecton Function -> return as dataframe -Updated 7/5/17\ndef CKS_Read_Query(query):\n try:\n #Create MS SQL conection via ODBC driver\n cnxn = pyodbc.connect(\"DSN=SQL_R_CHKShot\")\n cur = cnxn.cursor()\n df = psql.read_sql(query, cnxn)\n cnxn.close()\n #print(df)\n return df\n except \"Query Error\":\n print(\"WV Query Error...!\")\n\n#1)Eof \n\n#2)Wellview DB connecton Function -> return as dataframe -Updated 7/5/17\ndef WV_Read_Query(query):\n try:\n cnxn = pyodbc.connect(\"DSN=SQL_R_WV\") \n cur = cnxn.cursor()\n df = psql.read_sql(query, cnxn)\n cnxn.close()\n #print(df)\n return df\n except \"Wellview Query Error...!\":\n print(\"Wellview Query Error...!\")\n \n#2)Eof\n\n#3)VuMax Prd connecton Function -> return as dataframe -Updated 7/5/17\ndef VMX_PRD_Read_Query(query):\n try:\n cnxn = pyodbc.connect(driver='{SQL Server}', server='OKCSQLPRD1021', database='VuMaxDR',\n uid=\"Vmx_vumaxadmin\",pwd=\"vumaxadmin\",trusted_connection=\"no\")\n cur = cnxn.cursor()\n df = psql.read_sql(query, cnxn)\n cnxn.close()\n #print(df)\n return df\n except \"VuMax PRD Query Error...!\":\n print(\"VuMax PRDQuery Error...!\")\n\n#3)Eof\n\n#4)Local db connecton Function -> return as dataframe -Updated 7/12/17\ndef VMX_TST_Read_Query(query):\n try:\n cnxn = pyodbc.connect(driver='{SQL Server}', server='OKCSQLTST087\\TEST', database='VuMaxDR',\n uid=\"Vmx_vumaxadmin\",pwd=\"vumaxadmin\",trusted_connection=\"no\")\n cur = cnxn.cursor()\n df = psql.read_sql(query, cnxn)\n cnxn.close()\n #print(df)\n return df\n except \"VuMax TST Query Error...!\":\n print(\"VuMax TST Query Error...!\")\n\n#4)Eof\n\n#5)Write dataframe to CSV -> return conf message -Updated 7/xx/17\ndef export_DF_To_CSV(dataframe, fileName):\n try:\n dataframe.to_csv(fileName)\n print(\"The data frame \" + fileName + \" has been written successfully!\")\n except \"Error\":\n print(\"Write file error?\")\n#5)Eof\n\n#5)Read CSV data in dataframe -> return dataframe -Updated 7/xx/17\ndef import_CSV_to_DF(fileName):\n try:\n table = pd.read_csv(fileName)\n print(\"The file \" + fileName + \" has been read successfully!\")\n return table\n except \"Error\":\n print(\"Read file error?\")\n#6)Eof\n","sub_path":"CUC Export Files 8_7_17/Data_Model.py","file_name":"Data_Model.py","file_ext":"py","file_size_in_byte":2721,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"180811007","text":"import matplotlib.pyplot as pyplot\nimport math\n\ndef principal():\n valores_de_x = [] #lista de valores de x\n valores_de_y = [] #lista de valores de y\n x = -2\n for i in range(100):\n x = x + 0.05\n valores_de_x.append(x) #adiciona valores de x na lista\n for x in valores_de_x:\n y = f(x)\n valores_de_y.append(y) #adiciona valores calculados de y na lista\n pyplot.plot(valores_de_x,valores_de_y) #plota valores\n pyplot.xlabel('X')\n pyplot.ylabel('Y')\n pyplot.show() #mostra o gráfico\n\ndef f(x):\n if (-2) <= x and x <=0:\n return (1 / math.sqrt(2)) * (math.cos(math.pi*x) - math.sin((math.pi*x)/2) + 1)\n if 0 < x and x<= 2:\n return (1 / math.sqrt(2)) * (math.cos(math.pi*x) + math.sin((math.pi*x)/2) + 1)\n else:\n return 0\n\nprincipal()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":779,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"450513140","text":"if __name__ == '__main__':\n import os\n import numpy as np\n import pandas as pd\n from IRWLS import *\n import argparse\n import time\n \n parser = argparse.ArgumentParser(description='find prior and nonprior predictions, save to csv')\n \n parser.add_argument('--types', '-t', nargs='?', type=int, \n default=3, help='number of types')\n parser.add_argument('--pixels', '-p', nargs='?', type=int, \n default=2000, help='number of pixels')\n parser.add_argument('--index', '-i', nargs='?', type=int, \n default=0, help='index of cluster file')\n parser.add_argument('--iters', '-it', nargs='?', type=int,\n default=15, help='number of iterations for alt max')\n args = parser.parse_args()\n \n data_path = os.path.join(os.getcwd(),\"data\")\n X_vals = np.genfromtxt(os.path.join(data_path,\"X_vals.csv\"),delimiter=\",\",skip_header=1)\n Q_mat = np.genfromtxt(os.path.join(data_path,\"Q_mat.csv\"),delimiter=\",\",skip_header=1)\n\n clusters = pd.read_csv(os.path.join(data_path,\n \"clusters_B-\"+\n str(args.types)+\"-\"+\n str(args.pixels)+\"-\"+\n str(args.index)+\".csv\"))\n \n B = pd.read_csv(os.path.join(data_path, \"B-\"+\n str(args.types)+\"-\"+\n str(args.pixels)+\"-\"+\n str(args.index)+\".csv\"), delimiter=',', index_col=0).to_numpy()\n \n nUMI = np.loadtxt(os.path.join(data_path, \"nUMI-\"+\n str(args.types)+\"-\"+\n str(args.pixels)+\"-\"+\n str(args.index)+\".csv\"), delimiter=',',)\n \n test = IRWLS(nUMI = nUMI\n , B = B, X_vals = X_vals, Q_mat = Q_mat)\n \n cluster_init = np.array([B.T[clusters['x'].eq(i)].mean(axis=0) for i in range(args.types)]).T\n \n start_time = time.time()\n prior = np.ones(args.types) * 0.3 / args.types\n prior_output, plls = test.alt_max(cluster_init,\n reset=False, prior = prior, iters=args.iters, parallel = True, return_lls=True)\n print(\"time elapsed\",time.time()-start_time)\n \n start_time = time.time()\n noprior_output, nlls = test.alt_max(cluster_init,\n reset=False, prior = None, iters=args.iters, parallel = True, return_lls=True)\n print(\"time elapsed\",time.time()-start_time)\n \n \n \n np.savetxt(os.path.join(data_path,\"prior-curr_S\"+\"-\"+\n str(args.types)+\"-\"+\n str(args.pixels)+\"-\"+\n str(args.index)+\".csv\"), prior_output[0])\n np.savetxt(os.path.join(data_path,\"prior-curr_W\"+\"-\"+\n str(args.types)+\"-\"+\n str(args.pixels)+\"-\"+\n str(args.index)+\".csv\"), prior_output[1])\n \n np.savetxt(os.path.join(data_path,\"noprior-curr_S\"+\"-\"+\n str(args.types)+\"-\"+\n str(args.pixels)+\"-\"+\n str(args.index)+\".csv\"), noprior_output[0])\n np.savetxt(os.path.join(data_path,\"noprior-curr_W\"+\"-\"+\n str(args.types)+\"-\"+\n str(args.pixels)+\"-\"+\n str(args.index)+\".csv\"), noprior_output[1])\n \n np.savetxt(os.path.join(data_path,\"prior-lls\"+\"-\"+\n str(args.types)+\"-\"+\n str(args.pixels)+\"-\"+\n str(args.index)+\".csv\"), plls)\n np.savetxt(os.path.join(data_path,\"noprior-lls\"+\"-\"+\n str(args.types)+\"-\"+\n str(args.pixels)+\"-\"+\n str(args.index)+\".csv\"), nlls)\n","sub_path":"src/gen_pred.py","file_name":"gen_pred.py","file_ext":"py","file_size_in_byte":4164,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"151396210","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models\nfrom django.conf import settings\nfrom UserModel import *\nimport uuid\nimport datetime\n\n# Create your models here.\nclass UserManager(models.Manager):\n def create_user(self, user):\n user_model = self.create(name=user.name, user_name=user.user_name,\n password=user.password, email=user.email)\n return user_model\n\n def find_user_by_user_name(self, user_name):\n user = self.get(user_name=user_name)\n return user\n\n def find_user_by_user_id(self, user_id):\n user = self.get(id=user_id)\n return user\n\nclass User(models.Model):\n name = models.CharField(max_length=30)\n user_name = models.CharField(max_length=50, unique=True)\n password = models.CharField(max_length=50)\n email = models.EmailField(verbose_name='email address', max_length=254, unique=True)\n objects = UserManager()\n def __str__(self):\n return self.user_name\n\n\n#ROL Model\nclass RolManager(models.Manager):\n def create_rol_for_user(self, user, rol):\n rol_model = self.create(user=user, rol=rol)\n return rol_model\n \n def find_rol_by_user_id(self, user_id):\n rol = self.get(user_id=user_id)\n return rol\n\nclass Rol(models.Model):\n rol = models.CharField(max_length=50)\n user = models.ForeignKey(User, on_delete=models.CASCADE)\n objects = RolManager()\n\n\n#Auth Token Model\nclass AuthTokenManager(models.Manager):\n def create_token_for_user(self, user):\n token = uuid.uuid4().hex\n last_activation = datetime.datetime.utcnow()\n token_model = self.create(token=token,last_activation=last_activation,\n user=user)\n return token_model\n\n def find_token_by_user_id(self, user_id):\n token = self.get(user_id = user_id)\n return token\n \n def update_last_activate_token(self, token_id):\n token = self.get(id=token_id)\n token.last_activation = datetime.datetime.utcnow()\n token.save()\n return token\n def find_token_by_value(self, token):\n real_token = self.get(token=token)\n return real_token\n\n\nclass Token(models.Model):\n token = models.CharField(max_length=254, unique=True)\n date_created = models.DateField(auto_now=True)\n last_activation = models.DateTimeField()\n user = models.ForeignKey(User, on_delete=models.CASCADE)\n objects = AuthTokenManager()\n ","sub_path":"ERP/Authentication/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2439,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"78604318","text":"from five import grok\nfrom opengever.activity import notification_center\nfrom opengever.base.browser.resolveoguid import ResolveOGUIDView\nfrom opengever.ogds.base.utils import ogds_service\nfrom plone import api\nfrom Products.CMFPlone.interfaces import IPloneSiteRoot\nfrom zExceptions import NotFound\nfrom zExceptions import Unauthorized\n\n\nclass ResolveNotificationView(ResolveOGUIDView):\n grok.name('resolve_notification')\n grok.context(IPloneSiteRoot)\n grok.require('zope2.View')\n\n def render(self):\n notification_id = self.request.get('notification_id', '')\n center = notification_center()\n self.notification = center.get_notification(notification_id)\n\n if not self.notification:\n raise NotFound('Invalid notification_id ({}) is given'.format(\n self.request.get('notification')))\n\n if not self.check_permission():\n raise Unauthorized()\n\n self.mark_as_read()\n self.redirect()\n\n def check_permission(self):\n \"\"\"Check if the current user is allowed to view the notification.\"\"\"\n\n current_user = api.user.get_current()\n return self.notification.userid == current_user.getId()\n\n def mark_as_read(self):\n self.notification.is_read = True\n\n def redirect(self):\n \"\"\"Redirect to the affected resource. If the resource is stored\n in an other admin_unit than the current one, it redirects to the\n resolve_oguid view on this admin_unit.\"\"\"\n\n oguid = self.notification.activity.resource.oguid\n\n if oguid.is_on_current_admin_unit:\n url = oguid.resolve_object().absolute_url()\n\n else:\n admin_unit = ogds_service().fetch_admin_unit(oguid.admin_unit_id)\n url = ResolveOGUIDView.url_for(oguid, admin_unit)\n\n return self.request.RESPONSE.redirect(url)\n","sub_path":"opengever/activity/browser/resolve.py","file_name":"resolve.py","file_ext":"py","file_size_in_byte":1852,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"569335699","text":"import sys\nsys.stdin = open(\"문자열 비교_input.txt\")\nT = int(input())\nfor tc in range(1, T+1):\n S1 = input()\n S2 = input()\n L1 = len(S1)\n L2 = len(S2)\n result = 0\n for i in range(L2-L1+1):\n cnt = 0\n for j in range(L1):\n if S1[j] != S2[i+j]:\n break\n else:\n cnt += 1\n if cnt == L1:\n result = 1\n\n print('#{} {}'.format(tc, result))\n\n\n\n\n","sub_path":"work/실습/3. String/문자열 비교.py","file_name":"문자열 비교.py","file_ext":"py","file_size_in_byte":451,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"264625594","text":"from django import forms\nfrom django.contrib.auth.models import User\nfrom django.contrib.auth.forms import UserCreationForm\nfrom django.forms import (\n\n Select,\n Textarea,\n DateInput,\n TextInput,\n EmailInput,\n NumberInput,\n PasswordInput,\n SelectDateWidget,\n\n)\n\nfrom .models import Customer, Product, Invoice\n\n\nclass CreateCustomerForm(forms.ModelForm):\n class Meta:\n model = Customer\n\n fields = ['customer_name', 'address', 'email']\n # fields = '__all__'\n\n widgets = {\n 'customer_name': TextInput(attrs={'class': 'form-control'}),\n 'address': TextInput(attrs={'class': 'form-control'}),\n 'email': EmailInput(attrs={'class': 'form-control'}),\n\n }\n\n\nclass CreateProductForm(forms.ModelForm):\n class Meta:\n model = Product\n\n fields = ['product_name', 'category', 'description']\n\n widgets = {\n 'product_name': TextInput(attrs={'class': 'form-control'}),\n 'category': TextInput(attrs={'class': 'form-control'}),\n 'description': Textarea(attrs={'class': 'form-control'}),\n\n }\n\n\nclass CreateInvoiceForm(forms.ModelForm):\n class Meta:\n model = Invoice\n\n fields = ['customer', 'currency', 'date', 'item_code', 'item_description', 'quantity', 'unit_price',\n 'discount']\n\n widgets = {\n 'customer': Select(attrs={'class': 'form-control'}),\n 'currency': Select(attrs={'class': 'form-control'}),\n 'date': SelectDateWidget(attrs={'class': 'custom-select'}),\n 'item_code': TextInput(attrs={'class': 'custom-select'}),\n 'item_description': Select(attrs={'class': 'custom-select'}),\n 'quantity': NumberInput(attrs={'class': 'custom-select'}),\n 'unit_price': NumberInput(attrs={'class': 'custom-select'}),\n 'discount': NumberInput(attrs={'class': 'custom-select'}),\n # 'total': NumberInput(attrs={'class': 'custom-select'}),\n\n }\n\n","sub_path":"products_invoices/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":2018,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"135118293","text":"# 펠린드롭 01\r\ndef is_palindrome1(word):\r\n word = list(word)\r\n reverse = word[-1: : -1]\r\n return word == reverse\r\n\r\n# 펠린드롭 02\r\ndef is_palindrome2(word):\r\n for left in range(len(word) // 2):\r\n # 한 쌍이라도 일치하지 않으면 바로 False를 리턴하고 함수를 끝냄\r\n right = len(word) - left - 1\r\n if word[left] != word[right]:\r\n return False\r\n # for문에서 나왔다면 모든 쌍이 일치\r\n return True\r\n# 테스트\r\nprint(is_palindrome1(\"racecar\"))\r\nprint(is_palindrome1(\"stars\"))\r\nprint(is_palindrome2(\"토마토\"))\r\nprint(is_palindrome2(\"kayak\"))\r\nprint(is_palindrome1(\"hello\"))","sub_path":"palin.py","file_name":"palin.py","file_ext":"py","file_size_in_byte":663,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"588018530","text":"import random as rand\nimport math\nimport numpy as np\n\n\nclass Neuron:\n def __init__(self, **kwargs):\n self.weights = kwargs.get('weights', None)\n self.bias = kwargs.get('bias', 1)\n input_num = kwargs.get('input_num', 2)\n if self.weights is None:\n self.weights = []\n for i in range(input_num + 1):\n self.weights.append(rand.random() * 2 - 1)\n\n def output(self, input_row):\n result = 0\n # result = sum(np.multiply([1] + input_row, self.weights))\n # result = sum([x * w for x, w in zip([1] + input_row, self.weights)])\n for x, w in zip([1] + input_row, self.weights):\n result += x * w\n return 1 / (1 + math.exp(-result * self.bias))\n\n def delta(self, output_weights, output_deltas, desired_output, output):\n result = output * (1 - output) * self.bias\n if desired_output is not None:\n result *= desired_output - output\n else:\n result *= sum([w * d for (w, d) in zip(output_weights, output_deltas)])\n return result\n\n def teach(self, input_row, delta, t_step):\n return [i * t_step * delta for i in [1] + input_row]\n\n\nclass Layer:\n def __init__(self, neuron_num, input_num):\n self.neurons = []\n for i in range(neuron_num):\n self.neurons.append(Neuron(input_num=input_num))\n self.inputs = None\n\n def output(self):\n return [n.output(self.inputs) for n in self.neurons]\n\n def weights_for_inputs(self):\n return np.array([n.weights[1:] for n in self.neurons]).transpose()\n\n def mod_weights(self, delta_weights):\n for n, dw in zip(self.neurons, delta_weights):\n n.weights = np.add(n.weights, dw)\n\n def get_weights(self):\n return [n.weights for n in self.neurons]\n\n def deltas(self, **kwargs):\n output_weights = kwargs.get('output_weights', None)\n output_deltas = kwargs.get('output_deltas', None)\n desired_output = kwargs.get('desired_output', None)\n calc_output = kwargs.get('calc_output', None)\n if desired_output is None:\n result = [n.delta(weights, output_deltas, None, output) for n, weights, output\n in zip(self.neurons, output_weights, calc_output)]\n else:\n result = [n.delta(None, None, desired, output) for n, desired, output\n in zip(self.neurons, desired_output, calc_output)]\n return result\n\n def teach_row(self, deltas, t_step):\n return [n.teach(self.inputs, delta, t_step) for n, delta in zip(self.neurons, deltas)]\n\n\nclass Network:\n def __init__(self, depth, width, input_num):\n self.layers = [Layer(width[0], input_num)]\n self.input_num = input_num\n for d in range(depth - 1):\n self.layers.append(Layer(width[d + 1], width[d]))\n\n def output(self, input_row):\n for l in self.layers:\n l.inputs = input_row\n input_row = l.output()\n return input_row\n\n def full_output(self, input_row):\n self.layers[0].inputs = input_row\n result = [self.layers[0].output()]\n for l in self.layers[1:]:\n l.inputs = result[-1]\n result.append(l.output())\n return result\n\n def effectiveness(self, test_set):\n result = 0\n for (row, exp) in test_set:\n # result += sum([math.fabs(o - y) for o, y in zip(self.output(row), exp)]) / len(exp)\n my_list = self.output(row)\n max_value = max(my_list)\n max_index = my_list.index(max_value)\n if exp[max_index] == 1:\n result += 1\n # return 1 - result / len(test_set)\n return result / len(test_set)\n\n def teach_row(self, input_row, desired_output, t_step):\n full_output = self.full_output(input_row)\n weights = self.layers[-1].weights_for_inputs()\n deltas = self.layers[-1].deltas(desired_output=desired_output, calc_output=full_output[-1])\n delta_weights = [self.layers[-1].teach_row(deltas, t_step)]\n for l, out in zip(reversed(self.layers[:-1]), reversed(full_output[:-1])):\n deltas = l.deltas(output_weights=weights, output_deltas=deltas, calc_output=out)\n delta_weights.append(l.teach_row(deltas, t_step))\n weights = l.weights_for_inputs()\n return delta_weights\n\n def teach_batch(self, t_batch, t_step):\n delta_weights = self.teach_row(t_batch[0][0], t_batch[0][1], t_step)\n for row in t_batch[1:]:\n new_dw = self.teach_row(row[0], row[1], t_step)\n delta_weights = [np.add(dw1, dw2) for dw1, dw2 in zip(delta_weights, new_dw)]\n delta_weights = [np.divide(dw, len(t_batch)) for dw in delta_weights]\n for l, w in zip(self.layers, delta_weights[::-1]):\n l.mod_weights(w)\n\n def teach(self, teaching_set, validating_set, batch_size, t_step, max_iter=1000):\n for i in range(max_iter):\n rand.shuffle(teaching_set)\n batch_num = 0\n for batch in [teaching_set[i:i + batch_size] for i in range(0, len(teaching_set), batch_size)]:\n self.teach_batch(batch, t_step)\n batch_num += 1\n print(str(i) + ' tset ' + str(self.effectiveness(teaching_set)))\n print(str(i) + ' vset ' + str(self.effectiveness(validating_set)))\n\n\ndef test1():\n l = Layer(4, 2)\n print([n.weights for n in l.neurons])\n print(l.weights_for_inputs())\n l.inputs = [1, 0]\n print(l.deltas(desired_output=1))\n\n\ndef test2():\n n = Network(2, [4, 2], 2)\n for l in n.layers:\n print(l.weights_for_inputs())\n print(n.teach_row([1, 0], [0, 1], 1))\n\n\ndef test3():\n n = Network(2, [4, 2], 2)\n for l in n.layers:\n print(l.weights_for_inputs())\n n.teach_batch([[[1, 0], [0, 1]]], 1)\n print(\"after\")\n for l in n.layers:\n print(l.weights_for_inputs())\n\n\ndef test4():\n t_set = [([0, 0], [0]), ([1, 1], [0]), ([0, 1], [1]), ([1, 0], [1])]\n net = Network(2, [3, 1], 2)\n net.teach(t_set, t_set, 4, 1)\n print(net.output([0, 0]))\n print(net.output([1, 1]))\n print(net.output([0, 1]))\n print(net.output([1, 0]))\n","sub_path":"mlp1.py","file_name":"mlp1.py","file_ext":"py","file_size_in_byte":6193,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"179928549","text":"import math\n\n\ndef leitura():\n \n arq = input(\"Digite o nome do arquivo csv de entrada: \")\n\n f = open(arq+\".csv\", \"r\")\n\n coluna = 0\n missingIds = []\n i = 0\n valores = []\n nonMissing = 0\n\n while True:\n coluna = int(input(\"Digite o numero da coluna: \"))\n if(coluna == 0 or coluna == 1 or coluna < 0 or coluna >= 5):\n print(\"Coluna inválida. Tente outra.\")\n else:\n break\n\n for line in f:\n if i == 0:\n i = i+1\n continue\n \n s = line.replace(\"\\n\",\"\")\n a = s.split(\",\")\n if(a[coluna] != '?'):\n valores.append(int(a[coluna]))\n nonMissing = nonMissing+1\n else:\n missingIds.append(i)\n i=i+1\n\n # Calculando moda\n if valores.count(0) >= valores.count(1) and valores.count(0) >= valores.count(2):\n moda = 0\n elif valores.count(1) >= valores.count(0) and valores.count(1) >= valores.count(2):\n moda = 1\n else:\n moda = 2\n\n #Calculando média\n media = math.ceil(sum(valores)/nonMissing)\n\n #Calculando mediana\n valores.sort()\n if len(valores)%2 == 0:\n meio = int(len(valores)/2)\n mediana = math.ceil( (valores[meio] + valores[meio+1])/2 )\n else:\n mediana = valores[int(len(valores)/2)]\n\n f.close()\n\n return {\n \"media\":media,\n \"moda\":moda,\n \"mediana\":mediana,\n \"missing\":missingIds,\n \"coluna\":coluna,\n \"arq\":arq\n }\n\ndef main():\n\n res = leitura()\n print(\"Selecione o tipo de substituição a ser utilizado: ( 1-Media | 2-Mediana | 3-Moda )\")\n op = int(input())\n\n print(\"Mostrando os valores calculados para cada uma das 3 opções de substituição: \")\n print()\n print(\"Media = \",res[\"media\"])\n print(\"Mediana = \",res[\"mediana\"])\n print(\"Moda = \",res[\"moda\"])\n print()\n\n if op == 3:\n val = res[\"moda\"]\n elif op == 2:\n val = res[\"mediana\"]\n else:\n val = res[\"media\"]\n\n escrita(op,val,res[\"missing\"],res[\"coluna\"],res[\"arq\"])\n\n\n\ndef escrita(op,val,missingIds,coluna,arq):\n\n\n f = open(arq+\".csv\", \"r\")\n f2 = open(\"result.csv\", \"w\")\n\n i=0\n for line in f:\n if i == 0:\n f2.write(line)\n i=i+1\n continue\n \n if i in missingIds:\n s = line.replace(\"\\n\",\"\")\n a = s.split(\",\")\n\n a[coluna] = str(val)\n\n wline = str(a[0])+''.join(\",\"+j for j in a[1::])+'\\n'\n f2.write(wline)\n else:\n f2.write(line)\n\n i = i+1\n\n\n f.close()\n f2.close()\n\n\n\nmain()","sub_path":"tarefa2/tarefa2.py","file_name":"tarefa2.py","file_ext":"py","file_size_in_byte":2619,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"384171060","text":"\"\"\"\r\nConfigure Security Policy\r\n\"\"\"\r\n\r\n__author__ = ['Sasikumar Sekar']\r\n__contact__ = 'sasik@juniper.net'\r\n__copyright__ = 'Juniper Networks Inc.'\r\n__date__ = '2017'\r\n\r\n\r\ndef configure_groups_global_policy(device=None, from_zone=None, to_zone=None, policy_name=None,\r\n source_address=None, destination_address=None,\r\n application=None, action=None, default_policy_action=None,\r\n global_policy=False, scheduler_name=None,\r\n default_policy=False, commit=False):\r\n \"\"\"\r\n Configuring groups global policy configuration on the box\r\n\r\n :Example:\r\n python: configure_groups_global_policy(device=router_handle, from_zone=trust, to_zone=untrust,\r\n policy_name=p1, commit=True)\r\n robot:\r\n configure groups global policy device=router_handle from_zone=trust\r\n to_zone=untrust policy_name=p1 commit=${TRUE}\r\n\r\n configure groups global policy device=${dh} default_policy=${True}\r\n default_policy_action=deny\r\n configure groups global policy device=${dh} from_zone=trust\r\n to_zone=untrust policy_name=p1\r\n scheduler_name=daily_scheduler\r\n configure groups global policy device=${dh} global_policy=${True}\r\n policy_name=p1 source_address=${source}\r\n destination_address=${destination}\r\n application=any action=permit\r\n configure groups global policy device=${dh} from_zone=trust\r\n to_zone=untrust policy_name=p1\r\n source_address=${source} destination_address=${destination}\r\n application=any action=deny\r\n\r\n :param str device:\r\n \t**REQUIRED** device handler\r\n :param str from_zone:\r\n \t*OPTIONAL* Define a policy context from this zone\r\n :param str to_zone:\r\n \t*OPTIONAL* Destination zone\r\n :param str policy_name:\r\n \t*OPTIONAL* Security policy name\r\n :param list source_address:\r\n *OPTIONAL* Match source address\r\n :param list destination_address:\r\n \t*OPTIONAL* Match destination address\r\n :param list application:\r\n *OPTIONAL* Port-based application\r\n :param str action:\r\n \t*OPTIONAL* Specify policy action to take when packet match criteria\r\n :param str default_policy_action:\r\n *OPTIONAL* default policy action.\r\n :param str scheduler_name:\r\n *OPTIONAL* Name of security scheduler\r\n :param bool global_policy:\r\n *OPTIONAL* Define a global policy context. Default value: commit=False\r\n :param bool default_policy:\r\n *OPTIONAL* Configure default action when no user-defined policy match\r\n Default value: commit=False\r\n :param bool commit:\r\n *OPTIONAL* Whether to commit at the end or not. Default value: commit=False\r\n :return:\r\n \t* ``True`` when policy configuration is entered\r\n :raises Exception: when mandatory parameter is missing\r\n\r\n \"\"\"\r\n if device is None:\r\n\r\n raise Exception(\"'device' is mandatory parameter for this function\")\r\n\r\n cmd = 'set groups global security policies '\r\n\r\n if global_policy:\r\n cmd = cmd + ' global '\r\n\r\n if from_zone is not None and to_zone is not None:\r\n cmd = cmd + ' from-zone ' + from_zone + ' to-zone ' + to_zone\r\n\r\n if policy_name is not None:\r\n cmd = cmd + ' policy ' + policy_name\r\n\r\n if default_policy:\r\n cmd = cmd + ' default-policy '\r\n\r\n if scheduler_name is not None:\r\n cmd = cmd + ' scheduler-name ' + scheduler_name\r\n\r\n if source_address is not None:\r\n if isinstance(source_address, list):\r\n for temp in source_address:\r\n device.config(command_list=[cmd + ' match source-address ' + temp])\r\n else:\r\n device.config(command_list=[cmd + ' match source-address ' + source_address])\r\n if destination_address is not None:\r\n if isinstance(destination_address, list):\r\n for temp in destination_address:\r\n device.config(command_list=[cmd + ' match destination-address ' + temp])\r\n else:\r\n device.config(command_list=[cmd + ' match destination-address ' + destination_address])\r\n if application is not None:\r\n if isinstance(application, list):\r\n for temp in application:\r\n device.config(command_list=[cmd + ' match application ' + temp])\r\n else:\r\n device.config(command_list=[cmd + ' match application ' + application])\r\n\r\n if action is not None:\r\n device.config(command_list=[cmd + ' then ' + action])\r\n\r\n elif default_policy_action is not None:\r\n device.config(command_list=[cmd + default_policy_action])\r\n\r\n else:\r\n device.config(command_list=[cmd])\r\n\r\n if commit:\r\n return device.commit(timeout=60)\r\n else:\r\n return True\r\n","sub_path":"NITA/lib/jnpr/toby/security/policy/groups_global_security_policy.py","file_name":"groups_global_security_policy.py","file_ext":"py","file_size_in_byte":4924,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"255730405","text":"import os\nfrom flask import Flask, session, redirect, url_for, abort, render_template, flash, request\nfrom connMySQL import connMySQL\n\n######################################\n# use connMySQL:\n#cursor = connMySQL().cursor()\n#sql = \"select * from entries limit 10\"\n#try:\n# cursor.execute(sql)\n# data = cursor.fetchall()\n# print data\n#except Exception, e:\n# print e\n# sys.exit()\n######################################\n\n# static\n\n#os.urandom(12)\n\napp = Flask(__name__)\napp.secret_key = '\\x9e\\xa3$\\x07h^[`\\x99m'\n\n@app.route('/', methods=['GET', 'POST'])\ndef index():\n if request.method == 'GET':\n flash(\"GET Successed visit!\")\n else:\n flash(\"NOT GET!\")\n return render_template('index.html')\n\nif __name__ == '__main__':\n #app.run(host='192.168.221.128', port=80)\n app.run(host='0.0.0.0', port=8080)\n","sub_path":"flaskr/flaskr.py","file_name":"flaskr.py","file_ext":"py","file_size_in_byte":836,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"373479997","text":"'''\nCreated on 18 de jul de 2016\nCompute the GLRLM matrix\n@author: romue\n'''\n\nimport numpy as np\nfrom scipy.ndimage import rotate\n\ndef glrlm(im, nBins, angle):\n \n b = im\n nbits = nBins\n matrix = np.zeros((len(np.unique(b)),nbits))\n \n if angle == 0:\n for j in b:\n a = j\n atual = a[0]\n acc = 0\n i = 1\n while (True):\n \n if atual == a[i]:\n acc += 1\n i += 1 \n else:\n matrix[atual,acc] += 1\n atual = a[i]\n acc = 0\n i += 1\n if i == len(a):\n matrix[atual,acc] += 1\n break\n if angle == 90:\n b = np.rot90(b)\n for j in b:\n a = j\n atual = a[0]\n acc = 0\n i = 1\n while (True):\n \n if atual == a[i]:\n acc += 1\n i += 1 \n else:\n matrix[atual,acc] += 1\n atual = a[i]\n acc = 0\n i += 1\n if i == len(a):\n matrix[atual,acc] += 1\n break\n \n if angle == 45:\n b = rotate(b,45)\n for j in b:\n a = j\n atual = a[0]\n acc = 0\n i = 1\n while (True):\n if atual == a[i]:\n acc += 1\n i += 1 \n else:\n if atual != 0:\n matrix[atual,acc] += 1\n atual = a[i]\n acc = 0\n i += 1\n if i == len(a):\n if atual != 0:\n matrix[atual,acc] += 1\n break\n if angle == 135:\n b = np.rot90(rotate(b,45))\n for j in b:\n a = j\n atual = a[0]\n acc = 0\n i = 1\n while (True):\n if atual == a[i]:\n acc += 1\n i += 1 \n else:\n if atual != 0:\n matrix[atual,acc] += 1\n atual = a[i]\n acc = 0\n i += 1\n if i == len(a):\n if atual != 0:\n matrix[atual,acc] += 1\n break\n \n return features(matrix)\n \ndef features(gl):\n '''\n -------------------------------------------\n Current supported statistics include:\n -------------------------------------------\n Short Run Emphasis (SRE)\n Long Run Emphasis (LRE)\n Gray-Level Nonuniformity (GLN)\n Run Length Nonuniformity (RLN)\n Run Percentage (RP)\n Low Gray-Level Run Emphasis (LGRE)\n High Gray-Level Run Emphasis (HGRE)\n Short Run Low Gray-Level Emphasis (SRLGE)\n Short Run High Gray-Level Emphasis (SRHGE)\n Long Run Low Gray-Level Emphasis (LRLGE)\n Long Run High Gray-Level Emphasis (LRHGE)\n --------------------------------------------\n '''\n\n GLRLM = gl\n numGLRLM = 1 \n \n # 11 statistics for each GLRLM\n \n tGLRLM = GLRLM;\n\n s = tGLRLM.shape\n c_vector = np.array(range(1,s[0]+1))\n r_vector = np.array(range(1,s[1]+1))\n\n c_matrix,r_matrix = np.meshgrid(c_vector,r_vector);\n c_matrix = c_matrix+1\n r_matrix = r_matrix+1\n\n N_runs = np.sum(tGLRLM)\n\n N_tGLRLM = s[0]*s[1];\n\n #--------------------Prepare four matrix for speedup--------------\n # 2.Gray-Level Run-Number Vector\n p_g = np.sum(tGLRLM,axis=0);\n\n # 3.Run-Length Run-Number Vector\n p_r = np.sum(tGLRLM,axis=1);\n \n #------------------------Statistics-------------------------------\n # 1. Short Run Emphasis (SRE)\n SRE = np.sum(p_r/(c_vector**2))/N_runs;\n\n # 2. Long Run Emphasis (LRE)\n LRE = np.sum(p_r*(c_vector**2))/N_runs;\n # 3. Gray-Level Nonuniformity (GLN)\n GLN = np.sum(p_g**2)/N_runs;\n # 4. Run Length Nonuniformity (RLN)\n RLN = np.sum(p_r**2)/N_runs;\n # 5. Run Percentage (RP)\n RP = N_runs/N_tGLRLM;\n # 6. Low Gray-Level Run Emphasis (LGRE)\n LGRE = np.sum(p_g/(r_vector**2))/N_runs;\n # 7. High Gray-Level Run Emphasis (HGRE)\n HGRE = np.sum(p_g*r_vector**2)/N_runs;\n # 8. Short Run Low Gray-Level Emphasis (SRLGE)\n SGLGE =calculate_SGLGE(tGLRLM,r_matrix.T,c_matrix.T,N_runs);\n # 9. Short Run High Gray-Level Emphasis (SRHGE)\n SRHGE =calculate_SRHGE(tGLRLM,r_matrix.T,c_matrix.T,N_runs);\n # 10. Long Run Low Gray-Level Emphasis (LRLGE)\n LRLGE =calculate_LRLGE(tGLRLM,r_matrix.T,c_matrix.T,N_runs);\n # 11.Long Run High Gray-Level Emphasis (LRHGE\n LRHGE =calculate_LRHGE(tGLRLM,r_matrix.T,c_matrix.T,N_runs);\n \n \n return [SRE, LRE, GLN, RLN, RP, LGRE, HGRE, SGLGE, SRHGE, LRLGE, LRHGE];\n\n \n \ndef calculate_SGLGE(tGLRLM,r_matrix,c_matrix,N_runs):\n # Short Run Low Gray-Level Emphasis (SRLGE):\n\n term = tGLRLM/((r_matrix*c_matrix)**2)\n SGLGE= np.sum(sum(term))/N_runs\n return SGLGE\n\ndef calculate_SRHGE(tGLRLM,r_matrix,c_matrix,N_runs):\n # Short Run High Gray-Level Emphasis (SRHGE):\n \n term = tGLRLM*(r_matrix**2)/(c_matrix**2)\n SRHGE = np.sum(np.sum(term))/N_runs\n return SRHGE\n\ndef calculate_LRLGE(tGLRLM,r_matrix,c_matrix,N_runs):\n # Long Run Low Gray-Level Emphasis (LRLGE):\n\n term = tGLRLM*(c_matrix**2)/(r_matrix**2)\n LRLGE = np.sum(np.sum(term))/N_runs\n return LRLGE\n\ndef calculate_LRHGE(tGLRLM,r_matrix,c_matrix,N_runs):\n\n # Long Run High Gray-Level Emphasis (LRHGE):\n term = tGLRLM*(c_matrix**2)*(r_matrix**2);\n LRHGE = np.sum(np.sum(term))/N_runs;\n return LRHGE\n\n \n \n#b = [[0,0,1,1,0,0],[2,2,0,0,1,1],[0,0,1,2,0,0],[2,0,1,1,0,0],[0,0,2,1,1,1],[1,2,0,0,1,1]]\n#print(glrlm(b, 4, 0))\n#print(glrlm(b, 4, 45))\n#print(glrlm(b, 4, 90))\n#print(glrlm(b, 4, 135)) ","sub_path":"classical/glrlm.py","file_name":"glrlm.py","file_ext":"py","file_size_in_byte":5978,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"221948497","text":"import matplotlib.pyplot as plt\nfrom mpl_toolkits.axes_grid1 import make_axes_locatable\nimport numpy as np\nfrom scipy.interpolate import interp1d\n\nfrom spectractor import parameters\nfrom spectractor.config import set_logger\nfrom spectractor.simulation.simulator import SimulatorInit, SpectrumSimulation\nfrom spectractor.simulation.atmosphere import Atmosphere, AtmosphereGrid\nfrom spectractor.fit.fitter import FitWorkspace, run_minimisation_sigma_clipping\nfrom spectractor.tools import plot_spectrum_simple\n\n\nclass SpectrumFitWorkspace(FitWorkspace):\n\n def __init__(self, file_name, atmgrid_file_name=\"\", nwalkers=18, nsteps=1000, burnin=100, nbins=10,\n verbose=0, plot=False, live_fit=False, truth=None):\n \"\"\"Class to fit a spectrum extracted with Spectractor.\n\n The spectrum is supposed to be the product of the star SED, the instrument throughput and the atmospheric\n transmission, contaminated eventually by a second order diffraction.\n The truth parameters are loaded from the file header if provided.\n If provided, the atmospheric grid is used for the atmospheric transmission simulations and interpolated\n with splines, otherwise Libradtran is called at each step (slower).\n\n Parameters\n ----------\n file_name: str\n Spectrum file name.\n atmgrid_file_name: str, optional\n Atmospheric grid file name (default: \"\").\n nwalkers: int, optional\n Number of walkers for MCMC fitting.\n nsteps: int, optional\n Number of steps for MCMC fitting.\n burnin: int, optional\n Number of burn-in steps for MCMC fitting.\n nbins: int, optional\n Number of bins for MCMC chains analysis.\n verbose: int, optional\n Verbosity level (default: 0).\n plot: bool, optional\n If True, many plots are produced (default: False).\n live_fit: bool, optional\n If True, many plots along the fitting procedure are produced to see convergence in live (default: False).\n truth: array_like, optional\n Array of truth parameters to compare with the best fit result (default: None).\n\n Examples\n --------\n\n >>> filename = 'tests/data/reduc_20170530_134_spectrum.fits'\n >>> atmgrid_filename = filename.replace('spectrum', 'atmsim')\n >>> load_config(\"config/ctio.ini\")\n >>> w = SpectrumFitWorkspace(filename, atmgrid_file_name=atmgrid_filename, nsteps=1000,\n ... burnin=2, nbins=10, verbose=1, plot=True, live_fit=False)\n >>> lambdas, model, model_err = w.simulate(*w.p)\n >>> w.plot_fit()\n\n \"\"\"\n FitWorkspace.__init__(self, file_name, nwalkers, nsteps, burnin, nbins, verbose, plot, live_fit, truth=truth)\n if \"spectrum\" not in file_name:\n raise ValueError(\"file_name argument must contain spectrum keyword and be an output from Spectractor.\")\n self.my_logger = set_logger(self.__class__.__name__)\n self.spectrum, self.telescope, self.disperser, self.target = SimulatorInit(file_name)\n self.airmass = self.spectrum.header['AIRMASS']\n self.pressure = self.spectrum.header['OUTPRESS']\n self.temperature = self.spectrum.header['OUTTEMP']\n if atmgrid_file_name == \"\":\n self.atmosphere = Atmosphere(self.airmass, self.pressure, self.temperature)\n else:\n self.use_grid = True\n self.atmosphere = AtmosphereGrid(file_name, atmgrid_file_name)\n if parameters.VERBOSE:\n self.my_logger.info(f'\\n\\tUse atmospheric grid models from file {atmgrid_file_name}. ')\n self.lambdas = self.spectrum.lambdas\n self.data = self.spectrum.data\n self.err = self.spectrum.err\n self.data_cov = self.spectrum.cov_matrix\n self.A1 = 1.0\n self.A2 = 0\n self.ozone = 400.\n self.pwv = 3\n self.aerosols = 0.05\n self.reso = -1\n self.D = self.spectrum.header['D2CCD']\n self.shift_x = self.spectrum.header['PIXSHIFT']\n self.B = 0\n self.p = np.array([self.A1, self.A2, self.ozone, self.pwv, self.aerosols, self.reso, self.D,\n self.shift_x, self.B])\n self.fixed = [False] * self.p.size\n # self.fixed[0] = True\n # self.fixed[1] = True\n self.fixed[5] = True\n self.fixed[6:8] = [True, True]\n # self.fixed[7] = False\n self.fixed[8] = True\n # self.fixed[-1] = True\n self.input_labels = [\"A1\", \"A2\", \"ozone\", \"PWV\", \"VAOD\", \"reso [pix]\", r\"D_CCD [mm]\",\n r\"alpha_pix [pix]\", \"B\"]\n self.axis_names = [\"$A_1$\", \"$A_2$\", \"ozone\", \"PWV\", \"VAOD\", \"reso [pix]\", r\"$D_{CCD}$ [mm]\",\n r\"$\\alpha_{\\mathrm{pix}}$ [pix]\", \"$B$\"]\n self.bounds = [(0, 2), (0, 2/parameters.GRATING_ORDER_2OVER1), (300, 700), (0, 10), (0, 0.01),\n (0, 10), (50, 60), (-2, 2), (-np.inf, np.inf)]\n if atmgrid_file_name != \"\":\n self.bounds[2] = (min(self.atmosphere.OZ_Points), max(self.atmosphere.OZ_Points))\n self.bounds[3] = (min(self.atmosphere.PWV_Points), max(self.atmosphere.PWV_Points))\n self.bounds[4] = (min(self.atmosphere.AER_Points), max(self.atmosphere.AER_Points))\n self.nwalkers = max(2 * self.ndim, nwalkers)\n self.simulation = SpectrumSimulation(self.spectrum, self.atmosphere, self.telescope, self.disperser)\n self.amplitude_truth = None\n self.lambdas_truth = None\n self.output_file_name = file_name.replace('_spectrum', '_spectrum_A2=0')\n self.get_truth()\n\n def get_truth(self):\n \"\"\"Load the truth parameters (if provided) from the file header.\n\n \"\"\"\n if 'A1_T' in list(self.spectrum.header.keys()):\n A1_truth = self.spectrum.header['A1_T']\n A2_truth = 0 * self.spectrum.header['A2_T']\n ozone_truth = self.spectrum.header['OZONE_T']\n pwv_truth = self.spectrum.header['PWV_T']\n aerosols_truth = self.spectrum.header['VAOD_T']\n reso_truth = -1\n D_truth = self.spectrum.header['D2CCD_T']\n shift_truth = 0\n B_truth = 0\n self.truth = (A1_truth, A2_truth, ozone_truth, pwv_truth, aerosols_truth,\n reso_truth, D_truth, shift_truth, B_truth)\n self.lambdas_truth = np.fromstring(self.spectrum.header['LBDAS_T'][1:-1], sep=' ', dtype=float)\n self.amplitude_truth = np.fromstring(self.spectrum.header['AMPLIS_T'][1:-1], sep=' ', dtype=float)\n else:\n self.truth = None\n\n def plot_spectrum_comparison_simple(self, ax, title='', extent=None, size=0.4):\n \"\"\"Method to plot a spectrum issued from data and compare it with simulations.\n\n Parameters\n ----------\n ax: Axes\n Axes instance of shape (4, 2).\n title: str, optional\n Title for the simulation plot (default: '').\n extent: array_like, optional\n Extent argument for imshow to crop plots (default: None).\n size: float, optional\n Relative size of the residual pad (default: 0.4).\n \"\"\"\n lambdas = self.spectrum.lambdas\n sub = np.where((lambdas > parameters.LAMBDA_MIN) & (lambdas < parameters.LAMBDA_MAX))\n if extent is not None:\n sub = np.where((lambdas > extent[0]) & (lambdas < extent[1]))\n plot_spectrum_simple(ax, lambdas=lambdas, data=self.data, data_err=self.err,\n units=self.spectrum.units)\n p0 = ax.plot(lambdas, self.model, label='model')\n ax.fill_between(lambdas, self.model - self.model_err,\n self.model + self.model_err, alpha=0.3, color=p0[0].get_color())\n if self.amplitude_truth is not None:\n ax.plot(self.lambdas_truth, self.amplitude_truth, 'g', label=\"truth\")\n # ax.plot(self.lambdas, self.model_noconv, label='before conv')\n if title != '':\n ax.set_title(title, fontsize=10)\n ax.legend()\n divider = make_axes_locatable(ax)\n ax2 = divider.append_axes(\"bottom\", size=size, pad=0, sharex=ax)\n ax.figure.add_axes(ax2)\n min_positive = np.min(self.model[self.model > 0])\n idx = np.logical_not(np.isclose(self.model[sub], 0, atol=0.01 * min_positive))\n residuals = (self.spectrum.data[sub][idx] - self.model[sub][idx]) / self.err[sub][idx]\n residuals_err = self.spectrum.err[sub][idx] / self.err[sub][idx]\n ax2.errorbar(lambdas[sub][idx], residuals, yerr=residuals_err, fmt='ro', markersize=2, label='(Data-Model)/Err')\n ax2.axhline(0, color=p0[0].get_color())\n ax2.grid(True)\n residuals_model = self.model_err[sub][idx] / self.err[sub][idx]\n ax2.fill_between(lambdas[sub][idx], -residuals_model, residuals_model, alpha=0.3, color=p0[0].get_color())\n # std = np.std(residuals)\n # ax2.set_ylim([-2. * std, 2. * std])\n ax2.set_xlabel(ax.get_xlabel())\n # ax2.set_ylabel('(Data-Model)/Err', fontsize=10)\n ax2.legend()\n ax2.set_xlim((lambdas[sub][0], lambdas[sub][-1]))\n ax.set_xlim((lambdas[sub][0], lambdas[sub][-1]))\n ax.set_ylim((0.9 * np.min(self.spectrum.data[sub]), 1.1 * np.max(self.spectrum.data[sub])))\n ax.set_xticks(ax2.get_xticks()[1:-1])\n ax.get_yaxis().set_label_coords(-0.08, 0.6)\n # ax2.get_yaxis().set_label_coords(-0.11, 0.5)\n\n def simulate(self, A1, A2, ozone, pwv, aerosols, reso, D, shift_x, B):\n \"\"\"Interface method to simulate a spectrogram.\n\n Parameters\n ----------\n A1: float\n Main amplitude parameter.\n A2: float\n Relative amplitude of the order 2 spectrogram.\n ozone: float\n Ozone parameter for Libradtran (in db).\n pwv: float\n Precipitable Water Vapor quantity for Libradtran (in mm).\n aerosols: float\n Vertical Aerosols Optical Depth quantity for Libradtran (no units).\n reso: float\n Width of the Gaussian kernel to convolve the spectrum.\n D: float\n Distance between the CCD and the disperser (in mm).\n shift_x: float\n Shift of the order 0 position along the X axis (in pixels).\n B: float\n Amplitude of the simulated background (considered flat in ADUs).\n\n Returns\n -------\n lambdas: array_like\n Array of wavelengths (1D).\n model: array_like\n 2D array of the spectrogram simulation.\n model_err: array_like\n 2D array of the spectrogram simulation uncertainty.\n\n Examples\n --------\n\n >>> filename = 'tests/data/sim_20170530_134_spectrum.fits'\n >>> atmgrid_filename = filename.replace('spectrum', 'atmsim')\n >>> load_config(\"config/ctio.ini\")\n >>> w = SpectrumFitWorkspace(filename, atmgrid_filename, verbose=1, plot=True, live_fit=False)\n >>> lambdas, model, model_err = w.simulate(*w.p)\n >>> w.plot_fit()\n\n \"\"\"\n lambdas, model, model_err = self.simulation.simulate(A1, A2, ozone, pwv, aerosols, reso, D, shift_x, B)\n self.model = model\n self.model_err = model_err\n return lambdas, model, model_err\n\n def plot_fit(self):\n \"\"\"Plot the fit result.\n\n Examples\n --------\n\n >>> filename = 'tests/data/reduc_20170530_134_spectrum.fits'\n >>> atmgrid_filename = filename.replace('spectrum', 'atmsim')\n >>> load_config(\"config/ctio.ini\")\n >>> w = SpectrumFitWorkspace(filename, atmgrid_filename, verbose=1, plot=True, live_fit=False)\n >>> lambdas, model, model_err = w.simulate(*w.p)\n >>> w.plot_fit()\n\n .. plot::\n :include-source:\n\n from spectractor.fit.fit_spectrum import SpectrumFitWorkspace\n file_name = 'tests/data/reduc_20170530_134_spectrum.fits'\n atmgrid_file_name = file_name.replace('spectrum', 'atmsim')\n fit_workspace = SpectrumFitWorkspace(file_name, atmgrid_file_name=atmgrid_file_name, verbose=True)\n A1, A2, ozone, pwv, aerosols, reso, D, shift_x = fit_workspace.p\n lambdas, model, model_err = fit_workspace.simulation.simulate(A1,A2,ozone, pwv, aerosols, reso, D, shift_x)\n fit_workspace.lambdas = lambdas\n fit_workspace.model = model\n fit_workspace.model_err = model_err\n fit_workspace.plot_fit()\n\n \"\"\"\n fig = plt.figure(figsize=(12, 6))\n ax1 = plt.subplot(222)\n ax2 = plt.subplot(224)\n ax3 = plt.subplot(121)\n A1, A2, ozone, pwv, aerosols, reso, D, shift, B = self.p\n self.title = f'A1={A1:.3f}, A2={A2:.3f}, PWV={pwv:.3f}, OZ={ozone:.3g}, VAOD={aerosols:.3f},\\n ' \\\n f'reso={reso:.2f}pix, D={D:.2f}mm, shift={shift:.2f}pix, B={B:.2g}'\n # main plot\n self.plot_spectrum_comparison_simple(ax3, title=self.title, size=0.8)\n # zoom O2\n self.plot_spectrum_comparison_simple(ax2, extent=[730, 800], title='Zoom $O_2$', size=0.8)\n # zoom H2O\n self.plot_spectrum_comparison_simple(ax1, extent=[870, 1000], title='Zoom $H_2 O$', size=0.8)\n fig.tight_layout()\n if self.live_fit:\n plt.draw()\n plt.pause(1e-8)\n plt.close()\n else:\n if parameters.DISPLAY and parameters.VERBOSE:\n plt.show()\n if parameters.PdfPages:\n parameters.PdfPages.savefig()\n if parameters.SAVE:\n figname = self.filename.replace('.fits', '_bestfit.pdf')\n self.my_logger.info(f'Save figure {figname}.')\n fig.savefig(figname, dpi=100, bbox_inches='tight')\n\n def decontaminate_order2(self):\n lambdas = self.spectrum.lambdas\n lambdas_order2 = self.simulation.lambdas_order2\n A1, A2, ozone, pwv, aerosols, reso, D, shift, B = self.p\n lambdas_binwidths_order2 = np.gradient(lambdas_order2)\n lambdas_binwidths = np.gradient(lambdas)\n sim_conv = interp1d(lambdas, self.model * lambdas, kind=\"linear\", bounds_error=False, fill_value=(0, 0))\n err_conv = interp1d(lambdas, self.model_err * lambdas, kind=\"linear\", bounds_error=False, fill_value=(0, 0))\n spectrum_order2 = sim_conv(lambdas_order2) * lambdas_binwidths_order2 / lambdas_binwidths\n err_order2 = err_conv(lambdas_order2) * lambdas_binwidths_order2 / lambdas_binwidths\n self.model = (sim_conv(lambdas) - A2 * spectrum_order2) / lambdas\n self.model_err = (err_conv(lambdas) - A2 * err_order2) / lambdas\n\n def get_truth_without_order2(self):\n lambdas, model, model_err = self.simulation.simulate(1., 0., self.ozone, self.pwv, self.aerosols, self.reso,\n self.D, self.shift_x)\n self.lambdas_truth = lambdas\n self.amplitude_truth = model\n\n\ndef lnprob_spectrum(p):\n \"\"\"Logarithmic likelihood function to maximize in MCMC exploration.\n\n Parameters\n ----------\n p: array_like\n Array of SpectrumFitWorkspace parameters.\n\n Returns\n -------\n lp: float\n Log of the likelihood function.\n\n \"\"\"\n global w\n lp = w.lnprior(p)\n if not np.isfinite(lp):\n return -1e20\n return lp + w.lnlike(p)\n\n\ndef run_spectrum_minimisation(fit_workspace, method=\"newton\"):\n \"\"\"Interface function to fit spectrum simulation parameters to data.\n\n Parameters\n ----------\n fit_workspace: SpectrumFitWorkspace\n An instance of the SpectrogramFitWorkspace class.\n method: str, optional\n Fitting method (default: 'newton').\n\n Examples\n --------\n\n >>> filename = 'tests/data/sim_20170530_134_spectrum.fits'\n >>> atmgrid_filename = filename.replace('sim', 'reduc').replace('spectrum', 'atmsim')\n >>> load_config(\"config/ctio.ini\")\n >>> w = SpectrumFitWorkspace(filename, atmgrid_file_name=atmgrid_filename, verbose=1, plot=True, live_fit=False)\n >>> parameters.VERBOSE = True\n >>> run_spectrum_minimisation(w, method=\"newton\")\n\n \"\"\"\n my_logger = set_logger(__name__)\n guess = np.asarray(fit_workspace.p)\n if method != \"newton\":\n run_minimisation(fit_workspace, method=method)\n else:\n # fit_workspace.simulation.fast_sim = True\n # costs = np.array([fit_workspace.chisq(guess)])\n # if parameters.DISPLAY and (parameters.DEBUG or fit_workspace.live_fit):\n # fit_workspace.plot_fit()\n # params_table = np.array([guess])\n my_logger.info(f\"\\n\\tStart guess: {guess}\\n\\twith {fit_workspace.input_labels}\")\n epsilon = 1e-4 * guess\n epsilon[epsilon == 0] = 1e-4\n epsilon[-1] = 0.001 * np.max(fit_workspace.data)\n\n # fit_workspace.simulation.fast_sim = True\n # fit_workspace.simulation.fix_psf_cube = False\n # run_minimisation_sigma_clipping(fit_workspace, method=\"newton\", epsilon=epsilon, fix=fit_workspace.fixed,\n # xtol=1e-4, ftol=1 / fit_workspace.data.size, sigma_clip=10, niter_clip=3,\n # verbose=False)\n\n fit_workspace.simulation.fast_sim = False\n run_minimisation_sigma_clipping(fit_workspace, method=\"newton\", epsilon=epsilon, fix=fit_workspace.fixed,\n xtol=1e-6, ftol=1 / fit_workspace.data.size, sigma_clip=10, niter_clip=3,\n verbose=False)\n if fit_workspace.filename != \"\":\n parameters.SAVE = True\n ipar = np.array(np.where(np.array(fit_workspace.fixed).astype(int) == 0)[0])\n fit_workspace.plot_correlation_matrix(ipar)\n header = f\"{fit_workspace.spectrum.date_obs}\\nchi2: {fit_workspace.costs[-1] / fit_workspace.data.size}\"\n fit_workspace.save_parameters_summary(ipar, header=header)\n # save_gradient_descent(fit_workspace, costs, params_table)\n fit_workspace.plot_fit()\n parameters.SAVE = False\n\n\nif __name__ == \"__main__\":\n from argparse import ArgumentParser\n from spectractor.config import load_config\n from spectractor.fit.fitter import run_minimisation\n\n parser = ArgumentParser()\n parser.add_argument(dest=\"input\", metavar='path', default=[\"tests/data/reduc_20170530_134_spectrum.fits\"],\n help=\"Input fits file name. It can be a list separated by spaces, or it can use * as wildcard.\",\n nargs='*')\n parser.add_argument(\"-d\", \"--debug\", dest=\"debug\", action=\"store_true\",\n help=\"Enter debug mode (more verbose and plots).\", default=True)\n parser.add_argument(\"-v\", \"--verbose\", dest=\"verbose\", action=\"store_true\",\n help=\"Enter verbose (print more stuff).\", default=False)\n parser.add_argument(\"-o\", \"--output_directory\", dest=\"output_directory\", default=\"outputs/\",\n help=\"Write results in given output directory (default: ./outputs/).\")\n parser.add_argument(\"-l\", \"--logbook\", dest=\"logbook\", default=\"ctiofulllogbook_jun2017_v5.csv\",\n help=\"CSV logbook file. (default: ctiofulllogbook_jun2017_v5.csv).\")\n parser.add_argument(\"-c\", \"--config\", dest=\"config\", default=\"config/ctio.ini\",\n help=\"INI config file. (default: config.ctio.ini).\")\n args = parser.parse_args()\n\n parameters.VERBOSE = args.verbose\n if args.debug:\n parameters.DEBUG = True\n parameters.VERBOSE = True\n\n file_names = args.input\n\n load_config(args.config)\n\n filenames = ['outputs/sim_20170530_134_spectrum.fits']\n filenames = [\n 'outputs/data_30may17_HoloAmAg_prod6.9/sim_20170530_104_spectrum.fits',\n 'outputs/data_30may17_HoloAmAg_prod6.9/sim_20170530_109_spectrum.fits',\n 'outputs/data_30may17_HoloAmAg_prod6.9/sim_20170530_114_spectrum.fits',\n 'outputs/data_30may17_HoloAmAg_prod6.9/sim_20170530_119_spectrum.fits',\n 'outputs/data_30may17_HoloAmAg_prod6.9/sim_20170530_124_spectrum.fits',\n 'outputs/data_30may17_HoloAmAg_prod6.9/sim_20170530_129_spectrum.fits',\n 'outputs/data_30may17_HoloAmAg_prod6.9/sim_20170530_134_spectrum.fits',\n 'outputs/data_30may17_HoloAmAg_prod6.9/sim_20170530_139_spectrum.fits',\n 'outputs/data_30may17_HoloAmAg_prod6.9/sim_20170530_144_spectrum.fits',\n 'outputs/data_30may17_HoloAmAg_prod6.9/sim_20170530_149_spectrum.fits',\n 'outputs/data_30may17_HoloAmAg_prod6.9/sim_20170530_154_spectrum.fits',\n 'outputs/data_30may17_HoloAmAg_prod6.9/sim_20170530_159_spectrum.fits',\n 'outputs/data_30may17_HoloAmAg_prod6.9/sim_20170530_164_spectrum.fits',\n 'outputs/data_30may17_HoloAmAg_prod6.9/sim_20170530_169_spectrum.fits',\n 'outputs/data_30may17_HoloAmAg_prod6.9/sim_20170530_174_spectrum.fits',\n 'outputs/data_30may17_HoloAmAg_prod6.9/sim_20170530_179_spectrum.fits',\n 'outputs/data_30may17_HoloAmAg_prod6.9/sim_20170530_184_spectrum.fits',\n 'outputs/data_30may17_HoloAmAg_prod6.9/sim_20170530_189_spectrum.fits',\n 'outputs/data_30may17_HoloAmAg_prod6.9/sim_20170530_194_spectrum.fits',\n 'outputs/data_30may17_HoloAmAg_prod6.9/sim_20170530_199_spectrum.fits']\n params = []\n chisqs = []\n filenames = ['outputs/sim_20170530_134_spectrum.fits']\n for filename in filenames:\n atmgrid_filename = filename.replace('sim', 'reduc').replace('spectrum', 'atmsim')\n\n w = SpectrumFitWorkspace(filename, atmgrid_file_name=atmgrid_filename, nsteps=1000,\n burnin=200, nbins=10, verbose=1, plot=True, live_fit=False)\n run_spectrum_minimisation(w, method=\"newton\")\n params.append(w.p)\n chisqs.append(w.costs[-1])\n params = np.asarray(params).T\n\n # fig, ax = plt.subplots(1, len(params))\n # for ip, p in enumerate(params):\n # print(f\"{w.input_labels[ip]}:\", np.mean(p), np.std(p))\n # ax[ip].plot(p, label=f\"{w.input_labels[ip]}\")\n # ax[ip].grid()\n # ax[ip].legend()\n # plt.show()\n\n # w.decontaminate_order2()\n # fit_workspace.simulate(*fit_workspace.p)\n # fit_workspace.plot_fit()\n # run_emcee(fit_workspace, ln=lnprob_spectrum)\n # fit_workspace.analyze_chains()\n","sub_path":"spectractor/fit/fit_spectrum.py","file_name":"fit_spectrum.py","file_ext":"py","file_size_in_byte":22564,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"273260688","text":"import math\nfrom typing import *\n\nclass State:\n\n \"\"\"\n The State class can return the current player name, determine the valid\n moves.\n \"\"\"\n\n def __init__(self, is_p1_turn: bool) -> None:\n\n \"\"\"Create a new State self with is_p1_turn\n\n @param self: State\n @param is_p1_turn: player one's turn\n @rtype: None\n \"\"\"\n self.is_p1_turn = is_p1_turn\n\n\n def get_current_player_name(self) -> str:\n \"\"\"\n Return the current player name.\n\n @param self: State\n @rtype: str\n\n >>> self.is_p1_turn == True\n 'p1'\n\n >>> self.is_p1_turn == False\n 'p2'\n \"\"\"\n\n if self.is_p1_turn:\n return 'p1'\n return 'p2'\n\n\n def get_possible_moves(self):\n raise NotImplementedError('Subclass needed!')\n\n\n def is_valid_move(self, move_to_make: Any) -> bool:\n \"\"\"\n Return True if the moves are valid.\n\n @param self: State\n @param move_to_make: user input\n @rtype: bool\n\n >>> move_to_make = 4\n >>> self.get_possible_moves() == [1, 2, 3]\n >>> self.is_valid_move()\n False\n\n >>> move_to_make = 4\n >>> self.get_possible_moves() == [1, 2, 4]\n >>> self.is_valid_move()\n True\n \"\"\"\n if move_to_make in self.get_possible_moves():\n return True\n return False\n\n def make_move(self, move_to_make):\n\n if self.is_p1_turn == True:\n self.is_p1_turn = False\n else:\n self.is_p1_turn = True\n\n\n def __eq__(self, other: 'State') -> bool:\n \"\"\"\n Return whether Rational self is equivalent to other.\n\n @param self: State\n @param other: State | Any\n @rtype: bool\n \"\"\"\n return (type(self) == type(other)) and (self.is_p1_turn == other.is_p1_turn)\n\n\n def __str__(self):\n raise NotImplementedError\n\n\nclass SubSquareState(State):\n\n \"\"\"\n The SubSquareState class is able to determine the possible moves,\n and apply the move.\n \"\"\"\n\n def __init__(self, is_p1_turn: bool, remaining_number: int =None) -> None:\n\n \"\"\"\n Create a new SubSquareState self with is_p1_turn\n\n @param self: SubSquareState\n @param is_p1_turn: player one's turn\n @rtype: None\n \"\"\"\n self.remaining_number = remaining_number\n if remaining_number is None:\n self.remaining_number = int(input(\"Please enter the number to start: \"))\n State.__init__(self, is_p1_turn)\n\n def get_possible_moves(self) -> List:\n \"\"\"\n Return the next possible moves for the player.\n\n @param self: SubSquareState\n @rtype: List\n\n >>> self.remaining_number = 13\n >>> self.get_possible_moves()\n ['1', '4', '9']\n\n >>> self.remaining_number = 0\n >>> self.get_possible_moves()\n []\n \"\"\"\n move = []\n possible = int(math.sqrt(self.remaining_number))\n for num in range(1, possible + 1):\n move.append(str(num ** 2))\n return move\n\n\n def make_move(self, move_to_make: int) -> 'State':\n\n \"\"\"\n Return a new SubSquareState with valid move.\n\n >>> self.remaining_number = 5\n >>> move_to_make = 4\n self.remaining_number = 1\n\n >>> self.remaining_number = 4\n >>> move_to_make = 4\n self.remaining_number = 0\n\n \"\"\"\n\n if self.is_p1_turn:\n new_player_turn = False\n else:\n new_player_turn = True\n\n new_val = self.remaining_number - int(move_to_make)\n new_state = SubSquareState(new_player_turn, new_val)\n\n return new_state\n\n def __str__(self) -> str:\n\n \"\"\"Return the string representation of the current remaining number.\"\"\"\n\n return 'the remaining number is {}'.format(self.remaining_number)\n\n\nclass ChopstickState(State):\n\n '''The ChopsticksState class updates the state of the hands every time the\n player makes a move.'''\n\n starting_set_up: Dict\n\n def __init__(self, is_p1_turn: bool) -> None:\n\n \"\"\"\n Creates a new self with is_p1_turn.\n \"\"\"\n\n State.__init__(self, is_p1_turn)\n self.starting_set_up = {'l1': 1, 'r1': 1, 'l2': 1, 'r2': 1}\n self.p1_moves = [\"ll\", \"lr\", \"rl\", \"rr\"]\n self.p2_moves = [\"ll\", \"lr\", \"rl\", \"rr\"]\n self.p1_hand_state = [True, True]\n self.p2_hand_state = [True, True]\n\n\n def get_possible_moves(self) -> List:\n\n \"\"\"\n Return the possible moves.\n\n @param self: ChopstickState\n @rtype: List\n\n >>> player = 'p1'\n >>> move = [\"ll\", \"lr\", \"rl\", \"rr\"]\n >>> self.get_possible_moves()\n ['l1', 'l2']\n \"\"\"\n\n results = []\n if self.get_current_player_name() == 'p1':\n for move in self.p1_moves:\n move = move[0] + \"1\" + \", \" + move[1] + \"2\"\n results.append(move)\n else:\n for move in self.p2_moves:\n move = move[0] + \"2\" + \", \" + move[1] + \"1\"\n results.append(move)\n return results\n\n\n def change_possible_moves(self, hand: int, player: int) -> None:\n\n '''Changes the next possible moves after make_move.\n\n @param hand:int\n @param player: int\n @rtype: None\n '''\n\n moves = self.p1_moves if player == 1 else self.p2_moves\n # player determines which hand is dead\n index = 0\n hand = \"l\" if hand == 0 else \"r\"\n while index < len(moves):\n if moves[index].startswith(hand):\n moves.remove(moves[index]) #removes the dead hand\n else:\n index += 1\n\n\n def make_move(self, move_to_make: List) -> State:\n\n \"\"\"\n Returns a new state of the game.\n \"\"\"\n\n if len(move_to_make) == 2:\n if self.get_current_player_name() == \"p1\":\n fixed_move = move_to_make[0] + \"1\" + \", \" + move_to_make[1] + \"2\"\n else:\n fixed_move = move_to_make[0] + \"2\" + \", \" + move_to_make[1] + \"1\"\n move_to_make = fixed_move\n\n lst = move_to_make.replace(' ', '').split(',') #space after comma\n self.starting_set_up[lst[1]] += self.starting_set_up[lst[0]]\n\n for hands in self.starting_set_up.keys():\n self.starting_set_up[hands] = self.starting_set_up[hands] % 5\n ind = 0 if hands.startswith('l') else 1\n #self.starting_set_up = {'l1': 1, 'r1': 1, 'l2': 1, 'r2': 1}\n if self.starting_set_up[hands] == 0:\n\n if hands.endswith('1'):\n self.p1_hand_state[ind] = False\n self.change_possible_moves(ind, 1)\n else:\n self.p2_hand_state[ind] = False\n self.change_possible_moves(ind, 2)\n\n if self.get_current_player_name() == 'p1':\n self.is_p1_turn = False\n else:\n self.is_p1_turn = True\n\n return self\n\n def __str__(self):\n\n \"\"\"Returns the string representation of the state.\"\"\"\n\n return \"the current state is: {}-{} {}-{}\".format(self.starting_set_up[\"l1\"], \\\n self.starting_set_up[\"r1\"], \\\n self.starting_set_up[\"l2\"], \\\n self.starting_set_up[\"r2\"])\n\n\nif __name__ == '__main__':\n import python_ta\n python_ta.check_all(config=\"a1_pyta.txt\")\n","sub_path":"csc148/a1/state.py","file_name":"state.py","file_ext":"py","file_size_in_byte":7543,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"231572261","text":"# 仅定义生成方法,不创建列表\ng = (x for x in range(1, 11))\nprint(g)\nprint(next(g))\nfor n in g:\n print(n)\n\n# 函数生成斐波拉契数列\n# def fib(max):\n# n, a, b = 0, 0, 1\n# while n < max:\n# print(b)\n# a, b = b, a + b\n# n = n + 1\n# return 'done'\n\n# 将函数改为generator\ndef fib(max):\n n, a, b = 0, 0, 1\n while n < max:\n yield (b)\n a, b = b, a + b\n n = n + 1\n\nfor i in fib(10):\n print(i)\n\n","sub_path":"com/AdvancedFeatures/Generator.py","file_name":"Generator.py","file_ext":"py","file_size_in_byte":477,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"349885009","text":"#!/usr/bin/env python\n\"\"\"This module implements a ROS node that\nplots the data relative to the coverage task.\"\"\"\n\nimport matplotlib as mpl\nmpl.use('Agg')\nimport matplotlib.pyplot as plt\nfrom matplotlib.transforms import Affine2D\nfrom matplotlib.backends.backend_agg import FigureCanvasAgg\n\nfrom matplotlib.patches import Rectangle\n\nfrom quad_control.msg import camera_pose\nfrom quad_control.srv import LandmarksTrade\n\n\nimport rospy\n\nfrom utilities.coverage_giorgio import Camera, Landmark_list\n\nget = rospy.get_param\n\nimport numpy\n\nfrom math import pi,cos,sin\n\n#import utilities.coverage_utilities as cov\n\nclass ProjectorPlotNode():\n\n\tdef __init__(self):\n\n\t\tself.frequency = get(\"/planner_frequency\",1e1)\n\t\tself.D_OPT = get(\"/D_OPT\",2)\n\t\tself.name_agents = get(\"/name_agents\", '').rsplit(' ')\n\n\t\tself.x_min = get(\"/x_min\",-1.5)\n\t\tself.y_min = get(\"/y_min\",-2.2)\n\t\tself.x_max = get(\"/x_max\",2)\n\t\tself.y_max = get(\"/y_max\",1.7)\n\t\tself.d_worry = get(\"/delta_worry\",0.5)\n\n\t\tself.r = get(\"/radius_circle_proj\",0.5)\n\n\t\trospy.init_node('projector_node', anonymous=True)\n\n\t\tself.colors = ['b', 'r', 'g']\n\n\t\tself.cam = {}\n\t\tself.lmks = {}\n\t\tself.index = {}\n\n\t\ti =0\n\t\tfor ns in self.name_agents:\n\t\t\tself.cam[ns] = Camera()\n\t\t\tself.lmks[ns] = Landmark_list([])\n\t\t\tself.index[ns] = i\n\t\t\ti += 1\n\t\t\t# plot, = ax.plot([], [], lw=2, label = \"position \" + ns, color = \"k\")\n\t\t\t# self.pos_plot_list[ns] = plot\n\t\t\t# plot, = ax.plot([], [], lw=2, label = \"orientation \" + ns , color = \"k\")\n\t\t\t# # arrow(0, 0, 0.5, 0.5, head_width=0.05, head_length=0.1, fc='k', ec='k')\n\t\t\t# # plot, = ax.arrow([], [], [], [], )\n\t\t\t# self.v_plot_list[ns] = plot\n\t\t\tif ns == \"\":\n\t\t\t\trospy.Subscriber(\"/camera_pose\", camera_pose, lambda data,ns = ns: self.camera_pose_callback(data,ns))\n\t\t\telse:\n\t\t\t\trospy.Subscriber(\"/\" + ns + \"/camera_pose\", camera_pose, lambda data,ns = ns: self.camera_pose_callback(data,ns))\n\n\t\trospy.Service(\"/load_lmks_projector\", LandmarksTrade, self.load_lmks)\t\n\n\n\n\t\t#plt.legend(self.plot_list.values())\n\t\t#self.ani = animation.FuncAnimation(self.figure, self.redraw, int(self.frequency), blit=False)\n\n\tdef camera_pose_callback(self, data, ns):\n\t\tself.cam[ns].new_pose(data)\n\n\tdef load_lmks(self,data):\n\t\t# rospy.logwarn(data.name_agent + str(id(self.lmks[data.name_agent])))\n\t\tself.lmks[data.name_agent] = Landmark_list([])\n\t\tself.lmks[data.name_agent].from_lists(q = data.q, u = data.u)\n\t\t# rospy.logwarn(\"Landmarks loaded projector\")\n\t\t# rospy.logwarn(str(data.name_agent))\n\t\t# rospy.logwarn(data.name_agent + str(id(self.lmks[data.name_agent])))\n\t\treturn {}\n\n\t# def redraw(self,data=None):\n\t# \tangle = numpy.linspace(-pi, pi, num=100)\n\t# \tfor ns in self.name_agents:\n\t# \t\tp = self.cam[ns].position()\n\t# \t\tx = [p[0] + self.r * cos(a) for a in angle]\n\t# \t\ty = [p[1] + self.r * sin(a) for a in angle]\n\t# \t\tself.pos_plot_list[ns].set_data(x,y)\n\t# \t\tv = self.cam[ns].orientation_as_vector()\n\t# \t\tself.v_plot_list[ns].set_data([p[0],p[0]+v[0]],[p[1],p[1]+v[1]])\n\t# \treturn self.pos_plot_list, self.v_plot_list\n\n\t# def run(self):\n\t# \tplt.show()\n\tdef save_to_proj(self):\n\t\tax = plt.gca()\n\t\tplt.axis('off')\n\t\tr = 4./3./1.04\n\t\tly = 6.50\n\t\tlx = ly*r\n\t\tcy = 0.75\n\t\tcx = 0.6\n\t\tax.set_xlim([cx-lx/2.,cx+lx/2.])\n\t\tax.set_ylim([cy-ly/2.,cy+ly/2.])\n\t\ttransform = Affine2D().rotate_deg(105)\n\t\tax.set_transform(transform)\n\t\tplt.savefig(\"/home/giorgiocorra/videoproj/videoproj.png\",bbox_inches='tight',dpi=120)\n\n\n\tdef save_plot(self):\n\t\tpos_plot_list = {}\n\t\tv_plot_list = {}\n\t\tlmk_plot_list = {}\n\n\t\tplt.clf()\n\t\tplt.cla()\n\n\t\t# # Cage\n\t\t# plt.axhspan(ymin = self.y_min, ymax = self.y_max, xmin = self.x_min, xmax = self.x_max, lw = 4, fc = 'none')\n\t\t# plt.axhspan(ymin = self.y_min + self.d_worry, ymax = self.y_max - self.d_worry, xmin = self.x_min + self.d_worry, xmax = self.x_max - self.d_worry, lw = 4, ls = 'dashed', fc = 'none')\n\t\t\n\t\t# Quads and lmks\n\t\tax = plt.gca()\n\t\tfigure = plt.gcf()\n\n\t\trect = Rectangle(xy=(self.x_min,self.y_min), width = self.x_max - self.x_min, height = self.y_max - self.y_min, fill = False, angle = 0.0, lw = 4)\n\t\tax.add_patch(rect)\n\t\trect = Rectangle(xy=(self.x_min + self.d_worry,self.y_min + self.d_worry), width = (self.x_max - self.d_worry) - (self.x_min + self.d_worry), height = (self.y_max - self.d_worry) - (self.y_min + self.d_worry), fill = False, angle = 0.0, lw = 4, ls = 'dashed')\n\t\tax.add_patch(rect)\n\t\tangle = numpy.linspace(-pi, pi, num=100)\n\t\tfor ns in self.name_agents:\n\t\t\tcol = self.colors[self.index[ns]]\n\t\t\t#rospy.logwarn(\"Color: \" + str(self.index[ns]))\n\t\t\tp = self.cam[ns].position()\n\t\t\tx = [p[0] + self.r * cos(a) for a in angle]\n\t\t\ty = [p[1] + self.r * sin(a) for a in angle]\n\t\t\tplot, = ax.plot([], [], lw=4, color = col)\n\t\t\tpos_plot_list[ns] = plot\n\t\t\tpos_plot_list[ns].set_data(x,y)\n\t\t\tv = self.cam[ns].orientation_as_vector()\n\t\t\tv_plot_list[ns] = ax.arrow(p[0], p[1], v[0], v[1], head_width=0.1, head_length=0.2, fc = col, ec= col, lw = 4)\n\t\t\tvis_set = self.lmks[ns].visible_set(self.cam[ns],self.D_OPT)\n\t\t\tnot_vis_set = self.lmks[ns].not_visible_set(self.cam[ns],self.D_OPT)\n\t\t\t#rospy.logwarn(str(not_vis_set))\n\t\t\tlmk_plot_list[ns] = []\n\t\t\tfor lmk in vis_set.lst:\n\t\t\t\tq = lmk.q\n\t\t\t\tu = lmk.u\n\t\t\t\tlmk_plot_list[ns].append(ax.arrow(q[0], q[1], 0.3*u[0], 0.3 * u[1], lw = 2,head_width=0.2, head_length=0.3, fc = col, ec= col, fill=True))\n\t\t\tfor lmk in not_vis_set.lst:\n\t\t\t\tq = lmk.q\n\t\t\t\tu = lmk.u\n\t\t\t\tlmk_plot_list[ns].append(ax.arrow(q[0], q[1], 0.3*u[0], 0.3 * u[1], lw=2, head_width=0.2, head_length=0.3, fc = 'w', ec= col, fill=True))\n\n\n\t\tself.save_to_proj()\n\n\nif __name__ == '__main__':\n\tplot_node = ProjectorPlotNode()\n\trate = rospy.Rate(4)\n\twhile not rospy.is_shutdown():\n\t\tplot_node.save_plot()\n\t\trate.sleep()\n\t# plot_node.run()\n\n\n","sub_path":"quad_control/scripts/projector_node.py","file_name":"projector_node.py","file_ext":"py","file_size_in_byte":5669,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}
+{"seq_id":"399482380","text":"import cv2\r\non = cv2.imread('on.jpg')\r\noff = cv2.imread('off.jpg')\r\nlock = cv2.imread('lock.jpg')\r\n\r\nglobal p\r\nF=0\r\nT=1\r\np=F\r\ncv2.imshow('result',on)\r\ndef click(event,x,y,flags,param):\r\n if event==cv2.EVENT_LBUTTONDOWN:\r\n print('mouse coords:',x,y) \r\n if 0\\n \\n abc\\n'\n )\n\n\ndef test_parse_text():\n document = parse_text(\n \"abc\", \"sphinx\", load_sphinx_env=True, sphinx_conf={\"project\": \"MyST Parser\"}\n )\n assert document.pformat() == (\n '\\n \\n abc\\n'\n )\n\n\ndef test_strong(renderer_mock):\n render_token(renderer_mock, \"Strong\")\n assert renderer_mock.document.pformat() == dedent(\n \"\"\"\\\n \n \n \"\"\"\n )\n\n\ndef test_emphasis(renderer_mock):\n render_token(renderer_mock, \"Emphasis\")\n assert renderer_mock.document.pformat() == dedent(\n \"\"\"\\\n \n \n \"\"\"\n )\n\n\ndef test_raw_text(renderer_mock):\n render_token(renderer_mock, \"RawText\", children=False, content=\"john & jane\")\n assert renderer_mock.document.pformat() == dedent(\n \"\"\"\\\n \n john & jane\n \"\"\"\n )\n\n\ndef test_inline_code(renderer_mock):\n renderer_mock.render(tokenize_span(\"`foo`\")[0])\n assert renderer_mock.document.pformat() == dedent(\n \"\"\"\\\n \n \n foo\n \"\"\"\n )\n\n\ndef test_paragraph(renderer_mock):\n render_token(renderer_mock, \"Paragraph\", position=(0, 1))\n assert renderer_mock.document.pformat() == dedent(\n \"\"\"\\\n \n \n \"\"\"\n )\n\n\ndef test_heading(renderer_mock):\n render_token(renderer_mock, \"Heading\", level=1, position=(0, 0))\n assert renderer_mock.document.pformat() == dedent(\n \"\"\"\\\n \n \n \n \"\"\"\n )\n\n\ndef test_block_code(renderer_mock):\n\n renderer_mock.render(tokenize_main([\"```sh\\n\", \"foo\\n\", \"```\\n\"])[0])\n assert renderer_mock.document.pformat() == dedent(\n \"\"\"\\\n \n \n foo\n \"\"\"\n )\n\n\ndef test_block_code_no_language(renderer_mock):\n\n renderer_mock.render(tokenize_main([\"```\\n\", \"foo\\n\", \"```\\n\"])[0])\n assert renderer_mock.document.pformat() == dedent(\n \"\"\"\\\n \n \n foo\n \"\"\"\n )\n\n\ndef test_image(renderer_mock):\n render_token(renderer_mock, \"Image\", src=\"src\", title=\"title\")\n assert renderer_mock.document.pformat() == dedent(\n \"\"\"\\\n \n \n \"\"\"\n )\n\n\ndef test_image_with_alt(renderer_mock):\n renderer_mock.render(tokenize_main([r\"\"])[0])\n assert renderer_mock.document.pformat() == dedent(\n \"\"\"\\\n \n \n \n \"\"\"\n )\n\n\ndef test_quote(renderer_mock):\n render_token(renderer_mock, \"Quote\", position=(0, 0))\n assert renderer_mock.document.pformat() == dedent(\n \"\"\"\\\n \n \n \"\"\"\n )\n\n\ndef test_bullet_list(renderer_mock):\n render_token(renderer_mock, \"List\", start_at=None)\n assert renderer_mock.document.pformat() == dedent(\n \"\"\"\\\n \n \n \"\"\"\n )\n\n\ndef test_enumerated_list(renderer_mock):\n render_token(renderer_mock, \"List\", start_at=1)\n assert renderer_mock.document.pformat() == dedent(\n \"\"\"\\\n \n \n \"\"\"\n )\n\n\ndef test_list_item(renderer_mock):\n render_token(renderer_mock, \"ListItem\")\n assert renderer_mock.document.pformat() == dedent(\n \"\"\"\\\n \n \n \"\"\"\n )\n\n\ndef test_math(renderer_mock):\n render_token(renderer_mock, \"Math\", content=\"$a$\")\n assert renderer_mock.document.pformat() == dedent(\n \"\"\"\\\n \n