diff --git "a/4420.jsonl" "b/4420.jsonl" new file mode 100644--- /dev/null +++ "b/4420.jsonl" @@ -0,0 +1,687 @@ +{"seq_id":"630738337","text":"import os\nimport re\nimport numpy as np\nimport pandas as pd\nimport random as rd\nfrom .utils import padding\nfrom .preprocess import Preprocess\n\ncolumns=[\"documentId\",\"sentenceId\",\"sentence\"]\n\n\nclass PathLineDocuments():\n \"\"\"Load documents through files.\n Each item corresponds to each document.\n Each sentence in a document is preprocessed in this class.\n \n Args (str): path to the source file or directory\n \"\"\"\n def __init__(self, source, limit=None):\n self.source = source\n self.limit = limit\n self.num_valid_data=0\n self.is_counted=False\n if os.path.isfile(self.source):\n self.input_files = [self.source]\n elif os.path.isdir(self.source):\n self.source = os.path.join(self.source, '')\n self.input_files = os.listdir(self.source)\n self.input_files = [self.source + file for file in self.input_files]\n self.input_files.sort()\n else:\n raise ValueError('input is neither a file nor a path')\n \n def __iter__(self):\n \"\"\"iterate through the files\"\"\"\n for file_name in self.input_files:\n ids, sentences = self.read_tsv(file_name)\n if not self.is_counted:\n self.num_valid_data += len(sentences) - len(np.unique(np.array(ids)[:,1]))*2\n yield (ids, sentences)\n if not self.is_counted:\n print(\"loaded {} files.\".format(len(self.input_files)))\n print(\"There are {} sentences available for training.\".format(self.num_valid_data))\n self.is_counted=True\n \n def read_tsv(self, filepath):\n df = pd.read_csv(filepath, delimiter=',', header=0, names=columns)\n \n document_ids = df[\"documentId\"].values\n sentence_ids = df[\"sentenceId\"].values\n self._ids = np.column_stack((document_ids, sentence_ids))\n self._sentences = df[\"sentence\"].values\n return self._ids, self._sentences\n \nclass DataLoader():\n def __init__(self, documents, batch_size, n_positive, n_negative, seq_length, token2id, random_seed=42):\n assert isinstance(documents, PathLineDocuments)\n self.documents = documents\n self.batch_size = batch_size\n self.n_positive = n_positive\n self.n_negative = n_negative\n self.seq_length = seq_length\n self.token2id = token2id\n self.unk = token2id['']\n self.valid_sen = 0\n self.not_valid_sen = 0\n rd.seed(random_seed)\n \n def __iter__(self):\n tar=[]\n pos=[[] for i in range(self.n_positive)]\n neg=[[] for i in range(self.n_negative)]\n batch_y=np.array(([1.0/self.n_positive]*self.n_positive+[0.0]*self.n_negative)*self.batch_size).reshape(\n self.batch_size, self.n_positive+self.n_negative)\n for ids, document in self.documents:\n if len(document) < 1 + self.n_positive + self.n_negative:\n continue\n ids = np.array(ids)\n sections = np.unique(ids[:,0])\n current_section = ids[0,0]\n for t, s_id in enumerate(ids):\n if current_section != s_id[0]:\n # new section\n current_section = s_id[0]\n self.not_valid_sen += 1\n continue\n elif t==len(ids)-1:\n # the end of a document\n self.not_valid_sen += 1\n break\n elif current_section != ids[t+1,0]:\n # the end of a section\n self.not_valid_sen += 1\n continue\n elif isinstance(document[t-1], float):\n if np.isnan(document[t-1]):\n self.not_valid_sen += 1\n continue\n elif isinstance(document[t], float):\n if np.isnan(document[t]):\n self.not_valid_sen += 1\n continue\n elif isinstance(document[t+1], float):\n if np.isnan(document[t+1]):\n self.not_valid_sen += 1\n continue\n else:\n tar.append(self.get_id_sequence(document[t]))\n pos[0].append(self.get_id_sequence(document[t-1]))\n pos[1].append(self.get_id_sequence(document[t+1]))\n for i, n in enumerate(rd.sample(self.other_than(document, t-1, t+1), self.n_negative)):\n neg[i].append(self.get_id_sequence(n))\n self.valid_sen += 1\n if len(tar)==self.batch_size:\n yield ([np.array(tar)]+[np.array(p) for p in pos]+[np.array(n) for n in neg], batch_y)\n tar=[]\n pos=[[] for i in range(self.n_positive)]\n neg=[[] for i in range(self.n_negative)]\n \n def get_id_sequence(self, line):\n line = list(map(lambda x: self.token2id.get(x, 0), line))\n return padding(line, self.seq_length, self.unk)\n \n def other_than(self, some_list, inf, sup):\n if inf==0:\n return some_list[sup+1:]\n elif sup==len(some_list)-1:\n return some_list[:inf]\n else:\n return some_list[:inf] + some_list[sup+1:]","sub_path":"src/preprocess/load.py","file_name":"load.py","file_ext":"py","file_size_in_byte":5359,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"444227083","text":"#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n# @Time : 2019/6/10 20:31\n# @Author : Durat\n# @Email : durant.zeng@sunvalley.com.cn\n# @File : albumsShare4Front.py\n# @Software: PyCharm\nimport sys,os\nBASE_DIR=os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\nsys.path.append(BASE_DIR)\nimport json\nimport requests\nfrom common.FileParsing import FileParser\nfrom common.baseUtil import baseUtils\nfrom interface.base.login.authentication import Authentication\nfrom common.Logger import Logger\n\nclass albumsShare4Front:\n\n def __init__(self):\n self.logger = Logger(logger=\"albumsShare4Front\").getlog()\n\n def get_albumsShare4FrontURL(self,baseURL,URL,lang,timeStamp,clientVersionInfo,access_token):\n '''\n :param baseURL:\n :param lang:\n :param timeStamp:\n :param clientVersionInfo:\n :param access_token:\n :return:特辑-专辑分享\n '''\n albumsShare4FrontURL = baseURL + URL + \"?lang=%s&timeStamp=%s&clientVersionInfo=%s&access_token=%s\" % (lang, timeStamp, clientVersionInfo,access_token)\n self.logger.info(\"url为:%s\" %albumsShare4FrontURL)\n return albumsShare4FrontURL\n\n\n\n def send_request_albumsShare4Front(self,url,shareType,shareWay,sharedId):\n '''\n :param url:\n :param shareType:\n :param shareWay:\n :param sharedId:\n :return:\n '''\n\n headers = {\"Content-Type\": \"application/json\"}\n if shareType == \"专辑\" and shareWay == \"微信\":\n parameters = {\n \"shareType\":\"1\",\n \"shareWay\":\"1\",\n \"sharedId\":sharedId\n }\n self.logger.info(\"请求的参数为:%s\" %parameters)\n r = requests.post(url, data=json.dumps(parameters), headers=headers,timeout=30)\n self.logger.info(\"返回的参数为:%s\" % json.loads(r.text))\n return json.loads(r.text)\n elif shareType == \"专辑\" and shareWay == \"微信朋友圈\":\n parameters = {\n \"shareType\":\"1\",\n \"shareWay\":\"0\",\n \"sharedId\":sharedId\n }\n self.logger.info(\"请求的参数为:%s\" %parameters)\n r = requests.post(url, data=json.dumps(parameters), headers=headers,timeout=30)\n self.logger.info(\"返回的参数为:%s\" % json.loads(r.text))\n return json.loads(r.text)\n elif shareType == \"专辑\" and shareWay == \"微博\":\n parameters = {\n \"shareType\":\"1\",\n \"shareWay\":\"2\",\n \"sharedId\":sharedId\n }\n self.logger.info(\"请求的参数为:%s\" %parameters)\n r = requests.post(url, data=json.dumps(parameters), headers=headers,timeout=30)\n self.logger.info(\"返回的参数为:%s\" % json.loads(r.text))\n return json.loads(r.text)\n\n elif shareType == \"专辑\" and shareWay == \"QQ\":\n parameters = {\n \"shareType\":\"1\",\n \"shareWay\":\"3\",\n \"sharedId\":sharedId\n }\n self.logger.info(\"请求的参数为:%s\" %parameters)\n r = requests.post(url, data=json.dumps(parameters), headers=headers,timeout=30)\n self.logger.info(\"返回的参数为:%s\" % json.loads(r.text))\n return json.loads(r.text)\n elif shareType == \"社区\" and shareWay == \"微信\":\n parameters = {\n \"shareType\":\"2\",\n \"shareWay\":\"1\",\n \"sharedId\":sharedId\n }\n self.logger.info(\"请求的参数为:%s\" %parameters)\n r = requests.post(url, data=json.dumps(parameters), headers=headers,timeout=30)\n self.logger.info(\"返回的参数为:%s\" % json.loads(r.text))\n return json.loads(r.text)\n elif shareType == \"社区\" and shareWay == \"微博\":\n parameters = {\n \"shareType\":\"2\",\n \"shareWay\":\"2\",\n \"sharedId\":sharedId\n }\n self.logger.info(\"请求的参数为:%s\" %parameters)\n r = requests.post(url, data=json.dumps(parameters), headers=headers,timeout=30)\n self.logger.info(\"返回的参数为:%s\" % json.loads(r.text))\n return json.loads(r.text)\n elif shareType == \"社区\" and shareWay == \"QQ\":\n parameters = {\n \"shareType\":\"2\",\n \"shareWay\":\"3\",\n \"sharedId\":sharedId\n }\n self.logger.info(\"请求的参数为:%s\" %parameters)\n r = requests.post(url, data=json.dumps(parameters), headers=headers,timeout=30)\n self.logger.info(\"返回的参数为:%s\" % json.loads(r.text))\n return json.loads(r.text)\n elif shareType == \"系统\" and shareWay == \"微信\":\n parameters = {\n \"shareType\":\"3\",\n \"shareWay\":\"1\",\n \"sharedId\":sharedId\n }\n self.logger.info(\"请求的参数为:%s\" %parameters)\n r = requests.post(url, data=json.dumps(parameters), headers=headers,timeout=30)\n self.logger.info(\"返回的参数为:%s\" % json.loads(r.text))\n return json.loads(r.text)\n elif shareType == \"系统\" and shareWay == \"微博\":\n parameters = {\n \"shareType\":\"3\",\n \"shareWay\":\"2\",\n \"sharedId\":sharedId\n }\n self.logger.info(\"请求的参数为:%s\" %parameters)\n r = requests.post(url, data=json.dumps(parameters), headers=headers,timeout=30)\n self.logger.info(\"返回的参数为:%s\" % json.loads(r.text))\n return json.loads(r.text)\n elif shareType == \"系统\" and shareWay == \"QQ\":\n parameters = {\n \"shareType\":\"3\",\n \"shareWay\":\"3\",\n \"sharedId\":sharedId\n }\n self.logger.info(\"请求的参数为:%s\" %parameters)\n r = requests.post(url, data=json.dumps(parameters), headers=headers,timeout=30)\n self.logger.info(\"返回的参数为:%s\" % json.loads(r.text))\n return json.loads(r.text)\n else:\n self.logger.error(\"传的参数有误,请检查!\")\n\n\n\nif __name__ == \"__main__\":\n\n\n imi = albumsShare4Front()\n # print(imi)\n phone = \"13723746965\"\n config0 = FileParser(r'D:\\anjouAutoTest\\config\\Authentication_url.ini')\n dev_AC_URL = config0.get('Authentication', 'dev')\n print(dev_AC_URL)\n config1 = FileParser(r'D:\\anjouAutoTest\\config\\env.ini')\n base = baseUtils()\n clientVersionInfo = config1.get(\"clientVersionInfo\", \"clientVersionInfo\")\n lang = config1.get(\"lang\", \"zh\")\n currentTime = base.getTimeStamp()\n AC = Authentication()\n DATA = AC.get_Android_CN_logged_in(phone)\n url = AC.get_AuthenticationURL(dev_AC_URL, lang, currentTime, clientVersionInfo)\n\n access_token = AC.get_Access_token(url, DATA)\n\n config2 = FileParser(r'D:\\anjouAutoTest\\config\\api_url.ini')\n base_url = config2.get(\"base_url\",\"base_url_dev\")\n\n\n\n albumsShare4FrontURL = config2.get(\"imi_cms_url\",\"albumsShare4FrontURL\")\n albumsShare4FrontURL = imi.get_albumsShare4FrontURL(base_url,albumsShare4FrontURL,lang,currentTime,clientVersionInfo,access_token)\n\n\n # print(queryDiyPicURL)\n\n\n sharedId = \"0055358489bb44e8b40b41706fd0b6d6\"\n shareType = \"专辑\"\n shareWay = \"微信\"\n # #\n # # # #\n imi.send_request_albumsShare4Front(albumsShare4FrontURL,shareType,shareWay,sharedId)\n\n\n","sub_path":"interface/tutu/Album/albumsShare4Front.py","file_name":"albumsShare4Front.py","file_ext":"py","file_size_in_byte":7697,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"178134561","text":"import socket\nimport select\nimport utils\nimport sys\n\nclass chat_client(object):\n\n def __init__(self, name, address, port):\n self.name = name\n self.address = address\n self.port = int(port)\n self.sockets = [sys.stdin]\n\n def prompt(self):\n sys.stdout.write(utils.CLIENT_MESSAGE_PREFIX)\n sys.stdout.flush()\n\n def run(self):\n sock = socket.socket()\n #sock.settimeout(2)\n try:\n sock.connect((self.address,self.port))\n sock.send(self.name)\n except:\n print(utils.CLIENT_CANNOT_CONNECT,\n self.address,\n self.port)\n sys.exit()\n self.sockets.append(sock)\n self.prompt()\n\n while True:\n ready_to_read,_,_ = select.select(self.sockets,[],[])\n for s in ready_to_read:\n if s == sock:\n data = s.recv(1024)\n if not len(data):\n print(utils.CLIENT_SERVER_DISCONNECTED,\n self.address,\n self.port)\n sys.exit()\n datas = data.split(':::')\n if len(datas) == 1:\n sys.stdout.write('\\n'+datas[0]+'\\n')\n else:\n sys.stdout.write('\\n['+datas[0]+'] '+datas[1]+'\\n')\n sys.stdout.flush()\n else:\n data = sys.stdin.readline()\n sock.send(data[:-1])\n self.prompt()\n\n\nif __name__ == '__main__':\n if len(sys.argv) != 4:\n print(\"Usage:python chat_client.py username address port\")\n client = chat_client(sys.argv[1],sys.argv[2],sys.argv[3])\n client.run()\n\n","sub_path":"projects/proj1_chat/chat_client.py","file_name":"chat_client.py","file_ext":"py","file_size_in_byte":1785,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"457690023","text":"import csv\r\nimport sys\r\n\r\nwalk_time = []\r\nwalk_data = []\r\navg=[]\r\nsum=0.0\r\nfile = open('walk-pocket.csv')\r\nreader = csv.reader(file)\r\n\r\ndef stepCount(data_avg):\r\n count=0;\r\n for x in range (0, len(avg),37):\r\n max=0\r\n for var in range(x, x+37):\r\n if(avg[x] > max):\r\n max=avg[x]\r\n if(max > data_avg):\r\n count=count+1\r\n print(\"Number of steps walked =\",count)\r\n\r\ndef preprocess(sum):\r\n for row in reader:\r\n walk_data.append(row[2])\r\n walk_time.append(row[0])\r\n window=walk_time.index(\"311\") #according to the data nearest value to 0.3s window is 311ms. hence setting window size to index of 311ms\r\n walk_data_sum = 0.0\r\n for var in range(1, len(walk_data)):\r\n walk_data_sum = walk_data_sum + float(walk_data[var])\r\n data_avg = walk_data_sum/(len(walk_data)-1) #average of entire data\r\n for var in range(1, window+1):\r\n sum= sum + float(walk_data[var])\r\n avg.append(sum/window)\r\n for var in range (window+2, len(walk_data)):\r\n sum = sum - float(walk_data[var-(window+1)])\r\n sum = sum + float(walk_data[var])\r\n avg.append(sum/window)\r\n stepCount(data_avg) #called step count process\r\n\r\npreprocess(sum) #called initial process\r\nfile.close()\r\n","sub_path":"PA2/p2.py","file_name":"p2.py","file_ext":"py","file_size_in_byte":1279,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"159985595","text":"from __future__ import print_function\n\nfrom dolfin import *\nimport csv\nimport sys\nfrom scipy.special import jv\nfrom sympy import re, im, sqrt, symbols, lambdify, besselj, sympify\n\n__author__ = 'jh'\n\nnote = '' # to append name of precomputed solution modification\nfname = 'tmp.csv'\nR = 1.5\n# read coeficients from chosen file\ninfile = open(fname, 'r')\ncsvreader = csv.reader(infile, delimiter=',')\nn_coefs = csvreader.next()[0]\ncoefs_mult = [sympify(i.replace('*^', 'E')) for i in csvreader.next()]\ncoefs_bes_mult = [sympify(i.replace('*^', 'E')) for i in csvreader.next()]\ncoefs_bes = [sympify(i.replace('*^', 'E')) for i in csvreader.next()]\ncoef_par_max = csvreader.next()[0]\ncoef_par = csvreader.next()[0]\n\n# for meshName in ['cyl_d1', 'cyl_d2', 'cyl_d3', 'cyl_e3']:\n#for meshName in ['cyl_c1', 'cyl_c2', 'cyl_c3']:\nfor meshName in ['cyl15_3']:\n print('Mesh: '+meshName)\n mesh = Mesh(\"meshes/\" + meshName + \".xml\")\n cell_function = MeshFunction(\"size_t\", mesh, \"meshes/\" + meshName + \"_physical_region.xml\")\n facet_function = MeshFunction(\"size_t\", mesh, \"meshes/\" + meshName + \"_facet_region.xml\")\n\n PS = FunctionSpace(mesh, \"Lagrange\", 2) # partial solution (must be same order as V)\n\n f = HDF5File(mpi_comm_world(), 'precomputed/precomputed_'+meshName+note+'.hdf5', 'w')\n\n # precomputation of Bessel functions=============================================================================\n temp = toc()\n coefs_r_prec = [] # these will be functions in PS\n coefs_i_prec = [] # these will be functions in PS\n c0ex = Expression(\"(maxc-c*(x[0]*x[0]+x[1]*x[1]))\", maxc=Constant(coef_par_max), c=Constant(coef_par))\n f.write(interpolate(c0ex, PS), \"parab\")\n # plot(interpolate(c0ex, PS), interactive=True, title='Parab')\n for i in range(8):\n r = symbols('r')\n besRe = re(coefs_mult[i] * (coefs_bes_mult[i] * besselj(0, r * coefs_bes[i]) + 1))\n besIm = im(coefs_mult[i] * (coefs_bes_mult[i] * besselj(0, r * coefs_bes[i]) + 1))\n besRe_lambda = lambdify(r, besRe, ['numpy', {'besselj': jv}])\n besIm_lambda = lambdify(r, besIm, ['numpy', {'besselj': jv}])\n\n\n class PartialReSolution(Expression):\n def eval(self, value, x):\n rad = float(sqrt(x[0] * x[0] + x[1] * x[1]))\n # conversion to float needed, u_lambda (and near) cannot use sympy Float as input\n value[0] = 0 if near(rad, R) else besRe_lambda(rad) # do not evaluate on boundaries, it's 0\n # print(value) gives reasonable values\n\n\n expr = PartialReSolution()\n print('i = '+str(i)+' interpolating real part')\n # plot(interpolate(expr, PS), interactive=True, title='Real%d'%i)\n f.write(interpolate(expr, PS), \"real%d\" % i)\n\n\n class PartialImSolution(Expression):\n def eval(self, value, x):\n rad = float(sqrt(x[0] * x[0] + x[1] * x[1]))\n # conversion to float needed, u_lambda (and near) cannot use sympy Float as input\n value[0] = 0 if near(rad, R) else besIm_lambda(rad) # do not evaluate on boundaries, it's 0\n\n\n expr = PartialImSolution()\n print('i = '+str(i)+' interpolating imaginary part')\n # plot(interpolate(expr, PS), interactive=True, title='Imag%d'%i)\n f.write(interpolate(expr, PS), \"imag%d\" % i)\n #exit()\n\n print(\"Precomputed partial solution functions. Time: %f\" % (toc() - temp))\n\n\n","sub_path":"generate.py","file_name":"generate.py","file_ext":"py","file_size_in_byte":3439,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"439025384","text":"from django.http import HttpResponseRedirect, HttpResponse\nfrom django.http import Http404\nfrom django.shortcuts import get_object_or_404, render\nfrom django.core.urlresolvers import reverse\nfrom django.views import generic\nfrom django.utils import timezone\nfrom django.views.generic import View\n\nfrom .models import UserProfile\n\nfrom PIL import Image, ImageEnhance, ImageOps, ImageColor\nfrom django.conf import settings\nfrom django import template\nregister = template.Library()\n\n# Create your views here.\nclass UserProfileView(generic.DetailView):\n model = UserProfile\n template_name = 'myuserprofiles/user.html'\n context_object_name = 'myuser'\n\nclass IndexView(generic.ListView):\n template_name = 'myuserprofiles/index.html'\n context_object_name = 'users'\n\n def get_queryset(self):\n\t \"\"\"\n\t Return users in order of id.\n\t \"\"\"\n\t return UserProfile.objects.order_by('id')\n\n#class MyImageManipulation(View):\n# def get(self, request, *args, **kwargs):\n# return HttpResponse('This is GET request')\n#\n# def post(self, request, *args, **kwargs):\n# return HttpResponse('This is POST request')\n\nclass ImageTemp(generic.DetailView):\n\tmodel = UserProfile\n\ttemplate_name = 'myuserprofiles/myimagetemp.html'\n\ndef changeImageColor(myImage, c1, c2, c3, default):\n\t(red, green, blue, opacity) = myImage.split()\n\n\t# returns as \"RBG\", need in \"L\" format\n\tred = ImageOps.colorize(red, c1, default)\n\tgreen = ImageOps.colorize(green, c2, default)\n\tblue = ImageOps.colorize(blue, c3, default)\n\n\tred = red.convert(\"L\")\n\tgreen = green.convert(\"L\")\n\tblue = blue.convert(\"L\")\n\n\treturn Image.merge(\"RGBA\", (red, green, blue, opacity))\n\n\n# Numbers less than 1000 are colors. Numbers greater than 1000 are items.\ndef imageManipulation(request, pk, indicator):\n\t#import pdb; pdb.set_trace() ## For debugging\n\t\n\tindicator = int(indicator)\n\tmyImage = Image.open(settings.AVATARIMAGES_ROOT + \"/face.png\")\n\n\tif(indicator < 1000):\n\t\t###### Changing Image Color ######\n\t\tdefault = (255,255,255)\n\t\tcolor = indicator\n\t\tif(color == 1):\n\t\t\tmyImage = changeImageColor(myImage, \"#787878\", \"#bbbbbb\", \"#ffffff\", default)\n\t\telif(color == 2):\n\t\t\tmyImage = changeImageColor(myImage, \"#ffffff\", \"#aaaaaa\", \"#000000\", default)\n\t\tmyImage.save(settings.MEDIA_ROOT + \"/avatar_images/test1.png\", \"PNG\")\n\telse:\n\t\t###### Layering Images ######\n\t\titem = indicator\n\t\tif(item == 1000):\n\t\t\tmyImage2 = Image.open(settings.AVATARIMAGES_ROOT + \"/test1.png\")\n\t\t\tmyImage3 = Image.open(settings.AVATARIMAGES_ROOT + \"/eyepatch.png\")\n\t\t\tmyImage4 = Image.alpha_composite(myImage2, myImage3)\n\t\t\tmyImage4.save(settings.AVATARIMAGES_ROOT + \"/test1.png\", \"PNG\")\n\t\t\tmyImage2.close()\n\t\t\tmyImage3.close()\n\t\t\tmyImage4.close()\n\tmyImage.close()\n\t\n\treturn HttpResponseRedirect(reverse('myuserprofiles:user', args=(pk,)))\n\n","sub_path":"myuserprofiles/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2795,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"405005336","text":"class Solution:\r\n def eraseOverlapIntervals(self, intervals: List[List[int]]) -> int:\r\n size = len(intervals)\r\n if size <= 1:\r\n return 0\r\n\r\n intervals.sort(key=lambda x: x[1])\r\n res, lastEnd = 0, intervals[0][1]\r\n\r\n for i in range(1, size):\r\n curStart, curEnd = intervals[i][0], intervals[i][1]\r\n if curStart < lastEnd:\r\n res += 1\r\n else:\r\n lastEnd = curEnd\r\n\r\n return res\r\n","sub_path":"435/chongdie.py","file_name":"chongdie.py","file_ext":"py","file_size_in_byte":493,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"220450310","text":"# --------------------------------------------------------------------------- #\n# File Name :: test_service_rest.py\n# Purpose :: The unit test\n# --------------------------------------------------------------------------- #\n\n# ****************************************************************************\n#\n# Run unit testing via command line from PARENT directory\n# python -m tests.test_service_rest\n# Or\n# python -m tests.test_service_rest..\n#\n# ****************************************************************************\n\nimport unittest\n\nimport logging\n\n# You must initialize logging, otherwise you'll not see debug output.\nlevel = logging.INFO\n# for more debug print\n# level = logging.DEBUG\n\n# These two lines enable debugging at httplib level (requests->urllib3->http.client)\n# You will see the REQUEST, including HEADERS and DATA, and RESPONSE with HEADERS but without DATA.\n# The only thing missing will be the response.body which is not logged.\n\ntry:\n import http.client as http_client\nexcept ImportError:\n # Python 2\n import httplib as http_client\nif level == logging.DEBUG:\n http_client.HTTPConnection.debuglevel = 1\n\nlogging.basicConfig(format='%(asctime)s %(levelname)s %(message)s', level=level)\n\nlogging.getLogger().setLevel(level)\nrequests_log = logging.getLogger(\"requests.packages.urllib3\")\nrequests_log.setLevel(level)\nrequests_log.propagate = True\n\nfrom pyfsmsync.service_rest import ServiceManagerClient\n\nimport json\nfrom tests import *\n\n\nclass TestServiceRest(unittest.TestCase):\n\n def __init__(self, *args, **kwargs):\n super(TestServiceRest, self).__init__(*args, **kwargs)\n\n self.log = logging.getLogger()\n\n self.settings = Settings()\n\n def setUp(self):\n super(TestServiceRest, self).setUp()\n self.build_id = FINDIT_CRM\n\n @unittest.skip('need access permission')\n def test_create_task(self):\n\n self.service_rest = ServiceManagerClient(self.settings)\n task = self.service_rest.get_build_info(\n customer=None, # (required) - Customer name\n customer_id=None, # (required) - Customer party number\n title=None, # (required) - Task title\n description=None, # (optional) - Task description\n product=None, # (optional) - Software Product for standard products or Related product if software product family.\n spf=None, # (optional) - Software Product Family Name\n creator=None, # (required) - Username of the creator\n id=None # (required) - Salesforce case id\n )\n self.assertTrue(task)\n self.log.info(\n 'task)=\\n\\n%s\\n\\n'\n % (json.dumps(task, indent=2)))\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"SC/pyfsmsync/tests/test_service_rest.py","file_name":"test_service_rest.py","file_ext":"py","file_size_in_byte":2815,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"479265809","text":"\"\"\"BMC URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/2.1/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: path('', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.urls import include, path\n 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))\n\"\"\"\n\nfrom django.urls import path\nfrom . import views\napp_name ='[BmcAdminConfig]'\nurlpatterns = [\n path('', views.bmc_admin,name=\"bmc_admin\"), #加了name后,在HTML中可以用{%url 'bmc_admin'%}的方式访问\n path('snmp_test/', views.snmp_test,name=\"snmp_test\"),\n path(\"delete-/\", views.delete, name='delete'),\n\n]\n","sub_path":"bmc_admin/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":963,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"312917202","text":"from guilds import cnx\n\n\ndef is_handshake(PID, GID):\n # проверяю если есть как join так и invite\n cursor = cnx.cursor()\n query = \"SELECT 1 FROM guilds_playerrequest pr WHERE pr.PID = '%s' AND pr.GID = '%s' \" % (PID, GID,)\n cursor.execute(query)\n dS1 = cursor.fetchall()\n cursor.close()\n cursor = cnx.cursor()\n query = \"SELECT 1 FROM guilds_guildrequest pr WHERE pr.PID = '%s' AND pr.GID = '%s' \" % (PID, GID,)\n cursor.execute(query)\n dS2 = cursor.fetchall()\n # если нет заявок - гг\n if not (len(dS1) + len(dS2)) > 1:\n cursor.close()\n return False\n # а вот если они есть\n query = \"SELECT COUNT(1) FROM guilds_members WHERE Guild = '%s'\" % (GID,)\n cursor.execute(query)\n data = cursor.fetchall()\n cursor.close()\n if data[0][0] > 25:\n return False\n return True\n\n\ndef check_embargo(GID_source, GID_target):\n query = \"\"\"\n SELECT 1 FROM guilds_embargo \n WHERE GSource = '%s' AND GTarget = '%s'\n \"\"\" % (GID_source, GID_target)\n cursor = cnx.cursor()\n cursor.execute(query)\n dataSet = cursor.fetchall()\n cursor.close()\n if len(dataSet) > 0:\n return True\n else:\n return False\n","sub_path":"libs/cheks/cheks_mutual.py","file_name":"cheks_mutual.py","file_ext":"py","file_size_in_byte":1263,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"412912095","text":"\ndef run_formula(dv, param = None):\n defult_param = {'t1':5,'t2':2,'t3':60,'t4':30}\n if not param:\n param = defult_param\n \n ESR30 = dv.add_formula('VEMA10', \n '''Ewma(StdDev(Return(close,%s,%s),%s),%s)'''%(param['t1'],param['t2'],param['t3'],param['t4']),\n is_quarterly=False)\n \n return ESR30 ","sub_path":"10_New_Factors/ESR30.py","file_name":"ESR30.py","file_ext":"py","file_size_in_byte":341,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"318277192","text":"import ftplib\n\ndef main():\n\n #\n print(\"-- Sender --\")\n # there a bunch of different types of server lists i want to use,\n # this one stores what the user will see, they're ordered by appearance on axebane's account on streamline\n userServerNames = [\"45.121.208.22:27058\",\"45.121.208.21:27058\",\"45.121.211.30:27055\",\"45.121.211.30:27065\",\"45.121.210.27:27075\"]\n # this one is for browsing through files if we establish an FTP connection\n fileServerNames = [None] * (len(userServerNames) - 1)\n for ii in range(len(userServerNames) - 1):\n fileServerNames[ii] = userServerNames[ii].replace(\":\",\"_\")\n\n # this one is used for establishing the FTP connection (it's really only here cause i'm too lazy to remember what the substring method is)\n useServerNames = [\"45.121.208.22\",\"45.121.208.21\",\"45.121.211.30\",\"45.121.211.30\",\"45.121.210.27\"]\n # get the index of what the user chooses\n serverChoice = userMenu(userServerNames,\"Please select which server you want to upload to\")\n\n print(\"you chose %s\" % userServerNames[serverChoice])\n # ((yeah ignore the fact that i'm storing the password in plain text lol))\n print(\"establishing connection between %s:%s\"% (useServerNames[serverChoice], 8821))\n ftp = ftplib.FTP(host=useServerNames[serverChoice],port_=8821,user=\"axebane\",passwd=\"z@uPvvq]H:S8{%#)\")\n print(\"connection established\")\n whitelistPath = \"addons/sourcemod/configs/whitelist\"\n\n # attempt to get to the whitelist file location\n try:\n installed = True\n print(\"going into file '%s'\"%(fileServerNames[serverChoice]))\n ftp.cwd(\"%s/%s\"%(fileServerNames[serverChoice],\"addons/sourcemod/configs\"))\n try:\n # a little test to see if the file whitelist exists\n ftp.cwd(\"whitelist\")\n except:\n # we can assume that the whitelist plugin is not installed\n print(\"I don't have the whitelist plugin installed!\")\n installed = False\n\n # if the whitelist plugin is installed\n if installed:\n fileName = \"whitelist.txt\"\n file = open(fileName, \"rb\")\n print(\"attempting to upload whitelist to server\")\n ftp.storbinary(\"STOR \" + fileName, file)\n print(\"success!\")\n\n # if we fail for some reason\n except:\n print(\"i failed :(\")\n data = []\n\n\n # ftp.retrbinary('whitelist', open('README', 'wb').write)\n print(ftp.dir())\n\n ftp.quit()\n\n \n# END main\n\n\ndef userMenu(menuOptions = [None,None], menuPrompt = \"\"):\n\n\n menu = menuPrompt\n userChoice = None\n for ii in range(len(menuOptions)):\n menu += \"\\n%s - %s\"%(ii+1, menuOptions[ii])\n\n\n while(userChoice == None):\n userChoice = input(menu + \"\\n\")\n for ii in range(len(menuOptions)):\n if( ii == int(userChoice) - 1):\n userChoice = ii\n elif( int(userChoice) - 1 == menuOptions[ii]):\n userChoice = ii\n # END loop\n\n return userChoice\n\nif( __name__ == '__main__'):\n main()","sub_path":"Mac/Flaktest/Whitelister/Contents/Uploader.py","file_name":"Uploader.py","file_ext":"py","file_size_in_byte":3035,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"99347071","text":"#使用牛顿迭代法与弦截法计算函数的零点\n#限于多项式(19.09.19)\nclass PolyFunc:\n\n def __init__(self):\n s=str(input(\"输入降幂多项式函数的各次系数:\\n\")).split(' ')\n for i in range(len(s)):\n s[i]= eval(s[i])\n self.content = s\n self.power = len(s) -1\n\n def f(self,x):\n ans = 0\n s = self.content\n n = self.power\n for i in range(n+1):\n ans = ans *x + s[i]\n return ans\n\n def df(self,x):\n ans=0\n s = self.content\n n = self.power\n for i in range(n):\n ans = ans *x +s[i]*(n-i) \n return ans\n\n def rightx(self,x1):\n ddf=0\n s = self.content\n n = self.power\n for i in range(n-1):\n ddf = ddf * x1 +(n-i)*(n-i-1)\n return self.f(x1)*ddf>0\n\n def NT(self):\n while True:\n x1=eval(input(\"输入牛顿法求解的初值:\"))\n if self.rightx(x1):\n break\n error = eval(input(\"输入解的精度:\"))\n i=1\n while True:\n x2 = x1-self.f(x1)/self.df(x1)\n if abs(x2-x1)= xmax-1.00:\n p011.axes.set_xlim(x-xmax+1.0,x+1.0)\n p021.axes.set_xlim(x-xmax+1.0,x+1.0)\n p031.axes.set_xlim(x-xmax+1.0,x+1.0)\n\n return p011, p021\n\n \n \n simulation = animation.FuncAnimation(f0, updateData, blit=False, frames=200, interval=1000, repeat=False)\n plt.show()\n \n \n\n# ani = animation.FuncAnimation(fig, animate, fargs=(xs, ys), interval=1000)\n# plt.show()\n","sub_path":"RoverInterface.py","file_name":"RoverInterface.py","file_ext":"py","file_size_in_byte":2707,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"629244541","text":"from itertools import product\n\nN = int(input())\n\nfor a, b in product(range(1, 38), range(1, 26)):\n if 3**a + 5**b == N:\n print(a, b)\n exit()\n\nprint(-1)\n","sub_path":"atcoder/2020/ARC/1024_arc106/A.py","file_name":"A.py","file_ext":"py","file_size_in_byte":169,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"298217757","text":"class Solution:\n # @param num : a list of integer\n # @return : a list of integer\n def nextPermutation(self, num):\n # write your code here\n #num_str = \"\".join(num)\n k = len(num)\n if k == 0 or k==1:\n return num\n \n while k > 0:\n if int(num[k-1]) < int(num[-1]):\n break\n k-=1\n \n if k == 0:\n return sorted(num)\n \n num[k-1], num[-1] = num[-1], num[k-1]\n return num[:k]+num[k:]\n\n\ns = Solution()\nt=s.nextPermutation([1,3,2,3])\nprint(t)\ns.nextPermutation([4,3,2,1])\nprint(t)\n","sub_path":"excrayg/leetcode/python/next_perm.py","file_name":"next_perm.py","file_ext":"py","file_size_in_byte":619,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"405371825","text":"import time\nimport sys\nimport math\nimport itertools\nvirtualpyloc = sys.argv[1]\nsys.path.append(virtualpyloc+'Debug')\n\nimport virtualpy\n\nimport pdb\n\n#from model_loader import load_model\nimport model_loader\n\nvirtualpy.set_color(0, 0, 0)\nvirtualpy.push_state()\nvirtualpy.set_resources_location(virtualpyloc+'resources\\\\')\nvirtualpy.spawn_thread('directx')\n\n\nvertex_type = virtualpy.VertexType((\"location\", \"POSITION\", 3), (\"color\", \"COLOR\", 4))\n\ncolor_shader = virtualpy.load_shader(\"shaders.hlsl\", vertex_type)\n\nvirtualpy.begin_model(vertex_type, virtualpy.PrimitiveType.triangle_strip)\na = {\"location\":(0.5, 0, -0.5/math.sqrt(3)), \"color\":(0.5, 0, 0, 1)}\nb = {\"location\":(0, 0, 1/math.sqrt(3)), \"color\":(0, 0.5, 0, 1)}\nc = {\"location\":(-0.5, 0, -0.5/math.sqrt(3)), \"color\":(0, 0, 0.5, 1)}\nd = {\"location\":(0, math.sqrt(2)/math.sqrt(3), 0), \"color\":(0.5, 0.5, 0.5, 1)}\nvirtualpy.add_vertex(**a)\nvirtualpy.add_vertex(**c)\nvirtualpy.add_vertex(**b)\nvirtualpy.add_vertex(**d)\nvirtualpy.add_vertex(**a)\nvirtualpy.add_vertex(**c)\npyramid_model = virtualpy.end_model()\n\nclass Pyramid(object):\n\tdetail_offsets = [\n\t\tvirtualpy.Position((0, math.sqrt(2)/math.sqrt(3), 0)),\n\t\tvirtualpy.Position((0, 0, 1/math.sqrt(3))),\n\t\tvirtualpy.Position((0.5, 0, -0.5/math.sqrt(3))),\n\t\tvirtualpy.Position((-0.5, 0, -0.5/math.sqrt(3))),\n\t]\n\n\tdef __init__(self, detail_level=0, detail_path=()):\n\t\tif len(detail_path) != detail_level:\n\t\t\traise ValueError(\"Attempting to create a pyramid with a detail_path with the wrong detail level\")\n\t\n\t\tself.entity = virtualpy.create_modeled_entity(pyramid_model, color_shader)\n\t\tself.detail_level = detail_level\n\t\tself.detail_path = tuple(detail_path)\n\t\tself.position = virtualpy.Position((0, 0, -2))\n\t\tfor i in range(detail_level):\n\t\t\tself.position += Pyramid.detail_offsets[detail_path[i]]*math.pow(0.5, i+1)\n\t\tself.scale = (math.pow(0.5, self.detail_level),)*3\n\t\tself.orientation = virtualpy.Quaternion((0, 0, 0, 1))\n\t\t\n\tdef display(self):\n\t\tvirtualpy.show_model(self.entity, self.position.vector, self.scale, self.orientation)\n\t\n\tdef shatter(self):\n\t\t# Returns an iterator of pyramids\n\t\treturn (Pyramid(self.detail_level+1, self.detail_path+(i,)) for i in range(4))\n\npyramids = [Pyramid()]\n\ncamera_location = [0, 0, 0]\n\nprev_time = time.perf_counter()\ncurr_time = prev_time\nmove_scale = 0.75\ntheta = 0\n\nfrequency_out = open('py_frequency', 'w')\n\n(prev_keys_at_state, prev_keys_since_state) = virtualpy.get_keyboard_state()\n\nwhile True:\n\ttime_diff = curr_time - prev_time\n\tfrequency_out.write(str(time_diff)+\"\\n\")\n\tfrequency_out.flush()\n\n\t(keys_at_state, keys_since_state) = virtualpy.get_keyboard_state()\n\t\n\tif keys_since_state[ord('W')]:\n\t\tcamera_location[2] -= move_scale*time_diff\n\tif keys_since_state[ord('S')]:\n\t\tcamera_location[2] += move_scale*time_diff\n\tif keys_since_state[ord('A')]:\n\t\tcamera_location[0] -= move_scale*time_diff\n\tif keys_since_state[ord('D')]:\n\t\tcamera_location[0] += move_scale*time_diff\n\tif keys_since_state[ord('Q')]:\n\t\tcamera_location[1] -= move_scale*time_diff\n\tif keys_since_state[ord('E')]:\n\t\tcamera_location[1] += move_scale*time_diff\n\t\t\n\tif keys_since_state[ord('P')] and not prev_keys_since_state[ord('P')]:\n\t\tpyramids = tuple(itertools.chain(*tuple(p.shatter() for p in pyramids)))\n\t\tprint ('a')\n\t\t\n\tvirtualpy.set_camera_location(camera_location)\n\tprev_keys_at_state = keys_at_state\n\tprev_keys_since_state = keys_since_state\n\t\n\ttheta = (theta + time_diff)% (2*3.14)\n\t\n\t#virtualpy.show_model(p2, (0, 0, -2), (1, 1, 1), virtualpy.Quaternion((0, 0, 0, 1)))\n\tfor pyramid in pyramids:\n\t\tpyramid.display()\n\t\n\t#virtualpy.show_model(entity, position=(0, 0, -3), scale=(1, 1, 1), rotation=virtualpy.Quaternion((math.sin(theta/2), 0, 0, math.cos(theta/2))))\n\tvirtualpy.push_state()\n\t\n\ttime.sleep(0.001)\n\n\tprev_time = curr_time\n\tcurr_time = time.perf_counter()","sub_path":"resources/tmp.py","file_name":"tmp.py","file_ext":"py","file_size_in_byte":3800,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"636284496","text":"#!/usr/bin/python\n\n\"\"\"\n 30-05-2018\n Author: Naman Jain\n\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\ndef main():\n \"\"\"\n Main Function\n \"\"\"\n friends = [109, 1017, 1127, 418, 625, 957, 89, 950, 946, 797, 981, 125, 455, 731, 1640, 485,\n 1309, 472, 1132, 1773, 906, 531, 742, 621]\n\n z_scores = []\n y_pos = range(len(friends))\n\n # average friends on facebook\n mean = np.mean(friends)\n std = np.std(friends)\n\n for friend in friends:\n # z scores\n z = (friend - mean) / std\n z_scores.append(z)\n\n # plot of z scores\n plt.bar(y_pos, z_scores)\n\n # plot at mean\n plt.plot((0, 25), (1, 1), 'g-')\n # plot at mean + SD\n plt.plot((0, 25), (0, 0), 'b-')\n # plot at mean - SD\n plt.plot((0, 25), (-1, -1), 'r-')\n\n plt.show()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"Basic Statistics/friends_z_score.py","file_name":"friends_z_score.py","file_ext":"py","file_size_in_byte":860,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"428413963","text":"\n\n#calss header\nclass _DEPLOY():\n\tdef __init__(self,): \n\t\tself.name = \"DEPLOY\"\n\t\tself.definitions = [u'to use something or someone, especially in an effective way: ', u'to move soldiers or equipment to a place where they can be used when they are needed: ']\n\n\t\tself.parents = []\n\t\tself.childen = []\n\t\tself.properties = []\n\t\tself.jsondata = {}\n\n\n\t\tself.specie = 'verbs'\n\n\tdef run(self, obj1 = [], obj2 = []):\n\t\treturn self.jsondata\n","sub_path":"xai/brain/wordbase/verbs/_deploy.py","file_name":"_deploy.py","file_ext":"py","file_size_in_byte":431,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"263829217","text":"#!/usr/bin/env python\n\n\"\"\"\nPython script for running generating 'simp' events through PU simulation, readout.\n\"\"\"\n\nimport sys, random\n\nfrom hpsmc.job import Job\nfrom hpsmc.tools import SLIC, JobManager, FilterMCBunches\n\njob = Job(name=\"simp job\")\njob.initialize()\n\nparams = job.params\ninput_files = params.input_files\n\nsimp_files = []\nfor input_file in input_files:\n simp_files.append(input_file)\n\nprocname = \"simp\"\n\n# insert empty bunches expected by pile-up simulation\nfilter_bunches = FilterMCBunches(java_args=[\"-DdisableSvtAlignmentConstants\"],\n inputs=simp_files,\n outputs=[procname+\"_filt.slcio\"],\n ecal_hit_ecut=0.05,\n enable_ecal_energy_filter=True,\n nevents=2000000,\n event_interval=250)\n\n# run simulated events in readout to generate triggers\nreadout = JobManager(steering_resource=params.readout_steering,\n java_args=[\"-DdisableSvtAlignmentConstants\"],\n run=params.run,\n detector=params.detector,\n inputs=[procname+\"_filt.slcio\"],\n outputs=[procname+\"_readout\"])\n\n# run the job\njob.components=[filter_bunches, readout]\njob.run()\n","sub_path":"python/jobs/simp_readout_job.py","file_name":"simp_readout_job.py","file_ext":"py","file_size_in_byte":1336,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"614265079","text":"import numpy as np\nimport matplotlib.pyplot as plt\ndef least_square(A):\n A_T=np.transpose(A)\n X=np.matmul(A_T,A)\n Y=np.linalg.inv(X)\n Z=np.matmul(Y,A_T)\n b=[1,1,1,1,1,1,1,1]\n b=np.array(b)\n b_T=b.reshape(len(b),1)\n w=np.matmul(Z,b_T)\n return w\n\ndef main_func():\n mat_1=[[3,3,1],[3,0,1],[2,1,1],[0,1.5,1]]\n u_mat_2=[[-1,1,1],[0,0,1],[-1,-1,1],[1,0,1]]\n mat_2=[[1,-1,-1],[0,0,-1],[1,1,-1],[-1,0,-1]]\n\n over_mat= mat_1+mat_2\n A = np.array(over_mat)\n w= least_square(A)\n x1=[]\n y1=[]\n x2=[]\n y2=[]\n\n for i in mat_1:\n x1.append(i[0])\n y1.append(i[1])\n\n\n for i in u_mat_2:\n x2.append(i[0])\n y2.append(i[1])\n\n plot1= plt.scatter(x1,y1,c=\"red\",label=\"FIRST\")\n plot2= plt.scatter(x2,y2,c=\"green\",label=\"SECOND\")\n w=np.transpose(w)\n x=np.array(range(-2,4))\n y=eval(\"x*(-w[0][0]/w[0][1])-(w[0][2]/w[0][1])\")\n classifier=plt.plot(x,y,label=\"LMS classifier\")\n\n## RUN CODE #########\n#main_func()\n#####################\n","sub_path":"least_square_2.py","file_name":"least_square_2.py","file_ext":"py","file_size_in_byte":1013,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"443900879","text":"from rest_framework.test import APIClient, APITestCase\nfrom rest_framework import status\nfrom django.urls import reverse\nfrom django.contrib.auth.models import User\nfrom ..models import Education\n\n\nclass EducationAPITest(APITestCase):\n\n\tdef setUp(self):\n\t\tself.client = APIClient(enforce_csrf_checks=True)\n\t\tself.user = User.objects.create(username='phyll',\n\t\t\t\t\t\t\t\t\t\temail='phyll@gmail.com',\n\t\t\t\t is_active=True,\n\t\t\t\t is_superuser=True,\n\t\t\t\t is_staff=True)\n\t\tself.client.force_authenticate(user=self.user)\n\n\tdef test_education_api_can_create(self):\n\t\turl = reverse('edu-api:edu-create')\n\t\tdata = {'institution': 'UPSA', 'duration': '2012-2016',\n\t\t\t\t'certificate': 'WASSCE'}\n\t\tresponse = self.client.post(url, data, format='json')\n\t\tself.assertEqual(response.status_code, status.HTTP_201_CREATED)\n\n\tdef test_education_api_can_get_detail(self):\n\t\tedu = Education.objects.create(user=self.user, institution='UPSA',\n\t\t\t duration='2012-2016', certificate='BECE')\n\t\turl = reverse('edu-api:edu-detail', kwargs={'pk': edu.id})\n\t\tresponse = self.client.get(url, format='json')\n\t\tself.assertEqual(response.status_code, status.HTTP_200_OK)\n\t\tself.assertContains(response, edu)\n\n\tdef test_eduaction_api_can_update(self):\n\t\tedu = Education.objects.create(user=self.user, institution='UPSA',\n\t\t\t duration='2012-2016', certificate='BECE')\n\t\tdata = {'institution': 'KNUST', 'duration': '2012-2016',\n\t\t\t\t'certificate': 'WASSCE'}\n\t\turl = reverse('edu-api:edu-update', kwargs={'pk': edu.id})\n\t\tresponse = self.client.put(url, data, format='json')\n\t\tself.assertEqual(response.status_code, status.HTTP_200_OK)\n\n\tdef test_education_api_can_delete(self):\n\t\tedu = Education.objects.create(user=self.user, institution='UPSA',\n\t\t\t duration='2012-2016', certificate='BECE')\n\t\turl = reverse('edu-api:edu-delete', kwargs={'pk': edu.id})\n\t\tresponse = self.client.delete(url, format='json', follow=True)\n\t\tself.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)","sub_path":"education/tests/test_api_views.py","file_name":"test_api_views.py","file_ext":"py","file_size_in_byte":2089,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"318703451","text":"import os\nimport thread\nfrom subprocess import Popen, PIPE\n\npwd=os.getcwd()\n\nos.chdir(r\"foxeyerobot/build\")\n#os.system(\"ls\")\nos.system(\"make\")\n\nos.chdir(pwd)\nos.chdir(r\"foxeyerobot/bin\")\n\nprint(\"starting main\")\np = Popen('./FoxI_main', stdin=PIPE)\n\ndef start_foxIiso():\n print(\"starting iso\")\n #os.system(\"./FoxI_iso --nodisplay --avicfg /home/AD/atewary/LUUM/DeepEdgeSample/videoOut/autoRV_03-12-2020_15-22-12_858~ValidateIsolation_LOCK_DOWN_Right_LL0_target_x23.3734_y28.9256_z35.2151_~\")\n\ntry:\n thread.start_new_thread(start_foxIiso,())\nexcept:\n print(\"Error\")\n\nprint(\"feeding iso\")\np.communicate(os.linesep.join([\"IDbg12\",\"quit\"]))\nprint(\"exit program\")\n","sub_path":"script.py","file_name":"script.py","file_ext":"py","file_size_in_byte":670,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"603471891","text":"# -*- coding: utf-8 -*-\nfrom django.shortcuts import render, redirect\nfrom django.http import Http404\nfrom django.core.exceptions import ObjectDoesNotExist\nfrom django.http import Http404, HttpResponse\nfrom datetime import datetime\nfrom posts.models import Categoria, Post, Busca\nfrom autores.models import Autor\nfrom destaques.models import Destaque\nfrom utils.palavras_ignoradas import PALAVRAS_IGNORADAS\n\n\ndef home(request):\n\n\tdestaques = Destaque.objects.filter(ativo=True).order_by('?')\n\tposts = Post.objects.filter(ativado=True)\n\n\tVARS = {\n\t\t'destaques': destaques,\n\t\t'posts': posts,\n\t}\n\n\treturn render(request, 'home.html', VARS)\n\n\ndef tema(request, slug_tema=None):\n\n\tposts = Post.objects.filter(ativado=True).filter(tema=slug_tema)\n\tif slug_tema == 'filmes':\n\t\tpage_name = 'Filmes'\n\telif slug_tema == 'series':\n\t\tpage_name = u'Séries'\n\telif slug_tema == 'quadrinhos':\n\t\tpage_name = 'Quadrinhos'\n\telif slug_tema == 'jogos':\n\t\tpage_name = 'Jogos'\n\telse:\n\t\tpage_name = None\n\n\turl_social = 'tema/%s/' % slug_tema\n\n\tVARS = {\n\t\t'posts': posts,\n\t\t'page_name': page_name,\n\t\t'url_social': url_social,\n\t}\n\n\treturn render(request, 'categoria.html', VARS)\n\n\ndef categoria(request, slug_categoria=None):\n\n\ttry:\n\t\tcategoria = Categoria.objects.get(slug=slug_categoria)\n\t\tpage_name = categoria.nome\n\texcept:\n\t\traise Http404\n\n\tposts = Post.objects.filter(ativado=True).filter(categoria=categoria.id)\n\n\turl_social = 'categoria/%s/' % slug_categoria\n\n\tVARS = {\n\t\t'categoria': categoria,\n\t\t'posts': posts,\n\t\t'page_name': page_name,\n\t\t'url_social': url_social,\n\t}\n\n\treturn render(request, 'categoria.html', VARS)\n\n\ndef post(request, slug_post=None):\n\n\ttry:\n\t\tpost = Post.objects.get(slug=slug_post)\n\t\tpost.visitas += 1\n\t\tpost.save()\n\texcept:\n\t\traise Http404\n\n\tVARS = {\n\t\t'post': post\n\t}\n\n\treturn render(request, 'interna.html', VARS)\n\n\ndef autor(request, slug_autor=None):\n\n\ttry:\n\t\tautor = Autor.objects.get(slug=slug_autor)\n\t\tpage_name = autor.nome\n\texcept:\n\t\traise Http404\n\n\tposts = Post.objects.filter(ativado=True).filter(autor=autor.id)\n\n\turl_social = 'autor/%s/' % slug_autor\n\n\tVARS = {\n\t\t'autor': autor,\n\t\t'posts': posts,\n\t\t'page_name': page_name,\n\t\t'url_social': url_social,\n\t}\n\n\treturn render(request, 'categoria.html', VARS)\n\n\ndef busca(request):\n\n\tif request.method == 'POST':\n\t\tbusca_sel = Busca(busca = request.POST.get('busca'))\n\t\tbusca_sel.save()\n\telse:\n\t\tbusca_sel = None\n\n\tfrom django.db.models import Q\n\tlista = busca_sel.busca.split()\n\tlista = [l for l in lista if not l in PALAVRAS_IGNORADAS]\n\t\n\tposts = Post.objects.filter(ativado=True).filter(reduce(lambda x, y: x | y, [Q(titulo__icontains=word) for word in lista]))\n\tif not posts:\n\t\tposts = Post.objects.filter(ativado=True).filter(reduce(lambda x, y: x | y, [Q(chamada__icontains=word) for word in lista]))\n\n\tVARS = {\n\t\t'posts': posts,\n\t\t'busca_sel': busca_sel,\n\t\t'page_name': 'Busca: %s' % busca_sel.busca,\n\t}\n\n\treturn render(request, 'categoria.html', VARS)\n\n\ndef social(request, id_post=None):\n\n\ttry:\n\t\tpost = Post.objects.get(id=id_post)\n\t\treturn redirect('/post/%s' % post.slug)\n\texcept:\n\t\traise Http404\n\n\ndef google_www(request):\n\treturn HttpResponse('google-site-verification: google0d3edb2e1b3cfbf5.html')\n\n\ndef google(request):\n\treturn HttpResponse('google-site-verification: google6012a7eb8296e7b7.html')","sub_path":"irmaonerd/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3279,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"208335350","text":"from django.shortcuts import render\nfrom main_app.forms import UrlFieldForm\nfrom .models import StatusCodeField\nimport asyncio\nfrom . import async_requests\n\n\ndef get_url(request):\n if request.method == 'POST':\n form = UrlFieldForm(request.POST)\n if form.is_valid():\n form.save()\n url = form.cleaned_data.get('url_field')\n asyncio.run(async_requests.main(url))\n else:\n form = UrlFieldForm()\n return render(request, 'main_app/index.html', context={'form': form})\n\n\ndef status(request):\n context = {\n 'status_codes': StatusCodeField.objects.all()\n }\n\n return render(request, 'main_app/index.html', context)\n","sub_path":"main_app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":683,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"535848495","text":"# Clase en la cual buscaremos si la IP solcitada por el usuario se encuentra en la BD o no.\nimport seleniumDATA\nimport procesamintoIPS\n\ntry:\n import pymongo\n from pymongo import MongoClient\nexcept:\n print(\"Falta libreria mongodb.\")\n\nclass buscarBD():\n def sacar_DB(self):\n myclient = MongoClient(\"mongodb://192.168.10.170:55059\") # Conectamos con la maquina mongodb en nuestro servidor docker. \n mydb = myclient[\"db_ip\"] # Solicitamos la base de datos que queremos.\n mycol = mydb[\"ip\"] # Solicitamos la columna donde se encuentra la informacion.\n contador_DATA = mycol.count_documents({\"IP\": ip }) # Lanzamos un contador el cual nos cuenta relaciones que encontramos en nuestra base de datos.\n # Comprobamos los resultados dandole una variable de True y False, para el despues procesamiento.\n if contador_DATA == 1:\n se_han_encontrado_datos = True\n if contador_DATA == 0:\n se_han_encontrado_datos = False\n return se_han_encontrado_datos\n sacar_DB()\n if se_han_encontrado_datos == True:\n myquery = { \"IP\": ip }\n mydoc = mycol.find(myquery)\n for dato in mydoc:\n print(dato)\n # Si la variable fue False el programa enviara la IP a la clase selenium para su procesamiento y sacada de información.\n else:\n seleniumDATA","sub_path":"buscarDB.py","file_name":"buscarDB.py","file_ext":"py","file_size_in_byte":1442,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"449455707","text":"\ndata = []\ncount = 0\n\nwith open('reviews.txt', 'r') as f:\n\tfor line in f:\n\t\tdata.append(line)\n\t\tcount += 1\n\t\tif count % 1000 == 0:\n\t\t\tprint(len(data))\nprint('檔案讀取完了,總共有', len(data), '筆資料')\n\n#字的計數\nwc = {} #word_count\nfor d in data:\n\twords = d.split()\n\tfor word in words:\n\t\tif word in wc:\n\t\t\twc[word] += 1 \n\t\telse:\n\t\t\twc[word] = 1\n\nwhile True:\n\task = input('請問要查詢的字為: ')\n\tif ask == 'q':\n\t\tbreak\n\tif ask not in wc:\n\t\tprint('沒有這個字')\n\telse:\n\t\tprint(ask, '這個字出現過', wc[ask], '次')\nprint('感謝使用本查詢功能')\n\n\n# for word in wc:\n# \tif wc[word] > 1000000:\n# \t\tprint(word, wc[word])\n\n\n\n\n\n\n\n\n#算留言平均長度\n\n\n# number = 0\n# for word in data:\n# \tnumber += len(word)\n# print('留言平均長度為', number/len(data))\n\n\n# new = []\n# for word in data:\n# \tif len(word) < 100:\n# \t\tnew.append(word)\n# print('共有', len(new), '筆留言小於100字')\n\n# good = []\n# for word in data:\n# \tif 'good' in word:\n# \t\tgood.append(word)\n# print('共有', len(good), '筆留言提到good')\n# print(good[0])\n\n# # good = [d for d in data if 'good' in d]\n# bad = ['bad' in d for d in data]\n\n\n\n\n\"\"\"\nword = 'Hi, new world'\n\nfor w in word:\n\tprint(w)\n\"\"\"","sub_path":"message.py","file_name":"message.py","file_ext":"py","file_size_in_byte":1214,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"426464501","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Apr 23 01:18:22 2017\n\n@author: providence\n\"\"\"\n\nimport numpy as np\nfrom scipy.spatial.distance import pdist,squareform\nimport matplotlib.pyplot as plt\n\nL = 100 # simulation box dimension\nN = 1000 # Number of particles\ndim = 2 # Dimensions\n\n# Generate random positions of particles\nr = (np.random.random(size=(N,dim))-0.5)*L\n\n\nt1 = time.time() \nuti = np.triu_indices(100, k=1) # upper triangular indices\na = np.square(r[uti[0]]-r[uti[1]])\na = np.sqrt(np.sum(a,axis=1))\n\nprint(time.time()-t1)\n\nt1 = time.time() \nDD = pdist(r)\nprint(time.time()-t1)\n\nprint(a,DD)","sub_path":"sandbox/faster.py","file_name":"faster.py","file_ext":"py","file_size_in_byte":641,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"461639279","text":"from django.shortcuts import render, redirect, reverse\nfrom django.contrib.auth.decorators import login_required\n\n@login_required\ndef view_cart(request):\n '''\n Display the cart contents and calculate the overall total to\n facilitate checkout\n '''\n if 'cart' in request.session:\n cart = request.session['cart']\n else:\n cart = []\n\n if 'cart_upvotes' in request.session:\n cart_upvotes = request.session['cart_upvotes']\n else:\n cart_upvotes = []\n\n total = sum(float(item['feature_cost']) for item in cart) + sum(float(item['cost']) for item in cart_upvotes)\n return render(request, 'cart.html', {'cart': cart, 'cart_upvotes': cart_upvotes, 'total': total})\n\n@login_required\ndef adjust_cart(request, title):\n '''\n Retrieve each proposed feature in the cart and amend its cost if the feature title matches\n the title against which the amount was changed\n '''\n new_cost = float(request.POST.get('cost'))\n cart = request.session.get('cart', [])\n\n for item in cart:\n if item['title'] == title:\n item['feature_cost'] = new_cost\n\n request.session['cart'] = cart\n return redirect(reverse('view_cart'))\n\n@login_required\ndef adjust_upvote_cart(request, id):\n '''\n Retrieve each upvoted feature in the cart and amend its cost if the feature id matches\n the id against which the amount was changed\n '''\n new_cost = float(request.POST.get('cost'))\n cart_upvotes = request.session.get('cart_upvotes', [])\n\n for item in cart_upvotes:\n if item['id'] == int(id):\n item['cost'] = new_cost\n\n request.session['cart_upvotes'] = cart_upvotes\n return redirect(reverse('view_cart'))\n","sub_path":"cart/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1703,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"590175957","text":"from flask import request\nfrom flask import jsonify\nfrom flask import Flask\nfrom functools import reduce\nfrom datetime import datetime\nimport requests\nimport json\n\napp = Flask(__name__)\n\nupdateUrlBase = \"https://api.thingspeak.com/update?\"\n\n\n# temp_in;temp_out;hum_out;hum_in;pressure;co2;co2uart;uptime\nfields = {}\nfields['temp_out'] = 'field1'\nfields['hum_out'] = 'field2'\nfields['temp_in'] = 'field3'\nfields['hum_in'] = 'field4'\nfields['co2'] = 'field5'\nfields['pressure'] = 'field6'\nfields['uptime'] = 'field7'\nfields['co2uart'] = 'field8'\napi_key = ''\n\n\ndef pairParam(field, value):\n return '&' + str(field) + '=' + str(value)\n\n\ndef secondsSinceMid():\n now = datetime.now()\n seconds_since_midnight = (\n now - now.replace(hour=0, minute=0, second=0, microsecond=0)).total_seconds()\n return seconds_since_midnight\n\n\n@app.route('/')\ndef hello():\n updateUrl = updateUrlBase\n\n res = {}\n for i in request.args:\n res[i] = request.args.get(i)\n if i in fields:\n thingspeakField = fields[i]\n updateUrl += pairParam(thingspeakField, res[i])\n\n updateUrl += pairParam('api_key', api_key)\n\n res['url'] = updateUrl\n\n r = requests.get(updateUrl)\n res['api_answer'] = r.json()\n\n res['fields_mapping'] = fields\n\n res['api'] = api_key\n\n return jsonify(res)\n\n\n@app.route('/process')\ndef process():\n tUrl = url + str(int(secondsSinceMid()))\n r = requests.get(tUrl)\n return str(r.json())\n\n res = {}\n for i in request.args:\n res[i] = request.args.get(i)\n\n res['seconds'] = int(secondsSinceMid())\n\n return jsonify(res)\n\n\ndef convert_to_thingspeak_format(data):\n if not data['name'] in fields:\n return {}\n return {'created_at': data['ts'], fields[data['name']]: data['value']}\n\n\ndef convert_to_influx(data):\n return data['name'] + \" value=\" + str(data['value']) + \" \" + str(data['ts'])\n\n\nsensors_cache = []\n\n\ndef send_to_thingspeak(data):\n global sensors_cache\n sensors_cache.extend(data)\n\n A = sensors_cache[:300]\n B = sensors_cache[300:]\n\n body = {}\n body['write_api_key'] = api_key\n body['updates'] = A\n\n try:\n r = requests.post(\n 'http://api.thingspeak.com/channels/538670/bulk_update.json', json=body)\n resp = r.json()\n if 'success' in resp and resp['success']:\n sensors_cache = B\n except Exception as e:\n return e\n\n return len(sensors_cache)\n\n\n@app.route('/bulk', methods=['GET', 'POST'])\ndef bulk():\n with open(\"static/log.txt\", \"a\") as f:\n f.write(str(datetime.now()))\n f.write(\"\\n\")\n f.write(\"headers: \\n\")\n f.write(str(request.headers['Sensors-Names']))\n f.write(\"\\n\")\n d = request.data\n f.write(str(d))\n f.write(\"\\n\\n\\n\")\n\n res = {}\n\n sensors_data_raw = request.data.decode(\"utf-8\").split('_')\n sensors_names = request.headers['Sensors-Names'].split(';')\n\n sensors_count = len(sensors_names)\n sensors_data = []\n for sensor in sensors_data_raw:\n if sensor:\n values = sensor.split(';')\n ts = int(values[0])\n sensors = []\n for i in range(sensors_count):\n if not values[i * 2 + 1]:\n continue\n\n sensor_data = {}\n sensor_data['name'] = sensors_names[i]\n sensor_data['value'] = values[i * 2 + 1]\n sensor_data['ts'] = ts - int(values[i * 2 + 2])\n sensors.append(sensor_data)\n\n sensors_data.append(sensors)\n\n sensors_data = reduce(list.__add__, sensors_data)\n ts_data = [convert_to_thingspeak_format(\n e) for e in sensors_data if e['name'] in fields]\n\n by_ts = {}\n for sensor in sensors_data:\n ts = sensor['ts']\n if not ts in by_ts:\n by_ts[ts] = {}\n by_ts[ts]['created_at'] = ts\n if sensor['name'] in fields:\n by_ts[ts][fields[sensor['name']]] = sensor['value']\n\n influx_data = [convert_to_influx(e) for e in sensors_data]\n r = requests.post(\n 'http://influxdb:8086/write?db=meteo&precision=s', data=\"\\n\".join(influx_data))\n\n cnt = send_to_thingspeak(list(by_ts.values()))\n return jsonify(cnt)\n\n\n@app.route('/log')\ndef log():\n # return \"1\"\n return app.send_static_file('log.txt')\n with open('log.txt') as f:\n return \" \".join(f.readlines())\n\n\nif __name__ == \"__main__\":\n with open('config.json') as f:\n data = json.load(f)\n global api_key\n api_key = data['api_key']\n\n app.run(host=\"0.0.0.0\", debug=True)\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":4573,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"469762840","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\nfrom argparse import ArgumentParser\n#from keras.preprocessing.text import Tokenizer\nimport numpy\nimport pdb\nimport re\nimport sys\n\n\nSTART = \"\"\nEND = \".\"\n\n\ndef main():\n parser = ArgumentParser(prog=\"simple-language-model\")\n parser.add_argument(\"training_input\")\n args = parser.parse_args()\n corpus_lines = None\n\n with open(args.training_input, \"r\") as fh:\n corpus_lines = fh.readlines()\n\n vocabulary = build_vocabulary(corpus_lines)\n x_train = []\n y_train = []\n\n for line in corpus_lines:\n for sentence in split_sentences(line):\n virtual_sentence = [START] + sentence\n\n if virtual_sentence[-1] != END:\n virtual_sentence += [END]\n\n for i, word in enumerate(virtual_sentence):\n if i + 1 < len(virtual_sentence):\n #print(word, virtual_sentence[i + 1])\n x_train += [vocabulary.ook_encode(word)]\n y_train += [vocabulary.ook_encode(virtual_sentence[i + 1])]\n\n #sys.exit(1)\n #print(\"training x: %s\" % x_train)\n #print(\"training y: %s\" % y_train)\n from keras.models import Sequential\n from keras.layers import Dense, LSTM, Embedding, Flatten\n model = Sequential()\n\n ###\n # Plain feed foward network (pass)\n ###\n #model.add(Dense(len(vocabulary) / 2, input_dim=len(vocabulary), activation=\"sigmoid\"))\n #model.add(Dense(len(vocabulary), activation=\"softmax\"))\n\n ###\n # Manual embeddings, feed foward network (..)\n ###\n model.add(Dense(10, input_dim=len(vocabulary), activation=\"linear\"))\n model.add(Dense(len(vocabulary) / 2, activation=\"sigmoid\"))\n model.add(Dense(len(vocabulary), activation=\"softmax\"))\n\n ###\n # Embeddings, feed foward network (fail)\n ###\n #model.add(Embedding(len(vocabulary), 10, input_length=1))\n #model.add(Flatten())\n #model.add(Dense(len(vocabulary), activation=\"softmax\"))\n\n # Random\n #model.add(LSTM(50))\n print(\"Vocabulary: %d\" % len(vocabulary))\n print(model.summary())\n model.compile(loss=\"categorical_crossentropy\",\n optimizer=\"adam\")\n model.fit(numpy.array(x_train), numpy.array(y_train), epochs=100, verbose=1)\n print(\"Fitted. Running 3 samples.\")\n\n for i in range(0, 3):\n previous = START\n sequence = [previous]\n\n while True:\n prediction = model.predict(numpy.array([vocabulary.ook_encode(previous)]), verbose=2)\n current = vocabulary.sampling_ook_decode(prediction)\n sequence += [current]\n previous = current\n\n if current == END:\n break\n\n if len(sequence) > 80:\n break\n\n print(\" \".join(sequence))\n\n return 0\n\n\nclass Vocabulary:\n def __init__(self, words):\n self.encoding = {}\n self.decoding = {}\n i = 0\n\n for word in words:\n self.encoding[word] = i\n self.decoding[i] = word\n i += 1\n\n def encode(self, word):\n return self.encoding[word]\n\n def ook_encode(self, word):\n l = [0] * len(self)\n l[self.encode(word)] = 1\n return numpy.array(l)\n\n def decode(self, value):\n return self.decoding[value]\n\n def ook_decode(self, array):\n return self.decode(array.argmax())\n\n def sampling_ook_decode(self, array):\n return self.decode(numpy.random.choice(len(self), 1, p=array[0])[0])\n\n def __len__(self):\n return len(self.encoding)\n\n\ndef split_words(text):\n return re.findall(r\"\\w+\", text, re.UNICODE)\n\n\ndef split_sentences(text):\n words = split_words(text)\n sentences = []\n sentence = []\n\n for word in words:\n if word == END:\n sentences += [sentence]\n sentence = []\n else:\n sentence += [word]\n\n if len(sentence) > 0:\n sentences += [sentence]\n\n return sentences\n\n\ndef build_vocabulary(corpus_lines):\n words = set()\n\n for line in corpus_lines:\n for word in split_words(line):\n words.add(word)\n\n words.add(START)\n words.add(END)\n return Vocabulary(words)\n\n\nif __name__ == \"__main__\":\n sys.exit(main())\n\n","sub_path":"simple-language-model.py","file_name":"simple-language-model.py","file_ext":"py","file_size_in_byte":4204,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"480448177","text":"#!/usr/bin/python\n\nimport roslib; roslib.load_manifest('axis_camera')\nimport rospy\nimport math\n\nfrom geometry_msgs.msg import PointStamped\n\n\nclass TestLookAt:\n def __init__(self):\n rospy.init_node('axis_ptz_test_look_at')\n self.pub = rospy.Publisher('/axis/target', PointStamped)\n \n def spin(self):\n P = PointStamped()\n self.pub.publish(P)\n rospy.sleep(1.0)\n for i in range(0,12):\n if rospy.is_shutdown():\n break\n P = PointStamped()\n P.header.stamp = rospy.Time.now()\n P.header.frame_id = \"/kingfisher/laser\"\n P.point.x = 3.0 * math.cos(i*math.pi/6.)\n P.point.y = 3.0 * math.sin(i*math.pi/6.)\n P.point.z = 0.0\n rospy.loginfo(\"Axis: Looking at \\n\" + str(P.point))\n self.pub.publish(P)\n rospy.sleep(5.0)\n\n\n\nif __name__ == \"__main__\": TestLookAt().spin()\n","sub_path":"tests/test_look_at.py","file_name":"test_look_at.py","file_ext":"py","file_size_in_byte":932,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"70549056","text":"from clubsandwich.blt.context import BearLibTerminalContext\nfrom clubsandwich.geom import Size, Point\n\nfrom components.fighter import Fighter\nfrom death_functions import kill_monster, kill_player\nfrom entity import Entity\nfrom game_states import GameStates\nfrom input_handlers import handle_keys\nfrom map import TileMap\nfrom render import render_all\n\nscreen = Size(80, 50)\nroom_max = 12\nroom_min = 8\nmax_rooms = 30\nmax_monsters_per_room = 3\n\nplayer = Entity(screen.x // 2, screen.y // 2, '@', 'white', 'Player', blocks=True, fighter=Fighter(30, 2, 5))\n\nentities = [player]\n\nmouse = Point(0, 0)\n\ngame_state = GameStates.PLAYERS_TURN\n\ntilemap = TileMap(screen)\ntilemap.make_map(max_rooms, room_min, room_max, screen.width, screen.height, player, entities, max_monsters_per_room)\n\nterminal = BearLibTerminalContext()\n\nterminal.open()\nterminal.set(\"\"\"window.size={size.width}x{size.height}\"\"\".format(size=screen))\nterminal.set(\"input: filter=[keyboard, mouse_left]\")\n\nwhile True:\n terminal.clear()\n render_all(terminal, player, entities, tilemap)\n terminal.puts(1, 1, 'Mouse: {}, {}'.format(mouse.x, mouse.y))\n terminal.refresh()\n key = terminal.read()\n action = handle_keys(key)\n print(action)\n\n player_turn_results = []\n\n if game_state == GameStates.PLAYERS_TURN:\n if action['move']:\n result = player.move_to(action['move'] + player.pos, tilemap, entities)\n if result:\n player_turn_results.extend(result)\n game_state = GameStates.ENEMY_TURN\n\n if action['mouse']:\n mouse = action['mouse']\n\n for result in player_turn_results:\n message = result.get('message')\n dead_entity = result.get('dead')\n\n if message:\n print(message)\n\n if dead_entity:\n if dead_entity == player:\n message, game_state = kill_player(dead_entity)\n else:\n message = kill_monster(dead_entity)\n\n if message:\n print(message)\n\n if game_state == GameStates.ENEMY_TURN:\n for entity in entities:\n if entity.ai:\n\n enemy_turn_results = entity.ai.take_turn(player, tilemap, entities)\n\n for result in enemy_turn_results:\n message = result.get('message')\n dead_entity = result.get('dead')\n\n if message:\n print(message)\n if dead_entity:\n if dead_entity == player:\n message, game_state = kill_player(dead_entity)\n else:\n message = kill_monster(dead_entity)\n\n if message:\n print(message)\n\n if game_state == GameStates.PLAYER_DEAD:\n break\n\n if game_state == GameStates.PLAYER_DEAD:\n break\n else:\n game_state = GameStates.PLAYERS_TURN\n\n if action['exit']:\n break\n\nterminal.close()\n","sub_path":"engine.py","file_name":"engine.py","file_ext":"py","file_size_in_byte":3061,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"100913185","text":"import dgl.function as fn\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nclass HeteroRGCNLayer(nn.Module):\n def __init__(self, G, in_size=None, out_size=64):\n super(HeteroRGCNLayer, self).__init__()\n # W_r for each relation\n if in_size is None:\n self.weight = nn.ModuleDict({\n # name : nn.Linear(in_size, out_size) for name in etypes\n etype : nn.Linear(G.nodes[srctype].data[\"feats\"].shape[-1], out_size) for srctype, etype, dsttype in G.canonical_etypes\n })\n else:\n self.weight = nn.ModuleDict({\n etype : nn.Linear(in_size, out_size) \n for srctype, etype, dsttype in G.canonical_etypes\n })\n\n\n def forward(self, G, feat_dict):\n # The input is a dictionary of node features for each type\n funcs = {}\n for srctype, etype, dsttype in G.canonical_etypes:\n # Compute W_r * h\n Wh = self.weight[etype](feat_dict[srctype])\n # Save it in graph for message passing\n G.nodes[srctype].data['Wh_%s' % etype] = Wh\n # Specify per-relation message passing functions: (message_func, reduce_func).\n # Note that the results are saved to the same destination feature 'h', which\n # hints the type wise reducer for aggregation.\n funcs[etype] = (fn.copy_u('Wh_%s' % etype, 'm'), fn.mean('m', 'h'))\n # Trigger message passing of multiple types.\n # The first argument is the message passing functions for each relation.\n # The second one is the type wise reducer, could be \"sum\", \"max\",\n # \"min\", \"mean\", \"stack\"\n G.multi_update_all(funcs, 'sum')\n # return the updated node feature dictionary\n return {ntype : G.nodes[ntype].data['h'] for ntype in G.ntypes}\n\nclass HeteroRGCN(nn.Module):\n def __init__(self, G, hidden_size, out_size):\n super(HeteroRGCN, self).__init__()\n # create layers\n self.layer1 = HeteroRGCNLayer(G=G, out_size=hidden_size)\n self.layer2 = HeteroRGCNLayer(G=G,in_size=hidden_size, out_size=out_size)\n\n def forward(self, G):\n embed = nn.ParameterDict({ntype : nn.Parameter(G.nodes[ntype].data[\"feats\"], requires_grad=False) \n for ntype in G.ntypes})\n if next(self.parameters()).is_cuda:\n embed =embed.cuda() \n h_dict = self.layer1(G, embed)\n h_dict = {k : F.leaky_relu(h) for k, h in h_dict.items()}\n h_dict = self.layer2(G, h_dict)\n # get paper logits\n return h_dict\n","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":2635,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"75810021","text":"\"\"\"projectweb URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/3.2/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: path('', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.urls import include, path\n 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))\n\"\"\"\nfrom django.urls import path\nfrom .views import (\n PostListView,\n PostDetailView,\n PostCreateView,\n PostUpdateView,\n PostDeleteView,\n UserPostListView\n )\nfrom . import views\n\nurlpatterns = [\n#as_view it's a method transform the class to a view we can see it\n path('', PostListView.as_view(), name='blog-home'),\n path('user/', UserPostListView.as_view(), name='user-posts'),\n path('post//', PostDetailView.as_view(), name='post-detail'),\n #if i want to see the blog one or two by details (pl hiya primary key (1,2..) \n #after that we need a template to show all our posts details\n path('post/new/', PostCreateView.as_view(), name='post-create'),\n path('post//update/', PostUpdateView.as_view(), name='post-update'),#here we should know the\"pk\" because we gona know hwich id of post we gone modifie\n path('post//delete/', PostDeleteView.as_view(), name='post-delete'),\n path('about/', views.about, name='blog-about'),\n\n #path('about/', views.AboutPageView.as_view(), name='about'),\n]\n#template with naming convention\n#/ .html\n#donc myapp_foormation POst(model eli testena fih) and the view type is List\n","sub_path":"myapp_formation/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1853,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"299406594","text":"# Copyright 2018-2019 QuantumBlack Visual Analytics Limited\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# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES\n# OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND\n# NONINFRINGEMENT. IN NO EVENT WILL THE LICENSOR OR OTHER CONTRIBUTORS\n# BE LIABLE FOR ANY CLAIM, DAMAGES, OR OTHER LIABILITY, WHETHER IN AN\n# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF, OR IN\n# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n#\n# The QuantumBlack Visual Analytics Limited (\"QuantumBlack\") name and logo\n# (either separately or in combination, \"QuantumBlack Trademarks\") are\n# trademarks of QuantumBlack. The License does not grant you any right or\n# license to the QuantumBlack Trademarks. You may not use the QuantumBlack\n# Trademarks or any confusingly similar mark as a trademark for your product,\n# or use the QuantumBlack Trademarks in any other manner that might cause\n# confusion in the marketplace, including but not limited to in advertising,\n# on websites, or on software.\n#\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# pylint: disable=no-member,unused-argument\nimport socket\n\nimport pytest\nimport requests\n\nfrom kedro.io import CSVHTTPDataSet, DataSetError\nfrom kedro.io.core import DataSetNotFoundError\n\nTEST_FILE_URL = \"http://example.com/test.csv\"\nTEST_SAMPLE_CSV_DATA = \"\"\"\n\"Index\", \"Mass (kg)\", \"Spring 1 (m)\", \"Spring 2 (m)\"\n 1, 0.00, 0.050, 0.050\n 2, 0.49, 0.066, 0.066\n 3, 0.98, 0.087, 0.080\n 4, 1.47, 0.116, 0.108\n 5, 1.96, 0.142, 0.138\n 6, 2.45, 0.166, 0.158\n 7, 2.94, 0.193, 0.174\n 8, 3.43, 0.204, 0.192\n 9, 3.92, 0.226, 0.205\n10, 4.41, 0.238, 0.232\"\"\"\n\n\n@pytest.fixture\ndef sample_remote_csv_file(requests_mock):\n return requests_mock.get(\n TEST_FILE_URL, content=TEST_SAMPLE_CSV_DATA.encode(\"utf-8\")\n )\n\n\n@pytest.fixture\ndef csv_data_set():\n return CSVHTTPDataSet(fileurl=TEST_FILE_URL)\n\n\nclass TestCSVHTTPDataSet:\n def test_successfully_load(self, csv_data_set, sample_remote_csv_file):\n \"\"\"\n Test that given the right URL returning good CSV content,\n we parse it successfully.\n \"\"\"\n df = csv_data_set.load()\n\n # Just check we'ce successfully loaded the data.\n assert len(df) == 10\n\n def test_resource_not_found(self, csv_data_set, requests_mock):\n \"\"\"\n The server responds with 404,\n we should raise a specific exception in this case.\n \"\"\"\n requests_mock.get(\n TEST_FILE_URL,\n content=b\"Nope, not found\",\n status_code=requests.codes.NOT_FOUND,\n )\n with pytest.raises(DataSetNotFoundError, match=\"The server returned 404 for\"):\n csv_data_set.load()\n\n def test_http_error(self, csv_data_set, requests_mock):\n \"\"\"\n In case of an unexpected HTTP error, we re-raise DataSetError.\n \"\"\"\n requests_mock.get(\n TEST_FILE_URL,\n content=b\"You shall not pass\",\n status_code=requests.codes.FORBIDDEN,\n )\n with pytest.raises(DataSetError, match=\"Failed to fetch data\"):\n csv_data_set.load()\n\n def test_socket_error(self, csv_data_set, requests_mock):\n \"\"\"\n If failed to connect completely and a socket error is raised,\n re-raise DataSetError.\n \"\"\"\n requests_mock.get(TEST_FILE_URL, exc=socket.error)\n with pytest.raises(DataSetError, match=\"Failed to connect\"):\n csv_data_set.load()\n\n def test_read_only_mode(self, csv_data_set):\n \"\"\"\n Saving is disabled on the data set.\n \"\"\"\n with pytest.raises(DataSetError, match=\"is a read only data set type\"):\n csv_data_set.save({})\n\n def test_exists_not_found(self, csv_data_set, requests_mock):\n \"\"\"\n The remote server returns 404, we should report that it doesn't exist.\n \"\"\"\n requests_mock.get(\n TEST_FILE_URL,\n content=b\"Nope, not found\",\n status_code=requests.codes.NOT_FOUND,\n )\n assert not csv_data_set.exists()\n\n def test_exists_http_error(self, csv_data_set, requests_mock):\n \"\"\"\n In case of an unexpected HTTP error,\n ``exists()`` should not silently catch it.\n \"\"\"\n requests_mock.get(\n TEST_FILE_URL,\n content=b\"You shall not pass\",\n status_code=requests.codes.FORBIDDEN,\n )\n with pytest.raises(DataSetError, match=\"Failed to fetch data\"):\n csv_data_set.exists()\n\n def test_exists_ok(self, csv_data_set, sample_remote_csv_file):\n \"\"\"\n If the file actually exists and server responds 200,\n ``exists()`` should return True\n \"\"\"\n assert csv_data_set.exists()\n","sub_path":"tests/io/test_csv_http.py","file_name":"test_csv_http.py","file_ext":"py","file_size_in_byte":5086,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"375843672","text":"print(\"CONTROLE DE COTAS DE DISCO\")\r\n\r\n# CRIANDO O ARQUIVO USUARIOS\r\narq = open(\"usuarios.txt\",\"w\")\r\narq.write(\"alexandre 456123789\"\r\n \"\\nanderson 1245698456\"\r\n \"\\nantonio 123456456\"\r\n \"\\ncarlos 91257581\"\r\n \"\\ncesar 987458\"\r\n \"\\nrosemary 789456125\")\r\narq.close()\r\n\r\n# LENDO O ARQUIVO USUARIOS LINHA POR LINHA\r\narq_read = open(\"usuarios.txt\",\"r\")\r\nlinhas = arq_read.readlines()\r\narq_read.close()\r\n\r\n# VARIAVEIS\r\nusuarios = []\r\nespacosUtilizados = []\r\nespacoTotal = 0.0\r\n\r\n# LOOP FOR PARA ADICIONAR CADA UMA DAS LINHAS DO ARQUIVO NAS VARIAVEIS\r\nfor linha in linhas:\r\n campos = linha.split()\r\n usuario = campos[0]\r\n espacoUtilizado = int(campos[1])\r\n usuarios.append(usuario)\r\n espacosUtilizados.append(espacoUtilizado)\r\n espacoTotal += espacoUtilizado\r\n\r\n# CRIANDO O ARQUIVO PARA O RELATORIO\r\narq1 = open('relatorio.txt', 'w')\r\narq1.write(\r\n 'ACME Inc. Uso do espaco em disco pelos usuarios\\n')\r\narq1.write(\r\n '------------------------------------------------------------------------')\r\narq1.write('\\nNr. Usuario Espaco utilizado %% do uso')\r\n\r\n# LOOP FOR PARA REALIZAR OS CALCULOS DE CADA ITENS DAS LISTAS/VARIAVEIS\r\nfor i in range(0, len(usuarios)):\r\n espacoMB = espacosUtilizados[i] / (1024.0 * 1024.0)\r\n percentualUso = espacosUtilizados[i] / espacoTotal\r\n arq1.write('\\n%d - %s - %.2f MB - %.2f%%' %\r\n (i + 1, usuarios[i], espacoMB, percentualUso * 100.0))\r\n\r\n# RESULTADO FINAL DOS CALCULOS\r\narq1.write('\\nEspaco total ocupado: %.2f MB' %\r\n (espacoTotal / (1024.0 * 1024.0)))\r\narq1.write('\\nEspaco medio ocupado: %.2f MB' %\r\n (espacoTotal / len(usuarios) / (1024.0 * 1024.0)))\r\narq1.close()\r\n","sub_path":"Controle de cotas de disco/Controle de cotas de disco.py","file_name":"Controle de cotas de disco.py","file_ext":"py","file_size_in_byte":1728,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"621899913","text":"arr = []\r\n\r\nwith open(\"A-large.in\") as f:\r\n n = int(f.readline())\r\n #print(n)\r\n for i in range(n):\r\n x = int(f.readline())\r\n arr.append(x)\r\n\r\nfo = open('output.out', 'w')\r\n\r\ndef evaluate(i, index):\r\n digits = []\r\n digits = list(set(str(i)))\r\n contor = 2\r\n while(len(digits)!=10):\r\n inc = contor * i\r\n digits= list(set( digits + list(set(str(inc)))))\r\n contor+=1\r\n fo.write(\"Case #{}: \".format(index) + str(inc)+ \"\\n\")\r\n \r\n \r\n\r\n \r\n#print(arr)\r\n\r\nfor i in range(n):\r\n if arr[i]==0: fo.write(\"Case #{}: INSOMNIA\".format(i+1) + \"\\n\")\r\n else: \r\n evaluate(arr[i], i+1)\r\n \r\nfo.close()\r\n \r\n ","sub_path":"codes/CodeJamCrawler/16_0_1/Ricka/gA.py","file_name":"gA.py","file_ext":"py","file_size_in_byte":674,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"326327701","text":"import pandas as pd\nimport numpy as np\nfrom sklearn.linear_model import LogisticRegression\nimport pickle\n\ndef data_split(data, ratio):\n np.random.seed(42)\n shuffled = np.random.permutation(len(data))\n test_set_size = int(len(data) * ratio)\n test_indices = shuffled[:test_set_size]\n train_indices = shuffled[test_set_size:]\n return data.iloc[train_indices], data.iloc[test_indices]\n\n\nif __name__ == \"__main__\":\n # read the data\n df = pd.read_csv('/home/dhruvin/python/code/Corona Symptom/data.csv')\n \n \n # train test split \n train, test = data_split(df, 0.2)\n \n x_train = train[['fever','Bodypain','age','Runnynose','diffBreath']].to_numpy()\n x_test = test[['fever','Bodypain','age','Runnynose','diffBreath']].to_numpy()\n\n y_train = train[['infectionProb']].to_numpy().reshape(560,)\n y_test = test[['infectionProb']].to_numpy().reshape(140,)\n\n # model implementation\n model = LogisticRegression()\n model.fit(x_train, y_train)\n\n # open a file, np.where you want to store the data\n file = open('model.pkl','wb')\n\n # dump information to that file\n pickle.dump(model, file)\n file.close()\n","sub_path":"Corona Symptom/myTraining.py","file_name":"myTraining.py","file_ext":"py","file_size_in_byte":1158,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"544183985","text":"\"\"\"\nName: Giang Duong\nID : 014533857\n# Homework 4.1 - PCA\n\"\"\"\nimport numpy as np\nA = [[1,2], [3,1], [2, 3]]\nAT = np.transpose(A)\nC = 1/2 * np.matmul(A, AT)\nprint(C)\neigenvalue, eigenvector = np.linalg.eig(C)\neigenvalueNEW = []\narray = []\nmin = min(eigenvalue)\nfor i in range(len(eigenvalue)):\n if eigenvalue[i] > min:\n eigenvalueNEW.append(eigenvalue[i])\n array.append(i)\n\n\nprint(\"Eigenvalues of C = \\n\",eigenvalueNEW)\nfor i in array:\n print(eigenvector[i])","sub_path":"CS271HMK_Assignment4_Duong_3857/4.4.py","file_name":"4.4.py","file_ext":"py","file_size_in_byte":477,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"249087119","text":"# 引入模块\nimport tensorflow as tf\n\n# 创建 silm 对象\nslim = tf.contrib.slim\n\n\ndef vgg_16(inputs,\n num_classes=1000,\n is_training=True,\n dropout_keep_prob=0.5,\n spatial_squeeze=True,\n scope='vgg_16'):\n # 建立 vgg_16 的网络结构\n with tf.variable_scope(scope, 'vgg_16', [inputs]):\n # conv1 两次,卷积网络3,3,特征层输出64,输出(224,224,64)\n net = slim.repeat(input, 2, slim.conv2d, 64, [3, 3], scope='conv1')\n # 最大池化2*2,输出net(112,112,64)\n net = slim.max_pool2d(net, [2, 2], scope='pool1')\n\n # conv2 两次,卷积网络3,3,特征层输出128,输出(112,112,256)\n net = slim.repeat(net, 2, slim.sonv2d, 128, [3, 3], scope='conv2')\n # 最大池化2*2,输出net(56,56,256)\n net = slim.max_pool2d(net, [2, 2], scope='pool2')\n\n # conv3 三次,卷积网络3,3,特征层输出256,输出(56,56,256)\n net = slim.repeat(net, 3, slim.con2d, 256, [3, 3], scope='conve3')\n # 最大池化2*2,输出net(28,28,256)\n net = slim.max_pool2d(net, [2, 2], scope='pool3')\n\n # conv4 三次,卷积网络3,3,特征层输出512,输出(28,28,512)\n net = slim.repeat(net, 3, slim.con2d, 512, [3, 3], scope='conve4')\n # 最大池化2*2,输出net(14,14,512)\n net = slim.max_pool2d(net, [2, 2], scope='pool4')\n\n # conv5 三次,卷积网络3,3,特征层输出512,输出(14,14,512)\n net = slim.repeat(net, 3, slim.conv2d, 512, [3, 3], scope='conve5')\n # 最大池化2*2,输出net(7,7,512)\n net = slim.max_pool2d(net, [2, 2], scope='pool5')\n\n # 利用卷积的方式模拟全连接层,net输出(7,7,4096)\n net = slim.conve2d(net, 4096, [7, 7], padding='VALID', scope='fc6')\n net = slim.dropout(net, dropout_keep_prob, is_training=is_training,\n scope='dropout6')\n # 利用卷积的方式模拟全连接层,net输出(1,1,4096)\n net = slim.con2d(net, 4096, [1, 1], scope='fc7')\n net = slim.dropout(net, dropout_keep_prob, is_training=is_training,\n scope='dropout7')\n # 利用卷积的方式模拟全连接层,net输出(1,1,100)\n net = slim.con2d(net, num_classes, [1, 1],\n activation_fn=None,\n normalizer_fn=None,\n scope='fc8')\n # 因为卷积的方式模拟全连接成,所以输出需平铺\n if spatial_squeeze:\n net = tf.spueeze(net, [1, 2], name='fc8/squeeze')\n return net\n","sub_path":"Homework/76+彭长江+四川/Vgg_.py","file_name":"Vgg_.py","file_ext":"py","file_size_in_byte":2681,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"490083441","text":"import math\nimport pprint\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.interpolate import spline\n\ndef f(x):\n res = 4+x+x*x\n return 1/res\n\ndef getPointsPoly(N):\n xlist = []\n ylist = []\n for i in range(N+1):\n x=-5+10.0/N*i\n xlist.append(x)\n ylist.append(f(x))\n\n return xlist, ylist\n\ndef getPointsCos(N):\n xlist = []\n ylist = []\n for i in range(N+1):\n x = (2.0*i+1)/(2*N+2)\n x = x * math.pi\n x = -5 * math.cos(x)\n\n xlist.append(x)\n ylist.append(f(x))\n\n return xlist, ylist\n\ndef estimate(X, Y, N):\n xlist = []\n ylist = []\n testy = []\n deltay = []\n ratio = []\n\n for i in range(501):\n x = i/50.0-5\n xlist.append(x)\n y1 = f(x)\n y2 = lagrange(x,X,Y)\n dy = math.fabs(y1-y2)\n ylist.append(y1)\n testy.append(y2)\n deltay.append(dy)\n ratio.append(dy/y1)\n\n drawFigure(xlist, ylist, xlist, testy)\n\n\n error = max(deltay)\n relateveError = max(ratio)\n print(\"N&%.12e&%.12e\" % (error, relateveError))\n\n# def estimateCos(X, Y, N):\n# xlist = []\n# ylist = []\n# testy = []\n# deltay = []\n# ratio = []\n\n# for i in range(501):\n# x = (2.0*i+1)/(2*N+2)\n# x = x * math.pi\n# x = -5 * math.cos(x)\n# # input()\n\n# xlist.append(x)\n# y1 = f(x)\n# y2 = lagrange(x,X,Y)\n# dy = math.fabs(y1-y2)\n# ylist.append(y1)\n# testy.append(y2)\n# deltay.append(dy)\n# ratio.append(dy/y1)\n\n\n# error = max(deltay)\n# relateveError = max(ratio)\n# print(error, relateveError)\n\n\n# # drawFigure(xlist, ylist, xlist, testy)\n# xlist.sort()\n# # pprint.pprint(xlist)\n\n# return error\n\n\ndef lagrange(x, xlist, ylist):\n n = len(xlist)\n res = 0.0\n for i in range(n):\n temp = 1.0\n for j in range(n):\n if i!=j:\n temp = temp*(x-xlist[j])/(xlist[i]-xlist[j])\n res = res + temp * ylist[i]\n return res\n\ndef drawFigure(pxlist, pylist, exlist, eylist):\n\n fig = plt.figure()\n ax1 = fig.add_subplot(111)\n\n ax1.set_title('Scatter Plot')\n plt.xlabel('X')\n plt.ylabel('Y')\n\n plt.xlim(-5, 5)\n plt.ylim(-0.1, 0.4)\n\n ax1.plot(pxlist, pylist, c='y')\n ax1.plot(exlist, eylist, c='b')\n #print(len(exlist), len(eylist))\n # ax1.scatter(pxlist, pylist, c='y')\n # ax1.scatter(exlist, eylist, c='b')\n\n\n plt.legend(['f(x)','p(x)'])\n plt.show()\n\ndef main():\n Nlist = [4,8,16]\n errorList = []\n for N in Nlist:\n X, Y = getPointsPoly(N)\n errorList.append(estimate(X,Y,N))\n\n for N in Nlist:\n X, Y = getPointsCos(N)\n errorList.append(estimate(X,Y,N))\n\n #print(errorList)\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"2019spring/numAnalysis/lab2/lab2.py","file_name":"lab2.py","file_ext":"py","file_size_in_byte":2800,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"450408325","text":"#\n# @lc app=leetcode id=123 lang=python\n#\n# [123] Best Time to Buy and Sell Stock III\n#\n\n# @lc code=start\nclass Solution(object):\n def maxProfit(self, prices):\n \"\"\"\n :type prices: List[int]\n :rtype: int\n \"\"\"\n # own intuition: 1 get list of valley and peaks;choose two subsets maximize profits\n # HALT thinking as hard problem\n\n # no 2 Garvit DP, DONT understand\n n = len(prices)\n if n == 1:\n return 0\n dp = [[0] * n for _ in range(3)]\n for i in range(1,3):\n maxDiff = -prices[0]\n for j in range(1, n):\n dp[i][j] = max(dp[i][j-1], prices[j] + maxDiff)\n maxDiff = max(maxDiff, dp[i-1][j] - prices[j])\n return dp[2][n-1]\n\n\n \n# @lc code=end\n\n","sub_path":"123.best-time-to-buy-and-sell-stock-iii.py","file_name":"123.best-time-to-buy-and-sell-stock-iii.py","file_ext":"py","file_size_in_byte":799,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"465343568","text":"from importlib import import_module\nimport numpy as np\nimport sys\nimport argparse\nfrom truth import version\nimport pytest\n\ndef attach_dimensional_subsetting_args(parser):\n \"\"\"Attach dimesional subsetting args to the parser.\n\n Args:\n parser (argparse.ArgumentParser) : Parser object\n\n Returns:\n argparse.ArgumentParser : Updated parser\n \"\"\"\n parser.add_argument(\n '-d', '--dimension',\n help='Dimensional subsetting. -d dim,[min],[max],[stride]',\n type=str,\n action='append'\n )\n return parser\n\n\ndef get_argument_parser():\n \"\"\"Get an argument parser for truth.\n\n Returns:\n argparse.Namespace : Arguments object\n \"\"\"\n parser = argparse.ArgumentParser()\n\n # Add version information\n parser.add_argument(\n '--version',\n help='Display Truth version',\n default=False,\n action='store_true'\n )\n\n parser.add_argument(\n '--disable_warnings',\n help='Disable python warnings',\n default=False,\n action='store_true'\n )\n\n # Add hyperslab-like syntax\n parser = attach_dimensional_subsetting_args(parser)\n\n # Subparsers override this to their default args\n parser.set_defaults(func=None)\n\n # # Add the metric\n # parser.add_argument('metric', help='Metric', nargs='?')\n #\n # # Add inputs\n # parser.add_argument('a', help='First input', nargs='?')\n # parser.add_argument('b', help='Second input', nargs='?')\n\n return parser\n\n\n\ndef cli(args): # pragma: no cover\n \"\"\"Run the command-line script.\n\n Args:\n args (argparse.Namespace) : Arguments object\n \"\"\"\n\n if args.version:\n print(version)\n sys.exit(0)\n\n # At minimum metric, a and b must be set\n if None in [args.metric, args.a, args.b]:\n get_argument_parser().print_help()\n sys.exit(1)\n\n # Get the module to load from the metric provided\n mod = args.metric\n segments = mod.split('.')\n\n # If there is no domain, assume it to be generic\n if len(segments) == 1:\n segments.insert(0, 'generic')\n\n segments.insert(0, 'truth')\n\n # Load the module\n try:\n\n # Prepare the import string\n mod_string = '.'.join(segments[:-1])\n\n # Import the module and get the function\n mod = import_module(mod_string)\n metric = getattr(mod, segments[-1])\n\n except Exception:\n\n print('ERROR: Metric %s is not known to Truth' % args.metric)\n sys.exit(1)\n\n\n # Load the data and calculate the metric\n try:\n\n # Infer the type, otherwise attempt to read from stdin\n a = np.array([float(_a) for _a in args.a.split(',')])\n b = np.array([float(_b) for _b in args.b.split(',')])\n\n # Calculate the metric\n result = metric(a, b)\n\n # Do something with the result (args will write out if needed)\n print(result)\n\n except Exception:\n\n print('ERROR: Unable to verify, check inputs.')\n sys.exit(1)\n\n\n# def prepare_slice(slice_str):\n# \"\"\"Prepare slice object for cutting.\n#\n# Args:\n# slice_str (str) : A slice string\n#\n# Returns:\n# slice : Slice object\n# \"\"\"\n#\n# # Break up the slice\n# segments = slice_str.split(':')\n#\n# # No slices error, more than 3 error\n# # TODO: How does this error look?\n# # TODO: Make this work for named coordinates?\n#\n# if len(segments) == 2:\n#\n# start = None if segments[0] is 'start' else int(segments[0])\n# end = None if segments[0] is 'end' else int(segments[1])\n# step = None\n#\n# elif len(segments) == 3:\n# start = None if segments[0] is 'start' else int(segments[0])\n# end = None if segments[0] is 'end' else int(segments[1])\n# step = int(segments[2])\n#\n# # Return the slice argument\n# return slice(start, end, step)\n\n# def print_version():\n# \"\"\"Print the currently loaded version of Truth.\"\"\"\n# print(version)\n","sub_path":"truth/core/cli.py","file_name":"cli.py","file_ext":"py","file_size_in_byte":3944,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"630171490","text":"\"\"\"\nThis is module mainly focus on country level (national level)interaction\n\nCreated on 2016/12/01\nVersion: 1.0\n@author: Sheng Liu\nShengLiu Copyright 2016-2017\n\n\"\"\"\nimport sys\nfrom h1b_exploring.All_about_input import option_input\nfrom h1b_exploring.h1b_draw import *\nfrom h1b_exploring.h1b_data import *\nfrom h1b_exploring.exception_list import wrong_option_exception\n\n\ndef national_level (h1b_data):\n\t\n\tprint (\" \")\n\tprint (\"================================ H1b Visa Approve Rate Exploring =================================\")\n\tprint (\"\")\n\tprint (\" You are now at National Level, please choose ONE indicator you interested in \")\n\tprint (\" : Application Pool \")\n\tprint (\" : Approve Rate \")\n\tprint (\" : Average Wage \")\n\tprint (\" : Return to Location Menu \")\n\tprint (\" WARNING: For Year Input : Only 2010 ~ 2016 \") \n\tprint (\"\")\n\tprint (\"==================================================================================================\")\n\tFlag = True\n\n\twhile Flag:\n\t\ttry:\n\t\t\tkey = option_input()\n\t\t\tif key == 'a':\n\t\t\t\tyear = input('Please input the year you are interested in: ')\n\t\t\t\tif year in ['2010','2011','2012','2013','2014','2015','2016']:\n\t\t\t\t\tyear = int(year)\n\t\t\t\t\tapplication_pool = h1b_data.calc_application_pool('Country',year)\n\t\t\t\t\tplot_cloropleth_map(application_pool,'Application Pool','Pool Size',year)\n\t\t\t\t\tprint(\"The information you requested has been saved, please use browser to open it...\")\n\t\t\t\telif year == 'quit':\n\t\t\t\t\tsys.exit(1)\n\t\t\t\telse:\n\t\t\t\t\traise wrong_option_exception\n\t\t\tif key == 'b':\n\t\t\t\tyear = input('Please input the year you are interested in: ')\n\t\t\t\tif year in ['2010','2011','2012','2013','2014','2015','2016']:\n\t\t\t\t\tyear = int(year)\n\t\t\t\t\tAPPROVE_RATE_LIST_Country = h1b_data.calc_approve_rate('Country',year)\n\t\t\t\t\tplot_cloropleth_map(APPROVE_RATE_LIST_Country,'Approve Rate','approve rate (%)',year)\n\t\t\t\t\tprint(\"The information you requested has been saved, please use browser to open it...\")\n\t\t\t\telif year == 'quit':\n\t\t\t\t\tsys.exit(1)\n\t\t\t\telse:\n\t\t\t\t\traise wrong_option_exception\n\t\t\tif key == 'c':\n\t\t\t\tyear = input('Please input the year you are interested in: ')\n\t\t\t\tif year in ['2010','2011','2012','2013','2014','2015','2016']:\n\t\t\t\t\tAVERAGE_WAGE_LIST_Country = h1b_data.calc_average_wage('Country',int(year))\n\t\t\t\t\tplot_cloropleth_map(AVERAGE_WAGE_LIST_Country,'Average Wage','average wage ($)',int(year))\n\t\t\t\t\tprint(\"The information you requested has been saved, please use browser to open it...\")\n\t\t\t\telif year == 'quit':\n\t\t\t\t\tsys.exit(1)\n\t\t\t\telse:\n\t\t\t\t\traise wrong_option_exception\n\t\t\tif key == 'r':\n\t\t\t\tFlag = False\n\t\texcept wrong_option_exception:\n\t\t\tprint (\"Invalid option, please reselect an indicator you interested in.\")\n\n\n","sub_path":"sl5924/1007_project/h1b_exploring/Country_Level.py","file_name":"Country_Level.py","file_ext":"py","file_size_in_byte":3064,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"322293194","text":"import bpy\nimport sys, os, logging\n\nclass SEQUENCER_MovieAssembly(bpy.types.Panel):\n bl_label = \"Movie Assembly\"\n bl_space_type = \"SEQUENCE_EDITOR\"\n bl_region_type = \"UI\"\n bl_category = \"Movie Assembly\"\n \n def draw(self, context):\n layout = self.layout\n \n layout.prop(context.scene.movie_assembly, \"project_index\")\n\n\nclass SEQUENCER_StripVersion(bpy.types.Panel):\n bl_label = \"Version\"\n bl_space_type = \"SEQUENCE_EDITOR\"\n bl_region_type = \"UI\"\n bl_category = \"Movie Assembly\"\n \n def draw(self, context):\n layout = self.layout\n \n box = layout.box()\n row = box.row()\n row.label(\"Type\")\n \n\n\n","sub_path":"addons/movie_assembly/ui.py","file_name":"ui.py","file_ext":"py","file_size_in_byte":687,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"631429865","text":"\"\"\"\nbase form:\n - parse_args(['option','value'])\nother forms:\n For long options (options with names longer than a single character), \n the option and value can also be passed as a single command-line argument, using = to separate them:\n - parse_args(['--option=value'])\n For short options (options only one character long), \n the option and its value can be concatenated:\n - parse_args(['-optionvalue'])\n\nAbout dest:\n - dest allows a custom attribute name to be provided: (in our case \"integers\")\nAbout metavar:\n - metavar only changes the displayed name - the name of the attribute on the parse_args() object is still \n determined by the dest value.\nAbout const:\n - \nAbout nargs:\n N (an integer). \n - N arguments from the command line will be gathered together into a list. For example:\n '+'\n - Just like '*', all command-line args present are gathered into a list. \n Additionally, an error message will be generated if there wasn’t at least one command-line argument present.\n '*'\n -\n '?'\n - One argument will be consumed from the command line if possible, and produced as a single item. \n If no command-line argument is present, the value from default will be produced.\n\"\"\"\nimport argparse\n\nparser = argparse.ArgumentParser(description=\"Process some integers.\")\nparser.add_argument(\n \"integers\", metavar=\"N\", type=int, nargs=\"+\", help=\"an integer for the accumulator\"\n)\nparser.add_argument(\n \"--sum\",\n dest=\"accumulate\",\n action=\"store_const\",\n const=sum,\n default=max,\n help=\"sum the integers (default: find the max)\",\n)\n\nargs = parser.parse_args()\nprint(args)\nprint(args.accumulate(args.integers))\n","sub_path":"argparse/6_example.py","file_name":"6_example.py","file_ext":"py","file_size_in_byte":1721,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"68822557","text":"try:\n from Tkinter import *\n from ttk import *\nexcept ImportError: # Python 3\n from tkinter import *\n from tkinter.ttk import *\n\nimport sqlite3\n\nclass MainApplication(Frame):\n\n def __init__(self, parent):\n Frame.__init__(self, parent)\n self.std_window = Toplevel()\n self.std_window.title(\"Game History\")\n self.standard_table = standard_table(self.std_window)\n self.summary_table = summary_table(self.std_window)\n\n\nclass standard_table(Frame):\n def __init__(self, std_window):\n\n self.tv = Treeview(std_window)\n self.tv['columns'] = ('userName', 'time', 'userStatus', 'winner')\n self.tv.heading(\"#0\", text='Game Number', anchor='w')\n self.tv.column(\"#0\", anchor=\"w\")\n\n self.tv.heading('userName', text='Player Name')\n self.tv.column('userName', anchor='center', width=100)\n self.tv.heading('time', text='Time')\n self.tv.column('time', anchor='center', width=100)\n self.tv.heading('userStatus', text='Player Status')\n self.tv.column('userStatus', anchor='center', width=100)\n self.tv.heading('winner', text='Winner')\n self.tv.column('winner', anchor='center', width=100)\n\n self.tv.grid(sticky=(N, S, W, E))\n self.tv.bind(\"\", self.OnDoubleClick)\n\n try:\n conn = sqlite3.connect(\"statistics.db\")\n except:\n print(\"Can't connect to sqlite3 database...\")\n\n c = conn.cursor()\n c.execute(\"SELECT * FROM statistics ORDER BY id DESC\")\n std = c.fetchall()\n conn.close()\n\n for record in std:\n self.tv.insert('', 'end', text=record[0], values=(record[1], record[2], record[3], record[4]))\n\n\n def OnDoubleClick(self, event):\n self.record = self.tv.selection()\n self.game_number = self.tv.item(self.record, \"text\")\n self.child_window = child_window(self.game_number)\n\nclass child_window(Frame):\n def __init__(self, game_number):\n\n win2 = Toplevel()\n win2.title(\"Computer Settings\")\n\n self.tree = Treeview(win2)\n self.tree['columns'] = ('color', 'difficulty', 'sadism', 'status')\n self.tree.heading(\"#0\", text='Game Number', anchor='w')\n self.tree.column(\"#0\", anchor=\"w\")\n\n self.tree.heading('color', text='Computer Color')\n self.tree.column('color', anchor='center', width=100)\n self.tree.heading('difficulty', text='Difficulty')\n self.tree.column('difficulty', anchor='center', width=100)\n self.tree.heading('sadism', text='Sadism')\n self.tree.column('sadism', anchor='center', width=100)\n self.tree.heading('status', text='Computer Status')\n self.tree.column('status', anchor='center', width=100)\n\n self.tree.grid(sticky=(N, S, W, E))\n\n try:\n conn = sqlite3.connect(\"statistics.db\")\n except:\n print(\"Can't connect to sqlite3 database...\")\n\n c = conn.cursor()\n c.execute(\"SELECT * FROM computerSettings WHERE id = \" + str(game_number))\n computer = c.fetchall()\n conn.close()\n\n for record in computer:\n self.tree.insert('', 'end', text=record[0], values=(record[1], record[2], record[3], record[4]))\n\n\nclass summary_table(Frame):\n def __init__(self, std_window):\n\n self.tv2 = Treeview(std_window)\n\n self.tv2['columns'] = ('count')\n self.tv2.heading(\"#0\", text='Player Status', anchor='w')\n self.tv2.column(\"#0\", anchor=\"w\")\n\n self.tv2.heading('count', text='Count')\n self.tv2.column('count', anchor='center', width=100)\n\n self.tv2.grid(sticky=(N, S, W, E))\n\n try:\n conn = sqlite3.connect(\"statistics.db\")\n except:\n print(\"Can't connect to sqlite3 database...\")\n\n c = conn.cursor()\n\n c.execute(\"SELECT userStatus, COUNT(*) FROM statistics GROUP BY userStatus ORDER BY COUNT(*) DESC\")\n std = c.fetchall()\n conn.close()\n\n for record in std:\n self.tv2.insert('', 'end', text=record[0], values=(record[1]))\n\ndef main():\n root = Tk()\n root.resizable(width=False, height=False)\n MainApplication(root).grid()\n root.title(\"Game History\")\n root.mainloop()\n\nif __name__ == '__main__':\n main()","sub_path":"game_history.py","file_name":"game_history.py","file_ext":"py","file_size_in_byte":4274,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"248665099","text":"import csv\nhosts=[['workstation.local','192.168.0.1'],['fileserver.local','172.16.0.1']]\n\nwith open('hosts.csv','w') as file:\n writer=csv.writer(file)\n writer.writerow(hosts)\n\n\nimport os\nimport csv\n\n# Create a file with data in it\ndef create_file(filename):\n with open(filename, \"w\") as file:\n file.write(\"name,color,type\\n\")\n file.write(\"carnation,pink,annual\\n\")\n file.write(\"daffodil,yellow,perennial\\n\")\n file.write(\"iris,blue,perennial\\n\")\n file.write(\"poinsettia,red,perennial\\n\")\n file.write(\"sunflower,yellow,annual\\n\")\n\n# Read the file contents and format the information about each row\ndef contents_of_file(filename):\n return_string = \"\"\n\n # Call the function to create the file\n create_file(filename)\n\n # Open the file\n with open(filename,'r+') as file:\n # Read the rows of the file into a dictionary\n csv_reader=csv.reader(file)\n # Process each item of the dictionary\n for name,color,type in csv_reader:\n return_string += \"a {} {} is {}\\n\".format(color, name, type)\n return return_string\n\n#Call the function\nprint(contents_of_file(\"flowers.csv\"))","sub_path":"generating csv.py","file_name":"generating csv.py","file_ext":"py","file_size_in_byte":1106,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"321043558","text":"# The prime factors of 13195 are 5, 7, 13 and 29.\n# What is the largest prime factor of the number 600851475143?\n\nimport numpy as np\n\ndef gcd(a,b):\n while (b != 0):\n a,b = b, a%b\n return a\n\ndef pollard_rho(n):\n i = 1\n x = np.random.randint(0,min(n,2**31-1))\n y = x\n k = 2\n factors = []\n for i in range(int(pow(n,0.25))):\n x = (pow(x,2)-1) % n\n d = gcd(y-x,n)\n if (d != 1 and d != n and d not in factors):\n factors.append(d)\n if i == k:\n y = x\n k *= 2\n return factors\n\ndef is_prime(n):\n if n == 2:\n return True\n for i in range(2,int(np.sqrt(n))+1):\n if n % i == 0:\n return False\n return True\n\n\ndef find_prime_factors(n,n_iter=1000):\n factors = []\n for i in range(n_iter):\n x = pollard_rho(n)\n for j in x:\n if j not in factors:\n factors.append(j)\n return [i for i in factors if is_prime(i)]\n\nfind_prime_factors(600851475143) # => [71,839,1471,6857]","sub_path":"003_largest_prime_factor/03_Largest_prime_factor.py","file_name":"03_Largest_prime_factor.py","file_ext":"py","file_size_in_byte":1024,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"461708977","text":"\"\"\"\nS and T are strings composed of lowercase letters. In S, no letter occurs more than once.\n\nS was sorted in some custom order previously. We want to permute the characters of T so that they match the order that S was sorted. More specifically, if x occurs before y in S, then x should occur before y in the returned string.\n\nReturn any permutation of T (as a string) that satisfies this property.\n\nExample :\nInput: \nS = \"cba\"\nT = \"abcd\"\nOutput: \"cbad\"\nExplanation: \n\"a\", \"b\", \"c\" appear in S, so the order of \"a\", \"b\", \"c\" should be \"c\", \"b\", and \"a\". \nSince \"d\" does not appear in S, it can be at any position in T. \"dcba\", \"cdba\", \"cbda\" are also valid outputs.\n\"\"\"\n\nclass Solution:\n def customSortString(self, S: str, T: str) -> str:\n extra = []\n same = ''\n rel = ['' for i in range(len(S))]\n for i in T:\n if i in S:\n same+=i\n else:\n extra.append(i)\n \n temp = \"\".join(extra)\n for i in same:\n rel[S.index(i)]+=i\n return temp+''.join(rel)\n","sub_path":"Strings/Custom_Sort_String.py","file_name":"Custom_Sort_String.py","file_ext":"py","file_size_in_byte":1073,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"651353922","text":"from cassandra.cluster import Cluster\nimport os\nfrom timeit import default_timer as timer\nimport cPickle as pickle\n\ncluster = Cluster(['10.10.1.4'])\nsession = cluster.connect('cifar10')\n\n\n\nstart = timer()\ndict = {}\n\ni = 0\n\nrows = session.execute(\"SELECT * FROM blob\")\n\nfor row in rows:\n dict.update({row.id: [row.image, row.label]})\n\n\nend = timer()\n#print(dict)\nprint(end - start)\n","sub_path":"Cifar10/cassandra/blob_batch.py","file_name":"blob_batch.py","file_ext":"py","file_size_in_byte":384,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"371372848","text":"#d>98 and d<102\n\n\nimport math\n\nv=float(input(\"qual a velocidade? \"))\nteta=float(input(\"Quantos graus? \"))\ng=9.8\nrad=teta*math.pi/180\n\n\nd=((v**2)*math.sin(2*rad))/g\nprint(d)\n\nif d>=98 and d<=102:\n\tprint('Acertou!')\nelif d<98:\n\tprint ('Muito perto')\nelse:\n\tprint ('Muito longe')","sub_path":"backup/user_307/ch30_2019_03_22_13_18_25_779295.py","file_name":"ch30_2019_03_22_13_18_25_779295.py","file_ext":"py","file_size_in_byte":276,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"236435607","text":"import os\n\n\n# ----------------------------------------------------------------------------------------------------------------------\nclass Util:\n \"\"\"\n A helper class with miscellaneous functions that don;t belong somewhere else.\n \"\"\"\n # ------------------------------------------------------------------------------------------------------------------\n @staticmethod\n def write_two_phases(the_filename, the_data):\n \"\"\"\n Writes a file in two phase to the filesystem.\n\n First write the data to a temporary file (in the same directory) and than renames the temporary file. If the\n file already exists and its content is equal to the data that must be written no action is taken. This has the\n following advantages:\n * In case of some write error (e.g. disk full) the original file is kep in tact and no file with partially data\n is written.\n * Renaming a file is atomic. So, running processes will never read a partially written data.\n\n :param str the_filename: The name of the file were the data must be stored.\n :param str the_data: The data that must be written.\n \"\"\"\n write_flag = True\n if os.path.exists(the_filename):\n with open(the_filename, 'r') as file:\n old_data = file.read()\n if the_data == old_data:\n write_flag = False\n\n if write_flag:\n tmp_filename = the_filename + '.tmp'\n with open(tmp_filename, 'w+') as file:\n file.write(the_data)\n os.replace(tmp_filename, the_filename)\n print(\"Wrote: '%s'.\" % the_filename)\n\n# ----------------------------------------------------------------------------------------------------------------------\n","sub_path":"pystratum/Util.py","file_name":"Util.py","file_ext":"py","file_size_in_byte":1782,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"224476485","text":"import asyncio\n\nfrom python3_anticaptcha import AntiCaptchaControl\n\n\nANTICAPTCHA_KEY = \"\"\n# Пример метода, отправляющего жалобу на неправильно решённую капчу-изображение.\n# В качестве параметра, принимает ключ антикапчи и ID неправильно решённой капчи + тип капчи\n# Возвращает логические True(жалоба прошла)/False(ошибка при жалобе)\nresult = AntiCaptchaControl.AntiCaptchaControl(anticaptcha_key=ANTICAPTCHA_KEY).complaint_on_result(\n reported_id=-5, captcha_type=\"image\"\n)\nprint(result)\n# Пример метода, отправляющего жалобу на неправильно решённую ReCaptcha.\n# В качестве параметра, принимает ключ антикапчи и ID неправильно решённой ReCaptcha + тип капчи\n# Возвращает логические True(жалоба прошла)/False(ошибка при жалобе)\nresult = AntiCaptchaControl.AntiCaptchaControl(anticaptcha_key=ANTICAPTCHA_KEY).complaint_on_result(\n reported_id=-5, captcha_type=\"recaptcha\"\n)\nprint(result)\n# Пример метода, принимающего ключ аккаунта и возвращающего актуальный баланс\nresult = AntiCaptchaControl.AntiCaptchaControl(anticaptcha_key=ANTICAPTCHA_KEY).get_balance()\nprint(result)\n# Пример метода, выдающий информацию о загрузке очереди, в зависимости от ID очереди\n# В данном случае queue_id = 1, то есть получаем информацию по загрузке очереди ImageToText (язык английский)\nresult = AntiCaptchaControl.AntiCaptchaControl(anticaptcha_key=ANTICAPTCHA_KEY).get_queue_status(queue_id=1)\nprint(result)\n\n# Асинхронный метод работы\nasync def run():\n try:\n # io.IOBase\n resolved = await AntiCaptchaControl.aioAntiCaptchaControl(\n anticaptcha_key=ANTICAPTCHA_KEY\n ).get_balance()\n print(resolved)\n\n resolved = await AntiCaptchaControl.aioAntiCaptchaControl(\n anticaptcha_key=ANTICAPTCHA_KEY\n ).complaint_on_result(reported_id=-8, captcha_type=\"image\")\n print(resolved)\n\n resolved = await AntiCaptchaControl.aioAntiCaptchaControl(\n anticaptcha_key=ANTICAPTCHA_KEY\n ).complaint_on_result(reported_id=-8, captcha_type=\"recaptcha\")\n print(resolved)\n\n resolved = await AntiCaptchaControl.aioAntiCaptchaControl(\n anticaptcha_key=ANTICAPTCHA_KEY\n ).get_queue_status(queue_id=1)\n print(resolved)\n\n except Exception as err:\n print(err)\n\n\nif __name__ == \"__main__\":\n loop = asyncio.get_event_loop()\n loop.run_until_complete(run())\n loop.close()\n","sub_path":"anticaptcha_examples/anticaptcha_control_example.py","file_name":"anticaptcha_control_example.py","file_ext":"py","file_size_in_byte":2960,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"50371402","text":"import sys\r\nimport linecache\r\nimport json\r\n\r\ndef pretty_print(data):\r\n return '\\n'.join([line for line in parseString(\r\n data).toprettyxml(indent=' ' * 2).split('\\n') if line.strip()])\r\n\r\n\r\ndef PrintException():\r\n exc_type, exc_obj, tb = sys.exc_info()\r\n f = tb.tb_frame\r\n lineno = tb.tb_lineno\r\n filename = f.f_code.co_filename\r\n linecache.checkcache(filename)\r\n line = linecache.getline(filename, lineno, f.f_globals)\r\n print(\r\n f'EXCEPTION IN ({filename}, LINE {lineno} \"{line.strip()}\"): {exc_obj}')\r\n\r\n\r\ndef writejson(filename, data):\r\n with open(filename, \"w\") as f:\r\n json.dump(data, f, indent=4)\r\n return 0\r\n\r\n\r\ndef readjson(filename):\r\n with open(filename, \"r\") as f:\r\n data = json.load(f)\r\n return data\r\n","sub_path":"src/supportmanager.py","file_name":"supportmanager.py","file_ext":"py","file_size_in_byte":778,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"518413649","text":"from flask import request\n\n\n# import tools\nfrom functools import wraps\nfrom Application.helpers.response import Response\n\ndef validator(function):\n @wraps(function)\n def wrapper(*args, **kwargs):\n\n errors = {}\n\n if 'name' in request.values and request.values.get('name'):\n if len(request.values.get(\"name\").strip()) < 2:\n errors.update({'name': 'Minimum 2 character required!'})\n if len(request.values.get('name').strip()) > 20:\n errors.update({'name': 'Maximum 20 character required!'})\n else:\n errors.update({'name': 'Name is required!'})\n\n if 'room_name' in request.values and request.values.get('room_name'):\n if len(request.values.get('room_name').strip()) < 2:\n errors.update({'room_name': 'Minimum 2 character required!'})\n if len(request.values.get('room_name').strip()) > 20:\n errors.update({\"room_name\": 'Maximum 20 character required!'})\n else:\n errors.update({'room_name': 'Room name is required!'})\n\n if len(errors) > 0:\n return Response(errors=errors, status_code=422, message='Invalid input!').send()\n return function(*args, **kwargs)\n return wrapper\n","sub_path":"Application/validators/chat_room/create.py","file_name":"create.py","file_ext":"py","file_size_in_byte":1261,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"59419447","text":"import sys\nimport glob\nimport unittest\n\nsys.path.append('.')\n\nfrom src.prob3 import serveillance\n\nclass TestProblem3(unittest.TestCase):\n def test_serveillance(self):\n # テストデータを格納したファイルのリストを取得する\n test_file_list = glob.glob('test/data/prob3-*.txt')\n\n for test_file_path in test_file_list:\n # ファイルからテストデータを読み込む\n with open(test_file_path, 'r') as f:\n log_list, expected, clash_threshold, busy_threshold, busy_length = f.read().split('\\n\\n')\n log_list = log_list.split('\\n')\n expected = expected.split('\\n')\n clash_threshold = int(clash_threshold)\n busy_threshold = int(busy_threshold)\n busy_length = int(busy_length)\n\n # ログファイルの監視を実行する\n result = serveillance(log_list, clash_threshold, busy_threshold, busy_length)\n\n # 実行結果が期待するものになっているか確認する\n if expected == ['no_clash']:\n self.assertEqual([], result)\n else:\n self.assertEqual(expected, result)\n\nif __name__ == '__main__':\n unittest.main()","sub_path":"test/test_prob3.py","file_name":"test_prob3.py","file_ext":"py","file_size_in_byte":1132,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"266728847","text":"r\"\"\"\nUnit tests for the assumptions module.\n\"\"\"\n\nimport unittest\nfrom assumptions import INCORRECT_SPACING_REGEX\nfrom assumptions import UNMANAGEABLE_SPACING_REGEX\n\nclass IncorrectSpacingRegexTest(unittest.TestCase):\n\n def test_finds_incorrect_element(self):\n line = 'A|----1--2--3---|----456---'\n match = INCORRECT_SPACING_REGEX.match(line)\n self.assertIsNotNone(match)\n self.assertEqual(match.group('number_run'), '456')\n\n def test_does_not_recognize_correct_line(self):\n line = 'E|-----1---2---3---|----4---5---6---|'\n self.assertIsNone(INCORRECT_SPACING_REGEX.match(line))\n\n\nclass UnmanageableSpacingRegexTest(unittest.TestCase):\n\n def test_finds_incorrect_element(self):\n line = 'A|----1--2--3---|----456---'\n match = UNMANAGEABLE_SPACING_REGEX.match(line)\n self.assertIsNotNone(match)\n self.assertEqual(match.group('number_run'), '456')\n\n def test_does_not_recognize_correct_line_single_glyphs(self):\n line = 'E|-----1---2---3---|----4---5---6---|'\n self.assertIsNone(UNMANAGEABLE_SPACING_REGEX.match(line))\n\n def test_does_not_recognize_correct_line_even_glyphs(self):\n line = 'E|--101010--|'\n match = UNMANAGEABLE_SPACING_REGEX.match(line)\n self.assertIsNone(match)\n","sub_path":"pyngwie/util/assumptions_unit_tests.py","file_name":"assumptions_unit_tests.py","file_ext":"py","file_size_in_byte":1294,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"393499485","text":"from tomviz import utils\nimport numpy as np\nimport tomviz.operators\n\n\nclass CenterOfMassAlignmentOperator(tomviz.operators.CancelableOperator):\n\n def transform_scalars(self, dataset):\n \"\"\"Automatically align tilt images by center of mass method\"\"\"\n self.progress.maximum = 1\n\n tiltSeries = utils.get_array(dataset).astype(float)\n\n self.progress.maximum = tiltSeries.shape[2]\n step = 0\n\n for i in range(tiltSeries.shape[2]):\n if self.canceled:\n return\n self.progress.message = 'Processing tilt image No.%d/%d' % (\n i + 1, tiltSeries.shape[2])\n\n tiltSeries[:, :, i] = centerOfMassAlign(tiltSeries[:, :, i])\n\n step += 1\n self.progress.value = step\n\n utils.set_array(dataset, tiltSeries)\n\n\ndef centerOfMassAlign(image):\n \"\"\"Shift image so that the center of mass of is at origin\"\"\"\n (Nx, Ny) = image.shape\n # set up coordinate\n y = np.linspace(0, Ny - 1, Ny)\n x = np.linspace(0, Nx - 1, Nx)\n [X, Y] = np.meshgrid(y, x)\n\n imageCOM_x = int(np.sum(image * X) / np.sum(image))\n imageCOM_y = int(np.sum(image * Y) / np.sum(image))\n\n sx = -(imageCOM_x - Nx // 2)\n sy = -(imageCOM_y - Ny // 2)\n\n output = np.roll(image, sx, axis=1)\n output = np.roll(output, sy, axis=0)\n\n return output\n","sub_path":"tomviz/python/AutoCenterOfMassTiltImageAlignment.py","file_name":"AutoCenterOfMassTiltImageAlignment.py","file_ext":"py","file_size_in_byte":1351,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"314928485","text":"# Run this cell to import the packages you will need to unpack the dataset\nimport pandas as pd\nimport numpy as np\nfrom matplotlib import pyplot as plt\nimport scipy\nfrom io import BytesIO\nfrom PIL import Image\nimport random\nimport pickle\nimport os\nimport zipfile\nimport scipy.ndimage\n#from google.colab import files\nfrom skimage import feature\nimport tensorflow as tf\n\nos.chdir('Data') # Don't rerun these two lines!\n\n\ntrain_simple_labels = pd.read_csv('train_simple_labels.csv', header = None)\ntrain_complex_labels = pd.read_csv('train_complex_labels.csv', header=None)\neval_simple_labels = pd.read_csv('eval_simple_labels.csv', header=None)\neval_complex_labels = pd.read_csv('eval_complex_labels.csv', header=None)\n\ntrain_simple_labels = pd.concat([train_simple_labels, eval_simple_labels], axis=0, ignore_index = True)\ntrain_complex_labels = pd.concat([train_complex_labels, eval_complex_labels], axis=0, ignore_index = True)\nLabels = pd.DataFrame(list(range(5500)))\ntrain_simple_labels = pd.concat([train_simple_labels, Labels], axis=1)\ntrain_simple_labels.columns = ['Label', 'Unique_Index']\ntrain_complex_labels = pd.concat([train_complex_labels, Labels], axis=1)\ntrain_complex_labels.columns = ['Label', 'Unique_Index']\n\n\n\nzip_ref = zipfile.ZipFile('Mamm_Images_Train.zip.zip', 'r')\nzip_ref.extractall('Mamm_Images_Train')\nzip_ref.close()\n\nzip_ref = zipfile.ZipFile('Mamm_Images_Eval_zip.zip', 'r')\nzip_ref.extractall('Mamm_Images_Eval')\nzip_ref.close()\n\nzip_ref = zipfile.ZipFile('Mamm_Images_Test.zip.zip', 'r')\nzip_ref.extractall('Mamm_Images_Test')\nzip_ref.close() \n\n\ntrain_images = []\nfor i in range(5000):\n im = scipy.ndimage.imread('Mamm_Images_Train/Mamm_Images_Train/image' + str(i) + '.jpg')\n train_images.append(im)\n \nfor h in range(500):\n im = scipy.ndimage.imread('Mamm_Images_Eval/Mamm_Images_Eval/image' +str(h) + '.jpg')\n train_images.append(im)\n \ntrain_images_df = pd.DataFrame([train_images])\ntrain_images_df = train_images_df.transpose()\nLabels = pd.DataFrame(list(range(5500)))\ntrain_images_df = pd.concat([train_images_df, Labels], axis = 1)\ntrain_images_df.columns = ['Images', 'Unique Index']\n\n\ntest_images = []\nfor k in range(1500):\n im = scipy.ndimage.imread('Mamm_Images_Test/Mamm_Images_Test/image' + str(k) + '.jpg')\n test_images.append(im)\n \n \ntest_images_df = pd.DataFrame([test_images])\ntest_images_df = test_images_df.transpose()\nLabels = pd.DataFrame(list(range(5500, 7000)))\ntest_images_df = pd.concat([test_images_df, Labels], axis = 1)\ntest_images_df.columns = ['Images', 'Unique Index']\n\ntrain_labels = train_simple_labels['Label'].as_matrix()\ntrain_images = np.array(train_images)\ntrain_images = train_images.reshape((train_images.shape[0],train_images.shape[1],train_images.shape[2],1))\n\nfrom tensorflow.python.keras.layers import Dense, Conv1D, Conv2D, Flatten, Dropout, MaxPool1D, MaxPool2D\nfrom tensorflow.python.keras.models import Sequential\n\nmodel = Sequential()\n\nmodel.add(Conv2D(filters=16,kernel_size=(3,3),strides=(3,3),input_shape=(train_images.shape[1],train_images.shape[2],1),activation='relu'))\nmodel.add(MaxPool2D(pool_size=(3,3)))\nmodel.add(Conv2D(filters=32,kernel_size=(3,3),padding='same',activation='sigmoid'))\nmodel.add(Dropout(0.2))\nmodel.add(Conv2D(filters=64,kernel_size=(3,3),padding='same',activation='sigmoid'))\nmodel.add(Dropout(0.2))\nmodel.add(Flatten())\nmodel.add(Dense(64,activation='relu'))\nmodel.add(Dense(32,activation='sigmoid'))\nmodel.add(Dense(1,activation='softmax'))\n\nmodel.compile(optimizer='rmsprop',\n loss='binary_crossentropy',\n metrics=['accuracy'])\n\nmodel.fit(train_images,\n train_labels,\n batch_size=100,\n epochs=20,\n validation_split=0.2)\n","sub_path":"Challenge/challenge_test.py","file_name":"challenge_test.py","file_ext":"py","file_size_in_byte":3735,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"571907480","text":"from survey import AnonymousSurvey;\nimport unittest;\n\nclass survey_test(unittest.TestCase):\n\n def setUp(self):\n question = 'What language do you speak?';\n self.my_survey = AnonymousSurvey(question);\n self.responses = ['English' , 'Chineese' , 'Spain'];\n \n\n def test_store_single_response(self):\n self.my_survey.store_response('English');\n self.assertIn('English', self.my_survey.responses);\n \n def test_three_responses(self):\n for response in self.responses:\n self.my_survey.store_response(response);\n \n for response in self.responses:\n self.assertIn(response , self.my_survey.responses);\n\nunittest.main();\n","sub_path":"ericMetisPractice/chapter11/test_servey.py","file_name":"test_servey.py","file_ext":"py","file_size_in_byte":706,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"129267093","text":"from pytest import mark\nimport numpy as np\nimport pytest\n\n\n@mark.parametrize('size', [4, 20, 100])\ndef test_random_transition(size):\n from src.models.simulation import random_transition\n\n np.random.seed(size ** 2)\n\n bias = np.random.randint(9)\n T = random_transition(size, bias)\n\n assert np.all((0 <= T) & (T <= 1)), \"the values are not between 0 and 1\"\n assert np.all(np.isclose(T.diagonal(), T.max(0))), \\\n \"staying is the largest probability\"\n assert np.all(np.isclose(T.sum(1), np.ones(size))), \\\n \"the columns don't sum to one\"\n\n\n@mark.parametrize('nodes', [10, 200])\n@mark.parametrize('path_length', [3, 100])\ndef test_random_path(nodes, path_length):\n from src.models.simulation import random_path\n\n locations, times = random_path(nodes, path_length, 20, 4, 42)\n assert (len(locations), len(times)) == (path_length, path_length)\n\n\n@mark.parametrize('seq, first, expected_node', [\n ([1], True, 1),\n ([1], False, 1),\n ([1, 2], False, 2),\n ([1, 1, 1, 1], True, 1),\n ([1, 1, 2, 2], True, 1),\n ([1, 1, 2, 2], False, 2),\n ([1, 2, 1, 2], False, 2),\n ([1, 2, 1, 2], True, 1),\n ([1, 1, 1, 3, 3, 2, 2, 2], True, 1),\n ([1, 1, 1, 3, 3, 2, 2, 2], False, 2)\n])\ndef test_longest_sequences(seq, first, expected_node):\n from src.models.movement import longest_sequence\n assert longest_sequence(seq, first) == expected_node\n\n\n@mark.parametrize('window, exp_partition', [\n ((0, 2, 4), ([2, 0], [5, 1, 5])),\n ((0, 3, 5), ([2, 0, 5, 1, 5], []))\n])\ndef test_split_sequence(window, exp_partition):\n from src.models.simulation import random_path\n from src.models.movement import split_sequences\n\n locations, times = random_path(6, 5, random_state=90)\n # generates this [2, 0, 5, 1, 5], [0, 0, 2, 2, 2]\n seq1, seq2 = split_sequences(locations, times, window)\n assert seq1 == exp_partition[0] and seq2 == exp_partition[1]\n\n\n@mark.parametrize('window, expected_move', [\n ((0, 3, 7), (1, 2)),\n ((0, 4, 8), (1, 2)),\n ((0, 1, 8), (2, 1)),\n ((0, 6, 8), None)\n])\ndef test_move(window, expected_move):\n from src.models.movement import longest_seq_move, MoveNotPossible\n\n locations = [2, 2, 1, 1, 3, 2, 2, 3]\n times = [0, 0, 2, 2, 2, 3, 5, 5]\n\n if expected_move is None:\n with pytest.raises(MoveNotPossible):\n longest_seq_move(locations, times, window)\n else:\n result = longest_seq_move(locations, times, window)\n assert result == expected_move\n","sub_path":"tests/test_models.py","file_name":"test_models.py","file_ext":"py","file_size_in_byte":2481,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"76568564","text":"#!/usr/bin/env python\nimport socket\nimport src\nimport select\nimport threading\n\nSOCKET_LIST = []\n\n\ndef broadcast(server_socket, sock, message):\n print('Message: ' + message)\n for socket in SOCKET_LIST:\n if socket != server_socket and socket != sock:\n print('s != server_socket and s != sock')\n try:\n print('Sending...')\n socket.send(message)\n except:\n print('I\\'m in except')\n socket.close()\n if socket in SOCKET_LIST:\n SOCKET_LIST.remove(socket)\n else:\n print('Address: ' + str(socket.getsockname()))\n\n\ndef server_exec(server_sock):\n print('Server started')\n SOCKET_LIST.append(server_sock)\n while True:\n ready_to_read, ready_to_write, in_error = select.select(SOCKET_LIST, [], [], 0)\n for sock in ready_to_read:\n if sock == server_sock:\n client_sock, addr = server_sock.accept()\n SOCKET_LIST.append(client_sock)\n broadcast(server_sock, client_sock, 'Client ({}) connected'.format(addr))\n else:\n try:\n data = sock.recv(1024).strip()\n if data:\n mes = '[{}]: {}'.format(str(sock.getpeername()), data.decode())\n\n if data.decode() == src.__cmd_stop__:\n server_stop(server_sock)\n return\n if data.decode() == src.__cmd_reboot__:\n server_reboot(server_sock)\n return\n if data.decode() == 'Hello':\n mes += ' world'\n if data.decode() == src.__cmd_ping__:\n mes += ' Pong'\n\n broadcast(server_sock, sock, mes)\n\n else:\n if sock in SOCKET_LIST:\n SOCKET_LIST.remove(sock)\n broadcast(server_sock, sock, 'Client {} is offline'.format(addr))\n except:\n broadcast(server_sock, sock, 'Client {} is offline'.format(addr))\n continue\n\n\ndef server_cmd(server_sock):\n print('Users: ' + str(len(SOCKET_LIST)))\n cmd = input()\n if cmd == src.__cmd_stop__:\n server_stop(server_sock)\n if cmd == src.__cmd_reboot__:\n server_reboot(server_sock)\n if cmd == src.__cmd_disconnected_all__:\n server_disconnected_all(server_sock)\n\n\ndef server_stop(server_sock):\n print('Stopping...')\n server_disconnected_all(server_sock)\n server_sock.close()\n # SOCKET_LIST.remove(server_sock)\n\n\ndef server_disconnected_all(server_sock):\n print('Disconnecting...')\n for s in SOCKET_LIST:\n if s != server_sock:\n print('disconnect ' + str(s.getsockname()[0]))\n s.close()\n SOCKET_LIST.remove(s)\n\n\ndef server_reboot(server_sock):\n print('Reboot')\n server_stop(server_sock)\n server_sock = server_start()\n\n\ndef server_start():\n print('Starting server...')\n server_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n server_sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n server_sock.bind((src.__ip__, src.__port__))\n server_sock.listen(5)\n\n server_thread = threading.Thread(target=server_exec, args=(server_sock,))\n server_thread.daemon = True\n server_thread.start()\n\n return server_sock\n\n\ndef main():\n server_sock = server_start()\n\n while True:\n print('Thread count: ' + str(threading.activeCount()))\n server_cmd(server_sock)\n\n\nif __name__ == \"__main__\":\n try:\n main()\n except KeyboardInterrupt:\n pass\n","sub_path":"src/core.py","file_name":"core.py","file_ext":"py","file_size_in_byte":3779,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"450146842","text":"\n\nimport numpy as np\nfrom numpy.random import uniform\n\nfrom astropy.io import ascii\n\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.basemap import Basemap\n\n\nm = Basemap(projection='hammer', lon_0=0, resolution='c')\n\n\npath = '/cos_pc19a_npr/data/WISE/W4/WISE_W4_W4SNRge3_W4MPROlt4.0_nohdr.tbl'\ncols = ['designation', 'ra', 'dec', 'sigra', 'sigdec', 'w1mpro', 'w1sigmpro', 'w1snr', 'w2mpro', 'w2sigmpro', 'w2snr', 'w3mpro', 'w3sigmpro', 'w3snr', 'w4mpro', 'w4sigmpro', 'w4snr', 'w4rchi2']\ntbl = ascii.read(path)\n\nra = tbl['ra']\ndec = tbl['dec']\n\n\"\"\"\nIn [11]: ra.m\nra.max ra.mean ra.meta ra.min ra.more \n\nIn [11]: ra.min\nOut[11]: \n\nIn [12]: print(ra.min)\n\n\nIn [13]: print(ra.min())\n0.0019758\n\"\"\"\n\n\nx = ra\ny = dec\n\nxmin = x.min()\nxmax = x.max()\nymin = y.min()\nymax = y.max()\n\nplt.title(\"376857 points with WISE W4<4.0 mag\")\nplt.subplots_adjust(hspace=0.5)\n\nplt.subplot(121)\nplt.hexbin(x, y, cmap=plt.cm.YlOrRd_r)\nplt.axis([xmin, xmax, ymin, ymax])\nplt.title(\"Hexagon binning\")\ncb = plt.colorbar()\ncb.set_label('counts')\n\nplt.subplot(122)\nplt.hexbin(x, y, bins='log', cmap=plt.cm.YlOrRd_r)\nplt.axis([xmin, xmax, ymin, ymax])\ncb = plt.colorbar()\ncb.set_label('log10(N)')\n\n\n#plt.show()\n#plt.savefig('hexbin_forWISE_temp.png')\n\nfig = matplotlib.pyplot.gcf()\nfig.set_size_inches(18.5, 10.5)\nfig.savefig('hexbin_forWISE_temp.png', dpi=100)\n\n\n\n## Now trying for the Hammer projection...\n\n# draw parallels and meridians.\nm.drawparallels(np.arange(-90.,120.,30.))\nm.drawmeridians(np.arange(0.,420.,60.))\n\nx, y = m(ra, dec)\ncrap = m.scatter(x,y, 10, marker='o', color='k')\n\n\nplt.title(\"Hammer Projection\")\nplt.show()\n","sub_path":"plots/sky_distribution/Berghea/hexbin_forWISE_hammer.py","file_name":"hexbin_forWISE_hammer.py","file_ext":"py","file_size_in_byte":1687,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"517530398","text":"class LAStockCheckup(object):\n __slots__ = [\n \"compRating\",\n \"industryGroupRank\",\n \"epsRating\",\n \"epsPctChgLastQtr\",\n \"epsPctChgLast3QtrsAvg\",\n \"numQtrsOfEpsAcceleration\",\n \"epsEstPctChgCurrentQtr\",\n #--> Estimate Revisions -> missing -> not able to get from MS data\n \"lastQtrPctEarningsSurprise\",\n \"epsPctChg3Years\",\n \"consecuiveYearsOfAnnualEpsGrowth\",\n \"epsEstPctChgForCurrentYear\",\n \"smrRating\",\n \"salesPctChgLastQtr\",\n \"salesGrowth3Years\",\n \"annualPreTaxMargin\",\n \"annualROE\",\n \"debtEquityRatio\",\n \"price\",\n \"rsRating\",\n \"pricePctOff52WeekHigh\",\n \"priceVs50DayMA\",\n \"volAvg50Day\",\n \"marketCap\",\n \"adRating\",\n \"upDownVolume\",\n \"pctChgInFundsOwnership\",\n \"qtrsOfIncreasingFundOwnership\"\n ]\n\n\nclass PetalumaStockCheckup:\n\n def __init__(self):\n pass\n\n def __validateMembers__(self):\n validFields = set([\n \"compRating\",\n \"epsRating\",\n \"epsPctChgLastQtr\",\n \"epsPctChg3Years\",\n \"salesPctChgLastQtr\",\n \"annualROE\",\n \"annualPreTaxMargin\",\n \"rsRating\",\n \"adRating\",\n \"upDownVolume\",\n \"dollarVolAvg50Day\",\n \"laStockCheckupGrade\",\n \"fromIbd50SlIpol\",\n \"percentDemand\"\n ])\n attributes = [a for a in dir(self) if not a.startswith('__')]\n for attribute in attributes:\n if attribute in validFields:\n pass\n else:\n raise Exception(\"Unknown field: {0} found in PetalumaStockCheckup.\".format(attribute))\n # end def\n# end class\n","sub_path":"mysite/web/typehelp.py","file_name":"typehelp.py","file_ext":"py","file_size_in_byte":1764,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"166340809","text":"# -*- coding: utf-8 -*-\n##############################################################################\n#\n# Elneo\n# Copyright (C) 2011-2015 Elneo (Technofluid SA) ().\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU Affero General Public License as\n# published by the Free Software Foundation, either version 3 of the\n# License, or (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU Affero General Public License for more details.\n#\n# You should have received a copy of the GNU Affero General Public License\n# along with this program. If not, see .\n#\n##############################################################################\n\nfrom openerp import models, fields, api, _\nimport openerp.addons.decimal_precision as dp\n\nclass StockReturnPickingLine(models.TransientModel):\n _inherit = 'stock.return.picking.line'\n\n qty_already_returned = fields.Float(string=\"Quantity already returned\",digits_compute=dp.get_precision('Product Unit of Measure'), readonly=True)\n\nclass StockReturnPicking(models.TransientModel):\n _inherit = 'stock.return.picking'\n \n already_returned = fields.Boolean(string='Already Returned',help='Technical field to help to know if products are already returned')\n \n @api.model\n def default_get(self,fields):\n res = super(StockReturnPicking,self).default_get(fields=fields)\n\n result1=[]\n pick = self.env['stock.picking'].browse(self.env.context.get('active_ids',False))\n \n if pick:\n \n already=False\n for move in pick.move_lines:\n qty = 0\n for m in move.returned_moves:\n qty = qty + m.product_uom_qty\n if qty > 0 :\n already = True\n \n result1.append({'qty_already_returned': qty, 'move_id': move.id})\n\n if len(result1) > 0:\n res1=[]\n if 'product_return_moves' in fields:\n for product_return_move in res['product_return_moves']:\n for result in result1:\n if result['move_id'] == product_return_move['move_id']:\n product_return_move['qty_already_returned'] = result['qty_already_returned']\n \n res1.append(product_return_move)\n \n res.update({'product_return_moves' : res1,'already_returned':already}) \n \n return res\n \n \n @api.multi\n def _create_returns(self): \n self.ensure_one()\n \n return_valid_auto = self.env['ir.config_parameter'].get_param('stock_return_picking_advanced.return_valid_auto',False)\n\n if return_valid_auto == 'True':\n new_picking_id, pick_type_id = super(StockReturnPicking,self.with_context(advanced_picking=True))._create_returns()\n picking = self.env['stock.picking'].browse(new_picking_id)\n picking_type = self.env['stock.picking.type'].browse(pick_type_id)\n \n #set good location_id, location_dest_id to new_move according to new picking_type\n for move in picking.move_lines:\n if picking_type.default_location_src_id:\n move.location_id = picking_type.default_location_src_id.id\n if picking_type.default_location_dest_id:\n move.location_dest_id = picking_type.default_location_dest_id.id\n \n picking.force_assign()\n picking.action_done()\n else:\n new_picking_id, pick_type_id = super(StockReturnPicking,self.with_context(advanced_picking=True))._create_returns()\n \n return new_picking_id, pick_type_id\n \n @api.multi\n def create_returns(self):\n res = {}\n self.ensure_one()\n \n return_create_invoice = self.env['ir.config_parameter'].get_param('stock_return_picking_advanced.return_create_invoice',False)\n \n if self.invoice_state == '2binvoiced' and return_create_invoice == \"True\":\n picking_id, pick_type_id = self._create_returns()\n wizard = self.env['stock.invoice.onshipping'].with_context(active_ids=[picking_id]).create({})\n invoice_id = wizard.create_invoice()\n if (isinstance(invoice_id,list)) and len(invoice_id) > 0:\n invoice_id = invoice_id[0]\n \n return {\n 'type': 'ir.actions.act_window',\n 'name': _('Invoice'),\n 'res_model': 'account.invoice',\n 'res_id': invoice_id, #If you want to go on perticular record then you can use res_id \n 'view_type': 'form',\n 'view_mode': 'form',\n 'target': 'self',\n 'nodestroy': True,\n }\n\n return super(StockReturnPicking,self).create_returns()\n\n# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:\n","sub_path":"stock_return_picking_advanced/wizard/stock_return_picking_advanced_wizard.py","file_name":"stock_return_picking_advanced_wizard.py","file_ext":"py","file_size_in_byte":5289,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"274380091","text":"import os\n\nfrom twisted.python.failure import Failure\nfrom scrapy.exceptions import NotConfigured\nfrom scrapy.dupefilters import RFPDupeFilter\n\n\n_middleware = None\n\n\nclass Dupefiltered(RuntimeError):\n def __init__(self, request):\n self.request = request\n\n\nclass ErrbackDupefilter(RFPDupeFilter):\n def request_seen(self, request):\n fp = self.request_fingerprint(request)\n if fp in self.fingerprints:\n if _middleware and request.errback:\n _middleware.queues.append(\n request.errback(Failure(Dupefiltered(request)))\n )\n return True\n self.fingerprints.add(fp)\n if self.file:\n self.file.write(fp + os.linesep)\n\n\nclass ErrbackDupefilterMiddleware(object):\n @classmethod\n def from_crawler(cls, crawler):\n if not crawler.settings.getbool('ERRBACK_DUPEFILTER_ENABLED'):\n raise NotConfigured\n return cls(crawler)\n\n def __init__(self, crawler):\n global _middleware\n _middleware = self\n self.queues = []\n\n def process_spider_output(self, response, result, spider):\n for x in result:\n yield x\n queues, self.queues = self.queues, []\n for queue in queues:\n for x in queue:\n yield x\n","sub_path":"errbackdupefilter.py","file_name":"errbackdupefilter.py","file_ext":"py","file_size_in_byte":1306,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"71592021","text":"def binarySearch(mylist, l, r, val):\n\n # if zero length, don't bother\n if len(mylist) == 0: return False\n\n # while l <= r, iterate\n while l <= r:\n mid = l + (r - l) // 2\n print(\"l = \" + str(l) + \", r = \" + str(r) + \", mid = \" + str(mid))\n # if mid value matches, return True\n if (mylist[mid] == val): return True\n elif (mylist[mid] < val): l = mid + 1\n else: r = mid - 1\n\n # return False, after recursing\n return False\n\n\n#print(binarySearch([0, 4, 5, 7, 8, 9, 10, 12], 0, 7, 13))\n#print(binarySearch([], 0, 0, 13))\n\n\ndef bubbleSort(myList):\n\n # walk through list\n for i in range(len(myList)):\n # look at i and i+1 element, swap\n idx = 0\n activeLen = len(myList) - 1\n while idx < activeLen:\n if myList[idx] > myList[idx + 1]:\n temp = myList[idx]\n myList[idx] = myList[idx + 1]\n myList[idx + 1] = temp\n idx += 1\n print(myList)\n\n\nbubbleSort([1, 4, 2, 10, 2, 8, 9, 5])","sub_path":"final_Practise.py","file_name":"final_Practise.py","file_ext":"py","file_size_in_byte":1032,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"89496218","text":"from setuptools import setup, Extension\nimport platform\n\nversion = '0.0.1'\n\nsetup(name='rnr',\n zip_safe=True,\n version=version,\n description='RNR.',\n long_description='RNR.',\n url='https://github.com/rstager/rnr',\n author='rkstager',\n install_requires=[\n ],\n author_email='rkstager@gmail.com',\n classifiers=[\n 'Development Status :: 5 - Production/Stable',\n 'Environment :: Console',\n 'Intended Audience :: Science/Research',\n 'License :: OSI Approved :: Apache Software License',\n 'Operating System :: OS Independent',\n 'Programming Language :: Python :: 3.5',\n 'Topic :: Scientific/Engineering',\n ],\n license='apache',\n packages=[\n 'rnr'\n ],\n ext_modules=[])\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":808,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"455176911","text":"from typing import ClassVar, cast\n\nfrom cuenca_validations.types import EntryType, RelatedTransaction\nfrom pydantic.dataclasses import dataclass\n\nfrom cuenca import resources\n\nfrom .base import Queryable, Retrievable\nfrom .resources import retrieve_uri\n\n\n@dataclass\nclass BalanceEntry(Retrievable, Queryable):\n _resource: ClassVar = 'balance_entries'\n\n amount: int # negative in the case of a debit\n descriptor: str\n name: str\n rolling_balance: int\n type: EntryType\n related_transaction_uri: RelatedTransaction\n\n @property # type: ignore\n def related_transaction(self):\n rt = self.related_transaction_uri\n resource = getattr(resources, rt.get_model())\n return cast(resource, retrieve_uri(rt)) if resource else None\n","sub_path":"cuenca/resources/balance_entries.py","file_name":"balance_entries.py","file_ext":"py","file_size_in_byte":765,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"311520508","text":"import pandas as pd\nimport math\nimport quandl\nimport numpy as np\nfrom sklearn import preprocessing, svm, model_selection\nfrom sklearn.linear_model import LinearRegression\nimport sklearn.model_selection\n\n\ndf = quandl.get('WIKI/GOOGL')\ndf = df[['Adj. Open','Adj. High','Adj. Low','Adj. Close','Adj. Volume']]\ndf['HL_PCT'] = (df['Adj. High'] - df['Adj. Close']) / df['Adj. Open'] * 100.0\ndf['PCT_Change'] = (df['Adj. Close'] - df['Adj. Open']) / df['Adj. Open'] * 100.0\n\ndf = df[['Adj. Close', 'HL_PCT','PCT_Change','Adj. Volume']] #features\n\nforecast_col = 'Adj. Close'\ndf.fillna('-99999',inplace=True)\n\nforecast_out = int(math.ceil(0.01*len(df))) #1% shift of data\n\ndf['Label'] = df[forecast_col].shift(-forecast_out)\ndf.dropna(inplace=True)\n\n# print(df.head())\n\nX = np.array(df.drop(['Label'],1)) #Features\nY = np.array(df['Label'])\nX = preprocessing.scale(X)\nY = np.array(df['Label'])\n\n\n\nX_train, X_test, Y_train, Y_test= model_selection.train_test_split(X,Y, test_size=0.2)\nclf = LinearRegression(n_jobs=-1)\n# clf = svm.SVR(kernel='poly')\nclf.fit(X_train,Y_train)\naccuracy = clf.score(X_test,Y_test)\n\n\nprint(accuracy)\n\n#Linear regression is squared error\n#n_jobs gives multithreading capabilities\n#SVM has kernals\n","sub_path":"regression_training_testing.py","file_name":"regression_training_testing.py","file_ext":"py","file_size_in_byte":1217,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"563273195","text":"import unittest\nfrom qunetsim.components.host import Host\nfrom qunetsim.components.network import Network\n\nfrom qunetsim.backends import EQSNBackend\nfrom qunetsim.backends import CQCBackend\n\n\n# @unittest.skip('')\nclass TestBackend(unittest.TestCase):\n backends = []\n\n @classmethod\n def setUpClass(cls):\n TestBackend.backends.append(EQSNBackend)\n TestBackend.backends.append(CQCBackend)\n # TestBackend.backends.append(projectQ)\n\n @classmethod\n def tearDownClass(cls):\n pass\n\n @unittest.skip('')\n def test_epr_generation(self):\n for b in TestBackend.backends:\n backend = b()\n network = Network.get_instance()\n network.start([\"Alice\", \"Bob\"], backend)\n alice = Host('Alice', backend)\n bob = Host('Bob', backend)\n alice.start()\n bob.start()\n network.add_host(alice)\n network.add_host(bob)\n\n # Test multiple times to eliminate probabilistic effects\n for _ in range(5):\n q1 = backend.create_EPR(alice.host_id, bob.host_id)\n q2 = backend.receive_epr(\n bob.host_id, alice.host_id, q_id=q1.id)\n assert q1.id == q2.id\n assert backend.measure(q1, False) == backend.measure(q2, False)\n\n network.stop(True)\n\n @unittest.skip('')\n def test_multiple_backends(self):\n for b in TestBackend.backends:\n backend1 = b()\n backend2 = b()\n network = Network.get_instance()\n network.start([\"Alice\", \"Bob\"], backend1)\n _ = Host('Alice', backend2)\n _ = Host('Bob', backend1)\n assert str(backend1._hosts) == str(backend2._hosts)\n network.stop(True)\n\n @unittest.skip('')\n def test_adding_hosts_to_backend(self):\n for b in TestBackend.backends:\n backend = b()\n network = Network.get_instance()\n network.start([\"Alice\"], backend)\n alice = Host('Alice', backend)\n alice.start()\n\n network.add_host(alice)\n network.stop(True)\n","sub_path":"integration_tests/test_backend.py","file_name":"test_backend.py","file_ext":"py","file_size_in_byte":2149,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"512917613","text":"import glob\nimport json\nimport logging\nimport os\nimport os.path\nimport re\nimport sys\nimport time\n\nimport requests\n\n\ndef get_size(file_dir):\n try:\n # we should only expect one file, if no, something is wrong\n file_name = glob.glob(os.path.join(file_dir, \"*\"))[0]\n return os.stat(file_name).st_size\n except:\n logging.exception(f\"error getting file from: {file_dir}\")\n return 0\n\n\ndef build_message(size):\n pkg_type, py_ver, cu_ver, *_ = os.environ.get(\"BUILD_ENVIRONMENT\", \"\").split() + [\n None,\n None,\n None,\n ]\n os_name = os.uname()[0].lower()\n if os_name == \"darwin\":\n os_name = \"macos\"\n return {\n \"normal\": {\n \"os\": os_name,\n \"pkg_type\": pkg_type,\n \"py_ver\": py_ver,\n \"cu_ver\": cu_ver,\n \"pr\": os.environ.get(\"CIRCLE_PR_NUMBER\"),\n \"build_num\": os.environ.get(\"CIRCLE_BUILD_NUM\"),\n \"sha1\": os.environ.get(\"CIRCLE_SHA1\"),\n \"branch\": os.environ.get(\"CIRCLE_BRANCH\"),\n },\n \"int\": {\n \"time\": int(time.time()),\n \"size\": size,\n \"commit_time\": int(os.environ.get(\"COMMIT_TIME\", \"0\")),\n },\n }\n\n\ndef send_message(message):\n access_token = os.environ.get(\"SCRIBE_GRAPHQL_ACCESS_TOKEN\")\n if not access_token:\n raise ValueError(\"Can't find access token from environment variable\")\n url = \"https://graph.facebook.com/scribe_logs\"\n r = requests.post(\n url,\n data={\n \"access_token\": access_token,\n \"logs\": json.dumps(\n [\n {\n \"category\": \"perfpipe_pytorch_binary_size\",\n \"message\": json.dumps(message),\n \"line_escape\": False,\n }\n ]\n ),\n },\n )\n print(r.text)\n r.raise_for_status()\n\n\nif __name__ == \"__main__\":\n file_dir = os.environ.get(\n \"PYTORCH_FINAL_PACKAGE_DIR\", \"/home/circleci/project/final_pkgs\"\n )\n if len(sys.argv) == 2:\n file_dir = sys.argv[1]\n print(\"checking dir: \" + file_dir)\n size = get_size(file_dir)\n if size != 0:\n try:\n send_message(build_message(size))\n except:\n logging.exception(\"can't send message\")\n","sub_path":".circleci/scripts/upload_binary_size_to_scuba.py","file_name":"upload_binary_size_to_scuba.py","file_ext":"py","file_size_in_byte":2329,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"418911060","text":"import sys\nimport tkinter as tk\n\n\nclass App(tk.Frame):\n def __init__(self, parent, title):\n tk.Frame.__init__(self, parent)\n self.npoints = 100\n self.Line1 = [0 for x in range(self.npoints)]\n self.Line2 = [0 for x in range(self.npoints)]\n self.Line3 = [0 for x in range(self.npoints)]\n parent.wm_title(title)\n parent.wm_geometry(\"800x400\")\n self.canvas = tk.Canvas(self, background=\"white\")\n self.img = tk.PhotoImage(file=\"bg.png\")\n self.canvas.create_image(0, 0, anchor=tk.NW, image=self.img)\n self.canvas.bind(\"\", self.on_resize)\n self.canvas.create_line((0, 0, 0, 0), tag='X', fill='darkblue', width=3)\n self.canvas.create_line((0, 0, 0, 0), tag='Y', fill='darkred', width=3)\n self.canvas.create_line((0, 0, 0, 0), tag='Z', fill='darkgreen', width=3)\n self.canvas.grid(sticky=\"news\")\n self.grid_rowconfigure(0, weight=1)\n self.grid_columnconfigure(0, weight=1)\n self.grid(sticky=\"news\")\n parent.grid_rowconfigure(0, weight=1)\n parent.grid_columnconfigure(0, weight=1)\n\n def on_resize(self, event):\n self.replot()\n\n def read_file(self):\n with open('test.txt', 'r') as f:\n try:\n data = [int(x) for x in f.readline().split(' ')]\n #print(data)\n x, y, z = data[0], data[1], data[2]\n self.append_values(x, y, z)\n self.after_idle(self.replot)\n except Exception as e:\n print(e)\n self.after(1000, self.read_file)\n\n def append_values(self, x, y, z):\n \"\"\"\n Update the cached data lists with new sensor values.\n \"\"\"\n self.Line1.append(float(x))\n self.Line1 = self.Line1[-1 * self.npoints:]\n self.Line2.append(float(y))\n self.Line2 = self.Line2[-1 * self.npoints:]\n self.Line3.append(float(z))\n self.Line3 = self.Line3[-1 * self.npoints:]\n return\n\n def replot(self):\n \"\"\"\n Update the canvas graph lines from the cached data lists.\n The lines are scaled to match the canvas size as the window may\n be resized by the user.\n \"\"\"\n w = self.winfo_width()\n h = self.winfo_height()\n max_X = max(self.Line1) + 1e-5\n max_Y = max(self.Line2) + 1e-5\n max_Z = max(self.Line3) + 1e-5\n max_all = max(max_X, max_Y, max_Z)\n coordsX, coordsY, coordsZ = [], [], []\n for n in range(0, self.npoints):\n x = (w * n) / self.npoints\n coordsX.append(x)\n coordsX.append(h - ((h * (self.Line1[n])) / max_all))\n coordsY.append(x)\n coordsY.append(h - ((h * (self.Line2[n])) / max_all))\n coordsZ.append(x)\n coordsZ.append(h - ((h * (self.Line3[n])) / max_all))\n self.canvas.coords('X', *coordsX)\n self.canvas.coords('Y', *coordsY)\n self.canvas.coords('Z', *coordsZ)\n\n\ndef main():\n root = tk.Tk()\n app = App(root, \"Test\")\n app.read_file()\n app.mainloop()\n return 0\n\n\nif __name__ == '__main__':\n sys.exit(main())\n","sub_path":"realtime_plot_from_file.py","file_name":"realtime_plot_from_file.py","file_ext":"py","file_size_in_byte":3151,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"48444456","text":"from django.urls import path\n\nfrom . import views\n\napp_name = 'books'\nurlpatterns = [\n path('', views.IndexView.as_view(), name='index'),\n path('/', views.detail, name='detail'),\n path('/edit', views.edit, name='edit'),\n path('/update', views.update_book, name='update'),\n path('add_book', views.add_book, name='add_book'),\n path('add_bulk', views.add_bulk, name='add_bulk'),\n\n]\n","sub_path":"bookclub/books/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":421,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"488258816","text":"from scapy.all import rdpcap\nfrom scapy.all import *\nfrom scapy.utils import *\n\npkts_list = rdpcap('/home/pythontools/Downloads/file.pcap')\n#This shows the number of packets in the file\nlenpkrt = len(pkts_list)\n#print(lenpkrt)\n\n\n#This is an example of reading a packet\n\n#pkts_list[0].show()\n\n#This is how you access the parameters\n#srcip = pkts_list[0]['IP'].src\n#print(srcip)\nx=0\n#this is an example of looping through and printing out a specific paramter\n# while (x < lenpkrt-1):\n# print(x)\n# x= x + 1\n# srcip = pkts_list[x]['IP'].src\n# print(srcip)\n\n#While loop is used to find a src ip in question\nbroj=1\nwhile (x < lenpkrt-1):\n # print(x)\n x= x + 1\n srcip = str(pkts_list[x]['IP'].src)\n if srcip == '192.168.2.147':\n \n #This shows you what the mac address is\n #if broj==1:\n # mac = pkts_list[1]['Ethernet'].src\n # print(\"MAC \",mac)\n #This will show you the whole packet\n \n #wholePacket = pkts_list[x].show()\n \n \n #print(\"Host: \", host)\n \n #print (wholePacket)\n #this exits the progam as soon as a positive result is returned\n\n try:\n test=pkts_list[x]['Raw'].load\n \n print(test.decode('utf-8'))\n\n except:\n \n red=\"\"\n novi=\"\"\n for i in range(len(test)):\n if test[i]< 32 or test[i]> 122:\n if len(novi) > 5:\n \n red=red+\":\"+novi\n \n novi=\"\"\n\n novi=novi+chr(test[i])\n\n if len(red) > 0:\n if \"krbtgt\" in red:\n print (x,\">\",red)\n pass\n \n\n \n\n \n \n\n broj+=1\nprint(broj)","sub_path":"myExcerscises/python_course/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1810,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"487151395","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n# @Date : 2019-12-04 11:22:43\n# @Author : wumingsheng (wu_mingsheng@126.com)\n# @Link : link\n# @Version : 1.0.0\n\nimport os\n\n\ndef git_commit(): \n print(\" ======= 提交代码到github ==== \")\n message = input(\"请输入提交信息: \")\n os.system(\"git add .\")\n os.system(\"git commit -m %s\" % message)\n return os.system(\"git push\")\n\ndef gitbook_build():\n print(\"gitbook build ... , please waiting...\")\n flag = os.system(\"gitbook build ./ ./docs --clean\")\n print(\"gitbook build to docs dir finished !\")\n return flag\n\nSUCCESS_FLAG = gitbook_build()\n\nif SUCCESS_FLAG == 0:\n FLAG = input(\"是否同步文件到git远程仓库(y/n)? \")\n if FLAG == \"y\": \n CODE = git_commit()\n if CODE == 0:\n print(\"success -- \", \"提交成功\")\n else:\n print(\"error -- 提交失败, \", \"返回code: \", CODE)\n","sub_path":"install.py","file_name":"install.py","file_ext":"py","file_size_in_byte":913,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"103953821","text":"from graphics import *\r\nfrom button import Button \r\nclass Quizans:\r\n def __init__(self, win):\r\n self.win = win\r\n self.aButton = Button(win, Point(56, 55), 25, 10, \"A\") \r\n self.aButton.activate() \r\n self.bButton = Button(win, Point(144, 55), 25, 10, \"B\")\r\n self.bButton.activate()\r\n self.nextButton = Button(win, Point(186.5, 45), 13, 8, \"NEXT\")\r\n self.nextButton.activate()\r\n\r\n def answer(self):\r\n \r\n # Event loop \r\n pt = self.win.getMouse() \r\n if self.aButton.clicked(pt): \r\n return \"A\"\r\n if self.bButton.clicked(pt):\r\n return \"B\"\r\n pt = self.win.getMouse()\r\n \r\n def next(self):\r\n pt = self.win.getMouse() \r\n if self.nextButton.clicked(pt): \r\n return True\r\n pt = self.win.getMouse() ","sub_path":"quizans.py","file_name":"quizans.py","file_ext":"py","file_size_in_byte":846,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"622075127","text":"import streamlit as vAR_st\r\n\r\ndef ascdesc():\r\n def asc():\r\n vAR_c=[]\r\n flag=0\r\n vAR_b=vAR_a.split(\",\")\r\n \r\n with col2:\r\n if s:\r\n for i in vAR_b:\r\n if i.isnumeric():\r\n vAR_c.append(int(i))\r\n else:\r\n vAR_st.subheader(\"Enter only numeric values\")\r\n flag=1\r\n break\r\n if flag==0: \r\n vAR_c.sort()\r\n vAR_res=','.join(str(item) for item in vAR_c)\r\n with col1:\r\n vAR_st.write(\"\")\r\n vAR_st.subheader(\"Answer is\")\r\n\r\n vAR_st.write('')\r\n vAR_st.subheader(vAR_res)\r\n\r\n def desc():\r\n vAR_c=[]\r\n vAR_b=vAR_a.split(\",\")\r\n with col2:\r\n if s:\r\n for i in vAR_b:\r\n if i.isnumeric():\r\n vAR_c.append(int(i))\r\n else:\r\n vAR_st.subheader(\"Enter only numeric values\")\r\n flag=1\r\n break\r\n \r\n if flag==0:\r\n vAR_c.sort(reverse=True)\r\n vAR_res=','.join(str(item) for item in vAR_c)\r\n with col1:\r\n vAR_st.write(\"\")\r\n vAR_st.subheader(\"Answer is\")\r\n vAR_st.write('')\r\n vAR_st.subheader(vAR_res)\r\n\r\n\r\n cl1,col1,col2,cl2= vAR_st.columns((1,2,2,1))\r\n ul1,col3,col4,ul2=vAR_st.columns((5,2,2,5))\r\n\r\n def cleartext():\r\n vAR_st.session_state[\"Clear\"]=\"\"\r\n vAR_st.session_state[\"Clear2\"]=\"Select\"\r\n\r\n with col3:\r\n s=vAR_st.button(\"Submit\")\r\n \r\n with col4:\r\n c=vAR_st.button(\"Clear\",on_click=cleartext)\r\n\r\n\r\n with col1:\r\n vAR_st.write('')\r\n vAR_st.subheader(\"Enter the numbers\")\r\n with col2:\r\n vAR_a=vAR_st.text_input(\"\",key=\"Clear\")\r\n with col1:\r\n vAR_st.write('')\r\n vAR_st.subheader(\" Sorting Order\")\r\n with col2:\r\n selected=vAR_st.selectbox(\"\",(\"Select\",\"Ascending order\",\"Descending order\"),key=\"Clear2\")\r\n\r\n if selected==\"Ascending order\":\r\n asc()\r\n \r\n if selected==\"Descending order\":\r\n desc()\r\n\r\n\r\n \r\n\r\n\r\n \r\n\r\n\r\n \r\n","sub_path":"Grade 06/Application/source/ascdesc.py","file_name":"ascdesc.py","file_ext":"py","file_size_in_byte":2421,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"101752250","text":"import urllib.parse\nimport hashlib\nimport os.path\nimport glob\nimport logging\n\nimport aiohttp.web\n\nimport cryptography.x509\nimport cryptography.hazmat.backends\nimport cryptography.hazmat.primitives.hashes\nimport cryptography.hazmat.primitives.serialization\n\nfrom ...pdict import PersistentDict\nfrom ...config import ConfigObject\nfrom ... import Service\n\n#\n\nL = logging.getLogger(__name__)\n\n#\n\n\ndef pubkeyauth_middleware_factory(app, *args, mode='direct', service=None, **kwargs):\n\t'''\n\t`service` is the instance of `PublicKeyAuthenticationService`.\n\tIf `service` is not provided, every SSL client with certificate is authenticated.\n\n\t`mode` is one of `direct` or `proxy`.\n\n\t'''\n\n\t@aiohttp.web.middleware\n\tasync def pubkeyauth_direct_middleware(request, handler):\n\t\t'''\n\t\tThis middleware is used when ASAB is working directly with SSL socket\n\t\t'''\n\n\t\tssl_object = request.transport.get_extra_info('ssl_object')\n\t\tif ssl_object is None:\n\t\t\t# The connection is not a SSL\n\t\t\treturn await handler(request)\n\n\t\tcert = ssl_object.getpeercert(binary_form=True)\n\t\tif cert is None:\n\t\t\t# The client doesn't provided a certificate\n\t\t\treturn await handler(request)\n\n\t\ttry:\n\t\t\tcert = cryptography.x509.load_der_x509_certificate(\n\t\t\t\tcert,\n\t\t\t\tcryptography.hazmat.backends.default_backend()\n\t\t\t)\n\t\texcept Exception:\n\t\t\tL.exception(\"Error when parsing a client certificate\")\n\t\t\treturn await handler(request)\n\n\n\t\tif service is not None:\n\t\t\tif not service.authenticate(cert):\n\t\t\t\treturn await handler(request)\n\n\t\trequest.Identity = cert.subject.rfc4514_string()\n\n\t\treturn await handler(request)\n\n\treturn pubkeyauth_direct_middleware\n\n\n\t@aiohttp.web.middleware\n\tasync def pubkeyauth_proxy_middleware(request, handler):\n\t\t'''\n\t\tThis middleware is used when ASAB is working behind a SSL-terminating proxy.\n\t\tClient certificate is expected in X-SSL-Client-Cert\n\n\t\tThe client certificate is now extracted from `X-SSL-Client-Cert` header, where is it stored by NGinx by:\n\n\t\tproxy_set_header X-SSL-Client-Cert $ssl_client_escaped_cert;\n\nserver {\n\tlisten 443 ssl;\n\n\t# A server certificate\n\tssl_certificate_key letsencrypt/key.pem;\n\tssl_certificate\tletsencrypt/fullchain.cer;\n\n\t# Certificate of your custom CA for clients\n\tssl_trusted_certificate custom-ca-cert.pem;\n\n\t# make verification optional, so we can display a 403 message to those who fail authentication\n\tssl_verify_client optional_no_ca;\n\n\tlocation /websocket {\n\t\tif ($ssl_client_verify != SUCCESS) {\n\t\t\treturn 403;\n\t\t}\n\n\t\tproxy_pass http://localhost:8080/websocket;\n\t\tproxy_http_version 1.1;\n\n\t\tproxy_set_header Host $host;\n\t\tproxy_set_header X-Real-IP $remote_addr;\n\t\tproxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;\n\t\tproxy_set_header X-Forwarded-Proto $scheme;\n\n\t\tproxy_set_header Upgrade $http_upgrade;\n\t\tproxy_set_header Connection \"Upgrade\";\n\n\t\tproxy_set_header X-Forwarded-Client-Cert $ssl_client_escaped_cert;\n\t}\n}\n\n\t\t'''\n\n\t\tcert = request.headers.get('X-Forwarded-Client-Cert')\n\t\tif cert is None:\n\t\t\treturn await handler(request)\n\t\tcert = urllib.parse.unquote_to_bytes(cert)\n\n\t\ttry:\n\t\t\tcert = cryptography.x509.load_pem_x509_certificate(\n\t\t\t\tcert,\n\t\t\t\tcryptography.hazmat.backends.default_backend()\n\t\t\t)\n\t\texcept Exception:\n\t\t\tL.exception(\"Error when parsing a client certificate\")\n\t\t\treturn await handler(request)\n\n\t\tif service is not None:\n\t\t\tif not service.authenticate(cert):\n\t\t\t\treturn await handler(request)\n\n\t\trequest.Identity = cert.subject.rfc4514_string()\n\n\t\treturn await handler(request)\n\n\tif mode == 'direct':\n\t\treturn pubkeyauth_direct_middleware\n\telif mode == 'proxy':\n\t\treturn pubkeyauth_proxy_middleware\n\telse:\n\t\traise RuntimeError(\"Unknown mode '{}'\".format(mode))\n\n\n\nclass PublicKeyAuthenticationService(Service, ConfigObject):\n\n\t'''\n\tThis is an authentication service that uses the whitelist of public keys of authenticated clients.\n\tClients should provide a certificate via TLS handshake (aka mutual TLS authorization).\n\tThe public key from a certificate is then matched with certificates that are stored in the directory cache.\n\tA client is authenticated when the matching certificate is found, otherwise \"HTTPUnauthorized\" (401) is raised.\n\n\tClient certificates are issued by a dedicated Certificate Authority. You can establish your own.\n\tA public certificate of the client has to be placed into a client certificate directory of the server.\n\n\tThis authentication is designed from machine-to-machine websocket communication with small amount of requests.\n\tIt validates the certificate/public keys every time the client hits the server.\n\tThat is OK for long-lived WebSockets, but not scalable for a regular HTTP traffic.\n\n\t'''\n\n\tConfigDefaults = {\n\t\t'dir': './',\n\t\t'glob': '*-cert.pem',\n\t\t'index': '.index.bin',\n\t}\n\n\tdef __init__(self, app, *, service_name=\"asab.PublicKeyAuthenticationService\", config_section_name='asab:web:authn:pubkey', config=None):\n\t\tsuper().__init__(app, service_name)\n\t\tConfigObject.__init__(self, config_section_name, config)\n\n\t\tself.ClientCertDir = self.Config.get('dir')\n\t\tself.ClientCertGlob = self.Config.get('glob')\n\t\tself.IndexPDict = PersistentDict(os.path.join(self.ClientCertDir, self.Config.get('index')))\n\n\n\tdef authenticate(self, certificate):\n\t\tpublic_key = certificate.public_key()\n\t\tpk_digest = self.get_public_key_digest(public_key)\n\n\t\tentry = self.IndexPDict.get(pk_digest)\n\t\tif entry is None:\n\t\t\t# Key not found in the index, let's scan the directory\n\t\t\tself._scan_dir()\n\t\t\tentry = self.IndexPDict.get(pk_digest)\n\n\t\tif entry is None:\n\t\t\tL.warning(\"Authentication failed, public key not found\")\n\t\t\treturn False\n\n\t\tassert(entry is not None)\n\n\t\tpk_digest1 = self.get_public_key_digest_from_filename(entry)\n\t\tif pk_digest1 is None:\n\t\t\treturn False\n\n\t\treturn pk_digest == pk_digest1\n\n\n\tdef _scan_dir(self):\n\t\tknown_fnames = frozenset(self.IndexPDict.values())\n\t\tfor fname in glob.glob(os.path.join(self.ClientCertDir, self.ClientCertGlob)):\n\t\t\tif fname in known_fnames:\n\t\t\t\tcontinue\n\t\t\tpk_digest = self.get_public_key_digest_from_filename(fname)\n\t\t\tself.IndexPDict[pk_digest] = fname\n\n\n\tdef get_public_key_digest_from_filename(self, fname):\n\t\ttry:\n\t\t\twith open(fname, 'rb') as f:\n\t\t\t\t# Load a client certificate in PEM format\n\t\t\t\tcert = cryptography.x509.load_pem_x509_certificate(\n\t\t\t\t\tf.read(),\n\t\t\t\t\tcryptography.hazmat.backends.default_backend()\n\t\t\t\t)\n\t\texcept Exception:\n\t\t\treturn None\n\n\t\treturn self.get_public_key_digest(cert.public_key())\n\n\n\tdef get_public_key_digest(self, public_key):\n\t\t# Hash the public key\n\t\tpublic_key_bytes = public_key.public_bytes(\n\t\t\tcryptography.hazmat.primitives.serialization.Encoding.DER,\n\t\t\tcryptography.hazmat.primitives.serialization.PublicFormat.SubjectPublicKeyInfo\n\t\t)\n\t\th = hashlib.blake2b(public_key_bytes)\n\t\treturn h.digest()\n","sub_path":"asab/web/authn/pubkeyauth.py","file_name":"pubkeyauth.py","file_ext":"py","file_size_in_byte":6688,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"538730749","text":"import random\n\n\nclass BadCircuitGenerator:\n def __init__(self, randomInputDataList, circuit):\n self.randomInputDataList = randomInputDataList\n self.circuit = circuit\n\n #Compares two lists to see if items are equal and if they are at the same position in the lists\n def areListsEqual(self, aList, bList):\n if(len(aList) != len(bList)):\n return 0\n else:\n for i in range(0, len(aList)):\n if(aList[i] != bList[i]):\n return 0\n return 1\n\n\n def generateOutputList(self, listLength):\n randomList = []\n possibleValues = [0, 1]\n for i in range(0, listLength):\n randomList.append(random.choice(possibleValues))\n return randomList\n\n def generateBadOutputData(self, badDataRatio = 0.5):\n foundedKeys = []\n\n for inputSequence in self.randomInputDataList:\n for circuitInputSequence in list(self.circuit.dictionary.keys()):\n if self.areListsEqual(inputSequence.inputList, list(circuitInputSequence)):\n foundedKeys.append(inputSequence.inputList)\n\n foundedKeys = [list(x) for x in set(tuple(x) for x in foundedKeys)] #removing duplicates\n if badDataRatio >= 1.0:\n badDataRatio = 0.5\n\n random.shuffle(foundedKeys)\n numberOfKeys = len(foundedKeys)\n numberOfKeysToEdit = numberOfKeys * badDataRatio\n\n for i in range(0, int(numberOfKeysToEdit)):\n key = tuple(foundedKeys[i])\n if self.circuit.dictionary.get(key):\n self.circuit.dictionary[key] = self.generateOutputList(self.circuit.outputsNumber)\n return self.circuit","sub_path":"BIST/BadCircuitGenerator.py","file_name":"BadCircuitGenerator.py","file_ext":"py","file_size_in_byte":1701,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"396797459","text":"from PyQt5.QtCore import *\nfrom Business import *\nfrom Data.Materials import Material\nfrom Data.Parameters import *\n\n__author__ = 'mamj'\n\ncol_header = [\"Materials\"]\n\n\nclass MaterialsModel(QAbstractTableModel):\n\tdef __init__(self, doc):\n\t\tQAbstractItemModel.__init__(self)\n\t\tself._materials = doc.get_materials()\n\t\tself._doc = doc\n\t\tself._rows = []\n\t\tfor material_tuple in self._materials.get_materials():\n\t\t\tself._rows.append(material_tuple[1].uid)\n\t\tself._materials.add_change_handler(self.on_materials_changed)\n\t\tself.old_row_count = 0\n\n\tdef rowCount(self, model_index=None, *args, **kwargs):\n\t\treturn len(self._rows)\n\n\tdef columnCount(self, model_index=None, *args, **kwargs):\n\t\treturn len(col_header)\n\n\tdef data(self, model_index: QModelIndex, int_role=None):\n\t\tcol = model_index.column()\n\t\trow = model_index.row()\n\t\tdata = None\n\t\tif int_role == Qt.DisplayRole:\n\t\t\tmaterial_item = self._materials.get_material(self._rows[row])\n\t\t\tif col == 0:\n\t\t\t\tdata = material_item.name\n\t\telif int_role == Qt.EditRole:\n\t\t\tmaterial_item = self._materials.get_material(self._rows[row])\n\t\t\tif col == 0:\n\t\t\t\tdata = material_item.name\n\t\treturn data\n\n\tdef setData(self, model_index: QModelIndex, value: QVariant, int_role=None):\n\t\tcol = model_index.column()\n\t\trow = model_index.row()\n\t\tmaterial_item = self._materials.get_material(self._rows[row])\n\t\tif col == 0:\n\t\t\tmaterial_item.set_name(value)\n\t\t\treturn True\n\n\t\treturn False\n\n\tdef removeRow(self, row, QModelIndex_parent=None, *args, **kwargs):\n\t\tmaterial = self._materials.get_material(self._rows[row])\n\t\tremove_materials(self._doc, [material])\n\n\t# self._edges.remove_edge(edge)\n\n\tdef remove_rows(self, rows):\n\t\tmaterials = []\n\t\tfor row in rows:\n\t\t\tmaterials.append(self._materials.get_material(self._rows[row]))\n\t\tremove_materials(self._doc, materials)\n\n\tdef on_materials_changed(self, event: ChangeEvent):\n\t\tif type(event.object) is Material:\n\t\t\tif event.type == event.BeforeObjectAdded:\n\t\t\t\tself.beginInsertRows(QModelIndex(), len(self._rows), len(self._rows))\n\t\t\tif event.type == event.ObjectAdded:\n\t\t\t\tself._rows.append(event.object.uid)\n\t\t\t\tself.endInsertRows()\n\t\t\tif event.type == event.BeforeObjectRemoved:\n\t\t\t\tif event.object.uid in self._rows:\n\t\t\t\t\trow = self._rows.index(event.object.uid)\n\t\t\t\t\tself.beginRemoveRows(QModelIndex(), row, row)\n\t\t\tif event.type == event.ObjectRemoved:\n\t\t\t\tif event.object.uid in self._rows:\n\t\t\t\t\tself._rows.remove(event.object.uid)\n\t\t\t\t\tself.endRemoveRows()\n\t\t\tif event.type == event.ValueChanged:\n\t\t\t\tmat = event.sender\n\t\t\t\tif type(mat) is Material:\n\t\t\t\t\trow = self._rows.index(mat.uid)\n\t\t\t\t\tleft = self.createIndex(row, 0)\n\t\t\t\t\tright = self.createIndex(row, 3)\n\t\t\t\t\tself.dataChanged.emit(left, right)\n\n\t\tif event.type == event.Cleared:\n\t\t\tself.beginRemoveRows(QModelIndex(), 0, len(self._rows) - 1)\n\t\t\tself._rows = []\n\t\t\tself.endRemoveRows()\n\n\tdef flags(self, model_index: QModelIndex):\n\t\tdefault_flags = Qt.ItemIsSelectable | Qt.ItemIsEnabled | Qt.ItemIsEditable\n\t\treturn default_flags\n\n\tdef headerData(self, p_int, orientation, int_role=None):\n\t\tif int_role == Qt.DisplayRole:\n\t\t\tif orientation == Qt.Vertical:\n\t\t\t\treturn p_int\n\t\t\telse:\n\t\t\t\treturn col_header[p_int]\n\n\t\telse:\n\t\t\treturn\n\n\tdef get_materials_object(self):\n\t\treturn self._materials\n\n\tdef get_material(self, row):\n\t\treturn self._materials.get_material(self._rows[row])\n\n\tdef get_index_from_edge(self, material):\n\t\trow = self._rows.index(material.uid)\n\t\treturn self.index(row, 0)\n","sub_path":"GUI/Models/MaterialsModel.py","file_name":"MaterialsModel.py","file_ext":"py","file_size_in_byte":3422,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"102308018","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon May 24 23:52:02 2021\n\n@author: HASHIB\n\"\"\"\nimport glob\nimport cv2\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n#Collect Face data with and Without Mask\n#Read the mask image\n\npath = glob.glob(\"C:/Users/HASHIB/Desktop/Face detections/FaceMaskdetection/Dataset/train/without_mask/*.jpg\")\nwithout_mask = []\nhaar_data = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')\n\nfor image in path:\n n = cv2.imread(image)\n without_mask.append(n)\nlength = len(without_mask)\n\ndata =[]\nfor img in without_mask:\n \n faces = haar_data.detectMultiScale(img)\n for x,y,w,h in faces:\n cv2.rectangle(img, (x,y), (x+w,y+h), (255, 0, 255), 4)\n\n face = img[y:y+h, x:x+w, :]\n face = cv2.resize(face, (50,50))\n if len(data) < length:\n data.append(face)\n #cv2.imshow(\"Result\", img) \n if cv2.waitKey(2) == 27 or len(data) >= length:\n break\ncv2.destroyAllWindows() \n \n#if len(data) == length:\n #np.save('Training_Data_WithOut_mask.npy',data)\nplt.imshow(data[0])","sub_path":"Preprocess_Training_data(with_out__mask_images)/face_with_out_mask_detection.py","file_name":"face_with_out_mask_detection.py","file_ext":"py","file_size_in_byte":1100,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"34538850","text":"# Created by Eliot York of Hellopoetry.com\nimport os.path as opath\n\nfrom fabric.api import *\nfrom fabric.contrib.files import *\n\nAPP = \"\"\nDOMAIN = \"\"\nLOCAL_PROJECT_ROOT = \"\"\n\n# PROD SETTINGS\nenv.roledefs.update({\"WEB_SERVERS\": [\n \"user@1.1.1.1\",\n]})\n\nenv.rr = run\nenv.password = \"\"\nenv.project_root = \"\"\nenv.key_filename = None\n\n\n@task\n@roles([\"WEB_SERVERS\"])\ndef deploy():\n # sudo(\"echo 'password, please'\")\n local(\"git add --all .;git commit -m 'deploy %s';git push origin master;\" % APP)\n execute(deploy_web)\n\n\n@task\n@roles([\"WEB_SERVERS\"])\ndef deploy_web():\n with cd(env.project_root):\n run(\"git reset --hard; git pull origin master;\")\n run(\"./pip install -r requirements.txt;\")\n run(\"./manage syncdb --noinput;./manage migrate;./manage update_index;\")\n sudo(\"service %s restart\" % APP)\n\n\n@task\n@roles([\"WEB_SERVERS\"])\ndef requirements():\n with cd(env.project_root):\n run(\"./pip install -r requirements.txt\")\n\n\n@task\n@roles([\"WEB_SERVERS\"])\ndef update_nginx():\n with cd(env.project_root):\n put(\"%s/nginx.conf\" % (LOCAL_PROJECT_ROOT), \"/etc/nginx/sites-available/%s\" % DOMAIN, use_sudo=True)\n # sudo(\"sudo ln -s /etc/nginx/sites-available/%s /etc/nginx/sites-enabled/%s\" % (DOMAIN, DOMAIN))\n sudo(\"service nginx restart\")\n\n\n@task\n@roles([\"WEB_SERVERS\"])\ndef update_uwsgi():\n put(\"%s/%s.conf\" % (LOCAL_PROJECT_ROOT, APP), \"/etc/init/%s.conf\" % APP, use_sudo=True)\n # sudo(\"sudo ln -s /etc/nginx/sites-available/%s /etc/nginx/sites-enabled/%s\" % (DOMAIN, DOMAIN))\n sudo(\"service %s restart\" % APP)\n\n\n@task\n@roles([\"WEB_SERVERS\"])\ndef empty_web_crontab():\n run(\"sudo touch /tmp/project\")\n run(\"crontab - < /tmp/project && sudo rm -f /tmp/project\")\n\n\ndef manage():\n cmd = prompt(\"./manage ___:\")\n env.rr(\"cd %s; ./manage %s;\" % (env.project_root, cmd))\n\n\n@task\n@roles([\"WEB_SERVERS\"])\ndef test():\n sudo(\"echo 'test'\")\n\n######################\n# LOCAL PROJECT SETUP\n######################\n\n\ndef cd(path):\n old_cwd = env.get(\"cwd\", \"./\")\n if path[0] not in \"/~.\":\n path = opath.join(old_cwd, path)\n\n return settings(cwd=path)\n","sub_path":"example/fabfile.py","file_name":"fabfile.py","file_ext":"py","file_size_in_byte":2141,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"319167799","text":"from ftw.upgrade import UpgradeStep\n\n\nclass AllowToDeleteContentsOfPrivateFolder(UpgradeStep):\n \"\"\"Allow to delete contents of private folder.\n \"\"\"\n\n def __call__(self):\n self.install_upgrade_profile()\n self.update_workflow_security(['opengever_private_folder_workflow',\n 'opengever_private_dossier_workflow'],\n reindex_security=False)\n","sub_path":"opengever/core/upgrades/20171110104350_allow_to_delete_contents_of_private_folder/upgrade.py","file_name":"upgrade.py","file_ext":"py","file_size_in_byte":434,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"447651889","text":"import RPi.GPIO as GPIO\nimport time\nGPIO.setmode(GPIO.BCM)\n#control_pins = [7,11,13,15]\ncontrol_pins = [1,7,17,27]\n\n\n\nfor pin in control_pins:\n GPIO.setup(pin, GPIO.OUT)\n GPIO.output(pin, 0)\nhalfstep_seq = [\n [1,0,0,0],\n [1,1,0,0],\n [0,1,0,0],\n [0,1,1,0],\n [0,0,1,0],\n [0,0,1,1],\n [0,0,0,1],\n [1,0,0,1]\n]\n\ndirection=[8]\n\nwhile True:\n\tfor i in range(1800):\n\t\tfor halfstep in range(*direction):\n\t\t\tfor pin in range(4):\n\t\t\t\tGPIO.output(control_pins[pin], halfstep_seq[halfstep][pin])\n\t\t\t\ttime.sleep(0.0002)\n\n\tdirection = [7,-1,-1] if direction == [8] else [8]\n\nGPIO.cleanup()\n","sub_path":"IoT/RaspberryPi/messing_around/Motors/StepMotor/Frog_Full_length_test.py","file_name":"Frog_Full_length_test.py","file_ext":"py","file_size_in_byte":583,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"420751025","text":"# 将求s的最长回文子序列的长度转换为求s与s[::-1]的最长公共子序列的长度\n# 74 / 83 个通过测试用例,超时\nclass Solution(object):\n def longestPalindromeSubseq(self, s):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n if not s:\n return 0\n elif len(s) == 1:\n return 1\n # 题目转化一下就是求s与s[::-1]的最长公共子序列\n s1, s2 = s, s[::-1]\n n = len(s)\n # dp[i][j]代表s1[0..i]和s2[0..j]的最长公共子序列的长度\n dp = [[0 for _ in range(n)] for _ in range(n)]\n if s1[0] == s2[0]:\n dp[0][0] = 1\n for i in range(1, n):\n if s1[i] == s2[0] or dp[i - 1][0]:\n dp[i][0] = 1\n for j in range(1, n):\n if s2[j] == s1[0] or dp[0][j - 1]:\n dp[0][j] = 1\n for i in range(1, n):\n for j in range(1, n):\n if s1[i] == s2[j]:\n dp[i][j] = dp[i - 1][j - 1] + 1\n else:\n dp[i][j] = max(dp[i - 1][j], dp[i][j - 1])\n return dp[-1][-1]\n\n\nclass Solution(object):\n def longestPalindromeSubseq(self, s):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n if not s:\n return 0\n elif len(s) == 1:\n return 1\n # dp[i][j]表示s的第i个字符到第j个字符组成的子串中,最长的回文��列的长度\n n = len(s)\n dp = [[0 for _ in range(n)] for _ in range(n)]\n for i in range(n - 1, -1, -1):\n dp[i][i] = 1\n for j in range(i + 1, n):\n if s[i] == s[j]:\n dp[i][j] = dp[i + 1][j - 1] + 2\n else:\n dp[i][j] = max(dp[i + 1][j], dp[i][j - 1])\n return dp[0][n - 1]\n","sub_path":"题目分类/动态规划/longest_palindromic_subsequence_516.py","file_name":"longest_palindromic_subsequence_516.py","file_ext":"py","file_size_in_byte":1837,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"337036047","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu Apr 20 20:48:20 2017\r\n\r\n@author: Sumit Saurabh\r\n\"\"\"\r\nimport os\r\n #RUNNING MEDIAN CODE\r\ndef start():\r\n os.chdir(os.getcwd()+'\\\\wc_output')\r\n ip = open(\"result.txt\",\"r\").read().splitlines()\r\n #ip = ip.read()\r\n #print(ip)\r\n\r\n\r\n num_words =0 \r\n count=[] \r\n j=0\r\n for i in ip:\r\n words = i.split(' ')\r\n num_words+= len(words)\r\n count.append(num_words)\r\n #print(count[j])\r\n num_words=0\r\n j=j+1\r\n \r\n \r\n\r\n\r\n\r\n temp= []\r\n median=0\r\n\r\n for i in range(0, len(count)):\r\n temp.append(count[i])\r\n sort_numbers(temp)\r\n #print(temp)\r\n #print(len(temp)%2)\r\n if(len(temp)%2 == 0):\r\n k1=int((len(temp))/2)\r\n k2=int(((len(temp))/2)+1)\r\n median= float((temp[k1-1]+temp[k2-1])/2)\r\n else:\r\n k3=int((len(temp)+1)/2)\r\n median= float(temp[k3-1])\r\n print(median)\r\n \r\ndef sort_numbers(count):\r\n\r\n for i in range(1, len(count)):\r\n val = count[i]\r\n j = i - 1\r\n while (j >= 0) and (count[j] > val):\r\n count[j+1] = count[j]\r\n j = j - 1\r\n count[j+1] = val\r\n \r\nif __name__ == \"__main__\":\r\n start()\r\n \r\n \r\n \r\n\r\n \r\n \r\n","sub_path":"running_median.py","file_name":"running_median.py","file_ext":"py","file_size_in_byte":1308,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"521866414","text":"'''\nAMMM Lab Heuristics\nAbstract Decoder class\nCopyright 2020 Luis Velasco.\n\nThis program is free software: you can redistribute it and/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with this program. If not, see .\n'''\n\nclass _Decoder(object):\n def __init__(self, config, instance):\n self.config = config\n self.instance = instance\n\n def decode(self, generation):\n numDecoded = 0\n bestInGeneration = {'chr':None, 'solution':None, 'fitness':float('inf')}\n for individual in generation:\n numDecoded += 1\n if individual['fitness'] is None:\n solution, fitness = self.decodeIndividual(individual['chr'])\n individual['solution'] = solution\n individual['fitness'] = fitness\n if individual['fitness'] < bestInGeneration['fitness']:\n bestInGeneration = individual\n return bestInGeneration, numDecoded\n\n def getConfiguration(self):\n return self.config\n\n def decodeIndividual(self, chromosome):\n raise NotImplementedError","sub_path":"Heuristics/BRKGA_fwk/decoder.py","file_name":"decoder.py","file_ext":"py","file_size_in_byte":1544,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"509701585","text":"# %%\r\nimport scipy.io as sio\r\n\r\n# %%\r\nmat_contents = sio.loadmat('ImGHIrec2.mat')\r\n\r\n# %%\r\n\r\n\r\n# %%\r\n\r\n\r\n# %%\r\nDateTimeCom=sio.loadmat('DateTimeCom.mat')\r\ndt=DateTimeCom['DateTimeCom']\r\n\r\n\r\n# %%\r\nimport numpy as np\r\n\r\n\r\n\r\n\r\n# %%\r\nimport pandas as pd\r\ndt=pd.to_datetime(dt)\r\n\r\n# %%\r\nmat_contents.keys()\r\n\r\n# %%\r\nmat_Im=mat_contents[\"ImGHIrec2\"]\r\nmat_Im.shape\r\n\r\n# %%\r\nx=mat_Im[:,:,100]\r\ny=mat_Im[:,:,105]\r\n\r\n# %%\r\nx=x.reshape(x.size,1)\r\ny=y.reshape(y.size,1)\r\n\r\n# %%\r\n\r\nfrom matplotlib import pyplot as plt\r\n\r\n\r\n# %%\r\nplt.figure\r\nplt.plot(x,y,'xk')\r\nplt.show()\r\nplt.figure\r\nplt.plot(x,'r')\r\nplt.plot(y,'b')\r\nplt.show()\r\n\r\n\r\n# %%\r\n\r\n\r\n# %%\r\n","sub_path":"cam_ghi.py","file_name":"cam_ghi.py","file_ext":"py","file_size_in_byte":639,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"58451400","text":"# For Reddit API\nimport praw\n# To make the bot sleep after posting a comment\nimport time\n# To read the config file\nimport configparser\n\n# Reading config file to get user authentication details\nauthenticationDetails = configparser.ConfigParser()\nauthenticationDetails.read('greetingBot.ini')\n\n# Storing user authentication details from config file\nclientID = authenticationDetails.get('Authentication', 'ClientID')\nclientSecret = authenticationDetails.get('Authentication', 'clientSecret')\nuserName = authenticationDetails.get('Authentication', 'username')\nuserPassword = authenticationDetails.get('Authentication', 'password')\n\n# Creating the Reddit object and passing in authentication details through PRAW\ngreetingBot = praw.Reddit(user_agent = 'greeatingBot v0.1',\n client_id = clientID ,\n client_secret = clientSecret,\n username = userName,\n password = userPassword)\n\n# Points greetingBot to the r/learnprogramming subreddit\nsubreddit = greetingBot.subreddit('learnprogramming')\n# Creating a stream of posts/submissions to scan through\nposts = subreddit.stream.submissions()\n\n# These are the phrases or keywords that the bot will search for in each post\nkeywords = (\"is my first post here\", \"I'm new here\",\n \"I'm new on this site\", \"I haven't posted here before\",\n \"my first time posting\", \"I'm new to programming\",\n \"I'm very new to programming\", \"I'm really new to programming\" \n \"CS beginner\", \"beginner programmer\",\n \"starting to program\")\n\n\ndef main():\n print(\"Searching through posts...\")\n # Scanning through the posts on the subreddit\n for post in posts:\n # Boolean flag will determine whether or not a post:\n # 1. Has the phrase in the post\n # 2. Has not previously been commented on by the bot\n flag = False\n submission_text = post.selftext\n submission_author = post.author\n # Scans through each post for each phrase\n for keyword in keywords:\n if keyword in submission_text.lower():\n print(\"Matching post found!\")\n # If phrase is found, flag is changed to true\n flag = True\n # Creating a \"comment forest\" through PRAW that will iterate through each comment on the post\n post.comments.replace_more(limit=None)\n for comment in post.comments.list():\n if str(comment.author) == userName:\n print(\"Already commented on this one...\")\n print(\"Searching through posts...\")\n # If the bot has already commented on the post, it will adjust flag to false and move on\n flag = False\n # If flag is true at this point, a phrase has been found in the post and the bot has not commented on the post\n if flag:\n msg = \"Hey, u/{0}\".format(submission_author) + \", it looks like you're new to programming! \" \\\n \"That's great! Keep up the hard work and stay \" \\\n \"positive! Code on!\"\n\n # The bot posts the message and goes to sleep for two minutes\n # This allows newer accounts to use the bot and not be shut down for spam posting\n post.reply(msg)\n print(\"Encouraging comment posted!\")\n print(\"Going to sleep for two minutes...\")\n time.sleep(30)\n print(\"30 seconds...\")\n time.sleep(30)\n print(\"1 minute...\")\n time.sleep(30)\n print(\"1 minute 30 seconds...\")\n time.sleep(30)\n print(\"Searching through posts...\")\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"greetingBot.py","file_name":"greetingBot.py","file_ext":"py","file_size_in_byte":3838,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"255533660","text":"import json\nimport logging\n\nimport hyperopt\n\nfrom homeserv_inter.constants import TUNING_DIR\n\nlogger = logging.getLogger(__name__)\n\n\nclass HyperParamsTuning:\n \"\"\"Base class for hyper parameters tuning using hyperopt.\"\"\"\n\n int_params = ()\n float_params = ()\n\n @property\n def hypertuning_space(self):\n raise NotImplementedError\n\n def _ensure_type_params(self, params):\n \"\"\"Sanitize params according to their type.\"\"\"\n for k in self.int_params:\n if k in params:\n params[k] = int(params[k])\n\n for k in self.float_params:\n if k in params:\n params[k] = round(params[k], 3)\n\n return params\n\n def _hypertuning_save_results(self, best_params, trials):\n # Store eval_hist for best score:\n fpath = TUNING_DIR / \"eval_hist_best_score.json\"\n print(\"Saving {}\".format(fpath))\n\n # Best score idx:\n best_score = 0\n for i, d in enumerate(trials.results):\n if best_score < d[\"loss\"]:\n idx = i\n best_score = max(best_score, d[\"loss\"])\n\n with open(fpath, \"w\") as file:\n eval_hist = trials.trial_attachments(trials.trials[idx])[\"eval_hist\"]\n file.write(json.dumps(eval_hist))\n\n fpath = TUNING_DIR / \"best_params.json\"\n print(\"Saving {}\".format(fpath))\n with open(fpath, \"w\") as file:\n file.write(json.dumps(best_params))\n\n def tuning(self, max_evals=3):\n trials = hyperopt.Trials()\n try:\n # https://github.com/hyperopt/hyperopt/wiki/FMin\n best_params = hyperopt.fmin(\n fn=self.hypertuning_objective,\n space=self.hypertuning_space,\n algo=hyperopt.tpe.suggest,\n max_evals=max_evals,\n trials=trials, # store results\n )\n except Exception as e:\n logger.error(e)\n return\n\n # Save some results:\n self._hypertuning_save_results(best_params, trials)\n\n return best_params\n\n def hypertuning_objective(self, params):\n raise NotImplementedError\n","sub_path":"src/homeserv_inter/tuning.py","file_name":"tuning.py","file_ext":"py","file_size_in_byte":2145,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"354205556","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.5 (3351)\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-x86_64/egg/tests/pynestml_2_nest_type_converter_test.py\n# Compiled at: 2020-03-05 05:49:41\n# Size of source mod 2**32: 2896 bytes\nimport unittest\nfrom astropy import units\nfrom pynestml.codegeneration.pynestml_2_nest_type_converter import PyNestml2NestTypeConverter\nfrom pynestml.symbols.boolean_type_symbol import BooleanTypeSymbol\nfrom pynestml.symbols.integer_type_symbol import IntegerTypeSymbol\nfrom pynestml.symbols.nest_time_type_symbol import NESTTimeTypeSymbol\nfrom pynestml.symbols.predefined_types import PredefinedTypes\nfrom pynestml.symbols.predefined_units import PredefinedUnits\nfrom pynestml.symbols.real_type_symbol import RealTypeSymbol\nfrom pynestml.symbols.string_type_symbol import StringTypeSymbol\nfrom pynestml.symbols.unit_type_symbol import UnitTypeSymbol\nfrom pynestml.symbols.void_type_symbol import VoidTypeSymbol\nfrom pynestml.utils.unit_type import UnitType\nPredefinedUnits.register_units()\nPredefinedTypes.register_types()\nconvert = PyNestml2NestTypeConverter.convert\n\nclass PyNestMl2NESTTypeConverterTest(unittest.TestCase):\n\n def test_boolean_type(self):\n bts = BooleanTypeSymbol()\n result = convert(bts)\n self.assertEqual(result, 'bool')\n\n def test_real_type(self):\n rts = RealTypeSymbol()\n result = convert(rts)\n self.assertEqual(result, 'double')\n\n def test_void_type(self):\n vts = VoidTypeSymbol()\n result = convert(vts)\n self.assertEqual(result, 'void')\n\n def test_string_type(self):\n sts = StringTypeSymbol()\n result = convert(sts)\n self.assertEqual(result, 'std::string')\n\n def test_integer_type(self):\n its = IntegerTypeSymbol()\n result = convert(its)\n self.assertEqual(result, 'long')\n\n def test_unit_type(self):\n ms_unit = UnitType(name=str(units.ms), unit=units.ms)\n uts = UnitTypeSymbol(unit=ms_unit)\n result = convert(uts)\n self.assertEqual(result, 'double')\n\n def test_buffer_type(self):\n bts = IntegerTypeSymbol()\n bts.is_buffer = True\n result = convert(bts)\n self.assertEqual(result, 'nest::RingBuffer')\n\n def test_time_type(self):\n tts = NESTTimeTypeSymbol()\n result = convert(tts)\n self.assertEqual(result, 'nest::Time')","sub_path":"pycfiles/NESTML-3.1-py3.5/pynestml_2_nest_type_converter_test.cpython-35.py","file_name":"pynestml_2_nest_type_converter_test.cpython-35.py","file_ext":"py","file_size_in_byte":2453,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"223884946","text":"from django.core.management.base import BaseCommand, CommandError\nimport psycopg2\nfrom diseases.models import Disease\n\nclass Command(BaseCommand):\n help ='Updates local database'\n\n def handle(self, *args, **kwargs):\n print('Por favor, aguarde...')\n try:\n conn = psycopg2.connect(\"dbname='d5mma0lt0jpjfj' user='ekvytxmooqboqc' host='ec2-107-21-122-38.compute-1.amazonaws.com' password='638c124d07e29a9bdf595724d3293a39b2b84f9c2b3f8fe6878e7975fca6efeb'\")\n except:\n print('Não foi possível conectar com a base de dados')\n return\n\n cur = conn.cursor()\n\n cur.execute(\"\"\"select * from Pheno_Db\"\"\")\n\n rows = cur.fetchall()\n\n\n Disease.objects.all().delete()\n\n \n to_create = []\n for row in rows:\n if row[2] != None:\n to_create += [Disease(id=row[0], name=row[2], gene=row[1])]\n\n\n Disease.objects.bulk_create(to_create)\n print('DONE!')\n ","sub_path":"trydjango/src/diseases/management/commands/update_local.py","file_name":"update_local.py","file_ext":"py","file_size_in_byte":985,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"598901939","text":"import asyncio\n\n\n# 模拟一个耗时操作\nasync def test(i):\n print(\"start...\")\n # 不能再使用以前阻塞的暂停了\n await asyncio.sleep(2)\n print(\"end...\")\n return i\n\n\nif __name__ == '__main__':\n import time\n\n start_time = time.time()\n\n # # >=python3.4\n loop = asyncio.get_event_loop()\n # 注意:是loop的方法,而不是asyncio的,不然就会引发RuntimeError:no running event loop\n tasks = [loop.create_task(test(i)) for i in range(10)]\n loop.run_until_complete(asyncio.gather(*tasks))\n for task in tasks:\n print(task.result()) # 上面把协程对象转换成task对象(协程和future相互转换的中间层)\n \n # 2.016972780227661\n print(time.time() - start_time)\n","sub_path":"python/5.concurrent/ZCoroutine/z_base_and_old/2.asyncio_loop2.1.py","file_name":"2.asyncio_loop2.1.py","file_ext":"py","file_size_in_byte":750,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"612772157","text":"from PIL import Image\nimport numpy as np\n\nimg = Image.open('photo/left.jpg')\n\nwidth, height = img.size\n\n#from_points = [(0, 0), (width-1, 0), (width-1, height-1), (0, height-1)]\n#new_points = [(width-1, 0), (0, 0), (0, height-1), (width-1, height-1)]\n\nm = -0.5\nxshift = abs(m)*width\nnew_width = width + int(round(xshift))\n\n\nfin = img.transform((img.size), Image.PERSPECTIVE,(1, 200, 1, 250))\ncoeffs = find_coeffs(new_points, from_points)\n\n#fin = img.transform((width,height), Image.PERSPECTIVE, new_points, Image.BICUBIC)\n\nfin.show()\nimg.show()","sub_path":"1.py","file_name":"1.py","file_ext":"py","file_size_in_byte":544,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"419298012","text":"#!/usr/bin/python\n\n__author__ = \"imrul\"\n__date__ = \"$Oct 20, 2015 11:37:03 PM$\"\n\nimport csv\nimport random\nimport sys\nimport dataPreparation.random_sampling\n\n# This method replaces the probabilities by a randomely choose value(incidence rates)\ndef getRandomlyChosenValue(eachEntry):\n# Split , from each entry\n r = eachEntry.split(\",\"); \n# get each probability of the cause in data list\n data = r[0].split(\";\");\n state = getRandomState(data);\n return str(getTheMidPoint(state));\n\n\n# This method randomly choose actual incidence rate(0-1) \n# and return the state that the random number is in.\n# Here data is a list of probabilities of each entry.\ndef getRandomState(data):\n# generate random number(0.0 <= randNumber <=1.0)\n randNumber = random.random();\n state = 10;\n bound0 = float(data[0]);\n bound1 = bound0 + float(data[1]);\n bound2 = bound1 + float(data[2]);\n bound3 = bound2 + float(data[3]);\n bound4 = bound3 + float(data[4]);\n# bound5 = bound4 + float(data[5]);\n # sys.stdout.write(\"random number = \"+str(randNumber)+\"\\n\");\n # sys.stdout.write(\"bound0 \"+str(bound0)+\" bound1 \"+str(bound1)+\" bound2 \"+str(bound2)+\" bound3 \"+str(bound3)+\" bound4 \"+str(bound4)+\"\\n\");\n if(randNumber > 0 and randNumber <= bound0):\n state = 0;\n if(randNumber > bound0 and randNumber <= bound1):\n state = 1;\n if(randNumber > bound1 and randNumber <= bound2):\n state = 2;\n if(randNumber > bound2 and randNumber <= bound3):\n state = 3;\n if(randNumber > bound3 and randNumber <= bound4):\n state = 4;\n# if(randNumber > bound4 and randNumber <= bound5):\n# state = 5;\n return state;\n\n# This method gets the midpoint by each state(0,1,2,3,4)\ndef getTheMidPoint(state):\n ranges = list();\n ranges_w1 = list();\n ranges_w2 = list();\n ranges_w3 = list();\n\n s2BinList = list()\n s2BinList = [2,3,4];\n s2FreqList = list();\n s2FreqList = [129, 92, 76];\n\n s3BinList = list();\n s3BinList = [6.6, 8.2, 9.8, 11.4, 13];\n s3FreqList = list();\n s3FreqList =[89, 66, 32, 29, 36];\n \n s4BinList = list();\n s4BinList = [49.375, 84.75, 120.125, 155.5, 190.875, 226.25, 297];\n s4FreqList = list();\n s4FreqList =[203, 30, 11, 4, 3, 2, 1];\n\n ranges_w1 = [0.0, 0.98, 1.5, 4.5, 13.5, 297];\n ranges_w2 = [0.0, 0.5, 1.5, 4.5, 13.5, 297];\n ranges_w3 = [0.0, 0.5, 1.5, 4.5, 13.5, 297];\n\n ranges = ranges_w1;\n midPoint = 0.0;\n \n randomExact = 0.0;\n if(state == 0):\n midPoint = calculateMidpoint(ranges[0], ranges[1]);\n midPoint = 0.0;\n if(state == 1):\n midPoint = calculateMidpoint(ranges[1], ranges[2]);\n midPoint = 1.0;\n if(state == 2):\n midPoint = calculateMidpoint(ranges[2], ranges[3]);\n# midPoint = dataPreparation.random_sampling.generateRandomPointbyDistribution(s2BinList, s2FreqList, 1.5);\n midPoint = 2.821549;\n if(state == 3):\n midPoint = calculateMidpoint(ranges[3], ranges[4]);\n# midPoint = dataPreparation.random_sampling.generateRandomPointbyDistribution(s3BinList, s3FreqList, 4.5);\n midPoint = 8.007;\n if(state == 4):\n midPoint = calculateMidpoint(ranges[4], ranges[5]);\n# midPoint = dataPreparation.random_sampling.generateRandomPointbyDistribution(s4BinList, s4FreqList, 13.5);\n midPoint = 38.42745;\n if(state == 5):\n midPoint = 58.77419;\n return midPoint; \n\n\n# This method calculates the mid point between two points\ndef calculateMidpoint(lowerBound, upperBound):\n return float((lowerBound + upperBound) / 2);\n #return float(random.uniform(lowerBound,upperBound))\n\n#This method generates a random number between the given ranges\ndef generateUniformRandom(lowerbound, uppderBound):\n return float(random.uniform(lowerbound, uppderBound));\n\n# This is the input csv(, delimited)file by command line.\ndataFile = sys.argv[1];\n\n# Main Body of the Program\nnumberOfSamples = 100;\nid = 1;\nwith open(dataFile, 'rb') as csvfile:\n reader = csv.reader(csvfile, delimiter=',')\n i = 0;\n numberOfSamples = 0;\n for row in reader:\n randomN = 0;\n if(i == 0):\n sys.stdout.write(row[0] + \",\" + row[1] + \",\" + row[2] + \",\" + row[3] + \",\" + row[4] + \",\" + row[5] + \",\"+\"month,\"+\"id\"+\"\\n\");\n if(i != 0):\n if(float(row[5]) == 0.0):\n randomN = 100;\n if(float(row[5]) > 0.5 and float(row[5]) <= 1.5):\n randomN = 100;\n if(float(row[5]) > 1.5 and float(row[5]) <= 4.5):\n randomN = 100;\n if(float(row[5]) > 4.5 and float(row[5]) <= 13.5):\n randomN = 100;\n if(float(row[5]) > 13.5 and float(row[5]) <= 26.5):\n randomN = 100;\n if(float(row[5]) > 26.5):\n randomN = 100;\n j = 0;\n for j in range(0, randomN):\n sys.stdout.write(getRandomlyChosenValue(row[0]) + \",\" + getRandomlyChosenValue(row[1]) + \",\"\n + getRandomlyChosenValue(row[2]) + \",\" + getRandomlyChosenValue(row[3]) + \",\"\n + getRandomlyChosenValue(row[4]) + \",\" + row[5] + \"\\n\");\n id = id +1; \n i = i + 1; ","sub_path":"src/Sampling.py","file_name":"Sampling.py","file_ext":"py","file_size_in_byte":5255,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"213989422","text":"\n# itertools.product()\n\n# This tool computes the cartesian product of input iterables.\n# It is equivalent to nested for-loops.\n# For example, product(A, B) returns the same as ((x,y) for x in A for y in B). \n\n\nfrom itertools import product\n\nA = list(input().split()) # The list elements are in string form\nfor i in range(len(A)): # This loop converts each element from string to int\n A[i] = int(A[i])\n#print(A)\nB = list(input().split()) # The list elements are in string form\nfor i in range(len(B)): # This loop converts each element from string to int\n B[i] = int(B[i])\n#print(B)\nprint(list(product(A,B))) # This will print list i.e [(1, 3), (1, 4), (2, 3), (2, 4)]\nprint(*list(product(A,B))) # This will print list items side by side i.e (1, 3) (1, 4) (2, 3) (2, 4)\nprint(*list(product(A,B)), sep=\",\") # This will print list items side by side using comma i.e (1, 3), (1, 4), (2, 3), (2, 4)\n# replace sep = \"\" to get the desired result\n\n\n### BETTER VERSION\n\n# A = [int(x) for x in input().split()]\n# B = [int(y) for y in input().split()]\n\n# print(*itertools.product(A, B))","sub_path":"itertool.py","file_name":"itertool.py","file_ext":"py","file_size_in_byte":1099,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"393488531","text":"__author__ = 'Faaiz'\n\nfrom PySide.QtGui import *\nfrom PySide.QtUiTools import*\n\nclass SourcecodeWidget(QWidget):\n def __init__(self,par):\n QWidget.__init__(self,par)\n self.par = par\n loader=QUiLoader()\n self.dialog = loader.load(\"./sourcecodeWidget.ui\",None)\n label = self.dialog.findChild(QLabel,\"label\")\n layout = QVBoxLayout()\n layout.addWidget(self.dialog)\n self.setLayout(layout)\n #self.dialog.clicked.connect(self.openProject)\n","sub_path":"SourcecodeWidget.py","file_name":"SourcecodeWidget.py","file_ext":"py","file_size_in_byte":499,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"471069094","text":"from experiments.series_prove_of_concept import EvaluationUtils\n\nresult_dir = \"../result_window\"\n\ndata_sets = [\n # \"classic_gutenberg\",\n \"goodreads_genres\",\n # \"german_series\",\n # \"german_books\",\n]\nvectorization_algorithms = [\n # \"bert_sentence_based\",\n # \"flair_sentence_based\",\n # \"doc2vec\",\n # \"doc2vec_sentence_based_100\",\n # \"doc2vec_sentence_based_1000\",\n # \"bert\",\n # \"bert_sentence_based_100\",\n # \"bert_sentence_based_1000\",\n # \"flair\",\n # \"flair_sentence_based_100\",\n # \"flair_sentence_based_1000\",\n # \"bert_sentence_based_100_pt\",\n # \"roberta_sentence_based_100_pt\",\n # \"xlm_sentence_based_100_pt\",\n # \"bert_sentence_based_1000_pt\",\n # \"roberta_sentence_based_1000_pt\",\n # \"xlm_sentence_based_1000_pt\",\n\n \"book2vec\",\n # \"book2vec_concat\",\n \"book2vec_window\"\n]\nfilters = [\n \"no_filter\",\n # \"specific_words_moderate\",\n # \"specific_words_strict\"\n]\n\ntask_names = [\n \"AuthorTask\",\n # \"SeriesTask\",\n # \"GenreTask\",\n]\n\nEvaluationUtils.train_vecs(data_sets=data_sets,\n vectorization_algorithms=vectorization_algorithms,\n filters=filters)\n\nEvaluationUtils.run_evaluation(data_sets=data_sets,\n vectorization_algorithms=vectorization_algorithms,\n filters=filters,\n task_names=task_names,\n result_dir=result_dir)\n\nprint(\n EvaluationUtils.create_paper_table(f\"{result_dir}/simple_series_experiment_table.csv\", f\"{result_dir}/z_table.csv\",\n used_metrics=[\"ndcg\", \"f_prec\", \"f_prec01\", \"f_prec03\", \"f_prec05\",\n \"f_prec10\",\n \"length_metric\"],\n filters=filters))\n","sub_path":"experiments/window_experiments.py","file_name":"window_experiments.py","file_ext":"py","file_size_in_byte":1901,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"101213966","text":"\"\"\"\n Copyright (c) 2020 Intel Corporation\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n\"\"\"\n\nimport os\nimport os.path as osp\nfrom subprocess import run, DEVNULL, CalledProcessError\n\nimport yaml\nfrom yaml import Loader\n\nfrom ote import REID_TOOLS\n\nfrom .base import BaseExporter\nfrom ..registry import EXPORTERS\n\n\n@EXPORTERS.register_module()\nclass ReidExporter(BaseExporter):\n\n def _export_to_openvino(self, args, tools_dir):\n onnx_model_path = self._get_onnx_model_path(args[\"save_model_to\"], args[\"config\"])\n if not os.path.exists(onnx_model_path):\n self._export_to_onnx(args, tools_dir)\n\n with open(args[\"config\"], 'r') as f:\n config = yaml.load(f, Loader=Loader)\n mean_values = str(config['data']['norm_mean'])[1:-1]\n mean_values = str([float(s)*255 for s in mean_values.split(',')])\n scale_values = str(config['data']['norm_std'])[1:-1]\n scale_values = str([float(s)*255 for s in scale_values.split(',')])\n\n # read yaml here to ger mean std\n command_line = f'mo.py --input_model=\"{onnx_model_path}\" ' \\\n f'--mean_values=\"{mean_values}\" ' \\\n f'--scale_values=\"{scale_values}\" ' \\\n f'--output_dir=\"{args[\"save_model_to\"]}\" ' \\\n '--reverse_input_channels'\n\n try:\n run('mo.py -h', stdout=DEVNULL, stderr=DEVNULL, shell=True, check=True)\n except CalledProcessError:\n print('OpenVINO Model Optimizer not found, please source '\n 'openvino/bin/setupvars.sh before running this script.')\n return\n\n run(command_line, shell=True, check=True)\n\n @staticmethod\n def _get_onnx_model_path(save_dir, conf_path):\n return osp.join(save_dir, osp.splitext(osp.basename(conf_path))[0] + '.onnx')\n\n def _export_to_onnx(self, args, tools_dir):\n\n if not os.path.exists(args[\"save_model_to\"]):\n os.makedirs(args[\"save_model_to\"])\n\n onnx_model_path = self._get_onnx_model_path(args[\"save_model_to\"], args[\"config\"])\n\n run(f'python3 {os.path.join(tools_dir, \"convert_to_onnx.py\")} '\n f' --config-file {args[\"config\"]}'\n f' --output-name {onnx_model_path}'\n ' --disable-dyn-axes'\n f' model.load_weights {args[\"load_weights\"]}',\n shell=True,\n check=True)\n\n def _get_tools_dir(self):\n return REID_TOOLS\n","sub_path":"ote/ote/modules/exporters/reid.py","file_name":"reid.py","file_ext":"py","file_size_in_byte":2955,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"257085164","text":"#!/usr/bin/env python3\r\n# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Fri Mar 20 11:40:15 2020\r\n\r\n@author: nilesh-tawari \r\n\"\"\"\r\nimport os\r\nimport os.path\r\nimport ntpath\r\nimport argparse\r\n\r\n\r\n'''\r\nUSAGE: python -i BVEN_C01.0.AOI_01.faa -p BSUB -s 105\r\n'''\r\n\r\n# Parameters\r\nparser = argparse.ArgumentParser(description = 'Rename contigs in fasta file')\r\nparser.add_argument('-i', '--inp_file', help='Input file')\r\nparser.add_argument('-p', '--prefix', help='prefix for contigs, created from genus, species, year and sample id (GSPEYYXXX) e.g. BSUB2064')\r\n\r\nargs = parser.parse_args()\r\ninp_file = os.path.abspath(args.inp_file)\r\nprefix = args.prefix\r\n\r\n###############################################################################\r\ndef path_leaf(path):\r\n \"\"\"\r\n split the path in tail and head\r\n str -> str, str\r\n \"\"\"\r\n head, tail = ntpath.split(path)\r\n return head, tail or ntpath.basename(head)\r\n\r\nout_dir, filename_in = path_leaf(inp_file)\r\nfile_prefix = os.path.splitext(filename_in)[0]\r\nfile_suffix = os.path.splitext(filename_in)[1]\r\nfilename_out = file_prefix + \".renamedc\" + file_suffix\r\nout_file = os.path.join(out_dir, filename_out)\r\n\r\n###############################################################################\r\n\r\n# first determine number of contigs for renaming e.g. 001\r\nnc = 0\r\nwith open(inp_file, 'r') as fasta:\r\n for line in fasta:\r\n if line.startswith('>'):\r\n nc = nc + 1\r\nnc = len(str(nc))\r\n\r\ni = 1\r\nwith open(out_file, 'w') as out_fasta:\r\n with open(inp_file, 'r') as fasta:\r\n for line in fasta:\r\n if line.startswith('>'):\r\n line = '>{0}_C{1} {2}'.format(prefix, str(i).zfill(nc), line[1:])\r\n i = i + 1\r\n out_fasta.writelines(line)\r\nprint('Renamed contigs in the output file {0}'.format(out_file))\r\n","sub_path":"bin/rename_contig.py","file_name":"rename_contig.py","file_ext":"py","file_size_in_byte":1841,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"276516100","text":"class Solution:\n def rotate(self, nums: List[int], k: int) -> None:\n \"\"\"\n Do not return anything, modify nums in-place instead.\n \"\"\"\n k=k%len(nums)\n temp=nums[len(nums)-k:len(nums)]\n for i in range(len(nums)-1,k-1,-1):\n nums[i]=nums[i-k]\n nums[0:k]=temp","sub_path":"189. Rotate Array.py","file_name":"189. Rotate Array.py","file_ext":"py","file_size_in_byte":316,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"559100353","text":"#The total number of months\nimport os\nimport csv\n\n\n# Set path for file\ncsvpath = os.path.join(\"Resources\", \"budget_data.csv\")\n# Read the csvpath\nwith open(csvpath) as csvfile:\n csvreader = csv.reader(csvfile, delimiter=\",\")\n\n month_count = 0\n total = 0\n change = 0 \n prev_PL = 0\n tot_change = 0\n max_inc_value = 0\n max_dec_value = 0\n\n #Skip the header\n next(csvreader, None)\n\n for row in csvreader:\n #The total number of month\n month_count += 1\n #The net total amount of \"Profit/Losses\"\n total += int(row[1])\n # calculation for the first row and the rest \n if month_count ==1:\n prev_PL = int(row[1]) \n else:\n change = int(row[1]) - prev_PL\n tot_change += change\n prev_PL = int(row[1])\n # looking for maximum values in change and taking the date for the maximum found \n if change > max_inc_value:\n max_inc_value = change\n max_inc_date = row[0]\n if change < max_dec_value:\n max_dec_value= change\n max_dec_date = row[0]\n\n # calculation for average change, round up to 2 decimal places\n average_change = round(tot_change / (month_count - 1), 2)\n \n\n\n# printing final statement \nprint(\"Financial Analysis\")\nprint(\"----------------------------\")\nprint(f\"Total Months: {month_count}\") \nprint(f\"Total: ${total}\")\nprint(f\"Average Change: ${average_change}\")\nprint(f\"Greatest Increase in Profits: {max_inc_date} $({max_inc_value})\")\nprint(f\"Greatest Decrease in Profits: {max_dec_date} $({max_dec_value})\")\n\n\n# Open the file and write text\nwith open(os.path.join(\"Analysis\",\"Financial_analysis.txt\"), 'w' ) as textfile:\n print(\"Financial Analysis\", file = textfile)\n print(\"----------------------------\", file = textfile)\n print(f\"Total Months: {month_count}\", file = textfile) \n print(f\"Total: ${total}\", file = textfile)\n print(f\"Average Change: ${average_change}\", file = textfile)\n print(f\"Greatest Increase in Profits: {max_inc_date} $({max_inc_value})\", file = textfile)\n print(f\"Greatest Decrease in Profits: {max_dec_date} $({max_dec_value})\", file = textfile)\n \n","sub_path":"PyBank/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2222,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"443924224","text":"from django.contrib import messages\nfrom django.views.generic.edit import FormView\nfrom .forms import SlackInviteForm\nimport requests\n\n\n\nclass SlackInviteFormView(FormView):\n form_class = SlackInviteForm\n template_name = 'slack_invite.html'\n success_url = '/join-us-on-slack'\n\n def form_valid(self, form):\n for slack in form.cleaned_data['slack']:\n req = requests.post('https://%(subdomain)s.slack.com/api/users.admin.invite?email=%(email)s&token=%(api_key)s&set_active=true' % {\n 'subdomain': slack.subdomain,\n 'api_key': slack.api_key,\n 'email': form.cleaned_data['email']\n })\n\n response_json = req.json()\n\n if not response_json['ok']:\n if response_json['error'] == 'invalid_email':\n form.add_error('email', \"Invalid email, please try again\")\n elif response_json['error'] == 'invalid_auth':\n # bad token! let them know but email for help.\n from django.core.mail import mail_admins\n mail_admins('Bad Slack Token for %s (EOM)' % slack.name, '')\n form.add_error('slack', \"Hmm something is wrong with the Slack configuration for %s our end. We'll take a look ASAP, sorry about that!\" % slack.name)\n elif response_json['error'] == 'already_invited':\n form.add_error('slack', \"Looks like you've already been invited to %s!\" % slack.name)\n \n\n if form.errors:\n return super(SlackInviteFormView, self).form_invalid(form)\n\n messages.success(self.request, \"Success! You've been invited to %s Slack groups.\" % form.cleaned_data['slack'].count())\n return super(SlackInviteFormView, self).form_valid(form)\n","sub_path":"chowda/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1828,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"171025326","text":"from dvc.cli import parse_args\nfrom dvc.command.status import CmdDataStatus\n\n\ndef test_cloud_status(mocker):\n cli_args = parse_args(\n [\n \"status\",\n \"--cloud\",\n \"target1\",\n \"target2\",\n \"--jobs\",\n \"2\",\n \"--remote\",\n \"remote\",\n \"--all-branches\",\n \"--all-tags\",\n \"--all-commits\",\n \"--with-deps\",\n \"--recursive\",\n ]\n )\n assert cli_args.func == CmdDataStatus\n\n cmd = cli_args.func(cli_args)\n m = mocker.patch.object(cmd.repo, \"status\", autospec=True, return_value={})\n\n assert cmd.run() == 0\n\n m.assert_called_once_with(\n cloud=True,\n targets=[\"target1\", \"target2\"],\n jobs=2,\n remote=\"remote\",\n all_branches=True,\n all_tags=True,\n all_commits=True,\n with_deps=True,\n recursive=True,\n )\n","sub_path":"tests/unit/command/test_status.py","file_name":"test_status.py","file_ext":"py","file_size_in_byte":924,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"594138629","text":"import subprocess\nimport argparse\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"outDir\", help=\"Choose the output directory.\\nOutput will be saved to 'outDir/year/LEP_REG_BIN'\")\nparser.add_argument(\"year\", help=\"Choose the year: '2016', '2017' or '2018'\")\nparser.add_argument(\"--lep\", default=None, required=True, help=\"Choose number of leptons to use (REQUIRED)\")\nparser.add_argument(\"--reg\", default=None, required=True, help=\"Choose region to use (REQUIRED)\")\nparser.add_argument(\"--bin\", default=None, required=True, help=\"Choose bin to use (REQUIRED)\")\nargs = parser.parse_args()\n\nfileName = args.outDir+\"/\"+args.year+\"/\"+args.lep+\"_\"+args.reg+\"_\"+args.bin+\"_\"+\"mc_data/\"+\"yields.txt\"\nfakes = 0.0\nbkg = 0.0\ndata = 0.0\nwith open(fileName) as fp:\n line = fp.readline()\n cnt = 1\n while line:\n line = fp.readline()\n line_list = line.strip().split()\n if len(line_list) > 0:\n bkg_category = line_list[0]\n if 'fakes' in bkg_category: fakes = fakes + float(line_list[1])\n if 'BACKGROUND' in bkg_category: bkg = float(line_list[1])\n if 'DATA' in bkg_category: data = float(line_list[1])\n cnt += 1\nif data==0 or fakes==0: SF = 0\nelse: SF = (data - (bkg - fakes)) / fakes\nSF_string = \"ScaleFactor1F\" if \"1F\" in args.reg else \"ScaleFactor2F\" if \"2F\" in args.reg else \"ScaleFactor3F\"\nsubprocess.call([\"echo\", \"%s: %f\"%(SF_string,SF)])","sub_path":"TTHAnalysis/python/plotter/susy-sos/scripts/semiDD_SFs.py","file_name":"semiDD_SFs.py","file_ext":"py","file_size_in_byte":1406,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"177347713","text":"from astropy.utils import isiterable\nimport numpy as np\nfrom scipy import integrate\n\n\n__all__ = [\n 'growth_factor',\n 'growth_function',\n 'growth_function_carroll',\n 'growth_function_derivative',\n]\n\n\ndef growth_function_carroll(redshift, cosmology):\n \"\"\"Computation of the growth function.\n\n Return the growth function as a function of redshift for a given cosmology\n as approximated by Carroll, Press & Turner (1992) Equation 29.\n\n Parameters\n ----------\n redshift : array_like\n Array of redshifts at which to evaluate the growth function.\n cosmology : astropy.cosmology.Cosmology\n Cosmology object providing methods for the evolution history of\n omega_matter and omega_lambda with redshift.\n\n Returns\n -------\n growth : numpy.ndarray, or float if input scalar\n The growth function evaluated at the input redshifts for the given\n cosmology.\n\n Examples\n --------\n >>> import numpy as np\n >>> from astropy.cosmology import default_cosmology\n >>> redshift = np.array([0, 1, 2])\n >>> cosmology = default_cosmology.get()\n >>> growth_function_carroll(redshift, cosmology)\n array([0.781361..., 0.476280..., 0.327549...])\n\n References\n ----------\n doi : 10.1146/annurev.aa.30.090192.002435\n \"\"\"\n if isiterable(redshift):\n redshift = np.asarray(redshift)\n if np.any(redshift < 0):\n raise ValueError('Redshifts must be non-negative')\n\n Om = cosmology.Om(redshift)\n Ode = cosmology.Ode(redshift)\n Dz = 2.5 * Om / (1 + redshift)\n return Dz / (np.power(Om, 4.0/7.0) - Ode + (1 + 0.5*Om) * (1.0 + Ode/70.0))\n\n\ndef growth_factor(redshift, cosmology, gamma=6.0/11.0):\n \"\"\"Computation of the growth factor.\n\n Function used to calculate f(z), parametrised growth factor at different\n redshifts, as described in [1]_ equation 17.\n\n Parameters\n ----------\n redshift : array_like\n Array of redshifts at which to evaluate the growth function.\n cosmology : astropy.cosmology.Cosmology\n Cosmology object providing methods for the evolution history of\n omega_matter and omega_lambda with redshift.\n gamma : float\n Growth index providing an efficient parametrization of the matter\n perturbations.\n\n Returns\n -------\n growth_factor : ndarray, or float if input scalar\n The redshift scaling of the growth factor.\n\n Examples\n --------\n >>> import numpy as np\n >>> from astropy.cosmology import FlatLambdaCDM\n >>> cosmology = FlatLambdaCDM(H0=67.04, Om0=0.3183, Ob0=0.047745)\n >>> growth_factor(0, cosmology)\n 0.5355746155304598\n\n References\n ----------\n .. [1] E. V. Linder, Phys. Rev. D 72, 043529 (2005)\n \"\"\"\n z = redshift\n\n omega_m_z = cosmology.Om(z)\n growth_factor = np.power(omega_m_z, gamma)\n\n return growth_factor\n\n\ndef growth_function(redshift, cosmology, gamma=6.0/11.0):\n \"\"\"Computation of the growth function.\n\n Function used to calculate D(z), growth function at different redshifts,\n as described in [1]_ equation 16.\n\n Parameters\n ----------\n redshift : array_like\n Array of redshifts at which to evaluate the growth function.\n cosmology : astropy.cosmology.Cosmology\n Cosmology object providing methods for the evolution history of\n omega_matter and omega_lambda with redshift.\n gamma : float\n Growth index providing an efficient parametrization of the matter\n perturbations.\n\n Returns\n -------\n growth_function : ndarray\n The redshift scaling of the growth function.\n\n Examples\n --------\n >>> import numpy as np\n >>> from scipy import integrate\n >>> from astropy.cosmology import FlatLambdaCDM\n >>> cosmology = FlatLambdaCDM(H0=67.04, Om0=0.3183, Ob0=0.047745)\n >>> growth_function(0, cosmology)\n 0.7909271056297236\n\n References\n ----------\n .. [1] E. V. Linder, Phys. Rev. D 72, 043529 (2005)\n \"\"\"\n z = redshift\n\n def integrand(x):\n integrand = (growth_factor(x, cosmology, gamma) - 1) / (1 + x)\n return integrand\n\n if isinstance(z, int) or isinstance(z, float):\n integral = integrate.quad(integrand, z, 1100)[0]\n g = np.exp(integral)\n growth_function = g / (1 + z)\n\n elif isinstance(z, np.ndarray):\n growth_function = np.zeros(np.shape(z))\n\n for i, aux in enumerate(z):\n integral = integrate.quad(integrand, aux, 1100)[0]\n g = np.exp(integral)\n growth_function[i] = g / (1 + aux)\n\n else:\n raise ValueError('Redshift must be integer, float or ndarray ')\n\n return growth_function\n\n\ndef growth_function_derivative(redshift, cosmology, gamma=6.0/11.0):\n \"\"\"Computation of the first derivative of the growth function.\n\n Function used to calculate D'(z), derivative of the growth function\n with respect to redshift, described in [1]_ equation 16.\n\n Parameters\n ----------\n redshift : array_like\n Array of redshifts at which to evaluate the growth function.\n cosmology : astropy.cosmology.Cosmology\n Cosmology object providing methods for the evolution history of\n omega_matter and omega_lambda with redshift.\n gamma : float\n Growth index providing an efficient parametrization of the matter\n perturbations.\n\n Returns\n -------\n growth_function_derivative : ndarray, or float if input scalar\n The redshift scaling of the derivative of the growth function.\n\n Examples\n --------\n >>> import numpy as np\n >>> from scipy import integrate\n >>> from astropy.cosmology import FlatLambdaCDM\n >>> cosmology = FlatLambdaCDM(H0=67.04, Om0=0.3183, Ob0=0.047745)\n >>> growth_function_derivative(0, cosmology)\n -0.42360048051025856\n\n References\n ----------\n .. [1] E. V. Linder, Phys. Rev. D 72, 043529 (2005)\n \"\"\"\n z = redshift\n\n growth_function_derivative = - growth_function(z, cosmology, gamma) * \\\n growth_factor(z, cosmology, gamma) / (1.0 + z)\n\n return growth_function_derivative\n","sub_path":"skypy/power_spectrum/_growth.py","file_name":"_growth.py","file_ext":"py","file_size_in_byte":6055,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"279026803","text":"# -*- coding: utf-8 -*-\n# Part of Odoo. See LICENSE file for full copyright and licensing details.\n# http://www.pospal.cn/openplatform/productapi.html\nimport json\nimport time\nimport datetime\nimport requests\nimport sys\n# from source.odoo\n\nfrom odoo import api, fields, models\nimport _hashlib\nimport types\n\n\nfrom .bn_2dfire_common import *\nfrom .bn_2dfire_tools import *\nfrom .bn_2dfire_constant import *\n\n\n\n\nclass bn_2dfire_order(models.Model):\n _name = 'bn.2dfire.order'\n _description = '2dfire order'\n ordersn = fields.Char(string=u'订单编号')\n orderVo = fields.One2many('bn.2dfire.order.ordervo', 'orderids', string=u'订单流水号')\n orderlist = fields.One2many('bn.2dfire.order.orderlist', 'orderids', string=u'商品清单')\n totalPayVo = fields.One2many('bn.2dfire.order.totalpayvo', 'orderids', string=u'实际支付')\n payVo = fields.One2many('bn.2dfire.order.payvo', 'orderids', string=u'支付金额清单')\n serviceBillVo = fields.One2many('bn.2dfire.order.servicebillvo', 'orderids', string=u'账单')\n kindpayvo = fields.One2many('bn.2dfire.order.kindpayvolist', 'orderids', string=u'kindpayvo支付方式清单')\n entityId = fields.Char(string=u'店entity号码')\n store_code = fields.Char(string=u'门店代号')\n store_name = fields.Char(string=u'门店名称')\n _sql_constraints = [('unique_ordersn', 'UNIQUE(ordersn)', 'foo must be unique')]\n\n\nclass bn_2dfire_order_ordervo(models.Model):\n _name = 'bn.2dfire.order.ordervo'\n _description = '2dfire order ordervo'\n orderids = fields.Many2one('bn.2dfire.order', u'订单', ondelete='cascade')\n openTime = fields.Datetime(string=u'开单时间')\n seatName = fields.Char(string=u'座位名称')\n seatCode = fields.Char(string=u'座位CODE')\n peopleCount = fields.Char(string=u'就餐人数')\n orderId = fields.Char(string=u'订单Id')\n innerCode = fields.Char(string=u'账单号')\n code = fields.Char(string=u'单号 ')\n simpleCode = fields.Char(string=u'全局单号')\n orderType = fields.Char(string=u'订单类型')\n endTime = fields.Datetime(string=u'结单时间')\n\n orderFrom = fields.Char(string=u'单据来源 ')\n memo = fields.Char(string=u'备注')\n entityId = fields.Char(string=u'店entity号码')\n store_code = fields.Char(string=u'门店代号')\n store_name = fields.Char(string=u'门店名称')\n\n\nclass bn_2dfire_order_TotalPayVo(models.Model):\n _name = 'bn.2dfire.order.totalpayvo'\n _description = 'bn.2dfire.order.totalpayvo'\n orderids = fields.Many2one('bn.2dfire.order', u'订单', ondelete='cascade')\n currDate = fields.Datetime(string=u'发生日期')\n sourceAmount = fields.Float(string=u'原始费用')\n discountAmount = fields.Float(string=u'折后费用')\n resultAmount = fields.Float(string=u'应付总额')\n receiveAmount = fields.Float(string=u'实收总额')\n outFee = fields.Float(string=u'外送费')\n operateDate = fields.Datetime(string=u'结账时间 ')\n simpleCode = fields.Char(string=u'开发票额')\n invoice = fields.Float(string=u'结单时间')\n couponDiscount = fields.Float(string=u'券优惠金额 ')\n entityId = fields.Char(string=u'店entity号码')\n store_code = fields.Char(string=u'门店代号')\n store_name = fields.Char(string=u'门店名称')\n\n\nclass bn_2dfire_order_PayVo(models.Model):\n _name = 'bn.2dfire.order.payvo'\n _description = 'bn.2dfire.order.payvo'\n\n orderids = fields.Many2one('bn.2dfire.order', u'订单', ondelete='cascade')\n kindPayId = fields.Char(string=u'付款带吗 ')\n kindPayName = fields.Char(string=u'付款方式')\n kindPaySortName = fields.Char(string=u'支付类型')\n fee = fields.Float(string=u'实收额')\n type = fields.Char(string=u'类型方式')\n operatorCode = fields.Char(string=u'收银员编码')\n operator = fields.Char(string=u'收银员')\n payTime = fields.Datetime(string=u'收银时间')\n pay = fields.Float(string=u'现收金额')\n charge = fields.Float(string=u'找零')\n entityId = fields.Char(string=u'店entity号码')\n store_code = fields.Char(string=u'门店代号')\n store_name = fields.Char(string=u'门店名称')\n\n\nclass bn_2dfire_order_kindPayVoList(models.Model):\n _name = 'bn.2dfire.order.kindpayvolist'\n _description = 'bn.2dfire.order.kindpayvolist'\n orderids = fields.Many2one('bn.2dfire.order', u'订单', ondelete='cascade')\n name = fields.Char(string=u'Name')\n kind = fields.Char(string=u'kind')\n kindPaySortNm = fields.Char(string=u'kindPaySortNm')\n code = fields.Char(string=u'code')\n kindid = fields.Char(string=u'kindid')\n entityId = fields.Char(string=u'店entity号码')\n store_code = fields.Char(string=u'门店代号')\n store_name = fields.Char(string=u'门店名称')\n\n\nclass bn_2dfire_order_ServiceBillVo(models.Model):\n _name = 'bn.2dfire.order.servicebillvo'\n _description = 'bn.2dfire.order.servicebillvo'\n orderids = fields.Many2one('bn.2dfire.order', u'订单', ondelete='cascade')\n originAmount = fields.Float(string=u'原始消费金额 ')\n discountAmount = fields.Float(string=u'折后费用')\n originServiceCharge = fields.Float(string=u'原始服务费金额')\n originLeastAmount = fields.Float(string=u'原始最低消费')\n agioAmount = fields.Float(string=u'折后消费金额')\n agioServiceCharge = fields.Float(string=u'折后服务费')\n agioLeastAmount = fields.Float(string=u'折后最低消费')\n originReceivablesAmount = fields.Float(string=u'原始应收金额')\n agioReceivablesAmount = fields.Float(string=u'折后应收金额')\n finalAmount = fields.Float(string=u'最终应收金额')\n originTotal = fields.Float(string=u'原始总金额')\n agioTotal = fields.Float(string=u'折后总金额')\n reserveAmount = fields.Float(string=u'预付金额')\n outFee = fields.Float(string=u'外送费')\n notIncludeAmount = fields.Float(string=u'不计营业额总额')\n entityId = fields.Char(string=u'店entity号码')\n store_code = fields.Char(string=u'门店代号')\n store_name = fields.Char(string=u'门店名称')\n\n\nclass bn_2dfire_order_OderList(models.Model):\n _name = 'bn.2dfire.order.orderlist'\n _description = 'bn.2dfire.order.orderlist'\n # 订单详情列表\n orderids = fields.Many2one('bn.2dfire.order', u'订单', ondelete='cascade')\n orderId = fields.Char(string=u'订单ID')\n kind = fields.Char(string=u'点菜类型')\n name = fields.Char(string=u'品名', size=1500)\n makeName = fields.Char(string=u'做法')\n accountNum = fields.Float(string=u'结账数量')\n price = fields.Float(string=u'单价')\n ratio = fields.Float(string=u'折扣率')\n fee = fields.Float(string=u'金额')\n ratioFee = fields.Float(string=u'折后金额')\n specDetailName = fields.Char(string=u'规格名')\n accountUnit = fields.Char(string=u'结账单位')\n isMemberPrice = fields.Float(string=u'是否使用会员价(1.00表示使用会员价,0.00表示不使用)')\n menuId = fields.Char(string=u'商品编码')\n num = fields.Char(string=u'num')\n kindMenuName = fields.Char(string=u'菜类名 ', size=1500)\n rootKindMenuName = fields.Char(string=u'根类名 ', size=1500)\n giveDish = fields.Boolean(string=u'是否赠')\n canceled = fields.Boolean(string=u'是否取消(true:取消 false:没有取消)')\n memo = fields.Char(string=u'备注(退/赠理由)', size=1500)\n opUserName = fields.Char(string=u'操作人姓名(退/赠操作人)')\n entityId = fields.Char(string=u'店entity号码')\n store_code = fields.Char(string=u'门店代号')\n store_name = fields.Char(string=u'门店名称')\n\n\ndef get_2dfire_order_from_api(self, procdate):\n print('get_2dfire_order_from_api')\n print(procdate)\n MY_URL = self.env['bn.2dfire.url'].search([('code', '=', 'orderlist')])\n # MY_URL = self.env['bn.2dfire.url'].search([('code', '=', 'orderlist-v20')])\n\n # procdate= datetime.datetime.now() - datetime.timedelta(days=1)\n # stores = self.env['bn.2dfire.branchs'].get_vaild_branchs()\n stores = self.env['bn.2dfire.branchs'].search_bycode('00465628')\n # stores = self.env['bn.2dfire.branchs'].search_bycode('00401742')\n for store in stores:\n appid = store['appids']\n para = {\n 'para_my_url': MY_URL,\n 'para_my_appid': appid,\n 'para_my_store': store,\n 'para_connection': self,\n }\n\n data = {\n \"currdate\": procdate,\n \"orderids\": None\n }\n\n recordset = bn_2dfire_connect_api(para).Get_ResultAll(data)\n if recordset is not None:\n if 'model' in recordset:\n insert_2dfire_order(self, recordset['model'], store)\n\n return True\n\n\ndef get_2dfire_order_detail_from_api(self, procdate):\n print('get_2dfire_order_detail_from_api')\n MY_URL = self.env['bn.2dfire.url'].search([('code', '=', 'orderdetail')])\n\n # procdate= datetime.datetime.now() - datetime.timedelta(days=1)\n currdate = procdate.strftime(\"%Y-%m-%d\").replace('-', '')\n print(procdate)\n stores = self.env['bn.2dfire.branchs'].get_vaild_branchs()\n for store in stores:\n # print store['code']+'===>'+store['name']\n appid = store['appids']\n # print appid\n para = {\n 'para_my_url': MY_URL,\n 'para_my_appid': appid,\n 'para_my_store': store,\n 'para_connection': self,\n }\n\n orderlist = self.env['bn.2dfire.order.ordervo'].search(\n [('innerCode', 'like', currdate + '____'), ('entityId', '=', store['code'])])\n ld_by_orderid = []\n for rec in orderlist:\n ld_by_orderid.append(str(rec['orderId']))\n\n local_reord_number = get_local_record_number_2dfire_order_detail(self, str(ld_by_orderid))\n\n split_orderlist = split_order_byMaxNum(ld_by_orderid)\n ords = []\n remote_records = []\n # r001=[]\n for rec in split_orderlist:\n\n data = {\n \"currdate\": procdate,\n \"orderids\": str(rec)\n }\n\n recordset = bn_2dfire_connect_api(para).Get_ResultAll(data)\n\n if recordset is not None:\n if 'model' in recordset:\n\n # r001.append(recordset['model'])\n for rc in recordset['model']:\n remote_records.append(rc)\n # print remote_records\n print(len(remote_records))\n if len(remote_records) != 0 and local_reord_number != len(remote_records):\n # if len(remote_records) != 0 and local_reord_number == 0:\n print('local_reord_number')\n print(local_reord_number)\n\n print('remote_records')\n print(len(remote_records))\n\n insert_2dfire_order_detail(self, remote_records)\n\n return True\n\n\ndef insert_2dfire_order(self, recordsets, certifate):\n if (len(recordsets) == 0):\n return\n\n vals_order_insert = []\n vals_order_insert = {\n 'entityId': certifate['code'],\n 'store_code': certifate['code'],\n 'store_name': certifate['name'],\n 'ordersn': None,\n 'orderVo': None,\n 'totalPayVo': None,\n 'payVo': None,\n 'serviceBillVo': None,\n 'kindpayvo': None,\n }\n\n for rec in recordsets:\n\n vals_ordervo = []\n ov = rec['orderVo']\n r01 = self.env['bn.2dfire.order'].search([('ordersn', '=', ov['orderId'])])\n print(ov['innerCode'])\n\n if r01:\n continue\n\n print ( ov['entityId'],\n ov['innerCode'],\n bn_timestamp_to_date(ov['openTime']).strftime(BN_DATAFORMAT),\n bn_timestamp_to_date(ov['endTime']).strftime(BN_DATAFORMAT))\n\n ordevo_set = {\n 'orderId': ov['orderId'],\n \"innerCode\": ov['innerCode'],\n \"entityId\": ov['entityId'],\n \"openTime\": bn_timestamp_to_date(ov['openTime']).strftime(BN_DATAFORMAT),\n \"peopleCount\": ov['peopleCount'],\n \"code\": ov['code'],\n # \"simpleCode\": ov['simpleCode'],\n \"endTime\": bn_timestamp_to_date(ov['endTime']).strftime(BN_DATAFORMAT),\n \"orderFrom\": ov['orderFrom'],\n \"orderType\": ov['orderType'],\n \"memo\": ov.get('memo', ''),\n }\n vals_ordervo.append((0, 0, ordevo_set))\n vals_order_insert.update({\"ordersn\": ov['orderId']})\n vals_order_insert.update({\"orderVo\": vals_ordervo})\n\n vals_totalPayVo = []\n if 'totalPayVo' in rec:\n totalPayVo = rec['totalPayVo']\n\n totalPayVo_set = {\n 'currDate': bn_timestamp_to_date(totalPayVo['currDate']).strftime(BN_DATAFORMAT),\n \"sourceAmount\": totalPayVo['sourceAmount'],\n \"discountAmount\": totalPayVo['discountAmount'],\n \"resultAmount\": totalPayVo['resultAmount'],\n \"receiveAmount\": totalPayVo['receiveAmount'],\n \"outFee\": totalPayVo['outFee'],\n \"operateDate\": bn_timestamp_to_date(totalPayVo['operateDate']).strftime(BN_DATAFORMAT),\n \"invoice\": totalPayVo['invoice'],\n \"couponDiscount\": totalPayVo['couponDiscount'],\n }\n vals_totalPayVo.append((0, 0, totalPayVo_set))\n vals_order_insert.update({\"totalPayVo\": vals_totalPayVo})\n\n #插入支付清单\n vals_payVoList = []\n\n if 'payVoList' in rec:\n # if not rec['payVoList']:\n # print ('hello')\n\n for payVoList in rec['payVoList']:\n payVoList_set = {\n 'entityId': payVoList['entityId'],\n \"type\": payVoList['type'],\n \"kindPayId\": payVoList['kindPayId'],\n \"kindPayName\": payVoList['kindPayName'],\n \"kindPaySortName\": payVoList['kindPaySortName'],\n \"fee\": payVoList['fee'],\n \"operator\": payVoList['operator'],\n \"payTime\": bn_timestamp_to_date(payVoList['payTime']).strftime(BN_DATAFORMAT),\n \"pay\": payVoList['pay'],\n \"charge\": payVoList['charge'],\n }\n vals_payVoList.append((0, 0, payVoList_set))\n vals_order_insert.update({\"payVo\": vals_payVoList})\n\n #插入收款方式清单\n vals_kindPayVoList = []\n if 'kindPayVoList' in rec:\n\n for kindPayVoList in rec['kindPayVoList']:\n kindPayVoList_set = {\n 'name': kindPayVoList['name'],\n \"kind\": kindPayVoList['kind'],\n \"kindid\": kindPayVoList['id'],\n \"kindPaySortNm\": kindPayVoList['kindPaySortNm'],\n }\n vals_kindPayVoList.append((0, 0, kindPayVoList_set))\n vals_order_insert.update({\"kindpayvo\": vals_kindPayVoList})\n\n #插入账单明细\n vals_serviceBillVo = []\n serviceBillVo = rec['serviceBillVo']\n serviceBillVo_set = {\n 'agioAmount': serviceBillVo['agioAmount'],\n \"agioLeastAmount\": serviceBillVo['agioLeastAmount'],\n \"agioReceivablesAmount\": serviceBillVo['agioReceivablesAmount'],\n \"agioServiceCharge\": serviceBillVo['agioServiceCharge'],\n 'agioTotal': serviceBillVo['agioTotal'],\n \"discountAmount\": serviceBillVo['discountAmount'],\n \"entityId\": serviceBillVo['entityId'],\n \"finalAmount\": serviceBillVo['finalAmount'],\n \"notIncludeAmount\": serviceBillVo['notIncludeAmount'],\n \"originAmount\": serviceBillVo['originAmount'],\n \"originLeastAmount\": serviceBillVo['originLeastAmount'],\n \"originReceivablesAmount\": serviceBillVo['originReceivablesAmount'],\n \"originServiceCharge\": serviceBillVo['originServiceCharge'],\n \"originTotal\": serviceBillVo['originTotal'],\n \"outFee\": serviceBillVo['outFee'],\n \"reserveAmount\": serviceBillVo['reserveAmount'],\n }\n vals_serviceBillVo.append((0, 0, serviceBillVo_set))\n vals_order_insert.update({\"serviceBillVo\": vals_serviceBillVo})\n\n print(vals_order_insert)\n self.env['bn.2dfire.order'].create(vals_order_insert)\n self.env.cr.commit()\n\n return True\n\n\ndef insert_2dfire_order_detail(self, recordsets):\n if (len(recordsets) == 0):\n return\n vals = []\n for rec in recordsets:\n r01 = self.env['bn.2dfire.order.orderlist'].search([('orderId', '=', rec['orderId'])])\n\n print(rec['orderId'])\n\n if r01:\n continue\n\n\n vals = {\n 'entityId': rec['entityId'],\n 'kind': rec['kind'],\n 'fee': rec['fee'],\n 'ratio': rec['ratio'],\n 'accountNum': rec['accountNum'],\n 'isMemberPrice': rec['isMemberPrice'],\n 'menuId': rec['menuId'],\n 'price': rec['price'],\n 'giveDish': rec['giveDish'],\n 'num': rec['num'],\n 'canceled': rec['canceled'],\n 'ratioFee': rec['ratioFee'],\n 'accountUnit': rec['accountUnit'],\n 'entityId': rec['entityId'],\n 'rootKindMenuName': rec['rootKindMenuName'],\n 'kindMenuName': rec['kindMenuName'],\n 'name': rec['name'],\n 'orderId': rec['orderId'],\n 'orderids':self.env['bn.2dfire.order'].search([('ordersn','=',rec['orderId'])]).id\n }\n r01 = self.env['bn.2dfire.order.orderlist'].create(vals)\n\n return True\n\n\ndef get_local_record_number_2dfire_order_detail(self, orders):\n if len(orders) == 2:\n return 0\n else:\n orders = orders.replace('[', '(')\n orders = orders.replace(']', ')')\n sql = \"\"\" \n select count(*) \n FROM bn_2dfire_order_orderlist\n WHERE \"orderId\" in {0}\n \"\"\"\n sql = sql.format(orders.replace('[', '('))\n cr = self._cr\n cr.execute(sql)\n res = cr.fetchall()\n if len(res) != 0:\n recno = res[0][0]\n return recno\n else:\n return 0\n\n\ndef check_pos_line_not_in_pos_master(self):\n sql=\"\"\"\n SELECT\n \"orderId\",\n \"menuId\",\n price,\n num,\n \"ratioFee\",\n NAME,\n \"entityId\" \n FROM\n bn_2dfire_order_orderlist \n WHERE\n \"orderId\" IN (\n SELECT\n bn_2dire_orderid \n FROM\n pos_order \n WHERE\n ID NOT IN ( SELECT DISTINCT order_id FROM pos_order_line ) \n\t ) \n \"\"\"\n\n\n cr = self._cr\n cr.execute(sql)\n res = cr.fetchall()\n return res\n\n\ndef insert_pos_line_not_in_pos_master(self,processlist):\n\n if len(processlist)==0 :\n return False\n\n for item in processlist:\n pos_order_id=self.env['pos.order'].search([('bn_2dire_orderid','=',item[0])]).id\n product_id=self.env['product.product'].search([('default_code', '=', item[1])]).id\n price_tmp=item[2]\n num_tmp=item[3]\n ratiofree_tmp=item[4]\n name_tmp=item[5]\n branch=self.env['bn.2dfire.branchs'].search([('code', '=', item[6])])\n company_id=branch['company_id'].id\n print(item[0])\n\n val={\n 'company_id': company_id,\n 'order_id': pos_order_id,\n 'name': name_tmp,\n 'product_id': product_id,\n 'price_unit': price_tmp,\n 'price_subtotal': ratiofree_tmp,\n 'price_subtotal_incl': ratiofree_tmp,\n 'qty': num_tmp,\n }\n self.env['pos.order.line'].create(val)\n\n return True\n\n","sub_path":"odoofile/addons/bn_2dfire/models/bn_2dfire_order.py","file_name":"bn_2dfire_order.py","file_ext":"py","file_size_in_byte":20026,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"392205468","text":"import sys, resource\r\nsys.setrecursionlimit(1000000)\r\n# resource.setrlimit(resource.RLIMIT_STACK, (2**29, -1))\r\n\r\nN, D, X, Y = [int(x) for x in input().split()]\r\n\r\narr = [int(x) for x in input().split()]\r\n\r\ndef search(pos, X, Y, D):\r\n if pos == D: return 0\r\n return min(search(pos + 1, X, arr[pos], D) + abs(Y - arr[pos]), search(pos + 1, arr[pos], Y, D) + abs(X - arr[pos]))\r\n \r\nprint(search(0, X, Y, D))","sub_path":"july easy/power.py","file_name":"power.py","file_ext":"py","file_size_in_byte":414,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"292922368","text":"import os\nimport inspect\nimport time\nfrom utils.common.log import logger\nfrom selenium import webdriver\nfrom selenium.webdriver.support.select import Select\nfrom selenium.webdriver.common.action_chains import ActionChains\nfrom selenium.webdriver.common.by import By\nfrom selenium.common.exceptions import NoSuchElementException, NoSuchFrameException, JavascriptException, \\\n ScreenshotException\nfrom utils.config import DRIVER_PATH, REPORT_PATH\n\nCHROME_DRIVER_PATH = os.path.join(DRIVER_PATH, 'chromedriver.exe')\n\nTYPES = {'chrome': webdriver.Chrome, 'firefox': webdriver.Firefox, 'ie': webdriver.Ie}\nEXECUTABLE_PATH = {'chrome': CHROME_DRIVER_PATH, 'firefox': ''}\n\n\nclass UnSupportBrowserTypeError(Exception):\n pass\n\n\nclass Browser(object):\n def __init__(self, browser_type):\n super(Browser, self).__init__()\n self.driver = None\n self._type = browser_type\n if self._type in TYPES:\n self.browser = TYPES[self._type]\n else:\n raise UnSupportBrowserTypeError(\"UnSupport browser type, support %s only\" % ''.join(TYPES.keys()))\n self.accept_next_alert = None\n\n def browser_init(self, maximize_windows=True, implicitly_wait=10):\n logger.info('driver init start, opened browser')\n self.driver = self.browser(executable_path=EXECUTABLE_PATH[self._type])\n if maximize_windows:\n self.driver.maximize_window()\n self.driver.implicitly_wait(implicitly_wait)\n self.accept_next_alert = True\n return self\n\n # get driver\n def get_driver(self):\n return self.driver\n\n # Page factory\n def find_element(self, *loc):\n try:\n return self.driver.find_element(*loc)\n except NoSuchElementException as e:\n logger.error(\"can NOT find element by {0} with {1}\".format(loc[0], loc[1]))\n logger.exception(e.msg)\n\n def find_elements(self, *loc):\n try:\n return self.driver.find_elements(*loc)\n except NoSuchElementException as e:\n logger.error(\"can NOT find element {0} with {1}\".format(loc[0], loc[1]))\n logger.exception(e.msg)\n\n def find_name(self, _name):\n try:\n return self.driver.find_element(By.NAME, _name)\n except NoSuchElementException as e:\n logger.error(\"can NOT find element by {}\".format(_name))\n logger.exception(e.msg)\n\n def finds_name(self, _name):\n try:\n return self.driver.find_elements(By.NAME, _name)\n except NoSuchElementException as e:\n logger.error(\"can NOT find elements by {}\".format(_name))\n logger.exception(e.msg)\n\n def find_id(self, _id):\n try:\n return self.driver.find_element(By.ID, _id)\n except NoSuchElementException as e:\n logger.error(\"can NOT find element by {}\".format(_id))\n logger.exception(e.msg)\n\n def finds_id(self, _id):\n try:\n return self.driver.find_elements(By.ID, _id)\n except NoSuchElementException as e:\n logger.error(\"can NOT find elements by {}\".format(_id))\n logger.exception(e.msg)\n\n def find_class(self, _class_name):\n try:\n return self.driver.find_element(By.CLASS_NAME, _class_name)\n except NoSuchElementException as e:\n logger.error(\"can NOT find element by {}\".format(_class_name))\n logger.exception(e.msg)\n\n def finds_class(self, _class_name):\n try:\n return self.driver.find_elements(By.CLASS_NAME, _class_name)\n except NoSuchElementException as e:\n logger.error(\"can NOT find elements by {}\".format(_class_name))\n logger.exception(e.msg)\n\n def find_xpath(self, label_name=None, attr_name=None, value=None):\n try:\n if label_name and attr_name:\n return self.driver.find_element(By.XPATH,\n \"//{0}[contains(@{1}, '{2}')]\".format(label_name, attr_name, value))\n # The value can be xpath directly\n elif value is not None:\n return self.driver.find_element(by=By.XPATH, value=value)\n except NoSuchElementException as e:\n logger.error(\"can NOT find element by such a xpath\")\n logger.exception(e.msg)\n\n def finds_xpath(self, label_name=None, att_name=None, value=None):\n try:\n if label_name and att_name:\n return self.driver.find_elements(By.XPATH,\n \"//{0}[contains(@{1}, '{2}')]\".format(label_name, att_name, value))\n else:\n return self.driver.find_elements(by=By.XPATH, value=value)\n except NoSuchElementException as e:\n logger.error(\"can NOT find elements by such a xpath\")\n logger.exception(e.msg)\n\n def find_xpath_by_text(self, label_name, text_val):\n try:\n web_ele = self.driver.find_element(By.XPATH, \"//{0}[contains(text(), '{1}')]\".format(label_name, text_val))\n return web_ele\n except NoSuchElementException as e:\n logger.error(\"can NOT find element by such a xpath\")\n logger.exception(e.msg)\n\n def find_css(self, css_value=None):\n \"\"\"\n :param css_value: css path value\n :return: web element\n \"\"\"\n try:\n if css_value:\n return self.driver.find_element(by=By.CSS_SELECTOR, value=css_value)\n except NoSuchElementException as e:\n logger.error(\"can NOT find element by such a css path\")\n logger.exception(e.msg)\n\n def finds_css(self, css_value=None):\n try:\n if css_value:\n return self.driver.find_elements(by=By.CSS_SELECTOR, value=css_value)\n except NoSuchElementException as e:\n logger.error(\"can NOT find elements by such a css path\")\n logger.exception(e.msg)\n\n def save_screen_shot(self):\n day = time.strftime(\"%Y%m%d\", time.localtime(time.time()))\n screen_shot_path = os.path.join(REPORT_PATH, 'screen_shot_{0}'.format(day))\n if not os.path.exists(screen_shot_path):\n os.makedirs(screen_shot_path)\n name = inspect.stack()[1][3]\n screen_shot_file = os.path.join(screen_shot_path, '{0}.png'.format(name))\n try:\n self.driver.save_screenshot(screen_shot_file)\n logger.info(\"screen shot {0} has been saved in {1}\".format(name, screen_shot_path))\n except ScreenshotException as e:\n logger.exception(e.msg)\n\n # Encapsulate selenium method\n def right_click(self, web_element):\n ActionChains(self.driver).context_click(web_element).perform()\n\n def double_click(self, web_element):\n ActionChains(self.driver).double_click(web_element).perform()\n\n # hover: move mouse to special element\n def hover(self, web_element):\n ActionChains(self.driver).move_to_element(web_element).perform()\n\n @staticmethod\n def select_by_index(web_element, index=0):\n Select(web_element).select_by_index(index)\n\n @staticmethod\n def select_by_value(web_element, value):\n Select(web_element).select_by_value(value)\n\n @staticmethod\n def select_by_text(web_element, text):\n Select(web_element).select_by_visible_text(text)\n\n def refresh(self):\n self.driver.refresh()\n\n @staticmethod\n def clear(web_element):\n web_element.clear()\n\n @staticmethod\n def click(web_element):\n web_element.click()\n time.sleep(0.25)\n\n @staticmethod\n def send_keys(web_element, value, clear_first=True):\n \"\"\"\n :param web_element: web element found by driver\n :param value: keys to send\n :param clear_first: flag for clear input box\n :return: None\n \"\"\"\n if clear_first:\n web_element.clear()\n web_element.send_keys(value)\n\n @staticmethod\n def get_text(web_element):\n return web_element.text\n\n @staticmethod\n def submit(web_element):\n web_element.submit()\n\n @staticmethod\n def get_attr(web_element, attr_name):\n attr_value = web_element.get_attribute(attr_name)\n logger.debug(\"the attribute {} is {}\".format(attr_name, attr_value))\n return attr_value\n\n def upload_file(self, web_element, path):\n \"\"\"\n :param web_element: web element of upload button\n :param path: path of the upload file\n :return: None\n \"\"\"\n self.send_keys(web_element, value=path)\n\n # run a JavaScript script\n def run_js_script(self, js):\n try:\n self.driver.execute_script(js)\n except JavascriptException as e:\n logger.exception(e.msg)\n\n def switch_frame(self, frame_attr=None, web_element=None):\n \"\"\"\n :param frame_attr: attr(id or name) of frame\n :param web_element: need to locate frame first, if no id or name\n :return:\n \"\"\"\n try:\n if frame_attr:\n self.driver.switch_to.frame(frame_attr)\n else:\n self.driver.switch_to.frame(web_element)\n time.sleep(0.5)\n except NoSuchFrameException as e:\n logger.error(\"No such frame to switch by id or name\")\n logger.exception(e.msg)\n\n def close(self):\n self.driver.close()\n logger.info(\"web has been closed\")\n\n def quit(self):\n self.driver.quit()\n logger.info(\"browser has been quited\")\n","sub_path":"test/common/browser.py","file_name":"browser.py","file_ext":"py","file_size_in_byte":9505,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"275144396","text":"def st(string1, string2):\r\n if len(string1) == 0:\r\n return 0\r\n a = string2\r\n if string1[0] in a:\r\n return 1 + st(string1[1:], string2[0:])\r\n if string1[0] not in a:\r\n return 0 + st(string1[1:], string2[0:])\r\nprint(st('geese', 'elate'))\r\nprint(st('dinner', 'syrup'))\r\nprint(st('gattaca', 'aggtccaggcgc'))\r\ndef recursivesort(alist):\r\n def helper(sorting,already):\r\n new=[]\r\n if len(sorting)==0:\r\n return already\r\n else:\r\n x=min(sorting)\r\n sorting.remove(x)\r\n new.append(x)\r\n return helper(sorting,already+new)\r\n return helper(alist,[])\r\n","sub_path":"assign_ex/csfrall ass/scnd/sorting1.py","file_name":"sorting1.py","file_ext":"py","file_size_in_byte":650,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"541099556","text":"#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n# Created on 2017-08-10 14:01:42\n# Project: sport_list\n\nfrom pyspider.libs.base_handler import *\nimport xlwt\nfrom xlrd import open_workbook\nfrom xlutils.copy import copy\n\n\nclass Handler(BaseHandler):\n\n def __init__(self):\n self.row = 0\n workbook = xlwt.Workbook(encoding='utf-8')\n workbook.add_sheet('team')\n workbook.save(\"nba_player_test.xls\")\n\n crawl_config = {\n }\n\n @every(minutes=1)\n def on_start(self):\n self.crawl('http://nba.stats.qq.com/team/list.htm', callback=self.index_page, fetch_type='js')\n\n def index_page(self, response):\n teams_list = response.doc('div[class=\"teams-list\"]').find('a[href^=\"http://nba.stats.qq.com/team/?id=\"]')\n for each in teams_list.items():\n self.crawl(each.attr.href, callback=self.player_page, fetch_type='js')\n\n def player_page(self, response):\n\n rb = open_workbook('nba_player_test.xls')\n wb = copy(rb)\n ws = wb.get_sheet(0)\n\n a = []\n team_name = response.doc(\"h1\").text()\n ws.write(0, self.row, team_name)\n player_list = response.doc('table[class=\"tbl-fixed\"]').find('a[href*=\"type=player\"]')\n temp_tag = 1\n for each in player_list.items():\n name = each.text()\n a.append(name)\n ws.write(temp_tag, self.row, name)\n temp_tag += 1\n\n self.row += 1\n wb.save('nba_player_test.xls')\n\n return a","sub_path":"PySpider/nba_player.py","file_name":"nba_player.py","file_ext":"py","file_size_in_byte":1486,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"316972586","text":"# -*- mode: python; fill-column: 100; comment-column: 100; -*-\n\nimport os\nimport sys\nimport unittest\nfrom selenium.common.exceptions import TimeoutException\n\nsys.path.append(\n os.path.abspath(\n os.path.join(\n os.path.dirname(__file__),\n os.path.pardir)))\nimport base_test\n\n\nclass PageLoadTimeoutTest(base_test.WebDriverBaseTest):\n\n def test_should_timeout_on_page_load_taking_too_long(self):\n self.driver.set_page_load_timeout(0.01)\n with self.assertRaises(TimeoutException):\n self.load_page()\n\n def test_should_not_timeout_on_page_load(self):\n self.driver.set_page_load_timeout(30)\n self.load_page()\n pass\n\n def load_page(self):\n self.driver.get(\n self.webserver.where_is('timeouts/res/page_load_timeouts_tests.html'))\n\nif __name__ == \"__main__\":\n unittest.main()\n","sub_path":"misc/webdriver-w3c-tests/timeouts/page_load_timeouts_tests.py","file_name":"page_load_timeouts_tests.py","file_ext":"py","file_size_in_byte":873,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"197589945","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/robertoalotufo/Library/Enthought/Canopy_32bit/User/lib/python2.7/site-packages/ia636/iaimginfo.py\n# Compiled at: 2014-08-21 22:30:04\nimport numpy as np\n\ndef iaimginfo(f):\n t = type(f)\n if t != np.ndarray:\n return 'Not a ndarray. It is %s' % (t,)\n else:\n dt = f.dtype\n if dt == 'bool':\n return '%s %s %s %s %s' % (t, np.shape(f), f.dtype, f.min(), f.max())\n if dt == 'uint8':\n return '%s %s %s %d %d' % (t, np.shape(f), f.dtype, f.min(), f.max())\n return '%s %s %s %f %f' % (t, np.shape(f), f.dtype, f.min(), f.max())","sub_path":"pycfiles/ia636-0.11.8.macosx-10.6-i386.tar/iaimginfo.py","file_name":"iaimginfo.py","file_ext":"py","file_size_in_byte":748,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"110569284","text":"import copy\nimport json\nimport multiprocessing\nfrom itertools import chain\n\nfrom playsound import playsound\n\nfrom Scripts.BotFunctions import runSemlar\nfrom Scripts.decorators import logtime\nfrom Scripts.rivenmarket import Rivenmarket\n\nheadless = False\nmax_processes = 1\n\n\ndef load_weapons():\n weapons = json.load(open('data/weapons/weapons.json', 'r'))\n return list(chain.from_iterable([weapons[weapon] for weapon in weapons]))\n\n\n@logtime\ndef main():\n pool = multiprocessing.Pool(max_processes)\n weapons = load_weapons()\n\n rmkt = Rivenmarket(headless)\n argslist = []\n for weapon in weapons:\n print(\"---Scanning \" + weapon + \"---\")\n rmkt.loadWeapon(weapon)\n filename = weapon + \".csv\"\n args = [headless, copy.deepcopy(rmkt.modlist), filename]\n argslist.append(args)\n rmkt.quit()\n\n pool.map(runSemlar, [*argslist])\n\n print(\"---DONE---\")\n playsound('data/sound/sound.wav')\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":979,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"280312210","text":"from datetime import datetime, timedelta\nfrom provider.utils import get_filtered_fb_post\n\n\nURL = \"https://www.facebook.com/PortumCorvin/posts/\"\nFB_ID = \"728866253985071\"\n\ndef getMenu(today):\n menu = ''\n if today.weekday() < 5:\n is_this_week = lambda date: datetime.strptime(date, '%Y-%m-%dT%H:%M:%S%z').date() > today.date() - timedelta(days=7)\n menu_filter = lambda post: is_this_week(post['created_time']) and \"főételek\" in post['message'].lower()\n menu = get_filtered_fb_post(FB_ID, menu_filter)\n if \"Előételek:\" in menu:\n menu = menu.split(\"Előételek:\")[1].strip()\n menu = '
'.join(i for i in menu.split('\\n') if i)\n\n return {\n 'name': 'Portum',\n 'url': URL,\n 'menu': menu\n }\n\nif __name__ == \"__main__\":\n print(getMenu(datetime.today()))\n","sub_path":"provider/portum.py","file_name":"portum.py","file_ext":"py","file_size_in_byte":833,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"124747653","text":"\nfrom image import Image\n\nclass Font():\n def __init__(self, filepath):\n\n #All numbers are set up fro a font just consisting of numbers!\n self.width = 39\n self.height = 6\n\n self.char_width = 3\n self.char_height = 6\n\n self.font_image = Image(self.width, self.height, \"images/\" + filepath + \".xp\")\n\n def get_character(self, char):\n char = ord(char)\n if char >= ord('0') and char <= ord('9'):\n index = char - 48 #48 is character 0\n index *= self.char_width\n return self.font_image.tiles[index : index + self.char_width, 0 : self.char_height][\"graphic\"]\n if char == ord('-'):\n return self.font_image.tiles[30 : 30 + self.char_width, 0 : self.char_height][\"graphic\"]\n","sub_path":"fonts/font.py","file_name":"font.py","file_ext":"py","file_size_in_byte":774,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"398378775","text":"import platform\nimport os.path\nimport logging\nimport datetime\nimport sys\nimport io\nimport re\nimport ssl\nimport pickle\nimport time\nimport random\nimport pandas as pd\n\nfrom selenium import webdriver\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions\nfrom selenium.webdriver.firefox.firefox_binary import FirefoxBinary\nfrom selenium.webdriver.common.keys import Keys\nfrom selenium.webdriver.support.ui import Select\n\nDEBUG_MODE = True\n\nmsg = \"\"\naccountno = \"\"\nbrowser = None\n\ndef print_v(arg):\n # logging.info(\"[\" + str(datetime.datetime.utcnow()) + \"] \" + accountno + \" \" + str(arg))\n if \"--verbose\" in sys.argv: \n print(arg)\n\n\ndef dumpFile(title, content):\n if (not DEBUG_MODE): return\n if (os.path.exists(\"./DEBUG\") == False):\n os.mkdir(\"./DEBUG\")\n\n filename = title + \" \" + str(datetime.datetime.utcnow()) + \".dump.html\"\n filename = filename.replace(\":\",\".\").replace(\" \",\"-\")\n\n # https://regex101.com/r/VjbmPV/2\n contentClean = content.get_attribute(\"outerHTML\")\n pattern = re.compile(r\"\")\n subst = u\"\"\n contentClean = re.sub(pattern, subst, contentClean)\n\n if platform.system() == \"Windows\":\n dump = io.open(\"./DEBUG/\" + filename , \"w\", encoding=\"utf-8\")\n if platform.system() == \"Darwin\":\n dump = io.open(\"./DEBUG/\" + filename , \"w\", encoding=\"utf-8\")\n if platform.system() == \"Linux\":\n dump = io.open(\"./DEBUG/\" + filename , \"w\", encoding=\"utf-8\")\n dump.write(contentClean)\n dump.close()\n\ndef startFirefox(url):\n options = webdriver.FirefoxOptions()\n if not \"--GUI\" in sys.argv: options.add_argument(\"--headless\")\n if platform.system() == \"Windows\":\n browser = webdriver.Firefox(options=options, executable_path='./crawlers/Crawler - youtube/drivers/win/geckodriver')\n if platform.system() == \"Darwin\":\n browser = webdriver.Firefox(options=options, executable_path='./crawlers/Crawler - youtube/drivers/mac/geckodriver')\n if platform.system() == \"Linux\":\n firefox_binary = FirefoxBinary('/opt/firefox/firefox')\n browser = webdriver.Firefox(firefox_binary=firefox_binary, options=options, executable_path='./crawlers/Crawler - youtube/drivers/linux/geckodriver')\n\n try:\n # open dashboard\n browser.get(url)\n # print_v(\"Page loaded: '{}' [\".format(browser.title) + browser.current_url +']')\n\n except:\n browser.quit()\n print_v(\"An exception has occured while starting firefox\")\n return None\n \n return browser\n\n# add delay to bypass fb activity check\ndef simulateHumanShort():\n time.sleep(random.randint(1,2))\n \ndef simulateHumanMedium():\n time.sleep(random.randint(3,7))\n \ndef simulateHumanLong():\n time.sleep(random.randint(10,35))\n \ndef browseURL(url, user, pwd):\n \"\"\"Browse to Page\"\"\"\n global data\n\n if \"--GUI\" in sys.argv:\n print_v(\"Starting Firefox w Selenium in GUI mode...\")\n else:\n print_v(\"Starting Firefox w Selenium in headless mode...\")\n\n global browser\n browser = startFirefox(url)\n if browser == None:\n return None\n\n # wait for page to load\n try:\n WebDriverWait(browser, 20).until(\n expected_conditions.element_to_be_clickable((By.XPATH,\"//button/span[contains(text(), 'I agree')]\"))\n )\n except Exception as e:\n print_v(\"An exception has occured during page load(1): \" + str(type(e)) + ' ' + str(e) )\n\n # agree\n try:\n btnAgree = browser.find_element_by_xpath(\"//button/span[contains(text(), 'I agree')]\")\n browser.execute_script(\"arguments[0].scrollIntoView(true);\", btnAgree)\n browser.execute_script(\"arguments[0].click();\", btnAgree)\n except Exception as e:\n print_v(\"An exception has occured during page load(1-1): \" + str(type(e)) + ' ' + str(e) )\n\n # wait for page to load\n try:\n WebDriverWait(browser, 40).until(\n expected_conditions.visibility_of_element_located((By.XPATH,\"//div[@id='contents']\"))\n )\n except Exception as e:\n print_v(\"An exception has occured during page load(2): \" + str(type(e)) + ' ' + str(e) )\n\n comment = browser.find_element_by_xpath(\"//div[@id='meta']\")\n browser.execute_script(\"arguments[0].scrollIntoView(true);\", comment)\n\n comments_found = 0\n while True:\n comments = browser.find_elements_by_xpath(\"//ytd-comment-thread-renderer\")\n browser.execute_script(\"arguments[0].scrollIntoView(true);\", comments[-1])\n simulateHumanShort()\n if comments_found == len(comments):\n break\n comments_found = len(comments)\n\n\n for comment in comments:\n # replies = comment.find_element_by_xpath(\"//div[@id='replies']//div[@id='expander']\")\n body = comment.find_element_by_xpath(\".//div[@id='main']//ytd-expander[@id='expander']\")\n content = body.find_element_by_xpath(\".//div[@id='content']\")\n show_more = body.find_element_by_xpath(\".//paper-button[@id='more']\")\n if body.find_element_by_xpath(\".//paper-button[@id='more']\").get_attribute(\"hidden\") == None:\n browser.execute_script(\"arguments[0].click();\", show_more)\n simulateHumanMedium()\n\n print_v(content.text)\n data += [[content.text, len(content.text), url]]\n # simulateHumanShort()\n\n df = pd.DataFrame(data, columns=[\"raw text\", \"text_length\", \"source\"])\n df.to_csv('data/list.csv', index=False)\n\n # dumpFile(title=\"after loading\", content=browser.find_element_by_tag_name(\"html\"))\n return browser\n\ndef main():\n url = \"\"\n for arg in sys.argv:\n if \"--url=\" in arg:\n url = arg[len(\"--url=\"):]\n\n if url == \"\":\n print_v(\"Insufficient arguments\")\n return\n\n print_v(\"\\n======= Script started with arguments \" + str(sys.argv) + \" =========\")\n global msg\n \n # # store facebook credentials in pickle file. Do this once, to create the pickle file, then comment the following 3 lines of code\n\n # fb_credentials = open(\"../..//crawlers/Crawler - youtube/fb.pickle\",\"rb\")\n user, pwd = None, None #pickle.load(fb_credentials)\n\n browser = browseURL(url, user, pwd)\n if browser == None:\n return\n\n\n # finito\n browser.quit()\n print_v(\"======= Script ended =========\")\n\ndata = []\n\nsPath = \"\"\n\nlogging.basicConfig(filename=sPath + 'debug.log', level=logging.INFO)\n\ntry:\n main()\nexcept Exception as e:\n logging.critical(e, exc_info=True)\n if not browser is None:\n browser.quit()\n print_v(\"======= Script ended with error =========\")","sub_path":"crawlers/Crawler - youtube/getcomments.py","file_name":"getcomments.py","file_ext":"py","file_size_in_byte":6646,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"531527085","text":"import numpy as np\r\nimport cv2\r\nfrom .config import cfg\r\nfrom ..utils.blob import im_list_to_blob\r\n\r\n\r\ndef _get_image_blob(im):\r\n \"\"\"\r\n Converts an image into a network input.\r\n 也就是将图像转换为caffe所支持的输入数据结构即blob\r\n Arguments:\r\n im (ndarray): a color image in BGR order\r\n Returns:\r\n blob (ndarray): a data blob holding an image pyramid\r\n im_scale_factors (list): list of image scales (relative to im) used\r\n in the image pyramid\r\n \"\"\"\r\n im_orig = im.astype(np.float32, copy=True)\r\n im_orig -= cfg.PIXEL_MEANS\r\n\r\n im_shape = im_orig.shape\r\n im_size_min = np.min(im_shape[0:2])\r\n im_size_max = np.max(im_shape[0:2])\r\n\r\n processed_ims = []\r\n im_scale_factors = []\r\n\r\n for target_size in cfg.TEST.SCALES:\r\n im_scale = float(target_size) / float(im_size_min)\r\n # Prevent the biggest axis from being more than MAX_SIZE\r\n if np.round(im_scale * im_size_max) > cfg.TEST.MAX_SIZE:\r\n im_scale = float(cfg.TEST.MAX_SIZE) / float(im_size_max)\r\n im = cv2.resize(im_orig, None, None, fx=im_scale, fy=im_scale,\r\n interpolation=cv2.INTER_LINEAR)\r\n im_scale_factors.append(im_scale)\r\n processed_ims.append(im)\r\n\r\n # Create a blob to hold the input images\r\n \"\"\"\r\n Convert a list of images into a network input.\r\n Assumes images are already prepared (means subtracted, BGR order, ...).\r\n \"\"\"\r\n blob = im_list_to_blob(processed_ims)\r\n #blob所有图像,im_scale_factors对应图像的维度值\r\n return blob, np.array(im_scale_factors)\r\n\r\n\r\ndef _get_blobs(im, rois):\r\n #ROI(region of interest):感兴趣区域\r\n blobs = {'data' : None, 'rois' : None}\r\n blobs['data'], im_scale_factors = _get_image_blob(im)\r\n return blobs, im_scale_factors\r\n\r\n\r\ndef test_ctpn(sess, net, im, boxes=None):\r\n #根据最大图像维度值生成blob,并把所有图像保存到blob数组中。im_scales对应相应图像的维度值\r\n blobs, im_scales = _get_blobs(im, boxes)\r\n if cfg.TEST.HAS_RPN:\r\n im_blob = blobs['data']\r\n #blobs增加一个key,并赋值\r\n #[im_blob.shape[1] the hight of the images\r\n #[im_blob.shape[2] the wight of the Images\r\n #im_scales[0] the 比例 of the images\r\n blobs['im_info'] = np.array(\r\n [[im_blob.shape[1], im_blob.shape[2], im_scales[0]]],\r\n dtype=np.float32)\r\n # forward pass\r\n if cfg.TEST.HAS_RPN:\r\n feed_dict = {net.data: blobs['data'], net.im_info: blobs['im_info'], net.keep_prob: 1.0}\r\n #根据模型对图像识别roi区域\r\n rois = sess.run([net.get_output('rois')[0]],feed_dict=feed_dict)\r\n rois=rois[0]\r\n\r\n scores = rois[:, 0]\r\n if cfg.TEST.HAS_RPN:\r\n assert len(im_scales) == 1, \"Only single-image batch implemented\"\r\n boxes = rois[:, 1:5] / im_scales[0]\r\n return scores, boxes\r\n","sub_path":"ctpn/lib/fast_rcnn/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":2931,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"306569667","text":"\"\"\"\n1: Transform file attachments (like message.txt, main.js, etc...) to a gist.\n2: if the bot detect a token, it will create a gist to revoke it.\n\"\"\"\n\nimport asyncio\nimport os\nimport re\n\nimport aiohttp\nimport discord\nfrom discord.ext import commands\nimport filetype\n\nfrom .utils.misc import create_new_gist, add_reactions\nfrom .utils.i18n import use_current_gettext as _\n\n\nclass Miscellaneous(commands.Cog):\n def __init__(self, bot):\n self.bot = bot\n self.re_token = re.compile(r\"[\\w\\-=]+\\.[\\w\\-=]+\\.[\\w\\-=]+\", re.ASCII)\n\n @commands.Cog.listener()\n async def on_message(self, message: discord.Message):\n await self.bot.set_actual_language(message.author)\n if await self.token_revoke(message): return\n if message.channel.id not in self.bot.authorized_channels_id: return\n await self.attachement_to_gist(message)\n\n async def attachement_to_gist(self, message):\n if not message.attachments: return\n else: attachment = message.attachments[0]\n\n file = await message.attachments[0].read()\n if filetype.guess(file) is not None: return\n\n try: file_content = file.decode('utf-8')\n except: return\n\n if await self.token_revoke(message, attach_content=file_content): return\n\n await message.add_reaction('🔄')\n try: __, user = await self.bot.wait_for('reaction_add', check=lambda react, usr: not usr.bot and react.message.id == message.id and str(react.emoji) == '🔄', timeout=600)\n except asyncio.TimeoutError: return\n finally: await message.clear_reactions()\n\n await self.bot.set_actual_language(message.author)\n\n references = {\n '<:javascript:664540815086845952>': 'js',\n '<:python:664539154838978600>': 'py',\n '<:html:706981296710352997>': 'html',\n '<:php:664540814944370689>': 'php',\n '<:java:664540814772273163>': 'java',\n '<:go:665975979402985483>': 'go',\n '<:lua:664539154788515902>': 'lua',\n '<:ruby:664540815078588436>': 'rb',\n '<:rust:664539155329581094>': 'rs',\n '<:scala:665967129660751883>': 'scala',\n '<:swift:664540815821111306>': 'swift'\n }\n\n response_message = None\n if os.path.splitext(attachment.filename)[1] in tuple(f'.{ext}' for ext in references.values()):\n file_name = attachment.filename\n else:\n response_message = await message.reply((_(\"What's the programmation language ?\\n\") +\n _(\"Click on the correspondant reaction, or send a message with the extension (`.js`, `.py`...)\\n\\n\") +\n f\"{' '.join(references.keys())}\"), mention_author=False)\n\n task = self.bot.loop.create_task(add_reactions(response_message, references.keys()))\n\n done, pending = await asyncio.wait([\n self.bot.wait_for('message', timeout=120, check=lambda msg: msg.author.id == user.id and msg.channel.id == response_message.channel.id and len(msg.content) < 7 and msg.content.startswith('.')),\n self.bot.wait_for('reaction_add', timeout=120, check=lambda react, usr: usr.id == user.id and str(react.emoji) in references.keys())\n ], return_when=asyncio.FIRST_COMPLETED)\n\n try:\n stuff = done.pop().result()\n if isinstance(stuff, tuple): # A reaction has been added\n file_name = f\"code.{references.get(str(stuff[0].emoji))}\"\n else:\n file_name = f\"code{stuff.content}\"\n except asyncio.TimeoutError: return\n finally:\n task.cancel()\n await response_message.clear_reactions()\n for future in done:\n future.exception()\n for future in pending:\n future.cancel()\n async with message.channel.typing():\n try:\n json_response = await create_new_gist(os.getenv('GIST_TOKEN'), file_name, file_content)\n assert json_response.get('html_url')\n except: return await message.channel.send(_('An error occurred.'), delete_after=5)\n\n if not response_message:\n await message.reply(content=_(\"A gist has been created :\\n\") + f\"<{json_response['html_url']}>\", mention_author=False)\n else:\n await response_message.edit(content=_(\"A gist has been created :\\n\") + f\"<{json_response['html_url']}>\")\n\n async def token_revoke(self, message, attach_content=None):\n if attach_content:\n match = self.re_token.search(attach_content)\n else:\n match = self.re_token.search(message.content)\n if not match: return\n\n headers = {\n \"Authorization\": f\"Bot {match.group(0)}\"\n }\n url = \"https://discord.com/api/v8/users/@me\"\n async with aiohttp.ClientSession(headers=headers) as session:\n async with session.get(url=url) as response:\n if response.status == 200:\n await message.delete()\n await message.channel.send((_(\"**{message.author.mention} you just sent a valid bot token.**\\n\").format(message=message) +\n _(\"This one will be revoked, but be careful and check that it has been successfully reset on the **dev portal**.\\n\") +\n \"\"), allowed_mentions=discord.AllowedMentions.all())\n\n await create_new_gist(os.getenv('GIST_TOKEN'), 'token revoke', match.group(0))\n return True\n\n\ndef setup(bot):\n bot.add_cog(Miscellaneous(bot))\n bot.logger.info(\"Extension [miscellaneous] loaded successfully.\")\n\n","sub_path":"cogs/miscellaneous.py","file_name":"miscellaneous.py","file_ext":"py","file_size_in_byte":5859,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"50566483","text":"##\n# This module defines functions for working with category allocations in a \n# stock portfolio.\n#\n\n## Loads the category allocations from a stock portfolio.\n# @param filename name of the file containing the portfolio\n# @return a dictionary consisting of category codes and total per category\n#\ndef loadAllocations(filename) :\n # Open the stock portfolio file.\n infile = open(\"stocks.txt\", \"r\")\n \n # Extract the stocks and accumulate the category sums.\n allocations = {}\n for line in infile :\n fields = line.split()\n cat = fields[1]\n amount = float(fields[2])\n if cat in allocations :\n allocations[cat] = allocations[cat] + amount\n else :\n allocations[cat] = amount\n \n infile.close()\n return allocations \n\n## Builds a list of dictionaries that contain the categories, allocation\n# percentages, and slice colors.\n# @param allocations a dictionary containing the stock allocations by category\n# @return a dictionary containing the pie chart and legend information \n#\ndef buildChartData(allocations) :\n categories = [\n {\"cat\": \"small\", \"color\": \"blue\", \"label\": \"Small Cap\"},\n {\"cat\": \"mid\", \"color\": \"red\", \"label\": \"Mid Cap\"},\n {\"cat\": \"large\", \"color\": \"green\", \"label\": \"Large Cap\"}, \n {\"cat\": \"misc\", \"color\": \"magenta\", \"label\": \"Other\"}, \n {\"cat\": \"cash\", \"color\": \"yellow\", \"label\": \"Cash\"}\n ]\n \n # Compute the total allocations.\n total = sum(allocations.values())\n \n # Compute the percentages per category and build a list of categories.\n slices = []\n for info in categories :\n category = info[\"cat\"]\n info[\"size\"] = allocations[category] / total\n slices.append(info)\n \n return slices\n","sub_path":"P4EO_source/ch08/worked_example_3/portfolio.py","file_name":"portfolio.py","file_ext":"py","file_size_in_byte":1734,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"158123510","text":"\n\n#calss header\nclass _CARBON():\n\tdef __init__(self,): \n\t\tself.name = \"CARBON\"\n\t\tself.definitions = [u'a chemical element that exists in its pure form as diamond or graphite, and is an important part of other substances such as coal and oil, as well as being contained in all plants and animals', u'a carbon copy ']\n\n\t\tself.parents = []\n\t\tself.childen = []\n\t\tself.properties = []\n\t\tself.jsondata = {}\n\n\n\t\tself.specie = 'nouns'\n\n\n\tdef run(self, obj1 = [], obj2 = []):\n\t\treturn self.jsondata\n","sub_path":"xai/brain/wordbase/nouns/_carbon.py","file_name":"_carbon.py","file_ext":"py","file_size_in_byte":491,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"438178899","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('petitions', '0011_auto_20151023_1551'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='petition',\n name='deadline',\n field=models.DateTimeField(null=True),\n ),\n ]\n","sub_path":"petitions/migrations/0012_auto_20151023_1656.py","file_name":"0012_auto_20151023_1656.py","file_ext":"py","file_size_in_byte":408,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"572737906","text":"from django.contrib.auth.models import User\nfrom basic.models import *\n\nfrom django.shortcuts import render_to_response\nfrom django.template.context import RequestContext\nfrom django import forms\nf = forms.EmailField()\n\n# Create your views here.\ndef home(request):\n\treturn render_to_response('splash.html',{}, context_instance=RequestContext(request))\n\n# Create your views here.\ndef signup(request):\n\tstatus = None\n\tif request.method == \"POST\":\n\t\tname = request.POST.get(\"name\")\n\t\temail = request.POST.get(\"email\")\n\t\twhy = request.POST.get(\"why\")\n\t\tif name and email and why:\n\t\t\ttry:\n\t\t\t\tf.clean(email)\n\t\t\t\tvalid = True\n\t\t\texcept:\n\t\t\t\tvalid = False\n\n\t\t\t#save\n\t\t\tif valid:\n\t\t\t\tif User.objects.filter(email=email).exists():\n\t\t\t\t\tstatus = \"email exists\"\n\t\t\t\telse:\n\t\t\t\t\tuser = User.objects.create(first_name=name, email=email)\n\t\t\t\t\tuser.save()\n\t\t\t\t\tsignup = SignUp.objects.create(user=user, why=why)\n\t\t\t\t\tsignup.save()\n\t\t\t\t\tstatus = \"saved!\"\n\t\t\telse:\n\t\t\t\tstatus = \"bad email\"\n\t\telse:\n\t\t\t#error\n\t\t\tstatus = \"empty fields\"\n\treturn render_to_response('signup.html',\n\t\t \t\t\t\t\t {'status':status}, context_instance=RequestContext(request))","sub_path":"basic/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1129,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"329599326","text":"import sys\nimport json\nimport xml.etree.ElementTree as elementTree\n\n# Method for fetching the request payload from stdin\ndef get_stdin():\n buf = \"\"\n while(True):\n line = sys.stdin.readline()\n buf += line\n if line == \"\":\n break\n return buf\n\n\n# Main service body\nif __name__ == \"__main__\":\n\n # Load the xml body\n svn_data = get_stdin()\n loaded_xml = elementTree.fromstring(svn_data)\n\n # Find and loop through the log entries converting each one\n # to an equivalent JSON format\n xml_log_entrys = loaded_xml.findall('logentry')\n json_entries = []\n\n for entry in xml_log_entrys:\n\n # Collect together the information about the files (not folders)\n # involved in the commit\n\n filesXML = entry.findall(\"paths/path\")\n files = list(map(lambda path: path.text.strip(), filesXML))\n\n json_entries.append({\n 'revision': entry.get('revision').strip() if entry.get('revision') is not None else '',\n 'author': entry.find('author').text.strip() if entry.find('author').text is not None else '',\n 'date': entry.find('date').text.strip() if entry.find('date').text is not None else '',\n 'message': entry.find('msg').text.strip() if entry.find('msg').text is not None else '',\n 'files': files\n })\n\n print(json.dumps({ 'result': json_entries }))\n\n\n\n\n\n\n","sub_path":"svn-json-log/transform-log.py","file_name":"transform-log.py","file_ext":"py","file_size_in_byte":1395,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"77918634","text":"#!/usr/bin/env python\n\n\"\"\"\nNaiveBayesModel.py: (part of speech, spelling) probability model\n\nUsage:\n\tfrom NaiveBayesModel import NaiveBayesModel as Model\n\tm = Model(\"hillary_train\")\n\tm2 = Model(\"trump_train\")\n\tscore = m.score(m2, test_file.read())\n\"\"\"\n\n__author__ = \"Prakhar Sahay\"\n__date__ = \"December 17th, 2016\"\n\n# import statements\nimport nltk\nfrom operator import itemgetter\n\nclass NaiveBayesModel():\n\n\tdef __init__(self, file):\n\t\tself.tagged = []# [(DT, The), (NN, dog), ...]\n\t\tself.transitions = []# [(DT, NN), ...]\n\t\tself.analyze(file)\n\n\t# build a probability model from the training file\n\tdef analyze(self, file):\n\n\t\t# analyze each line as separate sample\n\t\tfor sample in file:\n\t\t\tfor sentence in nltk.sent_tokenize(sample):\n\t\t\t\twords = nltk.word_tokenize(sentence)# [The, dog, ...]\n\t\t\t\ttagged = nltk.pos_tag(words)# [(The, DT), (dog, NN), ...]\n\t\t\t\t# better performance if tag is condition and word is sample\n\t\t\t\ttagged2 = [(tag, word) for (word, tag) in tagged]# [(DT, The), (NN, dog), ...]\n\t\t\t\tself.tagged.extend(tagged2)\n\t\t\t\ttag_sequence = list(map(itemgetter(1), tagged))# [DT, NN, ...]\n\t\t\t\tself.transitions.extend(nltk.bigrams(tag_sequence))\n\n\t\t# update distributions\n\t\tself.pair_cfd = nltk.ConditionalFreqDist(self.tagged)\n\t\tself.transition_cfd = nltk.ConditionalFreqDist(self.transitions)\n\n\t# return positive number if self is better match for sample text\n\t# return negative number if other model is better match\n\tdef score(self, other, sample):\n\n\t\tpos_score = 1\n\t\tneg_score = 1\n\t\tfor sentence in nltk.sent_tokenize(sample):\n\t\t\ttagged = nltk.pos_tag(nltk.word_tokenize(sentence))\n\t\t\tfor (wtp1, wtp2) in nltk.bigrams(tagged):\n\t\t\t\t# twp: (word, tag) pair\n\t\t\t\tpos_score *= self.frequency_of(other, wtp1, wtp2)\n\t\t\t\tneg_score *= other.frequency_of(self, wtp1, wtp2)\n\n\t\t\t# get output probability of the first (word, tag) pair also\n\t\t\tfirst_pair = tagged[0]\n\t\t\tpos_score *= self.p_output(other, first_pair[1], first_pair[0])\n\t\t\tneg_score *= other.p_output(self, first_pair[1], first_pair[0])\n\n\t\treturn pos_score - neg_score\n\n\t# helper\n\tdef frequency_of(self, other, wtp1, wtp2):\n\n\t\t# unpack tagged bigram\n\t\ttag1 = wtp1[1]\n\t\tword2,tag2 = wtp2\n\n\t\tp_transition = self.p_transition(other, tag1, tag2)\n\t\tp_output = self.p_output(other, tag2, word2)\n\n\t\treturn p_output * p_transition\n\n\t# computes P(t2+t1 | self) / P(t2+t1)\n\tdef p_transition(self, other, tag1, tag2):\n\t\tif tag1 in self.transition_cfd:\n\t\t\tfd = self.transition_cfd[tag1]\n\t\t\tif tag1 in other.transition_cfd:\n\t\t\t\tother_fd = other.transition_cfd[tag1]\n\t\t\telse:\n\t\t\t\tother_fd = nltk.FreqDist()\n\n\t\t\tif tag2 in fd:\n\t\t\t\tlikelihood = fd[tag2] / fd.N()\n\t\t\t\tpredictor_prior = (fd[tag2] + other_fd[tag2]) / (fd.N() + other_fd.N())\n\t\t\t\treturn likelihood / predictor_prior\n\n\t\treturn 1 / self.transition_cfd.N()\n\n\n\t# computes P(w+t | self) / P(w+t)\n\tdef p_output(self, other, tag, word):\n\t\tif tag in self.pair_cfd:\n\t\t\tfd = self.pair_cfd[tag]\n\t\t\tif tag in other.pair_cfd:\n\t\t\t\tother_fd = other.pair_cfd[tag]\n\t\t\telse:\n\t\t\t\tother_fd = nltk.FreqDist()\n\n\t\t\tif word in fd:\n\t\t\t\tlikelihood = fd[word] / fd.N()\n\t\t\t\tpredictor_prior = (fd[word] + other_fd[word]) / (fd.N() + other_fd.N())\n\t\t\t\treturn likelihood / predictor_prior\n\n\t\treturn 1 / self.pair_cfd.N()","sub_path":"NaiveBayesModel.py","file_name":"NaiveBayesModel.py","file_ext":"py","file_size_in_byte":3200,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"116017381","text":"#File Name: dice_hailey_AS10.py\n#File Path: /home/dice/Desktop/dice_hailey_AS10.py\n#Run Command: sudo python3 /home/dice/Desktop/dice_hailey_AS10.py\n\n#Hailey Dice\n#10/25/2019\n#AS.10\n#3 Sort\n\nimport random\nimport itertools\noverallPoints = 0\n\ndef sort(a, b, c):\n global overallPoints\n comps = 0\n swaps = 0\n if a > c:\n comps += 1\n a, c = c, a\n swaps += 1\n print(\"now:\", a, b, c)\n else:\n comps += 1\n \n if a > b:\n comps += 1\n a, b = b, a\n swaps += 1\n print(\"now:\", a, b, c)\n else:\n comps += 1\n \n if b > c:\n comps += 1\n b, c = c, b\n swaps += 1\n print(\"now:\", a, b, c)\n else:\n comps += 1\n \n totalPoints = swaps+comps\n overallPoints += totalPoints\n print(\"comparisons\", comps)\n print(\"swaps\", swaps)\n print(\"total points\", totalPoints)\n \n\n\n\nnums = list(itertools.permutations([1, 2, 3]))\nprint(nums)\n\nfor i in range(len(nums)):\n x = nums[i][0]\n y = nums[i][1]\n z = nums[i][2]\n print(x, y, z)\n sort(x, y, z)\n print(\"\")\n\n\nprint(\"TOTAL:\", overallPoints)\n \n","sub_path":"3sort.py","file_name":"3sort.py","file_ext":"py","file_size_in_byte":1137,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"287365847","text":"from HTMLParser import *\nfrom django.template.loader import render_to_string\nimport json\nimport os\nimport subprocess\nimport uuid\n\n\nMIDI_DIR = '/var/www/midiroom/myproject/media/midi/'\nLY_DIR = '/var/www/midiroom/myproject/media/ly/'\n\n\ndef json2ly(json_string):\n # string -> dict\n json_dict = json.loads(json_string)\n\n # build dict of values to be inserted into lilypond template\n ret = {}\n ret['tracks'] = [x for x in json_dict['tracks'] if not x['muted']]\n ret['drums'] = json_dict['drums']\n ret['tempo'] = json_dict['tempo']\n\n # insert dict values into lilypond template\n ly = render_to_string('template.ly', ret)\n\n return ly\n\n\ndef ly2midi(ly, name):\n subprocess.call(['lilypond', \"-o\", MIDI_DIR + \"/temp/\" + name, ly])\n\n\ndef json2midi(json_string, name):\n h = HTMLParser()\n\n # translate json into lilypond\n ly_string = h.unescape(json2ly(json_string))\n\n # write lilypond to file\n ly_filename = LY_DIR + str(uuid.uuid4()) + \".ly\"\n ly_file = open(ly_filename, \"w\")\n ly_file.write(ly_string)\n ly_file.close()\n\n # generate midi file from lilypond file\n ly2midi(ly_filename, name)\n\n # remove lilypond file\n os.remove(ly_filename)\n\n return (\n \"\"\"/media/midi/temp/\"\"\"\n + name\n + \"\"\".midi\"\"\",\n ly_string)\n","sub_path":"song/json2midi.py","file_name":"json2midi.py","file_ext":"py","file_size_in_byte":1300,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"532895222","text":"'''\n将collection根据 映射规则 分成 N 个桶\n对每个桶分别进行排序\n然后进行组合\n\n可以发现桶排序的效率与桶的划分方法和映射规则有直接关系\n映射规则与桶的个数相关\n\n如果桶的个数很大,则桶排序效率趋近于计数排序\n如果桶的个数很少,比如1个桶,则桶排序效率趋近于桶内排序算法的效率\n'''\nimport random\n\ndef bucket_sort(collection):\n '''\n 生成桶的方法:生成 max_num//10 - min_num//10+1 个桶\n 这里选择的映射方法: num // 10 - min_num // 10,这样可以保证第一个桶的每个\n 数字都是比第二个桶的数字小的,这样在合并的时候就很方便\n '''\n min_num, max_num = min(collection), max(collection)\n bucketArr = [[] for i in range(max_num//10-min_num//10+1)]\n for i in collection:\n index = i // 10 - min_num // 10\n bucketArr[index].append(i)\n collection.clear()\n for i in bucketArr:\n i.sort()\n collection.extend(i)\n return collection\n\nif __name__ == \"__main__\":\n collection = [random.randint(1,100) for _ in range(100)]\n collection_sorted = bucket_sort(collection)\n # print(collection_sorted)","sub_path":"sorts/bucket_sort.py","file_name":"bucket_sort.py","file_ext":"py","file_size_in_byte":1207,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"199995847","text":"import torch\nimport torch.optim as optim\nimport torch.optim.lr_scheduler as lr_sched\nfrom torch.utils.data import DataLoader\nimport torch.nn as nn\nfrom tensorboardX import SummaryWriter\nimport sys\n\nsys.path.append(\"/home/tbarton/Pointnet2_PyTorch/\")\nimport etw2.etw_pytorch_utils as pt_utils\nimport os\nimport argparse\n\ntorch.manual_seed(0)\nfrom generate_fake_data import read_point_clouds\nfrom pointnet2.models import Pointnet2SemMSG as Pointnet\nfrom pointnet2.models.pointnet2_msg_sem import model_fn_decorator\nfrom pointnet2.train.train_sem_seg import image_grid, load_data, eval_model\nimport numpy as np\nimport random\nfrom mpl_toolkits.mplot3d import Axes3D # noqa: F401 unused import\nimport matplotlib.pyplot as plt\n\noutpath = \"model_output\"\ndata_path = \"data\"\nVERBOSE = False\nlr_clip = 1e-5\nbnm_clip = 1e-2\nmax_evalimages = 1\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\n\ndef log_print(s, of):\n with open(of, 'a') as f:\n f.write(f\"{s}\\n\")\n print(s)\n\n\ndef loadConfigFile(exp_name):\n args = None\n with open(f\"{outpath}/{exp_name}/config.txt\") as f:\n for line in f:\n args = eval(line)\n\n assert args is not None, 'failed to load config'\n return args\n\n\n\n\ndef writeConfigFile(args):\n os.system(f'mkdir {outpath} > /dev/null 2>&1')\n os.system(f'mkdir {outpath}/{args.exp_name} > /dev/null 2>&1')\n os.system(f'mkdir {outpath}/{args.exp_name}/plots > /dev/null 2>&1')\n os.system(f'mkdir {outpath}/{args.exp_name}/points > /dev/null 2>&1')\n os.system(f'mkdir {outpath}/{args.exp_name}/models > /dev/null 2>&1')\n with open(f\"{outpath}/{args.exp_name}/config.txt\", \"w\") as f:\n f.write(f\"{args}\\n\")\n\n\ndef run_train(exp_name, checkpoints, dataset, rd_seed, holdout_perc, batch_size,\n load_epochs=None, n_epochs=200, eval_frequency=20):\n random.seed(rd_seed)\n np.random.seed(rd_seed)\n torch.manual_seed(rd_seed)\n train_loader, test_loader = load_data(dataset, results_folder,\n holdout_perc, batch_size,\n exp_names[0])\n for net, load_epoch in zip(checkpoints, load_epochs):\n input_folder = f\"{outpath}/{net}\"\n checkpoint_name = lambda e: f\"{input_folder}/models/eval_epoch_{e}.ckpt\"\n best_checkpoint_name = lambda \\\n e: f\"{input_folder}/models/eval_epoch_{e}_best.ckpt\"\n # writer = SummaryWriter(f\"runs/{exp_name}\") if \\\n # load_epoch is None else SummaryWriter(f\"runs\"\n # f\"/{exp_name + str(load_epoch)}\")\n\n\n print('training ...')\n lr_lbmd = lambda it: max(\n args.lr_decay ** (int(it * args.batch_size / args.decay_step)),\n lr_clip / args.lr,\n )\n bnm_lmbd = lambda it: max(\n args.bn_momentum\n * args.bn_decay ** (int(it * args.batch_size / args.decay_step)),\n bnm_clip,\n )\n\n # default value\n it = -1 # for the initialize value of `LambdaLR` and `BNMomentumScheduler`\n best_loss = 1e10\n\n model = Pointnet(num_classes=2, input_channels=3, use_xyz=True).to(device)\n optimizer = optim.Adam(model.parameters(), lr=args.lr,\n weight_decay=args.weight_decay)\n\n if load_epoch is not None:\n file_name = checkpoint_name(load_epoch)\n loading_results = pt_utils.load_checkpoint(model, optimizer, file_name)\n if loading_results is None:\n raise IOError(\"Unable to create file {}\".format(file_name))\n it, epoch, best_percentage = loading_results\n\n lr_scheduler = lr_sched.LambdaLR(optimizer, lr_lambda=lr_lbmd,\n last_epoch=it)\n bnm_scheduler = pt_utils.BNMomentumScheduler(model, bn_lambda=bnm_lmbd,\n last_epoch=it)\n\n it = max(it, 0) # for the initialize value of `trainer.train`\n val_it = 0\n weight = torch.tensor([.58, .42])\n if args.one_class:\n loss_func = torch.nn.BCEWithLogitsLoss()\n else:\n loss_func = nn.CrossEntropyLoss(weight=weight.cuda())\n\n model_fn = model_fn_decorator(loss_func)\n\n for batch in train_loader:\n model.eval()\n if bnm_scheduler is not None:\n bnm_scheduler.step(it)\n\n\n preds, loss, eval_res = model_fn(model, batch,\n results_folder=results_folder)\n it += 1\n\n\n\n if test_loader is not None:\n val_loss, res = eval_model(model, model_fn, test_loader,\n epoch, results_folder, writer)\n\n is_best = val_loss < best_loss\n best_loss = min(best_loss, val_loss)\n\n\ndef eval_model(model, model_fn, d_loader, epoch, results_folder, writer):\n model.eval()\n\n eval_dict = {}\n total_loss = 0.0\n count = 1.0\n for i, data in enumerate(d_loader):\n preds, loss, eval_res = model_fn(model, data, eval=True, epoch=epoch,\n results_folder=results_folder)\n\n total_loss += loss.item()\n count += 1\n\n for k, v in eval_res.items():\n if v is not None:\n eval_dict[k] = eval_dict.get(k, 0) + v\n if i < max_evalimages:\n eval_dict[\"data\"] = eval_dict.get(\"data\", []) + [data]\n eval_dict[\"preds\"] = eval_dict.get(\"preds\", []) + [preds]\n\n return total_loss / count, eval_dict\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description=\"Arg parser\")\n parser.add_argument('-en1', '--exp_name_1', help='name of experiment',\n type=str)\n parser.add_argument('-en2', '--exp_name_2', help='name of experiment',\n type=str)\n parser.add_argument('-mn', '--model_name', default=None,\n help='name of the model used for evaluation, do not specify for model_name == exp_name',\n type=str)\n parser.add_argument('-d', '--dataset', help='dataset to use', type=str)\n parser.add_argument(\"-batch_size\", type=int, default=2,\n help=\"Batch size [default: 32]\")\n parser.add_argument(\"-num_points\", type=int, default=4000,\n help=\"Number of points to train with [default: 4096]\", )\n parser.add_argument(\"-weight_decay\", type=float, default=0,\n help=\"L2 regularization coeff [default: 0.0]\", )\n parser.add_argument(\"-lr\", type=float, default=1e-4,\n help=\"Initial learning rate [default: 1e-2]\")\n parser.add_argument(\"-lr_decay\", type=float, default=0.5,\n help=\"Learning rate decay gamma [default: 0.5]\", )\n parser.add_argument(\"-decay_step\", type=float, default=2e5,\n help=\"Learning rate decay step [default: 20]\", )\n parser.add_argument(\"-bn_momentum\", type=float, default=0.9,\n help=\"Initial batch norm momentum [default: 0.9]\", )\n parser.add_argument(\"-bn_decay\", type=float, default=0.5,\n help=\"Batch norm momentum decay gamma [default: 0.5]\", )\n parser.add_argument(\"-epochs\", type=int, default=1000,\n help=\"Number of epochs to train for\")\n parser.add_argument('-m', '--mode', default=\"load\", type=str)\n parser.add_argument('-le1', '--load_epoch_1', default=None, type=int)\n parser.add_argument('-le2', '--load_epoch_2', default=None, type=int)\n\n parser.add_argument('-rd', '--rd_seed', default=42, type=int)\n parser.add_argument('-ho', '--holdout_perc', default=.1, type=float)\n parser.add_argument('-oc', '--one_class', default=True, type=bool)\n parser.add_argument('-ti', '--train_idx',\n default=\"model_output/1class/train_idx.txt\", type=str)\n parser.add_argument('-si', '--test_idx',\n default=\"model_output/1class/test_idx.txt\", type=str)\n\n args = parser.parse_args()\n if args.mode == \"load\":\n if not args.load_epoch:\n raise IOError\n en=[args.exp_name_1, args.exp_name_2]\n le = [args.load_epoch_1, args.load_epoch_2]\n run_train(\n en, args.dataset, args.rd_seed, args.holdout_perc,\n args.batch_size, le\n )\n # if args.mode == \"train\":\n # writeConfigFile(args)\n # run_train(\n # args.exp_name, args.dataset, args.rd_seed, args.holdout_perc,\n # args.batch_size, args.load_epoch\n # )\n","sub_path":"pointnet2/train/multilevel_eval.py","file_name":"multilevel_eval.py","file_ext":"py","file_size_in_byte":8602,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"190003609","text":"import json\nimport os\nfrom unittest import TestCase, skipIf\n\nfrom app.main import ALLOWED_TASKS\nfrom parameterized import parameterized_class\nfrom starlette.testclient import TestClient\nfrom tests.test_api import TESTABLE_MODELS\n\n\n@skipIf(\n \"structured-data-classification\" not in ALLOWED_TASKS,\n \"structured-data-classification not implemented\",\n)\n@parameterized_class(\n [\n {\"model_id\": model_id}\n for model_id in TESTABLE_MODELS[\"structured-data-classification\"]\n ]\n)\nclass StructuredDataClassificationTestCase(TestCase):\n def setUp(self):\n self.old_model_id = os.getenv(\"MODEL_ID\")\n self.old_task = os.getenv(\"TASK\")\n os.environ[\"MODEL_ID\"] = self.model_id\n os.environ[\"TASK\"] = \"structured-data-classification\"\n\n from app.main import app, get_pipeline\n\n get_pipeline.cache_clear()\n\n self.app = app\n\n @classmethod\n def setUpClass(cls):\n from app.main import get_pipeline\n\n get_pipeline.cache_clear()\n\n def tearDown(self):\n if self.old_model_id is not None:\n os.environ[\"MODEL_ID\"] = self.old_model_id\n else:\n del os.environ[\"MODEL_ID\"]\n if self.old_task is not None:\n os.environ[\"TASK\"] = self.old_task\n else:\n del os.environ[\"TASK\"]\n\n def test_simple(self):\n data = {\n \"1\": [7.4, 7.8],\n \"2\": [0.7, 0.88],\n \"3\": [7.4, 7.8],\n \"4\": [7.4, 7.8],\n \"5\": [7.4, 7.8],\n \"6\": [7.4, 7.8],\n \"7\": [7.4, 7.8],\n \"8\": [7.4, 7.8],\n \"9\": [7.4, 7.8],\n \"10\": [7.4, 7.8],\n \"11\": [7.4, 7.8],\n }\n\n inputs = {\"data\": data}\n with TestClient(self.app) as client:\n response = client.post(\"/\", json={\"inputs\": inputs})\n\n self.assertEqual(\n response.status_code,\n 200,\n )\n content = json.loads(response.content)\n self.assertEqual(type(content), list)\n self.assertEqual(len(content), 2)\n\n def test_malformed_input(self):\n with TestClient(self.app) as client:\n response = client.post(\"/\", data=b\"Where do I live ?\")\n\n self.assertEqual(\n response.status_code,\n 400,\n )\n content = json.loads(response.content)\n self.assertEqual(set(content.keys()), {\"error\"})\n\n def test_missing_columns(self):\n data = {\"1\": [7.4, 7.8], \"2\": [0.7, 0.88]}\n\n inputs = {\"data\": data}\n with TestClient(self.app) as client:\n response = client.post(\"/\", json={\"inputs\": inputs})\n self.assertEqual(\n response.status_code,\n 400,\n )\n","sub_path":"api-inference-community/docker_images/generic/tests/test_api_structured_data_classification.py","file_name":"test_api_structured_data_classification.py","file_ext":"py","file_size_in_byte":2712,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"422040795","text":"import os\n\nclass info(object):\n def __init__(self,job_name,job_dir,host_info,control_list_file=None):\n self.job_name = job_name\n self.job_dir = job_dir\n self.host_base = host_info.host_base\n self.mothur_path = host_info.mothur_path\n self.processors = host_info.processors\n self.classifiers = list(['NTM_disease','Persistent_infection'])\n self.class_options = list([['TRUE','FALSE'],['TRUE','FALSE']])\n self.sample_list_file = open(str(self.job_dir+'/sample_list.csv'),'r')\n if control_list_file != None:\n if control_list_file == True:\n self.control_list_file = open(str(self.job_dir+'/control_sample_list.csv'),'r')\n if control_list_file != True:\n self.control_list_file = open(str(self.job_dir+'/'+self.control_list_file),'r')\n \n self.mothur_ref_dir=str(self.host_base+\"data/fastq_files/ref/\")\n self.job_fastq_dir=str(self.host_base+\"data/fastq_files/lab/\")\n self.mothur_output_path=str(self.job_dir+\"/analysis/mothur/\")\n if not os.path.exists(self.mothur_output_path):\n os.makedirs(self.mothur_output_path)\n self.stability_files = open(str(self.job_dir+'/analysis/mothur/'+job_name+'.files'),'w')\n self.batch_file_name = str(self.job_dir+'/analysis/mothur/'+job_name+'.batch')\n self.batch_file=open(self.batch_file_name,'w')\n self.mothur_output_file=str(self.job_dir+\"/analysis/mothur/mothur_\"+job_name+\".out\")\n self.sample_list = list()\n self.control_list = list()\n\ndef clean(object):\n if os.path.exists(object.mothur_output_file): os.remove(object.mothur_output_file)\n return","sub_path":"src/classes/job.py","file_name":"job.py","file_ext":"py","file_size_in_byte":1625,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"499772211","text":"# Recursion on strings\n# Challenge: how to tell if a character is palindrome (回词,调转字母顺序,单词相同)\n\n# Non-recursion way\ndef is_palindrome(text):\n return text == text[::-1]\n\n# Recursion method\n\n# Convert a string to just characters\n# CAUTION: be careful with return when it involves boolean\ndef palindrome(raw_text):\n \"\"\"\n To tell if a string is palindrome\n\n :param text: any string\n :return: True if it is palindrome, else False.\n \"\"\"\n text = raw_text.lower()\n text = text.replace(\" \", \"\")\n\n print(\"text is now\", text)\n print(\"length of text is\", len(text))\n\n if len(text) <= 3:\n return text[0] == text[-1]\n else:\n if text[0] == text[-1]:\n return palindrome(text[1:-1])\n else:\n return False\n # DO NOT FORGET TO RECURSE properly, with a return command here!\n\nraw_text = \"a bca\"\nprint(palindrome(raw_text))\n\nprint()\n# MIT 另解\ndef palindrome2(raw_text):\n text = raw_text.lower()\n text = text.replace(\" \", \"\")\n\n print(\"text is now\", text)\n print(\"length of text is\", len(text))\n\n if len(text) <= 3:\n return text[0] == text[-1]\n else:\n return text[0] == text[-1] and palindrome2(text[1:-1])\n # 注意这里巧用and来节省代码数量\n\nraw_text2 = \"zabcbaz\"\nprint(palindrome2(raw_text2))\n","sub_path":"ProgrammingCourses/MIT6001X/week2/recursion_8_non_numeric.py","file_name":"recursion_8_non_numeric.py","file_ext":"py","file_size_in_byte":1332,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"69964526","text":"\"\"\"\n Transpose Matrix\n Given a 2D integer array matrix, return the transpose of matrix.\nThe transpose of a matrix is the matrix flipped over its main diagonal, switching the matrix's row and column indices.\nExample 1:\nInput: matrix = [[1,2,3],[4,5,6],[7,8,9]]\nOutput: [[1,4,7],[2,5,8],[3,6,9]]\nExample 2:\n\nInput: matrix = [[1,2,3],[4,5,6]]\nOutput: [[1,4],[2,5],[3,6]]\n\nConstraints:\nm == matrix.length\nn == matrix[i].length\n1 <= m, n <= 1000\n1 <= m * n <= 105\n-109 <= matrix[i][j] <= 109\n\"\"\"\n\nclass Solution:\n def transpose(self, matrix: list[list[int]]) -> list[list[int]]:\n height = len(matrix)\n width = len(matrix[0])\n new_mat = [[0 for _ in range(height)] for _ in range(width)]\n for i in range(height):\n for j in range(width):\n new_mat[j][i] = matrix[i][j]\n return new_mat\n\nSolution().transpose([[1,2,3],[4,5,6],[7,8,9]])\nSolution().transpose([[1,2,3],[4,5,6]])","sub_path":"Leetcode questions and answers/transpose_matrix.py","file_name":"transpose_matrix.py","file_ext":"py","file_size_in_byte":929,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"287724517","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 ('movies', '0009_movie_subtitle'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Notification',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('type', models.IntegerField(choices=[(0, b'News'), (1, b'Suggestion'), (2, b'Ask For Suggestion')])),\n ('movie', models.ForeignKey(to='movies.Movie')),\n ('target', models.ForeignKey(related_name='+', to='movies.Watcher')),\n ('watcher', models.ForeignKey(to='movies.Watcher')),\n ],\n ),\n ]\n","sub_path":"movies/migrations/0010_notification.py","file_name":"0010_notification.py","file_ext":"py","file_size_in_byte":810,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"376421034","text":"# -*- coding: utf-8 -*-\n\n# @File : builtin-type-example.py\n# @Date : 2018-09-20\n# @Author : Peng Shiyu\n\n\n# type 函数检查一个变量的类型\nimport os\n\n\ndef func(value):\n print(value, type(value))\n\n\nfunc(1)\nfunc(1.0)\nfunc(\"name\")\n\n\"\"\"\n(1, )\n(1.0, )\n('name', )\n\"\"\"\n\n\ndef load(file_):\n if isinstance(file_, type(\"\")):\n file_ = open(file_, \"r\")\n return file_.read()\n\n\nfilename = \"example/source/file.txt\"\nprint(load(filename)) # 传入文件路径\nprint(load(open(filename, \"r\"))) # 传入文件对象\n","sub_path":"source/learning/example/builtin-type-example.py","file_name":"builtin-type-example.py","file_ext":"py","file_size_in_byte":567,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"310363289","text":"import os\nimport utils\nimport sys\nimport subprocess\nimport time\nimport struct\n\n'''\ndef createCommand(Params):\n command = [Params.simpleTracerPath, \"--payload\", Params.testProgramName, \"--outfile\", \"stdout\", #\"--disableLogs\",\n \"--flow\", \"--binlog\", \"--binbuffered\", \"--writeLogOnFile\"]\n\n return command\n'''\n\n# writes to a process's pipe a variable encoded in numBytes\ndef writeToProcess(var, process, numBytes, doFlush=True):\n process.stdin.write(var.to_bytes(numBytes, 'little'))\n process.stdin.flush()\n\ndef processDataStream(dataStream, streamSize, entryTemplate):\n\n # Caching some variables for faster access\n entryType_TestName = entryTemplate.TN\n entryType_Module = entryTemplate.TM\n entryType_Offset = entryTemplate.TO\n\n streamPos = 0\n prevModuleName = ''\n prevOffset = -1\n while streamPos < streamSize:\n currModuleName = prevModuleName\n currOffset = -1\n entry = utils.getNextEntryFromStream(dataStream, streamPos, entryTemplate)\n\n type = entry[0]\n len = entry[1]\n moduleString = entry[2]\n offset = entry[3]\n cost = entry[4]\n jumpType = entry[5]\n entrySize = entry[6]\n\n streamPos += entrySize\n\n if type == entryType_Module:\n currModuleName = moduleString\n prevModuleName = currModuleName\n elif type == entryType_Offset:\n # use here currModuleName#offset\n print(str(currModuleName) + str(offset))\n elif type == entryType_TestName:\n continue # we are not interested in this type of data\n\n'''\ndef simulateCommText(Params, inputString):\n command = createCommand(Params)\n p = subprocess.Popen(command, bufsize=-1, stdin=subprocess.PIPE, stdout=subprocess.PIPE,\n stderr=subprocess.STDOUT) # fully buffered, PIPE read/write\n\n # write input len\n writeToProcess(int(len(inputString)), p, 4)\n\n entryFtm = 'I h h I'\n entrySize = struct.calcsize(entryFtm)\n # alignment = 4 # this is the header alignment. how can we get this from code ?\n # alignmentMask = ~(alignment - 1)\n\n for i in range(0, 1):\n # Write a new input payload\n utils.writeToProcess(1, p, 1, False)\n payloadInput = bytearray(inputString, 'utf8')\n p.stdin.write(payloadInput)\n p.stdin.flush()\n\n # Read the size of the returned buffer and data\n streamData = p.stdout.readline().decode('utf8').split(\"&\");\n for line in streamData:\n print(line)\n\n # Write a message to let to other end know that it's over\n writeToProcess(0, p, 1)\n\n # Read any garbabe output ? More like a check to make sure nothing is left behind\n while (p.poll()):\n garbageOutput = p.stdout.read()\n print(\"Garbage output !! \" + garbageOutput)\n\n # close\n'''\n\ndef simulateCommBinary(p, Params, inputString):\n # alignment = 4 # this is the header alignment. how can we get this from code ?\n # alignmentMask = ~(alignment - 1)\n\n for i in range(0, 10000):\n # Write a new input payload\n writeToProcess(1, p, 1, False)\n payloadInput = bytearray(inputString, 'utf8')\n p.stdin.write(payloadInput)\n p.stdin.flush()\n\n # Read the size of the returned buffer and data\n streamSize = struct.unpack(\"I\", p.stdout.read(4))[0]\n #print(streamSize)\n streamData = p.stdout.read(streamSize)\n\n processDataStream(streamData, streamSize, Params.entryTemplate)\n\n print(\"==============================\")\n\n # Write a message to let to other end know that it's over\n writeToProcess(0, p, 1)\n\n # Read any garbabe output ? More like a check to make sure nothing is left behind\n while (p.poll()):\n garbageOutput = p.stdout.read()\n print(\"Garbage output !! \" + garbageOutput)\n\n # close\n\n\ndef main(argv=None):\n Params = utils.readParams()\n\n print (\"simple tracer path \" + Params.simpleTracerPath + \" \" + Params.testProgramName)\n inputString = \"ciprian paduraru este un programator sa vedem ce iese acu\"\n\n # create the process\n command = utils.createTracerCmd(Params)\n p = subprocess.Popen(command, bufsize=-1, stdin=subprocess.PIPE, stdout=subprocess.PIPE,\n stderr=subprocess.STDOUT) # fully buffered, PIPE read/write\n\n # write input len\n utils.writeToProcess(int(len(inputString)), p, 4)\n\n simulateCommBinary(p, Params,inputString)\n #simulateCommText(Params, inputString)\n\n\n\n\n\nif __name__ == \"__main__\":\n sys.exit(main())\n","sub_path":"utRunSimpleText.py","file_name":"utRunSimpleText.py","file_ext":"py","file_size_in_byte":4643,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"397729056","text":"#!/hint/python3\n\nimport os\nimport shlex\nimport subprocess\nfrom contextlib import contextmanager\nfrom typing import Generator, List\n\nfrom .uiutil import run as _run\nfrom .uiutil import run_txtcapture\n\n\ndef run(args: List[str]) -> None:\n print(\"$ \" + (\" \".join(shlex.quote(arg) for arg in args)))\n _run(args)\n\n\n@contextmanager\ndef gcr_login() -> Generator[None, None, None]:\n key = os.getenv('GCLOUD_SA_KEY')\n if key == '':\n key = run_txtcapture(\n ['keybase', 'fs', 'read', '/keybase/team/datawireio/secrets/googlecloud.gcr-ci-robot.datawire.json.key'])\n\n subprocess.run(\n ['gcloud', 'auth', 'activate-service-account', '--key-file=-'],\n check=True,\n text=True,\n input=key,)\n subprocess.run(['gcloud', 'auth', 'configure-docker'], check=True)\n yield\n subprocess.run(['docker', 'logout', 'https://gcr.io'], check=True)\n\n\ndef get_images(source_registry: str, repo: str, tag: str, image_append: str = '', registries: List[str] = ['gcr.io/datawire']):\n images = [f\"{source_registry}/{repo}:{tag}\",]\n for registry in registries:\n dst = f'{registry}/{repo}:{tag}'\n if image_append != '':\n dst = f'{registry}/{repo}-{image_append}:{tag}'\n images.append(dst)\n return images\n\n\ndef main(tags: List[str],\n source_registry: str = 'docker.io/datawire',\n repos: List[str] = ['emissary',],\n image_append: str = '') -> None:\n print('Note: This script can be rerun.')\n print('If pushes to registries fail, you can rerun the command in your terminal to debug.')\n print('If pushes fail, it might be a credentials problem with gcr or quay.io or an issue with your gcloud installation.')\n with gcr_login():\n for repo in repos:\n for tag in tags:\n images = get_images(source_registry, repo, tag, image_append)\n src = f'{source_registry}/{repo}:{tag}'\n run(['docker', 'pull', src])\n for dst in images:\n if dst == src:\n continue\n run(['docker', 'tag', src, dst])\n run(['docker', 'push', dst])\n","sub_path":"releng/lib/mirror_artifacts.py","file_name":"mirror_artifacts.py","file_ext":"py","file_size_in_byte":2171,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"49980675","text":"\"\"\"Utilities for GPT indices.\"\"\"\nimport logging\nimport re\nfrom typing import Dict, List, Optional, Set, Tuple\n\nfrom llama_index.schema import BaseNode, MetadataMode\nfrom llama_index.utils import globals_helper, truncate_text\nfrom llama_index.vector_stores.types import VectorStoreQueryResult\n\n_logger = logging.getLogger(__name__)\n\n\ndef get_sorted_node_list(node_dict: Dict[int, BaseNode]) -> List[BaseNode]:\n \"\"\"Get sorted node list. Used by tree-strutured indices.\"\"\"\n sorted_indices = sorted(node_dict.keys())\n return [node_dict[index] for index in sorted_indices]\n\n\ndef extract_numbers_given_response(response: str, n: int = 1) -> Optional[List[int]]:\n \"\"\"Extract number given the GPT-generated response.\n\n Used by tree-structured indices.\n\n \"\"\"\n numbers = re.findall(r\"\\d+\", response)\n if len(numbers) == 0:\n return None\n else:\n return numbers[:n]\n\n\ndef expand_tokens_with_subtokens(tokens: Set[str]) -> Set[str]:\n \"\"\"Get subtokens from a list of tokens., filtering for stopwords.\"\"\"\n results = set()\n for token in tokens:\n results.add(token)\n sub_tokens = re.findall(r\"\\w+\", token)\n if len(sub_tokens) > 1:\n results.update({w for w in sub_tokens if w not in globals_helper.stopwords})\n\n return results\n\n\ndef log_vector_store_query_result(\n result: VectorStoreQueryResult, logger: Optional[logging.Logger] = None\n) -> None:\n \"\"\"Log vector store query result.\"\"\"\n logger = logger or _logger\n\n assert result.ids is not None\n assert result.nodes is not None\n similarities = (\n result.similarities\n if result.similarities is not None and len(result.similarities) > 0\n else [1.0 for _ in result.ids]\n )\n\n fmt_txts = []\n for node_idx, node_similarity, node in zip(result.ids, similarities, result.nodes):\n fmt_txt = f\"> [Node {node_idx}] [Similarity score: \\\n {float(node_similarity):.6}] {truncate_text(node.get_content(), 100)}\"\n fmt_txts.append(fmt_txt)\n top_k_node_text = \"\\n\".join(fmt_txts)\n logger.debug(f\"> Top {len(result.nodes)} nodes:\\n{top_k_node_text}\")\n\n\ndef default_format_node_batch_fn(\n summary_nodes: List[BaseNode],\n) -> str:\n \"\"\"Default format node batch function.\n\n Assign each summary node a number, and format the batch of nodes.\n\n \"\"\"\n fmt_node_txts = []\n for idx in range(len(summary_nodes)):\n number = idx + 1\n fmt_node_txts.append(\n f\"Document {number}:\\n\"\n f\"{summary_nodes[idx].get_content(metadata_mode=MetadataMode.LLM)}\"\n )\n return \"\\n\\n\".join(fmt_node_txts)\n\n\ndef default_parse_choice_select_answer_fn(\n answer: str, num_choices: int, raise_error: bool = False\n) -> Tuple[List[int], Optional[List[float]]]:\n \"\"\"Default parse choice select answer function.\"\"\"\n answer_lines = answer.split(\"\\n\")\n answer_nums = []\n answer_relevances = []\n for answer_line in answer_lines:\n line_tokens = answer_line.split(\",\")\n if len(line_tokens) != 2:\n if not raise_error:\n continue\n else:\n raise ValueError(\n f\"Invalid answer line: {answer_line}. \"\n \"Answer line must be of the form: \"\n \"answer_num: , answer_relevance: \"\n )\n answer_num = int(line_tokens[0].split(\":\")[1].strip())\n if answer_num > num_choices:\n continue\n answer_nums.append(answer_num)\n answer_relevances.append(float(line_tokens[1].split(\":\")[1].strip()))\n return answer_nums, answer_relevances\n","sub_path":"llama_index/indices/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":3616,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"512379182","text":"import os\nimport shutil\n\ntry:\n from configparser import SafeConfigParser # py3\nexcept:\n from ConfigParser import SafeConfigParser\n\nPATH_PACKAGE = os.path.dirname(__file__)\nFILE_CONFIG_SAMPLE = os.path.join(PATH_PACKAGE, 'sydep.cfg.sample')\n\n\ndef main(args):\n \"\"\"\n Init function of script. Called by :file:`sydep`.\n\n :param args: dictionary of arguments from command \\\n line (got by :py:class:`docopt`)\n \"\"\"\n if args['init']:\n copy_config()\n else:\n config = load_config()\n\n if args['push']:\n push(config, args)\n if args['pull']:\n pull(config, args)\n\n\ndef copy_config():\n \"\"\"\n Copy sample config file into current directory.\n \"\"\"\n try:\n open('./sydep.cfg', 'r')\n print('Remove sydep.cfg first. It cannot be overwritten.')\n except:\n shutil.copyfile(FILE_CONFIG_SAMPLE, './sydep.cfg')\n open('./.sydepignore', 'a').close()\n\n\ndef load_config():\n \"\"\"\n Load config from current directory.\n \"\"\"\n file = open('./sydep.cfg', 'r')\n config = SafeConfigParser()\n config.readfp(file)\n return config\n\n\ndef push(config, args):\n \"\"\"\n Push local files to remote server\n\n :param config: instance of :py:class:`ConfigParser`\n :param args: dictionary of arguments from command \\\n line (got by :py:class:`docopt`)\n \"\"\"\n run_cmd('rsync -a{verbose}z --exclude-from=.sydepignore'\n ' -e ssh {local} {server}:{remote}', config, args)\n\n\ndef pull(config, args):\n \"\"\"\n Update local files from server - overwrite just existing files,\n don't create new ones.\n\n :param config: instance of :py:class:`ConfigParser`\n :param args: dictionary of arguments from command \\\n line (got by :py:class:`docopt`)\n \"\"\"\n run_cmd('rsync -a{verbose}z --existing --exclude-from=.sydepignore'\n ' -e ssh {server}:{remote} {local}', config, args)\n\n\ndef run_cmd(cmd, config, args):\n \"\"\"\n Run given command after inserting variables.\n\n :param cmd: input command\n :param config: instance of :py:class:`ConfigParser`\n :param args: dictionary of arguments from command \\\n line (got by :py:class:`docopt`)\n \"\"\"\n cmd = cmd.format(\n verbose='v' if not args['--quiet'] else '',\n server=config.get('server', 'server'),\n remote=config.get('server', 'remote'),\n local=config.get('server', 'local'),\n )\n\n if not args['--quiet']:\n print(cmd)\n\n os.system(cmd)\n","sub_path":"sydep/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2520,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"201184434","text":"from enum import Enum\nfrom functools import cached_property\nfrom threading import Event, Lock\nfrom typing import TYPE_CHECKING\n\nfrom cloudshell.api.cloudshell_api import ResourceInfo\nfrom cloudshell.api.common_cloudshell_api import CloudShellAPIError\n\nfrom shell_tests.configs import (\n AdditionalPort,\n DeploymentResourceConfig,\n ResourceCommand,\n ResourceConfig,\n ServiceConfig,\n)\nfrom shell_tests.errors import BaseAutomationException, DependenciesBrokenError\nfrom shell_tests.helpers.logger import logger\nfrom shell_tests.helpers.threads_helper import set_thread_name_with_suffix\n\nif TYPE_CHECKING:\n from shell_tests.handlers.cs_handler import CloudShellHandler\n from shell_tests.handlers.sandbox_handler import SandboxHandler\n from shell_tests.handlers.shell_handler import ShellHandler\n\n\nclass DeviceType(Enum):\n REAL_DEVICE = \"Real device\"\n SIMULATOR = \"Simulator\"\n WITHOUT_DEVICE = \"Without device\"\n SHELL_FROM_TEMPLATE = \"Shell from template\"\n\n\nclass ResourceHandler:\n def __init__(\n self,\n conf: ResourceConfig,\n cs_handler: \"CloudShellHandler\",\n shell_handler: \"ShellHandler\",\n ):\n self.conf = conf\n self.name = conf.name\n self.attributes = {}\n self.children_attributes = {}\n self._cs_handler = cs_handler\n self._shell_handler = shell_handler\n\n self.dependencies_are_broken = False\n self._sandbox_handler = None\n self._autoload_lock = Lock()\n self._autoload_started = Event()\n self.autoload_finished = Event()\n self.is_autoload_success: bool | None = None\n\n @classmethod\n def create(\n cls,\n conf: ResourceConfig,\n cs_handler: \"CloudShellHandler\",\n shell_handler: \"ShellHandler\",\n ) -> \"ResourceHandler\":\n set_thread_name_with_suffix(conf.name)\n logger.info(f\"Start preparing the resource {conf.name}\")\n resource = cls(conf, cs_handler, shell_handler)\n resource._create_resource()\n logger.info(f\"The resource {resource.name} prepared\")\n return resource\n\n @property\n def sandbox_handler(self) -> \"SandboxHandler\":\n if self._sandbox_handler is None:\n raise BaseAutomationException(\"You have to add Sandbox Handler\")\n return self._sandbox_handler\n\n @sandbox_handler.setter\n def sandbox_handler(self, val: \"SandboxHandler\"):\n self._sandbox_handler = val\n\n @cached_property\n def family(self) -> str:\n return self.get_details().ResourceFamilyName\n\n @property\n def device_type(self) -> DeviceType:\n if \"SHELL_FROM_TEMPLATE\" in self.conf.name:\n return DeviceType.SHELL_FROM_TEMPLATE\n elif not self.conf.device_ip:\n return DeviceType.WITHOUT_DEVICE\n elif self.conf.attributes.get(\"User\"):\n return DeviceType.REAL_DEVICE\n else:\n return DeviceType.SIMULATOR\n\n @property\n def model(self) -> str:\n return self._shell_handler.model\n\n def _create_resource(self):\n ip = self.conf.device_ip or \"127.0.0.1\" # if we don't have a real device\n self.name = self._cs_handler.create_resource(self.name, self.model, ip)\n if self.conf.attributes:\n self.set_attributes(self.conf.attributes)\n\n def set_attributes(self, attributes: dict[str, str]):\n \"\"\"Set attributes for the resource and update internal dict.\"\"\"\n namespace = self.model if not self.conf.is_first_gen else \"\"\n self._cs_handler.set_resource_attributes(self.name, namespace, attributes)\n self.attributes.update(attributes)\n\n def set_children_attributes(self, children_attributes: dict[str, dict[str, str]]):\n \"\"\"Set children attributes.\"\"\"\n for child_name, attributes in children_attributes.items():\n child_name = f\"{self.name}/{child_name}\"\n child_info = self._cs_handler.get_resource_details(child_name)\n\n for attribute_name, attribute_value in attributes.items():\n self._set_child_attribute(child_info, attribute_name, attribute_value)\n\n def _set_child_attribute(\n self, child_info: ResourceInfo, attribute_name: str, attribute_value: str\n ):\n namespace = child_info.ResourceModelName\n for attribute_info in child_info.ResourceAttributes:\n namespace, name = attribute_info.Name.rsplit(\".\", 1)\n if name == attribute_name:\n break\n self._cs_handler.set_resource_attributes(\n child_info.Name, namespace, {attribute_name: attribute_value}\n )\n\n def _autoload(self):\n try:\n self._cs_handler.resource_autoload(self.name)\n except CloudShellAPIError as e:\n if str(e.code) != \"129\" and e.message != \"no driver associated\":\n raise\n self._cs_handler.update_driver_for_the_resource(self.name, self.model)\n self._cs_handler.resource_autoload(self.name)\n except DependenciesBrokenError:\n self.dependencies_are_broken = True\n raise\n\n def autoload(self):\n \"\"\"Run Autoload for the resource.\"\"\"\n self._autoload_started.set()\n with self._autoload_lock:\n try:\n self._autoload()\n if self.conf.additional_ports:\n self._add_additional_ports(self.conf.additional_ports)\n if self.conf.children_attributes:\n self.set_children_attributes(self.conf.children_attributes)\n except Exception:\n self.is_autoload_success = False\n self.autoload_finished.set()\n raise\n else:\n self.is_autoload_success = True\n self.autoload_finished.set()\n\n self._autoload_started.clear()\n\n def autoload_if_needed(self):\n if not self.autoload_finished.is_set():\n if self._autoload_started.is_set():\n self.autoload_finished.wait()\n else:\n self.autoload()\n\n def get_details(self) -> ResourceInfo:\n \"\"\"Get resource details.\"\"\"\n return self._cs_handler.get_resource_details(self.name)\n\n def get_commands(self) -> list[str]:\n return self._cs_handler.get_resource_commands(self.name)\n\n def execute_command(self, command_name: str, command_kwargs: dict[str, str]) -> str:\n \"\"\"Execute the command for the resource.\"\"\"\n try:\n output = self.sandbox_handler.execute_resource_command(\n self.name, command_name, command_kwargs\n )\n except DependenciesBrokenError:\n self.dependencies_are_broken = True\n raise\n return output\n\n def health_check(self) -> str:\n \"\"\"Run health check command on the resource.\"\"\"\n logger.info(f'Starting a \"health_check\" command for the {self.name}')\n output = self.execute_command(\"health_check\", {})\n logger.debug(f\"Health check output: {output}\")\n return output\n\n def run_custom_command(self, command: str) -> str:\n \"\"\"Execute run custom command on the resource.\"\"\"\n logger.info(f'Start a \"run_custom_command\" command {command}')\n output = self.execute_command(\"run_custom_command\", {\"custom_command\": command})\n logger.debug(f\"Run custom command output: {output}\")\n return output\n\n def run_custom_config_command(self, command: str) -> str:\n \"\"\"Execute run custom config command on the resource.\"\"\"\n logger.info(f'Start a \"run_custom_config_command\" command {command}')\n output = self.execute_command(\n \"run_custom_config_command\", {\"custom_command\": command}\n )\n logger.debug(f\"Run custom config command output: {output}\")\n return output\n\n def run_resource_commands(self, commands: list[ResourceCommand]):\n for command in commands:\n if command.mode is command.mode.CONFIG:\n self.run_custom_config_command(command.command)\n else:\n self.run_custom_command(command.command)\n\n def save(self, path_to_save: str, configuration_type: str) -> str:\n \"\"\"Execute save command on the resource.\"\"\"\n logger.info('Start a \"save\" command')\n logger.debug(\n f\"Path to save: {path_to_save}, configuration type: {configuration_type}\"\n )\n\n output = self.execute_command(\n \"save\",\n {\"folder_path\": path_to_save, \"configuration_type\": configuration_type},\n )\n logger.debug(f\"Save command output: {output}\")\n return output\n\n def orchestration_save(self, mode: str, custom_params: str = \"\") -> str:\n \"\"\"Execute orchestration save command.\"\"\"\n logger.info('Start a \"orchestration save\" command')\n logger.debug(f\"Mode: {mode}, custom params: {custom_params}\")\n output = self.execute_command(\n \"orchestration_save\", {\"mode\": mode, \"custom_params\": custom_params}\n )\n logger.debug(f\"Orchestration save command output: {output}\")\n return output\n\n def restore(self, path: str, configuration_type: str, restore_method: str) -> str:\n \"\"\"Execute restore command.\n\n :param path: path to the file\n :param configuration_type: startup or running\n :param restore_method: append or override\n \"\"\"\n logger.info('Start a \"restore\" command')\n logger.debug(\n f\"Path: {path}, configuration_type: {configuration_type}, \"\n f\"restore_method: {restore_method}\"\n )\n output = self.execute_command(\n \"restore\",\n {\n \"path\": path,\n \"configuration_type\": configuration_type,\n \"restore_method\": restore_method,\n },\n )\n logger.debug(f\"Restore command output: {output}\")\n return output\n\n def orchestration_restore(\n self, saved_artifact_info: str, custom_params: str = \"\"\n ) -> str:\n \"\"\"Execute orchestration restore command.\"\"\"\n logger.info('Start a \"orchestration restore\" command')\n logger.debug(\n f\"Saved artifact: {saved_artifact_info}, custom params: {custom_params}\"\n )\n output = self.execute_command(\n \"orchestration_restore\",\n {\n \"saved_artifact_info\": saved_artifact_info,\n \"custom_params\": custom_params,\n },\n )\n logger.debug(f\"Orchestration restore command output: {output}\")\n return output\n\n def rename(self, new_name: str):\n \"\"\"Rename the resource.\"\"\"\n self.name = self._cs_handler.rename_resource(self.name, new_name)\n\n def _add_additional_ports(self, additional_port_configs: list[AdditionalPort]):\n info = self.get_details()\n for child_res in info.ChildResources:\n if child_res.ResourceFamilyName == \"CS_Chassis\":\n chassis_name = child_res.Name\n break\n else:\n _name = self._cs_handler.create_resource(\n name=\"Chassis 1\",\n model=f\"{info.ResourceModelName}.GenericChassis\",\n address=\"CH1\",\n family=\"CS_Chassis\",\n parent_path=info.Name,\n )\n chassis_name = f\"{info.Name}/{_name}\"\n\n for i, port_conf in enumerate(additional_port_configs, 1):\n self._cs_handler.create_resource(\n name=port_conf.name,\n model=f\"{info.ResourceModelName}.GenericPort\",\n address=f\"P{i}\",\n family=\"CS_Port\",\n parent_path=chassis_name,\n )\n\n def finish(self):\n self._cs_handler.delete_resource(self.name)\n\n\nclass ServiceHandler:\n def __init__(self, name: str, attributes: dict[str, str], model: str):\n self.name = name\n self.model = model\n self.family = None\n self.attributes = attributes\n\n self._sandbox_handler = None\n\n @classmethod\n def from_conf(cls, conf: ServiceConfig) -> \"ServiceHandler\":\n return cls(conf.name, conf.attributes, conf.model)\n\n @property\n def sandbox_handler(self) -> \"SandboxHandler\":\n if self._sandbox_handler is None:\n raise BaseAutomationException(\"You have to add Sandbox Handler\")\n return self._sandbox_handler\n\n @sandbox_handler.setter\n def sandbox_handler(self, val: \"SandboxHandler\"):\n self._sandbox_handler = val\n\n @property\n def device_type(self) -> DeviceType:\n return DeviceType.REAL_DEVICE\n\n def execute_command(self, command_name: str, command_kwargs: dict[str, str]) -> str:\n \"\"\"Execute the command for the service.\"\"\"\n return self.sandbox_handler.execute_service_command(\n self.name, command_name, command_kwargs\n )\n\n def load_config(self, config_path: str, extra_kwargs: dict | None = None) -> str:\n \"\"\"Execute a command load_config for the service.\"\"\"\n extra_kwargs = extra_kwargs or {}\n extra_kwargs.update({\"config_file_location\": config_path})\n return self.execute_command(\"load_config\", extra_kwargs)\n\n def start_traffic(self, extra_kwargs: dict | None = None) -> str:\n \"\"\"Execute a command start traffic for the service.\"\"\"\n return self.execute_command(\"start_traffic\", extra_kwargs or {})\n\n def stop_traffic(self, extra_kwargs: dict | None = None) -> str:\n \"\"\"Execute a command stop traffic for the service.\"\"\"\n return self.execute_command(\"stop_traffic\", extra_kwargs or {})\n\n def get_statistics(self, extra_kwargs: dict | None = None) -> str:\n \"\"\"Execute a command get statistics for the service.\"\"\"\n return self.execute_command(\"get_statistics\", extra_kwargs or {})\n\n def get_test_file(self, test_name: str) -> str:\n \"\"\"Execute a command get test file for the service.\"\"\"\n return self.execute_command(\"get_test_file\", {\"test_name\": test_name})\n\n\nclass DeploymentResourceHandler:\n def __init__(\n self,\n conf: DeploymentResourceConfig,\n vm_name: str,\n sandbox_handler: \"SandboxHandler\",\n ):\n self.conf = conf\n self.name = vm_name\n self.vm_name = vm_name\n self.attributes = {}\n self._sandbox_handler = sandbox_handler\n self._cs_handler = sandbox_handler._cs_handler\n\n @classmethod\n def create_resource(\n cls, conf: DeploymentResourceConfig, sandbox_handler: \"SandboxHandler\"\n ) -> \"DeploymentResourceHandler\":\n logger.info(f\"Start preparing the resource {conf.name}\")\n vm_name = sandbox_handler.get_deployment_resource_name()\n resource = cls(conf, vm_name, sandbox_handler)\n if conf.attributes:\n resource.set_attributes(conf.attributes)\n logger.info(f\"The resource {resource.name} prepared\")\n return resource\n\n @property\n def device_type(self):\n return DeviceType.REAL_DEVICE\n\n @cached_property\n def model(self):\n return self.get_details().ResourceModelName\n\n @cached_property\n def device_ip(self):\n return self.get_details().Address\n\n def rename(self, new_name: str):\n self.name = self._cs_handler.rename_resource(self.name, new_name)\n\n def set_attributes(self, attributes: dict[str, str]):\n \"\"\"Set attributes for the resource and update internal dict.\"\"\"\n namespace = self.model if not self.conf.is_first_gen else \"\"\n self._cs_handler.set_resource_attributes(self.name, namespace, attributes)\n self.attributes.update(attributes)\n\n def get_details(self) -> ResourceInfo:\n \"\"\"Get resource details.\"\"\"\n return self._cs_handler.get_resource_details(self.name)\n\n def refresh_vm_details(self):\n \"\"\"Refresh VM Details for the App.\"\"\"\n self._sandbox_handler.refresh_vm_details([self.name])\n","sub_path":"shell_tests/handlers/resource_handler.py","file_name":"resource_handler.py","file_ext":"py","file_size_in_byte":15859,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"585250000","text":"# class TreeNode:\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\n# Solution 1 - Recursive\n\n\nclass Solution:\n def countNodes(self, root: TreeNode) -> int:\n def foo(root):\n if not root:\n return 0\n left = foo(root.left)\n right = foo(root.right)\n return left + right + 1\n return foo(root)\n\n# Solution 2 - Iterative\n\n\nclass Solution:\n def countNodes(self, root: TreeNode) -> int:\n cache = [root]\n count = 0\n if not root:\n return 0\n while cache:\n node = cache.pop(0)\n count += 1\n if node.left:\n cache.append(node.left)\n if node.right:\n cache.append(node.right)\n return count\n\n\n# Solution 3 - binary Search\nclass Solution:\n def countNodes(self, root):\n if not root:\n return 0\n\n height = 0\n head = root\n while head:\n height += 1\n head = head.left\n\n low = 1 << (height - 1)\n high = (1 << height) - 1\n\n while low < high:\n m = mid = (low + high + 1) // 2\n path = []\n while m != 1:\n path.append(m)\n m = m // 2\n cur = 1\n head = root\n while head and path:\n if cur * 2 == path[-1]:\n head = head.left\n else:\n head = head.right\n cur = path.pop()\n \n if head:\n low = mid\n else:\n high = mid - 1\n return low","sub_path":"0222.py","file_name":"0222.py","file_ext":"py","file_size_in_byte":1680,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"604821821","text":"import numpy as np\n\nnum_comparisons = 0\n\n\ndef quicksort(a):\n global num_comparisons\n n = len(a)\n if n < 2:\n return\n\n left = 0\n p = a[left]\n partition_idx = partition(a, left, n, p)\n\n # Recursive calls\n quicksort(a[:partition_idx])\n num_comparisons += len(a[:partition_idx])\n quicksort(a[partition_idx + 1:])\n num_comparisons += len(a[partition_idx + 1:])\n\n return a\n\n\ndef quicksort2(a):\n global num_comparisons\n # print(a)\n n = len(a)\n if n < 2:\n return\n\n # print('quicksort: ' + str(a))\n\n p = a[n - 1]\n a[0], a[n - 1] = p, a[0]\n\n # print('after moving pivot to left: ' + str(a))\n\n partition_idx = partition(a, 0, n, p)\n\n # Recursive calls\n quicksort2(a[:partition_idx])\n num_comparisons += len(a[:partition_idx])\n quicksort2(a[partition_idx + 1:])\n num_comparisons += len(a[partition_idx + 1:])\n\n return a\n\n\ndef quicksort3(a):\n global num_comparisons\n # print(a)\n n = len(a)\n if n < 2:\n return\n\n left = 0\n right = n\n\n # Compute p as the median-of-three\n if n % 2 == 0:\n middle_idx = int(n/2) - 1\n else:\n middle_idx = int(n/2)\n median_array = [a[left], a[middle_idx], a[right - 1]]\n p = int(np.median(median_array))\n # print('a = ' + str(a))\n # print('median_array = ' + str(median_array))\n # print('pivot = ' + str(p))\n\n if p == a[middle_idx]:\n a[0], a[middle_idx] = p, a[0]\n\n elif p == a[right - 1]:\n a[0], a[right - 1] = p, a[0]\n\n partition_idx = partition(a, 0, n, p)\n\n # Recursive calls\n quicksort3(a[:partition_idx])\n num_comparisons += len(a[:partition_idx])\n quicksort3(a[partition_idx + 1:])\n num_comparisons += len(a[partition_idx + 1:])\n\n return a\n\n\ndef partition(a, left, right, p):\n i = left + 1\n for j in range(i, right):\n\n if a[j] < p:\n a[i], a[j] = a[j], a[i]\n i += 1\n\n # Swap left element with a[i - 1]\n a[left], a[i - 1] = a[i - 1], a[left]\n\n return i - 1\n\n\nif __name__ == '__main__':\n qs_file = 'data/QuickSort.txt'\n a = []\n with open(qs_file) as f:\n for line in f:\n a.append(int(line))\n\n a = np.array(a)\n print(a)\n\n # a = np.array([3, 8, 2, 5, 1, 4, 7, 6])\n # a = [3, 8, 2, 5, 1, 4, 7, 6]\n\n a = quicksort(a)\n print('a = ' + str(a))\n\n print('num_comparisons = ' + str(num_comparisons))\n\n\n num_comparisons = 0\n a = []\n with open(qs_file) as f:\n for line in f:\n a.append(int(line))\n\n a = np.array(a)\n print('unsorted array = ' + str(a))\n\n a = quicksort2(a)\n # num_comparisons += len(a) - 1\n print('a = ' + str(a))\n\n print('num_comparisons = ' + str(num_comparisons))\n\n num_comparisons = 0\n a = []\n with open(qs_file) as f:\n for line in f:\n a.append(int(line))\n\n a = np.array(a)\n print(a)\n\n a = quicksort3(a)\n # num_comparisons += len(a) - 1\n print('a = ' + str(a))\n print('num_comparisons = ' + str(num_comparisons))\n\n","sub_path":"quicksort.py","file_name":"quicksort.py","file_ext":"py","file_size_in_byte":3016,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"571560252","text":"from django import forms\nfrom django.utils.translation import gettext_lazy as _\n\nfrom Main.models import Individual, Department\n\n\nclass IndividualForm(forms.ModelForm):\n class Meta:\n model = Individual\n fields = '__all__'\n labels = {\n 'name': _('الأسم'),\n 'rank': _('الدرجة'),\n 'military_number': _('الرقم العسكري'),\n 'address': _('العنوان الدائم'),\n 'phone_number': _('رقم التليفون'),\n 'relative_phone_number': _('رقم التليفون أقرب الأقارب'),\n\n }\n\n\nclass DepartmentForm(forms.ModelForm):\n class Meta:\n model = Department\n fields = '__all__'\n labels = {\n 'name': _('الأسم')\n }\n","sub_path":"Main/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":790,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"103373353","text":"import os\nimport time\nimport dateutil.relativedelta\nimport mysql.connector\nfrom datetime import datetime, date\nimport datetime\n\nnew_conn = mysql.connector.connect(host='192.168.50.151',user='search',password='search@zyxr.com', database='invest')\nnew_cursor = new_conn.cursor(dictionary=True)\n\ndef getSum():\n allnum=0\n for idx in range(0,100):\n sql = \"select ifnull(sum(\" \\\n \"loan_principal+loan_interest+loan_add_interest+\" \\\n \"plan_principal+plan_interest+plan_add_interest+\" \\\n \"xrdt_principal+xrdt_interest+xrdt_add_interest),0) as num from invest.t_investment_sum_%02d \" % (idx)\n new_cursor.execute(sql)\n rows = new_cursor.fetchall()\n for row in rows:\n num=row[\"num\"]\n allnum=allnum+num\n\n print(allnum)\n\n\ngetSum()","sub_path":"python_self/工作/专门修复王武问题(长期跑)/算平台待收/计算待收.py","file_name":"计算待收.py","file_ext":"py","file_size_in_byte":815,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"306386369","text":"from django.utils.translation import gettext as _\nfrom django_datatables_view.base_datatable_view import BaseDatatableView\nfrom src.bin.bin import table_dropdown, format_date, format_status\nfrom src.bin.search import get_query\n\nbase_url = \"/document/\"\n\n\nclass DocumentTable(BaseDatatableView):\n\n from .models import Document\n\n second_base = ''\n\n # The model we're going to show\n model = Document\n\n # define the columns that will be returned\n columns = ['name', 'classification', 'keyword', 'year', 'file_location', 'status']\n\n # define column names that will be used in sorting\n # order is important and should be same as order of columns\n # displayed by datatables. For non sortable columns use empty\n # value like ''\n order_columns = ['name', 'classification', 'classification', 'year', 'file_location']\n\n # set max limit of records returned, this is used to protect our site if someone tries to attack our site\n # and make it return huge amount of data\n max_display_length = 50\n\n classification = None\n\n keyword = None\n\n def get_initial_queryset(self):\n # return queryset used as base for further sorting/filtering\n # these are simply objects displayed in datatable\n # You should not filter data returned here by any filter values entered by user. This is because\n # we need some base queryset to count total number of records.\n\n self.classification = self.request.GET.get(\"classification\")\n self.keyword = self.request.GET.get(\"keyword\")\n\n if self.classification:\n if self.classification == \"plan\":\n return self.model.objects.filter(status=1, classification__icontains=\"plan\")\n else:\n return self.model.objects.filter(status=1, classification=self.classification)\n elif self.keyword:\n return self.model.objects.filter(status=1, keyword=self.keyword)\n else:\n return self.model.objects.filter(status=1)\n\n def render_column(self, row, column):\n # We want to render user as a custom column\n if column == 'file_location':\n return \"
\" \\\n \"Open Document\"\\\n .format(row.pk)\n\n elif column == 'file_location2':\n return \"Download\"\\\n .format(row.file_location.url)\n\n elif column == 'mda':\n try:\n return row.mda.name\n except AttributeError:\n return \"\"\n\n elif column == \"keyword\":\n ret = \"\"\n for x in row.keyword.all():\n ret += \"%s
\" % x.name\n return ret\n\n elif column == 'status':\n actions = [\n {\n 'link': \"%s%s%s/%s/\" % (base_url, self.second_base, 'update', str(row.pk)),\n 'label': _('Update'),\n },\n {\n 'link': \"%s%s%s/%s/\" % (base_url, self.second_base, 'delete', str(row.pk)),\n 'label': _('Delete'),\n },\n ]\n return table_dropdown(actions)\n else:\n return super(self.__class__, self).render_column(row, column)\n\n def filter_queryset(self, qs):\n # use parameters passed in POST request to filter queryset\n\n # simple example:\n search = self.request.GET.get('search[value]', None)\n if search:\n search_query = get_query(search, ['name', 'keyword__name', 'year'])\n qs = qs.filter(search_query)\n\n return qs\n","sub_path":"src/document/datatables.py","file_name":"datatables.py","file_ext":"py","file_size_in_byte":3929,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"152518302","text":"import shutil, random\nimport python_magic\nimport threading\nimport time\nimport os\n\n\ndef finder(start,stop):\n a=\"jpegFiles\"\n fileDict={\"ASCII\":\"txtFiles\",\"JPEG\":\"jpegFiles\",\"Audio\":\"mpegFiles\",\"PNG\":\"pngFiles\"}\n for i in range (start,stop):\n origin = \"files/{0}{1}\".format(\"file\", i)\n filetype=python_magic.from_file(origin)\n a=fileDict.get(filetype.split()[0])\n name = \"{0}/{1}{2}\".format(a, \"file\", i)\n shutil.copyfile(origin, name )\n\n#Single thread\nstart_time = time.time()\nfinder(10,150)\nprint(\"--- %s seconds for singlethread ---\" % (time.time() - start_time))\n\n#remevo files from folders\nfor folder in [\"txtFiles\",\"jpegFiles\",\"mpegFiles\",\"pngFiles\"]:\n for the_file in os.listdir(folder):\n file_path = os.path.join(folder, the_file)\n try:\n if os.path.isfile(file_path):\n os.unlink(file_path)\n except Exception as e:\n print(e)\n\n#Multi thread\nstart_time = time.time()\ntry:\n x=threading.Thread(target=finder, args=(10,76))\n y=threading.Thread(target=finder, args=(76,150))\n x.start()\n y.start()\n x.join()\n y.join()\nexcept:\n print (\"Error: unable to start thread\")\nprint(\"--- %s seconds for multithread ---\" % (time.time() - start_time))\n\n\n","sub_path":"lab8/lab8.py","file_name":"lab8.py","file_ext":"py","file_size_in_byte":1258,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"119247106","text":"from runtime import proRuntime as runtime\n\ndef sum(char):\n sum = (ord(char) - ord('A')) + 1\n return sum\n\nscore = 0\nscore2 = 0\nindex = 0\nwith open(\"names.txt\", 'r') as file:\n names = file.read().split(\",\")\n names.sort()\nwhile index < len(names):\n i = 1\n score = 0\n namelen = len(names[index].replace('\\\"', '')) # \"삭제\n while i <= namelen:\n score += sum(names[index][i])\n i += 1\n\n score2 += score * (index + 1)\n index += 1\n\nprint(score2)\nruntime()\n","sub_path":"problem22.py","file_name":"problem22.py","file_ext":"py","file_size_in_byte":494,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"602765538","text":"#coding:utf-8\r\nimport model\r\nfrom google.appengine.api import memcache\r\nfrom google.appengine.api import images\r\nfrom getimageinfo import getImageInfo\r\nfrom utility import cacheV2\r\n\r\nfrom upyun import UpYun,md5,md5file\r\n\r\ndef cache(key=\"\",time=3600):\r\n def _decorate(method):\r\n def _wrapper(*args, **kwargs):\r\n val = memcache.get(key)\r\n if val is None:\r\n val = method(*args, **kwargs)\r\n memcache.set(key,val,time)\r\n return val\r\n return _wrapper\r\n return _decorate\r\n\r\n\r\ndef CreateAlbum(user,name='',password='',summary = ''):\r\n '''创建相册'''\r\n album = model.Albums(AlbumName=name,AlbumPassword=password,AlbumAuthor=user,Summary = summary)\r\n album.Save()\r\n memcache.delete('ALLALBUMS')\r\n return True\r\n\r\n#yibin135\r\n#yibin\r\n\r\n\r\n@cache(key='ALLALBUMS',time=3600)\r\ndef GetAllAlbums():\r\n\r\n albums=model.Albums().GetAll()\r\n return albums\r\n\r\n\r\n@cacheV2('ALBUM_{id}')\r\ndef GetAlbum(id):\r\n data = model.Albums().get_by_id(int(id))\r\n return data\r\n\r\n\r\n\r\ndef DeleteAlbum(id):\r\n album = GetAlbum(int(id))\r\n if album is not None:\r\n for a in album.Photos():\r\n a.delete()\r\n album.Delete()\r\n memcache.delete('ALLALBUMS')\r\n\r\n\r\n\r\ndef AddPhoto(name,description,mime,album,user,stream,imgurl=''):\r\n 'Add Photo'\r\n photo = model.Photo()\r\n photo.Album = album\r\n photo.Author = user\r\n photo.Description = description\r\n photo.Mime = mime\r\n photo.Name = name\r\n photo.PhotoStream = None\r\n photo.Size=len(stream)\r\n photo.FileType,photo.Width,photo.Height=getImageInfo(stream)\r\n photo.imgurl = imgurl\r\n photo.Save()\r\n memcache.delete('ALLALBUMS')\r\n return photo\r\n\r\ndef DeletePhoto(id):\r\n photo = model.Photo().get_by_id(int(id))\r\n if photo is not None:\r\n u = UpYun()\r\n if photo.imgurl is not None:\r\n path = photo.imgurl.replace('http://imgstore.b0.upaiyun.com','')\r\n u.delete(path)\r\n photo.Album.PhotoCount -=1\r\n photo.Album.put()\r\n photo.delete()\r\n memcache.delete('ALLALBUMS')\r\n\r\n\r\n\r\n\r\n\r\n\r\n@cacheV2('PHOTO_{id}')\r\ndef GetPhoto(id):\r\n '''根据ID获取单张相片'''\r\n id=int(id)\r\n photo = model.Photo().get_by_id(id)\r\n return photo \r\n\r\n \r\n if photo is not None:\r\n #photo.ViewCount+=1\r\n #photo.Update()\r\n data['photo'] = photo\r\n data['prev'] = photo.Prev()\r\n data['next'] = photo.Next()\r\n return data; \r\n\r\n\r\n@cacheV2('PREV_PHOTO_{id}')\r\ndef PrevPhoto(id):\r\n photo = GetPhoto(id)\r\n if photo is not None:\r\n return photo.Prev()\r\n return None\r\n\r\n@cacheV2('NEXT_PHOTO_{id}')\r\ndef NextPhoto(id):\r\n photo = GetPhoto(id)\r\n if photo is not None:\r\n return Photo.Next()\r\n return None\r\n\r\n\r\ndef downImage(id,size=\"image\"):\r\n image = resizeImage(id,size)\r\n return image\r\n\r\ndef resizeImage(id,size=\"image\"):\r\n image=GetPhoto(id)\r\n if not image:return None\r\n\r\n #upyun api\r\n if size!='image':\r\n return image.imgurl+'!thumb'\r\n return image.imgurl\r\n\r\n if size==\"image\":return image\r\n img=images.Image(image.PhotoStream)\r\n width = height = 200\r\n if size == 'thumb':\r\n width = 140\r\n height = 100\r\n img.resize(width,height)\r\n img.im_feeling_lucky()\r\n image.PhotoStream=img.execute_transforms(output_encoding=images.JPEG)\r\n return image\r\n\r\n\r\ndef Settings():\r\n pass","sub_path":"methods.py","file_name":"methods.py","file_ext":"py","file_size_in_byte":3434,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"340726753","text":"import synapse.exc as s_exc\nimport synapse.datamodel as s_datamodel\n\nimport synapse.lib.module as s_module\n\nimport synapse.cortex as s_cortex\n\nimport synapse.tests.utils as s_t_utils\n\ndepmodel = {\n 'ctors': (\n ('test:dep:str', 'synapse.lib.types.Str', {'strip': True}, {'deprecated': True}),\n ),\n 'types': (\n ('test:dep:easy', ('test:str', {}), {'deprecated': True}),\n ('test:dep:comp', ('comp', {'fields': (('int', 'test:int'), ('str', 'test:dep:easy'))}), {}),\n ('test:dep:array', ('array', {'type': 'test:dep:easy'}), {})\n ),\n 'forms': (\n ('test:dep:easy', {'deprecated': True}, (\n ('guid', ('test:guid', {}), {'deprecated': True}),\n ('array', ('test:dep:array', {}), {}),\n ('comp', ('test:dep:comp', {}), {}),\n )),\n ('test:dep:str', {}, (\n ('beep', ('test:dep:str', {}), {}),\n )),\n ),\n 'univs': (\n ('udep', ('test:dep:easy', {}), {}),\n ('pdep', ('test:str', {}), {'deprecated': True})\n )\n}\n\nclass DeprecatedModel(s_module.CoreModule):\n\n def getModelDefs(self):\n return (\n ('test:dep', depmodel),\n )\n\nclass DataModelTest(s_t_utils.SynTest):\n\n async def test_datamodel_formname(self):\n modl = s_datamodel.Model()\n mods = (\n ('hehe', {\n 'types': (\n ('derp', ('int', {}), {}),\n ),\n 'forms': (\n ('derp', {}, ()),\n ),\n }),\n )\n\n with self.raises(s_exc.BadFormDef):\n modl.addDataModels(mods)\n\n async def test_datamodel_no_interface(self):\n modl = s_datamodel.Model()\n mods = (\n ('hehe', {\n 'types': (\n ('test:derp', ('int', {}), {\n 'interfaces': ('foo:bar',),\n }),\n ),\n 'forms': (\n ('test:derp', {}, ()),\n ),\n }),\n )\n\n with self.raises(s_exc.NoSuchName):\n modl.addDataModels(mods)\n\n async def test_datamodel_dynamics(self):\n\n modl = s_datamodel.Model()\n\n with self.raises(s_exc.NoSuchType):\n modl.addType('he:he', 'ha:ha', {}, {})\n\n with self.raises(s_exc.NoSuchType):\n modl.addForm('he:he', {}, [])\n\n self.none(modl.delForm('newp'))\n\n self.none(modl.delType('newp'))\n\n with self.raises(s_exc.BadPropDef):\n modl.addType('he:he', 'int', {}, {})\n modl.addForm('he:he', {}, [\n ('asdf',),\n ])\n\n with self.raises(s_exc.NoSuchProp):\n modl.delFormProp('he:he', 'newp')\n\n with self.raises(s_exc.NoSuchForm):\n modl.delFormProp('ne:wp', 'newp')\n\n with self.raises(s_exc.NoSuchUniv):\n modl.delUnivProp('newp')\n\n modl.addIface('test:iface', {})\n\n modl.addType('bar', 'int', {}, {})\n modl.addType('foo:foo', 'int', {}, {'interfaces': ('test:iface',)})\n\n modl.addForm('foo:foo', {}, ())\n modl.addFormProp('foo:foo', 'bar', ('bar', {}), {})\n\n with self.raises(s_exc.NoSuchForm):\n modl.addFormProp('foo:newp', 'bar', ('bar', {}), {})\n\n with self.raises(s_exc.CantDelType):\n modl.delType('bar')\n\n with self.raises(s_exc.CantDelForm):\n modl.delForm('foo:foo')\n\n modl.delFormProp('foo:foo', 'bar')\n modl.delForm('foo:foo')\n\n async def test_datamodel_del_prop(self):\n\n modl = s_datamodel.Model()\n\n modl.addType('foo:bar', 'int', {}, {})\n modl.addForm('foo:bar', {}, (('x', ('int', {}), {}), ))\n modl.addUnivProp('hehe', ('int', {}), {})\n modl.addFormProp('foo:bar', 'y', ('int', {}), {})\n\n self.nn(modl.prop('foo:bar:x'))\n self.nn(modl.prop('foo:bar:y'))\n self.nn(modl.prop('foo:bar.hehe'))\n\n self.nn(modl.form('foo:bar').prop('x'))\n self.nn(modl.form('foo:bar').prop('y'))\n self.nn(modl.form('foo:bar').prop('.hehe'))\n\n self.len(3, modl.propsbytype['int'])\n\n modl.delFormProp('foo:bar', 'y')\n\n self.nn(modl.prop('foo:bar:x'))\n self.nn(modl.prop('foo:bar.hehe'))\n self.nn(modl.form('foo:bar').prop('x'))\n self.nn(modl.form('foo:bar').prop('.hehe'))\n\n self.len(2, modl.propsbytype['int'])\n self.none(modl.prop('foo:bar:y'))\n self.none(modl.form('foo:bar').prop('y'))\n\n modl.delUnivProp('hehe')\n\n self.none(modl.prop('.hehe'))\n self.none(modl.form('foo:bar').prop('.hehe'))\n\n async def test_datamodel_form_refs_cache(self):\n async with self.getTestCore() as core:\n\n refs = core.model.form('test:comp').getRefsOut()\n self.len(1, refs['prop'])\n\n await core.addFormProp('test:comp', '_ipv4', ('inet:ipv4', {}), {})\n\n refs = core.model.form('test:comp').getRefsOut()\n self.len(2, refs['prop'])\n\n await core.delFormProp('test:comp', '_ipv4')\n\n refs = core.model.form('test:comp').getRefsOut()\n self.len(1, refs['prop'])\n\n async def test_model_deprecation(self):\n # Note: Inverting these currently causes model loading to fail (20200831)\n mods = ['synapse.tests.utils.TestModule',\n 'synapse.tests.test_datamodel.DeprecatedModel',\n ]\n conf = {'modules': mods}\n\n with self.getTestDir() as dirn:\n\n with self.getAsyncLoggerStream('synapse.lib.types') as tstream, \\\n self.getAsyncLoggerStream('synapse.datamodel') as dstream:\n core = await s_cortex.Cortex.anit(dirn, conf)\n\n dstream.seek(0)\n ds = dstream.read()\n self.isin('universal property .udep is using a deprecated type', ds)\n self.isin('type test:dep:easy is based on a deprecated type test:dep:easy', ds)\n tstream.seek(0)\n ts = tstream.read()\n self.isin('Array type test:dep:array is based on a deprecated type test:dep:easy', ts)\n\n # Using deprecated forms and props is warned to the user\n msgs = await core.stormlist('[test:dep:easy=test1 :guid=(t1,)] [:guid=(t2,)]')\n self.stormIsInWarn('The form test:dep:easy is deprecated', msgs)\n self.stormIsInWarn('The property test:dep:easy:guid is deprecated or using a deprecated type', msgs)\n\n # Comp type warning is logged by the server, not sent back to users\n mesg = 'type test:dep:comp field str uses a deprecated type test:dep:easy'\n with self.getAsyncLoggerStream('synapse.lib.types', mesg) as tstream:\n _ = await core.stormlist('[test:dep:easy=test2 :comp=(1, two)]')\n self.true(await tstream.wait(6))\n\n msgs = await core.stormlist('[test:str=tehe .pdep=beep]')\n self.stormIsInWarn('property test:str.pdep is deprecated', msgs)\n\n # Extended props, custom universals and tagprops can all trigger deprecation notices\n mesg = 'tag property depr is using a deprecated type test:dep:easy'\n with self.getAsyncLoggerStream('synapse.datamodel', mesg) as dstream:\n await core.addTagProp('depr', ('test:dep:easy', {}), {})\n self.true(await dstream.wait(6))\n\n mesg = 'universal property ._test is using a deprecated type test:dep:easy'\n with self.getAsyncLoggerStream('synapse.datamodel', mesg) as dstream:\n await core.addUnivProp('_test', ('test:dep:easy', {}), {})\n self.true(await dstream.wait(6))\n\n mesg = 'extended property test:str:_depr is using a deprecated type test:dep:easy'\n with self.getAsyncLoggerStream('synapse.cortex', mesg) as cstream:\n await core.addFormProp('test:str', '_depr', ('test:dep:easy', {}), {})\n self.true(await cstream.wait(6))\n\n # Deprecated ctor information propagates upward to types and forms\n msgs = await core.stormlist('[test:dep:str=\" test\" :beep=\" boop \"]')\n self.stormIsInWarn('form test:dep:str is deprecated or using a deprecated type', msgs)\n self.stormIsInWarn('property test:dep:str:beep is deprecated or using a deprecated type', msgs)\n\n await core.fini()\n\n # Restarting the cortex warns again for various items that it loads from the hive\n # with deprecated types in them. This is a coverage test for extended properties.\n with self.getAsyncLoggerStream('synapse.cortex', mesg) as cstream:\n async with await s_cortex.Cortex.anit(dirn, conf) as core:\n self.true(await cstream.wait(6))\n\n async def test_datamodel_getmodeldefs(self):\n '''\n Make sure you can make a new model with the output of datamodel.getModelDefs\n '''\n modl = s_datamodel.Model()\n modl.addIface('test:iface', {})\n modl.addType('foo:foo', 'int', {}, {'interfaces': ('test:iface',)})\n modl.addForm('foo:foo', {}, ())\n mdef = modl.getModelDefs()\n modl2 = s_datamodel.Model()\n modl2.addDataModels(mdef)\n\n async def test_model_comp_readonly_props(self):\n async with self.getTestCore() as core:\n q = '''\n syn:type:subof=comp $opts=:opts\n -> syn:form:type $valu=$node.value()\n for ($name, $thing) in $opts.fields {\n $v=$lib.str.format('{v}:{t}', v=$valu, t=$name) syn:prop=$v\n }\n +syn:prop\n -:ro=1\n '''\n nodes = await core.nodes(q)\n mesg = f'Comp forms with secondary properties that are not read-only ' \\\n f'are present in the model: {[n.ndef[1] for n in nodes]}'\n self.len(0, nodes, mesg)\n\n async def test_datamodel_edges(self):\n\n async with self.getTestCore() as core:\n\n with self.raises(s_exc.NoSuchForm):\n core.model.addEdge(('hehe', 'woot', 'newp'), {})\n\n with self.raises(s_exc.NoSuchForm):\n core.model.addEdge(('inet:ipv4', 'woot', 'newp'), {})\n\n with self.raises(s_exc.BadArg):\n core.model.addEdge(('inet:ipv4', 10, 'inet:ipv4'), {})\n\n with self.raises(s_exc.BadArg):\n core.model.addEdge(('meta:rule', 'matches', None), {})\n\n model = await core.getModelDict()\n self.isin(('meta:rule', 'matches', None), [e[0] for e in model['edges']])\n\n model = (await core.getModelDefs())[0][1]\n self.isin(('meta:rule', 'matches', None), [e[0] for e in model['edges']])\n","sub_path":"synapse/tests/test_datamodel.py","file_name":"test_datamodel.py","file_ext":"py","file_size_in_byte":10698,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"579366309","text":"# KL dendogram, heatmap, groups and MDS\r\n\r\nimport os\r\nimport csv\r\nimport numpy as np\r\nimport scipy.stats as stats\r\nimport seaborn as sns\r\nimport matplotlib.pyplot as plt\r\nimport pandas as pd\r\nfrom scipy.cluster import hierarchy\r\nfrom scipy.spatial import distance\r\nimport scipy\r\nfrom sklearn.manifold import MDS\r\nimport matplotlib.patches as mpatches\r\nfrom mpl_toolkits import mplot3d\r\nimport matplotlib.lines as mlines\r\nimport matplotlib.pyplot as plt\r\nimport scipy.cluster.hierarchy as sc\r\nfrom matplotlib.pyplot import cm\r\nimport matplotlib as mpl\r\nimport scipy.spatial.distance as ssd\r\nimport matplotlib.image as mpimg\r\n\r\n\r\ndef find_all_vs(r):\r\n all_vs = []\r\n for d, subd, files in os.walk(r):\r\n for file in files:\r\n with open(os.path.join(d, file), mode='r') as infile:\r\n reader = csv.reader(infile)\r\n vs = [row[0] for row in reader if row[0] != 'unresolved']\r\n all_vs += vs[1:] # remove header\r\n return set(all_vs)\r\n\r\n\r\ndef calc_distribution(f, vs_set, n):\r\n vs_dict = dict()\r\n # init with low values instead of 0 for the KL\r\n for v in vs_set:\r\n vs_dict[v] = 0.1\r\n with open(f, mode='r') as infile:\r\n reader = csv.reader(infile)\r\n vs = [row[0] for row in reader if row[0] != 'unresolved']\r\n # remove header\r\n vs = vs[1:]\r\n if len(vs) > n:\r\n vs = np.random.choice(vs, n)\r\n # count segments\r\n for v in vs:\r\n vs_dict[v] += 1\r\n # find distribution\r\n n = len(vs)\r\n for v in vs_dict:\r\n vs_dict[v] = vs_dict[v]/n\r\n dist = []\r\n for v in vs_set:\r\n dist.append(vs_dict[v])\r\n return dist\r\n\r\n\r\ndef names_to_labels(headers):\r\n labels = []\r\n ticks = {'Pre': 'P', 'Donors': 'D', '1_month': '1M', '1_year': '1Y', '4_years': '4Y'}\r\n for i in headers:\r\n id = i.split('_')[-1]\r\n time = '_'.join(i.split('_')[:-1])\r\n for key in ticks:\r\n if key in time:\r\n time = ticks[key]\r\n labels.append(time + '_' + id)\r\n return labels\r\n\r\n\r\ndef kl_heatmap(data, headers, my_ax):\r\n # headers = names_to_labels(headers)\r\n headers = [''] * len(headers)\r\n for i in range(len(data)):\r\n data[i][i] = np.nan\r\n h = sns.heatmap(data, xticklabels=headers, yticklabels=headers, cmap='coolwarm', annot_kws={\"size\": 10}, ax=my_ax) # vmin=0.1, vmax=0.6\r\n my_ax.set_title('Vs distributions Euclidian distance')\r\n my_ax.text(-0.1, 1.1, 'B', transform=my_ax.transAxes,\r\n fontsize=16, fontweight='bold', va='top', ha='right')\r\n\r\n\r\ndef two_groups_statistic(my_data, samples_list):\r\n g1 = ['1Y_014', '1M_014', 'D_016', '1M_016', 'D_019', '1M_037',\r\n 'D_037', '1Y_037', '1M_019', '1Y_011', 'D_011', '1M_011', '1M_001']\r\n print('--------------------------------')\r\n print('statistical tests for two groups:')\r\n within_dis = []\r\n between_dis = []\r\n for i1, s in enumerate(samples_list):\r\n if s in g1:\r\n f1 = 1\r\n else:\r\n f1 = 2\r\n for i2, s2 in enumerate(samples_list):\r\n if i1 > i2:\r\n continue\r\n if s2 in g1:\r\n f2 = 1\r\n else:\r\n f2 = 2\r\n if f1 == f2:\r\n within_dis.append(my_data[i1][i2])\r\n else:\r\n between_dis.append(my_data[i1][i2])\r\n t = scipy.stats.ttest_ind(within_dis, between_dis, equal_var=False)\r\n print('within vs. between: t=' + str(t[0]) + ', p-val=' + str(t[1]))\r\n\r\n\r\ndef time_points_statistics(my_data, samples_list):\r\n print('--------------------------------')\r\n print('statistical tests for time points:')\r\n g1 = ['1Y_014', '1M_014', '1M_016', '1M_037', '1Y_037', '1M_019', '1Y_011', '1M_011', '1M_001']\r\n dis = {'D': [], 'P': [], '1M_1': [], '1M_2': [], '1Y_1': [], '1Y_2': [], '4Y': []}\r\n for ind1, s1 in enumerate(samples_list):\r\n tp1 = s1.split('_')[0]\r\n if '1' in tp1:\r\n if s1 in g1:\r\n tp1 = tp1 + '_1'\r\n else:\r\n tp1 = tp1 + '_2'\r\n for ind2, s2 in enumerate(samples_list):\r\n if ind1 > ind2:\r\n continue\r\n tp2 = s2.split('_')[0]\r\n if '1' in tp2:\r\n if s2 in g1:\r\n tp2 = tp2 + '_1'\r\n else:\r\n tp2 = tp2 + '_2'\r\n if tp1 == tp2:\r\n dis[tp1].append(my_data[ind1][ind2])\r\n for ind1, g in enumerate(dis):\r\n for ind2, g2 in enumerate(dis):\r\n if ind1 >= ind2:\r\n continue\r\n t = scipy.stats.ttest_ind(dis[g], dis[g2], equal_var=False)\r\n if t[1] < 0.05:\r\n print(g + ' vs. ' + g2 + ': t= ' + str(t[0]) + ', p-val=' + str(t[1]))\r\n dis = {'D': [], 'P': [], '1M': [], '1Y': [], '4Y': []}\r\n for ind1, s1 in enumerate(samples_list):\r\n tp1 = s1.split('_')[0]\r\n for ind2, s2 in enumerate(samples_list):\r\n if ind1 > ind2:\r\n continue\r\n tp2 = s2.split('_')[0]\r\n if tp1 == tp2:\r\n dis[tp1].append(my_data[ind1][ind2])\r\n for ind1, g in enumerate(dis):\r\n for ind2, g2 in enumerate(dis):\r\n if ind1 >= ind2:\r\n continue\r\n t = scipy.stats.ttest_ind(dis[g], dis[g2], equal_var=False)\r\n if t[1] < 0.05:\r\n print(g + ' vs. ' + g2 + ': t= ' + str(t[0]) + ', p-val=' + str(t[1]))\r\n\r\n\r\ndef plot_cluster_gram(my_data, my_headers, my_ax):\r\n for i in range(len(my_data)):\r\n my_data[i][i] = 0\r\n samples_list = names_to_labels(my_headers)\r\n two_groups_statistic(my_data, samples_list)\r\n time_points_statistics(my_data, samples_list)\r\n distArray = ssd.squareform(my_data)\r\n linkage = sc.linkage(distArray, method='average')\r\n colors_dict = {'D': 'springgreen', 'P': 'orangered',\r\n '1M': 'royalblue', '1Y': 'orange',\r\n '4Y': 'magenta'}\r\n colors = {s: colors_dict[s.split('_')[0]] for s in samples_list}\r\n # for different branches colors chamge treshold to .7\r\n d = sc.dendrogram(linkage, labels=samples_list, color_threshold=0, above_threshold_color=\"grey\",\r\n ax=my_ax, orientation='right', leaf_font_size=7)\r\n ylbls = my_ax.get_ymajorticklabels()\r\n for i in range(len(ylbls)):\r\n ylbls[i].set_color(colors[ylbls[i].get_text()])\r\n order = [my_headers[i] for i in d['leaves']]\r\n my_ax.text(-0.1, 1.1, '2 A', transform=my_ax.transAxes,\r\n fontsize=16, fontweight='bold', va='top', ha='right')\r\n return order\r\n\r\n\r\ndef plot_categories_swarmplot(df, labels, my_ax, ts):\r\n g = sns.swarmplot(x=' ', y='Euclidian distances', data=df, order=labels, ax=my_ax, size=3)\r\n g.set_xticklabels(labels)\r\n my_ax.set_title('Euclidian Distances By Categories')\r\n # statistical annotation\r\n inds = [[0, 1], [1, 2], [2, 3], [0, 2], [0, 3], [1, 3]]\r\n y, h = df['Euclidian distances'].max(), 0.07\r\n for i, pair in enumerate(inds):\r\n if pair[0] == 0:\r\n continue\r\n t, p = ts[i]\r\n if p < 0.001:\r\n s = '***'\r\n else:\r\n if p < 0.01:\r\n s = '**'\r\n else:\r\n if p < 0.05:\r\n s = '*'\r\n else:\r\n continue\r\n my_ax.plot([pair[0], pair[0], pair[1], pair[1]], [y, y + h, y + h, y], lw=0.5, c='grey')\r\n my_ax.text((pair[0] + pair[1]) * .5, y + h, s, ha='center', va='bottom', color='k', fontsize=10)\r\n h += 0.05\r\n my_ax.text(-0.1, 1.1, 'C', transform=my_ax.transAxes,\r\n fontsize=16, fontweight='bold', va='top', ha='right')\r\n my_ax.grid(False)\r\n g.set_ylim(0, 0.3)\r\n\r\n\r\ndef calc_euclidian(a, b):\r\n return np.linalg.norm(np.array(a)-np.array(b))\r\n\r\n\r\ndef calc_statistics(group1_, group2_, group3_, group4_):\r\n anova_f = scipy.stats.f_oneway(group2_, group3_, group4_)\r\n anova_f_all = scipy.stats.f_oneway(group1_, group2_, group3_, group4_)\r\n print('--------------------------------')\r\n print('ANOVA:')\r\n print('3 groups: F=' + str(anova_f[0]) + ', p-val=' + str(anova_f[1]))\r\n print('All groups: F=' + str(anova_f_all[0]) + ', p-val=' + str(anova_f_all[1]))\r\n t1 = scipy.stats.ttest_ind(group1_, group2_, equal_var=False)\r\n t2 = scipy.stats.ttest_ind(group2_, group3_, equal_var=False)\r\n t3 = scipy.stats.ttest_ind(group3_, group4_, equal_var=False)\r\n t4 = scipy.stats.ttest_ind(group1_, group3_, equal_var=False)\r\n t5 = scipy.stats.ttest_ind(group1_, group4_, equal_var=False)\r\n t6 = scipy.stats.ttest_ind(group2_, group4_, equal_var=False)\r\n print('t-Tests:')\r\n print('category(+) host(+) vs. category(+) host(-): t=' + str(t1[0]) + ', p-val=' + str(t1[1]))\r\n print('category(+) host(-) vs. category(-) host(+): t=' + str(t2[0]) + ', p-val=' + str(t2[1]))\r\n print('category(-) host(+) vs. category(-) host(-): t=' + str(t3[0]) + ', p-val=' + str(t3[1]))\r\n print('category(+) host(+) vs. category(-) host(+): t=' + str(t4[0]) + ', p-val=' + str(t4[1]))\r\n print('category(+) host(+) vs. category(-) host(-): t=' + str(t5[0]) + ', p-val=' + str(t5[1]))\r\n print('category(+) host(-) vs. category(-) host(-): t=' + str(t6[0]) + ', p-val=' + str(t6[1]))\r\n return [t1, t2, t3, t4, t5, t6]\r\n\r\n\r\ndef scatter_3d_mds(results, samples_list):\r\n shapes = {'001': 'D', '007': '8', '011': '*', '014': 's', '016': 'v', '017': 'P',\r\n '019': 9, '022': 'H', '023': '.', '031': 8, '037': 'd'}\r\n colors_dict = {'D': 'springgreen', 'P': 'orangered',\r\n '1M': 'royalblue', '1Y': 'orange',\r\n '4Y': 'magenta'}\r\n markers = [shapes[s.split('_')[-1]] for s in samples_list]\r\n samples_list = names_to_labels(samples_list)\r\n colors = [colors_dict[s.split('_')[0]] for s in samples_list]\r\n ax = fig.add_subplot(3, 2, 4, projection='3d')\r\n for x, y, z, m, c in zip(results[:, 0], results[:, 1], results[:, 2], markers, colors):\r\n ax.scatter3D([x], [y], [z], c=c, marker=m, s=10)\r\n patches = []\r\n for key in shapes:\r\n patches.append(mlines.Line2D([], [], color='gray', marker=shapes[key], linestyle='None',\r\n markersize=7, label=key))\r\n for key in colors_dict:\r\n patches.append(mpatches.Patch(color=colors_dict[key], label=key))\r\n ax.legend(handles=patches, fontsize='small', loc='center left', bbox_to_anchor=(1, 0.5))\r\n axes[1][1].text(-0.1, 1.1, 'D', transform=ax.transAxes, fontsize=16, fontweight='bold', va='top', ha='right')\r\n ax.set_title('Euclidian Distances Of V Distribution IF')\r\n\r\n\r\ndef plot_all_avg(d, my_ax):\r\n colors = {'D': 'springgreen', 'P': 'orangered'}\r\n ticks = {'month': '1M', 'year_': '1Y', 'years': '4Y'}\r\n for cat in d:\r\n labels = []\r\n for key in colors:\r\n if key in cat:\r\n c = colors[key]\r\n break\r\n y = []\r\n yerr = []\r\n for key2 in ticks:\r\n for s2 in d[cat]:\r\n if key2 in s2:\r\n labels.append(ticks[key2])\r\n y.append(d[cat][s2][0])\r\n yerr.append(d[cat][s2][1])\r\n break\r\n my_ax.errorbar(list(range(len(y))), y, yerr=yerr,\r\n fmt='-o', color=c, label=key)\r\n my_ax.set_xticks(list(range(len(y))))\r\n my_ax.set_xticklabels(labels)\r\n my_ax.set_xlabel('Time')\r\n my_ax.set_ylabel('Euclidian Similarity')\r\n my_ax.legend(fontsize='x-small', loc=0)\r\n my_ax.set_title('Euclidian Distances Over Time')\r\n my_ax.text(-0.1, 1.1, 'E', transform=my_ax.transAxes,\r\n fontsize=16, fontweight='bold', va='top', ha='right')\r\n\r\n\r\nif __name__ == '__main__':\r\n\r\n # create grid for figure\r\n sns.set(style='whitegrid', rc={\"grid.linewidth\": 1.0})\r\n sns.set_context(\"paper\", font_scale=1.0)\r\n fig, axes = plt.subplots(3, 2, figsize=(10, 10))\r\n axes[1][1].axis(\"off\")\r\n axes[2][1].axis(\"off\")\r\n\r\n # LOAD DATA -----------------------------------------------------------------------\r\n\r\n # all possible V segments\r\n root_dir = 'BM_processed_IF'\r\n all_vs = find_all_vs(root_dir)\r\n\r\n n = 1000\r\n\r\n # generate V distribution per file\r\n dist_dict = dict()\r\n for directory, subdirectories, files in os.walk(root_dir):\r\n for file in files:\r\n path = os.path.join(directory, file)\r\n d = calc_distribution(path, all_vs, n)\r\n key = directory.split(os.sep)[1] + ':' + file\r\n dist_dict[key] = d\r\n\r\n # KL (A + B) -----------------------------------------------------------------------\r\n\r\n # compute KL between every two samples\r\n kl_dict = dict()\r\n i = 0\r\n for file in dist_dict:\r\n i += 1\r\n j = 0\r\n v_dist = dist_dict[file]\r\n kl_dict[file] = dict()\r\n for file2 in dist_dict:\r\n j += 1\r\n v2_dist = dist_dict[file2]\r\n if i <= j:\r\n kl_dict[file][file2] = calc_euclidian(v_dist, v2_dist)\r\n else:\r\n kl_dict[file][file2] = kl_dict[file2][file]\r\n\r\n # order the data\r\n samples_order = ['Donors', 'Recipients_Pre_transplant', '1_month_post', '1_year_post', '4_years_post']\r\n patients_order = ['011', '014', '001', '016', '019', '037',\r\n '007', '017', '022', '023', '031']\r\n files_order = []\r\n for sample in samples_order:\r\n for p_id in patients_order:\r\n for file in kl_dict:\r\n if sample in file and file.split('-')[2] == p_id:\r\n files_order.append([file, sample + '_' + p_id])\r\n\r\n # write data to csv\r\n file_name = 'euclidian_distances_more_files_IF.csv'\r\n with open(file_name, 'w') as csvfile:\r\n headers = [file[1] for file in files_order]\r\n fieldnames = ['file'] + headers\r\n writer = csv.DictWriter(csvfile, fieldnames=fieldnames)\r\n writer.writeheader()\r\n data_arr = []\r\n for f in files_order:\r\n data = {'file': f[1]}\r\n tmp = []\r\n file = f[0]\r\n for f2 in files_order:\r\n file2 = f2[0]\r\n val = kl_dict[file][file2]\r\n data[f2[1]] = val\r\n tmp.append(val)\r\n writer.writerow(data)\r\n data_arr.append(tmp)\r\n leaves_order = plot_cluster_gram(data_arr, headers, axes[0][0])\r\n leaves_order.reverse()\r\n\r\n # rerrange the heatmap by the clusters\r\n data_arr = []\r\n for f in leaves_order:\r\n file = [key for key in kl_dict.keys() if key.split(':')[0] == '_'.join(f.split('_')[:-1]) and f.split('_')[-1] in key.split(':')[1]][0]\r\n tmp = []\r\n for f2 in leaves_order:\r\n file2 = [key for key in kl_dict.keys() if\r\n key.split(':')[0] == '_'.join(f2.split('_')[:-1]) and f2.split('_')[-1] in key.split(':')[1]][0]\r\n val = kl_dict[file][file2]\r\n tmp.append(val)\r\n data_arr.append(tmp)\r\n kl_heatmap(data_arr, leaves_order, axes[0][1])\r\n\r\n # CATEGORIES (C) -----------------------------------------------------------------------\r\n\r\n # read distances from csv\r\n data_dict = dict()\r\n with open(file_name, mode='r') as infile:\r\n reader = csv.DictReader(infile)\r\n for row in reader:\r\n file = row['file']\r\n del row['file']\r\n data_dict[file] = row\r\n\r\n # create groups\r\n x = []\r\n y = []\r\n group1 = []\r\n group2 = []\r\n group3 = []\r\n group4 = []\r\n category_order = ['TP+ R+', 'TP+ R-', 'TP- R+', 'TP- R-']\r\n for i, file in enumerate(data_dict):\r\n sample = '_'.join(file.split('_')[:-1])\r\n id1 = file.split('_')[-1]\r\n for j, file2 in enumerate(data_dict):\r\n if i > j:\r\n continue\r\n sample2 = '_'.join(file2.split('_')[:-1])\r\n id2 = file2.split('_')[-1]\r\n if sample == sample2:\r\n if id1 == id2:\r\n x.append(category_order[0])\r\n group1.append(float(data_dict[file][file2]))\r\n else:\r\n x.append(category_order[1])\r\n group2.append(float(data_dict[file][file2]))\r\n else:\r\n if id1 == id2:\r\n x.append(category_order[2])\r\n group3.append(float(data_dict[file][file2]))\r\n else:\r\n x.append(category_order[3])\r\n group4.append(float(data_dict[file][file2]))\r\n y.append(float(data_dict[file][file2]))\r\n\r\n d = {' ': x, 'Euclidian distances': y}\r\n df = pd.DataFrame(data=d)\r\n # plot_categories_swarmplot(df, category_order, axes[1][0])\r\n\r\n # STATISTICAL TESTS -----------------------------------------------------------------------\r\n\r\n # perform ANOVA and t-tests between the groups\r\n t_results = calc_statistics(group1, group2, group3, group4)\r\n # swarmplot of all groups\r\n plot_categories_swarmplot(df, category_order, axes[1][0], t_results)\r\n\r\n # MDS (D) ---------------------------------------------------------------------------------\r\n\r\n # read distances from csv\r\n distances_mat = []\r\n with open(file_name) as csvfile:\r\n reader = csv.reader(csvfile)\r\n for i, row in enumerate(reader):\r\n if i == 0:\r\n samples = row[1:]\r\n samples = [s.replace(':', '_') for s in samples]\r\n else:\r\n if len(row) == 0:\r\n continue\r\n data = [0.0 if val == 'nan' else float(val) for val in row[1:]]\r\n distances_mat.append(data)\r\n\r\n # perform MDS on the distance matrix\r\n model = MDS(n_components=3, random_state=1)\r\n out = model.fit_transform(np.array(distances_mat))\r\n scatter_3d_mds(out, samples)\r\n\r\n # DONORS/PRE DISTANCES (E) ---------------------------------------------------------------------------------\r\n\r\n ids = ['011', '016', '019', '037']\r\n categories = ['Donors', 'Pre']\r\n\r\n # create distance dict, both categories for each time point, for every patient\r\n data_dict = dict()\r\n with open(file_name, mode='r') as infile:\r\n reader = csv.DictReader(infile)\r\n for row in reader:\r\n file = row['file']\r\n sample = '_'.join(file.split('_')[:-1])\r\n id = file.split('_')[-1]\r\n for c in categories:\r\n if c in sample and id in ids:\r\n if id not in data_dict:\r\n data_dict[id] = {key: dict() for key in categories}\r\n del row['file']\r\n for i in row:\r\n if id in i and categories[0] not in i and categories[1] not in i:\r\n data_dict[id][c][i] = row[i]\r\n\r\n # create new dictionary, for each category all distance in every time point\r\n times_d = {c: {} for c in categories}\r\n for c in categories:\r\n times = set()\r\n all_val = dict()\r\n for id in data_dict:\r\n for t in data_dict[id][c].keys():\r\n times.add('_'.join(t.split('_')[:-1]))\r\n\r\n for t in times:\r\n times_d[c][t] = []\r\n for id in ids:\r\n key = t + '_' + id\r\n times_d[c][t].append(float(data_dict[id][c].get(key, 0)))\r\n times_d[c][t] = [np.average(times_d[c][t]), np.std(times_d[c][t])]\r\n\r\n plot_all_avg(times_d, axes[2][0])\r\n\r\n # save figure\r\n plt.savefig('supp_figure2.png')\r\n fig.savefig('supp_figure2.svg', format='svg', dpi=1200)\r\n plt.close()\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"supp_Fig2.py","file_name":"supp_Fig2.py","file_ext":"py","file_size_in_byte":19682,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"481059520","text":"import sys\n\nfrom .barh import _get_matrix_of_eighths, _trim_trailing_zeros, barh\n\n\ndef hist(\n counts,\n bin_edges,\n orientation=\"vertical\",\n max_width=40,\n bins=20,\n grid=None,\n bar_width=1,\n strip=False,\n force_ascii=False,\n):\n if orientation == \"vertical\":\n return hist_vertical(\n counts,\n xgrid=grid,\n bar_width=bar_width,\n strip=strip,\n force_ascii=force_ascii,\n )\n\n assert orientation == \"horizontal\", \"Unknown orientation '{}'\".format(orientation)\n return hist_horizontal(\n counts,\n bin_edges,\n max_width=40,\n bins=20,\n bar_width=bar_width,\n force_ascii=force_ascii,\n )\n\n\ndef hist_horizontal(\n counts,\n bin_edges,\n max_width=40,\n bins=20,\n bar_width=1,\n show_bin_edges=True,\n show_counts=True,\n force_ascii=False,\n):\n if show_bin_edges:\n labels = [\n \"{:+.2e} - {:+.2e}\".format(bin_edges[k], bin_edges[k + 1])\n for k in range(len(bin_edges) - 1)\n ]\n else:\n labels = None\n\n out = barh(\n counts,\n labels=labels,\n max_width=max_width,\n bar_width=bar_width,\n show_counts=show_counts,\n force_ascii=force_ascii,\n )\n\n return out\n\n\ndef _flip(matrix):\n n = len(matrix[0])\n return [[row[-(i + 1)] for row in matrix] for i in range(n)]\n\n\ndef hist_vertical(\n counts,\n bins=30,\n max_height=10,\n bar_width=2,\n strip=False,\n xgrid=None,\n force_ascii=False,\n):\n if xgrid is None:\n xgrid = []\n\n matrix = _get_matrix_of_eighths(counts, max_height, bar_width)\n\n if strip:\n # Cut off leading and trailing rows of 0\n k0 = 0\n for row in matrix:\n if any([item != 0 for item in row]):\n break\n k0 += 1\n\n k1 = 0\n for row in matrix[::-1]:\n if any([item != 0 for item in row]):\n break\n k1 += 1\n n = len(matrix)\n matrix = matrix[k0 : n - k1]\n else:\n k0 = 0\n\n if (\n hasattr(sys.stdout, \"encoding\")\n and sys.stdout.encoding in [\"utf-8\", \"UTF-8\", \"UTF8\"]\n and not force_ascii\n ):\n block_chars = [\" \", \"▁\", \"▂\", \"▃\", \"▄\", \"▅\", \"▆\", \"▇\", \"█\"]\n left_seven_eighths = \"▉\"\n else:\n block_chars = [\" \", \"*\", \"*\", \"*\", \"*\", \"*\", \"*\", \"*\", \"*\"]\n left_seven_eighths = \"*\"\n\n # print text matrix\n out = []\n for row in _flip(matrix):\n\n # Cut off trailing zeros\n r = _trim_trailing_zeros(row)\n\n c = [block_chars[item] for item in r]\n\n # add grid lines\n for i in xgrid:\n # print(row[xgrid])\n pos = (i - k0) * bar_width - 1\n if row[pos] == 8 and (pos + 1 == len(row) or row[pos + 1] > 0):\n c[pos] = left_seven_eighths\n\n out.append(\"\".join(c))\n\n return out\n","sub_path":"asciiplotlib/hist.py","file_name":"hist.py","file_ext":"py","file_size_in_byte":2939,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"641230112","text":"import logging\nfrom settings import READ_LOG_FILE\n\n# create logger\nlogger = logging.getLogger(__name__)\nlogger.setLevel(logging.INFO)\n\n# log file\nlogfile = READ_LOG_FILE\n\n# set handlers\nfile_handler = logging.FileHandler(logfile, mode=\"w\")\nfile_handler.setLevel(logging.INFO)\n\n# formatters\nfile_format = logging.Formatter(\"*** %(asctime)s - %(filename)s: ***\\n%(levelname)s: %(message)s\")\n\n# set formatters on handlers\nfile_handler.setFormatter(file_format)\n\n# add handlers to logger\nlogger.addHandler(file_handler)\n\n\n\n\n\n\n","sub_path":"logger/read_logger.py","file_name":"read_logger.py","file_ext":"py","file_size_in_byte":522,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"428393538","text":"import re\nimport cgi\nimport urllib\nfrom services.exceptions import *\nfrom google.appengine.ext import db\n\nclass PartResource(db.Model):\n\tautoId = db.IntegerProperty(required=False)\n\tautoFatherId = db.IntegerProperty(required=False)\n\tname = db.StringProperty(required=False)\n\tupperCaseName = db.StringProperty(required=False)\n\tresourceRef = db.StringProperty(required=False)\n\tresourceCode = db.StringProperty(required=False)\n\tidFather = db.IntegerProperty(required=False)\n\n\tcompanyId = db.IntegerProperty(required=False)\n\t\n\tdef toDict(self):\n\t\tobjDic={}\n\t\tobjDic[\"id\"]=self.key().id()\n\t\tobjDic[\"autoId\"]=self.autoId\n\t\tobjDic[\"autoFatherId\"]=self.autoFatherId\n\t\tobjDic[\"name\"]=self.name\n\t\tobjDic[\"resourceRef\"]=self.resourceRef\n\t\tobjDic[\"resourceCode\"]=self.resourceCode\n\t\tobjDic[\"idFather\"]=self.idFather\n\t\treturn objDic\n\tdef toDictFront(self):\n\t\tobjDic={}\n\t\tobjDic[\"id\"]=str(self.key().id())\n\t\t#objDic[\"autoId\"]=self.autoId\n\t\t#objDic[\"autoFatherId\"]=self.autoFatherId\n\t\tobjDic[\"name\"]=self.name\n\t\tobjDic[\"resourceRef\"]=self.resourceRef\n\t\tobjDic[\"resourceCode\"]=self.resourceCode\n\t\tobjDic[\"idFather\"]=str(self.idFather)\n\t\treturn objDic\n\tdef toDictReduced(self):\n\t\tobjDic={}\n\t\tobjDic[\"id\"]=str(self.key().id())\n\t\tobjDic[\"name\"]=self.name\n\t\tobjDic[\"resourceRef\"]=self.resourceRef\n\t\tobjDic[\"resourceCode\"]=self.resourceCode\n\t\tobjDic[\"idFather\"]=str(self.idFather)\n\t\treturn objDic\n'''\n\nautoId, autoFatherId, name, upperCaseName, resourceRef, resourceCode, idFather\n\nautoId=autoId, autoFatherId=autoFatherId, name=name, upperCaseName=upperCaseName, resourceRef=resourceRef, resourceCode=resourceCode, idFather=idFather\n\nautoId\nautoFatherId\nname\nupperCaseName\nresourceRef\nresourceCode\nidFather\n\n'''","sub_path":"services/models/partResourceModel.py","file_name":"partResourceModel.py","file_ext":"py","file_size_in_byte":1691,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"145935607","text":"\"\"\"\nIn a binary tree, the root node is at depth 0, and children of each depth k node are at depth k+1.\n\nTwo nodes of a binary tree are cousins if they have the same depth, but have different parents.\n\nWe are given the root of a binary tree with unique values, and the values x and y of two different nodes in the tree.\n\nReturn true if and only if the nodes corresponding to the values x and y are cousins.\n\nExample 1:\n\nInput: root = [1,2,3,4], x = 4, y = 3\nOutput: false\n\nExample 2:\n\nInput: root = [1,2,3,null,4,null,5], x = 5, y = 4\nOutput: true\n\nExample 3:\n\nInput: root = [1,2,3,null,4], x = 2, y = 3\nOutput: false\n\nNote:\n\n The number of nodes in the tree will be between 2 and 100.\n Each node has a unique integer value from 1 to 100.\n\"\"\"\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n parent_x = 0\n parent_y = 0\n depth = 0\n def isCousins(self, root: TreeNode, x: int, y: int) -> bool:\n \n def dfs(node,parent,depth):\n if node==None:\n return \n if node.val==x:\n self.depth-=depth\n self.parent_x = parent\n if node.val==y:\n self.depth+=depth\n self.parent_y = parent\n \n dfs(node.left,node.val,depth+1)\n dfs(node.right,node.val,depth+1)\n return \n dfs(root,root.val,0)\n if self.depth==0 and self.parent_x!=self.parent_y:\n return True\n return False","sub_path":"leetcode/May-31-day/week1/cousins_in_bin_tree.py","file_name":"cousins_in_bin_tree.py","file_ext":"py","file_size_in_byte":1621,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"356939299","text":"# -*- coding:utf-8 -*-\n# @Author :kobe\n# @time :2020/8/24 17:26\n# @File :response.py\n# @Software : PyCharm\n\n\nfrom rest_framework.response import Response\nfrom rest_framework.generics import GenericAPIView\n\nclass APIResponse(Response):\n\n def __init__(self, data_status=0, data_msg='ok', results=None, http_status=None, headers=None, exception=False, **kwargs):\n # data的初始状态\n data = {\n 'statusCode': data_status,\n 'message': data_msg\n }\n # data的响应数据体\n if results is not None:\n data['results'] = results\n # data的其他数据\n # if kwargs is not None:\n # for k, v in kwargs.items():\n # self[k] = v\n # data.update(kwargs)\n if kwargs is not None:\n for k, v in kwargs.items():\n setattr(kwargs, k, v)\n super().__init__(data=data, status=http_status, headers=headers, exception=exception)\n","sub_path":"utils/response.py","file_name":"response.py","file_ext":"py","file_size_in_byte":978,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"572964286","text":"\"\"\"Functions for preprocessing texts. Not language-specific.\"\"\"\n\nfrom unicodedata import normalize\n\n\ndef cltk_normalize(text, compatibility=True):\n if compatibility:\n return normalize(\"NFKC\", text)\n else:\n return normalize(\"NFC\", text)\n\n\ndef remove_non_ascii(input_string):\n \"\"\"Remove non-ascii characters\n Source: http://stackoverflow.com/a/1342373\n \"\"\"\n no_ascii = \"\".join(i for i in input_string if ord(i) < 128)\n return no_ascii\n\n\ndef remove_non_latin(input_string, also_keep=None):\n \"\"\"Remove non-Latin characters.\n `also_keep` should be a list which will add chars (e.g. punctuation)\n that will not be filtered.\n \"\"\"\n if also_keep:\n also_keep += [\" \"]\n else:\n also_keep = [\" \"]\n latin_chars = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n latin_chars += latin_chars.lower()\n latin_chars += \"\".join(also_keep)\n no_latin = \"\".join([char for char in input_string if char in latin_chars])\n return no_latin\n","sub_path":"src/cltk/alphabet/text_normalization.py","file_name":"text_normalization.py","file_ext":"py","file_size_in_byte":974,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"183648828","text":"from skimage.morphology import medial_axis\nimport scipy.io as sio\n\nimport matplotlib.pyplot as plt\n\nimage = sio.loadmat('binaryImage.mat')['binaryImage']\n\nskeleton, distance = medial_axis(image, return_distance=True)\ndist_on_skel = distance * skeleton\n\nfig, (ax1, ax2) = plt.subplots(1, 2, figsize=(8, 4), sharex=True, sharey=True,\n subplot_kw={'adjustable': 'box-forced'})\nax1.imshow(image, cmap=plt.cm.gray, interpolation='nearest')\nax1.axis('off')\nax2.imshow(dist_on_skel, cmap=plt.cm.spectral, interpolation='nearest')\nax2.contour(image, [0.5], colors='k')\nax2.axis('off')\n\nplt.savefig('distance.png', dpi=1200)\n# plt.show()","sub_path":"skeleton.py","file_name":"skeleton.py","file_ext":"py","file_size_in_byte":658,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"170311070","text":"import tensorflow as tf\r\nimport numpy as np\r\nimport pandas as pd\r\n\r\nprint ('hello world!')\r\n\r\n\r\ndata=pd.read_csv(\"data.csv\")\r\n\r\n\r\ndata_train=np.array(data[['roll_length','d_cut_width_i','i_length_slot','hcrop','tcrop']])\r\ny_data=np.array(data[['corect_length']])\r\ndata_train=data_train.T\r\ny_data=y_data.T\r\n#print(data_train,data_train.shape)\r\n#print(y_data,y_data.shape)\r\n\r\n# print(data_train[0])\r\n# print(data_train[3])\r\n# print(data_train[4])\r\n# print ((data_train[1]*(data_train[2]-1)))\r\n#批量注释ctrl+/\r\n\r\n\r\n\r\n##create TensorFlow structure start\r\nlen_crop=tf.Variable(tf.random_uniform([1], -1.0, 1.0),name=\"len_crop\")#大小写注意!\r\n\r\ntarget_length=data_train[0]+data_train[3]+data_train[4]+len_crop+(data_train[1]*(data_train[2]-1))\r\nprint(target_length)\r\n\r\nloss=tf.reduce_mean(tf.square(target_length-y_data),name=\"loss\")\r\noptimizer=tf.train.GradientDescentOptimizer(0.01)\r\ntrain=optimizer.minimize(loss,name=\"train\")\r\n\r\n##初始化\r\ninit=tf.initialize_all_variables()\r\n##create TensorFlow structure end\r\n\r\n\r\n#执行初始化\r\nsess=tf.Session()\r\nsess.run(init)##very important\r\n\r\nwriter=tf.summary.FileWriter('./graphs',sess.graph)\r\nfor step in range(800):\r\n sess.run(train)\r\n if step %2 ==0:\r\n print(step,sess.run(len_crop))\r\nwriter.close()\r\n\r\n\r\n\r\n\r\n#filename_queue=tf.train.string_input_producer(['data.csv'])\r\n#reader=tf.TextLineReader()\r\n#key,value=reader.read(filename_queue)\r\n#print(col=tf.decode_csv(value,record_defaults=[[]*50]))","sub_path":"calcu_length_addition/calcu_length_addition.py","file_name":"calcu_length_addition.py","file_ext":"py","file_size_in_byte":1465,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"204194978","text":"import argparse\nimport os\nfrom typing import List, Union\n\nimport cv2 as cv\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n\ndef _get_grayscale_image(img: np.ndarray) -> np.ndarray:\n return cv.cvtColor(img, cv.COLOR_BGR2GRAY)\n\n\ndef _absolute_histogram(img: np.ndarray) -> List[int]:\n height, width = img.shape\n\n hist = [0] * 256\n\n for v in np.nditer(img):\n hist[v] += 1\n\n assert sum(hist) == height * width\n return hist\n\n\ndef _relative_histogram(absolute_hist: List[int]) -> List[float]:\n factor = sum(absolute_hist)\n rel_hist = [1 / factor * bin for bin in absolute_hist]\n\n assert abs(sum(rel_hist) - 1) < 1e-6\n\n return rel_hist\n\n\ndef _cumulative_histogram(hist: List[Union[int, float]]) -> List[Union[int, float]]:\n assert len(hist) == 256\n cumulative_hist = [sum(hist[:v]) for v in range(0, 256)]\n\n return cumulative_hist\n\n\ndef _calculate_histogram_mapping(abs_hist: List[float], m: int, n: int) -> List[int]:\n c = []\n for i in range(256):\n a = 255 / (m * n)\n b = sum(abs_hist[:i + 1])\n c.append(int(a * b))\n\n return c\n\n\ndef _equalize_histogram(img: np.ndarray, mapping: List[int]) -> np.ndarray:\n img_output = img.copy()\n\n for (x, y), v in np.ndenumerate(img):\n img_output[x, y] = mapping[v]\n\n return img_output\n\n\ndef _parse_arguments() -> dict:\n parser = argparse.ArgumentParser()\n parser.add_argument('file', help='The input image file.')\n\n return vars(parser.parse_args())\n\n\nimage_path = _parse_arguments()['file']\n\nif not os.path.exists(image_path):\n raise FileNotFoundError(image_path)\n\nimage = cv.imread(image_path)\nimage_gray = _get_grayscale_image(image)\nwidth, height, _ = image.shape\nabs_histogram = _absolute_histogram(image_gray)\nrel_histogram = _relative_histogram(abs_histogram)\ncum_abs_histogram = _cumulative_histogram(abs_histogram)\ncum_rel_histogram = _cumulative_histogram(rel_histogram)\n\nplt.title('Absolute histogram of {}'.format(image_path))\nplt.bar(range(len(abs_histogram)), abs_histogram)\n\nplt.show()\n\nplt.title('Relative histogram of {}'.format(image_path))\nplt.bar(range(len(rel_histogram)), rel_histogram)\nplt.show()\n\nplt.title('Cumulative relative histogram of {}'.format(image_path))\nplt.bar(range(len(cum_rel_histogram)), cum_rel_histogram)\nplt.show()\n\nmapping_hist = _calculate_histogram_mapping(abs_histogram, width, height)\nimg_eq = _equalize_histogram(image_gray, mapping_hist)\n\nplt.title('Source {} gray'.format(image_path))\nplt.imshow(image_gray, cmap='gray')\nplt.show()\n\nplt.title('Equalized {}'.format(image_path))\nplt.imshow(img_eq, cmap='gray')\nplt.show()\n\nabs_eq_histogram = _absolute_histogram(img_eq)\nrel_eq_histogram = _relative_histogram(abs_eq_histogram)\ncum_eq_rel_histogram = _cumulative_histogram(rel_eq_histogram)\n\nplt.title('Eq. Cumulative relative histogram of {}'.format(image_path))\nplt.bar(range(len(cum_eq_rel_histogram)), cum_eq_rel_histogram)\nplt.show()\n","sub_path":"histogram/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2925,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"165033562","text":"class Node(object):\n def __init__(self, value=None, pointer=None):\n self.value = value\n self.pointer = None\nclass Queue(object):\n def __init__(self):\n self.head = None\n self.tail = None\n def isEmpty(self):\n return not bool(self.head)\n\n def enqueue(self, value):\n node = Node(value)\n\n if not self.head:\n self.head = node\n self.tail = node\n else:\n if self.tail:\n self.tail.pointer = node\n self.tail = node\n\n def size(self):\n node = self.head\n\n count = 0\n while node:\n count += 1\n node = node.pointer\n return count\n\n def peek(self):\n return self.head.value\n\n def __repr__(self):\n items = []\n\n node = self.head\n while node:\n items.append(node.value)\n node = node.pointer\n items.reverse()\n return '{}'.format(items)\n\n def dequeue(self):\n if self.head:\n value = self.head.value\n\n self.head = self.head.pointer\n return value\n else:\n print('Queue is empty')\n\nif __name__ == '__main__':\n queue = Queue()\n print(queue.isEmpty())\n queue.enqueue(23)\n queue.enqueue(4)\n queue.enqueue(8)\n print(\"Size: \", queue.size())\n print(queue)\n print(\"Peek: \", queue.peek())\n print(\"Dequeue! \", queue.dequeue())\n print(queue)\n","sub_path":"Data Structures/linked_queue.py","file_name":"linked_queue.py","file_ext":"py","file_size_in_byte":1442,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"470837599","text":"main_channel = 'D0EA1QUE7' # private\nsecondary_channel = 'C0EA4CNRG' #main channel\n\ncommand_key = '--' #key identifier for commands\n\ntriggers_host = 'localhost'\ntriggers_dir = 'SFTP_1'\ntriggers_share = '\\\\\\\\' + triggers_host + '\\\\' + triggers_dir\n\n#events_host = ''\n#pflo_host = ''\n\n# bot channel id: D0EA1QUE7\n# bot_playpen channel: C0EA4CNRG\n# bot user id : U0E7M8BV1","sub_path":"globalstatic.py","file_name":"globalstatic.py","file_ext":"py","file_size_in_byte":370,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"96857957","text":"import scrapy\nfrom scrapy.selector import Selector\nfrom scrapy import signals\nfrom scrapy.xlib.pydispatch import dispatcher\nfrom afinn import Afinn\nimport os\nimport os.path\n\nclass MySpider(scrapy.Spider):\n name = \"base_spider\"\n base_dir = \"../www_roots\"\n cur_root_url = \"\"\n\n folder_size_dict = {}\n Max_Folder_Size = 1048576 #1MB\n\n def start_requests(self):\n urls = [\n 'http://www.concordia.ca/artsci/biology.html',\n 'http://www.concordia.ca/artsci/chemistry.html',\n 'http://www.concordia.ca/artsci/exercise-science.html',\n 'http://www.concordia.ca/artsci/geography-planning-environment.html',\n 'http://www.concordia.ca/artsci/math-stats.html',\n 'http://www.concordia.ca/artsci/physics.html',\n 'http://www.concordia.ca/artsci/psychology.html',\n 'http://www.concordia.ca/artsci/science-college.html',\n 'https://www.concordia.ca/artsci/science-college/about/life-at-the-college.html'\n ]\n # last link is the secret page\n\n # To be called when spider finishes\n dispatcher.connect(self.sentiment_analysis, signals.spider_closed)\n\n # create dir for the root page\n if not os.path.exists(self.base_dir):\n os.makedirs(self.base_dir)\n\n for url in urls:\n # www.example.com/foo/bar\n self.cur_root_url = url.split('://')[1]\n self.cur_root_url = url.split('.html')[0]\n print (self.cur_root_url)\n\n # e.g. Biology (used to keep record in size dictionary)\n department = self.cur_root_url.split('/')[-1]\n # www_root/bar\n cur_root_dirname = self.base_dir + \"/\" + department\n\n # create dir for the current sub-root page\n if not os.path.exists(cur_root_dirname):\n os.makedirs(cur_root_dirname)\n\n # init departments folder size\n print (\"DICT STAT\")\n print (self.folder_size_dict)\n if os.path.exists(cur_root_dirname):\n self.folder_size_dict[department] = sum(os.path.getsize(cur_root_dirname + '/' + f) for f in os.listdir(cur_root_dirname) if os.path.isfile(cur_root_dirname + '/' + f))\n else:\n self.folder_size_dict[department] = 0\n\n if self.folder_size_dict[department] < self.Max_Folder_Size:\n request = scrapy.Request(url=url, callback=self.parse)\n request.meta['cur_root_dirname'] = cur_root_dirname\n request.meta['department'] = department\n yield request\n else:\n print (\"this dept is full (in main)\")\n\n def parse(self, response):\n cur_root_dirname = response.meta['cur_root_dirname']\n department = response.meta['department']\n\n # example.html\n page = response.url.split(\"/\")[-1]\n if '.' in page:\n page_type = str(page).split('.')[1]\n else:\n page_type = \"\"\n # example\n filename = str(page).split('.')[0]\n\n # follow url if current dept folder size is under (1MB) ?\n if page_type == \"html\":\n if self.folder_size_dict[department] < self.Max_Folder_Size:\n\n # handle file saving and append count if filename exists\n count = 1\n if not os.path.isfile(cur_root_dirname + '/' + page):\n write_to_file(self, response, cur_root_dirname, department, filename)\n else:\n while os.path.isfile(cur_root_dirname + '/' + filename + str(count) + \".txt\"):\n count += 1\n write_to_file(self, response, cur_root_dirname, department, filename)\n\n # handle spawning new requests for all links in page\n for href in response.css('a::attr(href)').extract():\n # if starts with slash and not moving up dirs\n utf = str(href).encode('utf-8', 'ignore')\n if utf.startswith('/') and \"..\" not in utf and utf.endswith('.html'):\n request = scrapy.Request(response.urljoin(href), callback=self.parse)\n request.meta['cur_root_dirname'] = cur_root_dirname\n request.meta['department'] = department\n yield request\n else:\n print (\"this dept is full, (in parse)\")\n print (department)\n print (self.folder_size_dict)\n else:\n print (\"not html page\")\n print (department)\n print (self.folder_size_dict)\n\n # SENTIMENT ANALYSIS FUNCTION ######################################################\n def sentiment_analysis(self, spider):\n print (\"in sent-anal\")\n print (self.base_dir)\n afinn = Afinn()\n\n with open(\"../SCORES.txt\", 'w') as outFile:\n outFile.write(\"SENTIMENT ANALYSIS OF THE ROOT URLs (Folders)\\n\"\n \"--------------------------------------------- \")\n\n # in each root dir (root URL)\n for d in os.listdir(self.base_dir):\n d = self.base_dir + '/' + d\n if os.path.isdir(d):\n output = \"\"\n dept_score = 0\n num_words = 0\n\n # with each file, read in and add/avg score\n for f in os.listdir(d):\n f = d + '/' + f\n if os.path.isfile(f):\n with open(f, 'r') as inFile:\n file_contents = inFile.read().replace('\\n', '')\n dept_score += afinn.score(file_contents)\n num_words += len(file_contents.split())\n\n with open(\"../SCORES.txt\", 'a') as outFile:\n dept = d.split('/')[-1]\n output += \"\\n\\nDepartment : \" + dept + \\\n \"\\nScore : \" + str(dept_score) + \\\n \"\\n - Total words : \" + str(num_words) + \\\n \"\\n - Score per word: \" + str(round(dept_score/num_words, 7))\n outFile.write(output)\n print (\"Analyzing \" + dept + \" and saving to...\")\n print (str(outFile))\n\n\ndef write_to_file(self, response, cur_root_dirname, department, filename):\n path_to_file = cur_root_dirname + '/' + filename + \".txt\"\n with open(path_to_file, 'a') as f:\n site = get_tags(response)\n f.write(site.encode('utf-8', 'ignore'))\n self.log('Saved file %s' % filename)\n self.folder_size_dict[department] += os.path.getsize(path_to_file)\n\n\ndef get_tags(response):\n site = ''.join(response.xpath(\"//p//text()\").extract()).strip()\n site += ''.join(response.xpath(\"//h1//text()\").extract()).strip()\n site += ''.join(response.xpath(\"//h2//text()\").extract()).strip()\n site += ''.join(response.xpath(\"//h3//text()\").extract()).strip()\n site += ''.join(response.xpath(\"//h4//text()\").extract()).strip()\n site += ''.join(response.xpath(\"//h5//text()\").extract()).strip()\n site += ''.join(response.xpath(\"//h6//text()\").extract()).strip()\n site += ''.join(response.xpath(\"//li//text()\").extract()).strip()\n return site\n\n","sub_path":"P3/spiders/Spider.py","file_name":"Spider.py","file_ext":"py","file_size_in_byte":7302,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"645512109","text":"from flask import Flask\nfrom flask import request\nfrom flask import jsonify \nfrom flask_sqlalchemy import SQLAlchemy\n\n\n\napp = Flask(__name__) \n\n\nSECRET_KEY = 'p9Bv<3Eid9%$i01'\nSQLALCHEMY_DATABASE_URI = 'mysql://root:root@localhost/testdb'\n\napp.config[\"SQLALCHEMY_DATABASE_URI\"] = SQLALCHEMY_DATABASE_URI\n# db variable initialization\ndb = SQLAlchemy(app)\n\n\nclass User(db.Model):\n id = db.Column(db.Integer,primary_key=True)\n firstname=db.Column(db.String(30), nullable=True)\n lastname=db.Column(db.String(30), nullable=True)\n email=db.Column(db.String(50), nullable=True)\n\n\n def __repr__(self):\n return \"\".format(self.firstname)\n\n@app.route('/api/') \ndef hello_world(): \n return \"Hello World!\" \n\n@app.route(\"/api/add/\", methods=[\"POST\"])\ndef home():\n print(\"adding user is called\")\n user = User(firstname=request.form.get(\"firstname\"),lastname=request.form.get(\"lastname\"),email=request.form.get(\"email\"))\n db.session.add(user)\n db.session.commit()\n return \"inserted\"\n\n\nif __name__ == '__main__': \n app.run(host=\"0.0.0.0\", port=5000, debug=True)","sub_path":"run copy.py","file_name":"run copy.py","file_ext":"py","file_size_in_byte":1237,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"618873794","text":"import sys\nimport random\nfrom collections import *\n\ndef solve(lines):\n dic = defaultdict(lambda: 0)\n for line in lines:\n line = line.strip()\n for word in line.split(\" \"):\n dic[word] += 1\n dic = sorted(dic.items(), key = lambda x:x[0])\n return dic\n\nif __name__ == \"__main__\":\n with open(sys.argv[1]) as f:\n lines = f.readlines()\n #lines = open(sys.argv[1], \"r\")\n result = solve(lines)\n \n #単語の異なり数\n print(\"There are [{}] words in data/wiki-en-word.\".format(len(result)))\n #数単語の頻度\n for _ in range(5):\n word = result[random.randint(0, len(list(result))-1)]\n print(\"----> {} : {}\".format(word[0], word[1]))","sub_path":"nakatsuji/tutorial00/tutorial00.py","file_name":"tutorial00.py","file_ext":"py","file_size_in_byte":709,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"141684100","text":"import random\nimport socket\nimport time\n\ns = socket.socket() # Create a socket object\nhost = \"127.0.0.1\" # Get local machine name\nport = 9085\ns.bind((host, port)) # Bind to the port\n\ns.listen(5) # Now wait for client connection.\n\nwhile True:\n # Establish connection with client. \n c, (client_host, client_port) = s.accept()\n print(client_host)\n c.send('HTTP/1.0 200 OK\\n'.encode('utf-8'))\n c.send('Content-Type: text/html\\n'.encode('utf-8'))\n c.send('\\n'.encode('utf-8')) # header and body should be separated by additional newline\n c.send(\"\"\"\n \n \n

Hello World

this is my server!\n \n \n \"\"\".encode('utf-8')) # Use triple-quote string.\n c.close()","sub_path":"students/K33401/laboratory_works/Egorov_Michil/laboratory_work_1/asd.py","file_name":"asd.py","file_ext":"py","file_size_in_byte":778,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"425187495","text":"#This is a program which we are still working on, this program is used\n#to obtain a list of errors that pair a list of bad events to one fix\n\nimport re\nimport os\nimport json\nimport type_annotate\n\n\"\"\"\nupdates from list_of_errors:\n1. use 'min' field as well as 'in'\n2. fix wierd pairing\n3. create timeline for each problem\n\nNOTE: used 'in' for fix but 'min' for bad!!\n\"\"\"\n\ndir = os.path.abspath(__file__ + '/../')\ntarget = os.path.join(dir, 'sp14-concise')\n#target = os.path.join(dir, 'check-concise')\n\n#concise = os.path.join(dir, 'prob_set')\noutput3 = os.path.join(dir, 'list_of_errors_ver3.json')\noutput = os.path.join(dir, 'check.json')\n\n#homework problem list\nproblems_hw1 = ['palindrome', 'listReverse', 'digitalRoot', 'additivePersistence', 'digitsOfInt', 'sumList','???']\nproblems_hw2 = ['build', 'eval', 'exprToString', 'fixpoint', 'wwhile', 'removeDuplicates', 'assoc','???']\nproblems_hw3 = ['bigMul', 'mulByDigit', 'bigAdd', 'removeZero', 'padZero', 'clone', 'stringOfList', 'sepConcat', 'pipe', 'sqsum','???']\n\n#match home work with their sets\ndef find_problem_set(hw_num):\n problem_set = list()\n\n if hw_num == 'hw1':\n problem_set = problems_hw1\n\n elif hw_num == 'hw2':\n problem_set = problems_hw2\n\n elif hw_num == 'hw3':\n problem_set = problems_hw3\n\n return problem_set\n\n#find all the problems in the 'in' field\ndef find_all_prob(problem, lines):\n prob_list = list()\n\n for line in lines:\n item = eval(line)\n for j in item['ocaml']:\n if problem in j['in']:\n prob_list.append(item)\n break\n else:\n continue\n\n prob_list.append('???')\n break\n\n return prob_list\n\n#pack homework with the problems\ndef build_dict(hw_num, problem):\n new_dict = dict()\n new_dict['hw'] = hw_num\n new_dict['problem'] = problem\n new_dict['bad'] = []\n new_dict['fix'] = []\n return new_dict\n\n### MAIN\nof3 = open(output3, 'a')\ncount_bads = 0\ncount_groups = 0\ncount_no_fix = 0\n\nfor i in os.listdir(target):\n\n filename = str.split(i, '.')\n\n student = filename[0]\n hw_num = filename[1]\n\n #print(i)\n\n with open(os.path.join(target, i)) as inf:\n\n lines = inf.readlines()\n print(student)\n\n problem_set = find_problem_set(hw_num)\n\n for label in problem_set:\n\n #if student != 'awfong': continue\n summary = build_dict(hw_num, label)\n events = find_all_prob(label, lines)\n #print(len(events))\n\n index = 0\n\n # find the first bad program\n while index < len(events) and not events[index]['ocaml'][0]['out']:\n index += 1\n continue\n\n # find all trailing bad programs until a fix\n while index < len(events):\n\n print(student, hw_num, label, index)\n #print(summary['bad'])\n\n # 5 weird case that make the programs run into infinite loop\n if(student == 'awfong' and label == 'fixpoint' and index == 2) or \\\n (student == 'chl218' and label == 'fixpoint' and index == 5) or \\\n (student == 'cs130saw' and label == 'fixpoint' and index == 21) or \\\n (student == 'nrashink' and label == 'fixpoint' and index == 49) or \\\n (student == 'r1hull' and label == 'fixpoint' and index == 33) or \\\n (student == 'alperez' and label == 'wwhile' and index == 9) or \\\n (student == 'cs130saj' and label == 'fixpoint' and index == 13) or\\\n (student == 'cs130sat' and label == 'fixpoint' and index == 25) or \\\n (student == 'cs130sat' and label == 'fixpoint' and index == 27) or \\\n (student == 'cs130sat' and label == 'fixpoint' and index == 31) or \\\n (student == 'cs130sax' and label == 'fixpoint' and index == 54) or \\\n (student == 'cs130sbk' and label == 'fixpoint' and index == 16) or \\\n (student == 'ichin' and label == 'fixpoint' and index == 10) or \\\n (student == 'jnonno' and label == 'fixpoint' and index == 39) or \\\n (student == 'nbradbur' and label == 'fixpoint' and index == 13) or \\\n (student == 'phngo' and label == 'wwhile' and index == 13) or \\\n (student == 't10lee' and label == 'fixpoint' and index == 6) or\\\n (student == 'w7lau' and label == 'fixpoint' and index == 66) or \\\n (student == 'w7lau' and label == 'wwhile' and index == 0) or \\\n (student == 'w7lau' and label == 'wwhile' and index == 3) or \\\n (student == 'w7lau' and label == 'wwhile' and index == 13) :\n\n print(\"here\")\n of = open(output, 'a')\n #print(lines)\n of.write(str(lines))\n of.close\n index+=1\n continue\n \n # bad programs\n if (events[index]['ocaml'][0]['out'] != \"\"):\n summary['bad'].append(events[index]['ocaml'][0]['min'])\n count_bads += 1\n index += 1\n print('bad')\n continue\n \n #need to judge whether it is a true fix or not\n else:\n\n ret = type_annotate.annotate_and_compile(events[index], label, hw_num)\n #print(ret)\n #make a list of ignore flase fix\n if('rror' in ret):\n isfix = False\n else:\n isfix = True\n\n # true fix, write to file\n if (summary['bad'] != [] and isfix):\n #print(type_annotate.annotate_and_compile(events[index], label, hw_num))\n summary['fix'].append(events[index]['ocaml'][0]['min'])\n print('fix') \n index += 1\n\n # write to file, ignore empty dicts\n json.dump(summary, of3)\n of3.write('\\n')\n count_groups += 1\n\n # skip false fix\n elif( not isfix):\n #print(events[index])\n #summary['bad'].append(events[index]['ocaml'][0]['min'])\n #print('skip')\n index += 1\n\n continue\n\n # reach end of the list but finds no fix\n if summary['bad'] and (summary['fix'] == '' or not summary['fix']):\n summary['fix'].append('')\n count_no_fix += 1\n #print('no fix')\n\n # write to file\n #print(\"no fix\")\n json.dump(summary, of3)\n of3.write('\\n')\n count_groups += 1\n\n # list is not end, continue\n summary = build_dict(hw_num, label)\n\n inf.close()\n\nof3.close()\nprint(count_bads)\nprint(count_no_fix)\nprint(count_groups)","sub_path":"Spring_2016/list_of_errors_ver3/list_of_errors_ver3.py","file_name":"list_of_errors_ver3.py","file_ext":"py","file_size_in_byte":6279,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"142169125","text":"# coding: utf-8\nimport logging\nfrom collections import defaultdict, namedtuple\n\nfrom PyQt5.QtCore import (Qt, QAbstractItemModel, QModelIndex,\n QAbstractTableModel)\n\nfrom mhw_armor_edit import AmDatEntry\nfrom mhw_armor_edit.assets import Definitions\n\nlog = logging.getLogger(__name__)\n\n\nclass TreeModel(QAbstractItemModel):\n def __init__(self):\n super().__init__()\n self.root_nodes = self._get_root_nodes()\n\n def _get_root_nodes(self):\n raise NotImplementedError()\n\n def index(self, row: int, column: int, parent: QModelIndex):\n if not parent.isValid():\n return self.createIndex(row, column, self.root_nodes[row])\n parent_node = parent.internalPointer()\n return self.createIndex(row, column, parent_node.subnodes[row])\n\n def parent(self, index: QModelIndex):\n if not index.isValid():\n return QModelIndex()\n node = index.internalPointer()\n if node.parent is None:\n return QModelIndex()\n else:\n return self.createIndex(node.parent.row, 0, node.parent)\n\n def reset(self):\n self.root_nodes = self._get_root_nodes()\n QAbstractItemModel.reset(self)\n\n def rowCount(self, parent):\n if not parent.isValid():\n return len(self.root_nodes)\n node = parent.internalPointer()\n return len(node.subnodes)\n\n\nclass TreeNode:\n def __init__(self, parent, row):\n self.parent = parent\n self.row = row\n self.subnodes = []\n\n\nclass ArmorSetNode(TreeNode):\n def __init__(self, value, parent, row, children):\n super().__init__(parent, row)\n self.value = value\n self.children = children\n self.subnodes = [\n ArmorEntryNode(elem, self, index)\n for index, elem in enumerate(children)\n ]\n\n\nclass ArmorEntryNode(TreeNode):\n def __init__(self, ref, parent, row):\n super().__init__(parent, row)\n self.ref = ref\n self.subnodes = []\n\n @property\n def value(self):\n return self.ref.equip_slot\n\n\nEntryKey = namedtuple(\"EntryKey\", [\"index\", \"equip_slot\"])\n\n\nclass ArmorSetTreeModel(TreeModel):\n def __init__(self, entries):\n self.entries = entries\n super().__init__()\n\n def _get_root_nodes(self):\n groups = defaultdict(list)\n keys = list()\n for entry in self.entries:\n group_key = entry.set_id\n entry_key = EntryKey(\n entry.index,\n Definitions.lookup(\"equip_slot\", entry.equip_slot)\n )\n groups[group_key].append(entry_key)\n if group_key not in keys:\n keys.append(group_key)\n return [\n ArmorSetNode(Definitions.lookup(\"set\", key), None, index, groups[key])\n for index, key in enumerate(keys)\n ]\n\n def columnCount(self, parent):\n return 1\n\n def data(self, index, role):\n if not index.isValid():\n return None\n node = index.internalPointer()\n if role == Qt.DisplayRole and index.column() == 0:\n return node.value\n return None\n\n def headerData(self, section, orientation, role):\n if orientation == Qt.Horizontal \\\n and role == Qt.DisplayRole \\\n and section == 0:\n return 'Name'\n return None\n\n def roleNames(self):\n return {\n Qt.UserRole + 1: b\"set\"\n }\n\n\nclass ArmorListModel(QAbstractTableModel):\n def __init__(self, entries):\n self.entries = entries\n super().__init__()\n\n def rowCount(self, parent=None, *args, **kwargs):\n return len(self.entries)\n\n def columnCount(self, parent=None, *args, **kwargs):\n return 3\n\n def data(self, index, role=None):\n if role == Qt.DisplayRole:\n if index.column() == 0:\n entry = self.entries[index.row()]\n return str(entry.index)\n if index.column() == 1:\n entry = self.entries[index.row()]\n return Definitions.lookup(\"set\", entry.set_id)\n if index.column() == 2:\n entry = self.entries[index.row()]\n return Definitions.lookup(\"equip_slot\", entry.equip_slot)\n return None\n\n def headerData(self, section, orient, role=None):\n if orient == Qt.Horizontal \\\n and role == Qt.DisplayRole:\n if section == 0: return \"Index\"\n if section == 1: return \"Set\"\n if section == 2: return \"Equip Slot\"\n return None\n","sub_path":"src/mhw_armor_edit/tree.py","file_name":"tree.py","file_ext":"py","file_size_in_byte":4575,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"48412792","text":"# Open File\r\nfile = open(\"WorldSeriesWinners.txt\", \"r\")\r\n# Read lines in the file\r\nfilelines = file.readlines()\r\n# Create a list for the stripped lines\r\nstrippedfile = []\r\n# Iterate through filelines variable and append elements into the list stripped of \\n\r\nfor team in filelines:\r\n strippedfile.append(team.rstrip(\"\\n\"))\r\n\r\n# Set the stage - create dictionaries and variables\r\nteamdictionary = {}\r\nyearwinner = {}\r\nyearinteger = 1903\r\nnumberofwins = 0\r\nfirstyear = yearinteger\r\nlastyear = 0\r\n\r\n# Iterate through teams in the stripped file\r\nfor team in strippedfile:\r\n # if the year is 1904 or 1994, when the world series wasn't played, store its value as no world series this year\r\n if yearinteger == 1904 or yearinteger == 1994:\r\n yearwinner[yearinteger] = \"No World Series This Year\"\r\n # if the year is any other year, set the value to the team\r\n else:\r\n yearwinner[yearinteger] = team\r\n # accumulate\r\n yearinteger += 1\r\n\r\n # If the team isn't in the team dictionary yet, put it in there and set its value to 1\r\n if team not in teamdictionary:\r\n teamdictionary[team] = 1\r\n # if it is in there, add one to its value\r\n else:\r\n numberofwins = teamdictionary[team]\r\n newnumberofwins = numberofwins + 1\r\n teamdictionary[team] = newnumberofwins\r\n\r\n# preparation for print statements - the .txt file only contained world series from 1903 to 2006, so I used a variable rather than hardcoding those values\r\nlastyear = yearinteger - 1\r\n\r\n# Ask user for a year\r\nUserinput = int(input(\"Please enter a value between 1903 and 2006: \"))\r\n\r\n# If the year isn't between the first and last year, error out\r\nif Userinput not in range(firstyear, lastyear + 1):\r\n print(\"Error: Please Enter A Value Between\", firstyear, \"and\", lastyear)\r\n# If the year is 1904 or 1994, tell the user there is not a world series in that year\r\nelif Userinput == 1904 or Userinput == 1994:\r\n print(\"There was not a World Series in that year\")\r\n# Print the team and how many times they have won for the user's inputted year\r\nelse:\r\n print(\r\n \"The\",\r\n yearwinner[Userinput],\r\n \"won in\",\r\n Userinput,\r\n \"and they have won the world series\",\r\n teamdictionary[yearwinner[Userinput]],\r\n \"times in total.\",\r\n )\r\n\r\n# close file\r\nfile.close()\r\n","sub_path":"World Series Winners.py","file_name":"World Series Winners.py","file_ext":"py","file_size_in_byte":2334,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"213358331","text":"from tkinter import *\nfrom tkinter import ttk\nimport pyperclip\n\ntranslate = ''\n\n# Add in mode checkboxes later\n#mode = { 1: 'encrypt', 2: 'decrypt'}\n#modeSelect = mode[1]\n\n\ndef encrypt(*args):\n global translate\n try:\n msg = str(plain_or_cipher_txt.get()).upper()\n key = float(keyStore.get())\n LETTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'\n for symbol in msg:\n if symbol in LETTERS:\n num = LETTERS.find(symbol)\n num = num + key\n if num >= len(LETTERS):\n num = num - len(LETTERS)\n elif num < 0:\n num = num + len(LETTERS)\n translate = translate + LETTERS[int(num)]\n converted.set(translate)\n else:\n translate = translate + symbol\n converted.set(translate)\n pyperclip.copy(translate)\n except TypeError:\n pass\n except ValueError:\n pass\n\ndef decrypt(*args):\n global translate\n try:\n msg = str(plain_or_cipher_txt.get()).upper()\n key = float(keyStore.get())\n LETTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'\n for symbol in msg:\n if symbol in LETTERS:\n num = LETTERS.find(symbol)\n num = num - key\n if num >= len(LETTERS):\n num = num - len(LETTERS)\n elif num < 0:\n num = num + len(LETTERS)\n translate = translate + LETTERS[int(num)]\n converted.set(translate)\n else:\n translate = translate + symbol\n converted.set(translate)\n except TypeError:\n pass\n except ValueError:\n pass\n\ndef clearLabel():\n global translate\n translate = ''\n plain_or_cipher_txt.set('')\n converted.set('')\n keyStore.set('')\n\n\n# window framework\nroot = Tk()\nroot.title(\"Caesar Cipher\")\nmainframe = ttk.Frame(root, padding=\"3 3 12 12\")\nmainframe.grid(column=0, row=0, sticky=(N, W, E, S))\nmainframe.columnconfigure(0, weight=1)\nmainframe.rowconfigure(0, weight=1)\n\n# vars\nplain_or_cipher_txt = StringVar()\nconverted = StringVar()\nkeyStore = StringVar()\n\n#plain txt entry\nplain_or_cipher_txt_entry = ttk.Entry(mainframe, width=15, textvariable=plain_or_cipher_txt)\nplain_or_cipher_txt_entry.grid(column=1, row=1, sticky=(W, E))\nttk.Label(mainframe, text=\"Plain/Cipher Text\").grid(column=2, row=1, sticky=W)\n\n# key entry\nkey_entry = ttk.Entry(mainframe, width=4, textvariable=keyStore)\nkey_entry.grid(column=1, row=2, sticky=(E))\nttk.Label(mainframe, text='Key').grid(column=2, row=2, sticky=W)\n\n# encryption button\nttk.Button(mainframe, text=\"Encrypt\", command=encrypt).grid(column=1, row=3, sticky=E)\n\n# decryption button\nttk.Button(mainframe, text=\"Decrypt\", command=decrypt).grid(column=2, row=3)\n\n# clear button\nttk.Button(mainframe, text=\"Clear All\", command=clearLabel).grid(column=3, row=3, sticky=E)\n\n# translated txt\nttk.Label(mainframe, text=\"Translated:\").grid(column=1, row=4, sticky=W)\nttk.Label(mainframe, textvariable=converted).grid(column=2, row=4, sticky=(W, E))\n\nfor child in mainframe.winfo_children(): child.grid_configure(padx=5, pady=5)\nplain_or_cipher_txt_entry.focus()\nroot.bind('', encrypt)\n\nroot.mainloop()\n","sub_path":"caesar.py","file_name":"caesar.py","file_ext":"py","file_size_in_byte":3273,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"343009946","text":"import numpy as np\n\n\ndef getRC2Ind(imgShape, imageMask=None):\n \"\"\"\n In a 2D image, get a dictionary mapping from (row, col) to linear index i of flattened image, and vice versa,\n :param imgShape: the shape of the image\n :param imageMask: if the image is sparse, use imageMask to generate the mapping\n :return:\n \"\"\"\n if imageMask == None:\n imageMask = np.ones(imgShape) > 0\n N_x, N_y = imgShape[1], imgShape[0]\n x = np.arange(N_x)\n y = np.arange(N_y)\n X, Y = np.meshgrid(x, y)\n ind_rc_map = np.zeros((imgShape[0] * imgShape[1], 3), dtype='int')\n for i, (r, c) in enumerate(zip(Y[imageMask], X[imageMask])):\n ind_rc_map[i, :] = [i, r, c]\n # make a dictionary\n ind2rc = {x[0]: tuple(x[1:]) for x in ind_rc_map}\n rc2ind = {tuple(x[1:]): x[0] for x in ind_rc_map}\n return ind2rc, rc2ind","sub_path":"lbl_ir/lbl_ir/gui_tools/rc2ind_mapping.py","file_name":"rc2ind_mapping.py","file_ext":"py","file_size_in_byte":846,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"77290946","text":"import torch\nimport torch.nn as nn\nimport os\nimport gym\n\nimport argparse\nimport math\nfrom torch.distributions import Normal\nfrom utils import *\n\nimport pickle\nimport argparse\nimport numpy as np\nfrom collections import deque\n\nimport torch.optim as optim\n\n\n\ndef get_action(mu, std):\n action = torch.normal(mu, std)\n action = action.data.numpy()\n return action\n\ndef get_entropy(mu, std):\n dist = Normal(mu, std)\n entropy = dist.entropy().mean()\n return entropy\n\ndef log_prob_density(x, mu, std):\n log_prob_density = -(x - mu).pow(2) / (2 * std.pow(2)) \\\n - 0.5 * math.log(2 * math.pi)\n return log_prob_density.sum(1, keepdim=True)\n\ndef get_reward(discrim, state, action):\n state = torch.Tensor(state)\n action = torch.Tensor(action)\n state_action = torch.cat([state, action])\n with torch.no_grad():\n return -math.log(discrim(state_action)[0].item())\n\ndef save_checkpoint(state, filename):\n torch.save(state, filename)\n\n\nimport torch\nimport numpy as np\n# from utils.utils import get_entropy, log_prob_density\n\n\ndef train_discrim(discrim, memory, discrim_optim, demonstrations, args):\n memory = np.array(memory)\n states = np.vstack(memory[:, 0])\n actions = list(memory[:, 1])\n\n states = torch.Tensor(states)\n actions = torch.Tensor(actions)\n\n criterion = torch.nn.BCELoss()\n\n for _ in range(args.discrim_update_num):\n learner = discrim(torch.cat([states, actions], dim=1))\n demonstrations = torch.Tensor(demonstrations)\n expert = discrim(demonstrations)\n\n discrim_loss = criterion(learner, torch.ones((states.shape[0], 1))) + \\\n criterion(expert, torch.zeros((demonstrations.shape[0], 1)))\n\n discrim_optim.zero_grad()\n discrim_loss.backward()\n discrim_optim.step()\n\n expert_acc = ((discrim(demonstrations) < 0.5).float()).mean()\n learner_acc = ((discrim(torch.cat([states, actions], dim=1)) > 0.5).float()).mean()\n\n return expert_acc, learner_acc\n\n\ndef train_actor_critic(actor, critic, memory, actor_optim, critic_optim, args):\n memory = np.array(memory)\n states = np.vstack(memory[:, 0])\n actions = list(memory[:, 1])\n rewards = list(memory[:, 2])\n masks = list(memory[:, 3])\n\n old_values = critic(torch.Tensor(states))\n returns, advants = get_gae(rewards, masks, old_values, args)\n\n mu, std = actor(torch.Tensor(states))\n old_policy = log_prob_density(torch.Tensor(actions), mu, std)\n\n criterion = torch.nn.MSELoss()\n n = len(states)\n arr = np.arange(n)\n\n for _ in range(args.actor_critic_update_num):\n np.random.shuffle(arr)\n\n for i in range(n // args.batch_size):\n batch_index = arr[args.batch_size * i: args.batch_size * (i + 1)]\n batch_index = torch.LongTensor(batch_index)\n\n inputs = torch.Tensor(states)[batch_index]\n actions_samples = torch.Tensor(actions)[batch_index]\n returns_samples = returns.unsqueeze(1)[batch_index]\n advants_samples = advants.unsqueeze(1)[batch_index]\n oldvalue_samples = old_values[batch_index].detach()\n\n values = critic(inputs)\n clipped_values = oldvalue_samples + \\\n torch.clamp(values - oldvalue_samples,\n -args.clip_param,\n args.clip_param)\n critic_loss1 = criterion(clipped_values, returns_samples)\n critic_loss2 = criterion(values, returns_samples)\n critic_loss = torch.max(critic_loss1, critic_loss2).mean()\n\n loss, ratio, entropy = surrogate_loss(actor, advants_samples, inputs,\n old_policy.detach(), actions_samples,\n batch_index)\n clipped_ratio = torch.clamp(ratio,\n 1.0 - args.clip_param,\n 1.0 + args.clip_param)\n clipped_loss = clipped_ratio * advants_samples\n actor_loss = -torch.min(loss, clipped_loss).mean()\n\n loss = actor_loss + 0.5 * critic_loss - 0.001 * entropy\n\n critic_optim.zero_grad()\n loss.backward(retain_graph=True)\n critic_optim.step()\n\n actor_optim.zero_grad()\n loss.backward()\n actor_optim.step()\n\n\ndef get_gae(rewards, masks, values, args):\n rewards = torch.Tensor(rewards)\n masks = torch.Tensor(masks)\n returns = torch.zeros_like(rewards)\n advants = torch.zeros_like(rewards)\n\n running_returns = 0\n previous_value = 0\n running_advants = 0\n\n for t in reversed(range(0, len(rewards))):\n running_returns = rewards[t] + (args.gamma * running_returns * masks[t])\n returns[t] = running_returns\n\n running_delta = rewards[t] + (args.gamma * previous_value * masks[t]) - \\\n values.data[t]\n previous_value = values.data[t]\n\n running_advants = running_delta + (args.gamma * args.lamda * \\\n running_advants * masks[t])\n advants[t] = running_advants\n\n advants = (advants - advants.mean()) / advants.std()\n return returns, advants\n\n\ndef surrogate_loss(actor, advants, states, old_policy, actions, batch_index):\n mu, std = actor(states)\n new_policy = log_prob_density(actions, mu, std)\n old_policy = old_policy[batch_index]\n\n ratio = torch.exp(new_policy - old_policy)\n surrogate_loss = ratio * advants\n entropy = get_entropy(mu, std)\n\n return surrogate_loss, ratio, entropy\n\nclass Actor(nn.Module):\n def __init__(self, num_inputs, num_outputs, args):\n super(Actor, self).__init__()\n self.fc1 = nn.Linear(num_inputs, args.hidden_size)\n self.fc2 = nn.Linear(args.hidden_size, args.hidden_size)\n self.fc3 = nn.Linear(args.hidden_size, num_outputs)\n\n self.fc3.weight.data.mul_(0.1)\n self.fc3.bias.data.mul_(0.0)\n\n def forward(self, x):\n x = torch.tanh(self.fc1(x))\n x = torch.tanh(self.fc2(x))\n mu = self.fc3(x)\n logstd = torch.zeros_like(mu)\n std = torch.exp(logstd)\n return mu, std\n\n\nclass Critic(nn.Module):\n def __init__(self, num_inputs, args):\n super(Critic, self).__init__()\n self.fc1 = nn.Linear(num_inputs, args.hidden_size)\n self.fc2 = nn.Linear(args.hidden_size, args.hidden_size)\n self.fc3 = nn.Linear(args.hidden_size, 1)\n\n self.fc3.weight.data.mul_(0.1)\n self.fc3.bias.data.mul_(0.0)\n\n def forward(self, x):\n x = torch.tanh(self.fc1(x))\n x = torch.tanh(self.fc2(x))\n v = self.fc3(x)\n return v\n\n\nclass Discriminator(nn.Module):\n def __init__(self, num_inputs, args):\n super(Discriminator, self).__init__()\n self.fc1 = nn.Linear(num_inputs, args.hidden_size)\n self.fc2 = nn.Linear(args.hidden_size, args.hidden_size)\n self.fc3 = nn.Linear(args.hidden_size, 1)\n\n self.fc3.weight.data.mul_(0.1)\n self.fc3.bias.data.mul_(0.0)\n\n def forward(self, x):\n x = torch.tanh(self.fc1(x))\n x = torch.tanh(self.fc2(x))\n prob = torch.sigmoid(self.fc3(x))\n return prob\n\n\n\n\n\n# parser = argparse.ArgumentParser()\n# parser.add_argument('--env', type=str, default=\"Hopper-v2\",\n# help='name of Mujoco environement')\n# parser.add_argument('--iter', type=int, default=5,\n# help='number of episodes to play')\n# parser.add_argument(\"--load_model\", type=str, default='ppo_max.tar',\n# help=\"if you test pretrained file, write filename in save_model folder\")\n#\n# args = parser.parse_args()\n\nif __name__ == \"__main__\":\n\n env = gym.make(args.env_name)\n env.seed(args.seed)\n torch.manual_seed(args.seed)\n\n num_inputs = env.observation_space.shape[0]\n num_actions = env.action_space.shape[0]\n running_state = ZFilter((num_inputs,), clip=5)\n\n print('state size:', num_inputs)\n print('action size:', num_actions)\n\n actor = Actor(num_inputs, num_actions, args)\n critic = Critic(num_inputs, args)\n discrim = Discriminator(num_inputs + num_actions, args)\n\n actor_optim = optim.Adam(actor.parameters(), lr=args.learning_rate)\n critic_optim = optim.Adam(critic.parameters(), lr=args.learning_rate,\n weight_decay=args.l2_rate)\n discrim_optim = optim.Adam(discrim.parameters(), lr=args.learning_rate)\n\n # load demonstrations\n expert_demo, _ = pickle.load(open('./expert_demo/expert_demo.p', \"rb\"))\n demonstrations = np.array(expert_demo)\n print(\"demonstrations.shape\", demonstrations.shape)\n\n writer = SummaryWriter(args.logdir)\n\n if args.load_model is not None:\n saved_ckpt_path = os.path.join(os.getcwd(), 'save_model', str(args.load_model))\n ckpt = torch.load(saved_ckpt_path)\n\n actor.load_state_dict(ckpt['actor'])\n critic.load_state_dict(ckpt['critic'])\n discrim.load_state_dict(ckpt['discrim'])\n\n running_state.rs.n = ckpt['z_filter_n']\n running_state.rs.mean = ckpt['z_filter_m']\n running_state.rs.sum_square = ckpt['z_filter_s']\n\n print(\"Loaded OK ex. Zfilter N {}\".format(running_state.rs.n))\n\n episodes = 0\n train_discrim_flag = True\n\n for iter in range(args.max_iter_num):\n actor.eval(), critic.eval()\n memory = deque()\n\n steps = 0\n scores = []\n\n while steps < args.total_sample_size:\n state = env.reset()\n score = 0\n\n state = running_state(state)\n\n for _ in range(10000):\n if args.render:\n env.render()\n\n steps += 1\n\n mu, std = actor(torch.Tensor(state).unsqueeze(0))\n action = get_action(mu, std)[0]\n next_state, reward, done, _ = env.step(action)\n irl_reward = get_reward(discrim, state, action)\n\n if done:\n mask = 0\n else:\n mask = 1\n\n memory.append([state, action, irl_reward, mask])\n\n next_state = running_state(next_state)\n state = next_state\n\n score += reward\n\n if done:\n break\n\n episodes += 1\n scores.append(score)\n\n score_avg = np.mean(scores)\n print('{}:: {} episode score is {:.2f}'.format(iter, episodes, score_avg))\n writer.add_scalar('log/score', float(score_avg), iter)\n\n actor.train(), critic.train(), discrim.train()\n if train_discrim_flag:\n expert_acc, learner_acc = train_discrim(discrim, memory, discrim_optim, demonstrations, args)\n print(\"Expert: %.2f%% | Learner: %.2f%%\" % (expert_acc * 100, learner_acc * 100))\n if expert_acc > args.suspend_accu_exp and learner_acc > args.suspend_accu_gen:\n train_discrim_flag = False\n train_actor_critic(actor, critic, memory, actor_optim, critic_optim, args)\n\n if iter % 100:\n score_avg = int(score_avg)\n\n model_path = os.path.join(os.getcwd(), 'save_model')\n if not os.path.isdir(model_path):\n os.makedirs(model_path)\n\n ckpt_path = os.path.join(model_path, 'ckpt_' + str(score_avg) + '.pth.tar')\n\n save_checkpoint({\n 'actor': actor.state_dict(),\n 'critic': critic.state_dict(),\n 'discrim': discrim.state_dict(),\n 'z_filter_n': running_state.rs.n,\n 'z_filter_m': running_state.rs.mean,\n 'z_filter_s': running_state.rs.sum_square,\n 'args': args,\n 'score': score_avg\n }, filename=ckpt_path)","sub_path":"algos/behavioral_cloning/GAIL.py","file_name":"GAIL.py","file_ext":"py","file_size_in_byte":11823,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"161725214","text":"from odoo import fields,models,api,_\nimport datetime\n\n\nclass SupportTicket(models.Model):\n _name = 'support.ticket'\n _inherit='mail.thread'\n _description = 'Sunfire Support Desk'\n _rec_name='name'\n \n name = fields.Char(string='Subject',help=\"The Subject of the Support Ticket.\")\n tag_id=fields.Many2one('support.tag',string=\"Tag\",required=True,help=\"Tag of current Support Ticket. Incident/Request/Change Request/Problem\")\n ticket_no=fields.Char(string=\"Ticket No.\",store=True,help=\"Ticket Number of the current Support Ticket\")\n channel_id=fields.Many2one('support.channel',string=\"Channel\",help=\"Channel of the current Support Ticket\")\n severity_id=fields.Many2one('support.severity',string=\"Severity\",help=\"Severity of the current Support Ticket\")\n category_id=fields.Many2one('support.category',string=\"Category\",help=\"Category of the current Support Ticket\")\n\n \n logged_date=fields.Datetime(string=\"Looged Time\",help=\"Last Action Taken Time\",compute='compute_logged_date')\n \n @api.multi\n def compute_logged_date(self):\n li=[]\n for actions in self:\n for action_lines in actions.action_line:\n if action_lines.write_date:\n li.append(action_lines.write_date)\n if li!=[]:\n actions.logged_date=max(li)\n li=[]\n\n \n #Setting the domain of Assigned User to Technical Users\n @api.model\n def onchng_user(self):\n appr_obj=self.env['approval_types.info'].search([('approval_type','=','Technical Services')])\n li=[]\n domain={}\n for i in appr_obj.role_line:\n li.append(i.users.id)\n domain['assigned_user_id']=[('id','in',li)]\n #print(\"Onchange================>\")\n return [('id','in',li)]\n \n assigned_user_id=fields.Many2one('res.users',string=\"Assigned Engineer\",domain=lambda self:self.onchng_user(),track_visibility='always',help=\"The Technical User to whom the Ticket is to be assigned\")\n partner_id=fields.Many2one('res.partner',string=\"Customer\",help=\"The Customer who has raised the Ticket\")\n email=fields.Char(string=\"Email\",help=\"The Email of the Customer who has raised the Ticket\")\n action_line=fields.One2many('support.actions','action_id',help=\"The Actions taken by the Assigned User on the Suppport Ticket\")\n attach_line=fields.One2many('support.attach','attach_id',help=\"The Documents for the Support Ticket\")\n description_line=fields.One2many('support.description','description_id')\n state=fields.Selection([\n ('open', 'Open'),\n ('assigned', 'Assigned'),\n ('in_progress', 'Work in Progress'),\n ('awaiting', 'Awaiting Customer'),\n ('resolved', 'Resolved'),('closed','Closed')\n ], string='Status', readonly=True, copy=False, index=True, track_visibility='onchange', default='open')\n time_assign=fields.Datetime('Assign Time')\n time_resolve=fields.Datetime('Resolve Time')\n time_open=fields.Datetime('Open Time')\n time_close=fields.Datetime('Close Time')\n reassign=fields.Boolean('Reassign',default=False)\n reassign_line=fields.One2many('support.reassign','reassign_id',string='Reassigned User')\n mobile=fields.Char(string=\"Mobile\")\n \n #Function to frwd mail on change of state\n def state_mail(self):\n email_template = self.env['ir.model.data'].get_object('sunfire_support','support_ticket_status_mail')\n email_values = email_template.generate_email([self.id])[self.id]\n email_values['model'] = \"support.ticket\"\n email_values['res_id'] = self.id\n #assigned_user = self.env['res.users'].browse( int(values['user_id']) )\n email_values['email_to'] = self.partner_id.email or self.email\n email_values['body_html'] = email_values['body_html'].replace(\"_user_name_\", self.partner_id.name)\n email_values['body'] = email_values['body'].replace(\"_user_name_\", self.partner_id.name)\n send_mail = self.env['mail.mail'].create(email_values)\n #print(\"here======+>\")\n send_mail.send() \n\n @api.multi\n def action_assigned(self):\n if self.assigned_user_id:\n values={ \n 'reassign_id':self.id,\n 'user_id':self.env.uid,\n 'reassign_user_id':self.assigned_user_id.id\n }\n self.reassign_line.create(values)\n #self.state_mail()\n return self.write({'state': 'assigned','time_assign':datetime.datetime.now()})\n @api.multi\n def action_in_progress(self):\n #self.state_mail()\n return self.write({'state': 'in_progress'})\n @api.multi\n def action_awaiting(self):\n #self.state_mail()\n return self.write({'state': 'awaiting'})\n @api.multi\n def action_resolved(self):\n #self.state_mail()\n return self.write({'state': 'resolved','time_resolve':datetime.datetime.now()})\n @api.multi\n def action_close(self):\n #self.state_mail()\n return self.write({'state': 'closed','time_close':datetime.datetime.now()})\n #Set Email of the Customer if present else Enter on screen\n @api.onchange('partner_id')\n def set_email(self):\n if self.partner_id:\n #print(self.partner_id.child_ids.id)\n for i in self.partner_id.child_ids:\n if i.type=='cust_it_support':\n #print(i.email,i.mobile)\n self.email=i.email\n self.mobile=i.mobile\n #assigns ticket number\n def set_ticket_number(self,vals):\n tag_obj=self.env['support.tag']\n\n tag_ids=tag_obj.search([('id','=',vals['tag_id'])])\n vals['time_open']=datetime.datetime.now()\n if tag_ids.name==\"Incident\":\n vals['ticket_no'] = self.env['ir.sequence'].next_by_code('website.support.ticket.incident') \n elif tag_ids.name==\"Request\": \n vals['ticket_no'] = self.env['ir.sequence'].next_by_code('website.support.ticket.request')\n elif tag_ids.name==\"Change Request\":\n vals['ticket_no'] = self.env['ir.sequence'].next_by_code('website.support.ticket.change_request')\n elif tag_ids.name==\"Problem\":\n vals['ticket_no'] = self.env['ir.sequence'].next_by_code('website.support.ticket.problem')\n else:\n vals['ticket_no'] = self.env['ir.sequence'].next_by_code('website.support.ticket')\n \n #Create Method\n @api.model\n def create(self, vals):\n self.set_ticket_number(vals)\n new_id = super(SupportTicket,self).create(vals)\n return new_id\n \n @api.multi\n def write(self,vals):\n if 'reassign' in vals and 'assigned_user_id' in vals:\n if vals['reassign']==True:\n values={ \n 'reassign_id':self.id,\n 'user_id':self.env.uid,\n 'reassign_user_id':vals['assigned_user_id']\n }\n re_id=self.reassign_line.create(values)\n #print(re_id)\n vals['reassign']=False\n new_id = super(SupportTicket,self).write(vals)\n return new_id\n\n#Master for Description\nclass SupportDescription(models.Model):\n _name='support.description'\n _rec_name='name'\n _description=\"Sunfire Support Description\"\n name=fields.Char(string=\"Description\",help=\"The Description by the User for the current Support Ticket\")\n user_id=fields.Many2one('res.users',readonly=True,store=True,string=\"User\")\n description_id=fields.Many2one('support.ticket')\n\n @api.model\n def create(self,vals):\n #web_obj=self.env['support.ticket'].search([('id','=',vals['description_id'])])\n vals['user_id']=self.env.uid\n new_id = super(SupportDescription, self).create(vals)\n return new_id\n#Master for Attachments\nclass SupportAttach(models.Model):\n _name=\"support.attach\"\n _description=\"Sunfire Support Attachment\"\n _rec_name=\"name\"\n name=fields.Char(string=\"Atachment Description\",help=\"The Description for the Attachment attached\")\n attachment=fields.Binary('Attachment',help=\"The Attachement to be attached for the Support Ticket\")\n attach_id=fields.Many2one('support.ticket')\n filename=fields.Char('Filename')\n\n \n#Master for Actions Taken\nclass SupportActions(models.Model):\n _name=\"support.actions\"\n _description=\"Sunfire Support Actions\"\n _rec_name=\"name\"\n name=fields.Char(string=\"Actions Taken\",help=\"The Action taken by the User for the current Support Ticket\")\n assigned_user_id=fields.Many2one('res.users',readonly=True,store=True,string=\"Assigned User\")\n action_id=fields.Many2one('support.ticket')\n wrk_loc=fields.Selection([('onsite','Onsite'),('remote','Remote')],string=\"Work Location\")\n #action_date=fields.Date(string=\"Date\",default=datetime.date.today(),readonly=True,store=True)\n @api.model\n def create(self,vals):\n web_obj=self.env['support.ticket'].search([('id','=',vals['action_id'])])\n vals['assigned_user_id']=web_obj.assigned_user_id.id\n new_id = super(SupportActions, self).create(vals)\n return new_id\n \n#Master for Severity\nclass SupportCategory(models.Model):\n _name=\"support.category\"\n _description=\"Sunfire Support Categories\"\n _rec_name=\"name\"\n name=fields.Char(string=\"Category\",help=\"The Category To be used for Support Ticket\")\n\n#Master for Severity\nclass SupportSeverity(models.Model):\n _name = 'support.severity'\n _description = 'Sunfire Support severity'\n _rec_name='name'\n \n name = fields.Char(string='Severity',help=\"The Severity To be used for Support Ticket\")\n\n#Master for Tag\nclass SupportTag(models.Model):\n _name = 'support.tag'\n _description = 'Sunfire Support Tag'\n _rec_name='name'\n \n name = fields.Char(string='Tag',help=\"The Tag To be used for Support Ticket\")\n\n#Master for Channel\nclass SupportChannel(models.Model):\n _name = 'support.channel'\n _description = 'Sunfire Support Channel'\n _rec_name='name'\n\n name = fields.Char(string='Channel',help=\"The Channel To be used for Support Ticket\")\n\nclass support_reassign(models.Model):\n _name='support.reassign'\n _description='Sunfire Reassignment Log'\n reassign_id=fields.Many2one('support.ticket')\n reassign_user_id=fields.Many2one('res.users',string='Reassigned User',readonly=True,store=True)\n user_id=fields.Many2one('res.users',string=\"Assigned UserId\",readonly=True,store=True)\n #reassign_datereassign_date=fields.Date(string=\"Reassign Date\",default=datetime.date.today(),readonly=True,store=True)\n","sub_path":"sunfire_support/models/support_ticket.py","file_name":"support_ticket.py","file_ext":"py","file_size_in_byte":10551,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"193234198","text":"# Popraw program Wymieszane litery tak, żeby każdemu słowu towarzyszyła\n# podpowiedź. Gracz powinien mieć możliwość zobaczenia podpowiedzi, jeśli\n# utknie w martwym punkcie. Dodaj system punktacji, który nagradza graczy\n# rozwiązujących anagram bez uciekania się do podpowiedzi.\n\nimport random\n\nslowa = (\"python\", \"gdansk\", \"dlaczego\", \"gdynia\", \"wsb\")\npodpowiedzi = {\n 'python': \"jezyk w którym napisany jest ten program\",\n 'gdansk': \"jedno z miast trojmiasta\",\n 'dlaczego': \"pytajnik powodu\",\n 'gdynia': \"najmłodsze miasto trójmiasta\",\n 'wsb': \"uczelnia w której powstał ten program\"\n}\npkt = 10\nword = random.choice(slowa)\npodpowiedz = podpowiedzi[word]\npoprawnie = word\npomie = \"\"\nwhile word:\n position = random.randrange(len(word))\n pomie += word[position]\n word = word[:position] + word[(position+1):]\n\nprint(\"\"\"\n Witaj w grze 'Wymieszane litery'!\n Uporządkuj litery, aby odtworzyć prawidłowe słowo.\n(Aby uzyskać podpowiedź wpisz '/podpowiedź'.)\n(Aby zakończyć zgadywanie, naciśnij klawisz Enter bez podawania odpowiedzi.)\n\"\"\"\n)\nprint(\"Zgadnij jakie to słowo:\", pomie)\n\nuzylPodpowiedzi = False\nzgaduj = input(\"\\nTwoja odpowiedź: \")\nwhile zgaduj != poprawnie and zgaduj != \"\":\n if zgaduj == \"/podpowiedź\":\n pkt -= 4 if pkt - 4 >= 0 else pkt\n uzylPodpowiedzi = True\n print(\"podpowiedź: \", podpowiedz)\n zgaduj = input(\"Twoja odpowiedź: \")\n continue\n pkt -= 1 if pkt - 1 >= 0 else pkt\n print(\"Niestety, to nie to słowo\")\n if uzylPodpowiedzi:\n print(podpowiedz)\n zgaduj = input(\"Twoja odpowiedź: \")\nif zgaduj == poprawnie:\n print(\"Zgadza się! Zgadłeś!\\nOtwrzymujesz %d pkt\" %pkt)\nprint(\"Dziękuję za udział w grze.\")\n","sub_path":"lab1/zad3.py","file_name":"zad3.py","file_ext":"py","file_size_in_byte":1745,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"55898534","text":"from collections import ChainMap\nfrom copy import deepcopy\nfrom functools import lru_cache\nimport logging\nfrom types import SimpleNamespace\nfrom typing import Callable, Dict, Iterator, Mapping, Pattern, Sequence, Union\nfrom typing import Any as AnyType\n\nimport dependency_injection\nfrom lxml import etree\n\n\n# constants\n\n\n__version__ = '0.1b1'\n\nREF_IDENTIFYING_ATTRIBUTE = '_this_is_a_Ref_resolver_'\n\nTRAVERSE_DEPTH_FIRST = True << 0\nTRAVERSE_WIDTH_FIRST = False << 0\nTRAVERSE_LEFT_TO_RIGHT = True << 1\nTRAVERSE_RIGHT_TO_LEFT = False << 1\nTRAVERSE_TOP_TO_BOTTOM = True << 2\nTRAVERSE_BOTTOM_TO_TOP = False << 2\nTRAVERSE_ROOT_ONLY = True << 3\n\n\n# logging\n\n\nlogger = logging.getLogger(__name__)\n\"\"\" Module logger, configure as you need. \"\"\"\ndbg = logger.debug\nnfo = logger.info\n\n\n# exceptions\n\n\nclass InxsException(Exception):\n \"\"\" Base class for inxs exceptions. \"\"\"\n pass\n\n\nclass FlowControl(InxsException):\n \"\"\" Base class for exception that control the evaluation of handlers. \"\"\"\n def __init__(self):\n super().__init__()\n dbg('{} is evoked.'.format(self.__class__.__name__))\n\n\nclass AbortRule(FlowControl):\n \"\"\" Can be raised to abort the evaluation of all the currently processed :class:`inxs.Rule` 's\n remaining tests and handlers. No further elements will be considered for that rule. This is\n similar to Python's builtin ``break`` in iterations.\n \"\"\"\n\n\nclass AbortTransformation(FlowControl):\n \"\"\" Can be raised to cancel the remaining :term:`transformation steps`. \"\"\"\n\n\nclass SkipToNextElement(FlowControl):\n \"\"\" Can be raised to abort handling of the current element. This is similar to Python's\n builtin ``continue`` in iterations.\n \"\"\"\n\n\n# helpers\n\n\nAttributesConditionType = Dict[Union[str, Pattern], Union[str, Pattern, None]]\n\n\ndef _condition_factory(condition: Union[str, AttributesConditionType, Callable]) -> Callable:\n \"\"\" Generates test functions for conditions provided as string or mapping. \"\"\"\n if isinstance(condition, str):\n if condition == '/':\n return _is_root_condition\n elif condition == '*':\n return _is_any_element_condition\n elif ':' in condition and '::' not in condition:\n # assumes URI\n dbg('Adding {} as namespace condition.'.format(condition))\n return HasNamespace(condition)\n elif condition.isalpha():\n # assumes tag\n dbg(\"Adding {} as tag's local name condition.\".format(condition))\n return HasLocalname(condition)\n else:\n # assumes XPath\n dbg('Adding {} as XPath condition.'.format(condition))\n return MatchesXPath(condition)\n elif isinstance(condition, Mapping):\n dbg('Adding {} as attribute condition.'.format(condition))\n return MatchesAttributes(condition)\n else:\n return condition\n\n\ndef dot_lookup(obj: AnyType, name: str):\n \"\"\" Looks up the attribute ``name`` from ``obj`` considering nested attributes that are\n separated by a ``.`` \"\"\"\n for _name in name.split('.'):\n obj = getattr(obj, _name)\n return obj\n\n\ndef _flatten_sequence(seq: Sequence):\n result = []\n for item in seq:\n if isinstance(item, Sequence) and not isinstance(item, str):\n result.extend(_flatten_sequence(item))\n else:\n result.append(item)\n return tuple(result)\n\n\ndef _is_any_element_condition(_, __):\n return True\n\n\ndef _is_flow_control(obj: AnyType) -> bool:\n try:\n return issubclass(obj, FlowControl)\n except TypeError:\n return False\n\n\ndef _is_root_condition(element, transformation):\n return element is transformation.root\n\n\n# rules definition\n\n\ndef Any(*conditions: Sequence[Callable]) -> Callable:\n \"\"\" Returns a callable that evaluates the provided test functions and returns ``True`` if any\n of them returned that.\n \"\"\"\n conditions = tuple(_condition_factory(x) for x in conditions)\n\n def evaluator(element: etree._Element, transformation: Transformation) -> bool:\n return any(x(element, transformation) for x in conditions)\n return evaluator\n\n\ndef OneOf(*conditions: Sequence[Callable]) -> Callable:\n \"\"\" Returns a callable that evaluates the provided test functions and returns ``True`` if\n exactly one of them returned that.\n \"\"\"\n conditions = tuple(_condition_factory(x) for x in conditions)\n\n def evaluator(element: etree._Element, transformation: Transformation) -> bool:\n return [x(element, transformation) for x in conditions].count(True) == 1\n return evaluator\n\n\ndef Not(*conditions: Sequence[Callable]) -> Callable:\n \"\"\" Returns a callable that evaluates the provided test functions and returns ``True`` if any\n of them returned ``False``.\n \"\"\"\n conditions = tuple(_condition_factory(x) for x in conditions)\n\n def evaluator(element: etree._Element, transformation: Transformation) -> bool:\n return not any(x(element, transformation) for x in conditions)\n return evaluator\n\n\ndef HasNamespace(namespace: str) -> Callable:\n \"\"\" Returns a callable that tests an element for the given tag namespace. \"\"\"\n def evaluator(element: etree._Element, _) -> bool:\n return etree.QName(element).namespace == namespace\n return evaluator\n\n\ndef HasLocalname(tag: str) -> Callable:\n \"\"\" Returns a callable that tests an element for the given local tag name. \"\"\"\n def evaluator(element: etree._Element, _) -> bool:\n return etree.QName(element).localname == tag\n return evaluator\n\n\ndef MatchesXPath(xpath: Union[str, Callable]) -> Callable:\n \"\"\" Returns a callable that tests an element for the given XPath expression (whether the\n evaluation result on the transformation root contains it) . If the ``xpath`` argument is a\n callable, it will be called with the current transformation as argument to obtain the\n expression.\n \"\"\"\n def callable_evaluator(element: etree._Element, transformation: Transformation) -> bool:\n _xpath = xpath(transformation)\n dbg(\"Resolved XPath from callable: '{}'\".format(_xpath))\n return element in transformation.xpath_evaluator(_xpath)\n\n def string_evaluator(element: etree._Element, transformation: Transformation) -> bool:\n return element in transformation.xpath_evaluator(xpath)\n\n return callable_evaluator if callable(xpath) else string_evaluator\n\n\ndef MatchesAttributes(constraints: AttributesConditionType) -> Callable:\n \"\"\" Returns a callable that tests an element's attributes for constrains defined in a\n :term:`mapping`.\n All constraints must be matched to resolve as true. Expected keys and values can be\n provided as string or compiled regular expression object from the :mod:`re` module.\n A ``None`` as value constraint evaluates as true if the key is in the attributes regardless\n its value. It also implies that at least one attribute must match the key's constraint if\n this one is a regular expression object.\n Alternatively a callable can be passed that returns such mappings during the\n transformation.\n \"\"\"\n def callable_evaluator(transformation):\n kwargs = dependency_injection.resolve_dependencies(\n constraints, transformation._available_symbols).as_kwargs\n return MatchesAttributes(constraints(**kwargs))(transformation.states.current_element)\n\n if callable(constraints):\n return callable_evaluator\n\n key_string_constraints = {k: v for k, v in constraints.items() if isinstance(k, str)}\n key_re_constraints = {k: v for k, v in constraints.items() if isinstance(k, Pattern)}\n\n def evaluator(element: etree._Element, _) -> bool:\n attributes = element.attrib\n value_string_constraints, value_re_constraints = {}, {}\n\n # check attributes' keys with string constraints\n for key_constraint, value_constraint in key_string_constraints.items():\n if key_constraint not in attributes:\n return False\n if value_constraint is None:\n continue\n if isinstance(value_constraint, str):\n value_string_constraints[key_constraint] = value_constraint\n elif isinstance(value_constraint, Pattern):\n value_re_constraints[key_constraint] = value_constraint\n\n # check attributes' keys with regular expression constraints\n for key_constraint, value_constraint in key_re_constraints.items():\n _matched = False\n for attribute in (x for x in attributes if key_constraint.match(x)):\n _matched = True\n if isinstance(value_constraint, str):\n value_string_constraints[attribute] = value_constraint\n elif isinstance(value_constraint, Pattern):\n value_re_constraints[attribute] = value_constraint\n if value_constraint is None and not _matched:\n return False\n\n # check attributes' values\n for key, constraint in value_string_constraints.items():\n if attributes[key] != constraint:\n return False\n for key, constraint in value_re_constraints.items():\n if not constraint.match(attributes[key]):\n return False\n\n return True\n\n return evaluator\n\n\ndef Ref(name: str) -> Callable:\n \"\"\" Returns a callable that can be used for value resolution in a condition test or\n :term:`handler function` that supports that. The value will be looked up during the\n processing of a transformation in :attr:`Transformation._available_symbols` by the given\n ``name``. This allows to reference dynamic values in :term:`transformation steps` and\n :class:`Rule` s.\n \"\"\"\n def simple_resolver(transformation) -> AnyType:\n dbg('Resolving {}.'.format(name))\n return transformation._available_symbols[name]\n setattr(simple_resolver, REF_IDENTIFYING_ATTRIBUTE, None)\n\n def dot_resolver(transformation) -> AnyType:\n token = name.split('.')\n obj = transformation._available_symbols[token[0]]\n for _name in token[1:]:\n obj = getattr(obj, _name)\n return obj\n setattr(dot_resolver, REF_IDENTIFYING_ATTRIBUTE, None)\n\n if '.' in name:\n return dot_resolver\n return simple_resolver\n\n\ndef If(x: AnyType, operator: Callable, y: AnyType) -> Callable:\n \"\"\" Returns a callable that can be used as condition test in a :class:`Rule`.\n The arguments ``x`` and ``y`` can be given as callables that will be used to get the\n ``operator``'s input values during execution.\n Before you implement your own operators, mind that there are a lot available within\n Python's ``__builtins__`` and the standard library, in particular the :mod:`operator`\n module.\n\n Examples:\n\n >>> If(Ref('previous_result'), operator.is_not, None)\n\n \"\"\"\n # TODO allow single arguments\n def evaluator(_, transformation: Transformation) -> AnyType:\n if callable(x):\n _x = x(**dependency_injection.resolve_dependencies(\n x, transformation._available_symbols).as_kwargs)\n dbg(\"x resolved to '{}'\".format(_x))\n else:\n _x = x\n if callable(y):\n _y = y(**dependency_injection.resolve_dependencies(\n y, transformation._available_symbols).as_kwargs)\n dbg(\"y resolved to '{}'\".format(_y))\n else:\n _y = y\n return operator(_x, _y)\n return evaluator\n\n\nclass Rule:\n \"\"\" Instances of this class can be used as conditional :term:`transformation steps` that are\n evaluated against all traversed elements.\n\n :param conditions: All given conditions must evaluate as ``True`` in order for this\n rule to apply.\n Strings and mappings can be provided as shortcuts, see\n :ref:`rule_condition_shortcuts` for details.\n The conditions are always called with the currently evaluated\n ``element`` and the :class:`Transformation` instance as arguments.\n There are helper functions for grouping conditions logically:\n :func:`Any`, :func:`Not` and :func:`OneOf`.\n :type conditions: A single callable, string or mapping, or a :term:`sequence` of such.\n :param handlers: These handlers will be called if the conditions matched. They can take\n any argument whose name is available in\n :attr:`Transformation._available_symbols`.\n :type handlers: A single callable or a :term:`sequence` of such.\n :param name: The optional rule's name.\n :type name: String.\n :param traversal_order: An optional traversal order that overrides the transformation's\n default :attr:`Transformation.config.traversal_order`, see\n :ref:`traversal_strategies` for details.\n :type traversal_order: Integer.\n \"\"\"\n __slots__ = ('name', 'conditions', 'handlers', 'traversal_order')\n\n def __init__(self, conditions, handlers, name: str = None,\n traversal_order: Union[int, None] = None):\n\n self.name = name\n dbg(\"Initializing rule '{}'.\".format(name))\n\n if not isinstance(conditions, Sequence) or isinstance(conditions, str):\n conditions = (conditions,)\n conditions = _flatten_sequence(conditions)\n self.conditions = tuple(_condition_factory(x) for x in conditions)\n if _is_root_condition in self.conditions:\n traversal_order = TRAVERSE_ROOT_ONLY\n self.conditions = tuple(x for x in self.conditions if x is not _is_root_condition)\n\n if not isinstance(handlers, Sequence):\n handlers = (handlers,)\n self.handlers = _flatten_sequence(handlers)\n self.traversal_order = traversal_order\n\n\n# transformation\n\n\ndef _traverse_df_ltr_btt(root) -> Iterator[etree._Element]:\n def yield_children(element):\n for child in element:\n yield from yield_children(child)\n yield element\n yield from yield_children(root)\n\n\ndef _traverse_df_ltr_ttb(root) -> Iterator[etree._Element]:\n yield from root.iter()\n\n\ndef _traverse_root(root) -> Iterator[etree._Element]:\n yield root\n\n\nclass Transformation:\n \"\"\" A transformation instance is defined by its :term:`transformation steps` and\n :term:`configuration`. It is to be called with an ``lxml`` representation of an XML element\n as transformation root, only this element and its children will be considered during\n traversal.\n\n :param steps: The designated transformation steps of the instance are given as a sequence\n of positional arguments.\n :param config: The configuration values for the instance are passed as keyword arguments.\n Beside the following keywords, it can be populated with any key-value-pairs\n that will be available in :attr:`inxs.Transformation._available_symbols`\n during a transformation.\n The defaults are defined in :attr:`~inxs.config_defaults`.\n\n - ``context`` can be provided as mapping with items that are added to the\n :term:`context` before a (sub-)document is processed.\n - ``common_rule_conditions`` can be used to define one or more conditions\n that must match in all rule evaluations. E.g. a transformation could be\n restricted to elements with a certain namespace without redundantly\n defining that per rule. Can be given as a single object (e.g. a string) or\n as sequence.\n - ``copy`` is a boolean that defaults to ``True`` and indicates whether\n to process on a copy of the document's tree object.\n - ``name`` can be used to identify a transformation.\n - ``result_object`` sets the transformation's attribute that is returned as\n result. Dot-notation lookup (e.g. ``context.target``) is implemented. Per\n default the transformation root is returned.\n - ``traversal_order`` sets the default traversal order for rule evaluations\n and itself defaults to depth first, left to right, to to bottom. See\n :ref:`traversal_strategies` for possible values.\n \"\"\"\n __slots__ = ('config', 'steps', 'states')\n\n config_defaults = {\n 'common_rule_conditions': None,\n 'context': {},\n 'copy': True,\n 'name': None,\n 'result_object': None,\n 'traversal_order': TRAVERSE_DEPTH_FIRST | TRAVERSE_LEFT_TO_RIGHT | TRAVERSE_TOP_TO_BOTTOM\n }\n \"\"\" The default :term:`configuration` values. Changing members on an instance actually affects\n the class unless a copy of this mapping as copied and bound as instance attribute. \"\"\"\n\n traversers = {\n TRAVERSE_DEPTH_FIRST | TRAVERSE_LEFT_TO_RIGHT | TRAVERSE_BOTTOM_TO_TOP:\n _traverse_df_ltr_btt,\n TRAVERSE_DEPTH_FIRST | TRAVERSE_LEFT_TO_RIGHT | TRAVERSE_TOP_TO_BOTTOM:\n _traverse_df_ltr_ttb,\n TRAVERSE_ROOT_ONLY: _traverse_root\n }\n\n def __init__(self, *steps, **config):\n dbg(\"Initializing transformation instance named: '{}'.\".format(config.get('name')))\n self.steps = _flatten_sequence(steps)\n self.config = SimpleNamespace(**config)\n self._set_config_defaults()\n self._expand_rules(self.config.common_rule_conditions)\n self.states = None\n\n @property\n def name(self):\n \"\"\" The ``name`` member of the transformation's :term:`configuration`. \"\"\"\n return getattr(self.config, 'name', None)\n\n def _expand_rules(self, common_rule_conditions):\n if common_rule_conditions is None:\n return\n\n if not isinstance(common_rule_conditions, Sequence) or \\\n isinstance(common_rule_conditions, str):\n common_rule_conditions = (common_rule_conditions,)\n\n expanded_steps = []\n for step in self.steps:\n if isinstance(step, Rule):\n expanded_steps.append(Rule(common_rule_conditions + step.conditions, step.handlers,\n step.name, step.traversal_order))\n else:\n expanded_steps.append(step)\n self.steps = tuple(expanded_steps)\n\n def _set_config_defaults(self) -> None:\n for key, value in self.config_defaults.items():\n if not hasattr(self.config, key):\n dbg(\"Using default value '{}' for config key '{}'.\".format(value, key))\n setattr(self.config, key, value)\n\n def __call__(self, transformation_root: etree._Element, copy: bool = None, **context) \\\n -> AnyType:\n copy = self.config.copy if copy is None else copy\n self._init_transformation(transformation_root, copy, context)\n\n for step in self.steps:\n _step_name = step.name if hasattr(step, 'name') else step.__name__\n dbg(\"Processing rule '{}'.\".format(_step_name))\n\n self.states.current_step = step\n try:\n if isinstance(step, Rule):\n self._apply_rule(step)\n elif callable(step):\n self._apply_handlers(step)\n else:\n raise RuntimeError\n except AbortTransformation:\n dbg(\"Aborting due to 'AbortTransformation'.\")\n break\n\n result = dot_lookup(self, self.config.result_object)\n self._finalize_transformation()\n return result\n\n def _init_transformation(self, transformation_root, copy, context) -> None:\n dbg('Initializing processing.')\n if not isinstance(transformation_root, etree._Element):\n raise RuntimeError('A transformation must be called with an lxml Element object.')\n\n self.states = SimpleNamespace()\n self.states.current_element = None\n self.states.previous_result = None\n\n resolved_context = deepcopy(self.config.context)\n resolved_context.update(context)\n dbg('Initial context:\\n{}'.format(resolved_context))\n self.states.context = SimpleNamespace(**resolved_context)\n\n if copy:\n dbg('Cloning source document tree.')\n source_tree = transformation_root.getroottree()\n self.states.tree = deepcopy(source_tree)\n transformation_root_xpath = source_tree.getpath(transformation_root)\n self.states.root = \\\n self.states.tree.xpath(transformation_root_xpath, smart_prefix=True)[0]\n else:\n self.states.tree = transformation_root.getroottree()\n self.states.root = transformation_root\n\n if self.config.result_object is None:\n dbg(\"Setting result_object to 'root'.\")\n self.config.result_object = 'root'\n self.states.__config_result_object_is_none__ = True\n else:\n self.states.__config_result_object_is_none__ = False\n\n self.states.xpath_evaluator = etree.XPathEvaluator(self.states.root, smart_prefix=True)\n\n def _apply_rule(self, rule) -> None:\n traverser = self._get_traverser(rule.traversal_order)\n dbg('Using traverser: {}'.format(traverser))\n\n for element in traverser(self.states.root):\n if isinstance(element, etree._Comment):\n continue\n dbg('Evaluating {}.'.format(element))\n self.states.current_element = element\n try:\n if self._test_conditions(element, rule.conditions):\n self._apply_handlers(*rule.handlers)\n except AbortRule:\n dbg('Aborting rule.')\n break\n except SkipToNextElement:\n dbg('Skip to next element.')\n continue\n\n self.states.current_element = None\n\n @lru_cache(8)\n def _get_traverser(self, traversal_order: Union[int, None]) -> Callable:\n if traversal_order is None:\n traversal_order = self.config.traversal_order\n traverser = self.traversers.get(traversal_order)\n if traverser is None:\n raise NotImplementedError\n return traverser\n\n def _test_conditions(self, element, conditions) -> bool:\n # there's no dependency injection here because its overhead\n # shall be avoided during testing conditions\n for condition in conditions:\n dbg(\"Testing condition '{}'.\".format(condition))\n if not condition(element, self):\n dbg('The condition did not apply.')\n return False\n dbg('The condition applied.')\n return True\n\n def _apply_handlers(self, *handlers) -> None:\n dbg('Applying handlers.')\n for handler in handlers:\n if _is_flow_control(handler):\n raise handler\n kwargs = dependency_injection.resolve_dependencies(\n handler, self._available_symbols).as_kwargs\n if isinstance(handler, Transformation):\n kwargs['transformation_root'] = self.states.current_element or self.states.root\n kwargs['copy'] = False\n dbg(\"Applying handler {}.\".format(handler))\n self.states.previous_result = handler(**kwargs)\n\n def _finalize_transformation(self) -> None:\n dbg('Finalizing preocessing.')\n if self.states.__config_result_object_is_none__:\n del self.config.result_object\n self.states = None\n\n @property\n def _available_symbols(self) -> Mapping:\n \"\"\" This mapping contains items that are used for the dependency injection of handler\n functions. These names are included:\n\n - All attributes of the transformation's :term:`configuration`, overridden by the\n following.\n - All attributes of the transformation's :term:`context`, overridden by the following.\n - ``config`` - The :term:`configuration` namespace object.\n - ``context`` - The :term:`context` namespace object.\n - ``element`` - The element that matched a :class:`Rule`'s conditions or ``None`` in\n case of :term:`simple transfotmation steps`.\n - ``previous_result`` - The result that was returned by the previously evaluated\n handler function.\n - ``root`` - The root element of the processed (sub-)document a.k.a tranformation root.\n - ``transformation`` - The calling :class:`Transformation` instance.\n - ``tree`` - The tree object of the processed document.\n - ``xpath_evaluator`` - The XPathEvaluator instance that is bound to the\n transformation root.\n\n \"\"\"\n guaranteed_symbols = {\n 'config': self.config,\n 'context': self.states.context,\n 'element': self.states.current_element,\n 'previous_result': self.states.previous_result,\n 'root': self.states.root,\n 'transformation': self,\n 'tree': self.states.tree,\n 'xpath_evaluator': self.states.xpath_evaluator\n }\n return ChainMap(guaranteed_symbols, vars(self.states.context), vars(self.config))\n\n # aliases that are supposed to be broken when the transformation isn't processing\n\n @property\n def context(self):\n \"\"\" This property can be used to access the :term:`context` while the transformation is\n processing.\n \"\"\"\n return self.states.context\n\n @property\n def root(self):\n \"\"\" This property can be used to access the root element of the currently processed\n (sub-)document.\n \"\"\"\n return self.states.root\n\n @property\n def tree(self):\n \"\"\" This property can be used to access the tree object of the currently processed\n document.\n \"\"\"\n return self.states.tree\n\n @property\n def xpath_evaluator(self):\n \"\"\" During a transformation an :class:`lxml.etree.XPathEvaluator` using the processed\n (sub-)document's root element as such is bound to this property. \"\"\"\n return self.states.xpath_evaluator\n\n\n__all__ = [\n '__version__', 'logger',\n 'TRAVERSE_BOTTOM_TO_TOP', 'TRAVERSE_DEPTH_FIRST', 'TRAVERSE_LEFT_TO_RIGHT',\n 'TRAVERSE_RIGHT_TO_LEFT', 'TRAVERSE_ROOT_ONLY', 'TRAVERSE_TOP_TO_BOTTOM',\n 'TRAVERSE_WIDTH_FIRST',\n AbortRule.__name__, AbortTransformation.__name__,\n SkipToNextElement.__name__, InxsException.__name__,\n 'Any', 'Not', 'OneOf',\n 'HasNamespace', 'HasLocalname', 'MatchesAttributes', 'MatchesXPath',\n 'If', 'Ref',\n Rule.__name__, Transformation.__name__\n]\n","sub_path":"inxs/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":27102,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"300464443","text":"# coding=utf-8\nimport telebot\nimport logging\n\nbot = telebot.TeleBot('1163114593:AAFGXPuRouF8Sx-kOh0nkFU3sWSFieuYnO4')\nname = ''\nsurname = ''\nclas = ''\nslov = {}\n\n\ndef main(use_logging, level_name):\n if use_logging:\n telebot.logger.setLevel(logging.getLevelName(level_name))\n bot.polling(none_stop=True, interval=1)\n\n\n@bot.message_handler(commands=['start'])\ndef start_message(mess):\n global name\n sent = bot.send_message(mess.chat.id, 'Привет, Как тебя зовут?')\n print(mess.chat.id)\n slov[mess.chat.id] = ['start']\n print(slov)\n bot.register_next_step_handler(sent, surname_message)\n\n\n@bot.message_handler(commands=['help'])\ndef help_message(mess):\n bot.send_message(mess.chat.id, '/start')\n\n\ndef surname_message(message):\n global name\n if len(slov[message.chat.id]) > 0:\n slov[message.chat.id].append(message.text)\n sent = bot.send_message(message.chat.id, f'{slov[message.chat.id][1].capitalize()} как ваша фамилия?')\n print(slov)\n bot.register_next_step_handler(sent, class_message)\n\n\ndef class_message(message):\n global name, surname\n if len(slov[message.chat.id]) > 1:\n slov[message.chat.id].append(message.text)\n sent = bot.send_message(message.chat.id,\n f'{slov[message.chat.id][2].capitalize()}'\n f' {slov[message.chat.id][1].capitalize()} в каком вы классе'\n f'(написать через нижние подчеркивание, пример 10_1)')\n print(slov)\n bot.register_next_step_handler(sent, end_message)\n\n\ndef end_message(message):\n global clas, name, surname\n if len(slov[message.chat.id]) > 2:\n slov[message.chat.id].append(message.text)\n sent = bot.send_message(message.chat.id, f'{slov[message.chat.id][2].capitalize()}'\n f' {slov[message.chat.id][1].capitalize()}'\n f' {slov[message.chat.id][3]} верно?')\n print(slov)\n bot.register_next_step_handler(sent, yes_no_message)\n\n\ndef yes_no_message(message):\n if message.text.lower() == 'да':\n a = slov.pop(message.chat.id)\n pass\n else:\n a = slov.pop(message.chat.id)\n sent = bot.send_message(message.chat.id, 'Давай заново. Как тебя зовут')\n slov[message.chat.id] = ['start']\n print(slov)\n bot.register_next_step_handler(sent, surname_message)\n\n\nprint(name, surname, clas)\n\nif __name__ == '__main__':\n main(True, 'DEBUG')\n","sub_path":"osnova.py","file_name":"osnova.py","file_ext":"py","file_size_in_byte":2652,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"297899556","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\n\"\"\"\nHTTP request objects. Ported from webapp2, refactored to\nsupport Python versions > 2.7, 3.0\n\"\"\"\n\nimport sys\nimport cgi\nimport webob\n\nif sys.version < '3':\n # python 2.7 compatibility\n from urllib import urlencode\n from cStringIO import StringIO\n\nelse:\n # python 3.0 compatibility\n from urllib.parse import urlencode\n from io import BytesIO as StringIO\n\nfrom .utils.strings import _basestring, _bytes\n\n#<----------------------------------------------------------------------------->\n\nclass Request(webob.Request):\n \"\"\"Abstraction for an HTTP request.\n\n Most extra methods and attributes are ported from webapp. Check the\n `WebOb documentation `_ for the ones not listed here.\n \"\"\"\n\n #: A reference to the active :class:`WSGIApplication` instance.\n app = None\n \n #: A reference to the active :class:`Response` instance.\n response = None\n \n #: A reference to the matched :class:`Route`.\n route = None\n \n #: The matched route positional arguments.\n route_args = None\n \n #: The matched route keyword arguments.\n route_kwargs = None\n \n #: A dictionary to register objects used during the request lifetime.\n registry = None\n \n # Attributes from webapp.\n request_body_tempfile_limit = 0\n uri = property(lambda self: self.url)\n query = property(lambda self: self.query_string)\n\n def __init__(self, environ, *args, **kwargs):\n \"\"\"Constructs a Request object from a WSGI environment.\n\n :param environ:\n A WSGI-compliant environment dictionary.\n \"\"\"\n unicode_errors = kwargs.pop('unicode_errors', 'ignore')\n decode_param_names = kwargs.pop('decode_param_names', True)\n super(Request, self).__init__(environ, unicode_errors=unicode_errors,\n decode_param_names=decode_param_names,\n *args, **kwargs)\n self.registry = {}\n\n def get(self, argument_name, default_value=''):\n \"\"\"Returns the query or POST argument with the given name.\n\n We parse the query string and POST payload lazily, so this will be a\n slower operation on the first call.\n\n :param argument_name:\n The name of the GET, POST, PUT or DELETE argument.\n :param default_value:\n The value to return if the given argument is not present.\n :returns:\n Returns the first value with the given name given in the request.\n Use the get_all method to return a list of all values with the \n specified argument name.\n \"\"\"\n param_value = self.get_all(argument_name)\n\n if len(param_value) > 0:\n return param_value[0]\n \n else:\n return default_value\n\n def get_all(self, argument_name, default_value=None):\n \"\"\"Returns a list of query or POST arguments with the given name.\n\n We parse the query string and POST payload lazily, so this will be a\n slower operation on the first call.\n\n :param argument_name:\n The name of the query or POST argument.\n :param default_value:\n The value to return if the given argument is not present,\n None may not be used as a default, if it is then an empty\n list will be returned instead.\n :returns:\n A (possibly empty) list of values.\n \"\"\"\n\n if default_value is None:\n default_value = []\n\n param_value = self.params.getall(argument_name)\n\n if param_value is None or len(param_value) == 0:\n return default_value\n\n for i in range(len(param_value)):\n if isinstance(param_value[i], cgi.FieldStorage):\n param_value[i] = param_value[i].value\n\n return param_value\n\n def arguments(self):\n \"\"\"Returns a list of the arguments provided in the query and/or POST.\n\n The return value is a list of strings.\n \"\"\"\n return list(set(self.params.keys()))\n\n def get_range(self, name, min_value=None, max_value=None, default=0):\n \"\"\"Parses the given int argument, limiting it to the given range.\n\n :param name:\n The name of the argument.\n :param min_value:\n The minimum int value of the argument (if any).\n :param max_value:\n The maximum int value of the argument (if any).\n :param default:\n The default value of the argument if it is not given.\n :returns:\n An int within the given range for the argument.\n \"\"\"\n value = self.get(name, default)\n if value is None:\n return value\n\n try:\n value = int(value)\n except ValueError:\n value = default\n if value is not None:\n if max_value is not None:\n value = min(value, max_value)\n\n if min_value is not None:\n value = max(value, min_value)\n\n return value\n\n @classmethod\n def blank(cls, path, environ=None, base_url=None, headers=None, **kwargs): # pragma: no cover\n \"\"\"Adds parameters compatible with WebOb >= 1.0: POST and **kwargs.\"\"\"\n \n try:\n return super(Request, cls).blank(path, environ=environ,\n base_url=base_url, headers=headers, **kwargs)\n except TypeError:\n if not kwargs:\n raise\n\n data = kwargs.pop('POST', None)\n \n if data is not None:\n environ = environ or {}\n environ['REQUEST_METHOD'] = 'POST'\n \n if hasattr(data, 'items'):\n data = data.items()\n \n if not isinstance(data, _bytes):\n data = urlencode(data)\n \n environ['wsgi.input'] = StringIO(data.encode('utf-8'))\n environ['webob.is_body_seekable'] = True\n environ['CONTENT_LENGTH'] = str(len(data))\n environ['CONTENT_TYPE'] = 'application/x-www-form-urlencoded'\n\n base = super(Request, cls).blank(path, environ=environ,\n base_url=base_url, headers=headers)\n if kwargs:\n obj = cls(base.environ, **kwargs)\n obj.headers.update(base.headers)\n return obj\n else:\n return base\n\n#<----------------------------------------------------------------------------->\n\nclass RequestContext(object):\n \"\"\"Context for a single request.\n\n The context is responsible for setting and cleaning global variables for\n a request.\n \"\"\"\n\n #: A :class:`WSGIApplication` instance.\n app = None\n #: WSGI environment dictionary.\n environ = None\n\n def __init__(self, app, environ):\n \"\"\"Initializes the request context.\n\n :param app:\n An :class:`WSGIApplication` instance.\n :param environ:\n A WSGI environment dictionary.\n \"\"\"\n self.app = app\n self.environ = environ\n\n def __enter__(self):\n \"\"\"Enters the request context.\n\n :returns:\n A tuple ``(request, response)``.\n \"\"\"\n \n # Build request and response.\n request = self.app.request_class(self.environ)\n response = self.app.response_class()\n \n # Make active app and response available through the request object.\n request.app = self.app\n request.response = response\n \n # Register global variables.\n self.app.set_globals(app=self.app, request=request)\n return request, response\n\n def __exit__(self, exc_type, exc_value, traceback):\n \"\"\"Exits the request context.\n\n This release the context locals except if an exception is caught\n in debug mode. In this case they are kept to be inspected.\n \"\"\"\n if exc_type is None or not self.app.debug:\n # Unregister global variables.\n self.app.clear_globals()\n","sub_path":"webtools/request.py","file_name":"request.py","file_ext":"py","file_size_in_byte":7989,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"332005822","text":"\"\"\"\niterator Vs iterable?\n-->consider a book\n no. of pages in book can be iterate\n -->is iterable--->lists, dict, tuple, set, array\n -->produces an iterator\n bookmark in book\n -->is iterator\n --->it tells/gives us obj where it is exactly while iterating over iterable\n -->used in generators\n -->it can be any value which produces stream of values\n -->only operation in iterators is next()\niterator = iter(iterable) # or iterable.__iter__()\nvalue = next(iterator) # or iterator.next() or iterator.__next__()\nvalue = next(iterator)\n...\n\n\n\n\nAbstract and customize your iterations!\nSee how you can use more generators and __iter__ method in your code\n\nwhat is xrange?--->it is an obj which is iterator\n\nHow to approach modifying list while iterating over it?\n-->best approach would be to create new list\n-->There is problem if we are iterating over list from starting and remove any ele\n -->It will miss next element while it traverse\n --suppose it is at 4th ele and if we delete it\n -->then 5th will come to 4th place\n -->so it is missed in next iteration\n-->other hack is to travers list from back and modify it if required\n\"\"\"\n\n\n# my_dict = {'name': 'rohan', 'id': 1}\n# print(my_dict)\n# popped = my_dict.pop('name')\n# print(popped)\n# print(my_dict)\n# popped = my_dict.pop('id')\n# print(popped)\n# print(my_dict)\n# popped = my_dict.pop('age', None)\n# print(popped)\n# print(my_dict)\n\nclass InTest(object):\n def __init__(self, my_list):\n self.test_list = my_list\n\n def __contains__(self, item):\n # this method makes class as iterable object\n for index, val in enumerate(self.test_list):\n if val == item:\n return True\n return False\n\n\n# map() returns an iterator object\n# map(function, iterable)\npets = ('bird', 'snake', 'dog', 'turtle', 'cat', 'hamster')\nuppercased_pets = list(map(str.upper, pets))\n\n# below is list comprehension to replace above map usage\npets = ('bird', 'snake', 'dog', 'turtle', 'cat', 'hamster')\nuppercased_pets = [pet.upper() for pet in pets]\n\n# Nested List Comprehensions\n# for readability, it’s not recommended to have more than two levels.\nnested_numbers = ((1, 4, 7, 8), (2, 3, 5))\nsquares = [x * x for numbers in nested_numbers for x in numbers]\n\n# use of walrus in python 3.8+ in list comprehension\n# import random\n# letters = list('this is to produce a list of letters')\n# vowels = [letter.upper() for _ in range(0, 10) if (letter := random.choice(letters)) in list('aeoui')]\n\n# syntax for set comprehension\n# {expression for item in iterable}\n\n\n# syntax for dict comprehension\n# {key_expression : value_expression for item in iterable}\nif __name__ == '__main__':\n input_list = [i for i in range(1000)]\n test = InTest(input_list)\n print(-1 in test)\n","sub_path":"DSA/learn_python/concepts.py","file_name":"concepts.py","file_ext":"py","file_size_in_byte":2841,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"120001814","text":"\r\n# coding=utf-8\r\n# Copyright 2020: Yelong Shen.\r\n#\r\n# Licensed under the Apache License, Version 2.0 (the \"License\");\r\n# you may not use this file except in compliance with the License.\r\n# You may obtain a copy of the License at\r\n#\r\n# http://www.apache.org/licenses/LICENSE-2.0\r\n#\r\n# Unless required by applicable law or agreed to in writing, software\r\n# distributed under the License is distributed on an \"AS IS\" BASIS,\r\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n# See the License for the specific language governing permissions and\r\n# limitations under the License.\r\n\r\nfrom __future__ import absolute_import\r\nfrom __future__ import division\r\nfrom __future__ import print_function\r\n\r\nimport collections\r\nimport json\r\nimport math\r\nimport os\r\nimport random\r\n#import modeling\r\n#import optimization\r\n#import tokenization\r\nimport six\r\n#import tensorflow as tf\r\nimport encoder\r\n\r\nimport re\r\nimport sys\r\n\r\nfrom progress.bar import Bar as Bar\r\nimport os\r\nimport torch\r\nfrom torch.utils.data import Dataset\r\nfrom torch.utils.data import DataLoader\r\n\r\nimport torch\r\nimport numpy\r\n\r\nclass CqrExample(object):\r\n \"\"\"A single training/test example for simple sequence classification.\r\n For examples without an answer, the start and end position are -1.\r\n \"\"\"\r\n def __init__(self, unique_id, doc, query, context_query, ans):\r\n #self.qas_id = qas_id\r\n self.unique_id = unique_id\r\n self.doc = doc\r\n self.context_query = context_query\r\n self.query = query\r\n self.ans = ans\r\n\r\ndef read_squad_examples(input_file, tokenizer, skip_unk = 1):\r\n \"\"\"Read a SQuAD json file into a list of SquadExample.\"\"\"\r\n #with tf.gfile.Open(input_file, \"r\") as reader:\r\n with open(input_file, \"r\") as reader:\r\n input_data = json.load(reader)[\"data\"]\r\n\r\n examples = []\r\n unique_id = 1000000000\r\n unique_to_ids = {}\r\n \r\n for entry in input_data:\r\n for paragraph in entry[\"paragraphs\"]:\r\n paragraph_text = paragraph[\"context\"]\r\n\r\n for qa in paragraph[\"qas\"]:\r\n qas_id = qa[\"id\"]\r\n question_text = qa[\"question\"]\r\n orig_answer_text = None\r\n is_impossible = False\r\n if True: # is_training:\r\n if True: #args.version_2_with_negative:\r\n is_impossible = qa[\"is_impossible\"]\r\n\r\n if not is_impossible:\r\n answer = qa[\"answers\"][0]\r\n orig_answer_text = answer[\"text\"].strip()\r\n else:\r\n start_position = -1\r\n end_position = -1\r\n orig_answer_text = \"\"\r\n\r\n # skip the unk examples.\r\n if is_impossible and skip_unk > 0:\r\n continue\r\n\r\n example = CqrExample(\r\n #qas_id=qas_id,\r\n unique_id=unique_id,\r\n doc=paragraph_text,\r\n query=question_text,\r\n context_query=question_text,\r\n ans=orig_answer_text)\r\n\r\n unique_to_ids[unique_id] = (qas_id, len(examples))\r\n examples.append(example)\r\n unique_id += 1\r\n\r\n return examples, unique_to_ids\r\n\r\ndef read_coqa_examples(input_file, tokenizer, history, turn_ids):\r\n \"\"\"Read a coqa json file into a list of CoqaExample.\"\"\"\r\n with open(input_file, 'r') as f:\r\n dataset = json.load(f)\r\n\r\n examples = []\r\n\r\n unique_id = 500000000\r\n unique_to_ids = {}\r\n\r\n for i, datum in enumerate(dataset['data']):\r\n if (i % 1000 == 0):\r\n print(\"processig {} examples\".format(i))\r\n \r\n source = datum[\"source\"]\r\n para_id = datum[\"id\"]\r\n filename = datum[\"filename\"]\r\n doc = datum[\"story\"]\r\n \r\n context_questions = []\r\n context_answers = []\r\n\r\n for question, answer in zip(datum['questions'], datum['answers']):\r\n assert question['turn_id'] == answer['turn_id']\r\n turn_id = question['turn_id']\r\n\r\n question_text = question['input_text'].strip()\r\n\r\n ans_span_text = answer['span_text']\r\n ans_input_text = answer['input_text'].strip()\r\n\r\n context_questions.append(question_text)\r\n context_answers.append(ans_input_text)\r\n\r\n context_query = question_text\r\n \r\n ch_idx = len(context_questions) - 1\r\n\r\n for h in range(ch_idx, max(0, ch_idx - history), -1):\r\n context_query = context_questions[h-1] + ' ' + context_answers[h-1] + ' ; ' + context_query\r\n\r\n if not turn_id in turn_ids:\r\n continue\r\n \r\n example = CqrExample(\r\n #para_id=para_id,\r\n #turn_id=turn_id,\r\n unique_id=unique_id,\r\n doc=doc,\r\n query=question_text,\r\n context_query=context_query,\r\n ans=ans_input_text)\r\n\r\n unique_to_ids[unique_id] = (para_id, turn_id, len(examples))\r\n\r\n examples.append(example)\r\n unique_id += 1\r\n return examples, unique_to_ids\r\n\r\ndef read_quac_examples(input_file, tokenizer, history, turn_ids):\r\n \"\"\"Read a quac json file into a list of QuACExample.\"\"\"\r\n #with open(input_file, 'r') as f:\r\n # dataset = json.load(f)\r\n \r\n __datum_list = json.load(open(input_file, 'r'))['data']\r\n \r\n examples = []\r\n\r\n unique_id = 100000000\r\n unique_to_ids = {}\r\n\r\n para_id = 0\r\n\r\n for i, datum in enumerate(__datum_list):\r\n if (i % 1000 == 0):\r\n print(\"processig {} examples\".format(i))\r\n\r\n if not 'paragraphs' in datum.keys():\r\n print(datum.keys())\r\n print('key paragraphs not in datum...', datum)\r\n continue\r\n\r\n doc_title = '' \r\n if 'section_title' in datum:\r\n doc_title = datum['section_title']\r\n\r\n back_ground = ''\r\n if 'background' in datum:\r\n back_ground = datum['background']\r\n\r\n for paragraph in datum['paragraphs']:\r\n para_id += 1\r\n\r\n context_str = back_ground + paragraph['context'][:-len('CANNOTANSWER')].strip()\r\n\r\n context_questions = []\r\n context_answers = []\r\n\r\n for qas in paragraph['qas']:\r\n _id = qas['id']\r\n yes_no_tag = qas['yesno']\r\n question_text = qas['question'].strip()\r\n ans = qas['orig_answer']\r\n \r\n ans_text = ans['text'].strip()\r\n #ans_pos = ans['answer_start']\r\n turn_id = int(_id.split('_q#')[1]) + 1\r\n followups = qas['followup']\r\n\r\n if yes_no_tag == 'y':\r\n ans_text = 'Yes, ' + ans_text\r\n elif yes_no_tag == 'n':\r\n ans_text = 'No, ' + ans_text\r\n\r\n context_questions.append(question_text)\r\n context_answers.append(ans_text)\r\n\r\n context_query = question_text\r\n \r\n ch_idx = len(context_questions) - 1\r\n\r\n for h in range(ch_idx, max(0, ch_idx - history), -1):\r\n context_query = context_questions[h-1] + ' ' + context_answers[h-1] + ' ; ' + context_query\r\n\r\n if not turn_id in turn_ids:\r\n continue\r\n\r\n if ans_text == 'CANNOTANSWER':\r\n continue\r\n\r\n example = CqrExample(\r\n #q_id=_id,\r\n #turn_id=turn_id,\r\n unique_id=unique_id,\r\n doc=context_str,\r\n query=question_text,\r\n context_query=context_query,\r\n ans=ans_text)\r\n \r\n unique_to_ids[unique_id] = (_id, turn_id, para_id, len(examples))\r\n\r\n examples.append(example)\r\n unique_id += 1\r\n return examples, unique_to_ids\r\n\r\n \r\nclass CqrFeatures(object):\r\n \"\"\"A single set of features of data.\"\"\"\r\n def __init__(self,\r\n unique_id,\r\n #para_id,\r\n #turn_id,\r\n doc_tokens,\r\n doc_len,\r\n query_tokens,\r\n query_len,\r\n ans_tokens,\r\n ans_len):\r\n self.unique_id = unique_id\r\n\r\n self.doc_tokens = doc_tokens\r\n self.doc_len = doc_len\r\n self.query_tokens = query_tokens\r\n self.query_len = query_len\r\n self.ans_tokens = ans_tokens\r\n self.ans_len = ans_len\r\n\r\nclass CqrDataset(Dataset):\r\n def __init__(self, features, fill_batch):\r\n self.num_features = len(features)\r\n self.fill_batch = fill_batch\r\n self.features = features\r\n self.rng = random.Random(778)\r\n\r\n def __len__(self):\r\n return int((self.num_features + self.fill_batch - 1)/ self.fill_batch) * self.fill_batch\r\n \r\n def __getitem__(self, item):\r\n if(item >= self.num_features):\r\n item = self.rng.randint(0, self.num_features - 1)\r\n feature = self.features[item]\r\n\r\n output = {\"unique_id\" : feature.unique_id,\r\n \"doc_tokens\" : feature.doc_tokens,\r\n \"doc_len\" : feature.doc_len,\r\n \"query_tokens\" : feature.query_tokens,\r\n \"query_len\" : feature.query_len,\r\n \"ans_tokens\" : feature.ans_tokens,\r\n \"ans_len\" : feature.ans_len\r\n }\r\n return {key: torch.tensor(value, dtype=torch.int32) for key, value in output.items()}\r\n\r\n\r\ndef convert_examples_to_cqrfeatures(examples, tokenizer, pad_token, max_seq_length, max_query_length, max_ans_length, dataset='coqa'): \r\n def __padding_tokens(tokens, max_seq_length, pad_token, direct):\r\n if len(tokens) > max_seq_length:\r\n if direct > 0:\r\n pad_tokens = tokens[:max_seq_length]\r\n else:\r\n pad_tokens = tokens[-max_seq_length:]\r\n else:\r\n pad_tokens = tokens\r\n token_len = len(pad_tokens)\r\n pad_tokens = pad_tokens + [pad_token for _ in range(max_seq_length - token_len)]\r\n return pad_tokens, token_len\r\n\r\n #unique_id = 1000000000\r\n cqr_features = []\r\n #unique_to_ids = {}\r\n \r\n for (example_index, example) in enumerate(examples):\r\n context_query_tokens = tokenizer.encode(example.context_query) # tokenizer.tokenize(example.question_text)\r\n if len(context_query_tokens) > max_query_length:\r\n if dataset == 'coqa' or dataset == 'quac':\r\n context_query_tokens = context_query_tokens[-max_query_length:]\r\n elif dataset == 'squad':\r\n context_query_tokens = context_query_tokens[0:max_query_length]\r\n\r\n all_doc_tokens = tokenizer.encode(example.doc)\r\n if len(all_doc_tokens) > max_seq_length:\r\n all_doc_tokens = all_doc_tokens[0:max_seq_length]\r\n \r\n ans_tokens = tokenizer.encode(example.ans)\r\n if len(ans_tokens) > max_ans_length:\r\n ans_tokens = ans_tokens[0:max_ans_length]\r\n\r\n d_tokens, d_len = __padding_tokens(all_doc_tokens, max_seq_length, pad_token, 1)\r\n q_tokens, q_len = __padding_tokens(context_query_tokens, max_query_length, pad_token, 1)\r\n a_tokens, a_len = __padding_tokens(ans_tokens, max_ans_length, pad_token, 1)\r\n\r\n feature = CqrFeatures(\r\n unique_id=example.unique_id,\r\n #para_id=example.para_id,\r\n #turn_id=example.turn_id, \r\n doc_tokens=d_tokens,\r\n doc_len=d_len,\r\n\r\n query_tokens=q_tokens,\r\n query_len=q_len,\r\n\r\n ans_tokens=a_tokens,\r\n ans_len=a_len\r\n )\r\n\r\n cqr_features.append(feature)\r\n\r\n #if dataset == 'coqa':\r\n # unique_id[unique_id] = (example.para_id, example.turn_id)\r\n #elif dataset == 'quac':\r\n # unique_to_ids[unique_id] = (example.q_id, example.turn_id)\r\n #elif dataset == 'squad':\r\n # unique_to_ids[unique_id] = (example.qas_id)\r\n #unique_id += 1\r\n return cqr_features\r\n\r\n\r\n\r\ndef write_coqa_mrc_predictions(unique_to_ids, all_results, output_prediction_file):\r\n \"\"\"Write final predictions to the json file and log-odds of null if needed.\"\"\"\r\n #tf.logging.info(\"Writing predictions to: %s\" % (output_prediction_file))\r\n #tf.logging.info(\"Writing nbest to: %s\" % (output_nbest_file))\r\n \r\n all_predictions = []\r\n for result in all_results:\r\n unique_id = result[0]\r\n para_id, turn_id, _ = unique_to_ids[unique_id]\r\n\r\n cur_prediction = collections.OrderedDict()\r\n cur_prediction['id'] = para_id\r\n cur_prediction['turn_id'] = turn_id\r\n cur_prediction['answer'] = result[1]\r\n\r\n all_predictions.append(cur_prediction)\r\n\r\n #with tf.gfile.GFile(output_prediction_file, \"w\") as writer:\r\n with open(output_prediction_file, \"w\") as writer:\r\n writer.write(json.dumps(all_predictions, indent=4) + \"\\n\")\r\n\r\ndef write_quac_mrc_predictions(unique_to_ids, all_results, output_prediction_file):\r\n all_predictions = {}\r\n\r\n for result in all_results:\r\n unique_id = result[0]\r\n answer_text = result[1]\r\n\r\n q_id, turn_id, para_id, _ = unique_to_ids[unique_id]\r\n\r\n if not para_id in all_predictions:\r\n all_predictions[para_id] = collections.OrderedDict()\r\n all_predictions[para_id]['best_span_str'] = [] # [0] * pred_turn_ids[p_id]\r\n all_predictions[para_id]['qid'] = [] #[0] * pred_turn_ids[p_id]\r\n all_predictions[para_id]['yesno'] = [] #[0] * pred_turn_ids[p_id]\r\n all_predictions[para_id]['followup'] = [] #[0] * pred_turn_ids[p_id]\r\n\r\n cur_prediction = all_predictions[para_id]\r\n\r\n cur_prediction['qid'].append(q_id) #[turn_id-1] = pred_data.qid_dict[(p_id, turn_id)]\r\n cur_prediction['followup'].append(\"m\") #[turn_id-1] = pred_data.followup[(p_id, turn_id)]\r\n\r\n if answer_text.startswith('Yes,'):\r\n cur_prediction['yesno'].append('y')\r\n answer_text = answer_text[len('Yes,'):].strip()\r\n elif answer_text.startswith('No,'):\r\n cur_prediction['yesno'].append('n')\r\n answer_text = answer_text[len('No,'):].strip()\r\n else:\r\n cur_prediction['yesno'].append('x')\r\n\r\n cur_prediction['best_span_str'].append(answer_text)\r\n\r\n with open(output_prediction_file, \"w\") as writer:\r\n for para_id in all_predictions:\r\n writer.write(json.dumps(all_predictions[para_id], indent=4) + \"\\n\")\r\n\r\ndef write_mrc_predictions(unique_to_ids, all_results, output_prediction_file, dataset='coqa'):\r\n if dataset == 'coqa':\r\n write_coqa_mrc_predictions(unique_to_ids, all_results, output_prediction_file)\r\n elif dataset == 'quac':\r\n write_quac_mrc_predictions(unique_to_ids, all_results, output_prediction_file)\r\n\r\n\r\ndef write_questions(unique_to_ids, all_examples, all_results, tokenizer, output_prediction_file, dataset='coqa'):\r\n \"\"\"Write final predictions to the json file and log-odds of null if needed.\"\"\"\r\n #tf.logging.info(\"Writing predictions to: %s\" % (output_prediction_file))\r\n #tf.logging.info(\"Writing nbest to: %s\" % (output_nbest_file))\r\n #unique_to_ids = {}\r\n #example_idx = 0\r\n #for example in all_examples:\r\n # unique_to_ids[feature.unique_id] = (feature.para_id, feature.turn_id, fea_idx) \r\n # fea_idx += 1\r\n\r\n all_predictions = []\r\n\r\n for result in all_results:\r\n unique_id = result[0]\r\n gen_query = result[1]\r\n\r\n\r\n cur_prediction = collections.OrderedDict()\r\n\r\n if dataset == 'coqa':\r\n para_id, turn_id, example_id = unique_to_ids[unique_id]\r\n cur_prediction['id'] = para_id\r\n elif dataset == 'quac':\r\n q_id, turn_id, para_id, example_id = unique_to_ids[unique_id]\r\n cur_prediction['id'] = q_id\r\n \r\n example = all_examples[example_id]\r\n\r\n\r\n cur_prediction['turn_id'] = turn_id\r\n cur_prediction['doc'] = all_examples[example_id].doc # tokenizer.decode(fea.doc_tokens[:fea.doc_len])\r\n cur_prediction['answer'] = all_examples[example_id].ans # tokenizer.decode(fea.ans_tokens[:fea.ans_len])\r\n cur_prediction['orig_query'] = all_examples[example_id].context_query # tokenizer.decode(fea.query_tokens[:fea.query_len])\r\n cur_prediction['gen_query'] = gen_query\r\n\r\n all_predictions.append(cur_prediction)\r\n\r\n #with tf.gfile.GFile(output_prediction_file, \"w\") as writer:\r\n with open(output_prediction_file, \"w\") as writer:\r\n writer.write(json.dumps(all_predictions, indent=4) + \"\\n\")\r\n","sub_path":"python/gpt_finetune/cqr_dataset.py","file_name":"cqr_dataset.py","file_ext":"py","file_size_in_byte":15310,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"271642951","text":"class SluggishAdopter(Adopter):\n \"\"\"\n A SluggishAdopter really dislikes travelling. The further away the\n AdoptionCenter is linearly, the less likely they will want to visit it.\n Since we are not sure the specific mood the SluggishAdopter will be in on a\n given day, we will asign their score with a random modifier depending on\n distance as a guess.\n Score should be\n If distance < 1 return 1 x number of desired species\n elif distance < 3 return random between (.7, .9) times number of desired species\n elif distance < 5. return random between (.5, .7 times number of desired species\n else return random between (.1, .5) times number of desired species\n \"\"\"\n # Your Code Here, should contain an __init__ and a get_score method.\n def __init__(self,name,desired_species,location):\n Adopter.__init__(self,name,desired_species)\n self.location = tuple([float(i) for i in location])\n \n def get_linear_distance(self,adoption_center): \n d = ((adoption_center.get_location()[0]-self.location[0])**2+(adoption_center.get_location()[1]-self.location[1])**2)**(0.5)\n return float(d)\n \n def get_score(self,adoption_center):\n distance = self.get_linear_distance(adoption_center)\n if distance < 1:\n will = 1\n elif distance >= 1 and distance <3:\n will = random.uniform(0.7,0.9)\n elif distance >=3 and distance <5:\n will = random.uniform(0.5,0.7)\n else:\n will = random.uniform(0.1,0.5)\n score = will*adoption_center.get_number_of_species(self.desired_species)\n return float(score)\n","sub_path":"Problem7/sluggishAdopter.py","file_name":"sluggishAdopter.py","file_ext":"py","file_size_in_byte":1649,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"271593423","text":"#BigData Project\n#Contributos: Abiesel, Ramphis, Alexander, Laizla & Andrea\n\n#imports\nimport csv\n\n\n#input code\nfile_tweets = []\nfile_name = input(\"Enter the file name: \")\n\ndefault_file_name = 'ASCE_Samples_v2.csv' \nif(len(file_name)<= 1):\n file_name = default_file_name\n\nwith open(file_name) as File:\n reader = csv.DictReader(File)\n for row in reader:\n file_tweets.append(row)\n'''\n for loop saves every sentences\n'''\nsentences = [] #Contains every sentences of each row\ncounter = 0\nfor i in file_tweets:\n sentences.append(file_tweets[counter]['text'])\n counter+= 1\n\n\n\n#Text Analysis\n\"\"\"\n Disruption Type: \n hurricane related:\n power: 1, communication: 2, water: 3, wastewater: 4, transportation : 5, other -:6\n \n hurricante not related: 7\n\n Disruption Status:\n actual disruption - 1\n not disruption - 0\n\"\"\"\n\n'''\ntweetlistHR = {'hurricane': [], 'water': [], 'power': [], 'communication': [], 'wastewater': [], 'transportion':[], 'other': []}\n\ntweetlistHR['hurricane'] = [\"hurricane Irma\", \"hurricane\"]\ntweetlistHR['water'] = [\"bottle of water\", \"drinking water\", \"water\", \"bottled water\"]\ntweetlistHR['power'] = [\"power off\", \"power down\", \"lost power\", \"fallen power service\", \n \"fallen power cables\", \"fallen power spot\", \"power back\", \"power is back\",\n ]\n'''\ndef evaluate_text(s, l):\n rslt = []\n founded = False\n for word in s.split():\n for i in l:\n if(word == i):\n founded = True\n return \n \n return True\n\ndef assign_number(s):\n if s == 'power':\n return 1\n elif s == 'communication':\n return 2\n elif s == 'water':\n return 3\n elif s == 'wastewater':\n return 4\n elif s == 'transportation':\n return 5\n elif s == 'other':\n return 6\n else:\n return 7\n\n\n\n\n\n#output code\n\n\n","sub_path":"Mainclass.py","file_name":"Mainclass.py","file_ext":"py","file_size_in_byte":1910,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"252965748","text":"from typing import List\n\n\nclass Solution:\n def minPathSum(self, grid: List[List[int]]) -> int:\n '''\n 124 ms\t15.2 MB\tPython3\n '''\n if not grid or not grid[0]:\n return 0\n\n n, m = len(grid), len(grid[0])\n if n == 1:\n return sum(g for g in grid[0])\n if m == 1:\n return sum(g[0] for g in grid)\n\n dp = [[0 for j in range(m)] for i in range(n)]\n\n # 填好右下角以及底边右边的各格子\n dp[n-1][m-1] = grid[n-1][m-1]\n for i in range(n-2, -1, -1):\n dp[i][m-1] = grid[i][m-1] + dp[i+1][m-1]\n for j in range(m-2, -1, -1):\n dp[n-1][j] = grid[n-1][j] + dp[n-1][j+1]\n \n for i in range(n-2, -1, -1):\n for j in range(m-2, -1, -1):\n dp[i][j] = grid[i][j] + min(dp[i+1][j], dp[i][j+1])\n\n return dp[0][0]\n\nif __name__ == \"__main__\":\n sol = Solution()\n print(sol.minPathSum([\n [1,3,1],\n [1,5,1],\n [4,2,1]\n]))\n print(sol.minPathSum([\n[9,1,4,8]\n]))","sub_path":"leetcode/64.minimum-path-sum.py","file_name":"64.minimum-path-sum.py","file_ext":"py","file_size_in_byte":1037,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"382402107","text":"def indexEqualsValue(array):\r\n if len(array)==0:\r\n return -1\r\n if len(array)==1:\r\n if array[0]==0:\r\n return 0\r\n else:\r\n return -1\r\n n=len(array)\r\n l=0\r\n r=n-1\r\n while 0 <=l<=n-1 and 0 <= r <=n-1 and r>=l:\r\n if array[l]==l:\r\n return l\r\n mid=(l+r)//2\r\n if array[mid]mid:\r\n r=mid-1\r\n else:\r\n r=mid\r\n if array[mid]!=mid:\r\n return -1","sub_path":"index_equals_value.py","file_name":"index_equals_value.py","file_ext":"py","file_size_in_byte":512,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"417754736","text":"#! /usr/bin/env python\n# -*- coding: utf-8 -*-\nfrom argparse import ArgumentParser\nimport subprocess\nimport os\n\n\ndef parser():\n ap = ArgumentParser()\n ap.add_argument(\n '-u',\n '--uuid',\n type=str,\n dest='uuid',\n required=True,\n help='this is dSYMs of uuid'\n )\n ap.add_argument(\n '-d',\n '--dir',\n type=str,\n dest='dir',\n required=False,\n default=os.path.expanduser('~/Desktop/tmp_dSYMs'),\n help='target directory'\n )\n aps = ap.parse_args()\n return aps\n\n\ndef findFile(uuid):\n res = subprocess.check_output(['mdfind', uuid])\n return res.split(\"\\n\")\n\n\ndef copyFile(src, dst):\n if not os.path.exists(dst):\n print('======== create directory ' + dst)\n os.mkdir(dst)\n res = subprocess.check_call(['cp', '-rp', src, dst])\n return res == 0\n\n\nif __name__ == '__main__':\n args = parser()\n if args.uuid != \"\":\n files = findFile(args.uuid)\n files.pop()\n if len(files) == 1:\n if copyFile(files[0], args.dir):\n print('======== complete copy')\n print('======== copy directory')\n print(args.dir)\n else:\n print('copy error')\n else:\n print('======== discover 2 or more files')\n print('\\n'.join(files))\n else:\n print(\"not select uuid\")\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1404,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"55732527","text":"import scipy.spatial as ss\nimport math\nimport numpy.random as nr\nimport random\n\n##!!!Estimatore per la MI con algoritmo da Kraskov et al. 2004\ndef mi(x,y,k=3,base=2):\n \"\"\" Mutual information of x and y\n x,y should be a list of vectors, e.g. x = [[1.3],[3.7],[5.1],[2.4]]\n if x is a one-dimensional scalar and we have four samples\n \"\"\"\n assert len(x)==len(y), \"Lists should have same length\"\n assert k <= len(x) - 1, \"Set k smaller than num. samples - 1\"\n intens = 1e-12 #small noise to break degeneracy, see doc.\n x = [list(p + intens*nr.rand(len(x[0]))) for p in x]\n y = [list(p + intens*nr.rand(len(y[0]))) for p in y]\n points = zip2(x,y)\n #Find nearest neighbors in joint space, p=inf means max-norm\n tree = ss.cKDTree(points)\n dvec = [tree.query(point,k+1,p=float('inf'))[0][k] for point in points]\n a,b,c,d = avgdigamma(x,dvec), avgdigamma(y,dvec), digamma(k), digamma(len(x))\n return (-a-b+c+d)#/log(base)\n############################################################################\n\n#####UTILITY FUNCTIONS\ndef vectorize(scalarlist):\n \"\"\" Turn a list of scalars into a list of one-d vectors\n \"\"\"\n return [(x,) for x in scalarlist]\n\ndef shuffle_test(x,y,z=False,ns=10,ci=0.95,**kwargs):#measure,\n \"\"\" Shuffle test\n Repeatedly shuffle the x-values and then estimate measure(x,y,[z]).\n Returns the mean and conf. interval ('ci=0.95' default) over 'ns' runs.\n 'measure' could me mi,cmi, e.g. Keyword arguments can be passed.\n Mutual information and CMI should have a mean near zero.\n \"\"\"\n xp = x[:] #A copy that we can shuffle\n outputs = []\n for i in range(ns):\n random.shuffle(xp)\n if z:\n outputs.append(mi(xp,y,z,**kwargs))\n else:\n outputs.append(mi(xp,y,**kwargs))\n outputs.sort()\n\n\n sigma=0.0;\n med=0.0;\n\n for i in range (0,ns):\n med+=outputs[i]\n\n med*=1/ns\n\n for i in range (0,ns):\n sigma+=(outputs[i]-med)*(outputs[i]-med)\n\n sigma=math.sqrt(sigma)\n sigma*=1/(math.sqrt(ns))\n sigma*=1.96\n\n return med,sigma;\n\n#####INTERNAL FUNCTIONS\n\ndef avgdigamma(points,dvec):\n #This part finds number of neighbors in some radius in the marginal space\n #returns expectation value of \n N = len(points)\n tree = ss.cKDTree(points)\n avg = 0.\n for i in range(N):\n dist = dvec[i]\n #subtlety, we don't include the boundary point,\n #but we are implicitly adding 1 to kraskov def bc center point is included\n num_points = len(tree.query_ball_point(points[i],dist-1e-15,p=float('inf')))\n avg += digamma(num_points)/N\n return avg\n\ndef zip2(*args):\n #zip2(x,y) takes the lists of vectors and makes it a list of vectors in a joint space\n #E.g. zip2([[1],[2],[3]],[[4],[5],[6]]) = [[1,4],[2,5],[3,6]]\n return [sum(sublist,[]) for sublist in zip(*args)]\n\n","sub_path":"PINI/entropy_estimators.py","file_name":"entropy_estimators.py","file_ext":"py","file_size_in_byte":2753,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"567772301","text":"import cv2\nimport numpy as np\n\ndef makeImgs(data):\n for i in range(len(data)):\n image = np.zeros((64,64,1), np.uint8)\n scaled = [data[i][x]*255/16 for x in range(64)]\n for x in range(8):\n for y in range(8):\n image[x*8:x*8+7,y*8:y*8+7]\n cv2.imwrite(\"img\"+str(i)+\".jpg\", image)","sub_path":"kMeans/visualize.py","file_name":"visualize.py","file_ext":"py","file_size_in_byte":332,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"199553779","text":"# Day_04_01_translation.py\nimport requests\nimport json\n\ndef not_used():\n # Accept:*/*\n # Accept-Encoding:gzip, deflate\n # Accept-Language:ko-KR,ko;q=0.8,en-US;q=0.6,en;q=0.4\n # Connection:keep-alive\n # Content-Length:236\n # content-type:application/x-www-form-urlencoded; charset=UTF-8\n # Cookie:npic=zAiceKejPrHjVaf0nAVhV173yzw7cI4PH3GGz9vRJVd03DGTkIu48Df82n4kKY5GCA==; NNB=ALGCGT7MAFVFQ; nx_ssl=2; NaverSuggestPlus=unuse; NaverSuggestUse=use%26use; wcs_bt=dccae51cc9ffb4:1483578203\n # Host:labspace.naver.com\n # Origin:http://labspace.naver.com\n # Referer:http://labspace.naver.com/nmt/\n # User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36\n # x-naver-client-id:labspace\n\n headers = {'x-naver-client-id': 'labspace'}\n\n payload = dict(source='ko', target='en',\n text='세상은 데이터를 가진 자와 갖지 않은 자로 나뉩니다.')\n\n url= 'http://labspace.naver.com/api/n2mt/translate'\n recvd = requests.post(url, data=payload, headers=headers)\n print(recvd)\n print(recvd.text)\n print(type(recvd.text))\n\n root = json.loads(recvd.text)\n print(type(root))\n print(root.keys()) # 'message'\n\n message = root['message']\n print(message)\n print(message.keys()) # '@service', '@type', '@version', 'result'\n\n result = message['result']\n print(result)\n print(result.keys()) # 'tarLangType', 'translatedText', 'srcLangType'\n print('-'*50)\n\n print(result['srcLangType'])\n print(result['tarLangType'])\n print(result['translatedText'])\n # The world is divided into those who have no data.\n\n\ndef translate(text, kor2eng):\n headers = {'x-naver-client-id': 'labspace'}\n payload = dict(source='ko', target='en', text=text)\n\n if not kor2eng:\n payload['source'] = 'en'\n payload['target'] = 'ko'\n\n url= 'http://labspace.naver.com/api/n2mt/translate'\n recvd = requests.post(url, data=payload, headers=headers)\n\n root = json.loads(recvd.text)\n message = root['message']\n result = message['result']\n\n return result['translatedText']\n\nprint(translate('파이썬을 계속 공부하는 방법이 있을까요?', True))\nprint(translate('Do you know how to keep up with python?', False))\n\n\n\n\n\n\n","sub_path":"python_practice/python_2016_12/python_snu_2016_12/Day_04_01_translation.py","file_name":"Day_04_01_translation.py","file_ext":"py","file_size_in_byte":2313,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"239121450","text":"import Utils\nimport random\nimport Reddit\nimport pickle\nimport argparse\nimport discord\nfrom discord.ext import commands\n\nbot = commands.Bot(command_prefix=\".\", help_command=None)\nparser = argparse.ArgumentParser(description=\"discord bot go brrrr\")\noptions = []\n\nparser.add_argument(\"--discordToken\", \"-d\", help=\"Discord bot token.\")\nparser.add_argument(\"--redditID\", \"-i\", help=\"Your reddit client ID.\")\nparser.add_argument(\"--redditSecret\", \"-s\", help=\"Your reddit client secret.\")\n\nargs = parser.parse_args()\n\n# Attempts to read \"options.cfg\"\n# If reading \"options.cfg\" is not successful, it will print the error, and exit the program with the code of -1\nif args.discordToken and args.redditID and args.redditSecret:\n with open(\"options.cfg\", \"wb\") as configFile:\n pickle.dump([args.discordToken, args.redditID, args.redditSecret], configFile)\n\n with open(\"options.cfg\", \"rb\") as configFile:\n options = pickle.load(configFile)\nelse:\n try:\n with open(\"options.cfg\", \"rb\") as configFile:\n options = pickle.load(configFile)\n if len(options) != 3:\n print(\"Missing options in \\\"options.cfg\\\", or missing arguments.\")\n exit(-1)\n except FileNotFoundError as e:\n print(\"\\\"options.cfg\\\" was not found.\")\n exit(-1)\n\nimageScrapperReddit = Reddit.ImageScrapper(options[1], options[2])\n\n\n# Prints a ready message once the bot is ready\n@bot.event\nasync def on_ready():\n print(\"lol bot is ready\")\n\n\n# \".reddit\" command\n@bot.command()\nasync def reddit(ctx, *, args):\n parsedArgs = args.split(\" \")\n\n # Checks if the first argument is valid\n # Sends back error if the argument is invalid\n\n # .reddit top \n if parsedArgs[0] == \"top\":\n # Checks if the seconds argument is a string name of the subreddit or an index of the subreddit\n # If it is nether, it will be defaulted to r/hentai\n try:\n parsedArgs[1]\n\n try:\n submissions = imageScrapperReddit.Get(ctx.guild, imageScrapperReddit.subreddits[int(parsedArgs[1])], \"top\")\n except:\n submissions = imageScrapperReddit.Get(ctx.guild, parsedArgs[1], \"top\")\n except:\n parsedArgs.append(\"hentai\")\n submissions = imageScrapperReddit.Get(ctx.guild, parsedArgs[1], \"top\")\n\n # Checks to make sure the Get function returns a list\n # Prints error message if it doesn't\n if isinstance(submissions, int):\n print(f\"Error! Function returned {submissions}\")\n else:\n # If submissions length is more than zero, a random submission will be chosen and removed from the submissions\n # Else, The cache will be refreshed, then a random submission will be chosen and removed from the submissions\n if len(submissions) > 0:\n choice = random.choice(submissions)\n imageScrapperReddit.Remove(ctx.guild, parsedArgs[1], \"top\", choice)\n else:\n imageScrapperReddit.RefreshCache(ctx.guild, parsedArgs[1], \"top\")\n submissions = imageScrapperReddit.Get(ctx.guild, parsedArgs[1], \"top\")\n\n choice = random.choice(submissions)\n imageScrapperReddit.Remove(ctx.guild, parsedArgs[1], \"top\", choice)\n\n await ctx.send(embed=Utils.redditEmbed(choice))\n\n # .reddit hot \n elif parsedArgs[0] == \"hot\":\n # Checks if the seconds argument is a string name of the subreddit or an index of the subreddit\n # If it is nether, it will be defaulted to r/hentai\n try:\n parsedArgs[1]\n try:\n submissions = imageScrapperReddit.Get(ctx.guild, imageScrapperReddit.subreddits[int(parsedArgs[1])], \"hot\")\n except:\n submissions = imageScrapperReddit.Get(ctx.guild, parsedArgs[1], \"hot\")\n except:\n parsedArgs.append(\"hentai\")\n submissions = imageScrapperReddit.Get(ctx.guild, parsedArgs[1], \"hot\")\n\n # Checks to make sure the Get function returns a list\n # Prints error message if it doesn't\n if isinstance(submissions, int):\n print(f\"Error! Function returned {submissions}\")\n else:\n # If submissions length is more than zero, a random submission will be chosen and removed from the submissions\n # Else, The cache will be refreshed, then a random submission will be chosen and removed from the submissions\n if len(submissions) > 0:\n choice = random.choice(submissions)\n imageScrapperReddit.Remove(ctx.guild, parsedArgs[1], \"hot\", choice)\n else:\n imageScrapperReddit.RefreshCache(ctx.guild, parsedArgs[1], \"hot\")\n submissions = imageScrapperReddit.Get(ctx.guild, parsedArgs[1], \"hot\")\n\n choice = random.choice(submissions)\n imageScrapperReddit.Remove(ctx.guild, parsedArgs[1], \"hot\", choice)\n\n await ctx.send(embed=Utils.redditEmbed(choice))\n\n # .reddit refresh \n elif parsedArgs[0] == \"refresh\":\n\n embed = discord.Embed(title=\"Refreshing the cache...\", color=Utils.EmbedColor)\n embed.set_author(name=f\"Cache refresh requested by {ctx.message.author.name}\", icon_url=ctx.message.author.avatar_url)\n\n await ctx.send(embed=embed)\n\n # Checks if the seconds argument is a string name of the subreddit or an index of the subreddit\n # If it is nether, it will be defaulted to r/hentai\n try:\n parsedArgs[1]\n try:\n topReturn = imageScrapperReddit.RefreshCache(ctx.guild, imageScrapperReddit.subreddits[int(parsedArgs[1])], \"top\")\n hotReturn = imageScrapperReddit.RefreshCache(ctx.guild, imageScrapperReddit.subreddits[int(parsedArgs[1])], \"hot\")\n except:\n topReturn = imageScrapperReddit.RefreshCache(ctx.guild, parsedArgs[1], \"top\")\n hotReturn = imageScrapperReddit.RefreshCache(ctx.guild, parsedArgs[1], \"hot\")\n except:\n parsedArgs.append(\"hentai\")\n topReturn = imageScrapperReddit.RefreshCache(ctx.guild, parsedArgs[1], \"top\")\n hotReturn = imageScrapperReddit.RefreshCache(ctx.guild, parsedArgs[1], \"hot\")\n\n # Checks to make sure returnValue is 0\n # If returnValue is -1, there was an error trying to get the posts\n # If returnValue is -2, the second argument is not a valid cache\n if hotReturn == 0 and topReturn == 0:\n\n await ctx.send(\n embed=discord.Embed(\n title=\"It seems to have all went well!\",\n description=f\"The cache has been refreshed!\",\n color=Utils.EmbedColor\n )\n )\n\n elif hotReturn == -1 or topReturn == -1:\n\n await ctx.send(\n embed=discord.Embed(\n title=\"There was an error when trying to retrieve the posts!\",\n description=\"This either means Reddit is down or the Reddit web app is broke.\",\n color=Utils.EmbedColor\n )\n )\n\n # .reddit subreddits\n elif parsedArgs[0] == \"subreddits\":\n await ctx.send(embed=Utils.supportedSubredditsEmbed(imageScrapperReddit.subreddits))\n\n else:\n await ctx.send(embed=Utils.errorEmbed(f\"\\\"{parsedArgs[0]}\\\" is not a valid argument for `.reddit`!\"))\n\n\n# \".help\" command\n@bot.command(aliases=[\"usage\"])\nasync def help(ctx):\n # Creates fancy help screen embed, so it looks like I know what im doing\n\n embed = discord.Embed(\n title=\"Help and Usage\",\n color=Utils.EmbedColor\n )\n\n embed.add_field(name=\".help/.usage\", value=\"Shows this help screen.\", inline=False)\n embed.add_field(\n name=\".reddit \",\n value=\"Picks a random image from the top or hot section on the chosen subreddit or subreddit index.\"\n \"\\nDefaults to r/hentai if the subreddit or subreddit index is not valid or no argument is supplied.\"\n \"\\nExamples:\"\n \"\\n`.reddit top hentai`\"\n \"\\n`.reddit top 0`\",\n inline=False\n )\n embed.add_field(\n name=\".reddit refresh \",\n value=\"Refreshes the cache of the chosen subreddit or subreddit index.\"\n \"\\nDefaults to r/hentai if the subreddit or subreddit index is not valid or no argument is supplied.\"\n \"\\nExamples:\"\n \"\\n`.reddit refresh hentai`\"\n \"\\n`.reddit refresh 0`\",\n inline=False\n )\n embed.add_field(\n name=\".reddit subreddits\",\n value=\"Lists all of the supported subreddits.\",\n inline=False\n )\n embed.add_field(\n name=\"Project Homepage:\",\n value=\"[https://github.com/catjacks38/HentaiDiscordBot](url)\",\n inline=False\n )\n embed.add_field(\n name=\"Submit any Bugs or Feature Requests Here:\",\n value=\"[https://github.com/catjacks38/HentaiDiscordBot/issues](url)\",\n inline=False\n )\n\n await ctx.send(embed=embed)\n\n\n# Tries to use the discord token\n# If there is an error, the script exits with code -1\ntry:\n bot.run(options[0])\nexcept:\n print(\"Discord bot token isn't valid.\")\n exit(-1)\n","sub_path":"bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":9408,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"410771528","text":"# Copyright 2021 Pants project contributors (see CONTRIBUTORS.md).\n# Licensed under the Apache License, Version 2.0 (see LICENSE).\n\nfrom __future__ import annotations\n\nimport re\nfrom enum import Enum\n\nfrom pants.backend.shell.subsystems.shell_setup import ShellSetup\nfrom pants.core.goals.test import RuntimePackageDependenciesField, TestTimeoutField\nfrom pants.core.util_rules.environments import EnvironmentField\nfrom pants.core.util_rules.system_binaries import BinaryPathTest\nfrom pants.engine.rules import collect_rules, rule\nfrom pants.engine.target import (\n COMMON_TARGET_FIELDS,\n BoolField,\n Dependencies,\n IntField,\n MultipleSourcesField,\n OverridesField,\n SingleSourceField,\n SpecialCasedDependencies,\n StringField,\n StringSequenceField,\n Target,\n TargetFilesGenerator,\n TargetFilesGeneratorSettings,\n TargetFilesGeneratorSettingsRequest,\n ValidNumbers,\n generate_file_based_overrides_field_help_message,\n generate_multiple_sources_field_help_message,\n)\nfrom pants.engine.unions import UnionRule\nfrom pants.util.enums import match\nfrom pants.util.strutil import help_text, softwrap\n\n\nclass ShellDependenciesField(Dependencies):\n pass\n\n\nclass ShellSourceField(SingleSourceField):\n # Normally, we would add `expected_file_extensions = ('.sh',)`, but Bash scripts don't need a\n # file extension, so we don't use this.\n uses_source_roots = False\n\n\nclass ShellGeneratingSourcesBase(MultipleSourcesField):\n uses_source_roots = False\n\n\nclass ShellGeneratorSettingsRequest(TargetFilesGeneratorSettingsRequest):\n pass\n\n\n@rule\ndef generator_settings(\n _: ShellGeneratorSettingsRequest,\n shell_setup: ShellSetup,\n) -> TargetFilesGeneratorSettings:\n return TargetFilesGeneratorSettings(\n add_dependencies_on_all_siblings=not shell_setup.dependency_inference\n )\n\n\n# -----------------------------------------------------------------------------------------------\n# `shunit2_test` target\n# -----------------------------------------------------------------------------------------------\n\n\nclass Shunit2Shell(Enum):\n sh = \"sh\"\n bash = \"bash\"\n dash = \"dash\"\n ksh = \"ksh\"\n pdksh = \"pdksh\"\n zsh = \"zsh\"\n\n @classmethod\n def parse_shebang(cls, shebang: bytes) -> Shunit2Shell | None:\n if not shebang:\n return None\n first_line = shebang.splitlines()[0]\n matches = re.match(rb\"^#! *[/\\w]*/(?P\\w+) *(?P\\w*)\", first_line)\n if not matches:\n return None\n program = matches.group(\"program\")\n if program == b\"env\":\n program = matches.group(\"arg\")\n try:\n return cls(program.decode())\n except ValueError:\n return None\n\n @property\n def binary_path_test(self) -> BinaryPathTest | None:\n arg = match( # type: ignore[misc]\n self,\n {\n self.sh: None,\n self.bash: \"--version\",\n self.dash: None,\n self.ksh: \"--version\",\n self.pdksh: None,\n self.zsh: \"--version\",\n },\n )\n if not arg:\n return None\n return BinaryPathTest((arg,))\n\n\nclass Shunit2TestDependenciesField(ShellDependenciesField):\n supports_transitive_excludes = True\n\n\nclass Shunit2TestTimeoutField(TestTimeoutField):\n pass\n\n\nclass SkipShunit2TestsField(BoolField):\n alias = \"skip_tests\"\n default = False\n help = \"If true, don't run this target's tests.\"\n\n\nclass Shunit2TestSourceField(ShellSourceField):\n pass\n\n\nclass Shunit2ShellField(StringField):\n alias = \"shell\"\n valid_choices = Shunit2Shell\n help = \"Which shell to run the tests with. If unspecified, Pants will look for a shebang line.\"\n\n\nclass Shunit2TestTarget(Target):\n alias = \"shunit2_test\"\n core_fields = (\n *COMMON_TARGET_FIELDS,\n Shunit2TestSourceField,\n Shunit2TestDependenciesField,\n Shunit2TestTimeoutField,\n SkipShunit2TestsField,\n Shunit2ShellField,\n RuntimePackageDependenciesField,\n )\n help = help_text(\n f\"\"\"\n A single test file for Bourne-based shell scripts using the shunit2 test framework.\n\n To use, add tests to your file per https://github.com/kward/shunit2/. Specify the shell\n to run with by either setting the field `{Shunit2ShellField.alias}` or including a\n shebang. To test the same file with multiple shells, create multiple `shunit2_tests`\n targets, one for each shell.\n\n Pants will automatically download the `shunit2` bash script and add\n `source ./shunit2` to your test for you. If you already have `source ./shunit2`,\n Pants will overwrite it to use the correct relative path.\n \"\"\"\n )\n\n\n# -----------------------------------------------------------------------------------------------\n# `shunit2_tests` target generator\n# -----------------------------------------------------------------------------------------------\n\n\nclass Shunit2TestsGeneratorSourcesField(ShellGeneratingSourcesBase):\n default = (\"*_test.sh\", \"test_*.sh\", \"tests.sh\")\n help = generate_multiple_sources_field_help_message(\n \"Example: `sources=['test.sh', 'test_*.sh', '!test_ignore.sh']`\"\n )\n\n\nclass Shunit2TestsOverrideField(OverridesField):\n help = generate_file_based_overrides_field_help_message(\n Shunit2TestTarget.alias,\n \"\"\"\n overrides={\n \"foo_test.sh\": {\"timeout\": 120},\n \"bar_test.sh\": {\"timeout\": 200},\n (\"foo_test.sh\", \"bar_test.sh\"): {\"tags\": [\"slow_tests\"]},\n }\n \"\"\",\n )\n\n\nclass Shunit2TestsGeneratorTarget(TargetFilesGenerator):\n alias = \"shunit2_tests\"\n core_fields = (\n *COMMON_TARGET_FIELDS,\n Shunit2TestsGeneratorSourcesField,\n Shunit2TestsOverrideField,\n )\n generated_target_cls = Shunit2TestTarget\n copied_fields = COMMON_TARGET_FIELDS\n moved_fields = (\n Shunit2TestDependenciesField,\n Shunit2TestTimeoutField,\n SkipShunit2TestsField,\n Shunit2ShellField,\n RuntimePackageDependenciesField,\n )\n help = \"Generate a `shunit2_test` target for each file in the `sources` field.\"\n\n\n# -----------------------------------------------------------------------------------------------\n# `shell_source` and `shell_sources` targets\n# -----------------------------------------------------------------------------------------------\n\n\nclass ShellSourceTarget(Target):\n alias = \"shell_source\"\n core_fields = (*COMMON_TARGET_FIELDS, ShellDependenciesField, ShellSourceField)\n help = \"A single Bourne-based shell script, e.g. a Bash script.\"\n\n\nclass ShellSourcesGeneratingSourcesField(ShellGeneratingSourcesBase):\n default = (\"*.sh\",) + tuple(f\"!{pat}\" for pat in Shunit2TestsGeneratorSourcesField.default)\n help = generate_multiple_sources_field_help_message(\n \"Example: `sources=['example.sh', 'new_*.sh', '!old_ignore.sh']`\"\n )\n\n\nclass ShellSourcesOverridesField(OverridesField):\n help = generate_file_based_overrides_field_help_message(\n ShellSourceTarget.alias,\n \"\"\"\n overrides={\n \"foo.sh\": {\"skip_shellcheck\": True]},\n \"bar.sh\": {\"skip_shfmt\": True]},\n (\"foo.sh\", \"bar.sh\"): {\"tags\": [\"linter_disabled\"]},\n }\n \"\"\",\n )\n\n\nclass ShellSourcesGeneratorTarget(TargetFilesGenerator):\n alias = \"shell_sources\"\n core_fields = (\n *COMMON_TARGET_FIELDS,\n ShellSourcesGeneratingSourcesField,\n ShellSourcesOverridesField,\n )\n generated_target_cls = ShellSourceTarget\n copied_fields = COMMON_TARGET_FIELDS\n moved_fields = (ShellDependenciesField,)\n help = \"Generate a `shell_source` target for each file in the `sources` field.\"\n\n\n# -----------------------------------------------------------------------------------------------\n# `shell_command` target\n# -----------------------------------------------------------------------------------------------\n\n\nclass ShellCommandCommandField(StringField):\n alias = \"command\"\n required = True\n help = \"Shell command to execute.\\n\\nThe command is executed as 'bash -c ' by default.\"\n\n\nclass RunInSandboxRunnableField(StringField):\n alias = \"runnable\"\n required = True\n help = help_text(\n \"\"\"\n Address to a target that can be invoked by the `run` goal (and does not set\n `run_in_sandbox_behavior=NOT_SUPPORTED`). This will be executed along with any arguments\n specified by `argv`, in a sandbox with that target's transitive dependencies, along with\n the transitive dependencies specified by `execution_dependencies`.\n \"\"\"\n )\n\n\nclass ShellCommandOutputsField(StringSequenceField):\n alias = \"outputs\"\n help = help_text(\n \"\"\"\n Specify the shell command output files and directories, relative to the value of `workdir`.\n\n Use a trailing slash on directory names, i.e. `my_dir/`.\n\n Relative paths (including `..`) may be used, as long as the path does not ascend further\n than the build root.\n \"\"\"\n )\n removal_hint = \"To fix, use `output_files` and `output_directories` instead.\"\n removal_version = \"2.17.0.dev0\"\n\n\nclass ShellCommandOutputFilesField(StringSequenceField):\n alias = \"output_files\"\n required = False\n default = ()\n help = help_text(\n \"\"\"\n Specify the shell command's output files to capture, relative to the value of `workdir`.\n\n For directories, use `output_directories`. At least one of `output_files` and\n `output_directories` must be specified.\n\n Relative paths (including `..`) may be used, as long as the path does not ascend further\n than the build root.\n \"\"\"\n )\n\n\nclass ShellCommandOutputDirectoriesField(StringSequenceField):\n alias = \"output_directories\"\n required = False\n default = ()\n help = help_text(\n \"\"\"\n Specify full directories (including recursive descendants) of output to capture from the\n shell command, relative to the value of `workdir`.\n\n For individual files, use `output_files`. At least one of `output_files` and\n `output_directories` must be specified.\n\n Relative paths (including `..`) may be used, as long as the path does not ascend further\n than the build root.\n \"\"\"\n )\n\n\nclass ShellCommandOutputDependenciesField(ShellDependenciesField):\n supports_transitive_excludes = True\n alias = \"output_dependencies\"\n deprecated_alias = \"dependencies\"\n deprecated_alias_removal_version = \"2.17.0.dev0\"\n\n help = lambda: softwrap(\n f\"\"\"\n Any dependencies that the output artifacts require in order to be effectively consumed.\n\n To enable legacy use cases, if `{ShellCommandExecutionDependenciesField.alias}` is `None`, these dependencies will\n be materialized in the command execution sandbox. This behavior is deprecated, and will be\n removed in version 2.17.0.dev0.\n \"\"\"\n )\n\n\nclass ShellCommandExecutionDependenciesField(SpecialCasedDependencies):\n alias = \"execution_dependencies\"\n required = False\n default = None\n\n help = help_text(\n \"\"\"\n The execution dependencies for this shell command.\n\n Dependencies specified here are those required to make the command complete successfully\n (e.g. file inputs, binaries compiled from other targets, etc), but NOT required to make\n the output side-effects useful. Dependencies that are required to use the side-effects\n produced by this command should be specified using the `output_dependencies` field.\n\n If this field is specified, dependencies from `output_dependencies` will not be added to\n the execution sandbox.\n \"\"\"\n )\n\n\nclass ShellCommandSourcesField(MultipleSourcesField):\n # We solely register this field for codegen to work.\n alias = \"_sources\"\n uses_source_roots = False\n expected_num_files = 0\n\n\nclass RunInSandboxSourcesField(MultipleSourcesField):\n # We solely register this field for codegen to work.\n alias = \"_sources\"\n uses_source_roots = False\n expected_num_files = 0\n\n\nclass RunInSandboxArgumentsField(StringSequenceField):\n alias = \"args\"\n default = ()\n help = f\"Extra arguments to pass into the `{RunInSandboxRunnableField.alias}` field.\"\n\n\nclass RunInSandboxStdoutFilenameField(StringField):\n alias = \"stdout\"\n default = None\n help = \"A filename to capture the contents of `stdout` to, relative to the value of `workdir`.\"\n\n\nclass RunInSandboxStderrFilenameField(StringField):\n alias = \"stderr\"\n default = None\n help = \"A filename to capture the contents of `stdout` to, relative to the value of `workdir`.\"\n\n\nclass ShellCommandTimeoutField(IntField):\n alias = \"timeout\"\n default = 30\n help = \"Command execution timeout (in seconds).\"\n valid_numbers = ValidNumbers.positive_only\n\n\nclass ShellCommandToolsField(StringSequenceField):\n alias = \"tools\"\n default = ()\n help = help_text(\n \"\"\"\n Specify required executable tools that might be used.\n\n Only the tools explicitly provided will be available on the search PATH,\n and these tools must be found on the paths provided by\n [shell-setup].executable_search_paths (which defaults to the system PATH).\n \"\"\"\n )\n\n\nclass ShellCommandExtraEnvVarsField(StringSequenceField):\n alias = \"extra_env_vars\"\n help = help_text(\n \"\"\"\n Additional environment variables to include in the shell process.\n Entries are strings in the form `ENV_VAR=value` to use explicitly; or just\n `ENV_VAR` to copy the value of a variable in Pants's own environment.\n \"\"\"\n )\n\n\nclass ShellCommandLogOutputField(BoolField):\n alias = \"log_output\"\n default = False\n help = \"Set to true if you want the output from the command logged to the console.\"\n\n\nclass ShellCommandWorkdirField(StringField):\n alias = \"workdir\"\n default = \".\"\n help = help_text(\n \"Sets the current working directory of the command. \\n\\n\"\n \"Values are relative to the build root, except in the following cases:\\n\\n\"\n \"* `.` specifies the location of the `BUILD` file.\\n\"\n \"* Values beginning with `./` are relative to the location of the `BUILD` file.\\n\"\n \"* `/` or the empty string specifies the build root.\\n\"\n \"* Values beginning with `/` are also relative to the build root.\"\n )\n\n\nclass RunShellCommandWorkdirField(StringField):\n alias = \"workdir\"\n default = \".\"\n help = help_text(\n \"Sets the current working directory of the command that is `run`. Values that begin with \"\n \"`.` are relative to the directory you are running Pants from. Values that begin with `/` \"\n \"are from your project root.\"\n )\n\n\nclass ShellCommandOutputRootDirField(StringField):\n alias = \"root_output_directory\"\n default = \"/\"\n help = help_text(\n \"Adjusts the location of files output by this command, when consumed as a dependency.\\n\\n\"\n \"Values are relative to the build root, except in the following cases:\\n\\n\"\n \"* `.` specifies the location of the `BUILD` file.\\n\"\n \"* Values beginning with `./` are relative to the location of the `BUILD` file.\\n\"\n \"* `/` or the empty string specifies the build root.\\n\"\n \"* Values beginning with `/` are also relative to the build root.\"\n )\n\n\nclass ShellCommandTestDependenciesField(ShellCommandExecutionDependenciesField):\n pass\n\n\nclass SkipShellCommandTestsField(BoolField):\n alias = \"skip_tests\"\n default = False\n help = \"If true, don't run this tests for target.\"\n\n\nclass ShellCommandTarget(Target):\n alias = \"experimental_shell_command\"\n core_fields = (\n *COMMON_TARGET_FIELDS,\n ShellCommandOutputDependenciesField,\n ShellCommandExecutionDependenciesField,\n ShellCommandCommandField,\n ShellCommandLogOutputField,\n ShellCommandOutputsField,\n ShellCommandOutputFilesField,\n ShellCommandOutputDirectoriesField,\n ShellCommandSourcesField,\n ShellCommandTimeoutField,\n ShellCommandToolsField,\n ShellCommandExtraEnvVarsField,\n ShellCommandWorkdirField,\n ShellCommandOutputRootDirField,\n EnvironmentField,\n )\n help = help_text(\n \"\"\"\n Execute any external tool for its side effects.\n\n Example BUILD file:\n\n experimental_shell_command(\n command=\"./my-script.sh --flag\",\n tools=[\"tar\", \"curl\", \"cat\", \"bash\", \"env\"],\n execution_dependencies=[\":scripts\"],\n output_files=[\"logs/my-script.log\"],\n output_directories=[\"results\"],\n )\n\n shell_sources(name=\"scripts\")\n\n Remember to add this target to the dependencies of each consumer, such as your\n `python_tests` or `docker_image`. When relevant, Pants will run your `command` and\n insert the `outputs` into that consumer's context.\n\n The command may be retried and/or cancelled, so ensure that it is idempotent.\n \"\"\"\n )\n\n\nclass ShellRunInSandboxTarget(Target):\n alias = \"experimental_run_in_sandbox\"\n core_fields = (\n *COMMON_TARGET_FIELDS,\n RunInSandboxRunnableField,\n RunInSandboxArgumentsField,\n ShellCommandExecutionDependenciesField,\n ShellCommandOutputDependenciesField,\n ShellCommandLogOutputField,\n ShellCommandOutputFilesField,\n ShellCommandOutputDirectoriesField,\n RunInSandboxSourcesField,\n ShellCommandTimeoutField,\n ShellCommandToolsField,\n ShellCommandExtraEnvVarsField,\n ShellCommandWorkdirField,\n ShellCommandOutputRootDirField,\n RunInSandboxStdoutFilenameField,\n RunInSandboxStderrFilenameField,\n EnvironmentField,\n )\n help = help_text(\n \"\"\"\n Execute any runnable target for its side effects.\n\n Example BUILD file:\n\n experimental_run_in_sandbox(\n runnable=\":python_source\",\n argv=[\"\"],\n tools=[\"tar\", \"curl\", \"cat\", \"bash\", \"env\"],\n execution_dependencies=[\":scripts\"],\n outputs=[\"results/\", \"logs/my-script.log\"],\n )\n\n shell_sources(name=\"scripts\")\n \"\"\"\n )\n\n\nclass ShellCommandRunTarget(Target):\n alias = \"experimental_run_shell_command\"\n core_fields = (\n *COMMON_TARGET_FIELDS,\n ShellCommandExecutionDependenciesField,\n ShellCommandCommandField,\n RunShellCommandWorkdirField,\n )\n help = help_text(\n \"\"\"\n Run a script in the workspace, with all dependencies packaged/copied into a chroot.\n\n Example BUILD file:\n\n experimental_run_shell_command(\n command=\"./scripts/my-script.sh --data-files-dir={chroot}\",\n execution_dependencies=[\"src/project/files:data\"],\n )\n\n The `command` may use either `{chroot}` on the command line, or the `$CHROOT`\n environment variable to get the root directory for where any dependencies are located.\n\n In contrast to the `experimental_shell_command`, in addition to `workdir` you only have\n the `command` and `execution_dependencies` fields as the `tools` you are going to use are\n already on the PATH which is inherited from the Pants environment. Also, the `outputs` does\n not apply, as any output files produced will end up directly in your project tree.\n \"\"\"\n )\n\n\nclass ShellCommandTestTarget(Target):\n alias = \"experimental_test_shell_command\"\n core_fields = (\n *COMMON_TARGET_FIELDS,\n ShellCommandTestDependenciesField,\n ShellCommandCommandField,\n ShellCommandLogOutputField,\n ShellCommandSourcesField,\n ShellCommandTimeoutField,\n ShellCommandToolsField,\n ShellCommandExtraEnvVarsField,\n EnvironmentField,\n SkipShellCommandTestsField,\n ShellCommandWorkdirField,\n )\n help = help_text(\n \"\"\"\n Run a script as a test via the `test` goal, with all dependencies packaged/copied available in the chroot.\n\n Example BUILD file:\n\n experimental_test_shell_command(\n name=\"test\",\n tools=[\"test\"],\n command=\"test -r $CHROOT/some-data-file.txt\",\n execution_dependencies=[\"src/project/files:data\"],\n )\n\n The `command` may use either `{chroot}` on the command line, or the `$CHROOT`\n environment variable to get the root directory for where any dependencies are located.\n\n In contrast to the `experimental_run_shell_command`, this target is intended to run shell commands as tests\n and will only run them via the `test` goal.\n \"\"\"\n )\n\n\ndef rules():\n return [\n *collect_rules(),\n UnionRule(TargetFilesGeneratorSettingsRequest, ShellGeneratorSettingsRequest),\n ]\n","sub_path":"src/python/pants/backend/shell/target_types.py","file_name":"target_types.py","file_ext":"py","file_size_in_byte":21035,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"272805858","text":"import json\n\nfrom bm_instance_agent.common import utils\nfrom bm_instance_agent import exception\n\n\nclass Base(object):\n \"\"\" Construct obj from req body\n \"\"\"\n\n k_v_mapping = {}\n\n allowed_keys = []\n\n def __init__(self):\n for v in self.k_v_mapping.values():\n setattr(self, v, None)\n\n @staticmethod\n def body(req):\n b_data = req.get('body', {})\n if isinstance(b_data, str):\n b_data = json.loads(b_data)\n return b_data\n\n def construct(self, data):\n for k in self.allowed_keys:\n setattr(self, k, data.get(k))\n\n def to_json(self):\n return {k: getattr(self, k) for k in self.allowed_keys}\n\n\nclass BmInstanceObj(Base):\n \"\"\" Construct a bm instance obj from req body\n\n Bm instance part of req::\n {\n 'bmInstance': {\n 'uuid': 'uuid',\n 'provisionIpAddress': '192.168.101.10',\n 'provisionNicMac': 'aa:bb:cc:dd:ee:ff'\n }\n }\n \"\"\"\n\n allowed_keys = ['uuid', 'provision_ip', 'provision_mac']\n\n @classmethod\n def from_json(cls, bm_instance):\n obj = cls()\n obj.construct(bm_instance)\n\n return obj\n\n\nclass VolumeObj(Base):\n \"\"\" Construct a volume obj from req body\n\n Volume part of req::\n {\n 'volume': {\n 'uuid': 'uuid',\n 'primaryStorageType': 'NFS',\n 'type': 'Data/Sys',\n 'path': '/path/to/nfs/qcow2/volume',\n 'format': 'qcow2',\n 'deviceId': 2\n }\n }\n \"\"\"\n\n allowed_keys = ['uuid', 'device_id']\n\n @classmethod\n def from_json(cls, volume):\n obj = cls()\n obj.construct(volume)\n return obj\n\n\nclass PortObj(Base):\n \"\"\" Construct a Port obj from req body\n\n A port example::\n {\n 'mac': 'aa:bb:cc:dd:ee:ff',\n 'ipAddress': '10.0.120.10',\n 'netmask': '255.255.255.0',\n 'gateway': '10.0.120.1',\n 'vlanId': '1024',\n 'defaultRoute': True\n }\n\n `nextDefaultRoutePort` only used during port detach.\n \"\"\"\n\n allowed_keys = ['mac', 'ip_address', 'netmask', 'gateway',\n 'default_route', 'iface_name', 'vlan_id']\n\n @classmethod\n def from_json(cls, port):\n obj = cls()\n obj.construct(port)\n\n local_ifaces = utils.get_interfaces()\n if obj.mac not in local_ifaces:\n raise exception.NewtorkInterfaceNotFound(mac=obj.mac,\n vlan_id=obj.vlan_id)\n # NOTE(ya.wang) For vlan nic, the name is 'iface.vlan_id', therefore\n # try to split it.\n iface_name = local_ifaces.get(obj.mac).split('.')[0]\n if obj.vlan_id:\n iface_name = '{iface_name}.{vlan_id}'.format(\n iface_name=iface_name, vlan_id=obj.vlan_id)\n setattr(obj, 'iface_name', iface_name)\n\n return obj\n\n\nclass NetworkObj(Base):\n \"\"\" Construct a network obj from req body\n\n single port req example::\n {\n 'port': {\n 'mac': '52:54:00:23:f1:c0',\n 'ipAddress': '10.0.120.10',\n 'netmask': '255.255.255.0',\n 'gateway': '10.0.120.1',\n 'vlanId': '1024',\n 'defaultRoute': True\n }\n }\n\n multi ports req example::\n {\n 'ports': [\n {\n 'mac': '52:54:00:23:a1:c0',\n 'ipAddress': '10.0.120.10',\n 'netmask': '255.255.255.0',\n 'gateway': '10.0.120.1',\n 'vlanId': '1024',\n 'defaultRoute': True\n },\n {\n 'mac': '52:54:00:e5:c3:bf',\n 'ipAddress': '10.0.130.10',\n 'netmask': '255.255.255.0',\n 'gateway': '10.0.130.1',\n 'vlanId': '1024',\n 'defaultRoute': False\n }\n ]\n }\n\n \"\"\"\n\n @classmethod\n def from_json(cls, req):\n if not req:\n return None\n\n obj = cls()\n setattr(obj, 'default_gw_addr', '')\n setattr(obj, 'ports', [])\n\n ports = req if isinstance(req, list) else [req]\n for port_dict in ports:\n obj.ports.append(PortObj.from_json(port_dict))\n\n if port_dict.get('default_route'):\n obj.default_gw_addr = port_dict.get('gateway')\n return obj\n\n\nclass HeaderObj(Base):\n \"\"\" Construct a request header obj from req headers\n\n A req headers example::\n {\n 'taskuuid': '4dca1e5c-6b25-498d-b89e-99c55b32bd81',\n 'callbackurl': 'mn callback url',\n 'Gateway-Callback-Uri': 'The callback url which proxy by gw nginx'\n }\n\n If callbackurl and Gateway-Callback-Uri both exist, use\n Gateway-Callback-Uri\n \"\"\"\n\n allowed_keys = ['task_uuid', 'callback_url']\n\n @classmethod\n def from_headers(cls, headers):\n obj = cls()\n\n setattr(obj, 'task_uuid', headers.get('taskuuid'))\n\n if 'Gateway-Callback-Uri' in headers:\n setattr(obj, 'callback_url', headers.get('Gateway-Callback-Uri'))\n else:\n setattr(obj, 'callback_url', headers.get('callbackurl'))\n\n return obj\n","sub_path":"bm-instance-agent/bm_instance_agent/objects.py","file_name":"objects.py","file_ext":"py","file_size_in_byte":5131,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"65119796","text":"from igramscraper.instagram import Instagram\n\ninstagram = Instagram()\n\n# authentication supported\ninstagram.with_credentials('', '')\ninstagram.login()\n\n#Getting an account by id\naccount = instagram.get_account('bluck')\n\n# Available fields\n'''print('Account info:')\nprint('Id: ', account.identifier)\nprint('Username: ', account.username)\nprint('Full name: ', account.full_name)\nprint('Biography: ', account.biography)\n\nprint('External Url: ', account.external_url)\nprint('Number of published posts: ', account.media_count)\nprint('Number of followers: ', account.followed_by_count)\nprint('Number of follows: ', account.follows_count)\nprint('Is private: ', account.is_private)\nprint('Is verified: ', account.is_verified)'''\n\nfollowers = instagram.get_followers(account.identifier, 90, 90, delayed=True)\nfor follower in followers['accounts']:\n print('bluck ', follower.username)\n\naccount = instagram.get_account('erick.rojas.988')\nfollowers = instagram.get_followers(account.identifier, 90, 90, delayed=True)\nfor follower in followers['accounts']:\n print('eric ', follower.username)\n\n\n\n\n# or simply for printing use \n#print(account)","sub_path":"insta/crawltwo.py","file_name":"crawltwo.py","file_ext":"py","file_size_in_byte":1142,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"426117977","text":"import os\nimport numpy as np\nfrom rpeakdetection.rpeak_detector import RPeakDetector\nrpd = RPeakDetector()\nevaluation_width = 36\necg_folder = \"../data/ecg/mitdb/\"\npeaks_folder = \"../data/peaks/pan_tompkins/\"\nprecisions = list()\nrecalls = list()\nfor name in os.listdir(peaks_folder):\n peaks = list()\n file = open(peaks_folder + name, \"r\")\n name = name.replace(\".tsv\", \"\")\n for line in file:\n peak = line.replace(\"\\n\", \"\")\n peaks.append(int(peak))\n precision, recall = rpd.evaluate(peaks, ecg_folder + name, evaluation_width )\n precisions.append(precision)\n recalls.append(recall)\nprint(\"av prec\")\nprint(np.mean(precisions))\nprint(\"av recall\")\nprint(np.mean(recalls))","sub_path":"rpeakdetection/pan_tompkins.py","file_name":"pan_tompkins.py","file_ext":"py","file_size_in_byte":700,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"62010028","text":"\n\nfrom xai.brain.wordbase.verbs._subside import _SUBSIDE\n\n#calss header\nclass _SUBSIDES(_SUBSIDE, ):\n\tdef __init__(self,): \n\t\t_SUBSIDE.__init__(self)\n\t\tself.name = \"SUBSIDES\"\n\t\tself.specie = 'verbs'\n\t\tself.basic = \"subside\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/verbs/_subsides.py","file_name":"_subsides.py","file_ext":"py","file_size_in_byte":245,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"135700011","text":"import sqlite3\n\ndbpath = \"test07.sqlite\"\nconn = sqlite3.connect(dbpath)\n\n# pricelist_head = [\"Code\",\"Name\",\"Market\",\"Category\",\"Dealunit\",\"255orNot\",\"Start\",\"Max\",\"Min\",\"End\"]\n\ncur = conn.cursor()\ncur.execute(\"DROP TABLE IF EXISTS items\")\ncur.execute(\"\"\"\nCREATE TABLE items (\n item_id INTEGER PRIMARY KEY,\n date TEXT,\n code TEXT,\n name TEXT,\n market TEXT,\n category TEXT,\n dealunit TEXT,\n nikkei TEXT,\n start TEXT,\n max TEXT,\n min TEXT,\n end TEXT)\n \"\"\")\nconn.commit()\n\nfilename = \"test04_output_20180425.csv\"\ndate = filename.strip(\".csv\")[-8:]\nfp = open(filename,\"r\")\nflag = 0\n\nfor line in fp.readlines():\n if flag == 0:\n flag = 1\n continue\n data = line.strip(\"\\n\").split(\",\")\n data.insert(0,date)\n# print(data)\n cur = conn.cursor()\n# data = [[\"Mango\", 770], [\"Kiwi\", 400], [\"Grape\", 800],\n# [\"Peach\", 940], [\"Persimmon\", 700], [\"Banana\", 400]]\n cur.execute(\n \"INSERT INTO items(date, code, name, market, category, dealunit, nikkei, start, max, min, end) VALUES (?,?,?,?,?,?,?,?,?,?,?)\",\n data)\n conn.commit()\n\ncur = conn.cursor()\ncur.execute(\"SELECT item_id, date, code, name, market, category, dealunit, nikkei, start, max, min, end FROM items\")\nitem_list = cur.fetchall()\nfor it in item_list:\n print(it)\n\n","sub_path":"test07.py","file_name":"test07.py","file_ext":"py","file_size_in_byte":1313,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"352262616","text":"import sys\nimport os\nimport subprocess\nimport picamera\nimport numpy as np\nfrom keras.applications.resnet50 import ResNet50\nfrom keras.preprocessing import image\nfrom keras.applications.resnet50 import preprocess_input, decode_predictions\n\ncamera = picamera.PiCamera()\ncamera.resolution = (224, 224)\n\nmodel = ResNet50(weights='imagenet')\ndevnull = open('os.devnull', 'w')\n\ni = 1\nwhile True:\n camera.capture(\"img.jpg\")\n img = image.load_img(\"img.jpg\", target_size=(224, 224))\n x = image.img_to_array(img)\n x = np.expand_dims(x, axis=0)\n x = preprocess_input(x)\n\n pred = model.predict(x)\n word = decode_predictions(pred)[0][0][1].replace('_',' ')\n word2 = decode_predictions(pred)[0][1][1].replace('_',' ')\n speak = \"Okay I got it. I believe I'm looking at some kind of {} or {}\".format(word, word2)\n print(speak)\n os.rename('img.jpg', 'outputs/resnet/{}-{}-{}.jpg'.format(i,word, word2))\n subprocess.run(['pico2wave', '-w', 'outputs/resnet/{}-result.wav'.format(i), \"{}\".format(speak)], \n stdout=devnull, stderr=subprocess.STDOUT)\n subprocess.call(['aplay','outputs/resnet/{}-result.wav'.format(i)])\n print()\n i += 1","sub_path":"image-classification/resnet-classify.py","file_name":"resnet-classify.py","file_ext":"py","file_size_in_byte":1177,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"250844207","text":"from django import forms\nfrom django.contrib import admin\nfrom django.db import models\n\nfrom users.models import YamdbUser\n\n\n@admin.register(YamdbUser)\nclass YamdbUserAdmin(admin.ModelAdmin):\n list_display = ('pk', 'username', 'email', 'first_name', 'last_name',\n 'role', 'is_active')\n search_fields = ('email', 'username', 'first_name', 'last_name',)\n list_filter = ('role',)\n empty_value_display = '-not filled-'\n list_display_links = ('pk', 'email',)\n date_hierarchy = 'last_login'\n\n fieldsets = (\n (None, {\n 'fields': ('first_name', 'last_name', 'username', 'email', 'bio',)\n }),\n ('Advanced options', {\n 'classes': ('collapse',),\n 'fields': ('role', 'date_joined', 'last_login',\n 'is_active', 'is_staff', 'is_superuser'),\n }),\n )\n formfield_overrides = {\n models.TextField: {'widget': forms.Textarea},\n }\n","sub_path":"users/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":949,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"9838986","text":"import tkinter as tkr\nimport time\nimport random\n\ncanvas_size=600\nball_diameter=30\nball_radius=ball_diameter/2\ndist_threshold=1\n\ntk=tkr.Tk()\ntk.title(\"Assignment 1.3 - IRM2017008\")\ncanvas=tkr.Canvas(tk,width=canvas_size,height=canvas_size)\ncanvas.grid()\n\nfinal_points=[]\nfor i in range(3):\n final_x=random.randint(0,canvas_size-ball_diameter)\n final_y=random.randint(0,canvas_size-ball_diameter)\n final_points.append([final_x,final_y])\n\n\ninitial_points=[]\ndestination_index=[]\nfor i in range(14):\n init_x=random.randint(0,canvas_size-ball_diameter)\n init_y=random.randint(0,canvas_size-ball_diameter)\n index1=random.randint(0,2)\n destination_index.append(index1)\n final_x=final_points[index1][0]\n if(init_x==final_x):\n i-=1\n continue\n initial_points.append([init_x,init_y])\n\nprint(destination_index)\n\n#ball=canvas.create_oval(init_x,init_y,init_x+ball_diameter,init_y+ball_diameter,fill=\"yellow\")\nballs=[]\nslopes=[]\nvelocity=[]\npaths=[]\nsigns=[]\nfor i in range(14):\n init_x=initial_points[i][0]\n init_y=initial_points[i][1]\n \n final_x=final_points[destination_index[i]][0]\n final_y=final_points[destination_index[i]][1]\n \n ball=canvas.create_oval(init_x,init_y,init_x+ball_diameter,init_y+ball_diameter,fill=\"yellow\")\n balls.append(ball)\n \n slope=(final_y-init_y)/(final_x-init_x)\n slopes.append(slope)\n if init_xfinal_x:\n x_sign=-1\n if init_y>final_y:\n y_sign=-1\n signs.append([x_sign,y_sign])\n \n pi_x=init_x+ball_radius\n pi_y=init_y+ball_radius\n pf_x=final_x+ball_radius\n pf_y=final_y+ball_radius\n path=canvas.create_line(pi_x,pi_y,pf_x,pf_y);\n paths.append(path)\n \n\n\"\"\"\ninitial_ball=canvas.create_oval(init_x,init_y,init_x+ball_diameter,init_y+ball_diameter,fill=\"light blue\")\n\"\"\"\nfinal_balls=[]\nfor i in range(3):\n final_x=final_points[i][0]\n final_y=final_points[i][1]\n final_ball=canvas.create_oval(final_x,final_y,final_x+ball_diameter,final_y+ball_diameter,fill=\"light blue\")\n final_balls.append(final_ball)\n\n\ncounter=0\nreached=[]\nwhile True:\n for i in range(14):\n if(i in reached):\n continue\n ball=balls[i]\n x=velocity[i][0]\n y=velocity[i][1]\n canvas.move(ball,x,y)\n final_x=final_points[destination_index[i]][0]\n final_y=final_points[destination_index[i]][1]\n pos=canvas.coords(ball)\n \n \n '''\n #Stopping Condition 1 for Ball\n dist1=abs(pos[1]-final_y)\n dist2=abs(pos[0]-final_x)\n if(dist1final_x):\n cur_x_sign=-1\n if(pos[1]>final_y):\n cur_y_sign=-1\n if(x_sign!=cur_x_sign or y_sign!=cur_y_sign):\n print(i,\" reached Destination !\")\n reached.append(i)\n counter+=1\n ''' \n \n final_ball_pos=canvas.coords(final_balls[destination_index[i]])\n if(pos[0]==final_ball_pos[0] or pos[1]==final_ball_pos[1] or pos[2]==final_ball_pos[2] or pos[3]==final_ball_pos[3]):\n print(i,\" reached Destination !\")\n reached.append(i)\n counter+=1\n \n \n if(counter>=14):\n print(\"HERE\")\n break\n tk.update()\n time.sleep(0.001)\n pass\n\ntk.mainloop()","sub_path":"Assignment_1.3.py","file_name":"Assignment_1.3.py","file_ext":"py","file_size_in_byte":3730,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"300058820","text":"from pandas import *\nfrom ggplot import *\n\ndef plot_weather_data(turnstile_weather):\n '''\n plot_weather_data is passed a dataframe called turnstile_weather.\n Use turnstile_weather along with ggplot to make another data visualization\n focused on the MTA and weather data we used in Project 3.\n\n Make a type of visualization different than what you did in the previous exercise.\n Try to use the data in a different way (e.g., if you made a lineplot concerning\n ridership and time of day in exercise #1, maybe look at weather and try to make a\n histogram in this exercise). Or try to use multiple encodings in your graph if\n you didn't in the previous exercise.\n\n You should feel free to implement something that we discussed in class\n (e.g., scatterplots, line plots, or histograms) or attempt to implement\n something more advanced if you'd like.\n\n Here are some suggestions for things to investigate and illustrate:\n * Ridership by time-of-day or day-of-week\n * How ridership varies by subway station (UNIT)\n * Which stations have more exits or entries at different times of day\n (You can use UNIT as a proxy for subway station.)\n\n If you'd like to learn more about ggplot and its capabilities, take\n a look at the documentation at:\n https://pypi.python.org/pypi/ggplot/\n\n You can check out the link\n https://www.dropbox.com/s/meyki2wl9xfa7yk/turnstile_data_master_with_weather.csv\n to see all the columns and data points included in the turnstile_weather\n dataframe.\n\n However, due to the limitation of our Amazon EC2 server, we are giving you a random\n subset, about 1/3 of the actual data in the turnstile_weather dataframe.\n '''\n #find ten stations with most number of entries\n data_units = turnstile_weather.groupby('UNIT').sum()\n data_units = data_units.sort_index(by=['ENTRIESn_hourly'], ascending = False)\n data_units = data_units[0:10]\n\n data_plot = turnstile_weather[turnstile_weather['UNIT'].isin(data_units.index)]\n data_plot = data_plot[['UNIT', 'ENTRIESn_hourly', 'rain']]\n data_plot = data_plot.groupby(['UNIT', 'rain']).sum().reset_index()\n plot = ggplot(data_plot, aes(x = data_plot.index, y = 'ENTRIESn_hourly', color = 'rain')) + geom_point(aes(size=30)) + scale_x_continuous(breaks=range(0,20), labels = ['R011', '', 'R012', '', 'R018', '', 'R022', '', 'R033', '', 'R046', '', 'R055', '', 'R084', '', 'R170', '', 'R179', '']) + xlab('Stations') + ylab('Total Entries') + ggtitle('Total number of entries at ten stations with most entries compared according to rain (Legend- Magenta: Rain, Cyan: No Rain)')\n return plot\n","sub_path":"P1/Problem Set 4/plot_weather_data2.py","file_name":"plot_weather_data2.py","file_ext":"py","file_size_in_byte":2651,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"243196303","text":"import sqlite3\nimport threading\n\n\nclass DataBase:\n def __init__(self, db_file):\n self.conn = sqlite3.connect(db_file, check_same_thread=False)\n self.mutex = threading.Lock()\n print(\"open database successfully\")\n\n def create_table(self):\n c = self.conn.cursor()\n c.execute(\"CREATE TABLE IF NOT EXISTS INFO \"\n \"(NAME CHAR(100) NOT NULL,\"\n \"TRACE CHAR(100) PRIMARY KEY NOT NULL,\"\n \"LENGTH INT NOT NULL,\"\n \"COVERAGE CHAR(1000));\")\n print(\"Table created successfully\")\n self.conn.commit()\n\n def store(self, names, trace):\n cmd = \"INSERT OR IGNORE INTO INFO (NAME, TRACE, LENGTH) values (\" \\\n \"\\'\" + names + \"\\',\\'\" + str(trace) + \"\\',\" + str(len(trace)) + \")\"\n try:\n if self.mutex.acquire(1):\n c = self.conn.cursor()\n c.execute(cmd)\n self.conn.commit()\n self.mutex.release()\n except Exception as e:\n print(\"store error %s\" % e)\n\n def collect(self):\n ids = []\n cmd = \"SELECT NAME, TRACE FROM INFO WHERE COVERAGE IS NULL\"\n try:\n if self.mutex.acquire(1):\n c = self.conn.cursor()\n cursor = c.execute(cmd)\n self.mutex.release()\n for row in cursor:\n ids.append(row)\n return ids\n except Exception as e:\n print(\"store error %s\" % e)\n\n def setCover(self, trace, coverage):\n cmd = \"UPDATE INFO SET COVERAGE =\\'\" + str(coverage) + \"\\' WHERE TRACE=\\'\" + str(trace) + \"\\'\"\n try:\n if self.mutex.acquire(1):\n c = self.conn.cursor()\n c.execute(cmd)\n self.conn.commit()\n self.mutex.release()\n except Exception as e:\n print(\"setCover error %s\" % e)\n\n def getCover(self, trace, name=None):\n if trace:\n cmd = \"SELECT COVERAGE FROM INFO WHERE TRACE=\\'\" + str(trace) + \"\\'\"\n elif name:\n cmd = \"SELECT COVERAGE FROM INFO WHERE NAME=\\'\" + name + \"\\'\"\n try:\n c = self.conn.cursor()\n cursor = c.execute(cmd)\n for row in cursor:\n return row[0]\n except Exception as e:\n print(\"getCover error %s\" % e)\n\n def delete(self, trace):\n cmd = \"DELETE FROM INFO WHERE TRACE=\\'\" + str(trace) + \"\\'\"\n try:\n if self.mutex.acquire(1):\n c = self.conn.cursor()\n c.execute(cmd)\n self.conn.commit()\n self.mutex.release()\n except Exception as e:\n print(\"delete error %s\" % e)\n\n def close(self):\n self.conn.close()","sub_path":"train/database.py","file_name":"database.py","file_ext":"py","file_size_in_byte":2786,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"116364122","text":"\"\"\"PocketStock URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/1.11/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.conf.urls import url, include\n 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))\n\"\"\"\nfrom django.conf.urls import url, include\nfrom django.contrib import admin\nfrom django.contrib.auth import views as auth_views\nfrom . import views, duo_auth\n\nurlpatterns = [\n url(r'^getDashBoardData/$', views.getDashBoardData, name='getDashboardData'),\n url(r'^publicforum/$', views.publicForum, name='publicForum'),\n url(r'^$', views.home, name='home'),\n url(r'insert/', views.insertData, name='ins'),\n url(r'getCompanies/', views.getCompanies, name='getCompanies'),\n url(r'searchResults/', views.searchResults, name='searchresults'),\n url(r'^admin/', admin.site.urls),\n url(r'^accounts/', include('django.contrib.auth.urls')),\n url(r'^accounts/signup', views.signup, name=\"signup\"),\n\n url(r'^oauth/', include('social_django.urls', namespace='social')),\n url(r'^login/$', auth_views.login, name='login'),\n url(r'^logout/$', auth_views.logout, name='logout'),\n\n url(r'^settings/$', views.settings, name='settings'),\n url(r'^settings/password/$', views.password, name='password'),\n\n url(r'^accounts/duo_login', duo_auth.login),\n url(r'^accounts/duo_logout/$', duo_auth.logout),\n url(r'^home/$', views.home, name='homepage'),\n\n url(r'^dashboard/$', views.registered_home, name='dashboard'),\n url(r'^prediction/$', views.predict, name='prediction'),\n url(r'^create_transaction/$', views.create_transaction, name='create_transaction'),\n url(r'^stockProfile/$', views.stockProfile, name='stockProfile'),\n url(r'^forum/', views.forumPage, name=\"forum\"),\n\n url(r'^chat/$', views.chat_room_direct, name='chat'),\n #url(r'^chat/new/$', views.new_room, name='new_room'),\n url(r'^chat/(?P

\\n

Reddit

'\n '\\n

\\n' % {'t': t})\n for folder in urls.keys():\n content += ('

%(n)s'\n '

\\n

\\n' % {'t': t, 'n': folder})\n for url in urls[folder]:\n content += ('

%s\\n'\n % (url[0], t, url[1]))\n content += '

\\n'\n content += '

\\n' * 3\n ifile = open('chrome-bookmarks.html', 'w')\n ifile.write(content)\n\n\ndef main():\n \"\"\"main func.\"\"\"\n parser = argparse.ArgumentParser(\n description=(\n 'Exports saved Reddit posts into a HTML file'\n 'that is ready to be imported into Google Chrome'\n )\n )\n parser.add_argument(\"-v\", \"--verbose\", help=\"increase output verbosity\",\n action=\"store_true\")\n args = parser.parse_args()\n\n # set logging config\n if args.verbose:\n logging.basicConfig(level=logging.DEBUG)\n\n # login\n r = praw.Reddit(user_agent='export saved 1.0')\n r.login(\n username=AccountDetails.REDDIT_USERNAME,\n password=AccountDetails.REDDIT_PASSWORD,\n disable_warning=True\n )\n logging.debug('Login succesful')\n\n # csv setting\n csv_fields = ['URL', 'Title', 'Selection', 'Folder']\n csv_rows = []\n delimiter = ','\n\n # filter saved item for link\n for idx, i in enumerate(r.user.get_saved(limit=None, time='all'), 1):\n logging.debug('processing {}#'.format(idx))\n if not hasattr(i, 'title'):\n i.title = i.link_title\n try:\n folder = str(i.subreddit)\n except AttributeError:\n folder = \"None\"\n csv_rows.append([i.permalink.encode('utf-8'), i.title.encode('utf-8'),None, folder])\n\n # write csv using csv module\n with open(\"export-saved.csv\", \"w\") as f:\n csvwriter = csv.writer(f, delimiter=delimiter, quoting=csv.QUOTE_MINIMAL)\n csvwriter.writerow(csv_fields)\n for row in csv_rows:\n csvwriter.writerow(row)\n logging.debug('csv written.')\n\n # convert csv to bookmark\n converter = Converter(\"export-saved.csv\")\n converter.convert()\n logging.debug('html written.')\n\n sys.exit(0)\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"export-saved.py","file_name":"export-saved.py","file_ext":"py","file_size_in_byte":3690,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"222021328","text":"import os\nimport numpy as np\nimport errno\nimport torchvision.utils as vutils\nfrom tensorboardX import SummaryWriter\nfrom IPython import display\nimport torch\nfrom matplotlib import pyplot as plt\n\nif torch.cuda.is_available():\n plt.switch_backend('agg')\nimport PIL, PIL.Image\n\n'''\n TensorBoard Data will be stored in './runs' path\n'''\n\nlowest = -1.0\nhighest = 1.0\n\n\nclass Logger:\n\n def __init__(self, model_name, data_name):\n self.model_name = model_name\n self.data_name = data_name\n\n self.comment = '{}_{}'.format(model_name, data_name)\n # self.data_subdir = '{}/{}'.format(model_name, data_name)\n self.data_subdir = '{}'.format(data_name)\n\n # TensorBoard\n self.writer = SummaryWriter(comment=self.comment)\n\n def log(self, d_error, g_error, epoch, n_batch, num_batches):\n\n var_class = torch.Tensor\n if type(d_error.data) == var_class:\n d_error = d_error.data.cpu().numpy()\n if type(g_error.data) == var_class:\n g_error = g_error.data.cpu().numpy()\n\n step = Logger._step(epoch, n_batch, num_batches)\n self.writer.add_scalar(\n '{}/D_error'.format(self.comment), d_error, step)\n self.writer.add_scalar(\n '{}/G_error'.format(self.comment), g_error, step)\n\n def log_images(self, images, relevance, num_images, epoch, n_batch, num_batches, format='NCHW', normalize=True):\n \"\"\"\n input images are expected in format (NCHW)\n \"\"\"\n relevance = visualize(relevance.cpu().numpy() if torch.cuda.is_available()\n else relevance.numpy(), heatmap)\n\n if type(images) == np.ndarray:\n images = torch.from_numpy(images)\n if type(relevance) == np.ndarray:\n relevance = torch.from_numpy(relevance)\n\n if format == 'NCHW':\n relevance = relevance.permute(0, 3, 1, 2)\n\n step = Logger._step(epoch, n_batch, num_batches)\n img_name = '{}/images{}'.format(self.comment, '')\n\n # concat images\n if images.size(1) == 1:\n images = images.repeat(1, 3, 1, 1)\n if torch.cuda.is_available():\n images = images.cuda()\n relevance = relevance.cuda()\n images = torch.cat((images, relevance))\n\n # Make horizontal grid from image tensor\n horizontal_grid = vutils.make_grid(\n images, normalize=normalize, scale_each=True, pad_value=1)\n # Make vertical grid from image tensor\n nrows = int(np.sqrt(num_images))\n grid = vutils.make_grid(\n images, nrow=nrows, normalize=True, scale_each=True, pad_value=1)\n\n # Add horizontal images to tensorboard\n self.writer.add_image(img_name, horizontal_grid, step)\n\n # Save plots\n self.save_torch_images(horizontal_grid, grid, epoch, n_batch)\n\n def save_torch_images(self, horizontal_grid, grid, epoch, n_batch, plot_horizontal=True):\n out_dir = './output/{}'.format(self.data_subdir)\n Logger._make_dir(out_dir)\n\n # Plot and save horizontal\n fig = plt.figure(figsize=(32, 16), facecolor='white')\n if torch.cuda.is_available():\n horizontal_grid = horizontal_grid.cpu()\n plt.imshow(np.moveaxis(horizontal_grid.numpy(), 0, -1))\n plt.axis('off')\n if plot_horizontal:\n display.display(plt.gcf())\n self._save_images(fig, epoch, n_batch, 'hori')\n plt.close()\n\n # Save squared\n # fig = plt.figure()\n # plt.imshow(np.moveaxis(grid.numpy(), 0, -1))\n # plt.axis('off')\n # self._save_images(fig, epoch, n_batch)\n # plt.close()\n\n def _save_images(self, fig, epoch, n_batch, comment=''):\n out_dir = './output/{}'.format(self.data_subdir)\n Logger._make_dir(out_dir)\n fig.savefig('{}/{}_epoch_{}_batch_{}.png'.format(out_dir, comment, epoch, n_batch))\n\n @staticmethod\n def display_status(epoch, num_epochs, n_batch, num_batches, d_error, g_error, d_pred_real, d_pred_fake):\n\n var_class = torch.Tensor\n if type(d_error.data) == var_class:\n d_error = d_error.detach().cpu().item()\n if type(g_error.data) == var_class:\n g_error = g_error.detach().cpu().item()\n if type(d_pred_real.data) == var_class:\n d_pred_real = d_pred_real.data\n if type(d_pred_fake.data) == var_class:\n d_pred_fake = d_pred_fake.data\n\n print('Epoch: [{}/{}], Batch Num: [{}/{}]'.format(\n epoch, num_epochs, n_batch, num_batches)\n )\n print('Discriminator Loss: {:.4f}, Generator Loss: {:.4f}'.format(d_error, g_error))\n print('D(x): {:.4f}, D(G(z)): {:.4f} \\n'.format(d_pred_real.mean(), d_pred_fake.mean()))\n\n def save_models(self, generator, discriminator, epoch):\n out_dir = './data/models/{}'.format(self.data_subdir)\n Logger._make_dir(out_dir)\n torch.save(generator.state_dict(),\n '{}/G_epoch_{}'.format(out_dir, epoch))\n torch.save(discriminator.state_dict(),\n '{}/D_epoch_{}'.format(out_dir, epoch))\n\n def close(self):\n self.writer.close()\n\n # Private Functionality\n\n @staticmethod\n def _step(epoch, n_batch, num_batches):\n return epoch * num_batches + n_batch\n\n @staticmethod\n def _make_dir(directory):\n try:\n os.makedirs(directory)\n except OSError as e:\n if e.errno != errno.EEXIST:\n raise\n\n\n# --------------------------------------\n# Color maps ([-1,1] -> [0,1]^3)\n# --------------------------------------\n\ndef heatmap(x):\n x = x[..., np.newaxis]\n\n # positive relevance\n hrp = 0.9 - np.clip(x - 0.3, 0, 0.7) / 0.7 * 0.5\n hgp = 0.9 - np.clip(x - 0.0, 0, 0.3) / 0.3 * 0.5 - np.clip(x - 0.3, 0, 0.7) / 0.7 * 0.4\n hbp = 0.9 - np.clip(x - 0.0, 0, 0.3) / 0.3 * 0.5 - np.clip(x - 0.3, 0, 0.7) / 0.7 * 0.4\n\n # negative relevance\n hrn = 0.9 - np.clip(-x - 0.0, 0, 0.3) / 0.3 * 0.5 - np.clip(-x - 0.3, 0, 0.7) / 0.7 * 0.4\n hgn = 0.9 - np.clip(-x - 0.0, 0, 0.3) / 0.3 * 0.5 - np.clip(-x - 0.3, 0, 0.7) / 0.7 * 0.4\n hbn = 0.9 - np.clip(-x - 0.3, 0, 0.7) / 0.7 * 0.5\n\n r = hrp * (x >= 0) + hrn * (x < 0)\n g = hgp * (x >= 0) + hgn * (x < 0)\n b = hbp * (x >= 0) + hbn * (x < 0)\n\n return np.concatenate([r, g, b], axis=-1)\n\n\ndef graymap(x):\n x = x[..., np.newaxis]\n return np.concatenate([x, x, x], axis=-1) * 0.5 + 0.5\n\n\n# --------------------------------------\n# Visualizing data\n# --------------------------------------\n\ndef visualize(x, colormap):\n N = len(x)\n assert (N <= 16)\n x = colormap(x / np.abs(x).max())\n\n # Create a mosaic and upsample\n x = x.reshape([N, x.shape[2], x.shape[3], 3])\n return x\n # x = np.pad(x, ((0, 0), (0, 0), (2, 2), (2, 2), (0, 0)), 'constant', constant_values=1)\n # x = x.transpose([0, 2, 1, 3, 4]).reshape([1 * 32, N * 32, 3])\n # x = np.kron(x, np.ones([2, 2, 1]))\n # PIL.Image.fromarray((x * 255).astype('byte'), 'RGB').save('./data/images/VGAN/MNIST/' + name)\n","sub_path":"WassersteinGAN-master/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":7059,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"128451989","text":"import json\n\nclass VIST:\n def __init__(self, sis_file = None, dii_file= None):\n if sis_file != None:\n sis_dataset = json.load(open(sis_file, 'r'))\n self.LoadAnnotations(sis_dataset)\n else: exit('sis not found, terminating')\n \n if dii_file != None:\n dii_dataset = json.load(open(dii_file, 'r'))\n self.LoadDii(dii_dataset)\n else: exit('dii not found, terminating')\n\n\n def LoadAnnotations(self, sis_dataset = None):\n images = {}\n stories = {}\n\n if 'images' in sis_dataset:\n for image in sis_dataset['images']:\n images[image['id']] = image\n\n if 'annotations' in sis_dataset:\n annotations = sis_dataset['annotations']\n for annotation in annotations:\n story_id = annotation[0]['story_id']\n stories[story_id] = stories.get(story_id, []) + [annotation[0]]\n\n self.images = images # images = {imageid: imageinstance(title, tags, id... etc)}\n self.stories = stories # stories = {story_id: [storyinstance0,1,2,3,4]} each instance contain photo_flickr_id, text, original_text \n \n #self.imagetags = self.images.values()[i]['tags']\n #self.imagetitles = self.images.values()[i]['title']\n #self.storytext = self.stories['story_id'][i]['text']\n #self.storyoriginal = self.stories['story_id'][i]['original_text']\n \n def LoadDii(self, dii_dataset):\n descs = {} \n if 'annotations' in dii_dataset:\n annotations = dii_dataset['annotations']\n for annotation in annotations:\n imgid = annotation[0]['photo_flickr_id']\n description = annotation[0]['text']\n descs[imgid] = description\n self.descs = descs # {imgid: description string }\n\n # need to be written\n\n","sub_path":"vist.py","file_name":"vist.py","file_ext":"py","file_size_in_byte":1881,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"194353137","text":"# Libraries\n# Standard library\nimport random\nimport matplotlib.pyplot as plt\n\n# Third-party libraries\nimport numpy as np\n\n\nclass Network(object):\n def __init__(self, sizes):\n self.sizes = sizes\n np.random.seed(123)\n self.weights = [np.random.rand(i, o)\n for i, o in zip(sizes[1:], sizes[:-1])]\n\n self.biases = [np.random.rand(d, 1)\n for d in sizes[1:]]\n\n def SGD(self, training_data, epochs, mini_batch_size, eta, test_data=None):\n cost = []\n for ep in range(epochs):\n print(\"Epoch {} complete\".format(ep))\n np.random.seed(123)\n #random.shuffle(training_data)\n\n for k in range(0, len(training_data), mini_batch_size):\n mini_batch = training_data[k:k+mini_batch_size]\n self.update_mini_batch(mini_batch, eta)\n print(\"Mini-Batch {} complete\".format(k))\n\n cost.append(sum(np.array(calculate_cost(\n training_data, self.weights, self.biases)).flatten()))\n plt.plot(cost)\n plt.show()\n\n def update_mini_batch(self, mini_batch, eta):\n nuble_Ws = [np.zeros(w.shape) for w in self.weights]\n nuble_Bs = [np.zeros(b.shape) for b in self.biases]\n\n for x, y in mini_batch:\n bnws, bnbs = self.backprop(x, y)\n nuble_Ws = [nws+bnw for nws, bnw in zip(nuble_Ws, bnws)]\n nuble_Bs = [nbs+bbw for nbs, bbw in zip(nuble_Bs, bnbs)]\n\n self.weights = [w-(eta/len(mini_batch)*nw)\n for w, nw in zip(self.weights, nuble_Ws)]\n self.biases = [b-(eta/len(mini_batch)*nb)\n for b, nb in zip(self.biases, nuble_Bs)]\n\n def backprop(self, x, y):\n derivative_by_w = [np.zeros_like(w) for w in self.weights]\n derivative_by_b = [np.zeros_like(b) for b in self.biases]\n zz = []\n aa = [x]\n\n for w, b in zip(self.weights, self.biases):\n z = w@aa[-1] + b\n a = sigmoid(z)\n zz.append(z)\n aa.append(a)\n\n d = (aa[-1]-y)*sigmoid_prime(zz[-1])\n derivative_by_b[-1] += d\n derivative_by_w[-1] += d@aa[-2].T\n\n for l in reversed(range(1, len(self.sizes)-1)):\n d = self.weights[l].T@d*sigmoid_prime(zz[l-1])\n derivative_by_b[l-1] += d\n derivative_by_w[l-1] += d@aa[l-1].T\n\n return (derivative_by_w, derivative_by_b)\n\n\ndef calculate_cost(training, w, b):\n return sum([calculate_output(y, x, w, b) for x, y in training])/len(training)\n\n\ndef calculate_output(y, x, w, b):\n a = x\n for wl, bl in zip(w, b):\n a = sigmoid(wl@a+bl)\n return (y-a)**2\n\n\ndef sigmoid(z):\n return 1.0/(1.0+np.exp(-z))\n\n\ndef sigmoid_prime(z):\n return sigmoid(z)*(1-sigmoid(z))\n","sub_path":"src/re_network.py","file_name":"re_network.py","file_ext":"py","file_size_in_byte":2805,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"77679777","text":"import numpy as np\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nfrom gurobipy.gurobipy import Model, GRB, LinExpr, Var\nfrom pcst.formulation import PCST\nfrom pcst.network import Network, Type, Edge\nfrom pandas import DataFrame, Series, read_csv\n\nbeta = 8\n\nkinases_es = {'A': 0.6, 'B': 0.4, 'E': 0.4}\nsites_fc = {'C_S2': 0.7, 'D_S2': 0.6, 'E_S2': 0.3}\n\nks_network = DataFrame([\n ('A', 'C', 'C_S1'),\n ('A', 'C', 'C_S2'),\n ('B', 'C', 'C_S2'),\n ('B', 'D', 'D_S2'),\n ('C', 'E', 'E_S2'),\n ('C', 'F', 'F_S1')\n], columns=['kinase', 'substrate', 'site'])\n\nsites, kinases, substrates = set(ks_network['site']), set(ks_network['kinase']), set(ks_network['substrate'])\nin_edges, out_edges = set(ks_network['kinase'] + '_' + ks_network['site']), set(ks_network['site'] + '_' + ks_network['substrate'])\n\nin_edges_costs = {edge: 1 / es for kinase, es in kinases_es.items() for edge in in_edges if edge.startswith(kinase)}\nout_edges_costs = {edge: 1 / fc for site, fc in sites_fc.items() for edge in out_edges if edge.startswith(site)}\n\n# Create problem\nlp = Model('KS')\n\n# Initialise nodes variables\nfor v in sites:\n lp.addVar(vtype=GRB.BINARY, name=v)\n\nfor v in kinases:\n lp.addVar(vtype=GRB.BINARY, name=v)\n\nfor v in substrates.difference(kinases):\n lp.addVar(vtype=GRB.BINARY, name=v)\n\n# Initialise edges variables\nfor edge in in_edges:\n lp.addVar(vtype=GRB.BINARY, name=edge)\n\nfor edge in out_edges:\n lp.addVar(vtype=GRB.BINARY, name=edge)\n\n# Update variables\nlp.update()\n\n# Initialise constraints\nfor site in sites:\n lhs = LinExpr([(1, lp.getVarByName(edge)) for edge in in_edges if edge.endswith(site)])\n lp.addConstr(lhs, GRB.EQUAL, lp.getVarByName(site))\n\nfor site in sites:\n for out_edge in out_edges:\n if out_edge.startswith(site):\n lp.addConstr(lp.getVarByName(out_edge), GRB.EQUAL, lp.getVarByName(site))\n\nfor kinase in kinases:\n for in_edge in in_edges:\n if in_edge.startswith(kinase):\n lp.addConstr(lp.getVarByName(kinase), GRB.GREATER_EQUAL, lp.getVarByName(in_edge))\n\nfor substrate in substrates:\n for out_edge in out_edges:\n if out_edge.endswith(substrate):\n lp.addConstr(lp.getVarByName(substrate), GRB.GREATER_EQUAL, lp.getVarByName(out_edge))\n\n# Initialise objective function\nobj = LinExpr()\n\nfor edge in in_edges:\n obj.addTerms(in_edges_costs[edge] if edge in in_edges_costs else 1, lp.getVarByName(edge))\n\nfor edge in out_edges:\n obj.addTerms(out_edges_costs[edge] if edge in out_edges_costs else 1, lp.getVarByName(edge))\n\nfor node in sites:\n obj.addTerms(-sites_fc[node] * beta if node in sites_fc else 0, lp.getVarByName(node))\n\nfor node in kinases:\n obj.addTerms(1e-6, lp.getVarByName(node))\n\nfor node in substrates:\n obj.addTerms(1e-6, lp.getVarByName(node))\n\nlp.setObjective(obj, GRB.MINIMIZE)\n\n# Optimise\nlp.optimize()\n\n{var.VarName: var.x for var in lp.getVars() if var.x != 0.0}","sub_path":"tests/pcst/example_4.py","file_name":"example_4.py","file_ext":"py","file_size_in_byte":2920,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"414550659","text":"#!usr/bin/evn python3\n\n#A、B手中的牌\nA = [2,4,1,2,5,6]\nhead_A = 0\ntail_A = len(A)\nB = [3,1,3,5,6,4]\nhead_B = 0\ntail_B = len(B)\n\n#桌上的牌\ndesk = []\n\n#桶\nflag = []\nfor i in range(10):\n flag.append(0)\n\n'''交替出牌,相同则取走'''\nwhile head_A != tail_A and head_B != tail_B:\n print(desk)\n this_A = A[head_A]\n if flag[this_A] > 0: #桌上有牌与此次出牌相同\n #取走相同牌及中间所夹所有\n A.append(this_A) #此次出牌\n tail_A += 1\n while desk[-1] != this_A:\n A.append(desk[-1])\n tail_A += 1\n flag[desk[-1]] -= 1\n desk.pop()\n A.append(desk[-1]) #桌上与此次相同的牌\n tail_A += 1\n flag[desk[-1]] -= 1\n desk.pop()\n else:\n flag[this_A] += 1\n desk.append(this_A)\n head_A += 1 #A队首后移\n print(\"A\",end=\"\")\n print(A[head_A:tail_A])\n this_B = B[head_B]\n if flag[this_B] > 0: \n B.append(this_B)\n tail_B += 1\n while desk[-1] != this_B:\n B.append(desk[-1])\n tail_B += 1\n flag[desk[-1]] -= 1\n desk.pop()\n B.append(desk[-1])\n tail_B += 1\n flag[desk[-1]] -= 1\n desk.pop()\n else:\n flag[this_B] += 1\n desk.append(this_B)\n head_B += 1\n print(\"B\",end=\"\")\n print(B[head_B:tail_B])\nif head_A == tail_A:\n print(\"B获胜\")\n print(\"B手中的牌是\",end=\":\")\n print(B[head_B:tail_B])\nelif head_B == tail_B:\n print(\"A获胜\")\n print(\"A手中的牌是\",end=\":\")\n print(A[head_A:tail_A])\nprint(\"桌上的牌为\",end=\":\")\nprint(desk)\n","sub_path":"array_list/cardgame.py","file_name":"cardgame.py","file_ext":"py","file_size_in_byte":1636,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"534058686","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[1]:\n\n\nimport pandas as pd\nimport numpy as np\n\n\n# In[2]:\n\n\ndata_preprocessed = pd.read_csv('C:/Users/USER/Downloads/The Data Science Course 2021 - All Resources/Part_8_Case_Study/S59_L443/Absenteeism-preprocessed.csv')\n\n\n# In[3]:\n\n\ndata_preprocessed.head()\n\n\n# In[4]:\n\n\ndata_preprocessed['Absenteeism Time in Hours'].median()\n\n\n# In[5]:\n\n\ntargets = np.where(data_preprocessed['Absenteeism Time in Hours'] > 3, 1, 0)\n\n\n# In[6]:\n\n\ntargets\n\n\n# In[7]:\n\n\ndata_preprocessed['Excessive Absenteeism'] = targets\n\n\n# In[8]:\n\n\ndata_preprocessed.head()\n\n\n# In[9]:\n\n\ntargets.sum()/targets.shape[0]\n\n\n# In[10]:\n\n\ndata_with_targets = data_preprocessed.drop(['Absenteeism Time in Hours','Day of the Week','Distance to Work','Daily Work Load Average'], axis=1)\n\n\n# In[11]:\n\n\ndata_with_targets is data_preprocessed\n\n\n# In[12]:\n\n\ndata_with_targets.head()\n\n\n# In[13]:\n\n\ndata_with_targets.shape\n\n\n# In[14]:\n\n\ndata_with_targets.iloc[:,0:14]\n\n\n# In[15]:\n\n\ndata_with_targets.iloc[:,:14]\n\n\n# In[16]:\n\n\nunscaled_inputs = data_with_targets.iloc[:,:-1]\n\n\n# In[17]:\n\n\n#from sklearn.preprocessing import StandardScaler\n\n#absenteeism_scaler = StandardScaler()\n\n\n# In[18]:\n\n\nfrom sklearn.base import BaseEstimator, TransformerMixin\nfrom sklearn.preprocessing import StandardScaler\n\nclass CustomScaler(BaseEstimator,TransformerMixin): \n \n def __init__(self,columns):\n self.scaler = StandardScaler()\n self.columns = columns\n self.mean_ = None\n self.var_ = None\n\n def fit(self, X, y=None):\n self.scaler.fit(X[self.columns], y)\n self.mean_ = np.mean(X[self.columns])\n self.var_ = np.var(X[self.columns])\n return self\n\n def transform(self, X, y=None, copy=None):\n init_col_order = X.columns\n X_scaled = pd.DataFrame(self.scaler.transform(X[self.columns]), columns=self.columns)\n X_not_scaled = X.loc[:,~X.columns.isin(self.columns)]\n return pd.concat([X_not_scaled, X_scaled], axis=1)[init_col_order]\n\n\n# In[19]:\n\n\nunscaled_inputs.columns.values\n\n\n# In[20]:\n\n\n#columns_to_scale = ['Month Value','Day of the Week', 'Transportation Expense', 'Distance to Work',\n # 'Age', 'Daily Work Load Average', 'Body Mass Index', 'Education','Children', 'Pet']\ncolumns_to_omit = ['Reason_1', 'Reason_2', 'Reason_3', 'Reason_4', ]\n\n\n# In[21]:\n\n\ncolumns_to_scale = [x for x in unscaled_inputs.columns.values if x not in columns_to_omit] \n\n\n# In[22]:\n\n\nabsenteeism_scaler = CustomScaler(columns_to_scale)\n\n\n# In[23]:\n\n\nabsenteeism_scaler.fit(unscaled_inputs)\n\n\n# In[24]:\n\n\nscaled_inputs = absenteeism_scaler.transform(unscaled_inputs)\n\n\n# In[25]:\n\n\nscaled_inputs\n\n\n# In[26]:\n\n\nscaled_inputs.shape\n\n\n# In[27]:\n\n\nfrom sklearn.model_selection import train_test_split\n\n\n# In[28]:\n\n\ntrain_test_split(scaled_inputs, targets)\n\n\n# In[29]:\n\n\nx_train, x_test, y_train, y_test, = train_test_split(scaled_inputs, targets, train_size =0.8, random_state = 20)\n\n\n# In[30]:\n\n\nprint(x_train.shape, y_train.shape)\n\n\n# In[31]:\n\n\nprint(x_test.shape, y_test.shape)\n\n\n# In[32]:\n\n\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn import metrics\n\n\n# In[33]:\n\n\nreg = LogisticRegression()\n\n\n# In[34]:\n\n\nreg.fit(x_train,y_train)\n\n\n# In[35]:\n\n\nreg.score(x_train,y_train)\n\n\n# In[36]:\n\n\n# Manually check the accuracy \n\n\n# In[37]:\n\n\nmodel_outputs = reg.predict(x_train)\nmodel_outputs\n\n\n# In[38]:\n\n\ny_train\n\n\n# In[39]:\n\n\nmodel_outputs == y_train\n\n\n# In[40]:\n\n\nnp.sum((model_outputs==y_train))\n\n\n# In[41]:\n\n\nmodel_outputs.shape[0]\n\n\n# In[42]:\n\n\nnp.sum((model_outputs==y_train)) / model_outputs.shape[0]\n\n\n# In[43]:\n\n\nreg.intercept_\n\n\n# In[44]:\n\n\nreg.coef_\n\n\n# In[45]:\n\n\nunscaled_inputs.columns.values\n\n\n# In[46]:\n\n\nfeature_name = unscaled_inputs.columns.values\n\n\n# In[47]:\n\n\nsummary_table = pd.DataFrame (columns=['Feature name'], data = feature_name)\n\nsummary_table['Coefficient']= np.transpose(reg.coef_)\n\nsummary_table\n\n\n# In[48]:\n\n\nsummary_table.index = summary_table.index + 1\nsummary_table.loc[0] = ['Intercept', reg.intercept_[0]]\nsummary_table = summary_table.sort_index()\nsummary_table\n\n\n# In[49]:\n\n\nsummary_table['Odds_ratio'] = np.exp(summary_table.Coefficient)\n\n\n# In[50]:\n\n\nsummary_table\n\n\n# In[51]:\n\n\nsummary_table.sort_values('Odds_ratio', ascending=False )\n\n\n# In[52]:\n\n\nreg.score(x_test,y_test)\n\n\n# In[53]:\n\n\npredicted_proba = reg.predict_proba(x_test)\npredicted_proba\n\n\n# In[55]:\n\n\npredicted_proba.shape\n\n\n# In[56]:\n\n\npredicted_proba[:,1]\n\n\n# In[57]:\n\n\nimport pickle\n\n\n# In[58]:\n\n\nwith open('model', 'wb') as file:\n pickle.dump(reg, file)\n\n\n# In[59]:\n\n\nwith open('scaler','wb') as file:\n pickle.dump(absenteeism_scaler, file)\n\n\n# In[ ]:\n\n\n\n\n","sub_path":"Case Study ML.py","file_name":"Case Study ML.py","file_ext":"py","file_size_in_byte":4638,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"10591084","text":"import os\r\nimport sys\r\n\r\nif __name__ == '__main__':\r\n if len(sys.argv) == 4:\r\n\r\n parent_folder_path = sys.argv[1]\r\n tv_show_name = sys.argv[2]\r\n number_of_seasons = sys.argv[3]\r\n\r\n try:\r\n if os.path.isdir(parent_folder_path):\r\n tv_show_folder = os.path.join(parent_folder_path, tv_show_name)\r\n\r\n os.mkdir(tv_show_folder)\r\n os.chdir(path=tv_show_folder)\r\n\r\n if number_of_seasons.isnumeric():\r\n #Creates folders for x seasons.\r\n for i in range(0, int(number_of_seasons)):\r\n os.mkdir(os.path.join(os.getcwd(), f'Season { i + 1 }'))\r\n\r\n with open(os.path.join(tv_show_folder, 'README.txt'), 'w') as f:\r\n f.write(f'Enjoy watching {tv_show_name}!\\nNote: In case you\\'re still wondering, yes, you can delete this file.')\r\n \r\n\r\n\r\n #Just in case something goes wrong.\r\n except FileExistsError as e: \r\n print(\"You attempted to create a folder that already exists...\\nBe careful next time.\")\r\n\r\n else:\r\n print('WRONG USAGE!')\r\n print('The correct usage is: python3 autoshow.py [PARENT FOLDER PATH] [TV SHOW NAME] [NUMBER OF SEASONS].')\r\n\r\n","sub_path":"autoshow.py","file_name":"autoshow.py","file_ext":"py","file_size_in_byte":1291,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"383758147","text":"\"\"\"\nProduce un piu csv uno per code list\ndove ogni riga presenta\nProject.crs:Project.recipient_id\ne il valore anno dopo anno di quella code list.\n\nCRSID | RECIPIENT | 2004 | ... | 2012\n\n\"\"\"\nimport csvkit\nfrom django.db.models import Count\nimport sys\n\nfrom openaid.projects.models import Project\n\nYEARS = [str(x) for x in range(2004, 2013)]\nDEFAULT_YEARS_VALUES = dict([(y, u'') for y in YEARS])\nFIELDS = ['crsid', 'recipient', 'agency'] + [str(x) for x in range(2004, 2013)]\n\ndef create_writer(name):\n f = open('%s.csv' % name, 'w')\n return f, csvkit.DictWriter(f, FIELDS)\n\n\ndef run():\n\n aid_file, aid_writer = create_writer('aid')\n aid_writer.writeheader()\n sector_file, sector_writer = create_writer('sector')\n sector_writer.writeheader()\n channel_file, channel_writer = create_writer('channel')\n channel_writer.writeheader()\n\n for i, project in enumerate(Project.objects.annotate(activity_count=Count('activity')).filter(activity_count__gt=1)):\n\n aids = {}\n sectors = {}\n channels = {}\n agency = ''\n\n for activity in project.activity_set.all():\n\n year = str(activity.year)\n\n aid = activity.aid_type.code if activity.aid_type else 'XXX'\n if year in aids:\n if aid not in aids[year]:\n aids[year] += '/%s' % aid\n else:\n aids[year] = aid\n sector = activity.sector.code if activity.sector else 'XXX'\n if year in sectors:\n if sector not in sectors[year]:\n sectors[year] += '/%s' % sector\n else:\n sectors[year] = sector\n channel = activity.channel.code if activity.channel else 'XXX'\n if year in channels:\n if channel not in channels[year]:\n channels[year] += '/%s' % channel\n else:\n channels[year] = channel\n\n agency = activity.agency.name if activity.agency else ''\n\n line = {\n 'crsid': project.crsid ,\n 'recipient': project.recipient.code,\n 'agency': agency,\n }\n line.update(DEFAULT_YEARS_VALUES)\n\n for codelist, writer in [(aids, aid_writer), (sectors, sector_writer), (channels, channel_writer)]:\n\n codelist_line = line.copy()\n codelist_line.update(codelist)\n writer.writerow(codelist_line)\n\n sys.stdout.write(\"\\rMulti activity project: %d\" % (i), ending='')\n sys.stdout.flush()\n\n aid_file.close()\n sector_file.close()\n channel_file.close()","sub_path":"project/scripts/csv_codelist_by_year.py","file_name":"csv_codelist_by_year.py","file_ext":"py","file_size_in_byte":2588,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"132116993","text":"import gymnasium as gym\nimport gym_explore\n\n\nenv = gym.make('escaper-v0', render_mode=\"human\", continuous=False)\nobs, info = env.reset()\nfor i in range(1000):\n obs, rew, term, trun, info = env.step(env.action_space.sample())\n print(obs, rew, term, trun, info)\n if term or trun:\n env.reset()\nenv.close()\n","sub_path":"test_env.py","file_name":"test_env.py","file_ext":"py","file_size_in_byte":319,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"600555434","text":"import json\n\nfrom django.http import HttpResponse, JsonResponse\nfrom django.shortcuts import render\n\n# Create your views here.\nfrom rest_framework.views import View, APIView\n\nfrom book.models import PeopleInfo\nfrom .people_serializer import PeopleSerializer\n\nfrom rest_framework.response import Response\n\n## TODO:1 类视图正常写法\nclass PeopleInfoView(View):\n\n filter_fields = ['id','name']\n\n def get(self, req):\n peoples = PeopleInfo.objects.all()\n # 对比两次 debug 讲解\n #问题1: step into, 对比 step into mycode\n #问题2: Step PeopleSerializer step over 不执行 init 吗\n #问题3: 进入后执行 Dispatch\n # 感觉并没有 通过 debug 看到了代码 一步一步 的完整执行过程\n # serializer = PeopleSerializer(instance=peoples, many=True)\n # data into\n people_list = []\n for people in peoples:\n people_list.append({\n 'name': people.name,\n 'id': people.id,\n 'book_name': people.book.name,\n 'description': people.description,\n # gender 在不使用序列化器的时候 返回 0,1 使用序列化器的时候 返回 男 女\n 'gender': people.gender\n })\n\n # return Response(data=serializer.data)\n return JsonResponse(data=people_list, safe=False)\n\n def post(self, request):\n # 获取数据\n json_str = request.body\n json_str = json_str.decode() # python3.6 无需执行此步\n req_dict = req_data = json.loads(json_str)\n print(req_data)\n # serializer = PeopleSerializer(data=req_data)\n # serializer.save()\n people = PeopleInfo.objects.create(\n name=req_data.get('name'),\n book_id=req_data.get('book')\n )\n return JsonResponse({\n 'name': people.name,\n 'pub_date': people.id\n }, safe=False)\n # return HttpResponse(req_dict.get('name'))\n #\n\n\n# 参数是正则命名匹配传过去的\nclass PeopleInfoDetail(View):\n\n def get(self, req, id):\n try:\n people = PeopleInfo.objects.get(pk=id)\n except PeopleInfo.DoesNotExist:\n # 返回这里柑橘不好\n return HttpResponse(status=400)\n return JsonResponse({\n 'name': people.name,\n 'id': people.id\n }, safe=False)\n\n def put(self, req, id):\n try:\n people = PeopleInfo.objects.get(pk=id)\n except PeopleInfo.DoesNotExist:\n return HttpResponse(status=400)\n params = json.loads(req.body.decode())\n name = params.get('name', people.name)\n people.name = name\n people.save()\n return JsonResponse({\n 'name': people.name,\n 'id': people.id,\n 'description': people.description,\n 'gender': people.gender\n }, status=200)\n\n def delete(self, req, id):\n try:\n people = PeopleInfo.objects.get(pk=id)\n except PeopleInfo.DoesNotExist:\n return HttpResponse(status=400)\n people.delete()\n # return JsonResponse(data='ok', status=204)\n return HttpResponse(status=204)\n\n\n\n","sub_path":"bookmanager_serializer/people/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3247,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"618801072","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Mar 18 17:59:39 2017\n\n@author: Arnab Ghosh\n\"\"\"\n\nimport pylab as plt\n\nmySamples = []\nmyLinear = []\nmyQuadritic = []\nmyCubic = []\nmyExponential = []\n\nfor i in range (0,30):\n mySamples.append(i)\n myLinear.append(i)\n myQuadritic.append(i**2)\n myCubic.append(i**3)\n myExponential.append(1.5**i)\n \nplt.figure('lin')\nplt.clf() # clear the frame\nplt.ylim(0,1000)\nplt.xlabel('sample points')\nplt.ylabel('linear function')\nplt.plot (mySamples, myLinear, 'b-', label=\"linear\", linewidth = 2.0)\nplt.legend(loc='upper left')\nplt.figure('quad')\nplt.clf() # clear the frame\nplt.ylim(0,1000)\nplt.plot (mySamples, myQuadritic, 'ro', label=\"quad\", linewidth = 3.0)\nplt.legend()\nplt.figure('cube')\nplt.clf() # clear the frame\nplt.plot (mySamples, myCubic, 'g^',label=\"cube\", linewidth = 4.0)\nplt.figure('expo')\nplt.clf() # clear the frame\nplt.yscale('log') # put a function for y axis instead of a regular linear scale\nplt.plot (mySamples, myExponential, 'r--', label=\"exp\", linewidth = 5.0)\n\n\nplt.figure('quad')\nplt.xlabel('sample points')\nplt.ylabel('quad function')\nplt.title(\"Quadritic\")\n","sub_path":"Programs/plot.py","file_name":"plot.py","file_ext":"py","file_size_in_byte":1135,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"595122019","text":"import matplotlib\nmatplotlib.use('Agg')\n\nimport subprocess\nimport os\nimport sys\nimport numpy as np\nfrom multiprocessing import Pool\n#import pdb\n\n#increase the maximum number of open files allowed\n#import resource\n#resource.setrlimit(resource.RLIMIT_NOFILE, (3000,-1))\n\nimport pyroms\nimport pyroms_toolbox\n\nfrom remap_bdry import remap_bdry\nfrom remap_bdry_uv import remap_bdry_uv\n\n'''\nlst_year = sys.argv[1:]\n\ndata_dir = '/import/AKWATERS/kshedstrom/HYCOM/Svalbard/data/'\ndst_dir='./bdry/'\n\nlst_file = []\n\nfor year in lst_year:\n lst = subprocess.getoutput('ls ' + data_dir + 'HYCOM_GLBy0.08_' + year + '_[01]*')\n# lst = subprocess.getoutput('ls ' + data_dir + 'HYCOM_GLBy0.08_' + year + '*')\n# lst = subprocess.getoutput('ls ' + data_dir + 'HYCOM_GLBy0.08_' + year + '_0*')\n# lst = subprocess.getoutput('ls ' + data_dir + 'HYCOM_GLBy0.08_' + year + '_0[4-9]*')\n lst = lst.split()\n lst_file = lst_file + lst\n\nprint('Build OBC file from the following file list:')\n\nprint(lst_file)\nprint(' ')\n\nsrc_grd_file = data_dir + 'HYCOM_GLBy0.08_2018_345.nc'\nsrc_grd = pyroms_toolbox.Grid_HYCOM.get_nc_Grid_HYCOM2(src_grd_file)\ndst_grd = pyroms.grid.get_ROMS_grid('ARCTIC4')\n'''\n\n\nimport os\n\n#file1=input(\"Enter the Godas full filename:\")\nfile1=(\"Godas_uvsshts_jan_2019_.nc\")\nprint(\"Build OBC file from the following file {}.\".format(file1))\n#directory=input(\"Enter Absolute Godas file path(Directory path):\")\nprint(\"os getcwd:\",os.getcwd())\ndirectory=os.getcwd()\ndst_dir=directory\nsrc_grd=pyroms_toolbox.Grid_HYCOM.get_nc_Grid_HYCOM2(directory+\"/\"+file1)\ndst_grd=pyroms.grid.get_ROMS_grid('GODASROMS')\nprint(\"Source grid:\",src_grd)\n\n\n\n#def do_file(file):\nzeta = remap_bdry(file1, 'SSH', src_grd, dst_grd, dst_dir=dst_dir)\ndst_grd2 = pyroms.grid.get_ROMS_grid('GODASROMS', zeta=zeta)\nremap_bdry(file1, 'temp', src_grd, dst_grd2, dst_dir=dst_dir)\nremap_bdry(file1, 'salt', src_grd, dst_grd2, dst_dir=dst_dir)\n# pdb.set_trace()\nremap_bdry_uv(file1, src_grd, dst_grd2, dst_dir=dst_dir)\n\nprint(\"#\"*45)\n # merge file\nbdry_file = dst_dir + file1.rsplit('/')[-1][:-3] + '_bdry_' + dst_grd.name + '.nc'\n\nout_file = dst_dir + file1.rsplit('/')[-1][:-3] + '_SSH_bdry_' + dst_grd.name + '.nc'\ncommand = ('ncks', '-a', '-O', out_file, bdry_file)\nsubprocess.check_call(command)\nos.remove(out_file)\nout_file = dst_dir + file1.rsplit('/')[-1][:-3] + '_temp_bdry_' + dst_grd.name + '.nc'\ncommand = ('ncks', '-a', '-A', out_file, bdry_file)\nsubprocess.check_call(command)\nos.remove(out_file)\nout_file = dst_dir + file1.rsplit('/')[-1][:-3] + '_salt_bdry_' + dst_grd.name + '.nc'\ncommand = ('ncks', '-a', '-A', out_file, bdry_file)\nsubprocess.check_call(command)\nos.remove(out_file)\nout_file = dst_dir + file1.rsplit('/')[-1][:-3] + '_u_bdry_' + dst_grd.name + '.nc'\ncommand = ('ncks', '-a', '-A', out_file, bdry_file)\nsubprocess.check_call(command)\nos.remove(out_file)\nout_file = dst_dir + file1.rsplit('/')[-1][:-3] + '_v_bdry_' + dst_grd.name + '.nc'\ncommand = ('ncks', '-a', '-A', out_file, bdry_file)\nsubprocess.check_call(command)\nos.remove(out_file)\nprint(\"current working directory:\",os.getcwd())\nprint(\"All task done !!!\")\n\n#processes = 4\n#p = Pool(processes)\n#results = p.map(do_file, lst_file)\n","sub_path":"may_be_helpful_files/Godas_to_Roms_boundary_file.py","file_name":"Godas_to_Roms_boundary_file.py","file_ext":"py","file_size_in_byte":3196,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"61007365","text":"#!/usr/bin/python3.2\n\nfrom multiprocessing import Pool\n\npo = Pool()\nint_list = [x for x in range(0, 1000000)]\nfor x in int_list:\n j = print(str(x ** 3))\n po.apply_async(j)\npo.close()\npo.join()\n","sub_path":"Scripts/Python/TEST/cubed_numbers.py","file_name":"cubed_numbers.py","file_ext":"py","file_size_in_byte":199,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"87185924","text":"from gensim.models import fasttext\nfrom gensim.models.word2vec import Word2Vec\nfrom gensim.models.keyedvectors import KeyedVectors\nimport logging\n\n\ndef get_contents():\n contents = []\n with open('../thchs30_label/thchs30_word_text.txt', 'r', encoding='utf-8') as fid:\n for line in fid:\n parts = line.strip().split(' ')\n utt_id = parts[0]\n text = parts[1:]\n text = \"\".join(text)\n contents.append(text)\n return contents\n\n\nseq = get_contents()\nlogging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)\n#model.build_vocab(seq)\n#model.train(seq, total_examp\nmodel = Word2Vec(seq, min_count=1)\nmodel.save('thchs30_char.model')\nmodel.wv.save_word2vec_format(\"thchs30_char.txt\")\n","sub_path":"get_embedding/char_embedding.py","file_name":"char_embedding.py","file_ext":"py","file_size_in_byte":775,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"28532862","text":"from django.contrib import admin\n\nfrom .models import Profile,RenfortDisponible\nfrom .models import Absence,Navire,Renfort\nfrom .models import Remplacement,Equipe,RemplacementDisponible\nclass ProfileAdmin(admin.ModelAdmin):\n list_display = ('user','user_last_name','fonction', 'equipeName', 'email')\n list_display_links = ('user',)\n def user_last_name(self, obj):\n return obj.user.last_name\n def equipeName(self, obj):\n return obj.equipe.nom\n user_last_name.short_description = 'Nom'\n equipeName.short_description = 'Equipe'\nadmin.site.register(Profile, ProfileAdmin)\nclass AbsenceAdmin(admin.ModelAdmin):\n list_display = ('absent','validee', 'dateDemande')\n list_display_links = ('absent',)\nadmin.site.register(Absence, AbsenceAdmin)\nclass RemplacementDisponibleAdmin(admin.ModelAdmin):\n list_display_link=('remplacantsDispo')\nadmin.site.register(RemplacementDisponible, RemplacementDisponibleAdmin)\nclass RemplacementAdmin(admin.ModelAdmin):\n def absenceName(self, obj):\n return (obj.absence.absent.user.last_name, obj.absence.dateBegin,obj.absence.dateEnd)\n list_display = ('date','quart', 'absenceName')\n absenceName.short_description= 'Caraq. Absence' \nadmin.site.register(Remplacement, RemplacementAdmin)\nclass EquipeAdmin(admin.ModelAdmin):\n list_display = ('nom','dateDebut')\n list_display_links = ('nom',)\n\nadmin.site.register(Equipe, EquipeAdmin)\nclass NavireAdmin(admin.ModelAdmin):\n list_display = ('nom','op', 'appontement','arrivee',)\n list_display_links = ('nom',)\nadmin.site.register(Navire, NavireAdmin)\nclass RenfortAdmin(admin.ModelAdmin):\n def navireName(self, obj):\n return (obj.navire.nom)\n list_display = ('date','quart', 'navireName')\n navireName.short_description= 'Nom bateau'\nadmin.site.register(Renfort, RenfortAdmin)\nclass RenfortDisponibleAdmin(admin.ModelAdmin):\n list_display_link=('renfortDisponible')\nadmin.site.register(RenfortDisponible, RenfortDisponibleAdmin)","sub_path":"gestion/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":1988,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"207833591","text":"import requests\nimport random\nimport json\nimport proxies\n\nip_addresses = proxies.ip_addresses\nproxy = None\n\n#region CONNECTION FUNCTIONS\ndef find_proxy(url):\n global proxy\n connected = False\n while not connected:\n proxy_index = random.randint(0, len(ip_addresses) - 1)\n print('trying ip : ' + ip_addresses[proxy_index])\n try:\n if proxy is None:\n proxy = {\"http\": ip_addresses[proxy_index], \"https\": ip_addresses[proxy_index]}\n response = requests.get(url, proxies=proxy)\n if response.status_code == 200:\n connected = True\n print('Successefull')\n return {'proxy': proxy, 'response': response}\n else:\n proxy = None\n print('IP blocked. Trying next. Remove this one from the list')\n ip_addresses.pop(proxy_index)\n except Exception as e:\n print(e)\n proxy = None\n ip_addresses.pop(proxy_index)\n print('IP failed. Trying next. Remove this one from the list')\n\ndef get_url(url):\n global proxy\n response = requests.get(url)\n print('Trying without proxy...')\n if response.status_code == 200:\n print('Response successeful!')\n return response\n else:\n print('Response failed, trying with proxy...')\n find_proxy_result = find_proxy(url)\n proxy = find_proxy_result['proxy']\n return find_proxy_result['response']\n#endregion\n\n\n\n#region SAVE/LOAD\ndef write_to_file(json_file, path):\n with open(path, 'w', encoding='utf8') as f:\n json.dump(json_file, f, indent=4, separators=(',', ': '), ensure_ascii=False)\n#endregion\n\n","sub_path":"Parser/parser.py","file_name":"parser.py","file_ext":"py","file_size_in_byte":1698,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"212927690","text":"import base64\nimport logging\nimport os\nimport re\nimport requests\nimport sys\n\nfrom flask import Flask, jsonify, redirect, request\n\ntry:\n from dotenv import load_dotenv\n dotenv_path = os.path.join(os.path.dirname(__file__), '.env')\n load_dotenv(dotenv_path)\nexcept:\n pass\n\nURL_RE = re.compile(os.environ.get('URL_REGEX') or r\".+\")\nMAX_TIMEOUT=float(os.environ.get('MAX_TIMEOUT')) if 'MAX_TIMEOUT' in os.environ else 60.0\n\napp = Flask(__name__)\n\nif 'DYNO' in os.environ:\n app.logger.addHandler(logging.StreamHandler(sys.stdout))\n app.logger.setLevel(logging.ERROR)\n\n\ndef request_wants_json():\n best = request.accept_mimetypes.best_match(['application/json', 'text/plain'])\n return best == 'application/json' and request.accept_mimetypes[best] > request.accept_mimetypes['text/plain']\n\n\n@app.route('/')\ndef index():\n return redirect('https://github.com/Benjamin-Dobell/tts-proxy')\n\n@app.route('/forward', methods=['PUT'])\ndef forward_request():\n params = request.get_json(force=True)\n\n url = params.get('url')\n method = params.get('method')\n\n if not url:\n return ('URL not specified', 422)\n\n if not method:\n return ('HTTP method not specified', 422)\n\n if not URL_RE.fullmatch(url):\n return ('Specified URL is not permitted', 403)\n\n headers = {\n **(params.get('headers') or {}),\n }\n headers['X-Forwarded-For'] = '%s, %s' % (headers['X-Forwarded-For'], request.remote_addr) if 'X-Forwarded-For' in headers else request.remote_addr\n\n timeout = min(MAX_TIMEOUT, float(params['timeout'])) if 'timeout' in params else MAX_TIMEOUT\n\n body = None\n\n if 'body' in params:\n body = base64.b64decode(params['body']) if params.get('base64') else params['body']\n\n if body:\n body = body.encode()\n\n response = requests.request(method, url, timeout=timeout, headers=headers, data=body)\n\n wrapped_response = {\n 'status_code': response.status_code,\n 'headers': dict(response.headers),\n }\n\n if response.content:\n if 'content-type' in response.headers and response.headers['content-type'].lower() == 'application/octet-stream':\n wrapped_response['body'] = base64.b64encode(response.content)\n wrapped_response['base64'] = True\n else:\n wrapped_response['body'] = response.text\n\n return jsonify(wrapped_response)\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2367,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"396085377","text":"#! /usr/bin/python\r\n'''experiment file'''\r\n\r\nfrom config import *\r\nimport world\r\nimport agent\r\nimport module\r\nimport reinforcement \r\nimport inverseRL\r\n\r\nclass Experiment():\r\n def __init__(self, data_file):\r\n self.data_file = data_file\r\n self.mouse = MOUSE \r\n self.draw = DRAW\r\n # init maze\r\n self.testMaze = world.Maze(MAZE_ROW, MAZE_COL)\r\n\r\n # init agent\r\n self.myAgent = agent.Agent([int(self.testMaze.rows/2),int(self.testMaze.columns/2)], self.testMaze)\r\n self.stepCount = 0\r\n self.max_step = MAX_STEP\r\n\r\n # init module classes and instances\r\n self.moduleClass = []\r\n for i in range(NUM_MODULE_CLASS):\r\n new_module = module.moduleClass(classID = i, world = self.testMaze, random_gen = RAND_GENS[i],\\\r\n collectable = COLLECTABLES[i], unit_reward = UNIT_REWARDS[i], weight = WEIGHTS[i],\\\r\n gamma = GAMMAS[i], num_inst = NUM_INSTS[i])\r\n# new_module = module.moduleClass(classID = i , world = self.testMaze, random_gen = True)\r\n self.moduleClass.append(new_module) \r\n\r\n def run(self): \r\n # draw environment\r\n if self.draw: \r\n # draw maze\r\n self.testMaze.draw()\r\n # draw agent\r\n self.myAgent.draw(True)\r\n # draw module instances\r\n for module in self.moduleClass: module.draw(True)\r\n\r\n while (self.stepCount <= self.max_step):\r\n # for each module class, for each instance, calculate Q values\r\n module_Qvalues = []\r\n for module in self.moduleClass:\r\n # use '+=' instead of 'append' to concatenate lists\r\n module_Qvalues += reinforcement.calc_Qvalues(module, self.myAgent.pos, self.testMaze)\r\n # SumQ\r\n globalQvalue = reinforcement.sumQ(module_Qvalues)\r\n\r\n # chooses action using softmax, according to global Q values\r\n action = reinforcement.softmax_act(globalQvalue)\r\n\r\n '''IRL data recording''' #TODO: write this as a single line function\r\n if RECORDING:\r\n new_insts = []\r\n for module in self.moduleClass:\r\n for inst in module.insts:\r\n ds = reinforcement.calc_dists(self.myAgent.pos, inst, self.testMaze) \r\n new_inst = inverseRL.observed_inst(self.stepCount, module.classID, module.unit_reward, action, ds)\r\n new_insts.append(new_inst)\r\n\r\n# self.data_file.write(str(self.trial) + ',' + str(self.stepCount))\r\n for inst in new_insts:\r\n inst.record(self.data_file)\r\n self.data_file.write(' ')\r\n# print(inst)\r\n self.data_file.write('\\n')\r\n del new_insts\r\n '''end IRL part'''\r\n\r\n # move one step only when mouse clicks\r\n if self.mouse: self.testMaze.window.getMouse()\r\n \r\n # agent takes action\r\n self.myAgent.move(action)\r\n \r\n # compute reward for agent and remove collecable instances\r\n for module in self.moduleClass:\r\n self.myAgent.cum_reward += module.calc_reward_rm_inst(self.myAgent.pos)\r\n\r\n # visualization\r\n if self.draw:\r\n # self.testMaze.window.flush()\r\n self.myAgent.draw(False)\r\n for module in self.moduleClass:\r\n module.draw(False)\r\n \r\n self.stepCount +=1\r\n #print(\"StepCount: \", stepCount)\r\n \r\n # upon finished, close window\r\n if self.draw: self.testMaze.window.close()\r\n\r\n\r\n\r\n\r\n#Experiment\r\ndata_file = open(sys.argv[1],'w')\r\n#data_file.write(str(R_PRIZE) + ',' + str(R_OBS) + ',' + str(GAMMA_PRIZE) + ',' + str(GAMMA_OBS) + ',' + str(ETA) + '\\n')\r\n\r\nfor trial in range(MAX_TRIAL):\r\n print(\"trial #\", trial)\r\n experiment = Experiment(data_file)\r\n experiment.run()\r\n\r\ndata_file.close()\r\n\r\n#Hold graph window\r\n#raw_input(\"Press enter to exit\")\r\n\r\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4138,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"186902880","text":"from flask import Flask, render_template, request, session, redirect, jsonify, g\nfrom sqlalchemy import create_engine, Column, Integer, String\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy.orm import sessionmaker\n\nengine = create_engine(\"sqlite:///sample.sqlite3\")\nBase = declarative_base()\n\napp = Flask(__name__)\napp.secret_key = b'random string...'\n\nclass Mydata(Base):\n __tablename__ = \"mydata\"\n\n id = Column(Integer, primary_key=True)\n name = Column(String(255))\n mail = Column(String(255))\n age = Column(Integer)\n\n def toDict(self):\n return {\n \"id\": int(self.id),\n \"name\":str(self.name),\n \"mail\":str(self.mail),\n \"age\":int(self.age)\n }\n\ndef getByList(arr):\n res = []\n for item in arr:\n res.append(item.toDict())\n return res\n\ndef getAll():\n Session = sessionmaker(bind=engine)\n ses = Session()\n res = ses.query(Mydata).all()\n ses.close()\n return res\n\n\n@app.route('/', methods=['GET'])\ndef index():\n return render_template(\n \"index.html\",\n title=\"Index\",\n message=\"※SQLite3 Database\",\n # alert=\"This is SQLite3 DataBase Sample!\"\n )\n\n@app.route('/ajax', methods=['GET'])\ndef ajax():\n mydata = getAll()\n return jsonify(getByList(mydata))\n\n@app.route('/form', methods=['POST'])\ndef form():\n name = request.form.get(\"name\")\n mail = request.form.get(\"mail\")\n age = int(request.form.get(\"age\"))\n print(\"@\", name, mail, age)\n mydata = Mydata(name=name, mail=mail, age=age)\n Session = sessionmaker(bind=engine)\n ses = Session()\n ses.add(mydata)\n ses.commit()\n ses.close()\n return \"ok\"\n\nif __name__ == \"__main__\":\n app.debug = True\n app.run(host=\"localhost\")","sub_path":"databese_test_alchemy/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1770,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"156764632","text":"\"\"\"\nMacro handling passes\n\nMacros are expanded on block-by-block\n\"\"\"\nfrom __future__ import absolute_import, print_function, division\nfrom numba import ir\n\n\nclass MacroError(Exception):\n pass\n\n\ndef expand_macros(blocks):\n constants = {}\n for blk in blocks.values():\n module_getattr_folding(constants, blk)\n expand_macros_in_block(constants, blk)\n\n\ndef module_getattr_folding(constants, block):\n for inst in block.body:\n if isinstance(inst, ir.Assign):\n rhs = inst.value\n\n if isinstance(rhs, ir.Global):\n constants[inst.target.name] = rhs.value\n\n elif isinstance(rhs, ir.Expr) and rhs.op == 'getattr':\n if rhs.value.name in constants:\n base = constants[rhs.value.name]\n constants[inst.target.name] = getattr(base, rhs.attr)\n\n elif isinstance(rhs, ir.Const):\n constants[inst.target.name] = rhs.value\n\n elif isinstance(rhs, ir.Var) and rhs.name in constants:\n constants[inst.target.name] = constants[rhs.name]\n\n elif isinstance(rhs, ir.FreeVar):\n constants[inst.target.name] = rhs.value\n\ndef expand_macros_in_block(constants, block):\n calls = []\n for inst in block.body:\n if isinstance(inst, ir.Assign):\n rhs = inst.value\n if isinstance(rhs, ir.Expr) and rhs.op == 'call':\n callee = rhs.func\n macro = constants.get(callee.name)\n if isinstance(macro, Macro):\n # Rewrite calling macro\n assert macro.callable\n calls.append((inst, macro))\n args = [constants[arg.name] for arg in rhs.args]\n kws = dict((k, constants[v.name]) for k, v in rhs.kws)\n try:\n result = macro.func(*args, **kws)\n except BaseException as e:\n msg = str(e)\n headfmt = \"Macro expansion failed at {line}\"\n head = headfmt.format(line=inst.loc)\n newmsg = \"{0}:\\n{1}\".format(head, msg)\n raise MacroError(newmsg)\n if result:\n # Insert a new function\n result.loc = rhs.loc\n inst.value = ir.Expr.call(func=result, args=rhs.args,\n kws=rhs.kws, loc=rhs.loc)\n elif isinstance(rhs, ir.Expr) and rhs.op == 'getattr':\n # Rewrite get attribute to macro call\n # Non-calling macro must be triggered by get attribute\n base = constants.get(rhs.value.name)\n if base is not None:\n value = getattr(base, rhs.attr)\n if isinstance(value, Macro):\n macro = value\n if not macro.callable:\n intr = ir.Intrinsic(macro.name, macro.func, args=())\n inst.value = ir.Expr.call(func=intr, args=(),\n kws=(), loc=rhs.loc)\n\n\nclass Macro(object):\n \"\"\"A macro object is expanded to a function call\n \"\"\"\n __slots__ = 'name', 'func', 'callable', 'argnames'\n\n def __init__(self, name, func, callable=False, argnames=None):\n self.name = name\n self.func = func\n self.callable = callable\n self.argnames = argnames\n\n def __repr__(self):\n return ' %s>' % (self.name, self.func)\n\n","sub_path":"numba/macro.py","file_name":"macro.py","file_ext":"py","file_size_in_byte":3618,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"263974765","text":"import os\nfrom pkgutil import iter_modules\n\n__all__ = []\n\ndef global_import(name):\n p = __import__(name, globals(), locals(), level=1)\n lst = p.__all__ if '__all__' in dir(p) else dir(p)\n if lst:\n del globals()[name]\n for k in lst:\n if not k.startswith('__'):\n globals()[k] = p.__dict__[k]\n __all__.append(k)\n\n_CURR_DIR = os.path.dirname(__file__)\nfor _, module_name, _ in iter_modules(\n [os.path.dirname(__file__)]):\n srcpath = os.path.join(_CURR_DIR, module_name + '.py')\n if not os.path.isfile(srcpath):\n continue\n if not module_name.startswith('_'):\n global_import(module_name)\n","sub_path":"nnpix/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":676,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"116013800","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Oct 16 22:27:47 2022\n\n@author: alex\n\"\"\"\n\nimport numpy as np\n\nfrom pyro.dynamic import pendulum\nfrom pyro.control import controller\nfrom pyro.analysis import costfunction\nfrom pyro.planning import dynamicprogramming\nfrom pyro.planning import discretizer\n\nfrom reinforcementlearning import QLearning\n\nsys = pendulum.SinglePendulum()\n\nsys.x_ub[0] = 4.0\nsys.x_lb[0] = -7.0\nsys.x_lb[1] = -6.0\nsys.x_ub[1] = 6.0\n\n# Discrete world \ngrid_sys = discretizer.GridDynamicSystem( sys , [101,101] , [3] , 0.1)\n\n# Cost Function\nqcf = costfunction.QuadraticCostFunction.from_sys(sys)\n\nqcf.xbar = np.array([ -3.14 , 0 ]) # target\nqcf.INF = 300\n\nqcf.R[0,0] = 1.0\n\nqcf.S[0,0] = 10.0\nqcf.S[1,1] = 10.0\n\n\n# DP algo\ndp = QLearning( grid_sys , qcf ) \n\ndp.compute_J_from_Q()\n\ndp.compute_policy_from_Q()\n\ndp.compute_episodes(1000)\n\ndp.plot_cost2go()","sub_path":"dev/reinforcement_learning/rl_tests/pendulum_test_rl.py","file_name":"pendulum_test_rl.py","file_ext":"py","file_size_in_byte":895,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"422171950","text":"#!/usr/bin/env python\n\nimport os,sys\nimport optparse\nimport commands\nimport math\n\nusage = 'usage: %prog [options]'\nparser = optparse.OptionParser(usage)\nparser.add_option('-q', '--queue' , dest='queue' , help='batch queue' , default='1nh')\nparser.add_option('-g', '--granularity', dest='granularity' , help='granularities \\\"layer_i-layer_j:factor,layer:factor,...\\\"' , default='0-29:4')\nparser.add_option('-n', '--noise' , dest='noise' , help='noise (in Mips) \\\"layer_i-layer_j:factor,layer:factor,...\\\"' , default='0-29:0.1')\nparser.add_option('-t', '--thresh' , dest='threshold' , help='threshold (in ADC) \\\"layer_i-layer_j:factor,layer:factor,...\\\"' , default='0-29:25')\nparser.add_option('-N', '--Nevts' , dest='Nevts' , help='number of events to process' , default=0, type=int)\nparser.add_option('-m', '--miptoadc' , dest='MipToADC' , help='adc counts per MIP' , default=50, type=int)\nparser.add_option('-r', '--randomseed' , dest='seed' , help='random seed' , default=0, type=int)\nparser.add_option('-d', '--debug' , dest='debug' , help='debug output' , default=0, type=int)\nparser.add_option('-s', '--scenario' , dest='scenario' , help='Integer describing scenario.' , default=0, type=int)\nparser.add_option('-o', '--out' , dest='out' , help='output directory' , default=os.getcwd() )\nparser.add_option('-e', '--eos' , dest='eos' , help='eos path to save root file to EOS', default='root://eoscms//eos/cms/store/user/amagnan/HGCalHEGeant4/run_0')\nparser.add_option('-S', '--no-submit' , action=\"store_true\", dest='nosubmit' , help='Do not submit batch job.')\n(opt, args) = parser.parse_args()\n\nnevents=opt.Nevts\n\n#myg4dir=\"/afs/cern.ch/work/a/amagnan/public/HGCalEEGeant4/\"\n#myg4dir=\"root://eoscms//eos/cms/store/cmst3/group/hgcal/Geant4\"\n#myg4dir=\"root://eoscms//eos/cms/store/user/amagnan/HGCalHEGeant4\"\n\nfor version in [23]:\n #for particle in [\"Gamma\",\"GammaPU\",\"PU\"]:\n for particle in [\"e-\",\"pi-\"]: #\"SimplePU\"]:\n #for eta in [30,35]:\n #for eta in [20,25,30,35]:\n eosDir='%s/%s'%(opt.eos,particle)\n #for en in [5,10,25,40,50,60,80,100,150,200,300,400,500,1000]:\n for en in [10,15,20,25,30,35,40,45,50,60,80]: #,100,200,300,400,500]:\n #for en in [0,1,2,3,4,5,6,7,8,9]:\n #for en in [5,10,25,50,75,100]:\n #for en in [150,200,300,500]:\n \n inDir='%s/HGcal_version%d_e%d.root'%(eosDir,version,en)\n outDir='%s/version_%d/scenario_%d/%s/e_%d/'%(opt.out,version,opt.scenario,particle,en)\n outlog='%s/digitizer.log'%(outDir)\n os.system('mkdir -p %s'%outDir)\n \n #wrapper\n scriptFile = open('%s/runJob.sh'%(outDir), 'w')\n scriptFile.write('#!/bin/bash\\n')\n scriptFile.write('source %s/../g4env.sh\\n'%(os.getcwd()))\n scriptFile.write('localdir=`pwd`\\n')\n scriptFile.write('echo \"--Local directory is \" $localdir >> %s\\n'%outlog)\n scriptFile.write('%s/bin/digitizer %d %s $localdir %s %s %s %d %d %d | tee %s\\n'%(os.getcwd(),opt.Nevts,inDir,opt.granularity,opt.noise,opt.threshold,opt.MipToADC,opt.seed,opt.debug,outlog))\n scriptFile.write('ls * >> %s\\n'%outlog)\n if len(opt.eos)>0:\n outTag='version%d_scenario%d_e%d'%(version,opt.scenario,en)\n scriptFile.write('grep \"alias eos=\" /afs/cern.ch/project/eos/installation/cms/etc/setup.sh | sed \"s/alias /export my/\" > eosenv.sh\\n')\n scriptFile.write('source eosenv.sh\\n')\n scriptFile.write('$myeos mkdir -p %s\\n'%eosDir)\n scriptFile.write('myfilepath=`ls DigiPFcal*.root`\\n')\n scriptFile.write('echo \" --- Root file name to copy to EOS is: \"$myfilepath>> %s\\n'%outlog)\n scriptFile.write('cmsStage -f $myfilepath %s/HGcal_%s.root\\n'%(eosDir,outTag))\n scriptFile.write('if (( \"$?\" != \"0\" )); then\\n')\n scriptFile.write('echo \" --- Problem with copy of file $myfilepath to EOS. Keeping locally.\" >> %s\\n'%outlog)\n scriptFile.write('else\\n')\n scriptFile.write('echo \" --- File $myfilepath successfully copied to EOS: %s/HGcal_%s.root\" >> %s\\n'%(eosDir,outTag,outlog))\n scriptFile.write('rm $myfilepath\\n')\n scriptFile.write('fi\\n')\n scriptFile.write('cp * %s/\\n'%(outDir))\n scriptFile.write('echo \"All done\"\\n')\n scriptFile.close()\n \n #submit\n os.system('chmod u+rwx %s/runJob.sh'%outDir)\n #\n if opt.nosubmit : os.system('echo bsub -q %s %s/runJob.sh'%(opt.queue,outDir)) \n else: os.system(\"bsub -q %s \\'%s/runJob.sh\\'\"%(opt.queue,outDir))\n \n","sub_path":"analysis/submitDigi.py","file_name":"submitDigi.py","file_ext":"py","file_size_in_byte":5027,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"176371716","text":"import pandas as pd # 고정변수, 종속변수 분리를 위한 pandas 프레임워크 활용\nfrom sklearn import svm, metrics, model_selection # sklearn:\n\ncsv = pd.read_csv('iris.csv')\ndata = csv[[\"SepalLength\",\"SepalWidth\",\"PetalLength\",\"PetalWidth\"]]\nlabel = csv[[\"Name\"]]\nclf = svm.SVC()\ncorrects = model_selection.cross_val_score(clf, data, label, cv=5)\n\nprint(\"각각의 정답률 =\", corrects)\nprint(\"평균 정답률 =\", corrects.average())","sub_path":"03. AI/01. Machine Learning/머신러닝분석_학생평가/김치우_지도학습_간소화.py","file_name":"김치우_지도학습_간소화.py","file_ext":"py","file_size_in_byte":450,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"641536982","text":"# valueIterationAgents.py\n# -----------------------\n# Licensing Information: You are free to use or extend these projects for\n# educational purposes provided that (1) you do not distribute or publish\n# solutions, (2) you retain this notice, and (3) you provide clear\n# attribution to UC Berkeley, including a link to http://ai.berkeley.edu.\n# \n# Attribution Information: The Pacman AI projects were developed at UC Berkeley.\n# The core projects and autograders were primarily created by John DeNero\n# (denero@cs.berkeley.edu) and Dan Klein (klein@cs.berkeley.edu).\n# Student side autograding was added by Brad Miller, Nick Hay, and\n# Pieter Abbeel (pabbeel@cs.berkeley.edu).\n\n\nimport mdp, util\nimport logging, sys\nlogging.basicConfig(stream=sys.stderr, level=logging.DEBUG)\nfrom learningAgents import ValueEstimationAgent\n\nclass ValueIterationAgent(ValueEstimationAgent):\n \"\"\"\n * Please read learningAgents.py before reading this.*\n\n A ValueIterationAgent takes a Markov decision process\n (see mdp.py) on initialization and runs value iteration\n for a given number of iterations using the supplied\n discount factor.\n \"\"\"\n\n def __init__(self, mdp, discount = 0.9, iterations = 100):\n \"\"\"\n Your value iteration agent should take an mdp on\n construction, run the indicated number of iterations\n and then act according to the resulting policy.\n\n Some useful mdp methods you will use:\n mdp.getStates()\n mdp.getPossibleActions(state)\n mdp.getTransitionStatesAndProbs(state, action)\n mdp.getReward(state, action, nextState)\n mdp.isTerminal(state)\n \"\"\"\n self.mdp = mdp\n self.discount = discount\n self.iterations = iterations\n self.values = util.Counter() # A Counter is a dict with default 0\n for _ in range(0, iterations):\n self.newValues = util.Counter()\n for st in mdp.getStates():\n if len(mdp.getPossibleActions(st)) != 0:\n maxV = -sys.maxint\n for act in mdp.getPossibleActions(st):\n newV = 0\n for tst, prob in mdp.getTransitionStatesAndProbs(st, act):\n r = mdp.getReward(st, act, tst)\n newV += prob*(r + discount* self.values[tst])\n if newV > maxV: maxV = newV\n self.newValues[st]=maxV\n else:\n self.newValues[st]=self.values[st]\n self.values = self.newValues\n #logging.debug('values:%s', self.values)\n \n def getValue(self, state):\n \"\"\"\n Return the value of the state (computed in __init__).\n \"\"\"\n return self.values[state]\n\n\n def computeQValueFromValues(self, state, action):\n \"\"\"\n Compute the Q-value of action in state from the\n value function stored in self.values.\n \"\"\"\n v = 0\n for tst, prob in self.mdp.getTransitionStatesAndProbs(state, action):\n r = self.mdp.getReward(state, action, tst)\n v += prob*(r + self.discount* self.values[tst])\n return v\n\n def computeActionFromValues(self, state):\n \"\"\"\n The policy is the best action in the given state\n according to the values currently stored in self.values.\n\n You may break ties any way you see fit. Note that if\n there are no legal actions, which is the case at the\n terminal state, you should return None.\n \"\"\"\n action = None\n maxV = -sys.maxint\n for act in self.mdp.getPossibleActions(state):\n v = 0\n for tst, prob in self.mdp.getTransitionStatesAndProbs(state, act):\n r = self.mdp.getReward(state, act, tst)\n v += prob*(r + self.discount* self.values[tst])\n if v>maxV: \n maxV = v\n action = act\n return action\n \n\n def getPolicy(self, state):\n return self.computeActionFromValues(state)\n\n def getAction(self, state):\n \"Returns the policy at the state (no exploration).\"\n return self.computeActionFromValues(state)\n\n def getQValue(self, state, action):\n return self.computeQValueFromValues(state, action)\n","sub_path":"BerkeleyAI/reinforcement/valueIterationAgents.py","file_name":"valueIterationAgents.py","file_ext":"py","file_size_in_byte":4375,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"216251364","text":"from __future__ import division\nimport _init_paths\nfrom fast_rcnn.config import cfg\nfrom fast_rcnn.test import im_detect\nfrom fast_rcnn.nms_wrapper import nms\nfrom utils.timer import Timer\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport scipy.io as sio\nimport caffe, os, sys, cv2\nimport argparse\nimport sys\n\n# Dockerface network\nNETS = {'vgg16': ('VGG16',\n 'output/faster_rcnn_end2end/wider/vgg16_dockerface_iter_80000.caffemodel')}\n\ndef parse_args():\n \"\"\"Parse input arguments.\"\"\"\n parser = argparse.ArgumentParser(description='Face Detection using Faster R-CNN')\n parser.add_argument('--gpu', dest='gpu_id', help='GPU device id to use [0]',\n default=0, type=int)\n parser.add_argument('--cpu', dest='cpu_mode',\n help='Use CPU mode (overrides --gpu)',\n action='store_true')\n parser.add_argument('--net', dest='demo_net', help='Network to use [vgg16]',\n choices=NETS.keys(), default='vgg16')\n parser.add_argument('--video', dest='video_path', help='Path of video')\n parser.add_argument('--output_string', dest='output_string', help='String appended to output file')\n parser.add_argument('--conf_thresh', dest='conf_thresh', help='Confidence threshold for the detections, float from 0 to 1', default=0.85, type=float)\n parser.add_argument('--fps', dest='fps', help=\"frame rate of the output video, float > 0.0\", default=1.0, type=float)\n args = parser.parse_args()\n\n return args\n\nif __name__ == '__main__':\n cfg.TEST.HAS_RPN = True # Use RPN for proposals\n # cfg.TEST.BBOX_REG = False\n\n args = parse_args()\n\n prototxt = os.path.join(cfg.MODELS_DIR, NETS[args.demo_net][0],\n 'faster_rcnn_alt_opt', 'faster_rcnn_test.pt')\n caffemodel = os.path.join(cfg.DATA_DIR, 'faster_rcnn_models',\n NETS[args.demo_net][1])\n\n prototxt = 'models/face/VGG16/faster_rcnn_end2end/test.prototxt'\n caffemodel = NETS[args.demo_net][1]\n\n if not os.path.isfile(caffemodel):\n raise IOError(('{:s} not found.\\nDid you run ./data/script/'\n 'fetch_faster_rcnn_models.sh?').format(caffemodel))\n\n if args.cpu_mode:\n caffe.set_mode_cpu()\n else:\n caffe.set_mode_gpu()\n caffe.set_device(args.gpu_id)","sub_path":"scripts/feature_extraction/head_pose_detection/02.dockerface/tools/.ipynb_checkpoints/run_face_detection_on_video-checkpoint.py","file_name":"run_face_detection_on_video-checkpoint.py","file_ext":"py","file_size_in_byte":2200,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"414058048","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Mar 19 20:28:01 2018\n\n@author: oliver.cairns\n\nThis file adds elo rankings to the data. The \n\"\"\"\nimport Setup\nimport pandas as pd\nimport math\nimport numpy as np\nfrom copy import copy\nfrom scipy import optimize\n\n#Clean FTR column\ndef results_map(result):\n if result == \"H\":\n return 1.0\n if result == \"A\":\n return 0.0\n if result == \"D\":\n return 0.5\n else:\n print('failure')\n\n#calculate the winning chances of a player vs oppoent, for a given ratings dataframe. \ndef calc_winning_chances(ratings_dict, first_player,second_player):\n\t#implimented from formula for elo: e1 = 10^(r1/400)/[10^(r1/400) + 10^(r2/400)]\n\trating_1 = ratings_dict[first_player]['current_rating']/400\n\trating_2 = ratings_dict[second_player]['current_rating']/400\n\tq1 = math.pow(10.0, rating_1)\n\tq2 = math.pow(10.0, rating_2)\n\te1 = q1/(q1+q2)\n\treturn e1\n\n#updates the global ratings_dict, given a single game + k-factor\ndef update_elos_and_winning_chances(game,game_index,ratings_dict,k_factor,matches_df):\n first_player=game['HomeTeam']\n second_player=game['AwayTeam']\n outcome=game['FTR']\n date = game['Date']\n #calculate chance of first player winning game (can be reused with other ratings algorithms (although ratings will be meaningless))\n e1 = calc_winning_chances(ratings_dict,first_player,second_player)\n e2 =1.0 - e1\n \n #update historic rankings - slows down code, but allows you to plot ELO charts\n \"\"\"\n ratings_dict[first_player]['historic_ratings'].append(copy(ratings_dict[first_player]['current_rating']))\n ratings_dict[second_player]['historic_ratings'].append(copy(ratings_dict[second_player]['current_rating']))\n ratings_dict[first_player]['historic_predictions'].append(copy(e1))\n ratings_dict[second_player]['historic_predictions'].append(copy(e2))\n ratings_dict[first_player]['historic_dates'].append(copy(date))\n ratings_dict[second_player]['historic_dates'].append(copy(date))\n \"\"\"\n matches_data.loc[game_index,'HomeElo'] = ratings_dict[first_player]['current_rating']\n\n matches_data.loc[game_index,'AwayElo'] = ratings_dict[second_player]['current_rating']\n\n matches_data.loc[game_index,'HomeProb'] = e1\n\t\n #measure performance of prediction vs actual win/loss draw. Brier change = square of prediction error.\n if(outcome == 1.0):\n ratings_dict[first_player]['current_rating'] += e2*k_factor\n ratings_dict[second_player]['current_rating'] -= e2*k_factor\n brier_change = e2*e2\n\n elif(outcome == 0.0):\n ratings_dict[first_player]['current_rating'] -= e1*k_factor\n ratings_dict[second_player]['current_rating'] += e1*k_factor\n brier_change = e1*e1\n \n elif(outcome == 0.5):\n ratings_dict[first_player]['current_rating'] += (1/2-e1)*k_factor\n ratings_dict[second_player]['current_rating'] += (1/2-e2)*k_factor\n brier_change = (e1-0.5)*(e1-0.5)\n \n return brier_change\n\ndef calc_brier_and_elos(matches_data,k_factor):\n #Ignore first two years - so that ELOs can be calibrated\n first_year = matches_data['season'].min()\n \n matches_data.sort_values(by=\"Date\")\n matches_data['HomeElo'] = 0\n matches_data['AwayElo'] = 0\n matches_data['HomeProb'] = 0\n \n \n unique_teams = sorted(set(matches_data['HomeTeam']))\n ratings_dict = {}\n for team in unique_teams:\n ratings_dict[team]={'current_rating':1200.0,'stats':[0,0,0],'historic_ratings':[],'results':[],'historic_predictions':[], 'historic_dates':[]}\n \n #Adjust so championship teams have a worse rating\n first_league = matches_data.groupby(by='HomeTeam')['league'].first()\n if first_league[team]== \"Championship\":\n ratings_dict[team]['current_rating'] = 1100.0\n \n matches_data.groupby(by='HomeTeam')['league'].first() \n #How quickly do ratings adjust?\n #Can tune this to minimise Brier score - for now just using constant value\n \n current_brier = 0\n \n \n for i, game in matches_data.iterrows():\n brier_change = update_elos_and_winning_chances(game=game,game_index = i, ratings_dict = ratings_dict, k_factor=k_factor, matches_df = matches_data)\n if game['season'] == first_year:\n brier_change = 0\n\n current_brier += brier_change\n \n \n print(\"Brier: \",current_brier)\n print(\"K factor: \",k_factor)\n print()\n \n return current_brier,matches_data\n\n#load_path = Setup.raw_data + \"Premier League results - extract.csv\"\n\nload_path = Setup.raw_data + \"1. a Premier League results - raw data.csv\"\n\nsave_path = Setup.raw_data + \"1. b Premier League results - extract with ELOs.csv\"\n\nmatches_data = pd.read_csv(load_path,encoding='latin1')\n#Clean datetimes\n\n\n\n#Some issues with data quality before 1999. Excluding for now\nmatches_data = matches_data[matches_data['season'] > 1999]\n\nmatches_data['FTR']=matches_data['FTR'].map(results_map)\n\n#Shorten 2002 and 2003 data - all other dates are partial rather than full\nmatches_data['Date'].replace('2002','02',inplace=True,regex=True)\nmatches_data['Date'].replace('2003','03',inplace=True,regex=True)\nmatches_data['Date2'] = pd.to_datetime(matches_data['Date'],format='%d/%m/%y').dt.date\n\n\ndef optimize_brier(k_factor,args=(matches_data)):\n matches_data = args\n brier_score, matches_data = calc_brier_and_elos(matches_data,k_factor)\n return brier_score\n\n#Finds the optimal k factor - takes quite a long time\n'''\noptimization = optimize.minimize(optimize_brier,method='BFGS',x0=17.84674206)\nprint(optimization)\nk_star= optimization['x'] \n'''\n\nk_star = 13.4932324\n\n#We just want the matches data - adds elo infor as columns\nbrier_score, matches_data = calc_brier_and_elos(matches_data,k_star)\n\n#Save output\nmatches_data.to_csv(path_or_buf=save_path)\n\n#Checking dates issues - no longer relevant\n'''\ntest = matches_data[['Date2','Date','season']].copy()\n\ntest['year'] = test['Date2'].apply(lambda x: x.year)\n\ntest['month'] = test['Date2'].apply(lambda x: x.month)\n\ntest['dummy'] = 1\n\ntest['diff'] = test['season'] - test['year']\n\n\nsummary_table = pd.pivot_table(test, values='dummy', index=['month','diff'], columns='season', aggfunc='sum',margins_name='All')\n\n#summary_table_2 = pd.pivot_table(matches_data, values=['HY', index=['league'], columns='season', aggfunc='sum',margins_name='All')\nprint(summary_table)\n'''","sub_path":"py_files/1. cleaning/add_elo_rankings.py","file_name":"add_elo_rankings.py","file_ext":"py","file_size_in_byte":6380,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"649407205","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Feb 14 13:22:58 2018\n\n@author: jeffr\n\"\"\"\n\n\n\n\n\n\"\"\" NOTE: Pour la modification du script aller à la ligne 183 et modifier selon \nl'emplacement de votre fichier txt (matrice) et le nombre de composantes (nb_c) \nainsi que le nombre d'itérations\"\"\"\n\n\n\n\n\nimport numpy as np\nfrom scipy.optimize import minimize\nimport scipy.stats as stats\nimport dm3_lib as dm3\nfrom functools import partial\nfrom tqdm import tqdm\nfrom sklearn.cluster import AgglomerativeClustering\nimport time\n\n\nimport matplotlib\n\n\nclass HyperspectralSegmentationMCR_LLM:\n\n \n \n @classmethod\n def mcr_llm3d(cls, xi, nb_c, nb_iter =25):\n\n m,n,o = np.shape(xi)\n c_f = np.zeros((o*n, nb_c))\n x_f = np.zeros((o*n, m))\n for i in range(n):\n #x=xi[:,i,:].T\n #[s, x_sum, x_norm, x_raw, ci] = cls.initialisation(x, nb_c)\n #c_f[i*o:(i+1)*o,:np.size(ci,axis=1)] = ci\n x_f[i*o:(i+1)*o,:] = xi[:,i,:].T\n\n #x_norm, x_sum = cls.initialisation_2d(x_f)\n start = time.time()\n s, x_sum, x_norm, x_raw, c_f = cls.initialisation(x_f, nb_c)\n end = time.time()\n tottime = (end-start)//60\n print(tottime)\n\n for nb_iter in tqdm(range(nb_iter)):\n # Concentrations (with Poisson likelihood maximization)\n \n c = cls.C_plm(x_f, s, x_norm, x_sum, nb_c, c_f)\n s = cls.s_plm(x_norm, c)\n c_f = c\n\n\n return c,s\n\n\n\n\n\n\n\n @classmethod\n def initialisation_2d(cls, x):\n\n x_sum = np.asarray([np.sum(x, axis=1)]).T\n x_norm = x / x_sum\n x_norm = np.nan_to_num(x_norm)\n x_raw = x # note that la\n return x_norm, x_sum\n\n\n @classmethod\n def initialisation(cls, x, nb_c):\n\n x_sum = np.asarray([np.sum(x, axis=1)]).T\n x_norm = x / x_sum\n x_norm = np.nan_to_num(x_norm)\n x_raw = x # note that lambda is a function in python, lada replaces lambda as not to overwrite it. Also lada is a shitty russian car manufacturer, look it up!\n\n\n\n c_pred= AgglomerativeClustering(n_clusters=nb_c, linkage= 'ward').fit(x_norm).labels_\n s = np.zeros(( np.size(x_norm, axis = 1),nb_c))\n for j in range(0,nb_c):\n filter1 = c_pred==j\n spec = np.mean(x_norm[filter1,:],axis =0).T\n s[:,j-1] = spec.T\n \n \n s = s.T\n c_pred = x_norm @ s.T @ np.linalg.inv(s @ s.T)\n return s, x_sum, x_norm, x_raw, c_pred\n \n\n @classmethod\n def s_plm(cls,x,c):\n S2 = np.linalg.inv(c.T@c)@c.T@x# Multilinear regression\n S2[S2 <= np.spacing(1)] = np.spacing(1) # avoid 0 values\n s = S2/ (np.sum(S2, axis =1) * np.ones((np.size(S2, axis = 1),1))).T# Normalization\n return s\n\n \n \n @classmethod\n def C_plm(cls,x, s, xnorm,x_sum,nb_c, c_pred):\n #initialize C\n\n [n,m] = np.shape(x)\n c_new = np.zeros((n,nb_c))\n \n c_iter_mod = c_new\n #Paralled FOR loops\n \n\n #with ThreadPoolExecutor(max_workers=cpus) as executor:\n #for ids in range(0,n):\n \n for ids in range(0,n):\n \n \n #a= executor.submit(partial(cls.pyPLM,nb_c,s),xnorm[ids,:])\n #C[ids,:] = a.result() \n \n if ids<5:\n c_new[ids,:], c_iter_mod[ids,:] = cls.pyPLM(nb_c, s, xnorm[ids,:], c_pred[ids,:], boolin=False)\n else:\n c_new[ids,:], c_iter_mod[ids,:] = cls.pyPLM(nb_c, s, xnorm[ids,:], c_pred[ids-5:ids,:], boolin=True) \n \n # avoid errors (this part should not be necessary)\n c_new[np.isnan(c_new)] = 1/nb_c\n c_new[np.isinf(c_new)] = 1/nb_c\n c_new[c_new<0] = 0\n c_sum1 = np.array([np.sum(c_new,axis=1)])\n c_sum =c_sum1.T@np.ones((1,np.size(c_new,axis =1)))\n c_new = c_new/c_sum\n\n return c_new\n \n \n @classmethod\n def pyPLM(cls, nb_c, s, x_norm, c,boolin=False):\n c_old = c\n\n yObs = x_norm\n yObs = np.array([yObs])\n\n # sum of every value is equal to 1\n def con_one(c):\n return 1-sum(c) \n \n\n # all values are positive\n bnds = ((0.0, 1.0),) * nb_c\n\n cons = [{'type': 'eq', 'fun': con_one}]\n\n def regressLL(s, yObs, c_pred):\n \n \n yPred = c_pred @ s\n \n\n # Calculate the negative log-likelihood as the negative sum of the log of a normal\n # PDF where the observed values are normally distributed around the mean (yPred)\n # with a standard deviation of sd\n logLik = -np.sum(stats.norm.logpdf(yObs, loc=yPred))\n\n # Tell the function to return the NLL (this is what will be minimized)\n return (logLik)\n\n try:\n c_pred = x_norm @ s.T @ np.linalg.inv(s @ s.T)\n\n\n \n if boolin:\n cavc = np.average(c_old, axis = 0)*c_pred\n c_pred = cavc/sum(cavc)\n \n except np.linalg.LinAlgError:\n\n cavc = np.average(c_old, axis = 0)\n c_pred = cavc/sum(cavc)\n \n pass\n \n # Run the minimizer\n results = minimize(partial(regressLL, s, yObs), c_pred, method='SLSQP', bounds=bnds, constraints=cons, jac =False)\n results = results.x\n results = np.asarray(results)\n\n c_new = results.reshape(int(len(results) / nb_c), nb_c)\n return c_new,c_pred\n \ndm3f = dm3.DM3(\"EELS Spectrum Image (dark ref corrected).dm3\")\nx = dm3f.imagedata\nnb_c =3 # nombre de composantes\nnb_iter = 25 # nombre d'itérations\n\n[c, s] = HyperspectralSegmentationMCR_LLM.mcr_llm3d(x,nb_c,nb_iter) # appel de l'algorithme\n\nmatplotlib.pyplot.plot(c)\n\n\n\n\n","sub_path":"Fichiers incomplets ou non-fonctionnels/Initialisateur/MCRLLM_Ward_initialized.py","file_name":"MCRLLM_Ward_initialized.py","file_ext":"py","file_size_in_byte":5828,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"220578855","text":"class Database():\n mentors_data = [\n [1, 'Attila', 'Molnár', 'Atesz', '003670/630-0539', 'attila.molnar@codecool.com', 'Miskolc', 23],\n [2, 'Pál', 'Monoczki', 'Pali', '003630/327-2663', 'pal.monoczki@codecool.com', 'Miskolc', None],\n [3, 'Sándor', 'Szodoray', 'Szodi', '003620/519-9152', 'sandor.szodoray@codecool.com', 'Miskolc', 7],\n [4, 'Dániel', 'Salamon', 'Dani', '003620/508-0706', 'daniel.salamon@codecool.com', 'Budapest', 4],\n [5, 'Miklós', 'Beöthy', 'Miki', '003630/256-8118', 'miklos.beothy@codecool.com', 'Budapest', 42],\n [6, 'Tamás', 'Tompa', 'Tomi', '003630/370-0748', 'tamas.tompa@codecool.com', 'Budapest', 42],\n [7, 'Mateusz', 'Ostafil', 'Mateusz', '003648/518-664-923', 'mateusz.ostafil@codecool.com', 'Krakow', 13]\n ]\n\n applicants_data = [\n [1, 'Dominique', 'Williams', '003630/734-4926', 'dolor@laoreet.co.uk', 61823],\n [2, 'Jemima', 'Foreman', '003620/834-6898', 'magna@etultrices.net', 58324],\n [3, 'Zeph', 'Massey', '003630/216-5351', 'a.feugiat.tellus@montesnasceturridiculus.co.uk', 61349],\n [4, 'Joseph', 'Crawford', '003670/923-2669', 'lacinia.mattis@arcu.co.uk', 12916],\n [5, 'Ifeoma', 'Bird', '003630/465-8994', 'diam.duis.mi@orcitinciduntadipiscing.com', 65603],\n [6, 'Arsenio', 'Matthews', '003620/804-1652', 'semper.pretium.neque@mauriseu.net', 39220],\n [7, 'Jemima', 'Cantu', '003620/423-4261', 'et.risus.quisque@mollis.co.uk', 10384],\n [8, 'Carol', 'Arnold', '003630/179-1827', 'dapibus.rutrum@litoratorquent.com', 70730],\n [9, 'Jane', 'Forbes', '003670/653-5392', 'janiebaby@adipiscingenimmi.edu', 56882],\n [10, 'Ursa', 'William', '003620/496-7064', 'malesuada@mauriseu.net', 91220]\n ]\n\n @classmethod\n def get_mentors(cls):\n from mentor import Mentor\n return [Mentor(raw_mentor) for raw_mentor in cls.mentors_data]\n\n @classmethod\n def get_applicants(cls):\n from applicant import Applicant\n return [Applicant(raw_applicant) for raw_applicant in cls.applicants_data]\n","sub_path":"db.py","file_name":"db.py","file_ext":"py","file_size_in_byte":2079,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"568282123","text":"# check whether the result of prime_number * next_prime_number + 2 is prime number or not\n# ref. stackoverflow.com\n#\n# pip3 install sympy!\n#\n# 2022.07.17 by neibc96@gmail.com & GD\n\nimport math\nfrom datetime import datetime\nimport sys\nimport platform\nimport sympy\n\n#global variables\nispause = 0\n\ndef is_prime(n):\n if n % 2 == 0 and n > 2: \n return False\n return all(n % i for i in range(3, int(math.sqrt(n)) + 1, 2))\n \nprint('environment_uname : ', end='')\nprint(platform.platform())\n\nmaxnum = 1000\n\n#startnum = 3 \n\nwhile maxnum > 0:\n pnum1 = 2\n pnum2 = 3\n noftrue = 0\n noffalse = 0\n\n maxnum = int(input(\"input max target investigation value(>1, 0 to end) ex> 2020123212321223 : \"))\n print('-------------------------------------------------------')\n print('start time : ' + datetime.utcnow().strftime('%Y/%m/%d_%H:%M:%S.%f'))\n starta = datetime.now()\n\n for i in range(3, maxnum):\n# if is_prime(i) == True:\n if sympy.isprime(i) == True:\n pnum2 = i\n \n tval = pnum1 * pnum2 + 2\n# pcheckresult = is_prime(tval)\n pcheckresult = sympy.isprime(tval)\n if pcheckresult == True:\n noftrue=noftrue+1\n else: \n noffalse=noffalse+1\n print('%d * %d + 2 = %d and %s' %(pnum1, pnum2, tval, pcheckresult))\n pnum1 = pnum2\n startb = datetime.now()\n print('\\nend time : ' + datetime.utcnow().strftime('%Y/%m/%d_%H:%M:%S.%f'))\n print('-------------------------------------------------------')\n print('time diff : ', end='')\n print(startb-starta)\n print('max number : %d' %maxnum)\n print('number of total prime numbers within maxnum : %d' %(noftrue+noffalse))\n print('ratio of prime numbers within maxnum : %f ' %((noftrue+noffalse)/maxnum))\n print('\\nnumber of true samples : %d' %noftrue)\n print('number of false samples : %d' %noffalse)\n print('ratio of true samples : %f' %(noftrue/(noftrue+noffalse)))\n\nif ispause > 0:\n input('enter key to end')\n","sub_path":"checkgdprimeguess.py","file_name":"checkgdprimeguess.py","file_ext":"py","file_size_in_byte":2055,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"5361928","text":"import urllib\n\ndef read_text():\n quotes = open(\"/Users/jordach/Documents/GitHub/NanoDegreeFullStackWebDev/CheckProfanity/movie_quotes.txt\")\n contents_of_file = quotes.read()\n print(contents_of_file)\n quotes.close()\n check_profanity(contents_of_file)\n\ndef check_profanity(text_to_check):\n connect = urllib.urlopen(\"http://www.wdylike.appspot.com/?q\"+text_to_check)\n output = connect.read()\n print(output)\n connect.close()\n if \"true\" in output:\n print(\"Profanity in Text!!!\")\n elif \"false\" in output:\n print(\"This document is free of curse words\")\n else:\n print(\"Error occured checking document for curse words\")\n \nread_text()\n","sub_path":"CheckProfanity/Check_Profanity.py","file_name":"Check_Profanity.py","file_ext":"py","file_size_in_byte":685,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"386482646","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Apr 11 22:54:42 2019\n\n@author: HP\n\"\"\"\nimport numpy as np\n#-----------------------------------------------------------------------------------------\nclass My_Metrics:\n #---------------------------------------------------\n def __init__(self):\n self.true_positive = []\n self.true_negative = []\n self.false_positive = []\n self.false_negative = []\n self.true_positives_length = 0\n self.true_negatives_length = 0\n self.false_negatives_length = 0\n self.false_positives_length = 0\n self.confusion_matrix_exists = False\n #print(\"\\t===================\\n\\tIn constructor\\n\\t===================\\n\")\n \n #---------------------------------------------------\n def confusion_matrix(self,actual,prediction):\n for i in range(len(actual)):\n if actual[i] == prediction[i] and actual[i] == 0:\n self.true_negative.append(i)\n \n if actual[i] == prediction[i] and actual[i] == 1:\n self.true_positive.append(i)\n \n if actual[i] != prediction[i]:\n if actual[i] == 1 and prediction[i] == 0:\n self.false_negative.append(i)\n if actual[i] == 0 and prediction[i] == 1:\n self.false_positive.append(i)\n \n self.true_positives_length = len(self.true_positive)\n self.true_negatives_length = len(self.true_negative)\n self.false_negatives_length = len(self.false_negative)\n self.false_positives_length = len(self.false_positive)\n confusionMatrix = np.array([\n [self.true_negatives_length, self.false_positives_length],\n [self.false_negatives_length, self.true_positives_length]\n ])\n self.confusion_matrix_exists = True\n return(confusionMatrix)\n \n #---------------------------------------------------\n def accuracy_score(self,actual,prediction):\n if not self.confusion_matrix_exists :\n self.confusion_matrix(actual,prediction)\n total_correct_predictions = self.true_negatives_length + self.true_positives_length\n total_incorrect_predictions = self.false_negatives_length + self.false_positives_length\n total_predictions = total_correct_predictions + total_incorrect_predictions\n accuracyScore = total_correct_predictions / total_predictions\n \n return(accuracyScore)\n \n #---------------------------------------------------\n def precision_score(self,actual,prediction):\n if not self.confusion_matrix_exists :\n self.confusion_matrix(actual,prediction)\n \n precisionScore = (self.true_positives_length / (self.true_positives_length + self.false_positives_length))\n \n return(precisionScore)\n \n #---------------------------------------------------\n def recall_score(self,actual,prediction):\n if not self.confusion_matrix_exists :\n self.confusion_matrix(actual,prediction)\n \n recallScore = (self.true_positives_length / (self.true_positives_length + self.false_negatives_length))\n \n return(recallScore)\n \n #---------------------------------------------------\n def f1_score(self,actual,prediction):\n precisionScore = self.precision_score(actual,prediction)\n recallScore = self.recall_score(actual,prediction)\n \n f1_Score = 2 * (precisionScore * recallScore) / (precisionScore + recallScore)\n \n return(f1_Score)\n \n# End of Class","sub_path":"ProcessBuilder_Test/ML_Pyhton_Programs/My_Custom_Metrics_Implementation.py","file_name":"My_Custom_Metrics_Implementation.py","file_ext":"py","file_size_in_byte":3671,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"451446646","text":"'''\n Author: Diogo Costa\n 014 - List Remove Duplicates\n \n Description: README.md\n'''\n\n\n# Version 1 using a loop and constructing a list\ndef removeDuplicatesV1(list):\n newList = []\n\n for cur in list:\n if cur in newList: continue\n newList.append(cur)\n\n return newList\n\n\n# Version 2 using set function\ndef removeDuplicatesV2(list):\n return set(list)\n\n\nif __name__ == \"__main__\":\n # Random List\n a = [1, 1, 1, 3, 4, 5]\n\n # Version 1 using a loop\n newList1 = removeDuplicatesV1(a)\n\n # Version 2 using a set() function\n newList2 = list(removeDuplicatesV2(a))\n\n # Print results\n print(f\"Version 1: {newList1}\")\n print(f\"Version 2: {newList2}\")","sub_path":"exercices/014 - List Remove Duplicates/014.py","file_name":"014.py","file_ext":"py","file_size_in_byte":693,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"48647537","text":"from django.urls import path,include\nfrom django.contrib import admin\n\n\nurlpatterns = [\n path('',include('home.urls')),\n path('login/',include('authentication.urls')),\n path('admin/', admin.site.urls),\n path('train/',include('trains.urls'))\n]\n","sub_path":"project/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":255,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"557284210","text":"from __future__ import print_function\nfrom sandpile import Sandpile, grid_edges\nimport networkx as nx\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport itertools\n\n\ndef score(G):\n ninc = sum([G.node[n0]['current'] for n0 in G.nodes() if (n0 != 'sink')])\n if ninc == 0:\n print('no nodes included',[G.node[n0]['current'] for n0 in G.nodes() if (n0 != 'sink')])\n return np.inf\n loss = sum([G.node[n0]['value'] for n0 in G.nodes() if (n0 != 'sink') and\n (G.node[n0]['current']==1)])**2\n\n return loss\n\n\ndef main(n_iter):\n np.random.seed(258)\n low,high=(-1000,1000)\n size = 50\n vals = np.random.randint(low,high,size)\n initial = np.random.random_integers(0,1,size)\n print('start',initial)\n edges = [[i,j] for i,j in itertools.permutations(range(size),2)] + [[k,'sink'] for k in range(size)]\n G = Sandpile(edges)\n s = {i:size*2 for i in range(size)}\n G.set_state(s)\n history = G.stabilize(hist=False)\n # for n_ in np.random.choice(range(size),size=25):\n # print(G.add_chip(n_))\n # print(G.get_state())\n for n0,val in enumerate(vals):\n G.node[n0]['value'] = val\n G.node[n0]['current'] = initial[n0]\n print(n0,G.node[n0])\n\n loss = score(G)\n loss0 = loss\n # print(initial)\n # for i in range(n):\n # print(initial[i*n:i*n+n])\n # print(loss)\n for i_ in range(n_iter):\n if i_ % 10000 == 0:\n print(i_,loss)\n print([G.node[node]['current'] for node in range(size)])\n n0 = np.random.choice(range(size),size=1)\n fires = G.add_chip(n0[0])\n if fires != {}:\n for v in fires.iterkeys():\n G.node[v]['previous'] = G.node[v]['current']\n G.node[v]['current'] = 1-G.node[v]['current']\n # for i in range(n):\n # print(final[i*n:i*n+n])\n loss1 = score(G)\n # print(loss1)\n if loss1 == 0:\n print('got to 0 after {}!'.format(i_))\n loss = loss1\n break\n elif loss1 <= loss:\n loss = loss1\n pass\n else:\n # print('reverting')\n for v in fires.iterkeys():\n G.node[v]['current'] = G.node[v]['previous']\n final = np.array([G.node[node]['current'] for node in range(size)])\n print('&'*80)\n print(vals)\n print('started',loss0)\n print(initial)\n print(loss)\n print('ended',loss)\n print(final)\n print('should be smallest sum: ',final*vals)\n print((final*vals).sum())\n print('searched {} configurations out of {} ({}%)'.format(i_,2**size,float(i_*100)/(2**size)))\n\n # print('stable:',G.is_stable())\n # print(G.get_state())\n # print(history)\n\n # np.random.seed(987)\n # nodes = np.random.randint(0,n**2,size=n_iter,dtype=int)\n # fires = map(G.add_chip,nodes)\n # fire_lengths = map(lambda x: len(x),fires)\n # plt.figure()\n # plt.hist(fire_lengths,bins=25)\n #\n # plt.savefig('soc_plots/power_rule.png')\n # plt.close()\n # idxs = np.random.choice([i for i,x in enumerate(fire_lengths) if x > 0],\n # size=20,replace=False)\n # # idxs.sort()\n # for idx in idxs:\n # plt.figure()\n # toplot = np.zeros((n,n))\n # h = map(lambda x: (int(x/n),x%n),fires[idx].keys())\n # for r,c in h:\n # toplot[r,c]=1\n # plt.imshow(toplot)\n # plt.savefig('soc_plots/avalanche_{}.png'.format(idx))\n # plt.close()\n\n\n\n\nif __name__ == '__main__':\n main(n_iter=1000000)\n","sub_path":"subset_sum.py","file_name":"subset_sum.py","file_ext":"py","file_size_in_byte":3581,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"35310543","text":"from django.contrib import admin\nfrom django.urls import path, include\n\nfrom . import views\n\nurlpatterns = [\n path('', views.HomePageView.as_view(), name='home'),\n path('register', views.RegisterView.as_view(), name='register'),\n path('login', views.LoginView.as_view(), name='login'),\n path('logout', views.logout, name='logout'),\n path('apis', include('apis.urls')),\n path('admin/', admin.site.urls),\n]\n","sub_path":"projex/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":423,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"44393582","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 ('grants', '0023_app_files_optional'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='grantcycle',\n name='amount_note',\n field=models.CharField(help_text=b'Text to display in parenthesis after \"Amount Requested\" in the grant application form', max_length=255, blank=True),\n ),\n ]\n","sub_path":"sjfnw/grants/migrations/0024_cycle_amount_note.py","file_name":"0024_cycle_amount_note.py","file_ext":"py","file_size_in_byte":521,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"367661647","text":"# -*- coding:utf-8 -*-\n'''\n# -------------------------------------------------\n# FileName: \t\tmerge.py\n# CreateDate: \t\t2020-07-12 17:36:39\n# Author: \t\t\tlibins\n# Contact:\t\t\tlibins.cn@gmail.com\n# LastModified: \t2020-07-12 17:36:40\n# SoftWare:\t\t\tVisual Studio Code\n# Description: \t\tLeetCode88题,合并两个有序数组\t\n# -------------------------------------------------\n'''\n\n\nclass Solution(object):\n def merge(self, nums1, m, nums2, n):\n # 定义三个索引\n id = m + n - 1\n id1 = m - 1\n id2 = n - 1\n while id >= 0:\n if id1 < 0: # 如果第第一个数组已经比较完毕,则直接将第二个数组的元素遍历出来放到对应下标的数组1即可\n for i in range(0, id2+1):\n nums1[i] = nums2[i]\n break\n if id2 < 0: # 如果第二个数组已经比较完毕,则说明合并完毕,则直接返回\n break\n # 如果第一个元素的当前最大值小于第二个数组的当前最大值,则将第二个元素的当前最大值放到此处,同时更新第二个元素的索引、以及合并比较的ID往前一位,\n if nums1[id1] <= nums2[id2]:\n nums1[id] = nums2[id2]\n id2 -= 1\n id -= 1\n continue\n if nums1[id1] > nums2[id2]:\n nums1[id] = nums1[id1]\n id1 -= 1\n id -= 1\n continue\n return nums1\n\n\nsolution = Solution\nnums1 = [2, 0]\nm = 1\nnums2 = [1]\nn = 1\nret = solution.merge(nums1, m, nums2, n)\nprint(ret)\n","sub_path":"merge.py","file_name":"merge.py","file_ext":"py","file_size_in_byte":1605,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"172786268","text":"# -*- coding: utf-8 -*-\n\n\"\"\"\nReference for testing Flask\n\n- Flask Documentation http://flask.pocoo.org/docs/0.12/testing/\n- Flask Cookbook: http://flask.pocoo.org/docs/0.12/tutorial/testing/\n\"\"\"\n\nimport logging\nimport unittest\n\nfrom pybel import BELGraph\nfrom pybel.examples import egf_graph\nfrom pybel.examples.homology_example import (\n homology_graph, mouse_csf1_protein, mouse_csf1_rna,\n mouse_mapk1_protein, mouse_mapk1_rna,\n)\nfrom pybel.examples.sialic_acid_example import dap12, shp1, shp2, sialic_acid_graph, syk, trem2\nfrom pybel_tools.mutation import collapse_by_central_dogma_to_genes, expand_internal, infer_central_dogma\nfrom pybel_tools.pipeline import Pipeline\nfrom pybel_tools.query import Query\nfrom pybel_tools.selection import get_subgraph_by_annotation_value\nfrom tests.constants import ExampleNetworkMixin, make_graph_1, protein_a_tuple\nfrom tests.mocks import MockQueryManager\n\nlog = logging.getLogger(__name__)\nlog.setLevel(10)\n\n\nclass TestMockManager(unittest.TestCase):\n def test_make(self):\n manager = MockQueryManager()\n self.assertEqual(0, manager.count_networks())\n\n def test_make_with_graph(self):\n graph_1 = make_graph_1()\n manager = MockQueryManager(graphs=[graph_1])\n self.assertEqual(1, manager.count_networks())\n\n\nclass QueryTest(ExampleNetworkMixin):\n def setUp(self):\n super(QueryTest, self).setUp()\n self.manager = MockQueryManager()\n\n def test_pipeline(self):\n test_graph_1 = self.graph_1 # Defined in test.constants.TestNetworks\n\n infer_central_dogma(test_graph_1)\n\n self.assertEqual(9, test_graph_1.number_of_nodes()) # 4 nodes already there + 2*2 proteins + 1 (rna)\n self.assertEqual(8, test_graph_1.number_of_edges()) # 3 already there + 2*2 proteins + 1 (rna)\n\n network = self.manager.insert_graph(test_graph_1)\n\n pipeline = Pipeline()\n pipeline.append(collapse_by_central_dogma_to_genes)\n\n query = Query(\n network_ids=[network.id],\n pipeline=pipeline\n )\n result_graph = query.run(self.manager)\n\n self.assertEqual(4, result_graph.number_of_nodes()) # same number of nodes than there were\n self.assertEqual(3, result_graph.number_of_edges()) # same number of edges than there were\n\n def test_pipeline_2(self):\n test_network = self.graph_1 # Defined in test.constants.TestNetworks\n\n infer_central_dogma(test_network)\n\n network = self.manager.insert_graph(test_network)\n network_id = network.id\n\n pipeline = Pipeline()\n pipeline.append(get_subgraph_by_annotation_value, 'Annotation', 'foo')\n\n query = Query(network_ids=[network_id])\n query.append_seeding_neighbors([\n protein_a_tuple\n ])\n query.pipeline = pipeline\n\n result = query.run(self.manager, in_place=False)\n self.assertIsNotNone(result, msg='Query returned none')\n\n self.assertEqual(3, result.number_of_nodes()) # only expanded to node protein_a and gene_c\n self.assertEqual(2, result.number_of_edges()) # three nodes with two relationships\n\n def test_query_multiple_networks(self):\n egf_network = self.manager.insert_graph(sialic_acid_graph.copy())\n sialic_acid_network = self.manager.insert_graph(egf_graph.copy())\n\n query = Query()\n query.append_network(egf_network.id)\n query.append_network(sialic_acid_network.id)\n query.append_seeding_neighbors([syk.as_tuple()])\n query.append_pipeline(infer_central_dogma)\n\n result = query.run(self.manager, in_place=False)\n self.assertIsNotNone(result, msg='Query returned none')\n\n self.assertIn(shp1.as_tuple(), result)\n self.assertIn(shp2.as_tuple(), result)\n self.assertIn(trem2.as_tuple(), result)\n self.assertIn(dap12.as_tuple(), result)\n\n self.assertEqual(15, result.number_of_nodes())\n self.assertEqual(14, result.number_of_edges())\n\n def test_get_subgraph_by_annotation_value(self):\n graph = homology_graph.copy()\n\n result = get_subgraph_by_annotation_value(graph, 'Species', '10090')\n self.assertIsNotNone(result, msg='Query returned none')\n self.assertIsInstance(result, BELGraph)\n\n self.assertIn(mouse_mapk1_protein.as_tuple(), result)\n self.assertIn(mouse_csf1_protein.as_tuple(), result)\n\n self.assertEqual(2, result.number_of_nodes())\n self.assertEqual(1, result.number_of_edges())\n\n def test_seeding_1(self):\n test_network_1 = self.manager.insert_graph(homology_graph.copy())\n\n query = Query(network_ids=[test_network_1.id])\n query.append_seeding_neighbors([mouse_csf1_rna, mouse_mapk1_rna])\n\n result = query.run(self.manager, in_place=False)\n self.assertIsNotNone(result, msg='Query returned none')\n self.assertIsInstance(result, BELGraph)\n\n self.assertIn(mouse_mapk1_rna.as_tuple(), result)\n self.assertIn(mouse_csf1_rna.as_tuple(), result)\n self.assertIn(mouse_mapk1_protein.as_tuple(), result)\n self.assertIn(mouse_csf1_protein.as_tuple(), result)\n\n self.assertEqual(6, result.number_of_nodes())\n self.assertEqual(4, result.number_of_edges())\n\n def test_seeding_with_pipeline(self):\n test_network_1 = self.manager.insert_graph(homology_graph.copy())\n\n query = Query(network_ids=[test_network_1.id])\n query.append_seeding_neighbors([mouse_csf1_rna, mouse_mapk1_rna])\n query.append_pipeline(expand_internal)\n result = query.run(self.manager, in_place=False)\n self.assertIsNotNone(result, msg='Query returned none')\n self.assertIsInstance(result, BELGraph)\n\n self.assertIn(mouse_mapk1_rna.as_tuple(), result)\n self.assertIn(mouse_csf1_rna.as_tuple(), result)\n self.assertIn(mouse_mapk1_protein.as_tuple(), result)\n self.assertIn(mouse_csf1_protein.as_tuple(), result)\n\n self.assertEqual(6, result.number_of_nodes())\n self.assertEqual(5, result.number_of_edges())\n\n def test_query_multiple_networks_with_api(self):\n test_network_1 = self.manager.insert_graph(homology_graph.copy())\n\n pipeline = Pipeline()\n pipeline.append(expand_internal)\n pipeline.append(get_subgraph_by_annotation_value, 'Species', '10090')\n\n query = Query(\n network_ids=[test_network_1.id],\n pipeline=pipeline\n )\n query.append_seeding_neighbors([mouse_csf1_rna, mouse_mapk1_rna])\n\n result = query.run(self.manager, in_place=False)\n self.assertIsNotNone(result, msg='Query returned none')\n\n self.assertEqual(2, result.number_of_nodes())\n self.assertIn(mouse_mapk1_protein.as_tuple(), result)\n self.assertIn(mouse_csf1_protein.as_tuple(), result)\n\n self.assertEqual(1, result.number_of_edges())\n","sub_path":"tests/test_query.py","file_name":"test_query.py","file_ext":"py","file_size_in_byte":6878,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"212793732","text":"\"\"\"\nThis should be a module description.\n\"\"\"\n\n# nessesary to force parens around print arguments.\nfrom __future__ import print_function\n\ndef __valid_line(text):\n \"\"\"\n Checks whether a line is to be kept wrt. options.\n \"\"\"\n if text[0:14] == \"\"))\n val2 = (not __valid_line(\"\"))\n val3 = (__valid_line(\\\n \" \"))\n\n if not val1:\n print (\" fail at val1\")\n if not val2:\n print (\" fail at val2\")\n if not val3:\n print (\" fail at val3\")\n\n return val1 and val2 and val3\n\n\nif __name__ == \"__main__\":\n tests()\n main()\n","sub_path":"python3stuff/aplanetConverter/ap_to_ma.py","file_name":"ap_to_ma.py","file_ext":"py","file_size_in_byte":1830,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"106764682","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\nfrom typing import List\n\n\ndef convert_to_absolute(number: float) -> float:\n if number < 0:\n number -= 2*number\n return number\n else:\n return number\n\n\ndef use_prefixes() -> List[str]:\n prefixes, suffixe = 'JKLMNOPQ', 'ack'\n mots = []\n for letter in prefixes:\n mots.append(letter + suffixe)\n return mots\n\n\ndef prime_integer_summation() -> int:\n count = 0\n valid = 0\n for num in range(2, 101):\n for i in range (1,101):\n if num % i == 0:\n valid += 1\n if valid == 2:\n count += num\n valid = 0\n return count\n \n\ndef factorial(number: int) -> int:\n mul = 1\n for num in range (1, number):\n mul = mul + num * mul\n return mul\n\n\ndef use_continue() -> None:\n for i in range(1, 11):\n if i != 5:\n print(i)\n\n\ndef verify_ages(groups: List[List[int]]) -> List[bool]:\n valid = True\n acceptance = []\n for group in groups:\n twofive = False\n fifty = False\n older_70 = False\n valid = True\n for person in group:\n if person < 18:\n valid = False\n if person > 70:\n older_70 = True\n if person == 25:\n twofive = True\n if person == 50:\n fifty = True\n if len(group) > 10 or len(group) <= 3:\n valid = False\n elif older_70 and fifty:\n valid = False\n if twofive:\n valid = True\n if valid:\n acceptance.append(True)\n else:\n acceptance.append(False)\n return acceptance\n\n\ndef main() -> None:\n number = -4.325\n print(f\"La valeur absolue du nombre {number} est {convert_to_absolute(number)}\")\n\n print(f\"La liste des noms générés avec les préfixes est: {use_prefixes()}\")\n\n print(f\"La somme des 100 premiers nombre premier est : {prime_integer_summation()}\")\n\n number = 10\n print(f\"La factiorelle du nombre {number} est: {factorial(number)}\")\n \n print(f\"L'affichage de la boucle est:\")\n use_continue()\n\n groups = [\n [15, 28, 65, 70, 72], [18, 24, 22, 50, 70], [25, 2],\n [20, 22, 23, 24, 18, 75, 51, 49, 100, 18, 20, 20], [70, 50, 26, 28], [75, 50, 18, 25],\n [13, 25, 80, 15], [20, 30, 40, 50, 60], [75, 50, 100, 28]\n ]\n print(f\"Les différents groupes sont: {groups}\")\n print(f\"L'acceptance des groupes est: {verify_ages(groups)}\")\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"exercice.py","file_name":"exercice.py","file_ext":"py","file_size_in_byte":2558,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"70196315","text":"\"\"\"Input parameter class for network executable.\"\"\"\nfrom voluptuous import Schema, ExactSequence, Any\nfrom aiida.orm import Dict\nfrom aiida.plugins import DataFactory\nimport aiida_zeopp.parsers.plain as pp\n\n# These options allow specifying the name of the output file\n# key : [ accepted values, labels ]\nOUTPUT_OPTIONS = {\n 'cssr': (bool, ['structure_cssr']),\n 'v1': (bool, ['structure_v1']),\n 'xyz': (bool, ['structure_xyz']),\n 'nt2': (bool, ['network_nt2']),\n 'res': (bool, ['free_sphere_res']),\n 'zvis': (bool, ['network_zvis']),\n 'axs': (float, ['nodes_axs']),\n 'visVoro': (float, ['voro', 'voro_accessible', 'voro_nonaccessible']),\n 'sa': (ExactSequence([float, float, int]), ['surface_area_sa']),\n 'vsa': (ExactSequence([float, float, int]), ['surface_sample_vsa']),\n 'vol': (ExactSequence([float, float, int]), ['volume_vol']),\n 'volpo': (ExactSequence([float, float, int]), ['pore_volume_volpo']),\n 'ray_atom': (ExactSequence([float, float, int]), ['ray_atom']),\n 'block': (ExactSequence([float, int]), ['block']),\n 'psd': (ExactSequence([float, float, int]), ['psd']),\n 'chan': (float, ['channels_chan']),\n 'gridG': (bool, ['grid_gaussian']),\n 'gridGBohr': (bool, ['grid_gaussian_bohr']),\n 'strinfo': (bool, ['str_info']),\n 'oms': (bool, ['open_metal_sites']),\n}\n\n# Currently NOT implemented\n# These options produce an output file with a hardcoded name\n# key : [ accepted values, [ output file name(s) ], label ]\n#fixed_OUTPUT_OPTIONS = {\n# 'gridBOV': (bool, ['{}_f.bov', '{}_f.distances'], 'grid_bov'),\n#}\n\nHA_OPTIONS = [\n 'OCC',\n 'FCC',\n 'ACC',\n 'AQC',\n 'DDH',\n 'TIH',\n 'ICH',\n 'ICC',\n 'RIH',\n 'S4',\n 'S10',\n 'S20',\n 'S30',\n 'S40',\n 'S50',\n 'S100',\n 'S500',\n 'S1000',\n 'S10000',\n 'DEF',\n 'HI',\n 'MED',\n 'LOW',\n]\n\n# These options modify the output of other options\n# key : [ accepted values, label ]\nMODIFIER_OPTIONS = {\n 'ha': (Any(bool, *HA_OPTIONS), ['high_accuracy']),\n 'stripatomnames': (bool, ['strip_atom_names']),\n 'nor': (bool, ['no_radial']),\n 'allowAdjustCoordsAndCell': (bool, ['allow_adjust_coords_and_cell']),\n}\n\nALL_OPTIONS = dict(\n list(OUTPUT_OPTIONS.items()) + list(MODIFIER_OPTIONS.items()))\n\n\nclass NetworkParameters(Dict):\n \"\"\" Command line parameters for zeo++ network binary\n \"\"\"\n\n _schema = Schema({k: ALL_OPTIONS[k][0] for k in ALL_OPTIONS})\n schema = _schema.schema # alias for easier printing\n\n _OUTPUT_FILE_PREFIX = 'out.{}'\n\n # pylint: disable=redefined-builtin, too-many-function-args\n def __init__(self, dict=None, **kwargs):\n \"\"\"\n Constructor for the data class\n\n :param dict: the dictionary to set\n\n Usage: ``NetworkParameters(dict={'cssr': True})``\n \"\"\"\n dict = self.validate(dict)\n super(NetworkParameters, self).__init__(dict=dict, **kwargs)\n\n @classmethod\n def validate(cls, parameters_dict):\n \"\"\"validate parameters\"\"\"\n return cls._schema(parameters_dict)\n\n def cmdline_params(self, structure_file_name=None, radii_file_name=None):\n \"\"\"Synthesize command line parameters\n\n e.g. [ '-axs', '0.4', 'out.axs', 'structure.cif']\n \"\"\"\n parameters = []\n\n if radii_file_name is not None:\n parameters += ['-r', radii_file_name]\n\n pm_dict = self.get_dict()\n output_keys = self.output_keys\n\n for k, val in pm_dict.items():\n\n parameter = ['-{}'.format(k)]\n if isinstance(val, bool):\n # if boolean is false, no parameter to add\n if not val:\n continue\n elif isinstance(val, list):\n parameter += val\n else:\n parameter += [val]\n\n # add output file name(s)\n # Note: For visVoro option, only one (prefix) can be specified\n if k in output_keys:\n parameter += [self._OUTPUT_FILE_PREFIX.format(k)]\n\n parameters += parameter\n\n if structure_file_name is not None:\n parameters += [structure_file_name]\n\n return list(map(str, parameters))\n\n @property\n def output_dict(self):\n \"\"\"Return dictionary of specified options requiring an output file name.\n\n Keys are the selected options that require an output file name,\n values are the file names.\n \"\"\"\n output_dict = {}\n\n parameters_dict = self.get_dict()\n\n for k in parameters_dict:\n if k not in OUTPUT_OPTIONS:\n continue\n\n if parameters_dict[k] is False:\n continue\n\n nfiles = len(OUTPUT_OPTIONS[k][1])\n if nfiles == 1:\n output_dict[k] = [self._OUTPUT_FILE_PREFIX.format(k)]\n else:\n # if multiple files, append link labels\n labels = OUTPUT_OPTIONS[k][1]\n output_dict[k] = [\n self._OUTPUT_FILE_PREFIX.format(k) + '.{}'.format(label)\n for label in labels\n ]\n\n return output_dict\n\n @property\n def output_keys(self):\n \"\"\"Return subset of specified options requiring an output file name.\n\n Out of the selected options, return those that you need to specify an\n output file name for.\n \"\"\"\n return list(self.output_dict.keys())\n\n @property\n def output_files(self):\n \"\"\"Return list of output files to be retrieved\"\"\"\n # Note: This flattens list(self.output_dict.values())\n return [item for files in self.output_dict.values() for item in files]\n\n @property\n def output_parsers(self):\n \"\"\"Return list of output parsers to use.\n\n :param parameters: the parameters object used to generate the cmdline parameters\n :type parameters: aiida_zeopp.data.parameters.NetworkParameters\n\n :returns: List of parsers to be used for each output file.\n List element is None, if parser is not implemented.\n :rtype: list\n \"\"\"\n parsers = []\n for k in self.output_dict:\n if k == 'vol':\n parsers += [pp.AVolumeParser]\n elif k == 'volpo':\n parsers += [pp.PoreVolumeParser]\n elif k == 'sa':\n parsers += [pp.SurfaceAreaParser]\n elif k == 'res':\n parsers += [pp.ResParser]\n elif k == 'chan':\n parsers += [pp.ChannelParser]\n elif k == 'psd':\n parsers += [pp.PoresSizeDistParser]\n elif k == 'visVoro':\n parsers += [None for _f in OUTPUT_OPTIONS[k][1]]\n #elif k == 'cssr':\n # parsers += [sp.CssrParser]\n else:\n parsers += [None]\n\n return parsers\n\n @property\n def output_links(self):\n \"\"\"Return list of output link names\"\"\"\n output_links = []\n for k in self.output_keys:\n output_links += OUTPUT_OPTIONS[k][1]\n return output_links\n\n def get_structure_file_name(self, structure): # pylint: disable=no-self-use\n \"\"\"Get file name of input structure.\n\n The 'network; binary detects file formats by file extension.\n We therefore need to make sure that the file extension of the input file matches its format.\n\n :param structure: Structure input of plugin\n :returns: input file name\n :rtype: str\n\n \"\"\"\n\n # treating only CifData for the moment - could extend to other formats in the future\n if isinstance(structure, DataFactory('cif')):\n return structure.filename if structure.filename.endswith(\n '.cif') else structure.filename + '.cif'\n\n raise ValueError('Input structure has unknown type {}'.format(\n type(structure)))\n","sub_path":"aiida_zeopp/data/parameters.py","file_name":"parameters.py","file_ext":"py","file_size_in_byte":7858,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"171276542","text":"# Pruebas usando algoritmo de diferencia entre cuadros para deteccion de\n# movimiento, pero usado para restar el fondo\n\nimport numpy as np\nimport cv2 as cv\n\nkernel = np.ones((20,20),np.uint8)\n\nimg = cv.imread('haz.JPG',1)\nfondo = cv.imread('fondo.JPG',1)\n\nimg = cv.cvtColor(img, cv.COLOR_BGR2GRAY)\nfondo = cv.cvtColor(fondo, cv.COLOR_BGR2GRAY)\n\nfgbg = cv.createBackgroundSubtractorMOG2()\n\nfgmask = fgbg.apply(img)\nfgmask = fgbg.apply(fondo)\n\nimg_final=cv.morphologyEx(fgmask, cv.MORPH_OPEN, kernel)\n\ncv.namedWindow('img', cv.WINDOW_NORMAL)\ncv.imshow('img', img_final)\n\ncv.waitKey(0)\ncv.destroyAllWindows()\n","sub_path":"backgroundremove.py","file_name":"backgroundremove.py","file_ext":"py","file_size_in_byte":606,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"366343268","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.7 (3394)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: /home/mad/Documents/spike/spike/File/Solarix.py\n# Compiled at: 2019-08-14 15:56:48\n# Size of source mod 2**32: 18826 bytes\n\"\"\"\nSolarix.py\n\n Utility to Handle Solarix files\n\nCreated by mac on 2013-05-24.\nupdated may 2017 to python 3, added compress option\n\nCopyright (c) 2013 __NMRTEC__. All rights reserved.\n\"\"\"\nfrom __future__ import print_function, division\nimport sys, os, unittest, glob\nimport os.path as op\nimport numpy as np, array, tables\nfrom xml.dom import minidom\nfrom time import time\nimport math\nfrom .. import NPKData as npkd\nfrom ..FTICR import FTICRData\nfrom ..File import HDF5File as hf\nif sys.version_info[0] < 3:\n pass\nelse:\n xrange = range\n\ndef read_param(parfilename):\n \"\"\"\n Open the given file and retrieve all parameters from apexAcquisition.method\n NC is written when no value for value is found\n \n structure : 0\n \n read_param returns values in a dictionnary\n \"\"\"\n xmldoc = minidom.parse(parfilename)\n x = xmldoc.documentElement\n pp = {}\n children = x.childNodes\n for child in children:\n if child.nodeName == 'paramlist':\n params = child.childNodes\n for param in params:\n if param.nodeName == 'param':\n k = str(param.getAttribute('name'))\n for element in param.childNodes:\n if element.nodeName == 'value':\n try:\n v = str(element.firstChild.toxml())\n except:\n v = 'NC'\n\n pp[k] = v\n\n return pp\n\n\ndef read_scan(filename):\n \"\"\"\n Function that returns the number of scan that have been recorded\n It is used to see wether the number of recorded points corresponds to the L_20 parameter\n \"\"\"\n xmldoc = minidom.parse(filename)\n x = xmldoc.documentElement\n pp = {}\n children = x.childNodes\n count_scan = 0\n for child in children:\n if child.nodeName == 'scan':\n count_scan += 1\n\n return count_scan\n\n\ndef read_ExciteSweep(filename):\n \"\"\"\n Function that returns the lower and higher frequency of the pulse generator\n \"\"\"\n ExciteSweep_lines = np.genfromtxt(filename, comments='*', delimiter='\\n')\n highfreq = np.fromstring(ExciteSweep_lines[0])\n lowfreq = np.fromstring(ExciteSweep_lines[(-1)])\n return (lowfreq, highfreq)\n\n\ndef get_param(param, names, values):\n \"\"\"\n From params, this function returns the value of the given param\n \"\"\"\n for i in xrange(len(names)):\n if names[i] == param:\n return values[i]\n\n\ndef locate_acquisition(folder):\n \"\"\"\n From the given folder this function return the absolute path to the apexAcquisition.method file\n It should always be in a subfolder \n \"\"\"\n L = glob.glob(op.join(folder, '*', 'apexAcquisition.method'))\n if len(L) > 1:\n raise Exception('You have more than 1 apexAcquisition.method file in the %s folder, using the first one' % folder)\n else:\n if len(L) == 0:\n raise Exception(\"You don't have any apexAcquisition.method file in the %s folder, please double check the path\" % folder)\n return L[0]\n\n\ndef locate_ExciteSweep(folder):\n \"\"\"\n From the given folder this function return the absolute path to the ExciteSweep file\n It should always be in a subfolder \n \"\"\"\n L = glob.glob(op.join(folder, '*', 'ExciteSweep'))\n if len(L) > 1:\n raise Exception('You have more than 1 ExciteSweep file in the %s folder, using the first one' % folder)\n else:\n if len(L) == 0:\n raise Exception(\"You don't have any ExciteSweep file in the %s folder, please double check the path\" % folder)\n return L[0]\n\n\ndef Import_1D(inifolder, outfile='', compress=False):\n \"\"\"\n Entry point to import 1D spectra\n It returns a FTICRData\n It writes a HDF5 file if an outfile is mentionned\n \"\"\"\n if sys.maxsize == 2147483647:\n flag = 'l'\n else:\n flag = 'i'\n if op.isfile(inifolder):\n folder = op.dirname(inifolder)\n else:\n if op.isdir(inifolder):\n folder = inifolder\n else:\n if not op.exists(inifolder):\n raise Exception('File does not exist: ' + inifolder)\n else:\n raise Exception('File is undecipherable: ' + inifolder)\n try:\n parfilename = locate_acquisition(folder)\n except:\n raise Exception('%s does not seem to be a valid Solarix spectrum' % (inifolder,))\n\n params = read_param(parfilename)\n sizeF1 = int(params['TD'])\n if os.path.isfile(os.path.join(folder, 'fid')):\n fname = os.path.join(folder, 'fid')\n else:\n raise Exception('You are dealing with 2D data, you should use Import_2D')\n data = FTICRData(dim=1)\n data.axis1.size = sizeF1\n data.axis1.specwidth = float(params['SW_h'])\n try:\n l, h = read_ExciteSweep(locate_ExciteSweep(folder))\n except:\n data.axis1.highfreq = float(params['EXC_Freq_High'])\n data.axis1.lowfreq = float(params['EXC_Freq_Low'])\n else:\n data.axis1.lowfreq, data.axis1.highfreq = l, h\n data.axis1.highmass = float(params['MW_high'])\n data.axis1.left_point = 0\n data.axis1.offset = 0.0\n data.axis1.calibA = float(params['ML1'])\n data.axis1.calibB = float(params['ML2'])\n data.axis1.calibC = float(params['ML3'])\n if not math.isclose(data.axis1.calibC, 0.0):\n print('Using 3 parameters calibration, Warning calibB is -ML2')\n data.axis1.calibB *= -1\n else:\n data.params = params\n if outfile:\n HF = hf.HDF5File(outfile, 'w', compress=compress)\n HF.create_from_template(data)\n HF.store_internal_object(params, h5name='params')\n HF.store_internal_file(parfilename)\n HF.store_internal_file(locate_ExciteSweep(folder))\n data.hdf5file = HF\n else:\n data.buffer = np.zeros(sizeF1)\n data.adapt_size()\n with open(fname, 'rb') as (f):\n tbuf = f.read(4 * sizeF1)\n abuf = np.array(array.array(flag, tbuf))\n data.buffer[:] = abuf[:]\n if outfile:\n HF.flush()\n return data\n\n\ndef Import_2D(folder, outfile='', F1specwidth=None, compress=False):\n \"\"\"\n Entry point to import 2D spectra\n It returns a FTICRData\n It writes a HDF5 file if an outfile is mentionned\n \n compression (compress=True) is efficient, but takes a lot of time.\n \"\"\"\n if sys.maxsize == 2147483647:\n flag = 'l'\n else:\n flag = 'i'\n parfilename = locate_acquisition(folder)\n params = read_param(parfilename)\n sizeF1 = read_scan(os.path.join(folder, 'scan.xml'))\n sizeF2 = int(params['TD'])\n if os.path.isfile(os.path.join(folder, 'ser')):\n fname = os.path.join(folder, 'ser')\n else:\n raise Exception('You are dealing with 1D data, you should use Import_1D')\n data = FTICRData(dim=2)\n data.axis2.size = sizeF2\n data.axis2.specwidth = float(params['SW_h'])\n try:\n l, h = read_ExciteSweep(locate_ExciteSweep(folder))\n except:\n data.axis2.highfreq = float(params['EXC_Freq_High'])\n data.axis2.lowfreq = float(params['EXC_Freq_Low'])\n else:\n data.axis2.lowfreq, data.axis2.highfreq = l, h\n data.axis2.highmass = float(params['MW_high'])\n data.axis2.left_point = 0\n data.axis2.offset = 0.0\n data.axis2.calibA = float(params['ML1'])\n data.axis2.calibB = float(params['ML2'])\n data.axis2.calibC = float(params['ML3'])\n if not math.isclose(data.axis2.calibC, 0.0):\n print('Using 3 parameters calibration, Warning calibB is -ML2')\n data.axis2.calibB *= -1\n else:\n data.axis1.size = sizeF1\n if F1specwidth is not None:\n data.axis1.specwidth = F1specwidth\n else:\n f1 = float(params['IN_26'])\n if f1 < 0.0001:\n data.axis1.specwidth = 1.0 / (2 * f1)\n else:\n data.axis1.specwidth = data.axis2.specwidth\n data.axis1.highfreq = data.axis2.highfreq\n data.axis1.lowfreq = data.axis2.lowfreq\n data.axis1.highmass = float(params['MW_high'])\n data.axis1.left_point = 0\n data.axis1.offset = 0.0\n data.axis1.calibA = data.axis2.calibA\n data.axis1.calibB = data.axis2.calibB\n data.axis1.calibC = data.axis2.calibC\n data.params = params\n c1 = int(sizeF1 / 8.0 + 1)\n c2 = int(sizeF2 / 8.0 + 1)\n if outfile:\n HF = hf.HDF5File(outfile, 'w')\n if compress:\n HF.set_compression(True)\n HF.create_from_template(data)\n HF.store_internal_object(params, h5name='params')\n HF.store_internal_file(parfilename)\n HF.store_internal_file(os.path.join(folder, 'scan.xml'))\n HF.store_internal_file(locate_ExciteSweep(folder))\n data.hdf5file = HF\n else:\n data.buffer = np.zeros((sizeF1, sizeF2))\n with open(fname, 'rb') as (f):\n for i1 in xrange(sizeF1 - 1):\n tbuf = f.read(4 * sizeF2)\n abuf = np.array(array.array(flag, tbuf))\n data.buffer[i1, :] = abuf[:]\n\n if outfile:\n HF.flush()\n return data\n\n\ndef read_2D(sizeF1, sizeF2, filename='ser'):\n \"\"\"\n Reads in a Solarix 2D fid\n\n sizeF1 is the number of fid\n sizeF2 is the number of data-points in the fid\n uses array\n \"\"\"\n if sys.maxsize == 2147483647:\n flag = 'l'\n else:\n flag = 'i'\n sz1, sz2 = int(sizeF1), int(sizeF2)\n fbuf = np.empty((sz1, sz2))\n with open(filename, 'rb') as (f):\n for i1 in xrange(sz1):\n tbuf = f.read(4 * sz2)\n abuf = array.array(flag, tbuf)\n fbuf[i1, 0:sz2] = abuf[0:sz2]\n\n return FTICRData(buffer=fbuf)\n\n\ndef read_3D(sizeF1, sizeF2, sizeF3, filename='ser'):\n \"\"\"\n Ebauche de fonction\n \n Reads in a Apex 3D fid\n\n uses array\n \"\"\"\n if sys.maxsize == 2147483647:\n flag = 'l'\n else:\n flag = 'i'\n sz1, sz2, sz3 = int(sizeF1), int(sizeF2), int(sizeF3)\n fbuf = np.empty((sz1, sz2, sz3))\n with open(filename, 'rb') as (f):\n for i1 in xrange(sz1):\n tbuf = f.read(4 * sz2)\n abuf = array.array(flag, tbuf)\n fbuf[i1, 0:sz2] = abuf[0:sz2]\n\n return FTICRData(buffer=fbuf)\n\n\ndef write_ser(bufferdata, filename='ser'):\n \"\"\"\n Write a ser file from FTICRData\n \"\"\"\n with open(filename, 'wb') as (f):\n for i in range(len(bufferdata)):\n for j in range(len(bufferdata[0])):\n f.write(bufferdata[i][j].astype('int32').tostring())\n\n\nclass Solarix_Tests(unittest.TestCase):\n\n def setUp(self):\n from ..Tests import filename, directory\n import ConfigParser\n rootfiles = os.getcwd()\n self.TestFolder = directory()\n self.DataFolder = filename('bilirubin_2D_000001.d')\n self.serfile = filename('bilirubin_2D_000001.d/ser')\n self.outHDF = filename('bilirubin_2D_000001.direct.msh5')\n self.name_write = filename('file_write')\n self.name_fticr = filename('file_fticr')\n self.name_npar = filename('file_npar')\n self.npar_fticr = filename('npar_fticr')\n self.name_chunk = filename('Chunk.hf')\n self.name_get = filename('file_fticr')\n self.verbose = 1\n\n def announce(self):\n if self.verbose > 0:\n print('\\n========', self.shortDescription(), '===============')\n\n def _test_Import_2D(self):\n \"\"\"Test and time routine that import 2D from the MS-FTICR folder to the file given as second argument \"\"\"\n self.announce()\n t0 = time()\n d = Import_2D(self.DataFolder, self.name_get)\n print('import', time() - t0, 'secondes')\n\n def _test_Import_2D_keep_mem(self):\n \"\"\"Test and time routine that import 2D from the MS-FTICR folder in memory\"\"\"\n from ..Tests import filename, directory\n self.announce()\n t0 = time()\n d = filename('subP_2D_000001.d')\n print('import', time() - t0, 'secondes')\n\n def _test_2(self):\n \"\"\" Test and time direct processing\"\"\"\n self.announce()\n d = Import_2D(self.DataFolder)\n t0 = time()\n t00 = t0\n d.rfft(axis=2)\n print('rfft2', time() - t0, 'secondes')\n t0 = time()\n d.rfft(axis=1)\n print('rfft1', time() - t0, 'secondes')\n t0 = time()\n d.modulus()\n print('modulus', time() - t0, 'secondes')\n t0 = time()\n print('modulus', time() - t0, 'secondes')\n print('calcul', time() - t00, 'secondes')\n d.display(scale=30, show=True)\n d.fticrfile.close()\n\n def _test_3(self):\n \"\"\"Another strategy close the file after fft on F2 and reopen everything for F1 fft\"\"\"\n from ..Tests import filename, directory\n self.announce()\n d = Import_2D(self.DataFolder, filename('essai.ap'))\n t0 = time()\n t00 = t0\n d.rfft(axis=2)\n d.fticrfile.close()\n print('rfft2', time() - t0, 'secondes')\n t0 = time()\n F = ff(filename('essai.ap'), 'rw')\n F.load()\n d2 = F.data\n d2.rfft(axis=1)\n print('rfft1', time() - t0, 'secondes')\n t0 = time()\n d2.modulus()\n print('modulus', time() - t0, 'secondes')\n t0 = time()\n print('modulus', time() - t0, 'secondes')\n print('calcul', time() - t00, 'secondes')\n d2.display(scale=5, show=True)\n F.close()\n H = ff(filename('essai.ap'), 'r')\n H.load()\n B = H.data\n H.close()\n\n\nif __name__ == '__main__':\n unittest.main()","sub_path":"pycfiles/spike_py-0.99.17.tar/Solarix.cpython-37.py","file_name":"Solarix.cpython-37.py","file_ext":"py","file_size_in_byte":13939,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"142267261","text":"# python2 - function handler\n\nfrom PIL import Image\nfrom skimage.transform import resize\nimport cv2\nimport glob\nimport numpy as np\n\ndef rgbImage_equalizeHist(img):\n # input: numpy array (rgb image)\n # return numpy array (rgb image)\n img_YCrCb = cv2.cvtColor(img, cv2.COLOR_RGB2YCrCb)\n c1, c2, c3 = cv2.split(img_YCrCb)\n c1 = cv2.equalizeHist(c1)\n img_back = cv2.merge((c1,c2,c3))\n img_back = cv2.cvtColor(img_back, cv2.COLOR_YCrCb2RGB)\n return img_back\n\n\ndef img_rand_crop(img, crop_range, target_range):\n # img: 3d-array\n # crop_range: tuple\n # target range: tuple\n cx, cy = crop_range\n max_x, max_y = img.shape[0:2]\n img_w, img_h = target_range\n \n # define max border\n anchor_x_range = max_x - cx\n anchor_y_range = max_y - cy\n # random get\n x_left = np.random.randint(anchor_x_range)\n y_top = np.random.randint(anchor_y_range)\n #\n im_get = img[x_left:x_left+cx, y_top:y_top+cy, :]\n im_get = np.array(resize(im_get, (img_w,img_h), mode = 'reflect'))\n return im_get\n\ndef img_center_crop(img, target_size):\n # return center cropprd image (not resizing)\n # img should be a PIL image object\n # target size should be a tuple, eg (224, 224)\n width, height = img.size\n left = (width - target_size[0])/2\n right = (width + target_size[0])/2\n top = (height - target_size[1])/2\n bottom = (height + target_size[1])/2\n \n img.crop((left, top, right, bottom))\n return(img)\n\n### Image with t-sne reduction -- visualization module\ndef min_resize(img, size):\n w, h = map(float, img.shape[:,2])\n if min([w, h]) != size:\n if w <= h:\n img = resize(img, (int(round((h/w)*size)), int(size)))\n else:\n img = resize(img, (int(size), int(round((w/h)*size))))\n return img\n\ndef img_resize(img, size):\n img = resize(img, (size, size))\n\ndef gray_to_color(img):\n if len(img.shape) == 2:\n img = np.dstack([img] * 3)\n return img\n\ndef image_scatter(tsne_features, images, res = 1024, cval = 1.):\n # tsne_features: projection of tsne\n # images: np.array list of images (4-D or 3D, N x img_w x img_h) -- in RGB / gray\n # img_res: single image size\n # res: full image res\n # cval: backgroud color value\n tsne_features = tsne_features.astype('float64')\n images = [gray_to_color(image) for image in images]\n images = np.array(images)\n #images = [min_resize(image, img_res) for image in images]\n \n max_width = max([image.shape[0] for image in images])\n max_height = max([image.shape[1] for image in images])\n \n xx = tsne_features[:, 0]\n yy = tsne_features[:, 1]\n\n x_min, x_max = xx.min(), xx.max()\n y_min, y_max = yy.min(), yy.max()\n\n sx = (x_max-x_min)\n sy = (y_max-y_min)\n if sx > sy:\n res_x = sx/float(sy)*res\n res_y = res\n else:\n res_x = res\n res_y = sy/float(sx)*res\n #print(res_x, res_y, max_width, max_height)\n res_x = int(res_x)\n res_y = int(res_y)\n \n canvas = np.ones((res_x+max_width, res_y+max_height, 3))*cval\n x_coords = np.linspace(x_min, x_max, res_x)\n y_coords = np.linspace(y_min, y_max, res_y)\n\n for x,y,image in zip(xx, yy, images):\n w,h = image.shape[:2]\n x_idx = np.argmin((x - x_coords)**2)\n y_idx = np.argmin((y - y_coords)**2)\n canvas[x_idx:x_idx+w, y_idx:y_idx+h] = image\n return canvas\n###\n\n","sub_path":"misc/python2_function_handler.py","file_name":"python2_function_handler.py","file_ext":"py","file_size_in_byte":3408,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"643199362","text":"# -*- coding: utf-8 -*-\n\nfrom sefaria.model import *\nimport codecs\n\n\ndef word_count_by_ref(ref_name, lang='he', version=None):\n \"\"\"\n Get a dictionary of words and the number of times they appear\n :param ref_name:\n :param lang: language to count from\n :param version: name of the version. If not specified, function will get it on it's own.\n :return:\n \"\"\"\n\n counts = {}\n\n # get version title if not supplied\n if not version:\n version = next(v for v in Ref(ref_name).version_list() if v['language'] == lang)\n\n # convert ref into a list of words\n text = TextChunk(Ref(ref_name), lang, version['versionTitle']).as_string()\n text = text.split()\n\n for word in text:\n if word in list(counts.keys()):\n counts[word] += 1\n else:\n counts[word] = 1\n\n return counts\n\n\ndef most_common_words(counts, n=-1):\n \"\"\"\n Given a dictionary of word counts, return counts in a sorted list.\n :param counts: Dictionary of words and the number of times they appear\n :param n: Number of results. If -1 (default), will return all words.\n :return: List of tuples, tuples contain word and the number of times it appears\n \"\"\"\n\n result = sorted(list(counts.items()), key=lambda x: x[1], reverse=True)\n\n if n == -1:\n return result\n else:\n return result[:n]\n\n\nref_list = ['Bava Kamma.83b-94a', 'Berakhot.2a-30b', 'Megillah.2a-17a', 'Megillah.25b-32a',\n 'Shabbat.67b-76b']\n\nfor thing in ref_list:\n filename = 'Most common words in {}.txt'.format(thing)\n\n outfile = codecs.open(filename, 'w', 'utf-8')\n\n c = most_common_words(word_count_by_ref(thing), 150)\n\n for result in c:\n outfile.write('{}: {}\\n'.format(*result))\n\n outfile.close()\n","sub_path":"misc/text matching/word_counter.py","file_name":"word_counter.py","file_ext":"py","file_size_in_byte":1761,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"415772325","text":"Matriz = []\nprint()\nSomaElementosDasColunasImpares = 0\nSomaElementosDaSegundaEQuartaColuna = 0\nfor i in range(3):\n Matriz.append([0]* 6)\nfor c in range(3):\n for d in range(6):\n Matriz[c][d] = float(input(\"Qual o elemento da matriz [\" + str (c+1) +\"][\" + str (d+1) + \"] ? \"))\nfor e in range(3):\n for f in range(6):\n if f % 2 == 0:\n SomaElementosDasColunasImpares = SomaElementosDasColunasImpares + Matriz[e][f]\nfor g in range(3):\n for h in range(6):\n if h == 1 or h == 3:\n SomaElementosDaSegundaEQuartaColuna = SomaElementosDaSegundaEQuartaColuna + Matriz[g][h]\nMediaAritmeticaDaSegundaEQuartaColuna = SomaElementosDaSegundaEQuartaColuna / 6\nprint()\nprint(\"Sua matriz original é\")\nprint()\nfor a in range(3):\n for b in range(6):\n print(Matriz[a][b], end=\" \")\n print()\nprint()\nfor k in range(3):\n Matriz[k][5] = Matriz[k][0] + Matriz[k][1]\nprint(\"A soma de todos os elementos das colunas ímpares é:\",SomaElementosDasColunasImpares)\nprint()\nprint(\"A média aritmética dos elementos da segunda e quarta coluna é:\",MediaAritmeticaDaSegundaEQuartaColuna)\nprint()\nprint(\"Sua matriz modificada com a sexta coluna sendo a soma dos elementos da coluna 1 e coluna 2 é:\")\nfor p in range(3):\n for q in range(6):\n print(Matriz[p][q], end=\" \")\n print()","sub_path":"Lista 6/lista06ex08.py","file_name":"lista06ex08.py","file_ext":"py","file_size_in_byte":1326,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"364126503","text":"\"\"\"Python: Programming in Context (2e)\"\"\"\n__author__ = 'ncoop'\n\nfrom chapter3 import *\nfrom chapter8 import *\n\n# Exercise 8.5 -- given in railfencebruteforce.py\nprint(railBreak(\"n oci mreidontoowp mgorw\"))\n\n# Exercise 8.11\nprint()\ntext = 'Are there 25, 26, or 27 non-letters to remove?'\nletters = extractLetters(text)\nprint('%s\\n%s' % (text, letters))\nprint('(The answer is %d?)' % (len(text) - len(letters)))\n\nprint()\nr = list_vs_string()\nfor i in r.items():\n print('%18s method: %8.6f sec' % (i[0], i[1]))\n\n# preparing the ciphertext\nf = open('resources/wells.txt')\nplaintext = \"\"\"He remained standing at the edge of the pit that the Thing had made\nfor itself, staring at its strange appearance, astonished chiefly at\nits unusual shape and colour, and dimly perceiving even then some\nevidence of design in its arrival. The early morning was wonderfully\nstill, and the sun, just clearing the pine trees towards Weybridge,\nwas already warm. He did not remember hearing any birds that morning,\nthere was certainly no breeze stirring, and the only sounds were the\nfaint movements from within the cindery cylinder. He was all alone on\nthe common.\"\"\"\n#plaintext = findpara('He remained standing', f.read())\nprint('\\nPlaintext:')\nprint(plaintext)\n\nciphertext = substitutionEncrypt(plaintext, genKeyFromPass('hgwells'))\n\n\n# Exercise 8.14\nfor i in [2, 8, 9]:\n print('\\nwords of length %d:' % i)\n print(wordPop(plaintext, i))\n\n# Exercise 8.15, 8.16\nprint()\nfor letters in range(1, 5):\n topsuffix, topwords = word_endings(plaintext, letters)\n print('Most popular %d-letter suffix: \"~%s\" (%d words)' % (letters, topsuffix, len(topwords)))\n\n# regex exercises\nl0 = '[A-Za-z]*'\nprint('\\nExercise 8.17: Words ending with \"s\":')\nprint(regex_words(l0 + 's$', plaintext))\n\nprint('\\nExercise 8.18: Words ending with \"ing\":')\nprint(regex_words(l0 + 'ing$', plaintext))\n\ns = 'Hissing brass crockpot bassinet?! SpsS is it.'\nprint('\\nExercise 8.19: Words containing \"ss\" in \"%s\":' % s)\nprint(regex_words(l0 + 'ss' + l0, s))\n\ns = 'Aha, Adam, as an azalea.'\nprint('\\nExercise 8.20: Words beginning and ending with \"a\" in \"%s\":' % s)\nprint(regex_words('a' + l0 + 'a', s))\n\nprint('\\nExercise 8.21: Words starting with \"st\":')\nprint(regex_words('st' + l0, plaintext))\n\ns = 'Boot the loot, toot-sweet.'\nprint('\\nExercise 8.22: Four-letter words where the middle two letters are vowels in \"%s\":' % s)\nprint(regex_words('^.[aeiou]{2}.$', s))\n\nprint('\\n%35s | %15s' % ('url', 'hostname'))\nfor url in [\n 'https://example.com/',\n 'www.example.com/',\n 'http://www.example.com/',\n 'http://www.example.com',\n 'http://www.example.com/subdir/',\n 'http://www.example.com/index.html',\n 'ftp://sputnik.smc.edu/',\n 'http://www',\n 'http://',\n]:\n print('%35s | %15s' % (url, get_hostname(url)))\n\nprint('\\n%15s | %10s | %10s' % ('full filename', 'name', 'suffix'))\nfor f in [\n 'a.out',\n 'README.txt',\n 'README.txt~',\n 'README.txt.bak',\n 'config',\n '.gitignore'\n]:\n (n, s) = split_filename(f)\n print('%15s | %10s | %10s' % (f, n, s))","sub_path":"chapter8-tests.py","file_name":"chapter8-tests.py","file_ext":"py","file_size_in_byte":3059,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"509444667","text":"import numpy as np\nfrom numba import njit, float64, int8, int32, typed\nfrom numba.experimental import jitclass\nfrom sklearn.cluster import MeanShift\nfrom itertools import product\nfrom multiprocessing import Pool\nimport time\n\n\nclass Point:\n def __init__(self, real_value, predictions_set, predicted_value, is_virgin, is_completed, changed, error=np.inf):\n self.real_value = real_value\n self.predictions_set = predictions_set\n self.predicted_value = predicted_value\n self.is_virgin = is_virgin\n self.is_completed = is_completed\n self.changed = changed\n self.error = error\n\n def info(self):\n print(\"{ set size:\", self.predictions_set.size, \"error:\", abs(self.real_value - self.predicted_value), \"}\", end=' ', flush=True)\n\n\ndef normalize(arr):\n return (arr - arr.min()) / (arr.max() - arr.min())\n\n\nLORENZ = np.genfromtxt(\"lorenz.txt\") # последние k элементов ряда - тестовая выборка\n\nTEST_BEGIN = 99900\nTEST_END = 100000\n\nCLAWS_MAX_DIST = 9\nNUMBER_OF_CLAWS = 4\n\nTRAIN_GAP = 1000\nTEST_GAP = 1\n\nMAX_NORM_DELTA = 0.008 # было 0.015\nMAX_ABS_ERROR = 0.03 # изначально было 0.05\n\nS = 34 # количество предшедствующих точек ряда, необходимое для прогнозирования точки\n\nK_MAX = 100\n\nDAEMON = 1\n\nINITIAL_ITER_NUM = 2\nITER_EPS = 10**(-5)\nmax_iter_num = 10\n\n\ndef get_points_from_prepared_prediction(i, k): # считывается только правая часть (НЕ историческая)\n values = np.genfromtxt(\"prepared_prediction.txt\")\n new_points = []\n for value_num in range(len(values)):\n if np.isnan(values[value_num]):\n new_points.append(Point(LORENZ[i - k + 1 + value_num], np.array([]), np.nan, 1, 0, 1)) # непрогнозируемая\n else:\n new_points.append(Point(LORENZ[i - k + 1 + value_num], np.array([]), values[value_num], 0, 0, 1)) # push дал прогноз\n\n return new_points\n\nimport collections\ndef print_predictions_set(point):\n print(collections.Counter(point.predictions_set))\n\n# @njit\ndef reforecast(points):\n print(\"\\nreforcasting started:\")\n for template_number in range(len(templates_by_distances)):\n x, y, z = templates_by_distances[template_number]\n for right_point in range(S, len(points)): # right_point - это индекс в points\n # points indexes in vector\n point0 = points[right_point - z - y - x - 3]\n point1 = points[right_point - z - y - 2]\n point2 = points[right_point - z - 1]\n point3 = points[right_point]\n template_vector = np.array([point0, point1, point2, point3])\n\n for claw_to_shoot in range(NUMBER_OF_CLAWS):\n # shooting_point_index = right_point - NUMBER_OF_CLAWS + claw_to_shoot + 1\n shooting_point = template_vector[claw_to_shoot]\n\n if shooting_point.is_completed:\n continue\n\n indexes_to_compare = list(filter(lambda _: _ != claw_to_shoot, range(4)))\n\n # вектор из значений ряда для сравнения по норме\n cur_gunpoints = np.array([tmp.predicted_value for tmp in template_vector[indexes_to_compare]])\n\n if np.isnan(np.sum(cur_gunpoints)):\n # print(\"template\", template_number, \"can't be used\")\n continue\n\n if template_vector[indexes_to_compare][0].changed + template_vector[indexes_to_compare][1].changed\\\n + template_vector[indexes_to_compare][2].changed == 0 and\\\n not np.isnan(template_vector[claw_to_shoot].predicted_value):\n continue\n\n for shifted_template in shifts_for_each_template[template_number]:\n if np.linalg.norm(cur_gunpoints - shifted_template[indexes_to_compare]) <= MAX_NORM_DELTA:\n shooting_point.predictions_set = np.append(\n shooting_point.predictions_set, shifted_template[claw_to_shoot])\n shooting_point.is_virgin = False\n # for printed_point_index in range(S, len(points)):\n # points[printed_point_index].info()\n # print('\\n')\n\n for right_point in range(S, len(points)):\n print(\" recalculating point\", right_point)\n point_obj = points[right_point]\n\n if point_obj.predictions_set.size:\n new_value = np.mean(point_obj.predictions_set)\n point_obj.changed = (new_value != point_obj.predicted_value)\n point_obj.predicted_value = new_value\n else:\n point_obj.changed = 0\n continue\n\n cur_error = abs(point_obj.real_value - point_obj.predicted_value)\n point_obj.error = cur_error\n\n if DAEMON and cur_error > MAX_ABS_ERROR and right_point != len(points) - 1:\n point_obj.predicted_value = np.nan\n print(\"%d-th point is unpredictable, error = %f\" % (right_point, cur_error))\n print(\"set: \", end='')\n print_predictions_set(points[right_point])\n\n else:\n print(\"%d-th point is predictable, predicted_value: %f, error = %f\" % (right_point, points[right_point].predicted_value, cur_error))\n print(\"set: \", end='')\n print_predictions_set(points[right_point])\n # for printed_point_index in range(S, len(points)):\n # points[printed_point_index].info()\n print('\\n')\n\n return points\n\n\n# прогнозирование точки i (index) за k шагов вперед; должна вернуть ошибку и прогнозируемость\ndef predict(i, k):\n complete_points = [Point(_, np.array([]), _, 0, 1, 1) for _ in LORENZ[i - k - 33: i - k + 1]] # 34 точки\n # new_points = [Point(_, np.array([]), np.nan, 1, 0, 1) for _ in LORENZ[i - k + 1: i + 1]] # было до i + 34 точки\n new_points = get_points_from_prepared_prediction(i, k)\n points = complete_points + new_points\n\n iter_vectors = [] # list of vectors of points to predict for each iteration\n iter_errors = np.array([]) # array: rows = iters, columns = points => cell = error on i-th iter on j-th point\n\n for iter_num in range(INITIAL_ITER_NUM):\n print(\"iter_num: \", iter_num)\n points = reforecast(points)\n # костыль для изменения changed на 0 у completed точек\n if iter_num == 0:\n for tmp_point in range(S):\n points[tmp_point].changed = 0\n iter_vectors.append(np.array([tmp.predicted_value for tmp in points[S:]]))\n iter_errors = np.concatenate((iter_errors, [tmp.error for tmp in points[S:]]), axis=0)\n iter_num = INITIAL_ITER_NUM\n firstVect = iter_vectors[-1]\n secondVect = iter_vectors[-2]\n norm_of_iters_diff = np.inf\n if (np.isnan(firstVect) == np.isnan(secondVect)).all():\n norm_of_iters_diff = np.linalg.norm(firstVect[~np.isnan(firstVect)] - secondVect[~np.isnan(secondVect)])\n print(\"iter_num:\", iter_num, \"| difference: \", norm_of_iters_diff)\n # while norm_of_iters_diff > ITER_EPS and iter_num <= max_iter_num:\n while iter_num <= max_iter_num:\n # print(\"\\n\\ncur_point = \".upper(), cur_point, \":\", sep='')\n print(\"iter_num:\", iter_num, \"| difference: \", norm_of_iters_diff)\n points = reforecast(points)\n iter_vectors.append(np.array([tmp.predicted_value for tmp in points[S:]]))\n iter_errors = np.concatenate((iter_errors, [tmp.error for tmp in points[S:]]), axis=0)\n firstVect = iter_vectors[-1]\n secondVect = iter_vectors[-2]\n if (np.isnan(firstVect) == np.isnan(secondVect)).all():\n norm_of_iters_diff = np.linalg.norm(firstVect[~np.isnan(firstVect)] - secondVect[~np.isnan(secondVect)])\n iter_num += 1\n\n import matplotlib.pyplot as plt\n iter_num = 0\n for iter_vector in iter_vectors:\n print(\"iter_num:\", iter_num, \"iter vector: |\", iter_vector, '|')\n plt.plot(np.linspace(0, k, k), LORENZ[i - k + 1:i + 1], color='red') # real values\n plt.scatter(np.linspace(0, k, k), iter_vector, color=(0.0, 0.0, iter_num / 10))\n plt.show()\n iter_num += 1\n print(\"last norm difference: \", norm_of_iters_diff)\n\n iter_errors = iter_errors.reshape(iter_num, k)\n for j in range(k):\n plt.plot(np.linspace(0, iter_num, iter_num), iter_errors[:, j], color='purple')\n plt.title(\"errors for %d-th point\" % (j + 1))\n plt.ylabel(\"RMSE\")\n plt.xlabel(\"iteration number\")\n plt.show()\n\n return abs(LORENZ[i] - points[-1].predicted_value), not np.isnan(points[-1].predicted_value)\n\n\n# Generating templates\ntemplates_by_distances = np.array(list(\n product(range(CLAWS_MAX_DIST + 1), range(CLAWS_MAX_DIST + 1), range(CLAWS_MAX_DIST + 1)))\n)\n\n# Training - FIT\nshifts_for_each_template = np.array([]).reshape((0, TRAIN_GAP - 3, NUMBER_OF_CLAWS)) # (0, 97, 4)\nfor template_number in range(len(templates_by_distances)):\n [x, y, z] = templates_by_distances[template_number]\n cur_claws_indexes = np.array([0, x + 1, x + y + 2, x + y + z + 3])\n mask_matrix = cur_claws_indexes + np.arange(TRAIN_GAP - cur_claws_indexes[3]).reshape(-1, 1) # матрица сдвигов\n # nan values to add at the end\n nan_list = [[np.nan, np.nan, np.nan, np.nan] for _ in range(TRAIN_GAP - (x + y + z + 3), TRAIN_GAP - 3)]\n nan_np_array = np.array(nan_list).reshape(len(nan_list), 4)\n current_template_shifts = np.concatenate(\n [LORENZ[mask_matrix], nan_np_array]) # все свдвиги шаблона данной конфигурации + дополнение\n shifts_for_each_template = np.concatenate(\n [shifts_for_each_template, current_template_shifts.reshape((1, TRAIN_GAP - 3, NUMBER_OF_CLAWS))])\n\n#\n# # t1 = time.time()\n# for k in range(33, K_MAX + 1, 4):\n# sum_of_abs_errors = 0\n# number_of_unpredictable = 0\n#\n# works = [[test_point, k] for test_point in range(TEST_BEGIN, TEST_BEGIN + TEST_GAP)]\n#\n# if __name__ == '__main__':\n# with Pool(processes=4) as pool:\n# test_points = pool.starmap(predict, works)\n#\n# # test_points = [predict(work[0], work[1]) for work in works]\n#\n# for (error, is_predictable) in test_points: # till TEST_END + 1\n# # print(\"(error, is_predictable):\", (error, is_predictable), '\\n')\n# if is_predictable:\n# sum_of_abs_errors += error\n# else:\n# number_of_unpredictable += 1\n#\n# if number_of_unpredictable == TEST_GAP:\n# k_RMSE = np.nan\n# else:\n# k_RMSE = sum_of_abs_errors / (TEST_GAP - number_of_unpredictable)\n#\n# print(\"k =\", k, k_RMSE, number_of_unpredictable / TEST_GAP, flush=True)\n#\n# # t2 = time.time()\n# # print(\"time:\", t2 - t1)\n#\n\npredict(13590, 15)\n\n\n\n","sub_path":"Push/Code/self-healing_push.py","file_name":"self-healing_push.py","file_ext":"py","file_size_in_byte":10955,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"567752045","text":"\n#:coding: utf-8\n#tmax -shell script/tmax_tdf_atpg_loc.tcl 669\n#tmax -shell script/tmax_fsim.tcl 709\n#-40\n\n\n\nimport os\nimport re\nimport random\nimport argparse\n\n\ndef rep(file1,file2,file3,file4,file5,file6,file7,file8,file9,file10):\n\tflg = 1\n\tf2 = open(file2,'w')\n\tf3 = open(file3,'w')\n\tf4 = open(file4,'w')\n\tf5 = open(file5,'w')\n\tf6 = open(file6,'w')\n\tf7 = open(file7,'w')\n\tf8 = open(file8,'w')\n\tf9 = open(file9,'w')\n\tf10 = open(file10,'w')\n\tline2 = \"0\"\n\tline3 = \"0\"\n\tline4 = \"0\"\n\tline5 = \"0\"\n\n\told = \"1\"\n\tfor line in open(file1, 'r'):\n\t\tline2 = line\n\t\tline3 = line\n\t\tline4 = line\n\t\tline5 = line\n\n\t\tif flg == 0 :\n########################piの設定#######################\n\t\t\tx = re.search(r'_pi\"=(\\d|N|P)+',line) \n\t\t\tif x :\n\t\t\t\thoge = x.group(0)[5:]\n\t\t\t\tchar_hoge2 = list(hoge)\n\n\t\t\t\tfor num in range(0,len(char_hoge2)):\n\t\t\t\t\tif char_hoge2[num] == \"N\":\n\t\t\t\t\t\tchar_hoge2[num] = \"1\"\n\n\t\t\t\twrite_data = '_pi\"='\n\t\t\t\twrite_data = write_data + \"\".join(char_hoge2)\n\t\t\t\tline2 = line[0:x.start()]+ write_data +line[x.end():len(line)]\n\t\t\t\tline3 = line[0:x.start()]+ write_data +line[x.end():len(line)]\n\t\t\t\tline4 = line[0:x.start()]+ write_data +line[x.end():len(line)]\n\t\t\t\tline5 = line[0:x.start()]+ write_data +line[x.end():len(line)]\n\n###########################test_siの設定###############\n\t\t\ta = re.search(r'test_si\\d*\"=(\\d|N)+',line)\n\t\t\tif a :\n\t\t\t\tn_count = 0\n\t\t\t\tnum_count = 0\n\t\t\t\ttest = line.split('\"')[1]\n\t\t\t\thoge = a.group(0)[9:]\n\t\t\t\tchar_hoge2 = list(hoge)\n\t\t\t\tchar_hoge3 = list(hoge)\n\t\t\t\tchar_hoge4 = list(hoge)\n\t\t\t\tchar_hoge5 = list(hoge)\n\n\t\t\t\tfor num in range(0,len(char_hoge2)):\n\t\t\t\t\tnum = len(char_hoge2) - num - 1\n\n\t\t\t\t\tif char_hoge2[num] == \"N\":\n\t\t\t\t\t\trand = random.randint(0,1)\n\n\t\t\t\t\t\tchar_hoge2[num] = str(old)\n\t\t\t\t\t\tchar_hoge3[num] = \"0\"\n\t\t\t\t\t\tchar_hoge4[num] = \"1\"\n\t\t\t\t\t\tchar_hoge5[num] = str(rand)\n\n\t\t\t\t\telse:\n\t\t\t\t\t\tif char_hoge2[num] == \"1\" or char_hoge2[num] == \"0\":\n\t\t\t\t\t\t\told = char_hoge2[num]\n\n\n\t\t\t\twrite_data = test\n\t\t\t\twrite_data2 = write_data + \"\".join(char_hoge2)\n\t\t\t\twrite_data3 = write_data + \"\".join(char_hoge3)\n\t\t\t\twrite_data4 = write_data + \"\".join(char_hoge4)\n\t\t\t\twrite_data5 = write_data + \"\".join(char_hoge5)\n\n\t\t\t\tline2 = line[0:a.start()]+ write_data2 +line[a.end():len(line)]\n\t\t\t\tline3 = line[0:a.start()]+ write_data3 +line[a.end():len(line)]\n\t\t\t\tline4 = line[0:a.start()]+ write_data4 +line[a.end():len(line)]\n\t\t\t\tline5 = line[0:a.start()]+ write_data5 +line[a.end():len(line)]\n\t\t\t\n\t\t\t\tf6.write(\"\".join(list(hoge))[1:] + \"\\n\")\n\t\t\t\tf7.write(\"\".join(char_hoge2)[1:] + \"\\n\")\n\t\t\t\tf8.write(\"\".join(char_hoge3)[1:] + \"\\n\")\n\t\t\t\tf9.write(\"\".join(char_hoge4)[1:] + \"\\n\")\n\t\t\t\tf10.write(\"\".join(char_hoge5)[1:] + \"\\n\")\n\n\n\t\telse :\n\t\t\titemList = line[:-1].split(' ')\n\t\t\tif itemList[0] == \"Pattern\" :\n\t\t\t\tflg = 0\n\n\t\tf2.write(line2)\n\t\tf3.write(line3)\n\t\tf4.write(line4)\n\t\tf5.write(line5)\n\n\nif __name__ == '__main__':\n\tparser = argparse.ArgumentParser(description = 'clk or clock serch')\n\tparser.add_argument('-i','--i',dest = 'file_name',type=str,default='')\n\tparser.add_argument('-c','--c',dest = 'chain_count',type=str,default='')\n\n\targs = parser.parse_args()\n\tInput_filename = args.file_name\n\tchain = args.chain_count\n\t\n\thoge = re.split(r'/|\\.', Input_filename)\n\tz = hoge[-2]\n\n\tfilename1 = \"./tmax_output/\" + z +\"_scan\" + chain + \"_tdf_loc_en.stil\"\n\tfilename2 = \"./tmax_output/\" + z +\"_scan\" + chain + \"_tdf_loc_myfill.stil\"\n\tfilename3 = \"./tmax_output/\" + z +\"_scan\" + chain + \"_tdf_loc_0-fill.stil\"\n\tfilename4 = \"./tmax_output/\" + z +\"_scan\" + chain + \"_tdf_loc_1-fill.stil\"\n\tfilename5 = \"./tmax_output/\" + z +\"_scan\" + chain + \"_tdf_loc_r-fill.stil\"\n\tfilename6 = \"./probability/\" + z +\"_scan\" + chain + \".txt\"\n\tfilename7 = \"./probability/\" + z +\"_scan\" + chain + \"_myfill.txt\"\n\tfilename8 = \"./probability/\" + z +\"_scan\" + chain + \"_0-fill.txt\"\n\tfilename9 = \"./probability/\" + z +\"_scan\" + chain + \"_1-fill.txt\"\n\tfilename10 = \"./probability/\" + z +\"_scan\" + chain +\"_r-fill.txt\"\n\n\trep(filename1,filename2,filename3,filename4,filename5,filename6,filename7,filename8,filename9,filename10)\n","sub_path":"src/X_fill.py","file_name":"X_fill.py","file_ext":"py","file_size_in_byte":4011,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"269108798","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.linux-x86_64/egg/everlytic/api.py\n# Compiled at: 2014-03-14 03:05:27\nimport logging\nfrom xmlrpclib import ServerProxy, Fault, ProtocolError\nfrom xml.parsers.expat import ExpatError\nfrom django.core.exceptions import ImproperlyConfigured\nfrom django.conf import settings\nlogger = logging.getLogger('everlytic-api')\ntry:\n EVERLYTIC_HOST = settings.EVERLYTIC['URL']\n EVERLYTIC_API_KEY = settings.EVERLYTIC['API_KEY']\n EVERLYTIC_LIST_ID = settings.EVERLYTIC['LIST_ID']\nexcept AttributeError:\n raise ImproperlyConfigured('EVERLYTIC settings are missing')\nexcept KeyError as e:\n raise ImproperlyConfigured('EVERLYTIC setting %s is missing.' % str(e))\n\ndef subscribeUser(last_name, first_name, email, receive_email, everlytic_id=None):\n \"\"\" Subscribe the user to the everlytic mailing list, and return the\n everlytic user id to the caller.\n \"\"\"\n sp = None\n try:\n sp = ServerProxy(EVERLYTIC_HOST)\n except IOError:\n logger.error('xmlrpclib: Could not connect to the remote host.')\n return\n\n if not everlytic_id:\n everlytic_id = _checkForExistingEverlyticUser(sp, last_name, first_name, email)\n if not everlytic_id:\n return _createEverlyticUser(sp, email, receive_email, last_name, first_name)\n _updateSubscription(sp, everlytic_id, receive_email)\n return everlytic_id\n\n\ndef _updateSubscription(sp, contact_id, receive_email):\n \"\"\" Update the subscription status of a contact on a mailing list.\n \"\"\"\n try:\n result = sp.contacts.updateSubscriptions(EVERLYTIC_API_KEY, contact_id, {str(EVERLYTIC_LIST_ID): {'cmapping_email_status': receive_email and 'subscribed' or 'unsubscribed'}})\n if result['status'] != 'success':\n logger.warning('Everlytic error: %s', result['message'])\n except Fault as e:\n logger.error('XMLRPC Fault. Code: %s, Message %s', e.faultCode, e.faultString)\n except ProtocolError as e:\n logger.error('XMLRPC Protocol Error. url: %s, code: %s, message: %s', e.url, e.errcode, e.errmsg)\n except ExpatError:\n logger.error('ExpatError: Response does not contain XML')\n\n\ndef _createEverlyticUser(sp, email, receive_email, last_name=None, first_name=None):\n \"\"\" Create a new user on the EverLytic service and (un)subscribe them to\n the list, all in one go.\n \"\"\"\n params = {'contact_email': email}\n if first_name is not None:\n params['contact_name'] = first_name\n if last_name is not None:\n params['contact_lastname'] = last_name\n try:\n result = sp.contacts.create(EVERLYTIC_API_KEY, params, [\n EVERLYTIC_LIST_ID], receive_email and 'subscribed' or 'unsubscribed', 'update')\n if result['status'] == 'success':\n return result['contact_id']\n logger.warning('Everlytic error: %s', result['message'])\n except Fault as e:\n logger.error('XMLRPC Fault. Code: %s, Message %s', e.faultCode, e.faultString)\n except ProtocolError as e:\n logger.error('XMLRPC Protocol Error. url: %s, code: %s, message: %s', e.url, e.errcode, e.errmsg)\n except ExpatError:\n logger.error('ExpatError: Response does not contain XML')\n\n return\n\n\ndef _checkForExistingEverlyticUser(sp, last_name, first_name, email):\n \"\"\" Check if the user exists on the Everlytic database\n \"\"\"\n try:\n result = sp.contacts.getBatch(EVERLYTIC_API_KEY, {'contact_lastname': last_name, \n 'contact_name': first_name, \n 'contact_email': email})\n if int(result['total']) > 0:\n everlytic_user = result['data'][0]\n return everlytic_user['contact_id']\n except Fault as e:\n logger.error('XMLRPC Fault. Code: %s, Message %s', e.faultCode, e.faultString)\n except ProtocolError as e:\n logger.error('XMLRPC Protocol Error. url: %s, code: %s, message: %s', e.url, e.errcode, e.errmsg)\n except ExpatError:\n logger.error('ExpatError: Response does not contain XML')\n\n return\n\n\ndef deleteEverlyticUser(contact_id):\n \"\"\" Delete the given contact from the Everlytic database\n \"\"\"\n sp = None\n try:\n sp = ServerProxy(EVERLYTIC_HOST)\n except IOError:\n logger.error('xmlrpclib: Could not connect to the remote host.')\n return False\n\n try:\n result = sp.contacts.delete(EVERLYTIC_API_KEY, contact_id)\n if result['status'] != 'success':\n logger.warning('Everlytic error: %s', result['message'])\n else:\n return True\n except Fault as e:\n logger.error('XMLRPC Fault. Code: %s, Message %s', e.faultCode, e.faultString)\n except ProtocolError as e:\n logger.error('XMLRPC Protocol Error. url: %s, code: %s, message: %s', e.url, e.errcode, e.errmsg)\n except ExpatError:\n logger.error('ExpatError: Response does not contain XML')\n\n return False","sub_path":"pycfiles/jmbo_everlytic-0.1.3-py2.7/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":5002,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"325772479","text":"import os\nimport time\nimport redis\nimport random\n\nfrom flask import render_template\nfrom flask import request\nfrom flask import jsonify\n\nfrom play import app\nfrom play import util\nfrom play import config\n\nif os.getenv(\"REDISTOGO_URL\") != None:\n r = redis.from_url(os.getenv(\"REDISTOGO_URL\"))\nelif os.getenv(\"PLAY_ENV\") == \"docker\":\n HOST='play_redis'\n PORT=6379\n DB=0\n r=redis.Redis(host=HOST, port=PORT, db=DB)\nelse:\n HOST='localhost'\n PORT=6379\n DB=0\n r=redis.Redis(host=HOST, port=PORT, db=DB)\n\ng_vid = \"\"\ng_sec = 0\n\n@app.route(\"/\")\ndef index():\n return render_template('index.html', message=\"/play\")\n\n@app.route('/play')\ndef play():\n return render_template('play.html')\n\n@app.route('/list', methods=['GET'])\ndef list():\n global g_vid, g_sec\n if g_sec == 0:\n g_sec = time.time()\n list = play_list()\n if len(list) == 0:\n r.rpush(config.REDIS_KEY, random_video())\n list = play_list()\n g_vid = list[0].split(config.DIVISION_KEY)[0]\n return jsonify(list)\n\n@app.route('/post', methods=['POST'])\ndef post():\n vid = request.form[\"video_id\"]\n items = util.GetYoutubeItems(vid)\n for result_obj in items:\n duration = util.YTDurationToSeconds(result_obj[\"contentDetails\"][\"duration\"])\n if duration < 600:\n title = result_obj[\"snippet\"][\"title\"]\n r.rpush(config.REDIS_KEY, vid+config.DIVISION_KEY+title)\n return jsonify(play_list())\n\n@app.route('/pop', methods=['POST'])\ndef pop():\n global g_sec\n vid = request.form[\"video_id\"]\n item = r.lindex(config.REDIS_KEY, 0)\n if item.decode('utf-8').split(config.DIVISION_KEY)[0] == vid:\n r.lpop(config.REDIS_KEY)\n list = play_list()\n if len(list) > 0:\n title = list[0].split(config.DIVISION_KEY)[1]\n util.PostToSlack(\"Now playing - \" + title)\n if r.llen(config.REDIS_KEY) <= 0:\n r.rpush(config.REDIS_KEY, random_video())\n list = play_list()\n g_sec = 0\n return jsonify(list)\n\n@app.route('/now', methods=['GET'])\ndef now():\n global g_vid, g_sec\n if g_vid == \"\":\n list = play_list()\n g_vid = list[0].split(config.DIVISION_KEY)[0]\n if g_sec != 0:\n diff = int(time.time() - g_sec)\n else:\n diff = g_sec\n dict = {\"vid\":g_vid, \"sec\":diff}\n return jsonify(dict)\n\n@app.route('/dope', methods=['POST'])\ndef dope():\n video_id = request.form[\"video_id\"]\n list = play_list()\n for i in list:\n t = i.split(config.DIVISION_KEY)\n vid = t[0]\n title = t[1]\n if vid == video_id:\n for l in dope_list():\n lvid = l.split(config.DIVISION_KEY)[0]\n if lvid == video_id:\n return jsonify()\n r.rpush(config.REDIS_DOPE_KEY, vid+config.DIVISION_KEY+title)\n util.PostToSlack(\"dope: \" + title)\n return jsonify()\n\n@app.route('/api/queue', methods=['POST'])\ndef api_queue():\n vid = util.GetVideoId(request.json[\"youtube_url\"])\n items = util.GetYoutubeItems(vid)\n for result_obj in items:\n duration = util.YTDurationToSeconds(result_obj[\"contentDetails\"][\"duration\"])\n if duration < 600:\n title = result_obj[\"snippet\"][\"title\"]\n r.rpush(config.REDIS_KEY, vid+config.DIVISION_KEY+title)\n return jsonify(result=\"OK\", title=title, video_id=vid)\n return jsonify(result=\"NG\", title=\"\")\n\n@app.route('/api/list', methods=['GET'])\ndef api_list():\n list = play_list()\n pl = []\n for l in list:\n t = l.split(config.DIVISION_KEY)\n vid = t[0]\n title = t[1]\n song = {\"video_id\": vid, \"title\": title}\n pl.append(song)\n return jsonify(pl)\n\n@app.route('/api/dope', methods=['POST'])\ndef api_dope():\n global g_vid\n video_id = g_vid\n list = play_list()\n for i in list:\n t = i.split(config.DIVISION_KEY)\n vid = t[0]\n title = t[1]\n if vid == video_id:\n for l in dope_list():\n lvid = l.split(config.DIVISION_KEY)[0]\n if lvid == video_id:\n return jsonify(result=\"OK\", title=title)\n r.rpush(config.REDIS_DOPE_KEY, vid+config.DIVISION_KEY+title)\n return jsonify(result=\"OK\", title=title)\n\ndef play_list():\n play_list = r.lrange(config.REDIS_KEY, 0, -1)\n list = []\n for l in play_list:\n list.append(l.decode('utf-8'))\n return list\n\ndef dope_list():\n dope_list = r.lrange(config.REDIS_DOPE_KEY, 0, -1)\n list = []\n for l in dope_list:\n list.append(l.decode('utf-8'))\n return list\n\ndef random_video():\n list = dope_list()\n if len(list) <= 0:\n return config.DEFAULT_VALUE\n r = random.randint(0,len(list)-1)\n return list[r]\n","sub_path":"play/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4728,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"594673240","text":"# question4.py\r\n# program to draw functions\r\n# author: smxdip001\r\n\r\n\r\nimport math\r\nfunction = input(\"Enter a function f(x):\\n\")\r\n\r\nfor y in range(-10,11): #range\r\n for x in range(-10,11): #domain\r\n yreal = -y \r\n a = round(eval(function)) #calculate the y value for the corresponding x value\r\n if x == 0 and yreal == 0 and a != 0: #check if x and y are equal and if there is no intercept at 0.\r\n print(\"+\",end=\"\")\r\n elif x == 0 and a != yreal: # print vertical axis\r\n print(\"|\",end=\"\")\r\n elif yreal == 0 and a != 0: #print horizontal axis\r\n print(\"-\",end=\"\")\r\n elif a == yreal:\r\n print(\"o\",end=\"\")\r\n \r\n else:\r\n print(\" \",end=\"\")\r\n \r\n print()\r\n \r\n \r\n\r\n ","sub_path":"examples/data/Assignment_5/smxdip001/question4.py","file_name":"question4.py","file_ext":"py","file_size_in_byte":799,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"422774607","text":"'''\nCreated on 30 Jan 2020\n\n@author: snake91\n'''\n\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D # noqa: F401 unused import\n\n\nf = lambda u,v, theta: (u*v) / (u+v-u*v)\n\nf = lambda u,v, theta: np.exp(- ( ( (-np.log(u))**theta + (-np.log(v))**theta )**(1./theta) )) #gumbel\nf = lambda u,v, theta: (-1./theta) * np.log(1 + (((np.exp(-theta * u) - 1) * \n (np.exp(-theta * v) - 1) )/ (np.exp(-theta) - 1)))\nf = lambda u,v, theta: (u**(-theta) + v**(-theta) - 1)**(-1./theta) #clayton\n\n\ndef copulamle(theta, f, u,v,C):\n \n x = f(u,v,theta)\n x = np.where(x < 0, 0, x)\n x = np.where(x > 1, 1, x)\n \n res = np.log(np.mean((x - C)**2))\n \n print(theta[0], res, sep = \" \")\n return res\n\n\n\n\nif __name__ == \"__main__\":\n \n \n import pandas as pd\n import scipy.optimize as spo\n \n data = pd.read_csv(\"/home/snake91/data3d.csv\")\n\n x = data['x']\n y = data['y']\n z = data['z']\n Cxy = data['Cxy']\n Cxy_z = data['Cxy_z']\n\n# print(copulamle(50, x, y, Cxy))\n \n args = tuple(x,y,Cxy)\n paramUV = spo.minimize(copulamle, x0 = (2,), bounds = [(0, None)], args = (f, args))\n print(paramUV)\n \n args = Cxy,z,Cxy_z\n paramVZ = spo.minimize(copulamle, x0 = (2,), bounds = [(0, None)], args = (f, args))\n print(paramVZ)\n\n print(\"\")\n \n plt.scatter(x[:10000],y[:10000], s= 0.25, color = 'red')\n plt.scatter(Cxy[:10000],z[:10000], s= 0.25, color = 'blue')\n \n ''' C(C(x,y),z) '''\n fig = plt.figure()\n ax = fig.add_subplot(111, projection='3d')\n ax = fig.gca(projection='3d')\n \n ax.scatter(x[:10000], y[:10000], z[:10000], s=0.75)\n \n \n \n \n \n \n \n ","sub_path":"stats/copula/tests/copulamle3dim_1.py","file_name":"copulamle3dim_1.py","file_ext":"py","file_size_in_byte":1734,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"118349298","text":"import jinja2\n\nfrom jingo import register, env\n\n\n@register.function\n@jinja2.contextfunction\ndef tag_list(context, addon, dev_tags=None, user_tags=None):\n \"\"\"Display list of tags, with delete buttons.\"\"\"\n if not dev_tags and not user_tags:\n return ''\n if not dev_tags:\n dev_tags = []\n if not user_tags:\n user_tags = []\n\n c = {\n 'request': context['request'],\n 'addon': addon,\n 'dev_tags': dev_tags,\n 'user_tags': user_tags,\n }\n t = env.get_template('tags/tag_list.html').render(**c)\n return jinja2.Markup(t)\n","sub_path":"apps/tags/helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":580,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"56030255","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n#\n# timezone.py\n#\n# Copyright © 2013-2015 DSGos\n#\n# This file is part of DSGos_Installer.\n#\n# DSGos_Installer 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# DSGos_Installer 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# The following additional terms are in effect as per Section 7 of the license:\n#\n# The preservation of all legal notices and author attributions in\n# the material or in the Appropriate Legal Notices displayed\n# by works containing it is required.\n#\n# You should have received a copy of the GNU General Public License\n# along with DSGos_Installer; If not, see .\n\n\nfrom gi.repository import Gtk, Gdk\n\nimport os\nimport multiprocessing\nimport queue\nimport urllib.request\nimport urllib.error\nimport time\nimport logging\nimport hashlib\n\nimport misc.tz as tz\nimport misc.misc as misc\nimport misc.timezonemap as timezonemap\nfrom gtkbasebox import GtkBaseBox\n\nNM = 'org.freedesktop.NetworkManager'\nNM_STATE_CONNECTED_GLOBAL = 70\n\n\nclass Timezone(GtkBaseBox):\n def __init__(self, params, prev_page=\"location\", next_page=\"keymap\"):\n super().__init__(self, params, \"timezone\", prev_page, next_page)\n\n self.map_window = self.ui.get_object('timezone_map_window')\n\n self.combobox_zone = self.ui.get_object('comboboxtext_zone')\n self.combobox_region = self.ui.get_object('comboboxtext_region')\n\n # Show regions in three columns\n self.combobox_region.set_wrap_width(3)\n\n self.tzdb = tz.Database()\n self.timezone = None\n\n # This is for populate_cities\n self.old_zone = None\n\n # Autotimezone process will store detected coords in this queue\n self.auto_timezone_coords = multiprocessing.Queue()\n\n # Process to try to determine timezone.\n self.autodetected_coords = None\n self.start_auto_timezone_process()\n\n # Setup window\n self.tzmap = timezonemap.TimezoneMap()\n self.tzmap.connect('location-changed', self.on_location_changed)\n\n # Strip .UTF-8 from locale, icu doesn't parse it\n self.locale = os.environ['LANG'].rsplit('.', 1)[0]\n self.map_window.add(self.tzmap)\n self.tzmap.show()\n\n def translate_ui(self):\n \"\"\" Translates all ui elements \"\"\"\n label = self.ui.get_object('label_zone')\n txt = _(\"Zone:\")\n label.set_markup(txt)\n\n label = self.ui.get_object('label_region')\n txt = _(\"Region:\")\n label.set_markup(txt)\n\n label = self.ui.get_object('label_ntp')\n txt = _(\"Use Network Time Protocol (NTP) for clock synchronization\")\n label.set_markup(txt)\n\n self.header.set_subtitle(_(\"Select Your Timezone\"))\n\n def on_location_changed(self, tzmap, tz_location):\n # loc = self.tzdb.get_loc(self.timezone)\n if not tz_location:\n self.timezone = None\n self.forward_button.set_sensitive(False)\n else:\n self.timezone = tz_location.get_property('zone')\n logging.info(\"Location changed to : %s\", self.timezone)\n self.update_comboboxes(self.timezone)\n self.forward_button.set_sensitive(True)\n\n def update_comboboxes(self, timezone):\n zone, region = timezone.split('/', 1)\n self.select_combobox_item(self.combobox_zone, zone)\n self.populate_cities(zone)\n self.select_combobox_item(self.combobox_region, region)\n\n @staticmethod\n def select_combobox_item(combobox, item):\n tree_model = combobox.get_model()\n tree_iter = tree_model.get_iter_first()\n\n while tree_iter is not None:\n value = tree_model.get_value(tree_iter, 0)\n if value == item:\n combobox.set_active_iter(tree_iter)\n tree_iter = None\n else:\n tree_iter = tree_model.iter_next(tree_iter)\n\n def set_timezone(self, timezone):\n self.timezone = timezone\n res = self.tzmap.set_timezone(timezone)\n # res will be False if the timezone is unrecognised\n self.forward_button.set_sensitive(res)\n\n def on_zone_combobox_changed(self, widget):\n new_zone = self.combobox_zone.get_active_text()\n if new_zone is not None:\n self.populate_cities(new_zone)\n\n def on_region_combobox_changed(self, widget):\n new_zone = self.combobox_zone.get_active_text()\n new_region = self.combobox_region.get_active_text()\n if new_zone is not None and new_region is not None:\n new_timezone = \"{0}/{1}\".format(new_zone, new_region)\n # Only set timezone if it has changed :p\n if self.timezone != new_timezone:\n self.set_timezone(new_timezone)\n\n def populate_zones(self):\n zones = []\n for loc in self.tzdb.locations:\n zone = loc.zone.split('/', 1)[0]\n if zone not in zones:\n zones.append(zone)\n zones.sort()\n tree_model = self.combobox_zone.get_model()\n tree_model.clear()\n for zone in zones:\n tree_model.append([zone, zone])\n\n def populate_cities(self, selected_zone):\n if self.old_zone != selected_zone:\n regions = []\n for loc in self.tzdb.locations:\n zone, region = loc.zone.split('/', 1)\n if zone == selected_zone:\n regions.append(region)\n regions.sort()\n tree_model = self.combobox_region.get_model()\n tree_model.clear()\n for region in regions:\n tree_model.append([region, region])\n self.old_zone = selected_zone\n\n def prepare(self, direction):\n self.translate_ui()\n self.populate_zones()\n self.timezone = None\n self.forward_button.set_sensitive(False)\n\n if self.autodetected_coords is None:\n try:\n self.autodetected_coords = self.auto_timezone_coords.get(False, timeout=20)\n except queue.Empty:\n logging.warning(\"Can't autodetect timezone coordinates\")\n\n if self.autodetected_coords:\n coords = self.autodetected_coords\n try:\n latitude = float(coords[0])\n longitude = float(coords[1])\n timezone = self.tzmap.get_timezone_at_coords(latitude, longitude)\n self.set_timezone(timezone)\n self.forward_button.set_sensitive(True)\n except ValueError as value_error:\n self.autodetected_coords = None\n logging.warning(\"Can't autodetect timezone coordinates: %s\", value_error)\n\n self.show_all()\n\n def start_auto_timezone_process(self):\n proc = AutoTimezoneProcess(self.auto_timezone_coords, self.settings)\n proc.daemon = True\n proc.name = \"timezone\"\n self.process_list.append(proc)\n # self.global_process_queue.put(proc)\n proc.start()\n\n @staticmethod\n def log_location(loc):\n logging.debug(\"timezone human zone: %s\", loc.human_zone)\n logging.debug(\"timezone country: %s\", loc.country)\n logging.debug(\"timezone zone: %s\", loc.zone)\n logging.debug(\"timezone human country: %s\", loc.human_country)\n\n if loc.comment:\n logging.debug(\"timezone comment: %s\", loc.comment)\n\n if loc.latitude:\n logging.debug(\"timezone latitude: %s\", loc.latitude)\n\n if loc.longitude:\n logging.debug(\"timezone longitude: %s\", loc.longitude)\n\n def store_values(self):\n loc = self.tzdb.get_loc(self.timezone)\n\n if loc:\n self.settings.set(\"timezone_human_zone\", loc.human_zone)\n self.settings.set(\"timezone_country\", loc.country)\n self.settings.set(\"timezone_zone\", loc.zone)\n self.settings.set(\"timezone_human_country\", loc.human_country)\n\n if loc.comment:\n self.settings.set(\"timezone_comment\", loc.comment)\n else:\n self.settings.set(\"timezone_comment\", \"\")\n\n if loc.latitude:\n self.settings.set(\"timezone_latitude\", loc.latitude)\n else:\n self.settings.set(\"timezone_latitude\", \"\")\n\n if loc.longitude:\n self.settings.set(\"timezone_longitude\", loc.longitude)\n else:\n self.settings.set(\"timezone_longitude\", \"\")\n\n self.log_location(loc)\n\n # This way process.py will know that all info has been entered\n self.settings.set(\"timezone_done\", True)\n\n return True\n\n def on_switch_ntp_activate(self, ntp_switch):\n self.settings['use_timesyncd'] = ntp_switch.get_active()\n\n\nclass AutoTimezoneProcess(multiprocessing.Process):\n def __init__(self, coords_queue, settings):\n super(AutoTimezoneProcess, self).__init__()\n self.coords_queue = coords_queue\n self.settings = settings\n\n def run(self):\n # Calculate logo hash\n logo = \"data/images/DSGos/DSGos-logo-mini2.png\"\n logo_path = os.path.join(self.settings.get(\"DSGos_Installer\"), logo)\n with open(logo_path, \"rb\") as logo_file:\n logo_bytes = logo_file.read()\n logo_hasher = hashlib.sha1()\n logo_hasher.update(logo_bytes)\n logo_digest = logo_hasher.digest()\n\n # Wait until there is an Internet connection available\n if not misc.has_connection():\n logging.warning(\"Can't get network status. DSGos_Installer will try again in a moment\")\n while not misc.has_connection():\n time.sleep(4) # Wait 4 seconds and try again\n\n logging.debug(\"A working network connection has been detected.\")\n\n # Do not start looking for our timezone until we've reached the language screen\n # (welcome.py sets timezone_start to true when next is clicked)\n while not self.settings.get('timezone_start'):\n time.sleep(2)\n\n # OK, now get our timezone\n\n logging.debug(\"We have connection. Let's get our timezone\")\n try:\n url = urllib.request.Request(\n url=\"http://geo.DSGos.com\",\n data=logo_digest,\n headers={\"User-Agent\": \"DSGos Installer\", \"Connection\": \"close\"})\n with urllib.request.urlopen(url) as conn:\n coords = conn.read().decode('utf-8').strip()\n\n if coords == \"0 0\":\n # Sometimes server returns 0 0, we treat it as an error\n coords = None\n except Exception as general_error:\n logging.error(general_error)\n coords = None\n\n if coords:\n coords = coords.split()\n logging.debug(\n _(\"Timezone (latitude %s, longitude %s) detected.\"),\n coords[0],\n coords[1])\n self.coords_queue.put(coords)\n\nif __name__ == '__main__':\n def _(x): return x\n\n from test_screen import _, run\n run('Timezone')\n","sub_path":"airootfs/usr/share/DSGos-Installer/DSGos_Installer/timezone.py","file_name":"timezone.py","file_ext":"py","file_size_in_byte":11353,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"412755210","text":"\"\"\"\nCopyright 2013 Rackspace\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\"\"\"\n\n\nclass PairingBehaviors(object):\n\n def __init__(self, client, cleanup_client, config):\n super(PairingBehaviors, self).__init__()\n self.client = client\n self.cleanup_client = cleanup_client\n self.pairing_config = config\n self.worker_ids = []\n\n def remove_created_workers(self):\n self.cleanup_client.connect()\n self.cleanup_client.auth()\n for worker_id in self.worker_ids:\n self.cleanup_client.remove_worker(worker_id)\n self.cleanup_client.disconnect()\n self.worker_ids = []\n\n def pair_worker_from_config(self, hostname=None, ip_v4=None, ip_v6=None,\n personality=None, status=None, os_type=None,\n memory_mb=None, arch=None, cpu_cores=None,\n load_average=None, disks=None):\n resp = self.pair_worker(\n hostname=hostname or self.pairing_config.hostname,\n ip_v4=ip_v4 or self.pairing_config.ip_v4,\n ip_v6=ip_v6 or self.pairing_config.ip_v6,\n personality=personality or self.pairing_config.personality,\n status='new',\n os_type=os_type or self.pairing_config.os_type,\n memory_mb=memory_mb or self.pairing_config.memory_mb,\n arch=arch or self.pairing_config.arch,\n cpu_cores=cpu_cores or self.pairing_config.cpu_cores,\n load_average=load_average or self.pairing_config.load_average,\n disks=disks or self.pairing_config.disks)\n\n return resp\n\n def pair_worker(self, hostname=None, ip_v4=None, ip_v6=None,\n personality=None, status=None, os_type=None,\n memory_mb=None, arch=None, cpu_cores=None,\n load_average=None, disks=None):\n\n response = self.client.pair(\n hostname=hostname,\n ip_v4=ip_v4,\n ip_v6=ip_v6,\n personality=personality,\n status=status,\n os_type=os_type,\n memory_mb=memory_mb,\n arch=arch,\n cpu_cores=cpu_cores,\n load_average=load_average,\n disks=disks)\n\n # Store information so we can remove all workers later\n if response.entity is not None:\n self.worker_ids.append(response.entity.worker_id)\n\n return response\n","sub_path":"cloudcafe/meniscus/coordinator_api/behaviors.py","file_name":"behaviors.py","file_ext":"py","file_size_in_byte":2910,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"467601697","text":"from django.conf.urls import url\nfrom views import *\n\n\nurlpatterns = [\n url(r'register/$', user_register),\n url(r'register_verify/$', user_register_verify),\n url(r'register_handle/$', user_register_handle),\n url(r'login/$', user_login),\n url(r'login_handle/$', user_login_handle),\n url(r'user_center_info/$', user_center_info),\n url(r'logout/$', logout),\n]\n","sub_path":"DailyFresh/user_part/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":378,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"95222122","text":"#!/usr/bin/env python\n\nimport os\nfrom distutils.core import setup\nfrom distutils.core import Command\n\n\nclass TestCommand(Command):\n user_options = []\n\n def initialize_options(self):\n pass\n\n def finalize_options(self):\n pass\n\n def run(self):\n from django.conf import settings\n import django\n from django.core.management import call_command\n\n django_version = django.get_version().split('.')\n print('Testing against Django version %s' % '.'.join(django_version))\n\n settings.configure(\n DATABASES={\n 'default': {\n 'NAME': ':memory:',\n 'ENGINE': 'django.db.backends.sqlite3'}},\n MIDDLEWARE_CLASSES = (\n 'django.middleware.common.CommonMiddleware',\n 'django.middleware.csrf.CsrfViewMiddleware',\n ),\n STRIPE_PUBLIC_KEY = os.environ.get('STRIPE_PUBLIC_KEY'),\n STRIPE_SECRET_KEY = os.environ.get('STRIPE_SECRET_KEY'),\n INSTALLED_APPS=(\n 'django.contrib.auth',\n 'django.contrib.contenttypes',\n 'django.contrib.sessions',\n 'stripejs'\n ),\n TEMPLATES = [{\n 'BACKEND': 'django.template.backends.django.DjangoTemplates',\n 'DIRS': [],\n 'APP_DIRS': True,\n 'OPTIONS': {\n 'context_processors': [\n 'django.template.context_processors.debug',\n 'django.template.context_processors.request',\n 'django.contrib.auth.context_processors.auth',\n 'django.contrib.messages.context_processors.messages',\n ],\n },\n }]\n )\n\n\n if getattr(django, 'setup', None):\n django.setup()\n\n\n call_command('test', 'stripejs')\n\n\nclass ShellCommand(Command):\n user_options = []\n\n def initialize_options(self):\n pass\n\n def finalize_options(self):\n pass\n\n def run(self):\n import django\n from django.conf import settings\n from django.core.management import call_command\n\n settings.configure(\n DATABASES={\n 'default': {\n 'NAME': ':memory:',\n 'ENGINE': 'django.db.backends.sqlite3'}},\n INSTALLED_APPS=('stripejs',),\n STRIPE_PUBLIC_KEY = os.environ.get('STRIPE_PUBLIC_KEY'),\n STRIPE_SECRET_KEY = os.environ.get('STRIPE_SECRET_KEY'))\n\n if getattr(django, 'setup', None):\n django.setup()\n \n call_command('shell')\n\n\nsetup(\n name='django-stripejs',\n version='0.1',\n description='Django Stripe payment integration',\n author='Richard Cox',\n author_email='richard@bot37.com',\n url='https://github.com/Khabi/django-simple-stripe',\n packages=[\n 'stripejs',\n 'stripejs/templatetags'\n ],\n classifiers=[\n 'Development Status :: 1 - Beta',\n 'Environment :: Web Environment',\n 'Framework :: Django',\n 'Intended Audience :: Developers',\n 'License :: OSI Approved :: MIT License',\n 'Operating System :: OS Independent',\n 'Programming Language :: Python',\n 'Topic :: Utilities'\n ],\n requires=['stripe'],\n cmdclass={'test': TestCommand, 'shell': ShellCommand}\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":3425,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"347806935","text":"#-*- coding: utf-8 -*-\nfrom django.conf.urls import patterns, url\n\nfrom . import views\n\n\nurlpatterns = patterns('',\n url(r'^$', views.IndexView.as_view(), name='index'),\n url(r'^(?P[\\w-]+)/$', views.DetailView.as_view(), name='detail'),\n url(r'^(?P[\\w-]+)/results/$', views.ResultsView.as_view(), name='results'),\n url(r'^(?P[\\w-]+)/vote/$', views.vote, name='vote'),\n)\n","sub_path":"polls/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":400,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"199244147","text":"# rot.py \n# Script for cracking simple rotation ciphers.\n# \n# Usage \n# Script reads from stdin; writes to output file specfied by constant variable. \n# For each line in the input file, all rotation values (determined by ALPHA_SIZE) are considered. \n# The 0th entry for each output section denotes the original (unrotated) input line. \n\nimport fileinput \n\nOUTFILE_NAME = \"out.txt\"\n\n# determines maximum rotation amount \nALPHA_SIZE = 26\n\n# uppercase decimal min / max \nU_MIN = 65 \nU_MAX = 90\n\n# lowercase decimal min / max \nL_MIN = 97\nL_MAX = 122 \n\ndef main():\n\tf = open(OUTFILE_NAME, \"w\")\n\n\tfor line in fileinput.input():\n\t\t# strip newline \n\t\tline = line.strip()\n\n\t\tf.write(\"------------------------------------------------\\n\")\n\t\t\n\t\tfor i in range(ALPHA_SIZE):\n\t\t\t# rotate the chars in this line by this amount\n\t\t\trotated_line = rotate(line, i)\n\t\t\tf.write(str(i) + \" \" + rotated_line)\n\t\t\tf.write(\"\\n\")\n\n\t\tf.write(\"------------------------------------------------\\n\")\n\n\tf.close()\n\n\treturn None \n\n# rotate a string by given rotation value\n# return the rotated string \ndef rotate(string, rotation):\n\ts = \"\"\n\tfor c in string:\n\t\tdec = ord(c)\n\t\tif (dec >= U_MIN) and (dec <= U_MAX):\n\t\t\t# captial letter\n\t\t\trd = inc_upper(dec, rotation)\n\t\t\ts += chr(rd)\n\t\telif (dec >= L_MIN) and (dec <= L_MAX):\n\t\t\t# lowercase letter\n\t\t\trd = inc_lower(dec, rotation)\n\t\t\ts += chr(rd)\n\t\telse:\n\t\t\t# dont rotate non-alphabetical \n\t\t\ts += c\n\n\treturn s \n\n# increment an uppercase char by given rotation value \n# return the incremented decimal value \ndef inc_upper(decimal, rotation):\n\tn = decimal \n\tfor i in range(rotation):\n\t\tn += 1\n\n\t\t# manual rollover \n\t\tif n > U_MAX:\n\t\t\tn = U_MIN\n\n\treturn n \n\n# increment a lowercase char by given rotation value\n# return the incremented decimal value \ndef inc_lower(decimal, rotation):\n\tn = decimal \n\tfor i in range(rotation):\n\t\tn += 1\n\t\t\n\t\t# manual rollover \n\t\tif n > L_MAX:\n\t\t\tn = L_MIN\n\n\treturn n \n\nif __name__ == \"__main__\":\n\tmain()","sub_path":"python/rot.py","file_name":"rot.py","file_ext":"py","file_size_in_byte":1945,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"576969397","text":"#!/usr/bin/env python3\n\n\"\"\"General ACT backend uploader. Reads facts as JSON\nfrom the stdin, uploading accordingly\"\"\"\n\nimport json\nimport os\nimport sys\nimport traceback\nfrom logging import error, warning\n\nimport act.api\nfrom act.workers.libs import worker\n\n\ndef main(actapi: act.api.Act) -> None:\n \"\"\"Process stdin, parse each separat line as a JSON structure and\n register a fact based on the structure. The form of input should\n be the on the form accepted by the ACT Rest API fact API.\"\"\"\n\n for line in sys.stdin:\n data = json.loads(line)\n\n fact = actapi.fact(**data)\n try:\n fact.add()\n except act.api.base.ValidationError as err:\n warning(\"ValidationError while storing objects: %s\" % err)\n except act.api.base.ResponseError as err:\n error(\"ResponseError while storing objects: %s\" % err)\n sys.exit(1)\n\n\ndef main_log_error() -> None:\n \"Call main() and log all exceptions as errors\"\n try:\n # Look for default ini file in \"/etc/actworkers.ini\" and ~/config/actworkers/actworkers.ini\n # (or replace .config with $XDG_CONFIG_DIR if set)\n args = worker.handle_args(worker.parseargs(\"Generic uploader\"))\n actapi = worker.init_act(args)\n\n main(actapi)\n except Exception:\n error(\"Unhandled exception: {}\".format(traceback.format_exc()))\n raise\n\n\nif __name__ == '__main__':\n main_log_error()\n","sub_path":"act/workers/generic_uploader.py","file_name":"generic_uploader.py","file_ext":"py","file_size_in_byte":1439,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"536791337","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nif __name__ == '__main__':\n # tuple初始化\n tuple1 = ('a', 'b', 'c', '中文', '英文')\n\n # 使用索引遍历(访问)列表,支持正索引与负索引\n for i in range(0, len(tuple1)):\n print(tuple1[i])\n\n tuple2 = (1,)\n print(tuple2[0])\n","sub_path":"python3-demo01/Test03.py","file_name":"Test03.py","file_ext":"py","file_size_in_byte":322,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"477496275","text":"import sys\n\n\nnumberOfLines = int(input())\ncount = 0\ntext = []\n\ndef XyloHack (number):\n if(int(number) %2 == 0):\n text.append(content.upper())\n else:\n text.append(content.lower())\n\nfor i in range(numberOfLines):\n userInput = input()\n for char in userInput:\n count += 1\n if(char == '.'):\n content = userInput[:count-1].strip(\"'\")\n number = userInput[userInput.find(\"(\")+1:userInput.find(\")\")]\n XyloHack(number)\n count = 0\n\n\nprint(\"Below is the output:\")\nfor line in text:\n print(line)\n","sub_path":"P2/XyloHack.py","file_name":"XyloHack.py","file_ext":"py","file_size_in_byte":562,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"147669523","text":"import sys\nimport unittest\n\nfrom PyQt5 import QtGui, QtWidgets\n\n# set up import paths\nimport sas.qtgui.path_prepare\n\n# Local\nfrom sas.qtgui.Plotting.SetGraphRange import SetGraphRange\n\nif not QtWidgets.QApplication.instance():\n app = QtWidgets.QApplication(sys.argv)\n\nclass SetGraphRangeTest(unittest.TestCase):\n '''Test the SetGraphRange'''\n def setUp(self):\n '''Create the SetGraphRange'''\n\n self.widget = SetGraphRange(None)\n\n def tearDown(self):\n '''Destroy the GUI'''\n self.widget.close()\n self.widget = None\n\n def testDefaults(self):\n '''Test the GUI in its default state'''\n self.assertIsInstance(self.widget, QtWidgets.QDialog)\n self.assertEqual(self.widget.windowTitle(), \"Set Graph Range\")\n self.assertIsInstance(self.widget.txtXmin, QtWidgets.QLineEdit)\n self.assertIsInstance(self.widget.txtXmin.validator(), QtGui.QDoubleValidator)\n \n def testGoodRanges(self):\n '''Test the X range values set by caller''' \n self.assertEqual(self.widget.xrange(), (0.0, 0.0))\n self.assertEqual(self.widget.yrange(), (0.0, 0.0))\n\n new_widget = SetGraphRange(None, (\"1.0\", 2.0), (8.0, \"-2\"))\n self.assertEqual(new_widget.xrange(), (1.0, 2.0))\n self.assertEqual(new_widget.yrange(), (8.0, -2.0))\n\n\n def testBadRanges(self):\n '''Test the incorrect X range values set by caller'''\n with self.assertRaises(ValueError):\n new_widget = SetGraphRange(None, (\"1.0\", \"aa\"), (None, \"@\"))\n self.assertEqual(new_widget.xrange(), (1.0, 0.0))\n self.assertEqual(new_widget.yrange(), (0.0, 0.0))\n\n with self.assertRaises(AssertionError):\n new_widget = SetGraphRange(None, \"I'm a tuple\", None)\n self.assertEqual(new_widget.xrange(), (1.0, 0.0))\n self.assertEqual(new_widget.yrange(), (0.0, 0.0))\n\nif __name__ == \"__main__\":\n unittest.main()\n","sub_path":"src/sas/qtgui/Plotting/UnitTesting/SetGraphRangeTest.py","file_name":"SetGraphRangeTest.py","file_ext":"py","file_size_in_byte":1947,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"463813009","text":"def split_values(original_values):\n splited_values = []\n for val in original_values:\n splited_values.extend(val)\n return splited_values\n\n\ndef get_field_by_name(obj, field_name):\n if '.' not in field_name:\n if obj is None:\n return None\n if hasattr(obj, 'get'):\n return obj.get(field_name)\n if hasattr(obj, '__getitem__'):\n return obj[field_name]\n return getattr(obj, field_name)\n spliced = str(field_name).split('.', maxsplit=1)\n return get_field_by_name(get_field_by_name(obj, spliced[0]), spliced[1])\n\n\ndef create_and_or_query_from_values(field_name, field_type, values):\n if not values:\n return ''\n compare_op = ' = ' if field_type == 'SINGLE' else ' : '\n return ' AND ( ' + ' OR '.join(create_compare(field_name, compare_op, values)) + ' ) '\n\n\ndef create_compare(field_name, compare_op, values):\n for val in values:\n yield field_name + compare_op + '\"' + val + '\"'\n\n\ndef get_element_by_order(elements, element_order):\n for index_ in range(0, len(elements)):\n if elements[index_].get('order') == element_order:\n return elements[index_]\n return None\n\n\ndef build_join(resp, joins, order):\n previous_join = get_element_by_order(joins, order - 1)\n if not previous_join:\n return ''\n join_values = []\n for val in resp:\n field_value = get_field_by_name(val, str(previous_join.get('field')))\n if field_value:\n join_values.append(field_value)\n if 'SINGLE' != previous_join.get('type') and join_values:\n join_values = split_values(join_values)\n next_join = get_element_by_order(joins, order)\n return create_and_or_query_from_values(next_join.get('field'), next_join.get('type'), join_values)\n","sub_path":"securitycenter/creator-app/appflex/creator/query/query_process_helper.py","file_name":"query_process_helper.py","file_ext":"py","file_size_in_byte":1780,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"586702803","text":"'''\r\n\r\nPythagorean Triples\r\nA \"Pythagorean Triple\" is a set of positive integers, a, b and c that fits the rule:\r\n\r\na*a + b*b = c*c\r\n\r\nHere is a list of the first few Pythagorean Triples\r\n\r\n(3,4,5)\r\n\r\n(5,12,13)\r\n\r\nExample: scale 3,4,5 by 2 gives 6,8,10 which should be Pythagorean Triples\r\n\r\n'''\r\n\r\ndef PyTriples(a,b,c):\r\n\r\n asquare=a*a\r\n bsquare=b*b\r\n csquare=c*c\r\n if asquare+bsquare==csquare:\r\n print(\"Yes its a Pythagorean Triple\\n\")\r\n print(\"{} + {} = {}\".format(asquare,bsquare,csquare) )\r\n\r\n else:\r\n print(\"Nopes! Its not a Pythagorean Triple\")\r\n print(\"{} + {} is not = {}\".format(asquare, bsquare, csquare))\r\n\r\n\r\n\r\ndef main():\r\n print(\"Check if a triangle is Pythagorean triples\")\r\n\r\n a = int(input(\"input first integer a\"))\r\n b = int(input(\"input second integer b\"))\r\n c = int(input(\"input third integer c\"))\r\n\r\n PyTriples(a, b, c)\r\n\r\n again=input(\"Wanna Try again? y/n\")\r\n if again=='y':\r\n main()\r\n else:\r\n print(\"Goodbye! Thanks for using this app\")\r\n\r\nif __name__==\"__main__\": main()","sub_path":"Pythagorean Triples Checker.py","file_name":"Pythagorean Triples Checker.py","file_ext":"py","file_size_in_byte":1086,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"153667578","text":"import sys\nfrom troposphere import GetAtt, Join, Output, Parameter, Ref, Template\nfrom troposphere.s3 import Bucket, Private\n\nenv = sys.argv[1]\n\nCOMPONENT_NAME = env + \"YaegarBooksSharedResources\"\n\nt = Template(COMPONENT_NAME)\n\nt.add_version(\"2010-09-09\")\n\nt.add_description(COMPONENT_NAME + \" stacks\")\n\ns3bucket = t.add_resource(\n Bucket(\n \"S3BucketSharedResources\",\n AccessControl=Private\n )\n)\n\nt.add_output([\n Output(\n \"S3bucketArn\",\n Value=GetAtt(s3bucket, \"Arn\"),\n Description=\"Arn for S3\"\n )\n])\n\nprint(t.to_json())\n","sub_path":"stacks/src/shared-buckets.py","file_name":"shared-buckets.py","file_ext":"py","file_size_in_byte":568,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"450355381","text":"import functools\nimport logging\nfrom datetime import datetime\nfrom django.conf.urls import patterns, url\nfrom django.core.urlresolvers import reverse\nfrom django.db.models import Q\nfrom django.views.decorators.cache import never_cache\nfrom restlib2.http import codes\nfrom preserialize.serialize import serialize\nfrom avocado.models import DataQuery\nfrom avocado.events import usage\nfrom serrano import utils\nfrom serrano.forms import QueryForm\nfrom .base import ThrottledResource\nfrom .history import RevisionsResource, ObjectRevisionsResource, \\\n ObjectRevisionResource\nfrom . import templates\n\nlog = logging.getLogger(__name__)\n\nDELETE_QUERY_EMAIL_TITLE = \"'{0}' has been deleted\"\nDELETE_QUERY_EMAIL_BODY = \"\"\"The query named '{0}' has been deleted. You are\n being notified because this query was shared with you. This query is no\n longer available.\"\"\"\n\n\ndef query_posthook(instance, data, request):\n uri = request.build_absolute_uri\n data['_links'] = {\n 'self': {\n 'href': uri(reverse('serrano:queries:single', args=[instance.pk])),\n },\n 'forks': {\n 'href': uri(reverse('serrano:queries:forks', args=[instance.pk])),\n },\n 'stats': {\n 'href': uri(reverse('serrano:queries:stats', args=[instance.pk])),\n }\n }\n\n if getattr(instance, 'user', None) and instance.user.is_authenticated():\n data['is_owner'] = instance.user == request.user\n else:\n data['is_owner'] = instance.session_key == request.session.session_key\n\n if not data['is_owner']:\n del data['shared_users']\n\n return data\n\n\ndef forked_query_posthook(instance, data, request):\n uri = request.build_absolute_uri\n data['_links'] = {\n 'self': {\n 'href': uri(reverse('serrano:queries:single', args=[instance.pk])),\n },\n 'parent': {\n 'href': uri(reverse('serrano:queries:single',\n args=[instance.parent.pk])),\n }\n }\n\n return data\n\n\nclass QueryBase(ThrottledResource):\n cache_max_age = 0\n private_cache = True\n\n model = DataQuery\n template = templates.Query\n\n def prepare(self, request, instance, template=None):\n if template is None:\n template = self.template\n posthook = functools.partial(query_posthook, request=request)\n return serialize(instance, posthook=posthook, **template)\n\n def get_queryset(self, request, **kwargs):\n \"Constructs a QuerySet for this user or session.\"\n\n if getattr(request, 'user', None) and request.user.is_authenticated():\n kwargs['user'] = request.user\n elif request.session.session_key:\n kwargs['session_key'] = request.session.session_key\n else:\n # The only case where kwargs is empty is for non-authenticated\n # cookieless agents.. e.g. bots, most non-browser clients since\n # no session exists yet for the agent.\n return self.model.objects.none()\n\n return self.model.objects.filter(**kwargs)\n\n def get_object(self, request, pk=None, session=None, **kwargs):\n if not pk and not session:\n raise ValueError('A pk or session must used for the lookup')\n\n if not hasattr(request, 'instance'):\n queryset = self.get_queryset(request, **kwargs)\n\n try:\n if pk:\n instance = queryset.get(pk=pk)\n else:\n instance = queryset.get(session=True)\n except self.model.DoesNotExist:\n instance = None\n\n request.instance = instance\n\n return request.instance\n\n\nclass QueriesResource(QueryBase):\n \"Resource for accessing the queries a shared with or owned by a user\"\n template = templates.Query\n\n def prepare(self, request, instance, template=None):\n if template is None:\n template = self.template\n posthook = functools.partial(query_posthook, request=request)\n return serialize(instance, posthook=posthook, **template)\n\n def get_queryset(self, request, **kwargs):\n if getattr(request, 'user', None) and request.user.is_authenticated():\n f = Q(user=request.user) | Q(shared_users__pk=request.user.pk)\n elif request.session.session_key:\n f = Q(session_key=request.session.session_key)\n else:\n return super(QueriesResource, self).get_queryset(request, **kwargs)\n return self.model.objects.filter(f, **kwargs) \\\n .order_by('-accessed').distinct()\n\n def get(self, request):\n queryset = self.get_queryset(request)\n return self.prepare(request, queryset)\n\n def post(self, request):\n form = QueryForm(request, request.data)\n\n if form.is_valid():\n instance = form.save()\n usage.log('create', instance=instance, request=request)\n request.session.modified = True\n response = self.render(request, self.prepare(request, instance),\n status=codes.created)\n else:\n data = {\n 'message': 'Error creating query',\n 'errors': dict(form.errors),\n }\n response = self.render(request, data,\n status=codes.unprocessable_entity)\n return response\n\n\nclass QueryForksResource(QueryBase):\n \"Resource for accessing forks of the specified query or forking the query\"\n template = templates.ForkedQuery\n\n def is_not_found(self, request, response, **kwargs):\n return self.get_object(request, **kwargs) is None\n\n def get_queryset(self, request, **kwargs):\n instance = self.get_object(request, **kwargs)\n return self.model.objects.filter(parent=instance.pk)\n\n def get_object(self, request, pk=None, **kwargs):\n if not pk:\n raise ValueError('A pk must be used for the fork lookup')\n\n if not hasattr(request, 'instance'):\n try:\n instance = self.model.objects.get(pk=pk)\n except self.model.DoesNotExist:\n instance = None\n\n request.instance = instance\n\n return request.instance\n\n def prepare(self, request, instance, template=None):\n if template is None:\n template = self.template\n\n posthook = functools.partial(forked_query_posthook, request=request)\n return serialize(instance, posthook=posthook, **template)\n\n def _requestor_can_get_forks(self, request, instance):\n \"\"\"\n A user can retrieve the forks of a query if that query is public or\n if they are the owner of that query.\n \"\"\"\n if instance.public:\n return True\n\n if not getattr(request, 'user', None):\n return False\n\n return (request.user.is_authenticated() and\n request.user == instance.user)\n\n def _requestor_can_fork(self, request, instance):\n \"\"\"\n A user can fork a query if that query is public or if they are the\n owner or in the shared_users group of that query.\n \"\"\"\n if instance.public:\n return True\n\n if getattr(request, 'user', None) and request.user.is_authenticated():\n return (request.user == instance.user or\n instance.shared_users.filter(pk=request.user.pk).exists())\n\n return False\n\n def get(self, request, **kwargs):\n instance = self.get_object(request, **kwargs)\n\n if self._requestor_can_get_forks(request, instance):\n return self.prepare(request, self.get_queryset(request, **kwargs))\n\n data = {\n 'message': 'Cannot access forks',\n }\n return self.render(request, data, status=codes.unauthorized)\n\n def post(self, request, **kwargs):\n instance = self.get_object(request, **kwargs)\n\n if self._requestor_can_fork(request, instance):\n fork = DataQuery(name=instance.name,\n description=instance.description,\n view_json=instance.view_json,\n context_json=instance.context_json,\n parent=instance)\n\n if getattr(request, 'user', None):\n fork.user = request.user\n elif request.session.session_key:\n fork.session_key = request.session.session_key\n\n fork.save()\n request.session.modified = True\n\n posthook = functools.partial(query_posthook, request=request)\n data = serialize(fork, posthook=posthook, **templates.Query)\n\n return self.render(request, data, status=codes.created)\n\n data = {\n 'message': 'Cannot fork query',\n }\n return self.render(request, data, status=codes.unauthorized)\n\n\nclass PublicQueriesResource(QueryBase):\n \"Resource for accessing public queries\"\n template = templates.BriefQuery\n\n def prepare(self, request, instance, template=None):\n if template is None:\n template = self.template\n\n posthook = functools.partial(query_posthook, request=request)\n return serialize(instance, posthook=posthook, **template)\n\n def get_queryset(self, request, **kwargs):\n kwargs['public'] = True\n\n return self.model.objects.filter(**kwargs).order_by('-accessed') \\\n .distinct()\n\n def get(self, request):\n queryset = self.get_queryset(request)\n return self.prepare(request, queryset)\n\n\nclass QueryResource(QueryBase):\n \"Resource for accessing a single query\"\n def is_not_found(self, request, response, **kwargs):\n return self.get_object(request, **kwargs) is None\n\n def get(self, request, **kwargs):\n instance = self.get_object(request, **kwargs)\n usage.log('read', instance=instance, request=request)\n\n self.model.objects.filter(pk=instance.pk).update(\n accessed=datetime.now())\n\n return self.prepare(request, instance)\n\n def put(self, request, **kwargs):\n instance = self.get_object(request, **kwargs)\n\n form = QueryForm(request, request.data, instance=instance)\n\n if form.is_valid():\n instance = form.save()\n usage.log('update', instance=instance, request=request)\n request.session.modified = True\n response = self.render(request, self.prepare(request, instance))\n else:\n data = {\n 'message': 'Cannot update query',\n 'errors': dict(form.errors),\n }\n response = self.render(request, data,\n status=codes.unprocessable_entity)\n return response\n\n def delete(self, request, **kwargs):\n instance = self.get_object(request, **kwargs)\n\n if instance.session:\n data = {\n 'message': 'Cannot delete session query',\n }\n return self.render(request, data, status=codes.bad_request)\n\n utils.send_mail(instance.shared_users.values_list('email', flat=True),\n DELETE_QUERY_EMAIL_TITLE.format(instance.name),\n DELETE_QUERY_EMAIL_BODY.format(instance.name))\n\n instance.delete()\n usage.log('delete', instance=instance, request=request)\n request.session.modified = True\n\n\nclass QueryStatsResource(QueryBase):\n def is_not_found(self, request, response, **kwargs):\n return self.get_object(request, **kwargs) is None\n\n def get(self, request, **kwargs):\n instance = self.get_object(request, **kwargs)\n\n return {\n 'distinct_count': instance.context.apply().distinct().count(),\n 'record_count': instance.apply().count()\n }\n\n\nsingle_resource = never_cache(QueryResource())\nactive_resource = never_cache(QueriesResource())\npublic_resource = never_cache(PublicQueriesResource())\nforks_resource = never_cache(QueryForksResource())\nstats_resource = never_cache(QueryStatsResource())\n\nrevisions_resource = never_cache(RevisionsResource(\n object_model=DataQuery, object_model_template=templates.Query,\n object_model_base_uri='serrano:queries'))\nrevisions_for_object_resource = never_cache(ObjectRevisionsResource(\n object_model=DataQuery, object_model_template=templates.Query,\n object_model_base_uri='serrano:queries'))\nrevision_for_object_resource = never_cache(ObjectRevisionResource(\n object_model=DataQuery, object_model_template=templates.Query,\n object_model_base_uri='serrano:queries'))\n\n# Resource endpoints\nurlpatterns = patterns(\n '',\n url(r'^$', active_resource, name='active'),\n\n # Endpoints for specific queries\n url(r'^public/$', public_resource, name='public'),\n\n # Single queries\n url(r'^(?P\\d+)/$', single_resource, name='single'),\n url(r'^session/$', single_resource, {'session': True}, name='session'),\n\n # Stats\n url(r'^(?P\\d+)/stats/$', stats_resource, name='stats'),\n url(r'^session/stats/$', stats_resource, {'session': True}, name='stats'),\n\n # Forks\n # TODO add endpoint for session?\n url(r'^(?P\\d+)/forks/$', forks_resource, name='forks'),\n\n # Revision related endpoints\n url(r'^revisions/$', revisions_resource, name='revisions'),\n url(r'^(?P\\d+)/revisions/$', revisions_for_object_resource,\n name='revisions_for_object'),\n url(r'^(?P\\d+)/revisions/(?P\\d+)/$',\n revision_for_object_resource, name='revision_for_object'),\n)\n","sub_path":"charlies_revenge/lib/python2.7/site-packages/serrano/resources/query.py","file_name":"query.py","file_ext":"py","file_size_in_byte":13488,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"465418945","text":"# -*- coding: utf-8 -*-\n#\n# Copyright (C) 2019 CESNET.\n#\n# PyFS Multi-checksum File Storage is free software; you can redistribute it and/or modify it\n# under the terms of the MIT License; see LICENSE file for more details.\n\n\"\"\"PyFS Multi-checksum File Storage classes.\"\"\"\nfrom invenio_files_rest.storage import PyFSFileStorage, pyfs_storage_factory\n\n\nclass MultiChecksumFileStorage(PyFSFileStorage):\n \"\"\"File system storage extending PyFSFileStorage with multiple checksum algorithms support.\n \"\"\"\n\n def send_file(self, filename, mimetype=None, restricted=True,\n checksum=None, trusted=False, chunk_size=None,\n as_attachment=False):\n \"\"\"Send the file to the client.\"\"\"\n algos, checksums = checksum.split(':')\n algos = algos.split('+')\n checksums = checksums.split(';')\n for idx, sum in enumerate(checksums):\n if algos[idx] == 'md5':\n checksum = sum\n break\n else:\n checksum = None\n\n return super(MultiChecksumFileStorage, self).send_file(filename, mimetype, restricted, checksum,\n trusted, chunk_size, as_attachment)\n\n\ndef multichecksum_storage_factory(fileinstance=None, default_location=None,\n default_storage_class=None,\n filestorage_class=MultiChecksumFileStorage, fileurl=None,\n size=None, modified=None, clean_dir=True):\n \"\"\"Get factory function for creating a PyFS file storage instance.\"\"\"\n return pyfs_storage_factory(fileinstance, default_location, default_storage_class,\n filestorage_class, fileurl, size, modified, clean_dir)\n","sub_path":"invenio_files_multisum_storage/storage.py","file_name":"storage.py","file_ext":"py","file_size_in_byte":1792,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"207828988","text":"# Copyright 2014 Google Inc. All Rights Reserved.\n\n\"\"\"List operations command.\"\"\"\nfrom googlecloudapis.apitools.base import py as apitools_base\nfrom googlecloudsdk.calliope import base\nfrom googlecloudsdk.calliope import exceptions\nfrom googlecloudsdk.container.lib import util\nfrom googlecloudsdk.core import properties\nfrom googlecloudsdk.core import resources\nfrom googlecloudsdk.core.util import list_printer\n\n\nclass List(base.Command):\n \"\"\"List operations for container clusters.\"\"\"\n\n @staticmethod\n def Args(parser):\n \"\"\"Register flags for this command.\n\n Args:\n parser: An argparse.ArgumentParser-like object. It is mocked out in order\n to capture some information, but behaves like an ArgumentParser.\n \"\"\"\n pass\n\n def Run(self, args):\n \"\"\"This is what gets called when the user runs this command.\n\n Args:\n args: an argparse namespace. All the arguments that were provided to this\n command invocation.\n\n Returns:\n Some value that we want to have printed later.\n \"\"\"\n client = self.context['container_client']\n messages = self.context['container_messages']\n\n project_id = properties.VALUES.core.project.Get(required=True)\n zone_id = None\n if args.zone:\n zone_id = resources.Parse(args.zone, collection='compute.zones').zone\n\n try:\n if zone_id:\n # Zone-filtered list\n req = messages.ContainerProjectsZonesOperationsListRequest(\n projectId=project_id, zoneId=zone_id)\n return client.projects_zones_operations.List(req)\n else:\n # Global list\n req = messages.ContainerProjectsOperationsListRequest(\n projectId=project_id)\n return client.projects_operations.List(req)\n except apitools_base.HttpError as error:\n raise exceptions.HttpException(util.GetError(error))\n\n def Display(self, args, result):\n \"\"\"This method is called to print the result of the Run() method.\n\n Args:\n args: The arguments that command was run with.\n result: The value returned from the Run() method.\n \"\"\"\n list_printer.PrintResourceList(\n 'container.projects.zones.operations', result.operations)\n","sub_path":"sdk/google-cloud-sdk/.install/.backup/lib/googlecloudsdk/container/commands/operations/list.py","file_name":"list.py","file_ext":"py","file_size_in_byte":2165,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"484095867","text":"import os\nimport numpy as np\nimport pandas as pd\nfrom tqdm import tqdm\n\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport torch.backends.cudnn as cudnn\n\n\nclass PointDeepFM(nn.Module):\n def __init__(self,\n user_num, \n item_num, \n factors, \n act_activation,\n num_layers, # [32, 32] for example\n batch_norm,\n q, \n epochs, \n lr, \n reg_1=0.,\n reg_2=0.,\n loss_type='CL', \n gpuid='0', \n early_stop=True):\n \"\"\"\n Point-wise DeepFM Recommender Class\n Parameters\n ----------\n user_num : int, the number of users\n item_num : int, the number of items\n factors : int, the number of latent factor\n act_activation : str, activation function for hidden layer\n num_layers : int, number of hidden layers\n batch_norm : bool, whether to normalize a batch of data\n q : float, dropout rate\n epochs : int, number of training epochs\n lr : float, learning rate\n reg_1 : float, first-order regularization term\n reg_2 : float, second-order regularization term\n loss_type : str, loss function type\n gpuid : str, GPU ID\n early_stop : bool, whether to activate early stop mechanism\n \"\"\"\n super(PointDeepFM, self).__init__()\n os.environ['CUDA_VISIBLE_DEVICES'] = gpuid\n cudnn.benchmark = True\n\n self.factors = factors\n self.act_function = act_activation\n self.num_layers = num_layers\n self.batch_norm = batch_norm\n self.dropout = q\n self.epochs = epochs\n self.lr = lr\n self.reg_1 = reg_1\n self.reg_2 = reg_2\n self.loss_type = loss_type\n self.early_stop = early_stop\n\n self.embed_user = nn.Embedding(user_num, factors)\n self.embed_item = nn.Embedding(item_num, factors)\n\n self.u_bias = nn.Embedding(user_num, 1)\n self.i_bias = nn.Embedding(item_num, 1)\n\n self.bias_ = nn.Parameter(torch.tensor([0.0]))\n\n fm_modules = []\n if self.batch_norm:\n fm_modules.append(nn.BatchNorm1d(factors))\n fm_modules.append(nn.Dropout(self.dropout))\n self.fm_layers = nn.Sequential(*fm_modules)\n\n deep_modules = []\n in_dim = factors * 2 # user & item\n for _ in range(self.num_layers): # _ is dim if layers is list\n out_dim = in_dim\n deep_modules.append(nn.Linear(in_dim, out_dim))\n in_dim = out_dim\n if self.batch_norm:\n deep_modules.append(nn.BatchNorm1d(out_dim))\n if self.act_function == 'relu':\n deep_modules.append(nn.ReLU())\n elif self.act_function == 'sigmoid':\n deep_modules.append(nn.Sigmoid())\n elif self.act_function == 'tanh':\n deep_modules.append(nn.Tanh())\n deep_modules.append(nn.Dropout(self.dropout))\n\n self.deep_layers = nn.Sequential(*deep_modules)\n self.deep_out = nn.Linear(in_dim, 1, bias=False)\n\n self._init_weight()\n\n def _init_weight(self):\n nn.init.normal_(self.embed_item.weight, std=0.01)\n nn.init.normal_(self.embed_user.weight, std=0.01)\n nn.init.constant_(self.u_bias.weight, 0.0)\n nn.init.constant_(self.i_bias.weight, 0.0)\n\n # for deep layers\n for m in self.deep_layers:\n if isinstance(m, nn.Linear):\n nn.init.xavier_normal_(m.weight)\n nn.init.xavier_normal_(self.deep_out.weight)\n\n def forward(self, user, item):\n embed_user = self.embed_user(user)\n embed_item = self.embed_item(item)\n\n fm = embed_user * embed_item\n fm = self.FM_layers(fm)\n y_fm = fm.sum(dim=-1)\n\n y_fm = y_fm + self.u_bias(user) + self.i_bias(item) + self.bias_\n\n if self.num_layers:\n fm = self.deep_layers(fm)\n\n y_deep = torch.cat((embed_user, embed_item), dim=-1)\n y_deep = self.deep_layers(y_deep)\n\n # since BCELoss will automatically transfer pred with sigmoid\n # there is no need to use extra nn.Sigmoid(pred)\n pred = y_fm + y_deep\n\n return pred.view(-1)\n\n def fit(self, train_loader):\n if torch.cuda.is_available():\n self.cuda()\n else:\n self.cpu()\n\n optimizer = optim.SGD(self.parameters(), lr=self.lr)\n if self.loss_type == 'CL':\n criterion = nn.BCEWithLogitsLoss(reduction='sum')\n elif self.loss_type == 'SL':\n criterion = nn.MSELoss(reduction='sum')\n else:\n raise ValueError(f'Invalid loss type: {self.loss_type}')\n\n last_loss = 0.\n for epoch in range(1, self.epochs + 1):\n self.train()\n\n current_loss = 0.\n # set process bar display\n pbar = tqdm(train_loader)\n pbar.set_description(f'[Epoch {epoch:03d}]')\n for user, item, label in pbar:\n if torch.cuda.is_available():\n user = user.cuda()\n item = item.cuda()\n label = label.cuda()\n else:\n user = user.cpu()\n item = item.cpu()\n label = label.cpu()\n\n self.zero_grad()\n prediction = self.forward(user, item)\n\n loss = criterion(prediction, label)\n loss += self.reg_1 * (self.embed_item.weight.norm(p=1) +self.embed_user.weight.norm(p=1))\n loss += self.reg_2 * (self.embed_item.weight.norm() +self.embed_user.weight.norm())\n\n if torch.isnan(loss):\n raise ValueError(f'Loss=Nan or Infinity: current settings does not fit the recommender')\n\n loss.backward()\n optimizer.step()\n\n pbar.set_postfix(loss=loss.item())\n current_loss += loss.item()\n\n self.eval()\n delta_loss = float(current_loss - last_loss)\n if (abs(delta_loss) < 1e-5) and self.early_stop:\n print('Satisfy early stop mechanism')\n break\n else:\n last_loss = current_loss\n\n def predict(self, u, i):\n pred = self.forward(u, i).cpu()\n \n return pred\n\n\n","sub_path":"daisy/model/point/DeepFMRecommender.py","file_name":"DeepFMRecommender.py","file_ext":"py","file_size_in_byte":6446,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"388318468","text":"import numpy as np\nimport pandas as pd\nimport xgboost as xgb\nimport my_scripts.data_cleaning as dc\nimport matplotlib.pyplot as plt\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import mean_absolute_error, auc, roc_curve, accuracy_score, matthews_corrcoef, f1_score \n \n\nclass XGBoost_classifier_trainer:\n def __init__(self, df, target, split_test=True, learning_rate=1e-2, max_depth=5, n_estimators=10): \n # store relevant variables for later use \n self.target = target\n self.split_test = split_test\n \n # encode dataframe \n self.df, self.mappings = self.data_encoding(df)\n \n # prepare the train, test and validation set \n if split_test: \n self.X_train, self.X_test, self.y_train, self.y_test = train_test_split(self.df.drop(columns=[target]), self.df[target], test_size=0.2)\n else: \n self.X_train, self.y_train = self.df.drop(columns=[target]), self.df[target]\n \n self.X_train, self.X_valid, self.y_train, self.y_valid = train_test_split(self.X_train, self.y_train, test_size=0.2)\n \n # initialy, no assumption on features on which model should be trained \n self.features = self.X_train.columns\n \n # initialize model \n self.model = clf_xgb = xgb.XGBClassifier(max_depth=max_depth,\n learning_rate=learning_rate,\n n_estimators=n_estimators,\n verbosity=0,\n objective='binary:logistic',\n booster='gbtree',\n n_jobs=-1,\n subsample=0.7,\n use_label_encoder=False,\n )\n \n self.best_params = None\n \n def data_encoding(self, df): \n mappings = {}\n for col in dc.non_numerical_features(df):\n df, mapping = dc.feature_ordinalEncoding(df, col)\n mappings[col] = mapping\n return df, mappings\n \n \n def get_model(self):\n return self.model\n \n def get_training_data(self):\n return self.X_train, self.y_train\n \n def get_testing_data(self):\n if self.split_test: \n return self.X_test, self.y_test\n else:\n print(\"No training set defined. Please define a training set.\") \n return\n \n def get_validation_data(self):\n return self.X_valid, self.y_valid\n \n def get_best_params(self):\n return self.best_params\n \n def print_kpi(self, features):\n if self.split_test:\n y_pred = self.model.predict(self.X_test[features])\n # plot some relevant KPI\n print('Accuracy: {:.2f}'.format(accuracy_score(y_pred, self.y_test)))\n print('MCC Score: {:.2f}'.format(matthews_corrcoef(self.y_test, y_pred)))\n print('F1 Score: {:.2f}'.format(f1_score(self.y_test, y_pred)))\n \n # plot ROC curve \n fpr, tpr, _ = roc_curve(self.y_test, self.model.predict_proba(self.X_test[features])[:,1])\n plt.plot(fpr, tpr)\n plt.plot([0, 1], [0, 1],'r--')\n plt.xlabel(\"False Positive Rate\")\n plt.ylabel(\"True Positive Rate\")\n plt.title(\"ROC Curve - Area = {:.5f}\".format(auc(fpr, tpr)));\n else: \n print(\"No training set defined. Please define a training set.\")\n return\n \n def train_model(self, features=None, verbose=0, end_evaluation=False):\n if type(features) == type(None): \n features = self.X_train.columns\n \n self.features = features\n \n # train the model \n self.model.fit(self.X_train[features], self.y_train,\n eval_set=[(self.X_valid[features], self.y_valid)],\n early_stopping_rounds=100,\n verbose=verbose\n )\n \n # print some key kpi\n if end_evaluation:\n self.print_kpi(features)\n \n def find_best_params(self, max_depths, learning_rates, n_estimators, features, scoring='roc_auc'): \n min_max_depth = float('-inf')\n min_learning_rate = float('-inf')\n min_n_estimator = float('-inf')\n best_min_score = float('-inf')\n\n for max_depth in max_depths:\n for learning_rate in learning_rates: \n for n_estimator in n_estimators: \n # model definition\n clf_xgb = xgb.XGBClassifier(max_depth=max_depth,\n learning_rate=learning_rate,\n n_estimators=n_estimator,\n verbosity=0,\n objective='binary:logistic',\n booster='gbtree',\n n_jobs=-1,\n subsample=0.7,\n use_label_encoder=False,\n )\n\n # cross validation training\n min_current_score = np.min(cross_val_score(clf_xgb, self.X_train[features], self.y_train))\n\n if best_min_score < min_current_score: \n min_max_depth = max_depth\n min_learning_rate = learning_rate\n min_n_estimator = n_estimator\n best_min_score = min_current_score\n\n print(\"Best CV min score: {:.2f}\".format(best_min_score))\n self.best_params = {'max_depth': min_max_depth, 'learning_rate': min_learning_rate, 'n_estimator': min_n_estimator}\n return self.best_params\n \n def train_model_on_best_params(self, max_depths, learning_rates, n_estimators, features=None, scoring='roc_auc', end_evaluation=False):\n if type(features) == type(None): \n features = self.X_train.columns\n \n self.features = features\n \n self.find_best_params(max_depths, learning_rates, n_estimators, features, scoring)\n \n learning_rate = self.best_params['learning_rate']\n max_depth = self.best_params['max_depth']\n n_estimators = self.best_params['n_estimator']\n \n self.model = xgb.XGBClassifier(max_depth=max_depth,\n learning_rate=learning_rate,\n n_estimators=n_estimators,\n verbosity=0,\n objective='binary:logistic',\n booster='gbtree',\n n_jobs=-1,\n subsample=0.7,\n )\n \n # train the model \n self.model.fit(X_train[features], y_train,\n eval_set=[(X_valid[features], y_valid)],\n early_stopping_rounds=100,\n verbose=0)\n\n if end_evaluation: \n self.print_kpi(features)\n \n def print_feature_importance(self, nbr_features_to_print=10):\n features=self.features\n dict_feature_importance = dict(zip(features, self.model.feature_importances_))\n dict_feature_importance = {k: v for k, v in sorted(dict_feature_importance.items(), key=lambda item: item[1], reverse=True)}\n\n fig, ax = plt.subplots()\n y_pos = np.arange(len(features))\n\n ax.barh(y_pos[:nbr_features_to_print], list(dict_feature_importance.values())[:nbr_features_to_print], align='center')\n ax.set_yticks(y_pos[:nbr_features_to_print])\n ax.set_yticklabels(list(dict_feature_importance.keys())[:nbr_features_to_print])\n ax.invert_yaxis() # labels read top-to-bottom\n ax.set_xlabel('Relative Importance in the Descision')\n ax.set_title('Feature Importance')\n plt.show() \n return\n \n def return_k_most_important_features(self, k=1):\n features=self.features\n dict_feature_importance = dict(zip(features, self.model.feature_importances_))\n dict_feature_importance = {k_: v for k_, v in sorted(dict_feature_importance.items(), key=lambda item: item[1], reverse=True)}\n return np.array(list(dict_feature_importance.keys())[:k])","sub_path":"Hotel Bookings/my_scripts/XGBoost_trainer.py","file_name":"XGBoost_trainer.py","file_ext":"py","file_size_in_byte":8234,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"97075104","text":"\"\"\"\nluas.api\n~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nProvides methods for interrogating Dublin's Luas tram API\n\nCopyright (c) 2018 Ronan Murray \nLicensed under the MIT License\n\"\"\"\n\nimport logging\nfrom xml.etree import ElementTree\nfrom xml.etree.ElementTree import ParseError\nimport requests\nfrom luas.models import LuasLine, LuasDirection, LuasTram, LuasStops\n\n_LOGGER = logging.getLogger(__name__)\n\nATTR_STATUS = 'status'\nATTR_TRAMS = 'trams'\nATTR_DUE = 'due'\nATTR_DESTINATION = 'destination'\nATTR_DIRECTION = 'direction'\nATTR_ABBREV = 'abrev'\n\nATTR_INBOUND_VAL = 'Inbound'\nATTR_OUTBOUND_VAL = 'Outbound'\n\nDEFAULT_LUAS_API = \"http://luasforecasts.rpa.ie/xml/get.ashx\"\nDEFAULT_PARAMS = {'action': 'forecast', 'encrypt': 'false', 'stop': ''}\nDEFAULT_GREEN_LINE_STOP = 'STS'\nDEFAULT_RED_LINE_STOP = 'TAL'\nATTR_STOP_VAL = 'stop'\nATTR_DUE_VAL = 'dueMins'\nATTR_DESTINATION_VAL = 'destination'\nATTR_NO_TRAMS = 'No trams forecast'\n\nXPATH_STATUS = \".//message\"\nXPATH_DIRECTION_INBOUND = \".//direction[@name='Inbound']/tram\"\nXPATH_DIRECTION_OUTBOUND = \".//direction[@name='Outbound']/tram\"\n\n\nclass LuasClient:\n \"\"\"\n Create new Luas API client interface\n \"\"\"\n\n def __init__(self, api_endpoint=None, use_gzip=True):\n\n if not api_endpoint:\n api_endpoint = DEFAULT_LUAS_API\n\n _LOGGER.debug(\"Using API at %s\", api_endpoint)\n\n self._api_endpoint = api_endpoint\n self._use_gzip = use_gzip\n self._session = requests.Session()\n self._stops = LuasStops()\n\n def stop_details(self, stop):\n \"\"\"\n Returns raw JSON of the Luas details from the requested stop.\n :param stop: Stop to enquire about\n :return:\n \"\"\"\n response = {\n ATTR_STATUS: 'n/a',\n ATTR_TRAMS: []\n }\n\n luas_params = DEFAULT_PARAMS\n selected_stop = self._stops.stop(stop)\n if selected_stop is None:\n _LOGGER.error(\"Stop '%s' is not valid\", stop)\n return response\n\n DEFAULT_PARAMS[ATTR_STOP_VAL] = selected_stop[ATTR_ABBREV]\n\n if self._use_gzip:\n self._session.headers.update({'Accept-Encoding': 'gzip'})\n\n api_response = self._session.get(self._api_endpoint,\n params=luas_params)\n\n if api_response.status_code == 200:\n _LOGGER.debug('Response received for %s', stop)\n try:\n tree = ElementTree.fromstring(api_response.content)\n status = tree.find(XPATH_STATUS).text.strip()\n trams = []\n\n result = tree.findall(XPATH_DIRECTION_INBOUND)\n if result is not None:\n for tram in result:\n if tram.attrib[ATTR_DESTINATION_VAL] != ATTR_NO_TRAMS:\n trams.append({\n ATTR_DUE: tram.attrib[ATTR_DUE_VAL],\n ATTR_DIRECTION: ATTR_INBOUND_VAL,\n ATTR_DESTINATION:\n tram.attrib[ATTR_DESTINATION_VAL]\n })\n\n result = tree.findall(XPATH_DIRECTION_OUTBOUND)\n if result is not None:\n for tram in result:\n if tram.attrib[ATTR_DESTINATION_VAL] != ATTR_NO_TRAMS:\n trams.append({\n ATTR_DUE: tram.attrib[ATTR_DUE_VAL],\n ATTR_DIRECTION: ATTR_OUTBOUND_VAL,\n ATTR_DESTINATION:\n tram.attrib[ATTR_DESTINATION_VAL]\n })\n\n response[ATTR_STATUS] = status\n response[ATTR_TRAMS] = trams\n except ParseError as parse_err:\n _LOGGER.error(\n 'There was a problem parsing the Luas API response %s',\n parse_err\n )\n _LOGGER.error('Entire response %s', api_response.content)\n except AttributeError as attib_err:\n _LOGGER.error(\n 'There was a problem parsing the Luas API response %s',\n attib_err)\n _LOGGER.error('Entire response: %s', api_response.content)\n\n else:\n _LOGGER.error(\n 'HTTP error processing Luas response %s',\n api_response.status_code\n )\n\n return response\n\n def line_status(self, line=LuasLine.Green):\n \"\"\"\n Fetches the status of the line in questions\n :param line: Luas line in question\n :return: text description of the current line status\n \"\"\"\n\n stop = DEFAULT_GREEN_LINE_STOP\n if line == LuasLine.Red:\n stop = DEFAULT_RED_LINE_STOP\n\n response = self.stop_details(stop)\n return response[ATTR_STATUS]\n\n def all_trams(self, stop):\n \"\"\"\n Returns all trams from the provided stop\n :param stop: stop to search from\n :return: list of all trams\n \"\"\"\n stop_details = self.stop_details(stop)\n trams = []\n\n for tram in stop_details[ATTR_TRAMS]:\n trams.append(self._build_luas_tram_from_map(tram))\n\n return trams\n\n def next_tram(self, stop, direction=LuasDirection.Inbound):\n \"\"\"\n Retrieves the next tram departing from the requested stop\n in the requested direction\n :param stop: Stop name\n :param direction: Luas Direction\n :return: LuasTram contain next tram details\n \"\"\"\n\n stop_details = self.stop_details(stop)\n output_tram = None\n for tram in stop_details[ATTR_TRAMS]:\n if direction == LuasDirection.Inbound \\\n and tram[ATTR_DIRECTION] == ATTR_INBOUND_VAL:\n output_tram = tram\n break\n\n if direction == LuasDirection.Outbound \\\n and tram[ATTR_DIRECTION] == ATTR_OUTBOUND_VAL:\n output_tram = tram\n break\n\n return self._build_luas_tram_from_map(output_tram)\n\n @staticmethod\n def _build_luas_tram_from_map(tram):\n if tram is not None:\n direction = LuasDirection.Inbound\n if tram[ATTR_DIRECTION] == ATTR_OUTBOUND_VAL:\n direction = LuasDirection.Outbound\n\n return LuasTram(\n tram[ATTR_DUE],\n direction,\n tram[ATTR_DESTINATION]\n )\n\n return None\n","sub_path":"luas/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":6539,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"254740024","text":"# coding=utf-8\n\n# 参考 http://www.tuicool.com/articles/Inmmei http://effbot.org/imagingbook/image.htm\n\nresDir = \"../../Data/\"\n\n# 用于读取图片,和进行简单地操作\n# 如果文件不是 JPEG 格式,会自动将其转换成 JPEG 格式;如果转换失败,它会在控制台输出一条报告失败的消息。\nfrom PIL import Image\ndef PILImage():\n # 下面这句写出来,方便代码提示查看函数\n img = Image.Image()\n\n img = Image.open(resDir+\"Image/banboo.png\")\n\n # 转换为灰度图 并 保存\n greyImg = img.convert(\"L\")\n greyImg.save(\"PILImage/banboo_grey.png\")\n\n # 创建缩略图\n smallImg = img.copy()\n smallImg.thumbnail((128,128))\n smallImg.save(\"PILImage/banboo_small.png\")\n\n # 裁剪 box = (left, upper, right, lower), PIL 中指定坐标系的左上角坐标为(0,0)\n box=(100, 100, 200, 200)\n cropImg = img.crop(box)\n cropImg.save(\"PILImage/banboo_crop.png\")\n\n # 把裁剪的 旋转 180度后 放回去\n partRotateImg = img.copy()\n cropImg = cropImg.transpose(Image.ROTATE_180)\n partRotateImg.paste(cropImg,box)\n partRotateImg.save(\"PILImage/banboo_part_rotate.png\")\n\n # resize 和 rotate 要旋转一幅图像,可以使用逆时针方式表示旋转角度,然后调用 rotate() 方法:\n changeImg = img.resize((128,128))\n changeImg = changeImg.rotate(45)\n changeImg.save(\"PILImage/banboo_resize_rotate.png\")\n\n # 遍历 访问不可修改 getpixel((x,y)) x是横向,即第几列; y是纵向,即第几行。 或 im[x + y * size(0)]\n # 可修改访问 redImg.load()[x,y]\n redImg = img.copy()\n redImgPix = redImg.load()\n for x in range(img.size[0]):\n for y in range(img.size[1]):\n p = img.getpixel((x,y))\n redImgPix[x,y] = (p[0], 0, 0) # tuple 不允许修改内部元素,只能全部替换,\n # 所以这样常常不使用image本身遍历,而是放到一个array里进行计算\n redImg.save(\"PILImage/banboo_red.png\")\n\n # 使用 array 参考 matplotlib 和 numpyTest\n\nPILImage()\n\n\n\n\n\n\n\n\n","sub_path":"MLInAction/base/Image/PILImage.py","file_name":"PILImage.py","file_ext":"py","file_size_in_byte":2108,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"412607146","text":"# Пунктуация\n#\n# Напишите программу, которая считает количество знаков пунктуации в символьной строке.\n# К знакам пунктуации относятся символы из набора \".,;:!?\". Набор должен храниться\n# в виде множества.\n#\n# Пример:\n#\n# Введите строку: Я! Есть. Грут?! Я, Грут и Есть.\n#\n# Количество знаков пунктуации: 6\nznak = {'.', ',', ';', ':', '!', '?'}\ntext = input('Введите строку: ')\ncount = 0\nfor sym in text:\n if sym in znak:\n count += 1\n\nprint('\\nКоличество знаков пунктуации:', count)\n","sub_path":"19_dict/task_194_1.py","file_name":"task_194_1.py","file_ext":"py","file_size_in_byte":757,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"222394913","text":"import copy\r\nimport struct\r\nimport socket\r\n\r\ndef urltohex(data):#把网址反人性化\r\n url_split = data.split('.')\r\n target = b''\r\n for each in url_split:\r\n target+=struct.pack('b',len(each))+each.encode('utf-8')##查询数据包中的网址是每个点号隔开,前面带一个每个部分的长度\r\n target+=b'\\x00'\r\n return target\r\n\r\n# def gethosts2():#读取本地hosts文件,加入cache\r\n# with open('hosts','r') as f:\r\n# hosts = {}\r\n# for eachline in f:\r\n# data = eachline.replace('\\n','').split(' ')\r\n# target = urltohex(data[0])\r\n# hosts.setdefault(target,set([socket.inet_aton(data[1])]))\r\n# return hosts\r\n\r\ndef gethosts():#同一域名允许保存多个ip\r\n with open('hosts','r') as f:\r\n hosts = {}\r\n for eachline in f:\r\n data = eachline.replace('\\n','').split(' ')##将所有的换行符删除,并以空格为标志切开\r\n target = urltohex(data[0])\r\n i = 1\r\n while i < len(data):\r\n data[i] = socket.inet_aton(data[i])\r\n i+=1\r\n hosts.setdefault(target,set(data[1:]))\r\n return hosts\r\n\r\ndef pack_query(id,url):#客户端网址打包\r\n target = urltohex(url)\r\n return struct.pack('>H',id) + b'\\x01\\x00\\x00\\x01\\x00\\x00\\x00\\x00\\x00\\x00' + target + b'\\x00\\x01\\x00\\x01'\r\n\r\n\r\n\r\ndef geturl(data):#将网址格式人性化\r\n length = data[0]\r\n url=b''\r\n i=1\r\n while length!=0:\r\n url+=data[i:i+length]+b'.'\r\n i = i+length+1\r\n length = data[i-1]\r\n url = url[:-1]\r\n return url\r\n\r\ndef unpack_client(data):#对收到的数据进行处理,网站和ip格式人性化\r\n i=0\r\n #print(data)\r\n while True:##从12位开始往后找直到找到0就可以找到域名(未进行人性化,是16进制和带有长度的形式)\r\n if data[12+i]==0:\r\n break\r\n i+=1 \r\n name = data[12:12+i+1]##找到url并且翻译为字符串\r\n url = geturl(name)\r\n if data[3] == 133:##接收的是错误信号,不用读取直接返回url和0.0.0.0\r\n return url,{'0.0.0.0'}\r\n \r\n result = set([])\r\n num = int(data[6:8].hex(),16)\r\n counti = 0\r\n for i in range(num):\r\n if i==0:\r\n tmp = data[-16:]\r\n else:\r\n tmp = data[-16*(i+1):-16*i]\r\n if tmp[2:4]==b'\\x00\\x01':##如果是ipv4的数据包\r\n counti+=1\r\n ip = tmp[-4:]\r\n a = ''\r\n for each in ip:\r\n a += str(each) + '.'\r\n a = a[:-1]\r\n result.add(copy.deepcopy(a))\r\n \r\n return url,result\r\n\r\ndef unpack_server(data):#对收到的数据进行处理,网站和ip格式为改变,仍为16进制\r\n result = set([])\r\n num = int(data[6:8].hex(),16)\r\n counti = 0\r\n for i in range(num):\r\n if i==0:\r\n tmp = data[-16:]\r\n else:\r\n tmp = data[-16*(i+1):-16*i]\r\n if tmp[2:4]==b'\\x00\\x01':##如果是ipv4的数据包\r\n counti+=1\r\n ip = tmp[-4:]\r\n result.add(copy.deepcopy(ip))\r\n\r\n i=0\r\n while True:##从12位开始往后找直到找到0就可以找到域名(未进行人性化,是16进制和带有长度的形式)\r\n if data[12+i]==0:\r\n break\r\n i+=1 \r\n name = data[12:12+i+1]##找到url保持为16进制\r\n return name,result\r\n\r\n\r\ndef pack(id,url,hosts):#服务端打包发送给客户\r\n ip_set = hosts[url]\r\n ip_num = len(ip_set)\r\n Answers = b''\r\n for each in ip_set:\r\n Answers += b'\\xc0\\x0c\\x00\\x01\\x00\\x01\\x00\\x00\\x00\\x8a\\x00\\x04' + each\r\n if ip_set == {b'\\x00\\x00\\x00\\x00'}:\r\n return id + b'\\x81\\x85\\x00\\x01\\x00\\x00\\x00\\x00\\x00\\x00'+ url + b'\\x00\\x01\\x00\\x01'\r\n return id + b'\\x81\\x80\\x00\\x01' + struct.pack('>H', ip_num) + b'\\x00\\x00\\x00\\x00' + url + b'\\x00\\x01\\x00\\x01' + Answers\r\n","sub_path":"hanshu.py","file_name":"hanshu.py","file_ext":"py","file_size_in_byte":3892,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"418870153","text":"import matplotlib.pyplot as plt\r\nimport matplotlib.pylab as pylab\r\nimport numpy as np\r\nimport os\r\nimport cv2\r\n\r\n# keras\r\nfrom keras.models import Sequential\r\nfrom keras.layers.core import Dense,Activation\r\nfrom keras.optimizers import SGD\r\nfrom keras.utils import np_utils\r\nfrom keras.models import load_model\r\n\r\n\r\ndef create_ann():\r\n ann = Sequential()\r\n ann.add(Dense(128, input_dim=784, activation='sigmoid'))\r\n ann.add(Dense(128,activation='sigmoid'))\r\n ann.add(Dense(52, activation='sigmoid'))\r\n return ann\r\n\r\n\r\ndef train_ann(ann, X_train, y_train):\r\n '''Obucavanje vestacke neuronske mreze'''\r\n X_train = np.array(X_train, np.float32) # dati ulazi\r\n y_train = np.array(y_train, np.float32) # zeljeni izlazi za date ulaze\r\n\r\n # definisanje parametra algoritma za obucavanje\r\n sgd = SGD(lr=0.01, momentum=0.9)\r\n ann.compile(loss='mean_squared_error', optimizer=sgd)\r\n print (\"Pocelo obucavanje\")\r\n # obucavanje neuronske mreze\r\n training=ann.fit(X_train, y_train, epochs=2000, batch_size=1, verbose=0, shuffle=False)\r\n print(training.history)\r\n print(\"Zavrseno\")\r\n return ann\r\n\r\ndef load_image(path):\r\n return cv2.cvtColor(cv2.imread(path), cv2.COLOR_BGR2RGB)\r\ndef image_gray(image):\r\n return cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)\r\ndef image_bin(image_gs):\r\n height, width = image_gs.shape[0:2]\r\n image_binary = np.ndarray((height, width), dtype=np.uint8)\r\n ret,image_bin = cv2.threshold(image_gs, 127, 255, cv2.THRESH_BINARY)\r\n return image_bin\r\ndef invert(image):\r\n return 255-image\r\ndef display_image(image, color= False):\r\n if color:\r\n plt.imshow(image)\r\n plt.show()\r\n else:\r\n plt.imshow(image, 'gray')\r\n plt.show()\r\ndef dilate(image):\r\n kernel = np.ones((3,3)) # strukturni element 3x3 blok\r\n return cv2.dilate(image, kernel, iterations=1)\r\ndef erode(image):\r\n kernel = np.ones((3,3)) # strukturni element 3x3 blok\r\n return cv2.erode(image, kernel, iterations=1)\r\n\r\n\r\ndef scale_to_range(image): # skalira elemente slike na opseg od 0 do 1\r\n ''' Elementi matrice image su vrednosti 0 ili 255.\r\n Potrebno je skalirati sve elemente matrica na opseg od 0 do 1\r\n '''\r\n return image/255\r\n\r\n\r\ndef prepare_for_ann(regions):\r\n ready_for_ann = []\r\n for region in regions:\r\n # skalirati elemente regiona\r\n # region sa skaliranim elementima pretvoriti u vektor\r\n # vektor dodati u listu spremnih regiona\r\n scale = scale_to_range(region)\r\n ready_for_ann.append(matrix_to_vector(scale))\r\n\r\n return ready_for_ann\r\n\r\ndef matrix_to_vector(image):\r\n '''Sliku koja je zapravo matrica 28x28 transformisati u vektor sa 784 elementa'''\r\n return image.flatten()\r\n\r\n\r\ndef resize_region(region):\r\n '''Transformisati selektovani region na sliku dimenzija 28x28'''\r\n return cv2.resize(region,(28,28), interpolation = cv2.INTER_NEAREST)\r\n\r\n\r\ndef select_region(image_bin):\r\n x = 1130;\r\n y = 1280;\r\n h = 340;\r\n w = 200;\r\n region = image_bin[y:y + h + 1, x:x + w + 1]\r\n region=resize_region(region)\r\n region = scale_to_range(region)\r\n region=matrix_to_vector(region)\r\n return region\r\n\r\ndef select_test_region(image_bin):\r\n x = 1812;\r\n y = 111;\r\n h = 125;\r\n w = 249;\r\n region = image_bin[y:y + h + 1, x:x + w + 1]\r\n region=resize_region(region)\r\n region=scale_to_range(region)\r\n region=matrix_to_vector(region)\r\n\r\n return region\r\n\r\n\r\ndef select_roi(image_orig, image_bin):\r\n img, contours, hierarchy = cv2.findContours(image_bin.copy(), cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)\r\n sorted_regions = [] # lista sortiranih regiona po x osi (sa leva na desno)\r\n regions_array = []\r\n x=1130;\r\n y=1280;\r\n h=340;\r\n w=200;\r\n region = image_bin[y:y + h + 1, x:x + w + 1]\r\n region=scale_to_range(region)\r\n region=matrix_to_vector(region)\r\n regions_array.append([resize_region(region), (x, y, w, h)])\r\n cv2.rectangle(image_orig, (x, y), (x + w, y + h), (0, 255, 0), 2)\r\n regions_array = sorted(regions_array, key=lambda item: item[1][0])\r\n sorted_regions = sorted_regions = [region[0] for region in regions_array]\r\n\r\n # sortirati sve regione po x osi (sa leva na desno) i smestiti u promenljivu sorted_regions\r\n return image_orig, sorted_regions\r\n\r\n\r\ndef matrix_to_vector(image):\r\n return image.flatten()\r\n\r\n\r\ndef scale_to_range(image): # skalira elemente slike na opseg od 0 do 1\r\n return image/255\r\n\r\n\r\ndef convert_output(names):\r\n nn_outputs = []\r\n for index in range(len(names)):\r\n output = np.zeros(len(names))\r\n output[index] = 1\r\n nn_outputs.append(output)\r\n return np.array(nn_outputs)\r\n\r\ndef winner(output): # output je vektor sa izlaza neuronske mreze\r\n\r\n return max(enumerate(output), key=lambda x: x[1])[0]\r\n\r\ndef display_result(outputs, alphabet):\r\n result = []\r\n for output in outputs:\r\n result.append(alphabet[winner(output)])\r\n return result\r\nimage_color1 = load_image('test/test.jpg')\r\nplt.imshow(image_color1)\r\nplt.show()\r\n\r\npictures=os.listdir('images')\r\ndata = []\r\nlabels = []\r\nfor card in pictures:\r\n cardname=card.split('.')[0]\r\n labels.append(cardname)\r\n image_color = load_image('images/'+card)\r\n img = invert(image_bin(image_gray(image_color)))\r\n img_bin = erode(dilate(img))\r\n numbers = select_region(img)\r\n testImage=[matrix_to_vector(numbers)]\r\n data.append(matrix_to_vector(numbers))\r\nprint(\"Pokupio regione\")\r\nte_labels=convert_output(labels)\r\n\r\nprint(len(data))\r\nprint(len(te_labels))\r\n\r\nann=create_ann()\r\nprint(\"Mreza kreirana\")\r\n\r\nprint(\"Mreza kreirana\")\r\nprint(len(data))\r\nprint(\"Ulazi\")\r\n\r\nann=train_ann(ann,data,te_labels)\r\n\r\nann.save('NeuralNetwork.h5')\r\nimg2 = invert(image_bin(image_gray(image_color1)))\r\nimg_bin1 = erode(dilate(img2))\r\nregion =[select_test_region(img2)]\r\n\r\nresult=ann.predict(np.array(region))\r\nprint( result)\r\nprint( display_result(result,labels))\r\n#im = cv2.imread('images/poker.jpg')\r\n#gray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)\r\n#blur = cv2.GaussianBlur(gray, (1, 1), 1000)\r\n#flag, thresh = cv2.threshold(blur, 120, 255, cv2.THRESH_BINARY)\r\n\r\n#image,contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)\r\n#image=im.copy()\r\n#cv2.drawContours(image, contours, -1, (255, 0, 0), 1)\r\n#plt.imshow(image)\r\n#plt.show()\r\n#contours = sorted(contours, key=cv2.contourArea, reverse=True)[:5]\r\n\r\n#approx=0;\r\n#for i in range(len(contours)):\r\n # card = contours[i]\r\n # peri = cv2.arcLength(card,True)\r\n # approx = cv2.approxPolyDP(card,0.02*peri,True)\r\n #rect = cv2.minAreaRect(contours[2])\r\n #r = cv2.cv.boxPoints(rect)\r\n\r\n#h = np.array([ [0,0],[449,0],[449,449],[0,449] ],np.float32)\r\n#transform = cv2.getPerspectiveTransform(approx,h)\r\n#warp = cv2.cv.warpPerspective(im,transform,(450,450))\r\n#plt.imshow(warp)\r\n#plt.show()\r\n","sub_path":"soft/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":6861,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"599725332","text":"# This file is part of cbsTAS project\n#\n# Author: Gayathri Lokesh \n#\n# This defines all the global objects and object repositories\n\n_cfg_all_dut_info = {}\n_cfg_all_csp_info = {}\n_cfg_all_duts_obj = {}\n_cfg_out_dir = '/tmp'\n_cfg_log_level = 'INFO'\n_cfg_run_id = 'uninitialized'\n_cfg_timeout = 24 * 60 *60\n_cfg_platforms = []\n_cfg_module = None\n_cfg_user_extended_api = {'all': {}}\n_cfg_platform_api = {}\n_cfg_logger_db = {}\n","sub_path":"cbstas/cbstas_fw/cbstas_gdata/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":444,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"593392837","text":"# ---------------------------------------------------------------------------------------\n# downloads google images using google-images-download python script\n# Because google-images-download can download up to 100 images per call\n# we used the time_range filter to download 100 per day\n# Kindly specify a start_date and end_date in order to obtain 100 images per day\n# The pacakge was downloaded to /home/dan/source/taboola/3rd_party/google-images-download/google_images_download.py\n# but in order to fix a bug, i copied a copy to this directory and updated the python file\n# Prerequisites:\n# 1. Make sure the file google_images_download.py exists in the same directory\n# 2. The file google_images_download.py can be found here - google_images_download.py (There was a bug so please use the version here)\n# 3. sudo apt-get install python3-urllib3 # for python 3\n# or\n# pip3 install urllib3 # for python 3\n#\n# Usage example:\n# Usage : python download_google_images_in_time_range.py search_keywords requested_start_date(mm/dd/yyyy) num_of_days download_limit_per_day(max 100) output_directory split_by_date_flag\n# Example: python download_google_images_in_time_range_main.py dog 01/25/2018 70 /home/dan/source/taboola/3rd_party/google-images-download/google_images_download/downloads/ 0\n# This downloads dog images created 01/25/2018 and the next 70 days, 98 images per day, to the directory /home/dan/source/taboola/3rd_party/google-images-download/google_images_download/downloads/dog/\n# Author: Dan\n# Last updated: 2018-05-06\n# ---------------------------------------------------------------------------------------\n\n\nimport google_images_download\nimport sys\nimport datetime\nimport threading\n\ndef download_images_per_date(search_keywords,requested_date,download_limit,output_directory,split_by_date_flag):\n print('search_keywords [', search_keywords, ']')\n print('requested_date ,mm/dd/yyyy [', requested_date.strftime('%Y_%m_%d'), ']')\n print('download_limit [', download_limit, ']')\n print('search_keywords [', search_keywords, ']')\n print('output_directory [', output_directory, ']')\n print('split_by_date_flag [', split_by_date_flag, ']')\n\n requested_date_string_mmddyyyy=requested_date.strftime('%m/%d/%Y')\n requseted_date_subdirectory=requested_date.strftime('%Y_%m_%d')\n\n output_directory_arg=output_directory\n if(split_by_date_flag):\n output_directory_arg=output_directory+requseted_date_subdirectory+'/'\n\n print('output_directory_arg [', output_directory_arg, ']')\n\n response = google_images_download.googleimagesdownload()\n\n arguments = {\"keywords\": search_keywords,\n \"limit\": download_limit,\n \"print_urls\": True,\n 'time_range': str({\"time_min\": requested_date_string_mmddyyyy, \"time_max\": requested_date_string_mmddyyyy}),\n \"output_directory\": output_directory_arg}\n\n print('Before download', arguments)\n response.download(arguments) # passing the arguments to the function\n print('Finished download. Requested date [', requseted_date_subdirectory, ']')\n\n #\n # # Here is an example of the expected format for the arguments\n # # arguments = {\"keywords\": \"dog\",\n # # \"limit\": 3,\n # # \"print_urls\": True,\n # # 'time_range': str({\"time_min\":\"04/05/2017\",\"time_max\":\"04/05/2017\"}),\n # # \"output_directory\" : '/home/dan/source/taboola/3rd_party/google-images-download/google_images_download/downloads/'} # creating list of arguments\n\n\n\n\ndef download_images_date_range(search_keywords,start_date,end_date,download_limit,output_directory,split_by_date_flag):\n current_date = start_date\n delta = datetime.timedelta(days=1)\n while current_date <= end_date:\n print ('Before - starting the download thread ',current_date.strftime(\"%Y-%m-%d\"))\n args_tuple=(search_keywords,current_date,download_limit,output_directory,split_by_date_flag)\n download_thread = threading.Thread(target=download_images_per_date, args=args_tuple)\n download_thread.start()\n print('After - download thread started ',current_date.strftime(\"%Y-%m-%d\"))\n # download_images_per_date(search_keywords,current_date,download_limit,output_directory,split_by_date_flag)\n current_date+=delta\n\n\n\ndef main():\n\n # getting inputs in the command line\n # search_keywords, requested_date (mm/dd/yyyy), download_limit, output_directory, split_by_date_flag\n num_of_arguments=len(sys.argv)\n if(num_of_arguments==7):\n search_keywords=sys.argv[1]\n requested_start_date_string = sys.argv[2]\n num_of_days = int(sys.argv[3])\n download_limit = int(sys.argv[4])\n output_directory = sys.argv[5]\n split_by_date_flag = int(sys.argv[6])\n\n print('search_keywords [',search_keywords,']')\n print('requested_start_date_string ,mm/dd/yyyy [', requested_start_date_string, ']')\n print('num_of_days [', str(num_of_days), ']')\n print('download_limit [', download_limit, ']')\n print('search_keywords [', search_keywords, ']')\n print('output_directory [', output_directory, ']')\n print('split_by_date_flag [', split_by_date_flag, ']')\n else:\n print('Usage : python download_google_images_in_time_range_main.py search_keywords requested_start_date(mm/dd/yyyy) num_of_days download_limit_per_day(max 100) output_directory split_by_date_flag')\n print('Example: python download_google_images_in_time_range_main.py dog 01/25/2018 70 /home/dan/source/taboola/3rd_party/google-images-download/google_images_download/downloads/ 0')\n print(' This downloads dog images created 01/25/2018 and the next 70 days, 98 images per day, to the directory /home/dan/source/taboola/3rd_party/google-images-download/google_images_download/downloads/dog/ ')\n exit(-1)\n\n requested_start_date = datetime.datetime.strptime(requested_start_date_string, '%m/%d/%Y')\n requested_end_date = requested_start_date+ datetime.timedelta(days=num_of_days)\n\n download_images_date_range(search_keywords,\n requested_start_date,\n requested_end_date,\n download_limit,\n output_directory,\n split_by_date_flag)\n\n\nif __name__ == '__main__':\n main()\n\n","sub_path":"download_google_images_in_time_range/download_google_images_in_time_range.py","file_name":"download_google_images_in_time_range.py","file_ext":"py","file_size_in_byte":6633,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"260694341","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nSpyder Editor\r\n\r\nThis is a temporary script file.\r\n\"\"\"\r\n\r\ndef load_integers():\r\n ''' \r\n loads integers, stops when n=0\r\n '''\r\n lst = list()\r\n while True:\r\n try:\r\n n = int(input('integer: '))\r\n if n == 0:\r\n break\r\n lst.append(n)\r\n except ValueError:\r\n print('thats not an integer')\r\n \r\n return lst\r\n \r\ndef sum_from_right(L):\r\n counter = 1 \r\n while True:\r\n summ = 0\r\n done = True\r\n for i in range (0, len(L)):\r\n if L[i] > 0:\r\n done = False\r\n summ = summ + L[i] % 10\r\n L[i] = L[i] // 10 \r\n if done:\r\n break\r\n print ('the sum of the {}. digits from the right: {}'.format(counter,summ))\r\n counter += 1\r\n \r\ndef main():\r\n sum_from_right(load_integers())\r\n return\r\n \r\nmain()","sub_path":"week6/lab/qu1-add_different_digits.py","file_name":"qu1-add_different_digits.py","file_ext":"py","file_size_in_byte":929,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"36683718","text":"#!/usr/bin/python3\n\nimport random\nfrom sys import stderr\n\nrounds = 1000\nn = 3\n\nfor _ in range(rounds + 1):\n doors = set('ABC')\n first_choice = random.choice('ABC')\n doors.remove(first_choice)\n print (first_choice)\n stderr.write(str(first_choice) + '\\n')\n hint, bottle = input().split()\n if bottle == '0':\n if hint in doors:\n doors.remove(hint)\n second_choice = doors.pop()\n else:\n second_choice = hint\n print(second_choice)\n line = input().split()\n assert int(line[0]) == int(second_choice == line[1])\n\n\n\n\n","sub_path":"askmarilyn/submissions/wrong_answer/plays-1001-rounds.py","file_name":"plays-1001-rounds.py","file_ext":"py","file_size_in_byte":571,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"141879120","text":"from __future__ import print_function, absolute_import, unicode_literals\n\n__all__ = [\"TLSSMTPHandler\"]\n\nimport logging\nimport logging.handlers\n\nfrom .email_utils import send_msg\n\n\nclass TLSSMTPHandler(logging.handlers.SMTPHandler):\n def emit(self, record):\n try:\n msg = self.format(record)\n to = \", \".join(self.toaddrs)\n subj = self.getSubject(record)\n send_msg(to, msg, subj)\n except (KeyboardInterrupt, SystemExit):\n raise\n except:\n self.handleError(record)\n","sub_path":"wtf/error_handlers.py","file_name":"error_handlers.py","file_ext":"py","file_size_in_byte":550,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"402458205","text":"while True:\r\n try:\r\n r1,x1,y1,r2,x2,y2 = input().split(\" \")\r\n r1 = int(r1)\r\n x1 = int(x1)\r\n y1 = int(y1)\r\n r2 = int(r2)\r\n x2 = int(x2)\r\n y2 = int(y2)\r\n\r\n dist = ((x2-x1)**2 + (y2-y1)**2)**(1/2)\r\n\r\n if dist + r2 > r1:\r\n print(\"MORTO\")\r\n else:\r\n print(\"RICO\")\r\n except EOFError:\r\n break","sub_path":"uri1039.py","file_name":"uri1039.py","file_ext":"py","file_size_in_byte":389,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"33067438","text":"import tensorflow as tf\nimport numpy as np\n\n#tensore 1d con valori costanti\ntensor_1d = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])\ntensor_1d = tf.constant(tensor_1d)\nwith tf.Session() as sess:\n print(tensor_1d.get_shape())\n print(sess.run(tensor_1d))\n\n#tensore 2d con valori variabili\ntensor_2d = np.array([(1, 2, 3), (4, 5, 6), (7, 8, 9)])\ntensor_2d = tf.Variable(tensor_2d)\nwith tf.Session() as sess:\n sess.run(tf.global_variables_initializer())\n print(tensor_2d.get_shape())\n print(sess.run(tensor_2d))\n\n\ntensor_3d = np.array([[[ 0, 1, 2],[ 3, 4, 5],[ 6, 7, 8]],\n [[ 9, 10, 11],[12, 13, 14],[15, 16, 17]],\n [[18, 19, 20],[21, 22, 23],[24, 25, 26]]])\n\ntensor_3d = tf.convert_to_tensor(tensor_3d, dtype=tf.float64)\nwith tf.Session() as sess:\n print(tensor_3d.get_shape())\n print(sess.run(tensor_3d))\n\n\ninteractive_session = tf.InteractiveSession()\ntensor = np.array([1, 2, 3, 4, 5])\ntensor = tf.constant(tensor)\nprint(tensor.eval())\ninteractive_session.close()\n\n\"\"\"\nPython 2.7.10 (default, Oct 14 2015, 16:09:02) \n[GCC 5.2.1 20151010] on linux2\nType \"copyright\", \"credits\" or \"license()\" for more information.\n>>> ================================ RESTART ================================\n>>> \n(10,)\n[ 1 2 3 4 5 6 7 8 9 10]\n(3, 3)\n[[1 2 3]\n [4 5 6]\n [7 8 9]]\n(3, 3, 3)\n[[[ 0. 1. 2.]\n [ 3. 4. 5.]\n [ 6. 7. 8.]]\n\n [[ 9. 10. 11.]\n [ 12. 13. 14.]\n [ 15. 16. 17.]]\n\n [[ 18. 19. 20.]\n [ 21. 22. 23.]\n [ 24. 25. 26.]]]\n[1 2 3 4 5]\n>>> \n\"\"\"\n\n\n","sub_path":"Chapter02/Python 3.5/tensor_with_numpy_1.py","file_name":"tensor_with_numpy_1.py","file_ext":"py","file_size_in_byte":1545,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"115482073","text":"from pymongo import MongoClient\nimport spacy\nimport unidecode\nfrom decimal import Decimal\nfrom bson.decimal128 import Decimal128\n\nnlp = spacy.load('en')\n\nclient = MongoClient('localhost', 27017)\ndb = client['off']\n\n\ndef hasNumbers(inputString):\n return any(char.isdigit() for char in inputString)\n\n\ndef store_ingredients():\n tags = db.products.aggregate([{\"$group\": {\"_id\": \"$ingredients_tags\"}}], allowDiskUse=True, no_cursor_timeout=True)\n for d in tags:\n if d['_id']:\n for t in d['_id']:\n if ':' not in t:\n continue\n _, ing = t.split(':')\n if len(ing) < 3:\n continue\n if hasNumbers(ing):\n continue\n ing = ing.replace('-', ' ')\n res = db['ingredients'].find_one({'name': ing})\n if not res:\n db['ingredients'].insert_one({'name': ing, 'count': 1})\n else:\n db['ingredients'].update({'_id': res['_id']}, {'$inc': {'count': 1}})\n\ndef store_categories():\n tags = db.products.aggregate([{\"$group\": {\"_id\": \"$categories\"}}], allowDiskUse=True)\n for r in tags:\n if not r['_id']:\n continue\n for part in r['_id'].split(','):\n res = db['categories'].find_one({'name': part.strip()})\n if not res:\n db['categories'].insert_one({'name': part.strip(), 'count': 1})\n else:\n db['categories'].update({'_id': res['_id']}, {'$inc': {'count': 1}})\n\n\n\n#store_categories()\ndb.ingredients.delete_many({'count': {'$lt': 10}})","sub_path":"db_script.py","file_name":"db_script.py","file_ext":"py","file_size_in_byte":1638,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"510485578","text":"#\n# Copyright 2012 New Dream Network, LLC (DreamHost)\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\"\"\"Test ACL.\"\"\"\n\nimport datetime\nimport os\nimport uuid\n\nfrom keystonemiddleware import fixture as ksm_fixture\nfrom oslo_utils import fileutils\nimport six\nimport webtest\n\nfrom ceilometer.api import app\nfrom ceilometer.publisher import utils\nfrom ceilometer import sample\nfrom ceilometer.tests.functional import api as acl\nfrom ceilometer.tests.functional.api import v2\n\nVALID_TOKEN = uuid.uuid4().hex\nVALID_TOKEN2 = uuid.uuid4().hex\n\n\nclass TestAPIACL(v2.FunctionalTest):\n\n def setUp(self):\n super(TestAPIACL, self).setUp()\n self.auth_token_fixture = self.useFixture(\n ksm_fixture.AuthTokenFixture())\n self.auth_token_fixture.add_token_data(\n token_id=VALID_TOKEN,\n # FIXME(morganfainberg): The project-id should be a proper uuid\n project_id='123i2910',\n role_list=['admin'],\n user_name='user_id2',\n user_id='user_id2',\n is_v2=True\n )\n self.auth_token_fixture.add_token_data(\n token_id=VALID_TOKEN2,\n # FIXME(morganfainberg): The project-id should be a proper uuid\n project_id='project-good',\n role_list=['Member'],\n user_name='user_id1',\n user_id='user_id1',\n is_v2=True)\n\n for cnt in [\n sample.Sample(\n 'meter.test',\n 'cumulative',\n '',\n 1,\n 'user-good',\n 'project-good',\n 'resource-good',\n timestamp=datetime.datetime(2012, 7, 2, 10, 40),\n resource_metadata={'display_name': 'test-server',\n 'tag': 'self.sample'},\n source='test_source'),\n sample.Sample(\n 'meter.mine',\n 'gauge',\n '',\n 1,\n 'user-fred',\n 'project-good',\n 'resource-56',\n timestamp=datetime.datetime(2012, 7, 2, 10, 43),\n resource_metadata={'display_name': 'test-server',\n 'tag': 'self.sample4'},\n source='test_source')]:\n msg = utils.meter_message_from_counter(\n cnt, self.CONF.publisher.telemetry_secret)\n self.conn.record_metering_data(msg)\n\n def get_json(self, path, expect_errors=False, headers=None,\n q=None, **params):\n return super(TestAPIACL, self).get_json(path,\n expect_errors=expect_errors,\n headers=headers,\n q=q or [],\n **params)\n\n def _make_app(self):\n self.CONF.set_override(\"cache\", \"fake.cache\", group=acl.OPT_GROUP_NAME)\n file_name = self.path_get('etc/ceilometer/api_paste.ini')\n self.CONF.set_override(\"api_paste_config\", file_name)\n return webtest.TestApp(app.load_app())\n\n def test_non_authenticated(self):\n response = self.get_json('/meters', expect_errors=True)\n self.assertEqual(401, response.status_int)\n\n def test_authenticated_wrong_role(self):\n response = self.get_json('/meters',\n expect_errors=True,\n headers={\n \"X-Roles\": \"Member\",\n \"X-Tenant-Name\": \"admin\",\n \"X-Project-Id\":\n \"bc23a9d531064583ace8f67dad60f6bb\",\n })\n self.assertEqual(401, response.status_int)\n\n # FIXME(dhellmann): This test is not properly looking at the tenant\n # info. We do not correctly detect the improper tenant. That's\n # really something the keystone middleware would have to do using\n # the incoming token, which we aren't providing.\n #\n # def test_authenticated_wrong_tenant(self):\n # response = self.get_json('/meters',\n # expect_errors=True,\n # headers={\n # \"X-Roles\": \"admin\",\n # \"X-Tenant-Name\": \"achoo\",\n # \"X-Project-Id\": \"bc23a9d531064583ace8f67dad60f6bb\",\n # })\n # self.assertEqual(401, response.status_int)\n\n def test_authenticated(self):\n data = self.get_json('/meters',\n headers={\"X-Auth-Token\": VALID_TOKEN,\n \"X-Roles\": \"admin\",\n \"X-Project-Id\":\n \"bc23a9d531064583ace8f67dad60f6bb\",\n })\n ids = set(r['resource_id'] for r in data)\n self.assertEqual(set(['resource-good', 'resource-56']), ids)\n\n def test_with_non_admin_missing_project_query(self):\n data = self.get_json('/meters',\n headers={\"X-Roles\": \"Member\",\n \"X-Auth-Token\": VALID_TOKEN2,\n \"X-Project-Id\": \"project-good\"})\n ids = set(r['resource_id'] for r in data)\n self.assertEqual(set(['resource-good', 'resource-56']), ids)\n\n def test_with_non_admin(self):\n data = self.get_json('/meters',\n headers={\"X-Roles\": \"Member\",\n \"X-Auth-Token\": VALID_TOKEN2,\n \"X-Project-Id\": \"project-good\"},\n q=[{'field': 'project_id',\n 'value': 'project-good',\n }])\n ids = set(r['resource_id'] for r in data)\n self.assertEqual(set(['resource-good', 'resource-56']), ids)\n\n def test_non_admin_wrong_project(self):\n data = self.get_json('/meters',\n expect_errors=True,\n headers={\"X-Roles\": \"Member\",\n \"X-Auth-Token\": VALID_TOKEN2,\n \"X-Project-Id\": \"project-good\"},\n q=[{'field': 'project_id',\n 'value': 'project-wrong',\n }])\n self.assertEqual(401, data.status_int)\n\n def test_non_admin_two_projects(self):\n data = self.get_json('/meters',\n expect_errors=True,\n headers={\"X-Roles\": \"Member\",\n \"X-Auth-Token\": VALID_TOKEN2,\n \"X-Project-Id\": \"project-good\"},\n q=[{'field': 'project_id',\n 'value': 'project-good',\n },\n {'field': 'project_id',\n 'value': 'project-naughty',\n }])\n self.assertEqual(401, data.status_int)\n\n\nclass TestAPIEventACL(TestAPIACL):\n\n PATH = '/events'\n\n def test_non_admin_get_event_types(self):\n data = self.get_json('/event_types', expect_errors=True,\n headers={\"X-Roles\": \"Member\",\n \"X-Auth-Token\": VALID_TOKEN2,\n \"X-Project-Id\": \"project-good\"})\n self.assertEqual(401, data.status_int)\n\n\nclass TestApiEventRBAC(v2.FunctionalTest):\n\n PATH = '/events'\n\n def setUp(self):\n super(TestApiEventRBAC, self).setUp()\n content = ('{\"context_is_admin\": \"role:admin\",'\n '\"segregation\": \"rule:context_is_admin\",'\n '\"default\" : \"!\",'\n '\"telemetry:events:index\": \"rule:context_is_admin\",'\n '\"telemetry:events:show\": \"rule:context_is_admin\"}')\n if six.PY3:\n content = content.encode('utf-8')\n self.tempfile = fileutils.write_to_tempfile(content=content,\n prefix='policy',\n suffix='.json')\n\n self.CONF.set_override(\"policy_file\",\n self.path_get(self.tempfile),\n group='oslo_policy')\n self.app = self._make_app()\n\n def tearDown(self):\n os.remove(self.tempfile)\n super(TestApiEventRBAC, self).tearDown()\n\n def test_get_event_by_message_rbac(self):\n headers_rbac = {\"X-Roles\": \"non-admin\"}\n data = self.get_json(self.PATH + \"/100\",\n expect_errors=True,\n headers=headers_rbac,\n status=403)\n self.assertEqual(u'403 Forbidden\\n\\nAccess was denied to this '\n 'resource.\\n\\n RBAC Authorization Failed ',\n data.json['error_message'])\n\n def test_get_events_rbac(self):\n headers_rbac = {\"X-Roles\": \"non-admin\"}\n data = self.get_json(self.PATH,\n expect_errors=True,\n headers=headers_rbac,\n status=403)\n self.assertEqual(u'403 Forbidden\\n\\nAccess was denied to this '\n 'resource.\\n\\n RBAC Authorization Failed ',\n data.json['error_message'])\n\n def test_get_events_without_project(self):\n headers_no_proj = {\"X-Roles\": \"admin\", \"X-User-Id\": \"user-good\"}\n resp = self.get_json(self.PATH, expect_errors=True,\n headers=headers_no_proj, status=403)\n self.assertEqual(403, resp.status_int)\n\n def test_get_events_without_user(self):\n headers_no_user = {\"X-Roles\": \"admin\", \"X-Project-Id\": \"project-good\"}\n resp = self.get_json(self.PATH, expect_errors=True,\n headers=headers_no_user, status=403)\n self.assertEqual(403, resp.status_int)\n\n def test_get_events_without_scope(self):\n headers_no_user_proj = {\"X-Roles\": \"admin\"}\n resp = self.get_json(self.PATH,\n expect_errors=True,\n headers=headers_no_user_proj,\n status=403)\n self.assertEqual(403, resp.status_int)\n","sub_path":"ceilometer/tests/functional/api/v2/test_acl_scenarios.py","file_name":"test_acl_scenarios.py","file_ext":"py","file_size_in_byte":11054,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"161406091","text":"import json\nall_path = []\npdic = {}\nres = []\ndef explore(dic, parent,depth):\n if isinstance(dic,str):\n if dic in pdic:\n pdic[dic].append([depth+1,parent+'/'+dic])\n else:\n pdic[dic] = [[depth+1,parent+'/'+dic]]\n \"print(parent+'/'+dic)\"\n return\n for k,v in dic.items():\n if '{}/{}'.format(parent,k) not in all_path:\n all_path.append('{}/{}'.format(parent,k))\n if isinstance(v,dict):\n explore(v,parent+'/'+str(k),depth+1)\n if isinstance(v,list):\n for x in v:\n \"explore(x,parent+'/'+str(k))\"\n explore(x,parent,depth+1)\n else:\n pass\ndef fileSearch(fileToSearch,filesObj):\n with open(filesObj+'.json') as f:\n data = json.load(f)\n explore(data,'',-1)\n dop = pdic[fileToSearch]\n dop.sort()\n for depth,path in dop:\n res.append(path)\n print(res)\nfileToSearch,filesObj = input().split()\nfileSearch(fileToSearch,filesObj)\n'''\nfile1 test2\n'''","sub_path":"Prob#2 - File Search/File_Search.py","file_name":"File_Search.py","file_ext":"py","file_size_in_byte":1019,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"547530200","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.5 (3350)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: /Users/eetu/envs/cmsplugin-articles-ai/project/cmsplugin_articles_ai/migrations/0005_make_tag_slug_field_unique.py\n# Compiled at: 2017-07-21 05:10:28\n# Size of source mod 2**32: 457 bytes\nfrom __future__ import unicode_literals\nfrom django.db import migrations, models\n\nclass Migration(migrations.Migration):\n dependencies = [\n ('cmsplugin_articles_ai', '0004_data_migration_for_slug_field')]\n operations = [\n migrations.AlterField(model_name='tag', name='slug', field=models.SlugField(unique=True, verbose_name='slug', max_length=200))]","sub_path":"pycfiles/cmsplugin_articles_ai-0.2.4-py2.py3-none-any/0005_make_tag_slug_field_unique.cpython-35.py","file_name":"0005_make_tag_slug_field_unique.cpython-35.py","file_ext":"py","file_size_in_byte":709,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"229722814","text":"'''\nSudoku Module:\nRepresents the constraints\ninside a a 9x9 matrix\n'''\nimport numpy as np\n\n# Slicing object for 3x3 submatrix inside sudoku\nGRIDS = [slice(0,3), slice(3,6), slice(6,9)]\n\ndef is_valid(sudoku, row, col, cell):\n ''' Returns True if S[row, col] cell value is valid '''\n\n s_row = np.array(sudoku[row]).flatten() # Rows\n s_col = np.array(sudoku[:,col]).flatten() # Columns\n s_grid = get_grid(sudoku, row, col) # Grid (3x3)\n\n return (\n np.count_nonzero(s_row == cell) == 0 and\n np.count_nonzero(s_col == cell) == 0 and\n np.count_nonzero(s_grid == cell) == 0\n )\n\ndef get_grid(sudoku, row, col):\n ''' Returns the grid from a cells '''\n return np.array(sudoku[GRIDS[row//3], GRIDS[col//3]]).flatten()\n\ndef empty_cells(sudoku):\n ''' Returns the i,j value of the empty cells '''\n for i in range(9):\n row = list(np.array(sudoku[i]).flatten())\n if None in row:\n return i, row.index(None)\n\n # Empty cells not found\n return 9, 9 \n\ndef find_possible(sudoku, row, col):\n ''' Returns a set of posible answer to a cell '''\n pos = list(range(1,10))\n\n for i in range(9):\n if sudoku[row,i] is not None and sudoku[row, i] in pos:\n pos.remove(sudoku[row, i])\n if sudoku[i,col] is not None and sudoku[row, i] in pos:\n pos.remove(sudoku[i, col])\n \n for s in get_grid(sudoku, row, col):\n if s is not None and s in pos:\n pos.remove(s)\n\n return pos\n","sub_path":"src/sudoku.py","file_name":"sudoku.py","file_ext":"py","file_size_in_byte":1490,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"632966862","text":"# load modules needed \nimport DART as dart\nimport DART_state_space as DSS\nimport string\nimport experiment_settings as es\nimport TEM as tem\nimport TIL as til \nimport ERA as era\nimport plotting as pt \nimport datetime as datetime\nimport matplotlib.pyplot as plt\nimport imp as imp \nimport numpy as np\nimport matplotlib as mb\nimport WACCM as waccm\n\n# DART-WACCM with global DA\nGLOB = dart.basic_experiment_dict()\nGLOB['title'] = 'WACCM + DART'\nGLOB['exp_name'] = 'W0910_GLOBAL'\n\n# DART-WACCM with no DA\nNODA = dart.basic_experiment_dict()\nNODA['title'] = 'WACCM Free'\nNODA['exp_name'] = 'W0910_NODA'\n\n# ERA-Interim details\nERA = dart.basic_experiment_dict()\nERA['title'] = 'ERA-Interim'\nERA['exp_name'] = 'ERA0.75'\nERA['copystring'] = ''\nERA['diagnostic'] = ''\nERA['levtype']='pressure'\n\n# other stuff \nseconds_per_day = 60.0*60.0*24.0\nletters = list(string.ascii_lowercase)\n\n# list of latitude bands\ntropics = [-10,10]\nmidlats = [45,60]\npole = [70,85]\nlatrange_name_list = ['Tropics (10S-10N)','Midlatitudes (45N-60N)','North Pole (70N-85N)'] \nlatrange_list = ['tropics','midlats','pole']\nlatrange_dict = {'tropics':[-10,10],\n 'midlats':[45,60],\n 'pole':[70,85]}\nlatrange_name_dict = {'tropics':'Tropics (10S-10N)',\n 'midlats':'Midlatitudes (45N-60N)',\n 'pole':'North Pole (70N-85N)'}\n# define dateranages for individual months\nOCT = dart.daterange(date_start=datetime.datetime(2009,10,1,12,0,0), periods=31, DT='1D')\nNOV = dart.daterange(date_start=datetime.datetime(2009,11,1,12,0,0), periods=30, DT='1D')\nDEC = dart.daterange(date_start=datetime.datetime(2009,12,1,12,0,0), periods=31, DT='1D')\nJAN = dart.daterange(date_start=datetime.datetime(2010,1,1,12,0,0), periods=31, DT='1D')\nFEB = dart.daterange(date_start=datetime.datetime(2010,2,1,12,0,0), periods=28, DT='1D')\nMAR = dart.daterange(date_start=datetime.datetime(2010,3,1,12,0,0), periods=25, DT='1D')\n\n# variable full names for plotting\nvariable_names_dict={'WSTAR':'$w^{*}$',\n 'VSTAR':'$\\overline{v}^*$',\n 'WS':'$\\overline{w}^*S$',\n 'Nsq_wstar_forcing':'$-\\partial_z \\overline{w}^{*} N^2$',\n 'QRL_TOT':'Longwave Cooling',\n 'Nsq':'$N^2$',\n 'Q':'Water Vapor',\n 'O3':'Ozone',\n 'T':'Temp'\n\t\t\t\t\t}\n\n# strings that give the units for each variable \nvariable_units_dict={'WSTAR':'m/s',\n 'VSTAR':'m/s',\n 'WS':'K/day',\n 'Nsq_wstar_forcing':'$s^{-2}$/day',\n 'QRL_TOT':'K/day',\n 'Nsq':'s$^{-2}$',\n 'Q':'kg/kg',\n 'O3':'mol/mol',\n 'T':'K'\n\t\t\t\t\t}\n\n# import some colors \nfrom palettable.colorbrewer.qualitative import Set1_8 as bmap_variables\nfrom palettable.colorbrewer.qualitative import Dark2_8 as bmap_experiments\n\n\n# common plot settings \naa = 0.3 # the alpha assigned to individual ensemble members \n\n","sub_path":"Notebooks/TIL_project_settings.py","file_name":"TIL_project_settings.py","file_ext":"py","file_size_in_byte":3042,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"146101907","text":"#!/usr/bin/env python\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom cmath import * # complex number arithmetic\nimport random\nimport argparse # Useful for command line\n\n\ndef color():\n string = '#'\n for i in range(0, 6):\n string += str(random.randint(0, 9))\n return string\n\n\ndef line(x_start, y_start, x_end, y_end):\n # define iterations\n dt = .01 # timestep\n x, y = [], []\n if x_end == x_start:\n t = np.arange(y_start, y_end, dt)\n for i in t:\n x.append(x_start)\n y.append(i)\n elif x_end > x_start:\n m = (y_end - y_start) / (x_end - x_start)\n t = np.arange(x_start, x_end, dt)\n for i in t:\n x.append(i)\n y.append(m * (i - x_start) + y_start)\n elif x_end < x_start:\n # swap the values\n temp = x_end\n x_end = x_start\n x_start = temp\n temp = y_end\n y_end = y_start\n y_start = temp\n\n m = (y_end - y_start) / (x_end - x_start)\n t = np.arange(x_start, x_end, dt)\n for i in t:\n x.append(i)\n y.append(m * (i - x_start) + y_start)\n\n return x, y\n\n\ndef grid(bottom_l_x, bottom_l_y, top_r_x, top_r_y, res):\n total = []\n dt = abs(top_r_x - bottom_l_x) / res\n # vertical lines first\n t = np.arange(bottom_l_x, top_r_x + dt,\n dt) # has 1 extra line to make into box\n for i in t:\n total.append(line(i, bottom_l_y, i, top_r_y))\n\n # horizontal\n t = np.arange(bottom_l_y, top_r_y + dt,\n dt) # has one extra line to make it a box\n for i in t:\n total.append(line(bottom_l_y, i, top_r_y, i))\n\n return total\n\n\ndef cmap(w, d):\n # w = complex function\n # d = domain\n x, y = [], []\n # move [x vector, y vector] -> [(x_i,y_i),...]\n tup = []\n for i in range(len(d[0])):\n tup.append([d[0][i], d[1][i]])\n for i, j in tup:\n x.append(w(i, j).real)\n y.append(w(i, j).imag)\n\n return x, y\n\n\ndef cmap_m(w, D):\n \" assume this is a set of plots, instead of a single plot\"\n total = []\n for d in D:\n total.append(cmap(w, d))\n\n return total\n\n\ndef Plot(f):\n plt.plot(f[0], f[1], color()) # may collide but unlikely\n\n\ndef Plot_multiple(f):\n for i in f:\n plt.plot(i[0], i[1], color()) # may collide but unlikely\n\n\nif __name__ == '__main__':\n\n # make sense of user input from a terminal\n parser = argparse.ArgumentParser()\n parser.add_argument('--function',\n type=str,\n help='Enter complex number function',\n default=\"(x+1j*y)\")\n\n arg = parser.parse_args()\n\n header = str(arg.function) # \"exp(x+1j*y)\"\n w = lambda x, y: eval(header)\n\n Plot_multiple(cmap_m(w, grid(-pi, -pi, pi, pi, 20)))\n\n plt.title(header)\n plt.xlabel('Re')\n plt.ylabel('Im')\n plt.grid()\n plt.show()\n\n# Plot(line(-1, -1, 1, -1))\n# Plot(line(-1, 1, 1, 1))\n# Plot(line(-1, -1, -1, 1))\n# Plot(line(1, -1, 1, 1))\n\n# Plot(cmap(w, line(-5, e, 5, e)))\n# Plot(cmap(w, line(-1, 1, 1, 1)))\n# Plot(cmap(w, line(-1, -1, -1, 1)))\n# Plot(cmap(w, line(1, -1, 1, 1)))\n\n# Plot_multiple(grid(-1, -1, 1, 1, 3))\n","sub_path":"display_space.py","file_name":"display_space.py","file_ext":"py","file_size_in_byte":3197,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"175331513","text":"# -*- coding: utf-8 -*-\n\"\"\"\n努力不需要理由,如果需要,就是为了不需要的理由。\n\"\"\"\n\n__title__ = 'QGDT-cpu'\n__author__ = 'Ex_treme'\n__license__ = 'MIT'\n__copyright__ = 'Copyright 2018, Ex_treme'\n\nimport os\nimport sys\n\nsys.path.append(os.path.dirname(os.getcwd()))\n","sub_path":"QGDT/models/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":285,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"647641891","text":"#!/usr/bin/env python333\n\n# Author: Abdulraouf\n\n#!/usr/bin/env python33\nimport sys\nimport rospy\nimport moveit_commander\nimport collections\nimport geometry_msgs.msg\nimport numpy as np\nimport random\nfrom trajectory_msgs.msg import JointTrajectory\nfrom std_msgs.msg import Header\nfrom trajectory_msgs.msg import JointTrajectoryPoint\nimport rospy\nimport argparse\nimport actionlib\nimport control_msgs.msg\n\n\nimport rospy\n\nimport rospy\n\n\n#force_tourqesensors\nfrom geometry_msgs.msg._WrenchStamped import WrenchStamped\n#force_tourqesensors\n\nimport rospy\nfrom nav_msgs.msg import Odometry\nimport gym\nimport rospy\nimport roslaunch\nimport time\nimport numpy as np\nfrom gym import utils,spaces\nfrom geometry_msgs.msg import Twist\nfrom std_srvs.srv import Empty\nfrom sensor_msgs.msg import LaserScan\nfrom gym.utils import seeding\nimport gym\nimport rospy\nimport time\n\nimport tf\nimport time\nfrom gym import utils,spaces\nfrom sensor_msgs.msg import Imu\nfrom std_msgs.msg import Empty as EmptyTopicMsg\nfrom gym.utils import seeding\nfrom gym.envs.registration import register\nfrom gazebo_connection import GazeboConnection\nfrom gym.utils import seeding\nimport random\nfrom trajectory_msgs.msg import JointTrajectory\nfrom std_msgs.msg import Header\nfrom trajectory_msgs.msg import JointTrajectoryPoint\nimport rospy\nimport argparse\nimport actionlib\nimport control_msgs.msg\n\n\nimport random\nimport sys\nsys.path.insert(0, '..')\nimport os\nimport time\nimport math\nimport cv2 as cv\nimport numpy as np\n\nfrom gym import utils, spaces\n\nimport gym\nfrom gym import spaces\nreg=register(\nid='UR5env-v0',\nentry_point='UR5_env:UR5Env',)\n\n\nclass UR5Env(gym.Env):\n def __init__(self):\n super(UR5Env, self).__init__()\n moveit_commander.roscpp_initialize(sys.argv)\n rospy.init_node('moveit_group_python_interface',anonymous=True)\n self.unpause=rospy.ServiceProxy('/gazebo/unpause_physics',Empty)\n self.pause=rospy.ServiceProxy('/gazebo/pause_physics',Empty)\n self.reset_proxy=rospy.ServiceProxy('/gazebo/reset_simulation',Empty)\n self.robot=moveit_commander.RobotCommander()\n self.arm_group=moveit_commander.MoveGroupCommander(\"arm\")\n\n self.depth_axis,self.elvation_dis,self.lateral_dist= 0,0,0\n self.f_t =[0,0,0,0,0,0]\n self.privous_coord = [0, 0, 0]\n self.init = [0.43, 0.04, 0.5]\n self.coord = [0.43, 0.4, 0.5]\n self.target = [0.47, 0.0, 0.522]\n\n self.done = False\n self.target_reached = 3\n self.reward = 0\n self.epoch = 0\n self.wait = 20\n self.step_size = 0.001\n self.action_space = spaces.Discrete(17)\n self.observation_space = spaces.Box(low=-100, high=100, shape=(6,), dtype=np.float32)\n\ndef ft_sensors_listener_filter(self):\n # print(\"ft_sensors_listener_filter\")\n msg = rospy.wait_for_message(\"/ft_sensor/raw\",WrenchStamped)\n ft_data=[0,0,0,0,0,0]\n for i in range(50):\n print(\"force_torque:\",msg.wrench.force , msg.wrench.torque)\n ft_data += [msg.wrench.force , msg.wrench.torque]\n force_torque = [i / 50 for i in ft_data]\n ft = [round(i, 4) for i in force_torque]\n ft[1]=ft[1]-15\n if(np.isnan(f_t[0])):\n rospy.wait_for_service('/gazebo/pause_physics')\n try:\n self.pause()\n except (rospy.ServiceException) as e:\n print (\"/gazebo/pause_physics service call failed\")\n print(\"force_torque:\",ft)\n return ft\n\n\n def calculate_euclidean_distances(self):\n\n #distance between new self.coordinate and last coordinate\n\n self.dist_T_O = [np.linalg.norm(self.target[i]-self.privous_coord[i]) for i in range(3)]\n\n #distance between new coordinate and target\n self.dist_T_N = [np.linalg.norm(self.target[i]-self.coord[i]) for i in range(3)]\n print(\"dist_T_N\",self.dist_T_N)\n\n #define depth axis, elvation_dis, lateral_dist\n self.lateral_dist = np.linalg.norm(self.target[self.geoAxes[0]]-self.coord[self.geoAxes[0]])\n self.depth_axis = self.coord[self.geoAxes[1]]\n self.elvation_dis = np.linalg.norm(self.target[self.geoAxes[2]]-self.coord[self.geoAxes[2]])\n\n def step(self, action):\n\n self.reward = 0\n self.privous_coord = self.coord.copy()\n self.move(action)\n self.calculate_euclidean_distances()\n self.controller.stay(self.wait)\n #self.f_t = x.append(i) for i in self.ft_sensors_listener_filter()\n #self.f_t = [number / 10 for number in self.controller.get_ft()]\n self.check_collision()\n self.check_approching_target()\n self.check_target()\n\n\n state = [0,0,0,0,0,0]\n state = self.f_t\n\n print(\"state\",state )\n self.reward = round(self.reward, 2)\n print(\"REWARD = \",self.reward)\n print(\"=\"*30)\n self.epoch += 1\n print(\"EPOCH=\",self.epoch)\n if(self.epoch > 350):\n self.epoch = 0\n #self.reward -= 20\n self.done = True\n\n\n return np.array(state, dtype=np.float32), self.reward, self.done, {}\n\n def reset(self):\n\n print(\"*\"*30)\n self.done = False\n self.reward = 0\n self.epoch = 0\n #self.coord = self.init\n print(\"*** x, y, z =\",self.coord[0], self.coord[1], self.coord[2], \"***\")\n self.geoAxes=[1,0,2]\n self.depth_target= 0.46\n pose_targe.orientation.w = -0.5\n pose_targe.orientation.x = 0.5\n pose_targe.orientation.y = -0.5\n pose_targe.orientation.z = 0.5\n\n pose_targe.position.x = 0.55\n pose_targe.position.y = 0.0\n pose_targe.position.z = 0.52\n self.arm_group.set_max_velocity_scaling_factor(1)\n self.arm_group.set_max_acceleration_scaling_factor(1)\n self.arm_group.set_pose_target(pose_targe)\n plan1 = self.arm_group.go()\n\n\n if self.target_reached == 3:\n self.target_reached = 0\n self.target[0]=random.uniform(-0.1,0.1)\n self.init[0] = random.uniform(self.target[0] - 0.006, self.target[0] + 0.006)\n self.init[1] = random.uniform(-0.436, -0.433)\n self.init[2] = random.uniform(1.11, 1.117)\n self.controller.change_object_palace(self.target[0], -.75, 0.95,\"platt\")\n self.coord = self.init.copy()\n\n self.degree = ((self.coord[0]+0.0001)/0.0001) * 0.0135\n print(\"correction_value=\",self.degree)\n #self.target_reached = False\n\n self.arm_group.set_pose_target(pose_targe)\n plan1 = self.arm_group.go()\n self.f_t = self.ft_sensors_listener_filter()\n\n #Unpausesimulationtomakeobservation\n rospy.wait_for_service('/gazebo/unpause_physics')\n try:\n #resp_pause=pause.call()\n self.unpause()\n except(rospy.ServiceException) as e:\n print(\"/gazebo/unpause_physicsservicecallfailed\")\n\n return np.array( self.f_t, dtype=np.float32)\n\n def check_collision(self):\n collision = sum([True if self.f_t[i] > 40 \\\n else True if self.f_t[i] < -40 \\\n else False for i in range(6)])\n if collision > 0 :\n self.done= True\n self.reward -= 20\n print(\"*\"*10, \"COLLISION\", \"*\"*10)\n\n self.reward += sum([-1 if self.f_t[i] > 30 \\\n else -1 if self.f_t[i] < -30 \\\n else 1 for i in range(3)])\n print(\"force REWARD: = \", self.reward)\n #self.reward +=sum ([np.abs(self.f_t[i]) /r1 if self.f_t[i] < 20 and self.f_t[i] > -20 \\\n # and sum(self.dist_T_N) < 0.005 and sum(self.dist_T_N) < sum(self.dist_T_O) \\\n # else 0 for i in range(3)])\n self.reward += sum ([1 if self.f_t[i] < 30 and self.f_t[i] > -30 \\\n and sum(self.dist_T_N) < 0.01 and sum(self.dist_T_N) < sum(self.dist_T_O) \\\n else -1 for i in range(3)])\n print(\"force REWARD: = \", self.reward)\n\n def check_target(self):\n if self.elvation_dis > 0.02 or self.lateral_dist > 0.02:\n self.done = True\n self.reward -= 100\n print(10*\"*\",\"WENT OUT OF BORDERS\",10*\"*\")\n print(\"self.elvation_dis > 0.015 or self.late\",self.elvation_dis, self.lateral_dist)\n\n if np.abs(self.depth_axis) >= np.abs(self.depth_target) and self.elvation_dis < 0.002 and self.lateral_dist < 0.002 :\n self.done = True\n self.reward += 100\n self.target_reached += 1\n print(10*\"*\",\"TASK ACCOMPLISHED\",10*\"*\")\n\n def check_approching_target(self):\n print(\"REWARD: = \", self.reward)\n\n d_p = 0.0001\n r1 = 0.002\n r2 = 0.002\n print(\"approaching REWARD: = \", self.reward)\n\n print(\"sum(self.dist_T_N) < sum(self.dist_T_O)\",sum(self.dist_T_N), sum(self.dist_T_O))\n print(\"#\"*30)\n\n #self.reward +=sum ([(r1 / (self.dist_T_N [i]+d_p)) if self.dist_T_N [i] < self.dist_T_O[i] \\\n # else (r2 / (self.dist_T_N [i]+d_p)) if sum(self.dist_T_N) < sum(self.dist_T_O) \\\n # else -(r1 / (self.dist_T_N [i]+d_p)) for i in range(3)])\n self.reward += sum([ 2 if self.dist_T_N[i] < self.dist_T_O[i] \\\n else 0 if self.dist_T_N[i] == self.dist_T_O[i] else -2 for i in range(3)])\n print(\"approaching REWARD: = \", self.reward)\n self.reward += (-2 if np.abs(self.coord[self.geoAxes[1]]) < np.abs(self.privous_coord[self.geoAxes[1]]) and sum(self.dist_T_N) <= 0.01 \\\n else 4 if sum(self.dist_T_N) <= 0.01 else 0 )\n print(\"approaching REWARD: = \", self.reward)\n print(\"#\"*30)\n print(\"#\"*30)\n for i in range(3):\n print(r1 / (self.dist_T_N [i]+d_p))\n print(r2 / (self.dist_T_N [i]+d_p))\n print(\"#\"*30)\n\n def move(self, action):\n\n\n self.movment = [0,0,0]\n if (action == 0):#Movingonxaxis X\n self.coord[0] += self.step_size\n self.movment[0] = 1\n\n elif (action == 1):#Movingonx axis X\n self.coord[0] -= self.step_size\n self.movment[0] = 0.5\n\n elif (action == 2):##Movingony axis Y\n self.coord[1] -= self.step_size\n self.movment[0] = 0.5\n\n elif (action == 3):##Movingonz axis Z\n self.coord[2] += self.step_size\n self.movment[2] = 1\n\n elif (action == 4):##Movingonz axis Z\n self.coord[2] -= self.step_size\n\n elif (action == 5):##Movingonz axis XY\n self.coord[0] -= self.step_size\n self.coord[1] -= self.step_size\n\n elif (action == 6):##Movingonz axis XY\n self.coord[0] += self.step_size\n self.coord[1] -= self.step_size\n\n elif (action == 7):##Movingonz axis XZ\n self.coord[0] += self.step_size\n self.coord[2] += self.step_size\n\n elif (action == 8):##Movingonz axis XZ\n self.coord[0] -= self.step_size\n self.coord[2] -= self.step_size\n\n elif (action == 9):##Movingonz axis XZ\n self.coord[0] += self.step_size\n self.coord[2] -= self.step_size\n self.movment = [1,0,0.5]\n self.degree += self.correction_value\n\n elif (action == 10):##Movingonz axis XZ\n self.coord[0] -= self.step_size\n self.coord[2] += self.step_size\n\n elif (action == 11):##Movingonz axis YZ\n self.coord[1] -= self.step_size\n self.coord[2] -= self.step_size\n\n elif action == 12 :##Movingonz axis YZ\n self.coord[1] -= self.step_size\n self.coord[2] += self.step_size\n\n elif action == 13 :##Movingonz axis XYZ\n self.coord[0] += self.step_size\n self.coord[1] -= self.step_size\n self.coord[2] -= self.step_size\n\n elif action == 14 :##Movingonz axis XYZ\n self.coord[0] -= self.step_size\n self.coord[1] -= self.step_size\n self.coord[2] += self.step_size\n self.movment = [0.5,0.5,1]\n self.degree -= self.correction_value\n\n elif action == 15 :##Movingonz axis XYZ\n self.coord[0] -= self.step_size\n self.coord[1] -= self.step_size\n self.coord[2] -= self.step_size\n\n elif action >= 16 :##Movingonz axis XYZ\n self.coord[0] += self.step_size\n self.coord[1] -= self.step_size\n self.coord[2] += self.step_size\n\n print(\"SELECTED ACTION = \",action)\n print(\"cor:\", self.coord)\n pose_targe = geometry_msgs.msg.Pose()\n pose_targe.orientation.w = -0.5\n pose_targe.orientation.x = 0.5\n pose_targe.orientation.y = -0.5\n pose_targe.orientation.z = 0.5\n pose_targe.position.x = self.coord[0]\n pose_targe.position.y = self.coord[1]\n pose_targe.position.z = self.coord[2]\n\n self.arm_group.set_max_velocity_scaling_factor(0.5)\n self.arm_group.set_max_acceleration_scaling_factor(0.1)\n self.arm_group.set_pose_target(pose_targe)\n plan1 = self.arm_group.go()\n","sub_path":"ur5_ws/src/ur5_training/gym_ur5/envs/Ur5Env.py","file_name":"Ur5Env.py","file_ext":"py","file_size_in_byte":12991,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"430674456","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Jul 8 09:44:58 2018\n\n@author: Maximus\n\"\"\"\n\nimport os,fnmatch\n#import shutil\ntrain_folder = r'C:\\Maxim\\keras-facenet\\data\\faces+ids_2' \nfolders = os.listdir(train_folder)\n# Get path to folders for train\ncount = 0\ncnt =0\nnum_of_npy = 0\nfor fld in folders:\n im_folder = os.listdir(train_folder + '\\\\' + fld)\n if 'images' in im_folder:\n for f1 in os.listdir(train_folder + '\\\\' + fld + '\\\\images'):\n if fnmatch.fnmatch(f1,'*.npy'):\n os.remove(train_folder + '\\\\' + fld + '\\\\images' + '\\\\' +f1)\n num_of_npy += 1\n print('Remove all npy file in folder ' + fld)\n count += 1\n else:\n for f1 in os.listdir(train_folder + '\\\\' + fld):\n if fnmatch.fnmatch(f1,'*.npy'):\n os.remove(train_folder + '\\\\' + fld + '\\\\' +f1)\n num_of_npy += 1\n print('Remove all npy file in folder ' + fld)\n count += 1\n #continue\nprint('Done, delete npy files from ' + str(count) + ' folders')\nprint('Total number of deleted npy files is: ' + str(num_of_npy))\n\n\n\n# =============================================================================\n# import os,fnmatch\n# import shutil\n# #import shutil\n# train_folder = r'C:\\Maxim\\keras-facenet\\data\\vox2_data_processed_old' \n# folders = os.listdir(train_folder)\n# # Get path to folders for train\n# count = 0\n# cnt =0\n# num_of_npy = 0\n# for idx, fld in enumerate(folders):\n# shutil.rmtree(train_folder + '\\\\' + fld)\n# print('delete: ' + str(idx) + '/' +str(len(folders)-1) + ' Folder: ' + fld)\n# =============================================================================\n","sub_path":"Delete_npy_files.py","file_name":"Delete_npy_files.py","file_ext":"py","file_size_in_byte":1673,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"571140457","text":"from testInput import input\nfrom math import log\ndef find(arr, n):\n max_element = max(arr)\n max_bit = int(log(max_element, 2)) + 1\n ans = 0\n total_subarray = (n * (n + 1)) // 2\n print(arr,total_subarray)\n for i in range(max_bit):\n vector = []\n # find index of those element whose ith bit is not set\n for j in range(n):\n if (arr[j] & (1 << i)==0):\n vector.append(j)\n\n if len(vector) == 0:\n ans += total_subarray * (2 ** i)\n else:\n not_set_subarray = 0 # number of subarrays in which ith bit is not set\n c = 1\n for k in range(1, len(vector)):\n if vector[k] - vector[k - 1] == 1:\n c += 1\n else:\n not_set_subarray += (c * (c + 1)) // 2\n c = 1\n not_set_subarray += (c * (c + 1)) // 2\n if len(vector) == 1:\n not_set_subarray = 1\n value= (total_subarray - not_set_subarray) * (2 ** i)\n ans+=value\n print(i,vector,value)\n return ans\n\n\n# Driver Code\nn = int(input())\narr = list(map(int, input().split()))\nif n == 0:\n print(0)\nelif n == 1:\n print(arr[0])\nelse:\n print(find(arr, n))","sub_path":"Codenation/SumofAllSubarrayOR.py","file_name":"SumofAllSubarrayOR.py","file_ext":"py","file_size_in_byte":1264,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"565152356","text":"#def ordinal(n):\n #if n==1:\n #return \"1st\"\n #elif n==2:\n #return \"2nd\"\n #else:\n # return \"3rd\"\n \n ## refactoring \ndef ordinal(n):\n# if (type(n) == int) & (type(n) == float):\n # pass\n #else: \n #return \"Improper Input\"\n try: # try this, and\n n = int(n)\n except: # if an error occurred, return this (more efficient than just checking the type, since handles all kinds of errors)\n return \"Improper Input\"\n# n = str(n)\n last_digit = n % 10\n second_to_last_digit = (n %100) / 10\n endings = {1: \"st\", 2: \"nd\", 3: \"rd\"}\n ending = \"th\"\n if second_to_last_digit !=1 and last_digit in endings.keys() :\n ending = endings[last_digit]\n elif last_digit == 1:\n ending = \"st\"\n elif last_digit ==2:\n ending = \"nd\"\n elif last_digit ==3:\n ending = \"rd\"\n \n return str(n) + ending\n \n ","sub_path":"day3_testing/ordinal.py","file_name":"ordinal.py","file_ext":"py","file_size_in_byte":775,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"162004596","text":"import json\n\nmijson = {}\nmijson.setdefault(\"participantes\", [])\nnombre = \"\"\nprint(\"INTRODUCCIÓN DE PARTICIPANTES:\\n\")\nwhile nombre != \"salir\":\n nombre = input(\"Indica el nombre ('salir' para finalizar): \")\n if nombre != \"salir\":\n ciudad = input(\"indica la ciudad: \")\n edad = input(\"indica la edad: \")\n aficiones = []\n aficion = \"\"\n while aficion != \"fin\":\n aficion = input(\"Escribe una afición ('fin' para finalizar): \")\n if aficion != \"fin\":\n aficiones.append(aficion)\n mijson[\"participantes\"].append({\n \"nombre\": nombre,\n \"ciudad\": ciudad,\n \"edad\": int(edad),\n \"aficiones\": aficiones})\n print(\"-\" * 30)\nprint(\"DICCIONARIO FORMADO:\", mijson)\narchivo = open(\"participantes.json\", \"w\")\njson.dump(mijson, archivo, ensure_ascii=False, indent=3)\narchivo.close()","sub_path":"Bases de datos/JSON/guardarjson.py","file_name":"guardarjson.py","file_ext":"py","file_size_in_byte":919,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"611643356","text":"import torch\r\nimport torch.nn as nn\r\nimport torch.nn.functional as F\r\nimport torch.optim as optim\r\n\r\nimport numpy as np\r\nfrom data_management import Attribute_Representation\r\n\r\n\r\nclass Net(nn.Module):\r\n \r\n def __init__(self, imusizes, segmentsize, numberOfAttributes, gpudevice, uncertaintyForwardPasses=1,kernelsize=5 ):\r\n super(Net, self).__init__()\r\n #torch.nn.Conv1d(in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, groups=1, bias=True)\r\n #torch.nn.MaxPool1d(kernel_size, stride=None, padding=0, dilation=1, return_indices=False, ceil_mode=False)\r\n #torch.nn.Sigmoid\r\n #torch.nn.Linear(in_features, out_features, bias=True)\r\n #torch.nn.ReLU(inplace=False)\r\n self.gpudevice = gpudevice\r\n self.cuda(device=self.gpudevice)\r\n self.uncertaintyForwardPasses = uncertaintyForwardPasses\r\n self.imusizes = imusizes\r\n self.numberOfIMUs = len(imusizes)\r\n self.numberOfAttributes = numberOfAttributes\r\n\r\n self.imunets = []\r\n for sensorcount in imusizes:\r\n self.imunets.append(IMUnet(sensorcount, segmentsize,kernelsize, self.gpudevice))\r\n self.dropout1 = nn.Dropout(0,5)\r\n self.fc1 = nn.Linear(512*self.numberOfIMUs, 512, bias=True)\r\n self.dropout2 = nn.Dropout(0,5)\r\n self.fc2 = nn.Linear(512, self.numberOfAttributes, bias=True)\r\n \r\n def train(self,mode=True):\r\n super(Net, self).train(mode)\r\n for imu in self.imunets:\r\n imu.train()\r\n \r\n def eval(self):\r\n super(Net, self).eval() \r\n for imu in self.imunets:\r\n imu.eval()\r\n \r\n def forward(self,input):\r\n #input ist ein tensor mit shape[n,C_in,t,d] \r\n # n ist batch size\r\n # C_in = 1\r\n # t = sensor inputs\r\n # d = sensoren anzahl\r\n \r\n y = []\r\n firstsensor = 0\r\n for i in range(self.numberOfIMUs):\r\n lastsensor = firstsensor + self.imusizes[i]\r\n x = input[:,:,:,firstsensor:lastsensor]\r\n y.append(self.imunets[i](x))\r\n \r\n extractedFeatures = y[0]\r\n for tensor in range(1,len(y)):\r\n extractedFeatures = torch.cat((extractedFeatures,y[tensor]),dim=1)\r\n \r\n \r\n extractedFeatures = torch.reshape(extractedFeatures, (extractedFeatures.shape[0],-1) )\r\n\r\n #Compute single forwardpass without dropout\r\n z = torch.tensor(extractedFeatures)\r\n z = F.relu( self.fc1(self.dropout1(z)))\r\n z = torch.sigmoid( self.fc2(self.dropout2(z)))\r\n result = z\r\n \r\n if(self.training is True):\r\n return result\r\n else:\r\n ##TODO: do this...\r\n #results = torch.zeros((self.uncertaintyForwardPasses,self.numberOfAttributes))\r\n\r\n #for i in range(self.uncertaintyForwardPasses):\r\n # z = torch.tensor(extractedFeatures)\r\n # z = F.dropout(F.relu( self.fc1(z)),0.5,training=True)\r\n # z = torch.sigmoid( self.fc2(z))\r\n # results[i, :] = z\r\n\r\n ##torch.var(input, dim, keepdim=False, unbiased=True, out=None)\r\n ##torch.mean(input, dim, keepdim=False, out=None)\r\n #attribute_mean = torch.mean(results,0)\r\n #attribute_st_deviation = torch.sqrt( torch.var(results,0))\r\n\r\n #optimistic_prediction = attribute_mean.add(1,attribute_st_deviation)\r\n #pessimistic_prediction = attribute_mean.sub(1,attribute_st_deviation)\r\n\r\n #return [result,pessimistic_prediction,attribute_mean,optimistic_prediction]\r\n return result\r\n\r\nclass IMUnet(nn.Module): #defines a parrallel convolutional block\r\n def __init__(self,numberOfSensors, segmentsize,kernelsize, gpudevice):\r\n super(IMUnet, self).__init__()\r\n self.gpudevice = gpudevice\r\n self.cuda(device=self.gpudevice)\r\n\r\n padding = 0\r\n self.numberOfSensors = numberOfSensors\r\n self.measurementLength = segmentsize\r\n \r\n self.dropout1 = nn.Dropout(0,5)\r\n self.conv1 = nn.Conv2d( in_channels=1 , out_channels=64, kernel_size=(kernelsize,1), stride=1, padding=padding, bias=True)\r\n self.dropout2 = nn.Dropout(0,5)\r\n self.conv2 = nn.Conv2d(in_channels=64, out_channels=64, kernel_size=(kernelsize,1), stride=1, padding=padding, bias=True)\r\n self.pool1 = nn.MaxPool2d(kernel_size=(2,1), stride=1, padding=0, return_indices=False, ceil_mode=False)\r\n self.dropout3 = nn.Dropout(0,5)\r\n self.conv3 = nn.Conv2d(in_channels=64, out_channels=64, kernel_size=(kernelsize,1), stride=1, padding=padding, bias=True)\r\n self.dropout4 = nn.Dropout(0,5)\r\n self.conv4 = nn.Conv2d(in_channels=64, out_channels=64, kernel_size=(kernelsize,1), stride=1, padding=padding, bias=True)\r\n self.pool2 = nn.MaxPool2d(kernel_size=(2,1), stride=1, padding=0, return_indices=False, ceil_mode=False) \r\n self.dropout5 = nn.Dropout(0,5)\r\n \r\n #This is supposed to find out the inputsize of the final fullyconnected layer\r\n #segmentsize = segmentsize-4 #conv\r\n #segmentsize = segmentsize-4 #conv\r\n #segmentsize = segmentsize-1 #maxpool\r\n #segmentsize = segmentsize-4 #conv\r\n #segmentsize = segmentsize-4 #conv\r\n #segmentsize = segmentsize-1 #maxpool\r\n #number of sensors is constant\r\n #and C_out is 64 while C_in was 1\r\n neurons = (segmentsize-18)*numberOfSensors*64 \r\n self.fc1 = nn.Linear(int(neurons), 512, bias=True)\r\n \r\n \r\n \r\n \r\n \r\n def forward(self, input):\r\n input = F.relu( self.conv1( self.dropout1(input)))\r\n input = F.relu( self.conv2( self.dropout2(input)))\r\n input = self.pool1(input)\r\n input = F.relu( self.conv3( self.dropout3(input)))\r\n input = F.relu( self.conv4( self.dropout4(input)))\r\n input = self.pool2(input)\r\n batchsize = input.shape[0]\r\n input = torch.reshape(input,(batchsize,-1))\r\n input = F.relu( self.fc1( self.dropout5(input)))\r\n return input\r\n\r\n\r\ndef train(network, training_loader, validation_loader, attr_representation, distance_metric=\"cosine\", criterion=None, optimizer=None, epochs=2): \r\n \r\n network.train(True)\r\n\r\n if criterion is None:\r\n criterion = nn.BCELoss(weight=None, size_average=None, reduce=None, reduction='elementwise_mean')\r\n #criterion = nn.CrossEntropyLoss()\r\n if optimizer is None:\r\n optimizer = optim.SGD(network.parameters(), lr=0.001, momentum=0.9) #TODO: adapt lr and momentum \r\n\r\n for epoch in range(epochs): # loop over the dataset multiple times\r\n\r\n running_loss = 0.0\r\n for i, data in enumerate(training_loader, 0):\r\n # get the inputs\r\n inputs, labels = data\r\n # zero the parameter gradients\r\n optimizer.zero_grad()\r\n # forward + backward + optimize\r\n outputs = network(inputs)\r\n loss = criterion(outputs, attr_representation.attributevector_of_class(labels))\r\n loss.backward()\r\n optimizer.step()\r\n #print(\"progress {}\".format(i))\r\n # print statistics\r\n #running_loss += loss.item()\r\n if i % 1000 == 999: # print every 1000 mini-batches\r\n #print('[{}, {}] loss: {}'.format(epoch + 1, i + 1, running_loss / 100))\r\n #running_loss = 0.0\r\n test(network,training_loader, \"training\" , attr_representation,distance_metric,)\r\n test(network,validation_loader, \"validation\" , attr_representation,distance_metric)\r\n network.train(True)\r\n\r\n print('Finished Training')\r\n\r\n\r\ndef test(network,data_loader, data_name, attr_representation,distance_metric=\"cosine\"): #TODO: adapt this tutorial method for my purpose\r\n network.eval()\r\n\r\n correct = 0\r\n total = 0\r\n with torch.no_grad():\r\n for data in data_loader:\r\n inputs, labels = data\r\n #print(inputs.shape)\r\n outputs = network(inputs)\r\n #_, predicted = torch.max(outputs.data, 1)\r\n predicted = attr_representation.closest_class(outputs, distance_metric)\r\n total += labels.size(0)\r\n correct += (predicted.float() == labels.float()).sum().item()\r\n\r\n print('Accuracy of the network on the {}_set: {} %'.format( data_name,100 * correct / total ))\r\n \r\n #class_correct = list(0. for i in range(10))\r\n #class_total = list(0. for i in range(10))\r\n #with torch.no_grad():\r\n # for data in testloader:\r\n # inputs, labels = data\r\n # outputs = network(inputs)\r\n # #_, predicted = torch.max(outputs, 1)\r\n # predicted = attr_representation.closest_class(outputs, distance_metric)\r\n # c = (predicted == labels).squeeze()\r\n # for i in range(4):\r\n # label = labels[i]\r\n # class_correct[label] += c[i].item()\r\n # class_total[label] += 1\r\n\r\n\r\n #for i in range(10):\r\n # print('Accuracy of %5s : %2d %%' % (\r\n # classes[i], 100 * class_correct[i] / class_total[i]))\r\n \r\n\r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n ","sub_path":"src/neuralnetwork.py","file_name":"neuralnetwork.py","file_ext":"py","file_size_in_byte":9285,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"271930244","text":"import streamlit as st\nimport pandas as pd\n\nst.title('My first app')\n\ndf = pd.DataFrame({\n 'first column': [1, 2, 3, 4],\n })\n\noption = st.selectbox(\n 'Which number do you like best?',\n df['first column']\n)\nst.write('You selected: ', option)\n","sub_path":"sample.py","file_name":"sample.py","file_ext":"py","file_size_in_byte":255,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"638539537","text":"\"\"\"\nThe gray code is a binary numeral system where two successive values differ in only one bit.\n\nGiven a non-negative integer n representing the total number of bits in the code, print the sequence of gray code. A gray code sequence must begin with 0.\n\nExample 1:\n\nInput: 2\nOutput: [0,1,3,2]\nExplanation:\n00 - 0\n01 - 1\n11 - 3\n10 - 2\n\n\"\"\"\nclass Solution:\n def grayCode(self, n):\n \"\"\"\n :type n: int\n :rtype: List[int]\n \"\"\"\n sequence = [False for i in range(n)]\n self.res = [0]\n self.getAllcode(0,n,sequence)\n return self.res\n \n \n def getAllcode(self,cur,n,sequence):\n if len(self.res) == 2**n:\n return \n for i in range(n):\n if not sequence[i] and cur+2**i not in self.res and (cur+2**i)<2**n:\n sequence[i] = True\n self.res.append(cur+2**i)\n self.getAllcode(cur+2**i,n,sequence)\n \n elif sequence[i] and cur-2**i not in self.res and cur-2**i>0:\n sequence[i] = False\n self.res.append(cur-2**i)\n self.getAllcode(cur-2**i,n,sequence)\n sequence[i] = True\n \n \n ","sub_path":"August_18/89. Gray Code.py","file_name":"89. Gray Code.py","file_ext":"py","file_size_in_byte":1225,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"201501953","text":"# coding: utf-8\nfrom unittest.mock import MagicMock\n\nimport aioresponses as aioresponses\nimport pytest\n\nfrom rolling.client.http.client import HttpClient\nfrom rolling.client.lib.zone import ZoneLib as ClientZoneLib\nfrom rolling.gui.controller import Controller\nfrom rolling.gui.map.object import CurrentPlayer\nfrom rolling.gui.map.object import DisplayObjectManager\nfrom rolling.gui.map.render import TileMapRenderEngine\nfrom rolling.gui.map.widget import TileMapWidget\nfrom rolling.kernel import Kernel\nfrom rolling.map.source import ZoneMapSource\nfrom rolling.model.character import CharacterModel\nfrom rolling.server.lib.zone import ZoneLib as ServerZoneLib\n\n\n@pytest.fixture\ndef tilemapa_source(tilemapsourcea_txt: str, worldmapb_kernel: Kernel) -> ZoneMapSource:\n return ZoneMapSource(worldmapb_kernel, tilemapsourcea_txt)\n\n\n@pytest.fixture\ndef zone_map_widget(\n tilemapa_render_engine: TileMapRenderEngine,\n controller: Controller,\n tilemapa_source: ZoneMapSource,\n) -> TileMapWidget:\n return TileMapWidget(\n controller=controller, render_engine=tilemapa_render_engine, zone_map_source=tilemapa_source\n )\n\n\n@pytest.fixture\ndef aioresponses_mock() -> aioresponses:\n with aioresponses.aioresponses() as aiohttp_mock:\n yield aiohttp_mock\n\n\n@pytest.fixture\ndef worldmapb_server_zone_lib(worldmapb_kernel: Kernel) -> ServerZoneLib:\n return ServerZoneLib(worldmapb_kernel)\n\n\n@pytest.fixture\ndef http_client(\n aioresponses_mock: aioresponses, worldmapb_server_zone_lib: ServerZoneLib\n) -> HttpClient:\n client = HttpClient(server_address=\"http://127.0.0.1\")\n\n def _get_tile_types():\n return worldmapb_server_zone_lib.get_all_tiles()\n\n client.get_tile_types = _get_tile_types\n return client\n\n\n@pytest.fixture\ndef worldmapb_client_zone_lib(worldmapb_kernel: Kernel, http_client: HttpClient) -> ClientZoneLib:\n return ClientZoneLib(worldmapb_kernel, http_client)\n\n\n@pytest.fixture\ndef controller(\n worldmapb_kernel: Kernel,\n http_client: HttpClient,\n worldmapb_client_zone_lib: ClientZoneLib,\n franck_model: CharacterModel,\n display_object_manager__empty: DisplayObjectManager,\n) -> Controller:\n controller = Controller(\n client=http_client,\n kernel=worldmapb_kernel,\n display_object_manager=display_object_manager__empty,\n )\n controller._zone_lib = worldmapb_client_zone_lib\n controller._loop = MagicMock()\n controller._player_character = franck_model\n return controller\n\n\n@pytest.fixture\ndef franck_model(default_character_competences: dict) -> CharacterModel:\n return CharacterModel(\n id=\"abc\", name=\"franck\", **default_character_competences, skills={}, knowledges=[]\n )\n\n\nclass TestZoneMapWidget:\n def test_unit__center_on_player__ok__nominal_case(\n self,\n tilemapa_render_engine: TileMapRenderEngine,\n zone_map_widget: TileMapWidget,\n franck_model: CharacterModel,\n ) -> None:\n columns = 9\n rows = 6\n player = CurrentPlayer(character=franck_model, col_i=4, row_i=4)\n\n # Set player on map\n tilemapa_render_engine.display_objects_manager.add_object(player)\n tilemapa_render_engine.display_objects_manager.refresh_indexes()\n\n zone_map_widget.render((columns, rows)) # Default focus on player\n\n # Grab rows and decode them to readable thing\n str_rows = [r.decode() for r in tilemapa_render_engine.rows]\n\n assert [\n \" ⡩⡩⡩\",\n \" ⡩⡩⡩⡩\",\n \" ⡩⡩⡩⡩⡩\",\n \" ⡩ጰ⡩⡩⡩⡩\",\n \" ⡩⡩⡩⡩ʛ⡩⡩\",\n \" ⡩⡩⡩⡩⡩⡩⡩⡩\",\n ] == str_rows\n","sub_path":"tests/unit/gui/test_map_widget.py","file_name":"test_map_widget.py","file_ext":"py","file_size_in_byte":3682,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"165157136","text":"# Task 1\n# Напишіть калькулятор в якого будуть реалізовані операції додавання, віднімання, множення, ділення,\n# піднесення в степінь, взяття з під кореня, пошук відсотку від числа\n# калькулятор працює в нескінченному циклі. На кожній ітерації запитує перше число, операцію,\n# друге число, після чого робить певну операцію з цими числами\n#\n# Огорніть в конструкцію try... except... потенційно \"небезпечні\" місця, наприклад отримання числа і приведення\n# до типу даних або інструкції математичних операцій (ділення на нуль, наприклад)\n#\n# заповніть ваш скрипт логами\n# Логи здебільшого інформаційні (викликали таку функцію з такими аргументами)\n# + логи з помилками\n# причому логи повинні записуватись у файл, тому що в консолі ви будете взаємодіяти з калькулятором,\n# лог файл завжди відкривається в режимі дозапису.\n# так як ви працюєте з файлом не забудьте про те що це потенційне місце поломки\n\nimport logging\n\ntemplate = \"%(levelname)s: %(filename)s: %(asctime)s - %(message)s\"\nlogging.basicConfig(level=logging.INFO, filename=\"Calculator.log\", filemode=\"a\", format=template)\n\n\ndef add(x, y):\n return f'{x} + {y} = {x+y}'\n\n\ndef subtract(x, y):\n return f'{x} - {y} = {x-y}'\n\n\ndef multiply(x, y):\n return f'{x} * {y} = {round(x*y, 3)}'\n\n\ndef divide(x, y):\n return f'{x} / {y} = {round(x/y, 3)}'\n\n\ndef pow_(x, y):\n return f'{x} ** {y} = {round(x**y, 3)}'\n\n\ndef root(x, y):\n return f'Корінь за основою {y} числа {x} = {round(pow(x, 1/y), 3)}'\n\n\ndef percent(x, y):\n return f'{y} percent of {x} = {round((x * y) / 100, 3)}'\n\n\ndef input_calc(msg):\n while True:\n try:\n num = float(input(msg))\n except ValueError:\n logging.error(\"Invalid input\")\n print(\"Неправильний ввід. Операції проводяться тільки над числами.\")\n else:\n break\n return num\n\n\nclass NegativeDegreeError(Exception):\n pass\n\n\nclass NegativeNumberError(Exception):\n pass\n\n\nprint(\"*** КАЛЬКУЛЯТОР ****\")\nprint(\"1.Додавання\")\nprint(\"2.Віднімання\")\nprint(\"3.Множення\")\nprint(\"4.Ділення\")\nprint(\"5.Піднесення до степеня(число, степінь\")\nprint(\"6.Взяття з під кореня(число, основа кореня)\")\nprint(\"7.Пошук відсотку від числа(число, відсоток)\")\nprint(\"8.Вихід з програми\")\n\n\nwhile True:\n # Take input from the user\n choice = input(\"Введіть номер операції >> \")\n # Check if choice is one of the four options\n if choice in ('1', '2', '3', '4', '5', '7'):\n num1 = input_calc(\"Введіть перше число >> \")\n num2 = input_calc(\"Введіть друге число >> \")\n if choice == '1':\n logging.info(\"func add()\")\n print(add(num1, num2))\n\n elif choice == '2':\n logging.info(\"func substract()\")\n print(subtract(num1, num2))\n\n elif choice == '3':\n logging.info(\"func multiply()\")\n print(multiply(num1, num2))\n\n elif choice == '4':\n try:\n print(divide(num1, num2))\n\n except ZeroDivisionError:\n print(\"Помилка. Ділення на нуль.\")\n logging.error(\"ZeroDivisionError\")\n\n elif choice == '5':\n logging.info(\"func pow_()\")\n print(pow_(num1, num2))\n\n elif choice == '7':\n logging.info(\"func root()\")\n print(percent(num1, num2))\n\n elif choice == '6':\n\n try:\n\n num1 = input_calc(\"Введіть перше число >> \")\n\n if num1 < 0:\n raise NegativeNumberError\n\n num2 = input_calc(\"Введіть основу кореня >> \")\n\n if num2 < 0:\n raise NegativeDegreeError\n\n logging.info(\"func root()\")\n\n print(root(num1, num2))\n\n except ZeroDivisionError:\n\n print(\"Помилка. Ділення на нуль.\")\n\n logging.error(\"ZeroDivisionError\")\n\n except NegativeDegreeError:\n\n print(\"Степінь повинна бути > 0\")\n\n logging.error(\"NegativeDegreeError\")\n\n except NegativeNumberError:\n\n print(\"Число має бути > 0\")\n\n logging.error(\"NegativeNumberError\")\n\n elif choice == '8':\n logging.info(\"func exit()\")\n break\n else:\n print(\"Неправильний ввід. Такої операції не існує.\")\n logging.error(\"Invalid input\")\n\n# *** КАЛЬКУЛЯТОР ****\n# 1.Додавання\n# 2.Віднімання\n# 3.Множення\n# 4.Ділення\n# 5.Піднесення до степеня(число, степінь\n# 6.Взяття з під кореня(число, основа кореня)\n# 7.Пошук відсотку від числа(число, відсоток)\n# 8.Вихід з програми\n# Введіть номер операції >> ро\n# Неправильний ввід. Такої операції не існує.\n# Введіть номер операції >> 6\n# Введіть перше число >> 9\n# Введіть основу кореня >> -3\n# Степінь повинна бути > 0\n# Введіть номер операції >> 6\n# Введіть перше число >> 9\n# Введіть основу кореня >> 2\n# Корінь за основою 2.0 числа 9.0 = 3.0\n# Введіть номер операції >> 4\n# Введіть перше число >> 5\n# Введіть друге число >> 0\n# Помилка. Ділення на нуль.\n# Введіть номер операції >> 8\n#\n# Process finished with exit code 0\n\n","sub_path":"homeworks/exceptions_logging/HW#10_task1.py","file_name":"HW#10_task1.py","file_ext":"py","file_size_in_byte":6551,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"147416949","text":"import sys as system\nimport requests\nimport json\nimport decimal\nimport src.couriers as couriers\n\n# generally not great practice to have a global...\ndefault_items = [\n {\"id\": 4, \"name\": \"Cold Brew\", \"price\": 1.3},\n {\"id\": 3, \"name\": \"Ginger Tea\", \"price\": 1.2},\n {\"id\": 6, \"name\": \"Water\", \"price\": 1.0},\n]\nproduct_origin_codes = {\n \"Cold Brew\": \"Italy\",\n \"Ginger Tea\": \"China\",\n \"Water\": \"France\",\n}\nerror_message = \"is not an available option\"\n\n\ndef get_first_courier():\n all_couriers = couriers.get_couriers()\n first_courier = all_couriers[0]\n return first_courier\n\n\ndef format_price(price):\n price_formatted = \"{:.2f}\".format(price)\n return price_formatted\n\n\ndef get_items(items=default_items):\n return items\n\n\ndef get_countries():\n headers = {\"Content-Type\": \"application/json\"}\n api_url = \"https://restcountries.eu/rest/v2/all\"\n\n response = requests.get(api_url, headers=headers)\n\n if response.status_code == 200:\n return json.loads(response.content.decode(\"utf-8\"))\n else:\n return None\n\n\n# get user input for item they want to check\ndef products_origin_prompt():\n print(\"Which product do you want import information on?\")\n selected_product = input()\n return selected_product\n\n\n# retrieve country code for that product\ndef get_product_origin(product, product_origin_codes):\n product_origin = product_origin_codes[product]\n return product_origin\n\n\n# call countries api for countries info\n# retrieve country info using country code\ndef get_product_origin_info(product_origin, get_countries_function):\n countries = get_countries_function()\n for country in countries:\n if country[\"name\"] == product_origin:\n print(country)\n result = f'Country: {product_origin}, Currency: {country[\"currencies\"][0][\"code\"]}, Country Code: {country[\"alpha3Code\"]}'\n return result\n\n\ndef get_product_origin_menu():\n selected_product = products_origin_prompt()\n origin = get_product_origin(selected_product, product_origin_codes)\n try:\n print(get_product_origin_info(origin, get_countries))\n return 1\n except Exception as e:\n print(e)\n\n\ndef get_origin_info_navigator():\n while get_product_origin_menu() != 1:\n pass\n\n\ndef get_item_index(name, items):\n item_index = next(\n (index for (index, item) in enumerate(items) if item[\"name\"] == name)\n )\n return item_index\n\n\ndef update_item(updated_name, updated_price, product_to_update, items=default_items):\n item_index = get_item_index(product_to_update, items)\n product = items[item_index]\n product[\"name\"] = updated_name\n product[\"price\"] = updated_price\n\n print(\n f\"Successfully updated {product_to_update} to {updated_name}, £{updated_price}!\"\n )\n return items\n\n\ndef update_item_prompt():\n # needs validation on existence of product to be updated\n update_item_prompt = [\n \"You are in the update items menu\",\n \"What's the name of the product you wish to update?\",\n ]\n print(\"\\n\")\n print(\"\\n\".join(update_item_prompt))\n display_available_items(get_items(default_items))\n product_to_update = input()\n return product_to_update\n\n\ndef get_updated_item_name():\n # needs input validation\n updated_item_name_prompt = \"Please enter the updated product name\\n\"\n name = input(updated_item_name_prompt)\n return name\n\n\ndef get_updated_item_price():\n # needs input validation on input length and type etc.\n updated_item_price_prompt = \"Please enter the updated product price\\n\"\n price = input(updated_item_price_prompt)\n return convert_to_two_decimal_place(price)\n\n\ndef update_item_menu():\n # again, below three functions should probably\n # be composed into a single parent function\n # which would return the values in a collection\n product_to_update = update_item_prompt()\n name = get_updated_item_name()\n price = get_updated_item_price()\n\n try:\n update_item(name, price, product_to_update)\n return 1\n except Exception as e:\n print(e)\n\n\ndef update_item_navigator():\n while update_item_menu() != 1:\n pass\n\n\ndef add_item(new_item, items=default_items):\n items.append(new_item)\n formatted_price = format_price(new_item[\"price\"])\n print(\n f\"Successfully added {new_item['name']}, £{formatted_price} to the products list!\"\n )\n return items\n\n\ndef get_new_item_name():\n new_item_name_prompt = \"What's the name of the product you wish to add?\\n\"\n name = input(new_item_name_prompt)\n return name\n\n\ndef convert_to_two_decimal_place(price: str):\n # probably want more validation here\n decimal.getcontext().prec = 2\n return decimal.Decimal(price)\n\n\ndef get_new_item_price():\n new_item_price_prompt = \"What's the price of the product you wish to add?\\n\"\n price = input(new_item_price_prompt)\n return convert_to_two_decimal_place(price)\n\n\ndef create_new_item(id, name, price):\n # hacky solution, do not emulate as it's not expressive at all\n new_product_dictionary = locals()\n return new_product_dictionary\n\n\ndef get_available_id(items=default_items):\n all_ids = [items[\"id\"] for items in default_items]\n next_id = max(all_ids) + 1\n return next_id\n\n\ndef add_item_menu():\n # below needs input validation, validation against duplicating items\n # should combine below three functions in a parent function\n # probably called get_item_details()\n name = get_new_item_name()\n price = get_new_item_price()\n new_id = get_available_id()\n new_item = create_new_item(new_id, name, price)\n try:\n add_item(new_item, default_items)\n return 1\n except Exception as e:\n print(e)\n\n\ndef add_item_navigator():\n while add_item_menu() != 1:\n pass\n\n\ndef display_available_items(items):\n print(\"\\nProducts:\")\n for (\n index,\n item,\n ) in enumerate(items, 1):\n formatted_price = format_price(item[\"price\"])\n print(index, f\":: {item['name']} :: £ {formatted_price}\")\n\n\ndef products_menu_prompt_and_choices():\n products_menu_prompt = [\"You are in the products menu.\"]\n products_menu_choices = [\n \"Enter 0 to return to the main menu\",\n \"Enter 1 to see all products\",\n \"Enter 2 to add a product\",\n \"Enter 3 to update a product\",\n \"Enter 4 to get a product's origin info\",\n \"Enter 5 to see an available courier\",\n ]\n print(\"\\n\")\n print(\"\\n\".join(products_menu_prompt + products_menu_choices))\n\n\ndef products_menu(exit_menu_code):\n products_menu_prompt_and_choices()\n\n user_choice = input()\n leave_product_menu = user_choice == \"0\"\n show_items = user_choice == \"1\"\n add_item = user_choice == \"2\"\n update_item = user_choice == \"3\"\n get_item_origin_info = user_choice == \"4\"\n show_available_courier = \"5\"\n\n if show_items:\n display_available_items(get_items(default_items))\n elif add_item:\n add_item_navigator()\n elif update_item:\n update_item_navigator()\n elif get_item_origin_info:\n get_origin_info_navigator()\n elif leave_product_menu:\n return exit_menu_code\n elif show_available_courier:\n print(get_first_courier())\n else:\n print(user_choice, error_message)\n\n\ndef products_menu_navigation(menu_to_print):\n exit_code = 0\n while menu_to_print(exit_code) != exit_code:\n pass\n\n\ndef main_menu_prompt_and_choices():\n main_menu_prompt = [\"You are in the main menu\"]\n main_menu_options = [\n \"Enter 1 to enter the products menu\",\n \"Enter 0 to exit the app\",\n ]\n print(\"\\n\")\n print(\"\\n\".join(main_menu_prompt + main_menu_options))\n\n\ndef main_menu(exit_menu_code):\n main_menu_prompt_and_choices()\n\n user_choice = input()\n exit_app = user_choice == \"0\"\n leave_main_menu = user_choice == \"1\"\n\n if exit_app:\n system.exit(\"Byeee\")\n elif leave_main_menu:\n return exit_menu_code\n else:\n print(user_choice, error_message)\n\n\ndef main_menu_navigation(menu_to_print):\n exit_code = 1\n while menu_to_print(exit_code) != exit_code:\n pass\n\n\ndef navigation():\n is_open = True\n while is_open:\n main_menu_navigation(main_menu)\n products_menu_navigation(products_menu)\n\n\ndef main():\n navigation()\n\n\nif __name__ == \"__main__\":\n main()","sub_path":"src/products.py","file_name":"products.py","file_ext":"py","file_size_in_byte":8341,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"291578074","text":"# -*- coding:utf-8 -*-\nfrom django.shortcuts import render\nfrom django.views.generic import View\nfrom pure_pagination import Paginator, PageNotAnInteger\nfrom .models import CourseOrg, City\n\n\n# Create your views here.\n\n\nclass OrgView(View):\n \"\"\"课程机构列表\"\"\"\n\n def get(self, request):\n # 课程机构\n all_orgs = CourseOrg.objects.all()\n\n # 城市\n all_city = City.objects.all()\n\n # 热门机构按点击量取前3\n hot_orgs = all_orgs.order_by(\"-click_nums\")[:3]\n\n # 筛选城市\n city_id = request.GET.get('city', '')\n if city_id:\n all_orgs = all_orgs.filter(city_id=city_id)\n # 筛选类别\n category = request.GET.get('ct', '')\n if category:\n all_orgs = all_orgs.filter(category=category)\n\n # 排序功能\n sort = request.GET.get('sort', '')\n if sort:\n if sort == 'students':\n all_orgs = all_orgs.order_by('-students')\n elif sort == 'courses':\n all_orgs = all_orgs.order_by('-course_nums')\n\n org_nums = all_orgs.count()\n \n # 分页功能\n try:\n page = request.GET.get('page', 1)\n except PageNotAnInteger:\n page = 1\n\n p = Paginator(all_orgs, 8, request=request)\n\n orgs = p.page(page)\n\n return render(request, 'org-list.html', {\n 'all_orgs': orgs,\n 'all_city': all_city,\n 'org_nums': org_nums,\n 'city_id': city_id,\n 'category': category,\n 'hot_orgs': hot_orgs,\n 'sort': sort,\n })\n","sub_path":"apps/organization/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1636,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"480187124","text":"from django.shortcuts import render, get_object_or_404\nfrom .models import Post\nfrom django.core.paginator import Paginator, PageNotAnInteger, EmptyPage\nfrom .forms import CommentForm\nfrom taggit.models import Tag\n# Create your views here.\n\n\ndef post_list_view(request, tag_slug=None):\n post_list = Post.objects.all()\n tag=None\n if tag_slug:\n tag = get_object_or_404(Tag,slug=tag_slug)\n post_list=post_list.filter(tags__in=[tag])\n paginator = Paginator(post_list, 2)\n page_number = request.GET.get('page')\n try:\n post_list = paginator.page(page_number)\n except PageNotAnInteger:\n post_list = paginator.page(1)\n except EmptyPage:\n post_list = paginator.page(paginator.num_pages)\n\n return render(request,'blog/post_list.html',{'post_list': post_list,'tag':tag})\n\ndef post_detail_view(request,post,year):\n post = get_object_or_404(Post,\n slug=post,\n status='published',\n publish__year=year,)\n comments = post.comments.filter(active=True)\n new_comment = None\n #comment posted\n if request.method=='POST':\n comment_form = CommentForm(data=request.POST)\n if comment_form.is_valid():\n # create comment object but don't save in database yet\n new_comment = comment_form.save(commit=False)\n #assign the current post to the comment\n new_comment.post = post\n # save the comment to database\n new_comment.save()\n else:\n comment_form = CommentForm()\n\n return render(request,'blog/post_detail.html',{'post' : post,'comments':comments,'new_comment':new_comment,'comment_form':comment_form})\n\n\n# def post_detail_view(request,post,year,month,day):\n# post = get_object_or_404(Post,\n# slug=post,\n# status='published',\n# publish__year=year,\n# publish__month=month,\n# publish__day=day)\n# return render(request,'blog/post_detail.html',{'post' : post})\n\nfrom django.core.mail import send_mail\nfrom .forms import EmailSendForm\n\ndef mail_send_view(request,id):\n post = get_object_or_404(Post,id=id,status='published')\n sent=False\n if request.method=='POST':\n form=EmailSendForm(request.POST)\n if form.is_valid():\n cd = form.cleaned_data\n subject='{}({}) recommends you to read \"{}\"'.format(cd['name'],cd['email'],post.title)\n post_url=request.build_absolute_uri(post.get_absolute_url())\n message = 'Read post at :\\n {}\\n\\n{}\\'s Comments:\\n{}'.format(post_url,cd['name'],cd['comments'])\n send_mail(subject,message,'snehalkarale21@gmail.com',[cd['to']])\n sent = True\n else:\n form = EmailSendForm()\n return render(request,'blog/sharebymail.html',{'form':form, 'post':post, 'sent':sent})","sub_path":"blog/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2956,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"156490533","text":"import sys\nimport random\nfrom PyQt5.QtGui import QPainter, QColor\nfrom PyQt5.QtWidgets import QWidget, QApplication\nfrom PyQt5 import uic\n\n\nclass Example(QWidget):\n def __init__(self):\n super().__init__()\n self.setWindowTitle('main.py')\n uic.loadUi('UI.ui', self)\n self.pushButton.clicked.connect(self.drawer)\n self.flag = False\n\n def paintEvent(self, event):\n if self.flag:\n qp = QPainter()\n qp.begin(self)\n qp.setPen(QColor(255, 175, 1))\n rudius = int(random.randrange(1000))\n qp.drawArc(0, 0, rudius, rudius, 0 * 16, 360 * 16)\n self.flag = False\n\n def drawer(self):\n self.flag = True\n self.update()\n\n\nif __name__ == '__main__':\n app = QApplication(sys.argv)\n ex = Example()\n ex.show()\n sys.exit(app.exec())\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":853,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"115129315","text":"# Try handle virtual env if provided\nimport sys\n\nif \"--virtual-env\" in sys.argv:\n virtualEnvPath = sys.argv[sys.argv.index(\"--virtual-env\") + 1]\n virtualEnv = virtualEnvPath + \"/bin/activate_this.py\"\n exec(open(virtualEnv).read(), {\"__file__\": virtualEnv})\n\nfrom trame import start, update_state, change\nfrom trame.html import vuetify, paraview\nfrom trame.layouts import SinglePage\n\nfrom paraview import simple\n\n# -----------------------------------------------------------------------------\n# ParaView code\n# -----------------------------------------------------------------------------\n\nDEFAULT_RESOLUTION = 6\n\ncone = simple.Cone()\nrepresentation = simple.Show(cone)\nview = simple.Render()\n\n\n@change(\"resolution\")\ndef update_cone(resolution, **kwargs):\n cone.Resolution = resolution\n html_view.update()\n\n\ndef update_reset_resolution():\n update_state(\"resolution\", DEFAULT_RESOLUTION)\n\n\n# -----------------------------------------------------------------------------\n# GUI\n# -----------------------------------------------------------------------------\n\nhtml_view = paraview.VtkRemoteView(view, ref=\"view\")\n\nlayout = SinglePage(\"VTK Remote rendering\")\nlayout.logo.click = \"$refs.view.resetCamera()\"\n# layout.logo.children = [vuetify.VIcon('mdi-menu')]\nlayout.title.content = \"Cone Application\"\n\nwith layout.toolbar:\n vuetify.VSpacer()\n vuetify.VSlider(\n v_model=(\"resolution\", DEFAULT_RESOLUTION),\n min=3,\n max=60,\n step=1,\n hide_details=True,\n dense=True,\n style=\"max-width: 300px\",\n )\n vuetify.VDivider(vertical=True, classes=\"mx-2\")\n with vuetify.VBtn(icon=True, click=update_reset_resolution):\n vuetify.VIcon(\"mdi-undo-variant\")\n\nwith layout.content:\n vuetify.VContainer(\n fluid=True,\n classes=\"pa-0 fill-height\",\n children=[html_view],\n )\n\n# layout.footer.hide()\n\n# -----------------------------------------------------------------------------\n# Main\n# -----------------------------------------------------------------------------\n\nif __name__ == \"__main__\":\n start(layout, on_ready=update_cone)\n","sub_path":"examples/ParaView/SimpleCone/RemoteRendering.py","file_name":"RemoteRendering.py","file_ext":"py","file_size_in_byte":2121,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"549055618","text":"#!/usr/bin/env python\nfrom display import *\nfrom kim import *\nfrom mathworld import *\nfrom input import *\nfrom resources import *\nimport pygame\nimport random\nimport sys\n\ndisplay = Display((500,600))\n\ndef getfont(size=12):\n\tfonts = pygame.font.get_fonts()\n\tmonos = map(lambda x:x.find('mono') != -1,fonts)\n\tfont = pygame.font.SysFont(fonts[monos.index(True)],size)\n\treturn font\n\nclass Mouse:\n\tdef __init__(self):\n\t\tself.buttons = [0,0,0]\n\t\tself.pos = [0,0]\n\t\tself.rel = (0,0)\n\tdef update(self,event):\n\t\tself.pos = event.dict['pos']\n\t\tself.rel = event.dict['rel']\n\tdef press(self,num):\n\t\tself.buttons[num-1] = 1\n\tdef unpress(self,num):\n\t\tself.buttons[num-1] = 0\n\tdef getrel(self):\n\t\trel = self.rel[:]\n\t\tself.rel = (0,0)\n\t\treturn rel\n\nclass Input:\n\tdef __init__(self):\n\t\tself.fullscreen = False\n\t\tself.mouselook = False\n\t\tpygame.event.set_allowed([MOUSEBUTTONDOWN,MOUSEBUTTONUP,MOUSEMOTION,KEYDOWN,KEYUP,QUIT])\n\tdef getcommand(self,key):\n\t\tkey = py_to_key[key]\n\t\tif key in bindings.keys():\n\t\t\treturn bindings[key]\n\tdef update(self):\n\t\tfor event in pygame.event.get():\n\t\t\tif event.type == KEYDOWN:\n\t\t\t\tcommand = self.getcommand(event.key)\n\t\t\t\tif command == 'blah':\n\t\t\t\t\tpass\n\t\t\t\telif command == 'toggle_fullscreen':\n\t\t\t\t\tif self.fullscreen:\n\t\t\t\t\t\tpygame.display.toggle_fullscreen()\n\t\t\t\t\t\tself.fullscreen = False\n\t\t\t\t\t\tpygame.mouse.set_visible(1)\n\t\t\t\t\telse:\n\t\t\t\t\t\tpygame.display.toggle_fullscreen()\n\t\t\t\t\t\tself.fullscreen = True\n\t\t\t\t\t\tpygame.mouse.set_visible(1)\n\t\t\t\telif command == 'quit':\n\t\t\t\t\tself.quit()\n\t\t\telif event.type == KEYUP:\n\t\t\t\tcommand = self.getcommand(event.key)\n\t\t\t\tif command == 'blah':\n\t\t\t\t\tpass\n\t\t\telif event.type == QUIT:\n\t\t\t\tself.quit()\n\t\t\telif event.type == MOUSEBUTTONDOWN:\n\t\t\t\tmouse.press(event.button)\n\t\t\telif event.type == MOUSEBUTTONUP:\n\t\t\t\tmouse.unpress(event.button)\n\t\t\telif event.type == MOUSEMOTION:\n\t\t\t\tmouse.update(event)\n\tdef quit(self):\n\t\tif self.fullscreen:\n\t\t\tpygame.display.toggle_fullscreen()\n\t\t\tsys.exit(0)\n\t\telse:\n\t\t\tsys.exit(0)\n\nclass Scene:\n\tdef __init__(self,objects):\n\t\tself.objects = objects\n\tdef render(self,display):\n\t\tfor object in self.objects:\n\t\t\tobject.render_to(display)\n\tdef update(self):\n\t\tfor obj in self.objects:\n\t\t\tif hasattr(obj,'update'):\n\t\t\t\tobj.update()\n\nif __name__ == '__main__':\n\tpygame.init()\n\tfont = getfont()\n\tclock = pygame.time.Clock()\n\tinput = Input()\n\tmouse = Mouse()\n\tcode ='import %s as scene_file'%sys.argv[1].replace('.py','')\n\texec(code)\n\tscene = scene_file.scene\n\twhile 1:\n\t\tclock.tick()\n\t\tinput.update()\n\t\tscene.update()\n\t\tscene.render(display)\n\t\tpygame.display.update()\n","sub_path":"oldprogs/mathworld/engine.py","file_name":"engine.py","file_ext":"py","file_size_in_byte":2544,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"329381733","text":"import tkinter as tk\r\n\r\n# VARIABLES\r\n\r\n# HEX CODES\r\nFAINT_PINK = '#ffc0cb'\r\nSALMON_PINK = '#f87060'\r\n\r\n\r\n\r\n# makes window\r\nwin = tk.Tk()\r\n\r\n# True = Resize, False = not\r\nwin.resizable(True, True)\r\n\r\n#canvas.tk.Canvas(root)\r\n\r\npwetty_fwame = tk.Frame(win)\r\npwetty_fwame.pack()\r\n\r\ntk.Label(win, text=\"Label Time BABY\").pack()\r\ntk.Button(win, text=\"Press Me~~\", bg=FAINT_PINK, fg=SALMON_PINK).pack()\r\n\r\nlabel2 = tk.Label(win,text=\"^^^ Press that button\")\r\nlabel2.pack()\r\n\r\nbutton2 = tk.Button(win, text=\"No press meeee!!!\")\r\nbutton2.pack()\r\n\r\n# Starts GUI\r\nwin.mainloop()\r\n","sub_path":"GUI - 1.py","file_name":"GUI - 1.py","file_ext":"py","file_size_in_byte":570,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"307764987","text":"#! /usr/bin/env python\n# -*- coding: utf-8 -*-\n# Date: 2018/7/20\n\nimport io\nimport re\n\nfrom urllib.request import urlopen\n\nfrom PIL import Image, ImageDraw, ImageFont\n\nfrom qrcode import make as qr_make\n\n\nim = Image.open(\"page.png\")\n\ndraw = ImageDraw.Draw(im)\n\nqr_img = qr_make(\"http://www.baidu.com\").resize((160, 160, ), Image.ANTIALIAS)\n# 拼接二维码\nim.paste(qr_img, (140, 1020))\n\n# 添加文字\nfont = ImageFont.truetype(\"pingfang.ttf\", 30)\n\n# 270 宇宙中最后一个太阳\n# 350 宇宙\n\nname = \"哈哈哈哈哈\"\n\nspacing = 30 if re.search(r'[\\u4e00-\\u9fa5].+', name) else 16\n\nprint(spacing)\n\nposition_x = 375 - len(name) // 2 * spacing\n\nprint(position_x)\n\ndraw.text((position_x, 190), name, fill=(40, 39, 39), font=font)\n\n# 拼接头像\nhead_img_url = \"\"\n\nhead_img_stream = io.BytesIO(urlopen(head_img_url).read())\n\nhead_img = Image.open(head_img_stream).resize((110, 110, ), Image.ANTIALIAS)\n\nimb = Image.new('RGBA', (110, 110), (250, 220, 110))\n\npim_a = head_img.load()\n\npim_b = imb.load()\n\nr = float(110 / 2) # 圆心横坐标\n\nfor i in range(110):\n for j in range(110):\n lx = abs(i - r + 0.5) # 到圆心距离的横坐标\n ly = abs(j - r + 0.5) # 到圆心距离的纵坐标\n position = pow(lx, 2) + pow(ly, 2)\n if position <= pow(r, 2):\n pim_b[i, j] = pim_a[i, j]\n\nim.paste(imb, (320, 65))\n\nim.show()\n","sub_path":"20180720/demo.py","file_name":"demo.py","file_ext":"py","file_size_in_byte":1364,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"24927315","text":"import colored\nimport io\nimport os\nimport re\nimport shlex\nimport signal\nimport sys\nimport subprocess\nimport traceback\n\ndef color_text(s, color):\n return colored.stylize(s, colored.fg(color))\n \nstderr_file_name = 'err.out'\n\nMAGIC_STRING = '/.*/'\ndef compare_output_equivalence(desired_output, test_output):\n \"\"\" Desired outputs have the magic string '/.*/' inserted wherever the \n outputat that position doesn't actually matter. (For example, when the \n time to execute is printed, or another non-deterministic feature of the \n program.)\n \n `compare_outputs` makes sure all of the outputs match in between\n the magic strings. If they do, it returns True.\n \"\"\"\n output_pieces = desired_output.split(MAGIC_STRING)\n for piece in output_pieces:\n index_in_test = test_output.find(piece)\n if index_in_test < 0:\n return False\n else:\n test_output = test_output[index_in_test + len(piece):]\n return True\n \nclass TextAttackTest:\n def __init__(self, name=None, output=None, desc=None):\n if name is None:\n raise ValueError('Cannot initialize TextAttackTest without name')\n if output is None:\n raise ValueError('Cannot initialize TextAttackTest without output')\n if desc is None:\n raise ValueError('Cannot initialize TextAttackTest without description')\n self.name = name\n self.output = output\n self.desc = desc\n \n def execute(self):\n \"\"\" Executes test and returns test output. To be implemented by\n subclasses.\n \"\"\"\n raise NotImplementedError()\n \n def __call__(self):\n \"\"\" Runs test and prints success or failure. \"\"\"\n self.log_start()\n test_output, errored = self.execute()\n if (not errored) and compare_output_equivalence(self.output, test_output):\n self.log_success()\n return True\n else:\n self.log_failure(test_output, errored)\n return False\n \n def log_start(self):\n print(f'Executing test {color_text(self.name, \"blue\")}.')\n \n def log_success(self):\n success_text = f'✓ Succeeded.'\n print(color_text(success_text, 'green'))\n \n def log_failure(self, test_output, errored):\n fail_text = f'✗ Failed.'\n print(color_text(fail_text, 'red'))\n if errored:\n print(f'Test exited early with error: {test_output}')\n else:\n output1 = f'Test output: {test_output}.'\n output2 = f'Correct output: {self.output}.'\n print(f'\\n{output1}\\n{output2}\\n')\n\nclass CommandLineTest(TextAttackTest):\n \"\"\" Runs a command-line command to check for desired output. \"\"\"\n def __init__(self, command, name=None, output=None, desc=None):\n if command is None:\n raise ValueError('Cannot initialize CommandLineTest without command')\n self.command = command\n super().__init__(name=name, output=output, desc=desc)\n \n def execute(self):\n stderr_file = open(stderr_file_name, 'w+')\n if isinstance(self.command, tuple):\n # Support pipes via tuple of commands\n procs = []\n for i in range(len(self.command) - 1):\n if i == 0:\n proc = subprocess.Popen(shlex.split(self.command[i]), stdout=subprocess.PIPE)\n else:\n proc = subprocess.Popen(shlex.split(self.command[i]), stdout=subprocess.PIPE, stdin=proc.stdout)\n procs.append(proc)\n # Run last commmand\n result = subprocess.run(\n shlex.split(self.command[-1]), stdin=procs[-1].stdout, \n stdout=subprocess.PIPE, stderr=stderr_file \n )\n # Wait for all intermittent processes\n for proc in procs:\n proc.wait()\n else:\n result = subprocess.run(\n shlex.split(self.command), \n stdout=subprocess.PIPE,\n stderr=stderr_file \n )\n stderr_file.seek(0) # go back to beginning of file so we can read the whole thing\n stderr_str = stderr_file.read()\n # Remove temp file.\n remove_stderr_file()\n if result.returncode == 0:\n # If the command succeeds, return stdout.\n return result.stdout.decode(), False\n else:\n # If the command returns an exit code, return stderr.\n return stderr_str, True\n\nclass Capturing(list):\n \"\"\" A context manager that captures standard out during its execution. \n \n stackoverflow.com/questions/16571150/how-to-capture-stdout-output-from-a-python-function-call\n \n \"\"\"\n def __enter__(self):\n self._stdout = sys.stdout\n sys.stdout = self._stringio = io.StringIO()\n return self\n def __exit__(self, *args):\n self.extend(self._stringio.getvalue().splitlines())\n del self._stringio # free up some memory\n sys.stdout = self._stdout\n\nclass PythonFunctionTest(TextAttackTest):\n \"\"\" Runs a Python function to check for desired output. \"\"\"\n def __init__(self, function, name=None, output=None, desc=None):\n if function is None:\n raise ValueError('Cannot initialize PythonFunctionTest without function')\n self.function = function\n super().__init__(name=name, output=output, desc=desc)\n \n def execute(self):\n try:\n with Capturing() as output_lines:\n self.function()\n output = '\\n'.join(output_lines)\n return output, False\n except: # catch *all* exceptions\n exc_str_lines = traceback.format_exc().splitlines()\n exc_str = '\\n'.join(exc_str_lines)\n return exc_str, True\n\ndef remove_stderr_file():\n # Make sure the stderr file is removed on exit.\n try:\n os.unlink(stderr_file_name)\n except FileNotFoundError: \n # File doesn't exit - that means we never made it or already cleaned it up\n pass\n \ndef exit_handler(_,__): \n remove_stderr_file()\n\n# If the program exits early, make sure it didn't create any unneeded files.\nsignal.signal(signal.SIGINT, exit_handler)","sub_path":"local_tests/test_models.py","file_name":"test_models.py","file_ext":"py","file_size_in_byte":6251,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"93485911","text":"#!/usr/bin/env python\n# license removed for brevity\n\n# read sensor data from Aruidno, and convert it into joint angle, \n# and pulish it to hand forward kinematics calculator\n\nimport rospy\nfrom std_msgs.msg import Int16MultiArray, MultiArrayDimension\nfrom sensor_msgs.msg import JointState\nimport threading\n\n\nclass get_joint_angle(object):\n def __init__(self):\n\n self.callback_lock = threading.Lock();\n\n # 0 means sensor data is out of range, two possible reasons\n # (a)sensors may lose connections; (b) The motion is beyond the joint limitation\n # in either states, the robot should stop immediately \n self.sensor_check_boolean = 1\n self.common_k = 9.0/28.0\n self.sensor_data = [0,0,0,0,0]\n self.joint_angle_value_data = JointState()\n self.hand_joint_angle = JointState()\n\n rospy.init_node('get_joint_angle_sensor', anonymous=True)\n\n self.palm_sensor1 = rospy.get_param(\"joint_sensor_calibration/palm_sensor1\")\n self.palm_sensor2 = rospy.get_param(\"joint_sensor_calibration/palm_sensor2\")\n self.finger_sensor3 = rospy.get_param(\"joint_sensor_calibration/finger_sensor3\")\n self.finger_sensor4 = rospy.get_param(\"joint_sensor_calibration/finger_sensor4\")\n self.finger_sensor5 = rospy.get_param(\"joint_sensor_calibration/finger_sensor5\")\n\n self.left_finger_sensor_direction = rospy.get_param(\"left_finger_sensor_direction\")\n\n # subscribe data from sensor\n rospy.Subscriber(\"joint_value_arduino\", Int16MultiArray, self.call_back)\n joint_angle_value = rospy.Publisher('sensorToForwardKinematics', JointState, queue_size=10)\n rate = rospy.Rate(30)\n\n while not rospy.is_shutdown():\n\n self.callback_lock.acquire();\n self.hand_angle_data = [self.map_palm_jointA(), self.map_palm_jointE(),\n self.map_left_finger_lower(), self.map_middle_finger_lower(), self.map_right_finger_lower()]\n self.callback_lock.release();\n\n #self.hand_angle_data = [self.joint_angle_value_data.position[0], self.joint_angle_value_data.position[4]]\n\n # if self.sensor_data_limitation():\n self.hand_joint_angle.position = self.hand_angle_data\n joint_angle_value.publish(self.hand_joint_angle)\n\n # else:\n #stop the whole system\n #rospy.loginfo(\"there are some problems with hand joint sensors\")\n #rospy.is_shutdown()\n\n rate.sleep()\n rospy.spin()\n\n\n def call_back(self,msg):\n\n self.callback_lock.acquire();\n self.joint_angle_value_data.position = msg.data\n for i in range(0, len(self.joint_angle_value_data.position)):\n self.sensor_data[i] = self.joint_angle_value_data.position[i]\n self.callback_lock.release();\n\n# map the joint data to angle and pass data to forward kinematics solver\n\n def map_palm_jointA(self):\n self.palm_jointA_sensor = self.sensor_data[0]\n self.palm_jointA_0 = self.palm_sensor1\n self.palm_jointA_k = self.common_k\n self.palm_jointA_b = -self.common_k * self.palm_jointA_0\n self.palm_jointA_value = self.palm_jointA_k * self.palm_jointA_sensor + self.palm_jointA_b\n return self.palm_jointA_value\n\n def map_palm_jointE(self):\n self.palm_jointE_sensor = self.sensor_data[1]\n self.palm_jointE_0 = self.palm_sensor2\n self.palm_jointE_k = -self.common_k\n self.palm_jointE_b = -self.palm_jointE_k * self.palm_jointE_0\n self.palm_jointE_value = self.palm_jointE_k * self.palm_jointE_sensor + self.palm_jointE_b\n return self.palm_jointE_value\n\n def map_left_finger_lower(self):\n self.left_finger_lower_sensor = self.sensor_data[2]\n self.left_finger_lower_0 = self.finger_sensor3\n self.left_finger_lower_k = self.common_k * self.left_finger_sensor_direction\n self.left_finger_lower_b = -self.left_finger_lower_k * self.left_finger_lower_0\n self.left_finger_lower_value = self.left_finger_lower_k * self.left_finger_lower_sensor + self.left_finger_lower_b\n return self.left_finger_lower_value\n\n def map_middle_finger_lower(self):\n self.middle_finger_lower_sensor = self.sensor_data[3]\n self.middle_finger_lower_0 = self.finger_sensor4\n self.middle_finger_lower_k = -self.common_k\n self.middle_finger_lower_b = -self.middle_finger_lower_k * self.middle_finger_lower_0\n self.middle_finger_lower_value = self.middle_finger_lower_k * self.middle_finger_lower_sensor + self.middle_finger_lower_b\n return self.middle_finger_lower_value\n\n\n def map_right_finger_lower(self):\n self.right_finger_lower_sensor = self.sensor_data[4]\n self.right_finger_lower_0 = self.finger_sensor5\n self.right_finger_lower_k = -self.common_k\n self.right_finger_lower_b = -self.right_finger_lower_k * self.right_finger_lower_0\n self.right_finger_lower_value = self.right_finger_lower_k * self.right_finger_lower_sensor + self.right_finger_lower_b\n return self.right_finger_lower_value\n\n #for safety issue \n\n def sensor_data_limitation(self):\n self.sensor_lower_boundary = [0, 0, -80.0, -80.0, -80.0]\n self.sensor_upper_boundary = [60.0, 90.0, 90.0, 90.0, 90.0]\n for i in [0,1,2,3,4]:\n if ((self.hand_angle_data[i] >= -90.0) & (self.hand_angle_data[i] <= 90.0)):\n self.sensor_check_boolean = True\n #print self.hand_angle_data[i]\n else:\n self.sensor_check_boolean = False\n break\n #rospy.is_shutdown()\n return self.sensor_check_boolean\n\n\n\n\nif __name__ == '__main__':\n try:\n get_joint_angle()\n except rospy.ROSInterruptException: pass\n\n\n\n\n'''\n\n1. get joint angle value from arduino\n\n\n'''\n\n","sub_path":"kclhand_control/scripts/get_joint_angle_sensor_value.py","file_name":"get_joint_angle_sensor_value.py","file_ext":"py","file_size_in_byte":5879,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"218636605","text":"#!/usr/bin/python3\r\nfrom RPi import GPIO\r\nfrom time import sleep\r\nGPIO.setmode(GPIO.BCM)\r\nGPIO.setup(26, GPIO.OUT)\r\nGPIO.output(26, True)\r\nsleep(0.1)\r\nGPIO.output(26, False)\r\nGPIO.cleanup()\r\n\r\nimport time\r\nfrom rpi_ws281x import PixelStrip, Color\r\n\r\n# LED strip configuration:\r\nLED_COUNT = 34 # Number of LED pixels.\r\nLED_PIN = 13 # GPIO pin connected to the pixels (18 uses PWM!).\r\nLED_FREQ_HZ = 800000 # LED signal frequency in hertz (usually 800khz)\r\nLED_DMA = 10 # DMA channel to use for generating signal (try 10)\r\nLED_BRIGHTNESS = 255 # Set to 0 for darkest and 255 for brightest\r\nLED_INVERT = False # True to invert the signal (when using NPN transistor level shift)\r\nLED_CHANNEL = 1 # set to '1' for GPIOs 13, 19, 41, 45 or 53\r\n\r\ndef wheel(pos):\r\n \"\"\"Generate rainbow colors across 0-255 positions.\"\"\"\r\n if pos < 85:\r\n return Color(pos * 3, 255 - pos * 3, 0)\r\n elif pos < 170:\r\n pos -= 85\r\n return Color(255 - pos * 3, 0, pos * 3)\r\n else:\r\n pos -= 170\r\n return Color(0, pos * 3, 255 - pos * 3)\r\n\r\ndef rainbowCycle(strip, wait_ms=20, iterations=5):\r\n \"\"\"Draw rainbow that uniformly distributes itself across all pixels.\"\"\"\r\n for j in range(256 * iterations):\r\n for i in range(strip.numPixels()):\r\n strip.setPixelColor(i, wheel(\r\n (int(i * 256 / strip.numPixels()) + j) & 255))\r\n strip.show()\r\n time.sleep(wait_ms / 1000.0)\r\n\r\nstrip = PixelStrip(LED_COUNT, LED_PIN, LED_FREQ_HZ, LED_DMA, LED_INVERT, LED_BRIGHTNESS, LED_CHANNEL)\r\nstrip.begin()\r\n\r\nwhile True:\r\n rainbowCycle(strip) # rainbow","sub_path":"Leds/rainbow.py","file_name":"rainbow.py","file_ext":"py","file_size_in_byte":1635,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"351890883","text":"#coding: utf-8\n\nimport time\n\nfile = open(\"time.txt\", \"a+\") #tu jest file, ale mogłoby być coś innego\n\nfile.write(time.asctime() + \"\\n\" )\n\nfile.close()\n\n#execfile(\"test.py\") #wywołuj forlater\n\n","sub_path":"get-time.py","file_name":"get-time.py","file_ext":"py","file_size_in_byte":196,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"248716563","text":"\"\"\"\n判断是否精准匹配\n\"\"\"\nfrom pymongo import MongoClient\nimport re\nfrom standardization import StandardCity as sc\nimport requests\n\nclient136 = MongoClient('mongodb://192.168.0.136:27017')\nseaweed = client136['fangjia']['seaweed']\n\n\ndef format_name_address(name):\n specific_symbol = [\".\", \"|\", \"•\", \"、\", \";\", \";\", \",\", \",\", \"·\", \" \"]\n if name == None:\n return name\n for spe in specific_symbol:\n name = name.replace(spe, '')\n\n other_words = re.search(r'(\\(.*\\))', name)\n if other_words:\n name = name.replace(other_words.group(), '')\n\n return name\n\n\ndef match_api(keyword, city=None, preciselevel=None, category=None):\n \"\"\"\n :param keyword:\n :param city\n :param preciselevel: 价格等级:strict\n :param category: 类型:property\n\n :return\n \"\"\"\n key = \"F54F52381C49BB9EB4A33EB1B65604AE4B71A28AEE53518A94A2F360408B9056D57553931D15CE6DDE765562DAD286BA38E\" \\\n \"05A4CDAFC51C3D527A4959BF8E75A3B95DB7108FCEA340DDE61925616DB55118E1851E67D83EAD800460D100D6B667A4ED8EE67C8F7FB\"\n url = 'http://open.fangjia.com/address/match?'\n pay_load = {'address': keyword, 'city': city, 'preciseLevel': preciselevel, 'category': category, 'token': key}\n r = requests.get(url, params=pay_load)\n if r.json()['msg'] == 'ok':\n return r.json()['result']\n\n\nclass MatchSeaweed:\n # 获取匹配到的小区的名称、名称别名、精确地址、地址别名以及单独的地址别名、别名\n @classmethod\n def seaweed_name_list(cls, match_info_dict):\n # 定义一个list,初始加入名称\n name_list = [match_info_dict['name']]\n\n # 加入别名\n alias = match_info_dict.get('alias', None)\n if alias:\n name_list += alias\n\n # 加入精确地址\n pattern = re.compile(r'\\d+(号|弄|支|支弄)')\n if re.search(pattern, match_info_dict.get('address', '')):\n name_list.append(match_info_dict['address'])\n\n # 加入地址别名\n addalias = cls.get_address_alias(match_info_dict['city'], match_info_dict['district'], match_info_dict['name'],\n pattern)\n if addalias:\n name_list += addalias\n return name_list, addalias, alias\n\n @staticmethod\n def get_address_alias(scity, sregion, sname, pattern):\n one = seaweed.find_one({'city': scity, 'region': sregion, 'name': sname, 'status': 0, 'cat': 'district'},\n {'addr_alias': 1})\n addr_list = []\n if one and 'addr_alias' in one and one['addr_alias'] not in ['', [], None]:\n # 默认地址别名里面的都是精确地址,但是以防万一\n for a in one['addr_alias']:\n if re.search(pattern, str(a)):\n addr_list.append(a)\n if len(addr_list) > 0:\n return addr_list\n\n @classmethod\n def from_match_api(cls, city, name_address, region='', category=None):\n format_name = region + name_address if region and region not in name_address else name_address\n match_info_dict = match_api(format_name_address(format_name), city=city, category=category)\n\n if match_info_dict and match_info_dict['credit'] > 0:\n # 将名称、名称别名、精确地址、地址别名加入一个匹配列\n name_list, addalias, alias = cls.seaweed_name_list(match_info_dict)\n\n return_data = {'mcity': match_info_dict['city'],\n 'mregion': match_info_dict['district'],\n 'mname': match_info_dict['name'],\n 'maddress': match_info_dict.get('address'),\n 'malias': alias,\n 'maddralias': addalias,\n '_id': match_info_dict['id']}\n\n if city == match_info_dict['city'] and (\n str(region) in match_info_dict['district'] or match_info_dict['district'] in str(region)):\n if name_address in name_list:\n return_data['flag'] = '精确匹配'\n elif format_name_address(name_address) in name_list:\n return_data['flag'] = '精确匹配,加别名'\n else:\n return_data['flag'] = '模糊匹配'\n return return_data\n else:\n return_data['flag'] = '模糊匹配'\n return return_data\n\n\ndef match(city, **kwargs):\n \"\"\"\n\n :param city:\n :param kwargs:\n city: 城市\n region: 区域\n keyword: 名称\n category: property(小区),shop(商铺),office(写字楼)\n :return: 匹配结果\n \"\"\"\n\n region = kwargs.get('region')\n standard = sc()\n result, format_city = standard.standard_city(city)\n\n if result:\n result, region = standard.standard_region(format_city, region)\n else:\n return None\n\n keyword = kwargs.get('keyword')\n if keyword:\n category = kwargs.get('category')\n match = MatchSeaweed.from_match_api(format_city, keyword, region, category)\n return match\n\n\nif __name__ == '__main__':\n print(match(city='上海', region='长宁', keyword='新泾6村'))\n","sub_path":"lib/match_district.py","file_name":"match_district.py","file_ext":"py","file_size_in_byte":5246,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"358408755","text":"import paho.mqtt.client as mqtt\nfrom gpiozero import Motor\nimport threading\nimport time\nimport ultrasonic as us\n# motl = Motor(2, 3)\n# motr= Motor(14, 15)\nmotl = Motor(3, 2)\nmotr= Motor(15, 14)\n\njoys_pos=[]\nlr_pos_r=0\nfwrev_pos_r=0\n\nl_stop_val=0\nr_stop_val=0\n\ndef on_connect(client, userdata, flags, rc):\n print(\"Connected with result code \"+str(rc))\n\n client.subscribe('joystick/lr')\n client.subscribe('joystick/fwrev')\n \ndef on_message(client, userdata, msg):\n global joys_pos,lr_pos_r,fwrev_pos_r\n\n if msg.topic=='joystick/fwrev':\n fwrev_pos_r=float(msg.payload.decode())\n \n if msg.topic=='joystick/lr':\n lr_pos_r=float(msg.payload.decode())\n\n # data=msg.payload.decode()\n # joys_pos=data.split(',')\n # lr_pos_r=float(joys_pos[0])\n # fwrev_pos_r=float(joys_pos[1])\n\n\ndef client_loop():\n global client\n while True:\n client.loop()\n\ndef motor_stop():\n # for i in range(1,99,1):\n # l_pwr=l_stop_val-i/100\n # r_pwr=r_stop_val-i/100\n\n # if(l_pwr<0 or l_pwr>1):\n # pass\n # else:\n # motl.forward(l_pwr)\n\n # if(r_pwr<0 or r_pwr>1):\n # pass\n # else:\n # motr.forward(r_pwr)\n\n motl.stop()\n motr.stop()\n print('Stop')\n\n\nclient = mqtt.Client()\nclient.on_connect = on_connect\nclient.on_message = on_message\nclient.connect('192.168.100.235', 1883, 60)\n\nthreading.Thread(target=client_loop,daemon=True).start()\n\nwhile True:\n lr_pos=lr_pos_r\n fwrev_pos=fwrev_pos_r\n lr_pos_r=0\n fwrev_pos_r=0\n time.sleep(0.1)\n if lr_pos==0 and fwrev_pos<0: #forward\n motl.forward(speed=-fwrev_pos)\n motr.forward(speed=-fwrev_pos)\n \n l_stop_val=-fwrev_pos\n r_stop_val=-fwrev_pos\n\n print('Forward : ',-fwrev_pos)\n\n elif lr_pos==0 and fwrev_pos>0: #reverse\n if us.get_distance()<50:\n print('[STOP] Obstacle detected')\n motor_stop()\n else: \n print('Reverse : ',fwrev_pos)\n motl.backward(speed=fwrev_pos)\n motr.backward(speed=fwrev_pos)\n \n l_stop_val=fwrev_pos\n r_stop_val=fwrev_pos\n\n elif lr_pos<0 and fwrev_pos==0: #left\n motl.backward(-lr_pos)\n motr.forward(-lr_pos)\n \n l_stop_val=-lr_pos\n r_stop_val=-lr_pos\n\n print('Left : ',lr_pos)\n \n elif lr_pos>0 and fwrev_pos==0: #right\n motl.forward(lr_pos)\n motr.backward(lr_pos) \n \n l_stop_val=lr_pos\n r_stop_val=lr_pos\n\n print('Right : ',lr_pos)\n\n elif lr_pos<0 and fwrev_pos<0: # forward left\n if -lr_pos>-fwrev_pos:\n r_power=-lr_pos\n l_power=-fwrev_pos\n\n elif -lr_pos<-fwrev_pos:\n r_power=-fwrev_pos\n l_power=-lr_pos\n\n motl.forward(l_power)\n motr.forward(r_power)\n\n l_stop_val=l_power\n r_stop_val=r_power\n\n print('Forward Left')\n print('Mot L : ',l_power,' Mot R : ',r_power)\n\n elif lr_pos>0 and fwrev_pos<0: # forward right\n if lr_pos>-fwrev_pos:\n r_power=-fwrev_pos\n l_power=lr_pos\n \n elif lr_pos<-fwrev_pos:\n r_power=lr_pos\n l_power=-fwrev_pos\n\n motl.forward(l_power)\n motr.forward(r_power)\n\n l_stop_val=l_power\n r_stop_val=r_power\n\n print('Forward Right')\n print('Mot L : ',l_power,' Mot R : ',r_power)\n\n elif lr_pos<0 and fwrev_pos>0: # backward left\n if -lr_pos>fwrev_pos:\n r_power=-lr_pos\n l_power=fwrev_pos\n \n elif -lr_pos0 and fwrev_pos>0: # backward right\n if lr_pos>fwrev_pos:\n r_power=fwrev_pos\n l_power=lr_pos \n elif lr_pos= min_len:\n probe_rc = probe_rc[:-1]\n probe_list.append(probe_rc)\n probe_bind_len = len(probe_rc)\n idx_rc = idx_rc + 1\n while probe_bind_len2 >= min_len:\n probe_fc = probe_fc[1:]\n probe_list.append(probe_fc)\n probe_bind_len2 = len(probe_fc)\n idx_fc = idx_fc + 1\n else:\n long_seq_list.append(seq_record.id)\n \n idx = 1\n short = 0\n for seq_probe in probe_list: \n probe = (prefix_nt * poly_nt) + str(seq_probe)\n probe_length = len(probe)\n Tm_ori = primer3.calcTm(probe)\n Tm_ori2 = (\"%.2f\" % Tm_ori)\n GC_percent_ori = GC(probe)\n GC_per_2 = (\"%.2f\" % GC_percent_ori)\n output.write(seq_record.id + \"_\" + str(idx) + \"\\t\" + probe + \"\\t\" + str(GC_per_2) + \"\\t\" + str(Tm_ori2) + \"\\t\", end = '')\n if(probe_length <=40):\n short = short+1\n else:\n output.write(\"\\n\")\n if(probe_length <= 40):\n Tm = primer3.calcTm(probe)\n Tm2 = (\"%.2f\" % Tm)\n GC_percent = GC(probe)\n GC_per = (\"%.2f\" % GC_percent)\n Homodimer = primer3.calcHomodimer(probe)\n Hairpin = primer3.calcHairpin(probe)\n output.write(str(GC_per) + \"\\t\" + str(Tm2) + \"\\t\" + str(Hairpin.structure_found) + \"\\t\" + str(Homodimer.structure_found))\n idx = idx+1\n\n\noutput.close()\n","sub_path":"scripts/probe_design_11.py","file_name":"probe_design_11.py","file_ext":"py","file_size_in_byte":2910,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"592560413","text":"##+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n#Connect and list the dir of and FTP site\n#SOMETIMES THIS TIMES OUT.\nimport ftplib\n\n#Open ftp connection\nftp = ftplib.FTP('ftp.jackscrib.com', 'ericftp',\n'Chibby2000!')\n\n#List the files in the current directory\nprint (\"File List:\")\nfiles = ftp.dir()\nprint (files)\n\n#Chagne dir to the demos dir\n#ftp.cwd(\"/demos\")\n\n#print (\"File List:\")\n#files = ftp.dir()\n#print (files)\n\ngFile = open(\"Home.html\", \"wb\")\nftp.retrbinary('RETR Home.html', gFile.write)\ngFile.close()\n\nprint('FTP Closed')\n\n#Print the readme file contents\n#print (\"\\nReadme File Output:\")\n#gFile = open(\"readme.txt\", \"r\")\n#buff = gFile.read(\"GAVPOS.CSV\")\n#print (buff)\n#gFile.close()\n\nftp.quit()\n","sub_path":"VariousSnippets/dummy.py","file_name":"dummy.py","file_ext":"py","file_size_in_byte":726,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"506310093","text":"#Author:Chris.chen\n\n# /usr/bin/env python\n# coding=utf8\n\nfrom http import client\nfrom urllib import parse\nimport hashlib\nimport random\nimport json\n\nappid = '20180119000116826'\nsecretKey = 'X0NDF1CPlCp6XV9GAyrz'\n\n\nhttpClient = None\nmyurl = '/api/trans/vip/translate'\nq = 'apple' #要翻译的单词过语句\nfromLang = 'auto'\ntoLang = 'zh'\nsalt = random.randint(32768, 65536)\n\nsign = appid + q + str(salt) + secretKey\nm1 = hashlib.md5()\nm1.update(sign.encode())\nsign = m1.hexdigest()\n# print(sign)\nmyurl = myurl + '?appid=' + appid + '&q=' + parse.quote(q) + '&from=' + fromLang + '&to=' + toLang + '&salt=' + str(\n salt) + '&sign=' + sign\nprint(myurl)\ntry:\n httpClient = client.HTTPConnection('api.fanyi.baidu.com')\n httpClient.request('GET', myurl)\n # response是HTTPResponse对象\n response = httpClient.getresponse()\n result = response.read().decode()\n result = json.loads(result)\n print('response',result)\n\nexcept Exception as e:\n print(e)\nfinally:\n if httpClient:\n httpClient.close()\n","sub_path":"tools/other/百度翻译接口.py","file_name":"百度翻译接口.py","file_ext":"py","file_size_in_byte":1027,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"397387817","text":"from flask import Blueprint\nfrom models.state import State\nfrom models.amenity import Amenity\nfrom models.city import City\nfrom models.user import User\nfrom models.place import Place\nfrom models.review import Review\n\napp_views = Blueprint('app_views', __name__, url_prefix='/api/v1')\n\n\ndef get(data):\n ''' Sends HTTP GET request '''\n if data['p_id']:\n parent = storage.get(data['p_str'], data['p_id'])\n if parent:\n return jsonify([p.to_dict() for p in\n getattr(parent, data['p_child'])]), 200\n abort(404)\n if data['_id']:\n found = storage.get(data['str'], data['_id'])\n if found:\n return jsonify(found.to_dict()), 200\n abort(404)\n else:\n return jsonify([x.to_dict() for x in\n storage.all(data['str']).values()]), 200\n\n\ndef delete(data):\n ''' Sends HTTP DELETE request '''\n found = storage.get(data['str'], data['_id'])\n if found:\n storage.delete(found)\n storage.save()\n return jsonify({}), 200\n else:\n abort(404)\n\n\ndef post(data):\n ''' Sends HTTP POST request '''\n req = request.get_json()\n if req is None:\n return jsonify({'error': 'Not a JSON'}), 400\n for c in data['check']:\n if c not in req:\n return jsonify({'error': 'Missing {}'.format(c)}), 400\n if data['p_id']:\n if 'user_id' in data['check']:\n if not storage.get('User', req['user_id']):\n abort(404)\n parent = storage.get(data['p_str'], data['p_id'])\n if parent:\n req[data['p_prop']] = data['p_id']\n new = eval(data['str'])(**req)\n new.save()\n return jsonify(new.to_dict()), 201\n abort(404)\n new = eval(data['str'])(**req)\n new.save()\n return jsonify(new.to_dict()), 201\n\n\ndef put(data):\n ''' Sends HTTP PUT request '''\n req = request.get_json()\n if req is None:\n return jsonify({'error': 'Not a JSON'}), 400\n found = storage.get(data['str'], data['_id'])\n if found:\n for k, v in req.items():\n if k not in data['ignore']:\n setattr(found, k, v)\n storage.save()\n return jsonify(found.to_dict()), 200\n else:\n abort(404)\n\nfrom api.v1.views.index import *\nfrom api.v1.views.states import *\nfrom api.v1.views.cities import *\nfrom api.v1.views.amenities import *\nfrom api.v1.views.users import *\nfrom api.v1.views.places import *\nfrom api.v1.views.places_reviews import *\nfrom api.v1.views.places_amenities import *\n","sub_path":"api/v1/views/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2565,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"283735457","text":"import matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\n\nfrom evaluation.evaluation import sum_results, average_precision_recall\nfrom utils.fileaccess.utils import load_file\nfrom utils.workdir import cd_work\n\ncd_work()\nmodels = [\n # 'hsv',\n # 'background',\n # 'chromatic',\n 'blur',\n # 'blur_distortion',\n 'gray',\n 'distortion',\n 'mavlabgates',\n]\ntitles = [\n # 'hsv',\n # 'VOC \\n background',\n # 'chromatic',\n 'Blur',\n # 'blur \\n + distortion',\n 'Grey',\n 'Distortion',\n 'No\\n Augmentation',\n 'SnakeGate',\n]\n\ndatasets = [\n 'jevois_cyberzoo',\n 'jevois_basement',\n 'jevois_hallway',\n]\n\ndatasets_title = [\n 'Cyberzoo',\n 'Basement',\n 'Hallway'\n]\n\nious = [0.6]\nn_iterations = 5\nframe = pd.DataFrame()\n# frame['Name'] = models + ['SnakeGate']\nfor iou in ious:\n for d in datasets:\n for it in range(n_iterations):\n column = []\n for m in models:\n try:\n new_frame = pd.read_pickle('out/{0:s}_i{1:02d}/test_{2:s}/results_total.pkl'.format(m, it, d))\n cell = new_frame['{}_ap{:.6f}_i0{}'.format(d, iou, it)][0]\n column.append(cell)\n except FileNotFoundError as e:\n column.append(-1)\n print(e)\n continue\n\n result_file = 'out/snake/test_' + d + '_results_iou' + str(iou) + '_' + str(it) + '.pkl'.format(d,\n iou,\n it)\n\n results = load_file(result_file)\n mean_pr, mean_rec, std_pr, std_rec = average_precision_recall([sum_results(results['results'])])\n column.append(mean_pr.mean())\n\n frame['{}_iou{}_i0{}'.format(d, iou, it)] = column\n print(frame.to_string())\n\niou = 0.6\n# column_names = titles\n# table = pd.DataFrame()\n# table['Augmentation'] = column_names\n# for i_d, d in enumerate(datasets):\n# column_content = []\n# for i_m, _ in enumerate(models):\n# results = []\n# for i_i in range(n_iterations):\n# result = frame['{}_iou{}_i0{}'.format(d, iou, i_i)][i_m]\n# if result >= 0:\n# results.append(result)\n# column_content.append('${:.2f} \\pm {:.2f}$'.format(np.mean(results), np.std(results)))\n# table[datasets_title[i_d] + ' $ap_{' + str(int(np.round(iou * 100, 0))) + '}$'] = column_content\n#\n# print(table.to_string(index=False))\n# print(table.to_latex(index=False, escape=False))\n# save_file(table.to_latex(index=False, escape=False), 'augmentation.txt', 'doc/thesis/tables/', raw=True)\n\nplt.figure(figsize=(10, 3))\nplt.grid(b=True, which='major', color=(0.75, 0.75, 0.75), linestyle='-', zorder=0)\nplt.grid(b=True, which='minor', color=(0.75, 0.75, 0.75), linestyle='--', zorder=0)\nw = 1 / (len(datasets)) / 2\nhandles = []\nfor i_d, d in enumerate(datasets):\n mean = []\n err = []\n for i_m in range(len(models) + 1):\n results = []\n for i_i in range(n_iterations):\n result = frame['{}_iou{}_i0{}'.format(d, iou, i_i)][i_m]\n if result >= 0:\n results.append(result)\n mean.append(np.mean(results))\n err.append(np.std(results))\n h = plt.bar(np.arange(len(models) + 1) + 0.5 + i_d * w - (len(models) + 1) * w, mean, width=w, capsize=2,\n ecolor='gray', zorder=3)\n plt.errorbar(np.arange(len(models) + 1) + 0.5 + i_d * w - (len(models) + 1) * w, mean, err, 0, fmt=' ',\n ecolor='gray', capsize=2,\n elinewidth=1, zorder=3)\n handles.append(h)\nplt.legend(handles, datasets_title, bbox_to_anchor=(1.0, 1.0), loc='center right')\n\nplt.xticks(np.arange(len(models) + 1), titles)\nplt.ylabel('Average Precision')\nplt.minorticks_on()\nplt.ylim(0, 0.7)\n# plt.legend(handles, datasets_title)\nplt.subplots_adjust(left=None, bottom=0.2, right=None, top=None,\n wspace=0.3, hspace=0.3)\nplt.savefig('doc/presentation/augmentation.png',dpi=600, bbox_inches='ticht')\nplt.show(True)\n","sub_path":"src/python/doc/00_defense/plot_results_on_real.py","file_name":"plot_results_on_real.py","file_ext":"py","file_size_in_byte":4201,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"562321031","text":"\"\"\"\nThis is the people module and supports all the ReST actions for the\nPEOPLE collection\n\"\"\"\n\n# System modules\nfrom datetime import datetime\n\n# 3rd party modules\nfrom flask import make_response, abort\n\n\ndef get_timestamp():\n return datetime.now().strftime((\"%Y-%m-%d %H:%M:%S\"))\n\n\n# Data to serve with our API\nPEOPLE = {\n \"Farrell\": {\n \"fname\": \"Doug\",\n \"lname\": \"Farrell\",\n \"timestamp\": get_timestamp(),\n },\n \"Brockman\": {\n \"fname\": \"Kent\",\n \"lname\": \"Brockman\",\n \"timestamp\": get_timestamp(),\n },\n \"Easter\": {\n \"fname\": \"Bunny\",\n \"lname\": \"Easter\",\n \"timestamp\": get_timestamp(),\n },\n}\n\n\ndef read_all():\n \"\"\"\n This function responds to a request for /api/people\n with the complete lists of people\n\n :return: json string of list of people\n \"\"\"\n # Create the list of people from our data\n return [PEOPLE[key] for key in sorted(PEOPLE.keys())]\n\n\ndef read_one(lname):\n \"\"\"\n This function responds to a request for /api/people/{lname}\n with one matching person from people\n\n :param lname: last name of person to find\n :return: person matching last name\n \"\"\"\n # Does the person exist in people?\n if lname in PEOPLE:\n person = PEOPLE.get(lname)\n\n # otherwise, nope, not found\n else:\n abort(\n 404, \"Person with last name {lname} not found\".format(lname=lname)\n )\n\n return person\n\n\ndef create(person):\n \"\"\"\n This function creates a new person in the people structure\n based on the passed in person data\n\n :param person: person to create in people structure\n :return: 201 on success, 406 on person exists\n \"\"\"\n lname = person.get(\"lname\", None)\n fname = person.get(\"fname\", None)\n\n # Does the person exist already?\n if lname not in PEOPLE and lname is not None:\n PEOPLE[lname] = {\n \"lname\": lname,\n \"fname\": fname,\n \"timestamp\": get_timestamp(),\n }\n return PEOPLE[lname], 201\n\n # Otherwise, they exist, that's an error\n else:\n abort(\n 406,\n \"Person with last name {lname} already exists\".format(lname=lname),\n )\n\n\ndef update(lname, person):\n \"\"\"\n This function updates an existing person in the people structure\n\n :param lname: last name of person to update in the people structure\n :param person: person to update\n :return: updated person structure\n \"\"\"\n # Does the person exist in people?\n if lname in PEOPLE:\n PEOPLE[lname][\"fname\"] = person.get(\"fname\")\n PEOPLE[lname][\"timestamp\"] = get_timestamp()\n\n return PEOPLE[lname]\n\n # otherwise, nope, that's an error\n else:\n abort(\n 404, \"Person with last name {lname} not found\".format(lname=lname)\n )\n\n\ndef delete(lname):\n \"\"\"\n This function deletes a person from the people structure\n\n :param lname: last name of person to delete\n :return: 200 on successful delete, 404 if not found\n \"\"\"\n # Does the person to delete exist?\n if lname in PEOPLE:\n del PEOPLE[lname]\n return make_response(\n \"{lname} successfully deleted\".format(lname=lname), 200\n )\n\n # Otherwise, nope, person to delete not found\n else:\n abort(\n 404, \"Person with last name {lname} not found\".format(lname=lname)\n )\n","sub_path":"flask-connexion-rest/version_4/people.py","file_name":"people.py","file_ext":"py","file_size_in_byte":3423,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"597988291","text":"# -*- coding: utf-8 -*-\n\nfrom re import match as rematch\n\nclass IrcMessage(object):\n\n \"\"\"IRC message\"\"\"\n\n # should be overwritten with IrcMessage._bot = .. before init\n \"\"\"irc bot [core2.core2]\"\"\"\n _bot = None\n\n def __init__(self, raw, server_name):\n \"\"\"init irc message\n\n :raw: raw irc message\n\n \"\"\"\n splraw = raw.split()\n\n self._raw = raw\n self._server = self\n self._server_name = server_name\n self._command = splraw[1]\n self._prefix = splraw[0]\n\n # split prefix from nick[!user][@host] into nick,user,host\n # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n if self._prefix.startswith(':'):\n self._prefix = self._prefix[1:]\n if '!' in self._prefix:\n if '@' in self._prefix:\n self._nick = self._prefix.split('!', 1)\n self._user = self._nick[1].split('@', 1)\n self._host = self._user[1]\n self._user = self._user[0]\n self._nick = self._nick[0]\n else:\n self._nick = self._prefix.split('!')\n self._user = self._nick[1]\n self._nick = self._nick[0]\n self._host = None\n elif '@' in self._prefix:\n self._nick = self._prefix.split('!')\n self._host = self._nick[1]\n self._nick = self._nick[0]\n self._user = None\n else:\n self._nick = self._prefix\n self._user = None\n self._host = None\n else:\n # first word was not a prefix (e.g. PING,PONG)\n self._command = splraw[0]\n self._prefix = None\n\n # get middle and message\n # ~~~~~~~~~~~~~~~~~~~~~~\n self._message = None\n self._middle = []\n for ind,word in enumerate(splraw[1:] if self._prefix is None else splraw[2:]):\n if word.startswith(':'):\n ind += 1 if self._prefix is None else 2\n self._message = raw.split(None, ind)[ind][1:]\n break\n self._middle.append(word)\n\n # TODO: extras\n self.regex_groups = None\n\n def is_owner_nick(self):\n \"\"\"checks if sender's nick matches bot's owner nick\n\n :returns: [bool]\n\n \"\"\"\n return rematch(self.get_server()._owner_nick, self._nick)\n\n def is_owner_user(self):\n \"\"\"checks if sender's user matches bot's owner user\n\n :returns: [bool]\n\n \"\"\"\n return self._user is not None and rematch(self.get_server()._owner_user, self._user)\n\n def is_owner_host(self):\n \"\"\"checks if sender's host matches bot's owner host\n\n :returns: [bool]\n\n \"\"\"\n return self._host is not None and rematch(self.get_server()._owner_host, self._host)\n\n def get_server(self):\n \"\"\"returns the server from which the message originated\n\n :returns: server [server.Server]\n\n \"\"\"\n return self._bot._servers[self._server_name]\n\n def get_channel(self):\n if self._command in ('PRIVMSG', 'NOTICE', 'JOIN'):\n return self._middle[0]\n return None\n\n def say_back(self, msg):\n chan = self.get_channel()\n if chan is not None:\n self.get_server().say(chan, msg)\n return True\n return False\n\n def __repr__(self):\n return self._raw\n\n def __str__(self):\n return '{} {} {} {}'.format(self._prefix, self._command, self._middle, self._message)\n","sub_path":"irc_message.py","file_name":"irc_message.py","file_ext":"py","file_size_in_byte":3589,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"285830251","text":"from flask import Flask, request, render_template, render_template_string\nfrom flask import make_response\nfrom reportlab.pdfgen import canvas\n\nfrom Services.report_manager import ReportManager\nfrom Services.report_exception import ReportException\nfrom flask_restful import Resource, Api\n\napp = Flask(__name__)\n\n\n@app.route('/')\ndef server_1():\n return render_template('index.html'), 200\n\n\n@app.route('/api/v1/innroad/report', methods=['GET'])\ndef get_report():\n date1 = request.args.get('date1')\n date2 = request.args.get('date2')\n old_date1 = request.args.get('oldDate1')\n old_date2 = request.args.get('oldDate2')\n try:\n return render_template_string(ReportManager(date1, date2, old_date1, old_date2).get_report()), 200\n except ReportException as e:\n return e.to_json(), 500\n\n\n@app.route('/api/v1/innroad/report/excel', methods=['GET'])\ndef download_excel_report():\n date1 = request.args.get('date1')\n date2 = request.args.get('date2')\n old_date1 = request.args.get('oldDate1')\n old_date2 = request.args.get('oldDate2')\n try:\n return ReportManager(date1, date2, old_date1, old_date2).excel_report()\n except ReportException as e:\n return e.to_json(), 500\n\n\n@app.route('/api/v1/innroad/report/pdf', methods=['GET'])\ndef download_pdf_report():\n date1 = request.args.get('date1')\n date2 = request.args.get('date2')\n old_date1 = request.args.get('oldDate1')\n old_date2 = request.args.get('oldDate2')\n try:\n return ReportManager(date1, date2, old_date1, old_date2).pdf_report(), 200\n except ReportException as e:\n return e.to_json(), 500\n\n\n@app.route('/pdf')\ndef pdf():\n import io\n output = io.BytesIO()\n\n p = canvas.Canvas(output)\n p.drawString(100, 100, 'Hello')\n p.showPage()\n p.save()\n\n pdf_out = output.getvalue()\n output.close()\n\n response = make_response(pdf_out)\n response.headers['Content-Disposition'] = \"attachment; filename='sakulaci.pdf\"\n response.mimetype = 'application/pdf'\n return response\n\napi = Api(app)\n\nclass HelloWorld(Resource):\n def get(self):\n return {\"Hello\":\"Wold\"}\n\napi.add_resource(HelloWorld, '/hello')\n\n\nif __name__ == '__main__':\n app.run(host='0.0.0.0', port='5000')\n","sub_path":"Controllers/report_controller.py","file_name":"report_controller.py","file_ext":"py","file_size_in_byte":2243,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"211167196","text":"import boto3\nfrom app_model import User\nfrom urllib import request\nimport os\nfrom boto3.dynamodb.conditions import Key\n\nproject_dir = os.path.dirname(os.path.abspath(__file__))\nAWS_REGION = \"us-east-2\"\nAWS_ACCESS_KEY = \"AKIATQFHCTPYX2SYCJR5\"\nAWS_ACCESS_SECRET = \"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\"\ndynamodb = boto3.client('dynamodb', aws_access_key_id=AWS_ACCESS_KEY,\n aws_secret_access_key=AWS_ACCESS_SECRET, region_name=AWS_REGION)\ndynamodb_resource = boto3.resource('dynamodb', aws_access_key_id=AWS_ACCESS_KEY,\n aws_secret_access_key=AWS_ACCESS_SECRET, region_name=AWS_REGION)\ns3 = boto3.resource('s3', aws_access_key_id=AWS_ACCESS_KEY,\n aws_secret_access_key=AWS_ACCESS_SECRET)\ns3Client = boto3.client('s3', aws_access_key_id=AWS_ACCESS_KEY,\n aws_secret_access_key=AWS_ACCESS_SECRET)\nBUCKET = \"piyushthaware\"\n\n\ndef get_user_with_email(email):\n table = dynamodb_resource.Table(\"User\")\n user = table.get_item(\n Key={'email': email}\n )\n if \"Item\" in user:\n item = user[\"Item\"]\n user = User()\n user.email = item[\"email\"]\n user.password = item[\"password\"]\n user.username = item[\"username\"]\n return user\n else:\n return None\n\n\ndef get_music_by_title(title):\n table = dynamodb_resource.Table(\"Music1\")\n music = table.get_item(\n Key={\"title\": title}\n )\n if \"Item\" in music:\n return music[\"Item\"]\n else:\n return {}\n\n\ndef get_music_list():\n table = dynamodb_resource.Table(\"Music1\")\n music = table.scan()\n if \"Items\" in music:\n return music[\"Items\"]\n else:\n return []\n\n\ndef put_user_to_db(email=None, username=None, password=None, item_dict=None):\n table = dynamodb_resource.Table('User')\n item = item_dict if item_dict else {\n 'email': email,\n 'password': password,\n 'username': username\n }\n response = table.put_item(Item=item)\n\n\ndef put_music(item):\n table = dynamodb_resource.Table(\"Music1\")\n table.put_item(Item=item)\n\n\ndef put_subscription(item):\n table = dynamodb_resource.Table(\"user_subscription\")\n table.put_item(Item=item)\n\n\ndef get_user_subscriptions(user_email: str):\n table = dynamodb_resource.Table(\"user_subscription\")\n subscriptions = table.scan()\n if \"Items\" in subscriptions:\n subscriptions = subscriptions[\"Items\"]\n subscriptions = [subscription for subscription in subscriptions if\n subscription[\"user\"].lower() == user_email.lower()]\n return subscriptions\n else:\n return []\n\n\ndef delete_subscription(id):\n table = dynamodb_resource.Table(\"user_subscription\")\n try:\n table.delete_item(\n Key={\"id\": id}\n )\n return True\n except:\n return False\n\n\ndef create_table(table_name):\n dynamodb.create_table(\n TableName=table_name,\n KeySchema=[\n {\n 'AttributeName': 'title',\n 'KeyType': 'HASH' # Partition key\n }\n ],\n\n AttributeDefinitions=[\n {\n 'AttributeName': 'title',\n 'AttributeType': 'S'\n },\n ],\n ProvisionedThroughput={\n 'ReadCapacityUnits': 10,\n 'WriteCapacityUnits': 10\n }\n )\n\n\ndef upload_to_s3(url):\n try:\n key = url.split('/')[::-1][0] # In my situation, ids at the end are unique\n file_path = \"{}/images/{}\".format(project_dir, key)\n file_object = request.urlretrieve(url, file_path) # 'Like' a file object\n print(file_object, key)\n s3Client.put_object(Body=open(file_path, 'rb'), Bucket=BUCKET, Key=key)\n return \"Success\"\n except:\n pass\n","sub_path":"aws_proj/aws.py","file_name":"aws.py","file_ext":"py","file_size_in_byte":3803,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"568307584","text":"#!/usr/bin/env python\n\"\"\"\nUse an aggregation query to answer the following question.\n\nWhat are the list of distinct postal codes and count against them in our philly collection.\n\n\nThe 'make_pipeline' function creates and returns an aggregation pipeline\nthat can be passed to the MongoDB aggregate function. \nThe aggregation pipeline should be a list of one or more dictionary objects.\nOur code will be run against a MongoDB instance on the local machine.\n\n\"\"\"\n\ndef get_db(db_name):\n from pymongo import MongoClient\n client = MongoClient('localhost:27017')\n db = client[db_name]\n return db\n\ndef make_pipeline():\n # complete the aggregation pipeline\n pipeline = [{\"$match\" : {\"address.postcode\" : {\"$exists\" : 1}}},\n {\"$group\" : {\"_id\" : \"$address.postcode\",\n \"count\" : {\"$sum\" : 1}}},\n {\"$sort\" : {\"count\" : -1}},\n {\"$limit\" : 100}]\n return pipeline\n\ndef aggregate(db, pipeline):\n result = db.philly.aggregate(pipeline)\n return result\n\nif __name__ == '__main__':\n # The following statements will be used to test our code.\n \n db = get_db('philly')\n pipeline = make_pipeline()\n result = aggregate(db, pipeline)\n import pprint\n for doc in result:\n pprint.pprint(doc)\n","sub_path":"Philadelphia-dataset_postal_codes.py","file_name":"Philadelphia-dataset_postal_codes.py","file_ext":"py","file_size_in_byte":1294,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"547582408","text":"import os\n\nBASE_DIR = os.path.abspath(os.path.dirname(__file__))\n\n\n# Database connections\nSQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(BASE_DIR, 'crunch.db')\nSQLALCHEMY_MIGRATE_REPO = os.path.join(BASE_DIR, 'db_repository')\n\n\n# Application threads\nTHREADS_PER_PAGE = 2\n\n\n# Enable protection agains *Cross-site Request Forgery (CSRF)*\nWTF_CSRF_ENABLED = True\n\n# Use a secure, unique and absolutely secret key for\n# signing the data.\nCSRF_SESSION_KEY = \"beastMode\"\n\n\n# Secret key for signing cookies\nSECRET_KEY = 'beastMode'","sub_path":"backup/tournament/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":531,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"111553906","text":"import os\nimport sys\nfrom threading import Thread\n\nfrom db.dbWrapperBase import DbWrapperBase\nfrom db.DbFactory import DbFactory\nfrom utils.MappingManager import MappingManagerManager, MappingManager\nfrom utils.logging import initLogging, logger\nfrom utils.version import MADVersion\nfrom utils.walkerArgs import parseArgs\nfrom websocket.WebsocketServer import WebsocketServer\nfrom utils.updater import deviceUpdater\n\nargs = parseArgs()\nos.environ['LANGUAGE'] = args.language\ninitLogging(args)\n\n\ndef generate_mappingjson():\n import json\n newfile = {}\n newfile['areas'] = []\n newfile['auth'] = []\n newfile['devices'] = []\n newfile['walker'] = []\n newfile['devicesettings'] = []\n with open(args.mappings, 'w') as outfile:\n json.dump(newfile, outfile, indent=4, sort_keys=True)\n\n\ndef create_folder(folder):\n if not os.path.exists(folder):\n logger.info(str(folder) + ' created')\n os.makedirs(folder)\n\n\ndef start_madmin(args, db_wrapper: DbWrapperBase, ws_server, mapping_manager: MappingManager, deviceUpdater, jobstatus):\n from madmin.madmin import madmin_start\n madmin_start(args, db_wrapper, ws_server, mapping_manager, deviceUpdater, jobstatus)\n\n\nif __name__ == \"__main__\":\n logger.info('Start MAD configmode - pls wait')\n filename = os.path.join('configs', 'config.ini')\n if not os.path.exists(filename):\n logger.error(\n 'config.ini file not found - check configs folder and copy .example')\n sys.exit(1)\n\n filename = args.mappings\n if not os.path.exists(filename):\n generate_mappingjson()\n\n create_folder(args.file_path)\n create_folder(args.upload_path)\n\n db_wrapper, db_wrapper_manager = DbFactory.get_wrapper(args)\n\n db_wrapper.check_and_create_spawn_tables()\n db_wrapper.create_quest_database_if_not_exists()\n db_wrapper.create_status_database_if_not_exists()\n db_wrapper.create_usage_database_if_not_exists()\n db_wrapper.create_statistics_databases_if_not_exists()\n version = MADVersion(args, db_wrapper)\n version.get_version()\n\n MappingManagerManager.register('MappingManager', MappingManager)\n mapping_manager_manager = MappingManagerManager()\n mapping_manager_manager.start()\n mapping_manager_stop_event = mapping_manager_manager.Event()\n mapping_manager: MappingManager = mapping_manager_manager.MappingManager(db_wrapper, args, True)\n\n ws_server = WebsocketServer(args, None, db_wrapper, mapping_manager, None, True)\n t_ws = Thread(name='scanner', target=ws_server.start_server)\n t_ws.daemon = False\n t_ws.start()\n\n jobstatus: dict = {}\n\n device_Updater = deviceUpdater(ws_server, args, jobstatus)\n\n logger.success(\n 'Starting MADmin on port {} - open browser and click \"Mapping Editor\"', int(args.madmin_port))\n t_flask = Thread(name='madmin', target=start_madmin,\n args=(args, db_wrapper, ws_server, mapping_manager, device_Updater, jobstatus))\n t_flask.daemon = False\n t_flask.start()\n","sub_path":"configmode.py","file_name":"configmode.py","file_ext":"py","file_size_in_byte":3000,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"374518351","text":"# /Users/cpnota/repos/autonomous-learning-library/all/approximation/value/action/torch.py\nimport torch\nfrom torch.optim import RMSprop\nfrom all.agents import VAC\nfrom all.approximation import VNetwork, FeatureNetwork\nfrom all.logging import DummyWriter\nfrom all.policies import SoftmaxPolicy\nfrom .models import fc_relu_features, fc_policy_head, fc_value_head\n\n\ndef vac(\n discount_factor=0.99,\n lr_v=5e-3,\n lr_pi=1e-3,\n alpha=0.99, # RMSprop momentum decay\n eps=1e-5, # RMSprop stability\n device=torch.device('cpu')\n):\n def _vac(env, writer=DummyWriter()):\n value_model = fc_value_head().to(device)\n policy_model = fc_policy_head(env).to(device)\n feature_model = fc_relu_features(env).to(device)\n\n value_optimizer = RMSprop(value_model.parameters(), lr=lr_v, alpha=alpha, eps=eps)\n policy_optimizer = RMSprop(policy_model.parameters(), lr=lr_pi, alpha=alpha, eps=eps)\n feature_optimizer = RMSprop(feature_model.parameters(), lr=lr_pi, alpha=alpha, eps=eps)\n\n v = VNetwork(value_model, value_optimizer, writer=writer)\n policy = SoftmaxPolicy(policy_model, policy_optimizer, env.action_space.n, writer=writer)\n features = FeatureNetwork(feature_model, feature_optimizer)\n\n return VAC(features, v, policy, gamma=discount_factor)\n return _vac\n","sub_path":"all/presets/classic_control/vac.py","file_name":"vac.py","file_ext":"py","file_size_in_byte":1359,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"591530672","text":"## The solution of exercise 1.11\n## A function f is defined by the rule that f(n) = n if n < 3 and f(n) =\n## f(n - 1) + 2 * f(n - 2) + 3 * f(n - 3) if n >= 3. Write a procedure\n## that computes f by means of a recursive process. Write a procedure that\n## computes f by means of an iterative process\n##\n\ndef rec_f(n):\n \"\"\"Recursive process\"\"\"\n if n <= 3:\n return n\n else:\n return (rec_f(n - 1) + \\\n rec_f(n - 2) * 2 + \\\n rec_f(n - 3) * 3)\n\ndef itr_f(n):\n \"\"\"Iterative process\"\"\"\n if n <= 3:\n return n\n a, b, c = 1, 2, 3\n while n > 3:\n a, b, c, n = b, c, a * 3 + b * 2 + c, n - 1\n return c\n\n# The iterative process and the recursive process return the same result\n# in case the input parameter is integer. In other word, they return\n# different results when the input parameter @n is not an integer.\n\n\n","sub_path":"chapter_01/python/sicpc1e11.py","file_name":"sicpc1e11.py","file_ext":"py","file_size_in_byte":882,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"205348556","text":"\"\"\"Writes preferred flows to a JSON-LD archive in the output folder.\"\"\"\nimport pandas as pd\n\nimport fedelemflowlist\nfrom fedelemflowlist.globals import outputpath, flow_list_specs\n\n\nif __name__ == '__main__':\n\n all_flows = fedelemflowlist.get_flows(preferred_only=False)\n ver = flow_list_specs['list_version']\n file = f\"{outputpath}/FedElemFlowList_{ver}\"\n fedelemflowlist.write_jsonld(all_flows, f\"{file}_all.zip\")\n with pd.ExcelWriter(f\"{file}_all.xlsx\",\n # engine='xlsxwriter',\n # engine_kwargs={\n # 'options': {'strings_to_urls': False}}\n ) as writer:\n all_flows.to_excel(writer, index=False)\n","sub_path":"scripts/write_all_flows.py","file_name":"write_all_flows.py","file_ext":"py","file_size_in_byte":730,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"70235829","text":"import json\nimport random\nimport string\nimport hashlib\nimport time\n\nfrom Miner import Miner\nfrom Block import Block\nfrom MyThread import MyThread\n\nfrom threading import Thread\nfrom decimal import Decimal\n\nclass BlockChain(object):\n def __init__(self, hash_num):\n self.chain_list = []\n\n self.miner_list = []\n\n for i in range(6):\n self.miner_list.append(Miner)\n\n self.result_list = []\n\n self.gen_block(hash_num)\n\n @property\n def get_last_block(self):\n if len(self.chain_list):\n return self.chain_list[-1]\n return None\n\n def get_trans(self):\n dict_data = {'sender':''.join(random.sample(string.ascii_letters + string.digits, 8)),\n 'recipient':''.join(random.sample(string.ascii_letters + string.digits, 8)),\n 'amount':random.randrange(1, 10000)}\n return json.dumps(dict_data)\n\n def gen_block(self, initial_hash=None):\n if initial_hash:\n block = Block()\n block.index = 0\n block.nonce = random.randrange(0, 99999)\n block.previous_hash = '0'\n block.difficulty = 0\n block.transaction_data = self.get_trans()\n\n guess = str(block.index) + str(block.nonce) + block.previous_hash\n block.hash = hashlib.sha256(guess.encode()).hexdigest()\n\n block.timestamp = time.time()\n\n self.chain_list.append(block)\n else:\n for miner in self.miner_list:\n t = MyThread(target=miner.mine, args=(miner,len(self.chain_list),self.get_last_block.get_block_info()['Hash'],\n self.get_trans()))\n t.start()\n t.join()\n\n self.result_list.append(t.get_result())\n\n print('All blocks generated by miner:')\n\n for result in self.result_list:\n print(result[0].get_block_info())\n\n first_block = self.result_list[0][0]\n min_time = Decimal(self.result_list[0][1])\n\n for i in range(1, len(self.result_list)):\n if Decimal(self.result_list[i][1]) < min_time:\n first_block = self.result_list[i][0]\n\n self.chain_list.append(first_block)\n self.result_list=[]\n\n\n def show_chain(self):\n for block in self.chain_list:\n print(block.get_block_info())\n\n\n\n","sub_path":"BlockChain.py","file_name":"BlockChain.py","file_ext":"py","file_size_in_byte":2439,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"321135690","text":"import time\nimport pygame\nimport unittest\nimport gym_maze.envs.maze_view_2d as m2d\n\n# Test the musicfiles class\nclass TestGridUtilities(unittest.TestCase):\n def setUp(self):\n self.init_pos = (4, 3)\n self.maze = m2d.MazeView2D(screen_size=(500, 500), maze_size=(6, 7), \n res_path='/media/i/home/arnold/development/python/machine_learning/gym/gym-maze', \n n_mushrooms=0, n_cactuses=0, n_rocks=0,\n init_pos=self.init_pos)\n \n self.maze.update()\n \n return\n \n def teardown(self):\n pygame.quit()\n \n return\n \n def test_insert_thing(self):\n # Test vwhether insert_thing inserts a thing at the expected location\n pos = (2, 2)\n thing = self.maze.maze.insert_thing(m2d.Mushroom, pos)\n loc = thing.location\n exp_loc = pos\n self.assertEqual(loc, exp_loc, 'Incorrect location')\n \n # Test whether thing_by_id contains the inserted vehicle\n thing_id = thing.id\n inserted_thing = self.maze.maze.things_by_id[thing_id]\n self.assertEqual(thing, inserted_thing, 'Incorrect references: thing and inserted_thing')\n \n # Test whether thing is inserted in maze\n thing_type = thing.category\n idx = self.maze.maze.maze_cells[loc]\n self.assertEqual(idx, thing_type, 'thing_if not correctly inserted in maze_cells')\n \n return\n \n def test_find_by_loc(self):\n # Test the find_thing_by_loc function\n pos = (2, 2)\n thing = self.maze.maze.insert_thing(m2d.Mushroom, pos)\n loc = thing.location\n found_thing = self.maze.maze.find_thing_by_loc(loc)\n self.assertEqual(thing, found_thing, 'Incorrect location')\n \n return\n \n def test_move_over_field(self):\n #cols, rows = self.maze.maze.maze_size\n #print(self.maze.maze.print_maze())\n\n direction = \"W\"\n robot = self.maze.robot\n start_energy = robot.energy\n self.maze.robot.move(self.maze.maze, direction)\n exp_loc = (self.init_pos[0] + m2d.COMPASS[direction][0], self.init_pos[1] + m2d.COMPASS[direction][1])\n loc = robot.location\n cost, _ = robot.cost(self.maze.maze, direction)\n thing_energy = m2d.COST['Field']\n exp_energy = start_energy + thing_energy\n energy = robot.energy\n \n self.assertEqual(loc, exp_loc, 'Incorrect location')\n self.assertEqual(energy, exp_energy, 'Incorrect energy')\n \n return\n\n def test_move_against_wall(self):\n direction = \"E\"\n robot = self.maze.robot\n start_energy = robot.energy\n self.maze.robot.move(self.maze.maze, direction)\n exp_loc = self.init_pos\n loc = robot.location\n cost, _ = robot.cost(self.maze.maze, direction)\n thing_energy = m2d.COST['Wall']\n exp_energy = start_energy + thing_energy\n energy = robot.energy\n \n self.assertEqual(loc, exp_loc, 'Incorrect location')\n self.assertEqual(energy, exp_energy, 'Incorrect energy')\n \n return\n\n def test_move_over_mushroom(self):\n direction = \"W\"\n thing = self.maze.maze.insert_thing(m2d.Mushroom, (3, 3))\n \n robot = self.maze.robot\n start_energy = robot.energy\n self.maze.robot.move(self.maze.maze, direction)\n exp_loc = self.init_pos\n loc = robot.location\n thing_energy = thing.energy\n exp_energy = start_energy + thing_energy\n energy = robot.energy\n \n self.assertEqual(loc, exp_loc, 'Incorrect location')\n self.assertEqual(energy, exp_energy, 'Incorrect energy')\n \n return\n \n def test_move_over_cactus(self):\n direction = \"W\"\n thing = self.maze.maze.insert_thing(m2d.Cactus, (3, 3))\n\n robot = self.maze.robot\n start_energy = robot.energy\n self.maze.robot.move(self.maze.maze, direction)\n exp_loc = self.init_pos\n loc = robot.location\n thing_energy = thing.energy\n exp_energy = start_energy + thing_energy\n energy = robot.energy\n \n #print(loc, exp_loc)\n #print(energy, exp_energy, thing_energy)\n self.assertEqual(loc, exp_loc, 'Incorrect location')\n self.assertEqual(energy, exp_energy, 'Incorrect energy')\n \n return\n\n def test_move_rock(self):\n direction = \"W\"\n thing1 = self.maze.maze.insert_thing(m2d.Rock, (3, 3))\n thing2 = self.maze.maze.insert_thing(m2d.Rock, (2, 3))\n thing3 = self.maze.maze.insert_thing(m2d.Rock, (1, 3))\n\n robot = self.maze.robot\n start_energy = robot.energy\n self.maze.robot.move(self.maze.maze, direction)\n exp_loc = self.init_pos#(self.init_pos[0] + m2d.COMPASS[direction][0], self.init_pos[1] + m2d.COMPASS[direction][1])\n loc = robot.location\n thing_energy = thing1.energy + thing2.energy + thing3.energy\n exp_energy = start_energy + thing_energy\n energy = robot.energy\n \n #print(loc, exp_loc)\n #print(energy, exp_energy, thing_energy)\n self.assertEqual(loc, exp_loc, 'Incorrect location')\n self.assertEqual(energy, exp_energy, 'Incorrect energy')\n \n return\n \nif __name__ == '__main__':\n unittest.main()\n","sub_path":"gym-grid2D/tests/unit-test.py","file_name":"unit-test.py","file_ext":"py","file_size_in_byte":5386,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"553933062","text":"from flask_restful import Resource, reqparse\n\nfrom models.user import UserModel\nfrom models.ticket import TicketModel\n\n\nclass User(Resource):\n parser = reqparse.RequestParser()\n parser.add_argument('name',\n type=str,\n required=False,\n help=\"This field cannot be blank!\"\n )\n\n def get(self, id, is_customer):\n user = UserModel.find_by_id(id, is_customer)\n\n if user:\n return user.json(), 200\n return {'message': 'User not found.'}, 404\n\n def patch(self, id, is_customer):\n user = UserModel.find_by_id(id, is_customer)\n\n if user:\n data = User.parser.parse_args()\n user.name = data['name']\n\n try:\n user.update_to_db()\n except IntegrityError:\n return {\"message\":\n \"An error occurred inserting the item.\"}, 500\n\n return user.json(), 201\n\n return {'message': 'User not found'}, 404\n\n def delete(self, id, is_customer):\n user = UserModel.find_by_id(id, is_customer)\n\n if user:\n user.delete_from_db()\n\n return {\"message\": \"User deleted\"}\n\n\nclass UserTickets(Resource):\n\n def get(self, id, is_customer):\n # Returns tickets that the employee/customer is assigned to\n user = UserModel.find_by_id(id, is_customer)\n\n if user:\n return {\"tickets\": [ticket.json() for ticket\n in TicketModel.find_by_email(user.email, is_customer)]}\n return {\"message\": \"User not found\"}\n\n\nclass UserEmail(Resource):\n\n def get(self, email, is_customer):\n # Returns employee/customer that matches this email address\n user = UserModel.find_by_email(email, is_customer)\n\n if user:\n return user.json(), 200\n\n return {'message': 'User not found'}, 404\n\n\nclass UserCreator(Resource):\n parser = reqparse.RequestParser()\n parser.add_argument('email',\n type=str,\n required=False,\n help=\"This field cannot be blank!\"\n )\n parser.add_argument('name',\n type=str,\n required=False,\n help=\"This field cannot be blank!\"\n )\n\n def post(self, is_customer):\n # Creates new employee/customer if one with that email does not exist.\n data = UserCreator.parser.parse_args()\n\n user = UserModel.find_by_email(data['email'], is_customer)\n\n if user:\n return {\"message\": \"User already exists\"}, 404\n\n user = UserModel(data['email'], data['name'], is_customer=is_customer)\n\n try:\n user.add_to_db()\n except IntegrityError:\n return {\"message\": \"An error occurred inserting the item.\"}, 500\n\n return user.json(), 201\n","sub_path":"resources/user.py","file_name":"user.py","file_ext":"py","file_size_in_byte":2935,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"475457885","text":"import numpy as np\nimport torch\nimport sys\n\nsys.path.append('../../')\nimport popsan_drl.popsan_sac.core_cuda as core\n\n\nclass ReplayBuffer:\n \"\"\"\n A simple FIFO experience replay buffer for DDPG agents.\n\n with Running Mean and Var from hill-a/stable-baselines\n \"\"\"\n\n def __init__(self, obs_dim, act_dim, size, clip_limit, norm_update_every=1000):\n \"\"\"\n :param obs_dim: observation dimension\n :param act_dim: action dimension\n :param size: buffer sizes\n :param clip_limit: limit for clip value\n :param norm_update_every: update freq\n \"\"\"\n self.obs_buf = np.zeros(core.combined_shape(size, obs_dim), dtype=np.float32)\n self.obs2_buf = np.zeros(core.combined_shape(size, obs_dim), dtype=np.float32)\n self.act_buf = np.zeros(core.combined_shape(size, act_dim), dtype=np.float32)\n self.rew_buf = np.zeros(size, dtype=np.float32)\n self.done_buf = np.zeros(size, dtype=np.float32)\n self.ptr, self.size, self.max_size = 0, 0, size\n # Running z-score normalization parameters\n self.clip_limit = clip_limit\n self.norm_update_every = norm_update_every\n self.norm_update_batch = np.zeros(core.combined_shape(norm_update_every, obs_dim), dtype=np.float32)\n self.norm_update_count = 0\n self.norm_total_count = np.finfo(np.float32).eps.item()\n self.mean, self.var = np.zeros(obs_dim, dtype=np.float32), np.ones(obs_dim, dtype=np.float32)\n\n def store(self, obs, act, rew, next_obs, done):\n \"\"\"\n Insert entry into memory\n :param obs: observation\n :param act: action\n :param rew: reward\n :param next_obs: observation after action\n :param done: if true then episode done\n \"\"\"\n self.obs_buf[self.ptr] = obs\n self.obs2_buf[self.ptr] = next_obs\n self.act_buf[self.ptr] = act\n self.rew_buf[self.ptr] = rew\n self.done_buf[self.ptr] = done\n self.ptr = (self.ptr + 1) % self.max_size\n self.size = min(self.size + 1, self.max_size)\n # Update Mean and Variance\n # Have to at least update mean and variance once before training starts\n self.norm_update_batch[self.norm_update_count] = obs\n self.norm_update_count += 1\n if self.norm_update_count == self.norm_update_every:\n self.norm_update_count = 0\n batch_mean, batch_var = self.norm_update_batch.mean(axis=0), self.norm_update_batch.var(axis=0)\n tmp_total_count = self.norm_total_count + self.norm_update_every\n delta_mean = batch_mean - self.mean\n self.mean += delta_mean * (self.norm_update_every / tmp_total_count)\n m_a = self.var * self.norm_total_count\n m_b = batch_var * self.norm_update_every\n m_2 = m_a + m_b + np.square(delta_mean) * self.norm_total_count * self.norm_update_every / tmp_total_count\n self.var = m_2 / tmp_total_count\n self.norm_total_count = tmp_total_count\n\n def sample_batch(self, device, batch_size=32):\n \"\"\"\n Sample batch from memory\n :param device: pytorch device\n :param batch_size: batch size\n :return: batch\n \"\"\"\n idxs = np.random.randint(0, self.size, size=batch_size)\n batch = dict(obs=self.normalize_obs(self.obs_buf[idxs]),\n obs2=self.normalize_obs(self.obs2_buf[idxs]),\n act=self.act_buf[idxs],\n rew=self.rew_buf[idxs],\n done=self.done_buf[idxs])\n return {k: torch.as_tensor(v, dtype=torch.float32, device=device) for k, v in batch.items()}\n\n def normalize_obs(self, obs):\n \"\"\"\n Do z-score normalization on observation\n :param obs: observation\n :return: norm_obs\n \"\"\"\n eps = np.finfo(np.float32).eps.item()\n norm_obs = np.clip((obs - self.mean) / np.sqrt(self.var + eps),\n -self.clip_limit, self.clip_limit)\n return norm_obs\n","sub_path":"popsan_drl/popsan_sac/replay_buffer_norm.py","file_name":"replay_buffer_norm.py","file_ext":"py","file_size_in_byte":4023,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"558731454","text":"from django.urls import path\nfrom . import views\n\nurlpatterns = [\n\n\tpath('', views.index),\n\n\tpath('categories/', views.category, name=\"categories\"),\n\n\tpath('search//', views.search, name=\"search\"),\n\n path('module//', views.moduledetails, name=\"moduledetails\"),\n\n\n]","sub_path":"educat/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":286,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"383446217","text":"# -*- coding:utf-8 -*-\n\nimport cv2\nimport os\n\n\ndef on_trace_bar_changed(args):\n pass\n\n\npath = './segment_data/'\nfile_name = os.listdir(path)\nfor file_ in file_name:\n if '.bmp' in file_:\n img = cv2.imread(path+file_)\n cv2.namedWindow(\"real\")\n cv2.imshow(\"real\", img)\n cv2.namedWindow(\"Image\")\n blurred = cv2.GaussianBlur(img, (5, 5), 0)\n\n cv2.createTrackbar('thres', 'Image', 0, 255, on_trace_bar_changed)\n # 测试之后为68\n while True:\n cv2.imshow(\"Image\", img)\n thresh = cv2.getTrackbarPos('thres', 'Image')\n img = cv2.threshold(blurred, thresh, 255, cv2.THRESH_BINARY_INV)[1]\n # 键盘检测函数,0xFF是因为64位机器\n # https: // stackoverflow.com / questions / 20539497 / opencv - python - waitkey d- dont - respond\n k = cv2.waitKey(1) & 0xFF\n # print k\n if k == ord('q'):\n break\n\n print(thresh)\n cv2.destroyAllWindows()\n","sub_path":"实验/拟合反向求解/test_threshold.py","file_name":"test_threshold.py","file_ext":"py","file_size_in_byte":1014,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"225605605","text":"from django.shortcuts import render, render_to_response, HttpResponseRedirect, HttpResponse\nfrom .models import *\nfrom .forms import *\nfrom django.core.mail import send_mail\nfrom django.db import connection\n# Create your views here.\n\n\ndef index(request):\n args = {}\n return render(request, 'chessApp/index.html', args)\n\ndef add(request):\n return render(request, 'chessApp/addPlayer.html.html')\n\n\ndef addCompetition(request):\n count = None\n # form = None\n if request.method == 'POST':\n form = CountPlayerForm(request.POST)\n\n if form.is_valid():\n count = form.cleaned_data['count']\n return HttpResponseRedirect('/add/')\n\n else:\n form = CountPlayerForm()\n\n return render(request, 'chessApp/addCompetition.html', {'form': form, 'count': count})\n\n\ndef addPlayer(request):\n args = {}\n if request.method == 'POST':\n form = PlayerForm(request.POST)\n\n if form.is_valid():\n name = form.cleaned_data['name']\n l = []\n l.append(name)\n new_player = form.save()\n return HttpResponse('save {0}'.format(l))\n else:\n form = PlayerForm()\n\n return render(request, 'chessApp/index.html', {'form': form})\n\n\ndef addTable(request):\n args = {}\n cursor = connection.cursor()\n cursor.execute('SELECT COUNT(*) FROM players')\n row = cursor.fetchone()\n # args['count'] = Player.objects.raw('SELECT COUNT(*) FROM players')\n # args['count'].\n x = row[0]/2\n args['count'] = x\n r = round(x)\n args['r'] = r\n # args['tupe'] =\n for i in range(0, r):\n cursor.execute(\"INSERT INTO tables VALUES (%s,%s,1)\", [i, i])\n return render_to_response('chessApp/addCompetition.html', args)","sub_path":"chessApp/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1749,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"393649857","text":"from learn_codes.Unit_Testing.Test_Two.Employee import Empl\nimport unittest\n\n\nclass TestEmployee(unittest.TestCase):\n\n def test_email(self):\n\n emp1 = Empl(\"Krishna\", \"Singh\", 1500000)\n emp2 = Empl(\"Hari\", \"Om\", 16849165198)\n\n self.assertEqual(emp1.email, \"Krishna.Singh@gmail.com\")\n self.assertEqual(emp2.email, \"Hari.Om@gmail.com\")\n\n emp1.first = \"KrishnaChange\"\n emp2.first = \"HariChange\"\n\n self.assertEqual(emp1.email, \"KrishnaChange.Singh@gmail.com\")\n self.assertEqual(emp2.email, \"HariChange.Om@gmail.com\")\n\n def test_fullname(self):\n\n emp1 = Empl(\"Krishna\", \"Singh\", 1500000)\n emp2 = Empl(\"Hari\", \"Om\", 16849165198)\n\n self.assertEqual(emp1.fullname, \"Krishna Singh\")\n self.assertEqual(emp2.fullname, \"Hari Om\")\n\n","sub_path":"learn_codes/Unit_Testing/Test_Two/unit_test_two.py","file_name":"unit_test_two.py","file_ext":"py","file_size_in_byte":808,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"161704409","text":"from os import listdir\nfrom chatterbot import ChatBot\nfrom chatterbot.trainers import ListTrainer\n\n\nbot = ChatBot('DazOS Bot')\nbot.set_trainer(ListTrainer)\n\nfor files in listdir('/home/daniel/projetos/python3/dazos/chatterbot_corpus/data/portuguese/'):\n data = open('/home/daniel/projetos/python3/dazos/chatterbot_corpus/data/portuguese/' + files, 'r').readlines()\n bot.train(data)\n\nwhile True:\n mensagem = input('Você: ')\n if mensagem.strip() != 'tchau':\n resposta = bot.get_response(mensagem)\n print('DazOS Bot: ', resposta)\n if mensagem.strip() == 'tchau':\n print('DazOS Bot: Tchau! :)')\n break\n","sub_path":"dazos_train.py","file_name":"dazos_train.py","file_ext":"py","file_size_in_byte":642,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"102589929","text":"from sign.models import Event,Guest\nfrom django.http import JsonResponse\nfrom django.core.exceptions import ValidationError,ObjectDoesNotExist\nimport time\n\ndef add_event(request):\n\teid=request.POST.get('eid','')\n\tname=request.POST.get('name','')\n\tlim=request.POST.get('lim','')\n\tstatus=request.POST.get('status','')\n\taddress=request.POST.get('address','')\n\tstart_time=request.POST.get('start_time','')\n\tcreate_time=request.POST.get('create_time','')\n\n\tif eid=='' or name=='' or lim=='' or address=='' or start_time=='':\n\t\treturn JsonResponse({'status':10021,'message':'parameter error'})\n\n\tresult=Event.objects.filter(id=eid)\n\tif result:\n\t\treturn JsonResponse({'status':10022,'message':'event id already exists'})\n\n\tresult=Event.objects.filter(name=name)\n\tif result:\n\t\treturn JsonResponse({'status':10023,'message':'event name already exists'})\n\n\tif status=='':\n\t\tstatus=1\n\n\ttry:\n\t\tEvent.objects.create(id=eid,name=name,lim=lim,status=int(status),address=address,start_time=start_time,create_time=create_time)\n\texcept ValidationError as e:\n\t\terror='start_time format error.It must be in YYYY-MM-DD HH:MM:SS format'\n\t\treturn JsonResponse({'status':10024,'message':'start_time format error'})\n\n\treturn JsonResponse({'status':200,'message':'add event success'})\n\ndef get_event_list(request):\n\teid=request.GET.get('eid','')\n\tname=request.GET.get('name','')\n\n\tif eid=='' and name=='':\n\t\treturn JsonResponse({'status':10021,'message':'Please attach what you want to get'})\n\n\telse:\n\t\tif eid !='' and name=='':\n\t\t\tevent={}\n\t\t\ttry:\n\t\t\t\tresult=Event.objects.get(id=eid)\n\t\t\texcept ObjectDoesNotExist:\n\t\t\t\treturn JsonResponse({'status':10022,'message':'query result id is empty'})\n\t\t\telse:\n\t\t\t\tevent['name']=result.name\n\t\t\t\tevent['lim']=result.lim\n\t\t\t\tevent['address']=result.address\n\t\t\t\tevent['status']=result.status\n\t\t\t\tevent['start_time']=result.start_time\n\t\t\t\tevent['create_time']=result.create_time\t\t\t\t\n\t\t\t\treturn JsonResponse({'status':10023,'message':'success','data':event})\t\n\n\t\telif name != '' and eid=='':\n\t\t\tdatas = []\n\t\t\tresults=Event.objects.filter(name__contains=name)\n\t\t\tif results:\t\t\t\t\n\t\t\t\tfor r in results:\n\t\t\t\t\tevent={}\n\t\t\t\t\tevent['id']=r.id\n\t\t\t\t\tevent['name']=r.name\n\t\t\t\t\tevent['lim']=r.lim\n\t\t\t\t\tevent['address']=r.address\n\t\t\t\t\tevent['status']=r.status\n\t\t\t\t\tevent['start_time']=r.start_time\n\t\t\t\t\tevent['create_time']=r.create_time\n\t\t\t\t\tdatas.append(event)\n\t\t\t\treturn JsonResponse({'status':10024,'message':'success','data':datas})\n\t\t\telse:\n\t\t\t\treturn JsonResponse({'status':10025,'message':'query result by name is empty'})\n\ndef add_guest(request):\n\tgid=request.POST.get('gid','')\n\trealname=request.POST.get('realname','')\n\tphone=request.POST.get('phone','')\n\temail=request.POST.get('email','')\n\tsign=request.POST.get('sign','')\n\tevent_id=request.POST.get('event_id','')\n\tcreate_time=request.POST.get('create_time','')\n\n\tif gid=='' or realname=='' or phone=='' or email=='' or event_id=='' or create_time=='':\n\t\treturn JsonResponse({'status':10021,'message':'parameter error'})\n\n\tresult=Guest.objects.filter(id=gid)\n\tif result:\n\t\treturn JsonResponse({'status':10022,'message':'Guest id already exists.'})\n\n\tresult=Event.objects.get(id=event_id).status\n\tif not result:\n\t\treturn JsonResponse({'status':10025,'message':'Event status is not available.'})\n\n\tresult=Guest.objects.filter(phone=phone)\n\tif result:\n\t\treturn JsonResponse({'status':10023, 'message':'Guest phone already exists.'})\n\n\tevent_limit=Event.objects.get(id=event_id).lim\n\tguest_limit=Guest.objects.filter(event_id=event_id)\n\tif len(guest_limit)>len(event_limit):\n\t\treturn JsonResponse({'status':10026,'message':'event number is full'})\n\n\tif sign=='':\n\t\tsign=1\n\n\tresult=Event.objects.filter(id=event_id)\n\tif not result:\n\t\treturn JsonResponse({'status':10024, 'message':'Event id is not exist.'})\n\telse:\n\t\ttry:\n\t\t\tGuest.objects.create(id=gid,realname=realname,phone=phone,email=email,sign=sign,event_id=event_id,create_time=create_time)\n\t\texcept ValidationError as e:\n\t\t\terror='start_time format error.It must be in YYYY-MM-DD HH:MM:SS format'\n\t\t\treturn JsonResponse({'status':'10024','message':'create_time format error'})\n\n\t\treturn JsonResponse({'status':200,'message':'add event success'})\n\n\ndef get_guest_list(request):\n\tphone=request.GET.get('phone','')\n\tname=request.GET.get('name','')\n\tif phone=='' and name=='':\n\t\treturn JsonResponse({'status':10021,'message':'At least input a parameter.'})\n\n\tif phone!='':\n\t\tguest={}\n\t\ttry:\n\t\t\tresult=Guest.objects.get(phone=phone)\n\t\texcept ObjectDoesNotExist:\n\t\t\treturn JsonResponse({'status':10022,'message':'query result is empty'})\n\t\telse:\n\t\t\tguest['event_id']=result.event_id\n\t\t\tguest['realname']=result.realname\n\t\t\tguest['phone']=result.phone\n\t\t\tguest['email']=result.email\n\t\t\tguest['sign']=result.sign\n\t\t\tguest['create_time']=result.create_time\n\t\t\treturn JsonResponse({'status':10023, 'message':'success','data':guest})\n\tif name!='':\n\t\tdatas=[]\n\t\ttry:\n\t\t\tresults=Guest.objects.filter(realname__contains=name)\n\t\texcept ObjectDoesNotExist:\n\t\t\treturn JsonResponse({'status':10024,'message':'Doesn not have this kind of guest'})\n\t\telse:\n\t\t\tfor g in results:\n\t\t\t\tguest={}\n\t\t\t\tguest['event_id']=g.event_id\n\t\t\t\tguest['realname']=g.realname\n\t\t\t\tguest['phone']=g.phone\n\t\t\t\tguest['email']=g.email\n\t\t\t\tguest['sign']=g.sign\n\t\t\t\tguest['create_time']=g.create_time\n\t\t\t\tdatas.append(guest)\n\t\t\treturn JsonResponse({'status':10025,'message':'success','data':datas})\n\n\ndef user_sign(request):\n\teid=request.GET.get('eid','')\n\tphone=request.GET.get('phone','')\n\tif eid=='' or phone=='':\n\t\treturn JsonResponse({'status':10021,'message':'parameter error'})\n\tresult=Event.objects.filter(id=eid)\n\tif not result:\n\t\treturn JsonResponse({'status':10022,'message':'Event does NOT exist.'})\n\n\tresult=Event.objects.get(id=eid).status\n\tif not result:\n\t\treturn JsonResponse({'status':10023,'message':'Event is NOT available.'})\n\n\tevent_time=Event.objects.get(id=eid).start_time\n\tetime=str(event_time).split('.')[0]\n\ttimeArray=time.strptime(etime,\"%Y-%m-%d %H:%M:%S\")\n\te_time=int(time.mktime(timeArray))\n\n\tnow_time=str(time.time())\n\tntime=now_time.split('.')[0]\n\tn_time=int(ntime)\n\n\tif n_time>=e_time:\n\t\treturn JsonResponse({'status':10024,'message':'Event has started.'})\n\n\tresult=Guest.objects.get(phone=phone).event_id\n\tif int(result)!= int(eid):\n\t\treturn JsonResponse({'status':10025,'message':\"The guest NOT in the event, unable to sign.\"})\n\n\tresult=Guest.objects.get(phone=phone).sign\n\tif result:\n\t\treturn JsonResponse({'status':10026,'message':\"You have already signed in. Welcome to our party.\"})\n\telse:\n\t\tGuest.objects.filter(phone=phone).update(sign=\"True\")\n\t\treturn JsonResponse({'status':10027,'message':\"Sign in successfully. Welcome!\"})","sub_path":"sign/views_if.py","file_name":"views_if.py","file_ext":"py","file_size_in_byte":6638,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"120520793","text":"# Solution for Separate the Numbers\n\n\ndef is_beautiful(s):\n length = len(s)\n\n for i in range(0, length // 2): # split from n to 2 parts\n first_number_string = s[0:i + 1]\n nr = int(first_number_string)\n nr_string = str(nr)\n\n while len(nr_string) < length:\n nr += 1\n nr_string += str(nr)\n\n if nr_string == s:\n return 'YES ' + first_number_string\n\n return 'NO'\n\n\nif __name__ == '__main__':\n nr = int(input())\n\n for _ in range(nr):\n s = input()\n result = is_beautiful(s)\n print(result)\n","sub_path":"Python/Algorithms/Strings/Separate the Numbers.py","file_name":"Separate the Numbers.py","file_ext":"py","file_size_in_byte":587,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"389281372","text":"#! /usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n\"\"\"\nThis is also a script used to test for recycle\n\"\"\"\n\n__author__ = 'Leanna Li'\n\ndef animal():\n pets = ['dog', 'cat', 'pig']\n for pet in pets:\n print(\"A %s would make a great pet.\" % pet)\n print('Any of these animals would make a great pet.')\n\ndef main():\n animal()\n\nif __name__ == '__main__':\n main()\n","sub_path":"4-2.py","file_name":"4-2.py","file_ext":"py","file_size_in_byte":374,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"469309022","text":"from vnpy.trader.utils import optimize\nimport sys\nsys.path.append(\"/Users/apple/Desktop/celve/double\")\nfrom myIfStrategy_3 import myStrategy\nfrom datetime import datetime\nimport numpy as np\nimport os\nimport json\n\ndef setConfig(root=None):\n # 设置策略类\n optimize.strategyClass = myStrategy\n # 设置缓存路径,如果不设置则不会缓存优化结果。\n optimize.root = root\n # 设置引擎参数\n optimize.engineSetting = {\n \"startDate\": \"20160703 10:00:00\",\n \"endDate\": \"20190101 23:59:00\",\n \"dbName\": \"VnTrader_1Min_Db\",\n \"contract\":[{\n \"slippage\": 0.002,\n \"rate\": 5/10000,\n }]\n }\n # 设置策略固定参数\n optimize.globalSetting = {\n \"symbolList\": [\"A88:CTP\"],\n \"barPeriod\": 150,\n }\n # 设置策略优化参数\n optimize.paramsSetting = {\n \"envPeriod\": range(10,25,5),\n \"longenvPeriod\": range(20,35,5),\n \"MIfactor\": np.arange(0.05, 0.2, 0.05),\n \"bullPeriod\": range(15,30,5),\n \"bearPeriod\": (10,15,5),\n\n \"fastPeriod\": range(5,15,5),\n \"slowPeriod\": range(20,35,5),\n\n \"maPeriod\": range(25,35,5)\n\n }\n path = os.path.split(os.path.realpath(\"runOptParallel.py\"))[0]\n with open(path+\"/CTA_setting.json\") as f:\n globalSetting = json.load(f)[0]\n optimize.globalSetting = globalSetting\n optimize.initOpt()\n\n# 并行优化 无缓存\ndef runSimpleParallel():\n start = datetime.now()\n print(\"run simple | start: %s -------------------------------------------\" % start)\n setConfig()\n # optimize.runParallel() 并行优化,返回回测结果\n report = optimize.runParallel()\n print(report)\n report.sort_values(by = 'sharpeRatio', ascending=False, inplace=True)\n # 将结果保存成csv\n report.to_csv('opt_IF88.csv') \n end = datetime.now()\n print(\"run simple | end: %s | expire: %s -----------------------------\" % (end, end-start))\n\ndef main():\n runSimpleParallel()\n\nif __name__ == '__main__':\n main()","sub_path":"double/runOptParallel.py","file_name":"runOptParallel.py","file_ext":"py","file_size_in_byte":2095,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"159592989","text":"from typing import List\nfrom collections import defaultdict\n\n\nclass Solution:\n def findOrder(self, numCourses: int, prerequisites: List[List[int]]) -> List[int]:\n c_to_p = defaultdict(list)\n visited = defaultdict(int)\n order = []\n for c, p in prerequisites:\n c_to_p[c].append(p)\n\n def satisfy_p(c):\n if visited[c] == 1:\n return\n elif visited[c] == -1:\n raise Exception(\"cycle found\")\n visited[c] = -1\n for p in c_to_p[c]:\n satisfy_p(p)\n visited[c] = 1\n order.append(c)\n\n for c in range(numCourses):\n try:\n satisfy_p(c)\n except Exception as e:\n if str(e) == \"cycle found\":\n return []\n raise e\n return order\n\n\nr = Solution().findOrder(2, [[1, 0]])\nprint(r)\n","sub_path":"code/fb-prep/M210-course-schedule-ii.py","file_name":"M210-course-schedule-ii.py","file_ext":"py","file_size_in_byte":915,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"371212639","text":"import os\nimport unittest\nimport json\nfrom flask_sqlalchemy import SQLAlchemy\n\nfrom flaskr import create_app\nfrom models import setup_db, Question, Category\n\n\nclass TriviaTestCase(unittest.TestCase):\n \"\"\"This class represents the trivia test case\"\"\"\n\n def setUp(self):\n \"\"\"Define test variables and initialize app.\"\"\"\n self.app = create_app()\n self.client = self.app.test_client\n self.database_name = \"trivia_test\"\n self.database_path = \"postgres:///{}\".format(self.database_name)\n setup_db(self.app, self.database_path)\n\n self.new_valid_question = {\n 'question': 'This is a question?',\n 'answer': 'Answer to question',\n 'category_id': 4,\n 'difficulty': 2\n }\n\n self.new_invalid_404_question = {\n 'question': 'This is a question?',\n 'answer': 'Answer to question',\n 'category_id': 100,\n 'difficulty': 2\n }\n\n self.new_invalid_400_question = {\n 'question': '',\n 'answer': 'Answer to question',\n 'category_id': 1,\n 'difficulty': 2\n }\n\n # binds the app to the current context\n with self.app.app_context():\n self.db = SQLAlchemy()\n self.db.init_app(self.app)\n # create all tables\n self.db.create_all()\n\n def tearDown(self):\n \"\"\"Executed after reach test\"\"\"\n pass\n\n \"\"\"\n TODO\n Write at least one test for each test for successful operation and for expected errors.\n \"\"\"\n def test_create_new_question(self):\n res = self.client().post('/api/questions', json=self.new_valid_question)\n data = json.loads(res.data)\n self.assertTrue(data['success'])\n self.assertEqual(data['status_code'], 201)\n self.assertTrue(data['question_id'])\n\n\n def test_create_new_question_with_error_404(self):\n res = self.client().post('/api/questions', json=self.new_invalid_404_question)\n data = json.loads(res.data)\n self.assertFalse(data['success'])\n self.assertEqual(data['status_code'], 404)\n self.assertTrue(data['message'])\n\n def test_create_new_question_with_error_400(self):\n res = self.client().post('/api/questions', json=self.new_invalid_400_question)\n data = json.loads(res.data)\n self.assertFalse(data['success'])\n self.assertEqual(data['status_code'], 400)\n self.assertTrue(data['message'])\n\n\n def test_get_question(self):\n res = self.client().get('/api/questions?page=1')\n data = json.loads(res.data)\n self.assertEqual(data['status_code'], 200)\n self.assertTrue(data['success'])\n self.assertTrue(data['total_questions'])\n self.assertEqual(len(data['categories']), 6)\n self.assertTrue(data['questions'])\n\n def test_get_question_with_wrong_query_parameters(self):\n res = self.client().get('/api/questions?wrong=\"wrong\"')\n data = json.loads(res.data)\n self.assertFalse(data['success'])\n self.assertTrue(data['message'])\n self.assertEqual(data['status_code'], 400)\n\n def test_get_all_questions_related_to_specific_category(self):\n res = self.client().get('api/categories/100/questions')\n data = json.loads(res.data)\n self.assertFalse(data['success'])\n self.assertEqual(data['status_code'], 404)\n self.assertTrue(data['message'])\n\n def test_delete_question(self):\n res = self.client().delete('/api/questions/100')\n data = json.loads(res.data)\n self.assertFalse(data['success'])\n self.assertEqual(data['status_code'], 404)\n self.assertTrue(data['message'])\n\n def test_get_random_question(self):\n res = self.client().get('/api/quizzes?category=4')\n data = json.loads(res.data)\n self.assertTrue(data['success'])\n self.assertEqual(data['status_code'], 200)\n self.assertTrue(data['question'])\n\n def test_get_random_question_with_wrong_category(self):\n res = self.client().get('/api/quizzes?category=400')\n data = json.loads(res.data)\n self.assertFalse(data['success'])\n self.assertEqual(data['status_code'], 404)\n self.assertTrue(data['message'])\n\n def test_get_random_question_from_category_that_doesnt_have_questions(self):\n res = self.client().get('/api/quizzes?category=1')\n data = json.loads(res.data)\n self.assertFalse(data['success'])\n self.assertEqual(data['status_code'], 404)\n self.assertTrue(data['message'])\n\n def test_get_random_question_with_prev_question_parameter(self):\n res = self.client().get('/api/quizzes?category=4&prev_question=1')\n data = json.loads(res.data)\n self.assertTrue(data['success'])\n self.assertEqual(data['status_code'], 200)\n self.assertTrue(data['question'])\n\n\n def test_get_random_question_with_wrong_prev_question_parameter(self):\n res = self.client().get('/api/quizzes?category=4&prev_question=1000000')\n data = json.loads(res.data)\n self.assertFalse(data['success'])\n self.assertEqual(data['status_code'], 404)\n self.assertTrue(data['message'])\n\n# Make the tests conveniently executable\nif __name__ == \"__main__\":\n unittest.main()\n","sub_path":"backend/test_flaskr.py","file_name":"test_flaskr.py","file_ext":"py","file_size_in_byte":5325,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"538087868","text":"# Leonardo Altamirano Retto\n# 3 Semestre Software\n\nclass Cola_1:\n def __init__(self,tamanio):\n self.lista=[]\n self.size=tamanio\n self.top=0\n\n def push(self,dato):\n if self.top nrows1-1:\n break\n # data2[j] = np.concatenate((coldata[i], coldata[i+1], coldata[i+2]))\n pp = coldata[i]\n for k in range(1, ncon):\n pp = np.concatenate((pp, coldata[i+k]))\n data2[j] = pp\n j = j + 1\n\n newcol1 = fits.Column(name='ADC', format=coldim1, array=data2)\n t = fits.BinTableHDU.from_columns([newcol1, ])\n t.writeto(outFile)\n","sub_path":"ERESOL/concatrows.py","file_name":"concatrows.py","file_ext":"py","file_size_in_byte":1430,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"42255599","text":"from time import time\nimport os\nfrom math import log, ceil\nimport numpy as np\n\n\nclass LempelZiv():\n def __init__(self, filename, encoding='utf-8'):\n self.file = filename\n self.table = {''.encode(encoding): 0}\n self.encoding = encoding\n\n def compressFile2(self, outputname=None, getDict=None):\n '''\n Here we will compress the file following the next steps:\n 1. Open the file and encode it. We will work on a bytes string.\n 2. We apply thel LZ algorithm on the bytes string:\n a) We initialize the dictionary (self.table) with an empty\n bytearray. We set this as the position 0.\n b) We look, at each iteration, the segment [start:len(bytestring)]\n of the bytestring (we begin with start = 0). If we find a\n subsegment of bytes that is not in self.table, we look for\n the position of its prefix (this is, the bytes of the subsegment\n except the last one) to add, in compressed, the position + the\n last byte (both in binary) of the subsegment. Finally we add this\n subsegment to self.table.\n NOTE: A single character has prefix '', which\n is an empty bytearray whose position is 0 as mentioned before.\n 3. Finally, we look how many positions we found and how many bits\n are needed to write these positions in binary. With this we can set\n the same bit length for each element of compressed.\n 4. We join all elements of comressed in a bitstring, then we convert it\n to bytes to write the compressed file.\n '''\n\n filename, _ = os.path.splitext(self.file)\n if outputname:\n outputFile = outputname\n else:\n outputFile = filename + '.bin'\n\n # with open(self.file, 'r', encoding=self.encoding) as output:\n # text = output.read().encode(self.encoding)\n\n with open(self.file, 'rb') as output:\n text = output.read()\n\n # Here begins the Lempel Ziv algorithm:\n start = 0\n n_data = len(text) + 1\n compressed = []\n # t1 = time()\n while True:\n for i in range(1, n_data - start):\n w = text[start:start + i]\n\n if w not in self.table:\n pos = self.table[w[:-1]]\n codeword = bin(pos)[2:] + bin(w[-1])[2:].zfill(8)\n compressed.append(codeword)\n\n self.table[w] = len(self.table)\n start += i\n break\n\n # If the last characters of the file have appeared before:\n else:\n if start != n_data - 1:\n pos = self.table[w[:-1]]\n compressed.append(bin(pos)[2:] + bin(w[-1])[2:].zfill(8))\n break\n # t2 = time()\n\n # n_bits is the number of bits needed to write in binary the n postions\n n_bits = int(log(len(self.table), 2)) + 1\n\n bitstring = ''.join([bits.zfill(n_bits + 8) for bits in compressed])\n # t3 = time()\n # print(t3 - t2, t2 - t1)\n\n # We add the padding to make len(bitstring) % 8 == 0:\n extraPad = 8 - len(bitstring) % 8 if len(bitstring) % 8 != 0 else 0\n bitstring = bitstring.zfill(len(bitstring) + extraPad)\n\n # We pass the bitstring to bytes to write the file:\n encoded = int(bitstring, 2).to_bytes(\n int(len(bitstring) / 8), 'big')\n\n # We write the file\n with open(outputFile, 'wb') as output:\n # First we write the n_bits to be able to decompress the file.\n output.write(n_bits.to_bytes(ceil(n_bits / 256), 'big'))\n output.write(extraPad.to_bytes(1, 'big'))\n output.write(encoded)\n\n # print(t3 - t2, t2 - t1)\n\n if getDict is True:\n return self.table\n\n def compressFile(self, outputname=None):\n '''\n Alternative compressing method method\n\n '''\n\n filename, _ = os.path.splitext(self.file)\n if outputname:\n outputFile = outputname\n else:\n outputFile = filename + '.bin'\n\n with open(self.file, 'rb') as output:\n text = output.read()\n\n # text = [byte.to_bytes(1, 'big') for byte in bytestring]\n # t1 = time()\n\n compressed = []\n token = b''\n for i in range(len(text)):\n byte = text[i]\n token += byte.to_bytes(1, 'big')\n if token not in self.table:\n pos = self.table[token[:-1]]\n codeword = bin(pos)[2:] + bin(byte)[2:].zfill(8)\n self.table[token] = len(self.table)\n compressed.append(codeword)\n token = b''\n\n # If the last bytes have not been included (and so token is not empty):\n if token:\n pos = self.table[token[:-1]]\n codeword = bin(pos)[2:] + bin(byte)[2:].zfill(8)\n self.table[token] = len(self.table)\n compressed.append(codeword)\n\n # t2 = time()\n # print(t2 - t1)\n n_bits = int(log(len(self.table), 2)) + 1\n\n bitstring = ''.join([bits.zfill(n_bits + 8) for bits in compressed])\n\n # We add the padding to make len(bitstring) % 8 == 0:\n extraPad = 8 - len(bitstring) % 8 if len(bitstring) % 8 != 0 else 0\n bitstring = bitstring.zfill(len(bitstring) + extraPad)\n\n # We pass the bitstring to bytes to write the file:\n encoded = int(bitstring, 2).to_bytes(\n int(len(bitstring) / 8), 'big')\n\n # We write the file\n with open(outputFile, 'wb') as output:\n # First we write the n_bits to be able to decompress the file.\n output.write(n_bits.to_bytes(ceil(n_bits / 256), 'big'))\n output.write(extraPad.to_bytes(1, 'big'))\n output.write(encoded)\n\n def decompressFile(self, outputname=None):\n '''\n Here we will decompress the file:\n 1. Read the n_bits used to write in binary each position.\n 2. Read the extraPad and remove the zeros added to make\n len(bitstring) % 8 = 0.\n 3. Knowing n_bits and knowing that each character is 8 bits\n long, read the encoded file in intervals of n_bits + 8, where\n the first n_bits will be the position (pos) and the next 8 bits\n will be the character (char) that follows that position.\n '''\n\n filename, _ = os.path.splitext(self.file)\n if outputname:\n outputFile = outputname\n else:\n outputFile = filename + '_decompressed.txt'\n\n keys = {0: b''}\n\n with open(self.file, 'rb') as output:\n n_bits = int.from_bytes(output.read(1), 'big')\n extraPad = int.from_bytes(output.read(1), 'big')\n encoded = output.read()\n n_bytes = len(encoded)\n encoded = int.from_bytes(encoded, 'big')\n bitstring = bin(encoded)[2:].zfill(n_bytes * 8)\n bitstring = bitstring[extraPad:]\n\n text = []\n for i in range(0, int(len(bitstring) / (n_bits + 8))):\n pos = bitstring[i * (n_bits + 8): n_bits +\n i * (n_bits + 8)]\n last_char = bitstring[(i + 1) * n_bits +\n i * 8: (i + 1) * (n_bits + 8)]\n\n characters = keys[int(pos, 2)] + \\\n int(last_char, 2).to_bytes(1, 'big')\n\n text.append(characters)\n keys[len(keys)] = characters\n\n with open(outputFile, 'w', encoding=self.encoding,\n newline='\\n') as output:\n text = b''.join(text)\n text = text.decode(self.encoding)\n output.write(text)\n","sub_path":"lempel_ziv_compressor.py","file_name":"lempel_ziv_compressor.py","file_ext":"py","file_size_in_byte":7726,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"292408850","text":"# -*- coding: utf-8 -*-\n##############################################################################\n#\n# OpenERP, Open Source Management Solution\n# Copyright (C) 2004-2010 Tiny SPRL ().\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU Affero General Public License as\n# published by the Free Software Foundation, either version 3 of the\n# License, or (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU Affero General Public License for more details.\n#\n# You should have received a copy of the GNU Affero General Public License\n# along with this program. If not, see .\n#\n##############################################################################\n\nfrom openerp.osv import fields, osv\n\n#Mandato Info\nclass oper_mandato_info(osv.osv):\n _name = 'oper.mandato.info'\n _columns = {\n 'code': fields.date('Code Retiro'),\n 'type': fields.char('Tipo Proveedor', size=100), \n 'observacion': fields.text('Observaciones', size=200),\n 'info_id': fields.many2one('oper.mandato', 'Detalle Información', ondelete='cascade'),\n }\noper_mandato_info()\n\n#Mandato log\nclass oper_mandato_log(osv.osv):\n _name = 'oper.mandato.log'\n _columns = {\n 'fecha_log': fields.date('Fecha'),\n 'user': fields.char('Usuario', size=100), \n 'comentario': fields.text('Comentario', size=100),\n 'registro_id': fields.many2one('oper.mandato', 'Detalle Log', ondelete='cascade'),\n }\noper_mandato_log()\n\n#Mandato o contrato\nclass oper_mandato(osv.osv):\n _name = 'oper.mandato'\n _columns = {\n 'secuencia': fields.char('Descripcion', size=30),\n 'tipo_medio_pago': fields.selection([\n ('1','Cuenta Corriente'),\n ('2','Tarjeta Crédito')\n ], 'Medio de pago'),\n 'n_cuota': fields.integer('Numero Cuotas', size=10),\n 'amount_cuotas': fields.integer('Monto de la cuotas', size=10),\n 'direccion':fields.char('Dirección', siz=50),\n 'email': fields.char('E-mail', size=40), \n 'fono': fields.char('Fono', size=20),\n 'cel': fields.char('Celular', size=40),\n 'reajuste': fields.boolean ('Reajuste'),\n 'fecha_inicio': fields.date('Fecha de Inicio'),\n 'fecha_retiro': fields.date('Fecha de Retiro'),\n 'fecha_valida': fields.date('Fecha de Validacion'),\n 'fecha_envio': fields.date('Fecha de Envío'),\n 'fecha_aprobacion': fields.date('Fecha de Aprobacion'),\n 'fecha_rechazo': fields.date('Fecha de Rechazo'),\n 'n_tarjeta': fields.integer('Numero Tarjeta', size=30),\n 'n_ctacte': fields.integer('Numero Cuenta Corriente', size=10),\n 'estado': fields.char('Estado', size=20),\n 'proveedor_id': fields.many2one('res.partner','Proveedor', domain=[('supplier','=',True)]),\n 'divisa_id': fields.many2one('res.currency', 'Moneda'),\n 'institucion_id': fields.many2one('res.partner','Institucion', required=True, domain=[('is_institucion','=',True)]),\n 'socios_id': fields.many2one('res.partner','Socio',required=True,domain=[('is_socio','=',True)] ),\n 'recaudador_id': fields.many2one('oper.recaudador', 'Recaudador', required=True),\n 'emisor_id': fields.many2one('oper.file', 'Archivo'),\n 'state': fields.selection([\n ('draft', 'Borrador'),\n ('cancel', 'Cancelar'),\n ('retirar', 'Retirar'),\n ('validar', 'Validado'),\n ('enviado', 'Enviado'),\n ('aprobado', 'Aprobado'),\n ('rechazado', 'Rechazado'),\n ], 'Estado', readonly=True),\n 'ids_log':fields.one2many('oper.mandato.log','registro_id', 'Detalle Log', readonly=True),\n 'ids_info': fields.one2many('oper.mandato.info','info_id', 'Otra información'),\n 'contrato_id': fields.many2one('oper.contrato','contrato_id'),\n }\n _defaults = {\n 'reajuste': True,\n 'state': 'draft',\n #'moneda': 46,\n }\n \n def action_cancel (self, cr, uid, ids, context=None):\n self.write(cr, uid, ids, {'state': 'cancel'})\n return\n \n def action_retirar (self, cr, uid, ids, context=None):\n self.write(cr, uid, ids, {'state': 'retirar'})\n return\n \n def action_validar (self, cr, uid, ids, context=None):\n self.write(cr, uid, ids, {'state': 'validar'})\n return\n \n def action_enviado (self, cr, uid, ids, context=None):\n self.write(cr, uid, ids, {'state': 'enviado'})\n return\n \n def action_aprobado (self, cr, uid, ids, context=None):\n self.write(cr, uid, ids, {'state': 'aprobado'})\n return\n \n def action_rechazado (self, cr, uid, ids, context=None):\n self.write(cr, uid, ids, {'state': 'rechazado'})\n return\n \n def action_draft(self, cr, uid, ids, context=None):\n self.write(cr, uid, ids, {'state': 'draft'})\n return\n \noper_mandato()\n# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:#","sub_path":"econube_recaudacion/models/mandato.py","file_name":"mandato.py","file_ext":"py","file_size_in_byte":5427,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"47563134","text":"#Saisie des coefficients\r\na = 2\r\nb = 5\r\nc = 3\r\n\r\n#Calcul du discriminant\r\nD = (b^2)-(4*a*c)\r\n\r\nif D<0:\r\n print (\"Pas de solutions\")\r\n\r\nelif D == 0:\r\n x = b/(2*a)\r\n print (\"Une solution double\")\r\n print (x)\r\n \r\nelse:\r\n x1 = (-b-pow(D, 1/2))/(2*a)\r\n x2 = (-b+pow(D, 1/2))/(2*a)\r\n print (\"Deux solutions 'x1' et 'x2' \")\r\n","sub_path":"Exo1.py","file_name":"Exo1.py","file_ext":"py","file_size_in_byte":334,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"115109764","text":"#!/usr/bin/env python\n\"\"\"Convert the images registry text file into C source code.\"\"\"\n\nimport sys\n\nfrom images_registry import images_registry_add_jpeg\nfrom images_registry import load_images_registry\nfrom images_registry import load_jpeg_registry\n\n\ndef main(images_registry_path, jpeg_registry_path, header_path, c_path):\n \"\"\"Generate C source files based on the image registry definitions.\"\"\"\n images_registry = load_images_registry(images_registry_path)\n images_registry_add_jpeg(\n images_registry, load_jpeg_registry(jpeg_registry_path))\n\n # Add one more dummy entry to represent an \"empty\" image, real images start\n # with index 1.\n size = len(images_registry) + 1\n\n # All MAP images are put after FAST images, so the smallest offset of a MAP\n # image will tell how much space is required for FAST images.\n try:\n fast_size = min(image['map_offset'] for image in images_registry.values()\n if image['format'] == 'MAP')\n except ValueError:\n fast_size = 1\n\n header_out = open(header_path, 'w')\n header_out.write('#pragma once\\n')\n header_out.write('#include \\n\\n')\n header_out.write(f'#define IMAGE_REGISTRY_FAST_SIZE {fast_size}\\n')\n header_out.write('''\n#define IMAGE_REGISTRY_FAST 0\n#define IMAGE_REGISTRY_JPEG 1\n#define IMAGE_REGISTRY_MAP 2\n\ntypedef struct {\n int index;\n uint8_t type;\n uint8_t width;\n uint8_t height;\n uint8_t palette;\n uint8_t sinkline;\n uint32_t jpeg_length;\n uint32_t jpeg_offset;\n uint32_t map_offset;\n} ImagesRegistry_t;\\n\n''')\n header_out.write(f'extern const ImagesRegistry_t graphics_static_images_registry[{size}];\\n\\n')\n\n for i, image in enumerate(images_registry.values()):\n name = make_name(image).upper().replace('-', '_')\n header_out.write(f'#define LIBRARY_IMAGE_{name} {i + 1}\\n')\n\n header_out.close()\n\n c_out = open(c_path, 'w')\n c_out.write('#include \"images_registry.h\"\\n\\n')\n c_out.write('const ImagesRegistry_t graphics_static_images_registry[] = {\\n')\n c_out.write(' {},\\n')\n\n for i, image in enumerate(images_registry.values()):\n if image['format'] == 'FAST':\n format_ = 'IMAGE_REGISTRY_FAST'\n elif image['format'] == 'JPEG':\n format_ = 'IMAGE_REGISTRY_JPEG'\n elif image['format'] == 'MAP':\n format_ = 'IMAGE_REGISTRY_MAP'\n else:\n raise Exception(\n f'Invalid image type \"{image[\"format\"]}\".')\n\n c_out.write(' {\\n')\n c_out.write(f' .index={i + 1},\\n')\n c_out.write(f' .type={format_},\\n')\n c_out.write(f' .width={image[\"width\"]},\\n')\n c_out.write(f' .height={image[\"height\"]},\\n')\n c_out.write(f' .palette={image[\"palette\"]},\\n')\n c_out.write(f' .sinkline={image[\"sinkline\"]},\\n')\n c_out.write(f' .jpeg_length={image[\"jpeg_length\"]},\\n')\n c_out.write(f' .jpeg_offset={image[\"jpeg_offset\"]},\\n')\n c_out.write(f' .map_offset={image[\"map_offset\"]},\\n')\n c_out.write(' },\\n')\n\n c_out.write('};\\n')\n c_out.close()\n\n\ndef make_name(image):\n \"\"\"Format output filename of the image.\"\"\"\n return image['name'][:-4]\n\n\nif __name__ == '__main__':\n if len(sys.argv) != 5:\n print(f'Usage: {sys.argv[0]} ')\n sys.exit(1)\n\n main(sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4])\n","sub_path":"esp32/components/graphics/tools/compile-images-registry.py","file_name":"compile-images-registry.py","file_ext":"py","file_size_in_byte":3471,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"512310521","text":"import subprocess\nimport sys\nimport os\n\nclass RunServerMonitor:\n\n def runShells(self):\n pathToFile = os.getcwd()\n pathToLogs = pathToFile + \"/logsfiles\"\n \n unixDetection = 'uname -a'\n p = subprocess.Popen(unixDetection, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)\n out = p.communicate()[0]\n\n if 'Mint'.encode() in out:\n try:\n mintCommandrs = 'cd logfiles ; mate-terminal -e \"rcssserver --server::port=6000\"'\n mintCommandrm = 'mate-terminal -e \"rcssmonitor\"'\n mintRunTerm = subprocess.Popen(mintCommandrm, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)\n mintRunTers = subprocess.Popen(mintCommandrs, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)\n except KeyboardInterrupt as e:\n sys.exit('Failed to start %r, reason %s' % (mintRunTerm, e))\n sys.exit('Failed to start %r, reason %s' % (mintRunTers, e))\n\n elif 'Ubuntu'.encode() in out:\n try:\n # otherwise gnome-terminal is the issued terminal for ubuntu \n ubuntuCommandrs = 'cd logfiles ; gnome-terminal -e \"rcssserver --server::port=6000\"'\n ubuntuCommandrm = 'gnome-terminal -e \"rcssmonitor\"' \n ubuntuRunTermrm = subprocess.Popen(ubuntuCommandrm, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)\n ubuntuRunTermrs = subprocess.Popen(ubuntuCommandrs, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)\n except KeyboardInterrupt as e:\n sys.exit('Failed to start %r, reason %s' % (ubuntuRunTermrm, e))\n sys.exit('Failed to start %r, reason %s' % (ubuntuRunTermrs, e))\n\n elif 'Darwin'.encode() in out:\n try:\n macOSCommandcd = \"osascript -e\" + \"'tell app \" + '\"Terminal\" ' + \"to do script \" + '\"cd ' + pathToLogs + \" ; \"+ \"rcssserver --server::port=6000\" + '\"' + \"' \"\n macOSCommandrm = \"\"\" osascript -e 'tell app \"Terminal\" to do script \"rcssmonitor\"' \"\"\"\n macOStermcd = subprocess.Popen(macOSCommandcd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)\n macOStermrm = subprocess.Popen(macOSCommandrm, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) \n except KeyboardInterrupt as e:\n sys.exit('Failed to start %r, reason %s' % (macOStermcd, e))\n sys.exit('Failed to start %r, reason %s' % (macOStermrm, e))\n else:\n print(\"OS not supported.\")\n","sub_path":"src/run_server_monitor.py","file_name":"run_server_monitor.py","file_ext":"py","file_size_in_byte":2636,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"604234504","text":"# -*- coding: utf-8 -*-\n#\n# This file is part of Lifewatch DAAP.\n# Copyright (C) 2015 Ana Yaiza Rodriguez Marrero.\n#\n# Lifewatch DAAP 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# Lifewatch DAAP 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 Lifewatch DAAP. If not, see .\n\n#\n#\n\nfrom fixture import DataSet\n\n\nclass CommunityData(DataSet):\n class daap:\n id = 'daap'\n title = 'LifeWatch Open Science Framework'\n id_user = 1\n\n class cuerda_del_pozo:\n id = 'cuerdadelpozo'\n title = 'Cuerda del Pozo',\n curation_policy = ('Datasets related to the Cuerda del Pozo '\n 'reservoir at Soria')\n id_user = 1\n","sub_path":"lw_daap/deploy/fixtures/communities.py","file_name":"communities.py","file_ext":"py","file_size_in_byte":1159,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"614101062","text":"class TreeNode(object):\n\tdef __init__(self, nid, frontLeaf):\n\t\tself.nid = nid\n\t\tself.label = 0\n\t\tself.reln = 0\n\t\tself.frontLeaf = frontLeaf\n\t\tself.leftChild = None\n\t\tself.rightChild = None\n\t\tself.parent = None\n\n\tdef setParent(self, parentId, nodes):\n\t\tif nodes[parentId] is None:\n\t\t\tnodes[parentId] = TreeNode(parentId, self.frontLeaf)\n\t\tnodes[parentId].addChild(self)\n\t\tself.parent = nodes[parentId]\n\n\tdef addChild(self, node):\n\t\tif self.leftChild is None:\n\t\t\tself.leftChild = node\n\t\t\tself.frontLeaf = node.frontLeaf\n\t\telif self.frontLeaf > node.frontLeaf:\n\t\t\tself.rightChild = self.leftChild\n\t\t\tself.leftChild = node\n\t\t\tself.frontLeaf = node.frontLeaf\n\t\telse:\n\t\t\tself.rightChild = node\n\n\tdef isLeaf(self):\n\t\treturn self.leftChild is None\n\n\tdef printNode(self):\n\t\tif self.parent is not None:\n\t\t\tprint('node-', self.nid, '(Leaf-', self.isLeaf(), '): ', self.parent.nid)\n\t\telse:\n\t\t\tprint('node-', self.nid, '(ROOT)')","sub_path":"data_utils/TreeNode.py","file_name":"TreeNode.py","file_ext":"py","file_size_in_byte":915,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"103406186","text":"from enum import Enum\nfrom pathlib import Path\nfrom typing import Dict\n\nfrom drepr.models import Representation, CSVResource, NetCDF4Resource, JSONResource\nfrom drepr.query.selection_interface import SelectionGraph\nfrom drepr.services.ra_executor.preprocessing.preprocessing import exec_preprocessing\nfrom drepr.services.ra_executor.ra_executor import exec_ra_query\nfrom drepr.query.return_format import ReturnFormat\nfrom drepr.services.ra_reader import CSVRAReader, JSONRAReader, NetCDFRAReader\nfrom drepr.services.ra_reader.multi_ra_reader import MultiRAReader\nfrom drepr.services.ra_reader.ra_reader import RAReader\n\n\nclass DataSource:\n \"\"\"https://en.wikipedia.org/wiki/Datasource\"\"\"\n\n def __init__(self, repr: Representation, resources: Dict[str, str]):\n self.resources = resources\n self.repr: Representation = repr\n self.is_preprocessed: bool = False\n\n readers = {}\n for rid, rtype in self.repr.resources.items():\n if isinstance(rtype, CSVResource):\n reader = CSVRAReader(Path(resources[rid]), delimiter=rtype.delimiter)\n elif isinstance(rtype, NetCDF4Resource):\n reader = NetCDFRAReader(Path(resources[rid]))\n elif isinstance(rtype, JSONResource):\n reader = JSONRAReader(Path(resources[rid]))\n else:\n raise NotImplementedError()\n\n readers[rid] = reader\n\n if len(readers) == 1:\n self.reader: RAReader = next(iter(readers.values()))\n else:\n self.reader: RAReader = MultiRAReader(readers)\n\n def dump2json(self):\n if isinstance(self.reader, MultiRAReader):\n return self.reader.dump2json()\n return {next(iter(self.repr.resources.keys())): self.reader.dump2json()}\n\n def preprocess(self):\n if not self.is_preprocessed:\n exec_preprocessing(self.repr, self.reader)\n\n def select(self, sg: SelectionGraph) -> 'DSQueryInterface':\n self.preprocess()\n return DSQueryInterface(self, sg)\n\n\nclass DSQueryInterface:\n \"\"\"Query data which is described by `ont`\"\"\"\n\n def __init__(self, data_source: DataSource, sg: SelectionGraph):\n self.data_source = data_source\n self.sg = sg\n\n def exec(self, return_format: ReturnFormat=ReturnFormat.JsonLD):\n if isinstance(self.data_source.reader, RAReader):\n return exec_ra_query(self.data_source.repr, self.data_source.reader, self.sg, return_format)\n else:\n raise NotImplementedError()\n\n\n\n\n","sub_path":"toberemoved/drepr-old/old_code/prototype/drepr/data_source.py","file_name":"data_source.py","file_ext":"py","file_size_in_byte":2533,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"250897842","text":"#!/usr/bin/env python3\n\nimport os\nimport sys\nimport pandas\nimport getpass\nimport requests\nimport argparse\nimport numpy as np\nfrom tabulate import tabulate\nimport matplotlib.pyplot as plt\nimport matplotlib.dates as mdates\nfrom datetime import datetime, timedelta\n\n\nclass PlotObject(object):\n def __init__(self, x, y, label='', style='b-'):\n self.x = x\n self.y = y\n self.label = label\n self.style = style\n\n\nclass Issue(object):\n def __init__(self, issue_dict):\n self.number = issue_dict['number']\n self.state = issue_dict['state']\n self.url = issue_dict['url']\n self.labels = issue_dict['labels']\n\n self.title = issue_dict['title']\n self.title = self.title.replace('\\r', '') \\\n .replace('\\n', '') \\\n .replace(',', ' ')\n\n self.created_dt = issue_dict['created_at']\n if self.created_dt is not None:\n self.created_dt = datetime.strptime(self.created_dt,\n '%Y-%m-%dT%H:%M:%SZ')\n\n self.closed_dt = issue_dict['closed_at']\n if self.closed_dt is not None:\n self.closed_dt = datetime.strptime(self.closed_dt,\n '%Y-%m-%dT%H:%M:%SZ')\n\n def __issue_to_dict(self, i=None):\n if i is None:\n l = ''\n else:\n l = self.labels[i]['name']\n\n return dict(number=self.number,\n created_dt=self.created_dt,\n closed_dt=self.closed_dt,\n state=self.state,\n title=self.title,\n url=self.url,\n label=l)\n\n def get(self):\n data = []\n if len(self.labels) > 0:\n for i in range(0, len(self.labels)):\n data.append(self.__issue_to_dict(i))\n else:\n data.append(self.__issue_to_dict())\n return data\n\n\ndef get_data(username, password,\n url=\"https://api.github.com/repos/hydroshare/hydroshare/issues\",\n outpath='hydroshare_git_issues.csv'):\n\n dat = []\n idx = []\n\n AUTH = (username, password)\n\n r = requests.get('%s?state=all&per_page=50&page=%d' % (url, 1), auth=AUTH)\n jdat = r.json()\n for d in jdat:\n dat.append(Issue(d))\n\n # loop through github issue pages and save issue json\n if 'link' in r.headers:\n pages = dict(\n [(rel[6:-1], url[url.index('<')+1:-1]) for url, rel in\n [link.split(';') for link in\n r.headers['link'].split(',')]])\n print('--> collecting data.', end='', flush=True)\n while 'last' in pages and 'next' in pages:\n pg = pages['next'].split('=')[-1]\n r = requests.get(pages['next'], auth=AUTH)\n jdat = r.json()\n\n # save the issue\n for d in jdat:\n dat.append(Issue(d))\n print('.', end='', flush=True)\n\n # exit when the last page is reached\n if pages['next'] == pages['last']:\n break\n\n pages = dict(\n [(rel[6:-1], url[url.index('<')+1:-1]) for url, rel in\n [link.split(';') for link in\n r.headers['link'].split(',')]])\n\n print('done')\n\n # save to csv\n print('--> writing issues to csv...', end='', flush=True)\n with open(outpath, 'w') as f:\n f.write('#\\n# Generated on %s\\n' % datetime.now())\n f.write('# Notes: each issue is listed below once for each git label'\n ' that it has. This makes analysis with pandas easier\\n#\\n')\n headers = list(dat[0].get()[0].keys())\n f.write('%s\\n' % ','.join(headers))\n for item in dat:\n for label in item.get():\n txt_list = [str(label[h]) for h in headers]\n f.write('%s\\n' % ','.join(txt_list))\n print('done')\n\n\ndef load_data(working_dir):\n csv = os.path.join(working_dir, 'git_issues.csv')\n if not os.path.exists(csv):\n print('--> !Error: could not find git_issues.csv in %s' %\n path)\n sys.exit(0)\n\n # load the csv file into a pandas dataframe\n df = pandas.read_csv(csv, sep=',', comment='#')\n \n df['created_dt'] = pandas.to_datetime(df.created_dt, errors='coerce') \\\n .dt.normalize()\n df['closed_dt'] = pandas.to_datetime(df.closed_dt, errors='coerce') \\\n .dt.normalize()\n\n # summarize all issues by label\n\n #import pdb; pdb.set_trace()\n\n d = df.groupby('label').count().number.to_frame()\n d.columns = ['all_issues']\n\n # summarize all open issues\n d1 = df[df.state == 'open'].groupby('label').count().number.to_frame()\n d1.columns = ['open_issues']\n\n #d = d.merge(d1, on='label')\n d = d.merge(d1, left_index=True, right_index=True)\n\n# tbl = tabulate(d.sort_values('all_issues', ascending=False),\n# headers='keys', tablefmt='psql')\n# print(tbl)\n\n # indicate issues as either 'open' or 'closed'\n df.loc[df.state == 'open', 'open'] = 1\n df.loc[df.state == 'closed', 'closed'] = 1\n\n return df\n \n\ndef all_issues(working_dir):\n \n print('--> computing all issues...', flush=True, end='')\n df = load_data(working_dir)\n\n # select unique issue numbers to remove duplicates caused by\n # issues having multiple labels\n df_unique = df.drop_duplicates('number')\n\n # group by date\n df_dt = df_unique.groupby(pandas.Grouper(key='created_dt', freq='W')) \\\n .count().cumsum()\n\n xdata = df_dt.index\n ydata = df_dt.number.values\n \n plot = PlotObject(x=xdata, y=ydata, label='all issues', style='k-')\n\n print('%d total' % ydata[-1])\n return plot\n\ndef closed_issues(working_dir):\n \n print('--> computing all closed...', flush=True, end='')\n \n df = load_data(working_dir)\n\n # select unique issue numbers to remove duplicates caused by\n # issues having multiple labels\n df_unique = df.drop_duplicates('number')\n\n # group by date\n df_dt = df_unique.groupby(pandas.Grouper(key='created_dt', freq='W')) \\\n .count().cumsum()\n\n xdata = df_dt.index\n ydata = df_dt.closed.values\n\n plot = PlotObject(x=xdata, y=ydata, label='closed issues', style='b-')\n\n print('%d total' % ydata[-1])\n return plot\n\n\ndef open_issues(working_dir):\n\n print('--> computing all open...', flush=True, end='')\n\n df = load_data(working_dir)\n\n # select unique issue numbers to remove duplicates caused by\n # issues having multiple labels\n df_unique = df.drop_duplicates('number')\n\n # group by date\n df_dt = df_unique.groupby(pandas.Grouper(key='created_dt', freq='W')) \\\n .count().cumsum()\n\n xdata = df_dt.index\n ydata = df_dt.open.values\n\n plot = PlotObject(x=xdata, y=ydata, label='open issues', style='r-')\n\n print('%d total' % ydata[-1])\n return plot\n\n\ndef open_bugs(working_dir):\n\n df = load_data(working_dir)\n\n # plot a summary of open issues\n df_open = df[df.state == 'open']\n\n # group open bugs by date\n df_open_bug = df_open[df_open.label == 'bug']\n df_open_bug_list = list(df_open_bug.number.values)\n df_open_bug = df_open_bug.groupby(pandas.Grouper(key='created_dt',\n freq='W')) \\\n .count().cumsum()\n xdata = df_open_bug.index\n ydata = df_open_bug.number.values\n\n plot = PlotObject(x=xdata, y=ydata, label='open - bugs', style='r-')\n return plot\n\ndef open_enhancements(working_dir):\n \n df = load_data(working_dir)\n\n # plot a summary of open issues\n df_open = df[df.state == 'open']\n\n # group open enhancements by date\n df_open_enh = df_open[df_open.label == 'enhancement']\n df_open_enh_list = list(df_open_enh.number.values)\n df_open_enh = df_open_enh.groupby(pandas.Grouper(key='created_dt',\n freq='W')) \\\n .count().cumsum()\n\n xdata = df_open_enh.index\n ydata = df_open_enh.number.values\n \n plot = PlotObject(x=xdata, y=ydata, label='open - enhancements', style='b-')\n return plot\n\ndef open_other(working_dir):\n\n df = load_data(working_dir)\n \n # plot a summary of open issues\n df_open = df[df.state == 'open']\n\n # group all open issues that are not bugs or enhancements by date\n df_open_non = df_open[~df_open.label.isin(['bug', 'enhancement'])]\n df_open_non = df_open_non.drop_duplicates('number')\n\n df_open_bug = df_open[df_open.label == 'bug']\n df_open_bug_list = list(df_open_bug.number.values)\n df_open_enh = df_open[df_open.label == 'enhancement']\n df_open_enh_list = list(df_open_enh.number.values)\n\n # remove all issue numbers that exist in enhancements and bugs lists\n bug_enh_tickets = list(df_open_bug_list) + list(df_open_enh_list)\n df_open_non = df_open_non[~df_open_non.isin(bug_enh_tickets)]\n\n df_open_non = df_open_non.groupby(pandas.Grouper(key='created_dt',\n freq='W')) \\\n .count().cumsum()\n\n xdata = df_open_non.index\n ydata = df_open_non.number.values\n\n plot = PlotObject(x=xdata, y=ydata, label='open - other', style='k-')\n return plot\n\ndef plot(plotObjs_ax1, filename, plotObjs_ax2=[], **kwargs):\n \"\"\"\n Creates a figure give plot objects\n plotObjs: list of plot object instances\n filename: output name for figure *.png\n **kwargs: matplotlib plt args, e.g. xlabel, ylabel, title, etc\n \"\"\"\n\n # create figure of these data\n print('--> making figure...')\n fig = plt.figure(figsize=(12, 9))\n plt.xticks(rotation=45)\n plt.subplots_adjust(bottom=0.25)\n ax = plt.axes()\n\n # set plot attributes\n for k, v in kwargs.items():\n getattr(ax, 'set_'+k)(v)\n\n for pobj in plotObjs_ax1:\n ax.plot(pobj.x, pobj.y, pobj.style, label=pobj.label)\n\n if len(plotObjs_ax2) > 0:\n ax2 = ax.twinx()\n for pobj in plotObjs_ax2:\n ax2.plot(pobj.x, pobj.y, pobj.style, label=pobj.label)\n\n # add a legend\n plt.legend()\n\n # add monthly minor ticks\n months = mdates.MonthLocator()\n ax.xaxis.set_minor_locator(months)\n\n # save the figure and the data\n print('--> saving figure as %s' % filename)\n plt.savefig(filename)\n\n\nif __name__ == \"__main__\":\n \n parser = argparse.ArgumentParser()\n parser.add_argument('--working-dir',\n help='path to working directory',\n required=True)\n parser.add_argument('--git-url',\n help='url for github project',\n default=\"https://api.github.com/repos/hydroshare/hydroshare/issues\")\n parser.add_argument('--filename',\n help='filename for the output figure',\n default='git-issues.png')\n parser.add_argument('--figure_title',\n help='title for output figure',\n default='Summary of Git Issues')\n parser.add_argument('--collect',\n help='force collection of data',\n action='store_true')\n parser.add_argument('-a',\n help='plot all issues',\n action='store_true')\n parser.add_argument('-o',\n help='plot open issues',\n action='store_true')\n parser.add_argument('-c',\n help='plot closed issues',\n action='store_true')\n parser.add_argument('-b',\n help='plot open bug tickets',\n action='store_true')\n parser.add_argument('-e',\n help='plot open enhancement tickets',\n action='store_true')\n parser.add_argument('-n',\n help='plot open non-bug, non-enhancement issues',\n action='store_true')\n args = parser.parse_args()\n\n\n csv = os.path.join(args.working_dir, 'git_issues.csv')\n url = args.git_url\n\n # collect github data\n if not os.path.exists(csv) or args.collect:\n username = input('Please enter your Github username: ')\n password = getpass.getpass('Password: ')\n get_data(username, password, url, csv)\n else:\n print('--> reusing %s' % csv)\n\n plots = []\n if args.a:\n plots.append(all_issues(args.working_dir))\n if args.o:\n plots.append(open_issues(args.working_dir))\n if args.c:\n plots.append(closed_issues(args.working_dir))\n if args.b:\n plots.append(open_bugs(args.working_dir))\n if args.e:\n plots.append(open_enhancements(args.working_dir))\n if args.n:\n plots.append(open_other(args.working_dir))\n\n if len(plots) > 0:\n plot(plots, os.path.join(args.working_dir, args.filename),\n title=args.figure_title,\n ylabel='Number of Issues',\n xlabel='Date Created')\n \n\n","sub_path":"scripts/reporting/git.py","file_name":"git.py","file_ext":"py","file_size_in_byte":13065,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"96508700","text":"import sys\nsys.path.append('..')\nimport numpy as np\nimport subprocess\nfrom subprocess import DEVNULL, STDOUT, check_call\nimport os, signal\n\nfrom utils.general_utils import loadpklz, savepklz, evaluate_single_state, temp_seed\n\nimport models\n\nmodel = 'Merging'\nnimc = models.__dict__[model]()\n\nT = nimc.k\ndim = nimc.Theta.shape[0]\nexp_id = int(sys.argv[1])\nport_base = 9100\nplasmalab_root = '/home/daweis2/plasmalab-1.4.4/'\n\ndef get_initial_state(seed):\n with temp_seed(np.abs(seed) % (2**32)):\n state = np.random.rand(nimc.Theta.shape[0])\\\n * (nimc.Theta[:,1] - nimc.Theta[:,0])\\\n + nimc.Theta[:,0]\n state = state.tolist()\n return state\n\nif __name__ == '__main__':\n budgets = np.logspace(np.log(0.65 * 1e5)/np.log(2), np.log(5e5)/np.log(2), num=7, base=2).astype('int')[:-1]\n budgets = (budgets/16.0).astype('int')\n #epsilon = 0.01\n delta = 0.01\n\n port = port_base + exp_id\n tmp_model_name = 'model_%d'%port\n tmp_spec_name = 'spec_%d'%port\n with open(tmp_model_name, 'w') as f:\n f.write('%d %d %d'%(dim, T+1, port))\n with open(tmp_spec_name, 'w') as f:\n f.write('F<=1000 (T<=%d & US>0)'%T)\n\n results = []\n original_results = []\n num_queries = []\n\n for budget in budgets:\n #delta = 2 / np.exp((budget*0.8)*2*(epsilon**2))\n epsilon = np.sqrt(np.log(2/delta)/np.log(np.e)/2/(budget*0.8))\n print(epsilon, delta, budget)\n # The os.setsid() is passed in the argument preexec_fn so\n # it's run after the fork() and before exec() to run the shell.\n _simulator = subprocess.Popen('cd ../; python3 simulator.py --model %s --port %d'%(model, port), shell=True, preexec_fn=os.setsid, stdout=DEVNULL)\n output = subprocess.check_output(plasmalab_root+'/plasmacli.sh launch -m '+tmp_model_name+':PythonSimulatorBridge -r '+tmp_spec_name+':bltl -a smartsampling -A\"Maximum\"=True -A\"Epsilon\"=%lf -A\"Delta\"=%lf -A\"Budget\"=%d'%(epsilon, delta, budget), universal_newlines=True, shell=True)\n os.killpg(os.getpgid(_simulator.pid), signal.SIGTERM) # Send the signal to all the process groups\n with open('../data/PlasmaLab_%s_epsilon%lf_delta%lf_budget%d_exp%d.txt'%(model, epsilon, delta, budget, exp_id), 'w') as f:\n f.write(output)\n\n with open('../data/PlasmaLab_%s_epsilon%lf_delta%lf_budget%d_exp%d.txt'%(model, epsilon, delta, budget, exp_id), 'r') as f:\n output = f.readlines()\n\n # Strips the newline character\n output = [line.strip() for line in output]\n seeds = output[1:-6]\n num_queries.append(len(seeds))\n final_iter = [int(line.split(' ')[3]) for line in seeds[-budget+10::]]\n final_iter = set(final_iter)\n original_results.append(float(output[-2].split('|')[2]))\n # print(original_results)\n final_iter = [get_initial_state(seed) for seed in final_iter]\n tmp_results = []\n for initial_states in final_iter:\n np.random.seed(1024)\n result = evaluate_single_state(nimc, initial_states, nimc.k, mult=10000)\n tmp_results.append(result)\n initial_states = final_iter[np.argmax(tmp_results)]\n np.random.seed(1024)\n result = evaluate_single_state(nimc, initial_states, nimc.k, mult=250000)\n print(result)\n\n results.append(result)\nprint({'results':results, 'num_queries':num_queries, 'original_results':original_results})\nsavepklz({'results':results, 'num_queries':num_queries, 'original_results':original_results}, '../data/PlasmaLab_%s_exp%d.pklz'%(model, exp_id))\nos.system('rm '+tmp_model_name+' '+tmp_spec_name)\n","sub_path":"scripts/PlasmaLab_collect_data_ME.py","file_name":"PlasmaLab_collect_data_ME.py","file_ext":"py","file_size_in_byte":3621,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"210794265","text":"from kafka import KafkaProducer\nfrom json import dumps\nimport time\nimport ccxt\nimport os\nimport pymysql\nimport datetime\nfrom dotenv import load_dotenv\n\ndef on_send_success(record_metadata):\n # 보낸데이터의 매타데이터를 출력한다\n print(\"record_metadata:\", record_metadata)\n\n\nload_dotenv()\n\n# 카프카 서버\nbootstrap_servers = [\"localhost:9092\"]\n\n# 카프카 공급자 생성\nproducer = KafkaProducer(bootstrap_servers=bootstrap_servers,\n key_serializer=None,\n value_serializer=lambda x: dumps(x).encode('utf-8'))\n\n# 카프카 토픽\nstr_topic_name = 'Topic1'\n\n# db 연결\ndb = pymysql.connect(\n host=\"localhost\", port=3306, user=\"root\", passwd=os.getenv('DB_PASSWORD'), db=\"data\", charset=\"utf8\", autocommit=True\n)\ncur = db.cursor()\n\n# 시작 시간 설정\n#today = datetime.date.fromtimestamp(1504224000000)\ncur.execute(\"select min(time) from btc_usdt_day\")\nret = cur.fetchone()\nif len(ret) == 0:\n print(\"No data\")\n exit()\nnow = ret[0]\n\nwhile True:\n cur.execute(\"select high from btc_usdt_day where time='\"+now.strftime(\"%Y-%m-%d %H:%M:%S\")+\"'\")\n ret = cur.fetchone()\n\n time.sleep(10)\n if len(ret) == 0:\n continue\n\n price = ret[0]\n # 카프카 공급자 토픽에 데이터를 보낸다\n data = {\"value\": price, \n\t\t\"yesterday\": {'open':19144, 'high':19160, 'low':19000, 'close':19100, 'volume':0.02},\n\t\t\"today\": {'open':19144, 'high':19360, 'low':19100, 'close':19300, 'volume':0.10},\n\t\t\"moving_average\": {'5':19100, '10':19000, '20':18900}\n\t}\n\n producer.send(str_topic_name, value=data).add_callback(on_send_success)\\\n .get(timeout=10) # blocking maximum timeout\n print('data:', data)\n\n now += datetime.timedelta(days = 1)\n\n","sub_path":"eventinjector.py","file_name":"eventinjector.py","file_ext":"py","file_size_in_byte":1784,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"579728266","text":"from tkinter import *\n\n\ndef on_select():\n print(v_gender.get())\ndef on_select1(e):\n print(e.widget[\"text\"])\n print(e.widget[\"value\"])\n\n\nroot = Tk()\nroot.option_add(\"*Font\", \"consolas 30\")\n\nv_gender = StringVar()\nv_gender.set(\"f\")\n\nf1 = Frame(root)\nf1.grid(row=0, column=0)\n\nRadiobutton(f1,\n text=\"male\",\n variable=v_gender,\n value=\"m\",\n fg=\"deep sky blue\",\n command=on_select).pack(side=LEFT)\nRadiobutton(f1,\n text=\"female\",\n variable=v_gender,\n value=\"f\",\n fg=\"hot pink\",\n command=on_select).pack(side=LEFT)\n\nd = {\"Thai\": \"th\", \"Japanese\": \"jp\", \"chinese\": \"cn\"}\nf2 = Frame(root)\ntv_code = StringVar()\ntv_code.set(\"th\")\nf2.grid(row=0, column=1)\nfor k, v in d.items():\n r = Radiobutton(f2, text=k, variable=tv_code, value=v,indicatoron=False,width=11,\n fg=\"dark blue\")\n r.pack(anchor=W)\n r.bind('', on_select1)\nroot.mainloop()","sub_path":"GUI_radiobutton.py","file_name":"GUI_radiobutton.py","file_ext":"py","file_size_in_byte":983,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"273244082","text":"import unittest\nimport pandas as pd\nimport sys, os\nsys.path.append(os.path.abspath(os.path.join('..')))\n\nfrom extract_dataframe import read_json\nfrom extract_dataframe import TweetDfExtractor\nfrom clean_tweets_dataframe import Clean_Tweets\n\n_, tweet_list = read_json(\"data/covid19.json\")\n\n#Test Clean Dataframe Functions\n\nclass TestTweetDfClean(unittest.TestCase):\n def setUp(self) -> pd.DataFrame:\n self.extractor = TweetDfExtractor(tweet_list[:5])\n self.df= self.extractor.get_tweet_df() \n self.clean_tweets=Clean_Tweets(self.df)\n\n def test_drop_unwanted_column(self):\n \n unwantedDropped=self.clean_tweets.drop_unwanted_column(self.df)\n self.assertEqual(len(unwantedDropped[unwantedDropped['retweet_count'] == 'retweet_count' ].index) , 0)\n \n def test_drop_duplicate(self ):\n data=self.clean_tweets.drop_duplicate(self.df)\n self.assertEqual(data.duplicated(subset=[\"original_text\"],keep=\"last\").sum().astype(int) , 0)\n \n def test_convert_to_datetime(self):\n data=self.clean_tweets.convert_to_datetime(self.df)\n self.assertEqual(str(data[\"created_at\"].dtype), \"datetime64[ns, UTC]\")\n \n def test_convert_to_numbers(self):\n \n data=self.clean_tweets.convert_to_numbers(self.df)\n self.assertTrue(str(data[\"subjectivity\"].dtype)==\"int64\" or str(data[\"subjectivity\"].dtype)==\"float64\" ) \n def test_remove_non_english_tweets(self):\n \n data=self.clean_tweets.drop_duplicate(self.df)\n self.assertEqual(len(data[data['lang'] != 'en'].index) , 0)\n\n\nif __name__ == '__main__':\n\tunittest.main()","sub_path":"tests/test_clean_datafram.py","file_name":"test_clean_datafram.py","file_ext":"py","file_size_in_byte":1629,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"56162410","text":"x=int(input())\r\nnums=[]\r\nfor i in range(0,x):\r\n nums.append(int(input()))\r\n\r\nn=max(nums)\r\nlist=[1]*(n+1)\r\nlist[0]=0\r\nlist[1]=0\r\n\r\nprimeArray=[]\r\n\r\nfor i in range(2,n+1):\r\n if list[i]==1:\r\n j=i*2\r\n while j 1:\n output_filename = sys.argv[1]\n plt.savefig(output_filename)\n else:\n plt.show()","sub_path":"pycfiles/openbandparams-0.9-py2.7/Plot_Strained_Band_Offset_vs_Lattice_Constant_of_Quaternary3.py","file_name":"Plot_Strained_Band_Offset_vs_Lattice_Constant_of_Quaternary3.py","file_ext":"py","file_size_in_byte":3121,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"633125275","text":"import threading\nimport socket\nfrom .msg import MsgStream, MsgConn, MsgPublisher\n\nclass Node(MsgStream, MsgPublisher):\n def __init__(self, id):\n super().__init__()\n self._id = id\n\n def publish(self, msg):\n with self._connsLock:\n for conn in self._conns:\n conn.publish(msg)\n with self._clientConnsLock:\n for conn in self._clientConns:\n conn.publish(msg)\n\nclass Interface(MsgPublisher, MsgStream):\n def __init__(self, id):\n super().__init__(self)\n self.id = id\n\nclass INetInterface(Interface):\n def __init__(self, id):\n super().__init__(id)\n self._port = None \n self._thread = None\n self._conns = []\n self._connsLock = threading.Lock()\n self._clientConns = []\n self._clientConnsLock = threading.Lock()\n\n def connect(self, host, port):\n sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n sock.connect((host, port))\n\n conn = MsgConn(sock.makefile('rw'))\n conn.listen(self) # Add us as a listener\n # Take the lock\n with self._connsLock:\n self._conns.append(conn)\n\n def start(self, port):\n if self._thread is None:\n self._thread = threading.Thread(target=self._run, args=(port,))\n self._thread.start()\n\n def join_thread(self):\n if self._thread is not None:\n self._thread.join()\n \n def _run(self, port):\n sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n sock.bind((\"0.0.0.0\", port))\n sock.listen()\n\n while True:\n conn, addr = sock.accept()\n\n msg_conn = MsgConn(conn.makefile('rw'))\n msg_conn.listen(self) # Add the node as a listener for the connection\n with self._clientConnsLock:\n self._clientConns.append(msg_conn)\n notify(Msg())\n msg_conn.start()\n\n\n","sub_path":"whiteelephant/node.py","file_name":"node.py","file_ext":"py","file_size_in_byte":2010,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"216133423","text":"from ilastik.shell.gui.startShellGui import startShellGui\nfrom thresholdMaskingWorkflow import ThresholdMaskingWorkflow\n\ndebug_testing = False\nif debug_testing:\n def test(shell, workflow):\n #projFilePath = '/home/bergs/Downloads/synapse_detection_training1.ilp'\n projFilePath = '/magnetic/MyProject.ilp'\n\n shell.openProjectFile(projFilePath)\n \n startShellGui( ThresholdMaskingWorkflow, test )\n\nelse:\n startShellGui( ThresholdMaskingWorkflow )\n","sub_path":"ilastik/workflows/examples/thresholdMasking/thresholdMaskingWorkflowMainGui.py","file_name":"thresholdMaskingWorkflowMainGui.py","file_ext":"py","file_size_in_byte":476,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"536066828","text":"#!/usr/bin/python\r\n# -*- coding: utf-8 -*-\r\n\r\nfrom bs4 import BeautifulSoup\r\nfrom selenium import webdriver\r\nfrom common_library import *\r\n\r\n#크롭 옵션 생성\r\noptions = webdriver.ChromeOptions()\r\n#headless 속성 설정\r\noptions.add_argument('--headless')\r\noptions.add_argument('window-size=1920x1080')\r\noptions.add_argument('--disable-gpu')\r\noptions.add_argument('Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36')\r\n#화면없는 크롬 브라우저 생성\r\nbrowser = webdriver.Chrome(executable_path = get_chrome_driver_path() + 'chromedriver',\r\n chrome_options=options)\r\n## PhantomJS 생성\r\nbrowser = webdriver.PhantomJS(get_phantomjs_driver_path() + 'phantomjs')\r\n##browser.get('https://www.myntra.com/watches/fossil/fossil-women-rose-gold-toned-dial-watch-es3352i/759168/buy')\r\n#탐색할 URL설정\r\nbrowser.get('https://m.stock.naver.com/index.nhn?marketIndex=MARKET')\r\n#브라우저 지연시간 설정\r\nbrowser.implicitly_wait(DELAY_LOADING_TIME)\r\n#t = browser.find_element_by_xpath('//*[@id=\"content\"]/div/div/div/table/tbody')\r\n#print(t.text)\r\n#BeautifulSoup으로 변환하기 위한 html객체 생성\r\nhtml = browser.page_source\r\n#print('+++++++++++++++++++++++++++++++',html)\r\n#BeautifulSoup객체 생성\r\nsoup = BeautifulSoup(html,\"html.parser\")\r\n#크롤링 하고자 하는 위치의 CSS Selector 기능을 이용해 값 읽어오기\r\nprodList = soup.select('#content > div > div.ct_box.home_my._home_my_wrapper > div.item_list_wrp._item_wrapper > table > tbody > tr > td > span')\r\n#prodList 리스트 값에서 하나씩 꺼내 읽는다.\r\n#print('+++++++++++++++++++++++',prodList)\r\nfor prod in prodList:\r\n print(prod.text)\r\n\r\ndriver = webdriver.Chrome(executable_path = get_chrome_driver_path() + 'chromedriver')\r\ndriver.implicitly_wait(DELAY_LOADING_TIME)\r\n#해딩 페이지 스크린샷 생성\r\n#driver.get_screenshot_as_file('naver_main.png')\r\n\r\n## url에 접근한다.\r\ndriver.get('https://nid.naver.com/nidlogin.login')\r\nnaver_id = input('input your id : ')\r\nnaver_pw = input('input your password : ')\r\ndriver.find_element_by_name('id').send_keys(naver_id)\r\ndriver.find_element_by_name('pw').send_keys(naver_pw)\r\n\r\n## 로그인 버튼을 눌러주자.\r\ndriver.find_element_by_xpath('//*[@id=\"frmNIDLogin\"]/fieldset/input').click()\r\n","sub_path":"MyProject/helloPython/my_project/naver_stock.py","file_name":"naver_stock.py","file_ext":"py","file_size_in_byte":2357,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"137751304","text":"from nose.tools import *\nfrom lexicon import parser\n\ndef test_parseverbfirst():\n\tresult = parser.parse_sentence([('verb', 'hit'), ('noun', 'bear')])\n\tassert_equal(result.subject, 'player')\n\tassert_equal(result.verb, 'hit')\n\tassert_equal(result.object, 'bear')\n\t\ndef test_wrong_sentence_struct():\n\tinput = [('stop', 'the'), ('error', 'for'), ('error', 'it')]\n\tassert_raises(parser.ParserError, parser.parse_sentence, input)\n\n","sub_path":"tests/parser_tests.py","file_name":"parser_tests.py","file_ext":"py","file_size_in_byte":424,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"582518024","text":"from PyQt4.QtGui import (QDialog, QLabel, QPushButton, QLineEdit,\r\n QGridLayout, QSizePolicy)\r\n\r\nfrom PyQt4.QtCore import Qt\r\n\r\nfrom checks import is_acceptable\r\nfrom errorDialog import ErrorDialog\r\n\r\nlimits = [(1, 20), (-10, 10), (0, 1)]\r\n\r\n\r\nclass Dialog(QDialog):\r\n def __init__(self, window, calledBefore=True, particleObject=None):\r\n # Creates the dialog of handpicked size\r\n\r\n super().__init__()\r\n self.data = [-1, -1, -1, False]\r\n self.setWindowFlags(Qt.WindowTitleHint | Qt.WindowCloseButtonHint)\r\n self.limits = limits\r\n self.calledBefore = calledBefore\r\n if particleObject is None:\r\n self.setWindowTitle('New particle')\r\n else:\r\n self.setWindowTitle('Edit particle')\r\n self.particleObject = particleObject\r\n self.needRemoveButton = False\r\n\r\n self.w = 100\r\n self.h = 75\r\n y = window.height()/2 + window.geometry().y() + self.h/1.75\r\n x = window.width()/2 - 50 + window.geometry().x()\r\n if particleObject is not None:\r\n x = particleObject.x() + particleObject.r + window.geometry().x()-66\r\n self.setGeometry(x, y, self.w, self.h)\r\n # self.adjustSize()\r\n # print(self.width(), self.height())\r\n # self.setFixedSize(self.size())\r\n\r\n self.init_UI()\r\n\r\n def init_UI(self):\r\n # Fills dialog with widgets to allow to enter mass, velocity\r\n # and coefficient of restitution\r\n\r\n self.mainLayout = QGridLayout()\r\n # self.mainLayout.setSizeConstraint(QGridLayout.SetFixedSize)\r\n self.setLayout(self.mainLayout)\r\n\r\n self.nameLabels = [QLabel(), QLabel(), QLabel()]\r\n self.lineEdits = [QLineEdit(), QLineEdit(), QLineEdit()]\r\n self.limitsLabels = [QLabel(), QLabel(), QLabel()]\r\n self.contents = [self.nameLabels, self.lineEdits, self.limitsLabels]\r\n\r\n self.nameLabels[0].setText('Mass:')\r\n self.nameLabels[1].setText('Velocity:')\r\n self.nameLabels[2].setText('e with prev. particle:')\r\n self.limitsLabels[0].setText('%d to %d' % (limits[0][0], limits[0][1]))\r\n self.limitsLabels[1].setText('%d to %d' % (limits[1][0], limits[1][1]))\r\n self.limitsLabels[2].setText('%d to %d' % (limits[2][0], limits[2][1]))\r\n\r\n self.okButton = QPushButton('OK')\r\n self.okButton.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)\r\n self.okButton.clicked.connect(self.close_)\r\n self.okButton.setMinimumWidth(10)\r\n\r\n for each in self.limitsLabels:\r\n each.setAlignment(Qt.AlignRight)\r\n for each in self.nameLabels:\r\n each.setAlignment(Qt.AlignRight)\r\n for each in self.lineEdits:\r\n each.setFixedWidth(45)\r\n each.setMaxLength(5)\r\n self.lineEdits[1].setMaxLength(6)\r\n\r\n for i in range(3):\r\n for j in range(2):\r\n self.mainLayout.addWidget(self.contents[i][j], j, i)\r\n\r\n if self.particleObject is not None:\r\n self.initialData = self.data\r\n self.initialData[0] = self.particleObject.mass\r\n self.initialData[1] = self.particleObject.velocity\r\n self.lineEdits[0].setText('%.2f' % (self.initialData[0]))\r\n self.lineEdits[1].setText('%.2f' % (self.initialData[1]))\r\n self.removeButton = QPushButton('Remove')\r\n self.removeButton.clicked.connect(self.remove)\r\n self.removeButton.setMinimumWidth(47)\r\n self.needRemoveButton = True\r\n elif self.calledBefore:\r\n j += 1\r\n self.mainLayout.addWidget(self.nameLabels[2], j, 0)\r\n self.mainLayout.addWidget(self.lineEdits[2], j, 1)\r\n self.mainLayout.addWidget(self.limitsLabels[2], j, 2)\r\n\r\n if self.needRemoveButton is True:\r\n self.mainLayout.addWidget(self.okButton, j+1, 1)\r\n self.mainLayout.addWidget(self.removeButton, j+1, 2)\r\n else:\r\n self.mainLayout.addWidget(self.okButton, j+1, 1, j+1, 2)\r\n\r\n def remove(self):\r\n # Sets a flag that particle should be removed and closes the dialog.\r\n\r\n self.data[3] = True\r\n self.close()\r\n\r\n def close_(self):\r\n # Checks values user entered and stores them in main classes.\r\n\r\n self.data = [-1, -1, -1, False]\r\n for i, e in enumerate(self.lineEdits):\r\n data = e.text()\r\n if is_acceptable(data, *self.limits[i]):\r\n self.data[i] = float(data)\r\n elif not (self.particleObject is None and self.calledBefore):\r\n if i != 2:\r\n error(i, data)\r\n self.data = self.initialData\r\n break\r\n else:\r\n error(i, data)\r\n self.data = self.initialData\r\n break\r\n else:\r\n self.close()\r\n\r\n def get_data(self):\r\n # Returns the data user entered.\r\n\r\n return self.data\r\n\r\n\r\ndef error(err, val):\r\n # Displays error dialog.\r\n\r\n msg = ErrorDialog(err, val)\r\n msg.exec_()\r\n","sub_path":"dialogWindow.py","file_name":"dialogWindow.py","file_ext":"py","file_size_in_byte":5082,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"363502377","text":"import model.issue as model_issue\nimport model.question as model_question\nimport model.option as model_option\n\n\ndef id(value):\n issue = model_issue.Issue.query.get(value)\n if issue is None:\n raise Exception(\"Data base is empty, import sql.\")\n data = dict(\n id=issue.id,\n title=issue.title,\n description=issue.description,\n account_id=issue.account_id,\n questions=[]\n )\n\n questions = model_question.Question.query.filter_by(issue_id=issue.id).all()\n for question in questions:\n options = model_option.Option.query.filter_by(question_id=question.id)\n\n options_data = []\n for option in options:\n options_data.append(dict(\n id=option.id,\n text=option.text,\n ))\n\n data['questions'].append(dict(\n id=question.id,\n text=question.text,\n issue_id=question.issue_id,\n answer_id=question.answer_id,\n options=options_data\n ))\n\n\n return data\n","sub_path":"tenacity/command/issue.py","file_name":"issue.py","file_ext":"py","file_size_in_byte":1026,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"475053290","text":"import anvil\nimport cv2\nimport numpy as np\n\ndef bll(name):\n return anvil.Block('minecraft', name)\n\nimg = cv2.imread('aa.png')\n\nimg = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n\nnames = {1:'white_wool', 2:'light_gray_wool', 3:'gray_wool', 4:'dark_gray_wool', 5:'black_wool'}\n\nn_elem = len(names)\nimg = 255 - img\nimg = img/(255/n_elem)\nimg = img.astype(int)\n\nsh = img.shape\n\nmy_region = anvil.EmptyRegion(0,0)\n\nx = 0\n\nfor i in range(sh[0]):\n for j in range(sh[1]):\n y = sh[0] - i\n z = j\n if(img[i, j] != 0):\n my_region.set_block(bll(names[img[i, j]]), x, y, z)\n\n\n#my_region.save('r.0.0.mca')\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":623,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"406457513","text":"import requests\nfrom datetime import datetime\nimport csv\nimport os\nfrom itertools import repeat, zip_longest\nfrom utils.dbmanager import DBManager\nimport pandas as pd\n\n\nSMARTMETER_ATTRIBUTES = {\n 'table_name': 'smartmeter_data',\n 'table_columns': {\n 'house_name': 'TEXT',\n 'time': 'TEXT',\n 'activePower_W': 'REAL',\n 'apparentPower_VA': 'REAL', \n 'billingActivePower_W': 'REAL', \n 'current_A': 'REAL', \n 'negativeEnergy_Wh': 'REAL', \n 'negativeEnergyReactive_Varh': 'REAL', \n 'positiveEnergy_Wh': 'REAL', \n 'positiveEnergyReactive_Varh': 'REAL', \n 'reactivePower_Var': 'REAL', \n 'voltage_V': 'REAL'\n }\n}\nSMARTMETER_DATE_ATTRIBUTES = {\n 'table_name': 'smartmeter_fetched_date',\n 'table_columns': {\n 'house_name': 'TEXT UNIQUE',\n 'date': 'TEXT'\n }\n}\nSMARTMETER_HTTP_QUERY = 'http://sm2.energyiotlab.com:4242/api/query?start={}&end={}&m=sum:{}'\nINITIAL_FETCH_DATE = datetime(2018,6,1)\n\n# helper date conversion functions\ndate_to_str = lambda date: datetime.strftime(date, \"%Y/%m/%d-%H:%M:%S\")\nstr_to_date = lambda s: datetime.strptime(s, \"%Y/%m/%d-%H:%M:%S\")\n\n\nclass SmartMeterDataManager:\n def __init__(self, csv_path, db_path):\n \"\"\"Connect to sqlite db and check for tables.\"\"\"\n self.dbmanager = DBManager(db_path)\n self.table_name = SMARTMETER_ATTRIBUTES['table_name']\n self.columns = list(SMARTMETER_ATTRIBUTES['table_columns'].keys())\n self.attrs = [c for c in self.columns if c not in ['house_name', 'time']]\n self.house_device_id_dict = self._read_house_device_id_csv(csv_path)\n \n # check tables\n for meta in [SMARTMETER_ATTRIBUTES, SMARTMETER_DATE_ATTRIBUTES]:\n table_name = meta['table_name']\n self.dbmanager.create_table_if_not_exists(table_name, meta['table_columns'])\n \n # add initial dates if they don't exist\n if table_name == 'smartmeter_fetched_date':\n c = self.dbmanager.conn.cursor()\n for record in zip(self.house_device_id_dict.keys(), repeat(date_to_str(INITIAL_FETCH_DATE))):\n c.execute('INSERT OR IGNORE INTO {} VALUES (?,?)'.format(table_name), record)\n c.close()\n self.dbmanager.conn.commit()\n \n def _read_house_device_id_csv(self, file_path): # file_path = 'data/smart_meter'\n \"\"\"Read all csv in the file directory and create dictionary for mapping house names to device ids.\"\"\"\n csvs = [os.path.join(file_path, f) for f in os.listdir(file_path) if f.endswith('.csv')]\n\n house_device_id_dict = {}\n for csvpath in csvs:\n with open(csvpath, encoding='utf-8') as csvfile:\n reader = csv.reader(csvfile)\n next(reader, None) # skip the headers\n for row in reader:\n house_device_id_dict[\"-\".join(row[:3])] = row[3]\n return house_device_id_dict\n \n def download_data(self, house_name, device_id=None, start_date=None, end_date=None):\n \"\"\"Fetch data from server, save to db, and return bool whether process was successful.\"\"\"\n \n if not device_id:\n device_id = self.house_device_id_dict[house_name]\n if not start_date:\n start_date = self._get_last_fetched_dates()[house_name]\n if not end_date:\n end_date = datetime.now()\n \n print(\"%-18s FROM %s...\" % (house_name, date_to_str(start_date)), end=' ')\n data_dict = {}\n data_len = 0\n\n # iterate over all attributes\n for j, attr in enumerate(self.attrs):\n print(\"%d..\" % (j+1), end=' ')\n\n # try fetching data from server\n try:\n response_data = self._perform_query(device_id, attr, start_date, end_date)\n except requests.exceptions.HTTPError as e:\n print(\" ERROR WITH '%s-%s'! SKIPPING...\" % (device_id, attr))\n print(\" \", e)\n return False\n except IndexError as e:\n print(\" NO NEW DATA! SKIPPING...\")\n return True\n\n # append fetched data to dict\n data_dict[attr] = list(response_data.values())\n\n # add time column to dict\n if 'time' not in data_dict:\n # transform unix time to korean date time\n data_dict['time'] = [date_to_str(datetime.fromtimestamp(int(t))) for t in response_data.keys()]\n data_len = len(response_data)\n else:\n \n # save to db if no errors ocurred during fetching\n print(\"Saving %6d records...\" % len(data_dict['time']), end=' ')\n\n self._save_to_db(house_name, data_dict)\n self._set_last_fetched_date(house_name, end_date)\n\n print(\"Done!\")\n return True\n \n def download_all_data(self):\n \"\"\"Download data for all households in the dictionary up to current time.\"\"\"\n failed_houses = []\n end_date = datetime.now()\n \n num_houses = len(self.house_device_id_dict)\n \n print(\"=== DOWNLOADING DATA TO DATABASE UPTO %s FOR ALL %d HOUSEHOLDS ===\" % (date_to_str(end_date), num_houses))\n \n start_dates = self._get_last_fetched_dates()\n \n # iterate over all households\n for i, (house_name, device_id) in enumerate(self.house_device_id_dict.items()):\n print(\"#%3d/%d.\" % (i+1, num_houses), end=' ') # prefix for logs\n success = self.download_data(house_name, device_id, start_dates[house_name], end_date)\n if not success:\n failed_houses.append(house_name)\n \n print(\"=== FETCHING DATA DONE! %d/%d SUCCESSFUL ===\" % (num_houses - len(failed_houses), num_houses))\n \n def _perform_query(self, device_id, attribute, start_date, end_date):\n \"\"\"Perform http query to data server and fetch data.\"\"\"\n # helper function for performing http request\n def perform_request(query):\n r = requests.get(query)\n if r.ok:\n return r\n else:\n raise requests.exceptions.HTTPError(\"HTTP Status Error: %d\" % r.status_code)\n \n # helper function for correctly formating datetime\n date_to_str = lambda date: datetime.strftime(date, \"%Y/%m/%d-%H:%M:%S\")\n \n # generate query\n key = device_id + \"_\" + attribute\n query = SMARTMETER_HTTP_QUERY.format(date_to_str(start_date), date_to_str(end_date), key)\n \n # perform request\n r = perform_request(query)\n \n # extract data\n data = r.json()[0]['dps']\n \n return data\n \n def _save_to_db(self, house_name, data_dict):\n \"\"\"Save fetched data to db.\"\"\"\n # helper function for getting records in batches\n def get_data_batch(batch_size):\n records = zip(repeat(house_name), *data_dict.values())\n batch_iterator = [iter(records)]*batch_size\n for batch in zip_longest(*batch_iterator):\n yield [x for x in batch if x]\n \n # format query\n insert_query = 'INSERT INTO {} ({}) VALUES ({})'.format(\n self.table_name, \n ', '.join([\"house_name\", *data_dict.keys()]), \n ', '.join(['?']*len(self.columns))\n )\n \n # perform insertion in batches\n c = self.dbmanager.conn.cursor()\n for d in get_data_batch(500):\n c.executemany(insert_query, d)\n c.close()\n \n self.dbmanager.conn.commit()\n\n def _get_last_fetched_dates(self):\n \"\"\"Retrieve last successful fetch date.\"\"\"\n table_name = SMARTMETER_DATE_ATTRIBUTES['table_name']\n dates = {}\n for house_name, datestr in self.dbmanager.conn.execute(\"SELECT * FROM {}\".format(table_name)).fetchall():\n dates[house_name] = str_to_date(datestr)\n return dates\n \n def _set_last_fetched_date(self, house_name, date):\n \"\"\"Record last successful fetch date.\"\"\"\n table_name = SMARTMETER_DATE_ATTRIBUTES['table_name']\n self.dbmanager.conn.execute(\"UPDATE {} SET date = ? WHERE house_name = ?\".format(table_name), (date_to_str(date), house_name))\n self.dbmanager.conn.commit()\n \n def get_dataframe(self, house_name, start_date=None, end_date=None, preprocess=True):\n \"\"\"Return pandas dataframe of smartmeter data.\"\"\"\n # join table and subtable\n query = 'SELECT * FROM {}'.format(self.table_name)\n \n # append conditions to end of query\n conds = []\n vals = []\n if house_name:\n conds.append(\"house_name = ?\")\n vals.append(house_name)\n if start_date:\n conds.append(\"time > ?\")\n vals.append(date_to_str(start_date))\n if end_date:\n conds.append(\"time < ?\")\n vals.append(date_to_str(end_date))\n \n if len(conds) > 0:\n query += ' WHERE ' + ' AND '.join(conds)\n params = tuple(vals)\n else:\n params = None \n \n # execute query\n df = pd.read_sql_query(query, self.dbmanager.conn, params=params)\n if len(df) == 0:\n return df\n \n # convert date column to pandas datetime format\n df.time = pd.to_datetime(df.time)\n \n if preprocess:\n # filter out columns that are zero for all time interval\n df = df[df.columns[(df != 0).any()]]\n # resample by taking average of 10 min. intervals\n df = df.set_index('time').resample('10min').mean()\n \n return df\n \n def get_housenames(self):\n \"\"\"Return available housenames with smartmeter data.\"\"\"\n return list(self.house_device_id_dict.keys())\n \n def get_daterange(self, house_name):\n \"\"\"Query existing date range of smartmeter data and return the datetimes.\"\"\"\n start_date = str_to_date(self.dbmanager.conn.execute(\"SELECT MIN(time) FROM {} WHERE house_name = ?\".format(self.table_name), (house_name,)).fetchone()[0])\n end_date = str_to_date(self.dbmanager.conn.execute(\"SELECT MAX(time) FROM {} WHERE house_name = ?\".format(self.table_name), (house_name,)).fetchone()[0])\n return start_date, end_date","sub_path":"utils/smartmeter.py","file_name":"smartmeter.py","file_ext":"py","file_size_in_byte":10486,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"647791673","text":"# -*- coding: utf-8 -*-\nimport socket\nimport sys\n\nfrom flask import jsonify\n\nfrom knxnet import *\nfrom knxnet import knxnet\n\n\nclass connectionKNX:\n def __init__(self, gateway_ip, gateway_port):\n # -> in this example, for sake of simplicity, the two ports are the same.\n self.action = None\n self.gateway_ip = gateway_ip\n self.gateway_port = gateway_port\n self.data_endpoint = ('0.0.0.0', 0)\n self.control_endpoint = ('0.0.0.0', 0)\n\n # -> Socket creation\n self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n self.sock.bind(('', 3672))\n\n self.channel_id = None\n self.sequence_counter = None\n\n def send_data(self, data, data_size, acpi, dest_group_addr):\n \"\"\"\n Send command data to a KNX enabled device\n :param data:\n :param data_size:\n :param acpi:\n :param dest_group_addr:\n :return:\n \"\"\"\n\n # -----------------------------------\n # -> (0) Establish connection\n # -----------------------------------\n\n self.establish_connection(data, acpi, data_size, dest_group_addr)\n\n # -----------------------------------\n # -> (1) Send tunneling ack request\n # -----------------------------------\n\n self.tunneling_ack_request()\n\n print('-----------------------------------')\n\n # -----------------------------------\n # -> (2) Disconnect request\n # -----------------------------------\n\n disconnect_resp_object = self.disconnect_request()\n\n # <- Retrieving data from disconnect request\n disconnect_channel_id = disconnect_resp_object.channel_id\n disconnect_status = disconnect_resp_object.status\n print('Channel ID: ', disconnect_channel_id)\n print('Channel status: ', disconnect_status)\n\n print('-----------------------------------')\n\n def read_data(self, data, data_size, acpi, dest_group_addr):\n \"\"\"\n Read data from a KNX enabled device\n :param data:\n :param data_size:\n :param acpi:\n :param dest_group_addr:\n :return:\n \"\"\"\n # -----------------------------------\n # -> (0) Establish connection\n # -----------------------------------\n\n self.establish_connection(data, data_size, acpi, dest_group_addr)\n\n # -----------------------------------\n # -> (1) Send tunneling ack request\n # -----------------------------------\n\n # <- Send Tunneling ack\n tunnel_ack = knxnet.create_frame(knxnet.ServiceTypeDescriptor.TUNNELLING_ACK,\n self.channel_id,\n 0,\n self.sequence_counter)\n\n self.sock.sendto(tunnel_ack.frame, (self.gateway_ip, self.gateway_port))\n\n # <- Read Status\n data_recv, addr = self.sock.recvfrom(1024)\n tunnel_resp_object = knxnet.decode_frame(data_recv)\n\n # -----------------------------------\n # -> (2) Disconnect request\n # -----------------------------------\n\n disconnect_resp_object = self.disconnect_request()\n\n # <- Retrieving data from disconnect request\n disconnect_channel_id = disconnect_resp_object.channel_id\n disconnect_status = disconnect_resp_object.status\n print('Channel ID: ', disconnect_channel_id)\n print('Channel status: ', disconnect_status)\n\n print('-----------------------------------')\n\n return tunnel_resp_object.data\n\n def establish_connection(self, data, data_size, acpi, dest_group_addr):\n \"\"\"\n Basic dialog between a client and the gateway to establish connection\n and exchange according data\n :param data: data to be sent: [0, 1] or [0..255]\n :param data_size: data size, in bytes: [1, 2]\n :param acpi: o for reading, 2 for writing\n :param dest_group_addr: x/y/z\n :return:\n \"\"\"\n # -----------------------------------\n # -> (1) Sending Connection request\n # -----------------------------------\n conn_resp_object = self.connection_request()\n # <- Retrieving channel_id & status from Connection response\n conn_channel_id = conn_resp_object.channel_id\n conn_status = conn_resp_object.status\n self.channel_id = conn_channel_id\n print('Channel ID: ', conn_channel_id)\n print('Channel status: ', conn_status)\n print('-----------------------------------')\n # -----------------------------------\n # -> (2) Sending Connection State request\n # -----------------------------------\n state_resp_object = self.connection_state_request()\n # <- Retrieving channel_id & status from Connection State response\n state_channel_id = state_resp_object.channel_id\n state_status = state_resp_object.status\n print('Channel ID: ', state_channel_id)\n print('Channel status: ', state_status)\n print('-----------------------------------')\n # -----------------------------------\n # -> (3) Tunneling request\n # -----------------------------------\n tunnel_resp_object = self.tunneling_request(data, data_size, dest_group_addr, acpi)\n # <- Retrieving data from Tunneling response\n tunnel_channel_id = tunnel_resp_object.channel_id\n tunnel_status = tunnel_resp_object.status\n self.sequence_counter = tunnel_resp_object.sequence_counter\n print('Channel ID: ', tunnel_channel_id)\n print('Channel status: ', tunnel_status)\n print('Sequence counter: ', self.sequence_counter)\n print('-----------------------------------')\n # -----------------------------------\n # -> (4) Tunneling request read\n # -----------------------------------\n self.tunneling_request_read()\n\n def disconnect_request(self):\n print('#5 Disconnect request')\n disconnect_req = \\\n knxnet.create_frame(knxnet.ServiceTypeDescriptor.DISCONNECT_REQUEST, self.channel_id, self.control_endpoint)\n conn_req_dtgrm = disconnect_req.frame # -> Serializing\n self.sock.sendto(conn_req_dtgrm, (self.gateway_ip, self.gateway_port))\n\n # <- Receiving Tunneling response\n data_recv, addr = self.sock.recvfrom(1024)\n disconnect_resp_object = knxnet.decode_frame(data_recv)\n\n return disconnect_resp_object\n\n def tunneling_ack_request(self):\n print('#4 Tunneling ack request')\n tunneling_ack = \\\n knxnet.create_frame(knxnet.ServiceTypeDescriptor.TUNNELLING_ACK,\n self.channel_id,\n self.sequence_counter)\n conn_req_dtgrm = tunneling_ack.frame # -> Serializing\n self.sock.sendto(conn_req_dtgrm, (self.gateway_ip, self.gateway_port))\n\n def tunneling_request_read(self):\n print('#4 Tunneling request read')\n\n # <- Receiving Tunneling request response\n data_recv, addr = self.sock.recvfrom(1024)\n tunnel_requ_resp_object = knxnet.decode_frame(data_recv)\n\n return tunnel_requ_resp_object\n\n def tunneling_request(self, data, data_size, dest_group_addr, apci):\n print('#3 Tunneling request')\n tunneling_req = \\\n knxnet.create_frame(knxnet.ServiceTypeDescriptor.TUNNELLING_REQUEST,\n dest_group_addr,\n self.channel_id,\n data,\n data_size,\n apci)\n conn_req_dtgrm = tunneling_req.frame # -> Serializing\n self.sock.sendto(conn_req_dtgrm, (self.gateway_ip, self.gateway_port))\n\n # <- Receiving Connection State response\n data_recv, addr = self.sock.recvfrom(1024)\n tunnel_resp_object = knxnet.decode_frame(data_recv)\n return tunnel_resp_object\n\n def connection_state_request(self):\n print('#2 Connection State request')\n conn_state_req = \\\n knxnet.create_frame(knxnet.ServiceTypeDescriptor.CONNECTION_STATE_REQUEST,\n self.channel_id, self.control_endpoint)\n conn_req_dtgrm = conn_state_req.frame # -> Serializing\n self.sock.sendto(conn_req_dtgrm, (self.gateway_ip, self.gateway_port))\n\n # <- Receiving Connection State response\n data_recv, addr = self.sock.recvfrom(1024)\n state_resp_object = knxnet.decode_frame(data_recv)\n return state_resp_object\n\n def connection_request(self):\n print('#1 Connection request')\n conn_req_object = \\\n knxnet.create_frame(knxnet.ServiceTypeDescriptor.CONNECTION_REQUEST,\n self.control_endpoint, self.data_endpoint)\n conn_req_dtgrm = conn_req_object.frame # -> Serializing\n self.sock.sendto(conn_req_dtgrm, (self.gateway_ip, self.gateway_port))\n\n # <- Receiving Connection response\n data_recv, addr = self.sock.recvfrom(1024)\n conn_resp_object = knxnet.decode_frame(data_recv)\n return conn_resp_object\n\n\ndef process(data, size, apci, grp_add):\n dest_addr_group = knxnet.GroupAddress.from_str(grp_add)\n print('data: ', data)\n print('size: ', size)\n print('acpi: ', apci)\n print('group: ', grp_add)\n\n res = jsonify(result=\"Success write data [dummy value]\")\n\n\n c1 = connectionKNX(\"127.0.0.1\", 3671)\n\n # set action\n c1.action = grp_add[0]\n\n if c1.action == '2':\n c1.send_data(data, size, apci, dest_addr_group)\n #ToDo: check if value was written successfully\n res = jsonify(result=\"Success write data\")\n\n elif c1.action == 0:\n data = c1.read_data(data, size, apci, dest_addr_group)\n print('The value is :', data)\n #ToDo: check if value was read successfully\n res = jsonify(result=data)\n else:\n res = jsonify(result=\"no valid action specified. \"\n \"(Valid actions are [0]:read, [2]:control\")\n\n return res\n\n\ndef main(argv):\n data = int(argv[0])\n size = int(argv[1])\n apci = int(argv[2])\n grp_add = argv[3]\n\n print(grp_add[0])\n\n print('data: ', argv[0])\n print('size: ', argv[1])\n print('acpi: ', argv[2])\n print('group: ', argv[3])\n process(data, size, apci, grp_add)\n\n\nif __name__ == \"__main__\":\n # run in terminal with 'python3 KNX.py arg1 arg2 arg3 arg4'\n main(sys.argv[1:])\n\n '''\n Example:\n python3 KNX.py 200 2 2 3/4/1 # set store 1 to 200\n python3 KNX.py 50 2 2 0/4/1 # set valve 1 to 50\n '''\n","sub_path":"KNX.py","file_name":"KNX.py","file_ext":"py","file_size_in_byte":10672,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"617110819","text":"import cv2\r\n\r\nmavi = [255, 0, 0]\r\nwan = cv2.imread(\"wan.jpeg\")\r\n\r\nreplicate = cv2.copyMakeBorder(wan, 10, 10, 10, 10, cv2.BORDER_REPLICATE)\r\n\r\nconstant = cv2.copyMakeBorder(wan, 10, 10, 10, 10, cv2.BORDER_CONSTANT, value=mavi)\r\n# düz mavi renkli border yapar\r\n\r\n#cv2.imshow(\"original\", wan)\r\n#cv2.imshow(\"replicate\", replicate)\r\n#cv2.imshow(\"constant\", constant)\r\n\r\n#cv2.waitKey(0)\r\n\r\nroi = wan[30:120, 100:200]\r\n# we choose our roi, then we will plot a rectangle to there\r\ncv2.rectangle(wan, (30, 120), (100, 200), (0, 255, 255), 2)\r\n# dikdörtgeni çizdik\r\n\r\ncv2.imshow(\"roi\", wan)\r\ncv2.waitKey(0)\r\ncv2.destroyAllWindows()\r\n\r\n\r\n","sub_path":"_2.py","file_name":"_2.py","file_ext":"py","file_size_in_byte":631,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"405209883","text":" #-*- coding: utf-8 -*- \n\nimport logging, datetime\nfrom api.lib.error import *\nfrom api.lib.action import Action\nfrom api.conf.content_conf import *\nfrom api.conf.mypeople_conf import *\nfrom api.conf.state_conf import *\nfrom api.action.send import send\n\nclass sendFromMessage(Action):\n\t\n\tlogger = logging.getLogger('api')\n\tdao = None\n\n\tdef __init__(self, request):\n\t\tself.action = request['action']\n\t\tself.buddyId = request['buddyId']\n\t\tself.content = request['content']\n\t\tself.request = request\n\n\tdef send_action(self, send_content):\n\t\tsend_params = self.set_params_send(self.buddyId, send_content)\n\t\tsend = send(send_params)\n\t\t\n\t\tresult = send.execute()\n\t\n\t\treturn result\n\n\tdef _get_params_parse(self, state_info):\n\t\tparse_list = state_info['parse_list']\t\n\t\tparse_detail = state_info['detail']\n\n\t\tfor index, parse in enumerate(parse_list):\n\t\t\tif index == 0:\n\t\t\t\tpass\n\t\t\telse:\n\t\t\t\tpre_index = self.content.find(parse_list[index-1]) + len(parse_list[index-1])\n\t\t\t\tpost_index = self.content.find(parse)\n\n\t\t\t\tparams = {}\n\t\t\t\tparams[parse_list[index-1]] = self.content[pre_index:post_index]\n\n\t\t\t\tif len(parse_list)-1 == index:\n\t\t\t\t\t#last\n\t\t\t\t\tparams[parse_list[index]] = self.content[post_index+len(parse_list[index]):]\n\n\t\tresult_params = {}\n\t\tfor parse in parse_list:\n\t\t\tif parse in parse_detail:\n\t\t\t\tkey = parse_detail[parse]\n\t\t\t\tself.logger.debug(key)\n\t\t\t\tvalue = params[parse]\n\t\t\t\tresult_params[key] = value.strip()\n\t\t\t\tself.logger.debug(result_params[key])\n\n\t\tself.logger.debug(result_params)\n\t\treturn result_params\n\n\tdef makesearch(self, params):\n\t\tsearch_list = []\n\n\t\tfor key in params:\n\t\t\tvalue = params[key]\n\t\t\tsearch_dict = {'key':key, 'value':value, 'option': 'eq'}\n\t\t\tsearch_list.append(search_dict)\n\n\t\tself.logger.debug(search_list)\n\t\treturn search_list\t\t\t\t\t\t\n\n\tdef execute(self):\n\t\tuser_dao = self.locator.getDAO('users')\n\t\tmember_dao = self.locator.getDAO('members')\n\t\tusers = user_dao.getInstanceFromKey('mypeople_id', self.buddyId)\n\n\t\tif len(users) == 0:\n\t\t\t#result = self.send_action(CONTENT_INFO['insert_user'])\n\t\t\tfrom api.action.addBuddy import addBuddy\n\t\t\taction = addBuddy(self.request)\n\t\t\tresult = action.execute()\n\t\telse:\n\t\t\tuser = users[0]\n\t\t\tmember = member_dao.getVOfromID(user.members_id)\n\t\t\tstate = user.state\n\n\t\t\tif state == 'ready':\n\t\t\t\tstate_info = STATE_INFO[state]\n\n\t\t\t\tsplit_list = self.content.split('\\n',1)\n\t\t\t\tself.logger.debug(split_list)\n\t\t\t\t\n\t\t\t\ttitle = split_list[0]\n\t\t\t\ttitle = str(title.strip())\n\n\t\t\t\tself.logger.debug(state_info)\n\t\t\t\tself.logger.debug(title)\n\n\t\t\t\tif title in state_info:\n\t\t\t\t\tparse_info = state_info[title]\n\t\t\t\t\tself.logger.debug(parse_info)\n\n\t\t\t\t\tif parse_info is None:\n\t\t\t\t\t\tcontent = split_list[1]\n\t\t\t\t\t\tcontent = str(content.strip())\n\t\t\t\t\t\t\n\t\t\t\t\t\tinsert_params = {}\n\t\t\t\t\t\tinsert_params['content'] = content\n\t\t\t\t\t\tinsert_params['members'] = member\n\t\t\t\t\t\t\n\t\t\t\t\t\tdiary_dao = self.locator.getDAO('daily_diary')\n\t\t\t\t\t\tdiary_id = diary_dao.insert(insert_params)\t\n\t\t\t\t\t\tself.logger.debug(diary_id)\t\t\t\n\t\t\t\t\t\tnow = datetime.datetime.now()\n\t\t\t\t\t\tnow_date = now.strftime(\"%Y/%m/%d\")\n\t\t\t\t\t\tcomplete_content = \"-작성자: %s\\n-작성날짜: %s\\n\\n%s\" %(str(member.name),str(now_date),CONTENT_INFO['complete_diary'])\n\t\t\t\t\t\tself.send_action(complete_content)\t\t\t\n\t\n\t\t\telif state == 'wait_register':\n\t\t\t\tstate_info = STATE_INFO[state]\n\t\t\t\tparams = self._get_params_parse(state_info)\n\t\t\t\tself.logger.debug(params)\t\t\t\t\t\n\t\n\t\t\t\tsearch = self.makesearch(params)\n\t\t\t\tmember_list, count = member_dao.select(search=search)\n\t\t\t\t\n\t\t\t\tif count == 0:\n\t\t\t\t\tresult = self.send_action(CONTENT_INFO['fail_to_find_member'])\t\t\t\t\n\t\t\t\telse:\n\t\t\t\t\tmember = member_list[0]\t\t\t\n\t\t\t\t\tupdate_params = {'members_id' : int(member.id), 'state':'ready'}\n\t\t\t\t\tuser_dao.update(user.id, update_params)\n\t\t\t\t\tcontent = \"%s %s 님\" % (CONTENT_INFO['complete_register'], str(member.name))\n\t\t\t\t\tresult = self.send_action(content)\n\t\t\t\t\tresult = self.send_action(CONTENT_INFO['explain_to_use'])\n\n\t\treturn result\t\t\t\t\n","sub_path":"api/action/sendFromMessage.py","file_name":"sendFromMessage.py","file_ext":"py","file_size_in_byte":3923,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"614908320","text":"# Connect Four - Prog0 at TU Graz SS 2019\n# Name: Al-Abbasi Mohammad\n# Student ID:_01514741\nfrom turtle import *\n\ngame_field = [\n [0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0],\n]\nperson_to_play = [2]\ndef print_field_to_console(field):\n print(\"---------------------\")\n # ToDo: Some code to output the current game_field in the command line\n print(game_field[5])\n print(game_field[4])\n print(game_field[3])\n print(game_field[2])\n print(game_field[1])\n print(game_field[0])\n print(\"|A |B |C |D |E |F |G|\")\n print(\"---------------------\")\n\n\ndef update_game_field(row_number, column_number, field, turtle):\n # This function draws the current color at\n # row_number, column_number in the field dataset with given turtle\n try:\n turtle.goto(50 + column_number * 50, 50 + row_number * 55)\n if field[row_number][column_number] == 0:\n MovingTurtle.dot(80, \"black\")\n if field[row_number][column_number] == 1:\n MovingTurtle.dot(80, \"red\")\n if field[row_number][column_number] == 2:\n MovingTurtle.dot(80, \"yellow\")\n except IndexError:\n return\nrow_number = 6\ncolumn_number = 7\ndef location_in_field(field, column):\n return field[row_number - 1][column] == 0\n\ndef row_to_drop(field, column):\n for r in range(row_number):\n if field[r][column] == 0:\n return r\ndef brick_to_drop(field, column, row, brick):\n field[row][column] = brick\ndef on_click_handler(x, y):\n print(\"Clicked on:\", [x, y])\n column = int(x/55)\n if location_in_field(game_field, column):\n row = row_to_drop(game_field, column)\n brick_to_drop(game_field, column, row, turn_())\n update_game_field(row, column, game_field, MovingTurtle)\n print_field_to_console(game_field)\n else:\n print(\"The column is already occupied!\")\n\n if check_game_winner(game_field):\n if game_field[row][column] == 1:\n print(\"player 1 won!\")\n sc.clear()\n user_input = sc.textinput(\"Player 1 won!\", \"Type in your name\")\n MovingTurtle.goto(200, 350)\n MovingTurtle.color('red')\n MovingTurtle.write(\"Congratulations\", True, \"center\", (\"Arial\", 60, \"normal\"))\n MovingTurtle.goto(200, 300)\n MovingTurtle.color('red')\n MovingTurtle.write(str(user_input), True, \"center\", (\"Arial\", 60, \"normal\"))\n MovingTurtle.goto(200, 250)\n MovingTurtle.color('red')\n MovingTurtle.write(\"You won!\", True, \"center\", (\"Arial\", 60, \"normal\"))\n else:\n print(\"player 2 won!\")\n sc.clear()\n user_input = sc.textinput(\"Player 2 won!\", \"Type in your name\")\n MovingTurtle.goto(200, 350)\n MovingTurtle.color('yellow')\n MovingTurtle.write(\"Congratulations\", True, \"center\", (\"Arial\", 60, \"normal\"))\n MovingTurtle.goto(200, 300)\n MovingTurtle.color('yellow')\n MovingTurtle.write(str(user_input), True, \"center\", (\"Arial\", 60, \"normal\"))\n MovingTurtle.goto(200, 250)\n MovingTurtle.color('yellow')\n MovingTurtle.write(\"You won!\", True, \"center\", (\"Arial\", 60, \"normal\"))\ndef turn_():\n if person_to_play.pop() == 2:\n person_to_play.append(1)\n return 1\n else:\n person_to_play.append(2)\n return 2\n\n# ToDo: Check who is the winner\ndef check_game_winner(field):\n row_count = -1\n for row_ in field:\n row_count = row_count + 1\n column_count = -1\n for column in row_:\n column_count = column_count + 1\n try:\n # check horizontal location for win\n if (field[row_count][column_count]\n == field[row_count][column_count + 1]\n == field[row_count][column_count + 2]\n == field[row_count][column_count + 3]\n & field[row_count][column_count] > 0):\n return field[row_count][column_count]\n # ToDo: Implement all rules to check whether the game is won or not\n # check vertical location for win\n elif (field[row_count][column_count]\n == field[row_count + 1][column_count]\n == field[row_count + 2][column_count]\n == field[row_count + 3][column_count]\n & field[row_count][column_count] > 0):\n return field[row_count][column_count]\n # check for positively sloped diagonal\n elif (field[row_count][column_count]\n == field[row_count + 1][column_count + 1]\n == field[row_count + 2][column_count + 2]\n == field[row_count + 3][column_count + 3]\n & field[row_count][column_count] > 0):\n return field[row_count][column_count]\n # check for negatively sloped diagonal\n elif (field[row_count][column_count]\n == field[row_count - 1][column_count + 1]\n == field[row_count - 2][column_count + 2]\n == field[row_count - 3][column_count + 3]\n & field[row_count][column_count] > 0):\n return field[row_count][column_count]\n except IndexError:\n continue\n return False\n\nsc = Screen()\nsc.setworldcoordinates(0, 0, 400, 400)\nsc.bgcolor('blue')\nsc.onclick(on_click_handler)\nMovingTurtle = Turtle()\nMovingTurtle.speed(0)\nMovingTurtle.penup()\nMovingTurtle.hideturtle()\ndef draw_field_with_turtle():\n column = 0\n raw = 0\n for c in range(6):\n for r in range(7):\n update_game_field(raw, column, game_field, MovingTurtle)\n column += 1\n raw += 1\n column = 0\n\n#if __name__ == '__main__':\n# print(\"Hello World! - Console Message\")\n# sc.listen()\n# print(person_to_play)\n# print(\"Players\")\n# print_field_to_console(game_field)\n# sc.tracer(0,0)\n# draw_field_with_turtle()\n# sc.update()\n# sc.mainloop()\n\ngame_over = False\nturn = 0\nif __name__ == '__main__':\n print(\"Hello World! - Console Message\")\n\n print_field_to_console(game_field)\n draw_field_with_turtle()\n\t# ToDo: Start game logic correctly\n while not game_over:\n # ToDo: Display which user is next\n #ask for player 1 input\n if turn == 0:\n col = True\n while col:\n try:\n column = int(input(\"Player 1 put your brick in a column (0-6):\"))\n if column < 7 and column >= -1:\n if location_in_field(game_field, column):\n raw = row_to_drop(game_field, column)\n brick_to_drop(game_field, column, raw, 1)\n col = False\n break\n else:\n print(\"The column is already occupied.\")\n else:\n print(\"Put your brick in a range of (0-6):\")\n except ValueError:\n print(\"Incorrect Value.Please insert a Number\")\n continue\n if check_game_winner(game_field):\n # ToDo: Display congratulations to winner on screen when the game is won\n print(\"Congratulations.Player 1 won\")\n MovingTurtle.color('red')\n MovingTurtle.goto(200, 380)\n MovingTurtle.write(\"Congratulations!.Player 1 won!\", True, \"center\",(\"Arial\", 25, \"normal\"))\n game_over = True\n\n #ask for plyer 2 input\n else:\n col = True\n while col:\n try:\n column = int(input(\"Player 2 put your brick in a column (0-6):\"))\n if column < 7 and column >= -1:\n if location_in_field(game_field, column):\n raw = row_to_drop(game_field, column)\n brick_to_drop(game_field, column, raw, 2)\n col = False\n break\n else:\n print(\"The column is already occupied.\")\n else:\n print(\"Put your brick in a range of (0-6):\")\n except ValueError:\n print(\"Incorrect Value.Please insert a Number\")\n continue\n\n if check_game_winner(game_field):\n # ToDo: Display congratulations to winner on screen when the game is won\n print(\"Congratulations.Player 2 won\")\n MovingTurtle.color('yellow')\n MovingTurtle.goto(200, 380)\n MovingTurtle.write(\"Congratulations!.Player 2 won!\", True, \"center\", (\"Arial\", 25, \"normal\"))\n game_over = True\n\n #game_field.reverse()\n print_field_to_console(game_field)\n update_game_field(raw, column, game_field, MovingTurtle)\n\n # make winning great again\n if check_game_winner(game_field):\n win_great_again = input(\"Enter your name :\")\n MovingTurtle.goto(220, 355)\n MovingTurtle.write( win_great_again + \" won!\" , True, \"center\", (\"Arial\", 25, \"normal\"))\n turn +=1\n turn = turn % 2","sub_path":"ConnectFour_Last_Version.py","file_name":"ConnectFour_Last_Version.py","file_ext":"py","file_size_in_byte":9656,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"636282896","text":"import logging\nfrom http import HTTPStatus\nfrom unittest.mock import Mock, patch, sentinel\n\nimport pytest\n\nfrom apiclient import exceptions\nfrom apiclient.authentication_methods import NoAuthentication\nfrom apiclient.client import LOG as client_logger\nfrom apiclient.client import BaseClient\nfrom apiclient.exceptions import ClientError, RedirectionError, ServerError, UnexpectedError\nfrom apiclient.request_formatters import BaseRequestFormatter, JsonRequestFormatter\nfrom apiclient.response_handlers import BaseResponseHandler, JsonResponseHandler\n\n\n# Minimal client - no implementation\nclass Client(BaseClient):\n pass\n\n\n# Real world api client with GET methods implemented.\nclass JSONPlaceholderClient(BaseClient):\n base_url = \"https://jsonplaceholder.typicode.com\"\n\n def get_all_todos(self) -> dict:\n url = f\"{self.base_url}/todos\"\n return self.read(url)\n\n def get_todo(self, todo_id: int) -> dict:\n url = f\"{self.base_url}/todos/{todo_id}\"\n return self.read(url)\n\n\nmock_response_handler_call = Mock()\nmock_request_formatter_call = Mock()\n\n\nclass MockResponseHandler(BaseResponseHandler):\n \"\"\"Mock class for testing.\"\"\"\n\n @staticmethod\n def get_request_data(response):\n mock_response_handler_call(response)\n return response\n\n\nclass MockRequestFormatter(BaseRequestFormatter):\n \"\"\"Mock class for testing.\"\"\"\n\n @classmethod\n def format(cls, data: dict):\n mock_request_formatter_call(data)\n return data\n\n\nclient = Client(\n authentication_method=NoAuthentication(),\n response_handler=MockResponseHandler,\n request_formatter=MockRequestFormatter,\n)\n\n\ndef test_client_initialization_with_invalid_authentication_method():\n with pytest.raises(RuntimeError) as exc_info:\n Client(\n authentication_method=None,\n response_handler=MockResponseHandler,\n request_formatter=MockRequestFormatter,\n )\n expected_message = \"provided authentication_method must be an instance of BaseAuthenticationMethod.\"\n assert str(exc_info.value) == expected_message\n\n\ndef test_client_initialization_with_invalid_response_handler():\n with pytest.raises(RuntimeError) as exc_info:\n Client(\n authentication_method=NoAuthentication(),\n response_handler=None,\n request_formatter=MockRequestFormatter,\n )\n assert str(exc_info.value) == \"provided response_handler must be a subclass of BaseResponseHandler.\"\n\n\ndef test_client_initialization_with_invalid_requests_handler():\n with pytest.raises(RuntimeError) as exc_info:\n Client(\n authentication_method=NoAuthentication(),\n response_handler=MockResponseHandler,\n request_formatter=None,\n )\n assert str(exc_info.value) == \"provided request_formatter must be a subclass of BaseRequestFormatter.\"\n\n\ndef test_set_and_get_default_headers():\n client = Client(\n authentication_method=NoAuthentication(),\n response_handler=MockResponseHandler,\n request_formatter=MockRequestFormatter,\n )\n assert client.get_default_headers() == {}\n client.set_default_headers({\"first\": \"header\"})\n assert client.get_default_headers() == {\"first\": \"header\"}\n # Setting the default headers should overwrite the original\n client.set_default_headers({\"second\": \"header\"})\n assert client.get_default_headers() == {\"second\": \"header\"}\n\n\ndef test_set_and_get_default_query_params():\n client = Client(\n authentication_method=NoAuthentication(),\n response_handler=MockResponseHandler,\n request_formatter=MockRequestFormatter,\n )\n assert client.get_default_query_params() == {}\n client.set_default_query_params({\"first\": \"header\"})\n assert client.get_default_query_params() == {\"first\": \"header\"}\n # Setting the default query params should overwrite the original\n client.set_default_query_params({\"second\": \"header\"})\n assert client.get_default_query_params() == {\"second\": \"header\"}\n\n\ndef test_set_and_get_default_username_password_authentication():\n client = Client(\n authentication_method=NoAuthentication(),\n response_handler=MockResponseHandler,\n request_formatter=MockRequestFormatter,\n )\n assert client.get_default_username_password_authentication() is None\n client.set_default_username_password_authentication((\"username\", \"password\"))\n assert client.get_default_username_password_authentication() == (\"username\", \"password\")\n # Setting the default username password should overwrite the original\n client.set_default_username_password_authentication((\"username\", \"morecomplicatedpassword\"))\n assert client.get_default_username_password_authentication() == (\"username\", \"morecomplicatedpassword\")\n\n\n@patch(\"apiclient.client.requests\")\ndef test_create_method_success(mock_requests):\n mock_requests.post.return_value.status_code = 201\n client.create(sentinel.url, data={\"foo\": \"bar\"})\n mock_requests.post.assert_called_once_with(\n sentinel.url, auth=None, headers={}, data={\"foo\": \"bar\"}, params={}, timeout=10.0\n )\n\n\n@patch(\"apiclient.client.requests\")\ndef test_read_method_success(mock_requests):\n mock_requests.get.return_value.status_code = 200\n client.read(sentinel.url)\n mock_requests.get.assert_called_once_with(\n sentinel.url, auth=None, headers={}, params={}, data=None, timeout=10.0\n )\n\n\n@patch(\"apiclient.client.requests\")\ndef test_replace_method_success(mock_requests):\n mock_requests.put.return_value.status_code = 200\n client.replace(sentinel.url, data={\"foo\": \"bar\"})\n mock_requests.put.assert_called_once_with(\n sentinel.url, auth=None, headers={}, data={\"foo\": \"bar\"}, params={}, timeout=10.0\n )\n\n\n@patch(\"apiclient.client.requests\")\ndef test_update_method_success(mock_requests):\n mock_requests.patch.return_value.status_code = 200\n client.update(sentinel.url, data={\"foo\": \"bar\"})\n mock_requests.patch.assert_called_once_with(\n sentinel.url, auth=None, headers={}, data={\"foo\": \"bar\"}, params={}, timeout=10.0\n )\n\n\n@patch(\"apiclient.client.requests\")\ndef test_delete_method_success(mock_requests):\n mock_requests.delete.return_value.status_code = 200\n client.delete(sentinel.url)\n mock_requests.delete.assert_called_once_with(\n sentinel.url, auth=None, headers={}, params={}, data=None, timeout=10.0\n )\n\n\n@pytest.mark.parametrize(\n \"client_method,client_args,patch_methodname\",\n [\n (client.create, (sentinel.url, {\"foo\": \"bar\"}), \"apiclient.client.requests.post\"),\n (client.read, (sentinel.url,), \"apiclient.client.requests.get\"),\n (client.replace, (sentinel.url, {\"foo\": \"bar\"}), \"apiclient.client.requests.put\"),\n (client.update, (sentinel.url, {\"foo\": \"bar\"}), \"apiclient.client.requests.patch\"),\n (client.delete, (sentinel.url,), \"apiclient.client.requests.delete\"),\n ],\n)\ndef test_make_request_error_raises_and_logs_unexpected_error(\n client_method, client_args, patch_methodname, caplog\n):\n caplog.set_level(level=logging.ERROR, logger=client_logger.name)\n with patch(patch_methodname) as mock_requests_method:\n mock_requests_method.side_effect = (ValueError(\"Error raised for testing\"),)\n with pytest.raises(UnexpectedError) as exc_info:\n client_method(*client_args)\n assert str(exc_info.value) == \"Error when contacting 'sentinel.url'\"\n messages = [r.message for r in caplog.records if r.levelno == logging.ERROR]\n assert \"An error occurred when contacting sentinel.url\" in messages\n\n\n@pytest.mark.parametrize(\n \"client_method,client_args,patch_methodname\",\n [\n (client.create, (sentinel.url, {\"foo\": \"bar\"}), \"apiclient.client.requests.post\"),\n (client.read, (sentinel.url,), \"apiclient.client.requests.get\"),\n (client.replace, (sentinel.url, {\"foo\": \"bar\"}), \"apiclient.client.requests.put\"),\n (client.update, (sentinel.url, {\"foo\": \"bar\"}), \"apiclient.client.requests.patch\"),\n (client.delete, (sentinel.url,), \"apiclient.client.requests.delete\"),\n ],\n)\ndef test_server_error_raises_and_logs_client_server_error(\n client_method, client_args, patch_methodname, caplog\n):\n caplog.set_level(level=logging.WARNING, logger=client_logger.name)\n with patch(patch_methodname) as mock_requests_method:\n mock_requests_method.return_value.status_code = 500\n mock_requests_method.return_value.url = sentinel.url\n mock_requests_method.return_value.reason = \"A TEST server error occurred\"\n mock_requests_method.return_value.text = \"{'foo': 'bar'}\"\n\n with pytest.raises(ServerError) as exc_info:\n client_method(*client_args)\n assert str(exc_info.value) == \"500 Error: A TEST server error occurred for url: sentinel.url\"\n messages = [r.message for r in caplog.records if r.levelno == logging.WARNING]\n assert \"500 Error: A TEST server error occurred for url: sentinel.url. data={'foo': 'bar'}\" in messages\n\n\n@pytest.mark.parametrize(\n \"client_method,client_args,patch_methodname\",\n [\n (client.create, (sentinel.url, {\"foo\": \"bar\"}), \"apiclient.client.requests.post\"),\n (client.read, (sentinel.url,), \"apiclient.client.requests.get\"),\n (client.replace, (sentinel.url, {\"foo\": \"bar\"}), \"apiclient.client.requests.put\"),\n (client.update, (sentinel.url, {\"foo\": \"bar\"}), \"apiclient.client.requests.patch\"),\n (client.delete, (sentinel.url,), \"apiclient.client.requests.delete\"),\n ],\n)\ndef test_not_modified_response_raises_and_logs_client_redirection_error(\n client_method, client_args, patch_methodname, caplog\n):\n caplog.set_level(level=logging.ERROR, logger=client_logger.name)\n with patch(patch_methodname) as mock_requests_method:\n mock_requests_method.return_value.status_code = 304\n mock_requests_method.return_value.url = sentinel.url\n mock_requests_method.return_value.reason = \"A TEST redirection error occurred\"\n mock_requests_method.return_value.text = \"{'foo': 'bar'}\"\n\n with pytest.raises(RedirectionError) as exc_info:\n client_method(*client_args)\n assert str(exc_info.value) == \"304 Error: A TEST redirection error occurred for url: sentinel.url\"\n messages = [r.message for r in caplog.records if r.levelno == logging.ERROR]\n assert (\n \"304 Error: A TEST redirection error occurred for url: sentinel.url. data={'foo': 'bar'}\" in messages\n )\n\n\n@pytest.mark.parametrize(\n \"client_method,client_args,patch_methodname\",\n [\n (client.create, (sentinel.url, {\"foo\": \"bar\"}), \"apiclient.client.requests.post\"),\n (client.read, (sentinel.url,), \"apiclient.client.requests.get\"),\n (client.replace, (sentinel.url, {\"foo\": \"bar\"}), \"apiclient.client.requests.put\"),\n (client.update, (sentinel.url, {\"foo\": \"bar\"}), \"apiclient.client.requests.patch\"),\n (client.delete, (sentinel.url,), \"apiclient.client.requests.delete\"),\n ],\n)\ndef test_not_found_response_raises_and_logs_client_bad_request_error(\n client_method, client_args, patch_methodname, caplog\n):\n caplog.set_level(level=logging.ERROR, logger=client_logger.name)\n with patch(patch_methodname) as mock_requests_method:\n mock_requests_method.return_value.status_code = 404\n mock_requests_method.return_value.url = sentinel.url\n mock_requests_method.return_value.reason = \"A TEST not found error occurred\"\n mock_requests_method.return_value.text = \"{'foo': 'bar'}\"\n\n with pytest.raises(ClientError) as exc_info:\n client_method(*client_args)\n assert str(exc_info.value) == \"404 Error: A TEST not found error occurred for url: sentinel.url\"\n messages = [r.message for r in caplog.records if r.levelno == logging.ERROR]\n assert (\n \"404 Error: A TEST not found error occurred for url: sentinel.url. data={'foo': 'bar'}\" in messages\n )\n\n\n@pytest.mark.parametrize(\n \"client_method,client_args,patch_methodname\",\n [\n (client.create, (sentinel.url, {\"foo\": \"bar\"}), \"apiclient.client.requests.post\"),\n (client.read, (sentinel.url,), \"apiclient.client.requests.get\"),\n (client.replace, (sentinel.url, {\"foo\": \"bar\"}), \"apiclient.client.requests.put\"),\n (client.update, (sentinel.url, {\"foo\": \"bar\"}), \"apiclient.client.requests.patch\"),\n (client.delete, (sentinel.url,), \"apiclient.client.requests.delete\"),\n ],\n)\ndef test_unexpected_status_code_response_raises_and_logs_unexpected_error(\n client_method, client_args, patch_methodname, caplog\n):\n caplog.set_level(level=logging.ERROR, logger=client_logger.name)\n with patch(patch_methodname) as mock_requests_method:\n mock_requests_method.return_value.status_code = 100\n mock_requests_method.return_value.url = sentinel.url\n mock_requests_method.return_value.reason = \"A TEST bad status code error occurred\"\n mock_requests_method.return_value.text = \"{'foo': 'bar'}\"\n\n with pytest.raises(UnexpectedError) as exc_info:\n client_method(*client_args)\n assert str(exc_info.value) == \"100 Error: A TEST bad status code error occurred for url: sentinel.url\"\n messages = [r.message for r in caplog.records if r.levelno == logging.ERROR]\n expected_log_message = (\n \"100 Error: A TEST bad status code error occurred for url: sentinel.url. \" \"data={'foo': 'bar'}\"\n )\n assert expected_log_message in messages\n\n\n@pytest.mark.parametrize(\n \"client_method,client_args,patch_methodname\",\n [\n (client.read, (sentinel.url,), \"apiclient.client.requests.get\"),\n (client.replace, (sentinel.url, {\"foo\": \"bar\"}), \"apiclient.client.requests.put\"),\n (client.update, (sentinel.url, {\"foo\": \"bar\"}), \"apiclient.client.requests.patch\"),\n (client.delete, (sentinel.url,), \"apiclient.client.requests.delete\"),\n ],\n)\ndef test_query_params_are_updated_and_not_overwritten(client_method, client_args, patch_methodname):\n # Params are not expected on POST endpoints, so this method is not placed under test.\n with patch(patch_methodname) as mock_requests_method:\n mock_requests_method.return_value.status_code = 200\n\n client_method(*client_args, params={\"New\": \"Header\"})\n\n assert mock_requests_method.call_count == 1\n args, kwargs = mock_requests_method.call_args\n assert \"params\" in kwargs\n assert kwargs[\"params\"][\"New\"] == \"Header\"\n\n\n@pytest.mark.parametrize(\n \"client_method,client_args,patch_methodname\",\n [\n (client.create, (sentinel.url, {\"foo\": \"bar\"}), \"apiclient.client.requests.post\"),\n (client.read, (sentinel.url,), \"apiclient.client.requests.get\"),\n (client.replace, (sentinel.url, {\"foo\": \"bar\"}), \"apiclient.client.requests.put\"),\n (client.update, (sentinel.url, {\"foo\": \"bar\"}), \"apiclient.client.requests.patch\"),\n (client.delete, (sentinel.url,), \"apiclient.client.requests.delete\"),\n ],\n)\ndef test_delegates_to_response_handler(client_method, client_args, patch_methodname):\n mock_response_handler_call.reset_mock()\n\n with patch(patch_methodname) as mock_requests_method:\n requests_response = Mock(status_code=200)\n mock_requests_method.return_value = requests_response\n\n client_method(*client_args)\n\n mock_response_handler_call.assert_called_once_with(requests_response)\n\n\n@pytest.mark.parametrize(\n \"client_method,url,patch_methodname\",\n [\n (client.create, sentinel.url, \"apiclient.client.requests.post\"),\n (client.replace, sentinel.url, \"apiclient.client.requests.put\"),\n (client.update, sentinel.url, \"apiclient.client.requests.patch\"),\n ],\n)\ndef test_data_parsing_delegates_to_request_formatter(client_method, url, patch_methodname):\n # GET and DELETE requests dont pass data so they are not being tested\n mock_request_formatter_call.reset_mock()\n\n with patch(patch_methodname) as mock_requests_method:\n requests_response = Mock(status_code=200)\n mock_requests_method.return_value = requests_response\n\n client_method(url, sentinel.data)\n\n mock_request_formatter_call.assert_called_once_with(sentinel.data)\n\n\ndef test_read_real_world_api(json_placeholder_cassette):\n client = JSONPlaceholderClient(\n authentication_method=NoAuthentication(),\n response_handler=JsonResponseHandler,\n request_formatter=JsonRequestFormatter,\n )\n assert len(client.get_all_todos()) == 200\n\n expected_todo = {\n \"completed\": False,\n \"id\": 45,\n \"title\": \"velit soluta adipisci molestias reiciendis harum\",\n \"userId\": 3,\n }\n assert client.get_todo(45) == expected_todo\n\n\n@pytest.mark.parametrize(\n \"status_code,expected_exception\",\n [\n (HTTPStatus.MULTIPLE_CHOICES, exceptions.MultipleChoices),\n (HTTPStatus.MOVED_PERMANENTLY, exceptions.MovedPermanently),\n (HTTPStatus.FOUND, exceptions.Found),\n (HTTPStatus.SEE_OTHER, exceptions.SeeOther),\n (HTTPStatus.NOT_MODIFIED, exceptions.NotModified),\n (HTTPStatus.USE_PROXY, exceptions.UseProxy),\n (HTTPStatus.TEMPORARY_REDIRECT, exceptions.TemporaryRedirect),\n (HTTPStatus.PERMANENT_REDIRECT, exceptions.PermanentRedirect),\n (HTTPStatus.BAD_REQUEST, exceptions.BadRequest),\n (HTTPStatus.UNAUTHORIZED, exceptions.Unauthorized),\n (HTTPStatus.PAYMENT_REQUIRED, exceptions.PaymentRequired),\n (HTTPStatus.FORBIDDEN, exceptions.Forbidden),\n (HTTPStatus.NOT_FOUND, exceptions.NotFound),\n (HTTPStatus.NOT_ACCEPTABLE, exceptions.NotAcceptable),\n (HTTPStatus.PROXY_AUTHENTICATION_REQUIRED, exceptions.ProxyAuthenticationRequired),\n (HTTPStatus.REQUEST_TIMEOUT, exceptions.RequestTimeout),\n (HTTPStatus.CONFLICT, exceptions.Conflict),\n (HTTPStatus.GONE, exceptions.Gone),\n (HTTPStatus.LENGTH_REQUIRED, exceptions.LengthRequired),\n (HTTPStatus.PRECONDITION_FAILED, exceptions.PreconditionFailed),\n (HTTPStatus.REQUEST_ENTITY_TOO_LARGE, exceptions.RequestEntityTooLarge),\n (HTTPStatus.REQUEST_URI_TOO_LONG, exceptions.RequestUriTooLong),\n (HTTPStatus.UNSUPPORTED_MEDIA_TYPE, exceptions.UnsupportedMediaType),\n (HTTPStatus.REQUESTED_RANGE_NOT_SATISFIABLE, exceptions.RequestedRangeNotSatisfiable),\n (HTTPStatus.EXPECTATION_FAILED, exceptions.ExpectationFailed),\n (HTTPStatus.UNPROCESSABLE_ENTITY, exceptions.UnprocessableEntity),\n (HTTPStatus.LOCKED, exceptions.Locked),\n (HTTPStatus.FAILED_DEPENDENCY, exceptions.FailedDependency),\n (HTTPStatus.UPGRADE_REQUIRED, exceptions.UpgradeRequired),\n (HTTPStatus.PRECONDITION_REQUIRED, exceptions.PreconditionRequired),\n (HTTPStatus.TOO_MANY_REQUESTS, exceptions.TooManyRequests),\n (HTTPStatus.REQUEST_HEADER_FIELDS_TOO_LARGE, exceptions.RequestHeaderFieldsTooLarge),\n (HTTPStatus.INTERNAL_SERVER_ERROR, exceptions.InternalServerError),\n (HTTPStatus.NOT_IMPLEMENTED, exceptions.NotImplemented),\n (HTTPStatus.BAD_GATEWAY, exceptions.BadGateway),\n (HTTPStatus.SERVICE_UNAVAILABLE, exceptions.ServiceUnavailable),\n (HTTPStatus.GATEWAY_TIMEOUT, exceptions.GatewayTimeout),\n (HTTPStatus.HTTP_VERSION_NOT_SUPPORTED, exceptions.HttpVersionNotSupported),\n (HTTPStatus.VARIANT_ALSO_NEGOTIATES, exceptions.VariantAlsoNegotiates),\n (HTTPStatus.INSUFFICIENT_STORAGE, exceptions.InsufficientStorage),\n (HTTPStatus.LOOP_DETECTED, exceptions.LoopDetected),\n (HTTPStatus.NOT_EXTENDED, exceptions.NotExtended),\n (HTTPStatus.NETWORK_AUTHENTICATION_REQUIRED, exceptions.NetworkAuthenticationRequired),\n ],\n)\ndef test_exceptions_get_mapped_correctly_by_response_status_code(status_code, expected_exception):\n with patch(\"apiclient.client.requests.get\") as mock_get:\n mock_get.return_value.status_code = status_code\n\n with pytest.raises(expected_exception):\n client.read(sentinel.url)\n","sub_path":"tests/test_client.py","file_name":"test_client.py","file_ext":"py","file_size_in_byte":19946,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"356297752","text":"from env import Maze\nfrom test15_Sarsa_1 import QLearningTable\n\n\ndef update():\n for epoch in range(100):\n\n observation = env.reset()\n\n action = RL.choose_action(str(observation))\n\n while True:\n env.render()\n\n observation_, r, done = env.step(action)\n\n action_ = RL.choose_action(str(observation_))\n\n RL.learn(str(observation), action, r, str(observation_), action_)\n\n observation = observation_\n action = action_\n\n if done:\n break\n\n env.destroy()\n\n\nenv = Maze()\nRL = QLearningTable(actions=list(range(env.n_actions)))\nenv.after(100, update)\nenv.mainloop()\n","sub_path":"test15_Sarsa_2.py","file_name":"test15_Sarsa_2.py","file_ext":"py","file_size_in_byte":675,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"426659654","text":"import numpy as np\nfrom scipy import signal\nimport matplotlib.pyplot as plt\nfrom pyvib.forcing import multisine\nfrom pyvib.common import db\n\n\ndef plot(sig):\n plt.figure()\n for i, u in enumerate(sig):\n U = np.fft.fft(u)\n plt.subplot(2,2,1+i)\n plt.plot(db(U),'+')\n plt.xlabel('Frequency line')\n plt.ylabel('Amplitude (dB)')\n plt.title(f'Phase realization {i+1}')\n plt.subplot(2,2,3+i)\n plt.plot(np.angle(U),'+')\n plt.xlabel('Frequency line')\n plt.ylabel('Phase (rad)')\n plt.title(f'Phase realization {i+1}')\n\n\n# Generate two realizations of a full multisine with 1000 samples and\n# excitation up to one third of the Nyquist frequency\nN = 1000 # One thousand samples\nkind = 'full' # Full multisine\nf2 = round(N//6) # Excitation up to one sixth of the sample frequency\nR = 2 # Two phase realizations\nu, lines, freq = multisine(f2=f2,N=N,lines=kind,R=R)\n# Check spectra\nplot(u)\n# The two realizations have the same amplitude spectrum, but different phase\n# realizations (uniformly distributed between [-π,π))\n\n# Generate a random odd multisine where the excited odd lines are split in\n# groups of three consecutive lines and where one line is randomly chosen in\n# each group to be a detection line (i.e. without excitation)\nN = 1000\nkind = 'oddrandom'\nf2 = round(N//6)\nR = 1\n# One out of three consecutive odd lines is randomly selected to be a detection line\nngroup = 3\nu1,lines, freq = multisine(f2=f2,N=N,lines=kind,R=R,ngroup=ngroup)\n# Generate another phase realization of this multisine with the same excited\n# lines and detection lines\nu2,*_ = multisine(N=N,lines=lines,R=1)\nplot((u1[0], u2[0]))\n\n# Change the coloring and rms level of a default multisine\nu3 = multisine()[0][0]\nb, a = signal.cheby1(2,10,2*0.1) # Filter coefficients\nU3 = np.fft.fft(u3)\nworN = 2*np.pi*np.arange(len(u3))/len(u3)\nw, h = signal.freqz(b,a,worN)\nU_colored = h * U3 # Filtered spectrum\nu_colored = np.real(np.fft.ifft(U_colored)) # Colored multisine signal\nu_scaled = 2*u_colored/np.std(u_colored) # Scaled signal to rms value 2\n# (u_colored is zero-mean)\nplot((u3,u_scaled))\n\nplt.show()\n","sub_path":"examples/pnlss/multisine.py","file_name":"multisine.py","file_ext":"py","file_size_in_byte":2163,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"538748489","text":"import torch\nfrom torch.autograd import Variable\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch import optim\nimport pickle\nimport numpy as np\nfrom PIL import Image\nimport pickle\nfrom scipy.stats import lognorm\n\nfrom src.data.mat_data import getMatData, matDataLoader\nfrom src.models.simple_net import RobustNet\n\n\ndef test():\n allAccuracy =[]\n allWrongs = []\n for batch_idx, (data, target) in enumerate(matDataLoader(testData, testLabels, batchSize, shuffle=False)):\n data_temp = np.copy(data)\n data, target = Variable(data), Variable(target)\n data, target = data.cuda(), target.cuda()\n data = data.view(-1, dimIn)\n Net.eval()\n net_out = Net(data)\n prediction = net_out.max(1)[1]\n selector = (prediction != target).cpu().numpy().astype(np.bool)\n wrongs = data_temp[selector]\n testAcc = list((prediction == target).cpu().numpy())\n if not sum(testAcc) == len(target) and False:\n print(prediction.cpu().numpy()[testAcc == 0])\n print(target.cpu().numpy()[testAcc==0])\n allAccuracy.extend(testAcc)\n allWrongs.extend(wrongs)\n print(f\"Test accuracy is {np.mean(allAccuracy)}\")\n\n\ndef train():\n for epoch in range(epochs):\n epochAcc = []\n lossArr = []\n for batch_idx, (data, target) in enumerate(matDataLoader(trainData, trainLabels, batchSize, shuffle=True)):\n data, target = Variable(data), Variable(target)\n data, target = data.cuda(), target.cuda()\n data = data.view(-1, dimIn)\n optimizer.zero_grad()\n Net.train()\n net_out = Net(data)\n prediction = net_out.max(1)[1]\n loss = criterion(net_out, target)\n loss.backward()\n optimizer.step()\n currAcc = (prediction == target).cpu().numpy()\n epochAcc.extend(list(currAcc))\n lossArr.append(loss.data.item())\n print(f\"Train epoch: {epoch}, loss is {np.mean(lossArr)}, accuracy is {np.mean(epochAcc)}\")\n if epoch % test_interval == 0:\n test()\n\n\n# relevant variables\ndimIn = 249*249\ndimOut = 2\nlearning_rate = 0.000001\nepochs = 200\nlog_interval = 2\ntest_interval = 2\nbatchSize = 800\npathMat = \"data/processed/freq_8_contrast_001_sample.mat\"\n\ndata, labels = getMatData(pathMat, shuffle=True, extraNoise=True)\ndata = torch.from_numpy(data).type(torch.float32)\npickle.dump([data, labels], open('mat1PercentData.p', 'wb'))\n# data, labels = pickle.load(open(\"mat1PercentData.p\", 'rb'))\ndimIn = data[0].shape[1]**2\n# denoise data!\ndataStd = data.std()\ndataMean = data.mean()\ndata = data-dataMean\ndata[data>dataStd] = 0\ndata[data<-dataStd] = 0\ndata = data.sign()*(data.abs()+1).log()\n# Image.fromarray(data[4]*(255/20)).show()\nlabels = torch.from_numpy(labels.astype(np.long))\ntestData = data[:int(len(data)*0.2)]\ntestLabels = labels[:int(len(data)*0.2)]\ntrainData = data[int(len(data)*0.2):]\ntrainLabels = labels[int(len(data)*0.2):]\n\nNet = RobustNet(dimIn=dimIn, dimOut=dimOut, dropout=0.2)\nNet.cuda()\nNet.load_state_dict(torch.load('trained_RobustNet_denoised.torch'))\nprint(Net)\n\noptimizer = optim.Adam(Net.parameters(), lr=learning_rate)\ncriterion = nn.NLLLoss()\n# Train the network\ntrain()\n\nlearning_rate=0.0000001\noptimizer = optim.Adam(Net.parameters(), lr=learning_rate, amsgrad=True)\nepochs = 50\n\n# Train the network more\ntrain()\n\ntorch.save(Net.state_dict(), \"trained_RobustNet_denoised.torch\")\n\nprint('\\nDone!')\n","sub_path":"deepLearning/simpleNet_experiment.py","file_name":"simpleNet_experiment.py","file_ext":"py","file_size_in_byte":3486,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"407917198","text":"# 203. Remove Linked List Elements\n\n# 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 removeElements(self, head: 'ListNode', val: 'int') -> 'ListNode':\n fakehead = ListNode(None)\n fakehead.next = head\n curr = fakehead\n while curr and curr.next:\n if curr.next.val == val:\n curr.next =curr.next.next\n else:\n curr = curr.next\n return fakehead.next\n \n ","sub_path":"203.py","file_name":"203.py","file_ext":"py","file_size_in_byte":570,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"508091383","text":"def rev(myString):\n\n strList = list(myString)\n newList = []\n for i in range(len(strList)):\n i = -(i + 1)\n newList.append(str(list(strList[i])))\n revString = ''.join(newList)\n return revString\n\nprint(rev(\"magdalena\"))\n\n\ndef rever(x):\n output = \"\"\n for c in x:\n output = c + output\n\n return output\n\nprint(rever(\"magda\"))","sub_path":"various.py","file_name":"various.py","file_ext":"py","file_size_in_byte":363,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"167186249","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom hashlib import md5\n\nREQUEST_UNKNOW = 0\nREQUEST_GOODBYE = 1\nREQUEST_FILE = 2\nREQUEST_LOG = 3\nREQUEST_PING = 4\nREQUEST_PONG = 5\n\nclass Request(object):\n \"\"\"\n Base request class\n \"\"\"\n\n def __init__(self):\n \"\"\"\n Constructor\n \"\"\"\n self._type = REQUEST_UNKNOW\n\n def get_type(self):\n \"\"\"\n Return request type\n\n Returns:\n int: request type\n \"\"\"\n return self._type\n\n def __str__(self):\n \"\"\"\n To string method\n \"\"\"\n raise NotImplementedError('Method __str__ is not implemented!')\n\n def log_str(self):\n \"\"\"\n To log\n \"\"\"\n return self.__str__()\n\n def from_dict(self, request):\n \"\"\"\n Fill request with specified dict\n\n Args:\n request (dict): request under dict format\n \"\"\"\n raise NotImplementedError('Method from_dict is not implemented!')\n\n def to_dict(self):\n \"\"\"\n Convert object to dict for easier json/bson conversion\n\n Return:\n dict: class member onto dict\n \"\"\"\n return {\n u'_type': self._type\n }\n\n\n\n\n\nclass RequestGoodbye(Request):\n def __init__(self):\n \"\"\"\n Constructor\n \"\"\"\n self._type = REQUEST_GOODBYE\n\n def __str__(self):\n \"\"\"\n To string method\n \"\"\"\n return u'RequestGoodbye()'\n\n def from_dict(self, request):\n \"\"\"\n Fill request with specified dict\n\n Args:\n request (dict): request under dict format\n \"\"\"\n return {}\n\n\n\n\n\nclass RequestPing(Request):\n def __init__(self):\n \"\"\"\n Constructor\n \"\"\"\n self._type = REQUEST_PING\n\n def __str__(self):\n \"\"\"\n To string method\n \"\"\"\n return u'RequestPing()'\n\n def from_dict(self, request):\n \"\"\"\n Fill request with specified dict\n\n Args:\n request (dict): request under dict format\n \"\"\"\n return {}\n\n\n\n\nclass RequestPong(Request):\n def __init__(self):\n \"\"\"\n Constructor\n \"\"\"\n self._type = REQUEST_PONG\n\n def __str__(self):\n \"\"\"\n To string method\n \"\"\"\n return u'RequestPong()'\n\n def from_dict(self, request):\n \"\"\"\n Fill request with specified dict\n\n Args:\n request (dict): request under dict format\n \"\"\"\n return {}\n\n\n\n\n\nclass RequestFile(Request):\n \"\"\"\n Request for file changes\n \"\"\"\n\n ACTION_UPDATE = 0\n ACTION_MOVE = 1\n ACTION_CREATE = 2\n ACTION_DELETE = 3\n\n TYPE_FILE = 0\n TYPE_FILE_STR = u'FILE'\n TYPE_DIR = 1\n TYPE_DIR_STR = u'DIR'\n\n def __init__(self):\n \"\"\"\n Constructor\n \"\"\"\n #request type\n self._type = REQUEST_FILE\n #file action\n self.action = None\n #mode: file or directory\n self.mode = None\n #source file path\n self.src = None\n #destination file path \n self.dest = None\n #file content for some actions (create, update)\n self.content = u''\n #file content md5 needed to avoid circular copy\n self.md5 = None\n\n def __str__(self):\n \"\"\"\n To string method\n \"\"\"\n action = None\n if self.action == self.ACTION_UPDATE:\n action = u'UPDATE'\n elif self.action == self.ACTION_MOVE:\n action = u'MOVE'\n elif self.action == self.ACTION_CREATE:\n action = u'CREATE'\n elif self.action == self.ACTION_DELETE:\n action = u'DELETE'\n\n type = None\n if self.type == self.TYPE_DIR:\n type = self.TYPE_DIR_STR\n else:\n type = self.TYPE_FILE_STR\n\n return u'RequestFile(action:%s, type:%s, src:%s, dest:%s, content:%d bytes md5:%s)' % (action, type, self.src, self.dest, len(self.content), self.md5)\n\n def log_str(self):\n \"\"\"\n Return log string\n\n Returns:\n string\n \"\"\"\n action = None\n if self.action == self.ACTION_UPDATE:\n action = u'Update'\n elif self.action == self.ACTION_MOVE:\n action = u'Move'\n elif self.action == self.ACTION_CREATE:\n action = u'Create'\n elif self.action == self.ACTION_DELETE:\n action = u'Delete'\n\n type_ = None\n if self.type == self.TYPE_DIR:\n type_ = self.TYPE_DIR_STR\n else:\n type_ = self.TYPE_FILE_STR\n\n if self.action in (self.ACTION_UPDATE, self.ACTION_CREATE):\n return u'%s %s %s (%d bytes md5:%s)' % (action, type_, self.src, len(self.content), self.md5)\n elif self.action == self.ACTION_DELETE:\n return u'%s %s %s' % (action, type_, self.src)\n else:\n return u'%s %s %s to %s' % (action, type_, self.src, self.dest)\n\n def from_dict(self, request):\n \"\"\"\n Fill request with specified dict\n\n Args:\n request (dict): request under dict format\n \"\"\"\n for key in list(request.keys()):\n if key == u'action':\n self.action = request[key]\n elif key == u'type':\n self.type = request[key]\n elif key == u'src':\n self.src = request[key]\n elif key == u'dest':\n self.dest = request[key]\n if key == u'content':\n self.content = request[key]\n if key == u'md5':\n self.md5 = request[key]\n\n def to_dict(self):\n \"\"\"\n Convert object to dict for easier json/bson conversion\n\n Return:\n dict: class member onto dict\n \"\"\"\n out = {\n u'_type': self._type,\n u'action': self.action,\n u'type': self.type,\n u'src': self.src,\n u'md5': self.md5\n }\n if self.dest:\n out[u'dest'] = self.dest\n if len(self.content) > 0:\n out[u'content'] = self.content\n\n return out\n\n\n\n\n\n\nclass RequestLog(Request):\n \"\"\"\n Request for log changes\n \"\"\"\n def __init__(self):\n \"\"\"\n Constructor\n \"\"\"\n #request type\n self._type = REQUEST_LOG\n #contain exception record\n self.log_record = None\n #contain log message\n self.log_message = None\n\n def __str__(self):\n \"\"\"\n To string\n \"\"\"\n if self.log_record:\n return u'RequestLog(log_record: %s)' % self.log_record['msg']\n elif self.log_message:\n return u'RequestLog(log_message: %s)' % self.log_message\n else:\n return u'RequestLog(empty)'\n\n def is_empty(self):\n \"\"\"\n Return True if empty\n\n Returns:\n bool\n \"\"\"\n if self.log_record or self.log_message:\n return False\n\n return True\n\n def from_dict(self, request):\n \"\"\"\n Fill request with specified dict\n\n Args:\n request (dict): request under dict format\n \"\"\"\n for key in list(request.keys()):\n if key == u'log_record':\n self.log_record = request[key]\n elif key == u'log_message':\n self.log_message = request[key]\n\n def to_dict(self):\n \"\"\"\n Convert object to dict for easier json/bson conversion\n\n Return:\n dict: class member onto dict\n \"\"\"\n out = {\n u'_type': self._type,\n u'log_record': self.log_record,\n u'log_message': self.log_message\n }\n\n return out\n\n","sub_path":"pyremotedev/request.py","file_name":"request.py","file_ext":"py","file_size_in_byte":7675,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"420114857","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.5 (62131)\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.3-fat/egg/wsgixml/util.py\n# Compiled at: 2006-09-19 09:39:26\nfrom urllib import quote\n\nclass iterwrapper:\n \"\"\"\n Wraps the response body iterator from the application to meet WSGI\n requirements.\n \"\"\"\n\n def __init__(self, wrapped, responder):\n \"\"\"\n wrapped - the iterator coming from the application\n response_chunk_handler - a callable for any processing of a\n response body chunk before passing it on to the server.\n \"\"\"\n self._wrapped = iter(wrapped)\n self._responder = responder(self._wrapped)\n if hasattr(wrapped, 'close'):\n self.close = self._wrapped.close\n\n def __iter__(self):\n return self\n\n def next(self):\n return self._responder.next()\n\n\ndef get_request_url(environ):\n url = environ['wsgi.url_scheme'] + '://'\n if environ.get('HTTP_HOST'):\n url += environ['HTTP_HOST']\n else:\n url += environ['SERVER_NAME']\n if environ['wsgi.url_scheme'] == 'https':\n if environ['SERVER_PORT'] != '443':\n url += ':' + environ['SERVER_PORT']\n elif environ['SERVER_PORT'] != '80':\n url += ':' + environ['SERVER_PORT']\n url += quote(environ.get('SCRIPT_NAME', ''))\n url += quote(environ.get('PATH_INFO', ''))\n if environ.get('QUERY_STRING'):\n url += '?' + environ['QUERY_STRING']\n return url","sub_path":"pycfiles/wsgixml-0.3-py2.5/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":1560,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"549985537","text":"\"\"\"\n练习:\n使用urllib.request 和 正则表达式\n来完成对内涵段子网页中所有的内涵段子的获取和保存\n\n内涵段子网站:\nhttp://neihanba.92kaifa.com/wenzi/\nhttp://neihanba.92kaifa.com/wenzi/index_2.html\nhttp://neihanba.92kaifa.com/wenzi/index_3.html\n\n可以发现:除了首页之外其余的页面都是在网址中加入/index_数字.html\n\n发现了网页的规律之后呢还需要查看网页的源码来观察对应段子的标签是什么\n\n查看对应网站的源码:\n

\n
\n\t夏天为了穿裙子,在网上拍了个安全裤,货到了,同事问我:买了什么?我说:安全裤。她竟然反问我:穿上这个就不会怀孕了?
\n\n\n
\n\n网页中所有的段子对应的信息都是上面的格式,因此便可以指定对应的正则表达式来进行匹配\n注意得取消正则表达式的贪婪模式\n\npattern = re.compile('\\s+
\\s+(.*?)\\s+
')\n\n\n最后遇到问题:\nurllib.error.HTTPError: HTTP Error 504: Gateway Timeout\n网关超时,暂时无解\n\"\"\"\nimport urllib.request\nimport re\nimport random\n\n\nclass Spider(object):\n \"\"\"\n 创建爬虫类来爬取内涵吧网站中所有的内涵段子\n \"\"\"\n def __init__(self):\n \"\"\"\n 初始化方法\n \"\"\"\n # 指定所需要爬取的静态页面路径\n self.url = \"http://neihanba.92kaifa.com/wenzi/\"\n # 是否进行爬取的开关,默认为true\n self.switch = True\n # user-agent可以是一个列表\n self.ag_list = [\n \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10.6; rv2.0.1) Gecko/20100101 Firefox/4.0.1\",\n \"Mozilla/5.0 (Windows NT 6.1; rv2.0.1) Gecko/20100101 Firefox/4.0.1\",\n \"Opera/9.80 (Macintosh; Intel Mac OS X 10.6.8; U; en) Presto/2.8.131 Version/11.11\",\n \"Opera/9.80 (Windows NT 6.1; U; en) Presto/2.8.131 Version/11.11\",\n \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_0) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.56 Safari/535.11\"\n ]\n # 正则表达式(取消贪婪模式)(注意正则里面的是双引号,加入是单引号的话就不对了)\n self.pattern = re.compile(r'\\s+
\\s+(.*?)\\s+
', re.S)\n # 对每一条段子进行编号\n self.num = 1\n\n def get_html(self, page_num):\n \"\"\"\n 获取页面信息\n :param:page_num 表示所要爬取的指定页面\n :return:\n \"\"\"\n print('开始下载第'+str(page_num)+'页...')\n # 构造url\n if page_num != 1:\n full_url = self.url+\"index_\"+str(page_num)+\".html\"\n else:\n full_url = self.url\n request = urllib.request.Request(full_url)\n # 在user-agent列表里随机选择一个做为user-agent\n user_agent = random.choice(self.ag_list)\n # 使用add_header方法来添加或者修改一个http报头\n request.add_header('User-Agent', user_agent)\n response = urllib.request.urlopen(request)\n\n # 爬取到的网页源码\n html = response.read().decode(\"utf-8\")\n # print(html)\n # 利用正则表达式将网页中的内涵段子提取出来\n nei_han_list = self.pattern.findall(html)\n # print(len(nei_han_list))\n # 对所有的段子进行处理\n self.get_content(nei_han_list)\n\n def write_content(self, content):\n \"\"\"\n 将信息写入到文件中保存下来\n :return:\n \"\"\"\n print('开始保存第'+str(self.num)+'个段子...')\n with open('duanzi.txt', 'a') as duan_zi:\n duan_zi.write(content)\n\n\n def strat_spider(self):\n \"\"\"\n 爬虫启动,控制爬虫进行网页的爬取操作\n :return:\n \"\"\"\n # 用i来控制所要爬取的网页序号,从1开始\n\n # 用户交互型友好处理\n # i = 1\n # while self.switch:\n # print(\"爬虫启动...\")\n # self.get_html(i)\n # command = input(\"是否需要继续进行,继续请输入任意字符,退出请输入:quit\")\n # if command == \"quit\":\n # self.switch = False\n # print('谢谢使用!')\n # else:\n # i += 1\n\n # 自动爬取所有的段子信息\n for i in range(1, 452):\n print('爬虫启动...')\n self.get_html(i)\n print('谢谢使用')\n\n\n def get_content(self, nei_han_list):\n \"\"\"\n 获取每条内涵信息\n :param:content从网页中获取到的内涵段子信息\n :return:\n \"\"\"\n print('开始获取段子...')\n # 对每一个段子进行处理\n for content in nei_han_list:\n duan_zi = str(self.num)+'.'+content.replace('', '')+'\\n'\n self.num += 1\n # print(duan_zi)\n self.write_content(duan_zi)\n\nif __name__ == '__main__':\n nei_han_spider = Spider()\n nei_han_spider.strat_spider()\n\n","sub_path":"code/python/05-spider/day03/01-neihanduanzi.py","file_name":"01-neihanduanzi.py","file_ext":"py","file_size_in_byte":5083,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"1938137","text":"#!/usr/bin/env python3\n\nimport sys\nimport glob\n\n# ['attacks/__init__.py', 'attacks/AES_SboxOut_HW.py', 'attacks/DES_SboxOut_HW.py', 'attacks/AES_TTableOut_HW.py', 'attacks/XorOut_HW.py']\ndef usage():\n print(\"Attack model must be one of:\")\n fl = glob.glob(\"support/attacks/*.py\") # imported from ../\n for f in fl:\n fx = f.replace(\"support/attacks/\",\"\")\n fx2 = fx.replace(\".py\",\"\")\n if fx2 == \"__init__\":\n continue\n print(\" - %s\" % fx2)\n\ndef fetchModel(modelname):\n try:\n exec(\"from support.attacks.%s import AttackModel; fe = AttackModel()\" % modelname,globals())\n return fe\n except:\n print(\"Could not load attack model '%s'\" % modelname)\n usage()\n sys.exit(0)\n\nif __name__ == \"__main__\":\n print(\"ATTACK MODEL LOADER, DO NOT CALL DIRECTLY.\")\n","sub_path":"support/attack.py","file_name":"attack.py","file_ext":"py","file_size_in_byte":779,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"219067810","text":"\"\"\"\nFind a Fixed Point (Value equal to index) in a given array\nGiven an array of n distinct integers sorted in ascending order,\nwrite a function that returns a Fixed Point in the array,\nif there is any Fixed Point present in array, else returns -1.\nFixed Point in an array is an index i such that arr[i] is equal to i. Note that integers in array can be negative.\n\nExamples:\n Input: arr[] = {-10, -5, 0, 3, 7}\n Output: 3 // arr[3] == 3\n\n Input: arr[] = {0, 2, 5, 8, 17}\n Output: 0 // arr[0] == 0\n\n\n Input: arr[] = {-10, -5, 3, 4, 7, 9}\n Output: -1 // No Fixed Point\n\n\"\"\"\n\n\ndef get_fixed_number(arr, n):\n res = -1\n for i in range(n):\n if i == arr[i]:\n res = i\n break\n return res\n\n\narray = [16, 17, 4, 3, 5, 2]\nprint(get_fixed_number(array, len(array)))\n\narray = [5, 7, 2, 7, 5, 2, 5]\nprint(get_fixed_number(array, len(array)))\n\narray = [4, 5]\nprint(get_fixed_number(array, len(array)))\n","sub_path":"Arrays/9_find-a-fixed-point-in-a-given-array.py","file_name":"9_find-a-fixed-point-in-a-given-array.py","file_ext":"py","file_size_in_byte":956,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"25675270","text":"#!/usr/bin/python\n#https://www.hackerrank.com/challenges/encryption\nfrom math import sqrt\nfrom math import floor\nfrom math import ceil\nmsg = input()\n\n# row < column\n\nrows = floor(sqrt(len(msg)))\ncolumns = ceil(sqrt(len(msg)))\n\nif (rows * columns) < len(msg):\n rows += 1\n\ntable = []\nindex = 0\n\nfor r in range(rows):\n row = []\n for c in range(columns):\n if index < len(msg):\n row.append(msg[index])\n index+=1\n else:\n row.append('')\n table.append(row)\n\nindex = 0\nresult = \"\"\nr = 0\nfor c in range(columns):\n for r in range(rows):\n result += table[r][c]\n result += \" \"\n\nprint(result)","sub_path":"encryption/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":612,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"74406583","text":"import KratosMultiphysics as KM\n\nfrom KratosMultiphysics.ShallowWaterApplication.shallow_water_analysis import ShallowWaterAnalysis\n\nclass BenchmarkingUtilities:\n def __init__(self, options = ['regular_analysis','convergence_analysis']):\n self.options = options\n\n @staticmethod\n def RunCase(parameters):\n model = KM.Model()\n analysis = ShallowWaterAnalysis(model, parameters)\n analysis.Run()\n\n @staticmethod\n def GetParametersFromListOfProcesses(processes_list, name):\n for item, processes in processes_list.items():\n for process in processes:\n if process['python_module'].GetString() == name:\n return process['Parameters']\n\n @staticmethod\n def GetParametersFromListOfModelers(modelers_list, name):\n for modeler in modelers_list:\n if modeler['modeler_name'].GetString() == name:\n return modeler['Parameters']\n\n @staticmethod\n def ReplaceSettings(parameters, setting, value):\n if isinstance(value, str):\n parameters[setting].SetString(value)\n elif isinstance(value, int):\n parameters[setting].SetInt(value)\n elif isinstance(value, float):\n parameters[setting].SetDouble(value)\n else:\n raise Exception('Unsupported type')\n\n @classmethod\n def ReplaceProcessSettings(cls, processes_list, python_module, setting, value):\n parameters = cls.GetParametersFromListOfProcesses(processes_list, python_module)\n cls.ReplaceSettings(parameters, setting, value)\n\n @classmethod\n def ReplaceModelerSettings(cls, processes_list, python_module, setting, value):\n parameters = cls.GetParametersFromListOfModelers(processes_list, python_module)\n cls.ReplaceSettings(parameters, setting, value)\n\n def ParseArguments(self, argv, default_mode = 'regular_analysis'):\n if len(argv) > 2:\n err_msg = 'Too many input arguments.\\n'\n err_msg += self.Usage()\n raise Exception(err_msg)\n elif len(argv) == 2:\n self.mode = argv[1]\n else:\n self.mode = default_mode\n wrn_msg = 'Setting the analysis mode to \"{}\"\\n\\n'.format(self.mode)\n wrn_msg += self.Usage()\n wrn_msg += '\\n\\n'\n KM.Logger.PrintWarning(wrn_msg)\n\n def Mode(self):\n return self.mode\n\n def Usage(self):\n usage = 'Usage of this script:\\n'\n usage += '> python MainKratos.py \"mode\"\\n'\n usage += 'The possible modes are:\\n - '\n usage += '\\n - '.join(self.options)\n return usage\n\n def PrintUsage(self):\n KM.Logger.PrintInfo(self.Usage())\n\n def PrintUnknownModeMessage(self):\n msg = 'Unknown mode. The specified value is \"{}\"\\n'.format(self.mode)\n msg += self.Usage()\n KM.Logger.PrintInfo(msg)\n","sub_path":"applications/ShallowWaterApplication/python_scripts/benchmarks/benchmarking_utilities.py","file_name":"benchmarking_utilities.py","file_ext":"py","file_size_in_byte":2876,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"173732098","text":"from GraphPolicyController import GraphPolicyController\r\nfrom random_config import newconfig\r\nimport numpy as np\r\nimport boto3\r\nimport pickle\r\nimport time\r\nimport sys\r\n\r\n#Initialize-------------------------------------------------------------------------------------------\r\n#Generate Policy Containers\r\nnumNodes = 4 #number of graph controller nodes\r\nalpha = 0.05 #learning rate\r\nnumTMAs = 4 #cardinality of TMA space\r\nnumObs = 12 #cardinality of observation space\r\nN_k = 50 #number of iterations\r\nN_r = 100 #How many times the simulation will run to get its averate.\r\nN_s = 50 #number of samples per iteration\r\nN_b = 5 #number of \"best\" samples kept from each iteration\r\nN_agent = 1 #number of agnet\r\nbestValue = -10000000 #best value so far\r\n\r\nidxStart = 13\r\n\r\nControllers = [] #collect controllers for each agent\r\n\r\nif idxStart == 0:\r\n\tfor idxAgent in range(0,N_agent):\r\n\t\tmGraphPolicyController = GraphPolicyController(numNodes, alpha, numTMAs, numObs, N_s)\r\n\t\tControllers.append(mGraphPolicyController)\r\nelse:\r\n\titeration = idxStart-1\r\n\ts3 = boto3.resource('s3', region_name = 'us-west-1')\r\n\tbucket = s3.Bucket('adfproject')\r\n\tdirectory_name = \"policy\" + str(iteration)\r\n\twith open('pdump', 'wb') as data:\r\n\t\tbucket.download_fileobj(directory_name + '/policy', data)\r\n\twith open('pdump', 'rb') as data:\r\n\t\tControllers = [pickle.load(data)]\r\n\t#Retrieve reward.\r\n\tprint(\"Retrieving Rewards\")\r\n\trewards = np.zeros((N_s, N_r))\r\n\r\n\tdb = boto3.resource(\"dynamodb\", region_name = 'us-west-1')\r\n\ttable = db.Table(\"ADFEval\" + str(iteration))\r\n\ttableContents = table.scan()[\"Items\"]\r\n\tfor i in tableContents:\r\n\t\ttrialNum = int(i[\"TrialNum\"])\r\n\t\tcol = trialNum % N_r\r\n\t\trow = int((trialNum - col)/N_r)\r\n\t\ttry:\r\n\t\t\trewards[row,col] = float(i[\"reward\"])\r\n\t\texcept:\r\n\t\t\trewards[row,col] = 0\r\n\tcurIterationValues = np.sum(rewards, axis=1)/N_r\r\n\tprint(\"Rewards Retrieved\")\r\n\tprint(curIterationValues)\r\n\r\n\t#Process Values\r\n\tprint(\"Processing Rewards\")\r\n\r\n\tfor idxSample in range(0,N_s):\r\n\r\n\t\tif curIterationValues[idxSample] > bestValue:\r\n\t\t\t#Record New Best Value Parameters\r\n\t\t\tbestValue = curIterationValues[idxSample]\r\n\r\n\t\t\tControllers[0].setGraph(idxSample)\r\n\t\t\t[best_TMAs, best_Transitions] = Controllers[0].getPolicyTable();\r\n\r\n\t\t\tfor idxAgent in range(1, N_agent):\r\n\t\t\t\tControllers[idxAgent].setGraph(idxSample)\r\n\t\t\t\t[bestTMAs, bestTransitions] = Controllers[idxAgent].getPolicyTable();\r\n\t\t\t\tbest_TMAs = np.append(best_TMAs,bestTMAs, axis = 0)\r\n\t\t\t\tbest_Transitions = np.append(best_Transitions, bestTransitions, axis = 0)\r\n\t\t\tnp.save(\"best_TMAs\", best_TMAs)\r\n\t\t\tnp.save(\"best_Transitions\", best_Transitions)\r\n\r\n\tfor idxAgent in range(0,N_agent):\r\n\t\tControllers[idxAgent].updateProbs(curIterationValues, N_b, iteration)\r\n\r\n\tprint(\"Iteration \" + str(iteration) + \" Complete\")\r\n\r\n\r\n\r\nfor idxIter in range(idxStart,N_k):\r\n\r\n\t#Sample and Save------------------------------------------------------------------------------------\r\n\ts3 = boto3.client('s3')\r\n\tbucket = \"adfproject\"\r\n\r\n\t#Sample Policy\r\n\tdirectory_name = \"policy\" + str(idxIter)\r\n\ts3.put_object(Bucket=bucket, Key=(directory_name + '/'))\r\n\tprint(\"Uploading Policy\")\r\n\tfor idxAgent in range(0,N_agent):\r\n\t\tControllers[idxAgent].sample(N_s)\r\n\t\ts3.put_object(Body = pickle.dumps(Controllers[idxAgent]),Bucket=bucket, Key=(directory_name + '/policy'))\r\n\r\n\t#Sample Configuration\r\n\tdirectory_name = \"config\" + str(idxIter)\r\n\ts3.put_object(Bucket=bucket, Key=(directory_name + '/'))\r\n\tprint(\"Uploading Configurations\")\r\n\tfor idxRun in range(0,N_r):\r\n\t\tnewconfig(idxRun)\r\n\t\ts3.upload_file(Filename = (\"./configuration/rc\" + str(idxRun) +\".xml\"), Bucket=bucket, Key = directory_name + '/rc' + str(idxRun) + \".xml\")\r\n\r\n\r\n\t#Propogate to table-------------------------------------------------------------------------------\r\n\t#Create table\r\n\tprint(\"Making Table\")\r\n\tdb = boto3.client('dynamodb')\r\n\ttablename = \"ADFEval\" + str(idxIter)\r\n\r\n\texisting_tables = db.list_tables()['TableNames']\r\n\r\n\tif tablename in existing_tables:\r\n\t\tprint(\"Deleteing Old Table\")\r\n\t\tdb.delete_table(TableName=tablename)\r\n\t\twaiter = db.get_waiter('table_not_exists')\r\n\t\twaiter.wait(TableName=tablename)\r\n\t\tprint (\"Old Table Deleted\")\r\n\r\n\tdb.create_table(\r\n\t\tTableName = tablename,\r\n\t\tKeySchema = [\r\n\t\t\t{\r\n\t\t\t\t'AttributeName': 'TrialNum',\r\n\t\t\t\t'KeyType': 'HASH'\r\n\t\t\t}\r\n\t\t],\r\n\t\tAttributeDefinitions = [\r\n\t\t\t{\r\n\t\t\t\t'AttributeName': 'TrialNum',\r\n\t\t\t\t'AttributeType': 'N'\r\n\t\t\t}\r\n\t\t],\r\n\t\tProvisionedThroughput={\r\n\t\t\t'ReadCapacityUnits': 10,\r\n\t\t\t'WriteCapacityUnits': 10\r\n\t\t}\r\n\t)\r\n\r\n\r\n\twaiter = db.get_waiter('table_exists')\r\n\twaiter.wait(TableName=tablename)\r\n\tprint(\"New table \" + tablename + \" created.\")\r\n\r\n\tprint(\"Filling table with \" + str(N_s*N_r) + \" entries.\")\r\n\tdbr = boto3.resource('dynamodb')\r\n\ttable = dbr.Table(tablename)\r\n\twith table.batch_writer() as batch:\r\n\t\tfor idxSample in range(0,N_s):\r\n\t\t\tfor idxRun in range(0,N_r):\r\n\t\t\t\tbatch.put_item(\r\n\t\t\t\t\tItem = {\r\n\t\t\t\t\t\t'TrialNum': idxSample*N_r+idxRun,\r\n\t\t\t\t\t\t'PolicyNum': idxSample,\r\n\t\t\t\t\t\t'Configuration': idxRun\r\n\t\t\t\t\t}\r\n\t\t\t\t)\r\n\tprint(\"Table filled.\")\r\n\r\n\r\n\t#Assign Jobs\r\n\tprint(\"Generating Jobs\")\r\n\tbatch = boto3.client('batch')\r\n\r\n\tfor idxJob in range(0, N_s*N_r):\r\n\t\tbatch.submit_job(\r\n\t\t\tjobName='adf-trial-' + str(idxJob) + '-itr-' + str(idxIter), # use your HutchNet ID instead of 'jdoe'\r\n\t\t\tjobQueue='adf-job0queue', # sufficient for most jobs\r\n\t\t\tjobDefinition='adf-job', # use a real job definition\r\n\t\t\tcontainerOverrides={\r\n\t\t\t\t\"environment\": [ # optionally set environment variables\r\n\t\t\t\t\t{\"name\": \"TRIAL\", \"value\": str(idxJob)},\r\n\t\t\t\t\t{\"name\": \"ITERATION\", \"value\": str(idxIter)}\r\n\t\t\t\t]\r\n\t\t\t})\r\n\tprint(\"Jobs Generated\")\r\n\t#)\r\n\r\n\r\n\t#Wait till finished\r\n\tprint(\"Monitoring Job Completion\")\r\n\twhile True:\r\n\t\tbatch = boto3.client('batch')\r\n\t\tsub = len(batch.list_jobs(jobQueue = \"adf-job0queue\", jobStatus = 'SUBMITTED')[\"jobSummaryList\"])\r\n\t\tpen = len(batch.list_jobs(jobQueue = \"adf-job0queue\", jobStatus = 'PENDING')[\"jobSummaryList\"])\r\n\t\trunnable = len(batch.list_jobs(jobQueue = \"adf-job0queue\", jobStatus = 'RUNNABLE')[\"jobSummaryList\"])\r\n\t\tsta = len(batch.list_jobs(jobQueue = \"adf-job0queue\", jobStatus = 'STARTING')[\"jobSummaryList\"])\r\n\t\trunning = len(batch.list_jobs(jobQueue = \"adf-job0queue\", jobStatus = 'RUNNING')[\"jobSummaryList\"])\r\n\t\tif (sub+pen+runnable+sta+running) == 0:\r\n\t\t\tprint(\"Jobs done.\")\r\n\t\t\tbreak\r\n\t\telse:\r\n\t\t\tprint(\"-\")\r\n\t\t\tprint(\"Jobs still going.\")\r\n\t\t\tprint(\"Submitted: \" + str(sub))\r\n\t\t\tprint(\"Pending: \" + str(pen))\r\n\t\t\tprint(\"Runnable: \" + str(runnable))\r\n\t\t\tprint(\"Starting: \" + str(sta))\r\n\t\t\tprint(\"Running: \" + str(running))\r\n\t\t\tprint(\"-\")\r\n\t\t\ttime.sleep(10)\r\n\t\t\tsys.stdout.write(\"\\033[F \\033[F \\033[F \\033[F \\033[F \\033[F \\033[F \\033[F\")\r\n\r\n\t#Retrieve reward.\r\n\tprint(\"Retrieving Rewards\")\r\n\trewards = np.zeros((N_s, N_r))\r\n\r\n\ttableContents = table.scan()[\"Items\"]\r\n\tfor i in tableContents:\r\n\t\ttrialNum = int(i[\"TrialNum\"])\r\n\t\tcol = trialNum % N_r\r\n\t\trow = int((trialNum - col)/N_r)\r\n\t\ttry:\r\n\t\t\trewards[row,col] = float(i[\"reward\"])\r\n\t\texcept:\r\n\t\t\trewards[row,col] = 0\r\n\tcurIterationValues = np.sum(rewards, axis=1)/N_r\r\n\tprint(\"Rewards Retrieved\")\r\n\tprint(curIterationValues)\r\n\r\n\t#Process Values\r\n\tprint(\"Processing Rewards\")\r\n\r\n\tfor idxSample in range(0,N_s):\r\n\r\n\t\tif curIterationValues[idxSample] > bestValue:\r\n\t\t\t#Record New Best Value Parameters\r\n\t\t\tbestValue = curIterationValues[idxSample]\r\n\r\n\t\t\tControllers[0].setGraph(idxSample)\r\n\t\t\t[best_TMAs, best_Transitions] = Controllers[0].getPolicyTable();\r\n\r\n\t\t\tfor idxAgent in range(1, N_agent):\r\n\t\t\t\tControllers[idxAgent].setGraph(idxSample)\r\n\t\t\t\t[bestTMAs, bestTransitions] = Controllers[idxAgent].getPolicyTable();\r\n\t\t\t\tbest_TMAs = np.append(best_TMAs,bestTMAs, axis = 0)\r\n\t\t\t\tbest_Transitions = np.append(best_Transitions, bestTransitions, axis = 0)\r\n\t\t\tnp.save(\"best_TMAs\", best_TMAs)\r\n\t\t\tnp.save(\"best_Transitions\", best_Transitions)\r\n\r\n\tfor idxAgent in range(0,N_agent):\r\n\t\tControllers[idxAgent].updateProbs(curIterationValues, N_b, idxIter)\r\n\r\n\tprint(\"Iteration \" + str(idxIter) + \" Complete\")\r\n\t#Repeat\r\n","sub_path":"GDice/awsJobGeneration.py","file_name":"awsJobGeneration.py","file_ext":"py","file_size_in_byte":7986,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"449399788","text":"#coding=utf-8\r\n\r\nimport logging\r\n\r\nimport requests\r\n# import requests.Response\r\n\r\nlogging.basicConfig(level=logging.DEBUG, format=\"[%(asctime)s] %(name)s:%(levelname)s: %(message)s\")\r\n\r\n\r\n'''\r\n继续requests基础分享,本文主要分享以下内容:\r\n\r\n请求头定制\r\n\r\nPOST请求\r\n'''\r\n\r\n\r\nif __name__ != '__main__':\r\n print(\"开源优测 - requests自定义请求头基本示例\")\r\n\r\n url = \"http://www.baidu.com\"\r\n\r\n headers={ \"user-agent\": \"www.testingunion.com\",\"custom-head\":\"DeepTest\"}\r\n\r\n r=requests.get(url,headers=headers)\r\n print(r.text)\r\n\r\n\r\n\r\n'''\r\n注:所有的header值必须是string、bytestring或unicode,虽然传递unicode header是允许的,但不建议这样做\r\n\r\npython requests_headers_demo.py\r\n在运行上述命令前,先启动wireshark,用来抓取报文,看下我们自定义的headers是否正常被设置。\r\n'''\r\n\r\nif __name__ != '__main__':\r\n print(\"requests post示例\")\r\n\r\n # 目标url\r\n url = \"http://httpbin.org/post\"\r\n\r\n # 请求头headers\r\n headers = {\"custom-header\": \"mypost\"}\r\n\r\n # 要post的数据\r\n data = {\"data_1\": \"deeptest\", \"data_2\": \"testingunion.com\"}\r\n\r\n # 发送post请求\r\n r = requests.post(url, data=data, headers=headers)\r\n\r\n # 输出结果\r\n # print(r.text)\r\n\r\n #postjson数据到服务。\r\nif __name__ == '__main__':\r\n\r\n print(\"requests post json数据示例\")\r\n\r\n # 目标服务url\r\n url = \"http://jsonplaceholder.typicode.com/posts\"\r\n\r\n # 自定义头\r\n headers = {\r\n \"custom-post\": \"my-post\",\r\n \"custom-header\": \"my-json-header\"\r\n }\r\n\r\n # 要post的数据\r\n json_data = {\r\n \"title\": \"deeptest\",\r\n \"body\": \"开源优测\",\r\n \"userId\": \"1\"\r\n }\r\n print(type(json_data))\r\n\r\n # post json格式的数据\r\n r = requests.post(url, json=json_data, headers=headers)\r\n\r\n # 打印下返回结果\r\n print(r.text)","sub_path":"第一期/北京-菜鸟渣渣/Fast_Learning_python3/interface_test/mission_10chapters/_request_demo.py","file_name":"_request_demo.py","file_ext":"py","file_size_in_byte":1907,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"381451649","text":"from django import forms\n\nfrom veiculos.models import Veiculo\n\nclass FormularioVeiculo(forms.ModelForm):\n \"\"\"\n Formulario para o model Veiculo\n \"\"\"\n class Meta:\n model = Veiculo\n exclude = []\n \n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n for campo in self.fields:\n self.fields[campo].widget.attrs.update({'class':'form-control'})\n","sub_path":"veiculos/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":417,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"607838491","text":"# Copyright 2021 Pants project contributors (see CONTRIBUTORS.md).\n# Licensed under the Apache License, Version 2.0 (see LICENSE).\n\nfrom textwrap import dedent\n\nimport pytest\n\nfrom pants.backend.project_info import peek\nfrom pants.backend.project_info.peek import Peek, TargetData, TargetDatas\nfrom pants.base.specs import RawSpecs, RecursiveGlobSpec\nfrom pants.core.target_types import ArchiveTarget, FilesGeneratorTarget, FileTarget, GenericTarget\nfrom pants.engine.addresses import Address\nfrom pants.engine.rules import QueryRule\nfrom pants.testutil.rule_runner import RuleRunner\n\n\n@pytest.mark.parametrize(\n \"expanded_target_infos, exclude_defaults, expected_output\",\n [\n pytest.param(\n [],\n False,\n \"[]\\n\",\n id=\"null-case\",\n ),\n pytest.param(\n [\n TargetData(\n FilesGeneratorTarget(\n {\n \"sources\": [\"*.txt\"],\n # Regression test that we can handle a dict with `tuple[str, ...]` as\n # key.\n \"overrides\": {(\"foo.txt\",): {\"tags\": [\"overridden\"]}},\n },\n Address(\"example\", target_name=\"files_target\"),\n ),\n (\"foo.txt\", \"bar.txt\"),\n tuple(),\n )\n ],\n True,\n dedent(\n \"\"\"\\\n [\n {\n \"address\": \"example:files_target\",\n \"target_type\": \"files\",\n \"dependencies\": [],\n \"overrides\": {\n \"('foo.txt',)\": {\n \"tags\": [\n \"overridden\"\n ]\n }\n },\n \"sources\": [\n \"foo.txt\",\n \"bar.txt\"\n ],\n \"sources_raw\": [\n \"*.txt\"\n ]\n }\n ]\n \"\"\"\n ),\n id=\"single-files-target/exclude-defaults\",\n ),\n pytest.param(\n [\n TargetData(\n FilesGeneratorTarget(\n {\"sources\": [\"foo.txt\"]}, Address(\"example\", target_name=\"files_target\")\n ),\n (\"foo.txt\",),\n tuple(),\n )\n ],\n False,\n dedent(\n \"\"\"\\\n [\n {\n \"address\": \"example:files_target\",\n \"target_type\": \"files\",\n \"dependencies\": [],\n \"description\": null,\n \"overrides\": null,\n \"sources\": [\n \"foo.txt\"\n ],\n \"sources_raw\": [\n \"foo.txt\"\n ],\n \"tags\": null\n }\n ]\n \"\"\"\n ),\n id=\"single-files-target/include-defaults\",\n ),\n pytest.param(\n [\n TargetData(\n FilesGeneratorTarget(\n {\"sources\": [\"*.txt\"], \"tags\": [\"zippable\"]},\n Address(\"example\", target_name=\"files_target\"),\n ),\n tuple(),\n tuple(),\n ),\n TargetData(\n ArchiveTarget(\n {\n \"output_path\": \"my-archive.zip\",\n \"format\": \"zip\",\n \"files\": [\"example:files_target\"],\n },\n Address(\"example\", target_name=\"archive_target\"),\n ),\n None,\n (\"foo/bar:baz\", \"qux:quux\"),\n ),\n ],\n True,\n dedent(\n \"\"\"\\\n [\n {\n \"address\": \"example:files_target\",\n \"target_type\": \"files\",\n \"dependencies\": [],\n \"sources\": [],\n \"sources_raw\": [\n \"*.txt\"\n ],\n \"tags\": [\n \"zippable\"\n ]\n },\n {\n \"address\": \"example:archive_target\",\n \"target_type\": \"archive\",\n \"dependencies\": [\n \"foo/bar:baz\",\n \"qux:quux\"\n ],\n \"files\": [\n \"example:files_target\"\n ],\n \"format\": \"zip\",\n \"output_path\": \"my-archive.zip\"\n }\n ]\n \"\"\"\n ),\n id=\"single-files-target/exclude-defaults\",\n ),\n ],\n)\ndef test_render_targets_as_json(expanded_target_infos, exclude_defaults, expected_output):\n actual_output = peek.render_json(expanded_target_infos, exclude_defaults)\n assert actual_output == expected_output\n\n\n@pytest.fixture\ndef rule_runner() -> RuleRunner:\n return RuleRunner(\n rules=[\n *peek.rules(),\n QueryRule(TargetDatas, [RawSpecs]),\n ],\n target_types=[FilesGeneratorTarget, GenericTarget],\n )\n\n\ndef test_non_matching_build_target(rule_runner: RuleRunner) -> None:\n rule_runner.write_files({\"some_name/BUILD\": \"target()\"})\n result = rule_runner.run_goal_rule(Peek, args=[\"other_name\"])\n assert result.stdout == \"[]\\n\"\n\n\ndef test_get_target_data(rule_runner: RuleRunner) -> None:\n rule_runner.write_files(\n {\n \"foo/BUILD\": dedent(\n \"\"\"\\\n target(name=\"bar\", dependencies=[\":baz\"])\n\n files(name=\"baz\", sources=[\"*.txt\"])\n \"\"\"\n ),\n \"foo/a.txt\": \"\",\n \"foo/b.txt\": \"\",\n }\n )\n tds = rule_runner.request(\n TargetDatas,\n [RawSpecs(recursive_globs=(RecursiveGlobSpec(\"foo\"),), description_of_origin=\"tests\")],\n )\n assert list(tds) == [\n TargetData(\n GenericTarget({\"dependencies\": [\":baz\"]}, Address(\"foo\", target_name=\"bar\")),\n None,\n (\"foo/a.txt:baz\", \"foo/b.txt:baz\"),\n ),\n TargetData(\n FilesGeneratorTarget({\"sources\": [\"*.txt\"]}, Address(\"foo\", target_name=\"baz\")),\n (\"foo/a.txt\", \"foo/b.txt\"),\n (\"foo/a.txt:baz\", \"foo/b.txt:baz\"),\n ),\n TargetData(\n FileTarget(\n {\"source\": \"a.txt\"}, Address(\"foo\", relative_file_path=\"a.txt\", target_name=\"baz\")\n ),\n (\"foo/a.txt\",),\n (),\n ),\n TargetData(\n FileTarget(\n {\"source\": \"b.txt\"}, Address(\"foo\", relative_file_path=\"b.txt\", target_name=\"baz\")\n ),\n (\"foo/b.txt\",),\n (),\n ),\n ]\n","sub_path":"src/python/pants/backend/project_info/peek_test.py","file_name":"peek_test.py","file_ext":"py","file_size_in_byte":7179,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"613326040","text":"# -*- coding: utf-8 -*-\n\nfrom flask import Flask, render_template, request\n\nfrom dao import Dao\n\napp = Flask(__name__)\ndao = Dao()\n\n\n@app.route('/', methods=['GET', 'POST'])\ndef top():\n if request.method == 'POST':\n input_values = {'name': request.form['name'],\n 'company': request.form['company'],\n 'tel': request.form['tel'],\n 'mail': request.form['mail']}\n dao.insert_business_card(input_values)\n\n registered = dao.select_all_business_cards()\n return render_template('index.html', registered=registered)\n\n\n@app.route('/search', methods=['POST'])\ndef search():\n search_word = request.form['search_word']\n column = request.form['column']\n\n if column == 'name':\n registered = dao.select_business_cards_by_name(search_word)\n elif column == 'company':\n registered = dao.select_business_cards_by_company(search_word)\n elif column == 'tel':\n registered = dao.select_business_cards_by_tel(search_word)\n elif column == 'mail':\n registered = dao.select_business_cards_by_mail(search_word)\n else:\n registered = []\n\n return render_template('index.html', registered=registered)\n\n\nif __name__ == '__main__':\n app.run(host='0.0.0.0', port=80, debug=True)\n","sub_path":"web/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1297,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"626815645","text":"#!/usr/bin/env python3\nfrom sys import argv, exit\n\nimport model_lcs_lib as ll\n\n\ndef main(m, n, alphabet, gen_seed, file_full_extension):\n # Automatic cast:\n m = int(m)\n n = int(n)\n alphabet = alphabet\n gen_seed = int(gen_seed)\n\n # Generate lcs instance\n instance = ll.instance_randgen_1(m, n, alphabet, gen_seed)\n\n # Generate selected output\n print(ll.instance_to_str(instance, ll.file_extension_to_format_name(file_full_extension)))\n\n\nif __name__ == \"__main__\":\n from sys import argv\n assert len(argv) == 6, 'Miss arguments'\n main(argv[1], argv[2], argv[3], argv[4], argv[5])\n exit(0)\n","sub_path":"example_problems/problems_to_be_done/somme/gen/randgen_1_basic.py","file_name":"randgen_1_basic.py","file_ext":"py","file_size_in_byte":625,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"469262993","text":"import asyncio\nfrom datetime import datetime\nimport os\n\nfrom aiohttp import web\nimport aiohttp_jinja2\nfrom aiopg.sa import create_engine\nimport itsdangerous\nimport jinja2\n\nfrom .handlers import index\nfrom .handlers.auth import registration, login, profile\n\n\n@asyncio.coroutine\ndef middleware_factory(app, handler):\n @asyncio.coroutine\n def middleware(request):\n now = datetime.now()\n print(now, handler.__name__, sep=' ')\n return (yield from handler(request))\n\n return middleware\n\n\nclass Ferrum(web.Application):\n\n def __init__(self, *args, **kwargs):\n self.engine = None\n\n self.config = {\n 'DB_HOST': os.environ.get('DB_HOST', 'localhost'),\n 'DB_PORT': os.environ.get('DB_PORT', 5432),\n 'DB_NAME': os.environ.get('DB_NAME', 'ferrum'),\n 'DB_USER': os.environ.get('DB_USER', 'clayman'),\n 'DB_PASSWORD': os.environ.get('DB_PASSWORD', ''),\n\n 'APP_ROOT': os.path.realpath(os.path.dirname(\n os.path.abspath(__file__))),\n }\n\n self.config['MIGRATIONS_ROOT'] = os.path.join(\n self.config['APP_ROOT'], 'models', 'migrations')\n\n self.config['TEMPLATES_ROOT'] = os.path.join(self.config['APP_ROOT'],\n 'templates')\n\n self.signer = itsdangerous.TimedJSONWebSignatureSerializer('top-secret', expires_in=300)\n\n kwargs['middlewares'] = [middleware_factory, ]\n\n super(Ferrum, self).__init__(*args, **kwargs)\n\n self.configure_database()\n\n def configure_database(self):\n db_host = self.config.get('DB_HOST')\n db_port = self.config.get('DB_PORT')\n\n uri = 'postgresql+psycopg2://{0}:{1}@{2}:{3}/{4}'.format(\n self.config.get('DB_USER'), self.config.get('DB_PASSWORD'),\n db_host, db_port, self.config.get('DB_NAME'))\n self.config['SQLALCHEMY_DATABASE_URI'] = uri\n\n @asyncio.coroutine\n def configure_db_engine(self):\n engine = yield from create_engine(user=self.config['DB_USER'],\n password=self.config['DB_PASSWORD'],\n database=self.config['DB_NAME'],\n host=self.config['DB_HOST'],\n port=self.config['DB_PORT'],\n loop=self.loop)\n self.engine = engine\n\n @asyncio.coroutine\n def configure(self):\n yield from self.configure_db_engine()\n\n aiohttp_jinja2.setup(self, loader=jinja2.FileSystemLoader(\n self.config['TEMPLATES_ROOT']))\n\n self.router.add_route('GET', '/', index)\n self.router.add_route('POST', '/auth/login', login)\n self.router.add_route('POST', '/auth/register', registration)\n self.router.add_route('GET', '/profile', profile)\n\n @asyncio.coroutine\n def close(self):\n self.engine.close()\n","sub_path":"ferrum/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2965,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"441461194","text":"import requests\nfrom bs4 import BeautifulSoup\nimport re\nimport time\nimport numpy as np\nimport datetime\nimport pickle\n\n#each page has 100 games on it (other than the last page)\ndef get_game_ids(games=100, pickle=False):\n\n '''\n First step in updating the database.\n A list of list of games is returned and saved to a pickle in the following format:\n [game id, game name, current rating on bgg]\n ex. [174430, 'Gloomhaven', 1]\n Args:\n games (int) default 1000\n Must be a multiple of 100. If not, the next lowest number divisible by 100 is used. For example if 962 is passed, that will result in 900 games being returned in the list.\n '''\n if games < 100:\n print(\"Specified number of games must be a multiple of 100.\")\n if games/100 != 1:\n print(\"Warning: You have specified a number of games that is not a multiple of 100. {} games will be added to list.\".format(int(games/100)*100))\n\n url = 'https://www.boardgamegeek.com/browse/boardgame/page/'\n random_sec = np.random.uniform(5,7,[1000,])\n id_list = []\n for page in range(int(games/100)):\n req = requests.get(url+str(page+1))\n soup = BeautifulSoup(req.text, 'html.parser')\n thumbnails = soup.find_all('td',attrs={\"class\": \"collection_thumbnail\"})\n time.sleep(np.random.choice(random_sec))\n for thumbnail in thumbnails:\n current = thumbnail.a['href'].split('/')\n game = current[3].replace(\"-\", \" \")\n game = \" \".join([x[:1].upper() + x[1:] for x in game.split()])\n id_list.append([int(current[2]),game])\n print(\"{} games\".format((page+1)*100))\n for i,game in enumerate(id_list):\n game.append(i+1)\n if pickle is True:\n pkl_file_path = \"data/game_ids/{}.pkl\".format(datetime.date.today().strftime(\"%Y_%m_%d\"))\n with open(pkl_file_path, 'wb') as fp:\n pickle.dump(id_list, fp)\n return id_list\n","sub_path":"get_ids.py","file_name":"get_ids.py","file_ext":"py","file_size_in_byte":1934,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"443068254","text":"#\n# This source file is part of the EdgeDB open source project.\n#\n# Copyright 2008-present MagicStack Inc. and the EdgeDB authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n\n\nfrom edb.lang.schema import deltarepo\nfrom edb.lang.schema import delta as sd\n\nfrom . import common\nfrom . import dbops, deltadbops, delta\n\nfrom .datasources import deltalog\n\n\nclass MetaDeltaRepository(deltarepo.MetaDeltaRepository):\n def __init__(self, connection):\n self.connection = connection\n\n async def delta_ref_to_id(self, ref):\n table = deltadbops.DeltaRefTable()\n condition = dbops.TableExists(table.name)\n have_deltaref = condition.execute(\n delta.CommandContext(self.connection))\n\n result = []\n\n if have_deltaref:\n query = 'SELECT id FROM %s WHERE ref = $1' % common.qname(\n *table.name)\n\n ps = self.connection.prepare(query)\n\n result = ps.first(ref.ref) or ref.ref\n\n try:\n result = int(result, 16)\n except ValueError:\n result = None\n\n if ref.offset:\n rev_id = '%x' % result\n result = await deltalog.fetch(\n self.connection, rev_id=rev_id, offset=ref.offset)\n\n if not result:\n raise sd.DeltaRefError('unknown revision: %s' % ref)\n result = int(result[0][0], 16)\n\n return result\n else:\n return None\n","sub_path":"edb/server/pgsql/deltarepo.py","file_name":"deltarepo.py","file_ext":"py","file_size_in_byte":1988,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"570132732","text":"#!/usr/bin/env python3\n\"\"\"infoset Sentry3 (Servertech intelligent CDU power strip) agent.\n\nDescription:\n\n This script:\n 1) Retrieves a variety of system information\n 2) Posts the data using HTTP to a server listed\n in the configuration file\n\n\"\"\"\n# Standard libraries\nimport logging\nfrom collections import defaultdict\n\n# infoset libraries\nfrom infoset.agents import agent as Agent\nfrom infoset.utils import log\nfrom infoset.utils import jm_configuration\nfrom infoset.snmp import snmp_manager\nfrom infoset.snmp import mib_if\nfrom infoset.snmp import mib_if_64\n\nlogging.getLogger('requests').setLevel(logging.WARNING)\nlogging.basicConfig(level=logging.DEBUG)\n\n\nclass PollingAgent(object):\n \"\"\"Infoset agent that gathers data.\n\n Args:\n None\n\n Returns:\n None\n\n Functions:\n __init__:\n populate:\n post:\n \"\"\"\n\n def __init__(self, config_dir):\n \"\"\"Method initializing the class.\n\n Args:\n config_dir: Configuration directory\n\n Returns:\n None\n\n \"\"\"\n # Initialize key variables\n self.agent_name = 'interfaces'\n\n # Get configuration\n self.config = jm_configuration.ConfigAgent(\n config_dir, self.agent_name)\n\n # Get snmp configuration information from infoset\n self.snmp_config = jm_configuration.ConfigSNMP(config_dir)\n\n def name(self):\n \"\"\"Return agent name.\n\n Args:\n None\n\n Returns:\n value: Name of agent\n\n \"\"\"\n # Return\n value = self.agent_name\n return value\n\n def query(self):\n \"\"\"Query all remote hosts for data.\n\n Args:\n None\n\n Returns:\n None\n\n \"\"\"\n # Check each hostname\n hostnames = self.config.agent_snmp_hostnames()\n for hostname in hostnames:\n # Get valid SNMP credentials\n validate = snmp_manager.Validate(\n hostname, self.snmp_config.snmp_auth())\n snmp_params = validate.credentials()\n\n # Log message\n if snmp_params is None:\n log_message = (\n 'No valid SNMP configuration found '\n 'for host \"%s\" ') % (hostname)\n log.log2warn(1022, log_message)\n continue\n\n # Create Query make sure MIB is supported\n snmp_object = snmp_manager.Interact(snmp_params)\n query = mib_if.init_query(snmp_object)\n query64 = mib_if_64.init_query(snmp_object)\n if query.supported() is False:\n log_message = (\n 'The IF-MIB is not supported by host \"%s\"'\n '') % (hostname)\n log.log2warn(1024, log_message)\n continue\n\n # Get the UID for the agent after all preliminary checks are OK\n uid_env = Agent.get_uid(hostname)\n\n # Post data to the remote server\n self.upload(uid_env, hostname, query, query64)\n\n def upload(self, uid, hostname, query, query64):\n \"\"\"Post system data to the central server.\n\n Args:\n uid: Unique ID for Agent\n hostname: Hostname\n query: SNMP credentials object (IF-MIB 32 bit)\n query64: SNMP credentials object (IF-MIB 64 bit)\n\n Returns:\n None\n\n \"\"\"\n # Initialize key variables\n ignore = []\n agent = Agent.Agent(uid, self.config, hostname)\n\n # Get a list of interfaces to ignore because they are down\n status = query.ifoperstatus()\n for key, value in status.items():\n if value != 1:\n ignore.append(key)\n\n # Get descriptions\n descriptions = query.ifdescr(safe=True)\n if bool(descriptions) is False:\n return\n\n # Update 32 bit data\n _update_32(agent, ignore, descriptions, query)\n\n # Update 64 bit data\n _update_64(agent, ignore, descriptions, query64)\n\n # Post data\n success = agent.post()\n\n # Purge cache if success is True\n if success is True:\n agent.purge()\n\n\ndef _update_64(agent, ignore, descriptions, query64):\n \"\"\"Return all the CLI options.\n\n Args:\n agent: Agent object\n ignore: List of ifIndexes to ignore\n descriptions: Dict keyed by ifIndex of ifDescr values\n query64: SNMP query object (64 bit)\n\n Returns:\n None\n\n \"\"\"\n # Initialize key variables\n prefix = ''\n state = {}\n data = defaultdict(lambda: defaultdict(dict))\n\n # Don't provide 64 bit counter data if not supported\n if query64.supported() is False:\n return\n\n ##########################################################################\n # Handle 64 bit counters\n ##########################################################################\n labels = ['ifHCInOctets', 'ifHCOutOctets']\n state['ifHCInOctets'] = query64.ifhcinoctets(safe=True)\n state['ifHCOutOctets'] = query64.ifhcoutoctets(safe=True)\n\n # Make sure we received values\n for label in labels:\n if bool(state[label]) is False:\n return\n\n # Create dictionary for eventual posting\n for label in labels:\n for key, value in state[label].items():\n if key in ignore:\n continue\n source = descriptions[key]\n data[label][source] = value * 8\n\n # Populate agent\n agent.populate_dict(prefix, data, base_type='counter64')\n\n\ndef _update_32(agent, ignore, descriptions, query):\n \"\"\"Return all the CLI options.\n\n Args:\n agent: Agent object\n ignore: List of ifIndexes to ignore\n descriptions: Dict keyed by ifIndex of ifDescr values\n query: SNMP query object\n\n Returns:\n None\n\n \"\"\"\n # Initialize key variables\n prefix = ''\n state = {}\n data = defaultdict(lambda: defaultdict(dict))\n\n ##########################################################################\n # Handle 32 bit counters\n ##########################################################################\n # Get results from querying device\n labels = ['ifInOctets', 'ifOutOctets']\n state['ifInOctets'] = query.ifinoctets(safe=True)\n state['ifOutOctets'] = query.ifoutoctets(safe=True)\n\n # Make sure we received values\n for label in labels:\n if bool(state[label]) is False:\n return\n\n # Create dictionary for eventual posting\n for label in labels:\n for key, value in state[label].items():\n if key in ignore:\n continue\n source = descriptions[key]\n data[label][source] = value * 8\n\n # Populate agent\n agent.populate_dict(prefix, data, base_type='counter32')\n\n\ndef main():\n \"\"\"Start the infoset agent.\n\n Args:\n None\n\n Returns:\n None\n\n \"\"\"\n # Get configuration\n cli = Agent.AgentCLI()\n config_dir = cli.config_dir()\n poller = PollingAgent(config_dir)\n\n # Do control\n cli.control(poller)\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"infoset/agents/standard/interfaces.py","file_name":"interfaces.py","file_ext":"py","file_size_in_byte":7094,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"480229137","text":"from django.shortcuts import render\nfrom .forms import StudentRegistration\n# Create your views here.\n\n\ndef showformdata(request):\n if request.method == 'POST':\n fm = StudentRegistration(request.POST)\n if fm.is_valid():\n print('Form Validated')\n name = fm.cleaned_data['name']\n email = fm.cleaned_data['email']\n print('Name', name)\n print('Email', email)\n\n else:\n\n fm = StudentRegistration()\n\n print('get se aaya hai')\n\n\n \n return render(request, 'enroll/userregistration.html', {'form': fm})\n","sub_path":"gs37/enroll/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":572,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"354498745","text":"import logging\nimport typing\n\nfrom app.models.api.util.exception import NotFound, ServerError\nfrom app.routes.utils import Namespace, get_module_routers\nfrom fastapi import APIRouter\n\n\nlogger = logging.getLogger(__name__)\n\n\ndef get_router() -> APIRouter:\n router = APIRouter()\n\n namespaces: typing.Dict[str, Namespace] = {\n \"user\": {\n \"resources\": [\"candidate\", \"job\"],\n # \"dependencies\": [Depends(api_security.get_auth_user_id)], # type: ignore\n },\n }\n\n for name, namespace in namespaces.items():\n logger.debug(\"Mounting namespace: %s\", name)\n for resource in namespace[\"resources\"]:\n module_name = f\"app.routes.v1.{resource}\"\n logger.debug(\"\\tMounting %s\", module_name)\n for sub_router in get_module_routers(module_name):\n router.include_router(\n sub_router,\n prefix=f\"/{resource}\",\n tags=[resource.capitalize()],\n dependencies=namespace.get(\"dependencies\", []),\n responses={500: {\"model\": ServerError}, 404: {\"model\": NotFound}},\n )\n\n return router\n","sub_path":"app/routes/v1/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1176,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"40372843","text":"#!/usr/bin/env python\n# coding=utf-8\n\"\"\"\n\n\"\"\"\n\n\ndef get_season_mask_from_dti(dti, season_months):\n mask = None\n for m in season_months:\n if mask is None:\n mask = dti.month == m\n else:\n mask = mask | (dti.month == m)\n return mask\n\n\ndef select_seasonal_from_index_data(index_data, season_months):\n mask = get_season_mask_from_dti(index_data.index, season_months)\n return index_data[mask]\n\n\ndef select_seasonal_from_var(ncvar, dti, season_months):\n mask = get_season_mask_from_dti(dti, season_months)\n return ncvar[mask, :, :]\n\n\ndef anoms(dat, dti):\n res = np.empty(dat.shape)\n for month in range(1, 13):\n n = dat[dti.month == month, :, :].mean(axis=0)\n mv = dat[dti.month == month, :, :]\n mr = mv - n\n res[dti.month == month, :, :] = mr\n return np.ma.masked_less(res, -9999)\n\n\nif __name__ == '__main__':\n import os\n import pickle\n import common\n from common import get_pdo, get_nino34, get_idx_mask\n import numpy as np\n import netCDF4\n import datetime\n import pandas as pd\n\n var = 'sst'\n\n var_fn = 'ersst.v5.188001-202001.nc'\n\n # prepare index data\n nino = get_nino34()\n pdo = get_pdo()\n index_data = pd.DataFrame({'pdo': pdo, 'nino': nino})\n index_data = index_data.dropna()\n index_data = index_data[(index_data.index.year >= common.y_min) * (index_data.index.year <= common.y_max)]\n index_data['idx'] = pd.Series(data=range(len(index_data)), index=index_data.index)\n\n # read var data\n fn = os.path.join(common.data_path, var_fn)\n nc = netCDF4.Dataset(fn, 'r')\n lats = np.array(nc.variables['lat'][:])\n lons = np.array(nc.variables['lon'][:])\n dates = netCDF4.num2date(nc.variables['time'][:], nc.variables['time'].units, calendar=nc.variables['time'].calendar)\n dates = [datetime.datetime(d.year, d.month, 1) for d in dates]\n dti = pd.DatetimeIndex(dates)\n\n var_arr = np.array(nc.variables[var][dti > index_data.index[0], 0, :, :])\n dti = dti[dti > index_data.index[0]]\n var_arr[var_arr < -998] = np.nan\n var_arr = anoms(var_arr, dti)\n\n # for each phase\n for season_name, smonths, nino_sign, pdo_sign, fig_num in common.ensopdo_combinations_generator():\n # use only data for months is this season\n index_data_season = select_seasonal_from_index_data(index_data, smonths)\n try:\n with open(common.get_cache_mean_fn(var, season_name, fig_num), 'rb') as f:\n res_mean = pickle.load(f)\n except FileNotFoundError:\n # use only data for specific phase\n mask = get_idx_mask(index_data_season, 'nino', nino_sign, common.nino_th) & get_idx_mask(index_data_season, 'pdo', pdo_sign, common.pdo_th)\n idx = index_data_season[mask]['idx'].values\n if len(idx) == 0:\n print('skipped', season_name, smonths, nino_sign, pdo_sign, fig_num)\n continue\n selected_values = var_arr[idx, :, :]\n res_mean = selected_values.mean(axis=0)\n # selected_prcnt = selected_values / res_prcnt\n with open(common.get_cache_mean_fn(var, season_name, fig_num), 'wb') as f:\n pickle.dump(res_mean, f)\n\n","sub_path":"prepare_erSST_per_phase.py","file_name":"prepare_erSST_per_phase.py","file_ext":"py","file_size_in_byte":3232,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"123251897","text":"class Flux_densities:\n \n def __init__(self,acfluxes,dcfluxes):\n \n self.acfluxes = acfluxes\n self.dcfluxes = dcfluxes\n \n self.leg_segments = self.acfluxes.permeances.leg_segments\n self.segment_areas = self.acfluxes.permeances.core.segment_areas\n self.time_states = self.acfluxes.time_states\n \n self.deltaflux = self.acfluxes.deltaflux\n self.bac_offset = self.acfluxes.offset\n \n self.bac = {state:{leg:{segment:deltaflux_leg/self.segment_areas[segment] for segment in self.leg_segments[leg]} \n for leg,deltaflux_leg in deltaflux_state.items()} \n for state,deltaflux_state in self.deltaflux.items()}\n self.bdc = {state:{leg:{segment:dcflux_leg/self.segment_areas[segment] for segment in self.leg_segments[leg]} \n for leg,dcflux_leg in dcflux_state.items()} \n for state,dcflux_state in self.dcfluxes.dc_flux.items()}\n self.bpeak = {state:{leg:{segment:bdc_segment+self.bac[state][leg][segment]/2 for segment,bdc_segment in bdc_leg.items()} \n for leg,bdc_leg in bdc_state.items()} \n for state,bdc_state in self.bdc.items()}\n \n self.bac_max_with_key, self.bac_max = self.max_by_leg(self.bac)\n self.bdc_max_with_key, self.bdc_max = self.max_by_leg(self.bdc)\n self.bpeak_max_with_key, self.bpeak_max = self.max_by_leg(self.bpeak)\n \n def max_by_leg(self,bdict):\n def absmax(b_dict):\n absv=[abs(val) for val in b_dict.values()]\n k=list(b_dict.keys())\n m=max(absv)\n mkey=k[absv.index(m)]\n return {mkey:b_dict[mkey]} \n withkey = {state:{leg: absmax(b_legs) for leg,b_legs in b_state.items()} \n for state,b_state in bdict.items()}\n withoutkey = {state:{leg: list(absmax(b_legs).values())[0] for leg,b_legs in b_state.items()} \n for state,b_state in bdict.items()} \n return withkey,withoutkey","sub_path":"libs/flux_densities.py","file_name":"flux_densities.py","file_ext":"py","file_size_in_byte":2125,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"349710093","text":"from django.conf import settings\nfrom rest_framework import serializers\nfrom rest_framework.validators import UniqueTogetherValidator\n\nfrom file_processing.models import FileModel\nfrom file_processing.utils import extract_currency, extract_date\nfrom suppliers.models import Transaction\nfrom . import validators\n\nimport logging\nlogger = logging.getLogger(__name__)\n\nclass FileUploadSerializer(serializers.ModelSerializer):\n file = serializers.FileField(\n use_url=False, # to not have filename as full url in response\n validators=[\n validators.MimeTypeValidator(settings.ALLOWED_MIME_TYPES),\n validators.FileNameValidator(settings.FILENAME_REGEX)\n ])\n\n class Meta(object):\n model = FileModel\n fields = [\n 'file'\n ]\n\n def validate(self, attrs):\n logger.info('Running file validation on: {0}'.format(attrs['file']))\n attrs = self.validate_currency(attrs)\n attrs = self.validate_date(attrs)\n attrs = self.validate_supplier_id(attrs)\n\n self.validate_unique_file(attrs)\n self.validate_unique_transaction(attrs)\n return attrs\n\n def validate_currency(self, attrs):\n try:\n attrs['currency'] = extract_currency(attrs['file'].name)\n except (AttributeError, IndexError):\n raise serializers.ValidationError('Currency is not recognized.')\n return attrs\n\n def validate_date(self, attrs):\n try:\n attrs['date'] = extract_date(attrs['file'].name)\n except (AttributeError, IndexError, ValueError):\n raise serializers.ValidationError('Bad date format.')\n return attrs\n\n def validate_supplier_id(self, attrs):\n attrs['supplier_id'] = self.context['request'].user.id\n return attrs\n\n def validate_unique_file(self, attrs):\n validator = UniqueTogetherValidator(\n queryset=self.Meta.model.objects.all(),\n fields=('supplier_id', 'date', 'currency')\n )\n validator.set_context(self)\n validator(attrs)\n\n def validate_unique_transaction(self, attrs):\n validator = UniqueTogetherValidator(\n queryset=Transaction.objects.all(),\n fields=('product__supplier_id', 'delivered', 'customer__currency')\n )\n validator.set_context(self)\n validator({\n 'product__supplier_id': attrs['supplier_id'],\n 'customer__currency': attrs['currency'],\n 'delivered': attrs['date'],\n })\n","sub_path":"api/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":2519,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"563408894","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.7 (3394)\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.15-x86_64/egg/metadata_client/tests/modules/experiment_type_test.py\n# Compiled at: 2017-06-19 07:48:53\n# Size of source mod 2**32: 5078 bytes\n\"\"\"ExperimentTypeTest class\"\"\"\nimport unittest\nfrom metadata_client.metadata_client import MetadataClient\nfrom .module_base import ModuleBase\nfrom ..common.config_test import *\nfrom common.generators import Generators\nfrom ..common.secrets import *\nfrom modules.experiment_type import ExperimentType\nMODULE_NAME = EXPERIMENT_TYPE\n\nclass ExperimentTypeTest(ModuleBase, unittest.TestCase):\n\n def setUp(self):\n self.mdc_client = MetadataClient(client_id=(CLIENT_OAUTH2_INFO['CLIENT_ID']),\n client_secret=(CLIENT_OAUTH2_INFO['CLIENT_SECRET']),\n token_url=(CLIENT_OAUTH2_INFO['TOKEN_URL']),\n refresh_url=(CLIENT_OAUTH2_INFO['REFRESH_URL']),\n auth_url=(CLIENT_OAUTH2_INFO['AUTH_URL']),\n scope=(CLIENT_OAUTH2_INFO['SCOPE']),\n user_email=(CLIENT_OAUTH2_INFO['EMAIL']),\n base_api_url=BASE_API_URL)\n _ExperimentTypeTest__unique_name1 = Generators.generate_unique_name('ExperimentType01')\n _ExperimentTypeTest__unique_identifier1 = Generators.generate_unique_identifier()\n self.exp_typ_01 = {'name':_ExperimentTypeTest__unique_name1, \n 'identifier':_ExperimentTypeTest__unique_identifier1, \n 'flg_available':'true', \n 'description':'desc 01'}\n _ExperimentTypeTest__unique_name_upd = Generators.generate_unique_name('ExperimTypeUpd1')\n _ExperimentTypeTest__unique_identifier_upd = Generators.generate_unique_identifier(1)\n self.exp_typ_01_upd = {'name':_ExperimentTypeTest__unique_name_upd, \n 'identifier':_ExperimentTypeTest__unique_identifier_upd, \n 'flg_available':'false', \n 'description':'desc 01 Updated!'}\n\n def test_create_experiment_type(self):\n exp_typ_01 = ExperimentType(metadata_client=(self.mdc_client),\n name=(self.exp_typ_01['name']),\n identifier=(self.exp_typ_01['identifier']),\n flg_available=(self.exp_typ_01['flg_available']),\n description=(self.exp_typ_01['description']))\n result1 = exp_typ_01.create()\n self.assert_create_success(MODULE_NAME, result1, self.exp_typ_01)\n experiment_type = result1['data']\n experiment_type_id = result1['data']['id']\n experiment_type_name = result1['data']['name']\n exp_typ_01_dup = exp_typ_01\n result2 = exp_typ_01_dup.create()\n expect_app_info = {'name': ['has already been taken']}\n self.assert_create_error(MODULE_NAME, result2, expect_app_info)\n result3 = ExperimentType.get_by_name(self.mdc_client, experiment_type_name)\n self.assert_find_success(MODULE_NAME, result3, self.exp_typ_01)\n result4 = ExperimentType.get_by_id(self.mdc_client, experiment_type_id)\n self.assert_find_success(MODULE_NAME, result4, self.exp_typ_01)\n result5 = ExperimentType.get_by_id(self.mdc_client, -666)\n self.assert_find_error(MODULE_NAME, result5, RESOURCE_NOT_FOUND)\n exp_typ_01.name = self.exp_typ_01_upd['name']\n exp_typ_01.identifier = self.exp_typ_01_upd['identifier']\n exp_typ_01.flg_available = self.exp_typ_01_upd['flg_available']\n exp_typ_01.description = self.exp_typ_01_upd['description']\n result6 = exp_typ_01.update()\n self.assert_update_success(MODULE_NAME, result6, self.exp_typ_01_upd)\n exp_typ_01.name = '__THIS_NAME_IS_1_CHARACTERS_LONGER_THAN_THE_ALLOWED_MAX_NUM__'\n exp_typ_01.flg_available = self.exp_typ_01_upd['flg_available']\n exp_typ_01.description = self.exp_typ_01_upd['description']\n result7 = exp_typ_01.update()\n expect_app_info = {'name': ['is too long (maximum is 60 characters)']}\n self.assert_update_error(MODULE_NAME, result7, expect_app_info)\n result8 = exp_typ_01.delete()\n self.assert_delete_success(MODULE_NAME, result8)\n result9 = exp_typ_01.delete()\n self.assert_delete_error(MODULE_NAME, result9, RESOURCE_NOT_FOUND)\n\n def fields_validation(self, receive, expect):\n self.assert_eq_hfield(receive, expect, 'name', STRING)\n self.assert_eq_hfield(receive, expect, 'identifier', STRING)\n self.assert_eq_hfield(receive, expect, 'flg_available', BOOLEAN)\n self.assert_eq_hfield(receive, expect, 'description', STRING)\n\n\nif __name__ == '__main__':\n unittest.main()","sub_path":"pycfiles/metadata_client-3.0.5-py3.7/experiment_type_test.cpython-37.py","file_name":"experiment_type_test.cpython-37.py","file_ext":"py","file_size_in_byte":4610,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"51252669","text":"import redis, ast\nfrom collections import OrderedDict\nfrom django.shortcuts import render_to_response\nfrom django.template.context import RequestContext\n\n\ndef index(request):\n r = redis.StrictRedis(host='localhost', port=6379, db=0)\n if r.get('gainer') or r.get('loser'):\n g = r.get('gainer')\n l = r.get('loser')\n g_data_dict = ast.literal_eval(g)\n l_data_dict = ast.literal_eval(l)\n gain_data_list = []\n for g_k, g_v in OrderedDict(g_data_dict).items():\n for gain_header in g_v:\n gain_data_list.append(gain_header)\n loss_data_list = []\n for l_k, l_v in OrderedDict(l_data_dict).items():\n for loss_header in l_v:\n loss_data_list.append(loss_header)\n return render_to_response('nifty50_table.html',{'gainer_list':gain_data_list,'loser_list':loss_data_list},RequestContext(request))\n","sub_path":"nifty/nifty50/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":902,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"25907980","text":"import requests\nimport json\nimport xlsxwriter\nfrom datetime import datetime\nworkbook = xlsxwriter.Workbook('PamAir-Data-09-08-2021.xlsx')\nurl_='https://api.pamair.org/services/airstation'\n\nheaders_airs={\n 'authorization': 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpYXQiOjE2Mjg0OTYzMTgsImV4cCI6MTYyODQ5NjYxOCwiYXVkIjoiL3NlcnZpY2VzL2FpcnN0YXRpb24iLCJzdWIiOiIzY2Y5ZDk4OC1kMmQ5LTQ1YTEtOGM5Yy0zNTUyODQ5OTA5YzciLCJpc3MiOiJwYW1haXItcGFydG5lciJ9.gmHS8Tyb3DHc9-99NPkQpezGZQQaqRcYUJ20SPtg4RE',\n 'content-type': 'application/json',\n 'clientid':'3cf9d988-d2d9-45a1-8c9c-3552849909c7'\n}\nresult= requests.get(url_,headers=headers_airs)\nres_json=result.json()\n#print(res_json)\nurl_2=\"https://api.pamair.org/services/airusaqi24\"\nheaders_airs24={\n 'authorization': 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpYXQiOjE2Mjg0OTY0NTYsImV4cCI6MTYyODQ5Njc1NiwiYXVkIjoiL3NlcnZpY2VzL2FpcnVzYXFpMjQiLCJzdWIiOiIzY2Y5ZDk4OC1kMmQ5LTQ1YTEtOGM5Yy0zNTUyODQ5OTA5YzciLCJpc3MiOiJwYW1haXItcGFydG5lciJ9.5946FFE_b2vMVA3crfNZd8T_Fu0_i772E6O6eQyFaCE',\n 'clientid':'3cf9d988-d2d9-45a1-8c9c-3552849909c7',\n 'content-type': 'application/json'\n}\nlist__=[]\nfor row in res_json[\"data\"]:\n print(row[\"idst\"])\n print(\"\\n\")\n payload={\"idst\": row[\"idst\"]}\n str_loca=\"\"\n if len(row[\"nameVi\"])>31:\n for x in range(0,29):\n str_loca=str_loca+row[\"nameVi\"][x]\n print(str_loca)\n else:\n str_loca=row[\"nameVi\"]\n if str_loca==\"Đường 1/4\":\n str_loca=\"Đường 1-4\"\n rum=1 \n try:\n rum=1\n worksheet=workbook.add_worksheet(str_loca)\n except:\n rum+=1\n worksheet=workbook.add_worksheet(str_loca+\"-\"+str(rum))\n res_row=requests.post(url_2,data=json.dumps(payload),headers=headers_airs24)\n res_obj=res_row.json()[\"aqi\"]\n row_line=1\n col_line=0\n worksheet.write(0,col_line,\"TIME\")\n worksheet.write(0,col_line+1,\"AQI\")\n worksheet.write(0,col_line+2,\"Location\")\n worksheet.write(1,col_line+2,row[\"infoLo\"])\n for x in res_obj:\n dt_obj = datetime.fromtimestamp(int(x[\"longtime\"])/1000)\n print(type(dt_obj))\n print(\"\\n\")\n value=x[\"value\"]\n worksheet.write(row_line,col_line,str(dt_obj))\n worksheet.write(row_line,col_line+1,value)\n row_line+=1\n list__.append(res_row)\nworkbook.close()\nprint(len(list__))\n\n\n\n\n","sub_path":".ipynb_checkpoints/arm-checkpoint.py","file_name":"arm-checkpoint.py","file_ext":"py","file_size_in_byte":2346,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"545583672","text":"import os\nimport math\nimport random\nimport copy\nimport array\nimport scipy.ndimage\nimport matplotlib.pyplot as plt\nimport numpy as np\n\ndef read_environment(envfile):\n\tef = open(envfile)\n\tenvironment = ef.readlines()\n\timg_width = int(environment[0])\n\timg_height = int(environment[1])\n\tnum_view = int(environment[2])\n\tmax_bound = int(environment[3])\n\tmin_bound = int(environment[4])\n\tpixel_mean = float(environment[5])\n\tef.close()\n\treturn img_width, img_height, num_view, max_bound, min_bound, pixel_mean\n\ndef get_serie_uid(filepath):\n\tfilename = os.path.basename(filepath)\n\tfileparts = os.path.splitext(filename)\n\treturn fileparts[0]\n\t\ndef write_mhd_file(mhdfile, data, dsize):\n\tdef write_meta_header(filename, meta_dict):\n\t\theader = ''\n\t\t# do not use tags = meta_dict.keys() because the order of tags matters\n\t\ttags = ['ObjectType', 'NDims', 'BinaryData', 'NoduleDiameter'\n\t\t\t'BinaryDataByteOrderMSB', 'CompressedData', 'CompressedDataSize',\n\t\t\t'TransformMatrix', 'Offset', 'CenterOfRotation',\n\t\t\t'AnatomicalOrientation',\n\t\t\t'ElementSpacing',\n\t\t\t'DimSize',\n\t\t\t'ElementType',\n\t\t\t'ElementDataFile',\n\t\t\t'Comment', 'SeriesDescription', 'AcquisitionDate', 'AcquisitionTime', 'StudyDate', 'StudyTime']\n\t\tfor tag in tags:\n\t\t\tif tag in meta_dict.keys():\n\t\t\t\theader += '%s = %s\\n' % (tag, meta_dict[tag])\n\t\tf = open(filename, 'w')\n\t\tf.write(header)\n\t\tf.close()\n\tdef dump_raw_data(filename, data):\n\t\t\"\"\" Write the data into a raw format file. Big endian is always used. \"\"\"\n\t\t#---write data to file\n\t\t# Begin 3D fix\n\t\tdata = data.reshape([data.shape[0], data.shape[1] * data.shape[2]])\n\t\t# End 3D fix\n\t\trawfile = open(filename, 'wb')\n\t\ta = array.array('f')\n\t\tfor o in data:\n\t\t\ta.fromlist(list(o))\n\t\t# if is_little_endian():\n\t\t# a.byteswap()\n\t\ta.tofile(rawfile)\n\t\trawfile.close()\n\t\t\n\tassert (mhdfile[-4:] == '.mhd')\n\tmeta_dict = {}\n\tmeta_dict['ObjectType'] = 'Image'\n\tmeta_dict['BinaryData'] = 'True'\n\tmeta_dict['BinaryDataByteOrderMSB'] = 'False'\n\tmeta_dict['ElementType'] = 'MET_FLOAT'\n\tmeta_dict['NDims'] = str(len(dsize))\n\tmeta_dict['DimSize'] = ' '.join([str(i) for i in dsize])\n\tmeta_dict['ElementDataFile'] = os.path.split(mhdfile)[1].replace('.mhd', '.raw')\n\twrite_meta_header(mhdfile, meta_dict)\n\tpwd = os.path.split(mhdfile)[0]\n\tif pwd:\n\t\tdata_file = pwd + '/' + meta_dict['ElementDataFile']\n\telse:\n\t\tdata_file = meta_dict['ElementDataFile']\n\tdump_raw_data(data_file, data)\n\ndef set_window_width(image, MIN_BOUND=-1024.0):\n\timage[image < MIN_BOUND] = MIN_BOUND\n\treturn image\n\t\ndef coord_overflow(coord, shape):\n\tupbound = shape - coord\t\n\tif coord[coord<0].size>0 or upbound[upbound<=0].size>0:\n\t\treturn True\n\telse:\n\t\treturn False\n\ndef resample(image, old_spacing, new_spacing=[1, 1, 1]):\n\tresize_factor = old_spacing / new_spacing\n\tnew_real_shape = image.shape * resize_factor\n\tnew_shape = np.round(new_real_shape)\n\treal_resize_factor = new_shape / image.shape\n\tnew_spacing = old_spacing / real_resize_factor\n\tif image.shape[0]<1000:\n \timage = scipy.ndimage.interpolation.zoom(image, real_resize_factor, mode='nearest')\n\telse:\n\t\tnum_batch = int(math.ceil(image.shape[0]/1000))\n\t\tfor b in range(num_batch):\n\t\t\timage_batch = image[b*1000:min((b+1)*1000,image.shape[0]), :, :]\n\t\t\timage_batch = scipy.ndimage.interpolation.zoom(image_batch, real_resize_factor, mode='nearest')\n\t\t\tif 'new_image' in dir():\n\t\t\t\tnew_image = np.append(new_image, image_batch, axis=0)\n\t\t\telse:\n\t\t\t\tnew_image = image_batch\n\t\timage = new_image\n\n\treturn image, new_spacing\n\ndef make_patchs(voxel):\n\twidth, length, height = voxel.shape\n\tpatch_size = np.min(voxel.shape)\n\tpatchs = np.zeros(shape=(9,patch_size,patch_size), dtype = float)\n\tpatchs[0] = voxel[:,:,int(height/2)]\n\tpatchs[1] = voxel[:,int(length/2),:]\n\tpatchs[2] = voxel[int(width/2),:,:]\n\tfor h in range(height):\n\t\tpatchs[3,:,h] = voxel[:,h,h]\n\t\tpatchs[4,h,:] = voxel[h,:,h]\n\t\tpatchs[5,:,h] = voxel[:,h,height-h-1]\n\t\tpatchs[6,h,:] = voxel[h,:,height-h-1]\n\tfor w in range(width):\n\t\tpatchs[7,w,:] = voxel[w,w,:]\n\t\tpatchs[8,w,:] = voxel[width-w-1,w,:]\n\t\n\treturn patchs\n\ndef concatenate_patchs(patchs, num_channels=3):\n\timg_height = patchs.shape[1]\n\timg_width = patchs.shape[2]\n\thalf_width = int(img_width/2)\n\thalf_height = int(img_height/2)\n\n\t#3 orders of patch indices\n\tpatch_indices_list = []\n\tpatch_indices = [ind for ind in range(9)]\n\tpatch_indices_list.append(patch_indices)\n\tpatch_indices_list.append(copy.copy(patch_indices))\n\tpatch_indices_list.append(copy.copy(patch_indices))\n\t#random.shuffle(patch_indices_list[0])\n\trandom.shuffle(patch_indices_list[1])\n\tpatch_indices_list[2].reverse()\n\n\tpatch_chan = np.zeros(shape=(4*img_height,4*img_width,num_channels), dtype=float)\n\tfor c in range(num_channels):\n\t\tpatch_indices = patch_indices_list[c]\n\t\taug_patch = np.ndarray(shape=(9*img_height, 9*img_width), dtype=float)\n\t\tfor h in range(3):\n\t\t\tfor w in range(3):\n\t\t\t\tfor hi in range(3):\n\t\t\t\t\tfor wi in range(3):\n\t\t\t\t\t\taug_patch[(h*3+hi)*img_height:(h*3+hi+1)*img_height, (w*3+wi)*img_width:(w*3+wi+1)*img_width] = patchs[patch_indices[hi*3+wi]]\n\t\tpatch_chan[:,:,c] = aug_patch[2*img_height+half_height:7*img_height-half_height, 2*img_width+half_width:7*img_width-half_width]\n\n\treturn patch_chan\n\ndef nodule_cluster(nodule_centers, scale, iterate=False):\n\tprint(\"Clustering:\")\n\tclusters=[]\n\tl=len(nodule_centers)\n\tif l==0:\n\t\treturn clusters\n\tcenter_index_cluster = 0 - np.ones(len(nodule_centers), dtype=int)\n\t#initial clustering\n\tpoint = nodule_centers[l-1]\t#point is a list\n\tcenter_index_cluster[l-1] = 0\n\tclusters.append([point, point, 1])\n\tfor i in range(l-1):\n\t\tpoint = nodule_centers[i] #The current point to be clustered\n\t\tflag = 0\n\t\tnearsqdist = scale * scale\n\t\tnearcand = -1\n\t\t#find the older cluster\n\t\tfor j in range(len(clusters)):\n\t\t\t#calculate the distance with only coordination but prediction\n\t\t\tsqdist = (point[0]-clusters[j][0][0])*(point[0]-clusters[j][0][0]) + (point[1]-clusters[j][0][1])*(point[1]-clusters[j][0][1]) + (point[2]-clusters[j][0][2])*(point[2]-clusters[j][0][2])\n\t\t\tif sqdist=0 and nearcand!=center_index_cluster[i]:\n\t\t\t\t\tconverge = False\n\t\t\t\t\toldcand = center_index_cluster[i]\n\t\t\t\t\tif oldcand>=0:\n\t\t\t\t\t\tclusters[oldcand][1] = [(clusters[oldcand][1][0] - point[0]),\n\t\t\t\t\t\t\t\t\t\t\t\t (clusters[oldcand][1][1] - point[1]),\n\t\t\t\t\t\t\t\t\t\t\t\t (clusters[oldcand][1][2] - point[2]),\n\t\t\t\t\t\t\t\t\t\t\t\t (clusters[oldcand][1][3] - point[3])]\n\t\t\t\t\t\tclusters[oldcand][2] = clusters[oldcand][2] - 1\n\t\t\t\t\t\tclusters[oldcand][0] = [(clusters[oldcand][1][0]) / clusters[oldcand][2],\n\t\t\t\t\t\t\t\t\t\t\t\t(clusters[oldcand][1][1]) / clusters[oldcand][2],\n\t\t\t\t\t\t\t\t\t\t\t\t(clusters[oldcand][1][2]) / clusters[oldcand][2],\n\t\t\t\t\t\t\t\t\t\t\t\t(clusters[oldcand][1][3]) / clusters[oldcand][2]]\n\t\t\t\t\tclusters[nearcand][1] = [(clusters[nearcand][1][0]+point[0]),\n\t\t\t\t\t\t\t\t(clusters[nearcand][1][1]+point[1]),\n\t\t\t\t\t\t\t\t(clusters[nearcand][1][2]+point[2]),\n\t\t\t\t\t\t\t\t(clusters[nearcand][1][3]+point[3])]\n\t\t\t\t\tclusters[nearcand][2] = clusters[nearcand][2]+1\n\t\t\t\t\tclusters[nearcand][0] = [(clusters[nearcand][1][0]) / clusters[nearcand][2],\n\t\t\t\t\t\t\t\t\t\t\t (clusters[nearcand][1][1]) / clusters[nearcand][2],\n\t\t\t\t\t\t\t\t\t\t\t (clusters[nearcand][1][2]) / clusters[nearcand][2],\n\t\t\t\t\t\t\t\t\t\t\t (clusters[nearcand][1][3]) / clusters[nearcand][2]]\n\t\t\t\t\tcenter_index_cluster[i] = nearcand\n\tsolid_clusters = [c for c in clusters if c[2]>0]\n\tprint('Clustering Done')\n\n\treturn solid_clusters","sub_path":"toolbox/MITools.py","file_name":"MITools.py","file_ext":"py","file_size_in_byte":9045,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"615098660","text":"#!/bin/env python\n# -*- coding: utf-8 -*-\nfrom ... import config\nfrom ...lib import utils\nfrom ..index import Index\nfrom .. import file_entity\nfrom sqlalchemy import and_\nfrom threading import Thread\nfrom sqlalchemy import insert\nfrom sqlalchemy import update\nfrom sqlalchemy import delete\nfrom .. import document_entity\nfrom . import CustomContextFactory\nfrom ..entities import LBIndexError\nfrom sqlalchemy.util import KeyedTuple\nfrom sqlalchemy.orm.state import InstanceState\nfrom liblightbase.lbdoc.doctree import DocumentTree\nfrom ...lib import cache\nimport logging\n\nlog = logging.getLogger()\n\n\nclass DocumentContextFactory(CustomContextFactory):\n\n \"\"\" Document Factory Methods.\n \"\"\"\n\n def __init__(self, request, next_id_fn=None):\n super(DocumentContextFactory, self).__init__(request)\n\n # liblightbase.lbbase.Base object\n base = self.get_base()\n\n # LBDoc_ object (mapped ORM entity).\n self.entity = document_entity(self.base_name,\n next_id_fn=next_id_fn,\n **base.relational_fields)\n\n # LBFile_ object (mapped ORM entity).\n self.file_entity = file_entity(self.base_name)\n\n # Index object \n self.index = Index(base, self.get_full_document)\n\n def create_files(self, member, files):\n \"\"\"\n Create files (actually update id_doc, because file already exists)\n in database.\n @param files: List of file id's to create in database.\n \"\"\"\n if len(files) > 0:\n stmt = update(self.file_entity.__table__).where(\n self.file_entity.__table__.c.id_file.in_(files))\\\n .values(id_doc=member.id_doc)\n self.session.execute(stmt)\n\n def delete_files(self, member, files):\n \"\"\"\n Will delete files that are not present in document.\n @param member: LBDoc_ object (mapped ORM entity).\n @param files: List of files ids present in document.\n \"\"\"\n where_clause = [(self.file_entity.__table__.c.id_doc==member.id_doc)]\n if len(files) > 0:\n notin_clause = self.file_entity.__table__.c.id_file.notin_(files)\n where_clause.append(notin_clause)\n where_clause = and_(*where_clause)\n stmt = delete(self.file_entity.__table__).where(where_clause)\n else:\n stmt = delete(self.file_entity.__table__).where(*where_clause)\n self.session.execute(stmt)\n\n def create_member(self, data):\n \"\"\" \n @param data: dictionary at the format {column_name: value}.\n Receives the data to INSERT at database (table lb_doc_).\n Here the document will be indexed, and files within it will be created.\n \"\"\"\n member = self.entity(**data)\n self.session.add(member)\n self.create_files(member, data['__files__'])\n for name in data:\n setattr(member, name, data[name])\n self.session.commit()\n self.session.close()\n if self.index.is_indexable:\n Thread(target=self.async_create_member,\n args=(data, self.session)).start()\n return member\n\n def async_create_member(self, data, session):\n \"\"\" \n Called as a process. This method will update dt_idx in case of\n success while asyncronous indexing.\n \"\"\"\n ok, data = self.index.create(data)\n if ok:\n datacopy = data.copy()\n data.clear()\n data['document'] = datacopy['document']\n data['dt_idx'] = datacopy['dt_idx']\n stmt = update(self.entity.__table__).where(\n self.entity.__table__.c.id_doc == datacopy['id_doc'])\\\n .values(**data)\n session.begin()\n try:\n session.execute(stmt)\n session.commit()\n except:\n pass\n finally:\n session.close()\n\n def update_member(self, member, data, index=True):\n \"\"\" \n Receives the data to UPDATE at database (table lb_doc_). \n Here the document will be indexed, files within it will be created,\n and files that are not in document will be deleted.\n @param member: LBDoc_ object (mapped ORM entity).\n @param data: dictionary at the format {column_name: value}.\n @param index: Flag that indicates the need of indexing the\n document. \n \"\"\"\n self.delete_files(member, data['__files__'])\n self.create_files(member, data['__files__'])\n data.pop('__files__')\n stmt = update(self.entity.__table__).where(\n self.entity.__table__.c.id_doc == data['id_doc'])\\\n .values(**data)\n self.session.execute(stmt)\n self.session.commit()\n self.session.close()\n if index and self.index.is_indexable:\n Thread(target=self.async_update_member,\n args=(data['id_doc'], data, self.session)).start()\n\n # Clear cache\n log.debug(\"Realizando limpeza de cache para a base %s\", self.base_name)\n #cache.clear_document_cache(self.base_name, data['id_doc'])\n cache.clear_collection_cache(self.base_name)\n\n return member\n\n def async_update_member(self, id, data, session):\n \"\"\" \n Called as a process. This method will update dt_idx in case of\n success while asyncronous indexing.\n \"\"\"\n ok, data = self.index.update(id, data, session)\n if ok:\n datacopy = data.copy()\n data.clear()\n data['document'] = datacopy['document']\n data['dt_idx'] = datacopy['dt_idx']\n stmt = update(self.entity.__table__).where(\n self.entity.__table__.c.id_doc == datacopy['id_doc'])\\\n .values(**data)\n session.begin()\n try:\n session.execute(stmt)\n session.commit()\n except:\n pass\n finally:\n session.close()\n\n def delete_member(self, id):\n \"\"\" \n @param id: primary key (int) of document.\n\n Query the document object, verify the flag `dt_del`. If setted,\n that means that this document was deleted once, but it's index was not\n successfull deleted. So we delete the document. If not, will try to\n delete it's index and document. In case of failure, will SET all \n columns to NULL and clear document, leaving only it's metadata.\n \"\"\"\n stmt1 = delete(self.entity.__table__).where(\n self.entity.__table__.c.id_doc == id)\n stmt2 = delete(self.file_entity.__table__).where(\n self.file_entity.__table__.c.id_doc == id)\n self.session.execute(stmt1)\n self.session.execute(stmt2)\n self.session.commit()\n self.session.close()\n if self.index.is_indexable:\n Thread(target=self.async_delete_member,\n args=(id, self.session)).start()\n\n # Clear cache\n cache.clear_collection_cache(self.base_name)\n\n return True\n\n def async_delete_member(self, id, session):\n error, data = self.index.delete(id)\n if error:\n stmt = insert(LBIndexError.__table__).values(**data)\n session.begin()\n try:\n session.execute(stmt)\n session.commit()\n except:\n pass\n finally:\n session.close()\n\n def get_full_document(self, document, session=None):\n \"\"\" This method will return the document with files texts\n within it.\n \"\"\"\n if session is None:\n session = self.session\n id = document['_metadata']['id_doc']\n file_cols = (\n self.file_entity.id_file,\n self.file_entity.filetext,\n self.file_entity.dt_ext_text)\n dbfiles = session.query(*file_cols).filter_by(id_doc= id).all()\n session.close()\n files = { }\n if dbfiles:\n for dbfile in dbfiles:\n files[dbfile.id_file] = dict(filetext=dbfile.filetext)\n return self.put_doc_text(document, files)\n\n def put_doc_text(self, document, files):\n \"\"\" This method will parse a document, find files within it,\n and then update each file (with text, if exists)\n \"\"\"\n if type(document) is dict:\n _document = document.copy()\n elif type(document) is list:\n _document = {document.index(i): i for i in document}\n for k, v in _document.items():\n if type(v) is dict and utils.is_file_mask(v):\n _file = files.get(v['id_file'])\n if _file: v.update(_file)\n elif type(v) is dict or type(v) is list:\n document[k] = self.put_doc_text(v, files)\n return document\n\n def member_to_dict(self, member, fields=None):\n \"\"\"\n @param member: LBDoc_ object (mapped ORM entity).\n\n Converts @member object to SQLAlchemy's KeyedTuple, and then to\n Python's dictionary. Will also prune the dictionary member, if\n user send some nodes on query.\n \"\"\"\n try:\n dict_member = member._asdict()\n except AttributeError as e:\n # Continue parsing\n log.debug(\"Error parsing as dict!\\n%s\", e)\n if not isinstance(member, KeyedTuple):\n member = self.member2KeyedTuple(member)\n\n # Get document as dictionary object.\n dict_member = member._asdict()['document']\n\n fields = getattr(self,'_query', {}).get('select')\n if fields and not '*' in fields:\n # Will prune tree nodes.\n # dict_member can be None if method could not find any fileds\n # matching the nodes list.\n dict_member = DocumentTree(dict_member).prune(nodes=fields)\n\n return dict_member\n\n def to_json(self, value, fields=None, wrap=True):\n obj = self.get_json_obj(value, fields, wrap)\n if getattr(self, 'single_member', None) is True and type(obj) is list:\n obj = obj[0]\n return utils.object2json(obj)\n\n def get_files_text_by_document_id(self, id_doc, close_session=True):\n \"\"\"\n @param id_doc: id from document \n @param close_session: If true, will close current session, \n else will not.\n\n This method will return a dictonary in the format {id_file: filetext},\n with all docs referenced by @param: id_doc\n \"\"\"\n # Query documents\n files = self.session.query(self.file_entity.id_file,\n self.file_entity.filetext).filter_by(id_doc=id_doc).all() or [ ]\n\n if close_session is True:\n # Close session if param close_session is True\n self.session.close()\n\n files = { }\n for file_ in files:\n # Build dictionary\n files[file_.id_file] = file_.filetext\n\n return files","sub_path":"lbgenerator/model/context/document.py","file_name":"document.py","file_ext":"py","file_size_in_byte":10945,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"377783347","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sat Apr 01 17:51:29 2017\r\n\r\n@author: estok\r\n\"\"\"\r\n\r\nimport numpy as np\r\nA = np.arange(0,100).reshape(10,10)\r\nB = np.arange(100,200).reshape(10,10)\r\n\r\nreplace_every_nth=3\r\nreplacement=9\r\nv=3\r\nfor v in range(0, len(A), replace_every_nth):\r\n A[v] = replacement\r\n\r\nAmean=A.mean()\r\nBmax=B.max()\r\nC=np.multiply(B,Amean)\r\nCdet=np.linalg.det(C)\r\nv=Cdet+Bmax\r\nD=np.multiply(B,v)\r\na=(D - D%1)\r\nb=(np.floor(D))\r\n\r\nz=(Amean*Bmax)*4\r\nm = D.flat[np.abs(D - z).argmin()]\r\nprint(m)\r\n","sub_path":"Diplomovy_projekt/Numpy zadania/Numpy task3/riesenie3.py","file_name":"riesenie3.py","file_ext":"py","file_size_in_byte":510,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"301685279","text":"import pika\n\n\nclass PlayNotifier(object):\n def __init__(self,):\n self.host = 'localhost'\n self.connection = pika.BlockingConnection(pika.ConnectionParameters(self.host))\n self.channel = self.connection.channel()\n\n def publish_play(self, play: dict, gameIdentifier: int):\n exchange = 'plays-exchange'.format(gameIdentifier)\n routing_key = 'left-side-plays'.format(gameIdentifier)\n try:\n self.channel.basic_publish(exchange=exchange,\n routing_key=routing_key,\n body=play)\n except ConnectionError:\n print(\"DAMN YOU WABBIT!\")\n print(\"[x] Sent Score to Queue\")\n\n\n\n\n","sub_path":"main/service/notifiers/play.py","file_name":"play.py","file_ext":"py","file_size_in_byte":746,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"467344705","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\nimport argparse\nimport io\nimport os\nimport sys\n\ntry:\n from chatette.generator import Generator\n from chatette.parser import Parser\nexcept ImportError:\n from generator import Generator\n from parser import Parser\n\nDEFAULT_OUTPUT_FILENAME = \"output.json\"\nDEFAULT_TESTING_DATASET_FILENAME = \"testing-dataset.json\"\n\n\ndef main():\n argument_parser = argparse.ArgumentParser(\n description=\"Generates Rasa NLU datasets from a template file\",\n add_help=True)\n argument_parser.add_argument(\"input\", help=\"Path to template file\",\n type=str)\n argument_parser.add_argument(\"-o\", \"--out\", dest=\"output\", required=False,\n help=\"Output file path\",\n type=str, default=None)\n if len(sys.argv[1:]) == 0:\n argument_parser.print_help()\n argument_parser.exit()\n\n args = argument_parser.parse_args()\n\n template_file_path = args.input\n dir_path = os.path.dirname(template_file_path)\n output_filename = DEFAULT_OUTPUT_FILENAME\n\n if args.output:\n output_filename = args.output\n\n output_file_path = os.path.join(dir_path, output_filename)\n testing_filename = DEFAULT_TESTING_DATASET_FILENAME\n testing_file_path = os.path.join(dir_path, testing_filename)\n\n with io.open(template_file_path, 'r') as in_file:\n parser = Parser(in_file)\n parser.parse()\n # parser.printDBG()\n print(\"\")\n\n generator = Generator(output_file_path, testing_file_path, parser)\n generator.generate()\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"chatette/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":1638,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"14780101","text":"# The following codes are programmed by Shanran Tang\r\n# for Insight Data Engineering coding challenge.\r\n\r\nimport sys\r\n\r\n# Open the window.txt file and read the averanging window size\r\nwith open(sys.argv[1],'r') as file1:\r\n#with open('window.txt','r') as file1:\r\n window=int(file1.read())\r\nprint('The size of averaging window is %d.' % window)\r\n\r\n\r\n# Open the actual.txt file and read the data into a list of dictionaries\r\nprint('processing actual data ...')\r\nActual=[]\r\ni=0\r\nwith open(sys.argv[2],'r') as file2:\r\n#with open('actual-test.txt','r') as file2:\r\n actual_data=file2.readlines()\r\n \r\n # Read each line and put the data into a list assuming pipe-delimited\r\n for line in actual_data:\r\n line_list=line.split('|')\r\n actual_hour=float(line_list[0])\r\n actual_hour=int(round(actual_hour))\r\n actual_stock=line_list[1]\r\n actual_price=float(line_list[2])\r\n actual_price=round(actual_price,2)\r\n \r\n # Add an item at the end of the list when it reads the data of the next hour\r\n # assuming the data are listed in chronological order\r\n if actual_hour-i>0:\r\n Actual.append({})\r\n i=i+1\r\n \r\n Actual[actual_hour-1][actual_stock]=actual_price \r\n\r\n\r\n# Open the predicted.txt file and read the data into a list of dictionaries\r\nprint('processing predicted data ...')\r\nPredicted=[]\r\ni=0\r\nwith open(sys.argv[3],'r') as file3:\r\n predict_data=file3.readlines()\r\n # Read each line and put the data into a list assuming pipe-delimited\r\n for line in predict_data:\r\n line_list=line.split('|')\r\n predict_hour=float(line_list[0])\r\n predict_hour=int(round(predict_hour))\r\n predict_stock=line_list[1]\r\n predict_price=float(line_list[2])\r\n predict_price=round(predict_price,2)\r\n \r\n # Add an item at the end of the list when it reads the data of the next hour\r\n # assuming the data are listed in chronological order\r\n if predict_hour-i>0:\r\n Predicted.append({})\r\n i=i+1\r\n \r\n Predicted[predict_hour-1][predict_stock]=predict_price\r\n\r\n\r\n# Compute the hourly-averaged error and write the results in 'comparison.txt'\r\nprint('computing window-averaged errors ...')\r\nwith open(sys.argv[4],'w') as file4:\r\n for i in range(len(Predicted)-window+1):\r\n number=0 #'number' is the counter for the number of valid predictions found in one window\r\n error=0 #'error' is the sum of all the errors in one window\r\n for j in range(i,window+i): # Scan through all the hourly records in one window\r\n for stock in Predicted[j]: # Scan through all the stock in one dictionary in the lists\r\n if stock in Actual[j]:\r\n error=error+abs(Predicted[j][stock]-Actual[j][stock])\r\n number=number+1\r\n if number>0:\r\n c='%.2f' %(error/number)\r\n else: # Ouput 'NA' when there is no valid prediction found in one window\r\n c='NA'\r\n # Write the pipe-delimited data in 'comparison.txt'\r\n a=str(i+1)\r\n b=str(i+window)\r\n line_str=a+'|'+b+'|'+c+'\\n'\r\n file4.write(line_str) \r\nprint('Comparison has been done successfully!')\r\n\r\n","sub_path":"src/prediction-validation.py","file_name":"prediction-validation.py","file_ext":"py","file_size_in_byte":3267,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"237689238","text":"#!/usr/bin/env python\n\nimport webapp2\nimport codecs\nimport cgi\n\nform = \"\"\"\n
\n

ROT 13

\n
\n\n \n\n
\n
\n \n
\n\"\"\"\n\n\nclass Rot13Handler(webapp2.RequestHandler):\n def get(self):\n self.response.headers['Content-Type'] = 'text/html'\n self.response.write(form % {\"text\": \"\"})\n\n def post(self):\n text = self.request.get(\"text\")\n\n text = codecs.encode(text, 'rot_13')\n text = cgi.escape(text)\n\n self.response.headers['Content-Type'] = 'text/html'\n self.response.write(form % {\"text\": text})\n","sub_path":"Week2/rot13.py","file_name":"rot13.py","file_ext":"py","file_size_in_byte":705,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"338738061","text":"# -*- coding: windows-1250 -*-\nimport logging\nfrom struct import *\n\nlogger = logging.getLogger('Endicator')\n\n##All the packets for the control and notification channel share a common header format:\n## 1 2 3\n##0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1\n##+-------------------------------+------------------------------+\n##| FIXED | Message ID |\n##+-------------------------------+------------------------------+\n##| Vendor ID |\n##+-------------------------------+------------------------------+\n##| Length |\n##+-------------------------------+\n##FIXED: Must be 0x8001 for commands and 0x0001 for responses.\n##Message ID: Id of the message. It is a sequence number used to map requests to its responses: a request and its corresponding response have the same message ID (the id is local to the channel).\n##Vendor ID: Must be 21336: the IANA “SMI Network Management Private Enterprise Code” assigned to CAEN SpA.\n##Length: Encodes the length of the message (in bytes) including the header.\n\n##The header is followed by a list of AVPs the number of which depends on the command. Each AVP have the following format:\n## 1 2 3\n##0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1\n##+-------------------------------+------------------------------+\n##| RESERVED | Length |\n##+-------------------------------+------------------------------+\n##| Attribute Type | Attribute Value ……… |\n##+-------------------------------+------------------------------+\n##| ………[ until length is reached ]……… |\n##+--------------------------------------------------------------+\n##RESERVED: The first 16 bits are reserved for future extensions. All reserved bits must be set to 0 on outgoing messages and ignored on incoming messages.\n##Length: Encodes the length of the AVP packet including the length and the reserved fields.\n##Attribute type: A 2 byte code identifying the attribute type.\n##Attribute value: The actual attribute value according to the type. It follows immediately after the Attribute Type field and runs for the remaining bytes indicated in the Length (i.e. Length minus 6 bytes of header).\n\nclass AttributeValueType(object):\n\tdef __init__(self):\n\t\tself.STRING = 1\n\t\tself.ONEBYTE = 2\n\t\tself.TWOBYTE = 3\n\t\tself.FOURBYTE = 4\n\t\tself.TIMESTAMP = 5\t\t\t\t\n\nclass AttributeType(object):\n\t'''Super class for attribute types, contains attribute code, description and length of value, also dict of possible values with codes'''\n\tdef __init__(self, code, length, value = None ):\n\t\tself.Code = code\n\t\tself.Value = value\n\t\tself.Description = self.__class__.__name__\n\t\tself.Length = length\t\t\n\t\tself.ValueDescriptions = {}\t\t\n\t\t\n\tdef __str__(self):\t\t\n\t\t#TODO\n\t\tval = ''\n\t\tif type(self.Value) == type(''):\n\t\t\tval = '%s' % self.Value\n\t\telif self.Length in ( 2, 4 ):\t\t\t\n\t\t\tval = '0x%x' % self.Value\t\t\n\t\telif self.Length == 8:\n\t\t\tval = '0x%x' % self.Value\n##\t\telif self.Length > 8:\n##\t\t\tval = '%s' % self.Value\t\t\n\t\t\t\n\t\t\t\n\t\tif not len(self.ValueDescriptions):\n\t\t\treturn 'AVP: %s CODE: %d/0x%x VALUE: %s/%s (%s) LENGTH: %d' % (self.Description, self.Code, self.Code, self.Value, val, repr(val), self.Length)\n\t\telse:\n\t\t\treturn 'AVP: %s CODE: %d/0x%x DESCRIPTION: \"%s\" VALUE: %s/%s (%s) LENGTH: %d' % (self.Description, self.Code, self.Code, self.ValueDescriptions[self.Value], self.Value, val, repr(val) , self.Length)\n\n\tdef toBytes(self):\n\t\tpacker = '>HHH'\n\t\tAVP_Reserved = 0x0000\n\t\tAVP_Length = self.Length\n\t\tAVP_Type = self.Code\n\t\tAVP_Value = self.Value\n\t\tif type(AVP_Value) == type(''):\n\t\t\tAVP_Length = len( AVP_Value )\n\t\t\tpacker += '%ds' % len( AVP_Value )\n\t\telse:\n\t\t\tif self.Length == 2:\n\t\t\t\tpacker += 'H'\n\t\t\telif self.Length == 4:\n\t\t\t\tpacker += 'I'\n\t\t\telse:\n\t\t\t\traise CAENRFIDException('Value with length %d not implemented!' % self.Length )\n\t\t#we add 6 bytes of length for size of AVP\n\t\tAVP_Length = 6 + AVP_Length\n\t\tretBytes = pack( packer, AVP_Reserved, AVP_Length, AVP_Type, AVP_Value )\n\t\tlogger.debug( 'AVP toBytes: %s', repr(retBytes))\n\t\treturn retBytes\n\n\ndef CreateAttributeType( attributeType, attributeValue ):\n\t'''Helper method which creates right AttributeType from code'''\n\t\n\tif\t\tattributeType == 0x01:\n\t\treturn AttributeTypes.CommandName( attributeValue )\n\telif \tattributeType == 0x02:\n\t\treturn AttributeTypes.ResultCode( attributeValue )\n\telif \tattributeType == 0x0E:\n\t\treturn AttributeTypes.EventType( attributeValue )\n\telif \tattributeType == 0x0F:\n\t\treturn AttributeTypes.TagIDLen( attributeValue )\n\telif \tattributeType == 0x10:\n\t\treturn AttributeTypes.TimeStamp( attributeValue )\n\telif \tattributeType == 0x11:\n\t\treturn AttributeTypes.TagID( attributeValue )\n\telif \tattributeType == 0x12:\n\t\treturn AttributeTypes.TagType( attributeValue )\n\telif \tattributeType == 0x1E:\n\t\treturn AttributeTypes.ChannelName( attributeValue )\n\telif \tattributeType == 0x1F:\n\t\treturn AttributeTypes.ChannelAddress( attributeValue )\n\telif \tattributeType == 0x20:\n\t\treturn AttributeTypes.TriggerName( attributeValue )\n\telif \tattributeType == 0x21:\n\t\treturn AttributeTypes.TriggerType( attributeValue )\n\telif \tattributeType == 0x22:\n\t\treturn AttributeTypes.ReadPointName( attributeValue )\n\telif \tattributeType == 0x4D:\n\t\treturn AttributeTypes.TagValue( attributeValue )\n\telif \tattributeType == 0x4E:\n\t\treturn AttributeTypes.TagAddress( attributeValue )\n\telif \tattributeType == 0x50:\n\t\treturn AttributeTypes.Length( attributeValue )\n\telif \tattributeType == 0x51:\n\t\treturn AttributeTypes.BitRate( attributeValue )\n\telif \tattributeType == 0x52:\n\t\treturn AttributeTypes.PowerGet( attributeValue )\n\telif \tattributeType == 0x54:\n\t\treturn AttributeTypes.Protocol( attributeValue )\n\telif \tattributeType == 0x56:\n\t\treturn AttributeTypes.Boolean( attributeValue )\n\telif \tattributeType == 0x58:\n\t\treturn AttributeTypes.IPAddress( attributeValue )\n\telif \tattributeType == 0x59:\n\t\treturn AttributeTypes.IPNetMask( attributeValue )\n\telif \tattributeType == 0x5A:\n\t\treturn AttributeTypes.IPGateway( attributeValue )\n\telif \tattributeType == 0x5B:\n\t\treturn AttributeTypes.DESBEnable( attributeValue )\n\telif \tattributeType == 0x5C:\n\t\treturn AttributeTypes.FWRelease( attributeValue )\n\telif \tattributeType == 0x5D:\n\t\treturn AttributeTypes.DESBStatus( attributeValue )\n\telif \tattributeType == 0x5C:\n\t\treturn AttributeTypes.EPCPWD( attributeValue )\n\telif \tattributeType == 0x5F:\n\t\treturn AttributeTypes.RFOnOff( attributeValue )\n\telif \tattributeType == 0x60:\n\t\treturn AttributeTypes.BaudRate( attributeValue )\n\telif \tattributeType == 0x61:\n\t\treturn AttributeTypes.DataBits( attributeValue )\n\telif \tattributeType == 0x62:\n\t\treturn AttributeTypes.StopBits( attributeValue )\n\telif \tattributeType == 0x63:\n\t\treturn AttributeTypes.Parity( attributeValue )\n\telif \tattributeType == 0x64:\n\t\treturn AttributeTypes.FlowCtrl( attributeValue )\n\telif \tattributeType == 0x65:\n\t\treturn AttributeTypes.DateTime( attributeValue )\n\telif \tattributeType == 0x66:\n\t\treturn AttributeTypes.SelUnselOp( attributeValue )\n\telif \tattributeType == 0x67:\n\t\treturn AttributeTypes.Bitmask( attributeValue )\n\telif \tattributeType == 0x69:\n\t\treturn AttributeTypes.IORegister( attributeValue )\n\telif \tattributeType == 0x6A:\n\t\treturn AttributeTypes.ConfigParameter( attributeValue )\n\telif \tattributeType == 0x6B:\n\t\treturn AttributeTypes.ConfigValue( attributeValue )\n\telif \tattributeType == 0x6C:\n\t\treturn AttributeTypes.NoOfTriggers( attributeValue )\n\telif \tattributeType == 0x6D:\n\t\treturn AttributeTypes.NoOfChannels( attributeValue )\n\telif \tattributeType == 0x6E:\n\t\treturn AttributeTypes.EventMode( attributeValue )\n\telif \tattributeType == 0x6F:\n\t\treturn AttributeTypes.UpgradeType( attributeValue )\n\telif \tattributeType == 0x70:\n\t\treturn AttributeTypes.UpgradeArgument( attributeValue )\n\telif \tattributeType == 0x71:\n\t\treturn AttributeTypes.MemoryBank( attributeValue )\n\telif \tattributeType == 0x72:\n\t\treturn AttributeTypes.Payload( attributeValue )\n\telif \tattributeType == 0x73:\n\t\treturn AttributeTypes.G2Password( attributeValue )\n\telif \tattributeType == 0x74:\n\t\treturn AttributeTypes.G2NSI( attributeValue )\n\telif \tattributeType == 0x75:\n\t\treturn AttributeTypes.QParameter( attributeValue )\n\telif \tattributeType == 0x76:\n\t\treturn AttributeTypes.ReaderInfo( attributeValue )\n\telif \tattributeType == 0x77:\n\t\treturn AttributeTypes.RFRegulation( attributeValue )\n\telif \tattributeType == 0x78:\n\t\treturn AttributeTypes.RFChannel( attributeValue )\n\telif \tattributeType == 0x7A:\n\t\treturn AttributeTypes.RSSI( attributeValue )\n\telif \tattributeType == 0x7B:\n\t\treturn AttributeTypes.AVP_OPTION( attributeValue )\n\telif \tattributeType == 0x7C:\n\t\treturn AttributeTypes.AVP_XPC( attributeValue )\n\telif \tattributeType == 0x7D:\n\t\treturn AttributeTypes.AVP_PV( attributeValue )\n\telif \tattributeType == 0x96:\n\t\treturn AttributeTypes.PowerSet( attributeValue )\n\telif \tattributeType == 0xFB:\n\t\treturn AttributeTypes.SourceName( attributeValue )\n\telse:\n\t\traise CAENDRFIDException(\"Unknown attribute type 0x%x\" % attributeType)\n\nclass AttributeTypes:\n\t'''Container class for attribute types and helper methods'''\n\n\tclass CommandName( AttributeType ):\n\t\t'''CommandName: the command to be executed. All the commands are specified in the relevant table. Attribute value is 2 bytes long.'''\n\t\tdef __init__(self, value ):\t\n\t\t\tsuper(CommandName, self).__init__( 0x01, 2, value )\n\t\t\t\n\tclass ResultCode( AttributeType ):\n\t\t'''ResultCode: a code representing an indication on the result of the command. All the commands are specified in the relevant table. Attribute value is 2 bytes long.'''\n\n\t\tERR_SUCCESS \t\t= 0\n\t\tERR_UNKNOWN \t\t= 102\n\t\tERR_INVALIDCMD \t\t= 127\n\t\tERR_PWROUTRANGE \t= 183\n\t\tERR_INVALIDPAR \t\t= 200\n\t\tERR_TAGNOTPRESENT \t= 202\n\t\tERR_TAGWRITE \t\t= 203\n\t\tERR_TAGBADADDRESS \t= 205\n\t\tERR_INVALIDFUNCTION\t= 206\n\t\tERR_LOCKED \t\t\t= 209\n\t\tERR_FAILED \t\t\t= 210\n\t\t\t\t\n\t\tdef __init__(self, value):\n\t\t\tsuper( self.__class__, self).__init__( 0x02, 2, value )\n\t\t\t\n\t\t\tself.ValueDescriptions = {\n\t\t\t\t0 : 'ERR_SUCCESS', \\\n\t\t\t\t102: 'ERR_UNKNOWN', \\\n\t\t\t\t127: 'ERR_INVALIDCMD', \\\n\t\t\t\t183: 'ERR_PWROUTRANGE', \\\n\t\t\t\t200: 'ERR_INVALIDPAR', \\\n\t\t\t\t202: 'ERR_TAGNOTPRESENT', \\\n\t\t\t\t203: 'ERR_TAGWRITE', \\\n\t\t\t\t205: 'ERR_TAGBADADDRESS', \\\n\t\t\t\t206: 'ERR_INVALIDFUNCTION', \\\n\t\t\t\t209: 'ERR_LOCKED', \\\n\t\t\t\t210: 'ERR_FAILED'}\n\n\tclass EventType( AttributeType ):\n\t\t'''EventType: the type of the notified event. Attribute value is 4 bytes long.'''\n\t\tUnknown_Event=0x00\n\t\tTag_glimpsed= 0x01\n\t\tTag_New\t\t= 0x02\n\t\tTag_Observed= 0x03\n\t\tTag_Lost \t= 0x04\n\t\tTag_Purged \t= 0x05\n\t\t\n\t\tdef __init__(self, value):\n\t\t\tsuper( self.__class__, self).__init__( 0x0E, 4, value )\t\t\t\n\t\t\tself.ValueDescriptions = { \\\n\t\t\t\t0x00: 'Unknown Event', \\\n\t\t\t\t0x01: 'Tag glimpsed', \\\n\t\t\t\t0x02: 'Tag New', \\\n\t\t\t\t0x03: 'Tag Observed', \\\n\t\t\t\t0x04: 'Tag Lost', \\\n\t\t\t\t0x05: 'Tag Purged'}\n\n\tclass TagIDLen( AttributeType ):\n\t\t'''TagIDLen: the length of the tag ID. Attribute value is 2 bytes long.'''\n\t\tdef __init__(self, value):\n\t\t\tsuper( self.__class__, self).__init__( 0x0F, 2, value )\t\t\t\n\n\tclass TimeStamp( AttributeType ):\n\t\t'''TimeStamp: an indication of the time. Attribute is 8 bytes long and must be interpreted as follow:\n\t\t\t- the 4 least significant bytes are the seconds elapsed from the 1 January 1970.\n\t\t\t- the 4 most significant bytes are the micro-seconds.'''\n\t\tdef __init__(self, value):\n\t\t\tsuper( self.__class__, self).__init__( 0x10, 8, value )\t\t\t\n\n\tclass TagID( AttributeType ):\n\t\t'''TagID: the ID read from the tag. Attribute value has a maximum length of 64 bytes. For ISO18000 tags only the first 8 bytes are significant while for EPC tags all the 12 bytes are significant.'''\n\t\tdef __init__(self, value):\n\t\t\tsuper( self.__class__, self).__init__( 0x11, 2, value )\n\t\t\tself.Length = len(value)\n\t\t\t\t\t\t\n\tclass TagType( AttributeType ):\n\t\t'''TagType: the tag’s type. Attribute value is 2 bytes long'''\n\t\tISO18KB = 0x00\n\t\tEPCC1G1 = 0x01\n\t\tISO18KA = 0x02\n\t\tEPCC1G2 = 0x03\n\t\tEPC119 \t= 0x05\n\t\t\t\n\t\tdef __init__(self, value):\n\t\t\tsuper( self.__class__, self).__init__( 0x12, 2, value )\n\t\t\t\n\t\t\tself.ValueDescriptions = { \\\n\t\t\t\t0x00: 'ISO18KB', \\\n\t\t\t\t0x01: 'EPCC1G1', \\\n\t\t\t\t0x02: 'ISO18KA', \\\n\t\t\t\t0x03: 'EPCC1G2', \\\n\t\t\t\t0x05: 'EPC119' }\n\n\tclass ChannelName( AttributeType ):\n\t\t'''ChannelName: the name of the notification channel. Attribute value has a maximum length of 30 bytes.'''\n\t\tdef __init__(self, value):\t\t\t\n\t\t\tsuper( self.__class__, self).__init__( 0x1E, 30, value )\n\t\t\tself.Value = value[:30]\n\t\t\tself.Length = len( self.Value )\n\n\tclass ChannelAddress( AttributeType ):\n\t\t'''ChannelAddress: the address of the notification channel. Attribute value has a maximum length of 30 bytes.'''\n\t\tdef __init__(self, value):\n\t\t\tsuper( self.__class__, self).__init__( 0x1F, 30, value )\n\t\t\tself.Value = value[:30]\n\t\t\tself.Length = len( self.Value )\n\n\tclass TriggerName( AttributeType ):\n\t\t'''TriggerName: the name of the trigger. Attribute value has a maximum length of 30 bytes.'''\n\t\tdef __init__(self, value):\n\t\t\tsuper( self.__class__, self).__init__( 0x20, 30, value )\n\t\t\tself.Value = value[:30]\n\t\t\tself.Length = len( self.Value )\n\n\tclass TriggerType( AttributeType ):\n\t\t'''TriggerType: the type of the trigger. Attribute value has a maximum length of 30 bytes.'''\n\t\tdef __init__(self, value):\n\t\t\tsuper( self.__class__, self).__init__( 0x21, 30, value )\n\t\t\tself.Value = value[:30]\n\t\t\tself.Length = len( self.Value )\n\n\tclass ReadPointName( AttributeType ):\n\t\t'''ReadPointName: a string2 representing the name of the read point. Attribute value has a maximum length of 5 bytes and can assume the following values:\n\t\t\t“Ant0”, “Ant1”, “Ant2”, “Ant3”'''\n\t\tdef __init__(self, value):\n\t\t\tsuper( self.__class__, self).__init__( 0x22, 5, value )\n\t\t\tself.Value = value[:5]\n\t\t\tself.Length = len( self.Value )\n\n\tclass TagValue( AttributeType ):\n\t\t'''TagValue: data read from the tag memory (when applicable). Attribute value has a maximum length of 128 bytes.'''\n\t\tdef __init__(self, value):\n\t\t\tsuper( self.__class__, self).__init__( 0x4D, 128, value )\n\t\t\tself.Value = value[:128]\n\t\t\tself.Length = len(self.Value)\n\n\tclass TagAddress( AttributeType ):\n\t\t'''TagAddress: the memory location address of the tag where read or write data (when applicable). Attribute value is 2 bytes long.'''\n\t\tdef __init__(self, value):\n\t\t\tsuper( self.__class__, self).__init__( 0x4E, 2, value )\t\t\t\n\n\t#0x4F\tRESERVED.\n\t\t\t\n\tclass Length( AttributeType ):\n\t\t'''Length: a value representing the length of a parameter. Attribute value is 2 bytes long.'''\n\t\tdef __init__(self, value):\n\t\t\tsuper( self.__class__, self).__init__( 0x50, 2, value )\n\t\t\t\t\t\t\n\tclass BitRate( AttributeType ):\n\t\t'''BitRate: a value representing the RF BitRate. Attribute value is 2 bytes long'''\n\n\t\tTransmit__DSB_ASK_10kbit_Receive__FM0_10kbit = 0x00\n\t\tTransmit__DSB_ASK_10kbit_Receive__FM0_40kbit = 0x01\n\t\tTransmit__DSB_ASK_40kbit_Receive__FM0_40kbit = 0x02\n\t\tTransmit__DSB_ASK_40kbit_Receive__FM0_160kbit = 0x03\n\t\tTransmit__DSB_ASK_160kbit_Receive__FM0_400kbit = 0x04\n\t\tTransmit__DSB_ASK_40kbit_Receive__Miller_M_2_160kbit = 0x05\n\t\tTransmit__PR_ASK_40kbit_Receive__Miller_M_4_250kbit = 0x06\n\t\tTransmit__PR_ASK_40kbit_Receive__Miller_M_4_300kbit = 0x07\n\t\tTransmit__PR_ASK_40kbit_Receive__Miller_M_2_250kbit = 0x08\n\t\tTransmit__PR_ASK_40kbit_Receive__FM0_40kbit = 0x09\n\t\tTransmit__DSB_ASK_40kbit_Receive__Miller_M_4_256kbit = 0x0A\n\t\tTransmit__PR_ASK_40kbit_Receive__Miller_M_4_320kbit = 0x0B\n\t\tTransmit__PR_ASK_40kbit_Receive__FM0_640kbit = 0x0C\n\t\tTransmit__PR_ASK_80kbit_Receive__Miller_M_4_320kbit = 0x0D\n\t\tTransmit__PR_ASK_40kbit_Receive__Miller_M_4_256kbit = 0x0E\n\t\t\n\t\tdef __init__(self, value):\n\t\t\tsuper( self.__class__, self).__init__( 0x51, 2, value )\n\t\t\t\n\t\t\tself.ValueDescriptions = { \\\n\t\t\t\t0x00: 'Transmit : DSB ASK 10kbit, Receive : FM0 10kbit', \\\n\t\t\t\t0x01: 'Transmit : DSB ASK 10kbit, Receive : FM0 40kbit', \\\n\t\t\t\t0x02: 'Transmit : DSB ASK 40kbit, Receive : FM0 40kbit', \\\n\t\t\t\t0x03: 'Transmit : DSB ASK 40kbit, Receive : FM0 160kbit', \\\n\t\t\t\t0x04: 'Transmit : DSB ASK 160kbit, Receive : FM0 400kbit', \\\n\t\t\t\t0x05: 'Transmit : DSB ASK 40kbit, Receive : Miller M=2 160kbit', \\\n\t\t\t\t0x06: 'Transmit : PR ASK 40kbit, Receive : Miller M=4 250kbit', \\\n\t\t\t\t0x07: 'Transmit : PR ASK 40kbit, Receive : Miller M=4 300kbit', \\\n\t\t\t\t0x08: 'Transmit : PR ASK 40kbit, Receive : Miller M=2 250kbit', \\\n\t\t\t\t0x09: 'Transmit : PR ASK 40kbit, Receive : FM0 40kbit', \\\n\t\t\t\t0x0A: 'Transmit : DSB ASK 40kbit, Receive : Miller M=4 256kbit', \\\n\t\t\t\t0x0B: 'Transmit : PR ASK 40kbit, Receive : Miller M=4 320kbit', \\\n\t\t\t\t0x0C: 'Transmit : PR ASK 40kbit, Receive : FM0 640kbit', \\\n\t\t\t\t0x0D: 'Transmit : PR ASK 80kbit, Receive : Miller M=4 320kbit', \\\n\t\t\t\t0x0E: 'Transmit : PR ASK 40kbit, Receive : Miller M=4 256kbit'}\n\t\t\t\n\tclass PowerGet( AttributeType ):\n\t\t'''PowerGet: a value representing the RF power. Attribute value is 4 bytes long. (used for read the current setting)'''\n\t\tdef __init__(self, value):\n\t\t\tsuper( self.__class__, self).__init__( 0x52, 4, value )\n\t\t\t\t\t\t\n\t#0x53 RESERVED.\n\t\t\t\n\tclass Protocol( AttributeType ):\n\t\t'''Protocol: a value representing the air protocol. Attribute value is 4 bytes long'''\n\t\tISO18000_6B = 0x00\n\t\tEPCC1G1 \t= 0x01\n\t\tISO18000_6A = 0x02\n\t\tEPCC1G2 \t= 0x03\n\t\t\n\t\tdef __init__(self, value):\n\t\t\tsuper( self.__class__, self).__init__( 0x54, 4, value )\n\t\t\t\n\t\t\tself.ValueDescriptions = { \\\n\t\t\t\t0x00: 'ISO18000-6B', \\\n\t\t\t\t0x01: 'EPCC1G1', \\\n\t\t\t\t0x02: 'ISO18000-6A', \\\n\t\t\t\t0x03: 'EPCC1G2' }\n\t\t\t\n\tclass ReadPointStatus( AttributeType ):\n\t\t'''ReadPointStatus: a value representing the antenna’s status. Attribute value is 4 bytes long'''\n\t\tdef __init__(self, value):\n\t\t\tsuper( self.__class__, self).__init__( 0x56, 4, value )\n\t\t\t\n\t\t\tself.ValueDescriptions = {\n\t\t\t\t0x00: 'Good: antenna is well connected.', \\\n\t\t\t\t0x01: 'Poor: antenna has a low quality connection.', \\\n\t\t\t\t0x02: 'Bad: antenna is not connected or broken.' }\n\t\t\t\n\tclass Boolean( AttributeType ):\n\t\t'''Boolean: a value representing a boolean data. Attribute value is 2 bytes long'''\n\t\tFALSE = 0x00\n\t\tTRUE = 0x01\n\t\t\n\t\tdef __init__(self, value):\n\t\t\tsuper( self.__class__, self).__init__( 0x57, 2, value )\t\t\t\n\t\t\tself.ValueDescriptions = { 0x00: 'FALSE', 0x01: 'TRUE' } #Not 0x00=True actually\n\t\t\t\n\tclass IPAddress( AttributeType ):\n\t\t'''IPAddress: a string representing an IP address formatted with the standard IP dotted decimal format. Attribute value has a maximum length of 30 bytes.'''\n\t\tdef __init__(self, value):\n\t\t\tsuper( self.__class__, self).__init__( 0x58, 30, value )\t\t\t\n\t\t\t\n\tclass IPNetMask( AttributeType ):\n\t\t'''IPNetMask: a string4 representing an IP netmask formatted with the standard IP dotted decimal format. Attribute value has a maximum length of 30 bytes.'''\n\t\tdef __init__(self, value):\n\t\t\tsuper( self.__class__, self).__init__( 0x59, 30, value )\n\t\t\t\t\t\t\n\tclass IPGateway( AttributeType ):\n\t\t'''IPGateway: a string representing an IP address formatted with the standard IP dotted decimal format. Attribute value has a maximum length of 30 bytes.'''\n\t\tdef __init__(self, value):\n\t\t\tsuper( self.__class__, self).__init__( 0x5A, 30, value )\n\t\t\t\t\t\t\n\tclass DESBEnable( AttributeType ):\n\t\t'''DESBEnable: used to enable/disable the Data Exchange Status Bit handling for ISO18000-6b and EPC 1.19 anti-collision algorithm. Attribute value is 2 bytes'''\n\t\tDisable = 0x00\n\t\tEnable\t= 0x01\n\t\t\n\t\tdef __init__(self, value):\n\t\t\tsuper( self.__class__, self).__init__( 0x5B, 2, value )\n\t\t\t\n\t\t\tself.ValueDescriptions = {0x00: 'Disable the DESB handling.', 0x01: 'Enable the DESB handling.'} #not 0x00\n\n\tclass FWRelease( AttributeType ):\n\t\t'''FWRelease: a string representing the device’s firmware revision. Attribute value has a maximum length of 200 bytes.'''\n\t\tdef __init__(self, value):\n\t\t\tsuper( self.__class__, self).__init__( 0x5C, 200, value )\n\t\t\t\t\t\t\n\tclass DESBStatus( AttributeType ):\n\t\t'''DESBStatus: used to check the Data Exchange Status Bit handling for ISO18000-6b and EPC 1.19 anti-collision algorithm. Attribute value is 2 bytes long'''\n\t\tDisabled = 0x00\n\t\tEnabled\t= 0x01\n\t\t\n\t\tdef __init__(self):\n\t\t\tsuper( self.__class__, self).__init__( 0x5D, 2, value )\t\t\t\n\t\t\tself.ValueDescriptions = {0x00: 'DESB handling is not enabled.', 0x01: 'DESB handling is enabled.'} #not 0x00 \n\t\t\t\n\tclass EPCPWD( AttributeType ):\n\t\t'''EPCPWD: a value representing an EPC tag password. Attribute value is 2 bytes long.'''\n\t\tdef __init__(self, value):\n\t\t\tsuper( self.__class__, self).__init__( 0x5C, 2, value )\n\t\t\t\n\tclass RFOnOff( AttributeType ):\n\t\t'''RFOnOff: used to start the generation of a continuous wave for test purposes. Attribute value is 2 bytes long'''\n\t\tSTOP \t= 0x00\n\t\tSTART\t= 0x01\n\t\t\n\t\tdef __init__(self, value):\n\t\t\tsuper( self.__class__, self).__init__( 0x5F, 2, value )\t\t\t\n\t\t\tself.ValueDescriptions = {0x00: 'Stop the wave generation.', 0x01: 'Start the wave generation.' }\n\t\t\t\t\t\t \n\tclass BaudRate( AttributeType ):\n\t\t'''BaudRate: a value representing the baudrate setting of serial port. Attribute value is 4 bytes long.'''\n\t\tdef __init__(self, value):\t\t\t\n\t\t\tsuper( self.__class__, self).__init__( 0x60, 4, value )\n\t\t\t\n\t\t\t\n\tclass DataBits( AttributeType ):\n\t\t'''DataBits: a value representing the databits setting of serial port. Attribute value is 4 bytes long.'''\n\t\tdef __init__(self, value):\n\t\t\tsuper( self.__class__, self).__init__( 0x61, 4, value )\n\t\t\t\n\t\t\t\n\tclass StopBits( AttributeType ):\n\t\t'''StopBits: a value representing the stopbits setting of serial port. Attribute value is 4 bytes long.'''\n\t\tdef __init__(self, value):\n\t\t\tsuper( self.__class__, self).__init__( 0x62, 4, value )\n\t\t\t\n\t\t\t\n\tclass Parity( AttributeType ):\n\t\t'''Parity: a value representing the parity setting of serial port. Attribute value is 4 bytes long'''\n\t\tNo_parity\t= 0x00\n\t\tOdd_parity\t= 0x01\n\t\tEven_parity = 0x02\n\t\t\n\t\tdef __init__(self, value):\n\t\t\tsuper( self.__class__, self).__init__( 0x63, 4, value )\t\t\t\n\t\t\tself.ValueDescriptions = { \\\n\t\t\t\t0x00: 'No parity', \\\n\t\t\t\t0x01: 'Odd parity', \\\n\t\t\t\t0x02: 'Even parity' }\n\t\t\t\n\tclass FlowCtrl( AttributeType ):\n\t\t'''FlowCtrl: a value representing the flow control setting of serial port. Attribute value is 4 bytes long'''\n\t\tNo_flow_control\t\t\t= 0x00\n\t\tHardware_flow_control\t= 0x01\n\t\tSoftware_flow_control \t= 0x02 #(not yet implemented)\n\t\t\n\t\tdef __init__(self, value):\n\t\t\tsuper( self.__class__, self).__init__( 0x64, 4, value )\t\t\t\n\t\t\tself.ValueDescriptions = { \\\n\t\t\t\t0x00: 'No flow control', \\\n\t\t\t\t0x01: 'Hardware flow control', \\\n\t\t\t\t0x02: 'Software flow control (not yet implemented)' }\n\t\t\t\t\n\tclass DateTime( AttributeType ):\n\t\t'''DateTime: a value representing a date and time. Attribute value has a maximum length of 30 bytes. The data format is: YYYY–MM–DD HH:MM:SS'''\n\t\tdef __init__(self, value):\n\t\t\tsuper( self.__class__, self).__init__( 0x65, 30, value )\n\t\t\tself.Value = value[:30]\n\t\t\tself.Length = len(self.Value)\n\n\tclass SelUnselOp( AttributeType ):\n\t\t'''SelUnselOp: a value representing the tag selection operation defined by the ISO18000-6B protocol. Attribute value is 2 bytes long'''\n\t\tselect_equal\t\t= 0x00\n\t\tselect_not_equal\t= 0x01\n\t\tselect_greater_than\t= 0x02\n\t\tselect_lower_than\t= 0x03\n\t\tunselect_equal\t\t= 0x04\n\t\tunselect_not_equal\t= 0x05\n\t\tunselect_greater_than=0x06\n\t\tunselect_lower_than\t= 0x07\n\t\t\n\t\tdef __init__(self, value):\n\t\t\tsuper( self.__class__, self).__init__( 0x66, 2, value )\t\t\t\n\t\t\tself.ValueDescriptions = {\n\t\t\t\t0x00: 'select equal', \\\n\t\t\t\t0x01: 'select not equal', \\\n\t\t\t\t0x02: 'select greater than', \\\n\t\t\t\t0x03: 'select lower than', \\\n\t\t\t\t0x04: 'unselect equal', \\\n\t\t\t\t0x05: 'unselect not equal', \\\n\t\t\t\t0x06: 'unselect greater than', \\\n\t\t\t\t0x07: 'unselect lower than' }\n\n\tclass Bitmask( AttributeType ):\n\t\t'''Bitmask: a value representing the flag parameter used in the newRawReadID command. Attribute value is 2 bytes long (only 8 least significant bits are used).'''\n\t\tdef __init__(self, value):\n\t\t\tsuper( self.__class__, self).__init__( 0x67, 2, value )\n\t\t\t\n\n\t#0x68 RESERVED.\n\t\t\t\n\tclass IORegister( AttributeType ):\n\t\t'''IORegister: a value representing the status of the I/O lines of the reader. Where input lines are separated from output ones, input lines are mapped on the less significant bits while outputs are mapped on the most significant. Attribute value is 4 bytes long (effective used bits depend on the reader model).'''\n\t\tdef __init__(self, value):\n\t\t\tsuper( self.__class__, self).__init__( 0x69, 4, value )\n\t\t\t\n\n\tclass ConfigParameter( AttributeType ):\n\t\t'''ConfigParameter: a value representing a configuration parameter. Attribute value is 4 bytes long'''\n\t\tReadCycle_configuration\t\t\t= 0x00\n\t\tObserved_Threshold_configuation\t= 0x01\n\t\tLost_Threshold_configuration\t= 0x02\n\t\tStarting_Q_value \t\t\t\t= 0x03 #(Valid values: 0 - 15). EPC C1GEN2 Protocol only.\n\t\tSession\t\t\t\t\t\t\t= 0x04 #(Valid values: 0 - 3). EPC C1GEN2 protocol only.\n\t\tTarget \t\t\t\t\t\t\t= 0x05 #(Valid values: 0 - 1). EPC C1GEN2 protocol only.\n\t\tSelected \t\t\t\t\t\t= 0x06 #(Valid values: 0, 1, 2, 3). EPC C1GEN2 protocol only.\n\t\tData_Exchange_Status_B \t\t\t= 0x07 #(Valid values: 0 - 1). ISO 18000-6B protocol only.\n\t\tAntenna_dwell_time\t\t\t \t= 0x08 #during_inventory (msec). A528 only.\n\t\tInventory_type \t\t\t\t\t= 0x09 #(Valid values: 0 - 3). A528 only.' }\n\t\t\n\t\tdef __init__(self, value):\n\t\t\tsuper( self.__class__, self).__init__( 0x6A, 4, value )\t\t\t\n\t\t\tself.ValueDescriptions = {\n\t\t\t\t0x00: 'ReadCycle configuration', \\\n\t\t\t\t0x01: 'Observed Threshold configuation', \\\n\t\t\t\t0x02: 'Lost Threshold configuration', \\\n\t\t\t\t0x03: 'Starting Q value (Valid values: 0 - 15). EPC C1GEN2 Protocol only.', \\\n\t\t\t\t0x04: 'Session (Valid values: 0 - 3). EPC C1GEN2 protocol only.', \\\n\t\t\t\t0x05: 'Target (Valid values: 0 - 1). EPC C1GEN2 protocol only.', \\\n\t\t\t\t0x06: 'Selected (Valid values: 0, 1, 2, 3). EPC C1GEN2 protocol only.', \\\n\t\t\t\t0x07: 'Data Exchange Status B (Valid values: 0 - 1). ISO 18000-6B protocol only.', \\\n\t\t\t\t0x08: 'Antenna dwell time during inventory (msec). A528 only.', \\\n\t\t\t\t0x09: 'Inventory type (Valid values: 0 - 3). A528 only.' }\n\n\tclass ConfigValue( AttributeType ):\n\t\t'''ConfigValue: a value for the configuration parameter. Attribute value is 4 bytes long.'''\n\t\tdef __init__(self, value):\n\t\t\tsuper( self.__class__, self).__init__( 0x6B, 4, value )\n\t\t\t\n\n\tclass NoOfTriggers( AttributeType ):\n\t\t'''NoOfTriggers: a value representing the number of triggers. Attribute value is 2 bytes long.'''\n\t\tdef __init__(self, value):\n\t\t\tsuper( self.__class__, self).__init__( 0x6C, 2, value )\n\t\t\t\n\n\tclass NoOfChannels( AttributeType ):\n\t\t'''NoOfChannels: a value representing the number of channels. Attribute value is 2 bytes long.'''\n\t\tdef __init__(self, value):\n\t\t\tsuper( self.__class__, self).__init__( 0x6D, 2, value )\n\t\t\t\n\n\tclass EventMode( AttributeType ):\n\t\t'''EventMode: a value representing the event handling mode. Attribute value is 2 bytes long'''\n\t\tReadCycle_mode\t= 0x00\n\t\tTime_Mode\t\t= 0x01\n\t\tNo_Event_Mode\t= 0x02\n\t\t\n\t\tdef __init__(self, value):\n\t\t\tsuper( self.__class__, self).__init__( 0x6E, 2, value )\t\t\n\t\t\tself.ValueDescriptions = {\n\t\t\t\t0x00: 'ReadCycle mode', \\\n\t\t\t\t0x01: 'Time Mode', \\\n\t\t\t\t0x02: 'No Event Mode' }\n\t\t\t\n\tclass UpgradeType( AttributeType ):\n\t\t'''UpgradeType: a value representing the type of upgrade to perform. Attribute value is 2 bytes long'''\n\t\tTFTP_firmware_upgrade = 0x01\n\t\t\n\t\tdef __init__(self, value ):\t\t\t\n\t\t\tsuper( self.__class__, self).__init__( 0x6F, 2, value )\n\t\t\tself.ValueDescriptions = {0x01: 'TFTP firmware upgrade.'}\n\n\tclass UpgradeArgument( AttributeType ):\n\t\t'''UpgradeArgument: a value representing the argument for the requested upgrade. Attribute value has a maximum length of 255 bytes.\tFor TFTP upgrade (code 0x01) the string has the form: ‘ : ’.'''\n\t\tdef __init__(self, value):\n\t\t\tsuper( self.__class__, self).__init__( 0x70, 255, value )\n\t\t\t\n\tclass MemoryBank( AttributeType ):\n\t\t'''MemoryBank: a value representing the memory bank of a EPC Class 1 Generation 2 tag. Attribute value is 2 bytes long'''\n\t\tReserved_Memory_Bank\t= 0x00\n\t\tEPC_Memory_Bank\t\t\t= 0x01\n\t\tTID_Memory_Bank\t\t\t= 0x02\n\t\tUser_Memory_Bank\t\t= 0x03\n\t\t\n\t\tdef __init__(self, value):\n\t\t\tsuper( self.__class__, self).__init__( 0x71, 2, value )\t\t\t\n\t\t\tself.ValueDescriptions = { \\\n\t\t\t\t0x00: 'Reserved Memory Bank', \\\n\t\t\t\t0x01: 'EPC Memory Bank', \\\n\t\t\t\t0x02: 'TID Memory Bank', \\\n\t\t\t\t0x03: 'User Memory Bank' }\n\n\tclass Payload( AttributeType ):\n\t\t'''Payload: a value representing the payload parameter for the EPC Class 1 Gen 2 lock command (see the EPC Gen2 specification for details). Attribute value is 4 bytes long.'''\n\t\tdef __init__(self, value):\n\t\t\tsuper( self.__class__, self).__init__( 0x72, 4, value )\n\t\t\t\n\n\tclass G2Password( AttributeType ):\n\t\t'''G2Password: a value representing the Acess / Kill password parameter for the EPC Class 1 Gen 2 commands (see the EPC Gen2 specification for details). Attribute value is 4 bytes long.'''\n\t\tdef __init__(self, value):\n\t\t\tsuper( self.__class__, self).__init__( 0x73, 4, value )\n\t\t\t\n\n\tclass G2NSI( AttributeType ):\n\t\t'''G2NSI: a value representing the numbering system identifier for the EPC Class 1 Gen 2 tags’ id (see the EPC Gen2 specification for details). Attribute value is 2 bytes long.'''\n\t\tdef __init__(self, value):\n\t\t\tsuper( self.__class__, self).__init__( 0x74, 2, value )\n\t\t\t\n\n\tclass QParameter( AttributeType ):\n\t\t'''QParameter: a value representing the initial value for the Q parameter involved in the EPC Class 1 Gen 2 anticollision algorithm (see the EPC Gen2 specification for details). Attribute value is 2 bytes long.'''\n\t\tdef __init__(self, value):\n\t\t\tsuper( self.__class__, self).__init__( 0x75, 2, value )\n\t\t\t\n\n\tclass ReaderInfo( AttributeType ):\n\t\t'''ReaderInfo: a string indicating the model and the serial number of the reader.'''\n\t\tdef __init__(self, value):\n\t\t\tsuper( self.__class__, self).__init__( 0x76, 255, value ) #unspecified length in documentation\t\t\t\n\t\t\tself.Length = len(self.Value)\n\n\tclass RFRegulation( AttributeType ):\n\t\t'''RFRegulation: a value representing the RF regulation to use. Attribute value is 2 bytes long'''\n\t\tETSI_EN_302_208\t= 0x00\n\t\tETSI_EN_300_220\t= 0x01\n\t\tFCC\t\t\t\t= 0x02\n\t\tMalaysia\t\t= 0x03\n\t\tJapan\t\t\t= 0x04\n\t\tKorea\t\t\t= 0x05\n\t\tAustralia\t\t= 0x06\n\t\tChina\t\t\t= 0x07\n\t\tTaiwan\t\t\t= 0x08\n\t\tSingapore\t\t= 0x09\n\t\tBrazil\t\t\t= 0x0A\n\t\tJapan_STD_T106\t= 0x0B\n\t\tJapan_STD_T107\t= 0x0C\n\t\t\t\t\t\t\n\t\tdef __init__(self, value):\n\t\t\tsuper( self.__class__, self).__init__( 0x77, 2, value )\t\t\t\n\t\t\tself.ValueDescriptions = { \\\n\t\t\t\t0x00: 'ETSI EN 302 208', \\\n\t\t\t\t0x01: 'ETSI EN 300 220', \\\n\t\t\t\t0x02: 'FCC', \\\n\t\t\t\t0x03: 'Malaysia', \\\n\t\t\t\t0x04: 'Japan', \\\n\t\t\t\t0x05: 'Korea', \\\n\t\t\t\t0x06: 'Australia', \\\n\t\t\t\t0x07: 'China', \\\n\t\t\t\t0x08: 'Taiwan', \\\n\t\t\t\t0x09: 'Singapore', \\\n\t\t\t\t0x0A: 'Brazil', \\\n\t\t\t\t0x0B: 'Japan_STD_T106', \\\n\t\t\t\t0x0C: 'Japan_STD_T107' }\n\n\tclass RFChannel( AttributeType ):\n\t\t'''RFChannel: a value representing the RF channel to use. Attribute value is 2 bytes long and can assume values in the range 0 … 9. Channels are referred to the ETSI EN 302 208 regulation'''\n\t\tdef __init__(self, value):\n\t\t\tsuper( self.__class__, self).__init__( 0x78, 2, value )\n\t\t\t\n\n\tclass RSSI( AttributeType ):\n\t\t'''RSSI: a value representing the backscattered RF field strenght. Attribute value is 2 bytes long.'''\n\t\tdef __init__(self, value):\n\t\t\tsuper( self.__class__, self).__init__( 0x7A, 2, value )\n\t\t\t\n\n\tclass AVP_OPTION( AttributeType ):\n\t\t'''AVP_OPTION'''\n\t\tdef __init__(self, value):\n\t\t\tsuper( self.__class__, self).__init__( 0x7B, 2, value ) #unspecified length in docs\n\t\t\t\n\n\tclass AVP_XPC( AttributeType ):\n\t\t'''AVP_XPC a value representing the XPC word. Attribute value is 4 bytes long.'''\n\t\tdef __init__(self, value):\n\t\t\tsuper( self.__class__, self).__init__( 0x7C, 4, value )\n\t\t\t\n\n\tclass AVP_PC( AttributeType ):\n\t\t'''AVP_PC a value representing the PC word. Attribute value is 4 bytes long.'''\n\t\tdef __init__(self, value):\n\t\t\tsuper( self.__class__, self).__init__( 0x7D, 4, value )\n\t\t\t\n\n\tclass PowerSet( AttributeType ):\n\t\t'''PowerSet: a value (mW) representing the RF power emitted during the communication with tags. Attribute value is 4 bytes long (used to set a new current value).'''\n\t\tdef __init__(self, value ):\n\t\t\tsuper( self.__class__, self).__init__( 0x96, 4, value )\n\t\t\t\n\n\tclass SourceName( AttributeType ):\n\t\t'''SourceName: a string representing the name of the data source. Attribute value has a maximum length of 30 bytes and can assume the following values: “Source_0”, “Source_1”, “Source_2”, “Source_3”'''\n\t\tdef __init__(self, value):\n\t\t\tsuper( self.__class__, self).__init__( 0xFB, 30, value )\n\t\t\tself.Value = value[:30]\n\t\t\tself.Length = len(self.Value)\n\n\n\n\n","sub_path":"Endicate/rfid/CaenAttributeTypes.py","file_name":"CaenAttributeTypes.py","file_ext":"py","file_size_in_byte":32579,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"181918140","text":"# -*- coding: utf-8 -*-\nimport time\nimport json\nimport logging\nimport requests\nimport hashlib\nfrom odoo import api, fields, models\nfrom odoo.exceptions import UserError\n\n_logger = logging.getLogger(__name__)\n\n\nclass BankCardInfo(models.TransientModel):\n _description = '查询银行卡信息'\n _name = 'union.pay.search.bank.card.info'\n\n @api.model\n def search_bank_card_info(self, card_no):\n \"\"\"查询银行卡信息\n :param card_no :银行卡号\n \"\"\"\n card_no = card_no.replace(' ', '')\n logging.info('>>>需要查询的银行卡号为:{}'.format(card_no))\n token = self.env['union.pay.system.conf'].search([('key', '=', 'token')]).value\n api_signature = self.env['ir.config_parameter'].sudo().get_param('union_pay.api_signature')\n cardinfo_url = self.env['union.pay.system.conf'].search([('key', '=', 'cardinfo_url')]).value\n data = {'cardNo': card_no}\n time_str = int(round(time.time() * 1000))\n sha256_str = \"{}{}{}\".format(api_signature, json.dumps(data), time_str)\n # SHA-256算法加密\n sha256 = hashlib.sha256()\n sha256.update(sha256_str.encode('utf-8'))\n # url参数\n cardinfo_url = \"{}?token={}&sign={}&ts={}\".format(cardinfo_url, token, sha256.hexdigest(), time_str)\n headers = {'Content-Type': 'application/json'}\n result = requests.post(url=cardinfo_url, headers=headers, data=json.dumps(data), timeout=15)\n logging.info(result.text)\n # 解析结果\n try:\n result = json.loads(result.text)\n if result.get('respCd') != '0000':\n raise UserError(\"银联返回信息:{}\".format(result.get('respMsg')))\n return result.get('data')\n except KeyError as e:\n raise UserError(u\"KeyError异常错误:{}\".format(e.message))\n except requests.exceptions.Timeout:\n raise UserError(u'请求超时!')\n except TypeError as e:\n raise UserError(u\"TypeError系统错误!返回信息:{}\".format(e.message))\n\n\nclass GetUnionPayToken(models.TransientModel):\n _description = '获取银联token值'\n _name = 'union.pay.get.token'\n\n @api.model\n def get_union_pay_token(self):\n \"\"\"获取银联token值的方法函数\n 获取token值需要用户用户唯一凭证(appid)和用户唯一凭证密钥(AppSecret)\n \"\"\"\n api_appid = self.env['ir.config_parameter'].sudo().get_param('union_pay.api_appid')\n api_appsecret = self.env['ir.config_parameter'].sudo().get_param('union_pay.api_appsecret')\n if not api_appid and not api_appsecret:\n logging.info(\"银联设置项中的用户唯一凭证和用户唯一凭证密钥不能为空!\")\n return False\n token_url = self.env['union.pay.system.conf'].search([('key', '=', 'token_url')]).value\n if not token_url:\n logging.info('获取Token值URL记录不存在')\n return False\n data = {'app_id': api_appid, 'app_secret': api_appsecret}\n # 发送数据\n result = requests.get(url=token_url, params=data, timeout=10)\n result = json.loads(result.text)\n logging.info(result)\n if result.get('respCd') == '0000':\n token = self.env['union.pay.system.conf'].search([('key', '=', 'token')])\n if token:\n token.write({\n 'value': result.get('token')\n })\n else:\n logging.info(\"获取银联Token失败!请检查网络是否通畅或检查日志输出\")\n","sub_path":"union_pay/models/bank_card_info.py","file_name":"bank_card_info.py","file_ext":"py","file_size_in_byte":3589,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"147572692","text":"#!/usr/bin/env python3\nimport setuptools\nimport os\n\ntry: # for pip >= 10\n from pip._internal.download import PipSession\n from pip._internal.req import parse_requirements\nexcept ImportError: # for pip <= 9.0.3\n from pip.download import PipSession\n from pip.req import parse_requirements\n\n \nwith open(\"README.md\", \"r\") as fh:\n long_description = fh.read()\n\nsetuptools.setup(\n name=\"mans_to_es\",\n version=\"1.4\",\n author=\"LDO-CERT\",\n author_email=\"gcert@leonardocompany.com\",\n description=\"Send .mans to ElasticSearch\",\n long_description=long_description,\n long_description_content_type=\"text/markdown\",\n license='Apache License, Version 2.0',\n url=\"https://github.com/LDO-CERT/mans_to_es\",\n packages=setuptools.find_packages(),\n classifiers=[\n \"Programming Language :: Python :: 3\",\n \"Operating System :: OS Independent\",\n ],\n entry_points={'console_scripts': ['mans_to_es=mans_to_es.mans_to_es:main']},\n install_requires=[str(req.req) for req in parse_requirements(\n 'requirements.txt', session=PipSession(),\n )],\n)","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1099,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"491665095","text":"#!/usr/bin/env python3\n# \n# preview control\n\nimport math\nimport numpy as np\nimport control\nimport control.matlab\nimport csv\n\nclass preview_control():\n def __init__(self, dt, period, z, Q = 1.0e+8, H = 1.0):\n self.dt = dt\n self.period = period\n G = 9.8\n A = np.matrix([\n [0.0, 1.0, 0.0],\n [0.0, 0.0, 1.0],\n [0.0, 0.0, 0.0]])\n B = np.matrix([[0.0], [0.0], [1.0]])\n C = np.matrix([[1.0, 0.0, -z/G]])\n D = 0\n sys = control.matlab.ss(A, B, C, D)\n sys_d = control.c2d(sys, dt)\n self.A_d, self.B_d, self.C_d, D_d = control.matlab.ssdata(sys_d)\n E_d = np.matrix([[dt], [1.0], [0.0]])\n Zero = np.matrix([[0.0], [0.0], [0.0]])\n Phai = np.block([[1.0, -self.C_d * self.A_d], [Zero, self.A_d]])\n G = np.block([[-self.C_d*self.B_d], [self.B_d]])\n GR = np.block([[1.0], [Zero]])\n Gd = np.block([[-self.C_d*E_d], [E_d]])\n Qm = np.zeros((4,4))\n Qm[0][0] = Q\n P = control.dare(Phai, G, Qm, H)[0]\n self.F = -np.linalg.inv(H+G.transpose()*P*G)*G.transpose()*P*Phai\n xi = (np.eye(4)-G*np.linalg.inv(H+G.transpose()*P*G)*G.transpose()*P)*Phai;\n self.f = []\n self.xp, self.yp = np.matrix([[0.0],[0.0],[0.0]]), np.matrix([[0.0],[0.0],[0.0]])\n self.ux, self.uy = 0.0, 0.0\n for i in range(0,round(period/dt)):\n self.f += [-np.linalg.inv(H+G.transpose()*P*G)*G.transpose()*np.linalg.matrix_power(xi.transpose(),i-1)*P*GR]\n\n def set_param(self, t, current_x, current_y, foot_plan, pre_reset = False):\n x, y = current_x.copy(), current_y.copy()\n if pre_reset == True:\n self.xp, self.yp = x.copy(), y.copy()\n self.ux, self.uy = 0.0, 0.0\n COG_X = []\n for i in range(round((foot_plan[1][0] - t)/self.dt)):\n px, py = self.C_d * x, self.C_d * y\n ex, ey = foot_plan[0][1] - px, foot_plan[0][2] - py\n X, Y = np.block([[ex], [x - self.xp]]), np.block([[ey], [y - self.yp]])\n self.xp, self.yp = x.copy(), y.copy()\n dux, duy = self.F * X, self.F * Y\n index = 1\n for j in range(1,round(self.period/self.dt)-1):\n if round((i+j)+t/self.dt) >= round(foot_plan[index][0]/self.dt):\n dux += self.f[j] * (foot_plan[index][1]-foot_plan[index-1][1])\n duy += self.f[j] * (foot_plan[index][2]-foot_plan[index-1][2])\n index += 1\n self.ux, self.uy = self.ux + dux, self.uy + duy\n x, y = self.A_d * x + self.B_d * self.ux, self.A_d * y + self.B_d * self.uy\n COG_X += [np.block([x[0][0], y[0][0], px[0][0], py[0][0]])]\n return COG_X, x, y\n\nif __name__ == '__main__':\n pc = preview_control(0.01, 1.0, 0.27)\n foot_step = [[0, 0, 0], [0.34, 0, 0.06+0.00], [0.68, 0.05, -0.06+0.02], [1.02, 0.10, 0.06+0.04], [1.36, 0.15, -0.06+0.06], [1.7, 0.20, 0.06+0.08], [2.04, 0.25, 0.0+0.10], [2.72, 0.25, 0.0+0.10], [100, 0.25, 0.0+0.10]]\n x, y = np.matrix([[0.0],[0.0],[0.0]]), np.matrix([[0.0],[0.0],[0.0]])\n with open('result.csv', mode='w') as f:\n f.write('')\n t = 0\n while True:\n if len(foot_step) <= 2:\n break\n cog, x, y = pc.set_param(t, x, y, foot_step)\n with open('result.csv', mode='a') as f:\n writer = csv.writer(f)\n for i in cog:\n writer.writerow(i.tolist()[0])\n f.write('\\n')\n del foot_step[0]\n t = foot_step[0][0]\n# print(pc.set_param([0,0], [0,0], [0,0], foot_step))\n","sub_path":"GankenKun/preview_control.py","file_name":"preview_control.py","file_ext":"py","file_size_in_byte":3272,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"392881886","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Jul 14 03:18:32 2020\n\n@author: SID\n\"\"\"\n\n\"\"\"\ncode for plotting charts for calculations done in calculations.py\n\"\"\"\nimport matplotlib.pyplot as plt\nfrom calculations import *\nimport seaborn as sns\n\n\n\n#plotting returns of stocks\ncol = get_m_returns(df).columns\n\ndef plot_m_returns(df):\n #l = len(m_returns.columns)\n plt.figure(figsize = (45,20))\n m_returns = get_m_returns(df)\n \n for i in range(len(m_returns.columns)):\n plt.subplot(14,2,i+1)\n plt.plot(m_returns[col[i]])\n plt.title(col[i])\n plt.tight_layout()\n plt.show()\n\n \n#plotting protfolio returns\ndef plot_pf_returns(df):\n plt.figure(figsize=(5,2))\n plt.plot(get_pf_returns(df))\n plt.title(\"RETURNS OF PORTFOLIO OVER TIME\")\n plt.show()\n\n \n \n \n#plotting drawdown of the portfolio\ndef plot_drawdown(df):\n plt.figure()\n plt.plot(get_wealth_index(df))\n plt.plot(get_peaks(df))\n plt.xlabel(\"Maximum drawdown: \" + str(get_drawdown(df)))\n plt.title(\"PORTFOLIO DRAWDOWN\")\n plt.show()\n\n\n\n#plotting drawdown of the index\ndef plot_ind_drawdown(df):\n plt.figure()\n plt.plot(get_ind_wealth_index(df))\n plt.plot(get_ind_peaks(df))\n\n\n\n \n\n#plotting returns of portfolio vs indices\ndef plot_benchmark(df,df1):\n #l = len(m_returns.columns)\n plt.figure(figsize = (20,len(df1.columns)*4))\n pf_returns = get_pf_returns(df)\n index_returns = get_a_returns(df1)\n\n for i in range(len(df1.columns)):\n plt.subplot(len(df1.columns),1,i+1)\n plt.plot(pf_returns.values, linewidth=3, label = \"portfolio\")\n plt.plot(index_returns.iloc[:,i].values, linestyle='dashed', label = \"index\")\n plt.title(index_returns.columns[i])\n\n \n #plt.tight_layout()\n plt.legend()\n plt.show()\n\n\n\n\n\n \n#print(df1.columns.shape())\n\n#plotting correlation matrix of all stocks in portfolio\ndef plot_corr_matrix(df):\n m_returns = get_m_returns(df)\n corr = m_returns.corr()\n plt.figure(figsize = (20,15))\n matrix = sns.heatmap(corr, annot = True)\n plt.show()\n #return matrix\n\n#plot portfolio value over time\ndef plot_pf_value(df,amt = 5000000):\n x= []\n y = []\n for i in range(2010,2021):\n x.append(round(((get_pf_value(df,i)+1)*amt),2))\n y.append(i)\n \n #show pf value\n table_value = pd.DataFrame()\n table_value[\"YEAR\"] = np.array(y)\n table_value[\"AMOUNT\"] = np.array(x)\n print(table_value)\n \n #plot pf value\n fig,ax = plt.subplots()\n ax.plot(y,x)\n plt.title(\"Portfolio wealth over the years\")\n plt.ylabel(\"Amount in crores\")\n\n plt.show()\n\n\n\n \n\n#pf_returns = get_pf_returns(df)\n#print(pf_returns.index.year)\n\n","sub_path":"plotcode.py","file_name":"plotcode.py","file_ext":"py","file_size_in_byte":2772,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"646473540","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sat Jul 11 15:31:00 2020\r\n\r\n@author: priyadarshan\r\n\"\"\"\r\nimport numpy as np\r\nimport copy\r\nimport subprocess\r\nimport random\r\nfrom pyeasyga import pyeasyga\r\n\r\n\r\n\r\n\r\n#This is the binary GA code for the rail electrification paper\r\n\r\n#Input files:\r\n#Network file original - Used in section 1\r\nnetwork_file_path = \"network_file.txt\"\r\n#Electrification costs - Used in section 2\r\nelec_costs = \"Electrification_costs.csv\"\r\n#Electrification TSTT and capacity data - Used in section 3\r\nelec_data = \"Electrification_data.csv\"\r\n#Final generation population is written here - Used in section 5\r\nresults_file=\"results.txt\"\r\n\r\n\r\n#Constants defined here\r\nrandom.seed(1)\r\nTotal_electrification_budget = 10000000\r\n#Note that electrification costs are in 1000s for our dataset, so we divide the total budget accordingly.\r\n#100 billion corresponds to 100 million written above\r\n\r\n\r\n##################Section 1############################\r\n#This block reads in the network file for editing in every GA iteration and saves it as list net\r\n#NOTE: Network should not have separate information for AB and BA links. We create that later.\r\nwith open(network_file_path) as f:\r\n net = f.readlines()\r\nf.close()\r\n#This calculates the number of lines in the network file.\r\n#It is assumed that there are 4 lines of metadata, one line end of metadata, 2 lines of space and a line of headings\r\nnum_lines_datafile = len(net)\r\nnum_links = num_lines_datafile-8\r\n\r\n\r\n\r\n\r\n\r\n\r\n##################Section 2############################\r\n#This block reads in the link electrification costs\r\nwith open(elec_costs) as f:\r\n electrification_costs_raw = f.readlines()\r\nf.close()\r\n\r\ncost_array = np.zeros(num_links)\r\nfor i in range(num_links):\r\n cost_array[i] = float(electrification_costs_raw[i])\r\n\r\n#Initialize the y vector, or set of links to be electrified.\r\n#1 means electrified, 0 means not electrified\r\nbinary_array = np.zeros(num_links)\r\n\r\n#These following lines are debugging lines which electrify three links\r\n# binary_array[1]=1\r\n# binary_array[3]=1\r\n# binary_array[4]=1\r\n\r\n#This block defines the function for calculating electrification costs\r\n#Note that both arguments must be numpy arrays\r\ndef calculate_electrification_costs(cost_array, binary_upgrade_array):\r\n return np.dot(cost_array,binary_upgrade_array)\r\n\r\n\r\n\r\n\r\n\r\n##################Section 3############################\r\n#This section defines a function to calculate the new network file from electrified binary array\r\n#This section also saves it as net_new.txt in the AlgB sub-folder\r\n\r\n#Function definition starts here\r\n\r\ndef write_electrified_network(binary_array):\r\n \r\n #Read the electrification data which is JA, JB, length, DGC_AB, DGC_BA, EGC_AB, EGC_BA, AB capacity, BA capacity, DFFTT_AB, DFFTT_BA, EFFTT_AB, EFFTT_BA\r\n with open(elec_data) as f:\r\n electrification_data_raw = f.readlines()\r\n f.close()\r\n \r\n electrification_data = np.zeros((num_links,13))\r\n \r\n for i in range(num_links):\r\n electrification_data[i] = [x.strip() for x in electrification_data_raw[i].split(',')]\r\n \r\n #Change metadata\r\n #The metadata header is created here and stored in a variable named new_header_temp\r\n new_num_links= int(2*(num_links + np.sum(binary_array)))\r\n \r\n line_4 = \" \"+str(new_num_links)+\"\\n\"\r\n \r\n new_header_temp = net[0]+net[1]+net[2]+line_4+net[4]+net[5]+net[6]+net[7]\r\n \r\n #Change network information\r\n \r\n ##this has the original network information\r\n net_temp_array = []\r\n \r\n for i in range(len(net)):\r\n if i<8:\r\n continue\r\n else:\r\n net_temp_array.append(net[i].split())\r\n \r\n ##Add the BA links with appropriate capacity\r\n net_temp_array_BA = copy.deepcopy(net_temp_array)\r\n for i in range(len(net_temp_array_BA)):\r\n net_temp_array_BA[i][0] = net_temp_array[i][1]\r\n net_temp_array_BA[i][1] = net_temp_array[i][0]\r\n net_temp_array_BA[i][2] = electrification_data[i][8]\r\n net_temp_array_BA[i][4] = electrification_data[i][4]\r\n \r\n \r\n \r\n ##Add electrified link data (given binary_array)\r\n electrified_links = []\r\n for i in range(len(binary_array)):\r\n if binary_array[i] == 0:\r\n continue\r\n else:\r\n electrified_link_data = copy.deepcopy(net_temp_array[i])\r\n #change the FFTT\r\n electrified_link_data[4] = str(electrification_data[i][5])\r\n electrified_link_data[2] =str(float(electrified_link_data[2]) * 1.001) \r\n electrified_link_data[3] =str(float(electrified_link_data[3]) * 1.001) \r\n electrified_links.append(electrified_link_data)\r\n #Repeat for BA link\r\n electrified_link_data = copy.deepcopy(net_temp_array_BA[i])\r\n #change the FFTT\r\n electrified_link_data[4] = str(electrification_data[i][6])\r\n electrified_link_data[2] =str(float(electrified_link_data[2]) * 1.001)\r\n electrified_link_data[3] =str(float(electrified_link_data[3]) * 1.001) \r\n electrified_links.append(electrified_link_data)\r\n \r\n \r\n #Save the metadata and network into a file names net_new.tntp\r\n #Step 1 compines the AB links, BA links and electrified links\r\n net_new = net_temp_array+net_temp_array_BA+electrified_links\r\n\r\n file1 = open(\"AlgB_data/net.txt\",\"w\")\r\n file1.write(new_header_temp)\r\n for i in range(len(net_new)):\r\n file1.write(\"\\t\" + str(net_new[i][0]) + \"\\t\" + str(net_new[i][1]) + \"\\t\" + str(net_new[i][2]) + \"\\t\" + str(net_new[i][3]) + \"\\t\" + str(net_new[i][4]) + \"\\t\" + str(net_new[i][5]) + \"\\t\" + str(net_new[i][6]) + \"\\t\" + str(net_new[i][7]) + \"\\t\" + str(net_new[i][8]) + \"\\t\" + str(net_new[i][9]) + \"\\t\" + \";\" + \"\\n\") \r\n file1.close() \r\n\r\n #print (\"File written successfully\")\r\n \r\n return\r\n\r\n#write_electrified_network(binary_array)\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n##################Section 4############################\r\n#This block is the candidate evaluation function.\r\n#Takes a candidate solution as input, calls the electrified network writer to write new network, solves TAP for it, and then returns the total system cost\r\n#Also, if the candidate solution violates total budget constraint, returns value of -9999999999999999\r\n\r\ndef fitness_evaluation(binary_arrays,data):\r\n fitness = -9999999999999999\r\n if calculate_electrification_costs(cost_array, binary_arrays)>Total_electrification_budget:\r\n print(\"overbudget\")\r\n return fitness\r\n else:\r\n write_electrified_network(binary_arrays)\r\n TScost_out = subprocess.check_output([\"java\", \"-jar\", \"AlgB_data/wrapPD.zip\" , \"AlgB_data/net.txt\" , \"AlgB_data/trips.txt\", \"AlgB_data/oneClass.txt\"],universal_newlines = True)\r\n return (-1*float(TScost_out))\r\n # return random.randint(-50000000, 10000000)\r\n\r\n\r\n# a_test=fitness_evaluation(binary_array,net)\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n#################Section 5############################\r\n#This section runs the binary GA for rail electrification.\r\n\r\n#Step1 - define data\r\ndata = net\r\n\r\n\r\n#Step 2 - create individual data \r\ndef create_individual(data):\r\n individual = copy.deepcopy(binary_array)\r\n return individual\r\n\r\n\r\n#Step 3 - initialize GA\r\nga = pyeasyga.GeneticAlgorithm(data, population_size=15, generations=100, crossover_probability=0.0, mutation_probability=0.3, elitism=True, maximise_fitness=True)\r\nga.create_individual = create_individual\r\n\r\n#Step 4 - assign fitness function\r\nga.fitness_function = fitness_evaluation\r\n\r\n\r\n#Step 5 - run GA\r\nga.run()\r\n\r\n\r\n#Step 6 - print out last generation\r\nfor individual in ga.last_generation():\r\n print (individual)\r\n\r\n#Step 7 - Save individuals to a file named results_txt\r\nfile1 = open(results_file,\"w\")\r\nnp.set_printoptions(threshold=np.inf)\r\nfile1.write(str(ga.best_individual()[1]))\r\nfile1.close()\r\n\r\n\r\n\r\n","sub_path":"Rail_GA.py","file_name":"Rail_GA.py","file_ext":"py","file_size_in_byte":7907,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"491402140","text":"import cv2\nimport numpy as np \nfrom matplotlib import pyplot as plt\n\ndef edgeDetect():\n\n cap = cv2.VideoCapture(0)\n\n while(cap.isOpened()):\n\n ret, frame = cap.read()\n\n if ret == True:\n\n plt.subplot(121), plt.show(frame, cmap = 'gray')\n plt.title(\"Initial video\"),plt.xticks([]), plt.yticks([])\n\n edge = cv2.Canny(frame, 100, 200)\n\n plt.subplot(122), plt.show(edge, cmap = 'gray')\n plt.title(\"This is an edge detected video\"), plt.xticks([]), plt.yticks([])\n\n if waitKey(1) & 0xFF == ord('q'):\n break\n\n else:\n break\n\n cv2.release()\n cv2.destroyAllWindows()\n\n\n\nedgeDetect()\n","sub_path":"edgedetect.py","file_name":"edgedetect.py","file_ext":"py","file_size_in_byte":697,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"419817426","text":"# -*- coding: utf-8 -*-\n# (C) 2013 Smile ()\n# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).\n\nfrom odoo import api, models\n\n\nclass AccountTax(models.Model):\n _inherit = 'account.tax'\n\n @api.multi\n def _get_move_line_vals(\n self, amount, journal_type, analytic_account_id,\n default=None, refund=False):\n if journal_type.endswith('_refund'):\n journal_type = journal_type.replace('_refund', '')\n refund = True\n sign = (journal_type == 'purchase') ^ refund and -1 or 1\n vals_list = []\n for tax_info in self.compute_all(amount)['taxes']:\n if tax_info['amount']:\n vals = (default or {}).copy()\n debit, credit = 0.0, tax_info['amount'] * sign\n if credit < 0.0:\n debit, credit = abs(credit), abs(debit)\n account_id = tax_info['account_id']\n if refund and tax_info['refund_account_id']:\n account_id = tax_info['refund_account_id']\n tax = self.browse(tax_info['id'])\n vals.update({\n 'account_id': account_id,\n 'debit': debit,\n 'credit': credit,\n 'tax_line_id': tax.id,\n })\n if tax.include_base_amount:\n vals['tax_ids'] = [(6, 0, tax.children_tax_ids.ids)]\n if tax.analytic:\n vals['analytic_account_id'] = analytic_account_id\n vals_list.append(vals)\n return vals_list\n","sub_path":"smile_account_asset/models/account_tax.py","file_name":"account_tax.py","file_ext":"py","file_size_in_byte":1610,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"364302654","text":"\"\"\"\nNodes that represent the data in a Quilt package.\n\"\"\"\nimport os\n\nimport pandas as pd\nfrom six import iteritems, string_types\n\nfrom .tools import core\nfrom .tools.const import SYSTEM_METADATA\nfrom .tools.util import is_nodename\n\n\nclass Node(object):\n \"\"\"\n Abstract class that represents a group or a leaf node in a package.\n \"\"\"\n def __init__(self, meta):\n # Can't instantiate it directly\n assert self.__class__ != Node.__class__\n assert meta is not None\n self._meta = meta\n\n def _class_repr(self):\n \"\"\"Only exists to make it easier for subclasses to customize `__repr__`.\"\"\"\n return \"<%s>\" % self.__class__.__name__\n\n def __repr__(self):\n return self._class_repr()\n\n def __call__(self):\n return self._data()\n\n def _data(self):\n raise NotImplementedError\n\n\nclass DataNode(Node):\n \"\"\"\n Represents a dataframe or a file. Allows accessing the contents using `()`.\n \"\"\"\n def __init__(self, package, node, data, meta):\n super(DataNode, self).__init__(meta)\n\n self._package = package\n self._node = node\n self.__cached_data = data\n\n def _data(self):\n \"\"\"\n Returns the contents of the node: a dataframe or a file path.\n \"\"\"\n if self.__cached_data is None:\n # TODO(dima): Temporary code.\n store = self._package.get_store()\n if isinstance(self._node, core.TableNode):\n self.__cached_data = store.load_dataframe(self._node.hashes)\n elif isinstance(self._node, core.FileNode):\n self.__cached_data = store.get_file(self._node.hashes)\n else:\n assert False\n return self.__cached_data\n\n\nclass GroupNode(Node):\n \"\"\"\n Represents a group in a package. Allows accessing child objects using the dot notation.\n Warning: calling _data() on a large dataset may exceed local memory capacity in Python (Only\n supported for Parquet packages).\n \"\"\"\n def __init__(self, meta):\n super(GroupNode, self).__init__(meta)\n\n def __setattr__(self, name, value):\n if name.startswith('_') or isinstance(value, Node):\n super(Node, self).__setattr__(name, value)\n else:\n raise AttributeError(\"{val} is not a valid package node\".format(val=value))\n\n def __repr__(self):\n pinfo = super(GroupNode, self).__repr__()\n group_info = '\\n'.join(name + '/' for name in sorted(self._group_keys()))\n if group_info:\n group_info += '\\n'\n data_info = '\\n'.join(sorted(self._data_keys()))\n return '%s\\n%s%s' % (pinfo, group_info, data_info)\n\n def _items(self):\n return ((name, child) for name, child in iteritems(self.__dict__)\n if not name.startswith('_'))\n\n def _data_keys(self):\n \"\"\"\n every child key referencing a dataframe\n \"\"\"\n return [name for name, child in self._items() if not isinstance(child, GroupNode)]\n\n def _group_keys(self):\n \"\"\"\n every child key referencing a group that is not a dataframe\n \"\"\"\n return [name for name, child in self._items() if isinstance(child, GroupNode)]\n\n def _keys(self):\n \"\"\"\n keys directly accessible on this object via getattr or .\n \"\"\"\n return [name for name in self.__dict__ if not name.startswith('_')]\n\n def _add_group(self, groupname):\n child = GroupNode({})\n setattr(self, groupname, child)\n\n def _data(self):\n \"\"\"\n Merges all child dataframes. Only works for dataframes stored on disk - not in memory.\n \"\"\"\n store = None\n hash_list = []\n stack = [self]\n while stack:\n node = stack.pop()\n if isinstance(node, GroupNode):\n stack.extend(child for _, child in sorted(node._items(), reverse=True))\n else:\n if not isinstance(node._node, core.TableNode):\n raise ValueError(\"Group contains non-dataframe nodes\")\n if not node._node.hashes:\n raise NotImplementedError(\"Can only merge built dataframes. Build this package and try again.\")\n node_store = node._package.get_store()\n if store is None:\n store = node_store\n elif node_store is not store:\n raise NotImplementedError(\"Can only merge dataframes from the same store\")\n hash_list += node._node.hashes\n\n if not hash_list:\n return None\n\n return store.load_dataframe(hash_list)\n\n\nclass PackageNode(GroupNode):\n \"\"\"\n Represents a package.\n \"\"\"\n def __init__(self, package, meta):\n super(PackageNode, self).__init__(meta)\n self._package = package\n\n def _class_repr(self):\n finfo = self._package.get_path()\n return \"<%s %r>\" % (self.__class__.__name__, finfo)\n\n def _set(self, path, value, build_dir=''):\n \"\"\"Create and set a node by path\n\n This creates a node from a filename or pandas DataFrame.\n\n If `value` is a filename, it must be relative to `build_dir`.\n `value` is stored as the export path.\n\n `build_dir` defaults to the current directory, but may be any\n arbitrary directory path, including an absolute path.\n\n Example:\n # Set `pkg.graph_image` to the data in '/home/user/bin/graph.png'.\n # If exported, it would export to '/bin/graph.png'\n `pkg._set(['graph_image'], 'bin/fizz.bin', '/home/user')`\n\n :param path: Path list -- I.e. ['examples', 'new_node']\n :param value: Pandas dataframe, or a filename relative to build_dir\n :param build_dir: Directory containing `value` if value is a filename.\n \"\"\"\n assert isinstance(path, list) and len(path) > 0\n\n if isinstance(value, pd.DataFrame):\n metadata = {}\n core_node = core.TableNode(hashes=[], format=core.PackageFormat.default.value)\n elif isinstance(value, string_types + (bytes,)):\n # bytes -> string for consistency when retrieving metadata\n value = value.decode() if isinstance(value, bytes) else value\n if os.path.isabs(value):\n raise ValueError(\"Invalid path: expected a relative path, but received {!r}\".format(value))\n # Security: filepath does not and should not retain the build_dir's location!\n metadata = {SYSTEM_METADATA: {'filepath': value, 'transform': 'id'}}\n core_node = core.FileNode(hashes=[])\n if build_dir:\n value = os.path.join(build_dir, value)\n else:\n accepted_types = tuple(set((pd.DataFrame, bytes) + string_types))\n raise TypeError(\"Bad value type: Expected instance of any type {!r}, but received type {!r}\"\n .format(accepted_types, type(value)), repr(value)[0:100])\n\n for key in path:\n if not is_nodename(key):\n raise ValueError(\"Invalid name for node: {}\".format(key))\n\n node = self\n for key in path[:-1]:\n child = getattr(node, key, None)\n if not isinstance(child, GroupNode):\n child = GroupNode({})\n setattr(node, key, child)\n\n node = child\n\n key = path[-1]\n data_node = DataNode(self._package, core_node, value, metadata)\n setattr(node, key, data_node)\n","sub_path":"compiler/quilt/nodes.py","file_name":"nodes.py","file_ext":"py","file_size_in_byte":7503,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"619430671","text":"# File: graduation.py\n# Author: Daniel Diseroad\n# Date: 11/8/16\n# Section: 28\n# E-mail: ddiser1@umbc.edu\n# Description: This program uses a text file to get information about students and output it into another txt file\n# Collaboration: During lab, collaboration between students is allowed,\n# although I understand I still must understand the material\n# and complete the assignment myself. \n\ndef main():\n roster = open(\"roster.txt\",\"r\")\n announcements = open(\"announcements.txt\",\"w\")\n valeGpa = []\n valeN = []\n for line in roster:\n degree, gpa, lastN, firstN = line.split(\";\")\n firstN = firstN[:-1]\n name = firstN + \" \" + lastN\n valeGpa.append(gpa)\n valeN.append(name)\n line = name + \" is graduating with a degree in \" + degree + \"\\n\"\n print(line)\n announcements.write(line)\n highest,index = 0,0\n for i in range(len(valeGpa)):\n if float(valeGpa[i]) > highest:\n highest = float(valeGpa[i])\n index = i\n print(\"The student with the highest GPA is\", valeN[index],\"with an\",valeGpa[index])\n roster.close()\n announcements.close()\nmain()\n","sub_path":"201/Labs/lab10/graduation.py","file_name":"graduation.py","file_ext":"py","file_size_in_byte":1205,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"296467655","text":"import json, requests\nfrom urllib.request import urlopen\n\nclass IP:\n\n\tdef __init__(self):\n\n\t\tIP = requests.get('http://ip.42.pl/raw').text # Get the IP\n\n\t\t# Get the location information of IP\n\t\turl = 'https://ipapi.co/{}/json/'.format(IP)\n\t\tresponse = urlopen(url)\n\t\tdata = json.load(response)\n\n\t\t# Extract individual information from IP\n\t\tself.IP = data['ip']\n\t\tself.org = data['org']\n\t\tself.city = data['city']\n\t\tself.country = data['country']\n\t\tself.latitude = data['latitude']\n\t\tself.longitude = data['longitude']\n\t\tself.region = data['region']\n\n\nif __name__ == \"__main__\":\n\tip = IP()\n\tprint(ip.IP);","sub_path":"app/scripts/IP.py","file_name":"IP.py","file_ext":"py","file_size_in_byte":604,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"502901252","text":"from flask import request, jsonify\nfrom logs.simplex_logger import logger\nfrom common_funcs.send_data_to_front import send_data\nfrom values_cord_indicator.get_dataframe_from_db import CreateDownloadDfIndicator\nfrom values_cord_indicator.conditions_for_df import GetUploadData\nfrom values_cord_indicator.database_queries import GetDfForDownloadIndicator\nfrom values_cord_indicator.indicator_helpers import make_dataframe_readable\nfrom common_funcs.funcs_for_user import create_dataframe_for_user_by_title\nfrom abc import abstractmethod\n\n\nclass DownloadIndicator:\n\n def __init__(self, indicator):\n self.indicator = indicator\n self.indicator_data = None\n self.filename = None\n\n def indicator_download(self):\n\n input_arguments = self.__get_input_args()\n if not input_arguments:\n return jsonify(500), '0'\n db_df = self.__queries_to_db()\n download_df = CreateDownloadDfIndicator(self.indicator_data)\n dataframe = download_df.create_download_dataframe(input_arguments, db_df)\n if dataframe is None:\n return jsonify(500), '0'\n\n dataframe = make_dataframe_readable(dataframe, self.indicator_data)\n dataframe_for_user = create_dataframe_for_user_by_title(dataframe, 'Имя роли')\n excel_file = send_data(dataframe_for_user)\n\n if excel_file:\n return excel_file, self.filename\n else:\n return jsonify(500), '0'\n\n def __get_input_args(self):\n input_arguments = {'scenario': int(request.form.get('scenario', 0)),\n 'version': int(request.form.get('version', 0))}\n self.__determine_indicator_download_metadata()\n if self.indicator_data is None or self.filename is None:\n return None\n return input_arguments\n\n def __queries_to_db(self):\n queries = GetDfForDownloadIndicator(self.indicator_data)\n queries.fill_df_for_download_indicator()\n\n return queries\n\n def __determine_indicator_download_metadata(self):\n upload_data = GetUploadData()\n self.indicator_data = upload_data.get_indicator_instance(self.indicator)\n self.filename = upload_data.get_excel_filename(self.indicator)\n","sub_path":"values_cord_indicator/indicators_download.py","file_name":"indicators_download.py","file_ext":"py","file_size_in_byte":2227,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"187965634","text":"import os\n\ntry:\n from dotenv import load_dotenv\n load_dotenv(verbose=True)\nexcept Exception:\n pass\n\nAWS_READ_TABLE = os.getenv(\"AWS_READ_TABLE\")\nAWS_WRITE_TABLE = os.getenv(\"AWS_WRITE_TABLE\")\nAWS_REGION = os.getenv(\"REGION\")\nORIGINS = os.getenv(\"ORIGINS\")\nWEBHOOK_URL = os.getenv(\"WEBHOOK_URL\")\nERROR_WEBHOOK = os.getenv(\"ERROR_WEBHOOK\")\nS3_BUCKET = os.getenv(\"S3_BUCKET\")\n\nEMAIL = {\n \"CONFIG_SET\": \"ConfigSet\",\n \"CHARSET\": \"UTF-8\",\n # The subject line for the email.\n \"SUBJECT\": \"Amazon SES Test (SDK for Python)\",\n # The email body for recipients with non-HTML email clients.\n \"BODY_TEXT\": (\"Amazon SES Test (Python)\\r\\n\"\n \"This email was sent with Amazon SES using the \"\n \"AWS SDK for Python (Boto).\"),\n # The HTML body of the email.\n \"BODY_HTML\": \"\"\"\n \n \n

Amazon SES Test (SDK for Python)

\n

This email was sent with\n Amazon SES using the\n \n AWS SDK for Python (Boto).

\n \n \"\"\"\n}\n","sub_path":"python/e-sender/code/core/conf.py","file_name":"conf.py","file_ext":"py","file_size_in_byte":1142,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"570064657","text":"\nimport os\nimport glob\n\ndef createClassIndList(movie_dir, list_dir,class_dest):\n\n movie_cat_list = os.listdir(movie_dir)\n classind = {}\n\n for c,fi in enumerate(movie_cat_list):\n classind[fi] = c\n\n with open(class_dest, 'w') as f:\n for k,v in classind.items():\n f.write('{}'.format(v) + ' ' +k+'\\n')\n return classind\n\ndef createTraintestLists(movie_dir, train_dest, test_dest, classind):\n\n with open(train_dest, 'w') as tr, open(test_dest, 'w') as ts:\n for fol in classind.keys():\n data_path = os.path.join(movie_dir,fol)\n data_list = os.listdir(data_path)\n #print(data_list)\n for i,fil in enumerate(data_list):\n fil_pa = os.path.join(fol,fil)\n #print(fil_pa)\n if i < 3:\n tr.write(fil_pa + '\\n')\n else:\n ts.write(fil_pa + '\\n')\n\nif __name__ == '__main__':\n\n data_dir = 'C:\\\\Users\\\\Reem\\\\Projects\\\\ActionRecognition\\\\data'\n movie_dir = os.path.join(data_dir, 'Movie_dataset_sample')\n list_dir = os.path.join(data_dir, 'movieTrainTestlist')\n\n class_dest = os.path.join(list_dir,'classInd.txt')\n class_ind = createClassIndList(movie_dir, list_dir, class_dest)\n\n train_dest = os.path.join(list_dir, 'trainlist0.txt')\n test_dest = os.path.join(list_dir, 'testlist0.txt')\n createTraintestLists(movie_dir, train_dest, test_dest, class_ind)\n","sub_path":"textCreation.py","file_name":"textCreation.py","file_ext":"py","file_size_in_byte":1448,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"462085331","text":"import pygame\n\ngravity = 0.01\n\n\nclass QueenSprite:\n def __init__(self, col, img, target_posn):\n \"\"\" Create and initialize a queen for this\n target position on the board\n \"\"\"\n self.image = img\n self.col_number = col\n self.target_posn = target_posn\n (x, y) = target_posn\n self.posn = (x, 0) # Start ball at top of its column\n self.y_velocity = 0 # with zero initial velocity\n\n def update(self):\n self.y_velocity += gravity # Gravity changes velocity\n (x, y) = self.posn\n new_y_pos = y + self.y_velocity # Velocity moves the ball\n\n (target_x, target_y) = self.target_posn # Unpack the position\n dist_to_go = target_y - new_y_pos # How far to our floor?\n\n if dist_to_go < 0: # Are we under floor?\n self.y_velocity = -0.65 * self.y_velocity # Bounce\n new_y_pos = target_y + dist_to_go # Move back above floor\n\n self.posn = (x, new_y_pos) # to this new position.\n\n def draw(self, target_surface):\n target_surface.blit(self.image, self.posn)\n\n def printxy(self):\n print(\"Queen[{2}] (x,y) & Target ():({0}), {1}\".format(self.posn, self.target_posn, self.col_number))\n\n\ndef draw_board(the_board):\n \"\"\" Draw a chess board with queens, as determined by the the_board. \"\"\"\n\n pygame.init()\n colors = [(255, 0, 0), (0, 0, 0)] # Set up colors [red, black]\n\n n = len(the_board) # This is an NxN chess board.\n surface_sz = 480 # Proposed physical surface size.\n sq_sz = surface_sz // n # sq_sz is length of a square.\n surface_sz = n * sq_sz # Adjust to exactly fit n squares.\n\n # Create the surface of (width, height), and its window.\n surface = pygame.display.set_mode((surface_sz, surface_sz))\n\n queen = pygame.transform.scale(pygame.image.load(\"pic/queen.png\"),\n (int(sq_sz - 4), int(sq_sz - 4)))\n\n # Use an extra offset to centre the ball in its square.\n # If the square is too small, offset becomes negative,\n # but it will still be centered :-)\n queen_offset = (sq_sz - queen.get_width()) // 2\n\n all_sprites = [] # Keep track of all the sprites\n\n # Create a sprite object for each queen, and populate our list.\n for (col, row) in enumerate(the_board):\n a_queen = QueenSprite(col, queen,\n (col * sq_sz + queen_offset, row * sq_sz + queen_offset))\n all_sprites.append(a_queen)\n\n while True:\n\n # Look for an event from keyboard, mouse, etc.\n ev = pygame.event.poll()\n if ev.type == pygame.QUIT:\n break;\n\n for sprite in all_sprites:\n sprite.update()\n # sprite.printxy()\n\n # Draw a fresh background (a blank chess board)\n for row in range(n): # Draw each row of the board.\n c_indx = row % 2 # Alternate starting color\n for col in range(n): # Run through cols drawing squares\n the_square = (col * sq_sz, row * sq_sz, sq_sz, sq_sz)\n surface.fill(colors[c_indx], the_square)\n # Now flip the color index for the next square\n c_indx = (c_indx + 1) % 2\n\n # Ask the sprite to draw its self\n for sprite in all_sprites:\n sprite.draw(surface)\n\n pygame.display.flip()\n\n pygame.quit()\n\n\nif __name__ == '__main__':\n draw_board([0, 5, 3, 1, 6, 4, 2])\n","sub_path":"17_pygame/Example_17.4.py","file_name":"Example_17.4.py","file_ext":"py","file_size_in_byte":3432,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"246075073","text":"#!/usr/bin/python3\nimport CAN\nimport CANopen\n\nCAN_INTERFACE = \"vcan0\"\n\ncan_bus = CAN.Bus(CAN_INTERFACE)\n\nnode_id = 0x02\n\ncanopen_od = CANopen.ObjectDictionary({\n CANopen.ODI_DEVICE_TYPE: 0x00000000,\n CANopen.ODI_ERROR: 0x00,\n CANopen.ODI_HEARTBEAT_PRODUCER_TIME: 1000, # 16-bit, in ms\n CANopen.ODI_IDENTITY: CANopen.Object({\n CANopen.ODSI_VALUE: 4,\n CANopen.ODSI_IDENTITY_VENDOR: 0x00000000,\n CANopen.ODSI_IDENTITY_PRODUCT: 0x00000001,\n CANopen.ODSI_IDENTITY_REVISION: 0x00000000,\n CANopen.ODSI_IDENTITY_SERIAL: 0x00000001,\n }),\n CANopen.ODI_SDO_SERVER: CANopen.Object({\n CANopen.ODSI_VALUE: 2,\n CANopen.ODSI_SDO_SERVER_DEFAULT_CSID: (CANopen.FUNCTION_CODE_SDO_RX << CANopen.FUNCTION_CODE_BITNUM) + node_id,\n CANopen.ODSI_SDO_SERVER_DEFAULT_SCID: (CANopen.FUNCTION_CODE_SDO_TX << CANopen.FUNCTION_CODE_BITNUM) + node_id,\n }),\n CANopen.ODI_TPDO1_COMMUNICATION_PARAMETER: CANopen.Object({\n CANopen.ODSI_VALUE: 2,\n CANopen.ODSI_TPDO_COMM_PARAM_ID: node_id,\n CANopen.ODSI_TPDO_COMM_PARAM_TYPE: 1,\n }),\n CANopen.ODI_TPDO1_MAPPING_PARAMETER: CANopen.Object({\n CANopen.ODSI_VALUE: 2,\n 0x01: (CANopen.ODI_SYNC << 16) + (CANopen.ODSI_VALUE << 8) + 32,\n 0x02: (CANopen.ODI_SYNC_TIME << 16) + (CANopen.ODSI_VALUE << 8) + 32,\n }),\n})\n\nnode = CANopen.Node(can_bus, node_id, canopen_od)\nnode.boot()\nnode.listen(True) # Listen forever (blocking)\n","sub_path":"canopen-node.py","file_name":"canopen-node.py","file_ext":"py","file_size_in_byte":1462,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"552692731","text":"#!/usr/bin/env python\n\n# import own scripts\nimport matrix as bt\nimport image as mi\nimport Memory\nimport Network\n\n# import numpy\nimport numpy as np\nfrom numpy import random\n\n# tensorflow\nimport numpy as np\nimport tensorflow as tf\nfrom tensorflow import keras\n\n# Import OpenCV libraries and tools\nimport cv2 as cv\nfrom cv_bridge import CvBridge, CvBridgeError\n\n# ROS\nimport rospy\nimport rospkg\nfrom std_msgs.msg import String, Float32, Int32\nfrom sensor_msgs.msg import Image, CompressedImage\nfrom geometry_msgs.msg import Twist\nfrom gazebo_msgs.srv import GetModelState\nfrom gazebo_msgs.msg import ModelState\nfrom gazebo_msgs.srv import SetModelState\n\n# other\nimport math\nimport time\nimport random\n\n\nclass Node:\n # callback; copies the received image into a global numpy-array\n def cam_im_raw_callback(self, msg):\n # convert ROS image to cv image, copy it and save it as a global\n # numpy-array\n # last image\n img = self.imgHelper.img_conversion(msg)\n self.my_img = np.copy(img)\n\n # last couple of images (image queue)\n mod = self.img_cnt % self.number_of_images\n self.my_img_queue[mod] = self.my_img\n\n # count the received images\n self.img_cnt += 1\n print(\"Number of images = \" + str(self.img_cnt))\n\n # wait until a new image is received\n def get_image(self):\n nr_images = self.img_cnt\n while (self.img_cnt <= nr_images):\n pass\n return self.my_img\n\n # wait until image stack is full\n def get_stack_of_images(self):\n nr_images = self.img_cnt\n mod_old = -1\n while (self.img_cnt <= (nr_images + self.number_of_images)):\n mod_new = self.img_cnt % self.number_of_images\n if not (mod_new == mod_old):\n self.img_stack[mod_new][0] = self.my_img\n mod_old = mod_new\n return self.img_stack\n\n # constructor\n def __init__(self):\n # helper classes\n self.bot = bt.Bot() # reward + q-matrix\n self.imgHelper = mi.MyImage() # image processing\n self.memory = Memory.Memory(100) # replay buffer\n\n # global variables\n # images\n # next couple of (four) consecutive images\n self.number_of_images = 4\n self.my_img = np.zeros(50) # current image\n self.img_stack = np.zeros(shape=[self.number_of_images, 1,\n len(self.my_img)])\n self.img_cnt = 0 # number of images received\n # image queue for the last couple of images\n self.my_img_queue = np.zeros(shape=[self.number_of_images,\n len(self.my_img)])\n\n self.vel_msg = Twist() # message to post on topic /cmd_vel\n self.start = time.time() # starting time\n self.explorationMode = False # Bool: exploring (True) or exploiting (False)?\n\n # terminal states\n self.lost_line = 7\n self.stop_action = 7\n\n # current state and action (initially negative)\n self.curr_state = -1\n self.curr_action = -1\n\n # last state (initially negative)\n self.last_state = -1000\n\n # starting coordinates of the robot\n self.x_position = -0.9032014349\n self.y_position = -6.22487658223\n self.z_position = -0.0298790967155\n\n # initial values\n self.max_episodes = 200\n self.speed = 10.0\n\n # deviation from speed to turn the robot to the left or to the\n # right\n self.sharp = self.speed * (\n 1.0 / 7.0) # sharp curve => big difference\n self.middle = self.speed * (\n 1.0 / 8.5) # middle curve => middle difference\n self.slightly = self.speed * (\n 1.0 / 10.0) # slight curve => slight difference\n\n # strings to display actions and states\n self.action_strings = {\n 0: \"sharp left\",\n 1: \"left\",\n 2: \"slightly left\",\n 3: \"forward\",\n 4: \"slightly right\",\n 5: \"right\",\n 6: \"sharp right\",\n 7: \"stop\"\n }\n\n self.state_strings = {\n 0: \"far left\",\n 1: \"left\",\n 2: \"slightly left\",\n 3: \"middle\",\n 4: \"slightly right\",\n 5: \"right\",\n 6: \"far right\",\n 7: \"lost\"\n }\n\n # neural network\n # target vector\n #self.targets = np.zeros(shape=[1, (len(self.action_strings)-1)],\n #dtype='float64')\n self.sess = tf.compat.v1.Session() # tensorflow session object\n self.batch_size = 4 # batch size for replay buffer\n self.mini_batch_size = 2 # batch size for neural network\n # policy network to train on\n dim_input = np.zeros(shape=[4, 200])\n self.policy_net = Network.Network(images = dim_input,\n size_layer1 = 5, size_layer2 = 5, session = self.sess,\n batch_size =\n self.mini_batch_size)\n # target network to calculate optimal q-values on\n self.target_net = Network.Network(images = self.img_stack,\n size_layer1 = 5, size_layer2 = 5, session = self.sess, batch_size =\n self.mini_batch_size)\n\n # publisher to publish on topic /cmd_vel\n self.velocity_publisher = rospy.Publisher('/cmd_vel', Twist,\n queue_size=100)\n # initializing ROS-node\n rospy.init_node('reinf_matrix_driving', anonymous=True)\n # subscribe to topic '/camera/image_raw' using rospy.Subscriber\n # class\n self.sub = rospy.Subscriber('/camera/image_raw', Image,\n self.cam_im_raw_callback)\n\n # sets fields of Twist variable so robot drives sharp left\n def sharp_left(self):\n vel_msg = Twist()\n vel_msg.linear.x = self.speed + self.sharp\n vel_msg.linear.y = self.speed - self.sharp\n vel_msg.linear.z = 0\n vel_msg.angular.x = 0\n vel_msg.angular.y = 0\n vel_msg.angular.z = 0\n # print(\"SHARP LEFT\")\n return vel_msg\n\n # sets fields of Twist variable so robot drives slightly left\n def slightly_left(self):\n vel_msg = Twist()\n vel_msg.linear.x = self.speed + self.slightly\n vel_msg.linear.y = self.speed - self.slightly\n vel_msg.linear.z = 0\n vel_msg.angular.x = 0\n vel_msg.angular.y = 0\n vel_msg.angular.z = 0\n # print(\"SLIGHTLY LEFT\")\n return vel_msg\n\n # sets fields of Twist variable so robot drives left\n def left(self):\n vel_msg = Twist()\n vel_msg.linear.x = self.speed + self.middle\n vel_msg.linear.y = self.speed - self.middle\n vel_msg.linear.z = 0\n vel_msg.angular.x = 0\n vel_msg.angular.y = 0\n vel_msg.angular.z = 0\n # print(\"LEFT\")\n return vel_msg\n\n # sets fields of Twist variable so robot drives forward\n def forward(self):\n vel_msg = Twist()\n vel_msg.linear.x = self.speed\n vel_msg.linear.y = self.speed\n vel_msg.linear.z = 0\n vel_msg.angular.x = 0\n vel_msg.angular.y = 0\n vel_msg.angular.z = 0\n # print(\"FORWARD\")\n return vel_msg\n\n # sets fields of Twist variable so robot drives slightly right\n def slightly_right(self):\n vel_msg = Twist()\n vel_msg.linear.x = self.speed - self.slightly\n vel_msg.linear.y = self.speed + self.slightly\n vel_msg.linear.z = 0\n vel_msg.angular.x = 0\n vel_msg.angular.y = 0\n vel_msg.angular.z = 0\n # print(\"SLIGHTLY RIGHT\")\n return vel_msg\n\n # sets fields of Twist variable so robot drives right\n def right(self):\n vel_msg = Twist()\n vel_msg.linear.x = self.speed - self.middle\n vel_msg.linear.y = self.speed + self.middle\n vel_msg.linear.z = 0\n vel_msg.angular.x = 0\n vel_msg.angular.y = 0\n vel_msg.angular.z = 0\n # print(\"RIGHT\")\n return vel_msg\n\n # sets fields of Twist variable so robot drives sharp right\n def sharp_right(self):\n vel_msg = Twist()\n vel_msg.linear.x = self.speed - self.sharp\n vel_msg.linear.y = self.speed + self.sharp\n vel_msg.linear.z = 0\n vel_msg.angular.x = 0\n vel_msg.angular.y = 0\n vel_msg.angular.z = 0\n # print(\"SHARP RIGHT\")\n return vel_msg\n\n # sets fields of Twist variable to stop robot and puts the robot\n # back to starting position\n def stop(self):\n print(\"Stop\")\n vel_msg = Twist()\n vel_msg.linear.x = 0.0\n vel_msg.linear.y = 0.0\n vel_msg.linear.z = 0\n vel_msg.angular.x = 0\n vel_msg.angular.y = 0\n vel_msg.angular.z = 0\n return vel_msg\n\n # wait for next image (do not start with state 'lost')\n # curr_number_img = self.img_cnt\n # while (self.img_cnt <= curr_number_img + 2):\n # i = 1\n\n # publishes stopping message\n def stopRobot(self):\n vel = self.stop()\n self.velocity_publisher.publish(vel)\n\n # send the ROS message\n def execute_action(self, action):\n # execute action\n vel = Twist()\n directions = {\n 0: self.sharp_left,\n 1: self.left,\n 2: self.slightly_left,\n 3: self.forward,\n 4: self.slightly_right,\n 5: self.right,\n 6: self.sharp_right,\n 7: self.stop\n }\n function = directions.get(action)\n vel = function()\n self.velocity_publisher.publish(vel)\n\n ######################################### QUELLE ##########################################\n '''\n https://answers.gazebosim.org//question/18372/getting-model-state-via-rospy/\n '''\n\n def set_position(self, x, y, z):\n state_msg = ModelState()\n state_msg.model_name = 'three_pi'\n state_msg.pose.position.x = x\n state_msg.pose.position.y = y\n state_msg.pose.position.z = z\n state_msg.pose.orientation.x = 0\n state_msg.pose.orientation.y = 0\n state_msg.pose.orientation.z = 0\n state_msg.pose.orientation.w = 0\n\n rospy.wait_for_service('/gazebo/set_model_state')\n try:\n set_state = rospy.ServiceProxy('/gazebo/set_model_state',\n SetModelState)\n resp = set_state(state_msg)\n\n except rospy.ServiceException as e:\n print(\"Service call failed: %s\" % e)\n\n ###########################################################################################\n\n # At the moment: reset to same starting position\n # choose one of five given positions randomly\n def choose_random_starting_position(self):\n # choose random number between 0 and 1\n rand = random.uniform(0, 1)\n '''\n if(rand <= (1.0/5.0)):\n #initial starting position\n self.x_position = -3.4032014349\n self.y_position = -6.22487658223\n self.z_position = -0.0298790967155\n if (rand > (1.0/5.0) and rand <= (2.0 / 5.0)):\n # straight line (long) going into left curve\n self.x_position = -0.9032014349\n self.y_position = -6.22487658223\n self.z_position = -0.0298790967155\n elif (rand > (2.0 / 5.0) and rand <= (3.0 / 5.0)):\n # sharp left curve\n self.x_position = 0.930205421421\n self.y_position = -5.77364575559\n self.z_position = -0.0301045554742\n elif (rand > (5.0 / 5.0) and rand <= (4.0 / 5.0)):\n # sharp right curve\n self.x_position = 1.1291257432\n self.y_position = -3.37940826549\n self.z_position = -0.0298815752691\n else:\n # straight line going into right curve\n self.x_position = 0.4132014349\n self.y_position = -2.89940826549\n self.z_position = -0.0298790967155\n '''\n # straight line (long)\n self.x_position = -0.9032014349\n self.y_position = -6.22487658223\n self.z_position = -0.0298790967155\n\n\n # if user pressed ctrl+c --> stop the robot\n def shutdown(self):\n print(\"Stopping\")\n # publish\n self.vel_msg = self.stop()\n self.velocity_publisher.publish(self.vel_msg)\n\n # puts robot back to starting position\n def reset_environment(self):\n self.choose_random_starting_position()\n self.set_position(self.x_position, self.y_position,\n self.z_position)\n\n # decide whether to explore or to exploit\n def epsilon_greedy(self, e):\n # random number\n exploration_rate_threshold = random.uniform(0, 1)\n\n if (exploration_rate_threshold < e):\n # explore\n self.explorationMode = True\n return True\n else:\n # exploit\n self.explorationMode = False\n return False\n\n # main program\n def reinf_main(self):\n # tell program what to do on shutdown (user presses ctrl+c)\n rospy.on_shutdown(self.shutdown)\n\n # time statistics\n self.start = time.time() # starting time\n self.learning_time = 0 # end of learning\n\n # episodes\n self.explorationMode = False # exploring or exploiting?\n episode_counter = 0 # number of done episodes\n step_counter = 0 # counts every while iteration\n gamma = 0.95 # learning rate\n alpha = 0.8 # learning rate\n\n # variables deciding whether to explore or to exploit\n exploration_prob = 0.99\n decay_rate = 0.001\n min_exploration_rate = 0.01\n max_exploration_rate = 1\n\n # set starting position of the robot\n # not random, even though the name says differently\n self.choose_random_starting_position()\n self.set_position(self.x_position, self.y_position,\n self.z_position)\n\n # initialize starting parameters\n # current state and action are negative before starting\n self.curr_state = -1\n self.curr_action = -1\n self.last_state = -1000\n\n # images\n # image for current state\n img = np.zeros(shape=[self.number_of_images, 1, 50])\n # image for last state\n last_img = np.zeros(shape=[self.number_of_images, 1, 50])\n\n # wait for the first couple of images without doing anything\n # to make sure, that the first image received is a proper one\n self.get_stack_of_images()\n\n\n # important steps of the algorithm\n try:\n rate = rospy.Rate(20)\n # main loop\n while not rospy.is_shutdown():\n # reinforcement learning\n if (episode_counter <= self.max_episodes):\n print(\"Learning\")\n # wait for next image\n # img = self.get_stack_of_images()\n last_img = np.copy(img)\n my_img = self.get_image()\n my_img_queue = np.copy(self.my_img_queue)\n img[0] = my_img\n # print(\"Shape of image = \" + str(np.shape(img)))\n\n # save last state, get new state and calculate reward\n self.last_state = self.curr_state\n print(\"Last state: \" + str(\n self.state_strings.get(self.last_state)))\n self.curr_state = self.bot.get_state(my_img)\n # stop robot immediatley, but still do calculations\n if(self.curr_state == self.lost_line):\n self.stopRobot()\n\n print(\"Current state: \" + str(self.state_strings.get(\n self.curr_state)))\n reward = self.bot.calculate_reward(self.curr_state)\n print(\"Reward: \" + str(reward))\n\n # store experience\n my_img_queue = my_img_queue.flatten()\n self.memory.store_experience(my_img_queue, last_img,\n self.curr_action, reward)\n\n # update target network\n # targets = self.fill_targets(self.last_state)\n # targets = self.fill_targets(self.curr_action, reward)\n if(step_counter % 100 == 1):\n self.target_net = self.policy_net.copy(self.target_net)\n\n '''\n # update NN if the last state was not 'lost'\n # otherwise it will only learn to stop,\n # because after a stop action, the robot will always\n # be in the middle -> highest reward\n if not (self.last_state == self.lost_line):\n # get random (batch of) experience(s)\n experience = []\n batch_sz = self.number_of_images\n if not (self.curr_action == -1):\n experience = self.memory.get_random_experience(\n batch_size=batch_sz)\n\n # put input in network model\n # use experiences by a chance of 50% if enough episodes\n # explored\n rand = random.uniform(0, 1)\n if (\n episode_counter >= self.max_episodes / 4 and rand >= 0.5):\n print(\"Using experience\")\n # make a stack of experience images\n exp_img = np.zeros(\n shape=[self.number_of_images, 1, 50])\n for i in range(len(experience)):\n exp_img[i] = experience[i].get(\"last_state\")\n\n # feed network\n output = self.update_weights(images=exp_img,\n learning_rate=0.01,\n sess=sess, epochs=1,\n tgts=targets)\n\n # make new experiences\n else:\n output = self.update_weights(images=img,\n learning_rate=0.01,\n sess=sess, epochs=1,\n tgts=targets)\n\n # print(\"\\n\\nOutput of DNN = \" + str(output))\n self.q_values = output\n # print(\"Q Values = \" + str(self.q_values))\n '''\n\n # get optimal q-values for current state via the target\n # network\n # for later use:\n # targets = self.target_net.use_network(images=last_img)\n # current use: keep it simple\n targets = np.zeros(shape=[1, 7])\n for i in range(len(targets[0])):\n targets[0, i] = 0\n if not(self.curr_action == -1):\n targets[0, self.curr_action] = reward # 1\n\n # get self.batch_size number of examples from buffer\n buffer_examples = self.memory.get_random_experience(\n self.batch_size)\n # print(\"Buffer = \" + str(buffer_examples))\n buffer_images = []\n for i in range(len(buffer_examples)):\n state = buffer_examples[i].get(\n \"state\")\n state = state.flatten()\n print(\"state[i] = \" + str(state))\n buffer_images.append(state)\n\n print(\"shape buffer_images = \" + str(np.shape(buffer_images)))\n\n # update policy network with optimal q-values\n output = self.policy_net.update_weights(\n images=buffer_images, epochs=1, targets=targets,\n learning_rate=0.01)\n\n # print(\"\\n\\nOutput of DNN = \" + str(output))\n self.q_values = output\n # print(\"Q Values = \" + str(self.q_values))\n\n # begin a new episode if robot lost the line\n if (self.curr_state == self.lost_line):\n # stop robot\n self.stopRobot()\n # set robot back to starting position\n self.reset_environment()\n # episode is done => increase counter\n episode_counter += 1\n print(\"NEW EPISODE: \", episode_counter)\n # print current q-matrix to see what's\n # going on\n # self.bot.printMatrix(time.time())\n print(\"-\" * 100)\n # skip the next steps and start a new loop\n continue\n\n # get the next action\n # if exploring: choose random action\n if (self.epsilon_greedy(exploration_prob)):\n print(\"Exploring\")\n # action = self.bot.explore(img[self.number_of_images - 1])\n action = np.argmax(self.q_values)\n print(\"Action: \" + self.action_strings.get(action))\n self.execute_action(action)\n self.curr_action = action\n # if exploiting: choose best action\n else:\n print(\"Exploiting\")\n # choose best action by using the NN with the current\n # image, not updating it\n self.q_values = self.policy_net.use_network(\n images=my_img_queue)\n action = np.argmax(self.q_values)\n print(\"Action: \" + self.action_strings.get(action))\n self.execute_action(action)\n self.curr_action = action\n\n # decay the probability of exploring\n exploration_prob = min_exploration_rate + (\n max_exploration_rate - min_exploration_rate) * \\\n np.exp(-decay_rate * episode_counter)\n\n # end of iteration\n print(\"-\" * 100)\n\n # start a new loop at the current position\n # (robot will only be set back to starting\n # position if line is lost)\n\n # using trained network to drive\n else:\n # first time in else: save time that robot\n # spent learning\n if (episode_counter == self.max_episodes + 1):\n self.learning_time = time.time()\n\n print(\"Driving!\")\n # wait for new image\n img[0] = self.get_image()\n # choose best next action from neural network\n # action = self.bot.drive(img)\n # use NN, do NOT update it\n self.q_values = self.policy_net.use_network(images=my_img_queue)\n action = np.argmax(self.q_values)\n print(\"Action: \" + self.action_strings.get(action))\n # execute action\n self.execute_action(action)\n # stop if line is lost (hopefully never, if\n # robot learned properly)\n if (action == self.stop_action):\n self.reset_environment()\n\n step_counter += 1\n\n except rospy.ROSInterruptException:\n pass\n\n\n# start node\nif __name__ == '__main__':\n node = Node()\n node.reinf_main()\n","sub_path":"node/DQN/dqn_2/src/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":20963,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"81414008","text":"from django.contrib import admin\n\nfrom lifeapp.models.Cite import Cite\nfrom lifeapp.models.CiteCategory import CiteCategory\nfrom lifeapp.models.Contact import Contact\nfrom lifeapp.models.Fixture import Fixture\nfrom lifeapp.models.FixtureCategory import FixtureCategory\nfrom lifeapp.models.Partner import Partner\nfrom lifeapp.models.TimeContext import TimeContext\nfrom lifeapp.models.TimeEntry import TimeEntry\n\n\nclass ContactAdmin(admin.ModelAdmin):\n list_display = ('__str__',)\n\nadmin.site.register(Contact, ContactAdmin)\n\n\nclass TimeContextAdmin(admin.ModelAdmin):\n list_display = ('name', 'client')\n list_filter = ('client__name',)\n\n\nclass TimeEntryAdmin(admin.ModelAdmin):\n list_display = ('__str__', 'context', 'client', 'start_date', 'end_date', 'duration')\n list_filter = ('context__name', 'context__client__name')\n\nadmin.site.register(TimeContext, TimeContextAdmin)\nadmin.site.register(TimeEntry, TimeEntryAdmin)\n\n\nclass PartnerAdmin(admin.ModelAdmin):\n list_display = ['name', 'created_on']\n\n\nclass FixtureCategoryAdmin(admin.ModelAdmin):\n list_display = ['name', 'created_on']\n\n\nclass FixtureAdmin(admin.ModelAdmin):\n list_display = ['code', 'category', 'manufacturer', 'model', 'creditor', 'bought_on', 'created_on']\n list_filter = ['category', 'manufacturer', 'creditor']\n\nadmin.site.register(Fixture, FixtureAdmin)\nadmin.site.register(FixtureCategory, FixtureCategoryAdmin)\nadmin.site.register(Partner, PartnerAdmin)\n\n\nclass CategoryAdmin(admin.ModelAdmin):\n list_display = ('name',)\n\n\nclass CiteAdmin(admin.ModelAdmin):\n list_display = ('text', 'source', 'category', 'date_added')\n list_filter = ('category__name',)\n\nadmin.site.register(CiteCategory, CategoryAdmin)\nadmin.site.register(Cite, CiteAdmin)\n\n","sub_path":"lifeapp/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":1754,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"500438523","text":"# coding=utf8\n# author = 'AaronChou'\nfrom __future__ import division\nfrom numpy import *\nimport matplotlib.pyplot as plt\nimport time\nimport MySQLdb\nimport sys\n\nreload(sys)\nsys.setdefaultencoding('utf-8')\n\n\ndef mysqlQuery(sql):\n \"\"\"\n\n :rtype : MySQL查询\n \"\"\"\n conn = MySQLdb.connect(host='192.168.2.249', user='root', passwd='admin', db='o2o')\n cursor = conn.cursor(MySQLdb.cursors.DictCursor)\n cursor.execute(sql)\n rows = cursor.fetchall()\n cursor.close()\n conn.close()\n return rows\n\n\ndef get_test():\n sql = \"select * from offline_test\"\n rows = mysqlQuery(sql)\n return rows\n\ndef get_user_rate():\n sql = \"select * from off_u_rate order by user_id\"\n rows = mysqlQuery(sql)\n maps = {}\n for row in rows:\n if maps.has_key(row[\"user_id\"]):\n maps[row[\"user_id\"]][row[\"tag\"]] += row[\"num\"]\n else:\n maps[row[\"user_id\"]] = [0, 0, 0]\n maps[row[\"user_id\"]][row[\"tag\"]] += row[\"num\"]\n\n user_rate = {}\n for ma in maps:\n m = maps[ma]\n sum = m[0]+m[1]\n rate = 0.5\n if sum != 0:\n rate = round(m[1] / sum,5)\n user_rate[ma] = rate\n return user_rate\n\ndef main():\n out = open(\"E:\\\\Datamining\\\\tianchi\\\\o2o\\\\submit.csv\", \"w\")\n user_rate = get_user_rate()\n test_rows = get_test()\n for row in test_rows:\n if user_rate.has_key(row[\"User_id\"]):\n out.write(str(row[\"User_id\"])+\",\"+str(row[\"Coupon_id\"])+\",\"+str(row[\"Date_received\"])+\",\"+ str(user_rate[row[\"User_id\"]])+\"\\n\")\n else:\n out.write(str(row[\"User_id\"])+\",\"+str(row[\"Coupon_id\"])+\",\"+str(row[\"Date_received\"])+\",\"+ str(0.5)+\"\\n\")\n out.close()\n\nmain()","sub_path":"competition/o2o/submit_test.py","file_name":"submit_test.py","file_ext":"py","file_size_in_byte":1688,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"323335861","text":"import os\nimport torch\nfrom fairseq.models.bart import BARTModel\nimport csv\nimport json\nimport argparse\n\n\nclass AF_Data_Generation():\n\n\tdef __init__(self, model_path):\n\t\t\n\t\tself.bart = BARTModel.from_pretrained(\n\t\t model_path,\n\t\t checkpoint_file='checkpoint_best.pt',\n\t\t data_name_or_path='rocstories_kw_story-bin'\n\t\t)\n\t\tself.bart.cuda()\n\t\tself.bart.eval()\n\t\tself.bart.half()\n\n\n\tdef generate_implausible_stories(self, args, gt_stories, num_sents_gt_stories, file_type, ind_file):\n\t\t#This function takes the manipulated plots and leverages the conditional LM (finetuned BART) to generate implausible stories\n\t\tfr = open(args.man_plts, 'r')\n\t\tmanipulated_plots = fr.readlines()\n\t\ttsv_file = open(os.path.join(args.data_path, 'ManPlts/{}_pos_neg_stories_{}.tsv'.format(file_type, ind_file)), 'w')\n\t\ttsv_writer = csv.writer(tsv_file, delimiter='\\t', lineterminator='\\n')\n\n\t\tcount = 1\n\t\tbsz = args.batch_size\n\t\tconv_lines = []\n\t\tgt_stories_lines = []\n\t\tnum_sents_gt_lines = []\n\t\tindj = 0\n\t\tfor ind_line, plots in enumerate(manipulated_plots[:100]):\n\t\t\tplots = plots.strip()\n\t\t\tconv_lines.append(plots)\n\t\t\tgt_stories_lines.append(gt_stories[ind_line])\n\t\t\tnum_sents_gt_lines.append(num_sents_gt_stories[ind_line])\n\t\t\tif count % bsz == 0:\n\t\t\t\twith torch.no_grad():\n\t\t\t\t\thyps = self.bart.sample(conv_lines, sampling =True, lenpen=2.0, max_len_b=args.max_len_b, min_len=args.min_len, sampling_topk=args.sampling_topk, temperature=args.temperature, beam=args.beam)\n\t\t\t\tfor ind, hypothesis in enumerate(hyps):\n\t\t\t\t\thypothesis = hypothesis.strip().split('
')[:num_sents_gt_lines[ind]]\n\t\t\t\t\thypothesis = ''.join(hypothesis)\n\t\t\t\t\thypothesis = hypothesis.replace(' ', ' ')\n\t\t\t\t\ttsv_writer.writerow([indj, '1', indj, gt_stories_lines[ind]])\n\t\t\t\t\tindj+=1\n\t\t\t\t\ttsv_writer.writerow([indj, '0', indj, hypothesis])\n\t\t\t\t\tindj+=1\t\n\t\t\t\tnum_sents_gt_lines=[]\n\t\t\t\tgt_stories_lines = []\n\t\t\t\tconv_lines = []\n\t\t\tcount +=1\n\t\tif conv_lines != []:\n\t\t\thyps = self.bart.sample(conv_lines, sampling=True, lenpen=2.0, max_len_b=args.max_len_b, min_len=args.min_len, sampling_topk=args.sampling_topk, temperature=args.temperature, beam=args.beam)\n\t\t\tfor ind, hypothesis in enumerate(hyps):\n\t\t\t\thypothesis = hypothesis.strip().split('')[:num_sents_gt_lines[ind]]\n\t\t\t\thypothesis = ''.join(hypothesis)\n\t\t\t\thypothesis = hypothesis.replace(' ', ' ')\n\t\t\t\ttsv_writer.writerow([indj, '1', indj, gt_stories_lines[ind]])\n\t\t\t\tindj+=1\n\t\t\t\ttsv_writer.writerow([indj, '0', indj, hypothesis])\n\t\t\t\tindj+=1\n\n\n\tdef create_json_AF_input(self, args):\n\t\t#This function takes \"num_negative_samples\" tsv files that includes stories with different negative samples and creates a json file as an input for AF \n\t\tfor mode in ['train', 'valid', 'test']:\n\t\t\tfor ind in range(args.num_negative_samples):\n\t\t\t\tglobals()['fr_{}_{}'.format(mode,ind)] = open(os.path.join(args.data_path, 'ManPlts/{}_pos_neg_stories_{}.tsv'.format(mode, ind)), 'r')\n\t\t\t\tglobals()['lines_{}_{}'.format(mode,ind)] = globals()['fr_{}_{}'.format(mode,ind)].readlines()\n\t\tfw = open(os.path.join(args.data_path, args.json_file), 'w')\n\n\t\toutput = []\n\t\tfor mode in ['train', 'valid', 'test']:\n\t\t\tind=0\n\t\t\tfor i in range(0, len(globals()['lines_{}_{}'.format(mode,ind)]), 2):\n\t\t\t\toutput_text ={}\n\t\t\t\tgt_story = globals()['lines_{}_{}'.format(mode,ind)][i].split('\\t')[3].split('\\n')[0].strip()\n\t\t\t\tgens=[]\n\t\t\t\tfor ind in range(args.num_negative_samples):\n\t\t\t\t\tglobals()['gen_story{}'.format(ind)]=' '.join(globals()['lines_{}_{}'.format(mode,ind)][i+1].split('\\t')[3].split('\\n')[0].strip().split('')[3:]).replace(' ', ' ').strip()\n\t\t\t\t\tgens.append(globals()['gen_story{}'.format(ind)])\n\t\t\t\tprmpt = ' . '.join(gt_story.split(' . ')[:3]).strip()\n\t\t\t\tif prmpt[-1] not in ['?', '.', '!']:\n\t\t\t\t\tprmpt = prmpt + ' .'\n\t\t\t\tgt_story = ' . '.join(gt_story.split(' . ')[3:])\n\t\t\t\toutput_text[\"ctx\"] = prmpt\n\t\t\t\toutput_text[\"gt_detok\"] = gt_story\n\t\t\t\toutput_text[\"gens\"] = gens \n\t\t\t\toutput.append(output_text)\n\t\t\t\tind=0\n\t\t\t\t\t\t\t\n\t\tfw.write('\\n'.join(json.dumps(i, ensure_ascii=False) for i in output))\n\n\n\nif __name__==\"__main__\":\n\n\tparser = argparse.ArgumentParser()\n\tparser.add_argument(\"--bart_model_path\", type=str, default=\"Models/Ft_BART_Story_Generator/ROC/\", help=\"model path including finetuned BART model as the conditional LM\")\n\tparser.add_argument(\"--data_path\", type=str, default='Data/ROC/ROC_Eval', help='data path for ROC_Eval data')\n\tparser.add_argument(\"--json_file\", type=str, default='ROC_AF_input.json', help='json input files')\n\tparser.add_argument(\"--num_negative_samples\", type=int, default=6, help=\"number of negative (implausible) samples to generate for each plausible story\")\n\tparser.add_argument(\"--batch_size\", type=int, default=32, help='batch size to generate samples')\n\tparser.add_argument(\"--max_len_b\", type=int, default=200, help='max length of stories')\n\tparser.add_argument(\"--min_len\", type=int, default=10, help='min length of stories')\n\tparser.add_argument(\"--sampling_topk\", type=int, default=50, help='topk sampling')\n\tparser.add_argument(\"--temperature\", type=float, default=0.8, help='temperature value')\n\tparser.add_argument(\"--beam\", type=float, default=4, help='beam size')\n\n\t\n\targs = parser.parse_args()\n\taf = AF_Data_Generation(args.bart_model_path)\n\t\n\tfor file_type in ['train', 'valid', 'test']:\n\t\t#file including ground truth stories\n\t\targs.gt_stories=args.data_path+'/Rocstories_{}'.format(file_type)\n\t\t#file including manipulated plots\n\t\targs.man_plts=args.data_path+'/ManPlts/Rocstories_{}_manipulated_plts'.format(file_type)\n\t\tfr_gt = open(args.gt_stories, 'r')\n\t\tlines_gt_stories = fr_gt.readlines()\n\t\tgt_stories=[]\n\t\tnum_sents_gt_stories=[]\n\t\tfor ind_line, story in enumerate(lines_gt_stories):\n\t\t\tgt_story = lines_gt_stories[ind_line].split('@')[0].split('')[1].strip().split('')[1:]\n\t\t\tgt_story = [g.strip() for g in gt_story]\n\t\t\tnum_sents_gt_stories.append(len(gt_story))\n\t\t\tgt_story = ' '.join(gt_story).strip()\n\t\t\tgt_story = gt_story.replace(' ', ' ')\n\t\t\tgt_stories.append(gt_story)\n\t\n\t\t#Generate args.num_negative_samples different tsv files each including gt_stories as positive and generated negative stories as implausible ones\n\t\tfor ind in range(args.num_negative_samples):\n\t\t\taf.generate_implausible_stories(args, gt_stories, num_sents_gt_stories, file_type, ind)\n\n\taf.create_json_AF_input(args)\n\n","sub_path":"make_AF_input_ROC.py","file_name":"make_AF_input_ROC.py","file_ext":"py","file_size_in_byte":6299,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"445339006","text":"'''\nWrite a function sum_up_diagonals() which accepts an NxN list of lists and sums\nthe two main diagonals in the array: the one from the upper left to lower right,\nand the one from the upper right to the lower left.\n'''\n\ndef sum_up_diagonals(l):\n # left_counter starts at 0 and goes up to the max len of the list.\n # right_coutner starts at the max len of the list and goes to 0.\n # This is repeated for each row.\n # The values of each diagonal are appended to their respective lists.\n left_counter = 0\n right_counter = len(l) - 1\n left_to_right = []\n right_to_left = []\n\n for x in range(len(l)):\n left_to_right.append(l[x][left_counter])\n right_to_left.append(l[x][right_counter])\n left_counter += 1\n right_counter -= 1\n\n return sum(left_to_right + right_to_left)\n\n\n\nlist1 = [\n [ 1, 2 ],\n [ 3, 4 ]\n]\n\nlist2 = [\n [ 1, 2, 3 ],\n [ 4, 5, 6 ],\n [ 7, 8, 9 ]\n]\n\nlist3 = [\n [ 4, 1, 0 ],\n [ -1, -1, 0],\n [ 0, 0, 9,]\n]\n\nlist4 = [\n [ 1, 2, 3, 4],\n [ 5, 6, 7, 8 ],\n [ 9, 10, 11, 12 ],\n [ 13, 14, 15, 16 ]\n]\n\nprint(sum_up_diagonals(list3))","sub_path":"2019_coding/sum_up_diagonals.py","file_name":"sum_up_diagonals.py","file_ext":"py","file_size_in_byte":1090,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"438392642","text":"from sklearn.metrics import roc_curve, auc\nfrom MiST import globaldef as gl\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy import interp\nfrom itertools import cycle\nfrom sklearn import svm\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.multiclass import OneVsRestClassifier\nfrom sklearn.preprocessing import label_binarize\n\ndef roc_curves_multi(y_test,y_score,n_classes):\n\n plot_labels = gl.arg['multi_train_plot_labels']\n opath = gl.arg['mva_path'] + '/'\n\n\n # Compute ROC curve and ROC area for each class\n fpr = dict()\n tpr = dict()\n roc_auc = dict()\n for i in range(n_classes):\n fpr[i], tpr[i], _ = roc_curve(y_test[:, i], y_score[:, i])\n roc_auc[i] = auc(fpr[i], tpr[i])\n\n # Compute micro-average ROC curve and ROC area\n fpr[\"micro\"], tpr[\"micro\"], _ = roc_curve(y_test.ravel(), y_score.ravel())\n roc_auc[\"micro\"] = auc(fpr[\"micro\"], tpr[\"micro\"])\n\n\n lw = 1\n # Compute macro-average ROC curve and ROC area\n\n # First aggregate all false positive rates\n all_fpr = np.unique(np.concatenate([fpr[i] for i in range(n_classes)]))\n \n # Then interpolate all ROC curves at this points\n mean_tpr = np.zeros_like(all_fpr)\n for i in range(n_classes):\n mean_tpr += interp(all_fpr, fpr[i], tpr[i])\n \n # Finally average it and compute AUC\n mean_tpr /= n_classes\n \n fpr[\"macro\"] = all_fpr\n tpr[\"macro\"] = mean_tpr\n roc_auc[\"macro\"] = auc(fpr[\"macro\"], tpr[\"macro\"])\n \n # Plot all ROC curves\n plt.figure()\n plt.plot(fpr[\"micro\"], tpr[\"micro\"],\n label='micro-average ROC curve (area = {0:0.2f})'\n ''.format(roc_auc[\"micro\"]),\n color='deeppink', linestyle=':', linewidth=1)\n \n plt.plot(fpr[\"macro\"], tpr[\"macro\"],\n label='macro-average ROC curve (area = {0:0.2f})'\n ''.format(roc_auc[\"macro\"]),\n color='navy', linestyle=':', linewidth=1)\n \n colors = cycle(['aqua', 'orangered', 'mediumorchid','gold','green','red','magenta','blue','brown'])\n for i, color in zip(range(n_classes), colors):\n plt.plot(fpr[i], tpr[i], color=color, lw=lw,\n label='ROC curve of '+ plot_labels[i] +' (area = {1:0.2f})'\n ''.format(i, roc_auc[i]))\n \n plt.plot([0, 1], [0, 1], 'k--', lw=lw)\n plt.xlim([0.0, 1.0])\n plt.ylim([0.0, 1.05])\n plt.xlabel('False Positive Rate')\n plt.ylabel('True Positive Rate')\n plt.title('Receiver operating characteristic for multi-class')\n plt.legend(loc=\"lower right\",fontsize='xx-small')\n plt.show()\n plt.savefig(opath + '/ROC' +'.pdf')\n","sub_path":"MiST/ROC_multi.py","file_name":"ROC_multi.py","file_ext":"py","file_size_in_byte":2638,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"41410821","text":"#%%\nimport numpy as np\nimport pandas as pd\nimport matplotlib\n#matplotlib.use ('Qt5Agg')\nimport matplotlib.pyplot as plt\nmatplotlib.rcParams['text.usetex'] = True\nimport matplotlib.collections as mcol\nfrom matplotlib.legend_handler import HandlerLineCollection, HandlerTuple\nfrom matplotlib.lines import Line2D\nfrom matplotlib.ticker import ScalarFormatter\nfrom matplotlib.markers import TICKLEFT, TICKRIGHT, TICKUP, TICKDOWN, CARETLEFT, CARETRIGHT, CARETUP, CARETDOWN\nfrom scipy import signal, interpolate, optimize\nfrom collections import OrderedDict\n\n#-------def---******************************************************************\ndef readcsv(datafilename):\n #csvの読み込みを行う関数\n df=pd.read_csv(datafilename,header=None) #datafilenameは〜.csv\n dft = np.array(df).T #読み込みしたcsvを横方向に転置\n dftr = dft[:,1:] #最初の文字列の行は取っ払う.文字列行ない場合はこの行をコメントアウト\n dftru = np.array(dftr,dtype=np.float64) #読み込んだ時点でstrだから,floatに直す!!これはめっちゃ重要!!\n return dftru #配列で返してるよ\n\ndef loadtxt(datafilename,skip_rows,delim):\n #csvの読み込みを行う関数,ロードしたいdatafilename(拡張子前)とskipしたい行数を右側に入れてね\n a = \"./\" + datafilename + \".txt\" \n df = np.loadtxt(a,skiprows = skip_rows, delimiter = delim )\n dftr = df.T\n return dftr\n\ndef Load_HeNe(datafilename):\n df = loadtxt(datafilename,5,\",\")\n fringe=df[1]\n #smoothing----------------------------------------------#\n x_org = np.linspace(0,(len(fringe)-1),len(fringe))\n x_aft = np.linspace(0,(len(fringe)-1),100000)\n fringe_interp = interpolate_akm(fringe,x_org,x_aft)\n fringe_ret = interpolate_akm(fringe_interp,x_aft,x_org)\n #-------------------------------------------------------#\n #physical constants-------------------------------------#\n HeNe_hacho = 6328e-10\n hikari = 2.99792458e8\n #-------------------------------------------------------#\n #fringe analysis----------------------------------------#\n fringe = fringe_ret\n wn = np.zeros(50000, dtype = float) \n k = 0\n for i in range(0,(len(fringe)-1)):\n if (fringe[i]>=fringe[i+1] and fringe[i]*fringe[i+1]<=0.0):\n wn[k] = i\n k = k + 1\n wnc = np.trim_zeros(wn)\n #-------------------------------------------------------#\n #fringe interpolate-------------------------------------#\n x = np.linspace(0,(len(wnc)-1),len(wnc))\n x_interp = np.linspace(0,len(fringe),10000)\n wncx = HeNe_hacho/hikari * x * 1e12\n fringe_pos = interpolate_akm(wncx,wnc,x_interp)\n #-------------------------------------------------------#\n return fringe_pos\n\ndef interpolate_akm(graph,point_before,point_after):\n #グラフの点数を補間する.この関数では前データ点数情報(ex.delay(10000))からほしい後データ点数(ex.delayFT(8192))情報を入力すれば良い\n f = interpolate.Akima1DInterpolator(point_before, graph)\n y = f(point_after)\n return y\n\ndef delay_recalibration(delay,points):\n #fringeから得られたdelayは点数間隔が一定でないから,このままでは信号をフーリエ変換ができない.\n #したがって,点数間隔が一定なdelayを作って信号を更正する必要がある..\n #(例えば)10000の間隔が一定でないデータを線形な8192のdelayに更正する関数である.\n points = int(points) #pointsはほしいデータ点数これをintにしとく\n x = np.linspace(0,(points - 1),points) #ほしいデータ点数個の整数をずらっと並べる\n length = len(delay) #元delayの点数\n length = int(length) #intにしとく\n delay_r = x * (delay[(length - 1)] - delay[0])/points + delay[0] #一次関数にしちゃうのだぜ\n return delay_r\n\ndef frqaxis_maker(delay,points):\n #周波数軸メーカー.元delayを入れて,補間したsignalの点数の半分の値をpointsにすれば良い.\n #これも点数間隔を一定にする家庭も含んでいる.\n #なぜなら点数間隔を一定にした信号をフーリエ変換したら,点数間隔が一定なFTスペクトルができるはずだから横軸も点数間隔が一緒でなくてはならない.\n points = int(points)\n x = np.linspace(0,(points - 1),points)\n length = len(delay)\n length = int(length)\n frq = x / (delay[(length - 1)] - delay[0]) * (2*points - 1)/(2*points)\n return frq\n\ndef FFT_abs_amp(Interpsig):\n #FFTの各要素複素数の大きさを取ったスペクトルを表したもの.\n #要素数は半分になるよ.\n #frqと要素数合う(はずだ)よ.\n #これは2乗が取れてるバージョン.igorは magnitude squared\n N = len(Interpsig)\n FFTsig = np.fft.fft(Interpsig)\n FFTsig_abs = np.abs(FFTsig)\n FFTsig_abs_amp = FFTsig_abs/N *2\n FFTsig_abs_amp[0] = FFTsig_abs_amp[0]/2\n FFTsig_abs_amp_halfpoints = FFTsig_abs_amp[:int(N/2)]\n return FFTsig_abs_amp_halfpoints\n\ndef FFT_abs_display(FFTsignal,frqaxis):\n FFTsignal_len = len(FFTsignal)\n frqaxis_len = len(frqaxis)\n ymax = FFTsignal.max()\n if FFTsignal_len == frqaxis_len :\n plt.plot(frqaxis,FFTsignal)\n plt.xlim(0,8.5)\n plt.ylim(0,ymax*1.1)\n plt.legend()\n plt.show() \n else:\n print('both of element numbers are not corresponding!!')\n\ndef FFT_abs_amp_series(row_sig,row_delay):\n if len(row_sig) == 10000:\n if len(row_delay) == 10000:\n delayFT = delay_recalibration(row_delay,8192)\n frq = frqaxis_maker(row_delay,4096)\n Interpsig = interpolate_akm(row_sig,row_delay,delayFT) * 1e6 #1e6倍にしてるので,縦軸に(10^{-6})入れてね.\n Interpsig_FFT_abs_amp = FFT_abs_amp(Interpsig) #1e6倍にしてるので,縦軸に(10^{-6})入れてね.\n else:\n print('Number of delay array is not 10000.')\n else:\n print('Number of signal array is not 10000.')\n \n return Interpsig, Interpsig_FFT_abs_amp, delayFT, frq\n\ndef index_seek(value,ary):\n ary_length = len(ary)\n s = ary[0]\n ind = 0\n for i in range(1,ary_length):\n if (np.abs(s - value)) >= (np.abs(ary[i] - value)):\n s = ary[i]\n ind = i\n return ind\n\ndef peak_seek(frq,sig,peak_frq):\n peakfrq_len = len(peak_frq)\n peak_inf = np.zeros((peakfrq_len,2))\n index_shift = index_seek(0.12,frq)\n for i in range(peakfrq_len):\n index_frq = index_seek(peak_frq[i],frq)\n start = np.abs(index_frq - index_shift)\n end = np.abs(index_frq + index_shift)\n peak_max = 0.0\n peak_pos = 0.0\n\n for j in range(start,end):\n if peak_max < sig[j] :\n peak_max = sig[j]\n peak_pos = frq[j]\n\n peak_inf[i][0] = peak_pos\n peak_inf[i][1] = peak_max\n \n return peak_inf\n\ndef peak_seek_simple(frq,sig,peak_frq):\n index_shift = index_seek(0.12,frq)\n index_frq = index_seek(peak_frq,frq)\n start = np.abs(index_frq - index_shift) \n end = np.abs(index_frq + index_shift)\n peak_max = 0.0\n peak_pos = 0.0\n\n for j in range(start,end):\n if peak_max < sig[j] :\n peak_max = sig[j]\n peak_pos = frq[j]\n\n return peak_max, peak_pos\n \ndef window_function(position,width,delayFT):\n Anorm = 1.0/(np.sqrt(np.pi * 2.0 * width))\n y_win = Anorm * np.exp(-((delayFT - position)**2.0/(width)**(2.0)))\n return y_win\n\ndef STFT_origin(Interpsig,delayFT,window_width,start,end):\n start_index = index_seek(start,delayFT)\n end_index = index_seek(end,delayFT)\n total_index = (end_index - start_index) + 1\n data_len = int(len(delayFT)/2)\n y_fftabs = np.zeros((total_index,data_len),dtype = float)\n j = 0\n\n for i in range(start_index,end_index):\n y_win = window_function(delayFT[i],window_width,delayFT)\n y_conv = Interpsig * y_win\n y_fftabs[j] = FFT_abs_amp(y_conv)\n j += 1 \n\n return y_fftabs, start_index, end_index\n\ndef STFT_nrml(Interpsig,delayFT,window_width,start,end):\n start_index = index_seek(start,delayFT)\n end_index = index_seek(end,delayFT)\n total_index = (end_index - start_index) + 1\n data_len = int(len(delayFT)/2)\n y_fftabs = np.zeros((total_index,data_len),dtype = float)\n j = 0\n\n for i in range(start_index,end_index):\n y_win = window_function(delayFT[i],window_width,delayFT)\n y_conv = Interpsig * y_win\n y_fftabs[j] = FFT_abs_amp(y_conv)\n j += 1 \n\n y_fftabs_nrml = y_fftabs/y_fftabs.max()\n return y_fftabs_nrml, start_index, end_index\n\ndef erf_modoki(x,pos,width):\n return 1.0/(1.0 + np.exp(-(x-pos)/width)) \n\ndef kink(x,pos,width,intensity):\n return 4.0 * intensity*erf_modoki(x,pos,width) * (- erf_modoki(x,pos,width) + 1)\n#-------def---******************************************************************\n\n#%%\ndelay = Load_HeNe(\"C3fringe00001\")\nplt.plot(delay)\n\n\n#%%\n","sub_path":"Load_HeNe.py","file_name":"Load_HeNe.py","file_ext":"py","file_size_in_byte":9048,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"461151027","text":"import sys\nimport string\nimport os\n\ndef checkLast4(label):\n if len(label) < 4:\n return False\n else:\n if label[-4:] == 'stem' or label[-4:] == 'form':\n return True\n else:\n return False\n\ndef generate_tuple(line, transitions, states, n):\n splitting = line.split()\n inState = splitting[0][1:]\n outState = splitting[1][1:]\n inSymbol = splitting[2][0:len(splitting[2])-2]\n\n if inState in states:\n inState = states[inState]\n else:\n states[inState] = 'q'+str(n)\n n = n + 1\n inState = states[inState]\n\n if outState in states:\n outState = states[outState]\n else:\n states[outState] = 'q'+str(n)\n n = n + 1\n outState = states[outState]\n if (inState, inSymbol) in transitions:\n transitions[(inState, inSymbol)].append(outState)\n else:\n tmp = []\n tmp.append(outState)\n transitions[(inState, inSymbol)] = tmp\n return (inState, inSymbol, outState, n)\n\nif __name__ == \"__main__\":\n input_lex = sys.argv[1]\n input_morph = sys.argv[2]\n output_file = sys.argv[3]\n startStateMorph = None\n endState = None\n startState = None\n transitions = {}\n labelList = []\n wordList = []\n catList = []\n wordCat = {}\n wordEndState = {}\n oldState = {}\n startCat = {}\n stateList = []\n with open(input_lex,'r') as lex:\n wordState = 0\n for line in lex:\n lexSplit = line.split()\n if len(lexSplit) == 0:\n continue\n wordList.append(lexSplit[0])\n wordEndState[lexSplit[0]] = wordState + len(lexSplit[0])\n wordState += len(lexSplit[0])\n wordCat[lexSplit[0]] = lexSplit[1]\n if lexSplit[1] not in catList:\n catList.append(lexSplit[1])\n\n with open(input_morph,'r') as morph:\n i = 0\n n = 0\n for line in morph:\n if len(line) == 1 and line[0] == '\\n':\n i += 1\n continue\n if i == 0:\n endState = line[0:len(line)-1]\n else:\n tuple = generate_tuple(line,transitions,oldState,n)\n if i == 1:\n startState = tuple[0]\n if tuple[0] not in stateList:\n stateList.append(tuple[0])\n if tuple[2] not in stateList:\n stateList.append(tuple[2])\n if tuple[1] in catList:\n if tuple[1] in startCat:\n startCat[tuple[1]].append(tuple[2])\n else:\n tmp = []\n tmp.append(tuple[2])\n startCat[tuple[1]] = tmp\n n = tuple[3]\n i += 1\n endState = oldState[endState]\n fsa = open('fsa1','w')\n fsa.write(startState+'\\n')\n state = 1\n for word in wordList:\n i = 0\n j = 0\n for i in range(0, len(word)):\n if i == 0:\n if len(word) != 1:\n fsa.write('(w0 (w'+str(state)+' \\\"'+str(word[i])+'\\\" *e*))\\n')\n if len(word) == 1:\n fsa.write('(w0 (w'+str(state)+' \\\"'+str(word[i])+'\\\" \\\"'+wordCat[word]+'\\\"))\\n')\n break\n else:\n if i == len(word)-1:\n fsa.write('(w'+str(state+j)+' (w'+str(state+j+1)+' \\\"'+str(word[i])+'\\\" \\\"'+wordCat[word]+'\\\"))\\n')\n else:\n fsa.write('(w'+str(state+j)+' (w'+str(state+j+1)+' \\\"'+str(word[i])+'\\\" *e*))\\n')\n j += 1\n i += 1\n state = state + len(word)\n fsa.write('(w'+str(state-1)+' ('+startState+' *e* *e*))\\n')\n fsa.write('(w'+str(state-1)+' (w0'+' *e*'+'))\\n')\n fsa.close()\n fsa2 = open('fsa2','w')\n fsa2.write(endState+'\\n')\n id = 0\n catList.append('*e*')\n for key in catList:\n for s in stateList:\n if (s,key) in transitions:\n for t in transitions[(s,key)]:\n if key == '*e*':\n fsa2.write('('+s+' ('+t+' *e*'+'))\\n')\n else:\n fsa2.write('('+s+' ('+t+' \\\"'+key+'\\\"))\\n')\n fsa2.close() \n os.popen(\"carmel fsa1 fsa2 > \"+output_file) \n '''\n if (len(suffixLabel[key]) == 1):\n fsa.write('('+s+' ('+t+' \\\"'+suffixLabel[key]+'\\\"))\\n')\n else:\n i = 0\n for l in suffixLabel[key]:\n if i == 0:\n fsa.write('('+s+' (m'+str(id)+' \\\"'+suffixLabel[key][0]+'\\\"))\\n')\n id += 1\n if i == 1:\n fsa.write('(m'+str(id-1)+' (m'+str(id)+' \\\"'+suffixLabel[key][i]+'\\\"))\\n')\n id += 1\n if i != 0 and i != 1:\n fsa.write('(m'+str(id-1)+' (m'+str(id)+' \\\"'+suffixLabel[key][i]+'\\\"))\\n')\n id += 1\n if i == len(suffixLabel[key])-1:\n fsa.write('(m'+str(id-1)+' ('+endState+' '+'*e*'+'))\\n')\n i += 1\n '''\n","sub_path":"HW4/expand_fsm1.py","file_name":"expand_fsm1.py","file_ext":"py","file_size_in_byte":5318,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"631401547","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Apr 11 23:56:59 2021\n\n@author: POLAB\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport inspect\nfrom datetime import datetime\n\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Dropout, GRU\nfrom keras.optimizers import Adam\n\nfrom sklearn.preprocessing import StandardScaler\n\nclass NN():\n # def __init__(self):\n # pass\n \n def __init__(self, input_shape, output_size, layers=3, units=3, \n dropout=0.05, loss='mse', optimizer='adam'):\n self.verbose = False\n self.display = True\n \n model = Sequential()\n for i, u in zip(range(layers), np.linspace(units, 1, layers)):\n if i 0:\n vertex1 = self.verteces_queue.pop()\n\n self.distances[vertex1.index] = vertex1\n for data in self.connections[vertex1.index]:\n vertex2 = self.verteces[data[0]]\n weight = data[1]\n\n self.relax(vertex1, vertex2, weight)\n heapq.heapify(self.verteces_queue.queue)\n\n def relax(self, vertex1, vertex2, weight):\n if vertex2.distance > vertex1.distance + weight:\n vertex2.distance = vertex1.distance + weight\n vertex2.parent = vertex1\n\n def initialize_single_source(self):\n for i in range(len(self.table)):\n v = LowCostFlights.Vertex(i)\n if i == self.start:\n v.distance = 0\n self.verteces.append(v)\n self.verteces_queue.push(v, v.distance)\n\n\ndef make_connections(table, connections):\n for i in range(len(table)):\n for j in range(len(table[i])):\n if table[i][j] != 0:\n connections[i].append([j, table[i][j]])\n\n\ndef main():\n table = [[0, 9, 0, 3, 2, 0, 0, 0],\n [0, 0, 7, 2, 0, 0, 9, 0],\n [7, 0, 0, 0, 0, 7, 7, 0],\n [0, 2, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 5, 0],\n [0, 3, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 4, 0],\n ]\n connections = [[] for i in range(len(table))]\n make_connections(table, connections)\n queries = [\n [0, 5],\n [3, 6],\n [6, 4],\n [3, 2],\n [5, 4],\n [5, 3],\n [7, 6],\n [4, 5],\n [2, 6]]\n dijktra = [None for i in range(len(table))]\n for query in queries:\n start = query[0]\n end = query[1]\n if dijktra[start] is not None:\n l = dijktra[start]\n if l.distances[end].distance != LowCostFlights.max_val:\n print(l.distances[end].distance)\n else:\n print('NO WAY')\n else:\n l = LowCostFlights(table, start, connections)\n l.distances\n dijktra[start] = l\n if l.distances[end].distance != LowCostFlights.max_val:\n print(l.distances[end].distance)\n else:\n print('NO WAY')\n\nif __name__ == '__main__':\n main()\n","sub_path":"week6/1-Low-Cost-Flights/low_cost_flights.py","file_name":"low_cost_flights.py","file_ext":"py","file_size_in_byte":4116,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"4903886","text":"# Put Function Definitions here\n\n# Import numpy and pandas library\nimport pandas as pd\nimport numpy as np\n\n# Returns Function\n# Takes current and previous sample and finds price difference\ndef asset_return(asset_price):\n # Get current and previous prices from asset price\n c_price = asset_price[1:]\n p_price = asset_price[0:-1]\n \n # Calculate the return\n return np.divide(c_price,p_price)-1\n\n# Expected Return Function\n# Returns the expected return from the asset return\ndef expected_return(ar):\n # Get the size of the array\n n = np.float64(ar.shape[0])\n \n # Calculate the expected return\n return np.sum(np.multiply(ar,(1/n)))\n\n# Volatility Function\n# Returns the volatility of the asset from the asset price\ndef volatility(asset_price):\n # Find the asset_return\n ar = asset_return(asset_price)\n \n # Find the expected return with asset return squared\n E = expected_return(np.power(ar,2))\n \n # Find the expected return and square it\n u2 = np.power(expected_return(ar),2)\n \n # Calculate the volatility\n return E - u2\n\n# Sharpe Ratio\n# Returns the sharpe ratio for a given asset\ndef sharpe(asset_price, rf_price):\n u = expected_return(asset_return(asset_price))\n sigma = volatility(asset_price)\n rf = expected_return(asset_return(rf_price))\n \n return (u - rf)/sigma\n\n# Set parameters\nparam ='close_price'\nstart ='2010-01-01'\nend = '2016-01-01' \nfreq='daily'\n\n# Get Apple Price and plot\naapl_dcp = get_pricing(\n 'AAPL', \n fields = param,\n start_date = start,\n end_date = end,\n frequency= freq\n)\naapl_dcp.plot()\n\n# Get Starbucks Price and plot\nsbux_dcp = get_pricing(\n 'SBUX', \n fields = param,\n start_date = start,\n end_date = end,\n frequency= freq\n)\nsbux_dcp.plot()\n\n# Get Sanofi Price and plot\nsny_dcp = get_pricing(\n 'SNY', \n fields = param,\n start_date = start,\n end_date = end,\n frequency= freq\n)\nsny_dcp.plot()\n\n# Get S&P500 index fund price and plot\nspy_dcp = get_pricing(\n 'SPY', \n fields = param,\n start_date = start,\n end_date = end,\n frequency = freq\n)\nspy_dcp.plot()\n\n# Calculate Daily Return and plot\nr_aapl_dcp = asset_return(aapl_dcp)\nr_sbux_dcp = asset_return(sbux_dcp)\nr_sny_dcp = asset_return(sny_dcp)\nr_spy_dcp = asset_return(spy_dcp)\n\n# Calculate the Expected Return and Volatility of Asset\ner_aapl_dcp = expected_return(r_aapl_dcp)\nv_aapl_dcp = volatility(aapl_dcp)\nprint('AAPL:')\nprint('Expected Return: %f' % (er_aapl_dcp))\nprint('Volatility: %f' % (v_aapl_dcp))\n\nprint('')\n\n# Calculate the Expected Return and Volatility of Asset\ner_sbux_dcp = expected_return(r_sbux_dcp)\nv_sbux_dcp = volatility(sbux_dcp)\nprint('SBUX:')\nprint('Expected Return: %f' % (er_sbux_dcp))\nprint('Volatility: %f' % (v_sbux_dcp))\n\nprint('')\n\n# Calculate the Expected Return and Volatility of Asset\ner_sny_dcp = expected_return(r_sny_dcp)\nv_sny_dcp = volatility(sbux_dcp)\nprint('SNY:')\nprint('Expected Return: %f' % (er_sny_dcp))\nprint('Volatility: %f' % (v_sny_dcp))\n\nprint('')\n\n# Calculate the Expected Return and Volatility of S&P500 Index Fund\ner_spy_dcp = expected_return(r_spy_dcp)\nv_spy_dcp = volatility(spy_dcp)\nprint('SPY:')\nprint('Expected Return: %f' % (er_spy_dcp))\nprint('Volatility: %f' % (v_spy_dcp))\n\nprint('')\n\n# Calculate Sharpe Ratio\nprint('Sharpe Ratio (Apple): %f' % (sharpe(aapl_dcp,spy_dcp)))\nprint('Sharpe Ratio (Starbucks): %f' % (sharpe(sbux_dcp,spy_dcp)))\nprint('Sharpe Ratio (Sanofi): %f' % (sharpe(sny_dcp,spy_dcp)))\n\n# Set the time length (days) to hold and sell\ntime_length = 365\n\n# Set initial investement\nii = 1000000\n\n# Given time period and principal investment, project expected return for Apple\npi = ii\nlb_pi = pi\nub_pi = pi\nprint ('Apple')\nprint('Time Period: %d days' % time_length)\nprint('Principal Investment: $%.2f' % pi)\nfor i in range(time_length):\n pi = (1+er_aapl_dcp)*pi\n lb_pi = (1+er_aapl_dcp-v_aapl_dcp)*lb_pi\n ub_pi = (1+er_aapl_dcp+v_aapl_dcp)*ub_pi\n \nprint('Expected Return: $%.2f' % pi)\nprint('Net Return: $%.2f' % (pi-ii))\nprint('Expected Return (Lower Bound): $%.2f' % lb_pi)\nprint('Net Return (Lower Bound): $%.2f' % (lb_pi-ii))\nprint('Expected Return (Upper Bound): $%.2f' % ub_pi)\nprint('Net Return (Upper Bound): $%.2f' % (ub_pi-ii))\n\nprint('')\n\n# Given time period and principal investment, project expected return for Starbucks\npi = ii\nlb_pi = pi\nub_pi = pi\nprint ('Starbucks')\nprint('Time Period: %d days' % time_length)\nprint('Principal Investment: $%.2f' % pi)\nfor i in range(time_length):\n pi = (1+er_sbux_dcp)*pi\n lb_pi = (1+er_sbux_dcp-v_sbux_dcp)*lb_pi\n ub_pi = (1+er_sbux_dcp+v_sbux_dcp)*ub_pi\n \nprint('Expected Return: $%.2f' % pi)\nprint('Net Return: $%.2f' % (pi-ii))\nprint('Expected Return (Lower Bound): $%.2f' % lb_pi)\nprint('Net Return (Lower Bound): $%.2f' % (lb_pi-ii))\nprint('Expected Return (Upper Bound): $%.2f' % ub_pi)\nprint('Net Return (Upper Bound): $%.2f' % (ub_pi-ii))\n\nprint('')\n\n# Given time period and principal investment, project expected return for Sanofi\npi = ii\nlb_pi = pi\nub_pi = pi\nprint ('Sanofi')\nprint('Time Period: %d days' % time_length)\nprint('Principal Investment: $%.2f' % pi)\nfor i in range(time_length):\n pi = (1+er_sny_dcp)*pi\n lb_pi = (1+er_sny_dcp-v_sny_dcp)*lb_pi\n ub_pi = (1+er_sny_dcp+v_sny_dcp)*ub_pi\n \nprint('Expected Return: $%.2f' % pi)\nprint('Net Return: $%.2f' % (pi-ii))\nprint('Expected Return (Lower Bound): $%.2f' % lb_pi)\nprint('Net Return (Lower Bound): $%.2f' % (lb_pi-ii))\nprint('Expected Return (Upper Bound): $%.2f' % ub_pi)\nprint('Net Return (Upper Bound): $%.2f' % (ub_pi-ii))\n","sub_path":"notes.py","file_name":"notes.py","file_ext":"py","file_size_in_byte":5578,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"64406483","text":"from typing import List\n\nclass Solution:\n def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:\n def bt(res, cur, curSum, start):\n if curSum == target:\n res.append(cur)\n return\n \n if curSum > target:\n return\n \n for i in range(start, len(candidates)):\n bt(res, cur + [candidates[i]], curSum + candidates[i], i)\n \n res = []\n bt(res, [], 0, 0)\n return res","sub_path":"leetcode/39-Combination-Sum.py","file_name":"39-Combination-Sum.py","file_ext":"py","file_size_in_byte":530,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"482057919","text":"from django.shortcuts import render, redirect\r\nfrom django.http import HttpResponse,HttpResponseRedirect, JsonResponse\r\nfrom django.views.generic import CreateView, View, TemplateView\r\nfrom django.urls import reverse_lazy,reverse\r\nfrom django.dispatch import receiver\r\nfrom apps.events.models import *\r\nfrom apps.location.models import *\r\nfrom .models import Bill, DetailsBill\r\nfrom apps.tickets.models import Ticket\r\nfrom django.contrib.auth.models import User\r\nfrom django.db import connection \r\nfrom django.db.models import Count\r\nfrom django.views.decorators.csrf import csrf_exempt,csrf_protect \r\nfrom .forms import BillForm, AddTicketsForm, BuyTicketsLocationForm\r\nimport time\r\nimport json\r\nfrom django.contrib.auth.decorators import permission_required\r\nfrom apps.event_type.models import EventType\r\nfrom django.core.serializers.json import DjangoJSONEncoder\r\nfrom django.core import serializers\r\nfrom django.core.serializers import serialize\r\ndef index_sale(request):\r\n return render(request, 'sales/createSale.html')\r\n\r\nclass BillCreate(CreateView):\r\n\tmodel = Bill\r\n\ttemplate_name = 'sales/base.html'\r\n\tform_class = BillForm\r\n\ts_form_class = AddTicketsForm\r\n\tsuccess_url = reverse_lazy('sales:index')\r\n\r\n\tdef get_context_data(self, **kwargs):\r\n\t\tcontext = super(BillCreate, self).get_context_data(**kwargs)\r\n\t\tif 'form' not in context:\r\n\t\t\tcontext['form'] = self.form_class(self.request.GET)\r\n\t\tif 'form2' not in context:\r\n\t\t\tcontext['form2'] = self.s_form_class(self.request.GET)\r\n\t\treturn context\r\n\r\n\tdef post(self, request, *args, **kwargs):\r\n\t\tself.object = self.get_object\r\n\t\tform = self.form_class(request.POST)\r\n\t\tform2 = self.s_form_class(request.POST)\r\n\t\tif form.is_valid() and form2.is_valid():\r\n\t\t\tbill = form.save()\r\n\t\t\tticket = tickets.objects.get(pk=form2.id)\r\n\t\t\tticket.id_bill = bill\r\n\t\t\tticket.state = 'Vendido'\r\n\t\t\tticket.save()\r\n\t\t\treturn HttpResponseRedirect(self.get_success_url())\r\n\t\telse:\r\n\t\t\treturn self.render_to_response(self.get_context_data(form=form, form2=form2))\r\n\r\ndef listEvent(request):\r\n\t\tevent = Event.objects.filter(state=\"Activo\")\r\n\t\tcontext = {'events':event}\r\n\t\treturn render(request,'sales/viewsEvent.html',context)\r\n\r\n@permission_required('users.Vendedor' ,reverse_lazy('evento_listar_compras'))\r\ndef listEvent1(request):\r\n\t\tevent = Event.objects.filter(state=\"Activo\")\r\n\t\tcontext = {'events':event}\r\n\t\treturn render(request,'sales/saleEvent.html',context)\r\n\r\n@permission_required('users.Vendedor' ,reverse_lazy('evento_listar_compras'))\r\ndef viewSales(request):\t\r\n\treturn render(request, 'sales/viewSales.html')\r\n\r\ndef getDailySales(request):\r\n\tif request.is_ajax:\r\n\t\tif request.method == 'GET':\r\n\t\t\tuser = User.objects.get(id=request.user.id)\r\n\t\t\tdate = request.GET.get('dateO')\r\n\t\t\tbills = Bill.objects.all().filter(id_profile=request.user.id, date_bill=date)\r\n\t\t\tbills = [ bill_serializer(bill) for bill in bills]\r\n\t\t\treturn HttpResponse(json.dumps(bills,cls=DjangoJSONEncoder), content_type = \"application/json\")\r\n\r\ndef bill_serializer(bill):\r\n\treturn {'id': bill.id, 'metodo_pago': bill.payment_method, 'total': bill.total_bill}\r\n\r\ndef getIdBillLast():\r\n\tbill=Bill.objects.all().last()\r\n\tif bill == None:\r\n\t\treturn 1\r\n\telse:\r\n\t\treturn int(bill.id)+1\r\n\r\n@permission_required('users.Vendedor' ,reverse_lazy('evento_listar_compras'))\r\n@csrf_exempt\r\ndef createSale(request,id):\r\n\tuser=User.objects.get(id=request.user.id)\r\n\tuserFullName = user.first_name + \" \" + user.last_name\r\n\tbill_id = getIdBillLast()\r\n\thora = time.strftime(\"%c\")\r\n\tevent = Event.objects.get(id=id)\r\n\ttickets_avalibles=getListTicketsAvalibles(event)\r\n\tlist_events_type=getListTypeEvents()\r\n\tif request.is_ajax:\r\n\t\tif request.method == \"POST\":\r\n\t\t\tsale = eval(request.POST.get('post_venta_envio'))\r\n\t\t\tnewBill = Bill(total_bill= sale['total'], id_profile= user, payment_method= sale['metodo_pago'], type_bill='Venta') \r\n\t\t\tnewBill.save()\r\n\t\t\ttickets = sale['tickets']\r\n\t\t\tfor ticket in tickets:\r\n\t\t\t\taddTicketBill(ticket, newBill)\r\n\t\t\t\taddDetailsBill(ticket, newBill)\r\n\t\t\treturn HttpResponse(json.dumps({'status':'success'}), content_type=\"application/json\")\r\n\tcontext = {'event':event,'hora':hora,'avalibleTicket':tickets_avalibles, 'eventType':list_events_type, 'bill':bill_id , 'userFullName':userFullName}\r\n\treturn render(request,'sales/createSale.html',context)\r\n\r\n\r\ndef getListTypeEvents():\r\n\tallTypeEvents = EventType.objects.all()\r\n\treturn allTypeEvents\r\n\r\ndef getIdEventType(eventTypeName):\r\n\tidEventType = EventType.objects.values('id').filter(name=eventTypeName)\r\n\treturn idEventType\r\n\r\ndef getIdEventForName(eventName):\r\n\tidEvent = Event.objects.values('id').filter(name=eventName)\r\n\treturn idEvent\r\n\r\ndef getEventsForTypes(request):\r\n\teventTypeName = request.GET.get('select_buscar')\r\n\tidEventType = getIdEventType(eventTypeName)[0]\r\n\teventsForTypes = Event.objects.all().filter(event_type=str(idEventType['id']))\r\n\teventsForTypes = [ event_serializer(eventForType) for eventForType in eventsForTypes]\t\r\n\treturn HttpResponse(json.dumps(eventsForTypes,cls=DjangoJSONEncoder), content_type = \"application/json\")\r\n\r\ndef event_serializer(event):\r\n\treturn {'id':event.id, 'name':event.name, 'initial_date':event.initial_date, 'capacity':event.capacity}\r\n\r\ndef new_tickets_avalibles(tickets_avalibles):\r\n\treturn {'count':tickets_avalibles[0], 'name':tickets_avalibles[1], 'cost':tickets_avalibles[2], 'id':tickets_avalibles[3]}\r\n\r\ndef getNewEvent(request):\r\n\teventName = request.GET.get('get_event_selec')\r\n\tidEvent = getIdEventForName(eventName)[0]\r\n\tevent = event_serializer(Event.objects.get(id=str(idEvent['id'])))\r\n\ttickets_avalibles=getListTicketsAvalibles(Event.objects.get(id=str(idEvent['id'])))\r\n\ttickets_avalibles=[ new_tickets_avalibles(tickets_avalible) for tickets_avalible in tickets_avalibles ]\r\n\tcontexto = {'event':event,'avalibleTicket':tickets_avalibles}\t\r\n\treturn HttpResponse(json.dumps(contexto,cls=DjangoJSONEncoder), content_type = \"application/json\")\r\n\r\ndef addTicketBill(ticketIn, Bill):\r\n\tcontador = int(ticketIn['cant'])\r\n\tfor i in range(contador):\r\n\t\tticket = Ticket.objects.filter(location_id=ticketIn['id_location'], state__exact=\"Disponible\")[0]\r\n\t\tticket.id_bill = Bill\r\n\t\tticket.state = \"Vendido\"\r\n\t\tticket.save()\r\n\r\ndef addDetailsBill(ticketIn, Bill):\r\n\tdetailsBill = DetailsBill(id_location=getLocation(ticketIn['id_location']), eventName=ticketIn['event_name'], cant=ticketIn['cant'], subtotal=ticketIn['subtotal'])\r\n\tdetailsBill.id_bill = Bill\r\n\tdetailsBill.save()\r\n\r\n@permission_required('users.Vendedor' ,reverse_lazy('evento_listar_compras'))\r\ndef getBill(request):\r\n\tfullName = request.user.first_name + request.user.last_name\r\n\tidBill = request.GET.get('get_bill')\r\n\tbill = Bill.objects.get(id=idBill)\r\n\tdetailsBills = DetailsBill.objects.filter(id_bill=idBill)\r\n\tdetailsBills=[ detailsBill_serializer(detailsBill) for detailsBill in detailsBills ]\r\n\treturn HttpResponse(json.dumps({'id':bill.id, 'date':bill.date_bill, 'name':fullName, 'total':bill.total_bill,'detailsBills':detailsBills},cls=DjangoJSONEncoder), content_type = \"application/json\")\r\n\r\ndef detailsBill_serializer(detailsBill):\r\n\tcosto = (detailsBill.subtotal/detailsBill.cant)\r\n\treturn {'eventName': detailsBill.eventName, 'cant': detailsBill.cant, 'locationName': str(detailsBill.id_location), 'costo': costo, 'subtotal': detailsBill.subtotal}\r\n\r\ndef getLocationName(idLocation):\r\n\tname = Location.objects.values('name').filter(id=idLocation)\r\n\treturn name[0]['name']\r\n\r\ndef getLocation(idLocation):\r\n\tlocation = Location.objects.get(id=idLocation)\r\n\treturn location\r\n\r\ndef createShop(request,id):\r\n\thora = time.strftime(\"%c\")\r\n\tevent = Event.objects.get(id=id)\r\n\ttickets_avalibles=getListTicketsAvalibles(event)\r\n\tlist_events_type=getListTypeEvents()\r\n\tbill_id = 0\r\n\tbill=Bill.objects.all().last()\r\n\tif bill == None:\r\n\t\tbill_id=1\r\n\telse:\r\n\t\tbill_id=int(bill.id)+1\r\n\tcontext = {'event':event,'hora':hora,'avalibleTicket':tickets_avalibles, 'eventType':list_events_type,'bill':bill_id}\r\n\tif event.url == \"http://localhost:8000\":\r\n\t\tcontext = {'event':event,'hora':hora,'avalibleTicket':tickets_avalibles, 'eventType':list_events_type,'bill':bill_id}\r\n\t\treturn render(request,'sales/createShopping.html',context)\r\n\telse:\r\n\t\tcontext = {'event':event}\r\n\t\treturn render(request,'sales/eventRefer.html',context)\r\n\r\nclass GetDataAjaxView(TemplateView):\r\n\r\n\tdef get(self,request, *args, **kwargs):\r\n\t\tquantitys = json.loads(request.GET['jsonQuantitys'])\r\n\t\tubications = json.loads(request.GET['jsonUbications'])\r\n\t\tpago =request.GET['pago']\r\n\t\ttotal =request.GET['total']\r\n\t\tx=0\r\n\t\tbill=createBillAjax(request,pago,'Compra',total)\r\n\t\twhile x < int(len(ubications)): \r\n\t\t\tlocation=Location.objects.get(id=ubications[x])\r\n\t\t\taddShopping(location.id,quantitys[x],bill) \r\n\t\t\tx+=1\r\n\t\treturn JsonResponse({'status':'success'})\r\n\r\ndef addShopping(id_location,cantidad, Bill):\r\n\tcontador = int(cantidad)\r\n\tfor i in range(contador):\r\n\t\tticket = Ticket.objects.filter(location_id=id_location, state__exact=\"Disponible\")[0]\r\n\t\tticket.id_bill = Bill\r\n\t\tticket.state = \"Vendido\"\r\n\t\tticket.save()\r\n\r\ndef createBillAjax(request,payment_method,type_bill,total):\r\n\tcreate_bill(request)\r\n\tbill_id=Bill.objects.all().last()\r\n\tbill_id.payment_method=payment_method\r\n\tbill_id.type_bill=type_bill\r\n\tbill_id.total_bill=total\r\n\tbill_id.save()\r\n\treturn bill_id\r\n\r\ndef listShops(request):\r\n\tuser=User.objects.get(id=request.user.id)\r\n\tlistShops=getMyShops(user.id)\r\n\tcontext = {'listShops':listShops}\r\n\treturn render(request,'sales/myShops.html',context)\r\n\r\ndef getMyShops(user):\r\n\tcursor = connection.cursor()\r\n\tinstruction=\"SELECT count(*),sales_bill.id,sales_bill.total_bill,sales_bill.date_bill FROM events_event,tickets_ticket,sales_bill WHERE tickets_ticket.event_id=events_event.id AND tickets_ticket.id_bill_id=sales_bill.id AND sales_bill.type_bill='Compra' AND sales_bill.id_profile_id=\"+str(user)+\" GROUP BY sales_bill.id,sales_bill.total_bill,sales_bill.date_bill;\"\r\n\tprint(instruction)\r\n\tcursor.execute(instruction)\r\n\trows = cursor.fetchall()\r\n\tconnection.commit()\r\n\tconnection.close()\r\n\tprint(rows)\r\n\treturn rows\r\n\r\n\r\ndef getListTicketsAvalibles(event):\r\n cursor = connection.cursor()\r\n instruction = \"SELECT count(*),location_location.name,location_location.cost, location_location.id FROM tickets_ticket,location_location WHERE location_location.id=tickets_ticket.location_id AND state='Disponible' AND tickets_ticket.event_id=\"+str(event.id)+\" GROUP BY location_location.name,location_location.cost, location_location.id;\"\r\n cursor.execute(instruction)\r\n rows = cursor.fetchall()\r\n connection.commit()\r\n connection.close()\r\n return rows\r\n\r\n\r\ndef add_ticket_to_bill(bill,ticket):\r\n\tticket = Ticket.objects.get(id=ticket)\r\n\tticket.id_bill=bill\r\n\tticket.state='Vendido'\r\n\tticket.save()\r\n\r\n\r\ndef create_bill(request):\r\n\tuser=User.objects.get(id=request.user.id)\r\n\tprint(user.id)\r\n\tbill = Bill(id_profile=user)\r\n\tbill.save()\r\n\r\ndef calculate(ubications, event, quantity):\t\r\n\tif str(quantity) != '':\r\n\t\tticket = Ticket.objects.all().filter(event_id=event, ubication=ubications).first()\t\r\n\t\tquantityTickets = int(quantity)\r\n\t\tcost = ticket.cost * quantityTickets\r\n\r\ndef newSales(request):\r\n\treturn render(request,'sales/listEventsSale.html')","sub_path":"sporticket/apps/sales/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":11189,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"303714205","text":"#Alexander Little - alittle5@cnm.edu\r\n#duelists 1 / Single Combat\r\n#adds:\r\n# Class based to facilitate Graphical User Interface\r\n########Needed to restructure duel function to operate based on button pressed\r\n# Blood letting in semi-random increments\r\n# X Main Menu Structure\r\n# Points System\r\n# Draw is now considered a 'clash'\r\nimport random\r\n#import knights_game_simple\r\n#import wx\r\n#import GUI_base\r\n\r\n\r\n\r\nmatch = 1\r\nrnd = 1\r\n#score [0]=player score [1]=CPU score [2]= round\r\nscore = [0, 0, 1]\r\nhealth = [1, 1]\r\nwounds = [0, 0]\r\nblood = [0.0, 0.0] #1.0 = 1 gallon\r\nplay = \"y\"\r\nlongest = [0]\r\nattacks = ('Parry/Riposte', 'Swing', 'Lunge')\r\ntitle = \" -=Welcome to The Arena=-\"\r\nrules = \"===========================================================\"\r\nrules += \" \\nRULES: 1)\" + str(attacks[2]) + \" Beats \" + str(attacks[1]) #+ \", but \" + attacks[2] + \" is beaten by \" + attacks[0]\r\nrules += \" \\n 2)\" + str(attacks[0]) + \" Beats \" + str(attacks[2]) \r\nrules += \" \\n 3)\" + attacks[1] + \" Beats \" + str(attacks[0]) \r\nrules += \" \\n 4) When you and your enemy strike with an\"\r\nrules += \" \\n identical attack, it is known as a clash!\"\r\nrules += \" \\n You will gain +1 health on each clash! (max 3)\"\r\nrules += \"\\nSee how many duels you can win before you fall. good luck!\"\r\nrules += \"\\n===========================================================\"\r\ncSt = 0\r\nlSt = 0 #change to load in high score\r\n#anim = knights_game_simple\r\nclass game():\r\n #clean up match repeats\r\n match = 0\r\n def __init__(self, match = 0, rnd = 1, score = [0, 0, 1],\r\n health = [1, 1],\r\n wounds = [0, 0],\r\n blood = [0.0, 0.0], \r\n play = \"y\",\r\n longest = [0],\r\n attacks = ('Block', 'Swing', 'Stab'),\r\n title = \"Welcome to The Arena.\",\r\n rules = \"RULES: \" + attacks[2] + \" BEATS \" + attacks[1] + \" BEATS \" + attacks[0] + \" BEATS \" + attacks[2],\r\n cSt = 0, lSt = 0\r\n ):\r\n self.match = match\r\n self.rnd = rnd\r\n #score [0]=player score [1]=CPU score [2]=draws/round # \r\n self.score = score\r\n self.health = health\r\n self.wounds = wounds\r\n self.blood = blood #1.0 = 1 gallon\r\n self.play = play\r\n self.longest = longest\r\n self.attacks = attacks\r\n self.title = title\r\n self.rules = rules\r\n self.cSt = cSt\r\n self.lSt = lSt\r\n match = 0\r\n rnd = 1\r\n #score[0] = player score [1] = CPU\r\n ######\r\n #score = [0, 0, 1]\r\n play = \"y\"\r\n attacks = ('swing', 'block', 'stab')\r\n ######\r\n \r\n\r\n #round, score, health, wounds, blood, longest round\r\n #round, score, health, wounds, blood, longest round, current winstreak, longest winstreak\r\n def duel_lite(rnd, score, uAtk):\r\n #match += 1\r\n #print \"---------------------\"\r\n #print \"Round: \" + str(rnd)\r\n #print \"---------------------\"\r\n #print \"Attacks: 1 = Rock 2 = Paper 3 = Scissors\"\r\n #uAtk = input(\"Choose your attack: \")\r\n uAtk += -1\r\n cAtk = random.choice(attacks)\r\n## if uAtk == -1:\r\n## cAtk = 0\r\n## return\r\n #print \"your move:\", attacks[uAtk], \"enemy move:\", cAtk\r\n\r\n #result returns which animations to play\r\n #result[0] = left animations\r\n #result[1] = right animations\r\n result = (0,0,health)\r\n \r\n \r\n if (attacks.index(cAtk) == 0 and uAtk == 1):\r\n #enemy swing hits\r\n health[0] -= 1\r\n lRslt = 5\r\n rRslt = 1\r\n #score[1] = (score[1] + 1)\r\n \r\n elif (attacks.index(cAtk) == 1 and uAtk == 0):\r\n #player swing hits\r\n health[1] -= 1\r\n lRslt = 1\r\n rRslt = 5\r\n #score[0] = (score[0] + 1)\r\n \r\n elif (attacks.index(cAtk) == 1 and uAtk == 2 ):\r\n #enemy block hits\r\n health[0] -= 1\r\n lRslt = 6\r\n rRslt = 2\r\n #score[1] = (score[1] + 1)\r\n \r\n elif (attacks.index(cAtk) == 2 and uAtk == 1):\r\n #player block hits\r\n health[1] -= 1\r\n\r\n lRslt = 2\r\n rRslt = 6\r\n #score[0] = (score[0] + 1)\r\n\r\n elif (attacks.index(cAtk) == 2 and uAtk == 0):\r\n #enemy stab hits\r\n health[0] -= 1\r\n\r\n lRslt = 4\r\n rRslt = 3\r\n #score[1] = (score[1] + 1)\r\n \r\n elif (attacks.index(cAtk) == 0 and uAtk == 2):\r\n #player stab hits\r\n health[1] = (health[1] -1)\r\n\r\n lRslt = 3\r\n rRslt = 4\r\n #score[0] = (score[0] + 1)\r\n #print (result[0], result[1])\r\n# #result[2] = health\r\n #return result\r\n\r\n \r\n elif (attacks.index(cAtk) == uAtk):\r\n #clash \r\n rnd += 1\r\n if health[0] < 3:\r\n health[0] += 1\r\n #Result +7 = clash animation\r\n lRslt = uAtk + 7\r\n rRslt = uAtk + 7\r\n #score[2] += 1 #add to round count (do it below, having both increments more than you want :P\r\n \r\n \r\n ## print attacks.index(cAtk)\r\n ## print uAtk\r\n #return score\r\n if (health[0] < 1):\r\n #resetting player's wins for now\r\n score[0] = 0\r\n #\r\n score[1] += 1\r\n lRslt += 9\r\n rRslt += 9\r\n score[2] = 0 #reset round count\r\n #match = 1 #reset level\r\n #add death result/change result[0] to death result\r\n #health[0] = 1\r\n elif (health[1] < 1):\r\n score[0] += 1\r\n lRslt += 9\r\n rRslt += 9\r\n score[2] = 0 #reset round count\r\n #match += 1 #go to next level\r\n #health[1] = 1\r\n #add death result/change result[0] to death result\r\n score[2] += 1\r\n result = (lRslt, rRslt, health)\r\n print (result[0], result[1])\r\n print (\"your health: \", health[0])\r\n# #result[2] = health\r\n return result\r\n#UPDATED animation/result key:\r\n#animation key: 0 = idle, 1 = swing, 2 = block, 3 = stab,\r\n# 4 = swing fail, 5 = block fail, 6 = stab fail\r\n#\r\n# 7 = swing clash 8 = block clash 9 = stab clash\r\n#\r\n# 10= swing kill 11= block kill 12= stab kill\r\n# 13= swing death 14= block death 15= stab death\r\n#knight_anims_r src should change with level\r\n\r\n\r\n def old_duel(self, rnd, score, health, wounds, blood, longest, cSt, lSt, uAtk = 0, cAtk = 0):\r\n\r\n bld_drp = (.01, .02, .03, .04, .05, .06, .07, .08, .09, .10)\r\n bld_gsh = (.6, .75, .8, .86, .9, .93, 1.0)\r\n## print(\"---------------------\")\r\n## print (\"Round: \" + str(rnd))\r\n## print (\"---------------------\")\r\n if (longest[0] < rnd):\r\n longest[0] = rnd\r\n## print (\"rounds: \" + str(rnd))\r\n## print (\"Attacks: 1 = \" + attacks[0] + \" 2 = \" + attacks[1] + \" 3 = \" + attacks[2])\r\n## uAtk = int(input(\"Choose your attack: \"))\r\n## uAtk += -1\r\n if (uAtk < 0 or uAtk > 2 or uAtk):\r\n print (\"Agh! your hand must have slipped!\")\r\n print (\"luckily the sword flew towards the enemy!\")\r\n uAtk = 2\r\n #cAtk = attacks[0]#random.choice(attacks)\r\n cAtk = random.choice(attacks)\r\n## print (\"your move:\", attacks[uAtk], \"enemy move:\", cAtk)\r\n if (attacks.index(cAtk) == 0 and uAtk == 2):\r\n \r\n## print (\"|=|-|=|-|=|-|=|-|=|-|=|-|=|-|=|-|=|-|=|\"\r\n## \"\\n Enemy's\", cAtk, \"hits..\"\r\n## \"\\n|=|-|=|-|=|-|=|-|=|-|=|-|=|-|=|-|=|-|=|\")\r\n\r\n health[0] += -1\r\n wounds[0] += 1\r\n blood[0] += random.choice(bld_drp)\r\n## print (\"your health:\", health[0], \"enemy health:\", health[1])\r\n if (health[0] <= 0): \r\n score[1] = (score[1] + 1)\r\n blood[0] += random.choice(bld_gsh)\r\n## print (\"you've been slain.\")\r\n #health[0] = 1 #reset player health\r\n #return\r\n else:\r\n rnd += 1\r\n self.duel(rnd, score, health, wounds, blood, longest, cSt, lSt)\r\n elif (attacks.index(cAtk) == 2 and uAtk == 0):\r\n\r\n## print (\"|=|+|=|+|=|+|=|+|=|+|=|+|=|+|=|+|=|+|=|\")\r\n## print (\" Your\", attacks[uAtk], \"hits!\")\r\n## print (\"|=|+|=|+|=|+|=|+|=|+|=|+|=|+|=|+|=|+|=|\")\r\n health[1] += -1\r\n wounds[1] += 1\r\n blood[1] += random.choice(bld_drp)\r\n## print (\"your health:\", health[0], \"enemy health:\", health[1])\r\n if (health[1] <= 0):\r\n## print (\"|=|+|=|+|=|+|=|+|=|+|=|+|=|+|=|+|=|+|=|\")\r\n## print (\" Enemy slain! You are victorious!\")\r\n## print (\"|=|+|=|+|=|+|=|+|=|+|=|+|=|+|=|+|=|+|=|\")\r\n blood[1] += random.choice(bld_gsh)\r\n score[0] = (score[0] + 1)\r\n self.cSt += 1\r\n health[1] = 1 #reset enemy health\r\n else:\r\n rnd += 1\r\n self.duel(rnd, score, health, wounds, blood, longest, cSt, lSt)\r\n \r\n elif (attacks.index(cAtk) > uAtk):\r\n \r\n## print (\"|=|-|=|-|=|-|=|-|=|-|=|-|=|-|=|-|=|-|=|\")\r\n## print (\" Enemy's\", cAtk, \"hits..\")\r\n## print (\"|=|-|=|-|=|-|=|-|=|-|=|-|=|-|=|-|=|-|=|\")\r\n \r\n health[0] += -1\r\n wounds[0] += 1\r\n blood[0] += random.choice(bld_drp)\r\n## print (\"your health:\", health[0], \"enemy health:\", health[1])\r\n if (health[0] <= 0): \r\n score[1] = (score[1] + 1)\r\n blood[0] += random.choice(bld_gsh)\r\n## print (\"you've been slain.\")\r\n #health[0] = 1 #reset player health\r\n #return\r\n else:\r\n rnd += 1\r\n self.duel(rnd, score, health, wounds, blood, longest, cSt, lSt)\r\n \r\n elif (attacks.index(cAtk) < uAtk):\r\n## print (\"|=|+|=|+|=|+|=|+|=|+|=|+|=|+|=|+|=|+|=|\")\r\n## print (\" Your\", attacks[uAtk], \"hits!\")\r\n## print (\"|=|+|=|+|=|+|=|+|=|+|=|+|=|+|=|+|=|+|=|\")\r\n health[1] += -1\r\n wounds[1] += 1\r\n blood[1] += random.choice(bld_drp)\r\n## print (\"your health:\", health[0], \"enemy health:\", health[1])\r\n if (health[1] <= 0):\r\n## print (\"|=|+|=|+|=|+|=|+|=|+|=|+|=|+|=|+|=|+|=|\")\r\n## print (\" Enemy slain! You are victorious!\")\r\n## print (\"|=|+|=|+|=|+|=|+|=|+|=|+|=|+|=|+|=|+|=|\")\r\n score[0] = (score[0] + 1)\r\n blood[1] += random.choice(bld_gsh)\r\n self.cSt += 1\r\n health[1] = 1 #reset enemy health\r\n else:\r\n rnd += 1\r\n self.duel(rnd, score, health, wounds, blood, longest, cSt, lSt)\r\n \r\n elif (attacks.index(cAtk) == uAtk and uAtk != 0):\r\n## print (\"|=|-|=|+++|=|-|=|\")\r\n## print (\"|=|+-CLASH!!-+|=|\")\r\n## print (\"|=|-|=|+++|=|-|=|\")\r\n if (health[0] < 3): \r\n## print (\"YOU GAIN 1 HEALTH\")\r\n health[0] += 1\r\n## else:\r\n## print (\"Already at max health\")\r\n## print (\"your health:\", health[0])\r\n score[2] += 1\r\n rnd += 1\r\n self.duel(rnd, score, health, wounds, blood, longest, cSt, lSt)\r\n \r\n\r\n #could return a list of info if necessary\r\n\r\n def play_game(self):\r\n play = self.play\r\n match = self.match\r\n health = self.health\r\n #note: cSt and lSt below are called slightly differently because their info goes both ways post-duel\r\n cSt = self.cSt\r\n lSt = self.lSt\r\n print (title)\r\n print (rules)\r\n \r\n while (play != \"n\"):\r\n #starting health levels will change when game levels/characters are implemented\r\n #health = [1,1]\r\n \r\n ##reset health levels for player if they died\r\n if (health[0] <= 0):\r\n health[0] = 1\r\n## print (\"your health:\", health[0], \"enemy health:\", health[1])\r\n \r\n #print \"Your remaining health: \", health[0]\r\n while (health[0] > 0):\r\n## print (\"------------\")\r\n match += 1\r\n## print (\"Duel #\" + str(match))\r\n## anim.k_ctrl()\r\n self.duel(rnd, score, health, wounds, blood, longest, cSt, lSt)\r\n\r\n #reset win streak if player dies\r\n if (health[0] < 1):\r\n self.cSt = 0\r\n \r\n if (self.cSt >= self.lSt):\r\n self.lSt = self.cSt\r\n\r\n## play = input(\"Continue duels? (y/n)\")\r\n\r\n\r\n def score_string(self):\r\n \"returns a score string\"\r\n sscore = \"\\n=============SCORE BREAKDOWN===================\"\r\n sscore += \"\\nAllied blood split... \" + str(blood[0]) + \" gallons\"\r\n sscore += \"\\nEnemy blood spilt.... \" + str(blood[1]) + \" gallons\"\r\n sscore += \"\\nAllied wounds........ \" + str(wounds[0])\r\n sscore += \"\\nEnemy wounds......... \" + str(wounds[1])\r\n sscore += \"\\nLongest Duel......... \" + str(longest[0]) + \" rounds\"\r\n sscore += \"\\nLongest win streak... \" + str(g.lSt)\r\n sscore += \"\\n===============================================\"\r\n sscore += \"\\nDuels won: \" + str(score[0]) + \" |-| Duels Lost: \" + str(score[1]) + \" |-| Clashes: \" + str(score[2])\r\n sscore += \"\\n===============================================\"\r\n return sscore\r\n \r\n def mini_score(self):\r\n mini = \"===============================================\"\r\n mini += \"\\nDuels won: \" + str(score[0]) + \" |-| Duels Lost: \" + str(score[1]) + \" |-| Clashes: \" + str(score[2])\r\n mini += \"\\n===============================================\"\r\n return mini\r\n def get_score():\r\n return score\r\n def set_level(level):\r\n global match\r\n match = level\r\n def get_level():\r\n return match\r\n\r\n\r\n\r\n#g = game()\r\n#anim.k_ctrl()\r\n#g.play_game()\r\n#print (g.score_string())\r\n\r\n\r\n","sub_path":"game_class_stripped.py","file_name":"game_class_stripped.py","file_ext":"py","file_size_in_byte":14633,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"452274479","text":"#!/usr/bin/env python\n\nimport time\nfrom astropy import units as u\nimport datetime as dt\nimport pytz\nfrom cxotime import CxoTime\nimport Ska.engarchive.fetch as fetch\n\nfrom contextlib import contextmanager\nimport signal\n\n\nclass TimeoutException(Exception):\n pass\n\n\n@contextmanager\ndef force_timeout(seconds):\n '''\n For some reason, my MAUDE fetches using the Ska API sometimes\n timeout on the ssl.do_handshake() call. I'm lazy and don't want\n to figure it out, so this function will force a timeout of the call\n after a given number of seconds. If you wrap it in a try/except and a while\n loop, it will simply try again (which almost always fixes the issue). \n '''\n def signal_handler(signum, frame):\n raise TimeoutException(\"Timed out! Pressing on...\")\n signal.signal(signal.SIGALRM, signal_handler)\n signal.alarm(seconds)\n try:\n yield\n finally:\n signal.alarm(0)\n\n\n\n\ndef are_we_in_comm(verbose=False, cadence=2, fake_comm=False):\n # Always be fetching from MAUDE\n fetch.data_source.set('maude allow_subset=True')\n\n # These fetches are really fast. Slow the cadence a bit.\n time.sleep(cadence) # cadence is in seconds here\n\n # If there VCDU frame values within the last 60 seconds, this will not be empty\n ref_vcdu = fetch.Msid('CVCDUCTR', start=CxoTime.now() - 60 * u.s)\n\n # Will be True if in comm, False if not.\n in_comm = len(ref_vcdu) > 0\n\n if fake_comm is True:\n in_comm = True\n\n if verbose:\n if in_comm:\n print(\n f'({CxoTime.now().strftime(\"%m/%d/%Y %H:%M:%S\")} | VCDU {ref_vcdu.vals[-1]} | #{in_comm_counter}) IN COMM!', end='\\r')\n elif not in_comm:\n print(\n f'({CxoTime.now().strftime(\"%m/%d/%Y %H:%M:%S\")}) Not in Comm. ', end='\\r\\r\\r')\n\n return in_comm\n\n\ndef timestamp_string():\n # return CxoTime.now().strftime(\"%m/%d/%Y %H:%M:%S\")\n # return dt.datetime.now().strftime(\"%m/%d/%Y %H:%M:%S\")\n return dt.datetime.now(pytz.timezone('US/Eastern')).strftime(\"%m/%d/%Y %I:%M:%S %p\") + f\" {dt.datetime.now(pytz.timezone('US/Eastern')).astimezone().tzinfo}\"\n\n\ndef main():\n while True:\n in_comm = are_we_in_comm(verbose=True)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"hrcsentinel/heartbeat.py","file_name":"heartbeat.py","file_ext":"py","file_size_in_byte":2284,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"145509801","text":"# -*- coding: cp1252 -*-\r\n\r\nimport pygame\r\nimport math\r\nimport random\r\nimport time\r\n\r\npygame.init()\r\n\r\nscreen = pygame.display.set_mode((800,600))\r\n\r\nbackground = pygame.image.load('Imagens/background.png')\r\n\r\ncurrent_time = 0\r\n\r\nvida_value = 10\r\n\r\nmultiplicador = 1\r\n\r\ncombo_value = 0\r\n\r\nscore_value = 0\r\n\r\nfont = pygame.font.Font('freesansbold.ttf', 32)\r\n\r\nscoreX = 10 \r\nscoreY = 50\r\n\r\nvidaX = 10\r\nvidaY = 10\r\n\r\ncomboX = 10\r\ncomboY = 100\r\n\r\npygame.display.set_caption(\"Survive Covid\")\r\nicon = pygame.image.load('Imagens/icon.png')\r\npygame.display.set_icon(icon)\r\n\r\nplayerImg = pygame.image.load('Imagens/carrinho.png')\r\nplayerImg = pygame.transform.scale(playerImg, (50, 50))\r\nplayerX = 400\r\nplayerY = 480\r\nplayerX_change = 0\r\n\r\ncovidImg = pygame.image.load('Imagens/covid.png')\r\ncovidImg = pygame.transform.scale(covidImg, (50, 50))\r\ncovidX = random.randint(0, 700)\r\ncovidY = -15000\r\ncovidY_change = 2.5\r\n\r\nfeijaoImg = pygame.image.load('Imagens/feijao.png')\r\nfeijaoImg = pygame.transform.scale(feijaoImg, (50, 50))\r\nfeijaoX = random.randint(0, 700)\r\nfeijaoY = -60\r\nfeijaoY_change = 1.5\r\n\r\narrozImg = pygame.image.load('Imagens/arroz.png')\r\narrozImg = pygame.transform.scale(arrozImg, (50, 50))\r\narrozX = random.randint(0, 700)\r\narrozY = -3000\r\narrozY_change = 2\r\n\r\ngelImg = pygame.image.load('Imagens/gel.png')\r\ngelImg = pygame.transform.scale(gelImg, (50, 50))\r\ngelX = random.randint(0, 700)\r\ngelY = -8000\r\ngelY_change = 2.5\r\n\r\ndef show_score(x, y):\r\n score = font.render(\"Pontos: \" + str(score_value), True, (255, 255, 255))\r\n screen.blit(score, (x, y))\r\n\r\ndef show_vida(x, y):\r\n vida = font.render(\"Vida: \" + str(vida_value), True, (255, 255, 255))\r\n screen.blit(vida, (x, y))\r\n\r\ndef show_combo(x, y):\r\n combo = font.render(\"Combo: x\" + str(multiplicador), True, (255, 255, 255))\r\n screen.blit(combo, (x, y))\r\n\r\ndef player(x, y):\r\n screen.blit(playerImg, (x, y))\r\n \r\ndef covid(x, y):\r\n screen.blit(covidImg, (x, y))\r\n\r\ndef feijao(x, y):\r\n screen.blit(feijaoImg, (x, y))\r\n\r\ndef arroz(x, y):\r\n screen.blit(arrozImg, (x, y))\r\n \r\ndef gel(x, y):\r\n screen.blit(gelImg, (x, y))\r\n\r\ndef isCollisionCovid(playerX, playerY, covidX, covidY):\r\n distance = math.sqrt((math.pow(playerX-covidX,2)) + (math.pow(playerY-covidY,2)))\r\n if distance < 65:\r\n return True\r\n else:\r\n return False\r\n\r\ndef isCollisionFeijao(playerX, playerY, feijaoX, feijaoY):\r\n distance = math.sqrt((math.pow(playerX-feijaoX,2)) + (math.pow(playerY-feijaoY,2)))\r\n if distance < 65:\r\n return True\r\n else:\r\n return False\r\n\r\ndef isCollisionArroz(playerX, playerY, arrozX, arrozY):\r\n distance = math.sqrt((math.pow(playerX-arrozX,2)) + (math.pow(playerY-arrozY,2)))\r\n if distance < 65:\r\n return True\r\n else:\r\n return False\r\n\r\ndef isCollisionGel(playerX, playerY, gelX, gelY):\r\n distance = math.sqrt((math.pow(playerX-gelX,2)) + (math.pow(playerY-gelY,2)))\r\n if distance < 65:\r\n return True\r\n else:\r\n return False\r\n\r\nrunning = True\r\nwhile running:\r\n\r\n screen.fill((0, 0, 0))\r\n screen.blit(background, (0, 0))\r\n for event in pygame.event.get():\r\n if event.type == pygame.QUIT:\r\n running = False\r\n\r\n if event.type == pygame.KEYDOWN:\r\n if event.key == pygame.K_LEFT:\r\n playerX_change = -5\r\n if event.key == pygame.K_RIGHT:\r\n playerX_change = 5\r\n\r\n if event.type == pygame.KEYUP:\r\n if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:\r\n playerX_change = 0\r\n \r\n current_time = pygame.time.get_ticks()\r\n\r\n covidY += covidY_change\r\n feijaoY += feijaoY_change\r\n arrozY += arrozY_change\r\n gelY += gelY_change\r\n playerX += playerX_change\r\n\r\n if playerX <= 0:\r\n playerX = 0\r\n elif playerX >= 730:\r\n playerX = 730\r\n\r\n if combo_value >= 5:\r\n multiplicador = 2\r\n\r\n if combo_value >= 10:\r\n multiplicador = 4\r\n\r\n if combo_value >= 15:\r\n multiplicador = 6\r\n\r\n collision = isCollisionCovid(playerX, playerY, covidX, covidY)\r\n if collision:\r\n\r\n soma_covid = 0\r\n covidMultiplicado = multiplicador * soma_covid\r\n covidX = random.randint(0, 770)\r\n covidY = -60\r\n covidY_change += 0.02\r\n score_value += covidMultiplicado\r\n playerX_change += 0.02\r\n combo_value += 0\r\n vida_value -=5\r\n\r\n collision = isCollisionFeijao(playerX, playerY, feijaoX, feijaoY)\r\n if collision:\r\n\r\n soma_feijao = 5\r\n feijaoMultiplicado = multiplicador * soma_feijao\r\n feijaoX = random.randint(0, 770)\r\n feijaoY = -60\r\n feijaoY_change += 0.02\r\n score_value += feijaoMultiplicado\r\n playerX_change += 0.02\r\n combo_value += 1\r\n vida_value +=1\r\n\r\n collision = isCollisionArroz(playerX, playerY, arrozX, arrozY)\r\n if collision:\r\n\r\n soma_arroz = 10\r\n arrozMultiplicado = multiplicador * soma_arroz\r\n arrozX = random.randint(0, 700)\r\n arrozY = -60\r\n arrozY_change += 0.02\r\n playerX_change += 0.02\r\n score_value += arrozMultiplicado\r\n combo_value += 1\r\n vida_value +=2\r\n \r\n collision = isCollisionGel(playerX, playerY, gelX, gelY)\r\n if collision:\r\n\r\n soma_gel = 20\r\n gelMultiplicado = multiplicador * soma_gel\r\n gelX = random.randint(0, 700)\r\n gelY = -60\r\n gelY_change += 0.02\r\n playerX_change += 0.02\r\n score_value += gelMultiplicado\r\n combo_value += 1\r\n vida_value +=3\r\n\r\n if covidY >= 600:\r\n covidX = random.randint(0, 700)\r\n covidY = -60\r\n covidY_change += 0.02\r\n playerX_change += 0.02\r\n combo_value = 0\r\n multiplicador = 1\r\n vida_value -=0\r\n \r\n if feijaoY >= 600:\r\n feijaoX = random.randint(0, 700)\r\n feijaoY = -60\r\n feijaoY_change += 0.02\r\n playerX_change += 0.02\r\n combo_value = 0\r\n multiplicador = 1\r\n vida_value -=1\r\n\r\n if arrozY >= 600:\r\n arrozX = random.randint(0, 770)\r\n arrozY = -60\r\n arrozY_change += 0.02\r\n playerX_change += 0.02\r\n combo_value = 0\r\n multiplicador = 1\r\n vida_value -=2\r\n \r\n if gelY >= 600:\r\n gelX = random.randint(0, 770)\r\n gelY = -60\r\n gelY_change += 0.02\r\n playerX_change += 0.02\r\n combo_value = 0\r\n multiplicador = 1\r\n vida_value -=3\r\n \r\n if current_time >= 10000:\r\n arroz(arrozX, arrozY)\r\n \r\n if current_time >= 25000:\r\n gel(gelX, gelY)\r\n \r\n if current_time >= 35000:\r\n covid(covidX, covidY)\r\n \r\n if vida_value >= 10:\r\n vida_value = 10\r\n \r\n if vida_value <= 0:\r\n vida_value = 0\r\n\r\n covid(covidX, covidY)\r\n player(playerX, playerY)\r\n feijao(feijaoX, feijaoY)\r\n show_score(scoreX, scoreY)\r\n show_combo(comboX, comboY)\r\n show_vida(vidaX, vidaY)\r\n pygame.display.update()\r\n\r\n ","sub_path":"pythonProject/apresentar.py","file_name":"apresentar.py","file_ext":"py","file_size_in_byte":7020,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"344711909","text":"from imports.imports import readFile\n\n\nlista = readFile(\"input2\")\n\n\ndef operate(list):\n i = 0\n while list[i] != 99:\n if list[i] == 1:\n list[list[i + 3]] = list[list[i + 1]] + list[list[i + 2]]\n elif list[i] == 2:\n list[list[i + 3]] = list[list[i + 1]] * list[list[i + 2]]\n i = i + 4\n #list = list\n return list\n\n\ndef operate2():\n asdlol = 0\n total = 19690720\n lis = lista\n for i in range(0, 100):\n for j in range(0, 100):\n lis = readFile(\"input2\")\n lis[1] = j\n lis[2] = i\n operate(lis)\n if lis[0] == total:\n asdlol1 = lis[1]\n asdlol2 = lis[2]\n print(\"{0}, {1}\".format(asdlol1,asdlol2))\n return asdlol\n\n\nprint(operate(lista)[0])\noperate2()","sub_path":"2/2.py","file_name":"2.py","file_ext":"py","file_size_in_byte":830,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"315378566","text":"import unittest\nimport time\nfrom selenium.webdriver.common.keys import Keys\nfrom selenium import webdriver\nimport json\nfrom . import test_login as login\n\n\nclass TestFollowUser(unittest.TestCase):\n var_dict = {}\n\n @classmethod\n def setUpClass(cls):\n try:\n # with open('account\\\\selenium_tests\\\\test_variables.json') as file: # windows\n with open('account//selenium_tests//test_variables.json') as file: # linux\n cls.var_dict = json.load(file)\n except IOError:\n print('\\n\\t**NEED JSON FILE FOR TEST VARIABLES**\\n')\n\n cls.driver = webdriver.Edge(cls.var_dict['driver_exe'])\n login.TestLogin().test_login(cls.driver)\n cls.driver.find_element_by_xpath(cls.var_dict['people_link']).click()\n time.sleep(2)\n\n # @unittest.skip('already tested')\n def test_follow_user(self):\n self.driver.find_element_by_xpath(self.var_dict['fifth_user']).click()\n time.sleep(2)\n self.driver.find_element_by_xpath(self.var_dict['follow_button']).click()\n time.sleep(2)\n \n assert self.driver.find_element_by_xpath(self.var_dict['user_follower_count_xpath']).text == '2'\n\n @classmethod\n def tearDownClass(cls):\n cls.driver.quit()\n\n\nif __name__ == '__main__':\n unittest.main()","sub_path":"account/selenium_tests/test_follow_user.py","file_name":"test_follow_user.py","file_ext":"py","file_size_in_byte":1311,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"654500299","text":"#!/usr/bin/python3\n#coding=utf-8\n\n__metaclass__ = type\n__author__ = 'xdlove'\n\nclass Solution:\n\n def kmpPre(self, tar):\n tlen = len(tar)\n next = [-1 for x in range(tlen + 1)]\n i, j = 0, -1\n while i < tlen:\n while j != -1 and tar[i] != tar[j]:\n j = next[j]\n i += 1\n j += 1\n next[i] = j\n return next\n\n def strStr(self, source, target):\n try:\n slen = len(source)\n tlen = len(target)\n except:\n return -1\n next = self.kmpPre(target)\n if slen + tlen == 0:\n return 0\n i, j = 0,0\n while i < slen:\n if tlen == 0:\n return 0\n while j != -1 and source[i] != target[j]:\n j = next[j]\n i += 1\n j += 1\n if j >= tlen:\n return i - tlen\n return -1\n\nif __name__ == '__main__':\n res = Solution().strStr(\"ads\",\"aid\")\n print(res)\n","sub_path":"PyEveryDay/2016-06-12.py","file_name":"2016-06-12.py","file_ext":"py","file_size_in_byte":1005,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"499625546","text":"\r\n\r\nimport numpy as np\r\nfrom flask import Flask, render_template, request, jsonify\r\nimport joblib\r\nfrom sklearn.preprocessing import LabelEncoder\r\n\r\nle = LabelEncoder()\r\n\r\nfrom sklearn.preprocessing import StandardScaler\r\n\r\nsc = StandardScaler()\r\n\r\napp = Flask(__name__, template_folder='Templates')\r\n\r\n\r\n@app.route(\"/\")\r\ndef home():\r\n return render_template('home.html')\r\n\r\n\r\n@app.route(\"/result\", methods=[\"POST\", \"GET\"])\r\ndef result():\r\n list_col = ['item_weight', 'item_fat_content', 'item_visibility', 'item_type',\r\n 'item_mrp', 'outlet_establishment_year', 'outlet_size',\r\n 'outlet_location_type', 'outlet_type']\r\n\r\n item_weight = float(request.form['item_weight'])\r\n item_fat_content = str(request.form['item_fat_content'])\r\n item_visibility = float(request.form['item_visibility'])\r\n item_type = str(request.form['item_type'])\r\n item_mrp = float(request.form['item_mrp'])\r\n outlet_establishment_year = int(request.form['outlet_establishment_year'])\r\n outlet_size = str(request.form['outlet_size'])\r\n outlet_location_type = str(request.form['outlet_location_type'])\r\n outlet_type = str(request.form['outlet_type'])\r\n\r\n # print(item_fat_content)\r\n\r\n # Label Encoding\r\n\r\n le = joblib.load(r'Le.sav')\r\n\r\n item_fat_content = le.fit_transform([item_fat_content])\r\n item_type = le.fit_transform([item_type])\r\n outlet_size = le.fit_transform([outlet_size])\r\n outlet_location_type = le.fit_transform([outlet_location_type])\r\n outlet_type = le.fit_transform([outlet_type])\r\n\r\n inputs = np.array([item_weight, item_fat_content, item_visibility, item_type, item_mrp, outlet_establishment_year,\r\n outlet_size, outlet_location_type, outlet_type]).reshape(1, -1)\r\n print(inputs)\r\n\r\n # Lets put all in the list\r\n\r\n # Lets apply Standard Scaler\r\n\r\n sc = joblib.load(r'Sc.sav')\r\n inputs_std = sc.transform(inputs)\r\n\r\n # Lets apply prediction\r\n\r\n model = joblib.load(r'RandomForest.sav')\r\n\r\n prediction = model.predict(inputs_std)\r\n prediction = prediction.tolist()\r\n\r\n return jsonify({'prediction': prediction})\r\n\r\n\r\nif __name__ == '__main__':\r\n app.run(debug=True, port=7890)","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2211,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"400144518","text":"\"\"\"\nDefines the blueprint for the users\n\"\"\"\nfrom flask import Blueprint\nfrom flask_restful import Api\n\nfrom resources import UserResource, UsersResource\n\nUSER_BLUEPRINT = Blueprint(\"user\", __name__)\nApi(USER_BLUEPRINT).add_resource(\n UserResource, \"/user//\"\n)\n\nUSERS_BLUEPRINT = Blueprint(\"best_movie\", __name__)\nApi(USERS_BLUEPRINT).add_resource(\n UsersResource, \"/users//\"\n)\n","sub_path":"server/src/routes/user.py","file_name":"user.py","file_ext":"py","file_size_in_byte":457,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"314098535","text":"#Followed these blog posts. Build AST and plug in the ARITH language. \n\n# https://ruslanspivak.com/lsbasi-part7/\n# https://rosettacode.org/wiki/Arithmetic_evaluation#Python\n# \n# Used pyinstaller for makefile, learn how to write one from this website\n# https://github.com/operatorequals/covertutils/blob/master/makefile\n# Which is just some random git repo used pyinstaller\n\n\nimport operator\n \nclass AstNode(object):\n def __init__( self, opr, left, right ):\n self.opr = opr\n self.l = left\n self.r = right\n \n def eval(self):\n return self.opr(IntExp(self.l.eval()), IntExp(self.r.eval())).eval()\n \n \nclass Exp(object):\n\tdef __init__(self):\n\t\tself.e = None\n\tdef eval (self):\n\t\treturn\n\nclass IntExp(Exp):\n\tdef __init__(self, n):\n\t\tself.e = int(n)\n\t\t# print(\"n\",n)\n\n\tdef eval(self):\n\t\treturn self.e\n\nclass SumExp(Exp):\n\tdef __init__(self,e1,e2):\n\t\tself.e1 = e1\n\t\tself.e2 = e2\n\tdef eval(self):\n\t\treturn self.e1.eval() + self.e2.eval()\n\nclass MultExp(Exp):\n\tdef __init__(self,e1,e2):\n\t\tself.e1 = e1\n\t\tself.e2 = e2\n\tdef eval(self):\n\t\treturn self.e1.eval() * self.e2.eval()\n\t\n\nclass MinusExp(Exp):\n\tdef __init__(self,e1,e2):\n\t\tself.e1 = e1\n\t\tself.e2 = e2\n\tdef eval(self):\n\t\treturn self.e1.eval() - self.e2.eval()\n\nclass PowExp(Exp):\n\tdef __init__(self,e1,e2):\n\t\tself.e1 = e1\n\t\tself.e2 = e2\n\tdef eval(self):\n\t\treturn pow(self.e1.eval() , self.e2.eval())\n\t\n\n \nclass Yaccer(object):\n def __init__(self):\n self.operstak = []\n self.nodestak =[]\n self.__dict__.update(self.state1)\n \n def v1( self, valStrg ):\n # Value String\n # print(\"valStrg\",valStrg)\n self.nodestak.append( IntExp(valStrg))\n self.__dict__.update(self.state2)\n #print 'push', valStrg\n \n def o2( self, operchar ):\n # Operator character or open paren in state1\n def openParen(a,b):\n return 0\t\t# function should not be called\n \n opDict= { '+': ( SumExp, 2, 2 ),\n '-': (MinusExp, 2, 2 ),\n '*': (MultExp, 3, 3 ),\n '^': (PowExp, 4, 4 ),\n\n }\n operPrecidence = opDict[operchar][2]\n #print(\"opDict[operchar]\",opDict[operchar])\n self.redeuce(operPrecidence)\n \n self.operstak.append(opDict[operchar])\n self.__dict__.update(self.state1)\n # print 'pushop', operchar\n \n def syntaxErr(self, char ):\n # Open Parenthesis \n print ('parse error - near operator \"%s\"' %char)\n \n \n def end(self):\n self.redeuce(0)\n return self.nodestak.pop()\n \n def redeuce(self, precidence):\n # print(\"precidence\",precidence,\"self.operstak\",self.operstak)\n while len(self.operstak)>0:\n tailOper = self.operstak[-1]\n if tailOper[1] < precidence: break\n \n tailOper = self.operstak.pop()\n vrgt = self.nodestak.pop()\n vlft= self.nodestak.pop()\n self.nodestak.append( AstNode(tailOper[0], vlft, vrgt))\n # print 'reduce'\n \n state1 = { 'v': v1, 'o':syntaxErr, 'po':o2 }\n state2 = { 'v': syntaxErr, 'o':o2, 'po':syntaxErr}\n \n \ndef Lex( exprssn, p ):\n bgn = None\n cp = -1\n for c in exprssn:\n cp += 1\n if c in '+*^': # throw in exponentiation (^)for grins\n # print(\"+-*cp, bgn\", cp, bgn)\n if bgn is not None:\n #print(\"cp, bgn\", cp, bgn, exprssn[bgn:cp])\n p.v(p, exprssn[bgn:cp])\n bgn = None\n \n p.o(p, c)\n elif c in ' \\t':\n if bgn is not None:\n p.v(p, exprssn[bgn:cp])\n bgn = None\n elif c in '0123456789':\n if bgn is None:\n bgn = cp\n elif c in '-':\n # print(\"cp, bgn\", cp, bgn, exprssn[bgn:cp])\n # print(\"length\", exprssn[cp+1:cp+2])#==' ')\n if exprssn[cp+1:cp+2] == ' ':\n if bgn is not None:\n p.v(p, exprssn[bgn:cp])\n bgn = None\n p.o(p, c)\n else:\n if bgn is None:\n bgn = cp\n else:\n print ('Invalid character in expression')\n if bgn is not None:\n p.v(p, exprssn[bgn:cp])\n bgn = None\n \n if bgn is not None:\n p.v(p, exprssn[bgn:cp+1])\n bgn = None\n return p.end()\n \n \nexpr = input(\"\")\nastTree = Lex( expr, Yaccer())\nprint (astTree.eval())\n# print (expr, '=',astTree.eval())","sub_path":"ARITH/arith.py","file_name":"arith.py","file_ext":"py","file_size_in_byte":4249,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"598024702","text":"from flask_wtf import Form\nfrom wtforms import SelectField, SubmitField\n\n\nclass BondItem(Form):\n list_ = SelectField('Список', coerce=int)\n submit = SubmitField('связать')\n\n def __init__(self, choices, *args, **kwargs):\n super(BondItem, self).__init__(*args, **kwargs)\n self.list_.choices = choices\n","sub_path":"sandbox/blogs/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":335,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"211445736","text":"#exec(open('templates\\\\featsel_classification.py').read())\nimport subprocess as sp\nimport pandas as pd\nimport sklearn.feature_selection as sfs\nimport numpy as np\nimport pickle as pk\nimport sklearn.ensemble as ensemble\n\nif __name__ == '__main__':\n sp.call('cls', shell = True)\n\n # load some data\n with open('.\\\\data\\\\pima.pkl', 'rb') as fl:\n df = pk.load(fl)\n\n # ----------------------------------------\n # Constants\n # ----------------------------------------\n np.set_printoptions(precision = 4, suppress = True)\n seed = 29\n figsize = (16, 10)\n\n # specify the x and y matrices\n ycols = ['class']\n xcolsnum = list(set(df.select_dtypes([np.number]).columns) - set(ycols))\n xcolsnonnum = list(set(df.select_dtypes([object]).columns) - set(ycols))\n xcols = xcolsnum + xcolsnonnum\n X = df.loc[:, xcols].values\n y = np.ravel(df.loc[:, ycols].values)\n\n # number of features to select\n k = 2\n\n # ----------------------------------------\n # Select-k-best algorithms\n # ----------------------------------------\n selectors = dict()\n selectors['chi2'] = sfs.SelectKBest(score_func = sfs.chi2, k = k)\n selectors['f_classif'] = sfs.SelectKBest(score_func = sfs.f_classif, k = k)\n selectors['mutual_info_classif'] = sfs.SelectKBest(score_func = sfs.mutual_info_classif, k = k)\n results = dict()\n for entry in selectors.items():\n selector = entry[1]\n selector.fit(X, y)\n srs = pd.Series(selector.scores_, index = xcols)\n srs.sort_values(ascending = False, inplace = True)\n results[entry[0]] = srs\n print('{0} feature rankings:'.format(entry[0]))\n for idx in srs.index:\n print(' {0: <20} - {1:.4f}'.format(idx, srs[idx]))\n print('')\n\n # ----------------------------------------\n # Feature importance\n # ----------------------------------------\n model = ensemble.ExtraTreesClassifier(random_state = seed)\n model.fit(X, y)\n srs = pd.Series(model.feature_importances_, index = xcols)\n srs.sort_values(ascending = False, inplace = True)\n results['ExtraTrees'] = srs\n print('ExtraTreesClassifier feature importance rankings:')\n for idx in srs.index:\n print(' {0: <20} - {1:.4f}'.format(idx, srs[idx]))\n print('')\n\n model = ensemble.RandomForestClassifier(random_state = seed)\n model.fit(X, y)\n srs = pd.Series(model.feature_importances_, index = xcols)\n srs.sort_values(ascending = False, inplace = True)\n results['RandomForest'] = srs\n print('RandomForestClassifier feature importance rankings:')\n for idx in srs.index:\n print(' {0: <20} - {1:.4f}'.format(idx, srs[idx]))\n print('')\n\n # ----------------------------------------\n # Recursive Feature Elimination\n # ----------------------------------------\n # specify any model\n model = ensemble.ExtraTreesClassifier(random_state = seed)\n selector = sfs.RFE(model, n_features_to_select = k).fit(X, y)\n srs = pd.Series(selector.ranking_, index = xcols)\n srs.sort_values(ascending = True, inplace = True)\n results['rfe'] = srs\n print('Recursive feature elimination feature rankings:')\n for idx in srs.index:\n print(' {0: <20} - {1:.4f}'.format(idx, srs[idx]))\n print('')\n\n # get best features according to all ranking schemes\n dfresults = pd.DataFrame(index = xcols)\n rank = np.arange(0, len(xcols))\n for entry in results.items():\n dfresults[entry[0]] = pd.Series(rank.copy(), index = entry[1].index)\n srs = dfresults.sum(axis = 1).sort_values()\n print('All features ranked:')\n for idx in srs.index:\n print(' {0}'.format(idx))\n print('')\n print('Best {0} features:'.format(k))\n for cnt in range(k):\n print(' {0}'.format(srs.index[cnt]))","sub_path":"templates/featsel_classification.py","file_name":"featsel_classification.py","file_ext":"py","file_size_in_byte":3799,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"262115331","text":"\nfrom logging import info, warning\nfrom bot.airflow_helpers.db_helper import insert_docs, delete_docs, get_docs\nfrom bot.airflow_helpers.quotes import get_uplifting_quote\nfrom bot.airflow_helpers.twitter_helper import send_tweet\n\n\nMONGODB_DB = \"happy\"\nMONGODB_COLLECTION_SOURCE = \"tweets\"\nMONGODB_COLLECTION_DESTINATION = \"tweet_replies\"\n\n\ndef _get_top_depressed_tweets(n):\n aggregate_query = [\n {'$sort': {\"prob\": -1}},\n {'$limit': n}\n ]\n return get_docs(MONGODB_DB,\n MONGODB_COLLECTION_SOURCE,\n aggregate_query)\n\n\ndef _tweet_reply(reply_doc):\n # print(reply_doc)\n\n text = \"@{user_mention} {text}\".format(user_mention=reply_doc['tweet_doc']['author'], text=reply_doc['reply'])\n in_reply_to_status_id = reply_doc['tweet_doc']['_id']\n\n\n # from datetime import datetime\n # text = \"@hapybot test again\" + str(datetime.now())\n # in_reply_to_status_id=\"1219607118698831872\"\n\n print(text, in_reply_to_status_id)\n send_tweet(text, in_reply_to_status_id=in_reply_to_status_id)\n\n\ndef send_replies(n):\n tweet_docs = _get_top_depressed_tweets(n)\n reply_documents = []\n for tweet_doc in tweet_docs:\n uplifting_quote = get_uplifting_quote(tweet_doc['text'])\n reply_doc = {\n 'tweet_doc' : tweet_doc,\n 'reply' : uplifting_quote,\n\n }\n\n # send reply\n _tweet_reply(reply_doc)\n\n reply_documents.append(reply_doc)\n\n # inserting them in a different collection\n # _insert_replies(mongo_hook, reply_documents)\n insert_docs(MONGODB_DB, MONGODB_COLLECTION_DESTINATION, reply_documents)\n\n\n # removing them from the old collection\n # _delete_tweets(mongo_hook, [doc['tweet_doc']['_id'] for doc in reply_documents])\n delete_docs(MONGODB_DB, MONGODB_COLLECTION_SOURCE, [doc['tweet_doc']['_id'] for doc in reply_documents])\n\n\nif __name__ == \"__main__\":\n send_replies(1)\n","sub_path":"bot/airflow_helpers/replies.py","file_name":"replies.py","file_ext":"py","file_size_in_byte":1973,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"186182991","text":"# Write a program to find the node at which the intersection of two singly linked lists begins.\n\n\n# For example, the following two linked lists:\n\n# A: a1 → a2\n# ↘\n# c1 → c2 → c3\n# ↗ \n# B: b1 → b2 → b3\n# begin to intersect at node c1.\n\n# Definition for singly-linked list.\n# class ListNode(object):\n# def __init__(self, x):\n# self.val = x\n# self.next = None\n\nclass Solution(object):\n def getIntersectionNode(self, headA, headB):\n \"\"\"\n :type head1, head1: ListNode\n :rtype: ListNode\n \"\"\"\n curA = headA\n curB = headB\n stepA = 0\n while curA:\n curA = curA.next\n stepA += 1\n\n stepB = 0\n while curB:\n curB = curB.next\n stepB += 1\n\n curA = headA\n curB = headB\n # Offset to make sure it's starting the same\n if stepA > stepB:\n moreA = stepA - stepB\n while moreA:\n curA = curA.next\n moreA -= 1\n else:\n moreB = stepB - stepA\n while moreB:\n curB = curB.next\n moreB -= 1\n\n while curA and curB:\n if curA is curB:\n return curA\n else:\n curA = curA.next\n curB = curB.next\n return None\n\n\n # 好几种解法,包括brute force, O(mn), 和hash http://tech-wonderland.net/blog/leetcode-intersection-of-two-linked-lists-4-different-methods.html\n # http://bookshadow.com/weblog/2014/12/04/leetcode-intersection-two-linked-lists/\n\n# Consider the case that two list has equal length, the problem became so easy: only two pointers are needed. Scan from the start of each list, check if the node are the same. Problem solved !\n# 不需要查合并点后面的,因为一旦合并了,后面肯定一样\n# However, just like the example showed in the question, we need to handle the case when the two list are not equal in length. What to do then? Let's make them equal !\n# (1) Get the length of list A, say n_a.\n# (2) Get the length of list B, say n_b.\n# These two steps will take O(n) time. (n = n_a + n_b)\n# (3) Set two pointers. Make the pointer of longer list abs(n_a-n_b) steps forward.\n# (4) Scan the two list until find the intersection, or to the end of list.\n# This step will take O(n) time.\n\n# Totally, time complexity is O(n), space complexity is O(1).\n","sub_path":"intersection-of-two-linked-lists-(E)-(160).py","file_name":"intersection-of-two-linked-lists-(E)-(160).py","file_ext":"py","file_size_in_byte":2498,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"483144470","text":"#Problem 2 ECE 4984\n#!/usr/bin/python3\n\nimport argparse\n\ndef minimum(edges, neighbors, i):\n\n\tsortedList = [neighbors[0]]\n\t\n\tminimum = neighbors[0][\"wij\"]\n\n\tfor newVertex in neighbors:\n\t\tif minimum > newVertex[\"wij\"]:\n\t\t\tsortedList.insert(0, neighbors)\n\n\treturn sortedList[0]\n\n\ndef dijkstra(edges, start, end, n):\n\t\n\tcostToCome = []\n\topenList = []\n\tvisitedList = [start]\n\tneighbors = []\n\trepeatedVal = False\n\tlowest = {}\n\tpossDirections = []\n\trouteTaken = []\n\tcostRoute = []\n\trunAgain = False\n\tfirstRun = True\n\n\t# fill the cost to come list\n\tfor x in range(int(n)):\n\t\tif x == start-1:\n\t\t\tcostToCome.append(0)\n\t\telse:\n\t\t\tcostToCome.append(float('inf'))\n\n\twhile len(openList) != 0 or firstRun:\t\t\t#not int(end) in visitedList or not runAgain:\n\t\tfirstRun = False\n\n\t\t#find new neighbors\n\t\tcurrVertex = visitedList[len(visitedList) - 1]\t#=2\n\t\t\n\t\tfor dictionary in edges:\n\t\t\tif dictionary[\"i\"] == currVertex:\t\t\t#=2,1,1\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t#=2,3,1.2\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t#=2,5,2\n\n\t\t\t\t# make sure the value isn't already listed as a neighbor\n\t\t\t\t\n\t\t\t\tfor value in visitedList:\n\t\t\t\t\tif dictionary[\"j\"] == value:\n\t\t\t\t\t\trepeatedVal = True\n\t\t\t\t\n\n\t\t\t\tif repeatedVal:\n\t\t\t\t\trepeatedVal = False\n\t\t\t\telse:\n\t\t\t\t\topenList.append(dictionary[\"j\"])\n\t\t\t\t\tpossDirections.append(dictionary)\n\n\t\t# new neighbors have been found\n\n\t\t# now search for the lowest weight\n\t\tminimum = 100\n\t\t'''\n\t\tprint()\n\t\tprint(\"possDirections:\")\n\t\tprint(possDirections)\n\t\t'''\n\n\t\tfor possRoutes in possDirections:\n\t\t\tif possRoutes[\"wij\"] < minimum:\n\t\t\t\trunAgain = False\n\t\t\t\tminimum = possRoutes[\"wij\"]\n\t\t\t\tquickestRoute = possRoutes\n\t\t\telif possRoutes[\"wij\"] == minimum:\n\t\t\t\trunAgain = True\n\t\t\t\tminimum = possRoutes[\"wij\"]\n\t\t\t\tquickestRoute = possRoutes\n\t\t\t\t# run one more time\n\n\n\t\ttotalWeight = quickestRoute[\"wij\"] + costToCome[quickestRoute[\"i\"]-1]\n\n\t\tif costToCome[quickestRoute[\"j\"]-1] > totalWeight:\n\t\t\t#print(\"totalWeight is less\")\n\t\t\tcostToCome[quickestRoute[\"j\"]-1] = totalWeight\n\n\t\tpossDirections.remove(quickestRoute)\n\t\topenList.remove(quickestRoute[\"j\"])\n\t\tvisitedList.append(quickestRoute[\"j\"])\n\n\n\tbacktrace = end\n\t\n\t#time to backtrace the optimal route\n\twhile int(backtrace) != int(start):\n\t\tfor index in visitedList:\t\t\t\t\t\t\t#search through all the neighbors\n\t\t\tfor dict1 in edges:\t\t\t\t\t\t\t#find the corresponding edges to the current neighbor\n\t\t\t\tif int(index) == int(dict1[\"i\"]):\t\t\t\t\t#if the current neighbor is found within the edges\n\t\t\t\t\t#print(str(index))\n\t\t\t\t\tif int(backtrace) == int(dict1[\"j\"]):\t\t\t#the final value is the neighbor\n\t\t\t\t\t\trouteTaken.append(int(backtrace))\n\t\t\t\t\t\tbacktrace = index\n\t\t\t\tif int(backtrace) == int(index):\n\t\t\t\t\tbreak\n\t\t\tif int(backtrace) == int(index):\n\t\t\t\tbreak\n\n\trouteTaken.reverse()\n\trouteTaken.insert(0, start)\n\tfor step in routeTaken:\n\t\tcostRoute.append(costToCome[step - 1])\t\n\n\tprint(costRoute[len(costRoute) - 1], file=open(\"output_cost.txt\", \"a\"))\n\tprint(len(visitedList), file=open(\"output_numiters.txt\", \"a\"))\n\nif __name__ == '__main__':\n\n\tparser = argparse.ArgumentParser()\n\tparser.add_argument(\"a\")\n\targs = parser.parse_args()\n\n\tedges = []\n\n# 1) read from the input.txt file\n\n\twith open(args.a) as fin:\n\t\t\n\t\tn = fin.readline()\n\t\tprint(\"total number of vertices: \" + n)\n\t\tstart = int(fin.readline())\n\t\tprint(\"starting index: \" + str(start))\n\t\tend = int(fin.readline())\n\t\tprint(\"goal vertex: \" + str(end))\n\n\t\tfor line in fin:\n\t\t\tlineArray = line.split()\n\t\t\tnewDict = {\"i\" : int(lineArray[0]), \"j\" : int(lineArray[1]), \"wij\": float(lineArray[2])}\n\t\t\tedges.append(newDict)\n\t\t\tdel newDict\n\n\n\n\tdijkstra(edges, start, end, n)\n","sub_path":"P2/Problem2.py","file_name":"Problem2.py","file_ext":"py","file_size_in_byte":3512,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"416357150","text":"# =============================================================================\n# Copyright 2020 NVIDIA. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# =============================================================================\n\n\"\"\"\nTutorial on how to use this script to solve NER task could be found here:\nhttps://nvidia.github.io/NeMo/nlp/intro.html#named-entity-recognition\n\"\"\"\n\nimport math\nimport numpy as np\nimport os\nimport warnings\nwarnings.simplefilter(\"ignore\")\nimport nemo\nfrom nemo import logging\nfrom nemo.utils.lr_policies import WarmupAnnealing\n\nimport nemo.collections.nlp as nemo_nlp\nfrom nemo.collections.nlp.data import NemoBertTokenizer\nfrom nemo.collections.nlp.nm.trainables import TokenClassifier\nfrom nemo.backends.pytorch.common.losses import CrossEntropyLossNM, LossAggregatorNM\nfrom nemo.collections.nlp.callbacks.punctuation_capitalization_callback import eval_iter_callback, eval_epochs_done_callback\nfrom nemo.collections.nlp.data.datasets.datasets_utils import calc_class_weights\n\nimport torch\nimport torch.cuda.profiler as profiler\nimport pyprof\nimport time\nimport sys\nimport datetime\n\nclass CustomSimpleLossLoggerCallback(nemo.core.SimpleLossLoggerCallback):\n \"\"\"\n For callback documentation: please see\n https://nvidia.github.io/NeMo/tutorials/callbacks.html\n \"\"\"\n\n def __init__(\n self, tensors, print_func=None, get_tb_values=None, log_to_tb_func=None, step_freq=25, tb_writer=None,\n ):\n\n super().__init__( tensors)\n if not isinstance(tensors, list):\n tensors = [tensors]\n self._tensors = tensors\n self._print_func = print_func\n self._get_tb_values = get_tb_values\n self._log_to_tb_func = log_to_tb_func\n self._step_freq = step_freq\n self._swriter = tb_writer\n self._start_time = None\n self._last_epoch_start = None\n self._last_iter_start = None\n\n @property\n def tensors(self):\n return self._tensors\n\n def on_action_start(self):\n if self.global_rank is None or self.global_rank == 0:\n logging.info(\"Starting .....\")\n self._start_time = time.time()\n\n def on_action_end(self):\n if self.global_rank is None or self.global_rank == 0:\n if self._swriter is not None:\n self._swriter.close()\n delta = datetime.timedelta(seconds=(time.time() - self._start_time))\n logging.info(\"Done in %s\", delta)\n\n def on_epoch_start(self):\n if self.global_rank is None or self.global_rank == 0:\n logging.info(f\"Starting epoch {self.epoch_num}\")\n self._last_epoch_start = time.time()\n def on_epoch_end(self):\n if self.global_rank is None or self.global_rank == 0:\n step = self.step\n\n delta = datetime.timedelta(seconds=(time.time() - self._last_epoch_start))\n logging.info(f\"Finished epoch {self.epoch_num} in {delta}\")\n\n\n def on_iteration_start(self):\n if self.step == 4:\n profiler.start()\n logging.info(f\"********************Starting profiler at step: \"+str(self.step))\n\n if self.global_rank is None or self.global_rank == 0:\n self._last_iter_start = time.time()\n\n def on_iteration_end(self):\n\n if self.step == 4:\n profiler.stop()\n logging.info(f\"********************Stopping profiler at step: \"+str(self.step))\n\n if self.global_rank is None or self.global_rank == 0:\n step = self.step\n run_time = time.time() - self._last_iter_start\n logging.info(f\"Step {self.step} time: {run_time} seconds\")\n\n\n\n\nDATA_DIR = \"/workspace/data\"\nWORK_DIR = \"/workspace/working\"\n\n# See the list of available pre-trained models by calling\n# the nemo_nlp.nm.trainables.get_bert_models_list()\nPRETRAINED_BERT_MODEL = \"bert-base-uncased\"\n\n# model parameters\nBATCHES_PER_STEP = 1\nBATCH_SIZE = 512\nCLASSIFICATION_DROPOUT = 0.1\nMAX_SEQ_LENGTH = 64\nNUM_EPOCHS = 1\nLEARNING_RATE = 0.00002\nLR_WARMUP_PROPORTION = 0.1\nOPTIMIZER = \"adam\"\nSTEP_FREQ = 200 # determines how often loss will be printed and checkpoint saved\nPUNCT_NUM_FC_LAYERS = 3\nNUM_SAMPLES = 5000\n\n# Instantiate neural factory with supported backend\nnf = nemo.core.NeuralModuleFactory(\n backend=nemo.core.Backend.PyTorch,\n\n # If you're training with multiple GPUs, you should handle this value with\n # something like argparse. See examples/nlp/token_classification.py for an example.\n local_rank=None,\n\n # If you're training with mixed precision, this should be set to mxprO1 or mxprO2.\n # See https://nvidia.github.io/apex/amp.html#opt-levels for more details.\n #optimization_level=\"O0\",\n optimization_level=\"O1\",\n \n # Define path to the directory you want to store your results\n log_dir=WORK_DIR,\n\n # If you're training with multiple GPUs, this should be set to\n # nemo.core.DeviceType.AllGpu\n placement=nemo.core.DeviceType.GPU)\n\t\n# If you're using a standard BERT model, you should do it like this. To see the full\n# list of BERT/ALBERT/RoBERTa model names, call nemo_nlp.nm.trainables.get_bert_models_list()\n\ntokenizer = NemoBertTokenizer(pretrained_model=PRETRAINED_BERT_MODEL)\nbert_model = nemo_nlp.nm.trainables.get_huggingface_model(pretrained_model_name=PRETRAINED_BERT_MODEL)\n\ntrain_data_layer = nemo_nlp.nm.data_layers.PunctuationCapitalizationDataLayer(\n tokenizer=tokenizer,\n text_file=os.path.join(DATA_DIR, 'text_train.txt'),\n label_file=os.path.join(DATA_DIR, 'labels_train.txt'),\n max_seq_length=MAX_SEQ_LENGTH,\n batch_size=BATCH_SIZE)\n\npunct_label_ids = train_data_layer.dataset.punct_label_ids\ncapit_label_ids = train_data_layer.dataset.capit_label_ids\n\n\n# Define classifier for Punctuation and Capitalization tasks\npunct_classifier = TokenClassifier(\n hidden_size=bert_model.hidden_size,\n num_classes=len(punct_label_ids),\n dropout=CLASSIFICATION_DROPOUT,\n num_layers=PUNCT_NUM_FC_LAYERS,\n name='Punctuation')\n\ncapit_classifier = TokenClassifier(\n hidden_size=bert_model.hidden_size,\n num_classes=len(capit_label_ids),\n dropout=CLASSIFICATION_DROPOUT,\n name='Capitalization')\n\n\n# If you don't want to use weighted loss for Punctuation task, use class_weights=None\npunct_label_freqs = train_data_layer.dataset.punct_label_frequencies\nclass_weights = calc_class_weights(punct_label_freqs)\n\n# define loss\npunct_loss = CrossEntropyLossNM(logits_ndim=3, weight=class_weights)\ncapit_loss = CrossEntropyLossNM(logits_ndim=3)\ntask_loss = LossAggregatorNM(num_inputs=2)\n\ninput_ids, input_type_ids, input_mask, loss_mask, subtokens_mask, punct_labels, capit_labels = train_data_layer()\n\nhidden_states = bert_model(\n input_ids=input_ids,\n token_type_ids=input_type_ids,\n attention_mask=input_mask)\n\npunct_logits = punct_classifier(hidden_states=hidden_states)\ncapit_logits = capit_classifier(hidden_states=hidden_states)\n\npunct_loss = punct_loss(\n logits=punct_logits,\n labels=punct_labels,\n loss_mask=loss_mask)\n\ncapit_loss = capit_loss(\n logits=capit_logits,\n labels=capit_labels,\n loss_mask=loss_mask)\n\ntask_loss = task_loss(\n loss_1=punct_loss,\n loss_2=capit_loss)\n\t\n\t\ncallback_train = CustomSimpleLossLoggerCallback(\n tensors=[task_loss, punct_loss, capit_loss, punct_logits, capit_logits],\n print_func=lambda x: logging.info(\"Loss: {:.3f}\".format(x[0].item())),\n step_freq=STEP_FREQ)\n\ntrain_data_size = len(train_data_layer)\n\n# If you're training on multiple GPUs, this should be\n# train_data_size / (batch_size * batches_per_step * num_gpus)\nsteps_per_epoch = int(train_data_size / (BATCHES_PER_STEP * BATCH_SIZE))\nprint ('Number of steps per epoch: ', steps_per_epoch)\n\n# Callback to evaluate the model\n#callback_eval = nemo.core.EvaluatorCallback(\n# eval_tensors=[eval_punct_logits,\n# eval_capit_logits,\n# eval_punct_labels,\n# eval_capit_labels,\n# eval_subtokens_mask],\n# user_iter_callback=lambda x, y: eval_iter_callback(x, y),\n# user_epochs_done_callback=lambda x: eval_epochs_done_callback(x,\n# punct_label_ids,\n# capit_label_ids),\n# eval_step=steps_per_epoch)\n\n# Callback to store checkpoints\n#ckpt_callback = nemo.core.CheckpointCallback(\n# folder=nf.checkpoint_dir,\n# step_freq=STEP_FREQ)\n\t\n\t\nlr_policy = WarmupAnnealing(NUM_EPOCHS * steps_per_epoch,\n warmup_ratio=LR_WARMUP_PROPORTION)\n\npyprof.init()\n\nwith torch.autograd.profiler.emit_nvtx():\n\n nf.train(tensors_to_optimize=[task_loss],\n callbacks=[callback_train],\n lr_policy=lr_policy,\n batches_per_step=BATCHES_PER_STEP,\n optimizer=OPTIMIZER,\n optimization_params={\"num_epochs\": NUM_EPOCHS,\n \"lr\": LEARNING_RATE})\n\n\n","sub_path":"notebooks/punctuation_pyprof_o1.py","file_name":"punctuation_pyprof_o1.py","file_ext":"py","file_size_in_byte":9345,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"10589263","text":"#!/usr/bin/python\nfrom eye import get_eye_data\nimport time\nimport scrollphathd\nIMAGE_BRIGHTNESS = .6\n\nROLL = get_eye_data(\"roll\")\nROLL_REVERSE = ROLL[::-1]\ndef roll():\n for data in ROLL:\n for x in range(0, scrollphathd.DISPLAY_WIDTH):\n for y in range(0, scrollphathd.DISPLAY_HEIGHT):\n brightness = data[x][y]\n scrollphathd.pixel(x, y, brightness * IMAGE_BRIGHTNESS)\n scrollphathd.show()\n time.sleep(0.01)","sub_path":"examples/fannypack/roll.py","file_name":"roll.py","file_ext":"py","file_size_in_byte":437,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"370093890","text":"# -*- coding: utf-8 -*-\n# pylint: disable=invalid-name,missing-docstring\n\n# Copyright 2017 IBM RESEARCH. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# =============================================================================\n\n\"\"\"Quick program to test json backend\n\"\"\"\nimport unittest\n\nfrom qiskit import qasm, unroll, QuantumProgram\n\nfrom .common import QiskitTestCase, Path\n\n\nclass TestJsonOutput(QiskitTestCase):\n \"\"\"Test Json output.\n\n This is mostly covered in test_quantumprogram.py but will leave\n here for convenience.\n \"\"\"\n def setUp(self):\n self.QASM_FILE_PATH = self._get_resource_path(\n 'qasm/entangled_registers.qasm', Path.EXAMPLES)\n\n def test_json_output(self):\n seed = 88\n qp = QuantumProgram()\n qp.load_qasm_file(self.QASM_FILE_PATH, name=\"example\")\n\n basis_gates = [] # unroll to base gates, change to test\n unroller = unroll.Unroller(qasm.Qasm(data=qp.get_qasm(\"example\")).parse(),\n unroll.JsonBackend(basis_gates))\n circuit = unroller.execute()\n self.log.info('test_json_ouptut: {0}'.format(circuit))\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"test/python/test_jsonoutput.py","file_name":"test_jsonoutput.py","file_ext":"py","file_size_in_byte":1716,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"347108250","text":"import docutils.nodes\nimport re\nimport nbformat.v4\nimport os.path\nimport datetime\nfrom .utils import LanguageTranslator, JupyterOutputCellGenerators, get_source_file_name\n\nclass JupyterCodeTranslator(docutils.nodes.GenericNodeVisitor):\n\n URI_SPACE_REPLACE_FROM = re.compile(r\"\\s\")\n URI_SPACE_REPLACE_TO = \"-\"\n\n def __init__(self, builder, document):\n docutils.nodes.NodeVisitor.__init__(self, document)\n\n self.lang = None\n self.nodelang = None\n self.visit_first_title = True\n\n self.langTranslator = LanguageTranslator(builder.config[\"templates_path\"])\n\n # Reporter\n self.warn = self.document.reporter.warning\n self.error = self.document.reporter.error\n\n # Settings\n self.settings = document.settings\n self.builder = builder\n self.source_file_name = get_source_file_name(\n self.settings._source,\n self.settings.env.srcdir)\n self.default_lang = builder.config[\"jupyter_default_lang\"]\n\n # Create output notebook\n self.output = nbformat.v4.new_notebook()\n\n # Variables defined in conf.py\n self.jupyter_static_file_path = builder.config[\"jupyter_static_file_path\"]\n self.jupyter_kernels = builder.config[\"jupyter_kernels\"]\n self.jupyter_write_metadata = builder.config[\"jupyter_write_metadata\"]\n self.jupyter_drop_solutions = builder.config[\"jupyter_drop_solutions\"]\n self.jupyter_drop_tests = builder.config[\"jupyter_drop_tests\"]\n self.jupyter_ignore_no_execute = builder.config[\"jupyter_ignore_no_execute\"]\n self.jupyter_ignore_skip_test = builder.config[\"jupyter_ignore_skip_test\"]\n self.jupyter_lang_synonyms = builder.config[\"jupyter_lang_synonyms\"]\n self.jupyter_target_html = builder.config[\"jupyter_target_html\"]\n self.jupyter_download_nb_image_urlpath = builder.jupyter_download_nb_image_urlpath\n self.jupyter_images_markdown = builder.config[\"jupyter_images_markdown\"]\n self.jupyter_target_pdf = builder.config[\"jupyter_target_pdf\"]\n self.jupyter_pdf_showcontentdepth = builder.config[\"jupyter_pdf_showcontentdepth\"]\n self.jupyter_pdf_book = builder.config[\"jupyter_pdf_book\"]\n self.book_index = builder.config[\"jupyter_pdf_book_index\"]\n if hasattr(builder, 'add_bib_to_latex'):\n self.add_bib_to_latex = builder.add_bib_to_latex\n\n # set the value of the cell metadata[\"slideshow\"] to slide as the default option\n self.slide = \"slide\" \n self.metadata_slide = False #value by default for all the notebooks, we change it for those we want\n\n\n # Header Block\n template_paths = builder.config[\"templates_path\"]\n header_block_filename = builder.config[\"jupyter_header_block\"]\n\n full_path_to_header_block = None\n for template_path in template_paths:\n if header_block_filename:\n if os.path.isfile(template_path + \"/\" + header_block_filename):\n full_path_to_header_block = os.path.normpath( template_path + \"/\" + header_block_filename)\n\n if full_path_to_header_block:\n with open(full_path_to_header_block) as input_file:\n lines = input_file.readlines()\n\n line_text = \"\".join(lines)\n formatted_line_text = self.strip_blank_lines_in_end_of_block(\n line_text)\n nb_header_block = nbformat.v4.new_markdown_cell(\n formatted_line_text)\n\n # Add the header block to the output stream straight away\n self.output[\"cells\"].append(nb_header_block)\n\n # Write metadata\n if self.jupyter_write_metadata:\n meta_text = \\\n \"Notebook created: {:%Y-%m-%d %H:%M:%S} \\n\"\\\n \"Generated from: {} \"\n\n metadata = meta_text.format(\n datetime.datetime.now(),\n self.source_file_name)\n\n self.output[\"cells\"].append(\n nbformat.v4.new_markdown_cell(metadata))\n\n # Variables used in visit/depart\n self.in_code_block = False # if False, it means in markdown_cell\n self.output_cell_type = None\n self.code_lines = []\n\n # generic visit and depart methods\n # --------------------------------\n simple_nodes = (\n docutils.nodes.TextElement,\n docutils.nodes.image,\n docutils.nodes.colspec,\n docutils.nodes.transition) # empty elements\n\n def default_visit(self, node):\n pass\n\n def default_departure(self, node):\n pass\n\n # specific visit and depart methods\n # ---------------------------------\n\n # =========\n # Sections\n # =========\n def visit_document(self, node):\n \"\"\"at start\n \"\"\"\n # we need to give the translator a default language!\n # the translator needs to know what language the document is written in\n # before depart_document is called.\n self.lang = self.default_lang\n\n def depart_document(self, node):\n \"\"\"at end\n \"\"\"\n if not self.lang:\n self.warn(\n \"Highlighting language is not given in .rst file. \"\n \"Set kernel as default(python3)\")\n self.lang = self.default_lang\n\n # metadata for slides, this activates the option where each cell can be a slide\n if self.metadata_slide:\n self.output.metadata.celltoolbar = \"Slideshow\"\n\n\n # Update metadata\n if self.jupyter_kernels is not None:\n try:\n self.output.metadata.kernelspec = \\\n self.jupyter_kernels[self.lang][\"kernelspec\"]\n self.output.metadata[\"filename\"] = self.source_file_name.split(\"/\")[-1]\n self.output.metadata[\"title\"] = self.title\n except:\n self.warn(\n \"Invalid jupyter kernels. \"\n \"jupyter_kernels: {}, lang: {}\"\n .format(self.jupyter_kernels, self.lang))\n\n def visit_highlightlang(self, node):\n lang = node.attributes[\"lang\"].strip()\n if lang in self.jupyter_kernels:\n self.lang = lang\n else:\n self.warn(\n \"Highlighting language({}) is not defined \"\n \"in jupyter_kernels in conf.py. \"\n \"Set kernel as default({})\"\n .format(lang, self.default_lang))\n self.lang = self.default_lang\n\n # =================\n # Inline elements\n # =================\n def visit_Text(self, node):\n text = node.astext()\n if self.in_code_block:\n self.code_lines.append(text)\n\n def depart_Text(self, node):\n pass\n\n def visit_title(self, node):\n #TODO: add support for docutils .. title::\n if self.visit_first_title:\n self.title = node.astext()\n self.visit_first_title = False\n \n # ================\n # code blocks\n # ================\n def visit_literal_block(self, node):\n _parse_class = JupyterOutputCellGenerators.GetGeneratorFromClasses(self, node)\n self.output_cell_type = _parse_class[\"type\"]\n self.solution = _parse_class[\"solution\"]\n self.test = _parse_class[\"test\"]\n\n try:\n self.nodelang = node.attributes[\"language\"].strip()\n except KeyError:\n self.nodelang = self.lang\n if self.nodelang == 'default':\n self.nodelang = self.lang\n\n # Translate the language name across from the Sphinx to the Jupyter namespace\n self.nodelang = self.langTranslator.translate(self.nodelang)\n\n self.in_code_block = True\n self.code_lines = []\n\n # If the cell being processed contains code written in a language other than the one that\n # was specified as the default language, do not create a code block for it - turn it into\n # markup instead.\n if self.nodelang != self.langTranslator.translate(self.lang):\n if self.nodelang in self.jupyter_lang_synonyms:\n pass\n else:\n self.output_cell_type = JupyterOutputCellGenerators.MARKDOWN\n\n def depart_literal_block(self, node):\n if self.solution and self.jupyter_drop_solutions: \n pass # Skip solutions if we say to. \n elif self.test and self.jupyter_drop_tests:\n pass # Skip tests if we say to.\n else: # Don't skip otherwise. \n line_text = \"\".join(self.code_lines)\n formatted_line_text = self.strip_blank_lines_in_end_of_block(line_text)\n new_code_cell = self.output_cell_type.Generate(formatted_line_text, self)\n\n # add slide metadata on each cell, value by default: slide\n if self.metadata_slide: #value by default for all the notebooks, we change it for those we want\n new_code_cell.metadata[\"slideshow\"] = { 'slide_type': self.slide}\n self.slide = \"slide\"\n #Save Collapse Cell Option for HTML Parser\n if \"collapse\" in node[\"classes\"]:\n new_code_cell[\"metadata\"][\"html-class\"] = 'collapse'\n #Save hide-output cell option for HTML Parser\n if \"hide-output\" in node[\"classes\"]:\n new_code_cell[\"metadata\"][\"hide-output\"] = True\n else:\n new_code_cell[\"metadata\"][\"hide-output\"] = False\n #Code Output\n if self.output_cell_type is JupyterOutputCellGenerators.CODE_OUTPUT:\n # Output blocks must be added to code cells to make any sense.\n # This script assumes that any output blocks will immediately follow a code\n # cell; a warning is raised if the cell immediately preceding this output\n # block is not a code cell.\n #\n # It is assumed that code cells may only have one output block - any more than\n # one will raise a warning and be ignored.\n mostRecentCell = self.output[\"cells\"][-1]\n if mostRecentCell.cell_type != \"code\":\n self.warn(\"Warning: Class: output block found after a \" +\n mostRecentCell.cell_type + \" cell. Outputs may only come after code cells.\")\n elif mostRecentCell.outputs:\n self.warn(\n \"Warning: Multiple class: output blocks found after a code cell. Each code cell may only be followed by either zero or one output blocks.\")\n else:\n mostRecentCell.outputs.append(new_code_cell)\n else:\n self.output[\"cells\"].append(new_code_cell)\n\n self.in_code_block = False\n\n # ===================\n # general methods\n # ===================\n @staticmethod\n def strip_blank_lines_in_end_of_block(line_text):\n lines = line_text.split(\"\\n\")\n\n for line in range(len(lines)):\n if len(lines[-1].strip()) == 0:\n lines = lines[:-1]\n else:\n break\n\n return \"\\n\".join(lines)\n\n","sub_path":"sphinxcontrib/jupyter/writers/translate_code.py","file_name":"translate_code.py","file_ext":"py","file_size_in_byte":11080,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"133549894","text":"import csv, sys\n\nif (len(sys.argv) != 6):\n\tprint(\"format: python3 join_csv.py OUT-FILE FILE-1 KEY-INDEX-1 FILE-2 KEY-INDEX-2\")\n\texit()\n\nwith open(sys.argv[2], 'rb') as file:\n\n\treader = csv.reader(file, delimiter=\",\", quotechar='\"')\n\t\n\twith open(sys.argv[4]) as file2:\n\t\t\n\t\treader2 = csv.reader(file2, delimiter=\",\", quotechar='\"')\n\n\t\tfor a1 in reader:\n\t\t\t\n\t\t\tfor a2 in reader2:\n\t\t\t\ta = reader[a1]\n\t\t\t\taa = reader[a2]\n\t\t\t\tif a[int(sys.argv[3])] == aa[int(sys.argv[5])]:\n\t\t\t\t\t\n\t\t\t\t\ta.extend(aa[int(sys.argv[5])+1:])\n\n\t\t\t\t\twith open(sys.argv[1], 'wb') as csvfile:\n\t\t\t\t\t\tprint(reader)\n\t\t\t\t\t\tspamwriter = csv.writer(csvfile, delimiter=',',\n\t\t\t\t\t\t\t\t\t\t\tquotechar='\"', quoting=csv.QUOTE_MINIMAL)\n\n\t\t\t\t\t\tspamwriter.writerow(a)\n\t\t\t\t\t\t\n\t\t\t\t\tcontinue\n\n\n","sub_path":"join_csv.py","file_name":"join_csv.py","file_ext":"py","file_size_in_byte":741,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"524439529","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n# ~ Author: Pavel Ivanov\n\nfrom flask import Blueprint\nfrom flask_httpauth import HTTPTokenAuth\nfrom flask_server import jsonrpc\nfrom flask_server import db\n\nfrom sqlalchemy.orm import exc\n\nfrom exceptions import flask as flask_exc\n\nfrom models.session import Session\nfrom models import scenario as scn\n\n\nmod_auth = Blueprint('auth', __name__)\nauth = HTTPTokenAuth(scheme='WWWToken')\njsonrpc.register_blueprint(mod_auth)\n\n\n@auth.verify_token\ndef verify_token(token):\n \"\"\"Верификация токена авторизации\n\n \"\"\"\n return Session.get_active(token) is not None\n\n\n@jsonrpc.method(\"Scenario.create(caption=String, scenario_data=Object) -> Object\", validate=True)\n@auth.login_required\ndef scenario_create(caption, scenario_data):\n \"\"\" Создание сценария\n\n :param caption: str\n :param scenario_data: dict\n :return: dict\n \"\"\"\n scenario = scn.Scenario(caption)\n\n valid_properties = ['caption', 'text', 'for_queue', 'parent_id']\n\n for prop, value in scenario_data.items():\n if prop not in valid_properties:\n raise flask_exc.InvalidProperty(\"Invalid property %r\" % prop)\n\n setattr(scenario, prop, value)\n\n db.session.add(scenario)\n db.session.commit()\n\n return {\n \"id\": scenario.id,\n \"caption\": str(scenario),\n }\n\n\n@jsonrpc.method(\"Scenario.edit(scenario_id=Number, scenario_data=Object) -> Object\", validate=True)\n@auth.login_required\ndef scenario_edit(scenario_id, scenario_data):\n \"\"\" Редактирование сценария\n\n :param scenario_id:\n :param scenario_data:\n :return:\n \"\"\"\n try:\n scenario = scn.Scenario.query.filter(scn.Scenario.id == scenario_id).one()\n except exc.NoResultFound:\n raise flask_exc.ObjectDoesNotExist\n\n valid_properties = ['caption', 'text', 'for_queue', 'parent_id']\n\n for prop, value in scenario_data.items():\n if prop not in valid_properties:\n raise flask_exc.InvalidProperty(\"Invalid property %r\" % prop)\n\n setattr(scenario, prop, value)\n\n db.session.commit()\n\n return {\n \"id\": scenario.id,\n \"caption\": scenario.caption,\n \"text\": scenario.text,\n \"for_queue\": scenario.for_queue,\n \"parent_id\": scenario.parent_id,\n }\n\n\n@jsonrpc.method(\"Scenario.remove(scenario_id=Number)\", validate=True)\n@auth.login_required\ndef scenario_remove(scenario_id):\n \"\"\" Удаление сценария\n\n :param scenario_id: int\n :return: None\n \"\"\"\n try:\n scenario = scn.Scenario.query.filter(scn.Scenario.id == scenario_id).one()\n except exc.NoResultFound:\n raise flask_exc.ObjectDoesNotExist\n\n db.session.delete(scenario)\n db.session.commit()\n\n\n@jsonrpc.method(\"Scenario.tree() -> Array\")\n@auth.login_required\ndef scenario_tree():\n \"\"\" Возвращает дерево сценариев\n\n :return: list\n \"\"\"\n return [{\n \"id\": scenario.id,\n \"parent\": scenario.parent_id or \"#\",\n \"text\": str(scenario),\n \"state\": {\n \"opened\": True,\n }\n } for scenario in scn.Scenario.query.all()]\n\n\n@jsonrpc.method(\"Scenario.get_by_queue(queue_name=String) -> Object\", validate=True)\n@auth.login_required\ndef scenario_get_by_queue(queue_name):\n \"\"\" Возвращает заголовок и текст сценария по названию очереди\n\n :param queue_name: str\n :return: dict\n \"\"\"\n try:\n scenario = scn.Scenario.query.filter(scn.Scenario.for_queue == queue_name).limit(1).one()\n except exc.NoResultFound:\n return\n\n return {\n \"caption\": scenario.caption,\n \"text\": scenario.text,\n }\n\n\n@jsonrpc.method(\"Scenario.get_by_id(scenario_id=Number) -> Object\", validate=True)\n@auth.login_required\ndef scenario_get_by_id(scenario_id):\n \"\"\" Возвращает заголовок и текст сценария по ID\n\n :param scenario_id: int\n :return:\n \"\"\"\n try:\n scenario = scn.Scenario.query.filter(scn.Scenario.id == scenario_id).one()\n except exc.NoResultFound:\n return\n\n return {\n \"caption\": scenario.caption,\n \"text\": scenario.text,\n }\n\n\n@jsonrpc.method(\"Scenario.get_data(scenario_id=Number) -> Object\", validate=True)\n@auth.login_required\ndef scenario_get_data(scenario_id):\n \"\"\" Возвращает данные по сценарию\n\n :param scenario_id: int\n :return: dict\n \"\"\"\n try:\n scenario = scn.Scenario.query.filter(scn.Scenario.id == scenario_id).one()\n except exc.NoResultFound:\n raise flask_exc.ObjectDoesNotExist\n\n return {\n \"id\": scenario.id,\n \"caption\": scenario.caption,\n \"text\": scenario.text,\n \"for_queue\": scenario.for_queue,\n \"parent_id\": scenario.parent_id,\n }\n","sub_path":"controllers/scenario.py","file_name":"scenario.py","file_ext":"py","file_size_in_byte":4854,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"19450368","text":"import math\n#算度数,最大度数的log\nf1=open('coraall_fac1.txt','w')\nsu=1\nf={}\nfac=1\n\nfor fac in range(1,71825):\n #print(fac)\n su=fac*su\n #f[fac]=su\n a=math.log(su)\n f1.write(str(fac))\n f1.write(\" \")\n f1.write(str(a))\n f1.write(\"\\n\")\nf1.close()\n\n#n=3\n#x=math.sqrt(2*math.pi*n) *math.pow(n/math.exp(1),n)\n#x=0.5*math.log(2*math.pi*n,10)+n*math.log(n/math.exp(1),10)\n#y=math.exp(1) 40634\n#y=math.log(100,10)\n#y=math.log(100,10)\n#print(y)\n#print(x)\n'''\nf2=open('fac1.txt','r')\nfac={}\nfac[0]=1\nfor line in f2.readlines():\n line=line.strip()\n s=line.split()\n fac[int(s[0])]=float(s[1])\nf2.close()\n\n#a=math.exp(fac[1000])\n#print(math.exp(fac[23332]))\nz=math.pow(2,3)\nprint(z)\nx=10\na=math.log(math.e)\nb=math.exp(a)\nprint(a)\nprint(b)\n'''","sub_path":"node/test4.py","file_name":"test4.py","file_ext":"py","file_size_in_byte":771,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"467663275","text":"from __future__ import print_function\nimport argparse\n\nimport chainer\nimport chainer.functions as F\nimport chainer.links as L\nfrom chainer import training, iterators, serializers, optimizers\nfrom chainer.training import extensions\n\nfrom CNNSmall import CNNSmall\nfrom CNNMedium import CNNMedium\n\n\ndef main():\n archs = {\n 'cnnsmall': CNNSmall,\n 'cnnmedium': CNNMedium,\n }\n\n parser = argparse.ArgumentParser(description='Cifar-10 CNN example')\n parser.add_argument('--arch', '-a', choices=archs.keys(),\n default='cnnsmall', help='Convnet architecture')\n parser.add_argument('--batchsize', '-b', type=int, default=64,\n help='Number of images in each mini-batch')\n parser.add_argument('--epoch', '-e', type=int, default=20,\n help='Number of sweeps over the dataset to train')\n parser.add_argument('--gpu', '-g', type=int, default=-1,\n help='GPU ID (negative value indicates CPU)')\n parser.add_argument('--out', '-o', default='result-cifar10',\n help='Directory to output the result')\n parser.add_argument('--resume', '-r', default='',\n help='Resume the training from snapshot')\n args = parser.parse_args()\n\n print('GPU: {}'.format(args.gpu))\n print('# Minibatch-size: {}'.format(args.batchsize))\n print('# epoch: {}'.format(args.epoch))\n print('')\n\n # 1. Setup model\n class_num = 10\n model = archs[args.arch](n_out=class_num)\n classifier_model = L.Classifier(model)\n if args.gpu >= 0:\n chainer.cuda.get_device(args.gpu).use() # Make a specified GPU current\n classifier_model.to_gpu() # Copy the model to the GPU\n\n # 2. Setup an optimizer\n optimizer = optimizers.Adam()\n optimizer.setup(classifier_model)\n\n # 3. Load the CIFAR-10 dataset\n train, test = chainer.datasets.get_cifar10()\n\n # 4. Setup an Iterator\n train_iter = iterators.SerialIterator(train, args.batchsize)\n test_iter = iterators.SerialIterator(test, args.batchsize,\n repeat=False, shuffle=False)\n\n # 5. Setup an Updater\n updater = training.StandardUpdater(train_iter, optimizer, device=args.gpu)\n # 6. Setup a trainer (and extensions)\n trainer = training.Trainer(updater, (args.epoch, 'epoch'), out=args.out)\n\n # Evaluate the model with the test dataset for each epoch\n trainer.extend(extensions.Evaluator(test_iter, classifier_model, device=args.gpu))\n\n trainer.extend(extensions.dump_graph('main/loss'))\n trainer.extend(extensions.snapshot(), trigger=(1, 'epoch'))\n trainer.extend(extensions.LogReport())\n trainer.extend(extensions.PrintReport(\n ['epoch', 'main/loss', 'validation/main/loss',\n 'main/accuracy', 'validation/main/accuracy', 'elapsed_time']))\n trainer.extend(extensions.PlotReport(\n ['main/loss', 'validation/main/loss'],\n x_key='epoch', file_name='loss.png'))\n trainer.extend(extensions.PlotReport(\n ['main/accuracy', 'validation/main/accuracy'],\n x_key='epoch',\n file_name='accuracy.png'))\n\n trainer.extend(extensions.ProgressBar())\n\n # Resume from a snapshot\n if args.resume:\n serializers.load_npz(args.resume, trainer)\n\n # Run the training\n trainer.run()\n serializers.save_npz('{}/{}-cifar10.model'\n .format(args.out, args.arch), model)\n\nif __name__ == '__main__':\n main()\n\n\n","sub_path":"src/04_cifar_cnn/train_cifar10.py","file_name":"train_cifar10.py","file_ext":"py","file_size_in_byte":3480,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"136098643","text":"import turtle\nimport urllib.request\nimport time\nturtle.speed(6)\n\n#istiklal marşı ilk başlık ve ilk iki kıtası intenetten alınıyor\nbaglanti=\"https://raw.githubusercontent.com/ibrahim-kasalak/codeweek2020/main/istiklal_marsi.txt\"\ndosya = urllib.request.urlopen(baglanti)\nmars=dosya.readlines()\n\n#bayrak için uygun konuma gidiliyor\nturtle.Screen().setup(800,600)\nturtle.shape(\"turtle\")\nturtle.penup()\nturtle.goto(-300,100)\nturtle.pendown()\nturtle.color(\"red\")\n#dikdörtgen\nturtle.begin_fill()\nfor i in range(2):\n turtle.forward(200)\n turtle.left(90)\n turtle.forward(100)\n turtle.left(90)\nturtle.end_fill()\nturtle.penup()\nturtle.goto(-240,120)\nturtle.color(\"white\")\n#hilal\nturtle.begin_fill()\nturtle.circle(30)\nturtle.end_fill()\nturtle.goto(-230,125)\nturtle.pendown()\nturtle.color(\"red\")\nturtle.begin_fill()\nturtle.circle(25)\nturtle.end_fill()\nturtle.penup()\nturtle.goto(-220,145)\nturtle.pendown()\nturtle.color(\"white\")\nturtle.begin_fill()\n#yıldız\nfor i in range(5):\n turtle.forward(30)\n turtle.left(144)\nturtle.end_fill()\n\nturtle.penup()\nturtle.color(\"red\")\nturtle.goto(100,200)\n#istiklal marşı yazılıyor\nx,y=turtle.position()\nfor misra in mars:\n turtle.write(misra.decode(\"utf-8\"), align=\"center\", font=(\"Times New Roman\",14,\"italic\"))\n time.sleep(1)\n y-=30\n turtle.goto(x,y)\n\nturtle.hideturtle()\nturtle.done()\nturtle.mainloop()\n","sub_path":"istiklal_marsi.py","file_name":"istiklal_marsi.py","file_ext":"py","file_size_in_byte":1372,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"562845708","text":"from collections import defaultdict\nclass Solution:\n def findOrder(self, numCourses: int, prerequisites: List[List[int]]) -> List[int]:\n def Helper(idx):\n if idx in visited:\n return True\n if idx in inStack:\n return False\n inStack.add(idx)\n for nhbr in dictn[idx]:\n if not Helper(nhbr):\n return False\n \n inStack.remove(idx)\n visited.add(idx)\n stack.append(idx)\n return True\n \n dictn = defaultdict(list)\n for i in prerequisites:\n dictn[i[1]].append(i[0])\n visited = set()\n inStack = set()\n stack = []\n for idx in range(numCourses):\n if idx not in visited:\n if not Helper(idx):\n return []\n return stack[::-1]\n","sub_path":"accepted_codes/Course_Schedule_II/Course Schedule II_294164593.py","file_name":"Course Schedule II_294164593.py","file_ext":"py","file_size_in_byte":900,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"613381937","text":"import GPyOpt as gpt\nimport numpy as np\nfrom numpy.random import seed\n\n# Global Variables Declaration\n_bounds_list = []\n_epsilon = 2\n_iter_count_opt = 30\n_iter_count_cutoff = 20\n_founded_minima_list = []\n_rounding_constant = 1\n_omitted_regions = []\n# dimension\n_dimension = 2\n\n\n# The black box function\ndef fn_my_black_box_function(parameter_values):\n y = -abs(np.sin(parameter_values[0]) * np.cos(parameter_values[1]) * np.exp(\n abs(1 - (np.sqrt(parameter_values[0] ** 2 + parameter_values[1] ** 2)) / np.pi))) # HolderTableFunction\n return y\n\n\n# This is called during actual sampling for finding the global minima\ndef fn_call_black_box_function_1(bounds):\n parameter_values = []\n for i in range(_dimension):\n parameter_values.append(bounds[0][i])\n result = fn_my_black_box_function(parameter_values)\n return result\n\n\n# This function is called while finding the nearest point where function becomes zero\n# The observation is sent as a square of the function to maintain continuity\ndef fn_call_black_box_function_2(bounds):\n parameter_values = []\n for i in range(_dimension):\n parameter_values.append(bounds[0][i])\n result = fn_my_black_box_function(parameter_values)\n return result ** 2\n\n\n# Bayesian Optimization module for finding the global minima within the given bounds\ndef fn_bayesian_optimization(lower_upper_bound_list):\n global _iter_count_opt\n value_list = []\n for i in range(_dimension):\n dict_value = {'name': 'x' + str(i), 'type': 'continuous',\n 'domain': (lower_upper_bound_list[i][0], lower_upper_bound_list[i][1])}\n value_list.append(dict_value)\n bounds = value_list\n my_problem = gpt.methods.BayesianOptimization(fn_call_black_box_function_1, # function to optimize\n bounds, # box-constraints of the problem\n acquisition_type='EI',\n exact_feval=True) # Selects the Expected improvement\n max_iter = _iter_count_opt\n max_time = 1000 # time budget\n eps = 10e-10 # Minimum allowed distance between the last two observations\n\n my_problem.run_optimization(max_iter, max_time, eps)\n _founded_minima_list.append((my_problem.x_opt[0], my_problem.x_opt[1], my_problem.fx_opt))\n print(\"Found \" + str(len(_founded_minima_list)) + \"th minimum point====== (\" + str(my_problem.x_opt[0]) + \",\" + str(\n my_problem.x_opt[1]) + \",\" + str(my_problem.fx_opt) + \")\")\n return my_problem.x_opt, my_problem.fx_opt\n\n\n# Bayesian Optimization for finding the cutoff points within the given modules\ndef fn_find_cutoffs(lower_upper_bound_list, str_side):\n global _iter_count_cutoff\n value_list = []\n for i in range(_dimension):\n dict_value = {'name': 'x' + str(i), 'type': 'continuous',\n 'domain': (lower_upper_bound_list[i][0], lower_upper_bound_list[i][1])}\n value_list.append(dict_value)\n bounds = value_list\n my_problem = gpt.methods.BayesianOptimization(fn_call_black_box_function_2, # function to optimize\n bounds, # box-constraints of the problem\n acquisition_type='EI',\n exact_feval=True) # Selects the Expected improvement\n max_iter = _iter_count_cutoff\n max_time = 1000 # time budget\n eps = 10e-10 # Minimum allowed distance between the last two observations\n\n my_problem.run_optimization(max_iter, max_time, eps)\n print(\"Found \" + str_side + \"th iteration) zero point at parameters===\" + str(\n my_problem.x_opt) + \"with function values==\" + str(my_problem.fx_opt))\n return my_problem.x_opt\n\n\ndef fn_my_controller():\n global _bounds_list, _epsilon, _omitted_regions\n while True:\n print(\"Stack : (\" + str(len(_bounds_list)) + \") >> \" + str(_bounds_list))\n if len(_bounds_list) == 0:\n break\n dimension_bounds = _bounds_list[-1]\n del _bounds_list[-1]\n print(\"Current exploring range : \" + str(dimension_bounds))\n minimum_point, minimum_value = fn_bayesian_optimization(dimension_bounds)\n # Skip if minimum value very close to zero\n if round(minimum_value) >= 1:\n continue\n new_region_list = []\n dim_zero_points_list = []\n omitted_list = []\n for i in range(_dimension):\n # Left search for dimension i\n left_zero_point = fn_max((minimum_point[i] - _epsilon), dimension_bounds[i][0])\n left_zero_point_prev = left_zero_point\n count_left = 1\n # create the lower upper bound list where bounds are same for every other dimension except i\n lower_upper_bound_list_left = []\n for j in range(_dimension):\n if j != i:\n lower_upper_bound_list_left.append((minimum_point[j], minimum_point[j]))\n else:\n lower_upper_bound_list_left.append((left_zero_point, minimum_point[j]))\n while True:\n left_zero_point_1 = fn_find_cutoffs(lower_upper_bound_list_left,\n str('left ' + str(i) + ' (' + str(count_left)))\n left_zero_point = left_zero_point_1[i]\n if round(left_zero_point_prev, _rounding_constant) == round(left_zero_point, _rounding_constant):\n break\n else:\n left_zero_point_prev = left_zero_point\n count_left = count_left + 1\n\n # left side for i dimension (Region 1)\n zero_list_left = []\n for j in range(0, i):\n zero_list_left.append(dim_zero_points_list[j])\n zero_list_left.append((dimension_bounds[i][0], left_zero_point))\n for j in range(i + 1, _dimension):\n zero_list_left.append((dimension_bounds[j][0], dimension_bounds[j][1]))\n\n new_region_list.append(zero_list_left)\n\n # Right search for dimension i\n right_zero_point = fn_min((minimum_point[i] + _epsilon), dimension_bounds[i][1])\n right_zero_point_prev = right_zero_point\n count_right = 1\n lower_upper_bound_list_right = []\n for j in range(_dimension):\n if j != i:\n lower_upper_bound_list_right.append((minimum_point[j], minimum_point[j]))\n else:\n lower_upper_bound_list_right.append((minimum_point[j], right_zero_point))\n while True:\n\n right_zero_point_1 = fn_find_cutoffs(lower_upper_bound_list_right,\n str('right ' + str(i) + ' (' + str(count_right)))\n right_zero_point = right_zero_point_1[i]\n if round(right_zero_point_prev, _rounding_constant) == round(right_zero_point, _rounding_constant):\n break\n else:\n right_zero_point_prev = right_zero_point\n count_right = count_right + 1\n\n # right side for i dimension (Region 1)\n zero_list_right = []\n for j in range(0,i):\n zero_list_right.append(dim_zero_points_list[j])\n zero_list_right.append((right_zero_point, dimension_bounds[i][1]))\n for j in range(i + 1, _dimension):\n zero_list_right.append((dimension_bounds[j][0], dimension_bounds[j][1]))\n\n new_region_list.append(zero_list_right)\n omitted_list.append((left_zero_point, right_zero_point))\n dim_zero_points_list.append((left_zero_point, right_zero_point))\n print(\"=========omitted_list\"+str(omitted_list))\n\n print(\"Region list :\" + str(new_region_list))\n _omitted_regions.append(omitted_list)\n # Check if a zero region belongs to omitted list\n\n for k in range(len(new_region_list)):\n # Region k\n flag = 0\n print(\"RegionA : \" + str(new_region_list[k]))\n for j in range(_dimension):\n if round(new_region_list[k][j][0]) == round(new_region_list[k][j][1]):\n flag = 1\n print(\"AB: 1\")\n break\n if fn_check_ommited_regions(new_region_list[k]):\n flag = 1\n print(\"AB: 2\")\n if flag == 0:\n _bounds_list.append(new_region_list[k])\n print(\"RegionB : \" + str(new_region_list[k]))\n\n\n\ndef fn_max(num1, num2):\n if num1 > num2:\n return num1\n else:\n return num2\n\n\ndef fn_min(num1, num2):\n if num1 < num2:\n return num1\n else:\n return num2\n\n\ndef fn_check_ommited_regions(check_region):\n global _omitted_regions\n _flag = 0\n for region in _omitted_regions:\n _flag = 0\n for i in range(_dimension):\n print(str(round(region[i][0])) + '===' + str(round(check_region[i][0])) + '==' + str(round(region[i][1])) + '===' + str(round(check_region[i][1])))\n if (round(region[i][0]) <= round(check_region[i][0]) and round(region[i][1]) >= round(check_region[i][1])):\n _flag = 1\n else:\n _flag = 0\n break\n if _flag == 1:\n return True\n return False\n\n\nif __name__ == '__main__':\n seed(123)\n _bounds_list.append([(-10, 10), (-10, 10)])\n fn_my_controller()\n print(str(_founded_minima_list))\n print(\"Ommitted Regions list===\" + str(_omitted_regions))\n\n","sub_path":"Visualizations/FindMultipleMinima.py","file_name":"FindMultipleMinima.py","file_ext":"py","file_size_in_byte":9634,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"406576758","text":"import matplotlib.pyplot as plt\nimport numpy as np\nimport uncertainties.unumpy as unp\nimport os, platform,sys\nfrom scipy.optimize import curve_fit\n#functions\nimport stuff.get.data as data\n\n\n\n\ndef avg(lng,x):\n z=0\n sum=0\n if lng<=1:\n sum=x[0]\n elif lng>1:\n while lng > z:\n sum=sum+x[z]\n z=z+1\n sum=sum/lng\n return sum\n\ndef sgm(lng,avg,x):\n z=0\n siegma=0\n while lng>z:\n siegma=siegma+((avg-x[z])**2)\n z=z+1\n siegma=siegma/(lng-1)\n siegma=np.sqrt(siegma)\n return siegma\n\ndef fehlercal(x):\n lng=len(x)\n aveg=avg(lng,x)\n return aveg,sgm(lng,aveg,x)\n\ndef fehler():\n x=data.gdata(1,1)\n avg,sgm=fehlercal(x)\n print('avg:')\n print(avg)\n print('Sigmaabweichung')\n print(sgm)\n\ndef help():\n print('\\n\\\n e : Fehlerrechnung\\n\\\n h : help\\n\\\n q : quit\\n\\\n ')\n","sub_path":"SPECTRUM_v2-2016-01-18/SPECTRUM v2/stuff/error.py","file_name":"error.py","file_ext":"py","file_size_in_byte":883,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"415173383","text":"import pytest\n\nfrom leetcode.easy.ex0000_0100.ex0026 import InitialSolution, ImprovedSolution\n\n\n@pytest.mark.parametrize('input, expected', [\n ([1], [1]),\n ([1, 1, 2], [1, 2]),\n ([0,0,1,1,1,2,2,3,3,4], [0,1,2,3,4]),\n ([1, 2, 3, 4], [1, 2, 3, 4]),\n ([-100, 11, 22, 99], [-100, 11, 22, 99]),\n ([1, 1, 1, 1], [1]),\n ([1, 2, 2, 2, 3], [1, 2, 3]),\n ([1, 2, 2, 2], [1, 2]),\n])\ndef test_removes_duplicates(input: list[int], expected: int):\n k = InitialSolution().removeDuplicates(input)\n\n assert len(expected) == k\n assert input[:len(expected)] == expected\n\n k = ImprovedSolution().removeDuplicates(input)\n\n assert len(expected) == k\n assert input[:len(expected)] == expected\n\n","sub_path":"python/leetcode/easy/ex0000_0100/test/test_ex0026.py","file_name":"test_ex0026.py","file_ext":"py","file_size_in_byte":712,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"168653774","text":"'''\nMANTAINER: openshift@essiprojects.com\n\nEl proposito de este script es realizar backup de todos aquellos PersistentVolumeClaims especificados en el fichero info.json.\nEste script se puede ejcutar tanto dentro de un pod como desde un bastion de Openshift. En el caso de ejecutarse desde un bastion, es importante que el contexto de Openshift (Kubernetes) del usuario que ejecuta el script, tenga asigando el cluster-role cluster-admin. Si se ejecuta en un pod, se debe asignar serviceaccount con role cluster-admin al pod. Previamente a desplegar este proyecto, se tiene que construir la imagen que hay en el directorio `oc-rsyncer-agent`, y indicar alguna informacion sobre esta en el fichero info.json, para pasarle la informacion al pod, una opcion podria ser configmap y volumen montado con opcion sub-path. Es importante tener en cuenta que el storage de los pods es ephemeral y que por tanto a este pod donde se deplegaria el proyecto habria que montarle un PersistentVolumeClaim para asi garantizar la persistencia de los datos. \n- Si cuando se ejecuta el script, uno no esta loggeado contra el api de OpenShift, no se enviara correo ni se procedera con ninguna ejecucion\n- No se debe borrar el pod rsyncer temporal mientras este en Running y el script no haya finalizado\nPara mas información consultar en el fichero README.md\n'''\nimport os,sys,json,time, yaml, logging, argparse as ap\nfrom datetime import datetime\nfrom kubernetes import client, config\nfrom openshift.dynamic import DynamicClient, exceptions as OpenShiftExceptions\nfrom pathlib import Path\nfrom jinja2 import Template \nfrom logging.handlers import RotatingFileHandler\nfrom emailSender import send_email\n\nemail_header='Ejecución Smart PV Containarized Replicator -' + '{:%Y-%m-%d}'.format(datetime.now()) \n\nlogger = logging.getLogger('OCPRSYNCER')\n\nlogger.setLevel(logging.DEBUG)\n\n#configurar log level con opciones\nfilehandler = logging.FileHandler('{:%Y-%m-%d-%H:%M}.ocprsynser.log'.format(datetime.now()))\nformatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')\nfilehandler.setFormatter(formatter)\nlogger.addHandler(filehandler)\nlog_filename= filehandler.baseFilename\nconsoleHandler = logging.StreamHandler(sys.stdout)\nconsoleHandler.setFormatter(formatter)\nlogger.addHandler(consoleHandler)\nlogger.debug('Smart PersistentVolume Containered Replicator is just started...')\n\ntry:\n import textwrap\n textwrap.indent\nexcept AttributeError: \n def indent(text, amount, ch=' '):\n padding = amount * ch\n return ''.join(padding+line for line in text.splitlines(True))\nelse:\n def indent(text, amount, ch=' '):\n return textwrap.indent(text, amount * ch)\n\nPARAMS_JSON='conf/info.json'\n\n#variables globales para api \nv1_pvc=None\nv1_pod=None\nv1_projects=None\nv1_is=None\nv1_pv=None\n\nprojects_list=None\njson_key_error='''\nEjemplo de como usar el fichero JSON de parametro de entrada:\n {\n \"AGENT_IMAGE_STREAM\": \"rsyncer-agent\",\n \"AGENT_IMAGE_TAG\": \"latest\",\n \"AGENT_PROJECT\": \"rsync-agent\",\n \"SOURCE_VOLUMES\": [\n {\n \"NAMESPACE\": \"example\",\n \"PVCS\": [\"pvc-example\"]\n },\n ]\n }\n\t\t'''\n \n#ruta backup, si el script se ejecuta en un host, la raiz de los backups sera /backup, si se ejecuta en un pod, sera /opt/app-root/backup\nROOT_BACKUP_FOLDER=\"/backup/PVCs\"\n\n#opciones generales rsync\nRSYNC_OPTIONS=\" --delete=true --progress=true\"\nRSYNC_RESTORE_OPTIONS=\" --progress=true\"\n\nclass JsonError(Exception):\n def __init__(self, message,info=\"\"):\n super().__init__(message)\n self.message = message\n self.info=info\n def __str__(self):\n return str('Mensaje de error: '+self.message+'\\n'+indent(self.info,0)) \n \n\n#print diccionario, proposito debug\ndef print_map(map):\n print(json.dumps(map,indent=2))\n\n'''\nEl objetivo de esta funcion es inicializar el contexto de openshift (kubernetes).\nDependiendo de si el script se ejecuta en un pod o en un host, la configuracion se obtiene por una via u otra y se inicalizan las variables v1_pod y v1_pvc para las llamadas a la api.\n'''\ndef initialize():\n logger.info('Procediendo a inicializar los objetos API')\n if \"OPENSHIFT_BUILD_NAME\" in os.environ:\t#si el script se esta ejecutando en un pod... cargar el contexto desde dento del pod\n config.load_incluster_config()\n global ROOT_BACKUP_FOLDER\n ROOT_BACKUP_FOLDER=\"/opt/app-root/backup\"\n else:\n config.load_kube_config()\t\t\t#sino... cargar el contexto desde ~/.kube/config\n logger.info('Configuracion contexto (.kube/config) cargada')\n k8s_config = client.Configuration()\t\t\n k8s_client = client.api_client.ApiClient(configuration=k8s_config)\n dyn_client = DynamicClient(k8s_client)\t#crear objeto cliente API openshift desde configuracion kubernetes\n global v1_pvc\n global v1_is\n global v1_pod\n global v1_projects\n global projects_list\n global v1_pv\n try:\n v1_pvc = dyn_client.resources.get(api_version='v1',kind='PersistentVolumeClaim')\n v1_pv = dyn_client.resources.get(api_version='v1',kind='PersistentVolume')\n v1_is = dyn_client.resources.get(api_version='v1',kind='ImageStream')\n v1_pod = dyn_client.resources.get(api_version='v1',kind='Pod')\n v1_projects = dyn_client.resources.get(api_version='project.openshift.io/v1', kind='Project')\n projects_list = list(map(lambda project: project['metadata']['name'],v1_projects.get()['items']))\n logger.info('Objetos api Openshift instanciados')\n except (OpenShiftExceptions.UnauthorizedError, OpenShiftExceptions.ForbiddenError) as e: \n logger.critical('Unathorized, es requerido oc login, o el server no esta corriendo...')\n sys.exit(-1) \n\n'''\nEsta funcion valida el json de entrada, cuyo PATH esta especificado en la constante PARAMS_JSON\n'''\ndef validate_and_read__params_json():\n logger.info('Procediendo a validar y leer los parametros json')\n try:\n info=json.loads(open(PARAMS_JSON).read())\n logger.debug('Comprobando si existe clave SOURCE_VOLUMES...')\n if 'SOURCE_VOLUMES' not in info: raise JsonError('Clave SOURCE_VOLUMES no encontrada',json_key_error)\n logger.debug('Comprobando si existe clave SMTP_SERVER...')\n if 'SMTP_SERVER' not in info: raise JsonError('Clave SMTP_SERVER no encontrada',json_key_error)\n logger.debug('Comprobando si existe clave AGENT_IMAGE_TAG...')\n if 'AGENT_IMAGE_TAG' not in info: raise JsonError('Clave AGENT_IMAGE_TAG no encontrada',json_key_error)\n logger.debug('Comprobando si existe clave AGENT_IMAGE_STREAM...')\n if 'AGENT_IMAGE_STREAM' not in info: raise JsonError('Clave AGENT_IMAGE_STREAM no encontrada',json_key_error)\n logger.debug('Comprobando si existe clave AGENT_PROJECT...')\n if 'AGENT_PROJECT' not in info: raise JsonError('Clave AGENT_PROJECT no encontrada',json_key_error)\n logger.debug('Comprobando existencia del proyecto: ' + info['AGENT_PROJECT'] )\n if info['AGENT_PROJECT'] not in projects_list: raise JsonError(\"Proyecto '\"+info['AGENT_PROJECT']+\"' no encontrado\", \"Es importante seguir los pasos del README.md, para asi empezar construyendo la imagen del pod temporal\")\n logger.debug('Comprobando existencia del ImageStream: ' + info['AGENT_IMAGE_STREAM'] )\n v1_is.get(name=info['AGENT_IMAGE_STREAM'],namespace=info['AGENT_PROJECT']) \n logger.debug('Verificando correcto formatado del campo \"SOURCE_VOLUMES\"')\n for params in info['SOURCE_VOLUMES']: \n if params=={}: raise JsonError('Hay un diccionario vacio dentro del json',json_key_error)\n if 'NAMESPACE' not in params: raise JsonError('Clave NAMESPACE falta en la seccion: ' + str(params),json_key_error)\n if 'PVCS' not in params: raise JsonError('Clave PVCS falta en la seccion: ' + str(params),json_key_error)\n return info\n except JsonError as e:\n logger.warn(str(e))\n except json.decoder.JSONDecodeError as e:\n logger.warn('Json no ha sido bien formatado. '+ str(e))\n except OpenShiftExceptions.NotFoundError as e:\n logger.error(\"Image stream '\" +info['AGENT_IMAGE_STREAM']+\"' no encontrado en proyecto '\"+info['AGENT_PROJECT']+\"'\" )\n else:\n logger.info('El json ha sido correctamente formatado') \n return \n \n \n\n'''\nEsta rutina crea un PV con los datos de la aplicacion, para agilizar no tener que crearlo manualmente a posteriori\n'''\ndef create_pv(namespace,pvc):\n pv_yaml=open('templates/pv.yaml.j2','r').read()\n template=Template(pv_yaml)\n try:\n v1_pv.get(name=str(pvc['spec']['volumeName']+'-backup'))\n except OpenShiftExceptions.NotFoundError: \n logger.info('Procediendo a crear PV: '+ pvc['spec']['volumeName']+'backup')\n params_pv={\n 'pv_name': pvc['spec']['volumeName']+'-backup',\n\t 'accessModes': pvc['spec']['accessModes'],\n 'namespace': pvc['metadata']['namespace'],\n\t\t 'storageClass': 'nexica-nfs',\n 'serverNFS': 'vdm-oscont.uoc.es',\n\t\t 'size': pvc['spec']['resources']['requests']['storage']}\n pv_definition=template.render(params=params_pv)\n pv_template=yaml.load(pv_definition, Loader=yaml.FullLoader)\n try:\n resp = v1_pv.create(body=pv_template,namespace=namespace)\n logger.info('PV: ' + pvc['spec']['volumeName']+'-backup'+' creado')\n except Exception as e:\n logger.error('No se pudo crear el pv: '+ pvc['spec']['volumeName']+ '-backup')\n logger.error(e)\n else:\n logger.info('PV: '+ pvc['spec']['volumeName']+ '-backup ya existente')\n\n\n\n\n'''\nEl objetivo de esta funcion es iterar sobre la lista de pares PROYECTO:PVCs, especificada en el fichero info.json, asi pues, para cada proyecto se pedira al api pods solo en estado Running y pvcs, del proyecto que se este tratando. A continuacion, se iterara sobre los PVCs y se delegara en la funcion rsync, para que esta, con toda esta informacion (PODs, pvc, proyecto actual, nombre image-stream y proyecto donde se encuentra el image-stream a partir del cual se creara un pod temporal si es que ningun pod monta el pvc concreto).\n\nSi un proyecto o pvc no existe, dara error y se procedera con el siguiente de la lista.\nSi el pvc no existe, no se procedera a tratarloi\nEs obligatorio que en el json existan las siguientes claves:\n\"AGENT_IMAGE_TAG\": \"latest\",\n\"AGENT_IMAGE_STREAM\": \"rsyncer-agent\",\n\"AGENT_PROJECT\": \"rsync-agent\",\n\"SOURCE_VOLUMES\": [\n {\n \"NAMESPACE\": \"example\",\n \"PVCS\": [\"pvc-example\"]\n },\n ]\n}\n'''\ndef treat_pvcs(info,args):\n html_params={}\n logger.info('Procediendo a procesar los diferentes PersistentVolumeClaims especificados en el JSON')\n for params in info['SOURCE_VOLUMES']:\n namespace=params['NAMESPACE']\n logger.debug(\"NAMESPACE ACTUAL: \" + namespace)\n if namespace in projects_list:\n pods=list(v1_pod.get(namespace=namespace).to_dict()['items'])\n for pvc in params['PVCS']:\n try:\n pvcget=v1_pvc.get(namespace=namespace,name=pvc).to_dict() \n if pvcget.get('status',{}).get('phase',\"\") == \"Bound\": \n logger.info('Procediendo a procesar el objeto PersistentVolumeClaim: ' + pvc + ' proyecto: ' + namespace)\n message=rsync(pods,pvcget,namespace,info['AGENT_IMAGE_TAG'],info['AGENT_IMAGE_STREAM'],info['AGENT_PROJECT'],args)\n if message is not None:\n html_params['PersistentVolumeClaim: '+pvc]=message\n else:\n if not(args.restore): \n create_pv(namespace,pvcget)\n else: \n error=\"ERROR: PVC no esta en estado Bound, PVC: \"+ str(params['PVCS'])\n logger.error(error)\n html_params['PersistentVolumeClaim: '+pvc]=error\n logger.error(error)\n except OpenShiftExceptions.NotFoundError: \n error=\"PersistentVolumeClaim '\" + pvc + \"' no existe\"\n html_params['PersistentVolumeClaim: '+pvc]=error\n logger.error(error)\n else: \n error=\"Proyecto '\" + namespace + \"' not existe\"\n logger.error(error)\n html_params['Proyecto '+namespace]=error \n return html_params\n\n \n'''\nEl objetivo de esta funcion es iterar sobre los pods y encontrar cual es el que monta el pvc a tratar. Si se encuentra el pod, se procede a realizar el rsync contra este, una vez acabado, se sale de la funcion, pues no hay nada mas que hacer. Si resulta que ningun pod monta el volumen, se procedera a crear un pod temporal en el proyecto donde esta el pvc, el cual montara el volumen y se hara el oc rsync contra este. \n\nEste pod temporal se construira mediante los parametros especificados en el info.json (nombre image-stream, proyecto donde se encuentra image-stream). El pod, por defecto, esperara unos 5 minutos para desplegarse, si en 5 minutos no se ha desplegado correctamnte (estado=='Running'), se procedera a tratar al siguiente PersistentVolumeClaim y no se eliminara el pod temporal, con proposito de debug. Si el pod temporal se desplega correctamente, se procedera a hacer rsync contra este, una vez finalizado el rsync, se destruira. \n'''\ndef rsync(pods,pvc,namespace,agent_image_tag,agent_image_stream,agent_project,args):\n for pod in pods: \n volume_pod_pvc=list(filter(lambda volume: volume.get('persistentVolumeClaim',{}).get('claimName','')==pvc['metadata']['name'],pod['spec']['volumes'])) #se comprueba que el pod tenga el pvc montado\n if volume_pod_pvc: #si tiene volumen asociado al pvc y el status es 'Running', se recorreran los containers para coger el que atache el volumen\n logger.debug(\"Existe un pod que monta el PVC... pod: '\"+pod['metadata']['name'] +\"' , pvc: \" + pvc['metadata']['name'] )\n if pod['status']['phase']==\"Running\":\n logger.debug('El pod tiene estado Running, se procedera a realizar oc rsync contra este...')\n for container in pod['spec']['containers']:\t\n volume_mount=list(filter(lambda volume_mount: volume_mount['name']==volume_pod_pvc[0]['name'],container['volumeMounts']))\n if volume_mount: break #se encontro el volume_mount \n pod_path=volume_mount[0]['mountPath'] #siempre deberia encontrarse el volume_mount, muy extrano tiene que ser para que no\n pod_name=pod['metadata']['name']\n if not(args.restore):\n Path(ROOT_BACKUP_FOLDER + \"/\"+namespace+\"/\"+pvc['metadata']['name']).mkdir(parents=True, exist_ok=True)\n command=\"oc -n \" + namespace + \" rsync \" + pod_name +\":\" + pod_path + \" \"+ ROOT_BACKUP_FOLDER + \"/\" +namespace + \"/\"+pvc['metadata']['name'] + RSYNC_OPTIONS\n else:\n command=\"oc -n \" + namespace + \" rsync \" + ROOT_BACKUP_FOLDER + \"/\" +namespace + \"/\"+pvc['metadata']['name'] + \" \"+ pod_name+\":\"+pod_path +\" \"+ RSYNC_RESTORE_OPTIONS\n logger.info(command)\n logger.info(os.popen(command).read()) \n logger.debug('oc rsync realizado con exito!')\n return #la funcion se acaba porque ya se encontro un pod donde el pvc estaba montado, si el codigo continua su ejecucion es porque el pvc esta 'Bound' pero ningun pod lo tiene montado\n else: #si hay contenedor que monta el volumen, pero no esta Running, entonces si el pvc es ReadWriteOnce se informara y no se continuara\n if 'ReadWriteOnce' in pvc['spec']['accessModes']:\n logger.error('No se pudo procesar el PVC:' + pvc['spec']['metadata']+' pues es de tipo ReadWriteOnce y ya esta montado por un pod ('+pod['metadata']['name']+') que no esta en estado Running...')\n return \"Pod '\" + pod['metadata']['name'] + \"' not Running\"\n\n #en este caso, pueden darse las siguientes dos situaciones:\n #que ningun pod monta el PVC y por tanto levantaremos el pod temporal\n #puede que algun pod no 'Running' monte el PVC y que el PVC no sea ReadWriteOnce, pues es montable por el pod temporal \n message=None\n logger.debug('Se procede a crear un pod temporal en el proyecto: '+namespace)\n logger.info(os.popen('oc tag '+agent_project +'/'+agent_image_stream+':' + agent_image_tag + ' '+namespace+'/rsyncer-agent:latest -n ' + agent_project).read())\n pod_image=os.popen('oc get is rsyncer-agent -o yaml -n '+namespace+' | grep dockerImageRepository | tail -n1').read().split(\": \")[1].rstrip()\n pod_yaml=open('templates/pod.yaml.j2','r').read()\n template=Template(pod_yaml)\n params_pod_temporary={\n 'backup_path': '/backup',\n 'name': 'rsyncer-pod-agent',\n 'image': pod_image,\n 'pvc': pvc['metadata']['name'],\n 'volume_name': str(pvc['metadata']['namespace']) + '-pvc-volume' }\n tt=0\n running=1\n pod_definition=template.render(params=params_pod_temporary)\n pod_template=yaml.load(pod_definition, Loader=yaml.FullLoader)\n resp = v1_pod.create(body=pod_template,namespace=namespace) #controlar excepcion, si no se crea bien\n for wait in range(1,60):\n pod=v1_pod.get(namespace=namespace,name=\"rsyncer-pod-agent\")\n status=pod['status']['phase']\n logger.info(\"El estado del pod temporal es... '\" + status+\"', proyecto: \" + namespace)\n if status==\"Running\": break\n time.sleep(3)\n tt=tt+3\n if tt>=(300/3):\n message=\"Pod temporal no levanto en proyecto: \"+namespace\n logger.error('Pod temporal, no consiguio levantar en proyecto: ' + namespace) \n running=0\n break\n\n if (running):\t#si el pod llego a levantar (status==\"Running\"), habra que hacer rsync\n logger.debug(\"Realizando rsync contra pod temporal en proyecto: \"+namespace)\n if not(args.restore):\n command=\"oc -n \" + namespace + \" rsync \"+ params_pod_temporary['name'] +\":\" + params_pod_temporary['backup_path'] + \" \"+ ROOT_BACKUP_FOLDER +\"/\" +namespace + \"/\"+pvc['metadata']['name'] + RSYNC_OPTIONS\n Path(ROOT_BACKUP_FOLDER + \"/\"+namespace+\"/\"+pvc['metadata']['name']).mkdir(parents=True, exist_ok=True)\n else:\n command=\"oc -n \" + namespace + \" rsync \"+ ROOT_BACKUP_FOLDER +\"/\" +namespace + \"/\"+pvc['metadata']['name'] +\" \" + params_pod_temporary['name'] +\":\" + params_pod_temporary['backup_path'] + \" \" + RSYNC_RESTORE_OPTIONS\n logger.info(command)\n logger.info(os.popen(command).read())\n logger.info('Se procede a borrar el pod temporal')\n v1_pod.delete(name=params_pod_temporary['name'] , namespace=namespace)\n try:\n for wait in range(1,60):\t#esperaremos a que se borre el pod, como maximo 3 minutos\n v1_pod.get(namespace=namespace,name=\"rsyncer-pod-agent\")\n logger.info(\"Pod agente no se ha borrado aun, namespace: \" + namespace)\n time.sleep(5)\n except:\n pass\n else:\n if message is not None: \n message=message+'; Pod temporal no se pudo borrar en proyecto: '+ namespace\n else:\n message='Pod temporal no se pudo borrar en proyecto: '+ namespace\n logger.error('Pod temporal no se pudo borrar, procediento a forzar borrado del pod')\n logger.info(os.popen('oc delete po rsyncer-pod-agent --grace-period=0 --force -n '+namespace).read())\n logger.info(\"Pod temporal en en proyecto \" + namespace + \" fue borrado\")\n return message\n\n\n'''\nMetodo principal, de momento no hay parametros de entrada.\n'''\nif __name__ == \"__main__\":\n parser = ap.ArgumentParser(description=\"Este proyecto realiza una copia entre PVCS\")\n parser.add_argument(\"--restore\",action='store_true', help=\"Restore mode\")\n parser.add_argument(\"--backup\",action='store_true',help=\"Backup mode\")\n args, leftovers = parser.parse_known_args()\n if len(sys.argv)>2:\n logger.error(\"Solo se acepta una unica opcion, ejecuta `python3 oc-rsync.py --help` para mas informacion\")\n quit()\n initialize() #se inicializa el cliente del api de openshift con contexto correspondiente\n info=validate_and_read__params_json() #se verifica y comprueba el json (parametros de entrada)\n if info is not None:\t#si no han habido errores\n results_execution=treat_pvcs(info,args) #si el json es correcto\n table_html_params={'info':results_execution,'logfile':log_filename}\n send_email(info['SMTP_SERVER'],info['SMTP_PORT'],email_header,info['MAIL_SENDER'],info['MAIL_DEST'],[log_filename],table_html_params,logger) \n logger.debug('Proceso de sincronizacion de PV completado....')\n","sub_path":"oc-rsync.py","file_name":"oc-rsync.py","file_ext":"py","file_size_in_byte":20687,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"151479133","text":"# - * - coding: utf-8 -*-#\nfrom __future__ import absolute_import, division, unicode_literals\n\nfrom scrapy.log import WARNING\nfrom scrapy import Request\nimport re\nimport json\nimport math\n\nfrom HP_Master_Project.utils import is_empty\nfrom HP_Master_Project.items import ProductItem\nfrom HP_Master_Project.spiders import BaseProductsSpider\nfrom HP_Master_Project.extract_brand import extract_brand_from_first_words\n\n\nclass EnGbHpSpider(BaseProductsSpider):\n name = 'en_gb_hp'\n allowed_domains = ['store.hp.com', 'www.hp.com']\n\n SEARCH_URL = \"http://eu1-search.doofinder.com/5/search?hashid=68255af0073c20fc7a549d26435bccd8&page=1&query={search_term}&rpp=5&type=CG953\"\n PAGINATE_URL = \"http://eu1-search.doofinder.com/5/search?hashid=68255af0073c20fc7a549d26435bccd8&page={page_no}&query={search_term}&rpp=5&type=CG953\"\n API_URL = 'https://admin.metalocator.com/webapi/api/matchedretailerproducturls?Itemid=8343' \\\n '&apikey=f5e4337a05acceae50dc116d719a2875&username=fatica%2Bscrapingapi@gmail.com' \\\n '&password=8y3$u2ehu2e..!!$$&retailer_id={retailer_id}'\n\n total_matches = None\n\n headers = {'Origin': \"http://store.hp.com\"}\n\n def __init__(self, *args, **kwargs):\n super(EnGbHpSpider, self).__init__(\n site_name=self.allowed_domains[0], *args, **kwargs)\n self.current_page = 0\n self.user_agent = \"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) \" \\\n \"Chrome/60.0.3112.90 Safari/537.36\"\n\n def _parse_single_product(self, response):\n return self.parse_product(response)\n\n def parse_product(self, response):\n product = response.meta['product']\n if response.meta['req_url'] != response.url:\n if response.meta['req_url'].replace('http', 'https', 1) != response.url:\n return\n # Parse name\n name = self._parse_name(response)\n product['name'] = name\n\n # Parse image\n image = self._parse_image(response)\n product['image'] = image\n\n model = self._parse_model(response)\n product['model'] = model\n product['ean'] = None\n #\n product['currencycode'] = 'GBP'\n product['locale'] = 'en-UK'\n sku = self._parse_sku(response)\n product['sku'] = sku\n price = self._parse_price(response)\n product['price'] = price\n product['saleprice'] = price\n # retailer_key = self._parse_retailer_key(response)\n product['retailer_key'] = sku\n in_store = self._parse_instore(response)\n product['instore'] = in_store\n product['gallery'] = self._parse_gallery(response)\n features = self._parse_features(response)\n product['features'] = features\n product['condition'] = 1\n product['productstockstatus'] = self._parse_stock_status(response)\n self._parse_categories(response)\n return product\n\n @staticmethod\n def _parse_name(response):\n title = response.xpath('//h1[@class=\"pb-product__name\"]/text()').extract()\n if title:\n return title[0]\n\n @staticmethod\n def _parse_image(response):\n img = response.xpath('//ul[@class=\"gal-nav\"]/li/a/img/@data-src').extract()\n if img:\n return img[0]\n\n @staticmethod\n def _parse_sku(response):\n sku = response.xpath('//*[@itemprop=\"sku\"]/@content')[0].extract()\n return sku\n\n def _parse_stock_status(self, response):\n stock_value = self.STOCK_STATUS['CALL_FOR_AVAILABILITY']\n try:\n stock_message = response.xpath('//*[@itemprop=\"availability\"]/@content')[0].extract()\n if 'instock' in stock_message.lower():\n stock_value = self.STOCK_STATUS['CALL_FOR_AVAILABILITY']\n elif 'outofstock' in stock_message.lower():\n stock_value = self.STOCK_STATUS['OUT_OF_STOCK']\n elif 'callforavailability' in stock_message.lower():\n stock_value = self.STOCK_STATUS['CALL_FOR_AVAILABILITY']\n elif 'discontinued' in stock_message.lower():\n stock_value = self.STOCK_STATUS['OTHER']\n\n except BaseException as e:\n self.log(\"Error parsing stock status data: {}\".format(e), WARNING)\n\n return stock_value\n\n @staticmethod\n def _parse_categories(response):\n product = response.meta['product']\n\n categories = response.xpath('//ul[contains(@class, \"breadcrumbs\")]/li/a/text()').extract()\n product['categories'] = categories\n return product\n\n def _parse_model(self, response):\n model = response.xpath('//p[contains(@class, \"prod-nr\")]/text()').extract()\n if model:\n return self.clear_text(model[0].replace('Part Number: ', ''))\n\n @staticmethod\n def _parse_gallery(response):\n gallery = response.xpath('//ul[@class=\"gal-nav\"]/li/a/img/@data-src').extract()\n return gallery\n\n @staticmethod\n def _parse_price(response):\n price = response.xpath('//*[@itemprop=\"price\"]/@content')[0].extract()\n if price:\n return price\n\n def _parse_retailer_key(self, response):\n retailer_key = response.xpath('//div[@class=\"prodSku\"]/span[@class=\"prodNum\"]/text()').extract()\n if retailer_key:\n return self.clear_text(retailer_key[0])\n\n def _parse_instore(self, response):\n if self._parse_price(response):\n return 1\n\n return 0\n\n def _parse_shiptostore(self, response):\n if self._parse_shippingphrase(response):\n return 1\n\n return 0\n\n def _parse_shippingphrase(self, response):\n pharse = response.xpath('//div[@class=\"estShipMessagePDP\"]/text()').extract()\n if pharse:\n return self.clear_text(pharse[0])\n\n def _parse_features(self, response):\n features = []\n features_name = response.xpath('//div[contains(@class, \"specs__table\")]/table[@class=\"specs-table\"]/tr')\n for f_name in features_name:\n key = f_name.xpath('.//th/text()').extract()\n value = f_name.xpath('.//td/text()').extract()\n if value:\n features.append({key[0]: value[0]})\n return features\n\n def clear_text(self, str_result):\n return str_result.replace(\"\\t\", \"\").replace(\"\\n\", \"\").replace(\"\\r\", \"\").replace(u'\\xa0', ' ').strip()\n\n def _scrape_total_matches(self, response):\n data = json.loads(response.body)\n if self.retailer_id:\n return len(data)\n self.total_matches = data['total']\n return self.total_matches\n\n def _scrape_product_links(self, response):\n link_list = []\n if self.retailer_id:\n data = json.loads(response.body)\n for link in data:\n link = link['product_link']\n link_list.append(link)\n for link in link_list:\n yield link, ProductItem()\n else:\n data = json.loads(response.body)\n self.total_matches = data['total']\n links = []\n for result in data['results']:\n links.append(result['link'])\n\n for link in links:\n yield link, ProductItem()\n\n def _scrape_next_results_page_link(self, response):\n if self.retailer_id:\n return None\n search_term = response.meta['search_term']\n self.current_page += 1\n if self.current_page < math.ceil(self.total_matches / 5.0):\n next_page = self.PAGINATE_URL.format(search_term=search_term, page_no=self.current_page)\n return next_page\n","sub_path":"HP_Master_Project/spiders/en_gb_hp.py","file_name":"en_gb_hp.py","file_ext":"py","file_size_in_byte":7602,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"514052078","text":"#!/usr/bin/python\n\nfrom testing import *\nimport re\n\ndef emphasis_to_brackets(text):\n reset_sequence = chr(27) + \"\\[0m\" # convert reset to closer\n text = re.sub(reset_sequence, \"]\", text)\n ansi_color_regex = chr(27) + \"\\[[0-9;]*m\" # all other sequences are opener\n text = re.sub(ansi_color_regex, \"[\", text)\n return text\n","sub_path":"assign1/slink/sanity.py","file_name":"sanity.py","file_ext":"py","file_size_in_byte":347,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"394548009","text":"#! /usr/bin/python\r\n# data_dict keys must correspond to the fillable field names from the template.\r\nimport os\r\nimport pdfrw\r\nimport csv\r\n\r\n#Sorry I don't remember where this script came from, but it is useful.\r\ntemplate_path = 'Form FGIS-921-2-template.pdf'\r\noutput_path = ''\r\n\r\nANNOT_KEY = '/Annots'\r\nANNOT_FIELD_KEY = '/T'\r\nANNOT_VAL_KEY = '/V'\r\nANNOT_RECT_KEY = '/Rect'\r\nSUBTYPE_KEY = '/Subtype'\r\nWIDGET_SUBTYPE_KEY = '/Widget'\r\ncarriers = []\r\nquantities = []\r\ndates = []\r\nrow_count = 0\r\nnum_track = 1\r\nform_number = 0\r\ndata_dict_stub = {\r\n 'destination_country': 'Country of Destination',\r\n 'carrier_identification': 'Carrier Identification',\r\n 'cert_number': 'Inspection Certificate Number',\r\n 'loading_dates': 'Loading Dates',\r\n '4quantity': 'Shipment Weight',\r\n 'elevator_location': 'Elevator Location',\r\n 'shipper_info': 'Shipper Information',\r\n '3GrainCommodity': 'Grain/Commodity'\r\n}\r\ndata_dict_temp = {}\r\ndata_dict = {}\r\n\r\n#This function is the pdf part. \r\ndef write_fillable_pdf(input_pdf_path, output_pdf_path, data_dict):\r\n template_pdf = pdfrw.PdfReader(input_pdf_path)\r\n annotations = template_pdf.pages[0][ANNOT_KEY]\r\n for annotation in annotations:\r\n if annotation[SUBTYPE_KEY] == WIDGET_SUBTYPE_KEY:\r\n if annotation[ANNOT_FIELD_KEY]:\r\n key = annotation[ANNOT_FIELD_KEY][1:-1]\r\n if key in data_dict.keys():\r\n annotation.update(\r\n pdfrw.PdfDict(V='{}'.format(data_dict[key]))\r\n )\r\n pdfrw.PdfWriter().write(output_pdf_path, template_pdf)\r\n\r\n#Read in the carrier data.\r\nwith open('921_template.csv', 'r') as csvfile:\r\n reader = csv.reader(csvfile, delimiter=',', quotechar='|')\r\n next(reader)\r\n for row in reader:\r\n row_count = row_count + 1\r\n carriers.append(row[0])\r\n dates.append(row[1])\r\n quantities.append(row[2])\r\n\r\n#Compute the needed number of forms (22 containers max per form)\r\nfor i in range(1, row_count):\r\n if row_count/22 < i:\r\n form_number = i\r\n break\r\n\r\n#Get basic info- repeated on all forms\r\nfor k, v in data_dict_stub.items():\r\n data_dict_stub[k] = input(\"Enter \" + v + \": \")\r\n \r\n#No need for this to be entered by user.\r\ndata_dict_stub['total_page_num'] = str(form_number)\r\n\r\n#Write the forms\r\nfor j in range(1,form_number + 1):\r\n #Get the carrier info for form j.\r\n for i in range(1,23):\r\n try:\r\n data_dict_temp['Carrier-'+str(i)] = carriers[num_track-1]\r\n data_dict_temp['Date-'+str(i)] = dates[num_track-1]\r\n data_dict_temp['Quantity-'+str(i)] = quantities[num_track-1]\r\n data_dict_temp['14 No of Live InsectsRow'+str(i)] = 0\r\n num_track = num_track + 1\r\n except IndexError: break\r\n\r\n data_dict_stub['page_num'] = str(j)\r\n data_dict.update(data_dict_stub)\r\n data_dict.update(data_dict_temp)\r\n \r\n output_path = data_dict['carrier_identification'] + '-921-' + str(j)+ '.pdf'\r\n\r\n write_fillable_pdf(template_path, output_path, data_dict)\r\n data_dict_temp.clear()\r\n data_dict.clear()\r\n","sub_path":"fgis_921_filler.py","file_name":"fgis_921_filler.py","file_ext":"py","file_size_in_byte":3124,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"575528901","text":"#!/usr/bin/env python\r\n# -*- coding: utf-8 -*-\r\n#\r\n# Copyright (c) 2021 Intel Corporation\r\n#\r\n# Licensed under the Apache License, Version 2.0 (the \"License\");\r\n# you may not use this file except in compliance with the License.\r\n# You may obtain a copy of the License at\r\n#\r\n# http://www.apache.org/licenses/LICENSE-2.0\r\n#\r\n# Unless required by applicable law or agreed to in writing, software\r\n# distributed under the License is distributed on an \"AS IS\" BASIS,\r\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n# See the License for the specific language governing permissions and\r\n# limitations under the License.\r\n\r\nimport multiprocessing\r\nimport threading\r\nimport subprocess\r\nimport time\r\nimport os\r\nimport sys\r\nimport argparse\r\nimport array\r\nimport logging\r\nimport numpy as np\r\nimport time\r\nfrom utils import TF_BERTDataSet\r\n\r\nlogging.basicConfig(level=logging.INFO)\r\nlog = logging.getLogger(\"DISTILBERT\")\r\n\r\n\r\ndef get_args():\r\n parser = argparse.ArgumentParser()\r\n parser.add_argument(\"--batch_size\", default=8,\r\n type=int, help=\"Batch size\")\r\n parser.add_argument(\"--input_model\", default=\"distilbert_base_uncased_mrpc.onnx\",\r\n type=str, help=\"input_model_path\")\r\n parser.add_argument(\"--output_model\", default=\"./ir/\", type=str, help=\"output_model_path\")\r\n parser.add_argument(\"--vocab_file\", default=\"./data/vocab.txt\", \r\n type=str, help=\"vocab_file_path\")\r\n parser.add_argument(\"--do_lower_case\", type=bool, default=True,\r\n help=\"vocab whether all lower case\")\r\n parser.add_argument(\"--data_dir\", default=\"./data/MRPC/\", type=str,\r\n help=\"The input data dir. Should contain the .tsv files.\")\r\n parser.add_argument(\"--config\", default=\"./bert.yaml\", type=str, help=\"yaml path\")\r\n parser.add_argument('--benchmark', action='store_true', default=False)\r\n parser.add_argument('--tune', action='store_true',\r\n default=False, help=\"whether quantize the model\")\r\n parser.add_argument('--mode', type=str, help=\"benchmark mode of performance or accuracy\")\r\n args = parser.parse_args()\r\n return args\r\n\r\ndef main():\r\n\r\n args = get_args()\r\n if args.benchmark:\r\n from neural_compressor.experimental import Benchmark, common\r\n ds = TF_BERTDataSet(args.data_dir, args.vocab_file, args.do_lower_case)\r\n evaluator = Benchmark(args.config)\r\n evaluator.model = common.Model(args.input_model)\r\n evaluator.b_dataloader = common.DataLoader(ds, args.batch_size)\r\n evaluator(args.mode)\r\n\r\n if args.tune:\r\n from neural_compressor.experimental import Quantization, common\r\n ds = TF_BERTDataSet(args.data_dir, args.vocab_file, args.do_lower_case)\r\n quantizer = Quantization(args.config)\r\n quantizer.model = common.Model(args.input_model)\r\n quantizer.eval_dataloader = common.DataLoader(ds, args.batch_size)\r\n quantizer.calib_dataloader = common.DataLoader(ds, args.batch_size)\r\n q_model = quantizer()\r\n q_model.save(args.output_model)\r\n\r\nif __name__ == '__main__':\r\n main()\r\n","sub_path":"examples/engine/nlp/distilbert_base_uncased_mrpc/run_engine.py","file_name":"run_engine.py","file_ext":"py","file_size_in_byte":3180,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"473718395","text":"from processor.webdriverfactory import WebDriverFactory\nfrom processor import config\nfrom processor.basepage import BasePage\nfrom processor.Sandbox_Api import SandboxApi\nimport time\nimport json\n\nclass User(BasePage):\n def __init__(self, teleId):\n self.banking = SandboxApi()\n self.wdf = WebDriverFactory(config.browser)\n self.driver = \"\"\n super().__init__(self.driver)\n\n self.telegramID = str(teleId)\n self.username = \"\"\n self.email = \"\"\n self.password = \"asdASD123!\"\n self.first = \"\"\n self.last = \"\"\n\n self.id = \"\"\n self.secret = \"\"\n self.callback = \"\"\n self.code = \"\"\n self.token = \"\"\n\n self.cust_id = \"\"\n self.balance = \"\"\n self.avail_balance = \"\"\n self.rewards_point = 100\n\n self.tokenExpiry = \"\"\n\n def set_username(self, username):\n self.username = username.lower()\n\n def add_points(self, amount):\n self.rewards_point = self.rewards_point + amount\n self.store()\n\n def load(self):\n try:\n with open(config.cdat, 'r') as cdat:\n database = json.load(cdat)\n cdat.close()\n\n self.username = database[self.telegramID][\"username\"]\n self.email = database[self.telegramID][\"email\"]\n self.password = database[self.telegramID][\"password\"]\n self.first = database[self.telegramID][\"first\"]\n self.last = database[self.telegramID][\"last\"]\n\n self.id = database[self.telegramID][\"id\"]\n self.secret = database[self.telegramID][\"secret\"]\n self.callback = database[self.telegramID][\"callback\"]\n self.code = database[self.telegramID][\"code\"]\n self.token = database[self.telegramID][\"token\"]\n self.rewards_point = database[self.telegramID][\"rewards_point\"]\n\n self.tokenExpiry = database[self.telegramID][\"token_expiry\"]\n if self.tokenExpiry < time.time():\n self.getCode()\n self.getToken()\n self.getAccount()\n self.store()\n return True\n\n except:\n return False\n\n def store(self):\n try:\n with open(config.cdat, 'r') as cdat:\n database = json.load(cdat)\n cdat.close()\n\n user_data = {}\n user_data[\"username\"] = self.username\n user_data[\"email\"] = self.email\n user_data[\"password\"] = self.password\n user_data[\"first\"] = self.first\n user_data[\"last\"] = self.last\n\n user_data[\"id\"] = self.id\n user_data[\"secret\"] = self.secret\n user_data[\"callback\"] = self.callback\n user_data[\"code\"] = self.code\n user_data[\"token\"] = self.token\n\n user_data[\"cust_id\"] = self.cust_id\n user_data[\"balance\"] = self.balance\n user_data[\"balance_available\"] = self.avail_balance\n user_data[\"rewards_point\"] = self.rewards_point\n\n user_data[\"token_expiry\"] = self.tokenExpiry\n\n database[self.telegramID] = user_data\n\n with open(config.cdat, 'w') as cdat:\n json.dump(database, cdat)\n cdat.close()\n return True\n except:\n return False\n\n\n def register(self, first, last, email):\n try:\n self.first = first\n self.last = last\n self.email = email\n self.driver = self.wdf.getWebDriverInstance(config.apm_url)\n self.elementClick(\"//a[text()='Register']\", locatorType=\"XPATH\")\n self.elementClick(\"//option[text()='{}']\".format(\"Mr.\"), locatorType=\"XPATH\")\n self.sendKeys(self.first, \"//input[contains(@id, '_signup_first_name')]\", locatorType=\"XPATH\")\n self.sendKeys(self.last, \"//input[contains(@id, '_signup_last_name')]\", locatorType=\"XPATH\")\n self.sendKeys(self.email, \"//input[contains(@id, '_signup_email')]\", locatorType=\"XPATH\")\n self.sendKeys(self.password, \"//input[contains(@id, '_signup_password')]\", locatorType=\"XPATH\")\n self.sendKeys(self.password, \"//input[contains(@id, '_signup_password_confirmation')]\", locatorType=\"XPATH\")\n self.elementClick(\"//input[@type='submit']\", locatorType=\"XPATH\")\n time.sleep(3)\n self.driver.get(config.mailcatcher_url)\n self.elementClick(\"//tr[1]//td[1]\",locatorType=\"XPATH\")\n self.driver.switch_to.frame(self.driver.find_element_by_xpath(\"//iframe\"))\n time.sleep(1)\n self.elementClick(\"//a[contains(@href, 'confirmation')]\", locatorType=\"XPATH\")\n time.sleep(1)\n\n self.driver.quit()\n self.driver = self.wdf.getWebDriverInstance(config.apm_url)\n self.sendKeys(self.email, \"//input[contains(@id, 'session_email')]\", locatorType=\"XPATH\")\n self.sendKeys(self.password, \"//input[contains(@id, 'session_password')]\", locatorType=\"XPATH\")\n self.elementClick(\"//input[@type='submit']\", locatorType=\"XPATH\")\n self.elementClick(\"//a[text()='New App']\", locatorType=\"XPATH\")\n self.sendKeys(\"MrSir\"+str(time.time())+self.email,\"//input[@id='app_name']\", locatorType=\"XPATH\")\n self.sendKeys(\"MrSir\",\"//input[@id='app_provider']\", locatorType=\"XPATH\")\n self.sendKeys(\"MrSir\",\"//textarea[@id='app_description']\", locatorType=\"XPATH\")\n self.sendKeys(\"http://localhost:3005\",\"//input[@id='app_url']\", locatorType=\"XPATH\")\n self.sendKeys(\"http://localhost:3005\",\"//input[@id='app_callback_urls']\", locatorType=\"XPATH\")\n self.sendKeys(\"support@mrsir.com\",\"//input[@id='app_support_email']\", locatorType=\"XPATH\")\n self.sendKeys(\"http://localhost:3005\",\"//input[@id='app_support_url']\", locatorType=\"XPATH\")\n self.sendKeys(\"http://localhost:3005\",\"//input[@id='app_tos_url']\", locatorType=\"XPATH\")\n self.sendKeys(\"http://localhost:3005\",\"//input[@id='app_privacy_policy_url']\", locatorType=\"XPATH\")\n self.elementClick(\"//input[@id='banking-scope']\", locatorType=\"XPATH\")\n self.elementClick(\"//*[text()='Basic, read-write']\", locatorType=\"XPATH\")\n self.elementClick(\"//input[@type='submit']\", locatorType=\"XPATH\")\n\n self.id = self.driver.find_element_by_xpath(\"//tr[.//th[text()='Client ID']]//td//code\").text\n self.secret = self.driver.find_element_by_xpath(\"//tr[.//th[text()='Client Secret']]//td//code\").text\n self.callback = self.driver.find_element_by_xpath(\"//tr[.//th[text()='Callback URLs']]//td//code\").text\n self.driver.get(config.apm_url+config.auth_url.format(self.id))\n self.elementClick(\"//a[contains(text(), 'Next')]\", locatorType=\"XPATH\")\n self.elementClick(\"//a[contains(text(), 'Allow')]\", locatorType=\"XPATH\")\n self.elementClick(\"//input[@type='submit']\", locatorType=\"XPATH\")\n self.code = str(self.driver.current_url).split(\"?code=\")[1].split(\"&state\")[0]\n self.driver.quit()\n return True\n except:\n return False\n\n def getCode(self):\n try:\n self.driver = self.wdf.getWebDriverInstance(config.apm_url)\n self.sendKeys(self.email, \"//input[contains(@id, 'session_email')]\", locatorType=\"XPATH\")\n self.sendKeys(self.password, \"//input[contains(@id, 'session_password')]\", locatorType=\"XPATH\")\n self.elementClick(\"//input[@type='submit']\", locatorType=\"XPATH\")\n self.driver.get(config.apm_url + config.auth_url.format(self.id))\n time.sleep(1)\n self.code = str(self.driver.current_url).split(\"?code=\")[1].split(\"&state\")[0]\n self.driver.quit()\n return True\n except:\n return False\n\n\n def getToken(self):\n try:\n self.token = self.banking.get_authorization(self.id, self.secret, self.code)\n self.logTime()\n return True\n except:\n return False\n\n def getAccount(self):\n rawData = self.banking.get_accounts(self.token)\n data = json.loads(rawData)['data'][0]\n self.cust_id = data['id']\n self.balance = data['balance']\n self.avail_balance = data['balance_available']\n\n def transfer(self, receiver, amount, note=\"\"):\n with open(config.cdat, 'r') as cdat:\n database = json.load(cdat)\n cdat.close()\n\n receiverID = \"\"\n for user in database:\n if receiver == database[user]['username']:\n telegramID = user\n receiverID = database[user]['cust_id']\n\n if receiverID == \"\":\n return \"NOT FOUND\"\n else:\n external = str(time.time()).split(\".\")[1]+\"gdg\"+str(time.time()).split(\".\")[1]\n response = self.banking.post_internal_transfer(self.token, self.cust_id, receiverID, external, amount, note)\n\n if response.status_code == 201:\n return str(telegramID)\n else:\n return \"FAILED\"\n\n def username_to_telegram_id(self, username):\n with open(config.cdat, 'r') as cdat:\n database = json.load(cdat)\n cdat.close()\n\n telegram_id = \"\"\n for user in database:\n if username == database[user]['username']:\n return user\n return None\n\n def logTime(self):\n self.tokenExpiry = time.time()+3600\n\n\n\n\n\n# us = User(\"239618248\")\n# us.load()\n# us.getAccount()\n\n# us.register(\"user\", \"user\", \"user@6.com\")\n# us.getCode()\n# us.getToken()\n# print(us.token)\n# us.store()\n","sub_path":"user.py","file_name":"user.py","file_ext":"py","file_size_in_byte":9676,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"187342954","text":"from unittest import TestCase\nfrom methods import is_proper_instance_type, dispatcher, is_proper_instance, \\\n register_type, update_instance\nfrom mock import Mock\n\n\nclass MethodsTest(TestCase):\n def setUp(self):\n self.types = dict()\n self.types[u'mysql'] = \\\n {u'description': u'mysql: world leading relational database',\n u'name': u'mysql',\n u'ts': 1416402816.064837,\n u'available': True}\n self.types[u'virtual1'] = \\\n {u'description': u'virtual worker for testing purposes',\n u'name': u'virtual1',\n u'ts': 1424338658.027424,\n u'available': True}\n\n self.instance = {\n 'id': '666',\n 'additional': 'info',\n 'foo': 'bar'\n }\n\n def tearDown(self):\n pass\n\n def test_is_proper_type(self):\n for type_name in self.types:\n res = is_proper_instance_type(self.types[type_name])\n self.assertTrue(res)\n\n cpy = self.types['mysql'].copy()\n fields = ['description', 'ts', 'available']\n for field in fields:\n cpy.pop(field)\n self.assertTrue(is_proper_instance_type(cpy))\n\n cpy = self.types['mysql'].copy()\n # each type has to have a name!\n cpy.pop('name')\n self.assertFalse(is_proper_instance_type(cpy))\n\n def test_is_proper_instance(self):\n res = is_proper_instance(self.instance)\n self.assertTrue(res)\n\n res = is_proper_instance({'some': 'test'})\n self.assertFalse(res)\n\n def test_dispatching_types(self):\n instance_store = Mock()\n type_store = Mock()\n type_store.update = Mock(return_value=True)\n\n msg = {'subject': 'instance_type', 'type': self.types['mysql']}\n dispatcher(msg, instance_store, type_store)\n self.assertEqual(type_store.update.call_count, 1)\n args, kwargs = type_store.update.call_args\n self.assertEqual('mysql', args[0])\n\n self.assertTrue('available' in args[1])\n self.assertTrue('description' in args[1])\n self.assertTrue('ts' in args[1])\n\n def test_register_type(self):\n type_store = Mock()\n type_store.update = Mock(return_value=True)\n register_type({'useless': 'type'}, type_store)\n self.assertFalse(type_store.update.called)\n\n for type_name in self.types:\n type_store.update = Mock(return_value=True)\n register_type(self.types[type_name], type_store)\n args, kwargs = type_store.update.call_args\n self.assertEqual(type_name, args[0])\n self.assertTrue('available' in args[1])\n self.assertTrue('description' in args[1])\n self.assertTrue('ts' in args[1])\n\n def test_update_instance(self):\n instance_store = Mock()\n instance_store.update = Mock(return_value=True)\n\n instance = self.instance.copy()\n instance.pop('id')\n update_instance(instance, instance_store)\n self.assertEqual(instance_store.update.call_count, 0)\n\n update_instance(self.instance, instance_store)\n self.assertEqual(instance_store.update.call_count, 1)\n args, kwargs = instance_store.update.call_args\n self.assertEqual(self.instance['id'], args[0])\n self.assertTrue('last_info' in args[1])\n\n def test_dispatching_instances(self):\n type_store = Mock()\n instance_store = Mock()\n instance_store.update = Mock(return_value=True)\n msg = {'subject': 'instance_info', 'instance': self.instance}\n dispatcher(msg, instance_store, type_store)\n self.assertTrue(instance_store.update.call_count, 1)\n\n def test_fooling_dispatcher(self):\n type_store = Mock()\n instance_store = Mock()\n # not possible to register inappropriate instance type\n msg = {'subject': 'instance_type', 'type': {'useless': 'type'}}\n dispatcher(msg, instance_store, type_store)\n self.assertEqual(type_store.call_count, 0)\n\n # not possible to register inappropriate instance type\n msg = {'subject': 'instance_type', 'x-type': {'useless': 'type'}}\n dispatcher(msg, instance_store, type_store)\n self.assertEqual(type_store.call_count, 0)\n\n # not possible to register inappropriate instance\n msg = {'subject': 'instance_info', 'x-type': {'useless': 'foobar'}}\n dispatcher(msg, instance_store, type_store)\n self.assertEqual(instance_store.call_count, 0)\n\n msg = {'subject': 'instance_info', 'instance': {'no-id': 'foobar'}}\n dispatcher(msg, instance_store, type_store)\n self.assertEqual(instance_store.call_count, 0)\n\n msg = {'ever': 'wonder', 'why': {'we': 'go'}}\n dispatcher(msg, instance_store, type_store)\n self.assertEqual(instance_store.call_count, 0)\n\n\n\n\n\n","sub_path":"tests/test_methods.py","file_name":"test_methods.py","file_ext":"py","file_size_in_byte":4861,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"54818965","text":"# Universidad del Valle de Guatemala\n# Grafica por Computadora - CC3044\n# Julio Herrera 19402\n# SR1: Points\n\nfrom src.glTypes import V2, newColor\nfrom src.gl import Renderer\nfrom numpy import sin\n\nwidth = 800\nheight = 600\n\nrend = Renderer(width, height)\nrend.glClearColor(0.8, 0.8, 0.8)\nrend.glClear()\nrend.glColor(0.5, 0.7, 0.9)\n\n# Vertex with default viewport\nrend.glVertex(0, 0, newColor(0, 0, 0))\nrend.glVertex(-1, -1, newColor(0, 0, 0))\nrend.glVertex(-1, 1, newColor(0, 0, 0))\nrend.glVertex(1, -1, newColor(0, 0, 0))\nrend.glVertex(1, 1, newColor(0, 0, 0))\n\n# Stablishing a viewport\nrend.glViewPort(100, 250, 200, 100)\n\n# Drawing inside the viewport\nfor x in range(width - 1):\n y0 = int((sin(x / 10) * 50) + height/2)\n y1 = int((sin((x+1) / 10) * 50) + height/2)\n rend.glLine(V2(x,y0), V2((x+1),y1), newColor(1, 0, 0))\n\n# Vertex with new viewport\nrend.glVertex(0, 0, newColor(0, 0, 1))\nrend.glVertex(-1, -1, newColor(0, 0, 1))\nrend.glVertex(-1, 1, newColor(0, 0, 1))\nrend.glVertex(1, -1, newColor(0, 0, 1))\nrend.glVertex(1, 1, newColor(0, 0, 1))\n\nrend.glFinish(\"outputs/SR1.bmp\")","sub_path":"SR1.py","file_name":"SR1.py","file_ext":"py","file_size_in_byte":1086,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"475655010","text":"# 导包\nimport time\n\nfrom selenium import webdriver\n\n# 创建浏览器驱动对象\ndriver = webdriver.Firefox()\n\n# 打开页面\n# driver.get(\"D:\\\\webAutoTest\\\\page\\\\注册A.html\")\ndriver.get(\"file:///D:/webAutoTest/page/%E6%B3%A8%E5%86%8C%E5%AE%9E%E4%BE%8B.html\")\n\n# 浏览器窗口最大化\n# driver.maximize_window()\n# time.sleep(3)\n\n# 设置窗口大小\n# driver.set_window_size(400, 300)\n# time.sleep(3)\n\n# 改变浏览器的位置\n# driver.set_window_position(200, 200)\n\n# 点击‘AA 新浪 网站’\n# driver.find_element_by_link_text(\"AA 新浪 网站\").click()\n\n# 后退\n# driver.back()\n# time.sleep(3)\n\n# 前进\n# driver.forward()\n# time.sleep(2)\n\n# 刷新\n# driver.refresh()\n\n# 点击‘注册A网页’\n# driver.find_element_by_link_text(\"注册A网页\").click()\n# time.sleep(3)\n\n# 关闭当前窗口\n# driver.close()\n\n\n# 获取页面title\nprint(\"title=\", driver.title)\n\n# 获取当前页面的url\nprint(\"url=\", driver.current_url)\n\n# 暂停3秒\ntime.sleep(5)\n\n# 关闭驱动\ndriver.quit()\n","sub_path":"day03/test02_broswer.py","file_name":"test02_broswer.py","file_ext":"py","file_size_in_byte":1003,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"29142304","text":"def find_minimal_sum(matrix):\n size = len(matrix)\n visited = [(0, 0)]\n visited.extend((n, size) for n in range(size))\n visited.extend((size, n) for n in range(size))\n paths = {(0, 0): matrix[0][0]}\n\n while True:\n smallest_path = min(paths, key=paths.get)\n x, y = smallest_path\n candidates = []\n if (x + 1, y) not in visited:\n candidates.append((x + 1, y))\n if (x, y + 1) not in visited:\n candidates.append((x, y + 1))\n if len(candidates) == 0:\n del paths[smallest_path]\n continue\n new_path = min(candidates, key=lambda cell: paths[smallest_path] + matrix[cell[0]][cell[1]])\n paths[new_path] = paths[smallest_path] + matrix[new_path[0]][new_path[1]]\n visited.append(new_path)\n if new_path == (size - 1, size - 1):\n return paths[new_path]\n\n\ndef matrix_from_file(path):\n with open(path) as matrix_file:\n return [[int(col) for col in row.split(',')] for row in matrix_file]\n\n\ndef test_po81():\n assert find_minimal_sum(matrix_from_file('p081_test_matrix.txt'))\n\n\ndef p081():\n return find_minimal_sum(matrix_from_file('p081_matrix.txt'))\n\n\nif __name__ == '__main__':\n print(p081())\n","sub_path":"p081.py","file_name":"p081.py","file_ext":"py","file_size_in_byte":1238,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"132756310","text":"# 텍스트파일의 x,y 좌표를 바탕으로 히트맵을 출력해주는 heatmap.py\n\nimport numpy as np \nfrom scipy.stats.kde import gaussian_kde\nimport matplotlib.pyplot as plt\n\ndef printHeatMap(image_x, image_y) :\n x, y = np.genfromtxt('../result/player_coord.txt', delimiter=',', unpack=True)\n\n k = gaussian_kde(np.vstack([x, y]))\n xi, yi = np.mgrid[0:image_y:y.size**0.5*1j,0:image_x:x.size**0.5*1j] \n zi = k(np.vstack([yi.flatten(),xi.flatten()]))\n\n Z, xedges, yedges = np.histogram2d(x, y)\n plt.pcolormesh(xedges, yedges, Z.T)\n\n # 공백 제거\n plt.xticks([]), plt.yticks([])\n plt.tight_layout()\n plt.subplots_adjust(left = 0, bottom = 0, right = 1, top = 1, hspace = 0, wspace = 0)\n fig = plt.figure(figsize=(image_y/101.0,image_x/100.0))\n\n ax = fig.add_subplot(111)\n\n # alpha=0.5를 통해 색을 반투명하게 설정\n ax.contourf(xi, yi, zi.reshape(xi.shape), alpha=0.5, cmap='RdYlBu_r')\n\n ax.set_xlim(0, image_y)\n ax.set_ylim(image_x, 0)\n ax.axis('off')\n ax.autoscale(False)\n ext = ax.get_window_extent().transformed(plt.gcf().dpi_scale_trans.inverted())\n\n # 미리 지정한 pitch에 덮어씌우기\n im = plt.imread('../image/pitch.png')\n ax.imshow(im, extent=[0, image_y, image_x,0 ])\n\n fig.savefig('../result/result_heatmap.png', bbox_inches=ext)\n plt.clf()\n plt.close(fig)\n\nif __name__ == \"__main__\":\n printHeatMap(337,600) # 테스트용 하드코딩\n plt.show()\n\n\n# 참고 컬러바 출력 코드\n# ax=plt.gca() #get the current axes\n# PCM=ax.get_children()[2] #get the mappable, the 1st and the 2nd are the x and y axes\n# plt.colorbar(PCM, ax=ax) ","sub_path":"All_Is_Well_program/src/heatmap.py","file_name":"heatmap.py","file_ext":"py","file_size_in_byte":1679,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"270456885","text":"#!/usr/bin/env python\n\n# based on 'export-sprites.py' and 'glsprite.py' from TCHOW Rainbow; code used is released into the public domain.\n\n# Note: Script meant to be executed from within blender, as per:\n# blender --background --python export-scene.py -- \n\nimport sys, re\n\nargs = []\nfor i in range(0, len(sys.argv)):\n if sys.argv[i] == '--':\n args = sys.argv[i + 1:]\n\nif len(args) != 2:\n print(\n \"\\n\\nUsage:\\nblender --background --python export-scene.py -- [:layer] \\nExports the walk mech in layer (default 3) to a binary blob\\n\")\n exit(1)\n\ninfile = args[0]\nlayer = 3\nm = re.match(r'^(.*):(\\d+)$', infile)\nif m:\n infile = m.group(1)\n layer = int(m.group(2))\noutfile = args[1]\n\nprint(\"Will export walk mesh from layer \" + str(layer) + \" from file '\" + infile + \"' to blob '\" + outfile + \"'\");\n\nimport bpy\nimport mathutils\nimport struct\nimport math\n\n# ---------------------------------------------------------------------\n# Export scene:\n\nbpy.ops.wm.open_mainfile(filepath=infile)\n\n# Scene file format:\n# vtx0 contains all vertices of the walk mesh\n# nom0 contains all vertex normals of the walk mesh\n# tri0 contains all triangle vertex indices\n\nvertex_data = b\"\"\nvertex_normal_data = b\"\"\ntri_data = b\"\"\n\nwalk_mesh_found = False\n\nfor obj in bpy.data.objects:\n if obj.layers[layer - 1] and obj.type == 'MESH' and obj.name == 'WalkMesh':\n walk_mesh_found = True\n for vertex in obj.data.vertices:\n for x in vertex.co:\n vertex_data += struct.pack('f', x)\n for n in vertex.normal:\n vertex_normal_data += struct.pack('f', n)\n for poly in obj.data.polygons:\n # print(poly.vertices[3])\n assert (len(poly.vertices) == 3)\n tri_data += struct.pack('III', poly.vertices[0], poly.vertices[1], poly.vertices[2])\n\n vertex_count = len(obj.data.vertices)\n\n # check that we wrote as much data as anticipated:\n assert (vertex_count * 3 * 4 == len(vertex_data))\n assert (len(obj.data.polygons) * 3 * 4 == len(tri_data))\n assert (vertex_count * 3 * 4 == len(vertex_normal_data))\n\n print(vertex_count, 'number of vertices')\n print(len(obj.data.polygons), 'number of triangles')\n\nif walk_mesh_found:\n\n # write the strings chunk and scene chunk to an output blob:\n blob = open(outfile, 'wb')\n\n\n def write_chunk(magic, data):\n blob.write(struct.pack('4s', magic)) # type\n blob.write(struct.pack('I', len(data))) # length\n blob.write(data)\n\n\n write_chunk(b'vtx0', vertex_data)\n write_chunk(b'tri0', tri_data)\n write_chunk(b'nom0', vertex_normal_data)\n\n print(\"Wrote \" + str(blob.tell()) + \" bytes to '\" + outfile + \"'\")\n blob.close()\n\nelse:\n print(\"Cannot Find Walk Mesh!\")\n","sub_path":"meshes/export-walk-mesh.py","file_name":"export-walk-mesh.py","file_ext":"py","file_size_in_byte":2852,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"621112408","text":"from __future__ import unicode_literals\nfrom django.db import models\nfrom django.core.validators import URLValidator\nfrom django.core.exceptions import ValidationError\n\nclass BotManager(models.Manager):\n def getBotByName(self, name):\n try:\n bot = self.get(name=name)\n return bot\n except groupMeBot.DoesNotExist:\n return None\n\n def getBotByID(self, botID):\n try:\n bot = self.get(botID=botID)\n return bot\n except groupMeBot.DoesNotExist:\n return None\n\n def activateBot(self, botID):\n bot = self.getBotByID(botID)\n if (bot is not None):\n try:\n bot.active = True\n bot.full_clean()\n bot.save()\n return True\n except ValidationError:\n return False\n return False\n\n def deActivateBot(self, botID):\n bot = self.getBotByID(botID)\n if (bot is not None):\n try:\n bot.active = False\n bot.full_clean()\n bot.save()\n return True\n except ValidationError:\n return False\n return False\n\n def changeBotGroupName(self, botID, groupname):\n bot = self.getBotByID(botID)\n if (bot is not None):\n try:\n bot.groupname = groupname\n bot.full_clean()\n bot.save()\n return True\n except ValidationError:\n return False\n return False\n\n def addBot(self, name, botID, victimID, groupname, avatar_url, callback_url):\n try: \n bot = groupMeBot(name = name,\n botID = botID,\n victimID = victimID,\n avatar_url = avatar_url,\n callback_url = callback_url,\n groupname = groupname)\n bot.full_clean()\n bot.save()\n return True\n except ValidationError:\n return False\n\n def removeBotByName(self, name):\n if (self.getBotByName(name) is not None):\n numDeleted = self.getBotByName(name).delete()\n #only ever supposed to delete one bot\n if (numDeleted[0] != 1 or numDeleted[1]['bot.groupMeBot'] != 1):\n return False\n return True\n return False\n\n def removeBotByID(self, botID):\n if (self.getBotByID(botID) is not None):\n numDeleted = self.getBotByID(botID).delete()\n #only ever supposed to delete one bot\n if (numDeleted[0] != 1 or numDeleted[1]['bot.groupMeBot'] != 1):\n return False\n return True\n return False\n\n#inherits from Model\n#id field generated automatically, basically like SQL\nclass groupMeBot(models.Model):\n botID = models.TextField(unique=True)\n name = models.TextField(unique=True) #shorter than textfield\n victimID = models.IntegerField(unique=True)\n groupname = models.TextField(default=\"Tests\")\n callback_url = models.URLField(default=\"https://www.google.com\", validators=[URLValidator])\n avatar_url = models.URLField(default=\"https://www.google.com\", validators=[URLValidator])\n active = models.BooleanField(default=False)\n\n botmanager = BotManager()\n\n #__str__ for python 3, __unicode__ for python 2\n def __str__(self):\n return self.name\n'''\nclass groupMeMember(models.Model):\n title = models.CharField(max_length=140) #shorter than textfield \n body = models.TextField()\n date = models.DateTimeField()\n def __str__(self):\n return self.title\n'''\n\n'''\nclass groupMeGroup(models.Model):\n name = models.TextField(unique=True) \n groupid = models.TextField()\n \n def __str__(self):\n return self.name\n'''","sub_path":"bot/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":3858,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"526206644","text":"# Question1: read and write csv data\ndef read_and_write_csv_data():\n \"\"\"\n stocks.csv\n Symbol,Price,Date,Time,Change,Volume\n \"AA\",39.48,\"6/11/2007\",\"9:36am\",-0.18,181800\n \"AIG\",71.38,\"6/11/2007\",\"9:36am\",-0.15,195500\n \"AXP\",62.58,\"6/11/2007\",\"9:36am\",-0.46,935000\n \"BA\",98.31,\"6/11/2007\",\"9:36am\",+0.12,104800\n \"C\",53.08,\"6/11/2007\",\"9:36am\",-0.25,360900\n \"CAT\",78.29,\"6/11/2007\",\"9:36am\",-0.23,225400\n :return:\n \"\"\"\n\n import csv\n with open('stocks.csv') as f:\n f_csv = csv.reader(f)\n headers = next(f_csv)\n for row in f_csv:\n pass\n\n # more maintainer\n from collections import namedtuple\n with open('stock.csv') as f:\n f_csv = csv.reader(f)\n headings = next(f_csv)\n Row = namedtuple('Row', headings)\n for r in f_csv:\n row = Row(*r)\n # Process row\n\n # Another method: Using the DictReader\n import csv\n with open('stocks.csv') as f:\n f_csv = csv.DictReader(f)\n for row in f_csv:\n # process row\n # row['Symbol'] row['Change']\n pass\n\n # Write to CSV datas by using the writer object\n headers = ['Symbol', 'Price', 'Date', 'Time', 'Change', 'Volume']\n rows = [('AA', 39.48, '6/11/2007', '9:36am', -0.18, 181800),\n ('AIG', 71.38, '6/11/2007', '9:36am', -0.15, 195500),\n ('AXP', 62.58, '6/11/2007', '9:36am', -0.46, 935000),\n ]\n\n with open('stocks.csv', 'w') as f:\n f_csv = csv.writer(f)\n f_csv.writerow(headers)\n f_csv.writerows(rows)\n\n # 如果你有一个字典序列的数据,可以像这样做:\n headers = ['Symbol', 'Price', 'Date', 'Time', 'Change', 'Volume']\n rows = [{'Symbol': 'AA', 'Price': 39.48, 'Date': '6/11/2007',\n 'Time': '9:36am', 'Change': -0.18, 'Volume': 181800},\n {'Symbol': 'AIG', 'Price': 71.38, 'Date': '6/11/2007',\n 'Time': '9:36am', 'Change': -0.15, 'Volume': 195500},\n {'Symbol': 'AXP', 'Price': 62.58, 'Date': '6/11/2007',\n 'Time': '9:36am', 'Change': -0.46, 'Volume': 935000},\n ]\n\n with open('stocks.csv', 'w') as f:\n f_csv = csv.DictWriter(f, headers)\n f_csv.writeheader()\n f_csv.writerows(rows)\n\n # Preference for csv module partitioning or parsing CSV data\n # this way is not recommended\n with open('stocks.csv') as f:\n for line in f:\n row = line.split(',')\n # 使用这种方式的一个缺点就是你仍然需要去处理一些棘手的细节问题。 比如,如果某些字段值被\n # 引号包围,你不得不去除这些引号。 另外,如果一个被引号包围的字段碰巧含有一个逗号,那么\n # 程序就会因为产生一个错误大小的行而出错。\n # 默认情况下,csv 库可识别Microsoft Excel所使用的CSV编码规则。\n # Example of reading tab-separated values\n with open('stock.tsv') as f:\n f_tsv = csv.reader(f, delimiter='\\t')\n for row in f_tsv:\n # Process row\n ...\n # 如果你正在读取CSV数据并将它们转换为命名元组,需要注意对列名进行合法性认证。\n # 例如,一个CSV格式文件有一个包含非法标识符的列头行,类似下面这样:\n # Street Address,Num-Premises,Latitude,Longitude 5412 N CLARK,10,41.980262,-87.668452\n import re\n with open('stock.csv') as f:\n f_csv = csv.reader(f)\n headers = [re.sub('[^a-zA-Z_]', '_', h) for h in next(f_csv)]\n Row = namedtuple('Row', headers)\n for r in f_csv:\n row = Row(*r)\n # Process row\n ...\n # 还有重要的一点需要强调的是,csv产生的数据都是字符串类型的,它不会做任何其他类型的转换。\n # 如果你需要做这样的类型转换,你必须自己手动去实现。 下面是一个在CSV数据上执行其他类型\n # 转换的例子:\n # this convert 实际是传递的一个闭包\n col_types = [str, float, str, str, float, int]\n with open('stocks.csv') as f:\n f_csv = csv.reader(f)\n headers = next(f_csv)\n for row in f_csv:\n # Apply conversions to the row items\n row = tuple(\n convert(value) for convert, value in zip(col_types, row))\n ...\n # 另外,下面是一个转换字典中特定字段的例子:\n print('Reading as dicts with type conversion')\n field_types = [('Price', float),\n ('Change', float),\n ('Volume', int)]\n\n with open('stocks.csv') as f:\n for row in csv.DictReader(f):\n row.update((key, conversion(row[key]))\n for key, conversion in field_types)\n print(row)\n\n\n# Question2: read and write json data\ndef read_and_write_json_data():\n # To json\n import json\n\n data = {\n 'name': 'ACME',\n 'shares': 100,\n 'price': 542.23\n }\n\n json_str = json.dumps(data)\n\n # To string\n data = json.loads(json_str)\n\n # handle with file\n # Writing JSON data\n with open('data.json', 'w') as f:\n json.dump(data, f)\n\n # Reading data back\n with open('data.json', 'r') as f:\n data = json.load(f)\n\n # SON编码支持的基本数据类型为 None , bool , int , float 和 str , 以及包含这些\n # 类型数据的lists,tuples和dictionaries。\n # 比如,True会被映射为true,False被映射为false,而None会被映射为null。\n json.dumps(False) # false\n d = {'a': True,\n 'b': 'Hello',\n 'c': None}\n json.dumps(d) # '{\"b\": \"Hello\", \"c\": null, \"a\": true}'\n\n # Using pprint let the code more beauty\n from pprint import pprint\n pprint(d)\n\n # 一般来讲,JSON解码会根据提供的数据创建dicts或lists。 如果你想要创建其他类型的对象,\n # 可以给 json.loads() 传递object_pairs_hook或object_hook参数。\n # 例如,下面是演示如何解码JSON数据并在一个OrderedDict中保留其顺序的例子:\n s = '{\"name\": \"ACME\", \"shares\": 50, \"price\": 490.1}'\n from collections import OrderedDict\n data = json.loads(s, object_pairs_hook=OrderedDict)\n print(data)\n\n # 下面是如何将一个JSON字典转换为一个Python对象例子:\n class JSONObject:\n def __init__(self, d):\n self.__dict__ = d\n data = json.loads(s, object_hook=JSONObject)\n print(data.name)\n print(data.shares)\n print(data.price)\n\n data = json.loads(s, object_pairs_hook=OrderedDict)\n print(json.dumps(data))\n print(json.dumps(data, indent=4))\n\n # 如果你想序列化对象实例,你可以提供一个函数,它的输入是一个实例,\n # 返回一个可序列化的字典。例如:\n def serialize_instance(obj):\n d = {'__classname__': type(obj).__name__}\n d.update(vars(obj))\n return d\n # 如果你想反过来获取这个实例,可以这样做:\n # Dictionary mapping names to known classes\n class Point:\n def __init__(self, x, y):\n self.x = x\n self.y = y\n\n classes = {\n 'Point': Point\n }\n\n def unserialize_object(d):\n clsname = d.pop('__classname__', None)\n if clsname:\n cls = classes[clsname]\n obj = cls.__new__(cls) # Make instance without calling __init__\n for key, value in d.items():\n setattr(obj, key, value)\n return obj\n else:\n return d\n\n p = Point(2, 3)\n s = json.dumps(p, default=serialize_instance)\n print(s) # '{\"__classname__\": \"Point\", \"y\": 3, \"x\": 2}'\n a = json.loads(s, object_hook=unserialize_object)\n print(a)\n print(a.x)\n print(a.y)\n\n\n# Question3: Encoding and decoding hexadecimal numbers\ndef encoding_and_decoding_hexadecimal_numbers():\n # You want to decode a hex string into a byte string or encode a byte string\n # into a hex string\n # Initial byte string\n s = b'hello'\n # Encode as hex\n import binascii\n h = binascii.b2a_hex(s)\n print(h)\n # Decode back to bytes\n print(binascii.a2b_hex(h))\n\n\n# Question4: Encoding and decoding Base64 data\ndef encoding_and_decoding_base64_data():\n # Some byte data\n s = b'hello'\n import base64\n # Encode as Base64\n a = base64.b64encode(s)\n print(a)\n\n # Decode from Base64\n print(base64.b64decode(a))\n\n # Base64编码仅仅用于面向字节的数据比如字节字符串和字节数组。 此外,编码处理的输出结果\n # 总是一个字节字符串。 如果你想混合使用Base64编码的数据和Unicode文本,你必须添加一个\n # 额外的解码步骤。例如:\n a = base64.b64encode(s).decode('ascii')\n print(a)\n\n\n# Question5: Read and write binary array data\ndef read_write_binary_array_data():\n # You want to read and write a binary array of structured data\n # into a Python tuple.\n # Binary data can be processed using the structure module.\n from struct import Struct\n def write_records(records, format, f):\n '''\n Write a sequence of tuples to a binary file of structures.\n '''\n record_struct = Struct(format)\n for r in records:\n f.write(record_struct.pack(*r))\n\n # Example\n if __name__ == '__main__':\n records = [(1, 2.3, 4.5),\n (6, 7.8, 9.0),\n (12, 13.4, 56.7)]\n with open('data.b', 'wb') as f:\n write_records(records, '= curdate();\"\ntime_pool = pd.read_sql(sql_time, db)['TABLE_NAME'].tolist()\nstock_pool = [x.lower() for x in lt_stock_list if x.lower() not in time_pool]\nif os.path.exists('Analysis_MoneyFlow_name.log'):\n with open('Analysis_MoneyFlow_name.log', \"r\", encoding='utf-8') as f:\n errlist = f.read().split(', ')\n stock_pool = [x for x in stock_pool if x in errlist]\n os.remove('Analysis_MoneyFlow_name.log')\nelse:\n pass\n\ntotal = len(stock_pool)\nidx = 0\n\n# %%\nfor name in stock_pool:\n idx += 1\n try:\n df_smf = pd.read_sql(\"SELECT * FROM stock_moneyflow.`%s` AS t;\" % name,\n db,\n index_col='trade_date')\n\n df_smf['jgV'] = df_smf.eval('buy_elg_vol - sell_elg_vol')\n df_smf['dhV'] = df_smf.eval('buy_lg_vol - buy_lg_vol - jgV')\n df_smf['zhV'] = df_smf.eval('buy_md_vol - sell_md_vol - dhV')\n df_smf['shV'] = df_smf.eval('sell_md_vol - buy_md_vol')\n\n # %%\n df_sb = pd.read_sql(\n \"SELECT trade_date,float_share FROM stock_basic.`%s` AS t;\" % name,\n db,\n index_col='trade_date')\n df_a1 = pd.concat([df_smf[['jgV', 'dhV', 'zhV', 'shV']], df_sb],\n axis=1)\n myD = 60\n df_a1['super_capital'] = df_a1['jgV'].ewm(\n span=myD, adjust=False).mean() * myD / df_a1['float_share']\n df_a1['large_capital'] = df_a1['dhV'].ewm(\n span=myD, adjust=False).mean() * myD / df_a1['float_share']\n df_a1['middle_capital'] = df_a1['zhV'].ewm(\n span=myD, adjust=False).mean() * myD / df_a1['float_share']\n df_a1['retail_capital'] = df_a1['shV'].ewm(\n span=myD, adjust=False).mean() * myD / df_a1['float_share']\n\n df_sd = pd.read_sql(\n \"SELECT trade_date,pre_close,pct_chg FROM stock_daily.`%s` AS t;\" %\n name,\n db,\n index_col='trade_date')\n df_a1 = pd.concat([df_a1, df_sd], axis=1)\n\n # %%\n def label_encoder1(df):\n if (df['super_capital'] - df['large_capital']) > 0:\n return 0\n else:\n return 1\n\n def label_encoder2(df):\n if (df['super_capital'] - df['middle_capital']) > 0:\n return 0\n else:\n return 1\n\n def label_encoder3(df):\n if (df['super_capital'] - df['retail_capital']) > 0:\n return 0\n else:\n return 1\n\n def label_encoder4(df):\n if (df['large_capital'] - df['middle_capital']) > 0:\n return 0\n else:\n return 1\n\n def label_encoder5(df):\n if (df['large_capital'] - df['retail_capital']) > 0:\n return 0\n else:\n return 1\n\n def label_encoder6(df):\n if (df['middle_capital'] - df['retail_capital']) > 0:\n return 0\n else:\n return 1\n\n def estimate(df):\n if df['pct_chg'] < 0:\n return 0\n else:\n return 1\n\n df_a1['label_1'] = df_a1.apply(label_encoder1, axis=1)\n df_a1['label_2'] = df_a1.apply(label_encoder2, axis=1)\n df_a1['label_3'] = df_a1.apply(label_encoder3, axis=1)\n df_a1['label_4'] = df_a1.apply(label_encoder4, axis=1)\n df_a1['label_5'] = df_a1.apply(label_encoder5, axis=1)\n df_a1['label_6'] = df_a1.apply(label_encoder6, axis=1)\n df_a1['class'] = df_a1.apply(estimate, axis=1)\n\n # 打印进度\n print('Seq: ' + str(idx) + ' of ' + str(total) + '\\tCode: ' +\n str(name))\n\n # %%\n df = df_a1[[\n 'pre_close', 'pct_chg', 'super_capital', 'large_capital',\n 'middle_capital', 'retail_capital', 'label_1', 'label_2',\n 'label_3', 'label_4', 'label_5', 'label_6', 'class'\n ]]\n create = \"CREATE TABLE IF NOT EXISTS `%s`(\\\n `trade_date` DATE,\\\n pre_close DECIMAL(20, 2) DEFAULT 0,\\\n pct_chg DECIMAL(20, 2) DEFAULT 0,\\\n `super_capital` DECIMAL(20, 2) DEFAULT 0,\\\n `large_capital` DECIMAL(20, 2) DEFAULT 0,\\\n `middle_capital` DECIMAL(20, 2) DEFAULT 0,\\\n `retail_capital` DECIMAL(20, 2) DEFAULT 0,\\\n `label_1` int DEFAULT NULL,\\\n `label_2` int DEFAULT NULL,\\\n `label_3` int DEFAULT NULL,\\\n `label_4` int DEFAULT NULL,\\\n `label_5` int DEFAULT NULL,\\\n `label_6` int DEFAULT NULL,\\\n `class` int DEFAULT NULL,\\\n PRIMARY KEY (trade_date)\\\n )ENGINE = MyISAM CHARSET = UTF8MB4;\" % name\n with db.connect() as con:\n con.execute('use analysis_moneyflow;')\n con.execute(create)\n db_smy = create_engine(\n \"mysql+pymysql://root:root@localhost:3306/analysis_moneyflow\")\n\n # %%\n df_base = pd.read_sql(name.lower(), db_smy, columns=['trade_date'])\n df = df[~df['trade_date'].isin(df_base['trade_date'])]\n df.reset_index(inplace=True)\n df.rename(columns={\n 'index': 'trade_date',\n }, inplace=True)\n df.to_sql(name, db_smy, if_exists='append', index=False)\n\n# %%\n except Exception as err:\n with open('Analysis_MoneyFlow_err.log', \"a\", encoding='utf-8') as f:\n f.write(\"{}\\t({}.{})\\n\".format(\n err, name,\n datetime.datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")) +\n \"-\" * 30 + \"\\n\")\n with open('Analysis_MoneyFlow_name.log', \"a\", encoding='utf-8') as f:\n f.write(\"{}, \".format(name))\n continue\n","sub_path":"stock_data/Analysis_MoneyFlow/Analysis_MoneyFlow.py","file_name":"Analysis_MoneyFlow.py","file_ext":"py","file_size_in_byte":5988,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"232824911","text":"\ndef define_network(input_var, channels, image_size,classification_mode=False):\n (width, height) = image_size\n\n from lasagne.layers import InputLayer, ExpressionLayer, DenseLayer, DropoutLayer, NonlinearityLayer\n from lasagne.nonlinearities import softmax\n from lasagne.layers import Pool2DLayer as PoolLayer\n from lasagne.layers import Conv2DLayer as ConvLayer\n\n net = {}\n net['input'] = InputLayer((None, channels, height, width), input_var=input_var)\n net['conv1_1'] = ConvLayer(\n net['input'], 64, 3, pad=1, flip_filters=False)\n net['conv1_2'] = ConvLayer(\n net['conv1_1'], 64, 3, pad=1, flip_filters=False)\n net['pool1'] = PoolLayer(net['conv1_2'], 2)\n net['conv2_1'] = ConvLayer(\n net['pool1'], 128, 3, pad=1, flip_filters=False)\n net['conv2_2'] = ConvLayer(\n net['conv2_1'], 128, 3, pad=1, flip_filters=False)\n net['pool2'] = PoolLayer(net['conv2_2'], 2)\n net['conv3_1'] = ConvLayer(\n net['pool2'], 256, 3, pad=1, flip_filters=False)\n net['conv3_2'] = ConvLayer(\n net['conv3_1'], 256, 3, pad=1, flip_filters=False)\n net['conv3_3'] = ConvLayer(\n net['conv3_2'], 256, 3, pad=1, flip_filters=False)\n net['pool3'] = PoolLayer(net['conv3_3'], 2)\n net['conv4_1'] = ConvLayer(\n net['pool3'], 512, 3, pad=1, flip_filters=False)\n net['conv4_2'] = ConvLayer(\n net['conv4_1'], 512, 3, pad=1, flip_filters=False)\n net['conv4_3'] = ConvLayer(\n net['conv4_2'], 512, 3, pad=1, flip_filters=False)\n net['pool4'] = PoolLayer(net['conv4_3'], 2)\n net['conv5_1'] = ConvLayer(\n net['pool4'], 512, 3, pad=1, flip_filters=False)\n net['conv5_2'] = ConvLayer(\n net['conv5_1'], 512, 3, pad=1, flip_filters=False)\n net['conv5_3'] = ConvLayer(\n net['conv5_2'], 512, 3, pad=1, flip_filters=False)\n net['pool5'] = PoolLayer(net['conv5_3'], 2)\n net['fc6'] = DenseLayer(net['pool5'], num_units=4096)\n net['fc6_dropout'] = DropoutLayer(net['fc6'], p=0.5)\n net['fc7'] = DenseLayer(net['fc6_dropout'], num_units=4096)\n\n if(classification_mode):\n net['fc7_dropout'] = DropoutLayer(net['fc7'], p=0.5)\n net['fc8'] = DenseLayer(net['fc7_dropout'], num_units=2622, nonlinearity=None)\n net['prob'] = NonlinearityLayer(net['fc8'], softmax)\n output_layer = net[\"prob\"]\n last_inited_layer = net[\"prob\"]\n else:\n\n\n net['code'] = ExpressionLayer(net['fc7'], lambda X: X / X.norm(2, axis=1).reshape((X.shape[0], 1)),\n output_shape='auto')\n output_layer = net[\"code\"]\n last_inited_layer = net['fc7']\n\n return output_layer, last_inited_layer\n\ndef initialize(last_inited_layer,modelfilename,classification_mode=False):\n if(modelfilename.endswith('.mat')) :\n from scipy.io import matlab\n data = matlab.loadmat(modelfilename, struct_as_record=False, squeeze_me=True)\n srcnet = data['net']\n import lasagne\n t = 0\n tlayers = lasagne.layers.get_all_layers(last_inited_layer)\n layerlabels = ['input', 'conv1_1', 'conv1_2','pool1', 'conv2_1', 'conv2_2', 'pool2', 'conv3_1', 'conv3_2', 'conv3_3', 'pool3', 'conv4_1', 'conv4_2','conv4_3', 'pool4', 'conv5_1', 'conv5_2', 'conv5_3', 'pool5', 'fc6', 'fc6_dropout', 'fc7']\n if(classification_mode):\n layerlabels.extend(['fc7_dropout','fc8'])\n for s, srclayer in enumerate(srcnet.layers):\n if (t >= len(layerlabels)):\n break\n if ('weights' in srclayer._fieldnames):\n while(srclayer.name != layerlabels[t]):\n t+=1\n tlayer = tlayers[t]\n if(srclayer.name[0] == 'f') :\n w = srclayer.weights[0]\n # print('fc%s -> %s' %(w.shape,tlayer.W.get_value().shape))\n if(w.shape[0]!=tlayer.W.get_value().shape[0]):\n w = w.transpose(2, 0, 1, 3)\n w = w.reshape(-1, w.shape[-1])\n tlayer.W.set_value(w)\n else:\n w = srclayer.weights[0]\n # print('conv %s -> %s' %(w.shape,tlayer.W.get_value().shape))\n w = w.transpose(3,2,0,1)\n tlayer.W.set_value(w)\n tlayer.b.set_value(srclayer.weights[1])\n t+=1\n else:\n continue\n else:\n import cPickle as pickle\n with open(modelfilename, 'rb') as f:\n pvalues = pickle.load(f)\n\n import lasagne\n lasagne.layers.set_all_param_values(last_inited_layer, pvalues[0:30])\n\ndef load_means(modelfilename):\n from scipy.io import matlab\n data = matlab.loadmat(modelfilename, struct_as_record=False, squeeze_me=True)\n srcnet = data['net']\n import numpy as np\n mean_image = srcnet.normalization.averageImage\n mean_image = mean_image[:,np.newaxis, np.newaxis]\n mean_image = np.tile(mean_image,[1, srcnet.normalization.imageSize[0], srcnet.normalization.imageSize[1]])\n std_image = np.ones(3)\n return (mean_image, std_image)\n\n","sub_path":"vgg_face_net.py","file_name":"vgg_face_net.py","file_ext":"py","file_size_in_byte":5108,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"539111380","text":"import logging\nfrom math import floor\n\nfrom numpy import array, zeros\nfrom networkx import DiGraph, add_path\n\nfrom cspy import BiDirectional\n\nfrom vrpy.subproblem import _SubProblemBase\n\nlogger = logging.getLogger(__name__)\n\n\nclass _SubProblemCSPY(_SubProblemBase):\n \"\"\"\n Solves the sub problem for the column generation procedure with cspy;\n attemps to find routes with negative reduced cost.\n\n Inherits problem parameters from `SubproblemBase`\n \"\"\"\n\n def __init__(self, *args, exact):\n \"\"\"Initializes resources.\"\"\"\n # Pass arguments to base\n super(_SubProblemCSPY, self).__init__(*args)\n self.exact = exact\n # Resource names\n self.resources = [\n \"stops/mono\",\n \"load\",\n \"time\",\n \"time windows\",\n \"collect\",\n \"deliver\",\n ]\n # Set number of resources as attribute of graph\n self.sub_G.graph[\"n_res\"] = len(self.resources)\n # Default lower and upper bounds\n self.min_res = [0] * len(self.resources)\n # Add upper bounds for mono, stops, load and time, and time windows\n total_demand = sum([self.sub_G.nodes[v][\"demand\"] for v in self.sub_G.nodes()])\n self.max_res = [\n floor(len(self.sub_G.nodes()) / 2), # stop/mono\n floor(total_demand / 2), # load\n sum(\n [self.sub_G.edges[u, v][\"time\"] for u, v in self.sub_G.edges()]\n ), # time\n 1, # time windows\n total_demand, # pickup\n total_demand, # deliver\n ]\n # Initialize cspy edge attributes\n for edge in self.sub_G.edges(data=True):\n edge[2][\"res_cost\"] = zeros(len(self.resources))\n # Initialize max feasible arrival time\n self.T = 0\n\n # @profile\n def solve(self, time_limit):\n \"\"\"\n Solves the subproblem with cspy.\n\n Resolves until:\n 1. heuristic algorithm gives a new route (column with -ve reduced cost);\n 2. exact algorithm gives a new route;\n 3. neither heuristic nor exact give a new route.\n\n Note : time_limit has no effect for the moment\n \"\"\"\n if not self.run_subsolve:\n return self.routes, False\n\n self.formulate()\n logger.debug(\"resources = {}\".format(self.resources))\n logger.debug(\"min res = {}\".format(self.min_res))\n logger.debug(\"max res = {}\".format(self.max_res))\n\n more_routes = False\n\n while True:\n if self.exact:\n alg = BiDirectional(\n self.sub_G,\n self.max_res,\n self.min_res,\n direction=\"both\",\n method=\"generated\",\n time_limit=time_limit,\n REF_forward=self.get_REF(\"forward\"),\n REF_backward=self.get_REF(\"backward\"),\n REF_join=self.get_REF(\"join\"),\n )\n else:\n alg = BiDirectional(\n self.sub_G,\n self.max_res,\n self.min_res,\n direction=\"both\",\n method=\"generated\",\n time_limit=time_limit,\n threshold=-1,\n REF_forward=self.get_REF(\"forward\"),\n REF_backward=self.get_REF(\"backward\"),\n REF_join=self.get_REF(\"join\"),\n )\n alg.run()\n logger.debug(\"subproblem\")\n logger.debug(\"cost = %s\" % alg.total_cost)\n logger.debug(\"resources = %s\" % alg.consumed_resources)\n if alg.total_cost < -(1e-3):\n more_routes = True\n self.add_new_route(alg.path)\n logger.debug(\"new route %s\" % alg.path)\n logger.debug(\"reduced cost = %s\" % alg.total_cost)\n logger.debug(\"real cost = %s\" % self.total_cost)\n break\n # If not already solved exactly\n elif not self.exact:\n # Solve exactly from here on\n self.exact = True\n # Solved heuristically and exactly and no more routes\n else:\n break\n return self.routes, more_routes\n\n def formulate(self):\n \"\"\"Updates max_res depending on which contraints are active.\"\"\"\n # Problem specific constraints\n if self.num_stops:\n self.add_max_stops()\n else:\n self.add_monotone()\n if self.load_capacity:\n self.add_max_load()\n if self.duration:\n self.add_max_duration()\n if self.time_windows:\n if not self.duration:\n # Update upper bound for duration\n self.max_res[2] = 1 + self.sub_G.nodes[\"Sink\"][\"upper\"]\n # Time windows feasibility\n self.max_res[3] = 0\n # Maximum feasible arrival time\n self.T = max(\n self.sub_G.nodes[v][\"upper\"]\n + self.sub_G.nodes[v][\"service_time\"]\n + self.sub_G.edges[v, \"Sink\"][\"time\"]\n for v in self.sub_G.predecessors(\"Sink\")\n )\n\n if self.load_capacity and self.distribution_collection:\n self.max_res[4] = self.load_capacity[self.vehicle_type]\n self.max_res[5] = self.load_capacity[self.vehicle_type]\n\n def add_new_route(self, path):\n \"\"\"Create new route as DiGraph and add to pool of columns\"\"\"\n route_id = len(self.routes) + 1\n new_route = DiGraph(name=route_id)\n add_path(new_route, path)\n self.total_cost = 0\n for (i, j) in new_route.edges():\n edge_cost = self.sub_G.edges[i, j][\"cost\"][self.vehicle_type]\n self.total_cost += edge_cost\n new_route.edges[i, j][\"cost\"] = edge_cost\n if i != \"Source\":\n self.routes_with_node[i].append(new_route)\n new_route.graph[\"cost\"] = self.total_cost\n new_route.graph[\"vehicle_type\"] = self.vehicle_type\n self.routes.append(new_route)\n\n def add_max_stops(self):\n \"\"\"Updates maximum number of stops.\"\"\"\n # Change label\n self.resources[0] = \"stops\"\n # The Sink does not count (hence + 1)\n self.max_res[0] = self.num_stops + 1\n for (i, j) in self.sub_G.edges():\n self.sub_G.edges[i, j][\"res_cost\"][0] = 1\n\n def add_monotone(self):\n \"\"\"Updates monotone resource.\"\"\"\n # Change label\n self.resources[0] = \"mono\"\n for (i, j) in self.sub_G.edges():\n self.sub_G.edges[i, j][\"res_cost\"][0] = 1\n\n def add_max_load(self):\n \"\"\"Updates maximum load.\"\"\"\n self.max_res[1] = self.load_capacity[self.vehicle_type]\n for (i, j) in self.sub_G.edges():\n demand_head_node = self.sub_G.nodes[j][\"demand\"]\n self.sub_G.edges[i, j][\"res_cost\"][1] = demand_head_node\n\n def add_max_duration(self):\n \"\"\"Updates maximum travel time.\"\"\"\n self.max_res[2] = self.duration\n for (i, j) in self.sub_G.edges():\n travel_time = self.sub_G.edges[i, j][\"time\"]\n self.sub_G.edges[i, j][\"res_cost\"][2] = travel_time\n\n def get_REF(self, type_):\n \"\"\"\n Returns custom REFs if time, time windows, and/or distribution collection.\n Based on Righini and Salani (2006).\n \"\"\"\n if self.time_windows or self.distribution_collection:\n # Use custom REF\n if type_ == \"forward\":\n return self.REF_forward\n elif type_ == \"backward\":\n return self.REF_backward\n elif type_ == \"join\":\n return self.REF_join\n else:\n # Use default\n return\n\n def REF_forward(self, cumulative_res, edge, **kwargs):\n \"\"\"\n Resource extension for forward paths.\n \"\"\"\n new_res = array(cumulative_res)\n # extract data\n i, j = edge[0:2]\n # stops/monotone resource\n new_res[0] += 1\n # load\n new_res[1] += self.sub_G.nodes[j][\"demand\"]\n # time\n # Service times\n theta_i = self.sub_G.nodes[i][\"service_time\"]\n theta_j = self.sub_G.nodes[j][\"service_time\"]\n theta_t = self.sub_G.nodes[\"Sink\"][\"service_time\"]\n # Travel times\n travel_time_ij = self.sub_G.edges[i, j][\"time\"]\n try:\n travel_time_jt = self.sub_G.edges[j, \"Sink\"][\"time\"]\n except KeyError:\n travel_time_jt = 0\n # Time windows\n # Lower\n a_j = self.sub_G.nodes[j][\"lower\"]\n a_t = self.sub_G.nodes[\"Sink\"][\"lower\"]\n # Upper\n b_j = self.sub_G.nodes[j][\"upper\"]\n b_t = self.sub_G.nodes[\"Sink\"][\"upper\"]\n\n new_res[2] = max(new_res[2] + theta_i + travel_time_ij, a_j)\n\n # time-window feasibility resource\n if not self.time_windows or (\n new_res[2] <= b_j\n and new_res[2] < self.T - a_j - theta_j\n and a_t <= new_res[2] + travel_time_jt + theta_t <= b_t\n ):\n new_res[3] = 0\n else:\n new_res[3] = 1\n\n if self.distribution_collection:\n # Pickup\n new_res[4] += self.sub_G.nodes[j][\"collect\"]\n # Delivery\n new_res[5] = max(new_res[5] + self.sub_G.nodes[j][\"demand\"], new_res[4])\n\n return new_res\n\n def REF_backward(self, cumulative_res, edge, **kwargs):\n \"\"\"\n Resource extension for backward paths.\n \"\"\"\n new_res = array(cumulative_res)\n i, j = edge[0:2]\n # monotone resource\n new_res[0] -= 1\n # load\n new_res[1] += self.sub_G.nodes[i][\"demand\"]\n # Get relevant service times (thetas) and travel time\n # Service times\n theta_i = self.sub_G.nodes[i][\"service_time\"]\n theta_j = self.sub_G.nodes[j][\"service_time\"]\n theta_s = self.sub_G.nodes[\"Source\"][\"service_time\"]\n # Travel times\n travel_time_ij = self.sub_G.edges[i, j][\"time\"]\n try:\n travel_time_si = self.sub_G.edges[\"Source\", i][\"time\"]\n except KeyError:\n travel_time_si = 0\n # Lower time windows\n a_i = self.sub_G.nodes[i][\"lower\"]\n a_s = self.sub_G.nodes[\"Source\"][\"lower\"]\n # Upper time windows\n b_i = self.sub_G.nodes[i][\"upper\"]\n b_j = self.sub_G.nodes[j][\"upper\"]\n b_s = self.sub_G.nodes[\"Source\"][\"upper\"]\n\n new_res[2] = max(new_res[2] + theta_j + travel_time_ij, self.T - b_i - theta_i)\n\n # time-window feasibility\n if not self.time_windows or (\n new_res[2] <= b_j\n and new_res[2] < self.T - a_i - theta_i\n and a_s <= new_res[2] + theta_s + travel_time_si <= b_s\n ):\n new_res[3] = 0\n else:\n new_res[3] = 1\n\n if self.distribution_collection:\n # Delivery\n new_res[5] += new_res[5] + self.sub_G.nodes[i][\"demand\"]\n # Pickup\n new_res[4] = max(new_res[5], new_res[4] + self.sub_G.nodes[i][\"collect\"])\n\n return new_res\n\n def REF_join(self, fwd_res, bwd_res, edge):\n \"\"\"\n Appropriate joining of forward and backward resources.\n \"\"\"\n final_res = zeros(len(self.resources))\n i, j = edge[0:2]\n\n # Get relevant service times (thetas) and travel time\n theta_i = self.sub_G.nodes[i][\"service_time\"]\n theta_j = self.sub_G.nodes[j][\"service_time\"]\n travel_time = self.sub_G.edges[i, j][\"time\"]\n\n # Invert monotone resource\n bwd_res[0] = self.max_res[0] - bwd_res[0]\n # Fill in final res\n # Monotone / stops\n final_res[0] = fwd_res[0] + bwd_res[0] + 1\n # Load\n final_res[1] = fwd_res[1] + bwd_res[1]\n # time\n final_res[2] = fwd_res[2] + theta_i + travel_time + theta_j + bwd_res[2]\n # Time windows\n if not self.time_windows or final_res[2] <= self.T:\n final_res[3] = fwd_res[3] + bwd_res[3]\n else:\n final_res[3] = 1\n\n if self.distribution_collection:\n final_res[4] = fwd_res[4] + bwd_res[4]\n final_res[5] = fwd_res[5] + bwd_res[5]\n\n return array(final_res)\n","sub_path":"vrpy/subproblem_cspy.py","file_name":"subproblem_cspy.py","file_ext":"py","file_size_in_byte":12291,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"551343254","text":"#! /usr/bin/env python3.5\n# -*- coding: utf-8 -*-\n# encoding='utf-8'\nimport pickle as cPickle\nimport numpy as np\nimport requests\nimport keras\nimport util\nimport sys\n\nmodel = util.init_model()\nmodel.load_weights(util.filepath)\n\ndef handle(url):\n r = requests.get(url)\n text = util.filter(str(r.content,'utf-8'))\n\n vocab = cPickle.load(open(\"./vocab.bin\",'rb'), encoding='latin1')\n X_test = util.encode(vocab, text)\n\n Y_test = model.predict(np.array(X_test).reshape([1,util.max_line_len]))\n if Y_test[0][0] > Y_test[0][1]:\n print(\"Evil URL ,\", url)\n else:\n print(\"Normal URL,\", url)\n #print(text)\n print(\"概率: \", max(Y_test[0][0] , Y_test[0][1]))\n\ndef main():\n url = \"http://baidu.com/\"\n if len(sys.argv) == 2:\n url = sys.argv[1]\n handle(url)\n\n\nif __name__ == '__main__':\n #main()\n testlist = ['http://www.danshiqi.com','http://www.tytz9.com','http://www.dyshicheng.com','http://www.jiansheng88.com','http://www.dayuefund.net','http://www.younaidp.com','http://92.lui66sy.xyz/pw/','http://8460.shuadan99.com/','https://0fffxx.com/fanhao/newest#header']\n for it in testlist:\n handle(it)","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1162,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"47484699","text":"import tensorflow as tf\nimport matplotlib.pyplot as plt\nimport supervised_learning.models.dnn.tf_v5_dnn_utils as dnn_utils\nimport supervised_learning.models.data.data_utils as data_utils\n\n\ndef dnn_model(x_train, y_train, x_test, y_test, activation, last_activation, learning_rate, cost_function, batch_size,\n num_of_iterations, dims_of_layers):\n params = dnn_utils.init_params(dims_of_layers)\n mini_batches = data_utils.generate_random_mini_batches(x_train, y_train, batch_size)\n num_of_layers = len(dims_of_layers)\n costs = []\n\n for i, mini_batch in enumerate(mini_batches):\n mini_batch_x, mini_batch_y = mini_batch\n for j in range(num_of_iterations):\n cost, grads = dnn_utils.forward_and_backward(params, mini_batch_x, mini_batch_y, activation,\n last_activation, cost_function, num_of_layers)\n params = dnn_utils.update_parameters(params, grads, learning_rate, num_of_layers)\n if j % 100 == 0:\n print(cost)\n costs.append(cost)\n\n accuracy_train = dnn_utils.predict(params, x_train, y_train, activation, last_activation, num_of_layers)\n print(accuracy_train)\n accuracy_test = dnn_utils.predict(params, x_test, y_test, activation, last_activation, num_of_layers)\n print(accuracy_test)\n\n plt.figure()\n plt.plot(costs)\n plt.xlabel(\"반복횟수\")\n plt.ylabel(\"cost\")\n plt.title(\"cost graph\")\n plt.show()\n return params\n\n\nx_train, x_test, y_train, y_test, output_dim = data_utils.load_sign_dataset()\nx_train, y_train, input_dim = data_utils.flatten(x_train, y_train)\nx_train = data_utils.centralized(x_train)\n\nx_test, y_test, input_dim = data_utils.flatten(x_test, y_test)\nx_test = data_utils.centralized(x_test)\n\ny_train = data_utils.one_hot_encoding(y_train, output_dim)\ny_test = data_utils.one_hot_encoding(y_test, output_dim)\n\nlearning_rate = 0.001\nnum_of_iteration = 10000\n\ndnn_model(x_train, y_train, x_test, y_test, \"relu\", \"softmax\", learning_rate=0.01, cost_function=\"cross_entropy\",\n batch_size=108, num_of_iterations=1000, dims_of_layers=[input_dim, 16, 16, output_dim])\n","sub_path":"supervised_learning/models/dnn/tf_dnn_model.py","file_name":"tf_dnn_model.py","file_ext":"py","file_size_in_byte":2181,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"399582368","text":"# Copyright 2016 Mellanox Technologies, Ltd\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\"\"\"sdn_journal change data to text\n\nRevision ID: 5d5e04ea01d5\nCreate Date: 2016-08-16 06:01:54.795542\n\n\"\"\"\n\nfrom alembic import op\nimport sqlalchemy as sa\n\nfrom networking_mlnx.plugins.ml2.drivers.sdn import constants as sdn_const\n\n\n# revision identifiers, used by Alembic.\nrevision = '5d5e04ea01d5'\ndown_revision = 'd02c04effb34'\n\n\ndef upgrade():\n op.alter_column('sdn_journal', 'data',\n existing_type=sa.PickleType(),\n type_=sa.Text,\n existing_nullable=True)\n op.alter_column('sdn_journal', 'state',\n existing_type=sa.Enum(\n sdn_const.PENDING, sdn_const.FAILED,\n sdn_const.PROCESSING, sdn_const.COMPLETED,\n name='state'),\n type_=sa.Enum(\n sdn_const.PENDING, sdn_const.FAILED,\n sdn_const.PROCESSING, sdn_const.MONITORING,\n sdn_const.COMPLETED,\n name='state'),\n existing_nullable=True)\n","sub_path":"networking_mlnx/db/migration/alembic_migrations/versions/newton/expand/5d5e04ea01d5_sdn_journal_change_data_to_text.py","file_name":"5d5e04ea01d5_sdn_journal_change_data_to_text.py","file_ext":"py","file_size_in_byte":1686,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"354427000","text":"import tensorflow as tf\nfrom keras.layers import Input, UpSampling2D\nfrom keras import backend as K\nimport numpy as np\n\nsess = tf.InteractiveSession()\n\ndef getImageTensor():\n \"\"\"\n (batch, height, width, channels)\n \"\"\"\n image = [ [ [1], [2], [3] ],\n [ [4], [5], [6] ],\n [ [7], [8], [9] ] ]\n\n return image \n\ndef getImageTensorMultiChannel():\n \"\"\"\n (batch, height, width, channels)\n \"\"\"\n def c(v):\n return [ v, v, v ]\n\n image = [ [ c(1), c(2), c(3) ],\n [ c(4), c(5), c(6) ],\n [ c(7), c(8), c(9) ] ]\n\n return image \n\ndef test1():\n l = UpSampling2D((2, 2))\n x = np.array([getImageTensor()])\n d = tf.convert_to_tensor(x, dtype=tf.float32)\n return l(d)\n \n\ndef test2():\n l = UpSampling2D((1, 1))\n x = np.array([getImageTensor()])\n d = tf.convert_to_tensor(x, dtype=tf.float32)\n\n return l(d)\n\ndef test3():\n l = UpSampling2D((2, 2))\n x = np.array([getImageTensorMultiChannel()])\n d = tf.convert_to_tensor(x, dtype=tf.float32)\n\n return l(d)\n\ntests = [test1, test2, test3]\n\nfor test in tests:\n print(test)\n x = test().eval()\n print(x)\n","sub_path":"python/upscale_test.py","file_name":"upscale_test.py","file_ext":"py","file_size_in_byte":1074,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"488903463","text":"\n# -*- coding: utf-8 -*-\n\n# Originally \n\n# Complete attempt at wrapping Objective-C objects in Python.\n# ObjCClass and ObjCInstance use cached objects with __new__\n\n# all imports listed explicitly to help PyChecker\nfrom pycocoa import NSApplication, NSBackingStoreBuffered, NSRect4_t, \\\n NSStr, NSWindow, NSWindowStyleMaskUsual, libobjc, \\\n ObjCClass, ObjCInstance, ObjCSubclass\n\n__version__ = '18.04.06'\n\n\nclass MySubclassImplementation(object):\n MySubclass = ObjCSubclass('NSObject', 'MySubclass')\n\n @MySubclass.method('v')\n def doSomething(self):\n if not hasattr(self, 'x'):\n self.x = 0\n self.x += 1\n print('doSomething', self.x)\n self.doSomething2()\n\n @MySubclass.method('v')\n def doSomething2(self):\n print('doSomething2', self.x)\n\n\ndef run_window():\n\n app = NSApplication.sharedApplication()\n# pool = NSAutoreleasePool.alloc().init() # PYCHOK expected\n\n window = NSWindow.alloc()\n window.initWithContentRect_styleMask_backing_defer_(\n NSRect4_t(100,100,300,300),\n NSWindowStyleMaskUsual,\n NSBackingStoreBuffered,\n False)\n window.setTitle_(NSStr(\"Class Window\"))\n window.makeKeyAndOrderFront_(None)\n\n app.run()\n\n\ndef stupid_stuff(class_name):\n\n NSObject = ObjCClass(class_name)\n print(NSObject)\n print(libobjc.object_getClassName(NSObject.ptr))\n\n x = NSObject.alloc() # PYCHOK expected\n print(libobjc.object_getClassName(x.ptr))\n print('x', x)\n print('x.init', x.init)\n print('x.init()', x.init())\n print('x.objc_class', x.objc_class)\n print(x.retainCount())\n print(x.retain())\n print(x.retainCount())\n print(x.retain())\n print(x.retainCount())\n print(x.retain())\n print(x.retainCount())\n\n if class_name == 'NSApplication':\n # only one NSApplication allowed\n return\n\n y = NSObject.alloc() # PYCHOK expected\n print('y', y)\n print('y.init', y.init)\n print('y.init()', y.init())\n print('y.objc_class', y.objc_class)\n print(y.retainCount())\n print(y.retain())\n print(y.retainCount())\n\n\nif __name__ == '__main__':\n\n import sys\n\n if len(sys.argv) < 2:\n print('USAGE: python class_wrapper4.py ')\n exit(1)\n\n class_name = sys.argv[1]\n\n MySubclass = ObjCClass('MySubclass')\n print(MySubclass)\n x = MySubclass.alloc().init()\n print(x)\n\n x.doSomething()\n x.doSomething()\n x.doSomething()\n\n print(len(ObjCInstance._objc_cache))\n x.release()\n del x\n print(len(ObjCInstance._objc_cache))\n\n stupid_stuff(class_name)\n# run_window()\n","sub_path":"test/class_wrapper4.py","file_name":"class_wrapper4.py","file_ext":"py","file_size_in_byte":2731,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"368978694","text":"from scipy import constants as C\nimport numpy as np\nimport dispersion\nimport surface\nimport volume\nimport input_tools\n\nmaterial_selection = ['NaCl','ZnSe'][1]\n\nmks_length = 10e-6 / (2*np.pi)\ninch = mks_length*100/2.54\ncm = mks_length*100\nbundle_scale = 1e-4\nsim = []\nwave = []\nray = []\noptics = []\ndiagnostics = []\nmess = 'Processing input file...\\n'\n\n# Preprocessing calculations\n\nhelper = input_tools.InputHelper(mks_length)\n\n# Setup pulse parameters\n\na00 = 1.0\nw00 = 1.0\nr00 = .001/mks_length # spot size of radiation\nrb = r00*bundle_scale\nt00 = 20e-15*C.c/mks_length\nband = (0.5,5.0)\n\n# Setup prism\n\nif material_selection=='ZnSe':\n\tmaterial = dispersion.ZnSe(mks_length)\n\tprism_box = (2/inch,1/inch,1.5/inch)\n\trefraction_angle = np.pi/8\nelse:\n\tmaterial = dispersion.NaCl(mks_length)\n\tprism_box = (2/inch,1/inch,1.5/inch)\n\trefraction_angle = np.pi/6\n\nnrefr = np.sqrt(1+material.chi(w00)[0])\nincidence_angle = np.arcsin(nrefr*np.sin(refraction_angle))\nmess += 'TIR angle = ' + str(np.arcsin(1/nrefr)*180/np.pi) + ' deg\\n'\n\n# General layout\n\nf = 0.1/mks_length\nMdeg1 = 25.0\nMdeg2 = 10.0\nRM = 0.5/inch\nfocus = (.1*f,0.0,0.0,0.0)\n\n# Set up dictionaries\n\nfor i in range(1):\n\n\tsim.append({'mks_length' : mks_length ,\n\t\t\t\t'mks_time' : mks_length/C.c ,\n\t\t\t\t'message' : mess})\n\n\twave.append([{\t# EM 4-potential (eA/mc^2) , component 0 not used\n\t\t\t\t\t'a0' : (0.0,0.0,0.0,a00) ,\n\t\t\t\t\t# 4-vector of pulse metrics: duration,x,y,z 1/e spot sizes\n\t\t\t\t\t'r0' : (t00,r00,r00,t00) ,\n\t\t\t\t\t# 4-wavenumber: omega,kx,ky,kz\n\t\t\t\t\t'k0' : (w00,w00,0.0,0.0) ,\n\t\t\t\t\t# 0-component of focus is time at which pulse reaches focal point.\n\t\t\t\t\t# If time=0 use paraxial wave, otherwise use spherical wave.\n\t\t\t\t\t# Thus in the paraxial case the pulse always starts at the waist.\n\t\t\t\t\t'focus' : focus,\n\t\t\t\t\t'supergaussian exponent' : 2},\n\t\t\t\t{\t# EM 4-potential (eA/mc^2) , component 0 not used\n\t\t\t\t\t'a0' : (0.0,0.0,0.0,a00) ,\n\t\t\t\t\t# 4-vector of pulse metrics: duration,x,y,z 1/e spot sizes\n\t\t\t\t\t'r0' : (t00/5,r00,r00,t00/5) ,\n\t\t\t\t\t# 4-wavenumber: omega,kx,ky,kz\n\t\t\t\t\t'k0' : (5*w00,5*w00,0.0,0.0) ,\n\t\t\t\t\t# 0-component of focus is time at which pulse reaches focal point.\n\t\t\t\t\t# If time=0 use paraxial wave, otherwise use spherical wave.\n\t\t\t\t\t# Thus in the paraxial case the pulse always starts at the waist.\n\t\t\t\t\t'focus' : focus,\n\t\t\t\t\t'supergaussian exponent' : 2}])\n\n\tray.append({\t'number' : (64,32,8,1),\n\t\t\t\t\t'bundle radius' : (rb,rb,rb,rb),\n\t\t\t\t\t'loading coordinates' : 'cylindrical',\n\t\t\t\t\t# Ray box is always put at the origin\n\t\t\t\t\t# It will be transformed appropriately by SeaRay to start in the wave\n\t\t\t\t\t'box' : band + (0.0,3*r00,0.0,2*np.pi,-2*t00,2*t00)})\n\n\toptics.append([\n\t\t{\t'object' : surface.disc('M1'),\n\t\t\t'reflective' : True,\n\t\t\t'radius' : RM,\n\t\t\t'origin' : helper.set_pos([2/cm,0.0,0.0]),\n\t\t\t'euler angles' : helper.rot_zx_deg(90-Mdeg1)},\n\n\t\t{\t'object' : surface.SphericalCap('M2'),\n\t\t\t'reflective' : True,\n\t\t\t'radius of sphere' : 2*f,\n\t\t\t'radius of edge' : RM,\n\t\t\t'origin' : helper.polar_move_zx(f-2/cm,180-2*Mdeg1),\n\t\t\t'euler angles' : helper.rot_zx_deg(-90-2*Mdeg1+Mdeg2)},\n\n\t\t{\t'object' : surface.disc('M3'),\n\t\t\t'reflective' : True,\n\t\t\t'radius' : RM,\n\t\t\t'origin' : helper.polar_move_zx(7/cm,-2*(Mdeg1-Mdeg2)),\n\t\t\t'euler angles' : helper.rot_zx_deg(0.5*(90-2*(Mdeg1-Mdeg2)))},\n\n\t\t{\t'object' : volume.PellinBroca('P1'),\n\t\t\t'dispersion outside' : dispersion.Vacuum(),\n\t\t\t'dispersion inside' : material,\n\t\t\t'size' : prism_box,\n\t\t\t'angle' : refraction_angle,\n\t\t\t'origin' : helper.move(-0.7*np.sin(incidence_angle)*prism_box[2],0.0,6/cm),\n\t\t\t'euler angles' : helper.rot_zx(incidence_angle)},\n\n\t\t{\t'object' : surface.SphericalCap('M4'),\n\t\t\t'reflective' : True,\n\t\t\t'radius of sphere' : 2*f,\n\t\t\t'radius of edge' : RM,\n\t\t\t'origin' : helper.move(7/cm,0.0,prism_box[1]),\n\t\t\t'euler angles' : helper.rot_zx_deg(90-Mdeg2)},\n\n\t\t{\t'object' : surface.EikonalProfiler('det'),\n\t\t\t'size' : (2/inch,2/inch),\n\t\t\t'origin' : helper.polar_move_zx(f,180-2*Mdeg2),\n\t\t\t'euler angles' : helper.rot_zx_deg(90-2*Mdeg2)}\n\t\t])\n\n\tdiagnostics.append({'suppress details' : False,\n\t\t\t\t\t\t'clean old files' : True,\n\t\t\t\t\t\t'orbit rays' : (32,2,8,1),\n\t\t\t\t\t\t'base filename' : 'out/test'})\n","sub_path":"examples/lwir-spectrometer.py","file_name":"lwir-spectrometer.py","file_ext":"py","file_size_in_byte":4128,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"10916738","text":"import io\nimport json\nimport pathlib\nimport tempfile\nimport contextlib\n\nfrom dffml.cli.cli import CLI\nfrom dffml import (\n DataFlow,\n Definition,\n Input,\n op,\n run,\n GetSingle,\n chdir,\n AsyncTestCase,\n)\n\nOP_DEF_STRING = \"\"\"\nfrom dffml import op,Definition\n\n@op(\n inputs={\"input_string\": Definition(name=\"InputString\", primitive=\"str\")},\n outputs={\n \"output_string\": Definition(name=\"OutputString\", primitive=\"str\")\n },\n)\ndef echo_string(input_string):\n return {\"output_string\": input_string}\n\n\"\"\"\n\n\nclass TestDataflowCreate(AsyncTestCase):\n async def test_create_from_path(self):\n # Create temp dir and write op to ops.py\n with tempfile.TemporaryDirectory() as tmpdirname:\n # Change directory into the tempdir\n with chdir(tmpdirname):\n # Write out op to op.py\n operation_file_path = pathlib.Path(tmpdirname, \"ops.py\")\n operation_file_path.write_text(OP_DEF_STRING)\n # We make the name the path relative to our cwd\n operation_qualname = \"ops:echo_string\"\n dataflow_file_path = pathlib.Path(tmpdirname, \"dataflow.json\")\n # $ dffml dataflow create \\\n # ops:echo_string get_single\n with io.StringIO() as dataflow:\n with contextlib.redirect_stdout(dataflow):\n await CLI.cli(\n \"dataflow\",\n \"create\",\n *[operation_qualname, \"get_single\"],\n \"-seed\",\n '[\"OutputString\"]=get_single_spec',\n )\n test_dataflow = DataFlow._fromdict(\n **json.loads(dataflow.getvalue())\n )\n # Make sure the operation is in the dataflow\n self.assertIn(operation_qualname, test_dataflow.operations)\n # Run the dataflow\n async for ctx_str, results in run(\n test_dataflow,\n [\n Input(\n value=\"Irregular at magic school\",\n definition=test_dataflow.operations[\n operation_qualname\n ].inputs[\"input_string\"],\n )\n ],\n ):\n self.assertIn(\"OutputString\", results)\n self.assertEqual(\n results[\"OutputString\"], \"Irregular at magic school\",\n )\n","sub_path":"tests/df/test_df_create.py","file_name":"test_df_create.py","file_ext":"py","file_size_in_byte":2648,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"338795209","text":"import json\nimport os\n\nimport yaml\nfrom pycocotools.coco import COCO\nimport numpy as np\nimport skimage.io as io\nimport matplotlib.pyplot as plt\nimport pylab\n\n\nfrom get_coco_annotation import GetAnn\n\nclass GaussianJson():\n '''\n convert coco annotations to our Gaussian Json format\n '''\n\n def __init__(self, coco_data_dir):\n self.newid = 0\n self.coco_data_dir = coco_data_dir\n\n\n def generate_gaussian_json(self, data_type):\n self.__get_basic_info__()\n self.__get_categories__()\n self.__get_img_ann__(data_type)\n\n json_data = {\n \"info\": self.info,\n \"vehicle_info\": self.vehicle_info,\n \"log_info\": self.log_info,\n \"categories\": self.categories,\n \"images\": self.imgs,\n \"annotations\": self.anns\n }\n\n with open(os.path.join(self.coco_data_dir, \"Annotations_%s.json\" % data_type), 'w') as jsonfile:\n jsonfile.write(json.dumps(json_data, sort_keys=True))\n\n\n\n def __get_basic_info__(self, ros_info=False):\n '''\n # get basic info such as description and vehicle/log info .etc\n :param self:\n :param ros_info:\n :return:\n '''\n\n self.info = {\n \"year\": 2018,\n \"version\": 'test_api_v1',\n \"description\": 'convert coco2017 to gaussian dataset merging the thing & stuff tasks',\n \"contributor\": 'gaussian dl team',\n \"device\": 'coco images',\n \"date_created\": '2018-07-28'\n }\n\n self.vehicle_info = [{\n \"id\": '',\n \"hardware_version\": '',\n \"software_version\": '',\n \"sensor_list\": [],\n \"sensor_frequency\": 0\n }]\n\n self.log_info = [{\n \"id\": '',\n \"type\": '',\n \"vehicle_id\": 0,\n \"location\": '',\n \"starting time\": '',\n \"end time\": ''\n }]\n\n\n def __get_categories__(self):\n\n self.categories = []\n self.category_dict = {}\n f = open('../../gaussian_categories.yml', 'r')\n catseqs = yaml.load(f)\n for super, seqs in catseqs.items():\n for name, id in seqs.items():\n self.categories.append({\"supercategory\": super, \"name\": name, \"id\": id})\n self.category_dict[name] = id\n\n\n def __get_img_ann__(self, data_type):\n\n # init GetAnn Object and get COCO Annotations\n coco_ann = GetAnn()\n img_ids = coco_ann.get_gaussian_imgIds(data_type)\n anns_list, img_list = coco_ann.get_img_ann_list(img_ids, self.category_dict)\n\n self.anns = coco_ann.mask2polys(anns_list)\n\n # reset img id and note the mapping dict\n img_newid_map = {}\n\n\n # get gaussian imgs\n gs_imgs = []\n for img in img_list:\n self.newid += 1\n gs_img = {}\n\n # convert gaussian dataset and note the mapping\n img_newid_map[self.newid] = img['id']\n # gs_img['id'] = self.newid\n # gs_img['file_name'] = self.newid + '.jpg'\n\n # for validation\n gs_img['id'] = img['id']\n gs_img['file_name'] = img['file_name']\n gs_img['coco_url'] = img['coco_url']\n\n gs_img['width'] = img['width']\n gs_img['height'] = img['height']\n gs_img['depth'] = 3\n gs_img['device'] = 'camera'\n gs_img['date_captured'] = img['date_captured']\n gs_img['rosbag_name'] = ''\n gs_img['encode_type'] = 'rgb'\n gs_img['is_synthetic'] = 'no'\n gs_img['vehicle_info_id'] = ''\n gs_img['log_info_id'] = ''\n gs_img['weather'] = ''\n gs_imgs.append(gs_img)\n\n self.imgs = gs_imgs\n\n # get the map between gaussian imgid and coco imgid\n self.img_newid_map = img_newid_map\n\n\nif __name__ == \"__main__\":\n\n coco_datapath = './'\n gs_json = GaussianJson(coco_datapath)\n gs_json.generate_gaussian_json('val2017')\n\n\n\n\n\n\n","sub_path":"lib/datasets/convert_to_gaussian/coco/coco2gaussian/create_gaussian_json.py","file_name":"create_gaussian_json.py","file_ext":"py","file_size_in_byte":4019,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"320818484","text":"import unittest\r\nimport datetime\r\n\r\nfrom entities.BookOrder import BookOrder\r\nfrom services import BookOrder_service as commons_bookorder_service\r\nbookorder_service = commons_bookorder_service.BookOrderService(\"BookOrder\")\r\n\r\ntest_primary_key_1 = 200\r\n\r\n\r\nclass TestDaoBookOrder(unittest.TestCase):\r\n\r\n def test_dao(self):\r\n\r\n print(\"--- test BookOrderPersistence \")\r\n\r\n entity = BookOrder()\r\n # --- Key values\r\n entity.id = test_primary_key_1\r\n # --- Other values\r\n entity.shopCode = \"AAA\"\r\n entity.customerCode = \"AAA\"\r\n entity.employeeCode = \"AAA\"\r\n entity.date = datetime.datetime.strptime(\"1011-11-11 00:00:00\", \"%Y-%m-%d %H:%M:%S\")\r\n entity.state = 1\r\n\r\n # --- DELETE\r\n print(\"Delete : {}\".format(entity.to_dict()))\r\n bookorder_service.delete(entity)\r\n cpt_initial = bookorder_service.count_all()\r\n print(\"Initial count = {}\".format(cpt_initial))\r\n\r\n # --- CREATE\r\n print(\"Create : {}\".format(entity))\r\n bookorder_service.insert(entity)\r\n self.assertTrue(bookorder_service.exists_by_id(test_primary_key_1))\r\n self.assertTrue(bookorder_service.exists(entity))\r\n\r\n cpt = bookorder_service.count_all()\r\n self.assertEqual(cpt, cpt_initial + 1)\r\n print(\"Count = {}\".format(cpt))\r\n\r\n # --- FIND\r\n print(\"Find by id ...\")\r\n element = bookorder_service.find_by_id(test_primary_key_1)\r\n self.assertIsNotNone(element)\r\n self.assertEqual(type(element), type(entity))\r\n self.assertEqual(element.to_dict(), entity.to_dict())\r\n self.assertTrue(bookorder_service.exists(entity))\r\n print(\"Found : {}\".format(element))\r\n\r\n # --- UPDATE\r\n # --- Change values\r\n entity.date = datetime.datetime.strptime(\"2022-02-22 00:00:00\", \"%Y-%m-%d %H:%M:%S\")\r\n entity.state = 2\r\n element = bookorder_service.update(entity)\r\n print(\"Update : {}\".format(entity))\r\n self.assertEqual(element, 1)\r\n\r\n # --- RELOAD AFTER UPDATE\r\n print(\"Find by id ...\")\r\n element = bookorder_service.find_by_id(test_primary_key_1)\r\n self.assertIsNotNone(element)\r\n self.assertEqual(type(element), type(entity))\r\n self.assertEqual(element.to_dict(), entity.to_dict())\r\n print(\"Found : {}\".format(element))\r\n\r\n # --- DELETE\r\n element = bookorder_service.delete_by_id(test_primary_key_1)\r\n self.assertEqual(element, 1)\r\n self.assertEqual(bookorder_service.delete_by_id(test_primary_key_1), False)\r\n self.assertEqual(bookorder_service.delete(entity), 0)\r\n\r\n cpt_final = bookorder_service.count_all()\r\n self.assertEqual(cpt_final, cpt_initial)\r\n print(\"Final count = {}\".format(cpt))\r\n\r\n self.assertFalse(bookorder_service.exists_by_id(test_primary_key_1))\r\n self.assertFalse(bookorder_service.exists(entity))\r\n self.assertEqual(bookorder_service.find_by_id(test_primary_key_1), False)\r\n\r\n print(\"Normal end of persistence service test.\")\r\n\r\n","sub_path":"back-python-final/commons/UnitTest/unit_test_BookOrder.py","file_name":"unit_test_BookOrder.py","file_ext":"py","file_size_in_byte":3092,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"223454788","text":"from MySQL import ConnectMySQL\n\nDB = ConnectMySQL.DB()\n\ncursor = DB.con()\n\nsql = '''\nDROP TABLE IF EXISTS EMPLOYEE;\nCREATE TABLE EMPLOYEE (\n FIRST_NAME CHAR(20) NOT NULL,\n LAST_NAME CHAR(20),\n AGE INT,\n SEX CHAR(1),\n INCOME FLOAT )\n'''\nresult = cursor.execute(sql)\nprint(result)\nDB.close()\n","sub_path":"MySQL/Created.py","file_name":"Created.py","file_ext":"py","file_size_in_byte":332,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"497458922","text":"'''\n1) Array and pointers(?)\n How are arguments passed in functions (call by value or reference)\n What happens when:\n Def: Foo (a):\n a[3]=10 return\n a = [1,2,3,4,5]\n foo(a)\n Print (a)\n\n\t\t\tDef foo (a):\n\t\t\t\tprint(id(a))\n\t\tAssume variable “a” ultimately contains a number 1.\n\n\tScope of variable\n\t\tDef foo():\n\t\t\t#Print (s)\n\t\t\tS = “local variable”\n\t\t\tPrint (“in foo”, s)\n\t\tS = “global variable\n\t\tPrint (“in main”, s\n\t\tfoo()\n\t\tPrint (“in main”, s)\n\t\tWhat happens if you un-comment 1st line of foo? How can you prevent it?\n'''\n\n\n# def foo(a):\n# a[3] = 10\n# return\n# a = [1, 2, 3, 4, 5]\n# foo(a)\n# print(a)\n#\n#\n# def foo(a):\n# print(id(a))\n\n\ndef foo():\n # print(s)\n s = \"local variable\"\n print(\"in foo\", s)\n\ns = \"global variable\"\nprint(\"in main\", s)\nfoo()\nprint(\"in main\", s)\n\n# __init__, __del__\n\na = [1, 2, 3, 4]\nb = [\"a\", \"b\", \"c\", \"d\"]\nsync_index = [(aValue, bValue) for aIndex, aValue in enumerate(a) for bIndex, bValue in enumerate(b) if aIndex is bIndex]\nprint(\"List Comprehension - Sync to list keeping same index: \\n\", sync_index)\n\nsync_lambda = map(lambda x, y: (x, y), a, b)\nprint(\"Lambda function - Sync to list keeping same index: \\n\", list(sync_lambda))","sub_path":"ml-training-master/projects/1.py","file_name":"1.py","file_ext":"py","file_size_in_byte":1278,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"553044009","text":"import torch\nfrom torch.utils.tensorboard import SummaryWriter\nfrom boltzmann import protein\nfrom boltzmann.generative import transforms\nfrom boltzmann import nn\nfrom boltzmann import utils\nfrom simtk import openmm as mm\nfrom simtk.openmm import app\nimport numpy as np\nimport mdtraj as md\nimport os\nimport shutil\nimport argparse\nfrom tqdm import tqdm\n\n\ndef get_device():\n if torch.cuda.is_available():\n print(\"Using cuda\")\n device = torch.device(\"cuda\")\n else:\n print(\"Using CPU\")\n device = torch.device(\"cpu\")\n return device\n\n\ndef delete_run(name):\n if os.path.exists(f\"models/{name}.pkl\"):\n os.remove(f\"models/{name}.pkl\")\n if os.path.exists(f\"training_traj/{name}.pdb\"):\n os.remove(f\"training_traj/{name}.pdb\")\n if os.path.exists(f\"sample_traj/{name}.pdb\"):\n os.remove(f\"sample_traj/{name}.pdb\")\n if os.path.exists(f\"runs/{name}\"):\n shutil.rmtree(f\"runs/{name}\")\n\n\ndef create_dirs():\n os.makedirs(\"models\", exist_ok=True)\n os.makedirs(\"training_traj\", exist_ok=True)\n os.makedirs(\"sample_traj\", exist_ok=True)\n\n\ndef create_tensorboard(name):\n return SummaryWriter(log_dir=f\"runs/{name}\", purge_step=0, flush_secs=30)\n\n\ndef load_trajectory(pdb_path, dcd_path):\n print(\"Loading trajectory\")\n t = md.load(args.dcd_path, top=args.pdb_path)\n ind = t.topology.select(\"backbone\")\n t.superpose(t, frame=0, atom_indices=ind)\n return t\n\n\ndef build_network(\n n_dim,\n topology,\n training_data,\n n_coupling,\n use_affine_coupling,\n spline_points,\n hidden_features,\n hidden_layers,\n dropout_fraction,\n device,\n):\n print(\"Creating network\")\n layers = []\n\n # Create the mixed transofrm layer\n pca_block = protein.PCABlock(\"backbone\", True)\n mixed = protein.MixedTransform(n_dim, topology, [pca_block], training_data)\n layers.append(mixed)\n\n # Create the coupling layers\n for _ in range(n_coupling):\n p = transforms.RandomPermutation(n_dim - 6, 1)\n mask_even = utils.create_alternating_binary_mask(features=n_dim - 6, even=True)\n mask_odd = utils.create_alternating_binary_mask(features=n_dim - 6, even=False)\n if use_affine_coupling:\n t1 = transforms.AffineCouplingTransform(\n mask=mask_even,\n transform_net_create_fn=lambda in_features, out_features: nn.ResidualNet(\n in_features=in_features,\n out_features=out_features,\n hidden_features=hidden_features,\n num_blocks=hidden_layers,\n dropout_probability=dropout_fraction,\n use_batch_norm=True,\n ),\n )\n t2 = transforms.AffineCouplingTransform(\n mask=mask_odd,\n transform_net_create_fn=lambda in_features, out_features: nn.ResidualNet(\n in_features=in_features,\n out_features=out_features,\n hidden_features=hidden_features,\n num_blocks=hidden_layers,\n dropout_probability=dropout_fraction,\n use_batch_norm=True,\n ),\n )\n else:\n t1 = transforms.PiecewiseRationalQuadraticCouplingTransform(\n mask=mask_even,\n transform_net_create_fn=lambda in_features, out_features: nn.ResidualNet(\n in_features=in_features,\n out_features=out_features,\n hidden_features=hidden_features,\n num_blocks=hidden_layers,\n dropout_probability=dropout_fraction,\n use_batch_norm=True,\n ),\n tails=\"linear\",\n tail_bound=5,\n num_bins=spline_points,\n apply_unconditional_transform=False,\n )\n t2 = transforms.PiecewiseRationalQuadraticCouplingTransform(\n mask=mask_odd,\n transform_net_create_fn=lambda in_features, out_features: nn.ResidualNet(\n in_features=in_features,\n out_features=out_features,\n hidden_features=hidden_features,\n num_blocks=hidden_layers,\n dropout_probability=dropout_fraction,\n use_batch_norm=True,\n ),\n tails=\"linear\",\n tail_bound=5,\n num_bins=spline_points,\n apply_unconditional_transform=False,\n )\n layers.append(p)\n layers.append(t1)\n layers.append(t2)\n\n net = transforms.CompositeTransform(layers).to(device)\n print(net)\n print_number_trainable_params(net)\n return net\n\n\ndef load_network(path, device):\n net = torch.load(path).to(device)\n print(net)\n print_number_trainable_params(net)\n return net\n\n\ndef setup_optimizer(net, init_lr, weight_decay):\n optimizer = torch.optim.AdamW(\n net.parameters(), lr=init_lr, weight_decay=weight_decay\n )\n return optimizer\n\n\ndef setup_scheduler(optimizer, init_lr, final_lr, epochs, warmup_epochs, warmup_factor):\n anneal = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, epochs, final_lr)\n warmup = utils.GradualWarmupScheduler(\n optimizer, warmup_factor, warmup_epochs, after_scheduler=anneal\n )\n return warmup\n\n\ndef print_number_trainable_params(net):\n total_params = sum(p.numel() for p in net.parameters() if p.requires_grad)\n print()\n print(f\"Network has {total_params} trainable parameters\")\n print()\n\n\ndef get_openmm_context(pdb_path):\n pdb = app.PDBFile(pdb_path)\n ff = app.ForceField(\"amber99sbildn.xml\", \"amber99_obc.xml\")\n system = ff.createSystem(\n pdb.topology,\n nonbondedMethod=app.CutoffNonPeriodic,\n nonbondedCutoff=1.0,\n constraints=None,\n )\n integrator = mm.LangevinIntegrator(298, 1.0, 0.002)\n simulation = app.Simulation(pdb.topology, system, integrator)\n context = simulation.context\n return context\n\n\ndef get_energy_evaluator(openmm_context, temperature, energy_high, energy_max, device):\n energy_high = torch.tensor(\n energy_high, dtype=torch.float32, device=device, requires_grad=False\n )\n energy_max = torch.tensor(\n energy_max, dtype=torch.float32, device=device, requires_grad=False\n )\n\n def eval_energy(x):\n return protein.regularize_energy(\n protein.openmm_energy(x, openmm_context, temperature),\n energy_high,\n energy_max,\n )\n\n return eval_energy\n\n\ndef run_training(args, device):\n writer = create_tensorboard(args.output_name)\n\n traj = load_trajectory(args.pdb_path, args.dcd_path)\n n_dim = traj.xyz.shape[1] * 3\n training_data_npy = traj.xyz.reshape(-1, n_dim)\n training_data = torch.from_numpy(training_data_npy.astype(\"float32\"))\n print(\"Trajectory loaded\")\n print(\"Data has size:\", training_data.shape)\n\n if args.load_network:\n net = load_network(f\"models/{args.load_network}.pkl\", device=device)\n else:\n net = build_network(\n n_dim=n_dim,\n topology=traj.topology,\n training_data=training_data,\n n_coupling=args.coupling_layers,\n use_affine_coupling=args.is_affine,\n spline_points=args.spline_points,\n hidden_features=args.hidden_features,\n hidden_layers=args.hidden_layers,\n dropout_fraction=args.dropout_fraction,\n device=device,\n )\n\n optimizer = setup_optimizer(\n net=net,\n init_lr=args.init_lr / args.warmup_factor,\n weight_decay=args.weight_decay,\n )\n scheduler = setup_scheduler(\n optimizer,\n init_lr=args.init_lr,\n final_lr=args.final_lr,\n epochs=args.epochs,\n warmup_epochs=args.warmup_epochs,\n warmup_factor=args.warmup_factor,\n )\n\n openmm_context = get_openmm_context(args.pdb_path)\n energy_evaluator = get_energy_evaluator(\n openmm_context=openmm_context,\n temperature=args.temperature,\n energy_high=args.energy_high,\n energy_max=args.energy_max,\n device=device,\n )\n\n # Shuffle the training data\n n = training_data_npy.shape[0]\n n_val = int(n / args.fold_validation)\n np.random.shuffle(training_data_npy)\n\n # Split the training and validation sets\n val_data = torch.as_tensor(training_data_npy[:n_val, :], device=device)\n train_data = torch.as_tensor(training_data_npy[n_val:, :], device=device)\n indices = np.arange(train_data.shape[0])\n indices_val = np.arange(val_data.shape[0])\n\n # We're going choose a random latent vector and see what it transforms to\n # as we train the network.\n fixed_coords = []\n fixed_z = torch.normal(0, 1, size=(1, n_dim - 6), device=device)\n\n with tqdm(range(args.epochs)) as progress:\n for epoch in progress:\n net.train()\n optimizer.zero_grad()\n\n if args.train_example:\n index_batch = np.random.choice(indices, args.batch_size, replace=True)\n x_batch = train_data[index_batch, :]\n z, z_jac = net.forward(x_batch)\n example_ml_loss = (\n 0.5 * torch.mean(torch.sum(z ** 2, dim=1)) * args.example_weight\n )\n example_jac_loss = -torch.mean(z_jac) * args.example_weight\n example_loss = example_ml_loss + example_jac_loss\n\n if args.train_energy:\n z_batch = torch.normal(\n 0, 1, size=(args.batch_size, n_dim - 6), device=device\n )\n x, x_jac = net.inverse(z_batch)\n energies = energy_evaluator(x)\n energy_kl_loss = torch.mean(energies) * args.energy_weight\n energy_jac_loss = -torch.mean(x_jac) * args.energy_weight\n energy_loss = energy_kl_loss + energy_jac_loss\n\n if args.train_example and args.train_energy:\n loss = example_loss + energy_loss\n elif args.train_example:\n loss = example_loss\n else:\n loss = energy_loss\n\n loss.backward()\n optimizer.step()\n scheduler.step(epoch)\n\n if epoch % args.log_freq == 0:\n net.eval()\n\n # Output our training losses\n writer.add_scalar(\"Train/loss\", loss.item(), epoch)\n if args.train_example:\n writer.add_scalar(\"Train/example_ml\", example_ml_loss.item(), epoch)\n writer.add_scalar(\n \"Train/example_jac\", example_jac_loss.item(), epoch\n )\n writer.add_scalar(\"Train/example_total\", example_loss.item(), epoch)\n if args.train_energy:\n writer.add_scalar(\"Train/energy_kl\", energy_kl_loss.item(), epoch)\n writer.add_scalar(\"Train/energy_jac\", energy_jac_loss.item(), epoch)\n writer.add_scalar(\"Train/energy_total\", energy_loss.item(), epoch)\n\n # Compute our validation losses\n with torch.no_grad():\n # Compute the example validation loss\n index_val = np.random.choice(\n indices_val, args.batch_size, replace=True\n )\n x_val = val_data[index_val, :]\n z_prime, z_prime_jac = net.forward(x_val)\n example_ml_loss_val = (\n 0.5\n * torch.mean(torch.sum(z_prime ** 2, dim=1))\n * args.example_weight\n )\n example_jac_loss_val = (\n -torch.mean(z_prime_jac) * args.example_weight\n )\n example_loss_val = example_ml_loss_val + example_jac_loss_val\n\n # Compute the energy validation loss\n z_val = torch.normal(\n 0, 1, size=(args.batch_size, n_dim - 6), device=device\n )\n x_prime, x_prime_jac = net.inverse(z_val)\n val_energies = energy_evaluator(x_prime)\n energy_kl_loss_val = torch.mean(val_energies) * args.energy_weight\n energy_jac_loss_val = -torch.mean(x_prime_jac) * args.energy_weight\n energy_loss_val = energy_kl_loss_val + energy_jac_loss_val\n\n # Compute the overall validation loss\n if args.train_example and args.train_energy:\n loss_val = example_loss_val + energy_loss_val\n elif args.train_example:\n loss_val = example_loss_val\n else:\n loss_val = energy_loss_val\n\n progress.set_postfix(\n loss=f\"{loss.item():8.3f}\", val_loss=f\"{loss_val.item():8.3f}\"\n )\n\n writer.add_scalar(\"Validation/loss\", loss_val.item(), epoch)\n writer.add_scalar(\n \"Validation/example_ml\", example_ml_loss_val.item(), epoch\n )\n writer.add_scalar(\n \"Validation/example_jac\", example_jac_loss_val.item(), epoch\n )\n writer.add_scalar(\n \"Validation/example_total\", example_loss_val.item(), epoch\n )\n writer.add_scalar(\n \"Validation/energy_kl\", energy_kl_loss_val.item(), epoch\n )\n writer.add_scalar(\n \"Validation/energy_jac\", energy_jac_loss_val.item(), epoch\n )\n writer.add_scalar(\n \"Validation/energy_total\", energy_loss_val.item(), epoch\n )\n writer.add_scalar(\n \"Energies/mean_energy\", torch.mean(val_energies).item(), epoch\n )\n writer.add_scalar(\n \"Energies/median_energy\",\n torch.median(val_energies).item(),\n epoch,\n )\n writer.add_scalar(\n \"Energies/minimum_energy\", torch.min(val_energies).item(), epoch\n )\n\n fixed_x, fixed_x_jac = net.inverse(fixed_z)\n fixed_energy = torch.mean(\n protein.openmm_energy(fixed_x, openmm_context, args.temperature)\n )\n fixed_coords.append(fixed_x.cpu().detach().numpy())\n writer.add_scalar(\n \"Energies/fixed_energy\", fixed_energy.item(), epoch\n )\n\n # Save our final model\n torch.save(net, f\"models/{args.output_name}.pkl\")\n\n # Log our final losses to the console\n print(\"Final loss:\", loss.item())\n if args.train_example:\n print(\"Final example loss:\", example_loss.item())\n if args.train_energy:\n print(\"Final energy loss:\", energy_loss.item())\n print(\"Final validation loss:\", loss_val.item())\n print(\"Final validation example loss:\", example_loss_val.item())\n print(\"Final validation energy loss:\", energy_loss_val.item())\n print(\"Final fixed energy loss:\", fixed_energy.item())\n\n # Write the fixed_coords to trajectory\n fixed_coords = np.array(fixed_coords)\n fixed_coords = fixed_coords.reshape(fixed_coords.shape[0], -1, 3)\n traj.unitcell_lengths = None\n traj.unitcell_angles = None\n traj.xyz = fixed_coords\n traj.save(f\"training_traj/{args.output_name}.pdb\")\n\n # Generate examples and write trajectory\n net.eval()\n z = torch.normal(0, 1, size=(args.batch_size, n_dim - 6), device=device)\n x, _ = net.inverse(z)\n x = x.cpu().detach().numpy()\n x = x.reshape(args.batch_size, -1, 3)\n traj.xyz = x\n traj.save(f\"sample_traj/{args.output_name}.pdb\")\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(\n prog=\"train.py\", description=\"Train generative model of molecular conformation.\"\n )\n\n path_group = parser.add_argument_group(\"paths and filenames\")\n # Paths and filenames\n path_group.add_argument(\"--pdb-path\", required=True, help=\"path to pdb file\")\n path_group.add_argument(\"--dcd-path\", required=True, help=\"path to dcd file\")\n path_group.add_argument(\"--output-name\", required=True, help=\"base name for output\")\n path_group.add_argument(\n \"--overwrite\", action=\"store_true\", help=\"overwrite previous run\"\n )\n path_group.set_defaults(overwrite=False)\n\n # Optimization parameters\n optimizer_group = parser.add_argument_group(\"optimization parameters\")\n optimizer_group.add_argument(\n \"--epochs\",\n type=int,\n default=1000,\n help=\"number of training iterations (default: %(default)d)\",\n )\n optimizer_group.add_argument(\n \"--batch-size\",\n type=int,\n default=1024,\n help=\"size of training batch (default: %(default)d)\",\n )\n optimizer_group.add_argument(\n \"--warmup-epochs\",\n type=int,\n default=10,\n help=\"gradually raise learning rate over first WARMUP_EPOCHS (default: %(default)d)\",\n )\n optimizer_group.add_argument(\n \"--warmup-factor\",\n type=float,\n default=1000,\n help=\"learning rate starts WARMUP_FACTOR below init-lr (default: %(default)d)\",\n )\n optimizer_group.add_argument(\n \"--init-lr\",\n type=float,\n default=1e-3,\n help=\"initial learning rate (default: %(default)g)\",\n )\n optimizer_group.add_argument(\n \"--final-lr\",\n type=float,\n default=1e-5,\n help=\"final learning rate (default: %(default)g)\",\n )\n optimizer_group.add_argument(\n \"--weight-decay\",\n type=float,\n default=1e-3,\n help=\"strength of weight decay (default: %(default)g)\",\n )\n optimizer_group.add_argument(\n \"--dropout-fraction\",\n type=float,\n default=0.5,\n help=\"strength of dropout (default: %(default)g)\",\n )\n optimizer_group.add_argument(\n \"--log-freq\",\n type=int,\n default=10,\n help=\"how often to update tensorboard (default: %(default)d)\",\n )\n optimizer_group.add_argument(\n \"--fold-validation\",\n type=float,\n default=10.0,\n help=\"how much data to set aside for training (default: %(default)d)\",\n )\n\n # Network parameters\n network_group = parser.add_argument_group(\"network parameters\")\n network_group.add_argument(\n \"--load-network\", default=None, help=\"load previously trained network\"\n )\n network_group.add_argument(\n \"--coupling-layers\",\n type=int,\n default=4,\n help=\"number of coupling layers (%(default)d)\",\n )\n network_group.add_argument(\n \"--hidden-features\",\n type=int,\n default=128,\n help=\"number of hidden features in each layer (default: %(default)d)\",\n )\n network_group.add_argument(\n \"--hidden-layers\",\n type=int,\n default=2,\n help=\"number of hidden layers (default: %(default)d)\",\n )\n network_group.add_argument(\n \"--spline-points\",\n type=int,\n default=8,\n help=\"number of spline points in NSF layers (default: %(default)d)\",\n )\n network_group.add_argument(\n \"--is-affine\",\n action=\"store_true\",\n help=\"use affine rather than NSF layers (default: False)\",\n )\n network_group.set_defaults(is_affine=False)\n\n # Loss Function parameters\n loss_group = parser.add_argument_group(\"loss function parameters\")\n loss_group.add_argument(\n \"--train-example\",\n dest=\"train_example\",\n action=\"store_true\",\n help=\"include training by example in loss (default: True)\",\n )\n loss_group.add_argument(\n \"--no-train-example\", dest=\"train_example\", action=\"store_false\"\n )\n loss_group.set_defaults(train_example=True)\n loss_group.add_argument(\n \"--train-energy\",\n dest=\"train_energy\",\n action=\"store_true\",\n help=\"including training by energy in loss (default: False)\",\n )\n loss_group.add_argument(\n \"--no-train-energy\", dest=\"train_energy\", action=\"store_false\"\n )\n loss_group.set_defaults(train_ml=False)\n loss_group.add_argument(\n \"--example-weight\",\n type=float,\n default=1.0,\n help=\"weight for training by example (default: %(default)g)\",\n )\n loss_group.add_argument(\n \"--energy-weight\",\n type=float,\n default=1.0,\n help=\"weight for training by energy (default: %(default)g)\",\n )\n\n # Energy evaluation parameters\n energy_group = parser.add_argument_group(\"parameters for energy function\")\n energy_group.add_argument(\n \"--temperature\",\n type=float,\n default=298.0,\n help=\"temperature (default: %(default)g)\",\n )\n energy_group.add_argument(\n \"--energy-max\",\n type=float,\n default=1e20,\n help=\"maximum energy (default: %(default)g)\",\n )\n energy_group.add_argument(\n \"--energy-high\",\n type=float,\n default=1e10,\n help=\"log transform energies above this value (default: %(default)g)\",\n )\n\n args = parser.parse_args()\n\n if not (args.train_example or args.train_energy):\n raise RuntimeError(\n \"You must specify at least one of train_example or train_energy.\"\n )\n\n model_path = f\"models/{args.output_name}.pkl\"\n if os.path.exists(model_path):\n if args.overwrite:\n print(f\"Warning: output `{model_path}' already exists. Overwriting anyway.\")\n else:\n raise RuntimeError(\n f\"Output '{model_path}' already exists. If you're sure use --overwrite.\"\n )\n\n # Remove any old data for this run\n delete_run(args.output_name)\n\n create_dirs()\n device = get_device()\n run_training(args, device)\n","sub_path":"examples/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":22217,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"614650277","text":"#!/usr/bin/env python3\n\nimport socket\n\nHOST = '127.0.0.1' # The server's hostname or IP address\nPORT = 65432 # The port used by the server\n\nwith socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:\n try:\n s.connect((HOST, PORT)) # connect to server\n print('connection with server was successfull')\n except:\n print('Connection can not be complete')\n exit()\n try:\n while True:\n # enter the text we want to send to server\n text = str(input('write text: '))\n if text == 'exit':\n break\n s.send(text.encode())\n print('we are sending data!') # encode text to bytes\n data = s.recv(1024) # get data in bytes from server\n print('we are received data!')\n # decode and output data from server\n print(data.decode())\n except:\n print('connection was lost')\n","sub_path":"client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":944,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"634515683","text":"import logging\nfrom .. import utils\nlog = logging.getLogger(__name__)\n\n\nclass PersonalityApiMixin(object):\n def inject_file(self, dst_path, src_path=None, file_data=None, timeout=10):\n params = {'t': timeout}\n url = self._url(\"/service/personality\")\n inject_file_config = utils.inject_file_config(dst_path, src_path, file_data)\n res = self._post_json(url, params=params, data=inject_file_config)\n self._raise_for_status(res)\n return res.raw","sub_path":"agent/wormholeclient/wormholeclient/api/personality.py","file_name":"personality.py","file_ext":"py","file_size_in_byte":485,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"223970976","text":"#lambda code to process tweets automatically from S3 bucket to AWS Dynamodb\nimport json\nimport csv \nimport boto3\ndef lambda_handler(event, context):\n region = 'eu-west-1'\n record_ddlist = [] \n try:\n s3 = boto3.client('s3') \n dynamodb = boto3.client('dynamodb', region_name = region)\n bucket = event['Records'][0]['s3']['bucket']['name']\n key = event['Records'][0]['s3']['object']['key']\n print('Bucket: ', bucket, 'Key: ', key)\n csv_file = s3.get_object(Bucket=bucket, Key=key)\n record_list = csv_file[\"Body\"].read().decode('utf-8').split('\\n')\n csv_reader = csv.reader(record_list, delimiter=',', quotechar='\"')\n for row in csv_reader:\n id = row[1] \n text = row[2] \n label = row[3]\n add_to_db = dynamodb.put_item(\n TableName = 'covid_tweets',\n Item = {\n 'id' : {'S': str(id)},\n 'label' : {'S': str(label)},\n 'text' : {'S': str(text)},\n })\n print(\"Successfully added\")\n except Exception as e:\n print(str(e))","sub_path":"lambda code.py","file_name":"lambda code.py","file_ext":"py","file_size_in_byte":1150,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"575474170","text":"class DisjointSet:\n\t\"\"\"\n\tDisjoint Set to perform Union/Find functions\n\t\"\"\"\n\tdef __init__(self, objects):\n\t\tself.size = len(objects)\n\t\tself.parent = dict(zip(objects, objects))\n\t\tself.rank = dict.fromkeys(objects, 0)\n\t\n\tdef find(self, x):\n\t\t\"\"\"\n\t\tFinds the parent of :x in the disjoint set\n\t\t\"\"\"\n\t\tif self.parent[x] != x:\n\t\t\tself.parent[x] = self.find(self.parent[x])\n\t\treturn self.parent[x]\n\t\n\tdef same_set(self, x, y):\n\t\t\"\"\"\n\t\tIndicates whether :x and :y belong to the same set\n\t\t\"\"\"\n\t\treturn self.find(x) == self.find(y)\n\t\n\tdef union(self, x, y):\n\t\t\"\"\"\n\t\tUnifies :x and :y\n\t\t\"\"\"\n\t\txRoot = self.find(x)\n\t\tyRoot = self.find(y)\n\t\tif xRoot == yRoot:\n\t\t\treturn # Union\n\t\tif self.rank[xRoot] < self.rank[yRoot]:\n\t\t\tself.parent[xRoot] = yRoot\n\t\telse:\n\t\t\tself.parent[yRoot] = xRoot\n\t\t\tif self.rank[xRoot] == self.rank[yRoot]:\n\t\t\t\tself.rank[xRoot] += 1\n\nclass BinaryIndexedTree:\n\t\"\"\"\n\tBinary Indexed Tree implementation, handles cumulative frequencies\n\tin range [1:x]\n\tNOTE: Tree is 1-based\n\t\"\"\"\n\tdef __init__(self, n):\n\t\tself.size = n + 1\n\t\tself.tree = dict.fromkeys(xrange(1, n + 1), 0)\n\t\n\tdef update(self, x, val):\n\t\t\"\"\"\n\t\tUpdates the frequency of the element at position :x with :val\n\t\tunits while keeping update the respective cumulative frequencies\n\t\t\"\"\"\n\t\twhile x < self.size:\n\t\t\tself.tree[x] += val\n\t\t\tx += x & -x\n\t\n\tdef read(self, x):\n\t\t\"\"\"\n\t\tGives the cumulative frequency of the element in position :x,\n\t\ti.e. read(x) = frequency in range [1:x]\n\t\t\"\"\"\n\t\ts = 0\n\t\twhile x > 0:\n\t\t\ts += self.tree[x]\n\t\t\tx -= x & -x\n\t\treturn s\n\n\tdef find_highest_index(self, freq):\n\t\t\"\"\"\n\t\tFinds the index of the highest number whose frequency is equal to\n\t\t:freq. Returns the index in the tree, if exists; None otherwise.\n\t\tNOTE: Works ONLY for non-negative frequencies in the tree.\n\t\t\"\"\"\n\t\tidx = 0\n\t\tmask = 1 << (self.size.bit_length() - 1)\n\t\twhile mask != 0:\n\t\t\tk = idx + mask\n\t\t\tif k in self.tree and freq >= self.tree[k]:\n\t\t\t\tidx = k\n\t\t\t\tfreq -= self.tree[k]\n\t\t\tmask >>= 1\n\t\treturn idx if freq == 0 else None\n\nclass Trie:\n\t\"\"\"\n\tA Trie is a tree representation of a set of words by storing two words\n\twith identical prefixes under the same branch of the tree.\n\tAdding, retrieving and finding prefixes in the tree is O(L) where L is\n\tthe length of the string sought\n\t\"\"\"\n\tdef __init__(self):\n\t\tself.words = 0\n\t\tself.prefixes = 0\n\t\tself.edges = dict()\n\t\n\tdef __repr__(self, offset=0):\n\t\ts = \"\\n\"\n\t\tfor k in self.edges:\n\t\t\ts += \"{}{} {}\".format(\"|\" * offset, k, self.edges[k].__repr__(offset=offset+2))\n\t\treturn s\n\n\tdef __contains__(self, word):\n\t\t\"\"\"\n\t\tSays if a given :word is stored in this trie. \"x\" in trie\n\t\t\"\"\"\n\t\treturn self.count_words(word) > 0\n\t\n\tdef add_word(self, word, index=0):\n\t\t\"\"\"\n\t\tAdds the suffix of :word starting at :index to this trie\n\t\t\"\"\"\n\t\tif len(word) - index == 0:\n\t\t\tself.words += 1\n\t\telse:\n\t\t\tself.prefixes += 1\n\t\t\tk = word[index]\n\t\t\tif k not in self.edges:\n\t\t\t\tself.edges[k] = Trie()\n\t\t\tself.edges[k].add_word(word, index+1)\n\t\n\tdef count_words(self, word, index=0):\n\t\t\"\"\"\n\t\tCounts the number of times that the suffix of :word\n\t\tstarting at :index appears in the trie\n\t\t\"\"\"\n\t\tif len(word) - index == 0:\n\t\t\treturn self.words\n\t\tk = word[index]\n\t\tif k not in self.edges:\n\t\t\treturn 0\n\t\telse:\n\t\t\treturn self.edges[k].count_words(word, index=index+1)\n\t\n\tdef count_prefixes(self, prefix, index=0):\n\t\t\"\"\"\n\t\tCounts the number of times that the suffix of :prefix\n\t\tof :word appears in the trie. When :index=0 then it just\n\t\tcalculates how many times :prefix appears in the trie\n\t\t\"\"\"\n\t\tif len(prefix) - index == 0:\n\t\t\treturn self.prefixes\n\t\tk = prefix[index]\n\t\tif k not in self.edges:\n\t\t\treturn 0\n\t\telse:\n\t\t\treturn self.edges[k].count_prefixes(prefix, index=index+1)\n\nclass SuffixArray:\n\t\"\"\"\n\tSuffix Array\n\t\"\"\"\n\tdef __init__(self, A):\n\t\tself.A = list(A)\n\t\tself.A.append('$')\n\t\tself.n = len(self.A) - 1\n\t\n\tdef cmp_ki(self, a, b):\n\t\tif a == b:\n\t\t\treturn 0\n\t\telif self.ik[a] != self.ik[b]:\n\t\t\treturn cmp(self.ik[a], self.ik[b])\n\t\telse:\n\t\t\treturn cmp(self.ik[a + self.hh], self.ik[b + self.hh])\n\n\tdef suffix_array(self):\n\t\t\"\"\"\n\t\tObtains the suffix array of the provided word :A\n\t\t\"\"\"\n\t\tself.ki = [0] * (self.n + 1)\n\t\tself.ik = [0] * (self.n + 1)\n\t\ts = [0] * (self.n + 1)\n\t\tfor i in xrange(self.n + 1):\n\t\t\tself.ki[i] = i\n\t\t\tself.ik[i] = ord(self.A[i])\n\t\tself.hh = 1\n\t\twhile s[self.n] != self.n:\n\t\t\tself.ki = sorted(self.ki, cmp=self.cmp_ki)\n\t\t\tfor i in xrange(self.n):\n\t\t\t\ts[i + 1] = s[i] + (1 if self.cmp_ki(self.ki[i], self.ki[i + 1]) < 0 else 0)\n\t\t\tfor i in xrange(self.n + 1):\n\t\t\t\tself.ik[self.ki[i]] = s[i]\n\t\t\tself.hh <<= 1\n\t\treturn self.ki\n\t\n\tdef longest_common_prefix(self):\n\t\t\"\"\"\n\t\tObtains the longest common prefix once the suffix\n\t\tarray was obtained for the provided word :A\n\t\t\"\"\"\n\t\th = 0\n\t\tself.lcp = [0] * self.n\n\t\tfor i in xrange(self.n):\n\t\t\tj = self.ki[self.ik[i] - 1]\n\t\t\twhile self.A[j + h] == self.A[i + h]:\n\t\t\t\th += 1\n\t\t\tself.lcp[self.ik[i] - 1] = h;\n\t\t\tif h > 0:\n\t\t\t\th -= 1\n\t\treturn self.lcp\n\nclass SegmentTree:\n\t\"\"\"\n\tSegment Tree to store an array whose values will\n\tbe incremented by intervals and queried by index\n\t\"\"\"\n\tdef __init__(self, range_from, range_to, A=None):\n\t\t\"\"\"\n\t\tCreates a Segment Tree with inclusive interval [:left, :right]\n\t\t\"\"\"\n\t\tself.range_from = range_from\n\t\tself.range_to = range_to\n\t\tif self.range_from == self.range_to:\n\t\t\tself.left = None\n\t\t\tself.right = None\n\t\telse:\n\t\t\tmid = self.range_from + (self.range_to - self.range_from) / 2\n\t\t\tself.left = SegmentTree(self.range_from, mid, A)\n\t\t\tself.right = SegmentTree(mid + 1, self.range_to, A)\n\t\t# Fill: value, sum, min, max variables\n\t\tif not A:\n\t\t\t# Default values\n\t\t\tself.value = 0 # Value in the interval\n\t\t\tself.sum = 0 # Sum of all the values in the interval\n\t\t\tself.min = 0 # Min value in the interval\n\t\t\tself.max = 0 # Max value in the interval\n\t\telif self.range_from == self.range_to:\n\t\t\t# Handle array with initial values\n\t\t\tself.value = A[self.range_from]\n\t\t\tself.sum = self.value\n\t\t\tself.min = self.value\n\t\t\tself.max = self.value\n\t\telse:\n\t\t\t# Update values of parent nodes\n\t\t\tself.value = 0\n\t\t\tself.sum = self.left.sum + self.right.sum\n\t\t\tself.min = min(self.left.min, self.right.min)\n\t\t\tself.max = max(self.left.max, self.right.max)\n\t\n\tdef __repr__(self):\n\t\treturn \"[{}, {}]: value={}, sum={}, min={}, max={}\".format(\n\t\t\tself.range_from, self.range_to, self.value, self.sum, self.min, self.max)\n\n\tdef increment(self, x, y, value):\n\t\t\"\"\"\n\t\tIncrements the array by :value in the inclusive interval [:x, :y]\n\t\t\"\"\"\n\t\tself.sum += value * (y - x + 1) # value * size of interval [x:y]\n\t\tif x == self.range_from and y == self.range_to:\n\t\t\tself.value += value\n\t\t\tself.max += value\n\t\t\tself.min += value\n\t\telse:\n\t\t\t# Lazily propagate increment of left and right nodes\n\t\t\tmid = self.range_from + (self.range_to - self.range_from) / 2\n\t\t\tif x <= mid:\n\t\t\t\tself.left.increment(x, min(y, mid), value)\n\t\t\tif mid < y:\n\t\t\t\tself.right.increment(max(x, mid + 1), y, value)\n\t\t\t# Update max and min values\n\t\t\tself.max = self.value + max(self.left.max, self.right.max)\n\t\t\tself.min = self.value + min(self.left.min, self.right.min)\n\n\tdef query(self, x):\n\t\t\"\"\"\n\t\tQuery the value of the array with index :x\n\t\t\"\"\"\n\t\tif self.range_from == self.range_to:\n\t\t\treturn self.value\n\t\tmid = self.range_from + (self.range_to - self.range_from) / 2\n\t\tif x <= mid:\n\t\t\treturn self.value + self.left.query(x)\n\t\telse:\n\t\t\treturn self.value + self.right.query(x)\n\n\tdef query_min(self, x, y):\n\t\t\"\"\"\n\t\tQuery the minimum of values within the inclusive interval [:x, :y]\n\t\t\"\"\"\n\t\tif x == self.range_from and y == self.range_to:\n\t\t\treturn self.min\n\t\telse:\n\t\t\tmid = self.range_from + (self.range_to - self.range_from) / 2\n\t\t\tmn = float('inf')\n\t\t\tif x <= mid:\n\t\t\t\tmn = min(mn, self.left.query_min(x, min(y, mid)))\n\t\t\tif mid < y:\n\t\t\t\tmn = min(mn, self.right.query_min(max(x, mid + 1), y))\n\t\t\treturn mn + self.value\n\n\tdef query_max(self, x, y):\n\t\t\"\"\"\n\t\tQuery the maximum of values within the inclusive interval [:x, :y]\n\t\t\"\"\"\n\t\tif x == self.range_from and y == self.range_to:\n\t\t\treturn self.max\n\t\telse:\n\t\t\tmid = self.range_from + (self.range_to - self.range_from) / 2\n\t\t\tmx = -float('inf')\n\t\t\tif x <= mid:\n\t\t\t\tmx = max(mx, self.left.query_max(x, min(y, mid)))\n\t\t\tif mid < y:\n\t\t\t\tmx = max(mx, self.right.query_max(max(x, mid + 1), y))\n\t\t\treturn mx + self.value\n\t\n\tdef query_sum(self, x, y):\n\t\t\"\"\"\n\t\tQuery the sum of values within the inclusive interval [:x, :y]\n\t\t\"\"\"\n\t\tif x == self.range_from and y == self.range_to:\n\t\t\treturn self.sum\n\t\telse:\n\t\t\tmid = self.range_from + (self.range_to - self.range_from) / 2\n\t\t\ts = 0\n\t\t\tif x <= mid:\n\t\t\t\ts += self.left.query_sum(x, min(y, mid))\n\t\t\tif mid < y:\n\t\t\t\ts += self.right.query_sum(max(x, mid + 1), y)\n\t\t\treturn (y - x + 1) * self.value + s\n","sub_path":"LinkedBasics/DataStructures.py","file_name":"DataStructures.py","file_ext":"py","file_size_in_byte":8631,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"366358714","text":"import numpy as np\nimport os\nimport matplotlib.pyplot as plt\nimport csv\nimport sys\ncsv.field_size_limit(sys.maxsize)\nimport tabulate\n# https://github.com/gregbanks/python-tabulate\nimport scipy.spatial as spatial\nfrom scipy import stats, integrate\nfrom tabulate import tabulate\nfrom scipy import stats, integrate\nimport pickle\n\nNUM = 502628 # number of individuals\nTOLENGTH = 0.227 # pixel to length (um)\n\n'''Functions for Loading Raw Data'''\n\ndef save_data(dir_save, names, data):\n if not os.path.exists(dir_save):\n os.makedirs(dir_save)\n if type(names) is list:\n for i, name in enumerate(names):\n np.save(os.path.join(dir_save, name), data[i])\n else:\n np.save(os.path.join(dir_save, names), data)\n \n\ndef get_items(dir_file):\n # Get the first row in csv file dir_file\n with open(dir_file, 'rU') as csvfile:\n reader = csv.reader(csvfile, delimiter=',', dialect=csv.excel_tab)\n for i, row in enumerate(reader):\n row_item = row\n break\n return row_item\n \n\ndef get_ind(dir_file, names):\n # Find the list index of one item represented by name in csv file dir_file\n # return the index if names is a char; a list of index if names is a list\n row_item = get_items(dir_file)\n if type(names) is list:\n inds = []\n for name in names:\n inds.append(row_item.index(name))\n return inds\n else:\n return row_item.index(names)\n \ndef get_data(dir_file, names):\n # Get the data of item names for all individuals\n # return the data list if names is char; a list containing data lists if names is a list\n \n if type(names) is list:\n data = [[] for i in names]\n else:\n data = []\n \n inds = get_ind(dir_file, names)\n \n with open(dir_file, 'rU') as csvfile:\n reader = csv.reader(csvfile, delimiter=',')\n for i, row in enumerate(reader):\n #if np.mod(i, 10000) == 0:\n #print(i)\n if type(names) is list:\n for j, ind in enumerate(inds):\n data[j].append(row[ind])\n else:\n data.append(row[inds])\n return data\n\ndef generate_data(dir_file, dir_save, names):\n names_new = []\n # only generate data which are not generated before\n for name in names:\n if not os.path.isfile(os.path.join(dir_save, name) + '.npy'):\n names_new.append(name)\n \n # if all items are generated before\n if not names_new:\n return\n \n data_new = get_data(dir_file, names_new)\n save_data(dir_save, names_new, data_new)\n \n\ndef get_batch(dir_file, nums):\n # return randomly-chosen num individual batch\n \n if type(nums) is list:\n number_rand = []\n data = []\n k = []\n for num in nums:\n number_rand.append(np.sort(np.random.choice(np.arange(1, NUM+1), num, replace=False)))\n data.append([])\n k.append(0)\n else:\n k = 0\n number_rand = np.sort(np.random.choice(np.arange(1, NUM+1), nums, replace=False))\n \n with open(dir_file, 'rb') as csvfile:\n reader = csv.reader(csvfile, delimiter=',')\n for i, row in enumerate(reader):\n if type(nums) is list:\n for j, num in enumerate(nums):\n if i == number_rand[j][k[j]]:\n if k[j] < num - 1:\n k[j] = k[j] + 1\n data[j].append(row)\n else:\n if i == number_rand[k]:\n k = k + 1\n data.append(row)\n \n if np.mod(i, 10000) == 0:\n print(i) \n if i == 100:\n break\n return data\n \ndef generate_batch(dir_file, dir_save, nums):\n # generate and save random batch\n nums_new = []\n nums_new_str = []\n for num in nums:\n name = str(num)\n if not os.path.isfile(os.path.join(dir_save, name) + '.npy'):\n nums_new.append(num)\n nums_new_str.append(str(num)) \n data = get_batch(dir_file, nums_new)\n save_data(dir_save, nums_new_str, data)\n ","sub_path":"functions/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":4195,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"391775056","text":"import json\n\ndata = []\nwith open(\"../data/tweets.json\", \"r\") as file2read:\n for line in file2read.readlines():\n try:\n line = json.loads(line)\n data.append(line)\n except:\n continue\n\nprint(len(data))\n\ndata = sorted(data, key=lambda item: item[\"created_at\"], reverse=True)\n\nwith open(\"../data/sorted_tweets.json\", \"w\") as file2write:\n for line in data:\n line = json.dumps(line)\n file2write.write(line + \"\\n\")\n","sub_path":"Identify_Topics/Crawling/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":473,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"255976310","text":"def linear_search(nlist,element):\r\n index_count = 0\r\n nlist_size = len(nlist)\r\n while index_count < nlist_size:\r\n temp = nlist[index_count]\r\n if temp == element:\r\n return index_count\r\n index_count += 1\r\n return -1\r\n\r\n\r\n\r\ndef binary(item,search,start,end):\r\n if start >end:\r\n return -1\r\n mid = (start+end)//2\r\n if item[mid] == search:\r\n return mid\r\n if search < item[mid]:\r\n return binary(item,search,start,mid-1)\r\n else:\r\n return binary(item,search,mid+1,end)\r\n \r\nitem_list = [\"apple\",\"orange\",\"melon\",\"banana\",\"pineapple\"]\r\n\r\nchoose = str(input(\"Enter your choice for binary or linear search : \")).lower()\r\n\r\n\r\nif choose == \"binary\":\r\n search_val = \"apple\"\r\n print(\"Index Number of apple\",(binary(item_list,search_val,0,len(item_list))))\r\n \r\nelif choose == \"linear\":\r\n print(\"Index Number of pineapple\",(linear_search(item_list,\"pineapple\")))\r\n #print(linear_search(item_list,\"cherry\"))\r\nelse:\r\n print(\"Invalid choice\")\r\n","sub_path":"Practical5_TEST.py","file_name":"Practical5_TEST.py","file_ext":"py","file_size_in_byte":1035,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"587990508","text":"def sorting(str):\r\n order = \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1357902468\"\r\n index_list = []\r\n character_list = list(order)\r\n final_word = \"\"\r\n for character in str:\r\n pos = order.index(character)\r\n index_list.append(pos)\r\n character_list[pos] = character\r\n for num in sorted(index_list):\r\n final_word += character_list[num]\r\n return final_word\r\n \r\n","sub_path":"code challenge #1.py","file_name":"code challenge #1.py","file_ext":"py","file_size_in_byte":423,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"293011111","text":"#!/usr/bin/python\n\n#\n# Copyright (C) 2016 The Android Open Source Project\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n\n\"\"\"Cleans up any orphaned .pyc files in the tree.\"\"\"\n\n\nfrom __future__ import print_function\nimport argparse\nimport fnmatch\nimport os\nimport sys\n\n\ndef get_user_input(prompt):\n \"\"\"Prompt a user for input and return the result.\"\"\"\n print(prompt)\n sys.stdout.flush()\n result = sys.stdin.readline()\n return result\n\n\ndef parse_args(argv):\n \"\"\"Parse the command line arguments.\n\n Args:\n argv: The list of command line arguments to parse.\n\n Returns:\n The populated namespace object returned from argparse.parse_args(..).\n \"\"\"\n parser = argparse.ArgumentParser(description=__doc__)\n parser.add_argument('--quiet', action='store_true',\n help='Do not print any output.')\n parser.add_argument('--yes', action='store_true',\n help='Do not prompt for confirmation.')\n parser.add_argument('directory', nargs='?',\n default=os.path.dirname(\n os.path.dirname(os.path.realpath(__file__))),\n help='The base directory to search.')\n args = parser.parse_args(argv)\n\n if args.quiet and not args.yes:\n parser.error(\n 'Using the --quiet flag requires also using the --yes flag.')\n\n return args\n\n\ndef main(argv):\n args = parse_args(argv)\n\n if args.quiet:\n sys.stdout = open('/dev/null', 'w')\n\n matches = []\n failures = []\n for dirpath, _, filenames in os.walk(args.directory):\n for filename in fnmatch.filter(filenames, '*.pyc'):\n filepath = os.path.join(dirpath, filename)\n # If a .pyc file does not have a corresponding .py file, add it\n # to the list of matches.\n if not os.path.isfile(filepath[:-1]):\n matches.append(filepath)\n\n if not matches:\n print('No orphaned .pyc files found.')\n else:\n print('Found the following orphaned .pyc files:')\n print('\\n'.join(' ' + f for f in matches))\n\n if args.yes:\n choice = 'Y'\n else:\n choice = get_user_input('Remove these files? (y/N)').strip().upper()\n if choice == 'Y':\n # Remove the matched files. Under certain circumstances, an\n # OSError may be raised, so keep track of how many files have been\n # successfully deleted.\n count = 0\n for f in matches:\n try:\n os.remove(f)\n count += 1\n except OSError:\n failures.append(f)\n if failures:\n print('Could not remove:')\n print('\\n'.join(' ' + f for f in failures))\n print('{} files removed.'.format(count))\n\n else:\n print('Files not removed.')\n\n\nif __name__ == '__main__':\n sys.exit(main(sys.argv[1:]))\n","sub_path":"tools/cleanup.py","file_name":"cleanup.py","file_ext":"py","file_size_in_byte":3471,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"392317358","text":"from flask import Flask, request\nfrom flask_cors import CORS\nimport pandas as pd\nimport pickle\n\napp = Flask(__name__)\nCORS(app)\n\n\n@app.route('/')\ndef index():\n return \"Add '/api/Track Title With Spaces Between Words' to end of Heroku app URL in address field. Or, for HTML-compliance, '/api/Track%20Title%20With...\"\n\n\n@app.route('/api/')\ndef get_track_recomm(track_title):\n pkl_file = open('track_titles_word2vec.pkl', 'rb') # pickle file with trained model from AWS SageMaker\n word2vec_model = pickle.load(pkl_file)\n\n df = pd.read_csv('mood-title-tags-artists.csv')\n\n # print('first 5 lines of df:', df.head())\n track_words = track_title.split('%20') # creates a list with one string\n track_words = track_words.pop(0) # removes string from list\n track_words = track_words.split(' ') # creates list with 1+ string\n # print('track_words is:', track_words)\n # print('type of track_words is:', type(track_words))\n track_recomm_list = []\n for word in track_words[:2]:\n try:\n output_list = word2vec_model.wv.most_similar(word, topn=1)\n print('\\noutput_list is:', output_list)\n output_word = output_list[0][0]\n track_recomm = df.loc[df['title'].str.contains(output_word)]['title'].values\n artist_recomm = df.loc[df['title'].str.contains(output_word)]['artist_name'].values\n track_recomm = list(zip(track_recomm, artist_recomm))\n track_recomm_list.append(track_recomm)\n print('mood of track_recomm is:', \\\n df[df['title'].str.contains(output_word)]['mood'].values)\n\n except Exception as e:\n print(e, 'occurred.', word, 'not found in title vocabulary.')\n continue\n print('track_recomm_list is:', track_recomm_list)\n print('type of track_recomm_list is:', type(track_recomm_list))\n return pd.Series(track_recomm_list).to_json()\n\n\nif __name__ == '__main__':\n app.run(debug=True)\n","sub_path":"music-finder-flask/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1975,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"493445190","text":"from decimal import *\nfrom random import randrange\nimport copy\nclass MethodRepository:\n digitcounter = 0\n def CountRepInClass(self, Data):\n DF=0\n DHF1=0\n DHF2=0\n DHF3=0\n\n temp=len(Data)\n increment=1\n print ('Hello Data')\n for X in Data:\n check = X\n\n if check[-1]==\"DF\":\n DF += 1\n elif check[-1]=='DHF1':\n DHF1 += 1\n elif check[-1]=='DHF2':\n DHF2 += 1\n elif check[-1] == 'DHF3':\n DHF3 += 1\n\n return [DF,DHF1,DHF2,DHF3]\n\n def MadeChunks(self, Data):\n\n del Data[000]\n TrainData= []\n TestData=[]\n i=-1\n Total = len(Data)\n for X in range(1,370):\n i +=1\n Random = randrange(1,Total,3)\n Record = Data[Random]\n if(i<270):\n TrainData.append(Record)\n if(i>=270):\n TestData.append(Record)\n return TrainData,TestData\n\n def Findings(self, data, att_Col, Class):\n TrueList = copy.deepcopy(Class)\n FalseList = copy.deepcopy(Class)\n WList = copy.deepcopy(Class)\n AbList = copy.deepcopy(Class)\n PList = copy.deepcopy(Class)\n PPList = copy.deepcopy(Class)\n classListA = copy.deepcopy(Class)\n classListB = copy.deepcopy(Class)\n classListC = copy.deepcopy(Class)\n classListD = copy.deepcopy(Class)\n PDF = 1\n PDHF1 = 1\n PDHF2 = 1\n PDHF3 = 1\n NDF = 1\n NDHF1 = 1\n NDHF2 = 1\n NDHF3 = 1\n WDF = 1\n WDHF1 = 1\n WDHF2 = 1\n WDHF3 = 1\n AbDF = 1\n AbDHF1 = 1\n AbDHF2 = 1\n AbDHF3 = 1\n DF = 1\n DHF1 = 1\n DHF2 = 1\n DHF3 = 1\n classADF = 1\n for X in data:\n if X[att_Col].isdigit() and self.digitcounter == 0:\n if int(X[att_Col]) >= 10 and int(X[att_Col]) <= 20:\n i = 0\n for m in Class:\n if (X[-1] == m):\n if (classListA[i] not in Class):\n classADF = copy.deepcopy(classListA[i])\n classADF += 1\n classListA[i] = classADF\n else:\n classListA[i] = 1\n i += 1\n elif int(X[att_Col]) > 20 and int(X[att_Col]) <= 30:\n i = 0\n for m in Class:\n if (X[-1] == m):\n if (classListB[i] not in Class):\n classBDF = copy.deepcopy(classListB[i])\n classBDF += 1\n classListB[i] = classBDF\n else:\n classListB[i] = 1\n i += 1\n elif int(X[att_Col]) > 30:\n i = 0\n for m in Class:\n if (X[-1] == m):\n if (classListC[i] not in Class):\n classCDF = copy.deepcopy(classListC[i])\n classCDF += 1\n classListC[i] = classCDF\n else:\n classListC[i] = 1\n i += 1\n\n elif X[att_Col].isdigit() and self.digitcounter == 1:\n if int(X[att_Col]) >= 0 and int(X[att_Col]) <= 1999:\n i = 0\n for m in Class:\n if (X[-1] == m):\n if (classListA[i] not in Class):\n classADF = copy.deepcopy(classListA[i])\n classADF += 1\n classListA[i] = classADF\n else:\n classListA[i] = 1\n i += 1\n elif int(X[att_Col]) > 1999 and int(X[att_Col]) <= 3500:\n i = 0\n for m in Class:\n if (X[-1] == m):\n if (classListB[i] not in Class):\n classBDF = copy.deepcopy(classListB[i])\n classBDF += 1\n classListB[i] = classBDF\n else:\n classListB[i] = 1\n i += 1\n elif int(X[att_Col]) > 3500 and int(X[att_Col]) <= 10000:\n i = 0\n for m in Class:\n if (X[-1] == m):\n if (classListC[i] not in Class):\n classCDF = copy.deepcopy(classListC[i])\n classCDF += 1\n classListC[i] = classCDF\n else:\n classListC[i] = 1\n i += 1\n\n elif X[att_Col].isdigit() and self.digitcounter == 2:\n if int(X[att_Col]) > 0 and int(X[att_Col]) <= 30000:\n i = 0\n for m in Class:\n if (X[-1] == m):\n if (classListA[i] not in Class):\n classADF = copy.deepcopy(classListA[i])\n classADF += 1\n classListA[i] = classADF\n else:\n classListA[i] = 1\n i += 1\n elif int(X[att_Col]) > 30000 and int(X[att_Col]) <= 80000:\n i = 0\n for m in Class:\n if (X[-1] == m):\n if (classListB[i] not in Class):\n classBDF = copy.deepcopy(classListB[i])\n classBDF += 1\n classListB[i] = classBDF\n else:\n classListB[i] = 1\n i += 1\n elif int(X[att_Col]) > 80000 and int(X[att_Col]) <= 150000:\n i = 0\n for m in Class:\n if (X[-1] == m):\n if (classListC[i] not in Class):\n classCDF = copy.deepcopy(classListC[i])\n classCDF += 1\n classListC[i] = classCDF\n else:\n classListC[i] = 1\n i += 1\n elif int(X[att_Col]) > 150000:\n i = 0\n for m in Class:\n if (X[-1] == m):\n if (classListD[i] not in Class):\n classDDF = copy.deepcopy(classListD[i])\n classDDF += 1\n classListD[i] = classDDF\n else:\n classListD[i] = 1\n i += 1\n\n elif X[att_Col] == 'y' and X[-1] in Class:\n i = 0\n for m in Class:\n if (X[-1] == m):\n if (TrueList[i] not in Class):\n PDF = copy.deepcopy(TrueList[i])\n PDF += 1\n TrueList[i] = PDF\n else:\n TrueList[i] = 1\n i += 1\n '''\n if (X[-1] == 'DF'):\n TrueList[0] = PDF\n PDF += 1\n elif (X[-1] == 'DHF1'):\n TrueList[1] = PDHF1\n PDHF1 += 1\n elif (X[-1] == 'DHF2'):\n TrueList[2] = PDHF2\n PDHF2 += 1\n elif (X[-1] == 'DHF3'):\n TrueList[3] = PDHF3\n PDHF3 += 1\n '''\n elif (X[att_Col] == 'n' and X[-1] in Class):\n i = 0\n for m in Class:\n if (X[-1] == m):\n if (FalseList[i] not in Class):\n NDF = copy.deepcopy(FalseList[i])\n NDF += 1\n FalseList[i] = NDF\n else:\n FalseList[i] = 1\n i += 1\n '''\n if (X[-1] == 'DF'):\n FalseList[0] = NDF\n NDF += 1\n elif (X[-1] == 'DHF1'):\n FalseList[1] = NDHF1\n NDHF1 += 1\n elif (X[-1] == 'DHF2'):\n FalseList[2] = NDHF2\n NDHF2 += 1\n elif (X[-1] == 'DHF3'):\n FalseList[3] = NDHF3\n NDHF3 += 1\n '''\n elif (X[att_Col] == 'w' and X[-1] in Class):\n i = 0\n for m in Class:\n if (X[-1] == m):\n if (WList[i] not in Class):\n WDF = copy.deepcopy(WList[i])\n WDF += 1\n WList[i] = WDF\n else:\n WList[i] = 1\n i += 1\n '''\n if (X[-1] == 'DF'):\n WList[0] = WDF\n WDF += 1\n elif (X[-1] == 'DHF1'):\n WList[1] = WDHF1\n WDHF1 += 1\n elif (X[-1] == 'DHF2'):\n WList[2] = WDHF2\n WDHF2 += 1\n elif (X[-1] == 'DHF3'):\n WList[3] = WDHF3\n WDHF3 += 1\n '''\n elif (X[att_Col] == 'ab' and X[-1] in Class):\n i = 0\n for m in Class:\n if (X[-1] == m):\n if (AbList[i] not in Class):\n AbDF = copy.deepcopy(AbList[i])\n AbDF += 1\n AbList[i] = AbDF\n else:\n AbList[i] = 1\n i += 1\n '''\n if (X[-1] == 'DF'):\n AbList[0] = AbDF\n AbDF += 1\n elif (X[-1] == 'DHF1'):\n AbList[1] = AbDHF1\n AbDHF1 += 1\n elif (X[-1] == 'DHF2'):\n AbList[2] = AbDHF2\n AbDHF2 += 1\n elif (X[-1] == 'DHF3'):\n AbList[3] = AbDHF3\n AbDHF3 += 1\n '''\n elif (X[att_Col] == 'p' and X[-1] in Class):\n i = 0\n for m in Class:\n if (X[-1] == m):\n if (PList[i] not in Class):\n DF = copy.deepcopy(PList[i])\n DF += 1\n PList[i] = DF\n else:\n PList[i] = 1\n i += 1\n '''\n if (X[-1] == 'DF'):\n PList[0] = DF\n DF += 1\n elif (X[-1] == 'DHF1'):\n PList[1] = DHF1\n DHF1 += 1\n elif (X[-1] == 'DHF2'):\n PList[2] = DHF2\n DHF2 += 1\n elif (X[-1] == 'DHF3'):\n PList[3] = DHF3\n DHF3 += 1\n '''\n if X[att_Col].isdigit():\n self.digitcounter += 1\n DataRet = {}\n DataRet = {\"y\": TrueList, \"n\": FalseList, \"w\": WList, \"ab\": AbList, \"p\": PList, \"A\": classListA, \"B\": classListB,\n \"C\": classListC, \"D\": classListD}\n\n return DataRet\n\n def CountDifferent(self,Data, AttrCol):\n Diff_Val= []\n CopyData = copy.deepcopy(Data)\n for i in range(len(CopyData)):\n if (CopyData[i][12] not in ['A', 'B', 'C', 'D']):\n if int(CopyData[i][12]) >= 10 and int(CopyData[i][12]) <= 20:\n CopyData[i][12] = 'A'\n elif int(CopyData[i][12]) > 20 and int(CopyData[i][12]) <= 30:\n CopyData[i][12] = 'B'\n elif int(CopyData[i][12]) > 30:\n CopyData[i][12] = 'C'\n\n if int(CopyData[i][13]) >= 0 and int(CopyData[i][13]) <= 1999:\n CopyData[i][13] = 'A'\n elif int(CopyData[i][13]) > 1999 and int(CopyData[i][13]) <= 3500:\n CopyData[i][13] = 'B'\n elif int(CopyData[i][13]) > 3500 and int(CopyData[i][13]) <= 10000:\n CopyData[i][13] = 'C'\n\n if int(CopyData[i][14]) >= 0 and int(CopyData[i][14]) <= 30000:\n CopyData[i][14] = 'A'\n elif int(CopyData[i][14]) > 30000 and int(CopyData[i][14]) <= 80000:\n CopyData[i][14] = 'B'\n elif int(CopyData[i][14]) > 80000 and int(CopyData[i][14]) <= 150000:\n CopyData[i][14] = 'C'\n elif int(CopyData[i][14]) > 150000:\n CopyData[i][14] = 'D'\n for X in CopyData:\n if(X[AttrCol] not in Diff_Val):\n Diff_Val.append(X[AttrCol])\n\n return Diff_Val\n\n\n def MakeStruc(self, Rep_att,Data,A_val):\n i=1\n Attr_Val = MethodRepository.CountDifferent(self,Data,A_val)\n length= len(Attr_Val)\n ClassVal=[\"Attributes\",\"DF\",\"DHF1\",\"DHF2\",\"DHF3\"]\n Matrix =[]\n Matrix.append(ClassVal)\n for X in range(length):\n Matrix.append([])\n Matrix[i].append(Attr_Val[X])\n Matrix[i].append(Rep_att[Attr_Val[X]])\n i+=1\n return Matrix\n def Total(self,Data):\n Total=len(Data)-1\n return Total\n\n def PredictC(self, structure,Total,Differnce):\n PC=[]\n Result=0.0\n i=-1\n for I in range(4):\n i += 1\n Result=0.0\n for J in range(1,Differnce+1):\n Result+= int(structure[J][1][i])\n Result = Result/Total\n PC.append(Result)\n return PC\n\n def PredictX(self,structure,Total,Difference):\n i=1\n Data=[]\n Result=0.0\n XData=[]\n Total = len(Total)\n Class =\"\"\n X={}\n for J in range(1,Difference+1):\n Data = structure[J][1]\n Class = structure[J][0]\n for K in Data:\n Result += K\n Result=Result/Total\n X={Class: Result}\n XData.append(X)\n return XData\n\n def PredictXC(self,Structure,Total,Differnce):\n temp=0.0\n Result=0.0\n XCData=[]\n TempArray=[]\n k=-1\n i=-1\n Increment=-1\n Filler =[\"DF\",\"DHF1\",\"DHF2\",\"DHF3\"]\n for J in range(4):\n Class=\"\"\n TempArray = []\n i+=1\n k+=1\n t=0\n Increment+=1\n for I in range(1,Differnce+1):\n temp = Structure[I][1][i]\n Class = Structure[I][0][t]\n Result = temp/float(Total[Increment])\n TempArray.append(Class)\n TempArray.append(Result)\n XCData.append([])\n XCData[k].append({Filler[k]:[TempArray]})\n return XCData\n\n def PosterierP (self,C,XC,X,Attributes):\n Result =0.0\n increment =1\n c=0\n i=-1\n ListToRet =[]\n New_XC = MethodRepository.UnlockCList(self,XC)\n New_X = MethodRepository.UnlockXList(self,X,Attributes)\n AttributeName=[\"DF\",\"DHF1\",\"DHF2\",\"DHF3\"]\n TestValue = New_XC[0][1]\n for X in range(len(C)):\n increment=1\n c=0\n ListToRet.append([])\n i+=1\n ListToRet[i].append(AttributeName[X])\n for J in range(len(New_X)):\n ClassName= New_XC[X][c]\n AttrCLass =New_XC[X][increment]\n Attribute = New_X[J]\n Class = C[X]\n Result=None\n getcontext().prec=3\n Result=round(((AttrCLass*Class) /Attribute), 3)\n increment +=2\n c+=2\n ListToRet[i].append(ClassName)\n ListToRet[i].append(Result)\n return ListToRet\n\n\n\n#have to look here\n def UnlockCList(self,Structure):\n ClasList =[\"DF\",\"DHF1\",\"DHF2\",\"DHF3\"]\n ListToRet = []\n for X in range(len(ClasList)):\n test = Structure[X]\n newVal = test[0]\n anotherNewVal = newVal[ClasList[X]]\n anAnNewVal = anotherNewVal[0]\n ListToRet.append(anAnNewVal)\n return ListToRet\n\n # have to look here\n def UnlockXList(self,Structure,Attributes):\n XList=[\"n\",\"y\"]\n ListToRet =[]\n for X in range(len(Attributes)):\n Test = Structure[X]\n NewVal = Test[Attributes[X]]\n ListToRet.append(NewVal)\n return ListToRet\n\n def FinalStructure(self,PosterierP, Attributes):\n FinalStruc=[]\n i=1\n k=0\n index =1\n FinalStruc.append([\"Attribute\",\"DF\",\"DHF1\",\"DHF2\",\"DHF3\"])\n for X in Attributes:\n FinalStruc.append([])\n FinalStruc[i].append(X)\n i+=1\n\n for J in PosterierP:\n index =1\n k=0\n for T in Attributes:\n k+=2\n temp = J[k]\n FinalStruc[index].append(temp)\n index+=1\n return FinalStruc\n\n def Filter(self, Data, Class):\n ListToReturn = {}\n keys = [\"y\", \"n\", \"w\", \"ab\", \"p\", \"A\", \"B\", \"C\", \"D\"]\n increment = -1\n for J in keys:\n increment = -1\n temp = Data[J]\n if (temp != Class):\n for final in temp:\n increment += 1\n if (final in Class):\n temp[increment] = 0\n\n ListToReturn[J] = temp\n\n return ListToReturn\n\n def EvolveAttP(self,FinalStruct,TestD, Total):\n increment = 0\n index = -1\n legth = len(TestD)\n EvolvingList = []\n for Test in range(len(TestD)):\n EvolvingList.append([])\n increment = 0\n\n index += 1\n for X in FinalStruct:\n j = 1\n temp = TestD[Test][increment]\n increment += 1\n for J in X:\n if (j > 1):\n if (J[0] == temp):\n EvolvingList[index].append(J)\n j += 1\n return EvolvingList\n\n def EvolveForUser(self,FinalStruct,TestD, Total):\n increment = 0\n index = -1\n legth = len(TestD)\n EvolvingList = []\n\n increment = 0\n EvolvingList.append([])\n\n index += 1\n for X in FinalStruct:\n j = 1\n temp = TestD[increment]\n increment += 1\n for J in X:\n if (j > 1):\n if (J[0] == temp):\n EvolvingList[index].append(J)\n j+= 1\n return EvolvingList\n\n\n def findClassP(self,Total,Findings):\n Result=[]\n temp=0.0\n t1=0.0\n t2=0.0\n for X in Findings:\n t1=float(X)\n t2=float(Total)\n temp= t1/t2\n Result.append(temp)\n return Result\n\n def Predict(self,Values,ClassP):\n temp=1.0\n temp1 = 1.0\n temp2 = 1.0\n temp3 = 1.0\n\n Final={}\n Result=[]\n i=-1\n for R in Values:\n temp = 1.0\n temp1 = 1.0\n temp2 = 1.0\n temp3 = 1.0\n Result.append([])\n i+=1\n count =0\n for A in R:\n t1=float(A[1])\n\n M=temp*t1\n temp=M\n\n t2=float(A[2])\n B=temp1*t2\n temp1=B\n\n t3=float(A[3])\n C=temp2*t3\n temp2=C\n\n t4=float(A[4])\n D=temp3*t4\n temp3=D\n count+=1\n\n\n\n temp=round(temp*ClassP[0],15)\n temp1 = round(temp1 * ClassP[1],15)\n temp2 = round(temp2 * ClassP[2],15)\n temp3 = round(temp3 * ClassP[3],15)\n if( temp2>0):\n print(\"Yes yes yes!\")\n Result[i].append(temp)\n Result[i].append(temp1)\n Result[i].append(temp2)\n Result[i].append(temp3)\n\n return Result\n\n\n\n\n\n\n\n\n def Accuracy(self,TestD,Result):\n increment =-1\n Total = float(len(TestD))\n Count=0\n length= len(Result)\n print ('Actual Prediction')\n for X in TestD:\n print(X[-1]+\" \"+Result[increment])\n if(increment< length):\n increment += 1\n if(X[-1]==Result[increment]):\n Count+=1\n\n accuracy = (Count/Total)*100\n return accuracy\n\n def GivePrediction(self,Predictions):\n Classes =[\"DF\",\"DHF1\",\"DHF2\",\"DHF3\"]\n result=[]\n for predict in Predictions:\n temp = predict\n i=0\n location =0\n compare=0\n for X in predict:\n if(X>compare):\n location=i\n compare=X\n i+=1\n reply = Classes[location]\n result.append(reply)\n\n return result\n def GivePredictionToUser(self,Prediction):\n Classes = [\"DF\", \"DHF1\", \"DHF2\", \"DHF3\"]\n result = []\n\n\n i = 0\n location = 0\n compare = 0\n for X in Prediction:\n if (X > compare):\n location = i\n compare = X\n i += 1\n reply = Classes[location]\n result.append(reply)\n\n return result\n\n\n def ZeroFreProblem(self, Data, Keys):\n\n for K in Keys:\n Lisst = Data[K]\n j=-1\n for i in Lisst:\n j+=1\n Lisst[j]+=1\n return Data\n\n def UniqueList(self, TraningData):\n list = []\n for X in TraningData:\n list.append(X[-1])\n listunique = set(list)\n listunique = sorted(listunique,None,None, False)\n return listunique\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"userInformation/Methods.py","file_name":"Methods.py","file_ext":"py","file_size_in_byte":21417,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"17835450","text":"# coding: utf-8\r\n__author__ = 'Joaquim Leitão'\r\n\r\n# Imports to be used in the code\r\nimport Pyro4.core\r\nimport math\r\nimport time\r\n\r\n# Pyro4 Specific data\r\nport = 6000\r\nname = \"NIBoard\"\r\nuri = \"PYRO:/\" + name + \"@localhost:\" + str(port)\r\n\r\n# Get a Pyro4 proxy to the greeting object\r\nboard_interaction = Pyro4.Proxy(uri)\r\n\r\nwhile True:\r\n valor = raw_input(\"Insere o valor\")\r\n board_interaction.execute_task(\"ao0\", 1, float(valor))\r\n board_interaction.execute_task(\"ao1\", 1, float(valor))\r\n\r\n\"\"\"\r\n# Generate the actuation signal\r\nx = [i for i in range(10)]\r\ndata = [abs(math.sin(i)) for i in x]\r\nprint data\r\n\r\n# Send each value to the board, specifying the desired physical channel where the actuation is going to be performed\r\n# (in this case the actuation is going to take place in the physical channel ao0)\r\nfor current in data:\r\n result = board_interaction.execute_task(\"ao0\", 1, current)\r\n print \"Executing task... \" + str(result) + \"!\"\r\n time.sleep(1)\r\n\r\n# Read all the channels with previously defined number of samples\r\nprint board_interaction.read_all()\r\n\r\n# Read all the channels with a specified number of samples per channel\r\nprint board_interaction.read_all(num_samples={\"ai0\": 3, \"ai1\": 3, \"ai2\": 3, \"ai3\": 3, \"ai4\": 3, \"ai5\": 3,\r\n \"ai6\": 3, \"ai7\": 3})\r\n\"\"\"","sub_path":"daqmxinterface/Client.py","file_name":"Client.py","file_ext":"py","file_size_in_byte":1332,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"287003545","text":"import os\nimport shutil\n\nsettingsFile = open('./flattenerSettings.txt', 'r')\ndirectoryToReadFrom = settingsFile.readline().strip()\n\nflattenedDirectory = directoryToReadFrom + '/_flattened-files'\n\nprint('moving files from ' + directoryToReadFrom + ' to ' + flattenedDirectory)\n\ntry:\n os.mkdir(flattenedDirectory)\nexcept OSError:\n print('failed to create dir')\n\n# subdirectories = os.walk(directoryToReadFrom)\n\nfor root, dirs, files in os.walk(directoryToReadFrom):\n for name in files:\n filePath = os.path.join(root, name)\n print(filePath)\n try:\n if name.lower().endswith(('.png', '.jpg', '.jpeg')):\n os.rmdir(filePath)\n print('deleted ' + filePath)\n shutil.move(filePath, flattenedDirectory + '/' + name)\n except:\n print('failed to move file')\n\n if not os.listdir(root):\n os.rmdir(root)\n","sub_path":"flattenSubdirectories.py","file_name":"flattenSubdirectories.py","file_ext":"py","file_size_in_byte":904,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"335640300","text":"# -*- coding: utf-8 -*-\n\"\"\"\nAuthor: Sam Lamont, Labeeb Ahmed\nCreated: 6/7/2019\nLicense: Creative Commons Attribution 4.0 International (CC BY 4.0)\n http://creativecommons.org/licenses/by/4.0/\nPython version: Tested on Python 3.6x (x64)\n\n\nPURPOSE\n------------------------------------------------------------------------------\n[Floodplain and Channel Evaluation Toolkit]\n\nFACET is a standalone Python tool that uses open source modules to map the\nfloodplain extent and compute stream channel and floodplain geomorphic metrics\nsuch as channel width, streambank height, active floodplain width,\nand stream slope from DEMs.\n\n\nU.S. GEOLOGICAL SURVEY DISCLAIMER\n------------------------------------------------------------------------------\nThis software has been approved for release by the U.S. Geological Survey\n(USGS). Although the software has been subjected to rigorous review, the\nUSGS reserves the right to update the software as needed pursuant to further\nanalysis and review. No warranty, expressed or implied, is made by the USGS\nor the U.S. Government as to the functionality of the software and related\nmaterial nor shall the fact of release constitute any such warranty.\nFurthermore, the software is released on condition that neither the USGS nor\nthe U.S. Government shall be held liable for any damages resulting from its\nauthorized or unauthorized use.\n\nAny use of trade, product or firm names is for descriptive purposes only and\ndoes not imply endorsement by the U.S. Geological Survey.\n------------------------------------------------------------------------------\n\n\nNOTES\n------------------------------------------------------------------------------\n\"\"\"\n\nfrom pathlib import Path\nimport configparser\nimport funcs_v2\nimport glob\nimport logging\nimport os\nimport pandas as pd\nimport sys\nimport time\n\nimport config\nimport funcs_v2\n\ndef initialize_logger(log_file):\n logger = logging.getLogger('logger_loader')\n logging.basicConfig(filename=log_file, filemode='w')\n logger.setLevel(logging.INFO)\n formatter = logging.Formatter('%(asctime)s %(levelname)s [%(lineno)d] - %(message)s', '%m/%d/%Y %I:%M:%S %p')\n handler = logging.StreamHandler()\n handler.setLevel(logging.INFO)\n handler.setFormatter(formatter)\n logger.addHandler(handler)\n return logger\n\ndef clear_out_logger(logger):\n handlers = logger.handlers[:]\n for handler in handlers:\n handler.close()\n logger.removeHandler(handler)\n\nif __name__ == '__main__':\n \n print('\\n<<< Start >>>\\r\\n')\n\n # read in config file\n config_file = config.get_config_path()\n Config = configparser.ConfigParser()\n Config.read(config_file)\n\n # << PARAMETERS >> \n str_reachid = Config['reach and order']['reach_id']\n str_orderid = Config['reach and order']['order_id']\n\n # Cross section method:\n parm_ivert = float(Config['cross section method']['parm_ivert']) # 0.2 default\n XnPtDist = int(\n Config['cross section method']['XnPtDist']) # 3 is default Step along Xn length for interpolating elevation\n parm_ratiothresh = float(Config['cross section method']['parm_ratiothresh']) # 1.5 default\n parm_slpthresh = float(Config['cross section method']['parm_slpthresh']) # 0.03 default\n p_fpxnlen = int(Config['cross section method']['p_fpxnlen']) # 2D cross-section method (assign by order?)\n # p_buffxnlen = Config['cross section method']['p_buffxnlen'] # meters Hardcoded in: get_xn_length_by_order()\n p_xngap = int(Config['cross section method']['p_xngap']) # 3 default (spacing between cross sections)\n\n # Width from curvature via buffering method:\n use_wavelet_curvature_method = Config['width from curvature via buff. method']['use_wavelet_curvature_method']\n i_step = int(Config['width from curvature via buff. method'][\n 'i_step']) # length of reach segments for measuring width from bank pixels (and others?)\n max_buff = int(Config['width from curvature via buff. method'][\n 'max_buff']) # maximum buffer length for measuring width based on pixels\n\n # Preprocessing paths and Flags specifying what to run:\n inputProc = Config['paths and flags']['taudem cores'] # str(2) # number of cores to use for TauDEM processes\n str_mpi_path = Config['paths and flags']['mpi_path']\n str_taudem_dir = Config['paths and flags']['taudem_path']\n run_wg = Config['paths and flags'][\n 'wt_grid'] # Run create weight grid by finding start points from a given streamlines layer?\n run_taudem = Config['paths and flags']['taudem'] # Run TauDEM functions?\n physio = Config['paths and flags']['physio']\n census_roads = Config['paths and flags']['census roads']\n census_rails = Config['paths and flags']['census rails']\n gs_path = Config['paths and flags']['go-spatial']\n\n # define breach method\n rd_strm_breach_wbt = funcs_v2.str2bool(Config['breach options']['rd strm + wbt breach mtd'])\n rd_strm_breach_gs = funcs_v2.str2bool(Config['breach options']['rd strm + go-spatial mtd'])\n breach_gs = funcs_v2.str2bool(Config['breach options']['go-spatial mtd'])\n breach_wbt = funcs_v2.str2bool(Config['breach options']['default wbt breach mtd'])\n\n # test to see at least one breach method is defined\n mtd_sums = [rd_strm_breach_wbt, rd_strm_breach_gs, breach_wbt]\n print(mtd_sums)\n mtd_sum = sum(map(int, mtd_sums))\n if mtd_sum is 1:\n pass\n else:\n print('None or multiple breach methods defined! Please review config file and try again')\n sys.exit(0)\n\n # sys.exit(0)\n # CRS:\n spatial_ref = Config['spatial ref']['crs']\n\n # list of Hucs to exclude from FACET runs\n skip_list = Config['exclude HUCs']['skip_list'].split(',')\n skip_str = ','.join(skip_list)\n\n # logfile path\n log_file = Config['logging']['log_file']\n\n # logging\n logger = initialize_logger(log_file)\n logger.info(f'Following HUCs will be skipped based on exclusion list: {skip_str}')\n\n # ===============================================================================================\n # BEGIN BULK PROCESSING LOOP\n # ===============================================================================================\n\n # << FOR BULK PROCESSING >>\n # Specify path to root:\n data_dir = Config['paths and flags']['data_dir']\n lst_paths = glob.glob(f\"{data_dir}\\\\*\")\n lst_paths.sort() # for testing\n # ===============================================================================================\n # Chesapeake file structure:\n # ===============================================================================================\n for i, path in enumerate(lst_paths):\n path = Path(path) # convert to Windows path\n str_nhdhr_huc4 = path / f'{path.stem}.shp' # Z:\\facet\\CFN_CB_HUC10\\0206\\0206.shp\n\n if str_nhdhr_huc4.is_file():\n logger.info(f'HUC4 shp does exist!: {str_nhdhr_huc4}')\n pass\n else:\n logger.info(f'HUC4 shp DOES NOT exist!: {str_nhdhr_huc4}')\n break\n\n # Re-project the NHD to match the DEM:\n str_nhdhr_huc4_proj = funcs_v2.reproject_vector_layer(path, str_nhdhr_huc4,\n spatial_ref) # Z:\\facet\\CFN_CB_HUC10\\0205\\0205_proj.shp\n\n for root, dirs, files in os.walk(path):\n for huc_dir in dirs:\n start_time_i = time.clock()\n\n hucID = huc_dir # HUC 10 or 12 ID\n root = Path(root) # HUC4 directory\n huc_dir = root / hucID\n\n print(huc_dir, hucID)\n\n str_dem = huc_dir / f'{hucID}_dem.tif'\n if str_dem.is_file():\n logger.info(f'raw DEM exists: {str_dem}')\n else:\n logger.warning(f'raw DEM DOES NOT exists: {str_dem}')\n continue\n\n if hucID in skip_list:\n continue\n\n # construct file paths\n str_dem_path = str_dem\n str_nhdhr_huc10 = huc_dir / f'{hucID}_dem_nhdhires.shp'\n str_dem_proj = huc_dir / f'{hucID}_dem_proj.tif'\n str_breached_dem_path = huc_dir / f'{hucID}_breach.tif'\n\n # Project dem raster\n str_dem_path_proj = funcs_v2.reproject_grid_layer(str_dem_path, spatial_ref, str_dem_proj,\n resolution=(3.0, 3.0))\n\n # Clip the HUC4 nhdhr streamlines layer to the HUC10:\n funcs_v2.clip_features_using_grid(str_nhdhr_huc4_proj, str_nhdhr_huc10, str_dem_path_proj, spatial_ref,\n logger)\n\n # Call preprocessing function:\n if rd_strm_breach_wbt:\n dem_merge = funcs_v2.cond_dem_for_road_x_stream_crossings(huc_dir, hucID, str_dem_proj,\n str_nhdhr_huc10, census_roads,\n census_rails)\n funcs_v2.breach_dem(dem_merge, str_breached_dem_path)\n\n elif rd_strm_breach_gs:\n dem_merge = funcs_v2.cond_dem_for_road_x_stream_crossings(huc_dir, hucID, str_dem_proj,\n str_nhdhr_huc10, census_roads,\n census_rails)\n funcs_v2.breach_using_gs_wbt_method(huc_dir, str_dem_proj, gs_path, str_breached_dem_path,\n spatial_ref)\n\n elif breach_gs:\n funcs_v2.breach_using_gs_wbt_method(huc_dir, str_dem_proj, gs_path, str_breached_dem_path,\n spatial_ref)\n\n elif breach_wbt:\n # default breach\n funcs_v2.breach_dem(str_dem_proj, str_breached_dem_path)\n\n # additional preprocessing steps\n funcs_v2.preprocess_dem(huc_dir, str_nhdhr_huc10, spatial_ref,\n str_mpi_path, str_taudem_dir,\n run_wg, run_taudem, physio,\n hucID, str_breached_dem_path, inputProc)\n\n # start of post-processing steps(???)\n str_dem_path = huc_dir / f'{hucID}_dem_proj.tif'\n str_hand_path = huc_dir / f'{hucID}_breach_hand.tif'\n str_net_path = huc_dir / f'{hucID}_breach_net.shp'\n str_raster_net_path = huc_dir / f'{hucID}_breach_net.tif'\n str_sheds_path = huc_dir / f'{hucID}_breach_w_diss_physio.shp'\n # output paths\n str_csv_path = huc_dir / f'{hucID}.csv'\n str_chxns_path = huc_dir / f'{hucID}_breach_chxns.shp'\n str_bankpts_path = huc_dir / f'{hucID}_breach_bankpts.shp'\n str_chanmet_segs = huc_dir / f'{hucID}_breach_net_ch_width.shp'\n str_bankpixels_path = huc_dir / f'{hucID}_breach_bankpixels.tif'\n str_fpxns_path = huc_dir / f'{hucID}_breach_fpxns.shp'\n str_fim_path = huc_dir / f'{hucID}_breach_hand_3sqkm_fim.tif'\n str_fim_csv = huc_dir / f'{hucID}_breach_hand_3sqkm_fim_h.csv'\n str_comp_path = huc_dir / f'{hucID}_breach_comp.tif'\n\n # Convert vector streamlines to raster with pixel streamline values matching linkno:\n funcs_v2.rasterize_gdf(str_net_path, str_hand_path, str_raster_net_path, None, None)\n\n # << GET CELL SIZE >>\n cell_size = int(funcs_v2.get_cell_size(str_dem_path)) # range functions need int?\n\n # << BUILD STREAMLINES COORDINATES >>\n logger.info('Generating the stream network coordinates from the csv file...')\n df_coords, streamlines_crs = funcs_v2.get_stream_coords_from_features(str_net_path, cell_size,\n str_reachid, str_orderid,\n logger) # YES!\n df_coords.to_csv(str_csv_path)\n logger.info('Reading the stream network coordinates from the csv file...')\n df_coords = pd.read_csv(str_csv_path, )\n\n # ============================= << CROSS SECTION ANALYSES >> =====================================\n # << CREATE Xn SHAPEFILES >>\n # Channel:\n funcs_v2.write_xns_shp(df_coords, streamlines_crs, str_chxns_path, False, p_xngap, logger)\n # Floodplain:\n funcs_v2.write_xns_shp(df_coords, streamlines_crs, str_fpxns_path, True, int(30), logger)\n\n # << INTERPOLATE ELEVATION ALONG Xns >>\n df_xn_elev = funcs_v2.read_xns_shp_and_get_dem_window(str_chxns_path, str_dem_path, logger)\n\n # Calculate channel metrics and write bank point shapefile...# NOTE: Use raw DEM here?? \n funcs_v2.chanmetrics_bankpts(df_xn_elev, str_chxns_path, str_dem_path,\n str_bankpts_path, parm_ivert, XnPtDist,\n parm_ratiothresh, parm_slpthresh, logger)\n\n # ========================== << BANK PIXELS AND WIDTH FROM CURVATURE >> ==========================\n funcs_v2.bankpixels_from_curvature_window(df_coords, str_dem_path, str_bankpixels_path,\n cell_size, use_wavelet_curvature_method,\n logger)\n\n funcs_v2.channel_width_from_bank_pixels(df_coords, str_net_path, str_bankpixels_path,\n str_reachid, i_step, max_buff,\n str_chanmet_segs, logger)\n\n # ============================= << DELINEATE FIM >> =====================================\n funcs_v2.fim_hand_poly(str_hand_path, str_sheds_path, str_reachid,\n str_fim_path, str_fim_csv, logger)\n\n # ============================ << FLOODPLAIN METRICS >> =====================================\n # 1D approach:\n funcs_v2.read_fp_xns_shp_and_get_1D_fp_metrics(str_fpxns_path, str_fim_path, str_dem_path, logger)\n\n # 2D approach:\n funcs_v2.fp_metrics_chsegs(str_fim_path, 'ch_wid_tot', str_chanmet_segs, logger)\n\n # ==================== << HAND CHARACTERISTICS >> ====================================\n \"\"\" \n Calculate channel and FP metrics through analysis of the HAND grid, separating the \n in-channel pixels from the FP pixels.\n \"\"\"\n funcs_v2.hand_analysis_chsegs(str_hand_path, str_chanmet_segs, str_raster_net_path, str_fim_path,\n str_dem_path, logger)\n\n end_time = time.clock() - start_time_i\n logger.info(f'\\nRun time for {hucID}: {end_time}\\r\\n')\n","sub_path":"main_dev.py","file_name":"main_dev.py","file_ext":"py","file_size_in_byte":15541,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"424797332","text":"from selenium import webdriver\nimport time\ndriver = webdriver.Chrome()\n\ndriver.get('https://docs.seleniumhq.org/')\n\n# by ID\nprint(driver.find_element_by_id(\"editPage\").text)\n\n# by CSS selector\nprint(driver.find_element_by_css_selector('body.homepage.push:nth-child(2) div:nth-child(8) div:nth-child(2) div:nth-child(1) > img:nth-child(1)').get_attribute('src'))\n\ntime.sleep(1)\ndriver.quit()","sub_path":"Example/example_1.py","file_name":"example_1.py","file_ext":"py","file_size_in_byte":390,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"451983971","text":"#!/usr/bin/python3\n\nimport paho.mqtt.client as mqtt\nimport ssl\nimport json,time\nimport RPi.GPIO as GPIO\n\nGPIO.setwarnings(False)\n\ndef on_connect(client, userdata, flags, rc):\n print(\"Connected with result code \"+str(rc))\n client.subscribe(\"$aws/things/Raspberry-pi/shadow/update/accepted\")\n\ndef on_message(client, userdata, msg):\n message_json = json.loads(msg.payload.decode())\n GPIO.setmode(GPIO.BOARD)\n GPIO.setup(11, GPIO.OUT)\n if message_json['state']['desired']['led'] == \"on\":\n print(\"LED ON\")\n GPIO.output(11,GPIO.HIGH)\n elif message_json['state']['desired']['led'] == \"off\":\n print(\"LED OFF\")\n GPIO.output(11,GPIO.LOW)\n elif message_json['state']['desired']['led'] == \"blink\":\n print(\"blinking\")\n count=message_json['state']['desired']['count']\n print(count)\n for i in range (0,int(count)):\n GPIO.output(11,GPIO.HIGH)\n time.sleep(0.1)\n GPIO.output(11,GPIO.LOW)\n time.sleep(0.1)\n\n\n#Connect to AWS IoT\nclient = mqtt.Client(client_id=\"myrasp\")\nclient.on_connect = on_connect\nclient.on_message = on_message\nclient.tls_set(ca_certs='/root/root-CA.pem', certfile='/root/c9aa9ef139-certificate.pem.crt', keyfile='/root/c9aa9ef139-private.pem.key', tls_version=ssl.PROTOCOL_SSLv23)\nclient.tls_insecure_set(True)\nclient.connect(\"A1470V05UAX5KX.iot.eu-west-1.amazonaws.com\", 8883, 30)\nclient.loop_forever()\n\n\n","sub_path":"aws_subscribe.py","file_name":"aws_subscribe.py","file_ext":"py","file_size_in_byte":1444,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"54285233","text":"from flask import (\n Blueprint, flash, g, redirect, render_template, request,\n url_for, session\n)\nfrom werkzeug.exceptions import abort\n\nfrom blackjack.auth import login_required\nfrom blackjack.db import get_db\nfrom blackjack.blackjack import *\n\nbp = Blueprint('play', __name__, url_prefix='/play')\n\n@bp.route('/begin', methods=('GET', 'POST'))\n@login_required\ndef begin():\n\n\tif request.method == 'POST':\t\t# if form of method POST was submitted:\n\t \tif \"newGame\" in request.form:\t\t # if player clicked on this button:\n\t \t\treturn redirect(url_for('play.game'))\t# execute the route\n\t \telif \"statistics\" in request.form:\t\t # if player clicked on this button:\n\t \t\treturn redirect(url_for('welcome.statistics'))\t# execute the route\n\n\treturn render_template('play/begin.html')\n\n@bp.route('/game', methods=('GET', 'POST'))\n@login_required\ndef game():\n\n\tgame = Game()\t\t\t\t # create a new game\n\n\tif 'gameDeck' in session: # if a game is already in progress\n\t\tgame.restoreGame(session) # restore the state of the game\n\t\tgame.clearHands()\t\t # clear the player/dealer hands\n\n\tif request.method == 'GET':\t\t\t # if user arrived directly via game route \n\t\tif len(game.deck.deck) < 10:\t # if there aren't at least 10 cards in deck,\n\t\t\tflash('Playing with a new deck...') # flash a 'new deck' message\n\t\t\tgame = Game()\t\t\t\t # then instantiate a new Game (w. new deck)\n\n\t\tgame.beginDeal()\t\t\t\t # deal 2 cards to player and dealer\n\t\tgame.storeToSession(session)\t # store the game state to session\n\n\t\t# if either player has a blackjack:\n\t\tif game.playerHand.isBlackjack() or game.dealerHand.isBlackjack():\n\t\t\tgame.findWinner(session)\t # evaluate game result\n\t\t\tgame.storeToSession(session) # store the game state to session\n\t\t\treturn redirect(url_for('play.result'))\t# execute the result route\n\t\t\t\t\t# in this case, the player won't see game page\n\n\telif request.method == 'POST':\t\t# if user clicked Hit/Stand button\n\n\t\tgame.restoreGame(session)\t\t # restore the state of the game\n\n\t\tif \"hit\" in request.form:\t\t # if player clicked on \"Hit\":\n\t\t\tgame.hitPlayer()\t\t\t # deal 1 card to player\n\t\t\tgame.storeToSession(session) # store the game state to session\n\t\t\n\t\t\tif game.playerHand.isBust():\t# if playerHand is over 21:\n\t\t\t\tgame.findWinner(session)\t# evaluate game result\n\t\t\t\tgame.storeToSession(session) # store the game state to session\n\t\t\t\treturn redirect(url_for('play.result'))\t# execute the result route\n\n\t\telif \"stand\" in request.form:\t\t# if player clicked on \"Stand\"\n\n\t\t\tgame.dealerTurn()\t\t\t\t# run dealer strategy\n\t\t\tgame.findWinner(session)\t\t# evaluate game result\n\t\t\tgame.storeToSession(session) # store the game state to session\n\t\t\t\n\t\t\treturn redirect(url_for('play.result'))\t# execute the result route\n\n\treturn render_template('play/game.html',\t# render the game template\n\t\tplayerHand = session['playerHand'], dealerPartialHand = session['dealerHand'][1:],\n\t\tplayerHandValue = session['playerHandValue'], dealerHandValue = session['dealerHandValue'],\n\t\tgameDeck = session['gameDeck'], deckSize = session['deckSize'],\n\t\tuserChoice = ['hit','stand']\n\t)\n\n\n@bp.route('/result', methods=('GET', 'POST'))\t# user arrives here after game is completed\n@login_required\ndef result():\n \n\tif request.method == 'POST':\t\t# if form of method POST was submitted:\n\t \tif \"playAgain\" in request.form:\t\t # if player clicked on this button:\n\t \t\treturn redirect(url_for('play.game'))\t# execute the route\n\t \telif \"statistics\" in request.form:\t\t # if player clicked on this button:\n\t \t\treturn redirect(url_for('welcome.statistics'))\t# execute the route\n\t \telif \"logout\" in request.form:\t\t # if player clicked on this button:\n\t \t\treturn redirect(url_for('auth.logout'))\t# execute the route\n\n\treturn render_template('play/results.html',\t# render the result template\n\t\tplayerHand = session['playerHand'], dealerHand = session['dealerHand'],\n\t\tplayerHandValue = session['playerHandValue'], dealerHandValue = session['dealerHandValue'],\n\t\tgameDeck = session['gameDeck'], deckSize = session['deckSize'],\n\t\tgameResult = session['gameResult']\n\t)","sub_path":"blackjack/play.py","file_name":"play.py","file_ext":"py","file_size_in_byte":4029,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"436324315","text":"# This assignment about data and .csv files can be done from home on your laptop.\n# You do not need a pi-top, but you will need to install the PyCharm IDE for\n# running this Python script.\n#\n# First, download and install PyCharm from https://www.jetbrains.com/pycharm/download/\n#\n# Then, watch the instruction video \"Open Python script in PyCharm and run it\",\n# which can be found on the \"Training: Python\" web page. The video will help\n# you get started with PyCharm.\n#\n# Before you do this assignment, make sure that you have completed the\n# \"Basic Syntax.py\" assignment from previous lesson. It can be found\n# in the \"Lesson 1 and 2\" folder on the \"Training: Python\" web page.\n\n# ******************************** THE ASSIGNMENT ********************************\n# 1. Complete the script below so you can create a .csv file with data\n# 2. Import the .csv file in Microsoft Excel (choose Data -> From Text/CSV in\n# the menu bar).\n# 3. Create a bar chart for the data that was imported\n# ********************************************************************************\n\n# The following line will make the csv functions from Python available to this\n# script\nimport csv\n\n\n# On this line, we set the name of our .csv file\ncsv_file_name = 'body-length.csv'\n\n\n# Here, we will open the file and write data to it\nwith open(csv_file_name, 'w', newline='') as csvfile:\n data_writer = csv.writer(csvfile, delimiter=',', quotechar='\"', quoting=csv.QUOTE_MINIMAL)\n\n # Let's write the header row\n data_writer.writerow(['Name', 'Length'])\n\n # We will add 10 rows of data to the file. The loop is already there, but you need\n # to complete the code.\n for i in range(0, 10):\n # TO DO: ask for the name of a friend or family member and then for his/her body length.\n # store the results in the name and length variables.\n # If you need help about reading user input, then search the web for 'python user input'.\n # You will also need to convert the second answer (body length) to a float\n # (search the web for 'python string to float').\n name = ''\n length = 0.0\n length_chosen = False\n print(\"New user, please enter your name.\")\n while name == '':\n name = input()\n print(name + \", please input your length in meters.\")\n while not length_chosen:\n length_chosen = True\n length = input()\n try:\n length = float(length)\n except ValueError:\n print(\"Invalid input! Please try again.\")\n length_chosen = False\n if length_chosen:\n if length > 2.72:\n print(\"You're either taller than the tallest person to ever exist, or you've entered your length wrong.\")\n length_chosen = False\n if length < 0.599:\n print(\"You either entered your length wrong, or you've not been born yet.\")\n length_chosen = False\n \n # And finally, write a line of code that adds the name and length to the .csv file\n # Search the web for 'python csv write row' for help.\n data_writer.writerow([name, length])\n\n\n\n","sub_path":"6 Periode 6/Scripting/Work from Home Assignment.py","file_name":"Work from Home Assignment.py","file_ext":"py","file_size_in_byte":3213,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"616430521","text":"import pandas as pd\r\nimport random\r\nimport os\r\nimport time\r\nimport argparse\r\nimport sys\r\n\r\ndef getMaxFreq(table, col):\r\n return list(table.iloc[:,col].value_counts().to_dict().values())[0]\r\n\r\ndef load_dictionary(table, frame):\r\n d = {}\r\n for t in table:\r\n d.setdefault(t[frame[0]], []).append(t[frame[1]])\r\n return d\r\n\r\ndef olken(cust_list, order_dict, lineitem_dict, max_p):\r\n \"\"\"\r\n Init\r\n \"\"\"\r\n p = 1.0\r\n\r\n value = random.choice(cust_list)\r\n\r\n if value in order_dict:\r\n p *= len(order_dict[value])\r\n value = random.choice(order_dict[value])\r\n else:\r\n return False\r\n\r\n if value in lineitem_dict:\r\n p *= len(lineitem_dict[value])\r\n else:\r\n return False\r\n\r\n return random.uniform(0, max_p) < p\r\n\r\ndef main():\r\n \"\"\"\r\n Parsing Arguments\r\n \"\"\"\r\n parser = argparse.ArgumentParser(description=\"take params including scale factors and sample size\")\r\n parser.add_argument('--sf', nargs=1)\r\n if (parser.parse_args().sf == None):\r\n print(\"Please specify scale factor after --sf\\ne.g. \\\"python EO_Q3.py --sf 0.1\\\"\")\r\n exit(0)\r\n else:\r\n sf = parser.parse_args().sf[0]\r\n \r\n \"\"\"\r\n Load Table\r\n \"\"\"\r\n cur_dir = os.path.dirname(os.path.realpath(__file__))\r\n data_path = os.path.join(cur_dir, \"data\", sf + \"x\")\r\n if not os.path.exists(data_path):\r\n print(\"\\\"{}\\\" doesn't exists... please check again...\".format(data_path))\r\n exit(0)\r\n cust_table = pd.read_table(os.path.join(cur_dir, \"data\", sf + \"x\", \"customer.tbl\"), delimiter='|', usecols=[0], names=[\"CUSTKEY\"])\r\n order_table = pd.read_table(os.path.join(cur_dir, \"data\", sf + \"x\", \"orders.tbl\"), delimiter='|', usecols=[0, 1], names=[\"ORDERKEY\", \"CUSTKEY\"])\r\n lineitem_table = pd.read_table(os.path.join(cur_dir, \"data\", sf + \"x\", \"lineitem.tbl\"), delimiter='|', usecols=[0, 3], names=[\"ORDERKEY\", \"LINENUMBER\"])\r\n\r\n cust_list = cust_table['CUSTKEY'].values.tolist()\r\n order_list = order_table.values.tolist()\r\n lineitem_list = lineitem_table.values.tolist()\r\n \r\n \"\"\"\r\n Prepare to sample\r\n \"\"\"\r\n max_p = 1.0\r\n frame = [(0,0),(1,0),(0,1)]\r\n print('Extended Olken on Q3 ...')\r\n print('building dictionary ...')\r\n order_dict = load_dictionary(order_list,frame[1])\r\n lineitem_dict = load_dictionary(lineitem_list,frame[2])\r\n\r\n lst_table = [cust_table,order_table,lineitem_table]\r\n\r\n for tbl in range(1,len(frame)):\r\n max_p *= getMaxFreq(lst_table[tbl],frame[tbl][0])\r\n\r\n print('max_p = {}'.format(max_p))\r\n\r\n \"\"\"\r\n Begin sampling\r\n \"\"\"\r\n print('begin sampling ...')\r\n for tot_size in [1000,10000,100000,1000000]:\r\n print('sample size = {}'.format(tot_size))\r\n sample_size = 0\r\n start_time = time.time()\r\n trail = 1\r\n while sample_size < tot_size:\r\n if olken(cust_list,order_dict,lineitem_dict, max_p):\r\n sample_size += 1\r\n trail +=1\r\n\r\n print(\"sampling time = {}, trail = {}\".format((time.time() - start_time), trail))\r\n print(\"--\"*50)\r\n\r\nif __name__ == '__main__':\r\n main()","sub_path":"EO_Q3.py","file_name":"EO_Q3.py","file_ext":"py","file_size_in_byte":3137,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"452935884","text":"# https://www.hackerrank.com/challenges/np-inner-and-outer/problem?isFullScreen=true\r\n# Problem : First, print the inner product. Second, print the outer product.\r\n# Sample Input\r\n# 0 1\r\n# 2 3\r\n\r\n# Sample Output\r\n# 3\r\n# [[0 0]\r\n# [2 3]]\r\n\r\n\r\nimport numpy as np\r\n\r\nA = np.array(input().split(), int)\r\nB = np.array(input().split(), int)\r\nprint( np.inner(A,B), np.outer(A,B), sep=\"\\n\" )","sub_path":"0_reference/Hackerrank/Practice Python/Numpy/Inner and Outer.py","file_name":"Inner and Outer.py","file_ext":"py","file_size_in_byte":384,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"473990661","text":"import numpy as np\nimport sys\nimport tensorflow as tf\n\n# set up input here\ntrain_data = np.load(\"concaveData.npy\")\ntrain_label = np.load(\"concaveTarget.npy\")\nN, p = train_data.shape\n\n# set up test data\ntest_date = np.load(\"TestData.npy\")\ntest_label = np.load(\"TestTarget.npy\")\n\n\n# minibatch gradient descent algorithm\nif len(sys.argv) == 1:\n batch_size = train_data.shape[0] // 10 # 10 batches\nelse:\n batch_size = int(sys.argv[1])\n print(batch_size)\n\n\n# function to create a list containing mini-batches\ndef create_mini_batches(X, z, batch_size):\n mini_batches = []\n data = np.hstack((X, z))\n np.random.shuffle(data)\n n_minibatches = data.shape[0] // batch_size\n\n for i in range(n_minibatches):\n mini_batch = data[i * batch_size:(i + 1)*batch_size, :]\n X_mini = mini_batch[:, :-1]\n z_mini = mini_batch[:, -1] # z is a vector, not a 1-column array\n mini_batches.append((X_mini, z_mini))\n if data.shape[0] % batch_size != 0:\n mini_batch = data[i * batch_size:data.shape[0]]\n X_mini = mini_batch[:, :-1]\n z_mini = mini_batch[:, -1]\n mini_batches.append((X_mini, z_mini))\n return mini_batches\n\n\n# set up network\nn_inputs = p\nn_hidden1 = 250\nn_hidden2 = 125\nn_hidden3 = 60\nn_hidden4 = 20\nn_outputs = 3 # 3 classes\n\n# use placeholder nodes to represent training data and targets\n# shape of input is (None, n_inputs)\n# assume training data is scaled to [0,1] floating point\n# during execution phase, X will be replaced with one training batch at a time\nX = tf.placeholder(tf.float32, shape=(None, n_inputs), name=\"X\")\nt = tf.placeholder(tf.int64, shape= None, name=\"t\")\n\n# create two hidden layers and output layer\nwith tf.name_scope(\"dnn\"):\n hidden1 = tf.layers.dense(X, n_hidden1, name=\"hidden1\", activation=tf.nn.elu)\n hidden2 = tf.layers.dense(hidden1, n_hidden2, name=\"hidden2\", activation=tf.nn.elu)\n hidden3 = tf.layers.dense(hidden2, n_hidden3, name=\"hidden3\", activation=tf.nn.elu)\n hidden4 = tf.layers.dense(hidden3, n_hidden4, name=\"hidden4\", activation=tf.nn.elu)\n logits = tf.layers.dense(hidden4, n_outputs, name=\"outputs\")\n\n# define cost function to train network\nwith tf.name_scope(\"loss\"):\n xentropy = tf.nn.sparse_softmax_cross_entropy_with_logits(labels=t, logits=logits)\n loss = tf.reduce_mean(xentropy, name=\"loss\")\n\n# define how to train\nlearning_rate = 0.01\nwith tf.name_scope(\"train\"):\n optimizer = tf.train.GradientDescentOptimizer(learning_rate)\n training_step = optimizer.minimize(loss)\n\n\n\n# how to evaluate model\nwith tf.name_scope(\"eval\"):\n correct = tf.nn.in_top_k(logits, t, 1)\n accuracy = tf.reduce_mean(tf.cast(correct, tf.float32))\n\n\n# initialize\ninit = tf.global_variables_initializer()\nsaver = tf.train.Saver()\n\nn_epochs = 500\nis_converge = -1\nthreshold_accuracy = 0.985\nmax_accuracy = 0.0\nconvergence_epoch = 0.0\ntry:\n with tf.Session() as session:\n init.run()\n for epoch in range(n_epochs):\n mini_batches = create_mini_batches(train_data, train_label.reshape(train_label.shape[0], 1), batch_size)\n for mini_batch in mini_batches:\n # do training step first\n X_batch, t_batch = mini_batch\n session.run(training_step, feed_dict={X:X_batch, t:t_batch})\n\n # check accuracies training and test\n acc_train = accuracy.eval(feed_dict={X: X_batch, t: t_batch})\n acc_val = accuracy.eval(feed_dict={X: test_date, t: test_label})\n max_accuracy = max(max_accuracy, acc_val)\n\n # to determine the convergence point\n if (max_accuracy > threshold_accuracy) and (is_converge == 0):\n is_converge = 1\n convergence_epoch = epoch\n\n print('epoch : ', epoch, ' Accuracy for Train Data : ', \"{0:.3f}\".format(round(acc_train, 3)),\n ' Accuracy for Test Data : ', \"{0:.3f}\".format(round(acc_val, 3)))\n\n if is_converge == 1:\n print(\"The Model converged at epoch : \", convergence_epoch)\n else:\n print(\"The Model doesn't converge !\")\n\n print('Maximum accuracy of the DNN Model (With ELU Activation Function) : ', max_accuracy)\n print(', Converged at epoch : ',\n convergence_epoch, ' Maximum Accuracy of the model : ', max_accuracy)\n\n save_path = saver.save(session,\"./model_final.ckpt\")\n\nexcept:\n ex = sys.exc_info()\n print(\"Exception Details : \", ex[0])","sub_path":"neural-network/NN_with_elu_activation.py","file_name":"NN_with_elu_activation.py","file_ext":"py","file_size_in_byte":4520,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"226944699","text":"############################################################################\n############################## Dependancies ################################\n############################################################################\n\nimport pandas as pd\nimport numpy as np\n\nfrom textblob import TextBlob, Word\nimport gensim\nfrom gensim.models.doc2vec import Doc2Vec, TaggedDocument\nfrom nltk.tokenize import word_tokenize\nfrom nltk.corpus import stopwords\nimport string\nimport re\n\nfrom sklearn.decomposition import PCA\nfrom sklearn.manifold import TSNE\nimport hdbscan\n\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\nsns.set(font_scale=1.5)\n\n### Import data\n\nresult = pd.read_csv('final_result.csv')\noutliers = pd.read_csv('clusterer/outliers.csv')\noutliers.columns = ['index', 'outlier']\n### Fix the Sent column\n\nsent = result['logistic'].str.extract(r'(\\d+\\.\\d+)').astype(float)\nsent.columns = ['sent']\ndf_sent = pd.concat([result, sent, outliers['outlier']], axis=1, join_axes=[result.index])\ndf_sent.columns\ndf_final_data = df_sent[['Rank', 'Title', 'Genre', 'Description', 'Director', 'Actors', 'Year', 'Runtime (Minutes)', 'Rating', 'Votes', 'Revenue (Millions)', 'Metascore', 'x', 'y', 'clust', 'Diversity', 'NE', 'sent', 'outlier']]\n\n############################################################################\n############################## Exploring Clusters ##########################\n############################################################################\n\n############################################################################\n#################### Plot the Original Variables\n\nsns.set_style('whitegrid')\n\ncolor_palette = sns.color_palette('Paired', 99)\npalette = [(0.85, 0.85, 0.85)] + list(color_palette)\n\ngrid_rev = sns.FacetGrid(result, col=\"clust\", hue=\"clust\", col_wrap=3, aspect=1.5, palette=palette)\ngrid_rev.map(plt.hist,\n \"Revenue (Millions)\",\n density=True,\n range=(0,200),\n alpha=0.7,\n orientation='vertical',\n bins=20)\n#plt.xscale('log')\ngrid_rev.savefig('pics/revenue', dpi=400)\n\ngrid_yer = sns.FacetGrid(result, col=\"clust\", hue=\"clust\", col_wrap=3, aspect=1.5, palette=palette)\ngrid_yer.map(sns.distplot, \"Year\")\ngrid_yer.savefig('pics/year', dpi=400)\n\ngrid_rat = sns.FacetGrid(result, col=\"clust\", hue=\"clust\", col_wrap=3, aspect=1.5, palette=palette)\ngrid_rat.map(sns.distplot, \"Rating\")\ngrid_rat.savefig('pics/rating', dpi=400)\n\ngrid_vot = sns.FacetGrid(result, col=\"clust\", hue=\"clust\", col_wrap=3, aspect=1.5, palette=palette)\ngrid_vot.map(plt.hist,\n \"Votes\",\n density=True,\n range=(0,100000),\n orientation='vertical',\n alpha=0.7,\n bins=20)\n#plt.yscale('log')\n#plt.xscale('log')\ngrid_vot.savefig('pics/votes', dpi=400)\n\n#################### Unique Users Count\n\n# count rows by cluster\ncount = df_final_data.groupby(['clust']).count()\n# count unique values by cluster\nnunique = df_final_data.groupby(['clust']).nunique()\n# concat results\nusers_count = pd.concat([count[['Director']],\n nunique[['Director']]],\n axis=1,\n join_axes=[count.index]).reset_index()\n# get rid of the noise cluster\nusers_count_no_noise = users_count.loc[1:,:]\n\nusers_count_no_noise.columns = ['clust', 'all users', 'unique users']\nusers_melt = pd.melt(users_count_no_noise, id_vars=['clust'])\n\nsns.set_style('whitegrid')\nfactorplt = sns.factorplot(x=\"clust\", y=\"value\", hue=\"variable\", data=users_melt,\n size=6, kind=\"bar\", palette=palette[1:3], aspect=1.7, legend_out=0)\n\nfactorplt.savefig('pics/users_uniq', dpi=400)\n\n############################################################################\n#################### Plot the Added Variables\n\nsns.set_style('whitegrid')\n\ngrid_sent = sns.FacetGrid(df_final_data, col=\"clust\", hue=\"clust\", col_wrap=3, aspect=1.5, palette=palette)\ngrid_sent.map(sns.distplot, 'sent')\ngrid_sent.savefig('pics/sent', dpi=400)\n\ngrid_div = sns.FacetGrid(df_final_data, col=\"clust\", hue=\"clust\", col_wrap=3, aspect=1.5, palette=palette)\ngrid_div.map(sns.distplot, 'Diversity')\ngrid_div.savefig('pics/diversity', dpi=400)\n\ngrid_ne = sns.FacetGrid(df_final_data, col=\"clust\", hue=\"clust\", col_wrap=3, aspect=1.5, palette=palette)\ngrid_ne.map(sns.distplot, 'NE')\ngrid_ne.savefig('pics/ne', dpi=400)\n\ngrid_reg = sns.FacetGrid(df_final_data, col=\"clust\", hue=\"clust\", col_wrap=3, aspect=1.5, palette=palette)\ngrid_reg.map(sns.regplot, 'sent', 'Rating', order=2, scatter_kws={'s':5})\ngrid_reg.savefig('pics/reg', dpi=400)\n\n\n############################################################################\n# jointplot\n\nfrom scipy.stats import kendalltau\n#x = result['probabilities'].str.extract(r'(\\d+\\.\\d+)').astype(float)\n#y = result['probabilities'].str.extract(r'[^>]+(\\d+\\.\\d+)').astype(float)\n\njoint = sns.jointplot(df_final_data['sent'], df_final_data['Rating'], kind=\"hex\", stat_func=kendalltau, cmap=\"coolwarm\")\njoint.savefig('pics/joint', dpi=400)\n\n############################################################################\n# clustermap\n\ndf_clust_map = df_final_data[['Year', 'Runtime (Minutes)', 'Rating', 'Votes', 'Revenue (Millions)', 'Metascore', 'x', 'y', 'clust', 'Diversity', 'NE', 'sent', 'outlier']].fillna(0)\n\nclust_map = sns.clustermap(df_clust_map.corr(),\n center=0,\n cmap=\"coolwarm\",\n #row_colors=color_palette,\n #col_colors=color_palette,\n linewidths=.75,\n figsize=(13, 13)\n )\nclust_map.savefig('pics/clmap', dpi=400)\n\n############################################################################\n###################### Heatmaps Variables\n\n######## Constructiveness\n### Sentiment\n\ndf_heat_sent = df_final_data[['clust', 'Year', 'sent']]\ndf_heat_sent.set_index('Year')\ntable_sent = pd.pivot_table(df_heat_sent, values='sent', index=['Year'], columns=['clust'])\n\nhtmp_sent = table_sent.fillna(method='backfill').sort_index(axis=0)\n\nplt.figure(figsize=(16, 10))\nhtmap_plot_sent = sns.heatmap(htmp_sent, cmap=\"coolwarm\", square=0, annot=True)\nfig_heat_sent = htmap_plot_sent.get_figure()\nfig_heat_sent.savefig('pics/heat_sent', dpi=400)\n\n######## Rationality\n### Diversity\n\ndf_heat_div = df_final_data[['clust', 'Year', 'Diversity']]\ndf_heat_div.set_index('Year')\ntable_div = pd.pivot_table(df_heat_div, values='Diversity', index=['Year'], columns=['clust'])\n\nhtmp_div = table_div.fillna(method='backfill').sort_index(axis=0)\n\nplt.figure(figsize=(16, 10))\nhtmap_plot_div = sns.heatmap(htmp_div, cmap=\"coolwarm\", square=0, annot=True)\nfig_heat_div = htmap_plot_div.get_figure()\nfig_heat_div.savefig('pics/heat_div', dpi=400)\n\n### NE\n\ndf_heat_ne = df_final_data[['clust', 'Year', 'NE']]\ndf_heat_ne.set_index('Year')\ntable_ne = pd.pivot_table(df_heat_ne, values='NE', index=['Year'], columns=['clust'])\nhtmp_ne = table_ne.fillna(method='backfill').sort_index(axis=0)\n\nplt.figure(figsize=(16, 10))\nhtmap_plot_ne = sns.heatmap(htmp_ne, cmap=\"coolwarm\", square=0, annot=True)\nfig_heat_ne = htmap_plot_ne.get_figure()\nfig_heat_ne.savefig('pics/heat_ne', dpi=400)\n\n### Outliers\n\ndf_heat_out = df_final_data[['clust', 'Year', 'outlier']]\ndf_heat_out.set_index('Year')\ntable_out = pd.pivot_table(df_heat_out, values='outlier', index=['Year'], columns=['clust'])\n\nhtmp_out = table_out.fillna(method='backfill').sort_index(axis=0)\n\nplt.figure(figsize=(16, 10))\nhtmap_plot_out = sns.heatmap(htmp_out, cmap=\"coolwarm\", square=0, annot=True)\nfig_heat_out = htmap_plot_out.get_figure()\nfig_heat_out.savefig('pics/heat_out', dpi=400)\n\n######## Equality\n### Unique Users\n\n\n# Directors\n\ndf_heat_user = df_final_data[['clust', 'Year', 'Director']].groupby(['Year', 'clust']).nunique().drop(['clust', 'Year'], axis=1)\nfilms_count = df_final_data[['clust', 'Year', 'Director']].groupby(['Year', 'clust']).count()\n\ndf_heat_user['Equality'] = (films_count['Director'] / df_heat_user['Director'])*1\n\ntable_user = pd.pivot_table(df_heat_user, values='Equality', index=['Year'], columns=['clust'])\n\nhtmp_user = table_user.fillna(method='backfill').sort_index(axis=0)\n\nplt.figure(figsize=(16, 10))\nhtmap_plot_user = sns.heatmap(htmp_user, cmap=\"coolwarm\", annot=True, fmt='g')\nfig_heat_user = htmap_plot_user.get_figure()\nfig_heat_user.savefig('pics/heat_user', dpi=400)\n\n# Actors\n\nactors = pd.DataFrame(df_final_data[['clust', 'Year', 'Actors']])\n\ndef splitDataFrameList(df,target_column,separator):\n ''' df = dataframe to split,\n target_column = the column containing the values to split\n separator = the symbol used to perform the split\n returns: a dataframe with each entry for the target column separated, with each element moved into a new row.\n The values in the other columns are duplicated across the newly divided rows.\n '''\n def splitListToRows(row,row_accumulator,target_column,separator):\n split_row = row[target_column].split(separator)\n for s in split_row:\n new_row = row.to_dict()\n new_row[target_column] = s\n row_accumulator.append(new_row)\n new_rows = []\n df.apply(splitListToRows,axis=1,args = (new_rows,target_column,separator))\n new_df = pd.DataFrame(new_rows)\n return new_df\n\nact_split = splitDataFrameList(actors, 'Actors', ',')\nact_split_count = act_split.groupby(['Year', 'clust']).nunique().drop(['clust', 'Year'], axis=1)\nact_split_count['Equality'] = (films_count['Director'] / act_split_count['Actors'])*4\n\ntable_user_act = pd.pivot_table(act_split_count, values='Equality', index=['Year'], columns=['clust'])\n\nhtmp_user_act = table_user_act.fillna(method='backfill').sort_index(axis=0)\n\nplt.figure(figsize=(16, 10))\nhtmap_plot_user_act = sns.heatmap(htmp_user_act, cmap=\"coolwarm\", annot=True, fmt='g')\nfig_heat_user_act = htmap_plot_user_act.get_figure()\nfig_heat_user_act.savefig('pics/heat_user_act', dpi=400)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n#\n","sub_path":"05_Explorer.py","file_name":"05_Explorer.py","file_ext":"py","file_size_in_byte":9911,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"39961931","text":"#!/usr/bin/env python\n# coding: utf-8\n\n\"\"\"\nSimple FTP interface, way tailored towards the DWD CDC FTP server.\n\nWhy not https://ftputil.sschwarzer.net/trac/wiki/WikiStart\nfor the various FTP accesses and https://github.com/jd/tenacity\nfor repeat()? Well, why not keep it simple :)\n\nCreated: 06.09.20\n\"\"\"\n\nfrom ftplib import FTP\nimport logging\nfrom typing import Union, Tuple, Any, List\nfrom pathlib import Path\n\nimport johanna\n\n\ndef get_station_match(station: int = None) -> str:\n return f\"*_{station:05d}_*.zip\" if station else \"*.zip\"\n\n\ndef dwd(folder):\n # TODO make this a Context Handler\n SERVER = \"opendata.dwd.de\"\n with johanna.Timer() as t:\n ftp = FTP(SERVER, timeout=15)\n ftp.login() # anonymous\n ftp.cwd(folder)\n logging.info(f\"Connected to ftp://{SERVER}/{folder} {t.read()}\")\n return ftp\n\n\ndef repeat(callback, do_times: int = 3, throttle_sec: float = 3.0) -> Union[Tuple[bool, None], Tuple[bool, Any]]:\n \"\"\"\n Repeat callback n times, with throttling to tame external resource access.\n Utilizes https://stackoverflow.com/questions/2083987/how-to-retry-after-exception/7663441#7663441\n :param callback: Function w/o parameters, may raise Exceptions or TimeoutError.\n :param do_times: Try at most that often to execute callback().\n :param throttle_sec: Wait a short time before executing callback().\n :return: (True, result of callback) if operation was successful, else (False, None)\n \"\"\"\n assert isinstance(do_times, int)\n assert 0 < do_times <= 10\n assert isinstance(throttle_sec, float)\n assert 0.0 <= throttle_sec <= 10.0\n\n logging.info(f\"Retrying max. {do_times} times ...\")\n for attempt in range(do_times):\n try:\n result = callback()\n # The exceptions are tuned for callbacks using FTP\n except TimeoutError as ex: # will hopefully catch socket timeout\n logging.exception(\"Timeout!\")\n except Exception as ex: # will not catch KeyboardInterrupt :)\n logging.exception(\"Exception!\")\n else: # executed when the execution falls thru the try\n break\n logging.info(f\"Retrying after {throttle_sec:0.1f} sec ...\")\n johanna.sleep(throttle_sec)\n else:\n johanna.flag_as_error()\n logging.error(f\"Finally failed.\")\n return False, None\n return True, result\n\n\ndef ftp_nlst(ftp: FTP, station: int = None) -> list:\n \"\"\"\n Retrieve list of matching file names.\n :param ftp: Mandatory open FTP connection in proper subdirectory.\n :param station: Optional numeric station number. Return all ststion files\n if not specified.\n :return: List of file names (maybe empty) or None in case of issues.\n \"\"\"\n\n def collect(fnam: str) -> None: # Callback for FTP.retrlines\n collect.zips.append(fnam)\n johanna.collect_stat(\"ftp_download_bytes_cnt\", len(fnam))\n\n def download() -> list:\n collect.zips = list()\n with johanna.Timer() as t:\n rt = ftp.retrlines(f\"NLST {station_match}\", callback=collect)\n logging.info(rt) # like \"226 Directory send OK.\"\n logging.info(f\"Retrieved {len(collect.zips)} filenames {t.read()}\")\n johanna.collect_stat(\"ftp_download_time_sec\", t.read(raw=True))\n johanna.collect_stat(\"ftp_download_file_cnt\", 1)\n return collect.zips\n\n station_match = get_station_match(station)\n logging.info(f\"FTP: trying to NLST {station_match}\")\n success, fnams = repeat(download, do_times=3, throttle_sec=3.0)\n if not success:\n logging.info(f\"Cannot retrieve file list for {station_match}.\")\n # None will be returned, not empty list\n return fnams\n\n\ndef ftp_retrbinary(ftp: FTP, from_fnam: str, to_path: Path, verbose: bool = False) -> Path:\n \"\"\"\n Download file to local.\n :param ftp: Mandatory open FTP connection in proper subdirectory.\n :param from_fnam: Mandatory file name for download.\n :param to_path: Mandatory local Path to download file to.\n :param verbose: Print tick per 100 packages.\n :return: Path of downloaded file or None on failure.\n \"\"\"\n\n def collect(b: bytes) -> None: # Callback für FTP.retrbinary\n collect.open_file.write(b)\n collect.cnt += 1\n collect.volume += len(b)\n tick = (collect.cnt % 100 == 0)\n if verbose and tick:\n print(\".\", end=\"\", flush=True)\n\n def download() -> Path:\n collect.cnt = 0\n collect.volume = 0\n with johanna.Timer() as t:\n with open(to_path, 'wb') as collect.open_file:\n rt = ftp.retrbinary(\"RETR \" + from_fnam, collect)\n if verbose:\n print() # awkward\n logging.info(rt)\n logging.info(f\"Downloaded {collect.volume:,} bytes in {collect.cnt} blocks {t.read()}\")\n johanna.collect_stat(\"ftp_download_bytes_cnt\", collect.volume)\n johanna.collect_stat(\"ftp_download_time_sec\", t.read(raw=True))\n johanna.collect_stat(\"ftp_download_file_cnt\", 1)\n return to_path\n\n logging.info(f\"FTP: trying to RETR {from_fnam} in BINARY mode ...\")\n success, path = repeat(download, do_times=3, throttle_sec=3.0)\n if not success:\n logging.info(f\"Cannot retrieve file {from_fnam}.\")\n # None will be returned, not target path\n return path\n\n\ndef ftp_retrlines(ftp: FTP, from_fnam: str, to_path: Path = None, verbose: bool = False) -> Union[Path, List[str]]:\n \"\"\"\n Download file to local.\n :param ftp: Mandatory open FTP connection in proper subdirectory.\n :param from_fnam: Mandatory file name for download.\n :param to_path: Path to download file to. If None a list(str) will be returned.\n :param verbose: Print tick per 100 lines.\n :return: Path of downloaded file or list(str) – or None on failure.\n \"\"\"\n\n def collect(s: str) -> None: # Callback für FTP.retrlines\n if to_path:\n collect.open_file.write(s + \"\\n\")\n collect.cnt += 1\n collect.volume += len(s) + 1\n else:\n collect.lines.append(s)\n collect.cnt += 1\n collect.volume += len(s) + 1\n tick = (collect.cnt % 100 == 0)\n if verbose and tick:\n print(\".\", end=\"\", flush=True)\n\n def download() -> Path:\n collect.cnt = 0\n collect.volume = 0\n with johanna.Timer() as t:\n if to_path:\n with open(to_path, 'w') as collect.open_file:\n rt = ftp.retrlines(\"RETR \" + from_fnam, collect)\n else:\n collect.lines = []\n rt = ftp.retrlines(\"RETR \" + from_fnam, collect)\n if verbose:\n print() # awkward\n logging.info(rt)\n logging.info(f\"Downloaded {collect.volume:,} bytes in {collect.cnt} lines {t.read()}\")\n johanna.collect_stat(\"ftp_download_bytes_cnt\", collect.volume)\n johanna.collect_stat(\"ftp_download_time_sec\", t.read(raw=True))\n johanna.collect_stat(\"ftp_download_file_cnt\", 1)\n return to_path if to_path else collect.lines\n\n logging.info(f\"FTP: trying to RETR {from_fnam} in TEXT mode ...\")\n success, path = repeat(download, do_times=3, throttle_sec=3.0)\n if not success:\n logging.info(f\"Cannot retrieve file {from_fnam}.\")\n # None will be returned, not target path or file content\n return path\n\n\nif __name__ == \"__main__\":\n pass\n","sub_path":"dwdcdc/ftplight.py","file_name":"ftplight.py","file_ext":"py","file_size_in_byte":7389,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"481970266","text":"import graphlib\nimport os\nimport signal\nimport sys\nimport threading\nimport time\nfrom collections import defaultdict\nfrom concurrent import futures\nfrom itertools import permutations, product\nfrom typing import List, Dict\n\nimport enlighten\nimport networkx as nx\nimport networkx.classes.filters as nxfilters\nfrom loguru import logger\n\nfrom .actions import AnyOfAction\nfrom .actions.action import Action, ActionForBuild\nfrom .util import set_terminal_title\nfrom .exceptions import UserException, OrchestraException, InternalException\n\nDUMMY_ROOT = \"Dummy root\"\n\n\nclass Executor:\n def __init__(self, actions, no_deps=False, no_force=False, pretend=False, threads=1):\n self.actions = actions\n self.no_deps = no_deps\n self.no_force = no_force\n self.pretend = pretend\n self.threads = 1\n\n self._toposorter = graphlib.TopologicalSorter()\n self._pool = futures.ThreadPoolExecutor(max_workers=threads, thread_name_prefix=\"Builder\")\n self._queued_actions: Dict[futures.Future, Action] = {}\n self._running_actions: List[Action] = []\n self._failed_actions: List[Action] = []\n self._stop_the_world = False\n\n self._total_remaining = None\n self._current_remaining = None\n self._stop_updating_display = False\n self._display_manager: enlighten.Manager\n self._display_thread: threading.Thread\n\n def run(self):\n dependency_graph = self._create_dependency_graph()\n\n self._verify_prerequisites(dependency_graph)\n\n self._init_toposorter(dependency_graph)\n\n try:\n self._toposorter.prepare()\n except graphlib.CycleError as e:\n raise InternalException(f\"A cycle was found in the solved dependency graph: {e.args[1]}\")\n\n if not self._toposorter.is_active():\n logger.info(\"No actions to perform\")\n\n self._total_remaining = dependency_graph.number_of_nodes()\n self._current_remaining = self._total_remaining\n\n self._start_display_update()\n\n signal.signal(signal.SIGINT, self._sigint_handler)\n\n self._stop_the_world = False\n\n # Schedule and run the actions\n while (self._toposorter.is_active() and not self._failed_actions) or self._queued_actions:\n for action in self._toposorter.get_ready():\n future = self._pool.submit(self._run_action, action)\n self._queued_actions[future] = action\n\n try:\n done, not_done = futures.wait(self._queued_actions, return_when=futures.FIRST_COMPLETED)\n except KeyboardInterrupt:\n self._stop_display_update()\n os.killpg(os.getpgid(os.getpid()), signal.SIGINT)\n\n for completed_future in done:\n action = self._queued_actions[completed_future]\n del self._queued_actions[completed_future]\n try:\n exception = completed_future.exception()\n except futures.CancelledError:\n continue\n\n if exception:\n for future in self._queued_actions:\n future.cancel()\n self._failed_actions.append(action)\n if isinstance(exception, OrchestraException):\n exception.log_error()\n else:\n logger.error(f\"An unexpected exception occurred while running {action}\")\n logger.error(exception)\n else:\n self._toposorter.done(action)\n\n assert len(self._queued_actions) == 0 and len(self._running_actions) == 0\n\n self._stop_display_update()\n\n return list(self._failed_actions)\n\n def _create_dependency_graph(\n self,\n remove_unreachable=True,\n simplify_anyof=True,\n remove_satisfied=True,\n intra_component_ordering=True,\n transitive_reduction=True,\n ):\n # Recursively collect all dependencies of the root action in an initial graph\n dependency_graph = self._create_initial_dependency_graph()\n\n # Find an assignment for all the choices so the graph becomes acyclic\n dependency_graph = self._assign_choices(dependency_graph)\n if dependency_graph is None:\n raise UserException(\"Could not find an acyclic assignment for the given dependency graph\")\n\n if remove_unreachable:\n self._remove_unreachable_actions(dependency_graph, [DUMMY_ROOT])\n\n if simplify_anyof:\n # The graph returned contains choices with only one alternative\n # Simplify them by turning A -> Choice -> B into A -> B\n self._simplify_anyof_actions(dependency_graph)\n\n # Remove the dummy root node\n true_roots = list(dependency_graph.successors(DUMMY_ROOT))\n dependency_graph.remove_node(DUMMY_ROOT)\n if remove_satisfied:\n self._remove_satisfied_attracting_components(dependency_graph)\n # Re-add the true root actions as they may have been removed\n if not self.no_force:\n dependency_graph.add_nodes_from(true_roots)\n\n if intra_component_ordering:\n dependency_graph = self._enforce_intra_component_ordering(dependency_graph)\n\n if transitive_reduction:\n dependency_graph = self._transitive_reduction(dependency_graph)\n\n return dependency_graph\n\n def _create_initial_dependency_graph(self):\n graph = nx.DiGraph()\n graph.add_node(DUMMY_ROOT)\n for action in self.actions:\n graph.add_edge(DUMMY_ROOT, action)\n self._collect_dependencies(action, graph)\n return graph\n\n def _collect_dependencies(self, action, graph, already_visited_nodes=None):\n if already_visited_nodes is None:\n already_visited_nodes = set()\n\n if action in already_visited_nodes:\n return\n\n already_visited_nodes.add(action)\n graph.add_node(action)\n if self.no_deps:\n return\n\n for dependency in action.dependencies:\n graph.add_edge(action, dependency)\n self._collect_dependencies(dependency, graph, already_visited_nodes=already_visited_nodes)\n\n def _assign_choices(self, graph):\n # We can assign the choices for each strongly connected component independently\n while has_choices(graph):\n strongly_connected_components = list(nx.algorithms.strongly_connected_components(graph))\n strongly_connected_components.sort(key=len, reverse=True)\n for strongly_connected_component in strongly_connected_components:\n any_of_nodes = [\n c\n for c in strongly_connected_component\n if isinstance(c, AnyOfAction) and len(list(graph.successors(c))) > 1\n ]\n if not any_of_nodes:\n # There are no InstallAny nodes in this SCC, don't waste time\n continue\n graph = self._assign_strongly_connected_component(graph, any_of_nodes, strongly_connected_component)\n if graph is None:\n return graph\n break\n\n return graph\n\n def _assign_strongly_connected_component(self, graph, remaining, strongly_connected_component):\n # TODO: the copy() operation ~halves performance. The other edge/node add/removal\n # operations have an impact as well. We can avoid them using filtered views.\n\n # No more choices remain, check if the subgraph\n # of the stringly connected components is cyclic\n if not remaining:\n subgraph = graph.copy()\n self._remove_unreachable_actions(subgraph, [DUMMY_ROOT])\n subgraph = subgraph.subgraph(strongly_connected_component)\n\n if has_unsatisfied_cycles(subgraph):\n return None\n else:\n return graph\n\n to_assign = remaining.pop()\n\n # Try all choices\n alternatives = list(graph.successors(to_assign))\n alternatives.sort(key=keyer(to_assign))\n\n graph.remove_edges_from((to_assign, s) for s in alternatives)\n\n for alternative in alternatives:\n graph.add_edge(to_assign, alternative)\n\n # Assigning nodes that are not reachable from the root is pointless\n _, pointless = filter_out_unreachable(graph, remaining, [DUMMY_ROOT])\n for n in pointless:\n remaining.remove(n)\n\n solved_graph = self._assign_strongly_connected_component(graph, remaining, strongly_connected_component)\n if solved_graph is None:\n graph.remove_edge(to_assign, alternative)\n\n for n in pointless:\n remaining.append(n)\n else:\n return solved_graph\n\n graph.add_edges_from((to_assign, a) for a in alternatives)\n remaining.append(to_assign)\n\n @staticmethod\n def _simplify_anyof_actions(graph):\n for action in list(graph.nodes):\n if isinstance(action, AnyOfAction):\n predecessors = list(graph.predecessors(action))\n successors = list(graph.successors(action))\n assert len(successors) == 1, f\"Choice {action} was not taken?\"\n graph.remove_node(action)\n graph.add_edges_from((p, successors[0]) for p in predecessors)\n\n @staticmethod\n def _remove_unreachable_actions(graph, roots):\n # Remove all nodes that are not reachable from one of the roots\n shortest_paths = nx.multi_source_dijkstra_path_length(graph, roots)\n for node in list(graph.nodes):\n if node not in shortest_paths:\n graph.remove_node(node)\n\n @staticmethod\n def _remove_satisfied_attracting_components(graph):\n # Remove sets of attracting components where all components are satisfied\n fixed_point_reached = False\n done_something = False\n while not fixed_point_reached:\n fixed_point_reached = True\n for attracting_components in nx.attracting_components(graph):\n if all(c.is_satisfied() for c in attracting_components):\n graph.remove_nodes_from(attracting_components)\n fixed_point_reached = False\n done_something = True\n break\n return done_something\n\n def _enforce_intra_component_ordering(self, dependency_graph):\n \"\"\"This pass ensures that when two builds of the same component are\n scheduled to be installed their direct antidependencies will find those exact builds\n when run.\n Example:\n +-------+\n +--+ A@1 +--+\n | +-------+ |\n +---v---+ +---v---+\n | B@1 | | A@2 +--+\n +-------+ +-------+ |\n +---v---+\n | B@2 |\n +-------+\n\n Wihout this pass both following schedules are both possible:\n - B@2, A@2, B@1, A@1\n - B@2, B@1, A@2, A@1\n The second schedule runs B@1 after B@2, but A@2 after B@1,\n so A@2 would not find the exact build it was expecting.\n\n The pass transforms the graph above into:\n\n +-------+\n +--+ A@1 +--+\n | +-------+ |\n +---v---+ +---v---+\n | B@1 +-----> A@2 +--+\n +---+---+ +-------+ |\n | +---v---+\n +----------------> B@2 |\n +-------+\n\n For each component C the algorithm creates a list of groups of actions, one for each build.\n Each group contains:\n 1. actions that pertain to a specific build of the component\n 2. actions that directly depend on actions of point 1\n The algorithm tries all possible permutations of the groups in the list.\n For each permutation [G1, G2, ..., Gn] all actions in\n group Gi are marked to depend on all actions in group Gi+1.\n The graph is checked for cycles and if none are found the order is accepted.\n \"\"\"\n scheduled_actions_per_build = defaultdict(set)\n scheduled_builds_per_component = defaultdict(set)\n scheduled_actions_per_direct_build_dependency = defaultdict(set)\n\n for action in dependency_graph.nodes:\n if isinstance(action, ActionForBuild):\n scheduled_builds_per_component[action.component].add(action.build)\n scheduled_actions_per_build[action.build].add(action)\n for d in dependency_graph.predecessors(action):\n scheduled_actions_per_direct_build_dependency[action.build].add(d)\n\n groups_by_component = defaultdict(list)\n for c, blds in scheduled_builds_per_component.items():\n if len(blds) < 2:\n continue\n\n for bld in blds:\n group = scheduled_actions_per_build[bld].union(scheduled_actions_per_direct_build_dependency[bld])\n groups_by_component[c].append(group)\n\n for component, group in groups_by_component.items():\n dependency_graph = self._try_group_orders(dependency_graph, group)\n if dependency_graph is None:\n raise UserException(\n f\"Could not enforce an order between actions of \"\n f\"component {component} pertaining to multiple builds\"\n )\n\n return dependency_graph\n\n @staticmethod\n def _try_group_orders(dependency_graph, group):\n for permutation in permutations(group):\n # TODO: duplicating the graph is not good for performance, might be worth removing nodes manually\n depgraph_copy = dependency_graph.copy()\n\n for g1, g2 in zip(permutation, permutation[1:]):\n # Add edge from all nodes in g1 to all nodes in g2\n for a1, a2 in product(g1, g2):\n same_action = a1 is a2\n same_build = (\n isinstance(a1, ActionForBuild) and isinstance(a2, ActionForBuild) and a1.build is a2.build\n )\n\n # Don't add self loops or edges between actions for the same build.\n # Self loops add an unbreakable cycle that we obviously don't want.\n # Edges between actions of the same build do not have any advantage in the best case\n # as depencencies for other actions of the same build do not cause order-of-execution issues,\n # while in the worst case they introduce unbreakable cycles (install A -> configure A -> install A).\n if same_action or same_build:\n continue\n\n depgraph_copy.add_edge(a1, a2, label=\"Intra-component ordering\")\n\n if not has_unsatisfied_cycles(depgraph_copy):\n return depgraph_copy\n\n @staticmethod\n def _transitive_reduction(graph):\n labels = nx.get_edge_attributes(graph, \"label\")\n\n if nx.is_directed_acyclic_graph(graph):\n reduced_graph = nx.algorithms.dag.transitive_reduction(graph)\n nx.set_edge_attributes(reduced_graph, labels, \"label\")\n return reduced_graph\n\n # It is not possible (rather, it is expensive and not uniquely defined)\n # to compute the transitive reduction on a graph with cycles\n # So we:\n # - perform a condensation which gives us a DAG\n # (by \"shrinking\" all strongly connected components in a single node)\n # - perform a transitive reduction\n # - expand the condensed graph back to it's expanded form\n condensed_graph = nx.algorithms.condensation(graph)\n mapping = condensed_graph.graph[\"mapping\"]\n members = nx.get_node_attributes(condensed_graph, \"members\")\n\n condensed_graph = nx.algorithms.transitive_reduction(condensed_graph)\n\n # TODO: review this code, it may be re-adding edges that were taken out by the transitive reduction\n inflated_graph = nx.DiGraph()\n for condensed_node in condensed_graph.nodes:\n condensed_node_members = members[condensed_node]\n subgraph = nx.subgraph_view(graph, filter_node=nxfilters.show_nodes(condensed_node_members))\n inflated_graph = nx.union(inflated_graph, subgraph)\n\n for u, v in graph.out_edges(condensed_node_members):\n v_condensed_node = mapping[v]\n if condensed_graph.has_edge(condensed_node, v_condensed_node):\n inflated_graph.add_edge(u, v)\n\n nx.set_edge_attributes(inflated_graph, labels, \"label\")\n return inflated_graph\n\n @staticmethod\n def _verify_prerequisites(dependency_graph):\n for action in dependency_graph.nodes:\n action.assert_prerequisites_are_met()\n\n def _init_toposorter(self, dependency_graph):\n for action in dependency_graph.nodes:\n dependencies = dependency_graph.successors(action)\n self._toposorter.add(action, *dependencies)\n\n def _run_action(self, action: Action):\n self._running_actions.append(action)\n self._current_remaining -= 1\n explicitly_requested = action in self.actions\n\n try:\n if self._stop_the_world:\n return\n return action.run(pretend=self.pretend, explicitly_requested=explicitly_requested)\n except Exception as e:\n self._stop_the_world = True\n raise e\n finally:\n self._running_actions.remove(action)\n\n def _start_display_update(self):\n self._stop_updating_display = False\n # Display manager and status bar must be initialized in main thread\n self._display_manager = enlighten.get_manager()\n self._status_bar = self._display_manager.status_bar(leave=False)\n self._display_thread = threading.Thread(target=self._update_display, name=\"Display updater\")\n self._display_thread.start()\n\n def _stop_display_update(self):\n self._stop_updating_display = True\n while self._display_thread is not None:\n pass\n self._display_manager.stop()\n sys.stdout.buffer.flush()\n sys.stderr.buffer.flush()\n\n def _update_display(self):\n self._status_bar.color = \"bright_white_on_lightslategray\"\n try:\n while not self._stop_updating_display:\n running_jobs_str = \", \".join(a.name_for_info for a in self._running_actions)\n self._status_bar_args = {\n \"jobs\": running_jobs_str,\n \"current\": self._total_remaining - self._current_remaining,\n \"total\": self._total_remaining,\n }\n set_terminal_title(f\"Running {running_jobs_str}\")\n self._status_bar.status_format = \"[{current}/{total}] Running {jobs}\"\n self._status_bar.update(**self._status_bar_args)\n self._status_bar.refresh()\n time.sleep(0.1)\n finally:\n self._status_bar.status_format = \"Done\"\n self._status_bar.refresh()\n self._status_bar.close()\n self._display_thread = None\n\n def _sigint_handler(self, sig, frame):\n signal.signal(signal.SIGINT, signal.SIG_DFL)\n self._stop_display_update()\n signal.default_int_handler(signal.SIGINT, frame)\n\n\ndef has_unsatisfied_cycles(graph):\n simple_cycles = list(nx.simple_cycles(graph))\n for cycle in simple_cycles:\n if not all(c.is_satisfied() for c in cycle):\n return True\n return False\n\n\ndef has_choices(graph):\n for node in graph.nodes:\n if isinstance(node, AnyOfAction) and len(list(graph.successors(node))) > 1:\n return True\n return False\n\n\ndef keyer(to_assign):\n def _keyer(action):\n \"\"\"\n Prioritize choices in this order:\n - installed build\n - preferred build (either explicitly specified or default)\n - all others in alphabetical order\n \"\"\"\n if action.is_satisfied():\n priority = 0\n elif action is to_assign.preferred_action:\n priority = 1\n else:\n priority = 2\n return priority, str(action)\n\n return _keyer\n\n\ndef filter_out_unreachable(graph, nodes, roots):\n shortest_paths = nx.multi_source_dijkstra_path_length(graph, roots)\n reachable = []\n unreachable = []\n for node in nodes:\n if node not in shortest_paths:\n unreachable.append(node)\n else:\n reachable.append(node)\n return reachable, unreachable\n","sub_path":"orchestra/executor.py","file_name":"executor.py","file_ext":"py","file_size_in_byte":20765,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"11795620","text":"# coding=utf-8\n\"\"\"\nUser query\n\"\"\"\nimport sys\n\n\ndef query_yes_no(question, default=\"yes\"):\n \"\"\"Ask a yes/no question via raw_input() and return their answer.\n\n :param question: is a string that is presented to the user.\n :param default: is the presumed answer if the user just hits .\n It must be \"yes\" (the default), \"no\" or None (meaning\n an answer is required of the user).\n\n :return: The \"answer\" return value is True for \"yes\", False for \"no\".\n \"\"\"\n valid = {\"yes\": True, \"y\": True, \"ye\": True,\n \"no\": False, \"n\": False}\n if default is None:\n prompt_str = \" [y/n] \"\n elif default == \"yes\":\n prompt_str = \" [Y/n] \"\n elif default == \"no\":\n prompt_str = \" [y/N] \"\n else:\n raise ValueError(\"invalid default answer: '%s'\" % default)\n\n while True:\n sys.stdout.write(question + prompt_str)\n try:\n # noinspection PyUnresolvedReferences,PyCompatibility\n choice = raw_input().lower()\n except NameError:\n choice = input().lower()\n\n if default is not None and choice == '':\n return valid[default]\n elif choice in valid:\n return valid[choice]\n else:\n sys.stdout.write(\"Please respond with 'yes' or 'no' (or 'y' or 'n').\\n\")\n\n\ndef prompt(question, default=None):\n \"\"\"\n Prompt the user with a question that can have a default value\n\n :param question: is a string that is presented to the user.\n :type question: str\n :param default: is the presumed answer if the user just hits .\n :type default: str\n :return: The \"answer\" return value.\n :rtype: str|None\n \"\"\"\n if default is None:\n prompt_str = \" \"\n else:\n prompt_str = \" [{default}] \".format(default=str(default))\n\n sys.stdout.write(question + prompt_str)\n try:\n # noinspection PyUnresolvedReferences,PyCompatibility\n choice = raw_input()\n except NameError:\n choice = input()\n if choice == '':\n return default\n return choice\n","sub_path":"prompt.py","file_name":"prompt.py","file_ext":"py","file_size_in_byte":2062,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"610141697","text":"def remove_consecutive_repeating_characters(string):\n new_string = \"\"\n for i in range(len(string)):\n if i == len(string) - 1 or string[i] != string[i + 1]:\n new_string += string[i]\n return new_string\n\n\ndef is_palindrome(string):\n new_string = \"\"\n for i in range(len(string)):\n if i == len(string) - 1 or string[i] != string[i + 1]:\n new_string += string[i]\n return new_string == new_string[::-1]\n\n\ndef permute(string):\n\n if len(string) == 1:\n return [string]\n\n permutations = []\n for i in range(len(string)):\n char = string[i]\n sub_permutations = permute(string[:i] + string[i + 1:])\n\n for perm in sub_permutations:\n permutations.append(char + perm)\n return permutations\n\n\ninp = input()\nperms = permute(inp)\npals = []\nfor perm in perms:\n if is_palindrome(perm):\n pals.append(perm)\n\neven = 0\nodd = 0\nfor pal in pals:\n if len(pal) % 2 == 0:\n even += 1\n else:\n odd += 1\n\nprint(even, odd)\n","sub_path":"Good String if palindrome after removing repeating characters.py","file_name":"Good String if palindrome after removing repeating characters.py","file_ext":"py","file_size_in_byte":1020,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"580873035","text":"# Ivy Tech - SDEV 140 - Introduction to Software Development\n# Chapter 5 Exercise 12. Maximum of Two Values\n# Andrew M. Pierce Associate of Applied Science - Software Development\n# Python 3.8.6\n\n# logging for exceptions / sys for quit / time for sleep\nimport logging\nimport sys\nimport time\n\n# Handles all user input, expects numeric entry and responses > 0\n\n\ndef inputHandling(question):\n while True:\n try:\n userInput = input(question)\n isinstance(float(userInput), str)\n except Exception:\n logging.exception('Caught an error')\n # Pauses program so that exception prints to screen\n # and user sees next step to continue after error message.\n time.sleep(1)\n print(\"Your number needs to be entered with numeric keys.\")\n userQuit = input(\"Hit enter to continue or type 'q' and enter to quit: \")\n if userQuit == 'q':\n sys.exit(\"Quitting Program\")\n else:\n # Makes sure input is greater than zero to avoid / by zero error or zero responses\n if float(userInput) % 1 != 0:\n print(\"Your input must be a whole number.\")\n userQuit = input(\"Hit enter to continue or type 'q' and enter to quit: \")\n if userQuit == 'q':\n sys.exit(\"Quitting Program\")\n else:\n return float(userInput)\n\n\ndef isEqual(valueOne, valueTwo):\n if valueOne != valueTwo:\n return False\n else:\n return True\n\n\ndef maximumOfTwoValues(valueOne, valueTwo):\n # This function always returns a number, if both numbers are equal it will return the first number.\n if valueOne > valueTwo:\n return valueOne\n elif valueTwo > valueOne:\n return valueTwo\n else:\n return valueOne\n\n\ndef main():\n print()\n print('This program will check which integer entered has the largest value.')\n valueOne = int(inputHandling(\"Enter the first whole number: \"))\n valueTwo = int(inputHandling(\"Enter the second whole number: \"))\n equalNumber = isEqual(valueOne, valueTwo)\n if equalNumber is False:\n largestNumber = maximumOfTwoValues(valueOne, valueTwo)\n print()\n print(f'The largest number inputted was {largestNumber}')\n else:\n print()\n print(f'Both values are equal. The maximum is the same: {valueOne}')\n print()\n input('Press enter to exit... ')\n\n\nmain()\n","sub_path":"Chapter 005 Exercises/PierceAndrewM03_Ch5Ex12.py","file_name":"PierceAndrewM03_Ch5Ex12.py","file_ext":"py","file_size_in_byte":2450,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"633573603","text":"import sys\n# sys.path.append(\"/afs/ipp-garching.mpg.de/home/m/mwillens/Programme/python/lib/\")\nsys.path.append(\"/afs/ipp-garching.mpg.de/home/o/osam/workspace/python3_projects/modules_osam\")\nsys.path.append(\"/afs/ipp-garching.mpg.de/aug/ads-diags/common/python/lib\")\nimport ECE_Load_osam as ECE\nimport importlib\nimportlib.reload(ECE)\nimport numpy as np\nimport my_funcs\nimport matplotlib.pylab as plt\nfrom matplotlib.ticker import FormatStrFormatter\nimport dd_20190506 as dd\n# import map_equ_20190429 as equ\n\ndef find_nearest_idx(array, value):\n \"find nearest idx in array for the value\"\n idx = (np.abs(array - value)).argmin()\n return idx\n\n\nEC=ECE.ECE()\n# shot = 37483\nshot = 37203\ntB,tE = 4.05, 4.1\nEC.Load(shot, Diagnostic='RMD', tBegin=tB,tEnd=tE)\nEC.LoadAllRhop()\nEC.freq\n# EC.R[:,idx_chs]\nEC.remove0chs()\nEC.time\nEC.chs_numbers\n\n\n\n\n\"\"\"\ndata = dd.shotfile('RRC', shot, 'AUGD')\n\nrhoNTM = data.getObjectData(b'rhoNTM')\ntime_rhoNTM = data(b'rhoNTM').time\n\nidxNTM_B = find_nearest_idx(time_rhoNTM, tB)\nidxNTM_E = find_nearest_idx(time_rhoNTM, tE)\n\nrhoNTM_t = rhoNTM[idxNTM_B:idxNTM_E+1]\ntime_rhoNTM_t = time_rhoNTM[idxNTM_B:idxNTM_E+1]\n\"\"\"\n\n\nrhop_min = 0.20\nrhop_max = 0.50\n\n# EC.rhop[0,:]\n# EC.rhop <\nidx_rhop = np.where((EC.rhop[0,:] > rhop_min) & (EC.rhop[0,:] < rhop_max))[0]\nchs_to_plot = EC.chs_numbers[idx_rhop]\n# chs_to_plot = np.array([37,38,39,40,41,42])\nremove_chs = [52]\nif remove_chs:\n try:\n idx_to_rem = list(chs_to_plot).index(remove_chs)\n chs_to_plot = np.delete(chs_to_plot, idx_to_rem)\n except:\n print(\"NO channels has been removed\")\n\nidx_chs = np.array([]).astype(int)\nfor i in range(len(chs_to_plot)):\n if chs_to_plot[i] in EC.chs_numbers:\n idx_chs = np.append(idx_chs,list(EC.chs_numbers).index(chs_to_plot[i]))\n\n\n# time_tr, R_tr = np.meshgrid(EC.time, EC.R[0,idx_chs])\ntime_tr, rhop_tr = np.meshgrid(EC.time, EC.rhop[0,idx_chs])\n# EC.Te.shape\nif 1 == 1:\n fig, ax = plt.subplots(figsize=(11, 9),constrained_layout=False)\n contours = ax.contourf(time_tr, rhop_tr, EC.Te[:,idx_chs].T,50,cmap=\"jet\")\n cbar = fig.colorbar(contours, ax=ax)\n cbar.ax.set_ylabel('Trad [eV]', rotation=90)\n\n ax2 = ax.twinx()\n ax2.set_ylim(ax.get_ylim())\n\n t_rhop_plot = EC.time[0]*np.ones(len(EC.rhop[0,idx_chs]))\n ax.plot(t_rhop_plot, EC.rhop[0,idx_chs], \"ko\")\n\n my_text = EC.chs_numbers[idx_chs].copy()\n for i, txt in enumerate(my_text):\n ax.annotate(txt, (t_rhop_plot[i],EC.rhop[0,idx_chs][i]),fontsize=10)\n\n # ax.plot(time_rhoNTM_t, rhoNTM_t, \"bo\")\n\n ax.set_yticks(EC.rhop[0,idx_chs])\n ax2.set_yticks(EC.rhop[0,idx_chs])\n ax.yaxis.set_major_formatter(FormatStrFormatter('%.2f'))\n R_ticks = EC.R[0,idx_chs].copy()\n for i in range(len(R_ticks)):\n R_ticks[i] = round(R_ticks[i],2)\n ax2.set_yticklabels(R_ticks)\n\n\n\n ax.set_xlabel(\"t [s]\")\n ax.set_ylabel(\"rhop\")\n ax2.set_ylabel(\"R [m]\")\n plt.title(\"RMD: Shot #%d\" %(EC.Shotnumber))\n plt.show()\n\nif 1 == 0:\n plt.plot(EC.time,EC.Te)\n plt.title(\"#%g\"%(shot))\n plt.show() \n\nif 1 == 0:\n my_text = EC.chs_numbers.copy()\n for i, txt in enumerate(my_text):\n plt.annotate(txt, (EC.R[1000][i],EC.z[1000][i] +0.001))\n plt.plot(EC.R[1000],EC.z[1000], \"bo\")\n plt.title(\"#%g\"%(shot))\n plt.show() \n\n# t_plot = 2.0 # [s] \n# idx_T = my_funcs.find_nearest_idx(EC.time,t_plot)\n# idx_rz = my_funcs.find_nearest_idx(EC.rztime,t_plot)\n\n# plt.plot(EC.rhop[idx_rz,:], EC.Te[idx_T,:], \"bo\")\n# plt.show()\n\n","sub_path":"python3_projects/ECE/ECE_R_trace.py","file_name":"ECE_R_trace.py","file_ext":"py","file_size_in_byte":3483,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"179597757","text":"import tensorflow as tf\n\ndef get_weight(shape,lamda):\n var = tf.Variable(tf.random_normal(shape),dtype=tf.float32)\n tf.add_to_collection('losses',tf.contrib.layers.l2_regularizer(lamda)(var))\n return var\n\nx = tf.placeholder(tf.float32,shape=(None,2))\ny_ = tf.placeholder(tf.float32,shape=(None,1))\n\ndimension_layer = [2,10,10,10,1]\nlayers = len(dimension_layer)\nbatch_size = 8\n\ncur_layer = x\n# 记录当前层\nin_dimension = dimension_layer[0]\n\n# 循环生成5层神经网络\nfor i in range(1,layers):\n out_dimension = dimension_layer[i]\n weight = get_weight([in_dimension,out_dimension],0.001)\n bias = tf.Variable(tf.constant(0.1,shape=[out_dimension]))\n cur_layer = tf.nn.relu(tf.matmul(cur_layer,weight)+bias)\n in_dimension = dimension_layer[i]\n\nmse_loss = tf.reduce_mean(tf.square(y_-cur_layer))\ntf.add_to_collection('losses',mse_loss)\nloss = tf.add_n(tf.get_collection('losses'))\n\n","sub_path":"learningRate.py","file_name":"learningRate.py","file_ext":"py","file_size_in_byte":910,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"581349248","text":"from torch import nn\nfrom torch.hub import load_state_dict_from_url\nfrom torch.nn import functional as F\n\n# vgg16_cinic10_bn(pretrained=True, num_classes=10)\n\nmodel_urls = {\n \"vgg11\": \"https://download.pytorch.org/models/vgg11-bbd30ac9.pth\",\n \"vgg13\": \"https://download.pytorch.org/models/vgg13-c768596a.pth\",\n \"vgg16\": \"https://download.pytorch.org/models/vgg16-397923af.pth\",\n \"vgg19\": \"https://download.pytorch.org/models/vgg19-dcbb9e9d.pth\",\n \"vgg11_bn\": \"https://download.pytorch.org/models/vgg11_bn-6002323d.pth\",\n \"vgg13_bn\": \"https://download.pytorch.org/models/vgg13_bn-abd245e5.pth\",\n \"vgg16_bn\": \"https://download.pytorch.org/models/vgg16_bn-6c64b313.pth\",\n \"vgg16_cinic10_bn\": \"https://download.pytorch.org/models/vgg16_bn-6c64b313.pth\",\n \"vgg19_bn\": \"https://download.pytorch.org/models/vgg19_bn-c79401a0.pth\",\n}\n\n\nclass VGG(nn.Module):\n \"\"\"VGG with BatchNorm performs best.\n We only add MCDropout in the classifier head (where VGG used dropout before, too).\"\"\"\n\n def __init__(self, features, num_classes=10, init_weights=True, smaller_head=False):\n super().__init__()\n\n self.features = features\n if smaller_head:\n # self.avgpool = nn.Identity()\n self.avgpool = nn.AdaptiveAvgPool2d((1, 1))\n self.classifier = nn.Sequential(\n nn.Dropout(),\n nn.Linear(512 * 1 * 1, 512),\n nn.BatchNorm1d(512),\n nn.ReLU(True),\n nn.Linear(512, num_classes),\n )\n else:\n # self.avgpool = nn.AdaptiveAvgPool2d((7, 7))\n self.avgpool = nn.AdaptiveAvgPool2d((1, 1))\n self.classifier = nn.Sequential(\n # nn.Linear(512 * 7 * 7, 4096),\n nn.Linear(512 * 1 * 1, 4096),\n nn.ReLU(True),\n nn.Dropout(),\n nn.Linear(4096, 4096),\n nn.ReLU(True),\n nn.Dropout(),\n nn.Linear(4096, num_classes),\n )\n\n if init_weights:\n self.apply(self.initialize_weights)\n\n def forward(self, x):\n x = self.features(x)\n x = self.avgpool(x)\n x = x.view(x.size(0), -1)\n x = self.classifier(x)\n x = F.log_softmax(x, dim=1)\n return x\n\n @staticmethod\n def initialize_weights(m):\n if isinstance(m, nn.Conv2d):\n nn.init.kaiming_normal_(m.weight, mode=\"fan_out\", nonlinearity=\"relu\")\n if m.bias is not None:\n nn.init.constant_(m.bias, 0)\n elif isinstance(m, nn.BatchNorm2d):\n nn.init.constant_(m.weight, 1)\n nn.init.constant_(m.bias, 0)\n elif isinstance(m, nn.Linear):\n nn.init.normal_(m.weight, 0, 0.01)\n nn.init.constant_(m.bias, 0)\n\n\ndef make_layers(cfg, batch_norm=False):\n layers = []\n in_channels = 3\n for v in cfg:\n if v == \"M\":\n layers += [nn.MaxPool2d(kernel_size=2, stride=2)]\n elif v == \"D2D_03\":\n pass\n elif v == \"D2D_04\":\n pass # layers += [mc_dropout.MCDropout2d(0.4)]\n else:\n conv2d = nn.Conv2d(in_channels, v, kernel_size=3, padding=1)\n if batch_norm:\n layers += [conv2d, nn.BatchNorm2d(v), nn.ReLU(inplace=True)]\n else:\n layers += [conv2d, nn.ReLU(inplace=True)]\n in_channels = v\n return nn.Sequential(*layers)\n\n\ncfgs = {\n \"A\": [64, \"M\", 128, \"M\", 256, 256, \"M\", 512, 512, \"M\", 512, 512, \"M\"],\n \"B\": [64, 64, \"M\", 128, 128, \"M\", 256, 256, \"M\", 512, 512, \"M\", 512, 512, \"M\"],\n \"D\": [\n 64,\n 64,\n \"M\",\n 128,\n 128,\n \"M\",\n 256,\n 256,\n 256,\n \"M\",\n 512,\n 512,\n 512,\n \"M\",\n 512,\n 512,\n 512,\n \"M\",\n ],\n \"E\": [\n 64,\n 64,\n \"M\",\n 128,\n 128,\n \"M\",\n 256,\n 256,\n 256,\n 256,\n \"M\",\n 512,\n 512,\n 512,\n 512,\n \"M\",\n 512,\n 512,\n 512,\n 512,\n \"M\",\n ],\n}\n\n# def _vgg(cfg, batch_norm, **kwargs):\n# return VGG(make_layers(cfgs[cfg], batch_norm=batch_norm), **kwargs)\ndef _vgg(\n arch,\n cfg,\n batch_norm,\n pretrained,\n progress,\n pretrained_features_only=False,\n **kwargs\n):\n if pretrained:\n kwargs[\"init_weights\"] = False\n model = VGG(make_layers(cfgs[cfg], batch_norm=batch_norm), **kwargs)\n if pretrained:\n state_dict = load_state_dict_from_url(model_urls[arch], progress=progress)\n model.load_state_dict(state_dict)\n if pretrained_features_only:\n state_dict = load_state_dict_from_url(model_urls[arch], progress=progress)\n fixed_state_dict = {\n path[len(\"features.\") :]: state\n for path, state in state_dict.items()\n if \"features.\" in path\n }\n\n model.features.load_state_dict(fixed_state_dict)\n return model\n\n\n# def vgg16_cinic10_bn(**kwargs):\ndef vgg16_cinic10_bn(pretrained=False, progress=True, **kwargs):\n \"\"\"\n VGG 16-layer model (configuration \"D\") with batch normalization\n Inspired by: https://github.com/geifmany/cifar-vgg/blob/master/cifar100vgg.py to follow\n https://ieeexplore.ieee.org/stamp/stamp.jsp?arnumber=7486599 and then gave up on Dropout in Conv layers\n and just used the smaller classifier head and reduced dropout.\n \"\"\"\n # return _vgg(\n # cfg=\"D\",\n # batch_norm=True,\n # smaller_head=True,\n # **kwargs,\n # )\n return _vgg(\n \"vgg16_cinic10_bn\",\n \"D\",\n True,\n progress=progress,\n pretrained_features_only=pretrained,\n pretrained=False,\n smaller_head=True,\n **kwargs,\n )\n","sub_path":"docs/source/experiments/old/model_selection/cifar_sgd/models/vgg.py","file_name":"vgg.py","file_ext":"py","file_size_in_byte":5821,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"83756039","text":"\"\"\"This module implements the computation of the cross-correlograms between\nclusters.\"\"\"\n\n# -----------------------------------------------------------------------------\n# Imports\n# -----------------------------------------------------------------------------\nfrom itertools import product\n\nimport numpy as np\n\nimport kwiklib.utils.logger as log\n\n# Trying to load the Cython version.\ntry:\n from correlograms_cython import compute_correlograms_cython as compute_correlograms\n log.debug((\"Trying to load the compiled Cython version of the correlograms\"\n \"computations...\"))\nexcept Exception as e:\n log.debug(e.message)\n try:\n log.debug((\"failed. Trying to use Cython directly...\"))\n import pyximport; pyximport.install(\n setup_args={'include_dirs': np.get_include()})\n from correlograms_cython import compute_correlograms_cython as compute_correlograms\n except Exception as e:\n log.debug(e.message)\n log.info((\"Unable to load the fast Cython version of the correlograms\"\n \"computations, so falling back to the pure Python version.\")\n )\n\n # Pure Python version.\n # --------------------\n def compute_correlograms(spiketimes, clusters, clusters_to_update=None,\n ncorrbins=None, corrbin=None):\n \n if ncorrbins is None:\n ncorrbins = NCORRBINS_DEFAULT\n if corrbin is None:\n corrbin = CORRBIN_DEFAULT\n \n # Ensure ncorrbins is an even number.\n assert ncorrbins % 2 == 0\n \n # Compute the histogram corrbins.\n # n = int(np.ceil(halfwidth / corrbin))\n n = ncorrbins // 2\n halfwidth = corrbin * n\n \n # size of the histograms\n nspikes = len(spiketimes)\n \n # correlograms will contain all correlograms for each pair of clusters\n correlograms = {}\n\n # unique clusters\n clusters_unique = np.unique(clusters)\n nclusters = len(clusters_unique)\n cluster_max = clusters_unique[-1]\n \n # clusters to update\n if clusters_to_update is None:\n clusters_to_update = clusters_unique\n clusters_mask = np.zeros(cluster_max + 1, dtype=np.bool)\n clusters_mask[clusters_to_update] = True\n \n # initialize the correlograms\n for cl in clusters_to_update:\n for i in clusters_unique:\n correlograms[(cl, i)] = np.zeros(ncorrbins, dtype=np.int32)\n\n # loop through all spikes, across all neurons, all sorted\n for i in range(nspikes):\n t0, cl0 = spiketimes[i], clusters[i]\n # pass clusters that do not need to be processed\n if clusters_mask[cl0]:\n # i, t0, c0: current spike index, spike time, and cluster\n # boundaries of the second loop\n t0min, t0max = t0 - halfwidth, t0 + halfwidth\n j = i + 1\n # go forward in time up to the correlogram half-width\n while j < nspikes:\n t1, cl1 = spiketimes[j], clusters[j]\n # pass clusters that do not need to be processed\n # if clusters_mask[cl1]:\n # compute only correlograms if necessary\n # and avoid computing symmetric pairs twice\n if t1 <= t0max:\n d = t1 - t0\n k = int(d / corrbin) + n\n correlograms[(cl0, cl1)][k] += 1\n else:\n break\n j += 1\n j = i - 1\n # go backward in time up to the correlogram half-width\n while j >= 0:\n t1, cl1 = spiketimes[j], clusters[j]\n # pass clusters that do not need to be processed\n # compute only correlograms if necessary\n # and avoid computing symmetric pairs twice\n if t0min <= t1:\n d = t1 - t0\n k = int(d / corrbin) + n - 1\n correlograms[(cl0, cl1)][k] += 1\n else:\n break\n j -= 1\n # Add the symmetric pairs.\n correlograms.update({(cl1, cl0): correlograms[cl0, cl1][::-1]\n for cl0 in clusters_to_update for cl1 in clusters_unique})\n return correlograms\n\n\n# -----------------------------------------------------------------------------\n# Global variables\n# -----------------------------------------------------------------------------\nNCORRBINS_DEFAULT = 100\nCORRBIN_DEFAULT = .001\n\n\n# -----------------------------------------------------------------------------\n# Computing one correlogram\n# -----------------------------------------------------------------------------\ndef compute_one_correlogram(spikes0, spikes1, ncorrbins, corrbin):\n clusters = np.hstack((np.zeros(len(spikes0), dtype=np.int32),\n np.ones(len(spikes1), dtype=np.int32)))\n spikes = np.hstack((spikes0, spikes1))\n # Indices sorting the union of spikes0 and spikes1.\n indices = np.argsort(spikes)\n C = compute_correlograms(spikes[indices], clusters[indices],\n ncorrbins=ncorrbins, corrbin=corrbin)\n return C[0, 1]\n\n\n# -----------------------------------------------------------------------------\n# Baselines\n# -----------------------------------------------------------------------------\ndef get_baselines(sizes, duration, corrbin):\n baselines = (sizes.reshape((-1, 1)) * sizes.reshape((1, -1)) \n * corrbin / (duration))\n return baselines\n \n ","sub_path":"klustaviewa/stats/correlograms.py","file_name":"correlograms.py","file_ext":"py","file_size_in_byte":6012,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"508863807","text":"\"\"\"\nEnvent Handler\n\"\"\"\nfrom pox.core import core\nimport pox.openflow.libopenflow_01 as of\nfrom pox.lib.util import dpid_to_str\nfrom pox.lib.revent import *\n#from datetime import datetime\nfrom lib import *\nfrom lib.ctl_boot_vMN_func import *\n\nwaitingList = []\nvap1_dpid = None\nvap2_dpid = None\nvmn_dpid = None\n#vap1_ip = None\n#vap2_ip = None\nlog = core.getLogger()\n\nclass ConnectionUp(Event):\n def __init__(self,connection,ofp):\n Event.__init__(self)\n self.connection = connection\n self.dpid = connection.dpid\n self.ofp = ofp\n\nclass ConnectionDown(Event):\n def __init__(self,connection,ofp):\n Event.__init__(self)\n self.connection = connection\n self.dpid = connection.dpid\n\nclass PacketIn(Event):\n def __init__(self,connection,ofp):\n Event.__init__(self)\n self.connection = connection\n self.dpid = connection.dpid \n\nclass MyEvents(object):\n def __init__(self):\n core.openflow.addListeners(self)\n\n def _handle_ConnectionUp(self,event):\n \"\"\"\n on connection up the controller installs a packet in rule on bridges\n \"\"\"\n global vap1_dpid\n global vap2_dpid\n global vmn_dpid\n\n ConnectionUp(event.connection,event.ofp)\n \n event.connection.send( of.ofp_flow_mod( action=of.ofp_action_output( port=10 ), priority=0))\n\n if is_vAP1(event.connection.features.ports): \n vap1_dpid = event.connection.dpid\n # packet_in rule to get vMN ip\n event.connection.send( of.ofp_flow_mod( action=of.ofp_action_output( port=of.OFPP_CONTROLLER ), priority=1,\n match=of.ofp_match( dl_type=0x800, nw_dst=ip_mn2vmn, \n nw_proto = proto_OF, tp_dst = of_port )))\n event.connection.send( of.ofp_flow_mod( action=of.ofp_action_output( port=of.OFPP_CONTROLLER ), priority=2,\n match=of.ofp_match( dl_type=0x800, nw_dst=ip_pkt_in, \n nw_proto = proto_UDP, tp_dst = ho_port )))\n event.connection.send( of.ofp_flow_mod( action=of.ofp_action_output( port=of.OFPP_CONTROLLER ), priority=2,\n match=of.ofp_match( dl_type=0x800, nw_dst=ip_pkt_in2, \n nw_proto = proto_UDP, tp_dst = ho_port )))\n elif is_vAP2(event.connection.features.ports): \n vap2_dpid = event.connection.dpid\n # packet_in rule to get vMN ip\n event.connection.send( of.ofp_flow_mod( action=of.ofp_action_output( port=of.OFPP_CONTROLLER ), priority=1,\n match=of.ofp_match( dl_type=0x800, nw_dst=ip_mn2vmn, \n nw_proto = proto_OF, tp_dst = of_port ))) \n event.connection.send( of.ofp_flow_mod( action=of.ofp_action_output( port=of.OFPP_CONTROLLER ), priority=2,\n match=of.ofp_match( dl_type=0x800, nw_dst=ip_pkt_in, \n nw_proto = proto_UDP, tp_dst = ho_port )))\n event.connection.send( of.ofp_flow_mod( action=of.ofp_action_output( port=of.OFPP_CONTROLLER ), priority=2,\n match=of.ofp_match( dl_type=0x800, nw_dst=ip_pkt_in2, \n nw_proto = proto_UDP, tp_dst = ho_port )))\n elif is_vMN(event.connection.features.ports):\n vmn_dpid = event.connection.dpid\n event.connection.send( of.ofp_flow_mod( action=of.ofp_action_output( port=of.OFPP_CONTROLLER ), priority=2,\n match=of.ofp_match( dl_type=0x800, nw_dst=ip_pkt_in, \n nw_proto = proto_UDP, tp_dst = ho_port )))\n \"\"\"\n event.connection.send( of.ofp_flow_mod( action=of.ofp_action_output( port=outport_vmn_eth0 ), priority=1,\n match=of.ofp_match( dl_type=0x800, nw_dst=cn_ip, \n nw_proto = handoverData[1], tp_dst = handoverData[2] )))\n \"\"\"\n\n def _handle_ConnectionDown(self,event):\n ConnectionDown(event.connection,event.dpid)\n #if is_vMN(event):\n # remove from list\n\n log.info(\"Switch %s DOWN.\",dpid_to_str(event.dpid))\n\n def _handle_PacketIn(self,event):\n global waitingList\n #global vmn_dpid\n #global vap1_ip\n #global vap2_ip\n\n PacketIn(event.connection,event.ofp)\n packet = event.parsed\n packet_in = event.ofp\n #pckin_ip_src = packet.srcip\n dst_port = 6633\n tcpp = event.parsed.find('tcp')\n if tcpp: dst_port = tcpp.dstport \n udpp = event.parsed.find('udp')\n if udpp: dst_port = udpp.dstport \n if packet.type == of.ethernet.IP_TYPE:\n ipv4_packet = event.parsed.find(\"ipv4\")\n\n log.info(\">>> Packet_in <<<\")\n log.debug(\"[MN = %s || AP = %s]\", ipv4_packet.srcip, dpid_to_str(event.dpid))\n log.debug(\"[ br_dpid: %s || src_ip: %s || dst_ip: %s ]\",dpid_to_str(event.dpid),ipv4_packet.srcip,ipv4_packet.dstip)\n if (vmn_dpid != None):\n if ((event.connection.dpid == vmn_dpid) and is_vMNout(ipv4_packet.srcip,ipv4_packet.dstip)):\n return\n if isMobileNode(ipv4_packet.srcip, ipv4_packet.dstip, ipv4_packet.protocol, dst_port):\n if (ipv4_packet.srcip not in waitingList):\n mn_id = get_MNid(ipv4_packet.srcip)\n vmn_ip = get_vMN(mn_id)\n if (vmn_ip == -1):\n waitingList.append(ipv4_packet.srcip)\n create_vMN(ipv4_packet.srcip)\n else:\n #update MNid\n add_vMN(event.connection.dpid, ipv4_packet.srcip, None, ipv4_packet.dstip)\n # AP -> vMN (brid, old_src_ip, old_dst_ip, new_src_ip, new_dst_ip, output_port)\n updateAP_flowtable(vap2_dpid, ipv4_packet.srcip, None, vap2_ip, vmn_ip, outport_ap_eth0)\n # AP -> MN (brid, old_src_ip, old_dst_ip, new_src_ip, new_dst_ip, output_port)\n updateAP_flowtable(vap2_dpid, vmn_ip, vap2_ip, vap2_ip, ipv4_packet.srcip, outport_ap_wlan0)\n elif udpp:\n if is_vMNrequest(ipv4_packet.dstip, ipv4_packet.protocol, dst_port):\n vmn_ip = ipv4_packet.srcip\n # update MN ID\n add_vMN(vmn_dpid, ipv4_packet.srcip, ipv4_packet.dstip, None)\n # AP -> vMN (brid, old_src_ip, old_dst_ip, new_src_ip, new_dst_ip, output_port)\n updateAP_flowtable(vap1_dpid, ipv4_packet.dstip, None, vap1_ip, ipv4_packet.srcip, outport_ap_eth0)\n # AP -> MN (brid, old_src_ip, old_dst_ip, new_src_ip, new_dst_ip, output_port)\n updateAP_flowtable(vap1_dpid, ipv4_packet.srcip, vap1_ip, vap1_ip, ipv4_packet.dstip, outport_ap_wlan0)\n if (ipv4_packet.dstip in waitingList): waitingList.remove(ipv4_packet.dstip)\n\n elif isHandover(ipv4_packet.dstip, ipv4_packet.protocol, dst_port):\n vmn_ip = ipv4_packet.srcip\n #vmn_dpid = event.connection.dpid\n # vMN -> AP2 (brid, old_src_ip, old_dst_ip, new_src_ip, new_dst_ip, protocol, protocol_port, output_port)\n updatevMN_flowtable(vmn_dpid, cn_ip, vmn_ip, vmn_ip, vap2_ip, handoverData[1], handoverData[2],outport_vmn_eth0)\n # vMN -> CN (brid, old_src_ip, old_dst_ip, new_src_ip, new_dst_ip, protocol, protocol_port, output_port)\n updatevMN_flowtable(vmn_dpid, vap2_ip, vmn_ip, vmn_ip, cn_ip, handoverData[1], handoverData[2],outport_vmn_eth0)\n\n elif is_vAPrequest(ipv4_packet.dstip, ipv4_packet.protocol, dst_port):\n advert_vMN(vmn_dpid, packet_in.buffer_id, packet_in.data)\n\n elif is_download(ipv4_packet.dstip, ipv4_packet.protocol, dst_port):\n updatevMN_flowtable(vmn_dpid, cn_ip, vmn_ip, vmn_ip, vap2_ip, handoverData[1], handoverData[2],outport_vmn_eth0)\n updateAP_flowtable(vap2_dpid, vmn_ip, vap2_ip, vap2_ip, ipv4_packet.srcip, outport_ap_wlan0)\n \ndef launch():\n core.registerNew(MyEvents)","sub_path":"HOmngmt4pox/vMN_creation/ctl_boot_vMN.py","file_name":"ctl_boot_vMN.py","file_ext":"py","file_size_in_byte":8022,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"212514675","text":"import gym\nimport os\nimport sys\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom gym import wrappers\nfrom datetime import datetime\nfrom sklearn.pipeline import FeatureUnion\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.kernel_approximation import RBFSampler\n\nclass CartPendulum:\n\tdef __init__(self, m1, m2, l, theta, c1, c2, dt):\n\t\tself.m1 = m1 # cart mass\n\t\tself.m2 = m2 # ball mass\n\t\tself.l = l # pendulum length\n\t\tself.theta = theta # pendulum angle\n\t\tself.theta_dot = 0\n\t\tself.theta_dot_dot = 0\n\t\tself.F = 0 # horizontal force on cart\n\n\t\t# cart\n\t\tself.x1 = 0\n\t\tself.x1_dot = 0\n\t\tself.x1_dot_dot = 0\n\n\t\t# ball\n\t\tself.x2 = l*np.sin(theta)\n\t\tself.y2 = -l*np.cos(theta)\n\t\tself.x2_dot = 0\n\t\tself.y2_dot = 0\n\t\tself.x2_dot_dot = 0\n\t\tself.y2_dot_dot = 0\n\n\t\t# friction coefficients\n\t\tself.c1 = c1 # friction coefficient of cart\n\t\tself.c2 = c2 # friction coefficient of ball\n\n\t\t# others\n\t\tself.g = 9.81 # gravitational acceleration\n\t\tself.dt = dt # update time step\n\n\tdef update(self):\n\t\tself.x1_dot_dot = (self.m2*self.l*self.theta_dot*self.theta_dot*np.sin(self.theta) + self.m2*self.g*np.sin(self.theta)*np.cos(self.theta) + self.F - self.c1*self.x1_dot + self.c2*self.theta_dot*np.cos(self.theta)) / (self.m1 + self.m2*np.sin(self.theta)*np.sin(self.theta))\n\t\tself.theta_dot_dot = (-self.m2*self.l*self.theta_dot*self.theta_dot*np.sin(self.theta)*np.cos(self.theta) - (self.m1 + self.m2)*self.g*np.sin(self.theta) - self.F*np.cos(self.theta) + self.c1*self.x1_dot*np.cos(self.theta) - (1 + self.m1/self.m2)*self.c2*self.theta_dot) / (self.l*(self.m1 + self.m2*np.sin(self.theta)*np.sin(self.theta)))\n\t\tself.x1_dot += self.x1_dot_dot*self.dt\n\t\tself.theta_dot += self.theta_dot_dot*self.dt\n\t\tself.x1 += self.x1_dot*self.dt\n\t\tself.theta += self.theta_dot*self.dt\n\t\tself.x2 = self.x1 + self.l*np.sin(self.theta)\n\t\tself.y2 = -self.l*np.cos(self.theta)\n\n\t\treturn self.x1, self.x2, self.y2\n\n\tdef get_position(self):\n\t\tprint('Cart position: (', self.x1, ', 0)')\n\t\tprint('Bob position: (', self.x2, ', ', self.y2, ')')\n\n\t\treturn self.x1, self.x2, self.y2\n\n\tdef set_force(self, F):\n\t\tself.F = F\n\n\tdef reset(self):\n\t\tm1 = 1.0 # cart mass\n\t\tm2 = 0.8 # bob mass\n\t\tl = 3.0 # link length\n\t\ttheta = 0.4 # initial angle\n\t\tdt = 0.01 # update interval\n\n\t\tself.m1 = m1 # cart mass\n\t\tself.m2 = m2 # ball mass\n\t\tself.l = l # pendulum length\n\t\tself.theta = theta # pendulum angle\n\t\tself.theta_dot = 0\n\t\tself.theta_dot_dot = 0\n\t\tself.F = 0 # horizontal force on cart\n\n\t\t# cart\n\t\tself.x1 = 0\n\t\tself.x1_dot = 0\n\t\tself.x1_dot_dot = 0\n\n\t\t# ball\n\t\tself.x2 = l*np.sin(theta)\n\t\tself.y2 = -l*np.cos(theta)\n\t\tself.x2_dot = 0\n\t\tself.y2_dot = 0\n\t\tself.x2_dot_dot = 0\n\t\tself.y2_dot_dot = 0\n\n\t\tself.dt = dt # update time step\n\nclass TargetSignal:\n\tdef __init__(self, omega, phi, amp, dt):\n\t\tself.omega = omega\n\t\tself.phi = phi\n\t\tself.amp = amp\n\t\tself.x = amp*np.sin(phi)\n\t\tself.dt = dt\n\t\tself.t = 0.0\n\n\tdef update(self):\n\t\tself.t += self.dt\n\t\tself.x = self.amp*np.sin(self.omega*self.t+self.phi)\n\t\treturn self.x\n\n\tdef get_position(self):\n\t\tprint('Target signal position: (', self.x, ', -5.0)')\n\t\treturn self.x\n\n\tdef reset(self):\n\t\tomega = 1.0\n\t\tphi = 0.0\n\t\tamp = 1.0\n\t\tdt = 0.01\n\t\tself.omega = omega\n\t\tself.phi = phi\n\t\tself.amp = amp\n\t\tself.x = amp*np.sin(phi)\n\t\tself.dt = dt\n\t\tself.t = 0.0\n\nclass System:\n\tdef __init__(self, cartpendulum, targetsignal):\n\t\tself.cartpendulum = cartpendulum\n\t\tself.targetsignal = targetsignal\n\t\tself.action_space_n = 4\n\n\tdef update(self):\n\t\tself.cartpendulum.update()\n\t\tself.targetsignal.update()\n\n\tdef reset(self):\n\t\tself.cartpendulum.reset()\n\t\tself.targetsignal.reset()\n\nclass SGDRegressor:\n\tdef __init__(self, D):\n\t\tself.w = np.random.randn(D) / np.sqrt(D)\n\t\tself.lr = 10e-2\n\n\tdef partial_fit(self, X, Y):\n\t\tself.w += self.lr*(Y - X.dot(self.w)).dot(X)\n\n\tdef predict(self, X):\n\t\treturn X.dot(self.w)\n\nclass FeatureTransformer:\n\tdef __init__(self):\n\t\tobservation_examples = np.random.random((20000, 4))*2 -1\n\t\tscaler = StandardScaler()\n\t\tscaler.fit(observation_examples)\n\n\t\tfeaturizer = FeatureUnion([\n\t\t\t(\"rbf1\", RBFSampler(gamma=2.00, n_components=1000)),\n\t\t\t(\"rbf2\", RBFSampler(gamma=1.00, n_components=1000)),\n\t\t\t(\"rbf3\", RBFSampler(gamma=0.50, n_components=1000)),\n\t\t\t(\"rbf4\", RBFSampler(gamma=0.20, n_components=1000)),\n\t\t\t])\n\t\tfeature_examples = featurizer.fit_transform(scaler.transform(observation_examples))\n\n\t\tself.dimensions = 4\n\t\tself.scaler = scaler\n\t\tself.featurizer = featurizer\n\n\tdef transform(self, observations):\n\t\tscaled = self.scaler.transform(observations)\n\t\treturn self.featurizer.transform(scaled)\n\nclass Model:\n\tdef __init__(self, env, feature_transformer):\n\t\tself.env = env\n\t\tself.models = []\n\t\tself.feature_transformer = feature_transformer\n\t\tfor i in range(env.action_space_n):\n\t\t\tmodel = SGDRegressor(feature_transformer.dimensions)\n\t\t\tself.models.append(model)\n\n\tdef predict(self, s):\n\t\tX = self.feature_transformer.transform(np.atleast_2d(s))\n\t\treturn np.array([m.predict(X)[0] for m in self.models])\n\n\tdef update(self, s, a, G):\n\t\tX = self.feature_transformer.transform(np.atleast_2d(s))\n\t\tself.models[a].partial_fit(X, [G])\n\n\tdef sample_action(self, s, eps):\n\t\tif np.random.random() < eps:\n\t\t\treturn self.env.action_space.sample()\n\t\telse:\n\t\t\treturn np.argmax(self.predict(s))\n\ndef play_one(env, model, eps, gamma):\n\tobservation = env.reset()\n\tdone = False\n\ttotalreward = 0\n\titers = 0\n\twhile not done and iters < 2000:\n\t\taction = model.sample_action(observation, eps)\n\t\tprev_observation = observation\n\t\tobservation, reward, done, info = env.step(action)\n\n\t\tif done:\n\t\t\treward = -200\n\n\t\tnext = model.predict(observation)\n\t\tassert(len(next.shape) == 1)\n\t\tG = reward + gamma*np.max(next)\n\t\tmodel.update(prev_observation, action, G)\n\n\t\tif reward == 1:\n\t\t\ttotalreward += reward\n\t\titers += 1\n\n\treturn totalreward\n\ndef plot_running_average(totalrewards):\n\tN = len(totalrewards)\n\trunning_average = np.empty(N)\n\tfor t in range(N):\n\t\trunning_average[t] = totalrewards[max(0, t-100):(t)].mean()\n\tplt.plot(running_average)\n\tplt.title(\"Running Average\")\n\tplt.show()\n\ndef main():\n\t# cart-pendulum parameters\n\tcart_m = 1.0 # cart mass\n\tbob1_m = 0.8 # bob mass\n\tbob1_l = 3.0 # link length\n\tbob1_theta = 0.4 # initial angle\n\tcart_fric = 0.5 # cart friction coefficient\n\tbob1_fric = 0.5 # pendulum friction coefficient\n\tdt = 0.01 # update interval\n\n\t# target signal parameters\n\tbob1_omega = 1.0\n\tbob1_phi = 0.0\n\tbob1_amp = 1.0\n\n\t# create a system of cart-pendulum and target signal\n\tcartpendulum = CartPendulum(cart_m, bob1_m, bob1_l, bob1_theta, cart_fric, bob1_fric, dt)\n\ttargetsignal = TargetSignal(bob1_omega, bob1_phi, bob1_amp, dt)\n\tsystem = System(cartpendulum, targetsignal)\n\n\t# create a feature transformer\n\tft = FeatureTransformer()\n\tmodel = Model(system, ft)\n\tgamma = 0.99\n\n\t# if 'monitor' in sys.argv:\n\t# \tfilename = os.path.basename(__file__).split('.')[0]\n\t# \tmonitor_dir = './' + filename + '_' + str(datetime.now())\n\t# \tenv = wrappers.Monitor(env, monitor_dir)\n\n\tN = 500\n\ttotalrewards = np.empty(N)\n\tcosts = np.empty(N)\n\tfor n in range(N):\n\t\teps = 1.0/np.sqrt(n+1)\n\t\ttotalreward = play_one(env, model, eps, gamma)\n\t\ttotalrewards[n] = totalreward\n\t\tif n % 100 == 0:\n\t\t\tprint(\"episode:\", n, \"total reward:\", totalreward, \"eps:\", eps, \"avg reward (last 100):\", totalrewards[max(0, n-100):(n+1)].mean())\n\n\tprint(\"avg reward for last 100 episodes:\", totalrewards[-100:].mean())\n\tprint(\"total steps:\", totalrewards.sum())\n\n\tplt.plot(totalrewards)\n\tplt.title(\"Rewards\")\n\tplt.show()\n\n\tplot_running_avg(totalrewards)\n\nif __name__ == '__main__':\n\tmain()","sub_path":"test01_cartpendulum/t09_cartpole_qlearning.py","file_name":"t09_cartpole_qlearning.py","file_ext":"py","file_size_in_byte":7491,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"465577980","text":"# -*- encoding: utf-8 -*-\n\"\"\"Routines and classes to control the overall build-system generation.\n\"\"\"\n\nimport sys\nimport os\nimport itertools\nfrom signal import signal, SIGTERM, SIGHUP, SIG_DFL\nimport logging\nimport argparse\nfrom contextlib import contextmanager\nimport operator\nimport shlex\nimport re\nimport subprocess\n\nfrom samurai import config\nfrom samurai._dumper import NinjaDumper\nfrom samurai._eval import Evaluator\nfrom samurai._eval import Context\nfrom samurai.command import Command\nfrom samurai.utils import TimeWatch\nfrom samurai._misc import signame\nimport samurai.sys as samurai_sys\nfrom samurai._log import init_logger\nfrom samurai._log import get_log_level_from_env\nfrom samurai.statement import ConsolePool\nfrom samurai.utils import get_ninja\nfrom samurai.utils import rm_f\nfrom samurai.utils import rmdir_p\n\nLOGGER = logging.getLogger(__name__)\n\nclass AutoRegen(Command):\n \"\"\"The rule to automatically re-generate the build manifest.\n\n This command is automatically added to the manifest by the generator.\n Thus, users are not supposed to use it.\n \"\"\"\n\n samurai_path = config.ROOT_PATH\n rel_build_dir = shlex.quote(os.getenv(\"SAMURAI_TOP_BUILD_DIR\", \"\"))\n command = \"PYTHONPATH=\\\"{samurai_path}:$PYTHONPATH\\\" \"\\\n \"SAMURAI_TOP_BUILD_DIR={rel_build_dir} \"\\\n \"python3 -m samurai._generator \"\\\n \"{i@manifest} {build_dir}\"\n description = \"Re-generating from {manifest}\"\n generator = True\n pool = ConsolePool\n\n def __init__(self, manifest, build_dir, context, evaluator):\n implicit_inputs = frozenset(itertools.chain(\n config.INTERNAL_SOURCES,\n evaluator.read_files,\n evaluator.imported_files))\n implicit_outputs = frozenset(itertools.chain(\n evaluator.written_files,\n [os.path.join(build_dir, config.BUILD_FILENAME)]))\n # Order only dependencies on sub-generators is important\n # here otherwise one several autoregen rules are triggered\n # subgenerators autoregen rule may not be run during the\n # manifest rebuild phase and thus run in the middle of\n # their own command.\n orderonly_inputs = tuple(map(operator.attrgetter(\"output\"),\n context.subgenerators))\n super().__init__(manifest=manifest,\n build_dir=build_dir,\n implicit_inputs=implicit_inputs,\n implicit_outputs=implicit_outputs,\n orderonly_inputs=orderonly_inputs)\n\nclass _TerminationLog(object):\n\n def __init__(self, dumper):\n self.time_watch = TimeWatch()\n self.dumper = dumper\n\n def __enter__(self):\n self.time_watch.start()\n return self\n\n def __exit__(self, exc_type, exc_value, traceback):\n self.time_watch.stop()\n if exc_type is not None:\n if issubclass(exc_type, SystemExit):\n LOGGER.error(\"generation stopped prematurely with code %d\",\n exc_value.code)\n elif issubclass(exc_type, KeyboardInterrupt):\n LOGGER.error(\"generation interrupted by user\")\n elif issubclass(exc_type, Exception):\n LOGGER.error(\"uncaught exception while generating\")\n LOGGER.info(\"%d build, %d rule, %d sub-generator\",\n self.dumper.build_count,\n self.dumper.rule_count,\n self.dumper.subgenerator_count)\n LOGGER.info(\"generation done in %s\", self.time_watch.stats)\n return False # Tell to re-raise the exception if there was one.\n\nclass Generator(object):\n \"\"\"Generate the overall build-system.\n\n A generator tight together an Evaluator and a Dumper.\n \"\"\"\n\n GENERATING_FILENAME = \".samurai_generating\"\n\n def __init__(self, manifest, build_dir):\n self.manifest = os.path.realpath(manifest)\n self.build_dir = os.path.realpath(build_dir)\n\n @property\n def output(self):\n return os.path.join(self.build_dir, config.BUILD_FILENAME)\n\n def generate(self):\n samurai_sys.build_dir = self.build_dir\n samurai_sys.output = self.output\n top_build_dir = os.getenv(\"SAMURAI_TOP_BUILD_DIR\")\n dumper = NinjaDumper(self.build_dir, top_build_dir=top_build_dir)\n with _rm_abandoned_outputs(self.output, top_build_dir=top_build_dir), \\\n _TerminationLog(dumper), \\\n _install_sighandlers(_on_interrupt, SIGTERM, SIGHUP), \\\n dumper:\n context = Context(dumper)\n samurai_sys.context = context\n evaluator = Evaluator(self.manifest)\n evaluator.evaluate()\n dumper.dump(AutoRegen(self.manifest, self.build_dir,\n context, evaluator))\n\n def should_generate(self, force):\n if force:\n return \"-f/--force is passed\"\n if not os.path.exists(self.output):\n return \"build.ninja file does not exists\"\n return None\n\n def maybe_generate(self, force=False):\n reason = self.should_generate(force)\n if reason:\n LOGGER.info(\"generating because %s\", reason)\n self.generate()\n else:\n LOGGER.info(\"skip unnecessary generation ; \"\n \"use -f/--force to force it\")\n\ndef _yield_ninja_targets_all(build_dir):\n proc = subprocess.Popen(\n (get_ninja(), \"-C\", str(build_dir), \"-t\", \"targets\", \"all\"),\n stdin=None,\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE,\n universal_newlines=True)\n for line in proc.stdout.readlines():\n yield line\n proc.wait()\n if proc.returncode != 0:\n raise RuntimeError(\"cannot list targets from build directory '{}':\\n{}\"\n .format(build_dir, proc.stderr.read().rstrip()))\n\ndef _get_all_ninja_outputs(build_dir, top_build_dir=None):\n rel_dir = build_dir if top_build_dir is None else top_build_dir\n targets = set()\n rx = re.compile(r\"^(.*): .*$\")\n for line in _yield_ninja_targets_all(build_dir):\n mo = rx.match(line)\n if not mo:\n raise RuntimeError(\"cannot get target from line: {!r}\"\n .format(line))\n output = mo.group(1)\n if not os.path.isabs(output):\n output = os.path.join(rel_dir, output)\n targets.add(output)\n return targets\n\ndef _rm_abandoned_outputs_list(filelist):\n dirs = set()\n for path in filelist:\n LOGGER.info(\"remove abandoned output: '%s'\", path)\n rm_f(path)\n dirs.add(os.path.dirname(path))\n for d in dirs:\n rmdir_p(d)\n\n@contextmanager\ndef _rm_abandoned_outputs(build_ninja_file, top_build_dir=None):\n build_dir = os.path.dirname(build_ninja_file)\n if os.path.exists(build_ninja_file):\n old_outputs = _get_all_ninja_outputs(build_dir, top_build_dir)\n else:\n old_outputs = None\n try:\n yield\n finally:\n if old_outputs is not None:\n new_outputs = _get_all_ninja_outputs(build_dir, top_build_dir)\n _rm_abandoned_outputs_list(set(old_outputs) - set(new_outputs))\n\n@contextmanager\ndef _install_sighandlers(handler, *signums):\n for signum in signums:\n signal(signum, handler)\n try:\n yield\n finally:\n for signum in signums:\n signal(signum, SIG_DFL)\n\ndef _on_interrupt(signum, frame):\n LOGGER.fatal(\"interrupted by %s\", signame(signum))\n sys.exit(2)\n\ndef _autoregen_cli():\n \"\"\"Internal Samurai CLI of the autoregen mode.\n \"\"\"\n parser = argparse.ArgumentParser(\n description=_autoregen_cli.__doc__,\n formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n parser.add_argument(\n \"manifest\",\n action=\"store\",\n help=\"Input manifest file.\")\n parser.add_argument(\n \"build_dir\",\n metavar=\"DIR\",\n action=\"store\",\n help=\"Directory where to generate the build-system.\")\n return parser\n\ndef _autoregen_main(argv):\n cli = _autoregen_cli()\n options = cli.parse_args(argv[1:])\n init_logger(get_log_level_from_env())\n samurai_sys.autoregen = True\n generator = Generator(options.manifest, options.build_dir)\n generator.generate()\n return 0\n\nif __name__ == \"__main__\":\n sys.exit(_autoregen_main(sys.argv))\n","sub_path":"samurai/_generator.py","file_name":"_generator.py","file_ext":"py","file_size_in_byte":8346,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"298048082","text":"def subsetsWithDup_iterative(S):\n res = [[]]\n S.sort()\n for i in range(len(S)):\n if i == 0 or S[i] != S[i - 1]:\n l = len(res)\n for j in range(len(res) - l, len(res)):\n res.append(res[j] + [S[i]])\n return res\n\n\ndef subsetsWithDup_recursive(nums):\n res = []\n nums.sort()\n helper(nums, 0, [], res)\n return res\ndef helper(nums, index, path, res):\n res.append(path)\n for i in range(index, len(nums)):\n if i > index and nums[i] == nums[i - 1]:\n continue\n helper(nums, i + 1, path + [nums[i]], res)\na = [2,1,2]\n\nprint(subsetsWithDup_iterative(a))\nprint(subsetsWithDup_recursive(a))","sub_path":"LeetCode/Arrays/subsets_ii.py","file_name":"subsets_ii.py","file_ext":"py","file_size_in_byte":665,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"334904758","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport sys\n\nsys.path.append(\"..\")\nfrom funciones import fechas, find_nearest_inicial, find_nearest_final, tiempos\n\n\"\"\"\nHace la fig2 del poster de la AGU2019, que es una proyección en 2D de la órbita\n\"\"\"\n\n\ndef datos():\n year, month, day, doy = fechas()\n ti, tf = tiempos()\n # path = f'../../../datos/clweb/{year}-{month}-{day}/' #path a los datos desde la laptop\n path = f\"../../../../../media/gabybosc/datos/clweb/{year}-{month}-{day}/\"\n mag = np.loadtxt(path + \"MAG.asc\")\n\n M = len(mag[:, 0]) # el numero de datos\n\n hh = mag[:, 3]\n mm = mag[:, 4]\n ss = mag[:, 5]\n\n t = hh + mm / 60 + ss / 3600 # hdec\n t_utc = [f\"{int(hh[j])}:{int(mm[j])}\" for j in range(len(t))]\n\n posicion = np.zeros((M, 3))\n for i in range(9, 12):\n posicion[:, i - 9] = mag[:, i] / 3390\n\n inicio = np.where(t == find_nearest_inicial(t, ti))[0][0]\n fin = np.where(t == find_nearest_final(t, tf))[0][0]\n\n posicion_cut = posicion[inicio:fin, :]\n t_cut = t[inicio:fin]\n\n return (t_cut, posicion_cut, year, month, day)\n\n\ndef datos_fijos(year, month, day, ti, tf):\n # path a los datos desde la laptop\n path = f\"../../../datos/clweb/{year}-{month}-{day}/\"\n mag = np.loadtxt(path + \"MAG.asc\")\n\n M = len(mag[:, 0]) # el numero de datos\n\n hh = mag[:, 3]\n mm = mag[:, 4]\n ss = mag[:, 5]\n\n t = hh + mm / 60 + ss / 3600 # hdec\n t_utc = [f\"{int(hh[j])}:{int(mm[j])}\" for j in range(len(t))]\n\n posicion = np.zeros((M, 3))\n for i in range(9, 12):\n posicion[:, i - 9] = mag[:, i] / 3390\n\n inicio = np.where(t == find_nearest_inicial(t, ti))[0][0]\n fin = np.where(t == find_nearest_final(t, tf))[0][0]\n\n posicion_cut = posicion[inicio:fin, :]\n t_cut = t[inicio:fin]\n\n return (t_cut, posicion_cut, year, month, day)\n\n\ndef BS_MPB(L, e, x0):\n THETA = np.linspace(0, np.pi * 3 / 4, 100)\n PHI = np.linspace(0, 2 * np.pi, 100)\n\n r1 = L / (1 + e * np.cos(THETA))\n\n X1 = x0 + r1 * np.cos(THETA)\n Y1 = r1 * np.sin(THETA) * np.cos(PHI)\n Z1 = r1 * np.sin(THETA) * np.sin(PHI)\n yz = np.sqrt(Y1**2 + Z1**2)\n return (X1, yz)\n\n\ndef marte(x_bs, yz_bs, x_mpb, yz_mpb):\n fig, ax = plt.subplots()\n ax.plot()\n ax.plot(x_bs, yz_bs, color=\"#07aec7\", linestyle=\"-.\")\n ax.plot(x_mpb, yz_mpb, color=\"#FF1493\", linestyle=\"-.\")\n ax.axis(\"equal\")\n ax.set_xlim(0, 3)\n ax.set_ylim(0, 2.5)\n circle = plt.Circle((0, 0), 1, color=\"#c1440e\", clip_on=True)\n ax.add_artist(circle)\n ax.set_title(\"MAVEN MSO coordinates\", fontsize=16)\n ax.set_xlabel(r\"$X_{MSO}$ ($R_M$)\", fontsize=14)\n ax.set_ylabel(r\"$(Y²_{MSO} + Z²_{MSO} )^{1/2}$ ($R_M$)\", fontsize=14)\n\n\ndef orbitas(posicion, year, month, day):\n x = posicion[:, 0]\n y = posicion[:, 1]\n z = posicion[:, 2]\n proyeccion = np.sqrt(y**2 + z**2)\n fig = plt.gcf()\n ax = fig.gca()\n ax.plot(x, proyeccion, label=f\"{day}-{month}-{year}\")\n\n\nx_bs, yz_bs = BS_MPB(2.04, 1.03, 0.64)\nx_mpb, yz_mpb = BS_MPB(0.96, 0.9, 0.78)\nmarte(x_bs, yz_bs, x_mpb, yz_mpb)\n\n\n# t, posicion_cut, year, month, day = datos()\n# t, posicion_cut, year, month, day = datos_fijos(2015, 10, 10, 12, 13)\n# orbitas(posicion_cut, year, month, day)\n\n# t, posicion_cut, year, month, day = datos_fijos(2015, 10, 12, 18.75, 19.75)\n# orbitas(posicion_cut, year, month, day)\n\nt, posicion_cut, year, month, day = datos_fijos(2016, \"03\", 16, 17.5, 18.5)\norbitas(posicion_cut, year, month, day)\n\n# t, posicion_cut, year, month, day = datos_fijos(2016, \"03\", 31, 12.5, 13.5)\n# orbitas(posicion_cut, year, month, day)\n\n# t, posicion_cut, year, month, day = datos_fijos(2016, \"04\", \"05\", 16, 17)\n# orbitas(posicion_cut, year, month, day)\n\n# t, posicion_cut, year, month, day = datos_fijos(2017, 11, 24, 12, 13)\n# orbitas(posicion_cut, year, month, day)\n\nplt.legend()\nplt.show(block=False)\n# plt.savefig(\"../outputs/figs_MPB/Orbitas.png\", dpi=200)\n","sub_path":"clweb/plot_orbitas.py","file_name":"plot_orbitas.py","file_ext":"py","file_size_in_byte":3917,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"198356433","text":"#!/bin/python3\r\n\r\nimport sys\r\nliste=[]\r\ndef solve(grades):\r\n for i in grades:\r\n if (i+2)%5==0 and i>35:\r\n ind=grades.index(i)\r\n del grades[ind]\r\n grades.insert(ind,i+2)\r\n\r\n elif (i+1)%5==0 and i>35:\r\n ind=grades.index(i)\r\n del grades[ind]\r\n grades.insert(ind,i+1)\r\n\r\n\r\n else:\r\n ind=grades.index(i)\r\n del grades[ind]\r\n grades.insert(ind,i)\r\n\r\n return grades\r\nn = int(input().strip())\r\ngrades = []\r\ngrades_i = 0\r\nfor grades_i in range(n):\r\n grades_i = int(input().strip())\r\n grades.append(grades_i)\r\nresult = solve(grades)\r\nprint (\"\\n\".join(map(str, result)))\r\n\r\n","sub_path":"HackerRank/Algorithm/grading_students.py","file_name":"grading_students.py","file_ext":"py","file_size_in_byte":691,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"436322179","text":"#!/usr/bin/env python3\n\n# Copyright 2014 Brett Slatkin, Pearson Education Inc.\n#\n# Udostępniono na licencji Apache w wersji 2.0 (\"Licencja\").\n# Tego pliku można używać jedynie zgodnie z warunkami Licencji.\n# Treść Licencji znajdziesz na stronie:\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# O ile obowiązujące prawo nie stanowi inaczej lub czegoś innego nie\n# uzgodniono w formie pisemnej, oprogramowanie objęte Licencją jest\n# dostarczane w stanie, w jakim jest (wersja \"AS IS\"), BEZ JAKIEJKOLWIEK\n# GWARANCJI, ani wyrażonej otwarcie, ani domyślnej. Dokładne zasady\n# i warunki Licencji znajdziesz w jej treści.\n\n# Przygotowania mające na celu odtworzenie środowiska użytego w książce.\nimport logging\nfrom pprint import pprint\nfrom sys import stdout as STDOUT\n\n\n# Przykład 1.\nfrom urllib.parse import parse_qs\nmy_values = parse_qs('red=5&blue=0&green=',\n keep_blank_values=True)\nprint(repr(my_values))\n\n\n# Przykład 2.\nprint('Czerwony: ', my_values.get('red'))\nprint('Zielony: ', my_values.get('green'))\nprint('Krycie: ', my_values.get('opacity'))\n\n\n# Przykład 3.\n# Dla ciągu tekstowego zapytania'red=5&blue=0&green='\nred = my_values.get('red', [''])[0] or 0\ngreen = my_values.get('green', [''])[0] or 0\nopacity = my_values.get('opacity', [''])[0] or 0\nprint('Czerwony: %r' % red)\nprint('Zielony: %r' % green)\nprint('Krycie: %r' % opacity)\n\n\n# Przykład 4.\nred = int(my_values.get('red', [''])[0] or 0)\ngreen = int(my_values.get('green', [''])[0] or 0)\nopacity = int(my_values.get('opacity', [''])[0] or 0)\nprint('Czerwony: %r' % red)\nprint('Zielony: %r' % green)\nprint('Krycie: %r' % opacity)\n\n\n# Przykład 5.\nred = my_values.get('red', [''])\nred = int(red[0]) if red[0] else 0\ngreen = my_values.get('green', [''])\ngreen = int(green[0]) if green[0] else 0\nopacity = my_values.get('opacity', [''])\nopacity = int(opacity[0]) if opacity[0] else 0\nprint('Czerwony: %r' % red)\nprint('Zielony: %r' % green)\nprint('Krycie: %r' % opacity)\n\n\n# Przykład 6.\ngreen = my_values.get('green', [''])\nif green[0]:\n green = int(green[0])\nelse:\n green = 0\nprint('Zielony: %r' % green)\n\n\n# Przykład 7.\ndef get_first_int(values, key, default=0):\n found = values.get(key, [''])\n if found[0]:\n found = int(found[0])\n else:\n found = default\n return found\n\n\n# Przykład 8.\ngreen = get_first_int(my_values, 'green')\nprint('Zielony: %r' % green)\n","sub_path":"Python/Python - efektywny Python/item_04.py","file_name":"item_04.py","file_ext":"py","file_size_in_byte":2420,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"496006552","text":"\n'''\n\nThis code extracts only the nouns from the crawled articles\nusing the Korean morpheme Mecab and saves them as text files.\n\n'''\n\nfrom konlpy.tag import Mecab\nmc = Mecab()\n\ndef pos_tag():\n articles = []\n articles_nng = []\n fname = []\n for i in range(1350,12213):\n try:\n with open('./DATA/article/article_%s_dongA.txt' % (i)) as f:\n articles.append(f.readlines())\n fname.append(\"article_%s_dongA.txt\"%(i))\n except:\n continue\n for i in range(len(fname)):\n a_nng = []\n articles[i] = mc.pos(articles[i][0])\n\n for j in range(len(articles[i])):\n if articles[i][j][1]=='NNG':\n a_nng.append(articles[i][j][0])\n else:\n continue\n articles[i] = a_nng\n with open('./DATA/article_nng/%s'%(fname[i]),'w') as f:\n for text in articles[i]:\n f.writelines(text)\n f.write('\\n')\n print('saved %s completely!'%(i+1350))\n\n# run\n\npos_tag()","sub_path":"POS TAGGING_dongA.py","file_name":"POS TAGGING_dongA.py","file_ext":"py","file_size_in_byte":1035,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"123968763","text":"#!/usr/bin/env python\n#https://docs.python.org/3/howto/curses.html\n#https://docs.python.org/2/library/curses.html\n\nimport curses #python -m pip install windows-curses\n#import curses.textpad\n#import time\n\nstdscr = curses.initscr()\n#curses.noecho() #To turn off mirroring pressed keys\n#curses.echo()\n\nGRAY_BASE = 15 #15 is max color without error\nGRAY_pair = 50\nRED_pair = 40\n\ncurses.start_color()\nstdscr.addstr(\"Type q to exit \", curses.color_pair(1)) #by default all color pares are default \nstdscr.addstr(\"Type p to print string, and c to print char \", curses.color_pair(1)) #by default all color pares are default \nstdscr.addstr(\"Type s to supress display pressed buttons\", curses.color_pair(1)) #by default all color pares are default \n\n\ncurses.init_color( GRAY_BASE, 500, 500, 500 ) #color (0-15), R,G,B (0-1000)\ncurses.init_pair( GRAY_pair, GRAY_BASE, curses.COLOR_BLACK )\nstdscr.addstr(2,0, \"RED ALERT!\", curses.color_pair(GRAY_pair))\n\ncurses.init_pair( RED_pair, GRAY_BASE, curses.COLOR_RED )\nstdscr.addstr(3,0, \"RED ALERT! 2\", curses.color_pair(RED_pair))\n\ncurses.curs_set(0) #make cursor invisible\n\n#Applications will also commonly need to react to keys instantly, without requiring the Enter key to be pressed;\n# this is called cbreak mode, as opposed to the usual buffered input mode.\n#curses.cbreak()\n\n#begin_x = 20\n#begin_y = 7\n#height = 5\n#width = 40\n#win = curses.newwin(height, width, begin_y, begin_x)\n#tb = curses.textpad.Textbox(win)\n#text = tb.edit()\nstdscr.addstr(8,1,'initial')#text.encode('utf_8')\n\n#hw = \"Hello world!\"\n\nwHeight= 8\nwWidth =40\nbegY = 4\nbegX = 20\nwin = curses.newpad(wHeight*10, wWidth) #newwin is fixed and gives err if text is bigger than window\n\ni = 0\nwhile 1:\n c = stdscr.getch()\n if c == ord('o'):\n win.addstr(f'{i}some Str ')\n \n win.refresh(i //20, 0, begY, begX, begY+wHeight, begX+wWidth) #[PadStartRow, PadStartCol, DispStartRow, DispStartcol, DispEndRow, DispEndCol]\n #if window is not a pad, just windowwin.refresh()\n i+=1\n elif c == ord('c'):\n win.clear()\n i=0\n win.refresh(i //20, 0, begY, begX, begY+wHeight, begX+wWidth)\n elif c == ord('s'):\n stdscr.addch(1,20,curses.ACS_HLINE)\n stdscr.addch(2,20,curses.ACS_PLUS)\n stdscr.addch(3,20,curses.ACS_LRCORNER)\n stdscr.addch(4,20,curses.ACS_DARROW)\n \n stdscr.addch(5,20,curses.ACS_LARROW)\n stdscr.addch(5,21,curses.ACS_LRCORNER)\n elif c == ord('p'):\n stdscr.addstr(10 +(i*2), 30, 'hel_\\u21B2_lo')\n stdscr.addstr(10 +(i*2), 40, 'При\\nвет')\n i+=1\n elif c == ord('c'):\n stdscr.addch('H')\n elif c == ord('s'):\n curses.noecho()\n elif c == ord('q'): break # Exit the while()\n elif c == curses.KEY_HOME: x = y = 0\n\ncurses.endwin()\n\n","sub_path":"025consoleNCurses.py","file_name":"025consoleNCurses.py","file_ext":"py","file_size_in_byte":2797,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"590241344","text":"#-*-coding:utf-8-*-\n#三根等长的绳子,折成两个长方形和一个正方形,各边长均为整数,求两个长方形面积和等于正方形的折叠方法数量,绳子长度从1-500,且等比例的算一种\n#例如20 1*9 2*8 5*5 40 2*18 4*16 10*10\nimport exetime\n\n@exetime.ExeTime\ndef solution():\n result = list()\n for i in range(0,501):\n result.append(0)\n for c in range(4,501,4): #由于正方形边长为整数-->周长为4的倍数\n result[c] = 0\n Ssquare = (c/4)*(c/4)\n for j in range(1,int(c/4)): #长方形边长关系 c/4-x 和 c/4+x\n Srectangle = (c/4-j)*(c/4+j)\n for k in range(1,int(c/4)):\n Srectangle2 = (c/4-k)*(c/4+k)\n if(Ssquare==Srectangle+Srectangle2):\n result[c]+=1\n return result\n\ndef Summary(arr):\n dic = dict()\n for i in range(len(arr)):\n if(arr[i]!=0):\n dic[i] = int(arr[i]/2)\n return dic\n\ndef DelRepeate(dic):\n keys = list(dic.keys())\n for i in keys:\n for j in range(2,int(keys[-1]/i)+1):\n if(i*j in keys):\n dic[i*j]=dic[i*j]-dic[i]\n return dic\ndef SumNum(dic):\n sum = 0\n for i in dic.values():\n sum += i\n return sum\n\n\n#数学方法\n# 设正方形边长为c \n#设第一条绳子S1=(c-a)(c+a)=c2-a2 ---> 同理推出第二条 c2-b2 当长方形和等于正方形时满足则满足条件 a2+b2=c2\n#假设出现同比整数倍情况则由上一条内容可推出a和b存在公约数故非同比整数倍则a和b约数为1\n\n\ndef GCD(a,b): #Greatest Common Divisor\n if(aresource quota<\\/a>\",\n r\"[resource quota](https://cloud.google.com/compute/docs/resource-quotas)\")\n\ns.replace(\"src/v1/doc/google/container/v1/doc_cluster_service.js\",\n \"https:\\/\\/cloud\\.google\\.com\\/kubernetes-engine\\/docs\\/reference\\/rest\\/v1\\/projects\\.zones\\.clusters\\.nodePool\",\n \"https://cloud.google.com/kubernetes-engine/docs/reference/rest/v1/projects.zones.clusters.nodePools#resource-nodepool\")\n\n# Node.js specific cleanup\nsubprocess.run(['npm', 'install'])\nsubprocess.run(['npm', 'run', 'fix'])\n","sub_path":"synth.py","file_name":"synth.py","file_ext":"py","file_size_in_byte":1192,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"294084979","text":"\nadj_list_graph = []\nvisited = []\npath = []\ndef main():\n global adj_list_graph, visited, path\n n = int(input())\n while n:\n v = int(input())\n adj_list_graph = [[] for _ in range(v)]\n visited = [False] * v\n for _ in range(v):\n input_graph = list(map(int, input().split(' ')))\n current_vertex = input_graph.pop(0)\n [adj_list_graph[current_vertex-1].append(adj_vertex) for adj_vertex in input_graph]\n dfs(0) # 1 is the start node\n print(path)\n # reset the relevant variables\n visited = []\n adj_list_graph = []\n path = []\n n -= 1\n return\n\n\ndef dfs(vertice):\n global path\n if visited[vertice]:\n return\n visited[vertice] = True\n path.append(vertice+1)\n for v in adj_list_graph[vertice]:\n dfs(v-1)\n\n\nif __name__ == '__main__':\n main()","sub_path":"Algorithms/Search/DFS/dfs.py","file_name":"dfs.py","file_ext":"py","file_size_in_byte":880,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"110033313","text":"from res import RealEstateScrapper\r\n\r\napi_keys = iter([\r\n # Naver (drakane)\r\n # \"wCNa%2FMBnfJIeZDVFlzEJo%2F%2FphsLnOKjvk0tS%2FxDHXnw95QZ87nbgtr7i3okgYlaZqGiHgVKfuMpruC8NPEQ1Iw%3D%3D\",\r\n \"%2BMU8%2FJTCgZ%2BCwG%2FpuO3KiZcbpAEFvfjCA9hHAJ6fobm7Wrt1Ar%2BlroFUuZoqd%2B3uz2otc4OEUEZk4H4w5kNP8w%3D%3D\",\r\n # Gmail (yuvenious)\r\n # \"yh5d7u8tLTrzl5kw8vDHvRLugGIjEsJ5j6SOhRnXma1%2F2IvWtUzc%2BhxmVtDFw1SRW2lREd%2BPZNpgUWmG6LI6yg%3D%3D\",\r\n # # Daum (drakane85)\r\n # \"a%2FvRarhLAb3kwKJfKtz5XA6HR1%2F4EtTBwD%2Bp42sznlZzxhKZu1Uk0EyN34vJYIvGZLDagtqGxvmEk5yj8hR5Kw%3D%3D\",\r\n # # mySNU (drakane8)\r\n # \"kpCf4%2B86hQm%2FFEFGoCZVysiA4dy60JFu4YnrxKpTW6JEd4MC0Q3er91tMAvgvL2zcAqxUxsStIFmWj9y0NU8oQ%3D%3D\",\r\n])\r\n\r\ndef main():\r\n city = '서울특별시'\r\n loc_names = None # 모든 지역구를 하고 싶다면 loc_names = None\r\n start_ym, end_ym = 201701, 201712 # 수집을 원하는 시작/종료 지점을 YYYYMM 형태로 입력\r\n output_filename = 'output' # archive directory가 자동 생성된 후, 확장자 csv 테이블형 자료가 저장됨\r\n\r\n res = RealEstateScrapper(city, loc_names, start_ym, end_ym, api_keys, output_filename)\r\n\r\n # res.export()\r\nif __name__ == '__main__':\r\n\r\n main()\r\n","sub_path":"src/old/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1224,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"404333674","text":"# -*- coding: utf-8 -*-\n# #############################################################################\n#\n# Author: Yannick Buron\n# Copyright 2013 Yannick Buron\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU Affero General Public License as\n# published by the Free Software Foundation, either version 3 of the\n# License, or (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU Affero General Public License for more details.\n#\n# You should have received a copy of the GNU Affero General Public License\n# along with this program. If not, see .\n#\n##############################################################################\n\n\nfrom openerp import netsvc\nfrom openerp import pooler\nfrom openerp.osv import fields, osv, orm\nfrom openerp.tools.translate import _\n\nimport time\nfrom datetime import datetime, timedelta\nimport subprocess\nimport openerp.addons.clouder.execute as execute\nimport erppeek\n\nimport logging\n\n_logger = logging.getLogger(__name__)\n\n\nclass clouder_container(osv.osv):\n _inherit = 'clouder.container'\n\n def deploy_post(self):\n super(clouder_container, self).deploy_post()\n if self.application_id.type_id.name == 'openldap':\n\n domain_dc = ''\n for dc in self.options['domain']['value'].split('.'):\n if domain_dc:\n domain_dc += ','\n domain_dc += 'dc=' + dc\n\n hostport = False\n for port in self.port_ids:\n if port.name == 'openldap':\n hostport = port.hostport\n\n server_obj = self.env['ldap.server']\n server_obj.create({\n 'name': self.fullname,\n 'host': self.server_id.name,\n 'port': hostport,\n 'binddn': 'cn=admin,' + domain_dc,\n 'basedn': 'ou=people,' + domain_dc,\n 'password': self.options['password']['value']\n })\n\n def purge(self):\n if self.application_id.type_id.name == 'openldap':\n\n hostport = False\n for port in self.port_ids:\n if port.name == 'openldap':\n hostport = port.hostport\n\n server_obj = self.pool.get('ldap.server')\n server_ids = server_obj.search([\n ('host', '=', self.server_id.name), ('port', '=', hostport)])\n server_ids.unlink()\n return super(clouder_container, self).purge()","sub_path":"clouder_users/deploy.py","file_name":"deploy.py","file_ext":"py","file_size_in_byte":2713,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"121172963","text":"#!/usr/bin/env python\n\n\"\"\"Borrowed from Carl Meyer's django-adminfiles.\"\"\"\n\nimport os\nimport sys\n\ncurrentdir = os.path.dirname(os.path.abspath(__file__))\nparentdir = os.path.dirname(currentdir)\nsys.path.insert(0, parentdir)\nsys.path.insert(0, currentdir)\n\nos.environ['DJANGO_SETTINGS_MODULE'] = 'testproject.settings'\n\nfrom django.test.simple import run_tests\n\n\ndef main():\n failures = run_tests(['test_app'], verbosity=1, interactive=True)\n sys.exit(failures)\n\nif __name__ == '__main__':\n main()\n","sub_path":"tests/runtests.py","file_name":"runtests.py","file_ext":"py","file_size_in_byte":506,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"241553560","text":"import logging\nimport re\nimport struct\nimport sys\nimport subprocess\nfrom pprint import pprint\n\nimport lief\nimport keystone\nimport capstone\n\ntry:\n import colorlog\nexcept ImportError:\n colorlog = None\n\nlog = logging.getLogger(__name__)\nlog.setLevel(logging.INFO)\nif \"DEBUG\" in sys.argv:\n log.setLevel(logging.DEBUG)\n del sys.argv[sys.argv.index(\"DEBUG\")]\n\nif colorlog is not None:\n handler = colorlog.StreamHandler()\n fmt = '%(log_color)s%(levelname)s%(reset)s : %(message)s'\n fmter = colorlog.ColoredFormatter(fmt)\n handler.setFormatter(fmter)\n log.addHandler(handler)\nelse:\n fmt = '%(levelname)s : %(message)s'\n handler = logging.StreamHandler()\n handler.setFormatter(logging.Formatter(fmt))\n log.addHandler(handler)\n\n_ks = None\n\n\ndef u8(x):\n return struct.unpack(\"B\", x)[0]\n\n\ndef p8(x):\n return struct.pack(\"B\", x)\n\n\ndef u16(x):\n return struct.unpack(\"H\", x)[0]\n\n\ndef p16(x):\n return struct.pack(\"H\", x)\n\n\ndef load_binary(path):\n return lief.parse(path)\n\n\ndef get_functions(binary):\n functions = {}\n for sym in binary.static_symbols:\n if sym.type == lief.ELF.SYMBOL_TYPES.FUNC:\n log.debug(\"got function symbol: {!r} 0x{:x}\"\n .format(sym.name, sym.value))\n functions[sym.name] = sym.value\n return functions\n\n\ndef load_blobs(binary):\n subprocess.check_call(\"cd hooks && make\", shell=True)\n\n entryhook = lief.parse('./hooks/setup_shadowmem')\n # FIXME: insert_content returns the same offset every time\n eh = binary.insert_content(entryhook.segments[0].data)\n # FIXME: symbol adding doesn't seem to work\n sym = lief.ELF.Symbol()\n sym.name = \"__ceflif_setup\"\n sym.value, sym.size = eh\n binary.add_static_symbol(sym)\n\n verifier = lief.parse('./hooks/call_verifier')\n vh = binary.insert_content(verifier.segments[0].data)\n sym = lief.ELF.Symbol()\n sym.name = \"__ceflif_verify\"\n sym.value, sym.size = eh\n binary.add_static_symbol(sym)\n\n init = lief.parse('./hooks/shadow_init')\n ih = binary.insert_content(init.segments[0].data)\n sym = lief.ELF.Symbol()\n sym.name = \"__ceflif_init\"\n sym.value, sym.size = eh\n binary.add_static_symbol(sym)\n\n x = {'init': ih[0], 'setup': eh[0], 'verify': vh[0]}\n log.debug(\", \".join(\"{}: 0x{:x}\".format(k, v) for k, v in x.iteritems()))\n return x\n\n\ndef ks_asm(code):\n global _ks\n if not _ks:\n _ks = keystone.Ks(keystone.KS_ARCH_X86, keystone.KS_MODE_32)\n # log.debug(code)\n encoding, _ = _ks.asm(code)\n return encoding\n\n\ndef create_init_asm(funcs, initfunc):\n tmpl = \"\"\"\n mov rdi, 0x{:x};\n call 0x{:x};\n \"\"\"\n x = []\n for func in funcs:\n a = funcs[func]\n if a > 0:\n x.append(tmpl.format(a, initfunc))\n return \"\".join(x)\n\n\ndef hook_entrypoint(binary, hooks, funcs):\n hook_virt = hooks['setup']\n asm = \"\"\"\n call 0x{:x};\n {}\n jmp 0x{:x};\n \"\"\"\n init_code = create_init_asm(funcs, hooks['init'])\n ep = binary.entrypoint\n log.debug(\"hooking entrypoint 0x{:x}\".format(ep))\n asm = asm.format(hook_virt, init_code, ep)\n log.debug(asm)\n log.debug(\"assembling entry hook\")\n ephook = ks_asm(asm)\n log.debug(\"got {!r}\".format(ephook))\n newep, _ = binary.insert_content(ephook)\n # newep += 0x00400000\n startsym = next(\n iter(filter(lambda s: s.name == \"_start\", binary.static_symbols)))\n startsym.value = newep\n log.debug(\"new entrypoint is 0x{:x}\".format(newep))\n\n\ndef find_calls(binary, func):\n return []\n\n\ndef instrument_call(binary, call):\n pass\n\n\ndef list_symbols(binary):\n for sym in binary.static_symbols:\n if sym.type == lief.ELF.SYMBOL_TYPES.FUNC:\n log.info(\"{} / 0x{:x}\".format(sym.name, sym.value))\n\n\ndef main():\n # load binary\n binary = load_binary(sys.argv[1])\n list_symbols(binary)\n # insert hooks\n hooks = load_blobs(binary)\n # find functions in binary\n # - iterate over symbols in binary\n # - gather a map symbols <-> address\n functions = get_functions(binary)\n # hook entry point to setup shadow memory\n hook_entrypoint(binary, hooks, functions)\n # instrument call instructions\n # - iterate over functions\n # - disassemble functions (capstone)\n # - for each call instruction\n # - add hook to call verifier\n for func in functions:\n calls = find_calls(binary, func)\n for call in calls:\n instrument_call(binary, call)\n\n list_symbols(binary)\n log.info(\"saving result\")\n binary.write(\"tests/out\")\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"elfcfi.py","file_name":"elfcfi.py","file_ext":"py","file_size_in_byte":4592,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"29091853","text":"#!/usr/bin/env python3\n# readf.py - read file with clib\nfrom ctypes import *\nMAX = 1024\n\n# load shared C library\nmylib = CDLL(\"libc.so.6\")\n\n# open file for reading\nfp = mylib.fopen(b'filedata', \"r\")\nsbuf = create_string_buffer(MAX)\nprint(\"reading filedata\")\nmylib.fread(sbuf, MAX, 1, fp)\nprint(sbuf.value.decode(\"ascii\"), end = '')\nmylib.fclose(fp)\n\n#####################################\n#\n# $ readf.py\n# reading filedata\n# Here is some data.\n#\n","sub_path":"py3/pgms/sec8/Extend/ctypes/readf.py","file_name":"readf.py","file_ext":"py","file_size_in_byte":457,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"151319122","text":"import numpy as np\nimport scipy as sp\nfrom scipy import signal\nimport sklearn as sk\nfrom sklearn import neighbors\nfrom . import preprocessing as pp\nfrom . import utilities as u\nfrom . import UnityTransforms as unity\nfrom matplotlib import pyplot as plt\nimport pickle\nimport os\nfrom scipy.interpolate import interp1d as spline\nfrom sklearn.linear_model import HuberRegressor as hreg\n\n\n\ndef calculate_posterior(prior,morphs,xx_lims = (-.1,1.1), sigma_likelihood=.3,calcZ=False):\n '''\n calculate posterior distribution for different morph values.\n likelihood is assumed to be gaussian with width\n morphs are assumed to be corrected wall morph values\n\n inputs: prior - [1, N] numpy array with PMF of prior distribution sampled at\n evenly spaced intervals between xx_lims[0] and xx_lims[1]\n morphs - [M,] numpy array of morph values at which to calculate the posterior\n i.e. array of means for the likelihood\n xx_lims - 2-tuple of limits over which prior is sampled\n sigma_likelihood - width of likelihood function\n returns: post - [M,N] numpy array of posterior distributions calculated at each morph value\n each row is a distribution\n xx - [N,] numpy array, interval over which posterior is sampled\n\n '''\n\n assert (prior.shape[0]==1), \"prior is wrong shape, must be 1 x N\"\n xx = np.linspace(xx_lims[0],xx_lims[1],num=prior.size) # samples\n post = prior*u.gaussian(morphs[:,np.newaxis],sigma_likelihood,xx[np.newaxis,:]) # prior x likelihood\n Z = post.sum(axis=1)\n post = post/post.sum(axis=1,keepdims=True) # normalize to be a valid distribution\n if calcZ:\n return post, xx, Z\n else:\n return post, xx\n\ndef make_sampling_spline(xx,prob):\n '''\n generate a spline to sample from probability distribution \"prob\"\n inputs - xx - values over which prob is sampled\n prob - probability mass function\n returns - a spline to sample from prob using a uniform random number generator\n '''\n prob/=prob.sum() # ensure prior is s distribution\n cum_prob = np.cumsum(prob) # cumulative probability\n cum_prob[0],cum_prob[-1] = 0,1 # make sure cum. distribution is actually 0-1\n\n return spline(cum_prob,xx)\n\n\ndef simulate_session(prior,morphs, n_neurons=100,n_samps=1,rbf_sigma=.4,alpha = 1., beta = .25,xx_lims = (-.3,1.3),gamma=True):\n '''\n simulate a set of gamma neurons that encode samples from a posterior distribution\n inputs: prior - [1 , N] numpy array, probability mass funciton sampled evenly over interval specified in xx_lims\n assumed that this is in corrected wall morph space\n morphs - [M,] numpy array of corrected wall morph values over which to calculate the posterior distribution\n n_neurons - number of neurons in simulation, modeled as cells with gamma activity. The shape parameter is\n determined by radial basis function tuning for different values of the stimulus. Each cell has a different\n preferred stimulus\n n_samps - number of samples to draw per trial\n rbf_sigma - width of radial basis functions\n alpha - scaling of radial basis function\n beta - additive offset of radial basis function, beta>=0\n xx_lims - limits over which prior is evenly sampled\n returns: sim_data - [M,N*n_samps] numpy array of neuron activity\n sim_data_sm - [M,M] numpy array, trial x trial similarity matrix for simulated population\n sim_data_sf - [M, ] numpy array, similarity fraction for simulated neurons\n\n '''\n\n post, xx = calculate_posterior(prior,morphs,xx_lims=xx_lims) # calculate posterior\n neurons = np.zeros([morphs.shape[0],n_neurons*n_samps]) #allocate for neual activity\n _mun = np.linspace(xx_lims[0],xx_lims[1],num=n_neurons) # evenly space means of radial basis functions along sampling limits\n for trial in range(post.shape[0]):\n samplingspline = make_sampling_spline(xx,post[trial,:]) # make spline to sample from posterior\n post_samples = samplingspline(np.random.rand(n_samps))\n for samp_i in range(post_samples.size):\n neurons[trial,n_neurons*samp_i:n_neurons*(samp_i+1)] = u.gaussian(_mun,rbf_sigma,post_samples[samp_i]) # get activation of radial basis function\n\n if gamma:\n simdata=np.random.gamma(alpha*neurons +beta) # sample gamma distributions\n else:\n simdata = alpha*neurons +beta\n # trial by trial similarity matrix\n simdata_norm = simdata/np.linalg.norm(simdata,axis=1,ord=2,keepdims=True)\n simdata_sm = np.dot(simdata_norm,simdata_norm.T)\n\n # calculate similarity fraction\n trial_info = {}\n trial_info['morphs']=np.copy(morphs)\n trial_info['morphs'][morphs<.1]=0\n trial_info['morphs'][morphs>.9]=1\n sf = u.similarity_fraction(simdata,trial_info)\n\n return simdata, simdata_sm, sf\n\ndef simmat_distribution(morphs,prior,nperms=100,n_neurons=100,n_samps=1,rbf_sigma=.4,alpha = 1., beta = .25,xx_lims = (-.1,1.1)):\n '''\n simulate a distribution of sessions for a fixed prior.\n inputs: nperms - integer, number of simulated first_sessions\n see simulate_session docstring for other inputs\n returns: SIMDATA - [nperms,N,M] numpy array of simulated activity for each cell\n SIMDATA_SM - [nperms,M,M] numpy array of trial x trial cosine similarity matrices\n SF - [nperms,M] numpy array of similarity fractions\n '''\n SIMDATA, SIMDATA_SM, SF = [],[],[]\n for it in range(nperms):\n if it%100 == 0:\n print(it)\n simdata,simdata_sm,sf = simulate_session(prior,morphs,n_samps=n_samps,n_neurons=n_neurons,rbf_sigma = rbf_sigma)\n SIMDATA.append(simdata)\n SIMDATA_SM.append(simdata_sm)\n SF.append(sf)\n return np.array(SIMDATA), np.array(SIMDATA_SM), np.array(SF)\n\ndef run_simmat_distributions(sess,rare_prior,freq_prior,nperms=1000,n_samps=1,rbf_sigma=.4,alpha = 1.,\n beta = .25,xx_lims = (-.1,1.1),basedir = \"D:\\\\Suite2P_Data\\\\\"):\n '''\n load real session data and simulate distribution of sessions assuming rare morph or frequent morph prior.\n uses exact trials shown in session and same number of neurons as recording\n\n inputs: sess - row from pandas array (behavior.sqlite) including session information\n rare_prior - [1,N] numpy array, rare morph condition probability mass function\n sampled evenly on interval defined by xx_lims\n assumed to have been calculated in corrected wall morph space\n freq_prior - [1,N] numpy array, freq morph condition probability mass function\n same assumptions as rare_prior\n nperms - number of simulations in each condition\n n_samps - number of sampls to draw on each trial\n rbf_sigma - width of radial basis functions\n alpha - scaling of radial basis function\n beta - additive constant for radial basis function\n xx_lims - interval over which priors are sampled\n basedir - base directory for finding session data\n returns: morphs - [# of trials,] numpy array, sorted, uncorrected wall morph values\n S_trial_mat - [# of trials, # of position bins, # of neurons] numpy array of cell activity rates, morph sorted,\n np.dot(S_tmat_norm,S_tmat_norm.T) - [# of trials, # of trials] numpy array, trial x trial population similarity matrices\n u.similarity_fraction(S_trial_mat,trial_info) - [# of trials,] numpy array, similarity fraction for real data\n SIMDATA - dict for rare and freq conditions: [nperms,# of trials, # of neurons*nsamps] numpy array, simulated data\n SIMDATA_SM - dict for rare and freq conditions: [nperms, # of trials, # of trials] numpy array, simulated trial x trial similarity matrices\n SIMDATA_SF - dict for rare and freq conditions: [nperms, # of trials] numpy array, similarity fractions for simulated data\n\n '''\n\n\n # load data\n with open(os.path.join(basedir,sess[\"MouseName\"],\"%s_%s_%i.pkl\" % (sess[\"Track\"],sess[\"DateFolder\"],sess[\"SessionNumber\"])),'rb') as f:\n data = pickle.load(f)\n\n S, tstart_inds, teleport_inds,VRDat = np.copy(data[\"S\"]), data[\"tstart_inds\"], data[\"teleport_inds\"],data[\"VRDat\"]\n S[np.isnan(S)]=0\n S = S/1546 #np.percentile(S,95,axis=0,keepdims=True)\n S_trial_mat = u.make_pos_bin_trial_matrices(np.copy(S),data['VRDat']['pos']._values,tstart_inds,\n teleport_inds,bin_size=10,mat_only=True)\n\n trial_info = data['trial_info']\n morphs = trial_info['morphs']+trial_info['wallJitter']\n morphsort = np.argsort(morphs)\n morphs = morphs[morphsort]\n trial_info['morphs'] = trial_info['morphs'][morphsort]\n\n S_trial_mat = S_trial_mat[morphsort,:,:]\n S_trial_mat = sp.ndimage.filters.gaussian_filter1d(S_trial_mat,2,axis=1)\n S_trial_mat[np.isnan(S_trial_mat)]=0\n S_tmat = S_trial_mat.reshape(S_trial_mat.shape[0],-1)\n S_tmat_norm = S_tmat/(np.linalg.norm(S_tmat,axis=1,ord=2,keepdims=True)+1E-8)\n\n # run simulations\n SIMDATA,SIMDATA_SM,SIMDATA_SF = {},{},{}\n for prior,name in zip([rare_prior,freq_prior],['rare','freq']):\n print(name)\n sd,sdsm,sdsf = simmat_distribution(unity.wallmorphx(morphs),prior,nperms=nperms,n_neurons=S_trial_mat.shape[-1])\n SIMDATA[name],SIMDATA_SM[name], SIMDATA_SF[name]= sd, sdsm,sdsf\n return trial_info,S_trial_mat, np.dot(S_tmat_norm,S_tmat_norm.T), u.similarity_fraction(S_trial_mat,trial_info), SIMDATA, SIMDATA_SM, SIMDATA_SF\n\n\ndef simulate_session_plot_results(sess,rare_prior,freq_prior,nperms=1000,n_samps=1,rbf_sigma=.4,alpha = 1., beta = .25,xx_lims = (-.1,1.1),\n out_dir = \"D:\\\\Morph_Results\\\\figures\\\\TheoreticalSimMats\\\\\"):\n '''\n Simulate similarity matrices from rare and frequent morph condition. Plot results and save dictionary of results\n\n inputs: sess - row from pandas array with session information\n nperms - number of simulations in each condition\n n_samps - number of samples drawn for each trial\n rbf_sigma - width of radial basis functions\n alpha - scaling of RBF\n beta - additive constant for RBF\n xx_lims - range over which prior is sampled\n\n\n '''\n\n # set minimal value for hypothesis tests\n epsilon = 1/nperms\n\n # run simulation\n trial_info,S_trial_mat,simmat, sf, SIMDATA,SIMDATA_SM,SIMDATA_SF = run_simmat_distributions(sess,rare_prior,freq_prior,nperms=nperms,\n n_samps=n_samps,\n rbf_sigma=rbf_sigma,alpha = alpha, beta = beta,\n xx_lims = xx_lims)\n morph = trial_info['morphs']+trial_info['wallJitter']\n # make output directory\n sessdir = os.path.join(out_dir,\"%s_%s_%i\" % (sess[\"MouseName\"],sess[\"DateFolder\"],sess[\"SessionNumber\"]))\n try:\n os.makedirs(sessdir)\n except:\n pass\n\n\n # plot real data\n simmat_z = sp.stats.zscore(simmat.ravel())\n f,ax = plt.subplots(1,2,figsize=[10,5])\n ax[0].imshow(simmat,vmin=np.percentile(simmat,20),vmax=np.percentile(simmat,80),cmap='Greys')\n ax[1].scatter(morphs,1-sf)\n ax[1].set_xlabel('$\\hat{S}$')\n ax[1].set_ylabel('SF')\n f.savefig(os.path.join(sessdir,\"simmat.pdf\"),format='pdf')\n\n # calculate correlation with rare morph and frequent morph simulations\n simsimmat_rare_z = sp.stats.zscore(SIMDATA_SM['rare'].reshape(SIMDATA_SM['rare'].shape[0],-1),axis=-1)\n simsimmat_freq_z = sp.stats.zscore(SIMDATA_SM['freq'].reshape(SIMDATA_SM['freq'].shape[0],-1),axis=-1)\n corr_rare, corr_freq = np.dot(simsimmat_rare_z,simmat_z)/simmat_z.shape[0],np.dot(simsimmat_freq_z,simmat_z)/simmat_z.shape[0]\n\n # calculate test statistic - difference in medians\n TSTAT = np.median(corr_rare)-np.median(corr_freq)\n print('median difference',TSTAT)\n\n # calculate test statistic for each simulated session\n null_dist = {}\n keys = ['rare','freq']\n for ind in [0,1]:\n # same prior data\n same_sms = SIMDATA_SM[keys[ind]]\n same_sms = sp.stats.zscore(same_sms.reshape(same_sms.shape[0],-1),axis=1)\n # other prior data\n diff_sms = SIMDATA_SM[keys[ind-1]]\n diff_sms = sp.stats.zscore(diff_sms.reshape(diff_sms.shape[0],-1),axis=1)\n null_dist[keys[ind]]=[]\n for row in range(SIMDATA_SM[keys[ind]].shape[0]):\n mask = np.ones((same_sms.shape[0],))\n mask[row]=0\n mask = mask>0\n\n # calculate correlation\n test,train = same_sms[row,:], same_sms[mask,:]\n corr_same, corr_diff = np.dot(train,test)/test.shape[0],np.dot(diff_sms,test)/test.shape[0]\n # calculate test statistic\n if ind == 0:\n tstat = np.median(corr_same)-np.median(corr_diff)\n else:\n tstat = np.median(corr_diff)-np.median(corr_same)\n\n if row%100==0:\n print(row,tstat)\n null_dist[keys[ind]].append(tstat)\n\n null_dist[keys[ind]]=np.array(null_dist[keys[ind]])\n\n # log [(probability rare morph test statistic< real test statistic)/(probability frequent morph test statistic> real test statistic)]\n llr = np.log10(np.maximum((null_dist['rare']TSTAT).sum()/null_dist['freq'].size ,epsilon))\n print('llr',llr)\n\n\n with open(os.path.join(sessdir,'simresults.pkl'),'wb') as file:\n pickle.dump({'SIMDATA':SIMDATA,'SIMDATA_SM':SIMDATA_SM,'SIMDATA_SF':SIMDATA_SF,\n 'morphs':morphs,'corr_rare':corr_rare,'corr_freq':corr_freq,'null_dist':null_dist,'llr':llr,'test_statistic':TSTAT},file)\n\n # plot histogram of test statistics from simulated data\n f,ax = plt.subplots()\n ax.hist(null_dist['freq'],alpha=.3)\n ax.hist(null_dist['rare'],alpha=.3)\n # plot test statistic from real data\n ax.vlines(TSTAT,0,nperms/4)\n ax.set_xlabel('test statistic')\n ax.set_ylabel('count')\n ax.set_title(\"Med Diff=%.3f, LLR=%.3f\" %(TSTAT,llr))\n f.savefig(os.path.join(sessdir,\"null_dists.pdf\"),format='pdf')\n f.savefig(os.path.join(sessdir,\"null_dists.png\"),format='png')\n\n # plot correlation of real data with simulated rare and frequent morph data\n f,ax = plt.subplots()\n allcorrs = np.concatenate((corr_rare,corr_freq))\n edges = np.linspace(np.amin(allcorrs),np.amax(allcorrs),num=25)\n rare_bins,_ = np.histogram(corr_rare,bins=edges)\n freq_bins,_ = np.histogram(corr_freq,bins=edges)\n ax.fill_between(edges[1:],rare_bins,alpha=.3,color='orange')\n ax.fill_between(edges[1:],freq_bins,alpha=.3,color='blue')\n ax.set_xlabel('correlation')\n ax.set_ylabel('count')\n ax.set_title(\"Med Diff=%.3f, LLR=%.3f\" %(TSTAT,llr))\n f.savefig(os.path.join(sessdir,\"corr_distributions.pdf\"),format='pdf')\n\n\n f,ax = plt.subplots()\n ax.plot(edges[1:],np.cumsum(rare_bins)/1000,color='orange')\n ax.plot(edges[1:],np.cumsum(freq_bins)/1000,color='blue')\n f.savefig(os.path.join(sessdir,\"corr_cumdistributions.pdf\"),format='pdf')\n\n # plot some example simulated sessions\n for name in ['rare', 'freq']:\n f,ax = plt.subplots(20,3,figsize=[15,100])\n for it in range(20):\n ax[it,0].imshow(SIMDATA[name][it,:,:],aspect='auto',cmap='pink')\n ax[it,0].set_xlabel('neuron index')\n ax[it,0].set_ylabel('trial (sorted)')\n ax[it,0].set_title('single cell activity')\n\n ax[it,1].imshow(SIMDATA_SM[name][it,:,:],vmin=np.percentile(SIMDATA_SM[name][it,:,:],20),vmax=np.percentile(SIMDATA_SM[name][it,:,:],80),cmap='Greys')\n ax[it,1].set_title('trial x trial similarity')\n\n ax[it,2].scatter(morphs,1-SIMDATA_SF[name][it,:])\n ax[it,2].set_ylabel(\"SF\")\n ax[it,2].set_xlabel(\"morph value\")\n f.savefig(os.path.join(sessdir,\"%s_eg_simulations.pdf\" % name),format='pdf')\n\n\nif __name__ == '__main__':\n df = pp.load_session_db(dir='D:\\\\')\n df = df[df['RewardCount']>40]\n df = df[df['Imaging']==1]\n df = df.sort_values(['MouseName','DateTime','SessionNumber'])\n df = df[df[\"Track\"]==\"TwoTower_foraging\"]\n for (mouse, first_ind) in zip(['4139265.3','4139265.4','4139265.5','4222168.1','4343703.1','4222153.1','4222153.2',\n '4222153.3','4222174.1','4222154.1','4343702.1'],[5,5,5,3,5,4,4,4,4,4,4]):\n df_mouse = df[df[\"MouseName\"]==mouse]\n\n for sess_ind in range(first_ind,df_mouse.shape[0]):\n sess = df_mouse.iloc[sess_ind]\n simulate_session_plot_results(sess)\n","sub_path":"morph_analyses/SimulatedSimMats.py","file_name":"SimulatedSimMats.py","file_ext":"py","file_size_in_byte":16962,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"475848355","text":"from CommonConstant import (\n DROP_COLUMN_NAME_LIST,\n TECHNICAL_INDEX_COLUMN_NAME_CLOSE,\n TECHNICAL_INDEX_COLUMN_NAME_LOW,\n TECHNICAL_INDEX_COLUMN_NAME_HIGH,\n TECHNICAL_INDEX_COLUMN_NAME_SHORT_EMA,\n TECHNICAL_INDEX_COLUMN_NAME_MIDDLE_EMA,\n TECHNICAL_INDEX_COLUMN_NAME_LONG_EMA,\n TECHNICAL_INDEX_COLUMN_NAME_MACD,\n TECHNICAL_INDEX_COLUMN_NAME_SIGNAL,\n TECHNICAL_INDEX_COLUMN_NAME_PLUS_DI,\n TECHNICAL_INDEX_COLUMN_NAME_MINUS_DI,\n TECHNICAL_INDEX_COLUMN_NAME_ADX,\n PREVIOUS_COLUMN_PREFIX,\n DIFFERENCE_COLUMN_SUFFIX\n )\nimport pandas as pd\nfrom TechnicalIndex import GetExponentialMovingAverage, GetMACD, GetDMIandADX\nfrom decimal import Decimal, InvalidOperation\nfrom LogMessage import CreateDataFrameAnalysisMessage\nfrom logging import getLogger\nlogger = getLogger()\n\n\ndef __DecimalizeDataFrame(sourceDataFrame):\n\n if sourceDataFrame is None or len(sourceDataFrame) == 0:\n return None\n\n sourceColumns = sourceDataFrame.columns\n sourceNdarray = sourceDataFrame.values\n Y_length, X_length = sourceNdarray.shape\n\n try:\n for X_idx in range(X_length):\n for Y_idx in range(Y_length):\n sourceNdarray[Y_idx, X_idx] = Decimal(str(sourceNdarray[Y_idx, X_idx]))\n except InvalidOperation:\n return None\n\n return pd.DataFrame(sourceNdarray, columns=sourceColumns)\n\n\ndef __GetDifferenceColumnBetweenTodayAndPreviousDay(sourceDataFrame):\n\n returnDataFrame = pd.DataFrame(None)\n\n todayColumns = [columnName for columnName in sourceDataFrame.columns if PREVIOUS_COLUMN_PREFIX not in columnName]\n\n for columnName in todayColumns:\n if PREVIOUS_COLUMN_PREFIX + columnName in sourceDataFrame.columns:\n returnDataFrame[columnName + DIFFERENCE_COLUMN_SUFFIX] = sourceDataFrame[columnName] - sourceDataFrame[PREVIOUS_COLUMN_PREFIX + columnName]\n\n return returnDataFrame\n\n\ndef __GetAlignedDataFrameLength(sourceDataFrameList):\n\n errorDataFrameList = [technicalIndexDataFrame for technicalIndexDataFrame in sourceDataFrameList if technicalIndexDataFrame is None or len(technicalIndexDataFrame) == 0]\n if len(errorDataFrameList) != 0:\n return []\n\n minimumRowsCount = min([len(technicalIndexDataFrame) for technicalIndexDataFrame in sourceDataFrameList])\n\n for technicalIndexDataFrame in sourceDataFrameList:\n if len(technicalIndexDataFrame) > minimumRowsCount:\n technicalIndexDataFrame.drop(labels=technicalIndexDataFrame.index[0:len(technicalIndexDataFrame) - minimumRowsCount], inplace=True)\n technicalIndexDataFrame.reset_index(drop=True, inplace=True)\n\n return sourceDataFrameList\n\n\ndef __GetPreviousDayTechnicalIndex(sourceDataFrame):\n\n previousDayTechnicalIndexDataFrame = sourceDataFrame.copy()\n previousTrainingTechnicalIndexColumnList = [PREVIOUS_COLUMN_PREFIX + columnName for columnName in sourceDataFrame.columns]\n previousDayTechnicalIndexDataFrame.columns = previousTrainingTechnicalIndexColumnList\n\n return previousDayTechnicalIndexDataFrame\n\n\ndef __GetDMIandADXDataFrame(sourceDataFrame):\n\n plusDIdataFrame, minusDIdataFrame, ADXdataFrame = GetDMIandADX(calculateSourceDataFrame=sourceDataFrame,\n calculateSourceColumnName_TodayHigh=TECHNICAL_INDEX_COLUMN_NAME_HIGH,\n calculateSourceColumnName_TodayLow=TECHNICAL_INDEX_COLUMN_NAME_LOW,\n calculateSourceColumnName_PreviousHigh=PREVIOUS_COLUMN_PREFIX + TECHNICAL_INDEX_COLUMN_NAME_HIGH,\n calculateSourceColumnName_PreviousLow=PREVIOUS_COLUMN_PREFIX + TECHNICAL_INDEX_COLUMN_NAME_LOW,\n calculateSourceColumnName_PreviousClose=PREVIOUS_COLUMN_PREFIX + TECHNICAL_INDEX_COLUMN_NAME_CLOSE,\n plusDIcolumnName=TECHNICAL_INDEX_COLUMN_NAME_PLUS_DI,\n minusDIcolumnName=TECHNICAL_INDEX_COLUMN_NAME_MINUS_DI,\n DI_Parameter=14,\n ADX_Parameter=26,\n ADXcolumnName=TECHNICAL_INDEX_COLUMN_NAME_ADX)\n\n if plusDIdataFrame is None or minusDIdataFrame is None or ADXdataFrame is None:\n return None\n\n DMIandADXDataFrameList = [plusDIdataFrame, minusDIdataFrame, ADXdataFrame]\n alignedDataFrameList = __GetAlignedDataFrameLength(DMIandADXDataFrameList)\n if len(alignedDataFrameList) == 0:\n return None\n\n DMIandADXDataFrame = pd.concat(alignedDataFrameList, axis=1)\n\n previousDayDMIandADXDataFrame = __GetPreviousDayTechnicalIndex(DMIandADXDataFrame)\n if previousDayDMIandADXDataFrame is None:\n return None\n\n DMIandADXDataFrame.drop(0, inplace=True)\n DMIandADXDataFrame.reset_index(drop=True, inplace=True)\n DMIandADXDataFrame = pd.concat([DMIandADXDataFrame, previousDayDMIandADXDataFrame.iloc[:-1]], axis=1)\n differenceDataFrameBetweenTodayAndPreviousDay = __GetDifferenceColumnBetweenTodayAndPreviousDay(DMIandADXDataFrame)\n if differenceDataFrameBetweenTodayAndPreviousDay is None:\n return None\n\n DMIandADXDataFrame = pd.concat([DMIandADXDataFrame, differenceDataFrameBetweenTodayAndPreviousDay], axis=1)\n\n return DMIandADXDataFrame\n\n\ndef GetDataFrameForAnalysis(sourceDataFrame):\n\n if sourceDataFrame is None or len(sourceDataFrame) == 0:\n logger.info(CreateDataFrameAnalysisMessage.sourceDataFrameError)\n return None\n\n technicalIndexDataFrame = sourceDataFrame.copy()\n\n for dropColumnName in DROP_COLUMN_NAME_LIST:\n if dropColumnName in technicalIndexDataFrame.columns:\n technicalIndexDataFrame.drop(dropColumnName, axis=1, inplace=True)\n\n technicalIndexDataFrame = __DecimalizeDataFrame(technicalIndexDataFrame)\n if technicalIndexDataFrame is None:\n logger.info(CreateDataFrameAnalysisMessage.decimalizeError)\n return None\n\n shortEMADataFrame = GetExponentialMovingAverage(calculateSourceDataFrame=technicalIndexDataFrame, calculate_parameter=5, calculateSourceColumnName=TECHNICAL_INDEX_COLUMN_NAME_CLOSE, returnDataFrameColumnName=TECHNICAL_INDEX_COLUMN_NAME_SHORT_EMA)\n middleEMADataFrame = GetExponentialMovingAverage(calculateSourceDataFrame=technicalIndexDataFrame, calculate_parameter=20, calculateSourceColumnName=TECHNICAL_INDEX_COLUMN_NAME_CLOSE, returnDataFrameColumnName=TECHNICAL_INDEX_COLUMN_NAME_MIDDLE_EMA)\n longEMADataFrame = GetExponentialMovingAverage(calculateSourceDataFrame=technicalIndexDataFrame, calculate_parameter=60, calculateSourceColumnName=TECHNICAL_INDEX_COLUMN_NAME_CLOSE, returnDataFrameColumnName=TECHNICAL_INDEX_COLUMN_NAME_LONG_EMA)\n MACD_DataFrame, signalDataFrame = GetMACD(calculateSourceDataFrame=technicalIndexDataFrame, calculateSourceColumnName=TECHNICAL_INDEX_COLUMN_NAME_CLOSE, baseLine_parameter=12, relativeLine_parameter=26, signal_parameter=9, MACDDataFrameColumnName=TECHNICAL_INDEX_COLUMN_NAME_MACD, signalDataFrameColumnName=TECHNICAL_INDEX_COLUMN_NAME_SIGNAL)\n\n technicalIndexDataFrameList = [technicalIndexDataFrame, shortEMADataFrame, middleEMADataFrame, longEMADataFrame, MACD_DataFrame, signalDataFrame]\n alignedDataFrameList = __GetAlignedDataFrameLength(technicalIndexDataFrameList)\n if len(alignedDataFrameList) == 0:\n logger.info(CreateDataFrameAnalysisMessage.technicalIndexDataFrameError)\n return None\n\n technicalIndexDataFrame = pd.concat(alignedDataFrameList, axis=1)\n\n previousDayTechnicalIndexDataFrame = __GetPreviousDayTechnicalIndex(technicalIndexDataFrame)\n if previousDayTechnicalIndexDataFrame is None:\n logger.info(CreateDataFrameAnalysisMessage.previousDayDataFrameError)\n return None\n\n technicalIndexDataFrame.drop(0, inplace=True)\n technicalIndexDataFrame.reset_index(drop=True, inplace=True)\n technicalIndexDataFrame = pd.concat([technicalIndexDataFrame, previousDayTechnicalIndexDataFrame.iloc[:-1]], axis=1)\n differenceDataFrameBetweenTodayAndPreviousDay = __GetDifferenceColumnBetweenTodayAndPreviousDay(technicalIndexDataFrame)\n if differenceDataFrameBetweenTodayAndPreviousDay is None:\n logger.info(CreateDataFrameAnalysisMessage.differenceDataFrameError)\n return None\n\n technicalIndexDataFrame = pd.concat([technicalIndexDataFrame, differenceDataFrameBetweenTodayAndPreviousDay], axis=1)\n\n DMIandADXDataFrame = __GetDMIandADXDataFrame(technicalIndexDataFrame)\n if DMIandADXDataFrame is None:\n logger.info(CreateDataFrameAnalysisMessage.DMIandADXDataFrameError)\n return None\n\n alignedDataFrameList = __GetAlignedDataFrameLength([technicalIndexDataFrame, DMIandADXDataFrame])\n if len(alignedDataFrameList) == 0:\n logger.info(CreateDataFrameAnalysisMessage.DMIandADXDataFrameError)\n return None\n\n technicalIndexDataFrame = pd.concat(alignedDataFrameList, axis=1)\n\n nonPriceMovementIndex = technicalIndexDataFrame.index[technicalIndexDataFrame[TECHNICAL_INDEX_COLUMN_NAME_CLOSE + DIFFERENCE_COLUMN_SUFFIX] == 0]\n if len(nonPriceMovementIndex) > 0:\n technicalIndexDataFrame.drop(nonPriceMovementIndex, inplace=True)\n technicalIndexDataFrame.reset_index(drop=True, inplace=True)\n\n return technicalIndexDataFrame\n\n","sub_path":"main/stockPriceAnalize/CreateDataFrameForAnalysis.py","file_name":"CreateDataFrameForAnalysis.py","file_ext":"py","file_size_in_byte":9923,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"640198299","text":"import socket\nimport sys\nimport argparse\nimport laserscan_pb2 as proto\nimport time\nimport threading\nfrom matplotlib import pyplot as plt\nfrom matplotlib import animation\nimport numpy as np\nimport math\n\nHOST, PORT = 'localhost', 8080\n\ns = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\ns.connect((HOST, PORT))\n\nflags = {'stop': False}\n\nlaserScans = []\n\nfrom pynput import keyboard\n\ndef on_press(key):\n try:\n print('alphanumeric key {0} pressed'.format(\n key.char))\n except AttributeError:\n if str(key) == 'Key.up':\n print('up')\n s.send(b'f')\n elif str(key) == 'Key.down':\n print('down')\n s.send(b's')\n elif str(key) == 'Key.left':\n print('left')\n s.send(b'l')\n elif str(key) == 'Key.right':\n s.send(b'r')\n\n\ndef threadFunc(s, flags):\n elementPositionsX = []\n elementPositionsY = []\n\n i = 0\n\n while True:\n if flags['stop']: break\n\n laserScan = proto.LaserScan()\n laserScan.ParseFromString(s.recv(11688))\n laserScans.append(laserScan) \n\n sensorPosition = laserScan.world_pose.position\n sensorOrientation = laserScan.world_pose.orientation\n\n angleDelta = 2 * math.acos(sensorOrientation.w)\n\n w = sensorOrientation.w\n z = sensorOrientation.z\n\n if ((1 > w > 0) and (0 > z > -1)) or ((-1 < w < 0) and (0 < z < 1)):\n angleDelta = -angleDelta\n\n for idx in range(len(laserScan.ranges)):\n r = laserScan.ranges[idx]\n\n if r != float('inf'):\n #dx = r * math.cos(laserScan.angle_min + idx * laserScan.angle_step)\n #dy = r * math.sin(laserScan.angle_min + idx * laserScan.angle_step)\n\n dx = r * math.cos(angleDelta + laserScan.angle_min + idx * laserScan.angle_step)\n dy = r * math.sin(angleDelta + laserScan.angle_min + idx * laserScan.angle_step)\n\n elementPositionX = sensorPosition.x + dx\n elementPositionY = sensorPosition.y + dy\n\n elementPositionsX.append(elementPositionX)\n elementPositionsY.append(elementPositionY)\n\n plt.plot(elementPositionsX, elementPositionsY, marker='o', ls='')\n plt.show()\n\n \n \n\n #print(sensorPosition)\n #print('rad', sensorOrientation.w)\n #print('unk', sensorOrientation.z)\n\n\n \"\"\"fig = plt.figure()\n ax = plt.axes(xlim=(-3, 3), ylim=(0,10))\n line, = ax.plot([], [], lw=2)\n\n def init():\n line.set_data([], [])\n i2 = 0\n return line,\n\n def animate(i):\n laserScan = proto.LaserScan()\n laserScan.ParseFromString(s.recv(11688))\n laserScans.append(laserScan) \n\n sensorPosition = laserScan.world_pose.position\n sensorOrientation = laserScan.world_pose.orientation\n\n if (i2 == 0):\n lastDeltaOrientation = sensorOrientation\n i2 = 1\n else:\n lastDeltaOrientation.w = lastDeltaOrientation.w * sensorOrientation.w\n lastDeltaOrientation.z = lastDeltaOrientation.z * sensorOrientation.z\n\n for idx in range(len(laserScan.ranges)):\n r = laserScan.ranges[idx]\n\n if r != float('inf'):\n #dx = r * math.cos(laserScan.angle_min + idx * laserScan.angle_step)\n #dy = r * math.sin(laserScan.angle_min + idx * laserScan.angle_step)\n\n dx = r * math.cos(laserScan.angle_min + idx * laserScan.angle_step)\n dy = r * math.sin(laserScan.angle_min + idx * laserScan.angle_step)\n\n #print('dx:', sensorPosition.x, dx, sensorPosition.x + dx)\n #print('dy:', sensorPosition.y, dy, sensorPosition.y + dy)\n \n\n\n print('rad', 2 * math.acos(lastDeltaOrientation.w))\n print('unk', lastDeltaOrientation.z)\n\n \n\n\n\n\n x = np.linspace(laserScan.angle_min, laserScan.angle_max, 640)\n y = np.array([r for r in laserScan.ranges])\n \n line.set_data(x, y)\n return line,\n\n anim = animation.FuncAnimation(fig, animate, init_func=init,\n frames=1000000, interval=1, blit=True)\n\n plt.show()\"\"\"\n\n\nthread = threading.Thread(target=threadFunc, args=(s, flags))\n\nthread.start()\n\ndef on_release(key):\n if key == keyboard.Key.esc:\n s.send(b'q')\n flags['stop'] = True\n return False\n\n# Collect events until released\nwith keyboard.Listener(\n on_press=on_press,\n on_release=on_release) as listener:\n listener.join()\n","sub_path":"client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":4555,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"227150454","text":"from numpy import *\nimport matplotlib.pyplot as plt\n\nfiles_ = ['imp_N1_d1gam0.010000_H1_dt0.001000.dat','imp_N1_d1gam0.010000_H1_dt0.005000.dat','imp_N1_d1gam0.010000_H1_dt0.010000.dat','imp_N1_d1gam0.010000_H1_dt0.100000.dat','imp_N1_d1gam0.010000_H1_dt1.000000.dat']\n\ndtype1 = [('E', 'f8'), ('V','f8'), ('T', 'f8'), ('A', 'f8')]\ndata_1 = loadtxt(files_[0],dtype=dtype1)\ndata_2 = loadtxt(files_[1], dtype=dtype1)\ndata_3 = loadtxt(files_[2], dtype=dtype1)\ndata_4 = loadtxt(files_[3], dtype=dtype1)\ndata_5 = loadtxt(files_[4], dtype=dtype1)\n\nE_1 = data_1['E']\nE_2 = data_2['E']\nE_3 = data_3['E']\nE_4 = data_4['E']\nE_5 = data_5['E']\n\nlength = len(E_1)\ngdc = linspace(0,length-1,length)\n\nplt.plot(gdc,E_1)\nplt.hold('on')\nplt.plot(gdc,E_2)\nplt.plot(gdc,E_3)\nplt.plot(gdc,E_4)\nplt.plot(gdc,E_5)\n\nplt.xlabel('GDC')\nplt.ylabel('Energy')\nplt.legend(['dt = 0.001','dt = 0.005','dt = 0.01','dt = 0.1','dt = 1.0'])\nplt.show()\n","sub_path":"results/data/imp_dt/plotenergy.py","file_name":"plotenergy.py","file_ext":"py","file_size_in_byte":915,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"301331910","text":"#!/usr/bin/env python\n# -*- coding: iso-8859-15 -*-\n\n# Author: Trestan Pillonel (trestan.pillonel[]gmail.com)\n# Date: 2019\n# ---------------------------------------------------------------------------\n\n\n\ndef locus2ko_table(hash2ko_dico,\n biodatabase,\n ko_accession2ko_id,\n hash2locus_list):\n\n from chlamdb.biosqldb import manipulate_biosqldb\n server, db = manipulate_biosqldb.load_db(biodatabase)\n\n sql2 = 'select locus_tag, seqfeature_id from annotation.seqfeature_id2locus_%s' % biodatabase\n\n locus2seqfeature_id = manipulate_biosqldb.to_dict(server.adaptor.execute_and_fetchall(sql2))\n\n sql2 = 'CREATE TABLE IF NOT EXISTS enzyme.seqfeature_id2ko_%s (seqfeature_id INT,' \\\n ' ko_id INT, ' \\\n ' thrshld FLOAT, ' \\\n ' score FLOAT, ' \\\n ' evalue FLOAT, ' \\\n ' index ko_id (ko_id),' \\\n ' index seqid (seqfeature_id));' % (biodatabase)\n\n server.adaptor.execute_and_fetchall(sql2,)\n\n for hash in hash2ko_dico:\n for locus_tag in hash2locus_list[hash]:\n ko = hash2ko_dico[hash][\"KO\"]\n thrshld = hash2ko_dico[hash][\"thrshld\"]\n score = hash2ko_dico[hash][\"score\"]\n evalue = hash2ko_dico[hash][\"E-value\"]\n if ko not in ko_accession2ko_id:\n print(\"KO %s not in ko_accession2ko_id, it was probably removed from KEGG, skipping...\" % ko)\n else:\n ko_id = ko_accession2ko_id[ko]\n seqfeature_id = locus2seqfeature_id[locus_tag]\n\n sql = 'insert into enzyme.seqfeature_id2ko_%s (seqfeature_id, ko_id, thrshld, score, evalue) values (%s, %s, %s, %s, %s)' % (biodatabase,\n seqfeature_id,\n ko_id,\n thrshld,\n score,\n evalue)\n\n\n server.adaptor.execute(sql,)\n server.commit()\n\n\ndef locus2ko_table_legacy(biodatabase, hash2ko, hash2locus_list):\n # create legacy table locus2ko\n # TODO: remove all depenancies to this table\n # content:\n\n '''\n taxon_id, locus_tag, orthogroup, ko_id (not numerical id but KO*)\n '''\n\n from chlamdb.biosqldb import manipulate_biosqldb\n server, db = manipulate_biosqldb.load_db(biodatabase)\n\n sql = 'select locus_tag, taxon_id from orthology_detail_%s' % biodatabase\n sql2 = 'select locus_tag, orthogroup from orthology_detail_%s' % biodatabase\n\n locus2taxon_id = manipulate_biosqldb.to_dict(server.adaptor.execute_and_fetchall(sql))\n locus2orthogroup = manipulate_biosqldb.to_dict(server.adaptor.execute_and_fetchall(sql2))\n\n sql2 = 'CREATE TABLE IF NOT EXISTS enzyme.locus2ko_%s (taxon_id INT,'\\\n ' locus_tag VARCHAR(200),' \\\n ' orthogroup varchar(200),' \\\n ' ko_id VARCHAR(200), index taxon_id (taxon_id), index ko_id (ko_id));' % (biodatabase)\n\n server.adaptor.execute_and_fetchall(sql2,)\n for hash in hash2ko:\n for locus in hash2locus_list[hash]:\n ko = hash2ko[hash][\"KO\"]\n\n sql = 'insert into enzyme.locus2ko_%s (taxon_id, locus_tag, orthogroup, ko_id) values (\"%s\", \"%s\", \"%s\", \"%s\")' % (biodatabase,\n locus2taxon_id[locus],\n locus,\n locus2orthogroup[locus],\n ko)\n\n server.adaptor.execute(sql,)\n server.commit()\n\n\ndef parse_kofamscan_output(result_file_list):\n hash2ko = {}\n for result_file in result_file_list:\n # # gene name KO thrshld score E-value KO definition\n with open(result_file, 'r') as f:\n for line in f:\n if line.startswith(\"#\"):\n continue\n if line.startswith(\"*\"):\n data = line[2:].strip().split()\n hash2ko[data[0]] = {}\n hash2ko[data[0]][\"KO\"] = data[1]\n hash2ko[data[0]][\"thrshld\"] = data[2]\n hash2ko[data[0]][\"score\"] = data[3]\n hash2ko[data[0]][\"E-value\"] = data[4]\n return hash2ko\n\n\nif __name__ == '__main__':\n import argparse\n from chlamdb.biosqldb import manipulate_biosqldb\n import chlamdb_setup_utils\n\n parser = argparse.ArgumentParser()\n parser.add_argument(\"-k\", '--ko_table_list', type=str, help=\"input blastGhost file\", nargs='+')\n parser.add_argument(\"-d\", '--database_name', type=str, help=\"database name\")\n parser.add_argument(\"-c\", '--corresp_table', type=str, help=\"hash to locus correspondance table\")\n parser.add_argument(\"-l\", '--legacy', action='store_true', help=\"Create legacy table(s)\")\n\n args = parser.parse_args()\n\n hash2locus_list = chlamdb_setup_utils.get_hash2locus_list(args.corresp_table)\n\n server, db = manipulate_biosqldb.load_db(args.database_name)\n sql = 'select ko_accession, ko_id from enzyme.ko_annotation'\n ko_accession2ko_id = manipulate_biosqldb.to_dict(server.adaptor.execute_and_fetchall(sql,))\n\n hash2ko = parse_kofamscan_output(args.ko_table_list)\n\n '''\n locus2ko_table(hash2ko,\n args.database_name,\n ko_accession2ko_id,\n hash2locus_list)\n '''\n \n if args.legacy:\n locus2ko_table_legacy(args.database_name, hash2ko, hash2locus_list)\n","sub_path":"db_setup/chlamdb-load-KO.py","file_name":"chlamdb-load-KO.py","file_ext":"py","file_size_in_byte":6347,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"22498643","text":"from django.shortcuts import render, get_object_or_404, render_to_response, redirect\nfrom django.views.generic import TemplateView, ListView, DetailView\nfrom django.views.decorators.csrf import csrf_exempt, csrf_protect\nfrom upload.models import Book, Upload, OCRResult, AudioBook\nfrom django.core.urlresolvers import reverse, reverse_lazy\nfrom django.http import HttpResponseRedirect, HttpResponse\nfrom django.core.paginator import Paginator\nfrom django.contrib.auth.models import User\nfrom django.contrib import messages\nfrom django.template import RequestContext\nfrom django.db.models import Count\nimport json, requests, os, zipfile, shutil, pathlib as pl\nfrom urllib.parse import urlencode\nfrom httplib2 import Http\nfrom . import settings\nimport time, datetime, logging, sys\n\nlogger = logging.getLogger(__name__)\nLOGGING = {\n 'handlers': {\n 'console': {\n 'level': 'DEBUG',\n 'class': 'logging.StreamHandler',\n 'stream': sys.stdout,\n },\n },\n 'loggers': {\n 'myApp.page_processors': {\n 'handlers': ['console'],\n 'level': 'DEBUG',\n }\n }\n}\n\n\nclass HomePage(TemplateView):\n template_name = \"index.html\"\n\n def get(self, request, *args, **kwargs):\n if request.user.is_authenticated():\n return HttpResponseRedirect(reverse_lazy(\"user_home\"))\n return super().get(request, *args, **kwargs)\n\n\nclass BookDetailsView(DetailView):\n template_name = 'book_details.html'\n model = Book\n\n def get_queryset(self):\n return Book.objects.all()\n\n\nclass UserHomePage(ListView):\n model = Book\n template_name = 'user_home.html'\n paginate_by = 10\n\n def get_queryset(self):\n try:\n book = Book.objects.all()\n except Exception:\n print(\"No book is present.\")\n book = []\n return book\n\n\nclass ViewLibrary(ListView):\n model = AudioBook\n template_name = 'my_library.html'\n paginate_by = 10\n\n def get_queryset(self):\n return AudioBook.objects.filter(username__exact=self.request.user.id)\n\n\nclass EditorPage(TemplateView):\n template_name = 'editor.html'\n\n def get_context_data(self):\n context = {}\n bookid = self.request.GET.get('bookid')\n title = Book.objects.get(id=bookid).title\n\n try:\n if Upload.objects.filter(book__id=bookid, processed=False).count():\n pages = Upload.objects.filter(book__id=bookid,\n processed=False).order_by('page_number')\n page_number = pages.values()[0]['page_number']\n else:\n page_number = Upload.objects.filter(book__id=bookid).count()\n except Exception as e:\n print(\"An error occured when finding the page number, taking default: \", e)\n page_number = Upload.objects.filter(book__id=bookid).count()\n count = Upload.objects.filter(book__id=bookid).count()\n if page_number == 1:\n page_position = 'first'\n elif page_number == count:\n page_position = 'last'\n else:\n page_position = 'intermediate'\n all_processed = int(Upload.objects.filter(book__id=bookid, processed=False).count() == 0)\n context['title'] = title\n context['bookid'] = bookid\n context['page_number'] = page_number\n pages = Upload.objects.filter(book__id=bookid, processed=False)\n context['pages'] = pages\n context['all_processed'] = all_processed\n context['page_position'] = page_position\n if all_processed:\n context['is_final_page'] = 1\n\n return context\n\n\nclass SingleEditorPage(TemplateView):\n template_name = 'single_page_editor.html'\n\n def get_context_data(self, pk):\n context = {}\n title = Book.objects.get(id=pk).title\n context['title'] = title\n context['bookid'] = pk\n return context\n\n\nclass ThanksPage(TemplateView):\n template_name = 'thanks.html'\n\n\nclass DownloadSuccess(TemplateView):\n template_name = 'download_success.html'\n\n\ndef get_mp3_files(bookname):\n # ts = time.time()\n # now = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d_%H:%M:%S')\n p = pl.Path(settings.MEDIA_ROOT + '/archive/' + bookname + '/daisy202/')\n allfiles = [settings.MEDIA_URL + 'archive/' + bookname + '/daisy202/' + os.path.basename(x)\n for x in [str(x) for x in list(p.glob('**/*.mp3'))] if 'tpbnarrator_res.mp3' not in x]\n allfiles = ','.join(allfiles)\n return allfiles\n\n\ndef save_audio_to_db(request):\n bookid = request.GET.get('data', '')\n audiobook = AudioBook()\n book = Book.objects.get(id=bookid)\n audiobook.book = book\n user = User.objects.get(id=request.user.id)\n audiobook.username = user\n # string = ''\n bookname = '_'.join(book.title.split(' '))\n audiobook.download_url = get_mp3_files(bookname)\n audiobook.save()\n mimetype = 'application/json'\n return HttpResponse(json.dumps({\"status\": 200}), mimetype)\n\n\ndef get_books(request):\n if request.is_ajax():\n q = request.GET.get('term', '')\n books = Book.objects.filter(title__icontains=q)[:20]\n results = []\n for book in books:\n book_json = {}\n book_json['id'] = book.id\n book_json['label'] = book.title\n book_json['value'] = book.title\n results.append(book_json)\n data = json.dumps(results)\n else:\n data = 'fail'\n mimetype = 'application/json'\n return HttpResponse(data, mimetype)\n\n\ndef get_audiobooks(request):\n if request.is_ajax():\n q = request.GET.get('term', '')\n audiobooks = AudioBook.objects.filter(book__title__icontains=q)[:20]\n results = []\n for book in audiobooks:\n book_json = {}\n book_json['id'] = book.id\n book_json['label'] = book.title\n book_json['value'] = book.title\n results.append(book_json)\n data = json.dumps(results)\n else:\n data = 'fail'\n mimetype = 'application/json'\n return HttpResponse(data, mimetype)\n\n\ndef get_book_id_from_name(request):\n bookname = request.POST.get('bookname', '')\n book_id = Book.objects.filter(title__exact=bookname).values('id')[0]['id']\n context = {}\n context['book_id'] = book_id\n mimetype = 'application/json'\n return HttpResponse(json.dumps(context), mimetype)\n\n\ndef get_audiobook_id_from_name(request):\n bookname = request.POST.get('audiobook_name', '')\n audiobook_id = AudioBook.objects.filter(book__title__exact=audiobook_name).values('id')[0]['id']\n context = {}\n context['audiobook_id'] = audiobook_id\n mimetype = 'application/json'\n return HttpResponse(json.dumps(context), mimetype)\n\n\ndef get_pre_loaded_xml(ocrtext, page_position, bookname, page_number=1):\n xmlpage_1_start = \"\"\"\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n {}\n Vikram\n \n \n \n {}\n

\n \"\"\".format(bookname, bookname, page_number, page_number)\n\n xmlpage_1_end = \"\"\"

\n \"\"\"\n\n xmlpage_last_start = \"\"\"\n {}\n

\n \"\"\".format(page_number, page_number)\n\n xmlpage_last_end = \"\"\"

\n
\n
\n
\n
\n \"\"\"\n\n xmlpage_int_start = \"\"\"{}\n

\n \"\"\".format(page_number, page_number)\n\n xmlpage_int_end = \"\"\"\n

\n \"\"\"\n\n if page_position == 'first':\n xmltext = xmlpage_1_start + \"\\n\" + ocrtext + \"\\n\" + xmlpage_1_end\n elif page_position == 'last':\n xmltext = xmlpage_last_start + \"\\n\" + ocrtext + \"\\n\" + xmlpage_last_end\n elif page_position == 'intermediate':\n xmltext = xmlpage_int_start + \"\\n\" + ocrtext + \"\\n\" + xmlpage_int_end\n return xmltext\n\n\ndef get_text_data_of_the_image(image, page_number, bookname, page_position='intermediate', media_url=''):\n print(\"image: {} and media_url: {} \".format(image, media_url))\n input_image = media_url + image\n output_path = \"/home/iiit/data/tts_out\"\n payload = {\"input_image\": input_image, \"output_path\": output_path}\n j = {\"xml\": \"The OCR could not be completed, there has been some error. \"}\n print(\"The payload is: \", payload)\n # url = \"http://127.0.0.1:5000/get_ocr_output\"\n url = \"http://10.2.16.111:5000/get_ocr_output\"\n session = requests.Session()\n session.trust_env = False\n try:\n print(\"Got the request. \")\n r = session.post(url, data=payload)\n print(\"Response: \", r.content.decode())\n j = json.loads(r.text)\n print(j)\n j[\"xml\"] = get_pre_loaded_xml(j[\"ocr_text\"], page_position, bookname, page_number)\n except Exception as e:\n print(\"Error message is: \" + str(e))\n return j[\"xml\"]\n\n\ndef append_xml_data(bookid, data):\n print(\"Appending data to daisy xml. \")\n book = Book.objects.get(id=bookid)\n if book.daisy_xml == '' or book.daisy_xml is None:\n daisy_xml = data\n else:\n daisy_xml = book.daisy_xml + \"\\n\" + data\n book.daisy_xml = daisy_xml\n book.save()\n return daisy_xml\n\n\ndef get_full_daisy_xml(bookid):\n daisy_xml = ''\n try:\n book = Book.objects.get(id=bookid)\n daisy_xml = book.daisy_xml\n except Exception:\n print(\"The book id could not be found. \", bookid)\n daisy_xml = None\n return daisy_xml\n\n\ndef get_bookname_from_id(bookid):\n bookname = ''\n try:\n book = Book.objects.get(id=bookid)\n bookname = book.title\n except Exception:\n print(\"The book could not be found. \", bookid)\n bookname = None\n return bookname\n\n\ndef load_image_and_text(request):\n data = {}\n bookid = request.GET.get('bookid', '')\n save_option = request.GET.get('saveOption', '')\n print(\"SAVE OPTION\", save_option)\n page_number = int(request.GET.get('page_number', ''))\n logger.debug(\"The current page loaded is: \", page_number)\n if page_number == '' or page_number is None:\n page_number = 1\n logger.debug(\"The book id in the request is: {}\".format(bookid))\n context = {}\n\n # There is a need to check if more pages are present\n page_id = Upload.objects.filter(book__id=bookid, processed=False).order_by('page_number').values()[0]['id']\n logger.debug(\"The corresponding page_id is: {}\".format(page_id))\n image = Upload.objects.filter(id=page_id).values('image')[0]['image']\n media_url = settings.MEDIA_URL\n media_root = settings.MEDIA_ROOT + \"/\"\n logger.debug(\"The image path is: {}\".format(image))\n if OCRResult.objects.filter(image_id=page_id):\n text = OCRResult.objects.filter(image_id=page_id).values('result')[0]['result']\n else:\n text = \"OCR is not complete. \"\n count = Upload.objects.filter(book__id=bookid).count()\n if page_number == 1:\n page_position = 'first'\n elif page_number == count:\n page_position = 'last'\n else:\n page_position = 'intermediate'\n print(\"This page is: \", page_position)\n print(\"page number: {}, count: {}\".format(page_number, count))\n bookname = get_bookname_from_id(bookid)\n test_text = get_text_data_of_the_image(image, page_number, bookname, page_position)\n print(\"Finished getting the text data for the image. \")\n\n if len(test_text):\n text = test_text\n\n context['bookid'] = bookid\n context['text'] = text\n context['title'] = get_bookname_from_id(bookid)\n context['daisy_xml'] = get_full_daisy_xml(bookid)\n context[\"img\"] = image\n context[\"media_url\"] = media_url\n context[\"page_position\"] = page_position\n context[\"all_processed\"] = '0'\n\n mimetype = 'application/json'\n return HttpResponse(json.dumps(context), mimetype)\n\n\ndef get_page_xml(bookid, page_number):\n page_xml = ''\n try:\n page = Upload.objects.get(book__id=bookid, page_number=page_number)\n page_xml = page.xmldata\n except Exception as e:\n print(\"The book id could not be found. \", bookid)\n return page_xml\n\n\ndef load_full_xml_to_editor(request):\n bookid = request.GET.get('bookid', '')\n page_number = request.GET.get('page_number', '')\n save_option = request.GET.get('saveOption', '')\n\n context = {}\n context[\"all_processed\"] = '1'\n context[\"daisy_xml\"] = get_full_daisy_xml(bookid)\n\n mimetype = 'application/json'\n return HttpResponse(json.dumps(context), mimetype)\n\n\ndef zipdir(path, ziph):\n all_files = []\n for root, dirs, files in os.walk(path):\n for f in files:\n # ziph.write(os.path.basename(os.path.join(root, f)))\n ziph.write(os.path.join(root, f), os.path.join(\"daisy202\", os.path.basename(os.path.join(root, f))))\n del all_files\n\n\ndef zipdir2(output_filename, input_dir):\n shutil.make_archive(output_filename, 'zip', input_dir)\n\n\n@csrf_exempt\ndef update_daisy_xml(request):\n bookid = request.POST.get('bookid', '')\n data = request.POST.get('data', '')\n try:\n book = Book.objects.get(id=bookid)\n book.completed = True\n book.save()\n except Exception as e:\n print(\"The book could not be saved. \" + str(e))\n mimetype = 'application/json'\n return HttpResponse(json.dumps({\"status\": \"200\", \"message\": \"success\"}), mimetype)\n\n\n@csrf_exempt\ndef download(request):\n title = request.GET.get(\"title\")\n zipf = zipfile.ZipFile(settings.MEDIA_ROOT + '/archive/' + title + '.zip', 'w', zipfile.ZIP_DEFLATED)\n zipdir(settings.MEDIA_ROOT + '/archive/' + title + \"/daisy202/\", zipf)\n zipf.close()\n messages.info(request, 'The file has been downloaded. ')\n return HttpResponse({\"status\": \"success\"})\n\n\n@csrf_exempt\ndef mark_page_as_processed(request):\n print(\"Marking this page as processed and saving the xmldata. \")\n book_id = request.POST.get('bookid', '')\n page_number = request.POST.get('pagenumber', '')\n xml_data = request.POST.get('xmldata', '')\n try:\n print(\"Page number from request is: \", page_number)\n upload = Upload.objects.get(book__id=book_id, page_number=page_number)\n upload.processed = True\n upload.xmldata = xml_data\n upload.save()\n append_xml_data(book_id, xml_data)\n except Exception as e:\n print(\"The record for book_id='{}' and page_number='{}' does not exist. \"\n .format(book_id, page_number))\n print(\"Error message for saving book is\", str(e))\n print(\"The page '{}' has been saved successfully. \".format(page_number))\n mimetype = 'application/json'\n return HttpResponse(json.dumps({\"url\": \"/edit/?bookid=\"+book_id}), mimetype)\n\n\n# References\n# File download\n# https://stackoverflow.com/questions/36392510/django-download-a-file\n#\n# Serve mp3 files\n# https://stackoverflow.com/questions/28113220/django-how-to-serve-mp3-files\n#\n# General archive\n# https://simpleisbetterthancomplex.com/archive/\n","sub_path":"ttsdaisy_v4/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":15750,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"634736359","text":"# -*- coding: utf-8 -*-\n##############################################################################\n#\n# NCTR, Nile Center for Technology Research\n# Copyright (C) 2011-2012 NCTR ().\n#\n##############################################################################\n\nfrom openerp import netsvc\nfrom openerp.tools.translate import _\nfrom openerp.osv import fields, osv, orm\nimport openerp.addons.decimal_precision as dp\n\nclass account_budget_operation(osv.Model):\n \"\"\"\n Account Budget Operation.\n Allow accountant to transfer special amount from multiple budget lines to another for plan budgets, Beside budget increase operation. \n \"\"\"\n _name = \"account.budget.operation\"\n \n _description = 'Budget Operations'\n\n def _get_period(self, cr, uid, context=None):\n \"\"\"\n\t\tMethod to get period ID\n\n @return: period ID or False\n \"\"\"\n periods = self.pool.get('account.period').find(cr, uid, context=context)\n return periods and periods[0] or False\n\n _columns = {\n 'name': fields.char('Name', size=64, required=True),\n \n 'type': fields.selection([('transfer', 'Transfer'), ('increase', 'Increase')],'Operation Type', \n required=True, readonly=True, states={'draft':[('readonly', False)]}),\n \n 'from_company_id': fields.many2one('res.company', 'Details Company', required=True, readonly=True, \n states={'draft':[('readonly', False)]}),\n\n 'analytic_account_id': fields.many2one('account.analytic.account', 'Cost Center', required=True, \n readonly=True, states={'draft':[('readonly', False)]}),\n\n 'company_id': fields.many2one('res.company', 'Company', required=True, readonly=True, \n states={'draft':[('readonly', False)]}),\n\n 'account_id': fields.many2one('account.account', 'Account', required=True, readonly=True, \n states={'draft':[('readonly', False)]}),\n\n 'period_id': fields.many2one('account.period', 'Period', required=True, readonly=True, \n states={'draft':[('readonly', False)]}),\n \n 'amount':fields.float('Amount', digits_compute=dp.get_precision('Account'), readonly=True, \n states={'draft':[('readonly', False)]}, help=\"If the it's positive that's mean the amount will increase this budget or it will decrease it.\"),\n\n 'budget_line': fields.many2one('account.budget.lines', 'Budget Line'),\n \n 'line_ids': fields.one2many('account.budget.operation.line', 'operation_id', 'Details',\n readonly=True, states={'draft':[('readonly', False)]}),\n \n 'state' : fields.selection([('draft', 'Draft'), ('complete', 'Waiting for Financial Manager Confirm'), \n ('confirm', 'Waiting for General Manager Approve'), ('approve', 'Waiting for Execution'),\n ('done','Done'), ('cancel', 'Canceled')], 'Status', required=True, readonly=True),\n }\n\n _defaults = {\n 'name': '/',\n 'state': 'draft',\n 'type': 'transfer',\n 'from_company_id': lambda self, cr, uid, context: self.pool.get('res.users').browse(cr, uid, uid, context=context).company_id.id,\n 'company_id': lambda self, cr, uid, context: self.pool.get('res.users').browse(cr, uid, uid, context=context).company_id.id,\n } \n _sql_constraints = [('amount_check', \"CHECK ( (type='transfer') OR (amount > 0) )\", _(\"Wrong amount, they must be positive\")),\n \n ]\n def unlink(self, cr, uid, ids, context = None):\n for s in self.read(cr, uid, ids, ['state'], context = context):\n if s['state'] != 'draft':\n raise orm.except_orm(_('Invalid action !'), _('Can not delete none draft operation !'))\n return super(account_budget_operation, self).unlink(cr, uid, ids, context = context)\n\n def onchange_company_id(self, cr, uid, ids, company):\n \"\"\" \n\t\tOn change method when change the from/to company fields then \n reset from_budget_line to False when from_company_id changed\n reset fields corresponding to company_to when to_company_id changed\n \n @param company: char 'from' or 'to'\n @return: dictionary of values to be change\n \"\"\"\n return {'value': company == 'from' and {'from_budget_line':False} or\n {'analytic_account_id':False, 'account_id':False, \n 'period_id':self._get_period(cr, uid)}}\n\n def onchange_line_ids(self, cr, uid, ids, line_ids):\n \"\"\" \n\t\tOn change used to update to_amount when any change happened in \n the account.budget.operation.line corresponding to account.budget.operation\n record\n \n @param line_ids: list of tuple of the all operation line values\n @return: dictionary of to_amount value to be change\n \"\"\"\n return {'value': {'amount': sum([l[2]['amount'] for l in line_ids if l[2]])}}\n\n def onchange_ttype(self, cr, uid, ids, ttype):\n line_pool = self.pool.get('account.budget.operation.line')\n if ttype=='increase':\n line_ids = ids and line_pool.search(cr, uid, [('operation_id', '=', ids[0])]) or False\n if line_ids:\n line_pool.unlink(cr, uid, line_ids)\n return{'value': {'line_ids': [] } }\n return True\n \n def action_cancel_draft(self, cr, uid, ids,context=None):\n \"\"\"\n Workflow function change record state to 'draft', \n delete old workflow instance and create new one \n @return: boolean True \n \"\"\"\n if not isinstance(ids,list): \n ids = [ids]\n self.write(cr, uid, ids, {'state': 'draft'}, context=context)\n wf_service = netsvc.LocalService(\"workflow\")\n for id in ids:\n wf_service.trg_delete(uid, 'account.budget.operation', id, cr)\n wf_service.trg_create(uid, 'account.budget.operation', id, cr)\n return True\n \n def copy(self, cr, uid, ids, default={}, context=None):\n \"\"\"Inherit copy method to reset name to /.\n \n @return: super copy method\n \"\"\"\n default.update({'name': '/'})\n return super(account_budget_operation, self).copy(cr, uid, ids, default=default, context=context)\n \n def complete(self, cr, uid, ids, context={}):\n \"\"\"\n Workflow function change state to complete and compute amount value & set operation number\n @return: True\n \"\"\"\n budget_pool = self.pool.get('account.budget')\n budget_line_pool = self.pool.get('account.budget.lines')\n for r in self.browse(cr, uid, ids, context=context):\n if r.type=='transfer' and not r.line_ids:\n raise osv.except_osv(_('Error!'),_('You cannot complete Transfer Operations without any Budget line.'))\n budget_ids = budget_pool.search(cr, uid,[('analytic_account_id', '=', r.analytic_account_id.id), \n ('period_id', '=', r.period_id.id)], context=context)\n budget_line_id = budget_line_pool.search(cr, uid,[('general_account_id', '=', r.account_id.id), \n ('account_budget_id', 'in', tuple(budget_ids))], context=context)\n if budget_line_id:\n line=budget_line_pool.browse(cr, uid, budget_line_id, context=context)[0]\n if line.residual_balance + r.amount <=0:\n raise orm.except_orm(_('Error!'),\n _(\"The amount you try to transfer (%s) is more than %s residual (%s)!\") % \\\n (r.amount, line.name, line.residual_balance,))\n for e in r.line_ids:\n if e.line_id.residual_balance - e.amount <0:\n raise orm.except_orm(_('Error!'),\n _(\"The amount you try to transfer (%s) is more than %s residual (%s)!\") % \\\n (e.amount, e.line_id.name, e.line_id.residual_balance,))\n self.write(cr, uid, ids,{'state':'complete','name': r.name == '/' and \n self.pool.get('ir.sequence').get(cr, uid, 'account.budget.operation') or \n r.name, 'amount': r.type=='increase' and r.amount or sum([l.amount for l in r.line_ids])}, context=context)\n return True\n\n def done(self, cr, uid, ids, context=None):\n \"\"\"\n Execute the operation by calling transfer function in budget line and change state to done.\n \"\"\"\n budget_line = self.pool.get('account.budget.lines')\n budget_line_id = False\n for r in self.browse(cr, uid, ids, context=context):\n to = {'analytic_account': r.analytic_account_id.id,\n 'account_id': r.account_id.id,\n 'period_id': r.period_id.id,\n 'company': r.company_id.id,\n 'amount' : r.amount\n }\n budget_line_id,history_ids=budget_line.transfer(cr, uid, {'type':r.type, 'line_ids': r.line_ids, 'to':to, 'reference':self._name+','+str(r.id)}, context=context)\n return self.write(cr, uid, ids,{'state':'done', 'budget_line':budget_line_id}, context=context)\n\n\nclass account_budget_line_ids(osv.Model):\n \"\"\"\n Budget lines which want to transfer from and the amount to transfer from each one. \n \"\"\"\n _name = \"account.budget.operation.line\"\n \n _description = 'Budget Line Transfer From'\n\n def _check_amount(self, cr, uid, ids, context=None):\n \"\"\"\n\t\tConstrain method to prohibit user from entering negative number.\n\n @return: Boolean True or False\n \"\"\"\n\n for line in self.browse(cr, uid, ids, context=context):\n if line.amount<=0:\n return False\n return True\n\n _columns = {\n 'line_id': fields.many2one('account.budget.lines', 'Budget Line', required=True),\n\n 'amount':fields.float('Amount', digits_compute=dp.get_precision('Account'), required=True,\n help=\"If the it's positive that's mean the amount will transfer from this budget to the main one and vice versa.\"),\n\n 'operation_id': fields.many2one('account.budget.operation', 'Operation'),\n }\n\n _constraints = [\n (_check_amount, 'Wrong amount, they must be positive!', ['amount']),\n ]\n\nclass budget_operation_history(osv.Model):\n \n _inherit = \"account.budget.operation.history\"\n \n _columns = {\n 'reference': fields.reference('Event Ref', selection=[('account.budget.operation', 'account.budget.operation')],size=128),\n }\n\n def unlink(self, cr, uid, ids, context = None):\n for s in self.read(cr, uid, ids, ['reference'], context = context):\n if s['reference'] is not None:\n raise orm.except_orm(_('Invalid action !'), _('Can not delete operation history while it has a related operation !'))\n return super(budget_operation_history, self).unlink(cr, uid, ids, context = context)\n \n \n# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:\n","sub_path":"v_7/NISS/common_shamil_v3/account_budget_custom/account_budget_operation.py","file_name":"account_budget_operation.py","file_ext":"py","file_size_in_byte":11363,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"379158966","text":"# Author: Raj Agrawal \n\n# The following script reads in all images stored in a root directory and converts \n# the images to an array.\n\n# Run $ffmpeg -i NAME.MOV -r 20 ../data/train/images/image_sequence%d.jpeg from\n# code folder to generate images in the training images folder\n\nfrom __future__ import division \n\nimport os\nimport glob\nimport numpy as np\nimport pandas as pd \n\nfrom scipy.misc import imread \nfrom scipy.ndimage.interpolation import zoom\n\ndef readImage(path, reduction_factor=.15):\n \"\"\"\n Overview: \n Reduces photo size by a factor of 1/reduction_factor \n and converts to greyscale \n ----------\n path: string \n Path where the image is is located. \n \n reduction_factor: float\n Defaults to .15. reduction_factor > 1 enlarges the photo and \n reduction_factor < 1 shrinks the photo. \n\n Returns\n -------\n reduced_image: numpy array \n Grayscaled and resized image \n \"\"\"\n grey_image = imread(path, flatten=True)\n return zoom(grey_image, reduction_factor)\n\ndef to3DMatrix(paths, imgsize=(81, 144), reduction_factor=.15):\n \"\"\"\n Overview: \n Reduces images size by a factor of 1/reduction_factor \n and converts to greyscale and stores in an array of\n shape (len(paths), length, width). \n ----------\n paths: list \n List consisting of paths where the images are located. See \n\n imgsize: tuple\n The (length,width) of image and defaults to (81, 144). \n \n reduction_factor: float\n Defaults to .15. reduction_factor > 1 enlarges the photo and \n reduction_factor < 1 shrinks the photo. \n\n Returns\n -------\n images_by_time: numpy array \n Grayscaled and resized images of shape \n (len(paths), length, width) \n \"\"\"\n num_images = len(paths)\n images_by_time = np.zeros(shape=(num_images, imgsize[0], imgsize[1])) \n for i, path in enumerate(paths):\n image = readImage(path, reduction_factor)\n images_by_time[i, :, :] = image\n print('Finished Processing image ' + str(i))\n return images_by_time\n\ndef toMatrix(paths, num_frames, imgsize=(81, 144), reduction_factor=.15):\n \"\"\"\n Overview: \n Reduces images size by a factor of 1/reduction_factor \n and converts to greyscale. Each 'sample' is of shape \n num_frames x imgsize. This aggregates all samples into \n a numpy array. \n ----------\n paths: list \n List consisting of paths where the images are located. See \n ** Note ** below \n\n num_frames: int \n The number of images in one sample\n\n imgsize: tuple\n The (length,width) of image and defaults to (81, 144). \n \n reduction_factor: float\n Defaults to .15. reduction_factor > 1 enlarges the photo and \n reduction_factor < 1 shrinks the photo. \n\n Returns\n -------\n images_by_time: numpy array \n Grayscaled and resized images of shape \n (num_samples, num_frames, length, width)\n\n Note: \n This ASSUMES that the paths are in the right order. In other words, \n if paths = [im1, im2, im3, im4] and num_frames = 2 this means sample\n 1 is [im1, im2] and sample 2 is [im3, im4]. \n \"\"\"\n num_images = len(paths)\n num_samples = int(num_images / num_frames)\n images_by_time = np.zeros(shape=(num_samples, num_frames, imgsize[0], imgsize[1])) \n for sample_index in range(num_samples):\n index_in_array = sample_index * num_frames\n sample_paths = paths[index_in_array:(num_frames + index_in_array)]\n sample = to3DMatrix(sample_paths, imgsize, reduction_factor)\n images_by_time[sample_index, :, :, :] = sample \n print('Finished Processing Sample ' + str(sample_index))\n return images_by_time\n\ndef toDurations(stopped_times_list):\n to_seconds = []\n for time in stopped_times_list:\n print(time)\n mins, secs = time.split(':') \n if mins == '':\n mins = 0\n to_sec = int(mins) * 60 + int(secs) \n to_seconds.append(to_sec)\n num_times = len(to_seconds)\n from_zero = [0] + to_seconds[0:(num_times - 1)]\n time_diffs = np.array(to_seconds) - np.array(from_zero)\n return time_diffs\n\ndef makeLabels(file_label, samps_per_sec=2):\n \"\"\"\n Frames happen every .05 seconds, one sample corresponds w/ 10 frames or\n 2 samples / seconds\n \"\"\"\n labels_by_time = pd.read_csv(file_label, header=None)\n to_durations = toDurations(list(labels_by_time[1]))\n labels_per_phase = list(labels_by_time[0])\n num_samps_per_sec = to_durations * samps_per_sec\n sample_labels = []\n for i, label in enumerate(labels_per_phase):\n num_samps = num_samps_per_sec[i]\n sample_labels += list(np.tile(label, num_samps))\n return np.array(sample_labels)\n\ndef makePaths(folder_root):\n \"\"\"\n Returns the paths of all files in the folder_root \n \"\"\"\n return glob.glob(os.path.join(folder_root, '*'))\n\ndef makeOrderedPaths(folder_root, num_pics):\n \"\"\"\n Returns the paths of all files in the folder_root but keeping frames in \n temporal order \n \"\"\"\n paths = [folder_root + '/image_sequence' + str(i) + '.jpeg' for i in range(1, num_pics + 1)]\n return paths\n\nif __name__ == '__main__':\n\n path_to_images = '../data/train/images'\n path_to_lables = '../data/train/video_labels.csv'\n \n # Read in video data/labels\n labels = makeLabels(path_to_lables, samps_per_sec=2) \n num_pics = len(makePaths(path_to_images))\n paths = makeOrderedPaths(path_to_images, num_pics)\n images_by_time = toMatrix(paths=paths, num_frames=10)\n \n # Shuffle data\n # Check to make sure this matches images_by_time --> might need to pad ends w/ extra labels \n # num_samples = images_by_time.shape[0]\n # indcs = np.arange(num_samples)\n # np.random.shuffle(indcs)\n # images_by_time = images_by_time[indcs]\n # labels = labels[indcs]\n\n # Save in data folder \n np.save('../data/train/images_by_time_mat', images_by_time)\n np.save('../data/train/labels', labels)\n","sub_path":"texting_driving/code/images_to_matrix.py","file_name":"images_to_matrix.py","file_ext":"py","file_size_in_byte":6044,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"92669847","text":"# 给你两个单链表的头节点 headA 和 headB ,请你找出并返回两个单链表相交的起始节点。如果两个链表不存在相交节点,返回 null 。 \n# \n# 图示两个链表在节点 c1 开始相交: \n# \n# \n# \n# 题目数据 保证 整个链式结构中不存在环。 \n# \n# 注意,函数返回结果后,链表必须 保持其原始结构 。 \n# \n# 自定义评测: \n# \n# 评测系统 的输入如下(你设计的程序 不适用 此输入): \n# \n# \n# intersectVal - 相交的起始节点的值。如果不存在相交节点,这一值为 0 \n# listA - 第一个链表 \n# listB - 第二个链表 \n# skipA - 在 listA 中(从头节点开始)跳到交叉节点的节点数 \n# skipB - 在 listB 中(从头节点开始)跳到交叉节点的节点数 \n# \n# \n# 评测系统将根据这些输入创建链式数据结构,并将两个头节点 headA 和 headB 传递给你的程序。如果程序能够正确返回相交节点,那么你的解决方案将被 视\n# 作正确答案 。 \n# \n# \n# \n# 示例 1: \n# \n# \n# \n# \n# 输入:intersectVal = 8, listA = [4,1,8,4,5], listB = [5,6,1,8,4,5], skipA = 2, sk\n# ipB = 3\n# 输出:Intersected at '8'\n# 解释:相交节点的值为 8 (注意,如果两个链表相交则不能为 0)。\n# 从各自的表头开始算起,链表 A 为 [4,1,8,4,5],链表 B 为 [5,6,1,8,4,5]。\n# 在 A 中,相交节点前有 2 个节点;在 B 中,相交节点前有 3 个节点。\n# \n# \n# 示例 2: \n# \n# \n# \n# \n# 输入:intersectVal = 2, listA = [1,9,1,2,4], listB = [3,2,4], skipA = 3, skipB = \n# 1\n# 输出:Intersected at '2'\n# 解释:相交节点的值为 2 (注意,如果两个链表相交则不能为 0)。\n# 从各自的表头开始算起,链表 A 为 [1,9,1,2,4],链表 B 为 [3,2,4]。\n# 在 A 中,相交节点前有 3 个节点;在 B 中,相交节点前有 1 个节点。\n# \n# \n# 示例 3: \n# \n# \n# \n# \n# 输入:intersectVal = 0, listA = [2,6,4], listB = [1,5], skipA = 3, skipB = 2\n# 输出:null\n# 解释:从各自的表头开始算起,链表 A 为 [2,6,4],链表 B 为 [1,5]。\n# 由于这两个链表不相交,所以 intersectVal 必须为 0,而 skipA 和 skipB 可以是任意值。\n# 这两个链表不相交,因此返回 null 。\n# \n# \n# \n# \n# 提示: \n# \n# \n# listA 中节点数目为 m \n# listB 中节点数目为 n \n# 1 <= m, n <= 3 * 104 \n# 1 <= Node.val <= 105 \n# 0 <= skipA <= m \n# 0 <= skipB <= n \n# 如果 listA 和 listB 没有交点,intersectVal 为 0 \n# 如果 listA 和 listB 有交点,intersectVal == listA[skipA] == listB[skipB] \n# \n# \n# \n# \n# 进阶:你能否设计一个时间复杂度 O(m + n) 、仅用 O(1) 内存的解决方案? \n# Related Topics 哈希表 链表 双指针 \n# 👍 1783 👎 0\n\n\n# leetcode submit region begin(Prohibit modification and deletion)\n# 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 getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode:\n la, lb = 0,0\n ptra,ptrb = headA,headB\n while ptra:\n ptra = ptra.next\n la+=1\n while ptrb:\n ptrb = ptrb.next\n lb+=1\n\n for i in range(la-lb):\n headA = headA.next\n for i in range(lb-la):\n headB = headB.next\n while headA and headB:\n if headA==headB:\n return headA\n headA = headA.next\n headB = headB.next\n return None\n \n# leetcode submit region end(Prohibit modification and deletion)\n","sub_path":"script/[160]相交链表.py","file_name":"[160]相交链表.py","file_ext":"py","file_size_in_byte":3668,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"563024442","text":"# encoding: utf8\nfrom __future__ import unicode_literals\nfrom __future__ import print_function\n\nimport os\nimport sys\nimport subprocess\nimport shutil\nimport re\nimport logging\nfrom datetime import datetime\n\nfrom .git import git, get_changes_from, create_version_tag, push_tags\nfrom .text_manipulation import preprocess_commit_messages\nfrom ello.project import ProjectMetadata\n\nlogger = logging.getLogger()\n\nCHANGELOG_FILE = 'CHANGELOG.txt'\nTMP_CHANGELOG_FILE = os.environ.get('TEMP') + '\\\\ell_changelog.tmp'\n\n\ndef make_changelog(args):\n logger.info(\"Atualizando CHANGELOG.txt\")\n\n if not os.path.isfile(CHANGELOG_FILE):\n touch_file(CHANGELOG_FILE)\n\n metadata = ProjectMetadata()\n previous_version = get_previous_version(metadata.version_tag)\n new_version = metadata.version_tag\n\n changes = get_changes_from(previous_version)\n changes = preprocess_commit_messages(changes)\n generate_temp_changelog(metadata.version, changes)\n\n merge_temp_with_changelog()\n\n # Atualiza informações no repositório\n commit_changelog(new_version)\n create_version_tag(new_version)\n \n if not args.no_push:\n push_tags()\n\n\ndef commit_changelog(version):\n logger.info(\"Criando commit de atualização de versão...\")\n git('add ' + CHANGELOG_FILE)\n git('commit -am \"Atualização do changelog ({0})\" '.format(version))\n\n\ndef get_previous_version(version):\n version_list = version.split('.')\n previous_build_number = int(version_list[-1], 10) - 1\n version_list[-1] = str(previous_build_number)\n return '.'.join(version_list)\n\n\ndef generate_temp_changelog(version, changes):\n current_date = datetime.now().strftime(\"%d/%m/%Y\")\n headline = \"{} - Revisão {}\\n\".format(current_date, version)\n with open(TMP_CHANGELOG_FILE, 'w', encoding='latin1') as f:\n f.write(headline)\n f.write(\"\\n\")\n for line in changes:\n # As instruções de codificação são para corrigir caracteres que não são\n # aceitos no encoding Latin-1\n f.write(line.encode('latin1', errors='replace').decode('latin1'))\n f.write(\"\\n\")\n f.write(\"\\n\")\n\n\ndef merge_temp_with_changelog():\n filenames = [TMP_CHANGELOG_FILE, CHANGELOG_FILE]\n with open('result.txt', 'w') as outfile:\n for fname in filenames:\n with open(fname) as infile:\n for line in infile:\n outfile.write(line)\n shutil.copyfile('result.txt', 'CHANGELOG.txt')\n os.remove('result.txt')\n\n\ndef latest_changes_text():\n \"\"\"Retorna o texto da última modificação do changelog\"\"\"\n changelog_header = re.compile('\\d{2}/\\d{2}/\\d{4} - ')\n lines = []\n with open('CHANGELOG.txt') as changelog:\n lines.append(changelog.readline())\n for line in changelog:\n match = changelog_header.search(line)\n if match:\n break\n lines.append(line)\n return ''.join(lines)\n\n\ndef touch_file(fname):\n with open(fname, 'a'):\n os.utime(fname, None)","sub_path":"ello/sdk/changelog.py","file_name":"changelog.py","file_ext":"py","file_size_in_byte":3020,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"335614716","text":"from time import time\nimport uuid\nimport rsa\nfrom rsa import VerificationError\nfrom api.schema.transaction import TransactionSchema\n\n\nclass Transaction:\n def __init__(self,\n id: str = None,\n sender: str = None,\n recipient: str = None,\n amount: float = None,\n signature: str = None,\n public_key: str = None):\n if not id:\n id = uuid.uuid4().hex\n self.id = id\n self.sender = sender\n self.recipient = recipient\n self.timestamp = time()\n self.amount = amount\n self.signature = signature\n self.public_key = public_key\n\n def validate(self):\n if self.amount <= 0:\n return False\n if not self.recipient:\n return False\n if not self.sender:\n return False\n if self.recipient == self.sender:\n return False\n if not self.verify_signature():\n return False\n return True\n\n def serialize(self, ignore=None):\n if ignore is None:\n ignore = []\n block_params = {x: self.__dict__[x] for x in self.__dict__ if x not in ignore}\n return TransactionSchema().dumps(block_params, separators=(',', ':'))\n\n def plain(self):\n return self.serialize(['signature', 'public_key'])\n\n def verify_signature(self):\n if self.signature and self.public_key:\n pk_bytes = bytes.fromhex(self.public_key)\n pk = rsa.PublicKey.load_pkcs1_openssl_pem(pk_bytes)\n try:\n return rsa.verify(self.plain().encode(), bytes.fromhex(self.signature), pk)\n except VerificationError:\n return False\n else:\n return False\n\n @staticmethod\n def from_schema(schema):\n transaction = Transaction()\n for key, value in schema.items():\n setattr(transaction, key, value)\n return transaction\n","sub_path":"core/Transaction.py","file_name":"Transaction.py","file_ext":"py","file_size_in_byte":1965,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"579433533","text":"from flask import Flask, render_template, request, redirect\nfrom mysqlconnection import connectToMySQL\napp = Flask(__name__)\n\nmysql = connectToMySQL('lead_gen_business')\n\n# Show all the cusomters and all theleads generated for each customer, since the beginning from this mysql db.\n\n@app.route('/')\ndef index():\n all_clients = mysql.query_db(\"SELECT CONCAT(clients.first_name, ' ', clients.last_name) AS Customer_Name, COUNT(leads.first_name) AS number_of_leads FROM clients JOIN sites ON sites.client_id = clients.client_id JOIN leads ON leads.site_id = sites.site_id GROUP BY clients.first_name\")\n # print(all_clients)\n return render_template('index.html', clients=all_clients)\n\napp.run(debug=True)\n","sub_path":"Python/flask_MySQL/leads_and_clients/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":710,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"561420903","text":"bl_info = {\n \"name\": \"2D_Canvas\",\n \"author\": \"Arjo Nagelhout\",\n \"version\": (1, 0),\n \"blender\": (2, 80, 0),\n \"description\": \"Quick canvas creation\",\n \"warning\": \"\",\n \"doc_url\": \"\",\n \"category\": \"Add Mesh\",\n}\n\nimport bpy\nfrom bpy.types import Operator\nfrom bpy_extras.object_utils import AddObjectHelper, object_data_add\n\ndef view3d_find( return_area = False ):\n # returns first 3d view, normally we get from context\n for area in bpy.context.window.screen.areas:\n if area.type == 'VIEW_3D':\n v3d = area.spaces[0]\n rv3d = v3d.region_3d\n for region in area.regions:\n if region.type == 'WINDOW':\n if return_area: return region, rv3d, v3d, area\n return region, rv3d, v3d\n return None, None\n\n\ndef add_canvas(self, context):\n # CREATE A CANVAS TO DRAW ON\n width = self.width\n height = self.height\n name = self.name\n align_view = self.align_view\n only_z = self.only_z\n \n # CREATE THE MESH\n bpy.ops.mesh.primitive_plane_add(size=1, enter_editmode=False, align='WORLD', location=context.scene.cursor.location)\n obj = bpy.context.object\n obj.name = name\n obj.show_wire = True\n\n bpy.ops.transform.rotate(value=1.5708, orient_axis='Y', orient_type='GLOBAL', orient_matrix=((1, 0, 0), (0, 1, 0), (0, 0, 1)), orient_matrix_type='GLOBAL', constraint_axis=(False, True, False), mirror=True, use_proportional_edit=False, proportional_edit_falloff='SMOOTH', proportional_size=1, use_proportional_connected=False, use_proportional_projected=False)\n bpy.ops.transform.rotate(value=1.5708, orient_axis='X', orient_type='GLOBAL', orient_matrix=((1, 0, 0), (0, 1, 0), (0, 0, 1)), orient_matrix_type='GLOBAL', constraint_axis=(True, False, False), mirror=True, use_proportional_edit=False, proportional_edit_falloff='SMOOTH', proportional_size=1, use_proportional_connected=False, use_proportional_projected=False)\n\n bpy.ops.object.transform_apply(location=False, rotation=True, scale=False)\n\n #bpy.ops.transform.resize(value=(1, width/500, 1), orient_type='GLOBAL', orient_matrix=((1, 0, 0), (0, 1, 0), (0, 0, 1)), orient_matrix_type='GLOBAL', constraint_axis=(False, True, False), mirror=True, use_proportional_edit=False, proportional_edit_falloff='SMOOTH', proportional_size=1, use_proportional_connected=False, use_proportional_projected=False)\n bpy.ops.transform.resize(value=(1, 1, height/width), orient_type='GLOBAL', orient_matrix=((1, 0, 0), (0, 1, 0), (0, 0, 1)), orient_matrix_type='GLOBAL', constraint_axis=(False, False, True), mirror=True, use_proportional_edit=False, proportional_edit_falloff='SMOOTH', proportional_size=1, use_proportional_connected=False, use_proportional_projected=False)\n\n if (align_view):\n r3d, rv3d, v3d = view3d_find()\n eulerangles = rv3d.view_rotation.to_euler()\n \n bpy.context.object.rotation_euler = eulerangles\n \n \n \n bpy.ops.transform.rotate(value=-1.5708, orient_axis='Y', orient_type='LOCAL', orient_matrix=((1, 0, 0), (0, 1, 0), (0, 0, 1)), orient_matrix_type='GLOBAL', constraint_axis=(False, True, False), mirror=True, use_proportional_edit=False, proportional_edit_falloff='SMOOTH', proportional_size=1, use_proportional_connected=False, use_proportional_projected=False)\n bpy.ops.transform.rotate(value=-1.5708, orient_axis='X', orient_type='LOCAL', orient_matrix=((1, 0, 0), (0, 1, 0), (0, 0, 1)), orient_matrix_type='GLOBAL', constraint_axis=(True, False, False), mirror=True, use_proportional_edit=False, proportional_edit_falloff='SMOOTH', proportional_size=1, use_proportional_connected=False, use_proportional_projected=False)\n \n if (only_z):\n \n bpy.context.object.rotation_euler[0] = 0\n bpy.context.object.rotation_euler[1] = 0\n \n \n \n\n\n # CREATE THE TEXTURE\n\n texture = bpy.data.images.new(name=name, width=width, height=height, alpha=True)\n texture.pixels[:] = (0.0, 0.0, 0.0, 0.0) * width * height\n\n\n # CREATE THE MATERIAL\n\n mat = bpy.data.materials.new(name=name)\n obj.data.materials.append(mat)\n mat.use_nodes = True\n\n nodes = mat.node_tree.nodes\n\n node_image = nodes.new(type=\"ShaderNodeTexImage\")\n node_image.location = -400, 300\n node_image.image = texture\n\n principled_bsdf = nodes.get(\"Principled BSDF\")\n\n links = mat.node_tree.links\n links.new(node_image.outputs[\"Color\"], principled_bsdf.inputs[\"Base Color\"])\n links.new(node_image.outputs[\"Alpha\"], principled_bsdf.inputs[\"Alpha\"])\n\n # SET BLEND MODE\n bpy.context.object.active_material.blend_method = 'CLIP'\n bpy.context.object.active_material.shadow_method = 'CLIP'\n bpy.context.object.active_material.alpha_threshold = 0\n \n\n # SWITCH TO DRAWING\n\n bpy.ops.paint.texture_paint_toggle()\n\nclass OBJECT_OT_add_canvas(Operator):\n \"\"\"Create a new 2D Canvas\"\"\"\n bl_idname = \"mesh.add_canvas\"\n bl_label = \"Add Canvas\"\n \n width = bpy.props.IntProperty(name=\"width\", default=1024)\n height = bpy.props.IntProperty(name=\"height\", default=1024)\n name = bpy.props.StringProperty(name=\"name\", default=\"Canvas\")\n align_view = bpy.props.BoolProperty(name=\"align view\", default=True)\n only_z = bpy.props.BoolProperty(name=\"only Z\", default=False)\n \n def invoke(self, context, event):\n wm = context.window_manager\n return wm.invoke_props_dialog(self)\n\n def execute(self, context):\n\n add_canvas(self, context)\n\n return {'FINISHED'}\n\n\n# Registration\n\ndef add_canvas_button(self, context):\n self.layout.operator(\n OBJECT_OT_add_canvas.bl_idname,\n text=\"Canvas\",\n icon='MESH_PLANE')\n\n\ndef register():\n bpy.utils.register_class(OBJECT_OT_add_canvas)\n bpy.types.VIEW3D_MT_add.append(add_canvas_button)\n\n\ndef unregister():\n bpy.utils.unregister_class(OBJECT_OT_add_canvas)\n bpy.types.VIEW3D_MT_add.remove(add_canvas_button)\n\n\nif __name__ == \"__main__\":\n register()","sub_path":"2D_Canvas.py","file_name":"2D_Canvas.py","file_ext":"py","file_size_in_byte":6008,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"305399473","text":"import fileinput\nfor line in fileinput.input():\n s = line\n\narr = list(map(int, s))\ntotal_candy = 0\n\n\ndef get_slice_total(a):\n i = 0\n slice_total = 0\n while a[i] < 0:\n i += 1\n left = i\n\n j = len(a) - 1\n while a[j] < 0:\n j -= 1\n\n right = j\n\n if left == right:\n return 0\n\n for k in range(left+1, right):\n if a[k] < 0:\n slice_total += 1\n\n return slice_total\n\n\nwhile any([x >= 0 for x in arr]):\n print(arr, get_slice_total(arr))\n total_candy += get_slice_total(arr)\n arr = [x-1 for x in arr]\n\nprint(total_candy)\n","sub_path":"problem-sets/2019-10-30/so_far_so_good_candy.py","file_name":"so_far_so_good_candy.py","file_ext":"py","file_size_in_byte":588,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"488804535","text":"import cv2\nimport math\nimport numpy as np\n\n# General functions\n\ndef order_rectangle_coordinates(box):\n \"\"\" Orders the coordinates of a rectagle to go clockwise\"\"\"\n\n # Code found at: https://www.pyimagesearch.com/2016/03/21/ordering-coordinates-clockwise-with-python-and-opencv/\n # the method is based on a function of the imutils library, however some adjustments have made as the method did not\n # function correctly\n\n # sort the points based on their x-coordinates\n box.sort(key=lambda x: x[0])\n xSorted = box\n\n # grab the left-most and right-most points from the sorted\n # x-roodinate points\n leftMost = xSorted[0:2]\n rightMost = xSorted[2:4]\n\n # now, sort the left-most coordinates according to their\n # y-coordinates so we can grab the top-left and bottom-left\n # points, respectively\n leftMost.sort(key=lambda x: x[1])\n (tl, bl) = leftMost\n\n # now that we have the top-left coordinate, use it as an\n # anchor to calculate the Euclidean distance between the\n # top-left and right-most points; by the Pythagorean\n # theorem, the point with the largest distance will be\n # our bottom-right point\n\n rightMost.sort(key=lambda x: x[1])\n (tr, br) = rightMost\n\n # return the coordinates in top-left, top-right,\n # bottom-right, and bottom-left order\n return np.array([tl, tr, br, bl])\n\n\ndef crop_to_contour(cnt, img):\n \"\"\"Crops an image to a contour\"\"\"\n x, y, w, h = cv2.boundingRect(cnt)\n return img[x: x + w, y:y + h]\n\n\ndef distance(p0, p1):\n \"\"\" Calculates the distance between two points \"\"\"\n return math.sqrt((p0[0] - p1[0]) ** 2 + (p0[1] - p1[1]) ** 2)\n\n\ndef fit_rectangle(cnt):\n \"\"\" Fits a rectangle around a contour \"\"\"\n\n rect = cv2.minAreaRect(cnt[0])\n box = cv2.boxPoints(rect)\n box = np.int0(box)\n\n return box\n\n\ndef crop_image(image, mask_dial, x_cap, y_cap, r_dial, mask_cap):\n \"\"\"Crops the original image and mask to the dial and adjusts the center coordinates of the dial\"\"\"\n\n img_dial = image * mask_dial\n img_dial = crop_to_circle(x_cap, y_cap, r_dial, img_dial)\n mask_cap = crop_mask_to_circle(x_cap, y_cap, r_dial, mask_cap)\n height, width = img_dial.shape[:2]\n x_cap = int(width / 2)\n y_cap = int(height / 2)\n\n return img_dial, mask_cap, x_cap, y_cap\n","sub_path":"image_processing/dial/helpers/general_functions.py","file_name":"general_functions.py","file_ext":"py","file_size_in_byte":2300,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"620448675","text":"import os\n\nfrom bookkeeper.core import models\nfrom bookkeeper.core.models import Bookkeeper\nfrom bookkeeper.io import fs_manager\nfrom bookkeeper.utils import const\n\ndef init(init_context):\n \"\"\"\n Create a bookkeeper instance in cwd with an initial context of the given \n name.\n \"\"\"\n kdir = os.path.join(os.getcwd(), const.BK_DIR)\n keeper = Bookkeeper(kdir, False, init_context)\n models.sync_bookkeeper(keeper)\n\ndef destroy():\n \"\"\"\n Remove the bookkeeper that manages the cwd.\n \"\"\"\n keeper = models.get_cwd_bookkeeper()\n models.delete_bookkeeper(keeper)\n\ndef create(cname):\n \"\"\"\n Create a context with the given name.\n \"\"\"\n keeper = models.get_cwd_bookkeeper()\n keeper.add_context_with_name(cname)\n models.sync_bookkeeper(keeper)\n\ndef switch(cname):\n \"\"\"\n Switch to the context with the given name.\n \"\"\"\n keeper = models.get_cwd_bookkeeper()\n keeper.set_context(cname)\n models.sync_bookkeeper(keeper)\n\ndef add(fpath):\n \"\"\"\n Add the given file to the current context of the cwd bookkeeper.\n \"\"\"\n if not os.path.isabs(fpath):\n fpath = fs_manager.with_cwd(fpath)\n keeper = models.get_cwd_bookkeeper()\n cc = keeper.current_context\n cc.add(fpath)\n models.sync_bookkeeper(keeper)\n\ndef add_all(fpath):\n \"\"\"\n Add the given file to all contexts of the cwd bookkeeper.\n \"\"\"\n if not os.path.isabs(fpath):\n fpath = fs_manager.with_cwd(fpath)\n keeper = models.get_cwd_bookkeeper()\n for ctx in keeper.contexts:\n ctx.add(fpath)\n models.sync_bookkeeper(keeper)\n\ndef remove(fpath):\n \"\"\"\n Remove the given file from the current context of the cwd bookkeeper.\n \"\"\"\n if not os.path.isabs(fpath):\n fpath = fs_manager.with_cwd(fpath)\n keeper = models.get_cwd_bookkeeper()\n cc = keeper.current_context\n cc.delete(fpath)\n\ndef remove_all(fpath):\n \"\"\"\n Remove the given file from all contexts of the cwd bookkeeper.\n \"\"\"\n if not os.path.isabs(fpath):\n fpath = fs_manager.with_cwd(fpath)\n keeper = models.get_cwd_bookkeeper()\n for ctx in keeper.contexts:\n ctx.delete(fpath)\n models.sync_bookkeeper(keeper)\n","sub_path":"bookkeeper/core/cli.py","file_name":"cli.py","file_ext":"py","file_size_in_byte":2188,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"373246516","text":"# std-lib imports\nimport json\nimport logging\n\n# thrid-party imports\nimport webapp2\n\n\nclass Webhook(webapp2.RequestHandler):\n\n def post(self, event=None):\n logging.info('Webhook received: {0}'.format(event))\n payload = json.loads(self.request.body)\n logging.info('Webhook payload: {0}'.format(payload))\n self.response.headers['Content-Type'] = 'application/json'\n self.response.write({'event': event, 'status': 'accepted'})\n\n\n# our main WSGI app\napp = webapp2.WSGIApplication(\n [\n webapp2.Route('/webhook/', Webhook),\n webapp2.Route('/webhook//', Webhook),\n ],\n debug=True,\n)\n","sub_path":"testserver/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":643,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"374212168","text":"from django.shortcuts import render\nfrom webapp.models import Propostas, CustomUser, Aluno, Orientador\n\n#pagina principal\ndef aluno_home_view (request):\n #propostas = Propostas.objects.all()\n #print(propostas)\n #return render(request, \"aluno/main_aluno.html\")\n\n propostas = Propostas.objects.all()\n alunos = Aluno.objects.all()\n users = CustomUser.objects.all()\n #para receber as propostas criadas pelo orientador atual\n user=Aluno.objects.get(admin_id=request.user.id)\n return render(request, \"aluno/main_aluno.html\", {'propostas':propostas, 'alunos':alunos, 'users':users}) \n\ndef aluno_info (request):\n return render(request, \"aluno/info.html\")\n\n#pagina principal\ndef admin_home(request):\n # para contar o numero de users\n countTotal = CustomUser.objects.count()\n countOrient = CustomUser.objects.filter(user_type=\"2\").count()\n countAluno = CustomUser.objects.filter(user_type=\"3\").count()\n users = CustomUser.objects.all()\n context = {\n 'countTotal':countTotal,\n 'countOrient':countOrient,\n 'countAluno':countAluno,\n 'users':users,\n }\n return render(request, \"admin/main_admin.html\", context)\n\ndef list_all_proposta_view (request): \n users = CustomUser.objects.all()\n propostas = Propostas.objects.all()\n return render(request, \"aluno/list_proposta.html\", {'propostas':propostas, 'users':users}) \n\ndef list_proposta_view(request, proposta_id):\n users = CustomUser.objects.all()\n proposta=Propostas.objects.get(id=proposta_id)\n return render(request, \"aluno/detail_proposta.html\", {\"proposta\": proposta, 'users':users})","sub_path":"webapp/views_aluno.py","file_name":"views_aluno.py","file_ext":"py","file_size_in_byte":1621,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"175223934","text":"from rest_framework import serializers\nfrom rest_framework.serializers import (\n\tModelSerializer,\n\tHyperlinkedIdentityField,\n\tSerializerMethodField\n\t)\n\nfrom symptom.models import (Symptom,\n\t\t\t\t\t\t\tSymptomCode,\n\t\t\t\t\t\t\tSymptomCode_Usage)\n\n\n\nclass SymptomCodeSerializer(serializers.ModelSerializer):\n\tclass Meta:\n\t\tmodel = SymptomCode\n\t\tfields = ['name',\n\t\t\t\t'title','description','symptom_type','category1','category2',\n\t\t\t\t'created_date','status','slug','url']\n\nclass SymptomCodeUrlSerializer(serializers.ModelSerializer):\n\tclass Meta:\n\t\tmodel = SymptomCode\n\t\tfields = ['name','title','url']\n\nclass SymptomCodeUsageUrlSerializer(serializers.ModelSerializer):\n\tclass Meta:\n\t\tmodel = SymptomCode_Usage\n\t\tfields = ['ordered','symptomcode','title']\n\t\tordering = ['ordered']\n\n\n\nclass SymptomSerializer(serializers.ModelSerializer):\n\tclass Meta:\n\t\tmodel = Symptom\n\t\tfields = ['performing','symptomcode','note','cnd',\n\t\t\t\t\t'created_date','user','url']\n\nclass SymptomUrlSerializer(serializers.ModelSerializer):\n\tclass Meta:\n\t\tmodel = Symptom\n\t\tfields = ['performing','url']\n\n# from rest_framework.serializers import (\n# \tModelSerializer,\n# \tHyperlinkedIdentityField,\n# \tSerializerMethodField\n# \t)\n\n\n# from symptom_code.models import SymptomCode\n\n\n# symptom_code_url = HyperlinkedIdentityField(\n# \t\tview_name='symptomcode-api:detail',\n# \t\tlookup_field='slug'\n# \t\t)\n\n# class SymptomCodeListSerializer(ModelSerializer):\n# \turl = symptom_code_url\n# \t# routing \t= RoutingListSerializer(read_only=True)\n# \tclass Meta:\n# \t\tmodel = SymptomCode\n# \t\t# fields ='__all__'\n# \t\tfields =[\n# \t\t\t'name',\n# \t\t\t'title',\n# \t\t\t'description',\n# \t\t\t'url',\n# \t\t\t'slug'\n# \t\t]\n\n# class SymptomCodeDetailSerializer(ModelSerializer):\n\n# \tclass Meta:\n# \t\tmodel = SymptomCode\n# \t\tfields ='__all__'\n\n\n# class SymptomCodeCreateSerializer (ModelSerializer):\n# \tclass Meta:\n# \t\tmodel = SymptomCode\n# \t\tfields =[\n# \t\t\t'name',\n# \t\t\t'title',\n# \t\t\t'description',\n# \t\t\t'category1',\n# \t\t\t'category2'\n# \t\t]\n\n# class SymptomCodeUpdateSerializer (ModelSerializer):\n# \tclass Meta:\n# \t\tmodel = SymptomCode\n# \t\tfields =[\n# \t\t\t'name',\n# \t\t\t'title',\n# \t\t\t'description',\n# \t\t\t'category1',\n# \t\t\t'category2'\n# \t\t]\n\n\n\n","sub_path":"wmp/symptom/api/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":2156,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"285240360","text":"from keras.preprocessing.image import ImageDataGenerator\nfrom keras.preprocessing.image import load_img\nfrom keras.preprocessing.image import img_to_array\nimport numpy as np\nimport os\n\nimport random\nfrom scipy import ndarray\n\n# image processing library\nimport skimage as sk\nfrom skimage import transform\nfrom skimage import util\nfrom skimage import io\nfrom skimage import filters\nfrom skimage.morphology import disk\n\ndef horizontal_flip(image_array: ndarray):\n # horizontal flip doesn't need skimage, it's easy as flipping the image array of pixels !\n return image_array[:, ::-1]\n\ndef swirl(image):\n return transform.swirl(image, strength=random.random(), radius=random.randint(50, 300))\n\n\n# dictionary of the transformations we defined earlier\navailable_transformations = {\n 'horizontal_flip': horizontal_flip,\n 'swirl': swirl,\n}\n\ndef shuffle(image_to_transform):\n num_transformations_to_apply = random.randint(1, len(available_transformations))\n\n num_transformations = 0\n transformed_image = None\n while num_transformations <= num_transformations_to_apply:\n # random transformation to apply for a single image\n key = random.choice(list(available_transformations))\n transformed_image = available_transformations[key](image_to_transform)\n num_transformations += 1\n return(transformed_image)\n\nimages = ['ricky-1.jpg', 'ricky-2.jpg', 'ricky-3.jpg']\nsharpen = np.array([[0,-1,0],[-1,5,-1],[0,-1,0]])\nimage_gen = ImageDataGenerator(rotation_range=35,\n width_shift_range=0.25,\n height_shift_range=0.25,\n shear_range=0.10,\n zoom_range=[0.75, 1.25],\n horizontal_flip=True,\n vertical_flip=False,\n fill_mode='reflect',\n data_format='channels_last',\n brightness_range=[0.25, 2.5],\n preprocessing_function=shuffle)\ntry:\n os.makedirs(\"images\")\nexcept:\n pass\n\nfor im in images:\n img = load_img(im, target_size=(360, 360))\n data = img_to_array(img)\n img = np.reshape(img, [1, 360, 360, 3])\n image_gen.fit(img)\n generator = image_gen.flow(img, batch_size=10, save_to_dir=\"images\", save_prefix=\"aug\", save_format=\"png\")\n i=0\n for next_generated in generator:\n i+=1\n if i==10:\n break\n","sub_path":"ricky-project/data_augmentation.py","file_name":"data_augmentation.py","file_ext":"py","file_size_in_byte":2477,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"487516705","text":"#coding=utf-8\r\n#只能操作docx\r\nfrom docx import Document\r\nimport os,datetime\r\nimport sys\r\nreload(sys)\r\nsys.setdefaultencoding('utf8')\r\n\r\nbegin = datetime.datetime.now()\r\nfor x in range(1,100):\r\n #打开文档\r\n document = Document(os.getcwd()+'/test.docx')\r\n #读取每段资料\r\n docText = '\\n\\n'.join([\r\n paragraph.text.encode('utf-8') for paragraph in document.paragraphs\r\n ])\r\n if docText.find(u'刷卡排污上位机平台')>-1:\r\n #print('%d----------------------------------------------%s'%(x,docText))\r\n continue\r\n #print docText\r\nend = datetime.datetime.now()\r\nprint(end-begin)","sub_path":"myword/readWord_bak.py","file_name":"readWord_bak.py","file_ext":"py","file_size_in_byte":630,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"480283936","text":"# Uzupelnij funkcje execute_query tak by wykonywala zadane zapytanie\n# Uzupelnij funkcję print_owners tak by wypisywala wszystkie osoby z bazy danych\n\n\nimport os\nimport sqlite3\n\n\nclass DBHandler:\n\n con = None\n\n def __init__(self, f):\n self.path = f\n self.__create_db()\n self.__create_tables()\n\n def __create_tables(self):\n try:\n self.__create_cars_table()\n except sqlite3.Error as e:\n print(e.args)\n try:\n self.__create_owners_table()\n except sqlite3.Error as e:\n print(e.args)\n\n def __create_db(self):\n if os.path.isfile(self.path):\n print(\"DB file already exists\")\n else:\n sqlite3.connect(self.path).close()\n\n def __create_cars_table(self):\n con = sqlite3.connect(self.path)\n with con:\n cur = con.cursor()\n cur.execute(\"CREATE TABLE Cars(Id INT, Name TEXT, Speed INT)\")\n cur.execute(\"INSERT INTO Cars VALUES(1,'Polonez',120)\")\n cur.execute(\"INSERT INTO Cars VALUES(2,'Maluch',90)\")\n cur.execute(\"INSERT INTO Cars VALUES(3,'Warszawa',90)\")\n cur.execute(\"INSERT INTO Cars VALUES(4,'Syrena',70)\")\n\n def __create_owners_table(self):\n persons = (\n (1, 'Adrian', 22),\n (2, 'Malgosia', 30),\n (3, 'Pawel', 55),\n (4, 'Kajtek', 80)\n )\n con = sqlite3.connect(self.path)\n with con:\n cur = con.cursor()\n cur.execute(\"CREATE TABLE Owners(Id INT, Name TEXT, Age INT)\")\n cur.executemany(\"INSERT INTO Owners VALUES(?, ?, ?)\", persons)\n\n def print_owners(self):\n results = self.execute_query(\"SELECT * from Owners\")\n for record in results:\n print(record[1])\n\n def execute_query(self, query):\n con = sqlite3.connect(self.path)\n with con:\n cur = con.cursor()\n cur.execute(query)\n results = cur.fetchall()\n return results\n\n\ndb = DBHandler('cars.db')\ndb.print_owners()\nprint(db.execute_query(\"SELECT * FROM Cars\"))\n\n\n","sub_path":"2018_12_08_PythonWPracyTestera - Rozwiazania/3_bazy_danych/sql_00.py","file_name":"sql_00.py","file_ext":"py","file_size_in_byte":2115,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"205792930","text":"from selenium import webdriver\nfrom webdriver_manager.chrome import ChromeDriverManager\nfrom bs4 import BeautifulSoup as BSoup\nimport time\nimport re\nimport requests\nimport webbrowser\nimport json\n\npo_nums = input('Input Purchase Order Number(s) (comma with space for multiple): ').split(', ')\n\noptions = webdriver.ChromeOptions()\noptions.add_argument(\"--headless\") \noptions.add_argument('--ignore-certificate-errors')\noptions.add_argument(\"--test-type\")\noptions.add_argument(\"--versions.chrome\")\n\ndriver = webdriver.Chrome(ChromeDriverManager().install())\ndriver.get('https://c4.qbo.intuit.com/qbo4/login?&useNeo=true®ion=GB')\ndriver.execute_script('doAcceptCookieWarning();')\n\ndriver.find_element_by_id('ius-userid').send_keys('')\ndriver.find_element_by_id('ius-password').send_keys('')\ndriver.find_element_by_id('ius-sign-in-submit-btn').click()\n\n#Waits for page to load and executes script to open CSC Ltd \ntime.sleep(5)\ndriver.get('https://c4.qbo.intuit.com/app/switchCompany?companyId=123146317817729');\n\ntime.sleep(1)\ndriver.get('https://c4.qbo.intuit.com/app/customerdetail?nameId=609')\n\ntime.sleep(3)\nsoup = BSoup(driver.page_source, 'html.parser') #Parser for shopify page HTML\ndriver.close()\n\np_order = [] #Stores all P-xxxxxxxx numbers from shopify page in p_order\nfor tds in soup.find_all('td', class_=\"dgrid-cell dgrid-cell-padding dgrid-column-3 field-referenceNumber\"):\n p_order += re.findall(r'\\d+', tds.text)\n\np_order_url = [\"https://api.veeqo.com/orders/\" + str(order_num) for order_num in p_order] #Order URL\n\n#Load api key\nwith open('apikey.json') as api_key: \n headers = json.load(api_key)\n\ni = 0\n#Extracts customer notes for given order url\nfor order in p_order_url:\n veeqo_json = requests.get(order, headers=headers).json()\n customer_note = veeqo_json['customer_note']['text']\n print('Searching order ' + veeqo_json['number'])\n\n for po in po_nums:\n if customer_note.find(po) != -1: #Search for matching purchase order number in notes\n print('Match found!')\n webbrowser.open(order.replace('api','app'), new=0)\n i += 1\n\n if i == len(po_nums):\n break\n\n if order == p_order_url[-1]:\n print('Not all orders found :(')\n\ninput('Press enter to exit.')\n","sub_path":"P-Finder.py","file_name":"P-Finder.py","file_ext":"py","file_size_in_byte":2339,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"311480116","text":"class Friend:\n def __init__(self, position, direction):\n self.position = int(position)\n self.tiredness = 0\n self.total_tiredness = 0\n self.direction = direction\n\n # Method that move according to the direction and increases\n # the tiredness\n def move(self):\n self.tiredness += 1\n if self.direction == -1:\n self.position -= 1\n else:\n self.position += 1\n self.total_tiredness += self.tiredness\n\n\na = int(input())\nb = int(input())\n# Discovers the walking direction for each friend.\n# -1: backward // 1: forward\nif a < b:\n direction_a = 1\n direction_b = -1\nelse:\n direction_a = -1\n direction_b = 1\n\nfriend_1 = Friend(a, direction_a)\nfriend_2 = Friend(b, direction_b)\n\naux = 0\n# Each friend moves at a time to find each other always\n# starting with the first friend moving\nwhile friend_1.position != friend_2.position:\n if aux % 2 == 0:\n friend_1.move()\n else:\n friend_2.move()\n aux += 1\n\nt = friend_1.total_tiredness + friend_2.total_tiredness\nprint(t)","sub_path":"Problema 1.py","file_name":"Problema 1.py","file_ext":"py","file_size_in_byte":1072,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"293958140","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Time : 2018/1/18 23:14\n# @Author : 张鹏辉\n# @File : urls.py\nfrom django.conf.urls import url\n\nfrom organization.views import OrgView, AddUserAskView, OrgHomeView,\\\n OrgCourseView, OrgDescView, OrgTeacherView, AddFavView\n\n\nurlpatterns = [\n # 机构首页\n url(r'^list/$', OrgView.as_view(), name=\"org_list\"),\n url(r'^add_ask/$', AddUserAskView.as_view(), name=\"add_ask\"),\n url(r'^home/(?P\\d+)/$', OrgHomeView.as_view(), name=\"org_home\"),\n url(r'^course/(?P\\d+)/$', OrgCourseView.as_view(), name=\"org_course\"),\n url(r'^desc/(?P\\d+)/$', OrgDescView.as_view(), name=\"org_desc\"),\n url(r'^teacher/(?P\\d+)/$', OrgTeacherView.as_view(), name=\"org_teacher\"),\n\n #机构收藏\n url(r'^add_fav/$', AddFavView.as_view(), name=\"add_fav\"),\n\n]\n","sub_path":"apps/organization/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":849,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"80563468","text":"#! /user/bin/env python\n\nimport os\nimport sys\nimport math\nfrom statistics import median\n\n\ndef create_summary(kernel, block_exp):\n\tocl_time = []\n\ttimestamp = []\n\tgpu_ticks = []\n\tcpu_ticks = []\n\ta_counters = []\n\tb_counters = []\n\tc_counters = []\n\tfor i in range(36):\n\t\ta_counters.append([])\n\tfor i in range(8):\n\t\tb_counters.append([])\n\t\tc_counters.append([])\n\tpsys_energy = []\n\tpkg_energy = []\n\tpp0_energy = []\n\tdram_energy = []\n\tgpu_energy = []\n\tocl_time_median = []\n\ttimestamp_median = []\n\tgpu_ticks_median = []\n\tcpu_ticks_median = []\n\ta_counters_median = []\n\tb_counters_median = []\n\tc_counters_median = []\n\tfor i in range(36):\n\t\ta_counters_median.append([])\n\tfor i in range(8):\n\t\tb_counters_median.append([])\n\t\tc_counters_median.append([])\n\tpsys_energy_median = []\n\tpkg_energy_median = []\n\tpp0_energy_median = []\n\tdram_energy_median = []\n\tgpu_energy_median = []\n\t\n\t# 32+256 tpb mode\n\t#if block_exp == 0: block_exp = 12\n\t#blocks = [1 for i in range(9)] + [i for i in range(2,33)] + [2**i for i in range(6,int(block_exp))]\n\t#tpb = [2**i for i in range(0,9)] + [32 for i in range(len(blocks)-10+1)] + [256 for i in range(len(blocks)-10+1)]\n\t#blocks = blocks + [i for i in range(2,33)] + [2**i for i in range(6,int(block_exp))]\n\t\n\t# 256 tpb mode\n\tif block_exp == 0: block_exp = 12\n\tblocks = [1 for i in range(9)] + [i for i in range(2,33)] + [2**i for i in range(6,int(block_exp))]\n\ttpb = [2**i for i in range(0,9)] + [256 for i in range(len(blocks)-10+1)]\n\t\n\t\n\t# 256 tpb 1-64 blocks mode \n\t#if block_exp == 0: block_exp = 12\n\t#blocks = [1 for i in range(9)] + [i for i in range(2,65)]\n\t#tpb = [2**i for i in range(0,9)] + [256 for i in range(len(blocks)-10+1)]\n\t\n\t\n\t#print(blocks)\n\t#print(tpb)\n\t\n\t#sys.exit()\n\n\n\tfor b,t in zip(blocks, tpb):\n\t\t\n\t\t#print(b,t)\n\t\t\n\t\tfilename = 'results_rpc_' + kernel + '_' + str(b) + '_blocks_' + str(t) + '_tpb.csv'\n\t\twith open('../results/' + filename, 'r') as f:\n\t\t\t\n\t\t\tlines = f.readlines()\n\t\t\theader = list(lines.pop(0).split())\t# remove header\n\t\t\tfor line in lines:\n\t\t\t\twords = list(line.split())\n\t\t\t\ti=0\n\t\t\t\tfor word in words:\n\t\t\t\t\tif i==0:\t# ocl_time\n\t\t\t\t\t\tocl_time.append(int(word))\n\t\t\t\t\tif i==1:\t# timestamp\n\t\t\t\t\t\ttimestamp.append(int(word))\n\t\t\t\t\telif i==2:\t# gpu ticks\n\t\t\t\t\t\tgpu_ticks.append(int(word))\n\t\t\t\t\telif i==3:\t# cpu ticks\n\t\t\t\t\t\tcpu_ticks.append(int(word))\n\t\t\t\t\telif i >= 12 and i < 12+36:\t# A counters\n\t\t\t\t\t\ta_counters[i-12].append(int(word))\n\t\t\t\t\telif i >= 12+36 and i < 12+36+8:\t# B counters\n\t\t\t\t\t\tb_counters[i-(12+36)].append(int(word))\n\t\t\t\t\telif i >= 12+36+8 and i < 12+36+8+8:\t# C counters\n\t\t\t\t\t\tc_counters[i-(12+36+8)].append(int(word))\n\t\t\t\t\telif i >= 12+36+8+8 and i < 12+36+8+8+1:\t# psys energy\n\t\t\t\t\t\tpsys_energy.append(int(word))\n\t\t\t\t\telif i >= 12+36+8+8+1 and i < 12+36+8+8+2:\t# pkg energy\n\t\t\t\t\t\tpkg_energy.append(int(word))\n\t\t\t\t\telif i >= 12+36+8+8+2 and i < 12+36+8+8+3:\t# pp0 energy\n\t\t\t\t\t\tpp0_energy.append(int(word))\n\t\t\t\t\telif i >= 12+36+8+8+3 and i < 12+36+8+8+4:\t# pp0 energy:\t# gpu energy\n\t\t\t\t\t\tdram_energy.append(int(word))\n\t\t\t\t\telif i >= 12+36+8+8+4:\t# gpu energy\n\t\t\t\t\t\tgpu_energy.append(int(word))\n\t\t\t\t\ti += 1\n\t\t\t\n\t\t\t\n\t\t\t\n\t\t\t\n\t\t\tocl_time_median.append(math.floor(median(ocl_time)))\n\t\t\ttimestamp_median.append(math.floor(median(timestamp)))\n\t\t\tgpu_ticks_median.append(math.floor(median(gpu_ticks)))\n\t\t\tcpu_ticks_median.append(math.floor(median(cpu_ticks)))\n\t\t\tfor i in range(len(a_counters)):\n\t\t\t\ta_counters_median[i].append(math.floor(median(a_counters[i])))\n\t\t\tfor i in range(len(b_counters)):\n\t\t\t\tb_counters_median[i].append(math.floor(median(b_counters[i])))\n\t\t\tfor i in range(len(c_counters)):\n\t\t\t\tc_counters_median[i].append(math.floor(median(c_counters[i])))\n\t\t\tpsys_energy_median.append(math.floor(median(psys_energy)))\n\t\t\tpkg_energy_median.append(math.floor(median(pkg_energy)))\n\t\t\tpp0_energy_median.append(math.floor(median(pp0_energy)))\n\t\t\tdram_energy_median.append(math.floor(median(dram_energy)))\n\t\t\tgpu_energy_median.append(math.floor(median(gpu_energy)))\n\t\t\t\n\t\t\t#if \"_16_\" in filename: print(a_counters_median[8])\n\t\t\t#if \"_16_\" in filename: print(a_counters)\n\t\t\t\n\t\t\t# reset lists for next iteration\n\t\t\tocl_time = []\n\t\t\ttimestamp = []\n\t\t\tgpu_ticks = []\n\t\t\tcpu_ticks = []\n\t\t\ta_counters = []\n\t\t\tb_counters = []\n\t\t\tc_counters = []\n\t\t\tfor i in range(36):\n\t\t\t\ta_counters.append([])\n\t\t\tfor i in range(8):\n\t\t\t\tb_counters.append([])\n\t\t\t\tc_counters.append([])\n\t\t\tpsys_energy = []\n\t\t\tpkg_energy = []\n\t\t\tpp0_energy = []\n\t\t\tdram_energy = []\n\t\t\tgpu_energy = []\n\n\n\tfor i in range(3,11):\n\t\theader.pop(3)\t# remove unnecesary cols\n\theader.insert(0, 'kernel')\n\theader.insert(1, 'block size')\n\theader.insert(2, 'threads per block')\n\n\t\t\t\n\twith open(kernel + '_summary.csv', 'w') as f:\n\t\tfor i in range(len(timestamp_median)):\n\t\t\tif i==0:\n\t\t\t\tprint('\\t'.join(header), file=f)\n\t\t\tprint(kernel + '\\t' + str(blocks[i]) + '\\t' + str(tpb[i]) + '\\t' + str(ocl_time_median[i]) + '\\t' + str(timestamp_median[i]) + '\\t' + str(gpu_ticks_median[i]) + '\\t' + str(cpu_ticks_median[i]) + '\\t', file=f, end='')\n\t\t\tfor j in range(len(a_counters_median)):\n\t\t\t\tprint(str(a_counters_median[j][i]) + '\\t', file=f, end='')\n\t\t\tfor j in range(len(b_counters_median)):\n\t\t\t\tprint(str(b_counters_median[j][i]) + '\\t' + str(c_counters_median[j][i]) + '\\t', file=f, end='')\n\t\t\tprint(str(psys_energy_median[i]) + '\\t', file=f, end='')\n\t\t\tprint(str(pkg_energy_median[i]) + '\\t', file=f, end='')\n\t\t\tprint(str(pp0_energy_median[i]) + '\\t', file=f, end='')\n\t\t\tprint(str(dram_energy_median[i]) + '\\t', file=f, end='')\n\t\t\tprint(str(gpu_energy_median[i]) + '\\t', file=f, end='')\n\t\t\tprint('', file=f)\n\t\n\t\n\t#header.pop(0)\t# remove kernel name\n\t#header[1] = '# ' + header[1]\t# comment first line for gnuplot\n\t#header.insert(2, '# threads')\t# add col total number of threads\n\t## add timers in sec, enrgy and power cols\n\t#header.append('OCL_TIMER [s]')\n\t#header.append('TIMESTAMP [s]')\n\t#header.append('GPU_TICKS [s]')\n\t#header.append('CPU_TICKS [s]')\n\t#header.append('PSYS_POWER [W]')\n\t#header.append('PKG_POWER [W]')\n\t#header.append('PP0_POWER [W]')\n\t#header.append('DRAM_POWER [W]')\n\t#header.append('GPU_POWER [W]')\n\t#\n\t#with open('../plots/' + kernel + '.csv', 'w') as f:\n\t#\tfor i in range(len(timestamp_median)):\n\t#\t\tif i==0:\n\t#\t\t\tprint('\\t'.join(header), file=f)\n\t#\t\tprint(str(blocks[i]) + '\\t' + str(tpb[i]) + '\\t' + str(blocks[i]*tpb[i]) + '\\t' + str(ocl_time_median[i]) + '\\t' + str(timestamp_median[i]) + '\\t' + str(gpu_ticks_median[i]) + '\\t' + str(cpu_ticks_median[i]) + '\\t', file=f, end='')\n\t#\t\tfor j in range(len(a_counters_median)):\n\t#\t\t\tprint(str(a_counters_median[j][i]) + '\\t', file=f, end='')\n\t#\t\tfor j in range(len(b_counters_median)):\n\t#\t\t\tprint(str(b_counters_median[j][i]) + '\\t' + str(c_counters_median[j][i]) + '\\t', file=f, end='')\n\t#\t\t# print energy\n\t#\t\tprint(str(psys_energy_median[i]) + '\\t', file=f, end='')\n\t#\t\tprint(str(pkg_energy_median[i]) + '\\t', file=f, end='')\n\t#\t\tprint(str(pp0_energy_median[i]) + '\\t', file=f, end='')\n\t#\t\tprint(str(dram_energy_median[i]) + '\\t', file=f, end='')\n\t#\t\tprint(str(gpu_energy_median[i]) + '\\t', file=f, end='')\n\t#\t\t# calc and print timers in seconds\n\t#\t\tocl_time_seconds = float(ocl_time_median[i])/1.0e9\n\t#\t\ttimestamp_seconds = float(timestamp_median[i])/12500000\n\t#\t\tgpu_seconds = float(gpu_ticks_median[i])/1050e6\n\t#\t\tcpu_seconds = float(cpu_ticks_median[i])/3.5e9\n\t#\t\tprint(str(ocl_time_seconds) + '\\t' + str(timestamp_seconds) + '\\t' + str(gpu_seconds) + '\\t' + str(cpu_seconds) + '\\t', file=f, end='')\n\t#\t\t# calc and print power\n\t#\t\tocl_time_seconds = ocl_time_median[i]/1.0e9\n\t#\t\tpsys_power = psys_energy_median[i] / ocl_time_seconds\n\t#\t\tpkg_power = pkg_energy_median[i] / ocl_time_seconds\n\t#\t\tpp0_power = pp0_energy_median[i] / ocl_time_seconds\n\t#\t\tdram_power = dram_energy_median[i] / ocl_time_seconds\n\t#\t\tgpu_power = pkg_power - pp0_power - dram_power\n\t#\t\tprint(str(psys_power) + '\\t' + str(pkg_power) + '\\t' + str(pp0_power) + '\\t' + str(dram_power) + '\\t' + str(gpu_power), file=f, end='')\n\t#\t\tprint('', file=f)\n\t\t\n\n\ndef create_summary_all_ops(kernel_name, block_exp):\n\tif 'add' in kernel_name:\n\t\tkernel_name_add = kernel_name\n\t\tkernel_name_sub = kernel_name.replace('add', 'sub')\n\t\tkernel_name_mul = kernel_name.replace('add', 'mul')\n\t\tkernel_name_div = kernel_name.replace('add', 'div')\n\t\tkernel_name_mad = kernel_name.replace('add', 'mad')\n\t\tcreate_summary(kernel_name_add, block_exp)\n\t\tcreate_summary(kernel_name_sub, block_exp)\n\t\tcreate_summary(kernel_name_mul, block_exp)\n\t\tcreate_summary(kernel_name_div, block_exp)\n\t\tcreate_summary(kernel_name_mad, block_exp)\n\telse:\n\t\tprint('Could not find \\'add\\' in kernel name.')\n\t\tsys.exit()\n\n\ndef create_summary_all_simd(kernel_name, block_exp):\n\tif 'scalar' in kernel_name:\n\t\tkernel_name_scalar = kernel_name\n\t\tkernel_name_vect2 = kernel_name.replace('scalar', 'vect2')\n\t\tkernel_name_vect4 = kernel_name.replace('scalar', 'vect4')\n\t\tkernel_name_vect8 = kernel_name.replace('scalar', 'vect8')\n\t\tkernel_name_vect16 = kernel_name.replace('scalar', 'vect16')\n\t\tcreate_summary(kernel_name_scalar, block_exp)\n\t\tcreate_summary(kernel_name_vect2, block_exp)\n\t\tcreate_summary(kernel_name_vect4, block_exp)\n\t\tcreate_summary(kernel_name_vect8, block_exp)\n\t\tcreate_summary(kernel_name_vect16, block_exp)\n\telse:\n\t\tprint('Could not find \\'scalar\\' in kernel name.')\n\t\tsys.exit()\n\n\ndef create_summary_all_simd_all_ops(kernel_name, block_exp):\n\tsimd = ['scalar', 'vect2', 'vect4', 'vect8', 'vect16']\n\tops = ['add', 'sub', 'mul', 'div', 'mad']\n\tkernel_names = []\n\tfor s in simd:\n\t\tfor o in ops:\n\t\t\tkernel_name_temp = kernel_name.replace('scalar', s)\n\t\t\tkernel_name_temp = kernel_name_temp.replace('add', o)\n\t\t\tkernel_names.append(kernel_name_temp)\n\t#print('\\n'.join(kernel_names))\n\tfor k in kernel_names:\n\t\tcreate_summary(k, block_exp)\n\n\n\nblock_exp = 0\nif len(sys.argv) > 3 and '--block_exp' in sys.argv:\n\tblock_exp = sys.argv[sys.argv.index('--block_exp')+1]\n\nif len(sys.argv) > 3 and '--all-ops' in sys.argv and '--all-simd' in sys.argv:\n\tcreate_summary_all_simd_all_ops(sys.argv[1], block_exp)\nelif len(sys.argv) > 2 and '--all-ops' in sys.argv:\n\tcreate_summary_all_ops(sys.argv[1], block_exp)\nelif len(sys.argv) > 2 and '--all-simd' in sys.argv:\n\tcreate_summary_all_simd(sys.argv[1], block_exp)\nelse:\n\tcreate_summary(sys.argv[1], block_exp)\n","sub_path":"summaries/create_summary_for_kernel.py","file_name":"create_summary_for_kernel.py","file_ext":"py","file_size_in_byte":10179,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"112649971","text":"def file_read(fname):\r\n with open(fname) as f:\r\n # x Content_List is the list that contain the read lines.\r\n c = f.readlines()\r\n print(c)\r\n #print(len(c))\r\n\r\n\r\nfile_read(\"file2.txt\")\r\n\r\n","sub_path":"21-02-2021 Python/CO5/CO5 1.py","file_name":"CO5 1.py","file_ext":"py","file_size_in_byte":228,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"32504044","text":"import os, json\nimport boto3\n\npersonalize_runtime = boto3.client('personalize-runtime')\n\nrealtime_campaign_arn = os.environ[\"PERSONALIZE_REALTIME_CAMPAIGN_ARN\"]\n\ndef lambda_handler(event, context):\n try:\n body = json.loads(event[\"body\"])\n user_id = body[\"userId\"]\n\n get_recommendations_response = personalize_runtime.get_recommendations(\n campaignArn = realtime_campaign_arn,\n userId = str(user_id),\n )\n\n response = {\n \"isBase64Encoded\": False,\n \"statusCode\": 200,\n \"headers\": { },\n \"body\": json.dumps(get_recommendations_response)\n }\n\n return response\n except Exception as exception:\n exceptionDictionary = {\n \"message\": str(exception),\n \"type\": exception.__class__.__name__\n }\n\n response = {\n \"isBase64Encoded\": False,\n \"statusCode\": 500,\n \"headers\": { },\n \"body\": json.dumps(exceptionDictionary)\n }\n\n return response\n","sub_path":"EndpointsKit/lambda_src/real_time_predictions/predict_with_user/predictWithUser.py","file_name":"predictWithUser.py","file_ext":"py","file_size_in_byte":1042,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"215916565","text":"import os\nimport base64\nimport requests\nimport json\nfrom datetime import datetime\nimport urllib.parse\nfrom datetime import datetime\nfrom flask import Flask, flash, redirect, render_template, request, session, abort, jsonify\nfrom flask_cors import CORS, cross_origin\nfrom writeJSONtoTEX import writeJSONtoTEX, writeJSONtoTEXEnriched\nfrom writeJSONtoHTML import writeJSONtoHTML\nimport shutil\n\napp = Flask(__name__,template_folder=\"build\", static_folder=\"build/static\")\nCORS(app, support_credentials=True)\napp.config['UPLOAD_FOLDER'] = \"build/static/media/pdf\"\n\n@app.route(\"/\")\ndef index():\n return render_template('index.html')\n\n@app.route('/get_categories', methods=['GET'])\ndef get_categories():\n return jsonify({'categories': ['Leda', 'Kot']})\n\n@app.route('/submit_form', methods=['POST'])\n@cross_origin()\ndef submit_form():\n content = request.json\n with open('build/static/resumerdf.json', 'w', encoding='utf-8') as outfile:\n json.dump(content, outfile, ensure_ascii=False, indent=2)\n # f= open(\"build/static/resumerdfwrite.json\",\"r\")\n # file_content = f.read()\n # url = \"http://rdf-translator.appspot.com/convert/json-ld/json-ld/content\"\n # payload = \"content=\" + urllib.parse.quote(file_content)\n # headers = {\n # 'Content-Type': \"application/x-www-form-urlencoded\",\n # 'cache-control': \"no-cache\"\n # }\n # response = requests.request(\"POST\", url, data=payload, headers=headers)\n # with open('build/static/resumerdf.json', 'w', encoding='utf-8') as outfile:\n # json.dump(json.loads(response.text), outfile, ensure_ascii=False, indent=2)\n return \"resumerdf.json\"\n\n@app.route('/generate_pdf', methods=['POST'])\ndef generate_pdf():\n req_data = request.get_json()\n content = req_data['data']['cv']\n designNumber = req_data['data']['designNumber']\n language = req_data['data']['language']\n now = datetime.now()\n dt_string = now.strftime(\"%d_%m_%Y_%H_%M_%S\")\n if not os.path.exists('build/static/media/pdf'):\n os.mkdir('build/static/media/pdf')\n writeJSONtoTEX(content, \"rdf2resume\" + dt_string, designNumber, language )\n return \"static/media/pdf/rdf2resume\" + dt_string\n\n@app.route('/generate_html', methods=['POST'])\ndef generate_html():\n req_data = request.get_json()\n content = req_data['data']['cv']\n language = req_data['data']['language']\n now = datetime.now()\n dt_string = now.strftime(\"%d_%m_%Y_%H_%M_%S\")\n # if not os.path.exists('build/static/media/html'):\n # os.mkdir('build/static/media/html')\n writeJSONtoHTML(content, \"rdf2resume\", language )\n #check if photo path exists\n photoPath = content['my0:aboutPerson']['my0:photo']\n if photoPath != \"\":\n \n # Destination path \n destination = \"build/static/media/html/img/\"\n \n # Copy the content of \n # source to destination \n shutil.copyfile(\"build/static/media/photos/\" + photoPath, destination + photoPath) \n\n shutil.make_archive('build/static/rdf2resume' + dt_string, 'zip', 'build/static/media/html')\n return \"rdf2resume\" + dt_string + \".zip\"\n\n@app.route('/generate_pdf_enriched', methods=['POST'])\ndef generate_pdf_enriched():\n req_data = request.get_json()\n content = req_data['data']['cv']\n designNumber = req_data['data']['designNumber']\n language = req_data['data']['language']\n now = datetime.now()\n dt_string = now.strftime(\"%d_%m_%Y_%H_%M_%S\")\n if not os.path.exists('build/static/media/pdf'):\n os.mkdir('build/static/media/pdf')\n writeJSONtoTEXEnriched(content, \"rdf2resume\" + dt_string, designNumber, language )\n return \"static/media/pdf/rdf2resume\" + dt_string\n\n@app.route('/upload', methods=['POST'])\n@cross_origin()\ndef process_upload_file():\n if request.method == 'POST':\n f = request.files['file']\n file_content = f.read()\n # url = \"http://rdf-translator.appspot.com/convert/\"+ request.args['standard'] +\"/json-ld/content\"\n # payload = \"content=\" + urllib.parse.quote(file_content)\n # headers = {\n # 'Content-Type': \"application/x-www-form-urlencoded\",\n # 'cache-control': \"no-cache\"\n # }\n # response = requests.request(\"POST\", url, data=payload, headers=headers)\n return(file_content)\n\n@app.route('/upload_photo', methods=['POST'])\n@cross_origin()\ndef process_upload_photo():\n if request.method == 'POST':\n f = request.files['file']\n if not os.path.exists('build/static/media/photos'):\n os.mkdir('build/static/media/photos')\n f.save(os.path.join('build/static/media/photos', f.filename))\n return(f.filename)\n \n# if __name__ == \"__main__\":\n# app.run()","sub_path":"Docker/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":4610,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"518598951","text":"from python_imagesearch.imagesearch import imagesearch_loop\r\nimport pyautogui\r\nimport time\r\nopened = 0\r\n\r\nwhile True:\r\n start = imagesearch_loop(\"./start.png\", 1, 0.5)\r\n print(\"position : \", start[0], start[1])\r\n pyautogui.click(x=start[0], y=start[1])\r\n time.sleep(1)\r\n open = imagesearch_loop(\"./open.png\", 1)\r\n print(\"position : \", open[0], open[1])\r\n pyautogui.click(x=open[0], y=open[1])\r\n time.sleep(2)\r\n box = imagesearch_loop(\"./box.png\", 1)\r\n print(\"position : \", box[0], box[1])\r\n pyautogui.click(x=box[0], y=box[1])\r\n time.sleep(4)\r\n openall = imagesearch_loop(\"./openall.png\", 1, 0.5)\r\n print(\"position : \", openall[0], openall[1])\r\n pyautogui.click(x=openall[0], y=openall[1])\r\n time.sleep(1)\r\n ok = imagesearch_loop(\"./ok.png\", 1, 0.5)\r\n print(\"position : \", ok[0], ok[1])\r\n pyautogui.click(x=ok[0], y=ok[1])\r\n opened = opened + 1\r\n print (\"opened: \" + str(opened))\r\n\r\n\r\n\r\n\r\n","sub_path":"openBox/openBox.py","file_name":"openBox.py","file_ext":"py","file_size_in_byte":952,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"338704025","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Jun 13 19:55:51 2019\n\n@author: xiaoxuan\n\"\"\"\n\n# Xiaoxuan Wang\n# 45448274\n# Practical Exam Question 2a\n\n# the 0th index is a dummy variable\nsales = [-1, 14, 8, 17, 22, 12, 6]\n\n# possible actions\naction = [0, 1, 2, 3, 4, 5]\n\n# stages: weeks 1 to 6\n# states: current stock available in store\n\n# value function\ndef V1(week, stock):\n if week == 7:\n return (stock,0, 0) # tuple: (profit, action, remains of the current week)\n else:\n best = (-1, 0, 0)\n for a in action:\n newstock = a*10 + stock\n sold = min(newstock, sales[week]) # the quantity sold in this week\n \n left = newstock - sold\n remain = max(0, left) # the quantity left at the end of the week\n \n best = max((12*sold-a*50-stock*0.5+V1(week+1, remain)[0],a, remain), best)\n return best\n\n# I assume that the store pays the storage cost at the beginning of next week\n\n# results\nV1(1,0)\nV1(2,6)\nV1(3,8)\nV1(4,1)\nV1(5,9)\nV1(6,7)\nV1(7,1)\n\n# Practical Exam Question 2b\n\ndef V2(week, stock, announced_already):\n if week == 7:\n return (stock,0)\n else:\n best = (-1, 0)\n for a in action:\n newstock = a*10 + stock\n \n if announced_already:\n sold = min(newstock, sales[week]*2)\n left = newstock - sold\n remain = max(0, left)\n best = max((12*sold-a*50-stock*0.5+V2(week+1, remain, True)[0],a), best)\n \n else:\n # scenario 1: still not announced\n newstock = a*10 + stock\n sold = min(newstock, sales[week])\n left = newstock - sold\n remain = max(0, left)\n profit1 = 12*sold-a*50-stock*0.5+V2(week+1, remain, False)[0]\n \n # scenario 2: announced this week\n sold = min(newstock, 2*sales[week])\n left = newstock - sold\n remain = max(0, left)\n profit2 = 12*sold-a*50-stock*0.5+V2(week+1, remain, True)[0]\n \n best = max((0.7*profit1+0.3*profit2, a), best)\n \n return best\n\n# result\nV2(1,0,False)","sub_path":"3-Dynamic_Programming/Classics.py","file_name":"Classics.py","file_ext":"py","file_size_in_byte":2269,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"468922252","text":"from stable_baselines3.common.torch_layers import BaseFeaturesExtractor\nimport gym\nimport torch as th\nimport torch.nn as nn\n\n\nclass CustomCNN(BaseFeaturesExtractor):\n def __init__(\n self,\n observation_space: gym.spaces.Box,\n features_dim: int = 256\n ):\n super(CustomCNN, self).__init__(observation_space, features_dim)\n n_input_channels = observation_space.shape[0]\n self.cnn = nn.Sequential(\n nn.Conv2d(n_input_channels, 32, kernel_size=3, stride=1, padding=1),\n nn.ReLU(),\n nn.Conv2d(32, 64, kernel_size=3, stride=1, padding=1),\n nn.ReLU(),\n nn.Conv2d(64, 128, kernel_size=3, stride=1, padding=0),\n nn.ReLU(),\n nn.Flatten(),\n )\n with th.no_grad():\n n_flatten = self.cnn(\n th.as_tensor(observation_space.sample()[None]).float()\n ).shape[1]\n\n self.linear = nn.Sequential(nn.Linear(n_flatten, features_dim), nn.ReLU())\n\n def forward(self, observations: th.Tensor) -> th.Tensor:\n return self.linear(self.cnn(observations))\n","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":1114,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"619492008","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Sep 1 22:19:18 2017\n\n@author: Jian Jiao\n\n64. Minimum Path Sum\n\nGiven a m x n grid filled with non-negative numbers, find a path from top left \nto bottom right which minimizes the sum of all numbers along its path.\n\nNote: You can only move either down or right at any point in time.\n\n\"\"\"\n\nclass Solution(object):\n def minPathSum(self, grid):\n \"\"\"\n :type grid: List[List[int]]\n :rtype: int\n \"\"\"\n rows = len(grid)\n \n if rows == 0:\n return 0\n \n cols = len(grid[0])\n \n if cols == 0:\n return 0\n \n tmp = [grid[0][0]]\n # col\n for i in range(1, cols):\n tmp.append(tmp[i-1] + grid[0][i])\n \n # row\n for i in range(1, rows):\n tmp[0] = tmp[0] + grid[i][0]\n \n # col\n for j in range(1, cols):\n tmp[j] = min(tmp[j-1], tmp[j]) + grid[i][j]\n \n return tmp[cols-1] \n \nslt = Solution()\nprint(slt.minPathSum([[1, 2, 3], [4, 5, 6], [7, 8, 9]]))\n","sub_path":"Python/064.MinimumPathSum.py","file_name":"064.MinimumPathSum.py","file_ext":"py","file_size_in_byte":1135,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"186968203","text":"# coding: UTF-8\nimport requests\nimport re\nimport html.parser as hp\nimport urllib\n\n# HTMLParserを継承したクラスを定義\ndef getTitle(url):\n data = urllib.request.urlopen(url)\n\n # HTMLの取得\n html = data.read()\n html = html.decode('utf-8')\n title = re.findall('(|\\n)(.*?)', html)\n\n return title[0][1]\n\n# クローリング処理\ndef crawling(url, check_url):\n\n # html取得\n resp = requests.get(url)\n\n # aタグを取得\n address = re.findall('(.*)', resp.text)\n\n for i in range(len(address)):\n # すでに登場済みの場合はパス\n if address[i][0] in check_url:\n continue\n\n # ダブりを削除するため\n check_url.append(address[i][0])\n\n # titleを取得する\n urlTitle = getTitle(address[i][0])\n\n # 表示させる\n print(urllib.parse.unquote(address[i][0]) + \"\\t\" + urlTitle)\n\n # 再度取得したURL内をクローリング\n crawling(urllib.parse.unquote(address[i][0]), check_url)\n\n\ndef main():\n check_url = []\n # アクセスするURL\n url = \"https://no1s.biz/\"\n\n # クローリング処理\n crawling(url, check_url)\n\nif __name__ == \"__main__\":\n main()","sub_path":"unifiedTest201804_2.py","file_name":"unifiedTest201804_2.py","file_ext":"py","file_size_in_byte":1274,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"604978075","text":"from collections import defaultdict, Counter\nimport pandas as pd\nimport numpy as np\nimport torch\nfrom scipy.special import logsumexp\nimport matplotlib.pyplot as plt\nfrom torch.autograd import Variable\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.metrics import precision_recall_fscore_support\n\n# A list of labels.\nOFFSET = '**OFFSET**'\n\n# deliverable 1.1\ndef bag_of_words(text):\n '''\n Count the number of word occurences for each document in the corpus\n\n :param text: a document, as a single string\n :returns: a Counter for a single document\n :rtype: Counter\n '''\n return Counter(text.split())\n\n # raise NotImplementedError\n\n# deliverable 1.2\ndef aggregate_counts(bags_of_words):\n '''\n Aggregate word counts for individual documents into a single bag of words representation\n\n :param bags_of_words: a list of bags of words as Counters from the bag_of_words method\n :returns: an aggregated bag of words for the whole corpus\n :rtype: Counter\n '''\n\n # YOUR CODE GOES HERE\n return sum(bags_of_words, Counter())\n # raise NotImplementedError\n\n# deliverable 1.3\ndef compute_oov(bow1, bow2):\n '''\n Return a set of words that appears in bow1, but not bow2\n\n :param bow1: a bag of words\n :param bow2: a bag of words\n :returns: the set of words in bow1, but not in bow2\n :rtype: set\n '''\n return set(bow1)-set(bow2)\n \n # raise NotImplementedError\n\n# deliverable 1.4\ndef prune_vocabulary(training_counts, target_data, min_counts):\n '''\n prune target_data to only words that appear at least min_counts times in training_counts\n\n :param training_counts: aggregated Counter for training data\n :param target_data: list of Counters containing dev bow's\n :returns: new list of Counters, with pruned vocabulary\n :returns: list of words in pruned vocabulary\n :rtype: list of Counters, set\n '''\n vocab = []\n data = []\n for k, v in training_counts.items():\n if v >= min_counts:\n vocab.append(k)\n for i in target_data:\n data.append({k: v for k, v in i.items() if k in vocab})\n return data, vocab\n # raise NotImplementedError\n\n### helper code\n\ndef read_data(filename,label='Era',preprocessor=bag_of_words):\n df = pd.read_csv(filename)\n return df[label].values,[preprocessor(string) for string in df['Lyrics'].values]\n\ndef oov_rate(bow1,bow2):\n return len(compute_oov(bow1,bow2)) / len(bow1.keys())\n\n\n# hint! use this.\ndef argmax(scores):\n items = list(scores.items())\n items.sort()\n return items[np.argmax([i[1] for i in items])][0]\n\n# This will no longer work for our purposes since python3's max does not guarantee deterministic ordering\n# argmax = lambda x : max(x.items(),key=lambda y : y[1])[0]\n\n# deliverable 2.1\ndef make_feature_vector(base_features,label):\n '''\n take a counter of base features and a label; return a dict of features, corresponding to f(x,y)\n\n :param base_features: counter of base features\n :param label: label string\n :returns: dict of features, f(x,y)\n :rtype: dict\n\n '''\n feat = {}\n for i in base_features:\n feat[(label, i)] = base_features[i]\n feat[(label, OFFSET)] = 1\n return feat\n\n# deliverable 2.2\ndef predict(base_features,weights,labels):\n '''\n prediction function\n\n :param base_features: a dictionary of base features and counts\n :param weights: a defaultdict of features and weights. features are tuples (label,base_feature).\n :param labels: a list of candidate labels\n :returns: top scoring label, scores of all labels\n :rtype: string, dict\n '''\n scoreLabel = {}\n for i in labels:\n feat = make_feature_vector(base_features,i)\n score = 0\n for j in feat:\n if j in weights:\n score += weights[j]*feat[j]\n scoreLabel[i] = score\n maxScore = argmax(scoreLabel)\n return maxScore, scoreLabel\n\ndef predict_all(x,weights,labels):\n '''\n Predict the label for all instances in a dataset\n\n :param x: base instances\n :param weights: defaultdict of weights\n :returns: predictions for each instance\n :rtype: numpy array\n\n '''\n answer = []\n for i in range(len(x)):\n maxScore, scoreLabel = predict(x[i], weights, labels)\n answer.append(maxScore)\n return np.array(answer)\n\ntheta_hand = defaultdict(float,\n {('2000s','money'):0.1,\n ('2000s','name'):0.2,\n ('1980s','tonight'):0.1,\n ('2000s','man'):0.1,\n ('1990s','fly'):0.1,\n ('pre-1980',OFFSET):0.1\n })\n\n# deliverable 3.1\ndef get_corpus_counts(x,y,label):\n \"\"\"Compute corpus counts of words for all documents with a given label.\n\n :param x: list of counts, one per instance\n :param y: list of labels, one per instance\n :param label: desired label for corpus counts\n :returns: defaultdict of corpus counts\n :rtype: defaultdict\n\n Example:\n x = [Counter({'aa': 1, 'bb': 2, 'cc': 3}),\n Counter({'aa': 1, 'dd': 2, 'ee': 3}),\n Counter({'bb': 1, 'cc': 2, 'dd': 3})]\n y = [1, 2, 1]\n label = 1\n get_corpus_counts(x,y,label) = {'aa': 1, 'bb': 3, 'cc': 5, 'dd': 3}\n\n \"\"\"\n wantedLables=[]\n answer =Counter() \n for i in range(len(y)):\n if y[i] == label:\n wantedLables.append((x[i]))\n for i in wantedLables:\n answer.update(i) \n return answer\n # raise NotImplementedError\n\n# deliverable 3.2\ndef estimate_pxy(x,y,label,smoothing,vocab):\n '''\n Compute smoothed log-probability P(word | label) for a given label.\n\n :param x: list of counts, one per instance\n :param y: list of labels, one per instance\n :param label: desired label\n :param smoothing: additive smoothing amount\n :param vocab: list of words in vocabulary\n :returns: defaultdict of log probabilities per word\n :rtype: defaultdict\n\n '''\n # print(vocab)\n answer = {}\n corpusCount = get_corpus_counts(x,y,label)\n for i in vocab:\n numerator = corpusCount[i]+smoothing\n x = sum(list(corpusCount.values()))\n denominator = x+(smoothing*len(vocab))\n answer[i] = np.log(numerator/denominator)\n return defaultdict(float,answer)\n # raise NotImplementedError\n\n# deliverable 3.3\ndef estimate_nb(x,y,smoothing):\n \"\"\"estimate a naive bayes model\n\n :param x: list of dictionaries of base feature counts\n :param y: list of labels\n :param smoothing: smoothing constant\n :returns: a defaultdict of features and weights. features are tuples (label,base_feature).\n :rtype: defaultdict\n\n Hint: See predict() for the exact return type information.\n\n \"\"\"\n xCopy=[]\n for i in x:\n xCopy.append(Counter(i))\n \n aggrCount = aggregate_counts(xCopy)\n vocab = []\n for k, v in aggrCount.items():\n if v >= 10:\n vocab.append(k)\n\n features = defaultdict()\n yLables = set(y)\n for i in yLables:\n corpusCount = get_corpus_counts(x,y,i)\n for j in vocab:\n numerator = corpusCount[j]+smoothing\n denominator = sum(list(corpusCount.values()))+(smoothing*len(vocab))\n features[(i, j)] = np.log(numerator/denominator)\n temp = list(y[i==y])\n features[(i, OFFSET)] = np.log(len(temp)/len(y))\n return features\n\n# deliverable 3.4\ndef find_best_smoother(x_tr_pruned,y_tr,x_dv_pruned,y_dv,smoothers):\n '''\n find the smoothing value that gives the best accuracy on the dev data\n\n :param x_tr: training instances\n :param y_tr: training labels\n :param x_dv: dev instances\n :param y_dv: dev labels\n :param smoothers: list of smoothing values\n :returns: 1) best smoothing value, 2) a dictionary of smoothing values and dev set accuracy.\n :rtype: 1) float, 2) dictionary\n\n '''\n answer = {}\n yLabels = set(y_tr)\n for i in smoothers:\n theta = estimate_nb(x_tr_pruned,y_tr,i)\n yHat = predict_all(x_dv_pruned,theta,yLabels)\n answer[i] = acc(yHat,y_dv)\n minKey = 0 \n minVal = float(\"inf\") \n for i in answer.keys():\n if answer[i] < minVal:\n minKey = i\n return answer[minKey], answer\n\ndef acc(y_hat,y):\n return (y_hat == y).mean()\n\ndef write_predictions(y_hat,filename):\n with open(filename,'w') as fout:\n for y_hat_i in y_hat:\n fout.write(y_hat_i + \"\\n\")\n\ndef read_predictions(filename):\n with open(filename,'r') as fin:\n return [line.rstrip() for line in fin.readlines()]\n\n## these are just for fun\n\ndef f1(y_hat,y,label):\n tp = sum((y_hat==label) & (y==label))\n fp = sum((y_hat==label) & (y!=label))\n fn = sum((y_hat!=label) & (y==label))\n #print tp,fp,fn\n r = tp/float(tp + fn + 1e-10)\n p = tp/float(tp + fp + 1e-10)\n f = 2 * r * p / (r + p + 1e-10)\n return f\n\ndef macro_f1(y_hat,y):\n all_labels = set(y)\n y_hat = np.array(y_hat)\n f1s = {label:f1(y_hat,y,label) for label in all_labels}\n return sum(f1s.values())/len(all_labels),f1s\n\n\n# deliverable 4.1\ndef make_numpy(bags_of_words, vocab):\n '''\n Convert the bags of words into a 2D numpy array\n\n :param bags_of_words: list of Counters\n :param vocab: pruned vocabulary\n :returns: the bags of words as a 2D numpy array (length of bags_of_words by length of vocab)\n :rtype: numpy array\n '''\n answer = np.zeros((len(bags_of_words),len(vocab)))\n sortedVocab = sorted(vocab)\n for i in range(len(bags_of_words)):\n for j in range(len(vocab)):\n if sortedVocab[j] in bags_of_words[i]:\n word = bags_of_words[i][sortedVocab[j]]\n answer[i][j] = word\n \n return answer\n\n# deliverable 4.2\ndef better_model():\n # scikit_log_reg = LogisticRegression() ## Tune parameters for this function.\n ### BEGIN SOLUTION\n return LogisticRegression(solver='saga', penalty='elasticnet', l1_ratio=0.7)\n ### END SOLUTION\n\n\n\n######################### helper code\ndef train_model(loss, model, X_tr_var, Y_tr_var,\n num_its = 200,\n X_dv_var = None,\n Y_dv_var = None,\n status_frequency=10,\n optim_args = {'lr':0.002,'momentum':0},\n param_file = 'best.params'):\n\n # initialize optimizer\n optimizer = optim.SGD(model.parameters(), **optim_args)\n\n losses = []\n accuracies = []\n\n for epoch in range(num_its):\n # set gradient to zero\n optimizer.zero_grad()\n # run model forward to produce loss\n output = loss.forward(model.forward(X_tr_var),Y_tr_var)\n # backpropagate and train\n output.backward()\n optimizer.step()\n\n #print(output.item())\n losses.append(output.item())\n\n # write parameters if this is the best epoch yet\n if X_dv_var is not None:\n # run forward on dev data\n _, Y_hat = model.forward(X_dv_var).max(dim=1)\n # compute dev accuracy\n acc = acc(Y_hat.data.numpy(),Y_dv_var.data.numpy())\n # save\n if len(accuracies) == 0 or acc > max(accuracies):\n state = {'state_dict':model.state_dict(),\n 'epoch':len(accuracies)+1,\n 'accuracy':acc}\n torch.save(state,param_file)\n accuracies.append(acc)\n\n # print status message if desired\n if status_frequency > 0 and epoch % status_frequency == 0:\n print(\"Epoch \"+str(epoch+1)+\": Dev Accuracy: \"+str(acc))\n\n # load parameters of best model\n checkpoint = torch.load(param_file)\n model.load_state_dict(checkpoint['state_dict'])\n\n return model, losses, accuracies\n\ndef plot_results(losses, accuracies):\n fig,ax = plt.subplots(1,2,figsize=[12,2])\n ax[0].plot(losses)\n ax[0].set_ylabel('loss')\n ax[0].set_xlabel('iteration');\n ax[1].plot(accuracies);\n ax[1].set_ylabel('dev set accuracy')\n ax[1].set_xlabel('iteration');\n\n# deliverable 5.1\ndef get_top_features_LR(scikit_log_reg, vocab,label_set,label,k):\n features = {}\n \n for i,j in enumerate(label_set):\n features[j] = i\n\n coeffFeatures = scikit_log_reg.coef_[features[label]]\n sortedVocab = sorted(vocab) \n sortedFeatures = sorted(zip(coeffFeatures,sortedVocab))\n\n answer = []\n for i in sortedFeatures:\n answer.append(i[1])\n\n return answer[-k:], answer[:k]\n\n# deliverable 5.2\ndef get_top_features_NB(theta_nb, label_set,label,k):\n features = {}\n\n for i,j in theta_nb.keys():\n if i == label and j != OFFSET:\n features[j] = theta_nb[(i,j)]\n\n feat = sorted(features.items(), key=lambda x: x[1])\n answer = []\n for i in feat:\n answer.append(i[0])\n return answer[-k:], answer[:k]\n\n# deliverable 6\ndef get_PRF(Y_hat_dv, Y_dv, label_set, label):\n precision = 0.0\n recall = 0.0\n f1 = 0.0\n precision, recall, f1, _ = precision_recall_fscore_support(Y_dv, Y_hat_dv, labels=[label_set.index(label)])\n return precision[0], recall[0], f1[0]\n ### END SOLUTION\n raise NotImplementedError\n","sub_path":"nlplab2_dist/nlplab2_dist/lab2.py","file_name":"lab2.py","file_ext":"py","file_size_in_byte":13102,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"113562222","text":"from sklearn.externals import joblib\nimport Settings\nimport os\nimport pandas as pd\nimport glob\nimport seaborn as sns\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.patches as mpatches\nimport matplotlib.ticker as ticker\nimport matplotlib.lines as mlines\n\nif __name__ == \"__main__\":\n\n df_res = pd.DataFrame()\n size = 'outputStochastic copy' # output, outputLarge, outputMedium, outputStochastic\n files = glob.glob(os.path.join(os.path.join(Settings.DATA_DIR, size), '*.z'))\n\n for file in files:\n conditions = file.replace(\".z\", \"\").replace(\"cme_data\", \"cme\").split('_')\n res = joblib.load(file)\n df = pd.DataFrame(np.array(res[:-1]).T, columns=['n_samples', 'MSE', 'Preds'])\n df['estimator'] = conditions[9]\n df['iteration'] = conditions[-1]\n df['metric'] = conditions[1]\n df['temp'] = conditions[5]\n df['m'] = int(conditions[3])\n df['l'] = int(conditions[4])\n df['ml'] = conditions[3] + ',' + conditions[4]\n df['logger'] = conditions[6]\n df['ranker'] = conditions[7]\n\n df_res = df_res.append(df)\n\n df_res['n_samples'] = df_res['n_samples'].astype(np.int32)\n df_res['log_rmse'] = np.log10(np.sqrt(df_res['MSE']))\n\n df_plot = df_res.query(\"temp == 'n1.0' and logger == 'ftree' \"\n \"and metric == 'ERR' and ranker == 'elasso'\")\n\n sns.set_style(\"ticks\")\n\n sns.set(font_scale=1.5)\n\n hue_kws = {'linestyles': [\"-\", \"--\", \"-.\", \":\", ':', '-'],\n 'markers': ['x', 'v', 'o', '^', 's', 'd'],\n 'capsize': [0.05] * 6}\n\n subplot_kws = {'markeredgewidth': [] * 5, 'markeredgecolor': ['black'] * 5}\n\n g = sns.FacetGrid(df_plot, hue=\"estimator\", hue_order=['CME-A', 'DM-tree', 'DR', 'PI-SN', 'IPS-SN', 'OnPolicy'],\n col=\"ml\",\n size=4.0, aspect=1.2, legend_out=True,\n hue_kws=hue_kws, ylim=(5e-7, 1.2))\n\n g.map(sns.pointplot, \"n_samples\", \"MSE\", scale=1.25)\n\n g.set(yscale=\"log\")\n g.set_ylabels(\"Mean Square Error\")\n g.set_xlabels(\"Number of observations\")\n\n plt.tight_layout()\n\n g.axes[0][0].set_title(\"M=100, K=10\")\n g.axes[0][1].set_title(\"M=10, K=5\")\n\n handlers = dict()\n\n g.hue_names = ['CME', 'Direct', 'DR', 'Slate', 'wIPS', 'OnPolicy']\n for hue, color, marker in zip(g.hue_names, g._colors, hue_kws['markers']):\n if marker == 'x':\n marker = \"X\"\n handlers[hue] = mlines.Line2D([], [], color=color, marker=marker, markersize=13)\n\n g.add_legend(handlers, title='Estimator')\n xticks = [1000, 2500, 6300, 16000, 40000, 100000]\n g.axes[0][0].xaxis.set_major_locator(plt.FixedLocator(range(len(xticks))))\n g.axes[0][1].xaxis.set_major_formatter(ticker.FixedFormatter(xticks))\n\n g.fig.get_children()[-1].set_bbox_to_anchor((1.01, 0.5, 0, 0))\n\n plt.subplots_adjust(right=0.9)\n\n plt.savefig('realdata_result_stochastic.pdf', format='pdf')\n","sub_path":"plot_result.py","file_name":"plot_result.py","file_ext":"py","file_size_in_byte":2960,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"431613551","text":"# These lines import modules\r\nimport media # This module includes the Movie class\r\nimport fresh_tomatoes\r\n\r\n# Define a movie instance by 1) title, 2) storyline,\r\n# 3) URL for poster image, 4) URL for trailer\r\n\r\ntoy_story = media.Movie(\"Toy Story\",\r\n \"A story of a boy and his toys that come to life.\",\r\n \"http://www.gstatic.com/tv/thumb/movieposters/17420/p17420_p_v8_ab.jpg\" # NOQA\r\n \"https://www.youtube.com/watch?v=KYz2wyBy3kc\")\r\n\r\navatar = media.Movie(\"Avatar\",\r\n \"A marine on an alien planet.\",\r\n \"http://t0.gstatic.com/images?q=tbn:ANd9GcQCfmvrE4fMo2cd8esc7mDZPtFSJThAujddMPkRtti1_ij6u-jp\", # NOQA\r\n \"https://www.youtube.com/watch?v=cRdxXPV9GNQ\")\r\n\r\nfirst_contact = media.Movie(\"Star Trek: First Contact\",\r\n \"The crew of the enterprise travels back in time.\",\r\n \"http://t2.gstatic.com/images?q=tbn:ANd9GcQqKE15EvuPYXqFa5X1PWPlljp1pu5Ss1UUNS98qp8RkJnSBSUU\", # NOQA\r\n \"https://www.youtube.com/watch?v=YQ1eiEvefKI\")\r\n\r\nlogan = media.Movie(\"Logan\",\r\n \"Wolverine as an old man.\",\r\n \"http://t1.gstatic.com/images?q=tbn:ANd9GcRPoMqL1vglrh7OF_69pT8gYMYnYaq1r7WfPMcD587V9uOR_hW2\", # NOQA\r\n \"https://www.youtube.com/watch?v=f7kIl-Q1yrA\")\r\n\r\nratatouille = media.Movie(\"Ratatouille\",\r\n \"A cute rate goes on a journey\",\r\n \"http://www.gstatic.com/tv/thumb/dvdboxart/165058/p165058_d_v8_aa.jpg\", # NOQA\r\n \"https://www.youtube.com/watch?v=uVeNEbh3A4U\")\r\n\r\nghost_busters = media.Movie(\"Ghost Busters (Original)\",\r\n \"Stupid people fight ghosts.\",\r\n \"http://t3.gstatic.com/images?q=tbn:ANd9GcRJG5IBNzP5r0lNiVbjvc-V4ejuqDRWorvC9cAx8eBYQ4hb5eVY\", # NOQA\r\n \"https://www.youtube.com/watch?v=eowrFdpcRbs\")\r\n\r\nmovies = [toy_story, avatar, first_contact, logan, ratatouille, ghost_busters]\r\nfresh_tomatoes.open_movies_page(movies) # Create movie page based on\r\n# list of movie instances\r\n","sub_path":"entertainment_center.py","file_name":"entertainment_center.py","file_ext":"py","file_size_in_byte":2199,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"189774818","text":"from enum import Enum\nfrom core.inputfile import Section\n\n\nclass CurveType(Enum):\n \"\"\"Curve Type\"\"\"\n STORAGE = 1\n SHAPE = 2\n DIVERSION = 3\n TIDAL = 4\n PUMP1 = 5\n PUMP2 = 6\n PUMP3 = 7\n PUMP4 = 8\n RATING = 9\n CONTROL = 10\n\n\nclass Curve(Section):\n \"\"\"Defines data curves and their X,Y points\"\"\"\n\n field_format = \" {:16}\\t{:10}\\t{:10}\\t{:10}\\n\"\n\n def __init__(self, new_text=None):\n Section.__init__(self)\n\n self.curve_id = '' # string\n \"\"\"Curve ID Label\"\"\"\n\n self.curve_type = CurveType.PUMP1\n \"\"\"Curve type\"\"\"\n\n self.curve_xy = [] # list of (x, y) tuples\n \"\"\"X, Y Values\"\"\"\n\n if new_text:\n self.set_text(new_text)\n\n def get_text(self):\n \"\"\"format contents of this item for writing to file\"\"\"\n inp = ''\n if self.comment:\n inp = self.comment + '\\n'\n type_name = self.curve_type.name\n for xy in self.curve_xy:\n inp += Curve.field_format.format(self.curve_id, type_name, xy[0], xy[1])\n type_name = \" \"\n return inp\n\n def set_text(self, new_text):\n self.__init__()\n for line in new_text.splitlines():\n self.set_comment_check_section(line)\n if line.strip():\n fields = line.split()\n if len(fields) > 2:\n self.curve_id = fields[0]\n try:\n self.curve_type = CurveType[fields[1].upper()]\n x_index = 2\n except:\n x_index = 1\n for x in range(x_index, len(fields) - 1, 2):\n self.curve_xy.append((fields[x], fields[x + 1]))\n","sub_path":"src/core/swmm/curves.py","file_name":"curves.py","file_ext":"py","file_size_in_byte":1748,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"532997838","text":"#Programa Hacer un algoritmo que calcule el total a pagar por la compra de camisas.\n#Si se compran tres camisas o más se aplica un descuento del 20%\n#sobre el total de la compra\n#Declaracion\nnc=0\ncosto,des,pt,pc=0.0,0.0,0.0,0.0\nimport os\n\n#Input\nnc=int(os.sys.argv[1])\npc=float(os.sys.argv[2])\n\n#Processing\ncosto=nc*pc\ndes=costo*0.20\npt=costo-des\n\nif (nc>=3):\n print(\"El costo de las camisas es:\",costo)\n print(\"El descuento es:\",des)\n print(\"El costo total a pagar es\",pt)\n\n","sub_path":"Mendoza/Simple09.py","file_name":"Simple09.py","file_ext":"py","file_size_in_byte":485,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"473768348","text":"#ex020\n#Sorteando uma ordem na lista\n#O mesmo Prof. do desafio anterior quer sortear a ordem de aprensentação de trabalhos dos alunos. Faça um progrma que leia o nome dos quatro alunos e mostre a ordem sorteada\n\nimport random\n\nn2 = input('Digite o primeiro nome: ')\nn3 = input('Digite o segundo nome: ')\nn4 = input('Digite o terceiro nome: ')\nn5 = input('Digite o quarto nome: ')\n\nn1 = random.sample([n2, n3, n4, n5], k=4)\n#resolução do prof.\nlista = [n5, n2, n3, n4]\nrandom.shuffle(lista)\n\n\nprint(n1)\nprint(lista)\n\n","sub_path":"ex020.py","file_name":"ex020.py","file_ext":"py","file_size_in_byte":521,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"81345583","text":"\"\"\"\nBuild service item action for AWS EKS Cluster Service blueprint.\n\"\"\"\nfrom common.methods import set_progress\nfrom infrastructure.models import CustomField, Environment\nfrom resources.models import ResourceType, Resource\nfrom resourcehandlers.aws.models import AWSHandler\nfrom servicecatalog.models import ServiceBlueprint\nfrom accounts.models import Group\nimport boto3\nfrom botocore.exceptions import ClientError\nimport ast\nimport time\n\n\ndef get_boto_client(resource=None, boto_service=''):\n if resource == None:\n return None\n env = Environment.objects.get(vpc_id=resource.vpc_id)\n rh = env.resource_handler.cast()\n client = boto3.client(boto_service,\n region_name=resource.aws_region,\n aws_access_key_id=rh.serviceaccount,\n aws_secret_access_key=rh.servicepasswd\n )\n return client, env\n\n\ndef generate_options_for_node_instance_type(**kwargs):\n instance_types = [\"t2.small\", \"t2.medium\", \"t2.large\", \"t2.xlarge\", \"t2.2xlarge\", \"t3.nano\", \"t3.micro\", \"t3.small\", \"t3.medium\", \"t3.large\", \"t3.xlarge\", \"t3.2xlarge\", \"m3.medium\", \"m3.large\", \"m3.xlarge\", \"m3.2xlarge\", \"m4.large\", \"m4.xlarge\", \"m4.2xlarge\", \"m4.4xlarge\", \"m4.10xlarge\", \"m5.large\", \"m5.xlarge\", \"m5.2xlarge\", \"m5.4xlarge\", \"m5.12xlarge\", \"m5.24xlarge\", \"c4.large\", \"c4.xlarge\", \"c4.2xlarge\", \"c4.4xlarge\", \"c4.8xlarge\", \"c5.large\", \"c5.xlarge\", \"c5.2xlarge\", \"c5.4xlarge\", \"c5.9xlarge\", \"c5.18xlarge\", \"i3.large\", \"i3.xlarge\", \"i3.2xlarge\",\n \"i3.4xlarge\", \"i3.8xlarge\", \"i3.16xlarge\", \"r3.xlarge\", \"r3.2xlarge\", \"r3.4xlarge\", \"r3.8xlarge\", \"r4.large\", \"r4.xlarge\", \"r4.2xlarge\", \"r4.4xlarge\", \"r4.8xlarge\", \"r4.16xlarge\", \"x1.16xlarge\", \"x1.32xlarge\", \"p2.xlarge\", \"p2.8xlarge\", \"p2.16xlarge\", \"p3.2xlarge\", \"p3.8xlarge\", \"p3.16xlarge\", \"p3dn.24xlarge\", \"r5.large\", \"r5.xlarge\", \"r5.2xlarge\", \"r5.4xlarge\", \"r5.12xlarge\", \"r5.24xlarge\", \"r5d.large\", \"r5d.xlarge\", \"r5d.2xlarge\", \"r5d.4xlarge\", \"r5d.12xlarge\", \"r5d.24xlarge\", \"z1d.large\", \"z1d.xlarge\", \"z1d.2xlarge\", \"z1d.3xlarge\", \"z1d.6xlarge\", \"z1d.12xlarge\"]\n return instance_types\n\n\ndef generate_options_for_subnets(resource=None, server=None, **kwargs):\n options = []\n if resource is not None:\n client, _ = get_boto_client(resource, 'ec2')\n response = client.describe_subnets(Filters=[\n {\n 'Name': 'state',\n 'Values': ['available']\n },\n {\n 'Name': 'vpc-id',\n 'Values': [resource.vpc_id]\n }\n ])\n subnets = response['Subnets']\n for subnet in subnets:\n options.append(subnet['SubnetId'])\n return options\n\n\ndef generate_options_for_cluster_security_group(resource=None, server=None, **kwargs):\n if resource is not None:\n options = ast.literal_eval(resource.security_groups)\n return options\n\n\ndef create_custom_fields():\n CustomField.objects.get_or_create(\n name='stack_id',\n defaults={\n \"label\": 'AWS EKS Stack ID',\n \"type\": 'STR',\n \"show_as_attribute\": True\n }\n )\n CustomField.objects.get_or_create(\n name='cluster_security_group',\n defaults={\n \"label\": 'AWS cluster control plane security group',\n \"type\": 'STR',\n \"show_as_attribute\": True\n }\n )\n CustomField.objects.get_or_create(\n name='node_group_name',\n defaults={\n \"label\": 'AWS EKS Stack Node Group Name',\n \"type\": 'STR',\n \"show_as_attribute\": True\n }\n )\n CustomField.objects.get_or_create(\n name='scaling_max_size',\n defaults={\n \"label\": 'AWS EKS Stack Max Size',\n \"type\": 'STR',\n \"show_as_attribute\": True\n }\n )\n CustomField.objects.get_or_create(\n name='scaling_min_size',\n defaults={\n \"label\": 'AWS EKS Stack Min Size',\n \"type\": 'STR',\n \"show_as_attribute\": True\n }\n )\n CustomField.objects.get_or_create(\n name='scaling_desired_capacity',\n defaults={\n \"label\": 'AWS EKS Stack Scaling Desired Capacity',\n \"type\": 'STR',\n \"show_as_attribute\": True\n }\n )\n CustomField.objects.get_or_create(\n name='node_instance_type',\n defaults={\n \"label\": 'AWS EKS Stack Node Instance Type',\n \"type\": 'STR',\n \"show_as_attribute\": True\n }\n )\n CustomField.objects.get_or_create(\n name='node_image_id',\n defaults={\n \"label\": 'AWS EKS Stack Node Image ID',\n \"type\": 'STR',\n \"show_as_attribute\": True\n }\n )\n CustomField.objects.get_or_create(\n name='node_volume_size',\n defaults={\n \"label\": 'AWS EKS Stack Node Volume Size',\n \"type\": 'STR',\n \"show_as_attribute\": True\n }\n )\n CustomField.objects.get_or_create(\n name='key_name',\n defaults={\n \"label\": 'AWS EKS Stack Key Name',\n \"type\": 'STR',\n \"show_as_attribute\": True\n }\n )\n CustomField.objects.get_or_create(\n name='bootstrap_arguments',\n defaults={\n \"label\": 'AWS EKS Stack Bootstrap Arguments',\n \"type\": 'STR',\n \"show_as_attribute\": True\n }\n )\n\ndef run(resource, logger=None, **kwargs):\n rh = AWSHandler.objects.get(id=resource.aws_rh_id)\n stack_name = '{{ stack_name }}'\n cluster_name = resource.name\n cluster_security_group = '{{cluster_security_group}}'\n\n # Worker node parameters\n node_group_name = '{{node_group_name}}'\n scaling_min_size = '{{scaling_min_size}}'\n scaling_desired_capacity = '{{scaling_desired_capacity}}'\n scaling_max_size = '{{scaling_max_size}}'\n node_instance_type = '{{node_instance_type}}'\n node_image_id = '{{node_image_id}}'\n node_volume_size = '{{node_volume_size}}'\n key_name = '{{key_name}}'\n bootstrap_arguments = '{{bootstrap_arguments}}'\n\n # Network Configuration\n vpc_id = resource.vpc_id\n subnets = ast.literal_eval(\"{{subnets}}\")\n\n create_custom_fields()\n resource_type, _ = ResourceType.objects.get_or_create(name=\"Stack\")\n blueprint, _ = ServiceBlueprint.objects.get_or_create(\n name=\"Amazon EKS Stack\")\n group = Group.objects.first()\n set_progress('Connecting to Amazon EKS')\n client = boto3.client('cloudformation',\n region_name=resource.aws_region,\n aws_access_key_id=rh.serviceaccount,\n aws_secret_access_key=rh.servicepasswd\n )\n\n set_progress('Creating Amazon EKS stack \"{}\"'.format(stack_name))\n\n try:\n parameters = [\n {\"ParameterKey\": \"ClusterControlPlaneSecurityGroup\",\n \"ParameterValue\": cluster_security_group},\n {\"ParameterKey\": \"NodeGroupName\", \"ParameterValue\": node_group_name},\n {\"ParameterKey\": \"NodeAutoScalingGroupMinSize\",\n \"ParameterValue\": scaling_min_size},\n {\"ParameterKey\": \"NodeAutoScalingGroupDesiredCapacity\",\n \"ParameterValue\": scaling_desired_capacity},\n {\"ParameterKey\": \"NodeAutoScalingGroupMaxSize\",\n \"ParameterValue\": scaling_max_size},\n {\"ParameterKey\": \"NodeInstanceType\",\n \"ParameterValue\": node_instance_type},\n {\"ParameterKey\": \"ClusterName\", \"ParameterValue\": cluster_name},\n {\"ParameterKey\": \"NodeVolumeSize\",\n \"ParameterValue\": node_volume_size},\n {\"ParameterKey\": \"KeyName\", \"ParameterValue\": key_name},\n {\"ParameterKey\": \"NodeVolumeSize\",\n \"ParameterValue\": node_volume_size},\n {\"ParameterKey\": \"BootstrapArguments\",\n \"ParameterValue\": bootstrap_arguments},\n {\"ParameterKey\": \"VpcId\", \"ParameterValue\": vpc_id},\n {\"ParameterKey\": \"NodeImageId\", \"ParameterValue\": node_image_id}\n ]\n\n for subnet in subnets:\n parameters.append(\n {\"ParameterKey\": \"Subnets\", \"ParameterValue\": subnet})\n\n response = client.create_stack(\n StackName=stack_name,\n TemplateURL='https://amazon-eks.s3-us-west-2.amazonaws.com/cloudformation/2019-02-11/amazon-eks-nodegroup.yaml',\n Parameters=parameters,\n Capabilities=['CAPABILITY_IAM']\n )\n set_progress('Creating stack \"{}\"'.format(stack_name))\n res, _ = Resource.objects.get_or_create(\n name=stack_name,\n defaults={\n 'blueprint': blueprint,\n 'group': group,\n 'parent_resource': resource,\n 'lifecycle': 'Active',\n 'resource_type': resource_type})\n res.stack_id = response['StackId']\n res.cluster_security_group=cluster_security_group\n res.node_group_name = node_group_name\n res.scaling_min_size = scaling_min_size\n res.scaling_desired_capacity = scaling_desired_capacity\n res.scaling_max_size = scaling_max_size\n res.node_instance_type = node_instance_type\n res.node_image_id = node_image_id\n res.node_volume_size = node_volume_size\n res.key_name = key_name\n res.bootstrap_arguments = bootstrap_arguments\n response = client.describe_stacks(\n StackName=stack_name\n )\n stacks = response['Stacks']\n # wait for stack to be created. Check status every minutes\n while stacks[0]['StackStatus'] == 'CREATE_IN_PROGRESS':\n set_progress('status of {}: \"{}\"'.format(\n stack_name, stacks[0]['StackStatus']))\n time.sleep(60)\n response = client.describe_stacks(\n StackName=stack_name\n )\n stacks = response['Stacks']\n\n res.save()\n if stacks[0]['StackStatus'] == 'CREATE_COMPLETE':\n return \"SUCCESS\", \"Stack creation was successful\", \"\"\n else:\n return \"FAILURE\", \"Stack creation was not successful\", \"\"\n except ClientError as e:\n set_progress('AWS ClientError: {}'.format(e))\n return \"FAILURE\", \"\", e\n except Exception as err:\n return \"FAILURE\", \"\", err\n","sub_path":"blueprints/eks/management/launch_nodes.py","file_name":"launch_nodes.py","file_ext":"py","file_size_in_byte":10361,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"398625638","text":"# -*- coding: utf-8 -*-\n\nfrom odoo import models, fields, api\n\nclass ArkcoModifierApprovingMatrixRFQ(models.Model):\n _inherit = 'purchase.order'\n\n \n @api.depends('amount_total','approving_matrix_id')\n def _get_approval_matrix_line(self):\n for rec in self:\n rec.approving_matrix_line_ids = False\n approval_matrix_lines = []\n if rec.approving_matrix_id:\n if rec.approving_matrix_id.matrix_type == 'amount':\n max_amount_list = []\n matrix = self.env['pr.approving.matrix'].search([('id', '=', rec.approving_matrix_id.id)])\n for line in matrix.line_ids:\n max_amount_list.append(line.max_amount)\n for line in matrix.line_ids:\n if (rec.amount_total <= line.max_amount) and (rec.amount_total >= line.min_amount):\n approval_lines = line\n elif (rec.amount_total >= line.max_amount) and (max(max_amount_list) == line.max_amount):\n approval_lines = line\n else:\n approval_lines = rec.approving_matrix_id.line_ids\n\n for line in approval_lines:\n approval_matrix_lines.append([0, 0, {\n 'employee_ids': [(6,0, line.employee_ids.ids)],\n 'name': line.name,\n 'min_amount': line.min_amount,\n 'max_amount':line.max_amount,\n 'approved': False,\n }\n ])\n if approval_matrix_lines:\n rec.approving_matrix_line_ids = approval_matrix_lines","sub_path":"beta-dev1/arkco_modifier_approving_matrix_rfq/models/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1726,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"7037887","text":"'''\n## 1 ##\njavaParser解析完成后存入数据库class表中\n本方法将class中的方法抽取并存入method表中\n'''\n\n\nfrom pymongo import MongoClient\n\n#获取方法体ast节点列表\ndef getMethodNodeList(node_list, method_start_line, method_end_line):\n method_node_list = []\n for node in node_list:\n node_start_line = node['startLine']\n if node_start_line in range(method_start_line, method_end_line+1):\n method_node_list.append(node)\n return method_node_list\n\n#获取方法体源代码\ndef getMethodSourceCode(source_code, method_start_line, method_end_line):\n method_code = []\n for code_line in source_code:\n line_num= code_line['line_num']\n if line_num in range(method_start_line, method_end_line+1):\n method_code.append(code_line)\n return method_code\n\n#\ndef getMethodComments(comment_doc_list, method_start_line, method_end_line):\n method_comment_list = []\n for comment_doc in comment_doc_list:\n comment_line = comment_doc['startline']\n if comment_line in range(method_start_line, method_end_line + 1):\n method_comment_list.append(comment_doc)\n return method_comment_list\n\n#从class中找到方法体及其对应信息\ndef findMethodDoc(classDoc):\n project_name = classDoc['projectName']\n class_name = classDoc['className']\n source_code = classDoc['sourceCode']\n node_list = classDoc['nodeList']\n method_scope_list = classDoc['method_scope_list']\n comment_doc_list = classDoc['comment_doc_list']\n method_doc_list = []\n\n for method_scope in method_scope_list:\n method_doc = method_scope\n method_start_line = method_scope['start'] #方法起始行\n method_end_line = method_scope['end'] #方法截止行\n method_node_list = getMethodNodeList(node_list, method_start_line, method_end_line) #获取方法体ast节点列表\n method_source_code = getMethodSourceCode(source_code, method_start_line, method_end_line) #获取方法体源代码\n method_comment_list = getMethodComments(comment_doc_list, method_start_line, method_end_line) #获取方法体内注释\n method_doc['method_node_list'] = method_node_list\n method_doc['method_source_code'] = method_source_code\n method_doc['method_comment_list'] = method_comment_list\n method_doc['project_name'] = project_name\n method_doc['class_name'] = class_name\n method_doc_list.append(method_doc)\n\n return method_doc_list\n\n\nif __name__ == \"__main__\":\n #连接数据库\n client = MongoClient(\"localhost\", 27017)\n db = client['deepScope']\n coll = db['class_all']\n coll_new = db['method']\n print(\"Database connected!\")\n\n #遍历数据库class\n count = 0\n for classDoc in coll.find():\n #从class中找到方法体及其对应信息\n method_doc_list = findMethodDoc(classDoc)\n if method_doc_list:\n coll_new.insert_many(method_doc_list)\n count += 1\n print(count)","sub_path":"sysu_commentScope_deepScope/dataPreprocess/methodExtract.py","file_name":"methodExtract.py","file_ext":"py","file_size_in_byte":2995,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"153339560","text":"import falcon\nfrom meniscus.api import ApiResource\nfrom meniscus.api import load_body\nfrom meniscus.api.pairing.pairing_process import PairingProcess\n\n\nclass PairingConfigurationResource(ApiResource):\n \"\"\"\n Webhook callback for the system package coordinator to\n configure the worker for pairing with its coordinator\n \"\"\"\n\n def on_post(self, req, resp):\n body = load_body(req)\n\n api_secret = body['api_secret']\n coordinator_uri = body['coordinator_uri']\n personality = body['personality']\n\n #start pairing on a separate process\n pairing_process = PairingProcess(\n api_secret, coordinator_uri, personality)\n pairing_process.run()\n\n resp.status = falcon.HTTP_200\n","sub_path":"meniscus/api/pairing/resources.py","file_name":"resources.py","file_ext":"py","file_size_in_byte":743,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"487745127","text":"#!/usr/bin/env python\nimport rospy\nimport carla\nfrom carla_waypoint_publisher import CarlaToRosWaypointConverter\n\nclass ConfigurableWayPointConverter(CarlaToRosWaypointConverter):\n def __init__(self, carla_world):\n super(ConfigurableWayPointConverter, self).__init__(carla_world)\n self.goal_index = int(rospy.get_param(\"~goal_index\", '0'))\n self.goal_pose = rospy.get_param(\"~goal_pose\", \"\")\n pose_set = False\n if len(self.goal_pose) > 10:\n self.goal_pose = self.goal_pose.split(',')\n if len(spawn_point) == 6:\n carla_goal = carla.Transform()\n carla_goal.location.x = float(self.goal_pose[0])\n carla_goal.location.y = -float(self.goal_pose[1])\n carla_goal.location.z = float(self.goal_pose[2]) + 2 # 2m above ground\n yaw = float(self.goal_pose[5])\n carla_goal.rotation.yaw = -math.degrees(yaw)\n if pose_set:\n self.goal = carla_goal\n else:\n self.goal = self.world.get_map().get_spawn_points()[self.goal_index]\n\ndef main():\n \"\"\"\n main function\n \"\"\"\n rospy.init_node(\"carla_waypoint_publisher\", anonymous=True)\n\n host = rospy.get_param(\"/carla/host\", \"127.0.0.1\")\n port = rospy.get_param(\"/carla/port\", 2000)\n\n rospy.loginfo(\"Trying to connect to {host}:{port}\".format(\n host=host, port=port))\n\n try:\n carla_client = carla.Client(host=host, port=port)\n carla_client.set_timeout(2)\n\n carla_world = carla_client.get_world()\n\n rospy.loginfo(\"Connected to Carla.\")\n\n waypointConverter = ConfigurableWayPointConverter(carla_world)\n\n rospy.spin()\n del waypointConverter\n del carla_world\n del carla_client\n\n finally:\n rospy.loginfo(\"Done\")\n\n\nif __name__ == \"__main__\":\n main()","sub_path":"src/cvsc/carla_waypoint_publisher/src/carla_waypoint_publisher/configurable_waypoint_publisher.py","file_name":"configurable_waypoint_publisher.py","file_ext":"py","file_size_in_byte":1860,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"261273217","text":"from django.conf.urls import url\n\nfrom . import views\n\nurlpatterns = [\n url(r'^event$', views.event, name='event'),\n url(r'^event_submit$', views.event_submit, name='event_submit'),\n url(r'^profile$', views.profile, name='profile'),\n url(r'^instructions$', views.instructions, name='instructions'),\n url(r'^pokedex$', views.pokedex, name='pokedex'),\n url(r'^scorepage$', views.scorepage, name='scorepage'),\n]","sub_path":"pokequest/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":426,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"611533398","text":"# Definition for a binary tree node\r\n# class TreeNode:\r\n# def __init__(self, x):\r\n# self.val = x\r\n# self.left = None\r\n# self.right = None\r\n \r\nclass Solution:\r\n # @param A : root node of tree\r\n # @return a list of integers\r\n def solve(self, root):\r\n def height(root):\r\n if not root:\r\n return 0\r\n lheight=height(root.left)\r\n rheight=height(root.right)\r\n if lheight>rheight:\r\n return lheight+1\r\n else:\r\n return rheight+1\r\n def curLevel(root,level,ans):\r\n if not root:\r\n return \r\n if level==1:\r\n ans.append(root.val)\r\n elif level>1:\r\n curLevel(root.left,level-1,ans)\r\n curLevel(root.right,level-1,ans)\r\n return ans\r\n h=height(root)\r\n res=[]\r\n for i in range(h,0,-1):\r\n res+=curLevel(root,i,[])\r\n return res","sub_path":"Programming/Tree Data Structure/Level Order/Reverse Level Order.py","file_name":"Reverse Level Order.py","file_ext":"py","file_size_in_byte":993,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"591624792","text":"import pickle \r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport pandas as pd\r\n\r\n\r\ndef loadData(fileName): \r\n # for reading also binary mode is important \r\n dbfile = open(fileName, 'rb') \r\n db = pickle.load(dbfile) \r\n #print(\"Length: \",len(db))\r\n \r\n #print(db)\r\n \r\n #for i in range(5):\r\n #print(db[i])\r\n dbfile.close() \r\n return db\r\n\r\n\r\ndef createDataforAxes(Alist,column):\r\n Alist = Alist[:,[column]]\r\n Alist = Alist[1:]\r\n Alist = np.reshape(Alist,(1,4))\r\n Alist = Alist[0]\r\n Alist = [float(i) for i in Alist]\r\n return Alist\r\n\r\n\r\nsimple = loadData('EpochVsAccuracy')\r\nbatch = loadData('EpochVsAccuracyBatch')\r\n\r\nsimple = np.asarray(simple)\r\nsimple_epochs = createDataforAxes(simple,0)\r\n\r\nsimple_times = createDataforAxes(simple,1)\r\n#print(simple_times)\r\n#print(batch)\r\n\r\nsimple_acc =createDataforAxes(simple,2)\r\n\r\nbatch = np.asarray(batch)\r\nbatch_times = createDataforAxes(batch,1)\r\nbatch_acc = createDataforAxes(batch,2)\r\n\r\ndef smooth(y, box_pts):\r\n box = np.ones(box_pts)/box_pts\r\n y_smooth = np.convolve(y, box, mode='same')\r\n return y_smooth\r\n\r\n\r\ndf=pd.DataFrame({'x': simple_epochs, 'y1': simple_times, 'y2': batch_times})\r\n\r\nplt.subplot(1,2,1)\r\nplt.plot('x', 'y1', data=df, linestyle='--', color = 'r' )\r\nplt.plot( 'x', 'y2', data=df,linestyle='--', color = 'g')\r\nplt.title('Time Vs. Epoch')\r\n\r\nplt.subplot(1,2,2)\r\nplt.plot( simple_epochs,simple_acc,linestyle='-', color = 'r')\r\nplt.plot( simple_epochs,batch_acc,linestyle='-', color = 'g')\r\nplt.title('Acc Vs. Epoch')\r\nplt.suptitle('Comparisons')\r\nplt.legend()\r\nplt.show()","sub_path":"MapTracer.py","file_name":"MapTracer.py","file_ext":"py","file_size_in_byte":1612,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"367529227","text":"\nimport json\nimport urllib.request\nimport facebook\nfrom rest_framework import status\nfrom rest_framework.views import APIView\nfrom rest_framework.response import Response\n\n# from api.serializers import SinglePostSerializer\n\n\ndef getGraph(request, given_access_token=None):\n user = request.user\n social = user.social_auth.get(provider='facebook')\n extra_data = social.extra_data\n if given_access_token:\n access_token = given_access_token\n else:\n access_token = extra_data.get('access_token')\n graph = facebook.GraphAPI(access_token=access_token, version=\"2.11\")\n return graph\n\n\n\nclass PagePostListView(APIView):\n\n def get(self, request, id):\n\n response_data = self.FbPageDetail(id)\n return Response(response_data)\n\n def FbPageDetail(self, page_id):\n graph = getGraph(self.request)\n page_only_access = graph.get_object(id=page_id, fields=\"access_token\")\n page_access_token = page_only_access.get('access_token')\n page_graph = getGraph(self.request, page_access_token)\n page = page_graph.get_object(id=page_id, fields=\"access_token,posts{created_time,id,message,attachments,type,permalink_url}\")\n\n insight_data = []\n\n for i in page.get('posts').get('data'):\n item = page_graph.get_connections(id=i.get('id'), connection_name='insights/post_video_views')\n insight_data.append(item)\n\n retinsight_data = {}\n\n\n for each in insight_data:\n\n first_data = each.get('data')[0]\n retinsight_data[first_data.get('id').split('/')[0]] = first_data.get('values')[0].get('value')\n\n\n return {'retinsight_data': retinsight_data, 'posts': page.get('posts'), 'access_token': page.get('access_token')}\n\n\nclass PagePostDeleteView(APIView):\n\n def get(self, request, id):\n\n response_data = self.FbPageDetail(id)\n return Response(response_data)\n\n def FbPageDelete(self, page_id):\n graph = getGraph(self.request)\n page = graph.delete_object(id='post_id')\n return Response(page)\n\n\nclass PageNextView(APIView):\n\n def get(self, request):\n\n get_data = request.GET\n raw_url = get_data.get('raw_url')\n page_id = get_data.get('page_id')\n\n response = urllib.request.urlopen(raw_url)\n data = json.load(response)\n\n\n graph = getGraph(self.request)\n page_only_access = graph.get_object(id=page_id, fields=\"access_token\")\n page_access_token = page_only_access.get('access_token')\n page_graph = getGraph(self.request, page_access_token)\n page = page_graph.get_object(id=page_id, fields=\"access_token,posts{created_time,id,message,attachments,type,permalink_url}\")\n\n insight_data = []\n\n for i in page.get('posts').get('data'):\n item = page_graph.get_connections(id=i.get('id'), connection_name='insights/post_impressions_unique/lifetime?fields=name,id,period,values')\n insight_data.append(item)\n\n\n retinsight_data = {}\n\n for each in insight_data:\n\n first_data = each.get('data')[0]\n retinsight_data[first_data.get('id').split('/')[0]] = first_data.get('values')[0].get('value')\n\n\n # return Response(data)\n return Response({'data': data, 'retinsight_data': retinsight_data})\n\n\nclass PagePostDAddView(APIView):\n\n def post(self, request, format=None):\n post_data = request.POST\n message = post_data.get('pMessage')\n page_id = post_data.get('page_id')\n access_token = post_data.get('access_token')\n is_published = post_data.get('is_published')\n\n if is_published == 'on':\n is_published = True\n else:\n is_published = False\n graph = getGraph(self.request, access_token)\n graph.put_object(parent_object=page_id, connection_name='feed', message=message, published=is_published)\n\n # graph.put_photo(image=open('img.jpg', 'rb'),\n # message='Look at this cool photo!')\n\n\n return Response(status=status.HTTP_200_OK)\n","sub_path":"api/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4045,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"380665729","text":"#!/usr/bin/env python\n# encoding: utf-8\n\ndef canJump(A):\n n = len(A)\n if n<= 1:\n return True\n\n if A[0] == 0:\n return False\n\n zeros=[]\n for i in range(1, n-1):\n if A[i]==0 and A[i+1]!=0:\n zeros.append(i)\n if A[-1]==A[-2] and A[-1]==0:\n zeros.append(n-2)\n\n if not zeros:\n return True\n\n last =-1\n for ix in zeros:\n if not isJump(A, last, ix):\n return False\n last = ix\n return True\n\ndef isJump(A,last, ix):\n for i in range(last +1, ix):\n if A[i] > ix- i:\n return True\n return False\n\n\n\nA =[1,0,0,1,1,2,2,0,0,0]\nprint(canJump(A))\n","sub_path":"week29/jump_game.py","file_name":"jump_game.py","file_ext":"py","file_size_in_byte":649,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"84110108","text":"#!/usr/bin/python\n\n__author__ = 'gdiaz'\n\nimport rospy\nimport random\n\nfrom threading import Thread\n\nfrom std_msgs.msg import UInt16, String\n\n# Use HW interface\nfrom uchile_soft_hand.hand_interface import HandInterface\n\nclass HandController(object):\n\n DEV_ID = 36\n def __init__(self, dxl_io, controller_namespace, port_namespace):\n \"\"\"\n Provides a high level interface over ROS for reading tactil-sensor data from Bender soft hand.\n It use methods provided by HandInterface class (non ROS hardware interface). See Documentation.\n \"\"\"\n # Only argument stuff\n self.running = False\n self.dxl_io = dxl_io\n\n self.controller_namespace = controller_namespace\n self.port_namespace = port_namespace\n\n self.state_update_rate = rospy.get_param(self.controller_namespace + '/rate', 2)\n rospy.logwarn(\"Using rate: {}\".format(self.state_update_rate))\n self.device_id = rospy.get_param(self.controller_namespace + '/id', 1)\n rospy.logwarn(\"Using id: {}\".format(self.device_id))\n self.hand_interface = HandInterface(dxl_io, dev_id=self.device_id)\n self.left_side_pressure = UInt16()\n self.right_side_pressure = UInt16()\n \n def initialize(self):\n self.left_side_pressure.data = 0\n return True\n\n def start(self):\n # Create subs, services, publishers, threads\n self.running = True\n # subscribers\n self.command_sub = rospy.Subscriber(self.controller_namespace + '/soft_hand_cmd', String, self.process_command)\n\n # publishers\n self.left_side_pressure_pub = rospy.Publisher(self.controller_namespace + '/left_side_pressure', UInt16, queue_size=50)\n self.right_side_pressure_pub = rospy.Publisher(self.controller_namespace + '/right_side_pressure', UInt16, queue_size=50)\n Thread(target=self.update_state).start()\n\n def stop(self):\n self.running = False\n self.command_sub.unregister()\n self.left_side_pressure_pub.unregister()\n\n def process_command(self, msg):\n rospy.logwarn(\"Not implemented yet:\")\n\n def update_state(self):\n rate = rospy.Rate(self.state_update_rate)\n while self.running and not rospy.is_shutdown():\n\n #update sensors data\n self.left_side_pressure.data = self.hand_interface.read_tactil_sensor(1)\n self.right_side_pressure.data = self.hand_interface.read_tactil_sensor(2)\n\n #publish data\n self.left_side_pressure_pub.publish(self.left_side_pressure)\n self.right_side_pressure_pub.publish(self.left_side_pressure)\n rate.sleep()","sub_path":"interface/hand_controller.py","file_name":"hand_controller.py","file_ext":"py","file_size_in_byte":2648,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"178724742","text":"HELP_STRING=\"\"\"\n\nDate : April 22,2021\n\nAuthor : Ruiyan Hou (ruiyan_hou@163.com)\n\nThis script will produce the figure 1 in the supplementary.\nWe take the pancreas dataset as an example to show the relationship between the log(gamma') in stochastic model and \nthe log(gamma') in dynamical model.\n\n\"\"\"\n\n\n# -*- coding: utf-8 -*-\nimport matplotlib\nmatplotlib.use('Agg')\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom hilearn import corr_plot\nimport pylab as pl\n\n\n#arrange data\nbetadf=pd.read_csv('/home/houruiyan/scRNAkineticprediction/scRNA-kinetics-prediction/data/estimated/pancreas_dynamical_beta_gamma.csv',index_col=0)\nprint(betadf)\ngammadf=pd.read_csv('/home/houruiyan/scRNAkineticprediction/scRNA-kinetics-prediction/data/estimated/pancreas_stochastical_gamma.csv',index_col=0)\nprint(gammadf)\nmergedf=pd.merge(betadf,gammadf,on='gene_id',how='left')\nmergedf.dropna(how='any',inplace=True)\nprint(mergedf)\nbetaX=((mergedf['log(fit_gamma)'].apply(lambda x:np.exp(x)))/(mergedf['log(fit_beta)'].apply(lambda x:np.exp(x)))).apply(np.log)\ngammaX=mergedf['log(velocity_gamma)']\nbetaX=betaX.values\ngammaX=gammaX.values\n\n\n\n#plot\ncorr_plot(betaX,gammaX,size=20,dot_color='tomato',alpha=0.8)\npl.xlabel(u\"Log(γ') in dynamical model\",fontsize=15)\npl.ylabel(u\"Log(γ') in stochastic model\",fontsize=15)\npl.title(u\"Pancreas\",fontsize=18,fontweight='medium')\nplt.legend(prop={'size':15})\nplt.savefig(\"/home/houruiyan/scRNAkineticprediction/figure/supp/FigS2/pancreas.pdf\", dpi=300, bbox_inches='tight')\nplt.show()","sub_path":"notebooks/figure/FigS1.py","file_name":"FigS1.py","file_ext":"py","file_size_in_byte":1530,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"338413009","text":"import numpy as np\r\nfrom osgeo import gdal\r\nfrom skimage.morphology import black_tophat, square, white_tophat\r\nfrom skimage.transform import rotate\r\n\r\n\r\n\r\ndef grayscale_raster_creation(input_MSfile, output_filename):\r\n \"\"\" \r\n This function creates a grayscale brightness image from an input image to be used for MBI calculation. For every pixel \r\n in the input image, the intensity values from the red, green, blue channels are first obtained, and the maximum of these values \r\n are then assigned as the pixel's intensity value, which would give the grayscale brightness image as mentioned earlier, as per \r\n standard practice in the remote sensing academia and industry. It is assumed that the first three channels of the input image \r\n correspond to the red, green and blue channels, irrespective of order.\r\n \r\n Inputs:\r\n - input_MSfile: File path of the input image that needs to be converted to grayscale brightness image\r\n - output_filename: File path of the grayscale brightness image that is to be written to file\r\n \r\n Outputs:\r\n - gray: Numpy array of grayscale brightness image of corresponding multi - channel input image\r\n \r\n \"\"\"\r\n \r\n image = np.transpose(gdal.Open(input_MSfile).ReadAsArray(), [1, 2, 0])\r\n gray = np.zeros((int(image.shape[0]), int(image.shape[1])))\r\n \r\n for i in range(image.shape[0]):\r\n for j in range(image.shape[1]):\r\n gray[i, j] = max(image[i, j, 0], image[i, j, 1], image[i, j, 2])\r\n \r\n input_dataset = gdal.Open(input_MSfile)\r\n input_band = input_dataset.GetRasterBand(1)\r\n gtiff_driver = gdal.GetDriverByName('GTiff')\r\n output_dataset = gtiff_driver.Create(output_filename, input_band.XSize, input_band.YSize, 1, gdal.GDT_Float32)\r\n output_dataset.SetProjection(input_dataset.GetProjection())\r\n output_dataset.SetGeoTransform(input_dataset.GetGeoTransform())\r\n output_dataset.GetRasterBand(1).WriteArray(gray)\r\n \r\n output_dataset.FlushCache()\r\n del output_dataset\r\n \r\n return gray\r\n\r\n \r\n \r\ndef MBI_MSI_calculation_and_feature_map_creation(input_grayfile, output_MBIname, output_MSIname, s_min, s_max, delta_s, \r\n calc_MSI = False, write_MBI = True, write_MSI = False):\r\n \"\"\" \r\n This function is used to calculate the Morphological Building Index (MBI) as proposed in the paper 'Morphological \r\n Building - Shadow Index for Building Extraction From High - Resolution Imagery Over Urban Areas' by Xin Huang and \r\n Liangpei Zhang (2012). \r\n \r\n Inputs:\r\n - input_grayfile: String or path of grayscale tif file to be used.\r\n - output_MBIname: String or path of MBI feature map to be written.\r\n - output_MSIname: String or path of MSI feature map to be written.\r\n - s_min: Minimum scale size to be used. (must be greater than or equal to 3).\r\n - s_max: Maximum scale size to be used.\r\n - delta_s: Spatial increment for scale size\r\n - calc_MS: Boolean indicating whether to calculate MSI.\r\n - write_MBI: Boolean indicating whether to write MBI feature map to file.\r\n - write_MSI: Boolean indicating whether to write MSI feature map to file.\r\n \r\n Outputs:\r\n - MBI: MBI feature map for input grayscale image.\r\n - MSI (optional): MSI feature map for input grayscale image.\r\n \r\n \"\"\"\r\n \r\n if s_min < 3:\r\n raise ValueError('s_min must be greater than or equal to 3.')\r\n \r\n gray = gdal.Open(input_grayfile).ReadAsArray() \r\n MP_MBI_list = []\r\n MP_MSI_list = []\r\n DMP_MBI_list = []\r\n DMP_MSI_list = []\r\n \r\n for i in range(s_min, s_max + 1, 2 * delta_s):\r\n SE_intermediate = square(i)\r\n SE_intermediate[ : int((i - 1) / 2), :] = 0\r\n SE_intermediate[int(((i - 1) / 2) + 1) : , :] = 0\r\n \r\n SE_1 = SE_intermediate\r\n SE_2 = rotate(SE_1, 45, order = 0, preserve_range = True).astype('uint8')\r\n SE_3 = rotate(SE_1, 90, order = 0, preserve_range = True).astype('uint8')\r\n SE_4 = rotate(SE_1, 135, order = 0, preserve_range = True).astype('uint8')\r\n \r\n MP_MBI_1 = white_tophat(gray, selem = SE_1)\r\n MP_MBI_2 = white_tophat(gray, selem = SE_2)\r\n MP_MBI_3 = white_tophat(gray, selem = SE_3)\r\n MP_MBI_4 = white_tophat(gray, selem = SE_4)\r\n \r\n if calc_MSI: \r\n MP_MSI_1 = black_tophat(gray, selem = SE_1)\r\n MP_MSI_2 = black_tophat(gray, selem = SE_2)\r\n MP_MSI_3 = black_tophat(gray, selem = SE_3)\r\n MP_MSI_4 = black_tophat(gray, selem = SE_4)\r\n \r\n MP_MSI_list.append(MP_MSI_1)\r\n MP_MSI_list.append(MP_MSI_2)\r\n MP_MSI_list.append(MP_MSI_3)\r\n MP_MSI_list.append(MP_MSI_4)\r\n \r\n MP_MBI_list.append(MP_MBI_1)\r\n MP_MBI_list.append(MP_MBI_2)\r\n MP_MBI_list.append(MP_MBI_3)\r\n MP_MBI_list.append(MP_MBI_4)\r\n \r\n \r\n for j in range(4, len(MP_MBI_list), 1):\r\n DMP_MBI_1 = np.absolute(MP_MBI_list[j] - MP_MBI_list[j - 4])\r\n DMP_MBI_list.append(DMP_MBI_1)\r\n \r\n if calc_MSI:\r\n DMP_MSI_1 = np.absolute(MP_MSI_list[j] - MP_MSI_list[j - 4])\r\n DMP_MSI_list.append(DMP_MSI_1)\r\n\r\n MBI = np.sum(DMP_MBI_list, axis = 0) / (4 * (((s_max - s_min) / delta_s) + 1))\r\n \r\n if calc_MSI:\r\n MSI = np.sum(DMP_MSI_list, axis = 0) / (4 * (((s_max - s_min) / delta_s) + 1))\r\n \r\n if write_MBI:\r\n input_dataset = gdal.Open(input_grayfile)\r\n input_band = input_dataset.GetRasterBand(1)\r\n gtiff_driver = gdal.GetDriverByName('GTiff')\r\n output_dataset = gtiff_driver.Create(output_MBIname, input_band.XSize, input_band.YSize, 1, gdal.GDT_Float32)\r\n output_dataset.SetProjection(input_dataset.GetProjection())\r\n output_dataset.SetGeoTransform(input_dataset.GetGeoTransform())\r\n output_dataset.GetRasterBand(1).WriteArray(MBI)\r\n \r\n output_dataset.FlushCache()\r\n del output_dataset\r\n \r\n if write_MSI:\r\n input_dataset_2 = gdal.Open(input_grayfile)\r\n input_band_2 = input_dataset_2.GetRasterBand(1)\r\n gtiff_driver_2 = gdal.GetDriverByName('GTiff')\r\n output_dataset_2 = gtiff_driver_2.Create(output_MSIname, input_band_2.XSize, input_band_2.YSize, 1, gdal.GDT_Float32)\r\n output_dataset_2.SetProjection(input_dataset_2.GetProjection())\r\n output_dataset_2.SetGeoTransform(input_dataset_2.GetGeoTransform())\r\n output_dataset_2.GetRasterBand(1).WriteArray(MSI)\r\n \r\n output_dataset_2.FlushCache()\r\n del output_dataset_2\r\n \r\n if calc_MSI: \r\n return MBI, MSI\r\n else:\r\n return MBI\r\n","sub_path":"Morphological Building Index.py","file_name":"Morphological Building Index.py","file_ext":"py","file_size_in_byte":6704,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"370217701","text":"## Config Variables, used to tweak game\n\nNUM_ROOMS = 30 # number of rooms in the map\nROOM_MIN_SIZE = 3 # minimum dimension for a room\nROOM_MAX_SIZE = 10 # max dimension for a room\nMAX_ROOM_INTERSECTS = 3 # max number of rooms that may intersect to form one room. Extra rooms above this are thrown out.\nMAP_WIDTH = 50 # width of the map\nMAP_HEIGHT = 50 # height of the map\n\nSCREEN_WIDTH = 640 # width of the screen the game runs in\nSCREEN_HEIGHT = 480 # height of the screen the game runs in\n\nTORCH_RADIUS = 7 # fov render distance\nFOV_LIGHT_WALLS = True # whether the FOV extends to visible wall tiles\nFOV_ALGO = 1 # fov algo to use","sub_path":"RoguePyGame(dev)/CONFIG.py","file_name":"CONFIG.py","file_ext":"py","file_size_in_byte":786,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"385073326","text":"from mypy_extensions import TypedDict\nfrom speclib import array\n\nblake2s_test = TypedDict('blake2s_test', {\n 'data': str,\n 'key': str,\n 'nn': int,\n 'output': str\n })\n\nblake2s_test_vectors = array([\n {'data': '616263',\n 'key': '',\n 'nn': 32,\n 'output': '508c5e8c327c14e2e1a72ba34eeb452f37458b209ed63a294d999b4c86675982'}\n])\n","sub_path":"specs/test_vectors/blake2s_test_vectors.py","file_name":"blake2s_test_vectors.py","file_ext":"py","file_size_in_byte":350,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"421541009","text":"# Copyright (c) 2017, 2018 Jae-jun Kang\n# See the file LICENSE for details.\n\nimport sys\n\nimport pytest\n\nsys.path.append('..')\nfrom x2py.fingerprint import Fingerprint\n\nfrom x2py.deserializer import Deserializer\nfrom x2py.serializer import Serializer\n\ndef test_creation():\n with pytest.raises(ValueError):\n fp = Fingerprint(-1)\n fp = Fingerprint(0)\n assert fp.length == 0\n assert fp.blocks is None\n fp = Fingerprint(32)\n assert fp.length == 32\n assert fp.blocks is None\n fp = Fingerprint(33)\n assert fp.length == 33\n assert len(fp.blocks) == 1\n fp = Fingerprint(64)\n assert fp.length == 64\n assert len(fp.blocks) == 1\n fp = Fingerprint(65)\n assert fp.length == 65\n assert len(fp.blocks) == 2\n\ndef test_copy_creation():\n for n in [32, 33]:\n fp1 = Fingerprint(n)\n indices = [0, 1, n - 2, n - 1]\n for i in indices:\n fp1.touch(i)\n fp2 = Fingerprint(fp1)\n for i in indices:\n assert fp2.get(i) == True\n # Make sure that we have a deep copy\n for i in indices:\n fp2.wipe(i)\n for i in indices:\n assert fp1.get(i) == True\n\ndef test_accessors():\n fp = Fingerprint(65)\n with pytest.raises(ValueError):\n fp.get(-1)\n fp.get(65)\n for i in range(65):\n assert fp.get(i) == False\n for i in [0, 1, 31, 32, 63]:\n fp.touch(i)\n assert fp.get(i) == True\n fp.wipe(i)\n assert fp.get(i) == False\n\ndef test_serialization():\n fp1 = Fingerprint(33)\n fp1.touch(31)\n fp1.touch(32)\n\n s = Serializer()\n fp1.serialize(s)\n assert len(s.buffer) == fp1.get_length()\n\n fp2 = Fingerprint(33)\n assert fp1 != fp2\n fp2.deserialize(Deserializer(s.buffer))\n assert fp1 == fp2\n\ndef test_equivalence():\n fp1 = Fingerprint(33)\n fp2 = Fingerprint(33)\n assert fp1.equivalent(fp1)\n assert fp1.equivalent(fp2)\n assert fp2.equivalent(fp1)\n fp1.touch(32)\n fp2.touch(31)\n fp2.touch(32)\n assert fp2.equivalent(fp1)\n assert not fp1.equivalent(fp2)\n\ndef test_eq_():\n fp1 = Fingerprint(33)\n fp2 = Fingerprint(33)\n assert fp1 == fp1\n assert fp1 == fp2\n assert not (fp1 != fp2)\n fp2.touch(32)\n assert not (fp1 == fp2)\n assert fp1 != fp2\n\ndef test_hash_():\n fp1 = Fingerprint(33)\n fp2 = Fingerprint(33)\n assert fp1.__hash__() == fp2.__hash__()\n fp2.touch(32)\n assert fp1.__hash__() != fp2.__hash__()\n\ndef test_lt_():\n fp1 = Fingerprint(32)\n fp2 = Fingerprint(33)\n fp3 = Fingerprint(33)\n assert not (fp1 < fp1)\n # with different lengths\n assert fp1 < fp2\n assert fp2 > fp1\n fp1.touch(0)\n assert fp1 < fp2\n # with same lengths\n assert not (fp2 < fp3)\n fp3.touch(31)\n assert fp2 < fp3\n fp2.touch(32)\n assert fp2 > fp3\n\n\n\n","sub_path":"tests/test_fingerprint.py","file_name":"test_fingerprint.py","file_ext":"py","file_size_in_byte":2819,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"453793074","text":"from django.http import HttpResponse, JsonResponse, HttpResponseRedirect\nfrom django.template import loader\nfrom django.shortcuts import render\nimport logging\nfrom .models import Endpoint\nfrom .forms import EndpointForm\n\ndef index(request):\n endpoints = Endpoint.objects.all()\n return render(request, 'index.html', {'endpoints': endpoints})\n\ndef addEndpoint(request):\n if request.method == 'POST':\n form = EndpointForm(request.POST)\n if form.is_valid():\n form.save()\n return HttpResponse(loader.get_template('thanks.html').render({}, request))\n else:\n form = EndpointForm()\n return render(request, 'add.html', {'form': form})\n\ndef endpoint(request, slug):\n endpoint = Endpoint.objects.get(url = slug, method = request.method)\n fomat = request.GET.get('format', 'html')\n\n if request.method == 'POST':\n endpoint.content = request.GET.get('content', endpoint.content)\n endpoint.save()\n\n if fomat == 'json' :\n response = JsonResponse({'content': endpoint.content}, status = endpoint.response_code)\n elif fomat == 'html' : \n response = HttpResponse( endpoint.content, status = endpoint.response_code)\n\n logger(request, response, slug)\n return response\n\ndef logger(request, response, slug):\n logging.basicConfig(filename='logging.log', format='%(asctime)s %(message)s', level=logging.INFO)\n logging.info('INFO {0} {1} {2} {3}'.format(slug, request.method, response.status_code, response.content))","sub_path":"api/mock/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1503,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"521270826","text":"#!/usr/bin/env python2.7\n# -*- coding: utf-8 -*-\n#\n# Copyright @ 2014 IT/CCOPS/OPSDEV, Qunar Inc. (qunar.com)\n#\n# Author: Jianing Yang \n#\n\nfrom flask.ext.sqlalchemy import SQLAlchemy\nfrom oslo.config import cfg\n\ndatabase_opts = [\n cfg.StrOpt('connection',\n default='sqlite:///rssboard.db',\n help='The database connection string'),\n]\n\nCONF = cfg.CONF\nCONF.register_cli_opts(database_opts, 'database')\nCONF.register_opts(database_opts, 'database')\n\ndb = SQLAlchemy(session_options={'autocommit': True})\ndb_admin = SQLAlchemy(session_options={'autocommit': False})\n\nfrom flask.ext.admin import Admin\nadmin = Admin()\n","sub_path":"openlb/extensions.py","file_name":"extensions.py","file_ext":"py","file_size_in_byte":669,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"34917715","text":"from graphviz import Digraph\n\nclass nodoDoble(object):\n\t\"\"\"docstring for nodoDoble\"\"\"\n\t\n\tdef __init__(self,dato):\n\t\t\n\t\tself.dato = dato\n\t\tself.siguiente = None\n\t\tself.anterior = None\n\n\nclass ListaDoble(object):\n\t\"\"\"docstring for ListaDoble\"\"\"\n\t\n\tdef __init__(self):\n\n\t\tself.inicio = None\n\n\n\tdef Insertar(self,dato):\n\n\t\tnuevo = nodoDoble(dato)\n\n\t\tif self.inicio == None:\n\n\t\t\tself.inicio = nuevo\n\t\t\tself.inicio.siguiente = self.inicio\n\t\t\tself.inicio.anterior = self.inicio\n\n\t\telse:\n\n\t\t\taux = self.inicio\n\n\t\t\twhile aux.siguiente != self.inicio and aux != None:\n\t\t\t\t\n\t\t\t\taux = aux.siguiente\n\n\t\t\taux.siguiente = nuevo\n\t\t\tnuevo.anterior = aux\n\t\t\tnuevo.siguiente = self.inicio\n\t\t\tself.inicio.anterior = nuevo\n\t\t\t\n\tdef Recorrer(self,usuario, contrasenia):\n\n\t\ttemp = self.inicio\n\t\tflag = False\n\n\t\twhile temp.siguiente != self.inicio:\n\n\t\t\tprint(\"Esta buscando\")\n\t\t\tprint(str(temp.dato.nombre))\n\t\t\t\n\t\t\tif temp.dato.nombre == usuario and temp.dato.pase == contrasenia:\n\n\t\t\t\tflag = True\n\t\t\t\tbreak\n\n\t\t\ttemp = temp.siguiente\n\n\t\tif temp.siguiente == self.inicio:\n\n\t\t\tif temp.dato.nombre == usuario and temp.dato.pase == contrasenia:\n\n\t\t\t\tflag = True\n\n\t\treturn str(flag)\n\n\tdef Graficar(self):\n\n\t\tg = Digraph('G', filename='DoubleList.gv', format='png')\n\n\t\tif self.inicio != None:\n\n\t\t\taux = self.inicio\n\n\t\t\twhile aux.siguiente != self.inicio:\n\n\t\t\t\tg.edge(str(aux.dato.nombre), str(aux.siguiente.dato.nombre))\n\t\t\t\tg.edge(str(aux.dato.nombre), str(aux.anterior.dato.nombre))\n\n\t\t\t\taux = aux.siguiente\n\n\t\t\tg.edge(str(aux.dato.nombre), str(aux.siguiente.dato.nombre))\n\t\t\tg.edge(str(aux.dato.nombre), str(aux.anterior.dato.nombre))\n\n\t\t\tg.view()\n\n\t\telse:\n\n\t\t\tprint (\"No se realizo la insercion\")","sub_path":"Servicios/Estructuras3.py","file_name":"Estructuras3.py","file_ext":"py","file_size_in_byte":1670,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"317913340","text":"from scipy.stats import binom\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nfig, ax = plt.subplots(1, 1)\nn, p = 25, 0.15\nx = np.arange(binom.ppf(0, n, p), binom.ppf(1, n, p))\nax.plot(x, binom.pmf(x, n, p), 'bo', label='binom pmf')\nax.vlines(x, 0, binom.pmf(x, n, p), colors='b', lw=5, alpha=0.5)\nax.legend(loc='best', frameon=False)\nplt.show()\n\n","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":351,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"371090214","text":"# Exercise with tuples which are IMMUTABLE\n# Can be created with the tuple function\n# Use [] to access things like a dictionary\n# Can have duplicate data\n\nmonths = (\n \"January\",\n \"February\",\n \"March\",\n \"April\",\n \"May\",\n \"June\",\n \"July\",\n \"August\",\n \"September\",\n \"October\",\n \"November\",\n \"December\",\n)\n\nprint(months[0])\n\n# Tuples can be used for keys in a dictionary but not lists\n\nlocations = {\n (35.123, 62.345): \"Tokyo Office\",\n (45.123, 92.345): \"London Office\",\n (25.123, 113.345): \"San Francisco Office\",\n}\n\nprint(locations[(35.123, 62.345)])\n\n# Example of how the dictionary method .items returns a tuple\n\ncat = {\"name\": \"Pudin\", \"age\": 5, \"toy\": \"yarn\"}\n\nprint(cat.items())\n","sub_path":"cs_python_lec/data_structures/tuples/tup_01.py","file_name":"tup_01.py","file_ext":"py","file_size_in_byte":729,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"61667388","text":"\"\"\"\r\nMain module for prototype with remodeled\r\ncollision detection\r\nWritten Jan 11, 2016 by Benjamin Reed\r\n\t\r\nCredit for this implementation goes to Sean J. McKiernan\r\n(Mekire) at /r/pygame\r\nhttps://github.com/Mekire\r\n\"\"\"\r\nimport sys\r\nimport Queue\r\n\r\nimport pygame as pyg\r\nimport constants as con\r\nfrom input import *\r\nfrom objects import *\r\nfrom stage import *\r\n\r\nclass App:\r\n \"\"\"\r\n A class to cleanly encapsulate main game loop phases,\r\n including initialization, event handling, and state \r\n updates\r\n \"\"\"\r\n def __init__(self):\r\n \"\"\"\r\n Get a reference to the display surface; set up required attributes;\r\n and instantiate player and stage objects\r\n \"\"\"\r\n self.screen = pyg.display.get_surface()\r\n self.screen_rect = self.screen.get_rect()\r\n self.clock = pyg.time.Clock()\r\n self.fps = con.TARGET_FPS\r\n\r\n # Boolean members\r\n self.done = False\r\n \r\n # Key state variable\r\n self.keys = pyg.key.get_pressed()\r\n \t\r\n # Initialize stage(s)\r\n self.stage_list = []\r\n self.stage_index = 0\r\n #self.test_stage = PlayStage(TESTSTAGE, self.player)\r\n self.test_stage = PlayStage(TESTSTAGE)\r\n self.stage_list.append(self.test_stage)\r\n self.current_stage = self.stage_list[self.stage_index]\r\n\r\n # Instantiate test objects and refer them to whatever\r\n # stage needs to be \"on point\"\r\n self.ball = Ball(self.current_stage)\r\n self.ball2 = Ball(self.current_stage, 300, 70)\r\n self.current_stage.objects.append(self.ball)\r\n self.current_stage.objects.append(self.ball2)\r\n\r\n def event_loop(self):\r\n \"\"\"\r\n Method encompassing one trip through the event queue\r\n Called within main_loop()\r\n \"\"\"\r\n for event in pyg.event.get():\r\n # Poll for quit event\r\n if event.type == pyg.QUIT:\r\n self.done = True\r\n elif event.type in (pyg.KEYUP, pyg.KEYDOWN):\r\n # Update key state\r\n self.keys = pyg.key.get_pressed()\r\n\r\n # Put a corresponding InputEvent onto\r\n # stage's input queue\r\n self.current_stage.input_queue.put(InputEvent(event.type, event.key))\r\n\r\n def render(self):\r\n \"\"\"\r\n Draws to the screen and updates the display\r\n \"\"\"\r\n\t\t\r\n # Draw level\r\n self.current_stage.draw(self.screen)\r\n\t\t\r\n # Draw game objects\r\n \r\n # Update display \r\n pyg.display.flip()\r\n\t\t\r\n def main_loop(self):\r\n \"\"\"\r\n Performs the main game loop\r\n \"\"\"\r\n while not self.done:\r\n self.event_loop()\r\n # Update game objects\r\n self.current_stage.update()\r\n self.render()\r\n self.clock.tick(self.fps)\r\n\t\t\t\r\ndef main():\r\n \"\"\"\r\n Main program function. Performs Pygame initialization,\r\n starts, and exits the program.\r\n \"\"\"\r\n pyg.init()\r\n pyg.display.set_caption(con.WINDOW_CAPTION)\r\n pyg.display.set_mode(con.SCREEN_SIZE)\r\n App().main_loop()\r\n pyg.quit()\r\n sys.exit()\r\n\t\r\nif __name__ == \"__main__\":\r\n main()\r\n","sub_path":"maingame.py","file_name":"maingame.py","file_ext":"py","file_size_in_byte":3195,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"585067242","text":"def cool_wrap(func):\r\n def wrapper(inlist):\r\n original = func(inlist)\r\n if not original:\r\n return('Нет')\r\n elif original > 10:\r\n return('Очень много')\r\n else:\r\n return original\r\n return wrapper\r\n\r\n\r\n@cool_wrap\r\ndef f(lst):\r\n count = 0\r\n for num in lst:\r\n if num % 2 == 0:\r\n count += 1\r\n return count","sub_path":"laba1(2).py","file_name":"laba1(2).py","file_ext":"py","file_size_in_byte":406,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"300303990","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nimport sqlite3\nimport models\nfrom sqlalchemy import create_engine, Table, Column, Integer, String, MetaData, Text, Date, Boolean, select, delete, and_\n\nfrom observable import Observable\n\ndef document_from_row(row):\n return models.Document(\n id=row[0],\n title=row[1],\n workid=row[2],\n type=row[3],\n executors=row[4].split(\",\"),\n description=row[5],\n is_checked=row[6],\n is_executed=row[7],\n date_created=row[8],\n date_alarm=row[9])\n\n\nclass DB(Observable):\n\n engine = None\n documents = None\n metadata = None\n connection = None\n\n def __init__(self, filename=None):\n Observable.__init__(self)\n if filename is None:\n self.filename = \":memory:\"\n else:\n self.filename = filename\n self.opened = False\n\n def _select(self):\n return self.documents.select(\n self.documents.id,\n self.documents.title,\n self.documents.workid,\n self.documents.type,\n self.documents.executors,\n self.documents.description,\n self.documents.is_executed,\n self.documents.is_checked,\n self.documents.is_hidden,\n self.documents.date_created,\n self.documents.date_alarm)\n\n def open(self):\n if not self.opened and self.filename:\n self.engine = create_engine(\"sqlite:///\" + self.filename)\n self.metadata = MetaData()\n self.documents = Table(\"documents\", self.metadata,\n Column(\"id\", String, primary_key=True),\n Column(\"title\", String),\n Column(\"workid\", String),\n Column(\"type\", Integer),\n Column(\"executors\", Text),\n Column(\"description\", Text),\n Column(\"is_executed\", Boolean),\n Column(\"is_checked\", Boolean),\n Column(\"date_created\", Date),\n Column(\"date_alarm\", Date))\n self.metadata.create_all(self.engine)\n self.connection=self.engine.connect()\n self.opened = True\n\n def close(self):\n if self.opened:\n self.connection.close()\n self.opened = False\n\n def document_delete(self, id):\n self.__check_db()\n query = delete(self.documents, self.documents.c.id == id)\n self.connection.execute(query)\n\n def document_get(self, id):\n self.__check_db()\n query = select([self.documents]).where(self.documents.c.id == id)\n row = self.connection.execute(query).fetchone()\n if not row:\n raise KeyError\n return document_from_row(row)\n\n def documents_get(self, user_query=None):\n self.__check_db()\n conditions = []\n if user_query:\n for key, value in user_query.iteritems():\n if key == \"executors\":\n if value:\n conditions.append((getattr(self.documents.c, key).like(\"%\" + value + \"%\")))\n elif key == \"created_from\":\n if value:\n conditions.append((self.documents.c.date_created >= value))\n elif key == \"created_to\":\n if value:\n conditions.append((self.documents.c.date_created <= value))\n elif key == \"alarm_from\":\n if value:\n conditions.append((self.documents.c.date_alarm >= value))\n elif key == \"alarm_to\":\n if value:\n conditions.append((self.documents.c.date_alarm <= value))\n else:\n if value is not None and value != \"\":\n conditions.append((getattr(self.documents.c, key) == value))\n\n query = select([self.documents]).where(and_(*conditions)).order_by(self.documents.c.date_alarm)\n\n return [document_from_row(row) for row in self.connection.execute(query)]\n\n def document_save(self, document):\n self.__check_db()\n values = {\n \"title\": document.title,\n \"workid\": document.workid,\n \"type\": document.type,\n \"executors\": \",\".join(document.executors),\n \"description\": document.description,\n \"is_checked\": document.is_checked,\n \"is_executed\": document.is_executed,\n \"date_created\": document.date_created,\n \"date_alarm\": document.date_alarm }\n\n try:\n query = self.documents.insert().values(id=document.id, **values)\n self.connection.execute(query)\n except:\n query = self.documents.update().where(\n self.documents.c.id==document.id).values(**values)\n self.connection.execute(query)\n self.fire()\n\n def __check_db(self):\n if not self.opened:\n raise RuntimeError(\"DB is not opened yet\")\n","sub_path":"sqlitedb.py","file_name":"sqlitedb.py","file_ext":"py","file_size_in_byte":5132,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"266061042","text":"\nimport logging\nimport os\nimport sys\nimport socket\n\nfrom messaging.message import Message\nfrom messaging.queue.dqs import DQS\n\nlog = logging.getLogger('nagiosmq')\n\nPLUGIN_OUTPUT_LIMIT = 16384\n\nclass Event(object):\n def __init__(self, debug=False):\n self._event = dict()\n self._debug = debug\n\n def add(self, k):\n event_key = k[7:].lower()\n self._event[event_key] = os.environ[k]\n\n def apply_filter(self, f_mod=None):\n # apply filters\n if f_mod:\n try:\n f_mod.mq_filter(self._event)\n except Exception as e:\n if self._debug:\n log.exception(e)\n\n def init(self, attr=None):\n keys = os.environ.keys()\n # populate\n for k in keys:\n if attr and k in attr:\n self.add(k)\n if not attr and \"NAGIOS_\" in k:\n self.add(k)\n\n # empty event\n if not self._event:\n if self._debug:\n log.debug(\"Empty event detected\")\n sys.exit(2)\n elif self._debug:\n log.debug(\"Event (%s, %s): %s\" % (self._event['hostname'], self._event['servicedesc'],\n len(self._event.keys())))\n\n # sanity for long service output (long output has hard-coded limit of 8kB)\n if 'longserviceoutput' in self._event.keys() \\\n and len(self._event['longserviceoutput']) > PLUGIN_OUTPUT_LIMIT:\n self._event['longserviceoutput'] = self._event['longserviceoutput'][0:PLUGIN_OUTPUT_LIMIT-5]+' ...'\n\n # transformations\n if 'longserviceoutput' in self._event.keys():\n self._event['longserviceoutput'] = unicode(self._event['longserviceoutput'],\n 'utf8', errors='replace')\n if 'serviceserver' not in self._event.keys():\n self._event['serviceserver'] = socket.gethostname()\n\n def enqueue(self, dirq, s_mod, c_map=None):\n try:\n mq_header, mq_body = s_mod.serialize(self._event, c_map=c_map)\n except Exception as e:\n if self._debug:\n log.exception(e)\n sys.exit(2)\n msg = Message(body=mq_body, header=mq_header)\n msg.is_text = True\n try:\n mq = DQS(path=dirq)\n mq.add_message(msg)\n except Exception as e:\n if self._debug:\n log.exception(e)\n sys.exit(2)\n\n def dequeue(self, mq, entry, des_mod):\n msg = des_mod.deserialize(mq.get_message(entry).get_body(), debug=self._debug)\n self._event.update(msg)\n\n def pipe(self, cmd_mod, cmd_pipe):\n cmd_mod.cmd(self._event, cmd_pipe, self._debug)\n","sub_path":"nagiosmq/structures.py","file_name":"structures.py","file_ext":"py","file_size_in_byte":2739,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"594226483","text":"#!/usr/bin/env python\r\n\"\"\"\r\n+------------------------------------------------------------------------------+\r\n| This ETL process queries the Zendesk API which responds with a JSON file |\r\n| containing key values which describe various properties of created tickets, |\r\n| such as datetime, advisor, order number, sku, etc. |\r\n| |\r\n| This file is then transformed in preparation for loading into Redshift. |\r\n| |\r\n| The reason that there are two processes running is because there |\r\n| are two ways for creating forms on zendesk: either through a preset form, |\r\n| or through a custom one. This distinction is important to the business for |\r\n| various reasons so all tickets are from the onset bucketed as either form, |\r\n| or non-form. |\r\n+------------------------------------------------------------------------------+\r\n\"\"\"\r\nimport datetime\r\nimport json\r\nimport re\r\nimport time\r\nimport os\r\n\r\nimport boto3\r\nimport psycopg2\r\nfrom tqdm import tqdm\r\nfrom zenpy import Zenpy, ZenpyException\r\n\r\n\r\ndef find_dates(conn, query):\r\n cursor = conn.cursor()\r\n cursor.execute(query)\r\n\r\n row = cursor.fetchone()\r\n start_date = datetime.datetime.strptime(str(row[0]), '%Y-%m-%d %H:%M:%S')\r\n end_date = datetime.datetime.now()\r\n return start_date, end_date\r\n\r\n\r\n# Function to extract order numbers from ticket subject line.\r\ndef extract_order_number(string):\r\n try:\r\n found = re.search('(1000[0-9]{5})', string).group(1)\r\n except AttributeError:\r\n # Order number not found\r\n found = '0'\r\n return found\r\n\r\n\r\n# Function to get timestamp in appropriate format.\r\ndef extract_timestamp(string):\r\n try:\r\n match = re.search('([0-9-]{10})T([0-9:]{8})Z', string)\r\n found1 = match.group(1)\r\n found2 = match.group(2)\r\n found = found1 + ' ' + found2\r\n post_replace = found.replace('\", \"',' ').replace('\"','')\r\n except AttributeError:\r\n # No timestamp or invalid format\r\n post_replace = None\r\n return post_replace\r\n\r\n\r\n# Function to extract SKUs from ticket description and return as a comma seperated list.\r\ndef extract_skus(text):\r\n results = []\r\n for line in text.split('\\n'):\r\n for word in line.split(' '):\r\n match = re.match('([A-Z0-9]{8}-[n 0-9]{3})', word)\r\n if match:\r\n results.append(str(match.group(1)))\r\n return results\r\n\r\n\r\n# Utility function to delete duplicate rows by the end of the process.\r\ndef delete_duplicates(conn):\r\n command = \"\"\"\r\n DELETE zendesk.tickets\r\n WHERE LENGTH(ticket_form)=0 AND id IN\r\n (\r\n SELECT id\r\n FROM\r\n (\r\n SELECT id, COUNT(*) AS count_\r\n FROM zendesk.tickets\r\n GROUP BY 1\r\n )\r\n WHERE count_ = 2\r\n );\r\n \"\"\"\r\n try:\r\n cursor = conn.cursor()\r\n cursor.execute(command)\r\n rows_deleted = cursor.rowcount\r\n return rows_deleted\r\n except Exception as e:\r\n print (e)\r\n\r\n\r\ndef make_document(ticket, form=None):\r\n return {\r\n 'id': str(ticket.id),\r\n 'ticket_form': str(form) if form else '',\r\n 'subject': str(ticket.subject),\r\n 'skus': extract_skus(ticket.description),\r\n 'order_id': extract_order_number(str(ticket.subject)),\r\n 'status': str(ticket.status),\r\n 'type': str(ticket.type),\r\n 'description': str(ticket.description),\r\n 'created_at': extract_timestamp(str(ticket.created_at)),\r\n 'brand_id': str(ticket.brand_id),\r\n 'group_id': str(ticket.group_id),\r\n 'assignee_id': str(ticket.assignee_id),\r\n 'assignee': str(ticket.assignee),\r\n 'submitter': str(ticket.submitter),\r\n 'recipient': str(ticket.recipient),\r\n 'raw_subject': str(ticket.raw_subject),\r\n 'tags': str(ticket.tags),\r\n 'is_public': str(ticket.is_public),\r\n 'satisfaction_rating': str(ticket._satisfaction_rating),\r\n 'allow_channelback': str(ticket.allow_channelback),\r\n 'etl_tstamp': str(datetime.datetime.now()),\r\n }\r\n\r\n\r\ndef extract_tickets(zenpy, start_date, end_date, filename, form=None):\r\n # Query tickets from Zendesk api and write results to file\r\n with open(filename, 'w') as out_file:\r\n try:\r\n for ticket in zenpy.search(\r\n created_between=[start_date, end_date],\r\n type='ticket',\r\n form=form):\r\n ticket_json = json.dumps(make_document(ticket, form=form))\r\n out_file.write(str(ticket_json))\r\n except ZenpyException as error:\r\n sys.exit(1)\r\n\r\n\r\ndef stage_and_load_tickets(conn, s3, filename):\r\n s3.upload_file(filename, 'json-repository', filename)\r\n\r\n command = \"\"\"\r\n COPY zendesk.tickets\r\n FROM 's3://json-repository/{}'\r\n CREDENTIALS 'aws_access_key_id=aws_access_key_id;aws_secret_access_key=aws_secret_access_key'\r\n JSON 's3://json-repository/zendesk_data_json_paths.json'\r\n ACCEPTINVCHARS;\r\n \"\"\".format(filename)\r\n try:\r\n cursor = conn.cursor()\r\n cursor.execute(command)\r\n except Exception as e:\r\n print (e)\r\n\r\n\r\ndef etl():\r\n s3 = boto3.client(\r\n 's3',\r\n aws_access_key_id=os.getenv(\"AWS_ACCESS_KEY_ID\"),\r\n aws_secret_access_key=os.getenv(\"AWS_SECRET_ACCESS_KEY\"),\r\n region_name=os.getenv(\"AWS_DEFAULT_REGION\"),\r\n )\r\n zenpy = Zenpy(\r\n email=os.getenv(\"ZENDESK_EMAIL\"),\r\n token=os.getenv(\"ZENDESK_TOKEN\"),\r\n subdomain=os.getenv(\"OUR_SUBDOMAIN\"),\r\n )\r\n dsn_string = os.getenv(\"REDSHIFT_CONN_STRING\")\r\n \r\n # Process nonform tickets\r\n conn = psycopg2.connect(dsn_string)\r\n conn.set_session(autocommit=True)\r\n nonform_query = \"SELECT MAX(created_at) FROM zendesk.tickets WHERE LENGTH(ticket_form)=0\"\r\n start_date, end_date = find_dates(conn, query=nonform_query)\r\n\r\n filename = time.strftime(\"%d_%m_%Y\") + '_zendesk_tickets.json'\r\n extract_tickets(zenpy, start_date, end_date, filename)\r\n stage_and_load_tickets(conn, s3, filename)\r\n\r\n delete_duplicates(conn)\r\n conn.close()\r\n\r\n # Process form tickets\r\n form_dsn = \"host='hostname' dbname='public' user='user' password='XXX' port='5439'\"\r\n conn = psycopg2.connect(dsn_string)\r\n conn.set_session(autocommit=True)\r\n form_query = \"SELECT MAX(created_at) FROM zendesk.tickets WHERE LENGTH(ticket_form)>0\"\r\n start_date, end_date = find_dates(conn, query=form_query)\r\n\r\n ticket_forms = [\r\n 'Pre sale product enquiry',\r\n 'Pre sale delivery enquiry',\r\n 'Pre sale invoice enquiry',\r\n 'Pre sale service enquiry',\r\n 'Pre despatch order enquiry',\r\n 'Post despatch delivery enquiry',\r\n 'Post despatch returns enquiry',\r\n 'Post despatch item damaged',\r\n 'Technical enquiry',\r\n 'Post despatch general enquiry',\r\n ]\r\n\r\n for form in tqdm(ticket_forms, leave=True):\r\n filename = time.strftime(\"%d_%m_%Y\") + '_zendesk_tickets_' + str(form) + '.json'\r\n extract_tickets(zenpy, start_date, end_date, filename, form=form)\r\n stage_and_load_tickets(conn, s3, filename)\r\n\r\n delete_duplicates(conn)\r\n conn.close()\r\n\r\n\r\nif __name__ == \"__main__\":\r\n etl()\r\n","sub_path":"zendesk_to_redshift.py","file_name":"zendesk_to_redshift.py","file_ext":"py","file_size_in_byte":7512,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"583065862","text":"\n\n'''\ndef near_reward(person):\n x = person.get('x')\n y = person.get('y')\n for reward in rewards:\n distance = m.sqrt((x - reward.x) ** 2 + (person.y - reward.y))\n dx = person.get('dx')\n dy = person.get('dy')\n n = person.get('rewards')\n n = n[0]\n person['dx'] = dx - (n % 2)* (n / 6) * dx\n person['dy'] = dy - ((n + 1) % 2)* (n / 6)* dy\n return person\n'''\n#Printing info read from user\ndef info_print(universe_list, people_list):\n print('All universes')\n print('-' * 40)\n for uni in universe_list:\n print(uni)\n print('All individuals')\n print('-'* 40)\n for person in people_list:\n print(person, end='')\n \ndef new_portal(person):\n pass\ndef collision_check(person, people_list):\n pass\n\ndef move(person):\n #if person.get('dx') person.get('dy') < 10: \n pass\n \n\nif __name__ == \"__main__\":\n user_file = input('Input file => ')\n print(user_file)\n #Assigning needed variables \n universes = []\n rewards = []\n portals = []\n individuals_list = []\n data = json.loads(open(user_file).read())\n #data is a dict, each item contains universe and individuals info\n for key in data:\n temp_person_list = []\n universe_name = ''\n universe_name = key.get('universe_name')\n rewards = key.get('rewards')\n portals = key.get('portals')\n\n #Creating a Universe object and appending it to a list \n current_uni = Universe(universe_name, rewards, portals)\n universes.append(current_uni)\n\n #this loop creates a Person object and appends it to a list\n temp_person_list = key.get('individuals')\n for person in temp_person_list:\n new_person = Person(person[0], person[1],\\\n universe_name, person[2],\\\n person[3], person[4],\\\n person[5], universe_name, [])\n individuals_list.append(new_person)\n \n #Printing out universe and individual info from given file \n print(info_print(universes, individuals_list))\n person.near_reward(step, rewards)\n person.check_speed(step)\n person.check_edges(step)\n person.check_crash(individuals_list, rewards, step)\n person.check_speed(step)\n person.move()\n person.check_speed(step)\n person.check_edges(step)\n person.check_crash(individuals_list, rewards, step)\n person.check_speed(step)\n \n person.move()\n person.check_edges(step)\n person.near_reward(step, rewards)\n person.check_speed(step)\n person.check_crash(individuals_list, rewards, step)\n person.check_speed(step) \n \n \n for person in individuals_list:\n person.check_edges(0)\n person.check_speed(0)\n if person.stop == True:\n stop.add(person) ","sub_path":"Homework/hw8/hw81.py","file_name":"hw81.py","file_ext":"py","file_size_in_byte":2789,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"241174092","text":"\n\nimport simplejson as json\n\nlist01= ['foo', {'bar': ('阿四', None, 1.0, 2)}]\nprint(list01)\nstr01=json.dumps(list01)\nprint(str01,type(str01))\n\nlist02 = json.loads(str01)\nprint(list02)\n\nfrom simplejson.compat import StringIO\nio = StringIO()\njson.dump(list02, io)\n\nprint(io.getvalue(),type(io))\n\n","sub_path":"ex03/json/J002_simplejson.py","file_name":"J002_simplejson.py","file_ext":"py","file_size_in_byte":296,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"244857304","text":"import os\nimport MaxwellConstruction as mx\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport argparse\n\n\ndef run_pr_case( a_eos, b_eos, w_eos, sigma, beta, TrList ):\n \n \"\"\"\n Ejecucion de casos de construccion de Maxwell\n \"\"\" \n\n \n # Directorio del caso y limpieza\n\n main_dir = os.getcwd()\n\n cases_dir = main_dir + '/a_{:.4f}_b_{:.4f}_w_{:.4f}_sigma_{:.4f}_beta_{:.4f}/'.format(a_eos, b_eos, w_eos, sigma, beta)\n\n os.system('rm -rf ' + cases_dir )\n\n os.system('mkdir -p ' + cases_dir )\n\n\n\n # Ecuacion de estado\n\n prob = mx.EOS('Peng-Robinson',a=a_eos,b=b_eos,w=w_eos)\n\n\n\n # Ejecucion para cada T reducida\n \n for Tr in TrList:\n\n \n\n # Directorio de ejecucion\n\n os.chdir( cases_dir ) \n \n case_name = 'Tr_{:.3f}'.format(Tr)\n\n os.system('cp -r ../Base ' + case_name )\n\n os.chdir( cases_dir + '/' + case_name)\n\n\n\n # Propiedades de coexistencia\n\n step = 0.999\n if Tr < 0.6:\n step = 0.9999\n \n \n if Tr >= 0.8:\n Vrmin,Vrmax = mx.coexistencia(prob, Tr, plotPV=False, Vspace=(0.3,50,10000), step_size=step)\n\n else:\n Vrmin,Vrmax = mx.coexistencia(prob, Tr, plotPV=False, Vspace=(0.28,4000,200000), step_size=step) \n\n \n \n # Reemplazo de propiedades\n \n os.system('sed -i \\'s/sigmaReplace/{:.5g}/g\\' Allrun'.format(args.sigma))\n\n os.system('sed -i \\'s/beta_pr_replace/{:.5g}/g\\' properties/macroProperties'.format(args.beta))\n \n os.system('sed -i \\'s/a_pr_replace/{:.5g}/g\\' properties/macroProperties'.format(args.a))\n\n os.system('sed -i \\'s/b_pr_replace/{:.5g}/g\\' properties/macroProperties'.format(args.b))\n\n os.system('sed -i \\'s/w_pr_replace/{:.5g}/g\\' properties/macroProperties'.format(args.w))\n\n os.system('sed -i \\'s/T_pr_replace/{:.7g}/g\\' start/initialFields'.format(Tr*prob.Tc()))\n\n os.system('sed -i \\'s/rhomin_pr_replace/{:.7g}/g\\' start/initialFields'.format(prob.rhoc()/Vrmax))\n\n os.system('sed -i \\'s/rhomax_pr_replace/{:.7g}/g\\' start/initialFields'.format(prob.rhoc()/Vrmin)) \n\n\n \n # Ejecucion\n\n print('Tr = {}'.format(Tr))\n\n os.system('./Allclean > log.Allclean')\n\n os.system('./Allpre > log.Allpre')\n\n os.system('./Allrun > log.lbm')\n\n \n \n os.chdir(main_dir) \n\n pass\n\n\n\n\n\n\n\nif __name__ == \"__main__\":\n\n\n\n # Argumentos de consola\n \n parser = argparse.ArgumentParser(description='Resolución del problema de construcción de Maxwell para diferentes constantes')\n\n parser.add_argument('-a', help='Constante a de PR', type=float, default = 1./50.)\n\n parser.add_argument('-b', help='Constante b de PR', type=float, default = 2./21.)\n\n parser.add_argument('-w', help='Constante w de PR', type=float, default = 0.5)\n\n parser.add_argument('-beta', help='Constante beta de fuerza de interaccion mixta', type=float, default = 1.25) \n\n parser.add_argument('-sigma', help='Constante sigma', type=float, default = 0.125) \n\n args = parser.parse_args()\n\n\n # Ejecucion de casos\n\n Tr = [0.95, 0.90, 0.85, 0.80, 0.75, 0.70, 0.65]\n\n run_pr_case( args.a, args.b, args.w, args.sigma, args.beta, Tr )\n\n\n\n \n","sub_path":"Imagenes/FC72/Fint/Coexistencia/runMaxwell.py","file_name":"runMaxwell.py","file_ext":"py","file_size_in_byte":3291,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"45309855","text":"import random\n\nclass Dealer():\n\n def __init__(self):\n '''\n The class constructor.\n\n Args:\n self (Dealer): an instance of Dealer\n '''\n\n self.deck = [1,2,3,4,5,6,7,8,9,10,11,12,13]\n\n def dealer_card(self):\n '''\n Draws a two random cards\n '''\n deck = self.deck.copy()\n deck_size = len(deck)\n\n rand_card = random.randint(0,deck_size - 1)\n first_card = deck.pop(rand_card)\n \n deck_size = len(deck)\n rand_card = random.randint(0,deck_size - 1)\n second_card = deck.pop(rand_card)\n\n deck.clear()\n\n return first_card, second_card","sub_path":"hilo/game/dealer.py","file_name":"dealer.py","file_ext":"py","file_size_in_byte":663,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"316528420","text":"\"\"\" Parses orca output files and writes extended xyz files for later use\n\"\"\"\n\nimport numpy as np\nimport glob\nfrom parse_molpro import read_write_xyz\n\ndef orca_parser(filename):\n \"\"\" Parses energies from orca output files\n \"\"\"\n with open(filename) as f:\n lines = f.readlines()\n\n if not \"ORCA TERMINATED NORMALLY\" in lines[-2]:\n print(f\"error reading {filename}\")\n return 0\n\n for line in lines[::-1]:\n if line.startswith(\"FINAL SINGLE POINT ENERGY\"):\n return float(line.split()[4])\n\n # should never get here\n raise SystemExit\n\ndef parse_and_write(log_datadir, output_datadir, xyz_datadir):\n \"\"\" Parse orca output files from `log_datadir` and\n writes extended xyz to `output_datadir` using the\n standard xyz-files from `xyz_datadir`\n \"\"\"\n orca_output_files = glob.glob(log_datadir + \"/*.log\")\n for log_filename in orca_output_files:\n energy = orca_parser(log_filename)\n log_basename = log_filename.split(\"/\")[-1].split(\".\")[0]\n xyz_filename = xyz_datadir + f\"/{log_basename}.xyz\"\n exyz_filename = output_datadir + f\"/{log_basename}.xyz\"\n read_write_xyz(xyz_filename, exyz_filename, energy)\n\nif __name__ == \"__main__\":\n parse_and_write(\"./batch_hybrid\", \"./exyz_hybrid\", \"./xyz\")\n\n","sub_path":"parse_orca.py","file_name":"parse_orca.py","file_ext":"py","file_size_in_byte":1302,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"261162275","text":"__author__ = 'Qianyun'\n\nimport argparse\nimport pickle\n\nparser = argparse.ArgumentParser(\n description='''make mutation search index table for covered region files'''\n)\nparser.add_argument('file_list',\n help='''File with path to each covered region files ''',\n type=argparse.FileType('r'))\nparser.add_argument('mutation_file',\n help='''sorted mutation file''',\n type=argparse.FileType('r'))\nparser.add_argument('index_file',\n help='''file to store index''',\n type=argparse.FileType('w'))\nargs = parser.parse_args()\n\nargs.mutation_file.readline()\nr = args.mutation_file.readline().split()\nmut_chr = \"chr\" + r[2]\nmut_pos = int(r[3])\n\nmutation_index = {}\n\nfor line in args.file_list:\n f = open(line.strip(), 'r')\n t = f.readline().split()\n region_name = f.name\n f.close()\n\n chr = t[0]\n pos = int(t[1])\n while (mut_chr < chr) or (mut_chr == chr and mut_pos < pos):\n r = args.mutation_file.readline().split()\n mut_chr = \"chr\" + r[2]\n mut_pos = int(r[3])\n args.mutation_file.seek(-2, 1)\n p = args.mutation_file.read(1)\n while p != '\\n':\n args.mutation_file.seek(-2, 1)\n p = args.mutation_file.read(1)\n mutation_index[region_name[-6:]] = args.mutation_file.tell()\n\npickle.dump(mutation_index, args.index_file)","sub_path":"src/mutation_hash.py","file_name":"mutation_hash.py","file_ext":"py","file_size_in_byte":1386,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"651747512","text":"import dash\nimport dash_core_components as dcc\nimport dash_html_components as html\nfrom dash.dependencies import Input, Output\nimport altair as alt\nimport pandas as pd\nimport geopandas as gpd\nimport json\nalt.data_transformers.disable_max_rows()\n# alt.data_transformers.enable('json')\n#alt.data_transformers.enable('data_server')\n\n# load geo_json file\ngeo_json_file_loc= '../Data/local-area-boundary.geojson'\n\ndef open_geojson():\n with open(geo_json_file_loc) as json_data:\n d = json.load(json_data)\n return d\n\ndef get_gpd_df():\n vancouver_json = open_geojson()\n gdf = gpd.GeoDataFrame.from_features((vancouver_json))\n return gdf\n\ngdf = get_gpd_df()\n# load crime data\ndf = pd.read_csv(\"../Data/crimedata_csv_all_years.csv\", encoding = 'latin-1', )\ndf = df[[\"NEIGHBOURHOOD\", \"TYPE\", 'YEAR','MONTH','HOUR']]\ndf['NEIGHBOURHOOD'] = df['NEIGHBOURHOOD'].str.replace(\"Musqueam\", \"Marpole\",regex = True)\ndf['NEIGHBOURHOOD'] = df['NEIGHBOURHOOD'].str.replace(\"Stanley Park\", \"West End\",regex = True)\ndf['TYPE'] = df['TYPE'].str.replace(\"Vehicle Collision or Pedestrian Struck (with Fatality)\", \"Vehicle Collision or Pedestrian Struck\",regex = True)\ndf['TYPE'] = df['TYPE'].str.replace(\"Vehicle Collision or Pedestrian Struck (with Injury)\", \"Vehicle Collision or Pedestrian Struck\",regex = True)\n\n\n## FUNCTIONS\ndef chart_filter(df, year = None, month = None, neighbourhood = None, crime = None):\n filtered_df = df\n if year != None:\n if type(year) == list:\n year_list = list(range(year[0], year[1]+1))\n filtered_df = filtered_df.query('YEAR == %s' % year_list)\n else:\n filtered_df = filtered_df.query('YEAR == %s' % year)\n if month != None:\n if type(month) == list:\n month_list = list(range(month[0], month[1]+1))\n filtered_df = filtered_df.query('MONTH == %s' % month_list)\n else:\n filtered_df = filtered_df.query('MONTH == %s' % month)\n if neighbourhood != None:\n if neighbourhood == []:\n neighbourhood = None\n elif type(neighbourhood) == list:\n filtered_df = filtered_df.query('DISTRICT == %s' % neighbourhood)\n else:\n filtered_df = filtered_df.query('DISTRICT == \"%s\"' % neighbourhood)\n if crime != None:\n if crime == []:\n crime = None\n elif type(crime) == list:\n filtered_df = filtered_df.query('OFFENSE_CODE_GROUP == %s' % crime)\n else:\n filtered_df = filtered_df.query('OFFENSE_CODE_GROUP == \"%s\"' % crime) \n return filtered_df\n\n# determine whether the input year is single value or not\ndef year_filter(year = None):\n if year[0] == year[1]:\n single_year = True\n else:\n single_year = False\n return single_year\n\n# use the filtered dataframe to create the map\n# create the geo pandas merged dataframe\ndef create_merged_gdf(df, gdf, neighbourhood):\n df = df.groupby(by = 'NEIGHBOURHOOD').agg(\"count\")\n if neighbourhood != None:\n neighbourhood = list(neighbourhood)\n for index_label, row_series in df.iterrows():\n # For each row update the 'Bonus' value to it's double\n if index_label not in neighbourhood:\n df.at[index_label , 'YEAR'] = None\n gdf = gdf.merge(df, left_on='name', right_on='NEIGHBOURHOOD', how='inner')\n return gdf\n\ndef create_geo_data(gdf):\n choro_json = json.loads(gdf.to_json())\n choro_data = alt.Data(values = choro_json['features'])\n return choro_data\n\n# mapping function based on all of the above\ndef gen_map(geodata, color_column, title, tooltip):\n '''\n Generates Boston neighbourhoods map with building count choropleth\n '''\n # Add Base Layer\n base = alt.Chart(geodata, title = title).mark_geoshape(\n stroke='black',\n strokeWidth=1\n ).encode(\n ).properties(\n width=300,\n height=300\n )\n # Add Choropleth Layer\n choro = alt.Chart(geodata).mark_geoshape(\n fill='lightgray',\n stroke='black'\n ).encode(\n alt.Color(color_column, \n type='quantitative', \n scale=alt.Scale(),\n title = \"Crime Counts\"),\n tooltip=tooltip\n )\n return base + choro\n\n# create plot functions\n\ndef vancouver_map(df):\n vancouver_map = gen_map(geodata = df, \n color_column='properties.YEAR', \n # color_scheme='yelloworangered',\n title = \"Crime Counts by Neighbourhood\",\n tooltip = [alt.Tooltip('properties.Name:O', title = 'Neighbourhood'),\n alt.Tooltip('properties.YEAR:Q', title = 'Crime Count')]\n ).configure_legend(labelFontSize=14, titleFontSize=16)\n return vancouver_map\n\n# set theme\ndef mds_special():\n font = \"Arial\"\n axisColor = \"#000000\"\n gridColor = \"#DEDDDD\"\n return {\n \"config\": {\n \"title\": {\n \"fontSize\": 24,\n \"font\": font,\n \"anchor\": \"start\", # equivalent of left-aligned.\n \"fontColor\": \"#000000\"\n },\n 'view': {\n \"height\": 300, \n \"width\": 400\n },\n \"axisX\": {\n \"domain\": True,\n #\"domainColor\": axisColor,\n \"gridColor\": gridColor,\n \"domainWidth\": 1,\n \"grid\": False,\n \"labelFont\": font,\n \"labelFontSize\": 12,\n \"labelAngle\": 0, \n \"tickColor\": axisColor,\n \"tickSize\": 5, # default, including it just to show you can change it\n \"titleFont\": font,\n \"titleFontSize\": 16,\n \"titlePadding\": 10, # guessing, not specified in styleguide\n \"title\": \"X Axis Title (units)\", \n },\n \"axisY\": {\n \"domain\": False,\n \"grid\": True,\n \"gridColor\": gridColor,\n \"gridWidth\": 1,\n \"labelFont\": font,\n \"labelFontSize\": 14,\n \"labelAngle\": 0, \n #\"ticks\": False, # even if you don't have a \"domain\" you need to turn these off.\n \"titleFont\": font,\n \"titleFontSize\": 16,\n \"titlePadding\": 10, # guessing, not specified in styleguide\n \"title\": \"Y Axis Title (units)\", \n # titles are by default vertical left of axis so we need to hack this \n #\"titleAngle\": 0, # horizontal\n #\"titleY\": -10, # move it up\n #\"titleX\": 18, # move it to the right so it aligns with the labels \n },\n }\n }\n\n# register the custom theme under a chosen name\nalt.themes.register('mds_special', mds_special)\n\n# enable the newly registered theme\nalt.themes.enable('mds_special')\n\n## wrap all the other functions\ndef make_choro_plot(df, gdf, year = None, month = None, neighbourhood = None, crime = None):\n df = chart_filter(df, year = year, month = month, crime = crime)\n gdf = create_merged_gdf(df, gdf, neighbourhood = neighbourhood)\n choro_data = create_geo_data(gdf)\n return vancouver_map(choro_data)\n\nexternal_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']\napp = dash.Dash(__name__, external_stylesheets=external_stylesheets)\nserver = app.server\n\napp.title = 'Vancouver Crime Dashboard'\n\n# colour dictionary\ncolors = {\"white\": \"#ffffff\",\n \"light_grey\": \"#d2d7df\",\n \"ubc_blue\": \"#082145\"\n }\n\napp.layout = html.Div(style={'backgroundColor': colors['light_grey']}, children = [\n\n # HEADER\n html.Div(className = 'row', style = {'backgroundColor': colors[\"ubc_blue\"], \"padding\" : 10}, children = [\n html.H2('Vancouver Crime Dashboard', style={'color' : colors[\"white\"]})\n ]),\n \n # BODY\n html.Div(className = \"row\", children = [\n\n #SIDE BAR\n html.Div(className = \"two columns\", style = {'padding': 20}, children= [\n html.P(\"Filter by Year\"),\n dcc.RangeSlider(\n id = 'year-slider',\n min=2015,\n max=2018,\n step=1,\n marks={\n 2015: '2015',\n 2016: '2016',\n 2017: '2017',\n 2018: '2018'\n },\n value=[2015,2018],\n ),\n html.Br(),\n html.P(\"Filter by Month\"),\n dcc.RangeSlider(\n id = 'month-slider',\n min=1,\n max=12,\n step=1,\n marks={\n 1: 'Jan',\n 2: '',\n 3: '',\n 4: '',\n 5: '',\n 6: 'June',\n 7: '',\n 8: '',\n 9: '',\n 10: '',\n 11: '',\n 12: 'Dec'\n },\n value=[1,12],\n ),\n\n \n\n html.Br(),\n html.P(\"Filter by Neighbourhood\"),\n dcc.Dropdown(\n id = 'neighbourhood-dropdown',\n options=[\n {'label': 'Oakridge', 'value': 'Oakridge'},\n {'label': 'Fairview', 'value': 'Fairview'},\n {'label': 'West End', 'value': 'West End'},\n {'label': 'Central Business District', 'value': 'Central Business District'},\n {'label': 'Hastings-Sunrise', 'value': 'Hastings-Sunrise'},\n {'label': 'Strathcona', 'value': 'Strathcona'},\n {'label': 'Grandview-Woodland', 'value': 'Grandview-Woodland'},\n {'label': 'Kitsilano', 'value': 'Kitsilano'}, \n {'label': 'Kensington-Cedar Cottage', 'value': 'Kensington-Cedar Cottage'}, \n {'label': 'Sunset', 'value': 'Sunset'}, \n {'label': 'Mount Pleasant', 'value': 'Mount Pleasant'} ,\n {'label': 'Shaughnessy', 'value': 'Shaughnessy'},\n {'label': 'Marpole', 'value': 'Marpole'}, \n {'label': 'West Point Grey', 'value': 'West Point Grey'}, \n {'label': 'Victoria-Fraserview', 'value': 'Victoria-Fraserview'}, \n {'label': 'Riley Park', 'value': 'Riley Park'},\n {'label': 'Arbutus Ridge', 'value': 'Arbutus Ridge'},\n {'label': 'Renfrew-Collingwood', 'value': 'Renfrew-Collingwood'},\n {'label': 'Killarney', 'value': 'Killarney'},\n {'label': 'Dunbar-Southlands', 'value': 'Dunbar-Southlands'},\n {'label': 'South Cambie', 'value': 'South Cambie'}\n\n\n\n ],\n value=None, style=dict(width='100%'),\n multi=True \n ),\n\n html.Br(),\n html.P(\"Filter by Crime\"),\n dcc.Dropdown(\n id = 'crime-dropdown',\n options=[\n {'label': 'Break and Enter Commercial', 'value': 'Break and Enter Commercial'} ,\n {'label': 'Break and Enter Residential/Other', 'value': 'Break and Enter Residential/Other'} ,\n {'label': 'Homicide', 'value': 'Homicide'} ,\n {'label': 'Mischief', 'value': 'Mischief'} ,\n {'label': 'Offence Against a Person', 'value': 'Offence Against a Person'} ,\n {'label': 'Other Theft', 'value': 'Other Theft'} ,\n {'label': 'Theft from Vehicle', 'value': 'Theft from Vehicle'} ,\n {'label': 'Theft of Bicycle', 'value': 'Theft of Bicycle'} ,\n {'label': 'Theft of Vehicle', 'value': 'Theft of Vehicle'} ,\n {'label': 'Vehicle Collision or Pedestrian Struck', 'value': 'Vehicle Collision or Pedestrian Struck'} \n ],\n value=None, style=dict(width='100%'),\n multi=True\n ),\n ]),\n # MAIN PLOTS\n html.Div(className = \"ten columns\", style = {\"backgroundColor\": colors['white'], \"padding\": 20}, children=[\n\n html.Iframe(\n sandbox='allow-scripts',\n id='choro-plot',\n height='800',\n width='800',\n style={'border-width': '0px'},\n )\n\n ])\n \n ])\n])\n\n@app.callback(\n dash.dependencies.Output('choro-plot', 'srcDoc'),\n [dash.dependencies.Input('year-slider', 'value'),\n dash.dependencies.Input('month-slider', 'value'),\n dash.dependencies.Input('neighbourhood-dropdown', 'value'),\n dash.dependencies.Input('crime-dropdown', 'value')])\n\ndef update_choro_plot(year_value, month_value, neighbourhood_value, crime_value):\n return make_choro_plot(df, gdf, year = year_value, month = month_value, neighbourhood = neighbourhood_value, crime = crime_value).to_html()\n\nif __name__ == '__main__':\n app.run_server(debug=True)","sub_path":"app/map_plot.py","file_name":"map_plot.py","file_ext":"py","file_size_in_byte":13656,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"627259435","text":"\"\"\"File that deals with everything about importing and sampling.\"\"\"\nimport os\nfrom functools import lru_cache\nfrom os.path import join\nimport numpy as np\nimport pandas as pd\nimport numpy as np\nfrom scipy.io import mmread\nfrom scipy.sparse import coo_matrix\nfrom zipfile import ZipFile\n\npath_here = os.path.dirname(os.path.dirname(__file__))\n\n\n@lru_cache(maxsize=None)\ndef import_pstat(combine_samples=True):\n \"\"\" Loads CSV file containing pSTAT5 levels from Visterra data. Incorporates only Replicate 1 since data missing in Replicate 2. \"\"\"\n path = os.path.dirname(os.path.dirname(__file__))\n data = np.array(pd.read_csv(join(path, \"ckine/data/pSTAT_data.csv\"), encoding=\"latin1\"))\n ckineConc = data[4, 2:14]\n tps = np.array([0.5, 1.0, 2.0, 4.0]) * 60.0\n # 4 time points, 10 cell types, 12 concentrations, 2 replicates\n IL2_data = np.zeros((40, 12))\n IL2_data2 = IL2_data.copy()\n IL15_data = IL2_data.copy()\n IL15_data2 = IL2_data.copy()\n cell_names = list()\n for i in range(10):\n cell_names.append(data[12 * i + 3, 1])\n # Subtract the zero treatment plates before assigning to returned arrays\n if i <= 4:\n zero_treatment = data[12 * (i + 1), 13]\n zero_treatment2 = data[8 + (12 * i), 30]\n else:\n zero_treatment = data[8 + (12 * i), 13]\n zero_treatment2 = data[8 + (12 * i), 30]\n # order of increasing time by cell type\n IL2_data[4 * i: 4 * (i + 1), :] = np.flip(data[6 + (12 * i): 10 + (12 * i), 2:14].astype(float) - zero_treatment, 0)\n IL2_data2[4 * i: 4 * (i + 1), :] = np.flip(data[6 + (12 * i): 10 + (12 * i), 19:31].astype(float) - zero_treatment2, 0)\n IL15_data[4 * i: 4 * (i + 1), :] = np.flip(data[10 + (12 * i): 14 + (12 * i), 2:14].astype(float) - zero_treatment, 0)\n IL15_data2[4 * i: 4 * (i + 1), :] = np.flip(data[10 + (12 * i): 14 + (12 * i), 19:31].astype(float) - zero_treatment2, 0)\n\n if combine_samples is False:\n return ckineConc, cell_names, IL2_data, IL2_data2, IL15_data, IL15_data2\n\n for i in range(IL2_data.shape[0]):\n for j in range(IL2_data.shape[1]):\n # take average of both replicates if specific entry isn't nan\n IL2_data[i, j] = np.nanmean(np.array([IL2_data[i, j], IL2_data2[i, j]]))\n IL15_data[i, j] = np.nanmean(np.array([IL15_data[i, j], IL15_data2[i, j]]))\n\n dataMean = pd.DataFrame(\n {\n \"Cells\": np.tile(np.repeat(cell_names, 48), 2),\n \"Ligand\": np.concatenate((np.tile(np.array(\"IL2\"), 480), np.tile(np.array(\"IL15\"), 480))),\n \"Time\": np.tile(np.repeat(tps, 12), 20),\n \"Concentration\": np.tile(ckineConc, 80),\n \"RFU\": np.concatenate((IL2_data.reshape(480), IL15_data.reshape(480))),\n }\n )\n\n return ckineConc, cell_names, IL2_data, IL15_data, dataMean\n\n\n# Receptor Quant - Beads (4/23 & 4/26)\n\n\nchannels = {}\nchannels[\"A\"] = [\"VL1-H\", \"BL5-H\", \"RL1-H\", \"RL1-H\", \"RL1-H\", \"Width\"]\nchannels[\"C\"] = [\"VL4-H\", \"VL6-H\", \"BL1-H\", \"BL3-H\"]\nchannels[\"D\"] = [\"VL1-H\", \"VL1-H\", \"VL1-H\", \"VL1-H\", \"VL1-H\"]\nchannels[\"E\"] = [\"VL6-H\", \"BL3-H\", \"BL5-H\", \"BL5-H\", \"BL5-H\", \"BL5-H\", \"BL5-H\"]\nchannels[\"F\"] = channels[\"G\"] = channels[\"H\"] = [\"RL1-H\", \"RL1-H\", \"RL1-H\", \"RL1-H\", \"RL1-H\"]\nchannels[\"I\"] = [\"BL1-H\", \"BL1-H\", \"BL1-H\", \"BL1-H\", \"BL1-H\"]\n\nreceptors = {}\nreceptors[\"A\"] = [\"CD25\", \"CD122\", \"CD132\", \"IL15(1)\", \"IL15(2)\", \" \"]\nreceptors[\"C\"] = [\"CD3\", \"CD4\", \"CD127\", \"CD45RA\"]\nreceptors[\"D\"] = [\"CD25\", \"CD25\", \"CD25\", \"CD25\", \"CD25\"]\nreceptors[\"E\"] = [\"CD8\", \"CD56\", \"CD122\", \"CD122\", \"CD122\", \"CD122\", \"CD122\"]\nreceptors[\"F\"] = [\"CD132\", \"CD132\", \"CD132\", \"CD132\", \"CD132\"]\nreceptors[\"G\"] = [\"IL15(1)\", \"IL15(1)\", \"IL15(1)\", \"IL15(1)\", \"IL15(1)\"]\nreceptors[\"H\"] = [\"IL15(2)\", \"IL15(2)\", \"IL15(2)\", \"IL15(2)\", \"IL15(2)\"]\nreceptors[\"I\"] = [\"CD127\", \"CD127\", \"CD127\", \"CD127\", \"CD127\"]\n\n\n@lru_cache(maxsize=None)\ndef import_pstat_all(singleCell=False, updateLigs=True):\n \"\"\" Loads CSV file containing all WT and Mutein pSTAT responses and moments\"\"\"\n WTbivDF = pd.read_csv(join(path_here, \"ckine/data/WTDimericMutSingleCellData.csv\"), encoding=\"latin1\")\n monDF = pd.read_csv(join(path_here, \"ckine/data/MonomericMutSingleCellData.csv\"), encoding=\"latin1\")\n respDF = pd.concat([WTbivDF, monDF])\n if singleCell:\n WTbivDFbin = pd.read_csv(join(path_here, \"ckine/data/WTDimericMutSingleCellDataBin.csv\"), encoding=\"latin1\")\n monDFbin = pd.read_csv(join(path_here, \"ckine/data/MonomericMutSingleCellDataBin.csv\"), encoding=\"latin1\")\n respDFbin = pd.concat([WTbivDFbin, monDFbin])\n respDFbin = respDFbin.loc[respDFbin[\"Bin\"].isin([1, 3])]\n respDFbin.loc[respDFbin[\"Bin\"] == 1, \"Cell\"] += r\" $IL2Ra^{lo}$\"\n respDFbin.loc[respDFbin[\"Bin\"] == 3, \"Cell\"] += r\" $IL2Ra^{hi}$\"\n respDF = pd.concat([respDF, respDFbin])\n\n if updateLigs:\n respDF.loc[(respDF.Bivalent == 0), \"Ligand\"] = (respDF.loc[(respDF.Bivalent == 0)].Ligand + \" (Mono)\").values\n respDF.loc[(respDF.Bivalent == 1), \"Ligand\"] = (respDF.loc[(respDF.Bivalent == 1)].Ligand + \" (Biv)\").values\n\n return respDF\n\n\n@lru_cache(maxsize=None)\ndef import_pstat_all_meyer():\n \"\"\" Loads CSV file containing all WT and Mutein pSTAT responses and moments\"\"\"\n respDF = pd.read_csv(join(path_here, \"ckine/data/Meyer_Flow.csv\"), encoding=\"latin1\")\n respDF = respDF.loc[(respDF.Date != \"7/22/22\") & (respDF.Date != \"3/17/23\")]\n return respDF\n\n\n@lru_cache(maxsize=None)\ndef getBindDict():\n \"\"\"Gets binding to pSTAT fluorescent conversion dictionary\"\"\"\n path = os.path.dirname(os.path.dirname(__file__))\n bindingDF = pd.read_csv(join(path, \"ckine/data/BindingConvDict.csv\"), encoding=\"latin1\")\n return bindingDF\n\n\n@lru_cache(maxsize=None)\ndef importReceptors():\n \"\"\"Makes Complete receptor expression Dict\"\"\"\n path = os.path.dirname(os.path.dirname(__file__))\n recDF = pd.read_csv(join(path_here, \"ckine/data/RecQuantitation.csv\"))\n recDFbin = pd.read_csv(join(path_here, \"ckine/data/BinnedReceptorData.csv\"))\n recDFbin = recDFbin.loc[recDFbin[\"Bin\"].isin([1, 3])]\n recDFbin.loc[recDFbin[\"Bin\"] == 1, \"Cell Type\"] += r\" $IL2Ra^{lo}$\"\n recDFbin.loc[recDFbin[\"Bin\"] == 3, \"Cell Type\"] += r\" $IL2Ra^{hi}$\"\n recDF = pd.concat([recDF, recDFbin])\n return recDF\n\n\ndef importCITE():\n \"\"\"Downloads all surface markers and cell types\"\"\"\n CITEmarkerDF = pd.read_csv(join(path_here, \"ckine/data/CITEdata_SurfMarkers.zip\"))\n return CITEmarkerDF\n\n\ndef makeRNAseqDF():\n \"\"\"Makes surface RNAseq DF\"\"\"\n matrix = mmread(join(path_here, \"ckine/data/GSM5008737_RNA_3P-matrix.mtx.gz\"))\n surfGenes = pd.read_csv(\"ckine/data/SurfaceGenes.csv\")\n featuresGenes = pd.read_csv(\"ckine/data/RNAfeatures.csv\")\n surfaceList = surfGenes[\"Gene\"].values\n allFeatures = featuresGenes[\"Gene\"].values\n surfInd = np.isin(allFeatures, surfaceList)\n cols = [i for i, x in enumerate(surfInd) if x]\n dataCoords = np.isin(matrix.row, cols)\n locList = np.where(surfInd == True)[0].tolist()\n newCoords = np.arange(0, len(locList)).tolist()\n\n colDict = {}\n for key in locList:\n for value in newCoords:\n colDict[key] = value\n newCoords.remove(value)\n break\n\n def vec_translate(a, my_dict):\n return np.vectorize(my_dict.__getitem__)(a)\n matrix2 = coo_matrix((matrix.data[dataCoords], (matrix.col[dataCoords], vec_translate(matrix.row[dataCoords], colDict))), shape=(matrix.shape[1], np.count_nonzero(surfInd)))\n geneCols = allFeatures[surfInd]\n GeneDF = pd.DataFrame(data=matrix2.toarray(), columns=geneCols)\n cellTypesDF = pd.read_csv(join(path_here, \"ckine/data/CITEcellTypes.csv\"))\n GeneDF = pd.concat([GeneDF, cellTypesDF], axis=1)\n GeneDF.to_csv(join(path_here, \"ckine/data/RNAseqSurface.csv.zip\"))\n\n\ndef importRNACITE():\n \"\"\"Downloads all surface markers and cell types\"\"\"\n RNAsurfDF = pd.read_csv(ZipFile(join(path_here, \"ckine/data/RNAseqSurface.csv.zip\")).open(\"RNAseqSurface.csv\"))\n return RNAsurfDF\n","sub_path":"ckine/imports.py","file_name":"imports.py","file_ext":"py","file_size_in_byte":8059,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"390291890","text":"import pytest\nimport json\nimport random\nfrom api_calls import API\n\nunicode_basic = \"!\\\"#$%&'()*+,-.0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\"\n\n\ndef character_template(name=None, value=\"\", pop_key=None):\n template = {\n \"education\": value,\n \"height\": value,\n \"identity\": value,\n \"name\": name,\n \"other_aliases\": value,\n \"universe\": value,\n \"weight\": value\n }\n if pop_key:\n template.pop(pop_key)\n return template\n\n\n@pytest.fixture(scope='session')\ndef api():\n a = API('http://rest.test.ivi.ru/', 'pashtet123@gmail.com', 'hgJH768Cv23')\n yield a\n a.reset_collection()\n\n\n@pytest.fixture(scope='class')\ndef character(api):\n r = api.insert_character(character_template(\"test_character\"))\n yield r\n api.delete_character(\"test_character\")\n\n\n@pytest.fixture(params=[('pashtet123@gmail.com', ''),\n ('pashtet123', 'hgJH768Cv23'),\n ('v', 'hgJH768Cv23'),\n ('', 'hgJH768Cv23'),\n ('', '1'),\n ('v', '1'),\n ('', '')])\ndef bad_auth_api(request):\n login, password = request.param\n return API('http://rest.test.ivi.ru/', login, password)\n\n\ndef test_wrong_auth(bad_auth_api):\n \"\"\"\n Некорректная попытка авторизации:\n запрашиваем characters с различными некорректными данными из фикстуры bad_auth_api\n \"\"\"\n r = bad_auth_api.get_all_characters()\n assert r.status_code == 401\n assert json.loads(r.text) == {\"error\": \"You have to login with proper credentials\"}\n\n\n@pytest.mark.dependency()\ndef test_get_characters(api, expected_length=1):\n \"\"\"\n Получение коллекции:\n запрашиваем characters с корректными username:password\n ожидаем код 200 и не пустой список персонажей\n api.characters и api.unique_names нужны для дальнейших тестов\n \"\"\"\n request = api.get_all_characters()\n characters = json.loads(request.text)[\"result\"]\n assert request.status_code == 200 and len(characters) >= expected_length\n api.characters = characters\n api.unique_names = set(x[\"name\"] for x in api.characters)\n\n\n@pytest.mark.dependency(depends=[\"test_get_characters\"])\nclass TestCollectionContent:\n\n def test_mangled_characters(self, api):\n \"\"\"\n Валидация коллекции:\n проверяем, что у каждого персонажа имеются все поля, указанные в документации\n \"\"\"\n expected_keys = sorted(character_template().keys())\n for character in api.characters:\n assert expected_keys == sorted(character.keys())\n\n def test_duplicate_characters(self, api):\n \"\"\"\n Валидация коллекции:\n проверяем отсутствие дубликатов в коллекции\n \"\"\"\n assert len(api.characters) == len(api.unique_names)\n\n\n@pytest.mark.dependency(depends=[\"test_get_characters\"])\ndef test_get_character(api):\n \"\"\"\n Получение одного персонажа:\n запрашиваем случайно выбранного персонажа из сохраненной коллекции\n получаем данные, совпадающие с имеющимися данными\n \"\"\"\n existing_character = random.choice(api.characters)\n character = api.get_character(existing_character[\"name\"])\n result = json.loads(character.text)[\"result\"][0]\n assert result == existing_character\n\n\n@pytest.mark.dependency(depends=[\"test_get_characters\"])\n@pytest.mark.parametrize('name', [x+\"name\" for x in unicode_basic])\ndef test_get_nonexistent_character(api, name):\n \"\"\"\n Получение несуществующего персонажа:\n запрашиваем персонажа, проверив, что его имени нет в списке имен персонажей в коллекции\n получаем данные, совпадающие с имеющимися данными\n \"\"\"\n assert name not in api.unique_names\n character = api.get_character(name)\n assert character.status_code == 200\n assert json.loads(character.text) == {\"result\": \"No such name\"}\n\n\n# TODO: find out if there are any constraints for character names\n# TODO: возможно не стоит проходить все символы из unicode_basic, если важно время выполнения теста (+~10 секунд)\n@pytest.mark.parametrize('value', [unicode_basic, 9999, 99.99, None, {'a': 'b'}, ['a', 'b']])\n@pytest.mark.parametrize('name', [9999, 99.99, \"test/name\"] + [x+\"name\" for x in unicode_basic])\ndef test_insert_character(api, name, value):\n \"\"\"\n Добавление нового песонажа:\n добавляем нового персонажа\n получаем его данные\n проверяем что полученные данные совпадают с отправленными\n удаляем персонажа\n \"\"\"\n insertion = api.insert_character(character_template(name, value))\n character = api.get_character(name)\n assert json.loads(insertion.text)[\"result\"] == json.loads(character.text)[\"result\"][0]\n api.delete_character(name)\n\n\ndef test_insert_duplicate_character(api, character):\n \"\"\"\n Добавление дубликата персонажа:\n добавляем персонажа с существующим в коллекции именем\n получаем ответ, что имя занято\n проверяем что персонаж действительно не добавился\n \"\"\"\n characters_before = api.get_all_characters()\n name = json.loads(character.text)[\"result\"][\"name\"]\n insertion = api.insert_character(character_template(name))\n assert \"{} is already exists\".format(name) in insertion.text\n characters_after = api.get_all_characters()\n assert len(json.loads(characters_before.text)[\"result\"]) == len(json.loads(characters_after.text)[\"result\"])\n\n\n@pytest.mark.parametrize('pop_key', character_template().keys())\ndef test_insert_broken_character(api, pop_key, name=\"failanyway\"):\n \"\"\"\n Добавление персонажа с некорректно составленными данными:\n последовательно пробуем отправить json без каждого поля\n каждый раз получаем ожидаемый ответ 400\n \"\"\"\n insertion = api.insert_character(character_template(name, pop_key))\n assert insertion.status_code == 400\n character = api.get_character(name)\n assert json.loads(character.text) == {\"result\": \"No such name\"}\n\n\nclass TestModifyCharacter:\n\n @pytest.mark.parametrize('value', [unicode_basic, 9999, 99.99, None, {'a': 'b'}, ['a', 'b']])\n @pytest.mark.parametrize('change_key', character_template(pop_key=\"name\").keys())\n def test_modify_character(self, api, character, change_key, value):\n \"\"\"\n Изменение данных персонажа:\n изменяем данные персонажа\n запрашиваем данные измененного песонажа\n убеждаемся, что полученные данные соответствуют измененным\n \"\"\"\n data = json.loads(character.text)[\"result\"]\n name = data[\"name\"]\n data[change_key] = value\n result = api.modify_character(name, data)\n assert result.status_code == 200\n result = api.get_character(name)\n assert json.loads(result.text)[\"result\"][0] == data\n\n @pytest.mark.parametrize('pop_key', character_template().keys())\n def test_invalid_modify_character(self, api, character, pop_key):\n \"\"\"\n Изменение данных персонажа на некорректные:\n последовательно пробуем отправить json без каждого поля\n каждый раз получаем ожидаемый ответ 400\n \"\"\"\n data = json.loads(character.text)[\"result\"]\n name = data[\"name\"]\n data.pop(pop_key)\n result = api.modify_character(name, data)\n assert result.status_code == 400\n\n\n@pytest.mark.dependency(depends=[\"test_get_characters\"])\ndef test_delete_existing_character(api, character):\n \"\"\"\n Удаление персонажа:\n удаляем персонажа\n получаем ожидаемый результат\n пробуем запросить удаленного персонажа\n получаем ответ, что его нет\n \"\"\"\n api.insert_character(character_template(\"test_character\"))\n result = api.delete_character(\"test_character\")\n character = api.get_character(\"test_character\")\n assert \"is deleted\" in result.text and \"No such name\" in character.text\n\n\ndef test_delete_nonexistent_character(api):\n \"\"\"\n Удаление несуществующего персонажа:\n удаляем персонажа\n получаем ожидаемый результат, что персонаж не найден\n \"\"\"\n name = \"i_do_not_exist\"\n delete_result = api.delete_character(name)\n assert \"No such name\" in delete_result.text\n\n\n@pytest.mark.dependency(depends=[\"test_delete_existing_character\"])\ndef test_collection_reset(api):\n \"\"\"\n Сброс коллекции:\n добавляем нового персонажа и берем из предыдущего теста имя удаленного персонажа\n отправляем запрос на сброс коллекции\n проверяем что добавленный персонаж теперь удален, а удаленный - восстановлен\n \"\"\"\n api.insert_character(character_template(\"to_be_deleted\"))\n api.reset_collection()\n deleted = api.get_character(api.deleted_character[\"name\"])\n added = api.get_character(\"to_be_deleted\")\n assert json.loads(deleted.text)[\"result\"][0] == api.deleted_character and \"No such name\" in added.text\n\n\n@pytest.mark.dependency(depends=[\"test_get_characters\"])\ndef test_collection_limit(api, db_limit=500):\n \"\"\"\n Добавление персонажа сверх лимита:\n вычисляем N - количество персонажей в коллекции\n успешно добавляем 500-N персонажей\n добавляем ещё одного\n получаем ответ, что коллекция заполнена\n пробуем запросить последнего добавленного персонажа на случай, если он все равно добавился\n \"\"\"\n characters_needed = db_limit - len(api.characters)\n for i in range(characters_needed):\n api.insert_character(character_template(\"dummy\" + str(i)))\n r = api.insert_character(character_template(\"failing\"))\n assert r.status_code == 400 and json.loads(r.text) == {\"error\": \"Collection can't contain more than 500 items\"}\n character = api.get_character(\"failing\")\n assert \"No such name\" in character.text\n","sub_path":"test_api.py","file_name":"test_api.py","file_ext":"py","file_size_in_byte":11464,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"157799944","text":"#!/usr/bin/env python3\n\n\nclass Tree:\n\n rootNode = None\n\n connectionQueue = []\n\n # True if a new queue list made by all of Root's child must be made.\n # Usually used only for the first few connections (5).\n connectingToRoot = True\n\n class Node:\n parentNode = None\n\n HostInstance = None\n\n firstChild = None\n secondChild = None\n thirdChild = None\n fourthChild = None\n fifthChild = None\n\n childCounter = 0 # From 0 to 5. 5 means the Node is full.\n siblingCounter = None # From 1 (first child) to 5 (last child)\n\n def __init__(self, parent, host, siblingCounter=1):\n self.parentNode = parent\n self.HostInstance = host\n self.siblingCounter = siblingCounter\n\n def getNode(self, value=-1):\n switcher = {\n -1: self.parentNode,\n 0: self,\n 1: self.firstChild,\n 2: self.secondChild,\n 3: self.thirdChild,\n 4: self.fourthChild,\n 5: self.fifthChild}\n return switcher[value]\n\n def getHost(self):\n return self.HostInstance\n\n def getChildCounter(self):\n return self.childCounter\n\n def increaseChildCounter(self, amount=1):\n self.childCounter += amount\n\n def __init__(self, host):\n self.startingNode = Node(None, host)\n self.rootNode = startingNode\n self.connectionQueue.append(self.startingNode)\n\n def addHost(self, host):\n currentNode = self.connectionQueue.pop()\n currentNodeNewChildCount = currentNode.getChildCounter() + 1\n newNode = Node(currentNode, newNode, currentNodeNewChildCount)\n currentNode.increaseChildCounter()\n if currentNodeNewChildCount < 5:\n self.connectionQueue.append(currentNode)\n else:\n if self.connectingToRoot:\n for i in range(1, 6):\n self.connectionQueue.append(currentNode.getNode(i))\n else:\n self.connectingToRoot = False\n # Be REALLY carefull: if the host disconnection is not good, this\n # will cause a lot of problems later, and won't work as intended.\n self.connectionQueue.append(currentNode.getNode(1))","sub_path":"Semester_project/ServerTree.py","file_name":"ServerTree.py","file_ext":"py","file_size_in_byte":2322,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"187391316","text":"import re\n\nf = open('mbox-short.txt','r')\nf = f.readlines()\n\nfor line in f:\n\tif re.search(\"From\", line):\n\t\tprint (line)\n\t\tnumbers= re.findall(\"[0-9]+\",line)\n\t\tprint (numbers)\n\t\tnames= re.findall(\"(\\S+)@\", line)[0]\n\t\tprint (names)","sub_path":"SI206-Fall2017-master/LAB4/lab4.py","file_name":"lab4.py","file_ext":"py","file_size_in_byte":229,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"549324020","text":"import sys\nfrom os import path\n\nfrom setuptools import setup\n\nHERE = path.abspath(path.dirname(__file__))\n\nwith open(path.join(HERE, \"pypbomb\", \"_version.py\")) as f:\n __version__ = \"\"\n exec(f.read())\n\nwith open(path.join(HERE, \"README.md\")) as f:\n readme = f.read()\n\nwith open(path.join(HERE, \"CHANGELOG.md\")) as f:\n changelog = f.read()\n\n\ndesc = readme + \"\\n\\n\" + changelog\ntry:\n import pypandoc\n\n long_description = pypandoc.convert_text(desc, \"rst\", format=\"md\")\n with open(path.join(HERE, \"README.rst\"), \"w\") as rst_readme:\n rst_readme.write(long_description)\nexcept (ImportError, OSError, IOError):\n long_description = desc\n\n\ndef requirements_from_txt(fname: str):\n txt_path = path.join(HERE, fname)\n with open(txt_path, \"r\") as txt_file:\n dependencies = txt_file.readlines()\n dependencies = [d.strip() for d in dependencies]\n return dependencies\n\n\ninstall_requires = requirements_from_txt(\"requirements.txt\")\ntests_require = requirements_from_txt(\"requirements_test.txt\")\n\nneeds_pytest = {\"pytest\", \"test\", \"ptr\"}.intersection(sys.argv)\nsetup_requires = [\"pytest-runner\"] if needs_pytest else []\n\nsetup(\n name=\"pypbomb\",\n version=__version__,\n python_requires=\">=3.7.*\",\n packages=[\"pypbomb\", \"pypbomb.tests\"],\n url=\"https://github.com/cartemic/pypbomb\",\n license=\"BSD-3\",\n author=\"Mick Carter\",\n author_email=\"cartemic@oregonstate.edu\",\n package_dir={\"pypbomb\": \"pypbomb\"},\n package_data={\n \"pypbomb\": [path.join(\"lookup_data\", \"*\")],\n \"pypbomb.tests\": [path.join(\"lookup_data\", \"*\")],\n },\n description=\"Tools for designing a detonation tube\",\n long_description=long_description,\n install_requires=install_requires,\n tests_require=tests_require,\n setup_requires=setup_requires,\n py_modules=[\"six\"],\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1827,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"479293566","text":"\"\"\"ProgrammingWeek URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/1.8/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))\n\"\"\"\nfrom django.conf.urls import include, url\nfrom django.contrib import admin\nfrom PWManagement import views as PWManagement_views\nfrom PWUser import views as PWUser_views\n\nurlpatterns = [\n url(r'^admin/', include(admin.site.urls)),\n url(r'^$', PWManagement_views.homepage, name=\"homepage\"),\n\n url(r'^homepage/$', PWManagement_views.homepage, name=\"homepage\"),\n url(r'^homecommon/$', PWManagement_views.homecommon, name=\"homecommon\"),\n url(r'^homemanager/$', PWManagement_views.homemanager, name=\"homemanager\"),\n\n url(r'^login/$', PWManagement_views.login, name=\"login\"),\n url(r'^logout/$', PWManagement_views.logout, name=\"logout\"),\n\n url(r'^useradd/$', PWManagement_views.useradd, name=\"useradd\"),\n url(r'^userlist/$', PWManagement_views.userlist, name=\"userlist\"),\n url(r'^recordlist/$', PWManagement_views.recordlist, name=\"recordlist\"),\n \n url(r'^userdetail/(?P[0-9]+)/$', PWManagement_views.userdetail, name=\"userdetail\"),\n url(r'^userchange/(?P[0-9]+)/$', PWManagement_views.userchange, name=\"userchange\"),\n url(r'^recorddetail/(?P[0-9]+)/$', PWManagement_views.recorddetail, name=\"recorddetail\"),\n\n url(r'^managertorecorddetail/(?P[0-9]+)/$', PWManagement_views.managertorecorddetail, name=\"managertorecorddetail\"),\n url(r'^recorddeal/(?P[0-9]+)/(?P[0-9]+)/$', PWManagement_views.recorddeal, name=\"recorddeal\"),\n url(r'^addleaveword/(?P[0-9]+)/$', PWManagement_views.addleaveword, name=\"addleaveword\"),\n]\n","sub_path":"13_Programming_Week_in_School/ProgrammingWeek/ProgrammingWeek/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":2102,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"262707376","text":"from tkinter import EventType\n\n\nMIN_HIGHLIGHT_WIDTH = 16\n\n\nclass Menu(object):\n\n str_deselected_centered = f\" {{:^{MIN_HIGHLIGHT_WIDTH}}} \"\n str_selected_centered = f\" {{:^{MIN_HIGHLIGHT_WIDTH}}} \"\n str_deselected = f\" {{:{MIN_HIGHLIGHT_WIDTH}}} \"\n str_selected = f\" {{:{MIN_HIGHLIGHT_WIDTH}}} \"\n\n def __init__(self, title, choices, disabled_choices=(), scroll=False):\n self.title = title\n self.choices = tuple(obj if isinstance(obj, Choice) else Choice(obj) for obj in choices)\n self.disabled_choices = disabled_choices\n self.scroll = scroll\n\n def show(self, surface, selection=0):\n self.surf = surface\n self.selection = selection\n self.return_value = None\n self.loop = True\n # i = 0\n # for choice in self.choices:\n # choice.menu, choice.index = self, i\n # i += 1\n while self.loop:\n self.draw_full()\n selected_choice = self.surf.t.loop(self.handle_event)\n if selected_choice == -1: # user pressed [Esc] to close menu\n self.close(-1)\n else:\n self.choices[selected_choice].select(self, selected_choice)\n return self.return_value\n\n def close(self, return_value):\n self.loop = False\n self.return_value = return_value\n\n def draw_full(self):\n self.surf.clear()\n if self.scroll:\n self.choices_y = self.surf.y_center - self.selection\n elif self.surf.get_style('content')['center_v']:\n self.choices_y = (self.surf.t.h - len(self.choices)) // 2 + bool(self.title)\n else:\n self.choices_y = 3\n if self.title and self.choices_y > 2:\n self.surf.print_at((self.choices_y - 2, 1), self.title, style='title')\n for i in range(len(self.choices)):\n if 0 <= self.choices_y + i < self.surf.h:\n self.draw_choice(i, False)\n self.update_selection(self.selection)\n\n def draw_choice(self, index, selected):\n if index in self.disabled_choices:\n state = 'disabled'\n else:\n state = 'de' * (not selected) + 'selected'\n fmt = getattr(self, 'str_' + 'de' * (not selected) + 'selected' +\n '_centered' * bool(self.surf.get_style(state)['center_h']))\n # fmt = (self.str_deselected, self.str_selected)[selected]\n text = fmt.format(self.choices[index].get_text(state))\n self.surf.print_at((self.choices_y + index, 1), text, style=state)\n\n def update_selection(self, selection=None):\n self.draw_choice(self.selection, False)\n self.selection = selection\n self.draw_choice(self.selection, True)\n\n def handle_event(self, e):\n if e.type == EventType.KeyPress:\n keysym = e.keysym.lower()\n if keysym in ('up', 'w', 'down', 's'):\n delta = -1 if keysym in ('up', 'w') else 1\n new_sel = self.selection + delta\n while new_sel in self.disabled_choices:\n new_sel += delta\n if 0 <= new_sel < len(self.choices):\n if self.scroll:\n self.selection = new_sel\n self.draw_full()\n else:\n self.update_selection(new_sel)\n elif keysym in ('space', 'return'):\n self.surf.t.exit_loop(self.selection)\n elif keysym in ('escape', 'q'):\n self.surf.t.exit_loop(-1)\n else:\n self.choices[self.selection].handle_keypress(self, e)\n\n\nclass Choice(object):\n\n # # Menu will set these when necessary\n # menu = None\n # index = None\n\n def __init__(self, text):\n self.text = text\n\n def get_text(self, state):\n return self.text\n\n def select(self, menu, index):\n menu.close(index)\n\n def handle_keypress(self, menu, e):\n \"\"\"Handle keypress and return True if choice needs to be redrawn.\"\"\"\n return False\n\n\nclass SpinnerChoice(Choice):\n\n def __init__(self, choices, default, on_choice=lambda choice: None,\n string_function=lambda choice: str(choice)):\n self.choices = choices\n if default in choices:\n self.selection = choices.index(default)\n else:\n self.selection = 0\n self.on_choice = on_choice\n self.string_function = string_function\n\n def get_text(self, state):\n s = self.string_function(self.choices[self.selection])\n s += ' ' * (len(s) % 2)\n f = '< {} >' if state == 'selected' else ' {} '\n return f.format(s)\n\n def select(self, menu, index):\n old_selection = self.selection\n self.selection = Menu(None, [self.string_function(choice) for choice in self.choices],\n scroll=True).show(menu.surf, selection=self.selection)\n if self.selection == -1:\n self.selection = old_selection\n else:\n self.on_choice(self.choices[self.selection])\n\n def handle_keypress(self, menu, e):\n \"\"\"Returns True if choice needs to be redrawn\"\"\"\n if e.keysym in ('Left', 'a', 'Right', 'd'):\n diff = -1 if e.keysym in ('Left', 'a') else +1\n self.selection = (self.selection + diff) % len(self.choices)\n self.on_choice(self.choices[self.selection])\n menu.draw_full()\n","sub_path":"tui/menu.py","file_name":"menu.py","file_ext":"py","file_size_in_byte":5420,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"18262490","text":"#https://programmers.co.kr/learn/courses/30/lessons/42840\r\n\"\"\"\r\n1번: \"12345\"[n%5]로 찍음\r\n2번: \"21232425\"[n%8]로 찍음\r\n3번: \"31245\"[n%10//2]로 찍음\r\n\"\"\"\r\n\r\ndef solution(answers):\r\n answer = [0]*3\r\n for n, v in enumerate(answers):\r\n if str(v) == \"12345\"[n%5]: answer[0]+=1\r\n if str(v) == \"21232425\"[n%8]: answer[1]+=1\r\n if str(v) == \"31245\"[n%10//2]: answer[2]+=1\r\n return [i+1 for i in range(3) if answer[i] == max(answer)]\r\n\r\nanswers = [1,2,3,4,5]\r\nprint(solution(answers))\r\n","sub_path":"완전탐색/1_모의고사.py","file_name":"1_모의고사.py","file_ext":"py","file_size_in_byte":518,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"403953347","text":"import os\nimport sys\nCURRENT_DIR = os.path.abspath(os.path.dirname(__file__))\nsys.path.append(os.path.join(CURRENT_DIR, \"..\", \"..\", \"..\"))\n\nimport ujson as json\nfrom collections import defaultdict, Counter\nimport argparse\n\nfrom aida_utilities.ltf_util import LTF_util\nfrom aida_utilities.finegrain_util import FineGrainedUtil\n\nfrom nltk.stem.snowball import SnowballStemmer\nfrom nltk import WordNetLemmatizer\nfrom pymystem3 import Mystem\n\nevent_newtype = {}\ntype_dict = defaultdict(lambda: defaultdict(lambda: defaultdict(str)))\ntrigger_dict = defaultdict(lambda: defaultdict(str))\ncontext_dict = defaultdict(lambda: defaultdict(str))\n\n\ndef load_lemmer(lang):\n if lang.startswith('en'):\n lemmer = WordNetLemmatizer()\n return lemmer\n elif lang.startswith('ru'):\n lemmer = Mystem()\n return lemmer\n elif lang.startswith('uk'):\n stemmer = dict()\n for line in open(os.path.join(CURRENT_DIR, 'rules', 'lemmatization-uk.txt')):\n line = line.rstrip('\\n')\n tabs = line.split('\\t')\n if len(tabs) == 2:\n stemmer[tabs[0]] = tabs[1]\n return stemmer\n else:\n return None\n\ndef lemma_long(trigger, lemmer, lang):\n if lang.startswith('en'):\n return ' '.join([lemmer.lemmatize(trigger_sub) for trigger_sub in trigger.split(' ')])\n elif lang.startswith('ru'):\n return ' '.join(lemmer.lemmatize(trigger))\n elif lang.startswith('uk'):\n toks = []\n for trigger_sub in trigger.split(' '):\n if trigger_sub in lemmer:\n toks.append(lemmer[trigger_sub])\n else:\n toks.append(trigger_sub)\n return ' '.join(toks)\n else:\n return trigger\n\n\ndef stem_long(trigger, stemmer, lang):\n if lang.startswith('uk'):\n toks = []\n for trigger_sub in trigger.split(' '):\n if trigger_sub in stemmer:\n toks.append(stemmer[trigger_sub])\n else:\n toks.append(trigger_sub)\n return ' '.join(toks)\n else:\n return ' '.join([stemmer.stem(trigger_sub) for trigger_sub in trigger.split(' ')])\n\ndef load_stemmer(lang):\n if lang.startswith('en'):\n stemmer = SnowballStemmer(\"english\")\n return stemmer\n elif lang.startswith('ru'):\n stemmer = SnowballStemmer(\"russian\")\n return stemmer\n elif lang.startswith('uk'):\n stemmer = dict()\n for line in open(os.path.join(CURRENT_DIR, 'rules', 'lemmatization-uk.txt')):\n line = line.rstrip('\\n')\n tabs = line.split('\\t')\n if len(tabs) == 2:\n stemmer[tabs[0]] = tabs[1]\n return stemmer\n else:\n return None\n\ndef load_mapping(mapping_file):\n mapping = {}\n for line in open(mapping_file):\n line = line.rstrip('\\n')\n tabs = line.split('\\t')\n mapping[tabs[0]] = tabs[1]\n return mapping\n\n# default mapping\nnewtype_mapping_backup = load_mapping(os.path.join(CURRENT_DIR, 'rules', 'mapping_backup.txt'))\n# if here, directly mapping\nnewtype_mapping_sure = load_mapping(os.path.join(CURRENT_DIR, 'rules', 'mapping.txt'))\n\n# if delete_type, directly delete\ndelete_type_sure = ['Business.DeclareBankruptcy', 'Business.End', 'Life.BeBorn', 'Life.Marry', 'Life.Divorce']\n# after apply rules, delete if no result\ndelete_type_notsure = ['Business.Start', 'Business.Merge']\n\ndef load_arg_mapping(mapping_arg_file):\n mapping = defaultdict(lambda: defaultdict(str))\n for line in open(mapping_arg_file):\n line = line.rstrip('\\n')\n tabs = line.split('\\t')\n if len(tabs) == 3:\n # newtype -> original role -> new role\n mapping[tabs[0]][tabs[1]] = tabs[2]\n else:\n print(line)\n return mapping\n\narg_mapping = load_arg_mapping(os.path.join(CURRENT_DIR, 'rules', 'mapping_args.txt'))\n\nprefix = \"https://tac.nist.gov/tracks/SM-KBP/2019/ontologies/LDCOntology#\"\n\ndef prep_type_old(typestr):\n return typestr.replace(\"https://tac.nist.gov/tracks/SM-KBP/2018/ontologies/SeedlingOntology#\", \"\")\n\ndef prep_arg_type_old(typestr):\n typestr = typestr.replace(\"https://tac.nist.gov/tracks/SM-KBP/2018/ontologies/SeedlingOntology#\", \"\")\\\n .replace(\".actual\", \"\")\n return typestr[typestr.find('_')+1:]\n\n# read entity fingrain\ndef entity_finegrain_by_cs(entity_finegrain, entity_dict):\n # entity_dict = defaultdict(set)\n for line in open(entity_finegrain):\n if line.startswith(':Entity'):\n line = line.rstrip('\\n')\n tabs = line.split('\\t')\n if tabs[1] == 'type':\n type_str = tabs[2].split('#')[-1]\n # add parent type\n tabs = type_str.split('.')\n for i in range(len(tabs)):\n entity_dict[tabs[0]].add('.'.join(tabs[:(i+1)]))\n return entity_dict\n\n# read old event types\ndef load_events(event_coarse, entity_dict):\n event_dict = {}\n for line in open(event_coarse):\n if line.startswith(':Event'):\n line = line.rstrip('\\n')\n tabs = line.split('\\t')\n event_id = tabs[0]\n if event_id not in event_dict:\n event_dict[event_id] = {}\n event_dict[event_id]['mention'] = {}\n event_dict[event_id]['args'] = {}\n if tabs[1] == 'type':\n event_dict[event_id]['type'] = prep_type_old(tabs[2])\n elif 'mention' in tabs[1]:\n event_dict[event_id]['mention'][tabs[2].replace(\"\\\"\", \"\")] = tabs[3] # trigger -> offset, to find context\n elif 'mention' not in tabs[1]:\n arg_role = prep_arg_type_old(tabs[1])\n arg = tabs[2]\n event_dict[event_id]['args'][arg_role] = entity_dict[arg]\n return event_dict\n\n# ps = PorterStemmer()\ndef trigger_lang_stem(trigger, offset, lang, stemmer, en_stemmer):\n # # ->english\n # if not lang.startswith('en'):\n # trigger = trans[offset]\n # lang = 'en'\n # stemmer = en_stemmer\n # stem\n trigger = trigger.lower()\n if stemmer is not None:\n trigger_stem = stem_long(trigger, stemmer, lang)\n return trigger_stem\n else:\n return trigger\n\n# read fine-grained type rules\ndef load_type_dict(type_dict_path):\n for line in open(type_dict_path):\n line = line.rstrip('\\n')\n tabs = line.split('\\t')\n old_type = tabs[0]\n new_type = tabs[1]\n arg_role = tabs[2]\n for arg_type in tabs[3].split(','):\n type_dict[old_type][arg_role][arg_type.strip()] = new_type\n return type_dict\n\n# read trigger constraint\ndef load_trigger_dict(trigger_dict_path, stemmer, lang):\n # stemmer = SnowballStemmer(\"english\")\n for line in open(trigger_dict_path):\n line = line.rstrip('\\n')\n tabs = line.split('\\t')\n old_type = tabs[0]\n new_type = tabs[1]\n for trigger_need in tabs[2].split(','):\n trigger_need = trigger_need.strip()\n trigger_need = stem_long(trigger_need, stemmer, lang)\n trigger_dict[old_type][trigger_need] = new_type\n return trigger_dict\n\n# read context constraint\ndef load_context_dict(context_dict_path, lemmer):\n # stemmer = SnowballStemmer(\"english\") # dict is english\n for line in open(context_dict_path):\n line = line.rstrip('\\n')\n tabs = line.split('\\t')\n old_type = tabs[0]\n new_type = tabs[1]\n for context_need in tabs[2].split(','):\n context_need = context_need.strip()\n context_need = lemma_long(context_need, lemmer, lang)\n context_dict[old_type][context_need] = new_type\n return context_dict\n\n# change type\ndef update_type(event_id, event_dict, type_dict, trigger_dict, context_dict, ltf_util,\n lang, stemmer, en_stemmer, lemmer):\n all_source_voter = Counter()\n\n # print(event_dict[event_id])\n\n old_type = event_dict[event_id]['type']\n if old_type in newtype_mapping_sure:\n return newtype_mapping_sure[old_type]\n if old_type in delete_type_sure:\n return None\n\n # by type\n new_types_by_arg = defaultdict(int)\n for arg_role in type_dict[old_type]:\n if arg_role in event_dict[event_id]['args']:\n if old_type == 'Life.Die' and (arg_role == 'Agent' or arg_role == 'Instrument'):\n return 'Life.Die.DeathCausedByViolentEvents'\n elif old_type == 'Life.Injure' and (arg_role == 'Agent' or arg_role == 'Instrument'):\n return 'Life.Injure.IllnessDegradationPhysical'\n arg_types = event_dict[event_id]['args'][arg_role]\n for arg_type in arg_types:\n # mutliple types\n if arg_type in type_dict[old_type][arg_role]:\n aida_type = type_dict[old_type][arg_role][arg_type]\n new_types_by_arg[aida_type] += 1\n new_types_by_arg_sorted = sorted(new_types_by_arg.items(), key=lambda x: (len(x[0].split('.')), x[1]),\n reverse=True)\n # print('arg-based: ', new_types_by_arg_sorted)\n if len(new_types_by_arg_sorted) > 0:\n max_type, max_score = new_types_by_arg_sorted[0]\n for each_type, each_score in new_types_by_arg_sorted:\n if each_score == max_score and len(max_type.split('.')) == len(each_type.split('.')):\n all_source_voter[each_type] += 1\n\n # by trigger\n new_types_by_trgger = defaultdict(int)\n new_types_by_context = defaultdict(int)\n for trigger in event_dict[event_id]['mention']:\n # only one offset, before coreference\n offset = event_dict[event_id]['mention'][trigger]\n # if use_translate:\n # trigger_stem = trigger_lang_stem(trigger, offset, lang, stemmer, en_stemmer)\n # else:\n trigger_stem = trigger_lang_stem(trigger, offset, lang, stemmer, en_stemmer)\n if trigger_stem in trigger_dict[old_type]:\n aida_type = trigger_dict[old_type][trigger_stem]\n new_types_by_trgger[aida_type] += 1\n # return trigger_dict[old_type][trigger_stem]\n # print(trigger, old_type, aida_type)\n # if trigger == 'fire' and 'set fire not in the sentence':\n\n\n # if lang == 'en':\n context_sent = ' '.join(ltf_util.get_context(offset)).lower()\n context_sent = lemma_long(context_sent, lemmer, lang)\n for context_symbol in context_dict[old_type]:\n if ' '+context_symbol+' ' in context_sent:\n aida_type = context_dict[old_type][context_symbol]\n new_types_by_context[aida_type] += 1\n # print(trigger, context_symbol, old_type, aida_type, context_sent)\n\n fire_str = {'en': 'fire', 'ru': 'Пожар', 'uk': 'вогонь'}\n set_fire_str = {'en': 'set fire', 'ru': 'поджечь', 'uk': 'підпалити'}\n if trigger_stem == fire_str[lang] and old_type == 'Conflict.Attack':\n # if use_translate:\n # stemmed = stem_long('set fire', en_stemmer, 'en')\n # else:\n stemmed = stem_long(set_fire_str[lang], stemmer, lang)\n if stemmed not in context_sent:\n aida_type = 'Conflict.Attack.FirearmAttack'\n all_source_voter[aida_type] += 1\n else:\n aida_type = 'Conflict.Attack.SetFire'\n all_source_voter[aida_type] += 1\n\n # print(trigger, old_type, aida_type)\n # context_words = ltf_util.get_context(offset)\n # for context_word in context_words:\n # context_word = stem_long(context_word, stemmer, lang)\n # if context_word in context_dict[old_type]:\n # aida_type = context_dict[old_type][context_word]\n # new_types_by_context[aida_type] += 1\n # # return context_dict[old_type][context_word]\n\n new_types_by_trgger_sorted = sorted(new_types_by_trgger.items(), key=lambda x: (len(x[0].split('.')), x[1]),\n reverse=True)\n # print('trigger-based: ', new_types_by_trgger_sorted)\n if len(new_types_by_trgger_sorted) > 0:\n max_type, max_score = new_types_by_trgger_sorted[0]\n for each_type, each_score in new_types_by_trgger_sorted:\n if each_score == max_score and len(max_type.split('.')) == len(each_type.split('.')):\n all_source_voter[each_type] += 1\n\n new_types_by_context_sorted = sorted(new_types_by_context.items(), key=lambda x: (len(x[0].split('.')), x[1]),\n reverse=True)\n # print('context-based: ', new_types_by_context_sorted)\n if len(new_types_by_context_sorted) > 0:\n max_type, max_score = new_types_by_context_sorted[0]\n for each_type, each_score in new_types_by_context_sorted:\n if each_score == max_score and len(max_type.split('.')) == len(each_type.split('.')):\n all_source_voter[each_type] += 1\n\n if len(all_source_voter) == 0:\n # not find\n if old_type in delete_type_notsure:\n # print('\\nno fine-grained type')\n return None\n else:\n return newtype_mapping_backup[old_type]\n newtype = all_source_voter.most_common(1)[0][0]\n # print('\\nfinal fine-grained type', old_type, '->', all_source_voter.most_common(1))\n # print('\\n=====================================\\n')\n return newtype\n\ndef update_type_all(event_dict, type_dict, trigger_dict, context_dict, ltf_util,\n lang, stemmer, en_stemmer, lemmer):\n for event_id in event_dict:\n newtype = update_type(event_id, event_dict, type_dict, trigger_dict, context_dict, ltf_util,\n lang, stemmer, en_stemmer,\n lemmer)\n if newtype is not None:\n event_newtype[event_id] = newtype\n # print(event_dict[event_id]['mention'])\n return event_newtype\n\ndef rewrite(event_newtype, event_coarse, output):\n f_out = open(output, 'w')\n deleted_events = set()\n for line in open(event_coarse):\n if line.startswith(':Event'):\n line = line.rstrip('\\n')\n tabs = line.split('\\t')\n event_id = tabs[0]\n if event_id in deleted_events:\n continue\n if event_id not in event_newtype:\n # print(event_id, 'deleted')\n deleted_events.add(event_id)\n continue\n # print(event_id)\n newtype = event_newtype[event_id]\n if tabs[1] == 'type':\n f_out.write('%s\\t%s\\t%s%s\\n' % (event_id, 'type', prefix, newtype))\n continue\n elif len(tabs) > 4 and 'mention' not in tabs[1]:# elif 'https:' in tabs[1]:\n old_role = tabs[1][tabs[1].find('_')+1:]\n # print(arg_mapping[newtype])\n if newtype in arg_mapping:\n if old_role in arg_mapping[newtype]:\n newrole = arg_mapping[newtype][old_role]\n else:\n newrole = old_role\n else:\n parent_type = newtype[:newtype.rfind('.')]\n # print('parent_type', parent_type)\n if parent_type in arg_mapping:\n if old_role in arg_mapping[parent_type]:\n newrole = arg_mapping[parent_type][old_role]\n else:\n newrole = old_role\n else:\n newrole = old_role\n if newrole != 'None':\n f_out.write('%s\\t%s%s_%s\\t%s\\t%s\\t%s\\n' %\n (event_id, prefix, newtype, newrole,\n tabs[2].replace(':Filler_', ':Entity_Filler_'), tabs[3], tabs[4]))\n continue\n f_out.write('%s\\n' % line)\n print('Events deleted: ', len(deleted_events))\n ## argument role update!!!!\n f_out.close()\n\ndef load_trans(trans_file, lang):\n trans = {}\n if lang.startswith('en'):\n return trans\n for line in open(trans_file):\n line = line.rstrip('\\n')\n tabs = line.split('\\t')\n if len(tabs) == 2:\n trans[tabs[0]] = tabs[1]\n else:\n if len(line) != 0:\n print('[ERROR] tranlation file can not separated by ', line)\n return trans\n\n\ndef runner(lang, ltf_dir, entity_finegrain, entity_freebase_tab, entity_coarse,\n filler_coarse, event_coarse, output, visualpath, entity_finegrain_aida\n ):\n ltf_util = LTF_util(ltf_dir)\n\n # trans = load_trans(trans_file, lang)\n\n type_dict_path = os.path.join(CURRENT_DIR, 'rules', 'type_dict.txt')\n trigger_dict_path = os.path.join(CURRENT_DIR, 'rules', lang+'_trigger_dict_clean_v2.txt')\n context_dict_path = os.path.join(CURRENT_DIR, 'rules', lang+'_context_dict.txt')\n hierarchy_dir = os.path.join(CURRENT_DIR, '../../../entity/aida_edl/conf/yago_taxonomy_wordnet_single_parent.json')\n finetype_util = FineGrainedUtil(hierarchy_dir)\n entity_dict = finetype_util.entity_finegrain_by_json(entity_finegrain, entity_freebase_tab, entity_coarse,\n filler_coarse)\n\n entity_dict = entity_finegrain_by_cs(entity_finegrain_aida, entity_dict)\n\n # print(entity_dict)\n stemmer = load_stemmer(lang)\n en_stemmer = load_stemmer('en')\n lemmer = load_lemmer(lang)\n\n event_dict = load_events(event_coarse, entity_dict)\n print('event_dict', len(event_dict))\n type_dict = load_type_dict(type_dict_path)\n # print(type_dict)\n trigger_dict = load_trigger_dict(trigger_dict_path, stemmer, lang)\n # print(trigger_dict)\n context_dict = load_context_dict(context_dict_path, lemmer)\n # print(context_dict)\n\n event_newtype = update_type_all(event_dict, type_dict, trigger_dict, context_dict, ltf_util,\n lang, stemmer, en_stemmer, lemmer)\n rewrite(event_newtype, event_coarse, output)\n\n if args.visualpath is not None:\n head = '''\n \n \n \n Page Title\n \n \n '''\n\n tail = '''\n \n \n '''\n\n f_html = open(visualpath, 'w')\n f_html.write('%s\\n' % head)\n count = 0\n for event in event_newtype:\n for trigger in event_dict[event]['mention']:\n count = count + 1\n ### print('Trigger: %s'%trigger[3], 'Argument: %s'%argument[3])\n f_html.write('

%d. Old Event type: %s;
New Event type: %s;
Trigger: %s;

' % (\n #
Argument: %s; Argument Role: %s\n count, event_dict[event]['type'], event_newtype[event], trigger)) # , event_dict[event]['type']\n sent_out = ltf_util.get_context(event_dict[event]['mention'][trigger])\n sent_out_new = []\n for word in sent_out:\n if word == trigger:\n word = '' + word + ''\n sent_out_new.append(word)\n f_html.write('

%s



' % (' '.join(sent_out_new)))\n # one trigger ##(??? multiple trigger?) -> no coreference, so not yet\n continue\n f_html.flush()\n f_html.close()\n\n print(\"Fine-grained event typing done for \", lang)\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('lang', type=str,\n help='lang.')\n parser.add_argument('ltf_dir', type=str,\n help='ltf_dir')\n parser.add_argument('entity_finegrain', default=str,\n help='entity_finegrain')\n parser.add_argument('entity_freebase_tab', type=str,\n help='entity_freebase_tab')\n parser.add_argument('entity_coarse', default=str,\n help='entity_coarse')\n parser.add_argument('event_coarse', default=str,\n help='event_coarse')\n # parser.add_argument('output_dir', default=str, help='output')\n parser.add_argument('output', default=str,\n help='output')\n parser.add_argument('--visualpath', default=None,\n help='visualpath')\n # parser.add_argument('--trans_file', type=None,\n # help='trans_file')\n parser.add_argument('--filler_coarse', type=None,\n help='filler_coarse')\n parser.add_argument('--entity_finegrain_aida', type=None,\n help='entity_finegrain_aida')\n\n args = parser.parse_args()\n\n lang = args.lang\n ltf_dir = args.ltf_dir\n entity_finegrain = args.entity_finegrain\n entity_freebase_tab = args.entity_freebase_tab\n entity_coarse = args.entity_coarse\n filler_coarse = args.filler_coarse\n event_coarse = args.event_coarse\n # trans_file = args.trans_file\n output = args.output\n visualpath = args.visualpath\n entity_finegrain_aida = args.entity_finegrain_aida\n # output_dir = args.output_dir\n # output = os.path.join(output_dir, 'events_%s_fine.cs' % lang)\n # visualpath = os.path.join(output_dir, 'events_%s_fine.html' % lang)\n\n runner(lang, ltf_dir, entity_finegrain, entity_freebase_tab, entity_coarse,\n filler_coarse, event_coarse, output, visualpath, entity_finegrain_aida\n )","sub_path":"event/aida_event/fine_grained/fine_grained_events.py","file_name":"fine_grained_events.py","file_ext":"py","file_size_in_byte":21527,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"543574377","text":"import spacy\n\nfrom server.pipeline_components import AtcEntityTagger\nfrom server.utils.number import replace_words_with_digits\n\nnlp = spacy.load(\"en_core_web_sm\")\nnlp.remove_pipe(\"ner\")\nnlp.add_pipe(AtcEntityTagger(nlp), last=True)\n\n\ndef annotate(text=\"\"):\n if not text:\n return \"\"\n text = text.lower()\n doc = nlp(text)\n\n markup = _create_entities_markup(doc)\n markup = replace_words_with_digits(markup)\n\n return markup\n\n\ndef _create_entities_markup(doc):\n markup_tokens = []\n\n for token in doc:\n bilou = token._.atc_ent_bilou_\n type_ = token._.atc_ent_type_\n\n if bilou == \"U\":\n markup_tokens.extend([f\"<{type_}>\", token.text, f\"\"])\n elif bilou == \"B\":\n markup_tokens.extend([f\"<{type_}>\", token.text])\n elif bilou == \"L\":\n markup_tokens.extend([token.text, f\"\"])\n else:\n markup_tokens.append(token.text)\n\n return \" \".join(markup_tokens)","sub_path":"server/server/annotate.py","file_name":"annotate.py","file_ext":"py","file_size_in_byte":977,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"526986135","text":"\"\"\"\n=======================\nNetwork simulation core\n=======================\n\nThis module contains the main Simulation class.\n\nA simulation object is responsible for creating network and process and to \nexecute the main loop, running the process on the network. It also handles I/O\nand logging. Saving data after each run.\n\n\"\"\"\n\n__author__ = \"Lukas Ahrenberg (lukas@ahrenberg.se)\"\n\n__license__ = \"Modified BSD License\"\n\n__all__ = ['Simulation']\n\nimport numpy\nimport sys\nimport imp\nimport csv\nimport time\nimport networkx\nimport copy\nimport os\nfrom collections import OrderedDict\nimport pickle\n\n# Local imports\n\nfrom nepidemix import process\n\n\nfrom nepidemix.exceptions import NepidemiXBaseException\n\nfrom nepidemix.utilities import NepidemiXConfigParser\n\nfrom nepidemix.version import full_version\n\nfrom nepidemix.utilities.dbio import sqlite3io\n\n# Logging\nimport logging\n\n# Set up Logging\nlogger = logging.getLogger(__name__)\n\n\nclass Simulation(object):\n \"\"\"\n Captures the functionality of a simulation in a class.\n\n A simulation has three stages: configuration, execution, and data export.\n Configuration is made using an ini-like language, and the configure method\n takes a Python ConfigParser compatible structure.\n Once the simulation is configured it is started by execute, and finally call\n saveData in order to save any simulation data to disc.\n \n What data is saved depends on how the simulation is configured (as outlined\n below) and on which process is used. Currently the simulation can be set up\n to track the number of nodes in each mean field state defined by the process\n and/or the full network (topology and states).\n\n A very short example running a simulation (given a configuration file named\n 'myconfig.ini'::\n \n cfParser = nepidemix.utilities.NepidemiXConfigParser()\n\n configFileName = 'myconfig.ini'\n\n with open(configFileName) as f:\n cfParser.readfp(f)\n\n S = nepidemix.simulation.Simulation()\n\n S.configure(cfParser)\n\n S.execute()\n\n S.saveData()\n \n\n Configuration files are written in an ini-like language with sections and\n