diff --git "a/731.jsonl" "b/731.jsonl" new file mode 100644--- /dev/null +++ "b/731.jsonl" @@ -0,0 +1,689 @@ +{"seq_id":"454460914","text":"from sarra import Session, Scenario, Hall\nfrom collections import OrderedDict\nimport re, random\n\n\nhowareyou = Scenario({\n 'match': '__all__',\n 'child': [\n {\n 'match': ['хорошо', 'нормально', 'гуд'],\n 'answer': 'Это же здорово!',\n },\n {\n 'match': ['плохо', 'ужасно', 'так себе'],\n 'answer': 'О, а что случилось?',\n 'child': [\n {\n 'match': ['не скажу', 'личное', 'не важно'],\n 'answer': 'Ну секрет так секрет :)'\n },\n {\n 'match': '__default__',\n 'answer': 'О, мне жаль :(',\n },\n ],\n },\n ],\n})\n\n\nif __name__ == '__main__':\n hall = Hall([howareyou])\n session = Session('me', hall)\n print('Bot: Как дела твои?')\n\n message = 'Плохо'\n print('Me: ' + message)\n\n answer = session.say(message)\n print('Bot: ' + answer)\n\n message = random.choice(['Умер котик', 'Да так, личное'])\n print('Me: ' + message)\n\n answer = session.say(message)\n print('Bot: ' + answer)\n\n\n\n","sub_path":"example/example.py","file_name":"example.py","file_ext":"py","file_size_in_byte":1269,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"19361470","text":"# coding:utf-8\n\nimport requests\nfrom PIL import Image\nfrom PIL import ImageEnhance\nimport pytesseract\n\n\ndef load_cookie(_username_):\n path = 'ecard-' + _username_ + '.cookie'\n try:\n with open(path, 'r') as f:\n return f.read().strip()\n except:\n return ''\n\n\ndef save_cookie(_username_, _cookie_):\n path = 'ecard-' + _username_ + '.cookie'\n try:\n with open(path, 'w') as f:\n f.write(_cookie_)\n except:\n pass\n\n\ndef test_authorized_cookie(_cookie_):\n req = requests.get(\n url='http://ecard.jxust.edu.cn/epay/',\n headers={\n 'Cookie': 'JSESSIONID=' + _cookie_}\n )\n return True if req.text.find('''/epay/index/welcome.jsp''') >= 0 else False\n\n\ndef generate_login_cookie(_username_, _password_):\n cookie = load_cookie(_username_)\n if test_authorized_cookie(cookie):\n return cookie\n req = requests.get('http://ecard.jxust.edu.cn/epay/person/index')\n cookies = dict(req.cookies)\n login_success = False\n try_time = 0\n while not login_success:\n img_req = requests.get(\n url='http://ecard.jxust.edu.cn/epay/codeimage',\n cookies=cookies\n )\n open('f.jpg', 'wb').write(img_req.content)\n im = Image.open('f.jpg')\n im = im.convert('L')\n im = ImageEnhance.Contrast(im)\n im = im.enhance(20)\n captcha_code = pytesseract.image_to_string(im)\n captcha_code = captcha_code.strip()\n captcha_code = captcha_code.replace(' ', '')\n try_time += 1\n login_req = requests.post(\n url='http://ecard.jxust.edu.cn/epay/j_spring_security_check',\n data={\n 'j_username': _username_,\n 'j_password': _password_,\n 'imageCodeName': captcha_code\n },\n headers={\n 'Cookie': 'JSESSIONID=' + cookies['JSESSIONID']\n },\n allow_redirects=False\n )\n if login_req.headers['Location'].find('epay/') >= 0:\n login_success = True\n cookies = dict(login_req.cookies)\n save_cookie(_username_, cookies['JSESSIONID'])\n return cookies['JSESSIONID']","sub_path":"ecard_login.py","file_name":"ecard_login.py","file_ext":"py","file_size_in_byte":2186,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"372208621","text":"from PyQt5.QtGui import QPixmap\n\nfrom PyQt5.QtWidgets import QLabel\nfrom Constants import *\n\n\nclass Bullet(QLabel):\n def __init__(self, offset_x, offset_y, parent, enemy=False):\n QLabel.__init__(self, parent)\n if enemy:\n self.setPixmap(QPixmap(\"images/bullet/enemy_bullet.png\"))\n else:\n self.setPixmap(QPixmap(\"images/bullet/bullet.png\"))\n self.offset_x = offset_x\n self.offset_y = offset_y\n self.active = False\n self.setGeometry(SCREEN_WIDTH, SCREEN_HEIGHT, self.pixmap().width(), self.pixmap().height())\n # self.setStyleSheet(\"border: 1px solid white;\")\n self.show()\n\n def player_game_update(self) -> bool:\n self.setGeometry(self.x(), self.y() - BULLET_SPEED, self.pixmap().width(), self.pixmap().height())\n if self.y() + self.pixmap().height() <= 0:\n self.active = False\n self.close()\n return True\n return False\n\n def enemy_game_update(self, enemy) -> bool:\n try:\n if not self.active:\n\n x = enemy.x() + enemy.width() / 2 - self.width() / 2\n y = enemy.y() + enemy.height()\n self.setGeometry(x, y, self.pixmap().width(), self.pixmap().height())\n self.active = True\n else:\n self.setGeometry(self.x(), self.y() + BULLET_SPEED, self.pixmap().width(), self.pixmap().height())\n\n if self.y() >= SCREEN_HEIGHT:\n self.hit()\n return True\n return False\n except AttributeError:\n return True\n\n def hit(self) -> None:\n self.active = False\n self.setGeometry(SCREEN_WIDTH, SCREEN_HEIGHT, self.pixmap().width(), self.pixmap().height())\n","sub_path":"Bullet/Bullets.py","file_name":"Bullets.py","file_ext":"py","file_size_in_byte":1776,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"499389116","text":"import re, traceback, keyword\n\ndef pnamedtuple(type_name, field_names, mutable=False):\n def show_listing(s):\n for i, l in enumerate(s.split('\\n'),1):\n print('{num: >3} {txt}'.format(num = i, txt = l.rstrip()))\n \n legal_type = r\"^[a-zA-Z]([a-zA-Z0-9_])*$\"\n match_type = re.match(legal_type, str(type_name))\n \n legal_field = r\"^(\\['[a-zA-Z]([a-zA-Z0-9_])*'(,'[a-zA-Z](\\w)*')*)|(([a-zA-Z]([a-zA-Z0-9_])*)(((\\s+)(\\w)*)*))|(([a-zA-Z]([a-zA-Z0-9_])*)((,(\\s+)[a-zA-Z]([a-zA-Z0-9_])*)*))$\"\n match_field = re.match(legal_field, str(field_names))\n \n #case 1: type or field name does not match pattern\n if match_type == None or match_field == None:\n raise SyntaxError\n \n #case 2: name contains keyword from kwlist\n all_names = []\n newlist = re.split(',|\\s', field_names)\n for name in newlist:\n all_names.append(name)\n num_of_empties = all_names.count('') #gets rid of ''\n for i in range(num_of_empties):\n all_names.remove('')\n for n in all_names:\n if n in keyword.kwlist:\n raise SyntaxError\n if re.match(legal_type, n) == None:\n raise SyntaxError\n print(all_names)\n #__init__\n '''\n def __init__(self, x, y):\n self.x = x\n self.y = y\n self._fields = ['x','y']\n self._mutable = False\n '''\n class_definition = 'class {x}: \\n\\tdef __init__(self,'.format(x=type_name)\n \n \n # put your code here\n # bind class_definition (used below) to the string constructed for the class\n\n\n\n # For initial debugging, always show the source code of the class\n #show_listing(class_definition)\n \n # Execute the class_definition string in a local namespace and bind the\n # name source_code in its dictionary to the class_defintion; return the\n # class object created; if there is a syntax error, list the class and\n # show the error\n name_space = dict(__name__='pnamedtuple_{type_name}'.format(type_name=type_name))\n try:\n exec(class_definition, name_space)\n name_space[type_name].source_code = class_definition\n except(SyntaxError, TypeError):\n show_listing(class_definition)\n traceback.print_exc()\n return name_space[type_name]\n\n\n \nif __name__ == '__main__':\n import driver\n driver.driver()\n","sub_path":"ICS33/program3/pcollections.py","file_name":"pcollections.py","file_ext":"py","file_size_in_byte":2326,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"45632114","text":"import ROOT\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib\nimport seaborn as sns\nfrom scipy import ndimage\nfrom sklearn.preprocessing import Normalizer\nimport time\nimport progressbar\nimport sys\nimport matplotlib.cm as cm\nfrom PIL import Image\nimport pandas as pd\nimport glob2\nimport os\nimport math\nimport scipy\n\n\nROOT.gSystem.Load(\"MG5/Delphes/libDelphes.so\")\n#store = pd.HDFStore('signal.h5')\n\ndef rotate(x, y, a):\n\txp = x*np.cos(a) - y*np.sin(a)\n\typ = x*np.sin(a) + y*np.cos(a)\n\treturn xp, yp\n\nfiles = glob2.glob('data/signal_data/*.root', recursive=True)\npixels = 25\nxwidth = 10\nywidth = 10\nmean_img = np.zeros((pixels,pixels))\n\nfor directory in files:\n\tdata_name = os.path.basename(directory).split('.root')[0]\n\tFile = ROOT.TChain(\"Delphes;1\")\n\tFile.Add(directory)\n\tNumber = File.GetEntries()\n\n\tfor i in progressbar.progressbar(range(Number)):\n\t\t#print \"-_-_-_- Event %0.f -_-_-_-\" %i\n\t\tEntry = File.GetEntry(i)\n\t\tTowerBranch = File.Tower.GetEntries()\n\t\tParticleBranch = File.Particle.GetEntries()\n\t\tET, eta, phi = [], [], []\n\t\tfor j in range(TowerBranch):\n\t\t\tET.append(File.GetLeaf(\"Tower.ET\").GetValue(j))\n\t\t\teta.append(File.GetLeaf(\"Tower.Eta\").GetValue(j))\n\t\t\tphi.append(File.GetLeaf(\"Tower.Phi\").GetValue(j))\n\t\tdf = pd.DataFrame({'ET':ET, 'eta':eta, 'phi':phi})\n\t\tnlarge = df['ET'].nlargest(2, keep='first')\n\t\tE_max = df.loc[df['ET'] == nlarge.iloc[0]]\n\t\tdf['eta'] -= E_max['eta'].values\n\t\tdf['phi'] -= E_max['phi'].values\n\t\tE2 = df.loc[df['ET'] == nlarge.iloc[1]]\n\t\tE2x, E2y = E2['eta'].values, E2['phi'].values\n\t\tx,y,z = df['eta'], df['phi'], df['ET']\n\t\ttheta = math.atan2(E2y, E2x)\n\t\tif (theta < 0.0):\n\t\t\ttheta += 2*np.pi\n\t\tx,y = rotate(x,y,-theta)\n\n\t\tdigitized = scipy.stats.binned_statistic_2d(x,y,z,statistic='sum', bins=pixels, range=[[-xwidth,xwidth],[-ywidth,ywidth]])\n\t\timg, xedges, yedges = digitized[0], digitized[1], digitized[2]\n\t\tmean_img = mean_img + img\n\t\tif i > 2000:\n\t\t\tbreak\n\n\textent = [xedges[0], xedges[-1], yedges[0], yedges[-1]]\n\tplt.imshow((mean_img/np.sum(mean_img)), extent=extent, norm=matplotlib.colors.LogNorm())#)\n\tplt.margins(0,0)\n\tcbar = plt.colorbar()\n\tcbar.set_label('ET in ECal Tower')\n\tplt.xlabel('$\\\\eta$')\n\tplt.ylabel('$\\\\phi$')\n\tplt.savefig('plots/jet_ET.pdf')\n\tplt.clf()\n","sub_path":"delph2fastjet.py","file_name":"delph2fastjet.py","file_ext":"py","file_size_in_byte":2243,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"116805851","text":"\"\"\"\nImplement functionality to reverse an input string. Print out the reversed string.\nFor example, given a string \"cool\", print out the string \"looc\".\nYou may use whatever programming language you'd like.\nVerbalize your thought process as much as possible before writing any code. Run through the UPER problem solving \nframework while going through your thought process. (edited) \n\"\"\"\n\ndef rev_string():\n\n input_string = input(\"Please Enter A String: \")\n\n x = [s.lower() for s in input_string]\n\n x = x[::-1]\n\n s = \"\"\n x = s.join(x)\n\n return x\n\nif __name__ == \"__main__\":\n\n # my_string = \"Aaron\"\n\n print(rev_string())","sub_path":"whiteboard/whiteboard.py","file_name":"whiteboard.py","file_ext":"py","file_size_in_byte":641,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"140247077","text":"# Compare Algorithms\nimport pandas\nimport seaborn as sns\nfrom sklearn import model_selection\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.discriminant_analysis import LinearDiscriminantAnalysis\nfrom sklearn.naive_bayes import GaussianNB\nfrom sklearn.svm import SVC\nfrom sklearn.ensemble import GradientBoostingClassifier\nfrom sklearn.neural_network import MLPClassifier\n#import xgboost as xgb\n\n\n# load dataset\nurl = \"https://archive.ics.uci.edu/ml/machine-learning-databases/pima-indians-diabetes/pima-indians-diabetes.data\"\nnames = [\"preg\", \"plas\", \"pres\", \"skin\", \"test\", \"mass\", \"pedi\", \"age\", \"class\"]\ndataframe = pandas.read_csv(url, names=names)\narray = dataframe.values\nX = array[:,0:8]\nY = array[:,8]\n# prepare configuration for cross validation test harness\nseed = 7\n# prepare models\nmodels = []\nmodels.append((\"LR\", LogisticRegression()))\nmodels.append((\"LDA\", LinearDiscriminantAnalysis()))\nmodels.append((\"KNN\", KNeighborsClassifier()))\nmodels.append((\"CART\", DecisionTreeClassifier()))\nmodels.append((\"RF\", RandomForestClassifier(random_state=7, n_estimators=300)))\nmodels.append((\"NB\", GaussianNB()))\nmodels.append((\"SVM\", SVC()))\nmodels.append((\"GBM\", GradientBoostingClassifier(random_state=7, n_estimators=300)))\nmodels.append((\"NN\", MLPClassifier(solver='lbfgs', alpha=1e-5, hidden_layer_sizes=(5, 2), random_state=7)))\n#models.append(\"XGB\", xgb.XGBModel())\n# evaluate each model in turn\nresults = []\nnames = []\nscoring = \"accuracy\"\nfor name, model in models:\n kfold = model_selection.KFold(n_splits=10, random_state=seed)\n cv_results = model_selection.cross_val_score(model, X, Y, cv=kfold, scoring=scoring)\n results.append(cv_results)\n names.append(name)\n msg = \"%s: %f (%f)\" % (name, cv_results.mean(), cv_results.std())\n print(msg)\n# boxplot algorithm comparison\nfig = sns.plt.figure()\nfig.suptitle(\"Algorithm Comparison\")\nax = fig.add_subplot(111)\nsns.plt.boxplot(results)\nax.set_xticklabels(names)\nsns.plt.show()","sub_path":"algo_comparison.py","file_name":"algo_comparison.py","file_ext":"py","file_size_in_byte":2125,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"41961256","text":"from configparser import SafeConfigParser as ConfigParser\nimport typing\n\nclass Config():\n def __init__(self):\n config = ConfigParser()\n config.read('config.ini')\n\n self.donor_roles: typing.List[int] = [353630811561394206, 353226278435946496]\n\n self.dbl_token: str = config.get('DEFAULT', 'dbl_token')\n self.token: str = config.get('DEFAULT', 'token')\n\n self.patreon: bool = config.get('DEFAULT', 'patreon_enabled') == 'yes'\n self.patreon_server: int = int(config.get('DEFAULT', 'patreon_server'))\n","sub_path":"config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":549,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"341534109","text":"# Copyright (C) 2013 Kevin Duffy.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\nimport re\nimport md5\nimport subprocess\n\nclass Wishlist(object):\n item_id_regex = re.compile(r\"/dp/(.*)\\?.*'>\")\n item_id_link_normal_regex = re.compile(r\"a-link-normal.*/dp/(.*)\\?.*['\\\"]>\")\n page_num_regex = re.compile(r'\"ajaxPagination\":(\\d+),')\n MAX_PAGES = 100\n\n @staticmethod\n def create_table(c):\n c.execute('''CREATE TABLE IF NOT EXISTS wishlists\n (id INT NOT NULL PRIMARY KEY,\n name TEXT NOT NULL,\n url TEXT NOT NULL)''')\n\n @classmethod\n def from_id(cls, wishlist_id, c):\n c.execute('''SELECT * FROM wishlists WHERE id=?''', (wishlist_id,))\n row = c.fetchone()\n wishlist_id = row[0]\n name = row[1]\n url = row[2]\n return cls(name, wishlist_id, url)\n\n @classmethod\n def from_url(cls, name, url):\n digest = md5.md5(url).hexdigest()[-10:]\n wishlist_id = int(digest, 16)\n o = cls(name, wishlist_id, url)\n return o\n\n def __init__(self, name, wishlist_id, url):\n self.name = name\n self.wishlist_id = wishlist_id\n self.url = url\n\n def get_item_ids(self):\n if not hasattr(self, '_item_ids'):\n last_page = None\n current_page = 1\n item_ids = set()\n while current_page < self.MAX_PAGES and (last_page is None or current_page <= last_page):\n url = '%s?layout=compact&reveal=unpurchased&filter=all&sort=date-added&page=%d' % (self.url, current_page)\n cmd = ['curl', '-L', '-s', url]\n output = subprocess.check_output(cmd)\n for line in output.splitlines():\n m = self.item_id_regex.search(line)\n if not m and '/dp/' in line:\n m = self.item_id_link_normal_regex.search(line)\n\n if m:\n item_id = m.groups(1)[0]\n item_ids.add(item_id)\n\n # if not set yet, get the last page number to support multiple page wishlists\n if last_page is None:\n m = self.page_num_regex.search(line)\n if m:\n last_page = int(m.groups(1)[0]) - 1\n current_page += 1\n\n self._item_ids = item_ids\n return self._item_ids\n\n def insert_into_table(self, c):\n c.execute('''INSERT OR IGNORE INTO wishlists VALUES (?, ?, ?)''', (self.wishlist_id, self.name, self.url))\n","sub_path":"wishlist.py","file_name":"wishlist.py","file_ext":"py","file_size_in_byte":3087,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"568737467","text":"# Faraday Penetration Test IDE\n# Copyright (C) 2016 Infobyte LLC (http://www.infobytesec.com/)\n# See the file 'doc/LICENSE' for the license information\n\nfrom sqlalchemy.sql import func\nfrom server.dao.base import FaradayDAO\nfrom server.models import Host, Interface, Service\n\n\nclass ServiceDAO(FaradayDAO):\n MAPPED_ENTITY = Service\n COLUMNS_MAP = {\n \"name\": Service.name,\n \"protocol\": Service.protocol,\n \"version\": Service.version,\n \"status\": Service.status,\n \"owned\": Service.owned\n }\n\n def list(self, port=None):\n return self.__get_services_by_host(port)\n\n def __get_services_by_host(self, port=None):\n result = self._session.query(Host.name,\n Host.os,\n Interface.ipv4_address,\n Interface.ipv6_address,\n Service.name,\n Service.ports).join(Host.interfaces, Interface.services).all()\n\n hosts = {}\n for service in result:\n service_ports = map(int, service[5].split(','))\n if port is not None and port not in service_ports:\n continue\n\n host = hosts.get(service[0], None)\n if not host:\n hosts[service[0]] = {\n 'name': service[0],\n 'os': service[1],\n 'ipv4': service[2],\n 'ipv6': service[3],\n 'services': [] }\n host = hosts[service[0]]\n\n host['services'].append({ 'name': service[4], 'ports': service_ports })\n\n return hosts.values()\n\n def count(self, group_by=None):\n total_count = self._session.query(func.count(Service.id)).scalar()\n\n # Return total amount of services if no group-by field was provided\n if group_by is None:\n return { 'total_count': total_count }\n\n # Otherwise return the amount of services grouped by the field specified\n if group_by not in ServiceDAO.COLUMNS_MAP:\n return None\n\n col = ServiceDAO.COLUMNS_MAP.get(group_by)\n query = self._session.query(col, func.count())\\\n .filter(Service.status.in_(('open', 'running')))\\\n .group_by(col)\n\n res = query.all()\n\n return { 'total_count': total_count,\n 'groups': [ { group_by: value, 'count': count } for value, count in res ] }\n\n\n","sub_path":"server/dao/service.py","file_name":"service.py","file_ext":"py","file_size_in_byte":2515,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"361833554","text":"#!/usr/bin/python3\n\nfrom ctypes import *\nimport numpy as np\nimport f90nml\nimport tempfile\nimport os\n\nimport matplotlib.pyplot as plt\nfrom matplotlib import cm\nfrom numpy import linalg as LA\nimport mpl_toolkits.mplot3d.art3d as art3d\nimport matplotlib.ticker as ticker\n\n\nclass TurbineData:\n\n\tdef __init__(self, **kwargs):\n\t\n\t\tparams = kwargs.get('params', np.zeros(30))\t\n\t\tself.turbineNum = params[0]\n\n\t\tself.position = np.zeros(3)\n\t\tself.orientation = np.zeros(3)\n\t\tself.velocity = np.zeros(3)\n\t\t\n\t\tself.position[0] = params[1]\n\t\tself.position[1] = params[2]\n\t\tself.position[2] = params[3]\n\n\t\tself.orientation[0] = params[4]\n\t\tself.orientation[1] = params[5]\n\t\tself.orientation[2] = params[6]\n\t\t\n\t\tself.velocity[0] = params[7]\n\t\tself.velocity[1] = params[8]\n\t\tself.velocity[2] = params[9]\n\t\t\n\t\tself.height = params[10]\n\t\tself.radius = params[11]\n\t\tself.diameter = 2.0 * self.radius\n\t\tself.area = params[12]\n\t\tself.ratedPower = params[13] \n\t\tself.power = params[14] \n\t\tself.fictitious = bool(params[15])\n\t\tself.yaw = True\n\t\tself.cpCurve = np.zeros((10,2))\n\n\t\tself.variables = {'position': self.position, 'V': self.velocity, 'H': self.height, 'R': self.radius, \\\n\t\t'D': self.diameter, 'A': self.area, 'P_r': self.ratedPower, 'P': self.power}\n\n\tdef UpdateDict(self):\n\t\tself.variables = {'position': self.position, 'V': self.velocity, 'H': self.height, 'R': self.radius, \\\n\t\t'D': self.diameter, 'A': self.area, 'P_r': self.ratedPower, 'P': self.power}\n\n\tdef WriteInputFile(self, filename):\n\n\n\t\ttmpFile = tempfile.NamedTemporaryFile(mode = 'w+', delete = True)\n\t\ttry:\n\t\t\ttmpFile.write('&turbine_data \\n /')\n\t\t\ttmpFile.seek(0)\t\t\t\n\t\t\tnamelist = f90nml.read(tmpFile.name)\t\t\t\n\t\tfinally:\n\t\t\ttmpFile.close()\n\t\t\t\t\t\t\n\t\tnamelist['turbine_data']['turbinenum'] = self.turbineNum\n\t\tnamelist['turbine_data']['position'] = self.position.tolist()\n\t\tnamelist['turbine_data']['orientation'] = self.orientation.tolist()\n\t\tnamelist['turbine_data']['yaw'] = self.yaw\n\t\tnamelist['turbine_data']['fictitious'] = self.fictitious\n\t\tnamelist['turbine_data']['height'] = self.height\n\t\tnamelist['turbine_data']['diameter'] = self.radius * 2.0\n\t\tnamelist['turbine_data']['cpcurve'] = self.cpCurve.tolist()\t\t\n\t\tnamelist['turbine_data']['ratedpower'] = self.ratedPower\n\t\t\n\t\tnamelist.write(filename, force=True)\n\t\t\n\t\t\n\tdef SetFromNamelist(self, filename):\n\t\t\n\t\tnamelist = f90nml.read(filename)\t\t\t\n\t\n\t\tif 'turbinenum' in namelist['turbine_data']:\t\t\t\t\t\n\t\t\tself.turbineNum = namelist['turbine_data']['turbinenum']\n\t\t\t\n\t\tif 'position' in namelist['turbine_data']:\t\t\t\n\t\t\tself.position = np.array(namelist['turbine_data']['position'])\n\t\t\t\n\t\tif 'orientation' in namelist['turbine_data']:\t\t\t\n\t\t\tself.orientation = np.array(namelist['turbine_data']['orientation'])\n\t\t\t\n\t\tif 'yaw' in namelist['turbine_data']:\t\t\t\n\t\t\tself.yaw = namelist['turbine_data']['yaw']\n\n\t\tif 'fictitious' in namelist['turbine_data']:\t\t\t\n\t\t\tself.fictitious = namelist['turbine_data']['fictitious']\n\t\t\t\n\t\tif 'height' in namelist['turbine_data']:\t\t\t\n\t\t\tself.height = namelist['turbine_data']['height']\n\t\t\t\n\t\tif 'diameter' in namelist['turbine_data']:\t\t\n\t\t\tself.diameter\t= namelist['turbine_data']['diameter']\n\t\tself.radius = self.diameter / 2.0\n\t\tself.area = np.pi * self.radius * self.radius\n\t\t\n\t\tif 'cpcurve' in namelist['turbine_data']:\t\t\n\t\t\tself.cpCurve = np.array(namelist['turbine_data']['cpcurve'])\n\t\t\n\t\tif 'ratedpower' in namelist['turbine_data']:\n\t\t\tself.ratedPower\t= namelist['turbine_data']['ratedpower']\n\t\t\t\n\t\t\ndef fmt(x, pos):\n\treturn str('{0:.2f}'.format(x))\n\nclass WindFLO:\n\n\tdef __init__(self, **kwargs):\n\t\n\t\tself.runDir = kwargs.get('runDir', '')\t\n\t\n\t\tself.rho = kwargs.get('rho', 1.2)\n\t\tself.turbulenceintensity = kwargs.get('turbulenceIntensity', 0.0)\n\t\tself.windmodel = kwargs.get('windModel', 'constant')\n\t\tself.modelvelocity = kwargs.get('modelVelocity', np.zeros(3))\n\t\tself.surfaceroughness = kwargs.get('surfaceRoughness', 0.0)\n\t\tself.referenceheight = kwargs.get('surfaceRoughness', 1.0)\n\t\tself.wakemodel = kwargs.get('wakeModel', 'Frandsen')\n\t\tself.wakemergemodel = kwargs.get('wakeMergeModel', 'Quadratic')\n\t\tself.wakeexpansioncoeff = kwargs.get('wakeExpansionCoeff', np.zeros(2))\n\t\tself.gaussorder = kwargs.get('gaussOrder', 4)\n\t\tself.montecarlopts = kwargs.get('monteCarloPts', 100)\n\t\tself.coe = kwargs.get('coe', 0.0)\n\t\tself.terrainmodel = kwargs.get('terrainModel', 'RBF')\n\t\tself.poweridw = kwargs.get('powerIDW', 4)\n\t\tself.rbfkernel = kwargs.get('rbfKernel', 1)\n\t\tself.shapefactor = kwargs.get('shapeFactor', 5)\n\t\tself.octreemaxpts = kwargs.get('octreeMaxPts', 100)\n\t\tself.octreedepth = kwargs.get('octreeDepth', 1)\n\t\tself.terrainfile = kwargs.get('terrainFile', '')\n\t\tself.windrosefile = kwargs.get('windRoseFile', '')\n\n\n\t\tself.AEP = 0.0\n\t\tself.farmPower = 0.0\n\t\tself.farmEfficiency = 0.0\n\t\tself.farmCost = 0.0\n\t\tself.landUsed = 0.0\n\t\tself.COE = 0.0\n\t\tself.totalRatedPower = 0.0\n\t\tself.normalizedAEP = 0.0\n\n\n\t\tself.nTurbines = kwargs.get('nTurbines', 0)\n\t\tself.turbines = []\n\t\tfor i in range(0, self.nTurbines):\n\t\t\tself.turbines.append( TurbineData( **kwargs ) )\n\n\n\t\tinputFile = kwargs.get('inputFile', '')\n\t\tif inputFile == '':\n\t\t\ttmpFile = tempfile.NamedTemporaryFile(mode = 'w+', delete = True)\n\t\t\ttry:\n\t\t\t\ttmpFile.write('&windflo_data \\n /')\n\t\t\t\ttmpFile.seek(0)\t\t\t\n\t\t\t\tself.namelist = f90nml.read(tmpFile.name)\t\t\t\n\t\t\tfinally:\n\t\t\t\ttmpFile.close()\n\t\telse:\t\n\t\t\tself.namelist = f90nml.read(inputFile)\n\t\t\tself.SetFromNamelist(**kwargs);\n\n\n\t\tresFile = kwargs.get('resFile', '')\n\t\tif resFile != '':\n\t\t\tself.ReadResultsFile(resFile)\n\t\t\t\n\n\t\tlibPath = kwargs.get('libDir', '')\n\t\tif libPath != '':\n\t\t\tself.libWindFLO = cdll.LoadLibrary('./'+libPath+'libWindFLO.so')\n\n\n\tdef __del__(self):\n\t\n\t\ttry:\n\t\t\tself.libWindFLO.CleanAll_()\n\t\t\tdlclose_func = CDLL(None).dlclose\n\t\t\tdlclose_func.argtypes = [c_void_p]\n\t\t\tdlclose_func.restype = c_int\n\t\t\tdlclose_func(self.libWindFLO._handle)\n\t\texcept:\n\t\t\tpass\n\n\tdef ParseKwargsForAnalysisParams(self, **kwargs):\n\t\n\t\tself.rho = kwargs.get('rho', self.rho)\n\t\tself.turbulenceintensity = kwargs.get('turbulenceIntensity', self.turbulenceintensity)\n\t\tself.windmodel = kwargs.get('windModel', self.windmodel)\n\t\tself.modelvelocity = kwargs.get('modelVelocity', self.modelvelocity)\n\t\tself.surfaceroughness = kwargs.get('surfaceRoughness', self.surfaceroughness)\n\t\tself.referenceheight = kwargs.get('surfaceRoughness', self.referenceheight)\n\t\tself.wakemodel = kwargs.get('wakeModel', self.wakemodel)\n\t\tself.wakemergemodel = kwargs.get('wakeMergeModel', self.wakemergemodel)\n\t\tself.wakeexpansioncoeff = kwargs.get('wakeExpansionCoeff', self.wakeexpansioncoeff)\n\t\tself.gaussorder = kwargs.get('gaussOrder', self.gaussorder)\n\t\tself.montecarlopts = kwargs.get('monteCarloPts', self.montecarlopts)\n\t\tself.coe = kwargs.get('coe', self.coe)\n\t\tself.terrainmodel = kwargs.get('terrainModel', self.terrainmodel)\n\t\tself.poweridw = kwargs.get('powerIDW', self.poweridw)\n\t\tself.rbfkernel = kwargs.get('rbfKernel', self.rbfkernel)\n\t\tself.shapefactor = kwargs.get('shapeFactor', self.shapefactor)\n\t\tself.octreemaxpts = kwargs.get('octreeMaxPts', self.octreemaxpts)\n\t\tself.octreedepth = kwargs.get('octreeDepth', self.octreedepth)\n\t\tself.terrainfile = kwargs.get('terrainFile', self.terrainfile)\n\t\tself.windrosefile = kwargs.get('windRoseFile', self.windrosefile)\n\n\n\tdef SetFromNamelist(self, **kwargs):\n\t\t\n\t\tif 'rho' in self.namelist['windflo_data']:\t\t\n\t\t\tself.rho = self.namelist['windflo_data']['rho']\n\t\t\n\t\tif 'modelvelocity' in self.namelist['windflo_data']:\t\t\n\t\t\tself.modelvelocity = np.array(self.namelist['windflo_data']['modelvelocity'])\n\t\t\t\n\t\tif 'windmodel' in self.namelist['windflo_data']:\t\t\n\t\t\tself.windmodel = self.namelist['windflo_data']['windmodel']\n\t\t\t\t\n\t\tif 'gaussorder' in self.namelist['windflo_data']:\t\t\n\t\t\tself.gaussorder = self.namelist['windflo_data']['gaussorder']\n\t\t\t\t\n\t\tif 'montecarlopts' in self.namelist['windflo_data']:\t\t\n\t\t\tself.montecarlopts = self.namelist['windflo_data']['montecarlopts']\n\t\t\t\t\n\t\tif 'referenceheight' in self.namelist['windflo_data']:\t\t\n\t\t\tself.referenceheight = self.namelist['windflo_data']['referenceheight']\n\t\t\t\t\n\t\tif 'surfaceroughness' in self.namelist['windflo_data']:\t\t\n\t\t\tself.surfaceroughness = self.namelist['windflo_data']['surfaceroughness']\n\t\t\t\t\n\t\tif 'turbulenceintensity' in self.namelist['windflo_data']:\t\t\n\t\t\tself.turbulenceintensity = self.namelist['windflo_data']['turbulenceintensity']\n\t\t\t\t\n\t\tif 'wakemodel' in self.namelist['windflo_data']:\t\t\n\t\t\tself.wakemodel = self.namelist['windflo_data']['wakemodel']\n\t\t\t\t\n\t\tif 'wakemergemodel' in self.namelist['windflo_data']:\t\t\n\t\t\tself.wakemergemodel = self.namelist['windflo_data']['wakemergemodel']\n\t\t\t\t\n\t\tif 'wakeexpansioncoeff' in self.namelist['windflo_data']:\t\t\n\t\t\tself.wakeexpansioncoeff = np.array(self.namelist['windflo_data']['wakeexpansioncoeff'])\n\t\t\t\t\n\t\tif 'coe' in self.namelist['windflo_data']:\t\t\n\t\t\tself.coe = self.namelist['windflo_data']['coe']\n\t\t\t\t\n\t\tif 'terrainmodel' in self.namelist['windflo_data']:\t\t\n\t\t\tself.terrainmodel = self.namelist['windflo_data']['terrainmodel']\n\t\t\t\t\n\t\tif 'terrainfile' in self.namelist['windflo_data']:\t\t\n\t\t\tself.terrainfile = self.namelist['windflo_data']['terrainfile']\n\t\t\t\t\n\t\tif 'poweridw' in self.namelist['windflo_data']:\t\t\n\t\t\tself.poweridw = self.namelist['windflo_data']['poweridw']\n\t\t\t\t\n\t\tif 'rbfkernel' in self.namelist['windflo_data']:\t\t\n\t\t\tself.rbfkernel = self.namelist['windflo_data']['rbfkernel']\n\t\t\t\t\n\t\tif 'shapefactor' in self.namelist['windflo_data']:\t\t\n\t\t\tself.shapefactor = self.namelist['windflo_data']['shapefactor']\n\t\t\t\t\n\t\tif 'octreemaxpts' in self.namelist['windflo_data']:\t\t\n\t\t\tself.octreemaxpts = self.namelist['windflo_data']['octreemaxpts']\n\t\t\t\t\n\t\tif 'octreedepth' in self.namelist['windflo_data']:\t\t\n\t\t\tself.octreedepth = self.namelist['windflo_data']['octreedepth']\n\t\t\t\t\n\t\tif 'windrosefile' in self.namelist['windflo_data']:\t\t\n\t\t\tself.windrosefile = self.namelist['windflo_data']['windrosefile']\n\t\t\t\n\t\tnTurbines = kwargs.get('nTurbines', 0)\t\t\t\n\t\tif 'turbinefiles' in self.namelist['windflo_data'] and nTurbines == 0:\n\t\t\tself.nTurbines = len(self.namelist['windflo_data']['turbinefiles'])\n\t\telif 'turbinefiles' in self.namelist['windflo_data']:\n\t\t\tnTurbines = len(self.namelist['windflo_data']['turbinefiles'])\n\t\t\t\n\t\tturbineFile = kwargs.get('turbineFile', '')\n\t\tself.turbines = []\n\t\tfor i in range(0, self.nTurbines):\n\t\t\tself.turbines.append( TurbineData( params = np.zeros(30) ) )\n\t\t\tif turbineFile != '':\n\t\t\t\tself.turbines[i].SetFromNamelist(turbineFile)\n\t\t\telif i < nTurbines:\n\t\t\t\tif os.path.exists(self.namelist['windflo_data']['turbinefiles'][i]):\n\t\t\t\t\tself.turbines[i].SetFromNamelist(self.namelist['windflo_data']['turbinefiles'][i])\n\t\t\n\n\n\n\tdef WriteInputFile(self, **kwargs):\n\t\n\t\trunDir = kwargs.get('runDir', self.runDir)\t\t\n\t\n\t\tself.namelist['windflo_data']['rho'] = self.rho\n\t\tself.namelist['windflo_data']['modelvelocity'] = self.modelvelocity.tolist()\n\t\tself.namelist['windflo_data']['windmodel'] = self.windmodel\n\t\tself.namelist['windflo_data']['gaussorder'] = self.gaussorder\n\t\tself.namelist['windflo_data']['montecarlopts'] = self.montecarlopts\n\t\tself.namelist['windflo_data']['referenceheight'] = self.referenceheight\n\t\tself.namelist['windflo_data']['surfaceroughness'] = self.surfaceroughness\n\t\tself.namelist['windflo_data']['turbulenceintensity'] = self.turbulenceintensity\n\t\tself.namelist['windflo_data']['wakemodel'] = self.wakemodel\n\t\tself.namelist['windflo_data']['wakemergemodel'] = self.wakemergemodel\n\t\tself.namelist['windflo_data']['wakeexpansioncoeff'] = self.wakeexpansioncoeff.tolist()\n\t\tself.namelist['windflo_data']['coe'] = self.coe\n\t\tself.namelist['windflo_data']['terrainmodel'] = self.terrainmodel\n\t\tself.namelist['windflo_data']['terrainfile'] = self.terrainfile\n\t\tself.namelist['windflo_data']['poweridw'] = self.poweridw\n\t\tself.namelist['windflo_data']['rbfkernel'] = self.rbfkernel\n\t\tself.namelist['windflo_data']['shapefactor'] = self.shapefactor\n\t\tself.namelist['windflo_data']['octreemaxpts'] = self.octreemaxpts\n\t\tself.namelist['windflo_data']['octreedepth'] = self.octreedepth\n\t\tself.namelist['windflo_data']['windrosefile'] = self.windrosefile\n\n\t\n\t\tself.namelist['windflo_data']['turbinefiles'] = []\n\t\tfor i in range(0, self.nTurbines):\n\t\t\tself.namelist['windflo_data']['turbinefiles'].append( runDir +'turbine'+str(i+1)+'.inp' )\n\t\t\tself.turbines[i].WriteInputFile( runDir + 'turbine'+str(i+1)+'.inp' )\n\n\t\tfilename = kwargs.get('inFile', 'WindFLO.inp')\n\t\tself.namelist.write(runDir + filename, force=True)\n\n\t\t\n\n\n\tdef run(self,**kwargs):\n\t\t\n\t\tself.ParseKwargsForAnalysisParams(**kwargs)\n\t\t\n\t\tself.runDir = kwargs.get('runDir', self.runDir)\t\t\t\n\t\tself.WriteInputFile(**kwargs)\n\t\t\t\n\t\tself.libWindFLO.Python_WindFLO_API.argtypes = [POINTER(c_char),\t\t# infilename\n\t\t\t\t\t\t\t\t\t\t\t\t \t POINTER(c_char),\t\t# infilename\n\t\t\t\t\t\t\t\t\t\t\t\t \t (c_int) ,\t\t\t\t# nturbines\n\t\t\t\t\t\t\t\t\t\t\t\t \t POINTER(c_double),\t# velocities\n\t\t\t\t\t\t\t\t\t\t\t\t \t POINTER(c_double),\t# power\n\t\t\t\t\t\t\t\t\t\t\t\t \t POINTER(c_double),\t# rated power\n\t\t\t\t\t\t\t\t\t\t\t\t \t POINTER(c_double)]\t# outputs\n\t\t\n\t\t\n\t\t\n\t\tinFile = self.runDir + kwargs.get('inFile', 'WindFLO.inp')\n\t\tCinFile = np.asarray(inFile + '\\0', dtype = c_char).ctypes.data_as(POINTER(c_char))\n\n\t\tresFile = self.runDir + kwargs.get('resFile', '')\n\t\tCoutFile = np.asarray(resFile + '\\0', dtype = c_char).ctypes.data_as(POINTER(c_char))\n\n\t\t\n\t\tvelocities = np.zeros(self.nTurbines*3, dtype = c_double)\n\t\tCvelocities = velocities.ctypes.data_as(POINTER(c_double))\n\t\t\n\t\tpower = np.zeros(self.nTurbines, dtype = c_double)\t\t\n\t\tCpower = power.ctypes.data_as(POINTER(c_double))\n\n\t\tratedpower = np.zeros(self.nTurbines, dtype = c_double)\t\t\n\t\tCratedpower = ratedpower.ctypes.data_as(POINTER(c_double))\n\n\n\t\toutputs = np.zeros(100, dtype = c_double)\t\t\t\t\n\t\tCoutputs = outputs.ctypes.data_as(POINTER(c_double))\n\n\t\tself.libWindFLO.Python_WindFLO_API(CinFile, CoutFile, c_int(self.nTurbines), Cvelocities, Cpower,Cratedpower, Coutputs)\n\n\t\tself.AEP = outputs[0]\n\t\tself.farmPower = outputs[1]\n\t\tself.farmEfficiency = outputs[2]\n\t\tself.farmCost = outputs[3]\n\t\tself.landUsed = outputs[4]\n\t\tself.COE = self.farmCost / self.AEP\t\t\n\t\tself.totalRatedPower = np.sum(ratedpower)\n\t\tself.normalizedAEP = self.AEP / (self.totalRatedPower * 365.0 * 24.0)\n\t\t\n\t\tself.UpdateDict()\n\t\t\n\t\tclean = kwargs.get('clean', True)\t\t\n\t\tk = 0\n\t\tfor i in range(0, self.nTurbines):\n\t\t\tfor j in range(0, 3):\n\t\t\t\tself.turbines[i].velocity[j] = velocities[k]\n\t\t\t\tk = k + 1\n\t\t\tself.turbines[i].power = power[i]\n\t\t\tself.turbines[i].ratedPower = ratedpower[i]\n\t\t\tself.turbines[i].UpdateDict()\t\t\t\n\t\t\tif clean:\t\t\t\n\t\t\t\tos.remove(self.namelist['windflo_data']['turbinefiles'][i])\n\t\tif clean:\t\t\n\t\t\tos.remove(inFile)\n\n\t\t\t\n\tdef clean(self):\n\t\tself.libWindFLO.Clean_()\n\tdef cleanall(self):\n\t\tself.libWindFLO.CleanAll_()\n\t\n\n\tdef ReadResultsFile(self, inFile):\n\t\n\t\tf = open(inFile,'r')\n\t\tline = f.readline()\n\t\t\n\t\t\n\t\t# Get the farm performance\n\t\tfor i in range(0,6):\n\t\t\tline = f.readline()\n\n\t\t\tvarName = line.split('=')[0].strip()\n\t\t\tvarVal = float(line.split('=')[1])\n\n\t\t\tif(varName == 'nTurbines'):\n\t\t\t\tself.nTurbines = int(varVal)\n\t\t\tif(varName == 'AEP'):\n\t\t\t\tself.AEP = varVal\n\t\t\tif(varName == 'Power'):\n\t\t\t\tself.farmPower = varVal\n\t\t\tif(varName == 'Efficiency'):\n\t\t\t\tself.farmEfficiency = varVal\n\t\t\tif(varName == 'Cost'):\n\t\t\t\tself.farmCost = varVal\n\t\t\tif(varName == 'Land Used'):\n\t\t\t\tself.landUsed = varVal\n\n\n\t\t# Get turbines in farm\n\t\tline = f.readline()\n\t\tline = f.readline()\n\t\tself.turbines = []\n\t\tfor i in range(0, self.nTurbines):\n\t\t\tline = f.readline()\n\t\t\t\n\t\t\tif(line.strip() == '$ConvexHull'):\n\t\t\t\tbreak\n\t\t\t\n\t\t\tturbineParams = [float(i) for i in line.split(',')]\n\t\t\tself.turbines.append( TurbineData( params = turbineParams ) )\n\t\t\n\t\t# Get convex hull params\t\t\n\t\tline = f.readline()\n\t\tline = f.readline()\n\n\t\tself.convexHull = np.zeros((self.nTurbines,2))\n\t\tj = 0\n\t\tfor i in range(0,self.nTurbines):\n\t\t\tline = f.readline()\n\t\t\tif(line.strip() == '$End'):\n\t\t\t\tbreak\n\t\t\n\t\t\tpoints = line.split(',')\n\t\t\tself.convexHull[j,0] = points[1]\n\t\t\tself.convexHull[j,1] = points[2]\n\t\t\tj = j + 1\n\t\n\t\tself.convexHull.resize((j,2))\n\t\t\n\t\t\n\t\tratedPower = np.array([i.ratedPower for i in self.turbines])\n\t\tself.totalRatedPower = np.sum(ratedPower)\n\t\tself.farmPower = np.sum(np.array([i.power for i in self.turbines]))\n\t\tself.farmEfficiency = self.farmPower / self.totalRatedPower\n\t\tself.normalizedAEP = self.AEP / (self.totalRatedPower * 365.0 * 24.0)\n\n\n#\t\tTake Care of Units\n\t\tif self.AEP > 1e7:\n\t\t\taepUnit = 'MWh'\n\t\telif self.AEP > 1e4:\n\t\t\taepUnit = 'kWh'\n\t\telse:\n\t\t\taepUnit = 'Wh'\n\n\t\tif self.farmPower > 1e7:\n\t\t\tpowerUnit = 'MW'\n\t\telif self.farmPower > 1e4:\n\t\t\tpowerUnit = 'kW'\n\t\telse:\n\t\t\tpowerUnit = 'W'\n\t\t\n\t\tif self.landUsed > 1e6:\n\t\t\tareaUnit = 'km^2'\n\t\telse:\n\t\t\tareaUnit = 'm^2'\n\n\t\tself.COE = self.farmCost / self.AEP\n\t\tcoeUnits = '$/'+aepUnit\n\n\t\tself.units = {'P': powerUnit,'Pr':powerUnit, 'A': areaUnit, 'AEP': aepUnit, 'COE': coeUnits}\n\n\tdef UpdateDict(self):\n\n#\t\tTake Care of Units\n\t\tif self.AEP > 1e7:\n\t\t\taepUnit = 'MWh'\n\t\telif self.AEP > 1e4:\n\t\t\taepUnit = 'kWh'\n\t\telse:\n\t\t\taepUnit = 'Wh'\n\n\t\tif self.farmPower > 1e7:\n\t\t\tpowerUnit = 'MW'\n\t\telif self.farmPower > 1e4:\n\t\t\tpowerUnit = 'kW'\n\t\telse:\n\t\t\tpowerUnit = 'W'\n\t\t\n\t\tif self.landUsed > 1e6:\n\t\t\tareaUnit = 'km^2'\n\t\telse:\n\t\t\tareaUnit = 'm^2'\n\n\t\tcoeUnits = '$/'+aepUnit\n\n\t\tself.units = {'P': powerUnit,'Pr':powerUnit, 'A': areaUnit, 'AEP': aepUnit, 'COE': coeUnits}\n\n\n\t\tself.scaling = {'MWh':1e-6, 'MW':1e-6, 'kWh':1e-3, 'kW':1e-3, 'Wh':1, 'W':1, 'km^2':1e-6, 'm^2':1,\\\n\t\t\t\t\t\t'$/MWh':1e6, '$/kWh':1e3, '$/Wh':1}\n\n\n\t\tself.props = {'P': self.farmPower, 'A': self.landUsed, 'AEP': self.AEP, 'COE': self.COE, \\\n\t\t\t\t\t 'nAEP': self.normalizedAEP, 'eff': self.farmEfficiency, 'cost':self.farmCost,\\\n\t\t\t\t\t 'Pr': self.totalRatedPower}\n\n\n\t\n\n\tdef getVar(self, variable):\n\t\n\t\tself.UpdateDict()\n\t\tvalue = self.props.get(variable, 0.0)\n\t\tunit = self.units.get( variable , '')\t\n\t\tscale = self.scaling.get(unit,1)\n\t\t\n\t\treturn value * scale, unit\n\t\t\n\t\t\n\n\tdef plotWindFLO2D(self, fig, plotVariable = 'V', scale = 1.0, title = ''):\n\t\t\n\t\tax = plt.subplot(1,1,1)\n\t\t\t\t\n\t\tax.set_xlabel('x [m]', fontsize=16, labelpad = 5)\n\t\tax.set_ylabel('y [m]', fontsize=16, labelpad = 5)\t\n\n\t\tax.tick_params(axis = 'x', which = 'major', labelsize = 15, pad=0)\n\t\tax.tick_params(axis = 'y', which = 'major', labelsize = 15, pad=0)\t\t\n\n\t\tx = np.array([i.position[0] for i in self.turbines])\n\t\ty = np.array([i.position[1] for i in self.turbines])\n\t\tvar = np.array([LA.norm(i.variables[plotVariable]) for i in self.turbines])\t* scale\t\n\n\t\tjet_map = plt.get_cmap('jet')\t\t\t\n\t\tscatterPlot = ax.scatter(x,y, c=var, marker = '^', s = 100, cmap = jet_map, alpha = 1)\n\n\t\tif( (max(var) - min(var)) > 0):\n\n\t\t\tcolorTicks = np.linspace(min(var), max(var), 7, endpoint = True)\n\t\t\tcolorBar = plt.colorbar(scatterPlot,pad = 0.06,shrink = 0.8, format = ticker.FuncFormatter(fmt), ticks = colorTicks)\t\n\t\t\n\t\t\tcolorBar.ax.tick_params(labelsize=16)\n\t\t\tcolorBar.ax.set_title(title, fontsize = 16,ha='left', pad = 15)\n\t\t#\ttick_locator = ticker.MaxNLocator(nbins=7)\n\t\t#\tcolorBar.locator = tick_locator\n\t\t\tcolorBar.update_ticks()\n\n\n\t\tplt.locator_params(axis='x', nbins=6)\n\t\tplt.locator_params(axis='y', nbins=6)\n\n\t\tplt.tight_layout()\n\t\t\n\n\t\treturn ax\n\n\n\n\tdef plotWindFLO3D(self, fig, plotVariable = ['V'], scale = [1.0], title = ['']):\n\t\t\n\t\t\n\t\tax = plt.subplot(1,1,1, projection='3d')\n\t\t\t\t\n\t\tax.set_xlabel('x [m]', fontsize=16, labelpad = 5)\n\t\tax.set_ylabel('y [m]', fontsize=16, labelpad = 5)\t\n\t\tax.set_zlabel('z [m]', fontsize=16, labelpad = 10)\t\n\n\t\tax.tick_params(axis = 'x', which = 'major', labelsize = 15, pad=0)\n\t\tax.tick_params(axis = 'y', which = 'major', labelsize = 15, pad=0)\t\t\n\t\tax.tick_params(axis = 'z', which = 'major', labelsize = 15, pad=5)\n\n\n\t\tnPlot = len(plotVariable)\n\t\n\t\tx = np.array([i.position[0] for i in self.turbines])\n\t\ty = np.array([i.position[1] for i in self.turbines])\n\t\tz = np.array([i.position[2] for i in self.turbines])\n\t\tH = np.array([i.height for i in self.turbines])\n\t\tvar1 = np.array([LA.norm(i.variables[plotVariable[0]]) for i in self.turbines])\t* scale[0]\n\t\n\t\tfor i in range(0,len(x)):\n\t\t\tax.plot( [x[i],x[i]], [y[i],y[i]], [z[i],z[i]+H[i]], markersize = 8, markerfacecolor = 'none', color = 'gray' )\n\n\t\tjet_map = plt.get_cmap('jet')\n\n\n\t\tif nPlot > 1:\n\t\t\tvar2 = np.array([LA.norm(i.variables[plotVariable[1]]) for i in self.turbines])\t* scale[1]\n\t\t\tminMarkerSize = 50\n\t\t\tmaxMarkerSize = 150\n\t\t\tmarkerSize = minMarkerSize + (var2 - min(var2)) * (maxMarkerSize / (max(var2) - min(var2)))\n\t\telse:\n\t\t\tmarkerSize = 100\n\n\n\t\tscatterPlot = ax.scatter(x,y,z+H, c=var1, marker = 'o', s = markerSize, cmap = jet_map, alpha = 1)\n\n\t\tcolorTicks = np.linspace(min(var1), max(var1), 7, endpoint = True)\n\t\tcolorBar = plt.colorbar(scatterPlot,pad = 0.0,shrink = 0.8, format = ticker.FuncFormatter(fmt), ticks = colorTicks)\t\n\t\t\n\t\tcolorBar.ax.tick_params(labelsize=15)\n\t\tcolorBar.ax.set_title(title[0], fontsize = 16,ha='left', pad = 10)\n#\t\ttick_locator = ticker.MaxNLocator(nbins=7)\n#\t\tcolorBar.locator = tick_locator\n\t\tcolorBar.update_ticks()\n\n\n\t\tif nPlot > 1:\n\n\t\t\t# produce a legend with a cross section of sizes from the scatter\n\t\t\ttmp = np.linspace(min(var2),max(var2), 5, endpoint = True)\t\t\t\n#\t\t\ttmp = np.arange(min(var2),max(var2), (max(var2) - min(var2)) / 5)\n\t\t\ttmpMs = minMarkerSize + (tmp - min(tmp)) * (maxMarkerSize / (max(tmp) - min(tmp)))\t\n\t\t\tlabels = ['{0:.1f}'.format(s) for s in tmp]\n\t\t\tpoints = [ax.scatter([], [], [], s=s, c='gray') for s in tmpMs]\n\t\t\tsizeLegend = plt.legend(reversed(points), reversed(labels), scatterpoints=1,loc=(-.35,0.2), fontsize = 15,frameon=True)\t\n\t\t\tsizeLegend.set_title(title[1], prop = {'size':'16'})\n\t\t\tsizeLegend.get_frame().set_linewidth(2.0)\n\n\n\t\t\n\t\tplt.locator_params(axis='x', nbins=6)\n\t\tplt.locator_params(axis='y', nbins=6)\n\n\t\tax.view_init(azim=-150,elev=30.)\t\n\n\t\tplt.subplots_adjust(left=0.25, right=1., top=0.9, bottom=0.01)\n\n\t\t\n\t\treturn ax\n\t\t\n\n\t\t\n\tdef getScaledPerformance(self, scale = False):\n\t\n\t\tAEP = 0.0\n\t\tfarmPower = 0.0\n\t\tlandUsed = 0.0\n\t\t\n\t\tif scale == False:\n\t\t\tAEP = self.AEP \n\t\t\tfarmPower = self.farmPower \n\t\t\tlandUsed = self.landUsed\n\n\t\t\treturn AEP, farmPower, landUsed\n\t\t\t\n\t\t\n\t\tif self.units['AEP'] == 'MW':\n\t\t\tAEP = self.AEP / 1e6\n\t\telif self.units['AEP'] == 'kW':\n\t\t\tAEP = self.AEP / 1e3\n\t\telse:\n\t\t\tAEP = self.AEP \n\n\t\tif self.units['P'] == 'MW':\n\t\t\tfarmPower = self.farmPower / 1e6\n\t\telif self.units['P'] == 'kW':\n\t\t\tfarmPower = self.farmPower / 1e3\n\t\telse:\n\t\t\tfarmPower = self.farmPower \n\t\t\n\t\tif \tself.units['A'] == 'km^2':\n\t\t\tlandUsed = self.landUsed / 1e6\n\t\telse:\n\t\t\tlandUsed = self.landUsed\n\t\t\n\n\t\treturn AEP, farmPower, landUsed\n\n\tdef annotatePlot(self, ax):\n\n\t\tAEP, power, landArea = self.getScaledPerformance(scale = True)\n\n\t\tCOE, _ = self.getVar('COE')\n\t\tAEP, _ = self.getVar('AEP')\n\t\tpower, _ = self.getVar('P')\n\t\tlandArea, _ = self.getVar('A')\n\n\t\tax.annotate( r'CoE = '+str('{0:.2f} '.format(COE)) + self.units['COE'], (0.0,0.0), (-.1,1.08), fontsize = 16, xycoords='axes fraction',va='top')\n#\t\tax.annotate( r'$AEP = $'+str('{0:.2f}'.format(AEP)) + self.units['AEP'], (0.0,0.0), (0.,1.08), fontsize = 16, xycoords='axes fraction',va='top')\n\t\tax.annotate( r'$\\overline{\\eta}_{Farm} = $'+str('{0:.2f}'.format(self.farmEfficiency)) , (0.0,0.0), (0.5,1.08), fontsize = 16, xycoords='axes fraction',va='top') \n\t\tax.annotate( r'$A_{Farm} = $'+str('{0:.2f}'.format(landArea)) + r' $'+ self.units['A']+'$', (0.0,0.0), (0.85,1.08), fontsize = 16, xycoords='axes fraction',va='top') \n#\t\tax.annotate( r'$AEP = $'+str('{0:.0f}'.format(self.AEP)) + ' kWH', (0.0,0.0), (-0.15,0.07), fontsize = 16)\n#\t\tax.annotate( r'$\\overline{Cost}_{Farm} = $'+str('{0:.0f}'.format(self.farmCost/self.farmPower)) + ' USD/kW', (0.0,0.0), (-0.15,0.07), fontsize = 16)\n\n\t\tplt.tight_layout()\n\n\n\tdef plotConvexHull(self, ax):\n\t\tax.plot(self.convexHull[:,0],self.convexHull[:,1], 'k-')\n\n","sub_path":"API/WindFLO.py","file_name":"WindFLO.py","file_ext":"py","file_size_in_byte":23670,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"619527430","text":"from django.conf.urls import patterns, url\n\nfrom main import views\n\nurlpatterns = patterns('',\n url(r'^$', views.index, name='index'),\n url(r'^contact/', views.contact, name='contact'),\n url(r'^music/', views.MusicView.as_view(), name='music'),\n url(r'^writing/', views.WritingView.as_view(), name='writing')\n)","sub_path":"main/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":322,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"151172973","text":"\"\"\"\r\n Use matplotlib to plot x and y plane in pixel\r\n\"\"\"\r\n\r\nimport pydicom\r\nimport numpy as np\r\n# from pydicom.data import get_testdata_files\r\n# import matplotlib\r\nimport matplotlib.pyplot as plt\r\nfrom matplotlib.widgets import Slider, Button\r\nimport os\r\n\r\n\r\ndef load_scan(path):\r\n slices = [pydicom.read_file(path + '/' + s) for s in os.listdir(path)]\r\n slices.sort(key=lambda x: int(x.InstanceNumber))\r\n try:\r\n slice_thickness = np.abs(slices[0].ImagePositionPatient[2] - slices[1].ImagePositionPatient[2])\r\n except:\r\n slice_thickness = np.abs(slices[0].SliceLocation - slices[1].SliceLocation)\r\n\r\n for s in slices:\r\n s.SliceThickness = slice_thickness\r\n\r\n return slices\r\n\r\n\r\n# def create_voxel_array(dcms):\r\n# image = np.stack([s.pixel_array for s in dcms])\r\n# return image\r\n\r\n\r\ndef update_sagittal(val):\r\n index = int(s_index.val)\r\n canvas_sagittal.set_data(voxel_sagittal[index, :])\r\n plt.draw()\r\n\r\n\r\ndata_path = r\"C:\\Users\\janej\\OneDrive\\MelbUni\\MASTER OF ENGINEERING\\CapstoneProject_2018\\Test_Images\\Series 002 [CT - Crane SPC]\"\r\ndcms = load_scan(data_path)\r\nimage = np.stack([s.pixel_array for s in dcms])\r\n# print(voxel.shape)\r\n# print(voxel)\r\n# print(voxel[0][0][0])\r\nvoxel_sagittal = image.transpose(2, 0, 1)\r\n# print(voxel_frontal[95][100][102])\r\n# print(voxel_frontal[0,:])\r\n\r\n\r\ncanvas_sagittal = plt.imshow(voxel_sagittal[0, :], cmap=plt.cm.bone)\r\nax_index = plt.axes([0.15, 0.1, 0.65, 0.03], facecolor='lightgoldenrodyellow')\r\ns_index = Slider(ax_index, 'Index', 0, 511, valinit=0, valstep=1)\r\ns_index.on_changed(update_sagittal)\r\nplot = plt.show()\r\n\r\n","sub_path":"test_code/plot_sagittal.py","file_name":"plot_sagittal.py","file_ext":"py","file_size_in_byte":1626,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"450599031","text":"import services.controlers.loggControler\nimport services.querys.countryQuery\nfrom services.exceptions import *\nimport os\nimport hashlib\nimport re\nimport cgi\nimport urllib\n\nclass CountriesControler:\n\tdef get(self):\n\t\tcountryQuery = services.querys.countryQuery.CountryQuery()\n\t\tcountriesList=[]\n\t\ttry:\n\t\t\tdata = countryQuery.getCountries()\n\t\t\tfor countryObject in data:\n\t\t\t\tcountry={}\n\t\t\t\tid = str(countryObject.key().id())\n\t\t\t\tcountry[\"id\"]=id\n\t\t\t\tcountry[\"autoId\"]=countryObject.autoId\n\t\t\t\tcountry[\"name\"]=countryObject.name\n\t\t\t\tcountriesList.append(country)\n\t\texcept Exception as e:\n\t\t\tloggControler = services.controlers.loggControler.LoggControler()\n\t\t\tloggControler.addLogg('Critical', ERROR_NO_DEFINIDO, e.message)\n\t\treturn countriesList\n\n\tdef getById(self, identifier):\n\t\tcountry={}\n\t\ttry:\n\t\t\tcountryQuery = services.querys.countryQuery.CountryQuery()\n\t\t\tattributesList=[]\n\t\t\tcountryObject = countryQuery.getCountryById(identifier)\n\t\t\tid = str(countryObject.key().id())\n\t\t\tcountry[\"id\"]=id\n\t\t\tcountry[\"autoId\"]=countryObject.autoId\n\t\t\tcountry[\"name\"]=countryObject.name\n\t\texcept Exception as e:\n\t\t\tloggControler = services.controlers.loggControler.LoggControler()\n\t\t\tloggControler.addLogg('Critical', ERROR_NO_DEFINIDO, e.message)\n\t\treturn country\n\n\tdef getByName(self, name):\t\n\t\tcountry={}\n\t\ttry:\n\t\t\tcountryQuery = services.querys.countryQuery.CountryQuery()\n\t\t\tcountries = countryQuery.getCountryByName(str(name))\n\t\t\tfor countryObject in countries:\n\t\t\t\tcountry[\"id\"] = countryObject.key().id()\n\t\t\t\tcountry[\"autoId\"]=countryObject.autoId\n\t\t\t\tcountry[\"name\"] = countryObject.name\n\t\texcept Exception as e:\n\t\t\tloggControler = services.controlers.loggControler.LoggControler()\n\t\t\tloggControler.addLogg('Critical', ERROR_NO_DEFINIDO, e.message)\n\t\treturn country\n\n\tdef addCountry(self, name):\n\t\tmessage=\"PAIS_NO_REGISTRADO\"\n\t\tstate = 300\n\t\ttry:\n\t\t\tcountryQuery = services.querys.countryQuery.CountryQuery()\n\t\t\t# VALIDACIONES\n\t\t\tdoRegister = True\n\t\t\tif countryQuery.getExists(name):\n\t\t\t\tdoRegister = False\n\t\t\t\tstate = 203\n\t\t\t\tmessage = message + \": EL ELEMENTO YA EXISTE\"\n\t\t\t# REGISTRO\n\t\t\tif doRegister == True:\n\t\t\t\tquery = countryQuery.addCountry(name)\n\t\t\t\tmessage=\"PAIS_REGISTRADO\"\n\t\t\t\tstate = OK\n\t\texcept Exception as e:\n\t\t\tloggControler = services.controlers.loggControler.LoggControler()\n\t\t\tloggControler.addLogg('Critical', ERROR_NO_DEFINIDO, e.message)\n\t\treturn message, state\n\n\tdef editCountry(self, name, identifier):\n\t\tmessage=\"PAIS_NO_MODIFICADO\"\n\t\tstate = 300\n\t\ttry:\n\t\t\tcountryQuery = services.querys.countryQuery.CountryQuery()\n\t\t\tcountryObject = countryQuery.getCountryById(identifier)\n\t\t\tcountryObject.name = name\n\t\t\tcountryObject.upperCaseName = name.upper()\n\t\t\tcountryQuery.editCountry(countryObject)\n\t\t\tmessage=\"PAIS_MODIFICADO\"\n\t\t\tstate = OK\n\t\texcept Exception as e:\n\t\t\tloggControler = services.controlers.loggControler.LoggControler()\n\t\t\tloggControler.addLogg('Critical', ERROR_NO_DEFINIDO, e.message)\t\n\t\treturn message, state\n\n\tdef\tdropAllCountries(self):\n\t\tmessage=\"PAISES_NO_ELIMINADOS\"\n\t\tstate = 300\n\t\ttry:\n\t\t\tcountryQuery = services.querys.countryQuery.CountryQuery()\n\t\t\tcountryQuery.dropAllCountries()\n\t\t\tmessage=\"PAISES_ELIMINADOS\"\n\t\t\tstate = OK\n\t\texcept Exception as e:\n\t\t\tloggControler = services.controlers.loggControler.LoggControler()\n\t\t\tloggControler.addLogg('Critical', ERROR_NO_DEFINIDO, e.message)\n\t\treturn message, state\n","sub_path":"services/controlers/countriesControler.py","file_name":"countriesControler.py","file_ext":"py","file_size_in_byte":3359,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"343556491","text":"from pyramid.view import view_config\nfrom pyramid.response import Response\nfrom pyramid.renderers import render_to_response\nimport pyramid.httpexceptions as exc\n\nfrom sqlalchemy.exc import DBAPIError\nfrom sqlalchemy.sql.expression import insert\n\nfrom datetime import datetime\nfrom parse import parse\n\nfrom ice_auth import models\nfrom ice_auth.utils import logs\n\nclass ListenerAuthView:\n def __init__(self, request):\n self.request = request\n\n # Method used to authenticate new listeners, that are trying to connect with icecast\n #---------------------------------------------------------------------------------------------------\n @view_config(route_name = 'icecast_listener_add', request_method = 'POST')\n def listener_add(self):\n log = logs.ice_log(__name__, self.request)\n\n # Try to find listener by the data from POST\n listener = self.findListenerByPost()\n if not listener:\n raise exc.HTTPUnauthorized()\n\n # If there is no access data connected to current listener, raise exception\n access = self.accessParams(listener)\n if not access:\n log.critical('There is no access data for listener with id {}'\n .format(listener.id, True))\n raise exc.HTTPInternalServerError()\n\n # Check if user has active account\n if datetime.now().date() > access.expiration_date:\n raise exc.HTTPForbidden()\n\n # Check if user is not already connected\n if self.countActiveListeners(listener) >= access.max_listeners:\n raise exc.HTTPForbidden()\n\n # Add user to active_listeners table\n new_listener = models.ActiveListeners(listener_id = listener.id, listener_ip = self.request.remote_addr)\n self.request.dbsession.add(new_listener)\n\n log.info('Listener with id {} connected to icecast'.format(listener.id))\n return Response(headerlist=[(\"listener_accepted\", \"1\")], status_int = 200)\n\n # Method used to remove disconnecting listeners from active listeners table\n #---------------------------------------------------------------------------------------------------\n @view_config(route_name = 'icecast_listener_remove', request_method = 'POST')\n def listener_remove(self):\n log = logs.ice_log(__name__, self.request)\n\n # Try to find listener by the data from POST\n listener = self.findListenerByPost()\n if not listener:\n raise exc.HTTPUnauthorized()\n\n if self.countActiveListeners(listener) <= 0:\n log.critical('Number of active listeners is <= 0 during listener_remove. | Listener id: {}'.format(listener.id), True)\n raise exc.HTTPInternalServerError()\n\n # Try to find active listener with given id and ip\n query = self.request.dbsession.query(models.ActiveListeners)\n listener_to_remove = query.filter(models.ActiveListeners.listener_id == listener.id).filter(models.ActiveListeners.listener_ip == self.request.remote_addr).first()\n\n # If there is no active listener that match to given ip, remove first with given id\n if not listener_to_remove:\n listener_to_remove = query.filter(models.ActiveListeners.listener_id == listener.id).first()\n\n # Check if we finally find him\n if not listener_to_remove:\n log.critical('Can not find listener with given id during listener_remove. | Listener id: {}'.format(listener.id), True)\n raise exc.HTTPInternalServerError()\n\n self.request.dbsession.delete(listener_to_remove) \n log.info('Listener with id {} disconnected from icecast'.format(listener.id)) \n return Response(status_int = 200)\n\n #---------------------------------------------------------------------------------------------------\n def findListenerByPost(self):\n # Get uuid from POST sent by icecast\n listener_uuid = self.uuidFromPost()\n\n # Try to find listener with given uuid\n listener = self.findListener(listener_uuid)\n if not listener:\n raise exc.HTTPUnauthorized()\n\n return listener\n\n #---------------------------------------------------------------------------------------------------\n def uuidFromPost(self): \n # Try to get mount data from POST\n icecast_data = self.request.params['mount']\n \n # Parse 'mount' data to get uuid (eg. data: '/auth_test?uuid=222-222')\n parsed_data = parse('/{}?uuid={}', icecast_data)\n if not parsed_data:\n log = logs.ice_log(__name__, self.request)\n log.error('Can not parse uuid', True)\n raise exc.HTTPBadRequest()\n\n # Try to get uuid from parsed data\n listener_uuid = parsed_data[-1]\n return listener_uuid\n\n #---------------------------------------------------------------------------------------------------\n def findListener(self, listener_uuid):\n query = self.request.dbsession.query(models.Listeners)\n listener = query.filter(models.Listeners.uuid == listener_uuid).first()\n return listener\n\n #---------------------------------------------------------------------------------------------------\n def accessParams(self, listener):\n log = logs.ice_log(__name__, self.request)\n if len(listener.access) != 1:\n log.critical('The number of access data for listener with id {} is different than 1. | Access data num: {}'\n .format(len(listener.access)), True)\n raise exc.HTTPInternalServerError()\n return listener.access[0]\n\n #---------------------------------------------------------------------------------------------------\n def countActiveListeners(self, listener):\n return len(listener.active_listeners)\n","sub_path":"ice_auth/views/icecast_auth.py","file_name":"icecast_auth.py","file_ext":"py","file_size_in_byte":5790,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"594472710","text":"import argparse\nimport json\nimport os\nfrom datetime import datetime\nfrom typing import Iterator\n\nimport boto3\nfrom mypy_boto3_s3.client import S3Client\nfrom mypy_boto3_sqs.client import SQSClient\n\nIS_LOCAL = bool(os.environ.get(\"IS_LOCAL\", False))\n\n\ndef into_sqs_message(bucket: str, key: str, region: str) -> str:\n return json.dumps(\n {\n \"Records\": [\n {\n \"eventTime\": datetime.utcnow().isoformat(),\n \"awsRegion\": region,\n \"principalId\": {\n \"principalId\": None,\n },\n \"requestParameters\": {\n \"sourceIpAddress\": None,\n },\n \"responseElements\": {},\n \"s3\": {\n \"schemaVersion\": None,\n \"configurationId\": None,\n \"bucket\": {\n \"name\": bucket,\n \"ownerIdentity\": {\n \"principalId\": None,\n },\n },\n \"object\": {\n \"key\": key,\n \"size\": 0,\n \"urlDecodedKey\": None,\n \"versionId\": None,\n \"eTag\": None,\n \"sequencer\": None,\n },\n },\n }\n ]\n }\n )\n\n\ndef send_s3_event(\n sqs_client: SQSClient,\n queue_url: str,\n output_bucket: str,\n output_path: str,\n):\n sqs_client.send_message(\n QueueUrl=queue_url,\n MessageBody=into_sqs_message(\n bucket=output_bucket,\n key=output_path,\n region=sqs_client.meta.region_name,\n ),\n )\n\n\ndef list_objects(client: S3Client, bucket: str) -> Iterator[str]:\n for page in client.get_paginator(\"list_objects_v2\").paginate(Bucket=bucket):\n for entry in page[\"Contents\"]:\n yield entry[\"Key\"]\n\n\ndef get_sqs_client() -> SQSClient:\n if IS_LOCAL:\n return boto3.client(\n \"sqs\",\n endpoint_url=os.environ[\"GRAPL_AWS_ENDPOINT\"],\n region_name=os.environ[\"AWS_REGION\"],\n aws_access_key_id=os.environ[\"GRAPL_AWS_ACCESS_KEY_ID\"],\n aws_secret_access_key=os.environ[\"GRAPL_AWS_ACCESS_KEY_SECRET\"],\n )\n else:\n return boto3.client(\"sqs\")\n\n\ndef get_s3_client() -> S3Client:\n if IS_LOCAL:\n return boto3.client(\n \"s3\",\n endpoint_url=os.environ[\"GRAPL_AWS_ENDPOINT\"],\n aws_access_key_id=os.environ[\"GRAPL_AWS_ACCESS_KEY_ID\"],\n aws_secret_access_key=os.environ[\"GRAPL_AWS_ACCESS_KEY_SECRET\"],\n )\n\n else:\n return boto3.client(\"s3\")\n\n\ndef main(deployment_name: str) -> None:\n s3, sqs = get_s3_client(), get_sqs_client()\n queue_name = deployment_name + \"-graph-merger-queue\"\n queue_url = sqs.get_queue_url(QueueName=queue_name)[\"QueueUrl\"]\n\n bucket = deployment_name + \"-subgraphs-generated-bucket\"\n for key in list_objects(s3, bucket):\n send_s3_event(\n sqs,\n queue_url,\n bucket,\n key,\n )\n\n\ndef parse_args() -> argparse.Namespace:\n parser = argparse.ArgumentParser(description=\"Replay graph-merger events\")\n parser.add_argument(\"--deployment_name\", dest=\"deployment_name\", required=True)\n return parser.parse_args()\n\n\nif __name__ == \"__main__\":\n\n args = parse_args()\n if args.deployment_name is None:\n raise Exception(\"Provide deployment name as first argument\")\n else:\n if args.deployment_name == \"local-grapl\":\n IS_LOCAL = True\n main(args.deployment_name)\n","sub_path":"etc/replay_data.py","file_name":"replay_data.py","file_ext":"py","file_size_in_byte":3799,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"217749607","text":"from gluon import current\n\ndef config(settings):\n \"\"\"\n Template settings for Bangladesh\n - designed to be used in a Cascade with an application template\n \"\"\"\n\n #T = current.T\n\n # Pre-Populate\n settings.base.prepopulate.append(\"locations/BD\")\n\n # Restrict to specific country/countries\n settings.gis.countries.append(\"BD\")\n # Dosable the Postcode selector in the LocationSelector\n #settings.gis.postcode_selector = False\n\n # L10n (Localization) settings\n settings.L10n.languages[\"bn\"] = \"Bengali\"\n # Default Language (put this in custom template if-required)\n #settings.L10n.default_language = \"bn\"\n # Default timezone for users\n settings.L10n.timezone = \"Asia/Dhaka\"\n # Default Country Code for telephone numbers\n settings.L10n.default_country_code = 880\n\n settings.fin.currencies[\"BDT\"] = \"Bangladeshi Taka\"\n settings.fin.currency_default = \"BDT\"\n\n# END =========================================================================\n","sub_path":"modules/templates/locations/BD/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":1000,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"505485383","text":"import random\nimport re\nfrom Execution import *\nfrom TestCase import *\nimport itertools\nimport copy\n\nclass MR():\n def __init__(self):\n self.set = ['A','G','C','T']\n self.name = self.__class__.__name__\n\n def setExecutor(self, executor):\n self.executor = executor\n\n def setTestCase(self, ts):\n self.original_ts = ts\n\n def process(self):\n self.executeTestCase(self.original_ts)\n original_input = Input(self.original_ts.infile)\n original_input.parseInfile() # load the A,B,C and matrix information\n original_output= self.getResults(self.original_ts)\n followup_ts = self.generateFollowupTestCase(original_input)\n self.executeTestCase(followup_ts)\n followup_output = self.getResults(followup_ts)\n expected_output = self.getExpectedOutput(original_output)\n self.isViolate = self.assertViolation(expected_output, followup_output)\n #if self.isViolate:\n # print(\"True\")\n #else:\n # print(\"False\")\n\n\n def generateFollowupTestCase(self, original_input):\n ts = TestCase()\n followup_infile = \"{}_f\".format(self.original_ts.infile)\n followup_outfile = \"{}_f\".format(self.original_ts.outfile)\n followup_outtree = \"{}_f\".format(self.original_ts.outtree)\n ts.setInputOutput(followup_infile, followup_outfile,followup_outtree)\n followup_input = self.getExpectedMatrix(original_input)\n followup_input.setInfile(followup_infile)\n followup_input.writeInfile()\n return ts\n\n def assertViolation(self, exp_output, followup_output):\n if exp_output.tree == followup_output.tree and exp_output.total_length == followup_output.total_length:\n return False\n else:\n return True\n\n def getExpectedOutput(self, original_output):\n expected_output = Output(original_output.outfile_name, original_output.outtree_name)\n expected_output.tree = original_output.tree\n expected_output.total_length = original_output.total_length\n return expected_output\n\n def getResults(self,ts):\n result = Output(ts.outfile, ts.outtree)\n result.parse()\n return result\n\n def executeTestCase(self,ts):\n self.executor.setInputOutputNames(ts.infile, ts.outfile, ts.outtree)\n self.executor.executeDnapars()\n\n def getExpectedMatrix(self, original_input):\n return original_input\n\n def setKilledMutantsTable(self,table):\n self.table = table\n\n\nclass MR1(MR):\n\n def __init__(self):\n super(MR1, self).__init__()\n self.a = 3\n self.b = 4\n\n def getExpectedMatrix(self, original_input):\n followup_input = copy.deepcopy(original_input)\n self.a = random.randint(0, len(followup_input.matrix[0])-1)\n self.b = self.a -3\n for i in range(len(followup_input.matrix)):\n temp = followup_input.matrix[i][self.a]\n followup_input.matrix[i][self.a] = followup_input.matrix[i][self.b]\n followup_input.matrix[i][self.b] = temp\n return followup_input\n\nclass MR2(MR):\n def __init__(self):\n super(MR2, self).__init__()\n self.insert_index = 3\n self.site_count = 50\n self.insert_site = random.choice(self.set) # randomly choice an element from a list. Don't use sample(), which will return a list object.\n\n def getExpectedMatrix(self,original_input):\n followup_input = copy.deepcopy(original_input)\n followup_input.B = str(int(followup_input.B)+self.site_count)\n for i in range(len(followup_input.matrix)):\n for j in range(self.site_count):\n followup_input.matrix[i].insert(self.insert_index, self.insert_site)\n return followup_input\n\nclass MR3(MR):\n def getExpectedMatrix(self, original_input):\n row = len(original_input.matrix)\n col = len(original_input.matrix[0])\n candidates = []\n for c in range(col):\n for r in range(1,row):\n if not original_input.matrix[r][c] == original_input.matrix[0][c]:\n candidates.append(c)\n break\n temp_matrix = []\n for r in range(row):\n temp = []\n for c in candidates:\n temp.append(original_input.matrix[r][c])\n temp_matrix.append(temp)\n\n original_input.B = str(len(candidates))\n original_input.matrix = temp_matrix\n return original_input\n\n\nclass MR4(MR):\n def getExpectedMatrix(self, original_input):\n original_input.B = str(2 * int(original_input.B))\n col = len(original_input.matrix[0])\n for i in range(len(original_input.matrix)):\n for j in range(col):\n original_input.matrix[i].append(original_input.matrix[i][j])\n return original_input\n\n def getExpectedOutput(self, original_output):\n expected_output = Output(original_output.outfile_name, original_output.outtree_name)\n expected_output.tree = original_output.tree\n expected_output.total_length = float(original_output.total_length)*2\n return expected_output\n\nclass MR5(MR):\n def __init__(self):\n super(MR5, self).__init__()\n\n def getExpectedMatrix(self, original_input):\n if len(original_input.matrix) == 4:\n insert_index = random.randint(0, len(original_input.matrix[0])-1)\n for i in range(4):\n original_input.matrix[i].insert(insert_index, self.set[i])\n original_input.B =str(int(original_input.B)+1)\n return original_input\n else:\n print(\"Cannot compound for this testcase\\n\")\n return None\n\n def assertViolation(self, exp_output, followup_output):\n if exp_output.tree == followup_output.tree:\n return False\n else:\n return True\n\n\nclass MR6(MR):\n def __init__(self):\n super(MR6, self).__init__()\n #self.permutation_set = dict(zip(self.set, random.sample(self.set, len(self.set))))\n self.permutation_set = []\n for i in range(len(self.set)):\n self.permutation_set.append(self.set[i-1])\n self.permutation_set = dict(zip(self.set, self.permutation_set))\n # self.permutation_set = dict(zip(self.set, random.sample(self.set, len(self.set))))\n\n def getExpectedMatrix(self, original_input):\n row = len(original_input.matrix)\n col = len(original_input.matrix[0])\n for i in range(row):\n for j in range(col):\n original_input.matrix[i][j] = self.permutation_set[original_input.matrix[i][j]]\n return original_input\n\nclass MR7(MR):\n def __init__(self):\n super(MR7, self).__init__()\n self.new_taxon = \"\"\n self.picked_taxon = \"\"\n self.source_index = 0\n\n def getExpectedMatrix(self, original_input):\n followup_input = copy.deepcopy(original_input)\n self.source_index = 2\n #self.source_index = random.randint(0,len(original_input.C)-1) # a<= N <= b\n self.picked_taxon = followup_input.C[self.source_index]\n self.new_taxon = self.picked_taxon+\"_1\"\n followup_input.C.insert(self.source_index, self.new_taxon)\n followup_input.A = str(int(followup_input.A)+1)\n followup_input.matrix.insert(self.source_index, followup_input.matrix[self.source_index])\n return followup_input\n\n def getExpectedOutput(self, original_output):\n expected_output = Output(original_output.outfile_name, original_output.outtree_name)\n tree = original_output.tree\n tree = re.sub(r\"{}\".format(self.picked_taxon), \"({},{})\".format(self.picked_taxon,self.new_taxon), tree)\n expected_output.tree = tree\n expected_output.total_length = original_output.total_length\n return expected_output\n\nclass CompositionMR(MR):\n def __init__(self):\n super(CompositionMR, self).__init__()\n self.MRs = [MR7(), MR4()]\n self.name = self.getName()\n self.MRs.reverse()\n\n def setMRs(self, mr_list):\n self.MRs = mr_list\n self.name = self.getName()\n self.MRs.reverse()\n\n def getName(self):\n return ''.join([mr.__class__.__name__ for mr in self.MRs])\n\n def getExpectedOutput(self, original_output):\n for mr in self.MRs:\n original_output = mr.getExpectedOutput(original_output)\n return original_output\n\n def getExpectedMatrix(self, original_input):\n followup_input = copy.deepcopy(original_input)\n for mr in self.MRs:\n followup_input = mr.getExpectedMatrix(followup_input)\n return followup_input\n\n def assertViolation(self, exp_output, followup_output):\n return self.MRs[-1].assertViolation(exp_output, followup_output)\n\ndef getCMRTestMR5List():\n mr_list = [[MR5(),MR1()],[MR5(),MR2()],[MR5(),MR3()],[MR5(),MR4()],[MR5(),MR6()]]\n cmr_list = []\n for cmr_c in mr_list:\n temp = CompositionMR()\n temp.setMRs(cmr_c)\n cmr_list.append(temp)\n return cmr_list\n\ndef getCMRPermutationsList(mr_list):\n cmr_list = []\n cmr_permutations = itertools.permutations(mr_list, 2)\n for cmr_p in cmr_permutations:\n temp = CompositionMR()\n temp.setMRs(list(cmr_p))\n cmr_list.append(temp)\n return cmr_list\n\ndef recordResult(file_name, mutants_list, mr_list):\n result = open(\"../results/\"+file_name,\"w\")\n temp = [v+\"\\t\" for v in mutants_list]\n temp.insert(0, \"\\t\")\n temp.append(\"\\n\")\n for cmr in mr_list:\n temp.append(\"{}\\t\".format(cmr.name))\n for v in mutants_list:\n temp.append(str(cmr.table[v])+\"\\t\")\n temp.append(\"\\n\")\n result.writelines(temp)\n result.close()\n\ndef MetamorphicTesting(executor, mutants_list, mr_list, test_case, num_of_samples):\n for mr in mr_list:\n table = dict(zip(mutants_list, [0]*len(mutants_list)))\n for i in range(num_of_samples):\n mr.setTestCase(test_case)\n mr.original_ts.setInputOutput(\"infile_{}\".format(i), \"outfile_{}\".format(i),\"outtree_{}\".format(i))\n mr.original_ts.generateRandomTestcase()\n mr.setExecutor(executor)\n for v in mutants_list:\n executor.setVersion(v)\n mr.process()\n if mr.isViolate:\n table[v] = table[v]+1\n mr.setKilledMutantsTable(table)\n\ndef testCMR():\n dna = Dnapars()\n num_of_samples = 1\n result_to_save_1= \"CMR_1000_part1.result\"\n result_to_save_2 = \"CMR_1000_part2.result\"\n mr_list = [MR1(),MR2(), MR3(), MR4(),MR6(), MR7()]\n mutants_list = [\"v1\",\"v2\",\"v3\",\"v4\",\"v5\",\"v6\",\"v7\",\"v8\",\"v9\",\"v10\"]\n cmr_list_1 = getCMRPermutationsList(mr_list)\n cmr_list_2 = getCMRTestMR5List()\n MetamorphicTesting(dna, mutants_list, cmr_list_1, TestCase(), num_of_samples)\n recordResult(result_to_save_1, mutants_list, cmr_list_1)\n MetamorphicTesting(dna, mutants_list, cmr_list_2, TestCase_V1(), num_of_samples)\n recordResult(result_to_save_2, mutants_list, cmr_list_2)\n\ndef testSingleMR():\n ts_1 =TestCase()\n ts_2 = TestCase_V1()\n dna = Dnapars()\n num_of_samples = 1\n result_to_save_1 = \"SMR_1000_part1.result\"\n result_to_save_2 = \"SMR_1000_part2.result\"\n mr_list_1 = [MR1(),MR2(), MR3(), MR4(),MR6(), MR7()]\n mr_list_2 = [MR5()]\n mutants_list = [\"v1\",\"v2\",\"v3\",\"v4\",\"v5\",\"v6\",\"v7\",\"v8\",\"v9\",\"v10\"]\n MetamorphicTesting(dna, mutants_list, mr_list_1, ts_1, num_of_samples)\n MetamorphicTesting(dna, mutants_list, mr_list_2, ts_2, num_of_samples)\n recordResult(result_to_save_1, mutants_list, mr_list_1)\n recordResult(result_to_save_2, mutants_list, mr_list_2)\n\n\ndef testSinglMRWithOneTestCase():\n ts =TestCase_V2()\n ts.setInputOutput(\"infile_{}\".format(\"t\"), \"outfile_{}\".format(\"t\"),\"outtree_{}\".format(\"t\"))\n ts.generateRandomTestcase()\n dna = Dnapars()\n cmr_list = [MR7()]\n mutants_list = [\"v1\",\"v2\",\"v3\",\"v4\",\"v5\",\"v6\",\"v7\",\"v8\",\"v9\",\"v10\"]\n for cmr in cmr_list:\n table = dict(zip(mutants_list, [0]*len(mutants_list)))\n cmr.setTestCase(ts)\n cmr.setExecutor(dna)\n dna.setVersion(\"v0\")\n cmr.process()\n if cmr.isViolate:\n table[\"v1\"] = table[\"v1\"]+1\n cmr.setKilledMutantsTable(table)\n\n\ndef testCMRWithOneTestCase():\n ts =TestCase_V2()\n ts.setInputOutput(\"infile_{}\".format(\"t\"), \"outfile_{}\".format(\"t\"),\"outtree_{}\".format(\"t\"))\n ts.generateRandomTestcase()\n dna = Dnapars()\n cmr1 = CompositionMR()\n cmr2 = CompositionMR()\n cmr1.setMRs([MR1(),MR7()])\n cmr2.setMRs([MR7(),MR1()])\n cmr_list = [cmr1,cmr2]\n mutants_list = [\"v1\",\"v2\",\"v3\",\"v4\",\"v5\",\"v6\",\"v7\",\"v8\",\"v9\",\"v10\"]\n for cmr in cmr_list:\n table = dict(zip(mutants_list, [0]*len(mutants_list)))\n cmr.setTestCase(ts)\n cmr.setExecutor(dna)\n dna.setVersion(\"v1\")\n cmr.process()\n if cmr.isViolate:\n table[\"v1\"] = table[\"v1\"]+1\n cmr.setKilledMutantsTable(table)\n\n\nif __name__ == \"__main__\":\n myenv = MyEnv()\n myenv.CreateWorkingDirs()\n testSingleMR()\n","sub_path":"DnaparsMetamorphicTest/MRs.py","file_name":"MRs.py","file_ext":"py","file_size_in_byte":13105,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"90501263","text":"import unittest, random, sys, time\nsys.path.extend(['.','..','../..','py'])\nimport h2o, h2o_browse as h2b, h2o_exec as h2e, h2o_import as h2i\n\n\nDO_COMPOUND = False\n\nphrasesCompound = [\n\n # use a dialetc with restricted grammar\n # 1. all functions are on their own line\n # 2. all functions only use data thru their params, or created in the function\n\n # \"a=1; a=2; function(x){x=a;a=3}\",\n # \"a=r.hex; function(x){x=a;a=3;nrow(x)*a}(a)\",\n # \"function(x){y=x*2; y+1}(2)\",\n # \"mean2=function(x){apply(x,1,sum)/nrow(x)};mean2(r.hex)\",\n]\n\nbadPhrases = [\n \"&&\",\n \"||\",\n \"%*%\",\n \"ifelse\",\n \"cbind\",\n \"print\",\n \"apply\",\n \"sapply\",\n \"ddply\",\n \"var\",\n \"Reduce\",\n \"cut\",\n \"findInterval\",\n \"runif\",\n \"scale\",\n \"t\",\n \"seq_len\",\n \"seq\",\n \"rep_len\",\n \"c\",\n \"table\",\n \"unique\",\n \"factor\",\n]\nphrases = [\n \"func1\",\n \"func2\",\n \"func3\",\n \"func4\",\n \"func5\",\n # \"func6\",\n \"nrow\",\n \"ncol\",\n \"length\",\n \"is.factor\",\n \"any.factor\",\n \"any.na\",\n \"isTRUE\",\n \"min.na.rm\",\n \"max.na.rm\",\n \"min\",\n \"max\",\n \"xorsum\",\n]\n\nif DO_COMPOUND:\n phrases += phrasesCompound\n\nclass Basic(unittest.TestCase):\n def tearDown(self):\n h2o.check_sandbox_for_errors()\n\n @classmethod\n def setUpClass(cls):\n global SEED\n SEED = h2o.setup_random_seed()\n h2o.init(1, java_heap_GB=12)\n\n @classmethod\n def tearDownClass(cls):\n h2o.tear_down_cloud()\n\n def test_exec2_apply_phrases(self):\n bucket = 'home-0xdiag-datasets'\n # csvPathname = 'standard/covtype.data'\n csvPathname = \"standard/covtype.shuffled.10pct.data\"\n\n hexKey = 'i.hex'\n parseResult = h2i.import_parse(bucket=bucket, path=csvPathname, schema='local', hex_key=hexKey)\n\n\n for col in [1]:\n initList = [\n ('r.hex', 'r.hex=i.hex'),\n (None, \"func1=function(x){max(x[,%s])}\" % col),\n (None, \"func2=function(x){a=3;nrow(x[,%s])*a}\" % col),\n (None, \"func3=function(x){apply(x[,%s],2,sum)/nrow(x[,%s])}\" % (col, col) ),\n # (None, \"function(x) { cbind( mean(x[,1]), mean(x[,%s]) ) }\" % col),\n (None, \"func4=function(x) { mean( x[,%s]) }\" % col), \n (None, \"func5=function(x) { sd( x[,%s]) }\" % col), \n (None, \"func6=function(x) { quantile(x[,%s] , c(0.9) ) }\" % col),\n ]\n for resultKey, execExpr in initList:\n h2e.exec_expr(h2o.nodes[0], execExpr, resultKey=resultKey, timeoutSecs=60)\n\n for p in phrases:\n # execExpr = \"sapply(r.hex, \" + p + \")\" \n execExpr = \"sapply(r.hex, \" + p + \")\" \n h2e.exec_expr(h2o.nodes[0], execExpr, resultKey=None, timeoutSecs=60)\n\nif __name__ == '__main__':\n h2o.unit_main()\n","sub_path":"py/testdir_single_jvm/test_exec2_sapply_phrases.py","file_name":"test_exec2_sapply_phrases.py","file_ext":"py","file_size_in_byte":2866,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"500768280","text":"\nfrom tkinter import *\nimport tkinter as tk\n\nimport student_tracking_main\nimport student_tracking_func\n\n\ndef load_gui(self):\n # Labels\n # Using the grid geometry manager, first access/instantiate tkinter's\n # 'Label' class and give that instantiation a class name 'self.lbl_fname'\n self.lbl_fname = tk.Label(self.master, text='First Name:')\n self.lbl_fname.grid(row=0,column=0,padx=(30,0),pady=(10,0),sticky=N+W)\n self.lbl_lname = tk.Label(self.master, text='Last Name:')\n self.lbl_lname.grid(row=2,column=0,padx=(30,0),pady=(10,0),sticky=N+W)\n self.lbl_phone = tk.Label(self.master, text='Phone Number:')\n self.lbl_phone.grid(row=4,column=0,padx=(30,0),pady=(10,0),sticky=N+W)\n self.lbl_email = tk.Label(self.master, text='Email Address:')\n self.lbl_email.grid(row=6,column=0,padx=(30,0),pady=(10,0),sticky=N+W)\n self.lbl_course = tk.Label(self.master, text='Current Course:')\n self.lbl_course.grid(row=8,column=0,padx=(30,0),pady=(10,0),sticky=N+W)\n self.lbl_student = tk.Label(self.master, text='Student Info:')\n self.lbl_student.grid(row=0,column=2,padx=(0,0),pady=(10,0),sticky=N+W)\n\n # Text Boxes\n # In OOP, we're creating an instance of what a class object can be, taking\n # tkinters diagram for an 'Entry', bringing it into reality, and then giving\n # that instance a name that we can access and call it, 'self.txt_fname'.\n self.txt_fname = tk.Entry(self.master,text='')\n self.txt_fname.grid(row=1,column=0,rowspan=1,columnspan=2,padx=(30,40),pady=(0,0),sticky=N+E+W)\n self.txt_lname = tk.Entry(self.master,text='')\n self.txt_lname.grid(row=3,column=0,rowspan=1,columnspan=2,padx=(30,40),pady=(0,0),sticky=N+E+W)\n self.txt_phone = tk.Entry(self.master,text='')\n self.txt_phone.grid(row=5,column=0,rowspan=1,columnspan=2,padx=(30,40),pady=(0,0),sticky=N+E+W)\n self.txt_email = tk.Entry(self.master,text='')\n self.txt_email.grid(row=7,column=0,rowspan=1,columnspan=2,padx=(30,40),pady=(0,0),sticky=N+E+W)\n self.txt_course = tk.Entry(self.master,text='')\n self.txt_course.grid(row=9,column=0,rowspan=1,columnspan=2,padx=(30,40),pady=(0,0),sticky=N+E+W)\n\n # List Box\n # Define a listbox with a scrollbar and grid them\n self.scrollbar1 = Scrollbar(self.master,orient=VERTICAL)\n self.lstList1 = Listbox(self.master,exportselection=0,yscrollcommand=self.scrollbar1.set)\n self.scrollbar1.config(command=self.lstList1.yview)\n self.scrollbar1.grid(row=1,column=5,rowspan=9,columnspan=1,padx=(0,0),pady=(0,0),sticky=N+E+S)\n self.lstList1.grid(row=1,column=2,rowspan=9,columnspan=3,padx=(0,0),pady=(0,0),sticky=N+E+S+W)\n\n #Buttons\n # When a user clicks on a button, we call the lambda function in the student_tracking_func\n # file that contains the instructions, and we pass in the key 'self'/ the class object.\n self.btn_submit = tk.Button(self.master,width=12,height=2,text='Submit',command=lambda: student_tracking_func.addToList(self))\n self.btn_submit.grid(row=9,column=0,padx=(30,0),pady=(45,10),sticky=W)\n self.btn_delete = tk.Button(self.master,width=25,height=2,text='Delete',command=lambda: student_tracking_func.onDelete(self))\n self.btn_delete.grid(row=10,column=4,padx=(15,0),pady=(15,10),sticky=E)\n\n # call to create the dB\n student_tracking_func.create_db(self)\n student_tracking_func.onRefresh(self)\n\n\n\n\nif __name__ == \"__main__\":\n pass\n \n","sub_path":"The_Tech_Academy_Python_Projects/Assignments/Student Tracking System App Assignment/student_tracking_gui.py","file_name":"student_tracking_gui.py","file_ext":"py","file_size_in_byte":3395,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"646406427","text":"#!/usr/bin/python3\n\nfrom flask import Flask, request\nfrom flask_restful import reqparse, abort, Api, Resource\nimport configparser\nimport logging\nimport atexit\nimport time\nimport daemon\nimport os\nfrom lockfile.pidlockfile import PIDLockFile\n\nfrom harvester.DBInterface import DBInterface\nfrom harvester.HarvestLogger import HarvestLogger\n\napp = Flask(__name__)\n\n# Disable the default logging, it will not work in daemon mode\napp.logger.disabled = True\nlog = logging.getLogger('werkzeug')\nlog.disabled = True\n\napi = Api(app)\n\nCACHE = {\"repositories\": {\"count\": 0, \"repositories\": [], \"timestamp\": 0}}\nCONFIG = {\"restapi\": None, \"db\": None, \"handles\": {}}\n\n\ndef get_log():\n if \"log\" not in CONFIG[\"handles\"]:\n CONFIG[\"handles\"][\"log\"] = HarvestLogger(CONFIG[\"restapi\"][\"logging\"])\n CONFIG[\"handles\"][\"log\"].info(\n \"Harvest REST API process starting on port {}\".format(CONFIG[\"restapi\"][\"api\"][\"listen_port\"]))\n return CONFIG[\"handles\"][\"log\"]\n\n\ndef get_db():\n if \"db\" not in CONFIG[\"handles\"]:\n CONFIG[\"handles\"][\"db\"] = DBInterface(CONFIG['db'])\n return CONFIG[\"handles\"][\"db\"]\n\n\ndef check_cache(objname):\n if objname in CACHE:\n if (int(time.time()) - CACHE[objname][\"timestamp\"] > int(CONFIG[\"restapi\"][\"api\"][\"max_cache_age\"])):\n get_log().debug(\"Cache expired for {}; reloading\".format(objname))\n if objname == \"repositories\":\n records = get_db().get_repositories()\n CACHE[\"repositories\"][\"repositories\"][:] = [] # Purge existing list\n for record in records:\n # Explicitly expose selected info here, so we do not accidentally leak internal data or something added in the future\n this_repo = {\n \"repository_id\": record[\"repository_id\"],\n \"repository_name\": record[\"repository_name\"],\n \"repository_url\": record[\"repository_url\"],\n \"homepage_url\": record[\"homepage_url\"],\n \"repository_thumbnail\": record[\"repository_thumbnail\"],\n \"repository_type\": record[\"repository_type\"],\n \"item_count\": record[\"item_count\"]\n }\n CACHE[\"repositories\"][\"repositories\"].append(this_repo)\n CACHE[\"repositories\"][\"count\"] = len(records)\n CACHE[\"repositories\"][\"timestamp\"] = int(time.time())\n\n\ndef log_shutdown():\n get_log().info(\"REST API process shutting down\")\n\n\ndef get_config_ini(config_file):\n c = configparser.ConfigParser()\n try:\n c.read(config_file)\n return c\n except:\n return None\n\n\n## API Methods\n\n# Shows a single repo\nclass Repo(Resource):\n def get(self, repo_id):\n repo_id = int(repo_id)\n get_log().debug(\"{} GET /repos/{}\".format(request.remote_addr, repo_id))\n check_cache(\"repositories\")\n for repo in CACHE[\"repositories\"][\"repositories\"]:\n if int(repo[\"repository_id\"]) == repo_id:\n return repo\n abort(404, message=\"Repo {} doesn't exist\".format(repo_id))\n\n\n# Shows a list of all repos\nclass RepoList(Resource):\n def get(self):\n get_log().debug(\"{} GET /repos\".format(request.remote_addr))\n check_cache(\"repositories\")\n return CACHE[\"repositories\"]\n\n\n# Default response\nclass Default(Resource):\n def get(self):\n get_log().debug(\"{} GET /\".format(request.remote_addr))\n return {}\n\n\n## API resource routing\n\napi.add_resource(RepoList, '/repos')\napi.add_resource(Repo, '/repos/')\napi.add_resource(Default, '/')\n\nif __name__ == '__main__':\n CONFIG[\"restapi\"] = get_config_ini(\"conf/restapi.conf\")\n CONFIG[\"db\"] = get_config_ini(\"conf/harvester.conf\")[\"db\"]\n\n with daemon.DaemonContext(pidfile=PIDLockFile(CONFIG[\"restapi\"][\"api\"][\"pidfile\"]), working_directory=os.getcwd()):\n atexit.register(log_shutdown)\n get_log()\n app.run(host='0.0.0.0', debug=False, port=int(CONFIG[\"restapi\"][\"api\"][\"listen_port\"]))\n","sub_path":"restapi.py","file_name":"restapi.py","file_ext":"py","file_size_in_byte":4066,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"61517921","text":"import giphy_client as gc\nfrom giphy_client.rest import ApiException\nimport requests\n\napi_instance = gc.DefaultApi()\napi_key=\"your api key\"\nterm=input(\"Enter the search query term:\")\nquery='@signwithrobert+{}'.format(term)\nfmt = 'gif'\nlimit=1\n\n\ndef giphy_search():\n try :\n response=api_instance.gifs_search_get(api_key,query,limit=1,fmt=fmt)\n gif_id = response.data[0]\n url_gif = gif_id.images.downsized.url\n except ApiException:\n print(\"Exception when calling DefaultApi->gifs_search_get: %s\\n\" % e)\n\n with open('test.gif','wb') as f:\n f.write(requests.get(url_gif).content)\n\n print(\"Done!\")\ngiphy_search()\n\n\n\n \n","sub_path":"src/prototypes/prototype2/giphy.py","file_name":"giphy.py","file_ext":"py","file_size_in_byte":663,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"6"} +{"seq_id":"174551619","text":"import tensorflow as tf\nimport numpy as np\nimport pandas as pd\nfrom DeepFM import DeepFM\nfrom sklearn.metrics import roc_auc_score\nimport os, sys\nimport argparse\nimport pickle\n\n\nparser = argparse.ArgumentParser(description='Run DeepFM')\nparser.add_argument('--dataset', type=str, nargs='?', default='berkeley0')\nparser.add_argument('--iter', type=int, nargs='?', default=50)\nparser.add_argument('--fm', type=bool, nargs='?', const=True, default=False)\nparser.add_argument('--deep', type=bool, nargs='?', const=True, default=False)\nparser.add_argument('--d', type=int, nargs='?', default=2)\nparser.add_argument('--nb_layers', type=int, nargs='?', default=4)\nparser.add_argument('--nb_neurons', type=int, nargs='?', default=50)\noptions = parser.parse_args()\n\n\nprint('Dataset', options.dataset)\n# os.chdir(os.path.join('data', options.dataset)) # Move to dataset folder\n\n\nwith open('berkeley0.pickle', 'rb') as f:\n Xi_train = pickle.load(f)\n Xv_train = pickle.load(f)\n y_train = pickle.load(f)\n Xi_test = pickle.load(f)\n Xv_test = pickle.load(f)\n y_test = pickle.load(f)\n\nnb_fields = len(Xi_train[0])\nprint(len(Xi_train), nb_fields, len(y_train), min(y_train), max(y_train))\ndata = np.array(Xv_train + Xv_test)\nprint('Interesting')\nprint(list(map(type, Xv_train[0])))\nprint(data.min(axis=0))\nprint(data.max(axis=0))\n\nnb_features = (1 + np.array(Xi_train + Xi_test).max(axis=0)).sum()\nprint(nb_features, 'features over', nb_fields, 'fields')\n\n# params\ndfm_params = {\n \"use_fm\": options.fm,\n \"use_deep\": options.deep,\n \"embedding_size\": options.d,\n \"dropout_fm\": [1.0, 1.0],\n \"deep_layers\": [options.nb_neurons] * options.nb_layers,\n \"dropout_deep\": [0.6] * (options.nb_layers + 1),\n \"deep_layers_activation\": tf.nn.relu,\n \"epoch\": options.iter,\n \"batch_size\": 1024,\n \"learning_rate\": 0.001,\n \"optimizer_type\": \"adam\",\n \"batch_norm\": 1,\n \"batch_norm_decay\": 0.995,\n \"l2_reg\": 0.01,\n \"verbose\": True,\n \"eval_metric\": roc_auc_score,\n \"random_seed\": 2017,\n 'feature_size': nb_features,\n 'field_size': nb_fields\n}\n\n# init a DeepFM model\ndfm = DeepFM(**dfm_params)\n\n# fit a DeepFM model\ndfm.fit(Xi_train, Xv_train, y_train, Xi_test, Xv_test, y_test)\n\n# evaluate a trained model\nauc_train = dfm.evaluate(Xi_train, Xv_train, y_train)\nauc_test = dfm.evaluate(Xi_test, Xv_test, y_test)\nprint('train auc={:f} test auc={:f}'.format(auc_train, auc_test))\n\n# make prediction on test\n# y_pred = dfm.predict(Xi_test, Xv_test)\n# with open('y_pred-{:.3f}-{:.3f}.txt'.format(auc_train, auc_valid), 'w') as f:\n# f.write('\\n'.join(map(str, y_pred)))\n","sub_path":"berkeley.py","file_name":"berkeley.py","file_ext":"py","file_size_in_byte":2605,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"6"} +{"seq_id":"25739009","text":"from decimal import Decimal\nimport json\nimport boto3\n\n\ndef load_users(users, dynamodb=None):\n if not dynamodb:\n dynamodb = boto3.resource('dynamodb', endpoint_url=\"http://localhost:8000\")\n\n table = dynamodb.Table('Users')\n for user in users:\n username = user['username']\n print(\"Adding user:\", username)\n table.put_item(Item=user)\n\n\nif __name__ == '__main__':\n with open(\"users.json\") as json_file:\n user_list = json.load(json_file, parse_float=Decimal)\n load_users(user_list)","sub_path":"no longer needed/load_users.py","file_name":"load_users.py","file_ext":"py","file_size_in_byte":526,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"6"} +{"seq_id":"270830179","text":"from __future__ import print_function\nimport unittest\nimport lsst.afw.geom as afwGeom\nimport lsst.utils.tests\nfrom helper import skyMapTestCase\n\ntry:\n import healpy\nexcept:\n healpy = None\n\nfrom lsst.skymap.healpixSkyMap import HealpixSkyMap\n\n\nclass HealpixTestCase(skyMapTestCase.SkyMapTestCase):\n\n def setUp(self):\n if not healpy:\n self.skipTest(\"Missing healpy dependency.\")\n\n self.config = HealpixSkyMap.ConfigClass()\n nside = 2**self.config.log2NSide\n self._NumTracts = healpy.nside2npix(nside) # Number of tracts to expect\n self._NeighborAngularSeparation = healpy.max_pixrad(\n nside) * afwGeom.radians # Expected tract separation\n self._SkyMapClass = HealpixSkyMap # Class of SkyMap to test\n self._SkyMapName = \"healpix\" # Name of SkyMap class to test\n self._numNeighbors = 1 # Number of neighbours\n\n def tearDown(self):\n if hasattr(self, \"config\"):\n del self.config\n\n\nclass MemoryTester(lsst.utils.tests.MemoryTestCase):\n pass\n\n\ndef setup_module(module):\n lsst.utils.tests.init()\n\n\nif __name__ == \"__main__\":\n lsst.utils.tests.init()\n unittest.main()\n","sub_path":"tests/test_healpixSkyMap.py","file_name":"test_healpixSkyMap.py","file_ext":"py","file_size_in_byte":1183,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"6"} +{"seq_id":"534295081","text":"import tkinter as tk\n\ndef processCheckbutton():\n print(\"check button is \" + (\"checked \" if v1.get() == 1 else \"unchecked\"))\n\ndef processRadiobutton():\n print((\"Red\" if v2.get() == 1 else \"Yellow\") + \" is selected \" )\n\ndef processButton():\n print(\"Your name is \" + name.get())\n\nwindow = tk.Tk()\nwindow.title(\"Widgets Demo\")\n\n#Window下的第一個Frame\n# Add a button, a check button, and a radio button to frame1\nframe1 = tk.Frame(window, bg = 'green') # Create and add a frame to window\nframe1.pack()\n\nv1 = tk.IntVar()\ncbtBold = tk.Checkbutton(frame1, text = \"Bold\", variable = v1, command = processCheckbutton) \nv2 = tk.IntVar()\nrbRed = tk.Radiobutton(frame1, text = \"Red\", bg = \"red\", variable = v2, value = 1, command = processRadiobutton) \nrbYellow = tk.Radiobutton(frame1, text = \"Yellow\", bg = \"yellow\", variable = v2, value = 2, command = processRadiobutton) \ncbtBold.grid(row = 1, column = 1)\nrbRed.grid(row = 1, column = 2)\nrbYellow.grid(row = 1, column = 3)\n\nseparator = tk.Frame(height = 2, bd = 1, relief = tk.SUNKEN).pack(fill = tk.X, padx = 5, pady = 5) #分隔線\n\n#Window下的第二個Frame\n# Add a button, a check button, and a radio button to frame1\nframe2 = tk.Frame(window, bg = 'pink') # Create and add a frame to window\nframe2.pack()\n\nlabel = tk.Label(frame2, text = \"Enter your name: \")\nname = tk.StringVar()\nentryName = tk.Entry(frame2, textvariable = name) \nbtGetName = tk.Button(frame2, text = \"Get Name\", command = processButton)\nmessage = tk.Message(frame2, text = \"It is a widgets demo\")\nlabel.grid(row = 1, column = 1)\nentryName.grid(row = 1, column = 2)\nbtGetName.grid(row = 1, column = 3)\nmessage.grid(row = 1, column = 4)\n\nseparator = tk.Frame(height = 2, bd = 1, relief = tk.SUNKEN).pack(fill = tk.X, padx = 5, pady = 5) #分隔線\n\n#Window下的Text\ntext1 = tk.Text(window)\ntext1.pack()\ntext1.insert(tk.END, \"\\n寫在Text中的文字1\")\ntext1.insert(tk.END, \"\\n寫在Text中的文字2\")\ntext1.insert(tk.END, \"\\n寫在Text中的文字3\")\ntext1.insert(tk.END, \"\\n寫在Text中的文字4\")\n\nwindow.mainloop()\n\n","sub_path":"_4.python/tkinter/tk_新進測試4_WidgetsDemo.py","file_name":"tk_新進測試4_WidgetsDemo.py","file_ext":"py","file_size_in_byte":2055,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"6"} +{"seq_id":"254180779","text":"#Leetcode problem Number 906\n#super pallindromes\n\nclass Solution(object):\n def superpalindromesInRange(self, L, R):\n \"\"\"\n :type L: str\n :type R: str\n :rtype: int\n \"\"\"\n p = generatePaldindromes(100)\n x = int(math.sqrt(int(L)))\n y = int(math.sqrt(int(R)))+1\n print(x,y)\n p = generatePaldindromes(y)\n ans = []\n for i in range(0,len(p)):\n if p[i]>=x:\n m = p[i]*p[i]\n if str(m)==str(m)[::-1]:\n ans.append(m)\n return len(ans)\n \n\n \ndef createPalindrome(inp, b, isOdd): \n n = inp \n palin = inp \n \n # checks if number of digits is odd or even \n # if odd then neglect the last digit of input in \n # finding reverse as in case of odd number of \n # digits middle element occur once \n if (isOdd): \n n = n / b \n \n # Creates palindrome by just appending reverse \n # of number to itself \n while (n > 0): \n palin = palin * b + (n % b) \n n = n / b \n return palin \n\n\n\ndef generatePaldindromes(n): \n ans = []\n # Run two times for odd and even length palindromes \n for j in range(2): \n # Creates palindrome numbers with first half as i. \n # Value of j decided whether we need an odd length \n # of even length palindrome. \n i = 1\n while (createPalindrome(i, 10, j % 2) < n): \n ans.append(createPalindrome(i, 10, j % 2)) \n i = i + 1\n return ans\n","sub_path":"superPallindrome.py","file_name":"superPallindrome.py","file_ext":"py","file_size_in_byte":1518,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"6"} +{"seq_id":"33116155","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\n# @Date: 2017/3/9\n# @Author: xmt\n\n\nSTR_FILE = '1.xml'\nSAVE_FILE_LIST = 'save.txt'\n\ndef is_chinese(uchar):\n \"\"\"判断一个unicode是否是汉字\"\"\"\n if uchar >= u'\\u4e00' and uchar <= u'\\u9fa5':\n return True\n else:\n return False\n\n\ndef save(values):\n # mystr = u'\\u591a'\n # mystr = mystr.encode('utf-8')\n mystr = values\n fp = open(SAVE_FILE_LIST, 'w')\n fp.write(mystr)\n fp.close()\n\n\ndef main():\n print('hello stat_chinese.py!')\n list_zh = []\n values = ''\n fp = open(STR_FILE, 'r')\n for line in fp:\n line = unicode(line, 'utf-8')\n # print(line)\n # print(type(line))\n # print(len(line))\n for uchar in line:\n # print(uchar)\n if is_chinese(uchar):\n # print(uchar)\n # print(type(uchar))\n # print(len(uchar))\n \"\"\" uchar = u'\\u591a',表示一个字符,长度为1 \"\"\"\n uchar = uchar.encode('utf-8')\n # list_zh.append(uchar)\n values += uchar\n fp.close()\n # print(len(list_zh))\n # print(str(list_zh))\n\n \n # for vaule in list_zh:\n # values += vaule\n print(values)\n save(values)\n\n # zhStr = ''\n # for zhChar in list_zh:\n # # print(zhChar)\n # zhStr += zhChar\n # print(zhStr)\n\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"06_python/02_tools/02_count_chinese/stat_chinese.py","file_name":"stat_chinese.py","file_ext":"py","file_size_in_byte":1416,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"6"} +{"seq_id":"101017327","text":"import os\nimport csv\nfrom flask import Flask, render_template, request, send_from_directory, redirect\n\napp = Flask(__name__)\n\n\n# Definiert Template für Startseite\n@app.route(\"/\")\ndef start():\n return render_template(\"index.html\")\n\n\n# weist den jeweiligen html Seiten eine URL zu\n@app.route(\"/\")\ndef html_page(page_name):\n return render_template(page_name)\n\n\n# Favicon\n@app.route(\"/favicon.ico\")\ndef favicon():\n return send_from_directory(os.path.join(app.root_path, \"static\"), \"desk_icon.ico\",\n mimetype='image/vnd.microsoft.icon')\n\n\n# Daten aus Kontakformular als Textdatei\ndef write_to_file(data):\n with open(\"database.txt\", mode=\"a\") as database:\n fullname = data[\"fullname\"]\n email = data[\"email\"]\n subject = data[\"subject\"]\n message = data[\"message\"]\n file = database.write(f\"\\n {fullname} {email}, {subject}, {message}\")\n\n\n# Daten aus Kontakformular in csv Datei\ndef write_to_csv(data):\n with open(\"database.csv\", newline=\"\", mode=\"a\") as database2:\n fullname = data[\"fullname\"]\n email = data[\"email\"]\n subject = data[\"subject\"]\n message = data[\"message\"]\n csv_writer = csv.writer(database2, delimiter=\";\", quotechar='\"', quoting=csv.QUOTE_MINIMAL)\n csv_writer.writerow([fullname, email, subject, message])\n\n\n# Kontaktformular abfrage\n@app.route('/submit_form', methods=['POST', 'GET'])\ndef submit_form():\n if request.method == \"POST\":\n data = request.form.to_dict()\n write_to_csv(data)\n return redirect(\"/thank_you.html\")\n else:\n return \"something went wrong\"\n","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":1642,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"6"} +{"seq_id":"235858663","text":"#coding=utf-8 \n# @Version : 1.0\n# @Time : 2019/03/11\n# @Author : YuepengWang\n# @File : 系统信息收集.py\n#\n# 此脚本为一个系统信息收集脚本\n\nimport time\nfrom sqlalchemy import create_engine\nimport pandas as pd\n\n\nengine = create_engine(\n str(r\"mysql+pymysql://%s:\" + '%s' + \"@%s/%s?charset=utf8\") % (\n 'admin', # mysql用户名\n '@WSX3edc', # mysql密码\n '192.168.132.2', # ip\n 'cmdb'), # 数据库名\n echo=True)\n\t\n\t\ndef insert_mysql():\n tmp_list = []\n cmd = 'hostname'\n Hostname = os.system(cmd)\n\n cmd1 = 'ip addr | grep \\'inet\\' | grep -v inet6 | grep -v 127.0.0.1 | awk -F/ \\'{print $1}\\'| awk \\'{print $2}\\''\n IP=os.system(cmd1)\n\n cmd2 = 'top -n 1|grep -v grep | grep \\'Cpu\\' | awk \\'{printf \"%.2f%\\n\", (100-$8)}\\''\n CPU = os.system(cmd2)\n\n cmd3 = 'free -h |grep Mem | awk \\'{printf \"%.2f%\\n\",($3/$2)*100}\\''\n Mem = os.system(cmd3)\n\n cmd4 = 'df -h | grep \\'/$\\' | awk \\'{print $5}\\''\n Disk = os.system(cmd4)\n\n cmd5 = 'netstat -an | awk \\'/^tcp/ {++S[$NF]} END {for(a in S) print a, S[a]}\\' | grep LISTEN | awk \\'{print $2}\\''\n TCP = os.system(cmd5)\n\n n1 = [Hostname, IP, CPU, Mem, Disk, TCP]\n tmp_list.append(n1)\n\n columns = ['Hostname', 'IP', 'CPU', 'Mem', 'Disk', 'TCP']\n df = pd.DataFrame(data=tmp_list, columns=columns)\n df.to_sql(name='Hostinfo', con=engine, if_exists='append', index=False)\n\n\nif __name__ == '__main__':\n start_time = time.time() # 计算程序开始时间\n insert_mysql()\n end_time = time.time() # 计算程序开始时间\n\n print(\"插入数据耗时:\", \"%.10fs\" % (end_time - start_time))","sub_path":"python学习训练/0 早期/系统信息收集.py","file_name":"系统信息收集.py","file_ext":"py","file_size_in_byte":1649,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"6"} +{"seq_id":"228561607","text":"from smap import driver, actuate\nfrom smap.util import periodicSequentialCall\n\nclass VirtualTemperature(driver.SmapDriver):\n def setup(self, opts):\n self.state = {'temperature': 0\n }\n self.readperiod = float(opts.get('ReadPeriod',.5))\n self.transition = float(opts.get('TransitionProb', 0.05))\n\n\n temperature = self.add_timeseries('/temperature', 'Temperature (C/F)',\n data_type='long')\n\n self.set_metadata('/', {'Metadata/Device': 'Temperature',\n 'Metadata/Model': 'Virtual Temperature',\n 'Metadata/Driver': __name__})\n\n temperature.add_actuator(SetpointActuator(device=self, path='temperature',\n _range=(0,1000)))\n\n metadata_type = [\n ('/temperature', 'Reading'),\n ('/temperature_act', 'Command')\n ]\n for ts, tstype in metadata_type:\n self.set_metadata(ts,{'Metadata/Type':tstype})\n\n def start(self):\n periodicSequentialCall(self.read).start(self.readperiod)\n\n def read(self):\n for k,v in self.state.iteritems():\n self.add('/'+k, v)\n\nclass VirtualTemperatureActuator(actuate.SmapActuator):\n def __init__(self, **opts):\n self.device = opts.get('device')\n self.path = opts.get('path')\n\n def get_state(self, request):\n return self.device.state[self.path]\n\nclass OnOffActuator(VirtualTemperatureActuator, actuate.BinaryActuator):\n def __init__(self, **opts):\n actuate.BinaryActuator.__init__(self)\n VirtualTemperatureActuator.__init__(self, **opts)\n\n def set_state(self, request, state):\n self.device.state[self.path] = int(state)\n return self.device.state[self.path]\n\nclass SetpointActuator(VirtualTemperatureActuator, actuate.ContinuousIntegerActuator):\n def __init__(self, **opts):\n actuate.ContinuousIntegerActuator.__init__(self, opts['_range'])\n VirtualTemperatureActuator.__init__(self, **opts)\n\n def set_state(self, request, state):\n self.device.state[self.path] = int(state)\n return self.device.state[self.path]\n\n\n","sub_path":"python/smap/drivers/simulation/virtualtemperature.py","file_name":"virtualtemperature.py","file_ext":"py","file_size_in_byte":2165,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"614981629","text":"import tkinter as tk\nfrom guisettings import *\n\n\nclass MaximalOutsideTemperatureWidget(tk.Frame):\n def __init__(self, root, *args, **kwargs):\n tk.Frame.__init__(self, root, *args, **kwargs)\n \n self.root = root\n self.Max = str(6)\n\n \n self.maximalOutsideTemperature = tk.Label(self, text=\"Max: \" + self.Max + \"°\", font = ('arial', LABEL_FONT_SIZE, 'bold'), background = \"#\" + BACKGROUND)\n self.maximalOutsideTemperature.grid() ","sub_path":"maximaloutsidetemperature.py","file_name":"maximaloutsidetemperature.py","file_ext":"py","file_size_in_byte":481,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"615253023","text":"import random\r\nimport nltk\r\nfrom PyQt4 import QtCore\r\n\r\n\r\nclass SentimentTesting():\r\n def __init__(self, training_object, analysed_file_path, corpus_feature_file_path, emitter):\r\n\r\n self.test_data = []\r\n self.corpus_features = []\r\n self.training_obj = training_object\r\n self.signal_emitter = emitter\r\n self.training_obj.open_trained_materials()\r\n\r\n self.training_obj.create_featuresets()\r\n self.training_obj.train_test_classifier(signal_emitter=self.signal_emitter)\r\n self.to_be_sentiment_analysed = analysed_file_path\r\n self.corpus_features_file_path = corpus_feature_file_path\r\n\r\n # import data and features\r\n def import_data(self):\r\n # import raw data\r\n self.file_content = open(self.to_be_sentiment_analysed).read()\r\n sentences = nltk.sent_tokenize(self.file_content)\r\n\r\n # import corpus features\r\n f = open(self.corpus_features_file_path, \"r\")\r\n feature_list = f.read().split(\"\\n\")\r\n self.corpus_features = feature_list\r\n f.close()\r\n\r\n # extract sentences with corpus features only\r\n for feature in self.corpus_features:\r\n for sentence in sentences:\r\n if feature in sentence:\r\n self.test_data.append(sentence)\r\n self.test_data = list(set(self.test_data))\r\n random.shuffle(self.test_data)\r\n\r\n\r\n # calculate feature sentiments\r\n def feature_sentiment(self, feature):\r\n feature_dictionary_with_sentiment = dict()\r\n feature_pos = 0\r\n feature_neg = 0\r\n feature_neutral = 0\r\n counter = 0\r\n\r\n for i in range(len(self.test_data)):\r\n if feature in self.test_data[i]:\r\n # print self.test_data[i]\r\n result = self.training_obj.sentiment(self.test_data[i])\r\n # print result\r\n if result[0] == 'pos' and result[1] >= 0.6:\r\n feature_pos += 1\r\n counter += 1\r\n elif result[0] == 'neg' and result[1] >= 0.6:\r\n feature_neg += 1\r\n counter += 1\r\n\r\n if counter == 0:\r\n return\r\n pospercent = round((float(feature_pos) / counter) * 100, 2)\r\n negpercent = round((float(feature_neg) / counter) * 100, 2)\r\n #neautralpercent = round((float(feature_neutral) / counter) * 100, 2)\r\n\r\n self.signal_emitter.emit(QtCore.SIGNAL(\"analysis_signal\"), feature, pospercent, negpercent)\r\n print(feature, \":--- \\t\\t\", \"Positive: \", pospercent, \"%, Negative: \\t\", negpercent, \"%\")\r\n\r\n # detemines the polarity and confidence of each review\r\n def test_run(self):\r\n for i in range(len(self.test_data)):\r\n print(self.test_data[i])\r\n print(self.training_obj.sentiment(self.test_data[i]))\r\n print(\"... ... ...\")\r\n\r\n # determines the sentiment of each feature\r\n def feature_based_sentiment_analysis(self):\r\n for feature in self.corpus_features:\r\n self.feature_sentiment(feature)\r\n","sub_path":"sentiment_analysis/testing_module.py","file_name":"testing_module.py","file_ext":"py","file_size_in_byte":3069,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"638930360","text":"# -*- coding: utf-8 -*-\n#################################################################################\n#\n# Copyright (c) 2016-Present Webkul Software Pvt. Ltd. ()\n#\n#################################################################################\n\nimport xmlrpclib\nfrom openerp.osv import fields, osv\nfrom openerp.tools.translate import _\n\n\t\nclass supplier_wizard(osv.osv_memory):\n\t_name = \"supplier.wizard\"\n\n\t_columns = {\n\t\t'supplier_token_key':fields.char('Supplier Token Key')\t\t\t\n\t}\n\n\tdef buttun_validate(self, cr, uid, ids, context=None):\n\t\tstatus = 'Supplier Connection Un-successful'\n\t\ttext = 'Test connection Un-successful please check the supplier api credentials!!!'\n\t\tcontext = dict(context or {})\n\t\tif context.has_key('active_id'):\n\t\t\tif ids:\n\t\t\t\tconfig_obj = self.pool.get('supplier.configure').browse(cr, uid, context['active_id'], context)\n\t\t\t\twizard_obj = self.browse(cr, uid, ids[0], context)\n\t\t\t\tsupplier_obj = xmlrpclib.ServerProxy(config_obj.url+'/xmlrpc/object')\n\t\t\t\tvalidate = supplier_obj.execute(config_obj.db, config_obj.supplier_uid, config_obj.pwd, 'vendor.configure', 'search', [('token_key','=', wizard_obj.supplier_token_key)])\n\t\t\t\tif not validate:\n\t\t\t\t\tself.pool.get('supplier.configure').write(cr, uid, context['active_id'], {'supplier_uid':False, 'validate':False}, context)\n\t\t\t\telse:\n\t\t\t\t\tself.pool.get('supplier.configure').write(cr, uid, context['active_id'], {'validate':True}, context)\n\t\t\t\t\ttext = \"Test Connection with supplier is successful\"\n\t\t\t\t\tstatus = \"Congratulation, It's Successfully Connected with Supplier Api.\"\n\t\t\n\t\t\tself.pool.get('supplier.configure').write(cr, uid, context['active_id'], {'status':status})\t\t\n\t\tpartial = self.pool.get('message.wizard').create(cr, uid, {'text':text})\n\t\treturn { 'name': (\"Information\"),\n\t\t\t\t 'view_mode': 'form',\n\t\t\t\t 'view_type': 'form',\n\t\t\t\t 'res_model': 'message.wizard',\n\t\t\t\t 'view_id': False,\n\t\t\t\t 'res_id': partial,\n\t\t\t\t 'type': 'ir.actions.act_window',\n\t\t\t\t 'nodestroy': True,\n\t\t\t\t 'target': 'new',\n\t\t\t }\n\n\t\t\n","sub_path":"magento/vendortosupplier/wizard/supplier_wizard.py","file_name":"supplier_wizard.py","file_ext":"py","file_size_in_byte":2027,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"16816419","text":"#! /usr/bin/env python3\n\n# Problem 30 - Digit fifth powers\n#\n# Surprisingly there are only three numbers that can be written as the sum\n# of fourth powers of their digits:\n#\n# 1634 = 1^4 + 6^4 + 3^4 + 4^4\n# 8208 = 8^4 + 2^4 + 0^4 + 8^4\n# 9474 = 9^4 + 4^4 + 7^4 + 4^4\n#\n# As 1 = 14 is not a sum it is not included.\n#\n# The sum of these numbers is 1634 + 8208 + 9474 = 19316.\n#\n# Find the sum of all the numbers that can be written as the sum of fifth\n# powers of their digits.\n\nimport unittest\n\nfrom util import *\n\ndef sumOfPowers(power, limit):\n for n in range(2, limit + 1):\n m = sum([d ** power for d in intToSeq(n)])\n if n == m:\n yield n\n\nclass Test(unittest.TestCase):\n def test_problem030(self):\n self.assertEqual(sum(sumOfPowers(4, 10000)), 19316)\n self.assertEqual(sum(sumOfPowers(5, 200000)), 443839)\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"problem030.py","file_name":"problem030.py","file_ext":"py","file_size_in_byte":902,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"609127359","text":"#run entire simulation in one go!!!\n#this code is called by app.py, primarilly it calls initparam.py which sets directories up and then runs each run.py file created\nimport sys \nimport imp\nfrom numpy import *\nimport os\nimport subprocess\nimport pdb\n\n###primary running directory\n#pathname='/Users/suresh/Source/wifis_simulator/' #string\n#pathname='/home/miranda/files/GitHub_files/wifis_simulator/' #for miranda's computer ;)\npathname='/Users/miranda/Public/wifis_simulator/'\n\n##make change current path to run_files directory (needed to run initparam.py\npath=os.path.abspath(pathname+'run_files/')\nsys.path.append(path)\n\n#read in system variables provided from app.py, stored for now as strings in sys.argv\n\n###sort into sets for ease of pushing to initparam.py, each set has one variable which has the name of each parameter and one which has the calue of each parameter as a string\n###if multiple values given for a parameter it is given as a string with commas seperating different entries, split this string into list (in this case have lists as entries in list)\n\n#denotes which files to save\nsavename=['SAVE_OBJCUBE','SAVE_PSFCUBE','SAVE_IND']\nsavestuff=[(sys.argv[1]),(sys.argv[2]),(sys.argv[3])]\n\n#denotes basic properties of observation\nbasicname=['INT_SKY','INT_SCI','NFRAMES_SCI','NFRAMES_SKY']\nbasicstuff=[(sys.argv[5]).split(','),(sys.argv[6]).split(','),(sys.argv[7]).split(','),(sys.argv[8]).split(',')]\n\n#denotes properties of objects to observe\nobjectstuff=[(sys.argv[10]).split(','),(sys.argv[11]).split(','),(sys.argv[12]).split(','),(sys.argv[13]).split(','),(sys.argv[14]).split(','),(sys.argv[15]).split(','),(sys.argv[16]).split(','),(sys.argv[17]).split(','),(sys.argv[18]).split(','),(sys.argv[19]).split(','),(sys.argv[20]).split(','),(sys.argv[21]).split(',')]\nobjectname=['MJ','SPEC','LABEL','TYPE','v1_1','v1_2','v4','v5','v6','v7','v9','v10']\n\n\n\ndirectory=sys.argv[4] #this one isn't in a grouping\npsffwhm=(sys.argv[9]).split(',') #neither is this\n\n#*************all values still strings***************\n\n#calculate how many runs will result from parameters given\nnruns=len(basicstuff[0])*len(basicstuff[1])*len(basicstuff[2])*len(basicstuff[3])\n\n#import initparam.py\nimport initparam\n#run initparam, piping the necissary variables\ninitparam.constructParam(pathname+'basis_top.param',directory,nruns,psffwhm,objectstuff,basicstuff,objectname,basicname,savestuff,savename) ##will need to take in the directory name as well will also need to work out how many runs from user input, how many psf's too? maybe later don't want to write psf.param files so how to figure out how many times to do it with what values\n\n##open the progress log\nlog=open(pathname+'runs/'+directory+'/supplements/progress', \"a\")\n###run run.script, does all the runs set up by initparam)\nsubprocess.call([pathname+'runs/'+directory+'/run.script'],shell=1,executable='/bin/bash')\n\n\n#delete files that we don't want to pass to the user (python codes, parameter files, run script . . .)\n#subprocess.Popen(['find '+pathname+directory+'/ -type f \\( -name \"*.param\" -o -name \"*.py\" -o -name \"*.script\" -o -name \"*.paramc\" \\) -delete'],shell=1,executable='/bin/bash')\n\n#change active path out of run_files\npath=os.path.abspath(pathname+'/')\nsys.path.append(path)\n\n#make results directory\n\nos.makedirs('../runs/'+directory+'/results')\n\n\nsubprocess.Popen(['find '+pathname+'runs/'+directory+' -name \\'sky_*.fits\\' -exec cp {} '+pathname+'runs/'+directory+'/results \\\\;'],shell=1,executable='/bin/bash')\n\n\n#do analysis and save images\n#go to right dir\npath=os.path.abspath(pathname+'analysis/')\nsys.path.append(path)\n#import code\nfrom analysis import *\n\n#do it\ndoAnalysis(pathname+'runs/',directory,nruns)\n\n#tar the directory that the simulations were in so the user can download it\nsubprocess.call(['tar','-cvf',pathname+'runs/'+directory+'/'+directory+'.tar', '../runs/'+directory+'/results/'])\n\n#write done message to progress log\nlog.write('All Simulations Complete, files now available for download')\n\n\n\n","sub_path":"execute_sim.py","file_name":"execute_sim.py","file_ext":"py","file_size_in_byte":3998,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"412206194","text":"'''\n• Complexity:\n\t○ O(mn); O(mn)\n• Topics\n\t○ dp\n• Related\n\t○ LC85 Maximal Rectangle\n\t○ LC363 Max Sum of Rectangle No Larger Than K\nbrutal force complexity为O((mn)^2),需要找到所有的squares\ndp: invaraint是:每个tile记录以该tile为右下角的square中最长的边长。所以每个tile可通过\ncheck上面,左边和左上3个tile即可确认本tile的大小 min(up, left, upperleft) + 1\n'''\nclass Solution:\n def maximalSquare(self, matrix: List[List[str]]) -> int:\n if not matrix or not matrix[0]: return 0\n \n m, n = len(matrix), len(matrix[0])\n dp = []\n for i in range(m + 1):\n dp.append([0] * (n + 1))\n \n max_ = 0\n for i in range(1, m + 1):\n for j in range(1 , n + 1):\n if matrix[i - 1][j - 1] == \"1\":\n dp[i][j] = min(dp[i - 1][j], dp[i][j - 1], dp[i - 1][j - 1]) + 1\n if dp[i][j] > max_: max_ = dp[i][j]\n return max_ ** 2","sub_path":"leetcode/221_maximal_square.py","file_name":"221_maximal_square.py","file_ext":"py","file_size_in_byte":1000,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"585904601","text":"from django.db import models\nfrom django.conf import settings\nfrom django.contrib.auth.models import User\nfrom django.contrib.gis.db import models as geomodels\nfrom django.contrib.postgres.fields import JSONField, ArrayField\nfrom django.urls import reverse\nfrom djgeojson.fields import PolygonField\n\n\nclass Country(models.Model):\n tgnid = models.IntegerField('Getty TGN id',blank=True, null=True)\n tgnlabel = models.CharField('Getty TGN preferred name',max_length=255, blank=True, null=True)\n iso = models.CharField('2-character code',max_length=2)\n gnlabel = models.CharField('geonames label',max_length=255)\n geonameid = models.IntegerField('geonames id')\n un = models.CharField('UN name',max_length = 3, blank=True, null=True)\n variants = models.CharField(max_length=512, blank=True, null=True)\n \n mpoly = geomodels.MultiPolygonField()\n \n def __str__(self):\n return self.gnlabel\n\n class Meta:\n managed = True\n db_table = 'countries'\n\n\n# user-created study area to constrain reconciliation\nclass Area(models.Model):\n # id (pk) auto-maintained, per Django\n owner = models.ForeignKey(settings.AUTH_USER_MODEL,\n related_name='areas', on_delete=models.CASCADE)\n type = models.CharField(max_length=20)\n title = models.CharField(max_length=255)\n description = models.CharField(max_length=2044)\n ccodes = ArrayField(models.CharField(max_length=2),blank=True, null=True)\n # geom = geomodels.MultiPolygonField(blank=True, null=True)\n geojson = JSONField(blank=True, null=True)\n created = models.DateTimeField(auto_now_add=True)\n # updated = models.DateTimeField(null=True, auto_now_add=True)\n\n def __str__(self):\n return str(self.id)\n\n def get_absolute_url(self):\n return reverse('areas:area-update', kwargs={'id': self.id})\n\n class Meta:\n managed = True\n db_table = 'areas'\n indexes = [\n # models.Index(fields=['', '']),\n ]\n","sub_path":"areas/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1974,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"251132990","text":"################################\r\n# #\r\n# Download doodles from google #\r\n# #\r\n################################\r\n\r\nfrom urllib.request import urlopen\r\nimport json\r\n\r\nyear = input(\"輸入年份: \")\r\n\r\nfor mouth in range(1, 13):\r\n url = \"https://www.google.com/doodles/json/\" + year + \"/\" + str(mouth) + \"?hl=zh_TW\"\r\n print(url)\r\n response = urlopen(url)\r\n doodles = json.load(response)\r\n for doodle in doodles:\r\n img_url = \"https:\" + doodle['url']\r\n print(img_url)\r\n response = urlopen(img_url)\r\n img = response.read()\r\n file_name = \"result/\" + img_url.split(\"/\")[-1]\r\n f = open(file_name, \"wb\")\r\n f.write(img)\r\n f.close()\r\n","sub_path":"20180506/main2.py","file_name":"main2.py","file_ext":"py","file_size_in_byte":751,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"6"} +{"seq_id":"391123408","text":"###############################################################################\r\n# AoC_2-1.py\r\n# 2019-12-03\r\n# Mike Quigley\r\n#\r\n# For description, see https://adventofcode.com/2019/day/2\r\n# Basically, it simulates a small computer. So far, there are 3 opcodes,\r\n# and each opcode takes 3 arguments, so each instruction takes 4 units of\r\n# memory. All arguments are memory addresses, which are sequential from 0\r\n#\r\n# Instruction Set:\r\n# 1: ADD a b dest: Adds a + b, stores result in dest\r\n# 2: MUL a b dest: As above, but multiplies instead of adds\r\n# 99: HALT\r\n#\r\n# Any opcode not in the list should throw an error and halt\r\n###############################################################################\r\n\r\nram = []\r\n\r\ndef list():\r\n for i in range(0,len(ram),4):\r\n print(i, ':', ram[i:i+4])\r\n\r\ndef init(n):\r\n for i in range(0,n):\r\n ram.append(0)\r\n\r\ndef load(program):\r\n pL = program.split(',')\r\n for i in range(0,len(pL)):\r\n ram[i] = int(pL[i])\r\n\r\ndef run():\r\n for i in range(0, len(ram), 4):\r\n if ram[i] == 1:\r\n ram[ram[i+3]] = ram[ram[i+1]] + ram[ram[i+2]]\r\n elif ram[i] == 2:\r\n ram[ram[i+3]] = ram[ram[i+1]] * ram[ram[i+2]]\r\n elif ram[i] == 99:\r\n print(\"END\")\r\n return\r\n else:\r\n print(\"ERROR UNKNOWN OPCODE\", ram[i], \"AT ADDR\", i)\r\n return\r\n\r\ninit(128)\r\ninp = \"Input String\"\r\nwhile inp != \"EXIT\":\r\n inp = input(\"> \")\r\n if inp == \"LIST\":\r\n list()\r\n elif inp == \"LOAD\":\r\n load(input(\"PROGRAM: \"))\r\n elif inp == \"RUN\":\r\n run()\r\n","sub_path":"AoC_2-1.py","file_name":"AoC_2-1.py","file_ext":"py","file_size_in_byte":1593,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"6"} +{"seq_id":"322893396","text":"print('starting')\nimport numpy as np\nimport pandas as pd\n# from sklearn.cluster import DBSCAN\n# import pylab as plt\nimport warnings\nfrom scipy.stats import multivariate_normal\nimport itertools\n\npd.set_option(\"display.max_columns\",1000) # don’t put … instead of multi columns\npd.set_option('expand_frame_repr',False) # for not wrapping columns if you have many\npd.set_option(\"display.max_rows\",8)\npd.set_option('display.max_colwidth',1000)\n\nprint('done imports')\n\nif __name__ == '__main__':\n import sys, os\n sys.path.append('../../')\n# sys.path.append(r'C:\\Users\\lisrael1\\Documents\\myThings\\lior_docs\\HU\\thesis\\quants\\code\\results\\modulo_vs_naive_2/')\n root_folder = os.path.realpath(__file__).replace('\\\\', '/').rsplit('modulo_vs_naive_2', 1)[0]+'/modulo_vs_naive_2/'\n sys.path.append(root_folder)\n # from int_force.rand_data import rand_data\n plot=True\n\n import int_force\n for i in range(10):\n print('*'*150)\n\n cov=np.mat([[0, 0],[0, 1]])\n cov=np.mat([[1, 1],[1, 1.2]])\n cov=np.mat([[0.53749846, 0.35644121],[0.35644121, 0.23651739]])\n cov=int_force.rand_data.rand_data.rand_cov(snr=10000)\n\n number_of_bins=401\n mod_size=1.8\n samples=1000\n quant_size=mod_size/number_of_bins\n snr=100000\n res=int_force.methods.ml_modulo.ml_map_method(samples, quant_size, number_of_bins, snr=snr, plot=False)\n print(res)\n\n # shifts=int_force.methods.ml_modulo.ml_map(cov, number_of_bins, mod_size, number_of_modulos=5, plots=plot)\n #\n # data=int_force.rand_data.rand_data.random_data(cov, 1000)\n # tmp=int_force.methods.methods.sign_mod(data, mod_size)\n # recovered=int_force.methods.methods.to_codebook(tmp, mod_size/number_of_bins)\n # recovered=int_force.methods.methods.from_codebook(recovered, mod_size/number_of_bins)\n # shifts.index.names=['X','Y']\n # shifts=shifts.reset_index(drop=False)\n # shifts=shifts.sort_values(['X', 'Y']).round(8)\n # recovered=recovered.sort_values(['X', 'Y']).round(8)\n # recovered=pd.merge(recovered, shifts, on=['X', 'Y'], how='left')\n # recovered['new_x']=recovered.X+recovered.x_shift*mod_size\n # recovered['new_y']=recovered.Y+recovered.y_shift*mod_size\n # recovered=recovered[['new_x', 'new_y']]\n #\n # recovered.columns=[['recovered']*2, ['X', 'Y']]\n # tmp.columns=[['after']*2, ['X', 'Y']]\n # data.columns=[['before']*2, ['X', 'Y']]\n #\n # data=data.join(tmp).join(recovered)\n # data=data.stack(0).reset_index(drop=False)\n #\n # if plot:\n # import plotly as py\n # import cufflinks\n # fig=data.figure(kind='scatter', x='X', y='Y', categories='level_1', size=4)\n # py.offline.plot(fig, auto_open=True, filename='data.html')\n\n\n\n","sub_path":"code/results/modulo_vs_naive_2/int_force/playground/ml_map.py","file_name":"ml_map.py","file_ext":"py","file_size_in_byte":2868,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"6"} +{"seq_id":"372635968","text":"import pandas as pd\nfrom hsm.society import *\nfrom hsm.models import *\nfrom hsm.maintenance import *\n\n# Script for Society and ResPartner Details.\ndata = pd.read_excel(r'C:\\Users\\lenovo\\Downloads\\Society Full Details.xlsx', sheet_name='Sheet1')\n\nsociety_col1 = pd.DataFrame(data, columns=['Name']) # SocietyDetails\nsociety_col2 = pd.DataFrame(data, columns=['RegistrationNo']) # SocietyDetails\nsociety_col3 = pd.DataFrame(data, columns=['Wings']) # SocietyDetails\nsociety_col4 = pd.DataFrame(data, columns=['Street1']) # PartnerDetails\nsociety_col5 = pd.DataFrame(data, columns=['Street2']) # PartnerDetails\nsociety_col6 = pd.DataFrame(data, columns=['City']) # PartnerDetails\nsociety_col7 = pd.DataFrame(data, columns=['Zipcode']) # PartnerDetails\nsociety_col8 = pd.DataFrame(data, columns=['MobileNo']) # PartnerDetails\nsociety_col9 = pd.DataFrame(data, columns=['AltMobileNo']) # PartnerDetails\nsociety_col10 = pd.DataFrame(data, columns=['Emailid']) # PartnerDetails\nsociety_col11 = pd.DataFrame(data, columns=['State'])\nsociety_col12 = pd.DataFrame(data, columns=['Country'])\n\nname = dict(society_col1.Name) # SocietyDetails\nrno = dict(society_col2.RegistrationNo) # SocietyDetails\nwings = dict(society_col3.Wings) # SocietyDetails\nst1 = dict(society_col4.Street1) # PartnerDetails\nst2 = dict(society_col5.Street2) # PartnerDetails\ncity = dict(society_col6.City) # PartnerDetails\nzip_code = dict(society_col7.Zipcode) # PartnerDetails\nmobile_no = dict(society_col8.MobileNo) # PartnerDetails\nalt_mobile_no = dict(society_col9.AltMobileNo) # PartnerDetails\nemail_id = dict(society_col10.Emailid) # PartnerDetails\nstate = dict(society_col11.State)\ncountry = dict(society_col12.Country)\n\n# for SocietyDetails\nfor i in range(len(name)):\n Soc_details1 = ResSociety(name=name[i], registration_number=rno[i]).save()\n # for Respartner data.\n ResCountry.objects.get_or_create(name=country[i])\n country_name = ResCountry.objects.get(name=country[i]) # getting country for allocation in state and partner\n ResState.objects.get_or_create(name=state[i], country=country_name)\n state_name = ResState.objects.get(name=state[i]) # getting state for allocation in partner\n partner_details = ResPartner.objects.filter(name=name[i]).update(street1=st1[i], street2=st2[i], city=city[i],\n zip_code=zip_code[i], mobile_no=mobile_no[i],\n alt_mobile_no=alt_mobile_no[i], email=email_id[i],\n state=state_name, country=country_name)\n # for wings,state,country data.\n for j in wings[i].split(','):\n wing_name = ResWing.objects.get_or_create(name=j)\n\n# Script for Society Flats\nflat_data = pd.read_excel(r'C:\\Users\\lenovo\\Downloads\\Society Flat Details.xlsx', sheet_name='Sheet1')\nflat_col1 = pd.DataFrame(flat_data, columns=['FlatNo'])\nflat_col2 = pd.DataFrame(flat_data, columns=['WingName'])\nflat_col3 = pd.DataFrame(flat_data, columns=['FlatArea_sqft'])\nflat_col4 = pd.DataFrame(flat_data, columns=['RegistrationNumber'])\nflat_col5 = pd.DataFrame(flat_data, columns=['RegistrationDate_yyyy_mm_dd'])\nflat_col6 = pd.DataFrame(flat_data, columns=['Allocated_YES_or_NO'])\nflat_col7 = pd.DataFrame(flat_data, columns=['Society'])\nflat_col8 = pd.DataFrame(flat_data, columns=['FlatOwner'])\nflat_col9 = pd.DataFrame(flat_data, columns=['FlatRenter'])\n\nflat_no = dict(flat_col1.FlatNo)\nflat_wing_names = dict(flat_col2.WingName)\nflat_area = dict(flat_col3.FlatArea_sqft)\nflat_registration_no = dict(flat_col4.RegistrationNumber)\nflat_registration_date = dict(flat_col5.RegistrationDate_yyyy_mm_dd)\nflat_allocated = dict(flat_col6.Allocated_YES_or_NO)\nflat_society = dict(flat_col7.Society)\nflat_owner = dict(flat_col8.FlatOwner)\nflat_renter = dict(flat_col9.FlatRenter)\n\nfor i in range(len(flat_no)):\n society_name = ResSociety.objects.get(name=flat_society[i])\n flat_wing_name = ResWing.objects.get(name=flat_wing_names[i])\n Flat_detail = ResFlat(number=flat_no[i], area=flat_area[i], registration_number=flat_registration_no[i],\n registration_date=flat_registration_date[i], society=society_name, wing=flat_wing_name).save()\n\n# # Script for Maintainance\n# Maintenance_data = pd.read_excel(r'C:\\Users\\lenovo\\Downloads\\MaintainanceDetails.xlsx', sheet_name='Sheet1')\n# # print(Maintenance_data)\n# Maintenance_col1 = pd.DataFrame(Maintenance_data, columns=['Name'])\n# Maintenance_col2 = pd.DataFrame(Maintenance_data, columns=['Description'])\n# Maintenance_col3 = pd.DataFrame(Maintenance_data, columns=['Society'])\n# Maintenance_col4 = pd.DataFrame(Maintenance_data, columns=['Cost_Rs'])\n#\n# maintenance_name = dict(Maintenance_col1.Name)\n# maintenance_description = dict(Maintenance_col2.Description)\n# maintenance_society_name = dict(Maintenance_col3.Society)\n# maintenance_cost = dict(Maintenance_col4.Cost_Rs)\n#\n# for i in range(len(maintenance_name)):\n# Maintenance_detail = Maintenance(name=maintenance_name[i], description=maintenance_description[i]).save()\n# maintenance_type = Maintenance.objects.get(name=maintenance_name[i])\n# maintenance_society_names = ResSociety.objects.get(name=maintenance_society_name[i])\n# MaintenanceLines(society=maintenance_society_names, maintenance_type=maintenance_type,\n# cost=maintenance_cost[i]).save()\n","sub_path":"housing_society_management/excel_data_to_model.py","file_name":"excel_data_to_model.py","file_ext":"py","file_size_in_byte":5451,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"6"} +{"seq_id":"42715200","text":"import importlib\nimport argparse\nimport tensorflow as tf\n\ndef build_parser():\n parser = argparse.ArgumentParser()\n # prefix arguments with `--m-`\n parser.add_argument('--m-fc-width', dest='fc_width', type=int, default=128)\n parser.add_argument('--m-activation', dest='activation', default='relu')\n\n return parser\n\n\ndef build_model(images, fc_width, activation):\n activation_fn = getattr(tf.nn, activation)\n\n net = images\n\n net = tf.contrib.layers.flatten(net)\n\n net = tf.contrib.layers.fully_connected(\n inputs=net,\n num_outputs=fc_width,\n activation_fn=activation_fn,\n biases_initializer=tf.zeros_initializer(),\n weights_initializer=tf.contrib.layers.xavier_initializer(),\n scope='fc1',\n )\n\n net = tf.contrib.layers.fully_connected(\n inputs=net,\n num_outputs=10,\n activation_fn=None,\n biases_initializer=tf.zeros_initializer(),\n weights_initializer=tf.contrib.layers.xavier_initializer(),\n scope='fc2',\n )\n\n return net\n","sub_path":"models/fc2.py","file_name":"fc2.py","file_ext":"py","file_size_in_byte":1043,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"6"} +{"seq_id":"335937895","text":"#!/usr/bin/env python3\n\n# Copyright (C) 2017-2020 The btclib developers\n#\n# This file is part of btclib. It is subject to the license terms in the\n# LICENSE file found in the top-level directory of this distribution.\n#\n# No part of btclib including this file, may be copied, modified, propagated,\n# or distributed except according to the terms contained in the LICENSE file.\n\n\"\"\"SEC compressed/uncompressed point representation.\"\"\"\n\nfrom .alias import Octets, Point\nfrom .curve import Curve, secp256k1\nfrom .exceptions import BTClibValueError\nfrom .utils import bytes_from_octets, hex_string\n\n\ndef bytes_from_point(Q: Point, ec: Curve = secp256k1, compressed: bool = True) -> bytes:\n \"\"\"Return a point as compressed/uncompressed octet sequence.\n\n Return a point as compressed (0x02, 0x03) or uncompressed (0x04)\n octet sequence, according to SEC 1 v.2, section 2.3.3.\n \"\"\"\n\n # check that Q is a point and that is on curve\n ec.require_on_curve(Q)\n\n if Q[1] == 0: # infinity point in affine coordinates\n raise BTClibValueError(\"no bytes representation for infinity point\")\n\n bPx = Q[0].to_bytes(ec.psize, byteorder=\"big\")\n if compressed:\n return (b\"\\x03\" if (Q[1] & 1) else b\"\\x02\") + bPx\n\n return b\"\\x04\" + bPx + Q[1].to_bytes(ec.psize, byteorder=\"big\")\n\n\ndef point_from_octets(pubkey: Octets, ec: Curve = secp256k1) -> Point:\n \"\"\"Return a tuple (x_Q, y_Q) that belongs to the curve.\n\n Return a tuple (x_Q, y_Q) that belongs to the curve according to\n SEC 1 v.2, section 2.3.4.\n \"\"\"\n\n pubkey = bytes_from_octets(pubkey, (ec.psize + 1, 2 * ec.psize + 1))\n\n bsize = len(pubkey) # bytes\n if pubkey[0] in (0x02, 0x03): # compressed point\n if bsize != ec.psize + 1:\n msg = \"invalid size for compressed point: \"\n msg += f\"{bsize} instead of {ec.psize + 1}\"\n raise BTClibValueError(msg)\n x_Q = int.from_bytes(pubkey[1:], byteorder=\"big\")\n try:\n y_Q = ec.y_even(x_Q) # also check x_Q validity\n return x_Q, y_Q if pubkey[0] == 0x02 else ec.p - y_Q\n except BTClibValueError as e:\n msg = f\"invalid x-coordinate: '{hex_string(x_Q)}'\"\n raise BTClibValueError(msg) from e\n elif pubkey[0] == 0x04: # uncompressed point\n if bsize != 2 * ec.psize + 1:\n msg = \"invalid size for uncompressed point: \"\n msg += f\"{bsize} instead of {2 * ec.psize + 1}\"\n raise BTClibValueError(msg)\n x_Q = int.from_bytes(pubkey[1 : ec.psize + 1], byteorder=\"big\")\n Q = x_Q, int.from_bytes(pubkey[ec.psize + 1 :], byteorder=\"big\")\n if Q[1] == 0: # infinity point in affine coordinates\n raise BTClibValueError(\"no bytes representation for infinity point\")\n if ec.is_on_curve(Q):\n return Q\n raise BTClibValueError(f\"point not on curve: {Q}\")\n else:\n raise BTClibValueError(f\"not a point: {pubkey!r}\")\n","sub_path":"btclib/secpoint.py","file_name":"secpoint.py","file_ext":"py","file_size_in_byte":2944,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"6"} +{"seq_id":"81938304","text":"\"\"\"Given a nitrogen source directory, this script:\n- builds nitrogen\n- syncs local nitrogen directories to rel/nitrogen\n- expands ./etc/vm.args.tmpl with appropriate variables for build environment\n- create symlink from rel/nitrogen/site/include/schema.hrl to ../include/schema/hrl\n- create symlink from rel/nitrogen/deps/subdomain to ../../subdomain\n\"\"\"\n\nimport optparse\nimport os.path\nimport shutil\nimport subprocess\nimport sys\n\njoin = os.path.join\nisdir = os.path.isdir\n\nSRC_DIR = os.path.dirname(os.path.abspath(__file__))\n\nTEMPLATE_SUFFIX = '.tmpl'\n\ndef shell(command):\n \"\"\"Run shell command and return tuple of (stdout, stderr, returncode)\"\"\"\n proc = subprocess.Popen(command, shell=True,\n stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n stdout, stderr = proc.communicate()\n return proc.returncode, stdout, stderr\n\ndef build_nitrogen(nitrogen_src_dir):\n print('building %s' % nitrogen_src_dir)\n return shell('cd %s && make rel_inets' % nitrogen_src_dir)\n\ndef sync(name, rel_dir):\n src_dir = join(SRC_DIR, name)\n assert isdir(src_dir)\n print('syncing %s to %s' % (src_dir, rel_dir))\n return shell('rsync -avP %s %s' % (src_dir, rel_dir))\n\ndef sync_src_to_rel(rel_dir):\n for name in [d for d in os.listdir(rel_dir) if isdir(d)]: #['etc', 'site']:\n #print(name)\n sync(name, rel_dir)\n\ndef inject_template_vars(template_file, vals):\n target_file = os.path.splitext(template_file)[0]\n #print(target_file)\n if os.path.exists(target_file):\n print('overwriting %s' % target_file)\n lines = [l.format(**vals) for l in open(template_file).readlines()]\n #print(lines)\n with open(target_file, 'w') as f:\n for l in lines:\n f.write(l)\n f.close()\n\ndef default_nitrogen_src_dir(platform=os.uname()[0]):\n if platform == 'Darwin':\n return os.path.expanduser('~/proj/sandbox/nitrogen.git')\n elif platform == 'Linux':\n return os.path.expanduser('~/pkg/nitrogen.git')\n\ndef assure_symlink(src, symlink):\n if not os.path.exists(symlink):\n print('creating symlink from %s to %s' % (src, symlink))\n os.symlink(src, symlink)\n assert os.path.islink(symlink)\n\ndef main():\n parser = optparse.OptionParser()\n parser.add_option('-n', '--nitrogen-src-dir', default=default_nitrogen_src_dir())\n opts, _args = parser.parse_args()\n\n assert isdir(opts.nitrogen_src_dir)\n retcode, out, err = build_nitrogen(opts.nitrogen_src_dir)\n assert retcode == 0\n print(out)\n nitrogen_rel_dir = join(opts.nitrogen_src_dir, 'rel/nitrogen')\n assert isdir(nitrogen_rel_dir)\n sync_src_to_rel(nitrogen_rel_dir)\n\n template_file = join(nitrogen_rel_dir, 'etc/vm.args%s' % TEMPLATE_SUFFIX)\n assert os.path.exists(template_file)\n vals = {\n 'shorthostname': shell('hostname -s')[1].strip(),\n 'cookie': open(os.path.expanduser('~/.erlang.cookie')).read()}\n print('injecting %s into template %s' % (vals, template_file))\n inject_template_vars(template_file, vals)\n\n schema_file = join(SRC_DIR, '../include/schema.hrl')\n assert os.path.exists(schema_file)\n schema_symlink = join(nitrogen_rel_dir, 'site/include/schema.hrl')\n assure_symlink(schema_file, schema_symlink)\n\n subdomain_dir = os.path.normpath(join(SRC_DIR, '../../subdomain'))\n assert isdir(subdomain_dir)\n deps_dir = join(nitrogen_rel_dir, 'deps')\n if not isdir(deps_dir):\n os.makedirs(deps_dir)\n subdomain_symlink = join(nitrogen_rel_dir, 'deps/subdomain')\n assure_symlink(subdomain_dir, subdomain_symlink)\n\n site_ebin_dir = join(nitrogen_rel_dir, 'site/ebin')\n assert isdir(site_ebin_dir)\n print('removing .beam files in %s' % site_ebin_dir) # so make will compile index.erl\n print(shell('cd %s && rm *.beam' % site_ebin_dir))\n\n print('making synced nitrogen')\n print(shell('cd %s && make' % nitrogen_rel_dir))\n\nif __name__ == '__main__':\n sys.exit(main())\n","sub_path":"nitrogen/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":3945,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"6"} +{"seq_id":"41379329","text":"#coding:utf-8\nimport os\nimport sys\nimport configparser\nimport base64\nfrom io import BytesIO\nfrom flask import make_response, request, abort, redirect, url_for, session\nfrom app_front import app_front_blue\nfrom tools.mysql_tools.mysql_tools import *\nfrom tools.other_tools.captcha_tools import get_verify_code\nfrom Logger import log\nfrom PIL import Image\n\ncurrent_path = os.path.realpath(__file__)\nroot_path = os.path.dirname(os.path.dirname(current_path))\ncfp_path = os.path.join(os.path.dirname(root_path), 'conf/cms.conf')\ncfp = configparser.ConfigParser()\ncfp.read(cfp_path, encoding='utf-8')\nfile_path = cfp.get('flask', 'file_path')\n\n# 图片保存路径\npicture_path = os.path.join(file_path, 'picture')\n# logo保存路径\nlogo_path = os.path.join(file_path, 'logo')\n# 用户图片保存路径\nlogouser_path = os.path.join(file_path, 'logouser')\n\n@app_front_blue.route('/show/picture/')\ndef showPicture():\n\t'''\n\n\t:return:\n\t'''\n\tfilename = request.args.get('filename')\n\twidth = request.args.get('width')\n\theight = request.args.get('height')\n\tif not filename:\n\t\tabort(404)\n\ttry:\n\t\tif width or height:\n\t\t\timg = Image.open(os.path.join(picture_path, '%s' % filename))\n\t\t\tif width and height:\n\t\t\t\twidth = int(width)\n\t\t\t\theight = int(height)\n\t\t\t\tout = img.resize((width, height))\n\n\t\t\telif width:\n\t\t\t\twidth = int(width)\n\t\t\t\timg_width, img_height = img.size\n\t\t\t\tif img_width >= width:\n\t\t\t\t\ttimes = img_width // width\n\t\t\t\telse:\n\t\t\t\t\ttimes = 1\n\t\t\t\tout = img.resize((img_width // times, img_height // times))\n\t\t\telse:\n\t\t\t\theight = int(height)\n\t\t\t\timg_width, img_height = img.size\n\t\t\t\tif img_height >= height:\n\t\t\t\t\ttimes = img_height // height\n\t\t\t\telse:\n\t\t\t\t\ttimes = 1\n\t\t\t\tout = img.resize((img_width // times, img_height // times))\n\t\t\tf = BytesIO()\n\t\t\tout.save(f, 'png')\n\t\t\tf.seek(0)\n\t\t\tresponse = make_response(f.read())\n\t\t\tresponse.headers['Content-Type'] = 'image/%s' % 'png'\n\t\t\treturn response\n\t\telse:\n\t\t\timage_data = open(os.path.join(picture_path, '%s' % filename), \"rb\").read()\n\t\t\timage_suff = filename.split('.')[-1]\n\t\t\tresponse = make_response(image_data)\n\t\t\tresponse.headers['Content-Type'] = 'image/%s' % image_suff\n\t\t\treturn response\n\texcept Exception as e:\n\t\tfunction_name = sys._getframe().f_code.co_name\n\t\tmsg = 'On line {} - {}'.format(sys.exc_info()[2].tb_lineno, e)\n\t\tlog(function_name).logger.error(msg)\n\t\tabort(404)\n\n@app_front_blue.route('/show/logo/', methods=['GET'])\ndef showLogo(filename):\n\t'''\n\t展示logo\n\t:param filename:\n\t:return:\n\t'''\n\tfile_dir = logo_path\n\tif request.method == 'GET':\n\t\tif filename is None:\n\t\t\tpass\n\t\telse:\n\t\t\ttry:\n\t\t\t\timage_data = open(os.path.join(file_dir, '%s' % filename), \"rb\").read()\n\t\t\t\tresponse = make_response(image_data)\n\t\t\t\tresponse.headers['Content-Type'] = 'image/png'\n\t\t\t\treturn response\n\t\t\texcept:\n\t\t\t\treturn redirect(url_for('app_front.showLogo', filename='upload_photo.jpg'))\n\telse:\n\t\tpass\n\n@app_front_blue.route('/show/logouser/', methods=['GET'])\ndef showLogouser(username):\n\t'''\n\t展示用户头像\n\t:param username:\n\t:return:\n\t'''\n\tfile_dir = logouser_path\n\t# filename = username\n\tif request.method == 'GET':\n\t\tif username is None:\n\t\t\tpass\n\t\telse:\n\t\t\ttry:\n\t\t\t\tfilename = getManagerLogo(username)\n\t\t\t\timage_data = open(os.path.join(file_dir, '%s' % filename), \"rb\").read()\n\t\t\t\tresponse = make_response(image_data)\n\t\t\t\tresponse.headers['Content-Type'] = 'image/png'\n\t\t\t\treturn response\n\t\t\texcept:\n\t\t\t\treturn redirect(url_for('app_front.showLogo', filename='upload_photo.jpg'))\n\telse:\n\t\tpass\n\n@app_front_blue.route('/captcha/')\ndef graph_captcha():\n\timage, code = get_verify_code()\n\tout = BytesIO() # 在内存中读写bytes\n\timage.save(out, 'png')\n\timage.close()\n\tout.seek(0)\n\tresp = make_response(out.read())\n\tresp.content_type = 'image/png'\n\tcode = code.lower()\n\tif 'captcha' in session:\n\t\tsession.pop('captcha', None)\n\tsession['captcha'] = code\n\treturn resp","sub_path":"myBlogCMS/app_front/front_picture.py","file_name":"front_picture.py","file_ext":"py","file_size_in_byte":3857,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"646314056","text":"# 分支算法执行类\nclass Worker:\n max = 0 # 上界 通过贪心算法找出近似值\n min = 0 # 下界 由每组的最小值组成\n pt_nodes = [] # 存放可扩展的节点\n pt_flag = 0 # 标记队列是否被使用 用于结束算法\n input_file = '' # 输入文件名\n output_file = '' # 输出文件名\n matrix = [] # 存放数据矩阵 行为单个任务 每个工人 完成所要的时间\n n = 0 # 数据矩阵的大小 n*n\n min_leaf_node = None # 消耗最小的节点\n\n # 初始化参数\n def __init__(self, input_file, output_file):\n self.input_file = input_file\n self.output_file = output_file\n self.read_data_from_file()\n self.n = len(self.matrix)\n self.get_low_limit()\n self.get_up_limit()\n\n # print(self.matrix)\n # print(self.n)\n # print(self.max)\n # print(self.min)\n\n\n # 从文件中读取数据 初始化数据矩阵\n def read_data_from_file(self):\n with open(self.input_file) as source:\n for line in source:\n data_cluster = line.split(',')\n temp = []\n for value in data_cluster:\n temp.append(int(value))\n self.matrix.append(temp)\n\n # 获取数据下界 最小值之和\n def get_low_limit(self):\n for i in range(self.n):\n self.min += min(self.matrix[i])\n\n # 获取数据上界 贪心算法\n def get_up_limit(self):\n # 初始化工人使用标记\n worker_mark = []\n for i in range(self.n):\n worker_mark.append(0)\n # 贪心算法 取得 近似最优解\n for i in range(self.n):\n temp = self.matrix[i]\n min_value = 5000\n index = 0\n for k in range(self.n):\n if worker_mark[k] == 0 and min_value > temp[k]:\n min_value = temp[k]\n index = k\n worker_mark[index] = 1 # 标记工人是否被分配\n self.max += min_value # 累积上限值\n\n # 分支界限算法\n def branch_limit(self):\n if self.pt_flag == 0: # 从第一层开始\n for i in range(self.n):\n time = self.matrix[0][i]\n if time <= self.max: # 没达到上限,创建节点,加入队列\n node = Node()\n node.deep = 0\n node.cost = time\n node.value = time\n node.worker = i\n self.pt_nodes.append(node)\n self.pt_flag = 1\n\n while self.pt_flag == 1: # 永久循环 等队列空了在根据条件判断来结束\n if len(self.pt_nodes) == 0:\n break\n temp = self.pt_nodes.pop(0) # 先进先出\n present_node = temp\n total_cost = temp.cost\n present_deep = temp.deep\n # 初始化工人分配标记\n worker_mark = []\n for i in range(self.n):\n worker_mark.append(0)\n\n # 检查本节点下的作业分配情况\n\n worker_mark[temp.worker] = 1\n while temp.father is not None:\n temp = temp.father\n worker_mark[temp.worker] = 1\n\n if present_deep + 1 == self.n: # 最后一排的叶子节点 直接分配结果\n if self.min_leaf_node is None:\n self.min_leaf_node = present_node\n else:\n if self.min_leaf_node.cost > present_node.cost:\n self.min_leaf_node = present_node\n else:\n children = self.matrix[present_deep + 1]\n # 检查本节点的子节点是否符合进入队列的要求\n for k in range(self.n):\n if children[k] + total_cost <= self.max and worker_mark[k] == 0:\n node = Node()\n node.deep = present_deep + 1\n node.cost = children[k] + total_cost\n node.value = children[k]\n node.worker = k\n node.father = present_node\n self.pt_nodes.append(node)\n\n # 输出算法执行的结果\n def output_result(self):\n file = open(self.output_file,'a')\n temp = self.min_leaf_node\n file.write('最少的消耗为:' + str(temp.cost) + '\\n')\n file.write('第'+str(temp.worker+1) + '位工人完成第'+str(temp.deep+1) + '份工作\\n')\n while temp.father is not None:\n temp = temp.father\n file.write('第' + str(temp.worker + 1) + '位工人完成第' + str(temp.deep + 1) + '份工作\\n')\n print('算法执行结果以及写入到文件:', self.output_file)\n\n\n# 分支节点类\nclass Node:\n def __init__(self):\n self.deep = 0 # 标记该节点的深度\n self.cost = 0 # 标记到达该节点的总消费\n self.father = None # 标记该节点的父节点\n self.value = 0 # 本节点的消费值\n self.worker = None # 本节点的该任务由第几位工人完成\n\n# 主逻辑\n# input_file = 'input_assign05_01.dat'\n# input_file = 'input_assign05_02.dat'\ninput_file = 'input.dat'\n# output_file = 'output_01.dat'\n# output_file = 'output_02.dat'\noutput_file = 'output.dat'\n\n# 初始化算法执行类\nworker = Worker(input_file, output_file)\n# 执行分支界限算法\nworker.branch_limit()\n# 输出结果\nworker.output_result()\n","sub_path":"MyCode/branch_limit.py","file_name":"branch_limit.py","file_ext":"py","file_size_in_byte":5667,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"523312061","text":"import sys\ninput=sys.stdin.readline\n\nN, M=list(input().split(' '))\nN=int(N)\nM=int(M)\npoket_book={}\nfor idx in range(N) :\n poket_name=input().rstrip()\n if poket_name not in poket_book :\n poket_book[poket_name]=idx+1\n\npoket_num=list(poket_book.keys())\n\nfor _ in range(M) :\n target=input().rstrip()\n if target.isdigit() :\n print(poket_num[int(target)-1])\n else :\n print(poket_book[target])","sub_path":"0120/1620_T1012.py","file_name":"1620_T1012.py","file_ext":"py","file_size_in_byte":422,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"18530740","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Apr 14 22:25:21 2020\n\n@author: w\n\"\"\"\n\nimport json \nfrom test import get_country_code \n\n# 将数据加载到一个列表中\nfilename = 'population_data.json'\nwith open(filename) as f: \n pop_data = json.load(f)\n \n# 打印每个国家2010年的人口 \nfor pop_dict in pop_data: \n if pop_dict['Year'] == '2010': \n country_name = pop_dict['Country Name']\n population = int(float(pop_dict['Value']))\n code = get_country_code(country_name)\n if code: \n print(code + \": \" +str(population))\n else: \n print('ERROR - ' + country_name)\n","sub_path":"temperature/world_population.py","file_name":"world_population.py","file_ext":"py","file_size_in_byte":632,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"523286529","text":"\n\n\n\nimport pytest\nfrom airtest.core.api import assert_exists, assert_equal, stop_app, start_app\n\nfrom poco.drivers.ios import iosPoco\n\nfrom common.settings import Common\nfrom driver.config import Driver_Config\nfrom page.mine.mytab import My_tab\nfrom page.order.order import Order\n\n\nclass TestSchool_Order:\n\n\n def test_order(self,enter_mytab):\n\n try:\n order = My_tab().get_order()\n iosPoco()(order).click()\n iosPoco()('其他订单').click()\n iosPoco()('待支付').click()\n value = iosPoco()('没有订单哦~').attr('name')\n assert_equal(value, '没有订单哦~', \"验证我的订单功能通过\")\n\n\n\n\n except Exception:\n value = '异常捕获'\n print('process except')\n assert_equal(value, '我的订单', \"验证我的订单功能不通过\")\n\n finally:\n\n Common().report()\n iosPoco()(\"btn return\").click()\n iosPoco()(\"btn return\").click()","sub_path":"Leap_UI_IOS/test_cases/test_order_cases/test_order.py","file_name":"test_order.py","file_ext":"py","file_size_in_byte":1002,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"616122286","text":"'''\n3. add a method to the classic LinkedList class that returns the last element\nfrom the list. Assume you don’t know how many elements are in the list.\n'''\nclass Node:\n def __init__(self, data):\n self.data = data\n self.next = None\n\n\nclass LinkedList:\n def __init__(self):\n self.head = None\n\n def add(self, data):\n node = Node(data)\n if self.head == None:\n self.head = node\n else:\n node.next = self.head\n self.head = node\n\n def search(self, key):\n iterator = self.head\n while iterator is not None:\n if iterator.data == key:\n return iterator\n iterator = iterator.next\n return None\n\n def __str__(self):\n iterator = self.head\n s = \"\"\n while iterator is not None:\n s += str(iterator.data) + \" \"\n iterator = iterator.next\n return s\n\n def last_element(self):\n iterator = self.head\n while iterator is not None and iterator.next is not None:\n iterator = iterator.next\n return iterator.data if iterator is not None else None\n","sub_path":"chapter14/exercise3.py","file_name":"exercise3.py","file_ext":"py","file_size_in_byte":1152,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"231689724","text":"# -*- coding: utf-8 -*-\nimport os\nimport re\nimport sys\nimport csv\nimport time\nimport random\nimport string\nimport logging\nimport urllib.parse\nfrom queue import Queue\nfrom queue import Empty\nimport bs4\nimport requests\nfrom pymongo import MongoClient\nfrom pymongo.errors import ServerSelectionTimeoutError\nfrom selenium import webdriver\nfrom selenium.webdriver.common.keys import Keys\nfrom multiprocessing.managers import BaseManager\n\nlogging.basicConfig(level=logging.INFO)\n\n\nclass Manager(BaseManager):\n pass\n\n\nclass Worker(object):\n\n def __init__(self):\n self.browser = webdriver.Chrome(executable_path='./chromedriver')\n self.url = 'https://s.1688.com/selloffer/rpc_async_render.jsonp'\n\n def analysis_html(self, soup):\n for n in range(1, 100):\n offerid = 'offer{}'.format(n)\n ware = soup.find('li', id=offerid)\n\n if not ware:\n break\n\n try:\n item_id = ware['offerid']\n except KeyError:\n try:\n item_id = ware.find(\n 'div', class_='sm-offer-company')['offerid']\n except TypeError:\n item_id = None\n\n try:\n title = ware.find('div', class_='sm-offer-title').a['title']\n except TypeError:\n try:\n title = ware.find(\n 'a', class_='sm-offer-photoLink')['title']\n except TypeError:\n title = None\n\n try:\n url = ware.find('div', class_='sm-offer-title').a['href']\n except TypeError:\n try:\n url = ware.find('a', class_='sm-offer-photoLink')['href']\n except TypeError:\n url = None\n\n url2 = None\n if len(url) > 100:\n url2 = 'https://detail.1688.com/offer/{0}.html'.format(item_id)\n\n try:\n price = ware.find(\n 'span', class_='sm-offer-priceNum')['title']\n if '&' in price:\n price = price[5:]\n else:\n price = price[1:]\n except TypeError:\n try:\n price = ware.find(\n 'div', class_='sm-offer-priceNum')['title']\n if '&' in price:\n price = price[5:]\n else:\n price = price[1:]\n except TypeError:\n price = None\n\n try:\n store_name = ware.find(\n 'a', class_='sm-offer-companyName')['title']\n except TypeError:\n store_name = None\n\n try:\n store_url = ware.find(\n 'a', class_='sm-offer-companyName')['href']\n except TypeError:\n store_url = None\n\n try:\n seller_id = ware['companyid']\n except TypeError:\n seller_id = None\n\n post = {\n 'ItemId': item_id, 'Title': title, 'Url': url,\n 'Url2': url2, 'Price': price, 'StoreName': store_name,\n 'StoreUrl': store_url, 'SellerId': seller_id\n }\n\n return post\n\n def start(self):\n Manager.register('get_task_queue')\n Manager.register('get_result_queue')\n Manager.register('get_cookies_payload')\n\n server_address = ('127.0.0.1', 8888)\n logging.info('Connect to server {}...'.format(server_address))\n m = Manager(address=server_address, authkey=b'abcdefg')\n m.connect()\n\n task = m.get_task_queue()\n result = m.get_result_queue()\n cookies_payloads = m.get_cookies_payload()\n\n page_numbers = list()\n while True:\n try:\n n = task.get(timeout=1)\n page_numbers.append(n)\n except Empty:\n logging.info('Task queue is empty.')\n break\n\n headers = {\n 'Host': 's.1688.com',\n 'User-Agent': ('Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 ('\n 'KHTML, like Gecko) Chrome/51.0.2704.106 Safari/537.36'),\n 'Accept': ('text/javascript, application/javascript, application/'\n 'ecmascript, application/x-ecmascript, */*; q=0.01'),\n 'Accept-Language': 'en-US,en;q=0.5',\n 'Accept-Encoding': 'gzip, deflate',\n 'X-Requested-With': 'XMLHttpRequest',\n 'Referer': ('https://s.1688.com/selloffer/offer_search.htm?'\n 'keywords={}&button_click=top&n=y'.format(payload['keywords']))\n }\n\n logging.info('Spider start work...')\n for n in page_numbers:\n payload['beginPage'] = n\n payload['_'] = int(time.time() * 1000)\n req = requests.get(self.url, headers=headers, cookies=cookies, params=payload)\n if 'login.1688.com' in req.url:\n logging.info('Need Login.')\n continue\n elif 'alisec.1688.com' in self.browser.current_url:\n logging.info('Need Checkcode.')\n continue\n regex = re.compile(r'\"html\":\" ([\\s\\S]*) },')\n text = re.search(regex, req.text).group()[9:-5]\n text = text.replace('<', '<').replace('>', '>').replace(\n '\\\\\\n', '').replace('\\\\n', '').replace('\\\\\\\\\"', '\"').replace(\n '\\\\\"', '\"').replace('<\\\\/', '\\d+)/(?P(high|second))/$', 'question_list', name='question_list'),\n url(r'^question/delete/$', 'delete_question', name='delete_question'),\n\n # url(r'^materials/$', TestMaterialsView.as_view(), name='test_materials')\n)\n","sub_path":"apps/tests/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":520,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"592482887","text":"from behave import given, when, then\nimport time\n\n@given('we navigate to the page \"{page}\"')\ndef server_is_up(context, page):\n try:\n context.server.get(page)\n time.sleep(5)\n except:\n raise","sub_path":"test/IntegrationTests/Features/Steps/ServerControl.py","file_name":"ServerControl.py","file_ext":"py","file_size_in_byte":215,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"114532643","text":"#!/usr/bin/python\n'''\nCreated on Mar 7, 2016\n\n@author: arthur\n'''\nfrom functools import wraps\nimport time\nimport csv\nimport os\nimport platform\nimport sys\n\nsys.path.append(os.path.realpath(os.path.join(os.path.dirname(__file__), \"..\")))\nfrom cadis.common.IFramed import IFramed\n\nINSTRUMENT = True\nINSTRUMENT_HEADERS = {}\n\ndef instrument_average(f):\n if not INSTRUMENT:\n return f\n else:\n if not f.__module__ in INSTRUMENT_HEADERS:\n INSTRUMENT_HEADERS[f.__module__] = []\n INSTRUMENT_HEADERS[f.__module__].append(f.func_name)\n @wraps(f)\n def instrument(*args, **kwds):\n obj = args[0]\n if isinstance(obj, IFramed):\n obj = obj.frame\n start = time.time()\n ret = f(*args, **kwds)\n end = time.time()\n if obj._instruments[f.__name__] == \"\":\n obj._instruments[f.__name__] = []\n obj._instruments[f.__name__].append((end - start) * 1000)\n return ret\n return instrument\n\ndef instrument(f):\n if not INSTRUMENT:\n return f\n else:\n if not f.__module__ in INSTRUMENT_HEADERS:\n INSTRUMENT_HEADERS[f.__module__] = []\n INSTRUMENT_HEADERS[f.__module__].append(f.func_name)\n @wraps(f)\n def instrument(*args, **kwds):\n obj = args[0]\n if isinstance(obj, IFramed):\n obj = obj.frame\n start = time.time()\n ret = f(*args, **kwds)\n end = time.time()\n if obj._instruments[f.__name__] == \"\":\n obj._instruments[f.__name__] = 0\n obj._instruments[f.__name__] += (end - start) * 1000\n return ret\n return instrument\n\nclass Instrument(object):\n def __init__(self, fname, headers=None, options=None):\n self.instruments = {}\n self.iteration = 0\n strtime = time.strftime(\"%Y-%m-%d_%H-%M-%S\")\n if not os.path.exists('stats'):\n os.mkdir('stats')\n self.ifname = os.path.join('stats', \"%s_%s.csv\" % (strtime,fname))\n if platform.system() != \"Windows\":\n linkname = os.path.join('stats', \"latest_%s\" % fname)\n if os.path.exists(linkname):\n os.remove(linkname)\n os.symlink(os.path.abspath(self.ifname), linkname) # @UndefinedVariable only in Linux!\n with open(self.ifname, 'w', 0) as csvfile:\n if options:\n csvfile.write(\"########\\n\")\n csvfile.write(\"Options, %s\\n\" % ','.join([\"%s:%s\" % (k,v) for k,v in options.values()]))\n csvfile.write(\"########\\n\\n\")\n self.headers = ['iteration']\n if headers:\n self.headers.extend(headers)\n self.headers.extend(INSTRUMENT_HEADERS.values())\n self.fieldnames = self.headers\n writer = csv.DictWriter(csvfile, delimiter=',', lineterminator='\\n', fieldnames=self.fieldnames)\n writer.writeheader()\n\n def clean(self):\n for k in self.instruments:\n self.instruments[k] = \"\"\n\n def add_instruments(self, instruments):\n self.instruments.update(instruments)\n\n def measure_call(self, f, header, *args, **kwargs):\n start = time.time()\n f(*args, **kwargs)\n end = time.time()\n self.instruments[header] = (end - start) * 1000\n\n def dump_stats(self):\n with open(self.ifname, 'a', 0) as csvfile:\n writer = csv.DictWriter(csvfile, delimiter=',', lineterminator='\\n', fieldnames=self.fieldnames)\n #d['vehicles'] = self.frame.count(self.frame.name2class(\"Vehicle\"))\n self.instruments['iteration'] = self.iteration\n for h in self.instruments:\n # if averaging, calculate it\n if isinstance(self.instruments[h], list):\n if len(self.instruments[h]) == 0:\n self.instruments[h] = \"\"\n else:\n self.instruments[h] = float(sum(self.instruments[h]))/len(self.instruments[h])\n writer.writerow(self.instruments)\n self.clean()\n self.iteration += 1\n","sub_path":"cadis/common/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":4165,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"157310178","text":"\n\nimport sys\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D # 3D 画图必备\n\nfrom fealpy.decorator import cartesian, barycentric\nfrom fealpy.mesh import MeshFactory\nfrom fealpy.functionspace import LagrangeFiniteElementSpace\n\nclass CosCosData:\n \"\"\"\n -\\Delta u = f\n u = cos(pi*x)*cos(pi*y)\n \"\"\"\n def __init__(self):\n pass\n\n def domain(self):\n return np.array([0, 1, 0, 1])\n\n @cartesian\n def solution(self, p):\n \"\"\"The exact solution\n Parameters\n ---------\n p : (..., 2)--> (2, ), (10, 2), (3, 10, 2)\n\n\n Examples\n -------\n p = np.array([0, 1], dtype=np.float64)\n p = np.array([[0, 1], [0.5, 0.5]], dtype=np.float64)\n \"\"\"\n x = p[..., 0]\n y = p[..., 1]\n pi = np.pi\n val = np.cos(pi*x)*np.cos(pi*y)\n return val # val.shape == x.shape\n\n @cartesian\n def source(self, p):\n \"\"\" The rigth hand side of Possion equaiton\n INPUT:\n p: array object\n \"\"\" \n x = p[..., 0]\n y = p[..., 1]\n pi = np.pi\n val = 2*pi*pi*np.cos(pi*x)*np.cos(pi*y)\n return val\n\n @cartesian\n def gradient(self, p):\n \"\"\" The gradient of the exact solution\n \"\"\" \n x = p[..., 0]\n y = p[..., 1]\n pi = np.pi\n val = np.zeros(p.shape, dtype=np.float64)\n val[..., 0] = -pi*np.sin(pi*x)*np.cos(pi*y)\n val[..., 1] = -pi*np.cos(pi*x)*np.sin(pi*y)\n return val # val.shape == p.shape\n\n @cartesian\n def flux(self, p):\n return -self.gradient(p)\n\n @cartesian\n def dirichlet(self, p):\n return self.solution(p)\n\n @cartesian\n def neumann(self, p, n):\n \"\"\"\n Neumann boundary condition\n\n Parameters\n -------\na\n P: (NQ, NE, 2)\n n: (NE, 2)\n\n grad*n: (NQ, NE, 2)\n \"\"\"\n grad = self.gradient(p) # (NQ, NE, 2)\n val = np.sum(grad*n, axis=-1) # (NQ, NE)\n return val\n\n @cartesian\n def robin(self, p, n):\n grad = self.gradient(p) # (NQ, NE, 2)\n val = np.sum(grad*n, axis=-1) # (NQ, NE)\n shape = len(val.shape)*(1, )\n kappa = np.array([1.0], dtype=np.float64).reshape(shape)\n val += self.solution(p)\n return val, kappa\n\n\np = int(sys.argv[1])\nn = int(sys.argv[2])\n\npde = CosCosData()\n\nmf = MeshFactory()\nbox = [0, 1, 0, 1]\nmesh = mf.boxmesh2d(box, nx=n, ny=n, meshtype='tri')\nspace = LagrangeFiniteElementSpace(mesh, p=p)\n\n# 插值\nuI = space.interpolation(pde.solution) # 是个有限元函数,同时也是一个数组\n \nprint('uI[0:10]:', uI[0:10]) # 打印前面 10 个自由度的值\n\nbc = np.array([1/3, 1/3, 1/3], dtype=mesh.ftype) #(3, )\nval0 = uI(bc) # (NC, )\nval1 = uI.grad_value(bc) # (NC, 2)\n\nprint('val0[0:10]:', val0[0:10]) # 打印 uI 在前面的 10 个单元重心处的函数值\nprint('val1[0:10]:', val1[0:10]) # 打印 uI 在前面的 10 个单元重心处的梯度值\n\n\n# error of interpolation\nerror0 = space.integralalg.L2_error(pde.solution, uI)\nerror1 = space.integralalg.L2_error(pde.gradient, uI.grad_value)\nprint('L2:', error0, 'H1:', error1)\n\nfig = plt.figure()\naxes = fig.gca(projection='3d')\nuI.add_plot(axes, cmap='rainbow')\nplt.show()\n \n\n\n \n\n \n","sub_path":"test/pde_model.py","file_name":"pde_model.py","file_ext":"py","file_size_in_byte":3302,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"183190128","text":"import asyncio\nimport json\nimport pytest\nfrom pynghttp2 import ClientSession, ServerSession, StreamClosedError, nghttp2\n\n\n@pytest.mark.asyncio\nasync def test_connection_refused(event_loop):\n with pytest.raises(ConnectionError):\n async with ClientSession(host='localhost', port=64602, loop=event_loop) as session:\n pass\n\n\n@pytest.mark.asyncio\nasync def test_ping(echo_server, event_loop):\n async with echo_server:\n async with ClientSession(host='localhost', port=64602, loop=event_loop) as session:\n assert session.request_allowed() == True, \"It must be allowed to send requests\"\n\n resp = session.get('http://localhost:64602/ping')\n assert resp.content.at_eof() == False, \"Response must not be at EOF before sending\"\n await resp\n\n assert resp.status == 200\n assert resp.content_length == 4\n assert resp.content_type == 'text/plain'\n\n # Wait for response content\n pong = await resp.text()\n assert resp.content.at_eof() == True, \"Response must be at EOF after receiving\"\n assert pong == \"pong\"\n\n # Check if content is correctly cached\n pong = await resp.text()\n assert pong == \"pong\", \"Repeated call to read should return identical results\"\n\n\n@pytest.mark.asyncio\nasync def test_echo(echo_server, event_loop):\n async with echo_server:\n async with ClientSession(host='localhost', port=64602, loop=event_loop) as session:\n msg = b\"Hello world!\"\n resp = session.post('http://localhost:64602/echo', data=msg)\n await resp\n echo = await resp.read()\n assert echo == msg, \"Echo message must be the same\"\n\n\n@pytest.mark.asyncio\nasync def test_stream(echo_server, event_loop):\n async with echo_server:\n async with ClientSession(host='localhost', port=64602, loop=event_loop) as session:\n resp = session.get('http://localhost:64602/stream')\n await resp\n\n size = 0\n while not resp.content.at_eof():\n chunk = await resp.content.read(2 ** 16)\n size += len(chunk)\n\n assert size == resp.content_length\n\n\n@pytest.mark.asyncio\nasync def test_interleave_streams(echo_server, event_loop):\n async with echo_server:\n async with ClientSession(host='localhost', port=64602, loop=event_loop) as session:\n stream1 = session.get('http://localhost:64602/stream')\n stream2 = session.get('http://localhost:64602/stream')\n\n await stream1\n await stream2\n\n size1 = 0\n size2 = 0\n while not stream1.content.at_eof() or not stream2.content.at_eof():\n if not stream1.content.at_eof():\n chunk = await stream1.content.read(2 ** 16)\n size1 += len(chunk)\n\n if not stream2.content.at_eof():\n chunk = await stream2.content.read(2 ** 16)\n size2 += len(chunk)\n\n assert size1 == stream1.content_length\n assert size2 == stream2.content_length\n\n\n@pytest.mark.asyncio\nasync def test_max_concurrect_streams(echo_server, event_loop):\n echo_server.settings = [\n (nghttp2.settings_id.MAX_CONCURRENT_STREAMS, 1),\n ]\n async with echo_server:\n async with ClientSession(host='localhost', port=64602, loop=event_loop) as session:\n resp1 = session.get('http://localhost:64602/ping')\n resp2 = session.get('http://localhost:64602/ping')\n task = await asyncio.gather(resp1, resp2)\n\n\n@pytest.mark.asyncio\nasync def test_interleave_streams_with_tasks(echo_server, event_loop):\n async def read_stream(resp):\n size = 0\n await resp\n\n while not resp.content.at_eof():\n chunk = await resp.content.read(2 ** 14)\n size += len(chunk)\n\n assert size == resp.content_length\n\n async with echo_server:\n async with ClientSession(host='localhost', port=64602, loop=event_loop) as session:\n stream1 = session.get('http://localhost:64602/stream')\n stream2 = session.get('http://localhost:64602/stream')\n\n await asyncio.gather(read_stream(stream1), read_stream(stream2), loop=event_loop)\n\n\n@pytest.mark.asyncio\nasync def test_block_stream(echo_server, event_loop):\n async with echo_server:\n async with ClientSession(host='localhost', port=64602, loop=event_loop) as session:\n stream1 = session.get('http://localhost:64602/stream')\n stream2 = session.get('http://localhost:64602/stream')\n\n await stream1\n await stream2\n\n # Read stream 2 first. This should block DATA blocks of stream 1\n size2 = 0\n while not stream2.content.at_eof():\n chunk = await stream2.content.read(2 ** 16)\n size2 += len(chunk)\n\n size1 = 0\n while not stream1.content.at_eof():\n chunk = await stream1.content.read(2 ** 16)\n size1 += len(chunk)\n\n assert size1 == stream1.content_length\n assert size2 == stream2.content_length\n\n\n@pytest.mark.asyncio\nasync def test_json(echo_server, event_loop):\n async with echo_server:\n async with ClientSession(host='localhost', port=64602, loop=event_loop) as session:\n msg = json.dumps({\n \"status\": \"ok\",\n \"error\": None,\n }).encode()\n\n resp = session.post('http://localhost:64602/echo', data=msg)\n await resp\n echo = await resp.json()\n assert echo[\"status\"] == \"ok\"\n assert echo[\"error\"] == None\n\n resp = session.post('http://localhost:64602/echo', data=\"invalid json\")\n await resp\n echo = await resp.json()\n assert echo == None\n\n\n@pytest.mark.asyncio\nasync def test_client_terminate(echo_server, event_loop):\n async with echo_server:\n async with ClientSession(host='localhost', port=64602, loop=event_loop) as session:\n await session.terminate()\n\n@pytest.mark.asyncio\nasync def test_client_terminate_with_request(echo_server, event_loop):\n async with echo_server:\n async with ClientSession(host='localhost', port=64602, loop=event_loop) as session:\n resp = session.get('http://localhost:64602/ping')\n\n # Terminate the session with a specific error code\n await session.terminate(nghttp2.error_code.INTERNAL_ERROR)\n\n # The error code is expected in the exception raised by all further operations\n with pytest.raises(ConnectionResetError) as excinfo:\n await resp\n await resp.text()\n assert \"INTERNAL_ERROR\" in str(excinfo.value)\n\n with pytest.raises(ConnectionError) as excinfo:\n resp = session.get('http://localhost:64602/ping')\n\n","sub_path":"tests/test_sessions.py","file_name":"test_sessions.py","file_ext":"py","file_size_in_byte":6967,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"495515","text":"#!/bin/env python3\n\"\"\"\nThis script creates a canonicalized version of KG2 stored in TSV files, ready for import into neo4j. The TSVs are\ncreated in the current working directory.\nUsage: python3 create_canonicalized_kg_tsvs.py [--test]\n\"\"\"\nimport argparse\nimport ast\nimport csv\nimport os\nimport sys\nimport time\nimport traceback\n\nfrom datetime import datetime\nfrom typing import List, Dict, Tuple, Union\nfrom neo4j import GraphDatabase\n\nsys.path.append(os.path.dirname(os.path.abspath(__file__))+\"/../../\") # code directory\nfrom RTXConfiguration import RTXConfiguration\nsys.path.append(os.path.dirname(os.path.abspath(__file__))+\"/../../ARAX/NodeSynonymizer/\")\nfrom node_synonymizer import NodeSynonymizer\n\n\ndef _run_cypher_query(cypher_query: str, kg=\"KG2\") -> List[Dict[str, any]]:\n # This function sends a cypher query to neo4j (either KG1 or KG2) and returns results\n rtxc = RTXConfiguration()\n if kg == \"KG2\":\n rtxc.live = \"KG2\"\n try:\n driver = GraphDatabase.driver(rtxc.neo4j_bolt, auth=(rtxc.neo4j_username, rtxc.neo4j_password))\n with driver.session() as session:\n print(f\" Sending cypher query to {kg} neo4j..\")\n query_results = session.run(cypher_query).data()\n print(f\" Got {len(query_results)} results back from neo4j\")\n driver.close()\n except Exception:\n tb = traceback.format_exc()\n error_type, error, _ = sys.exc_info()\n print(f\"ERROR: Encountered a problem interacting with {kg} neo4j. {tb}\")\n return []\n else:\n return query_results\n\n\ndef _convert_list_to_neo4j_format(input_list: List[any]) -> str:\n return str(input_list).strip(\"[\").strip(\"]\").replace(\"'\", \"\")\n\n\ndef _merge_two_lists(list_a: List[any], list_b: List[any]) -> List[any]:\n return list(set(list_a + list_b))\n\n\ndef _literal_eval_list(input_item: Union[str, List[any]]) -> List[any]:\n try:\n actual_list = ast.literal_eval(input_item)\n except Exception:\n return []\n else:\n return actual_list\n\n\ndef _convert_strange_provided_by_field_to_list(provided_by_field):\n # Needed temporarily until kg2-2+ is rolled out to production\n provided_by_list = []\n for item in provided_by_field:\n if \"[\" in item:\n item = item.replace(\"[\", \"\")\n if \"]\" in item:\n item = item.replace(\"]\", \"\")\n if \"'\" in item:\n item = item.replace(\"'\", \"\")\n provided_by_list.append(item)\n return provided_by_list\n\n\ndef _canonicalize_nodes(nodes: List[Dict[str, any]]) -> Tuple[List[Dict[str, any]], Dict[str, str]]:\n synonymizer = NodeSynonymizer()\n node_ids = [node.get('id') for node in nodes if node.get('id')]\n print(f\" Sending NodeSynonymizer.get_canonical_curies() a list of {len(node_ids)} curies..\")\n canonicalized_info = synonymizer.get_canonical_curies(curies=node_ids, return_all_types=True)\n print(f\" Creating canonicalized nodes..\")\n curie_map = dict()\n canonicalized_nodes = dict()\n for node in nodes:\n canonical_info = canonicalized_info.get(node['id'])\n canonicalized_curie = canonical_info.get('preferred_curie', node['id']) if canonical_info else node['id']\n node['publications'] = _literal_eval_list(node['publications']) # Only need to do this until kg2.2+ is rolled out\n if canonicalized_curie in canonicalized_nodes:\n existing_canonical_node = canonicalized_nodes[canonicalized_curie]\n existing_canonical_node['publications'] = _merge_two_lists(existing_canonical_node['publications'], node['publications'])\n else:\n if canonical_info:\n canonicalized_node = {\n 'id': canonicalized_curie,\n 'name': canonical_info.get('preferred_name', node['name']),\n 'types': list(canonical_info.get('all_types')),\n 'preferred_type': canonical_info.get('preferred_type', node['category_label']),\n 'publications': node['publications']\n }\n else:\n canonicalized_node = {\n 'id': canonicalized_curie,\n 'name': node['name'],\n 'types': [node['category_label']],\n 'preferred_type': node['category_label'],\n 'publications': node['publications']\n }\n canonicalized_nodes[canonicalized_node['id']] = canonicalized_node\n curie_map[node['id']] = canonicalized_curie # Record this mapping for easy lookup later\n\n # Create a node containing information about this KG2C build\n new_build_node = {'id': 'RTX:KG2C',\n 'name': f\"KG2C:Build created on {datetime.now().strftime('%Y-%m-%d %H:%M')}\",\n 'types': ['data_file'],\n 'preferred_type': 'data_file',\n 'publications': []}\n canonicalized_nodes[new_build_node['id']] = new_build_node\n\n # Decorate nodes with equivalent curies\n print(f\" Sending NodeSynonymizer.get_equivalent_nodes() a list of {len(canonicalized_nodes)} curies..\")\n equivalent_curies_dict = synonymizer.get_equivalent_nodes(list(canonicalized_nodes.keys()))\n for curie, canonical_node in canonicalized_nodes.items():\n equivalent_curies = []\n equivalent_curies_dict_for_curie = equivalent_curies_dict.get(curie)\n if equivalent_curies_dict_for_curie is not None:\n for equivalent_curie in equivalent_curies_dict_for_curie:\n equivalent_curies.append(equivalent_curie)\n canonical_node['equivalent_curies'] = equivalent_curies\n\n # Convert array fields into the format neo4j wants and do final processing\n for canonicalized_node in canonicalized_nodes.values():\n canonicalized_node['types'] = _convert_list_to_neo4j_format(canonicalized_node['types'])\n canonicalized_node['publications'] = _convert_list_to_neo4j_format(canonicalized_node['publications'])\n canonicalized_node['equivalent_curies'] = _convert_list_to_neo4j_format(canonicalized_node['equivalent_curies'])\n canonicalized_node['preferred_type_for_conversion'] = canonicalized_node['preferred_type']\n return list(canonicalized_nodes.values()), curie_map\n\n\ndef _remap_edges(edges: List[Dict[str, any]], curie_map: Dict[str, str], is_test: bool) -> List[Dict[str, any]]:\n allowed_self_edges = ['positively_regulates', 'interacts_with', 'increase']\n merged_edges = dict()\n for edge in edges:\n original_source_id = edge['subject']\n original_target_id = edge['object']\n if not is_test: # Make sure we don't wind up with any orphan edges\n assert original_source_id in curie_map\n assert original_target_id in curie_map\n canonicalized_source_id = curie_map.get(original_source_id, original_source_id)\n canonicalized_target_id = curie_map.get(original_target_id, original_target_id)\n edge_type = edge['simplified_edge_label']\n # Convert fields that should be lists to lists (only need to do this until kg2.2+ is rolled out to production)\n edge['provided_by'] = _convert_strange_provided_by_field_to_list(edge['provided_by'])\n edge['publications'] = _literal_eval_list(edge['publications'])\n if canonicalized_source_id != canonicalized_target_id or edge_type in allowed_self_edges:\n remapped_edge_key = f\"{canonicalized_source_id}--{edge_type}--{canonicalized_target_id}\"\n if remapped_edge_key in merged_edges:\n merged_edge = merged_edges[remapped_edge_key]\n merged_edge['provided_by'] = _merge_two_lists(merged_edge['provided_by'], edge['provided_by'])\n merged_edge['publications'] = _merge_two_lists(merged_edge['publications'], edge['publications'])\n else:\n new_remapped_edge = dict()\n new_remapped_edge['subject'] = canonicalized_source_id\n new_remapped_edge['object'] = canonicalized_target_id\n new_remapped_edge['simplified_edge_label'] = edge['simplified_edge_label']\n new_remapped_edge['provided_by'] = edge['provided_by']\n new_remapped_edge['publications'] = edge['publications']\n merged_edges[remapped_edge_key] = new_remapped_edge\n\n # Convert array fields into the format neo4j wants and do final processing\n for final_edge in merged_edges.values():\n final_edge['provided_by'] = _convert_list_to_neo4j_format(final_edge['provided_by'])\n final_edge['publications'] = _convert_list_to_neo4j_format(final_edge['publications'])\n final_edge['simplified_edge_label_for_conversion'] = final_edge['simplified_edge_label']\n final_edge['subject_for_conversion'] = final_edge['subject']\n final_edge['object_for_conversion'] = final_edge['object']\n return list(merged_edges.values())\n\n\ndef _modify_column_headers_for_neo4j(plain_column_headers: List[str]) -> List[str]:\n modified_headers = []\n array_columns = ['provided_by', 'types', 'equivalent_curies', 'publications']\n for header in plain_column_headers:\n if header in array_columns:\n header = f\"{header}:string[]\"\n elif header == 'id':\n header = f\"{header}:ID\"\n elif header == 'preferred_type_for_conversion':\n header = \":LABEL\"\n elif header == 'subject_for_conversion':\n header = \":START_ID\"\n elif header == 'object_for_conversion':\n header = \":END_ID\"\n elif header == 'simplified_edge_label_for_conversion':\n header = \":TYPE\"\n modified_headers.append(header)\n return modified_headers\n\n\ndef create_canonicalized_tsvs(is_test=False):\n # Grab the node data from KG2 neo4j and load it into TSVs\n print(f\" Starting nodes..\")\n nodes_query = f\"match (n) return n.id as id, n.name as name, n.category_label as category_label, \" \\\n f\"n.publications as publications{' limit 20000' if is_test else ''}\"\n nodes = _run_cypher_query(nodes_query)\n if nodes:\n print(f\" Canonicalizing nodes..\")\n canonicalized_nodes, curie_map = _canonicalize_nodes(nodes)\n print(f\" Canonicalized KG contains {len(canonicalized_nodes)} nodes ({round((len(canonicalized_nodes) / len(nodes)) * 100)}%)\")\n print(f\" Creating nodes header file..\")\n column_headers = list(canonicalized_nodes[0].keys())\n modified_headers = _modify_column_headers_for_neo4j(column_headers)\n with open(f\"{'test_' if is_test else ''}nodes_c_header.tsv\", \"w+\") as nodes_header_file:\n dict_writer = csv.DictWriter(nodes_header_file, modified_headers, delimiter='\\t')\n dict_writer.writeheader()\n print(f\" Creating nodes file..\")\n with open(f\"{'test_' if is_test else ''}nodes_c.tsv\", \"w+\") as nodes_file:\n dict_writer = csv.DictWriter(nodes_file, column_headers, delimiter='\\t')\n dict_writer.writerows(canonicalized_nodes)\n else:\n print(f\"ERROR: Couldn't get node data from KG2 neo4j.\")\n return\n\n # Grab the edge data from KG2 neo4j and load it into TSVs\n print(f\" Starting edges..\")\n edges_query = f\"match (n)-[e]->(m) return n.id as subject, m.id as object, e.simplified_edge_label as \" \\\n f\"simplified_edge_label, e.provided_by as provided_by, e.publications as publications\" \\\n f\"{' limit 20000' if is_test else ''}\"\n edges = _run_cypher_query(edges_query)\n if edges:\n print(f\" Remapping edges..\")\n remapped_edges = _remap_edges(edges, curie_map, is_test)\n print(f\" Canonicalized KG contains {len(remapped_edges)} edges ({round((len(remapped_edges) / len(edges)) * 100)}%)\")\n print(f\" Creating edges header file..\")\n column_headers = list(remapped_edges[0].keys())\n modified_headers = _modify_column_headers_for_neo4j(column_headers)\n with open(f\"{'test_' if is_test else ''}edges_c_header.tsv\", \"w+\") as edges_header_file:\n dict_writer = csv.DictWriter(edges_header_file, modified_headers, delimiter='\\t')\n dict_writer.writeheader()\n print(f\" Creating edges file..\")\n with open(f\"{'test_' if is_test else ''}edges_c.tsv\", \"w+\") as edges_file:\n dict_writer = csv.DictWriter(edges_file, column_headers, delimiter='\\t')\n dict_writer.writerows(remapped_edges)\n else:\n print(f\"ERROR: Couldn't get edge data from KG2 neo4j.\")\n return\n\n\ndef main():\n arg_parser = argparse.ArgumentParser(description=\"Creates a canonicalized KG2, stored in TSV files\")\n arg_parser.add_argument('--test', dest='test', action='store_true', default=False)\n args = arg_parser.parse_args()\n\n print(f\"Starting to create canonicalized KG TSV files..\")\n start = time.time()\n create_canonicalized_tsvs(args.test)\n print(f\"Done! Took {round((time.time() - start) / 60, 2)} minutes.\")\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"code/kg2/canonicalized/create_canonicalized_kg_tsvs.py","file_name":"create_canonicalized_kg_tsvs.py","file_ext":"py","file_size_in_byte":12982,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"290417213","text":"# -*- coding: utf-8 -*-\nimport numpy as np\n\nn = int(input( ' informe a quantidade de linhas/colunas: '))\n\nmatriz = np.empty([n,n])\n\nfor i in range (0,n,1):\n for j in range (0,n,1):\n matriz[i][j] = int(input('informe o %d° linha e o %d° coluna: ' %((i+1),(j+1))))\n\n#diagonal principal\nm = 0\nfor k in range (n):\n m = m + matriz[k][k]\n\n#diagonal secundario\ns = 0\nfor l in range (n):\n s = s + matriz[l][n-1-l]\nif (s != m):\n print(\"N\")\n exit()\n \n#colunas\nfor h in range (n):\n s = 0\n for g in range (n):\n s = s + matriz[g][h]\n if (s != m):\n print(\"N\")\n exit()\nprint('S')","sub_path":"moodledata/vpl_data/445/usersdata/348/103053/submittedfiles/matriz2.py","file_name":"matriz2.py","file_ext":"py","file_size_in_byte":622,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"331801879","text":"# -*- coding: utf-8 -*-\n# author Leo\n\nimport sys\nimport os\nimport codecs\nfrom Slide import Slide\nfrom PySide.QtGui import QFileDialog\nfrom PySide.QtCore import QDir\n\nclass FileManager() :\n currentFileName = \"\"\n mainApp = None\n path = None\n def __init__(self):\n \"null\"\n \n @staticmethod\n def getSeparator():\n return \"/\" #(\"\\\\\" if os.name == \"posix\" else \"/\")\n \n @staticmethod\n def openFile(): #opens a dialog window to choose the file, looking for python files only, and in the current directory.\n path = QFileDialog.getOpenFileName(None, \"Open file\", QDir.currentPath(), \"Python file (*.py)\")[0] \n FileManager.mainApp.navigationMenu.setFileName(path) \n FileManager.buildSlides(path) #for the side screen\n #FileManager.setFileName(path)\n \n @staticmethod\n def saveFile(path): \n pythonFile = codecs.open(path, \"w\", \"utf-8\") #opens the file in write mode...\n pythonFile.write(FileManager.exportSlides()) #and writes (i.e. saves) it\n FileManager.currentFileName = path #modifies the name of the file\n \n @staticmethod\n def compile(compilerPath):\n if(FileManager.currentFileName !=\"\"): #exception if there is no name\n try: \n os.system(\"python3 \"+compilerPath+' \"'+FileManager.currentFileName+'\"') #writes the right line in the terminal to compile\n except:\n os.system(\"python \"+compilerPath+' \"'+FileManager.currentFileName+'\"') #writes the right line in the terminal to compile\n \n \n @staticmethod\n def saveAndCompile(path,pathToCompiler): #does both\n FileManager.saveFile(path)\n FileManager.compile(pathToCompiler);\n \n @staticmethod\n def setFileName(path):\n #FileManager.currenFileName = path[path.rfind(os.pathsep):path.rfind('.')]\n print(\"filename:\"+FileManager.currentFileName)\n \n @staticmethod\n def buildSlides(path):\n #print(\"\\r\\npath\"+path) \n rootFolder = path[:-3]+\".slides\"+FileManager.getSeparator()\n #print(rootFolder)\n pythonCode = codecs.open(path, \"r\", \"utf-8\").read(); #open(path, \"r\", \"utf-8\")\n #print(pythonCode)\n listSlides = pythonCode.split(\"#beginSlide\") #separates the different slides ; begins where there is \"#beginS‪lide\"\n FileManager.mainApp.header=listSlides[0] \n #print(\"\\r\\n\"+str(len(listSlides)))\n #htmlFiles = glob.glob(rootFolder+\"*Page*.html\")\n for i in range(1,len(listSlides)):\n slide = Slide(listSlides[i],rootFolder+\"Page.\"+str(i-1)+\".html\")\n FileManager.mainApp.slides.append(slide)\n \n FileManager.mainApp.sideScreen.refresh();\n print(\"nb slides \"+str(len(listSlides)-1));\n \n @staticmethod\n def exportSlides(): #to get the python code from the slides which have been modified\n pythonCode = FileManager.mainApp.header\n for i in range(0,len(FileManager.mainApp.slides)):\n slide = FileManager.mainApp.slides[i]\n pythonCode +=\"#beginSlide\"+slide.pythonCode\n return pythonCode\n \n @staticmethod\n def displaySlide(index):\n currentSlide = FileManager.mainApp.slides[index]\n FileManager.mainApp.pythonScreen.setPythonCode(currentSlide.pythonCode)\n FileManager.mainApp.htmlScreen.displaySlide(currentSlide.htmlUrl)\n Slide.currentSlide= index\n","sub_path":"Python/SINP/trunk/dossierTravailGroupe/iteration2 G2+G6/FileManager.py","file_name":"FileManager.py","file_ext":"py","file_size_in_byte":3441,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"647297866","text":"import argparse\nimport torch\nimport torch.backends.cudnn as cudnn\nfrom PIL import Image\nfrom torchvision.transforms import ToTensor\n\nimport numpy as np\n\n# ===========================================================\n# Argument settings\n# ===========================================================\nparser = argparse.ArgumentParser(description='PyTorch Super Res Example')\nparser.add_argument('--input', type=str, required=False, default='/home/teven/canvas/python/super-resolution/dataset/urban100/images/test/img_049.png', help='input image to use')\nparser.add_argument('--model', '-m', type=str, default='srgan', help='choose which model is going to use')\nparser.add_argument('--output', type=str, default='test.jpg', help='where to save the output image')\nparser.add_argument('--baseline', type=str, default='baseline.jpg', help='where to save the baseline image')\nparser.add_argument('--diff', default=False, action='store_true', help='is model differential ?')\nparser.add_argument('--no-diff', dest='diff', action='store_false', help='is model differential ?')\nargs = parser.parse_args()\nprint(args)\n\n\n# ===========================================================\n# input image setting\n# ===========================================================\nGPU_IN_USE = torch.cuda.is_available()\nimg = Image.open(args.input)\nwidth, height = img.size\nimg.thumbnail((width / 4, height / 4), Image.ANTIALIAS)\nbaseline = img.resize((width, height))\n\n\n# ===========================================================\n# model import & setting\n# ===========================================================\ndevice = torch.device('cuda' if GPU_IN_USE else 'cpu')\nmodel_name = args.model\nfolder_name = args.model + (\"_diff\" if args.diff else \"\")\nfile_name = model_name + \"_generator.pth\" if \"gan\" in args.model else \"model.pth\"\nmodel_path = \"/home/teven/canvas/python/super-resolution/results/models/{}/{}\".format(folder_name, file_name)\nmodel = torch.load(model_path, map_location=lambda storage, loc: storage)\nmodel = model.to(device)\ndata = (ToTensor()(img)).view(1, -1, img.size[1], img.size[0])\ndata = data.to(device)\n\nif GPU_IN_USE:\n cudnn.benchmark = True\n\n\n# ===========================================================\n# output and save image\n# ===========================================================\nout = model(data)\nout = out.cpu()\nout_img = out.data[0].numpy()\nout_img *= 255.0\nout_img = out_img.clip(0, 255)\nout_img = np.transpose(out_img, axes=(1, 2, 0))\nprint(out_img.shape)\nout_img = Image.fromarray(np.uint8(out_img), 'RGB')\n\nout_img.save(args.output)\nprint('output image saved to ', args.output)\nbaseline.save(args.baseline)\nprint('baseline image saved to ', args.baseline)\n","sub_path":"super_resolve.py","file_name":"super_resolve.py","file_ext":"py","file_size_in_byte":2681,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"232711521","text":"#this is a program in which i will be learning python gui\nfrom tkinter import messagebox\nfrom math import *\nfrom tkinter import *\nmq = Tk()\ndef hello1():\n print('this is a program to be tested by joihn warui')\n Bu1 = Button(text='circle',fg='red',bg='black').grid(row=0,column=0)\n #this program calculates the area os a circle\n print('A = pi * r**2')\n r = eval(input('please enter r: '))\n A = pi * r**2\n print('the area of circle radius {} is {}'.format(r,A))\n\ndef hello2():\n print('this a proggramthat calculates the area of square')\n Bu2 = Button(text='square',fg='green',bg='black').grid(row=0,column=1)\n #this calcultes area of a square\n print('length and with are equal')\n l = int(input('please enter l: '))\n A = l * l\n print('tha area of a square length {} is {}'.format(l,A))\n\n\ndef hello3():\n print('this is aprogram that calcultes the area of a rectangle')\n Bu2 = Button(text='rectangle',fg='blue',bg='black').grid(row=0,column=2)\n #calcutes rectangle area\n print('rectangle has width and lenght')\n l= int(input('please enter l: '))\n w = int(input('please enter w: '))\n A = l * w\n print('the area of a rectangle lenght {} and width {} is {}'.format(l,w,A))\n\ndef mbox1():\n messagebox.showinfo(title ='save',message='youshould save your document now')\n\ndef mbox2():\n mess1 = messagebox.askyesno(title='quit',message='do you want to quit')\n if mess1 == 1:\n mq.destroy()\n \n \n\nmq.title('Area calculator')\nmq.geometry('700x700')\nBu1 = Button(text='circle',fg='red',bg='black',command=hello1).grid(row=0,column=0)\nBu2 = Button(text='square',fg='green',bg='black',command=hello2).grid(row=0,column=1)\nBu2 = Button(text='rectangle',fg='blue',bg='black',command=hello3).grid(row=0,column=2)\nmymenu = Menu()\nlist1 = Menu()\nlist1.add_command(label ='new file',command=hello1)\nlist1.add_command(label ='delete file')\nlist1.add_command(label ='open file')\nlist1.add_command(label ='save file',command=mbox1)\nlist1.add_command(label ='exit',command = mbox2)\nlist2 = Menu()\nlist2.add_command(label='undo')\nlist2.add_command(label='redo')\nlist2.add_command(label='cut')\nlist2.add_command(label='copy')\nlist3 = Menu()\nlist3.add_command(label='indent')\nlist3.add_command(label='tabify')\nlist3.add_command(label='toggle')\nlist3.add_command(label='dedent')\nlist4 = Menu()\nlist4.add_command(label='run')\nlist4.add_command(label='check module')\nlist4.add_command(label='python-shell')\nmymenu.add_cascade(label ='file',menu = list1)\nmymenu.add_cascade(label ='edit',menu= list2)\nmymenu.add_cascade(label ='format',menu = list3)\nmymenu.add_cascade(label ='run',menu=list4)\n\nmq.config(menu = mymenu)\n\nmq.mainloop()\n\n \n \n\n","sub_path":"messageboxlearning.py","file_name":"messageboxlearning.py","file_ext":"py","file_size_in_byte":2698,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"147595936","text":"#\n# testCount = int(input())\n#\n# for _ in range(testCount):\n# result = 1\n# people = []\n#\n# temp = int(input())\n# for _ in range(temp):\n# scores = list(map(int, input().split()))\n# people.append(scores)\n#\n# people.sort()\n#\n# min = people[0][1]\n#\n# for i in range(len(people)):\n# if people[i][1] < min:\n# min = people[i][1]\n# result += 1\n#\n# print(result)\n\nimport sys\n\nt = int(input())\n\nfor _ in range(t):\n n = int(input())\n lst = sorted([list(map(int, sys.stdin.readline().strip().split())) for x in range(n)],\n key = lambda x: x[0])\n\n cnt = 1\n min = lst[0][1]\n\n for i in range(1, n):\n if lst[i][1] < min:\n min = lst[i][1]\n cnt += 1\n\n print(cnt)","sub_path":"JeonPanGeun/pyAlgo/BOJ/1946.py","file_name":"1946.py","file_ext":"py","file_size_in_byte":787,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"532776259","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Nov 14 11:21:06 2018\n\n@author: Administrator\n@Desc: 进制数(2, 3, -1)\n\"\"\"\nfrom forecast_module import normal_setting as ns\nimport torch\nfrom forecast_module.datasets.tools import *\nfrom torch.utils.data import Dataset\nimport matplotlib.pyplot as plt\nfrom scipy.misc import imsave\n\ndataset_params = {'data_stride': 1, 'get_trend_size': 96,\n 'pic_length': 96, 'pic_stride': 10,\n 'data_width': 32, 'raw_width': 3, 'is_reshape': True\n }\n\n\nclass PictureTensorDataset(Dataset):\n def __init__(self, data_ori, points):\n print('dataset1')\n self.data_ori = data_ori\n self.data_time = data_ori['Time (UTC)']\n self.open = data_ori['Open']\n self.close = data_ori['Close']\n self.high = data_ori['High']\n self.low = data_ori['Low']\n\n self.is_verify = is_verify\n self.pic_length = dataset_params['pic_length']\n self.pic_stride = dataset_params['pic_stride']\n self.lenOfTrend = dataset_params['get_trend_size']\n self.stride = dataset_params['data_stride']\n self.data_width = dataset_params['data_width']\n self.raw_width = dataset_params['raw_width']\n self.lenOfTransform = self.pic_length + self.pic_stride * (self.data_width - 1)\n dataset_params['length'] = self.lenOfTransform\n\n if dataset_params['is_reshape'] is True:\n self.pic_width = self.data_width * self.raw_width\n else:\n self.pic_length = self.lenOfTransform\n self.pic_width = self.raw_width\n dataset_params['pic_size'] = (self.pic_width, self.pic_length)\n self.dataset_params = dataset_params\n self.points = points\n self.scale = [(n-1)*(n*n + n + 1) for n in range(1, 100, 1)]\n self.section = [-points, points]\n\n def __len__(self):\n return int((len(self.open) - self.lenOfTransform - self.lenOfTrend) / self.stride) + 1\n\n def __getitem__(self, item):\n data_close = self.close[item * self.stride: item * self.stride + self.lenOfTransform + self.lenOfTrend]\n pictureTensor_close = self.__to2dTensor(data_close[:self.lenOfTransform])\n if self.dataset_params['is_reshape']:\n pictureTensor_close = self.__reshape(pictureTensor_close)\n size = pictureTensor_close.shape\n pictureTensor = torch.zeros([1, size[0], size[1]])\n pictureTensor[0] = pictureTensor_close\n\n label = self.__getLabel(data_close[:self.lenOfTransform], data_close[-self.lenOfTrend:],\n np.max(self.high[\n item * self.stride + self.lenOfTransform: item * self.stride + self.lenOfTransform + self.lenOfTrend]),\n np.max(self.low[\n item * self.stride + self.lenOfTransform: item * self.stride + self.lenOfTransform + self.lenOfTrend]))\n return pictureTensor, label\n\n def __to2dTensor(self, data):\n lenOfTransform = len(data)\n d_min = np.min(data)\n data = data - d_min\n data_width = 3\n pic_tensor = torch.zeros((data_width, lenOfTransform))\n for i in range(lenOfTransform):\n x = data[i]\n pic_tensor[:, i] = torch.from_numpy(self.__transform(x))\n return pic_tensor\n\n\n def __get_unit(self, value):\n a = int(value * 100000)\n for i in range(len(self.scale)-1):\n if self.scale[i] <= a <= self.scale[i+1]:\n return i+2\n raise Exception('value out of the scale!(32 is max)')\n \n \n def __transform(self, value, u=2):\n a = int(value * 100000)\n l = [0 for i in range(15)]\n index = 14\n while a != 0:\n r = a % u\n l[index] = r\n index -= 1\n a = int(a / u)\n index += 1\n r = [l[index:index+2], l[index+2:index+5], l[index+5:]]\n return self.__to_dec(r)\n\n def __to_dec(self, r):\n d = [] \n for i in r:\n l = len(i)\n if l == 0:\n d.append(0)\n continue\n r_max = 2 ** l - 1\n dec = 0\n for j in range(l):\n dec = dec + i[j] * (2 ** (l-j-1))\n d.append(dec/r_max)\n if len(r[0]) == 2:\n high_scale = r[0][0] * 2 + r[0][1]\n if high_scale%2 == 1:\n #d[0] = 1 - d[0]\n d[1] = 1 - d[1]\n #d[2] = 1 - d[2]\n # print(r)\n # print(d)\n return np.array(d)\n\n def __reshape(self, pic_tensor):\n s = self.dataset_params['pic_stride'] # 滑动距离\n pic_length = self.dataset_params['pic_length'] # 每一行的数据个数\n raw_size = int((self.lenOfTransform - pic_length) / s) + 1\n p = torch.zeros(int(raw_size * self.raw_width), pic_length)\n for i in range(raw_size):\n p[i*self.raw_width:(i + 1) * self.raw_width, :] = pic_tensor[:, i * s: pic_length + i * s]\n return p\n\n def __getLabel(self, train_part, label_part, high, low):\n if ns.getLabelType == 0:\n return getLabel0(np.append(train_part[-1], label_part), self.section)\n elif ns.getLabelType == 1:\n train_part_size = 10\n return getLabel1(train_part=train_part[-train_part_size:],\n label_part=label_part)\n elif ns.getLabelType == 2:\n high_section = [0.00050]\n low_section = [0.00050]\n return getLabel2(np.append(train_part[-1], label_part), high_section, low_section, self.section,\n high, low)\n\n def __getSection(self, data, n):\n data = np.array([data[i + n] - data[i] for i in range(len(data) - n)])\n data = np.sort(data)\n is_cut = False\n class_num = self.dataset_params['output_size']\n cut_len = int(len(data) * 0.1)\n if is_cut:\n data = data[cut_len:len(data) - cut_len]\n class_cut = int(len(data) / class_num)\n Section = []\n index = 0\n for i in range(class_num - 1):\n index += class_cut\n Section.append(data[index])\n # Section.append(data[-1])\n return Section\n","sub_path":"forecast_module/datasets/dataset1.py","file_name":"dataset1.py","file_ext":"py","file_size_in_byte":6246,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"291997404","text":"import csv \r\nwith open('HeightWeight2.csv',newline='') as f: \r\n reader=csv.reader(f)\r\n fileData=list(reader)\r\nfileData.pop(0)\r\nnewData=[]\r\nfor i in range(len(fileData)):\r\n n=fileData[i][1]\r\n newData.append(float(n))\r\ntotalData=len(newData)\r\ntotal=0\r\nfor x in newData:\r\n total+=x\r\nmean=total/totalData\r\nprint(\"Mean: \", mean)","sub_path":"mean.py","file_name":"mean.py","file_ext":"py","file_size_in_byte":338,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"81334428","text":"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom compas_blender.utilities import delete_objects\nfrom compas_blender.utilities import get_objects\n\ntry:\n import bpy\nexcept ImportError:\n pass\n\n\n__all__ = [\n 'create_layer',\n 'create_layers',\n 'create_layers_from_path',\n 'create_layers_from_paths',\n 'create_layers_from_dict',\n 'clear_layer',\n 'clear_layers',\n 'clear_current_layer',\n 'delete_layer',\n 'delete_layers',\n]\n\n\n# ==============================================================================\n# create\n# ==============================================================================\n\ndef create_layer(layer):\n collection = bpy.data.collections.new(layer)\n bpy.context.scene.collection.children.link(collection)\n\n\ndef create_layers(layers):\n for layer in layers:\n create_layer(layer=layer)\n\n\ndef create_layers_from_path(path, separator='::'):\n raise NotImplementedError\n\n\ndef create_layers_from_paths(paths, separator='::'):\n for path in paths:\n create_layers_from_path(path=path)\n\n\ndef create_layers_from_dict(layers):\n raise NotImplementedError\n\n\n# ==============================================================================\n# clear\n# ==============================================================================\n\ndef clear_layer(layer):\n delete_objects(objects=get_objects(layer=layer))\n\n\ndef clear_layers(layers):\n for layer in layers:\n clear_layer(layer=layer)\n\n\ndef clear_current_layer():\n raise NotImplementedError\n\n\n# ==============================================================================\n# delete\n# ==============================================================================\n\ndef delete_layer(layer):\n collection = bpy.data.collections[layer]\n bpy.context.scene.collection.children.unlink(collection)\n bpy.ops.wm.redraw_timer(type='DRAW_WIN_SWAP', iterations=1)\n collection = bpy.data.collections[layer]\n bpy.data.collections.remove(collection)\n\n\ndef delete_layers(layers):\n for layer in layers:\n delete_layer(layer=layer)\n\n\n# ==============================================================================\n# Main\n# ==============================================================================\n\nif __name__ == \"__main__\":\n\n clear_layer(layer='Collection 1')\n\n print(list(bpy.data.collections))\n","sub_path":"src/compas_blender/utilities/layers.py","file_name":"layers.py","file_ext":"py","file_size_in_byte":2406,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"293067627","text":"import socket\r\nclass connect:\r\n\r\n # intial connection to server\r\n def __init__(self):\r\n self.HEADER = 2048\r\n self.PORT = 5050\r\n self.FMT = 'utf-8'\r\n self.DISCONNECT_MSG = \"[DISCONNECED]\"\r\n\r\n self.SERVER = '127.0.0.1'\r\n self.ADDR = (self.SERVER, self.PORT)\r\n self.client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\r\n self.client.connect(self.ADDR)\r\n\r\n # send to server\r\n def process(self, msg):\r\n message = msg.encode(self.FMT)\r\n msg_length = len(message)\r\n send_length = str(msg_length).encode(self.FMT)\r\n send_length += b' '* (self.HEADER - len(send_length))\r\n self.client.send(send_length)\r\n self.client.send(message)\r\n while True:\r\n if self.client.recv(2048):\r\n return self.client.recv(2048).decode(self.FMT)","sub_path":"AI/hub/client/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":862,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"29256534","text":"import trainer as T\n\ndef main():\n trainer = T.Trainer()\n for _ in range(5):\n trainer.collect_training_data(True, std = 0.5)\n for _ in range(1000):\n trainer.single_train_step()\n\nif __name__ == '__main__':\n main()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":238,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"342816312","text":"# coding:utf-8\n'''\n@Copyright:LintCode\n@Author: monolake\n@Problem: http://www.lintcode.com/problem/ugly-number-ii\n@Language: Python\n@Datetime: 16-11-16 16:01\n'''\n\nclass Solution:\n \"\"\"\n @param {int} n an integer.\n @return {int} the nth prime number as description.\n \"\"\"\n def nthUglyNumber(self, n):\n # write your code here\n bag = [1]\n i2 = 0\n i3 = 0\n i5 = 0\n while len(bag) < n:\n m2 = bag[i2] * 2 \n m3 = bag[i3] * 3\n m5 = bag[i5] * 5\n smallest = min(m2, m3, m5)\n if smallest == m2:\n i2 += 1\n elif smallest == m3:\n i3 += 1\n elif smallest == m5:\n i5 += 1\n if smallest not in bag:\n bag.append(smallest)\n \n return bag[-1]\n \n \n \n\n","sub_path":"4_ugly-number-ii/ugly-number-ii.py","file_name":"ugly-number-ii.py","file_ext":"py","file_size_in_byte":879,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"250994899","text":"class Solution(object):\n def flatten(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: void\n \"\"\"\n if not root:\n return\n self.helper(root)\n\n def helper(self, root):\n if not root:\n return None\n left = self.helper(root.left)\n right = self.helper(root.right)\n root.left, root.righddt = None, None\n if left:\n root.right = left\n cur = root.right\n while cur and cur.right:\n cur = cur.right\n cur.right = right\n else:\n root.right = right\n return root\n\nclass Solution2(object):\n def flatten(self, root):\n while root:\n if root.left:\n p = root.left\n while p.right:\n p = p.right\n root.right = root.left\n root.left = None\n root = root.right\n\n","sub_path":"Flatten_Binary_Tree_To_Linked_List/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":927,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"300009845","text":"#!/usr/local/Cellar/python3/3.2.2/bin/python3\n\nfrom GCJ import GCJ\nimport math\n\n\ndef choose(n, k):\n if 0 <= k <= n:\n ntok = 1\n ktok = 1\n for t in range(1, min(k, n - k) + 1):\n ntok *= n\n ktok *= t\n n -= 1\n return ntok // ktok\n else:\n return 0\n \n\n \ndef pyramid_size(sp):\n return ((2*sp-1)*(2*sp)) // 2\n\ndef solve(infile):\n N, X, Y = GCJ.readints(infile)\n if (X+Y) % 2 == 1: # keine Mitte landet hier\n return 0.0\n \n if X == 0 and Y == 0:\n return 1.0 \n # Unterpyramide berechnent\n sp = ((abs(X) + abs(Y)) // 2)\n \n min_pieces = pyramid_size(sp)\n if min_pieces >= N:\n return 0.0\n \n rest = N - min_pieces\n next_layer = pyramid_size(sp+1) - min_pieces\n one_side = (next_layer - 1) // 2\n allowed_fails = rest - Y\n if rest >= next_layer or rest >= (one_side + Y + 1):\n return 1.0\n if X == 0 and rest < next_layer:\n return 0.0\n else:\n summe = 0 \n for i in range(Y+1):\n summe += choose(rest,i)# * (0.5 ** rest)\n return 1 - (summe / (2**rest))\n \n\n\nif __name__ == \"__main__\":\n GCJ(\"B\",solve).run()","sub_path":"solutions_2700486_0/Python/xithan/B.py","file_name":"B.py","file_ext":"py","file_size_in_byte":1218,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"212791347","text":"# sub-parts of the U-Net model\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\n\nclass SeparableConv2d(nn.Module):\n def __init__(self, in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1,\n activation=nn.ELU):\n super(SeparableConv2d, self).__init__()\n self.kernel_size = kernel_size\n self.in_channels = in_channels\n self.out_channels = out_channels\n self.stride = stride\n self.padding = padding\n self.dilation = dilation\n\n self.block1 = nn.Sequential(nn.Conv2d(self.in_channels, self.out_channels, 1, bias=True),\n activation(),\n nn.Conv2d(self.out_channels, self.out_channels, self.kernel_size, self.stride,\n self.padding, self.dilation, self.out_channels, True),\n )\n\n def forward(self, input):\n return self.block1(input)\n\n\nclass SeparableConvTransposed2d(nn.Module):\n def __init__(self, in_channels, out_channels, kernel_size, stride=1, padding=0, output_padding=0, dilation=1,\n activation=nn.ELU):\n super(SeparableConvTransposed2d, self).__init__()\n self.kernel_size = kernel_size\n self.in_channels = in_channels\n self.out_channels = out_channels\n self.stride = stride\n self.padding = padding\n self.output_padding = output_padding\n self.dilation = dilation\n self.block1 = nn.Sequential(nn.Conv2d(self.in_channels, self.out_channels, 1, bias=True),\n activation(),\n nn.ConvTranspose2d(self.out_channels, self.out_channels, self.kernel_size,\n self.stride,\n self.padding, self.output_padding, self.out_channels, True),\n )\n\n def forward(self, input):\n return self.block1(input)\n\n\nclass double_conv(nn.Module):\n '''(conv => BN => ReLU) * 2'''\n\n def __init__(self, in_ch, out_ch):\n super(double_conv, self).__init__()\n self.conv = nn.Sequential(\n nn.BatchNorm2d(in_ch),\n SeparableConv2d(in_ch, out_ch, 3, padding=1),\n nn.ELU(alpha=0.1, inplace=True),\n nn.BatchNorm2d(out_ch),\n SeparableConv2d(out_ch, out_ch, 3, padding=1),\n nn.ELU(alpha=0.1, inplace=True),\n )\n\n def forward(self, x):\n x = self.conv(x)\n return x\n\n\nclass inconv(nn.Module):\n def __init__(self, in_ch, out_ch):\n super(inconv, self).__init__()\n self.conv = double_conv(in_ch, out_ch)\n\n def forward(self, x):\n x = self.conv(x)\n return x\n\n\ndef calc_pad(kernel_size=3, dilation=1):\n kernel_size = (kernel_size, kernel_size) if type(kernel_size) == int else kernel_size\n dilation = (dilation, dilation) if type(dilation) == int else dilation\n return ((kernel_size[0] - 1) * dilation[0] / 2, (kernel_size[1] - 1) * dilation[1] / 2)\n\n\nclass down(nn.Module):\n def __init__(self, in_ch, out_ch):\n kernel_size = 3\n dilation = 2\n super(down, self).__init__()\n self.mpconv = nn.Sequential(\n SeparableConv2d(in_ch, in_ch, kernel_size=kernel_size, stride=2, padding=calc_pad(kernel_size, dilation),\n dilation=dilation),\n double_conv(in_ch, out_ch)\n )\n\n def forward(self, x):\n x = self.mpconv(x)\n return x\n\n\nclass up(nn.Module):\n def __init__(self, in_ch, out_ch, bilinear=False):\n super(up, self).__init__()\n\n # would be a nice idea if the upsampling could be learned too,\n # but my machine do not have enough memory to handle all those weights\n if bilinear:\n self.up = nn.Upsample(scale_factor=2, mode='bilinear', align_corners=True)\n else:\n self.up = SeparableConvTransposed2d(in_ch // 2, in_ch // 2, 3, stride=2, padding=1, output_padding=1)\n\n self.conv = double_conv(in_ch, out_ch)\n\n def forward(self, x1, x2):\n x1 = self.up(x1)\n diffX = x1.size()[2] - x2.size()[2]\n diffY = x1.size()[3] - x2.size()[3]\n x2 = F.pad(x2, (diffX // 2, int(diffX / 2),\n diffY // 2, int(diffY / 2)))\n x = torch.cat([x2, x1], dim=1)\n x = self.conv(x)\n return x\n\n\nclass outconv(nn.Module):\n def __init__(self, in_ch, out_ch):\n super(outconv, self).__init__()\n self.conv = nn.Conv2d(in_ch, out_ch, 1)\n\n def forward(self, x):\n x = self.conv(x)\n return x\n","sub_path":"net_parts.py","file_name":"net_parts.py","file_ext":"py","file_size_in_byte":4692,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"503936466","text":"\nclass Groups(object):\n def __init__(self, client):\n \"\"\"\n client -- Seafile client object\n \"\"\"\n self.client = client\n\n def get_groups(self):\n \"\"\"\n Returns list of groups\n \"\"\"\n resp = self.client.get('/api2/groups/')\n value = resp.json()\n return value['groups']\n\n# def get_group_members(self, group_name):\n# \"\"\"\n# Returns list of members of a group\n# \"\"\"\n# groups = self.get_groups()\n# found = False\n# for i in groups:\n# if i['name'] == group_name:\n# url = '/api2/groups/{}/members/'.format(i['id'])\n# resp = self.client.get(url)\n# found = True\n# break\n# value = resp.json()\n# return value\n\n def create_group(self, group_name):\n \"\"\"\n Creates group\n\n group_name -- name\n \"\"\"\n data = {\n 'group_name': group_name,\n }\n resp = self.client.put(\n '/api2/groups/',\n data=data,\n )\n value = resp.json()\n return value\n\n def delete_group(self, group_name):\n \"\"\"\n Delete group\n\n group_name -- name\n \"\"\"\n url = '/api2/groups/{}'.format(self.get_id_from_group_name(group_name))\n resp = self.client.delete(url)\n value = resp.json()\n return value\n\n def get_id_from_group_name(self, group_name):\n groups = self.get_groups()\n for i in groups:\n if i['name'] == group_name:\n return i['id']\n\n raise ValueError('Group {} not found'.format(group_name))\n\n\n# class Group(object):\n# def __init__(self, client, group_id, group_name):\n# self.client = client\n# self.group_id = group_id\n# self.group_name = group_name\n# \n# def list_memebers(self):\n# pass\n# \n# def delete(self):\n# pass\n# \n# def add_member(self, username):\n# pass\n# \n# def remove_member(self, username):\n# pass\n# \n# def list_group_repos(self):\n# pass\n","sub_path":"seafileapi/group.py","file_name":"group.py","file_ext":"py","file_size_in_byte":2107,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"465424649","text":"#!/usr/bin/env python\r\n\r\nimport sys\r\nimport os\r\nimport subprocess\r\nimport shutil\r\nimport logging\r\n\r\ntry:\r\n from setuptools import setup, Extension\r\nexcept ImportError:\r\n from distutils.core import setup, Extension\r\n\r\nfrom distutils.command.build import build\r\nfrom distutils.command.install import install\r\n\r\nfrom settings import *\r\n\r\nlog = logging.getLogger()\r\n\r\n\r\ndef exec_cmd(cmdline, *args, **kwargs):\r\n msg = kwargs.get('msg')\r\n cwd = kwargs.get('cwd', '.')\r\n output = kwargs.get('output')\r\n\r\n if msg:\r\n print(msg)\r\n\r\n cmdline = ' '.join([cmdline] + list(args))\r\n\r\n proc = subprocess.Popen(cmdline,\r\n shell = kwargs.get('shell', True),\r\n cwd = cwd,\r\n env = kwargs.get('env'),\r\n stdout = subprocess.PIPE if output else None,\r\n stderr = subprocess.PIPE if output else None)\r\n\r\n stdout, stderr = proc.communicate()\r\n\r\n succeeded = proc.returncode == 0\r\n\r\n if not succeeded:\r\n log.error(\"%s failed: code = %d\", msg or \"Execute command\", proc.returncode)\r\n\r\n if output:\r\n log.debug(stderr)\r\n\r\n return succeeded, stdout, stderr if output else succeeded\r\n\r\n\r\ndef install_depot():\r\n if not os.path.exists(DEPOT_HOME):\r\n exec_cmd(\"git clone\",\r\n DEPOT_GIT_URL,\r\n DEPOT_HOME,\r\n cwd = os.path.dirname(DEPOT_HOME),\r\n msg = \"Cloning depot tools\")\r\n\r\n return\r\n\r\n # depot_tools updates itself automatically when running gclient tool\r\n if os.path.isfile(os.path.join(DEPOT_HOME, 'gclient')):\r\n _, stdout, _ = exec_cmd(os.path.join(DEPOT_HOME, 'gclient'),\r\n \"--version\",\r\n cwd = DEPOT_HOME,\r\n output = True,\r\n msg = \"Found depot tools\")\r\n\r\n\r\ndef checkout_v8():\r\n if not os.path.exists(V8_HOME):\r\n exec_cmd(os.path.join(DEPOT_HOME, 'fetch'),\r\n 'v8',\r\n cwd = os.path.dirname(V8_HOME),\r\n msg = \"Fetching Google V8 code\")\r\n\r\n exec_cmd('git fetch --tags',\r\n cwd = V8_HOME,\r\n msg = \"Fetching the release tag information\")\r\n\r\n exec_cmd('git checkout',\r\n V8_GIT_TAG,\r\n cwd = V8_HOME,\r\n msg = \"Checkout Google V8 v{}\".format(V8_GIT_TAG))\r\n\r\n exec_cmd(os.path.join(DEPOT_HOME, 'gclient'),\r\n 'sync',\r\n '-D',\r\n cwd = os.path.dirname(V8_HOME),\r\n msg = \"Syncing Google V8 code\")\r\n\r\n # On Linux, install additional dependencies, per\r\n # https://v8.dev/docs/build step 4\r\n if sys.platform in (\"linux\", \"linux2\", ) and v8_deps_linux:\r\n exec_cmd('./v8/build/install-build-deps.sh',\r\n cwd = os.path.dirname(V8_HOME),\r\n msg = \"Installing additional linux dependencies\")\r\n\r\ndef build_v8():\r\n exec_cmd(os.path.join(DEPOT_HOME, 'gn'),\r\n \"gen out.gn/x64.release.sample --args='{}'\".format(GN_ARGS),\r\n cwd = V8_HOME,\r\n msg = \"Generate build scripts for V8 (v{})\".format(V8_GIT_TAG))\r\n\r\n exec_cmd(os.path.join(DEPOT_HOME, 'ninja'),\r\n \"-C out.gn/x64.release.sample v8_monolith\",\r\n cwd = V8_HOME,\r\n msg = \"Build V8 with ninja\")\r\n\r\n\r\ndef clean_stpyv8():\r\n build_folder = os.path.join(STPYV8_HOME, 'build')\r\n\r\n if os.path.exists(os.path.join(build_folder)):\r\n shutil.rmtree(build_folder)\r\n\r\n\r\ndef prepare_v8():\r\n try:\r\n install_depot()\r\n checkout_v8()\r\n build_v8()\r\n clean_stpyv8()\r\n except Exception as e:\r\n log.error(\"Fail to checkout and build v8, %s\", str(e))\r\n\r\n\r\nclass stpyv8_build(build):\r\n def run(self):\r\n V8_GIT_TAG = V8_GIT_TAG_STABLE\r\n prepare_v8()\r\n build.run(self)\r\n\r\n\r\nclass stpyv8_develop(build):\r\n def run(self):\r\n V8_GIT_TAG = V8_GIT_TAG_MASTER\r\n prepare_v8()\r\n build.run(self)\r\n\r\n\r\nclass stpyv8_install_v8(build):\r\n def run(self):\r\n V8_GIT_TAG = V8_GIT_TAG_MASTER\r\n prepare_v8()\r\n\r\n\r\nclass stpyv8_build_no_v8(build):\r\n def run(self):\r\n clean_stpyv8()\r\n build.run(self)\r\n\r\n\r\nclass stpyv8_install(install):\r\n def run(self):\r\n self.skip_build = True\r\n\r\n if icu_data_folder:\r\n os.makedirs(icu_data_folder, exist_ok = True)\r\n shutil.copy(os.path.join(V8_HOME, \"out.gn/x64.release.sample/icudtl.dat\"),\r\n icu_data_folder)\r\n\r\n install.run(self)\r\n\r\n\r\nstpyv8 = Extension(name = \"_STPyV8\",\r\n sources = [os.path.join(\"src\", source) for source in source_files],\r\n define_macros = macros,\r\n include_dirs = include_dirs,\r\n library_dirs = library_dirs,\r\n libraries = libraries,\r\n extra_compile_args = extra_compile_args,\r\n extra_link_args = extra_link_args,\r\n )\r\n\r\nsetup(name = \"stpyv8\",\r\n version = STPYV8_VERSION,\r\n description = \"Python Wrapper for Google V8 Engine\",\r\n platforms = \"x86\",\r\n author = \"Philip Syme, Angelo Dell'Aera\",\r\n url = \"https://github.com/area1/stpyv8\",\r\n license = \"Apache License 2.0\",\r\n py_modules = [\"STPyV8\"],\r\n ext_modules = [stpyv8],\r\n classifiers = [\r\n \"Development Status :: 4 - Beta\",\r\n \"Environment :: Plugins\",\r\n \"Intended Audience :: Developers\",\r\n \"Intended Audience :: System Administrators\",\r\n \"License :: OSI Approved :: Apache Software License\",\r\n \"Natural Language :: English\",\r\n \"Operating System :: POSIX\",\r\n \"Programming Language :: C++\",\r\n \"Programming Language :: Python\",\r\n \"Topic :: Internet\",\r\n \"Topic :: Internet :: WWW/HTTP\",\r\n \"Topic :: Software Development\",\r\n \"Topic :: Software Development :: Libraries :: Python Modules\",\r\n \"Topic :: Utilities\",\r\n ],\r\n cmdclass = dict(\r\n build = stpyv8_build,\r\n develop = stpyv8_develop,\r\n v8 = stpyv8_install_v8,\r\n stpyv8 = stpyv8_build_no_v8,\r\n install = stpyv8_install),\r\n)\r\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":6422,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"438668552","text":"#!/usr/bin/env python\nimport os, sys, inspect\ncurrentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))\nparentdir = os.path.dirname(currentdir)\n#parentdir = os.path.dirname(parentdir)\nsys.path.insert(1,'/usr/local/lib/python3.5/dist-packages')\nfrom sklearn import linear_model\nfrom sklearn.metrics import mean_squared_error\n\nimport numpy as np,math\n\nfrom keras.layers import Input, LSTM\nfrom keras.models import Model\nimport keras\nfrom keras import backend as K\n #set learning phase\nK.set_learning_phase(1)\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Dropout, Flatten\nfrom keras.layers import Conv2D, MaxPooling2D\nfrom keras.optimizers import SGD,RMSprop,Adam\nfrom keras.models import load_model\nfrom keras.layers import TimeDistributed\nfrom utils.common import *\n\n\nclass rcnn_total_model:\n def __init__(self,complete_cached_model):\n\n\n #Inputs\n pose_input = Input(shape=(sequence_length,pose_data_dims[0]*pose_data_dims[1]))\n video_input = Input(shape=(sequence_length, IM_HEIGHT_model, IM_WIDTH_model, NUMBER_CHANNELS))\n\n\n #IMAGES RCNN MODE\n self.cnnmodel = self.get_cnn_model(conv1_size,conv2_size,no_layers)\n encoded_frame_sequence = TimeDistributed(self.cnnmodel)(video_input) # the output will be a sequence of vectors\n encoded_video_1 = LSTM(64)(encoded_frame_sequence)\n self.encoded_video = Dense(32)\n encoded_video = self.encoded_video(encoded_video_1)\n\n\n #POSE SEQUENCE MODEL\n self.posemodel = self.get_pose_model()\n pose_model_branch = self.posemodel(pose_input)\n\n #Total MODEL\n output_branches = keras.layers.Concatenate(axis=-1)([encoded_video,pose_model_branch])\n final_dense = Dense(64, activation='linear')(output_branches)\n total_output= Dense(number_outputs, activation='linear')(final_dense)\n self.total_model = Model(inputs=[video_input,pose_input], outputs=total_output)\n\n self.total_model = load_model(complete_cached_model)\n\n sgd = SGD(lr=10**(-3.5), decay=10**(-6), momentum=0.9, nesterov=True)\n self.total_model.compile(loss='mse', optimizer=sgd)\n\n\n\n def get_cnn_model(self,conv1_size,conv2_size,no_layers):\n cnnmodel = Sequential()\n cnnmodel.add(Conv2D(20, (3, 3), activation='relu', input_shape=(IM_HEIGHT, IM_WIDTH, NUMBER_CHANNELS)))\n cnnmodel.add(MaxPooling2D(pool_size=(2, 2)))\n cnnmodel.add(Dropout(0.25))\n cnnmodel.add(Conv2D(32, (3, 3), activation='relu'))\n cnnmodel.add(MaxPooling2D(pool_size=(2, 2)))\n cnnmodel.add(Dropout(0.25))\n cnnmodel.add(Flatten())\n return cnnmodel\n\n def get_pose_model(self):\n # expected input data shape: (batch_size, timesteps, data_dim)\n model = Sequential()\n model.add(LSTM(63, return_sequences=True,input_shape=(sequence_length,pose_data_dims[0]*pose_data_dims[1]))) # returns a sequence of vectors of dimension 32\n model.add(LSTM(53, return_sequences=True)) # returns a sequence of vectors of dimension 32\n model.add(LSTM(32)) # return a single vector of dimension 32\n return model\n\n def predict(self,x,x_images):\n return self.total_model.predict(x_images,x)\n","sub_path":"src/MovementModels/cyclist_rnn_model.py","file_name":"cyclist_rnn_model.py","file_ext":"py","file_size_in_byte":3244,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"570551108","text":"#!/usr/bin/env python\n\n__project_name__ = 'Pancake chat bot (HipChat edition)'\n__version__ = '2.1.0'\n\nimport argparse\nimport src as library\n\nif __name__ == \"__main__\":\n\n print(__project_name__ + ', version ' + __version__)\n\n parser = argparse.ArgumentParser()\n parser.add_argument('-c', '--config', help='config file to be used')\n\n args = parser.parse_args()\n\n # Config to use\n conf_name = args.config\n settings = library.config.Settings(conf_name)\n\n bot = library.Bot(settings.get())\n\n bot.join_rooms(settings.get('general:rooms'))\n bot.start()\n","sub_path":"pancake.py","file_name":"pancake.py","file_ext":"py","file_size_in_byte":576,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"549413665","text":"class Solution:\n \"\"\"\n @param s: the maximum length of s is 1000\n @return: the longest palindromic subsequence's length\n \"\"\"\n\n def longestPalindromeSubseq(self, s):\n # write your code here\n n = len(s)\n dp = [1] * n\n\n for i in range(n - 1, -1, -1):\n length = 0\n for j in range(i + 1, n):\n t = dp[j]\n if s[i] == s[j]: dp[j] = length + 2\n length = max(length, t)\n\n return max(dp) if dp else 0\n","sub_path":"lintcode/667-longest-palindromic-subsequence.py","file_name":"667-longest-palindromic-subsequence.py","file_ext":"py","file_size_in_byte":506,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"149567152","text":"#!/usr/bin/python\nimport sys\nimport os\nimport json\n\ndef gen_labels(src=\"./text.txt\",dist=\"../data/labels.txt\"):\n text_file = os.path.join(sys.path[0],src)\n fr = open(text_file,\"r+\",encoding=\"utf-8\")\n content = fr.read().replace(\"\\n\",\"\").replace(\" \",\"\")\n labels = get_labels(dist)\n cnt = len(labels)\n labels_file = os.path.join(sys.path[0], dist)\n fw = open(labels_file, \"w+\", encoding=\"utf-8\")\n for index,char in enumerate(content,cnt+1):\n if char != None and char not in labels.values():\n key = str(index).zfill(5)\n labels[key] = char\n json_labels = json.dumps(labels)\n fw.write(json_labels)\n fw.close()\n return labels\n\n\ndef get_labels(src=\"../data/labels.txt\"):\n labels_file = os.path.join(sys.path[0], src)\n labels = {}\n if not os.path.exists(labels_file):\n return labels\n fr = open(labels_file, \"r+\", encoding=\"utf-8\")\n labels_content = fr.read().strip().replace(\"\\n\", \"\")\n fr.close()\n if len(labels_content) > 0:\n labels = json.loads(labels_content)\n return labels\n\n\nif __name__ == \"__main__\":\n labels = gen_labels(\"../../assets/text.txt\",\"../../data/labels.txt\")\n # labels = get_labels()\n # for (key,char) in labels.items():\n # print(key+\":\"+char)","sub_path":"src/shencom/labels.py","file_name":"labels.py","file_ext":"py","file_size_in_byte":1273,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"6"} +{"seq_id":"654465110","text":"# coding: utf-8\n\n\"\"\"\n EVR API\n\n OpenAPI Generator'i jaoks kohandatud EVR API kirjeldus. Kasuta seda juhul, kui spetsifikatsioonile vastava EVR API kirjeldusega ei õnnestu klienti genereerida. # noqa: E501\n\n The version of the OpenAPI document: 1.8.0\n Generated by: https://openapi-generator.tech\n\"\"\"\n\n\nfrom __future__ import absolute_import\n\nimport re # noqa: F401\n\n# python 2 and python 3 compatibility library\nimport six\n\nfrom pyevr.openapi_client.api_client import ApiClient\nfrom pyevr.openapi_client.exceptions import ( # noqa: F401\n ApiTypeError,\n ApiValueError\n)\n\n\nclass AssortmentsApi(object):\n \"\"\"NOTE: This class is auto generated by OpenAPI Generator\n Ref: https://openapi-generator.tech\n\n Do not edit the class manually.\n \"\"\"\n\n def __init__(self, api_client=None):\n if api_client is None:\n api_client = ApiClient()\n self.api_client = api_client\n\n def assortments_list(self, **kwargs): # noqa: E501\n \"\"\"Sortimentide pärimine # noqa: E501\n\n Tagastab EVR-i aktiivsed sortimendid. # noqa: E501\n This method makes a synchronous HTTP request by default. To make an\n asynchronous HTTP request, please pass async_req=True\n >>> thread = api.assortments_list(async_req=True)\n >>> result = thread.get()\n\n :param async_req bool: execute request asynchronously\n :param int page: Tagastatav lehekülg\n :param str evr_language: Defineerib keele tagastatavatele veateadetele (toetatud on väärtused \\\"et\\\" eesti keele ning \\\"en\\\" inglise keele jaoks).\n :param _preload_content: if False, the urllib3.HTTPResponse object will\n be returned without reading/decoding response\n data. Default is True.\n :param _request_timeout: timeout setting for this request. If one\n number provided, it will be total request\n timeout. It can also be a pair (tuple) of\n (connection, read) timeouts.\n :return: PagedResultOfAssortment\n If the method is called asynchronously,\n returns the request thread.\n \"\"\"\n kwargs['_return_http_data_only'] = True\n return self.assortments_list_with_http_info(**kwargs) # noqa: E501\n\n def assortments_list_with_http_info(self, **kwargs): # noqa: E501\n \"\"\"Sortimentide pärimine # noqa: E501\n\n Tagastab EVR-i aktiivsed sortimendid. # noqa: E501\n This method makes a synchronous HTTP request by default. To make an\n asynchronous HTTP request, please pass async_req=True\n >>> thread = api.assortments_list_with_http_info(async_req=True)\n >>> result = thread.get()\n\n :param async_req bool: execute request asynchronously\n :param int page: Tagastatav lehekülg\n :param str evr_language: Defineerib keele tagastatavatele veateadetele (toetatud on väärtused \\\"et\\\" eesti keele ning \\\"en\\\" inglise keele jaoks).\n :param _return_http_data_only: response data without head status code\n and headers\n :param _preload_content: if False, the urllib3.HTTPResponse object will\n be returned without reading/decoding response\n data. Default is True.\n :param _request_timeout: timeout setting for this request. If one\n number provided, it will be total request\n timeout. It can also be a pair (tuple) of\n (connection, read) timeouts.\n :return: tuple(PagedResultOfAssortment, status_code(int), headers(HTTPHeaderDict))\n If the method is called asynchronously,\n returns the request thread.\n \"\"\"\n\n local_var_params = locals()\n\n all_params = [\n 'page',\n 'evr_language'\n ]\n all_params.extend(\n [\n 'async_req',\n '_return_http_data_only',\n '_preload_content',\n '_request_timeout'\n ]\n )\n\n for key, val in six.iteritems(local_var_params['kwargs']):\n if key not in all_params:\n raise ApiTypeError(\n \"Got an unexpected keyword argument '%s'\"\n \" to method assortments_list\" % key\n )\n local_var_params[key] = val\n del local_var_params['kwargs']\n\n if self.api_client.client_side_validation and 'page' in local_var_params and local_var_params['page'] > 2147483647: # noqa: E501\n raise ApiValueError(\"Invalid value for parameter `page` when calling `assortments_list`, must be a value less than or equal to `2147483647`\") # noqa: E501\n if self.api_client.client_side_validation and 'page' in local_var_params and local_var_params['page'] < 1: # noqa: E501\n raise ApiValueError(\"Invalid value for parameter `page` when calling `assortments_list`, must be a value greater than or equal to `1`\") # noqa: E501\n collection_formats = {}\n\n path_params = {}\n\n query_params = []\n if 'page' in local_var_params and local_var_params['page'] is not None: # noqa: E501\n query_params.append(('page', local_var_params['page'])) # noqa: E501\n\n header_params = {}\n if 'evr_language' in local_var_params:\n header_params['EVR-LANGUAGE'] = local_var_params['evr_language'] # noqa: E501\n\n form_params = []\n local_var_files = {}\n\n body_params = None\n # HTTP header `Accept`\n header_params['Accept'] = self.api_client.select_header_accept(\n ['application/json']) # noqa: E501\n\n # Authentication setting\n auth_settings = ['SecretApiKey'] # noqa: E501\n\n return self.api_client.call_api(\n '/api/assortments', 'GET',\n path_params,\n query_params,\n header_params,\n body=body_params,\n post_params=form_params,\n files=local_var_files,\n response_type='PagedResultOfAssortment', # noqa: E501\n auth_settings=auth_settings,\n async_req=local_var_params.get('async_req'),\n _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501\n _preload_content=local_var_params.get('_preload_content', True),\n _request_timeout=local_var_params.get('_request_timeout'),\n collection_formats=collection_formats)\n","sub_path":"pyevr/openapi_client/api/assortments_api.py","file_name":"assortments_api.py","file_ext":"py","file_size_in_byte":6639,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"6"} +{"seq_id":"139253405","text":"from django import template\nfrom datetime import datetime, timezone, timedelta\n\nregister = template.Library()\n\n@register.simple_tag\ndef split(value, arg):\n return value.split(arg)\n\n@register.simple_tag\ndef calculatetime(value):\n\n difference = datetime.now(timezone.utc) - timedelta(hours=5) - value\n if difference.days > 0:\n if difference.days == 1:\n return \"1 day ago\"\n else:\n return str(difference.days) + \" days ago\"\n\n hours = int(float(difference.seconds / 3600))\n if hours >= 1:\n if hours == 1:\n return \"1 hour ago\"\n else:\n return str(hours) + \" hours ago\"\n\n minutes = int(float(difference.seconds / 60))\n if minutes <= 2:\n return \"just now\"\n else:\n return str(minutes) + \" minutes ago\"","sub_path":"user_profile/templatetags/split_words 2.py","file_name":"split_words 2.py","file_ext":"py","file_size_in_byte":801,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"6"} +{"seq_id":"554478291","text":"# PRINT THE CHARACTERS ALONG WITH NEXT SPECIFIED POSITION OF THE STRING\n# a4c0b1 => aeccbc\ns = input('ENTER A STRING :')\nres = ''\nfor ch in s:\n if ch.isalpha():\n res += ch\n x = ch\n else:\n d = int(ch)\n res = res + chr(ord(x)+d)\nprint(res)","sub_path":"01-BASICS/22-chrSpecifiedPosition.py","file_name":"22-chrSpecifiedPosition.py","file_ext":"py","file_size_in_byte":272,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"6"} +{"seq_id":"241684738","text":"def bank(x,y):\r\n x = int(x)\r\n y = int(y)\r\n return (x*y*0.1)+x\r\n\r\nprint(\"Введите сумму денег и количество лет\")\r\n\r\na = input()\r\na = a.split()\r\n\r\nprint(bank(a[0], a[1]))","sub_path":"trash/bank.py","file_name":"bank.py","file_ext":"py","file_size_in_byte":207,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"6"} +{"seq_id":"90489455","text":"import time\nstart = time.time()\n\nA = 1\nB = 1\nfibo_total = 0\n\nwhile(A+B<4000000):\n if (A+B) % 2 == 0:\n fibo_total += A+B\n A, B = B, A+B\n\nprint('Euler n°2 answer :', fibo_total)\nprint('Find in :', \"%.2f\" % (time.time()-start),'sec')\n","sub_path":"001-020/Euler_002.py","file_name":"Euler_002.py","file_ext":"py","file_size_in_byte":245,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"6"} +{"seq_id":"598783655","text":"#app.py\nfrom flask import Flask, request, render_template\nimport urllib\nimport numpy as np\n\nimport matplotlib.pyplot as plt\nfrom matplotlib.dates import date2num\n\nfrom io import BytesIO\n\nimport pandas as pd\nfrom datetime import datetime, timedelta\n\napp = Flask(__name__)\n\n\n\n@app.route(\"/\")\ndef index():\n return render_template(\"index.html\")\n\n@app.route(\"/plot/btc\")\ndef plot_btc():\n\n # Obtain query parameters\n start = datetime.strptime(request.args.get(\"start\", default=\"2017-12-01\", type=str), \"%Y-%m-%d\")\n end = datetime.strptime(request.args.get(\"end\", default=\"2018-12-01\", type=str), \"%Y-%m-%d\")\n aval = request.args.get(\"aval\", default=15, type=float)\n place=request.args.get(\"place\", default=\"Nagoya\",type=str)\n place2=request.args.get(\"place2\", default=\"Naha\",type=str)\n place3=request.args.get(\"place3\", default=\"Sapporo\",type=str)\n \n df = pd.read_csv(\"temperature.csv\", index_col = 0, parse_dates=True)\n \n \n fig = plt.figure(figsize=(10,5),dpi=100)\n\n ax= fig.add_subplot(211)\n ax2= fig.add_subplot(212)\n \n \n \n ax.plot(df[ place] ,label=place)\n ax.plot(df[ place2] ,label=place2)\n ax.plot(df[ place3] ,label=place3)\n if start > end:\n start, end = end, start\n if (start + timedelta(days=7)) > end:\n end = start + timedelta(days=7)\n\n png_out = BytesIO()\n\n ax.set_xlim([start, end])\n plt.ylim(ymax=32)\n plt.ylim(ymin=-8)\n \n \n ax.set_ylabel(\"temperature\")\n plt.xticks(rotation=30)\n \n \n \n df['average'] = (df[place] + df[place2]+ df[place3])/3\n df[\"Place1\"] = df[place]-df['average']\n df[\"Place2\"] = df[place2]-df['average']\n df[\"Place3\"] = df[place3]-df['average']\n ax2.plot(df[ \"Place1\"] ,label=place)\n ax2.plot(df[ \"Place2\"] ,label=place2)\n ax2.plot(df[ \"Place3\"] ,label=place3)\n ax2.set_ylim([-aval, aval])\n ax2.set_ylabel(\"Temperature difference from average\")\n ax2.set_xlim([start, end])\n plt.legend(loc='upper right')\n \n\n\n plt.savefig(png_out, format=\"png\", bbox_inches=\"tight\")\n img_data = urllib.parse.quote(png_out.getvalue())\n \n \n\n\n return \"data:image/png:base64,\" + img_data\n\n\n\n\n\nif __name__ == \"__main__\":\n app.run(debug=True, port=5000)\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2226,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"6"} +{"seq_id":"331784486","text":"# -*- coding: utf-8 -*-\n# @Author: Gillett Hernandez\n# @Date: 2017-08-01 10:50:00\n# @Last Modified by: Gillett Hernandez\n# @Last Modified time: 2017-09-16 23:28:43\n\nfrom euler_funcs import timed, is_square\n\ndef is_triangle(n):\n # root^2 + root - 2n = 0\n # root = (sqrt(1+4*2*n)-1) / (2)\n inner = 1+4*2*n\n # print(inner, inner**0.5, int(inner**0.5)**2, int(inner**0.5)-1)\n return is_square(inner) and (int(inner**0.5)-1) % 2 == 0\n\ns = ord(\"A\")-1\ndef word_score(word):\n return sum(ord(c)-s for c in word)\n\n@timed\ndef main():\n words = []\n with open(\"../p042_words.txt\", \"r\") as fd:\n words = [word.strip().strip(\"\\\"\").strip() for word in fd.read().split(\",\")]\n # print(word_score(\"SKY\"), is_triangle(word_score(\"SKY\")))\n c = 0\n for word in words:\n if is_triangle(word_score(word)):\n c += 1\n print(c)\n\nif __name__ == '__main__':\n main()\n","sub_path":"Python/problem_42.py","file_name":"problem_42.py","file_ext":"py","file_size_in_byte":900,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"334488722","text":"import tensorflow as tf\r\nimport numpy as np\r\nimport h5py\r\nimport os\r\nfrom tensorflow.python.framework import ops\r\nimport BN_forward\r\nimport BN_backward\r\nn_x = 64\r\nn_y = 6\r\n\r\ndef sleep_stage_test(X_test, Y_test):\r\n with tf.Graph().as_default() as g:\r\n X = tf.placeholder(tf.float32, [None, n_x])\r\n Y = tf.placeholder(tf.float32, [None, n_y])\r\n parameters = BN_forward.initialize_para()\r\n Y_prediction = BN_forward.forward_prob(X, parameters, 1, is_training = False)\r\n saver = tf.train.Saver()\r\n correct_prediction = tf.equal(tf.argmax(Y_prediction, axis = 1), tf.argmax(Y, axis = 1))\r\n accuracy = tf.reduce_mean(tf.cast(correct_prediction, \"float\"))\r\n with tf.Session() as sess:\r\n ckpt = tf.train.get_checkpoint_state(BN_backward.Modelpath)\r\n if ckpt and ckpt.model_checkpoint_path:\r\n saver.restore(sess, ckpt.model_checkpoint_path)\r\n global_step = ckpt.model_checkpoint_path.split('/')[-1].split('-')[-1]\r\n accuracy_store = sess.run(accuracy, feed_dict= {X: X_test, Y: Y_test})\r\n print('after %s training-steps, dev/test accuracy = %g' % (global_step, accuracy_store))\r\n else:\r\n print('No Model file found')\r\n\r\ndef main():\r\n filepath = 'D:\\\\sa\\\\features\\\\TrainSet_20186501.h5'\r\n file = h5py.File(filepath, 'r')\r\n EEG_1 = file['EEG_1'][:]\r\n EEG_2 = file['EEG_2'][:]\r\n EEG = np.concatenate((EEG_1, EEG_2), axis=0)\r\n mean = np.reshape(np.mean(EEG, axis=1), [EEG.shape[0], 1])\r\n std = np.reshape(np.std(EEG, axis=1), [EEG.shape[0], 1])\r\n EEG -= mean\r\n EEG /= std\r\n print(np.mean(EEG[0, :]))\r\n print(np.std(EEG[0, :]))\r\n X_test = EEG[:, 90000:100000].T\r\n file.close()\r\n\r\n labelpath = 'D:\\\\sa\\\\features\\\\TrainSet_20186500.h5'\r\n file = h5py.File(labelpath, 'r')\r\n labels = file['train_set_num'][:]\r\n labels = np.squeeze(labels)\r\n labels_one = BN_backward.one_hot_matrix(labels, 6)\r\n Y_test= labels_one[:,90000:100000].T\r\n sleep_stage_test(X_test, Y_test)\r\n\r\nif __name__ == \"__main__\":\r\n main()\r\n print('test')\r\n","sub_path":"SA_source/DNN-BN_tensorflow/BN_test.py","file_name":"BN_test.py","file_ext":"py","file_size_in_byte":2137,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"212622295","text":"from zipline.api import order_target, record, symbol, history, add_history, order\n\nimport logbook\nlog = logbook.Logger('test')\n\ndef initialize(context):\n # Register 2 histories that track daily prices,\n # one with a 100 window and one with a 300 day window\n add_history(5, '1d', 'price')\n add_history(10, '1d', 'price')\n\n context.i = 0\n context.invested = False\n\ndef handle_data(context, data):\n # Skip first 300 days to get full windows\n context.i += 1\n if context.i < 10:\n return\n\n # Compute averages\n # history() has to be called with the same params\n # from above and returns a pandas dataframe.\n short_mavg = history(5, '1d', 'price').mean()\n long_mavg = history(10, '1d', 'price').mean()\n\n for sym in data:\n # sym = data.keys()[0]\n # sym = data.keys()[0]\n\n # Trading logic\n if short_mavg[sym] > long_mavg[sym] and not context.invested:\n # order_target orders as many shares as needed to\n # achieve the desired number of shares.\n order_target(sym, 5000)\n context.invested = True\n elif short_mavg[sym] < long_mavg[sym] and context.invested:\n order_target(sym, 0)\n context.invested = False\n # Save values for later inspection\n # record(close=data[sym].price,\n # short_mavg=short_mavg[sym],\n # long_mavg=long_mavg[sym])\n","sub_path":"algorithms/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1417,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"558431087","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Nov 10 18:08:34 2019\n\n@author: hiuhongkwan\n\"\"\"\nimport requests\nimport json\n# Complete the function below.\n# Base url: https://jsonmock.hackerrank.com/api/movies/search/?Title=\n\ndef getMovieTitles(substr):\n baseUrl = \"https://jsonmock.hackerrank.com/api/movies/search/?Title=\" + substr\n extraPages = \"&page=\"\n\n #now we are going to request the json and first we get the total no of pages\n r = requests.get(url = baseUrl) \n jsonResponse = r.json()\n totalNoOfPages = jsonResponse[\"total_pages\"]\n totalNoOfRecords = jsonResponse[\"total\"]\n titlesArray = []\n \n #request pages one by one\n for page in range(1, totalNoOfPages+1):\n pageUrl = baseUrl + extraPages + str(page)\n request = requests.get(url = pageUrl)\n pageJson = request.json()\n data = pageJson[\"data\"]\n for jsonObj in data:\n titlesArray.append(jsonObj[\"Title\"])\n \n titlesArray.sort()\n return titlesArray\n\ngetMovieTitles(\"spiderman\")\n","sub_path":"Macquarie_Hackerrank_Question/Macquarie_interview.py","file_name":"Macquarie_interview.py","file_ext":"py","file_size_in_byte":1043,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"351425780","text":"\n\nfrom xai.brain.wordbase.nouns._copycat import _COPYCAT\n\n#calss header\nclass _COPYCATS(_COPYCAT, ):\n\tdef __init__(self,): \n\t\t_COPYCAT.__init__(self)\n\t\tself.name = \"COPYCATS\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"copycat\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_copycats.py","file_name":"_copycats.py","file_ext":"py","file_size_in_byte":245,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"466628999","text":"def firstOrDefault(iterable, criteria=None, default=None):\n if iterable:\n for item in iterable:\n if(criteria is None):\n return item\n else:\n attrValue = getattr(item, criteria[\"key\"])\n if(attrValue == criteria[\"value\"]):\n return item\n \n return default\n","sub_path":"Blog/helpers/CollectionHelper.py","file_name":"CollectionHelper.py","file_ext":"py","file_size_in_byte":365,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"459542659","text":"import logging\nimport select\nimport subprocess\n\nfrom middlewared.utils import run\nfrom middlewared.utils.osc import IS_LINUX\n\nfrom .base_state import ServiceState\n\nlogger = logging.getLogger(__name__)\n\nif IS_LINUX:\n from pystemd.base import SDObject\n from pystemd.dbusexc import DBusUnknownObjectError\n from pystemd.dbuslib import DBus\n from pystemd.systemd1 import Unit\n\n class Job(SDObject):\n def __init__(self, job, bus=None, _autoload=False):\n super().__init__(\n destination=b\"org.freedesktop.systemd1\",\n path=job,\n bus=bus,\n _autoload=_autoload,\n )\n\n\nclass SimpleServiceLinux:\n systemd_unit = NotImplemented\n systemd_extra_units = []\n\n async def _get_state_linux(self):\n return await self.middleware.run_in_thread(self._get_state_linux_sync)\n\n def _get_state_linux_sync(self):\n unit = self._get_systemd_unit()\n\n if unit.Unit.ActiveState == b\"active\":\n return ServiceState(True, list(filter(None, [unit.MainPID])))\n else:\n return ServiceState(False, [])\n\n async def _start_linux(self):\n await self._unit_action(\"Start\")\n\n async def _stop_linux(self):\n await self._unit_action(\"Stop\")\n\n async def _restart_linux(self):\n await self._unit_action(\"Restart\")\n\n async def _reload_linux(self):\n await self._unit_action(\"Reload\")\n\n async def _identify_linux(self, procname):\n pass\n\n def _get_systemd_unit(self):\n unit = Unit(f\"{self.systemd_unit}.service\".encode())\n unit.load()\n return unit\n\n async def _unit_action(self, action, wait=True, timeout=5):\n return await self.middleware.run_in_thread(self._unit_action_sync, action, wait, timeout)\n\n def _unit_action_sync(self, action, wait, timeout):\n unit = self._get_systemd_unit()\n job = getattr(unit.Unit, action)(b\"replace\")\n\n if wait:\n with DBus() as bus:\n done = False\n\n def callback(msg, error=None, userdata=None):\n nonlocal done\n\n msg.process_reply(True)\n\n if msg.body[1] == job:\n done = True\n\n bus.match_signal(\n b\"org.freedesktop.systemd1\",\n b\"/org/freedesktop/systemd1\",\n b\"org.freedesktop.systemd1.Manager\",\n b\"JobRemoved\",\n callback,\n None,\n )\n\n job_object = Job(job, bus)\n try:\n job_object.load()\n except DBusUnknownObjectError:\n # Job has already completed\n return\n\n fd = bus.get_fd()\n while True:\n fds = select.select([fd], [], [], timeout)\n if not any(fds):\n break\n\n bus.process()\n\n if done:\n break\n\n async def _systemd_unit(self, unit, verb):\n await systemd_unit(unit, verb)\n\n\nasync def systemd_unit(unit, verb):\n result = await run(\"systemctl\", verb, unit, check=False, encoding=\"utf-8\", stderr=subprocess.STDOUT)\n if result.returncode != 0:\n logger.warning(\"%s %s failed with code %d: %r\", unit, verb, result.returncode, result.stdout)\n\n return result\n","sub_path":"src/middlewared/middlewared/plugins/service_/services/base_linux.py","file_name":"base_linux.py","file_ext":"py","file_size_in_byte":3437,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"528957851","text":"import collections\nfrom Traversal import TreeTraversal\n\n\nclass Node(TreeTraversal):\n def __init__(self, val):\n self.val = val\n self.left = None\n self.right = None\n super(Node, self).__init__()\n\n\ndef deleteNode(root: Node, value):\n if root is None:\n print(\"Node not found\")\n return root\n\n if root.val == value:\n\n # Node has right child or left child:\n if not root.right or not root.left:\n root = root.left if root.left else root.right\n\n # Node node has both right and left child:\n else:\n curr = root.right\n while curr.left:\n curr = curr.left\n root.val = curr.val\n root.right = deleteNode(root.right, curr.val)\n\n elif value > root.val:\n root.right = deleteNode(root.right, value)\n elif value < root.val:\n root.left = deleteNode(root.left, value)\n\n return root\n\n\ndef inOrder(root: Node):\n if not root:\n return\n inOrder(root.left)\n print(root.val)\n inOrder(root.right)\n\n\nif __name__ == \"__main__\":\n tree = Node(12)\n tree.left = Node(5)\n tree.left.left = Node(3)\n tree.left.left.left = Node(1)\n tree.right = Node(15)\n tree.right.left = Node(13)\n tree.right.right = Node(17)\n tree.right.right.right = Node(19)\n # deleteNode(tree, 19)\n inOrder(tree)\n # tree_1 = Node(56, Node(30, Node(22, Node(11, Node(3), Node(16)), Node(40))), Node(70, Node(60, Node(65, Node(63), Node(67))), Node(95)))\n tree.print_tree(tree)\n","sub_path":"BinaryTree/DeleteNode.py","file_name":"DeleteNode.py","file_ext":"py","file_size_in_byte":1533,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"182769653","text":"class QuickUnionUF:\r\n \r\n U_id = []\r\n\r\n def __init__(self,N):\r\n self.N = N\r\n for i in range(0,self.N):\r\n self.U_id.append(i)\r\n \r\n def root(self,i):\r\n self.i = i\r\n while self.i != self.U_id[i]:\r\n self.i = self.U_id[i]\r\n return self.i\r\n \r\n def connected(self,p,q):\r\n self.p = p\r\n self.q = q\r\n if self.root(self.p) == self.root(self.q):\r\n return True\r\n else:\r\n return False\r\n\r\n def union(self,p,q):\r\n self.p = p\r\n self.q = q\r\n i = self.root(self.p)\r\n j = self.root(self.q)\r\n self.U_id[i] = j\r\n \r\n \r\ncheck = QuickUnionUF(10)\r\n\r\nprint(\"Before connecting:\\n\",check.U_id)\r\n\r\n# Connecting elements\r\ncheck.union(4,3)\r\ncheck.union(3,8)\r\ncheck.union(6,5)\r\ncheck.union(9,4)\r\ncheck.union(2,1)\r\n\r\nprint(\"After connecting:\\n\",check.U_id)\r\n\r\n# Checking whether elements are connected\r\nprint(\"Connection status:\")\r\nprint(check.connected(9,1))\r\nprint(check.connected(2,1))","sub_path":"01_3_Quick_Union.py","file_name":"01_3_Quick_Union.py","file_ext":"py","file_size_in_byte":1045,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"238019256","text":"config = {}\n# set the parameters related to the training and testing set\n\nnKbase = 59\nnKnovel = 5\nnExemplars = 5\n\ndata_train_opt = {}\ndata_train_opt['nKnovel'] = nKnovel\ndata_train_opt['nKbase'] = -1\ndata_train_opt['nExemplars'] = nExemplars\ndata_train_opt['nTestNovel'] = nKnovel * 5\ndata_train_opt['nTestBase'] = nKnovel * 5\ndata_train_opt['batch_size'] = 2\ndata_train_opt['epoch_size'] = data_train_opt['batch_size'] * 1000\n\ndata_test_opt = {}\ndata_test_opt['nKnovel'] = nKnovel\ndata_test_opt['nKbase'] = nKbase\ndata_test_opt['nExemplars'] = nExemplars\ndata_test_opt['nTestNovel'] = 15 * data_test_opt['nKnovel']\ndata_test_opt['nTestBase'] = 15 * data_test_opt['nKnovel']\ndata_test_opt['batch_size'] = 1\ndata_test_opt['epoch_size'] = 500\n\nconfig['data_train_opt'] = data_train_opt\nconfig['data_test_opt'] = data_test_opt\n\nconfig['max_num_epochs'] = 60\n\nnetworks = {}\nnet_optionsF = {'userelu': True, 'usebn':True}\npretrainedF = './experiments/fsd_openl3CosineClassifier/feat_model_net_epoch*.best'\nnetworks['feat_model'] = {'def_file': 'architectures/dense.py', 'pretrained': pretrainedF, 'opt': net_optionsF, 'optim_params': None}\n\nnet_optim_paramsC = {'optim_type': 'adam', 'lr': 0.001, 'beta':(0.9, 0.999), 'amsgrad':True}\npretrainedC = './experiments/fsd_openl3CosineClassifier/classifier_net_epoch*.best'\nnet_optionsC = {'classifier_type': 'cosine', 'weight_generator_type': 'attention_based', 'nKall': nKbase, 'nFeat':2048, 'scale_cls': 10, 'scale_att': 10.0}\nnetworks['classifier'] = {'def_file': 'architectures/ClassifierWithFewShotGenerationModule.py', 'pretrained': pretrainedC, 'opt': net_optionsC, 'optim_params': net_optim_paramsC}\n\nconfig['networks'] = networks\n\ncriterions = {}\ncriterions['loss'] = {'ctype':'BCEWithLogitsLoss', 'opt':None}\nconfig['criterions'] = criterions\n\nconfig['openl3'] = True\n\nconfig['algorithm_type'] = 'FewShot'","sub_path":"config/openl3CosineClassifierGenWeightAttN5.py","file_name":"openl3CosineClassifierGenWeightAttN5.py","file_ext":"py","file_size_in_byte":1855,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"188420964","text":"import psycopg2\nfrom sqlalchemy import create_engine\nfrom typing import Dict\nfrom pathlib import Path\nfrom dotenv import dotenv_values\nfrom pandabox.exceptions import ConnectionNotExist\n\n\nclass DbManager:\n\n def __init__(self,\n env_path: Path = None,\n connection_strings: Dict = None,\n init_env: bool = True,\n use_prefix: bool = True,\n prefix: str = None):\n\n if connection_strings is None:\n connection_strings = {}\n\n if env_path is None:\n env_path = Path.cwd() / \".env\"\n\n # only use the default prefix is none is provided\n if use_prefix:\n if prefix is None:\n prefix = \"pandabox+\"\n else:\n prefix = \"\"\n\n self.env_path = env_path\n self.connection_strings = connection_strings\n self.prefix = prefix\n\n self._ex_msg = \"database {} connection string is not registered in the connection manager\"\n\n if init_env:\n self.init_env()\n\n def init_env(self):\n for key, value in dotenv_values(dotenv_path=self.env_path).items():\n if value.startswith(self.prefix):\n self.add_connection_string(key.lower(), value.replace(self.prefix, ''))\n\n def get_connection_string(self, name: str):\n for key, value in self.connection_strings.items():\n if name == key:\n return value\n raise ConnectionNotExist(self._ex_msg.format(name))\n\n def get_connection(self, name: str):\n for key, value in self.connection_strings.items():\n if key == name:\n return psycopg2.connect(value)\n raise ConnectionNotExist(self._ex_msg.format(name))\n\n def get_alchemy_engine(self, name: str):\n for key, value in self.connection_strings.items():\n if key == name:\n return create_engine(value)\n raise ConnectionNotExist(self._ex_msg.format(name))\n\n def add_connection_string(self, name: str, value: str):\n self.connection_strings[name] = value\n","sub_path":"pandabox/db/dbmanager.py","file_name":"dbmanager.py","file_ext":"py","file_size_in_byte":2082,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"643985613","text":"import re\n\n\ndef urlize_quoted_links(content):\n return re.sub(r'\"(https?://[^\"]*)\"', r'\"\\1\"', content)\n\n\nclass LimitedStream(object):\n # Taken from the Werkzeug source.\n # License: https://github.com/mitsuhiko/werkzeug/blob/master/LICENSE\n\n def __init__(self, stream, limit):\n self._read = stream.read\n self._readline = stream.readline\n self._pos = 0\n self.limit = limit\n\n def read(self, size=None):\n \"\"\"\n Read `size` bytes or if size is not provided everything is read.\n \"\"\"\n if self._pos >= self.limit:\n return self.on_exhausted()\n if size is None or size == -1: # -1 is for consistence with file\n size = self.limit\n to_read = min(self.limit - self._pos, size)\n try:\n read = self._read(to_read)\n except (IOError, ValueError):\n raise IOError('Client disconnected')\n if to_read and len(read) != to_read:\n raise IOError('Client disconnected')\n self._pos += len(read)\n return read\n","sub_path":"coreapi/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1071,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"472035258","text":"#!/usr/bin/env python3\n#import xml.etree.ElementTree as etree\nimport os\nimport sys\nimport re\nfrom lxml import etree\nimport argparse\nimport codecs\nimport rlcompleter\nimport subprocess\n\ndef totxt(fn):\n\t#xmlFile = re.compile(\".*\\.xml$\")\n\t#if xmlFile.match(fn):\n\tif os.path.isfile(fn):\n\t\tfileHandle = open (fn,\"r\" )\n\t\tlineList = fileHandle.readline()\n\t\tfileHandle.close()\n\t\troot = etree.parse(fn).getroot()\n\t\tattributes = root.attrib\n\t\tlang=attributes.get(\"language\")\n\t\tfor item in root.getiterator(\"{http://apertium.org/xml/corpus/0.9}entry\"):\n\t\t\tif args['sentence'] is not False: #split by sentence\n\t\t\t\titemtxt=str(item.text)\n\t\t\t\ttosplit=itemtxt.replace(' ',' ')\n\t\t\t\tif lang == \"eng\" or lang == \"en\" or lang == \"rus\" or lang == \"ru\" or lang == \"hye\" or lang == \"hy\":\n py2output = subprocess.check_output(['python', 'getnltk.py', tosplit, lang])\n py2output=(str(py2output,'utf-8'))\n\t\t\t\telse:\n\t\t\t\t\tprint(\"language not supported\")\n\t\t\t\t\tsys.exit(\"language not supported\")\n\t\t\t\tif args['output_file'] is not None:\n\t\t\t\t\t\toutput.write(item.attrib['title']+'\\n'+py2output)\n\t\t\t\telse:\n\t\t\t\t\tsys.stdout.write((item.attrib['title']+'\\n'+py2output))\n\t\t\telse: #split by paragraph (default)\n\t\t\t\tif args['output_file'] is not None:\n\t\t\t\t\toutput.write((item.attrib['title']+'\\n'+item.text+'\\n\\n'))\n\t\t\t\telse:\n\t\t\t\t\tsys.stdout.write((item.attrib['title']+'\\n'+item.text+'\\n\\n'))\n\ndef reattach(sentences):\n punctuation = ('.','!','?')\n previous = ''\n for sentence in sentences:\n if sentence not in punctuation:\n previous = sentence\n else:\n yield previous + sentence\n previous = ''\n if previous:\n yield previous + \"\\n\"\n\n\n#argparser\nparser = argparse.ArgumentParser(description='xml to txt script')\nparser.add_argument('corpus_dir', metavar='i', help='corpus directory (input)')\nparser.add_argument('-o','--output_file', help='name of output_file', required=False)\nparser.add_argument('-s', '--sentence', action='store_true', help=\"Splits corpus into sentences (only for trained languages; see http://wiki.apertium.org/wiki/Sentence_segmenting for more info)\")\n\n\n\nargs = vars(parser.parse_args())\n\nif args['output_file'] is not None:\n\toutput = open(args['output_file'], 'w')\n\n\n\n#if (args['corpus_dir'])[-4:] == \".xml\": #checks if user entered an xml file\nif os.path.isfile(args['corpus_dir']): #checks if user entered an xml file\n\ttotxt(args['corpus_dir'])\n\tif args['output_file'] is not None:\n\t\tfilename=args['corpus_dir'][args['corpus_dir'].rfind('/')+1:]\n\t\tprint(\"Adding content from \"+filename)\n\t\tprint(\"Done.\")\n#else: #if directory\nelif os.path.isdir(args['corpus_dir']):\n\tos.chdir(args['corpus_dir'])\n\tfiles = os.listdir('.')\n\tfor fn in files:\n\t\tfilename=fn\n\t\tif args['output_file'] is not None:\n\t\t\tprint(\"Adding content from \"+fn)\n\t\ttotxt(fn)\n\tif args['output_file'] is not None:\n\t\tprint(\"Done.\")\n\n\t\t\n\nif args['output_file'] is not None:\n\toutput.close()\n\n\n","sub_path":"apertium-tools/scraper/xml2txt.py","file_name":"xml2txt.py","file_ext":"py","file_size_in_byte":2981,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"265906338","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\nimport os\nimport sys\nimport time\nimport queue\nimport threading\n\nfrom PyQt5 import QtCore, QtGui, QtWebEngineCore, QtWebEngineWidgets\nfrom PyQt5.QtCore import QEventLoop\nfrom PyQt5.QtWidgets import QApplication\ntry:\n from . import content\nexcept SystemError:\n import content\n\n\nclass WorkerBase(QtCore.QThread):\n \"\"\"\n This class is used as the base comunicator with the application.\n It extends the QtCore.QThread class.\n \"\"\"\n TO_HTML = QtCore.pyqtSignal()\n SET_ICON = QtCore.pyqtSignal(str)\n SET_HTML = QtCore.pyqtSignal(str)\n LOAD_PAGE = QtCore.pyqtSignal(QtCore.QUrl)\n SEARCH_FOR = QtCore.pyqtSignal(str)\n SHUTDOWN_APPLICATION = QtCore.pyqtSignal()\n EXECUTE_JAVASCTIPT = QtCore.pyqtSignal(str)\n \n def __init__(self, connection_queue, content):\n \"\"\"\n This initializes the worker by extendind the parent __init__.\n \n Attention this method should not be overriden by the subclass!\n \n :param connection_queue: this is the queue needed to get requests by the application.\n :param content: this is the content manager object needed for the html base page\n \"\"\"\n super().__init__()\n self.connection_queue = connection_queue\n self.codebase = content\n self.codebase.title = \"DEFAULT\"\n \n def _change_icon(self, icon_path):\n \"\"\"\n This method will set the icon from the application. This is needed for \n dynamic icons.\n :param icon_path: the path to the icon\n \"\"\"\n self.SET_ICON.emit(icon_path)\n \n def _change_url(self, url):\n \"\"\"\n This command changes the url of the webkit window.\n \n :param url: is a url string.\n \"\"\"\n url = QtCore.QUrl(url)\n self.LOAD_PAGE.emit(url)\n \n def _set_html(self, html):\n \"\"\"\n This method will send some html code for the browser to excecute.\n \n :param html: html sequence to excecute.\n \"\"\"\n self.SET_HTML.emit(html)\n \n def _get_html(self):\n \"\"\"\n This method will send the get the html command.\n \"\"\"\n self.TO_HTML.emit()\n results = self.connection_queue.get()\n return results\n \n def _shutdown_application(self):\n \"\"\"\n This method will shut down the application.\n \"\"\"\n self.SHUTDOWN_APPLICATION.emit()\n \n def _check_for(self, name_of, interval = 0.5, timeout=None):\n \"\"\"\n This method is used to check and wait until an element is in the \n dom of the Website.\n \n :param name_of: is the CSS selector of the element\n :param interval: is the time between searches\n :param timeout: is the max time spend on seaching only if the value is a integer or float.\n :returns: returns True when that element has, been found and False after the timeout runes out.\n \"\"\"\n if timeout is not None:\n start_time = time.time()\n ending_time = start_time + timeout\n while True:\n results = self._search_for(name_of)\n if results.isNull():\n if timeout is not None:\n if time.time() < ending_time:\n time.sleep(interval)\n else:\n return False\n else:\n return True\n \n def _search_for(self, name_of):\n \"\"\"\n This method will send the search for command and\n return the results.\n :param name_of: this contains the name_of the element to search for.\n \"\"\"\n self.SEARCH_FOR.emit(name_of)\n results = self.connection_queue.get()\n return results\n \n def _excecute_javascript(self, script):\n \"\"\"\n This method will send the script over to the application interface and resive \n the evaluated content over the inteface. \n \n :param script: this is the script to excecute.\n :returns: the values returned by the javascript command. \n \"\"\"\n self.EXECUTE_JAVASCTIPT.emit(script)\n return self.connection_queue.get()\n \n def run(self):\n \"\"\"\n This is the base method that has to be overriden.\n \"\"\"\n raise NotImplementedError\n \t\nclass ApplicationBase(QApplication):\n \"\"\"\n This is the application base window. In here the window for the system is initialised.\n \"\"\"\n\n def __init__(self, worker_base, prefix=\"\"):\n \"\"\"\n Starts the application window.\n \n :param worker_base: set's the worker base to connect to, this has to be a child of the HtmlGui.WokerBase class\n :param prefix: set's the prefix for the temporary file direcotry.\n \"\"\"\n super().__init__(sys.argv)\n self.worker_base = worker_base\n self.connection_queue = queue.Queue(1)\n self.content = content.Content(prefix)\n self.set_ui()\n \n def set_ui(self):\n \"\"\"\n This method initializes \n \"\"\"\t\t\n # The worker and it's connections are build.\n self.worker = self.worker_base(self.connection_queue, self.content)\n self.worker.TO_HTML.connect(self._get_html)\n self.worker.SET_HTML.connect(self._set_html)\n self.worker.SET_ICON.connect(self._set_icon)\n self.worker.LOAD_PAGE.connect(self._load_page)\n self.worker.SEARCH_FOR.connect(self._search_for)\n self.worker.SHUTDOWN_APPLICATION.connect(self._quit_application)\n self.worker.EXECUTE_JAVASCTIPT.connect(self._evaluate_javascript)\n \n # create the widgets\n self._create_widget()\n \n # start the workers\n self.worker.start()\n \n def _set_icon(self, icon_path):\n \"\"\"\n This methods set's the icon for the system.\n \n :param icon_path: the icon path\n \"\"\"\n self.setWindowIcon(QtGui.QIcon(icon_path))\n \n def _create_widget(self):\n \"\"\"\n This method creates the widgets.\n \"\"\"\n self.web_page = QtWebEngineWidgets.QWebEnginePage() \n self.web_view = QtWebEngineWidgets.QWebEngineView()\n self.web_view.showMaximized() # maximizes the window on start\n self.web_view.setPage(self.web_page)\n \n @QtCore.pyqtSlot(QtCore.QUrl)\n def _load_page(self, page):\n \"\"\"\n This method will load the page given by the url.\n \"\"\"\n self.web_view.load(page)\n self.web_view.show()\n \n @QtCore.pyqtSlot(str)\n def _set_html(self, html):\n \"\"\"\n This method will set the html directly.\n \n :param html: the html as strings.\n \"\"\"\n location = QtCore.QUrl(self.content.get_directory(1) )\n self.web_view.setHtml(html, location)\n self.web_view.show()\n \n @QtCore.pyqtSlot(str)\n def _evaluate_javascript(self, script):\n \"\"\"\n This method will evaluate the JavaScript code and return (send over the queue) the results.\n \n :param script: the javascript code that has to be initialised.\n \"\"\"\n self.web_page.runJavaScript(script, FunctorOrLambda = self._add_to_queue)\n \n @QtCore.pyqtSlot(str)\n def _search_for(self, name_of):\n \"\"\"\n This method will search for a given element by it's CSS selector.\n \n :param name_of: is the CSS selector of the element to search for.\n \"\"\"\n self.web_page.findText(name_of, FunctorOrLambda = self._add_to_queue) \n \n @QtCore.pyqtSlot()\n def _get_html(self):\n \"\"\"\n This method will return the html.\n \"\"\"\n self.web_page.toHtml(self._add_to_queue)\n \n def _quit_application(self):\n \"\"\"\n This method will shutdown the system.\n \"\"\"\n self.quit()\n \n def _add_to_queue(self, object):\n \"\"\"\n This method will add the object to the connection queue.\n \n :param object: the object that has to be sendet \n \"\"\"\n self.connection_queue.put(object)\n ","sub_path":"HtmlGui/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":8082,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"456896317","text":"#macroOLS.py\nimport pandas as pd\npd.core.common.is_list_like = pd.api.types.is_list_like\nimport pandas_datareader.data as web\nimport datetime\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport os\nfrom matplotlib.backends.backend_pdf import PdfPages\nimport statsmodels.api as sm\n\ndef OLSRegression(df,endogVar, exogVars):\n #Select endogenous data for Y\n Y = dataFrame[endogVar]\n #Select exogenous data for X\n X = dataFrame[exogVars]\n #Add column of ones for constant\n X = sm.add_constant(X)\n print(X)\n #Run regression\n model = sm.OLS(Y,X)\n #Save results of regression\n results = model.fit()\n return results\n\ndef plotValues(df,keys):\n df[keys].plot.line(figsize=(24,12), legend=False, secondary_y=keys[0])\n plt.title(str(keys) + \"\\n\", fontsize=40)\n# plt.axhline(0)\n# plt.ylim([-10,10])\n plt.show()\n plt.close()\n\ndef scatterPlot(df, key1,key2,pp,start,end, title=\"\"):\n fig,ax = plt.subplots(figsize=(24,12))\n plt.scatter(x=df[key1], y=df[key2], s = 5**2, c=range( int(matplotlib.dates.date2num(end))))\n plt.axhline(0, ls = \"--\", color=\"k\", linewidth = 1)\n plt.axvline(0, ls=\"--\", color=\"k\", linewidth = 1)\n ax.set_xlabel(key1)\n ax.set_ylabel(key2)\n# ax.set_xlim(min(df[key1]) * .98, max(df[key1]) * 1.02)\n# ax.set_ylim(min(df[key2]) * .98, max(df[key2]) * 1.02)\n plt.colorbar()\n plt.set_cmap(\"plasma\")\n # get the old tick labels (index numbers of the dataframes)\n# clb_ticks = [int(t.get_text()) for t in clb.ColorbarBase(]\n # convert the old, index, ticks into year-month-day format\n# new_ticks = df.index[clb_ticks].strftime(\"%Y-%m-%d\")\n# clb.ax.yaxis.set_ticklabels(new_ticks)\n plt.savefig(str(start).replace(\":\",\"\") + \"-\" + str(end).replace(\":\",\"\")\\\n + \" \" +\\\n key1 + \" \" + key2 +' scatter '+'.png', bbox_inches=\"tight\")\n\n plt.show()\n pp.savefig(fig, bbox_inches=\"tight\")\n plt.close()\n\n\n\ndef buildSummaryCSV(csvSummary, csvName): \n #Create a new csv file\n file = open(csvName + \".csv\", \"w\")\n #write results in csv file\n file.write(csvSummary)\n #close CSV\n file.close()\n \npp = PdfPages(\"Gold Elasticities.pdf\") \nstart = datetime.datetime(1972, 1, 1)\nend = datetime.datetime(2018, 8, 1)\ndfDict = {}\n\ndfDict[\"Data\"] = web.DataReader(\"IPG21222N\", \"fred\", start, end).resample(\"Q\", how=\"mean\")\ndfDict[\"Data\"] = dfDict[\"Data\"].rename(columns = {\"IPG21222N\":\"Gold Production\"}) \ndfDict[\"Data\"][\"Price of Gold\"] = web.DataReader(\"GOLDPMGBD228NLBM\", \"fred\", start, end).resample(\"Q\", how=\"mean\")\ndfDict[\"Data\"][\"% Change in Gold Production\"] = (dfDict[\"Data\"][\"Gold Production\"].diff() / dfDict[\"Data\"][\"Gold Production\"])\ndfDict[\"Data\"][\"% Change in Gold Price\"] = dfDict[\"Data\"][\"Price of Gold\"].diff() / dfDict[\"Data\"][\"Price of Gold\"]\n\ndfDict[\"Data\"][\"Observed Price Elasticity\"] = dfDict[\"Data\"][\"% Change in Gold Production\"]\\\n / dfDict[\"Data\"][\"% Change in Gold Price\"] \ndfDict[\"Data\"]['Production MA'] = dfDict[\"Data\"][\"Gold Production\"].rolling(window=8).mean()\ndfDict[\"Data\"]['Price MA'] = dfDict[\"Data\"][\"Price of Gold\"].rolling(window=8).mean()\ndfDict[\"Data\"][\"% Change MA Production\"] = dfDict[\"Data\"]['Production MA'].diff()\\\n / dfDict[\"Data\"]['Production MA']\ndfDict[\"Data\"][\"% Change MA Price\"] = dfDict[\"Data\"]['Price MA'].diff()\\\n / dfDict[\"Data\"]['Price MA']\n\nplotValues(dfDict[\"Data\"],[\"Gold Production\",\"Price of Gold\"])\n\nplotValues(dfDict[\"Data\"],[\"Observed Price Elasticity\"])\n\nkey1 = \"Gold Production\"\nkey2 = \"Price of Gold\"\nscatterPlot(dfDict[\"Data\"], key1,key2,pp,start,end)\n\nkey1 = \"% Change in Gold Production\"\nkey2 = \"% Change in Gold Price\"\nplotValues(dfDict[\"Data\"],[key1,key2])\nscatterPlot(dfDict[\"Data\"], key1,key2,pp,start,end)\nkey1 = \"% Change MA Production\"\nkey2 = \"% Change MA Price\"\nscatterPlot(dfDict[\"Data\"], key1,key2,pp,start,end)\n\npp.close()","sub_path":"Sample Script/goldElasticities.py","file_name":"goldElasticities.py","file_ext":"py","file_size_in_byte":4013,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"21253860","text":"execfile(qt.reload_current_setup)\nimport msvcrt, time\nimport numpy as np\nfrom measurement.lib.pulsar import pulse, pulselib, element, pulsar\n\np_start = pulse.SquarePulse('sync1', length=100e-9, amplitude = 1)\np_stop = pulse.SquarePulse('p7889_stop', length=100e-9, amplitude = 1)\np_wait_length=10e-6\np_wait = pulse.SquarePulse('sync1', length=p_wait_length, amplitude = 0)\np_sync = pulse.SquarePulse('sync0', length=100e-9, amplitude = 1)\n\nint_time = 10e-3 #s\nwait_time = 1e-3 #s\nreprate = 100e3 #KHz\npulse_reps = int_time*reprate\nwait_reps = int(np.round(wait_time/p_wait_length))\nelts = []\n\nypts=121\n\ns= pulsar.Sequence('test_p7889_seq')\n#for i in np.arange(y_pts):\ne_sync=element.Element('sync_p7889_elt', pulsar=qt.pulsar)\ne_sync.add(p_sync, start = 200e-9)\ne_sync.add(p_wait)\ne_wait=element.Element('wait_p7889_elt', pulsar=qt.pulsar)\ne_wait.add(p_wait)\ne=element.Element('p7889_elt', pulsar=qt.pulsar)\ne.add(pulse.cp(p_wait,length = 1./reprate))\ne.add(p_start, start=200e-9, name='start')\n#e.add(p_stop, start=1e-9, refpulse='start')\n#e.add(p_stop, start=100e-9, refpulse='start')\n#e.add(p_stop, start=300e-9, refpulse = 'start')\n#e.append(T)\n\n#for i in range(int_time*reprate):\n\t\n\n#e.add(p_stop, start=30e-9*i, refpulse = 'start')\n#if i%2 == 0:\n#\t\te.add(p_stop, start=100e-9, refpulse = 'start')\n\n\nelts.append(e)\nelts.append(e_wait)\nelts.append(e_sync)\n\nfor i in range(ypts):\n\ts.append(name = 'sync_init'+str(i),\n\t wfname = e_sync.name,\n\t trigger_wait = 1,\n\t repetitions = 1)\n\ts.append(name = 'wait'+str(i),\n\t wfname = e_wait.name,\n\t trigger_wait = 0,\n\t repetitions = wait_reps)\n\n\ts.append(name = 'pulse'+str(i),\n\t wfname = e.name,\n\t trigger_wait = 0,\n\t repetitions = pulse_reps)\n\n#qt.pulsar.upload(*elts)\n##qt.pulsar.program_sequence(s)\nqt.pulsar.program_awg(s,*elts)\n\n\n\n# qt.instruments['p7889'].set_number_of_cycles(ypts)\n# qt.instruments['p7889'].set_number_of_sequences(1)\n# qt.instruments['p7889'].set_sweepmode_sequential(True)\n# qt.instruments['p7889'].set_sweep_preset(True)\n# qt.instruments['p7889'].set_sweep_preset_number(pulse_reps)\n\n# qt.instruments['p7889'].Start()\n# qt.msleep(0.5)\nqt.instruments['AWG'].start()\n\n# t0 = time.time()\n# c0 = 0\n# p=np.zeros(100000,dtype = 'int')\n# ii=0\n# while qt.instruments['p7889'].get_state(): \n# #time.sleep(0.1)\n# qt.msleep(0.2)\n# if msvcrt.kbhit():\n# kb_char=msvcrt.getch()\n# if kb_char == \"q\": \n# stop = True\n# break\n# t1 = time.time()\n# c1 = qt.instruments['p7889'].get_RoiSum()\n# #p[min([int((c1-c0)/(t1-t0)),100000-1])]+=1\n# if ii%10 == 0:\n# \tprint (c1-c0)/(t1-t0)\n# t0 = t1\n# c0 = c1\n# ii+=1\n\n# qt.instruments['p7889'].Stop()\n# qt.msleep(0.5)\n#qt.instruments['AWG'].stop()","sub_path":"scripts/rt2_scripts/scanning/test_p7889_2d.py","file_name":"test_p7889_2d.py","file_ext":"py","file_size_in_byte":2859,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"513221206","text":"#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n# Created by aaron at 3/30/17\n\n#System level\nimport locale\n\nfrom lib.files import *\nfrom lib.webs import *\nfrom lib.excel import *\nfrom lib.crawl import *\nimport setup\n\n\ndef inputKey():\n print('Please input keyword: ')\n keyword = input()\n if not keyword.isalnum:\n keyword.decode(sys.stdin.encoding or locale.getpreferredencoding(True))\n return keyword\n\ndef createFile():\n path = setup.DIR_PATH #'/home/aaron/py/test'\n filename = setup.FILE_NAME #'T' + time.strftime('%Y%m%d%H%M%S', time.localtime())\n\n file = Files(path, filename, '')\n\n file.createDir(str(path)) # Create Folder\n\n file.createFile(path, filename) # Create File\n return (path, filename)\n\ndef genLinks(keyword, path, filename):\n file = Files(path, filename, '')\n web = Webs()\n try:\n print('Searching page: 1 now')\n html = web.search(keyword)\n linklist = web.parse(html)\n linklist = '\\n'.join(linklist)\n file.writeFile(path, filename, linklist)\n print('Search page: 1 is completed')\n\n print('Searching more now')\n for i in range(1, setup.PAGE):\n linklist = web.searchMore()\n linklist = '\\n'.join(linklist)\n file.writeFile(path, filename, linklist)\n print('Search page: {0:2d} is completed'.format(i+1))\n\n except Exception:\n print('Failed')\n\n finally:\n setup.DRIVER.close()\n\ndef crawlAndWrite(path, filename):\n \"\"\"Crawling and write to excel\"\"\"\n crawl = Crawl()\n read = Files(path, filename, '')\n excel = Excel()\n records = read.readFile(path, filename)\n for record in records:\n record = record.strip('\\n')\n infos = crawl.crawler(record)\n for info in infos:\n url = info.get('url')\n comments = info.get('commentsInfo')\n for comment in comments:\n content = comment[0]\n user = comment[1]\n if len(comments) > 0:\n excel.write_info((user, content, url), path, filename)\n\ndef cleanUp():\n \"\"\"Clean up\"\"\"\n #Generate files list for clean up\n path = setup.DIR_PATH_FILE\n filename = setup.FILE_LIST # Create file in order to save file list\n file = Files(path, filename, '')\n file.createFile(path, filename)\n path = setup.DIR_PATH\n pathfile = setup.DIR_PATH_FILE\n file.fileList(path, pathfile, filename) # Generate file list\n\n file.fileRemove(path, pathfile, filename) # Remove file from folder\n\ndef main():\n \"\"\"Main routine\"\"\"\n file = createFile() # Create folder and txt for save links\n\n keyword = inputKey() # input\n\n path = file[0]\n filename = file[1]\n genLinks(keyword, path, filename) # generate linklist\n\n crawlAndWrite(path, filename) # crawling link and write into excel one by one\n\n\n# cleanUp() # clean up after done\n\nif __name__ == '__main__':\n main()","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2917,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"583310065","text":"import sympy\nfrom typing import Union\n\n\ndef make_keys(key_len: int, e: int) -> Union[int, int, int, int]:\n p1_len = (key_len // 2) + 1\n p2_len = key_len - p1_len\n prime1 = sympy.randprime(pow(2, p1_len-1), pow(2, p1_len)-1)\n prime2 = sympy.randprime(pow(2, p2_len-1), pow(2, p2_len)-1)\n\n if prime1 == prime2:\n while prime1 == prime2:\n prime2 = sympy.randprime(pow(2, p2_len - 1), pow(2, p2_len) - 1)\n\n n = prime1 * prime2\n lcm = sympy.lcm(prime1-1, prime2-1)\n d, a, b = sympy.gcdex(e, lcm)\n d = int(d % lcm)\n\n return n, e, lcm, d\n\n\ndef e_input() -> int:\n e = input('eの値を選択してください。(a~g)\\na: 3,\\nb: 5,\\nc: 17,\\nd: 257,\\ne: 65537,(推奨)\\nf: 131073,\\ng: 262145,\\n>> ')\n if e == 'a':\n return 3\n elif e == 'b':\n return 5\n elif e == 'c':\n return 17\n elif e == 'd':\n return 257\n elif e == 'e':\n return 65537\n elif e == 'f':\n return 131073\n elif e == 'g':\n return 262145\n else:\n print('入力エラー')\n return e_input()\n\n\ndef char_to_int(data: str) -> int: # 文字列を突っ込むと数列を返す\n char_list = list(data)\n int_list = []\n for i in range(len(char_list)):\n int_list.append(ord(char_list[i])-32)\n int_list.reverse()\n int_data = 0\n for i in range(len(int_list)):\n int_data += int_list[i] * pow(95, i)\n return int_data\n\n\ndef int_to_char(data: int) -> str: # 数列を突っ込むと文字列を返す\n i = 0\n while True:\n if data < pow(95, i+1):\n break\n i += 1\n\n int_list = []\n while i >= 0:\n int_text = 0\n a = pow(95, i)\n while int_text < 95: # 文字コードとしては0~94なので'<'でよろしい\n if (int_text + 1) * a > data:\n int_list.append(int_text)\n data -= int_text * a\n int_text += 95\n int_text += 1\n i -= 1\n\n char_list = []\n for i in range(len(int_list)):\n char_list.append(chr(int_list[i] + 32))\n char = ''.join(char_list)\n return char\n\n\ndef make_bin_expansion_list(data: int, bin_list: list, mod: int) -> list: # 二進展開の一覧表を作る\n bin_expansion_list = [[0, data]]\n for i in range(1, len(bin_list)):\n data = i, pow(bin_expansion_list[i-1][1], 2) % mod\n bin_expansion_list.append(data)\n return bin_expansion_list\n\n\ndef multiply(bin_list: list, bin_expansion_list: list, mod: int) -> int: # bin_listとbin_expansion_listから結果を計算する\n bin_list_re = list(reversed(bin_list))\n data = 1\n for i in range(len(bin_list_re)):\n if bin_list_re[i] == 1:\n data = data * bin_expansion_list[i][1] % mod\n return data\n\n\ndef bin_expansion(data: int, e: int, n: int) -> int: # data ^ e (mod n)\n bin_list = list(map(int, list(bin(e)[2:])))\n bin_expansion_list = make_bin_expansion_list(data, bin_list, n)\n output = multiply(bin_list, bin_expansion_list, n)\n return output\n","sub_path":"rsa_python/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":3033,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"115777199","text":"import sys\n\nd = {\n\t\"a\": 0,\n\t\"o\": 0,\n\t\"u\": 0,\n\t\"i\": 0,\n\t\"e\": 0\n}\n\ndef sorter(t):\n\treturn t[1]\n\ndef main():\n\t\n\tword_list = [line.strip() for line in sys.stdin.read()]\n\tfor char in word_list:\n\t\tchar = char.lower()\n\t\tif char in d:\n\t\t\td[char] += 1\n\n\ta = [str(value) for value in d.values()]\n\tm = len(max(a, key=len))\n\n\tfor (k, v) in sorted(d.items(), key=sorter, reverse=True):\n\t\tprint(\"{} : {:>{:d}}\".format(k, v, m))\n\t\n\n\nif __name__ == \"__main__\":\n\tmain()","sub_path":"week-04/vowels_41.py","file_name":"vowels_41.py","file_ext":"py","file_size_in_byte":452,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"119617035","text":"from django.conf.urls import url\nfrom . import views\nfrom rest_framework.urlpatterns import format_suffix_patterns\n\nurlpatterns = [\n\turl(r'^$', views.main_page, name='main_page'),\n url(r'^posts/$', views.post_list, name='post_list'),\n url(r'^posts/(?P\\d+)/$', views.post_detail, name='post_detail'),\n url(r'^posts/new/$', views.post_new, name='post_new'),\n url(r'^posts/(?P\\d+)/edit/$', views.post_edit, name='post_edit'),\n url(r'^posts/(?P\\d+)/delete/$', views.post_delete, name='post_delete'),\n url(r'^register/$', views.RegistrationFormView.as_view(), name=\"registration\"),\n url(r'^login/$', views.LoginFormView.as_view(), name=\"user_login\"),\n url(r'^logout/$', views.logout_, name=\"user_logout\"),\n url(r'^api/posts/$', views.PostList.as_view()),\n url(r'^api/posts/(?P\\d+)/', views.PostDetail.as_view()),\n]\n","sub_path":"areaapp/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":857,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"37294158","text":"# -*- encoding: utf-8 -*-\nimport random\nimport pilasengine\n\n\nclass Estado:\n\n def __init__(self, mono):\n self.mono = mono\n self.iniciar()\n\n def iniciar(self):\n pass\n\n\nclass Ingresando(Estado):\n\n def iniciar(self):\n self.contador = 0\n self.mono.y = -380\n self.mono.y = [-200], 0.5\n\n def actualizar(self):\n self.contador += 1\n\n if self.contador > 50:\n self.mono.estado = Jugando(self.mono)\n\n\nclass Jugando(Estado):\n\n def iniciar(self):\n pass\n\n def actualizar(self):\n velocidad = 5\n\n if pilas.escena.control.derecha:\n self.mono.x += velocidad\n elif pilas.escena.control.izquierda:\n self.mono.x -= velocidad\n\n if self.mono.x > 210:\n self.mono.x = 210\n elif self.mono.x < -210:\n self.mono.x = -210\n\n\nclass Perdiendo(Estado):\n\n def iniciar(self):\n self.mono.centro = ('centro', 'centro')\n self.velocidad = -2\n\n def actualizar(self):\n self.mono.rotacion += 7\n self.mono.escala += 0.01\n self.mono.x -= self.velocidad\n self.velocidad += 0.2\n self.mono.y -= 1\n\n\nclass MonoPersonalizado(pilasengine.actores.Mono):\n\n def iniciar(self):\n self.escala = 0.5\n self.y = -170\n self.estado = Ingresando(self)\n self.contador = 0\n\t\n def actualizar(self):\n self.estado.actualizar()\n \n def perder(self):\n mono.gritar()\n self.estado = Perdiendo(self)\n t.x = 0\n t.y = 0\n t.escala = 0\n t.escala = [1], 0.5\n pilas.tareas.eliminar_todas()\n\nclass Enemigo(pilasengine.actores.Bomba):\n\n def iniciar(self):\n pilasengine.actores.Bomba.iniciar(self)\n self.escala = 0.75\n self.arriba = 320\n self.x = random.randint(-210, 210)\n\n def actualizar(self):\n self.y -= 5\n pilasengine.actores.Bomba.actualizar(self)\n\n\nclass Item(pilasengine.actores.Banana):\n\n def iniciar(self):\n self.arriba = 320\n self.x = random.randint(-210, 210)\n\n def actualizar(self):\n self.abajo -= 5\n\n if self.arriba < -230:\n vidasPuntaje.aumentar(1)\n self.eliminar()\n\n\nclass ContadorDeVidas(pilasengine.actores.Actor):\n \n def iniciar(self):\n self.x = 500\n self.vidas = [pilas.actores.Banana() for x in range(3)]\n\n for indice, vida in enumerate(self.vidas):\n vida.escala=1.25\n vida.x = -270 + indice * 40\n vida.arriba = 200\n\t\n def actualizar(self):\n if((vidasPuntaje.obtener() == 1 and len(self.vidas) == 3) \n or (vidasPuntaje.obtener() == 2 and len(self.vidas) == 2)\n or (vidasPuntaje.obtener() == 3 and len(self.vidas) == 1)):\n vida = self.vidas.pop()\n vida.eliminar()\n if(vidasPuntaje.obtener() == 3 and len(self.vidas) == 0):\n vidasPuntaje.aumentar(1)\n mono.perder()\n\t\t\t\n\n\npilas = pilasengine.iniciar()\n\nfondo = pilas.fondos.Selva()\n\nt = pilas.actores.Texto(\"Juego terminado\")\nt.definir_color(pilas.colores.negro)\nt.x = 500\n\nvidasPuntaje = pilas.actores.Puntaje(x=500, y=150)\n\npuntos = pilas.actores.Puntaje(x=280, y=150)\n\nnivel = pilas.actores.Texto(x=270, y=180)\nnivel.definir_texto(\"Nivel 1\")\nnivel.definir_color(pilas.colores.negro)\n\nmono = MonoPersonalizado(pilas)\nitems = []\nenemigos = []\n\npilas.actores.vincular(ContadorDeVidas)\nvidas = pilas.actores.ContadorDeVidas()\n\ndef crear_item():\n un_item = Item(pilas)\n items.append(un_item)\n return True\n\npilas.tareas.agregar(2, crear_item)\n\ndef cuanto_toca_item(v, i):\n mono.sonreir()\n i.eliminar()\n puntos.aumentar(1)\n puntos.escala = 4\n puntos.escala = [1], 0.2\n puntos.rotacion = random.randint(30, 60)\n puntos.rotacion = [0], 0.2\n if(puntos.obtener() == 20):\n nivel.definir_texto(\"Nivel 2\")\n nivel.escala = 4\n nivel.escala = [1], 0.2\n nivel.rotacion = random.randint(30, 60)\n nivel.rotacion = [0], 0.2\n\npilas.colisiones.agregar(mono, items, cuanto_toca_item)\n\ndef crear_enemigo():\n un_enemigo = Enemigo(pilas)\n enemigos.append(un_enemigo)\n return True\n\npilas.tareas.agregar(3.3, crear_enemigo)\n\n\ndef cuanto_toca_enemigo(mono, enemigo):\n\tenemigo.eliminar()\n\tmono.perder()\n\npilas.colisiones.agregar(mono, enemigos, cuanto_toca_enemigo)\n\npilas.ejecutar()\n","sub_path":"angry_monkeys.py","file_name":"angry_monkeys.py","file_ext":"py","file_size_in_byte":4415,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"486134897","text":"# 문제\n# 다음 소스는 N번째 피보나치 수를 구하는 C++ 함수이다.\n\n# fibonacci(3)을 호출하면 다음과 같은 일이 일어난다.\n# fibonacci(3)은 fibonacci(2)와 fibonacci(1) (첫 번째 호출)을 호출한다.\n# fibonacci(2)는 fibonacci(1) (두 번째 호출)과 fibonacci(0)을 호출한다.\n# 두 번째 호출한 fibonacci(1)은 1을 출력하고 1을 리턴한다.\n# fibonacci(0)은 0을 출력하고, 0을 리턴한다.\n# fibonacci(2)는 fibonacci(1)과 fibonacci(0)의 결과를 얻고, 1을 리턴한다.\n# 첫 번째 호출한 fibonacci(1)은 1을 출력하고, 1을 리턴한다.\n# fibonacci(3)은 fibonacci(2)와 fibonacci(1)의 결과를 얻고, 2를 리턴한다.\n# 1은 2번 출력되고, 0은 1번 출력된다. N이 주어졌을 때, fibonacci(N)을 호출했을 때,\n# 0과 1이 각각 몇 번 출력되는지 구하는 프로그램을 작성하시오.\n\n# 입력\n# 첫째 줄에 테스트 케이스의 개수 T가 주어진다.\n# 각 테스트 케이스는 한 줄로 이루어져 있고, N이 주어진다. N은 40보다 작거나 같은 자연수 또는 0이다.\n\n# 출력\n# 각 테스트 케이스마다 0이 출력되는 횟수와 1이 출력되는 횟수를 공백으로 구분해서 출력한다.\n\nimport sys\nread = sys.stdin.readline\n\nn = int(read())\ncount0 = [1,0]\ncount1 = [0,1]\n\ndef fibonacci(n):\n global count0, count1\n if n<=1:\n return\n # 0 , 1 이상부터 확인 \n for i in range(2,n+1):\n count0.append(count0[i-1]+count0[i-2])\n count1.append(count1[i-1]+count1[i-2])\n\n return count0, count1\n \n# 40 보다 작은 수 이기 때문에 미리 배열로 저장\ncount0,count1 = fibonacci(40)\n\nfor _ in range(n):\n m = int(read())\n # print(count0, count1)\n print(count0[m], count1[m])","sub_path":"BaekJoon/Dynamic Programming/1003.py","file_name":"1003.py","file_ext":"py","file_size_in_byte":1785,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"467059795","text":"# Plot / Point / Groups\n# Make a scatterplot with categories encoded as colors.\n# ---\nfrom synth import FakeScatter\nfrom h2o_wave import site, data, ui\n\npage = site['/demo']\n\n\ndef create_fake_row(g, f, n):\n return [(g, x, y) for x, y in [f.next() for _ in range(n)]]\n\n\nn = 30\nf1, f2, f3 = FakeScatter(), FakeScatter(), FakeScatter()\nv = page.add('example', ui.plot_card(\n box='1 1 4 5',\n title='Point, groups',\n data=data('product price performance', n * 3),\n plot=ui.plot([ui.mark(type='point', x='=price', y='=performance', color='=product', shape='circle')])\n))\nv.data = create_fake_row('G1', f1, n) + create_fake_row('G2', f1, n) + create_fake_row('G3', f1, n)\n\npage.save()\n","sub_path":"py/examples/plot_point_groups.py","file_name":"plot_point_groups.py","file_ext":"py","file_size_in_byte":693,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"94934061","text":"import random\n\n#Ex. D.1:\ndef make_random_code():\n '''Returns a random four letter code. Each letter is one of the following:\n 'R', 'G', 'B', 'Y', 'O', or 'W'.'''\n return_string = ''\n for i in range(0,4):\n return_string += random.choice(['R','G','B','Y','O','W'])\n return return_string\n\n#Ex. D.2:\ndef count_exact_matches(str1, str2):\n '''Returns the number of times a character in the first string matches\n a character in the second string. It takes into account the relative location\n of the character.'''\n count = 0\n for i in range(4):\n if str1[i] == str2[i]:\n count += 1\n return count\n\n#Ex. D.3:\ndef count_letter_matches(str1, str2):\n '''Returns the number of letters that are the same between the two input strings\n regardless of order.'''\n \n \n def unique_letters(str1):\n '''Given a string, return its unique letters-- that is, letters that are \n repeated within the string are discounted.'''\n output = ''\n already_used = []\n for x in range(len(str1)):\n if str1[x] not in already_used:\n output += str1[x]\n already_used += list(str1[x])\n return output\n \n count = 0\n str1 = list(str1)\n str2 = list(str2)\n \n \n for x in unique_letters(str1):\n frequency_in_str1 = str1.count(x)\n frequency_in_str2 = str2.count(x)\n frequency_to_add = min(frequency_in_str1,frequency_in_str2)\n count += frequency_to_add\n return count\n\n#Ex. D.4:\ndef compare_codes(code, guess):\n '''Takes two strings both of length 4. Compares them and outputs a string\n of identical length representing the evaluation of the guess according to \n the game guidelines.'''\n black_pegs = count_exact_matches(code, guess) #frequency of black pegs\n white_pegs = count_letter_matches(code, guess) - black_pegs #frequency of white pegs\n dashes = abs(4 - (black_pegs + white_pegs)) #frequency of dashes\n blacks = 'b' * black_pegs\n whites = 'w' * white_pegs\n dashes = '-' * dashes\n output = blacks + whites + dashes\n return output\n\n#Ex. D.5:\ndef run_game():\n '''Runs the game. Takes no arguments. Returns nothing.'''\n n = 0 #number of moves\n print('New game.')\n code = make_random_code()\n while True:\n guess = input('Enter your guess: ')\n print('Result: {}'.format(compare_codes(code, guess)))\n if compare_codes(code, guess) == 'bbbb':\n print('Congratulations! You cracked the code in {} moves!'.format(n))\n break\n\n ","sub_path":"lab2b.py","file_name":"lab2b.py","file_ext":"py","file_size_in_byte":2574,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"644099066","text":"class Solution(object):\n\n def grayCode(self, n):\n res = [0]\n\n for i in xrange(n):\n sz = len(res)\n for n in xrange(sz - 1, -1, -1):\n res.append(res[n] + (1 << i))\n\n return res\n","sub_path":"pythonsolutions/0089_graycode.py","file_name":"0089_graycode.py","file_ext":"py","file_size_in_byte":236,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"213941812","text":"import json\nimport numpy as np\nimport os\n\nfrom PyQt5 import QtWidgets, QtCore\nfrom twisted.internet.defer import inlineCallbacks\n\nfrom client_tools.widgets import ClickableLabel, SuperSpinBox\n\nclass MoglabsXRF_RFClient(QtWidgets.QGroupBox):\n name = None\n DeviceProxy = None\n updateID = np.random.randint(0, 2**31 - 1)\n amplitudeDisplayUnits = [(0, 'dBm')]\n amplitudeDigits = None\n frequencyDisplayUnits = [(-6, 'uHz'), (-3, 'mHz'), (0, 'Hz'), (3, 'kHz'), \n (6, 'MHz'), (9, 'GHz')]\n frequencyDigits = None\n fmgainDisplayUnits = [ (6, 'MHz/V')]\n fmgainDigits = None\n amgainDisplayUnits = [(0, '%')]\n amgainDigits = None\n \n spinboxWidth = 100\n \n def __init__(self, reactor, cxn=None):\n QtWidgets.QDialog.__init__(self)\n self.reactor = reactor\n reactor.callInThread(self.initialize)\n self.connectLabrad()\n \n def initialize(self):\n import labrad\n cxn = labrad.connect(name=self.name, host=os.getenv('LABRADHOST') , password = '')\n self.device = self.DeviceProxy(cxn)\n self.reactor.callFromThread(self.populateGUI)\n # self.fm_dev1 = self.device.fm_dev1\n\n def populateGUI(self):\n self.nameLabel = ClickableLabel('' + self.name + '')\n \n self.channelLabel1 = ClickableLabel('' + 'CH 1' + '')\n self.stateButton1 = QtWidgets.QPushButton()\n self.stateButton1.setCheckable(True)\n \n self.frequencyLabel1 = ClickableLabel('Frequency: ')\n self.frequencyBox1 = SuperSpinBox(self.device._frequency_range, \n self.frequencyDisplayUnits, \n self.frequencyDigits)\n self.frequencyBox1.setFixedWidth(self.spinboxWidth)\n \n self.amplitudeLabel1 = ClickableLabel('Amplitude: ')\n self.amplitudeBox1 = SuperSpinBox(self.device._amplitude_range, \n self.amplitudeDisplayUnits, \n self.amplitudeDigits)\n self.amplitudeBox1.setFixedWidth(self.spinboxWidth)\n \n #############\n \n self.channelLabel2 = ClickableLabel('' + 'CH 2' + '')\n self.stateButton2 = QtWidgets.QPushButton()\n self.stateButton2.setCheckable(True)\n \n self.frequencyLabel2 = ClickableLabel('Frequency: ')\n self.frequencyBox2 = SuperSpinBox(self.device._frequency_range, \n self.frequencyDisplayUnits, \n self.frequencyDigits)\n self.frequencyBox2.setFixedWidth(self.spinboxWidth)\n \n self.amplitudeLabel2 = ClickableLabel('Amplitude: ')\n self.amplitudeBox2 = SuperSpinBox(self.device._amplitude_range, \n self.amplitudeDisplayUnits, \n self.amplitudeDigits)\n self.amplitudeBox2.setFixedWidth(self.spinboxWidth)\n \n ##############\n \n self.layout = QtWidgets.QGridLayout() \n self.layout.addWidget(self.nameLabel, 0, 0, 1, 2,\n QtCore.Qt.AlignHCenter)\n \n self.layout.addWidget(self.channelLabel1, 1, 0, 1, 1, \n QtCore.Qt.AlignRight)\n self.layout.addWidget(self.stateButton1, 1, 1)\n self.layout.addWidget(self.frequencyLabel1, 2, 0, 1, 1, \n QtCore.Qt.AlignRight)\n self.layout.addWidget(self.frequencyBox1, 2, 1)\n self.layout.addWidget(self.amplitudeLabel1, 3, 0, 1, 1, \n QtCore.Qt.AlignRight)\n self.layout.addWidget(self.amplitudeBox1, 3, 1)\n \n self.layout.addWidget(self.channelLabel2, 4, 0, 1, 1, \n QtCore.Qt.AlignRight)\n self.layout.addWidget(self.stateButton2, 4, 1)\n self.layout.addWidget(self.frequencyLabel2, 5, 0, 1, 1, \n QtCore.Qt.AlignRight)\n self.layout.addWidget(self.frequencyBox2, 5, 1)\n self.layout.addWidget(self.amplitudeLabel2, 6, 0, 1, 1, \n QtCore.Qt.AlignRight)\n self.layout.addWidget(self.amplitudeBox2, 6, 1)\n \n self.setLayout(self.layout)\n\n self.setWindowTitle(self.name)\n self.setFixedSize(120 + self.spinboxWidth, 250)\n \n self.connectSignals()\n self.reactor.callInThread(self.getAll)\n \n def getAll(self):\n self.getRFState1()\n self.getFrequency1()\n self.getAmplitude1()\n \n self.getRFState2()\n self.getFrequency2()\n self.getAmplitude2()\n \n def getRFState1(self):\n rf_state1 = self.device.rf_state1\n self.reactor.callFromThread(self.displayRFState1, rf_state1)\n\n def displayRFState1(self, rf_state1):\n if rf_state1:\n self.stateButton1.setChecked(1)\n self.stateButton1.setText('RF ON')\n else:\n self.stateButton1.setChecked(0)\n self.stateButton1.setText('RF OFF')\n\n def getFrequency1(self):\n frequency1 = self.device.frequency1\n self.reactor.callFromThread(self.displayFrequency1, frequency1)\n\n def displayFrequency1(self, frequency1):\n self.frequencyBox1.display(frequency1)\n \n def getAmplitude1(self):\n amplitude1 = self.device.amplitude1\n self.reactor.callFromThread(self.displayAmplitude1, amplitude1)\n\n def displayAmplitude1(self, amplitude1):\n self.amplitudeBox1.display(amplitude1)\n \n def getRFState2(self):\n rf_state2 = self.device.rf_state2\n self.reactor.callFromThread(self.displayRFState2, rf_state2)\n\n def displayRFState2(self, rf_state2):\n if rf_state2:\n self.stateButton2.setChecked(1)\n self.stateButton2.setText('RF ON')\n else:\n self.stateButton2.setChecked(0)\n self.stateButton2.setText('RF OFF')\n \n def getFrequency2(self):\n frequency2 = self.device.frequency2\n self.reactor.callFromThread(self.displayFrequency2, frequency2)\n\n def displayFrequency2(self, frequency2):\n self.frequencyBox2.display(frequency2)\n \n def getAmplitude2(self):\n amplitude2 = self.device.amplitude2\n self.reactor.callFromThread(self.displayAmplitude2, amplitude2)\n\n def displayAmplitude2(self, amplitude2):\n self.amplitudeBox2.display(amplitude2)\n \n def connectSignals(self):\n self.nameLabel.clicked.connect(self.onNameLabelClick)\n \n self.frequencyLabel1.clicked.connect(self.onFrequencyLabelClick1)\n self.amplitudeLabel1.clicked.connect(self.onAmplitudeLabelClick1)\n \n self.stateButton1.released.connect(self.onNewRFState1)\n self.frequencyBox1.returnPressed.connect(self.onNewFrequency1)\n self.amplitudeBox1.returnPressed.connect(self.onNewAmplitude1)\n \n self.frequencyLabel2.clicked.connect(self.onFrequencyLabelClick2)\n self.amplitudeLabel2.clicked.connect(self.onAmplitudeLabelClick2)\n \n self.stateButton2.released.connect(self.onNewRFState2)\n self.frequencyBox2.returnPressed.connect(self.onNewFrequency2)\n self.amplitudeBox2.returnPressed.connect(self.onNewAmplitude2)\n \n def onNameLabelClick(self):\n self.reactor.callInThread(self.getAll)\n \n def onFrequencyLabelClick1(self):\n self.reactor.callInThread(self.getFrequency1)\n \n def onAmplitudeLabelClick1(self):\n self.reactor.callInThread(self.getAmplitude1)\n \n def onNewRFState1(self):\n rf_state1 = self.stateButton1.isChecked()\n self.reactor.callInThread(self.setRFState1, rf_state1)\n \n def setRFState1(self, rf_state1):\n self.device.rf_state1 = rf_state1\n self.reactor.callFromThread(self.displayRFState1, rf_state1)\n\n def onNewFrequency1(self):\n frequency1 = self.frequencyBox1.value()\n self.reactor.callInThread(self.setFrequency1, frequency1)\n\n def setFrequency1(self, frequency1):\n self.device.frequency1 = frequency1\n self.reactor.callFromThread(self.displayFrequency1, frequency1)\n \n def onNewAmplitude1(self):\n amplitude1 = self.amplitudeBox1.value()\n self.reactor.callInThread(self.setAmplitude1, amplitude1)\n\n def setAmplitude1(self, amplitude1):\n self.device.amplitude1 = amplitude1\n self.reactor.callFromThread(self.displayAmplitude1, amplitude1)\n \n ######################\n \n def onFrequencyLabelClick2(self):\n self.reactor.callInThread(self.getFrequency2)\n \n def onAmplitudeLabelClick2(self):\n self.reactor.callInThread(self.getAmplitude2)\n \n def onNewRFState2(self):\n rf_state2 = self.stateButton2.isChecked()\n self.reactor.callInThread(self.setRFState2, rf_state2)\n \n def setRFState2(self, rf_state2):\n self.device.rf_state2 = rf_state2\n self.reactor.callFromThread(self.displayRFState2, rf_state2)\n\n def onNewFrequency2(self):\n frequency2 = self.frequencyBox2.value()\n self.reactor.callInThread(self.setFrequency2, frequency2)\n\n def setFrequency2(self, frequency2):\n self.device.frequency2 = frequency2\n self.reactor.callFromThread(self.displayFrequency2, frequency2)\n \n def onNewAmplitude2(self):\n amplitude2 = self.amplitudeBox2.value()\n self.reactor.callInThread(self.setAmplitude2, amplitude2)\n\n def setAmplitude2(self, amplitude2):\n self.device.amplitude2 = amplitude2\n self.reactor.callFromThread(self.displayAmplitude2, amplitude2)\n \n @inlineCallbacks\n def connectLabrad(self):\n from labrad.wrappers import connectAsync\n self.cxn = yield connectAsync(name=self.name, host=os.getenv('LABRADHOST'), password='')\n yield self.cxn.update.signal__signal(self.updateID)\n yield self.cxn.update.addListener(listener=self.receiveUpdate, source=None, \n ID=self.updateID)\n yield self.cxn.update.register(self.name)\n \n def receiveUpdate(self, c, updateJson):\n # to be updated\n update = json.loads(updateJson)\n \n state1 = update.get('state1')\n if state1 is not None:\n self.displayState1(state1)\n frequency1 = update.get('frequency1')\n if frequency1 is not None:\n self.displayFrequency1(frequency1)\n amplitude1 = update.get('amplitude1')\n if amplitude1 is not None:\n self.displayAmplitude1(amplitude1)\n \n state2 = update.get('state2')\n if state2 is not None:\n self.displayState2(state2)\n frequency2 = update.get('frequency2')\n if frequency2 is not None:\n self.displayFrequency2(frequency2)\n amplitude2 = update.get('amplitude2')\n if amplitude2 is not None:\n self.displayAmplitude2(amplitude2)\n \n def closeEvent(self, x):\n self.reactor.stop()\n\nclass MultipleClientContainer(QtWidgets.QWidget):\n name = None\n def __init__(self, client_list, reactor):\n QtWidgets.QDialog.__init__(self)\n self.client_list = client_list\n self.reactor = reactor\n self.populateGUI()\n \n def populateGUI(self):\n self.layout = QtWidgets.QHBoxLayout()\n for client in self.client_list:\n self.layout.addWidget(client)\n self.setFixedSize(240 * len(self.client_list), 270)\n self.setWindowTitle(self.name)\n self.setLayout(self.layout)\n\n def closeEvent(self, x):\n super(MultipleClientContainer, self).closeEvent(x)\n self.reactor.stop()\n\nif __name__ == '__main__':\n from rf2.devices.moglabs_XRF import MoglabsXRFProxy\n\n class MoglabsXRFClient(MoglabsXRF_RFClient):\n name = 'Moglabs_XRF'\n DeviceProxy = MoglabsXRFProxy\n \n frequencyDigits = 6\n amplitudeDigits = 2\n fmgainDigits = 1\n amgainDigits = 1\n \n from PyQt5 import QtWidgets\n app = QtWidgets.QApplication([])\n from client_tools import qt5reactor \n qt5reactor.install()\n from twisted.internet import reactor\n\n widgets = [\n MoglabsXRFClient(reactor),\n ]\n \n widget = MultipleClientContainer(widgets, reactor)\n widget.show()\n reactor.suggestThreadPoolSize(30)\n reactor.run()\n","sub_path":"rf2/clients/moglabsXRF_client.py","file_name":"moglabsXRF_client.py","file_ext":"py","file_size_in_byte":12405,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"281843723","text":"from array import array\nimport ROOT as r\nimport math\nfrom random import randint\n\ndef quad(*xs):\n\treturn math.sqrt(sum(x*x for x in xs))\n\ndef Absy(histogram, histoName, bin_arrayx, absbin_arrayy):\n\t#new_histo = r.TH2D(histoName+str(randint(0,1000)), histogram.GetTitle()+\"abs\", len(bin_arrayx)-1, array(\"d\", bin_arrayx), len(absbin_arrayy)-1, array(\"d\", absbin_arrayy))\n\tnew_histo = r.TH2D(histoName, histogram.GetTitle()+\"abs\", len(bin_arrayx)-1, array(\"d\", bin_arrayx), len(absbin_arrayy)-1, array(\"d\", absbin_arrayy))\n\tfor x in range(new_histo.GetXaxis().GetNbins()):\n\t\tfor absy in range(new_histo.GetYaxis().GetNbins()):\n\t\t\tyup = new_histo.GetYaxis().GetBinCenter(absy+1)\n\t\t\tydown = - yup\n\t\t\tnew_histo.SetBinContent(x+1, absy+1, histogram.GetBinContent(x+1, histogram.GetYaxis().FindFixBin(yup)) + histogram.GetBinContent(x+1, histogram.GetYaxis().FindFixBin(ydown)))\n\t\t\t#err = histogram.GetBinError(x+1, histogram.GetYaxis().FindFixBin(yup))**2 + histogram.GetBinError(x+1, histogram.GetYaxis().FindFixBin(ydown))**2\n\t\t\t#new_histo.SetBinError(x+1, absy+1, math.sqrt(err))\n\t\t\tnew_histo.SetBinError(x+1, absy+1, quad(histogram.GetBinError(x+1,histogram.GetYaxis().FindFixBin(yup)),histogram.GetBinError(x+1,histogram.GetYaxis().FindFixBin(ydown))))\n\t\t\t#print yup, ydown\n\treturn new_histo\n\ndef newRebin2D(histogram, histoName, bin_arrayx, bin_arrayy):\n 'Rebin 2D histo with irregular bin size'\n #old binning\n oldbinx = [float(histogram.GetXaxis().GetBinLowEdge(1))]\n oldbiny = [float(histogram.GetYaxis().GetBinLowEdge(1))]\n oldbinx.extend(float(histogram.GetXaxis().GetBinUpEdge(x)) for x in xrange(1, histogram.GetNbinsX()+1))\n oldbiny.extend(float(histogram.GetYaxis().GetBinUpEdge(y)) for y in xrange(1, histogram.GetNbinsY()+1))\n\n #if new binninf is just one number and int, use it to rebin rather than as edges\n if len(bin_arrayx) == 1 and isinstance(bin_arrayx[0], int):\n nrebin = bin_arrayx[0]\n bin_arrayx = [j for i, j in enumerate(oldbinx) if i % nrebin == 0]\n if len(bin_arrayy) == 1 and isinstance(bin_arrayy[0], int):\n nrebin = bin_arrayy[0]\n bin_arrayy = [j for i, j in enumerate(oldbiny) if i % nrebin == 0]\n\n #create a clone with proper binning\n # from pdb import set_trace; set_trace()\n new_histo = r.TH2D(histoName, histogram.GetTitle(),\n\t\tlen(bin_arrayx)-1, array(\"d\", bin_arrayx),\n\t\tlen(bin_arrayy)-1, array(\"d\", bin_arrayy),\n )\n\n #check that new bins don't overlap on old edges\n for x in bin_arrayx:\n if x==0:\n if not any( abs((oldx)) < 10**-8 for oldx in oldbinx ):\n raise Exception('New bin edge in x axis %s does not match any old bin edge, operation not permitted' % x)\n else:\n if not any( abs((oldx / x)-1.) < 10**-8 for oldx in oldbinx ):\n raise Exception('New bin edge in x axis %s does not match any old bin edge, operation not permitted' % x)\n for y in bin_arrayy:\n if y ==0:\n if not any( abs((oldy) )< 10**-8 for oldy in oldbiny ):\n raise Exception('New bin edge in y axis %s does not match any old bin edge, operation not permitted' % y)\n else:\n if not any( abs((oldy / y)-1.) < 10**-8 for oldy in oldbiny ):\n raise Exception('New bin edge in y axis %s does not match any old bin edge, operation not permitted' % y)\n\n #fill the new histogram\n for x in xrange(0, histogram.GetNbinsX()+2 ):\n for y in xrange(0, histogram.GetNbinsY()+2 ):\n new_bin_x = new_histo.GetXaxis().FindFixBin(\n histogram.GetXaxis().GetBinCenter(x)\n )\n new_bin_y = new_histo.GetYaxis().FindFixBin(\n histogram.GetYaxis().GetBinCenter(y)\n )\n new_histo.SetBinContent(\n new_bin_x, new_bin_y,\n histogram.GetBinContent(x,y) +\n new_histo.GetBinContent(new_bin_x, new_bin_y)\n )\n new_histo.SetBinError(\n new_bin_x, new_bin_y,\n quad(\n histogram.GetBinError(x,y),\n new_histo.GetBinError(new_bin_x, new_bin_y)\n )\n )\n #new_histo.Fill(\n # histogram.GetXaxis().GetBinCenter(x),\n # histogram.GetYaxis().GetBinCenter(y),\n # histogram.GetBinContent(x,y)\n # )\n\n new_histo.SetEntries( histogram.GetEntries() )\n return new_histo\n","sub_path":"GenericModel/couplingmodels/Rebin.py","file_name":"Rebin.py","file_ext":"py","file_size_in_byte":4472,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"482507920","text":"\"\"\"Describe logbook events.\"\"\"\nfrom homeassistant.const import ATTR_ENTITY_ID, ATTR_NAME\nfrom homeassistant.core import callback\n\nfrom . import ATTR_SOURCE, DOMAIN, EVENT_AUTOMATION_TRIGGERED\n\n\n@callback\ndef async_describe_events(hass, async_describe_event): # type: ignore\n \"\"\"Describe logbook events.\"\"\"\n\n @callback\n def async_describe_logbook_event(event): # type: ignore\n \"\"\"Describe a logbook event.\"\"\"\n data = event.data\n message = \"has been triggered\"\n if ATTR_SOURCE in data:\n message = f\"{message} by {data[ATTR_SOURCE]}\"\n return {\n \"name\": data.get(ATTR_NAME),\n \"message\": message,\n \"source\": data.get(ATTR_SOURCE),\n \"entity_id\": data.get(ATTR_ENTITY_ID),\n }\n\n async_describe_event(\n DOMAIN, EVENT_AUTOMATION_TRIGGERED, async_describe_logbook_event\n )\n","sub_path":"homeassistant/components/automation/logbook.py","file_name":"logbook.py","file_ext":"py","file_size_in_byte":883,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"548945758","text":"#!/usr/bin/python3\n\"\"\"Divide a matrix\"\"\"\n\n\ndef matrix_divided(matrix, div):\n \"\"\"function that divides all elements of a matrix\"\"\"\n if not check_matrix(matrix):\n raise TypeError(\"matrix must be a matrix\\\n(list of lists) of integers/floats\")\n for i in matrix:\n if len(i) == len(matrix[0]):\n pass\n else:\n raise TypeError(\"Each row of the matrix must have the same size\")\n if not isinstance(div, int) and not isinstance(div, float):\n raise TypeError(\"div must be a number\")\n if div == 0:\n raise ZeroDivisionError(\"division by zero\")\n else:\n return [[round(x/div, 2) for x in j] for j in matrix]\n\n\ndef check_matrix(matrix):\n if not isinstance(matrix, list):\n return False\n for i in matrix:\n if type(i) is not list:\n return False\n if any(not isinstance(y, (int, float)) for y in i):\n return False\n return True\n","sub_path":"0x07-python-test_driven_development/2-matrix_divided.py","file_name":"2-matrix_divided.py","file_ext":"py","file_size_in_byte":938,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"611354043","text":"\"\"\"\nCopyright (c) 2020, 2021 Red Hat, IBM Corporation and others.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\"\"\"\n\nimport json\n\n\ndef get_all_tunables():\n \"\"\"\n Query Dependency Analyzer API for the sla_class, direction, ml_algo and tunables, and return them.\n\n Returns:\n direction (str): Direction of optimization, minimize or maximize.\n ml_algo_impl (str): Hyperparameter optimization library to perform Bayesian Optimization.\n sla_class (str): The objective function that is being optimized.\n tunables (list): A list containing the details of each tunable in a dictionary format.\n \"\"\"\n # JSON returned by the Dependency Analyzer\n # Placeholder code until the actual API parsing code is added\n tuning_set_json = '{\"sla_class\": \"response_time\", \"direction\": \"minimize\", \"ml_algo_impl\": \"optuna_tpe\", ' \\\n '\"tunables\": [{\"name\": \"cpuRequest\", \"value_type\": \"double\", \"upper_bound\": 4, \"lower_bound\": ' \\\n '1, \"step\": 0.01}, {\"name\": \"memoryRequest\", \"value_type\": \"double\", \"upper_bound\": 1024, ' \\\n '\"lower_bound\": 100, \"step\": 0.01}]} '\n tuning_set = json.loads(tuning_set_json)\n sla_class = tuning_set[\"sla_class\"]\n direction = tuning_set[\"direction\"]\n ml_algo_impl = tuning_set[\"ml_algo_impl\"]\n tunables = tuning_set[\"tunables\"]\n return direction, ml_algo_impl, sla_class, tunables\n","sub_path":"hyperparameter_tuning/tunables.py","file_name":"tunables.py","file_ext":"py","file_size_in_byte":1895,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"429063126","text":"#!/usr/bin/python3\n# coding: utf-8\n\n\"\"\"\nAutors: CEREMA/DTerSO/DALETT/ESAD-ZELT/ TAHINJANAHARY Jean Noël\nProjet: Capteur Bluetooth open Source et open Hardware\n\"\"\"\n\nimport time, datetime\nimport threading\nimport signal\nimport paho.mqtt.client as paho\nimport sys, json\nimport bluetooth\nimport publisher as pub\n \nclass Detection(threading.Thread):\n \n\tdef __init__(self, delais,publish):\n\t\tthreading.Thread.__init__(self)\n\t\t# The keep_running is a threading.Event object that\n\t\t# indicates whether the thread should be terminated.\n\t\tself.keep_running = threading.Event()\n\t\tprint(delais)\n\t\tself.__delais = delais\n\t\tself.__publish = publish\n\t\t# ... Other thread setup code here ...\n \n\tdef run(self):\n\t\tprint(\"Thread # {} started\\n\".format(self.ident))\n\t\tprint(\"Detection code start here\")\n\t\twhile not self.keep_running.is_set():\n\t\t\t# ... Detection code here ...\n\t\t\tnearby_devices = bluetooth.discover_devices(duration=self.__delais, lookup_names=True, flush_cache= True, lookup_class=False)\n\t\t\tif len(nearby_devices) != 0:\n\t\t\t\t#What time is it please ?\n\t\t\t\tnow = datetime.datetime.today()\n\t\t\t\t#print(now.year, now.month, now.day, now.hour, now.minute, now.second)\n\t\t\t\thorodate = [now.year, now.month, now.day, now.hour, now.minute, now.second]\n\t\t\t\tnearby_devices.insert(0,horodate)\n\t\t\t\tself.__publish(nearby_devices)\n\t\t\t\ttime.sleep(.5)\n\t\t\telse:\n\t\t\t\tprint(\"No device detected ...\")\n\t\t\t\ttime.sleep(.5)\n \n\t\t# ... Clean shutdown code here ...\n\t\tprint(\"\\nThread # {} stopped\\n\".format(self.ident))\n\t\t\t\n\t\n\t\nclass ServiceExit(Exception):\n\t\"\"\"\n\tCustom exception which is used to trigger the clean exit\n\tof all running threads and the main program.\n\t\"\"\"\n\tpass\n \n \ndef service_shutdown(signum, frame):\n\tprint(\"\\nCaught signal {}\".format( signum))\n\traise ServiceExit\n\ndef main():\n\t# Register the signal handlers\n\tsignal.signal(signal.SIGTERM, service_shutdown)\n\tsignal.signal(signal.SIGINT, service_shutdown)\n \n\tprint(\"Starting main program\")\n\tprint(\"*********************\\n\\n\")\n\tprint(\"To Exit Press Ctrl+C\")\n\tprint(\"*********************\\n\\n\")\n\t# Start the detection threads\n\n\ttry:\n\t\tdetection = Detection(2,pub.on_publish)\n\t\tdetection.start()\n \n\t\t# Keep the main thread running, otherwise signals are ignored.\n\t\twhile True:\n\t\t\ttime.sleep(0.5)\n \n\texcept ServiceExit:\n\t\t# Terminate the running threads.\n\t\t# Set the shutdown flag on each thread to trigger a clean shutdown of each thread.\n\t\tdetection.keep_running.set()\n\t\t# Wait for the threads to close...\n\t\tdetection.join()\n\tpub.on_disconnect()\n\tprint('Exiting main program')\n \n \nif __name__ == '__main__':\n\tmain()\n","sub_path":"main_program.py","file_name":"main_program.py","file_ext":"py","file_size_in_byte":2550,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"575595881","text":"from die import Die\nimport pygal\n#创建两个筛子\ndie_1= Die()\ndie_2= Die()\nresults=[]\nfor roll_num in range(1000):\n result = die_1.roll()+die_2.roll()\n results.append(result)\n#分析结果\nfrequencies = []\nmax_result = die_1.num_sides+die_2.num_sides\nfor value in range(1,max_result+1):\n frequency = results.count(value)\n frequencies.append(frequency)\n#对结果进行可视化\nhist = pygal.Bar()\n\nhist.title = 'tesults of rolling one D6 1000 times'\nhist.x_lables = ['2','3','4','5','6','7','8','9','11','10','12']\nhist.x_title = 'Result'\nhist.y_title = 'Frequency of Rrsult'\n\nhist.add('D6+D6',frequencies)\nhist.render_to_file('dice_visual.svg')","sub_path":"matplotlib 应用/die_visual.py","file_name":"die_visual.py","file_ext":"py","file_size_in_byte":661,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"359722957","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\nfrom selenium import webdriver\nfrom time import sleep\n\ndriver = webdriver.Firefox()\n\nfirst_url = \"https://www.google.com.tw\"\nprint(\"now access %s\" % first_url)\ndriver.get(first_url)\nsleep(1)\n\nsecond_url = \"https://news.google.com/news/?ned=tw&hl=zh-TW&gl=TW\"\nprint(\"now access %s\" % second_url)\ndriver.get(second_url)\nsleep(1)\n\nprint(\"back to %s\" % first_url)\ndriver.back()\nsleep(1)\n\nprint(\"forward to %s\" % second_url)\ndriver.forward()\nsleep(1)\n\nstock_url = \"https://tw.stock.yahoo.com/\"\nprint(\"now access %s\" % stock_url)\ndriver.get(stock_url)\nsleep(2)\n\nfor i in range(1, 11):\n print(\"%d refresh\" %i)\n driver.refresh()\n sleep(2)\n\n# driver.quit()\n","sub_path":"ch04/back_forward_refresh.py","file_name":"back_forward_refresh.py","file_ext":"py","file_size_in_byte":704,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"463837967","text":"from astropy import wcs\nfrom astropy.io import fits\nimport numpy as np\n# from spire_data_utils import *\n\n\n\ndef find_lowest_mod(number, mod_number):\n while number > 0:\n if np.mod(number, mod_number) == 0:\n return number\n else:\n number -= 1\n return False\n\ndef find_nearest_upper_mod(number, mod_number):\n while number < 10000:\n if np.mod(number, mod_number) == 0:\n return number\n else:\n number += 1\n return False\n\nclass wcs_astrometry():\n ''' This class will contain the WCS header and other information necessary to construct arrays for fast \n astrometric transformations. \n \n Variables:\n \n all_fast_arrays (list of nd.arrays): contains all astrometry arrays across bands\n e.g. len(all_fast_arrays)= n_bands - 1\n \n dims (list of tuples): contains image dimensions for all observations\n \n wcs_objs (list of astropy.WCS objects): obtained from observation WCS headers\n \n filenames (list): observation names obtained when loading in FITS files\n \n \n Input:\n - \n -\n \n Functions:\n \n fit_astrom_arrays(): This function computes the mapping for lattices of points from one observation to \n another, using first differencing to get derivatives for subpixel perturbations.\n \n load_wcs_header(fits): Yes\n \n load_fast_astrom_arrays(fast_arrays): this loads in the arrays to the wcs_astrometry object to be \n used for 1st order approximation to astrometry\n \n pixel_to_pixel(coords, idx0, idx1): this will take coordinates in one observation (idx0) and convert them to \n the observation indicated by idx1. Will throw error if arrays to do so do not exist in class object\n \n \n Outputs:\n - \n - np.array([x', y', dy'/dx, dy'/dy, dx'/dx, dx'/dy])\n - \n '''\n \n all_fast_arrays = []\n wcs_objs = []\n filenames = []\n dims = []\n verbosity = 0\n \n # base_path = '/Users/richardfeder/Documents/multiband_pcat/Data/spire/'\n\n \n def __init__(self, auto_resize=False, nregion=1, base_path='/Users/richardfeder/Documents/multiband_pcat/Data/spire/'):\n self.wcs_objs = []\n self.filenames = []\n self.all_fast_arrays = []\n self.dims = []\n self.auto_resize = auto_resize\n self.nregion = nregion\n self.base_path = base_path\n \n def change_verbosity(self, verbtype):\n self.verbosity = verbtype\n\n def change_base_path(self, basepath):\n self.base_path = basepath\n \n def load_wcs_header_and_dim(self, filename=None, head=None, hdu_idx=None, round_up_or_down='up'):\n if head is None:\n self.filenames.append(filename)\n \n f = fits.open(filename)\n\n if hdu_idx is None:\n hdu_idx = 0\n \n head = f[hdu_idx].header\n\n if self.auto_resize:\n try:\n big_dim = np.maximum(head['NAXIS1'], head['NAXIS2'])\n except:\n print('didnt work upping it')\n hdu_idx += 1\n head = f[hdu_idx].header\n big_dim = np.maximum(head['NAXIS1'], head['NAXIS2'])\n\n if round_up_or_down =='up':\n big_pad_dim = find_nearest_upper_mod(big_dim, self.nregion)\n else:\n big_pad_dim = find_lowest_mod(big_dim, self.nregion)\n\n dim = (big_pad_dim, big_pad_dim)\n else:\n try:\n dim = (head['NAXIS1'], head['NAXIS2'])\n except:\n hdu_idx += 1\n head = f[hdu_idx].header\n dim = (head['NAXIS1'], head['NAXIS2'])\n print('dim:', dim)\n self.dims.append(dim)\n wcs_obj = wcs.WCS(head)\n self.wcs_objs.append(wcs_obj)\n \n def obs_to_obs(self, idx0, idx1, x, y):\n ra, dec = self.wcs_objs[idx0].all_pix2world(x, y, 0)\n x1, y1 = self.wcs_objs[idx1].all_world2pix(ra, dec, 0)\n return x1, y1\n \n def get_pint_dp(self, p):\n pint = np.floor(p+0.5)\n dp = p - pint\n return pint.astype(int), dp\n \n def get_derivative(self, idx0, idx1, x, y, epsx, epsy):\n \n x1, y1 = self.obs_to_obs(idx0, idx1, x+epsx, y+epsy)\n x0, y0 = self.obs_to_obs(idx0, idx1, x-epsx, y-epsy)\n \n dxp = x1 - x0\n dyp = y1 - y0\n \n if self.verbosity > 0:\n print('dxp:')\n print(dxp)\n print('dyp:')\n print(dyp)\n \n return dxp, dyp\n \n def fit_astrom_arrays(self, idx0, idx1, bounds0=None, bounds1=None):\n print('idx0:', idx0)\n print(self.dims)\n \n\n if bounds0 is not None:\n # if a rectangular mask is provided, then we only need to pre-compute the astrometry arrays over the masked region\n x = np.arange(bounds0[0,0], bounds0[0,1]+self.dims[idx0][0])\n y = np.arange(bounds0[1,0], bounds0[1,1]+self.dims[idx0][1])\n\n else:\n\n x = np.arange(0, self.dims[idx0][0])\n y = np.arange(0, self.dims[idx0][1])\n \n xv, yv = np.meshgrid(x, y)\n\n \n if self.verbosity > 0:\n print('xv:')\n print(xv)\n print('yv:')\n print(yv)\n\n dxp_dx, dyp_dx = self.get_derivative(idx0, idx1, xv, yv, 0.5, 0.0)\n dxp_dy, dyp_dy = self.get_derivative(idx0, idx1, xv, yv, 0.0, 0.5)\n \n xp, yp = self.obs_to_obs(idx0, idx1, xv, yv)\n\n if bounds1 is not None:\n xp -= bounds1[0,0]\n yp -= bounds1[1,0]\n \n if self.verbosity > 0:\n print('xp:')\n print(xp)\n print('yp:')\n print(yp)\n \n fast_arrays = np.array([xp, yp, dxp_dx, dyp_dx, dxp_dy, dyp_dy])\n self.all_fast_arrays.append(fast_arrays)\n \n def transform_q(self, x, y, idx):\n \n assert len(x)==len(y)\n xtrans, ytrans, dxpdx, dypdx, dxpdy, dypdy = self.all_fast_arrays[idx]\n xints, dxs = self.get_pint_dp(x)\n yints, dys = self.get_pint_dp(y)\n try:\n xnew = xtrans[yints,xints] + dxs*dxpdx[yints,xints] + dys*dxpdy[yints,xints]\n ynew = ytrans[yints,xints] + dxs*dypdx[yints,xints] + dys*dypdy[yints,xints] \n return np.array(xnew).astype(np.float32), np.array(ynew).astype(np.float32)\n except:\n print(np.max(xints), np.max(yints), xtrans.shape)\n print(xints, dxs, yints, dys)\n raise ValueError('problem accessing elements')\n\n\n\n\n\n\n ","sub_path":"fast_astrom.py","file_name":"fast_astrom.py","file_ext":"py","file_size_in_byte":6717,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"444258548","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Aug 15 13:55:11 2021\n\n@author: admin\n\"\"\"\n#perfect nummer example -- 6 = 1+2+3\nnum = 56\nls = []\n#ls = [i for i in range(1,num) if num%i == 0 ]\nfor i in range(1,num):\n if num%i == 0:\n ls.append(i)\n \nx = sum(ls) \nif x == num:\n print(\"Perfect\")\nelse:\n print(\"not\")\n \n ","sub_path":"projects/perfectnumber.py","file_name":"perfectnumber.py","file_ext":"py","file_size_in_byte":344,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"112143323","text":"#######################################################################\r\n### fcnn.py ###\r\n#######################################################################\r\n\r\nimport numpy as np\r\nfrom keras.models import Model, load_model\r\nfrom keras.layers import Input, Dense, BatchNormalization\r\nfrom keras.layers.advanced_activations import ReLU\r\nfrom keras.optimizers import RMSprop, Adam\r\nfrom keras.callbacks import EarlyStopping, ModelCheckpoint\r\nfrom keras import backend as K\r\n\r\n\r\n########################### function ################################\r\ndef batchGenerator(X, y, batch_size, input_length):\r\n batch_X = np.zeros((batch_size, input_length))\r\n\r\n\r\ndef r_square(y_true, y_pred):\r\n SS_res = K.sum(K.square(y_true - y_pred))\r\n SS_tot = K.sum(K.square(y_true - K.mean(y_true)))\r\n return (1 - SS_res/(SS_tot + K.epsilon()))\r\n\r\ndef pearson_coef(y_true, y_pred):\r\n y_true_c = y_true - K.mean(y_true)\r\n y_pred_c = y_pred - K.mean(y_pred)\r\n return K.sum(y_true_c * y_pred_c) / (K.sqrt(K.sum(K.square(y_true_c)) * K.sum(K.square(y_pred_c))) + K.epsilon())\r\n\r\n\r\n########################### model ################################\r\nclass fcnn(object):\r\n '''\r\n Fully connected nerual network\r\n '''\r\n def __init__(self, input_length, learning_rate=1e-4, optimizer='Adam'):\r\n self.input_length = input_length\r\n self.learning_rate = learning_rate\r\n if optimizer == 'Adam':\r\n self.optimizer = Adam(lr=self.learning_rate)\r\n elif optimizer == 'RMSprop':\r\n self.optimizer = RMSprop(lr=self.learning_rate, decay=1e-6)\r\n else:\r\n raise ValueError('Unrecognizable optimizer. Either Adam or RMSprop.')\r\n self.model = self._model()\r\n \r\n\r\n def _model(self):\r\n print('Initilizing fully connected nerual netowrk model ...', end='', flush=True)\r\n inputs = Input(shape=(self.input_length,), name='input')\r\n\r\n dense1 = Dense(256) (inputs)\r\n bn1 = BatchNormalization() (dense1)\r\n relu1 = ReLU(max_value=6.0) (bn1)\r\n\r\n dense2 = Dense(256) (relu1)\r\n bn2 = BatchNormalization() (dense2)\r\n relu2 = ReLU(max_value=6.0) (bn2)\r\n\r\n dense3 = Dense(256) (relu2)\r\n bn3 = BatchNormalization() (dense3)\r\n relu3 = ReLU(max_value=6.0) (bn3)\r\n\r\n output = Dense(1) (relu3)\r\n\r\n model = Model(inputs=inputs, outputs=output)\r\n model.compile(loss='mse', optimizer=self.optimizer, metrics=['mse', r_square, pearson_coef])\r\n print(' Done\\nModel structure summary:', flush=True)\r\n print(model.summary())\r\n\r\n return model\r\n \r\n def train(self, X_train, y_train, model_name, validation_split=0.0, validation_data=None, batch_size=32, epochs=200, verbose=1):\r\n print('Start training neural network ... ', end='', flush=True)\r\n early_stopper = EarlyStopping(patience=5, verbose=1)\r\n check_pointer = ModelCheckpoint(model_name, verbose=1, save_best_only=True)\r\n result = self.model.fit(X_train, y_train, \r\n validation_split=validation_split, \r\n validation_data=validation_data,\r\n batch_size=batch_size, \r\n epochs=epochs, \r\n verbose=verbose,\r\n shuffle=True,\r\n callbacks=[early_stopper, check_pointer])\r\n self.model = load_model(model_name)\r\n print('Done')\r\n\r\n\r\n def loadModel(self, path):\r\n print('Loading trained neural network model ... ', end='', flush=True)\r\n self.model = load_model(path)\r\n print('Done')\r\n \r\n def predict(self, X):\r\n print('Predicting with nerual network model ... ', flush=True)\r\n y = self.model.predict(X, verbose=1)\r\n return y","sub_path":"code/predict/model/fcnn.py","file_name":"fcnn.py","file_ext":"py","file_size_in_byte":3904,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"320535385","text":"import pickle\r\nfrom sklearn.pipeline import Pipeline, FeatureUnion\r\nfrom sklearn.svm import SVC\r\n\r\nfrom train.svm.shared_feature_computer import SharedFeatureComputer\r\nfrom train.svm.similarity_feature_computer import SimilarityFeatureComputer\r\nfrom train.utils import get_data\r\n\r\n\r\ndef create_model():\r\n file_name = 'train_batch1.csv'\r\n X, y = get_data(file_name)\r\n\r\n pipeline = Pipeline([\r\n ('feature_merging', FeatureUnion([\r\n ('shared_features', SharedFeatureComputer()),\r\n ('sim_features', SimilarityFeatureComputer()),\r\n ])\r\n ),\r\n ('clf', SVC(C=100))\r\n ])\r\n pipeline.fit(X, y)\r\n\r\n with open('svm_model.pkl', 'wb') as file:\r\n pickle.dump(pipeline, file)\r\n\r\nwith open('svm_model.pkl', 'rb') as f:\r\n loaded_model = pickle.load(f)\r\nX, y = get_data('train_batch1.csv')\r\nresults = loaded_model.predict(X)\r\nprint(results)\r\n","sub_path":"train/svm/create_model.py","file_name":"create_model.py","file_ext":"py","file_size_in_byte":909,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"553498078","text":"# Definition for singly-linked list.\n# class ListNode(object):\n# def __init__(self, x):\n# self.val = x\n# self.next = None\n\nclass Solution(object):\n def isPalindrome(self, head):\n \"\"\"\n :type head: ListNode\n :rtype: bool\n \"\"\"\n if not head or not head.next: return True\n slow=fast=head\n while fast.next and fast.next.next:\n fast=fast.next.next\n slow=slow.next\n if fast.next:\n slow=slow.next\n slow=self.reverse(slow)\n while slow:\n if slow.val!=head.val:\n return False\n slow=slow.next\n head=head.next\n return True\n def reverse(self, head):\n pre=None\n while head:\n next=head.next\n head.next=pre\n pre=head\n head=next\n return pre","sub_path":"234-Palindrome-Linked-List/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":870,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"16760843","text":"#######libraries############\nfrom bs4 import BeautifulSoup as bs\nfrom flask import Flask,request,jsonify,render_template\nimport pymongo\nfrom flask_cors import CORS,cross_origin\nimport requests as req\nfrom urllib.request import urlopen as ureq\n######libraries############\n\n\napp=Flask(__name__)\n\n@app.route('/',methods=['POST','GET'])\n@cross_origin()\ndef home():\n return render_template('index.html')\n\n@app.route('/scrap',methods=['POST'])\n@cross_origin()\ndef index():\n if request.method =='POST':\n search=request.form['content'].replace(' ','')\n try:\n '''''\n connect=pymongo.MongoClient(\"mongodb://localhost:27017/\")\n db=connect['first_crawler_flipkart']\n item_table=db[search].find({})\n #print(item_table.count())\n review_list = []\n if item_table.count()>0:\n return render_template('results.html',reviews=item_table)\n '''''\n review_list = []\n flipkart_url = \"https://www.flipkart.com/search?q=\" + search\n print(flipkart_url)\n uclient = ureq(flipkart_url)\n html_page = uclient.read()\n flipkart_html = bs(html_page, 'html.parser')\n box = flipkart_html.findAll('div', {'class': '_1AtVbE col-12-12'})\n del box[0:2]\n for i in box:\n #print(i)\n try:\n long_short_desc = list(i.div.children)\n except:\n print('not required tag')\n if len(long_short_desc) != 1:\n sbox = i.findAll('div', {'class': '_4ddWXP'})\n else:\n sbox = long_short_desc\n for j in sbox:\n product_link = \"https://www.flipkart.com\" + j.a['href']\n req = ureq(product_link)\n product_html = bs(req.read(), 'html.parser')\n whole_reviews = product_html.findAll('div', {'class': '_2c2kV-'})\n for k in whole_reviews:\n whole_com = k.findAll('div', {'class': '_16PBlm'})\n for l in whole_com:\n try:\n heading = l.div.div.div.p.text\n except:\n heading = 'NO heading'\n try:\n rating = l.div.div.div.div.text\n except:\n rating = 'no rating'\n try:\n comment = l.find('div', {'class': 't-ZTKy'}).div.div.text\n except:\n comment='no comment'\n try:\n name = l.find('p',{'class':'_2sc7ZR _2V5EHH'}).text\n except:\n name = 'no name'\n mydict = {\"Product\": search, \"Name\": name, \"Rating\": rating, \"CommentHead\": heading,\"Comment\":comment}\n #table.insert_one(mydict)\n #print(mydict)\n review_list.append(mydict)\n render_template('results.html', reviews=review_list)\n #print(review_list)\n return render_template('results.html',reviews=review_list)\n except Exception as e:\n print(e)\n return 'Something is wrong'\n else:\n return render_template('index.html')\n\n\n\n\n\n\n\n\n\n\nif __name__==\"__main__\":\n app.run(debug=True)\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":3627,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"117011329","text":"import random\nimport display as disp\nimport matplotlib.pylab as plt\n\n\nclass subadult:\n def __init__(self, sex):\n self.age = 15\n self.sex = sex\n\n\nclass Child:\n def __init__(self, sex):\n self.age = 0\n self.sex = sex\n\n def death(self,mom,adultFemale,subAdultFemale,childnum,env):\n deathrate_constant = (0.47 + mom*0.23 + (childnum-1)*43/13*0.01)*1.78/(2-env)\n if random.random()>deathrate_constant: # die\n return 1\n return 0\n\n\n\nclass Adult:\n def __init__(self, sex):\n self.sex = sex\n self.age = 30\n self.next_bear = 0\n self.child = []\n\n\n def deathrate(self,env):\n deathrate_constant = (self.age-36)/3*2.5/100\n if random.random() ')\n\n # 연도 Passing\n month += 3\n\n #print('-'*100)\n #print(\"Current Month \"+str(month))\n\n # 모든 객체 나이 증가 --> 나이에 따라 계급 변화 --> 어른이 죽을까? --> 만약 죽었을 때 아이가 있다면 입양 --> 출산\n\n number_of_adult_female = 0\n for i in ad:\n if i.sex is 'Female':\n number_of_adult_female += 1\n\n number_of_subadult_female = 0\n for i in subad:\n if i.sex is 'Female':\n number_of_subadult_female += 1\n\n number_of_child = 0\n for i in ad:\n for j in i.child:\n number_of_child += 1\n\n\n k = 18\n env = (k-(number_of_child+len(subad)+number_of_adult_female))/k\n\n\n # 준성체 나이 증가\n for i in subad:\n i.age += 3\n\n # 어른 나이 증가/ 아이 나이 증가\n for i in ad:\n i.age += 3\n for j in i.child:\n j.age += 3\n if j.death(1,number_of_adult_female,number_of_subadult_female,number_of_child,env) == 1:\n #print(\"[Event] Death of Child\")\n i.child.remove(j)\n\n for i in 고아:\n i.age += 3\n if i.death(0,number_of_adult_female,number_of_subadult_female,number_of_child,env)==1:\n #print(\"[Event] Death of Child\")\n 고아.remove(i)\n\n removes = []\n\n # subad --> Ad\n for i in subad:\n if i.age >= 30:\n 성별 = i.sex\n removes.append(i)\n if 성별 is 'Female':\n ad.append(Adult(성별))\n\n for i in removes:\n subad.remove(i)\n\n removes.clear()\n\n # child --> subad\n for i in ad:\n for j in i.child:\n if j.age >= 15:\n 성별 = j.sex\n removes.append(j)\n subad.append(subadult(성별))\n\n for j in removes:\n i.child.remove(j)\n\n removes.clear()\n\n # orphans(child) --> subad\n for i in 고아:\n if i.age >= 15:\n 성별 = i.sex\n removes.append(i)\n subad.append(subadult(성별))\n for i in removes:\n 고아.remove(i)\n\n\n\n # 어른이 죽는가?\n for i in range(len(ad)):\n # print(i)\n try:\n if ad[i].deathrate(env):\n # 어른은 그냥 죽을 수 없다 애들을 입양 보내야 한다!\n for j in range(len(ad[i].child)):\n 고아.append(ad[i].child[j])\n ad.remove(ad[i])\n\n #print('\\n[Event] '+str(i+1)+\" death\")\n # print(ad)\n # print(고아)\n\n except IndexError:\n pass\n\n # 입양 프로세스\n 입양할사람수 = 0\n for i in ad:\n if len(i.child)==0 and i.sex is 'Female':\n 입양할사람수 += 1\n\n # print('입양할 사람수',end='')\n # print(입양할사람수)\n #\n total_orphans = len(고아)\n # print('total_orphans',end='')\n # print(total_orphans)\n # print(고아)\n\n\n if 입양할사람수 and total_orphans:\n for i in ad:\n if len(i.child) == 0 and i.sex is 'Female': #입양자를 찾음\n #print(고아)\n try:\n if 입양할사람수 > 1:\n for j in range(int(total_orphans/입양할사람수)):\n i.child.append(고아[0])\n 고아.remove(고아[0])\n else:\n for j in range(len(고아)):\n i.child.append(고아[0])\n 고아.remove(고아[0])\n except IndexError:\n pass\n\n 입양할사람수 -= 1\n\n # Give Birth to babies ??\n parent_ad = []\n 아기를낳은어른수 = 0\n for i in ad:\n flag = i.give_birth(month)\n if flag:\n 아기를낳은어른수 += flag\n parent_ad.append(i)\n\n for i in range(int(아기를낳은어른수 / 2) + 1, 아기를낳은어른수):\n parent_ad[i].child.clear()\n parent_ad[i].next_bear -= 12\n\n\n # # For Clan Display\n # print('')\n # for i in range(len(ad)):\n # disp.display_adult(ad[i])\n #\n # print('')\n # for i in range(len(고아)):\n # disp.display_nonadult(고아[i])\n #\n # print('')\n # for i in range(len(subad)):\n # disp.display_nonadult(subad[i])\n\n #print()\n\n t1 = len(ad)\n t2 = 0\n for i in subad:\n if i.sex is 'Female':\n t2 += 1\n t3 = len(subad)-t2\n t4 = 0\n t5 = 0\n for i in ad:\n for j in i.child:\n if j.sex is 'Female':\n t4 += 1\n else:\n t5 += 1\n\n data1.append(t1)\n data2.append(t2)\n data3.append(t3)\n data4.append(t4)\n data5.append(t5)\n\n # print(a)\n # if a == 'show':\n # plt.title(\"Population Number Change by Months\")\n # colors = ['r', 'g', 'b', 'y', 'c', 'm']\n # markers = [\"o\", \"^\", \"s\", \"D\"]\n # plt.plot(range(int(month/3)), data1, c=colors[0], label='Adult Female')\n # plt.plot(range(int(month/3)), data2, c=colors[1], label='SubAdult Female')\n # plt.plot(range(int(month/3)), data3, c=colors[2], label='SubAdult Male')\n # plt.plot(range(int(month/3)), data4, c=colors[3], label='Child Female')\n # plt.plot(range(int(month/3)), data5, c=colors[4], label='Child Male')\n # plt.legend()\n # plt.ylabel(\"Number of Poplulation\")\n # plt.xlabel(\"Month\")\n # plt.show()\n\n avg1 += int(data1[-1])\n avg2 += int(data2[-1])\n avg3 += int(data3[-1])\n avg4 += int(data4[-1])\n avg5 += int(data5[-1])\n\nprint(avg1/loops)\nprint(avg2/loops)\nprint(avg3/loops)\nprint(avg4/loops)\nprint(avg5/loops)\n","sub_path":"nonhelping_clan.py","file_name":"nonhelping_clan.py","file_ext":"py","file_size_in_byte":8617,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"6"} +{"seq_id":"503490008","text":"import argparse\nimport numpy as np\nimport torch\nimport tqdm\nimport os\nimport pickle as pkl\nimport scipy as sp\nfrom base import utils as ut\n\nfrom base.train import train3d_Siamese\nfrom base.train import train3d_cls, train3d_cls_rnn\nfrom base.models.nns.v13 import Classifier\nfrom pprint import pprint\nfrom torchvision import datasets, transforms\n\nimport joblib\nfrom codebase.models.ae_relu_weight_tri import MultipleTimestepLSTM\n\n\nparser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)\nparser.add_argument('--z', type=int, default=512, help=\"Number of latent dimensions\")\nparser.add_argument('--iter_max', type=int, default=1580, help=\"Number of training iterations\")\nparser.add_argument('--iter_save', type=int, default=50, help=\"Save model every n iterations\")\nparser.add_argument('--run', type=int, default=35, help=\"Run ID. In case you want to run replicates\")\nparser.add_argument('--train', type=int, default=14, help=\"Flag for training\")\nparser.add_argument('--Type', type=str, default='Run_cls_new', help=\"Flag for training\")\n''' Type: Run_all_label_time_tri/Run_all_time/ Run_only_normal_time, Run_4_time, Run_all_label_time, Run_cls'''\nparser.add_argument('--iter_restart', type=int, default=4800, help=\"Save model every n iterations\")\nparser.add_argument('--BATCH_SIZE', type=int, default=20, help=\"Flag for training\")\nparser.add_argument('--iter_load', type=int, default=1, help=\"Flag for loading version of model\")\nparser.add_argument('--Siamese', type=str, default='SiameseNetTri', help=\"SiameseNetTri\\SiameseNetAE\\SiameseNet\\SiameseNetW\\SiamgeseNetAEReg\")\n\ncls_list= [0,2] # [0,1] -- [NC.MCI]\n\nglobal_step = 1500\n\n\n\n''' Initialize model layout'''\nargs = parser.parse_args()\n\nif args.Siamese == 'SiameseNetTri':\n from base.models.model import VAE3d, Siamese_Network_v2\n from base.models.nns.v13 import Distance_Relu_Loss\n\nType = args.Type\nvae3d_layout = [\n ('model={:s}', 'vae3d'),\n ('z={:02d}', args.z),\n ('run={:04d}', args.run)\n]\nvae3d_model_name = '_'.join([t.format(v) for (t, v) in vae3d_layout])\n\nrelu_loss_layout = [\n ('model={:s}', 'relu_loss'),\n ('z={:02d}', args.z),\n ('run={:04d}', args.run)\n]\nrelu_loss_model_name = '_'.join([t.format(v) for (t, v) in relu_loss_layout])\n\nSiameseNet_layout = [\n ('model={:s}', args.Siamese),\n ('z={:02d}', args.z),\n ('run={:04d}', args.run)\n]\nSiameseNet_model_name = '_'.join([t.format(v) for (t, v) in SiameseNet_layout])\n\nClassifier_layout = [\n ('model={:s}', 'Classfier'),\n ('z={:02d}', args.z),\n ('run={:04d}', args.run)\n]\nClassifier_model_name = '_'.join([t.format(v) for (t, v) in Classifier_layout])\n\nRNN_layout = [\n ('model={:s}', 'RNN'),\n ('z={:02d}', args.z),\n ('run={:04d}', args.run)\n]\nRNN_model_name = '_'.join([t.format(v) for (t, v) in RNN_layout])\n\n\n\npprint(vars(args))\nprint('Model name:', SiameseNet_model_name)\n\ndevice = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n\n''' Set random seed'''\nut.set_seed(2020)\n\npath =\"/scratch/users/zucks626/ADNI/ADNI_Longitudinal_1styear/raw_image/\"\npath_saveimg = \"/scratch/users/zucks626/ADNI/ADNI_Longitudinal_1styear/save_image/\"\n\npath_1 = \"/scratch/users/zucks626/ADNI/ADNI_Longitudinal_2ndyear/raw_image/\"\npath_2 = \"/scratch/users/zucks626/ADNI/ADNI_Longitudinal_1styear/raw_image/\"\npath2_saveimg = \"/scratch/users/zucks626/ADNI/ADNI_Longitudinal_2ndyear/save_image/\"\npath_all = \"/scratch/users/zucks626/ADNI/ADNI_Longitudinal_all/raw_image/\"\npathall_saveimg = \"/scratch/users/zucks626/ADNI/ADNI_Longitudinal_all/save_image/\"\n\npathallnew_img='/scratch/users/zucks626/ADNI/ADNI_Longitudinal_all_new/img_64_longitudinal/raw_image/'\nif Type == 'Run_cls_new':\n ''' Extract data from pickle file'''\n f = open(pathall_saveimg + \"augment_pair_cls_AD_rnn.pkl\",\"rb\")\n pair = pkl.load(f)\n f.close()\n print(len(pair))\n f = open(pathall_saveimg + \"augment_d_cls_AD_rnn.pkl\",\"rb\")\n dataset = pkl.load(f)\n f.close() \n f = open(pathall_saveimg + \"augment_label_cls_AD_rnn.pkl\",\"rb\")\n label = pkl.load(f)\n f.close() \n id_idx, cal_idx = ut.get_idx_label(label)\n pair_new, label_new = ut.get_pair_idx_label_new(id_idx,pair, cls_list)\n print(pair_new)\n print(label_new)\n print(len(pair_new))\n \nelif Type == 'Run_all_label_time_tri_new':\n ''' Extract data from pickle file'''\n\n ###################### store Normalized Dataset from dataset #####################\n f = open(pathall_saveimg + \"pair_all_clean.pkl\",\"rb\")\n pair = pkl.load(f)\n f.close() \n print(pair)\n\n f = open(pathall_saveimg + \"dataset_all_clean_before_D.pkl\",\"rb\")\n dataset_intmd = pkl.load(f)\n f.close()\n f = open(pathall_saveimg + \"Id_attr.pkl\",\"rb\")\n Id_attr = pkl.load(f)\n f.close()\n print(dataset_intmd.shape, dataset_intmd.dtype)\n\n new_d,new_l,new_pair = ut.augment_by_subject_rnn(dataset_intmd,pair,Id_attr,1200)\n\n \n new_d_AD, new_l_AD,new_pair_AD = ut.augment_by_subject_label_rnn(dataset_intmd,pair,Id_attr,1011)\n orig_d, orig_l,orig_pair = ut.augment_by_subject(dataset_intmd,pair,Id_attr,150)\n\n final_d = torch.cat([orig_d,new_d,new_d_AD])\n final_l = orig_l + new_l + new_l_AD\n final_pair = ut.append_pair(orig_pair,new_pair)\n final_pair = ut.append_pair(final_pair,new_pair_AD)\n print(final_pair)\n print(len(final_pair))\n print(len(final_l))\n\n f = open(pathall_saveimg + \"augment_pair_cls_AD_rnn.pkl\",\"wb\")\n pkl.dump(final_pair, f)\n f.close()\n f = open(pathall_saveimg + \"augment_d_cls_AD_rnn.pkl\",\"wb\")\n pkl.dump(final_d, f,protocol=4)\n f.close() \n f = open(pathall_saveimg + \"augment_label_cls_AD_rnn.pkl\",\"wb\")\n pkl.dump(final_l, f)\n f.close() \n sleep(10000) \n\n\nif args.Type == 'Run_cls_new':\n\n train_loader_list, train_label_loader_list, mask_loader_list = ut.split_dataset_folds_new_true_subject_rnn(dataset, label_new, pair_new,folds=5, BATCH_SIZE = args.BATCH_SIZE, shuffle=True,seed=2022)\n from codebase.models.nns.v13 import Classifier\n \n\n\nvae = VAE3d(z_dim=args.z, name=vae3d_model_name, device=device, nn='v13')\n\n\nrelu_loss = Distance_Relu_Loss(z_dim=args.z,name=relu_loss_model_name, device=device,requires_grad=True)\n\nif args.train == 14: \n writer = ut.prepare_writer(vae3d_model_name, overwrite_existing=True)\n ''' /scratch/users/zucks626/ADNI/ae_relu/checkpoints/'''\n ''' Load pre-trained vanilla VAE model'''\n ut.load_model_by_name_ae(vae, global_step=global_step, device=device)\n\n requires_grad = True\n LSTM = MultipleTimestepLSTM(fc_num_ch=16, lstm_num_ch=16, name= RNN_model_name,requires_grad=requires_grad,\n conv_act='relu', fc_act='relu', num_cls=2, num_timestep=6, skip_missing=True, init_lstm=True, rnn_type='GRU', fe_arch='Zucks', vae =vae).to(device)\n train3d_cls_rnn(model=LSTM, dataset = train_loader_list, label=train_label_loader_list, mask = mask_loader_list,\n device=device,\n tqdm=tqdm.tqdm,\n writer=writer,\n lr_decay_step=300, schedule=True,\n iter_max=args.iter_max,iter_restart=global_step,\n iter_save=args.iter_save,\n requires_grad=requires_grad,vae=None)\n\n","sub_path":"run_cls_ADNI_rnn.py","file_name":"run_cls_ADNI_rnn.py","file_ext":"py","file_size_in_byte":7223,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"6"} +{"seq_id":"433488835","text":"import fastText\nimport numpy\nimport json\nimport re\nfrom os import path\nimport sys\nfrom sys import stdin\nimport time\nfrom voiceassistant.model import BiLSTMCRF\nfrom voiceassistant.preprocessing import pad_nested_sequences\n\nintent_dir_path = path.dirname(path.dirname(path.realpath(__file__)))\n\ndef get_word_id(vocab, word):\n if word in vocab:\n return vocab[word]\n return vocab['']\n\ndef get_char_id(vocab, char):\n if char in vocab:\n return vocab[char]\n return vocab['']\n\nclass BaseIntent():\n def __init__(self):\n pass\n\n def parse(self, command):\n self.parse_command(command)\n\nclass NeuralIntent(BaseIntent):\n\n def __init__(self, name):\n # load labels\n label_path = path.join(intent_dir_path, \"config\", \"labels\", \"%s_labels.json\" % name)\n with open(label_path) as f:\n labels = json.load(f)\n \n # load words\n word_vocab_path = path.join(intent_dir_path, \"config\", \"vocab\", \"%s_word_vocab.json\" % name)\n with open(word_vocab_path) as f:\n word_vocab = json.load(f)\n n_words = len(word_vocab)\n self.vocab_map = word_vocab\n\n # load chars\n char_vocab_path = path.join(intent_dir_path, \"config\", \"vocab\", \"%s_char_vocab.json\" % name)\n with open(char_vocab_path) as f:\n char_vocab = json.load(f)\n n_chars = len(char_vocab)-2\n self.char_map = char_vocab\n\n # load variables\n variables_path = path.join(intent_dir_path, \"config\", \"schemas\", \"%s_schema.json\" % name)\n with open(variables_path) as f:\n self.variables = json.load(f)['variables']\n\n # load model\n weights_path = path.join(intent_dir_path, \"config\", \"weights\", \"%s.hdf5\" % name)\n self.model = BiLSTMCRF(labels, n_words, n_chars)\n self.model.build()\n self.model.load_weights(weights_path)\n self.idx2label = dict((number, label) for number, label in enumerate(labels))\n\n def parse(self, command):\n sentence = fastText.tokenize(command)\n\n words = [w.lower() for w in sentence]\n word_id_array = [[get_word_id(self.vocab_map, w) for w in sentence]]\n char_ids = [[[get_char_id(self.char_map, ch) for ch in w] for w in sentence]]\n char_ids = pad_nested_sequences(char_ids)\n\n p = self.model.predict([numpy.array(word_id_array), numpy.array(char_ids)])\n result = []\n for w, pred in zip(words, p[0]):\n print(\"{:15}: {}\".format(w, self.idx2label[pred]))\n result.append(self.idx2label[pred])\n\n features = {}\n\n for variable in self.variables:\n # count how many times it appears in command\n count = result.count('B-%s' % variable)\n\n features[variable] = []\n for idx, tag in enumerate(result):\n if tag == 'B-%s' % variable:\n feature = [words[idx]]\n word_idx = idx+1\n while word_idx < len(result) and result[word_idx] == 'I-%s' % variable:\n feature.append(words[word_idx])\n word_idx += 1\n\n feature = \" \".join(feature)\n features[variable].append(feature)\n\n return features","sub_path":"voiceassistant/intents/en/controllers/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":3268,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"6"} +{"seq_id":"96325933","text":"from subprocess import call\nimport os\nimport sys\nfrom os.path import join\nimport logging\n\nlogger = logging.getLogger('Clipper')\n\nclass Clipper():\n\tdef __init__(self):\n\t\tlogger.debug('initialized')\n\n\tdef clip_interactive(self, vids):\n\t\tc = 0\n\t\tfor vid in vids:\n\t\t\twhile True:\n\t\t\t\t# INTERACTIVELY GATHER START AND END TIMES AND GENERATE OUPUT PATH\n\t\t\t\tstarttime = input('enter start time e.g. 00:00:00: ') #'00:00:00'\n\t\t\t\tendtime = input('end time: ') #'00:01:00'\n\t\t\t\toutputpath = input('enter output path for clips: ')\n\t\t\t\toutput = join(outputpath, ('out_%d.mp4' % c))\n\t\t\t\tc+= 1\n\t\t\t\t# DON'T OVERWRITE EXISTING OUTPUT FILES\n\t\t\t\twhile os.path.isfile(output):\n\t\t\t\t\tc+= 1\n\t\t\t\t\toutput = join(outputpath, ('out_%d.mp4' % c))\n\n\t\t\t\tlogger.info('vid: %s' % vid)\n\t\t\t\tlogger.info('out: %s' % output)\n\t\t\t\tlogger.info('working....' )\n\t\t\t\tcall(['ffmpeg', '-i', vid,'-vcodec', 'copy', '-acodec', 'copy', '-copyinkf', '-ss', starttime, '-to', endtime, output], shell=True)\n\t\t\t\tlogger.info('\\nClipper: output clip %s\\n' % output)\n\t\t\t\tinp = input('continue clipping from this video? (y/n): ')\n\t\t\t\tif inp == 'n':\n\t\t\t\t\tbreak\n\t\tlogger.info('\\n\\nFinished Clipping!\\n\\n')\n\n\tdef clip(self, vids, timings, ouputpath):\n\t\tc = 0\n\t\ti=0\n\t\tfor vid in vids:\n\t\t\twhile True:\n\t\t\t\t# GET TIMINGS AND GENERATE OUPUT PATH\n\t\t\t\tstarttime = timings[i]\n\t\t\t\tendtime = timings[i]\n\t\t\t\toutput = join(outputpath, ('out_%d.mp4' % c))\n\t\t\t\tc+= 1\n\t\t\t\ti+= 1\n\t\t\t\t# DON'T OVERWRITE EXISTING OUTPUT FILES\n\t\t\t\twhile os.path.isfile(output):\n\t\t\t\t\tc+= 1\n\t\t\t\t\toutput = 'out_%d.mp4' % c\n\n\t\t\t\tlogger.info('vid: %s' % vid)\n\t\t\t\tcall(['ffmpeg', '-i', vid,'-vcodec', 'copy', '-acodec', 'copy', '-copyinkf', '-ss', starttime, '-to', endtime, output], shell=True)\n\t\t\t\tlogger.info('\\nClipper: output clip %s\\n' % output)\n\t\tlogger.info('\\n\\nFinished Clipping!\\n\\n')\n","sub_path":"pcs/clipper.py","file_name":"clipper.py","file_ext":"py","file_size_in_byte":1796,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"6"} +{"seq_id":"90002815","text":"def retrieval_precision(gold, predicted):\n \"\"\"\n Compute retrieval precision on the given gold set and predicted set.\n Note that it doesn't take into account the order or repeating elements.\n\n :param gold: the set of gold retrieved elements\n :param predicted: the set of predicted elements\n :return: precision value\n >>> retrieval_precision({1,2,3},{2})\n 1.0\n >>> retrieval_precision({2}, {1,2,3})\n 0.3333333333333333\n >>> retrieval_precision({2,3,4,8}, {1,2,3})\n 0.3333333333333333\n \"\"\"\n gold = set(gold)\n predicted = set(predicted)\n tp = len(gold & predicted)\n fp_tp = len(predicted)\n return tp/fp_tp\n\n\ndef retrieval_tp_with_altlabels(gold, predicted_sets):\n \"\"\"\n Compute rtrue positives on the given gold set and predicted set.\n Note that it doesn't take into account the order or repeating elements.\n\n :param gold: the set of gold retrieved elements\n :param predicted_sets: the set of predicted elements\n :return: number of true positives\n >>> retrieval_tp_with_altlabels({1,2,3},[[2,8,4], [1], [6,7], [12, 45]])\n 2\n >>> retrieval_tp_with_altlabels({1,2,3},[[2,3,4], [8]])\n 1\n \"\"\"\n return sum(any(l in gold for l in label_set) for label_set in predicted_sets)\n\n\ndef retrieval_prec_rec_f1(gold, predicted):\n \"\"\"\n Compute retrieval precision, recall and f-score. Note that it doesn't take into account the order\n and repeating elements.\n\n :param gold: the set of gold retrieved elements.\n :param predicted: the set of predicted elements.\n :return: a triple of precision, recall and f-score\n >>> retrieval_prec_rec_f1(['Star Wars', 'Black Swan', 'Thor', 'Leon'], ['Thor', 'Avengers', 'Iron Man'])\n (0.3333333333333333, 0.25, 0.28571428571428575)\n >>> retrieval_prec_rec_f1(['Star Wars', 'Black Swan', 'Thor', 'Leon'], [])\n (0.0, 0.0, 0.0)\n >>> retrieval_prec_rec_f1([1,2], [1,2,3])\n (0.6666666666666666, 1.0, 0.8)\n >>> retrieval_prec_rec_f1([1,2], [1])\n (1.0, 0.5, 0.6666666666666666)\n \"\"\"\n prec = retrieval_precision(gold, predicted) if len(predicted) > 0 else 0.0\n rec = retrieval_precision(predicted, gold) if len(gold) > 0 else 0.0\n f1 = 0.0\n if (rec+prec) > 0:\n f1 = 2.0 * prec * rec / (prec + rec)\n\n return prec, rec, f1\n\n\ndef retrieval_prec_rec_f1_with_altlabels(gold, predicted_sets):\n \"\"\"\n Compute retrieval precision, recall and f-score for the case when each predicted entity has alternative labels.\n Note that it doesn't take into account the order\n and repeating elements.\n\n :param gold: the set of gold retrieved elements.\n :param predicted_sets: the set of predicted elements.\n :return: a triple of precision, recall and f-score\n >>> retrieval_prec_rec_f1_with_altlabels(['Star Wars', 'Black Swan', 'Thor', 'Leon'], [['thor','Thor','God of thunder'], ['Avengers', 'Defenders'], ['Iron Man']])\n (0.3333333333333333, 0.25, 0.28571428571428575)\n >>> retrieval_prec_rec_f1_with_altlabels(['Star Wars', 'Black Swan', 'Thor', 'Leon'], [])\n (0.0, 0.0, 0.0)\n >>> retrieval_prec_rec_f1_with_altlabels(['Star Wars', 'Black Swan', 'Thor', 'Leon'], [[],[]])\n (0.0, 0.0, 0.0)\n >>> retrieval_prec_rec_f1_with_altlabels(['Leon'], [['Black Swan'],['Leon']])\n (0.5, 1.0, 0.6666666666666666)\n \"\"\"\n tp = retrieval_tp_with_altlabels(gold, predicted_sets)\n prec = tp / len(predicted_sets) if len(predicted_sets) > 0 else 0.0\n rec = tp / len(gold) if len(gold) > 0 else 0.0\n f1 = 0.0\n if (rec+prec) > 0:\n f1 = 2.0 * prec * rec / (prec + rec)\n\n return prec, rec, f1\n\n\nif __name__ == \"__main__\":\n import doctest\n print(doctest.testmod())\n\n","sub_path":"questionanswering/datasets/evaluation.py","file_name":"evaluation.py","file_ext":"py","file_size_in_byte":3666,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"6"} +{"seq_id":"175452838","text":"import heterocl as hcl\nhcl.init()\nfinal_extent_0 = 64\nfinal_extent_1 = 64\nfinal_extent_2 = 32\nfinal_extent_3 = 4\nfinal_min_0 = 0\nfinal_min_1 = 0\nfinal_min_2 = 0\nfinal_min_3 = 0\ndef top(input, filter, bias, ):\n f_conv = hcl.compute((final_extent_0, final_extent_1, final_extent_2, final_extent_3), lambda x, y, z, w: 0, name = \"f_conv\", dtype = hcl.Float(bits = 32))\n with hcl.Stage(\"f_conv\"):\n with hcl.for_(final_min_3, final_extent_3, name = \"f_conv_s0_n\") as f_conv_s0_n:\n with hcl.for_(final_min_2, final_extent_2, name = \"f_conv_s0_z\") as f_conv_s0_z:\n with hcl.for_(final_min_1, final_extent_1, name = \"f_conv_s0_y\") as f_conv_s0_y:\n with hcl.for_(final_min_0, final_extent_0, name = \"f_conv_s0_x\") as f_conv_s0_x:\n f_conv[f_conv_s0_x, f_conv_s0_y, f_conv_s0_z, f_conv_s0_n] = bias[f_conv_s0_z]\n with hcl.for_(final_min_3, final_extent_3, name = \"f_conv_s1_n\") as f_conv_s1_n:\n with hcl.for_(final_min_2, final_extent_2, name = \"f_conv_s1_z\") as f_conv_s1_z:\n with hcl.for_(final_min_1, final_extent_1, name = \"f_conv_s1_y\") as f_conv_s1_y:\n with hcl.for_(final_min_0, final_extent_0, name = \"f_conv_s1_x\") as f_conv_s1_x:\n with hcl.for_(0, 32, name = \"f_conv_s1_r__z\") as f_conv_s1_r__z:\n with hcl.for_(0, 3, name = \"f_conv_s1_r__y\") as f_conv_s1_r__y:\n with hcl.for_(0, 3, name = \"f_conv_s1_r__x\") as f_conv_s1_r__x:\n f_conv[f_conv_s1_x, f_conv_s1_y, f_conv_s1_z, f_conv_s1_n] = (f_conv[f_conv_s1_x, f_conv_s1_y, f_conv_s1_z, f_conv_s1_n] + (filter[f_conv_s1_r__x, f_conv_s1_r__y, f_conv_s1_r__z, f_conv_s1_z] * input[(f_conv_s1_r__x + f_conv_s1_x), (f_conv_s1_r__y + f_conv_s1_y), f_conv_s1_r__z, f_conv_s1_n]))\n f_relu = hcl.compute((final_extent_0, final_extent_1, final_extent_2, final_extent_3), lambda x, y, z, w: 0, name = \"f_relu\", dtype = hcl.Float(bits = 32))\n with hcl.Stage(\"f_relu\"):\n with hcl.for_(final_min_3, final_extent_3, name = \"f_relu_s0_n\") as f_relu_s0_n:\n with hcl.for_(final_min_2, final_extent_2, name = \"f_relu_s0_z\") as f_relu_s0_z:\n with hcl.for_(final_min_1, final_extent_1, name = \"f_relu_s0_y\") as f_relu_s0_y:\n with hcl.for_(final_min_0, final_extent_0, name = \"f_relu_s0_x\") as f_relu_s0_x:\n f_relu[f_relu_s0_x, f_relu_s0_y, f_relu_s0_z, f_relu_s0_n] = hcl.select(f_conv[f_relu_s0_x, f_relu_s0_y, f_relu_s0_z, f_relu_s0_n] > hcl.cast(dtype = hcl.Float(bits = 32), expr = 0.000000), f_conv[f_relu_s0_x, f_relu_s0_y, f_relu_s0_z, f_relu_s0_n], hcl.cast(dtype = hcl.Float(bits = 32), expr = 0.000000))\n final = hcl.compute((64, 64, 32, 4), lambda x, y, z, w: 0, name = \"final\", dtype = hcl.Float(bits = 32))\n with hcl.Stage(\"final\"):\n with hcl.for_(final_min_3, final_extent_3, name = \"final_s0_n\") as final_s0_n:\n with hcl.for_(final_min_2, final_extent_2, name = \"final_s0_z\") as final_s0_z:\n with hcl.for_(final_min_1, final_extent_1, name = \"final_s0_y\") as final_s0_y:\n with hcl.for_(final_min_0, final_extent_0, name = \"final_s0_x\") as final_s0_x:\n final[final_s0_x, final_s0_y, final_s0_z, final_s0_n] = f_relu[final_s0_x, final_s0_y, final_s0_z, final_s0_n]\n return final\ninput = hcl.placeholder((67, 67, 32, 4, ), name = \"input\", dtype = hcl.Float(bits = 32))\nfilter = hcl.placeholder((3, 3, 32, 32, ), name = \"filter\", dtype = hcl.Float(bits = 32))\nbias = hcl.placeholder((32, ), name = \"bias\", dtype = hcl.Float(bits = 32))\ns = hcl.create_schedule([input, filter, bias, ], top)\nf = hcl.build(s)\nprint(hcl.lower(s))\nimport numpy as np\nnp_input = np.load(\"input.npy\")\nhcl_input = hcl.asarray(np_input, dtype = hcl.Float(bits = 32))\nnp_filter = np.load(\"filter.npy\")\nhcl_filter = hcl.asarray(np_filter, dtype = hcl.Float(bits = 32))\nnp_bias = np.load(\"bias.npy\")\nhcl_bias = hcl.asarray(np_bias, dtype = hcl.Float(bits = 32))\noutput_shape = (64, 64, 32, 4, )\nhcl_out = hcl.asarray(np.zeros(output_shape), dtype = hcl.Float(bits = 32))\nf(hcl_input, hcl_filter, hcl_bias, hcl_out)\nnp_out = hcl_out.asnumpy()\nnp.save(\"output_heterocl.npy\", np_out)\n# print(hcl.build(s, target = \"soda\"))\nprint(hcl.build(s, target = \"merlinc\"))\n","sub_path":"new/conv/conv_gen.py","file_name":"conv_gen.py","file_ext":"py","file_size_in_byte":4384,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"6"} +{"seq_id":"6107515","text":"from functools import partial\n\nfrom .core import Pre, Post, Invariant, Raises, Offline, Silent, Ensure\n\n\n__all__ = [\n 'require', 'pre',\n 'ensure', 'post',\n 'inv', 'invariant',\n 'raises', 'safe',\n 'offline', 'silent',\n 'chain', 'pure',\n]\n\n\nrequire = pre = Pre\npost = Post\nensure = Ensure\ninv = invariant = Invariant\nraises = Raises\n\n\n# makes braces for decorator are optional\ndef _optional(_contract, _func=None, *, message=None, exception=None, debug=False):\n if _func is not None:\n return _contract()(_func)\n return _contract(message=message, exception=exception, debug=debug)\n\n\noffline = partial(_optional, Offline)\nsafe = partial(_optional, Raises)\nsilent = partial(_optional, Silent)\n\n\ndef chain(*contracts):\n def wrapped(func):\n for contract in contracts:\n func = contract(func)\n return func\n return wrapped\n\n\npure = chain(offline, safe, silent)\n","sub_path":"deal/aliases.py","file_name":"aliases.py","file_ext":"py","file_size_in_byte":913,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"6"} +{"seq_id":"249848050","text":"\"\"\"\nEASY - Rating\nUTF-8 is a character encoding that maps each symbol to one, two, three, or four bytes.\n\nFor example, the Euro sign, €, corresponds to the three bytes 11100010 10000010 10101100. The rules for mapping characters are as follows:\n\nFor a single-byte character, the first bit must be zero.\nFor an n-byte character, the first byte starts with n ones and a zero.\nThe other n - 1 bytes all start with 10.\nVisually, this can be represented as follows.\n\n Bytes | Byte format\n-----------------------------------------------\n 1 | 0xxxxxxx\n 2 | 110xxxxx 10xxxxxx\n 3 | 1110xxxx 10xxxxxx 10xxxxxx\n 4 | 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx\nWrite a program that takes in an array of integers representing byte values,\nand returns whether it is a valid UTF-8 encoding.\n\nAssumptions: Array given in one big contigous array\n\"\"\"\nimport math\n\n# current Solution gives us a O(n)\ndef UTF8EncodingCheck(arrOfBytes):\n bytelength = 8\n numBytes = math.floor(len(arrOfBytes) / bytelength)\n\n if numBytes == 0 and arrOfBytes[0] == 0:\n return True\n numberOfOnes = 0\n for x in range(numBytes+1):\n if arrOfBytes[x] == 1:\n numberOfOnes += 1\n\n if numBytes == numberOfOnes:\n p1 = 8\n p2 = 17\n while p2 <= len(arrOfBytes):\n if arrOfBytes[p1:p2][0] != 1 and arrOfBytes[p1:p2][1] != 0:\n return False\n else:\n p1 = p2 -1\n p2 += 8\n\n else:\n return False\n\n return True\n\n\"\"\"\nSolution of this in the answer uses bit shifting, and assumes that the\ninput comes in the form of arrays of arrays. Rather then one massive\narray of bit.\n\nNote: Learn Bit shifting in Python\n\nStill has the same complexity as your solution. However I think the interviewer\nwould want to see if you can actually do bit shifting\n\"\"\"\n\ndef valid(data):\n # follows almost the same thing you did expect it checks the first\n # chunck using Bit shifting\n first = data[0]\n\n if first >> 7 == 0:\n count = 0\n elif first >> 5 == 0b110:\n count = 1\n elif first >> 4 == 0b1110:\n count = 2\n elif first >> 3 == 0b11110:\n count = 3\n else:\n return False\n\n # then it goes through the rest just like your alog and\n # checks that the first two eles are 10 for the rest of\n # of the chuncks. Aagin using bit shifting\n for byte in data[1:]:\n if byte >> 6 == 0b10:\n count -= 1\n else:\n return False\n\n return count == 0\n\nif __name__ == \"__main__\":\n print(UTF8EncodingCheck([1,1,1,1,0,1,1,1,1,0,1,1,1,1,1,1,1,0,1,1,1,1,1,1,1,0,1,1,1,1,1,1]))\n","sub_path":"Old/Anything/UTF8EncodingCheck.py","file_name":"UTF8EncodingCheck.py","file_ext":"py","file_size_in_byte":2651,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"356603034","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Apr 30 16:48:18 2020\n\n@author: destash\n\"\"\"\n\nfrom lloyd import lloyd\nimport pandas as pd\nfrom others import DataFrameImputer, random_kmean_sklearn\nfrom time import time\n\n\n# =============================================================================\n# Initialisation des centres pour les kmeans : tirage uniforme de k centres\n# =============================================================================\n\ndef init_kmeans(X,k) :\n \n \"\"\"\n X : dataset\n k : number of centers\n \"\"\"\n \n centers=X.sample(n=k,replace=False).to_numpy()\n \n return centers\n\n\n# ================================================================================\n# Algorithme des kmeans++ semi supervisés faisant appel à l'algorithme de Lloyd\n# =================================================================================\n\ndef kmeans(X,k,e=10**-10) :\n \n \"\"\"\n X : dataset avec une partie des données déjà labelisées dans une colonne nommée clusters\n k : nombre de clusters\n e : seuil de tolérance\n \"\"\"\n \n centers = init_kmeans(X,k)\n centers,clusters = lloyd(k,X,centers,e)\n return centers,clusters\n\n\n# =============================================================================\n# Main\n# =============================================================================\n\nif __name__==\"__main__\":\n # Uploading ML dataset\n base=pd.read_csv('BigML_Dataset.csv',sep=',')\n \n X=base.iloc[:,1:]\n \n # Imputing based on mean for numeric, and most frequent for strings\n X = DataFrameImputer().fit_transform(X)\n X.fillna(X.mean())\n \n k,e=5,10**(-10)\n \n \n #kmeans\n t0=time()\n centers,clusters = kmeans(X,k,e)\n t1=time()\n print('En utilisant kmeans : %f' %(t1-t0))\n \n #comparaison avec kmeans de sklearn\n t2=time()\n resultat = random_kmean_sklearn(k,X)\n t3=time()\n print('En utilisant kmeans de sklearn : %f' %(t3-t2))","sub_path":"k_means.py","file_name":"k_means.py","file_ext":"py","file_size_in_byte":1979,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"437189182","text":"from flask_restful import Resource, Api\nfrom flask_restful import reqparse\nfrom flask import Blueprint, abort\nfrom sqlalchemy.sql.expression import func\nfrom marshmallow import ValidationError\nfrom .models import db, Talk\nfrom .serializers import VoteSchema, TalkSchema\nfrom .constants import VoteValue\n\n\napi_bp = Blueprint('api_v1', __name__)\napi = Api(api_bp)\n\n\ndef get_talk_or_abort(id):\n talk_obj = db.session.query(Talk).filter(Talk.id == id).first()\n if not talk_obj:\n abort(404, '`talk_id` is not in database')\n return talk_obj\n\n\nclass TalksListResource(Resource):\n\n def get(self):\n schema = TalkSchema()\n talk_objs = db.session.query(Talk)\n data = schema.dump(talk_objs, many=True).data\n return data, 200\n\n\napi.add_resource(TalksListResource, '/talks/', endpoint=\"api.talks\")\n\n\nclass TalkDetailResource(Resource):\n\n def get(self, id):\n schema = TalkSchema()\n talk_obj = get_talk_or_abort(id)\n data = schema.dump(talk_obj).data\n return data, 200\n\n\napi.add_resource(TalkDetailResource, '/talks//', endpoint=\"api.talk\")\n\n\nclass TalkRandResource(Resource):\n\n def get(self):\n schema = TalkSchema()\n talk_obj = db.session.query(Talk).order_by(func.random()).first()\n if not talk_obj:\n abort(404, '`talk_id` is not in database')\n data = schema.dump(talk_obj).data\n return data, 200\n\n\napi.add_resource(TalkRandResource, '/talks/random/', endpoint=\"api.talkrand\")\n\n\ndef validate_vote_type(value):\n if value not in [VoteValue.in_person.value, VoteValue.watch_later.value]:\n raise ValueError(\"Invalid object: must be watch_later or in_person\")\n return value\n\n\nclass VoteResource(Resource):\n\n parser = reqparse.RequestParser()\n parser.add_argument(\n 'vote', type=validate_vote_type,\n required=True, help='Must be in_person | watch_later')\n\n def post(self, id):\n return self.get()\n\n def get(self, id):\n talk_obj = get_talk_or_abort(id)\n args = self.parser.parse_args()\n vote = args['vote']\n\n vote_mapping = {\n VoteValue.in_person.value: 1,\n VoteValue.watch_later.value: 0, }\n\n schema = VoteSchema()\n msg = \"\"\n try:\n serial_obj = schema.load(\n {'value': vote_mapping[vote]},\n session=db.session)\n except ValidationError as err:\n err.messages\n valid_data = err.valid_data\n data = str(err)\n print(data, valid_data)\n ret_code = 400\n msg = \"Fail\"\n else:\n obj = serial_obj.data\n obj.talk = talk_obj\n db.session.add(obj)\n db.session.commit()\n msg = \"Success\"\n ret_code = 200\n return {\"message\": msg}, ret_code\n\n\napi.add_resource(VoteResource, '/talks//vote/', endpoint=\"api.vote\")\n","sub_path":"talkvoter/v1_resources.py","file_name":"v1_resources.py","file_ext":"py","file_size_in_byte":2923,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"570887032","text":"from tkinter import *\r\nfrom tkinter import ttk, messagebox\r\nimport os\r\n\r\nclass App(Frame):\r\n\r\n\tdef __init__(self,master=None):\r\n\t\tFrame.__init__(self,master)\r\n\t\tself.master = master\r\n\t\tself.master.title('FileFinder V1.0')\r\n\t\tself.master.minsize(250,400)\r\n\t\tself.master.maxsize(250,400)\r\n\t\tself.var = StringVar()\r\n\t\tself.radio_var = StringVar()\r\n\t\tself.pack()\r\n\r\n\tdef find(self):\r\n\t\ttry:\r\n\t\t\tpath = self.var.get()\r\n\t\t\ttype_search = '.'+ self.radio_var.get()\r\n\t\t\tos.chdir(path)\r\n\t\t\tcount = 1\r\n\t\t\tfor root,dirs,files in os.walk('.'):\r\n\t\t\t\tfor file in files :\r\n\t\t\t\t\tif file.endswith(type_search):\r\n\t\t\t\t\t\tself.listbox.insert(0,str(count)+'- '+file)\r\n\t\t\t\t\t\tcount += 1\r\n\t\t\tself.label.config(text= str(count)+'files')\r\n\t\texcept Exception as e:\r\n\t\t\tmessagebox.showerror('Eroor','something goes wrong please try again.')\r\n\t\t\tos._exit(0)\r\n\r\n\t\tfinally:\r\n\t\t\tself.entry.delete(0,END)\r\n\r\n\tdef clear(self):\r\n\t\tself.listbox.delete(0,END)\r\n\t\tself.label.config(text='fileFinder')\r\n\r\n\tdef widgets(self):\r\n\t\tself.label = Label(self,text='fileFinder')\r\n\t\tself.label.pack(expand = YES,fill=BOTH,pady=5)\r\n\t\tself.entry = ttk.Entry(self,width=44,textvariable=self.var)\r\n\t\tself.entry.pack(expand = YES,fill=BOTH,ipady=5,pady=5)\r\n\t\tself.entry.focus()\r\n\t\tframe_button = Frame(self).pack(expand=YES,fill=BOTH)\r\n\t\tself.radio_butt1 = Radiobutton(frame_button,text='video',variable= self.radio_var,value=\"mp4\").pack()\r\n\t\tself.radio_butt2 = Radiobutton(frame_button,text='document',variable= self.radio_var,value=\"pdf\").pack()\r\n\t\tself.radio_butt3 = Radiobutton(frame_button,text='song',variable= self.radio_var,value=\"mp3\").pack()\r\n\t\tself.listbox =Listbox(frame_button)\r\n\t\tself.listbox.pack(expand = YES,fill=BOTH)\r\n\t\tself.button_find =ttk.Button(frame_button,text='Find',command=self.find)\r\n\t\tself.button_find.pack(expand = YES,fill=BOTH)\r\n\t\tself.button_clear = ttk.Button(frame_button,text= 'Clear',command=self.clear)\r\n\t\tself.button_clear.pack(expand = YES,fill=BOTH)\r\n\r\n\r\n\t\r\n\r\n\r\nif __name__ == '__main__':\r\n\troot = Tk()\r\n\tapp = App(root)\r\n\tapp.widgets()\r\n\troot.mainloop()","sub_path":"File Fider V1.0.py","file_name":"File Fider V1.0.py","file_ext":"py","file_size_in_byte":2041,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"425567433","text":"\"\"\"\nKata description:\n\nBackground\nMoving average of a set of values and a window size is a series of local averages.\n\nExample:\n\nValues: [1, 2, 3, 4, 5]\nWindow size: 3\n\nMoving average is calculated as:\n\n\n 1, 2, 3, 4, 5\n | |\n ^^^^^^^\n (1+2+3)/3 = 2\n\n\n 1, 2, 3, 4, 5\n | |\n ^^^^^^^\n (2+3+4)/3 = 3\n\n\n 1, 2, 3, 4, 5\n | |\n ^^^^^^^\n (3+4+5)/3 = 4\n\nHere, the moving average would be [2, 3, 4]\nTask\nGiven a list values of integers and an integer n representing size of the window, calculate and return the moving\naverage.\n\nWhen integer n is equal to zero or the size of values list is less than window's size, return None\n\"\"\"\n\n\ndef moving_average(values, n):\n if n == 0:\n return None\n\n averages = []\n\n for i in range(len(values)):\n if i + n > len(values):\n break\n averages.append(sum(values[i:i + n]) // n)\n\n return averages if averages else None\n\n\nprint(moving_average([1, 2, 3, 4, 5], 3))\n","sub_path":"7_kyu_katas/moving_average.py","file_name":"moving_average.py","file_ext":"py","file_size_in_byte":972,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"622417224","text":"#http://svn.python.org/projects/sandbox/trunk/ttk-gsoc/samples/ttkcalendar.py\n#https://www.youtube.com/watch?v=FrS1lLb4HgA\nimport sys\nfrom cal import *\nfrom Tkinter import *\nimport time\n\n#Function for the clock in the main page.\ndef tick():\n global time1\n # get the current local time from the PC\n time2 = time.strftime('%H:%M:%S')\n # if time string has changed, update it\n if time2 != time1:\n time1 = time2\n clock.config(text=time2)\n clock.after(200, tick)\n\ndef days():\n\tdays = Tkinter.Toplevel(root)\n\troot.iconify()\n\tDAYS = [\n \t\t\"Lunes\",\n \t\t\"Martes\",\n \t\t\"Miercoles\", \n\t\t\"Jueves\",\n\t\t\"Viernes\",\n\t\t\"Sabado\",\n\t\t\"Domingo\"\n\t]\n\tHOURS = [\n\t\t\"5:00\",\n\t\t\"6:00\",\n\t\t\"7:00\",\n\t\t\"8:00\",\n\t\t\"9:00\",\n\t\t\"10:00\",\n\t\t\"11:00\"\n\t]\n\tvariable = StringVar(root)\n\tvariable2 = StringVar(root)\n\tvariable.set(DAYS[0])\n\tvariable2.set(HOURS[0])\n\tw = apply(OptionMenu, (days, variable) + tuple(DAYS))\n\tw2 = apply(OptionMenu, (days, variable2) + tuple(HOURS))\n\tw.pack()\n\tw2.pack()\n#\tdays.parent=days\n#\tdays.parent.protocol(\"WM_DELETE_WINDOW\", upRoot)\n\ndef upRoot():\n\troot.deiconify()\n\n#Main\nroot=Tk()\nroot.title('Timencan')\nbtn1 = Button(root, text=\"Agregar horario\", command = days)\n\ntime1 = ''\nclock = Label(root, font=('times', 35, 'bold'), bg='white')\nclock.pack()\n\n#Call the clock\ntick()\n\n#Call calendar widget in cal.py\ntest()\n\nbtn1.pack()\nmainloop()\n","sub_path":"calendar/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1363,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"643960405","text":"import numpy as np\r\nimport qutip as qt\r\nimport scipy\r\nimport matplotlib.pyplot as plt\r\nfrom scipy import constants\r\n\r\npi = np.pi\r\ne = constants.e # [C]\r\nh = constants.h # [m^2 kg/s]\r\nhbar = constants.hbar\r\n\r\ndef EC_to_C(EC):\r\n return ((e**2)/(2*h*EC*10**9))/(10**(-15))\r\n\r\ndef ket(Nq, i):\r\n return qt.basis(Nq, i)\r\n\r\ndef c(Nq):\r\n cc = 0\r\n for i in range(Nq-1):\r\n cc = cc + np.sqrt(i+1) * ( ket(Nq, i) * ket(Nq, i+1).dag() )\r\n return cc\r\n\r\nc1=c(3)\r\nc2=c(3)\r\nintterm=(qt.tensor(c1, c2.dag()) + qt.tensor(c1.dag(), c2))\r\n\r\ndef hamiltonian(Ec, Ej, N, ng):\r\n \r\n m = np.diag(4 * Ec * (np.arange(-N,N+1)-ng)**2) + 0.5 * Ej * (np.diag(-np.ones(2*N), 1) + np.diag(-np.ones(2*N), -1))\r\n return qt.Qobj(m)\r\n\r\ndef Energy_diagram(Ec,Ej,N,steps,lev): #第lev準位までみる lev\r\n pop10 = [0] * len(state_list) # population of the state |10>\r\n pop11 = [0] * len(state_list)# population of the state |11>\r\n pop02 = [0] * len(state_list)# population of the state |02>\r\n\r\n phase00 = [0] * len(state_list)\r\n phase10 = [0] * len(state_list)\r\n phase01 = [0] * len(state_list)\r\n phase11 = [0] * len(state_list)\r\n #phaseAdia = [0] * len(state_list)\r\n phaseDiff = [0] * len(state_list)\r\n \r\n for i in range(len(state_list)):\r\n \r\n final00[i] = state_list[i][:][0]\r\n final01[i] = state_list[i][:][1]\r\n final02[i] = state_list[i][:][2]\r\n final10[i] = state_list[i][:][3]\r\n final11[i] = state_list[i][:][4]\r\n final12[i] = state_list[i][:][5]\r\n final20[i] = state_list[i][:][6]\r\n final21[i] = state_list[i][:][7]\r\n final22[i] = state_list[i][:][8]\r\n #finalAdia[i] = state_list[i][:][2] + state_list[i][:][4] # eigenstate along the adiabatic line\r\n \r\n pop01[i] = norm * np.absolute(final01[i])**2 # the population is square of the magnitude.\r\n pop10[i] = norm * np.absolute(final10[i])**2\r\n pop11[i] = norm * np.absolute(final11[i])**2\r\n pop02[i] = norm * np.absolute(final02[i])**2\r\n \r\n phase00[i] = np.angle(final00[i]) / pi\r\n phase01[i] = np.angle(final01[i]) / pi\r\n phase10[i] = np.angle(final10[i]) / pi\r\n phase11[i] = np.angle(final11[i]) / pi\r\n #phaseAdia[i] = np.angle(finalAdia[i]) / pi\r\n #phaseDiff[i] = phaseAdia[i] - phase10[i] - phase01[i]\r\n \r\n phaseDiff[i] = phase11[i] - phase10[i] - phase01[i]\r\n \r\n # phase ordering\r\n if i > 0 and phase10[i] - phase10[i-1] < -1:\r\n phase10[i] = phase10[i] + 2\r\n if i > 0 and phase10[i] - phase10[i-1] > 1:\r\n phase10[i] = phase10[i] - 2\r\n \r\n if i > 0 and phaseDiff[i] - phaseDiff[i-2] < -1:\r\n phaseDiff[i] = phaseDiff[i] + 2\r\n if i > 0 and phaseDiff[i] - phaseDiff[i-2] > 1:\r\n phaseDiff[i] = phaseDiff[i] - 2\r\n \r\n return phaseDiff\r\n #return(phaseDiff,pop11,pop02)\r\n\r\n\"\"\"\r\ndef PhaseChange(state_list):\r\n \r\n final01 = [0] * len(state_list)\r\n final10 = [0] * len(state_list)\r\n final11 = [0] * len(state_list)\r\n\r\n phase10 = [0] * len(state_list)\r\n phase01 = [0] * len(state_list)\r\n phase11 = [0] * len(state_list)\r\n\r\n phaseDiff = [0] * len(state_list)\r\n \r\n for i in range(len(state_list)):\r\n \r\n final01[i] = state_list[i][:][1]\r\n final10[i] = state_list[i][:][3]\r\n final11[i] = state_list[i][:][4]\r\n \r\n phase01[i] = np.angle(final01[i]) / pi\r\n phase10[i] = np.angle(final10[i]) / pi\r\n phase11[i] = np.angle(final11[i]) / pi\r\n \r\n phaseDiff[i] = phase11[i] - phase10[i] - phase01[i]\r\n # phase ordering\r\n if i > 0 and phase10[i] - phase10[i-1] < -1:\r\n phase10[i] = phase10[i] + 2\r\n if i > 0 and phase10[i] - phase10[i-1] > 1:\r\n phase10[i] = phase10[i] - 2\r\n \r\n if i > 0 and phaseDiff[i] - phaseDiff[i-2] < -1:\r\n phaseDiff[i] = phaseDiff[i] + 2\r\n if i > 0 and phaseDiff[i] - phaseDiff[i-2] > 1:\r\n phaseDiff[i] = phaseDiff[i] - 2\r\n \r\n return(phaseDiff) \r\n\"\"\"\r\n\r\n#ketベクトル転写用\r\ndef tensor_to_flat(tensorproduct):\r\n \r\n d=tensorproduct.shape[0]\r\n onedvector=0\r\n for i in range(d):\r\n onedvector=onedvector+tensorproduct[i][0][0]*ket(d,i)\r\n \r\n return onedvector","sub_path":"quantum_okiba.py","file_name":"quantum_okiba.py","file_ext":"py","file_size_in_byte":7241,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"396284564","text":"import os, os.path\nimport re\n\nimport numpy as np\n\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn.feature_extraction.text import TfidfTransformer, TfidfVectorizer\n\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.model_selection import GridSearchCV\n\n\nfrom nltk.stem.porter import PorterStemmer\nfrom nltk.corpus import brown\nfrom nltk.corpus import stopwords\n\n\nX = np.array([], dtype=object)\ny = np.array([], dtype=object)\n\nbrown_categories = ['hobbies', 'news', 'government', 'reviews']\n\nfor brown_category in brown_categories:\n for fileid in brown.fileids(brown_category):\n doc = ''\n for w in brown.words(fileid):\n doc += '%s ' % w\n X = np.append(X, doc)\n y = np.append(y, brown_category)\n\n files_n = len([name for name in os.listdir('../%s' % brown_category)])\n for i in range(1, files_n + 1):\n file = open('../{}/{}_0{}.txt'.format(brown_category, brown_category, i))\n doc = file.read()\n X = np.append(X, doc)\n y = np.append(y, '%s' % brown_category)\n\n\n# Cleaning text data\nfor i in range(len(X)):\n string = X[i]\n string = re.sub(r\"[^A-Za-z0-9(),!?\\'\\`]\", \" \", string)\n string = re.sub(r\"\\'s\", \" \\'s\", string)\n string = re.sub(r\"\\'ve\", \" \\'ve\", string)\n string = re.sub(r\"n\\'t\", \" n\\'t\", string)\n string = re.sub(r\"\\'re\", \" \\'re\", string)\n string = re.sub(r\"\\'d\", \" \\'d\", string)\n string = re.sub(r\"\\'ll\", \" \\'ll\", string)\n string = re.sub(r\",\", \" , \", string)\n string = re.sub(r\"!\", \" ! \", string)\n string = re.sub(r\"\\(\", \" \\( \", string)\n string = re.sub(r\"\\)\", \" \\) \", string)\n string = re.sub(r\"\\?\", \" \\? \", string)\n string = re.sub(r\"\\s{2,}\", \" \", string)\n X[i] = string\n\n\nstop = stopwords.words('english')\nfor i in range(len(X)):\n text = X[i]\n clean_text = ''\n for w in text.split():\n if w not in stop:\n clean_text += \"%s \" % w\n X[i] = clean_text\n\n\ncount_vec = CountVectorizer()\n\ntfidf = TfidfTransformer()\nnp.set_printoptions(precision=3)\nX_tfidf = tfidf.fit_transform(count_vec.fit_transform(X)).toarray()\n\n\nX_train, X_test = X_tfidf[:140], X_tfidf[140:]\ny_train, y_test = y[:140], y[140:]\n\nclassifier = LogisticRegression(penalty='l1', C=15.0, random_state=0)\nclassifier.fit_transform(X_train, y_train)\naccuracy = classifier.score(X_test, y_test)","sub_path":"classifier/log_reg.py","file_name":"log_reg.py","file_ext":"py","file_size_in_byte":2307,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"479886368","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu Jun 13 11:53:06 2019\r\n\r\n@author: s143239\r\n\"\"\"\r\nimport tensorflow as tf\r\nfrom tensorflow import keras\r\nfrom keras.models import Model, Sequential\r\nfrom keras.layers import Input, Dense, Dropout, Flatten, Conv2D, MaxPooling2D, BatchNormalization\r\nfrom tensorflow.keras.losses import MSE, categorical_crossentropy\r\n\r\ndef deep_cnn(shape, num_classes, act = 'relu'):\r\n model = Sequential()\r\n # apply 32 convolution filters of size 3x3 each\r\n model.add(Conv2D(32, (3,3), padding=\"same\", input_shape=shape, activation = act))\r\n model.add(MaxPooling2D((2,2), strides = (2,2), padding = 'same'))\r\n \r\n model.add(Conv2D(32, (3,3), padding=\"same\", input_shape=shape, activation = act))\r\n model.add(MaxPooling2D((2,2), strides = (2,2), padding = 'same'))\r\n \r\n model.add(Conv2D(32, (3,3), padding=\"same\", input_shape=shape, activation = act))\r\n model.add(MaxPooling2D((2,2), strides = (2,2), padding = 'same'))\r\n \r\n model.add(Flatten())\r\n \r\n model.add(Dense(64, activation = act))\r\n model.add(Dropout(0.4))\r\n model.add(Dense(num_classes, activation = 'softmax'))\r\n \r\n model.summary()\r\n return model","sub_path":"model_spectrum.py","file_name":"model_spectrum.py","file_ext":"py","file_size_in_byte":1186,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"206334053","text":"from os import system\nfrom tempo import Tempo\nfrom personagem import Personagem\n\n\nif __name__ == \"__main__\": \n tempo = Tempo()\n personagem = Personagem()\n\n # MENU PRINCIPAL\n while True:\n system('cls')\n print(tempo)\n print('\\nBem-vindo a um dia normal de quarentena em 2021!')\n print('\\nO que sugere fazermos hoje:')\n print('[ 1 ] Estudar;')\n print('[ 2 ] Limpeza e higiene pessoal;')\n print('[ 3 ] Estimular a produção dos hormônios da felicidade para combatermos a depressão e a ansiedade;')\n print('[ 0 ] Dormir.')\n\n opcao = int(input('Escolha uma opção: '))\n \n # LAÇO DE REPETIÇÃO \n while True:\n # [ 1 ] ESTUDAR\n if opcao == 1:\n system('cls')\n print('O que você quer estudar?\\n\\n[ 1 ] Estudar programação na Blue Edtech\\n[ 2 ] Estudar para Concurso Público\\n[ 0 ] Menu principal\\n')\n escolha = int(input('Escolha uma opção: '))\n \n # [ 1 ] Estudar programação na Blue Edtech\n if escolha == 1:\n system('cls')\n if tempo.horas < 21:\n tempo.avancarTempo(60*3)\n print(tempo)\n personagem.estudarBlue()\n else:\n print(f'São {tempo.horas}:{tempo.minutos} horas.\\n')\n print('\\nAcabou de estudar? Você precisa descansar. Amanhã tem mais!')\n input('\\nPressione ENTER para continuar ...')\n break\n input('\\nPressione ENTER para continuar ...')\n\n # [ 2 ] Estudar para concurso público\n elif escolha == 2:\n system('cls')\n if tempo.horas < 21:\n personagem.estudarConcurso()\n tempo.avancarTempo(60*3)\n print(tempo)\n else:\n print(f'São {tempo.horas}:{tempo.minutos} horas.\\n')\n print('\\nEstá cansadx? Vamos dar um tempo, ok?')\n input('\\nPressione ENTER para continuar ...')\n break\n input('\\nPressione ENTER para continuar ...')\n elif escolha == 0:\n system('cls')\n break\n else:\n print('** Escolha apenas entre as opções disponíveis **')\n input('\\nAperte ENTER para continuar...')\n \n\n # [ 2 ] LIMPEZA E HIGIENE PESSOAL\n elif opcao == 2:\n system('cls')\n if tempo.horas < 16:\n tempo.avancarTempo(60*8)\n print(tempo)\n \n else:\n print(f'São {tempo.horas}:{tempo.minutos} horas.\\n\\nJá chega de limpar! Não exagere, também, né? Você precisa ir dormir.')\n input('\\nPressione ENTER para continuar ...')\n break\n input('\\nPressione ENTER para continuar ... ')\n break\n \n # AUMENTAR SAÚDE\n elif opcao == 3:\n system('cls')\n print('Escolha uma opção:\\n')\n print('[ 1 ] Comer alimentos saudáveis;')\n print('[ 2 ] Assistir Netiflix')\n print('[ 3 ] Corrida ao ar livre')\n print('[ 0 ] Menu Principal')\n\n escolha = int(input('Escolha uma opção acima: '))\n \n # COMIDA SAUDÁVEL\n if escolha == 1:\n personagem.comidaSaudavel()\n tempo.avancarTempo(30)\n print(tempo)\n print(personagem)\n input('\\nDigite ENTER para continuar...')\n \n # \"ASSISTIR NETFLIX\"\n elif escolha == 2:\n personagem.assistir()\n tempo.avancarTempo(60*2)\n print(tempo)\n print(personagem)\n input('\\nDigite ENTER para continuar...')\n \n # CORRIDA AO AR LIVRE\n elif escolha == 3:\n personagem.corrida()\n tempo.avancarTempo(60*2)\n print(tempo)\n print(personagem)\n input('\\nDigite ENTER para continuar...')\n # MENU PRINCIPAL\n elif escolha == 0:\n break\n else:\n system('cls')\n print('\\n** Escolha apenas entre as opções disponíveis! **')\n input('\\nDigite ENTER para continuar...')\n \n # IR DORMIR\n elif opcao == 0:\n tempo.dormir()\n print('')\n print(personagem)\n input('\\nPressione ENTER para ACORDAR...')\n break\n \n else:\n system('cls')\n print('Digite apenas números das opções.')\n input('\\nDigite ENTER para continuar...')\n break\n \n\n\n \n\n\n\n\n\n\n\n \n \n\n \n\n\n","sub_path":"Projeto_final_python_Andre_Vanessa_Blue.py","file_name":"Projeto_final_python_Andre_Vanessa_Blue.py","file_ext":"py","file_size_in_byte":5365,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"546916582","text":"from django.urls import path, include\n\nfrom .views import *\nfrom django.contrib.auth import views\n\nurlpatterns = [\n path('', index, name='index'),\n path('profile/bookings', bookins, name='bookins'),\n path('about', about, name='about'),\n path('profile', profile, name='profile'),\n path('stats', stats, name='stats'),\n path('timetable', rooms, name='rooms'),\n path('login', views.login, name='login'),\n path('auth', include('social_django.urls', namespace='social')),\n]","sub_path":"dashboard/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":491,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"262999165","text":"import re\n\n\nclass Phone:\n def __init__(self, phone):\n\n phone = str(phone)\n\n if self.is_valid(phone):\n self.__phone = phone\n else:\n raise ValueError('Invalid phone')\n\n def __str__(self):\n return self.mask()\n\n @staticmethod\n def is_valid(phone):\n return re.match('([0-9]{2,3})?([0-9]{2})?([0-9]{4,5})([0-9]{4})', phone) is not None\n\n def mask(self):\n\n matches = re.search('([0-9]{2,3})?([0-9]{2})?([0-9]{4,5})([0-9]{4})', self.__phone)\n\n return \"{}{}{}-{}\".format(\n f\"+{matches.group(1)} \" if matches.group(1) is not None else '',\n f\"({matches.group(2)}) \" if matches.group(2) is not None else '',\n matches.group(3),\n matches.group(4)\n )\n","sub_path":"brasilidades/Model/Phone.py","file_name":"Phone.py","file_ext":"py","file_size_in_byte":773,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"366432825","text":"import sys\n#\n# >>> Escriba el codigo del mapper a partir de este punto <<<\n#\ntotal=[]\n\nfor line in sys.stdin:\n line = line.strip()\n val,nada,letra = line.split(\"\\t\") \n val = int(val)\n \n x=(letra,nada,val)\n total.append(x)\n\ntotal.sort(key=lambda x: x[2])\n\nfor l in range(6):\n \n letra,nada,val=total[l]\n sys.stdout.write(\"{}\\t{}\\t{}\\n\".format(letra,nada,val))","sub_path":"01-hadoop-50/q09-10/reducer.py","file_name":"reducer.py","file_ext":"py","file_size_in_byte":385,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"178451310","text":"#python3\nimport random\n\ndef MergeSort(A, p, r):\n q = (p + r) // 2\n if p < r:\n MergeSort(A, p, q)\n MergeSort(A, q + 1, r)\n return Merge(A, p, q, r)\n\nMAX = 10000\n\ndef Merge(A, p, q, r):\n L = []\n R = []\n for i in range(p, q + 1):\n L.append(A[i])\n for i in range(q + 1, r + 1):\n R.append(A[i])\n L.append(MAX)\n R.append(MAX)\n i = 0\n j = 0\n for k in range(p, r + 1):\n if L[i] < R[j]:\n A[k] = L[i]\n i = i + 1\n else:\n A[k] = R[j]\n j = j + 1\n return A\n\nA = []\ns = random.randint(5, 10)\nfor i in range(0, s):\n A.append(random.randint(0, 50))\nprint(A)\nprint(MergeSort(A, 0, len(A)-1))","sub_path":"MergeSort.py","file_name":"MergeSort.py","file_ext":"py","file_size_in_byte":701,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"285719340","text":"from telebot import types\r\nfrom UserInst import UserInst\r\nfrom ALMConnect import ALMConnect\r\n\r\n\r\nclass MenuCreator:\r\n def main_menu(self):\r\n markup = types.ReplyKeyboardMarkup(one_time_keyboard=True, row_width=1)\r\n defect_lists = types.KeyboardButton('Списки дефектов')\r\n defect_reports = types.KeyboardButton('Отчеты по дефектам')\r\n markup.add(defect_lists, defect_reports)\r\n return markup\r\n\r\n def release_menu(self, user: UserInst):\r\n markup = types.ReplyKeyboardMarkup(one_time_keyboard=True, row_width=2)\r\n btns_list = list(types.KeyboardButton(rel) for rel in user.get_releases())\r\n for btn in btns_list:\r\n markup.add(btn)\r\n return markup\r\n\r\n def severity_menu(self, user: UserInst, release: str):\r\n markup = types.ReplyKeyboardMarkup(one_time_keyboard=True, row_width=2)\r\n btns_list = list(types.KeyboardButton(rel) for rel in user.get_severity(release))\r\n for btn in btns_list:\r\n markup.add(btn)\r\n return markup\r\n","sub_path":"MenuCreator.py","file_name":"MenuCreator.py","file_ext":"py","file_size_in_byte":1072,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"645774441","text":"from django.shortcuts import render\nfrom django.http import HttpResponse, JsonResponse\nimport subprocess\n\nfrom .models import Greeting\n\n\np = subprocess.Popen([\"python3\", 'index.py'],\n stdout = subprocess.PIPE,\n stdin = subprocess.PIPE)\n\n# Create your views here.\ndef index(request):\n # return HttpResponse('Hello from Python!')\n return render(request, \"index.html\")\n\ndef next(process):\n out = {}\n out['info'] = []\n print(process.poll())\n line = process.stdout.readline().decode(\"utf-8\")[:-1]\n if not(line):\n out['msg'] = \"failed\"\n return out\n \n while line[0] != '#':\n out['info'].append(line[1:])\n line = process.stdout.readline().decode(\"utf-8\")[:-1]\n out['msg'] = line[1:]\n\n print(\"returning\")\n print(out)\n return out\n\ndef no(request):\n global p\n p.stdin.write('n\\n'.encode())\n p.stdin.flush()\n return JsonResponse(next(p))\n\ndef yes(request):\n global p\n p.stdin.write('y\\n'.encode())\n p.stdin.flush()\n return JsonResponse(next(p))\n\ndef login(request):\n username = request.POST['name']\n pw = request.POST['password']\n global p\n out = 'l#'+str(username)+\",\"+str(pw)+\"\\n\"\n p.stdin.write(out.encode())\n p.stdin.flush()\n return JsonResponse(next(p))\n\ndef message(request):\n msg = request.POST['msg']\n global p\n out = \"m\"+msg+\"\\n\"\n p.stdin.write(out.encode())\n p.stdin.flush()\n return JsonResponse(next(p))\n\ndef start(request):\n global p\n p.stdin.write('s\\n'.encode())\n p.stdin.flush()\n return JsonResponse(next(p))\n","sub_path":"hello/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1598,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"540176939","text":"import cv2 as cv\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.spatial.distance import cosine\nimport math\n\nimage = cv.imread('steering.png')\nimage = image[300:430, 520:700]\nimage = cv.cvtColor(image, cv.COLOR_BGR2GRAY)\nret,thresh = cv.threshold(image,120,140,0)\n\nedged = cv.Canny(image,270,300)\n\nkernel = np.ones((5,5),np.uint8)\nclosed = cv.morphologyEx(edged, cv.MORPH_CLOSE, kernel)\n\n#cnts, contours, hierarchy = cv.findContours(closed.copy(), cv.RETR_TREE, cv.CHAIN_APPROX_SIMPLE)\n\n#cv.drawContours(image, contours, -1, (0,255,0), 3)\n\ncv.imwrite('img.png', closed)\n\nmat = np.argwhere(closed != 0)\nmat[:, [0,1]] = mat[:, [1, 0]]\nmat = np.array(mat).astype(np.float32)\n\nm, e = cv.PCACompute(mat, mean = np.array([]))\n\ncenter = tuple(m[0])\ntop = np.array((m[0][0]+1, m[0][1])).astype(np.float32)\nendpoint1 = tuple(m[0] + e[0]*10)\nendpoint2 = tuple(m[0] + e[1]*50)\n\n# center to endpoint1: 1st principal component\n\nprint(center)\nprint(top)\nprint(endpoint1)\nbase_vector = top - m[0]\npc1 = e[0]\npc1[1] = -pc1[1]\n\nangle = (cosine(base_vector, pc1))\n\nprint(angle)\n\ncv.circle(image, center, 5, 255)\ncv.line(image, center, endpoint1, 255)\ncv.line(image, center, tuple(top), 255)\n#cv.line(image, center, endpoint2, 255)\ncv.imwrite(\"out.bmp\", image)\n\n\n\n\n# m, e = cv.PCACompute(contours, mean = np.array([]))\n# print(m)\n\n","sub_path":"vugc2_control/src/visual_encoder_demo.py","file_name":"visual_encoder_demo.py","file_ext":"py","file_size_in_byte":1326,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"415343152","text":"# Copyright 2012 Diwaker Gupta\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 cgi\nimport jinja2\nimport os\nimport random\nimport string\nimport webapp2\n\nfrom google.appengine.api import memcache\nfrom google.appengine.api import users\nfrom google.appengine.ext import db\n\njinja_environment = jinja2.Environment(\n loader=jinja2.FileSystemLoader(os.path.dirname(__file__)))\n\nclass Paste(db.Model):\n id = db.StringProperty()\n content = db.TextProperty()\n timestamp = date = db.DateTimeProperty(auto_now_add=True)\n\ndef gen_random_string(length):\n chars = string.letters + string.digits\n return ''.join(random.choice(chars) for i in xrange(length))\n\nclass SavePaste(webapp2.RequestHandler):\n def post(self):\n user = users.get_current_user()\n if not user:\n self.redirect(users.create_login_url(self.request.uri))\n paste = Paste()\n paste.id = gen_random_string(8)\n paste.content = self.request.get('content')\n paste.put()\n self.response.set_cookie('delid', str(paste.key()))\n self.redirect('/' + paste.id)\n\nclass DelPaste(webapp2.RequestHandler):\n def post(self):\n user = users.get_current_user()\n if not user:\n self.redirect(users.create_login_url(self.request.uri))\n delid = self.request.get('delid')\n if delid:\n paste = Paste.get(delid)\n if paste:\n memcache.delete(paste.id)\n paste.delete()\n self.redirect('/')\n\nclass CreatePaste(webapp2.RequestHandler):\n def get(self):\n user = users.get_current_user()\n if not user:\n self.redirect(users.create_login_url(self.request.uri))\n template_values = {}\n template = jinja_environment.get_template('index.html')\n self.response.out.write(template.render(template_values))\n\nclass ShowPaste(webapp2.RequestHandler):\n def get(self, paste_id):\n paste = memcache.get(paste_id)\n if paste is None:\n query = db.Query(Paste)\n query.filter(\"id = \", paste_id)\n entry = query.get()\n if entry is None:\n self.abort(404)\n paste = entry.content\n memcache.add(paste_id, paste)\n template_values = {\"content\": cgi.escape(paste)}\n if 'delid' in self.request.cookies:\n template_values['delid'] = self.request.cookies.get('delid')\n self.response.delete_cookie('delid')\n template = jinja_environment.get_template('index.html')\n self.response.out.write(template.render(template_values))\n\napp = webapp2.WSGIApplication([\n (r'/', CreatePaste),\n (r'/paste', SavePaste),\n (r'/oops', DelPaste),\n (r'/(\\S+)', ShowPaste)\n ])\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3238,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"462182912","text":"#!/usr/bin/env python3\n# -*- coding: UTF-8 -*-\n# -----------------------------------------------------------------------------\n#\n# P A G E B O T\n#\n# Copyright (c) 2016+ Buro Petr van Blokland + Claudia Mens\n# www.pagebot.io\n# Licensed under MIT conditions\n#\n# Supporting DrawBot, www.drawbot.com\n# Supporting Flat, xxyxyz.org/flat\n# -----------------------------------------------------------------------------\n#\n# pbimage.py\n#\n\n\nimport os\n\nfrom pagebot.elements.element import Element\nfrom pagebot.constants import ORIGIN, CACHE_EXTENSIONS #\nfrom pagebot.toolbox.units import pointOffset, point2D, point3D, units, pt, upt\nfrom pagebot.toolbox.color import noColor\nfrom pagebot.toolbox.transformer import path2Extension\n\n\nclass Image(Element):\n \"\"\"The Image contains the reference to the actual binary image data.\n eId can be (unique) file path or eId.\n\n >>> from pagebot.toolbox.units import mm, p, point3D\n >>> from pagebot import getResourcesPath\n >>> imageFilePath = '/images/peppertom_lowres_398x530.png'\n >>> imagePath = getResourcesPath() + imageFilePath\n >>> from pagebot.contexts.drawbotcontext import DrawBotContext\n >>> from pagebot.constants import A4\n >>> from pagebot.document import Document\n >>> from pagebot.conditions import *\n >>> doc = Document(size=A4, originTop=False, padding=30)\n >>> page = doc[1]\n >>> e = Image(imagePath, xy=pt(220, 330), w=512, parent=page, conditions=[Fit2Sides()])\n >>> e.xy # Position of the image\n (220pt, 330pt)\n >>> (e.w, e.h), e.size # Identical result, width is the lead.\n ((512pt, 681.81pt), (512pt, 681.81pt))\n >>> e.h = 800 # Width is proportionally calculated, height is the lead.\n >>> e.size\n (600.75pt, 800pt)\n >>> e.h *= 1.5\n >>> e.size, e._w, e._h\n ((901.13pt, 1200pt), None, 1200pt)\n >>> e.size = mm(50), p(100) # Disproportional size setting\n >>> e.size\n (50mm, 100p)\n >>> e.size = None # Force answering the original image size\n >>> e.size # Initialize from file\n (398pt, 530pt)\n >>> page.w = mm(150)\n >>> e.conditions = [Top2Top(), Fit2Width()] # Set new condition, fitting on page padding of 30pt\n >>> doc.solve()\n Score: 2 Fails: 0\n >>> e.xy, e.size # Now disproportionally fitting the full page size of the A4-doc\n ((30pt, 99.44mm), (128.83mm, 486.32pt))\n \"\"\"\n isImage = True\n\n def __init__(self, path=None, name=None, w=None, h=None, size=None, z=0, mask=None,\n imo=None, index=1, saveScaled=True, **kwargs):\n Element.__init__(self, **kwargs)\n\n # Initialize the self.im and self.ih sizes of the image file, defined by path.\n # If the path does not exist, then self.im = self.ih = pt(0)\n self.path = path # If path is omitted or file does not exist, a gray/crossed rectangle will be drawn.\n self.initImageSize()\n\n # One of the two needs to be defined, the other can be None.\n # If both are set, then the image scales disproportional.\n if size is None and w is None and h is None: # Set size to original proportions in the file\n self.size = None\n elif size is not None: # Disproportional scaling if both are not None or reset to 100% with (None, None)\n self.size = size\n elif w is not None and h is not None: # Disproportional scaling\n self.size = w, h\n elif w is not None: # Separate settings, to keep proportions if only one it set.\n self.w = w # Sets self._h to None to indicate that width is the lead.\n elif h is not None:\n self.h = h # Sets self._w to None to indicate that height is the lead.\n self.z = z # Make conditions work with captions inside an image frame element.\n\n self.name = name\n self.mask = mask # Optional mask element.\n self.imo = imo # Optional ImageObject with filters defined. See http://www.drawbot.com/content/image/imageObject.html\n self.index = index # In case there are multiple images in the file (e.g. PDF), use this index. Default is first = 1\n # If True (default), then save the image to a scaled version in _scaled/ and alter self.path name to scaled image.\n # Do not scale the image, if the cache file already exists. If False, then not scaled cache is created.\n self.saveScaled = saveScaled \n\n def _get_size(self):\n \"\"\"Get/Set the size of the image. If one of (self._w, self._h) values is None,\n then it is calculated by propertion. If both are None, the original size of the\n image is returned. If both are not None, then that size is answered disproportionally.\n \"\"\"\n return self.w, self.h\n def _set_size(self, size):\n if size is None: # Reset to original size by single None value.\n size = None, None, None\n self._w, self._h, self.d = point3D(size)\n size = property(_get_size, _set_size)\n\n def _get_size3D(self):\n return self.w, self.h, self.d\n size3D = property(_get_size3D, _set_size)\n\n def _get_w(self):\n \"\"\"Get the intended width and calculate the new scale, validating the\n width to the image minimum width and the height to the image minimum height.\n If not self._h is defined, then the proportion is recalculated, depending on\n the ratio of the image.\"\"\"\n u = None\n if not self._w: # Width is undefined\n ihpt = upt(self.ih)\n if self._h and ihpt:\n u = self.iw * upt(self._h / ihpt) # Height is lead, calculate width.\n else:\n u = self.iw # Undefined and without parent, answer original image width.\n else:\n base = dict(base=self.parentW, em=self.em) # In case relative units, use the right kind of base.\n u = units(self._w, base=base) # Width is lead and defined as not 0 or None.\n return u\n def _set_w(self, w):\n # If self._h is set too, do disproportional sizing. Otherwise set to 0 or None.\n if w:\n w = units(w)\n self._w = w\n self._h = None\n w = property(_get_w, _set_w)\n\n def _get_h(self):\n u = None\n if not self._h: # Width is undefined\n iwpt = upt(self.iw)\n if self._w and iwpt:\n u = self.ih * upt(self._w / iwpt) # Width is lead, calculate height.\n else:\n u = self.ih # Undefined and without parent, answer original image width.\n else:\n base = dict(base=self.parentH, em=self.em) # In case relative units, use the right kind of base.\n u = units(self._h, base=base) # Height is lead and defined as not 0 or None.\n return u\n def _set_h(self, h):\n # If self._w is set too, do disproportional sizing. Otherwise set to 0 or None.\n if h:\n h = units(h)\n self._w = None\n self._h = h\n\n h = property(_get_h, _set_h)\n\n def __len__(self):\n u\"\"\"Answers the number of pages in the the current image file.\"\"\"\n if self.path:\n return self.context.numberOfImages(self.path)\n return 0\n\n def __repr__(self):\n return '[%s eId:%s path:%s]' % (self.__class__.__name__, self.eId, self.path)\n\n def addFilter(self, filters):\n \"\"\"Add the filter to the self.imo image object. Create the image\n object in case it doest not exist yet. To be extended into a better\n API. More feedback needed for what the DrawBot values in the filters do\n and what their ranges are.\"\"\"\n if self.imo is None and self.path is not None:\n self.imo = self.context.getImageObject(self.path)\n for filter, params in filters:\n getattr(self.imo, filter)(**params)\n\n def setPath(self, path):\n \"\"\"Set the path of the image. If the path exists, the get the real\n image size and store as self.iw, self.ih.\"\"\"\n self._path = path\n self.initImageSize() # Get real size from the file.\n\n def _get_path(self):\n return self._path\n def _set_path(self, path):\n self.setPath(path)\n path = property(_get_path, _set_path)\n\n def initImageSize(self):\n \"\"\"Initialize the image size. Note that this is done with the\n default/current Context, as there may not be a view availabe yet.\"\"\"\n if self.path is not None and os.path.exists(self.path):\n self.iw, self.ih = self.context.imageSize(self.path)\n else:\n self.iw = self.ih = pt(0) # Undefined or non-existing, there is no image file.\n\n def _get_imageSize(self):\n \"\"\"Answers the Point2D image size in pixels.\"\"\"\n return self.iw, self.ih\n imageSize = property(_get_imageSize)\n\n def getPixelColor(self, p, scaled=True):\n \"\"\"Answers the color in either the scaled point (x, y) or original\n image size point.\"\"\"\n assert self.path is not None\n x, y = point2D(p)\n if scaled:\n x = self.w / self.iw\n y = self.h / self.ih\n p = x, y\n return self.doc.context.imagePixelColor(self.path, p)\n\n def _getAlpha(self):\n \"\"\"Use alpha channel of the fill color as opacity of the image.\"\"\"\n sFill = self.css('fill', noColor)\n if isinstance(sFill, (tuple, list)) and len(sFill) == 4:\n _, _, _, alpha = sFill\n else:\n alpha = 1\n return alpha\n\n def saveScaledCache(self, view):\n \"\"\"If the self.saveScaled is True and the reduction scale is inside the range,\n then create a new cached image file, if it does not already exist. Scaling images in \n the DrawBot context is a fast operation, so always worthwhile to creating PNG from\n large export PDF files.\n In case the source is a PDF, then use self.index to request for the page.\n \"\"\"\n if self.path is None or not self.saveScaled:\n return\n if not self.iw or not self.ih: # Make sure not zero, to avoid division\n print('Image.saveScaledCache: %dx%d zero image size' % (self.iw, self.ih))\n return\n extension = path2Extension(self.path)\n resolutionFactor = self.resolutionFactors.get(extension, 1)\n # Translate the extension to the related type of output.\n exportExtension = CACHE_EXTENSIONS.get(extension, extension)\n resW = self.w * resolutionFactor \n resH = self.h * resolutionFactor\n sx, sy = upt(resW / self.iw, resH / self.ih)\n if not self.saveScaled and 0.8 <= sx and 0.8 <= sy: # If no real scale reduction, then skip. Never enlarge.\n return\n # Scale the image the cache does not exist already.\n # A new path is answers for the scaled image file. Reset the (self.iw, self.ih)\n self.path = self.context.scaleImage(\n path=self.path, w=resW, h=resH, index=self.index, \n showImageLoresMarker=self.showImageLoresMarker or view.showImageLoresMarker, \n exportExtension=exportExtension\n )\n\n def prepare(self, view, origin=None, drawElements=True):\n \"\"\"Respond to the top-down element broadcast to prepare for build.\n If the original image needs scaling, then prepare the build by letting the context\n make a new cache file with the scaled images.\n If the cache file already exists, then ignore, just continue the broadcast\n towards the child elements.\n \"\"\"\n self.saveScaledCache(view) \n for e in self.elements:\n e.prepare(view, origin, drawElements)\n\n def build_html(self, view, origin=None, drawElements=True):\n print('[%s.build_html] Not implemented yet' % self.__class__.__name__)\n\n def build_flat(self, view, origin=ORIGIN, drawElements=True):\n print('[%s.build_flat] Not implemented yet' % self.__class__.__name__)\n\n def build(self, view, origin=ORIGIN, drawElements=True):\n \"\"\"Draw the image in the calculated scale. Since we need to use the\n image by scale transform, all other measure (position, lineWidth) are\n scaled back to their original proportions.\n\n If stroke is defined, then use that to draw a frame around the image.\n Note that the (sx, sy) is already scaled to fit the padding position\n and size.\"\"\"\n\n context = self.context # Get current context and builder.\n b = context.b # This is a bit more efficient than self.b once we got context\n\n p = pointOffset(self.origin, origin)\n p = self._applyScale(view, p)\n px, py, _ = p = self._applyAlignment(p) # Ignore z-axis for now.\n\n self._applyRotation(view, p)\n\n if self.path is None or not os.path.exists(self.path) or not self.iw or not self.ih:\n # TODO: Also show error, in case the image does not exist, to differ from empty box.\n if self.path is not None and not os.path.exists(self.path):\n print('Warning: cannot find image file %s' % self.path)\n # Draw missing element as cross\n xpt, ypt, wpt, hpt = upt(px, py, self.w, self.h)\n context.stroke(0.5)\n context.strokeWidth(0.5)\n context.fill(None)\n context.rect(xpt, ypt, wpt, hpt)\n context.line((xpt, ypt), (xpt+wpt, ypt+hpt))\n context.line((xpt+wpt, ypt), (xpt, ypt+hpt))\n else:\n context.save()\n # Check if scaling exceeds limit, then generate a cached file and update the path\n # and (self.iw, self.ih) accordingly.\n\n sx = self.w / self.iw\n sy = self.h / self.ih\n context.scale(sx, sy)\n\n # If there is a clipRect defined, create the bezier path\n if self.clipRect is not None:\n clipRect = context.newPath()\n clX, clY, clW, clH = upt(self.clipRect)\n sclX = clX/sx\n sclY = clY/sx\n sclW = clW/sx\n sclH = clH/sy\n # move to a point\n clipRect.moveTo((sclX, sclY))\n # line to a point\n clipRect.lineTo((sclX, sclY+sclH))\n clipRect.lineTo((sclX+sclW, sclY+sclH))\n clipRect.lineTo((sclX+sclW, sclY))\n # close the path\n clipRect.closePath()\n # set the path as a clipping path\n b.clipPath(clipRect)\n # the image will be clipped inside the path\n #b.fill(0, 0, 0.5, 0.5)\n #b.drawPath(clipRect)\n elif self.clipPath is not None:\n #Otherwise if there is a clipPath, then use it.\n b.clipPath(self.clipPath)\n\n if self.imo is not None:\n with self.imo:\n b.image(self.path, (0, 0), pn=1, alpha=self._getAlpha())\n b.image(self.imo, upt(px/sx, py/sy), pageNumber=self.index, alpha=self._getAlpha())\n else:\n b.image(self.path, upt(px/sx, py/sy), pageNumber=self.index, alpha=self._getAlpha())\n # TODO: Draw optional (transparant) forground color?\n\n b.clipPath(None)\n context.restore()\n\n self.buildFrame(view, p) # Draw optional frame or borders.\n\n #if drawElements:\n # self.buildChildElements(view, p)\n\n self._restoreRotation(view, p)\n\n self._restoreScale(view)\n view.drawElementInfo(self, origin)\n\nif __name__ == '__main__':\n import doctest\n import sys\n sys.exit(doctest.testmod()[0])\n","sub_path":"Lib/pagebot/elements/pbimage.py","file_name":"pbimage.py","file_ext":"py","file_size_in_byte":15482,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"364456240","text":"# Copyright (c) 2012 Leif Johnson \n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\n'''This file contains recurrent network structures.'''\n\nimport climate\nimport numpy as np\nimport numpy.random as rng\nimport theano\nimport theano.tensor as TT\n\n#from theano.tensor.shared_randomstreams import RandomStreams\nfrom theano.sandbox.rng_mrg import MRG_RandomStreams as RandomStreams\n\nfrom . import feedforward as ff\n\nlogging = climate.get_logger(__name__)\n\n\ndef batches(samples, labels=None, steps=100, batch_size=64):\n '''Return a callable that generates samples from a dataset.\n\n Parameters\n ----------\n samples : ndarray (time-steps, data-dimensions)\n An array of data. Rows in this array correspond to time steps, and\n columns to variables.\n labels : ndarray (time-steps, label-dimensions), optional\n An array of data. Rows in this array correspond to time steps, and\n columns to labels.\n steps : int, optional\n Generate samples of this many time steps. Defaults to 100.\n batch_size : int, optional\n Generate this many samples per call. Defaults to 64. This must match the\n batch_size parameter that was used when creating the recurrent network\n that will process the data.\n\n Returns\n -------\n callable :\n A callable that can be used inside a dataset for training a recurrent\n network.\n '''\n def unlabeled_sample():\n xs = np.zeros((steps, batch_size, samples.shape[1]), ff.FLOAT)\n for i in range(batch_size):\n j = rng.randint(len(samples) - steps)\n xs[:, i, :] = samples[j:j+steps]\n return [xs]\n def labeled_sample():\n xs = np.zeros((steps, batch_size, samples.shape[1]), ff.FLOAT)\n ys = np.zeros((steps, batch_size, labels.shape[1]), ff.FLOAT)\n for i in range(batch_size):\n j = rng.randint(len(samples) - steps)\n xs[:, i, :] = samples[j:j+steps]\n ys[:, i, :] = labels[j:j+steps]\n return [xs, ys]\n return unlabeled_sample if labels is None else labeled_sample\n\n\nclass Network(ff.Network):\n '''A fully connected recurrent network with one input and one output layer.\n\n Parameters\n ----------\n layers : sequence of int\n A sequence of integers specifying the number of units at each layer. As\n an example, layers=(10, 20, 3) has one \"input\" layer with 10 units, one\n \"hidden\" layer with 20 units, and one \"output\" layer with 3 units. That\n is, inputs should be of length 10, and outputs will be of length 3.\n\n recurrent_layers : sequence of int, optional\n A sequence of integers specifying the indices of recurrent layers in the\n network. Non-recurrent network layers receive input only from the\n preceding layers for a given input, while recurrent layers also receive\n input from the output of the recurrent layer from the previous time\n step. Defaults to [len(layers) // 2 - 1], i.e., the \"middle\" layer of\n the network is the only recurrent layer.\n\n recurrent_sparsity : float in (0, 1), optional\n Ensure that the given fraction of recurrent model weights is initialized\n to zero. Defaults to 0, which makes all recurrent weights nonzero.\n\n hidden_activation : str, optional\n The name of an activation function to use on hidden network units.\n Defaults to 'sigmoid'.\n\n output_activation : str, optional\n The name of an activation function to use on output units. Defaults to\n 'linear'.\n\n rng : theano.RandomStreams, optional\n Use a specific Theano random number generator. A new one will be created\n if this is None.\n\n input_noise : float, optional\n Standard deviation of desired noise to inject into input.\n\n hidden_noise : float, optional\n Standard deviation of desired noise to inject into hidden unit\n activation output.\n\n input_dropouts : float, optional\n Proportion of input units to randomly set to 0.\n\n hidden_dropouts : float, optional\n Proportion of hidden unit activations to randomly set to 0.\n\n recurrent_error_start : int, optional\n Compute error metrics starting at this time step. (Defaults to 3.)\n '''\n\n @property\n def error_start(self):\n return self.kwargs.get('recurrent_error_start', 3)\n\n def setup_vars(self):\n '''Setup Theano variables for our network.\n\n Returns\n -------\n vars : list of theano variables\n A list of the variables that this network requires as inputs.\n '''\n # the first dimension indexes time, the second indexes the elements of\n # each minibatch, and the third indexes the variables in a given frame.\n self.x = TT.tensor3('x')\n\n # we store the initial state of recurrent hidden units in shared\n # variables indexed by this dictionary.\n self.h0 = {}\n\n return [self.x]\n\n def setup_layers(self, **kwargs):\n '''\n '''\n count = 0\n\n noise = kwargs.get('input_noise', 0)\n dropout = kwargs.get('input_dropouts', 0)\n x = self._add_noise(self.x, noise, dropout)\n\n kw = dict(\n sparse=kwargs.get('recurrent_sparsity', 0),\n radius=kwargs.get('recurrent_radius', 0),\n noise=kwargs.get('hidden_noise', 0),\n dropout=kwargs.get('hidden_dropouts', 0),\n )\n layers = kwargs.get('layers')\n recurrent = set(kwargs.get('recurrent_layers', [len(layers) // 2 - 1]))\n for i, (nin, nout) in enumerate(zip(layers[:-1], layers[1:])):\n z = self.hiddens and self.hiddens[-1] or x\n add = self.add_feedforward_layer\n if i in recurrent:\n add = self.add_recurrent_layer\n count += add(z, nin, nout, label=i, **kw)\n\n self.hiddens.pop()\n self.y = self._output_func(self.preacts[-1])\n logging.info('%d total network parameters', count)\n\n def add_recurrent_layer(self, x, nin, nout, **kwargs):\n '''Add a new recurrent layer to the network.\n\n Parameters\n ----------\n input : theano variable\n The theano variable that represents the inputs to this layer.\n nin : int\n The number of input units to this layer.\n nout : out\n The number of output units from this layer.\n label : any, optional\n The name of this layer, used for logging and as the theano variable\n name suffix. Defaults to the index of this layer in the network.\n sparse : float in (0, 1), optional\n If given, create sparse connections in the recurrent weight matrix,\n such that this fraction of the weights is set to zero. By default,\n this parameter is 0, meaning all recurrent weights are nonzero.\n radius : float, optional\n If given, rescale the initial weights to have this spectral radius.\n No scaling is performed by default.\n\n Returns\n -------\n count : int\n The number of learnable parameters in this layer.\n '''\n label = kwargs.get('label') or len(self.hiddens)\n\n b_h, _ = self.create_bias(nout, 'h_{}'.format(label))\n W_xh, _ = self.create_weights(nin, nout, 'xh_{}'.format(label))\n W_hh, _ = self.create_weights(nout, nout, 'hh_{}'.format(label), **kwargs)\n\n def fn(x_t, h_tm1, W_xh, W_hh, b_h):\n return self._hidden_func(TT.dot(x_t, W_xh) + TT.dot(h_tm1, W_hh) + b_h)\n\n batch_size = self.kwargs.get('batch_size', 64)\n self.h0[label] = theano.shared(\n np.zeros((batch_size, nout), 'f'), name='h0_{}'.format(label))\n\n hid, updates = theano.scan(\n name='rnn_{}'.format(label),\n fn=fn,\n sequences=[x],\n non_sequences=[W_xh, W_hh, b_h],\n outputs_info=[self.h0[label]])\n\n self.updates.update(updates)\n self.weights.extend([W_xh, W_hh])\n self.biases.append(b_h)\n self.preacts.append(None)\n self.hiddens.append(hid)\n\n return nout * (1 + nin + nout)\n\n\nclass MRNN(Network):\n '''Define recurrent network layers using multiplicative dynamics.\n\n The formulation of MRNN implemented here uses a factored dynamics matrix as\n described in Sutskever, Martens & Hinton, ICML 2011, \"Generating text with\n recurrent neural networks.\" This paper is available online at\n http://www.icml-2011.org/papers/524_icmlpaper.pdf.\n '''\n\n def add_recurrent_layer(self, x, nin, nout, **kwargs):\n '''Add a new recurrent layer to the network.\n\n Parameters\n ----------\n input : theano variable\n The theano variable that represents the inputs to this layer.\n nin : int\n The number of input units to this layer.\n nout : out\n The number of output units from this layer.\n label : any, optional\n The name of this layer, used for logging and as the theano variable\n name suffix. Defaults to the index of this layer in the network.\n factors : int, optional\n The number of factors to use in the hidden-to-hidden dynamics\n matrix. Defaults to the number of hidden units.\n\n Returns\n -------\n count : int\n The number of learnable parameters in this layer.\n '''\n label = kwargs.get('label') or len(self.hiddens)\n factors = kwargs.get('factors') or nout\n\n b_h, _ = self.create_bias(nout, 'h_{}'.format(label))\n\n W_xf, _ = self.create_weights(nin, factors, 'xf_{}'.format(label))\n W_hf, _ = self.create_weights(nout, factors, 'hf_{}'.format(label))\n W_fh, _ = self.create_weights(factors, nout, 'fh_{}'.format(label))\n W_xh, _ = self.create_weights(nin, nout, 'xh_{}'.format(label))\n\n def fn(x_t, h_tm1, W_xh, W_xf, W_hf, W_fh, b_h):\n f_t = TT.dot(TT.dot(h_tm1, W_hf) * TT.dot(x_t, W_xf), W_fh)\n return self._hidden_func(TT.dot(x_t, W_xh) + b_h + f_t)\n\n batch_size = self.kwargs.get('batch_size', 64)\n self.h0[label] = theano.shared(\n np.zeros((batch_size, nout), 'f'), name='h0_{}'.format(label))\n\n hid, updates = theano.scan(\n name='mrnn_{}'.format(label),\n fn=fn,\n sequences=[x],\n non_sequences=[W_xh, W_xf, W_hf, W_fh, b_h],\n outputs_info=[self.h0[label]])\n\n self.updates.update(updates)\n self.weights.extend([W_xh, W_xf, W_hf, W_fh])\n self.biases.append(b_h)\n self.preacts.append(None)\n self.hiddens.append(hid)\n\n return nout * (1 + nin) + factors * (2 * nout + nin)\n\n\nclass LSTM(Network):\n '''\n '''\n\n def add_recurrent_layer(self, x, nin, nout, **kwargs):\n '''Add a new recurrent layer to the network.\n\n Parameters\n ----------\n input : theano variable\n The theano variable that represents the inputs to this layer.\n nin : int\n The number of input units to this layer.\n nout : out\n The number of output units from this layer.\n label : any, optional\n The name of this layer, used for logging and as the theano variable\n name suffix. Defaults to the index of this layer in the network.\n\n Returns\n -------\n count : int\n The number of learnable parameters in this layer.\n '''\n label = kwargs.get('label') or len(self.hiddens)\n\n b_i, _ = self.create_bias(nout, 'i_{}'.format(label))\n b_f, _ = self.create_bias(nout, 'f_{}'.format(label))\n b_o, _ = self.create_bias(nout, 'o_{}'.format(label))\n b_c, _ = self.create_bias(nout, 'c_{}'.format(label))\n\n # these weight matrices are always diagonal.\n W_ci, _ = self.create_bias(nout, 'ci_{}'.format(label))\n W_cf, _ = self.create_bias(nout, 'cf_{}'.format(label))\n W_co, _ = self.create_bias(nout, 'co_{}'.format(label))\n\n W_xi, _ = self.create_weights(nin, nout, 'xi_{}'.format(label))\n W_xf, _ = self.create_weights(nin, nout, 'xf_{}'.format(label))\n W_xo, _ = self.create_weights(nin, nout, 'xo_{}'.format(label))\n W_xc, _ = self.create_weights(nin, nout, 'xc_{}'.format(label))\n\n W_hi, _ = self.create_weights(nout, nout, 'hi_{}'.format(label))\n W_hf, _ = self.create_weights(nout, nout, 'hf_{}'.format(label))\n W_ho, _ = self.create_weights(nout, nout, 'ho_{}'.format(label))\n W_hc, _ = self.create_weights(nout, nout, 'hc_{}'.format(label))\n\n def fn(x_t, h_tm1, c_tm1, W_ci, W_cf, W_co, W_xi, W_xf, W_xo, W_xc, W_hi, W_hf, W_ho, W_hc, b_i, b_f, b_o, b_c):\n i_t = TT.nnet.sigmoid(TT.dot(x_t, W_xi) + TT.dot(h_tm1, W_hi) + c_tm1 * W_ci + b_i)\n f_t = TT.nnet.sigmoid(TT.dot(x_t, W_xf) + TT.dot(h_tm1, W_hf) + c_tm1 * W_cf + b_f)\n c_t = f_t * c_tm1 + i_t * TT.tanh(TT.dot(x_t, W_xc) + TT.dot(h_tm1, W_hc) + b_c)\n o_t = TT.nnet.sigmoid(TT.dot(x_t, W_xo) + TT.dot(h_tm1, W_ho) + c_t * W_co + b_o)\n h_t = o_t * TT.tanh(c_t)\n return h_t, c_t\n\n W = [W_ci, W_cf, W_co, W_xi, W_xf, W_xo, W_xc, W_hi, W_hf, W_ho, W_hc]\n B = [b_i, b_f, b_o, b_c]\n\n batch_size = self.kwargs.get('batch_size', 64)\n (hid, _), updates = theano.scan(\n name='f_{}'.format(label),\n fn=fn,\n sequences=[x],\n non_sequences=W + B,\n outputs_info=[TT.zeros((batch_size, nout), dtype=ff.FLOAT),\n TT.zeros((batch_size, nout), dtype=ff.FLOAT)])\n\n self.updates.update(updates)\n self.weights.extend(W)\n self.biases.extend(B)\n self.preacts.append(None)\n self.hiddens.append(hid)\n\n return nout * (7 + 4 * nout + 4 * nin)\n\n\nclass Autoencoder(Network):\n '''An autoencoder attempts to reproduce its input.'''\n\n @property\n def cost(self):\n err = self.y - self.x\n return TT.mean((err * err).sum(axis=2)[self.error_start:])\n\n\nclass Predictor(Autoencoder):\n '''A predictor network attempts to predict its next time step.\n '''\n\n @property\n def cost(self):\n # we want the network to predict the next time step. y is the prediction\n # (output of the network), so we want y[0] to match x[1], y[1] to match\n # x[2], and so forth.\n err = self.x[1:] - self.generate_prediction(self.y)[:-1]\n return TT.mean((err * err).sum(axis=2)[self.error_start:])\n\n def generate_prediction(self, y):\n '''Given outputs from each time step, map them to subsequent inputs.\n\n This defaults to the identity transform, i.e., the output from one time\n step is treated as the input to the next time step with no\n transformation. Override this method in a subclass to provide, e.g.,\n predictions based on random samples, lookups in a dictionary, etc.\n\n Parameters\n ----------\n y : theano variable\n A symbolic variable representing the \"raw\" output of the recurrent\n predictor.\n\n Returns\n -------\n y : theano variable\n A symbolic variable representing the inputs for the next time step.\n '''\n return y\n\n\nclass Regressor(Network):\n '''A regressor attempts to produce a target output.'''\n\n def setup_vars(self):\n '''Setup Theano variables for our network.\n\n Returns\n -------\n vars : list of theano variables\n A list of the variables that this network requires as inputs.\n '''\n super(Regressor, self).setup_vars()\n\n # for a regressor, k specifies the correct outputs for a given input.\n self.k = TT.tensor3('k')\n\n return [self.x, self.k]\n\n @property\n def cost(self):\n err = self.y - self.k\n return TT.mean((err * err).sum(axis=2)[self.error_start:])\n\n\nclass Classifier(Network):\n '''A classifier attempts to match a 1-hot target output.'''\n\n def __init__(self, **kwargs):\n kwargs['output_activation'] = 'softmax'\n\n super(Classifier, self).__init__(**kwargs)\n\n def setup_vars(self):\n '''Setup Theano variables for our network.\n\n Returns\n -------\n vars : list of theano variables\n A list of the variables that this network requires as inputs.\n '''\n super(Classifier, self).setup_vars()\n\n # for a classifier, k specifies the correct labels for a given input.\n self.k = TT.ivector('k')\n\n return [self.x, self.k]\n\n @property\n def cost(self):\n return -TT.mean(TT.log(self.y)[TT.arange(self.k.shape[0]), self.k])\n\n @property\n def accuracy(self):\n '''Compute the percent correct classifications.'''\n return 100 * TT.mean(TT.eq(TT.argmax(self.y, axis=1), self.k))\n\n @property\n def monitors(self):\n yield 'acc', self.accuracy\n for i, h in enumerate(self.hiddens):\n yield 'h{}<0.1'.format(i+1), 100 * (abs(h) < 0.1).mean()\n yield 'h{}<0.9'.format(i+1), 100 * (abs(h) < 0.9).mean()\n\n def classify(self, x):\n return self.predict(x).argmax(axis=1)\n","sub_path":"theanets/recurrent.py","file_name":"recurrent.py","file_ext":"py","file_size_in_byte":18247,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"322652137","text":"\"\"\"\nSketch for Neo4j and python words graph implementation\n\"\"\"\nimport smart_open\nimport json\nimport os\nimport csv\nimport pickle\n\nfrom py2neo import Graph, Node, Relationship, Subgraph\nimport pandas as pd\nimport numpy as np\nimport nltk\n# nltk.download('punkt')\nfrom gensim import corpora\n\nGraphWordVertex = \"Word\"\nGraphNextWordRel = \"NextWord\"\n\nclass DBInfo:\n\tdef __init__(self, url, password, user='neo4j'):\n\t\tself.url = url\n\t\tself.user = user\n\t\tself.password = password\n\nclass Config:\n\tDEBUG = False\n\tDEBUG_CORPUS_PORTION = 100\n\tVOCABULARY_SAVE_PATH = \"dictionaryFiles/vocabularySave.pickle\"\n\tGRAPH_PATH = \"graph/\"\n\tNODES_FILENAME = \"nodes.csv\"\n\tNODES_HEADER = [\"id\", \"content\"]\n\tRELATIONSHIPS_FILENAME = \"relationships.csv\"\n\tRELATIONSHIPS_HEADER = [\"from\", \"to\", \"doc\"]\n\nclass Text2Neo4j:\n\t\"\"\"\n\tThis class will be used to build the graph from the corpus. It creates for each document a type of edges.\n\tVertices are unique words across all corpus.\n\t\"\"\"\n\n\n\tdef __init__(self, dbInfo, config):\n\t\t\"\"\"\n\t\tC'tor for this class.\n\t\t\"\"\"\n\t\tself.config = config\n\t\tself.graph = Graph(dbInfo.url, user=dbInfo.user, password=dbInfo.password)\n\n\t\tself.initFilesAndFolders()\n\n\t\tself.vocabulary = {}\n\t\t#\ttry loading existing dictionary:\n\t\tself.loadVocabulary()\n\n\n\tdef loadVocabulary(self):\n\t\tif os.path.exists(self.config.VOCABULARY_SAVE_PATH):\n\t\t\twith open(self.config.VOCABULARY_SAVE_PATH, 'rb') as f:\n\t\t\t\tself.vocabulary = pickle.load(f)\n\n\tdef saveVocabulary(self):\n\t\twith open(self.config.VOCABULARY_SAVE_PATH, 'wb') as f:\n\t\t\tpickle.dump(self.vocabulary, f, pickle.HIGHEST_PROTOCOL)\n\n\tdef initFilesAndFolders(self):\n\t\t\"\"\"\n\t\tGiven the initial configurations, initialize the files and folders needed for this class to work.\n\t\t:return:\n\t\t\"\"\"\n\t\tif not os.path.exists(self.config.GRAPH_PATH):\n\t\t\tos.makedirs(self.config.GRAPH_PATH)\n\n\t\tdictPath = self.config.VOCABULARY_SAVE_PATH.split('/')\n\t\tif not os.path.exists(dictPath[0]):\n\t\t\tos.makedirs(dictPath[0])\n\n\tdef text2Graph(self, text, docIdx=1):\n\t\t\"\"\"\n\n\t\t:param text: string of text to convert to edges list\n\t\t:param docIdx: the index of the current document\n\t\t:return: pandas DataFrame of the edges of the given text, where each row is of the format\n\t\tfrom (id), to (id), doc (index)\n\t\t\"\"\"\n\t\twordsArray = nltk.word_tokenize(text)\n\n\t\tif len(wordsArray) < 2:\n\t\t\treturn None\n\n\t\twordsArray = [self.cleanToken(w) for w in wordsArray]\n\t\tedgesList = np.zeros( (len(wordsArray)-1, 3) )\n\n\t\tedgesList[:, 0] = np.array([self.vocabulary[ wordsArray[i] ] for i in range(len(wordsArray)-1)])\n\t\tedgesList[:, 1] = np.array([self.vocabulary[wordsArray[i]] for i in range(1, len(wordsArray))])\n\t\tedgesList[:, 2] = docIdx * np.ones((len(wordsArray)-1,))\n\t\t# w1 = self.vocabulary[wordsArray[0]]\n\t\t# for i in range(1,len(wordsArray)):\n\t\t# \t#\tcreate a row with the ids of the 2 words as from,to + the doc idx:\n\t\t# \tw2 = self.vocabulary[ wordsArray[i] ]\n\t\t# \tedge = [w1, w2, docIdx]\n\t\t# \tedgesList[i-1,:] = np.array(edge)\n\t\t# \tw1 = w2\n\t\tedgesList = pd.DataFrame(edgesList, columns=self.config.RELATIONSHIPS_HEADER)\n\t\tedgesList.drop_duplicates(inplace=True)\n\t\treturn edgesList\n\n\tdef buildVocabularyFromCorpus(self, corpusFilePath, verbose=False):\n\t\t\"\"\"\n\t\tGiven the path to the corpus, build a vocabulary of all words in the corpus.\n\t\tThis is done by first tokenizing the text and then using the Dictionary from gensim.\n\t\t:param corpusFilePath:\n\t\t:param verbose:\n\t\t:return:\n\t\t\"\"\"\n\t\t#\tFirst, tokenize the corpus:\n\n\t\tlineNum = 0\n\t\tfor line in smart_open.smart_open(corpusFilePath):\n\t\t\tlineNum += 1\n\t\t\tarticle = json.loads(line)\n\t\t\tif not lineNum % 10000:\n\t\t\t\tself.saveVocabulary()\n\t\t\t\tif verbose:\n\t\t\t\t\tprint(\"Processed {} articles. Current article:\".format(lineNum))\n\t\t\t\t\tprint(\"Article title: %s\" % article['title'])\n\t\t\tself.addDocsToVocabulary([nltk.word_tokenize(article['title'])])\n\t\t\tfor section_title, section_text in zip(article['section_titles'], article['section_texts']):\n\t\t\t\tself.addDocsToVocabulary([nltk.word_tokenize(section_title), nltk.word_tokenize(section_text)])\n\n\t\t\t#\tFor now, for debugging use small portion of the corpus\n\t\t\tif self.config.DEBUG and lineNum > self.config.DEBUG_CORPUS_PORTION:\n\t\t\t\tbreak\n\n\t\tself.saveVocabulary()\n\n\tdef addDocsToVocabulary(self, docs):\n\t\t\"\"\"\n\t\tInsert all tokens in all given documents to the vocabulary.\n\t\t:param docs: A list of document, where each document is a list of tokens.\n\t\t:return:\n\t\t\"\"\"\n\t\tfor doc in docs:\n\t\t\tfor token in doc:\n\t\t\t\ttoken = self.cleanToken(token)\n\t\t\t\tif token not in self.vocabulary:\n\t\t\t\t\tself.vocabulary[token] = len(self.vocabulary)\n\n\tdef cleanToken(self, token):\n\t\t\"\"\"\n\t\tClean specific stuff known in this wikipedia corpus. such as '====' at beginning or end of sentences etc.\n\t\t\"\"\"\n\t\treturn self.strip_string(token, \"====\")\n\n\t@staticmethod\n\tdef strip_string(string, to_strip):\n\t\t#\ttaken from https://stackoverflow.com/questions/15870053/strip-an-ordered-sequence-of-characters-from-a-string\n\t\tif to_strip:\n\t\t\twhile string.startswith(to_strip):\n\t\t\t\tstring = string[len(to_strip):]\n\t\t\twhile string.endswith(to_strip):\n\t\t\t\tstring = string[:-len(to_strip)]\n\t\treturn string\n\n\tdef exportGraphVertices(self):\n\t\t\"\"\"\n\t\tUse the vocabulary (Dictionary) to extract all unique words, and construct a new .csv file\n\t\t that will define the vertices of the graph. Each unique word will be a vertex.\n\t\tTHIS ASSUMES THE VOCABULARY IS FILLED.\n\t\t:return:\n\t\t\"\"\"\n\t\twith open(self.config.GRAPH_PATH + self.config.NODES_FILENAME, 'w', encoding='utf-8') as csvFile:\n\t\t\twriter = csv.writer(csvFile)\n\n\t\t\t#\twrite the header first:\n\t\t\twriter.writerow(self.config.NODES_HEADER)\n\n\t\t\t#\twrite the nodes:\n\t\t\tfor word, wordId in self.vocabulary.items():\n\t\t\t\t#\tadd the current word to the graph:\n\t\t\t\twriter.writerow([word, wordId])\n\n\tdef exportGraphEdges(self, corpusFilePath, verbose=False):\n\t\t\"\"\"\n\t\tRead the corpus and set edges between relevant vertices.\n\t\t:param corpusFilePath: path to the corpus file.\n\t\t:param verbose:\n\t\t:return:\n\t\t\"\"\"\n\t\t#\tStart a .csv file with header:\n\t\theader = self.config.RELATIONSHIPS_HEADER\n\t\tedgesList = pd.DataFrame(columns=header)\n\t\t# with open(self.config.GRAPH_PATH + self.config.NODES_FILENAME, 'w', encoding='utf-8') as csvFile:\n\t\t# \twriter = csv.writer(csvFile)\n\t\t# \twriter.writerow(header)\n\n\t\tdocNum = 0\n\t\tfor line in smart_open.smart_open(corpusFilePath):\n\t\t\tdocNum += 1\n\t\t\tarticle = json.loads(line)\n\t\t\tif not docNum % 10000:\n\t\t\t\tedgesList.to_csv(index=False, path_or_buf=self.config.GRAPH_PATH + self.config.RELATIONSHIPS_FILENAME)\n\t\t\t\tif verbose:\n\t\t\t\t\tprint(\"Processed {} articles. Current article:\".format(docNum))\n\t\t\t\t\tprint(\"Article title: %s\" % article['title'])\n\t\t\ttitle2graph = self.text2Graph(article['title'], docNum)\n\t\t\tif title2graph is not None:\n\t\t\t\tedgesList = pd.concat([edgesList, title2graph])\n\t\t\tfor section_title, section_text in zip(article['section_titles'], article['section_texts']):\n\t\t\t\tsecTitle2graph = self.text2Graph(section_title, docNum)\n\t\t\t\tif secTitle2graph is not None:\n\t\t\t\t\tedgesList = pd.concat([edgesList, secTitle2graph ])\n\t\t\t\tedgesList = pd.concat([edgesList, self.text2Graph(section_text, docNum) ])\n\t\t\t\tpd.DataFrame.drop_duplicates(edgesList, inplace=True)\n\n\t\t\t#\tFor now, for debugging use small portion of the corpus\n\t\t\tif self.config.DEBUG and docNum > self.config.DEBUG_CORPUS_PORTION:\n\t\t\t\tbreak\n\n\t\tedgesList.to_csv(index=False, path_or_buf=self.config.GRAPH_PATH + self.config.RELATIONSHIPS_FILENAME)\n\n\tdef buildGraphFromCorpus(self, corpusFilePath):\n\t\t\"\"\"\n\t\tBuilds the Neo4j graph from the corpus.\n\t\t* Currently the corpus is assumed to be processed wiki dump.\n\t\t* You have to build the vocabulary prior to this method call.\n\n\t\t*\tAfter using this method you will get 2 .csv files. you need to copy them to the '/import' folder of Neo4j\n\t\tand run a Cypher query to insert the data. I will add here the query also (example):\n\t\tFor the Nodes:\n\t\tUSING PERIODIC COMMIT\n\t\tLOAD CSV WITH HEADERS FROM 'file:///nodes.csv' AS line CREATE (:Word {content:line.content})\n\n\t\tFor the Relationships:\n\t\tUSING PERIODIC COMMIT\n\t\tLOAD CSV WITH HEADERS FROM 'file:///relationships.csv' AS line MATCH (w1:Word {id:line.from}), (w2:Word {id:line.to})\n\t\tMERGE (w1)-(l:NextWord {doc:line.doc})->(w2)\n\n\n\t\t:param corpusFilePath:\n\t\t:return:\n\t\t\"\"\"\n\t\tself.exportGraphVertices()\n\t\tself.exportGraphEdges(corpusFilePath)\n\n\n\nif __name__ == '__main__':\n\tgraph = Graph(\"http://127.0.0.1:7474/\", password='7890')\n\t# res = pd.DataFrame(graph.data(\"MATCH (w:Word) return w\"))\n\t# print(res)\n\n\ttext1 = \"The cat is fat.\"\n\ttext2 = \"A cat is fat.\"\n\n\tt2n = Text2Neo4j(DBInfo(\"http://127.0.0.1:7474/\", \"7890\"))\n\tt2n.text2Graph(text1)\n\tt2n.text2Graph(text2)\n\n\n\n","sub_path":"Text2Neo4j.py","file_name":"Text2Neo4j.py","file_ext":"py","file_size_in_byte":8554,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"562872754","text":"# James Cooper, October 15 2018, Dice Race Game\r\nimport random # Import random module\r\nimport time # Import time module\r\n\r\nalt = 0 # Initiating alt to the value of 0\r\nx = 1 # Initiating x to the value of 1\r\n\r\nps1 = [] # Creation of list for Player 1 scores for each time the whole loop runs\r\nps2 = [] # Creation of list for Player 2 scores for each time the whole loop runs\r\n\r\nwhile x <= 6: # While loop for while x is less than or equal to 6\r\n alt = (alt + 1) % 2 # Function whos result will alternate between 1 and 0 everytime the loop is ran\r\n x = x + 1 # Adds 1 to x everytime the loop runs\r\n if alt == 1: # If statement if variable 'alt' is equal to 0\r\n num1 = random.randint(1,6) # Variable for random number from 1 to 6\r\n print(\"Player 1\") # Prints statement for who is rolling\r\n print(\"The die rolled to\", num1) # Print statement for the random integer of 'num1'\r\n ps1.append(num1) # Adds integer to 'ps1' list\r\n ps1f = sum(ps1) # Assigning variable to sum of all values in 'ps1' list\r\n print(ps1f, \"is your new score\") # Print statement for the current sum of 'ps1' list\r\n print(\"\") # Print blank line for spacing\r\n time.sleep(2)\r\n if alt == 0: # If statement if variable 'alt' is equal to 0\r\n num2 = random.randint(1,6) # Variable for random number from 1 to 6\r\n print(\"Player 2\") # Print statement for who is rolling\r\n print(\"The die rolled to\", num2) # Print statement for the random integer of 'num2'\r\n ps2.append(num2) # Adds integer to 'ps2' list\r\n ps2f = sum(ps2) # Assigning variable to sum of all values in 'ps2' list\r\n print(ps2f, \"is your new score\") # Print statement for the current sum of 'ps2' list\r\n print(\"\") # Print blank line for spacing\r\n time.sleep(2)\r\n\r\ns1 = sum(ps1) # Assigning variable to the sum of all values in 'ps1' list\r\ns2 = sum(ps2) # Assigning variable to the sum of all values in 'ps2' list\r\n\r\nif s1 > s2: # If statement if variable 's1' is greater than 's2'\r\n print(\"Player 1 won the game!\", '\\n') # If statement if variable 's1' is greater than 's2'\r\nif s1 < s2: # If statement for if variable 's1' is less than 's2'\r\n print(\"Player 2 won the game!\",'\\n') # Print statement if variabele 's1' is less than 's2'\r\nif s1 == s2: # If statement for if variable 's1' and 's2' are equal\r\n print(\"The game was a tie!\", '\\n') # Print statement if variable 's1' and 's2' are equal\r\n\r\nprint(\"Player 1 final score:\", s1) # Print statement of player 1's final score \r\nprint(\"Player 2 final score:\", s2) # Print statement of player 2's final score\r\n","sub_path":"Cooper_James_DiceRaceGame.py","file_name":"Cooper_James_DiceRaceGame.py","file_ext":"py","file_size_in_byte":2612,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"225638203","text":"from mltoolbox.draw import scatter\nimport matplotlib.pyplot as plt\nimport pytest\nimport numpy as np\n\n\ntest = [\n ([1], [1], [1], None, None, None),\n ([1, 1], [2, 2], [3, 3], None, None, None),\n (np.random.rand(1, 20), np.random.rand(1, 20), np.random.rand(1, 20), None, None, None),\n ([1], [1], [1], lambda x, y: x*y, np.arange(0, 10, .1), np.arange(0, 10, .1)),\n ([1, 1], [2, 2], [3, 3], lambda x, y: x**2 * y**2, np.arange(0, 10, .1), np.arange(0, 10, .1)),\n]\n@pytest.mark.parametrize(\"raw_x, raw_y, raw_z, equation, x, y\", test)\ndef test_matlib_3d(raw_x, raw_y, raw_z, equation, x, y):\n scatter.matlib_3d(raw_x, raw_y, raw_z, equation, x, y)\n plt.show()\n","sub_path":"mltoolbox/test/draw/test_scatter.py","file_name":"test_scatter.py","file_ext":"py","file_size_in_byte":677,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"154736112","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n# Time : 18/1/22 下午4:01\n# Author : Shi Bo\n# Email : pkushibo@pku.edu.cn\n# File : note_04.py\n\nimport tensorflow as tf\n\nBATCH_SIZE = 32\nVOCAB_SIZE = 1000\nEMBED_SIZE = 100\nNUM_SAMPLED = 10\nLEARNING_RATE = 0.001\n\ncenter_words = tf.placeholder(tf.int32, shape=[BATCH_SIZE])\ntarget_words = tf.placeholder(tf.int32, shape=[BATCH_SIZE])\n\nembed_matrix = tf.Variable(tf.random_uniform([VOCAB_SIZE, EMBED_SIZE], - 1.0, 1.0))\n\nembed = tf.nn.embedding_lookup(embed_matrix, center_words)\n\nnce_weight = tf.Variable(tf.truncated_normal([VOCAB_SIZE, EMBED_SIZE], stddev=1.0 / EMBED_SIZE ** 0.5))\nnce_bias = tf.Variable(tf.zeros([VOCAB_SIZE]))\n\nloss = tf.reduce_mean(\n tf.nn.nce_loss(weights=nce_weight, biases=nce_bias, labels=target_words, inputs=embed,\n num_sampled=NUM_SAMPLED, num_classes=VOCAB_SIZE))\n\noptimizer = tf.train.GradientDescentOptimizer(LEARNING_RATE).minimize(loss)\n","sub_path":"2017/note_04.py","file_name":"note_04.py","file_ext":"py","file_size_in_byte":947,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"192143986","text":"import cv2\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n# pic_path = './jian.png'\npic_path = './ce.png'\n# pic_path = './liang.png'\n\nimg = cv2.imread(pic_path, 0)\nhist = cv2.calcHist([img], [0], None, [256], [0, 256])\nplt.subplot(121)\nplt.imshow(img, 'gray')\nplt.xticks([])\nplt.yticks([])\nplt.title(\"Original\")\nplt.subplot(122)\nplt.hist(img.ravel(), 256, [0, 256])\nplt.show()","sub_path":"src/7.py","file_name":"7.py","file_ext":"py","file_size_in_byte":381,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"28462856","text":"\n# solution will return the parent of Q nodes in \n# a post order traveral binary search tree containg \n# nodes Q given hieght H\n \n#print(solution11([1, 2, 2, 3, 3, 3, 4, 5, 5,5], 2))\n# Python implementation to find the\n# parent of the given node\n\nimport math\n# Function to find the parent\n# of the given node\ndef solution(H, Q):\n out=[]\n for converter in Q:\n out.append(findParent(H,converter))\n return out\n \ndef findParent(height, node):\n\n\tstart = 1\n\tend = pow(2, height) - 1\n\n\t# Check whether the given node\n\t# is a root node.if it is then\n\t# return -1 because root\n\t# node has no parent\n\tif (end == node):\n\t\treturn -1\n\n\t# Loop till we found\n\t# the given node\n\twhile(node >= 1):\n\n\t\tend = end - 1\n\n\t\t# Find the middle node of the\n\t\t# tree because at every level\n\t\t# tree parent is divided\n\t\t# into two halves\n\t\tmid = start + (end - start)//2\n\n\t\t# if the node is found\n\t\t# return the parent\n\t\t# always the child nodes of every\n\t\t# node is node / 2 or (node-1)\n\t\tif(mid == node or end == node):\n\t\t\treturn (end + 1)\n\t\t\n\t\t# if the node to be found is greater\n\t\t# than the mid search for left\n\t\t# subtree else search in right subtree\n\t\telif (node < mid):\n\t\t\tend = mid\n\n\t\telse:\n\t\t\tstart = mid\n\nprint(solution(5,[19,14,28]))","sub_path":"Attempt3/lvl2a3.py","file_name":"lvl2a3.py","file_ext":"py","file_size_in_byte":1254,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"190291103","text":"#!/usr/bin/python3\nfrom sys import stderr, exc_info\n\n\ndef safe_print_integer_err(value):\n try:\n print(\"{:d}\".format(value))\n return True\n except:\n stderr.write(\"Exception: %s\\n\" % exc_info()[1])\n return False\n","sub_path":"0x05-python-exceptions/100-safe_print_integer_err.py","file_name":"100-safe_print_integer_err.py","file_ext":"py","file_size_in_byte":243,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"540248542","text":"import librosa\nimport librosa.display\nimport matplotlib.pyplot as plt\nimport tensorflow as tf\nimport numpy as np\nimport pandas as pd\n\n\ndef load_data(parent_dir, file_title, train_folds, dev_folds, test_folds):\n train_set = []\n dev_set = []\n test_set = []\n \n for i in train_folds:\n ds_filename = parent_dir + file_title + str(i)+\".csv\"\n df = pd.read_csv(ds_filename, index_col = None)\n train_set.append(df)\n \n for i in dev_folds:\n ds_filename = parent_dir + file_title + str(i)+\".csv\"\n df = pd.read_csv(ds_filename, index_col = None)\n dev_set.append(df)\n \n for i in test_folds:\n ds_filename = parent_dir + file_title + str(i)+\".csv\"\n df = pd.read_csv(ds_filename, index_col = None)\n test_set.append(df)\n \n print(\"done!\") \n return pd.concat(train_set, ignore_index=True), pd.concat(dev_set, ignore_index=True), pd.concat(test_set, ignore_index=True) \n\n\ndef one_hot_encode(labels):\n n_labels = len(labels)\n n_unique_labels = len(np.unique(labels))\n one_hot_encode = np.zeros((n_labels,n_unique_labels))\n one_hot_encode[np.arange(n_labels), labels] = 1\n return one_hot_encode\n","sub_path":"Data_Processing.py","file_name":"Data_Processing.py","file_ext":"py","file_size_in_byte":1203,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"405055988","text":"import numpy as np\nimport NeuralNet\nimport LoadData\n\ndata = LoadData.LoadData(X_labels='samples/train-labels-idx1-ubyte',\n X_images='samples/train-images-idx3-ubyte',\n Y_labels='samples/t10k-labels-idx1-ubyte',\n Y_images='samples/t10k-images-idx3-ubyte') # Load the data\nX_labels, X_images = data.get_train_data()\nX_images = data.preprocess(X_images)\n\nneural = NeuralNet.NeuralNet()\n\nfor i in range(0, 10000):\n if i % 500 == 0:\n print(i)\n # Initialize Y to a vector of 1s\n Y = np.zeros(10)\n Y[X_labels[i]] = 1.0\n\n neural.set_Y(Y)\n neural.set_X(X_images[i])\n neural.forward()\n neural.back_propagate()\n\nY_labels, Y_images = data.get_test_data()\nY_images = data.preprocess(Y_images)\n\ncount = 0\nfor i in range(0, 10000):\n if i % 500 == 0:\n print(i)\n # Initialize Y to a vector of 1s\n Y = np.zeros(10)\n Y[Y_labels[i]] = 1.0\n\n neural.set_Y(Y)\n neural.set_X(Y_images[i])\n neural.forward()\n if neural.get_results() == Y_labels[i]:\n count += 1\nprint(count)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1090,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"376423985","text":"\nfrom django.urls import path, reverse\nfrom django.conf.urls import url\nfrom .views import *\n#compareOutputView\napp_name = 'QRvisualisation'\n\nurlpatterns = [\n path('', index, name = 'index'),\n path('output/', output_visualisation, name = 'outputview'),\n path('form/', FormView.as_view(), name = 'formview'),\n path('output_maintenance/', output_visualisation_2 , name = 'outputview_2'),\n path('C139_analysis/', descriptive_stats_marcus, name = 'descriptive_stats_marcus'),\n path('WO_prediction/', descriptive_stats_jj, name = 'descriptive_stats_jj'),\n path('WO_by_quarter/', descriptive_stats_rahul, name = 'descriptive_stats_rahul'),\n path('output_trc/', output_trc_vis, name = 'output_trc_vis'),\n path('form_maintenance_zonal/', FormViewMaintenanceZonal.as_view(), name = 'formview_maintenance_zonal'),\n path('output_maintenance_zonal/', output_visualisation_maintenance_zonal, name = 'outputview_maintenance_zonal'),\n\n]\n\n## path('desired path', view class, name of view)\n","sub_path":"DVA/CODE/src/QRDVA/QRvisualisation/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1004,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"618622320","text":"import pygame\npygame.init() \n\n#Create variables for storing car x and y location\ncarx=130\ncary=500\n#create background variable\nbgy=0\n\nscreen = pygame.display.set_mode((600,600))\npygame.display.set_caption(\" Racing Game\")\ncarryOn = True\nwhile carryOn:\n for event in pygame.event.get(): \n if event.type == pygame.QUIT: \n carryOn = False\n \n #Change location of background image according to the absolute path you have got in your computer\n bgImg_location= \"C:/Users/dell/Documents/img/back_ground.jpg\" \n \n bgImg=pygame.image.load(bgImg_location).convert_alpha()\n bgImg_scaled=pygame.transform.smoothscale(bgImg,(600,800))\n screen.blit(bgImg_scaled,[0,0])\n \n #Change location of background image according to the absolute path you have got in your computer\n carImg_location=\"C:/Users/dell/Documents/img/car.png\"\n \n carImg=pygame.image.load(carImg_location).convert_alpha()\n #Encode for user input\n if event.type==pygame.KEYDOWN:\n if event.key==pygame.K_UP:\n cary-=2\n bgy-=1\n if event.key==pygame.K_DOWN:\n cary+=2\n bgy+=2\n if event.key==pygame.K_LEFT:\n carx-=10\n if event.key==pygame.K_RIGHT:\n carx+=10\n \n #Enter code for enter key here\n if event.key==pygame.K_RETURN:\n\t cary-=10\n \n \n \n screen.blit(carImg,[carx,cary])\n #reset car and screen\n #Check if \"cary\" is close to upper boundary\n if cary<=20:\n #Chnage background y location\n bgy=0\n #Reset \"cary\"\n cary=500\n\n pygame.display.flip()\n \npygame.quit()\n","sub_path":"SA1Solution.py","file_name":"SA1Solution.py","file_ext":"py","file_size_in_byte":1630,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"226227431","text":"# 写函数(类似的还有对象和模块)\ndef func1():\n print('Hello, Jade~')\n\n\ndef func2(a):\n \"\"\"这是函数文档:不会被打印。\"\"\"\n print('传递进来的' + str(a) + '是这个函数的参数')\n if a == 1:\n print('num=1')\n elif a == 2:\n print('num=2')\n else:\n print('num=other')\n\n\ndef SaySome(name, word):\n print(name + '->' + word)\n\n\ndef Collect(*par1):\n print('参数的长度是:', len(par1))\n print('第二个参数是:', par1[1])\n\n\ndef FuncBack():\n return [1, 2, 3, 'Daniel']\n\n\ndef func3(a, b):\n global gm\n c = a + b\n # print('m='+str(m))\n m = 50\n gm = m\n print('修改后的m值为', m)\n return c\n\n\nfunc1()\nfunc2(3)\nprint(func2.__doc__)\nprint.__doc__\nm = 1\ngm = 1\n# 关键字调用\nSaySome('Daniel', 'Jade')\nSaySome('Jade', 'Daniel')\nSaySome(name='Daniel', word='Jade')\n# 收集参数\nCollect(1, 'Daniel', 2)\n# 函数多个返回值\nprint(FuncBack())\n# 变量的作用域\nc_out = func3(1, 2)\nprint('c_out=' + str(c_out))\nprint('修改后的m值在外面为', m)\nprint('修改后的gm值在外面为', gm)\n\n\n# 闭包一种编程范式\ndef fun4(a):\n def fun5(b):\n return a - b\n\n return fun5\n\n\nprint(fun4(3)(5))\nprint(fun4(5)(3))\n\n\ndef fun6():\n a = 5\n\n def fun7():\n nonlocal a\n a *= a\n return a\n\n return fun7()\n\n\nprint(fun6())\n","sub_path":"function_1.py","file_name":"function_1.py","file_ext":"py","file_size_in_byte":1364,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"212809319","text":"import logging\nimport numpy as np\n\nfrom art.attacks.evasion import AdversarialTexturePyTorch\n\nlogger = logging.getLogger(__name__)\n\n\nclass AdversarialPhysicalTexture(AdversarialTexturePyTorch):\n \"\"\"\n ART's AdversarialTexturePytorch with overriden generate()\n \"\"\"\n\n def __init__(self, estimator, **kwargs):\n self.attack_kwargs = kwargs\n super(AdversarialTexturePyTorch, self).__init__(estimator=estimator)\n\n def generate(self, x, y, y_patch_metadata=None, **kwargs):\n \"\"\"\n :param x: Sample videos with shape (NFHWC)\n :param y: True labels of format `List[Dict[str, np.ndarray]]`, one dictionary for each input video. The keys of\n the dictionary are:\n - boxes [N_FRAMES, 4]: the boxes in [x1, y1, x2, y2] format, with 0 <= x1 < x2 <= W and\n 0 <= y1 < y2 <= H.\n :param y_patch_metadata: Metadata of the green screen patch of format `List[Dict[str, np.ndarray]]`. The keys of\n the dictionary are:\n - gs_coords: the coordinates of the patch in [top_left, top_right, bottom_right, bottom_left] format\n - cc_ground_truth: ground truth color information stored as np.ndarray with shape (24,3)\n - cc_scene: scene color information stored as np.ndarray with shape (24,3)\n - masks: binarized masks of the patch, where masks[n,x,y] == 1 means patch pixel in frame n and at position (x,y)\n :Keyword Arguments:\n * *shuffle* (``np.ndarray``) --\n Shuffle order of samples, labels, initial boxes, and foregrounds for texture generation.\n * *y_init* (``np.ndarray``) --\n Initial boxes around object to be tracked of shape (nb_samples, 4) with second dimension representing\n [x1, y1, x2, y2] with 0 <= x1 < x2 <= W and 0 <= y1 < y2 <= H.\n * *foreground* (``np.ndarray``) --\n Foreground masks of shape NFHWC of boolean values with False/0.0 representing foreground, preventing\n updates to the texture, and True/1.0 for background, allowing updates to the texture.\n :return: An array with adversarial patch and an array of the patch mask.\n \"\"\"\n\n if x.shape[0] > 1:\n raise ValueError(\"batch size must be 1\")\n\n # green screen coordinates used for placement of a rectangular patch\n gs_coords = y_patch_metadata[0][\"gs_coords\"]\n patch_width = int(np.max(gs_coords[:, 0]) - np.min(gs_coords[:, 0]))\n patch_height = int(np.max(gs_coords[:, 1]) - np.min(gs_coords[:, 1]))\n\n x_min = int(np.min(gs_coords[:, 1]))\n y_min = int(np.min(gs_coords[:, 0]))\n\n attack = AdversarialTexturePyTorch(\n self.estimator,\n patch_height=patch_height,\n patch_width=patch_width,\n x_min=x_min,\n y_min=y_min,\n **self.attack_kwargs\n )\n\n # this masked to embed patch into the background in the event of occlusion\n foreground = y_patch_metadata[0][\"masks\"]\n foreground = np.array([foreground])\n\n generate_kwargs = {\n \"y_init\": y[0][\"boxes\"][0:1],\n \"foreground\": foreground,\n \"shuffle\": kwargs.get(\"shuffle\", False),\n }\n generate_kwargs = {**generate_kwargs, **kwargs}\n attacked_video = attack.generate(x, y, **generate_kwargs)\n return attacked_video\n","sub_path":"armory/art_experimental/attacks/carla_adversarial_texture.py","file_name":"carla_adversarial_texture.py","file_ext":"py","file_size_in_byte":3460,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"529147572","text":"import sys\nimport os\nimport csv\n\n\nclass CarBase:\n def __init__(self, brand, photo_file_name, carrying, car_type):\n self.brand = brand\n self.photo_file_name = photo_file_name\n self.carrying = carrying\n self.car_type = car_type\n\n def get_photo_file(self):\n ext = os.path.splitext(self.photo_file_name)\n return ext[1]\n\n\nclass Car(CarBase):\n def __init__(self, brand, photo_file_name, carrying, passenger_seats_count, car_type='car'):\n super(Car, self).__init__(brand, photo_file_name, carrying, car_type)\n self.passenger_seats_count = passenger_seats_count\n\n\nclass Truck(CarBase):\n def __init__(self, brand, photo_file_name, carrying, body_whl=0.0, car_type='truck', body_width=0.0, body_height=0.0, body_length=0.0):\n super().__init__(brand, photo_file_name, carrying, car_type)\n self.body_whl = body_whl\n self.car_type = car_type\n self.body_width = body_width\n self.body_height = body_height\n self.body_length = body_length\n if len(body_whl) > 2:\n nlst = self.body_whl.split(sep='x')\n self.body_width = float(nlst[1])\n self.body_height = float(nlst[2])\n self.body_length = float(nlst[0])\n else:\n self.body_whl = 0.0\n self.body_width = 0.0\n self.body_height = 0.0\n self.body_length = 0.0\n\n\n\n\n def get_body_volume(self):\n lst = self.body_whl.split(sep='x')\n mult = 1\n for i in lst:\n mult = mult*int(i)\n return mult\n\n\nclass SpecMachine(CarBase):\n def __init__(self, brand, photo_file_name, carrying, extra, car_type='spec_machine'):\n super().__init__(brand, photo_file_name, carrying, car_type)\n self.extra = extra\n\n\nclass MyDialect(csv.Dialect):\n delimiter = ';'\n skipinitialspace = True\n quoting = csv.QUOTE_MINIMAL\n doublequote = False\n lineterminator = '\\n'\n quotechar = ' '\n\n\ndef get_car_list(csv_filename):\n object_list = []\n with open(csv_filename, encoding='utf-8') as f:\n reader = csv.reader(f, delimiter = ';')\n next(reader)\n for row in reader:\n if len(row) > 6:\n #print(row)\n make_object(row)\n try:\n object_list.append(make_object(row).__dict__)\n except:\n pass\n return object_list\n\n\ndef make_object(lst):\n for atrr in lst:\n if atrr == 'car':\n c = Car(lst[1], lst[3], float(lst[5]), int(lst[2]))\n return c\n elif atrr == 'truck':\n if len(lst[4]) > 2:\n t = Truck(lst[1], lst[3], float(lst[5]), lst[4])\n #print(dir(t))\n return t\n else:\n t = Truck(lst[1], lst[3], float(lst[5]), lst[4])\n return t\n elif atrr == 'spec_machine':\n s = SpecMachine(lst[1], lst[3], float(lst[5]), lst[6])\n return s\n else:\n pass\n\nif __name__ == '__main__':\n csv_filename = 'coursera_week3_cars.csv'\n get_car_list(csv_filename)\n print(get_car_list(csv_filename))\n","sub_path":"get_car_list .py","file_name":"get_car_list .py","file_ext":"py","file_size_in_byte":3161,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"271518024","text":"#!/usr/bin/python3\nimport re\nimport nltk\nimport sys\nimport getopt\nimport math\nimport functools\nimport _pickle as pickle\nfrom nltk import ngrams\nfrom nltk.corpus import wordnet as wn\nfrom data import set_postings_file, read_dict, get_corpus_size, get_doc_id_len_pairs, get_postings_list, get_doc_ids, get_doc_freq, get_main_posting_list\n\nRELEVANT = {}\n\ndef get_rel_terms():\n '''\n Retrieves relevant terms for each document from indexing stage\n '''\n f = open('rel.txt', 'rb')\n unpickler = pickle.Unpickler(f)\n while True:\n try:\n entry = unpickler.load()\n doc_id = entry[0]\n terms = entry[1]\n RELEVANT[int(doc_id)] = terms\n except EOFError:\n break\n\ndef usage():\n print(\"usage: \" + sys.argv[0] + \" -d dictionary-file -p postings-file -q file-of-queries -o output-file-of-results\")\n\n\ndef run_search(dict_file, postings_file, queries_file, results_file):\n '''\n Uses the given dictionary file and postings file\n to perform searching on the given queries file and\n output the results to a file\n '''\n print('running search on the queries...')\n set_postings_file(postings_file)\n read_dict(dict_file) # read from dictionary file and store in memory\n\n rf = open(results_file, 'w+', encoding=\"utf-8\")\n rf.write('')\n rf.close()\n\n queries = open(queries_file, 'r', encoding=\"utf-8\")\n lines = queries.readlines()\n query = ''\n rel_docs = []\n for i in range(len(lines)):\n if i == 0:\n query = lines[i].rstrip()\n else:\n rel_docs.append(int(lines[i]))\n\n rf = open(results_file, 'a', encoding=\"utf-8\")\n query_terms = parse_query(query)\n\n expand_query_terms = query_expand(query_terms)\n \n get_rel_terms()\n for rel_doc in rel_docs:\n try:\n # the important terms from each relevant doc are placed in one segment together\n expand_query_terms.append(RELEVANT[rel_doc])\n except KeyError: # doc is not found in relevant term dictionary\n continue\n \n query_terms_counts = counter(expand_query_terms)\n doc_scores = calculate_cosine_scores(expand_query_terms, query_terms_counts)\n result_docs = [k for k, v in sorted(doc_scores.items(), key=lambda item: (-item[1], item[0]))]\n\n for i in range(len(result_docs)):\n if i == len(result_docs) - 1:\n rf.write(str(result_docs[i]))\n else:\n rf.write(str(result_docs[i]) + ' ')\n\n rf.close()\n\n\ndef parse_query(query):\n '''\n Example - Query: 'what is \"fertility treatment\" AND damages'\n Output - [['what', 'is', 'fertility_treatment'], ['damages']]\n '''\n parsed_terms = []\n query_terms = [term.split(' ') for term in query.split(' AND ')]\n is_quote = False\n for segment in query_terms:\n segment_terms = []\n quote = \"\"\n for i in range(len(segment)):\n if segment[i].startswith('\"') and segment[i].endswith('\"'):\n segment_terms.append(segment[i].strip('\"'))\n elif segment[i].startswith('\"'):\n is_quote = True\n quote += segment[i].strip('\"') + \"_\"\n elif segment[i].endswith('\"'):\n is_quote = False\n quote += segment[i].strip('\"')\n segment_terms.append(quote)\n quote = \"\"\n elif not is_quote:\n segment_terms.append(segment[i])\n else:\n quote += segment[i] + \"_\"\n parsed_terms.append(segment_terms)\n\n return parsed_terms\n\n\ndef generate_syn(prev_value, next_value):\n '''\n Generates synonyms (a function use in reduce function in query_expand())\n '''\n name = next_value.name()\n if name not in prev_value:\n prev_value.append(name)\n return prev_value\n\n\ndef query_expand(parsed_terms):\n '''\n Add the synonyms of each term into the list for query expansion\n '''\n expanded_query_terms = []\n for segment in parsed_terms:\n segment_terms = []\n for term in segment:\n for syn in wn.synsets(term):\n lemma_arr = syn.lemmas()\n segment_terms = functools.reduce(generate_syn, lemma_arr, segment_terms)\n segment_terms += segment # concatenate original query terms\n expanded_query_terms.append(segment_terms)\n\n return expanded_query_terms\n\n\ndef calculate_tfidf_query(term, term_freq_in_query, corpus_size):\n '''\n Calculates the tf-idf (ltc) for a query\n '''\n if term_freq_in_query == 0:\n return 0\n doc_freq = get_doc_freq(term)\n if doc_freq == 0:\n return 0\n\n tf = 1 + math.log(term_freq_in_query, 10)\n idf = math.log(corpus_size / doc_freq, 10)\n return tf * idf\n\n\ndef calculate_tfidf_documents(zone):\n '''\n Calculates the tf-idf (lnc) for a document\n '''\n # title (0), content (1), date (2), court (3)\n alpha = [0.470588, 0.176471, 0.117647, 0.235294]\n result = 0\n for i in range(len(zone)):\n if zone[i] != 0:\n tf = 1 + math.log(zone[i], 10)\n result += alpha[i] * tf\n\n return result # idf not calculated for documents\n\n\ndef add_to_count(term, dictionary):\n '''\n Increases the query term frequency\n '''\n if term in dictionary:\n dictionary[term] += 1\n else:\n dictionary[term] = 1\n\n\ndef counter(query_terms):\n '''\n Returns the query term frequency (as a dictionary)\n '''\n count_dict = {}\n for segment in query_terms:\n for term in segment:\n split_term = term.split('_')\n if len(split_term) == 3:\n for item in list(ngrams(split_term, 2)):\n to_add = item[0] + '_' + item[1]\n add_to_count(to_add, count_dict)\n else:\n add_to_count(term, count_dict)\n return count_dict\n\n\ndef calculate_cosine_scores(query_terms, query_terms_counts):\n '''\n Returns a `scores` dictionary where the keys are doc IDs and the values are the cosine scores\n '''\n corpus_size = get_corpus_size()\n doc_id_len_pairs = get_doc_id_len_pairs()\n\n # retrieve all documents that fulfils the boolean requirement of query\n main_posting_list = get_main_posting_list(query_terms)\n scores = dict(zip(main_posting_list, [0] * len(main_posting_list)))\n\n # calculation\n for query_term in query_terms_counts:\n weight_tq = calculate_tfidf_query(query_term, query_terms_counts[query_term], corpus_size)\n current_posting_list = get_postings_list(query_term)\n for doc_id in main_posting_list:\n if doc_id in current_posting_list:\n scores[doc_id] += weight_tq * calculate_tfidf_documents(current_posting_list[doc_id])\n\n # normalize lengths\n for doc_id, score in scores.items():\n try:\n scores[doc_id] = score / doc_id_len_pairs[doc_id]\n except KeyError: # If document not found (unlikely)\n scores[doc_id] = 0\n\n return scores\n\n\ndictionary_file = postings_file = file_of_queries = output_file_of_results = None\n\ntry:\n opts, args = getopt.getopt(sys.argv[1:], 'd:p:q:o:')\nexcept getopt.GetoptError:\n usage()\n sys.exit(2)\n\nfor o, a in opts:\n if o == '-d':\n dictionary_file = a\n elif o == '-p':\n postings_file = a\n elif o == '-q':\n file_of_queries = a\n elif o == '-o':\n file_of_output = a\n else:\n assert False, \"unhandled option\"\n\nif dictionary_file == None or postings_file == None or file_of_queries == None or file_of_output == None :\n usage()\n sys.exit(2)\n\nrun_search(dictionary_file, postings_file, file_of_queries, file_of_output)\n","sub_path":"HW4/search.py","file_name":"search.py","file_ext":"py","file_size_in_byte":7640,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"613808086","text":"import argparse\r\nimport imutils\r\nimport cv2\r\nimport numpy as np\r\n\r\n# 创建参数解析器并解析参数\r\nap = argparse.ArgumentParser()\r\nap.add_argument(\"-v\", \"--video\", help=\"path to the video file\")\r\nap.add_argument(\"-a\", \"--min-area\", type=int, default=500, help=\"minimum area size\")\r\nargs = vars(ap.parse_args())\r\n\r\n# 读取视频文件\r\n# video = cv2.VideoCapture(\"C:\\\\Users\\\\panyi\\\\Desktop\\\\Work\\\\视频\\\\实验视频\\\\晴天背光 左上 慢速 标清.mp4\")\r\nvideo = cv2.VideoCapture(\"C:\\\\Users\\\\panyi\\\\Desktop\\\\Work\\\\视频\\\\原视频\\\\00000002704000000.mp4\")\r\n\r\n# 遍历视频的每一帧\r\nwhile True:\r\n\r\n # 获取当前帧并初始化状态信息\r\n ret, frame = video.read()\r\n\r\n # 视频播放完,循环播放\r\n if not ret:\r\n print('Video Replay')\r\n video.set(cv2.CAP_PROP_POS_FRAMES, 0)\r\n continue\r\n\r\n # 调整该帧的大小,转换为灰阶图像(并不需要高斯模糊)\r\n frame = imutils.resize(frame, width=500)\r\n gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\r\n # gray = cv2.GaussianBlur(gray, (21, 21), 0)\r\n\r\n # Shi-Tomasi角点检测\r\n corners = cv2.goodFeaturesToTrack(gray, 20, 0.01, 10)\r\n corners = np.int0(corners) # 20 个角点坐标\r\n\r\n for i in corners:\r\n # 压缩至一维:[[62, 64]] -> [62, 64]\r\n x, y = i.ravel()\r\n cv2.circle(frame, (x, y), 4, (0, 0, 255), -1)\r\n\r\n # 角点标记为红色并显示当前帧\r\n cv2.imshow('DST', frame)\r\n key = cv2.waitKey(1) & 0xFF\r\n\r\n# 清理摄像机资源\r\nvideo.release()\r\n","sub_path":"Shi-Tomasi.py","file_name":"Shi-Tomasi.py","file_ext":"py","file_size_in_byte":1535,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"590984945","text":"from django.shortcuts import render, get_object_or_404, redirect\nfrom accounts.models import UserProfile\nfrom django.views.generic import TemplateView\nfrom django.contrib.auth.models import User\nfrom django.contrib.auth.decorators import login_required\nfrom .forms import HomeForm\nfrom .models import Friend, Post\n\n# Create your views here.\n\n\n\nclass HomeView(TemplateView):\n template_name = 'vanta/home.html'\n def get(self,request):\n form = HomeForm()\n posts = Post.objects.all().order_by('-created')\n users = User.objects.exclude(id=request.user.id)\n friend = Friend.objects.get(current_user=request.user)\n friends = friend.users.all()\n args = {\n 'form': form, 'posts': posts, 'users': users, 'friends': friends\n }\n return render(request, self.template_name, args)\n def post(self,request):\n form = HomeForm(request.POST)\n if form.is_valid():\n post = form.save(commit = False)\n post.user =request.user\n post.save()\n text = form.cleaned_data['post']\n form = HomeForm()\n return redirect('animeweb:home')\n args = {'form':form,'text':text}\n return render(request, self.template_name, args)\n\n\n\n\n@login_required\ndef change_friends(request,operation,pk):\n friend = User.objects.get(pk=pk)\n if operation == 'add':\n Friend.make_friend(request.user,friend)\n elif operation == 'remove':\n Friend.lose_friend(request.user,friend)\n return redirect('animeweb:home')\n","sub_path":"mysite/animeweb/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1664,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"496576831","text":"import machine\nimport math\nimport network\nimport os\nimport time\nfrom machine import SD\nimport pycom\nfrom machine import Pin\nfrom machine import RTC\nimport gc\nimport ACC\nimport logging\nfrom math import floor, ceil\nimport socket_client\nimport ustruct\nimport dropfile\nfrom network import WLAN\nimport json\nimport diskutil\nimport pycom\nfrom kk_util import *\nimport gmail\nimport sys\nimport uerrno\n\n\niCAM = None\niACC = None\nlogger = None\nAP = None\nrtc = None\nsd = None\nT_exec = None\nT_meas = None\nT_now = None\nT_start = None\nX = None\nY = None\nZ = None\nrmsACC = None\nCTLR_IPADDRESS = None\nfilename = None\nopenSD = None\nlogfile = None\nlogfile_new = None\nwdt = None\nwdt_timeout = 90*60*1000\n\n# setup() state0\n# config() state1\n# measure() state2\n# deep_sleep() state3\n\ndef setup():\n global logger, rtc, sd, iCAM, iACC, CTLR_IPADDRESS, logfile, filename\n global wdt\n\n gc.enable()\n\n # HW Setup\n wdt = WDT(timeout=wdt_timeout)\n sd = SD()\n rtc = RTC()\n os.mount(sd,'/sd')\n\n # SYSTEM VARIABLES\n iCAM = pycom.nvs_get('iCAM') # pycom.nvs_set('iCAM',1)\n iACC = pycom.nvs_get('iACC') # pycom.nvs_set('iACC',1)\n\n logfile='/sd/log/{}.log'.format(datetime_string(time.time()))\n logging.basicConfig(level=logging.DEBUG,filename=logfile)\n logger = logging.getLogger(__name__)\n\n # NETWORK VARIABLES\n pbconf = pybytes.get_config()\n AP = pbconf['wifi']['ssid']\n if AP == 'wings':\n CTLR_IPADDRESS = '192.168.1.51'\n elif AP == 'RUT230_7714':\n CTLR_IPADDRESS = '192.168.1.100'\n # CONNECT TO AP\n wlan = WLAN(mode=WLAN.STA)\n while not wlan.isconnected():\n nets = wlan.scan()\n for net in nets:\n if net.ssid == 'RUT230_7714':\n pybytes.connect_wifi()\n # wlan.ifconfig(config=('192.168.1.100', '255.255.255.0', '192.168.1.1', '8.8.8.8'))\n # wlan.connect('RUT230_7714', auth=(WLAN.WPA2, 'Ei09UrDg'), timeout=5000)\n # while not wlan.isconnected():\n # machine.idle() # save power while waiting\n socket_client.CTLR_IPADDRESS = CTLR_IPADDRESS\n\n # GREETING\n logger.info('--------------------')\n logger.info(' Starting CAM{}-ACC{}'.format(iCAM, iACC))\n logger.info('--------------------')\n logger.info('AP={}'.format(AP))\n gc.collect()\n\n return\n\ndef config_measurement():\n #\n # GETTING TIME AND STATE OF CONTROLLER\n #\n global logger, rtc, sd, T_exec, T_meas, logfile_new\n logger.info('Config_measurement...')\n\n # GETTING STATE AND TIME FROM CTLR\n stateCTLR = None\n wdt = WDT(timeout=25*1000)\n while stateCTLR not in [2,4]:\n response = None\n while not response:\n requests = 'get,state;get,time;set,state{},1'.format(iACC)\n logger.info('sending request to CTLR: \"{}\"...'.format(requests))\n try:\n response = socket_client.request(requests)\n except:\n logger.exception('1st request failed.')\n # try:\n # response = socket_client.request(requests)\n # except OSError as exc:\n # # if exc.args[0] ==\n # pass\n # except:\n # raise\n time.sleep(1)\n response_list = response.split(';')\n stateCTLR = int(response_list[0])\n time_gps = int(response_list[1])\n rtc.init(time.localtime(time_gps))\n logger.info('stateCTLR = {} and time={}'.format(stateCTLR,rtc.now()))\n wdt.feed()\n wdt = WDT(timeout=wdt_timeout)\n\n # RENAME LOGFILE\n logfile_new = '/sd/log/{}.log'.format(datetime_string(time.time()))\n logging.fclose()\n os.rename(logfile,logfile_new)\n logging.basicConfig(level=logging.DEBUG,filename=logfile_new)\n\n if stateCTLR == 2:\n T_exec = 60*5\n T_meas = 20\n elif stateCTLR == 4:\n T_exec = 60*60\n T_meas = 60*3\n gc.collect()\n\n return\n\ndef measure():\n #\n # MEASURE\n #\n global T_meas, T_exec, T_now, T_start, X, Y, Z, rmsACC\n\n logger.info(\"Measuring ACC... \")\n ACC.setup()\n\n request = 'set,state{},2'.format(iACC)\n logger.info('sending request to the sever: \"{}\"'.format(request))\n response = socket_client.request(request)\n\n T_now = time.time()\n T_start = getNextGridTime(T_now+1, T_exec)\n logger.debug(\"T_cur={},{}\".format(T_now, datetime_string(T_now )))\n logger.debug(\"T_st ={},{}\".format(T_start,datetime_string(T_start)))\n logger.info(\"Waiting for {} seconds ...\".format(T_start - T_now))\n waitUntil(T_start)\n\n # MESURING\n pycom.heartbeat(False)\n pycom.rgbled(0x000F00)\n logger.info('starting measuring...')\n X,Y,Z,Xrms,Yrms,Zrms,Xavg,Yavg,Zavg = ACC.measure(Td=T_meas)\n rmsACC = (Xrms**2+Yrms**2+Zrms**2)**0.5\n logger.info('Avg(X,Y,Z)=(%f,%f,%f)',Xavg,Yavg,Zavg)\n logger.info('RMS(X,Y,Z)=(%f,%f,%f)',Xrms,Yrms,Zrms)\n pycom.rgbled(0x000000)\n time.sleep_ms(100)\n pycom.heartbeat(True)\n\n gc.collect()\n return\n\ndef store_to_SD():\n global filename\n\n filename = '/sd/data/uploading/gcam{}-acc{}-'.format(iCAM,iACC) + datetime_string(T_start)\n with open(filename,'wb') as file:\n for i in range(len(X)):\n file.write(ustruct.pack('= len(os.listdir(img_folder))):\n c = 0\n\n yield img, mask\n\n\ntrain_frame_path = \"data2/image_data\"\ntrain_mask_path = \"labels2/image_labels\"\n\nval_frame_path = \"data2/val_data\"\nval_mask_path = \"labels2/val_labels\"\n\ntest_frame_path = \"data2/test_data\"\ntest_mask_path = \"labels2/test_labels\"\n\n# Create data generators for the train, validation, and test sets\ntrain_gen = data_gen(train_frame_path, train_mask_path, batch_size=BATCH_SIZE)\nval_gen = data_gen(val_frame_path, val_mask_path, batch_size=BATCH_SIZE)\ntest_gen = data_gen(test_frame_path, test_mask_path, batch_size=BATCH_SIZE)\n\n\ndef conv2d_block(input_tensor, n_filters, kernel_size=3, batchnorm=True):\n # first layers\n x = Conv2D(filters=n_filters, kernel_size=(kernel_size, kernel_size),\n kernel_initializer=\"he_normal\", padding=\"same\")(input_tensor)\n if batchnorm:\n x = BatchNormalization()(x)\n x = Activation(\"relu\")(x)\n # second layer\n x = Conv2D(filters=n_filters, kernel_size=(kernel_size, kernel_size),\n kernel_initializer=\"he_normal\", padding=\"same\")(x)\n if batchnorm:\n x = BatchNormalization()(x)\n x = Activation(\"relu\")(x)\n return x\n\n\ndef get_unet(input_img, n_filters=16, dropout=0.5, batchnorm=True):\n # contracting path\n c1 = conv2d_block(input_img, n_filters=n_filters * 1, kernel_size=3,\n batchnorm=batchnorm)\n p1 = MaxPooling2D((2, 2))(c1)\n p1 = Dropout(dropout * 0.5)(p1)\n\n c2 = conv2d_block(p1, n_filters=n_filters * 2, kernel_size=3,\n batchnorm=batchnorm)\n p2 = MaxPooling2D((2, 2))(c2)\n p2 = Dropout(dropout)(p2)\n\n c3 = conv2d_block(p2, n_filters=n_filters * 4, kernel_size=3,\n batchnorm=batchnorm)\n p3 = MaxPooling2D((2, 2))(c3)\n p3 = Dropout(dropout)(p3)\n\n c4 = conv2d_block(p3, n_filters=n_filters * 8, kernel_size=3,\n batchnorm=batchnorm)\n p4 = MaxPooling2D((2, 2))(c4)\n p4 = Dropout(dropout)(p4)\n\n c5 = conv2d_block(p4, n_filters=n_filters * 16, kernel_size=3,\n batchnorm=batchnorm)\n\n # expansive path\n u6 = Conv2DTranspose(n_filters * 8, (3, 3), strides=(2, 2),\n padding=\"same\")(c5)\n u6 = concatenate([u6, c4])\n u6 = Dropout(dropout)(u6)\n c6 = conv2d_block(u6, n_filters=n_filters * 8, kernel_size=3,\n batchnorm=batchnorm)\n\n u7 = Conv2DTranspose(n_filters * 4, (3, 3), strides=(2, 2),\n padding=\"same\")(c6)\n u7 = concatenate([u7, c3])\n u7 = Dropout(dropout)(u7)\n c7 = conv2d_block(u7, n_filters=n_filters * 4, kernel_size=3,\n batchnorm=batchnorm)\n\n u8 = Conv2DTranspose(n_filters * 2, (3, 3), strides=(2, 2),\n padding=\"same\")(c7)\n u8 = concatenate([u8, c2])\n u8 = Dropout(dropout)(u8)\n c8 = conv2d_block(u8, n_filters=n_filters * 2, kernel_size=3,\n batchnorm=batchnorm)\n\n u9 = Conv2DTranspose(n_filters * 1, (3, 3), strides=(2, 2),\n padding=\"same\")(c8)\n u9 = concatenate([u9, c1], axis=3)\n u9 = Dropout(dropout)(u9)\n c9 = conv2d_block(u9, n_filters=n_filters * 1, kernel_size=3,\n batchnorm=batchnorm)\n\n outputs = Conv2D(NUM_CLASSES, (1, 1), activation=\"softmax\")(c9)\n model = Model(inputs=[input_img], outputs=[outputs])\n return model\n\n\ninput_img = Input(shape=(IM_HEIGHT, IM_WIDTH, 3), name=\"img\")\nmodel = get_unet(input_img, n_filters=16, dropout=0.05, batchnorm=True)\n\nprint(model.summary())\n\nmodel.compile(optimizer=Adam(lr=0.001),\n loss=\"categorical_crossentropy\",\n metrics=[\"acc\"])\n\nmodel.load_weights(\"unet-model-final.h5\")\n\ncallbacks = [EarlyStopping(patience=10, verbose=True),\n ReduceLROnPlateau(factor=0.1, patience=5, min_lr=0.0000001,\n verbose=True),\n ModelCheckpoint(\"unet-model-checkpoint.h5\", save_best_only=True,\n save_weights_only=True)]\n\nnum_training_samples = 30888\nnum_validation_samples = 4612\nnum_test_samples = 5043\nnum_epochs = 100\nresults = model.fit_generator(generator=train_gen,\n steps_per_epoch=num_training_samples//BATCH_SIZE,\n epochs=num_epochs, callbacks=callbacks,\n validation_data=val_gen,\n validation_steps=num_validation_samples//BATCH_SIZE,\n verbose=1)\n\n# Save last model\nmodel.save_weights(\"unet-model-{}.h5\".format(num_epochs))\n\nplt.figure(figsize=(8, 8))\nplt.title(\"Learning curve\")\nplt.plot(results.history[\"loss\"], label=\"loss\")\nplt.plot(results.history[\"val_loss\"], label=\"val_loss\")\nplt.plot(np.argmin(results.history[\"val_loss\"]),\n np.min(results.history[\"val_loss\"]), marker='x', color='r',\n label=\"best model\")\nplt.xlabel(\"Epochs\")\nplt.ylabel(\"log_loss\")\nplt.legend()\nplt.savefig(\"lossplot-unet-{}.png\".format(num_epochs), bbox_inches=\"tight\")\nplt.show()\n\nplt.figure(figsize=(8, 8))\nplt.title(\"Accuracy curve\")\nplt.plot(results.history[\"acc\"], label=\"acc\")\nplt.plot(results.history[\"val_acc\"], label=\"val_acc\")\nplt.plot(np.argmax(results.history[\"val_acc\"]),\n np.max(results.history[\"val_acc\"]), marker='x', color='r',\n label=\"best model\")\nplt.xlabel(\"Epochs\")\nplt.ylabel(\"acc\")\nplt.legend()\nplt.savefig(\"accplot-unet-{}.png\".format(num_epochs), bbox_inches=\"tight\")\nplt.show()\n\ntest_loss, test_acc = model.evaluate_generator(generator=test_gen,\n steps=num_test_samples,\n verbose=1)\nprint(\"\\n\")\nprint(\"Test acc: \", test_acc)\nprint(\"Test loss: \", test_loss)\n\n\n# Find the F1 scores of each class\nX_ = 0\ny_ = 0\nX_test = np.zeros((5043, 160, 160, 3))\ny_test = np.zeros((5043, 160, 160, 6), dtype=np.bool)\nfor i in range(5043):\n X_ = imread(\"data2/test_data/test_data\"+str(i)+\".png\").reshape((1, 160, 160, 3))/255.\n y_ = tiff.imread(\"labels2/test_labels/test_labels\"+str(i)+\".tif\").reshape((1, 160, 160, 6))\n X_test[i] = X_\n y_test[i] = y_\nY_test = np.argmax(y_test, axis=3).flatten()\ny_pred = model.predict(X_test)\nY_pred = np.argmax(y_pred, axis=3).flatten()\ncorrect = np.zeros((6))\ntotals1 = np.zeros((6))\ntotals2 = np.zeros((6))\n\nfor i in range(len(Y_test)):\n if Y_pred[i] == Y_test[i]:\n correct[Y_pred[i]] += 1\n totals1[Y_pred[i]] += 1\n totals2[Y_test[i]] += 1\n\nprecision = correct / totals1\nrecall = correct / totals2\nF1 = 2 * (precision*recall) / (precision + recall)\nprint(F1)\n\n# Load image and labels to create mask\nX = np.zeros((1681, 160, 160, 3))\ny = np.zeros((1681, 160, 160, 6), dtype=np.bool)\nfor i in range(0*1681, 1*1681):\n X_ = imread(\"data2/test_data/test_data\"+str(i)+\".png\").reshape((1, 160, 160, 3))/255.\n y_ = tiff.imread(\"labels2/test_labels/test_labels\"+str(i)+\".tif\").reshape((1, 160, 160, 6))\n X[i-0*1681] = X_\n y[i-0*1681] = y_\n\npreds_train = model.predict(X, verbose=True)\npreds_train_t = (preds_train == preds_train.max(axis=3)[..., None]).astype(int)\n\n\ndef plot_image(X, y, preds):\n width = 41\n height = 41\n image_array = np.zeros((width*160-(width-1)*14, height*160-(height-1)*14, 3), dtype=np.int)\n labels_array = np.zeros((width*160-(width-1)*14, height*160-(height-1)*14, 6), dtype=np.bool)\n preds_array = np.zeros((width*160-(width-1)*14, height*160-(height-1)*14, 6))\n for i in range(width):\n for j in range(height):\n image_array[i*(160-14):(i+1)*(160-14)+14, j*(160-14):(j+1)*(160-14)+14, :] = X[i*41+j]\n labels_array[i*(160-14):(i+1)*(160-14)+14, j*(160-14):(j+1)*(160-14)+14, :] = y[i*41+j]\n preds_array[i*(160-14):i*(160-14)+14, j*(160-14):(j+1)*(160-14)+14, :] += preds[i*41+j, :14, :, :]\n preds_array[i*(160-14):(i+1)*(160-14)+14, j*(160-14):j*(160-14)+14, :] += preds[i*41+j, :, :14, :]\n preds_array[i*(160-14)+14:(i+1)*(160-14)+14, j*(160-14)+14:(j+1)*(160-14)+14, :] += preds[i*41+j, 14:, 14:, :]\n\n fig, ax = plt.subplots(figsize=(10, 10))\n ax.imshow(image_array, interpolation=\"bilinear\")\n ax.grid(False)\n ax.set_xticks([])\n ax.set_yticks([])\n plt.savefig(\"unetfinalimage0.png\", bbox_inches=\"tight\")\n plt.show()\n\n # cars = yellow\n true_cars_overlay = (labels_array[..., 0] > 0).reshape((width*(160-14)+14, height*(160-14)+14, 1))\n true_cars_overlay_rgba = np.concatenate((true_cars_overlay, true_cars_overlay, np.zeros(true_cars_overlay.shape), true_cars_overlay * 1.0), axis=2)\n # buildings = blue\n true_buildings_overlay = (labels_array[..., 1] > 0).reshape((width*(160-14)+14, height*(160-14)+14, 1))\n true_buildings_overlay_rgba = np.concatenate((np.zeros(true_buildings_overlay.shape), np.zeros(true_buildings_overlay.shape), true_buildings_overlay, true_buildings_overlay * 01.), axis=2)\n # low_vegetation = cyan\n true_low_vegetation_overlay = (labels_array[..., 2] > 0).reshape((width*(160-14)+14, height*(160-14)+14, 1))\n true_low_vegetation_overlay_rgba = np.concatenate((np.zeros(true_low_vegetation_overlay.shape), true_low_vegetation_overlay, true_low_vegetation_overlay, true_low_vegetation_overlay * 1.0), axis=2)\n # trees = green\n true_trees_overlay = (labels_array[..., 3] > 0).reshape((width*(160-14)+14, height*(160-14)+14, 1))\n true_trees_overlay_rgba = np.concatenate((np.zeros(true_trees_overlay.shape), true_trees_overlay, np.zeros(true_trees_overlay.shape), true_trees_overlay * 1.0), axis=2)\n # impervious = white\n true_impervious_overlay = (labels_array[..., 4] > 0).reshape((width*(160-14)+14, height*(160-14)+14, 1))\n true_impervious_overlay_rgba = np.concatenate((true_impervious_overlay, true_impervious_overlay, true_impervious_overlay, true_impervious_overlay * 1.0), axis=2)\n # clutter = red\n true_clutter_overlay = (labels_array[..., 5] > 0).reshape((width*(160-14)+14, height*(160-14)+14, 1))\n true_clutter_overlay_rgba = np.concatenate((true_clutter_overlay, np.zeros(true_clutter_overlay.shape), np.zeros(true_clutter_overlay.shape), true_clutter_overlay * 1.0), axis=2)\n\n fig, ax = plt.subplots(2, 1, figsize=(20, 20))\n ax[0].imshow(image_array, interpolation=\"bilinear\")\n ax[0].imshow(true_cars_overlay_rgba, interpolation=\"bilinear\")\n ax[0].imshow(true_buildings_overlay_rgba, interpolation=\"bilinear\")\n ax[0].imshow(true_low_vegetation_overlay_rgba, interpolation=\"bilinear\")\n ax[0].imshow(true_trees_overlay_rgba, interpolation=\"bilinear\")\n ax[0].imshow(true_impervious_overlay_rgba, interpolation=\"bilinear\")\n ax[0].imshow(true_clutter_overlay_rgba, interpolation=\"bilinear\")\n ax[0].grid(False)\n ax[0].set_xticks([])\n ax[0].set_yticks([])\n\n # cars = yellow\n true_cars_overlay = (preds_array[..., 0] > 0).reshape((width*(160-14)+14, height*(160-14)+14, 1))\n true_cars_overlay_rgba = np.concatenate((true_cars_overlay, true_cars_overlay, np.zeros(true_cars_overlay.shape), true_cars_overlay * 1.0), axis=2)\n # buildings = blue\n true_buildings_overlay = (preds_array[..., 1] > 0).reshape((width*(160-14)+14, height*(160-14)+14, 1))\n true_buildings_overlay_rgba = np.concatenate((np.zeros(true_buildings_overlay.shape), np.zeros(true_buildings_overlay.shape), true_buildings_overlay, true_buildings_overlay * 1.0), axis=2)\n # low_vegetation = cyan\n true_low_vegetation_overlay = (preds_array[..., 2] > 0).reshape((width*(160-14)+14, height*(160-14)+14, 1))\n true_low_vegetation_overlay_rgba = np.concatenate((np.zeros(true_low_vegetation_overlay.shape), true_low_vegetation_overlay, true_low_vegetation_overlay, true_low_vegetation_overlay * 1.0), axis=2)\n # trees = green\n true_trees_overlay = (preds_array[..., 3] > 0).reshape((width*(160-14)+14, height*(160-14)+14, 1))\n true_trees_overlay_rgba = np.concatenate((np.zeros(true_trees_overlay.shape), true_trees_overlay, np.zeros(true_trees_overlay.shape), true_trees_overlay * 1.0), axis=2)\n # impervious = white\n true_impervious_overlay = (preds_array[..., 4] > 0).reshape((width*(160-14)+14, height*(160-14)+14, 1))\n true_impervious_overlay_rgba = np.concatenate((true_impervious_overlay, true_impervious_overlay, true_impervious_overlay, true_impervious_overlay * 1.0), axis=2)\n # clutter = red\n true_clutter_overlay = (preds_array[..., 5] > 0).reshape((width*(160-14)+14, height*(160-14)+14, 1))\n true_clutter_overlay_rgba = np.concatenate((true_clutter_overlay, np.zeros(true_clutter_overlay.shape), np.zeros(true_clutter_overlay.shape), true_clutter_overlay * 1.0), axis=2)\n\n ax[1].imshow(image_array, interpolation=\"bilinear\")\n ax[1].imshow(true_cars_overlay_rgba, interpolation=\"bilinear\")\n ax[1].imshow(true_buildings_overlay_rgba, interpolation=\"bilinear\")\n ax[1].imshow(true_low_vegetation_overlay_rgba, interpolation=\"bilinear\")\n ax[1].imshow(true_trees_overlay_rgba, interpolation=\"bilinear\")\n ax[1].imshow(true_impervious_overlay_rgba, interpolation=\"bilinear\")\n ax[1].imshow(true_clutter_overlay_rgba, interpolation=\"bilinear\")\n ax[1].grid(False)\n ax[1].set_xticks([])\n ax[1].set_yticks([])\n plt.savefig(\"unetfinallabels0.png\", bbox_inches=\"tight\")\n plt.show()\n\n\nplot_image(X, y, preds_train_t)\n","sub_path":"test_model.py","file_name":"test_model.py","file_ext":"py","file_size_in_byte":14947,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"46420797","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Apr 23 18:33:31 2017\n\n@author: Hou LAN\n\"\"\"\n#first make sure packages are loaded\nimport numpy as np\nimport pandas as pd\nimport time\n\nfrom sklearn import preprocessing, metrics\nfrom sklearn.cluster import KMeans\n\nfrom scipy import cluster\nfrom scipy.stats.stats import pearsonr\n\nimport matplotlib.pyplot as plt\nfrom matplotlib.externals import six\nfrom matplotlib.ticker import FuncFormatter, MaxNLocator\n\n\n\n\n\n#*********************************************#\n#\n# Data Preprocessing\n#\n#*********************************************#\n \n\n\n#check stock data\ndef check_colinfo(df_stock,col_name):\n '''accept a dataframe of stock price collection with firm tickers and timestamp;\n a list of firm tickers.\n print the anomalous column value information.\n '''\n #if there is null value in column\n if df_stock[col_name].isnull().any():\n #get the array of the index of null value\n idx = np.where(df_stock[col_name].isnull())\n #get the tickers of firms with null value\n null_tic = list(df_stock.ix[idx[0]].tic.unique()) \n if len(null_tic) <=10:\n for i in null_tic:\n print(col_name,'of',i,'have/has NULL value, please CHECK!')\n else:\n print(len(null_tic),'stocks have NULL value, please CHECK!')\n \n #if there is negative value\n if (df_stock[col_name]<0).any():\n neg_tic = list(df_stock.ix[df_stock[col_name]<0,'tic'].unique())\n if len(neg_tic) <=10:\n for i in neg_tic:\n print(col_name,'of',i,'have/has negative value(s), please CHECK!')\n else:\n print(len(neg_tic),'stocks have negative value(s), please CHECK!')\n \n #if there is repetitive record on the same day\n #for convenience we assume date as one seperate float column\n if df_stock.duplicated(['tic','datadate']).any():\n dup_tic = list(df_stock.ix[np.where(df_stock.duplicated(['tic','datadate']))[0],'tic'].unique())\n if len(dup_tic) <=10:\n for i in dup_tic:\n print(col_name,'of',i,'have/has repetitive value(s), please CHECK!')\n else:\n print(len(dup_tic),'stocks have repetitive value(s), please CHECK!')\n \n\n \n# plot sample of dataframe \ndef render_mpl_table(data, col_width=3.0, row_height=0.625, font_size=14,\n header_color='#40466e', row_colors=['#f1f1f2', 'w'], edge_color='w',\n bbox=[0, 0, 1, 1], header_columns=0,\n ax=None, **kwargs):\n '''accept a dataframe\n return an ax to see dataframe clearly\n '''\n #A5A5A5\n #change decimal if necessary\n data = np.round(data, decimals=5)\n if ax is None:\n size = (np.array(data.shape[::-1]) + np.array([0, 1])) * np.array([col_width, row_height])\n fig, ax = plt.subplots(figsize=size)\n ax.axis('off')\n\n mpl_table = ax.table(cellText=data.values, bbox=bbox, colLabels=data.columns, **kwargs)\n\n mpl_table.auto_set_font_size(False)\n mpl_table.set_fontsize(font_size)\n\n for k, cell in six.iteritems(mpl_table._cells):\n cell.set_edgecolor(edge_color)\n if k[0] == 0 or k[1] < header_columns:\n cell.set_text_props(weight='bold', color='w')\n cell.set_facecolor(header_color)\n else:\n cell.set_facecolor(row_colors[k[0]%len(row_colors) ])\n return ax\n\n#\n##*********************************************#\n##\n## Cluster\n##\n##*********************************************#\n#\n#\n# \n##K-means\n#\n##find optimal K by finding elbow point\n#def plot_k(data_matrix,range_max=15):\n# '''accept a data matrix and a right end \n# return a plot to visualize optimal k in K-Means \n# '''\n# distortions_k = []\n# for i in range(1,range_max):\n# km = KMeans(n_clusters=i)\n# km.fit(data_matrix)\n# distortions_k.append(km.inertia_)\n#\n# ax = plt.subplot(1,1,1)\n# ax.set_title('find elbow point in K-means')\n# ax = plt.plot(range(1,range_max),distortions_k,marker='o',c='#40466e')\n# \n# return ax\n#\n#\n#\n##validation by silhouette_score\n#\n#def validate_km(data_matrix,range_max=15):\n# '''accept a data matrix and a right end \n# return silhouette score of K-Means\n# '''\n# sc_scores_k = []\n# for i in range(2,range_max):\n# km = KMeans(n_clusters=i)\n# km.fit(data_matrix)\n# sc_score = metrics.silhouette_score(data_matrix,km.labels_,metric=\"euclidean\")\n# sc_scores_k.append(sc_score)\n# \n# return sc_scores_k\n# \n#\n#\n#\n#def validate_fcluster(data_matrix,range_max=15):\n# '''accept a data matrix and a right end \n# return silhouette score of hierarchical cluster\n# '''\n# sc_scores_f = []\n# Z = cluster.hierarchy.linkage(data_matrix,'ward')\n# for i in range(2,range_max):\n# fcluster = cluster.hierarchy.fcluster(Z,i,criterion='maxclust')\n# sc_score = metrics.silhouette_score(data_matrix,fcluster,metric=\"euclidean\")\n# sc_scores_f.append(sc_score)\n# \n# return sc_scores_f\n# \n#\n#\n#\n#\n##*********************************************#\n##\n## Correlation \n##\n##*********************************************#\n#\n#\n#\n#def find_leadstock(cluster):\n# \n# tic = list(cluster.columns.unique())\n# #calculate simple moving average to find \"group leader\" with maximum correlation with \"future values\" of other stocks\n# ret_lag = pd.DataFrame()\n# for i in tic:\n# ret_lag[i+'_lag'] = cluster[i].rolling(window = 5, center = False).mean()\n# \n# df_tmp = ret_lag.join(cluster)\n# df_tmp.fillna(0,inplace=True)\n# corr_df = df_tmp.corr(method='pearson')\n# leader = np.mean(abs(corr_df.ix[len(cluster.columns):,:(len(cluster.columns)-1)]).T).idxmax()\n# \n# return leader\n# \n#\n#\n#\n#def plot_cluster(cluster,leader,titlename):\n# with pd.plot_params.use('x_compat', True):\n# ax = cluster.plot(style='--',legend=False,title=titlename)\n# ax = cluster[leader].plot(color='r',linewidth='3',legend=True)\n# ax.set_ylabel('Normalized Return')\n# return ax\n#\n#\n#\n#\n#\n##*********************************************#\n##\n## Regression\n##\n##*********************************************#\n#\n#\n#\n##SVM predicting\n#\n#\n#from sklearn.svm import SVR\n#from sklearn import cross_validation\n#\n#\n#\n#def svr_predict_price(dates, prices, x):\n# date_tick = dates #use as tick\n# dates = np.reshape(list(range(len(dates))),(len(dates), 1)) # converting to matrix of n X 1\n# svr_rbf = SVR(kernel= 'rbf', C= 1e3, gamma= 0.1) # defining the support vector regression models\n# svr_lin = SVR(kernel= 'linear', C= 1e3)\n# svr_poly = SVR(kernel= 'poly', C= 1e3, degree= 2)\n# svr_rbf.fit(dates, prices) # fitting the data points in the models\n# svr_lin.fit(dates, prices)\n# svr_poly.fit(dates, prices)\n# fig = plt.figure()\n# ax = fig.add_subplot(1, 1, 1)\n# ax.set_xlim(0,len(date_tick))\n#\n# ax.scatter(np.reshape(list(range(len(date_tick))),(len(date_tick), 1)), prices, color= 'black', label= 'Data') # plotting the initial datapoints \n# ax.plot(dates, svr_rbf.predict(dates), color= 'red', label= 'RBF model') # plotting the line made by rbf kernel\n# ax.plot(dates,svr_lin.predict(dates), color= 'green', label= 'Linear model') # plotting the line made by linear kernel\n# ax.plot(dates,svr_poly.predict(dates), color= 'blue', label= 'Polynomial model') # plotting the line made by polynomial kernel\n# ax.set_xlabel('Date')\n# ax.set_ylabel('Price')\n# ax.set_title('Support Vector Regression')\n# ax.xaxis.set_major_locator(MaxNLocator(nbins=len(date_tick), integer=True))\n# ax.set_xticklabels(date_tick)\n# plt.legend(loc='best')\n# plt.xticks(rotation=45)\n# plt.tight_layout()\n# plt.show()\n# \n# loo = cross_validation.LeaveOneOut(len(prices))\n# score_rbf = cross_validation.cross_val_score(svr_rbf, dates, prices, scoring='mean_squared_error', cv=loo,)\n# score_lin = cross_validation.cross_val_score(svr_lin, dates, prices, scoring='mean_squared_error', cv=loo,)\n# score_poly = cross_validation.cross_val_score(svr_poly, dates, prices, scoring='mean_squared_error', cv=loo,)\n#\n# return score_rbf, score_lin, score_poly\n#\n#\n#\n#\n#\n#if __name__ == '__main__':\n# #read in stock data csv\n# df = pd.read_csv('fin_2017-04-23_2390.csv')\n# #get stock return\n# df['ret'] = df.groupby('tic')['Adj Close'].pct_change().fillna(0)\n# df.index = df.Date\n# \n# #visualize original stock dataframe from Yahoo Finance API\n## f1 = plt.figure()\n## ax1 = f1.add_subplot(111)\n# ax1 = render_mpl_table(df.head(), header_columns=0, col_width=2.0)\n# ax1.set_title('Sample of Original Stock DataFrame')\n#\n# #get return matrix\n# ret_df = df[[\"ret\", \"tic\"]].set_index(\"tic\", append=True).ret.unstack(\"tic\")\n# ret_matrix = ret_df.T.as_matrix()\n# ret_matrix = preprocessing.scale(ret_matrix.T).T\n# ret_df_norm = pd.DataFrame(ret_matrix.T,index=ret_df.index,columns=ret_df.columns)\n#\n# #visualize optimal K in K-means\n# f2 = plt.figure()\n# ax2 = f2.add_subplot(111)\n# ax2.set_title('To find elbow point in K-Means')\n# ax2 = plot_k(ret_matrix)\n#\n# sc_scores_k = validate_km(ret_matrix)\n# model = KMeans(n_clusters=2)\n# y_km = model.fit_predict(ret_matrix)\n# \n# Z = cluster.hierarchy.linkage(ret_matrix,'ward')\n# #visualize hierarchy dendrogram\n# f3 = plt.figure()\n# ax3 = f3.add_subplot(111)\n# ax3.set_title('Dendrogram of Hierarchy Cluster')\n# ax3 = cluster.hierarchy.dendrogram(Z)\n# fcluster = cluster.hierarchy.fcluster(Z,2,criterion='maxclust')\n# sc_scores_f = validate_fcluster(ret_matrix)\n# \n# #visualize the comparation between K-Means and hierarchy \n# #df_km_fclu = pd.DataFrame([sc_scores_k,sc_scores_f],index=['sc_scores_k','sc_scores_f'],columns=list(range(2,15))).T \n# #N = 3\n# #ind = np.arange(N) # the x locations for the groups\n# #width = 0.27 # the width of the bars \n# \n# #f = plt.figure()\n# #ax = f.add_subplot(111)\n# \n# #rects1 = ax.bar(ind+0.2, sc_scores_k[:3], width, color='#9999ff',alpha=0.6)\n# #rects2 = ax.bar(ind+width+0.2, sc_scores_f[:3], width, color='#ff9999',alpha=0.6)\n# \n# #ax.set_title('Comparison between KMeans and Hierarchy Cluster')\n# #ax.set_ylabel('Silhouette score')\n# #ax.set_xticks(ind+width+0.2)\n# #ax.set_xticklabels( ('Cluster 2', 'Cluster 3', 'Cluster 4') )\n# #ax.legend((rects1[0], rects2[0]), ('KMeans', 'Hierarchy') )\n#\n#\n# #get two cluster dataframe according to analysing above and use K-Means as a better clustering\n# names = np.array(ret_df.columns)\n# cluster_1 = ret_df_norm[names[y_km==0]]\n# cluster_2 = ret_df_norm[names[y_km==1]]\n#\n# \n# leader_1 = find_leadstock(cluster_1)\n# leader_2 = find_leadstock(cluster_2)\n#\n#\n#\n# #visualize cluster\n# plot_cluster(cluster_1,leader_1,'Cluster 1')\n## plot_cluster(cluster_2,leader_2,'Cluster 2')\n#\n# plt.show()\n# \n# #SVM prediction\n## df.reset_index(drop=True,inplace=True)\n## dates = df[df.tic==leader_2].Date\n## prices = df.ix[df.tic==leader_2,'Adj Close']\n#\n# #take much time\n## x,y,z = svr_predict_price(dates,prices,len(dates))\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\n\n\n\n\n \n\n\n","sub_path":"week6/houlan_41423018_2017-04-23.py","file_name":"houlan_41423018_2017-04-23.py","file_ext":"py","file_size_in_byte":11316,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"548786698","text":"'''\nDado un archivo “prueba.txt” de formato CSV (valores separados por coma), en\ndonde hay 3 campos: número de legajo, nombre y apellido, nota (de tipo entero),\nse pide: leerlo e imprimirlo por pantalla con el mismo formato que está en el\narchivo.\nNota: escribir un archivo para probar el programa. '''\ndef leer():\n file = open('prueba.csv')\n print(file)\n # for linea in file:\n # print(linea)\n file.close()\n\n\ndef leer2():\n file = open('prueba.csv')\n lista = file.readlines()\n for i in lista:\n x=lista.strip(\"\\n\")\n print(x)\n # print(lista)\n file.close()\nleer2()\n","sub_path":"Archivos/ejercicio-1.py","file_name":"ejercicio-1.py","file_ext":"py","file_size_in_byte":615,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"522591563","text":"#coding: utf-8\r\n\"\"\"\r\nThe documentaion describing authentication process is available on:\r\nhttp://www.ivona.com/speech-cloud\r\n\"\"\"\r\n\r\nimport hmac\r\nimport posixpath\r\nfrom hashlib import sha256 as sha256\r\nimport datetime\r\n\r\nimport six\r\n\r\nfrom six.moves.urllib.parse import quote\r\nfrom ivonaspeechcloud.const import METHOD_POST\r\n\r\n\r\nclass AuthenticationHelper(object):\r\n AWS_REQUEST = 'aws4_request'\r\n SERVICE_NAME = \"tts\"\r\n HASH_ALGORITHM = 'AWS4-HMAC-SHA256'\r\n DATE_FORMAT = '%Y%m%dT%H%M%SZ'\r\n\r\n @staticmethod\r\n def _sign(key, msg, hex_digest=False):\r\n sig = hmac.new(key, msg.encode('utf-8'), sha256)\r\n return sig.hexdigest() if hex_digest else sig.digest()\r\n\r\n @staticmethod\r\n def host_header(http_request):\r\n \"\"\"Generate Host header.\"\"\"\r\n port = http_request.port\r\n secure = http_request.protocol == 'https'\r\n if (port == 80 and not secure) or (port == 443 and secure):\r\n return http_request.host\r\n return '%s:%s' % (http_request.host, port)\r\n\r\n @classmethod\r\n def formatted_now(cls):\r\n return datetime.datetime.utcnow().strftime(cls.DATE_FORMAT)\r\n\r\n @staticmethod\r\n def get_utf8_value(value):\r\n if isinstance(value, six.text_type):\r\n return value.encode('utf-8')\r\n else:\r\n return value\r\n\r\n @staticmethod\r\n def canonical_headers(headers_to_sign):\r\n \"\"\"Return the headers that need to be included in the StringToSign\r\n in their canonical form by converting all header keys to lower\r\n case, sorting them in alphabetical order and then joining\r\n them into a string, separated by newlines.\r\n \"\"\"\r\n canonical = []\r\n\r\n for header in headers_to_sign:\r\n c_name = header.lower().strip()\r\n c_value = ' '.join(headers_to_sign[header].strip().split())\r\n canonical.append('%s:%s' % (c_name, c_value))\r\n return '\\n'.join(sorted(canonical))\r\n\r\n @staticmethod\r\n def signed_headers(headers_to_sign):\r\n return ';'.join(sorted([n.lower().strip() for n in headers_to_sign]))\r\n\r\n @staticmethod\r\n def canonical_uri(http_request):\r\n \"\"\"Generates canonical URI from the request.\"\"\"\r\n path = http_request.auth_path\r\n # Normalize the path\r\n # in windows normpath('/') will be '\\\\' so we change it back to '/'\r\n normalized = posixpath.normpath(path).replace('\\\\', '/')\r\n # Then urlencode whatever's left.\r\n encoded = quote(normalized)\r\n if len(path) > 1 and path.endswith('/'):\r\n encoded += '/'\r\n return encoded\r\n\r\n @staticmethod\r\n def payload_hash(http_request):\r\n \"\"\"Computes hash of the payload.\"\"\"\r\n return sha256(http_request.get_post_payload().encode('utf-8')).hexdigest()\r\n\r\n @classmethod\r\n def headers_to_sign(cls, http_request):\r\n \"\"\"Select the headers from the request that need to be included\r\n in the StringToSign.\r\n \"\"\"\r\n host_header_value = cls.host_header(http_request)\r\n headers_to_sign = {'Host': host_header_value}\r\n for name, value in http_request.headers.items():\r\n lname = name.lower()\r\n if lname.startswith('x-amz'):\r\n headers_to_sign[name] = value\r\n return headers_to_sign\r\n\r\n\r\n @classmethod\r\n def canonical_query_string(cls, method, qs_params):\r\n \"\"\"Generates query string which is used for signing the request afterwards.\"\"\"\r\n if method == METHOD_POST:\r\n return \"\"\r\n parts = []\r\n non_quote_chars = '-_.~'\r\n for param, value in sorted(list(qs_params.items())):\r\n utf8_value = cls.get_utf8_value(value)\r\n parts.append('%s=%s' % (quote(param, safe=non_quote_chars),\r\n quote(utf8_value, safe=non_quote_chars)))\r\n return '&'.join(parts)\r\n\r\n @classmethod\r\n def canonical_request(cls, http_request, method, qs_params):\r\n \"\"\"Generates string from request which is signed afterwards.\"\"\"\r\n headers_to_sign = cls.headers_to_sign(http_request)\r\n return '\\n'.join(\r\n [method.upper(), cls.canonical_uri(http_request), cls.canonical_query_string(method, qs_params),\r\n cls.canonical_headers(headers_to_sign) + '\\n', cls.signed_headers(headers_to_sign),\r\n cls.payload_hash(http_request)])\r\n\r\n @classmethod\r\n def credential_scope(cls, timestamp, region_name):\r\n \"\"\"\r\n Generate credential scope string.\r\n \"\"\"\r\n return '/'.join([timestamp, region_name, cls.SERVICE_NAME, cls.AWS_REQUEST])\r\n\r\n @classmethod\r\n def scope(cls, provider, timestamp, region_name):\r\n \"\"\"\r\n Generate scope string.\r\n \"\"\"\r\n return '{0}/{1}'.format(provider.access_key, cls.credential_scope(timestamp, region_name))\r\n\r\n @classmethod\r\n def string_to_sign(cls, timestamp, region_name, canonical_request, formatted_now):\r\n \"\"\"Return the canonical StringToSign.\"\"\"\r\n sts = [cls.HASH_ALGORITHM, formatted_now, cls.credential_scope(timestamp, region_name),\r\n sha256(canonical_request.encode('utf-8')).hexdigest()]\r\n return '\\n'.join(sts)\r\n\r\n @classmethod\r\n def signature(cls, provider, string_to_sign, timestamp, region_name):\r\n \"\"\"Computes the signature.\"\"\"\r\n key = provider.secret_key\r\n k_date = cls._sign(('AWS4' + key).encode('utf-8'), timestamp)\r\n k_region = cls._sign(k_date, region_name)\r\n k_service = cls._sign(k_region, cls.SERVICE_NAME)\r\n k_signing = cls._sign(k_service, cls.AWS_REQUEST)\r\n return cls._sign(k_signing, string_to_sign, hex_digest=True)\r\n","sub_path":"aws/ivona-speechcloud-sdk-python/build/lib/ivonaspeechcloud/authenticationhelper.py","file_name":"authenticationhelper.py","file_ext":"py","file_size_in_byte":5688,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"137932654","text":"import cv2\r\nimport numpy as np\r\n\r\n#VideoCapture\r\ncap = cv2.VideoCapture(0)\r\nharscade_file = cv2.CascadeClassifier(\"haarcascade_frontalface_default.xml\")\r\nface_data = []\r\nname = input(\"Enter name of the person:-\")\r\nskip = 0\r\ndata_path=\"./data/\"\r\n\r\nwhile True:\r\n ret,frame = cap.read()\r\n if(ret== False):\r\n continue\r\n gray_frame = cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)\r\n faces = harscade_file.detectMultiScale(frame,1.3,5)\r\n faces = sorted(faces,key = lambda f:f[2]*f[3])\r\n\r\n for face in faces:\r\n x,y,w,h = face\r\n cv2.rectangle(frame,(x,y),(x+w,y+h),(255,255,255),2)\r\n cv2.rectangle(gray_frame,(x,y),(x+w,y+h),(255,255,255),2)\r\n offset = 10\r\n face_section = frame[y-offset:y+h+offset,x-offset:x+w+offset]\r\n face_section=cv2.resize(face_section,(100,100))\r\n skip+=1\r\n if(skip%10==0):\r\n face_data.append(face_section)\r\n print(len(face_data))\r\n\r\n cv2.imshow(\"Frame\",frame)\r\n cv2.imshow(\"gray_frame\",gray_frame)\r\n key_pressed = cv2.waitKey(1) & 0xFF\r\n if(key_pressed==ord('q')):\r\n break;\r\nface_data=np.asarray(face_data)\r\nface_data=face_data.reshape((face_data.shape[0],-1))\r\nprint (face_data)\r\nnp.save(data_path+name+\".npy\",face_data)\r\nprint(\"data successfully saved at\"+data_path+name+\".npy\")\r\n\r\ncap.release()\r\ncv2.destroyAllWindows()\r\n","sub_path":"face_recognization/face_data_collect.py.py","file_name":"face_data_collect.py.py","file_ext":"py","file_size_in_byte":1355,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"129346379","text":"def MergeSortAndCountSplitInv(B, C, n):\n D = [None] * n\n l = 0\n for k in range(0, n):\n if (len(B) > 0):\n if(len(C) > 0):\n if(int(B[0]) < int(C[0])):\n D[k] = B[0]\n B.pop(0)\n else:\n D[k] = C[0]\n C.pop(0)\n if(len(B) > 0):\n l += len(B)\n else:\n D[k:] = B\n break\n else:\n D[k:] = C\n break\n return (D, l)\n\ndef SortAndCountInversions(A, n):\n if n == 1:\n return (A, 0)\n else:\n if n % 2 == 0:\n mid = int(n/2)\n A1 = A[0:mid]\n A2 = A[mid:n]\n else:\n mid = int((n-1)/2)\n A1 = A[0:mid]\n A2 = A[mid:n]\n len1 = len(A1)\n len2 = len(A2)\n (B, X) = SortAndCountInversions(A1, len1)\n (C, Y) = SortAndCountInversions(A2, len2)\n (D, Z) = MergeSortAndCountSplitInv(B, C, n)\n return (D, (X+Y+Z))\n\nNumArray = []\nwith open('IntegerArray.txt') as f:\n NumArray = f.read().splitlines()\n\n(SortedNumArray, NoOfInv) = SortAndCountInversions(NumArray, len(NumArray))\nprint (NoOfInv)\n","sub_path":"src/CountInversions.py","file_name":"CountInversions.py","file_ext":"py","file_size_in_byte":1229,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"318552655","text":"import os, sys\n\ncurrentdir = os.path.dirname(os.path.realpath(__file__))\nparentdir = os.path.dirname(currentdir)\nsys.path.append(parentdir) # PYTHON > 3.3 does not allow relative referencing\n\n# import tensorflow as tf\n# tf.enable_eager_execution()\n# import neurite.py.utils as neurite_utils\n\nfrom skimage.morphology import skeletonize_3d, ball\nfrom skimage.morphology import binary_closing, binary_opening\nfrom skimage.filters import median\nfrom skimage.measure import regionprops, label\nfrom skimage.transform import warp\n\nfrom scipy.ndimage import zoom\nfrom scipy.interpolate import LinearNDInterpolator, Rbf\n\nimport h5py\nimport numpy as np\nfrom tqdm import tqdm\nimport re\nimport nibabel as nib\nfrom nilearn.image import resample_img\n\nfrom Centerline.graph_utils import graph_to_ndarray, deform_graph, get_bifurcation_nodes, subsample_graph, \\\n apply_displacement\nfrom Centerline.skeleton_to_graph import get_graph_from_skeleton\nfrom Centerline.visualization_utils import plot_skeleton, compare_graphs\n\nfrom DeepDeformationMapRegistration.utils.operators import min_max_norm\nfrom DeepDeformationMapRegistration.utils import constants as C\n\nimport cupy\nfrom cupyx.scipy.ndimage import zoom as zoom_gpu\nfrom cupyx.scipy.ndimage import map_coordinates\n\nDATASET_LOCATION = '/mnt/EncryptedData1/Users/javier/vessel_registration/3Dirca/dataset/EVAL'\nDATASET_NAMES = ['Affine', 'None', 'Translation']\nDATASET_FILENAME = 'volume'\nIMGS_FOLDER = '/home/jpdefrutos/workspace/DeepDeformationMapRegistration/Centerline/centerlines'\n\nDATASTE_RAW_FILES = '/mnt/EncryptedData1/Users/javier/vessel_registration/3Dirca/nifti3'\nLITS_SEGMENTATION_FILE = 'segmentation'\nLITS_CT_FILE = 'volume'\n\n\ndef warp_volume(volume, disp_map, indexing='ij'):\n assert indexing is 'ij' or 'xy', 'Invalid indexing option. Only \"ij\" or \"xy\"'\n grid_i = np.linspace(0, disp_map.shape[0], disp_map.shape[0], endpoint=False)\n grid_j = np.linspace(0, disp_map.shape[1], disp_map.shape[1], endpoint=False)\n grid_k = np.linspace(0, disp_map.shape[2], disp_map.shape[2], endpoint=False)\n grid_i, grid_j, grid_k = np.meshgrid(grid_i, grid_j, grid_k, indexing=indexing)\n grid_i = (grid_i.flatten() + disp_map[..., 0].flatten())[..., np.newaxis]\n grid_j = (grid_j.flatten() + disp_map[..., 1].flatten())[..., np.newaxis]\n grid_k = (grid_k.flatten() + disp_map[..., 2].flatten())[..., np.newaxis]\n coords = np.hstack([grid_i, grid_j, grid_k]).reshape([*disp_map.shape[:-1], -1])\n coords = coords.transpose((-1, 0, 1, 2))\n # The returned volume has indexing xy\n return warp(volume, coords)\n\n\ndef keep_largest_segmentation(img):\n label_img = label(img)\n rp = regionprops(label_img) # Regions labeled with 0 (bg) are ignored\n biggest_area = (0, 0)\n for l in range(0, label_img.max()):\n if rp[l].area > biggest_area[1]:\n biggest_area = (l + 1, rp[l].area)\n img[label_img != biggest_area[0]] = 0.\n return img\n\n\ndef preprocess_image(img, keep_largest=False):\n ret = binary_closing(img, ball(1))\n ret = binary_opening(ret, ball(1))\n #ret = median(ret, ball(1), mode='constant')\n if keep_largest:\n ret = keep_largest_segmentation(ret)\n return ret.astype(np.float)\n\n\ndef build_displacement_map_interpolator(disp_map, backwards=False, indexing='ij'):\n grid_i = np.linspace(0, disp_map.shape[0], disp_map.shape[0], endpoint=False)\n grid_j = np.linspace(0, disp_map.shape[1], disp_map.shape[1], endpoint=False)\n grid_k = np.linspace(0, disp_map.shape[2], disp_map.shape[2], endpoint=False)\n grid_i, grid_j, grid_k = np.meshgrid(grid_i, grid_j, grid_k, indexing=indexing)\n grid_i = grid_i.flatten()\n grid_j = grid_j.flatten()\n grid_k = grid_k.flatten()\n # To generate the moving image, we used backwards mapping were the input was the fix image\n # Now we are doing direct mapping from the fix graph coordinates to the moving coordinates\n # The application points of the displacement map are thus the transformed \"moving image\"-grid\n # and the displacement vectors are reversed\n if backwards:\n coords = np.hstack([grid_i[..., np.newaxis], grid_j[..., np.newaxis], grid_k[..., np.newaxis]])\n return LinearNDInterpolator(coords, np.reshape(disp_map, [-1, 3]))\n else:\n grid_i = (grid_i + disp_map[..., 0].flatten())\n grid_j = (grid_j + disp_map[..., 1].flatten())\n grid_k = (grid_k + disp_map[..., 2].flatten())\n\n coords = np.hstack([grid_i[..., np.newaxis], grid_j[..., np.newaxis], grid_k[..., np.newaxis]])\n return LinearNDInterpolator(coords, -np.reshape(disp_map, [-1, 3]))\n\n\ndef resample_segmentation(img, output_shape, preserve_range, threshold=None, gpu=True):\n # Preserve range can be a bool (keep or not the original dyn. range) or a list with a new dyn. range\n zoom_f = np.divide(np.asarray(output_shape), np.asarray(img.shape))\n\n if gpu:\n out_img = zoom_gpu(cupy.asarray(img), zoom_f, order=1) # order = 0 or 1\n else:\n out_img = zoom(img, zoom_f)\n if isinstance(preserve_range, bool):\n if preserve_range:\n range_min, range_max = np.amin(img), np.amax(img)\n out_img = min_max_norm(out_img)\n out_img = out_img * (range_max - range_min) + range_min\n elif isinstance(preserve_range, list):\n range_min, range_max = preserve_range\n out_img = min_max_norm(out_img)\n out_img = out_img * (range_max - range_min) + range_min\n\n if threshold is not None and out_img.min() < threshold < out_img.max():\n range_min, range_max = np.amin(out_img), np.amax(out_img)\n out_img[out_img > threshold] = range_max\n out_img[out_img < range_max] = range_min\n return cupy.asnumpy(out_img) if gpu else out_img\n\n\nif __name__ == '__main__':\n for dataset_name in DATASET_NAMES:\n dataset_loc = os.path.join(DATASET_LOCATION, dataset_name)\n dataset_files = os.listdir(dataset_loc)\n dataset_files.sort()\n dataset_files = [os.path.join(dataset_loc, f) for f in dataset_files if DATASET_FILENAME in f]\n\n iterator = tqdm(dataset_files)\n for file_path in iterator:\n file_num = int(re.findall('(\\d+)', os.path.split(file_path)[-1])[0])\n\n iterator.set_description('{} ({}): laoding data'.format(file_num, dataset_name))\n vol_file = h5py.File(file_path, 'r')\n # fix_vessels = vol_file[C.H5_FIX_VESSELS_MASK][..., 0]\n disp_map = vol_file[C.H5_GT_DISP][:]\n bbox = vol_file['parameters/bbox'][:]\n bbox_min = bbox[:3]\n bbox_max = bbox[3:] + bbox_min\n\n # Load vessel segmentation mask and resize to 64^3\n fix_labels = nib.load(os.path.join(DATASTE_RAW_FILES, 'segmentation-{:04d}.nii.gz'.format(file_num)))\n fix_vessels = fix_labels.slicer[..., 1]\n fix_vessels = resample_img(fix_vessels, np.eye(3))\n fix_vessels = np.asarray(fix_vessels.dataobj)\n fix_vessels = preprocess_image(fix_vessels)\n fix_vessels = resample_segmentation(fix_vessels, vol_file['parameters/first_reshape'][:], [0, 1], 0.3,\n gpu=True)\n fix_vessels = fix_vessels[bbox_min[0]:bbox_max[0], bbox_min[1]:bbox_max[1], bbox_min[2]:bbox_max[2]]\n fix_vessels = resample_segmentation(fix_vessels, [64] * 3, [0, 1], 0.3, gpu=True)\n fix_vessels = preprocess_image(fix_vessels)\n\n mov_vessels = preprocess_image(warp_volume(fix_vessels, disp_map))\n mov_skel = skeletonize_3d(mov_vessels)\n ### Fix the incorrect scaling ###\n disp_map *= 2\n bbox_size = np.asarray(bbox[3:]) # Only load the bbox size\n rescale_factors = 64 / bbox_size\n\n disp_map[..., 0] = np.multiply(disp_map[..., 0], rescale_factors[0])\n disp_map[..., 1] = np.multiply(disp_map[..., 1], rescale_factors[1])\n disp_map[..., 2] = np.multiply(disp_map[..., 2], rescale_factors[2])\n #################################\n\n iterator.set_description('{} ({}): getting graphs'.format(file_num, dataset_name))\n # Prepare displacement map\n disp_map_interpolator = build_displacement_map_interpolator(disp_map, backwards=False)\n\n # Get skeleton and graph\n fix_skel = skeletonize_3d(fix_vessels)\n fix_graph = get_graph_from_skeleton(fix_skel, subsample=True)\n mov_graph = get_graph_from_skeleton(mov_skel, subsample=True) # deform_graph(fix_graph, disp_map_interpolator)\n\n ##### TODO: ERASE Check the mov graph ######\n # check_mov_vessels = vol_file[C.H5_MOV_VESSELS_MASK][..., 0]\n # check_mov_vessels = preprocess_image(check_mov_vessels)\n # check_mov_skel = skeletonize_3d(check_mov_vessels)\n # check_mov_graph = get_graph_from_skeleton(check_mov_skel, subsample=True)\n ###########\n fix_pts, fix_nodes, fix_edges = graph_to_ndarray(fix_graph)\n mov_pts, mov_nodes, mov_edges = graph_to_ndarray(mov_graph)\n\n fix_bifur_loc, fix_bifur_id = get_bifurcation_nodes(fix_graph)\n mov_bifur_loc, mov_bifur_id = get_bifurcation_nodes(mov_graph)\n\n iterator.set_description('{} ({}): saving data'.format(file_num, dataset_name))\n pts_file_path, pts_file_name = os.path.split(file_path)\n pts_file_name = pts_file_name.replace(DATASET_FILENAME, 'points')\n pts_file_path = os.path.join(pts_file_path, pts_file_name)\n pts_file = h5py.File(pts_file_path, 'w')\n\n pts_file.create_dataset('fix/points', data=fix_pts)\n pts_file.create_dataset('fix/nodes', data=fix_nodes)\n pts_file.create_dataset('fix/edges', data=fix_edges)\n pts_file.create_dataset('fix/bifurcations', data=fix_bifur_loc)\n pts_file.create_dataset('fix/graph', data=fix_graph)\n pts_file.create_dataset('fix/img', data=fix_vessels)\n pts_file.create_dataset('fix/skeleton', data=fix_skel)\n pts_file.create_dataset('fix/centroid', data=vol_file[C.H5_FIX_CENTROID][:])\n\n pts_file.create_dataset('mov/points', data=mov_pts)\n pts_file.create_dataset('mov/nodes', data=mov_nodes)\n pts_file.create_dataset('mov/edges', data=mov_edges)\n pts_file.create_dataset('mov/bifurcations', data=mov_bifur_loc)\n pts_file.create_dataset('mov/graph', data=mov_graph)\n pts_file.create_dataset('mov/img', data=mov_vessels)\n pts_file.create_dataset('mov/skeleton', data=mov_skel)\n pts_file.create_dataset('mov/centroid', data=vol_file[C.H5_MOV_CENTROID][:])\n\n pts_file.create_dataset('parameters/voxel_size', data=vol_file['parameters/voxel_size'][:])\n pts_file.create_dataset('parameters/original_affine', data=vol_file['parameters/original_affine'][:])\n pts_file.create_dataset('parameters/isotropic_affine', data=vol_file['parameters/isotropic_affine'][:])\n pts_file.create_dataset('parameters/original_shape', data=vol_file['parameters/original_shape'][:])\n pts_file.create_dataset('parameters/isotropic_shape', data=vol_file['parameters/isotropic_shape'][:])\n pts_file.create_dataset('parameters/first_reshape', data=vol_file['parameters/first_reshape'][:])\n pts_file.create_dataset('parameters/bbox', data=vol_file['parameters/bbox'][:])\n pts_file.create_dataset('parameters/last_reshape', data=vol_file['parameters/last_reshape'][:])\n\n pts_file.create_dataset('displacement_map', data=disp_map)\n\n vol_file.close()\n pts_file.close()\n\n iterator.set_description('{} ({}): drawing plots'.format(file_num, dataset_name))\n num = pts_file_name.split('-')[-1].split('.hd5')[0]\n imgs_folder = os.path.join(IMGS_FOLDER, dataset_name, num)\n os.makedirs(imgs_folder, exist_ok=True)\n plot_skeleton(fix_vessels, fix_skel, fix_graph, os.path.join(imgs_folder, 'fix'), ['.pdf', '.png'])\n plot_skeleton(mov_vessels, mov_skel, mov_graph, os.path.join(imgs_folder, 'mov'), ['.pdf', '.png'])\n iterator.set_description('{} ({})'.format(file_num, dataset_name))\n","sub_path":"Centerline/centerline.py","file_name":"centerline.py","file_ext":"py","file_size_in_byte":12306,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"143468220","text":"import logging, json, urllib, urllib2, time, math, re\n\nfrom datetime import datetime, timedelta\nfrom dateutil.parser import parse as parse_datetime\nfrom dateutil.tz import tzlocal, tzutc, gettz\n#import pytz\n\n# set a timeout so that no request will hang forever\nimport socket; socket.setdefaulttimeout(120)\n\ndef timediff(dt=None, to=None):\n if dt is None:\n dt = datetime.now(to.tzinfo if to else None)\n if to is None:\n to = datetime.now(dt.tzinfo if dt else None)\n\n td = to - dt\n total_seconds = td.total_seconds()\n\n if total_seconds < 0:\n total_seconds = -total_seconds\n negative = True\n else:\n negative = False\n\n if total_seconds < 1:\n s = 'now'\n elif total_seconds < 60:\n s = '%ss' % int(total_seconds)\n elif total_seconds < 3600:\n s = '%sm' % int(math.floor(total_seconds/60.0))\n elif total_seconds < 86400:\n s = '%sh%sm' % (int(math.floor(total_seconds/3600.0)),\n int(math.floor(total_seconds/60.0) % 60))\n elif total_seconds < 172800:\n s = '%sd%sh' % (int(math.floor(total_seconds/86400.0)),\n int(math.floor(total_seconds/3600.0) % 24))\n else:\n # use calendar days\n s = '%sd' % (to.date() - dt.date()).days\n\n return '-%s' % s if negative else s\n\ndef tumblr_last_post(base_hostname, api_key):\n url = 'http://api.tumblr.com/v2/blog/%s/info?api_key=%s' % \\\n (base_hostname, api_key)\n response = json.loads(urllib.urlopen(url).read())\n if response['meta']['status'] == 404:\n raise ValueError('blog %s not found' % base_hostname)\n dt = datetime.utcfromtimestamp(response['response']['blog']['updated'])\n return (datetime.now(tzutc()).date() - dt.date()).days\n\ndef twitter_last_post(username):\n url = 'http://api.twitter.com/1/statuses/user_timeline.json?'\n url += urllib.urlencode({'screen_name': username})\n response = json.loads(urllib.urlopen(url).read())\n return (datetime.now(tzutc()).date()\n - parse_datetime(response[0]['created_at']).date()).days\n\ndef _get_ip_address(provider='http://icanhazip.com'):\n ip = urllib.urlopen(provider).read()\n if len(ip) <= 16:\n ip = ip.rstrip()\n return ip\n else:\n raise ValueError('No IP Found! Please update provider.')\n\ndef namecheap_domains(username, api_user, api_key, ip_address=None):\n \"\"\"see: http://developer.namecheap.com/docs/doku.php?id=overview:3.api.access\n for how to enable api access and obtain api key\n \"\"\"\n url = 'https://api.namecheap.com/xml.response?'\n url += urllib.urlencode({\n 'ApiUser': api_user,\n 'ApiKey': api_key,\n 'UserName': username,\n 'Command': 'namecheap.domains.getList',\n 'ClientIp': ip_address or _get_ip_address(),\n 'PageSize': 100,\n 'Page': 1,\n 'SortBy': 'EXPIREDATE',\n #'ListType': 'EXPIRING',\n })\n\n response = urllib.urlopen(url).read()\n\n # Example resonse entry:\n # \n\n matches = re.findall(r'',\n response)\n\n results = []\n\n for name, expiration in matches:\n # TODO: use date not datetime\n days = (datetime.strptime(expiration, '%m/%d/%Y') - datetime.now()).days\n results.append({'name': name, 'values': [days]})\n\n return {'board': results}\n\n# note that if you want to get text content (body) and the email contains\n# multiple payloads (plaintext/ html), you must parse each message separately.\n# use something like the following: (taken from a stackoverflow post)\ndef _get_first_text_block(self, email_message_instance):\n \"\"\"email_message_instance is the return of message_from_string method\"\"\"\n maintype = email_message_instance.get_content_maintype()\n if maintype == 'multipart':\n for part in email_message_instance.get_payload():\n if part.get_content_maintype() == 'text':\n return part.get_payload()\n elif maintype == 'text':\n return email_message_instance.get_payload()\n\ndef gmail_starred_emails(email, password, days_back=30):\n # TODO: pass a timezone argument\n import imaplib\n import email as parser\n #from datetime import datetime, timedelta\n #from dateutil.parser import parse\n #import pytz\n\n mail = imaplib.IMAP4_SSL('imap.gmail.com')\n mail.login(email, password)\n mail.list()\n mail.select('[Gmail]/Starred', readonly=True)\n\n results = []\n\n since = (datetime.now() - timedelta(days=days_back)).strftime('%d-%b-%Y')\n typ, data = mail.search(None, '(SINCE \"%s\")' % since)\n\n for num in data[0].split():\n typ, data = mail.fetch(num, '(RFC822)')\n for response_part in data:\n if isinstance(response_part, tuple):\n msg = parser.message_from_string(response_part[1])\n\n #for header in ['subject', 'to', 'from', 'date']:\n # print '%-8s: %s' % (header.upper(), msg[header])\n\n results.append({\n 'name': msg['subject'],\n #'values': [msg['from'],\n # parse(msg['date']).strftime('%Y-%m-%d')],\n 'values': [timediff(parse_datetime(msg['date']))],\n })\n\n results = results[::-1]\n\n mail.close()\n mail.logout()\n\n return {'board': results}\n\ndef twitter_followers(username):\n url = 'https://api.twitter.com/1/users/show.json?'\n url += urllib.urlencode({'screen_name': username})\n response = json.loads(urllib.urlopen(url).read())\n return response['followers_count']\n\ndef twitter_friends(username):\n url = 'https://api.twitter.com/1/users/show.json?'\n url += urllib.urlencode({'screen_name': username})\n response = json.loads(urllib.urlopen(url).read())\n return response['friends_count']\n\ndef trello_board_items(api_key, oauth_token, board_id, list_name):\n # TODO: pass a timezone argument\n #from dateutil.parser import parse\n #import pytz\n\n url = 'https://api.trello.com/1/boards/%s?' % board_id\n url += urllib.urlencode({\n 'lists': 'all',\n 'list_fields': 'name',\n 'key': api_key,\n 'token': oauth_token,\n })\n\n response = json.loads(urllib.urlopen(url).read())\n\n for list in response['lists']:\n if list_name == list['name']:\n list_id = list['id']\n break\n else:\n raise ValueError('List named %s not found on board' % list_name)\n\n url = 'https://api.trello.com/1/lists/%s/cards?' % list_id\n url += urllib.urlencode({\n 'fields': 'name,due',\n 'key': api_key,\n 'token': oauth_token,\n })\n\n response = json.loads(urllib.urlopen(url).read())\n\n results = []\n\n for card in response:\n if card.get('due'):\n due = timediff(to=parse_datetime(card['due']))#(parse(card['due']) - datetime.now(pytz.utc)).days\n else:\n due = ''\n\n results.append({\n 'name': card['name'],\n 'values': [due],\n })\n\n return {'board': results}\n\ndef google_calendar_events(calendar_id, api_key, regex_blacklist=None,\n days_ahead=10):\n # TODO: pass a timezone argument\n #import re\n #import pytz\n #from dateutil.parser import parse\n\n if not isinstance(calendar_id, list):\n calendar_ids = [calendar_id]\n else:\n calendar_ids = calendar_id\n\n events = []\n\n for calendar_id in calendar_ids:\n if '@' in calendar_id:\n calendar_id = urllib.quote(calendar_id)\n\n url = 'https://www.googleapis.com/calendar/v3/calendars/%s/events?' % \\\n calendar_id\n\n now = datetime.utcnow()\n time_max = now + timedelta(days=days_ahead)\n\n url += urllib.urlencode({\n 'key': api_key,\n #'orderBy': 'startTime',\n # Z specifies UTC timezone in iso format\n 'timeMax': time_max.isoformat('T') + 'Z', # upper bound start time\n 'timeMin': now.isoformat('T') + 'Z', # lower bound by end time\n })\n\n next_url = url\n\n while True:\n response = json.loads(urllib.urlopen(next_url).read())\n if not 'items' in response:\n break\n events.extend(response['items'])\n\n # TODO: parse events here\n\n if not 'nextPageToken' in response:\n break\n next_token = response['nextPageToken']\n next_url = url + '&pageToken=%s' % next_token\n\n data = set()\n\n # TODO: place this in function _parse_event\n for event in events:\n try:\n if regex_blacklist:\n if re.match(regex_blacklist, event['summary'], re.IGNORECASE):\n continue\n\n if 'recurrence' in event:\n value = event['recurrence'][0].split('FREQ=')[1].split(';')[0]\n if value == 'MONTHLY': value = 'MNTLY'\n if value == 'WEEKLY': value = 'WKLY'\n if value == 'YEARLY': value = 'YRLY'\n else:\n value = parse_datetime(event['start']['dateTime'])#(parse(event['start']['dateTime']) - datetime.now(pytz.utc)).days\n #results.append({\n # 'name': event['summary'],\n # 'values': [value],\n #})\n data.add((event['summary'], value))\n except KeyError:\n continue\n\n\n # will sort in ascending order by date\n last = datetime.now(tzutc()) + timedelta(days=days_ahead+1)#(3000, 1, 1, tzinfo=tzlocal())\n #results = sorted(results, key=lambda x: x['values'][0] if \\\n # not isinstance(x['values'][0], basestring) else last)\n data = sorted(data, key=lambda x: x[1] if \\\n not isinstance(x[1], basestring) else last)\n\n results = []\n for name, value in data:\n # TODO: abbreviate recurrence here\n results.append({\n 'name': name,\n 'values': [value if isinstance(value, basestring) else timediff(to=value)],\n })\n\n #if not isinstance(result['values'][0], basestring):\n # result['values'][0] = timediff(to=result['values'][0])\n\n\n return {'board': results}\n\ndef uptimerobot_status(api_key):\n url = 'http://api.uptimerobot.com/getMonitors?'\n url += urllib.urlencode({\n 'apiKey': api_key,\n 'format': 'json',\n 'noJsonCallback': 1,\n })\n\n response = json.loads(urllib.urlopen(url).read())\n\n results = []\n\n status_map = {\n '0': 'paused',\n '1': 'not checked yet',\n '2': 'up',\n '8': 'seems down',\n '9': 'down',\n }\n\n for monitor in response['monitors']['monitor']:\n results.append({\n 'name': monitor['friendlyname'],\n 'values': [status_map[monitor['status']]],\n })\n\n return {'board': results}\n\ndef evernote_count(api_key, notebook_name):\n \"\"\"The api key for your account can be obtained from\n https://www.evernote.com/api/DeveloperToken.action\n \"\"\"\n import thrift.protocol.TBinaryProtocol as TBinaryProtocol\n import thrift.transport.THttpClient as THttpClient\n import evernote.edam.userstore.UserStore as UserStore\n import evernote.edam.notestore.NoteStore as NoteStore\n\n userStoreUri = \"https://www.evernote.com/edam/user\"\n userStoreHttpClient = THttpClient.THttpClient(userStoreUri)\n userStoreProtocol = TBinaryProtocol.TBinaryProtocol(userStoreHttpClient)\n userStore = UserStore.Client(userStoreProtocol)\n\n noteStoreUrl = userStore.getNoteStoreUrl(api_key)\n noteStoreHttpClient = THttpClient.THttpClient(noteStoreUrl)\n noteStoreProtocol = TBinaryProtocol.TBinaryProtocol(noteStoreHttpClient)\n noteStore = NoteStore.Client(noteStoreProtocol)\n\n guid = None\n\n # List all of the notebooks in the user's account \n notebooks = noteStore.listNotebooks(api_key)\n #print \"Found \", len(notebooks), \" notebooks:\"\n for notebook in notebooks:\n if notebook.name == notebook_name:\n guid = notebook.guid\n break\n\n filter = NoteStore.NoteFilter()\n filter.notebookGuid = guid\n noteCount = noteStore.findNoteCounts(api_key, filter, False)\n if noteCount.notebookCounts is None:\n return 0\n return noteCount.notebookCounts[guid]\n\ndef pocket_items(api_key, username, password, state, type='unread'):\n url = 'https://readitlaterlist.com/v2/get?'\n url += urllib.urlencode({\n 'apikey': api_key,\n 'username': username,\n 'password': password,\n 'state': type or '',\n 'count': 20,\n })\n\n if 'since' in state:\n url += '&since=%s' % state['since']\n\n response = json.loads(urllib.urlopen(url).read())\n results = []\n\n if not response['list']:\n return\n\n for key, item in response['list'].iteritems():\n results.append({\n 'title': item['title'],\n 'link': item['url'],\n 'content': item.get('tags', ''),\n 'image': '',\n })\n\n state['since'] = int(time.time())\n\n return results\n\ndef runkeeper_last_activity(access_token, timezone='US/Eastern'):\n # get endpoints from https://api.runkeeper.com/user/\n request = urllib2.Request('https://api.runkeeper.com/fitnessActivities/')\n request.add_header('Authorization', 'Bearer %s' % access_token)\n result = json.loads(urllib2.urlopen(request).read())\n\n if not result['items']:\n return -1\n\n dt = parse_datetime(result['items'][0]['start_time'])\n # runkeeper is timezone naive\n dt = dt.replace(tzinfo=gettz(timezone))\n return (datetime.now(gettz(timezone)).date() - dt.date()).days\n\ndef runkeeper_distance(access_token, num_days=10, units='km'):\n # get endpoints from https://api.runkeeper.com/user/\n request = urllib2.Request('https://api.runkeeper.com/fitnessActivities/')\n request.add_header('Authorization', 'Bearer %s' % access_token)\n result = json.loads(urllib2.urlopen(request).read())\n\n now = datetime.now()\n\n total_distance = 0\n\n for item in result['items']:\n start_time = parse_datetime(item['start_time'])\n if (now - start_time).days > num_days:\n break\n\n #item['total_distance'] # meters\n #item['duration'] # seconds\n\n total_distance += item['total_distance']\n\n if units == 'km':\n return total_distance / 1000.0\n elif units == 'miles':\n return total_distance * 0.000621371\n elif units == 'meters':\n return total_distance\n else:\n raise ValueError('Unrecognized units: %s' % units)\n","sub_path":"methods.py","file_name":"methods.py","file_ext":"py","file_size_in_byte":14698,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"272402574","text":"# Copyright 2023 Huawei Technologies Co., Ltd\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ============================================================================\n\nimport os\nimport math\nimport torch\nimport argparse\nimport numpy as np\nfrom tqdm import trange\nfrom PIL import Image\nfrom torchvision import transforms\n\n\n#============================================================================\n# Functions\n#============================================================================\ndef preprocess(img, img_size, crop_pct):\n scale_size = int(math.floor(img_size / crop_pct))\n input_transform = transforms.Compose([\n transforms.Resize(scale_size, Image.BICUBIC),\n transforms.CenterCrop(img_size),\n transforms.ToTensor(),\n transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),\n ])\n return input_transform(img)\n\n\ndef img_preprocess(args):\n save_path = os.path.realpath(args.prep_image)\n if not os.path.exists(save_path):\n os.makedirs(save_path)\n\n in_files = os.listdir(args.image_path)\n file_list = []\n if not os.path.isfile(os.path.join(args.image_path, in_files[0])):\n for sub_dir in in_files:\n image_path = os.path.join(args.image_path, sub_dir)\n sub_file_list = os.listdir(image_path)\n for file in sub_file_list:\n file_list.append(os.path.join(image_path, file))\n else:\n for file in in_files:\n file_list.append(os.path.join(args.image_path, file))\n\n suffix_len = -5\n file_list.sort(key=lambda x:int(x[suffix_len-8:suffix_len]))\n for i in trange(int(np.ceil(len(file_list) / args.batch_size))):\n for idx in range(args.batch_size):\n file_index = i * args.batch_size + idx\n if file_index < len(file_list):\n file = file_list[file_index]\n input_image = Image.open(file).convert('RGB')\n image_tensor = preprocess(input_image, 224, 0.96).unsqueeze(0)\n else:\n image_tensor = torch.zeros([1,3,224,224])\n\n input_tensor = image_tensor if idx == 0 \\\n else torch.cat([input_tensor, image_tensor], dim=0)\n\n img = np.array(input_tensor).astype(np.float32)\n img.tofile(os.path.join(save_path, \"input_{:05d}.bin\".format(i)))\n\n\n#============================================================================\n# Main\n#============================================================================\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument('--image-path', type=str, default=\"/opt/npu/imageNet/val\")\n parser.add_argument('--prep-image', type=str, default=\"./prep_image_bs1\")\n parser.add_argument('--batch-size', type=int, default=1)\n opt = parser.parse_args()\n\n img_preprocess(opt)\n","sub_path":"ACL_PyTorch/contrib/cv/classfication/convmixer_1536_20/convmixer_preprocess.py","file_name":"convmixer_preprocess.py","file_ext":"py","file_size_in_byte":3333,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"531358963","text":"import pandas as pd\npd.set_option('display.max_columns',100)\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom textblob import TextBlob\n\ndata = pd.read_csv('LineItemData.csv')\nprint(data.head())\n\ndata = data['Description'].dropna()\nprint(data.head())\n\nprint('Count Vectors')\nvec = CountVectorizer()\nmatrix = vec.fit_transform(data)\nprint(pd.DataFrame(matrix.toarray(), columns=vec.get_feature_names()).head())\n\nprint('TFID Tokeniser')\nvec = TfidfVectorizer(use_idf=False, norm='l1')\nmatrix = vec.fit_transform(data)\nprint(pd.DataFrame(matrix.toarray(), columns=vec.get_feature_names()).head())\n\n##S Stemming words\n\ndef textblob_tokenizer(str_input):\n blob = TextBlob(str_input.lower())\n tokens = blob.words\n words = [token.stem() for token in tokens]\n return words\n\nprint('TextBlob')\nvec = CountVectorizer(tokenizer=textblob_tokenizer)\nmatrix = vec.fit_transform(data.tolist())\nprint(pd.DataFrame(matrix.toarray(), columns=vec.get_feature_names()).head())\n\nvec = TfidfVectorizer(tokenizer=textblob_tokenizer,\n stop_words='english',\n norm='l1',\n use_idf=True)\nmatrix = vec.fit_transform(data)\nprint(pd.DataFrame(matrix.toarray(), columns=vec.get_feature_names()).head())\n\nfrom sklearn.cluster import KMeans\ncluster_no = 3\nkm = KMeans(n_clusters=cluster_no)\nkm.fit(matrix)\n\nprint('Top terms per cluster:')\norder_centroids = km.cluster_centers_.argsort()[:, ::-1]\nterms = vec.get_feature_names()\nfor i in range(cluster_no):\n top_ten_words = [terms[ind] for ind in order_centroids[i :5]]\n print('Cluster {}: {}'.format(i, ' '.join(top_ten_words)))\n\n\nresult = pd.DataFrame()\nresult['text'] = data\nresult['category'] = km.labels_\nprint(result.head())\n","sub_path":"KMeansV2.py","file_name":"KMeansV2.py","file_ext":"py","file_size_in_byte":1801,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"618540988","text":"#使用K近邻对\"\"鸢尾(Iris)\"数据集进行物种分类\r\n#从sklearn.datasets导入iris数据加载器\r\nfrom sklearn.datasets import load_iris\r\n#从sklearn.model_selection import train_test_split用于 数据分割\r\nfrom sklearn.model_selection import train_test_split\r\n#从sklearn.preprocessing import StandardScaler数据标准化模块\r\nfrom sklearn.preprocessing import StandardScaler\r\n#sklearn.neighbors import KNeighborsClassifier K近邻分类器\r\nfrom sklearn.neighbors import KNeighborsClassifier\r\n\r\n#使用sklearn.metrics import classification_report模块对预测结果做更加详细的分析\r\nfrom sklearn.metrics import classification_report\r\n\r\n\r\n#使用加载器读取数据并且存入变量 iris\r\niris=load_iris()\r\n#查验数据规模\r\n#print(iris.data.shape)\r\n#查看数据说明\r\n#print(iris.DESCR)\r\n#print(type(iris))#\r\n#print(type(iris.data))#\r\n#print(type(iris.target))\r\n#print(iris.target)\r\nx_train,x_test,y_train,y_test=train_test_split(iris.data,iris.target,test_size=0.25,random_state=33)\r\n\r\n#对训练和测试的特征数据进行标准化\r\nss=StandardScaler()\r\nx_train=ss.fit_transform(x_train)\r\nx_test=ss.fit_transform(x_test)\r\n\r\n#使用K近邻分类器对测试数据进行类别预测,预测结果储存在变量 y_predict\r\nknc=KNeighborsClassifier()\r\nknc.fit(x_train,y_train)\r\ny_predict=knc.predict(x_test)\r\n\r\n#对K近邻分类器在鸢尾花数据上的预测性能进行评估\r\n#使用模型自带的评估函数进行准确性评测\r\nprint(\" the accuracy of K-Nearest neighbor classifier is \")\r\nprint(knc.score(x_test,y_test))\r\n\r\n#使用sklearn.metrics import classification_report模块对预测结果做更加详细的分析\r\nprint(\"the accuracy of k-nearest neighbor classifier is \")\r\nprint(classification_report(y_test,y_predict,target_names=iris.target_names))\r\n","sub_path":"python/Machine_Learning_in_action/KNC_iris.py","file_name":"KNC_iris.py","file_ext":"py","file_size_in_byte":1864,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"531713161","text":"import requests\nimport pylibgen\nimport pytest\n\n\ndef check_url(url):\n r = requests.head(url, allow_redirects=True, timeout=10)\n r.raise_for_status()\n\n\n@pytest.mark.parametrize(\"fh\", pylibgen.constants.FILEHOST_URLS)\ndef test_filehosts(fh):\n b = pylibgen.Book(id=1421206, md5=\"1af2c71c1342e850e1e47013b06f9eb9\")\n check_url(b.get_url(fh))\n","sub_path":"tests/test_book.py","file_name":"test_book.py","file_ext":"py","file_size_in_byte":348,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"6"} +{"seq_id":"259852381","text":"#Last name: Marchin\n#First Name: Denis\n#Student ID Number: 999061009\n#CDF login id: g3dmarch\n#Contact email address: d.marchin@mail.utoronto.ca\n#BlueMix credentials: username,password\n#UG/Grad?: UG\n\n#Last name: Chang\n#First Name: Alex\n#Student ID Number: 1000064681\n#CDF login id: c2changk\n#Contact email address: alexx.chang@mail.utoronto.ca\n#BlueMix credentials: username,password\n#UG/Grad?: UG\n\n#By submitting this file, I declare that my electronic submission is my\n#own work, and is in accordance with the University of Toronto Code of\n#Behaviour on Academic Matters and the Code of Student Conduct, as well\n#as the collaboration policies of this course.\n\nfrom operator import add\nimport csv, sys, re, sys, string\n\n########## CONSTANTS #############################\n\n\nNUM_OF_ATTRIBUTES = 16 # not including avg sentence, avg token and sentence length\nclasses = [0,4]\n\n\n############ WORD REFERENCE #######################\n\nfirst_person = [\"i\", \"me\", \"my\", \"mine\", \"we\", \"us\", \"our\", \"ours\"]\nsecond_person = [\"you\", \"your\", \"yours\", \"u\", \"ur\", \"urs\"]\nthird_person = [\"he\", \"him\", \"his\", \"she\", \"her\", \"hers\", \"it\", \"its\", \"they\", \"them\", \"their\", \"theirs\"]\nfuture_tense = [\"'ll\", \"will\", \"gonna\"]\nfuture_tenseVB = [\"going\", \"to\"]\ncommon_nouns = [\"NN\", \"NNS\"]\nproper_nouns = [\"NNP\", \"NNPS\"]\nadverbs = [\"RB\", \"RBR\", \"RBS\"]\nwh_words = [\"WDT\", \"WP\", \"WP$\", \"WRB\"]\nslang = ['smh', 'fwb', 'lmfao', 'lmao', 'lms', 'tbh', 'rofl', 'wtf', 'bff', 'wyd', 'lylc', 'brb',\n 'atm', 'imao', 'sml', 'btw', 'bw', 'imho', 'fyi', 'ppl', 'sob', 'ttyl', 'imo', 'ltr', 'thx', 'kk', 'omg',\n 'ttys', 'afn', 'bbs', 'cya', 'ez', 'f2f', 'gtr', 'ic', 'jk', 'k', 'ly', 'ya', 'nm', 'np', 'plz', 'ru',\n 'so', 'tc', 'tmi', 'ym', 'ur', 'u', 'sol']\n \n\n#Reference for our counter where it gives the attribute: index of attr in our counter list\n\n \n#counts[] = # attribute : index\n\t\t\t#'first': 0,\n #'second': 1,\n #'third': 2,\n #'conjunctions': 3,\n #'past_tense':4,\n #'future_tense':5,\n #'commas':6,\n #'colons':7,\n #'dashes':8,\n #'parentheses':9,\n #'ellipsis':10,\n #'common':11,\n #'proper':12,\n #'adverbs':13,\n #'wh':14,\n #'slang':15,\n #'upper':16 \n\n####################################################\n\ndef counter(tokens):\n\n\tcounts = []\n\t\n\t#used for Future Tense\n\tgoing_VB = 0\n\tto_VB = 0\n\n\tfor num in range(0, NUM_OF_ATTRIBUTES + 1):\n\t\tcounts.append(0)\n\n\tfor token in tokens:\n\n\t\tsplit_token = token.split(\"/\") # split token into the word and tag\n\t\tword = split_token[0] # actual word\n\t\ttag = split_token[1] # assigned tag\n\t\t\n\t\t# check pronouns\n\t\tif word.lower() in first_person: # check if word is a first person pronoun\n\t\t\tcounts[0] = counts[0] + 1\n\t\telif word.lower() in second_person: # check if word is a second person pronoun\n\t\t\tcounts[1] = counts[1] + 1\n\t\telif word.lower() in third_person: # check if word is a third person pronoun\n\t\t\tcounts[2] = counts[2] + 1\n\n\t\tif tag.upper() == \"CC\" :\n\t\t\tcounts[3] = counts[3] + 1 # count coordinating conjunctions\n\n\t\tif tag.upper() == \"VBD\" :\n\t\t\tcounts[4] = counts[4] + 1 # count past tense\n\n\t\tif word.lower() in future_tense: #count easy future tense\n\t\t\tcounts[5] = counts[5] + 1\n\t\t\t\t\t\n\t\telif word.lower() in future_tenseVB or tag.upper() == \"VB\":\n\t\t\t\n\t\t\tif word.lower() == \"going\":\n\t\t\t\tgoing_VB = 1\n\n\t\t\telif word.lower() == \"to\":\n\t\t\t\tto_VB = 1\n\n\t\t\telif tag.upper() == \"VB\" and going_VB == 1 and to_VB == 1:\n\t\t\t\tcounts[5] = counts[5] + 1\n\t\t\t\tgoing_VB = 0\n\t\t\t\tto_VB = 0\t\n\t\n\t\telse:\n\t\t\tif going_VB != 0 or to_VB != 0:\n\t\t\t\tgoing_VB = 0\n\t\t\t\tto_VB = 0\n\t\t\t\t\t\n\t\tif len(word) < 2:\n\n\t\t\tif word == \",\" :\n\t\t\t\tcounts[6] = counts[6] + 1 # count commas\n\n\t\t\tif word == \";\" or word == \":\" :\n\t\t\t\tcounts[7] = counts[7] + 1 # count colons and semicolons\n\n\t\t\tif word == \"-\" :\n\t\t\t\tcounts[8] = counts[8] + 1 # count dashes\n\t\t\n\t\telse:\n\t\t\tellipse = 0\n\t\t\tfor c in word:\n\t\t\n\t\t\t\tif c == \",\" :\n\t\t\t\t\tcounts[6] = counts[6] + 1 # count commas\n\n\t\t\t\tif c == \";\" or word == \":\" :\n\t\t\t\t\tcounts[7] = counts[7] + 1 # count colons and semicolons\n\n\t\t\t\tif c == \"-\" :\n\t\t\t\t\tcounts[8] = counts[8] + 1 # count dashes\n\n\t\t\t\tif ellipse < 3 and c == \".\" : \n\t\t\t\t\tellipse += 1\n\n\t\t\t\telif ellipse > 2 and c == \".\" :\n\t\t\t\t\tcounts[9] = counts[9] + 1 # count ellipsis only if it is a group of 3 periods\n\t\t\t\t\tellipse = 0\n\n\t\tif tag.upper() in common_nouns:\n\t\t\tcounts[10] = counts[10] + 1 # count common nouns\n\n\t\tif tag.upper() in proper_nouns:\n\t\t\tcounts[11] = counts[11] + 1 # count proper nouns\n\n\t\tif tag.upper() in adverbs:\n\t\t\tcounts[12] = counts[12] + 1 # count adverbs\n\n\t\tif tag.upper() in wh_words:\n\t\t\tcounts[13] = counts[13] + 1 # count wh words\n\n\t\tif word.lower() in slang:\n\t\t\tcounts[14] = counts[14] + 1 # count slang words\n\n\t\tif word == word.upper() and len(word) > 1:\n\t\t\tcounts[15] = counts[15] + 1 # count all uppercase words\n\t\t\n\treturn counts\n\n\ndef process(tokens):\n\t\n\tarffdict = counter(tokens)\n\n\treturn arffdict\n \ndef getclass(token):\n\t\n\ttweetclass = re.findall('\\d+', token[0])\n\treturn int(tweetclass[0])\n\ndef get_sentence_length(tokens):\n\t\n\treturn len(tokens)\n\n\ndef get_token_length(tokens):\n\t\n\texclude = set(string.punctuation)\n\ttoken_lengths = []\n\t\n\tfor token in tokens:\n\t\tsplit_token = token.split(\"/\") # split token into the word and tag\n\n\t\ts = ''.join(c for c in split_token[0] if c not in exclude)\t\t#since we have defined our twtt file to always split puncuations from words\n\t\t\n\t\tif s != '':\n\t\t\ttoken_lengths.append(len(split_token[0]))\t#hyphens are also split from the words as well\t \n\t\t\t\n\treturn token_lengths\n\n\t\n\t\ndef output(fout, arff, tweetclass, sentences, sentence_len, token_len):\n\n\tif sentences != 0:\n\t\tavg_sentence_len = sum(sentence_len) / sentences\n\telse:\n\t\tavg_sentence_len = 0\n\t\n\tif len(token_len) != 0:\n\t\tavg_token_len = sum(token_len) / len(token_len)\n\telse:\n\t\tavg_token_len = 0\n\t\t\n\tfor current in arff:\n\t\tfout.write(str(current) + \",\")\n\tfout.write(str(avg_sentence_len) + \",\")\n\tfout.write(str(avg_token_len) + \",\")\n\tfout.write(str(sentences) + \",\")\n\tfout.write(str(tweetclass) + \"\\n\")\n\t\n\treturn 0\n\ndef write_start(fout):\n\tfout.write(\"@relation tweets\\n\")\n\tfout.write(\"\\n\")\n\tfout.write(\"@attribute first_person_count numeric\\n\")\n\tfout.write(\"@attribute second_person_count numeric\\n\")\n\tfout.write(\"@attribute third_person_count numeric\\n\")\n\tfout.write(\"@attribute coordinating_conjunctions numeric\\n\")\n\tfout.write(\"@attribute past_tense_verbs numeric\\n\")\n\tfout.write(\"@attribute future_tense_verbs numeric\\n\")\n\tfout.write(\"@attribute commas numeric\\n\")\n\tfout.write(\"@attribute colons numeric\\n\")\n\tfout.write(\"@attribute dashes numeric\\n\")\n\tfout.write(\"@attribute parentheses numeric\\n\")\n\tfout.write(\"@attribute ellipses numeric\\n\")\n\tfout.write(\"@attribute common_nouns numeric\\n\")\n\tfout.write(\"@attribute proper_nouns numeric\\n\")\n\tfout.write(\"@attribute adverbs numeric\\n\")\n\tfout.write(\"@attribute wh_words numeric\\n\")\n\tfout.write(\"@attribute modern_slang_acronyms numeric\\n\")\n\tfout.write(\"@attribute upper_case numeric\\n\")\n\tfout.write(\"@attribute average_length_of_sentences numeric\\n\")\n\tfout.write(\"@attribute average_length_of_tokens numeric\\n\")\n\tfout.write(\"@attribute number_of_senteces numeric\\n\")\n\tfout.write(\"@attribute positive_class {0,4}\\n\")\n\tfout.write(\"\\n\")\n\tfout.write(\"@data\\n\")\n\n\treturn 0;\n\t\t\n#________MAIN____________________\n\ninput_file = sys.argv[1]\noutput_file = sys.argv[2]\n#if (sys.argv[3]):\n\t\n\t#error check for sys arg >0\n#\tdatapoints = sys.argv[3] \n\t\n#\tfor c in classes:\n#\t\tdatacount['c'] = datapoints\n\t\t\n\nf = open(input_file)\nraw_data = f.readlines()\nf_out = open(output_file, \"w\")\n\n# write relation & attributes\nwrite_start(f_out)\n\ntweet = []\npattern = re.compile(\"\")\n\ntweetclass = -1\n\n\narff = []\nnew_arff = []\nsentences = 0\nsentence_len = []\ntoken_len = []\ni = 0\nfor line in raw_data:\n\ttokens = line.split()\n\n\tif pattern.match(str(tokens[0])): \n\n\t\tif tweetclass == -1:\n\t\t\ttweetclass = getclass(tokens)\n\t\telse: #signifies the end of the tweet\n\t\t\toutput(f_out, arff, tweetclass, sentences, sentence_len, token_len)\n\t\t\tarff = []\n\t\t\tsentences = 0\n\t\t\tsentence_len = []\n\t\t\ttoken_len = []\n\t\t\ttweetclass = getclass(tokens)\n\telse:\n\t\tif arff == []:\n\t\t\tarff = process(tokens)\n\t\t\tsentences += 1\n\t\t\tsentence_len.append(get_sentence_length(tokens))\n\t\t\ttoken_len.extend(get_token_length(tokens))\n\t\telse:\n\t\t\tnew_arff = process(tokens)\n\t\t\t#print(new_arff)\n\t\t\tarff = map(add, arff, new_arff)\n\t\t\tnew_arff = []\n\t\t\tsentences += 1\n\t\t\tsentence_len.append(get_sentence_length(tokens))\n\t\t\ttoken_len.extend(get_token_length(tokens))\n\t\t\t\noutput(f_out, arff, tweetclass, sentences, sentence_len, token_len) #last output as loop exits; it is needed\n\t\t\t\t\n\n\n","sub_path":"buildarff.py","file_name":"buildarff.py","file_ext":"py","file_size_in_byte":8924,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"6"} +{"seq_id":"430022966","text":"# This code is part of Qiskit.\n#\n# (C) Copyright IBM 2021.\n#\n# This code is licensed under the Apache License, Version 2.0. You may\n# obtain a copy of this license in the LICENSE.txt file in the root directory\n# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.\n#\n# Any modifications or derivative works of this code must retain this\n# copyright notice, and modified files need to carry a notice indicating\n# that they have been altered from the originals.\n\"\"\"\nComposite Experiment data class.\n\"\"\"\n\nfrom typing import Optional, Union, List\nfrom qiskit.result import marginal_counts\nfrom qiskit.exceptions import QiskitError\nfrom qiskit_experiments.framework.experiment_data import ExperimentData\n\n\nclass CompositeExperimentData(ExperimentData):\n \"\"\"Composite experiment data class\"\"\"\n\n def __init__(\n self,\n experiment,\n backend=None,\n job_ids=None,\n ):\n \"\"\"Initialize experiment data.\n\n Args:\n experiment (CompositeExperiment): experiment object that generated the data.\n backend (Backend): Optional, Backend the experiment runs on. It can either be a\n :class:`~qiskit.providers.Backend` instance or just backend name.\n job_ids (list[str]): Optional, IDs of jobs submitted for the experiment.\n\n Raises:\n ExperimentError: If an input argument is invalid.\n \"\"\"\n\n super().__init__(\n experiment,\n backend=backend,\n job_ids=job_ids,\n )\n\n # Initialize sub experiments\n self._components = [\n expr.__experiment_data__(expr, backend) for expr in experiment._experiments\n ]\n\n def __str__(self):\n line = 51 * \"-\"\n n_res = len(self._analysis_results)\n status = self.status()\n ret = line\n ret += f\"\\nExperiment: {self.experiment_type}\"\n ret += f\"\\nExperiment ID: {self.experiment_id}\"\n ret += f\"\\nStatus: {status}\"\n if status == \"ERROR\":\n ret += \"\\n \"\n ret += \"\\n \".join(self._errors)\n ret += f\"\\nComponent Experiments: {len(self._components)}\"\n ret += f\"\\nCircuits: {len(self._data)}\"\n ret += f\"\\nAnalysis Results: {n_res}\"\n ret += \"\\n\" + line\n if n_res:\n ret += \"\\nLast Analysis Result:\"\n ret += f\"\\n{str(self._analysis_results.values()[-1])}\"\n return ret\n\n def component_experiment_data(\n self, index: Optional[Union[int, slice]] = None\n ) -> Union[ExperimentData, List[ExperimentData]]:\n \"\"\"Return component experiment data\"\"\"\n if index is None:\n return self._components\n if isinstance(index, (int, slice)):\n return self._components[index]\n raise QiskitError(f\"Invalid index type {type(index)}.\")\n\n def _add_single_data(self, data):\n \"\"\"Add data to the experiment\"\"\"\n # TODO: Handle optional marginalizing IQ data\n metadata = data.get(\"metadata\", {})\n if metadata.get(\"experiment_type\") == self._type:\n\n # Add parallel data\n self._data.append(data)\n\n # Add marginalized data to sub experiments\n if \"composite_clbits\" in metadata:\n composite_clbits = metadata[\"composite_clbits\"]\n else:\n composite_clbits = None\n for i, index in enumerate(metadata[\"composite_index\"]):\n sub_data = {\"metadata\": metadata[\"composite_metadata\"][i]}\n if \"counts\" in data:\n if composite_clbits is not None:\n sub_data[\"counts\"] = marginal_counts(data[\"counts\"], composite_clbits[i])\n else:\n sub_data[\"counts\"] = data[\"counts\"]\n self._components[index]._add_single_data(sub_data)\n","sub_path":"qiskit_experiments/framework/composite/composite_experiment_data.py","file_name":"composite_experiment_data.py","file_ext":"py","file_size_in_byte":3836,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"6"} +{"seq_id":"68281201","text":"import os\nimport boto3\nfrom botocore.exceptions import ClientError\nimport requests\nimport arrow\nimport csv\nfrom time import sleep\nfrom decimal import *\n\nBASE_URL = os.environ['PSE_BASE_URL']\nQUOTE_API_PATH = os.environ['PSE_QUOTE_API_PATH']\nAPI_ENDPOINT = \"{}{}\".format(BASE_URL, QUOTE_API_PATH)\nTRADING_DATE_FORMAT = \"YYYY-MM-DD HH:mm:ss\"\nBUCKET_NAME = \"psedata\"\nPRICE_DAILY_PREFIX = \"price_daily\"\nCOMPANY_LIST_NAME = \"company_list.csv\"\nTMP_COMPANY_LIST = \"/tmp/{}\".format(COMPANY_LIST_NAME)\nTMP_DIRECTORY = \"/tmp\"\nCHUNK_SIZE = 15\n\ns3_client = boto3.client(\"s3\")\ndynamodb = boto3.resource(\"dynamodb\", region_name=os.environ['DYNAMODB_REGION'],\n endpoint_url=os.environ['DYNAMODB_ENDPOINT'])\ndynamodb_table = dynamodb.Table(os.environ['DYNAMODB_TABLE'])\n\n\ndef lambda_handler(event, context):\n target_date = get_event_datetime(event['time'])\n target_file_name = \"{}.csv\".format(target_date.isoformat())\n s3_key_name = \"{}/{}\".format(PRICE_DAILY_PREFIX, target_file_name)\n working_file_path = \"{}/{}\".format(TMP_DIRECTORY, target_file_name)\n\n prepare_local_working_file(working_file_path, s3_key_name)\n last_completed_stock_code = get_last_completed_stock_code(working_file_path)\n\n company_list = get_company_list()\n if last_completed_stock_code:\n print(\"Fast-forward after {}\".format(last_completed_stock_code))\n company_list = filter_completed_stock_codes(last_completed_stock_code, company_list)\n\n # If there is no previous stock code detected write the header\n if not last_completed_stock_code:\n header = \"STOCK_CODE,OPEN,LOW,HIGH,CLOSE,AVG_PRICE,VOLUME,VALUE\\n\"\n write_price_actions(working_file_path, [header])\n\n chunk = []\n for price_action in request_price_actions(target_date, company_list):\n # Only write when there is movement\n if price_action.get(\"open\"):\n dynamodb_write(price_action)\n\n pa = \"{},{},{},{},{},{},{},{}\\n\".format(price_action.get(\"stock_code\"),\n price_action.get(\"open\"),\n price_action.get(\"low\"),\n price_action.get(\"high\"),\n price_action.get(\"close\"),\n price_action.get(\"avg_price\"),\n price_action.get(\"volume\"),\n price_action.get(\"value\"))\n\n print(pa)\n chunk.append(pa)\n\n if len(chunk) == CHUNK_SIZE:\n print(\"Chunk full... Uploading to S3.\")\n write_price_actions(working_file_path, chunk)\n upload_working_file(working_file_path, s3_key_name)\n\n chunk = []\n\n # Wait 0.25 sec in between requests\n sleep(0.25)\n\n # Write and upload remaining chunk that did not meet the CHUNK_SIZE maximum\n if len(chunk) > 0:\n write_price_actions(working_file_path, chunk)\n upload_working_file(working_file_path, s3_key_name)\n\n print(\"Job done!\")\n\n\ndef request_price_actions(target_date, company_list):\n trading_date = target_date.isoformat()\n\n for company in company_list:\n response = requests.post(API_ENDPOINT, data={\"security\": company.get(\"security_id\")}, headers={\"referer\": BASE_URL})\n\n if response:\n json = response.json()\n records = json.get(\"records\")\n today = get_target_date(target_date, records)\n\n if today:\n price_action = {\n \"stock_code\": company.get(\"stock_code\"),\n \"trading_date\": trading_date,\n \"open\": today.get(\"sqOpen\"),\n \"low\": today.get(\"sqLow\"),\n \"high\": today.get(\"sqHigh\"),\n \"close\": today.get(\"sqClose\"),\n \"avg_price\": today.get(\"avgPrice\"),\n \"volume\": today.get(\"totalVolume\"),\n \"value\": today.get(\"totalValue\")\n }\n else:\n price_action = {\n \"stock_code\": company.get(\"stock_code\"),\n \"trading_date\": trading_date,\n \"open\": None,\n \"low\": None,\n \"high\": None,\n \"close\": None,\n \"avg_price\": None,\n \"volume\": None,\n \"value\": None\n }\n\n yield price_action\n\n\ndef get_event_datetime(event_date_str):\n return arrow.get(event_date_str).date()\n\n\ndef get_company_list():\n with open(TMP_COMPANY_LIST, \"wb\") as file:\n s3_client.download_fileobj(BUCKET_NAME, COMPANY_LIST_NAME, file)\n\n company_details = []\n with open(TMP_COMPANY_LIST, \"r\") as file:\n reader = csv.reader(file, delimiter=\",\", quotechar='\"')\n next(reader)\n\n for row in reader:\n company_details.append({\n \"stock_code\": row[0],\n \"company_name\": row[1],\n \"company_id\": row[2],\n \"security_id\": row[3]\n })\n\n return company_details\n\n\ndef filter_completed_stock_codes(after_stock_code, company_list):\n start_new_company_list = False\n _company_list = []\n\n for c in company_list:\n if not start_new_company_list and c.get(\"stock_code\") == after_stock_code:\n start_new_company_list = True\n continue\n if start_new_company_list:\n _company_list.append(c)\n\n return _company_list\n\n\ndef get_target_date(target_datetime, records):\n # The PSE API data is sorted from latest to oldest. So if the target_datetime\n # is the current date then this iteration would just execute once and returns.\n for r in records:\n raw_target_date = r.get(\"tradingDate\")\n trading_date = arrow.get(raw_target_date, TRADING_DATE_FORMAT)\n\n if target_datetime == trading_date.date():\n return r\n\n return False\n\n\ndef write_price_actions(working_file_path, price_actions):\n with open(working_file_path, \"a\") as file:\n for pa in price_actions:\n file.write(pa)\n\n\ndef upload_working_file(source_file_path, key_name):\n s3_client.upload_file(source_file_path, BUCKET_NAME, key_name, ExtraArgs={\n 'StorageClass': 'STANDARD_IA'\n })\n\n\ndef prepare_local_working_file(local_working_file_path, key_name):\n file_check = None\n try:\n file_check = s3_client.head_object(Bucket=BUCKET_NAME, Key=key_name)\n except ClientError:\n print(\"Object does not exist\")\n pass\n\n if file_check:\n print(\"Object exist, downloading\")\n with open(local_working_file_path, \"wb\") as file:\n s3_client.download_fileobj(BUCKET_NAME, key_name, file)\n else:\n # Create or truncate file if it exist in local for some reason\n with open(local_working_file_path, \"w\"):\n pass\n\n\ndef get_last_completed_stock_code(local_working_file_path):\n with open(local_working_file_path) as file:\n lines = file.readlines()\n lines_length = len(lines)\n\n # If it's empty or just the header row\n if lines_length <= 1:\n return False\n\n last_line = lines[lines_length - 1]\n values = last_line.split(\",\")\n stock_code = values[0]\n\n return stock_code.strip()\n\n\ndef dynamodb_write(price_action):\n item = {\n \"stock_code\": price_action.get(\"stock_code\"),\n \"trading_date\": price_action.get(\"trading_date\"),\n \"open\": dynamodb_decimal(price_action.get(\"open\")),\n \"low\": dynamodb_decimal(price_action.get(\"low\")),\n \"high\": dynamodb_decimal(price_action.get(\"high\")),\n \"close\": dynamodb_decimal(price_action.get(\"close\")),\n \"volume\": dynamodb_decimal(price_action.get(\"volume\"))\n }\n\n dynamodb_table.put_item(Item=item)\n\n\n# See https://github.com/boto/boto3/issues/665 why this needs to be done\ndef dynamodb_decimal(value):\n return Decimal(str(value))\n","sub_path":"lambda/price_daily/lambda_function.py","file_name":"lambda_function.py","file_ext":"py","file_size_in_byte":8027,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"6"} +{"seq_id":"295031456","text":"\n#Cleans a string\ndef clean_text(post):\n #post = re.sub(\"(@[A-Za-z0-9]+)|([^0-9A-Za-z \\t])|(\\w+:\\/\\/\\S+)\", \"\", post)\n #text_string = ' '.join(re.sub(\"(@[A-Za-z0-9]+)|([^0-9A-Za-z \\t])|(\\w+:\\/\\/\\S+)\",\" \",post).split())\n #post_noht = [i[1:] for i in post.split() if i.startswith(\"#\")]\n #post = ' '.join(post_noht).strip()\n post_tokens = tokenizer.tokenize(post)\n #post_tokens = word_tokenize(post)\n tokens_pos = list(range(0,len(post_tokens)))\n remove_pos = []\n for i in range(0,len(post_tokens)):\n re_match_hash = re.search('[#]+[0-9|A-Z|a-z]' ,str(post_tokens[i].encode('unicode_escape')))\n re_match_emoji = re.search('[u|U]+[0-9|fe]' ,str(post_tokens[i].encode('unicode_escape')))\n if re_match_hash is not None:\n remove_pos.append(i)\n if re_match_emoji is not None:\n remove_pos.append(i)\n text_pos = list(set(tokens_pos) - set(remove_pos))\n string_tokens = [post_tokens[k] for k in text_pos]\n text_string = ' '.join(post_tokens).strip()\n return text_string\n\n#Function for formating emojis to the dictionary form\ndef clean_emoji(emo):\n emo = emo.upper()\n emo = emo.split(' ')\n filtered_emo = []\n for i in range(len(emo)):\n e = emo[i].replace(\"B'\",\"\")\n e = e.replace(\"'\",\"\")\n e = e.replace(\",\",\"\") \n e = e.replace('\\\\\\\\','\\\\')\n if \"\\\\U\" in e:\n filtered_emo.append(e)\n return list(filtered_emo)\n\n#Emoji sentiment score: Send a string of emojis and get back sentiment score\ndef get_emoji_sentiment(emoji_string):\n emoji_text = []\n emoji_sentiment = []\n for line in emoji_string:\n if line in emoj_list:\n eindx = [z for z,x in enumerate(emoj_list) if x == line]\n if len(eindx) > 0:\n emoji_text.append(emoj['name'][eindx[0]])\n emoji_sentiment.append(emoj['score'][eindx[0]]) \n return emoji_sentiment\n \n#This is the ultimate function!\ndef divide_post(post, username):\n #Read emoji dictionary\n emoj = pd.read_csv(\"C:/Reachbird/data/emoji_dict.csv\")\n emoj_list = list(emoj['code'])\n \n post_tokens = tknzr.tokenize(post)\n tokens_pos = list(range(0,len(post_tokens)))\n unicode_pos = []\n hashtag_pos = [] \n for i in range(0,len(post_tokens)):\n re_match = re.search('[u|U]+[0-9|fe]' ,str(post_tokens[i].encode('unicode_escape')))\n if re_match is not None:\n unicode_pos.append(i)\n for i in range(0,len(post_tokens)):\n re_match = re.search('[#]+[0-9|A-Z|a-z]' ,str(post_tokens[i].encode('unicode_escape')))\n if re_match is not None:\n hashtag_pos.append(i)\n \n text_pos = list(set(tokens_pos) - (set().union(hashtag_pos,unicode_pos))) \n \n if len(unicode_pos) > 0:\n emoji_tokens = [post_tokens[k] for k in unicode_pos]\n emoji_string = ' '.join(emoji_tokens).strip()\n emoji_string = clean_emoji(str(emoji_string.encode('unicode_escape')))\n sentiment_array = get_emoji_sentiment(emoji_string)\n if len(sentiment_array) > 0:\n sum_sentiment_score = sum(sentiment_array)\n mean_sentiment_score = sum(sentiment_array)/len(sentiment_array)\n else:\n emoji_string = []\n sum_sentiment_score = 0\n mean_sentiment_score = 0\n \n if len(hashtag_pos) > 0:\n hashtag_tokens = [post_tokens[k] for k in hashtag_pos]\n hashtag_string = ' '.join(hashtag_tokens).strip()\n else:\n hashtag_string= []\n\n if len(text_pos) > 0:\n string_tokens = [post_tokens[k] for k in text_pos]\n text_string = ' '.join(string_tokens).strip()\n text_string = clean_text(text_string)\n else:\n text_string = []\n \n timestamp = datetime.now()\n \n dict_x = collections.defaultdict(list)\n dict_x['username'] = username\n dict_x['hour'] = timestamp.hour\n dict_x['timestamp'] = timestamp\n dict_x['text'] = text_string\n dict_x['hashtags'] = hashtag_string\n dict_x['sum_emoji_sentiment'] = sum_sentiment_score\n dict_x['mean_emoji_sentiment'] = mean_sentiment_score\n dict_x['caption_length'] = len(post)\n\n if not hashtag_string:\n dict_x['count_hashtags'] = len(hashtag_string)\n dict_x['has_hashtags'] = 0\n else:\n dict_x['count_hashtags'] = len(tknzr.tokenize(hashtag_string))\n dict_x['has_hashtags'] = 1\n\n dict_x['count_emojis'] = len(emoji_string)\n if len(emoji_string) > 0:\n dict_x['has_emojis'] = 1\n else:\n dict_x['has_emojis'] = 0\n \n for h in range(0,24):\n ind = \"hour_\" + str(h)\n if h == timestamp.hour:\n dict_x[ind] = 1\n else:\n dict_x[ind] = 0\n \n return dict_x\n","sub_path":"utilities/format_text.py","file_name":"format_text.py","file_ext":"py","file_size_in_byte":4717,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"6"} +{"seq_id":"264002477","text":"import pymysql\n\n# DB接続情報\ndef getConnection():\n return pymysql.connect(\n host = \"127.0.0.1\",\n db = \"study_info\",\n user = \"root\",\n password = \"\",\n charset = \"utf8\",\n cursorclass = pymysql.cursors.DictCursor\n )\n\n# DBにSELECT構文で接続(DB接続情報、 SQL構文)\ndef db_check(connection, sql):\n cursor =connection.cursor()\n cursor.execute(sql)\n result_data = cursor.fetchall()\n cursor.close()\n return result_data\n\ndef db_check_one(connection, sql):\n cursor = connection.cursor()\n cursor.execute(sql)\n result_data_one = cursor.fetchone()\n cursor.close()\n return result_data_one\n\n","sub_path":"myapp_2/modules/connect.py","file_name":"connect.py","file_ext":"py","file_size_in_byte":668,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"6"} +{"seq_id":"522699074","text":"from kivy.app import App\r\nfrom kivy.uix.label import Label\r\nfrom kivy.uix.image import Image\r\nfrom kivy.uix.widget import Widget\r\nfrom kivy.uix.button import Button\r\nfrom kivy.graphics import Rectangle, Ellipse, Color, Line\r\nfrom kivy.uix.screenmanager import Screen, ScreenManager\r\n\r\nfrom kivy.core.window import Window\r\nfrom kivy.clock import Clock\r\n#import time\r\n\r\nfrom random import randint\r\nfrom random import random as rand\r\n\r\nfrom kivy.base import EventLoop\r\n\r\nfrom kivy.core.audio import SoundLoader\r\n\r\n\r\nimport sqlite3\r\n\r\n###database\r\nconn = sqlite3.connect('highScore.db') \t\t\t\t\t\t\t#create if not exists and connect to the database named 'highScore.db'\r\nc = conn.cursor() \t\t\t\t\t\t\t#create a cursor object to add/manipulate the data in it, below operations\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t#are all done by cursor\r\n\r\nc.execute('''Create TABLE if not exists highscore('high')''')\t#create a table if not exists named 'highscore' with only one column 'high'\r\n#c.execute(\"INSERT INTO highscore(high) VALUES(?)\", [0]) #uncomment only when initially creating the database(running the script for first time\t\t#initially adding value while creating db\r\nc.execute(\"SELECT * FROM highscore\")\t\t\t\t\t\t\t#select all the the rows of the table named 'highscore'\r\n\r\nrows_list = c.fetchall()\t\t\t\t\t\t\t\t\t\t#Return the rows as list with each row is a list of cells in it\t\t\t\t\t\t\t\t\t\t\t\r\n\r\nhighscore = int(rows_list[0][0])\r\nconn.commit()\r\nconn.close()\r\n\r\ndef score_update(new_score):\r\n\tglobal highscore\r\n\tconn = sqlite3.connect('highScore.db')\r\n\tc = conn.cursor()\r\n\tc.execute(\"SELECT * FROM highscore\")\r\n\trows = c.fetchall()\t\t\t\t\t\t\t\t\t\t\t\t\r\n\thighscore = rows[0][0]\r\n\tif new_score > highscore:\r\n\t\tc.execute(\"DELETE FROM highscore\")\r\n\t\tc.execute(\"INSERT INTO highscore(high) VALUES(?)\", [new_score])\r\n\t\thighscore = new_score\r\n\tconn.commit()\r\n\tconn.close()\r\n###database\r\n\r\n\r\n#Important Note Always first set the device screen size \r\n#Window.size = (320, 550)\r\nx_0, y_0 = Window.size\r\n\r\nlime_green = (124/256, 252/256, 0/ 256, 1)\r\n\r\nclass MainApp(App):\r\n\r\n\t\r\n\tdef build(self):\r\n\t\t\r\n\t\tself.sound1 = SoundLoader.load('oldschool_drums.wav')\r\n\t\tself.sound1.loop = True\r\n\t\tself.sound1.play()\r\n\r\n\t\tself.game_over_sound = SoundLoader.load('game_over.wav')\r\n\t\tself.game_over_sound.bind(on_stop=self.new_game)\r\n\r\n\r\n\r\n\t\t\r\n\r\n\r\n\t\tself.ScreenM = ScreenManager()\r\n\t\tself.s0 = Screen_begin(name='begin')\r\n\t\tself.ScreenM.add_widget(self.s0)\r\n\r\n\t\tself.ScreenM.bind(on_touch_down=self.update_0)\r\n\r\n\t\tself.name_ = '1'\r\n\t\tself.collision_first = False\r\n\t\treturn self.ScreenM\r\n\r\n\r\n\tdef update_0(self, par1, par2):\r\n\t\tif self.ScreenM.current_screen != self.ScreenM.screens[0]:\r\n\t\t\treturn\r\n \r\n\t\tself.s1 = Screen(name='first')\r\n\t\tself.game = FlappyGame()\r\n\t\tself.s1.add_widget(self.game)\r\n\t\t#Clock.schedule_interval(self.game.update, 1/60)\r\n\t\tClock.schedule_interval(self.update, 1/60)\r\n\t\tself.ScreenM.add_widget(self.s1)\r\n\t\t\r\n\t\t\r\n\t\tself.ScreenM.current = self.ScreenM.screens[-1].name\r\n\t\t#del self.ScreenM.screens[-2]\r\n\r\n\r\n\tdef update(self, dt):\r\n\t\tif self.collision_first == True:\r\n\t\t\tself.game_over()\r\n\t\t\treturn\r\n\r\n\t\t\r\n\t\t\r\n\t\tif self.game.greenPipes.collided == True:\r\n\t\t\tself.game.bird.v_0 = 19\r\n\t\t\tself.game.bird.g = -20\r\n\r\n\t\t\tself.collision_first = True\r\n\t\t\tself.game.bird.collision_check = True\r\n\t\t\tscore_update(self.game.bird.score)\r\n\r\n\t\t\tself.game_over()\r\n\r\n\r\n\r\n\r\n\tdef game_over(self):\r\n\t\tself.sound1.stop()\r\n\t\tself.game_over_sound.play()\r\n\t\t#Clock.schedule_once(self.new_game, 3)\r\n\t\t\r\n\t\t\r\n\t\tif self.game.bird.Bird_.pos[1] > -10:\r\n\t\t\tself.game.bird.key_time = 0\r\n\t\t\t\r\n\t\t#else:\r\n\t\t#\tself.new_game()\r\n\t\t\r\n\r\n\tdef new_game(self, widget):\r\n\r\n\t\tself.name_ = str(int(self.name_)+1)\r\n\t\tself.game = FlappyGame()\r\n\t\tself.s2 = Screen(name=str('name')+self.name_)\r\n\t\tself.s2.add_widget(self.game)\r\n\t\tdel self.ScreenM.screens[-1]\r\n\t\tself.ScreenM.add_widget(self.s2)\r\n\t\tself.ScreenM.current = self.ScreenM.screens[-1].name\r\n\t\tself.sound1.play()\r\n\t\t#game_over_sound.stop()\r\n\t\tself.collision_first = False\r\n\t\t\t\r\n\r\n\r\n\t\r\n\r\nclass Screen_begin(Screen):\r\n\tdef __init__(self, **kwargs):\r\n\t\tsuper(Screen_begin, self).__init__(**kwargs)\r\n\r\n\r\n\t\tself.image = Image(source='./game_begin.png', keep_ratio=False, allow_stretch=True, pos=(0,0),size_hint=(None,None), size=(x_0,y_0))\r\n\r\n\t\tself.add_widget(self.image)\r\n\r\n\t\tself.label = Label(text=\"Tap to Begin\", pos=(x_0*0.5-((x_0//1.5)*0.5),y_0*0.5-((y_0//4)*0.5)), size_hint=(None, None), size=(x_0//1.5, y_0//4))\r\n\t\tself.add_widget(self.label)\r\n\t\tself.play = False\r\n\t\t\r\n\r\n\tdef Play(self, *largs):\r\n\t\tself.play = True\r\n\r\n\t\t\r\n\r\nclass GreenPipes(Widget):\r\n\r\n\tdef __init__(self,bird, **kwargs):\r\n\t\tsuper(GreenPipes,self).__init__(*kwargs)\r\n\t\tself.bird = bird\r\n\t\tself.collided = False\r\n\r\n \t\t#self.collided = False\r\n\r\n\t\tself.x = x_0\r\n\t\tself.y = 0\r\n\r\n\t\tself.size_x = x_0/7\r\n\t\tself.size_y_max = y_0/2.25\r\n\r\n\t\tself.pipes = []\r\n\t\t\r\n\t\tfor i in range(6):\r\n\t\t\t\t\t#Color(0.195, 0.800, 00.195, 1)\r\n\t\t\tsize_y_below = int(self.size_y_max*randint(65, 85)*0.01)\r\n\t\t\t####IMPORTANT nOTE ON IMAGES: KEEP RATIO FALSE AND STRECH TRUE THEN ONLY WHOLE SCREEN GETS OCCUPIED\r\n\t\t\tself.Pipe = Image(source=\"./down_pipe.png\", keep_ratio=False,allow_stretch=True,pos=(self.x + (x_0*0.5*i), self.y),size_hint=(None, None), size=(self.size_x, size_y_below))\r\n\t\t\tself.Pipe_ = Image(source=\"./up_pipe.png\", keep_ratio=False,allow_stretch=True,pos=(self.x + (x_0*0.5*i), y_0-(y_0 - (2*size_y_below))), size_hint=(None, None) ,size = (self.size_x, y_0 - (2*size_y_below)))\r\n\t\t\tself.add_widget(self.Pipe)\r\n\t\t\tself.add_widget(self.Pipe_)\r\n\t\t\tself.pipes.append((self.Pipe, self.Pipe_)) \r\n\r\n\t\tClock.schedule_interval(self.update, 1/60)\r\n\r\n\r\n\r\n\tdef update(self, dt):\r\n\r\n\t\tif self.collided == True:\r\n\t\t\treturn\r\n\r\n\t\tfor i in self.pipes:\r\n\t\t\tif True == i[0].collide_widget(self.bird.Bird_) or True == i[1].collide_widget(self.bird.Bird_) or self.bird.Bird_.pos[1] < 0:#self.bird.Bird_.pos[0], self.bird.Bird_.pos[1]):\r\n\r\n\t\t\t\tself.collided = True\r\n\t\t\t\t\r\n\r\n\t\t\r\n\r\n\t\tfor i in self.pipes:\r\n\t\t\tpower = (self.bird.score//22) \r\n\t\t\t\r\n\r\n\t\t\tx, y = i[0].pos\r\n\t\t\tx_, y_ = i[1].pos\r\n\t\t\t\r\n\t\t\tif x < -1*self.size_x:\r\n\t\t\t\tx = x_0 + (1.8*x_0)\r\n\t\t\t\tx_ = x_0 + (1.8*x_0)\r\n\r\n\t\t\tif x_0 < 320:\r\n\t\t\t\tneg = 1\r\n\t\t\telse:\r\n\t\t\t\tneg = int(x_0/320)* (1.2)**power\r\n\r\n\t\t\t#self.x = x - 1\r\n\t\t\ti[0].pos = (x-neg, y)\r\n\t\t\ti[1].pos = (x_-neg, y_)\r\n\r\n\r\n\r\nclass Bird(Widget):\r\n\tdef __init__(self, **kwargs):\r\n\t\tsuper(Bird, self).__init__(**kwargs)\r\n\t\t#self.pipes = pipes\r\n\t\t#print(self.pipes)\r\n\r\n\t\tself.x = x_0/4\r\n\t\tself.y = y_0/2\r\n\r\n\t\tself.x_size = int(x_0/6.4)\r\n\t\tself.y_size = int(y_0/18.3)\r\n\r\n\t\tself.v_0 = 0\r\n\t\tself.g = -1*int((y_0/56.12))\r\n\t\tself.t = 0\r\n\r\n\r\n\t\tself.key_time = 0\r\n\t\tself.key_press = 0\r\n\r\n\t\tself.score = 00\r\n\t\tself.collision_check = False\r\n\r\n\t\t\r\n\r\n\t\t\r\n\t\tself.Bird_ = Image(source=\"./bird_down.png\",keep_ratio=False,allow_stretch=True,pos=(self.x, self.y-(self.y_size/2)), size_hint= (None, None), size=(x_0//10, y_0//20))\r\n\t\tself.add_widget(self.Bird_)\r\n\r\n\r\n\t\tClock.schedule_interval(self.update, 1/60)\r\n\t\tEventLoop.window.bind(on_touch_down=self.keyboard)\r\n\r\n\r\n\r\n\t\r\n\tdef keyboard(self, *largs):\r\n\r\n\r\n\t\tif self.key_time <= 1 and self.key_press >= 3:\r\n\t\t\treturn\r\n\t\tself.key_time = 0\r\n\t\tself.key_press += 1\r\n\t\t\r\n\r\n\t\t\r\n\t\t\t#print(key)\r\n\t\tself.v_0 = int((y_0/100))\r\n\t\tself.t = 0\r\n\r\n\t\r\n\r\n\r\n\tdef update(self, dt):\r\n\t\t#print(self.pipes)\r\n\t\t#print(self.collide_widget(self.pipes))\r\n\t\r\n\r\n\t\tself.key_time += dt\r\n\r\n\r\n\t\t#y = y_0 + v_y(t) + a*t^2\r\n\t\t#v = v_0 + a*t\r\n\t\tif self.collision_check == False:\r\n\t\t\tself.score += (dt)\r\n\r\n\t\t\r\n\r\n\t\tself.t = self.t + dt\r\n\t\t\r\n\t\tself.v = self.v_0 + (self.g * self.t)\r\n\t\t\r\n\t\tif self.v >= 0:\r\n\t\t\tself.Bird_.source = \"./bird_up.png\"\r\n\t\telse:\r\n\t\t\tself.Bird_.source = \"./bird_down.png\"\r\n\r\n\r\n\t\tself.Bird_.pos =(self.Bird_.pos[0], self.Bird_.pos[1] + (self.v_0*self.t) + (0.5*(self.g *(self.t**2))) )\r\n\r\n\r\nclass FlappyGame(Widget):\r\n\tdef __init__(self, **kwargs):\r\n\t\tsuper(FlappyGame, self).__init__(*kwargs)\r\n\t\tself.bird = Bird()\r\n\t\tself.greenPipes = GreenPipes(self.bird)\r\n\t\tself.add_widget(Image(source='./backdrop.png', keep_ratio= False, allow_stretch=True, size_hint=(None,None), size=(x_0, y_0)))\r\n\t\tself.add_widget(self.greenPipes)\r\n\t\tself.add_widget(self.bird)\r\n\t\tself.score = 00\r\n\t\tself.Score = Label(text=' Score: '+str(self.score), size= (x_0//1.6, y_0//5.2) , pos= (x_0-(x_0//1.7), y_0-(y_0//5.4)), font_size = y_0//20)\r\n\t\tself.add_widget(self.Score)\r\n\t\tself.HScore = Label(text='HighScore: '+str(int(highscore)), size= (x_0//1.6, y_0//5.2) , pos= (x_0-(x_0//1.7), y_0-(y_0//5.4)-(y_0//17)), font_size = y_0//20)\r\n\t\tself.add_widget(self.HScore)\r\n\r\n\t\tClock.schedule_interval(self.score_update, 1/60)\r\n\r\n\tdef score_update(self, dt):\r\n\t\tself.Score.text = ' Score: '+str(int(self.bird.score))\r\n\t\t\r\n\r\n\r\nif __name__ == '__main__':\r\n\r\n\t\t\r\n\tMainApp().run()\r\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":8719,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"6"} +{"seq_id":"136802285","text":"import os \nimport pandas as pd \nimport numpy as np \nimport tensorflow as tf \nfrom keras import backend as K \nfrom keras import regularizers \nfrom keras.layers import Input, Dense, BatchNormalization, ReLU, LeakyReLU, Activation, Lambda \nfrom keras.models import Model \nfrom keras.optimizers import Adam, SGD \nfrom keras.callbacks import ModelCheckpoint, EarlyStopping, ReduceLROnPlateau, TensorBoard, LearningRateScheduler \nfrom sklearn.model_selection import GroupKFold, train_test_split \nfrom glob import glob \nfrom callbacks import PCRR, RMSE \nfrom losses import wmse\nfrom utils import rmse, rmse_np, pcrr4reg, pcrr4cls \nimport matplotlib.pyplot as plt \nimport seaborn as sns \n\nos.environ['CUDA_VISIBLE_DEVICES'] = '0'\n\ndf = pd.read_csv('./data/train_v3.csv')\ntest_df = pd.read_csv('./data/test_v3.csv')\nx_cols = [col for col in df.columns if col not in ['Cell Index', 'Cell Clutter Index', 'Clutter Index', 'RSRP']]\ntest_x = test_df[x_cols].values\n\nn_folds = 5\ngkf = GroupKFold(n_splits=n_folds)\nfold = 0\nrmse_scores = []\npcrr_scores = []\nfinal_pred = []\n\nif not os.path.exists('./k-fold/'): os.mkdir('./k-fold')\n\nfor train_idx, val_idx in gkf.split(X=df, y=df['RSRP'], groups=df['Cell Index']):\n fold += 1\n train_df = df.iloc[train_idx]\n val_df = df.iloc[val_idx]\n train_x = train_df[x_cols].values\n train_y = train_df['RSRP'].values\n val_x = val_df[x_cols].values\n val_y = val_df['RSRP'].values\n\n print('train_x.shape', train_x.shape)\n print('train_y.shape', train_y.shape)\n print('val_x.shape', val_x.shape)\n print('val_y.shape', val_y.shape)\n print('test_x.shape', test_x.shape)\n\n def lim2range(x, target_min=-130, target_max=-50) :\n x02 = K.tanh(x) + 1\n scale = ( target_max-target_min )/2.\n return x02 * scale + target_min\n\n K.clear_session()\n myInput = Input(shape=(train_x.shape[1], ), name='myInput')\n x = BatchNormalization(name='bn0')(myInput)\n x = Dense(128, name='fc1')(x)\n x = BatchNormalization(name='bn1')(x)\n x = ReLU(name='relu1')(x)\n x = Dense(128, name='fc2')(x)\n x = BatchNormalization(name='bn2')(x)\n x = ReLU(name='relu2')(x)\n # myOutput = Dense(1, activation=lim2range, name='myOutput')(x)\n myOutput = Dense(1, name='myOutput')(x)\n\n model = Model(inputs=myInput, outputs=myOutput)\n model.regularizers = [regularizers.l2(0.001)]\n optimizer = Adam(lr=1e-3)\n model.compile(loss='mse', optimizer=optimizer, metrics=[rmse])\n\n def scheduler(epoch, lr):\n reduce_epoches = [1, 2]\n if epoch in reduce_epoches:\n return 0.1*lr\n else:\n return lr\n\n lr_scheduler = LearningRateScheduler(scheduler, verbose=1)\n rmse_callback = RMSE(val_x, val_y)\n pcrr_callback = PCRR(-103, val_x, val_y)\n callbacks = [lr_scheduler, rmse_callback, pcrr_callback]\n\n model.fit(x=train_x, y=train_y, \n batch_size=2048, \n epochs=3,\n validation_data=(val_x, val_y), \n callbacks=callbacks\n )\n\n val_y_pred = model.predict(val_x, batch_size=10240)\n plt.figure()\n sns.distplot(val_y_pred)\n plt.savefig('fold_{}_val_pred_dist.png'.format(fold))\n \n print('Calculate final val RMSE and PCRR...')\n rmse_score = rmse_np(val_y, val_y_pred)\n rmse_scores.append(rmse_score)\n print('Fold {} Val RMSE Score: {}'.format(fold, rmse_score))\n\n pcrr_score = pcrr4reg(val_y, val_y_pred)\n pcrr_scores.append(pcrr_score)\n print('Fold {} Val PCRR Score: {}'.format(fold, pcrr_score))\n \n test_y_pred = model.predict(test_x, batch_size=10240, verbose=1)\n final_pred.append(test_y_pred)\n plt.figure()\n sns.distplot(test_y_pred)\n plt.savefig('fold_{}_test_pred_dist.png'.format(fold))\n\nprint('RMSE Scores: ', rmse_scores)\nprint('CV RMSE Score: ', np.array(rmse_scores).mean())\n\nprint('PCRR Scores: ', pcrr_scores)\nprint('CV PCRR Score: ', np.array(pcrr_scores).mean())\n\nif not os.path.exists('./results/'): os.mkdir('./results')\nfinal_pred = np.array(final_pred).mean(axis=0)\nplt.figure()\nsns.distplot(final_pred)\nplt.savefig('final_test_pred_dist.png')\n\ntest_df['RSRP'] = final_pred\nfor cell_index in test_df['Cell Index'].unique():\n sub_df = test_df[test_df['Cell Index'] == cell_index]\n rsrp = sub_df[['RSRP']].values.tolist()\n f = open(\"./results/test_{}.csv_result.txt\".format(cell_index), \"w\")\n f.write(str({'RSRP': rsrp}))\n f.close()","sub_path":"src/model_v3.py","file_name":"model_v3.py","file_ext":"py","file_size_in_byte":4406,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"6"} +{"seq_id":"67613994","text":"from collections import namedtuple\n\n\ndef stringify_arr(arr):\n return ' '.join([str(a) for a in arr])\n\n\ndef partition(arr, pivot_index):\n pivot = arr[pivot_index]\n\n left = [a for a in arr if a < pivot]\n right = [a for a in arr if a > pivot]\n equal = [a for a in arr if a == pivot]\n\n Partitions = namedtuple('Partitions', ['left', 'equal', 'right'])\n result = Partitions(left, equal, right)\n\n return result\n\n\ndef partition_and_merge(arr_arg):\n arr = arr_arg[:]\n pivot = arr[0]\n (left, equal, right) = partition(arr, 0)\n if (len(left) > 1):\n left = partition_and_merge(left)\n if (len(right) > 1):\n right = partition_and_merge(right)\n\n # merge\n result = left + [pivot] + right\n print(stringify_arr(result))\n return(result)\n","sub_path":"hacker_rank/algorithms/sorting/Quick_Sort/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":784,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"6"} +{"seq_id":"3081308","text":"# -*- coding: utf-8 -*-\n\nfrom django.shortcuts import render,redirect,get_object_or_404,get_list_or_404\nfrom django.core.urlresolvers import reverse\nfrom django.contrib.auth.decorators import login_required,permission_required\nfrom SGMGU.forms import *\nfrom SGMGU.models import *\nfrom django.contrib import messages\nfrom django.core.paginator import Paginator, EmptyPage, PageNotAnInteger,InvalidPage\nfrom django.core.cache import cache\nfrom .utiles import *\n\n\n\n\n#@cache_per_user(ttl=3600, cache_post=False)\ndef movimientos_internos(request):\n perfil=Perfil_usuario.objects.get(usuario=request.user)\n foto=perfil.foto\n organismo=perfil.organismo\n\n if perfil.categoria.nombre == \"organismo\":\n movimientos_internos=paginar(request,Expediente_movimiento_interno.objects.filter(organismo=organismo).order_by(\"-fecha_registro\"))\n else:\n movimientos_internos=paginar(request,Expediente_movimiento_interno.objects.all().order_by(\"-fecha_registro\"))\n context = {'categoria':perfil.categoria.nombre,'foto':foto,'expedientes':movimientos_internos,'paginas':crear_lista_pages(movimientos_internos)}\n return render(request, \"MovimietosInternos/movimientos_internos.html\", context)\n\n\n#Busqueda---------------------------------------------------------------------------------------------------------------\n@login_required\ndef buscar_movimientos_internos_ci(request,ci):\n expedientes=paginar(request,Expediente_movimiento_interno.objects.filter(graduado__ci=ci).order_by(\"-fecha_registro\"))\n context={'expedientes':expedientes,'busqueda':'si','termino_busqueda':'por CI',\"valor_busqueda\":ci,'paginas':crear_lista_pages(expedientes)}\n return render(request, \"MovimietosInternos/movimientos_internos.html\", context)\n\n\n\n@login_required\ndef eliminar_movimiento_interno(request,id_expediente):\n exp=Expediente_movimiento_interno.objects.get(id=id_expediente)\n graduado=exp.graduado\n exp.delete()\n graduado.delete()\n messages.add_message(request, messages.SUCCESS, \"El movimiento ha sido eliminado con éxito.\")\n return redirect(\"/movimientos_internos\")\n\n\n\n\n\n@login_required\ndef modificar_movimiento_interno(request,id_expediente):\n expediente=Expediente_movimiento_interno.objects.get(id=id_expediente)\n perfil=Perfil_usuario.objects.get(usuario=request.user)\n foto=perfil.foto\n\n if request.method == 'POST':\n form=RegistroMovimientoInternoForm(request.POST,request.FILES)\n if form.is_valid():\n nombre_graduado=form.cleaned_data['nombre_graduado']\n # apellidos_graduado=form.cleaned_data['apellidos_graduado']\n carrera_graduado=form.cleaned_data['carrera_graduado']\n anno_graduacion=form.cleaned_data['anno_graduacion']\n codigo_boleta=form.cleaned_data['codigo_boleta']\n imagen_boleta=form.cleaned_data['imagen_boleta']\n entidad_liberacion=form.cleaned_data['entidad_liberacion']\n entidad_aceptacion=form.cleaned_data['entidad_aceptacion']\n aprobado=form.cleaned_data['aprobado']\n municipio_entidad_liberacion=form.cleaned_data['municipio_entidad_liberacion']\n municipio_entidad_aceptacion=form.cleaned_data['municipio_entidad_aceptacion']\n causal_movimiento=form.cleaned_data['causal_movimiento']\n sintesis_causal_movimiento=form.cleaned_data['sintesis_causal_movimiento']\n detalle_direccion_residencia=form.cleaned_data['detalle_direccion_residencia']\n centro_estudio=form.cleaned_data['centro_estudio']\n municipio_residencia=form.cleaned_data['municipio_residencia']\n ci=form.cleaned_data['ci']\n\n expediente.graduado.nombre=nombre_graduado\n # expediente.graduado.apellidos=apellidos_graduado\n expediente.graduado.carrera=carrera_graduado\n expediente.graduado.anno_graduacion=anno_graduacion\n expediente.graduado.detalle_direccion_residencia=detalle_direccion_residencia\n expediente.graduado.ci=ci\n expediente.graduado.codigo_boleta=codigo_boleta\n expediente.graduado.imagen_boleta=imagen_boleta\n expediente.graduado.centro_estudio=centro_estudio\n expediente.graduado.municipio_direccion_residencia=municipio_residencia\n expediente.graduado.provincia_direccion_residencia=municipio_residencia.provincia\n expediente.graduado.save()\n\n expediente.aprobado_por=aprobado\n expediente.entidad_liberacion=entidad_liberacion\n expediente.entidad_aceptacion=entidad_aceptacion\n expediente.mun_entidad_liberacion= municipio_entidad_liberacion\n expediente.mun_entidad_aceptacion=municipio_entidad_aceptacion\n expediente.causal_movimiento=causal_movimiento\n expediente.sintesis_causal_movimiento=sintesis_causal_movimiento\n\n expediente.save()\n messages.add_message(request, messages.SUCCESS, \"El movimiento ha sido modificado con éxito.\")\n return redirect(\"/movimientos_internos\")\n\n else:\n form = RegistroMovimientoInternoForm(\n { 'nombre_graduado':expediente.graduado.nombre,\n # 'apellidos_graduado':expediente.graduado.apellidos,\n 'carrera_graduado':expediente.graduado.carrera.id,\n 'anno_graduacion':expediente.graduado.anno_graduacion,\n 'codigo_boleta':expediente.graduado.codigo_boleta,\n 'imagen_boleta':expediente.graduado.imagen_boleta,\n 'entidad_liberacion':expediente.entidad_liberacion,\n 'entidad_aceptacion':expediente.entidad_aceptacion,\n 'aprobado':expediente.aprobado_por,\n 'municipio_entidad_liberacion':expediente.mun_entidad_liberacion.id,\n 'municipio_entidad_aceptacion':expediente.mun_entidad_aceptacion.id,\n 'provincia_entidad_liberacion':expediente.mun_entidad_liberacion.provincia.id,\n 'provincia_entidad_aceptacion':expediente.mun_entidad_aceptacion.provincia.id,\n 'causal_movimiento':expediente.causal_movimiento.id,\n 'sintesis_causal_movimiento':expediente.sintesis_causal_movimiento,\n 'detalle_direccion_residencia':expediente.graduado.detalle_direccion_residencia,\n 'centro_estudio':expediente.graduado.centro_estudio.id,\n 'provincia_residencia':expediente.graduado.provincia_direccion_residencia.id,\n 'municipio_residencia':expediente.graduado.municipio_direccion_residencia.id,\n 'ci':expediente.graduado.ci\n }\n\n )\n\n # Creamos el contexto\n context = {'foto':foto,'form':form,'categoria':perfil.categoria.nombre}\n # Y mostramos los datos\n return render(request, \"MovimietosInternos/modificar_movimiento_interno.html\", context)\n\n\n\n\n@login_required\ndef registrar_movimiento_interno(request):\n foto=\"\"\n if request.user.is_authenticated():\n perfil=Perfil_usuario.objects.get(usuario=request.user)\n foto=perfil.foto\n if request.method == 'POST':\n form=RegistroMovimientoInternoForm(request.POST,request.FILES)\n if form.is_valid():\n nombre_graduado=form.cleaned_data['nombre_graduado']\n # apellidos_graduado=form.cleaned_data['apellidos_graduado']\n carrera_graduado=form.cleaned_data['carrera_graduado']\n anno_graduacion=form.cleaned_data['anno_graduacion']\n codigo_boleta=form.cleaned_data['codigo_boleta']\n imagen_boleta=form.cleaned_data['imagen_boleta']\n entidad_liberacion=form.cleaned_data['entidad_liberacion']\n entidad_aceptacion=form.cleaned_data['entidad_aceptacion']\n aprobado=form.cleaned_data['aprobado']\n municipio_entidad_liberacion=form.cleaned_data['municipio_entidad_liberacion']\n municipio_entidad_aceptacion=form.cleaned_data['municipio_entidad_aceptacion']\n causal_movimiento=form.cleaned_data['causal_movimiento']\n sintesis_causal_movimiento=form.cleaned_data['sintesis_causal_movimiento']\n detalle_direccion_residencia=form.cleaned_data['detalle_direccion_residencia']\n centro_estudio=form.cleaned_data['centro_estudio']\n municipio_residencia=form.cleaned_data['municipio_residencia']\n\n ci=form.cleaned_data['ci']\n graduado=Graduado(\n nombre=nombre_graduado,\n # apellidos=apellidos_graduado,\n carrera=carrera_graduado,\n anno_graduacion=anno_graduacion,\n detalle_direccion_residencia=detalle_direccion_residencia,\n ci=ci,\n codigo_boleta=codigo_boleta,\n imagen_boleta=imagen_boleta,\n centro_estudio=centro_estudio,\n municipio_direccion_residencia=municipio_residencia,\n provincia_direccion_residencia=municipio_residencia.provincia,\n\n )\n graduado.save()\n expediente=Expediente_movimiento_interno(\n graduado=graduado,\n organismo=perfil.organismo,\n aprobado_por=aprobado,\n entidad_liberacion=entidad_liberacion,\n entidad_aceptacion=entidad_aceptacion,\n mun_entidad_liberacion= municipio_entidad_liberacion,\n mun_entidad_aceptacion=municipio_entidad_aceptacion,\n causal_movimiento=causal_movimiento,\n sintesis_causal_movimiento=sintesis_causal_movimiento,\n )\n\n expediente.save()\n messages.add_message(request, messages.SUCCESS, \"El movimiento ha sido registrado con éxito.\")\n\n return redirect(\"/movimientos_internos\")\n\n else:\n form = RegistroMovimientoInternoForm()\n # Creamos el contexto\n context = {'foto':foto,'form':form,'categoria':perfil.categoria.nombre}\n # Y mostramos los datos\n return render(request, \"MovimietosInternos/registrar_movimiento_interno.html\", context)\n\n\n\n","sub_path":"SGMGU/views/view_movimientos_internos.py","file_name":"view_movimientos_internos.py","file_ext":"py","file_size_in_byte":9901,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"6"} +{"seq_id":"24216373","text":"#-*- coding = utf-8 -*-\r\n#@Author:何欣泽\r\n#@Time:2020/11/3 20:09\r\n#@File:speech_mix.py\r\n#@Software:PyCharm\r\n\r\nimport numpy as np\r\nimport librosa\r\n\r\nfor cout in range(1,34):\r\n woman = r\"C:\\Users\\MACHENIKE\\Desktop\\数字信号处理B\\项目\\woman_voice\\woman_voice ({cout}).wav\".format(cout = cout)\r\n man = r\"C:\\Users\\MACHENIKE\\Desktop\\数字信号处理B\\项目\\man_voice\\man_voice (1).wav\".format(cout = cout)\r\n\r\n woman_speech ,sample_rate1,= librosa.load(woman, sr=8000)\r\n man_speech ,sample_rate2,= librosa.load(man, sr=8000)\r\n\r\n # 找最短的音频\r\n minlength = min(len(woman_speech), len(man_speech))\r\n\r\n # 裁剪\r\n woman_speech = woman_speech[:minlength]\r\n man_speech = man_speech[:minlength]\r\n # 线性相加\r\n mixed_series = woman_speech + man_speech\r\n\r\n mixed_file_name = r'C:\\Users\\MACHENIKE\\Desktop\\数字信号处理B\\项目\\mixed_series\\mixed_series{}.wav'.format(cout)\r\n woman_file_name = r'C:\\Users\\MACHENIKE\\Desktop\\数字信号处理B\\项目\\woman_series\\woman_speech{}.wav'.format(cout)\r\n man_file_name = r'C:\\Users\\MACHENIKE\\Desktop\\数字信号处理B\\项目\\man_series\\man_speech{}.wav'.format(cout)\r\n #保存文件\r\n librosa.output.write_wav(mixed_file_name, mixed_series, sr=8000)\r\n librosa.output.write_wav(woman_file_name, woman_speech, sr=8000)\r\n librosa.output.write_wav(man_file_name, man_speech, sr=8000)\r\n\r\nprint('合成完成')","sub_path":"speech_mix.py","file_name":"speech_mix.py","file_ext":"py","file_size_in_byte":1416,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"6"} +{"seq_id":"618884554","text":"#!/usr/bin/env python\n\n\n# import only system from os \nfrom os import system, name \n \n# define our clear function \ndef clear(): \n # for windows \n if name == 'nt': \n _ = system('cls') \n # for mac and linux(here, os.name is 'posix') \n else: \n _ = system('clear') \n \n# now call function we defined above \nclear() \n\n####\n# Sets the rate of pay\n####\nPayRate = float(input(\"\\nEnter your pay rate per hour: \"))\nOverTimePayRate = PayRate * 1.5\nYN = input(\"\\nIs shift differential authorized for this position (Y/N)? \")\nif YN == \"Y\" or YN == \"y\":\n\tPERCENT = float(input(\"\\n\\tEnter the authorized shift differential percentage (5, 10, 15): \"))\n\tif PERCENT == 5:\n\t\tMultiplier = .05\n\telif PERCENT == 10:\n\t\tMultiplier = .10\n\telif PERCENT == 15:\n\t\tMultiplier = .15\n\telse:\n\t\tprint(\"\\n\\n\\tAn invalid percentage was entered; exiting!\")\n\t\texit(1)\nelse:\n\tMultiplier = 0\n\n####\n# collects information about amount of time worked\n####\nH1 = 0\nOT1 = 0\nfor x in [1, 2]:\n\tDays = int(input(\"\\nEnter the number of days worked in week\" + str(x) + \": \"))\n\tfor day in range(Days):\n\t\tHours = int(input(\"\\tEnter the number of hours worked in day\" + str(day+1) + \": \"))\n\t\t### determines whether there is any overtime hours\n\t\tif Hours > 8:\n\t\t\tOverTime = Hours - 8\n\t\t\tHours = Hours - OverTime\n\t\telse:\n\t\t\tOverTime = 0\n\t\t### Increments regular time and overtime hours\n\t\tH1 += Hours\n\t\tOT1 += OverTime\nHours = H1\nOverTime = OT1\nTotalHours = Hours + OverTime\n\n####\n# Calculates Gross Pay\n####\nRegularPay = Hours * PayRate\nRegShiftDiff = RegularPay * Multiplier\nOverTimePay = OverTime * OverTimePayRate\nOTShiftDiff = OverTimePay * Multiplier\nShiftDiff = RegShiftDiff + OTShiftDiff\nGrossPay = RegularPay + RegShiftDiff + OverTimePay + OTShiftDiff\n\n####\n# Calculates statutory taxes and Net Pay\n####\nFedTaxPercent = .24\nStateTaxPercent = .093\nFicaTaxPercent = .0765\nSUI_SDI_Percent = .0095\nFedTax = round(GrossPay * FedTaxPercent,2)\nStateTax = round(GrossPay * StateTaxPercent,2)\nFicaTax = round(GrossPay * FicaTaxPercent,2)\nSUI_SDI = round(GrossPay * SUI_SDI_Percent,2)\nNetPay = round(GrossPay - FedTax - StateTax - FicaTax - SUI_SDI, 2)\n\n####\n# Displays the final results of the calculations\n####\nclear()\nprint(\"\\t=================================\\n\\t= Pay Statement =\\n\\t=================================\")\nprint(\"\\n\\nTotal Hours for this two week period:\\t\" + str(TotalHours) + \"\\n\\tRegular Hours:\\t\\t\\t\" + str(Hours) + \"\\n\\tOvertime Hours:\\t\\t\\t\" + str(OverTime) + \"\\n\\nGross Pay:\\t\\t\\t\\t\" + str(GrossPay) + \"\\n\\tRegular Pay:\\t\\t\\t\" + str(RegularPay) + \"\\n\\tOvertime Pay:\\t\\t\\t\" + str(OverTimePay) + \"\\n\\tShift Differential:\\t\\t\" + str(ShiftDiff) + \"\\n\\nFederal Income Tax:\\t\\t\\t\" + str(FedTax) + \"\\nState Income Tax:\\t\\t\\t\" + str(StateTax) + \"\\nFICA Tax:\\t\\t\\t\\t\" + str(FicaTax) + \"\\nUnemployment Insurance:\\t\\t\\t\" + str(SUI_SDI) + \"\\n\\nNet Pay:\\t\\t\\t\\t\" + str(NetPay) + \"\\n\\n\")\n","sub_path":"netpay_calculator.py","file_name":"netpay_calculator.py","file_ext":"py","file_size_in_byte":2890,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"6"} +{"seq_id":"197441565","text":"# -*- coding: utf-8 -*-\nimport os\nfrom copy import copy\nfrom fabric.api import *\nfrom fabric.contrib.files import upload_template\n\nfrom fab_settings import *\n\nenv.directory = {\n 'production': '/home/u33635/u33635.netangels.ru/www'\n}\nenv.manage_dir = '%s/src'\nenv.activate = 'source %s/ENV/bin/activate'\n\nenv.deploy_user = env.user = SSH_USER\nenv.env_type = 'production'\n\nif not env.hosts:\n env.hosts = ['u33635.netangels.ru']\n\n\ndef production():\n upload()\n environment()\n local_settings()\n migrate()\n collect_static()\n # fcgi_config()\n restart()\n\n\ndef upload():\n directory = env.directory[env.env_type]\n os.chdir(os.path.dirname(__file__))\n local('git archive HEAD | gzip > archive.tar.gz')\n put('archive.tar.gz', directory + '/archive.tar.gz')\n with cd(directory):\n run('tar -zxf archive.tar.gz')\n run('rm archive.tar.gz')\n local('del archive.tar.gz')\n\n\ndef virtualenv(command):\n with cd(env.directory[env.env_type]):\n run(env.activate % env.directory[env.env_type] + ' && ' + command)\n\n\ndef environment():\n with cd(env.directory[env.env_type]):\n with settings(warn_only=True):\n run('virtualenv --system-site-packages ENV')\n virtualenv('pip install -r requirements.txt')\n\n\ndef local_settings():\n os.chdir(os.path.dirname(__file__))\n manage_dir = env.manage_dir % env.directory[env.env_type]\n params = copy(globals())\n params['ENV_TYPE'] = env.env_type\n\n with cd(manage_dir):\n upload_template(\n 'src/local_settings.py.sample',\n 'local_settings.py',\n params,\n backup=False\n )\n\n\ndef manage_py(command):\n manage_dir = env.manage_dir % env.directory[env.env_type]\n virtualenv('cd %s && python manage.py %s' % (manage_dir, command))\n\n\ndef migrate():\n manage_py('migrate')\n\n\ndef collect_static():\n run('mkdir -p %s/static' % env.directory[env.env_type])\n manage_py('collectstatic -c --noinput')\n\n\ndef fcgi_config():\n directory = env.directory[env.env_type]\n with cd(directory):\n run('cp tools/cgi-bin/* ../cgi-bin/')\n run('chmod 755 ../cgi-bin/*')\n\n\ndef restart():\n with settings(warn_only=True):\n run('pkill -u u33635 -f django-wrapper.fcgi')\n\n\n#------------------------------------------------------------------------------------------\n\ndef run_local():\n local('cd src && ..\\\\ENV\\\\Scripts\\\\python manage.py runserver 0.0.0.0:8000')\n\n\ndef local_env():\n with settings(warn_only=True):\n local('virtualenv.exe ENV --system-site-packages')\n local('ENV\\\\Scripts\\\\pip install -r requirements_test.txt ')\n\n\ndef enter(args=''):\n local('cd src && ..\\\\ENV\\\\Scripts\\\\python manage.py %s' % args)\n\n\ndef local_static():\n local('cd src && ..\\\\ENV\\\\Scripts\\\\python manage.py collectstatic -c --noinput')\n\n\ndef update_local_db():\n run(\"mysqldump -u %(DATABASE_USER)s -p%(DATABASE_PASSWORD)s -h %(DATABASE_HOST)s %(DATABASE_DB)s > dump.sql\" % globals())\n get(\"dump.sql\", \"dump.sql\")\n run(\"rm dump.sql\")\n local(\"mysql -uroot uralcon < dump.sql\" % globals())\n local(\"del dump.sql\")\n\n\ndef local_migrate():\n with settings(warn_only=True):\n local('cd src && ..\\\\ENV\\\\Scripts\\\\python manage.py makemigrations')\n local('cd src && ..\\\\ENV\\\\Scripts\\\\python manage.py migrate')\n","sub_path":"fabfile.py","file_name":"fabfile.py","file_ext":"py","file_size_in_byte":3311,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"6"} +{"seq_id":"516586177","text":"import numpy as np\n\n# equation of the plane is ax + by + cz = d, coordinates of the point are x, y, z\n\ndef project_on_plane(a, b, c, d, x, y, z):\n # t and t0 are some parameters\n t0 = d / (a ** 2 + b ** 2 + c ** 2)\n t = (d - a * x - b * y - c * z) / (a ** 2 + b ** 2 + c ** 2)\n\n # r is vector from the origin to the projection of the point, r0 is perpendicular vector from the origin to the plane\n r0 = np.array([a * t0, b * t0, c * t0])\n r = np.array([a * t + x, b * t + y, c * t + z])\n\n # i and j are basis vector of the plane, I have chosen them so that j intersects z axis and i x j is in the same direction as r0\n j = np.array([- a * t0, - b * t0, d / c - c * t0])\n j = j / np.linalg.norm(j)\n i = np.cross(j, r0)\n i = i / np.linalg.norm(i)\n\n # returns coordinates of the point's projection on plane in plane's coordinate system\n return np.dot(r - r0, i), np.dot(r - r0, j)\n","sub_path":"project.py","file_name":"project.py","file_ext":"py","file_size_in_byte":917,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"458976083","text":"# -*- coding: utf-8 -*-\r\n\r\n\r\nimport numpy as np\r\nimport pickle\r\nimport pandas as pd\r\n#from flasgger import Swagger\r\nimport streamlit as st\r\n\r\nfrom PIL import Image\r\n\r\ndef welcome():\r\n return \"Welcome All\"\r\n\r\n\r\ndef predict_note_authentication(data_in, model):\r\n\r\n prediction = model.predict(data_in)\r\n print(prediction)\r\n return prediction\r\n\r\n\r\ndef main():\r\n st.title(\"Data Analyst Salary Predictor\")\r\n html_temp = \"\"\"\r\n
\r\n

Streamlit Salary Prediction ML App

\r\n
\r\n \"\"\"\r\n\r\n st.markdown(html_temp, unsafe_allow_html=True)\r\n\r\n features = {'rating': 0,\r\n 'company_age': 0,\r\n 'size_1 to 50 Employees': 0,\r\n 'size_10000+ Employees': 0,\r\n 'size_1001 to 5000 Employees': 0,\r\n 'size_201 to 500 Employees': 0,\r\n 'size_5001 to 10000 Employees': 0,\r\n 'size_501 to 1000 Employees': 0,\r\n 'size_51 to 200 Employees': 0,\r\n 'type_of_ownership_College / University': 0,\r\n 'type_of_ownership_Company - Private': 0,\r\n 'type_of_ownership_Company - Public': 0,\r\n 'type_of_ownership_Franchise': 0,\r\n 'type_of_ownership_Government': 0,\r\n 'type_of_ownership_Hospital': 0,\r\n 'type_of_ownership_Nonprofit Organization': 0,\r\n 'type_of_ownership_Private Practice / Firm': 0,\r\n 'type_of_ownership_School / School District': 0,\r\n 'type_of_ownership_Subsidiary or Business Segment': 0,\r\n 'industry_Accounting': 0,\r\n 'industry_Advertising & Marketing': 0,\r\n 'industry_Aerospace & Defense': 0,\r\n 'industry_Architectural & Engineering Services': 0,\r\n 'industry_Automotive Parts & Accessories Stores': 0,\r\n 'industry_Banks & Credit Unions': 0,\r\n 'industry_Biotech & Pharmaceuticals': 0,\r\n 'industry_Brokerage Services': 0,\r\n 'industry_Cable, Internet & Telephone Providers': 0,\r\n 'industry_Colleges & Universities': 0,\r\n 'industry_Commercial Equipment Rental': 0,\r\n 'industry_Computer Hardware & Software': 0,\r\n 'industry_Consulting': 0,\r\n 'industry_Consumer Product Rental': 0,\r\n 'industry_Consumer Products Manufacturing': 0,\r\n 'industry_Department, Clothing, & Shoe Stores': 0,\r\n 'industry_Drug & Health Stores': 0,\r\n 'industry_Electrical & Electronic Manufacturing': 0,\r\n 'industry_Energy': 0,\r\n 'industry_Enterprise Software & Network Solutions': 0,\r\n 'industry_Express Delivery Services': 0,\r\n 'industry_Farm Support Services': 0,\r\n 'industry_Federal Agencies': 0,\r\n 'industry_Financial Analytics & Research': 0,\r\n 'industry_Financial Transaction Processing': 0,\r\n 'industry_Food & Beverage Manufacturing': 0,\r\n 'industry_Gambling': 0,\r\n 'industry_Gas Stations': 0,\r\n 'industry_Gift, Novelty & Souvenir Stores': 0,\r\n 'industry_Health Care Products Manufacturing': 0,\r\n 'industry_Health Care Services & Hospitals': 0,\r\n 'industry_Home Centers & Hardware Stores': 0,\r\n 'industry_Home Furniture & Housewares Stores': 0,\r\n 'industry_IT Services': 0,\r\n 'industry_Industrial Manufacturing': 0,\r\n 'industry_Insurance Agencies & Brokerages': 0,\r\n 'industry_Insurance Carriers': 0,\r\n 'industry_Internet': 0,\r\n 'industry_Investment Banking & Asset Management': 0,\r\n 'industry_K-12 Education': 0,\r\n 'industry_Legal': 0,\r\n 'industry_Lending': 0,\r\n 'industry_Logistics & Supply Chain': 0,\r\n 'industry_Membership Organizations': 0,\r\n 'industry_Miscellaneous Manufacturing': 0,\r\n 'industry_Municipal Governments': 0,\r\n 'industry_Preschool & Child Care': 0,\r\n 'industry_Real Estate': 0,\r\n 'industry_Religious Organizations': 0,\r\n 'industry_Research & Development': 0,\r\n 'industry_Security Services': 0,\r\n 'industry_Social Assistance': 0,\r\n 'industry_Staffing & Outsourcing': 0,\r\n 'industry_State & Regional Agencies': 0,\r\n 'industry_Telecommunications Manufacturing': 0,\r\n 'industry_Telecommunications Services': 0,\r\n 'industry_Transportation Equipment Manufacturing': 0,\r\n 'industry_Transportation Management': 0,\r\n 'industry_Wholesale': 0,\r\n 'sector_Accounting & Legal': 0,\r\n 'sector_Aerospace & Defense': 0,\r\n 'sector_Agriculture & Forestry': 0,\r\n 'sector_Arts, Entertainment & Recreation': 0,\r\n 'sector_Biotech & Pharmaceuticals': 0,\r\n 'sector_Business Services': 0,\r\n 'sector_Consumer Services': 0,\r\n 'sector_Education': 0,\r\n 'sector_Finance': 0,\r\n 'sector_Government': 0,\r\n 'sector_Health Care': 0,\r\n 'sector_Information Technology': 0,\r\n 'sector_Insurance': 0,\r\n 'sector_Manufacturing': 0,\r\n 'sector_Non-Profit': 0,\r\n 'sector_Oil, Gas, Energy & Utilities': 0,\r\n 'sector_Real Estate': 0,\r\n 'sector_Retail': 0,\r\n 'sector_Telecommunications': 0,\r\n 'sector_Transportation & Logistics': 0,\r\n 'revenue_1-2b': 0,\r\n 'revenue_1-5m': 0,\r\n 'revenue_10-25m': 0,\r\n 'revenue_100-500m': 0,\r\n 'revenue_10b': 0,\r\n 'revenue_2-5b': 0,\r\n 'revenue_25-50m': 0,\r\n 'revenue_5-10m': 0,\r\n 'revenue_50-100m': 0,\r\n 'revenue_500m-1b': 0,\r\n 'revenue_<1m': 0,\r\n 'city_Albany': 0,\r\n 'city_Altamonte Springs': 0,\r\n 'city_Anchorage': 0,\r\n 'city_Ankeny': 0,\r\n 'city_Ann Arbor': 0,\r\n 'city_Arlington': 0,\r\n 'city_Ashburn': 0,\r\n 'city_Atlanta': 0,\r\n 'city_Austin': 0,\r\n 'city_Baltimore': 0,\r\n 'city_Beaverton': 0,\r\n 'city_Bellevue': 0,\r\n 'city_Bethesda': 0,\r\n 'city_Birmingham': 0,\r\n 'city_Bloomington': 0,\r\n 'city_Bonita Springs': 0,\r\n 'city_Boston': 0,\r\n 'city_Boulder': 0,\r\n 'city_Bowie': 0,\r\n 'city_Brea': 0,\r\n 'city_Brentwood': 0,\r\n 'city_Bridgeton': 0,\r\n 'city_Brooklyn': 0,\r\n 'city_Brooklyn Heights': 0,\r\n 'city_Burlingame': 0,\r\n 'city_Cambridge': 0,\r\n 'city_Carlsbad': 0,\r\n 'city_Carson': 0,\r\n 'city_Center Valley': 0,\r\n 'city_Charlotte': 0,\r\n 'city_Chaska': 0,\r\n 'city_Chicago': 0,\r\n 'city_Chico': 0,\r\n 'city_Cincinnati': 0,\r\n 'city_Clarksburg': 0,\r\n 'city_Colmar': 0,\r\n 'city_Colorado Springs': 0,\r\n 'city_Columbia': 0,\r\n 'city_Columbus': 0,\r\n 'city_Culver City': 0,\r\n 'city_Dallas': 0,\r\n 'city_Danville': 0,\r\n 'city_Deerfield': 0,\r\n 'city_Denver': 0,\r\n 'city_Detroit': 0,\r\n 'city_Dublin': 0,\r\n 'city_Durham': 0,\r\n 'city_Eden Prairie': 0,\r\n 'city_Englewood': 0,\r\n 'city_Eugene': 0,\r\n 'city_Eureka': 0,\r\n 'city_Fairport': 0,\r\n 'city_Falls Church': 0,\r\n 'city_Flint': 0,\r\n 'city_Florham Park': 0,\r\n 'city_Fort Wayne': 0,\r\n 'city_Fremont': 0,\r\n 'city_Ft Carson': 0,\r\n 'city_Garden City': 0,\r\n 'city_Gilbert': 0,\r\n 'city_Glendale': 0,\r\n 'city_Golden': 0,\r\n 'city_Grand Prairie': 0,\r\n 'city_Greensboro': 0,\r\n 'city_Harrisburg': 0,\r\n 'city_Hartford': 0,\r\n 'city_Hayward': 0,\r\n 'city_Herndon': 0,\r\n 'city_Highland': 0,\r\n 'city_Houston': 0,\r\n 'city_Indianapolis': 0,\r\n 'city_Industry': 0,\r\n 'city_Irving': 0,\r\n 'city_Jacksonville': 0,\r\n 'city_Jersey City': 0,\r\n 'city_Kansas City': 0,\r\n 'city_King of Prussia': 0,\r\n 'city_Ladera Ranch': 0,\r\n 'city_Lafayette': 0,\r\n 'city_Lake Mary': 0,\r\n 'city_Lancaster': 0,\r\n 'city_Laramie': 0,\r\n 'city_Las Vegas': 0,\r\n 'city_Leander': 0,\r\n 'city_Lenexa': 0,\r\n 'city_Long Beach': 0,\r\n 'city_Los Angeles': 0,\r\n 'city_Loveland': 0,\r\n 'city_Lowell': 0,\r\n 'city_Mahwah': 0,\r\n 'city_Malden': 0,\r\n 'city_McLean': 0,\r\n 'city_Medford': 0,\r\n 'city_Memphis': 0,\r\n 'city_Miami': 0,\r\n 'city_Miami Lakes': 0,\r\n 'city_Minneapolis': 0,\r\n 'city_Minnetonka': 0,\r\n 'city_Mount Laurel': 0,\r\n 'city_Mountain View': 0,\r\n 'city_Mundelein': 0,\r\n 'city_Naples': 0,\r\n 'city_Nashville': 0,\r\n 'city_New Britain': 0,\r\n 'city_New Haven': 0,\r\n 'city_New York': 0,\r\n 'city_Newark': 0,\r\n 'city_Newport News': 0,\r\n 'city_Norfolk': 0,\r\n 'city_Normal': 0,\r\n 'city_North Canton': 0,\r\n 'city_Northbrook': 0,\r\n 'city_Oakland': 0,\r\n 'city_Ogden': 0,\r\n 'city_Oklahoma': 0,\r\n 'city_Oklahoma City': 0,\r\n 'city_Orlando': 0,\r\n 'city_Palm Beach Gardens': 0,\r\n 'city_Palo Alto': 0,\r\n 'city_Parsippany': 0,\r\n 'city_Pasadena': 0,\r\n 'city_Philadelphia': 0,\r\n 'city_Phoenix': 0,\r\n 'city_Pittsburgh': 0,\r\n 'city_Plano': 0,\r\n 'city_Pleasanton': 0,\r\n 'city_Plymouth': 0,\r\n 'city_Portland': 0,\r\n 'city_Portsmouth': 0,\r\n 'city_Provo': 0,\r\n 'city_Quantico': 0,\r\n 'city_Raleigh': 0,\r\n 'city_Reading': 0,\r\n 'city_Reno': 0,\r\n 'city_Richardson': 0,\r\n 'city_Richmond': 0,\r\n 'city_Riverwoods': 0,\r\n 'city_Roanoke': 0,\r\n 'city_Rolling Meadows': 0,\r\n 'city_Rosemont': 0,\r\n 'city_Roswell': 0,\r\n 'city_Roy': 0,\r\n 'city_Sacramento': 0,\r\n 'city_Saint Louis': 0,\r\n 'city_Saint Petersburg': 0,\r\n 'city_Salt Lake City': 0,\r\n 'city_San Antonio': 0,\r\n 'city_San Diego': 0,\r\n 'city_San Francisco': 0,\r\n 'city_San Jose': 0,\r\n 'city_San Marcos': 0,\r\n 'city_Santa Barbara': 0,\r\n 'city_Santa Clara': 0,\r\n 'city_Santa Cruz': 0,\r\n 'city_Scottsdale': 0,\r\n 'city_Seattle': 0,\r\n 'city_Sellersville': 0,\r\n 'city_Sheldonville': 0,\r\n 'city_Solon': 0,\r\n 'city_Somerset': 0,\r\n 'city_Springfield': 0,\r\n 'city_St Louis Park': 0,\r\n 'city_Stamford': 0,\r\n 'city_Stanford': 0,\r\n 'city_Stevens Point': 0,\r\n 'city_Sycamore': 0,\r\n 'city_Tampa': 0,\r\n 'city_Tempe': 0,\r\n 'city_Tigard': 0,\r\n 'city_Troy': 0,\r\n 'city_Urbandale': 0,\r\n 'city_Vienna': 0,\r\n 'city_Virginia': 0,\r\n 'city_Waltham': 0,\r\n 'city_Warrenton': 0,\r\n 'city_Washington': 0,\r\n 'city_Waterbury': 0,\r\n 'city_Wayne': 0,\r\n 'city_Wellesley': 0,\r\n 'city_West Palm Beach': 0,\r\n 'city_Westlake Village': 0,\r\n 'city_Westminster': 0,\r\n 'city_Wilmington': 0,\r\n 'city_Wilton': 0,\r\n 'city_Winchester': 0,\r\n 'city_Woodbury': 0,\r\n 'city_Worthington': 0,\r\n 'state_AK': 0,\r\n 'state_AL': 0,\r\n 'state_AZ': 0,\r\n 'state_CA': 0,\r\n 'state_CO': 0,\r\n 'state_CT': 0,\r\n 'state_DC': 0,\r\n 'state_DE': 0,\r\n 'state_FL': 0,\r\n 'state_GA': 0,\r\n 'state_IA': 0,\r\n 'state_IL': 0,\r\n 'state_IN': 0,\r\n 'state_KS': 0,\r\n 'state_KY': 0,\r\n 'state_MA': 0,\r\n 'state_MD': 0,\r\n 'state_ME': 0,\r\n 'state_MI': 0,\r\n 'state_MN': 0,\r\n 'state_MO': 0,\r\n 'state_NC': 0,\r\n 'state_NH': 0,\r\n 'state_NJ': 0,\r\n 'state_NV': 0,\r\n 'state_NY': 0,\r\n 'state_OH': 0,\r\n 'state_OK': 0,\r\n 'state_OR': 0,\r\n 'state_PA': 0,\r\n 'state_TN': 0,\r\n 'state_TX': 0,\r\n 'state_UT': 0,\r\n 'state_VA': 0,\r\n 'state_VT': 0,\r\n 'state_WA': 0,\r\n 'state_WI': 0,\r\n 'state_WV': 0,\r\n 'state_WY': 0}\r\n\r\n \r\n \r\n rating = st.text_input(\"Rating\", \"Type Here\")\r\n features['rating'] = rating\r\n\r\n company_age = st.text_input(\"company_age\", \"Type Here\")\r\n features['company_age'] = company_age\r\n\r\n # company size\r\n option = st.selectbox(\r\n 'Choose company size: ',\r\n ('size_1 to 50 Employees',\r\n 'size_10000+ Employees',\r\n 'size_1001 to 5000 Employees',\r\n 'size_201 to 500 Employees',\r\n 'size_5001 to 10000 Employees',\r\n 'size_501 to 1000 Employees',\r\n 'size_51 to 200 Employees'))\r\n\r\n st.write('You selected:', option)\r\n features[option] = 1 \r\n\r\n # type of ownership\r\n option = st.selectbox(\r\n 'Choose type of ownership: ',\r\n ('type_of_ownership_College / University',\r\n 'type_of_ownership_Company - Private',\r\n 'type_of_ownership_Company - Public',\r\n 'type_of_ownership_Franchise',\r\n 'type_of_ownership_Government',\r\n 'type_of_ownership_Hospital',\r\n 'type_of_ownership_Nonprofit Organization',\r\n 'type_of_ownership_Private Practice / Firm',\r\n 'type_of_ownership_School / School District',\r\n 'type_of_ownership_Subsidiary or Business Segment'))\r\n\r\n st.write('You selected:', option)\r\n features[option] = 1 \r\n\r\n\r\n # type of industry\r\n option = st.selectbox(\r\n 'Choose industry: ',\r\n ('industry_Accounting',\r\n 'industry_Advertising & Marketing',\r\n 'industry_Aerospace & Defense',\r\n 'industry_Architectural & Engineering Services',\r\n 'industry_Automotive Parts & Accessories Stores',\r\n 'industry_Banks & Credit Unions',\r\n 'industry_Biotech & Pharmaceuticals',\r\n 'industry_Brokerage Services',\r\n 'industry_Cable, Internet & Telephone Providers',\r\n 'industry_Colleges & Universities',\r\n 'industry_Commercial Equipment Rental',\r\n 'industry_Computer Hardware & Software',\r\n 'industry_Consulting',\r\n 'industry_Consumer Product Rental',\r\n 'industry_Consumer Products Manufacturing',\r\n 'industry_Department, Clothing, & Shoe Stores',\r\n 'industry_Drug & Health Stores',\r\n 'industry_Electrical & Electronic Manufacturing',\r\n 'industry_Energy',\r\n 'industry_Enterprise Software & Network Solutions',\r\n 'industry_Express Delivery Services',\r\n 'industry_Farm Support Services',\r\n 'industry_Federal Agencies',\r\n 'industry_Financial Analytics & Research',\r\n 'industry_Financial Transaction Processing',\r\n 'industry_Food & Beverage Manufacturing',\r\n 'industry_Gambling',\r\n 'industry_Gas Stations',\r\n 'industry_Gift, Novelty & Souvenir Stores',\r\n 'industry_Health Care Products Manufacturing',\r\n 'industry_Health Care Services & Hospitals',\r\n 'industry_Home Centers & Hardware Stores',\r\n 'industry_Home Furniture & Housewares Stores',\r\n 'industry_IT Services',\r\n 'industry_Industrial Manufacturing',\r\n 'industry_Insurance Agencies & Brokerages',\r\n 'industry_Insurance Carriers',\r\n 'industry_Internet',\r\n 'industry_Investment Banking & Asset Management',\r\n 'industry_K-12 Education',\r\n 'industry_Legal',\r\n 'industry_Lending',\r\n 'industry_Logistics & Supply Chain',\r\n 'industry_Membership Organizations',\r\n 'industry_Miscellaneous Manufacturing',\r\n 'industry_Municipal Governments',\r\n 'industry_Preschool & Child Care',\r\n 'industry_Real Estate',\r\n 'industry_Religious Organizations',\r\n 'industry_Research & Development',\r\n 'industry_Security Services',\r\n 'industry_Social Assistance',\r\n 'industry_Staffing & Outsourcing',\r\n 'industry_State & Regional Agencies',\r\n 'industry_Telecommunications Manufacturing',\r\n 'industry_Telecommunications Services',\r\n 'industry_Transportation Equipment Manufacturing',\r\n 'industry_Transportation Management',\r\n 'industry_Wholesale',\r\n))\r\n\r\n st.write('You selected:', option)\r\n features[option] = 1 \r\n\r\n # sector\r\n option = st.selectbox(\r\n 'Choose sector: ',\r\n ('sector_Accounting & Legal',\r\n 'sector_Aerospace & Defense',\r\n 'sector_Agriculture & Forestry',\r\n 'sector_Arts, Entertainment & Recreation',\r\n 'sector_Biotech & Pharmaceuticals',\r\n 'sector_Business Services',\r\n 'sector_Consumer Services',\r\n 'sector_Education',\r\n 'sector_Finance',\r\n 'sector_Government',\r\n 'sector_Health Care',\r\n 'sector_Information Technology',\r\n 'sector_Insurance',\r\n 'sector_Manufacturing',\r\n 'sector_Non-Profit',\r\n 'sector_Oil, Gas, Energy & Utilities',\r\n 'sector_Real Estate',\r\n 'sector_Retail',\r\n 'sector_Telecommunications',\r\n 'sector_Transportation & Logistics'))\r\n\r\n st.write('You selected:', option)\r\n features[option] = 1 \r\n\r\n\r\n # revenue\r\n option = st.selectbox(\r\n 'Choose revenue: ',\r\n ('revenue_1-2b',\r\n 'revenue_1-5m',\r\n 'revenue_10-25m',\r\n 'revenue_100-500m',\r\n 'revenue_10b',\r\n 'revenue_2-5b',\r\n 'revenue_25-50m',\r\n 'revenue_5-10m',\r\n 'revenue_50-100m',\r\n 'revenue_500m-1b',\r\n 'revenue_<1m'))\r\n\r\n st.write('You selected:', option)\r\n features[option] = 1 \r\n\r\n\r\n\r\n\r\n # city\r\n option = st.selectbox(\r\n 'Choose city: ',\r\n ('city_Albany',\r\n 'city_Altamonte Springs',\r\n 'city_Anchorage',\r\n 'city_Ankeny',\r\n 'city_Ann Arbor',\r\n 'city_Arlington',\r\n 'city_Ashburn',\r\n 'city_Atlanta',\r\n 'city_Austin',\r\n 'city_Baltimore',\r\n 'city_Beaverton',\r\n 'city_Bellevue',\r\n 'city_Bethesda',\r\n 'city_Birmingham',\r\n 'city_Bloomington',\r\n 'city_Bonita Springs',\r\n 'city_Boston',\r\n 'city_Boulder',\r\n 'city_Bowie',\r\n 'city_Brea',\r\n 'city_Brentwood',\r\n 'city_Bridgeton',\r\n 'city_Brooklyn',\r\n 'city_Brooklyn Heights',\r\n 'city_Burlingame',\r\n 'city_Cambridge',\r\n 'city_Carlsbad',\r\n 'city_Carson',\r\n 'city_Center Valley',\r\n 'city_Charlotte',\r\n 'city_Chaska',\r\n 'city_Chicago',\r\n 'city_Chico',\r\n 'city_Cincinnati',\r\n 'city_Clarksburg',\r\n 'city_Colmar',\r\n 'city_Colorado Springs',\r\n 'city_Columbia',\r\n 'city_Columbus',\r\n 'city_Culver City',\r\n 'city_Dallas',\r\n 'city_Danville',\r\n 'city_Deerfield',\r\n 'city_Denver',\r\n 'city_Detroit',\r\n 'city_Dublin',\r\n 'city_Durham',\r\n 'city_Eden Prairie',\r\n 'city_Englewood',\r\n 'city_Eugene',\r\n 'city_Eureka',\r\n 'city_Fairport',\r\n 'city_Falls Church',\r\n 'city_Flint',\r\n 'city_Florham Park',\r\n 'city_Fort Wayne',\r\n 'city_Fremont',\r\n 'city_Ft Carson',\r\n 'city_Garden City',\r\n 'city_Gilbert',\r\n 'city_Glendale',\r\n 'city_Golden',\r\n 'city_Grand Prairie',\r\n 'city_Greensboro',\r\n 'city_Harrisburg',\r\n 'city_Hartford',\r\n 'city_Hayward',\r\n 'city_Herndon',\r\n 'city_Highland',\r\n 'city_Houston',\r\n 'city_Indianapolis',\r\n 'city_Industry',\r\n 'city_Irving',\r\n 'city_Jacksonville',\r\n 'city_Jersey City',\r\n 'city_Kansas City',\r\n 'city_King of Prussia',\r\n 'city_Ladera Ranch',\r\n 'city_Lafayette',\r\n 'city_Lake Mary',\r\n 'city_Lancaster',\r\n 'city_Laramie',\r\n 'city_Las Vegas',\r\n 'city_Leander',\r\n 'city_Lenexa',\r\n 'city_Long Beach',\r\n 'city_Los Angeles',\r\n 'city_Loveland',\r\n 'city_Lowell',\r\n 'city_Mahwah',\r\n 'city_Malden',\r\n 'city_McLean',\r\n 'city_Medford',\r\n 'city_Memphis',\r\n 'city_Miami',\r\n 'city_Miami Lakes',\r\n 'city_Minneapolis',\r\n 'city_Minnetonka',\r\n 'city_Mount Laurel',\r\n 'city_Mountain View',\r\n 'city_Mundelein',\r\n 'city_Naples',\r\n 'city_Nashville',\r\n 'city_New Britain',\r\n 'city_New Haven',\r\n 'city_New York',\r\n 'city_Newark',\r\n 'city_Newport News',\r\n 'city_Norfolk',\r\n 'city_Normal',\r\n 'city_North Canton',\r\n 'city_Northbrook',\r\n 'city_Oakland',\r\n 'city_Ogden',\r\n 'city_Oklahoma',\r\n 'city_Oklahoma City',\r\n 'city_Orlando',\r\n 'city_Palm Beach Gardens',\r\n 'city_Palo Alto',\r\n 'city_Parsippany',\r\n 'city_Pasadena',\r\n 'city_Philadelphia',\r\n 'city_Phoenix',\r\n 'city_Pittsburgh',\r\n 'city_Plano',\r\n 'city_Pleasanton',\r\n 'city_Plymouth',\r\n 'city_Portland',\r\n 'city_Portsmouth',\r\n 'city_Provo',\r\n 'city_Quantico',\r\n 'city_Raleigh',\r\n 'city_Reading',\r\n 'city_Reno',\r\n 'city_Richardson',\r\n 'city_Richmond',\r\n 'city_Riverwoods',\r\n 'city_Roanoke',\r\n 'city_Rolling Meadows',\r\n 'city_Rosemont',\r\n 'city_Roswell',\r\n 'city_Roy',\r\n 'city_Sacramento',\r\n 'city_Saint Louis',\r\n 'city_Saint Petersburg',\r\n 'city_Salt Lake City',\r\n 'city_San Antonio',\r\n 'city_San Diego',\r\n 'city_San Francisco',\r\n 'city_San Jose',\r\n 'city_San Marcos',\r\n 'city_Santa Barbara',\r\n 'city_Santa Clara',\r\n 'city_Santa Cruz',\r\n 'city_Scottsdale',\r\n 'city_Seattle',\r\n 'city_Sellersville',\r\n 'city_Sheldonville',\r\n 'city_Solon',\r\n 'city_Somerset',\r\n 'city_Springfield',\r\n 'city_St Louis Park',\r\n 'city_Stamford',\r\n 'city_Stanford',\r\n 'city_Stevens Point',\r\n 'city_Sycamore',\r\n 'city_Tampa',\r\n 'city_Tempe',\r\n 'city_Tigard',\r\n 'city_Troy',\r\n 'city_Urbandale',\r\n 'city_Vienna',\r\n 'city_Virginia',\r\n 'city_Waltham',\r\n 'city_Warrenton',\r\n 'city_Washington',\r\n 'city_Waterbury',\r\n 'city_Wayne',\r\n 'city_Wellesley',\r\n 'city_West Palm Beach',\r\n 'city_Westlake Village',\r\n 'city_Westminster',\r\n 'city_Wilmington',\r\n 'city_Wilton',\r\n 'city_Winchester',\r\n 'city_Woodbury',\r\n 'city_Worthington'))\r\n\r\n st.write('You selected:', option)\r\n features[option] = 1 \r\n\r\n\r\n # state\r\n option = st.selectbox(\r\n 'Choose state: ',\r\n ('state_AK',\r\n 'state_AL',\r\n 'state_AZ',\r\n 'state_CA',\r\n 'state_CO',\r\n 'state_CT',\r\n 'state_DC',\r\n 'state_DE',\r\n 'state_FL',\r\n 'state_GA',\r\n 'state_IA',\r\n 'state_IL',\r\n 'state_IN',\r\n 'state_KS',\r\n 'state_KY',\r\n 'state_MA',\r\n 'state_MD',\r\n 'state_ME',\r\n 'state_MI',\r\n 'state_MN',\r\n 'state_MO',\r\n 'state_NC',\r\n 'state_NH',\r\n 'state_NJ',\r\n 'state_NV',\r\n 'state_NY',\r\n 'state_OH',\r\n 'state_OK',\r\n 'state_OR',\r\n 'state_PA',\r\n 'state_TN',\r\n 'state_TX',\r\n 'state_UT',\r\n 'state_VA',\r\n 'state_VT',\r\n 'state_WA',\r\n 'state_WI',\r\n 'state_WV',\r\n 'state_WY'))\r\n\r\n st.write('You selected:', option)\r\n features[option] = 1 \r\n\r\n file_name = \"model_file.p\"\r\n with open(file_name, 'rb') as pickled:\r\n data = pickle.load(pickled)\r\n model = data['model']\r\n\r\n features = list(features.values())\r\n features = np.array(features).reshape(1, -1)\r\n \r\n \r\n if st.button(\"Predict\"):\r\n result = float(predict_note_authentication(features, model))\r\n st.success('The predicted salary is: {} USD'.format(result*1000))\r\n \r\n\r\nif __name__ == '__main__':\r\n main()\r\n","sub_path":"streamlitAPP/st_app.py","file_name":"st_app.py","file_ext":"py","file_size_in_byte":30666,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"364959813","text":"#%% cell 0\nfrom multiprocessing import Pool\nimport sys\nsys.path.append('C:/Users/BOUÂMAMAElMehdi/documents/visual studio 2017/Projects/PythonBasics/PythonBasics/MBTI/')\nfrom DatabaseManager import *\nfrom TwitterManager import *\nfrom functools import partial\nimport os\n\nTweetFolderPath = \"M:/Datasets/TwitterMBTI/Parallel/\"\ndatas = ReadJsonFile(\"M:/Datasets/TwitterMBTI/MBTINotExtracted/twisty-2016-03/TwiSty-FR.json\")\nuserIds = GetUserIds(datas)\nos.chdir(TweetFolderPath)\n# We need to build a dictionnary of users / tweets first\n\nfor x in userIds[40:]:\n print(\"Processing user : \" + x)\n stringToSave = \"\"\n with Pool(100) as p:\n UserTweets = GetConfirmedTweetIdsOfUser(datas,x)\n checker = GetPostFromTwitter(UserTweets[0],x)\n print(checker)\n if(checker != \"\"):\n GetPostPartial = partial(GetPostFromTwitter, userId=x)\n result = p.map(GetPostPartial,UserTweets)\n else:\n result = \"\"\n with open(x + \".txt\",\"w+\", encoding=\"utf-8\") as file:\n file.writelines(result)\n\n","sub_path":"PythonBasics/Content/Helpers/ImportingDataIntoFiles.py","file_name":"ImportingDataIntoFiles.py","file_ext":"py","file_size_in_byte":1049,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"30572314","text":"import numpy as np\nimport pandas as pd\nfrom sklearn.feature_selection import SelectFromModel\nfrom sklearn.metrics import r2_score, mean_absolute_error as MAE\nfrom sklearn.model_selection import train_test_split, RandomizedSearchCV, GridSearchCV, KFold\nfrom sklearn.preprocessing import StandardScaler, MinMaxScaler, MaxAbsScaler, RobustScaler\nfrom lightgbm import LGBMRegressor\ntest = pd.read_csv('./data/dacon/comp1/test.csv', sep=',', header = 0, index_col = 0)\n\nx_train = np.load('./dacon/comp1/x_train.npy')\ny_train = np.load('./dacon/comp1/y_train.npy')\nx_pred = np.load('./dacon/comp1/x_pred.npy')\n\nx_train, x_test, y_train, y_test = train_test_split(\n x_train, y_train, train_size = 0.8, random_state = 66\n)\nprint(x_train.shape)\nprint(y_train.shape)\n# print(x_test.shape)\n\n# 2. model\nfinal_y_test_pred = []\nfinal_y_pred = []\nparameter = [\n {'n_estimators': [1],\n 'learning_rate': [0.05,0.06,0.07,0.08,0.09],\n 'max_depth': [6], \n 'boosting_type': ['dart'], \n 'drop_rate' : [0.3],\n 'objective': ['regression'], \n 'metric': ['logloss','mae'], \n 'is_training_metric': [True], \n 'num_leaves': [144], \n 'colsample_bytree': [0.7], \n 'subsample': [0.7]\n }\n]\n\nsettings = {\n 'verbose': False,\n 'eval_set' : [(x_train, y_train), (x_test,y_test)]\n}\n\nkfold = KFold(n_splits=5, shuffle=True, random_state=66)\n# 모델 컬럼별 4번\nfor i in range(4):\n model = LGBMRegressor()\n settings['eval_set'] = [(x_train, y_train[:,i]), (x_test,y_test[:,i])]\n model.fit(x_train,y_train[:,i], **settings)\n y_test_pred = model.predict(x_test)\n score = model.score(x_test,y_test[:,i])\n mae = MAE(y_test[:,i], y_test_pred)\n print(\"r2 : \", score)\n print(\"mae :\", mae)\n thresholds = np.sort(model.feature_importances_)[ [i for i in range(0,len(model.feature_importances_), 20)] ]\n print(\"model.feature_importances_ : \", model.feature_importances_)\n print(thresholds)\n best_mae = mae\n best_model = model\n best_y_pred = model.predict(x_pred)\n best_y_test_pred = y_test_pred\n print(best_y_pred.shape)\n for thresh in thresholds:\n if(thresh == 0): continue\n selection = SelectFromModel(model, threshold=thresh, prefit=True)\n # median 이 둘중 하나 쓰는거 이해하면 사용 가능\n ## 이거 주어준 값 이하의 중요도를 가진 feature를 전부 자르는 파라미터\n select_x_train = selection.transform(x_train)\n select_x_test = selection.transform(x_test)\n select_x_pred = selection.transform(x_pred)\n\n print(select_x_train.shape)\n\n selection_model = RandomizedSearchCV(LGBMRegressor(), parameter, cv = kfold,n_iter=4)\n settings['eval_set'] = [(select_x_train, y_train[:,i]), (select_x_test,y_test[:,i])]\n selection_model.fit(select_x_train, y_train[:,i], **settings)\n\n y_pred = selection_model.predict(select_x_test)\n r2 = r2_score(y_test[:,i],y_pred)\n mae = MAE(y_test[:,i],y_pred)\n print(selection_model.best_params_)\n if mae <= best_mae:\n print(\"예아~\")\n best_mae = mae\n best_model = selection_model\n best_y_pred = selection_model.predict(select_x_pred)\n best_y_test_pred = y_pred\n print(\"Thresh=%.3f, n=%d, MAE: %.5f R2: %.2f%%\" %(thresh, select_x_train.shape[1], mae, r2*100))\n final_y_pred.append(best_y_pred)\n final_y_test_pred.append(best_y_test_pred)\n\nprint('MAE :', MAE(y_test, np.array(final_y_test_pred).T))\n\nfinal_y_pred = np.array(final_y_pred)\n\nsubmissions = pd.DataFrame({\n \"id\": np.array(range(10000,20000)),\n \"hhb\": y_pred[:, 0],\n \"hbo2\": y_pred[:, 1],\n \"ca\": y_pred[:, 2],\n \"na\": y_pred[:, 3]\n})\nprint(submissions)\nsubmissions.to_csv('./Dacon/comp1/comp1_sub.csv', index = False)","sub_path":"Dacon/comp1/202006260211.py","file_name":"202006260211.py","file_ext":"py","file_size_in_byte":3865,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"108183014","text":"#!/usr/bin/env python2.5\n#\n# Copyright 2010 \n#\n# Compute intensity quantiles of a set of spectra.\n#\n# Usage:\n\n__authors__ = [ 'Ajit Singh ' ]\n\nimport os\nimport sys\n\nfrom optparse import OptionParser\n\nfrom msutil.ms2util import MS2_iterator\nfrom util.statistics import mean, variance\nfrom recipes.quantile import quantile\n\nif __name__ == \"__main__\":\n parser = OptionParser(usage = \"usage: %prog [options]\")\n parser.add_option(\"-i\", \"--input\",\n action = \"store\", type = \"string\", dest = \"filename\",\n help = \"Name of MS2 formatted spectra file to read.\")\n parser.add_option(\"-z\", \"--use_gzcat\",\n action = \"store_true\", dest = \"gzcat\",\n default = False, help = \"Use gzcat to decompress.\")\n (options, args) = parser.parse_args()\n\n if options.filename == '':\n parser.print_help()\n exit(-1)\n\n intensities = [ ]\n fn = os.path.abspath(options.filename)\n for s in MS2_iterator(fn, options.gzcat):\n intensities.extend(s.intensity)\n intensities = sorted(intensities)\n\n qtype = 8\n low = quantile(intensities, 1.0/3.0, qtype = qtype, issorted = True)\n med = quantile(intensities, 0.5, qtype = qtype, issorted = True)\n high = quantile(intensities, 2.0/3.0, qtype = qtype, issorted = True)\n\n print (low, med, high)\n\n","sub_path":"sourceCodes/python/spectra/spectra_intensity_quantiles.py","file_name":"spectra_intensity_quantiles.py","file_ext":"py","file_size_in_byte":1386,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"542366234","text":"print(\"=========1========\")\r\n\r\nfrom time import time\r\nfrom sys import version\r\nfrom random import *\r\n\r\npowt = 1000\r\nN = 10000\r\n\r\ndef tester(fun):\r\n\tt1 = time()\r\n\tfor i in range(powt):\r\n\t\tfun(N)\r\n\tt2 = time()\r\n\treturn t2-t1\r\n\r\ndef forStatement(n):\r\n\tl = []\r\n\tfor i in range(n):\r\n\t\tl.append(i*i)\r\n\r\ndef listComprehension(n):\r\n\tl = [i*i for i in range(n)]\r\n\r\ndef mapFunction(n):\r\n\tl = map(lambda i: i*i, range(n))\r\n\r\ndef generatorExpression(n):\r\n\tl = (i*i for i in range(n))\r\n\r\nprint(version)\r\ntest = (forStatement,listComprehension,mapFunction,generatorExpression)\r\nfor testFunction in test:\r\n\tprint(testFunction.__name__.ljust(20), '=>',tester(testFunction))\r\n\r\nprint(\"===========2=========\")\r\nl1 = [randrange(0,20) for i in range(100)]\r\nl2 = [randrange(0,20) for i in range(100)]\r\n#l3 = list(zip(l1,l2))\r\nk1 = list(filter(lambda x: sum(x)>3 and sum(x)<15,zip(l1,l2)))\r\nprint(k1)\r\n\r\nprint(\"==========3==========\")\r\nfrom math import sqrt\r\n\r\ndef trzecia(a,b):\r\n\tx_sr = sum(a)/len(a)\r\n\ty_sr = sum(b)/len(b)\r\n\tn = len(a)\r\n\tD = sum(list(map(lambda x: (x-x_sr)**2,a)))\r\n\tprint(D)\r\n\tc = 1/D * sum(list(map(lambda y,x: y*(x-x_sr),b,a)))\r\n\tprint(c)\r\n\td = y_sr - c * x_sr\r\n\tprint(d)\r\n\tdy = sqrt((sum(map(lambda y,x: (y - (c*x+d))**2,b,a)))/(n-2))\r\n\tprint(dy)\r\n\tdc = dy/sqrt(D)\r\n\tprint(dc)\r\n\tdd = dy*sqrt(1/n + (x_sr**2)/D)\r\n\tprint(dd)\r\n\treturn c,d,dy,dc,dd\r\n\t\r\n\r\na = [1,5,8,3]\r\nb = [1,3,2,4]\r\nprint(trzecia(a,b))\r\n\r\nprint(\"==========4===========\")\r\n\r\ndef myreduce(fun,a):\r\n\tx = a[0]\r\n\tfor i in a[1:]:\r\n\t\tx = fun(x,i)\r\n\treturn x\r\n\r\nprint(myreduce(lambda x,y: x+y,[1,2,3,4]))\r\nprint(myreduce(lambda x,y: x*y, [1,2,3,4]))\r\n\r\nprint(\"=========5============\")\r\nl5 = [[randrange(0,10),randrange(0,10)] for i in range(5)]\r\nprint(l5)\r\n#lo = myreduce(lambda x,y: map(isinstance(l5[0],int) x.append(l5[0]),l5),l5)","sub_path":"Lab5/zad.py","file_name":"zad.py","file_ext":"py","file_size_in_byte":1791,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"223495692","text":"# -*- coding:utf-8 -*-\n# @author :adolf\nimport requests\nimport base64\nimport os\nfrom shutil import copyfile\n\n# img_path = \"/home/shizai/adolf/ocr_project/rpa_verification/experiment_test/guoshui/captcha_img/img_4666_blue.png\"\nimg_dir = \"/home/shizai/adolf/ocr_project/rpa_verification/experiment_test/guoshui/captcha_img/\"\nimg_list = os.listdir(img_dir)\nfor img_name in img_list[-300:]:\n img_path = os.path.join(img_dir, img_name)\n color = img_path.split(\".\")[0].split(\"_\")[-1]\n # print(color)\n with open(img_path, \"rb\") as f:\n b = f.read()\n # param_key: black-全黑色,red-红色,blue-蓝色,yellow-黄色\n r = requests.post(\"http://152.136.207.29:19812/captcha/v1\", json={\n \"uid\": \"09a253fa-11f3-11eb-b6f9-525400a21e62\",\n \"model_name\": \"TAX\",\n \"image\": base64.b64encode(b).decode(),\n \"param_key\": color\n })\n print(r.json())\n res = r.json()['message']\n target_path = \"/home/shizai/adolf/ocr_project/rpa_verification/experiment_test/guoshui/captcha_xy\"\n if not os.path.exists(target_path):\n os.mkdir(target_path)\n copyfile(img_path, os.path.join(target_path, res + \"_\" + color + \".png\"))\n","sub_path":"experiment_test/guoshui/third/test_third.py","file_name":"test_third.py","file_ext":"py","file_size_in_byte":1167,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"128420402","text":"import requests\nimport re\nimport sys\nfrom datetime import datetime\nimport sqlite3\nimport sqlalchemy as db\nfrom sqlalchemy import create_engine\nfrom sqlalchemy import Column, Date, Integer, String, PickleType, select\nfrom sqlalchemy.ext.declarative import declarative_base\nimport pickle\nimport tkinter as tk\nimport json\n\ndef getData(name, Base, engine, tags):\n with open('synonyms.json') as f:\n d = json.load(f)\n if name in d.keys():\n name = d[name]\n urlName = \"https://\" + name\n site = requests.get(urlName)\n text = site.text\n pattern = re.compile(r'<((?!!)/?[a-zA-Z]*[\\s]*)')\n tagsDict = {}\n for i in re.findall(pattern, text):\n if i in tagsDict:\n tagsDict[i] += 1\n else:\n tagsDict[i] = 1\n sumOfTags = 0\n for i in tagsDict:\n sumOfTags += tagsDict[i]\n f = open(\"logs.txt\",\"a+\")\n dateTimeObj = datetime.now()\n timestampStr = dateTimeObj.strftime(\"%d-%b-%Y %H:%M:%S\")\n f.write(timestampStr + \"\\t\" + name + \"\\n\")\n f.close() \n\n query = db.insert(tags).values(name=name, url = urlName, date = dateTimeObj, tags_dict = tagsDict) \n # ResultProxy = engine.execute(query)\n engine.execute(query) \n return tagsDict\n\ndef view(name, engine, tags):\n with open('synonyms.json') as f:\n d = json.load(f)\n if name in d.keys():\n name = d[name]\n query = db.select([tags]).where(tags.name==name)\n ResultProxy = engine.execute(query)\n ResultSet = ResultProxy.first()\n return ResultSet\n\ndef main ():\n engine = create_engine('sqlite:///database.db')\n Base = declarative_base()\n\n class tags(Base):\n __tablename__ = \"tags\"\n id = Column(Integer, primary_key=True)\n name = Column(String) \n url = Column(String) \n date = Column(Date) \n tags_dict = Column(PickleType) \n \n def __init__(self, name, url, date, tags_dict):\n self.name = name \n self.url = url \n self.date = date \n self.tags_dict = tags_dict \n \n Base.metadata.create_all(engine)\n \n if len(sys.argv) > 1:\n if (sys.argv[1] == \"--view\"):\n print(view(sys.argv[2], engine, tags))\n elif (sys.argv[1] == \"--get\"):\n print(getData(sys.argv[2], Base, engine, tags))\n else:\n\n class App(tk.Frame):\n def __init__(self, master=None):\n super().__init__(master)\n self.master = master\n self.pack()\n self.create_widgets()\n\n\n \n def print_contents(self, event):\n print(self.contents.get())\n \n def create_widgets(self):\n self.get = tk.Button(self)\n self.get[\"text\"] = \"Загрузить\"\n self.get[\"command\"] = self.getDataW\n self.get.pack(side=\"left\", pady=10)\n\n self.view = tk.Button(self)\n self.view[\"text\"] = \"Показать из базы\"\n self.view[\"command\"] = self.viewDataW\n self.view.pack(side=\"left\", pady=10)\n\n self.entrythingy = tk.Entry()\n self.entrythingy.pack(side=\"top\")\n self.contents = tk.StringVar()\n self.contents.set(\"\")\n self.entrythingy[\"textvariable\"] = self.contents\n self.entrythingy.bind('',\n self.print_contents)\n\n self.get1 = tk.Button(self)\n self.get1[\"text\"] = \"Загрузить - Combobox\"\n self.get1[\"command\"] = self.getDataS\n self.get1.pack(side=\"left\", pady=10)\n\n self.view1 = tk.Button(self)\n self.view1[\"text\"] = \"Показать из базы - Combobox\"\n self.view1[\"command\"] = self.viewDataS\n self.view1.pack(side=\"left\", pady=10)\n\n \n self.Lb1 = tk.Listbox(root)\n self.Lb1.pack(side=\"top\")\n self.Lb1.insert(1, \"google.com\")\n self.Lb1.insert(2, \"www.facebook.com\")\n self.Lb1.pack()\n\n \n def getDataW(self):\n DataForDisplay = getData(self.contents.get(), Base, engine, tags)\n text.set(DataForDisplay)\n app.delete('1.0', tk.END)\n app.insert(tk.CURRENT, text.get())\n app.mainloop()\n \n\n def viewDataW(self):\n DataForDisplay = view(self.contents.get(), engine, tags)\n text.set(DataForDisplay)\n app.delete('1.0', tk.END)\n app.insert(tk.CURRENT, text.get())\n app.mainloop()\n\n def getDataS(self):\n DataForDisplay = getData(self.Lb1.get(self.Lb1.curselection()), Base, engine, tags)\n text.set(DataForDisplay)\n app.delete('1.0', tk.END)\n app.insert(tk.CURRENT, text.get())\n app.mainloop()\n \n\n def viewDataS(self):\n DataForDisplay = view(self.Lb1.get(self.Lb1.curselection()), engine, tags)\n text.set(DataForDisplay)\n app.delete('1.0', tk.END)\n app.insert(tk.CURRENT, text.get())\n app.mainloop()\n \n \n root = tk.Tk()\n\n text = tk.StringVar()\n text.set('')\n\n\n app = App(master=root)\n app = tk.Text(root, height=30, width=100)\n app.pack(side=\"left\",fill=\"both\",expand=True)\n # scroll = tk.Scrollbar(app)\n # scroll.pack(side=\"right\",fill=\"y\",expand=False)\n app.insert(tk.END, text.get())\n app.mainloop()\n\n\n \nif __name__ == '__main__':\n main()","sub_path":"tagcounter_app/tagcounter.py","file_name":"tagcounter.py","file_ext":"py","file_size_in_byte":5808,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"517251119","text":"\nfrom threading import Thread\n #modeul sauvagardant les candle d'une minute sous thread dans des fichiers\n#le run lance le thread qui scanne la fif et enregistre\n# pushresu charge la fifo avec des valeurs (semaine, minute, paire, nbmesures, open, top, low, close)\n\n\n# Start running the threads!\n\n\nimport queue\nimport time\nimport csv\n\nclass MyThread(Thread):\n q=None\n\n def __init__(self):\n ''' Constructor. '''\n Thread.__init__(self)\n self.q = queue.Queue()\n\n\n def pushresu(self, semaine,minute,paire,nbmesures,open,top, low, close):\n i=[semaine,minute,paire,nbmesures,open,top, low, close]\n if (self.q != None):\n self.q.put(i)\n\n\n def run(self):\n Encore = True\n while (Encore):\n while not self.q.empty():\n i = self.q.get()\n print(i)\n #print('Value %d in thread %s' % (i, self.getName()))\n #filename = i[2]+String(i[1])+String(i[0])+\".csv\"\n filename = i[2] + \"-\"+ '%0*d' % (3, i[0])+\".csv\"\n print(filename)\n with open(filename,'a') as csvfile:\n spamwriter = csv.writer(csvfile,delimiter='\\t',quotechar='|', quoting=csv.QUOTE_MINIMAL)\n\n spamwriter.writerow(i)\n csvfile.close()\n\n time.sleep(1)","sub_path":"candlesave.py","file_name":"candlesave.py","file_ext":"py","file_size_in_byte":1345,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"344938659","text":"#!/usr/local/autopkg/python\n#\n# Copyright 2019 Nathaniel Strauss\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom __future__ import absolute_import\n\nimport json\n\nfrom autopkglib import Processor, ProcessorError, URLGetter # noqa: F401\n\n__all__ = [\"SimpleJSONParser\"]\n\n\nclass SimpleJSONParser(URLGetter):\n \"\"\"Processor to output specified value of a JSON formatted file.\"\"\"\n\n description = __doc__\n input_variables = {\n \"json_key\": {\"required\": True, \"descripton\": \"JSON key value to be parsed.\",},\n \"json_url\": {\"required\": True, \"description\": \"URL of the JSON to be parsed.\",},\n }\n output_variables = {\"json_value\": {\"description\": \"JSON value from input key.\"}}\n\n def main(self):\n url = self.env.get(\"json_url\")\n response = self.download(url)\n key = self.env.get(\"json_key\")\n self.env[\"json_value\"] = json.loads(response)[key]\n self.output(\"{}\".format(self.env[\"json_value\"]))\n\n\nif __name__ == \"__main__\":\n processor = SimpleJSONParser()\n processor.execute_shell()\n","sub_path":"TestNav/SimpleJSONParser.py","file_name":"SimpleJSONParser.py","file_ext":"py","file_size_in_byte":1545,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"319191681","text":"from flask import Blueprint, render_template, abort, request, redirect, session\nfrom sqlalchemy import desc\nfrom KerbalStuff.objects import Featured, BlogPost, Mod\nfrom KerbalStuff.search import search_mods\nfrom KerbalStuff.common import *\n\nimport praw\n\nanonymous = Blueprint('anonymous', __name__, template_folder='../../templates/anonymous')\nr = praw.Reddit(user_agent=\"Kerbal Stuff\")\n\n@anonymous.route(\"/\")\ndef index():\n featured = Featured.query.order_by(desc(Featured.created)).limit(7)[:7]\n blog = BlogPost.query.order_by(desc(BlogPost.created)).all()\n return render_template(\"index.html\", featured=featured, blog=blog)\n\n@anonymous.route(\"/browse\")\ndef browse():\n featured = Featured.query.order_by(desc(Featured.created)).limit(7)[:7]\n top = search_mods(\"\", 0)[:7]\n new = Mod.query.filter(Mod.published).order_by(desc(Mod.created)).limit(7)[:7]\n return render_template(\"browse.html\", featured=featured, top=top, new=new)\n\n@anonymous.route(\"/about\")\ndef about():\n return render_template(\"about.html\")\n\n@anonymous.route(\"/markdown\")\ndef markdown_info():\n return render_template(\"markdown.html\")\n\n@anonymous.route(\"/privacy\")\ndef privacy():\n return render_template(\"privacy.html\")\n\n@anonymous.route(\"/search\")\ndef search():\n query = request.args.get('query')\n if not query:\n query = ''\n results = search_mods(query, 0)\n wrapped = list()\n for result in results:\n m = wrap_mod(result)\n if m:\n wrapped.append(m)\n return render_template(\"search.html\", results=wrapped, query=query)\n\n@anonymous.route(\"/c/\")\ndef c():\n s = r.get_subreddit(\"awwnime\").get_hot(limit=100)\n return render_template(\"c.html\", s=s)\n","sub_path":"KerbalStuff/blueprints/anonymous.py","file_name":"anonymous.py","file_ext":"py","file_size_in_byte":1692,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"415993030","text":"from __future__ import absolute_import\nimport os\nfrom celery import Celery, task\nfrom django.apps import AppConfig\nfrom django.conf import settings\nfrom django.core.management import call_command\nfrom django.core.mail import send_mail\nimport environ\n\nenv = environ.Env()\n\nif not settings.configured:\n # set the default Django settings module for the 'celery' program.\n os.environ.setdefault('DJANGO_SETTINGS_MODULE',\n 'config.settings.local') # pragma: no cover\n\n\napp = Celery('thesis_web',\n broker='redis://localhost',\n backend='redis://localhost',\n )\n\n\nclass CeleryConfig(AppConfig):\n name = 'thesis_web.taskapp'\n verbose_name = 'Celery Config'\n\n def ready(self):\n # Using a string here means the worker will not have to\n # pickle the object when using Windows.\n app.config_from_object('django.conf:settings')\n app.autodiscover_tasks(lambda: settings.INSTALLED_APPS, force=True)\n\n\n@app.task(bind=True)\ndef debug_task(self):\n print('Request: {0!r}'.format(self.request)) # pragma: no cover\n\n\n@task\ndef backup_database():\n return call_command('dbbackup')\n\n\n@task\ndef backup_media_files():\n return call_command('mediabackup')\n\n\n@task\ndef check_disk_quota():\n df = os.popen(\"df -Ph\").read()\n df_lines = df.split('\\n')\n use = ''\n for line in df_lines:\n if '/home/web' in line:\n fs, size, used, avail, use, mounted = line.split()\n if use[:-1] > 90:\n send_mail('Disk quota lavinia.fi.muni.cz',\n 'Automatic script tool detected that disk capacity exceeded to 90% of their capacity. Please,\\\nclear unused files or add more capacity.\\\n\\\nYou can turn off this checks at /admin/djcelery',\n 'noreply@lavinia.fi.muni.cz',\n '422437@mail.muni.cz')\n\n\nif __name__ == '__main__':\n app.start()\n","sub_path":"thesis_web/taskapp/celery.py","file_name":"celery.py","file_ext":"py","file_size_in_byte":1885,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"426607270","text":"\nimport itertools\n\n\nn = int(input())\n\ns = list(map(int, input().split()))\na = []\nb = []\n\nif n == len(s):\n for i in range(n):\n a.append(i + 1)\n\n p = itertools.permutations(a)\n\n for i in p:\n i = list(i)\n b.append(i)\n b.append(-1)\n\n if s in b:\n print(b[b.index(s) + 1])\n","sub_path":"baekjoon/b10972.py","file_name":"b10972.py","file_ext":"py","file_size_in_byte":310,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"459347629","text":"import pytest\n\nimport ibis\nimport ibis.expr.datatypes as dt\nimport ibis.expr.operations as ops\n\n\n@pytest.mark.parametrize(\n ['arg', 'type'],\n [\n ([1, 2, 3], dt.Array(dt.int8)),\n ([1, 2, 3.0], dt.Array(dt.double)),\n (['a', 'b', 'c'], dt.Array(dt.string)),\n ],\n)\ndef test_array_literal(arg, type):\n x = ibis.literal(arg)\n assert x._arg.value == arg\n assert x.type() == type\n\n\ndef test_array_length_scalar():\n raw_value = [1, 2, 4]\n value = ibis.literal(raw_value)\n expr = value.length()\n assert isinstance(expr.op(), ops.ArrayLength)\n","sub_path":"ibis/tests/expr/test_array.py","file_name":"test_array.py","file_ext":"py","file_size_in_byte":583,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"649552964","text":"\"\"\"\n==================================\nSample Excel Exhibit functionality\n==================================\n\nThis example demonstrates some of the flexibility of the ``Exhibits`` class. It\ncreates an Excel file called 'clrd.xlsx' that includes various statistics on\nindustry development patterns for each line of business in the CAS loss reserve\ndatabase.\n\nSee :ref:`Exhibits` for more detail.\n\n.. _exhibit_example:\n\"\"\"\nimport chainladder as cl\nimport pandas as pd\n\n# Grab industry Paid Triangles\nclrd = cl.load_dataset('clrd').groupby('LOB').sum()['CumPaidLoss']\n\n# Create instance of Exhibits\nexhibits = cl.Exhibits()\n\n# Line of Business Dictionary for looping\nlobs = dict(comauto='Commercial Auto',\n medmal='Medical Malpractice',\n othliab='Other Liability',\n ppauto='Private Passenger Auto',\n prodliab='Product Liability',\n wkcomp='Workers\\' Compensation')\n\n# Loop through each LOB\nfor key, value in lobs.items():\n title = ['CAS Loss Reserve Database',\n value, 'Cumulative Paid Loss',\n 'Evaluated as of 31-December-1997']\n # Show Raw Triangle\n exhibits.add_exhibit(key, clrd.loc[key],\n header=True, formats='money',\n title=title, col_nums=False,\n index_label='Accident Year')\n # Show Link Ratios\n exhibits.add_exhibit(key, clrd.loc[key].link_ratio,\n header=True, formats='decimal',\n col_nums=False,\n index_label='Accident Year',\n start_row=clrd.shape[2]+6)\n # Show various Various Averages\n df = pd.concat(\n (cl.Development(n_periods=2).fit(clrd.loc[key]).ldf_.drop_duplicates(),\n cl.Development(n_periods=3).fit(clrd.loc[key]).ldf_.drop_duplicates(),\n cl.Development(n_periods=7).fit(clrd.loc[key]).ldf_.drop_duplicates(),\n cl.Development().fit(clrd.loc[key]).ldf_.drop_duplicates(),\n cl.Development().fit(clrd.loc[key]).ldf_.drop_duplicates()),\n axis=0)\n df.index = ['2 Yr Wtd', '3 Yr Wtd', '7 Yr Wtd', '10 Yr Wtd', 'Selected']\n exhibits.add_exhibit(key, df, col_nums=False, formats='decimal',\n index_label='Averages', start_row=clrd.shape[2]*2+7)\n\n# Create Excel File\nexhibits.to_excel('clrd.xlsx')\n","sub_path":"docs/auto_examples/plot_exhibits.py","file_name":"plot_exhibits.py","file_ext":"py","file_size_in_byte":2360,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"488835493","text":"#!/usr/bin/env python3\n\nimport numpy as np\nimport itertools\nimport argparse\nimport collections\n\ndef states_of_Y(x, states):\n \"\"\"all possible states of Y to evaluate likelihood\"\"\"\n n_observations = len(x)\n y = list(itertools.product(states, repeat = n_observations))\n return y\ndef transArray(arr):\n \"\"\"return the transitions of an array\"\"\"\n return [(arr[i],arr[i+1]) for i in range(len(arr) - 1)]\ndef print_out(y_scores):\n \"\"\"print scores in a sorted order\"\"\"\n for y, score in sorted(y_scores.items(), key=lambda x: x[1]):\n print(\"{}\\t{}\".format(score, y))\n\ndef main(inputString):\n states = ['r', 's']\n obs = ['w', 'h', 'c']\n\n transitions = {\n ('r', 'r') : 0.7,\n ('r', 's') : 0.3,\n ('s', 'r') : 0.4,\n ('s', 's') : 0.6\n }\n\n emissions = {\n ('r', 'w') : 0.1,\n ('r', 'h') : 0.4,\n ('r', 'c') : 0.5,\n ('s', 'w') : 0.6,\n ('s', 'h') : 0.3,\n ('s', 'c') : 0.1\n }\n\n\n\n x = list(inputString)\n Y = states_of_Y(x, states)\n\n y_scores = dict()\n\n # iterate over all possible seqStates of Y\n for y in Y:\n\n # transistion states of sequence\n trans = transArray(y)\n\n # store log-likelihood values of each state\n logs = []\n\n # iterate across the nodes of the sequence\n for i in range(len(y)):\n\n # begin at node t1 and create start probability from first emission\n if i == 1:\n p_past = emissions[(y[i-1], x[i])]\n p_trans = transitions[trans[i-1]]\n p_current = emissions[(y[i], x[i])]\n\n # sum of log-likelihood function for node\n logs.append(\n sum([np.log(p) for p in [p_past, p_trans, p_current]])\n )\n\n # from node t2 on draw p_past from logs list\n if i > 1:\n p_past = logs[i - 2]\n p_trans = transitions[trans[i-1]]\n p_current = emissions[(y[i], x[i])]\n\n logs.append(\n sum(\n [p_past] + # already in log form\n [np.log(p) for p in [p_trans, p_current]])\n )\n\n # summation of log-likelihoods of each node for each y\n y_scores[y] = sum(logs)\n\n\n print_out(y_scores)\n\nif __name__ == '__main__':\n p = argparse.ArgumentParser()\n p.add_argument('-i', '--input', help = 'string of [whc] to predict states of weather', required=True)\n args = p.parse_args()\n main(args.input)\n","sub_path":"weather.py","file_name":"weather.py","file_ext":"py","file_size_in_byte":2537,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"184547759","text":"import sys\r\nsys.stdin = open(\"input.txt\", \"r\")\r\n\r\nimport itertools\r\n\r\nN, S = map(int, input().split())\r\nnumbers = list(map(int, input().split()))\r\nans = 0\r\nfor i in range(1, N+1):\r\n nCr = itertools.combinations(numbers, i)\r\n nCr_list = list(nCr)\r\n for i in range(len(nCr_list)):\r\n temp = nCr_list[i]\r\n cnt = 0\r\n for j in range(len(nCr_list[i])):\r\n cnt += nCr_list[i][j]\r\n if cnt == S:\r\n ans += 1\r\n #print(nCr_list[i])\r\n\r\nprint(ans)\r\n\r\n\r\n\r\n\r\n","sub_path":"Algorithm/Python/부분수열의합.py","file_name":"부분수열의합.py","file_ext":"py","file_size_in_byte":511,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"351644758","text":"\ndef find_noun_and_verb(): \n noun = 0\n verb = 0\n while noun < 100:\n verb = 0\n while verb < 100:\n intcode = [ int(x) for x in open('2019/day2/input.txt').readline().split(',') ]\n # test input\n #intcode = [ int(x) for x in open('2019/day2/testinput.txt').readline().split(',') ]\n\n intcode[1] = noun\n intcode[2] = verb\n i = 0\n while i < len(intcode):\n if intcode[i] == 1:\n intcode[intcode[i + 3]] = intcode[intcode[i + 1]] + intcode[intcode[i + 2]]\n elif intcode[i] == 2:\n intcode[intcode[i + 3]] = intcode[intcode[i + 1]] * intcode[intcode[i + 2]]\n elif intcode[i] == 99:\n break\n else:\n print('WTF')\n print(intcode)\n print(i)\n i += 4\n\n if intcode[0] == 19690720:\n print(intcode)\n return (noun, verb)\n verb += 1\n noun += 1\n return (None, None)\n\nnoun, verb = find_noun_and_verb()\nprint(noun)\nprint(verb)\nprint(noun * 100 + verb)\n\n\n\n\n ","sub_path":"2019/day2/puzzle2.py","file_name":"puzzle2.py","file_ext":"py","file_size_in_byte":1188,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"42379324","text":"def create_line_scan(self):\n if self.RSM is not None:\n self.busy_label.configure(text=\"Busy! Processing %s data points.\" % len(self.RSM.intensity))\n if self.origin_parallel_entry.get() != \"\":\n self.origin_parallel = float(self.origin_parallel_entry.get())\n if self.origin_normal_entry.get() != \"\":\n self.origin_normal = float(self.origin_normal_entry.get())\n if self.linescan_angle_entry.get() != \"\":\n self.linescan_angle = float(self.linescan_angle_entry.get())\n if self.linescan_width_entry.get() != \"\":\n self.linescan_width = float(self.linescan_width_entry.get())\n\n line = self.RSM.create_line_scan(self.origin_parallel, self.origin_normal,\n self.linescan_angle, self.linescan_width)\n\n self.linescan_plot_figure.patch.set_facecolor('white')\n bx = self.linescan_plot_figure.gca()\n bx.clear()\n bx.plot(line[0], line[1], '-o')\n bx.set_xlim(-0.005, 0.005)\n bx.set_yscale(self.line_scale.get())\n bx.set_ylabel(\"Counts\")\n bx.set_xlabel(r\"Distance from origin $[\\AA]^{-1}$\")\n\n self.linescan_canvas.draw()\n self.busy_label.configure(text=\"\")","sub_path":"dumpster.py","file_name":"dumpster.py","file_ext":"py","file_size_in_byte":1236,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"515703842","text":"class Solution(object):\n def totalNQueens(self, n):\n \"\"\"\n :type n: int\n :rtype: int\n \"\"\"\n self.total = 0\n\n def solve(cols, xy_sum, xy_diff):\n y = len(cols)\n if y == n:\n self.total += 1\n return\n for x in range(n):\n if x not in cols and x + y not in xy_sum and x - y not in xy_diff:\n cols.append(x)\n xy_sum.add(x + y)\n xy_diff.add(x - y)\n solve(cols, xy_sum, xy_diff)\n xy_sum.discard(x + y)\n xy_diff.discard(x - y)\n cols.pop()\n solve([], set(), set())\n return self.total\n","sub_path":"n_queens_ii.py","file_name":"n_queens_ii.py","file_ext":"py","file_size_in_byte":739,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"124225131","text":"import requests\n\ndata = {{i.data}}\nr = requests.post({{i.url | quote}}, data)\n\nrc = int(r.status_code)\nif rc != 200:\n\traise Exception('Failed to POST to {{i.url}}, status code is %s' % rc)\n\nwith open({{o.outfile | quote}}, 'w') as fout:\n\tfout.write(r.text)\n","sub_path":"bioprocs/scripts/web/pDownloadPost.py","file_name":"pDownloadPost.py","file_ext":"py","file_size_in_byte":262,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"608194807","text":"#\n# Copyright 2018 Analytics Zoo Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\nimport pandas as pd\nfrom zoo.chronos.preprocessing.utils import train_val_test_split\nfrom zoo.orca import init_orca_context, stop_orca_context\nfrom zoo.orca import OrcaContext\nfrom zoo.chronos.autots.forecast import AutoTSTrainer\nfrom zoo.chronos.config.recipe import LSTMGridRandomRecipe\nfrom zoo.chronos.autots.forecast import TSPipeline\nimport os\nimport argparse\nimport tempfile\n\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--cluster_mode', type=str, default=\"local\",\n help='The mode for the Spark cluster.')\nparser.add_argument(\"--num_workers\", type=int, default=2,\n help=\"The number of workers to be used in the cluster.\"\n \"You can change it depending on your own cluster setting.\")\nparser.add_argument(\"--cores\", type=int, default=4,\n help=\"The number of cpu cores you want to use on each node. \"\n \"You can change it depending on your own cluster setting.\")\nparser.add_argument(\"--memory\", type=str, default=\"10g\",\n help=\"The memory you want to use on each node. \"\n \"You can change it depending on your own cluster setting.\")\nparser.add_argument(\"--data_dir\", type=str, default=\"./nyc_taxi.csv\",\n help=\"the directory of electricity data file, you can download by running \"\n \"wget https://raw.githubusercontent.com/numenta/NAB/v1.0/\"\n \"data/realKnownCase/nyc_taxi.csv\")\n\nif __name__ == \"__main__\":\n\n args = parser.parse_args()\n\n num_nodes = 1 if args.cluster_mode == \"local\" else args.num_workers\n\n init_orca_context(cluster_mode=args.cluster_mode,\n cores=args.cores,\n num_nodes=num_nodes,\n memory=args.memory,\n init_ray_on_spark=True\n )\n\n # load the dataset. The downloaded dataframe contains two columns, \"timestamp\" and \"value\".\n df = pd.read_csv(args.data_dir, parse_dates=[\"timestamp\"])\n\n # split the dataframe into train/validation/test set.\n train_df, val_df, test_df = train_val_test_split(df, val_ratio=0.1, test_ratio=0.1)\n\n trainer = AutoTSTrainer(dt_col=\"timestamp\", # the column name specifying datetime\n target_col=\"value\", # the column name to predict\n horizon=1, # number of steps to look forward\n extra_features_col=None # list of column names as extra features\n )\n\n ts_pipeline = trainer.fit(train_df, val_df,\n recipe=LSTMGridRandomRecipe(\n num_rand_samples=1,\n epochs=1,\n look_back=6,\n batch_size=[64]),\n metric=\"mse\")\n\n # predict with the best trial\n pred_df = ts_pipeline.predict(test_df)\n\n # evaluate the result pipeline\n mse, smape = ts_pipeline.evaluate(test_df, metrics=[\"mse\", \"smape\"])\n print(\"Evaluate: the mean square error is\", mse)\n print(\"Evaluate: the smape value is\", smape)\n\n # save & restore the pipeline\n with tempfile.TemporaryDirectory() as tempdirname:\n my_ppl_file_path = ts_pipeline.save(tempdirname + \"saved_pipeline/nyc_taxi.ppl\")\n loaded_ppl = TSPipeline.load(my_ppl_file_path)\n\n # Stop orca context when your program finishes\n stop_orca_context()\n","sub_path":"pyzoo/zoo/chronos/examples/quickstart/zouwu_autots_nyc_taxi.py","file_name":"zouwu_autots_nyc_taxi.py","file_ext":"py","file_size_in_byte":4103,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"545883555","text":"import numpy as np\nimport cv2\nimport convolution\n\nclass gaussian_pyramid:\n pyramid = [] \n def __init__(self, img, levels, kernel = [], gauss_kernel_par= 0.3):\n self.img = img\n self.levels = levels\n if kernel == []:\n self.kernel = convolution.gaussian_kernel(gauss_kernel_par)\n else:\n self.kernel = kernel \n \n def interpolation(self,x,y,v, interp = 'bilinear'):\n if interp=='bilinear': \n if (x[0]==x[1]==x[2]==x[3]) or (y[0]==y[1]==y[2]==y[3]):\n return v[0]\n r1=(((x[1]-x[4])/(x[1]-x[0]))*v[2]+(((x[4]-x[0])/(x[1]-x[0])))*v[3])\n r2=(((x[1]-x[4])/(x[1]-x[0]))*v[0]+(((x[4]-x[0])/(x[1]-x[0])))*v[1])\n p=(((y[1]-y[4])/(y[0]-y[2]))*r1+(((y[4]-y[2])/(y[0]-y[2])))*r2)\n return p\n return 1\n\n def up_sample(self, image, size, interp = 'bilinear'):\n new_image=np.empty(size)\n if len(image.shape) == 3:\n new_image = np.empty((size[0], size[1], image.shape[2]))\n for depth in range(image.shape[2]):\n new_image[:, :, depth] = self.up_sample(image[:, :, depth], (size[0], size[1]), interp ) \n return new_image\n for i in range(size[0]):\n for j in range(size[1]):\n if(interp == 'bilinear'):\n i_min = min(i//2, image.shape[0]-1)\n j_min = min(j//2, image.shape[1]-1)\n i_lim = min(i_min +1, image.shape[0]-1)\n j_lim = min(j_min +1, image.shape[1]-1)\n y = [i_min, i_min, i_lim, i_lim, (i_min + i_lim)/2.0]\n x = [j_min, j_lim, j_min, j_lim, (j_min + j_lim)/2.0]\n z = [image[i_min, j_min], image[i_min, j_lim], image[i_lim, j_min], image[i_lim, j_lim]]\n new_image[i, j] = self.interpolation(x, y, z, interp)\n return new_image\n \n def down_sample(self, image, size, padding_type = 'zero', padding_color = 0):\n new_image=np.empty(size)\n filtered_image=convolution.convolve(image, self.kernel, normalize=False, padding_type = padding_type, padding_color = padding_color)\n for i in range(0,(image.shape[0]-image.shape[0]%2),2):\n for j in range(0,(image.shape[1]-image.shape[1]%2),2):\n new_image[i//2,j//2] = filtered_image[i,j]\n return new_image\n\n def down(self, level): #upsample the image\n axis_x=self.pyramid[level].shape[0] * 2\n axis_y=self.pyramid[level].shape[1] * 2\n if len(self.img.shape) == 3 :\n new_image = np.empty((axis_x,axis_y, self.img.shape[2]))\n for depth in range(self.img.shape[2]):\n new_image[:, :, depth] = self.up_sample(self.pyramid[level][:, :, depth],(axis_x,axis_y))\n return new_image\n else:\n new_image = self.up_sample(self.pyramid[level],(axis_x,axis_y))\n return new_image\n \n \n def up(self, level): #downsample the image\n axis_x=self.pyramid[level].shape[0]//2\n axis_y=self.pyramid[level].shape[1]//2\n if len(self.img.shape) == 3 :\n new_image = np.empty((axis_x,axis_y, self.img.shape[2]))\n for depth in range(self.img.shape[2]):\n new_image[:, :, depth] = self.down_sample(self.pyramid[level][:, :, depth],(axis_x,axis_y))\n return new_image\n else:\n new_image = self.down_sample(self.pyramid[level],(axis_x,axis_y))\n return new_image\n \n def build(self):\n self.pyramid = [self.img]\n for i in range(self.levels - 1):\n self.pyramid.append(self.up(i))\n \n def get(self, level):\n if(level >=0 and level < self.levels):\n return self.pyramid[level]\n exit('Parameter error: invalid gaussian pyramid level')\n \n def show(self, name = 'gauss_pyramid'):\n for i in range(self.levels):\n cv2.imwrite(name + str(i) + '.jpg', self.get(i))\n \ndef load_kernels():\n kernels = []\n #sobel\n kernels.append(np.array([[-1,0,1],\n [-2,0,2],\n [-1,0,1]]).astype(np.float))\n #gaussian 5x5\n kernels.append(convolution.gaussian_kernel(0.3))\n #gaussian 7x7\n kernels.append(np.array([[0, 0, 0, 5, 0, 0, 0],\n [0, 5, 18, 32, 18, 5, 0],\n [0, 18, 64, 100, 64, 18, 0],\n [5, 32, 100, 100, 100, 32, 5],\n [0, 18, 64, 100, 64, 18, 0],\n [0, 5, 18, 32, 18, 5, 0],\n [0, 0, 0, 5, 0, 0, 0]]).astype(np.float)/1068.0)\n return kernels\n\nif __name__ == \"__main__\":\n image_names = ['input/p1-1-0.jpg', 'input/p1-1-1.jpg', 'input/p1-1-2.png', 'input/p1-1-3.png']\n name_it = 0\n kernels = load_kernels()\n pyramid_levels = 7\n for image_name in image_names:\n image = cv2.imread(image_name, 1)\n for kernel in kernels:\n pyramid = gaussian_pyramid(image, levels = pyramid_levels, kernel = kernel)\n pyramid.build()\n #plot downsample results\n print('downsample results')\n for i in range(pyramid_levels):\n cv2.imwrite('output/p1-2-2-' + str(name_it) + '.jpg', pyramid.get(i))\n print(image_name, 'output/p1-2-2-' + str(name_it) + '.jpg')\n name_it += 1\n\n #plot upsample results\n print('upsample results')\n for i in range(pyramid_levels):\n cv2.imwrite('output/p1-2-2-' + str(name_it) + '.jpg', pyramid.down(i))\n print(image_name, 'output/p1-2-2-' + str(name_it) + '.jpg')\n name_it += 1\n","sub_path":"HW1/src/gaussian_pyramid.py","file_name":"gaussian_pyramid.py","file_ext":"py","file_size_in_byte":5796,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"77984812","text":"import os\nimport sys\nimport time\nimport numpy as np\nimport torch\nfrom torchvision import transforms\nfrom torchvision import datasets\nfrom torch.utils.data import DataLoader, Dataset\nimport torch.nn.functional as F\nimport torch.optim as optim\n\nresume = True\nbatch_size = 64\n#Convert the PIL image to tensor\n#0.13017,0.3081 是像素pixel的平均值和标准差\n\n#python cnn_mnist_break.py 3 5 0\n#python cnn_mnist_break.py 3 5 1\n#python cnn_mnist_break.py 3 5 2\n#python cnn_mnist_break.py 3 5 3\n#python cnn_mnist_break.py 3 5 4\n\ncurrent_round = int(sys.argv[1])\nepochs = int(sys.argv[2])\nnode_count = int(sys.argv[3])\nnode_id = int(sys.argv[4])\n\ntransform = transforms.Compose([\n transforms.ToTensor(),\n transforms.Normalize((0.1307,), (0.3081,))\n])\n\nclass DatasetSplit(Dataset):\n \"\"\"An abstract Dataset class wrapped around Pytorch Dataset class.\n \"\"\"\n\n def __init__(self, dataset, idxs):\n self.dataset = dataset\n self.idxs = [int(i) for i in idxs]\n\n def __len__(self):\n return len(self.idxs)\n\n def __getitem__(self, item):\n image, label = self.dataset[self.idxs[item]]\n return torch.tensor(image), torch.tensor(label)\n\nclass Net(torch.nn.Module):\n def __init__(self):\n super(Net, self).__init__()\n self.conv1 = torch.nn.Conv2d(1,10,kernel_size=5)#channel_in, channel_out\n self.conv2 = torch.nn.Conv2d(10,20,kernel_size=5)\n self.pooling = torch.nn.MaxPool2d(2)#取最大,即大小缩小一半\n self.fc = torch.nn.Linear(320,10)\n\n #计算图参考PPT\n def forward(self, x):\n batch_size = x.size(0)\n x = F.relu(self.pooling(self.conv1(x)))\n x = F.relu(self.pooling(self.conv2(x)))\n x = x.view(batch_size, -1)#flatten\n x = self.fc(x)\n return x\n\ntrain_dataset = datasets.MNIST(root='mnist/',\n train=True,\n download=True,\n transform=transform)\n\n# 60,000 training imgs --> 200 imgs/shard X 300 shards\nnum_shards, num_imgs = 200, 300\nnum_user_shards = int(num_shards / node_count)\nidx_shard = [i for i in range(num_shards)]\ntrain_idx = []\nidxs = np.arange(num_shards*num_imgs)\nlabels = train_dataset.train_labels.numpy()\n\n# sort labels\nidxs_labels = np.vstack((idxs, labels))\nidxs_labels = idxs_labels[:, idxs_labels[1, :].argsort()]\nidxs = idxs_labels[0, :]\n\n# divide and assign `num_user_shards` shards/client\nif current_round == 1:\n rand_set = np.random.choice(idx_shard, num_user_shards, replace=False)\n # print(rand_set)\n np.savetxt('train/non-iid/mnist_'+str(node_id), rand_set)\nelse:\n rand_set = np.loadtxt('train/non-iid/mnist_'+str(node_id))\n# idx_shard = list(set(idx_shard) - rand_set)\nfor rand in rand_set:\n train_idx = np.concatenate(\n (train_idx, idxs[int(rand)*num_imgs:(int(rand)+1)*num_imgs]), axis=0)\n\n# step_train = int(len(train_dataset)/node_count)\n# # idx = [i for i in range(node_id * step_train,(node_id + 1) * step_train)]\n# #\n# # train_loader = DataLoader(DatasetSplit(train_dataset, idx),\n# # shuffle=True,\n# # batch_size=batch_size)\n#\n# all_idx = [i for i in range(len(train_dataset))]\n# # train_idx = np.random.choice(all_idx, int(len(train_dataset)/node_count),\n# # replace=False)\n# #\n# # idxs_train = train_idx[:int(0.8*len(train_idx))]\n# # idxs_val = train_idx[int(0.8*len(train_idx)):int(0.9*len(train_idx))]\n# # idxs_test = train_idx[int(0.9*len(train_idx)):]\n# train_idx = train_idx = [i for i in range(node_id * step_train, (node_id + 1) * step_train)]\n\ntrain_loader = DataLoader(DatasetSplit(train_dataset, train_idx),\n shuffle=True,\n batch_size=batch_size)\n\n# valid_loader = DataLoader(DatasetSplit(train_dataset, idxs_val),\n# shuffle=True,\n# batch_size=batch_size)\n#\n# test_loader = DataLoader(DatasetSplit(train_dataset, idxs_test),\n# shuffle=True,\n# batch_size=batch_size)\n\n# test_dataset = datasets.MNIST(root='mnist/',\n# train=False,\n# download=True,\n# transform=transform)\n#\n# step_test = int(len(test_dataset)/node_count)\n# idx = [i for i in range(node_id * step_test,(node_id + 1) * step_test)]\n#\n# test_loader = DataLoader(DatasetSplit(test_dataset, idx),\n# shuffle=True,\n# batch_size=batch_size)\n\nmodel = Net()\ndevice = torch.device(\"cpu\")\nmodel.to(device)#convert parameters and buffers of all modules to cuda tensor\ncriterion = torch.nn.CrossEntropyLoss()\noptimizer = optim.SGD(model.parameters(),lr=0.01, momentum=0.5)\n\nif resume and current_round != 1:\n path_checkpoint = \"train/non-iid/checkpoint/agg/mnist_ckpt_\" + str(current_round-1) + \".pth\" # 断点路径\n checkpoint = torch.load(path_checkpoint) # 加载断点\n\n model.load_state_dict(checkpoint['net']) # 加载模型可学习参数\n\n optimizer.load_state_dict(checkpoint['optimizer']) # 加载优化器参数\n start_epoch = checkpoint['epoch'] # 设置开始的epoch\n\ndef train(epoch):\n running_loss = 0.0\n for batch_idx, data in enumerate(train_loader, 0):\n inputs, target = data\n inputs, target = inputs.to(device), target.to(device)\n #send the inputs and targets at every step to the GPU\n optimizer.zero_grad()\n\n outputs = model(inputs)\n loss = criterion(outputs, target)\n loss.backward()\n optimizer.step()\n\n # running_loss += loss.item()\n # if batch_idx % 100 == 99:\n # print('[%d, %5d] loss: %.3f' % (epoch + 1, batch_idx + 1, running_loss / 100))\n # running_loss = 0.0\n\n checkpoint = {\n \"net\": model.state_dict(),\n 'optimizer':optimizer.state_dict(),\n \"epoch\": epoch\n }\n if not os.path.isdir(\"train/non-iid/checkpoint/mnist/\"):\n os.mkdir(\"train/non-iid/checkpoint/mnist/\")\n torch.save(checkpoint, 'train/non-iid/checkpoint/mnist/ckpt_'+ str(node_id) + '_%s.pth' %(str(epoch)))\n\n# def valid():\n# correct = 0\n# total = 0\n# with torch.no_grad():\n# for data in valid_loader:\n# inputs, target = data\n# inputs, target = inputs.to(device), target.to(device)\n# outputs = model(inputs)\n# _, predicted = torch.max(outputs.data, dim=1)#选择概率最大的输出\n# total += target.size(0)\n# correct += (predicted == target).sum().item()\n\n # print('Accuracy on valid set in node ' + str(node_id) +': %.4f %%' % (100 * float(correct) / float(total)))\n\n# def test():\n# correct = 0\n# total = 0\n# with torch.no_grad():\n# for data in test_loader:\n# inputs, target = data\n# inputs, target = inputs.to(device), target.to(device)\n# outputs = model(inputs)\n# _, predicted = torch.max(outputs.data, dim=1)#选择概率最大的输出\n# total += target.size(0)\n# correct += (predicted == target).sum().item()\n\n # print('Accuracy on test set in node ' + str(node_id) +': %.4f %%' % (100 * float(correct) / float(total)))\n\nif __name__ == '__main__':\n for epoch in range(epochs):\n train(epoch)\n # valid()\n # test()","sub_path":"oracle/train/non-iid/cnn_mnist_train.py","file_name":"cnn_mnist_train.py","file_ext":"py","file_size_in_byte":7403,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"634251056","text":"import sys\nfrom datetime import date\n\n\nbeginning_of_time = date(1970, 1, 1)\n\ndef convert_date_to_int(date_str):\n month, day, year = [int(s) for s in date_str.strip().split(\"/\")]\n assert year <= 99\n assert month <= 12\n assert day <= 31\n d0 = date(2000 + int(year), int(month), int(day))\n assert d0 > beginning_of_time, \"too far in the past: \" + str(d0)\n delta = (d0 - beginning_of_time).days\n assert delta <= (1 << 32), \"time delta too large: \" + str(delta)\n return delta\n\ndef convert_meds_row(row):\n return \",\".join([\n row[0], # pid*\n \"0\", # ???\n \"0\", # year\n \"0\", # month\n \"1\" if (\"aspirin\" in row[4].lower()) else \"2\", # prescription*\n \"0\", # dosage\n \"0\", # administered\n str(convert_date_to_int(row[7])) # time-stamp*\n ])\n\ndef convert_diags_row(row):\n converted = [\"0\" for _ in row]\n converted[0] = row[0] # pid\n converted[8] = \"1\" if row[8][0:3] == \"414\" else \"2\" # diag\n converted[10] = str(convert_date_to_int(row[10]))\n return \",\".join(converted)\n\nif __name__ == '__main__':\n input_data_dir = sys.argv[1] \n output_data_dir = sys.argv[2] \n medication_raw_fn = \"medication.csv\"\n diagnosis_raw_fn = \"diagnosis.csv\"\n \n with open(\"/\".join([input_data_dir, medication_raw_fn])) as meds_in, \\\n open(\"/\".join([input_data_dir, diagnosis_raw_fn])) as diag_in, \\\n open(\"/\".join([output_data_dir, medication_raw_fn]), \"w\") as meds_out, \\\n open(\"/\".join([output_data_dir, diagnosis_raw_fn]), \"w\") as diag_out :\n print(\"converting data\")\n # read and convert\n meds_converted = [convert_meds_row(l.split(\",\")) for l in meds_in.readlines()]\n diags_converted = [convert_diags_row(l.split(\",\")) for l in diag_in.readlines()]\n # write out\n meds_out.write(\"\\n\".join(meds_converted))\n meds_out.write(\"\\n\")\n diag_out.write(\"\\n\".join(diags_converted))\n diag_out.write(\"\\n\")\n","sub_path":"tests/integration/aspirin-public-join/prep.py","file_name":"prep.py","file_ext":"py","file_size_in_byte":1999,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"129915532","text":"import logging\nimport re\nfrom datetime import datetime\n\nfrom datasets.dataset import Dataset\nfrom datasets.errors import DatasetErrors\nfrom storage.site import Site\nfrom utils.dateutils import parse_to_utc, now_as_utc\n\nlog = logging.getLogger(__name__)\n\n\nclass NSWDataset(Dataset):\n \"\"\"\n Returns NSW exposure sites.\n \"\"\"\n\n endpoint = 'https://data.nsw.gov.au/data/' \\\n 'dataset/0a52e6c1-bc0b-48af-8b45-d791a6d8e289/' \\\n 'resource/f3a28eed-8c2a-437b-8ac1-2dab3cf760f9/' \\\n 'download/covid-case-locations'\n\n def __init__(self):\n self.parser = NSWSiteParser()\n\n def sites(self) -> [Site]:\n response = self.get_with_retries(self.endpoint)\n\n sites = list(map(lambda s: self.parser.to_site(s), response.json()['data']['monitor']))\n log.info(f'Got {len(sites)} sites from NSW dataset API.')\n return sites\n\n\nclass NSWSiteParser:\n timezone = 'Australia/Sydney'\n time_pattern = re.compile(r'(\\d?\\d?[:.]?\\d?\\d[ap]m)')\n latlng_pattern = re.compile(r'([-]?\\d+\\.\\d+)')\n\n def to_site(self, site: dict) -> Site:\n errors = DatasetErrors()\n\n added_time = self._get_added_time(site, errors)\n exposure_start_time, exposure_end_time = self._get_exposure_times(site, errors, added_time)\n\n lat, long = self._get_lat_long(site, errors)\n\n return Site(\n suburb=site['Suburb'],\n title=site['Venue'],\n street_address=site['Address'],\n state='NSW',\n postcode=None,\n exposure_start_time=exposure_start_time,\n exposure_end_time=exposure_end_time,\n added_time=added_time,\n latitude=lat,\n longitude=long,\n geocode={},\n data_errors=errors.get(),\n )\n\n def _get_added_time(self, site: dict, errors: DatasetErrors):\n return errors.try_operation(lambda: parse_to_utc(f'{site[\"Last updated date\"]}T00:00:00', self.timezone),\n now_as_utc(), msg=f'Error parsing added date: {site[\"Last updated date\"]}')\n\n def _get_lat_long(self, site: dict, errors: DatasetErrors):\n lat = errors.try_operation(lambda: float(site['Lat']), None, msg=f'Error parsing \\'Lat\\' field: {site[\"Lat\"]}')\n long = errors.try_operation(lambda: float(site['Lon']), None, msg=f'Error parsing \\'Lon\\' field: {site[\"Lon\"]}')\n return lat, long\n\n def _get_exposure_times(self, site: dict, errors: DatasetErrors, default: datetime):\n error_msg = f'Error parsing \\'Time\\' field value: {site[\"Time\"]}'\n exposure_times = self.time_pattern.findall(site['Time'])\n\n start_time = errors.try_operation(lambda: exposure_times[0], '12:00am', msg=error_msg).replace('.', ':')\n exposure_start_time = errors.try_operation(\n lambda: parse_to_utc(f'{site[\"Date\"]} {start_time}', self.timezone),\n default,\n f'Error parsing \\'Date\\' field value in \\'{site[\"Date\"]} {start_time}\\''\n )\n\n end_time = errors.try_operation(lambda: exposure_times[1], '11:59pm', msg=error_msg).replace('.', ':')\n exposure_end_time = errors.try_operation(\n lambda: parse_to_utc(f'{site[\"Date\"]} {end_time}', self.timezone),\n default,\n f'Error parsing \\'Date\\' field value in \\'{site[\"Date\"]} {end_time}\\''\n )\n\n return exposure_start_time, exposure_end_time\n\n\nif __name__ == '__main__':\n dataset = NSWDataset()\n sites = dataset.sites()\n for s in sites:\n print(s)\n\n log.info(f'Total no of sites: {len(sites)}')\n","sub_path":"src/datasets/nsw_dataset.py","file_name":"nsw_dataset.py","file_ext":"py","file_size_in_byte":3593,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"21755878","text":"#!/usr/bin/env python\r\n#coding:utf-8\r\n\r\nimport cv2\r\nimport sys\r\n\r\nif __name__==\"__main__\":\r\n\r\n # VideoCaptureクラスをインスタンス化\r\n capture = cv2.VideoCapture(0)\r\n\r\n # Webカメラの接続確認\r\n if capture.isOpened() == False:\r\n print(\"Webカメラに接続されていません。\")\r\n sys.exit()\r\n\r\n cv2.namedWindow(\"Capture\", cv2.WINDOW_AUTOSIZE)\r\n\r\n while True:\r\n\r\n ret, image = capture.read()\r\n\r\n if ret == False:\r\n continue\r\n\r\n cv2.imshow(\"Capture\", image)\r\n\r\n # 何かキー入力があった場合,画像を保存して処理を抜ける\r\n if cv2.waitKey(33) >= 0:\r\n cv2.imwrite(\"image.png\", image)\r\n break\r\n\r\n # キャプチャを解放する\r\n capture.release()\r\n cv2.destroyAllWindows()\r\n","sub_path":"sonota_sample/sample_openCv.py","file_name":"sample_openCv.py","file_ext":"py","file_size_in_byte":825,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"65663662","text":"import os\nimport sys\nimport time\nimport torch\nimport numpy\n\n# setup data and environment\ngpu_name = '3'\nos.environ['CUDA_VISIBLE_DEVICES'] = gpu_name\ngpus = list(map(int, gpu_name.split(',')))\ndevice = torch.device('cuda' if gpus[0] >= 0 else 'cpu')\nchunk_sizes = [13]\nbatch_size = sum(chunk_sizes)\nnum_epochs = 270\nnum_worker = 10 \nlearn_rate = 5e-5 / 128 * batch_size\ndecay_step = [90, 120]\nroot_path = '/home'\ntrain_image_path = root_path + '/data/coco/train2017_subset'\ntrain_annotate_path = root_path + '/data/coco/annotations/instances_train2017_subset.json'\nvalidate_image_path = root_path + '/data/coco/val2017_subset'\nvalidate_annotate_path = root_path + '/data/coco/annotations/instances_val2017_subset.json'\nload_path = 'models/resnet50v1b'\nsave_path = 'models/exp01_resnet50v1b_reconstruct_cocoSubset_finetune'\nif not os.path.exists(save_path):\n os.makedirs(save_path)\nval_intervals = 5\nmetric = 'loss'\ntorch.cuda.manual_seed_all(317)\ntorch.backends.cudnn.deterministic = False\ntorch.backends.cudnn.benchmark = False\n\n# import sparse resent50v1d through Moffett IR \nfrom utils import load_model, save_model\nfrom resnet_IR import get_pose_net\njsn = '../centernet_resnetv1b_map31_sparsity80/resnet50_centernet.json'\nparams = '../centernet_resnetv1b_map31_sparsity80/resnet50_centernet.npz'\nmodel = get_pose_net(jsn, params, input_node_ids = [0], output_node_ids = [570], heads={'hm': 3, 'reg': 2, 'wh': 2}, head_conv=64)\n\n# import Moffett pruning optimizer\nimport pytorch_pruning\noptimizer = pytorch_pruning.AdamSparse(model.parameters(), lr=learn_rate, restore_sparsity=True, fix_sparsity=True, param_name=model.named_parameters())\n\n# setup trainer\nstart_epoch = 0\nfrom trainer import Trainer\ntrainer = Trainer(model, optimizer, gpus, chunk_sizes, device)\n\n# setup dataloader\nimport dataset_train_cocoSubset as dataset_train\nimport dataset_validate_cocoSubset as dataset_validate\nval_loader = torch.utils.data.DataLoader(\n dataset=dataset_validate.Dataset(validate_image_path, validate_annotate_path),\n num_workers=num_worker,\n pin_memory=True)\ntrain_loader = torch.utils.data.DataLoader(\n dataset=dataset_train.Dataset(train_image_path, train_annotate_path),\n batch_size=batch_size,\n shuffle=True,\n num_workers=num_worker,\n pin_memory=True,\n drop_last=True)\n\n#training\nbest = 1e10\nfor epoch in range(start_epoch + 1, num_epochs + 1):\n log_dict_train, _ = trainer.run_epoch('train', epoch, train_loader)\n for k, v in log_dict_train.items():\n SummaryWriter.add_scalar('train_{}'.format(k), v, epoch)\n if val_intervals > 0 and epoch % val_intervals == 0:\n save_model(os.path.join(save_path, 'model_{}.pth'.format('last')), epoch, model, optimizer)\n with torch.no_grad():\n log_dict_val, preds = trainer.run_epoch('val', epoch, val_loader)\n for k, v in log_dict_val.items():\n SummaryWriter.add_scalar('val_{}'.format(k), v, epoch)\n if log_dict_val[metric] < best:\n best = log_dict_val[metric]\n save_model(os.path.join(save_path, 'model_best.pth'), epoch, model)\n else:\n save_model(os.path.join(save_path, 'model_last.pth'), epoch, model, optimizer)\n if epoch in decay_step:\n save_model(os.path.join(save_path, 'model_{}.pth'.format(epoch)), epoch, model, optimizer)\n lr = learn_rate * (0.1 ** (decay_step.index(epoch) + 1))\n for param_group in optimizer.param_groups:\n param_group['lr' ] = lr\n","sub_path":"examples/cocoSubset/codes/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":3463,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"318406079","text":"import time\nimport RPi.GPIO as GPIO\nfrom SR02 import SR02_Supersonic as Supersonic_Sensor\n\nbuzzer_pin = 8\nscale = [261.6, 293.6, 329.6, 349.2, 391.9, 440.0, 493.8, 523.2]\n\nGPIO.setmode(GPIO.BOARD)\nGPIO.setup(buzzer_pin, GPIO.OUT)\n\ndistanceDetector = Supersonic_Sensor.Supersonic_Sensor(35)\ninterval = 9\n\nwhile distanceDetector.get_distance() <= interval:\n p = GPIO.PWM(buzzer_pin, 100)\n p.start(5)\n\ntry:\n p = GPIO.PWM(buzzer_pin, 100)\n p.start(5)\n\n for i in range(8):\n print(i + 1)\n p.ChangeFrequency(scale[i])\n time.sleep(0.5)\n\n p.stop()\n\nfinally:\n GPIO.cleanup()\n","sub_path":"scan.py","file_name":"scan.py","file_ext":"py","file_size_in_byte":607,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"614068028","text":"\"\"\"\nThis module contains AES-CBC encryption and decryption functions.\n\n* Assumes that we are using 8-bit (1 byte) unicode ASCII characters\n* One HEX character is 4-bit\n* Two HEX characters is 8-bit (1 byte) and corresponds to the\n ASCII code of one ASCII character\n\"\"\"\n\nblocksize = 16 # in bytes\n\nimport sys\nsys.path.append('/Users/ming/Dropbox/cryptography/crypto_python') # add path for ming-OSX\nimport crypto_common\nfrom Crypto.Cipher import AES\n\n\n\"\"\"\nGiven a IV as an ASCII string, this function pads a plaintext and encrypts the plaintext\nusing AES in CBC mode\nTakes an ASCII key, an ASCII IV and an ASCII plaintext\nReturns the ciphertext as an ASCII cipher text with IV prepended and padding\n\nUses the basic AES function provided by PyCrypto for each block,\nbut implements the CBC mode encryption as a learning experience.\n\nSee Lecture 2-9\n\"\"\"\n\ndef CBC_encrypt(key, IV, PT):\n\n # Trivial case\n if (not PT):\n return ''\n\n if (len(key) != 16 and len(key) != 24 and len(key) != 32):\n raise Exception(\"Keys must be 16, 24 or 32 bytes\")\n\n if (len(IV) != blocksize):\n raise Exception(\"IV must be 16 bytes(characters)\")\n\n CBC = AES.new(key, AES.MODE_ECB); # Uses the ECB mode for the basic AES encryption/decryption of individual blocks\n # Recall in Lecture 2-8: \"ECB is not semantically secure for messages that contain\n # more than one block\"\n\n PT = append_CBC_pad(PT) # pad message first\n\n if (len(PT) % blocksize != 0): # sanity check\n raise Exception(\"Padding plaintext must be a multiple of 16 bytes(characters)\")\n\n CT = IV\n\n temp = crypto_common.hextoascii(crypto_common.asciistrxor(IV, PT[:blocksize]))\n\n for x in range(0, len(PT)-blocksize, blocksize):\n CT += CBC.encrypt(temp)\n temp = crypto_common.hextoascii(crypto_common.asciistrxor(CT[-blocksize:], PT[x+blocksize:x+2*blocksize]))\n\n return CT + CBC.encrypt(temp)\n\n\n\"\"\"\nDecrypts a cypher text that is encryped using AES in CBC mode\nTakes an ASCII key and an ASCII cipher text\nReturns the decrypted message as an ASCII cipher text (without padding)\n\nUses the basic AES function provided by PyCrypto for each block,\nbut implements the CBC mode decryption as a learning experience.\n\nSee Lecture 2-9\n\"\"\"\n\ndef CBC_decrypt(key, CT):\n\n if (len(key) != 16 and len(key) != 24 and len(key) != 32):\n raise Exception(\"Keys must be 16, 24 or 32 bytes\")\n\n if ((not CT) or (len(CT) % blocksize != 0)):\n raise Exception(\"Ciphertext must be in blocks of 16 bytes(characters)\")\n\n CBC = AES.new(key, AES.MODE_ECB); # Uses the ECB mode for the basic AES encryption/decryption of individual blocks\n # Recall in Lecture 2-8: \"ECB is not semantically secure for messages that contain\n # more than one block\"\n\n return remove_CBC_pad(crypto_common.hextoascii(\"\".join([crypto_common.asciistrxor(CBC.decrypt(CT[x+blocksize:x+2*blocksize]), CT[x:x+blocksize]) for x in range(0, len(CT)-blocksize, blocksize)])))\n\n\n\"\"\"\nAppend CBC padding to an ASCII text message\nReturns an ASCII string\n\nSee Lecture 2-9\n\"\"\"\n\ndef append_CBC_pad(PT):\n\n # Handle trivial case\n if (not PT):\n return ''\n\n padLength = len(PT) % blocksize\n if (padLength == 0):\n return PT + chr(blocksize) * blocksize\n else:\n return PT + chr(padLength) * padLength\n\n\n\"\"\"\nRemoves CBC padding from an ASCII text message\nReturns an ASCII string\n\nSee Lecture 2-9\n(Repeated in Week4-ProgrammingAssignment.py)\n\"\"\"\n\ndef remove_CBC_pad(PT):\n\n # Handle trivial case\n if (not PT):\n return ''\n\n if (len(PT) % blocksize != 0):\n raise Exception(\"Plaintext must be in blocks of 16 bytes(characters)\")\n\n pad = ord(PT[-1]);\n\n for x in range(1, pad+1):\n if (ord(PT[-x]) != pad):\n raise Exception(\"Invalid padding\")\n\n return PT[:-pad];\n\n\n","sub_path":"CBC.py","file_name":"CBC.py","file_ext":"py","file_size_in_byte":3883,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"86016951","text":"\"\"\"\nLighting 3\n==========\n\n\"\"\"\n\nfrom rfxcom.protocol.base import BasePacketHandler\nfrom rfxcom.protocol.rfxpacketutils import RfxPacketUtils\n\n\nCOMMANDS = {\n 0x00: 'Bright',\n 0x08: 'Dim',\n 0x10: 'On',\n 0x11: 'Level 1',\n 0x12: 'Level 2',\n 0x13: 'Level 3',\n 0x14: 'Level 4',\n 0x15: 'Level 5',\n 0x16: 'Level 6',\n 0x17: 'Level 7',\n 0x18: 'Level 8',\n 0x19: 'Level 9',\n 0x1a: 'Off',\n 0x1c: 'Program',\n}\n\n\nclass Lighting4(BasePacketHandler):\n \"\"\"The Lighting4 protocol is a 9 bytes packet used by a number of lighting\n systems. For example Lightwave devices use this protocol.\n\n ==== ====\n Byte Meaning\n ==== ====\n 0 Packet Length, 0x0C (excludes this byte)\n 1 Packet Type, 0x12\n 2 Sub Type\n 3 Sequence Number\n 4 System\n 5 Channel 1\n 6 Channel 2\n 7 Command\n 8 RSSI and Filler\n ==== ====\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n\n super().__init__(*args, **kwargs)\n\n self.PACKET_TYPES = {\n 0x13: \"Lighting4 sensors\"\n }\n\n self.PACKET_SUBTYPES = {\n 0x00: 'PT2262',\n }\n\n def parse(self, data):\n \"\"\"Parse a 10 bytes packet in the Lighting4 format and return a\n dictionary containing the data extracted. An example of a return value\n would be:\n\n .. code-block:: python\n\n {\n 'packet_length': 9,\n 'packet_type': 19,\n 'packet_type_name': 'Lighting4 sensors',\n 'sequence_number': 4,\n 'packet_subtype': 0,\n 'packet_subtype_name': \"PT2262\",\n 'command': 17,\n 'command_text': \"Level 1\",\n 'pulse': 5\n }\n\n :param data: bytearray to be parsed\n :type data: bytearray\n\n :return: Data dictionary containing the parsed values\n :rtype: dict\n \"\"\"\n\n self.validate_packet(data)\n\n results = self.parse_header_part(data)\n\n cmd = (data[4] << 16) + (data[5] << 8) + data[6]\n pulse = data[7] << 8 + data[8]\n\n sensor_specific = {\n 'command': cmd,\n 'pulse': pulse\n }\n\n results.update(RfxPacketUtils.parse_signal_upper(data[9]))\n results.update(sensor_specific)\n\n return results\n","sub_path":"rfxcom/protocol/lighting4.py","file_name":"lighting4.py","file_ext":"py","file_size_in_byte":2365,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"553220353","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Dec 8 10:01:54 2020\n\n@author: lauraarendsen\n\"\"\"\n\nimport os\nimport mne\n\n#%% Concatenate multiple files for a single participant (raw-files). \n\n\"\"\"\nThis code was used for the few exeptions were several recording files were present for a participant\nafter concatenating the raw files, the usual preproc and epoching pipeline can be applied\n\"\"\"\n\n# NOTE: Manually change the file names for each participant\nraw_dir = \"/mnt/data/Laura/Tuebingen/Inspiration_Pain_Project/AcuteNMES_Study/RawData/\"\nos.chdir(raw_dir)\n\nfilename_1 = 'ScSe_R001.fif'\nfilename_2 = 'ScSe_R002.fif'\n#filename_3 = 'MiAn_R003.fif'\n#filename_4 = 'MiAn_R004.fif'\n\nraw_1 = mne.io.read_raw_fif(filename_1)\nraw_2 = mne.io.read_raw_fif(filename_2)\n#raw_3 = mne.io.read_raw_fif(filename_3)\n#raw_4 = mne.io.read_raw_fif(filename_4)\n\nraw_total = mne.concatenate_raws([raw_1, raw_2])\n#raw_total = mne.concatenate_raws([raw_1, raw_2, raw_3, raw_4])\n\nraw_total.save(raw_dir+'ScSe_R001_R002.fif', overwrite = False, split_size='2GB')","sub_path":"Concatenate_raw_fif.py","file_name":"Concatenate_raw_fif.py","file_ext":"py","file_size_in_byte":1053,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"410774983","text":"#client\r\nimport TxBlock\r\nimport Transaction\r\nimport Signatures\r\nimport pickle\r\nimport socket\r\n\r\nTCP_PORT = 5005\r\n\r\ndef sendBlock(ip_addr, block):\r\n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\r\n s.connect((ip_addr, TCP_PORT))\r\n data = pickle.dumps(block)\r\n s.send(data)\r\n s.close()\r\n return False\r\n\r\nif __name__ == \"__main__\":\r\n pr1,pu1 = Signatures.generate_keys()\r\n pr2,pu2 = Signatures.generate_keys()\r\n pr3,pu3 = Signatures.generate_keys()\r\n Tx1 = Transaction.Tx()\r\n Tx1.add_input(pu1,2.3)\r\n Tx1.add_output(pu2,1.0)\r\n Tx1.add_output(pu3,1.1)\r\n Tx1.signature(pr1)\r\n\r\n Tx2 = Transaction.Tx()\r\n Tx2.add_input(pu3,2.3)\r\n Tx2.add_input(pu2,1.0)\r\n Tx2.add_output(pu1,3.1)\r\n Tx2.signature(pr2)\r\n Tx2.signature(pr3)\r\n\r\n B1 = TxBlock.TxBlock(None)\r\n B1.addTx(Tx1)\r\n B1.addTx(Tx2)\r\n\r\n sendBlock('localhost', B1)\r\n\r\n sendBlock('localhost', Tx2)\r\n\r\n sendBlock('localhost', Tx1)\r\n","sub_path":"Client.py","file_name":"Client.py","file_ext":"py","file_size_in_byte":958,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"586480005","text":"import contextlib\nfrom typing import ContextManager\nfrom django import http\nfrom django.shortcuts import render, HttpResponse,redirect\nfrom .models import Shows\n\ndef index(request):\n return redirect('/shows')\ndef add(request):\n # Shows.objects.create(title=request.POST['form_title'],network=request.POST['form_network'],release_date=request.POST['form_res_date'],description=request.POST['form_desc'])\n # context={\n # 'myshows':x,\n # }\n return render(request,'add.html')\ndef create(request):\n \n Shows.objects.create(title=request.POST['form_title'],network=request.POST['form_network'],release_date=request.POST['form_res_date'],description=request.POST['form_desc'])\n my_last=Shows.objects.last()\n my_shows_id=my_last.id\n return redirect('/shows/'+str(my_shows_id))\n\ndef delete(request,id):\n x=Shows.objects.get(id=id)\n x.delete()\n return redirect('/')\ndef show_all(request):\n context={\n 'myshows':Shows.objects.all(),\n }\n return render(request,'shows.html',context)\ndef this_show_details(request,id):\n context={\n 'myshows':Shows.objects.get(id=id),\n }\n return render(request,'details.html',context)\ndef show_from_form(request):\n context={\n ''\n }\n return render(request,'details.html',context)\n\ndef show_edit(request,id):\n context={\n 'myshows':Shows.objects.get(id=id),\n }\n return render(request,'edit.html',context)\n\n\ndef update_show(request,id):\n updated_show=Shows.objects.get(id=id)\n updated_show.title=request.POST['edit_form_title']\n updated_show.network=request.POST['edit_form_network']\n updated_show.release_date=request.POST['edit_form_res_date']\n updated_show.description=request.POST['edit_form_desc']\n updated_show.save()\n pass\n \ndef this_update_details(request,id):\n context={\n 'myshows':Shows.objects.get(id=id),\n }\n return render(request,'details.html',context)\ndef update_details(request):\n\n x=Shows.objects.update(title=request.POST['edit_form_title'],network=request.POST['edit_form_network'],release_date=request.POST['edit_form_res_date'],description=request.POST['edit_form_desc'])\n x.save()\n context={\n 'myshows':Shows.objects.get(id=id),\n }\n return render(request,'details.html',context)","sub_path":"django/django_fundamentals/django_intro/semi_restful_tv_shows/tvshows_app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2305,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"615280347","text":"import pandas as pd\r\nimport numpy as np\r\nfrom sklearn.model_selection import KFold\r\nfrom sklearn.model_selection import cross_val_score\r\nfrom sklearn.neighbors import KNeighborsClassifier\r\n\r\n\r\nclass knnClassifier:\r\n\r\n k = 1\r\n data = []\r\n target = []\r\n\r\n def __init__(self, k=1, data=[], target=[] ):\r\n self.k = k\r\n self.data = data\r\n self.target = target\r\n\r\n def fit(self, data, target):\r\n self.data = data\r\n self.target = target\r\n return knnClassifier(self.k, self.data, self.target)\r\n\r\n def predict(self, test_data):\r\n nInputs = np.shape(test_data)[0]\r\n closest = np.zeros(nInputs)\r\n\r\n for n in range(nInputs):\r\n #compute distances\r\n distances = np.sum((self.data-test_data[n, :])**2, axis=1)\r\n\r\n indices = np.argsort(distances, axis=0)\r\n\r\n classes = np.unique(self.target[indices[:self.k]])\r\n\r\n if len(classes) == 1:\r\n closest[n] = np.unique(classes)\r\n else:\r\n counts = np.zeros(max(classes) + 1)\r\n for i in range(self.k):\r\n counts[self.target[indices[i]]] += 1\r\n closest[n] = np.max(counts)\r\n\r\n\r\n return closest\r\n\r\n\r\n def score(self, x_test, y_test):\r\n total = len(x_test)\r\n correct = 0\r\n\r\n for i in range(total):\r\n if x_test[i] == y_test[i]:\r\n correct += 1\r\n\r\n return float(correct) / total\r\n\r\n\r\ndef main():\r\n print(\"Please enter the number of the data set you would like to analyze\\n\")\r\n print(\"1. UCI Car Evaluation\\n\")\r\n print(\"2. Pima Indian Diabetes\\n\")\r\n print(\"3. Automobile MPG\\n\")\r\n dataset = input(\"> \")\r\n\r\n # preprocess chosen data\r\n if dataset == 1:\r\n data, test = car_data_prep()\r\n elif dataset == 2:\r\n data, test = pima_data_prep()\r\n elif dataset == 3:\r\n data, test = mpg_data_prep()\r\n\r\n # x_train, x_test, y_train, y_test = train_test_split(data, test, test_size=0.3)\r\n classifier = KNeighborsClassifier(n_neighbors=3)\r\n kfold = KFold(n_splits=3, random_state=7)\r\n # kfold_train, kfold_test = kfold.split(data, y=test)\r\n scores = cross_val_score(classifier, data, test, cv=kfold, scoring='accuracy')\r\n\r\n print(scores)\r\n\r\ndef car_data_prep():\r\n uci_car_data = pd.read_csv(\"https://archive.ics.uci.edu/ml/machine-learning-databases/car/car.data\")\r\n\r\n # Set column names on data frame\r\n columns = \"buying maint doors persons lug_boot safety target\".split()\r\n uci_car_data.columns = columns\r\n\r\n #print(uci_car_data)\r\n #print(uci_car_data[\"persons\"].value_counts())\r\n\r\n # make data numerical\r\n column_numerization = {\"buying\": {\"vhigh\": 4, \"high\": 3, \"med\": 2, \"low\": 1},\r\n \"maint\": {\"vhigh\": 4, \"high\": 3, \"med\": 2, \"low\": 1},\r\n \"doors\": {\"2\": 1, \"3\": 2, \"4\": 3, \"5more\": 4},\r\n \"persons\": {\"2\": 1, \"4\": 2, \"more\": 3},\r\n \"lug_boot\": {\"small\": 1, \"med\": 2, \"big\": 3},\r\n \"safety\": {\"low\": 1, \"med\": 2, \"high\": 3},\r\n \"target\": {\"unacc\": 1, \"acc\": 2, \"good\": 3, \"vgood\": 4}}\r\n uci_car_data.replace(column_numerization, inplace=True)\r\n\r\n # split data and targets into separate data frames\r\n uci_car_targets = uci_car_data.iloc[:, 6:]\r\n uci_car_data = uci_car_data.iloc[:, :6]\r\n\r\n # turn the data and target data frames into lists\r\n uci_car_data_array = uci_car_data.as_matrix()\r\n uci_car_targets_array = uci_car_targets.as_matrix()\r\n uci_car_targets_array = uci_car_targets_array.flatten()\r\n\r\n return uci_car_data_array, uci_car_targets_array\r\n\r\ndef pima_data_prep():\r\n # get data from the UCI database\r\n pima_data = pd.read_csv(\"https://archive.ics.uci.edu/ml/machine-learning-databases/pima-indians-diabetes/pima-indians-diabetes.data\")\r\n\r\n # give columns names\r\n columns = \"n_preg plasma bp tricep_fold insulin bmi pedigree age target\".split()\r\n pima_data.columns = columns\r\n #print(pima_data.dtypes)\r\n\r\n # mark zero values as NaN\r\n pima_data[[\"n_preg\", \"plasma\", \"bp\", \"tricep_fold\", \"insulin\"]] = pima_data[[\"n_preg\", \"plasma\", \"bp\", \"tricep_fold\", \"insulin\"]].replace(0, np.NaN)\r\n\r\n # drop rows with NaN\r\n pima_data.dropna(inplace=True)\r\n\r\n # Split the dataframe into data and targets\r\n pima_data_targets = pima_data.iloc[:, 8:]\r\n pima_data = pima_data.iloc[:, :8]\r\n\r\n pima_data_array = pima_data.as_matrix()\r\n pima_data_targets_array = pima_data_targets.as_matrix()\r\n pima_data_targets_array = pima_data_targets_array.flatten()\r\n\r\n return pima_data_array, pima_data_targets_array\r\ndef mpg_data_prep():\r\n # get space delimited data set from url\r\n mpg_data = pd.read_csv(\"https://archive.ics.uci.edu/ml/machine-learning-databases/auto-mpg/auto-mpg.data\", delim_whitespace=True)\r\n #print (mpg_data.dtypes)\r\n # give data set columns names\r\n columns = \"mpg cyl disp hp weight accel year origin model\".split()\r\n mpg_data.columns = columns\r\n\r\n #print(mpg_data.dtypes)\r\n\r\n # replace and remove missing values and associated rows\r\n mpg_data = mpg_data.replace(\"?\", np.NaN)\r\n mpg_data.dropna(inplace=True)\r\n\r\n # split dataframe into data (minus the model) and targets\r\n mpg_targets = mpg_data.iloc[:, :1]\r\n mpg_data = mpg_data.iloc[:, 1:8]\r\n\r\n mpg_data_array = mpg_data.as_matrix()\r\n mpg_targets_array = mpg_targets.as_matrix()\r\n mpg_targets_array = mpg_targets_array.flatten()\r\n\r\n return mpg_data_array, mpg_targets_array\r\n\r\nmain()","sub_path":"Ponder03.py","file_name":"Ponder03.py","file_ext":"py","file_size_in_byte":5604,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"7770665","text":"def resolve():\n '''\n code here\n '''\n from decimal import Decimal\n a, b, c = [int(item) for item in input().split()]\n \n x = c - a - b\n y = 2 * Decimal(a*b).sqrt()\n\n if y < x:\n print('Yes')\n else:\n print('No')\n\n\n\n\nif __name__ == \"__main__\":\n resolve()\n","sub_path":"Python_codes/p02743/s675982228.py","file_name":"s675982228.py","file_ext":"py","file_size_in_byte":297,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"643810352","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.7 (62211)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: C:\\repositorios\\web\\djmicrosip_apps\\django-microsip-liquida\\django-microsip-liquida\\forms.py\n# Compiled at: 2019-09-10 13:06:39\nfrom django import forms\nfrom .models import Registry, Cliente, ArticuloClave\nimport autocomplete_light\nfrom django.conf import settings\nfrom django.db import router\nimport os\n\nclass SelectDBForm(forms.Form):\n try:\n using = router.db_for_write(Registry)\n except:\n databases = []\n else:\n databases = settings.MICROSIP_DATABASES.keys()\n try:\n databases.remove(using)\n except:\n pass\n\n opcions = []\n for empresa in databases:\n opcions.append([empresa, empresa])\n\n conexion = forms.ChoiceField(choices=opcions)\n\n\nclass PreferenciasManageForm(forms.Form):\n facturaa_cliente = forms.ModelChoiceField(queryset=Cliente.objects.all(), widget=autocomplete_light.ChoiceWidget('ClienteAutocomplete'))\n facturaa_articulo_clave = forms.CharField()\n ruta_liquidacion = forms.CharField()\n empresas_a_ignorar = forms.CharField(required=False)\n carpeta_facturacion_sat = forms.CharField()\n\n def clean_ruta_liquidacion(self):\n ruta_liquidacion = self.cleaned_data['ruta_liquidacion']\n try:\n os.listdir(ruta_liquidacion)\n except WindowsError:\n raise forms.ValidationError('ruta de carpeta [%s] invalida.' % ruta_liquidacion)\n\n if not os.path.isfile(os.path.join(ruta_liquidacion, 'lprodrec.DBF')):\n raise forms.ValidationError('ruta de carpeta [%s] no es la ruta de liquidacion.' % ruta_liquidacion)\n return ruta_liquidacion\n\n def clean_carpeta_facturacion_sat(self):\n carpeta_facturacion_sat = self.cleaned_data['carpeta_facturacion_sat']\n try:\n os.listdir(os.path.join(carpeta_facturacion_sat, 'sellos'))\n except WindowsError:\n raise forms.ValidationError('ruta de la carpeta [%s] de datos de facturacion es invalida.' % carpeta_facturacion_sat)\n\n return carpeta_facturacion_sat\n\n def clean_facturaa_articulo_clave(self):\n articulo_clave = self.cleaned_data['facturaa_articulo_clave']\n if not ArticuloClave.objects.filter(clave=articulo_clave).exists():\n raise forms.ValidationError('No existe ningun articulo con la clave indicada')\n return articulo_clave\n\n def clean_empresas_a_ignorar(self):\n using = router.db_for_write(Registry)\n conexion_no = using.split('-')[0]\n empresas_a_ignorar_filed = self.cleaned_data['empresas_a_ignorar']\n databases = settings.MICROSIP_DATABASES.keys()\n if empresas_a_ignorar_filed:\n empresas_a_ignorar = empresas_a_ignorar_filed.split(',')\n empresas_a_ignorar = [ conexion_no + '-' + empresa for empresa in empresas_a_ignorar ]\n for empresa in empresas_a_ignorar:\n if empresa not in databases:\n raise forms.ValidationError('la empresa %s no se encuentra registrada en microsip' % empresa)\n\n return empresas_a_ignorar_filed\n\n def save(self, *args, **kwargs):\n facturaa_cliente_nombre = Registry.objects.get(nombre='SIC_EnlaceLiquida_FacturarA_ClienteNombre')\n facturaa_cliente_nombre.valor = self.cleaned_data['facturaa_cliente'].nombre\n facturaa_cliente_nombre.save()\n facturaa_articulo_clave = Registry.objects.get(nombre='SIC_EnlaceLiquida_FacturarA_ArticuloClave')\n facturaa_articulo_clave.valor = self.cleaned_data['facturaa_articulo_clave']\n facturaa_articulo_clave.save()\n ruta_liquidacion = Registry.objects.get(nombre='SIC_EnlaceLiquida_RutaLiquidacion')\n ruta_liquidacion.valor = self.cleaned_data['ruta_liquidacion']\n ruta_liquidacion.save()\n empresas_a_ignorar = Registry.objects.get(nombre='SIC_EnlaceLiquida_EmpresasAIgnorar')\n empresas_a_ignorar.valor = self.cleaned_data['empresas_a_ignorar']\n empresas_a_ignorar.save()\n carpeta_facturacion_sat = Registry.objects.get(nombre='SIC_CarpetaFacturacionSAT')\n carpeta_facturacion_sat.valor = self.cleaned_data['carpeta_facturacion_sat']\n carpeta_facturacion_sat.save()","sub_path":"pycfiles/django-microsip-liquida-2.0.2/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":4305,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"327432286","text":"\"\"\"\nContains code to monkey patch the livereload server to accept\na path argument for reloads\n\"\"\"\n\nfrom livereload.handlers import ForceReloadHandler, LiveReloadHandler\n\ndef monkey_patch_force_reload(self):\n \"\"\"\n Monkey patching the force reload handler to support css\n \"\"\"\n msg = {\n 'command': 'reload',\n 'path': self.get_argument('path', default=None) or '*',\n 'liveCSS': True,\n 'liveImg': True,\n\n }\n for waiter in LiveReloadHandler.waiters:\n try:\n waiter.write_message(msg)\n except:\n import logging\n logging.error('Error sending message', exc_info=True)\n LiveReloadHandler.waiters.remove(waiter)\n self.write('ok')\n\nForceReloadHandler._old_get = ForceReloadHandler.get\nForceReloadHandler.get = monkey_patch_force_reload\n","sub_path":"fabuild/monkey/livereload_forcehandler.py","file_name":"livereload_forcehandler.py","file_ext":"py","file_size_in_byte":829,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"448033210","text":"# SJTU EE208\n\nimport sys, os, lucene\n\nfrom java.io import File\nfrom org.apache.lucene.analysis.cjk import CJKAnalyzer\nfrom org.apache.lucene.index import DirectoryReader\nfrom org.apache.lucene.queryparser.classic import QueryParser\nfrom org.apache.lucene.store import SimpleFSDirectory\nfrom org.apache.lucene.search import IndexSearcher\nfrom org.apache.lucene.util import Version\n\ndef valid_file_name(s):\n '''\n convert s into a valid file name.\n input:\n s: str.\n output:\n s`: str, a valid file name.\n '''\n invalid_chars = r'/\\*?:\"<>|'\n new_s = ''\n for x in s:\n if x not in invalid_chars:\n new_s = f'{new_s}{x}'\n return new_s\n\ndef run(searcher, analyzer):\n '''\n Repeatedly get the results correspoing to the \n '''\n # while True:\n print()\n print (\"Hit enter with no input to quit.\")\n if not os.path.exists(\"search_result\"):\n os.mkdir(\"search_result\")\n # command = raw_input(\"Query:\")\n # command = unicode(command, 'GBK')\n\n while True:\n command = input(\"please input the query: \")\n if not command:\n break\n limit = int(input(\"please input the maximum retrieval file number: \"))\n new_path = 'search_result/{}'.format(valid_file_name(command))\n if not os.path.exists(new_path):\n os.mkdir(new_path)\n\n\n print()\n print (\"Searching for:\", command)\n query = QueryParser(\"name\", analyzer).parse(command)\n # parse the query and get the results.\n scoreDocs = searcher.search(query, int(limit)).scoreDocs\n result_file = open(new_path + \"/result_index.txt\", \"w\", encoding='utf-8')\n \n print (\"%s total matching documents.\" % len(scoreDocs))\n\n for i, scoreDoc in enumerate(scoreDocs):\n # read the title, path, name and url from the results,\n # and print them in the terminal.\n # besides, print the content in result_content\\_.txt\n doc = searcher.doc(scoreDoc.doc)\n title, path, name, url = doc.get(\"title\"), doc.get(\"path\"), doc.get(\"name\"), doc.get('url')\n \n read_file = open(path, 'r', encoding='utf-8')\n content = ''.join(read_file.readlines())\n read_file.close()\n \n result_file.write(\n f'id:{i + 1}, \\n' +\n f'title: {title}, \\n' + \n f'path: {path}, \\n' + \n f'name: {name}, \\n' +\n f'url: {url}, \\n' + \n f'score: {scoreDoc.score} \\n') # write to terminal\n\n print(f'id:{i + 1}, \\n' +\n f'title: {title}, \\n' + \n f'path: {path}, \\n' + \n f'name: {name}, \\n' +\n f'url: {url}, \\n' + \n f'score: {scoreDoc.score}') # write to file\n\n title = valid_file_name(title)\n if len(title) > 20:\n title = title[:20] + '...'\n \n \n content_file = open(new_path + f'/{i + 1}_{title}.html', 'w', encoding='utf-8')\n content_file.write(content)\n content_file.close()\n\n # print ('path:', doc.get(\"path\"), 'name:', doc.get(\"name\"), 'score:', scoreDoc.score)\n # print 'explain:', searcher.explain(query, scoreDoc.doc)\n\n result_file.close()\n\n\nif __name__ == '__main__':\n\n STORE_DIR = \"my_index\"\n #initialize.\n lucene.initVM(vmargs=['-Djava.awt.headless=true'])\n print ('lucene', lucene.VERSION)\n directory = SimpleFSDirectory(File(STORE_DIR).toPath())\n searcher = IndexSearcher(DirectoryReader.open(directory))\n analyzer = CJKAnalyzer()#Version.LUCENE_CURRENT)\n run(searcher, analyzer)\n del searcher\n","sub_path":"lab4/code/mySearchFiles.py","file_name":"mySearchFiles.py","file_ext":"py","file_size_in_byte":3745,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"90175769","text":"import pandas as pd\nimport numpy as np\nimport re\nimport time\nimport pickle\n\n\nmovie_lines_path = 'data\\movie_lines.txt'\nmovie_conversations_path = 'data\\movie_conversations.txt'\n\nmin_line_length = 2\nmax_line_length = 9\n\ndef read_data():\n lines = open(movie_lines_path, encoding='utf-8', errors='ignore').read().split('\\n')\n conv_lines = open(movie_conversations_path, encoding='utf-8', errors='ignore').read().split('\\n')\n return lines, conv_lines\n\n\ndef build_questions_and_answers(lines, conv_lines):\n id2line = {}\n for line in lines:\n _line = line.split(' +++$+++ ')\n if len(_line) == 5:\n id2line[_line[0]] = _line[4]\n\n convs = []\n for line in conv_lines[:-1]:\n _line = line.split(' +++$+++ ')[-1][1:-1].replace(\"'\", \"\").replace(\" \", \"\")\n convs.append(_line.split(','))\n\n questions = []\n answers = []\n\n for conv in convs:\n for i in range(len(conv) - 1):\n questions.append(id2line[conv[i]])\n answers.append(id2line[conv[i + 1]])\n\n # limit = 0\n # for i in range(limit, limit + 5):\n # print(questions[i])\n # print(answers[i])\n # print('')\n return questions, answers\n\ndef check_ques_and_ans_length(q, a):\n print('length of questions = ', len(q))\n print('length of ans = ', len(a))\n\ndef clean_text(text):\n text = text.lower()\n\n text = re.sub(r\"i'm\", \"i am\", text)\n text = re.sub(r\"he's\", \"he is\", text)\n text = re.sub(r\"she's\", \"she is\", text)\n text = re.sub(r\"it's\", \"it is\", text)\n text = re.sub(r\"that's\", \"that is\", text)\n text = re.sub(r\"what's\", \"that is\", text)\n text = re.sub(r\"where's\", \"where is\", text)\n text = re.sub(r\"how's\", \"how is\", text)\n text = re.sub(r\"\\'ll\", \" will\", text)\n text = re.sub(r\"\\'ve\", \" have\", text)\n text = re.sub(r\"\\'re\", \" are\", text)\n text = re.sub(r\"\\'d\", \" would\", text)\n text = re.sub(r\"\\'re\", \" are\", text)\n text = re.sub(r\"won't\", \"will not\", text)\n text = re.sub(r\"can't\", \"cannot\", text)\n text = re.sub(r\"n't\", \" not\", text)\n text = re.sub(r\"n'\", \"ng\", text)\n text = re.sub(r\"'bout\", \"about\", text)\n text = re.sub(r\"'til\", \"until\", text)\n text = re.sub(r\"[-()\\\"#/@;:<>{}`+=~|.!?,]\", \"\", text)\n\n return text\n\ndef clean_questions_and_answers(q, a):\n cleaned_questions = []\n for question in questions:\n cleaned_questions.append(clean_text(question))\n\n cleaned_answers = []\n for answer in answers:\n cleaned_answers.append(clean_text(answer))\n\n limit = 0\n for i in range(limit, limit + 5):\n print(cleaned_questions[i])\n print(cleaned_answers[i])\n print('')\n\n return cleaned_questions, cleaned_answers\n\ndef sentences_length_analysis(q, a):\n lengths = []\n for question in q:\n lengths.append(len(question.split()))\n for answer in a:\n lengths.append(len(answer.split()))\n\n # Create a dataframe so that the values can be inspected\n lengths = pd.DataFrame(lengths, columns=['counts'])\n print(lengths.describe())\n\ndef remove_long_and_short_sentences(q, a):\n short_questions_temp = []\n short_answers_temp = []\n\n i = 0\n for question in q:\n if len(question.split()) >= min_line_length and len(question.split()) <= max_line_length:\n short_questions_temp.append(question)\n short_answers_temp.append(a[i])\n i += 1\n\n # Filter out the answers that are too short/long\n short_questions = []\n short_answers = []\n\n i = 0\n for answer in short_answers_temp:\n if len(answer.split()) >= min_line_length and len(answer.split()) <= max_line_length:\n short_answers.append(answer)\n short_questions.append(short_questions_temp[i])\n i += 1\n\n print(\"# of questions:\", len(short_questions))\n print(\"# of answers:\", len(short_answers))\n print(\"% of data used: {}%\".format(round(len(short_questions) / len(q), 4) * 100))\n\n return short_questions, short_answers\n\n\ndef build_vocab(q, a):\n threshold = 10\n vocab = {}\n for question in q:\n for word in question.split():\n if word not in vocab:\n vocab[word] = 1\n else:\n vocab[word] += 1\n\n for answer in a:\n for word in answer.split():\n if word not in vocab:\n vocab[word] = 1\n else:\n vocab[word] += 1\n\n questions_vocab_to_int = {}\n\n word_num = 0\n for word, count in vocab.items():\n if count >= threshold:\n questions_vocab_to_int[word] = word_num\n word_num += 1\n\n answers_vocab_to_int = {}\n\n word_num = 0\n for word, count in vocab.items():\n if count >= threshold:\n answers_vocab_to_int[word] = word_num\n word_num += 1\n\n\n return questions_vocab_to_int, answers_vocab_to_int\n\ndef add_unique_token(questions_vocab_to_int, answers_vocab_to_int):\n codes = ['', '', '', '']\n\n for code in codes:\n questions_vocab_to_int[code] = len(questions_vocab_to_int) + 1\n\n for code in codes:\n answers_vocab_to_int[code] = len(answers_vocab_to_int) + 1\n\n return questions_vocab_to_int, answers_vocab_to_int\n\ndef build_int_to_word(questions_vocab_to_int, answers_vocab_to_int):\n questions_int_to_vocab = {v_i: v for v, v_i in questions_vocab_to_int.items()}\n answers_int_to_vocab = {v_i: v for v, v_i in answers_vocab_to_int.items()}\n return questions_int_to_vocab, answers_int_to_vocab\n\ndef add_EOS_to_answer(fine_length_answers):\n for i in range(len(fine_length_answers)):\n fine_length_answers[i] += ' '\n\n return fine_length_answers\n\ndef text_to_int(fine_length_questions, fine_length_answers, questions_vocab_to_int, answers_vocab_to_int):\n questions_int = []\n for question in fine_length_questions:\n ints = []\n for word in question.split():\n if word not in questions_vocab_to_int:\n ints.append(questions_vocab_to_int[''])\n else:\n ints.append(questions_vocab_to_int[word])\n questions_int.append(ints)\n\n answers_int = []\n for answer in fine_length_answers:\n ints = []\n for word in answer.split():\n if word not in answers_vocab_to_int:\n ints.append(answers_vocab_to_int[''])\n else:\n ints.append(answers_vocab_to_int[word])\n answers_int.append(ints)\n\n return questions_int, answers_int\n\n\n\n\ndef pad_sentence_batch(int_sentence, vocab_to_int):\n padded = []\n pad_int = vocab_to_int['']\n for sentence in int_sentence:\n padded_sentence = np.zeros(shape=(max_line_length),dtype=np.int32)\n sentence_length = len(sentence)\n padded_sentence = sentence\n padded_sentence[sentence_length:] = pad_int * np.ones(shape=(max_line_length-sentence_length+1),dtype=np.int32)\n padded.append(padded_sentence)\n return np.array(padded)\n\n\n\n\n\n\n\n\n\n\n\n\n\nif __name__ =='__main__':\n lines, conv_lines = read_data()\n # print(lines[:10])\n # print(conv_lines[:10])\n questions, answers = build_questions_and_answers(lines, conv_lines)\n check_ques_and_ans_length(questions, answers)\n cleaned_questions, cleaned_answers = clean_questions_and_answers(questions, answers)\n sentences_length_analysis(cleaned_questions, cleaned_answers)\n\n fine_length_questions, fine_length_answers = remove_long_and_short_sentences(cleaned_questions, cleaned_answers)\n\n questions_vocab_to_int, answers_vocab_to_int = build_vocab(fine_length_questions, fine_length_answers)\n questions_vocab_to_int, answers_vocab_to_int = add_unique_token(questions_vocab_to_int, answers_vocab_to_int)\n\n questions_int_to_vocab, answers_int_to_vocab = build_int_to_word(questions_vocab_to_int, answers_vocab_to_int)\n\n file_1 = open('data\\\\vocab_to_int.pickle', 'wb')\n pickle.dump(questions_vocab_to_int, file_1)\n\n file_2 = open('data\\int_to_vocab.pickle', 'wb')\n pickle.dump(questions_int_to_vocab, file_2)\n # np.save('data\\\\vocab_to_int.npy', questions_vocab_to_int)\n # np.save('data\\int_to_vocab.npy', questions_int_to_vocab)\n # print(questions_vocab_to_int)\n # print('xx', questions_vocab_to_int['gold'])\n\n\n\n print(len(questions_vocab_to_int))\n print(len(questions_int_to_vocab))\n print(len(answers_vocab_to_int))\n print(len(answers_int_to_vocab))\n\n fine_length_answers = add_EOS_to_answer(fine_length_answers)\n print(fine_length_questions[0])\n print(fine_length_answers[0])\n\n questions_int, answers_int = text_to_int(fine_length_questions, fine_length_answers, questions_vocab_to_int, answers_vocab_to_int)\n print(len(questions_int))\n print(len(answers_int))\n\n questions_int = np.array(questions_int)\n answers_int = np.array(answers_int)\n print(questions_int.shape)\n print(answers_int.shape)\n\n print(questions_int[0])\n print(answers_int[0])\n\n\n\nq1 = []\na1 = []\nfor int_word in questions_int[0]:\n word = questions_int_to_vocab[int_word]\n q1.append(word)\n\nfor int_word in answers_int[0]:\n word = answers_int_to_vocab[int_word]\n a1.append(word)\n\nprint(q1)\nprint(a1)\n\npadded_questions = pad_sentence_batch(questions_int, questions_vocab_to_int)\npadded_answers = pad_sentence_batch(answers_int, answers_vocab_to_int)\n\nprint(padded_questions[0])\nprint(padded_answers[0])\nprint(padded_questions.shape)\nprint(padded_answers.shape)\n\n\n# np.save('data\\idx_o.npy', idx_o)\n\nprint(answers_vocab_to_int[''])\nprint(answers_vocab_to_int[''])\nprint(answers_vocab_to_int[''])\nprint(answers_vocab_to_int[''])\n\ndef add_go(data):\n res = []\n go_int = answers_vocab_to_int['']\n for sentence in data:\n buf = sentence\n buf[:9] = sentence[1:10]\n buf[0] = go_int\n res.append(buf)\n\n return np.array(res)\n\n\ngo_ans = add_go(padded_answers)\n\nnp.save('data\\idx_q.npy', padded_questions)\nnp.save('data\\idx_a.npy', padded_answers)\nnp.save('data\\idx_o.npy', go_ans)\n\n\n\n\n\n","sub_path":"movie_dialogue_corpus/data_preprocess.py","file_name":"data_preprocess.py","file_ext":"py","file_size_in_byte":9967,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"484712555","text":"# coding=utf-8\n\nfrom django.contrib import admin\n\nfrom ..models import Cuerpo\n\n\n@admin.register(Cuerpo)\nclass CuerpoAdmin(admin.ModelAdmin):\n \"\"\"\n Especificación de la representación de Cuerpo en la interfaz de administración.\n \"\"\"\n list_display = (\n 'numero',\n 'nombre',\n '_niveles',\n )\n\n def _niveles(self, obj):\n \"\"\"\n Obtiene el listado de niveles asociados a la instancia.\n \"\"\"\n return \", \".join([nivel.get_nombre_corto() for nivel in obj.nivel_set.all()])\n _niveles.short_description = 'Niveles'\n","sub_path":"app_reservas/admin/cuerpo.py","file_name":"cuerpo.py","file_ext":"py","file_size_in_byte":574,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"221584977","text":"# -*- coding: UTF-8 -*-\nimport sqlite3\n\n\nclass SQlite(object):\n def __init__(self):\n self.db = sqlite3.connect('killmails.db')\n self.cursor = self.db.cursor()\n self.cursor.execute(\"\"\"\n create table if not exists Ships (\n ShipsID integer primary key,\n Title text unique)\n \"\"\")\n\n self.cursor.execute(\"\"\"\n create table if not exists Items (\n ItemID integer primary key,\n Title text unique,\n Count integer)\n \"\"\")\n\n\n def add_ship(self, shipsID, title):\n self.cursor.execute(\"\"\"\n insert or ignore into Ships\n values (?, ?)\n \"\"\", (shipsID, title))\n\n\n def get_itemData(self, itemID):\n self.cursor.execute(\"\"\"\n select Count\n from Items\n where ItemID = ?\n \"\"\", (itemID,))\n\n data = self.cursor.fetchall()\n return data[0] if data else None\n\n\n def add_item(self, itemID, title, count):\n try:\n data = self.get_itemData(itemID)\n count += data[0]\n\n self.cursor.execute(\"\"\"\n update Items set Count = \"%d\"\n where ItemID = ?\n \"\"\" % count, (itemID,))\n\n except TypeError:\n self.cursor.execute(\"\"\"\n insert into Items\n values (?, ?, ?)\n \"\"\", (itemID, title, count))\n\n\n def close(self):\n self.db.commit()\n self.db.close()\n\n\nif __name__ == '__main__':\n print('module sqlite.py')","sub_path":"sqlite.py","file_name":"sqlite.py","file_ext":"py","file_size_in_byte":1581,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"405348488","text":"class Solution:\n\n def sumPair(self, nums, target):\n '''\n nums type: list\n target type: int\n rtype: int\n '''\n if not nums:\n return 0\n\n res, dic = 0, {}\n for n in nums[:len(nums) // 2]:\n t = target - n\n pos = self.bsHelper(nums, t)\n res += pos\n # print(t, pos)\n return res\n\n def bsHelper(self, nums, t):\n l, r = 0, len(nums) - 1\n while l < r:\n m = l + r >> 1\n if t == nums[m]:\n return m\n if t > nums[m]:\n l = m + 1\n else:\n r = m - 1\n return l\n\n\nObj = Solution()\nnums = [1, 2, 4, 5, 6, 7]\nX = 7\nprint(Obj.sumPair(nums, X))\nprint(Obj.bsHelper(nums, 3))\n","sub_path":"LeetCode/test1.py","file_name":"test1.py","file_ext":"py","file_size_in_byte":783,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"548461248","text":"# leetcode - https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iv/\nclass Solution:\n def maxProfit(self, k: int, prices: List[int]) -> int:\n if k>=(len(prices)>>1):\n t_ik0,t_ik1=0,float('-inf')\n for price in prices:\n t_ik0_old=t_ik0\n t_ik0=max(t_ik0,t_ik1+price)\n t_ik1=max(t_ik1,t_ik0_old-price)\n return t_ik0\n t_ik0=[0]*(k+1)\n t_ik1=[float('-inf')]*(k+1)\n for price in prices:\n for j in range(k,0,-1):\n t_ik0[j]=max(t_ik0[j],t_ik1[j]+price)\n t_ik1[j]=max(t_ik1[j],t_ik0[j-1]-price)\n return t_ik0[k]\n","sub_path":"leetcode/best-time-to-buy-and-sell-stock-iv.py","file_name":"best-time-to-buy-and-sell-stock-iv.py","file_ext":"py","file_size_in_byte":669,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"418152987","text":"import math\nimport random\nimport pygame\nimport pygame.gfxdraw\nimport pygame.locals as pyglocal\n# local files\nfrom const import Colors\n\n\nclass BurnPoints:\n \"\"\" Burning Points Manager \"\"\"\n\n class Burn:\n \"\"\" Burning Point\"\"\"\n\n def __init__(self):\n self.x = 0\n self.y = 0\n self.wait = 0\n self.state = False\n\n def reset(self, x, y, wait):\n self.x = x\n self.y = y\n self.wait = wait\n self.state = True\n\n def get_params(self):\n return (self.x, self.y, self.wait)\n\n def off(self):\n self.state = False\n\n def decrement_and_off(self):\n self.wait -= 1\n if self.wait <= 0:\n self.state = False\n\n def __init__(self):\n self.points = [BurnPoints.Burn() for _ in range(100)]\n\n def reset(self):\n for point in self.points:\n point.off()\n\n def add(self, xyt):\n xy, t = xyt\n x, y = xy\n for point in self.points:\n if not point.state:\n point.reset(x, y, t)\n return\n\n def update(self):\n for point in self.points:\n if point.state:\n point.decrement_and_off()\n\n\n# number of zigzag of burning draw\nBURNING_ZIGZAG = 10\n# small burning size array (for each layer)\nSMALL_BURNING_SIZE_ARRAY = [8, 6, 4]\n# normal burning size array (for each layer)\nNORMAL_BURNING_SIZE_ARRAY = [12, 10, 8]\n# large burning size array (for each layer)\nLARGE_BURNING_SIZE_ARRAY = [14, 12, 10]\n# burning layer limit (~= buring time limit)\nBURNING_LAYER_MAX = 500\n\n\ndef anglexr(rate, r, x):\n return math.cos(math.pi * 2 * rate) * random.random() * r + x\n\n\ndef angleyr(rate, r, y):\n return math.sin(math.pi * 2 * rate) * random.random() * r + y\n\n\ndef create_burninglayer(r, x, y):\n \"create burning points\"\n return [(anglexr(n / BURNING_ZIGZAG, r, x),\n angleyr(n / BURNING_ZIGZAG, r, y))\n for n in range(BURNING_ZIGZAG)]\n\n\ndef draw_burning_with_size(screen, x, y, size_array):\n \"draw burning with size array\"\n for i, size in enumerate(size_array):\n color = Colors.BURN_GRADATION[i]\n layer = create_burninglayer(size, x, y)\n pygame.draw.polygon(screen, color, layer)\n\n\ndef draw_gunburn(screen, x, y):\n \"draw gun burn : burn for player's gunburn, missile and alien missile\"\n draw_burning_with_size(screen, x, y, SMALL_BURNING_SIZE_ARRAY)\n\n\nclass BuriningDrawer:\n \"\"\" Burning Drawer \"\"\"\n\n def __init__(self):\n self.burnlayers = list()\n burn_lt = 50\n for i in range(BURNING_LAYER_MAX):\n surf = pygame.Surface((burn_lt * 2, burn_lt * 2))\n draw_burning_with_size(surf, burn_lt, burn_lt,\n NORMAL_BURNING_SIZE_ARRAY)\n for i in range(5):\n x = burn_lt + random.randint(0, 4)\n y = burn_lt + random.randint(0, 4)\n draw_burning_with_size(surf, x, y, LARGE_BURNING_SIZE_ARRAY)\n surf.set_colorkey(Colors.BLACK, pyglocal.RLEACCEL)\n surf.convert_alpha()\n self.burnlayers.append(surf)\n\n def draw_burning(self, screen, burnpoints):\n \"draw general burning\"\n burn_lt = 50\n for point in burnpoints.points:\n if point.state:\n x, y, t = point.get_params()\n xy = (x - burn_lt, y - burn_lt)\n screen.blit(self.burnlayers[int(t)], xy)\n","sub_path":"contoh space game/pygame-simple-shooting-master/game/burn.py","file_name":"burn.py","file_ext":"py","file_size_in_byte":3493,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"175234425","text":"from p5 import *\n\n\nclass Particle:\n def __init__(self, start_x, start_y, mass):\n self.pos = Vector(start_x, start_y)\n self.vel = Vector(0, 0)\n self.acc = Vector(0, 0)\n self.mass = mass\n\n def display(self):\n scaling_factor = 30\n fill(255)\n circle(self.pos, scaling_factor * self.mass**.33)\n # ellipse(self.pos, scaling_factor * self.mass**.33, scaling_factor * self.mass**.33)\n # Volume of a sphere is 4/3 * pi * r**3, so r is proportional to V**(1/3)\n\n def update(self):\n self.vel += self.acc\n self.pos += self.vel\n # print(self.pos, self.vel)\n self.acc = Vector(0, 0)\n\n def apply_force(self, gravity):\n self.acc += gravity / self.mass\n\n def check_edges(self):\n if self.pos.y > height:\n self.vel.y *= -0.9 # damper\n self.pos.y = height\n\n if self.pos.x > width:\n self.vel.x *= -1\n self.pos.x = width\n\n\ndef setup():\n size(640, 360)\n\n\ndef draw():\n background(51)\n g0 = Vector(0, .3)\n wind = Vector(.1, 0)\n\n particle1.apply_force(g0 * particle1.mass) # gravity force is proportional to mass\n particle2.apply_force(g0 * particle2.mass)\n\n if mouse_is_pressed:\n particle1.apply_force(wind)\n particle2.apply_force(wind)\n\n particle1.check_edges()\n particle2.check_edges()\n particle1.update()\n particle2.update()\n particle1.display()\n particle2.display()\n\n\nif __name__ == '__main__':\n particle1 = Particle(200, 100, 1)\n particle2 = Particle(400, 100, 4)\n run()\n\n # In Clip 5 of Session 5, the lecturer discovered p5js couldn't keep two balls falling in sync because\n # the velos have a very tiny difference and he provided no solution. You don't observe this issue in p5py.","sub_path":"session_2/mass_damper.py","file_name":"mass_damper.py","file_ext":"py","file_size_in_byte":1804,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"424481926","text":"# -*- coding: utf-8 -*-\nimport django.utils.timezone\nimport django_date_extensions.fields\nfrom django.conf import settings\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('auth', '0001_initial'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='User',\n fields=[\n ('id', models.AutoField(serialize=False, primary_key=True, auto_created=True, verbose_name='ID')),\n ('password', models.CharField(max_length=128, verbose_name='password')),\n ('last_login', models.DateTimeField(verbose_name='last login', default=django.utils.timezone.now)),\n ('is_superuser', models.BooleanField(verbose_name='superuser status', default=False, help_text='Designates that this user has all permissions without explicitly assigning them.')),\n ('email', models.EmailField(unique=True, max_length=75)),\n ('first_name', models.CharField(max_length=30, blank=True)),\n ('last_name', models.CharField(max_length=30, blank=True)),\n ('is_staff', models.BooleanField(default=False)),\n ('is_active', models.BooleanField(default=True)),\n ('date_joined', models.DateTimeField(auto_now_add=True)),\n ('groups', models.ManyToManyField(verbose_name='groups', to='auth.Group', blank=True, related_name='user_set', related_query_name='user', help_text='The groups this user belongs to. A user will get all permissions granted to each of his/her group.')),\n ('user_permissions', models.ManyToManyField(verbose_name='user permissions', to='auth.Permission', blank=True, related_name='user_set', related_query_name='user', help_text='Specific permissions for this user.')),\n ],\n options={\n 'verbose_name': 'Organizer',\n 'verbose_name_plural': 'Organizers',\n },\n bases=(models.Model,),\n ),\n migrations.CreateModel(\n name='Event',\n fields=[\n ('id', models.AutoField(serialize=False, primary_key=True, auto_created=True, verbose_name='ID')),\n ('name', models.CharField(max_length=200)),\n ('date', django_date_extensions.fields.ApproximateDateField(max_length=10, blank=True, null=True)),\n ('city', models.CharField(max_length=200)),\n ('country', models.CharField(max_length=200)),\n ('latlng', models.CharField(max_length=30, blank=True, null=True)),\n ('is_on_homepage', models.BooleanField(default=False)),\n ],\n options={\n 'verbose_name_plural': 'List of events',\n },\n bases=(models.Model,),\n ),\n migrations.CreateModel(\n name='EventPage',\n fields=[\n ('event', models.OneToOneField(to='core.Event', serialize=False, primary_key=True)),\n ('title', models.CharField(max_length=200, blank=True, null=True)),\n ('description', models.TextField(blank=True, null=True, default='Django Girls is a one-day workshop about programming in Python and Django tailored for women.')),\n ('main_color', models.CharField(max_length=6, default='FF9400', blank=True, null=True, help_text='Main color of the chapter in HEX')),\n ('custom_css', models.TextField(blank=True, null=True)),\n ('url', models.CharField(max_length=200, blank=True, null=True)),\n ('is_live', models.BooleanField(default=False)),\n ],\n options={\n 'verbose_name': 'Website',\n },\n bases=(models.Model,),\n ),\n migrations.CreateModel(\n name='EventPageContent',\n fields=[\n ('id', models.AutoField(serialize=False, primary_key=True, auto_created=True, verbose_name='ID')),\n ('name', models.CharField(max_length=100)),\n ('content', models.TextField(help_text='HTML allowed')),\n ('background', models.ImageField(upload_to='event/backgrounds/', blank=True, null=True, help_text='Optional background photo')),\n ('position', models.PositiveIntegerField(help_text='Position of the block on the website')),\n ('is_public', models.BooleanField(default=False)),\n ('page', models.ForeignKey(to='core.EventPage')),\n ],\n options={\n 'ordering': ('position',),\n 'verbose_name': 'Website Content',\n },\n bases=(models.Model,),\n ),\n migrations.CreateModel(\n name='EventPageMenu',\n fields=[\n ('id', models.AutoField(serialize=False, primary_key=True, auto_created=True, verbose_name='ID')),\n ('title', models.CharField(max_length=255)),\n ('url', models.CharField(max_length=255)),\n ('position', models.PositiveIntegerField(help_text='Order of menu')),\n ('page', models.ForeignKey(to='core.EventPage')),\n ],\n options={\n 'ordering': ('position',),\n 'verbose_name': 'Website Menu',\n },\n bases=(models.Model,),\n ),\n migrations.CreateModel(\n name='Sponsor',\n fields=[\n ('id', models.AutoField(serialize=False, primary_key=True, auto_created=True, verbose_name='ID')),\n ('name', models.CharField(max_length=200, blank=True, null=True)),\n ('logo', models.ImageField(upload_to='event/sponsors/', blank=True, null=True, help_text='Make sure logo is not bigger than 200 pixels wide')),\n ('url', models.URLField(blank=True, null=True)),\n ('description', models.TextField(blank=True, null=True)),\n ('position', models.PositiveIntegerField(help_text='Position of the sponsor')),\n ('event_page_content', models.ForeignKey(to='core.EventPageContent')),\n ],\n options={\n 'ordering': ('position',),\n },\n bases=(models.Model,),\n ),\n migrations.AddField(\n model_name='event',\n name='main_organizer',\n field=models.ForeignKey(to=settings.AUTH_USER_MODEL, null=True, related_name='main_organizer', blank=True),\n preserve_default=True,\n ),\n migrations.AddField(\n model_name='event',\n name='team',\n field=models.ManyToManyField(to=settings.AUTH_USER_MODEL, blank=True, null=True),\n preserve_default=True,\n ),\n ]\n","sub_path":"core/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":6748,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"598665422","text":"\"\"\"\nпрослушивает порт и отправляет обратно капсованное говно\nвыводит полученное в юникод\n\"\"\"\n\nimport socket\nimport time\nimport os\n\nsock = socket.socket()\nsock.bind(('', 9090))\nsock.listen(1)\nconn, addr = sock.accept()\n\nprint('connected:', addr)\nprint(conn)\n\nwhile True:\n data = conn.recv(16384)\n udata = data.decode(\"utf-8\")\n if not data:\n break\n conn.send(data.upper())\n print(udata, time.strftime('%H.%M.%S %d/%m/%y'))\n\n#conn.close()\n","sub_path":"chat-server.py","file_name":"chat-server.py","file_ext":"py","file_size_in_byte":532,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"163052899","text":"## Inorder Traversal of Binary Tree\n# 1. Iterative approach - Using stack\n# 2. Recursive approach\n\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def inorderTraversal(self, root: TreeNode) -> List[int]:\n \n # Using Iteration\n result = []\n stack = []\n cur = root\n \n while cur!=None or stack!=[]:\n \n while cur!=None:\n stack.append(cur)\n cur = cur.left\n \n cur = stack.pop()\n result.append(cur.val)\n cur = cur.right\n \n return result\n \n# # Using Recursion\n# def inorderTraversal(self, root: TreeNode) -> List[int]:\n# result = []\n# def helper(root):\n# nonlocal result\n# if root:\n# helper(root.left)\n# result.append(root.val)\n# helper(root.right)\n# helper(root)\n \n# return result\n","sub_path":"Medium/inorderTraversal.py","file_name":"inorderTraversal.py","file_ext":"py","file_size_in_byte":1126,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"459305876","text":"from datetime import datetime\nimport logging\nimport os, requests,cgi, json, codecs,math\nimport base64\n\nfrom flask import Flask, redirect, render_template, request\n\nfrom google.cloud import datastore\nfrom google.cloud import storage\nfrom google.cloud import vision\n\n\nCLOUD_STORAGE_BUCKET = 'testproject-235616'\n\napp = Flask(__name__)\n\n\n@app.route('/')\ndef homepage():\n return render_template('homepage.html')\n\ndef getPlaceDetails(location):\n url = 'https://maps.googleapis.com/maps/api/place/findplacefromtext/json?key=AIzaSyCNQX5-4_hPDpluC7j-EZK13Oixn_47DpM&input=' + location + '&inputtype=textquery'\n response = requests.get(url)\n if response.ok:\n candidates = response.json()['candidates']\n if len(candidates) == 0:\n return False\n placeId = candidates[0]['place_id']\n url = 'https://maps.googleapis.com/maps/api/place/details/json?key=AIzaSyCNQX5-4_hPDpluC7j-EZK13Oixn_47DpM&placeid=' + placeId\n response = requests.get(url)\n if response.ok:\n result = response.json()['result']\n return {'latitude': result['geometry']['location']['lat'], 'longitude': result['geometry']['location']['lng'], 'shortName': result['address_components'][0]['short_name'],'longName': result['address_components'][0]['long_name'], 'type': result['types'][0]}\n else:\n return False\n else:\n return False\n\ndef getImageProperties(content):\n client = vision.ImageAnnotatorClient()\n image = vision.types.Image(content=content)\n\n response = client.image_properties(image=image)\n props = response.image_properties_annotation\n\n waterAmount = 0\n fieldsAmount = 0\n mountainsAmount = 0\n othersAmount = 0\n\n for color in props.dominant_colors.colors:\n if 200 <= color.color.green <= 222 and 169 <= color.color.red <= 189 and 230 <= color.color.blue :\n waterAmount += color.pixel_fraction\n elif 224 <= color.color.green <= 244 and 200 <= color.color.red <= 220 and 190 <= color.color.blue <= 210:\n mountainsAmount += color.pixel_fraction\n elif (236 <= color.color.green <= 246 and 234 <= color.color.red <= 244 and 225 <= color.color.blue <= 235) or (225 <= color.color.green <= 238 and 210 <= color.color.red <= 240 and 205 <= color.color.blue <= 230):\n fieldsAmount += color.pixel_fraction\n else:\n othersAmount += color.pixel_fraction\n\n if waterAmount == 0:\n waterAmount = 1 - (waterAmount + fieldsAmount + mountainsAmount + othersAmount)\n elif mountainsAmount == 0:\n mountainsAmount = (1 - (waterAmount + fieldsAmount + mountainsAmount + othersAmount))/2\n elif fieldsAmount == 0:\n fieldsAmount = (1 - (waterAmount + fieldsAmount + mountainsAmount + othersAmount))/1.5\n else:\n othersAmount += 1 - (waterAmount + fieldsAmount + mountainsAmount + othersAmount)\n\n return {'water': round(waterAmount* 100,2), 'fields': round(fieldsAmount* 100,2), 'mountains': round(mountainsAmount * 100,2), 'others': round(othersAmount * 100,2)}\n\ndef getImageFromlocation(location):\n url = 'https://maps.googleapis.com/maps/api/staticmap?center=' + location + '&size=800x800&maptype=roadmap&scale=2&key=AIzaSyCNQX5-4_hPDpluC7j-EZK13Oixn_47DpM'\n response = requests.get(url)\n if response.ok:\n image = base64.b64encode(response.content).decode()\n return {'base64': image, 'binary': response.content}\n else:\n return False\n\ndef getSearchResponses(query):\n url = 'https://www.googleapis.com/customsearch/v1?q=' + query + '&cx=013429757699244883815:0kpxacrknmm&key=AIzaSyCNQX5-4_hPDpluC7j-EZK13Oixn_47DpM'\n response = requests.get(url)\n if response.ok:\n result = []\n for item in response.json()['items']:\n result.append({'title': item['title'], 'link': item['link']})\n return result\n else:\n return False\n\ndef getFromDatastore(name):\n datastore_client = datastore.Client()\n query = datastore_client.query(kind='Location')\n query.add_filter('name', '=', name)\n result = list(query.fetch())\n\n if result == []:\n return False\n \n result = result[0]\n\n storage_client = storage.Client()\n bucket = storage_client.get_bucket(CLOUD_STORAGE_BUCKET)\n blob = bucket.get_blob(result['image_blob'])\n return {'name': result['name'], 'imageProperties': result['imageProperties'], 'searchResponses': result['searchResponses'],\"image\":blob.download_as_string().decode(), \"placeDetails\": result['placeDetails']}\n\ndef insertInDatastore(item):\n storage_client = storage.Client()\n bucket = storage_client.get_bucket(CLOUD_STORAGE_BUCKET)\n\n blob = bucket.blob(item['name'] + '-blob')\n blob.upload_from_string(item['image'])\n blob.make_public()\n datastore_client = datastore.Client()\n kind = 'Location'\n name = item['name']\n key = datastore_client.key(kind, name)\n entity = datastore.Entity(key)\n entity['name'] = item['name']\n entity['image_blob'] = blob.name\n entity['imageProperties'] = item['imageProperties']\n entity['searchResponses'] = item['searchResponses']\n entity['placeDetails'] = item['placeDetails']\n datastore_client.put(entity)\n\n\n@app.route('/compute', methods=['GET', 'POST'])\ndef compute():\n input = request.args.get('query')\n databaseItem = getFromDatastore(input)\n if not databaseItem == False:\n return json.dumps(databaseItem)\n\n placeDetails = getPlaceDetails(input)\n mapImage = getImageFromlocation(input)\n searchResponses = getSearchResponses(input)\n imageProperties = getImageProperties(mapImage['binary'])\n result = {'name': input, 'imageProperties': imageProperties, 'searchResponses': searchResponses,\"image\":mapImage['base64'], 'placeDetails': placeDetails}\n insertInDatastore(result)\n return json.dumps(result)\n\n\n@app.errorhandler(500)\ndef server_error(e):\n logging.exception('An error occurred during a request.')\n return \"\"\"\n An internal error occurred:
{}
\n See logs for full stacktrace.\n \"\"\".format(e), 500\n\n\nif __name__ == '__main__':\n # This is used when running locally. Gunicorn is used to run the\n # application on Google App Engine. See entrypoint in app.yaml.\n app.run(host='127.0.0.1', port=8080, debug=True)","sub_path":"Tema3/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":6264,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"189973835","text":"import os, vtk, qt, ctk, slicer\n#import cv2 as cv\nfrom slicer.ScriptedLoadableModule import *\n\n\n# TrackerCalibration\nclass TrackerCalibration(ScriptedLoadableModule):\n def __init__(self, parent):\n ScriptedLoadableModule.__init__(self, parent)\n self.parent.title = \"TrackerCalibration\" # TODO make this more human readable by adding spaces\n self.parent.categories = [\"Camera\"]\n self.parent.dependencies = []\n self.parent.contributors = [\"Adam Rankin (Robarts Research Institute)\"]\n self.parent.helpText = \"\"\"Perform camera calibration against an external tracker.\"\"\"\n self.parent.helpText += self.getDefaultModuleDocumentationLink()\n self.parent.acknowledgementText = \"\"\"\nThis file was originally developed by Jean-Christophe Fillion-Robin, Kitware Inc.\nand Steve Pieper, Isomics, Inc. and was partially funded by NIH grant 3P41RR013218-12S1.\n\"\"\"\n\n\n# TrackerCalibrationWidget\nclass TrackerCalibrationWidget(ScriptedLoadableModuleWidget):\n @staticmethod\n def get(widget, objectName):\n if widget.objectName == objectName:\n return widget\n else:\n for w in widget.children():\n resulting_widget = TrackerCalibrationWidget.get(w, objectName)\n if resulting_widget:\n return resulting_widget\n return None\n\n def __init__(self, parent):\n ScriptedLoadableModuleWidget.__init__(self, parent)\n\n self.logic = TrackerCalibrationLogic()\n\n self.isCapturing = False\n\n self.centerFiducialSelectionNode = None\n self.copyNode = None\n self.widget = None\n\n self.inputsContainer = None\n self.trackerContainer = None\n self.intrinsicsContainer = None\n self.autoSettingsContainer = None\n\n # Tracker\n self.captureButton = None\n self.previewButton = None\n self.imageSelector = None\n self.cameraSelector = None\n self.cameraTransformSelector = None\n self.volumeModeButton = None\n self.cameraModeButton = None\n self.cameraContainerWidget = None\n self.volumeContainerWidget = None\n self.manualModeButton = None\n self.autoModeButton = None\n self.semiAutoModeButton = None\n\n # Intrinsics\n self.capIntrinsicButton = None\n self.intrinsicCheckerboardButton = None\n self.intrinsicCircleGridButton = None\n self.adaptiveThresholdButton = None\n self.normalizeImageButton = None\n self.filterQuadsButton = None\n self.fastCheckButton = None\n self.symmetricButton = None\n self.asymmetricButton = None\n self.clusteringButton = None\n\n self.sceneObserverTag = None\n\n def setup(self):\n ScriptedLoadableModuleWidget.setup(self)\n\n # Load the UI From file\n scriptedModulesPath = eval('slicer.modules.%s.path' % self.moduleName.lower())\n scriptedModulesPath = os.path.dirname(scriptedModulesPath)\n path = os.path.join(scriptedModulesPath, 'Resources', 'UI', 'q' + self.moduleName + 'Widget.ui')\n self.widget = slicer.util.loadUI(path)\n self.layout.addWidget(self.widget)\n\n # Tracker calibration members\n self.inputsContainer = TrackerCalibrationWidget.get(self.widget, \"collapsibleButton_Inputs\")\n self.trackerContainer = TrackerCalibrationWidget.get(self.widget, \"collapsibleButton_Tracker\")\n self.intrinsicsContainer = TrackerCalibrationWidget.get(self.widget, \"collapsibleButton_Intrinsics\")\n self.captureButton = TrackerCalibrationWidget.get(self.widget, \"pushButton_Manual\")\n self.previewButton = TrackerCalibrationWidget.get(self.widget, \"pushButton_Automatic\")\n self.imageSelector = TrackerCalibrationWidget.get(self.widget, \"comboBox_ImageSelector\")\n self.cameraSelector = TrackerCalibrationWidget.get(self.widget, \"comboBox_CameraSource\")\n self.cameraTransformSelector = TrackerCalibrationWidget.get(self.widget, \"comboBox_CameraTransform\")\n self.volumeModeButton = TrackerCalibrationWidget.get(self.widget, \"radioButton_VolumeNode\")\n self.cameraModeButton = TrackerCalibrationWidget.get(self.widget, \"radioButton_CameraMode\")\n self.cameraContainerWidget = TrackerCalibrationWidget.get(self.widget, \"widget_CameraInput\")\n self.volumeContainerWidget = TrackerCalibrationWidget.get(self.widget, \"widget_VolumeInput\")\n self.manualModeButton = TrackerCalibrationWidget.get(self.widget, \"radioButton_Manual\")\n self.semiAutoModeButton = TrackerCalibrationWidget.get(self.widget, \"radioButton_SemiAuto\")\n self.autoModeButton = TrackerCalibrationWidget.get(self.widget, \"radioButton_Automatic\")\n self.autoSettingsContainer = TrackerCalibrationWidget.get(self.widget, \"groupBox_AutoSettings\")\n\n # Intrinsic calibration members\n self.capIntrinsicButton = TrackerCalibrationWidget.get(self.widget, \"pushButton_CaptureIntrinsic\")\n self.intrinsicCheckerboardButton = TrackerCalibrationWidget.get(self.widget, \"radioButton_IntrinsicCheckerboard\")\n self.intrinsicCircleGridButton = TrackerCalibrationWidget.get(self.widget, \"radioButton_IntrinsicCircleGrid\")\n self.adaptiveThresholdButton = TrackerCalibrationWidget.get(self.widget, \"checkBox_AdaptiveThreshold\")\n self.normalizeImageButton = TrackerCalibrationWidget.get(self.widget, \"checkBox_NormalizeImage\")\n self.filterQuadsButton = TrackerCalibrationWidget.get(self.widget, \"checkBox_FilterQuads\")\n self.fastCheckButton = TrackerCalibrationWidget.get(self.widget, \"checkBox_FastCheck\")\n self.symmetricButton = TrackerCalibrationWidget.get(self.widget, \"radioButton_SymmetricGrid\")\n self.asymmetricButton = TrackerCalibrationWidget.get(self.widget, \"radioButton_AsymmetricGrid\")\n self.clusteringButton = TrackerCalibrationWidget.get(self.widget, \"radioButton_Clustering\")\n\n # Hide the camera source as default is volume source\n self.cameraContainerWidget.setVisible(False)\n\n # Disable capture as image processing isn't active yet\n self.trackerContainer.setEnabled(False)\n self.intrinsicsContainer.setEnabled(False)\n\n # UI file method does not do mrml scene connections, do them manually\n self.imageSelector.setMRMLScene(slicer.mrmlScene)\n self.cameraSelector.setMRMLScene(slicer.mrmlScene)\n self.cameraTransformSelector.setMRMLScene(slicer.mrmlScene)\n\n # Connections\n self.captureButton.connect('clicked(bool)', self.onCaptureButton)\n self.previewButton.connect('clicked(bool)', self.onPreviewButton)\n self.imageSelector.connect(\"currentNodeChanged(vtkMRMLNode*)\", self.onImageSelected)\n self.cameraTransformSelector.connect(\"currentNodeChanged(vtkMRMLNode*)\", self.onCameraSelected)\n self.cameraSelector.connect(\"currentNodeChanged(vtkMRMLNode*)\", self.onSelect)\n self.volumeModeButton.connect('clicked(bool)', self.onInputModeChanged)\n self.cameraModeButton.connect('clicked(bool)', self.onInputModeChanged)\n self.manualModeButton.connect('clicked(bool)', self.onProcessingModeChanged)\n self.autoModeButton.connect('clicked(bool)', self.onProcessingModeChanged)\n\n self.capIntrinsicButton.connect('clicked(bool)', self.onIntrinsicCapture)\n self.intrinsicCheckerboardButton.connect('clicked(bool)', self.onIntrinsicModeChanged)\n self.intrinsicCircleGridButton.connect('clicked(bool)', self.onIntrinsicModeChanged)\n\n # Adding an observer to scene to listen for mrml node\n self.sceneObserverTag = slicer.mrmlScene.AddObserver(slicer.mrmlScene.NodeAddedEvent, self.onNodeAdded)\n\n # Choose red slice only\n lm = slicer.app.layoutManager()\n lm.setLayout(slicer.vtkMRMLLayoutNode.SlicerLayoutOneUpRedSliceView)\n\n # Refresh Apply button state\n self.onSelect()\n\n def cleanup(self):\n self.captureButton.disconnect('clicked(bool)', self.onCaptureButton)\n self.previewButton.disconnect('clicked(bool)', self.onPreviewButton)\n self.imageSelector.disconnect(\"currentNodeChanged(vtkMRMLNode*)\", self.onImageSelected)\n self.cameraTransformSelector.disconnect(\"currentNodeChanged(vtkMRMLNode*)\", self.onCameraSelected)\n self.cameraSelector.disconnect(\"currentNodeChanged(vtkMRMLNode*)\", self.onSelect)\n self.volumeModeButton.disconnect('clicked(bool)', self.onInputModeChanged)\n self.cameraModeButton.disconnect('clicked(bool)', self.onInputModeChanged)\n self.manualModeButton.disconnect('clicked(bool)', self.onProcessingModeChanged)\n self.autoModeButton.disconnect('clicked(bool)', self.onProcessingModeChanged)\n\n self.capIntrinsicButton.disconnect('clicked(bool)', self.onIntrinsicCapture)\n self.intrinsicCheckerboardButton.disconnect('clicked(bool)', self.onIntrinsicModeChanged)\n self.intrinsicCircleGridButton.disconnect('clicked(bool)', self.onIntrinsicModeChanged)\n\n slicer.mrmlScene.RemoveObserver(self.sceneObserverTag)\n\n def onIntrinsicCapture(self):\n pass\n\n def onImageSelected(self):\n # Set red slice to the copy node\n slicer.app.layoutManager().sliceWidget('Red').sliceLogic().GetSliceCompositeNode().SetForegroundVolumeID(self.imageSelector.currentNode().GetID())\n self.onSelect()\n\n def onCameraSelected(self):\n self.onSelect()\n\n def onIntrinsicModeChanged(self):\n if self.intrinsicCheckerboardButton.checked:\n self.adaptiveThresholdButton.enabled = True\n self.normalizeImageButton.enabled = True\n self.filterQuadsButton.enabled = True\n self.fastCheckButton.enabled = True\n self.symmetricButton.enabled = False\n self.asymmetricButton.enabled = False\n self.clusteringButton.enabled = False\n else:\n self.adaptiveThresholdButton.enabled = False\n self.normalizeImageButton.enabled = False\n self.filterQuadsButton.enabled = False\n self.fastCheckButton.enabled = False\n self.symmetricButton.enabled = True\n self.asymmetricButton.enabled = True\n self.clusteringButton.enabled = True\n\n def onSelect(self):\n self.capIntrinsicButton.enabled = (self.imageSelector.currentNode() or self.cameraSelector.currentNode()) and self.cameraTransformSelector.currentNode()\n self.captureButton.enabled = (self.imageSelector.currentNode() or self.cameraSelector.currentNode()) and self.cameraTransformSelector.currentNode()\n self.previewButton.enabled = (self.imageSelector.currentNode() or self.cameraSelector.currentNode()) and self.cameraTransformSelector.currentNode()\n self.trackerContainer.enabled = (self.imageSelector.currentNode() or self.cameraSelector.currentNode()) and self.cameraTransformSelector.currentNode()\n self.intrinsicsContainer.enabled = (self.imageSelector.currentNode() or self.cameraSelector.currentNode()) and self.cameraTransformSelector.currentNode()\n\n def onInputModeChanged(self):\n if self.volumeModeButton.checked:\n self.cameraContainerWidget.setVisible(False)\n self.volumeContainerWidget.setVisible(True)\n else:\n self.cameraContainerWidget.setVisible(True)\n self.volumeContainerWidget.setVisible(False)\n\n def onProcessingModeChanged(self):\n if self.manualModeButton.checked:\n self.captureButton.setVisible(True)\n self.previewButton.setVisible(False)\n self.autoSettingsContainer.setEnabled(False)\n elif self.semiAutoModeButton.checked:\n self.captureButton.setVisible(False)\n self.previewButton.setVisible(True)\n self.autoSettingsContainer.setEnabled(True)\n else:\n self.captureButton.setVisible(True)\n self.previewButton.setVisible(False)\n self.autoSettingsContainer.setEnabled(True)\n\n def onCaptureButton(self):\n if self.isCapturing:\n # Cancel button hit\n slicer.modules.markups.logic().StopPlaceMode()\n self.inputsContainer.setEnabled(True)\n self.trackerContainer.setEnabled(True)\n slicer.app.layoutManager().sliceWidget('Red').sliceLogic().GetSliceCompositeNode().SetForegroundVolumeID(self.centerFiducialSelectionNode.GetID())\n return()\n\n # Make a copy of the volume node (aka freeze cv capture) to allow user to play with detection parameters or click on center\n if self.copyNode is not None:\n # Clean up old copy\n slicer.mrmlScene.RemoveNode(self.copyNode)\n self.copyNode = None\n\n self.centerFiducialSelectionNode = slicer.mrmlScene.GetNodeByID(slicer.app.layoutManager().sliceWidget('Red').sliceLogic().GetSliceCompositeNode().GetForegroundVolumeID())\n self.copyNode = slicer.mrmlScene.CopyNode(self.centerFiducialSelectionNode)\n\n # Set red slice to the copy node\n slicer.app.layoutManager().sliceWidget('Red').sliceLogic().GetSliceCompositeNode().SetForegroundVolumeID(self.copyNode.GetID())\n\n # Initiate fiducial selection\n slicer.modules.markups.logic().StartPlaceMode(False)\n\n # Disable input changing while capture is active\n self.inputsContainer.setEnabled(False)\n self.trackerContainer.setEnabled(False)\n\n self.isCapturing = True\n self.captureButton.setText('Cancel')\n\n @vtk.calldata_type(vtk.VTK_OBJECT)\n def onNodeAdded(self, caller, event, callData):\n if type(callData) is slicer.vtkMRMLMarkupsFiducialNode:\n arr = [0,0,0]\n callData.GetMarkupPoint(callData.GetNumberOfMarkups()-1, 0, arr)\n callData.RemoveAllMarkups()\n slicer.mrmlScene.RemoveNode(callData)\n\n # Re-enable\n self.inputsContainer.setEnabled(True)\n self.trackerContainer.setEnabled(True)\n\n # TODO : store point and line pair\n\n # Resume playback\n slicer.app.layoutManager().sliceWidget('Red').sliceLogic().GetSliceCompositeNode().SetForegroundVolumeID(self.centerFiducialSelectionNode.GetID())\n\n def onPreviewButton(self):\n pass\n\n# TrackerCalibrationLogic\nclass TrackerCalibrationLogic(ScriptedLoadableModuleLogic):\n def __init__(self):\n self.pointList = []\n self.lineList = []\n\n def addPointToLine(self, point, line):\n pass\n\n def run(self, cameraImageNode, cameraPoseNode):\n return True\n\n\n# TrackerCalibrationTest\nclass TrackerCalibrationTest(ScriptedLoadableModuleTest):\n def setUp(self):\n \"\"\" Do whatever is needed to reset the state - typically a scene clear will be enough. \"\"\"\n slicer.mrmlScene.Clear(0)\n\n def test_TrackerCalibration1(self):\n self.delayDisplay(\"Starting the test\")\n self.delayDisplay('Test passed!')\n\n def runTest(self):\n \"\"\" Run as few or as many tests as needed here. \"\"\"\n self.setUp()\n self.test_TrackerCalibration1()","sub_path":"TrackerCalibration/TrackerCalibration.py","file_name":"TrackerCalibration.py","file_ext":"py","file_size_in_byte":14007,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"139424906","text":"#!/usr/bin/python3\n\"\"\"\nfetches https://intranet.hbtn.io/status\n\"\"\"\nimport urllib.request\nfrom sys import argv\nimport urllib.error\n\nif __name__ == \"__main__\":\n try:\n with urllib.request.urlopen(argv[1]) as response:\n content = response.read().decode('utf-8')\n print(content)\n except urllib.error.HTTPError as err:\n print(\"Error code: {}\".format(err.code))\n","sub_path":"0x11-python-network_1/3-error_code.py","file_name":"3-error_code.py","file_ext":"py","file_size_in_byte":393,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"134680147","text":"import sqlite3\n\ndef connect():\n connect = sqlite3.connect(\"books.db\")\n cursor = connect.cursor()\n cursor.execute(\"CREATE TABLE IF NOT EXISTS bookstore (id INTEGER PRIMARY KEY,\"\n \"title TEXT,\"\n \"author TEXT,\"\n \"year INTEGER,\"\n \"isbn INTEGER)\"\n )\n connect.commit()\n connect.close()\n\ndef insert(title,author,year,isbn):\n connect = sqlite3.connect(\"books.db\")\n cursor = connect.cursor()\n cursor.execute(\"INSERT INTO bookstore VALUES (NULL,?,?,?,?)\",(title, author, year, isbn))\n connect.commit()\n connect.close()\n\ndef view():\n connect = sqlite3.connect(\"books.db\")\n cursor = connect.cursor()\n cursor.execute(\"SELECT * FROM bookstore\")\n books = cursor.fetchall()\n connect.close()\n return books\n\ndef search(title=\"\", author=\"\", year=\"\", isbn=\"\"):\n connect = sqlite3.connect(\"books.db\")\n cursor = connect.cursor()\n cursor.execute(\"SELECT * FROM bookstore WHERE title=?\"\n \"OR author=?\"\n \"OR year=?\"\n \"OR isbn=?\", (title,author,year,isbn))\n books = cursor.fetchall()\n connect.close()\n return books\n\ndef delete(id):\n connect = sqlite3.connect(\"books.db\")\n cursor = connect.cursor()\n cursor.execute(\"DELETE FROM bookstore WHERE id=?\", (id,))\n connect.commit()\n connect.close()\n\ndef update(id,title,author,year,isbn):\n connect = sqlite3.connect(\"books.db\")\n cursor = connect.cursor()\n cursor.execute(\"UPDATE bookstore SET title=?, author=?, year=?, isbn=?\"\n \"WHERE id=?\", (title, author, year, isbn, id))\n connect.commit()\n connect.close()\n\ndef close():\n return True\n\n\n\nconnect()\n# insert(\"Holy Bible\", \"Joseph Smith\", 1823, 123456)\n# print(view())\n\n","sub_path":"back_end_script.py","file_name":"back_end_script.py","file_ext":"py","file_size_in_byte":1799,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"50752927","text":"#!/usr/bin/env python\n# license removed for brevity\n\nimport rospy\nimport actionlib\nfrom move_base_msgs.msg import MoveBaseAction, MoveBaseGoal\nimport speech_recognition as sr\nfrom subprocess import call\n\n\nr = sr.Recognizer()\n\n\ndef movebase_client():\n\n client = actionlib.SimpleActionClient('move_base',MoveBaseAction)\n client.wait_for_server()\n\n with sr.Microphone() as source:\n call([\"espeak\",\"-s140 -ven+18 -z\",\"Where Should I go ?\"])\n print(\"Where Should I go ?\")\n r.adjust_for_ambient_noise(source)\n audio = r.listen(source)\n #print(\"Sphinx thinks you said \" + r.recognize_sphinx(audio))\n data = r.recognize_google(audio)\n data = data.lower()\n print(\"Sphinx thinks you said \" + data)\n place = \"\"\n goal = MoveBaseGoal()\n goal.target_pose.header.frame_id = \"map\"\n goal.target_pose.header.stamp = rospy.Time.now()\n\n if 'kitchen' in data:\n call([\"espeak\",\"-s140 -ven+18 -z\",\"Going to kitchen\"])\n goal.target_pose.pose.position.x = 6.14083003998\n goal.target_pose.pose.position.y = -2.16255235672\n goal.target_pose.pose.orientation.w = 0.999742097682\n client.send_goal(goal) \n place=\"kitchen\" \n\n elif 'hall' in data:\n call([\"espeak\",\"-s140 -ven+18 -z\",\"Going to hall\"])\n goal.target_pose.pose.position.x = 0\n goal.target_pose.pose.position.y = 0\n goal.target_pose.pose.orientation.w = 0\n client.send_goal(goal)\n place=\"hall\"\n\n elif 'living' in data:\n call([\"espeak\",\"-s140 -ven+18 -z\",\"Going to living room\"])\n goal.target_pose.pose.position.x = -4.83513975143\n goal.target_pose.pose.position.y = 0.163211867213\n goal.target_pose.pose.orientation.w = 0.685605059046\n client.send_goal(goal)\n place=\"living room\"\n\n elif 'bed room' in data:\n call([\"espeak\",\"-s140 -ven+18 -z\",\"Going to bed room\"])\n goal.target_pose.pose.position.x = -5.12075853348\n goal.target_pose.pose.position.y = -5.67159795761\n goal.target_pose.pose.orientation.w = 0.743818342819\n client.send_goal(goal)\n place=\"bed room\"\n\n else:\n print(\"No Goal\")\n\n wait = client.wait_for_result()\n if not wait:\n rospy.logerr(\"Action server not available!\")\n rospy.signal_shutdown(\"Action server not available!\")\n else:\n return client.get_result(),place\n\nif __name__ == '__main__':\n try:\n rospy.init_node('movebase_client_py')\n while not rospy.is_shutdown():\n result,pl = movebase_client()\n if result:\n rospy.loginfo(\"Goal execution done!\")\n text=\"Reached to\" + pl\n call([\"espeak\",\"-s140 -ven+18 -z\",text])\n\n\n\n\n\n\n\n except rospy.ROSInterruptException:\n rospy.loginfo(\"Navigation test finished.\")\n","sub_path":"scripts/goal.py","file_name":"goal.py","file_ext":"py","file_size_in_byte":2833,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"376658185","text":"import os\nimport random\n\n# name(=id) of the skill, it must be unique and one word\nNAME='Joke'\nFULL_NAME=\"Joke\"\n\n#Should it appear in the mobile app?\nHIDDEN=False\n\n# optional description of the skill\nDESCRIPTION=''\n\nKEYWORDS = ['joke', 'funny']\n\nCONVERSATION=[\n\t{\n\t\t\"prompt\": \"\"\n\t}\n]\n\ndef before_conversation():\n f = open(os.path.join(os.path.dirname(os.path.realpath(__file__)), 'jokes.txt'), \"r\")\n jokes = []\n for x in f:\n jokes.append(x)\n joke = str(random.choice(jokes)).rstrip(\"\\n\")\n print(joke)\n return {\n \"joke\": joke\n }\n\ndef do(answers):\n return\n","sub_path":"IsaacREST/skills/scripts/joke.py","file_name":"joke.py","file_ext":"py","file_size_in_byte":583,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"607661673","text":"import itertools\nfrom collections import defaultdict\nimport matplotlib.pyplot as plt\nfrom config import *\nfrom sklearn import metrics\n\n\ndef get_object_features(data_frame):\n return data_frame.keys()[data_frame.dtypes.map(lambda x: x == 'object')]\n\n\ndef convert_attribute_to_int(data_set, attribute):\n data_set[attribute] = data_set[attribute].astype(\"category\")\n data_set[attribute] = data_set[attribute].cat.rename_categories(range(1, 1 + data_set[attribute].nunique())).astype(float)\n\n\ndef plot_feature(data_set, x):\n plt.figure()\n plt.title(x)\n plt.plot(data_set[x].values)\n plt.show(block=True)\n\n\ndef plot_feature_histogram(data_set, x):\n plt.figure()\n plt.title(x)\n plt.hist(data_set[x].dropna().values, bins='auto')\n plt.show(block=True)\n\n\n# scatter plot array\ndef plot_scatter_array(data_set, x, f):\n plt.figure()\n plt.title(f)\n plt.scatter(range(len(data_set)), data_set)\n plt.show(block=True)\n\n\n# scatter plot dataframe\ndef plot_scatter_dataframe(data_set, x):\n print(x)\n plt.figure()\n plt.title(x)\n plt.scatter(data_set[x].index, data_set[x].dropna().values)\n plt.show(block=True)\n\n\ndef print_missing_data(data):\n print(\"number of missing values: {}\".format(data.isnull().sum().values.sum()))\n print(\"number of incomplete rows: {}\".format(data.shape[0] - data.dropna().shape[0]))\n print('='*50)\n\n\ndef plot_label_and_feature(data):\n for feature in numerical_features:\n plt.xlabel(label)\n plt.ylabel(feature)\n plt.scatter(data[label], data[feature])\n plt.show()\n\n\ndef plot_feature_and_feature(data):\n for f in object_features_names[1:]:\n for feature in all_features_names[1:]:\n if f == feature:\n continue\n plt.xlabel(f)\n plt.ylabel(feature)\n plt.scatter(data[f], data[feature])\n plt.show()\n\n\ndef plot_feature_and_feature(data, f1, f2):\n plt.xlabel(f1)\n plt.ylabel(f2)\n plt.scatter(data[f1], data[f2])\n plt.show()\n\n\ndef get_label_to_feature_mapping():\n Looking_at_poles_results_dict = {}\n for i in range(1, 12):\n if i in [1, 9, 11]:\n Looking_at_poles_results_dict[i] = 1\n else:\n Looking_at_poles_results_dict[i] = -1\n Married_dict = {3: 1}\n Will_vote_only_large_party_dict = {}\n for i in range(1, 12):\n if i in [1, 9, 11]:\n Will_vote_only_large_party_dict[i] = 1\n elif i in [4, 5, 8]:\n Will_vote_only_large_party_dict[i] = 0\n else:\n Will_vote_only_large_party_dict[i] = -1\n result = {'Looking_at_poles_results': Looking_at_poles_results_dict,\n 'Married': Married_dict,\n 'Will_vote_only_large_party': Will_vote_only_large_party_dict}\n return result\n\n\ndef get_feature_to_feature_mapping():\n Most_Important_Issue_dict = {'Looking_at_poles_results': {4: -1, 6: -1, 7: -1},\n 'Will_vote_only_large_party': {4: 0., 6: 0., 7: 0.},\n 'Last_school_grades': {1: 100, 2: 90, 3: 60, 4: 40, 5: 80, 6: 30, 7: 50, 8: 70}}\n Looking_at_poles_results_dict = {'Will_vote_only_large_party': {1: 1.}}\n Will_vote_only_large_party_dict = {'Looking_at_poles_results': {-1: -1., 0: -1., 1: 1.}}\n Last_school_grades_dict = {'Most_Important_Issue': {100: 1, 90: 2, 60: 3, 40: 4, 80: 5, 30: 6, 50: 7, 70: 8},\n 'Looking_at_poles_results': {30: -1, 40: -1, 50: -1},\n 'Will_vote_only_large_party': {30: 0., 40: 0., 50: 0.}}\n Number_of_valued_Kneset_members_dict = {'Looking_at_poles_results': {5: -1, 6: -1, 7: -1},\n 'Last_school_grades': {16: 100}}\n result = {'Most_Important_Issue': Most_Important_Issue_dict,\n 'Looking_at_poles_results': Looking_at_poles_results_dict,\n 'Will_vote_only_large_party': Will_vote_only_large_party_dict,\n 'Last_school_grades': Last_school_grades_dict,\n \"Number_of_valued_Kneset_members\": Number_of_valued_Kneset_members_dict}\n return result\n\n\ndef get_feature_correlation(data, threshold):\n correlation_dict = defaultdict(list)\n for feature in data.columns:\n for other in data.columns:\n if other == feature:\n continue\n correlation = data[feature].corr(data[other], method='pearson')\n if abs(correlation) >= threshold:\n correlation_dict[feature].append(other)\n return correlation_dict\n\n\ndef get_feature_mi(data, threshold):\n correlation_dict = defaultdict(list)\n for feature in data.columns:\n for other in data.columns:\n if other == feature:\n continue\n mi = metrics.mutual_info_score(data[feature].values, data[other].values)\n if mi >= threshold:\n correlation_dict[feature].append(other)\n return correlation_dict\n\n\ndef find_linkage(data):\n for f1 in features_to_check_linkage[1:]:\n for f2 in features_to_check_linkage[1:]:\n if f1 == f2:\n continue\n for v in data[f1].dropna().unique():\n if data[data[f1] == v].dropna().nunique()[f2] == 1:\n print(\"{} {}\".format(f1, f2))\n break\n\n\ndef get_feature_list_from_mask(df, mask):\n return list(itertools.compress(df.columns.values, mask))\n\n\ndef get_features_mask(x, features):\n result = []\n for f in x.columns.values:\n if f in features:\n result.append(True)\n else:\n result.append(False)\n return result\n","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":5635,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"173791459","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n#\n# Copyright 2019 The FATE Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\nfrom federatedml.param.base_param import BaseParam\n\n\nclass DataIOParam(BaseParam):\n \"\"\"\n Define dataio parameters that used in federated ml.\n\n Parameters\n ----------\n input_format : {'dense', 'sparse', 'tag'}\n please have a look at this tutorial at \"DataIO\" section of federatedml/util/README.md.\n Formally,\n dense input format data should be set to \"dense\",\n svm-light input format data should be set to \"sparse\",\n tag or tag:value input format data should be set to \"tag\".\n delimitor : str\n the delimitor of data input, default: ','\n data_type : {'float64', 'float', 'int', 'int64', 'str', 'long'}\n the data type of data input\n exclusive_data_type : dict\n the key of dict is col_name, the value is data_type, use to specified special data type\n of some features.\n tag_with_value: bool\n use if input_format is 'tag', if tag_with_value is True,\n input column data format should be tag[delimitor]value, otherwise is tag only\n tag_value_delimitor: str\n use if input_format is 'tag' and 'tag_with_value' is True,\n delimitor of tag[delimitor]value column value.\n missing_fill : bool\n need to fill missing value or not, accepted only True/False, default: False\n default_value : None or object or list\n the value to replace missing value.\n if None, it will use default value define in federatedml/feature/imputer.py,\n if single object, will fill missing value with this object,\n if list, it's length should be the sample of input data' feature dimension,\n means that if some column happens to have missing values, it will replace it\n the value by element in the identical position of this list.\n missing_fill_method : {None, 'min', 'max', 'mean', 'designated'}\n the method to replace missing value\n missing_impute: None or list\n element of list can be any type, or auto generated if value is None, define which values to be consider as missing\n outlier_replace: bool\n need to replace outlier value or not, accepted only True/False, default: True\n outlier_replace_method : {None, 'min', 'max', 'mean', 'designated'}\n the method to replace missing value\n outlier_impute: None or list\n element of list can be any type, which values should be regard as missing value, default: None\n outlier_replace_value : None or object or list\n the value to replace outlier.\n if None, it will use default value define in federatedml/feature/imputer.py,\n if single object, will replace outlier with this object,\n if list, it's length should be the sample of input data' feature dimension,\n means that if some column happens to have outliers, it will replace it\n the value by element in the identical position of this list.\n with_label : bool\n True if input data consist of label, False otherwise. default: 'false'\n label_name : str\n column_name of the column where label locates, only use in dense-inputformat. default: 'y'\n label_type : {'int', 'int64', 'float', 'float64', 'long', 'str'}\n use when with_label is True.\n output_format : {'dense', 'sparse'}\n output format\n \"\"\"\n\n def __init__(self, input_format=\"dense\", delimitor=',', data_type='float64',\n exclusive_data_type=None,\n tag_with_value=False, tag_value_delimitor=\":\",\n missing_fill=False, default_value=0, missing_fill_method=None,\n missing_impute=None, outlier_replace=False, outlier_replace_method=None,\n outlier_impute=None, outlier_replace_value=0,\n with_label=False, label_name='y',\n label_type='int', output_format='dense', need_run=True):\n self.input_format = input_format\n self.delimitor = delimitor\n self.data_type = data_type\n self.exclusive_data_type = exclusive_data_type\n self.tag_with_value = tag_with_value\n self.tag_value_delimitor = tag_value_delimitor\n self.missing_fill = missing_fill\n self.default_value = default_value\n self.missing_fill_method = missing_fill_method\n self.missing_impute = missing_impute\n self.outlier_replace = outlier_replace\n self.outlier_replace_method = outlier_replace_method\n self.outlier_impute = outlier_impute\n self.outlier_replace_value = outlier_replace_value\n self.with_label = with_label\n self.label_name = label_name\n self.label_type = label_type\n self.output_format = output_format\n self.need_run = need_run\n\n def check(self):\n\n descr = \"dataio param's\"\n\n self.input_format = self.check_and_change_lower(self.input_format,\n [\"dense\", \"sparse\", \"tag\"],\n descr)\n\n self.output_format = self.check_and_change_lower(self.output_format,\n [\"dense\", \"sparse\"],\n descr)\n\n self.data_type = self.check_and_change_lower(self.data_type,\n [\"int\", \"int64\", \"float\", \"float64\", \"str\", \"long\"],\n descr)\n\n if type(self.missing_fill).__name__ != 'bool':\n raise ValueError(\"dataio param's missing_fill {} not supported\".format(self.missing_fill))\n\n if self.missing_fill_method is not None:\n self.missing_fill_method = self.check_and_change_lower(self.missing_fill_method,\n ['min', 'max', 'mean', 'designated'],\n descr)\n\n if self.outlier_replace_method is not None:\n self.outlier_replace_method = self.check_and_change_lower(self.outlier_replace_method,\n ['min', 'max', 'mean', 'designated'],\n descr)\n\n if type(self.with_label).__name__ != 'bool':\n raise ValueError(\"dataio param's with_label {} not supported\".format(self.with_label))\n\n if self.with_label:\n if not isinstance(self.label_name, str):\n raise ValueError(\"dataio param's label_name {} should be str\".format(self.label_name))\n\n self.label_type = self.check_and_change_lower(self.label_type,\n [\"int\", \"int64\", \"float\", \"float64\", \"str\", \"long\"],\n descr)\n\n if self.exclusive_data_type is not None and not isinstance(self.exclusive_data_type, dict):\n raise ValueError(\"exclusive_data_type is should be None or a dict\")\n\n return True\n","sub_path":"python/federatedml/param/dataio_param.py","file_name":"dataio_param.py","file_ext":"py","file_size_in_byte":7738,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"46376363","text":"import requests\nfrom model.input_data import *\nimport time\n\n# Тест использует файл paths.txt в папке *SecurOS\\Modules\\http_event_proxy\n\n\ndef test_send_request_get(search):\n response = requests.get(url=\"http://\" + slave_ip + \":\" + http_evgate_port + \"/event?param=123\")\n assert str(response.status_code) == \"200\"\n element = search.search_for_element(response, resp_param='param<{}>')\n assert element == \"123\"\n\n\ndef test_send_request_post_with_xml(search): # здесь проверяется полное значение data\n data = \"value1value2\"\n response = requests.post(url=\"http://\" + slave_ip + \":\" + http_evgate_port + \"/event\", data=data)\n assert str(response.status_code) == \"200\"\n element = search.search_for_element(response, resp_param='body<{}>,')\n assert data == element\n\n\ndef test_send_user_request_get_and_response(): # в тесте проводиться проверка на корректный запрос и не корректный параметр, респонс приходит, но там пусто (так и задумано).\n time.sleep(3)\n response = requests.get(url=\"http://\" + slave_ip + \":\" + http_evgate_port + \"/testreq?param=pam\")\n time.sleep(3)\n assert str(response.status_code) == \"200\"\n assert response.text == \"Response\"\n\n\ndef test_send_user_request_get_and_response_with_xml(search):\n response = requests.get(url=\"http://\" + slave_ip + \":\" + http_evgate_port + \"/test/xml?param=xml\")\n time.sleep(2)\n assert str(response.status_code) == \"200\"\n element = search.search_for_element(response, resp_param='{}')\n assert element == \"value\"\n\n\ndef test_send_user_request_post_and_response_with_json(search): # а здесь вместо полного значения (как в 1 тесте) проверяется конкретное значение\n data = \"value1value2\"\n response = requests.post(url=\"http://\" + slave_ip + \":\" + http_evgate_port + \"/test/json\", data=data)\n assert str(response.status_code) == \"200\"\n element = search.search_in_json(response, \"param\")\n assert element == \"value\"\n\n\n\n\n","sub_path":"test/test_http_event_gate.py","file_name":"test_http_event_gate.py","file_ext":"py","file_size_in_byte":2249,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"516337885","text":"from ImageEnlargeH import ImageEnlargeH\nfrom ImageEnlargeV import ImageEnlargeV\n\n#Esta funcion se encargar de alargar una imagen a un tamaño deseado. Como entrada tiene la imagen original y\n#la resolucion deseada. Como salida devuelve la imagen con la resolucion introducida.\n\ndef enlargeSC(image, final_resolution):\n row_final, col_final = final_resolution\n row_ini, col_ini = image.shape[0], image.shape[1]\n\n if (((row_ini - row_final) > 0) or ((col_ini - col_final) > 0)):\n print('Incorrect target resolution') #Comprobacion sobre las dimensiones. Deben ser mayores o iguales a las originales\n else:\n if ((row_ini - row_final) != 0): #Siempre y cuando se exija un alargamiento en dicha dimension\n resized_image, _ = ImageEnlargeH(image, row_final-row_ini) #Realiza el alargamiento mediante seams horizontales\n else: #Alargamiento vertical.\n resized_image = image\n \n if ((col_ini - col_final) != 0): #Siempre y cuando se exija un alargamiento en dicha dimension\n resized_image_target, _ = ImageEnlargeV(resized_image, col_final-col_ini) #Realiza el alargamiento mediante\n else: #seams verticales. Alargamiento horizontal.\n resized_image_target = resized_image\n\n return resized_image_target","sub_path":"enlargeSC.py","file_name":"enlargeSC.py","file_ext":"py","file_size_in_byte":1364,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"72441503","text":"from six.moves.urllib.request import urlopen, Request\nfrom six.moves.urllib.error import HTTPError\nfrom six.moves.urllib.parse import urlencode\n\n\nclass UrllibBackend(object):\n def request(self, url, data):\n if data:\n request = Request(url, urlencode(data).encode('ascii'))\n else:\n request = Request(url, None)\n try:\n response = urlopen(request)\n body = response.read()\n code = response.getcode()\n except HTTPError as e:\n code = e.code\n body = e.fp.read()\n return {'code': code, 'body': body, 'url': url}\n","sub_path":"captcha_solver/transport_backend/urllib_backend.py","file_name":"urllib_backend.py","file_ext":"py","file_size_in_byte":619,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"79869559","text":"from flask import Flask\napp = Flask(__name__)\n\nimport os\nimport cv2\nimport argparse\nfrom palettable import ColorPalette\n\n# Construct argument parser\nparser = argparse.ArgumentParser()\nparser.add_argument(\"-i\", \"--image\", type=str, required=True,\n help=\"Enter the filepath of the image you wish to \"\n \"be made palettable.\")\nparser.add_argument(\"-n\", \"--number\", type=int, default=5,\n help=\"Enter the number of colors to include in the palette.\")\nparser.add_argument(\"-p\", \"--position\", type=str, default='topRight',\n help=\"Where would you like to place the palette?\"\n \"Options: topRight, topLeft, bottomRight, bottomLeft\")\nparser.add_argument(\"-o\", \"--orientation\", type=str, default='vert',\n help=\"How would you like the palette oriented?\"\n \"Options: vert = vertical, horz = horizontal\")\nparser.add_argument(\"-s\", \"--scale\", type=float, default=0.3,\n help=\"The size of the color blocks in the palette, relative to the image size\")\nargs = vars(parser.parse_args())\n\n# Use image provided to incorporate the image color palette onto the image\ninput = args['image']\nnum = args['number']\npos = args['position']\norient = args['orientation']\nscale = args['scale']\n\noutput = os.path.join(os.path.expanduser('~'), \"Desktop/\")\nprint(\"Location of your palettable image:\", output)\nimage = cv2.imread(input)\npalettable = ColorPalette(image, n_sig=num, position=pos, orient=orient, size=scale)\npalettable.show_image_with_palette(output)\n","sub_path":"run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":1575,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"499884495","text":"'''\nAuthors: Katiana Kontolati, PhD Candidate, Johns Hopkins University\n Somdatta Goswami, Postdoctoral Researcher, Brown University\nTensorflow Version Required: TF1.15 \n'''\nimport numpy as np\nfrom matplotlib import pylab as plt\n\ninputs_test = np.loadtxt('./Output/target/f_test')\npred = np.loadtxt('./Output/target/u_pred')\ntrue = np.loadtxt('./Output/target/u_ref')\nnum_test = inputs_test.shape[0]\n\n# Load source test loss\ntest_loss_target = np.loadtxt('./Output/target/loss_test')\nepochs_target = np.loadtxt('./Output/target/epochs')\ntest_loss_source = np.loadtxt('./Output/source/loss_test')\nepochs_source = np.loadtxt('./Output/source/epochs')\n\nplt.rcParams.update({'font.size': 17})\nfig = plt.figure(constrained_layout=True, figsize=(7, 5))\ngs = fig.add_gridspec(1, 1)\nax = fig.add_subplot(gs[0])\nax.plot(epochs_source, test_loss_source, color='b', label='Testing Loss')\nax.set_yscale('log')\nax.set_ylabel('Loss')\nax.set_xlabel('Epochs')\nax.legend(loc='upper left')\nfig.savefig('./Output/source/loss_test_log.png')\n\n## Plotting both source and target loss\nfig = plt.figure(constrained_layout=True, figsize=(7, 5))\ngs = fig.add_gridspec(1, 1)\nax = fig.add_subplot(gs[0])\nax.plot(epochs_source, test_loss_source, color='b', label='source')\nax.plot(epochs_target[100:], test_loss_target[100:], color='r', label='target')\nax.set_ylabel('Loss')\nax.set_xlabel('Epochs')\nax.legend(loc='upper left')\nfig.savefig('./Output/target/loss_test_comparison.png')\n\n'''\nplt.rcParams.update({'font.size': 18})\nfig = plt.figure(figsize=(7, 6))\nepochs = train_loss.shape[0]\nx = np.linspace(1, epochs, epochs)\nplt.plot(x, train_loss, label='train loss')\nplt.yscale('log')\nplt.xlabel('Epochs')\nplt.ylabel('Loss')\nplt.legend()\nplt.tight_layout()\nplt.savefig('Output/train_loss.png', dpi=250)\n\nfig = plt.figure(figsize=(7, 6))\nplt.plot(x, test_loss, label='test loss')\nplt.yscale('log')\nplt.xlabel('Epochs')\nplt.ylabel('Loss')\nplt.legend()\nplt.tight_layout()\nplt.savefig('Output/test_loss.png', dpi=250)\n\nnx, ny = 28, 28\nx = np.linspace(0, 1, nx)\ny = np.linspace(0, 1, ny)\nxx, yy = np.meshgrid(x, y)\n\nindex = 0\ntot = int(nx*ny)\n\nsnapshots = 5\ntime = np.linspace(0,1,snapshots)\nprint(time)\nget = np.linspace(0, pred.shape[1], snapshots+1)\nget = [int(x) for x in get]\n\nplt.rcParams.update({'font.size': 12.5})\nth = 0\nfig, axs = plt.subplots(3, snapshots, figsize=(14.5,6), constrained_layout=True)\nplt.rcParams[\"axes.edgecolor\"] = \"black\"\nplt.rcParams[\"axes.linewidth\"] = 1\nfor col in range(snapshots):\n for row in range(3):\n ax = axs[row, col]\n if row == 0:\n ss1 = true[index, get[col]:get[col]+tot]\n pcm = ax.contourf(xx, yy, ss1.reshape(nx,ny), levels=np.linspace(np.min(ss1)-th, np.max(ss1)+th, 200), cmap='jet')\n cbar = plt.colorbar(pcm, ax=ax, format='%.1f', ticks=np.linspace(np.min(ss1)-th, np.max(ss1)+th , 5))\n ax.set_title(r'$t={}$'.format(time[col]))\n if row == 1:\n ss2 = pred[index, get[col]:get[col]+tot]\n pcm = ax.contourf(xx, yy, ss2.reshape(nx,ny), levels=np.linspace(np.min(ss1)-th, np.max(ss1)+th, 200), cmap='jet')\n cbar = plt.colorbar(pcm, ax=ax, format='%.1f', ticks=np.linspace(np.min(ss1)-th, np.max(ss1)+th , 5))\n if row == 2:\n errors = np.abs((pred - true)/true)\n ss = errors[index, get[col]:get[col]+tot]\n pcm = ax.contourf(xx, yy, ss.reshape(nx,ny), levels=200, cmap='jet')\n plt.colorbar(pcm, ax=ax, format='%.0e', ticks=np.linspace(np.min(ss), np.max(ss) , 5))\n\n if row == 2:\n ax.set_xlabel(r'$x$', fontsize=13)\n if col ==0 and row ==0:\n ax.set_ylabel('Reference \\n y', fontsize=13)\n if col == 0 and row==1:\n ax.set_ylabel('DeepONet \\n y', fontsize=13)\n if col == 0 and row==2:\n ax.set_ylabel('Error \\n y', fontsize=13)\n ax.locator_params(axis='y', nbins=3)\n ax.locator_params(axis='x', nbins=3)\nplt.savefig('Output/target/time_evolution_comparison.png', bbox_inches='tight', dpi=500)\n'''\n","sub_path":"TL1/postprocessing.py","file_name":"postprocessing.py","file_ext":"py","file_size_in_byte":4048,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"382676527","text":"from sqlalchemy import create_engine\nfrom sqlalchemy.orm import Session, scoped_session, sessionmaker\n\nfrom piecewise.config.settings import get_settings\n\nsettings = get_settings()\n\n\ndef get_session(url: str) -> Session:\n engine = create_engine(url)\n maker = scoped_session(\n sessionmaker(autocommit=False, autoflush=False, bind=engine))\n return maker\n\n\ndef get_database():\n db = get_session(settings.db_url)\n try:\n yield db\n finally:\n db.close()\n","sub_path":"backend/piecewise/db/session.py","file_name":"session.py","file_ext":"py","file_size_in_byte":486,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"32370583","text":"#!/usr/bin/env python3\n\n#\n# [download-discord-history.py]\n#\n# Processes Discord chat history from the Discord History Tracker and\n# compiles it into an easily-readable chat log, as well as a script to\n# download all attachments.\n#\n# Copyright (C) 2019, Liam Schumm\n#\n\nimport json\n\nout_lines = []\nurls = []\n\nwith open('dht.txt') as f:\n j = json.loads(f.read())\n\n print(json.dumps(j['data'], sort_keys=True, indent=4))\n\n messages = j['data']['337052742839435266']\n\n for message_id in sorted(messages.keys()):\n message = messages[message_id]\n \n contents = message['m'].replace('\\n', '\\n.... ')\n if 'a' in message:\n for attachment in message['a']:\n contents += ' [att(' + str(len(urls)) + ')]'\n urls.append(attachment['url'])\n\n out_lines.append(str(message['u']) + ': ' + contents)\n\nwith open('chat', 'w') as f:\n f.write('\\n'.join(out_lines))\n\ndownload_commands = []\nfor (i, url) in enumerate(urls):\n download_commands.append('curl '\n + url\n + ' > '\n + str(i)\n + '.'\n + url.split('/')[-1].split('.')[-1])\n \nwith open('download', 'w') as f:\n f.write('#!/usr/bin/env sh\\n' + '\\n'.join(download_commands))\n","sub_path":"download_discord_history.py","file_name":"download_discord_history.py","file_ext":"py","file_size_in_byte":1340,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"53811704","text":"import os\nimport shlex\nimport subprocess\nimport time\n\nfrom simtools.DataAccess.DataStore import DataStore\nfrom simtools.SimulationRunner.BaseSimulationRunner import BaseSimulationRunner\nfrom simtools.Utilities.General import init_logging, is_running\nlogger = init_logging(\"LocalRunner\")\nfrom COMPS.Data.Simulation import SimulationState\n\n\nclass LocalSimulationRunner(BaseSimulationRunner):\n \"\"\"\n Run one simulation.\n \"\"\"\n def __init__(self, simulation, experiment, thread_queue):\n super(LocalSimulationRunner, self).__init__(experiment)\n self.queue = thread_queue # used to limit the number of concurrently running simulations\n self.simulation = simulation\n self.sim_dir = self.simulation.get_path()\n\n if self.check_state() == SimulationState.Created:\n self.run()\n else:\n self.queue.get()\n if self.simulation.status not in (SimulationState.Failed, SimulationState.Succeeded, SimulationState.Canceled):\n self.monitor()\n\n def run(self):\n try:\n with open(os.path.join(self.sim_dir, \"StdOut.txt\"), \"w\") as out, open(os.path.join(self.sim_dir, \"StdErr.txt\"), \"w\") as err:\n # On windows we want to pass the command to popen as a string\n # On Unix, we want to pass it as a sequence\n # See: https://docs.python.org/2/library/subprocess.html#subprocess.Popen\n if os.name == \"nt\":\n command = self.experiment.command_line\n else:\n command = shlex.split(self.experiment.command_line)\n\n # Launch the command\n p = subprocess.Popen(command, cwd=self.sim_dir, shell=False, stdout=out, stderr=err)\n\n # We are now running\n self.simulation.pid = p.pid\n self.simulation.status = SimulationState.Running\n self.update_status()\n\n self.monitor()\n except Exception as e:\n print(\"Error encountered while running the simulation.\")\n print(e)\n finally:\n # Allow another different thread to run now that this one is done.\n self.queue.get()\n\n def monitor(self):\n \"\"\"\n Monitors the simulation process and update its status.\n \"\"\"\n sim_pid = self.simulation.pid\n\n while is_running(sim_pid, name_part=self.experiment.exe_name) and self.simulation.status != \"Cancelled\":\n logger.debug(\"monitor: waiting on pid: %s\" % sim_pid)\n self.simulation.message = self.last_status_line()\n self.update_status()\n time.sleep(self.MONITOR_SLEEP)\n\n logger.debug(\"monitor: done waiting on pid: %s\" % sim_pid)\n\n # When poll returns None, the process is done, test if succeeded or failed\n last_message = self.last_status_line()\n last_state = self.check_state()\n\n if \"Done\" in last_message or os.path.exists(os.path.join(self.sim_dir, 'trajectories.csv')):\n self.simulation.status = SimulationState.Succeeded\n else:\n # If we exited with a Canceled status, don't update to Failed\n if last_state != SimulationState.Canceled:\n self.simulation.status = SimulationState.Failed\n\n # Set the final simulation state\n logger.debug(\"monitor: Updating sim: %s with pid: %s to status: %s\" % (self.simulation.id, sim_pid, self.simulation.status.name))\n self.simulation.message = last_message\n self.simulation.pid = None\n self.update_status()\n\n def update_status(self):\n # For local sim, we save the object so we have the info we need\n DataStore.save_simulation(self.simulation)\n\n def last_status_line(self):\n \"\"\"\n Returns the last line of the status.txt file for the simulation.\n None if the file doesnt exist or is empty\n :return:\n \"\"\"\n status_path = os.path.join(self.sim_dir, 'status.txt')\n msg = None\n if os.path.exists(status_path) and os.stat(status_path).st_size != 0:\n with open(status_path, 'r') as status_file:\n msg = list(status_file)[-1]\n\n return msg.strip('\\n') if msg else \"\"\n\n def check_state(self):\n \"\"\"\n Update the simulation and check its state\n Returns: state of the simulation or None\n \"\"\"\n self.simulation = DataStore.get_simulation(self.simulation.id)\n return self.simulation.status\n\n","sub_path":"simtools/SimulationRunner/LocalRunner.py","file_name":"LocalRunner.py","file_ext":"py","file_size_in_byte":4491,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"199469044","text":"import datetime\nimport github\nimport requests\nimport textwrap\nimport time\nimport urllib\nimport user_prompt\n\ndef get_repo_names(self):\n if self.update_repo_names:\n question = textwrap.dedent(\"\"\"\n Should I collect names of new repos? If this is\n the first time it will take at least 5 days.\"\"\")\n ans = user_prompt.query_yes_no(question)\n if ans == True:\n while True:\n try:\n self.populate_repo()\n break\n except urllib.error.URLError as e:\n self.logger.error(e.reason)\n self.logger.info(\"Sleep for 10 minutes.\")\n time.sleep(600) # 10 mins\n self.logger.info(\"Trying again.\")\n pass\n\ndef populate_repo(self):\n \"\"\"\n See if there are new repos to add to the database. Only basic details are\n added; id, owner, name, description, is it a fork.\n \"\"\"\n \n self.logger.info(\" Populating repo table...\")\n \n # get connection\n self.open_con()\n self.logger.info(\" Opened database connection.\")\n \n # 'since' SQL\n select_sql = \"\"\"\n SELECT max(id)\n FROM repo_list;\n \"\"\"\n # start collecting repos\n while True:\n self.cur.execute(select_sql)\n since = self.cur.fetchone()[0]\n\n if since is None:\n since = github.GithubObject.NotSet\n msg = \" No records in repo table. Getting all...\"\n self.logger.info(msg)\n else:\n msg = \" Collecting repos with ID greater than %i...\"\\\n % (since)\n self.logger.info(msg)\n \n start_time = time.time()\n self.n = 0\n self.N = 0\n \n for rp in self.gh.get_repos(since=since):\n # try to save\n try:\n self.save_repo(rp)\n except:\n print(\"\\nError with repo: %s\\n\" % (rp._rawData['full_name']))\n raise\n \n # after 50k repos memory starts to get close to full, so break the\n # for loop\n if self.N == 50000:\n break\n \n self.con.commit()\n # results\n time_taken = time.time() - start_time\n msg = \" Processed %i repos in %.2fs.\" % (self.N, time_taken)\n self.logger.info(msg)\n\n # if tried to get repos and N is still 0, then there were no repos to\n # get so break the while loop, otherwise we should \"restart\" the for\n # loop\n if self.N == 0:\n break\n \n # goodbye\n self.close_con()\n self.logger.info(\" Closed database connection.\")\n\n\ndef save_repo(self, rp):\n \"\"\"\n Basic information for a repo is saved when scraped; id, name, full_name,\n description, fork, owner.\n \"\"\"\n \n data = rp._rawData\n \n # repo level\n keys = ['id', 'name', 'full_name', 'description', 'fork']\n dat = { key: data[key] for key in keys }\n \n # owner level\n try:\n dat['owner'] = data['owner']['login']\n except TypeError:\n self.logger.warning(\" Repo without an owner.\")\n pass\n\n # stats last checked\n dat['last_updated'] = datetime.datetime.fromtimestamp(time.time()) # Now\n \n self.insert(dat, \"repo_list\")\n","sub_path":"analysis/git_history/github_api/get_repo_names.py","file_name":"get_repo_names.py","file_ext":"py","file_size_in_byte":3337,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"233271056","text":"from unittest import TextTestResult, TextTestRunner, main, TestResult\n\n_COLOR = {'green': \"\\x1b[32;01m\",\n 'red': \"\\x1b[31;01m\",\n 'reset': \"\\x1b[0m\"\n }\n\n\ndef red_str(text):\n \"\"\"Return red text.\"\"\"\n global _COLOR\n return _COLOR['red'] + text + _COLOR['reset']\n\n\ndef green_str(text):\n \"\"\"Return green text.\"\"\"\n global _COLOR\n return _COLOR['green'] + text + _COLOR['reset']\n\n\nclass ColorTextTestResult(TextTestResult):\n \"\"\"Colored version.\"\"\"\n\n def addSuccess(self, test):\n if self.showAll:\n self.stream.writeln(green_str(\"Ok\\t\"))\n elif self.dots:\n self.stream.write(green_str('.'))\n TestResult.addSuccess(self, test)\n\n def addError(self, test, err):\n TestResult.addError(self, test, err)\n if self.showAll:\n self.stream.writeln(red_str(\"ERROR\\t\"))\n elif self.dots:\n self.stream.write(red_str('E'))\n\n def addFailure(self, test, err):\n TestResult.addFailure(self, test, err)\n if self.showAll:\n self.stream.writeln(red_str(\"FAIL\\t\"))\n elif self.dots:\n self.stream.write(red_str('F'))\n\n def printErrorList(self, flavour, errors):\n for test, err in errors:\n self.stream.writeln(self.separator1)\n self.stream.writeln(\"%s: %s\" % (red_str(flavour),\n self.getDescription(test)))\n self.stream.writeln(self.separator2)\n self.stream.writeln(\"%s\" % err)\n\n def _exc_info_to_string(self, err, test):\n return super()._exc_info_to_string(err, test)\n\n\nif __name__ == \"__main__\":\n runner = TextTestRunner\n runner.resultclass = ColorTextTestResult\n main(module=None, testRunner=runner)\n","sub_path":"tests/unittestcolor.py","file_name":"unittestcolor.py","file_ext":"py","file_size_in_byte":1765,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"167771189","text":"def calculateFibonacci(n):\n if n < 2:\n return n\n dp = [0, 1]\n for i in range(2, n + 1):\n dp.append(dp[i - 1] + dp[i - 2])\n return dp[n]\n\n\ndef main():\n print(\"7th Fibonacci is ---> \" + str(calculateFibonacci(7)))\n\nmain()\n","sub_path":"fibonacci/tabulation.py","file_name":"tabulation.py","file_ext":"py","file_size_in_byte":231,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"6"} +{"seq_id":"37677622","text":"from __future__ import unicode_literals\nimport erpnext.education.utils as utils\nimport frappe\nfrom datetime import date\n\nno_cache = 1\n\ndef get_context(context):\n\t# Load Query Parameters\n\ttry:\n\t\tprogram = frappe.form_dict['program']\n\t\tcontent = frappe.form_dict['content']\n\t\tcontent_type = frappe.form_dict['type']\n\t\tcourse = frappe.form_dict['course']\n\t\ttopic = frappe.form_dict['topic']\n\texcept KeyError:\n\t\tfrappe.local.flags.redirect_location = '/lms'\n\t\traise frappe.Redirect\n\n\n\t# Check if user has access to the content\n\thas_program_access = utils.allowed_program_access(program)\n\thas_content_access = allowed_content_access(program, content, content_type)\n\n\tif frappe.session.user == \"Guest\" or not has_program_access or not has_content_access:\n\t\tfrappe.local.flags.redirect_location = '/lms'\n\t\traise frappe.Redirect\n\n\n\t# Set context for content to be displayer\n\tcontext.content = frappe.get_doc(content_type, content).as_dict()\n\n\n\tif content_type == \"Quiz\":\n\t\tallowed_to_take_quiz = 1\n\t\tcontext.content.allowed_to_take_quiz = allowed_to_take_quiz\n\t\tif context.content.check_exam_permit == 1:\n\t\t\tcleared_for_examination = frappe.db.sql(\n\t\t\t\t\"\"\"select cleared_for_examination from `tabExam Students` where username=%s\"\"\", (frappe.session.user))\n\n\t\t\tif cleared_for_examination != ():\n\t\t\t\tallowed_to_take_quiz = cleared_for_examination[0][0]\n\n\t\t\tcontext.content.allowed_to_take_quiz = allowed_to_take_quiz\n\t\t\t# context.content.allowed_to_take_quiz = 0\n\n\n\tcontext.content.publish_date = context.content.publish_date if context.content.publish_date is not None else date.today()\n\tcontext.content_type = content_type\n\tcontext.program = program\n\tcontext.course = course\n\tcontext.topic = topic\n\tcontext.student_name = get_student(frappe.session.user)\n\ttopic = frappe.get_doc(\"Topic\", topic)\n\tcontent_list = [{'content_type':item.content_type, 'content':item.content} for item in topic.topic_content]\n\n\t# Set context for progress numbers\n\tcontext.position = content_list.index({'content': content, 'content_type': content_type})\n\tcontext.length = len(content_list)\n\n\t# Set context for navigation\n\tcontext.previous = get_previous_content(content_list, context.position)\n\tcontext.next = get_next_content(content_list, context.position)\n\tcontext.uploaded_files = []\n\tcontext.uploaded_files_s3 = \"\"\n\n\t# Get uploaded files\n\tactivity_name = context.content.name\n\tcontent_type = context.content.doctype\n\tuser = escape(frappe.session.user)\n\tactivity_name = escape(activity_name)\n\n\tif content_type == \"Article\":\n\n\t\twritten_activity_info = frappe.db.sql(f\"SELECT name,uploads,alternative_uploads from `tabWritten Activity` \"\n\t\t\t\t\t\t\t\t\t\t\t f\"WHERE activity LIKE '%{activity_name}%' \"\n\t\t\t\t\t\t\t\t\t\t\t f\"AND student='{user}'\", as_dict=1)\n\t\tsubmitted_files = []\n\t\tfor info in written_activity_info:\n\t\t\tsubmitted_files = frappe.db.sql(f\"SELECT file_name,file_url,creation FROM `tabFile` WHERE owner='{user}' \"\n\t\t\t\t\t\t\t\t\t\t\tf\"AND attached_to_name='{escape(info['name'])}'\"\n\t\t\t\t\t\t\t\t\t\t\tf\" AND attached_to_doctype='Written Activity'\", as_dict=1)\n\t\t\tcontext.uploaded_files_s3 = (info['uploads'] if info['uploads'] else \"\") + (info['alternative_uploads'] if info['alternative_uploads'] else \"\")\n\t\tcontext.uploaded_files = submitted_files\n\n\n\telif content_type == \"Video\":\n\t\twritten_activity_info = frappe.db.sql(f\"SELECT name, uploads,alternative_uploads from `tabWritten Activity` \"\n\t\t\t\t\t\t\t\t\t\t\t f\"WHERE video LIKE '%{activity_name}%' \"\n\t\t\t\t\t\t\t\t\t\t\t f\"AND student='{user}'\", as_dict=1)\n\t\tsubmitted_files = []\n\t\tfor info in written_activity_info:\n\t\t\tsubmitted_files = frappe.db.sql(f\"SELECT file_name,file_url,creation FROM `tabFile` WHERE owner='{user}' \"\n\t\t\t\t\t\t\t\t\t\t\tf\"AND attached_to_name='{escape(info['name'])}'\"\n\t\t\t\t\t\t\t\t\t\t\tf\" AND attached_to_doctype='Written Activity'\", as_dict=1)\n\t\t\tcontext.uploaded_files_s3 = (info['uploads'] if info['uploads'] else \"\") + (info['alternative_uploads'] if info['alternative_uploads'] else \"\")\n\n\t\tcontext.uploaded_files = submitted_files\n\telse:\n\t\tcontext.uploaded_files = []\n\ndef get_student(student_email):\n\tstudent_id = frappe.get_all(\"Student\", {\"student_email_id\": student_email}, [\"title\"])\n\tif student_id:\n\t\ttitle = student_id[0].title\n\t\treturn title\n\telse:\n\t\treturn \"\"\n\ndef escape(text):\n\tif text:\n\t\treturn text.replace(\"'\",\"\\\\'\")\n\treturn text\n\ndef get_next_content(content_list, current_index):\n\ttry:\n\t\treturn content_list[current_index + 1]\n\texcept IndexError:\n\t\treturn None\n\ndef get_previous_content(content_list, current_index):\n\tif current_index == 0:\n\t\treturn None\n\telse:\n\t\treturn content_list[current_index - 1]\n\ndef allowed_content_access(program, content, content_type):\n\tcontents_of_program = frappe.db.sql(\"\"\"select `tabTopic Content`.content, `tabTopic Content`.content_type\n\tfrom `tabCourse Topic`,\n\t\t `tabProgram Course`,\n\t\t `tabTopic Content`\n\twhere `tabCourse Topic`.parent = `tabProgram Course`.course\n\t\t\tand `tabTopic Content`.parent = `tabCourse Topic`.topic\n\t\t\tand `tabProgram Course`.parent = %(program)s\"\"\", {'program': program})\n\n\treturn (content, content_type) in contents_of_program","sub_path":"lms_api/silid/lms/content.py","file_name":"content.py","file_ext":"py","file_size_in_byte":5022,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"6"} +{"seq_id":"630569855","text":"from typing import List\nfrom itertools import combinations\n\n\nclass Solution:\n def subsets(self, nums: List[int]) -> List[List[int]]:\n ans = [[], nums]\n for i in range(1, len(nums)):\n ans.extend([list(a) for a in combinations(nums, i)])\n return ans\n\n\nif __name__ == '__main__':\n S = Solution()\n ans = S.subsets([1, 2, 3])\n print(ans)","sub_path":"cxy/NO08.04/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":376,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"6"} +{"seq_id":"640471453","text":"def sum_digits(n,sum_d):\n for i in range(0,len(n)):\n sum_d = sum_d + int(n[i])\n if sum_d < 10:\n return sum_d\n if sum_d >= 10:\n return sum_digits(str(sum_d),0)\nif __name__ == \"__main__\":\n while True:\n try:\n n = input()\n if n == \"0\":\n break\n g = sum_digits(n,0)\n print(g)\n except(EOFError):\n break\n\n","sub_path":"11332.py","file_name":"11332.py","file_ext":"py","file_size_in_byte":413,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"73978060","text":"from django.conf.urls import url\nfrom . import views\n\napp_name = 'liga_social'\nurlpatterns = [\n url(r'^$', views.indexView, name='index'),\n url(r'^torneos/$', views.TorneoListView.as_view(), name='torneos'),\n url(r'^torneos/(?P[0-9]+)/$', views.TorneoDetailView.as_view(), name='torneo'),\n url(r'^torneos/(?P[0-9]+)/jornadas/$', views.JornadaListView.as_view(), name='jornadas'),\n url(r'^torneos/(?P[0-9]+)/jornadas/(?P[0-9]+)/$', views.PartidoDetailView.as_view(), name='partido'),\n url(r'^torneos/(?P[0-9]+)/jornadas/(?P[0-9]+)/(?P[0-9]+)/$', views.juegoFormView, name='juegoFormView'),\n url(r'^equipos/$', views.EquipoListView.as_view(), name='equipos'),\n url(r'^equipos/(?P[0-9]+)/$', views.EquipoDetailView.as_view(), name='equipo'),\n url(r'^equipos/(?P[0-9]+)/(?P[0-9]+)/$', views.JugadorDetailView.as_view(), name='jugador'),\n]","sub_path":"liga_social/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":935,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"207226657","text":"import argparse\nimport os\nimport sys\nimport json\nimport six\nimport math\nimport csv \n\nfrom logger import log\nfrom logger import err_log\n\nfrom google.cloud import language\nfrom google.cloud.language import enums\nfrom google.cloud.language import types\n\n# entity types from enums.Entity.Type\nentity_type = ('UNKNOWN', 'PERSON', 'LOCATION', 'ORGANIZATION',\n 'EVENT', 'WORK_OF_ART', 'CONSUMER_GOOD', 'OTHER')\n\ndef entities_text(text):\n \"\"\"Detects entities in the text.\"\"\"\n\n client = language.LanguageServiceClient()\n\n if isinstance(text, six.binary_type):\n text = text.decode('utf-8')\n\n # Instantiates a plain text document.\n document = types.Document(\n content=text,\n type=enums.Document.Type.PLAIN_TEXT)\n\n # Detects entities in the document. You can also analyze HTML with:\n # document.type == enums.Document.Type.HTML\n entities = client.analyze_entities(document).entities\n\n \"\"\" \n for entity in entities:\n print('=' * 20)\n print(u'{:<16}: {}'.format('name', entity.name))\n print(u'{:<16}: {}'.format('type', entity_type[entity.type]))\n print(u'{:<16}: {}'.format('metadata', str(list(entity.metadata.iterkeys()))))\n print(u'{:<16}: {}'.format('salience', entity.salience))\n print(u'{:<16}: {}'.format('wikipedia_url', entity.metadata.get('wikipedia_url', '-').encode('ascii', 'ignore')))\n print(u'{:<16}: {}'.format('mid', entity.metadata.get('mid', '-').encode('ascii', 'ignore')))\n \"\"\"\n\n return entities\n\n# If __main__, lookat every article in the /articledata directory and make sure there is a corresponding\n# file in the /entityanalysis directory\nif __name__ == \"__main__\":\n total_words_used = 0\n current_article_id = 0\n current_article_data = \"articledata/{0}.txt\".format(current_article_id)\n current_entity_data = \"entityanalysis/{0}.csv\".format(current_article_id)\n while os.path.isfile(current_article_data):\n if os.path.isfile(current_entity_data):\n current_article_id = current_article_id + 1\n current_article_data = \"articledata/{0}.txt\".format(current_article_id)\n current_entity_data = \"entityanalysis/{0}.csv\".format(current_article_id)\n continue\n\n log(\"Getting article data from: {0}\".format(current_article_data))\n with open(current_article_data, 'r') as artdata:\n next(artdata)\n article_lines = []\n for line in artdata:\n article_lines.append(line)\n article = reduce(lambda x, y: x + \"\\n\" + y, article_lines)\n entities = entities_text(article)\n log(\"Article is {0} characters long.\".format(len(article)))\n total_words_used += math.ceil(len(article) / 1000.0) * 1000 # Round to the nearest 1000\n\n with open(current_entity_data, 'wb') as entdata:\n writer = csv.writer(entdata, delimiter=' ', lineterminator='\\n', quotechar='|', quoting=csv.QUOTE_ALL)\n for entity in entities:\n row = [\n entity.name,\n entity_type[entity.type],\n entity.salience,\n entity.metadata.get('wikipedia_url', '-').encode('ascii', 'ignore'),\n entity.metadata.get('mid', '-').encode('ascii', 'ignore')\n ]\n\n for metakey in entity.metadata.iterkeys():\n if metakey != \"wikipedia_url\" and metakey != \"mid\":\n row.append(entity.metadata.get(metakey, '-').encode('ascii', 'ignore'))\n \n writer.writerow(row)\n\n # Go to the next article even if the with() fails\n current_article_id = current_article_id + 1\n current_article_data = \"articledata/{0}.txt\".format(current_article_id)\n current_entity_data = \"entityanalysis/{0}.csv\".format(current_article_id)\n \n\n sys.exit(0)","sub_path":"entity_analysis.py","file_name":"entity_analysis.py","file_ext":"py","file_size_in_byte":3981,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"573246004","text":"\"\"\"\nDownload any resources/packages used by machine learning packages here.\nOther resources can also be downloaded.\nDefine a new function for a group of similar resources.\n\"\"\"\n\nimport nltk\n\ndef download_nltk_packages():\n\t\"\"\"Downloads packages used by nltk (http://www.nltk.org/data.html).\n\tPuts the downloaded files in $HOME/nltk_data/ directory [This location\n\tvaries by operating systems - check the below link]:\n\thttp://www.nltk.org/data.html#command-line-installation].\n\t\"\"\"\n\t# Define the packages to be downloaded here.\n\tpackages = [\n\t\t'stopwords',\n\t\t'punkt',\n\t\t'averaged_perceptron_tagger'\n\t]\n\n\tprint('START DOWNLOADING RESOURCES...')\n\tprint('NOTE: May take a few minutes if connection is slow.')\n\tfor package in packages:\n\t\tprint('Downloading ', package, '...')\n\t\tnltk.download(package)\n\t\tprint('... Done downloading ', package)\n\t\tprint('----------------------------------------')\n\nif __name__ == '__main__':\n\tdownload_nltk_packages()\n","sub_path":"install_resources.py","file_name":"install_resources.py","file_ext":"py","file_size_in_byte":942,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"267341354","text":"holidays_per_year = int(input())\n\nplay_time_mins_yearly = 30000\nwork_days_play_mins = 63\nholidays_play_mins = 127\n\ntotal_playtime = holidays_per_year * holidays_play_mins + (365 - holidays_per_year)*work_days_play_mins\n\nif total_playtime > play_time_mins_yearly:\n difference = total_playtime - play_time_mins_yearly\n diff_hours = difference // 60\n diff_mins = difference % 60\n print(\"Tom will run away\")\n print(f\"{diff_hours} hours and {diff_mins} minutes more for play\")\nelse:\n difference = play_time_mins_yearly - total_playtime\n diff_hours = difference // 60\n diff_mins = difference % 60\n print(\"Tom sleeps well\")\n print(f\"{diff_hours} hours and {diff_mins} minutes less for play\")\n","sub_path":"Conditional-Statements---More-Exercises/02. Sleepy Tom Cat.py","file_name":"02. Sleepy Tom Cat.py","file_ext":"py","file_size_in_byte":715,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"43260737","text":"from .utils import *\n\ndef standardGlobalAlignment(textA, textB, match, mismatch, gap):\n sizeA = len(textA) + 1\n sizeB = len(textB) + 1\n largestNumber = \"\"\n matrix = [[ [] for j in range(sizeB)] for i in range(sizeA)]\n matrix[0][0].append(0)\n for i in range(1, sizeA):\n gapValue = i * gap\n strGapValue = str(gapValue)\n if len(strGapValue) > len(largestNumber):\n largestNumber = strGapValue\n matrix[i][0].append(gapValue)\n matrix[i][0].append(\"U\")\n for j in range(1, sizeB):\n gapValue = j * gap\n if len(strGapValue) > len(largestNumber):\n largestNumber = strGapValue\n matrix[0][j].append(gapValue)\n matrix[0][j].append(\"L\")\n \n #necessary for make the table looks better, it can also have a minus\n\n for i in range(sizeA):\n for j in range(sizeB):\n if(i > 0 and j > 0):\n upGap = matrix[i-1][j][0] + gap\n leftGap = matrix[i][j-1][0] + gap\n comparisonValue = comparison(textA[i-1],\n textB[j-1], match, mismatch, matrix[i-1][j-1][0])\n maxValue = max(upGap, leftGap, comparisonValue)\n matrix[i][j].append(maxValue)\n \n maxValueString = str(maxValue)\n if len(maxValueString) > len(largestNumber):\n largestNumber = maxValueString\n\n if(upGap == maxValue):\n matrix[i][j].append(\"U\")\n if(leftGap == maxValue):\n matrix[i][j].append(\"L\")\n if(comparisonValue == maxValue):\n matrix[i][j].append(\"D\")\n \n score = matrix[sizeA - 1][sizeB - 1][0]\n alignment = getGlobalAlignments(textA, textB, matrix)\n result = []\n result.append(score)\n result.append(alignment)\n return result\n\ndef getGlobalAlignments(textA, textB, matrix):\n resultA = \"\"\n resultB = \"\"\n\n i = len(textA)\n j = len(textB)\n\n while i > 0 or j > 0 and len(matrix[i][j]) > 1:\n if matrix[i][j][1] == \"D\":\n resultA = textA[i-1] + resultA\n resultB = textB[j-1] + resultB\n i = i - 1\n j = j - 1\n elif matrix[i][j][1] == \"U\":\n resultA = textA[i-1] + resultA\n resultB = \"-\" + resultB\n i = i - 1\n elif matrix[i][j][1] == \"L\":\n resultA = \"-\" + resultA\n resultB = textB[j-1] + resultB\n j = j - 1\n \n #I forgot this in the last project\n \n \n return resultA + '\\n' + resultB\n","sub_path":"BMC_Proyecto_2_Metabolic_Pathways-master/Utils/global_alignment.py","file_name":"global_alignment.py","file_ext":"py","file_size_in_byte":2574,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"558682986","text":"import jsonpickle\n#import json\nimport simplejson as json\n\nfrom urllib.request import urlopen\nfrom bs4 import BeautifulSoup\nimport re\n\nfrom selenium import webdriver\nfrom selenium.webdriver.chrome import service\n\n\n\ndef get_pages_count(cate_num):\n #claculate pages count function\n attraction = \"job_types[]=\" + str(cate_num) + \"&jt[]=\" + str(cate_num) #IT unix --> project manager cate_num = 301\n #attraction = \"job_types[]=301&jt[]=301\" #IT unix --> project manager\n base_url = \"https://www.daijob.com/en/jobs/search_result?\"\n base_url_com = \"https://www.daijob.com\"\n page_num = \"&page=1\" #predefined as first page here as we need to get number of pages only\n sort_by = \"&sort_order=3\" #by updated date\n site_url = base_url + attraction + sort_by + str(page_num)\n \n #for testing, comment it when live ### hatm Wasfy\n \n #IT (PC, Web, Unix) IT (Mainframe) IT (Hardware/Network) IT (Embedded Software, Control Systems) IT (Other)\n site_url = \"https://www.daijob.com/en/jobs/search_result?account_types[]=1&job_types[]=300&job_types[]=301&job_types[]=302&job_types[]=303&job_types[]=304&job_types[]=305&job_types[]=306&job_types[]=307&job_types[]=400&job_types[]=401&job_types[]=402&job_types[]=403&job_types[]=404&job_types[]=405&job_types[]=500&job_types[]=501&job_types[]=502&job_types[]=503&job_types[]=504&job_types[]=505&job_types[]=506&job_types[]=507&job_types[]=4000&job_types[]=4001&job_types[]=4002&job_types[]=4003&job_types[]=600&job_types[]=601&job_types[]=603&job_types[]=604&job_types[]=605&job_types[]=612&job_types[]=606&job_types[]=607&job_types[]=608&job_types[]=609&job_types[]=611&job_types[]=610&jt[]=400&jt[]=500&jt[]=4000&jt[]=600&job_search_form_hidden=1&sort_order=3\" + str(page_num)\n\n\n ########################################\n\n #with page number: https://www.daijob.com/en/jobs/search_result?page=2&job_types[]=301&jt[]=301\n #site_url = \"http://goto.nagasaki-tabinet.com/spot/?page=1&list_type=row&sort_type=access&cate_m=2\"\n # = \"https://www.daijob.com/en/jobs/search_result?job_types[]=301&jt[]=301&page=2\"\n print(\"site_url is: \", site_url)\n #site_url = \"http://goto.nagasaki-tabinet.com/spot/?page=1&?latitude=&longitude=&list_type=row&sort_type=access&keyword=&cate_m=1\"\n\n #########\n # selenium\n ###############################################\n driver = webdriver.Opera(executable_path='/home/wasfy/python_progs/crawl_jobs/operadriver_linux64/operadriver')\n driver.get(site_url)\n print(\"Page Title is : %s\" %driver.title)\n\n ###############################################\n\n\n #####read = urlopen(site_url).read()\n read = driver.page_source\n #print (\" Title Of the Site Is : \" + title)\n\n #read = urlopen(site_url).read()\n #print (\" Title Of the Site Is : \" + title)\n soup = BeautifulSoup(read,\"html.parser\",from_encoding=\"UTF-8\")\n\n #soup = BeautifulSoup(read, 'html.parser')\n ####print (soup.title.get_text()) ## Example For Title\n #

12

\n mydivs_class_is_count = soup.find_all(\"div\", class_=\"search_sort clearfix mb30\")\n p_tags = mydivs_class_is_count[0].find_all(\"p\")\n \n #print(\"p_tags is: \", p_tags)\n span_tags = p_tags[0].find_all(\"span\")\n \n results_count = span_tags[0].text #each page takes 15 result as fixed system\n\n\n print(\"Results count is: \", results_count)\n\n #number of pages = (results_count/15)\n\n #devide by 15 and check if there is reminder then pages_number = results_count//15 +1, if not then results_count//15 \n\n if int(results_count) % 15 == 0: #means no reminder\n pages_count = int(results_count)//15\n else: #means any reminder\n pages_count = (int(results_count)//15) + 1\n\n print(\"Pages number is:\", pages_count)\n return pages_count, results_count\n\n\n\n#page_num = 1\n#while page_num <= pages_count:\n# print(\"Page number: \", page_num)\n# page_num +=1\n\n\n\n\n\ndef get_scrape_url(page_num, cate_num):\n\n #print (url)\n #return\n #attraction = \"job_types[]=301&jt[]=301\" #IT unix --> project manager\n attraction = \"job_types[]=\" + str(cate_num) + \"&jt[]=\" + str(cate_num) #IT unix --> project manager cate_num = 301\n base_url = \"https://www.daijob.com/en/jobs/search_result?\"\n base_url_com = \"https://www.daijob.com\"\n page_number = \"&page=\" + str(page_num)\n sort_by = \"&sort_order=3\" #by updated date\n account_type = \"&account_types[]=1\" #means we need only direct employer company not 3rd party rec company\n site_url = base_url + attraction + sort_by + account_type + str(page_number)\n \n #for testing, comment it when live ### hatm Wasfy\n\n #IT (PC, Web, Unix) IT (Mainframe) IT (Hardware/Network) IT (Embedded Software, Control Systems) IT (Other)\n ########################################\n site_url = \"https://www.daijob.com/en/jobs/search_result?account_types[]=1&job_types[]=300&job_types[]=301&job_types[]=302&job_types[]=303&job_types[]=304&job_types[]=305&job_types[]=306&job_types[]=307&job_types[]=400&job_types[]=401&job_types[]=402&job_types[]=403&job_types[]=404&job_types[]=405&job_types[]=500&job_types[]=501&job_types[]=502&job_types[]=503&job_types[]=504&job_types[]=505&job_types[]=506&job_types[]=507&job_types[]=4000&job_types[]=4001&job_types[]=4002&job_types[]=4003&job_types[]=600&job_types[]=601&job_types[]=603&job_types[]=604&job_types[]=605&job_types[]=612&job_types[]=606&job_types[]=607&job_types[]=608&job_types[]=609&job_types[]=611&job_types[]=610&jt[]=400&jt[]=500&jt[]=4000&jt[]=600&job_search_form_hidden=1&sort_order=3\" + str(page_number)\n\n\n #with page number: https://www.daijob.com/en/jobs/search_result?page=2&job_types[]=301&jt[]=301\n #site_url = \"http://goto.nagasaki-tabinet.com/spot/?page=1&list_type=row&sort_type=access&cate_m=2\"\n # = \"https://www.daijob.com/en/jobs/search_result?job_types[]=301&jt[]=301&page=2\"\n print(\"site_url is: \", site_url)\n #site_url = \"http://goto.nagasaki-tabinet.com/spot/?page=1&?latitude=&longitude=&list_type=row&sort_type=access&keyword=&cate_m=1\"\n #########\n # selenium\n ###############################################\n driver = webdriver.Opera(executable_path='/home/wasfy/python_progs/crawl_jobs/operadriver_linux64/operadriver')\n driver.get(site_url)\n print(\"Page Title is : %s\" %driver.title)\n\n ###############################################\n\n\n #####read = urlopen(site_url).read()\n read = driver.page_source\n #print (\" Title Of the Site Is : \" + title)\n\n #soup = BeautifulSoup(open(html_path, 'r'),\"html.parser\",from_encoding=\"iso-8859-1\")\n #soup = BeautifulSoup(read, 'html.parser')\n soup = BeautifulSoup(read,\"html.parser\",from_encoding=\"UTF-8\")\n #print (soup.title.get_text()) ## Example For Title\n ###->### print(\"all is: \\n\", soup)\n\n #scrape_url(\"hello\")\n \n '''\n place_name_list = []\n place_image_url_list = []\n place_name_t_list = []\n place_url_list = []\n place_short_desc_list = []\n place_long_desc_list = []\n '''\n\n #for jobs\n job_url_list = []\n job_date_list = []\n job_title_list = []\n job_company_list = []\n job_company_logo_list = []\n\n mydivs0 = soup.find_all(\"div\", class_=\"jobs_box_header_title mb16\")\n for div in mydivs0:\n ###print (div)\n #print(div.text)\n #print(div.contents)\n\n #main_image = div.find('div', attrs={'class': 'main_image'})\n main_image = div\n\n ##-->print(main_image.get_text())\n a_tags = main_image.find_all(\"a\")\n\n #for tag in a_tags:\n #print(tag)\n #img_tags = a_tags[0].find_all(\"img\")\n job_company = a_tags[0].text#get('href')\n #for img_tag in img_tags:\n # print(img_taga)\n #printing alternate text\n print(\"---------------------------------------------------------------------\")\n\n job_company_list.append(job_company) #\n print(\"job company: \", job_company)\n print(\"---------------------------------------------------------------------\")\n\n\n\n # for col_1 div, that has image url and name\n mydivs = soup.find_all(\"div\", class_=\"jobs_box_logo_wrap\")\n for div in mydivs: \n ###print (div)\n #print(div.text)\n #print(div.contents)\n \n #main_image = div.find('div', attrs={'class': 'main_image'})\n main_image = div\n\n ##-->print(main_image.get_text())\n a_tags = main_image.find_all(\"a\")\n \n #for tag in a_tags:\n #print(tag)\n #img_tags = a_tags[0].find_all(\"img\")\n place_image_detail_url = a_tags[0].get('href')\n #for img_tag in img_tags:\n # print(img_taga)\n #printing alternate text\n print(\"---------------------------------------------------------------------\")\n #place_name = img_tags[0]['alt']\n #place_name_list.append(place_name)\n #print(\"image alt (place_name): \", place_name)\n #printing image source\n #place_image_url = base_url + img_tags[0]['src']\n\n job_url = base_url_com + place_image_detail_url #acting as job adv url\n\n job_url_list.append(job_url) #acting as job adv url full one\n print(\"job url: \", job_url)\n print(\"---------------------------------------------------------------------\")\n\n\n img_tags = main_image.find_all(\"img\")\n job_company = img_tags[0].get('alt')\n job_company_logo = img_tags[0].get('src')\n\n job_company_list.append(job_company)\n job_company_logo_list.append(job_company_logo)\n\n \n # for col_2 div, that has place describtion, place url and name\n #mydivs2 = soup.find_all(\"div\", class_=\"jobs_table02 table01\")\n mydivs2 = soup.find_all(\"div\", class_=\"jobs_box_content\")\n\n #jobs_box_content\n print(\"+++++++++++++++++++\")\n #print(soup)\n for div in mydivs2:\n #print (div)\n ##print(div.text)\n #print(div.contents)\n\n #main_image = div.find('div', attrs={'class': 'title'})\n ##-->print(main_image.get_text())\n p_tags = div.find_all(\"p\", class_=\"ta_right fc_gray02\")\n #print(a_tags)\n span_tags = p_tags[0].find_all(\"span\")\n job_date = span_tags[0].text \n\n\n\n print(\"+---------------------------------------------------------------------+\")\n ###job_title = p_tags[0].text \n ###job_title_list.append(job_title)\n #print(\"job title: \", job_title)\n\n ####### ---> get updated date job_date\n #span_tags = p_tags[1].find_all(\"span\")\n\n #job_date = span_tags[0].text # job date\n\n \n #place_url = base_url + a_tags[0]['href']\n #place_url_list.append(place_url)\n print(\"job date: \", job_date)\n #print(\"+---------------------------------------------------------------------+\")\n \n #p_tags = div.find_all(\"p\")\n\n #place_short_desc = p_tags[0].text #short\n\n #div.find_all(\"p\", class_=(\"jobs_table02 table01\")\n job_date_list.append(job_date)\n\n #place_long_desc = p_tags[1].text #long\n #place_long_desc_list.append(place_long_desc)\n\n #print(\"short description: \", place_short_desc)\n #print(\"long description: \", place_long_desc)\n #print(\"++++++++++++++++++++++++++++++++++++++++++++\")\n print(\"+---------------------------------------------------------------------+\")\n\n mydivs3 = soup.find_all(\"div\", class_=\"jobs_box_header_position mb16\")\n\n #jobs_box_content\n print(\"+++++++++++++++++++\")\n #print(soup)\n for div in mydivs3:\n #print (div)\n ##print(div.text)\n #print(div.contents)\n\n #main_image = div.find('div', attrs={'class': 'title'})\n ##-->print(main_image.get_text())\n a_tags = div.find_all(\"a\")\n #print(a_tags)\n #span_tags = p_tags[0].find_all(\"span\")\n job_title = a_tags[0].text.rsplit(' ', 1)[0] \n job_title_list.append(job_title)\n\n\n\n print(\"+---------------------------------------------------------------------+\")\n ###job_title = p_tags[0].text \n ###job_title_list.append(job_title)\n print(\"job title: \", job_title)\n\n ####### ---> get updated date job_date\n #span_tags = p_tags[1].find_all(\"span\")\n\n #job_date = span_tags[0].text # job date\n\n\n #place_url = base_url + a_tags[0]['href']\n #place_url_list.append(place_url)\n #print(\"job date: \", job_date)\n\n\n\n return job_url_list, job_date_list, job_title_list, job_company_list, job_company_logo_list\n\n #place_name_t_list, place_image_url_list, place_url_list, place_short_desc_list, place_long_desc_list\n\n\n\ndef get_scrape_cate(pages_count, cate_num):\n #get_scrape_url(page_num, cate_num)\n '''\n place_name_t_list = []\n place_image_url_list = []\n place_url_list = []\n place_short_desc_list = []\n place_long_desc_list = []\n '''\n\n job_url_list = []\n job_date_list = []\n job_title_list = []\n job_company_list = []\n job_company_logo_list = []\n \n\n if pages_count > 1:\n page_num = 1\n while page_num <= pages_count:\n print(\"@@@@@@@@@@@@@@@@@@@@@@@@\")\n print(\"@Dealing with Page #\", str(page_num))\n print(\"@@@@@@@@@@@@@@@@@@@@@@@@\")\n job_url_listi, job_date_listi, job_title_listi, job_company_listi, job_company_logo_listi = get_scrape_url(str(page_num), str(cate_num))\n\n job_url_list.extend(job_url_listi)\n job_date_list.extend(job_date_listi)\n job_title_list.extend(job_title_listi)\n job_company_list.extend(job_company_listi)\n job_company_logo_list.extend(job_company_logo_listi)\n\n '''\n place_name_t_list.extend(place_name_t_listi)\n place_image_url_list.extend(place_image_url_listi)\n place_url_list.extend(place_url_listi)\n place_short_desc_list.extend(place_short_desc_listi)\n place_long_desc_list.extend(place_long_desc_listi)\n '''\n\n page_num +=1\n\n elif pages_count == 1:\n job_url_list, job_date_list, job_title_list, job_company_list, job_company_logo_list = get_scrape_url(\"1\", str(cate_num))\n\n return job_url_list, job_date_list, job_title_list, job_company_list, job_company_logo_list\n\n\n#-----------------------------------------------------------\n# Main code\n\n'''\n\"I feel history and culture\", \"Learn at the museum\", \"Relax in the hot spring\", \"Cobalt blue sea\", \"A distinctive park Superb view\", \"Scenic spots\", \"Outdoor sports\", \"Experience menu\", #activity \"Shopping\"\n'''\n#values = [\"history and culture\", \"museum\", \"hot spring\", \"sea\", \"park\", \"view\", \"sport\", \"activity\", \"shopping\"]\n#keys = [\"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\"]\n\n\n'''\nvalues = [\"Fresh seafood and tavern\", \"Excellent Yakiniku Yakitori\", \"Champon Ramen\", \"Sweets & Cafe\", \"Western food\", \"Island lunch\", \"Bar snack\"]\nkeys = [\"16\", \"17\", \"18\", \"19\", \"20\", \"21\", \"22\"]\nattraction_dict = dict(zip(keys, values))\n\n#############page_num = \"1\"\ncate_num = \"1\"\n\n#db_list = []\ncate_lists_dict = {}\nfor cate_num, value in sorted(attraction_dict.items()):\n \n print(\"%%%%%%% Working on Cate: \", value)\n print(\"%%%%%%% Working on Cate: \", cate_num)\n #^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\n # get_pages_count(cate_num)\n # get_scrape_url(page_num, cate_num)\n pages_count, results_count = get_pages_count(cate_num)\n #---------------------------------#\n\n place_name_t_list, place_image_url_list, place_url_list, place_short_desc_list, place_long_desc_list = get_scrape_cate(pages_count, cate_num)\n \n #zipofalllists1=zip(a,b,c,d,e)\n x_list = zip(place_name_t_list, place_image_url_list, place_url_list, place_short_desc_list, place_long_desc_list)\n cate_lists_dict[value] = x_list\n\n #^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\n print(\"*^^^^^^^^^^^length of place_name_t_list is: \", str(len(place_name_t_list)))\n\n for i in place_name_t_list:\n\n print(\"*************************************\")\n print(\"place name is: --> \", i)\n print(\"*************************************\")\n\n\n# write\nwith open(\"goto_food_db.json\", \"w\") as out_f:\n #json.dump(list(zipofalllists), out_f)\n json.dump(jsonpickle.encode(cate_lists_dict), out_f)\n'''\n\n# read\n##with open(\"out.json\", \"r\") as in_f:\n ##alllists = json.load(in_f)\n\n#for i, j, k, l, m, n, o, p, q in alllists:\n ##d[i] = [j, k]\n #print(\"i: \", i)\n ##print(\"j: \", j)\n ##print(\"k: \", c)\n\n\n\n\n\n#get_scrape_url(page_num, cate_num)\n\n#working June 2019\n###get_scrape_url(3, 301)\n#get_pages_count(301) #IT unix --> project manager cate_num = 301\n\n\n\n\ncate_num = \"301\" #dummy will not be used in case of forcing full url from outside\n# get_pages_count(cate_num)\n# get_scrape_url(page_num, cate_num)\npages_count, results_count = get_pages_count(cate_num)\n#---------------------------------#\n\njob_url_list, job_date_list, job_title_list, job_company_list, job_company_logo_list = get_scrape_cate(pages_count, cate_num)\n\n \n#zipofalllists1=zip(a,b,c,d,e)\nx_list = zip(job_url_list, job_date_list, job_title_list, job_company_list, job_company_logo_list)\n###cate_lists_dict[value] = x_list\n\n#^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\nprint(\"*^^^^^^^^^^^length of job_title_list is: \", str(len(job_title_list)))\n\nfor i in job_title_list:\n print(\"*************************************\")\n print(\"Job title is: --> \", i)\n print(\"*************************************\")\n\n\n# write\nwith open(\"jobs_it.json\", \"w\") as out_f:\n #json.dump(list(zipofalllists), out_f)\n ###json.dump(jsonpickle.encode(cate_lists_dict), out_f)\n json.dump(jsonpickle.encode(x_list), out_f)\n\n","sub_path":"daijob.com/scrap7.py","file_name":"scrap7.py","file_ext":"py","file_size_in_byte":17845,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"432181809","text":"#! python3\n# bulletPointAdder.py - Adds wikipedia bullet points to the start\n# of each line of text on the clipboard.\n\n\n#import pyperclip\nimport pyperclip\npyperclip.copy('''Lists of animals\nLists of aquarium life\nLists of biologists by author abbreviation\nLists of cultivars''')\norig_text = pyperclip.paste()\n\n# seperate lines and add stars\nnewline = orig_text.split('\\n')\nfor i in range(len(newline)): # loop through all index in the \"lines\" list\n newline[i] = '* ' + newline[i] # add star to each string in the list\ntext = '\\n'.join(newline)\nprint(text)\nprint(newline)\n","sub_path":"bulletpointAdder.py","file_name":"bulletpointAdder.py","file_ext":"py","file_size_in_byte":576,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"397030881","text":"import pandas\r\nimport re\r\nimport urllib.request, urllib.parse, urllib.error\r\nimport csv\r\nimport json\r\ndf = pandas.read_excel('maghale.xlsx')\r\nplot = df['Abbrev'].values\r\narea = list()\r\nn = 0\r\nfor name in plot:\r\n if n%2 !=0:\r\n area.append(name)\r\n n = n+1\r\n else:\r\n n = n+1\r\nfor line in area:\r\n h=\"\"\r\n codes = line.split(',')\r\n for member in codes:\r\n temp =member[1:len(member)-1]\r\n if temp[0] !=\"'\" :\r\n mov = temp\r\n else:\r\n mov = temp[1:]\r\n h= h + mov +\",\"\r\n print(h)\r\n","sub_path":"paper_prepocessing.py","file_name":"paper_prepocessing.py","file_ext":"py","file_size_in_byte":558,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"303152516","text":"from PIL import Image, ImageDraw\nimport random\nWIDTH = 512\nHEIGHT = 512\nCIRCLES_AMOUNT = 1000\nMAX_RADIUS = 12\nN_OF_GENERATION = int(input(\"Enter number of iterations(~20k recommended, it will take 10-20 minutes)\"))\n\ndef fitness_function(sketch, origin, lower_x, lower_y, upper_x, upper_y):\n if lower_x < 0:\n lower_x = 0\n if lower_y < 0:\n lower_y = 0\n if upper_x > WIDTH:\n upper_x = WIDTH\n if upper_y > HEIGHT:\n upper_y = HEIGHT\n square_difference = 0\n for i in range(lower_x, upper_x):\n for j in range(lower_y, upper_y):\n temp1 = sketch.getpixel((i, j))\n temp2 = origin.getpixel((i, j))\n a = 0\n if type(temp2) == type(a):\n temp2 = (temp2, temp2, temp2)\n\n square_difference += (temp1[0] - temp2[0]) ** 2 + (temp1[1] - temp2[1]) ** 2 + (temp1[2] - temp2[2]) ** 2\n return square_difference\n\n\ndef draw_circles(draw):\n for i in range(CIRCLES_AMOUNT):\n draw.ellipse((circles[i][0], circles[i][1], circles[i][0] +\n circles[i][2] * 2, circles[i][1] + circles[i][2] * 2), circles[i][3])\n\n\ndef annealing(mid, min, max, i):\n lower = mid - int(max * (N_OF_GENERATION - i + 1) * (1 / (2 * N_OF_GENERATION)))\n upper = mid + int(max * (N_OF_GENERATION - i + 1) * (1 / (2 * N_OF_GENERATION)))\n if lower < min:\n lower = min\n if upper > max:\n upper = max\n return lower, upper\n\n\norigin = Image.open(\"resources/sample16.tiff\")\n\nsketch = Image.new(\"RGB\", (WIDTH, HEIGHT), \"#000000\")\ndraw = ImageDraw.Draw(sketch)\n\ncircles = []\n# creating initial circles\nfor i in range(CIRCLES_AMOUNT):\n first_point_x = random.randint(-1 * MAX_RADIUS, WIDTH)\n first_point_y = random.randint(-1 * MAX_RADIUS, HEIGHT)\n radius = random.randint(8, MAX_RADIUS)\n\n circles.append([first_point_x, first_point_y, radius, \"#000000\"])\n\nfitness = fitness_function(sketch, origin, 1, 1, WIDTH, HEIGHT)\nfor i in range(N_OF_GENERATION):\n n = i % CIRCLES_AMOUNT\n\n prev1 = circles[n][0]\n prev2 = circles[n][1]\n# clearing the picture before drawing current circles\n draw.rectangle((1, 1, WIDTH, HEIGHT), \"#000000\")\n draw_circles(draw)\n\n circles[n][0] = random.randint(prev1 - MAX_RADIUS, prev1 + MAX_RADIUS)\n circles[n][1] = random.randint(prev2 - MAX_RADIUS, prev2 + MAX_RADIUS)\n\n old_fitness1 = fitness_function(sketch, origin, circles[n][0], circles[n][1],\n circles[n][0] + 2 * circles[n][2], circles[n][1] + 2 * circles[n][2])\n old_fitness2 = fitness_function(sketch, origin, prev1, prev2,\n prev1 + 2 * circles[n][2], prev2 + 2 * circles[n][2])\n\n draw.rectangle((1, 1, WIDTH, HEIGHT), \"#000000\")\n draw_circles(draw)\n\n new_fitness1 = fitness_function(sketch, origin, circles[n][0], circles[n][1],\n circles[n][0] + 2 * circles[n][2], circles[n][1] + 2 * circles[n][2])\n new_fitness2 = fitness_function(sketch, origin, prev1, prev2,\n prev1 + 2 * circles[n][2], prev2 + 2 * circles[n][2])\n\n if new_fitness1 + new_fitness2 - old_fitness1 - old_fitness2 > 0:\n circles[n][0] = prev1\n circles[n][1] = prev2\n else:\n fitness = fitness + new_fitness1 + new_fitness2 - old_fitness1 - old_fitness2\n\n# changing color trying to perform simulated annealing\n color = circles[n][3]\n values = tuple(int(color.lstrip('#')[i:i + 2], 16) for i in (0, 2, 4))\n lower_r, upper_r = annealing(values[0], 0, 255, i)\n lower_g, upper_g = annealing(values[1], 0, 255, i)\n lower_b, upper_b = annealing(values[2], 0, 255, i)\n lower_color = lower_r * 16 ** 4 + lower_g * 16 ** 2 + lower_b\n upper_color = upper_r * 16 ** 4 + upper_g * 16 ** 2 + upper_b\n\n draw.rectangle((1, 1, WIDTH, HEIGHT), \"#000000\")\n draw_circles(draw)\n old_fitness = fitness_function(sketch, origin, circles[n][0], circles[n][1],\n circles[n][0] + 2 * circles[n][2], circles[n][1] + 2 * circles[n][2])\n\n circles[n][3] = \"#%06X\" % random.randint(lower_color, upper_color)\n\n draw.rectangle((1, 1, WIDTH, HEIGHT), \"#000000\")\n draw_circles(draw)\n new_fitness = fitness_function(sketch, origin, circles[n][0], circles[n][1],\n circles[n][0] + 2 * circles[n][2], circles[n][1] + 2 * circles[n][2])\n if new_fitness - old_fitness > 0:\n circles[n][3] = color\n else:\n fitness = fitness + new_fitness - old_fitness\n\n if (i+1) % 100 == 0:\n sketch.save(\"output.png\")\n print(\"Mutation number:\" + str(i+1))\n","sub_path":"image_creator.py","file_name":"image_creator.py","file_ext":"py","file_size_in_byte":4633,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"618143097","text":"import math\n\ndef read_sudoku_from_file(filename):\n \"\"\" Parses a sudoku puzzle from a file. \"\"\"\n puzzle = []\n with open(filename, 'r') as fh:\n for line in fh:\n if line.strip():\n puzzle.append([int(i) for i in line.split()])\n\n return puzzle or None\n\n\ndef pprint_sudoku(puzzle):\n \"\"\" Pretty prints a sudoku puzzle. \"\"\"\n result = \"\"\n\n if puzzle:\n width = int(math.ceil(math.log10(len(puzzle)))) + 1\n\n for row in puzzle:\n for cell in row:\n result += \"{cell:<{width}}\".format(cell=cell, width=width)\n result += \"\\n\"\n\n print(result)\n","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":634,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"318283103","text":"from django.urls import path\nfrom nails_project.accounts import views\n\nurlpatterns = (\n path('sign-in/', views.SignInView.as_view(), name='sign in user'),\n path('sign-out/', views.SignOutView.as_view(), name='sign out user'),\n path('sign-up/', views.SignUpView.as_view(), name='sign up user'),\n path('profile//', views.ProfileUpdateView.as_view(), name='profile details'),\n path('delete//', views.ProfileDeleteView.as_view(), name='profile delete'),\n path('activate///', views.activate, name='activate'),\n)\n","sub_path":"nails_project/nails_project/accounts/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":556,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"357431823","text":"#!/usr/bin/env python\n# coding=utf-8\n# Stan 2012-04-08\n\nfrom __future__ import (division, absolute_import,\n print_function, unicode_literals)\n\nimport os\nimport logging\n\nimport xlrd\n\nfrom ...reg.result import *\nfrom .stuff.data_funcs import filter_match\nfrom .sheet import proceed_sheet\n\n\ndef proceed(filename, runtime, FILE):\n options = runtime.get('options', {})\n\n basename = os.path.basename(filename)\n root, ext = os.path.splitext(basename)\n ext = ext.lower()\n\n if ext in ['.xls', '.xlsx', '.xlsm', '.xlsb']:\n # Sheet\n if ext == '.xls':\n book = xlrd.open_workbook(filename, on_demand=True, formatting_info=True)\n else:\n reg_debug(FILE, \"Option 'formatting_info=True' is not implemented yet!\")\n book = xlrd.open_workbook(filename, on_demand=True)\n\n sheets = book.sheet_names()\n sheets_filter = options.get('sheets_filter')\n sheets_list = [i for i in sheets if filter_match(i, sheets_filter)]\n\n brief = [sheets, '---', sheets_list]\n reg_debug(FILE, brief)\n\n FILE.nsheets = book.nsheets\n\n for name in sheets_list:\n sh = book.sheet_by_name(name)\n i = sheets.index(name)\n proceed_sheet(sh, runtime, i, FILE)\n book.unload_sheet(name)\n","sub_path":"index/handlers/books0p3_reports/process.py","file_name":"process.py","file_ext":"py","file_size_in_byte":1316,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"16108093","text":"#_*_coding:utf-8_*_\nfrom correiosws import correios\nimport json\nnCdEmpresa=\"\"\nsDsSenha=\"\"\nnCdServico=\"04014\"\nnCepOrigem=\"37750000\"\t\nnCepDestino=\"37750000\"\t\nnVlPeso=\"0.5\"\nnCdFormato=\"1\"\nnVlComprimento=\"15\"\nnVlAltura=\"15\"\nnVlLargura=\"15\"\nnVlDiametro=\"15\"\nsCdMaoPropria=\"N\"\nnVlValorDeclarado=str(0)\nsCdAvisoRecebimento=\"N\"\ndata = correios.calc_preco_prazo_restricao(\n nCdEmpresa=nCdEmpresa,\n sDsSenha=sDsSenha,\n nCdServico=nCdServico,\n sCepOrigem=nCepOrigem,\n sCepDestino=nCepDestino,\n nVlPeso=nVlPeso,\n\tnCdFormato=nCdFormato,\n nVlComprimento=nVlComprimento,\n nVlAltura=nVlAltura,\n nVlLargura=nVlLargura,\n nVlDiametro=nVlDiametro,\n sCdMaoPropria=sCdMaoPropria,\n nVlValorDeclarado=nVlValorDeclarado,\n sCdAvisoRecebimento=sCdAvisoRecebimento,\n )\nprint(data)\n\n\n\n\n\n\n","sub_path":"test/calc_preco_prazo_restricao.py","file_name":"calc_preco_prazo_restricao.py","file_ext":"py","file_size_in_byte":854,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"511988254","text":"#!/usr/bin/env python3\n\"\"\"Server for multithreaded (asynchronous) chat application.\"\"\"\nfrom socket import AF_INET, socket, SOCK_STREAM\nfrom threading import Thread\n\n\ndef accept_incoming_connections():\n \"\"\"Sets up handling for incoming clients.\"\"\"\n while True:\n client, client_address = SERVER.accept()\n print(\"%s:%s has connected.\" % client_address)\n addresses[client] = client_address\n Thread(target=handle_client, args=(client,)).start()\n\n\ndef handle_client(client): # Takes client socket as argument.\n \"\"\"Handles a single client connection.\"\"\"\n\n clients[client] = \"123\"\n\n while True:\n msg = client.recv(BUFSIZ)\n broadcast(msg, name+\": \")\n\n\ndef broadcast(msg, prefix=\"\"): # prefix is for name identification.\n\n for sock in clients:\n #sock.send(bytes(prefix, \"utf8\")+msg)\n sock.send(msg)\n\n \nclients = {}\naddresses = {}\n\nHOST = \"127.0.0.1\"\nPORT = 33000\nBUFSIZ = 1024\nADDR = (HOST, PORT)\n\nSERVER = socket(AF_INET, SOCK_STREAM)\nSERVER.bind(ADDR)\n\nif __name__ == \"__main__\":\n SERVER.listen(5)\n print(\"Waiting for connection...\")\n ACCEPT_THREAD = Thread(target=accept_incoming_connections)\n ACCEPT_THREAD.start()\n ACCEPT_THREAD.join()\n SERVER.close()\n","sub_path":"submission/first brief/server/pickleSerEnc.py","file_name":"pickleSerEnc.py","file_ext":"py","file_size_in_byte":1248,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"244271260","text":"import pyodbc\n\nconnection = pyodbc.connect('DRIVER={ODBC Driver 17 for SQL Server};'\n 'SERVER=sbertech.database.windows.net;'\n 'DATABASE=Big Data Course DB;'\n 'UID={Admin1996};'\n 'PWD={Azure1996}')\n\ncursor = connection.cursor()\n\ncursor.execute(\"Select * from SalesLT.Customer\")\n\nrows = cursor.fetchall()\n\nfor row in rows:\n print (row)\n\n","sub_path":"Lab12(RollUp, Cube, window func)/lab12.py","file_name":"lab12.py","file_ext":"py","file_size_in_byte":448,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"652688047","text":"#!encoding=utf-8\nimport pygame\nimport os\nfrom PIL import Image\nimport StringIO\n\ndef getWordsList():\n f = open('input/3500.txt')\n line = f.read().strip()\n wordslist = line.split(' ')\n f.close()\n return wordslist\n\ndef pasteWord(word, output):\n '''输入一个文字,输出一张包含该文字的图片'''\n\n pygame.init()\n font = pygame.font.Font(os.path.join(\"fonts\", \"simfang.ttf\"), 64);\n text = word.decode('utf-8')\n imgName = \"output/f64/\" + output + \".png\"\n paste(text, font, imgName)\n\ndef paste(text, font, imgName, area = (0, 0)):\n '''根据字体,将一个文字黏贴到图片上,并保存'''\n im = Image.new(\"RGB\", (64, 128), (255, 255, 255))\n rtext = font.render(text, True, (0, 0, 0), (255, 255, 255))\n sio = StringIO.StringIO()\n pygame.image.save(rtext, sio)\n sio.seek(0)\n line = Image.open(sio)\n im.paste(line, area)\n# im.show()\n im.save(imgName)\n print(text + ' ' + 'ok...')\n\nwordsList=getWordsList()\nfor i in xrange(len(wordsList)):\n pasteWord(wordsList[i], str(i))\n","sub_path":"old-1.py","file_name":"old-1.py","file_ext":"py","file_size_in_byte":1055,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"94654175","text":"# This example script demonstrates how use Python to allow users to send SDK to Tello commands with their keyboard\n# This script is part of our course on Tello drone programming\n# https://learn.droneblocks.io/p/tello-drone-programming-with-python/\n\n# Import the necessary modules\nimport socket\nimport threading\nimport time\nimport sys\nfrom tkinter import Tk, Button, Label, Scale\n\n# IP and port of Tello\ntello_address = ('192.168.10.1', 8889)\n\n# IP and port of local computer\nlocal_address = ('', 9000)\n\n# Create a UDP connection that we'll send the command to\nsock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n\n# Bind to the local address and port\nsock.bind(local_address)\n\n# Button Commands\ndefault_speed = 30\ndefault_yaw = 30\n\n\ndef command_button_click():\n send(\"command\")\n\n\ndef takeoff_button_click():\n send(\"takeoff\")\n\n\ndef land_button_click():\n send(\"land\")\n\n\ndef battery_button_click():\n send(\"battery?\")\n\n\ndef end_button_click():\n send(\"land\")\n sys.exit(0)\n\n\ndef move_forward(event):\n send(\"rc 0 \" + str(speed_slider.get()) + \" 0 0\")\n\n\ndef move_left(event):\n send(\"rc -\" + str(speed_slider.get()) + \" 0 0 0\")\n\n\ndef move_right(event):\n send(\"rc \" + str(speed_slider.get()) + \" 0 0 0\")\n\n\ndef move_back(event):\n send(\"rc 0 -\" + str(speed_slider.get()) + \" 0 0\")\n\n\ndef stop(event):\n send(\"rc 0 0 0 0\")\n\n\ndef move_up(event):\n send(\"up \" + str(speed_slider.get()))\n\n\ndef move_down(event):\n send(\"down \" + str(speed_slider.get()))\n\n\ndef rotate_cw(event):\n send(\"cw \" + str(rotation_slider.get()))\n if rotation_slider.get() > 180:\n rotation_slider.set(default_yaw)\n\n\ndef rotate_ccw(event):\n send(\"ccw \" + str(rotation_slider.get()))\n if rotation_slider.get() > 180:\n rotation_slider.set(default_yaw)\n\n\ndef speed_increase(event):\n speed = speed_slider.get()\n if speed > 90:\n speed_slider.set(100)\n else:\n speed = speed + 10\n speed_slider.set(speed)\n\n\ndef speed_decrease(event):\n speed = speed_slider.get()\n if speed < 10:\n speed_slider.set(0)\n else:\n speed = speed - 10\n speed_slider.set(speed)\n\n\n# Send the message to Tello and allow for a delay in seconds\ndef send(message):\n # Try to send the message otherwise print the exception\n try:\n sock.sendto(message.encode(), tello_address)\n print(\"Sending message: \" + message)\n except Exception as e:\n print(\"Error sending: \" + str(e))\n\n# Receive the message from Tello\n\n\ndef receive():\n # Continuously loop and listen for incoming messages\n while True:\n # Try to receive the message otherwise print the exception\n try:\n response, ip_address = sock.recvfrom(128)\n print(\"Received message: \" + response.decode(encoding='utf-8'))\n# incoming_label.config(text = \"\\n\\nReceived message: \" + response.decode(encoding='utf-8'))\n except Exception as e:\n # If there's an error close the socket and break out of the loop\n sock.close()\n print(\"Error receiving: \" + str(e))\n break\n\n\ndef battery_percentage():\n send(\"battery?\")\n while True:\n try:\n response, ip_address = sock.recvfrom(128)\n battery_label.config(text=\"Battery: \" +\n response.decode(encoding='utf-8') + \"%\")\n except Exception as e:\n sock.close()\n break\n\n\n# Create and start a listening thread that runs in the background\n# This utilizes our receive function and will continuously monitor for incoming messages\nreceiveThread = threading.Thread(target=receive)\nreceiveThread.daemon = True\nreceiveThread.start()\n\n# Loop infinitely waiting for commands or until the user types quit or ctrl-c\nwhile True:\n flight_application = Tk()\n flight_application.title(\"Ocufly\")\n buttonWidth = 10\n\n command_button = Button(flight_application,\n text=\"Connect\",\n command=command_button_click,\n width=buttonWidth)\n command_button.grid(row=0, column=0)\n\n takeoff_button = Button(flight_application,\n text=\"Takeoff\",\n command=takeoff_button_click,\n width=buttonWidth)\n takeoff_button.grid(row=1, column=0)\n\n land_button = Button(flight_application,\n text=\"Land\",\n command=land_button_click,\n width=buttonWidth)\n land_button.grid(row=2, column=0)\n\n battery_button = Button(flight_application,\n text=\"Battery Level\",\n command=battery_button_click,\n width=buttonWidth)\n battery_button.grid(row=3, column=0)\n\n end_button = Button(flight_application,\n text=\"End\",\n command=end_button_click,\n width=buttonWidth)\n end_button.grid(row=4, column=0, )\n\n incoming_label = Label(flight_application, text=\"\\n\\nClick Connect\")\n incoming_label.grid(row=5, column=0)\n\n speed_slider_label = Label(flight_application, text=\"\\n\\nSpeed\")\n speed_slider_label.grid(row=6, column=0)\n speed_slider = Scale(flight_application,\n orient=\"horizontal\",\n from_=0, to=100)\n speed_slider.set(default_speed)\n speed_slider.grid(row=7, column=0)\n\n rotation_slider_label = Label(\n flight_application, text=\"\\n\\nDegrees of rotation\")\n rotation_slider_label.grid(row=8, column=0)\n rotation_slider = Scale(flight_application,\n orient=\"horizontal\",\n from_=1, to=360,)\n rotation_slider.set(default_yaw)\n rotation_slider.grid(row=9, column=0)\n\n controls_label = Label(\n flight_application, text=\"\\n\\nWASD controls\\nArrow keys altitude/yaw\\n=/- change speed\")\n controls_label.grid(row=10, column=0)\n\n battery_label = Label(flight_application, text=\"N/A\")\n battery_label.grid(row=11, column=0)\n\n flight_application.bind('w', move_forward)\n flight_application.bind('a', move_left)\n flight_application.bind('s', move_back)\n flight_application.bind('d', move_right)\n flight_application.bind('', move_up)\n flight_application.bind('', move_down)\n flight_application.bind('', rotate_ccw)\n flight_application.bind('', rotate_cw)\n flight_application.bind('', stop)\n flight_application.bind('=', speed_increase)\n flight_application.bind('-', speed_decrease)\n\n flight_application.mainloop()\n\n try:\n # Read keybord input from the user\n if(sys.version_info > (3, 0)):\n # Python 3 compatibility\n message = input('')\n else:\n # Python 2 compatibility\n message = raw_input('')\n\n # If user types quit then lets exit and close the socket\n if 'quit' in message:\n print(\"Program exited sucessfully\")\n sock.close()\n break\n\n # Send the command to Tello\n send(message)\n\n # Handle ctrl-c case to quit and close the socket\n except KeyboardInterrupt as e:\n sock.close()\n break\n","sub_path":"flight_software.py","file_name":"flight_software.py","file_ext":"py","file_size_in_byte":7246,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"454766239","text":"import urllib.request as rq\n\nfrom posixpath import basename as bn\nfrom urllib.parse import urlparse as pr\n\nwith open(\"file.txt\", \"r\") as ins:\n array = []\n for line in ins:\n array.append(line)\n\nfor x in array:\n print (x) # Just for debugging, to see if an URL pauses the process\n url = pr(x)\n print (bn(url.path)) # Just for debugging, to see the filename for the URL above\n rq.urlretrieve(x, bn(url.path))\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":423,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"27536539","text":"#!/usr/bin/env python3.3\n# Cards.py\n# Simon Swanson and Kyle Engel\n\n\nsuits = ['Clubs','Diamonds','Hearts','Spades']\n\nrankNames = {0: 'Unknown',\n 2: 'Two',\n 3: 'Three',\n 4: 'Four',\n 5: 'Five',\n 6: 'Six',\n 7: 'Seven',\n 8: 'Eight',\n 9: 'Nine',\n 10: 'Ten',\n 11: 'Jack',\n 12: 'Queen',\n 13: 'King',\n 14: 'Ace'}\n\n\nclass Card:\n\n def __init__(self, rank = 0, suit = 'Unknown'):\n self.rank = rank\n self.suit = suit\n\n def __str__(self):\n name = rankNames.get(self.rank, str(self.rank))\n return \"{} of {}\".format(name, self.suit)\n\n def __eq__(self, other):\n return self.suit == other.suit and self.rank is other.rank\n\n def __lt__(self, other):\n return self.suit == other.suit and self.rank < other.rank\n\n def __gt__(self, other):\n return self.suit != other.suit or (self.suit == other.suit and self.rank > other.rank)\n\n\nclass Deck:\n \n def __init__(self, discard = False):\n self.cards = []\n if not discard:\n for suit in suits:\n for rank in range(2,15):\n self.cards.append(Card(suit, rank))\n\n def __str__(self):\n cards = []\n for card in self.cards:\n cards.append(str(card))\n string = \", \".join(cards)\n return string\n\n def draw(self, cardStr):\n card = cardFromStr(cardStr)\n if not self.cards:\n print(\"Invalid. The deck is empty.\")\n elif card in self.cards:\n self.cards.remove(card)\n else:\n print(\"Invalid. {} does not exist in the deck.\".format(str(card)))\n\n\nclass Hand:\n \n def __init__(self, name = \"player\"):\n self.cards = []\n self.player = name\n self.voids = []\n\n def __str__(self):\n cards = []\n for card in self.cards:\n cards.append(str(card))\n if not cards:\n return self.player\n string = \", \".join(cards)\n return \"\\n\".join([self.player, string])\n\n def add(self, cardStr):\n card = cardFromStr(cardStr)\n if card in self.cards:\n print(\"Invalid. {} is already in {}'s hand.\".format(str(card), self.player))\n elif card != Card():\n self.cards.append(card)\n self.getVoids()\n else:\n print(\"Invalid. Input card is not a real card.\")\n\n def play(self, cardStr):\n card = cardFromStr(cardStr)\n if not self.cards:\n print(\"Invalid. The hand is empty.\")\n elif card in self.cards:\n self.cards.remove(card)\n self.getVoids()\n else:\n print(\"Invalid. {} does not exist in {}'s hand.\".format(str(card), self.player))\n\n def getVoids(self):\n self.voids = ['Clubs', 'Diamonds', 'Hearts', 'Spades']\n for card in self.cards:\n if card.suit in self.voids:\n self.voids.remove(card.suit)\n\n\ndef cardFromStr(cardStr):\n xs = cardStr.split()\n if xs[1] in suits:\n for (rank, name) in rankNames.items():\n if xs[0] == name:\n return Card(rank, xs[1])\n return Card()\n","sub_path":"Hearts/Cards.py","file_name":"Cards.py","file_ext":"py","file_size_in_byte":3124,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"26943408","text":"# Description:\n# There are a total of n courses you have to take, labeled from 0 to n-1.\n# Some courses may have prerequisites, for example to take course 0 you have to first take\n# course 1, which is expressed as a pair: [0,1]. Given the total number of courses and a\n# list of prerequisite pairs, is it possible for you to finish all courses?\n\n# Example 1:\n# Input: 2, [[1,0]] \n# Output: true\n# Explanation: There are a total of 2 courses to take. To take course 1 you should have\n# finished course 0. So it is possible.\n\n# Example 2:\n# Input: 2, [[1,0],[0,1]]\n# Output: false\n# Explanation: There are a total of 2 courses to take. \n# To take course 1 you should have finished course 0, and to take course 0 you\n# should also have finished course 1. So it is impossible.\n\n# Note:\n# The input prerequisites is a graph represented by a list of edges, not adjacency matrices.\n# Read more about how a graph is represented. You may assume that there are no duplicate\n# edges in the input prerequisites.\n\nfrom typing import List\n\nclass Solution:\n def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool:\n # corner case: 0 courses\n if(numCourses == 0):\n return False\n\n # takeClass[i] indicates if we can take class i; prereqs[i] contains the pre-\n # requisite courses for class i\n takeClass = [True]*numCourses\n prereqs = []\n numPrereqs = 0\n for i in range(numCourses):\n prereqs.append([])\n\n # iterate through prerequisites\n for preReqPair in prerequisites:\n if(len(preReqPair) <= 1):\n continue\n else:\n course = preReqPair[0]\n needed = preReqPair[1]\n if(course >= numCourses):\n continue\n elif(needed >= numCourses):\n return False\n else:\n prereqs[course].append(needed)\n takeClass[course] = False\n numPrereqs += 1\n\n # build out graph to determine if we can take class num\n def reqIterator(num, takeClass, count):\n if(count > numCourses):\n return False\n if(takeClass[num] == True):\n return True\n else:\n for prereq in prereqs[num]:\n if(takeClass[prereq] == True):\n continue\n else:\n check = reqIterator(prereq, takeClass, count+1)\n if(check):\n continue\n else:\n return False\n takeClass[prereq] = True\n return True\n\n # call on reqIterator for any classes that have prereqs\n for i in range(numCourses):\n if(takeClass[i] == False):\n check = reqIterator(i,takeClass,0)\n if(not check):\n return False\n\n return True\n\nif __name__ == '__main__':\n soln = Solution()\n test1 = soln.canFinish(2,[[1,0]]) #true\n test2 = soln.canFinish(2,[[0,1],[1,0]]) #false\n test3 = soln.canFinish(3,[[2,1],[1,0]]) #true\n test4 = soln.canFinish(3,[[2,1],[1,0],[0,2]]) #false\n test5 = soln.canFinish(1,[[1,0],[2,5]]) #true\n test6 = soln.canFinish(1,[[0,5]]) #false\n test7 = soln.canFinish(4,[[2,0],[1,0],[3,1],[3,2],[1,3]]) #false\n\n assert test1 == True\n assert test2 == False\n assert test3 == True\n assert test4 == False\n assert test5 == True\n assert test6 == False\n\n\n\n\n","sub_path":"Graphs/CourseSchedule.py","file_name":"CourseSchedule.py","file_ext":"py","file_size_in_byte":3583,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"549838459","text":"# Akshith Gara\n# 2048 AI\n# CS5400\n\nimport sys\nfrom datetime import datetime\nfrom astargs import Asgs\n\nfrom scraper import *\n\nif __name__ == '__main__':\n\n if len(sys.argv) > 1:\n inputFile = sys.argv[1]\n else:\n inputFile = input(\"Please enter the filename: \")\n\n firstState, goal, spawnList, gridSize = inputGrabber(inputFile)\n # Timer to measure the execution time.\n startTime = datetime.now()\n sol = Asgs(firstState, goal, spawnList, gridSize)\n endTime = datetime.now()\n execTime = endTime - startTime\n print(execTime.microseconds)\n # Prints the solution only if there is one.\n if sol:\n print(len(sol[0]))\n print(sol[0])\n for line in sol[1].STATE:\n print(' '.join([str(x) for x in line]))\n","sub_path":"game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":767,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"298780123","text":"# A Program to evaluate a 100 point quizzes that are graded on a scale\n# 90-100-A , 80-89-B, 70-79-C, 60-69-D, <60-F\n\n\nclass RangeDict(dict):\n def __getitem__(self, item):\n if not isinstance(item, range):\n for key in self:\n if item in key:\n return self[key]\n raise KeyError(item)\n else:\n return super().__getitem__(item) \n\nquiz_score = int(input(\"Please enter the result: \"))\n \ndict_values = RangeDict({range(90,101): 'A', range(80,90): 'B',range(70,80): 'C', range(60,70): 'D', range(0,61): 'F'})\n\nprint(\"The quiz result grade score is:\",dict_values[quiz_score])\n\n","sub_path":"eval_quizz_v2.py","file_name":"eval_quizz_v2.py","file_ext":"py","file_size_in_byte":652,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"549858879","text":"'''The relevant views for the Individual Score and Total Score'''\n\n#import generic api views\nfrom rest_framework import generics\n#the approriate serialziers\nfrom scores.api.serializers import IndividualScoreSerializer, TotalScoreSerializer\n#the permission\nfrom rest_framework.permissions import IsAuthenticated\n#the goals model\nfrom goals.models import Goal\n#individual scores model\nfrom scores.models import IndividualScore, TotalScore\n#for the custom exception\nfrom rest_framework.exceptions import APIException\n#for getting individual score objects created today, need current date\nfrom datetime import datetime\n\n#the API View\nfrom rest_framework.views import APIView\n#for the response\nfrom rest_framework.response import Response\nfrom rest_framework import status\n\nfrom django.http import Http404\n\n\nclass IndividualScoreUpdateView(APIView):\n \"\"\"View for updates of Individual scores. Endpoint accepts a list defining scores to update\"\"\"\n\n permission_classes = [IsAuthenticated]\n\n def get_object(self, pk, user):\n try:\n obj = IndividualScore.objects.get(pk=pk)\n #a list of scores for this user\n goal_list = Goal.objects.filter(user = user)\n score_list = list(IndividualScore.objects.filter(goal__in=goal_list))\n #check that this score belongs to this user\n if obj not in score_list:\n raise IndividualScore.DoesNotExist\n return IndividualScore.objects.get(pk=pk)\n except IndividualScore.DoesNotExist:\n return None\n\n def patch(self, request, **kwargs):\n instances = request.data\n #boolean to flag bad request\n flag = False\n #iterate over instance and add individually\n for update in instances:\n score_id = update['id']\n ind_score_obj = self.get_object(score_id, request.user)\n if ind_score_obj == None:\n flag = True\n break\n data = {'individual_score':update['individual_score']}\n serializer = IndividualScoreSerializer(ind_score_obj, data=data, partial = True)\n if serializer.is_valid():\n serializer.save()\n else:\n flag = True\n break\n if flag == False:\n return Response(status=status.HTTP_200_OK)\n return Response('wrong parameters', status=status.HTTP_400_BAD_REQUEST)\n \n#A list view of the scores to see all scores accumulated by a user. Accepts a query paramter for the month filter. In the form of a string \"Month YYYY\"\nclass TotalScoreListView(generics.ListAPIView):\n serializer_class = TotalScoreSerializer\n permission_classes = [IsAuthenticated]\n #the query set is all scores corosponding to goals set by the user\n def get_queryset(self):\n #the user\n user = self.request.user\n #the users goals\n goals = list(Goal.objects.filter(user = user))\n #a list of all individual scores\n scores_ = IndividualScore.objects.filter(goal__in = goals)\n #use individual scores to get total scores\n total_scores = TotalScore.objects.filter(id__in=scores_.values('total_score_id'))\n #clean the month param and filter if there\n month_arg = self.request.query_params.get('month', None)\n if month_arg is not None:\n month_filters = self.clean_month(month_arg)\n month = month_filters[0]\n year = month_filters[1]\n #filter by user and month\n total_scores = TotalScore.objects.filter(id__in=scores_.values('total_score_id'), date__year = year, date__month = month)\n else:\n #filter by just user\n total_scores = TotalScore.objects.filter(id__in=scores_.values('total_score_id'))\n \n return total_scores\n \n #a method that takes the month in the form \"Month YYYY and returns a list, month then year\"\n def clean_month(self, month):\n month_filters = month.split(' ')\n month_filters[1] = int(month_filters[1])\n month_str = month_filters[0]\n if month_str == 'January':\n month_filters[0] = 1\n elif month_str == 'February':\n month_filters[0] = 2\n elif month_str == 'March':\n month_filters[0] = 3\n elif month_str == 'April':\n month_filters[0] = 4\n elif month_str == 'May':\n month_filters[0] = 5\n elif month_str == 'June':\n month_filters[0] = 6\n elif month_str == 'July':\n month_filters[0] = 7\n elif month_str == 'August':\n month_filters[0] = 8\n elif month_str == 'September':\n month_filters[0] = 9\n elif month_str == 'October':\n month_filters[0] = 10\n elif month_str == 'November':\n month_filters[0] = 11\n elif month_str == 'December':\n month_filters[0] = 12\n \n\n return month_filters\n\n#the view for retriving all user goals. Accepts an optional paramter to allow for viewing goals for a particular total score defined by the passed in primary key of the total score object. Used for test\nclass IndividualScoreListView(generics.ListAPIView):\n serializer_class = IndividualScoreSerializer\n permission_classes = [IsAuthenticated]\n #the query set is all scores corosponding to goals set by the user\n def get_queryset(self):\n #filter for total score id if passed in\n total_score_id = self.request.query_params.get('id', None)\n if total_score_id is not None:\n score_list = IndividualScore.objects.filter(total_score = total_score_id)\n else:\n #filter by just user\n user = self.request.user\n goals = list(Goal.objects.filter(user = user))\n score_list = IndividualScore.objects.filter(goal__in = goals)\n #only select scores for this user's goals\n return score_list","sub_path":"backend/scores/api/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5924,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"173876573","text":"import os\nfrom multiprocessing import current_process\nfrom threading import current_thread\nfrom typing import List\nimport requests\nfrom aiohttp import ClientSession\n\n\ndef make_request(num: int):\n # io-bound\n\n pid: int = os.getpid()\n thread_name: str = current_thread().name\n process_name: str = current_process().name\n print(f\"{pid} - {process_name} - {thread_name}\")\n\n requests.get(\"https://httpbin.org/ip\")\n\n\nasync def make_request_async(num: int, client: ClientSession):\n # io-bound\n\n pid: int = os.getpid()\n thread_name: str = current_thread().name\n process_name: str = current_process().name\n print(f\"{pid} - {process_name} - {thread_name}\")\n\n await client.get(\"https://httpbin.org/ip\")\n\n\ndef get_prime_numbers(num) -> List:\n # cpu-bound\n\n pid: int = os.getpid()\n thread_name: str = current_thread().name\n process_name: str = current_process().name\n print(f\"{pid} - {process_name} - {thread_name}\")\n\n numbers: List = []\n\n prime: List = [True for i in range(num + 1)]\n p = 2\n\n while p * p <= num:\n if prime[p]:\n for i in range(p * 2, num + 1, p):\n prime[i] = False\n p += 1\n\n prime[0] = False\n prime[1] = False\n\n for p in range(num + 1):\n if prime[p]:\n numbers.append(p)\n\n return numbers","sub_path":"tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":1323,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"385739616","text":"import turtle\n\ndef draw_square(some_turtle):\n \n for i in range(4):\n\n some_turtle.forward(100)\n some_turtle.right(90)\n \ndef draw_art():\n\n window = turtle.Screen()\n window.bgcolor(\"blue\")\n \n giva = turtle.Turtle()\n giva.color(\"white\")\n giva.speed(0)\n\n for i in range(360):\n \n draw_square(giva)\n giva.seth(i)\n \n\n turtle.exitonclick()\n\ndraw_art()\n\n","sub_path":"square_circle.py","file_name":"square_circle.py","file_ext":"py","file_size_in_byte":417,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"240784882","text":"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom matplotlib import font_manager, rc\n\nplt.rcParams['axes.unicode_minus'] = False\n\nif platform.system() == 'Darwin':\n\trc('font', family='AppleGothic')\nelif platform.system() == 'Windows':\n\tpath = \"C:/Windows/Fonts/malgun.ttf\"\n\tfont_name = font_manager.FontProperties(fname=path).get_name()\n\trc('font',family=font_name)\nelse:\n\tprint(\"Unknon system...\")\n\npeopledf = pd.read_excel('population_in_seoul.xls')\npeopledf.drop(0,inplace=True)\nprint(peopledf)\n\ncolumns = ['남자', '여자', '고령자']\nfor x in columns:\n print(peopledf.loc[peopledf[x].isnull()])\n print('='*50)\n\npeopledf.dropna(how = 'any', inplace = True)\nprint(peopledf)\ndel peopledf['고령자']\nprint(peopledf)\npeopledf.reset_index(drop=True,inplace=True) # index 재 정리\nprint(peopledf)\n\npeopledf.plot(kind='bar')\nplt.show()\n","sub_path":"data_analysis/dataframe_seoul_exam.py","file_name":"dataframe_seoul_exam.py","file_ext":"py","file_size_in_byte":876,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"604875382","text":"import os, sys, platform\nfrom sikuli import *\n\nAppPath_PRE = \"/Applications/Adobe Premiere Elements 2019/Support Files/Adobe Premiere Elements.app/Contents/MacOS/Adobe Premiere Elements\"\nAAPath = \"/Applications/Adobe Elements 2019 Organizer.app/Contents/Elements Auto Creations 2019.app/Contents/MacOS/Elements Auto Creations 2019\"\nuserdir = os.path.expanduser('~')\n\nRootFolder = userdir + \"/Desktop/FD_Automation\"\nOutputFolder = RootFolder + \"/Output/\"\nSikuli_Path = userdir + \"/Downloads\"\nFD_Test_Execution_Data = RootFolder + \"/TestData/FD_Test_Execution_Data.xls\"\nScreenshotsFolder = OutputFolder + \"Screenshots\"\nBatFilesFolder = RootFolder + \"/BatFiles/\"\nCollectionFolder = RootFolder + \"/Collection/\"\nVideo_CALogs = userdir + \"/Documents/Adobe/Elements Organizer/17.0/CALog.log\"\nImage_FaceInfoLogs = userdir + \"/Documents/Adobe/Elements Organizer/17.0/FaceInfo.log\"\nVideo_timerLogs = userdir + \"/Documents/Adobe/Premiere Elements/17.0/timerlog.log\"\n# Tech = \"Cognitec\"\nTech = \"Mona\"\n# M = \"Image\"\nM = \"Video\"","sub_path":"TestScripts/Constants.py","file_name":"Constants.py","file_ext":"py","file_size_in_byte":1014,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"217427789","text":"\"\"\"This module provides keywords for manipulating files and directories.\"\"\"\n\nimport logging, os\nfrom xdaf.xdafext import *\n\n__all__ = ['CheckFile', 'DeleteFile', 'ReadLine']\n_logger = logging.getLogger(__name__)\n\nclass CheckFile(XDAFRetryKeyword):\n r\"\"\"Check the existence or attributes of a file. This keyword can also be\n applied on directories.\n\n Set variables:\n\n - C{mtime} - actual modification time of the file\n\n Examples::\n\n \n \n \n \n \n \n \n\n \n \n \n \n \n\n \"\"\"\n\n def __init__(self, filename, comparison='eq', exists='yes', mtime=None, interval='10s', timeout=None):\n r\"\"\"Initialize this keyword.\n\n @param filename: the full path of the file to be checked. For example,\n C{\"C:\\Windows\\WindowsUpdate.log\"}.\n @type filename: string\n @param comparison: (optional) the operator used in comparison between\n actual data and expected one. Acceptable values are C{\"eq\"},\n C{\"ne\"}, C{\"lt\"}, C{\"gt\"}, C{\"le\"} and C{\"ge\"}. Defaults to C{\"eq\"}.\n @type comparison: string\n @param exists: (optional) check if the file exists or doesn't exist.\n Defaults to C{\"yes\"}.\n @type exists: boolean literal\n @param mtime: (optional) check if the actual modification matches expectation.\n The actual and expected modification times are compared with\n operator specified by parameter 'C{comparison}'.\n @type mtime: integer\n @param interval: (optional) check interval. Formatted string, the format is\n 'C{