diff --git "a/5058.jsonl" "b/5058.jsonl" new file mode 100644--- /dev/null +++ "b/5058.jsonl" @@ -0,0 +1,100 @@ +{"seq_id":"598912271","text":"import requests\r\n# This import is actually used now, we use this to convert our input dictionary to JSON to use as a part of the request\r\nimport json\r\n\r\n# The header Content-Type : application/json tells the endpoint that it will receive data in JSON format! This\r\n# request will NOT work without this! Try it out yourself by removing it.\r\nrequest_headers = {\"Content-Type\": \"application/json\"}\r\n\r\n# The JSON object (python dictionary) to send to the API\r\ninput = \"Hello world\"\r\ndata_to_send = {\"INPUT\": input}\r\n\r\n# The endpoint for the API\r\napi_url = \"http://api.shoutcloud.io/V1/SHOUT\"\r\n\r\n# We make the actual request here, this seems similar to the last program, right? The difference here is that we\r\n# use the post() method instead and also send it the headers!\r\nresponse = requests.post(url=api_url, data=json.dumps(data_to_send), headers=request_headers)\r\n\r\n# Read the response as JSON and print out the \"OUTPUT\" field!\r\nresponse_json = response.json()\r\nprint(response_json[\"OUTPUT\"])","sub_path":"simple-python-post-example.py","file_name":"simple-python-post-example.py","file_ext":"py","file_size_in_byte":991,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"172758177","text":"\r\nimport pygame as pg\r\nfrom pygame import gfxdraw\r\nfrom game import projectile\r\n\r\n\r\nclass Player:\r\n\r\n def __init__(self, x, y, size, name, color=(0, 100, 200), health=10):\r\n\r\n self.x, self.y = x, y\r\n self.size = size\r\n\r\n self.color = color\r\n self.name = name\r\n self.vel = 0.2\r\n self.health = health\r\n self.alive = True\r\n\r\n self.projectiles = []\r\n self.hit = {}\r\n\r\n def shoot(self, events):\r\n for e in events:\r\n if e.type == pg.MOUSEBUTTONDOWN:\r\n self.projectiles.append(projectile.Projectile(self.x, self.y, pg.mouse.get_pos()))\r\n\r\n def move(self, dt, keybinds):\r\n keys = pg.key.get_pressed()\r\n if keys[getattr(pg, keybinds['move_left'])]:\r\n self.x -= self.vel * dt\r\n if keys[getattr(pg, keybinds['move_right'])]:\r\n self.x += self.vel * dt\r\n if keys[getattr(pg, keybinds['move_up'])]:\r\n self.y -= self.vel * dt\r\n if keys[getattr(pg, keybinds['move_down'])]:\r\n self.y += self.vel * dt\r\n\r\n def update(self, client):\r\n self.move(client.dt, client.keybinds)\r\n\r\n self.hit = {}\r\n self.shoot(client.events)\r\n for p in self.projectiles:\r\n p.update(client, self.projectiles)\r\n\r\n def draw(self, screen, font):\r\n # Name.\r\n if self.alive:\r\n label = font.render(str(self.name), True, (0, 0, 255))\r\n else:\r\n label = font.render(str(self.name) + ' (dead)', True, (255, 0, 0))\r\n screen.blit(label, (self.x - label.get_width() / 2, self.y - 50))\r\n\r\n # Character.\r\n gfxdraw.aacircle(screen, round(int(self.x)), round(int(self.y)), 20, self.color)\r\n gfxdraw.filled_circle(screen, round(int(self.x)), round(int(self.y)), 20, self.color)\r\n\r\n for p in self.projectiles:\r\n p.draw(screen)\r\n","sub_path":"game/player.py","file_name":"player.py","file_ext":"py","file_size_in_byte":1884,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"435322561","text":"\"\"\"NGS utilities: Indexed FASTA I/O.\"\"\"\nfrom __future__ import absolute_import, division, print_function\nfrom builtins import str\n\nimport logging\nfrom itertools import groupby\nfrom pyfaidx import Fasta\n\n\ndef fasta_extract_regions(fa_fname, intervals):\n \"\"\"Extract an iterable of regions from an indexed FASTA file.\n\n Input: FASTA file name; iterable of (seq_id, start, end) (1-based)\n Output: iterable of string sequences.\n \"\"\"\n with Fasta(fa_fname, as_raw=True) as fa_file:\n for chrom, rows in groupby(intervals, lambda cse: cse[0]):\n logging.info(\"Extracting sequences from chromosome %s\", chrom)\n for _chrom, start, end in rows:\n yield fa_file[_chrom][start:end]\n\n\ndef _fasta_extract_regions_safe(fa_fname, intervals):\n \"\"\"Simpler, slower version of fasta_extract_regions, for testing it.\"\"\"\n from Bio import SeqIO\n idx = SeqIO.index(fa_fname, 'fasta')\n for chrom, rows in groupby(intervals, lambda cse: cse[0]):\n logging.info(\"Extracting sequences from chromosome %s\", chrom)\n seq = str(idx[chrom].seq)\n for chrom, start, end in rows:\n subseq = seq[start:end]\n if len(subseq) != end - start:\n logging.info(\"Short subsequence %s:%d-%d; read %d, wanted %d\",\n chrom, start, end, len(subseq), end - start)\n yield subseq\n","sub_path":"cnvlib/ngfrills/faidx.py","file_name":"faidx.py","file_ext":"py","file_size_in_byte":1388,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"304933473","text":"import math\n\nfrom scipy.optimize import least_squares\n\nfrom utils import distance\n\n\ndef residuals(guess, p, r):\n x, y = guess\n res = ()\n for i in p:\n xi = p[i][0]\n yi = p[i][1]\n ri = r[i]\n res += ((distance((x, y), (xi, yi)) - ri) / ri**2, )\n return res\n\n\ndef nls(guess, p, r):\n ls = least_squares(residuals, guess, args=(p, r))\n return ls.x\n","sub_path":"nls.py","file_name":"nls.py","file_ext":"py","file_size_in_byte":388,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"252115004","text":"''' basic container '''\nimport functools\n\nfrom .method import ExtraNeed, RpcMethod\nfrom .typedef import Callable\n\n\nclass _MethodContainer:\n ''' Basic class which contains method maps '''\n def __init__(self):\n self.methods = {}\n\n def rpc_call(self, func):\n '''\n decorator function to make a function rpc_callable\n Usage example::\n\n # make one function to be rpc called\n @server.rpc_call\n def substract(num1, num2):\n return num1 - num2\n\n # also support for the async rpc call\n @server.rpc_call\n async def io_bound_call(num1):\n await asyncio.sleep(3)\n return num1\n '''\n @functools.wraps(func)\n def wrapped(*args, **kwargs):\n return func(*args, **kwargs)\n self.add_method(func)\n return wrapped\n\n def add_method(self, method,\n restrict=True,\n need_multiprocessing=False,\n need_multithreading=False):\n ''' add method to json rpc, to make it rpc callable\n\n :param method: which method to be rpc callable\n :param restrict: controls the behavior when try to add method which have already\n been added, if restrict is True, an exception will be raise when\n user try to add an exist method. Otherwise the method will be\n overrided\n :param need_multiprocessing: if the value is True, then when we call the rpc method,\n the method will execute in separate process, this argument\n is useful for the high-CPU method\n :param need_multithreading: if the value is True, when we call the rpc method,\n the method will execute in separate thread, this argument\n is useful for the IO-bound method. When all need_multiprocessing\n and need_multithreading are True, the method will be added as\n need multiprocessing method\n .. versionadded:: 0.3\n The `need_multiprocessing`, `need_multithreading` parameters were added\n '''\n if need_multiprocessing:\n extra_need = ExtraNeed.PROCESS\n elif need_multithreading:\n extra_need = ExtraNeed.THREAD\n else:\n extra_need = ExtraNeed.NOTHING\n\n if restrict and method.__name__ in self.methods:\n raise ValueError(\"The method is existed\")\n else:\n self.methods[method.__name__] = RpcMethod(method, extra_need)\n\n def get_rpc_method(self, method_name: str) -> RpcMethod:\n ''' get and return the instance of RpcMethod which is directly in the Container\n different to get_method, get_rpc_method will return RpcMethod instance '''\n try:\n return self.methods[method_name]\n except KeyError as e:\n raise ValueError(f'The method \"{method_name}\" is not registered in the Server')\n\n def get_method(self, method_name: str) -> Callable:\n ''' get and return actual rpc method, which is directly in the Container\n if the method is not existed, a ValueError will occured'''\n return self.get_rpc_method(method_name).func\n","sub_path":"ajson_rpc2/container.py","file_name":"container.py","file_ext":"py","file_size_in_byte":3374,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"210374455","text":"# -*- coding: utf-8 -*-\n\nfrom service.models import _SearchItem, none_to_string\nfrom service.query import TOWNNAME_FIELDNAME, STREETNAME_FIELDNAME, \\\n TOWNPART_FIELDNAME, MAX_TEXT_COUNT, \\\n compile_address\n\n__author__ = 'Radim Jäger'\n\n\ndef old_get_combined_text_searches(items):\n sql_list = []\n sql_sub_list = []\n\n def add_combination(sql_condition):\n # global sql_sub_list\n if not sql_sub_list:\n sql_sub_list.append(sql_condition)\n else:\n for i in range(len(sql_sub_list)):\n sql_sub_list[i] += \" and \" + sql_condition\n\n def add_candidates(field_name, value_list):\n if value_list is not None and value_list != []:\n for it in value_list:\n add_combination(field_name + \" = '\" + it + \"'\")\n\n for item in items:\n if item.isTextField():\n sql_sub_list = []\n add_candidates(TOWNNAME_FIELDNAME, item.towns)\n add_candidates(TOWNPART_FIELDNAME, item.townParts)\n add_candidates(STREETNAME_FIELDNAME, item.streets)\n\n if not sql_list:\n sql_list.extend(sql_sub_list)\n else:\n new_list = []\n for oldItem in sql_list:\n for newItem in sql_sub_list:\n new_list.append(oldItem + \" and \" + newItem)\n sql_list = []\n sql_list.extend(new_list)\n return sql_list\n\n\ndef get_text_items(items):\n result = []\n for item in items:\n if item.isTextField():\n result.append(item)\n if len(result) == MAX_TEXT_COUNT:\n break\n return result\n\n\ndef get_text_variants(text_items):\n streets = []\n towns = []\n town_parts = expanded_text_items(text_items)\n if not streets:\n streets = [_SearchItem(None, None, None)]\n if not towns:\n towns = [_SearchItem(None, None, None)]\n if not town_parts:\n town_parts = [_SearchItem(None, None, None)]\n return streets, towns, town_parts\n\n\ndef expanded_text_items(search_items):\n result = []\n for item in search_items:\n for street in item.streets:\n result.append(_SearchItem(item, street, STREETNAME_FIELDNAME))\n\n for town in item.towns:\n result.append(_SearchItem(item, town, TOWNNAME_FIELDNAME))\n\n for townPart in item.townParts:\n result.append(_SearchItem(item, townPart, TOWNPART_FIELDNAME))\n\n return result\n\n\ndef get_combined_text_searches(items):\n text_items = get_text_items(items)\n sql_items = []\n for item in text_items:\n sql_items.append(item)\n return []\n\n\ndef add_id(identifier, value, string, builder):\n if builder.formatText == \"json\":\n return '\\t\"%s\": %s,\\n%s' % (identifier, value, string)\n elif builder.formatText == \"xml\":\n return '\\t<%s>%s\\n%s' % (identifier, value, identifier, string)\n else:\n return value + builder.lineSeparator + string\n\n\ndef build_address(builder, candidates, with_id, with_distance=False):\n items = []\n for item in candidates:\n if item[4] == \"č.p.\":\n house_number = str(item[5])\n record_number = \"\"\n else:\n house_number = \"\"\n record_number = str(item[5])\n\n mop = none_to_string(item[9])\n if mop != \"\":\n pom = mop.split()\n district_number = pom[1]\n else:\n district_number = \"\"\n\n # TODO compiled address\n sub_str = compile_address(\n text_format=builder,\n street=none_to_string(item[3]),\n house_number=house_number,\n record_number=record_number,\n orientation_number=none_to_string(item[6]),\n orientation_number_character=none_to_string(item[7]),\n zip_code=str(item[8]),\n locality=none_to_string(item[1]),\n locality_part=none_to_string(item[2]),\n district_number=district_number,\n district_name=mop\n )\n\n if with_id:\n sub_str = add_id(\"id\", str(item[0]), sub_str, builder)\n if with_distance:\n sub_str = add_id(\"distance\", str(item[10]), sub_str, builder)\n items.append(sub_str)\n return items\n","sub_path":"rest-service/service/parseaddress.py","file_name":"parseaddress.py","file_ext":"py","file_size_in_byte":4232,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"248478901","text":"from django.contrib.auth.decorators import login_required\nfrom django.shortcuts import render, redirect\n\nimport account.api\nfrom . import account_forms\n\n\n@login_required\ndef startpage(request):\n history = account.api.get_history(request.user.id)\n\n ctx = {\n 'account_balance': sum(row['amount'] for row in history)\n }\n\n return render(request, 'budget/startpage.html', ctx)\n\n\n@login_required\ndef account_history(request):\n history = account.api.get_history(request.user.id)\n\n ctx = {\n 'history': history,\n 'history_sum': sum(row['amount'] for row in history)\n }\n\n return render(request, 'account/history.html', ctx)\n\n\n@login_required\ndef account_charge(request):\n form = account_forms.Charge(request.POST or None)\n if form.is_valid():\n form.save(user_id=request.user.id)\n\n return redirect('account_history')\n\n ctx = {\n 'form': form\n }\n\n return render(request, 'account/charge.html', ctx)\n","sub_path":"src/budget/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":967,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"432012635","text":"import pygame\n\nclass Settings:\n\n def __init__(self):\n # Configuraciones de la pantalla\n self.pantalla_width = 800\n self.pantalla_heigth = 600\n self.pantalla_FPS = 120\n\n # Patrones\n self.patron_bito = [\n ['XXXXX'],\n ['X-X-X'],\n ['-X-X-'],\n ['X---X'],\n ['XXXXX'],\n ['X---X'],\n ['X----'],\n ['XXXXX'],\n ['X----'],\n ['-XXX-'],\n ['X---X'],\n ['-XXX-']\n ]\n self.patron_mon = [\n ['XXXXX'],\n ['-X---'],\n ['--X--'],\n ['-X---'],\n ['XXXXX'],\n ['-XXX-'],\n ['X---X'],\n ['-XXX-'],\n ['XXXXX'],\n ['-X---'],\n ['--X--'],\n ['XXXXX']\n ]\n\n","sub_path":"settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":846,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"323152293","text":"# -*- coding=utf-8 -*-\n\nfrom flask import Flask, send_from_directory, request, render_template, make_response\nfrom flask_restful import reqparse, abort, Api, Resource\nfrom flask_cors import CORS\n\nfrom routes.routes import route_list\n\n__api_path = '/api/'\n\napp = Flask(__name__, static_url_path='')\nCORS(app, supports_credentials=True, resources={r\"/api/*\": {\"origins\": \"*\"}})\n# app.register_blueprint(wwwroot_route, url_prefix='/')\n\napi = Api(app)\n\n\n@app.route('/upload/')\ndef send_file(path):\n return send_from_directory('upload', path)\n\nparser = reqparse.RequestParser()\n\nfor _route in route_list:\n # __path = '/' if _route.get('is_root') else '/api/'\n api.add_resource(_route['handler'], __api_path + _route['path'])\n\n\n\nif __name__ == '__main__':\n app.run()\n","sub_path":"api/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":784,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"501584394","text":"import cv2\nimport numpy as np\nimport argparse\nimport torch\nimport torchvision\nimport torchvision.transforms as transforms\n\nap = argparse.ArgumentParser()\nap.add_argument(\"-i\", \"--input\", required=True,\n help = \"input image file\")\nap.add_argument(\"-o\", \"--output\", required=True,\n help=\"output file\")\nap.add_argument(\"-l\", \"--labels\", required=True,\n help=\"labels file\")\nargs = vars(ap.parse_args())\n\n# read in the labels file and extract classes names\nrows = open('synset_words.txt').read().strip().split(\"\\n\")\nclasses = [r[r.find(\" \") + 1:].split(\",\")[0] for r in rows]\n\n#def transform_img(image):\nimage = Image.open(args[\"input\"])\npreprocess = transforms.Compose([\n transforms.Resize(256),\n transforms.CenterCrop(224),\n transforms.ToTensor(),\n transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),\n])\n\ninput_tensor = preprocess(image)\ninput_batch = input_tensor.unsqueeze(0)\n\n# Load the Model\n\nmobile_net = torchvision.models.mobilenet_v2(pretrained=True)\n\nif torch.cuda.is_available():\n input_batch = input_batch.to('cuda')\n mobile_net.to('cuda')\n\nwith torch.no_grad():\n start = time.time()\n mobile_net.eval()\n preds = mobile_net(input_batch)\n end = time.time()\n print(\"[INFO] classification time {:.5} seconds\".format(end - start))\n\n# convert the preds into probabilities\nprobs = torch.nn.functional.softmax(preds[0], dim=0)\n\nsort_probs, indices = torch.sort(probs, descending=True)\nsorted_probs = sort_probs[:5]\n\nfor i, idx in enumerate(sorted_probs):\n if i == 0:\n text = \"Label: {}, {:.2f}%\".format(classes[int(torch.argmax(probs))],\n int(sorted_probs[0] * 100))\n print(classes[int(torch.argmax(probs))])\n cv2.putText(image, text, (100,250), cv2.FONT_HERSHEY_SIMPLEX,\n\t\t\t0.7, (0, 0, 255), 2)\n prob = float(sorted_probs[0] * 100)\n\n print(\"[INFO] {}. label: {}, probability: {:.5}\".format(i+1, text, prob))\n\n\ncv2.imshow(\"image\", image)\ncv2.waitKey(0)\n","sub_path":"RaspberryPi/OpenCV/MobileNet_v2.py","file_name":"MobileNet_v2.py","file_ext":"py","file_size_in_byte":2000,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"455103589","text":"# Hospital appointment no-show prediction\n# Simple NN using TensorFlow\n# April 2019\n# Eduardo Moura Cirilo Rocha\n\nimport pandas as pd # load csv data\nimport numpy as np\nfrom sklearn.model_selection import train_test_split # split into training and test set\nfrom sklearn.model_selection import StratifiedKFold\nimport dataset as ds # load dataset\nimport NN_Sigmoid as nn # implementation of DecisionTree\nfrom sklearn.metrics import accuracy_score\n\n\nfrom no_show import Suppressor # supress std output\n\n#with Suppressor():\n\nnumModels = 20\n\n# load dataset\nnoShow = ds.import_data_df([ds._FILE_PATHS['merged']])\nnoShow_X, noShow_y = noShow.iloc[:, :-1].values, noShow.iloc[:, -1].values\nnoShow_y = np.array([[i] for i in noShow_y])\n\n# separate training and test set randomly keeping classes ratio\ntrain_X, testX, train_Y, testY = train_test_split(\n noShow_X, noShow_y, test_size=0.2, random_state=42,\n stratify = noShow_y\n)\n\n# number of features\nnumFeatures = train_X.shape[1]\n# number of classes\nnumLabels = train_Y.shape[1]\n\nNN = []\nfor i in range(numModels):\n\n # separate training in validation and training set\n trainX, valX, trainY, valY = train_test_split(\n train_X, train_Y, test_size=0.15, random_state=42,\n stratify = train_Y\n )\n\n # Hidden layers\n hiddenLayers = [10, 5] \n\n net = nn.NN_Sigmoid(\n hiddenLayers, numFeatures, numLabels, 0.05,\n cross_entropy_weight = 4,\n optimizer = \"Adam\"\n )\n\n # train\n net.train(\n 500, trainX, trainY, \n valX=valX, valY=valY, val_epochs=15, val_patience=10\n )\n\n NN.append(net)\n\n\npredictions = np.around(testY/1000)\nlabels = np.around(testY/1000)\nfor net in NN:\n p,_,_,_ = net.predict(\n testX, testY\n )\n l = np.around(p)\n predictions += p\n labels += l\n\npredictions = predictions/numModels\nlabels = labels/numModels\nprint(predictions)\nprint(labels)\n\n\nprint(accuracy_score(np.around(predictions), testY))\nprint(accuracy_score(np.around(labels), testY))\n\n\n\n","sub_path":"Code/Ensemble.py","file_name":"Ensemble.py","file_ext":"py","file_size_in_byte":1999,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"637489963","text":"import os\nimport pickle\nimport torch\nimport json\nfrom collections import defaultdict, OrderedDict\nimport random\nfrom tqdm import tqdm, trange\nfrom transformers import *\n\nclass PreprocessData_Ground(object):\n \"\"\"docstring for PreprocessData\"\"\"\n def __init__(self, data_name, gpt_tokenizer_type, context_len):\n super(PreprocessData_Ground, self).__init__()\n self.tokenizer = GPT2Tokenizer.from_pretrained(gpt_tokenizer_type, cache_dir='../cache/')\n data_dir = os.path.join('./data', data_name)\n self.ground_path = os.path.join(data_dir, 'ground_token_context{}_{}.pkl'.format(context_len, gpt_tokenizer_type))\n self.context_len = context_len\n\n self.tokenizer.add_tokens([''])\n self.tokenizer.add_tokens([''])\n self.tokenizer.add_tokens([''])\n self.PAD = self.tokenizer.convert_tokens_to_ids('')\n self.SEP = self.tokenizer.convert_tokens_to_ids('')\n self.END = self.tokenizer.convert_tokens_to_ids('')\n\n if not os.path.exists(self.ground_path):\n train_context_path = os.path.join(data_dir, 'grounded', 'train.grounded.jsonl')\n train_contexts = self.load_context(train_context_path)\n dev_context_path = os.path.join(data_dir, 'grounded', 'dev.grounded.jsonl')\n dev_contexts = self.load_context(dev_context_path)\n test_context_path = os.path.join(data_dir, 'grounded', 'test.grounded.jsonl')\n test_contexts = self.load_context(test_context_path)\n\n token_dataset = {}\n token_dataset['train'] = train_contexts\n token_dataset['dev'] = dev_contexts\n token_dataset['test'] = test_contexts\n\n with open(self.ground_path, 'wb') as handle:\n pickle.dump(token_dataset, handle, protocol=pickle.HIGHEST_PROTOCOL)\n\n def load_context(self, data_path):\n data_context = []\n question_context = []\n with open(data_path, 'r') as fr:\n for _id, line in enumerate(tqdm(fr)):\n obj = json.loads(line)\n qc_list = obj['qc']\n ac_list = obj['ac']\n choice_context = []\n\n choice = obj['ans'].replace('_', ' ')\n\n for qc in qc_list[:5]:\n qc = qc.replace('_', ' ')\n\n context = choice + '' + qc\n context = self.tokenizer.encode(context, add_special_tokens=False)[:self.context_len]\n context += [self.PAD] * (self.context_len - len(context))\n\n choice_context.append(context)\n num_context = len(choice_context)\n for _ in range(5 - num_context):\n _input = [self.PAD] * self.context_len\n choice_context.append(_input)\n question_context.append(choice_context)\n if (_id + 1) % 5 == 0:\n data_context.append(question_context)\n question_context = []\n data_context = torch.tensor(data_context, dtype=torch.long)\n return data_context \n\n","sub_path":"commonsense-qa/utils/preprocess_csqa.py","file_name":"preprocess_csqa.py","file_ext":"py","file_size_in_byte":3117,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"575042386","text":"from random import randint\n\nclass Node():\n \"\"\"implementation of a simple Node object\"\"\"\n def __init__(self,data=None,next=None):\n self.next = next\n self.data = data\n def __str__(self):\n return str(self.data)\n\n\nclass LinkedList():\n \"\"\"linked list implementation\"\"\"\n def __init__(self,lst=[]):\n self.head = None\n self.len = 0\n for n in reversed(lst):\n self.insert(n)\n\n def insert(self,data):\n self.head = Node(data,self.head)\n self.len += 1\n\n def populate(self,q=10, rng=16):\n while self.len < q:\n self.insert(randint(0,rng))\n\n def append(self,data):\n if self.head is None:\n self.head = Node(data)\n return\n end = Node(data)\n n = self.head\n while n.next is not None:\n n = n.next\n n.next = end\n self.len += 1\n\n def deleteNode(self,n):\n cn = self.head\n if not cn:\n return False\n while cn.next:\n if cn.next == n:\n cn.next = cn.next.next\n return True\n cn = cn.next\n return False\n\n def deleteNode_fast(self,n):\n if not n:\n return False\n if not n.next:\n return self.deleteNode(n)\n n.data = n.next.data\n n.next = n.next.next\n return True\n\n def mkunique(self):\n buffer = set()\n n = self.head\n if n:\n buffer.add(n.data)\n else:\n return\n while n.next:\n if n.next.data not in buffer:\n buffer.add(n.next.data)\n n = n.next\n else:\n n.next = n.next.next\n self.len -= 1\n\n def print_data(self):\n n=self.head\n while n:\n print(n.data,end=', ')\n n = n.next\n print(n)\n if not self.head:\n print(\"The list is empty.\")\n\n def __str__(self):\n l = []\n n=self.head\n while n:\n l.append(n.data)\n n = n.next\n return str(l)\n\n def __iter__(self):\n cur_node = self.head\n while cur_node:\n yield cur_node\n cur_node = cur_node.next\n\n def __len__(self):\n return self.len\n\n def deleteNodeByData(self, data):\n \"\"\" deletes the first occurance of node, containing from list \"\"\"\n if self.head.data == data:\n self.head = self.head.next\n return\n n = self.head\n while n.next is not None:\n if n.next.data == data:\n n.next = n.next.next\n return self\n n = n.next\n return\n","sub_path":"Chapter 3 - Stacks and Queues/linkedlist.py","file_name":"linkedlist.py","file_ext":"py","file_size_in_byte":2690,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"393304123","text":"import uuid\nimport random\n\n\nclass Link:\n\tdef __init__(self, origin_node, origin_gate, target_node, target_slot, weight=None): \n\t\tself.uid = uuid.uuid4()\n\t\tself.origin_node = origin_node\n\t\tself.origin_gate = origin_gate\n\t\tself.target_node = target_node\n\t\tself.target_slot = target_slot\n\n\t\t# OPTIMAL WEIGHT INITIALIZATION \n\n\t\t# 2 layers:\n\t\t# self.weight = weight if weight is not None else weight == 0\n\n\t\t# 3+ layers:\n\t\tself.weight = weight if weight is not None else random.uniform(-.25, .25)\n","sub_path":"nodenet/link.py","file_name":"link.py","file_ext":"py","file_size_in_byte":493,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"640342871","text":"\nimport numpy as np\n#import scipy\n#import matcompat\n#import matplotlib.pylab as plt\nfrom consts import EPS\nfrom range_shuffle import range_shuffle\nfrom probr import probr\nfrom probqr import probqr\nfrom range_frac import range_frac\n\ndef xiq(spk, nt, q, biastype):\n assert biastype<=1\n\n # Local Variables: h44, p43q, h41, biastype, h2, h0, p22, h4, r44, bias, r41, h42, r43, r42, p44, p43, r22, p41, out, p21q, h22, p41q, h21, p42, rg, r21, ntrg, nt, p42q, p22q, L, p21r, pqq, h43, hc0, g, ntr4, j, ntr2, p44q, q, p, _srange0, spk, p21, p21i\n # Function calls: range_shuffle, rand, log2, lagrange2, floor, sum, lagrange3, eps, xiq, range_frac, probqr, probr, size\n #%This function estimates xiq of a set of trials\n #%The result is given in bits\n #%The estimator implemented is chosen by biastype:\n #%Bias correction\n #%0: direct\n #%1= cuadratic extrap\n #%2= naive NOT IMPLEMENTED\n #%3= Panzeri NOT IMPLEMENTED\n #%4= Montemurro NOT IMPLEMENTED\n #%5= Nemenman NOT IMPLEMENTED\n #L = matcompat.size(spk, 2.)\n #%ntr=size(spk,3);\n #%_srange0=[1:ntr];\n\n L=spk.shape[1]\n _srange0 = range_shuffle(nt)\n #%M=1+max(reshape(spk,1,[]));\n p = probr(spk, nt, _srange0, 1)\n pqq = probqr(spk, nt, _srange0, q, 1)\n bias = 0.\n if biastype >= 1:\n bias = 1\n if biastype == 8:\n bias = 8 #correct\n \n \n #%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n #%Direct estimation\n #%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n hc0 = -np.sum((p*np.log2((pqq+EPS))))\n _switch_val=bias\n if _switch_val == 0:\n bias = 0.\n h0 = hc0\n elif _switch_val == 1:\n #%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n #%This is the 3 point extrapolation taking 1/4, 1/2 and 1/1 of the trials\n #%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n _srange0 = range_shuffle(nt)\n ntr2 = np.floor((np.sum(nt)/2.))\n ntr4 = np.floor((np.sum(nt)/4.))\n r21 = range_frac(_srange0, nt, 2., 1.)\n r22 = range_frac(_srange0, nt, 2., 2.)\n r41 = range_frac(_srange0, nt, 4., 1.)\n r42 = range_frac(_srange0, nt, 4., 2.)\n r43 = range_frac(_srange0, nt, 4., 3.)\n r44 = range_frac(_srange0, nt, 4., 4.)\n p21 = probr(spk, nt, r21, 2.)\n p22 = probr(spk, nt, r22, 2.)\n p41 = probr(spk, nt, r41, 4.)\n p42 = probr(spk, nt, r42, 4.)\n p43 = probr(spk, nt, r43, 4.)\n p44 = probr(spk, nt, r44, 4.)\n p21q = probqr(spk, nt, r21, q, 2.)\n p22q = probqr(spk, nt, r22, q, 2.)\n p41q = probqr(spk, nt, r41, q, 4.)\n p42q = probqr(spk, nt, r42, q, 4.)\n p43q = probqr(spk, nt, r43, q, 4.)\n p44q = probqr(spk, nt, r44, q, 4.)\n h21 = -np.sum((p21*np.log2((p21q+EPS))))\n h22 = -np.sum((p22*np.log2((p22q+EPS))))\n h41 = -np.sum((p41*np.log2((p41q+EPS))))\n h42 = -np.sum((p42*np.log2((p42q+EPS))))\n h43 = -np.sum((p43*np.log2((p43q+EPS))))\n h44 = -np.sum((p44*np.log2((p44q+EPS))))\n h4 = (h41+h42+h43+h44)/4.\n h2 = (h21+h22)/2.\n #%h0=(8*hc0-6*h2+h4)/3; %parabolic extrapolation\n #%h0=(-h2*ntr2^2*(ntr-ntr4)+h4*ntr4^2*(ntr-ntr4)+hd*ntr^2*(ntr2-ntr4))/((ntr-ntr2)*(ntr-ntr4)*(ntr2-ntr4));\n h0 = lagrange3(np.array(np.hstack((1./ntr4, 1./ntr2, 1./np.sum(nt)))), np.array(np.hstack((h4, h2, hc0))), 0.)\n #%hst=(4*hd-h21-h22)/2; %linear extrapolation\n elif _switch_val == 2.:\n #%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n #%Naive correction\n #%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n h0 = 0.\n elif _switch_val == 3.:\n #%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n #%Panzeri\n #%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n h0 = 0.\n elif _switch_val == 4.:\n #%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n #%Montemurro\n #%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n h0 = 0.\n elif _switch_val == 5.:\n #%first recover absolute freqs\n h0 = 0.\n elif _switch_val == 7.:\n _srange0 = range_shuffle(nt)\n g = 5.\n ntrg = nt[0]-1.\n h21 = 0.\n for j in np.arange(1., (g)+1):\n out = np.floor(np.dot(nt[0], np.random.rand(1., 1.)))+1.\n rg = _srange0\n rg[:,int(out)-1] = np.array([])\n p21r = probr(spk, (nt-1.), rg, 1.)\n p21i = probqr(spk, (nt-1.), rg, q, 1.)\n h21 = h21-np.sum((p21r*np.log2((p21i+EPS))))\n \n h21 = matdiv(h21, g)\n h0 = lagrange2(np.array(np.hstack((1./ntrg, 1./nt[0]))), np.array(np.hstack((h21, hc0))), 0.)\n elif _switch_val == 8.:\n _srange0 = range_shuffle(nt)\n ntr2 = np.floor((np.sum(nt)/2.))\n r21 = range_frac(_srange0, nt, 2., 1.)\n r22 = range_frac(_srange0, nt, 2., 2.)\n p21 = probr(spk, nt, r21, 2.)\n p22 = probr(spk, nt, r22, 2.)\n p21q = probqr(spk, nt, r21, q, 2.)\n p22q = probqr(spk, nt, r22, q, 2.)\n h21 = -np.sum((p21*np.log2((p21q+EPS))))\n h22 = -np.sum((p22*np.log2((p22q+EPS))))\n h2 = (h21+h22)/2.\n #%h0=(8*hc0-6*h2+h4)/3; %parabolic extrapolation\n #%h0=(-h2*ntr2^2*(ntr-ntr4)+h4*ntr4^2*(ntr-ntr4)+hd*ntr^2*(ntr2-ntr4))/((ntr-ntr2)*(ntr-ntr4)*(ntr2-ntr4));\n h0 = lagrange2(np.array(np.hstack((1./ntr2, 1./np.sum(nt)))), np.array(np.hstack((h2, hc0))), 0.)\n \n #%error estimation, Latham's\n #%N=ntr;\n #%err=sqrt((sum(p.*log2(p+eps).^2)-(hd*L)^2)/(L*N));\n return h0","sub_path":"incubator/xiq.py","file_name":"xiq.py","file_ext":"py","file_size_in_byte":5794,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"296405546","text":"import os\nimport re\nimport csv\nimport urllib.request\nimport time\nfrom multiprocessing import Pool\nfrom functools import reduce\n\ndef download_from_csv(file_name):\n file_name = \"./agg/\"+file_name\n print(\"file \"+file_name+\" loaded\")\n with open(file_name, newline='') as csvfile:\n \n spamreader = csv.reader(csvfile, delimiter=',', quotechar='|')\n #print (spamreader.line_num)\n download_count=0\n failed_count=0\n\n for row in spamreader:\n if int(row[3])>=3:\n name = row[1].split('/')[-1]\n location = './images/'+row[0]+'/'+name\n if os.path.exists(location):\n #print(name+\" already exist\")\n continue\n try:\n urllib.request.urlretrieve(row[1], location)\n #print(name+\" downloaded\")\n download_count+=1\n except:\n #print(name+\" can not be downloaded\")\n failed_count+=1\n print(\"file %s, downloaded %d, failed %d\"%(file_name,download_count,failed_count))\n return (download_count,failed_count)\n\nif __name__ ==\"__main__\":\n #create folder\n types=['amusement', 'fear', 'anger', 'awe','contentment','disgust','sadness','excitement']\n for folder in types:\n if not os.path.exists('./images/'+folder):\n os.makedirs('./images/'+folder)\n\n #find all csv and call download method\n files=(os.listdir(\"./agg\"))\n r = re.compile(r\"\"\".*csv\"\"\")\n csv_files=(list(filter(r.match, files)))\n p=Pool(4)\n counts=p.map(download_from_csv, csv_files)\n\n #for file in csv_files:\n # download_from_csv(file)","sub_path":"data/download_you/download_images.py","file_name":"download_images.py","file_ext":"py","file_size_in_byte":1699,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"425660666","text":"#!/usr/bin/env python\n\"\"\"Functions that handle a processing framework execution event.\n\"\"\"\n\nimport os\nimport time\n\n\ndef get_timestamp():\n \"\"\"Create timestamp in a particular format.\n \"\"\"\n tstamp = time.strftime(\"%m/%d/%Y %H:%M:%S\", time.localtime())\n return tstamp\n\n\ndef log_pfw_event(config, block=None, subblock=None,\n subblocktype=None, info=None):\n \"\"\"Write info for a PFW event to a log file.\n \"\"\"\n if block:\n block = block.replace('\"', '')\n else:\n block = ''\n\n if subblock:\n subblock = subblock.replace('\"', '')\n else:\n subblock = ''\n\n if subblocktype:\n subblocktype = subblocktype.replace('\"', '')\n else:\n subblocktype = ''\n\n runsite = config.getfull('run_site')\n run = config.getfull('submit_run')\n logdir = config.getfull('uberctrl_dir')\n\n dagid = os.getenv('CONDOR_ID')\n if not dagid:\n dagid = 0\n\n deslogfh = open(\"%s/%s.deslog\" % (logdir, run), \"a\")\n deslogfh.write(\"%s %s %s %s %s %s %s\" % (get_timestamp(), dagid, run,\n runsite, block, subblocktype, subblock))\n if isinstance(info, list):\n for col in info:\n deslogfh.write(\",%s\" % col)\n else:\n deslogfh.write(\",%s\" % info)\n\n deslogfh.write(\"\\n\")\n deslogfh.close()\n","sub_path":"python/processingfw/pfwlog.py","file_name":"pfwlog.py","file_ext":"py","file_size_in_byte":1331,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"596263119","text":"import json\nfrom utils.load_config import load_configuration\nfrom datetime import datetime\nfrom utils.api_call import get_details\n\ntoday = datetime.now()\nprint(f\"New job started at {today}\")\nstart_date = today.strftime(\"%d-%m-%Y\")\nconfig = load_configuration(config_path=\"data/config.yml\")\nget_slot_by_district = config.get(\"COWIN\").get(\"SLOT_BY_DISTICT\")\nget_slot_by_pin = config.get(\"COWIN\").get(\"SLOT_BY_PINCODE\")\ndata = json.load(open(\"data/user_data.json\", \"r\"))\nfor user in data[\"user_data\"].items():\n chat_id = user[1].get(\"chat_id\")\n dist_list = user[1].get(\"districts\")\n age_group = user[1].get(\"age_groups\")\n print(chat_id, dist_list, age_group)\n for district_id in dist_list:\n get_details(district_id, start_date, age_group, chat_id)\n","sub_path":"cowin_bot/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":767,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"293507258","text":"import numpy as np\n\n\nclass MALAGaussian:\n def __init__(self, mu, sigma, N, eps, prior_mu, prior_sigma):\n self.eps = eps\n self.dataset = np.random.normal(loc=mu, scale=sigma, size=N)\n self.prior_mu = prior_mu\n self.prior_sigma = prior_sigma\n\n def log_q(self, mu1, sigma1, mu2, sigma2):\n N = len(self.dataset)\n m_1 = np.sum(self.dataset - mu2)\n m_2 = np.sum(np.power((self.dataset - mu2), 2))\n eps = self.eps\n\n theta = np.array([mu1, sigma1])\n\n mu = np.array(\n [mu2 + eps ** 2 * m_1 * 0.5 / sigma2 ** 2,\n sigma2 + eps ** 2 * 0.5 * m_2 / sigma2 ** 3 - 0.5 * eps ** 2 * N / sigma2])\n return -0.5 / eps ** 2 * (theta - mu).T.dot(theta - mu)\n\n def acceptation_rate(self, mu, sigma, new_mu, new_sigma):\n prior_ratio = np.exp(-0.5 * ((new_mu - self.prior_mu) ** 2 - (mu - self.prior_mu) ** 2) +\n -0.5 * ((new_sigma - self.prior_sigma) ** 2 - (sigma - self.prior_sigma) ** 2))\n jump_ratio = np.exp(self.log_q(mu, sigma, new_mu, new_sigma) - self.log_q(new_mu, new_sigma, mu, sigma))\n return min(1, prior_ratio * jump_ratio)\n\n def iteration(self, mu, sigma):\n N = len(self.dataset)\n m_1 = np.sum(self.dataset - mu)\n m_2 = np.sum(np.power((self.dataset - mu), 2))\n z = np.random.normal()\n w = np.random.normal()\n eps = self.eps\n\n new_mu = mu + eps ** 2 * m_1 / (2 * sigma ** 2) + eps * z\n new_sigma = sigma + 0.5 * eps ** 2 * m_2 / sigma ** 3 - 0.5 * N * eps ** 2 / sigma + eps * w\n\n u = np.random.rand()\n alpha = self.acceptation_rate(mu, sigma, new_mu, new_sigma)\n if u > alpha:\n new_mu = mu\n new_sigma = sigma\n return new_mu, new_sigma, alpha\n\n def run(self, nb_iter, mu_0, sigma_0):\n mu_estimation = mu_0\n sigma_estimation = sigma_0\n\n theta_over_time = np.zeros((nb_iter + 1, 2))\n theta_over_time[0] = mu_estimation, sigma_estimation\n\n alpha_over_time = np.zeros(nb_iter + 1)\n\n for i in range(nb_iter):\n mu_estimation, sigma_estimation, alpha_over_time[i + 1] = self.iteration(mu_estimation,\n sigma_estimation)\n theta_over_time[i + 1] = mu_estimation, sigma_estimation\n return theta_over_time, alpha_over_time\n","sub_path":"MALAGaussian.py","file_name":"MALAGaussian.py","file_ext":"py","file_size_in_byte":2428,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"552200876","text":"# wzór na długość wektora\r\n# u = abs(sqrt(x**2 + y**2))\r\n\r\nt = float(input(\"Czas:\"))\r\nx = 3\r\ny = 2\r\nfrom math import sqrt\r\nv = sqrt(x**2 + y**2)\r\nv = abs(v)\r\ns = v*t\r\nif t <= 100:\r\n print(\"Jasiek przeszedł %s metrów\" %s)\r\nelse:\r\n print(\"Jasiek przeszedł całą drogę\")\r\n","sub_path":"J.Karasek/Zadanie_7_Jasiek_2.py","file_name":"Zadanie_7_Jasiek_2.py","file_ext":"py","file_size_in_byte":282,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"165891190","text":"import pygame\nimport os\nfrom sys import exit\nfrom constants import *\nfrom menu import Menu\nfrom game_process import GameProcess\nfrom table_records import TableRecords\nfrom scene import Scene\nfrom load_levels import LoadLevels\nfrom control import Control\n\n\nclass Game:\n def __init__(self):\n pygame.mixer.music.play(-1)\n self.screen = pygame.display.set_mode(SIZE)\n self.close_app = False\n self.scene = Menu()\n self.scenes = {proceed_game_single: GameProcess, proceed_game_double: GameProcess,\n proceed_table_records: TableRecords, proceed_close_app: Exit, proceed_menu: Menu,\n proceed_levels: LoadLevels, proceed_control: Control}\n\n def main_loop(self):\n while not self.close_app:\n self.process_events()\n self.process_logic()\n self.process_drawing()\n pygame.time.wait(FPS)\n\n def process_events(self):\n for event in pygame.event.get():\n self.scene.process_events(event)\n if event.type == pygame.QUIT:\n self.close_app = True\n\n def process_logic(self):\n if self.scene.next_scene is not None:\n if proceed_game_single in self.scene.next_scene:\n self.scene = self.scenes[proceed_game_single](1, int(self.scene.next_scene[-1]))\n elif proceed_game_double in self.scene.next_scene:\n self.scene = self.scenes[proceed_game_single](2, int(self.scene.next_scene[-1]))\n else:\n self.scene = self.scenes[self.scene.next_scene]()\n self.scene.process_logic()\n\n def process_drawing(self):\n self.screen.fill((62, 58, 97))\n self.scene.draw(self.screen)\n pygame.display.flip()\n\n\nclass Exit(Scene):\n\n def process_logic(self):\n exit()\n","sub_path":"pacman/game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":1822,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"22712844","text":"from collections import defaultdict\n\n\n# Function reads a file from given path, format: see get_input_data(),\n# and returns dictionary and list of prefixes\ndef get_input_data_from_file(path_to_file):\n dictionary = []\n with open(path_to_file, 'r', encoding='utf-8') as f:\n for line in f:\n items = line.strip().split()\n if len(items) > 1:\n dictionary.append((items[0], int(items[1])))\n return dictionary\n\n\n# function reads input data from stdin,\n# in following format:\n# N - number of words\n# word freq\n# ...\n# N lines\n# ...\n# M - number of prefixes\n# prefix\n# ...\n# M lines\n# ...\n# and returns dictionary and list of prefixes\ndef get_input_data():\n dictionary = []\n prefixes = []\n number_of_words = int(input())\n for index in range(number_of_words):\n line = input()\n items = line.strip().split()\n dictionary.append((items[0], int(items[1])))\n number_of_prefixes = int(input())\n for index in range(number_of_prefixes):\n line = input()\n prefixes.append(line.strip())\n return dictionary, prefixes\n\n\n#\nclass SuggestionGenerator():\n \"\"\"\n SuggestionGenerator suggests a top 10 most used word for incoming prefix.\n \"\"\"\n def __init__(self, dictionary, max_len=10):\n self.shards = defaultdict(lambda: defaultdict(dict))\n self.cache = defaultdict(list)\n for word, freq in dictionary:\n if len(word) > 1:\n self.shards[word[0]][word[1:2]][word] = freq\n self.cache[word[0]].append((word, freq))\n for single_letter_word, word_info in self.cache.items():\n # sort first by freq in descending order then by lexicographical order\n word_info.sort(key=lambda word_info: (-word_info[1], word_info[0]))\n self.cache[single_letter_word] = word_info[:max_len]\n top_overall = []\n for single_letter_word, word_info in self.cache.items():\n top_overall.extend(word_info)\n top_overall.sort(key=lambda word_info: (-word_info[1], word_info[0]))\n self.cache[''] = top_overall[:max_len]\n\n def generate_suggestions(self, prefix, max_len=10):\n # there is no need to seek if prefix already in dict\n if prefix in self.cache:\n return self.cache[prefix]\n suggestions = []\n if prefix[:1] not in self.shards or \\\n prefix[1:2] not in self.shards[prefix[:1]]:\n return []\n for word, freq in self.shards[prefix[:1]][prefix[1:2]].items():\n if word.startswith(prefix):\n suggestions.append((word, freq))\n suggestions.sort(key=lambda word_info: (-word_info[1], word_info[0]))\n self.cache[prefix] = suggestions[:max_len]\n return self.cache[prefix]\n\n\nif __name__ == '__main__':\n dictionary, prefixes = get_input_data()\n suggestions_generator = SuggestionGenerator(dictionary)\n for prefix in prefixes:\n for word_info in suggestions_generator.generate_suggestions(prefix):\n print(word_info[0])\n print('')\n","sub_path":"generate_suggestions.py","file_name":"generate_suggestions.py","file_ext":"py","file_size_in_byte":3077,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"583644932","text":"import config\nimport os\n\nfrom flask import Flask\nfrom flask import jsonify, make_response\nfrom flask_graphql import GraphQLView\n\nimport graphene\n\napp = Flask(__name__)\n\nclass Company(graphene.ObjectType):\n name = graphene.String()\n review = graphene.Int()\n\nclass FlaskInfo(graphene.ObjectType):\n flask_env = graphene.String()\n mode = graphene.String()\n debug_mode = graphene.Int()\n\nclass Demo(graphene.ObjectType):\n hello = graphene.String(description='Hello world...')\n\n def resolve_hello(self, info):\n return 'World'\n\n company = graphene.Field(Company, description='Company info')\n\n def resolve_company(root, info):\n return Company(name=\"JacksonLabs\", review=5)\n \n flask_info = graphene.Field(FlaskInfo, description='Flask server info')\n\n def resolve_flask_info(root, info):\n return FlaskInfo(\n flask_env = os.environ['FLASK_ENV'],\n mode = os.environ['MODE'],\n debug_mode = os.environ['DEBUG_MODE'],\n )\n\nschema = graphene.Schema(query=Demo, auto_camelcase=False)\n\napp.add_url_rule(\n '/graphql',\n view_func=GraphQLView.as_view(\n 'graphql',\n schema=schema,\n graphiql=True\n )\n)\n\n@app.route('/')\ndef hello():\n print(\"Hello World\")\n return \"Hello World\"\n\n@app.route('/env')\ndef environment():\n data = {\n \"FLASK_ENV\": os.environ['FLASK_ENV'],\n \"MODE\": os.environ['MODE'],\n \"DEBUG_MODE\": os.environ['DEBUG_MODE'],\n }\n return make_response(jsonify(data), 200)\n\nif __name__ == '__main__':\n app.run()\n","sub_path":"flask-app/app/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1559,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"409239734","text":"class Persona(object):\n \"\"\"Clase que representa una Persona\"\"\"\n\n def __init__(self, cedula, nombre, apellido, sexo):\n \"\"\"Constructor de clase Persona\"\"\"\n self.cedula = cedula\n self.nombre = nombre\n self.apellido = apellido\n self.sexo = sexo\n\n def __str__(self):\n \"\"\"Devuelve una cadena representativa de Persona\"\"\"\n return \"%s: %s, %s %s, %s.\" % (\n self.__doc__[25:34], str(self.cedula), self.nombre, \n self.apellido, self.getGenero(self.sexo))\n\n def hablar(self, mensaje):\n \"\"\"Mostrar mensaje de saludo de Persona\"\"\"\n return mensaje\n\n def getGenero(self, sexo):\n \"\"\"Mostrar el genero de la Persona\"\"\"\n genero = ('Masculino','Femenino')\n if sexo == \"M\":\n return genero[0]\n elif sexo == \"F\":\n return genero[1]\n else:\n return \"Desconocido\"","sub_path":"herency.py","file_name":"herency.py","file_ext":"py","file_size_in_byte":905,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"36327798","text":"from django.http import HttpResponse, HttpResponseRedirect\nfrom django.shortcuts import render, get_object_or_404\nfrom django.urls import reverse\nimport os\nimport markovify\n\nfrom .forms import PoetryForm\n\n\ndata = open('corpora/christmas.txt',encoding=\"utf8\").read()\ncorpus = data.lower().split(\"\\n\")\n\n\n# Create your views here.\ndef index(request):\n return render(request, 'index.html')\n\n\ndef generate(request):\n print('You have reached me')\n\n if request.method == 'POST':\n form = PoetryForm(request.POST)\n\n if form.is_valid():\n return HttpResponseRedirect('/poetry', {'form': form})\n\n # If no entry we just assume some default values\n form = PoetryForm()\n form.poetry_seed = 'Yonder window breaks'\n form.n_words = 60\n\n # model here\n text_model = markovify.NewlineText(corpus)\n poem = make_song(text_model)\n\n\n\n return render(request, 'poetry.html', {'poem': poem})\n # return HttpResponseRedirect('/poetry', {'form': form})\n\n\ndef poetry(request):\n print(\"poetry function\")\n\n # poetry_seed = request.poetry_seed\n # n_words = request.n_words\n # print(poetry_seed, n_words)\n\n return render(request, 'poetry.html')\n\n\ndef make_stanza(lyrics_generator):\n stanza = []\n for _ in range(4):\n while True:\n line = lyrics_generator.make_sentence()\n if line is not None:\n stanza.append(line)\n stanza.append(\"\\n\")\n break\n return stanza\n\ndef make_song(lyrics_generator):\n chorus = make_stanza(lyrics_generator)\n\n song = [make_stanza(lyrics_generator), \"\\n\",\n ['CHORUS:'], chorus, \"\\n\",\n make_stanza(lyrics_generator), \"\\n\",\n ['CHORUS:'], chorus, \"\\n\",\n make_stanza(lyrics_generator)]\n\n flat_song = [item for sublist in song for item in sublist]\n return flat_song #os.linesep.join(song)","sub_path":"psite/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1883,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"508379390","text":"# author:joketeng time:2018/10/31\r\nimport os\r\nimport requests\r\nfrom tkinter import *\r\nimport re\r\nfrom tkinter import messagebox\r\nfrom time import *\r\n\r\n\r\nclass kugou(object):\r\n def __init__(self):\r\n self.headers = {\r\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.26 Safari/537.36 Core/1.63.6726.400 QQBrowser/10.2.2265.400'\r\n }\r\n self.search_url = 'http://songsearch.kugou.com/song_search_v2?keyword={}&page=1&pagesize=30'\r\n self.hash_url = 'http://www.kugou.com/yy/index.php?r=play/getdata&hash={}'\r\n\r\n def get(self, songname, downnum, savepath):\r\n download_names, download_urls = self.search_songname(songname, downnum)\r\n res = self.download_demo(download_names, download_urls, savepath)\r\n return res\r\n\r\n # 控制台下载音乐\r\n def download_demo(self, download_names, download_urls, savepath):\r\n if not os.path.exists(savepath):\r\n os.mkdir(savepath)\r\n res = ''\r\n for i in range(len(download_urls)):\r\n # 去除歌曲名存在的字符\r\n download_name = download_names[i].replace(\"<\\\\/em>\", \"\").replace(\"\", \"\").replace('\\\\', '').replace('/',\r\n '').replace( \" \", \"\").replace('.', '')\r\n download_url = download_urls[i]\r\n # 保存名\r\n savename = 'kugou_{}_{}.mp3'.format(str(i), download_name)\r\n try:\r\n r = requests.get(download_url, timeout=15, headers=self.headers)\r\n with open(savepath+savename, \"wb\") as code:\r\n code.write(r.content)\r\n res += \"下载\"+savename+\"成功\\n\"\r\n except:\r\n pass\r\n return res\r\n\r\n # 获得mp3的下载地址以及���曲名\r\n def search_songname(self, songname, songnum):\r\n res = requests.get(self.search_url.format(songname), headers=self.headers)\r\n filehashs = re.findall('\"FileHash\":\"(.*?)\"', res.text)\r\n temp_name = re.findall('\"SongName\":\"(.*?)\"', res.text)\r\n download_names = []\r\n download_urls = []\r\n for filehash in filehashs:\r\n if len(download_urls) == songnum:\r\n break\r\n res = requests.get(self.hash_url.format(filehash))\r\n paly_url = re.findall('\"play_url\":\"(.*?)\"', res.text)[0]\r\n # print(paly_url)\r\n download_url = paly_url.replace(\"\\\\\", \"\")\r\n # print(download_url)\r\n download_names.append(temp_name[len(download_urls)])\r\n download_urls.append(download_url)\r\n return download_names, download_urls\r\n\r\n\r\nclass kuwo(object):\r\n def __init__(self):\r\n self.headers = {\r\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36'\r\n }\r\n self.search_url = \"http://sou.kuwo.cn/ws/NSearch?type=all&catalog=yueku2016&key={}\"\r\n self.music_url = \"http://antiserver.kuwo.cn/anti.s?format=aac|mp3&rid=MUSIC_{}&type=convert_url&response=res\"\r\n\r\n def search_music(self, songname, songnum):\r\n res = requests.get(self.search_url.format(songname), headers=self.headers)\r\n songinfos = re.findall(' ', res.text)\r\n download_urls = []\r\n download_names = []\r\n for songinfo in songinfos:\r\n if len(download_urls) == songnum:\r\n break\r\n download_url = self.music_url.format(songinfo[0])\r\n download_names.append(songinfo[1])\r\n download_urls.append(download_url)\r\n return download_urls, download_names\r\n\r\n def get(self, songname, songnum, savepath):\r\n download_urls, dowmload_names = self.search_music(songname, songnum)\r\n res = self.demo_download(download_urls, dowmload_names, savepath)\r\n return res\r\n\r\n def demo_download(self, songurls, songnames, savepath ):\r\n # 地址不存在则创建\r\n if not os.path.exists(savepath):\r\n os.mkdir(savepath)\r\n res = ''\r\n for i in range(len(songurls)):\r\n download_name = songnames[i]\r\n download_url = songurls[i]\r\n savename = 'kuwo_{}_{}.mp3'.format(str(i), download_name)\r\n try:\r\n req = requests.get(download_url, headers=self.headers)\r\n with open(savepath+savename, 'wb') as music:\r\n music.write(req.content)\r\n res += \"下载\" + savename + \"成功\\n\"\r\n except:\r\n pass\r\n return res\r\n\r\n\r\nclass qq(object):\r\n def __init__(self):\r\n self.headers = {\r\n 'user - agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36'\r\n }\r\n self.search_url = 'https://c.y.qq.com/soso/fcgi-bin/client_search_cp?ct=24&qqmusic_ver=1298&new_json=1&remoteplace=txt.yqq.top&searchid=34725291680541638&t=0&aggr=1&cr=1&catZhida=1&lossless=0&flag_qc=0&p=1&n=20&w={}'\r\n self.songfcg = 'https://c.y.qq.com/base/fcgi-bin/fcg_music_express_mobile3.fcg?g_tk=5381&jsonpCallback=MusicJsonCallback9239412173137234&loginUin=0&hostUin=0&format=json&inCharset=utf8&outCharset=utf-8¬ice=0&platform=yqq&needNewCode=0&cid=205361747&callback=MusicJsonCallback9239412173137234&uin=0&songmid={}&filename={}.m4a&guid=8208467632'\r\n self.music_url = 'http://dl.stream.qqmusic.qq.com/{}.m4a?vkey={}&guid=8208467632&uin=0&fromtag=66'\r\n\r\n def search_music(self, songnames, songnums):\r\n req = requests.get(self.search_url.format(songnames), headers=self.headers)\r\n req.encoding = 'utf-8'\r\n items = re.findall('\"media_mid\":\"(.*?)\"', req.text)\r\n media_mids = []\r\n for i in range(len(items)):\r\n media_mids.append('C400'+items[i])\r\n # 歌曲 mid 正则表达式要定位正确......含有多种mid,要明确\r\n song_ids = re.findall('\"lyric_hilight\":\".*?\",\"mid\":\"(.*?)\",\"mv\"', req.text)\r\n song_names = re.findall('},\"name\":\"(.*?)\",\"newStatus\"', req.text)\r\n download_urls = []\r\n download_names = []\r\n for i in range(len(media_mids)):\r\n if len(download_urls) == songnums:\r\n break\r\n res = requests.get(self.songfcg.format(song_ids[i], media_mids[i]), headers=self.headers)\r\n vkey = re.findall('\"vkey\":\"(.*?)\"', res.text)[0]\r\n music = self.music_url.format(media_mids[i], vkey)\r\n download_names.append(song_names[i])\r\n download_urls.append(music)\r\n return download_urls, download_names\r\n\r\n def get(self, songname, songnum, savepath, lb_detailtext):\r\n download_urls, download_names = self.search_music(songname, songnum)\r\n success, fail = self.download_demo(download_urls, download_names, savepath, lb_detailtext)\r\n return success, fail\r\n\r\n def download_demo(self, download_urls, download_names, savepath, lb_detailtext):\r\n if not os.path.exists(savepath):\r\n os.mkdir(savepath)\r\n success = 0\r\n fail = 0\r\n for i in range(len(download_urls)):\r\n res = requests.get(download_urls[i], headers=self.headers)\r\n total_size = int(res.headers['content-length'])\r\n if total_size < 1024:\r\n fail += 1\r\n continue\r\n savename = 'qq_{}_{}.mp3'.format(str(i-fail), download_names[i])\r\n try:\r\n with open(savepath+savename, 'wb') as music:\r\n music.write(res.content)\r\n success += 1\r\n lb_detailtext.insert(END, \"下载\"+savename+\"成功\\n\")\r\n lb_detailtext.see(END)\r\n lb_detailtext.update()\r\n except:\r\n pass\r\n return success, fail\r\n\r\n\r\ndef show_author():\r\n title = '关于作者'\r\n message = '作者:joketeng\\nqq:907763566 网址:https://github.com/joketeng'\r\n messagebox.showinfo(title, message)\r\n\r\n\r\ndef stopDemo(root):\r\n root.quit()\r\n root.destroy()\r\n\r\n\r\nclass download(object):\r\n def __init__(self):\r\n self.engine = None\r\n self.songname = None\r\n self.songnum = 0\r\n self.link = './results'\r\n\r\n def run(self, lb_detailtext):\r\n if self.engine == \"qq音乐\":\r\n try:\r\n success, fail = qq().get(self.songname, self.songnum, self.link, lb_detailtext)\r\n lb_detailtext.insert(END, \"共下载成功\" + str(success) + \"首\\n\")\r\n lb_detailtext.insert(END, \"共下载失败\" + str(fail) + \"首\\n\")\r\n lb_detailtext.see(END)\r\n lb_detailtext.update()\r\n except:\r\n title = \"错误\"\r\n meg = \"无音乐资源,请重新输入\"\r\n messagebox.showinfo(title, meg)\r\n if self.engine == \"酷我音乐\":\r\n try:\r\n success = kuwo().get(self.songname, self.songnum, self.link)\r\n lb_detailtext.insert(END, success)\r\n except:\r\n title = \"错误\"\r\n meg = \"无音乐资源,请重新输入\"\r\n messagebox.showinfo(title, meg)\r\n if self.engine == \"酷狗音乐\":\r\n try:\r\n success = kugou().get(self.songname, self.songnum, self.link)\r\n lb_detailtext.insert(END, success)\r\n except:\r\n title = \"错误\"\r\n meg = \"无音乐资源,请重新输入\"\r\n messagebox.showinfo(title, meg)\r\n\r\n\r\n# 开启下载\r\nstart_download = download()\r\n\r\n\r\ndef downloader(op_engine_var, lb_name_var, lb_num_var, lb_link_var, lb_detailtext):\r\n try:\r\n engine = str(op_engine_var.get())\r\n songname = str(lb_name_var.get())\r\n songnum = int(lb_num_var.get())\r\n songlink = str(lb_link_var.get())\r\n except:\r\n title = '输入错误'\r\n msg = '歌曲名或歌曲下载数量输入错误!'\r\n messagebox.showerror(title, msg)\r\n return None\r\n start_download.engine = engine\r\n start_download.songname = songname\r\n start_download.songnum = songnum\r\n start_download.link = songlink\r\n start_download.run(lb_detailtext)\r\n\r\n\r\ndef Demo(options):\r\n assert len(options) > 1\r\n # 初始化TK()\r\n root = Tk()\r\n # 设置标题\r\n root.title('皮新')\r\n # 设置窗口大小\r\n root.geometry('480x360+500+300')\r\n # 设置长宽是否可变\r\n # root.resizable(width=False, height=True)\r\n # menu 导航菜单\r\n menubar = Menu(root)\r\n filemenu = Menu(menubar, tearoff=False)\r\n menubar.add_cascade(label='选项', menu=filemenu)\r\n filemenu.add_command(label=\"退出\", command=lambda: stopDemo(root))\r\n filemenu = Menu(menubar, tearoff=False)\r\n menubar.add_cascade(label='更多', menu=filemenu)\r\n filemenu.add_command(label=\"关于作者\", command=show_author)\r\n root.config(menu=menubar)\r\n # 主界面\r\n # 标头\r\n lb_title = Label(root, text=\"音乐下载器\")\r\n lb_title.place(relx=0.1, rely=0.05, anchor=CENTER)\r\n # 音乐源的选择\r\n option = []\r\n for i in options.values():\r\n option.append(i)\r\n lb_show = Label(root, text='音乐源列表')\r\n # relx rely为x,y轴的位置\r\n lb_show.place(relx=0.1, rely=0.15, anchor=CENTER)\r\n op_engine_var = StringVar()\r\n op_engine_var.set(options[1])\r\n op_engine = OptionMenu(root, op_engine_var, *option)\r\n op_engine.place(relx=0.27, rely=0.15, anchor=CENTER)\r\n # 歌曲名称\r\n lb_name = Label(root, text=\"歌曲名称\")\r\n lb_name.place(relx=0.1, rely=0.25, anchor=CENTER)\r\n lb_name_var = StringVar()\r\n lb_nametext = Entry(root, textvariable=lb_name_var, width=15, fg='gray', relief=GROOVE, bd=3)\r\n lb_nametext.insert(0, '成都')\r\n lb_nametext.place(relx=0.3, rely=0.25, anchor=CENTER)\r\n # 歌曲数量\r\n lb_num = Label(root, text='歌曲数量')\r\n lb_num.place(relx=0.1, rely=0.35, anchor=CENTER)\r\n lb_num_var = StringVar()\r\n lb_numtext = Entry(root, textvariable=lb_num_var, width=15, fg='gray', relief=GROOVE, bd=3)\r\n lb_numtext.insert(0, '1')\r\n lb_numtext.place(relx=0.3, rely=0.35, anchor=CENTER)\r\n # 歌曲路径\r\n lb_link = Label(root, text='存放路径')\r\n lb_link.place(relx=0.1, rely=0.45, anchor=CENTER)\r\n lb_link_var = StringVar()\r\n lb_linktext = Entry(root, textvariable=lb_link_var, width=15, fg='gray', relief=GROOVE, bd=3)\r\n lb_linktext.place(relx=0.3, rely=0.45, anchor=CENTER)\r\n # 下载详情\r\n lb_detail = Label(root, text=\"下载详情\")\r\n lb_detail.place(relx=0.1, rely=0.55, anchor=CENTER)\r\n lb_text_roll = Scrollbar(root)\r\n lb_text_roll.place(relx=0.8, rely=0.695, relheight=0.25, anchor=CENTER)\r\n lb_detailtext = Text(root, height=6, width=50)\r\n lb_detailtext.place(relx=0.425, rely=0.695, anchor=CENTER)\r\n lb_text_roll.config(command=lb_detailtext.yview)\r\n lb_detailtext.config(yscrollcommand=lb_text_roll.set)\r\n # 下载按钮\r\n bt_download = Button(root, text='搜索并下载', bd=2, width=15, height=2,\r\n command=lambda: downloader(op_engine_var, lb_name_var, lb_num_var, lb_link_var, lb_detailtext),\r\n font=('楷体', 10))\r\n bt_download.place(relx=0.2, rely=0.9, anchor=CENTER)\r\n root.mainloop()\r\n # 进入消息队列\r\n root.mainloop()\r\n\r\n\r\ndef main():\r\n options = {1: 'qq音乐', 2: '酷狗音乐', 3: '酷我音乐'}\r\n Demo(options)\r\n\r\n\r\nif __name__ == '__main__':\r\n main()","sub_path":"music_download/demo.py","file_name":"demo.py","file_ext":"py","file_size_in_byte":13588,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"402000470","text":"\"\"\"Multi processor experiment\"\"\"\n\nfrom multiprocessing import Process, current_process, cpu_count\nfrom cardscraper import CardScraper\nimport time\nimport os\nimport sys\n\n\ndef list_breakup(file_list, workers=None):\n \"\"\"Split the list of files into chunks\"\"\"\n broken_list = list()\n if workers is None:\n workers = cpu_count()\n items = len(file_list)/workers\n for worker in range(0, workers):\n runlist = list()\n for item in range(0, items+1):\n try:\n runlist.append(file_list.pop())\n except IndexError:\n break\n if worker == workers:\n if len(file_list) != 0:\n runlist.extend(filelist)\n broken_list.append(runlist)\n return broken_list\n\ndef runMulti(tasks, outputdir):\n d = CardScraper(output_dir=outputdir)\n for task in tasks:\n d.scanFile(task)\n\ndef runMultiByPath(inputdir, outputdir, workers=None):\n files2 = list()\n for root, dirs, files in os.walk(inputdir, topdown=False):\n for name in files:\n if name.split('.')[1] in ['pdf', 'PDF']:\n files2.append(root+'/'+name)\n processlist = list()\n bork = list_breakup(files2, workers=workers)\n for x in bork:\n p = Process(target=runMulti, args=(x, outputdir), name=str(bork.index(x)))\n processlist.append(p)\n p.start()\n\nif __name__ == \"__main__\":\n start = time.time()\n files2 = list()\n for root, dirs, files in os.walk(\"Y://HALRECORDS/input2/\", topdown=False):\n for name in files:\n if name.split('.')[1] in ['pdf', 'PDF']:\n files2.append(root+'/'+name)\n processlist = list()\n bork = list_breakup(files2)\n for x in bork:\n p = Process(target=runMulti, args=(x, \"Y://HALRECORDS/N390HA/\"), name=str(bork.index(x)))\n processlist.append(p)\n p.start()\n end = time.time()\n\n","sub_path":"cardscraper/multi.py","file_name":"multi.py","file_ext":"py","file_size_in_byte":1893,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"242922231","text":"from hydroDL import kPath, utils\nfrom hydroDL.app import waterQuality\nfrom hydroDL.master import basins\nfrom hydroDL.data import usgs, gageII, gridMET, ntn\nfrom hydroDL.master import slurm\nfrom hydroDL.post import axplot, figplot\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport os\nimport json\nimport sklearn.tree\nimport matplotlib.gridspec as gridspec\n\n\n# ts map of single dataset, label and code\nfreq = 'W'\ndirRoot1 = os.path.join(kPath.dirWQ, 'modelStat', 'WRTDS_weekly')\ndirRoot2 = os.path.join(kPath.dirWQ, 'modelStat', 'WRTDS_weekly_rmq')\n\ncode = '00955'\ndfRes1 = pd.read_csv(os.path.join(dirRoot1, 'result', code), dtype={\n 'siteNo': str}).set_index('siteNo')\n# dfRes2 = pd.read_csv(os.path.join(dirRoot2, 'result', code), dtype={\n# 'siteNo': str}).set_index('siteNo')\ndfGeo = gageII.readData(siteNoLst=dfRes1.index.tolist())\ndfGeo = gageII.updateCode(dfGeo)\n\n# select sites\nnS = 100\ndfR1 = dfRes1[dfRes1['count'] > nS]\nsiteNoLst = dfR1.index.tolist()\n# dfR2 = dfRes2.loc[siteNoLst]\ndfG = dfGeo.loc[siteNoLst]\nmat = dfR1['corr'].values\n\n\ndef subTree(indInput, varLst):\n x = dfG.iloc[indInput][varLst].values\n y = mat[indInput]\n x[np.isnan(x)] = -99\n clf = sklearn.tree.DecisionTreeRegressor(max_depth=1)\n clf = clf.fit(x, y)\n tree = clf.tree_\n feat = varLst[tree.feature[0]]\n th = tree.threshold[0]\n indLeft = np.where(x[:, tree.feature[0]] <= tree.threshold[0])[0]\n indRight = np.where(x[:, tree.feature[0]] > tree.threshold[0])[0]\n indLeftG = indInput[indLeft]\n indRightG = indInput[indRight]\n return indLeftG, indRightG, feat, th\n\n\ndef plotCdf(ax, indInput, indLeft, indRight):\n cLst = 'gbr'\n labLst = ['parent', 'left', 'right']\n y0 = mat[indInput]\n y1 = mat[indLeft]\n y2 = mat[indRight]\n dataLst = [y0, y1, y2]\n for k, data in enumerate(dataLst):\n xSort = np.sort(data[~np.isnan(data)])\n yRank = np.arange(1, len(xSort)+1) / float(len(xSort))\n ax.plot(xSort, yRank, color=cLst[k], label=labLst[k])\n ax.set_xlim([0, 1])\n ax.legend(loc='best', frameon=False)\n\n\ndef plotMap(ax, indInput):\n lat = dfG['LAT_GAGE'][indInput]\n lon = dfG['LNG_GAGE'][indInput]\n data = mat[indInput]\n axplot.mapPoint(ax, lat, lon, data, vRange=[0, 1], s=10)\n\n\ndef divide(indInput, colLst):\n gs = gridspec.GridSpec(2, 2)\n indLeft, indRight, feat, th = subTree(indInput, colLst)\n fig = plt.figure(figsize=[8, 4])\n ax1 = fig.add_subplot(gs[0:2, 0])\n plotCdf(ax1, indInput, indLeft, indRight)\n ax2 = fig.add_subplot(gs[0, 1])\n plotMap(ax2, indLeft)\n ax3 = fig.add_subplot(gs[1, 1])\n plotMap(ax3, indRight)\n fig.suptitle('{} {:.3f}'.format(feat, th))\n fig.show()\n return indLeft, indRight, feat, th\n\n\n# # node 0\ncolLst = dfG.columns.tolist()\nind0 = np.arange(len(siteNoLst))\nind1, ind2, feat1, th = divide(ind0, colLst=colLst)\nind3, ind4, feat2, th = divide(ind1, colLst=colLst)\nind5, ind6, feat3, th = divide(ind2, colLst=colLst)\n\n# remove some attrs\ncolLst = dfG.columns.tolist()\ncolLst.remove('NO200AVE')\ncolLst.remove('KFACT_UP')\n\n\nfor yr in range(1950, 2010):\n colLst.remove('PPT{}_AVG'.format(yr))\n colLst.remove('TMP{}_AVG'.format(yr))\nfor yr in range(1900, 2010):\n colLst.remove('wy{}'.format(yr))\nmonthLst=['JAN','FEB','APR','MAY','JUN','JUL','AUG','SEP','OCT','NOV','DEC']\nfor m in monthLst:\n colLst.remove('{}_PPT7100_CM'.format(m))\n colLst.remove('{}_TMP7100_DEGC'.format(m))\nind1, ind2, feat1, th = divide(ind0, colLst=colLst)\nind3, ind4, feat2, th = divide(ind1, colLst=colLst)\nind5, ind6, feat3, th = divide(ind2, colLst=colLst)\n","sub_path":"app/waterQual/CQ/All/carts/carts copy.py","file_name":"carts copy.py","file_ext":"py","file_size_in_byte":3615,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"11992798","text":"from django.urls import path\nfrom . import views\n\nurlpatterns = [\n path('', views.index, name='index'),\n path('optimizacion/', views.optimizacion, name='optimizacion'),\n path('calculoshelado/', views.calculos_helado, name='calculos_helado'),\n path('calculosmateria/', views.calculos_materia, name='calculos_materia'),\n path('calculos/', views.calculos, name='calculos'),\n path('scheduling/', views.scheduling, name='scheduling'),\n path('packing/', views.packing, name='packing'),\n]","sub_path":"trabajo_logica/optimizacion/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":502,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"413739399","text":"# -*- coding: utf-8 -*-\n\"\"\"\n@author:XuMing(xuming624@qq.com)\n@description: \n\"\"\"\nimport sys\n\nsys.path.append('..')\nfrom pytextclassifier import TextClassifier\n\nif __name__ == '__main__':\n m = TextClassifier()\n # model_name is choose classifier, support lr, random_forest, xgboost, svm, mlp, ensemble, stack\n print(m)\n data = [\n ('education', 'Student debt to cost Britain billions within decades'),\n ('education', 'Chinese education for TV experiment'),\n ('sports', 'Middle East and Asia boost investment in top level sports'),\n ('sports', 'Summit Series look launches HBO Canada sports doc series: Mudhar')\n ]\n m.train(data)\n\n r = m.predict(['Abbott government spends $8 million on higher education media blitz',\n 'Middle East and Asia boost investment in top level sports'])\n print(r)\n m.save()\n del m\n\n new_m = TextClassifier()\n new_m.load()\n predict_label_prob = new_m.predict_proba(['Abbott government spends $8 million on higher education media blitz'])\n print(predict_label_prob) # [[0.53337174 0.46662826]]\n print('classes_: ', new_m.model.classes_) # the classes ordered as prob\n\n predict_label = new_m.predict(['Abbott government spends $8 million on higher education media blitz',\n 'Middle East and Asia boost investment in top level sports'])\n print(predict_label) # ['education', 'sports']\n\n test_data = [\n ('education', 'Abbott government spends $8 million on higher education media blitz'),\n ('sports', 'Middle East and Asia boost investment in top level sports'),\n ]\n acc_score = new_m.test(test_data)\n print(acc_score) # 1.0\n","sub_path":"examples/base_demo.py","file_name":"base_demo.py","file_ext":"py","file_size_in_byte":1702,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"52610834","text":"from pprint import pprint\nimport argparse\nimport os\nfrom apiclient import discovery\nfrom httplib2 import Http\nfrom oauth2client import file, client, tools\n\n\ndef getCreds():\n service = None\n try:\n scope = \"https://www.googleapis.com/auth/spreadsheets\"\n client_secrets = os.path.abspath(\n 'C:/Users/BaronKimaru/Desktop/credentials.json')\n store = file.Storage('storage.json')\n creds = store.get()\n print(\"getCreds says creds is present as: \", creds)\n\n # if not present, create a handshake for its formation\n if not creds or creds.invalid:\n flags = argparse.ArgumentParser(\n parents=[tools.argparser]).parse_args()\n pprint(flags)\n flow = client.flow_from_clientsecrets(client_secrets, scope)\n creds = tools.run_flow(flow, store, flags)\n pprint(creds)\n\n service = discovery.build('sheets', 'v4', http=creds.authorize(Http()))\n\n except Exception as e:\n pprint(e), pprint(type(e))\n pprint(\"General Error\")\n\n return service\n","sub_path":"src/app/utils/sheetsapi.py","file_name":"sheetsapi.py","file_ext":"py","file_size_in_byte":1080,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"176520638","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Oct 27 17:12:42 2019\n\n@author: Marcin\n\"\"\"\n\nfrom fractions import Fraction\ndec = \"t\"\nulamki=[]\nwhile dec=='t':\n a = input ('Podaj ułamek w postaci a/b: ')\n a,b = a.split('/')\n a=int(a)\n b=int(b)\n ulamki.append((a,b))\n dec = input(\"czy chcesz podać kolejny ułamek? t/n: \")\n\n\nsuma=0\nfor a,b in ulamki:\n suma += Fraction(a,b)\n\n \nprint('Suma wynosi {}'.format(suma))","sub_path":"Programowanie_w_data_science_podstawy/Zadanie_6.py","file_name":"Zadanie_6.py","file_ext":"py","file_size_in_byte":432,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"629064169","text":"from time import *\nimport uuid\nfrom serializable import Serializable\n\nclass CommandForm(Serializable):\n def __init__(self, command, path, exit_status, context):\n self.uuid = uuid.uuid4().__str__()\n self.command = command\n self.path = path\n self.exit_status = exit_status\n self.context = context\n self.created = time()*1000\n\n\nclass UserContext(Serializable):\n def __init__(self, process_id, start_time, user_id, system_id):\n self.process_id = long(process_id)\n self.start_time = start_time\n self.user_id = user_id\n self.system_id = system_id\n","sub_path":"bashhub/model/command_form.py","file_name":"command_form.py","file_ext":"py","file_size_in_byte":617,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"570601910","text":"# Copyright (c) 2014, 2016, Oracle and/or its affiliates. All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\"\"\"\nZFS Storage Appliance Proxy\n\"\"\"\nimport json\n\nfrom oslo_log import log\nfrom oslo_service import loopingcall\n\nfrom cinder import exception\nfrom cinder.i18n import _, _LE, _LW\nfrom cinder.volume.drivers.zfssa import restclient\nfrom cinder.volume.drivers.zfssa import webdavclient\n\nLOG = log.getLogger(__name__)\n\n\ndef factory_restclient(url, **kwargs):\n return restclient.RestClientURL(url, **kwargs)\n\n\nclass ZFSSAApi(object):\n \"\"\"ZFSSA API proxy class\"\"\"\n\n def __init__(self):\n self.host = None\n self.url = None\n self.rclient = None\n\n def __del__(self):\n if self.rclient and self.rclient.islogin():\n self.rclient.logout()\n\n def _is_pool_owned(self, pdata):\n \"\"\"Returns True if the pool's owner is the same as the host.\"\"\"\n svc = '/api/system/v1/version'\n ret = self.rclient.get(svc)\n if ret.status != restclient.Status.OK:\n exception_msg = (_('Error getting version: '\n 'svc: %(svc)s.'\n 'Return code: %(ret.status)d '\n 'Message: %(ret.data)s.')\n % {'svc': svc,\n 'ret.status': ret.status,\n 'ret.data': ret.data})\n LOG.error(exception_msg)\n raise exception.VolumeBackendAPIException(data=exception_msg)\n\n vdata = json.loads(ret.data)\n return vdata['version']['asn'] == pdata['pool']['asn'] and \\\n vdata['version']['nodename'] == pdata['pool']['owner']\n\n def get_pool_details(self, pool):\n \"\"\"Get properties of a pool.\"\"\"\n svc = '/api/storage/v1/pools/%s' % pool\n ret = self.rclient.get(svc)\n if ret.status != restclient.Status.OK:\n exception_msg = (_('Error Getting Pool Stats: '\n 'Pool: %(pool)s '\n 'Return code: %(status)d '\n 'Message: %(data)s.')\n % {'pool': pool,\n 'status': ret.status,\n 'data': ret.data})\n LOG.error(exception_msg)\n raise exception.VolumeBackendAPIException(data=exception_msg)\n\n val = json.loads(ret.data)\n\n if not self._is_pool_owned(val):\n exception_msg = (_('Error Pool ownership: '\n 'Pool %(pool)s is not owned '\n 'by %(host)s.')\n % {'pool': pool,\n 'host': self.host})\n LOG.error(exception_msg)\n raise exception.InvalidInput(reason=exception_msg)\n return val['pool']\n\n def set_host(self, host, timeout=None):\n self.host = host\n self.url = \"https://\" + self.host + \":215\"\n self.rclient = factory_restclient(self.url, timeout=timeout)\n\n def login(self, auth_str):\n \"\"\"Login to the appliance\"\"\"\n if self.rclient and not self.rclient.islogin():\n self.rclient.login(auth_str)\n\n def logout(self):\n self.rclient.logout()\n\n def verify_service(self, service, status='online'):\n \"\"\"Checks whether a service is online or not\"\"\"\n svc = '/api/service/v1/services/' + service\n ret = self.rclient.get(svc)\n\n if ret.status != restclient.Status.OK:\n exception_msg = (_('Error Verifying '\n 'Service: %(service)s '\n 'Return code: %(ret.status)d '\n 'Message: %(ret.data)s.')\n % {'service': service,\n 'ret.status': ret.status,\n 'ret.data': ret.data})\n\n LOG.error(exception_msg)\n raise exception.VolumeBackendAPIException(data=exception_msg)\n\n data = json.loads(ret.data)['service']\n\n if data[''] != status:\n exception_msg = (_('%(service)s Service is not %(status)s '\n 'on storage appliance: %(host)s')\n % {'service': service,\n 'status': status,\n 'host': self.host})\n LOG.error(exception_msg)\n raise exception.VolumeBackendAPIException(data=exception_msg)\n\n def get_asn(self):\n \"\"\"Returns appliance asn.\"\"\"\n svc = '/api/system/v1/version'\n ret = self.rclient.get(svc)\n if ret.status != restclient.Status.OK:\n exception_msg = (_('Error getting appliance version details. '\n 'Return code: %(ret.status)d '\n 'Message: %(ret.data)s .')\n % {'ret.status': ret.status,\n 'ret.data': ret.data})\n LOG.error(exception_msg)\n raise exception.VolumeBackendAPIException(data=exception_msg)\n\n val = json.loads(ret.data)\n return val['version']['asn']\n\n def get_replication_targets(self):\n \"\"\"Returns all replication targets configured on the appliance.\"\"\"\n svc = '/api/storage/v1/replication/targets'\n ret = self.rclient.get(svc)\n if ret.status != restclient.Status.OK:\n exception_msg = (_('Error getting replication target details. '\n 'Return code: %(ret.status)d '\n 'Message: %(ret.data)s .')\n % {'ret.status': ret.status,\n 'ret.data': ret.data})\n LOG.error(exception_msg)\n raise exception.VolumeBackendAPIException(data=exception_msg)\n\n val = json.loads(ret.data)\n return val\n\n def edit_inherit_replication_flag(self, pool, project, volume, set=True):\n \"\"\"Edit the inherit replication flag for volume.\"\"\"\n svc = ('/api/storage/v1/pools/%(pool)s/projects/%(project)s'\n '/filesystems/%(volume)s/replication'\n % {'pool': pool,\n 'project': project,\n 'volume': volume})\n arg = {'inherited': set}\n ret = self.rclient.put(svc, arg)\n\n if ret.status != restclient.Status.ACCEPTED:\n exception_msg = (_('Error setting replication inheritance '\n 'to %(set)s '\n 'for volume: %(vol)s '\n 'project %(project)s '\n 'Return code: %(ret.status)d '\n 'Message: %(ret.data)s .')\n % {'set': set,\n 'project': project,\n 'vol': volume,\n 'ret.status': ret.status,\n 'ret.data': ret.data})\n LOG.error(exception_msg)\n raise exception.VolumeBackendAPIException(data=exception_msg)\n\n def create_replication_action(self, host_pool, host_project, tgt_name,\n tgt_pool, volume):\n \"\"\"Create a replication action.\"\"\"\n arg = {'pool': host_pool,\n 'project': host_project,\n 'target_pool': tgt_pool,\n 'target': tgt_name}\n\n if volume is not None:\n arg.update({'share': volume})\n\n svc = '/api/storage/v1/replication/actions'\n ret = self.rclient.post(svc, arg)\n if ret.status != restclient.Status.CREATED:\n exception_msg = (_('Error Creating replication action on: '\n 'pool: %(pool)s '\n 'Project: %(proj)s '\n 'volume: %(vol)s '\n 'for target: %(tgt)s and pool: %(tgt_pool)s'\n 'Return code: %(ret.status)d '\n 'Message: %(ret.data)s .')\n % {'pool': host_pool,\n 'proj': host_project,\n 'vol': volume,\n 'tgt': tgt_name,\n 'tgt_pool': tgt_pool,\n 'ret.status': ret.status,\n 'ret.data': ret.data})\n LOG.error(exception_msg)\n raise exception.VolumeBackendAPIException(data=exception_msg)\n\n val = json.loads(ret.data)\n return val['action']['id']\n\n def delete_replication_action(self, action_id):\n \"\"\"Delete a replication action.\"\"\"\n svc = '/api/storage/v1/replication/actions/%s' % action_id\n ret = self.rclient.delete(svc)\n if ret.status != restclient.Status.NO_CONTENT:\n exception_msg = (_('Error Deleting '\n 'replication action: %(id)s '\n 'Return code: %(ret.status)d '\n 'Message: %(ret.data)s.')\n % {'id': action_id,\n 'ret.status': ret.status,\n 'ret.data': ret.data})\n LOG.error(exception_msg)\n raise exception.VolumeBackendAPIException(data=exception_msg)\n\n def send_repl_update(self, action_id):\n \"\"\"Send replication update\n\n Send replication update to the target appliance and then wait for\n it to complete.\n \"\"\"\n\n svc = '/api/storage/v1/replication/actions/%s/sendupdate' % action_id\n ret = self.rclient.put(svc)\n if ret.status != restclient.Status.ACCEPTED:\n exception_msg = (_('Error sending replication update '\n 'for action id: %(id)s . '\n 'Return code: %(ret.status)d '\n 'Message: %(ret.data)s .')\n % {'id': action_id,\n 'ret.status': ret.status,\n 'ret.data': ret.data})\n LOG.error(exception_msg)\n raise exception.VolumeBackendAPIException(data=exception_msg)\n\n def _loop_func():\n svc = '/api/storage/v1/replication/actions/%s' % action_id\n ret = self.rclient.get(svc)\n if ret.status != restclient.Status.OK:\n exception_msg = (_('Error getting replication action: %(id)s. '\n 'Return code: %(ret.status)d '\n 'Message: %(ret.data)s .')\n % {'id': action_id,\n 'ret.status': ret.status,\n 'ret.data': ret.data})\n LOG.error(exception_msg)\n raise exception.VolumeBackendAPIException(data=exception_msg)\n\n val = json.loads(ret.data)\n if val['action']['last_result'] == 'success':\n raise loopingcall.LoopingCallDone()\n elif (val['action']['last_result'] == '' and\n val['action']['state'] == 'sending'):\n pass\n else:\n exception_msg = (_('Error sending replication update. '\n 'Returned error: %(err)s. '\n 'Action: %(id)s.')\n % {'err': val['action']['last_result'],\n 'id': action_id})\n LOG.error(exception_msg)\n raise exception.VolumeBackendAPIException(data=exception_msg)\n\n timer = loopingcall.FixedIntervalLoopingCall(_loop_func)\n timer.start(interval=5).wait()\n\n def get_replication_source(self, asn):\n \"\"\"Return the replication source json which has a matching asn.\"\"\"\n svc = \"/api/storage/v1/replication/sources\"\n ret = self.rclient.get(svc)\n if ret.status != restclient.Status.OK:\n exception_msg = (_('Error getting replication source details. '\n 'Return code: %(ret.status)d '\n 'Message: %(ret.data)s .')\n % {'ret.status': ret.status,\n 'ret.data': ret.data})\n LOG.error(exception_msg)\n raise exception.VolumeBackendAPIException(data=exception_msg)\n\n val = json.loads(ret.data)\n\n for source in val['sources']:\n if source['asn'] == asn:\n return source\n return None\n\n def sever_replication(self, package, src_name, project=None):\n \"\"\"Sever Replication at the destination.\n\n This method will sever the package and move the volume to a project,\n if project name is not passed in then the package name is selected\n as the project name\n \"\"\"\n\n svc = ('/api/storage/v1/replication/sources/%(src)s/packages/%(pkg)s'\n '/sever' % {'src': src_name, 'pkg': package})\n\n if not project:\n project = package\n\n arg = {'projname': project}\n ret = self.rclient.put(svc, arg)\n\n if ret.status != restclient.Status.ACCEPTED:\n exception_msg = (_('Error severing the package: %(package)s '\n 'from source: %(src)s '\n 'Return code: %(ret.status)d '\n 'Message: %(ret.data)s .')\n % {'package': package,\n 'src': src_name,\n 'ret.status': ret.status,\n 'ret.data': ret.data})\n LOG.error(exception_msg)\n raise exception.VolumeBackendAPIException(data=exception_msg)\n\n def move_volume(self, pool, project, volume, tgt_project):\n \"\"\"Move a LUN from one project to another within the same pool.\"\"\"\n svc = ('/api/storage/v1/pools/%(pool)s/projects/%(project)s'\n '/filesystems/%(volume)s' % {'pool': pool,\n 'project': project,\n 'volume': volume})\n\n arg = {'project': tgt_project}\n\n ret = self.rclient.put(svc, arg)\n if ret.status != restclient.Status.ACCEPTED:\n exception_msg = (_('Error moving volume: %(vol)s '\n 'from source project: %(src)s '\n 'to target project: %(tgt)s '\n 'Return code: %(ret.status)d '\n 'Message: %(ret.data)s .')\n % {'vol': volume,\n 'src': project,\n 'tgt': tgt_project,\n 'ret.status': ret.status,\n 'ret.data': ret.data})\n LOG.error(exception_msg)\n raise exception.VolumeBackendAPIException(data=exception_msg)\n\n def delete_project(self, pool, project):\n \"\"\"Delete a project.\"\"\"\n svc = ('/api/storage/v1/pools/%(pool)s/projects/%(project)s' %\n {'pool': pool,\n 'project': project})\n ret = self.rclient.delete(svc)\n if ret.status != restclient.Status.NO_CONTENT:\n exception_msg = (_('Error Deleting '\n 'project: %(project)s '\n 'on pool: %(pool)s '\n 'Return code: %(ret.status)d '\n 'Message: %(ret.data)s.')\n % {'project': project,\n 'pool': pool,\n 'ret.status': ret.status,\n 'ret.data': ret.data})\n LOG.error(exception_msg)\n raise exception.VolumeBackendAPIException(data=exception_msg)\n\n def get_project_stats(self, pool, project):\n \"\"\"Get project stats.\n\n Get available space and total space of a project\n returns (avail, total).\n \"\"\"\n svc = '/api/storage/v1/pools/%s/projects/%s' % (pool, project)\n ret = self.rclient.get(svc)\n if ret.status != restclient.Status.OK:\n exception_msg = (_('Error Getting Project Stats: '\n 'Pool: %(pool)s '\n 'Project: %(project)s '\n 'Return code: %(ret.status)d '\n 'Message: %(ret.data)s.')\n % {'pool': pool,\n 'project': project,\n 'ret.status': ret.status,\n 'ret.data': ret.data})\n LOG.error(exception_msg)\n raise exception.VolumeBackendAPIException(data=exception_msg)\n\n val = json.loads(ret.data)\n avail = val['project']['space_available']\n total = avail + val['project']['space_total']\n\n return avail, total\n\n def create_project(self, pool, project, compression=None, logbias=None):\n \"\"\"Create a project on a pool.\n\n Check first whether the pool exists.\n \"\"\"\n self.verify_pool(pool)\n svc = '/api/storage/v1/pools/' + pool + '/projects/' + project\n ret = self.rclient.get(svc)\n if ret.status != restclient.Status.OK:\n svc = '/api/storage/v1/pools/' + pool + '/projects'\n arg = {\n 'name': project\n }\n if compression and compression != '':\n arg.update({'compression': compression})\n if logbias and logbias != '':\n arg.update({'logbias': logbias})\n\n ret = self.rclient.post(svc, arg)\n if ret.status != restclient.Status.CREATED:\n exception_msg = (_('Error Creating Project: '\n '%(project)s on '\n 'Pool: %(pool)s '\n 'Return code: %(ret.status)d '\n 'Message: %(ret.data)s .')\n % {'project': project,\n 'pool': pool,\n 'ret.status': ret.status,\n 'ret.data': ret.data})\n LOG.error(exception_msg)\n raise exception.VolumeBackendAPIException(data=exception_msg)\n\n def create_initiator(self, initiator, alias, chapuser=None,\n chapsecret=None):\n \"\"\"Create an iSCSI initiator.\"\"\"\n\n svc = '/api/san/v1/iscsi/initiators/alias=' + alias\n ret = self.rclient.get(svc)\n if ret.status != restclient.Status.OK:\n svc = '/api/san/v1/iscsi/initiators'\n arg = {\n 'initiator': initiator,\n 'alias': alias\n }\n if chapuser and chapuser != '' and chapsecret and chapsecret != '':\n arg.update({'chapuser': chapuser,\n 'chapsecret': chapsecret})\n\n ret = self.rclient.post(svc, arg)\n if ret.status != restclient.Status.CREATED:\n exception_msg = (_('Error Creating Initiator: '\n '%(initiator)s on '\n 'Alias: %(alias)s '\n 'Return code: %(ret.status)d '\n 'Message: %(ret.data)s .')\n % {'initiator': initiator,\n 'alias': alias,\n 'ret.status': ret.status,\n 'ret.data': ret.data})\n LOG.error(exception_msg)\n raise exception.VolumeBackendAPIException(data=exception_msg)\n\n def add_to_initiatorgroup(self, initiator, initiatorgroup):\n \"\"\"Add an iSCSI initiator to initiatorgroup\"\"\"\n svc = '/api/san/v1/iscsi/initiator-groups/' + initiatorgroup\n ret = self.rclient.get(svc)\n if ret.status != restclient.Status.OK:\n svc = '/api/san/v1/iscsi/initiator-groups'\n arg = {\n 'name': initiatorgroup,\n 'initiators': [initiator]\n }\n ret = self.rclient.post(svc, arg)\n if ret.status != restclient.Status.CREATED:\n exception_msg = (_('Error Adding Initiator: '\n '%(initiator)s on group'\n 'InitiatorGroup: %(initiatorgroup)s '\n 'Return code: %(ret.status)d '\n 'Message: %(ret.data)s .')\n % {'initiator': initiator,\n 'initiatorgroup': initiatorgroup,\n 'ret.status': ret.status,\n 'ret.data': ret.data})\n LOG.error(exception_msg)\n raise exception.VolumeBackendAPIException(data=exception_msg)\n else:\n val = json.loads(ret.data)\n inits = val['group']['initiators']\n if inits is None:\n exception_msg = (_('Error Getting Initiators: '\n 'InitiatorGroup: %(initiatorgroup)s '\n 'Return code: %(ret.status)d '\n 'Message: %(ret.data)s .')\n % {'initiatorgroup': initiatorgroup,\n 'ret.status': ret.status,\n 'ret.data': ret.data})\n LOG.error(exception_msg)\n raise exception.VolumeBackendAPIException(data=exception_msg)\n\n if initiator in inits:\n return\n\n inits.append(initiator)\n svc = '/api/san/v1/iscsi/initiator-groups/' + initiatorgroup\n arg = {\n 'initiators': inits\n }\n ret = self.rclient.put(svc, arg)\n if ret.status != restclient.Status.ACCEPTED:\n exception_msg = (_('Error Adding Initiator: '\n '%(initiator)s on group'\n 'InitiatorGroup: %(initiatorgroup)s '\n 'Return code: %(ret.status)d '\n 'Message: %(ret.data)s .')\n % {'initiator': initiator,\n 'initiatorgroup': initiatorgroup,\n 'ret.status': ret.status,\n 'ret.data': ret.data})\n LOG.error(exception_msg)\n raise exception.VolumeBackendAPIException(data=exception_msg)\n\n def create_target(self, alias, interfaces=None, tchapuser=None,\n tchapsecret=None):\n \"\"\"Create an iSCSI target.\n\n :param interfaces: an array with network interfaces\n :param tchapuser, tchapsecret: target's chapuser and chapsecret\n :returns: target iqn\n \"\"\"\n svc = '/api/san/v1/iscsi/targets/alias=' + alias\n ret = self.rclient.get(svc)\n if ret.status != restclient.Status.OK:\n svc = '/api/san/v1/iscsi/targets'\n arg = {\n 'alias': alias\n }\n\n if tchapuser and tchapuser != '' and tchapsecret and \\\n tchapsecret != '':\n arg.update({'targetchapuser': tchapuser,\n 'targetchapsecret': tchapsecret,\n 'auth': 'chap'})\n\n if interfaces is not None and len(interfaces) > 0:\n arg.update({'interfaces': interfaces})\n\n ret = self.rclient.post(svc, arg)\n if ret.status != restclient.Status.CREATED:\n exception_msg = (_('Error Creating Target: '\n '%(alias)s'\n 'Return code: %(ret.status)d '\n 'Message: %(ret.data)s .')\n % {'alias': alias,\n 'ret.status': ret.status,\n 'ret.data': ret.data})\n LOG.error(exception_msg)\n raise exception.VolumeBackendAPIException(data=exception_msg)\n\n val = json.loads(ret.data)\n return val['target']['iqn']\n\n def get_target(self, alias):\n \"\"\"Get an iSCSI target iqn.\"\"\"\n svc = '/api/san/v1/iscsi/targets/alias=' + alias\n ret = self.rclient.get(svc)\n if ret.status != restclient.Status.OK:\n exception_msg = (_('Error Getting Target: '\n '%(alias)s'\n 'Return code: %(ret.status)d '\n 'Message: %(ret.data)s .')\n % {'alias': alias,\n 'ret.status': ret.status,\n 'ret.data': ret.data})\n LOG.error(exception_msg)\n raise exception.VolumeBackendAPIException(data=exception_msg)\n\n val = json.loads(ret.data)\n return val['target']['iqn']\n\n def add_to_targetgroup(self, iqn, targetgroup):\n \"\"\"Add an iSCSI target to targetgroup.\"\"\"\n svc = '/api/san/v1/iscsi/target-groups/' + targetgroup\n ret = self.rclient.get(svc)\n if ret.status != restclient.Status.OK:\n svccrt = '/api/san/v1/iscsi/target-groups'\n arg = {\n 'name': targetgroup,\n 'targets': [iqn]\n }\n\n ret = self.rclient.post(svccrt, arg)\n if ret.status != restclient.Status.CREATED:\n exception_msg = (_('Error Creating TargetGroup: '\n '%(targetgroup)s with'\n 'IQN: %(iqn)s'\n 'Return code: %(ret.status)d '\n 'Message: %(ret.data)s .')\n % {'targetgroup': targetgroup,\n 'iqn': iqn,\n 'ret.status': ret.status,\n 'ret.data': ret.data})\n LOG.error(exception_msg)\n raise exception.VolumeBackendAPIException(data=exception_msg)\n\n return\n\n arg = {\n 'targets': [iqn]\n }\n\n ret = self.rclient.put(svc, arg)\n if ret.status != restclient.Status.ACCEPTED:\n exception_msg = (_('Error Adding to TargetGroup: '\n '%(targetgroup)s with'\n 'IQN: %(iqn)s'\n 'Return code: %(ret.status)d '\n 'Message: %(ret.data)s.')\n % {'targetgroup': targetgroup,\n 'iqn': iqn,\n 'ret.status': ret.status,\n 'ret.data': ret.data})\n LOG.error(exception_msg)\n raise exception.VolumeBackendAPIException(data=exception_msg)\n\n def verify_pool(self, pool):\n \"\"\"Checks whether pool exists.\"\"\"\n svc = '/api/storage/v1/pools/' + pool\n ret = self.rclient.get(svc)\n if ret.status != restclient.Status.OK:\n exception_msg = (_('Error Verifying Pool: '\n '%(pool)s '\n 'Return code: %(ret.status)d '\n 'Message: %(ret.data)s.')\n % {'pool': pool,\n 'ret.status': ret.status,\n 'ret.data': ret.data})\n LOG.error(exception_msg)\n raise exception.VolumeBackendAPIException(data=exception_msg)\n\n def verify_project(self, pool, project):\n \"\"\"Checks whether project exists.\"\"\"\n svc = '/api/storage/v1/pools/' + pool + '/projects/' + project\n ret = self.rclient.get(svc)\n if ret.status != restclient.Status.OK:\n exception_msg = (_('Error Verifying '\n 'Project: %(project)s on '\n 'Pool: %(pool)s '\n 'Return code: %(ret.status)d '\n 'Message: %(ret.data)s.')\n % {'project': project,\n 'pool': pool,\n 'ret.status': ret.status,\n 'ret.data': ret.data})\n LOG.error(exception_msg)\n raise exception.VolumeBackendAPIException(data=exception_msg)\n\n def verify_initiator(self, iqn):\n \"\"\"Check whether initiator iqn exists.\"\"\"\n svc = '/api/san/v1/iscsi/initiators/' + iqn\n ret = self.rclient.get(svc)\n if ret.status != restclient.Status.OK:\n exception_msg = (_('Error Verifying '\n 'Initiator: %(iqn)s '\n 'Return code: %(ret.status)d '\n 'Message: %(ret.data)s.')\n % {'initiator': iqn,\n 'ret.status': ret.status,\n 'ret.data': ret.data})\n LOG.error(exception_msg)\n raise exception.VolumeBackendAPIException(data=exception_msg)\n\n def verify_target(self, alias):\n \"\"\"Check whether target alias exists.\"\"\"\n svc = '/api/san/v1/iscsi/targets/alias=' + alias\n ret = self.rclient.get(svc)\n if ret.status != restclient.Status.OK:\n exception_msg = (_('Error Verifying '\n 'Target: %(alias)s '\n 'Return code: %(ret.status)d '\n 'Message: %(ret.data)s.')\n % {'alias': alias,\n 'ret.status': ret.status,\n 'ret.data': ret.data})\n LOG.error(exception_msg)\n raise exception.VolumeBackendAPIException(data=exception_msg)\n\n def create_lun(self, pool, project, lun, volsize, targetgroup, specs):\n \"\"\"Create a LUN.\n\n specs - contains volume properties (e.g blocksize, compression).\n \"\"\"\n svc = '/api/storage/v1/pools/' + pool + '/projects/' + \\\n project + '/luns'\n arg = {\n 'name': lun,\n 'volsize': volsize,\n 'targetgroup': targetgroup,\n 'initiatorgroup': 'com.sun.ms.vss.hg.maskAll'\n }\n if specs:\n arg.update(specs)\n\n ret = self.rclient.post(svc, arg)\n if ret.status != restclient.Status.CREATED:\n exception_msg = (_('Error Creating '\n 'Volume: %(lun)s '\n 'Size: %(size)s '\n 'Return code: %(ret.status)d '\n 'Message: %(ret.data)s.')\n % {'lun': lun,\n 'size': volsize,\n 'ret.status': ret.status,\n 'ret.data': ret.data})\n LOG.error(exception_msg)\n raise exception.VolumeBackendAPIException(data=exception_msg)\n\n val = json.loads(ret.data)\n return val\n\n def get_lun(self, pool, project, lun):\n \"\"\"return iscsi lun properties.\"\"\"\n svc = '/api/storage/v1/pools/' + pool + '/projects/' + \\\n project + \"/luns/\" + lun\n ret = self.rclient.get(svc)\n if ret.status != restclient.Status.OK:\n exception_msg = (_('Error Getting '\n 'Volume: %(lun)s on '\n 'Pool: %(pool)s '\n 'Project: %(project)s '\n 'Return code: %(ret.status)d '\n 'Message: %(ret.data)s.')\n % {'lun': lun,\n 'pool': pool,\n 'project': project,\n 'ret.status': ret.status,\n 'ret.data': ret.data})\n LOG.error(exception_msg)\n raise exception.VolumeNotFound(volume_id=lun)\n\n val = json.loads(ret.data)\n ret = {\n 'name': val['lun']['name'],\n 'guid': val['lun']['lunguid'],\n 'number': val['lun']['assignednumber'],\n 'initiatorgroup': val['lun']['initiatorgroup'],\n 'size': val['lun']['volsize'],\n 'nodestroy': val['lun']['nodestroy'],\n 'targetgroup': val['lun']['targetgroup']\n }\n if 'origin' in val['lun']:\n ret.update({'origin': val['lun']['origin']})\n if 'custom:image_id' in val['lun']:\n ret.update({'image_id': val['lun']['custom:image_id']})\n ret.update({'updated_at': val['lun']['custom:updated_at']})\n if 'custom:cinder_managed' in val['lun']:\n ret.update({'cinder_managed': val['lun']['custom:cinder_managed']})\n\n return ret\n\n def get_lun_snapshot(self, pool, project, lun, snapshot):\n \"\"\"Return iscsi lun snapshot properties.\"\"\"\n svc = ('/api/storage/v1/pools/' + pool + '/projects/' +\n project + '/luns/' + lun + '/snapshots/' + snapshot)\n\n ret = self.rclient.get(svc)\n if ret.status != restclient.Status.OK:\n exception_msg = (_LE('Error Getting '\n 'Snapshot: %(snapshot)s of '\n 'Volume: %(lun)s in '\n 'Pool: %(pool)s, '\n 'Project: %(project)s '\n 'Return code: %(ret.status)d, '\n 'Message: %(ret.data)s.'),\n {'snapshot': snapshot,\n 'lun': lun,\n 'pool': pool,\n 'project': project,\n 'ret.status': ret.status,\n 'ret.data': ret.data})\n LOG.error(exception_msg)\n raise exception.SnapshotNotFound(snapshot_id=snapshot)\n\n val = json.loads(ret.data)['snapshot']\n ret = {\n 'name': val['name'],\n 'numclones': val['numclones'],\n }\n return ret\n\n def set_lun_initiatorgroup(self, pool, project, lun, initiatorgroup):\n \"\"\"Set the initiatorgroup property of a LUN.\"\"\"\n if initiatorgroup == '':\n initiatorgroup = 'com.sun.ms.vss.hg.maskAll'\n\n svc = '/api/storage/v1/pools/' + pool + '/projects/' + \\\n project + '/luns/' + lun\n arg = {\n 'initiatorgroup': initiatorgroup\n }\n\n ret = self.rclient.put(svc, arg)\n if ret.status != restclient.Status.ACCEPTED:\n LOG.error(_LE('Error Setting Volume: %(lun)s to InitiatorGroup: '\n '%(initiatorgroup)s Pool: %(pool)s Project: '\n '%(project)s Return code: %(ret.status)d Message: '\n '%(ret.data)s.'),\n {'lun': lun,\n 'initiatorgroup': initiatorgroup,\n 'pool': pool,\n 'project': project,\n 'ret.status': ret.status,\n 'ret.data': ret.data})\n\n def delete_lun(self, pool, project, lun):\n \"\"\"delete iscsi lun.\"\"\"\n svc = '/api/storage/v1/pools/' + pool + '/projects/' + \\\n project + '/luns/' + lun\n\n ret = self.rclient.delete(svc)\n if ret.status != restclient.Status.NO_CONTENT:\n exception_msg = (_('Error Deleting Volume: %(lun)s from '\n 'Pool: %(pool)s, Project: %(project)s. '\n 'Return code: %(ret.status)d, '\n 'Message: %(ret.data)s.'),\n {'lun': lun,\n 'pool': pool,\n 'project': project,\n 'ret.status': ret.status,\n 'ret.data': ret.data})\n LOG.error(exception_msg)\n if ret.status == restclient.Status.FORBIDDEN:\n # This means that the lun exists but it can't be deleted:\n raise exception.VolumeBackendAPIException(data=exception_msg)\n\n def create_snapshot(self, pool, project, lun, snapshot):\n \"\"\"create snapshot.\"\"\"\n svc = '/api/storage/v1/pools/' + pool + '/projects/' + \\\n project + '/luns/' + lun + '/snapshots'\n arg = {\n 'name': snapshot\n }\n\n ret = self.rclient.post(svc, arg)\n if ret.status != restclient.Status.CREATED:\n exception_msg = (_('Error Creating '\n 'Snapshot: %(snapshot)s on'\n 'Volume: %(lun)s to '\n 'Pool: %(pool)s '\n 'Project: %(project)s '\n 'Return code: %(ret.status)d '\n 'Message: %(ret.data)s.'),\n {'snapshot': snapshot,\n 'lun': lun,\n 'pool': pool,\n 'project': project,\n 'ret.status': ret.status,\n 'ret.data': ret.data})\n LOG.error(exception_msg)\n raise exception.VolumeBackendAPIException(data=exception_msg)\n\n def delete_snapshot(self, pool, project, lun, snapshot):\n \"\"\"delete snapshot.\"\"\"\n svc = '/api/storage/v1/pools/' + pool + '/projects/' + \\\n project + '/luns/' + lun + '/snapshots/' + snapshot\n\n ret = self.rclient.delete(svc)\n if ret.status != restclient.Status.NO_CONTENT:\n exception_msg = (_('Error Deleting '\n 'Snapshot: %(snapshot)s on '\n 'Volume: %(lun)s to '\n 'Pool: %(pool)s '\n 'Project: %(project)s '\n 'Return code: %(ret.status)d '\n 'Message: %(ret.data)s.')\n % {'snapshot': snapshot,\n 'lun': lun,\n 'pool': pool,\n 'project': project,\n 'ret.status': ret.status,\n 'ret.data': ret.data})\n LOG.error(exception_msg)\n raise exception.VolumeBackendAPIException(data=exception_msg)\n\n def clone_snapshot(self, pool, project, lun, snapshot, clone_proj, clone):\n \"\"\"clone 'snapshot' to a lun named 'clone' in project 'clone_proj'.\"\"\"\n svc = '/api/storage/v1/pools/' + pool + '/projects/' + \\\n project + '/luns/' + lun + '/snapshots/' + snapshot + '/clone'\n arg = {\n 'project': clone_proj,\n 'share': clone,\n 'nodestroy': True\n }\n\n ret = self.rclient.put(svc, arg)\n if ret.status != restclient.Status.CREATED:\n exception_msg = (_('Error Cloning '\n 'Snapshot: %(snapshot)s on '\n 'Volume: %(lun)s of '\n 'Pool: %(pool)s '\n 'Project: %(project)s '\n 'Clone project: %(clone_proj)s '\n 'Return code: %(ret.status)d '\n 'Message: %(ret.data)s.')\n % {'snapshot': snapshot,\n 'lun': lun,\n 'pool': pool,\n 'project': project,\n 'clone_proj': clone_proj,\n 'ret.status': ret.status,\n 'ret.data': ret.data})\n LOG.error(exception_msg)\n raise exception.VolumeBackendAPIException(data=exception_msg)\n\n def set_lun_props(self, pool, project, lun, **kargs):\n \"\"\"set lun properties.\"\"\"\n svc = '/api/storage/v1/pools/' + pool + '/projects/' + \\\n project + '/luns/' + lun\n if kargs is None:\n return\n\n if 'schema' in kargs:\n kargs.update(kargs.pop('schema'))\n\n ret = self.rclient.put(svc, kargs)\n if ret.status != restclient.Status.ACCEPTED:\n exception_msg = (_('Error Setting props '\n 'Props: %(props)s on '\n 'Volume: %(lun)s of '\n 'Pool: %(pool)s '\n 'Project: %(project)s '\n 'Return code: %(ret.status)d '\n 'Message: %(ret.data)s.')\n % {'props': kargs,\n 'lun': lun,\n 'pool': pool,\n 'project': project,\n 'ret.status': ret.status,\n 'ret.data': ret.data})\n LOG.error(exception_msg)\n raise exception.VolumeBackendAPIException(data=exception_msg)\n\n def num_clones(self, pool, project, lun, snapshot):\n \"\"\"Checks whether snapshot has clones or not.\"\"\"\n svc = '/api/storage/v1/pools/' + pool + '/projects/' + \\\n project + '/luns/' + lun + '/snapshots/' + snapshot\n\n ret = self.rclient.get(svc)\n if ret.status != restclient.Status.OK:\n exception_msg = (_('Error Getting '\n 'Snapshot: %(snapshot)s on '\n 'Volume: %(lun)s to '\n 'Pool: %(pool)s '\n 'Project: %(project)s '\n 'Return code: %(ret.status)d '\n 'Message: %(ret.data)s.')\n % {'snapshot': snapshot,\n 'lun': lun,\n 'pool': pool,\n 'project': project,\n 'ret.status': ret.status,\n 'ret.data': ret.data})\n LOG.error(exception_msg)\n raise exception.VolumeBackendAPIException(data=exception_msg)\n\n val = json.loads(ret.data)\n return val['snapshot']['numclones']\n\n def get_initiator_initiatorgroup(self, initiator):\n \"\"\"Returns the initiator group of the initiator.\"\"\"\n groups = []\n svc = \"/api/san/v1/iscsi/initiator-groups\"\n ret = self.rclient.get(svc)\n if ret.status != restclient.Status.OK:\n msg = _('Error getting initiator groups.')\n LOG.error(msg)\n raise exception.VolumeBackendAPIException(data=msg)\n val = json.loads(ret.data)\n for initiator_group in val['groups']:\n if initiator in initiator_group['initiators']:\n groups.append(initiator_group[\"name\"])\n return groups\n\n def create_schema(self, schema):\n \"\"\"Create a custom ZFSSA schema.\"\"\"\n base = '/api/storage/v1/schema'\n\n svc = \"%(base)s/%(prop)s\" % {'base': base, 'prop': schema['property']}\n ret = self.rclient.get(svc)\n if ret.status == restclient.Status.OK:\n LOG.warning(_LW('Property %s already exists.'), schema['property'])\n return\n\n ret = self.rclient.post(base, schema)\n if ret.status != restclient.Status.CREATED:\n exception_msg = (_('Error Creating '\n 'Property: %(property)s '\n 'Type: %(type)s '\n 'Description: %(description)s '\n 'Return code: %(ret.status)d '\n 'Message: %(ret.data)s.')\n % {'property': schema['property'],\n 'type': schema['type'],\n 'description': schema['description'],\n 'ret.status': ret.status,\n 'ret.data': ret.data})\n LOG.error(exception_msg)\n raise exception.VolumeBackendAPIException(data=exception_msg)\n\n def create_schemas(self, schemas):\n \"\"\"Create multiple custom ZFSSA schemas.\"\"\"\n ret = []\n for schema in schemas:\n res = self.create_schema(schema)\n ret.append(res)\n return ret\n\n\nclass ZFSSANfsApi(ZFSSAApi):\n \"\"\"ZFSSA API proxy class for NFS driver\"\"\"\n projects_path = '/api/storage/v1/pools/%s/projects'\n project_path = projects_path + '/%s'\n\n shares_path = project_path + '/filesystems'\n share_path = shares_path + '/%s'\n share_snapshots_path = share_path + '/snapshots'\n share_snapshot_path = share_snapshots_path + '/%s'\n\n services_path = '/api/service/v1/services/'\n\n def __init__(self, *args, **kwargs):\n super(ZFSSANfsApi, self).__init__(*args, **kwargs)\n self.webdavclient = None\n\n def set_webdav(self, https_path, auth_str):\n self.webdavclient = webdavclient.ZFSSAWebDAVClient(https_path,\n auth_str)\n\n def verify_share(self, pool, project, share):\n \"\"\"Checks whether the share exists\"\"\"\n svc = self.share_path % (pool, project, share)\n ret = self.rclient.get(svc)\n if ret.status != restclient.Status.OK:\n exception_msg = (_('Error Verifying '\n 'share: %(share)s on '\n 'Project: %(project)s and '\n 'Pool: %(pool)s '\n 'Return code: %(ret.status)d '\n 'Message: %(ret.data)s.')\n % {'share': share,\n 'project': project,\n 'pool': pool,\n 'ret.status': ret.status,\n 'ret.data': ret.data})\n LOG.error(exception_msg)\n raise exception.VolumeBackendAPIException(data=exception_msg)\n\n def create_snapshot(self, pool, project, share, snapshot):\n \"\"\"create snapshot of a share\"\"\"\n svc = self.share_snapshots_path % (pool, project, share)\n\n arg = {\n 'name': snapshot\n }\n\n ret = self.rclient.post(svc, arg)\n if ret.status != restclient.Status.CREATED:\n exception_msg = (_('Error Creating '\n 'Snapshot: %(snapshot)s on'\n 'share: %(share)s to '\n 'Pool: %(pool)s '\n 'Project: %(project)s '\n 'Return code: %(ret.status)d '\n 'Message: %(ret.data)s.')\n % {'snapshot': snapshot,\n 'share': share,\n 'pool': pool,\n 'project': project,\n 'ret.status': ret.status,\n 'ret.data': ret.data})\n LOG.error(exception_msg)\n raise exception.VolumeBackendAPIException(data=exception_msg)\n\n def delete_snapshot(self, pool, project, share, snapshot):\n \"\"\"delete snapshot of a share\"\"\"\n svc = self.share_snapshot_path % (pool, project, share, snapshot)\n\n ret = self.rclient.delete(svc)\n if ret.status != restclient.Status.NO_CONTENT:\n exception_msg = (_('Error Deleting '\n 'Snapshot: %(snapshot)s on '\n 'Share: %(share)s to '\n 'Pool: %(pool)s '\n 'Project: %(project)s '\n 'Return code: %(ret.status)d '\n 'Message: %(ret.data)s.')\n % {'snapshot': snapshot,\n 'share': share,\n 'pool': pool,\n 'project': project,\n 'ret.status': ret.status,\n 'ret.data': ret.data})\n LOG.error(exception_msg)\n raise exception.VolumeBackendAPIException(data=exception_msg)\n\n def create_snapshot_of_volume_file(self, src_file=\"\", dst_file=\"\"):\n src_file = '.zfs/snapshot/' + src_file\n return self.webdavclient.request(src_file=src_file, dst_file=dst_file,\n method='COPY')\n\n def delete_snapshot_of_volume_file(self, src_file=\"\"):\n return self.webdavclient.request(src_file=src_file, method='DELETE')\n\n def create_volume_from_snapshot_file(self, src_file=\"\", dst_file=\"\",\n method='COPY'):\n return self.webdavclient.request(src_file=src_file, dst_file=dst_file,\n method=method)\n\n def _change_service_state(self, service, state=''):\n svc = self.services_path + service + '/' + state\n ret = self.rclient.put(svc)\n if ret.status != restclient.Status.ACCEPTED:\n exception_msg = (_('Error Verifying '\n 'Service: %(service)s '\n 'Return code: %(ret.status)d '\n 'Message: %(ret.data)s.')\n % {'service': service,\n 'ret.status': ret.status,\n 'ret.data': ret.data})\n\n LOG.error(exception_msg)\n raise exception.VolumeBackendAPIException(data=exception_msg)\n data = json.loads(ret.data)['service']\n LOG.debug('%(service)s service state: %(data)s',\n {'service': service, 'data': data})\n\n status = 'online' if state == 'enable' else 'disabled'\n\n if data[''] != status:\n exception_msg = (_('%(service)s Service is not %(status)s '\n 'on storage appliance: %(host)s')\n % {'service': service,\n 'status': status,\n 'host': self.host})\n LOG.error(exception_msg)\n raise exception.VolumeBackendAPIException(data=exception_msg)\n\n def enable_service(self, service):\n self._change_service_state(service, state='enable')\n self.verify_service(service)\n\n def disable_service(self, service):\n self._change_service_state(service, state='disable')\n self.verify_service(service, status='offline')\n\n def modify_service(self, service, edit_args=None):\n \"\"\"Edit service properties\"\"\"\n if edit_args is None:\n edit_args = {}\n\n svc = self.services_path + service\n\n ret = self.rclient.put(svc, edit_args)\n\n if ret.status != restclient.Status.ACCEPTED:\n exception_msg = (_('Error modifying '\n 'Service: %(service)s '\n 'Return code: %(ret.status)d '\n 'Message: %(ret.data)s.')\n % {'service': service,\n 'ret.status': ret.status,\n 'ret.data': ret.data})\n\n LOG.error(exception_msg)\n raise exception.VolumeBackendAPIException(data=exception_msg)\n data = json.loads(ret.data)['service']\n LOG.debug('Modify %(service)s service '\n 'return data: %(data)s',\n {'service': service,\n 'data': data})\n\n def create_share(self, pool, project, share, args):\n \"\"\"Create a share in the specified pool and project\"\"\"\n svc = self.share_path % (pool, project, share)\n ret = self.rclient.get(svc)\n if ret.status != restclient.Status.OK:\n svc = self.shares_path % (pool, project)\n args.update({'name': share})\n ret = self.rclient.post(svc, args)\n if ret.status != restclient.Status.CREATED:\n exception_msg = (_('Error Creating '\n 'Share: %(name)s '\n 'Return code: %(ret.status)d '\n 'Message: %(ret.data)s.')\n % {'name': share,\n 'ret.status': ret.status,\n 'ret.data': ret.data})\n LOG.error(exception_msg)\n raise exception.VolumeBackendAPIException(data=exception_msg)\n else:\n LOG.debug('Editing properties of a pre-existing share')\n ret = self.rclient.put(svc, args)\n if ret.status != restclient.Status.ACCEPTED:\n exception_msg = (_('Error editing share: '\n '%(share)s on '\n 'Pool: %(pool)s '\n 'Return code: %(ret.status)d '\n 'Message: %(ret.data)s .')\n % {'share': share,\n 'pool': pool,\n 'ret.status': ret.status,\n 'ret.data': ret.data})\n LOG.error(exception_msg)\n raise exception.VolumeBackendAPIException(data=exception_msg)\n\n def get_share(self, pool, project, share):\n \"\"\"return share properties\"\"\"\n svc = self.share_path % (pool, project, share)\n ret = self.rclient.get(svc)\n if ret.status != restclient.Status.OK:\n exception_msg = (_('Error Getting '\n 'Share: %(share)s on '\n 'Pool: %(pool)s '\n 'Project: %(project)s '\n 'Return code: %(ret.status)d '\n 'Message: %(ret.data)s.')\n % {'share': share,\n 'pool': pool,\n 'project': project,\n 'ret.status': ret.status,\n 'ret.data': ret.data})\n LOG.error(exception_msg)\n raise exception.VolumeBackendAPIException(data=exception_msg)\n\n val = json.loads(ret.data)\n return val['filesystem']\n\n def get_volume(self, volume):\n LOG.debug('Getting volume %s.', volume)\n try:\n resp = self.webdavclient.request(src_file=volume,\n method='PROPFIND')\n except Exception:\n raise exception.VolumeNotFound(volume_id=volume)\n\n resp = resp.read()\n numclones = self._parse_prop(resp, 'numclones')\n result = {\n 'numclones': int(numclones) if numclones != '' else 0,\n 'updated_at': self._parse_prop(resp, 'updated_at'),\n 'image_id': self._parse_prop(resp, 'image_id'),\n 'origin': self._parse_prop(resp, 'origin'),\n 'cinder_managed': self._parse_prop(resp, 'cinder_managed'),\n }\n return result\n\n def delete_file(self, filename):\n try:\n self.webdavclient.request(src_file=filename, method='DELETE')\n except Exception:\n exception_msg = (_LE('Cannot delete file %s.'), filename)\n LOG.error(exception_msg)\n\n def set_file_props(self, file, specs):\n \"\"\"Set custom properties to a file.\"\"\"\n for key in specs:\n self.webdavclient.set_file_prop(file, key, specs[key])\n\n def _parse_prop(self, response, prop):\n \"\"\"Parse a property value from the WebDAV response.\"\"\"\n propval = \"\"\n for line in response.split(\"\\n\"):\n if prop in line:\n try:\n propval = line[(line.index('>') + 1):line.index(' int:\n \"\"\"\n l = [a, b]\n return sum(l)\n \"\"\"\n \n # 32 bits integer max\n MAX = 0x7FFFFFFF\n # 32 bits interger min\n MIN = 0x80000000\n \n # two's complement\n m = 0xffffffff # i is all 1 on 32 digits, a&i == a, a^i = i-a if a>0; -i-a if a<0\n \n while b!=0:\n a, b = (a^b) & m, (a&b)<<1 & m\n return a if a int:\n if not A:\n return 0\n \n xMax = len(A)\n yMax = len(A[0])\n \n for y in range(1, yMax):\n for x in range(xMax):\n if x == 0:\n A[y][x] += min(A[y-1][x], A[y-1][x+1])\n elif x == xMax-1:\n A[y][x] += min(A[y-1][x], A[y-1][x-1])\n elif 0 < x < xMax-1:\n A[y][x] += min(A[y-1][x], A[y-1][x+1], A[y-1][x-1])\n \n return min(A[-1])","sub_path":"dynamic-programming-patterns/931minimumFallingPathSum.py","file_name":"931minimumFallingPathSum.py","file_ext":"py","file_size_in_byte":569,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"608189912","text":"#!/usr/bin/env python\nimport ROOT\nimport numpy as np\nimport array\nimport os\nfrom BranchTools import Collection\nfrom BranchTools import AddCollectionsModule\nfrom myutils.Jet import Jet\n\nclass aJidx(AddCollectionsModule):\n\n def __init__(self):\n super(aJidx, self).__init__()\n self.nAddJetMax = 10\n\n def customInit(self, initVars):\n self.sample = initVars['sample']\n self.config = initVars['config']\n\n self.addIntegerVectorBranch(\"aJidx_202p5\", default=-1, length=self.nAddJetMax)\n self.addIntegerBranch(\"naJ_202p5\",default=-1)\n\n def processEvent(self, tree):\n # if current entry has not been processed yet\n if not self.hasBeenProcessed(tree):\n self.markProcessed(tree)\n for bn in ['aJidx_202p5']:\n for k in range(self.nAddJetMax):\n self._b(bn)[k] = -1\n\n jets = Jet.get(tree)\n\n jetSelection = lambda x: x.pt>20.0 and abs(x.eta) < 2.5 and x.index!=tree.hJidx[0] and x.index!=tree.hJidx[1]\n additionalJets = sorted([x for x in jets if jetSelection(x)], key=lambda j: -j.pt)\n additionalJetIndices = [x.index for x in additionalJets]\n\n self._b(\"naJ_202p5\")[0] = min(len(additionalJetIndices), self.nAddJetMax)\n for i in range(self._b(\"naJ_202p5\")[0]): \n self._b(\"aJidx_202p5\")[i] = additionalJetIndices[i]\n\n","sub_path":"python/myutils/aJidx.py","file_name":"aJidx.py","file_ext":"py","file_size_in_byte":1402,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"597719939","text":"#!/usr/bin/env python3\nfrom lilaclib import *\n\ndef pre_build():\n aur_pre_build()\n\n for line in edit_file('PKGBUILD'):\n if line.startswith('prepare() '):\n print(\"sed 's/CP866/CP936/g' -i iconv-utf8+CVE-2015-1315.patch\")\n else:\n print(line)\n","sub_path":"archlinuxcn/unzip-iconv/lilac.py","file_name":"lilac.py","file_ext":"py","file_size_in_byte":281,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"6904126","text":"from django.test import TestCase\nimport re\n# Create your tests here.\n\ndata = '12+3+1'\npriorty_num = 0\n\n\ndef add(num1, num2):\n priorty_num = 1\n return num1+num2\n\n\ndef minus(num1, num2):\n priorty_num = 2\n return num1-num2\n\n\ndef mul(num1, num2):\n priorty_num = 3\n return num1*num2\n\n\ndef div(num1, num2):\n priorty_num = 4\n if num2 == 0:\n print(\"division for zero\")\n else:\n return num1/num2\n\n\n'''\n 1. 우선순위가 높은 연산식부터 계산.\n 2. 12 + 3 -> 연산자를 파악해서 연산자의 앞뒤의 숫자를 연산자로 계산한다.\n \n'''\nresult1 = 0\ntmp_result = []\ntmp = re.findall(\"\\d+\", data)\noper = re.findall(\"\\D+\", data)\nprint (len(oper))\n\nif '+' in data:\n result = add(int(tmp[0]), int(tmp[1]))\n\nfor i in range(0, len(oper)):\n if oper[i] == '+':\n tmp_result.append(int(tmp[i]) + int(tmp[i+1]))\n\n\n\nprint (tmp_result)","sub_path":"tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":896,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"471769196","text":"GAME_SIZE = 4\n#SCORE_TO_WIN = 2048\n\nfrom game2048.game import Game\nfrom game2048.agents import ExpectiMaxAgent\n\n# save the dataset\n\nfor i in range(7):\n print(\"i = \", i)\n f1 = open(\"0_512.txt\", \"a\")\n f2 = open(\"512_1024.txt\", \"a\")\n f3 = open(\"1024_2048.txt\", \"a\")\n for j in range(8):\n print(\"j = \",j)\n game = Game(score_to_win=2048)\n agent = ExpectiMaxAgent(game=game)\n while True:\n direction = agent.step()\n scr=game.board.max()\n if(scr <= 256):f=f1\n elif(scr == 512):f=f2\n elif(scr == 1024):f=f3 \n if (game.end == 2):\n break\n #print (game.board)\n #print (\"direction: \", direction)\n for k in range(4):\n for p in range(4):\n print(game.board[k, p], file = f)\n print(direction, file = f) \n game.move(direction)\n f1.close()\n f2.close()\n f3.close()","sub_path":"generateDataSet.py","file_name":"generateDataSet.py","file_ext":"py","file_size_in_byte":969,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"418484416","text":"# encoding: utf-8\n#\n# Copyright 2016 Game Server Services, Inc. or its affiliates. All Rights\n# 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# A copy of the License is located at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# or in the \"license\" file accompanying this file. This file is distributed\n# on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n# express or implied. See the License for the specific language governing\n# permissions and limitations under the License.\n\nfrom gs2_core_client.Gs2Constant import Gs2Constant\nfrom gs2_core_client.AbstractGs2Client import AbstractGs2Client\nfrom aws_sdk_for_serverless.common import url_encoder\n\n\nclass Gs2ShowcaseClient(AbstractGs2Client):\n\n ENDPOINT = \"showcase\"\n\n def __init__(self, credential, region):\n \"\"\"\n コンストラクタ\n :param credential: 認証情報\n :type credential: IGs2Credential\n :param region: GS2リージョン\n :type region: str\n \"\"\"\n super(Gs2ShowcaseClient, self).__init__(credential, region)\n\n def get_current_showcase_master(self, request):\n \"\"\"\n 公開されているショーケースマスタを取得します
\n
:param request: リクエストパラメータ\n :type request: gs2_showcase_client.control.GetCurrentShowcaseMasterRequest.GetCurrentShowcaseMasterRequest\n :return: 結果\n :rtype: gs2_showcase_client.control.GetCurrentShowcaseMasterResult.GetCurrentShowcaseMasterResult\n \"\"\"\n query_strings = {}\n headers = {}\n if request.get_request_id() is not None:\n headers[\"X-GS2-REQUEST-ID\"] = request.get_request_id()\n from gs2_showcase_client.control.GetCurrentShowcaseMasterRequest import GetCurrentShowcaseMasterRequest\n\n from gs2_showcase_client.control.GetCurrentShowcaseMasterResult import GetCurrentShowcaseMasterResult\n return GetCurrentShowcaseMasterResult(self._do_get_request(\n url=Gs2Constant.ENDPOINT_HOST + \"/showcase/\" + str((\"null\" if request.get_showcase_name() is None or request.get_showcase_name() == \"\" else request.get_showcase_name())) + \"/item/master\",\n service=self.ENDPOINT,\n component=GetCurrentShowcaseMasterRequest.Constant.MODULE,\n target_function=GetCurrentShowcaseMasterRequest.Constant.FUNCTION,\n query_strings=query_strings,\n headers=headers\n ))\n\n def update_current_showcase_master(self, request):\n \"\"\"\n 公開するショーケースマスタを更新します
\n
\n :param request: リクエストパラメータ\n :type request: gs2_showcase_client.control.UpdateCurrentShowcaseMasterRequest.UpdateCurrentShowcaseMasterRequest\n :return: 結果\n :rtype: gs2_showcase_client.control.UpdateCurrentShowcaseMasterResult.UpdateCurrentShowcaseMasterResult\n \"\"\"\n body = { \n \"settings\": request.get_settings(),\n }\n\n headers = {}\n if request.get_request_id() is not None:\n headers[\"X-GS2-REQUEST-ID\"] = request.get_request_id()\n from gs2_showcase_client.control.UpdateCurrentShowcaseMasterRequest import UpdateCurrentShowcaseMasterRequest\n from gs2_showcase_client.control.UpdateCurrentShowcaseMasterResult import UpdateCurrentShowcaseMasterResult\n return UpdateCurrentShowcaseMasterResult(self._do_post_request(\n url=Gs2Constant.ENDPOINT_HOST + \"/showcase/\" + str((\"null\" if request.get_showcase_name() is None or request.get_showcase_name() == \"\" else request.get_showcase_name())) + \"/item/master\",\n service=self.ENDPOINT,\n component=UpdateCurrentShowcaseMasterRequest.Constant.MODULE,\n target_function=UpdateCurrentShowcaseMasterRequest.Constant.FUNCTION,\n body=body,\n headers=headers\n ))\n\n def create_item_group_master(self, request):\n \"\"\"\n 商品グループを新規作成します
\n
\n :param request: リクエストパラメータ\n :type request: gs2_showcase_client.control.CreateItemGroupMasterRequest.CreateItemGroupMasterRequest\n :return: 結果\n :rtype: gs2_showcase_client.control.CreateItemGroupMasterResult.CreateItemGroupMasterResult\n \"\"\"\n body = { \n \"name\": request.get_name(),\n \"itemNames\": request.get_item_names(),\n }\n\n headers = {}\n if request.get_request_id() is not None:\n headers[\"X-GS2-REQUEST-ID\"] = request.get_request_id()\n from gs2_showcase_client.control.CreateItemGroupMasterRequest import CreateItemGroupMasterRequest\n from gs2_showcase_client.control.CreateItemGroupMasterResult import CreateItemGroupMasterResult\n return CreateItemGroupMasterResult(self._do_post_request(\n url=Gs2Constant.ENDPOINT_HOST + \"/showcase/\" + str((\"null\" if request.get_showcase_name() is None or request.get_showcase_name() == \"\" else request.get_showcase_name())) + \"/master/itemGroup\",\n service=self.ENDPOINT,\n component=CreateItemGroupMasterRequest.Constant.MODULE,\n target_function=CreateItemGroupMasterRequest.Constant.FUNCTION,\n body=body,\n headers=headers\n ))\n\n def delete_item_group_master(self, request):\n \"\"\"\n 商品グループを削除します
\n
\n :param request: リクエストパラメータ\n :type request: gs2_showcase_client.control.DeleteItemGroupMasterRequest.DeleteItemGroupMasterRequest\n \"\"\"\n query_strings = {}\n headers = {}\n if request.get_request_id() is not None:\n headers[\"X-GS2-REQUEST-ID\"] = request.get_request_id()\n from gs2_showcase_client.control.DeleteItemGroupMasterRequest import DeleteItemGroupMasterRequest\n self._do_delete_request(\n url=Gs2Constant.ENDPOINT_HOST + \"/showcase/\" + str((\"null\" if request.get_showcase_name() is None or request.get_showcase_name() == \"\" else request.get_showcase_name())) + \"/master/itemGroup/\" + str((\"null\" if request.get_item_group_name() is None or request.get_item_group_name() == \"\" else request.get_item_group_name())) + \"\",\n service=self.ENDPOINT,\n component=DeleteItemGroupMasterRequest.Constant.MODULE,\n target_function=DeleteItemGroupMasterRequest.Constant.FUNCTION,\n query_strings=query_strings,\n headers=headers\n )\n\n def describe_item_group_master(self, request):\n \"\"\"\n 商品グループの一覧を取得します
\n
:param request: リクエストパラメータ\n :type request: gs2_showcase_client.control.DescribeItemGroupMasterRequest.DescribeItemGroupMasterRequest\n :return: 結果\n :rtype: gs2_showcase_client.control.DescribeItemGroupMasterResult.DescribeItemGroupMasterResult\n \"\"\"\n query_strings = {}\n if request.get_page_token() is not None:\n query_strings['pageToken'] = request.get_page_token()\n if request.get_limit() is not None:\n query_strings['limit'] = request.get_limit()\n headers = {}\n if request.get_request_id() is not None:\n headers[\"X-GS2-REQUEST-ID\"] = request.get_request_id()\n from gs2_showcase_client.control.DescribeItemGroupMasterRequest import DescribeItemGroupMasterRequest\n\n from gs2_showcase_client.control.DescribeItemGroupMasterResult import DescribeItemGroupMasterResult\n return DescribeItemGroupMasterResult(self._do_get_request(\n url=Gs2Constant.ENDPOINT_HOST + \"/showcase/\" + str((\"null\" if request.get_showcase_name() is None or request.get_showcase_name() == \"\" else request.get_showcase_name())) + \"/master/itemGroup\",\n service=self.ENDPOINT,\n component=DescribeItemGroupMasterRequest.Constant.MODULE,\n target_function=DescribeItemGroupMasterRequest.Constant.FUNCTION,\n query_strings=query_strings,\n headers=headers\n ))\n\n def get_item_group_master(self, request):\n \"\"\"\n 商品グループを取得します
\n
:param request: リクエストパラメータ\n :type request: gs2_showcase_client.control.GetItemGroupMasterRequest.GetItemGroupMasterRequest\n :return: 結果\n :rtype: gs2_showcase_client.control.GetItemGroupMasterResult.GetItemGroupMasterResult\n \"\"\"\n query_strings = {}\n headers = {}\n if request.get_request_id() is not None:\n headers[\"X-GS2-REQUEST-ID\"] = request.get_request_id()\n from gs2_showcase_client.control.GetItemGroupMasterRequest import GetItemGroupMasterRequest\n\n from gs2_showcase_client.control.GetItemGroupMasterResult import GetItemGroupMasterResult\n return GetItemGroupMasterResult(self._do_get_request(\n url=Gs2Constant.ENDPOINT_HOST + \"/showcase/\" + str((\"null\" if request.get_showcase_name() is None or request.get_showcase_name() == \"\" else request.get_showcase_name())) + \"/master/itemGroup/\" + str((\"null\" if request.get_item_group_name() is None or request.get_item_group_name() == \"\" else request.get_item_group_name())) + \"\",\n service=self.ENDPOINT,\n component=GetItemGroupMasterRequest.Constant.MODULE,\n target_function=GetItemGroupMasterRequest.Constant.FUNCTION,\n query_strings=query_strings,\n headers=headers\n ))\n\n def update_item_group_master(self, request):\n \"\"\"\n 商品グループを更新します
\n
\n :param request: リクエストパラメータ\n :type request: gs2_showcase_client.control.UpdateItemGroupMasterRequest.UpdateItemGroupMasterRequest\n :return: 結果\n :rtype: gs2_showcase_client.control.UpdateItemGroupMasterResult.UpdateItemGroupMasterResult\n \"\"\"\n body = { \n \"itemNames\": request.get_item_names(),\n }\n headers = {}\n if request.get_request_id() is not None:\n headers[\"X-GS2-REQUEST-ID\"] = request.get_request_id()\n from gs2_showcase_client.control.UpdateItemGroupMasterRequest import UpdateItemGroupMasterRequest\n from gs2_showcase_client.control.UpdateItemGroupMasterResult import UpdateItemGroupMasterResult\n return UpdateItemGroupMasterResult(self._do_put_request(\n url=Gs2Constant.ENDPOINT_HOST + \"/showcase/\" + str((\"null\" if request.get_showcase_name() is None or request.get_showcase_name() == \"\" else request.get_showcase_name())) + \"/master/itemGroup/\" + str((\"null\" if request.get_item_group_name() is None or request.get_item_group_name() == \"\" else request.get_item_group_name())) + \"\",\n service=self.ENDPOINT,\n component=UpdateItemGroupMasterRequest.Constant.MODULE,\n target_function=UpdateItemGroupMasterRequest.Constant.FUNCTION,\n body=body,\n headers=headers\n ))\n\n def create_item_master(self, request):\n \"\"\"\n 商品を新規作成します
\n
\n :param request: リクエストパラメータ\n :type request: gs2_showcase_client.control.CreateItemMasterRequest.CreateItemMasterRequest\n :return: 結果\n :rtype: gs2_showcase_client.control.CreateItemMasterResult.CreateItemMasterResult\n \"\"\"\n body = { \n \"name\": request.get_name(),\n \"currencyType\": request.get_currency_type(),\n \"price\": request.get_price(),\n \"itemType\": request.get_item_type(),\n }\n\n if request.get_meta() is not None:\n body[\"meta\"] = request.get_meta()\n if request.get_currency_money_name() is not None:\n body[\"currencyMoneyName\"] = request.get_currency_money_name()\n if request.get_currency_gold_name() is not None:\n body[\"currencyGoldName\"] = request.get_currency_gold_name()\n if request.get_currency_gold_pool_name() is not None:\n body[\"currencyGoldPoolName\"] = request.get_currency_gold_pool_name()\n if request.get_currency_consumable_item_item_pool_name() is not None:\n body[\"currencyConsumableItemItemPoolName\"] = request.get_currency_consumable_item_item_pool_name()\n if request.get_currency_consumable_item_item_name() is not None:\n body[\"currencyConsumableItemItemName\"] = request.get_currency_consumable_item_item_name()\n if request.get_currency_option() is not None:\n body[\"currencyOption\"] = request.get_currency_option()\n if request.get_item_money_name() is not None:\n body[\"itemMoneyName\"] = request.get_item_money_name()\n if request.get_item_gold_pool_name() is not None:\n body[\"itemGoldPoolName\"] = request.get_item_gold_pool_name()\n if request.get_item_gold_name() is not None:\n body[\"itemGoldName\"] = request.get_item_gold_name()\n if request.get_item_stamina_stamina_pool_name() is not None:\n body[\"itemStaminaStaminaPoolName\"] = request.get_item_stamina_stamina_pool_name()\n if request.get_item_consumable_item_item_pool_name() is not None:\n body[\"itemConsumableItemItemPoolName\"] = request.get_item_consumable_item_item_pool_name()\n if request.get_item_consumable_item_item_name() is not None:\n body[\"itemConsumableItemItemName\"] = request.get_item_consumable_item_item_name()\n if request.get_item_gacha_gacha_pool_name() is not None:\n body[\"itemGachaGachaPoolName\"] = request.get_item_gacha_gacha_pool_name()\n if request.get_item_gacha_gacha_name() is not None:\n body[\"itemGachaGachaName\"] = request.get_item_gacha_gacha_name()\n if request.get_item_amount() is not None:\n body[\"itemAmount\"] = request.get_item_amount()\n if request.get_item_option() is not None:\n body[\"itemOption\"] = request.get_item_option()\n if request.get_open_condition_type() is not None:\n body[\"openConditionType\"] = request.get_open_condition_type()\n if request.get_open_condition_limit_name() is not None:\n body[\"openConditionLimitName\"] = request.get_open_condition_limit_name()\n if request.get_open_condition_limit_counter_name() is not None:\n body[\"openConditionLimitCounterName\"] = request.get_open_condition_limit_counter_name()\n headers = {}\n if request.get_request_id() is not None:\n headers[\"X-GS2-REQUEST-ID\"] = request.get_request_id()\n from gs2_showcase_client.control.CreateItemMasterRequest import CreateItemMasterRequest\n from gs2_showcase_client.control.CreateItemMasterResult import CreateItemMasterResult\n return CreateItemMasterResult(self._do_post_request(\n url=Gs2Constant.ENDPOINT_HOST + \"/showcase/\" + str((\"null\" if request.get_showcase_name() is None or request.get_showcase_name() == \"\" else request.get_showcase_name())) + \"/master/item\",\n service=self.ENDPOINT,\n component=CreateItemMasterRequest.Constant.MODULE,\n target_function=CreateItemMasterRequest.Constant.FUNCTION,\n body=body,\n headers=headers\n ))\n\n def delete_item_master(self, request):\n \"\"\"\n 商品を削除します
\n
\n :param request: リクエストパラメータ\n :type request: gs2_showcase_client.control.DeleteItemMasterRequest.DeleteItemMasterRequest\n \"\"\"\n query_strings = {}\n headers = {}\n if request.get_request_id() is not None:\n headers[\"X-GS2-REQUEST-ID\"] = request.get_request_id()\n from gs2_showcase_client.control.DeleteItemMasterRequest import DeleteItemMasterRequest\n self._do_delete_request(\n url=Gs2Constant.ENDPOINT_HOST + \"/showcase/\" + str((\"null\" if request.get_showcase_name() is None or request.get_showcase_name() == \"\" else request.get_showcase_name())) + \"/master/item/\" + str((\"null\" if request.get_item_name() is None or request.get_item_name() == \"\" else request.get_item_name())) + \"\",\n service=self.ENDPOINT,\n component=DeleteItemMasterRequest.Constant.MODULE,\n target_function=DeleteItemMasterRequest.Constant.FUNCTION,\n query_strings=query_strings,\n headers=headers\n )\n\n def describe_item_master(self, request):\n \"\"\"\n 商品の一覧を取得します
\n
:param request: リクエストパラメータ\n :type request: gs2_showcase_client.control.DescribeItemMasterRequest.DescribeItemMasterRequest\n :return: 結果\n :rtype: gs2_showcase_client.control.DescribeItemMasterResult.DescribeItemMasterResult\n \"\"\"\n query_strings = {}\n if request.get_page_token() is not None:\n query_strings['pageToken'] = request.get_page_token()\n if request.get_limit() is not None:\n query_strings['limit'] = request.get_limit()\n headers = {}\n if request.get_request_id() is not None:\n headers[\"X-GS2-REQUEST-ID\"] = request.get_request_id()\n from gs2_showcase_client.control.DescribeItemMasterRequest import DescribeItemMasterRequest\n\n from gs2_showcase_client.control.DescribeItemMasterResult import DescribeItemMasterResult\n return DescribeItemMasterResult(self._do_get_request(\n url=Gs2Constant.ENDPOINT_HOST + \"/showcase/\" + str((\"null\" if request.get_showcase_name() is None or request.get_showcase_name() == \"\" else request.get_showcase_name())) + \"/master/item\",\n service=self.ENDPOINT,\n component=DescribeItemMasterRequest.Constant.MODULE,\n target_function=DescribeItemMasterRequest.Constant.FUNCTION,\n query_strings=query_strings,\n headers=headers\n ))\n\n def get_item_master(self, request):\n \"\"\"\n 商品を取得します
\n
:param request: リクエストパラメータ\n :type request: gs2_showcase_client.control.GetItemMasterRequest.GetItemMasterRequest\n :return: 結果\n :rtype: gs2_showcase_client.control.GetItemMasterResult.GetItemMasterResult\n \"\"\"\n query_strings = {}\n headers = {}\n if request.get_request_id() is not None:\n headers[\"X-GS2-REQUEST-ID\"] = request.get_request_id()\n from gs2_showcase_client.control.GetItemMasterRequest import GetItemMasterRequest\n\n from gs2_showcase_client.control.GetItemMasterResult import GetItemMasterResult\n return GetItemMasterResult(self._do_get_request(\n url=Gs2Constant.ENDPOINT_HOST + \"/showcase/\" + str((\"null\" if request.get_showcase_name() is None or request.get_showcase_name() == \"\" else request.get_showcase_name())) + \"/master/item/\" + str((\"null\" if request.get_item_name() is None or request.get_item_name() == \"\" else request.get_item_name())) + \"\",\n service=self.ENDPOINT,\n component=GetItemMasterRequest.Constant.MODULE,\n target_function=GetItemMasterRequest.Constant.FUNCTION,\n query_strings=query_strings,\n headers=headers\n ))\n\n def update_item_master(self, request):\n \"\"\"\n 商品を更新します
\n
\n :param request: リクエストパラメータ\n :type request: gs2_showcase_client.control.UpdateItemMasterRequest.UpdateItemMasterRequest\n :return: 結果\n :rtype: gs2_showcase_client.control.UpdateItemMasterResult.UpdateItemMasterResult\n \"\"\"\n body = { \n \"currencyType\": request.get_currency_type(),\n \"price\": request.get_price(),\n \"itemType\": request.get_item_type(),\n }\n if request.get_meta() is not None:\n body[\"meta\"] = request.get_meta()\n if request.get_currency_money_name() is not None:\n body[\"currencyMoneyName\"] = request.get_currency_money_name()\n if request.get_currency_gold_name() is not None:\n body[\"currencyGoldName\"] = request.get_currency_gold_name()\n if request.get_currency_gold_pool_name() is not None:\n body[\"currencyGoldPoolName\"] = request.get_currency_gold_pool_name()\n if request.get_currency_consumable_item_item_pool_name() is not None:\n body[\"currencyConsumableItemItemPoolName\"] = request.get_currency_consumable_item_item_pool_name()\n if request.get_currency_consumable_item_item_name() is not None:\n body[\"currencyConsumableItemItemName\"] = request.get_currency_consumable_item_item_name()\n if request.get_currency_option() is not None:\n body[\"currencyOption\"] = request.get_currency_option()\n if request.get_item_money_name() is not None:\n body[\"itemMoneyName\"] = request.get_item_money_name()\n if request.get_item_gold_pool_name() is not None:\n body[\"itemGoldPoolName\"] = request.get_item_gold_pool_name()\n if request.get_item_gold_name() is not None:\n body[\"itemGoldName\"] = request.get_item_gold_name()\n if request.get_item_stamina_stamina_pool_name() is not None:\n body[\"itemStaminaStaminaPoolName\"] = request.get_item_stamina_stamina_pool_name()\n if request.get_item_consumable_item_item_pool_name() is not None:\n body[\"itemConsumableItemItemPoolName\"] = request.get_item_consumable_item_item_pool_name()\n if request.get_item_consumable_item_item_name() is not None:\n body[\"itemConsumableItemItemName\"] = request.get_item_consumable_item_item_name()\n if request.get_item_gacha_gacha_pool_name() is not None:\n body[\"itemGachaGachaPoolName\"] = request.get_item_gacha_gacha_pool_name()\n if request.get_item_gacha_gacha_name() is not None:\n body[\"itemGachaGachaName\"] = request.get_item_gacha_gacha_name()\n if request.get_item_amount() is not None:\n body[\"itemAmount\"] = request.get_item_amount()\n if request.get_item_option() is not None:\n body[\"itemOption\"] = request.get_item_option()\n if request.get_open_condition_type() is not None:\n body[\"openConditionType\"] = request.get_open_condition_type()\n if request.get_open_condition_limit_name() is not None:\n body[\"openConditionLimitName\"] = request.get_open_condition_limit_name()\n if request.get_open_condition_limit_counter_name() is not None:\n body[\"openConditionLimitCounterName\"] = request.get_open_condition_limit_counter_name()\n headers = {}\n if request.get_request_id() is not None:\n headers[\"X-GS2-REQUEST-ID\"] = request.get_request_id()\n from gs2_showcase_client.control.UpdateItemMasterRequest import UpdateItemMasterRequest\n from gs2_showcase_client.control.UpdateItemMasterResult import UpdateItemMasterResult\n return UpdateItemMasterResult(self._do_put_request(\n url=Gs2Constant.ENDPOINT_HOST + \"/showcase/\" + str((\"null\" if request.get_showcase_name() is None or request.get_showcase_name() == \"\" else request.get_showcase_name())) + \"/master/item/\" + str((\"null\" if request.get_item_name() is None or request.get_item_name() == \"\" else request.get_item_name())) + \"\",\n service=self.ENDPOINT,\n component=UpdateItemMasterRequest.Constant.MODULE,\n target_function=UpdateItemMasterRequest.Constant.FUNCTION,\n body=body,\n headers=headers\n ))\n\n def buy_item(self, request):\n \"\"\"\n 購入処理を実行完了する為に必要となるスタンプシートを取得します。
\n スタンプシートの詳細は GS2 ドキュメントを参照してください。
\n
\n このAPIによって払い出されるスタンプシートが要求するタスクは以下のアクションの可能性があります。
\n
\n Gs2Money:VerifyByStampTask
\n Gs2Money:ConsumeWalletByStampTask
\n Gs2Gold:WithdrawFromWalletByStampTask
\n Gs2Stamina:ConsumeStaminaByStampTask
\n Gs2ConsumableItem:ConsumeInventoryByStampTask
\n Gs2Limit:UpCounterByStampTask
\n
\n このAPIによって払い出されるスタンプシートの完了は以下のアクションの可能性があります。
\n
\n Gs2Money:ChargeWalletByStampSheet
\n Gs2Gold:DepositIntoWalletByStampSheet
\n Gs2Stamina:ChangeStaminaByStampSheet
\n Gs2ConsumableItem:AcquisitionInventoryByStampSheet
\n
\n :param request: リクエストパラメータ\n :type request: gs2_showcase_client.control.BuyItemRequest.BuyItemRequest\n :return: 結果\n :rtype: gs2_showcase_client.control.BuyItemResult.BuyItemResult\n \"\"\"\n body = { \n \"keyName\": request.get_key_name(),\n }\n\n headers = {}\n if request.get_access_token() is not None:\n headers[\"X-GS2-ACCESS-TOKEN\"] = request.get_access_token()\n if request.get_request_id() is not None:\n headers[\"X-GS2-REQUEST-ID\"] = request.get_request_id()\n from gs2_showcase_client.control.BuyItemRequest import BuyItemRequest\n from gs2_showcase_client.control.BuyItemResult import BuyItemResult\n return BuyItemResult(self._do_post_request(\n url=Gs2Constant.ENDPOINT_HOST + \"/showcase/\" + str((\"null\" if request.get_showcase_name() is None or request.get_showcase_name() == \"\" else request.get_showcase_name())) + \"/item/\" + str((\"null\" if request.get_showcase_item_id() is None or request.get_showcase_item_id() == \"\" else request.get_showcase_item_id())) + \"\",\n service=self.ENDPOINT,\n component=BuyItemRequest.Constant.MODULE,\n target_function=BuyItemRequest.Constant.FUNCTION,\n body=body,\n headers=headers\n ))\n\n def describe_item(self, request):\n \"\"\"\n 陳列されている商品一覧を取得します
\n
:param request: リクエストパラメータ\n :type request: gs2_showcase_client.control.DescribeItemRequest.DescribeItemRequest\n :return: 結果\n :rtype: gs2_showcase_client.control.DescribeItemResult.DescribeItemResult\n \"\"\"\n query_strings = {}\n headers = {}\n if request.get_access_token() is not None:\n headers[\"X-GS2-ACCESS-TOKEN\"] = request.get_access_token()\n if request.get_request_id() is not None:\n headers[\"X-GS2-REQUEST-ID\"] = request.get_request_id()\n from gs2_showcase_client.control.DescribeItemRequest import DescribeItemRequest\n\n from gs2_showcase_client.control.DescribeItemResult import DescribeItemResult\n return DescribeItemResult(self._do_get_request(\n url=Gs2Constant.ENDPOINT_HOST + \"/showcase/\" + str((\"null\" if request.get_showcase_name() is None or request.get_showcase_name() == \"\" else request.get_showcase_name())) + \"/item\",\n service=self.ENDPOINT,\n component=DescribeItemRequest.Constant.MODULE,\n target_function=DescribeItemRequest.Constant.FUNCTION,\n query_strings=query_strings,\n headers=headers\n ))\n\n def get_item(self, request):\n \"\"\"\n 陳列されている商品を取得します
\n
:param request: リクエストパラメータ\n :type request: gs2_showcase_client.control.GetItemRequest.GetItemRequest\n :return: 結果\n :rtype: gs2_showcase_client.control.GetItemResult.GetItemResult\n \"\"\"\n query_strings = {}\n headers = {}\n if request.get_access_token() is not None:\n headers[\"X-GS2-ACCESS-TOKEN\"] = request.get_access_token()\n if request.get_request_id() is not None:\n headers[\"X-GS2-REQUEST-ID\"] = request.get_request_id()\n from gs2_showcase_client.control.GetItemRequest import GetItemRequest\n\n from gs2_showcase_client.control.GetItemResult import GetItemResult\n return GetItemResult(self._do_get_request(\n url=Gs2Constant.ENDPOINT_HOST + \"/showcase/\" + str((\"null\" if request.get_showcase_name() is None or request.get_showcase_name() == \"\" else request.get_showcase_name())) + \"/item/\" + str((\"null\" if request.get_showcase_item_id() is None or request.get_showcase_item_id() == \"\" else request.get_showcase_item_id())) + \"\",\n service=self.ENDPOINT,\n component=GetItemRequest.Constant.MODULE,\n target_function=GetItemRequest.Constant.FUNCTION,\n query_strings=query_strings,\n headers=headers\n ))\n\n def export_master(self, request):\n \"\"\"\n ショーケースマスターデータをエクスポートする
\n
:param request: リクエストパラメータ\n :type request: gs2_showcase_client.control.ExportMasterRequest.ExportMasterRequest\n :return: 結果\n :rtype: gs2_showcase_client.control.ExportMasterResult.ExportMasterResult\n \"\"\"\n query_strings = {}\n headers = {}\n if request.get_request_id() is not None:\n headers[\"X-GS2-REQUEST-ID\"] = request.get_request_id()\n from gs2_showcase_client.control.ExportMasterRequest import ExportMasterRequest\n\n from gs2_showcase_client.control.ExportMasterResult import ExportMasterResult\n return ExportMasterResult(self._do_get_request(\n url=Gs2Constant.ENDPOINT_HOST + \"/showcase/\" + str((\"null\" if request.get_showcase_name() is None or request.get_showcase_name() == \"\" else request.get_showcase_name())) + \"/master\",\n service=self.ENDPOINT,\n component=ExportMasterRequest.Constant.MODULE,\n target_function=ExportMasterRequest.Constant.FUNCTION,\n query_strings=query_strings,\n headers=headers\n ))\n\n def create_showcase_item_master(self, request):\n \"\"\"\n 陳列商品を新規作成します
\n
\n :param request: リクエストパラメータ\n :type request: gs2_showcase_client.control.CreateShowcaseItemMasterRequest.CreateShowcaseItemMasterRequest\n :return: 結果\n :rtype: gs2_showcase_client.control.CreateShowcaseItemMasterResult.CreateShowcaseItemMasterResult\n \"\"\"\n body = { \n \"category\": request.get_category(),\n \"priority\": request.get_priority(),\n }\n\n if request.get_item_name() is not None:\n body[\"itemName\"] = request.get_item_name()\n if request.get_item_group_name() is not None:\n body[\"itemGroupName\"] = request.get_item_group_name()\n if request.get_release_condition_type() is not None:\n body[\"releaseConditionType\"] = request.get_release_condition_type()\n if request.get_release_condition_schedule_name() is not None:\n body[\"releaseConditionScheduleName\"] = request.get_release_condition_schedule_name()\n if request.get_release_condition_schedule_event_name() is not None:\n body[\"releaseConditionScheduleEventName\"] = request.get_release_condition_schedule_event_name()\n headers = {}\n if request.get_request_id() is not None:\n headers[\"X-GS2-REQUEST-ID\"] = request.get_request_id()\n from gs2_showcase_client.control.CreateShowcaseItemMasterRequest import CreateShowcaseItemMasterRequest\n from gs2_showcase_client.control.CreateShowcaseItemMasterResult import CreateShowcaseItemMasterResult\n return CreateShowcaseItemMasterResult(self._do_post_request(\n url=Gs2Constant.ENDPOINT_HOST + \"/showcase/\" + str((\"null\" if request.get_showcase_name() is None or request.get_showcase_name() == \"\" else request.get_showcase_name())) + \"/master/showcaseItem\",\n service=self.ENDPOINT,\n component=CreateShowcaseItemMasterRequest.Constant.MODULE,\n target_function=CreateShowcaseItemMasterRequest.Constant.FUNCTION,\n body=body,\n headers=headers\n ))\n\n def delete_showcase_item_master(self, request):\n \"\"\"\n 陳列商品を削除します
\n
\n :param request: リクエストパラメータ\n :type request: gs2_showcase_client.control.DeleteShowcaseItemMasterRequest.DeleteShowcaseItemMasterRequest\n \"\"\"\n query_strings = {}\n headers = {}\n if request.get_request_id() is not None:\n headers[\"X-GS2-REQUEST-ID\"] = request.get_request_id()\n from gs2_showcase_client.control.DeleteShowcaseItemMasterRequest import DeleteShowcaseItemMasterRequest\n self._do_delete_request(\n url=Gs2Constant.ENDPOINT_HOST + \"/showcase/\" + str((\"null\" if request.get_showcase_name() is None or request.get_showcase_name() == \"\" else request.get_showcase_name())) + \"/master/showcaseItem/\" + str((\"null\" if request.get_category() is None or request.get_category() == \"\" else request.get_category())) + \"/\" + str((\"null\" if request.get_resource_id() is None or request.get_resource_id() == \"\" else request.get_resource_id())) + \"\",\n service=self.ENDPOINT,\n component=DeleteShowcaseItemMasterRequest.Constant.MODULE,\n target_function=DeleteShowcaseItemMasterRequest.Constant.FUNCTION,\n query_strings=query_strings,\n headers=headers\n )\n\n def describe_showcase_item_master(self, request):\n \"\"\"\n 陳列商品の一覧を取得します
\n
:param request: リクエストパラメータ\n :type request: gs2_showcase_client.control.DescribeShowcaseItemMasterRequest.DescribeShowcaseItemMasterRequest\n :return: 結果\n :rtype: gs2_showcase_client.control.DescribeShowcaseItemMasterResult.DescribeShowcaseItemMasterResult\n \"\"\"\n query_strings = {}\n if request.get_page_token() is not None:\n query_strings['pageToken'] = request.get_page_token()\n if request.get_limit() is not None:\n query_strings['limit'] = request.get_limit()\n headers = {}\n if request.get_request_id() is not None:\n headers[\"X-GS2-REQUEST-ID\"] = request.get_request_id()\n from gs2_showcase_client.control.DescribeShowcaseItemMasterRequest import DescribeShowcaseItemMasterRequest\n\n from gs2_showcase_client.control.DescribeShowcaseItemMasterResult import DescribeShowcaseItemMasterResult\n return DescribeShowcaseItemMasterResult(self._do_get_request(\n url=Gs2Constant.ENDPOINT_HOST + \"/showcase/\" + str((\"null\" if request.get_showcase_name() is None or request.get_showcase_name() == \"\" else request.get_showcase_name())) + \"/master/showcaseItem\",\n service=self.ENDPOINT,\n component=DescribeShowcaseItemMasterRequest.Constant.MODULE,\n target_function=DescribeShowcaseItemMasterRequest.Constant.FUNCTION,\n query_strings=query_strings,\n headers=headers\n ))\n\n def get_showcase_item_master(self, request):\n \"\"\"\n 陳列商品を取得します
\n
:param request: リクエストパラメータ\n :type request: gs2_showcase_client.control.GetShowcaseItemMasterRequest.GetShowcaseItemMasterRequest\n :return: 結果\n :rtype: gs2_showcase_client.control.GetShowcaseItemMasterResult.GetShowcaseItemMasterResult\n \"\"\"\n query_strings = {}\n headers = {}\n if request.get_request_id() is not None:\n headers[\"X-GS2-REQUEST-ID\"] = request.get_request_id()\n from gs2_showcase_client.control.GetShowcaseItemMasterRequest import GetShowcaseItemMasterRequest\n\n from gs2_showcase_client.control.GetShowcaseItemMasterResult import GetShowcaseItemMasterResult\n return GetShowcaseItemMasterResult(self._do_get_request(\n url=Gs2Constant.ENDPOINT_HOST + \"/showcase/\" + str((\"null\" if request.get_showcase_name() is None or request.get_showcase_name() == \"\" else request.get_showcase_name())) + \"/master/showcaseItem/\" + str((\"null\" if request.get_category() is None or request.get_category() == \"\" else request.get_category())) + \"/\" + str((\"null\" if request.get_resource_id() is None or request.get_resource_id() == \"\" else request.get_resource_id())) + \"\",\n service=self.ENDPOINT,\n component=GetShowcaseItemMasterRequest.Constant.MODULE,\n target_function=GetShowcaseItemMasterRequest.Constant.FUNCTION,\n query_strings=query_strings,\n headers=headers\n ))\n\n def update_showcase_item_master(self, request):\n \"\"\"\n 陳列商品を更新します
\n
\n :param request: リクエストパラメータ\n :type request: gs2_showcase_client.control.UpdateShowcaseItemMasterRequest.UpdateShowcaseItemMasterRequest\n :return: 結果\n :rtype: gs2_showcase_client.control.UpdateShowcaseItemMasterResult.UpdateShowcaseItemMasterResult\n \"\"\"\n body = { \n \"releaseConditionType\": request.get_release_condition_type(),\n \"priority\": request.get_priority(),\n }\n if request.get_release_condition_schedule_name() is not None:\n body[\"releaseConditionScheduleName\"] = request.get_release_condition_schedule_name()\n if request.get_release_condition_schedule_event_name() is not None:\n body[\"releaseConditionScheduleEventName\"] = request.get_release_condition_schedule_event_name()\n headers = {}\n if request.get_request_id() is not None:\n headers[\"X-GS2-REQUEST-ID\"] = request.get_request_id()\n from gs2_showcase_client.control.UpdateShowcaseItemMasterRequest import UpdateShowcaseItemMasterRequest\n from gs2_showcase_client.control.UpdateShowcaseItemMasterResult import UpdateShowcaseItemMasterResult\n return UpdateShowcaseItemMasterResult(self._do_put_request(\n url=Gs2Constant.ENDPOINT_HOST + \"/showcase/\" + str((\"null\" if request.get_showcase_name() is None or request.get_showcase_name() == \"\" else request.get_showcase_name())) + \"/master/showcaseItem/\" + str((\"null\" if request.get_category() is None or request.get_category() == \"\" else request.get_category())) + \"/\" + str((\"null\" if request.get_resource_id() is None or request.get_resource_id() == \"\" else request.get_resource_id())) + \"\",\n service=self.ENDPOINT,\n component=UpdateShowcaseItemMasterRequest.Constant.MODULE,\n target_function=UpdateShowcaseItemMasterRequest.Constant.FUNCTION,\n body=body,\n headers=headers\n ))\n\n def create_showcase(self, request):\n \"\"\"\n ショーケースを新規作成します
\n
\n :param request: リクエストパラメータ\n :type request: gs2_showcase_client.control.CreateShowcaseRequest.CreateShowcaseRequest\n :return: 結果\n :rtype: gs2_showcase_client.control.CreateShowcaseResult.CreateShowcaseResult\n \"\"\"\n body = { \n \"name\": request.get_name(),\n }\n\n if request.get_description() is not None:\n body[\"description\"] = request.get_description()\n if request.get_release_condition_trigger_script() is not None:\n body[\"releaseConditionTriggerScript\"] = request.get_release_condition_trigger_script()\n if request.get_buy_trigger_script() is not None:\n body[\"buyTriggerScript\"] = request.get_buy_trigger_script()\n headers = {}\n if request.get_request_id() is not None:\n headers[\"X-GS2-REQUEST-ID\"] = request.get_request_id()\n from gs2_showcase_client.control.CreateShowcaseRequest import CreateShowcaseRequest\n from gs2_showcase_client.control.CreateShowcaseResult import CreateShowcaseResult\n return CreateShowcaseResult(self._do_post_request(\n url=Gs2Constant.ENDPOINT_HOST + \"/showcase\",\n service=self.ENDPOINT,\n component=CreateShowcaseRequest.Constant.MODULE,\n target_function=CreateShowcaseRequest.Constant.FUNCTION,\n body=body,\n headers=headers\n ))\n\n def delete_showcase(self, request):\n \"\"\"\n ショーケースを削除します
\n
\n :param request: リクエストパラメータ\n :type request: gs2_showcase_client.control.DeleteShowcaseRequest.DeleteShowcaseRequest\n \"\"\"\n query_strings = {}\n headers = {}\n if request.get_request_id() is not None:\n headers[\"X-GS2-REQUEST-ID\"] = request.get_request_id()\n from gs2_showcase_client.control.DeleteShowcaseRequest import DeleteShowcaseRequest\n self._do_delete_request(\n url=Gs2Constant.ENDPOINT_HOST + \"/showcase/\" + str((\"null\" if request.get_showcase_name() is None or request.get_showcase_name() == \"\" else request.get_showcase_name())) + \"\",\n service=self.ENDPOINT,\n component=DeleteShowcaseRequest.Constant.MODULE,\n target_function=DeleteShowcaseRequest.Constant.FUNCTION,\n query_strings=query_strings,\n headers=headers\n )\n\n def describe_showcase(self, request):\n \"\"\"\n ショーケースの一覧を取得します
\n
:param request: リクエストパラメータ\n :type request: gs2_showcase_client.control.DescribeShowcaseRequest.DescribeShowcaseRequest\n :return: 結果\n :rtype: gs2_showcase_client.control.DescribeShowcaseResult.DescribeShowcaseResult\n \"\"\"\n query_strings = {}\n if request.get_page_token() is not None:\n query_strings['pageToken'] = request.get_page_token()\n if request.get_limit() is not None:\n query_strings['limit'] = request.get_limit()\n headers = {}\n if request.get_request_id() is not None:\n headers[\"X-GS2-REQUEST-ID\"] = request.get_request_id()\n from gs2_showcase_client.control.DescribeShowcaseRequest import DescribeShowcaseRequest\n\n from gs2_showcase_client.control.DescribeShowcaseResult import DescribeShowcaseResult\n return DescribeShowcaseResult(self._do_get_request(\n url=Gs2Constant.ENDPOINT_HOST + \"/showcase\",\n service=self.ENDPOINT,\n component=DescribeShowcaseRequest.Constant.MODULE,\n target_function=DescribeShowcaseRequest.Constant.FUNCTION,\n query_strings=query_strings,\n headers=headers\n ))\n\n def get_showcase(self, request):\n \"\"\"\n ショーケースを取得します
\n
:param request: リクエストパラメータ\n :type request: gs2_showcase_client.control.GetShowcaseRequest.GetShowcaseRequest\n :return: 結果\n :rtype: gs2_showcase_client.control.GetShowcaseResult.GetShowcaseResult\n \"\"\"\n query_strings = {}\n headers = {}\n if request.get_request_id() is not None:\n headers[\"X-GS2-REQUEST-ID\"] = request.get_request_id()\n from gs2_showcase_client.control.GetShowcaseRequest import GetShowcaseRequest\n\n from gs2_showcase_client.control.GetShowcaseResult import GetShowcaseResult\n return GetShowcaseResult(self._do_get_request(\n url=Gs2Constant.ENDPOINT_HOST + \"/showcase/\" + str((\"null\" if request.get_showcase_name() is None or request.get_showcase_name() == \"\" else request.get_showcase_name())) + \"\",\n service=self.ENDPOINT,\n component=GetShowcaseRequest.Constant.MODULE,\n target_function=GetShowcaseRequest.Constant.FUNCTION,\n query_strings=query_strings,\n headers=headers\n ))\n\n def get_showcase_status(self, request):\n \"\"\"\n ショーケースの状態を取得します
\n
:param request: リクエストパラメータ\n :type request: gs2_showcase_client.control.GetShowcaseStatusRequest.GetShowcaseStatusRequest\n :return: 結果\n :rtype: gs2_showcase_client.control.GetShowcaseStatusResult.GetShowcaseStatusResult\n \"\"\"\n query_strings = {}\n headers = {}\n if request.get_request_id() is not None:\n headers[\"X-GS2-REQUEST-ID\"] = request.get_request_id()\n from gs2_showcase_client.control.GetShowcaseStatusRequest import GetShowcaseStatusRequest\n\n from gs2_showcase_client.control.GetShowcaseStatusResult import GetShowcaseStatusResult\n return GetShowcaseStatusResult(self._do_get_request(\n url=Gs2Constant.ENDPOINT_HOST + \"/showcase/\" + str((\"null\" if request.get_showcase_name() is None or request.get_showcase_name() == \"\" else request.get_showcase_name())) + \"/status\",\n service=self.ENDPOINT,\n component=GetShowcaseStatusRequest.Constant.MODULE,\n target_function=GetShowcaseStatusRequest.Constant.FUNCTION,\n query_strings=query_strings,\n headers=headers\n ))\n\n def update_showcase(self, request):\n \"\"\"\n ショーケースを更新します
\n
\n :param request: リクエストパラメータ\n :type request: gs2_showcase_client.control.UpdateShowcaseRequest.UpdateShowcaseRequest\n :return: 結果\n :rtype: gs2_showcase_client.control.UpdateShowcaseResult.UpdateShowcaseResult\n \"\"\"\n body = { \n }\n if request.get_description() is not None:\n body[\"description\"] = request.get_description()\n if request.get_release_condition_trigger_script() is not None:\n body[\"releaseConditionTriggerScript\"] = request.get_release_condition_trigger_script()\n if request.get_buy_trigger_script() is not None:\n body[\"buyTriggerScript\"] = request.get_buy_trigger_script()\n headers = {}\n if request.get_request_id() is not None:\n headers[\"X-GS2-REQUEST-ID\"] = request.get_request_id()\n from gs2_showcase_client.control.UpdateShowcaseRequest import UpdateShowcaseRequest\n from gs2_showcase_client.control.UpdateShowcaseResult import UpdateShowcaseResult\n return UpdateShowcaseResult(self._do_put_request(\n url=Gs2Constant.ENDPOINT_HOST + \"/showcase/\" + str((\"null\" if request.get_showcase_name() is None or request.get_showcase_name() == \"\" else request.get_showcase_name())) + \"\",\n service=self.ENDPOINT,\n component=UpdateShowcaseRequest.Constant.MODULE,\n target_function=UpdateShowcaseRequest.Constant.FUNCTION,\n body=body,\n headers=headers\n ))\n","sub_path":"src/gs2_showcase_client/Gs2ShowcaseClient.py","file_name":"Gs2ShowcaseClient.py","file_ext":"py","file_size_in_byte":46617,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"498442702","text":"\"\"\"Programa que calcula el número de mutaciones puntuales (ditancia hammer) entre dos cadenas de ADN\"\"\"\r\n\r\ndata = open(\"rosalind_hamm.txt\", \"r\")\r\n\r\ns = data.read()\r\n\r\ncadena_inicial = []\r\ncadena_secundaria = []\r\ncuenta1 = 0\r\n\r\nfor i in s: #Ciclo que lee la primera cadena y la guarda en una variable\r\n\tif i != \"X\":\r\n\t\tcadena_inicial.append(i)\r\n\t\tcuenta1 += 1\r\n\telse:\r\n\t\tbreak\r\n\r\ncuenta2 = 0\r\n\r\nfor i in s: #Ciclo que lee la segunda cadena y la guarda en una variable\r\n\tif cuenta2 >= cuenta1 + 2:\r\n\t\tcadena_secundaria.append(i)\r\n\tcuenta2 += 1\r\n\r\nhammer = 0\r\n\r\nfor i in range(len(cadena_inicial)):\r\n\tif cadena_inicial[i] != cadena_secundaria[i]:\r\n\t\thammer += 1\r\n\r\ncadena_inicial = ''.join(cadena_inicial) #Instrucciones que convierten las cadenas de listas a strings\r\ncadena_secundaria = ''.join(cadena_secundaria)\r\n\r\nprint(cadena_inicial)\r\nprint(cadena_secundaria)\r\nprint(hammer)\r\n\r\nhammer = str(hammer)\r\n\r\nresp = open(\"resp_hamm.txt\", \"a\")\r\nresp.write(hammer)\r\nresp.close()\r\ndata.close()","sub_path":"rosalind/rosalind_hamm_1_code.py","file_name":"rosalind_hamm_1_code.py","file_ext":"py","file_size_in_byte":988,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"24075399","text":"# coding:UTF-8\n# 相比pygame1增加了输出按键名称、按键Unicode码、按键状态(按住ctrl、shift、alt)\n# 增加了鼠标在窗体内有动作时输出鼠标位置pos(左上角为原点)、相对上次运动距离rel、按键编号button(左中右三个键分别为123,设备相关)\n\nimport pygame,sys\npygame.init() \n\nscreen=pygame.display.set_mode((1280,720)) # 窗体大小\npygame.display.set_caption(\"pygame1\") # 标题\n\nwhile True: # 条件判断,注意大写\n for event in pygame.event.get(): # 当事件满足下列条件时:\n if event.type==pygame.QUIT: # 若事件类型为pygame.QUIT\n sys.exit() # 执行退出(来自sys包)\n elif event.type==pygame.KEYDOWN: # 事件为有键按下\n if event.unicode==\"\": # 若按下的键没有在pygame中对应的码,显示#\n print(\"[KEYDOWN]:\",\"#\",event.key,event.mod)\n else:\n print(\"[KEYDOWN]:\",event.unicode,event.key,event.mod)\n elif event.type==pygame.MOUSEMOTION: # 鼠标移动\n print(\"[MOUSEMOTION]:\",event.pos,event.rel,event.buttons)\n elif event.type==pygame.MOUSEBUTTONUP: # 鼠标按键松开\n print(\"[MOUSEBUTTONUP]:\",event.pos,event.button)\n elif event.type==pygame.MOUSEBUTTONDOWN: # 鼠标按键按下\n print(\"[MOUSEBUTTONDOWN]:\",event.pos,event.button)\n pygame.display.update() # 刷新显示(这是一个循环语句)","sub_path":"langnote/pygame/pygame4-1.py","file_name":"pygame4-1.py","file_ext":"py","file_size_in_byte":1472,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"475780514","text":"# https://arxiv.org/help/api/user-manual\n\n# built-in modules\nimport json\nimport logging\nimport os\nfrom pathlib import Path\nfrom typing import Dict, List, Tuple\n\n# external modules\nimport requests\nimport colorlog\nfrom bs4 import BeautifulSoup\n\nDEFAULT_DOWNLOAD_PATH = Path.home() / \"Downloads/ArXiv_Papers\"\n\n###########################################################################\n# Set up colored logger\n\nlogger = logging.getLogger()\nlogger.setLevel(logging.WARNING)\n\nsh = colorlog.StreamHandler()\nsh.setLevel(logging.DEBUG)\n\ncolor_formatter = colorlog.ColoredFormatter(\n fmt=\"%(log_color)s%(levelname)-8s%(reset)s %(log_color)s%(message)s\",\n datefmt=None,\n reset=True,\n log_colors={\n \"DEBUG\": \"green\",\n \"INFO\": \"cyan\",\n \"WARNING\": \"yellow\",\n \"ERROR\": \"red\",\n \"CRITICAL\": \"red,bg_yellow\",\n },\n secondary_log_colors={},\n style=\"%\",\n)\n\nsh.setFormatter(color_formatter)\nlogger.addHandler(sh)\n\n###########################################################################\n\n\ndef get_local_paper_folder_path() -> Path:\n download_path = os.environ.get(\"ARXIV_DOWNLOAD_FOLDER\")\n if download_path:\n download_path = Path(download_path).resolve()\n if not download_path.is_dir():\n logger.error(\n f\"Invalid ARXIV_DOWNLOAD_FOLDER: '{download_path}' is not a directory.\"\n )\n raise Exception(\n f\"Invalid ARXIV_DOWNLOAD_FOLDER: '{download_path}' is not a directory.\"\n )\n else:\n download_path = Path(DEFAULT_DOWNLOAD_PATH).resolve()\n if not download_path.is_dir():\n logger.debug(f\"Creating Directory: '{DEFAULT_DOWNLOAD_PATH}'\")\n os.makedirs(str(DEFAULT_DOWNLOAD_PATH))\n \n return download_path\n\n\ndef process_arxiv_url(url: str) -> Tuple[str]:\n def get_paper_id_from_url(url) -> str:\n while \"/\" in url:\n slash_idx = url.find(\"/\")\n url = url[slash_idx + 1 :]\n if url.endswith(\".pdf\"):\n return url[:-4]\n else:\n return url\n \n paper_id = get_paper_id_from_url(url)\n \n if \"arxiv.org/abs\" in url:\n # url is abstract page\n paper_url = url\n pdf_url = f\"https://arxiv.org/pdf/{paper_id}.pdf\"\n elif \"arxiv.org/pdf\" in url:\n # url is pdf page\n paper_url = f\"https://arxiv.org/abs/{paper_id}\"\n pdf_url = url\n else:\n logger.error(\"Unexpected URL Error by arxiv URL Handler.\")\n raise Exception(\"Unexpected URL Error by arxiv URL Handler.\")\n \n return paper_id, paper_url, pdf_url\n\n\ndef process_url(url: str) -> Dict[str, str]:\n if \"arxiv.org\" in url:\n src_website = \"arxiv\"\n paper_id, paper_url, pdf_url = process_arxiv_url(url)\n else:\n logger.error(\"URL not supported\")\n raise Exception(\"URL not supported\")\n\n tmp_paper_dict = {\n \"paper_id\": paper_id,\n \"paper_url\": paper_url,\n \"pdf_url\": pdf_url,\n \"src_website\": src_website,\n }\n\n return tmp_paper_dict\n\n\ndef get_paper_from_arxiv(tmp_paper_dict: Dict[str, str]) -> Dict[str, str]:\n logger.setLevel(logging.DEBUG)\n logger.debug(\"Processing...\")\n logger.setLevel(logging.WARNING)\n paper_url = tmp_paper_dict.get(\"paper_url\")\n paper_id = tmp_paper_dict.get(\"paper_id\")\n response = requests.get(paper_url)\n\n if response.status_code != 200:\n logger.error(f\"Cannot connect to {paper_url}\")\n raise Exception(f\"Cannot connect to {paper_url}\")\n\n # make soup\n soup = BeautifulSoup(response.text, \"html.parser\")\n\n # get TITLE\n result = soup.find(\"h1\", class_=\"title mathjax\")\n tmp = [i.string for i in result]\n paper_title = tmp.pop()\n tmp_paper_dict[\"title\"] = paper_title\n logger.setLevel(logging.DEBUG)\n logger.debug(f\"Paper Title: {paper_title}\")\n logger.setLevel(logging.WARNING)\n\n # get AUTHORS\n result = soup.find(\"div\", class_=\"authors\")\n author_list = [i.string.strip() for i in result]\n author_list.pop(0)\n while \",\" in author_list:\n author_list.remove(\",\")\n tmp_paper_dict[\"authors\"] = author_list\n\n # get ABSTRACT\n result = soup.find(\"blockquote\", class_=\"abstract mathjax\")\n tmp = [i.string for i in result]\n paper_abstract = tmp.pop()\n tmp = paper_abstract.split(\"\\n\")\n paper_abstract = \" \".join(tmp)\n tmp_paper_dict[\"abstract\"] = paper_abstract.strip()\n\n # get COMMENTS\n result = soup.find(\"td\", class_=\"tablecell comments mathjax\")\n if result:\n comments = [i.string.strip() if i.string else \"\" for i in result]\n comments = \" \".join(comments)\n else:\n comments = \"\"\n tmp_paper_dict[\"comments\"] = comments.strip()\n\n # get PWC (paper with code)\n # API: https://arxiv.paperswithcode.com/api/v0/papers/{paper_id}\n pwc_url = f\"https://arxiv.paperswithcode.com/api/v0/papers/{paper_id}\"\n pwc_response = requests.get(pwc_url)\n if pwc_response.status_code == 200:\n pwc = pwc_response.text\n pwc = json.loads(pwc)\n official_code_urls: list = pwc.get(\"all_official\", [])\n official_code_urls: list = [i.get(\"url\") for i in official_code_urls]\n pwc_page_url: str = pwc.get(\"paper_url\", \"\")\n else:\n official_code_urls = []\n pwc_page_url = \"\"\n tmp_paper_dict[\"official_code_urls\"] = official_code_urls\n tmp_paper_dict[\"pwc_page_url\"] = pwc_page_url.strip()\n\n # get BIBTEX\n bibtex_url = f\"https://arxiv.org/bibtex/{paper_id}\"\n bibtex_response = requests.get(bibtex_url)\n if bibtex_response.status_code == 200:\n bibtex = bibtex_response.text\n else:\n bibtex = \"\"\n tmp_paper_dict[\"bibtex\"] = bibtex.strip()\n\n return tmp_paper_dict\n\n\ndef download_pdf(paper_dict: Dict[str, str]) -> None:\n filepath = Path(paper_dict.get(\"filepath\"))\n if filepath.is_file():\n logger.debug(f\"Paper PDF already exists at: {filepath}\")\n else:\n logger.debug(f\"Downloading...\")\n logger.setLevel(logging.WARNING)\n response = requests.get(paper_dict.get(\"pdf_url\"))\n with filepath.open(mode=\"wb\") as f:\n f.write(response.content)\n logger.setLevel(logging.DEBUG)\n logger.debug(f\"Done! Paper saved to {filepath}\")\n return\n\n\ndef add_to_paper_list(download_dir: Path, paper_dict: Dict[str, str]) -> None:\n paper_list_path = Path(download_dir) / \"000_Paper_List.json\"\n paper_id = paper_dict.get(\"paper_id\")\n if not paper_list_path.is_file():\n paper_list = dict()\n paper_list[paper_id] = paper_dict\n with paper_list_path.open(mode=\"w\") as f:\n json.dump(paper_list, f, indent=4)\n else:\n with paper_list_path.open() as f:\n paper_list = json.load(f)\n if paper_id not in paper_list:\n paper_list[paper_id] = paper_dict\n with paper_list_path.open(mode=\"w\") as f:\n json.dump(paper_list, f, indent=4)\n return\n\n\ndef create_paper_note(download_dir: Path, paper_dict: Dict[str, str]) -> None:\n paper_id = paper_dict.get(\"paper_id\", \"\").strip()\n note_path = Path(download_dir) / f\"{paper_id}_Notes.md\"\n paper_url = paper_dict.get(\"paper_url\", \"\")\n pdf_url = paper_dict.get(\"pdf_url\", \"\")\n title = paper_dict.get(\"title\", \"\")\n authors: list = paper_dict.get(\"authors\", [])\n authors: list = [f\"- {name}\" for name in authors]\n authors: str = \"\\n\".join(authors)\n abstract = paper_dict.get(\"abstract\", \"\")\n comments = paper_dict.get(\"comments\", \"\")\n bibtex = paper_dict.get(\"bibtex\", \"\")\n official_code_urls: list = paper_dict.get(\"official_code_urls\", [])\n official_code_urls: list = [f\"- [{url}]({url})\" for url in official_code_urls]\n official_code_urls: str = \"\\n\".join(official_code_urls)\n pwc_page_url = paper_dict.get(\"pwc_page_url\", \"\")\n if pwc_page_url:\n pwc_page_url = f\"- [{pwc_page_url}]({pwc_page_url})\"\n\n # markdown content text\n md_content = f\"\"\"\n# {title}\n\n[arXiv]({paper_url}), [PDF]({pdf_url})\n\n## Authors\n\n{authors}\n\n## Abstract\n\n{abstract}\n\n## Comments\n\n{comments}\n\n## Source Code\n\nOfficial Code\n\n{official_code_urls}\n\nCommunity Code\n\n{pwc_page_url}\n\n## Bibtex\n\n```tex\n{bibtex}\n```\n\n## Notes\n\nType your reading notes here...\n\n\"\"\"\n if not note_path.is_file():\n with note_path.open(mode=\"w\") as f:\n f.write(md_content)\n return\n\n\ndef dl_paper(url: str) -> None:\n \"\"\"\n Get a Paper dictionary from a supported URL\n \"\"\"\n try:\n download_dir: Path = get_local_paper_folder_path()\n except Exception as e:\n logger.exception(e)\n logger.error(\"Abort: Environment Variable Error\")\n return\n\n try:\n tmp_paper_dict = process_url(url)\n except Exception as err:\n logger.error(f\"Abort: Error while processing URL: {url}\")\n return\n\n # verify expected keys are present\n for key in (\"paper_id\", \"paper_url\", \"pdf_url\", \"src_website\"):\n if not key in tmp_paper_dict:\n logger.error(f\"Abort: Error while processing URL: {url}\")\n return\n\n # start scraping from source website\n src_website = tmp_paper_dict.get(\"src_website\")\n if src_website == \"arxiv\":\n try:\n paper_dict = get_paper_from_arxiv(tmp_paper_dict)\n except Exception as err:\n logger.error(err)\n logger.error(\"Abort: Error while getting paper\")\n return\n else:\n logger.error(f\"Invalid source website: '{src_website}'\")\n return\n\n # adjust logging level\n logger.setLevel(logging.DEBUG)\n\n # construct filename\n paper_title = paper_dict.get(\"title\", \"\")\n paper_id = paper_dict.get(\"paper_id\", \"\").strip()\n paper_title = paper_title.strip().replace(\" \", \"_\")\n filepath = download_dir / f\"{paper_id}_{paper_title}.pdf\"\n paper_dict[\"filepath\"] = str(filepath)\n\n # download paper\n try:\n download_pdf(paper_dict)\n except Exception as err:\n logger.error(\"Error while downloading paper\")\n return\n\n\ndef add_paper(url: str) -> None:\n \"\"\"\n Get a Paper dictionary from a supported URL\n \"\"\"\n try:\n download_dir: Path = get_local_paper_folder_path()\n except Exception as e:\n logger.exception(e)\n logger.error(\"Abort: Environment Variable Error\")\n return\n\n try:\n tmp_paper_dict = process_url(url)\n except Exception as err:\n logger.error(f\"Abort: Error while processing URL: {url}\")\n return\n\n # verify expected keys are present\n for key in (\"paper_id\", \"paper_url\", \"pdf_url\", \"src_website\"):\n if not key in tmp_paper_dict:\n logger.error(f\"Abort: Error while processing URL: {url}\")\n return\n\n # start scraping from source website\n src_website = tmp_paper_dict.get(\"src_website\")\n if src_website == \"arxiv\":\n try:\n paper_dict = get_paper_from_arxiv(tmp_paper_dict)\n except Exception as err:\n logger.error(err)\n logger.error(\"Abort: Error while getting paper\")\n return\n else:\n logger.error(f\"Invalid source website: '{src_website}'\")\n return\n\n # adjust logging level\n logger.setLevel(logging.DEBUG)\n\n # construct filename\n paper_title = paper_dict.get(\"title\", \"\")\n paper_id = paper_dict.get(\"paper_id\", \"\").strip()\n paper_title = paper_title.strip().replace(\" \", \"_\")\n filepath = download_dir / f\"{paper_id}_{paper_title}.pdf\"\n paper_dict[\"filepath\"] = str(filepath)\n\n # download paper\n try:\n download_pdf(paper_dict)\n except Exception as err:\n logger.error(\"Error while downloading paper\")\n return\n\n # update paper list\n try:\n add_to_paper_list(download_dir, paper_dict)\n except Exception as err:\n logger.warning(\"Error while updating paper list\")\n return\n\n # Create paper notes\n try:\n create_paper_note(download_dir, paper_dict)\n except Exception as err:\n logger.warning(\"Error while creating note\")\n return\n\n\nif __name__ == \"__main__\":\n add_paper(\"https://arxiv.org/abs/1506.01497\")\n","sub_path":"arxiv_dl/arxiv_dl.py","file_name":"arxiv_dl.py","file_ext":"py","file_size_in_byte":12073,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"138701813","text":"from __future__ import annotations\n\nimport os\nimport sys\nfrom unittest import mock\n\nimport pytest\n\nfrom dxtbx.model import ExperimentList\n\nfrom xia2.Handlers.Phil import PhilIndex\nfrom xia2.Modules.Indexer.XDSIndexer import XDSIndexer\nfrom xia2.Schema.XCrystal import XCrystal\nfrom xia2.Schema.XSample import XSample\nfrom xia2.Schema.XSweep import XSweep\nfrom xia2.Schema.XWavelength import XWavelength\n\n\ndef exercise_xds_indexer(dials_data, tmp_path, nproc=None):\n if nproc is not None:\n PhilIndex.params.xia2.settings.multiprocessing.nproc = nproc\n\n template = dials_data(\"insulin\", pathlib=True) / \"insulin_1_###.img\"\n\n indexer = XDSIndexer()\n indexer.set_working_directory(os.fspath(tmp_path))\n\n experiments = ExperimentList.from_templates([template])\n imageset = experiments.imagesets()[0]\n indexer.add_indexer_imageset(imageset)\n\n cryst = XCrystal(\"CRYST1\", None)\n wav = XWavelength(\"WAVE1\", cryst, indexer.get_wavelength())\n samp = XSample(\"X1\", cryst)\n directory, image = os.path.split(imageset.get_path(1))\n sweep = XSweep(\"SWEEP1\", wav, samp, directory=directory, image=image)\n indexer.set_indexer_sweep(sweep)\n\n indexer.index()\n\n assert indexer.get_indexer_cell() == pytest.approx(\n (78.076, 78.076, 78.076, 90, 90, 90), abs=1\n ), indexer.get_indexer_cell()\n experiment = indexer.get_indexer_experiment_list()[0]\n sgi = experiment.crystal.get_space_group().info()\n assert sgi.type().number() == 197\n\n beam_centre = indexer.get_indexer_beam_centre()\n assert beam_centre == pytest.approx((94.4221, 94.5096), abs=1e-1)\n assert indexer.get_indexer_images() == [(1, 5), (20, 24), (41, 45)]\n print(indexer.get_indexer_experiment_list()[0].crystal)\n print(indexer.get_indexer_experiment_list()[0].detector)\n\n # test serialization of indexer\n json_str = indexer.as_json()\n print(json_str)\n indexer2 = XDSIndexer.from_json(string=json_str)\n indexer2.index()\n\n assert indexer.get_indexer_cell() == pytest.approx(indexer2.get_indexer_cell())\n assert indexer.get_indexer_beam_centre() == pytest.approx(\n indexer2.get_indexer_beam_centre()\n )\n assert indexer.get_indexer_images() == [\n tuple(i) for i in indexer2.get_indexer_images()\n ]\n\n indexer.eliminate()\n indexer2.eliminate()\n\n assert indexer.get_indexer_cell() == pytest.approx(indexer2.get_indexer_cell())\n assert indexer.get_indexer_lattice() == \"hR\"\n assert indexer2.get_indexer_lattice() == \"hR\"\n\n\ndef test_xds_indexer_serial(regression_test, ccp4, xds, dials_data, run_in_tmp_path):\n with mock.patch.object(sys, \"argv\", []):\n exercise_xds_indexer(dials_data, run_in_tmp_path, nproc=1)\n","sub_path":"tests/Modules/Indexer/test_XDS_indexer.py","file_name":"test_XDS_indexer.py","file_ext":"py","file_size_in_byte":2699,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"391654990","text":"import cherrypy\nimport os\nimport sys\n# sys.path.append(\"D:/Projects/Prometheus/src\") \nimport pandas\nfrom datetime import datetime as dt\nfrom sqlalchemy import create_engine\nfrom sqlalchemy.orm import sessionmaker\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy import Column , String, DATE, Table, MetaData\nfrom sqlalchemy.pool import NullPool\nfrom com.lunatus.phormio.QuandlData import QuandlData as qd\nfrom com.lunatus.phormio.analytics import Analytics\nimport numpy as np\nimport math\nimport random\nimport string\nimport scipy.stats as stats\nimport requests\nfrom lxml import etree\nimport time\nbase_dir = os.path.abspath(os.path.dirname(__file__))\nnow = dt.now()\n\nclass Prometheus(object):\n \n def initializeDB(self, user, password):\n engine_string = \"mysql+mysqlconnector://{}:{}@localhost:3306/test\".format(user, password)\n print(engine_string)\n cherrypy.log(\"Intializing Database\")\n self.engine = create_engine(engine_string, pool_size=50, max_overflow=0)\n Base = declarative_base()\n Base.metadata.create_all(self.engine)\n meta = MetaData(bind=self.engine)\n self.companies = Table('companies', meta, autoload=True, autoload_with=self.engine)\n self.Session = sessionmaker(bind=self.engine)\n self.request_no = 0\n @cherrypy.expose\n @cherrypy.tools.json_out()\n def getSearchResults(self, search_term):\n cherrypy.response.headers[\"Access-Control-Allow-Origin\"] = \"*\"\n self.request_no+=1\n \n cherrypy.log(\"Request {} received\".format(self.request_no))\n cherrypy.log(\"Execute engine.connect()\")\n self.conn = self.engine.connect()\n cherrypy.log(\"Creating session {}\".format(self.request_no))\n self.session = self.Session(bind=self.conn)\n cherrypy.log(\"Session {} opened\".format(self.request_no,))\n return_arr = []\n cherrypy.log(\"Running query\")\n \n results = self.session.query(self.companies).\\\n filter(self.companies.c.name.like('%%%s%%' %(search_term,))).limit(20).all()\n cherrypy.log(\"Retrieved results\")\n if len(results) == 0:\n dictionary={}\n dictionary[\"ticker\"]=\"none\"\n dictionary[\"name\"]=\"none\"\n dictionary[\"quandl_code\"]=\"none\"\n return_arr.append(dictionary)\n for result in results:\n dictionary={}\n quandl_code = result[0]\n name = result[1]\n splits = name.split(' ')\n ticker = splits[len(splits)-1][1:-1]\n dictionary[\"ticker\"]=ticker\n dictionary[\"quandl_code\"]=quandl_code\n dictionary[\"name\"]=name\n return_arr.append(dictionary)\n cherrypy.log(\"Committing session {}\".format(self.request_no,))\n self.session.commit()\n cherrypy.log(\"Closing session\")\n self.session.close()\n self.conn.close()\n cherrypy.log(\"Returning result\")\n# dictionary={}\n# dictionary[\"ticker\"]=\"test\"\n# dictionary[\"name\"]=\"test\"\n# dictionary[\"quandl_code\"]=\"test\"\n# return_arr.append(dictionary)\n \n return return_arr\n @cherrypy.expose\n @cherrypy.tools.json_out()\n def getBasicData(self, quandl_code, ticker):\n cherrypy.response.headers[\"Access-Control-Allow-Origin\"] = \"*\"\n basic_data = {}\n yql = \"https://query.yahooapis.com/v1/public/yql?\"\\\n \"q=select%20*%20from%20yahoo.finance.quotes%20where%20symbol\"\\\n \"%20in%20(%22{0}%22)&diagnostics=true&env=store%3A%2F%2F\"\\\n \"datatables.org%2Falltableswithkeys\".format(ticker,)\n res = requests.get(yql)\n root = etree.fromstring(res.content)\n bid_price = float(root.find(\".//BidRealtime\").text)\n ask_price = float(root.find(\".//AskRealtime\").text)\n day_low = float(root.find(\".//DaysLow\").text)\n day_high = float(root.find(\".//DaysHigh\").text)\n market_cap = root.find(\".//MarketCapitalization\").text\n last_price = float(root.find(\".//LastTradePriceOnly\").text)\n day_open = float(root.find(\".//Open\").text)\n previous_close = float(root.find(\".//PreviousClose\").text)\n last_trade_date = root.find(\".//LastTradeDate\").text\n volume = int(root.find(\".//Volume\").text)\n stock_exchange = root.find(\".//StockExchange\").text\n last_trade_time = root.find(\".//LastTradeTime\").text\n price_change = last_price - previous_close\n pct_change = last_price/previous_close - 1\n basic_data[\"bid_price\"] = bid_price\n basic_data[\"ask_price\"] = ask_price\n basic_data[\"day_low\"] = day_low\n basic_data[\"day_high\"] = day_high\n basic_data[\"market_cap\"] = market_cap\n basic_data[\"last_price\"] = last_price\n basic_data[\"open\"] = day_open\n basic_data[\"previous_close\"] = previous_close\n basic_data[\"last_trade_date\"] = last_trade_date\n basic_data[\"volume\"] = volume\n basic_data[\"price_change\"] = price_change\n basic_data[\"pct_change\"] = pct_change\n basic_data[\"stock_exchange\"] = stock_exchange\n basic_data[\"last_trade_time\"] = last_trade_time\n \n return basic_data\n @cherrypy.expose\n @cherrypy.tools.json_out()\n def getQuandlData(self, quandl_code, ticker, start_date=\"\", end_date=\"\"):\n cherrypy.response.headers[\"Access-Control-Allow-Origin\"] = \"*\"\n \n token = ''.join(random.sample(string.hexdigits,int(16)))\n codes = [quandl_code, \"YAHOO/INDEX_GSPC\"]\n params = {}\n data = {}\n params[\"start_date\"] = start_date\n params[\"end_date\"] = end_date\n d = qd(*codes, **params)\n concat_d = pandas.concat(d.getData(), axis=1)\n returns_data = concat_d.ix[:,[3,10]]\n returns_data.columns = [ticker, \"market\"]\n pct_returns = returns_data.pct_change()\n log_returns = np.log(pct_returns + 1)\n a = Analytics(log_returns)\n equation = \"%s ~ market\" % (ticker,)\n a.setOLSFit(equation)\n a.setSummary()\n mean = a.getSummary().loc[\"mean\", ticker]\n sigma = a.getSummary().loc[\"std\", ticker]\n n = len(log_returns[ticker])-1\n scale = sigma/math.sqrt(n)\n interval = stats.norm.interval(0.95, loc=mean, scale=scale)\n ub_ret = interval[1]\n lb_ret = interval[0]\n ub_price = math.exp(interval[1])*returns_data.ix[-1,0]\n lb_price = math.exp(interval[0])*returns_data.ix[-1,0]\n adj_r = a.getOLSFit().rsquared_adj\n p_val = a.getOLSFit().pvalues[\"market\"]\n beta = a.getOLSFit().params[\"market\"]\n observations = a.getOLSFit().nobs\n degrees_freeddom = a.getOLSFit().df_model\n data[\"sigma\"]= sigma\n data[\"mean\"] = mean\n data[\"ub_ret\"] = ub_ret\n data[\"lb_ret\"] = lb_ret\n data[\"ub_price\"] = ub_price\n data[\"lb_price\"] = lb_price\n data[\"adj_r\"] = adj_r\n data[\"p_val\"] = p_val\n data[\"beta\"] = beta\n data[\"degrees_freedom\"] = degrees_freeddom\n data[\"observations\"] = observations\n data[\"token\"] = token\n return data\n @cherrypy.expose\n def getRawData(self, token):\n cherrypy.response.headers[\"Access-Control-Allow-Origin\"] = \"*\"\n# cherrypy.response.headers['Content-Disposition'] = 'attachment; filename=\"data.csv\"'\n# d = cherrypy.session[token]\n return None\n \n# if __name__ == \"__main__\": \n# cherrypy.quickstart(Prometheus(), \"/\", config=\"app.conf\") \n \n ","sub_path":"Prometheus/src/com/lunatus/phormio/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":7541,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"546631244","text":"class Interval:\n def __init__(self, s=0, e=0):\n self.start = s\n self.end = e\nclass MergeInter:\n def merge(self, intervals):\n intervals = sorted(intervals,key = lambda k:k[0])\n res = []\n for i in intervals:\n if res and res[-1][-1] >= i[0]:\n res[-1][-1] = max(res[-1][-1],i[-1])\n else:\n res.append(i)\n return res\n \n","sub_path":"SolutionsPY/MergeIntervals.py","file_name":"MergeIntervals.py","file_ext":"py","file_size_in_byte":428,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"207715796","text":"#!/usr/bin/python\n\n#ref : https://stackoverflow.com/questions/2921847/what-does-the-star-operator-mean-in-python?lq=1\n\n#cmd : clear; python pointer.py\n\n\ndef mysum(a, b):\n return a + b\n\nvalues = (1, 2)\n\n# the use of * will unpack the tuple so that it actually executes as:\n# s = mysum(1, 2)\n\ns = mysum(*values)\n\nprint(s)\n\n\n# example 2\n\ndef mysum(*values):\n s = 0\n for v in values:\n s = s + v\n return s\n\ns = mysum(1, 2, 3, 4, 5)\nprint(s)\n\n\n# Built in method\nprint(sum([1, 2, 3, 4, 5]))\n","sub_path":"Python/pointers/pointer.py","file_name":"pointer.py","file_ext":"py","file_size_in_byte":506,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"500810982","text":"import json\nimport os\nimport requests\n\nfrom ace_logger import Logging\nfrom db_utils import DB\n\nfrom requests.auth import HTTPBasicAuth\n\nlogging = Logging()\n\ndb_config = {\n 'host': os.environ['HOST_IP'],\n 'user': os.environ['LOCAL_DB_USER'],\n 'password': os.environ['LOCAL_DB_PASSWORD'],\n 'port': os.environ['LOCAL_DB_PORT'],\n}\n\ndef get_api_id(button_id, queue_db):\n query = 'SELECT * FROM `button_functions` WHERE id IN (SELECT `function_id` FROM `button_function_mapping` WHERE `button_id`=(SELECT id FROM `button_definition` WHERE `button_id`=%s)) AND `api_id` IS NOT NULL'\n button_func = queue_db.execute(query, params=[button_id])\n\n if button_func.empty:\n logging.debug(f'Could not find function mapped to button `{button_id}`')\n return\n\n return list(button_func['api_id'])[0]\n\ndef parse_params(parameters):\n logging.info(f'Parsing parameters')\n\n parameters = json.loads(parameters)\n\n static_params = parameters.get('static_args', {})\n url_params = parameters.get('url_args', {})\n dynamic_params = parameters.get('dynamic_args', [])\n\n logging.debug(f'Static: {static_params}')\n logging.debug(f'URL: {url_params}')\n logging.debug(f'Dynamic: {dynamic_params}')\n\n return static_params, url_params, dynamic_params\n\ndef get_auth(auth_type, auth_params):\n logging.info('Getting authentication data.')\n\n if isinstance(auth_params, str):\n try:\n auth_params = json.loads(auth_params)\n except:\n message = f'Could not convert authentication params. [{auth_params}]'\n logging.error(message)\n raise ValueError(message)\n\n if auth_type is None:\n logging.info('No authentication.')\n return\n\n if auth_type.lower() == 'basic':\n user = auth_params.get('user', None)\n password = auth_params.get('password', None)\n\n if None in (user, password):\n message = 'User/Password is not given for authentication.'\n logging.error(message)\n raise ValueError(message)\n\n auth = HTTPBasicAuth(user, password)\n else:\n message = f'Unknown authentication type `{auth_type}`'\n logging.error(message)\n raise NotImplementedError(message)\n\n return auth\n\ndef check_dyanmic_value_type(value, value_type):\n try:\n if isinstance(value, eval(value_type)):\n return True\n else:\n logging.error(f'Expected type `{value_type}` got type `{type(value)}`')\n except:\n logging.exception('Could not evaluate data type.')\n return False\n\ndef hit(api_id, data=None, tenant_id=None):\n logging.info(f'Hitting API')\n\n logging.debug(f'API ID: {api_id}')\n logging.debug(f'Data: {data}')\n\n db_config['tenant_id'] = tenant_id\n db = DB('api_config', **db_config)\n\n # Get the API configuration\n api_config = db.get_all('api', condition={'id': api_id})\n\n if api_config.empty:\n logging.error(f'No configuration found for API ID `{api_id}`')\n return\n\n api_type = list(api_config['api_type'])[0]\n base_url = list(api_config['base_url'])[0]\n method = list(api_config['method'])[0].upper()\n parameters = list(api_config['parameters'])[0]\n auth_type = list(api_config['auth_type'])[0]\n auth_params = list(api_config['auth_params'])[0]\n\n logging.debug(f'API Type: {api_type}')\n logging.debug(f'Base URL: {base_url}')\n logging.debug(f'Method: {method}')\n logging.debug(f'Paramters: {parameters}')\n logging.debug(f'Auth Type: {auth_type}')\n logging.debug(f'Auth Params: {auth_params}')\n\n # Parse the parameters\n try:\n static_params, url_params, dynamic_params = parse_params(parameters)\n except:\n message = 'Could not parse parameters.'\n logging.exception(message)\n return {'flag': False, 'message': message}\n\n # Get the authentication data\n try:\n auth = get_auth(auth_type, auth_params)\n except:\n message = 'Error getting authentication data.'\n logging.exception(message)\n return {'flag': False, 'message': message}\n\n # Check if dynamic params keys are there in the data received\n dynamic_values = {}\n for param, conf in dynamic_params.items():\n param_type = conf.get('type', None)\n \n if param not in data:\n message = f'All dynamic parameter keys not found in data. (dynamic params: {dynamic_params})'\n logging.error(message)\n return {'flag': False, 'message': message}\n \n # Check if value of dynamic params are correct datatype\n if check_dyanmic_value_type(data[param], param_type):\n dynamic_values[param] = data[param]\n else:\n return {'flag': False, 'message': f'Expected type `{param_type}` for `{param}` got type `{type(data[param]).__name__}`'}\n \n # Create the final JSON to send\n final_data = {**static_params, **dynamic_values}\n\n if method == 'POST':\n logging.debug(f'POST method.')\n response = requests.post(base_url, json=final_data, params=url_params, auth=auth)\n elif method == 'GET':\n logging.debug(f'GET method.')\n response = requests.get(base_url, json=final_data, params=url_params, auth=auth)\n else:\n message = f'Unknown method `{method}`'\n logging.error(message)\n return {'flag': False, 'message': message}\n\n try:\n logging.debug(f'Getting response JSON.')\n reponse = response.json()\n except:\n logging.exception(f'Response JSON failed.')\n response = response.content()\n\n return response","sub_path":"app/acepi.py","file_name":"acepi.py","file_ext":"py","file_size_in_byte":5584,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"649652221","text":"import flask\nfrom indexd.errors import AuthError\nfrom indexd.errors import UserError\nfrom indexd.index.errors import NoRecordFound as IndexNoRecordFound\nfrom indexd.errors import UnexpectedError\nfrom indexd.index.blueprint import get_index\n\nblueprint = flask.Blueprint(\"drs\", __name__)\n\nblueprint.config = dict()\nblueprint.index_driver = None\n\n\n@blueprint.route(\"/ga4gh/drs/v1/objects/\", methods=[\"GET\"])\ndef get_drs_object(object_id):\n \"\"\"\n Returns a specific DRSobject with object_id\n \"\"\"\n ret = blueprint.index_driver.get(object_id)\n\n return flask.jsonify(indexd_to_drs(ret)), 200\n\n\n@blueprint.route(\"/ga4gh/drs/v1/objects\", methods=[\"GET\"])\ndef list_drs_records():\n records = get_index()[0].json[\"records\"]\n ret = {\"drs_objects\": [indexd_to_drs(record, True) for record in records]}\n\n return flask.jsonify(ret), 200\n\n\n@blueprint.route(\n \"/ga4gh/drs/v1/objects//access\",\n defaults={\"access_id\": None},\n methods=[\"GET\"],\n)\n@blueprint.route(\n \"/ga4gh/drs/v1/objects//access/\", methods=[\"GET\"]\n)\ndef get_signed_url(object_id, access_id):\n if not access_id:\n raise (UserError(\"Access ID/Protocol is required.\"))\n res = flask.current_app.fence_client.get_signed_url_for_object(\n object_id=object_id, access_id=access_id\n )\n if not res:\n raise IndexNoRecordFound(\"No signed url found\")\n\n return res, 200\n\n\ndef indexd_to_drs(record, list_drs=False):\n bearer_token = flask.request.headers.get(\"AUTHORIZATION\")\n self_uri = \"drs://\" + flask.current_app.hostname + \"/\" + record[\"did\"]\n drs_object = {\n \"id\": record[\"did\"],\n \"description\": \"\",\n \"mime_type\": \"application/json\",\n \"name\": record[\"file_name\"],\n \"created_time\": record[\"created_date\"],\n \"updated_time\": record[\"updated_date\"],\n \"size\": record[\"size\"],\n \"aliases\": [],\n \"contents\": [],\n \"self_uri\": self_uri,\n \"version\": record[\"rev\"],\n }\n\n if \"description\" in record:\n drs_object[\"description\"] = record[\"description\"]\n if \"alias\" in record:\n drs_object[\"aliases\"].append(record[\"alias\"])\n\n if \"contents\" in record:\n drs_object[\"contents\"] = record[\"contents\"]\n\n # access_methods mapping\n if \"urls\" in record:\n drs_object[\"access_methods\"] = []\n for location in record[\"urls\"]:\n location_type = location.split(\":\")[\n 0\n ] # (s3, gs, ftp, gsiftp, globus, htsget, https, file)\n\n drs_object[\"access_methods\"].append(\n {\n \"type\": location_type,\n \"access_url\": flask.current_app.fence_client.get_signed_url_for_object(\n record[\"did\"], \"\"\n )\n if bearer_token and not list_drs\n else {\"url\": location},\n \"access_id\": location_type,\n \"region\": \"\",\n }\n )\n print(drs_object)\n\n # parse out checksums\n drs_object[\"checksums\"] = []\n for k in record[\"hashes\"]:\n drs_object[\"checksums\"].append({\"checksum\": record[\"hashes\"][k], \"type\": k})\n\n return drs_object\n\n\n@blueprint.errorhandler(UserError)\ndef handle_user_error(err):\n ret = {\"msg\": str(err), \"status_code\": 400}\n return flask.jsonify(ret), 400\n\n\n@blueprint.errorhandler(AuthError)\ndef handle_auth_error(err):\n ret = {\"msg\": str(err), \"status_code\": 401}\n return flask.jsonify(ret), 401\n\n\n@blueprint.errorhandler(AuthError)\ndef handle_requester_auth_error(err):\n ret = {\"msg\": str(err), \"status_code\": 403}\n return flask.jsonify(ret), 403\n\n\n@blueprint.errorhandler(IndexNoRecordFound)\ndef handle_no_index_record_error(err):\n ret = {\"msg\": str(err), \"status_code\": 404}\n return flask.jsonify(ret), 404\n\n\n@blueprint.errorhandler(UnexpectedError)\ndef handle_unexpected_error(err):\n ret = {\"msg\": str(err), \"status_code\": 500}\n return flask.jsonify(ret), 500\n\n\n@blueprint.record\ndef get_config(setup_state):\n index_config = setup_state.app.config[\"INDEX\"]\n blueprint.index_driver = index_config[\"driver\"]\n","sub_path":"indexd/drs/blueprint.py","file_name":"blueprint.py","file_ext":"py","file_size_in_byte":4179,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"639521674","text":"\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom io import BytesIO\nimport base64\n\n\n# http://hplgit.github.io/web4sciapps/doc/pub/._web4sa_flask015.html\ndef damped_vibrations(t, A, b, w):\n return A*np.exp(-b*t)*np.cos(w*t)\n\ndef compute(A, b, w, T, resolution=500):\n \"\"\"Return filename of plot of the damped_vibration function.\"\"\"\n t = np.linspace(0, T, resolution+1)\n u = damped_vibrations(t, A, b, w)\n plt.figure() # needed to avoid adding curves in plot\n plt.plot(t, u)\n plt.title('A=%g, b=%g, w=%g' % (A, b, w))\n\n \"\"\"\n # Generating a static PNG file and rendered in html\n if not os.path.isdir('static'):\n os.mkdir('static')\n else:\n # Remove old plot files\n for filename in glob.glob(os.path.join('static', '*.png')):\n os.remove(filename)\n # Use time since Jan 1, 1970 in filename in order make a unique filename\n # that the browser has not chached\n plotfile = os.path.join('static', str(time()) + '.png')\n plt.savefig(plotfile)\n return plotfile\n \"\"\"\n\n # Generating a binary stream of result as a PNG in Base64 encoding string\n figfile = BytesIO()\n plt.savefig(figfile, format='png')\n figfile.seek(0) # rewind to beginning of file\n\n figdata_png = base64.b64encode(figfile.getvalue())\n figdata_png = figdata_png.decode(\"utf-8\")\n return figdata_png","sub_path":"app/science/compute.py","file_name":"compute.py","file_ext":"py","file_size_in_byte":1361,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"559998637","text":"import qcommon\nfrom tasks.qtask import QTask\n\n\nclass QTaskAbilityOrders(QTask):\n def __init__(self):\n\n # Inherit parent attributes (which gives us self.logger)\n QTask.__init__(self)\n\n def execute(self, bot, elapsed, loop):\n if not bot.has_started():\n return\n\n self.logger.debug(\"executing\")\n\n if not qcommon.global_configuration:\n return\n\n self.logger.debug(\"Ability Orders\")\n ability_strategy = qcommon.global_configuration[\"abilities\"]\n actives = qcommon.global_configuration[\"active\"][\"abilities\"]\n\n for ability_id in ability_strategy.keys():\n\n if ability_id not in actives and \"all\" not in actives:\n continue\n\n # Ensure mineral and vespene rates are OK\n if not qcommon.is_mineral_vespene_rate_ok(bot, ability_strategy, ability_id):\n self.logger.debug(\"ABILITY requested: {}, m/v rate(s) are too low\".format(ability_id))\n continue\n\n # Ensure mineral and vespene amounts are OK\n if not qcommon.is_mineral_vespene_amt_ok(bot, ability_strategy, ability_id):\n self.logger.debug(\"ABILITY requested: {}, m/v amount(s) are too low\".format(ability_id))\n continue\n\n # Check if we can do an upgrade (it must have all prereqs completed)\n prereqs = qcommon.techtree(ability_id)\n prereq_items = qcommon.tech_status(bot, prereqs)\n\n # Check if this already exists (or in process of being built)\n if ability_id in prereq_items:\n item = prereq_items[ability_id]\n total = item[\"num_ready\"] + item[\"num_pending\"] + item[\"num_queued\"]\n if total > 0:\n self.logger.debug(\"Ability exists: {}\".format(ability_id))\n continue\n\n # If there are prereqs then find the first one to build\n tech_to_build = ability_id\n for item in prereq_items:\n total = item[\"num_ready\"] + item[\"num_pending\"] + item[\"num_queued\"]\n if total > 0:\n self.logger.debug(\"Ability: {}, prereq exists, building tech: {}\".format(ability_id, tech_to_build))\n continue\n tech_to_build = item[\"tech\"]\n break\n\n if not bot.can_afford(tech_to_build):\n self.logger.debug(\"ability (original) requested: {}, prereq tech: {} has insufficient resources\".format(ability_id, tech_to_build))\n continue\n\n # If the prereq is a building, then queue it to be built\n if qcommon.is_building_type(tech_to_build):\n qcommon.global_building_prereqs.add(tech_to_build)\n continue\n\n # If we made it here then build the upgrade (note that the upgrade\n # will now be the first UPGRADE in the prereq list, and not the original upgrade)\n # self.logger.debug(\"Upgrade (original) requested: {}, prereq tech: {} will be built first\".format(upgrade_id, tech_to_build))\n qcommon.build_ability(bot, ability_strategy, ability_id, tech_to_build)\n","sub_path":"src/tasks/qtask_ability_orders.py","file_name":"qtask_ability_orders.py","file_ext":"py","file_size_in_byte":3179,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"256691062","text":"import json\nimport boto3\nfrom botocore.vendored import requests\n\ndef lambda_handler(event, context):\n # q = \"show me photos with City in them\"\n q = event[\"q\"]\n \n # Disambiguate the query using Lex\n lex = boto3.client('lex-runtime')\n lex_response = lex.post_text(\n botName='SearchPhotos',\n botAlias='Prod',\n userId=\"search-photos\", #unstructured['id'],\n inputText=q\n )\n keywords = lex_response['message'].split(\" \")\n \n # Search the keywords in ElasticSearch\n results = []\n if len(keywords) <= 2: # We only support 2 keywords. If there are more than 2, input is not valid.\n for keyword in keywords:\n host = \"https://vpc-photos-nkyltrkbx6wohrt4secyzqc37e.us-east-1.es.amazonaws.com\"\n search_url = host + \"/photos/_search?q=\" + keyword\n response = requests.get(search_url)\n response = response.json()\n for hit in response[\"hits\"][\"hits\"]:\n _source = hit[\"_source\"]\n objectKey = _source[\"objectKey\"]\n bucket = _source[\"bucket\"]\n labels = _source[\"labels\"]\n result = {\"url\": \"https://s3.amazonaws.com/\" + bucket + \"/\" + objectKey, \"labels\": labels}\n results.append(result)\n return {\n 'statusCode': 200,\n 'body': json.dumps({\"results\": results})\n }\n else: # Something wrong inside Lex\n return {\n 'statusCode': 400,\n 'body': lex_response[\"message\"]\n }\n\n\"\"\"\nresponse syntax:\n{\n \"results\": [\n {\n \"url\": \"string\",\n \"labels\": [\n \"string\"\n ]\n }\n ]\n}\n\"\"\"","sub_path":"hw3/search-photos.py","file_name":"search-photos.py","file_ext":"py","file_size_in_byte":1663,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"635270779","text":"# -*- coding:utf-8 -*-\n\n'''\n#@Author: Magician\n#@Date: 2020-09-22 19:23:50 \n#@Description: \n\nCopyright 2020 by Magician\n'''\nimport math\nimport random\nimport struct\nimport datetime\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport xlwt\nfrom matplotlib.ticker import FuncFormatter\n# from sympy import * \nfrom scipy import integrate\nfrom scipy.optimize import curve_fit\n\nf = xlwt.Workbook()\nsheet1 = f.add_sheet(u'sheet1',cell_overwrite_ok=True)\nrow0 = [u'nB',u'nC',u'T1',u'T2',u'T3',u'T4',u'T5',u'T6',u'T7',u'T8',u'Energy']\ncolumn = ''\nstatus = ''\nfor i in range(0,len(row0)):\n sheet1.write(0,i,row0[i])\n\nbinFile = open('E:\\\\PET\\\\数据集\\\\6BDM.samples','rb')\npoly = binFile.read()\nprint(\"字节长度:\",len(poly))\nframe = int(len(poly)/68)+1\nprint(\"帧数:\",frame-1)\n\ncircle = 65000 # 分析多少组数据 (.xls文件的上限是65536)\n\nglobal x_rate, y_rate \nglobal popt,popt_dict\nglobal space\nglobal bounds\nx_rate = 1 # 将x单位进行放缩\ny_rate = 1000 # 将y单位进行放缩\nspace = 2000\npopt = []\npopt_dict = ['a','b','d']\nnum = [40,110,180,270,270,180,110,40]\ny = np.array(num)\nbounds = ([-500,-2,0],[0,0,2])\n\n\ndef double_exp(x,a,b,d):\n \"\"\"双指数函数\n 参数:\n ------------\n x : float\n 当前时间与脉冲发生时间的差值\n a : float\n 由脉冲幅度决定\n b, d: float\n 由脉冲的上升和下降时间决定\n \"\"\"\n return a*np.exp(b*(x))*(1-np.exp(d*(x)))\n\ndef monto(x,a,b):\n \"\"\"\n # a,b为求取积分的上下限\n \"\"\"\n return (b-a)/len(x)*sum(double_exp(x,popt[0],popt[1],popt[2],popt[3]))\n\ndef integral(a,b):\n \"\"\"\n # a,b为求取积分的上下限\n \"\"\"\n return double_exp(b,popt[0],popt[1],popt[2],popt[3]) - double_exp(a,popt[0],popt[1],popt[2],popt[3])\n\ndef func(x):\n return popt[0]*np.exp(popt[1]*(x))*(1-np.exp(popt[2]*(x)))\n\ndef assert_popt(popt,bounds,num):\n '''检查拟合参数是否需要调整\n 参数:\n --------\n popt:拟合得到的参数\n bounds:参数范围\n num:第num+1次拟合\n '''\n for i in range(3):\n assert (popt[i]!=bounds[0][i]), \"参数%s下限值应该调整!!!\\n第%d帧数据所得双指数函数形式为:%f*exp(%f*(x))*(1-exp(%f*(x)))\"%(popt_dict[i],num+1,popt[0],popt[1],popt[2])\n assert (popt[i]!=bounds[1][i]), \"参数%s上限值应该调整!!!\\n第%d帧数据所得双指数函数形式为:%f*exp(%f*(x))*(1-exp(%f*(x)))\"%(popt_dict[i],num+1,popt[0],popt[1],popt[2])\n\nfor i in range(circle):\n poly_func = poly[i*68:(i+1)*68]\n content = struct.unpack(' float:\n args, kwargs = self._make_accumulation_request(\n ib_request_fn=self._ib_conn.reqAccountSummary,\n request_kwargs={\n \"groupName\": \"All\",\n \"tags\": AccountSummaryTags.TotalCashValue,\n },\n ib_receiver_fn=self._ib_conn.accountSummary,\n ib_end_fn=self._ib_conn.accountSummaryEnd,\n ib_cancel_fn=self._ib_conn.cancelAccountSummary,\n )\n acc_summary = args\n acc_value = float(acc_summary[3])\n\n return acc_value\n\n @property\n def datetime(self) -> datetime:\n args, kwargs = self._make_one_shot_request(\n ib_request_fn=self._ib_conn.reqCurrentTime,\n ib_receiver_fn=self._ib_conn.currentTime,\n )\n server_time = args[0]\n dt = datetime.fromtimestamp(server_time)\n\n return dt\n\n def subscribe_to_bars(\n self,\n symbol: str,\n bar_size: timedelta,\n func: Callable,\n fn_kwargs: Optional[dict] = None,\n ):\n raise NotImplementedError\n\n def get_position(\n self, symbol: str, *args, account: Optional[str] = None, **kwargs\n ) -> int:\n if self._ib_conn.client_id != MASTER_CLIENT_ID:\n raise AttributeError(\n f\"This client ID cannot request positions. Please use a broker\"\n f\" instantiated with the master client ID ({MASTER_CLIENT_ID})\"\n f\" to request positions.\"\n )\n\n pos = 0\n\n if self._positions is None:\n self._subscribe_to_positions()\n\n symbol_dict: Optional[Dict] = self._positions.get(symbol)\n if symbol_dict is not None:\n if account is None:\n for acc, acc_dict in symbol_dict.items():\n pos += acc_dict[\"position\"]\n else:\n pos += symbol_dict[account][\"position\"]\n\n return pos\n\n def buy(self, symbol: str, n_shares: int, **kwargs) -> bool:\n pass\n\n def sell(self, symbol: str, n_shares: int, **kwargs) -> bool:\n pass\n\n def get_transaction_fee(self) -> float:\n pass\n\n # ------------ todo: add to ABroker -----------------\n\n def subscribe_to_new_orders(\n self, func: Callable, fn_kwargs: Optional[Dict] = None,\n ):\n if fn_kwargs is None:\n fn_kwargs = {}\n self._ib_conn.subscribe(\n target_fn=self._ib_conn.openOrder,\n callback=func,\n include_target_args=True,\n callback_kwargs=fn_kwargs,\n )\n self._ib_conn.reqAutoOpenOrders(bAutoBind=True)\n\n # ---------- Requests Helpers ----------------------\n\n def _make_accumulation_request(\n self,\n ib_request_fn: Callable,\n ib_receiver_fn: Callable,\n ib_end_fn: Callable,\n ib_cancel_fn: Callable,\n request_kwargs: Optional[Dict] = None,\n ) -> Tuple[Tuple, Dict]:\n if request_kwargs is None:\n request_kwargs = {}\n req_id = self._get_next_req_id()\n results_queue = self._get_callback_queue(\n ib_receiver_fn=ib_receiver_fn, req_id=req_id,\n )\n end_queue = self._get_callback_queue(\n ib_receiver_fn=ib_end_fn, req_id=req_id,\n )\n request_kwargs[\"reqId\"] = req_id\n\n ib_request_fn(**request_kwargs)\n self._await_results_from_queue(queue=end_queue)\n args, kwargs = self._await_results_from_queue(queue=results_queue)\n ib_cancel_fn(req_id)\n\n return args, kwargs\n\n def _make_one_shot_request(\n self,\n ib_request_fn: Callable,\n ib_receiver_fn: Callable,\n request_kwargs: Optional[Dict] = None,\n ) -> Tuple[Tuple, Dict]:\n if request_kwargs is None:\n request_kwargs = {}\n results_queue = self._get_callback_queue(\n ib_receiver_fn=ib_receiver_fn,\n )\n\n ib_request_fn(**request_kwargs)\n args, kwargs = self._await_results_from_queue(queue=results_queue)\n\n return args, kwargs\n\n def _get_next_req_id(self) -> int:\n if self._req_id is None:\n self._get_req_id_from_ib()\n self._req_id -= 1\n self._req_id += 1\n return self._req_id\n\n def _get_req_id_from_ib(self):\n queue = self._get_callback_queue(\n ib_receiver_fn=self._ib_conn.nextValidId,\n )\n self._ib_conn.reqIds(numIds=1)\n args, kwargs = self._await_results_from_queue(queue=queue)\n self._req_id = args[0]\n\n def _get_callback_queue(\n self, ib_receiver_fn: Callable, req_id: Optional[int] = None,\n ):\n receiver_queue = Queue()\n self._ib_conn.subscribe(\n target_fn=ib_receiver_fn,\n callback=self._update_queue,\n callback_kwargs={\"queue\": receiver_queue, \"req_id\": req_id},\n )\n\n return receiver_queue\n\n @staticmethod\n def _update_queue(*args, queue: Queue, req_id: Optional[int], **kwargs):\n if req_id is None or (len(args) != 0 and args[0] == req_id):\n queue.put((args, kwargs))\n\n @staticmethod\n def _await_results_from_queue(queue: Queue) -> Any:\n while queue.empty():\n pass\n res = queue.get()\n\n return res\n\n def _subscribe_to_positions(self):\n request_positions = False\n\n with self._positions_lock:\n if self._positions is None:\n self._positions = {}\n request_positions = True\n\n if request_positions:\n self._ib_conn.subscribe(\n target_fn=self._ib_conn.position,\n callback=self._update_position,\n )\n end_queue = self._get_callback_queue(\n ib_receiver_fn=self._ib_conn.positionEnd,\n # req_id=-1, # just to have something returned in the queue\n )\n self._ib_conn.reqPositions()\n self._await_results_from_queue(queue=end_queue)\n\n def _update_position(\n self,\n account: str,\n contract: Contract,\n position: float,\n avgCost: float,\n ):\n symbol = contract.symbol\n print(f\"Updating positions {account} {contract.symbol}\")\n with self._positions_lock:\n symbol_pos = self._positions.setdefault(symbol, {})\n symbol_pos_acc = symbol_pos.setdefault(account, {})\n symbol_pos_acc[\"position\"] = position\n symbol_pos_acc[\"ave_cost\"] = avgCost\n","sub_path":"algotradepy/brokers/ib_broker.py","file_name":"ib_broker.py","file_ext":"py","file_size_in_byte":8319,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"83934054","text":"from setuptools import find_packages, setup\nfrom configparser import ConfigParser\n\nconfig = ConfigParser()\nconfig.read('../../src/metadata.ini')\n\nmetadata = config['default']\n\n\nsetup(\n name = metadata.get('name'),\n version = metadata.get('version'),\n description = metadata.get('description'),\n url = metadata.get('url'),\n author = metadata.get('author'),\n author_email = metadata.get('author_email'),\n license = 'MIT',\n\n python_requires = '>=3.6.0',\n\n packages = find_packages(exclude=('tests',)),\n include_package_data = True,\n\n classifiers = [\n 'Intended Audience :: Developers',\n 'License :: OSI Approved :: MIT License',\n 'Programming Language :: Python',\n 'Programming Language :: Python :: 3',\n 'Programming Language :: Python :: 3.6',\n 'Operating System :: OS Independent',\n 'Topic :: Software Development :: Assemblers'\n ]\n)\n","sub_path":"languages/python/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":986,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"489219605","text":"import itertools\nimport math\nimport random\n\n# Uncomment these 2 lines in order to have dynamic generation of\n# Cython extensions:\n# import pyximport\n# pyximport.install()\n\nfrom CPrime import prime_numbers, free_run\nfrom CDividends import find_dividends\n\n\ndef prime_numbers_reference(num):\n \"\"\"A reference implementation of a prime number generator.\n\n For num=10**7 it is 105 times slower than CPrime.prime_numbers\n on a CPU Intel i5 3335S @ 2.7GHz and 4 physical cores.\n\n More over needs much more memory to be allocated in advance, on\n an 8Gb machine it can raise a memory error already with num=10**8.\n \"\"\"\n assert(num >= 2)\n\n # Allocates a buffer of booleans for the range [0, num),\n # each boolean will tell as if a number is prime or not:\n numbers = [True for x in range(num)]\n\n # From the range [3, sqrt(num)] we set to false (non prime)\n # all multiplicand of each number found that is still marked\n # as prime (we consider only odd numbers):\n k = int(math.sqrt(num))\n for x in range(3, k + 1, 2):\n if numbers[x]:\n y = x * x # Multiplicands < x**2 have already been set\n while y < num:\n numbers[y] = False\n y += x # Next multiplicand.\n\n # Now we collect and return all the values for witch a multiplicand\n # has not been found:\n result = [2]\n result.extend(x\n for x in range(3, num, 2)\n if numbers[x])\n return result\n\n\ndef test_base():\n \"\"\"Base unit test for CPrime.prime_numbers()\"\"\"\n\n # Up to 10**7 e use a reference (but slow) implementation to test oru\n # fast algorithm:\n for order in range(1, 8):\n print('Order {}:'.format(order))\n max_number = 10 ** order\n prod_result = list(prime_numbers(max_number))\n ref_result = prime_numbers_reference(max_number)\n print(' PROD: ', prod_result[:100], '...' if order > 2 else '')\n print(' REF: ', ref_result[:100], '...' if order > 2 else '')\n assert prod_result == ref_result\n # From 10**8 to 10**10 we just generate numbers and test some random subset\n # of them:\n for order in range(8, 11):\n print('Order {}:'.format(order))\n print(' Executing...')\n max_number = 10 ** order\n results = [0 for x in range(1000)]\n for x in prime_numbers(max_number):\n results[random.randint(0, 999)] = x\n print(' Evaluating {} results'.format(len(results)))\n for x in results:\n test_prime_number(x)\n\n\ndef test_prime_number(x):\n print(' Testing {}'.format(x))\n dividends = list(itertools.islice(find_dividends(x), 101))\n if dividends:\n print(' DIVIDENDS: ',\n dividends[100:],\n '...' if len(dividends) > 100 else '')\n assert False, \"{} is not prime\".format(x)\n\n\nif __name__ == '__main__':\n test_base()\n","sub_path":"test_CPrime.py","file_name":"test_CPrime.py","file_ext":"py","file_size_in_byte":2897,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"631240033","text":"from collections import Counter,defaultdict,OrderedDict\n\nli=[1,2,3,4,5,6,7,7]\nsentence='blah blah blah thinking about python'\nprint(Counter(li))\nprint(Counter(sentence))\n\ndictionary=defaultdict(int,{'a':1,'b':2})\nprint(dictionary['c'])\n#provides default values for unknown variables which is eqivalent to --\nprint(int())\n\ndictionary=defaultdict(lambda: 'doesn\\'t exist',{'a':1,'b':2})\nprint(dictionary['c'])\n\nd=OrderedDict()\nd['a']=1\nd['b']=2\n\nd2=OrderedDict()\nd2['a']=1\nd2['b']=2\n\nprint(d2==d)\n\nf={'c':100}\nf['a']=1\nf['b']=2\n\nf2={'c':100}\nf2['b']=2\nf2['a']=1\n\nprint(f2==f)\n\n","sub_path":"Error/yoye.py","file_name":"yoye.py","file_ext":"py","file_size_in_byte":575,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"576425251","text":"import os\nimport sys\n#当前文件的路径\npwd = os.getcwd()\n#当前文件的父路径\nfather_path=os.path.abspath(os.path.dirname(pwd)+os.path.sep+\".\")\n#当前文件的前两级目录\ngrader_father=os.path.abspath(os.path.dirname(pwd)+os.path.sep+\"..\")\nlocal = grader_father + \"/music/static/base/lcmusic\"\nprint(local)\nfile_dir = r\"D:/pycharm workspace/music/static/base/lcmusic\"\n\nfile_dir = local\ni=0\nlccd = []\nb = None\nfor root, dirs, files in os.walk(file_dir):\n i+=1\n print(files) #当前路径下所有非目录子文件\n print(i)\n lccd = files\nprint(lccd)","sub_path":"Digital Asset Management/hw/hw2/music/app/rm.py","file_name":"rm.py","file_ext":"py","file_size_in_byte":575,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"7578043","text":"from OpenGL.GL import *\r\nimport glfw\r\n\r\ndef main():\r\n if not glfw.init():\r\n return\r\n\r\n window = glfw.create_window(640, 480, \"PyOpenGL Sample\", None, None)\r\n if not window:\r\n glfw.terminate()\r\n print('Failed to create window')\r\n return\r\n\r\n glfw.make_context_current(window)\r\n\r\n glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 4)\r\n glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 0)\r\n glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE)\r\n\r\n while not glfw.window_should_close(window):\r\n glClearColor(0, 0, 0, 1)\r\n glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)\r\n\r\n glfw.swap_buffers(window)\r\n\r\n glfw.poll_events()\r\n\r\n glfw.destroy_window(window)\r\n glfw.terminate()\r\n\r\nif __name__ == \"__main__\":\r\n main()\r\n","sub_path":"test_script/02/glfw_sample.py","file_name":"glfw_sample.py","file_ext":"py","file_size_in_byte":803,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"489304300","text":"'''\nfaça uma funcao recursiva par(numero)\nque retorna True se um numero é par e \nFalse se ele é impar\n\nA recursao é a seguinte: se o número\né grande (maior ou igual a 3),\npar(numero) = par(numero-2)\n'''\n\ndef par(numero):\n if numero == 0:\n return True\n if numero == 1:\n return False\n resultado = par(numero-2)\n return resultado\n\n'''\nfaça uma funcao recursiva div_por_tres(numero)\nque retorna True se um numero é divisivel por 3 \nFalse se ele não é\n\nA recursao é a seguinte: se o número\né grande (maior ou igual a 4),\ndiv_por_tres(numero) = div_por_tres(numero-3)\n'''\n\ndef div_por_tres(numero):\n \n if numero == 3:\n return True\n if numero < 3:\n return False\n \n resultado = div_por_tres(numero-3)\n return resultado\n\n\n\nimport unittest\nimport sys\ntry:\n from recursao_inicial_gabarito import *\nexcept:\n pass\nclass TestStringMethods(unittest.TestCase):\n\n def test_01_par_funciona(self):\n self.assertTrue(par(2))\n self.assertFalse(par(3))\n self.assertTrue(par(20))\n self.assertFalse(par(13))\n self.assertTrue(par(16))\n self.assertFalse(par(5))\n self.assertTrue(par(0))\n self.assertFalse(par(11))\n self.assertTrue(par(10))\n\n def test_02_par_recursivo(self):\n sys.setrecursionlimit(50)\n try:\n par(2000)\n self.fail('a sua função é recursiva?')\n except RecursionError:\n print('')\n print('correto, sua funcao é recursiva')\n finally:\n sys.setrecursionlimit(1000)\n \n def test_03_div_por_tres_funciona(self):\n self.assertTrue (div_por_tres(3))\n self.assertFalse(div_por_tres(4))\n self.assertTrue (div_por_tres(30))\n self.assertFalse(div_por_tres(40))\n self.assertTrue (div_por_tres(15))\n self.assertFalse(div_por_tres(11))\n self.assertTrue (div_por_tres(9))\n self.assertFalse(div_por_tres(8))\n self.assertTrue (div_por_tres(90))\n self.assertFalse(div_por_tres(89))\n \n def test_04_div_por_tres_recursivo(self):\n sys.setrecursionlimit(50)\n try:\n div_por_tres(2000)\n self.fail('a sua função é recursiva?')\n except RecursionError:\n print('')\n print('correto, sua funcao é recursiva')\n finally:\n sys.setrecursionlimit(1000)\n \ndef runTests():\n suite = unittest.defaultTestLoader.loadTestsFromTestCase(TestStringMethods)\n unittest.TextTestRunner(verbosity=2,failfast=True).run(suite)\n\nrunTests()\n","sub_path":"recursao_inicial.py","file_name":"recursao_inicial.py","file_ext":"py","file_size_in_byte":2616,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"484964459","text":"import re\nfrom bs4 import BeautifulSoup\n\n\ndef cleanTitle(text):\n return text.replace(\"\\n\", \"\").splitlines()[0].replace(\" \", \"\")\n\n\ndef extractHours(text):\n hours = \"\"\n\n match_hours = re.search(r\"\\((\\d+(h|:))?(\\d+(m?))?\\)\", text)\n if(match_hours):\n hours = \"\".join(match_hours.group())\n\n return hours\n\n\ndef extractMinutesCount(hours_text):\n minutes = 0\n\n match_hours = re.search(r\"\\d+(?=h|:)\", hours_text)\n if(match_hours):\n minutes += int(match_hours.group()) * 60\n\n match_minutes = re.search(r\"\\d+(?=m|\\))\", hours_text)\n if(match_minutes):\n minutes += int(match_minutes.group())\n\n # print(\n # f\"Hours matched: {match_hours.group() if match_hours else 0} \\n Minuted matched: {match_minutes.group() if match_minutes else 0} \\n -------- Total minutes: {minutes}------------\")\n\n return minutes\n\n\ndef getSoup(text):\n return BeautifulSoup(text, \"html.parser\")\n\n\ndef getSections(soup):\n return soup.findAll(\"div\", {\"class\": \"section-title\"})\n\n\ndef getSectionTitles(sections):\n _sections = []\n\n for section in sections:\n cleaned_text = cleanTitle(section.text)\n _sections.append(cleaned_text)\n\n return _sections\n\n\ndef getHoursPerSection(section_titles):\n _hours = []\n\n for section in section_titles:\n extracted_hours = extractHours(section)\n _hours.append(extracted_hours)\n\n return _hours\n\n\ndef getTotalHours(hours_per_section):\n _minutes = 0\n\n for section_hours in hours_per_section:\n minutes_number = extractMinutesCount(section_hours)\n _minutes += minutes_number\n\n return round(_minutes / 60, 1)\n","sub_path":"CourseHours.py","file_name":"CourseHours.py","file_ext":"py","file_size_in_byte":1630,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"75287719","text":"#encoding: UTF-8\n\n# Autor: Ernesto Ibhar Guevara Gomez, A01746121\n# Descripcion: Imprime la distancia recorrida en 6 horas y 10 horas ingresando la velocidad. Tambien imprime el tiempo que tarda en recorrer 500 km un auto.\n\n# A partir de aquí escribe tu programa\n\n#Solicitar velocidad\nValorDeVelocidad=input(\"Introduce la velocidad: \")\nvelocidad=int(ValorDeVelocidad)\n#Calcuar d1, d2, H\nd1= velocidad * 6\nd2= velocidad * 10\nH= 500 / velocidad\n#Imprimir resultados\nprint(d1, \"km\")\nprint(d2, \"km\")\nprint(H, \"hrs\")\n\n\n","sub_path":"auto.py","file_name":"auto.py","file_ext":"py","file_size_in_byte":515,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"556719481","text":"\n\nfrom xai.brain.wordbase.nouns._cousin import _COUSIN\n\n#calss header\nclass _COUSINS(_COUSIN, ):\n\tdef __init__(self,): \n\t\t_COUSIN.__init__(self)\n\t\tself.name = \"COUSINS\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"cousin\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_cousins.py","file_name":"_cousins.py","file_ext":"py","file_size_in_byte":238,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"74408368","text":"#!/bin/python3\n\nimport sys\n\nn = int(input().strip())\na = list(map(int, input().strip().split(' ')))\n# Write Your Code Here\ntotalNumSwaps = 0\nfor i in range(n):\n numberOfSwaps = 0\n for j in range(n-1):\n if a[j] > a[j + 1]:\n a[j], a[j+1] = a[j+1], a[j]\n numberOfSwaps+=1\n \n totalNumSwaps+=numberOfSwaps\n\n if numberOfSwaps == 0:\n break\n\nprint(\"Array is sorted in \" + format(totalNumSwaps) + \" swaps.\")\nprint(\"First Element: \" + format(a[0]))\nprint(\"Last Element: \" + format(a[n-1]))\n\n","sub_path":"Day20-Sorting/Day20.py","file_name":"Day20.py","file_ext":"py","file_size_in_byte":531,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"159373360","text":"class Solution:\n def containsDuplicate(self, nums):\n # Create a set to keep track of nums already encountered in the array\n visited = set()\n \n # Iterate through the list\n for num in nums:\n \n # if the number is already in the set, \n # that means we have a duplicate and can return True.\n if num in visited:\n return True\n # If the number isn't in the set, add it\n else:\n visited.add(num)\n \n # If we get to this point, we haven't found any duplicates.\n return False","sub_path":"day1/containsduplicates.py","file_name":"containsduplicates.py","file_ext":"py","file_size_in_byte":625,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"148711804","text":"from sqlite3.dbapi2 import PrepareProtocol, Row\nfrom tkinter import *\nfrom typing import Collection\nimport uteis as u\n\n\nclass FrameProduto(Frame):\n def __init__(self, parent):\n super().__init__(parent)\n lb_titulo = Label(self, text='Produtos').pack()\n\n self.frameCima = Frame(self)\n self.frameBaixo = Frame(self)\n self.bt_produtos = Button(self.frameCima, text='Produtos', width=15, command=self.show_frProdutos)\n self.bt_cadastro = Button(self.frameCima, text='Cadastrar', width=15, command= self.show_frCadastro)\n self.bt_produtos.pack(side=LEFT)\n self.bt_cadastro.pack(side=LEFT)\n\n \n self.frameCima.pack(side=TOP)\n self.frameBaixo.pack(side=BOTTOM)\n \n self.frameProdutos = Frame(self.frameBaixo)\n \n self.lb_pesquisarId = Label(self.frameProdutos, text='pesquisar ID nome:')\n self.etd_pesquisarId = Entry(self.frameProdutos)\n # self.lb_pesquisarNome = Label(self.frameProdutos, text='pesquisar Nome:')\n # self.etd_pesquisarNome = Entry(self.frameProdutos) \n self.bt_pesquisar = Button(self.frameProdutos, text='pesquisar', command=self.pesquisar)\n self.lb_avisoProduto = Label(self.frameProdutos, text=' ')\n\n self.lb_pesquisarId.grid(row='1', column='0')\n self.etd_pesquisarId.grid(row='1', column='1')\n # self.lb_pesquisarNome.grid(row='2', column='0')\n # self.etd_pesquisarNome.grid(row='2', column='1')\n self.bt_pesquisar.grid(row=3, column=1)\n self.lb_avisoProduto.grid(row=4, column=1)\n \n # frame cadastro =====================================\n self.frameCadastro = Frame(self.frameBaixo)\n self.lb_nome = Label(self.frameCadastro, text='nome:')\n self.etd_nome = Entry(self.frameCadastro)\n self.lb_preco = Label(self.frameCadastro, text='preço:')\n self.etd_preco = Entry(self.frameCadastro)\n self.lb_qtd = Label(self.frameCadastro, text='quantidade:')\n self.etd_qtd = Entry(self.frameCadastro)\n self.lb_tamanho = Label(self.frameCadastro, text='tamanho:')\n self.etd_tamanho = Entry(self.frameCadastro)\n self.lb_cor = Label(self.frameCadastro, text='cor:')\n self.etd_cor = Entry(self.frameCadastro)\n\n self.lb_nome.grid(row=1, column=0)\n self.etd_nome.grid(row=1, column=1)\n self.lb_preco.grid(row=2, column=0)\n self.etd_preco.grid(row=2, column=1)\n\n self.lb_qtd.grid(row=3, column=0)\n self.etd_qtd.grid(row=3, column=1)\n self.lb_tamanho.grid(row=4, column=0)\n self.etd_tamanho.grid(row=4, column=1)\n self.lb_cor.grid(row=5, column=0)\n self.etd_cor.grid(row=5, column=1)\n self.lb_avisoCadas = Label(self.frameCadastro, text=' ', fg='red')\n self.lb_avisoCadas.grid(row=7, column=1)\n\n self.bt_cadastrar = Button(self.frameCadastro, width=15, text='cadastrar', command=self.cadastrar)\n self.bt_cadastrar.grid(row=6, column=1)\n self.bt_resetar = Button(self.frameCadastro, width=15, text='resetar', command=self.reset_campoCadastro)\n self.bt_resetar.grid(row=6, column=0)\n\n # self.show_frProdutos()\n self.show_frCadastro()\n self.frameBaixo.pack() \n \n \n def pesquisar(self):\n opcao = self.etd_pesquisarId.get()\n dados = u.pesquisar(opcao=opcao)\n\n print(dados)\n \n for dado in dados:\n Label(None, text=f'nome:{dado[1]} valor:{dado[2]} quatidade:{dado[3]} tamanho:{dado[4]} cor:{dado[5]}').pack()\n \n self.etd_pesquisarId.delete(0, END)\n def show_frProdutos(self):\n self.etd_pesquisarId.focus()\n self.frameCadastro.forget()\n self.frameProdutos.pack()\n \n def show_frCadastro(self):\n self.etd_nome.focus()\n self.frameProdutos.forget()\n self.frameCadastro.pack()\n \n def cadastrar(self):\n print('cadastrar')\n nome = self.etd_nome.get()\n preco = self.etd_preco.get()\n qtd = self.etd_qtd.get()\n tamanho = self.etd_tamanho.get()\n cor = self.etd_cor.get()\n print(qtd)\n if not(qtd): \n qtd = '0'\n \n if not(preco):\n preco = 0\n \n if nome== '':\n self.lb_avisoCadas.config(text='campo nome obrigatorio', fg='red')\n elif qtd.isnumeric():\n qtd = int(qtd)\n preco = float(preco)\n \n print('preco', preco, 'tipo:', type(preco))\n print(nome, qtd, tamanho, cor)\n u.cadastrar_produto(nome=nome, preco=preco, quantidade=qtd, tamanho=tamanho, cor=cor)\n \n self.lb_avisoCadas.config(fg='green', text='cadastro feito com sucesso')\n self.reset_campoCadastro()\n\n else:\n self.lb_avisoCadas.config(text='somente numeros em quantidade', fg='red')\n def reset_campoCadastro(self):\n self.etd_nome.delete(0, END)\n self.etd_preco.delete(0, END)\n self.etd_qtd.delete(0, END)\n self.etd_cor.delete(0, END)\n self.etd_tamanho.delete(0, END)\n \n self.etd_nome.focus()\n\nif __name__ == '__main__':\n root = Tk()\n frame = FrameProduto(root)\n frame.pack()\n root.geometry('500x500')\n root.mainloop()","sub_path":"17-EmDev/frameProduto.py","file_name":"frameProduto.py","file_ext":"py","file_size_in_byte":5305,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"339422399","text":"from typing import Dict, Tuple, List\n\nimport arrow\nimport numpy as np\nimport requests\nfrom arrow import Arrow\nfrom flask import current_app\n\nfrom ads.models import db, DirectAccountSpending, DirectCampaign, DirectKeyword\n\n\nSECONDS_IN_DAY = 3600 * 24\n\n\ndef authorize_url(account_login) -> str:\n base_url = 'https://oauth.yandex.ru/authorize'\n params = {\n 'response_type': 'code',\n # 'device_id': None,\n # 'device_name': None,\n 'client_id': current_app.config['DIRECT_APP_ID'],\n # 'redirect_uri': 'https://ads.earlgreyness.com/oauth_callback',\n 'login_hint': account_login,\n 'force_confirm': 'true',\n # Строка состояния, которую Яндекс.OAuth возвращает без изменения.\n # Максимальная допустимая длина строки — 1024 символа.\n # Можно использовать, например, для защиты от CSRF-атак\n # или идентификации пользователя, для которого запрашивается токен.\n 'state': account_login, # TODO: digitally sign this, like in cookies\n }\n return requests.Request('GET', base_url, params=params).prepare().url\n\n\nclass AccountsSummary:\n def __init__(self, accounts):\n self.accounts = accounts\n\n @staticmethod\n def _count_keywords(account_id):\n return (\n db.session.query(DirectKeyword.Id)\n .join(DirectCampaign)\n .filter(*DirectKeyword.standard_filters(account_id))\n ).count()\n\n @staticmethod\n def _count_campaigns(account_id):\n return (\n db.session.query(DirectCampaign.Id)\n .filter(*DirectCampaign.standard_filters(account_id))\n ).count()\n\n def _spending_dataset(self, direction: str, moment: Arrow):\n assert direction in ('L', 'R')\n\n S = DirectAccountSpending\n\n if direction == 'L':\n condition = S.date_created < moment\n alignment = S.date_created.desc()\n else:\n condition = S.date_created > moment\n alignment = S.date_created\n\n account_ids = [x.id for x in self.accounts]\n\n query = (\n db.session.query(\n S.account_id,\n S.date_created,\n S.spent\n )\n .distinct(S.account_id)\n .filter(condition, S.account_id.in_(account_ids))\n .order_by(S.account_id, alignment)\n )\n\n return {x.account_id: (x.date_created.timestamp, x.spent) for x in query}\n\n def _spent(self, moment: Arrow) -> Dict[int, Tuple[int, int]]:\n data_l = self._spending_dataset('L', moment)\n data_r = self._spending_dataset('R', moment)\n\n account_ids = set(data_l) | set(data_r)\n\n timestamp = moment.timestamp\n\n result = {x.id: (timestamp, 0) for x in self.accounts}\n\n for account_id in account_ids:\n l = data_l.get(account_id)\n r = data_r.get(account_id)\n\n if l and r:\n xp, fp = zip(l, r)\n date, spent = timestamp, int(np.interp(timestamp, xp, fp))\n elif l and not r:\n date, spent = l\n elif not l and r:\n date, spent = r\n else:\n raise AssertionError('must be unreachable')\n\n result[account_id] = date, spent\n\n return result\n\n def calc(self) -> List[Dict]:\n moment_now = arrow.now()\n moment_midnight = moment_now.floor('day')\n moment_past = moment_now - current_app.config['SPENDING_DELTA_AVERAGE']\n\n spent_now = self._spent(moment_now)\n spent_midnight = self._spent(moment_midnight)\n spent_past = self._spent(moment_past)\n\n info = []\n\n for account in self.accounts:\n id = account.id\n\n now = spent_now[id]\n midnight = spent_midnight[id]\n past = spent_past[id]\n\n spent_today = (now[1] - midnight[1]) / 1000000\n\n delta = now[0] - past[0]\n spent = now[1] - past[1]\n\n try:\n rate = spent / delta * SECONDS_IN_DAY / 1000000\n except ZeroDivisionError:\n rate = None\n\n balance = account.Amount\n\n try:\n forecast = balance / rate\n except (TypeError, ZeroDivisionError):\n # TypeError if balance is None or rate_average is None\n forecast = None\n\n info.append({\n 'api_units': account.get_api_units(),\n 'status': account.status,\n 'login': account.login,\n 'balance': balance,\n 'spent_today': spent_today,\n 'spending_rate_average': rate,\n 'forecast': forecast,\n 'oauth_authorize_url': authorize_url(account.login),\n 'keywords_amount': self._count_keywords(account.id),\n 'campaigns_amount': self._count_campaigns(account.id),\n 'roistat_on': account.roistat_on,\n 'roistat_key': account.roistat_key,\n 'roistat_project': account.roistat_project,\n })\n\n return info\n","sub_path":"ads/business/accounts.py","file_name":"accounts.py","file_ext":"py","file_size_in_byte":5274,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"485085804","text":"import uuid\nfrom starlette.responses import JSONResponse\n# from starlette.requests import Request\nfrom src.apps.users.models import User\nfrom .models import *\nfrom src.config.settings import BASE_DIR, STATIC_ROOT, MEDIA_ROOT\nfrom src.apps.users.views import get_current_login\nfrom fastapi import APIRouter, Depends, BackgroundTasks, Response, status, Request, File, UploadFile, Body\nimport pathlib\nfrom typing import List , Optional\n\nimport os\nimport shutil\nfrom .service import *\nfrom .schema import *\nfrom .pydanticmodels import *\n\nclinto_router = APIRouter(dependencies=[Depends(get_current_login)])\n\ndays = [\"Monday\", \"Tuesday\", \"Wednesday\",\n \"Thursday\", \"Friday\", \"Saturday\", \"Sunday\"]\n@clinto_router.get('/doctorClinics/{userid}')\nasync def getClinics(userid: int):\n user = await User.get(id=userid).prefetch_related(\"workingclinics\")\n clinics = [{\"name\": clinic.name, \"email\": clinic.email}async for clinic in user.workingclinics.all()]\n\n@clinto_router.post('/createClinic')\nasync def createClinic(clinic: Create_Clinic):\n create_clinic = await clinic_view.create(clinic)\n print(create_clinic)\n \n@clinto_router.get('/getClinics')\nasync def get_clinics(limit:int = 10,offset:int = 0):\n clinics = await clinic_view.limited_data(limit=limit, offset=offset)\n clinics_objs = []\n for clinic in clinics:\n timings = await clinic.timings.all().values('timings','day')\n print(timings,\"imhere\")\n clinics_objs.append({\"clinic_data\": clinic, \"timings\": timings})\n return clinics_objs\n\n@clinto_router.post('/addDoctors')\nasync def add_doctors(clinic:int,user:int,data:Create_Doctor):\n create_doctor = await ClinicDoctors.create(clinic_id=clinic, user_id=user, **data.dict(exclude_unset=True))\n return create_doctor\n\n@clinto_router.post(\"/addClinicImages\")\nasync def clinic_images(clinic: int,files: List[UploadFile] = File(...)):\n file_paths = []\n clinic_obj = await Clinic.get(id=clinic)\n for file in files:\n sample_uuid = uuid.uuid4()\n path = pathlib.Path(\n MEDIA_ROOT, f\"clinicimages/{str(sample_uuid)+file.filename}\")\n os.makedirs(os.path.dirname(path), exist_ok=True)\n file_paths.append(str(path))\n with path.open('wb') as write:\n shutil.copyfileobj(file.file, write)\n clinic_obj.clinic_images = file_paths\n await clinic_obj.save()\n return clinic_obj\n\n@clinto_router.post(\"/addTimings\")\nasync def add_timings(clinic: bool, clinicid: int, timings: List[Create_Timings]):\n if clinic:\n for time in timings:\n timings_obj = ClinicTimings.get(clinic_id=clinicid,day=time.day)\n timings_obj.timings = time.timings\n await timings_obj.save()\n if not clinic:\n for time in timings:\n timings_obj = ClinicTimings.get(doctor_id=clinicid,day=time.day)\n timings_obj.timings = time.timings\n await timings_obj.save()\n return {\"success\":\"timing updated\"}\n\n@clinto_router.post(\"/getDoctorClinics\")\nasync def get_doctor_clinics(doctor:int):\n doctor_obj = await User.get(id=doctor).prefetch_related(\"workingclinics\")\n working_clinics = await doctor.workingclinics.all()\n return {\"working_clinics\": working_clinics,\"user\":doctor_obj}\n\n@clinto_router.post('/addRecopinist')\nasync def add_recopinist(data: Create_Recopinist):\n create_recopinist = await ClinicReceponists.create(clinic_id=clinic, user_id=user, **data.dict(exclude_unset=True))\n return create_recopinist\n\n@clinto_router.post('/addSlot')\nasync def add_slots(data: Create_AppointmentSlots,clinicid:int):\n create_slot = await AppointmentSlots.create(clinic_id=clinicid, user_id=user, **data.dict(exclude_unset=True))\n return create_slot\n\n@clinto_router.post('/addAppointments')\nasync def add_appointments(data: Create_AppointmentSlots, clinicid: int,user:int,slot:int,accepted_slot:Optional[int]=None):\n if accepted_slot is None:\n create_appointment = await Appointments.create(clinic_id=clinicid,user_id=user,requested_slot_id=slot,**data.dict(exclude_unset=True))\n if accepted_slot is not None:\n create_appointment = await Appointments.create(clinic_id=clinicid, user_id=user, requested_slot_id=slot,accepted_slot_id=accepted_slot **data.dict(exclude_unset=True))\n return create_appointment\n\n\n@clinto_router.get('/getAppointments')\nasync def get_appointments(limit: int, offset: int, status: Optional[AppointmentStatus]):\n if status is None:\n toReturn = appointment_view.limited_data(limit=limit,offset=offset)\n return toReturn\n toReturn = appointment_view.limited_data(limit=limit,offset=offset,status=status)\n return toReturn\n\n@clinto_router.get('/getSlots')\nasync def get_appointments(limit: int, offset: int, doctor:Optional[int]):\n if status is None:\n toReturn = appointment_view.limited_data(limit=limit,offset=offset)\n return toReturn\n toReturn = appointment_view.limited_data(limit=limit,offset=offset,status=status)\n return toReturn\n\n\n \n \n \n \n \n\n\n \n\n\n\n\n\n\n\n\n\n\n\n\n\n \n\n\n\n\n\n\n\n\n\n \n \n\n","sub_path":"src/apps/prescriptionapp/endpoints.py","file_name":"endpoints.py","file_ext":"py","file_size_in_byte":5075,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"175592534","text":"#!/usr/bin/env python3\n# -*- coding:utf-8 -*-\n# author: bigfoolliu\n\n\nimport os\nimport sys\nimport logging\n\nfrom tornado.options import define, options\nimport tornado.options\nimport tornado.httpserver\nimport tornado.ioloop\nimport tornado.web\n\nfrom config import ALLOW_ORIGIN, ALLOW_METHODS, ALLOW_HEADERS\n\nsys.path.append(os.path.dirname(__file__))\n\ndefine(\"port\", default=8000, help=\"run on the given port\", type=int)\n\n\nclass BaseHandler(tornado.web.RequestHandler):\n\n def set_default_headers(self):\n \"\"\"\n 使用响应头和options方法来支持跨域\n \"\"\"\n allow_origin = ALLOW_ORIGIN\n allow_methods = ALLOW_METHODS\n allow_headers = ALLOW_HEADERS\n self.set_header('Access-Control-Allow-Origin', allow_origin) # 跨域允许指定的域名访问该资源, 只可以指定一个\n self.set_header('Access-Control-Allow-Methods', allow_methods) # 跨域允许包含的方法\n self.set_header('Access-Control-Allow-Headers', allow_headers) # 跨域允许包含的头\n self.set_header('Access-Control-Max-Age', 1000) # 预检请求在浏览器缓存时间,改段时间内发post等请求不会再发预检请求\n\n def options(self):\n \"\"\"\n 预检请求,由浏览器发起,了解服务器对于某些接口等资源的支持情况\n 跨域请求,自定义请求头或者请求头中content-type为特殊格式都会发起\n \"\"\"\n self.set_status(200) # 先假定所有的资源都支持\n self.finish() # 结束请求\n\n\nclass IndexHandler(BaseHandler):\n def get(self):\n greeting = self.get_argument('greeting', 'Hello')\n self.write(f'{greeting}, friendly user!')\n self.finish()\n\n\nclass UploadHandler(BaseHandler):\n def post(self):\n print(self.request)\n self.write(\"ok\")\n self.finish()\n\n\ndef make_app():\n handlers = [\n (r\"/\", IndexHandler),\n (r\"/upload/single\", UploadHandler)\n ]\n return tornado.web.Application(handlers=handlers)\n\n\nif __name__ == \"__main__\":\n tornado.options.parse_command_line()\n logging.info('making app')\n app = make_app()\n logging.info(\"Starting tornado at http://127.0.0.1:8000\")\n http_server = tornado.httpserver.HTTPServer(app)\n http_server.listen(options.port)\n tornado.ioloop.IOLoop.instance().start()\n","sub_path":"playGround/backend/application.py","file_name":"application.py","file_ext":"py","file_size_in_byte":2341,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"402376049","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\ntry:\n from unittest import mock\nexcept ImportError:\n import mock\n\nfrom django.conf import settings\nfrom django.test import TestCase\nimport requests\n\nfrom channels.backends.yo import YoChannel\nfrom channels.exceptions import HttpError\n\n\nconfig = settings.CHANNELS[\"CHANNELS\"][\"yo\"]\n\n\nclass YoChannelTestCase(TestCase):\n def setUp(self):\n self.channel = YoChannel(**config)\n\n @mock.patch(\"requests.post\")\n def test_send(self, m):\n response = requests.Response()\n response.status_code = requests.codes.ok\n m.return_value = response\n\n # Just Yo\n self.channel.send(None)\n\n # Yo with text\n self.channel.send(\"🍣\")\n\n # Yo Link\n self.channel.send(None, options={\n \"yo\": {\"link\": \"http://docs.justyo.co/v1.0/docs/yo\"}})\n\n # Yo Location\n self.channel.send(None, options={\n \"yo\": {\"location\": \"35.0261581,135.7818476\"}})\n\n @mock.patch(\"requests.post\")\n def test_send_fail(self, m):\n response = requests.Response()\n response.status_code = requests.codes.forbidden\n m.return_value = response\n\n with self.assertRaises(HttpError):\n self.channel.send(None, fail_silently=False)\n\n self.channel.send(None, fail_silently=True)\n","sub_path":"tests/tests/backends/test_yo.py","file_name":"test_yo.py","file_ext":"py","file_size_in_byte":1347,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"566347999","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 ('tutor', '0015_auto_20150401_1126'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='MyPerson',\n fields=[\n ],\n options={\n 'proxy': True,\n },\n bases=('tutor.person',),\n ),\n ]\n","sub_path":"abosadmin/tutor/migrations/0016_myperson.py","file_name":"0016_myperson.py","file_ext":"py","file_size_in_byte":460,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"24611876","text":"from django.conf.urls.defaults import patterns, include, url\nfrom django.views.generic.simple import redirect_to\nfrom django_hello_world.hello.views import *\nfrom django.contrib.auth.views import login, logout\nfrom django.conf import settings\n# Uncomment the next two lines to enable the admin:\nfrom django.contrib import admin\n\nadmin.autodiscover()\n\nurlpatterns = patterns('',\n url(r'^$', HomePageView.as_view(), name='home'),\n url(r'^request/', RequestListView.as_view(),\n name='request'),\n # auth urls\n url(r'^accounts/login/$', login, name='login'),\n url(r'^accounts/logout/$', logout, name='logout'),\n url(r'^accounts/profile/$', redirect_to, {'url': '/'},\n name='accounts-profile'),\n url(r'^accounts/$', redirect_to, {'url': '/'},\n name='accounts'),\n # edit urls\n url(r'^edit/$', edit_view, name=\"edit-view\"),\n # admin urls\n url(r'^admin/doc/',\n include('django.contrib.admindocs.urls')),\n url(r'^admin/', include(admin.site.urls)), )\n\nurlpatterns += patterns('',\n url(r'^media/(?P.*)$', 'django.views.static.serve',\n {\n 'document_root': settings.MEDIA_ROOT,\n }),\n url(r'^static(?P.*)$', 'django.views.static.serve',\n {\n 'document_root': settings.STATIC_ROOT,\n }),\n )\n","sub_path":"django_hello_world/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1641,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"632379572","text":"from . import config, flaskmail\n\nfrom flask.ext.mail import Message\nfrom flask import render_template, current_app\n\nfrom datetime import datetime\nfrom threading import Thread\n\n\ndef send_email(to, subject, template, **kwargs):\n\n app = current_app._get_current_object()\n\n msg = Message(app.config['MAIL_SUBJECT_PREFIX'] + subject,\n sender = app.config['MAIL_SENDER'],\n recipients = [to])\n msg.body = render_template(template + '.txt', **kwargs)\n msg.html = render_template(template + '.html', **kwargs)\n\n def send_async_email():\n try:\n with app.app_context():\n flaskmail.send(msg)\n except:\n return False\n print(\"{} [INFO] finished sending email from '{}' to '{}' \"\n \"with subject '{}'\".format(datetime.now(),\n msg.sender, to, subject))\n\n thr = Thread(target=send_async_email)\n thr.start()\n return thr\n","sub_path":"app/email.py","file_name":"email.py","file_ext":"py","file_size_in_byte":941,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"524525449","text":"import os\nfrom collections import OrderedDict # For ordered Constance settings\nfrom django.utils.translation import ugettext_lazy as _ # Translations\n\n\n# Build paths inside the project like this: os.path.join(BASE_DIR, ...)\nBASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\n\n\n# Secret Key\ntry:\n SECRET_KEY\nexcept NameError:\n SECRET_FILE = os.path.join(BASE_DIR, 'secret.txt')\n try:\n SECRET_KEY = open(SECRET_FILE).read().strip()\n except IOError:\n try:\n import random\n SECRET_KEY = ''.join([random.SystemRandom().choice('abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)') for i in range(50)])\n secret = open(SECRET_FILE, 'w')\n secret.write(SECRET_KEY)\n secret.close()\n except IOError:\n Exception('Please create a %s file with random characters \\\n to generate your secret key!' % SECRET_FILE)\n\n\n# Application definition\nINSTALLED_APPS = [\n 'modeltranslation',\n 'django.contrib.admin',\n 'django.contrib.auth',\n 'django.contrib.contenttypes',\n 'django.contrib.sessions',\n 'django.contrib.messages',\n 'django.contrib.staticfiles',\n 'widget_tweaks',\n 'constance',\n 'constance.backends.database',\n 'ckeditor',\n 'ckeditor_uploader',\n 'cms',\n 'storages'\n]\n\nMIDDLEWARE = [\n 'django.middleware.security.SecurityMiddleware',\n 'django.contrib.sessions.middleware.SessionMiddleware',\n 'django.middleware.locale.LocaleMiddleware',\n 'django.middleware.common.CommonMiddleware',\n 'django.middleware.csrf.CsrfViewMiddleware',\n 'django.contrib.auth.middleware.AuthenticationMiddleware',\n 'django.contrib.messages.middleware.MessageMiddleware',\n 'django.middleware.clickjacking.XFrameOptionsMiddleware',\n]\n\nROOT_URLCONF = 'mcms.urls'\n\nTEMPLATES = [\n {\n 'BACKEND': 'django.template.backends.django.DjangoTemplates',\n 'DIRS': [],\n 'APP_DIRS': True,\n 'OPTIONS': {\n 'context_processors': [\n 'django.template.context_processors.debug',\n 'django.template.context_processors.request',\n 'django.contrib.auth.context_processors.auth',\n 'django.contrib.messages.context_processors.messages',\n 'constance.context_processors.config',\n 'cms.context_processors.menu_processor',\n 'django.template.context_processors.media',\n 'django.template.context_processors.i18n'\n ],\n },\n },\n]\n\nWSGI_APPLICATION = 'mcms.wsgi.application'\n\n\n# Database\n# https://docs.djangoproject.com/en/1.10/ref/settings/#databases\n\nDATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.sqlite3',\n 'NAME': 'db.sqlite3'\n }\n}\n\n\n# Password validation\n# https://docs.djangoproject.com/en/1.10/ref/settings/#auth-password-validators\n\nAUTH_PASSWORD_VALIDATORS = [\n {\n 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',\n },\n {\n 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',\n },\n {\n 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',\n },\n {\n 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',\n },\n]\n\n\n# Internationalization\n# https://docs.djangoproject.com/en/1.10/topics/i18n/\n\nLANGUAGE_CODE = 'en'\n\nLANGUAGES = [\n ('en', _('English')),\n ('pl', _('Polish')),\n]\n\n\nTIME_ZONE = 'Europe/Berlin'\n\nUSE_I18N = True\nUSE_L10N = True\nUSE_TZ = True\n\n# Custom dynamic settings with Constance\nCONSTANCE_BACKEND = 'constance.backends.database.DatabaseBackend'\n\nCONSTANCE_CONFIG = OrderedDict([\n # General settings\n ('SITE_NAME', ('mcms', '', str)),\n ('TAGLINE', ('simple django cms', '', str)),\n ('TAGLINE_PL', ('simple django cms', '', str)),\n # Menu\n ('MENU_ENABLED', (True, '', bool)),\n # Homepage\n ('HOMEPAGE_CONTENT', ('', '', str)),\n ('HOMEPAGE_CONTENT_PL', ('', '', str)),\n # Footer\n ('FOOTER_ENABLED', (True, '', bool)),\n ('FOOTER_CONTENT', ('© mcms 2017', '', str)),\n # Sidebar\n ('SIDEBAR_GLOBAL', (True, '', bool)),\n # Portfolio\n ('PORTFOLIO_ENABLED', (False, '', bool)),\n # SEO\n ('SEO_NOINDEX', (False, '', bool)),\n])\n\n# For login required pages\nLOGIN_REDIRECT_URL = '/'\n\n# CKEditor\nCKEDITOR_UPLOAD_PATH = \"uploads/\"\nCKEDITOR_IMAGE_BACKEND = 'pillow'\nCKEDITOR_JQUERY_URL = 'https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js'\nCKEDITOR_CONFIGS = {\n 'default': {\n 'toolbar': 'Custom',\n 'toolbar_Custom': [\n ['Maximize', 'Format', 'Bold', 'Italic', 'Underline', '-', 'TextColor', 'BGColor'],\n ['NumberedList', 'BulletedList', '-', 'Outdent', 'Indent', '-', 'JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock'],\n ['Link', 'Unlink', 'Anchor', 'Image', 'Embed', '-'],\n ['Undo', 'Redo', 'Cut', 'Copy', 'Paste', 'PasteText', 'PasteFromWord', '-', 'Undo', 'Redo', 'Find', 'Replace', '-', 'SelectAll', '-', 'Source']\n ],\n 'height': 400,\n 'width': '100%',\n 'extraPlugins': ','.join(\n [\n 'image2',\n 'embed',\n ]),\n 'language': 'en',\n },\n\n}\n\n# Deployment\nALLOWED_HOSTS = ['*']\nDEBUG = False\n\n# Load local settings in development\ntry:\n from mcms.local_settings import *\nexcept ImportError:\n pass\n","sub_path":"mcms/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":5425,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"552381035","text":"import pyowm\nimport telebot\n\nbot = telebot.TeleBot(\"776943820:AAGq2dyoqj_IgEKQNaculcHYh1Ws-qfxzHw\")\n\nowm = pyowm.OWM('6d00d1d4e704068d70191bad2673e0cc', language=\"ru\") # You MUST provide a valid API key\n\nprint(\"Started\")\n\n\n@bot.message_handler(commands=['start', 'help'])\ndef send_welcome(message):\n bot.reply_to(message, \"Приветствую! Напишите название города\")\n\n\n@bot.message_handler(content_types=['text'])\ndef send_msg(message):\n bot.send_message(message.chat.id, get_weather(message.text))\n\n\n# get_weather(message.text)\n\n\ndef get_weather(city):\n try:\n observation = owm.weather_at_place(city)\n w = observation.get_weather()\n t = w.get_temperature('celsius')[\"temp\"]\n return \"В городе \" + city + \" сейчас \" + w.get_detailed_status() + \"\\n\" + \"Температура \" + str(t) + \" градусов\"\n except:\n return \"Город не найден\"\n return answ\n\n\n# Search for current weather in London (Great Britain)\n# observation = owm.weather_at_place(input(\"Какой город? \"))\n# w = observation.get_weather()\n# t = w.get_temperature('celsius')[\"temp\"]\n# print(w)\n# print(t)\n\n# input()\n\nbot.polling(none_stop=True)\n","sub_path":"WeatherBot.py","file_name":"WeatherBot.py","file_ext":"py","file_size_in_byte":1226,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"376347966","text":"#! /usr/bin/env python\n# -*- coding: utf-8 -*-\n\n# URLconf\nfrom django.conf.urls import patterns ,url ,include\n\nfrom adam2014 import views\n\nurlpatterns = patterns(\"\", \n \turl(r'^hello$',views.helloworld,name='helloworld'),\n\n \t# 手机验证\n \t# GET\n \t# {phonenum, verifycode, .... }\n \turl(r'^register$', views.register, name='register'),\n\n \t# 基本信息\n \t# POST\n \t# {nickname, passoword, sex, age, ...}\n \t#url(r'^register$', views.register, name='register'),\n\n \t# 登陆\n \t# GET\n \t# {phonenum, password}\n \turl(r'^signin$', views.signin, name='signin'),\n\t\n \t# 更新通讯录\n \t# GET\n \t#url(r'^F5contact$', views.F5contact, name='F5contact'),\n\t\n \t# 刷新所有人位置\n \t# GET\n \t#url(r'^F5allPSN$', views.F5allPSN, name='F5allPSN'),\n\t\n \t# 快速获取单人地理位置\n \t# GET\n \t# {id}\n \turl(r'^getPSN$', views.getPSN, name='getPSN'),\n\n \t# 修改个人信息\n \t# POST\n \t# {nickname, sex, age, ....}\n \turl(r'^editinfo$', views.editinfo, name='editinfo'),\n\n \t# 更改头像\n \t# POST\n \turl(r'^editphoto$', views.editphoto, name='editphoto'),\n\n \t# 添加好友\n \t# POST\n \t# {request_user_phone}\n \turl(r'^addfriend$', views.addfriend, name='addfriend'),\n\n\n \t# 确认添加好友\n \t# POST\n \t# {confirmed,request_user_phone,self_user_phone}\n \turl(r'^confirm_addfriend$', views.confirm_addfriend, name='confirm_addfriend'),\n\n \t# 邀请好友\n \t# POST\n \t# {phonenum, name}\n \turl(r'^invitefriend$', views.invitefriend, name='invitefriend'),\n\n \t# 分享位置\n \t# POST\n \t# {PSN}\n \turl(r'^updatePSN$', views.updatePSN, name='updatePSN'),\n\n \t# 修改好友权限\n \t# POST\n \t# {top, block, delete, alias}\n \turl(r'^setfriend$', views.setfriend, name='setfriend'),\n\n # 用户登陆状态的test\n #url(r'^test1$', views.test1, name='test1'),\n # url(r'^test2/$', views.test2, name='test2'),\n # url(r'^test3/$', views.test3, name='test3'),\n # url(r'^test4/$', views.test4, name='test4'),\n\n\n #退出登陆\n # POST\n url(r'^signout', views.signout, name='signout'),\n\n #获得好友列表和好友详细信息,还有用户所加入的群组\n # POST\n url(r'^getFRandGroups', views.getFRandGroups, name='getFRandGroups'),\n\n\n #新建群组\n # POST\n url(r'^newAgroup', views.newAgroup, name='newAgroup'),\n\n #加人入群\n # POST\n url(r'^addUserToGroup', views.addUserToGroup, name='addUserToGroup'),\n\n #用户退群\n # POST\n url(r'^deleteUserToGroup', views.deleteUserToGroup, name='deleteUserToGroup'),\n\n #删除好友\n # POST\n url(r'^deleteFriendRelation', views.deleteFriendRelation, name='deleteFriendRelation'),\n\n\n\n\n\n\n\n\n #readSession\n url(r'^readSession', views.readSession, name='readSession'),\n\n\t)\n\n\n","sub_path":"zzc/adam2014/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":2663,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"593708509","text":"\"\"\"\nJoin dim and hash partitioned fact.\n\nCampaign meta:\n['campaign_00', 'video campaign \"euhvnlkkhy\"', 'metadata 1']\n['campaign_01', 'video campaign \"vuozqifebt\"', 'metadata 1']\n['campaign_02', 'video campaign \"mbtfddmblb\"', 'metadata 1']\n...\n\nImpressions.\n['50000', 'campaign_00', 'video_0', '0.5']\n['50018', 'campaign_08', 'video_0', '0.3333333333333333']\n['50020', 'campaign_00', 'video_0', '0.25']\n['50030', 'campaign_00', 'video_0', '0.2']\n...\n\n\"\"\"\n\n\nimport os, sys, csv, gzip\nimport io, time, math\nimport tempfile\nimport asyncio\nimport aioboto3\n\nimport boto3, shutil, string, random\nfrom pprint import pprint as pp\nfrom os.path import isdir, isfile, join\n\nfrom os import linesep\n\n\n\ntry:\n\timport cStringIO\nexcept ImportError:\n\timport io as cStringIO\n\n\t\t\ne=sys.exit\t\n\n\t\t\ns3\t\t\t= boto3.client('s3')\nbucket_name\t= 'crossix-test'\nfact_name \t= 'campaign_2k_c10.csv.gz'\nufn\t\t\t= 'unique_cn.csv'\n\nsql_stmt \t= \"\"\"SELECT * FROM s3object S \"\"\" \n\ncdim_fn\t\t= 'cdim_10_upd.csv'\n\ncdim_s3fn \t= 'cdim_1000.csv.gz'\ncfact_s3fn\t= 'campaign_100k_c1000.csv.gz'\n\ndim_key_col_pos=0\nfact_key_col_pos=1\n\ncolsep\t= ','\t\nkey_pos_in_fact_fn = 2\npart_pos_in_fact_fn = 1\ns3\t= boto3.client('s3')\ndim_cols_to_append = [2]\ndim_to_fact_cols = {2:4}\ns3_updated_fact_tn = 'FACT_IMPRESSIONS_UPDATED'\nif 0:\n\n\t\n\n\ttry:\n\t\timport __builtin__ as builtins\n\texcept:\n\t\timport builtins\n\t\t\n\tbuiltins.bucket_name=bucket_name\n\tbuiltins.fact_name=fact_name\n\tbuiltins.dim_key_col_pos=dim_key_col_pos\n\tbuiltins.fact_key_col_pos=fact_key_col_pos\n\tbuiltins.key_pos_in_fact_fn=key_pos_in_fact_fn\n\tbuiltins.part_pos_in_fact_fn=part_pos_in_fact_fn\n\tbuiltins.s3=s3\n\tbuiltins.colsep=colsep\n\tbuiltins.dim_to_fact_cols=dim_to_fact_cols\n\tbuiltins.s3_updated_fact_tn=s3_updated_fact_tn\n\tfrom include.update import get_files_to_update, update_and_upload\n\n\nif 0: #Create updated dim\n\twith open(cdim_fn, mode='w') as fh:\n\t\t\n\t\tcsvw = csv.writer(fh, delimiter = ',', quotechar = '\"', lineterminator = '\\n', quoting=csv.QUOTE_MINIMAL)\n\t\tfor i in range(10):\n\t\t\trow=['campaign_%02d' % (i), \t'video campaign \"%s\"' % \\\n\t\t\t(''.join(random.choice(string.ascii_lowercase) for i in range(100))), 'metadata 2']\n\t\t\tprint (row)\n\t\t\tcsvw.writerow(row)\n\t\t\t\n\te()\n\t\n\t\nif 0: #Create fact\n\twith open('campaign_100k_c1000.csv', mode='w') as fh:\n\t\t\n\t\tcsvw = csv.writer(fh, delimiter = ',', quotechar = '\"', lineterminator = '\\n', quoting=csv.QUOTE_MINIMAL)\n\t\tfor i in range(100000):\t\t\n\t\t\trow=[50000+i,'campaign_%04d' % (int(i)%1000), \t'video_%s' % (int(i)//100), \t1/(i//10+2)]\n\t\t\t#print(row)\n\t\t\tcsvw.writerow(row)\n\t\t\t\n\te()\n\t\n\t\n\t\ns = time.perf_counter()\n\nDIM_COLCNT=1\ndim=[]\ns3_prefix = 'tables'\ns3_dimtn = 'FACT_IMPRESSIONS_UPDATED'\ns3_dimfn = 'sum.csv'\t\nkey='%s/%s/B_0/FACT_IMPRESSIONS_UPDATED.B_0.campaign_00.updated_fact_from_dim.csv.gz' % (s3_prefix, s3_dimtn)\nprint(key)\nif 0: #count dim from s3\n\tsql_stmt \t= \"\"\"SELECT avg(cast(S._4 as float)) FROM s3object S\"\"\" \n\treq_dim = s3.select_object_content(\n\t\tBucket\t= bucket_name,\n\t\tKey\t\t= key,\n\t\tExpressionType\t= 'SQL',\n\t\tExpression\t\t= sql_stmt,\n\t\tInputSerialization \t= { 'CompressionType':'GZIP', \n\t\t'CSV': {'FileHeaderInfo': 'None'}},\n\t\tOutputSerialization = {'CSV': {\n\t\t\t\t\t'RecordDelimiter': linesep,\n\t\t\t\t\t'FieldDelimiter': ','}},\n\t\t#ScanRange = {'Start':0, 'End':40000 }\n\t)\n\n\n\tdef count_dim(req, dim):\n\n\t\tfor event in req['Payload']:\n\t\t\tif 'Records' in event:\n\t\t\t\trr=event['Records']['Payload'].decode('utf-8')\n\t\t\t\tfor i, rec in enumerate(rr.split(linesep)):\n\t\t\t\t\tif rec:\n\t\t\t\t\t\trow=rec.split(colsep)\n\t\t\t\t\t\tif row:\n\t\t\t\t\t\t\tdim.append(row)\n\t\t\t\t\t\t\tprint(row)\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\traise\n\n\tcount_dim(req_dim, dim)\n\t#pp(dim)\n\t#e()\n\n\n\n\n\n\n\nif 1:\n\tFACT_COLCNT=4\n\tfact={}\n\ts3_prefix = 'tables'\n\ts3_fact_tn = 'FACT_IMPRESSIONS_UPDATED'\n\tpart_name = 'B_0'\n\t#s3_fact_fn = '%s.%s.campaign_00.campaign.csv.gz' % (s3_fact_tn, part_name)\n\t\n\t\n\t\n\ts3r\t\t= boto3.resource('s3')\n\tprint(bucket_name)\n\tmybucket = s3r.Bucket(bucket_name)\n\t\n\tbucket_prefix=\"%s/%s/\" % (s3_prefix, s3_fact_tn)\n\tprint(bucket_prefix)\n\tobjs = mybucket.objects.filter(\n\tPrefix = bucket_prefix)\n\n\t\n\t\t\n\tdef get_key_from_fn(fn):\n\t\t\n\t\treturn fn.split(\".\")[key_pos_in_fact_fn]\n\tdef get_part_from_fn(fn):\t\t\n\t\treturn fn.split(\".\")[part_pos_in_fact_fn]\n\n\tasync def get_files_to_scan(objs, queue):\n\n\t\tfor obj in objs:\n\t\t\t#print(obj.key)\n\t\t\t\n\t\t\t#path, filename = os.path.split(obj.key)\n\t\t\t#part_name\t= get_part_from_fn(filename)\n\t\t\tif obj.key:\n\t\t\t\t#print(filename)\n\t\t\t\tawait queue.put(obj.key)\n\t\t\telse:\n\t\t\t\traise Exception('filename is not set')\n\t\tawait queue.put(None)\n\n\n\tasync def sums_in_file(counts_queue, s3_key):\n\t\tif 1: #Fact partitioner\n\n\t\t\tsql_stmt \t= \"\"\"SELECT count(*), sum(cast(S._4 as float)) FROM s3object S\"\"\" \n\t\t\treq_fact = s3.select_object_content(\n\t\t\t\tBucket\t= bucket_name,\n\t\t\t\tKey\t\t= s3_key,\n\t\t\t\tExpressionType\t= 'SQL',\n\t\t\t\tExpression\t\t= sql_stmt,\n\t\t\t\tInputSerialization \t= { 'CompressionType':'GZIP', \n\t\t\t\t'CSV': {'FileHeaderInfo': 'None'}},\n\t\t\t\tOutputSerialization = {'CSV': {\n\t\t\t\t\t\t\t'RecordDelimiter': '\\n',\n\t\t\t\t\t\t\t'FieldDelimiter': ','}},\n\t\t\t\t\n\t\t\t)\n\t\n\t\tfor event in req_fact['Payload']:\n\t\t\tif 'Records' in event:\n\t\t\t\trr=event['Records']['Payload'].decode('utf-8')\n\t\t\t\tfor i, rec in enumerate(rr.split(linesep)):\n\t\t\t\t\tif rec:\n\t\t\t\t\t\trow=rec.split(colsep)\n\t\t\t\t\t\tif row:\n\t\t\t\t\t\t\tprint('VP cnt, sum:', row)\n\t\t\t\t\t\t\tawait counts_queue.put(row)\n\n\t\t#await counts_queue.put(None)\n\t\t\n\t\n\tasync def sums_in_table(queue, counts_queue):\n\t\t\n\t\treaders=[]\n\t\tqz=[]\n\t\twhile True: \n\t\t\trow = await queue.get()\n\t\t\tqueue.task_done()\n\t\t\tif row:\n\t\t\t\ts3_key = row\n\t\t\t\tprint('S3 key: ',s3_key)\n\t\t\t\tif 1:\n\t\t\t\t\treaders.append(asyncio.create_task(sums_in_file(counts_queue, s3_key)))\n\n\t\t\telse:\n\t\t\t\tbreak\n\t\tawait asyncio.gather(*readers)\n\t\tawait counts_queue.put(None)\n\t\t\n\tasync def merge_sums(counts_queue, mean_q):\n\t\ttotal = 0\n\t\ttotals = 0\n\t\twhile True: \n\t\t\trow = await counts_queue.get()\n\t\t\tcounts_queue.task_done()\n\t\t\tif row:\n\t\t\t\tcnt = float(row[0])\n\t\t\t\tsm = float(row[1])\n\t\t\t\ttotal +=cnt\n\t\t\t\ttotals += sm\n\n\t\t\telse:\n\t\t\t\tbreak\n\t\tprint('Total rows:', total, ', sum:', totals)\n\t\tprint('Mean:', totals/total)\n\t\tawait mean_q.put(totals/total)\n\t\tawait mean_q.put(None)\n\t\t\n\tasync def s3_get_mean(mean_q):\n\t\tqueue = asyncio.Queue()\n\t\tcounts_queue = asyncio.Queue()\n\t\t\n\t\t\n\t\tawait asyncio.gather( get_files_to_scan(objs, queue), sums_in_table(queue, counts_queue), merge_sums(counts_queue, mean_q))\t\n\t\tawait queue.join()\n\t#////////////////////////////////////////////////////////\n\tasync def squares_in_file(counts_queue, s3_key, mean):\n\t\tif 1: #Fact partitioner\n\n\t\t\tsql_stmt \t= \"\"\"SELECT count(*), sum((cast(S._4 as float) - %s)*(cast(S._4 as float) - %s)) FROM s3object S\"\"\" \\\n\t\t\t% (mean, mean)\n\t\t\treq_fact = s3.select_object_content(\n\t\t\t\tBucket\t= bucket_name,\n\t\t\t\tKey\t\t= s3_key,\n\t\t\t\tExpressionType\t= 'SQL',\n\t\t\t\tExpression\t\t= sql_stmt,\n\t\t\t\tInputSerialization \t= { 'CompressionType':'GZIP', \n\t\t\t\t'CSV': {'FileHeaderInfo': 'None'}},\n\t\t\t\tOutputSerialization = {'CSV': {\n\t\t\t\t\t\t\t'RecordDelimiter': '\\n',\n\t\t\t\t\t\t\t'FieldDelimiter': ','}},\n\t\t\t\t\n\t\t\t)\n\t\n\t\tfor event in req_fact['Payload']:\n\t\t\tif 'Records' in event:\n\t\t\t\trr=event['Records']['Payload'].decode('utf-8')\n\t\t\t\tfor i, rec in enumerate(rr.split(linesep)):\n\t\t\t\t\tif rec:\n\t\t\t\t\t\trow=rec.split(colsep)\n\t\t\t\t\t\tif row:\n\t\t\t\t\t\t\tprint('VP cnt, square:', row)\n\t\t\t\t\t\t\tawait counts_queue.put(row)\n\t\t\t\t\t\t\t\n\tasync def squares_in_table(queue, counts_queue, mean):\n\t\t\n\t\treaders=[]\n\t\tqz=[]\n\t\twhile True: \n\t\t\trow = await queue.get()\n\t\t\tqueue.task_done()\n\t\t\tif row:\n\t\t\t\ts3_key = row\n\t\t\t\t#print('S3 key: ',s3_key)\n\t\t\t\tif 1:\n\t\t\t\t\treaders.append(asyncio.create_task(squares_in_file(counts_queue, s3_key,mean)))\n\n\t\t\telse:\n\t\t\t\tbreak\n\t\tawait asyncio.gather(*readers)\n\t\tawait counts_queue.put(None)\n\t\t\n\n\tasync def merge_squares(counts_queue):\n\t\ttotal = 0\n\t\ttotals = 0\n\t\twhile True: \n\t\t\trow = await counts_queue.get()\n\t\t\tcounts_queue.task_done()\n\t\t\tif row:\n\t\t\t\tcnt = float(row[0])\n\t\t\t\tsm = float(row[1])\n\t\t\t\ttotal +=cnt\n\t\t\t\ttotals += sm\n\n\t\t\telse:\n\t\t\t\tbreak\n\t\tprint('Total rows:', total, ', squares:', totals)\n\t\tprint('Stddev:', math.sqrt(totals/total))\n\t\t#await mean_q.put(totals/total)\n\t\t#await mean_q.put(None)\n\t\t\n\t\t\n\tasync def s3_get_stddev(mean_q):\n\t\tqueue = asyncio.Queue()\n\t\tcounts_queue = asyncio.Queue()\n\t\tmean = await mean_q.get()\n\t\t\n\t\tawait asyncio.gather( get_files_to_scan(objs, queue), squares_in_table(queue, counts_queue,mean), merge_squares(counts_queue))\t\n\t\tawait queue.join()\n\n\tif 0:\n\t\tasyncio.run(s3_count_fact())\n\t\telapsed = time.perf_counter() - s\n\t\tprint(f\"{__file__} executed in {elapsed:0.2f} seconds.\")\n\n\tif 1:\n\t\tmean_q = asyncio.Queue()\n\t\tasyncio.run(s3_get_mean(mean_q))\n\t\telapsed = time.perf_counter() - s\n\t\tprint(f\"Sum executed in {elapsed:0.2f} seconds.\")\n\n\tif 1:\n\t\t\n\t\tasyncio.run(s3_get_stddev(mean_q))\n\t\telapsed = time.perf_counter() - s\n\t\tprint(f\"Stddev executed in {elapsed:0.2f} seconds.\")\n\n\te()\n\nelapsed = time.perf_counter() - s\nprint(f\"{__file__} executed in {elapsed:0.2f} seconds.\")\n\n","sub_path":"aload/s3sum.py","file_name":"s3sum.py","file_ext":"py","file_size_in_byte":8838,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"219832916","text":"# coding=utf-8\n__author__ = 'wangqc'\n\n\nimport os\nimport sys\nimport logging\nimport math\nfrom datetime import datetime, timedelta\n\nimport pymongo\nimport pandas as pd\nimport numpy as np\nfrom sklearn.linear_model import LinearRegression\n\nreload(sys)\nsys.setdefaultencoding('utf-8')\nsys.path.append(os.path.join(os.path.split(os.path.realpath(__file__))[0], '..'))\nsys.path.append(os.path.join(os.path.split(os.path.realpath(__file__))[0], '../../util'))\n\nimport db as dbcon\nfrom common import dbutil\n\n\n# logging\n# logger_path = os.path.join(os.path.split(os.path.realpath(__file__))[0], 'logs/tmp.log')\nlogging.basicConfig(level=logging.INFO, format='%(name)-12s %(asctime)s %(levelname)-8s %(message)s')\nlogger_apkdownload = logging.getLogger('logger_apkdownload')\n\n\nclass Download_Optimization():\n\n def __init__(self):\n\n self.db = dbcon.connect_torndb()\n self.mongo = dbcon.connect_mongo()\n\n self.model = LinearRegression(fit_intercept=False)\n\n self.markets = (16010, 16020, 16030, 16040)\n self.sectors = [t.id for t in dbutil.get_tags_by_type(self.db, (11012,))]\n self.round_groups = {(1000, 1010, 1011, 1020): 'Pre-A',\n (1030, 1031, 1039, 1040, 1041): 'A~B',\n (1050, 1060, 1070, 1080, 1090, 1100, 1105, 1106, 1110): 'Post-B'}\n\n # day_range: (start_date, end_date)\n self.default_day_range = (100, 0)\n self.top_share = 0.05\n self.coef_threshold = 2\n self.modify_outlier = False\n\n def _get_cid_apk_pairs_by_sector_rounds(self, db, sector, round_group):\n\n sql_find_cid = '''\n select distinct c.id\n from company c join corporate cor on c.corporateId = cor.id join company_tag_rel ctr on c.id = ctr.companyId\n where ctr.tagId = %s and (c.active is null or c.active='Y') and c.type = 41010\n and c.round in %s and (ctr.active is null or ctr.active='Y')\n '''\n sql_find_apk = \"select domain from artifact where companyId=%s and type = 4050 and (active is null or active ='Y')\"\n\n return {cid.id: [apk.domain for apk in db.query(sql_find_apk % cid.id)] for cid in db.query(sql_find_cid % (sector, round_group))}\n\n def _train_model(self, apk, market, day_range=None, download_lower_bound=1000):\n\n day_range = day_range or self.default_day_range\n if day_range[0] < day_range[1]:\n raise ValueError(\"End day should be earlier than start day.\")\n df = pd.DataFrame(list(self.mongo.trend.android.find({'apkname': apk, 'appmarket': market,\n 'date': {'$gte': datetime.today() - timedelta(day_range[0]),\n '$lte': datetime.today() - timedelta(day_range[1])}}).sort([('date', 1)])))\n try:\n download, date = df['download'], df['date']\n except KeyError:\n return False\n download = np.array(download.fillna(0.0))\n if not download.any() or download[-1] < download_lower_bound:\n return False\n date = np.array([np.datetime64(d, 'D') for d in date])\n # y = np.array([np.float64(download[i+1] - download[i]) / np.float64(date[i+1] - date[i]) for i in xrange(len(download) - 1)])\n y = np.float64(download[1:] - download[:-1]) / np.float64(date[1:] - date[:-1])\n y[np.isnan(y)] = 0.0\n if self.modify_outlier:\n y = np.clip(y, 0, np.percentile(y, 97))\n X = np.arange(len(y)).reshape((-1, 1))\n try:\n self.model.fit(X, y)\n except ValueError:\n return False\n else:\n return True\n\n\n def _get_top_coef_by_sector_rounds(self, sector, round_group, top_share):\n\n cid_apk_pairs = self._get_cid_apk_pairs_by_sector_rounds(self.db, sector, round_group)\n cid_coef_pairs = []\n for cid, apks in cid_apk_pairs.items():\n temp_coef = 0.0\n for apk in apks:\n for market in self.markets:\n if self._train_model(apk, market):\n temp_coef = max(temp_coef, self.model.coef_)\n cid_coef_pairs.append((cid, temp_coef))\n return sorted(cid_coef_pairs, key=lambda x: x[1], reverse=True)[: int(len(cid_coef_pairs) * top_share)]\n\n\n def get_nice_download_cids(self, top_share=None, coef_threshold=None, sectors=None):\n\n top_share = top_share or self.top_share\n coef_threshold = coef_threshold or self.coef_threshold\n sectors = sectors or self.sectors\n count_cid = 0\n for sector in sectors:\n logger_apkdownload.info(\"Dealing tag id: %s\", sector)\n count_sector_cid = 0\n for round_group in sorted(self.round_groups):\n count_sector_round_cid = 0\n for cid, coef in self._get_top_coef_by_sector_rounds(sector, round_group, top_share):\n if coef >= coef_threshold:\n yield cid, math.log(coef, 2)\n count_sector_round_cid += 1\n logger_apkdownload.info('Tag id: %s Round: %s Nice download company amount: %s'\n % (sector, self.round_groups[round_group], count_sector_round_cid))\n count_sector_cid += count_sector_round_cid\n logger_apkdownload.info('Tag id: %s Nice download company amount: %s' % (sector, count_sector_cid))\n count_cid += count_sector_cid\n logger_apkdownload.info('Total nice download company amount: %s' % count_cid)\n\n\ndef test():\n\n test_do = Download_Optimization()\n with open('tmp/test_nice_download_output', 'w') as f:\n # 40 游戏\n for cid, score in test_do.get_nice_download_cids(sectors=[22, 40, 107]):\n f.write(dbutil.get_company_code(test_do.db, cid))\n f.write(' ')\n f.write(str(round(score, 4)))\n f.write('\\n')\n\n\ndef main():\n\n do = Download_Optimization()\n for cid, score in do.get_nice_download_cids():\n # 566646 下载优秀\n logger_apkdownload.info(\"Insert into company_tag_rel: companyid %s, tagid 566646\", cid)\n # dbutil.update_company_tag(do.db, cid, 566646, round(score, 4), \"Y\")\n do.db.close()\n\n\nif __name__ == \"__main__\":\n\n # test()\n main()\n","sub_path":"data/nlp/experiments/nice_download_u.py","file_name":"nice_download_u.py","file_ext":"py","file_size_in_byte":6268,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"425573044","text":"import os\nimport redis\nimport json\nfrom dotenv import load_dotenv\n\n\ndef create_dict_with_qa(file) -> dict:\n result = {}\n with open(file, 'r', encoding='KOI8-R') as _file:\n text_blocks = _file.read().split('\\n\\n')\n\n questions_and_answers_list = [text_block.strip('\\n') for text_block in text_blocks if\n 'Ответ' in text_block or 'Вопрос' in text_block]\n\n for num, text_block in enumerate(questions_and_answers_list):\n if 'Ответ' in text_block:\n question = ' '.join(questions_and_answers_list[num - 1].split('\\n')[1:])\n answer = ' '.join(text_block.split('\\n')[1:])\n result[question] = answer\n\n return result\n\n\ndef create_dict_with_qa_all_files(base_dir, files, num_files=None) -> dict:\n result = {}\n questions_and_answers_list = []\n for file in files[0:num_files]:\n with open(f'{base_dir}/{file}', 'r', encoding='KOI8-R') as _file:\n text_blocks = _file.read().split('\\n\\n')\n\n questions_and_answers_list.extend([text_block.strip('\\n') for text_block in text_blocks if\n 'Ответ' in text_block or 'Вопрос' in text_block])\n\n count = 1\n for num, text_block in enumerate(questions_and_answers_list):\n if 'Ответ' in text_block:\n question = ' '.join(questions_and_answers_list[num - 1].split('\\n')[1:])\n answer = ' '.join(text_block.split('\\n')[1:])\n result[f\"question_{count}\"] = {'question': question, 'answer': answer}\n count += 1\n\n return result\n\n\ndef update_redis(dir, db):\n files = os.listdir(dir)\n\n result = create_dict_with_qa_all_files(dir, files, 150)\n\n for key in result.keys():\n print(key)\n db.set(key, json.dumps(result[key]))\n\n db.set('questions', json.dumps(list(result.keys())))\n\n\nif __name__ == '__main__':\n load_dotenv()\n\n r = redis.Redis(host=os.environ['REDIS_HOST'],\n port=os.environ['REDIS_PORT'],\n password=os.environ['REDIS_PASSWORD'])\n dir_with_questions = 'quiz-questions'\n\n update_redis(dir_with_questions, r)\n","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2165,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"527488967","text":"import requests\n\ndef get_results_from_api():\n url = 'https://dennikn.sk/api/minute'\n resp = requests.get(url)\n resp.raise_for_status()\n site_json = resp.json()\n results = []\n for item in site_json['timeline']:\n results.append(item['content']['main'])\n\n return results\n\n","sub_path":"days/43-45-search-api/mpm_api/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":297,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"354800164","text":"from django.db import models\nfrom django.conf import settings\nfrom django.db.models.signals import post_save\n\nfrom accounts.models import GuestEmail\n# Create your models here.\n\nUser = settings.AUTH_USER_MODEL\n\nclass BillingProfileManager(models.Manager):\n def new_or_get(self,request):\n user = request.user\n guest_email_id = request.session.get('guest_email_id')\n created = False\n obj =None\n if user.is_authenticated:\n 'logged in user checkout; remember payement stuff'\n obj , created = self.model.objects.get_or_create(user=user , email = user.email)\n elif guest_email_id is not None:\n 'guest user checkout;auto reloads payment stuff'\n guest_email_obj = GuestEmail.objects.get(id=guest_email_id)\n obj , created = self.model.objects.get_or_create( email = guest_email_obj.email)\n else:\n pass\n return obj,created # billing_profile -->obj\n\n\nclass BillingProfile(models.Model):\n user = models.OneToOneField(User,on_delete=models.CASCADE, null=True ,blank=True)\n email = models.EmailField()\n active = models.BooleanField(default=True)\n update = models.DateTimeField(auto_now=True)\n timestamp = models.DateTimeField(auto_now_add=True)\n \n # customer_id in Stripe or Braintree\n\n objects = BillingProfileManager()\n\n def __str__(self):\n return self.email\n\n# if we have customer_id\n#def billing_profile_reciever(sender,instance,created,*args,**kwargs): \n #if created:\n #print(\"ACTUAL API REQUEST Send to stripe or braintree\")\n #instance.customer_id = newID\n #instance.save()\n\ndef user_created_reciever(sender,instance,created,*args,**kwargs): ### to automatically create billing profile when user is created.\n if created and instance.email:\n BillingProfile.objects.get_or_create(user=instance, email=instance.email)\n\n\npost_save.connect(user_created_reciever,sender=User)\n","sub_path":"goel_enterprises/billing/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2001,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"351537263","text":"from typing import List\nfrom ..configs.ApiConnection import SkyscannerFlights, SkyscannerCountries\nfrom ..utils.scripts import mergeSort\n\n\nclass FlightService():\n def __init__(self):\n self.skyscannerFlights = SkyscannerFlights()\n self.skyscannerCountries = SkyscannerCountries()\n\n def getFlights(self, outBound, inBound) -> List:\n nodes = []\n edges = []\n requestData = self.skyscannerFlights.connect(outBound, inBound)\n\n nodes = self.getPlaces(requestData)\n edges = self.createEdges(requestData)\n\n return {\n \"nodes\": nodes,\n \"edges\": edges\n }\n\n def getCountry(self) -> List:\n countries = []\n sorted_countries = []\n requestData = self.skyscannerCountries.connect()\n\n for node in requestData['Countries']:\n countries.append({\n \"name\": node['Name'],\n \"code\": node['Code']\n })\n\n sorted_countries = mergeSort(countries)\n\n return sorted_countries\n\n\n def getPlaces(self, requestData):\n places = []\n\n for node in requestData['Places']:\n if node['Type'] == \"Station\":\n places.append({\n \"id\": node['PlaceId'],\n \"cityName\": node['CityName'],\n \"cityIdStr\": node['CityId'],\n \"name\": node['Name'],\n \"country\": node['CountryName'],\n \"label\": f'{node[\"CityName\"]} - { node[\"IataCode\"]}'\n })\n\n return places\n\n def createEdges(self, requestData):\n edges = []\n\n for quote in requestData['Quotes']:\n edge = (quote['OutboundLeg']['OriginId'], quote['OutboundLeg']['DestinationId'], quote['MinPrice'])\n edges.append({\n \"from\": edge[0],\n \"to\": edge[1],\n \"label\": str(edge[2])\n })\n\n return edges\n","sub_path":"backend/src/services/FlightService.py","file_name":"FlightService.py","file_ext":"py","file_size_in_byte":1941,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"408884112","text":"from configdb import get_connection\n\ndef add_invoice(number, document, date, price, balance ):\n cnn = get_connection()\n with cnn.cursor() as cursor:\n cursor.execute(\"INSERT INTO invoice (number, document, date, price, balance) VALUES (%s,(select document from customer where document = %s),%s,%s,%s)\",(number, document, date, price, balance))\n cnn.commit()\n cnn.close()\n\ndef update_invoice( number, document, date, price, balance, id):\n cnn = get_connection()\n with cnn.cursor() as cursor:\n cursor.execute(\"UPDATE invoice SET number = %s, document = %s, date = %s, price = %s, balance = %s WHERE id = %s\",(number, document, date, price, balance, id))\n cnn.commit()\n cnn.close()\n\ndef delete_invoice(id):\n cnn = get_connection()\n with cnn.cursor() as cursor:\n cursor.execute(\"DELETE FROM invoice WHERE balance = 0 AND id=%s\", (id))\n cnn.commit()\n cnn.close()\n\ndef get_invoices():\n cnn = get_connection()\n invoices = []\n with cnn.cursor() as cursor:\n cursor.execute(\"SELECT id, document, number, date, price, balance FROM invoice\")\n invoices = cursor.fetchall()\n cnn.close()\n return invoices\n\ndef get_invoice_id(id):\n cnn = get_connection()\n invoice = None\n with cnn.cursor() as cursor:\n cursor.execute(\"SELECT id, number, document, date, price, balance FROM invoice WHERE id = %s\",(id))\n invoice = cursor.fetchone()\n cnn.close\n return invoice\n\ndef get_customerInvoice_doc(document):\n cnn = get_connection()\n invoice = None\n with cnn.cursor() as cursor:\n cursor.execute(\"SELECT document FROM customer WHERE document = %s\",(document))\n invoice = cursor.fetchone()\n cnn.close\n return invoice","sub_path":"invoice_controller.py","file_name":"invoice_controller.py","file_ext":"py","file_size_in_byte":1730,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"493764569","text":"import pandas as pd\nimport numpy as np\nimport warnings\nfrom global_vars.constants import *\nimport yaml\nfrom utils.Utils import *\n\n\nimport numbers\n\n\nclass Caster:\n @staticmethod\n def main_cast_and_prepare(df_c):\n df = df_c.copy()\n df = Caster._to_time(['BirthDay', 'Дата закрытия займа', 'Дата прописки', 'Дата заведения анкеты', 'Дата и время открытия по договору', 'Дата открытия по договору', 'Дата закрытия займа', 'sa_8 Дата регистрации последнего аккаунта', 'sa_9 Дата регистрации первого аккаунта'], df)\n df = Caster._to_numeric(df)\n if 'Ставка займа' in df.columns: df['Ставка займа'] = df['Ставка займа']/100\n if 'Сумма выдачи' in df.columns:\n df['Сумма выдачи'] = df['Сумма выдачи'] / 1000\n else:\n df['Сумма выдачи'] = np.nan\n rub_cols = ['Должок', 'На руках', 'Общий лимит', 'Лимит', 'real flow', 'real flow30', 'real flow60', 'real flow90']\n for col in rub_cols:\n if col in df.columns:\n df[col] = df[col] / 1000\n\n\n\n df['Макс прошлых выдач микро'] = np.floor(df['Макс прошлых выдач микро'] / 1000)\n\n with warnings.catch_warnings():\n warnings.simplefilter(\"ignore\", category=RuntimeWarning)\n max_credit_time = get_parameters()['max_credit_time']\n df['Фактическая длительность кредита'] = np.minimum(\n (df['Дата закрытия займа'] - df['Дата открытия по договору']).dt.days.values, max_credit_time)\n df['Фактическая длительность кредита'] = df['Фактическая длительность кредита'].fillna(-10000)\n df = Utils.classify_y(df)[0]\n df = Caster.eval_stavka_plus(df)[0]\n df = Utils.add_flow(df, percent=True)\n df['BranchID'] = df['BranchID'].map(Utils.branch_id2city)\n return df\n\n @staticmethod\n def _to_time(columns, df_c):\n df = df_c.copy()\n for column in columns:\n if column in df.columns:\n df[column] = pd.to_datetime(df[column], format='%Y-%m-%d')\n return df\n\n @staticmethod\n def _to_numeric(df_c):\n df = df_c.copy()\n\n # for column in df.columns:\n # if df[column].dtype == object and np.issubdtype(pd.to_numeric(df[column], errors='ignore').dtype, np.number):\n # print(column)\n\n columns = ['sa_24 Указан телефон',\n 'sa_25 Указан скайп',\n 'sa_26 Указан твиттер',\n 'sa_41 Разр. видеть чужие записи',\n 'sa_42 Разр. оставлять записи']\n for column in [x for x in columns if x in params.input_columns]:\n df[column] = pd.to_numeric(df[column])\n return df\n\n @staticmethod\n def eval_stavka_plus(*dfs):\n def eval_stavka_plus(df_c):\n df = df_c.copy()\n new_time = pd.Timestamp('2019-02-22')\n df['Ставка займа плюс'] = df['Ставка займа'] * (df['Дата открытия по договору'] < new_time) + np.invert(df['Дата открытия по договору'] < new_time)*(\n 0.0099 * df['BranchID'].isin([12, 37, 69]) + np.invert(df['BranchID'].isin([12, 37, 69])) * (\n 0.0125 * (df['JobGroupID'] == 13) + np.invert(df['JobGroupID'] == 13) * (\n 0.019\n )\n )\n )\n df['Ставка займа плюс'] = df['Ставка займа плюс'].round(4)\n return df\n return [eval_stavka_plus(df) if df is not None else None for df in dfs]\n","sub_path":"extractors/casters/Casters.py","file_name":"Casters.py","file_ext":"py","file_size_in_byte":4092,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"288791049","text":"#!/usr/bin/env python3\n\nfrom PIL import Image, ImageDraw, ImageFont, ImageColor\nimport math\nimport random\n\nCOLORS = {'A': 'red',\n 'T': '#FAA619', #'yellow',\n 'G': '#94BA33', #'green',\n 'C': '#01BADE', #'blue',\n '0': 'black',\n '1': 'gray'\n }\n\ndef main():\n width, height = 1024, 1024\n dx, dy = 64, 64\n maxx, maxy = math.floor(width/dx), math.floor(height/dy)\n fontname = \"SourceSansPro-Regular.otf\"\n fontsize = 62\n font = ImageFont.truetype(fontname, fontsize)\n img = Image.new('RGBA', (width, height))\n d = ImageDraw.Draw(img)\n \n char_set = 'ATGC10'\n\n for j in range(0, maxy):\n y = j * dy\n for i in range(0, maxx):\n x = i * dx\n char = random.choice(char_set)\n color = COLORS[char]\n w,h = font.getsize(char)\n xoffset = (dx-w)/2\n d.text((x+xoffset, y), char, fill=color, font=font)\n img.save(\"texture.png\")\n\n\nif __name__ == '__main__':\n main()\n\n \n","sub_path":"texmap.py","file_name":"texmap.py","file_ext":"py","file_size_in_byte":1020,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"452324659","text":"####################################################\n# Modified by Muhammad Ni'am #\n# Original code: http://thecodacus.com/ #\n####################################################\n\n# Import OpenCV2 for image processing | import opencv untuk memproses gambar\n# Import os for file path | Import os untuk jalur file\nimport cv2\n\n# Import numpy for matrix calculation | Impor numpy untuk perhitungan matriks\nimport numpy as np\n\n# Import Python Image Library (PIL) | Import pustaka gambar python\nfrom PIL import Image\n\nimport os\n\n\n# Membuat fungsi / method untuk membuat directory baru\ndef assure_path_exists(path):\n dir = os.path.dirname(path)\n if not os.path.exists(dir):\n os.makedirs(dir)\n\n\n# Create Local Binary Patterns Histograms for face recognization\n# Buat Histogram pola biner lokal untuk pengenalan wajah\nrecognizer = cv2.face.LBPHFaceRecognizer_create()\n\n# Using prebuilt frontal face training model, for face detection\n# Menggunakan model pelatihan wajah frontal prebuilt, untuk deteksi wajah\ndetector = cv2.CascadeClassifier(\"face-detect.xml\");\n\n\n# Create method to get the images and label data | buat metede untuk mendapatkan gambar dan label data\ndef getImagesAndLabels():\n path = (\"/home/pi/pengenal/dataset\")\n # Get all file path | dapatkan semua jalur file\n imagePaths = [os.path.join(path, f) for f in os.listdir(path)]\n\n # Initialize empty face sample | inisialisasi sampel wajah kosong\n faceSamples = []\n\n # Initialize empty id | inisialisasi id kosong\n ids = []\n\n # Loop all the file path | perulangan semua jalur file\n for imagePath in imagePaths:\n\n # Get the image and convert it to grayscale | dapatkan gambar dan ubah menjadi skala abu-abu\n PIL_img = Image.open(imagePath).convert('L')\n\n # PIL image to numpy array | gambar PIL ke array numpy\n img_numpy = np.array(PIL_img, 'uint8')\n\n # Get the image id | dapatkan ID gambar\n id = int(os.path.split(imagePath)[-1].split(\".\")[1])\n\n # Get the face from the training images | dapatkan wajad dari gambar training\n faces = detector.detectMultiScale(img_numpy)\n\n # Loop for each face, append to their respective ID | loop setiap wajah, tambahkan id masing-masing\n for (x, y, w, h) in faces:\n # Add the image to face samples | tambahkan gambar ke sampel wajah\n faceSamples.append(img_numpy[y:y + h, x:x + w])\n\n # Add the ID to IDs | tambahkan ID ke ID\n ids.append(id)\n\n # Pass the face array and IDs array | lulus array wajah dan array ID\n return faceSamples, ids\n\n\n#dapatkan wajah dan ID\n# faces, ids = getImagesAndLabels('dataset')\nfaces, ids = getImagesAndLabels()\n\n#latih model menggunakan wajah dan ID\nrecognizer.train(faces, np.array(ids))\n\n#simpan medel ke dalam trainer.yml\nassure_path_exists('trainer/')\nrecognizer.save('trainer/trainer.yml')\n","sub_path":"training.py","file_name":"training.py","file_ext":"py","file_size_in_byte":2909,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"187491386","text":"#\n# Copyright 2016 Quantopian, 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 numpy as np\nimport pandas as pd\nimport zipline.finance.risk as risk\nfrom zipline.utils import factory\n\nfrom zipline.testing.fixtures import WithTradingEnvironment, ZiplineTestCase\n\nfrom zipline.finance.trading import SimulationParameters\nfrom . import answer_key\nANSWER_KEY = answer_key.ANSWER_KEY\n\n\nclass TestRisk(WithTradingEnvironment, ZiplineTestCase):\n\n def init_instance_fixtures(self):\n super(TestRisk, self).init_instance_fixtures()\n\n start_session = pd.Timestamp(\"2006-01-01\", tz='UTC')\n end_session = pd.Timestamp(\"2006-12-29\", tz='UTC')\n\n self.sim_params = SimulationParameters(\n start_session=start_session,\n end_session=end_session,\n trading_calendar=self.trading_calendar,\n )\n\n self.algo_returns_06 = factory.create_returns_from_list(\n answer_key.ALGORITHM_RETURNS.values,\n self.sim_params\n )\n\n self.cumulative_metrics_06 = risk.RiskMetricsCumulative(\n self.sim_params,\n treasury_curves=self.env.treasury_curves,\n trading_calendar=self.trading_calendar,\n )\n\n for dt, returns in answer_key.RETURNS_DATA.iterrows():\n self.cumulative_metrics_06.update(dt,\n returns['Algorithm Returns'],\n returns['Benchmark Returns'],\n 0.0)\n\n def test_algorithm_volatility_06(self):\n algo_vol_answers = answer_key.RISK_CUMULATIVE.volatility\n for dt, value in algo_vol_answers.iteritems():\n dt_loc = self.cumulative_metrics_06.cont_index.get_loc(dt)\n np.testing.assert_almost_equal(\n self.cumulative_metrics_06.algorithm_volatility[dt_loc],\n value,\n err_msg=\"Mismatch at %s\" % (dt,))\n\n def test_sharpe_06(self):\n for dt, value in answer_key.RISK_CUMULATIVE.sharpe.iteritems():\n dt_loc = self.cumulative_metrics_06.cont_index.get_loc(dt)\n np.testing.assert_almost_equal(\n self.cumulative_metrics_06.sharpe[dt_loc],\n value,\n err_msg=\"Mismatch at %s\" % (dt,))\n\n def test_downside_risk_06(self):\n for dt, value in answer_key.RISK_CUMULATIVE.downside_risk.iteritems():\n dt_loc = self.cumulative_metrics_06.cont_index.get_loc(dt)\n np.testing.assert_almost_equal(\n value,\n self.cumulative_metrics_06.downside_risk[dt_loc],\n err_msg=\"Mismatch at %s\" % (dt,))\n\n def test_sortino_06(self):\n for dt, value in answer_key.RISK_CUMULATIVE.sortino.iteritems():\n dt_loc = self.cumulative_metrics_06.cont_index.get_loc(dt)\n np.testing.assert_almost_equal(\n self.cumulative_metrics_06.sortino[dt_loc],\n value,\n decimal=4,\n err_msg=\"Mismatch at %s\" % (dt,))\n\n def test_information_06(self):\n for dt, value in answer_key.RISK_CUMULATIVE.information.iteritems():\n dt_loc = self.cumulative_metrics_06.cont_index.get_loc(dt)\n np.testing.assert_almost_equal(\n value,\n self.cumulative_metrics_06.information[dt_loc],\n err_msg=\"Mismatch at %s\" % (dt,))\n\n def test_alpha_06(self):\n for dt, value in answer_key.RISK_CUMULATIVE.alpha.iteritems():\n dt_loc = self.cumulative_metrics_06.cont_index.get_loc(dt)\n np.testing.assert_almost_equal(\n self.cumulative_metrics_06.alpha[dt_loc],\n value,\n err_msg=\"Mismatch at %s\" % (dt,))\n\n def test_beta_06(self):\n for dt, value in answer_key.RISK_CUMULATIVE.beta.iteritems():\n dt_loc = self.cumulative_metrics_06.cont_index.get_loc(dt)\n np.testing.assert_almost_equal(\n value,\n self.cumulative_metrics_06.beta[dt_loc],\n err_msg=\"Mismatch at %s\" % (dt,))\n\n def test_max_drawdown_06(self):\n for dt, value in answer_key.RISK_CUMULATIVE.max_drawdown.iteritems():\n dt_loc = self.cumulative_metrics_06.cont_index.get_loc(dt)\n np.testing.assert_almost_equal(\n self.cumulative_metrics_06.max_drawdowns[dt_loc],\n value,\n err_msg=\"Mismatch at %s\" % (dt,))\n","sub_path":"tests/risk/test_risk_cumulative.py","file_name":"test_risk_cumulative.py","file_ext":"py","file_size_in_byte":4984,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"520136502","text":"# coding: utf-8\n\nfrom concurrent.futures import ThreadPoolExecutor\n\n# 线程池\n# 主线程中可以获取某一个线程的状态或者某一个任务的状态,以及返回值\n# 当一个线程完成的时候我们主线程能立即知道\n# futures可以让多线程和多进程编码接口一致\n\nimport time\n\ndef get_html(times):\n time.sleep(times)\n print(\"get page {} success\".format(times))\n\nexecutor = ThreadPoolExecutor(max_workers=2)\n# 通过sumbit函数提交执行的函数到线程池中\ntask1 = executor.submit(get_html, (3))\ntask2 = executor.submit(get_html, (2))\n\n# done 方法用户判断某个任务是否完成\nprint(task1.done())\n# print(task2.cancel()) # 可以取消未进入线程池的线程\ntime.sleep(5)\nprint(task1.done())\n\n# result方法可以获取task的执行结果\nprint(task1.result())\n\n\nif __name__ == '__main__':\n print(11111)","sub_path":"chapter11/concurrent_futures.py","file_name":"concurrent_futures.py","file_ext":"py","file_size_in_byte":870,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"80338952","text":"__author__ = 'blah900'\nIMAGE_RATIO = 0.75\nTILE_BUFFER = 1.2\n\n\nclass Graphics():\n BASE_WIDTH = 64\n BASE_HEIGHT = 64\n SCREEN_WIDTH = 1024\n SCREEN_HEIGHT = 768\n CENTER_X = SCREEN_WIDTH / 2\n CENTER_Y = SCREEN_HEIGHT / 2\n @staticmethod\n def get_surface_size():\n return (Graphics.BASE_WIDTH * TILE_BUFFER, Graphics.BASE_HEIGHT * TILE_BUFFER)\n\n @staticmethod\n def get_image_size():\n return (int(Graphics.BASE_WIDTH * IMAGE_RATIO), int(Graphics.BASE_HEIGHT * IMAGE_RATIO))\n\n @staticmethod\n def set_tile_size(width, height):\n Graphics.BASE_WIDTH = width\n Graphics.BASE_HEIGHT = height * IMAGE_RATIO\n Graphics.IMAGE_WIDTH = width * IMAGE_RATIO\n\n @staticmethod\n def set_screen_size(width, height):\n Graphics.SCREEN_WIDTH = width\n Graphics.SCREEN_HEIGHT = height\n Graphics.CENTER_X = width/2\n Graphics.CENTER_Y = height/2\n\n TILE_EDGE_SIZE = 1","sub_path":"graphics/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":938,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"357167138","text":"#um programa que leia dois numeros e fale qual e o maior ou se são iguais\nn1 = int(input('Primeiro numero : '))\nn2 = int(input('Segundo numero : '))\nif n1>n2:\n print('O primeiro numero é maior')\nelif n1 str:\n factorials = [1]*n\n for i in range(1,len(factorials)): factorials[i] = (i+1)*factorials[i-1]\n \n ans = ''\n digits = [str(i) for i in range(1, n+1)]\n k -= 1\n \n for i in range(n-1):\n group = k//factorials[-1*i-2]\n ans += digits[group]\n del digits[group]\n k = k%factorials[-1*i-2]\n \n return ans+digits[0]\n","sub_path":"0060 Permutation Sequence.py","file_name":"0060 Permutation Sequence.py","file_ext":"py","file_size_in_byte":489,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"40805409","text":"class Solution:\n from typing import List\n\n def twoSumV1(self, nums: List[int], target: int) -> List[int]:\n n = len(nums)\n for i in range(n):\n for j in range(i + 1, n):\n if nums[i] + nums[j] == target:\n return [i, j]\n\n def twoSumV2(self, nums: List[int], target: int) -> List[int]:\n val_id_map = dict()\n for i, num in enumerate(nums):\n if num in val_id_map:\n return [val_id_map[num], i]\n else:\n val_id_map[target - num] = i\n\n\ns = Solution()\nassert(s.twoSumV2([2, 7, 11, 15], 9) == [0, 1])\nassert(s.twoSumV2([3, 2, 4], 6) == [1, 2])\nassert(s.twoSumV2([3, 3], 6) == [0, 1])\n","sub_path":"0000-0099/0001/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":705,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"401436677","text":"import cv2\nimport numpy as np\n\n# loading image\nimage = cv2.imread(\"example.jpg\")\n# gradient conversion\ngray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n# blur\ngray = cv2.GaussianBlur(gray, (3, 3), 0)\ncv2.imwrite(\"gray.jpg\", gray)\n\n# contour recognition\nedged = cv2.Canny(gray, 10, 250)\ncv2.imwrite(\"edged.jpg\", edged)\n\n# closing\nkernel = cv2.getStructuringElement(cv2.MORPH_RECT, (7, 7))\nclosed = cv2.morphologyEx(edged, cv2.MORPH_CLOSE, kernel)\ncv2.imwrite(\"closed.jpg\", closed)\n\n# search and counting contours\ncnts = cv2.findContours(closed.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[1]\ntotal = 0\n\nimageLines = image\n\n# cycle by contours\nfor c in cnts:\n print(\"Current area = \", cv2.contourArea(c))\n if cv2.contourArea(c) < 3000:\n continue\n else:\n pass\n print(\"Centers fond \\n\")\n total += 1\n # contour approximation\n peri = cv2.arcLength(c, True)\n approx = cv2.approxPolyDP(c, 0.02 * peri, True)\n cv2.drawContours(image, [approx], -1, (0, 255, 0), 4)\n\n rect = cv2.minAreaRect(c)\n box = cv2.boxPoints(rect)\n box = np.int0(box)\n print(box, \"\\n\")\n\n rows, cols = imageLines.shape[:2]\n [vx, vy, x, y] = cv2.fitLine(c, cv2.DIST_L2, 0, 0.01, 0.01)\n lefty = int((-x * vy / vx) + y)\n righty = int(((cols - x) * vy / vx) + y)\n cv2.line(imageLines, (cols - 1, righty), (0, lefty), (0, 0, 255), 2)\n cv2.circle(imageLines, (x, y), 4, (0,0,255), thickness=-1)\n print(\"Obj #\", total, \"->\", x, y, \"\\n\")\n#\ncv2.imwrite(\"output.jpg\", image)","sub_path":"img_process.py","file_name":"img_process.py","file_ext":"py","file_size_in_byte":1504,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"513935666","text":"import numpy as np\nfrom . import parameters\nfrom .flow_rate import flow_rate\nfrom kinetics.monod_inhibition import monod \nfrom kinetics.monod_inhibition import inhibition_function\n\n\ndef mass_balance(c, t):\n \n # Stoichiometric matrix\n s = np.zeros((1, 2))\n s[0, 0] = -1\n s[0, 1] = parameters.y_x_s\n \n # Calculate rates\n mu = monod(parameters, c[0]) \n inhibition = inhibition_function(parameters, c[0])\n \n # Calculate feed_flow_rate\n feed_flow_rate = flow_rate(parameters, c[2], t)\n \n # Differential equations\n dx1dt = mu * s[0, 0] * c[1] * inhibition + feed_flow_rate * \\\n parameters.glucose_feed / c[2] # Glucose\n dx2dt = mu * s[0, 1] * c[1] * inhibition # Biomass\n dx3dt = feed_flow_rate\n \n dzdt = [dx1dt, dx2dt, dx3dt]\n return dzdt\n \n \n ","sub_path":"fed_batch_1/mass_balance.py","file_name":"mass_balance.py","file_ext":"py","file_size_in_byte":820,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"} +{"seq_id":"424816418","text":"import numpy as np\nimport time\n\nstart_time = time.time()\nfor i in range(1000):\n matrix_a = np.random.rand(100, 1000)\n matrix_b = np.random.rand(1000, 100)\n\n result = matrix_a.dot(matrix_b)\n\nend_time = time.time()\ntotal_time = end_time - start_time\n\nprint('Total Time:\\t' + repr(total_time) + ' s')\n","sub_path":"python_speed_test.py","file_name":"python_speed_test.py","file_ext":"py","file_size_in_byte":307,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"92"}